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