more set_state() tweaks to aid with plugin state loading
[ardour.git] / libs / ardour / plugin_insert.cc
1 /*
2     Copyright (C) 2000 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #ifdef WAF_BUILD
21 #include "libardour-config.h"
22 #endif
23
24 #include <string>
25
26 #include <sigc++/bind.h>
27
28 #include "pbd/failed_constructor.h"
29 #include "pbd/xml++.h"
30
31 #include "ardour/audio_buffer.h"
32 #include "ardour/automation_list.h"
33 #include "ardour/buffer_set.h"
34 #include "ardour/event_type_map.h"
35 #include "ardour/ladspa_plugin.h"
36 #include "ardour/plugin.h"
37 #include "ardour/plugin_insert.h"
38 #include "ardour/port.h"
39 #include "ardour/route.h"
40
41 #ifdef HAVE_SLV2
42 #include "ardour/lv2_plugin.h"
43 #endif
44
45 #ifdef VST_SUPPORT
46 #include "ardour/vst_plugin.h"
47 #endif
48
49 #ifdef HAVE_AUDIOUNITS
50 #include "ardour/audio_unit.h"
51 #endif
52
53 #include "ardour/audioengine.h"
54 #include "ardour/session.h"
55 #include "ardour/types.h"
56
57 #include "i18n.h"
58
59 using namespace std;
60 using namespace ARDOUR;
61 using namespace PBD;
62
63 const string PluginInsert::port_automation_node_name = "PortAutomation";
64
65 PluginInsert::PluginInsert (Session& s, boost::shared_ptr<Plugin> plug)
66         : Processor (s, plug->name())
67         , _signal_analysis_collected_nframes(0)
68         , _signal_analysis_collect_nframes_max(0)
69 {
70         /* the first is the master */
71
72         _plugins.push_back (plug);
73         set_automatable ();
74
75         {
76                 Glib::Mutex::Lock em (_session.engine().process_lock());
77                 IO::PortCountChanged (max(input_streams(), output_streams()));
78         }
79
80         ProcessorCreated (this); /* EMIT SIGNAL */
81 }
82
83 PluginInsert::PluginInsert (Session& s, const XMLNode& node)
84         : Processor (s, "unnamed plugin insert"),
85           _signal_analysis_collected_nframes(0),
86           _signal_analysis_collect_nframes_max(0)
87 {
88         if (set_state (node, Stateful::loading_state_version)) {
89                 throw failed_constructor();
90         }
91
92         {
93                 Glib::Mutex::Lock em (_session.engine().process_lock());
94                 IO::PortCountChanged (max(input_streams(), output_streams()));
95         }
96 }
97
98 bool
99 PluginInsert::set_count (uint32_t num)
100 {
101         bool require_state = !_plugins.empty();
102
103         /* this is a bad idea.... we shouldn't do this while active.
104            only a route holding their redirect_lock should be calling this
105         */
106
107         if (num == 0) {
108                 return false;
109         } else if (num > _plugins.size()) {
110                 uint32_t diff = num - _plugins.size();
111
112                 for (uint32_t n = 0; n < diff; ++n) {
113                         _plugins.push_back (plugin_factory (_plugins[0]));
114
115                         if (require_state) {
116                                 /* XXX do something */
117                         }
118                 }
119
120         } else if (num < _plugins.size()) {
121                 uint32_t diff = _plugins.size() - num;
122                 for (uint32_t n= 0; n < diff; ++n) {
123                         _plugins.pop_back();
124                 }
125         }
126
127         return true;
128 }
129
130 PluginInsert::~PluginInsert ()
131 {
132         GoingAway (); /* EMIT SIGNAL */
133 }
134
135 void
136 PluginInsert::auto_state_changed (Evoral::Parameter which)
137 {
138         if (which.type() != PluginAutomation)
139                 return;
140
141         boost::shared_ptr<AutomationControl> c
142                         = boost::dynamic_pointer_cast<AutomationControl>(data().control (which));
143
144         if (c && ((AutomationList*)c->list().get())->automation_state() != Off) {
145                 _plugins[0]->set_parameter (which.id(), c->list()->eval (_session.transport_frame()));
146         }
147 }
148
149 ChanCount
150 PluginInsert::output_streams() const
151 {
152         ChanCount out = _plugins.front()->get_info()->n_outputs;
153
154         if (out == ChanCount::INFINITE) {
155                 return _plugins.front()->output_streams ();
156         } else {
157                 out.set_audio (out.n_audio() * _plugins.size());
158                 out.set_midi (out.n_midi() * _plugins.size());
159                 return out;
160         }
161 }
162
163 ChanCount
164 PluginInsert::input_streams() const
165 {
166         ChanCount in = _plugins[0]->get_info()->n_inputs;
167
168         if (in == ChanCount::INFINITE) {
169                 return _plugins[0]->input_streams ();
170         } else {
171                 in.set_audio (in.n_audio() * _plugins.size());
172                 in.set_midi (in.n_midi() * _plugins.size());
173                 return in;
174         }
175 }
176
177 ChanCount
178 PluginInsert::natural_output_streams() const
179 {
180         return _plugins[0]->get_info()->n_outputs;
181 }
182
183 ChanCount
184 PluginInsert::natural_input_streams() const
185 {
186         return _plugins[0]->get_info()->n_inputs;
187 }
188
189 bool
190 PluginInsert::is_generator() const
191 {
192         /* XXX more finesse is possible here. VST plugins have a
193            a specific "instrument" flag, for example.
194          */
195
196         return _plugins[0]->get_info()->n_inputs.n_audio() == 0;
197 }
198
199 void
200 PluginInsert::set_automatable ()
201 {
202         set<Evoral::Parameter> a = _plugins.front()->automatable ();
203
204         Plugin::ParameterDescriptor desc;
205
206         for (set<Evoral::Parameter>::iterator i = a.begin(); i != a.end(); ++i) {
207                 if (i->type() == PluginAutomation) {
208                         can_automate (*i);
209                         _plugins.front()->get_parameter_descriptor(i->id(), desc);
210                         Evoral::Parameter param(*i);
211                         param.set_range(desc.lower, desc.upper, _plugins.front()->default_value(i->id()));
212                         boost::shared_ptr<AutomationList> list(new AutomationList(param));
213                         add_control(boost::shared_ptr<AutomationControl>(new PluginControl(this, *i, list)));
214                 }
215         }
216 }
217
218 void
219 PluginInsert::parameter_changed (Evoral::Parameter which, float val)
220 {
221         if (which.type() != PluginAutomation)
222                 return;
223
224         Plugins::iterator i = _plugins.begin();
225
226         /* don't set the first plugin, just all the slaves */
227
228         if (i != _plugins.end()) {
229                 ++i;
230                 for (; i != _plugins.end(); ++i) {
231                         (*i)->set_parameter (which, val);
232                 }
233         }
234 }
235
236 void
237 PluginInsert::set_block_size (nframes_t nframes)
238 {
239         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
240                 (*i)->set_block_size (nframes);
241         }
242 }
243
244 void
245 PluginInsert::activate ()
246 {
247         Processor::activate ();
248
249         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
250                 (*i)->activate ();
251         }
252 }
253
254 void
255 PluginInsert::deactivate ()
256 {
257         Processor::deactivate ();
258
259         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
260                 (*i)->deactivate ();
261         }
262 }
263
264 void
265 PluginInsert::connect_and_run (BufferSet& bufs, nframes_t nframes, nframes_t offset, bool with_auto, nframes_t now)
266 {
267         // Calculate if, and how many frames we need to collect for analysis
268         nframes_t collect_signal_nframes = (_signal_analysis_collect_nframes_max -
269                                             _signal_analysis_collected_nframes);
270         if (nframes < collect_signal_nframes) { // we might not get all frames now
271                 collect_signal_nframes = nframes;
272         }
273
274         ChanMapping in_map(input_streams());
275         ChanMapping out_map(output_streams());
276
277         /* Note that we've already required that plugins
278            be able to handle in-place processing.
279         */
280
281         if (with_auto) {
282
283                 uint32_t n = 0;
284
285                 for (Controls::iterator li = data().controls().begin(); li != data().controls().end(); ++li, ++n) {
286
287                         boost::shared_ptr<AutomationControl> c
288                                 = boost::dynamic_pointer_cast<AutomationControl>(li->second);
289
290                         if (c->parameter().type() == PluginAutomation && c->automation_playback()) {
291                                 bool valid;
292
293                                 const float val = c->list()->rt_safe_eval (now, valid);
294
295                                 if (valid) {
296                                         c->set_value(val);
297                                 }
298
299                         }
300                 }
301         }
302
303         if (collect_signal_nframes > 0) {
304                 // collect input
305                 //std::cerr << "collect input, bufs " << bufs.count().n_audio() << " count,  " << bufs.available().n_audio() << " available" << std::endl;
306                 //std::cerr << "               streams " << input_streams().n_audio() << std::endl;
307                 //std::cerr << "filling buffer with " << collect_signal_nframes << " frames at " << _signal_analysis_collected_nframes << std::endl;
308
309                 _signal_analysis_inputs.set_count(input_streams());
310
311                 for (uint32_t i = 0; i < input_streams().n_audio(); ++i) {
312                         _signal_analysis_inputs.get_audio(i).read_from(
313                                 bufs.get_audio(i),
314                                 collect_signal_nframes,
315                                 _signal_analysis_collected_nframes); // offset is for target buffer
316                 }
317
318         }
319
320         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
321                 (*i)->connect_and_run(bufs, in_map, out_map, nframes, offset);
322                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
323                         in_map.offset_to(*t, natural_input_streams().get(*t));
324                         out_map.offset_to(*t, natural_output_streams().get(*t));
325                 }
326         }
327
328         if (collect_signal_nframes > 0) {
329                 // collect output
330                 //std::cerr << "       output, bufs " << bufs.count().n_audio() << " count,  " << bufs.available().n_audio() << " available" << std::endl;
331                 //std::cerr << "               streams " << output_streams().n_audio() << std::endl;
332
333                 _signal_analysis_outputs.set_count(output_streams());
334
335                 for (uint32_t i = 0; i < output_streams().n_audio(); ++i) {
336                         _signal_analysis_outputs.get_audio(i).read_from(
337                                 bufs.get_audio(i),
338                                 collect_signal_nframes,
339                                 _signal_analysis_collected_nframes); // offset is for target buffer
340                 }
341
342                 _signal_analysis_collected_nframes += collect_signal_nframes;
343                 assert(_signal_analysis_collected_nframes <= _signal_analysis_collect_nframes_max);
344
345                 if (_signal_analysis_collected_nframes == _signal_analysis_collect_nframes_max) {
346                         _signal_analysis_collect_nframes_max = 0;
347                         _signal_analysis_collected_nframes   = 0;
348
349                         AnalysisDataGathered(&_signal_analysis_inputs,
350                                              &_signal_analysis_outputs);
351                 }
352         }
353         /* leave remaining channel buffers alone */
354 }
355
356 void
357 PluginInsert::silence (nframes_t nframes)
358 {
359         ChanMapping in_map(input_streams());
360         ChanMapping out_map(output_streams());
361
362         if (active()) {
363                 for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
364                         (*i)->connect_and_run (_session.get_silent_buffers ((*i)->get_info()->n_inputs), in_map, out_map, nframes, 0);
365                 }
366         }
367 }
368
369 void
370 PluginInsert::run (BufferSet& bufs, sframes_t /*start_frame*/, sframes_t /*end_frame*/, nframes_t nframes)
371 {
372         if (_active || _pending_active) {
373
374                 if (_session.transport_rolling()) {
375                         automation_run (bufs, nframes);
376                 } else {
377                         connect_and_run (bufs, nframes, 0, false);
378                 }
379
380         } else {
381
382                 /* FIXME: type, audio only */
383
384                 uint32_t in = _plugins[0]->get_info()->n_inputs.n_audio();
385                 uint32_t out = _plugins[0]->get_info()->n_outputs.n_audio();
386
387                 if (out > in) {
388
389                         /* not active, but something has make up for any channel count increase */
390
391                         for (uint32_t n = out - in; n < out; ++n) {
392                                 memcpy (bufs.get_audio(n).data(), bufs.get_audio(in - 1).data(), sizeof (Sample) * nframes);
393                         }
394                 }
395
396                 bufs.count().set_audio(out);
397         }
398
399         _active = _pending_active;
400 }
401
402 void
403 PluginInsert::set_parameter (Evoral::Parameter param, float val)
404 {
405         if (param.type() != PluginAutomation)
406                 return;
407
408         /* the others will be set from the event triggered by this */
409
410         _plugins[0]->set_parameter (param.id(), val);
411
412         boost::shared_ptr<AutomationControl> ac
413                         = boost::dynamic_pointer_cast<AutomationControl>(data().control(param));
414
415         if (ac) {
416                 ac->set_value(val);
417         } else {
418                 warning << "set_parameter called for nonexistant parameter "
419                         << EventTypeMap::instance().to_symbol(param) << endmsg;
420         }
421
422         _session.set_dirty();
423 }
424
425 float
426 PluginInsert::get_parameter (Evoral::Parameter param)
427 {
428         if (param.type() != PluginAutomation)
429                 return 0.0;
430         else
431                 return
432                 _plugins[0]->get_parameter (param.id());
433 }
434
435 void
436 PluginInsert::automation_run (BufferSet& bufs, nframes_t nframes)
437 {
438         Evoral::ControlEvent next_event (0, 0.0f);
439         nframes_t now = _session.transport_frame ();
440         nframes_t end = now + nframes;
441         nframes_t offset = 0;
442
443         Glib::Mutex::Lock lm (data().control_lock(), Glib::TRY_LOCK);
444
445         if (!lm.locked()) {
446                 connect_and_run (bufs, nframes, offset, false);
447                 return;
448         }
449
450         if (!data().find_next_event (now, end, next_event)) {
451
452                 /* no events have a time within the relevant range */
453
454                 connect_and_run (bufs, nframes, offset, true, now);
455                 return;
456         }
457
458         while (nframes) {
459
460                 nframes_t cnt = min (((nframes_t) ceil (next_event.when) - now), nframes);
461
462                 connect_and_run (bufs, cnt, offset, true, now);
463
464                 nframes -= cnt;
465                 offset += cnt;
466                 now += cnt;
467
468                 if (!data().find_next_event (now, end, next_event)) {
469                         break;
470                 }
471         }
472
473         /* cleanup anything that is left to do */
474
475         if (nframes) {
476                 connect_and_run (bufs, nframes, offset, true, now);
477         }
478 }
479
480 float
481 PluginInsert::default_parameter_value (const Evoral::Parameter& param)
482 {
483         if (param.type() != PluginAutomation)
484                 return 1.0;
485
486         if (_plugins.empty()) {
487                 fatal << _("programming error: ") << X_("PluginInsert::default_parameter_value() called with no plugin")
488                       << endmsg;
489                 /*NOTREACHED*/
490         }
491
492         return _plugins[0]->default_value (param.id());
493 }
494
495 boost::shared_ptr<Plugin>
496 PluginInsert::plugin_factory (boost::shared_ptr<Plugin> other)
497 {
498         boost::shared_ptr<LadspaPlugin> lp;
499 #ifdef HAVE_SLV2
500         boost::shared_ptr<LV2Plugin> lv2p;
501 #endif
502 #ifdef VST_SUPPORT
503         boost::shared_ptr<VSTPlugin> vp;
504 #endif
505 #ifdef HAVE_AUDIOUNITS
506         boost::shared_ptr<AUPlugin> ap;
507 #endif
508
509         if ((lp = boost::dynamic_pointer_cast<LadspaPlugin> (other)) != 0) {
510                 return boost::shared_ptr<Plugin> (new LadspaPlugin (*lp));
511 #ifdef HAVE_SLV2
512         } else if ((lv2p = boost::dynamic_pointer_cast<LV2Plugin> (other)) != 0) {
513                 return boost::shared_ptr<Plugin> (new LV2Plugin (*lv2p));
514 #endif
515 #ifdef VST_SUPPORT
516         } else if ((vp = boost::dynamic_pointer_cast<VSTPlugin> (other)) != 0) {
517                 return boost::shared_ptr<Plugin> (new VSTPlugin (*vp));
518 #endif
519 #ifdef HAVE_AUDIOUNITS
520         } else if ((ap = boost::dynamic_pointer_cast<AUPlugin> (other)) != 0) {
521                 return boost::shared_ptr<Plugin> (new AUPlugin (*ap));
522 #endif
523         }
524
525         fatal << string_compose (_("programming error: %1"),
526                           X_("unknown plugin type in PluginInsert::plugin_factory"))
527               << endmsg;
528         /*NOTREACHED*/
529         return boost::shared_ptr<Plugin> ((Plugin*) 0);
530 }
531
532 bool
533 PluginInsert::configure_io (ChanCount in, ChanCount out)
534 {
535         if (set_count (count_for_configuration (in, out)) < 0) {
536                 return false;
537         }
538
539         /* if we're running replicated plugins, each plugin has
540            the same i/o configuration and we may need to announce how many
541            output streams there are.
542
543            if we running a single plugin, we need to configure it.
544         */
545
546         if (_plugins.front()->configure_io (in, out) < 0) {
547                 return false;
548         }
549
550         // we don't know the analysis window size, so we must work with the
551         // current buffer size here. each request for data fills in these
552         // buffers and the analyser makes sure it gets enough data for the
553         // analysis window
554         session().ensure_buffer_set (_signal_analysis_inputs, in);
555         //_signal_analysis_inputs.set_count (in);
556
557         session().ensure_buffer_set (_signal_analysis_outputs, out);
558         //_signal_analysis_outputs.set_count (out);
559
560         // std::cerr << "set counts to i" << in.n_audio() << "/o" << out.n_audio() << std::endl;
561
562         return Processor::configure_io (in, out);
563 }
564
565 bool
566 PluginInsert::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
567 {
568         // Plugin has flexible I/O, so delegate to it
569         if (_plugins.front()->reconfigurable_io()) {
570                 return _plugins.front()->can_support_io_configuration (in, out);
571         }
572
573         ChanCount inputs  = _plugins[0]->get_info()->n_inputs;
574         ChanCount outputs = _plugins[0]->get_info()->n_outputs;
575
576         // Plugin inputs match requested inputs exactly
577         if (inputs == in) {
578                 out = outputs;
579                 return true;
580         }
581
582         // See if replication is possible
583         // We can replicate if there exists a single factor f such that, for every type,
584         // the number of plugin inputs * f = the requested number of inputs
585         uint32_t f             = 0;
586         bool     can_replicate = true;
587         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
588                 // No inputs of this type
589                 if (inputs.get(*t) == 0 && in.get(*t) == 0) {
590                         continue;
591
592                 // Plugin has more inputs than requested, can not replicate
593                 } else if (inputs.get(*t) >= in.get(*t)) {
594                         can_replicate = false;
595                         break;
596
597                 // Plugin inputs is not a factor of requested inputs, can not replicate
598                 } else if (inputs.get(*t) == 0 || in.get(*t) % inputs.get(*t) != 0) {
599                         can_replicate = false;
600                         break;
601
602                 // Potential factor not set yet
603                 } else if (f == 0) {
604                         f = in.get(*t) / inputs.get(*t);;
605                 }
606
607                 // Factor for this type does not match another type, can not replicate
608                 if (f != (in.get(*t) / inputs.get(*t))) {
609                         can_replicate = false;
610                         break;
611                 }
612         }
613
614         if (can_replicate) {
615                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
616                         out.set (*t, outputs.get(*t) * f);
617                 }
618                 return true;
619         } else {
620                 return false;
621         }
622 }
623
624 /* Number of plugin instances required to support a given channel configuration.
625  * (private helper)
626  */
627 int32_t
628 PluginInsert::count_for_configuration (ChanCount in, ChanCount /*out*/) const
629 {
630         if (_plugins.front()->reconfigurable_io()) {
631                 /* plugin has flexible I/O, so the answer is always 1 */
632                 /* this could change if we ever decide to replicate AU's */
633                 return 1;
634         }
635
636         // FIXME: take 'out' into consideration
637
638         ChanCount outputs = _plugins[0]->get_info()->n_outputs;
639         ChanCount inputs = _plugins[0]->get_info()->n_inputs;
640
641         if (inputs.n_total() == 0) {
642                 /* instrument plugin, always legal, but throws away any existing streams */
643                 return 1;
644         }
645
646         if (inputs.n_total() == 1 && outputs == inputs
647                         && ((inputs.n_audio() == 0 && in.n_audio() == 0)
648                                 || (inputs.n_midi() == 0 && in.n_midi() == 0))) {
649                 /* mono plugin, replicate as needed to match in */
650                 return in.n_total();
651         }
652
653         if (inputs == in) {
654                 /* exact match */
655                 return 1;
656         }
657
658         // assumes in is valid, so we must be replicating
659         if (inputs.n_total() < in.n_total()
660                         && (in.n_total() % inputs.n_total() == 0)) {
661
662                 return in.n_total() / inputs.n_total();
663         }
664
665         /* err... */
666         return 0;
667 }
668
669 XMLNode&
670 PluginInsert::get_state(void)
671 {
672         return state (true);
673 }
674
675 XMLNode&
676 PluginInsert::state (bool full)
677 {
678         XMLNode& node = Processor::state (full);
679
680         node.add_property("type", _plugins[0]->state_node_name());
681         node.add_property("unique-id", _plugins[0]->unique_id());
682         node.add_property("count", string_compose("%1", _plugins.size()));
683         node.add_child_nocopy (_plugins[0]->get_state());
684
685         /* add port automation state */
686         XMLNode *autonode = new XMLNode(port_automation_node_name);
687         set<Evoral::Parameter> automatable = _plugins[0]->automatable();
688
689         for (set<Evoral::Parameter>::iterator x = automatable.begin(); x != automatable.end(); ++x) {
690                 
691                 /*XMLNode* child = new XMLNode("port");
692                 snprintf(buf, sizeof(buf), "%" PRIu32, *x);
693                 child->add_property("number", string(buf));
694                 
695                 child->add_child_nocopy (automation_list (*x).state (full));
696                 autonode->add_child_nocopy (*child);
697                 */
698                 autonode->add_child_nocopy (((AutomationList*)data().control(*x)->list().get())->state (full));
699         }
700
701         node.add_child_nocopy (*autonode);
702
703         return node;
704 }
705
706 int
707 PluginInsert::set_state(const XMLNode& node, int version)
708 {
709         XMLNodeList nlist = node.children();
710         XMLNodeIterator niter;
711         XMLPropertyList plist;
712         const XMLProperty *prop;
713         ARDOUR::PluginType type;
714
715         if ((prop = node.property ("type")) == 0) {
716                 error << _("XML node describing plugin is missing the `type' field") << endmsg;
717                 return -1;
718         }
719
720         if (prop->value() == X_("ladspa") || prop->value() == X_("Ladspa")) { /* handle old school sessions */
721                 cout << "- LADSPA\n";
722                 type = ARDOUR::LADSPA;
723         } else if (prop->value() == X_("lv2")) {
724                 type = ARDOUR::LV2;
725         } else if (prop->value() == X_("vst")) {
726                 type = ARDOUR::VST;
727         } else if (prop->value() == X_("audiounit")) {
728                 type = ARDOUR::AudioUnit;
729         } else {
730                 error << string_compose (_("unknown plugin type %1 in plugin insert state"),
731                                   prop->value())
732                       << endmsg;
733                 return -1;
734         }
735
736         prop = node.property ("unique-id");
737
738         if (prop == 0) {
739 #ifdef VST_SUPPORT
740                 /* older sessions contain VST plugins with only an "id" field.
741                  */
742                 
743                 if (type == ARDOUR::VST) {
744                         prop = node.property ("id");
745                 }
746 #endif          
747                 /* recheck  */
748
749                 if (prop == 0) {
750                         error << _("Plugin has no unique ID field") << endmsg;
751                         return -1;
752                 }
753         }
754
755         cout << "- ID " << prop->value() << "\n";
756
757         boost::shared_ptr<Plugin> plugin;
758
759         plugin = find_plugin (_session, prop->value(), type);
760
761         if (plugin == 0) {
762                 error << string_compose(_("Found a reference to a plugin (\"%1\") that is unknown.\n"
763                                    "Perhaps it was removed or moved since it was last used."), prop->value())
764                       << endmsg;
765                 return -1;
766         }
767
768         uint32_t count = 1;
769         bool need_automatables = true;
770
771         if (_plugins.empty()) {
772                 /* if we are adding the first plugin, we will need to set
773                    up automatable controls.
774                 */
775                 need_automatables = true;
776         }
777
778         if ((prop = node.property ("count")) != 0) {
779                 sscanf (prop->value().c_str(), "%u", &count);
780         }
781
782         if (_plugins.size() != count) {
783
784                 _plugins.push_back (plugin);
785
786                 for (uint32_t n = 1; n < count; ++n) {
787                         _plugins.push_back (plugin_factory (plugin));
788                 }
789         }
790
791         if (need_automatables) {
792                 set_automatable ();
793         }
794
795         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
796                 if ((*niter)->name() == plugin->state_node_name()) {
797                         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
798                                 (*i)->set_state (**niter, version);
799                         }
800                         break;
801                 }
802         }
803
804         if (version < 3000) {
805                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
806                         if ((*niter)->name() == "Redirect") {
807                                 /* XXX do we need to tackle placement? i think not (pd; oct 16 2009) */
808                                 Processor::set_state (**niter, version);
809                                 break;
810                         }
811                 }
812                 set_parameter_state_2X (node, version);
813         } else {
814                 Processor::set_state (node, version);
815                 set_parameter_state (node, version);
816         }
817
818         // The name of the PluginInsert comes from the plugin, nothing else
819         _name = plugin->get_info()->name;
820
821         return 0;
822 }
823
824 void
825 PluginInsert::set_parameter_state (const XMLNode& node, int version)
826 {
827         XMLNodeList nlist = node.children();
828         XMLNodeIterator niter;
829
830         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
831                 
832                 if ((*niter)->name() != port_automation_node_name) {
833                         continue;
834                 }
835                 
836                 XMLNodeList cnodes;
837                 XMLProperty *cprop;
838                 XMLNodeConstIterator iter;
839                 XMLNode *child;
840                 const char *port;
841                 uint32_t port_id;
842
843                 cnodes = (*niter)->children ("AutomationList");
844
845                 for (iter = cnodes.begin(); iter != cnodes.end(); ++iter) {
846
847                         child = *iter;
848
849                         /* XXX this code knows way too much about the internal details of an AutomationList state node */
850
851                         if ((cprop = child->property("automation-id")) != 0) {
852                                 port = cprop->value().c_str();
853                         } else {
854                                 warning << _("PluginInsert: Auto: no plugin parameter number seen") << endmsg;
855                                 continue;
856                         }
857
858                         if (sscanf (port, "parameter-%" PRIu32, &port_id) != 1) {
859                                 warning << _("PluginInsert: Auto: no parameter number found") << endmsg;
860                                 continue;
861                         }
862
863                         if (port_id >= _plugins[0]->parameter_count()) {
864                                 warning << _("PluginInsert: Auto: plugin parameter out of range") << endmsg;
865                                 continue;
866                         }
867
868                         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(
869                                         data().control(Evoral::Parameter(PluginAutomation, 0, port_id), true));
870
871                         if (c) {
872                                 c->alist()->set_state (*child, version);
873                         } else {
874                                 error << string_compose (_("PluginInsert: automatable control %1 not found - ignored"), port_id) << endmsg;
875                         }
876                 }
877
878                 /* done */
879                 
880                 break;
881         }
882 }
883
884 void
885 PluginInsert::set_parameter_state_2X (const XMLNode& node, int version)
886 {
887         XMLNodeList nlist = node.children();
888         XMLNodeIterator niter;
889
890         /* look for port automation node */
891         
892         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
893
894                 if ((*niter)->name() != port_automation_node_name) {
895                         continue;
896                 }
897
898                 XMLNodeList cnodes;
899                 XMLProperty *cprop;
900                 XMLNodeConstIterator iter;
901                 XMLNode *child;
902                 const char *port;
903                 uint32_t port_id;
904                 
905                 cnodes = (*niter)->children ("port");
906                 
907                 for(iter = cnodes.begin(); iter != cnodes.end(); ++iter){
908                         
909                         child = *iter;
910                         
911                         if ((cprop = child->property("number")) != 0) {
912                                 port = cprop->value().c_str();
913                         } else {
914                                 warning << _("PluginInsert: Auto: no ladspa port number") << endmsg;
915                                 continue;
916                         }
917                         
918                         sscanf (port, "%" PRIu32, &port_id);
919                         
920                         if (port_id >= _plugins[0]->parameter_count()) {
921                                 warning << _("PluginInsert: Auto: port id out of range") << endmsg;
922                                 continue;
923                         }
924
925                         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(
926                                         data().control(Evoral::Parameter(PluginAutomation, 0, port_id), true));
927
928                         if (c) {
929                                 if (!child->children().empty()) {
930                                         c->alist()->set_state (*child->children().front(), version);
931                                 }
932                         } else {
933                                 error << string_compose (_("PluginInsert: automatable control %1 not found - ignored"), port_id) << endmsg;
934                         }
935                 }
936                 
937                 /* done */
938                 
939                 break;
940         } 
941 }
942
943
944 string
945 PluginInsert::describe_parameter (Evoral::Parameter param)
946 {
947         if (param.type() != PluginAutomation)
948                 return Automatable::describe_parameter(param);
949
950         return _plugins[0]->describe_parameter (param);
951 }
952
953 ARDOUR::nframes_t
954 PluginInsert::signal_latency() const
955 {
956         if (_user_latency) {
957                 return _user_latency;
958         }
959
960         return _plugins[0]->signal_latency ();
961 }
962
963 ARDOUR::PluginType
964 PluginInsert::type ()
965 {
966         boost::shared_ptr<LadspaPlugin> lp;
967 #ifdef VST_SUPPORT
968         boost::shared_ptr<VSTPlugin> vp;
969 #endif
970 #ifdef HAVE_AUDIOUNITS
971         boost::shared_ptr<AUPlugin> ap;
972 #endif
973
974         PluginPtr other = plugin ();
975
976         if ((lp = boost::dynamic_pointer_cast<LadspaPlugin> (other)) != 0) {
977                 return ARDOUR::LADSPA;
978 #ifdef VST_SUPPORT
979         } else if ((vp = boost::dynamic_pointer_cast<VSTPlugin> (other)) != 0) {
980                 return ARDOUR::VST;
981 #endif
982 #ifdef HAVE_AUDIOUNITS
983         } else if ((ap = boost::dynamic_pointer_cast<AUPlugin> (other)) != 0) {
984                 return ARDOUR::AudioUnit;
985 #endif
986         } else {
987                 /* NOT REACHED */
988                 return (ARDOUR::PluginType) 0;
989         }
990 }
991
992 PluginInsert::PluginControl::PluginControl (PluginInsert* p, const Evoral::Parameter &param, boost::shared_ptr<AutomationList> list)
993         : AutomationControl (p->session(), param, list, p->describe_parameter(param))
994         , _plugin (p)
995 {
996         Plugin::ParameterDescriptor desc;
997         p->plugin(0)->get_parameter_descriptor (param.id(), desc);
998         _logarithmic = desc.logarithmic;
999         _toggled = desc.toggled;
1000 }
1001
1002 void
1003 PluginInsert::PluginControl::set_value (float val)
1004 {
1005         /* FIXME: probably should be taking out some lock here.. */
1006
1007         if (_toggled) {
1008                 if (val > 0.5) {
1009                         val = 1.0;
1010                 } else {
1011                         val = 0.0;
1012                 }
1013         } else {
1014
1015                 /*const float range = _list->get_max_y() - _list->get_min_y();
1016                 const float lower = _list->get_min_y();
1017
1018                 if (!_logarithmic) {
1019                         val = lower + (range * val);
1020                 } else {
1021                         float log_lower = 0.0f;
1022                         if (lower > 0.0f) {
1023                                 log_lower = log(lower);
1024                         }
1025
1026                         val = exp(log_lower + log(range) * val);
1027                 }*/
1028
1029         }
1030
1031         for (Plugins::iterator i = _plugin->_plugins.begin();
1032                         i != _plugin->_plugins.end(); ++i) {
1033                 (*i)->set_parameter (_list->parameter().id(), val);
1034         }
1035
1036         boost::shared_ptr<Plugin> iasp = _plugin->_impulseAnalysisPlugin.lock();
1037         if (iasp) {
1038                 iasp->set_parameter (_list->parameter().id(), val);
1039         }
1040
1041         AutomationControl::set_value(val);
1042 }
1043
1044 float
1045 PluginInsert::PluginControl::get_value (void) const
1046 {
1047         /* FIXME: probably should be taking out some lock here.. */
1048
1049         float val = _plugin->get_parameter (_list->parameter());
1050
1051         return val;
1052
1053         /*if (_toggled) {
1054
1055                 return val;
1056
1057         } else {
1058
1059                 if (_logarithmic) {
1060                         val = log(val);
1061                 }
1062
1063                 return ((val - lower) / range);
1064         }*/
1065 }
1066
1067 boost::shared_ptr<Plugin>
1068 PluginInsert::get_impulse_analysis_plugin()
1069 {
1070         boost::shared_ptr<Plugin> ret;
1071         if (_impulseAnalysisPlugin.expired()) {
1072                 ret = plugin_factory(_plugins[0]);
1073                 _impulseAnalysisPlugin = ret;
1074         } else {
1075                 ret = _impulseAnalysisPlugin.lock();
1076         }
1077
1078         return ret;
1079 }
1080
1081 void
1082 PluginInsert::collect_signal_for_analysis(nframes_t nframes)
1083 {
1084         // called from outside the audio thread, so this should be safe
1085         // only do audio as analysis is (currently) only for audio plugins
1086         _signal_analysis_inputs.ensure_buffers(  DataType::AUDIO, input_streams().n_audio(),  nframes);
1087         _signal_analysis_outputs.ensure_buffers( DataType::AUDIO, output_streams().n_audio(), nframes);
1088
1089         _signal_analysis_collected_nframes   = 0;
1090         _signal_analysis_collect_nframes_max = nframes;
1091 }
1092