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