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