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