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