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