prepare strict-i/o configuration.
[ardour.git] / libs / ardour / plugin_insert.cc
1 /*
2     Copyright (C) 2000 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #ifdef WAF_BUILD
21 #include "libardour-config.h"
22 #endif
23
24 #include <string>
25
26 #include "pbd/failed_constructor.h"
27 #include "pbd/xml++.h"
28 #include "pbd/convert.h"
29
30 #include "ardour/audio_buffer.h"
31 #include "ardour/automation_list.h"
32 #include "ardour/buffer_set.h"
33 #include "ardour/debug.h"
34 #include "ardour/event_type_map.h"
35 #include "ardour/ladspa_plugin.h"
36 #include "ardour/luaproc.h"
37 #include "ardour/plugin.h"
38 #include "ardour/plugin_insert.h"
39
40 #ifdef LV2_SUPPORT
41 #include "ardour/lv2_plugin.h"
42 #endif
43
44 #ifdef WINDOWS_VST_SUPPORT
45 #include "ardour/windows_vst_plugin.h"
46 #endif
47
48 #ifdef LXVST_SUPPORT
49 #include "ardour/lxvst_plugin.h"
50 #endif
51
52 #ifdef AUDIOUNIT_SUPPORT
53 #include "ardour/audio_unit.h"
54 #endif
55
56 #include "ardour/session.h"
57 #include "ardour/types.h"
58
59 #include "i18n.h"
60
61 using namespace std;
62 using namespace ARDOUR;
63 using namespace PBD;
64
65 const string PluginInsert::port_automation_node_name = "PortAutomation";
66
67 PluginInsert::PluginInsert (Session& s, boost::shared_ptr<Plugin> plug)
68         : Processor (s, (plug ? plug->name() : string ("toBeRenamed")))
69         , _signal_analysis_collected_nframes(0)
70         , _signal_analysis_collect_nframes_max(0)
71         , _strict_io (false)
72         , _strict_io_configured (false)
73 {
74         /* the first is the master */
75
76         if (plug) {
77                 add_plugin (plug);
78                 create_automatable_parameters ();
79         }
80 }
81
82 bool
83 PluginInsert::set_count (uint32_t num)
84 {
85         bool require_state = !_plugins.empty();
86
87         /* this is a bad idea.... we shouldn't do this while active.
88            only a route holding their redirect_lock should be calling this
89         */
90
91         if (num == 0) {
92                 return false;
93         } else if (num > _plugins.size()) {
94                 uint32_t diff = num - _plugins.size();
95
96                 for (uint32_t n = 0; n < diff; ++n) {
97                         boost::shared_ptr<Plugin> p = plugin_factory (_plugins[0]);
98                         add_plugin (p);
99                         if (active ()) {
100                                 p->activate ();
101                         }
102
103                         if (require_state) {
104                                 /* XXX do something */
105                         }
106                 }
107
108         } else if (num < _plugins.size()) {
109                 uint32_t diff = _plugins.size() - num;
110                 for (uint32_t n= 0; n < diff; ++n) {
111                         _plugins.pop_back();
112                 }
113         }
114
115         return true;
116 }
117
118 PluginInsert::~PluginInsert ()
119 {
120 }
121
122 void
123 PluginInsert::control_list_automation_state_changed (Evoral::Parameter which, AutoState s)
124 {
125         if (which.type() != PluginAutomation)
126                 return;
127
128         boost::shared_ptr<AutomationControl> c
129                         = boost::dynamic_pointer_cast<AutomationControl>(control (which));
130
131         if (c && s != Off) {
132                 _plugins[0]->set_parameter (which.id(), c->list()->eval (_session.transport_frame()));
133         }
134 }
135
136 ChanCount
137 PluginInsert::output_streams() const
138 {
139         assert (!_plugins.empty());
140
141         PluginInfoPtr info = _plugins.front()->get_info();
142
143         if (_strict_io_configured) {
144                 return _configured_in; // XXX, check initial configuration
145         }
146         else if (info->reconfigurable_io()) {
147                 ChanCount out = _plugins.front()->output_streams ();
148                 // DEBUG_TRACE (DEBUG::Processors, string_compose ("Plugin insert, reconfigur(able) output streams = %1\n", out));
149                 return out;
150         } else {
151                 ChanCount out = info->n_outputs;
152                 // DEBUG_TRACE (DEBUG::Processors, string_compose ("Plugin insert, static output streams = %1 for %2 plugins\n", out, _plugins.size()));
153                 out.set_audio (out.n_audio() * _plugins.size());
154                 out.set_midi (out.n_midi() * _plugins.size() + midi_bypass.n_midi());
155                 return out;
156         }
157 }
158
159 ChanCount
160 PluginInsert::input_streams() const
161 {
162         assert (!_plugins.empty());
163
164         ChanCount in;
165
166         PluginInfoPtr info = _plugins.front()->get_info();
167
168         if (info->reconfigurable_io()) {
169                 assert (_plugins.size() == 1);
170                 in = _plugins.front()->input_streams();
171         } else {
172                 in = info->n_inputs;
173         }
174
175         DEBUG_TRACE (DEBUG::Processors, string_compose ("Plugin insert, input streams = %1, match using %2\n", in, _match.method));
176
177         if (_match.method == Split) {
178
179                 /* we are splitting 1 processor input to multiple plugin inputs,
180                    so we have a maximum of 1 stream of each type.
181                 */
182                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
183                         if (in.get (*t) > 1) {
184                                 in.set (*t, 1);
185                         }
186                 }
187                 return in;
188
189         } else if (_match.method == Hide) {
190
191                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
192                         in.set (*t, in.get (*t) - _match.hide.get (*t));
193                 }
194                 return in;
195
196         } else {
197
198                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
199                         in.set (*t, in.get (*t) * _plugins.size ());
200                 }
201
202                 return in;
203         }
204 }
205
206 ChanCount
207 PluginInsert::natural_output_streams() const
208 {
209         return _plugins[0]->get_info()->n_outputs;
210 }
211
212 ChanCount
213 PluginInsert::natural_input_streams() const
214 {
215         return _plugins[0]->get_info()->n_inputs;
216 }
217
218 bool
219 PluginInsert::has_no_inputs() const
220 {
221         return _plugins[0]->get_info()->n_inputs == ChanCount::ZERO;
222 }
223
224 bool
225 PluginInsert::has_no_audio_inputs() const
226 {
227         return _plugins[0]->get_info()->n_inputs.n_audio() == 0;
228 }
229
230 bool
231 PluginInsert::is_midi_instrument() const
232 {
233         /* XXX more finesse is possible here. VST plugins have a
234            a specific "instrument" flag, for example.
235          */
236         PluginInfoPtr pi = _plugins[0]->get_info();
237
238         return pi->n_inputs.n_midi() != 0 &&
239                 pi->n_outputs.n_audio() > 0;
240 }
241
242 void
243 PluginInsert::create_automatable_parameters ()
244 {
245         assert (!_plugins.empty());
246
247         set<Evoral::Parameter> a = _plugins.front()->automatable ();
248
249         for (set<Evoral::Parameter>::iterator i = a.begin(); i != a.end(); ++i) {
250                 if (i->type() == PluginAutomation) {
251
252                         Evoral::Parameter param(*i);
253
254                         ParameterDescriptor desc;
255                         _plugins.front()->get_parameter_descriptor(i->id(), desc);
256
257                         can_automate (param);
258                         boost::shared_ptr<AutomationList> list(new AutomationList(param, desc));
259                         boost::shared_ptr<AutomationControl> c (new PluginControl(this, param, desc, list));
260                         add_control (c);
261                         _plugins.front()->set_automation_control (i->id(), c);
262                 } else if (i->type() == PluginPropertyAutomation) {
263                         Evoral::Parameter param(*i);
264                         const ParameterDescriptor& desc = _plugins.front()->get_property_descriptor(param.id());
265                         if (desc.datatype != Variant::NOTHING) {
266                                 boost::shared_ptr<AutomationList> list;
267                                 if (Variant::type_is_numeric(desc.datatype)) {
268                                         list = boost::shared_ptr<AutomationList>(new AutomationList(param, desc));
269                                 }
270                                 add_control (boost::shared_ptr<AutomationControl> (new PluginPropertyControl(this, param, desc, list)));
271                         }
272                 }
273         }
274 }
275 /** Called when something outside of this host has modified a plugin
276  * parameter. Responsible for propagating the change to two places:
277  *
278  *   1) anything listening to the Control itself
279  *   2) any replicated plugins that make up this PluginInsert.
280  *
281  * The PluginInsert is connected to the ParameterChangedExternally signal for
282  * the first (primary) plugin, and here broadcasts that change to any others.
283  *
284  * XXX We should probably drop this whole replication idea (Paul, October 2015)
285  * since it isn't used by sensible plugin APIs (AU, LV2).
286  */
287 void
288 PluginInsert::parameter_changed_externally (uint32_t which, float val)
289 {
290         boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter (PluginAutomation, 0, which));
291
292         /* First propagation: alter the underlying value of the control,
293          * without telling the plugin(s) that own/use it to set it.
294          */
295
296         if (!ac) {
297                 return;
298         }
299
300         boost::shared_ptr<PluginControl> pc = boost::dynamic_pointer_cast<PluginControl> (ac);
301
302         if (pc) {
303                 pc->catch_up_with_external_value (val);
304         }
305
306         /* Second propagation: tell all plugins except the first to
307            update the value of this parameter. For sane plugin APIs,
308            there are no other plugins, so this is a no-op in those
309            cases.
310         */
311
312         Plugins::iterator i = _plugins.begin();
313
314         /* don't set the first plugin, just all the slaves */
315
316         if (i != _plugins.end()) {
317                 ++i;
318                 for (; i != _plugins.end(); ++i) {
319                         (*i)->set_parameter (which, val);
320                 }
321         }
322 }
323
324 int
325 PluginInsert::set_block_size (pframes_t nframes)
326 {
327         int ret = 0;
328         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
329                 if ((*i)->set_block_size (nframes) != 0) {
330                         ret = -1;
331                 }
332         }
333         return ret;
334 }
335
336 void
337 PluginInsert::activate ()
338 {
339         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
340                 (*i)->activate ();
341         }
342
343         Processor::activate ();
344 }
345
346 void
347 PluginInsert::deactivate ()
348 {
349         Processor::deactivate ();
350
351         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
352                 (*i)->deactivate ();
353         }
354 }
355
356 void
357 PluginInsert::flush ()
358 {
359         for (vector<boost::shared_ptr<Plugin> >::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
360                 (*i)->flush ();
361         }
362 }
363
364 void
365 PluginInsert::connect_and_run (BufferSet& bufs, pframes_t nframes, framecnt_t offset, bool with_auto, framepos_t now)
366 {
367         // Calculate if, and how many frames we need to collect for analysis
368         framecnt_t collect_signal_nframes = (_signal_analysis_collect_nframes_max -
369                                              _signal_analysis_collected_nframes);
370         if (nframes < collect_signal_nframes) { // we might not get all frames now
371                 collect_signal_nframes = nframes;
372         }
373
374         ChanCount const in_streams = input_streams ();
375         ChanCount const out_streams = output_streams ();
376
377         bool valid;
378         if (_match.method == Split) {
379                 /* fix the input mapping so that we have maps for each of the plugin's inputs */
380
381                 /* copy the first stream's buffer contents to the others */
382                 /* XXX: audio only */
383                 uint32_t first_idx = _in_map.get (DataType::AUDIO, 0, &valid);
384                 if (valid) {
385                         for (uint32_t i = in_streams.n_audio(); i < natural_input_streams().n_audio(); ++i) {
386                                 bufs.get_audio(_in_map.get (DataType::AUDIO, i, &valid)).read_from(bufs.get_audio(first_idx), nframes, offset, offset);
387                         }
388                 }
389         }
390
391         bufs.set_count(ChanCount::max(bufs.count(), in_streams));
392         bufs.set_count(ChanCount::max(bufs.count(), out_streams));
393
394         /* Note that we've already required that plugins
395            be able to handle in-place processing.
396         */
397
398         if (with_auto) {
399
400                 uint32_t n = 0;
401
402                 for (Controls::iterator li = controls().begin(); li != controls().end(); ++li, ++n) {
403
404                         boost::shared_ptr<AutomationControl> c
405                                 = boost::dynamic_pointer_cast<AutomationControl>(li->second);
406
407                         if (c->list() && c->automation_playback()) {
408                                 bool valid;
409
410                                 const float val = c->list()->rt_safe_eval (now, valid);
411
412                                 if (valid) {
413                                         /* This is the ONLY place where we are
414                                          *  allowed to call
415                                          *  AutomationControl::set_value_unchecked(). We
416                                          *  know that the control is in
417                                          *  automation playback mode, so no
418                                          *  check on writable() is required
419                                          *  (which must be done in AutomationControl::set_value()
420                                          *
421                                          */
422                                         c->set_value_unchecked(val);
423                                 }
424
425                         }
426                 }
427         }
428
429         if (collect_signal_nframes > 0) {
430                 // collect input
431                 //std::cerr << "collect input, bufs " << bufs.count().n_audio() << " count,  " << bufs.available().n_audio() << " available" << std::endl;
432                 //std::cerr << "               streams " << input_streams().n_audio() << std::endl;
433                 //std::cerr << "filling buffer with " << collect_signal_nframes << " frames at " << _signal_analysis_collected_nframes << std::endl;
434
435                 _signal_analysis_inputs.set_count(input_streams());
436
437                 for (uint32_t i = 0; i < input_streams().n_audio(); ++i) {
438                         _signal_analysis_inputs.get_audio(i).read_from(
439                                 bufs.get_audio(i),
440                                 collect_signal_nframes,
441                                 _signal_analysis_collected_nframes); // offset is for target buffer
442                 }
443
444         }
445
446
447         // copy - for now - since the map is offset below
448         // TODO: use dedicated maps per plugin
449         ChanMapping in_map (_in_map);
450         ChanMapping out_map (_out_map);
451
452         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
453                 if ((*i)->connect_and_run(bufs, in_map, out_map, nframes, offset)) {
454                         deactivate ();
455                 }
456                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
457                         in_map.offset_to(*t, natural_input_streams().get(*t));
458                         out_map.offset_to(*t, natural_output_streams().get(*t));
459                 }
460         }
461
462         if (collect_signal_nframes > 0) {
463                 // collect output
464                 //std::cerr << "       output, bufs " << bufs.count().n_audio() << " count,  " << bufs.available().n_audio() << " available" << std::endl;
465                 //std::cerr << "               streams " << output_streams().n_audio() << std::endl;
466
467                 _signal_analysis_outputs.set_count(output_streams());
468
469                 for (uint32_t i = 0; i < output_streams().n_audio(); ++i) {
470                         _signal_analysis_outputs.get_audio(i).read_from(
471                                 bufs.get_audio(i),
472                                 collect_signal_nframes,
473                                 _signal_analysis_collected_nframes); // offset is for target buffer
474                 }
475
476                 _signal_analysis_collected_nframes += collect_signal_nframes;
477                 assert(_signal_analysis_collected_nframes <= _signal_analysis_collect_nframes_max);
478
479                 if (_signal_analysis_collected_nframes == _signal_analysis_collect_nframes_max) {
480                         _signal_analysis_collect_nframes_max = 0;
481                         _signal_analysis_collected_nframes   = 0;
482
483                         AnalysisDataGathered(&_signal_analysis_inputs,
484                                              &_signal_analysis_outputs);
485                 }
486         }
487         /* leave remaining channel buffers alone */
488 }
489
490 void
491 PluginInsert::silence (framecnt_t nframes)
492 {
493         if (!active ()) {
494                 return;
495         }
496
497         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
498                 (*i)->connect_and_run (_session.get_scratch_buffers ((*i)->get_info()->n_inputs, true), _in_map, _out_map, nframes, 0);
499         }
500 }
501
502 void
503 PluginInsert::run (BufferSet& bufs, framepos_t start_frame, framepos_t /*end_frame*/, pframes_t nframes, bool)
504 {
505         if (_pending_active) {
506                 /* run as normal if we are active or moving from inactive to active */
507
508                 if (_session.transport_rolling() || _session.bounce_processing()) {
509                         automation_run (bufs, start_frame, nframes);
510                 } else {
511                         connect_and_run (bufs, nframes, 0, false);
512                 }
513
514         } else {
515                 uint32_t in = input_streams ().n_audio ();
516                 uint32_t out = output_streams().n_audio ();
517
518                 if (has_no_audio_inputs() || in == 0) {
519
520                         /* silence all (audio) outputs. Should really declick
521                          * at the transitions of "active"
522                          */
523
524                         for (uint32_t n = 0; n < out; ++n) {
525                                 bufs.get_audio (n).silence (nframes);
526                         }
527
528                 } else if (out > in) {
529
530                         /* not active, but something has make up for any channel count increase */
531
532                         // TODO: option round-robin (n % in) or silence additional buffers ??
533                         // for now , simply replicate last buffer
534                         for (uint32_t n = in; n < out; ++n) {
535                                 bufs.get_audio(n).read_from(bufs.get_audio(in - 1), nframes);
536                         }
537                 }
538
539                 bufs.count().set_audio (out);
540         }
541
542         _active = _pending_active;
543
544         /* we have no idea whether the plugin generated silence or not, so mark
545          * all buffers appropriately.
546          */
547
548 }
549
550 void
551 PluginInsert::automation_run (BufferSet& bufs, framepos_t start, pframes_t nframes)
552 {
553         Evoral::ControlEvent next_event (0, 0.0f);
554         framepos_t now = start;
555         framepos_t end = now + nframes;
556         framecnt_t offset = 0;
557
558         Glib::Threads::Mutex::Lock lm (control_lock(), Glib::Threads::TRY_LOCK);
559
560         if (!lm.locked()) {
561                 connect_and_run (bufs, nframes, offset, false);
562                 return;
563         }
564
565         if (!find_next_event (now, end, next_event) || _plugins.front()->requires_fixed_sized_buffers()) {
566
567                 /* no events have a time within the relevant range */
568
569                 connect_and_run (bufs, nframes, offset, true, now);
570                 return;
571         }
572
573         while (nframes) {
574
575                 framecnt_t cnt = min (((framecnt_t) ceil (next_event.when) - now), (framecnt_t) nframes);
576
577                 connect_and_run (bufs, cnt, offset, true, now);
578
579                 nframes -= cnt;
580                 offset += cnt;
581                 now += cnt;
582
583                 if (!find_next_event (now, end, next_event)) {
584                         break;
585                 }
586         }
587
588         /* cleanup anything that is left to do */
589
590         if (nframes) {
591                 connect_and_run (bufs, nframes, offset, true, now);
592         }
593 }
594
595 float
596 PluginInsert::default_parameter_value (const Evoral::Parameter& param)
597 {
598         if (param.type() != PluginAutomation)
599                 return 1.0;
600
601         if (_plugins.empty()) {
602                 fatal << _("programming error: ") << X_("PluginInsert::default_parameter_value() called with no plugin")
603                       << endmsg;
604                 abort(); /*NOTREACHED*/
605         }
606
607         return _plugins[0]->default_value (param.id());
608 }
609
610
611 bool
612 PluginInsert::can_reset_all_parameters ()
613 {
614         bool all = true;
615         uint32_t params = 0;
616         for (uint32_t par = 0; par < _plugins[0]->parameter_count(); ++par) {
617                 bool ok=false;
618                 const uint32_t cid = _plugins[0]->nth_parameter (par, ok);
619
620                 if (!ok || !_plugins[0]->parameter_is_input(cid)) {
621                         continue;
622                 }
623
624                 boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter(PluginAutomation, 0, cid));
625                 if (!ac) {
626                         continue;
627                 }
628
629                 ++params;
630                 if (ac->automation_state() & Play) {
631                         all = false;
632                         break;
633                 }
634         }
635         return all && (params > 0);
636 }
637
638 bool
639 PluginInsert::reset_parameters_to_default ()
640 {
641         bool all = true;
642
643         for (uint32_t par = 0; par < _plugins[0]->parameter_count(); ++par) {
644                 bool ok=false;
645                 const uint32_t cid = _plugins[0]->nth_parameter (par, ok);
646
647                 if (!ok || !_plugins[0]->parameter_is_input(cid)) {
648                         continue;
649                 }
650
651                 const float dflt = _plugins[0]->default_value (cid);
652                 const float curr = _plugins[0]->get_parameter (cid);
653
654                 if (dflt == curr) {
655                         continue;
656                 }
657
658                 boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter(PluginAutomation, 0, cid));
659                 if (!ac) {
660                         continue;
661                 }
662
663                 if (ac->automation_state() & Play) {
664                         all = false;
665                         continue;
666                 }
667
668                 ac->set_value (dflt, Controllable::NoGroup);
669         }
670         return all;
671 }
672
673 boost::shared_ptr<Plugin>
674 PluginInsert::plugin_factory (boost::shared_ptr<Plugin> other)
675 {
676         boost::shared_ptr<LadspaPlugin> lp;
677         boost::shared_ptr<LuaProc> lua;
678 #ifdef LV2_SUPPORT
679         boost::shared_ptr<LV2Plugin> lv2p;
680 #endif
681 #ifdef WINDOWS_VST_SUPPORT
682         boost::shared_ptr<WindowsVSTPlugin> vp;
683 #endif
684 #ifdef LXVST_SUPPORT
685         boost::shared_ptr<LXVSTPlugin> lxvp;
686 #endif
687 #ifdef AUDIOUNIT_SUPPORT
688         boost::shared_ptr<AUPlugin> ap;
689 #endif
690
691         if ((lp = boost::dynamic_pointer_cast<LadspaPlugin> (other)) != 0) {
692                 return boost::shared_ptr<Plugin> (new LadspaPlugin (*lp));
693         } else if ((lua = boost::dynamic_pointer_cast<LuaProc> (other)) != 0) {
694                 return boost::shared_ptr<Plugin> (new LuaProc (*lua));
695 #ifdef LV2_SUPPORT
696         } else if ((lv2p = boost::dynamic_pointer_cast<LV2Plugin> (other)) != 0) {
697                 return boost::shared_ptr<Plugin> (new LV2Plugin (*lv2p));
698 #endif
699 #ifdef WINDOWS_VST_SUPPORT
700         } else if ((vp = boost::dynamic_pointer_cast<WindowsVSTPlugin> (other)) != 0) {
701                 return boost::shared_ptr<Plugin> (new WindowsVSTPlugin (*vp));
702 #endif
703 #ifdef LXVST_SUPPORT
704         } else if ((lxvp = boost::dynamic_pointer_cast<LXVSTPlugin> (other)) != 0) {
705                 return boost::shared_ptr<Plugin> (new LXVSTPlugin (*lxvp));
706 #endif
707 #ifdef AUDIOUNIT_SUPPORT
708         } else if ((ap = boost::dynamic_pointer_cast<AUPlugin> (other)) != 0) {
709                 return boost::shared_ptr<Plugin> (new AUPlugin (*ap));
710 #endif
711         }
712
713         fatal << string_compose (_("programming error: %1"),
714                           X_("unknown plugin type in PluginInsert::plugin_factory"))
715               << endmsg;
716         abort(); /*NOTREACHED*/
717         return boost::shared_ptr<Plugin> ((Plugin*) 0);
718 }
719
720 bool
721 PluginInsert::configure_io (ChanCount in, ChanCount out)
722 {
723         Match old_match = _match;
724         ChanCount old_in = input_streams ();
725         ChanCount old_out = output_streams ();
726
727         _configured_in = in;
728         _configured_out = out;
729
730         /* set the matching method and number of plugins that we will use to meet this configuration */
731         _match = private_can_support_io_configuration (in, out);
732         if (set_count (_match.plugins) == false) {
733                 PluginIoReConfigure (); /* EMIT SIGNAL */
734                 return false;
735         }
736
737         /* configure plugins */
738         switch (_match.method) {
739         case Split:
740         case Hide:
741                 if (_plugins.front()->configure_io (_plugins.front()->get_info()->n_inputs, out) == false) {
742                         PluginIoReConfigure (); /* EMIT SIGNAL */
743                         return false;
744                 }
745                 break;
746
747         default:
748                 if (_plugins.front()->configure_io (in, out) == false) {
749                         PluginIoReConfigure (); /* EMIT SIGNAL */
750                         return false;
751                 }
752                 break;
753         }
754
755         if (_match.method == Split) {
756                 /* fix the input mapping so that we have maps for each of the plugin's inputs */
757                 _in_map = ChanMapping (natural_input_streams ());
758         } else {
759                 _in_map = ChanMapping (input_streams ());
760         }
761         _out_map = ChanMapping (output_streams());
762
763 #if 0
764         cout << "Set Channel Maps:" << name () << " " << this
765                 << "\nin:\n" << _in_map
766                 << "\nout:\n" << _out_map
767                 << "\n";
768 #endif
769
770
771         if (  (old_match.method != _match.method && (old_match.method == Split || _match.method == Split))
772                         || old_in != in
773                         || old_out != out
774                         )
775         {
776                 PluginIoReConfigure (); /* EMIT SIGNAL */
777         }
778
779         // we don't know the analysis window size, so we must work with the
780         // current buffer size here. each request for data fills in these
781         // buffers and the analyser makes sure it gets enough data for the
782         // analysis window
783         session().ensure_buffer_set (_signal_analysis_inputs, in);
784         //_signal_analysis_inputs.set_count (in);
785
786         session().ensure_buffer_set (_signal_analysis_outputs, out);
787         //_signal_analysis_outputs.set_count (out);
788
789         // std::cerr << "set counts to i" << in.n_audio() << "/o" << out.n_audio() << std::endl;
790
791         return Processor::configure_io (in, out);
792 }
793
794 /** Decide whether this PluginInsert can support a given IO configuration.
795  *  To do this, we run through a set of possible solutions in rough order of
796  *  preference.
797  *
798  *  @param in Required input channel count.
799  *  @param out Filled in with the output channel count if we return true.
800  *  @return true if the given IO configuration can be supported.
801  */
802 bool
803 PluginInsert::can_support_io_configuration (const ChanCount& in, ChanCount& out)
804 {
805         return private_can_support_io_configuration (in, out).method != Impossible;
806 }
807
808 /** A private version of can_support_io_configuration which returns the method
809  *  by which the configuration can be matched, rather than just whether or not
810  *  it can be.
811  */
812 PluginInsert::Match
813 PluginInsert::private_can_support_io_configuration (ChanCount const & inx, ChanCount& out)
814 {
815         _strict_io_configured = false;
816         if (_plugins.empty()) {
817                 return Match();
818         }
819
820         PluginInfoPtr info = _plugins.front()->get_info();
821         ChanCount in; in += inx;
822         midi_bypass.reset();
823
824         if (info->reconfigurable_io()) {
825                 /* Plugin has flexible I/O, so delegate to it */
826                 bool const r = _plugins.front()->can_support_io_configuration (in, out);
827                 if (!r) {
828                         return Match (Impossible, 0);
829                 }
830
831                 if (_strict_io && in.n_audio() < out.n_audio()) {
832                         DEBUG_TRACE (DEBUG::Processors, string_compose ("hiding output ports of reconfigurable %1\n", name()));
833                         out.set (DataType::AUDIO, in.get (DataType::AUDIO));
834                 }
835
836                 return Match (Delegate, 1);
837         }
838
839         ChanCount inputs  = info->n_inputs;
840         ChanCount outputs = info->n_outputs;
841
842         if (in.get(DataType::MIDI) == 1 && outputs.get(DataType::MIDI) == 0) {
843                 DEBUG_TRACE ( DEBUG::Processors, string_compose ("bypassing midi-data around %1\n", name()));
844                 midi_bypass.set(DataType::MIDI, 1);
845         }
846         if (in.get(DataType::MIDI) == 1 && inputs.get(DataType::MIDI) == 0) {
847                 DEBUG_TRACE ( DEBUG::Processors, string_compose ("hiding midi-port from plugin %1\n", name()));
848                 in.set(DataType::MIDI, 0);
849         }
850
851         bool no_inputs = true;
852         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
853                 if (inputs.get (*t) != 0) {
854                         no_inputs = false;
855                         break;
856                 }
857         }
858
859         if (no_inputs) {
860                 /* no inputs so we can take any input configuration since we throw it away */
861                 out = outputs + midi_bypass;
862                 return Match (NoInputs, 1);
863         }
864
865         /* Plugin inputs match requested inputs exactly */
866         if (inputs == in  && (!_strict_io || outputs.n_audio() == inputs.n_audio())) {
867                 out = outputs + midi_bypass;
868                 return Match (ExactMatch, 1);
869         }
870
871         /* We may be able to run more than one copy of the plugin within this insert
872            to cope with the insert having more inputs than the plugin.
873            We allow replication only for plugins with either zero or 1 inputs and outputs
874            for every valid data type.
875         */
876
877         uint32_t f             = 0;
878         bool     can_replicate = true;
879         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
880
881                 uint32_t nin = inputs.get (*t);
882
883                 // No inputs of this type
884                 if (nin == 0 && in.get(*t) == 0) {
885                         continue;
886                 }
887
888                 if (nin != 1 || outputs.get (*t) != 1) {
889                         can_replicate = false;
890                         break;
891                 }
892
893                 // Potential factor not set yet
894                 if (f == 0) {
895                         f = in.get(*t) / nin;
896                 }
897
898                 // Factor for this type does not match another type, can not replicate
899                 if (f != (in.get(*t) / nin)) {
900                         can_replicate = false;
901                         break;
902                 }
903         }
904
905         if (can_replicate) {
906                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
907                         out.set (*t, outputs.get(*t) * f);
908                 }
909                 out += midi_bypass;
910                 return Match (Replicate, f);
911         }
912
913         /* If the processor has exactly one input of a given type, and
914            the plugin has more, we can feed the single processor input
915            to some or all of the plugin inputs.  This is rather
916            special-case-y, but the 1-to-many case is by far the
917            simplest.  How do I split thy 2 processor inputs to 3
918            plugin inputs?  Let me count the ways ...
919         */
920
921         bool can_split = !_strict_io;
922         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
923
924                 bool const can_split_type = (in.get (*t) == 1 && inputs.get (*t) > 1);
925                 bool const nothing_to_do_for_type = (in.get (*t) == 0 && inputs.get (*t) == 0);
926
927                 if (!can_split_type && !nothing_to_do_for_type) {
928                         can_split = false;
929                 }
930         }
931
932         if (can_split) {
933                 out = outputs + midi_bypass;
934                 return Match (Split, 1);
935         }
936
937         /* If the plugin has more inputs than we want, we can `hide' some of them
938            by feeding them silence.
939         */
940
941         bool could_hide = false;
942         bool cannot_hide = false;
943         ChanCount hide_channels;
944
945         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
946                 if (inputs.get(*t) > in.get(*t)) {
947                         /* there is potential to hide, since the plugin has more inputs of type t than the insert */
948                         hide_channels.set (*t, inputs.get(*t) - in.get(*t));
949                         could_hide = true;
950                 } else if (inputs.get(*t) < in.get(*t)) {
951                         /* we definitely cannot hide, since the plugin has fewer inputs of type t than the insert */
952                         cannot_hide = true;
953                 }
954         }
955
956         if (could_hide && !cannot_hide) {
957                 if (_strict_io && inputs.get (DataType::AUDIO) == outputs.get (DataType::AUDIO)) {
958                         _strict_io_configured = true;
959                         outputs = inputs;
960                 } else {
961                         out = outputs + midi_bypass;
962                 }
963                 return Match (Hide, 1, hide_channels);
964         }
965
966         midi_bypass.reset();
967         return Match (Impossible, 0);
968 }
969
970 XMLNode&
971 PluginInsert::get_state ()
972 {
973         return state (true);
974 }
975
976 XMLNode&
977 PluginInsert::state (bool full)
978 {
979         XMLNode& node = Processor::state (full);
980
981         node.add_property("type", _plugins[0]->state_node_name());
982         node.add_property("unique-id", _plugins[0]->unique_id());
983         node.add_property("count", string_compose("%1", _plugins.size()));
984
985         /* remember actual i/o configuration (for later placeholder
986          * in case the plugin goes missing) */
987         node.add_child_nocopy (* _configured_in.state (X_("ConfiguredInput")));
988         node.add_child_nocopy (* _configured_out.state (X_("ConfiguredOutput")));
989
990         _plugins[0]->set_insert_id(this->id());
991         node.add_child_nocopy (_plugins[0]->get_state());
992
993         for (Controls::iterator c = controls().begin(); c != controls().end(); ++c) {
994                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl> ((*c).second);
995                 if (ac) {
996                         node.add_child_nocopy (ac->get_state());
997                 }
998         }
999
1000         return node;
1001 }
1002
1003 void
1004 PluginInsert::set_control_ids (const XMLNode& node, int version)
1005 {
1006         const XMLNodeList& nlist = node.children();
1007         XMLNodeConstIterator iter;
1008         set<Evoral::Parameter>::const_iterator p;
1009
1010         for (iter = nlist.begin(); iter != nlist.end(); ++iter) {
1011                 if ((*iter)->name() == Controllable::xml_node_name) {
1012                         const XMLProperty* prop;
1013
1014                         uint32_t p = (uint32_t)-1;
1015 #ifdef LV2_SUPPORT
1016                         if ((prop = (*iter)->property (X_("symbol"))) != 0) {
1017                                 boost::shared_ptr<LV2Plugin> lv2plugin = boost::dynamic_pointer_cast<LV2Plugin> (_plugins[0]);
1018                                 if (lv2plugin) {
1019                                         p = lv2plugin->port_index(prop->value().c_str());
1020                                 }
1021                         }
1022 #endif
1023                         if (p == (uint32_t)-1 && (prop = (*iter)->property (X_("parameter"))) != 0) {
1024                                 p = atoi (prop->value());
1025                         }
1026
1027                         if (p != (uint32_t)-1) {
1028
1029                                 /* this may create the new controllable */
1030
1031                                 boost::shared_ptr<Evoral::Control> c = control (Evoral::Parameter (PluginAutomation, 0, p));
1032
1033 #ifndef NO_PLUGIN_STATE
1034                                 if (!c) {
1035                                         continue;
1036                                 }
1037                                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl> (c);
1038                                 if (ac) {
1039                                         ac->set_state (**iter, version);
1040                                 }
1041 #endif
1042                         }
1043                 }
1044         }
1045 }
1046
1047 int
1048 PluginInsert::set_state(const XMLNode& node, int version)
1049 {
1050         XMLNodeList nlist = node.children();
1051         XMLNodeIterator niter;
1052         XMLPropertyList plist;
1053         const XMLProperty *prop;
1054         ARDOUR::PluginType type;
1055
1056         if ((prop = node.property ("type")) == 0) {
1057                 error << _("XML node describing plugin is missing the `type' field") << endmsg;
1058                 return -1;
1059         }
1060
1061         if (prop->value() == X_("ladspa") || prop->value() == X_("Ladspa")) { /* handle old school sessions */
1062                 type = ARDOUR::LADSPA;
1063         } else if (prop->value() == X_("lv2")) {
1064                 type = ARDOUR::LV2;
1065         } else if (prop->value() == X_("windows-vst")) {
1066                 type = ARDOUR::Windows_VST;
1067         } else if (prop->value() == X_("lxvst")) {
1068                 type = ARDOUR::LXVST;
1069         } else if (prop->value() == X_("audiounit")) {
1070                 type = ARDOUR::AudioUnit;
1071         } else if (prop->value() == X_("luaproc")) {
1072                 type = ARDOUR::Lua;
1073         } else {
1074                 error << string_compose (_("unknown plugin type %1 in plugin insert state"),
1075                                   prop->value())
1076                       << endmsg;
1077                 return -1;
1078         }
1079
1080         prop = node.property ("unique-id");
1081
1082         if (prop == 0) {
1083 #ifdef WINDOWS_VST_SUPPORT
1084                 /* older sessions contain VST plugins with only an "id" field.
1085                  */
1086
1087                 if (type == ARDOUR::Windows_VST) {
1088                         prop = node.property ("id");
1089                 }
1090 #endif
1091
1092 #ifdef LXVST_SUPPORT
1093                 /*There shouldn't be any older sessions with linuxVST support.. but anyway..*/
1094
1095                 if (type == ARDOUR::LXVST) {
1096                         prop = node.property ("id");
1097                 }
1098 #endif
1099                 /* recheck  */
1100
1101                 if (prop == 0) {
1102                         error << _("Plugin has no unique ID field") << endmsg;
1103                         return -1;
1104                 }
1105         }
1106
1107         boost::shared_ptr<Plugin> plugin = find_plugin (_session, prop->value(), type);
1108
1109         /* treat linux and windows VST plugins equivalent if they have the same uniqueID
1110          * allow to move sessions windows <> linux */
1111 #ifdef LXVST_SUPPORT
1112         if (plugin == 0 && type == ARDOUR::Windows_VST) {
1113                 type = ARDOUR::LXVST;
1114                 plugin = find_plugin (_session, prop->value(), type);
1115         }
1116 #endif
1117
1118 #ifdef WINDOWS_VST_SUPPORT
1119         if (plugin == 0 && type == ARDOUR::LXVST) {
1120                 type = ARDOUR::Windows_VST;
1121                 plugin = find_plugin (_session, prop->value(), type);
1122         }
1123 #endif
1124
1125         if (plugin == 0) {
1126                 error << string_compose(
1127                         _("Found a reference to a plugin (\"%1\") that is unknown.\n"
1128                           "Perhaps it was removed or moved since it was last used."),
1129                         prop->value())
1130                       << endmsg;
1131                 return -1;
1132         }
1133
1134         if (type == ARDOUR::Lua) {
1135                 XMLNode *ls = node.child (plugin->state_node_name().c_str());
1136                 // we need to load the script to set the name and parameters.
1137                 boost::shared_ptr<LuaProc> lp = boost::dynamic_pointer_cast<LuaProc>(plugin);
1138                 if (ls && lp) {
1139                         lp->set_script_from_state (*ls);
1140                 }
1141         }
1142
1143         // The name of the PluginInsert comes from the plugin, nothing else
1144         _name = plugin->get_info()->name;
1145
1146         uint32_t count = 1;
1147
1148         // Processor::set_state() will set this, but too late
1149         // for it to be available when setting up plugin
1150         // state. We can't call Processor::set_state() until
1151         // the plugins themselves are created and added.
1152
1153         set_id (node);
1154
1155         if (_plugins.empty()) {
1156                 /* if we are adding the first plugin, we will need to set
1157                    up automatable controls.
1158                 */
1159                 add_plugin (plugin);
1160                 create_automatable_parameters ();
1161                 set_control_ids (node, version);
1162         }
1163
1164         if ((prop = node.property ("count")) != 0) {
1165                 sscanf (prop->value().c_str(), "%u", &count);
1166         }
1167
1168         if (_plugins.size() != count) {
1169                 for (uint32_t n = 1; n < count; ++n) {
1170                         add_plugin (plugin_factory (plugin));
1171                 }
1172         }
1173
1174         Processor::set_state (node, version);
1175
1176         PBD::ID new_id = this->id();
1177         PBD::ID old_id = this->id();
1178
1179         if ((prop = node.property ("id")) != 0) {
1180                 old_id = prop->value ();
1181         }
1182
1183         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1184
1185                 /* find the node with the type-specific node name ("lv2", "ladspa", etc)
1186                    and set all plugins to the same state.
1187                 */
1188
1189                 if ((*niter)->name() == plugin->state_node_name()) {
1190
1191                         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1192                                 /* Plugin state can include external files which are named after the ID.
1193                                  *
1194                                  * If regenerate_xml_or_string_ids() is set, the ID will already have
1195                                  * been changed, so we need to use the old ID from the XML to load the
1196                                  * state and then update the ID.
1197                                  *
1198                                  * When copying a plugin-state, route_ui takes care of of updating the ID,
1199                                  * but we need to call set_insert_id() to clear the cached plugin-state
1200                                  * and force a change.
1201                                  */
1202                                 if (!regenerate_xml_or_string_ids ()) {
1203                                         (*i)->set_insert_id (new_id);
1204                                 } else {
1205                                         (*i)->set_insert_id (old_id);
1206                                 }
1207
1208                                 (*i)->set_state (**niter, version);
1209
1210                                 if (regenerate_xml_or_string_ids ()) {
1211                                         (*i)->set_insert_id (new_id);
1212                                 }
1213                         }
1214
1215                         break;
1216                 }
1217         }
1218
1219         if (version < 3000) {
1220
1221                 /* Only 2.X sessions need a call to set_parameter_state() - in 3.X and above
1222                    this is all handled by Automatable
1223                 */
1224
1225                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1226                         if ((*niter)->name() == "Redirect") {
1227                                 /* XXX do we need to tackle placement? i think not (pd; oct 16 2009) */
1228                                 Processor::set_state (**niter, version);
1229                                 break;
1230                         }
1231                 }
1232
1233                 set_parameter_state_2X (node, version);
1234         }
1235
1236         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1237                 if (active()) {
1238                         (*i)->activate ();
1239                 } else {
1240                         (*i)->deactivate ();
1241                 }
1242         }
1243
1244         return 0;
1245 }
1246
1247 void
1248 PluginInsert::update_id (PBD::ID id)
1249 {
1250         set_id (id.to_s());
1251         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1252                 (*i)->set_insert_id (id);
1253         }
1254 }
1255
1256 void
1257 PluginInsert::set_state_dir (const std::string& d)
1258 {
1259         // state() only saves the state of the first plugin
1260         _plugins[0]->set_state_dir (d);
1261 }
1262
1263 void
1264 PluginInsert::set_parameter_state_2X (const XMLNode& node, int version)
1265 {
1266         XMLNodeList nlist = node.children();
1267         XMLNodeIterator niter;
1268
1269         /* look for port automation node */
1270
1271         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1272
1273                 if ((*niter)->name() != port_automation_node_name) {
1274                         continue;
1275                 }
1276
1277                 XMLNodeList cnodes;
1278                 XMLProperty *cprop;
1279                 XMLNodeConstIterator iter;
1280                 XMLNode *child;
1281                 const char *port;
1282                 uint32_t port_id;
1283
1284                 cnodes = (*niter)->children ("port");
1285
1286                 for (iter = cnodes.begin(); iter != cnodes.end(); ++iter){
1287
1288                         child = *iter;
1289
1290                         if ((cprop = child->property("number")) != 0) {
1291                                 port = cprop->value().c_str();
1292                         } else {
1293                                 warning << _("PluginInsert: Auto: no ladspa port number") << endmsg;
1294                                 continue;
1295                         }
1296
1297                         sscanf (port, "%" PRIu32, &port_id);
1298
1299                         if (port_id >= _plugins[0]->parameter_count()) {
1300                                 warning << _("PluginInsert: Auto: port id out of range") << endmsg;
1301                                 continue;
1302                         }
1303
1304                         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(
1305                                         control(Evoral::Parameter(PluginAutomation, 0, port_id), true));
1306
1307                         if (c && c->alist()) {
1308                                 if (!child->children().empty()) {
1309                                         c->alist()->set_state (*child->children().front(), version);
1310
1311                                         /* In some cases 2.X saves lists with min_yval and max_yval
1312                                            being FLT_MIN and FLT_MAX respectively.  This causes problems
1313                                            in A3 because these min/max values are used to compute
1314                                            where GUI control points should be drawn.  If we see such
1315                                            values, `correct' them to the min/max of the appropriate
1316                                            parameter.
1317                                         */
1318
1319                                         float min_y = c->alist()->get_min_y ();
1320                                         float max_y = c->alist()->get_max_y ();
1321
1322                                         ParameterDescriptor desc;
1323                                         _plugins.front()->get_parameter_descriptor (port_id, desc);
1324
1325                                         if (min_y == FLT_MIN) {
1326                                                 min_y = desc.lower;
1327                                         }
1328
1329                                         if (max_y == FLT_MAX) {
1330                                                 max_y = desc.upper;
1331                                         }
1332
1333                                         c->alist()->set_yrange (min_y, max_y);
1334                                 }
1335                         } else {
1336                                 error << string_compose (_("PluginInsert: automatable control %1 not found - ignored"), port_id) << endmsg;
1337                         }
1338                 }
1339
1340                 /* done */
1341
1342                 break;
1343         }
1344 }
1345
1346
1347 string
1348 PluginInsert::describe_parameter (Evoral::Parameter param)
1349 {
1350         if (param.type() == PluginAutomation) {
1351                 return _plugins[0]->describe_parameter (param);
1352         } else if (param.type() == PluginPropertyAutomation) {
1353                 boost::shared_ptr<AutomationControl> c(automation_control(param));
1354                 if (c && !c->desc().label.empty()) {
1355                         return c->desc().label;
1356                 }
1357         }
1358         return Automatable::describe_parameter(param);
1359 }
1360
1361 ARDOUR::framecnt_t
1362 PluginInsert::signal_latency() const
1363 {
1364         if (_user_latency) {
1365                 return _user_latency;
1366         }
1367
1368         return _plugins[0]->signal_latency ();
1369 }
1370
1371 ARDOUR::PluginType
1372 PluginInsert::type ()
1373 {
1374        return plugin()->get_info()->type;
1375 }
1376
1377 PluginInsert::PluginControl::PluginControl (PluginInsert*                     p,
1378                                             const Evoral::Parameter&          param,
1379                                             const ParameterDescriptor&        desc,
1380                                             boost::shared_ptr<AutomationList> list)
1381         : AutomationControl (p->session(), param, desc, list, p->describe_parameter(param))
1382         , _plugin (p)
1383 {
1384         if (alist()) {
1385                 alist()->reset_default (desc.normal);
1386                 if (desc.toggled) {
1387                         list->set_interpolation(Evoral::ControlList::Discrete);
1388                 }
1389         }
1390
1391         if (desc.toggled) {
1392                 set_flags(Controllable::Toggle);
1393         }
1394 }
1395
1396 /** @param val `user' value */
1397 void
1398 PluginInsert::PluginControl::set_value (double user_val, PBD::Controllable::GroupControlDisposition group_override)
1399 {
1400         if (writable()) {
1401                 _set_value (user_val, group_override);
1402         }
1403 }
1404 void
1405 PluginInsert::PluginControl::set_value_unchecked (double user_val)
1406 {
1407         /* used only by automation playback */
1408         _set_value (user_val, Controllable::NoGroup);
1409 }
1410
1411 void
1412 PluginInsert::PluginControl::_set_value (double user_val, PBD::Controllable::GroupControlDisposition group_override)
1413 {
1414         /* FIXME: probably should be taking out some lock here.. */
1415
1416         for (Plugins::iterator i = _plugin->_plugins.begin(); i != _plugin->_plugins.end(); ++i) {
1417                 (*i)->set_parameter (_list->parameter().id(), user_val);
1418         }
1419
1420         boost::shared_ptr<Plugin> iasp = _plugin->_impulseAnalysisPlugin.lock();
1421         if (iasp) {
1422                 iasp->set_parameter (_list->parameter().id(), user_val);
1423         }
1424
1425         AutomationControl::set_value (user_val, group_override);
1426 }
1427
1428 void
1429 PluginInsert::PluginControl::catch_up_with_external_value (double user_val)
1430 {
1431         AutomationControl::set_value (user_val, Controllable::NoGroup);
1432 }
1433
1434 XMLNode&
1435 PluginInsert::PluginControl::get_state ()
1436 {
1437         stringstream ss;
1438
1439         XMLNode& node (AutomationControl::get_state());
1440         ss << parameter().id();
1441         node.add_property (X_("parameter"), ss.str());
1442 #ifdef LV2_SUPPORT
1443         boost::shared_ptr<LV2Plugin> lv2plugin = boost::dynamic_pointer_cast<LV2Plugin> (_plugin->_plugins[0]);
1444         if (lv2plugin) {
1445                 node.add_property (X_("symbol"), lv2plugin->port_symbol (parameter().id()));
1446         }
1447 #endif
1448
1449         return node;
1450 }
1451
1452 /** @return `user' val */
1453 double
1454 PluginInsert::PluginControl::get_value () const
1455 {
1456         boost::shared_ptr<Plugin> plugin = _plugin->plugin (0);
1457
1458         if (!plugin) {
1459                 return 0.0;
1460         }
1461
1462         return plugin->get_parameter (_list->parameter().id());
1463 }
1464
1465 PluginInsert::PluginPropertyControl::PluginPropertyControl (PluginInsert*                     p,
1466                                                             const Evoral::Parameter&          param,
1467                                                             const ParameterDescriptor&        desc,
1468                                                             boost::shared_ptr<AutomationList> list)
1469         : AutomationControl (p->session(), param, desc, list)
1470         , _plugin (p)
1471 {
1472         if (alist()) {
1473                 alist()->set_yrange (desc.lower, desc.upper);
1474                 alist()->reset_default (desc.normal);
1475         }
1476
1477         if (desc.toggled) {
1478                 set_flags(Controllable::Toggle);
1479         }
1480 }
1481
1482 void
1483 PluginInsert::PluginPropertyControl::set_value (double user_val, PBD::Controllable::GroupControlDisposition /* group_override*/)
1484 {
1485         if (writable()) {
1486                 set_value_unchecked (user_val);
1487         }
1488 }
1489
1490 void
1491 PluginInsert::PluginPropertyControl::set_value_unchecked (double user_val)
1492 {
1493         /* Old numeric set_value(), coerce to appropriate datatype if possible.
1494            This is lossy, but better than nothing until Ardour's automation system
1495            can handle various datatypes all the way down. */
1496         const Variant value(_desc.datatype, user_val);
1497         if (value.type() == Variant::NOTHING) {
1498                 error << "set_value(double) called for non-numeric property" << endmsg;
1499                 return;
1500         }
1501
1502         for (Plugins::iterator i = _plugin->_plugins.begin(); i != _plugin->_plugins.end(); ++i) {
1503                 (*i)->set_property(_list->parameter().id(), value);
1504         }
1505
1506         _value = value;
1507         AutomationControl::set_value (user_val, Controllable::NoGroup);
1508 }
1509
1510 XMLNode&
1511 PluginInsert::PluginPropertyControl::get_state ()
1512 {
1513         stringstream ss;
1514
1515         XMLNode& node (AutomationControl::get_state());
1516         ss << parameter().id();
1517         node.add_property (X_("property"), ss.str());
1518         node.remove_property (X_("value"));
1519
1520         return node;
1521 }
1522
1523 double
1524 PluginInsert::PluginPropertyControl::get_value () const
1525 {
1526         return _value.to_double();
1527 }
1528
1529 boost::shared_ptr<Plugin>
1530 PluginInsert::get_impulse_analysis_plugin()
1531 {
1532         boost::shared_ptr<Plugin> ret;
1533         if (_impulseAnalysisPlugin.expired()) {
1534                 ret = plugin_factory(_plugins[0]);
1535                 ret->configure_io (input_streams (), output_streams ());
1536                 _impulseAnalysisPlugin = ret;
1537         } else {
1538                 ret = _impulseAnalysisPlugin.lock();
1539         }
1540
1541         return ret;
1542 }
1543
1544 void
1545 PluginInsert::collect_signal_for_analysis (framecnt_t nframes)
1546 {
1547         // called from outside the audio thread, so this should be safe
1548         // only do audio as analysis is (currently) only for audio plugins
1549         _signal_analysis_inputs.ensure_buffers(  DataType::AUDIO, input_streams().n_audio(),  nframes);
1550         _signal_analysis_outputs.ensure_buffers( DataType::AUDIO, output_streams().n_audio(), nframes);
1551
1552         _signal_analysis_collected_nframes   = 0;
1553         _signal_analysis_collect_nframes_max = nframes;
1554 }
1555
1556 /** Add a plugin to our list */
1557 void
1558 PluginInsert::add_plugin (boost::shared_ptr<Plugin> plugin)
1559 {
1560         plugin->set_insert_id (this->id());
1561
1562         if (_plugins.empty()) {
1563                 /* first (and probably only) plugin instance - connect to relevant signals
1564                  */
1565
1566                 plugin->ParameterChangedExternally.connect_same_thread (*this, boost::bind (&PluginInsert::parameter_changed_externally, this, _1, _2));
1567                 plugin->StartTouch.connect_same_thread (*this, boost::bind (&PluginInsert::start_touch, this, _1));
1568                 plugin->EndTouch.connect_same_thread (*this, boost::bind (&PluginInsert::end_touch, this, _1));
1569         }
1570
1571         _plugins.push_back (plugin);
1572 }
1573
1574 void
1575 PluginInsert::realtime_handle_transport_stopped ()
1576 {
1577         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1578                 (*i)->realtime_handle_transport_stopped ();
1579         }
1580 }
1581
1582 void
1583 PluginInsert::realtime_locate ()
1584 {
1585         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1586                 (*i)->realtime_locate ();
1587         }
1588 }
1589
1590 void
1591 PluginInsert::monitoring_changed ()
1592 {
1593         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1594                 (*i)->monitoring_changed ();
1595         }
1596 }
1597
1598 void
1599 PluginInsert::start_touch (uint32_t param_id)
1600 {
1601         boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter (PluginAutomation, 0, param_id));
1602         if (ac) {
1603                 ac->start_touch (session().audible_frame());
1604         }
1605 }
1606
1607 void
1608 PluginInsert::end_touch (uint32_t param_id)
1609 {
1610         boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter (PluginAutomation, 0, param_id));
1611         if (ac) {
1612                 ac->stop_touch (true, session().audible_frame());
1613         }
1614 }