Create sidechain ports when created from template (#0007680)
[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/types_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 #include "ardour/port.h"
40
41 #ifdef LV2_SUPPORT
42 #include "ardour/lv2_plugin.h"
43 #endif
44
45 #ifdef WINDOWS_VST_SUPPORT
46 #include "ardour/windows_vst_plugin.h"
47 #endif
48
49 #ifdef LXVST_SUPPORT
50 #include "ardour/lxvst_plugin.h"
51 #endif
52
53 #ifdef MACVST_SUPPORT
54 #include "ardour/mac_vst_plugin.h"
55 #endif
56
57 #ifdef AUDIOUNIT_SUPPORT
58 #include "ardour/audio_unit.h"
59 #endif
60
61 #include "ardour/session.h"
62 #include "ardour/types.h"
63
64 #include "pbd/i18n.h"
65
66 using namespace std;
67 using namespace ARDOUR;
68 using namespace PBD;
69
70 const string PluginInsert::port_automation_node_name = "PortAutomation";
71
72 PluginInsert::PluginInsert (Session& s, boost::shared_ptr<Plugin> plug)
73         : Processor (s, (plug ? plug->name() : string ("toBeRenamed")))
74         , _sc_playback_latency (0)
75         , _sc_capture_latency (0)
76         , _plugin_signal_latency (0)
77         , _signal_analysis_collected_nframes(0)
78         , _signal_analysis_collect_nframes_max(0)
79         , _configured (false)
80         , _no_inplace (false)
81         , _strict_io (false)
82         , _custom_cfg (false)
83         , _maps_from_state (false)
84         , _latency_changed (false)
85         , _bypass_port (UINT32_MAX)
86         , _stat_reset (0)
87 {
88         /* the first is the master */
89
90         if (plug) {
91                 add_plugin (plug);
92                 create_automatable_parameters ();
93                 const ChanCount& sc (sidechain_input_pins ());
94                 if (sc.n_audio () > 0 || sc.n_midi () > 0) {
95                         add_sidechain (sc.n_audio (), sc.n_midi ());
96                 }
97         }
98 }
99
100 PluginInsert::~PluginInsert ()
101 {
102         for (CtrlOutMap::const_iterator i = _control_outputs.begin(); i != _control_outputs.end(); ++i) {
103                 boost::dynamic_pointer_cast<ReadOnlyControl>(i->second)->drop_references ();
104         }
105 }
106
107 void
108 PluginInsert::set_strict_io (bool b)
109 {
110         bool changed = _strict_io != b;
111         _strict_io = b;
112         if (changed) {
113                 PluginConfigChanged (); /* EMIT SIGNAL */
114         }
115 }
116
117 bool
118 PluginInsert::set_count (uint32_t num)
119 {
120         bool require_state = !_plugins.empty();
121
122         if (require_state && num > 1 && plugin (0)->get_info ()->type == ARDOUR::AudioUnit) {
123                 // we don't allow to replicate AUs
124                 return false;
125         }
126
127         /* this is a bad idea.... we shouldn't do this while active.
128          * only a route holding their redirect_lock should be calling this
129          */
130
131         if (num == 0) {
132                 return false;
133         } else if (num > _plugins.size()) {
134                 uint32_t diff = num - _plugins.size();
135
136                 for (uint32_t n = 0; n < diff; ++n) {
137                         boost::shared_ptr<Plugin> p = plugin_factory (_plugins[0]);
138                         add_plugin (p);
139
140                         if (require_state) {
141                                 XMLNode& state = _plugins[0]->get_state ();
142                                 p->set_state (state, Stateful::loading_state_version);
143                         }
144
145                         if (active ()) {
146                                 p->activate ();
147                         }
148                 }
149                 PluginConfigChanged (); /* EMIT SIGNAL */
150
151         } else if (num < _plugins.size()) {
152                 uint32_t diff = _plugins.size() - num;
153                 for (uint32_t n= 0; n < diff; ++n) {
154                         _plugins.pop_back();
155                 }
156                 PluginConfigChanged (); /* EMIT SIGNAL */
157         }
158
159         return true;
160 }
161
162
163 void
164 PluginInsert::set_sinks (const ChanCount& c)
165 {
166         _custom_sinks = c;
167         /* no signal, change will only be visible after re-config */
168 }
169
170 void
171 PluginInsert::set_outputs (const ChanCount& c)
172 {
173         bool changed = (_custom_out != c) && _custom_cfg;
174         _custom_out = c;
175         if (changed) {
176                 PluginConfigChanged (); /* EMIT SIGNAL */
177         }
178 }
179
180 void
181 PluginInsert::set_custom_cfg (bool b)
182 {
183         bool changed = _custom_cfg != b;
184         _custom_cfg = b;
185         if (changed) {
186                 PluginConfigChanged (); /* EMIT SIGNAL */
187         }
188 }
189
190 bool
191 PluginInsert::set_preset_out (const ChanCount& c)
192 {
193         bool changed = _preset_out != c;
194         _preset_out = c;
195         if (changed && !_custom_cfg) {
196                 PluginConfigChanged (); /* EMIT SIGNAL */
197         }
198         return changed;
199 }
200
201 bool
202 PluginInsert::add_sidechain (uint32_t n_audio, uint32_t n_midi)
203 {
204         // caller must hold process lock
205         if (_sidechain) {
206                 return false;
207         }
208         std::ostringstream n;
209         if (n_audio == 0 && n_midi == 0) {
210                 n << "TO BE RESET FROM XML";
211         } else if (owner()) {
212                 n << "SC " << owner()->name() << "/" << name() << " " << Session::next_name_id ();
213         } else {
214                 n << "tobeRenamed";
215         }
216         SideChain *sc = new SideChain (_session, n.str ());
217         _sidechain = boost::shared_ptr<SideChain> (sc);
218         _sidechain->activate ();
219         for (uint32_t n = 0; n < n_audio; ++n) {
220                 _sidechain->input()->add_port ("", owner(), DataType::AUDIO); // add a port, don't connect.
221         }
222         for (uint32_t n = 0; n < n_midi; ++n) {
223                 _sidechain->input()->add_port ("", owner(), DataType::MIDI); // add a port, don't connect.
224         }
225         PluginConfigChanged (); /* EMIT SIGNAL */
226         return true;
227 }
228
229 bool
230 PluginInsert::del_sidechain ()
231 {
232         if (!_sidechain) {
233                 return false;
234         }
235         _sidechain.reset ();
236         _sc_playback_latency = 0;
237         _sc_capture_latency = 0;
238         PluginConfigChanged (); /* EMIT SIGNAL */
239         return true;
240 }
241
242 void
243 PluginInsert::update_sidechain_name ()
244 {
245         if (!_sidechain) {
246                 return;
247         }
248
249         std::ostringstream n;
250
251         n << "SC ";
252         if (owner()) {
253                 n << owner()->name() << "/";
254         }
255
256         n << name() << " " << Session::next_name_id ();
257
258         _sidechain->set_name (n.str());
259 }
260
261 void
262 PluginInsert::control_list_automation_state_changed (Evoral::Parameter which, AutoState s)
263 {
264         if (which.type() != PluginAutomation)
265                 return;
266
267         boost::shared_ptr<AutomationControl> c
268                         = boost::dynamic_pointer_cast<AutomationControl>(control (which));
269
270         if (c && s != Off) {
271                 _plugins[0]->set_parameter (which.id(), c->list()->eval (_session.transport_sample()));
272         }
273 }
274
275 ChanCount
276 PluginInsert::output_streams() const
277 {
278         assert (_configured);
279         return _configured_out;
280 }
281
282 ChanCount
283 PluginInsert::input_streams() const
284 {
285         assert (_configured);
286         return _configured_in;
287 }
288
289 ChanCount
290 PluginInsert::internal_streams() const
291 {
292         assert (_configured);
293         return _configured_internal;
294 }
295
296 ChanCount
297 PluginInsert::internal_output_streams() const
298 {
299         assert (!_plugins.empty());
300
301         PluginInfoPtr info = _plugins.front()->get_info();
302
303         if (info->reconfigurable_io()) {
304                 ChanCount out = _plugins.front()->output_streams ();
305                 // DEBUG_TRACE (DEBUG::Processors, string_compose ("Plugin insert, reconfigur(able) output streams = %1\n", out));
306                 return out;
307         } else {
308                 ChanCount out = info->n_outputs;
309                 // DEBUG_TRACE (DEBUG::Processors, string_compose ("Plugin insert, static output streams = %1 for %2 plugins\n", out, _plugins.size()));
310                 out.set_audio (out.n_audio() * _plugins.size());
311                 out.set_midi (out.n_midi() * _plugins.size());
312                 return out;
313         }
314 }
315
316 ChanCount
317 PluginInsert::internal_input_streams() const
318 {
319         assert (!_plugins.empty());
320
321         ChanCount in;
322
323         PluginInfoPtr info = _plugins.front()->get_info();
324
325         if (info->reconfigurable_io()) {
326                 in = _plugins.front()->input_streams();
327         } else {
328                 in = info->n_inputs;
329         }
330
331         DEBUG_TRACE (DEBUG::Processors, string_compose ("Plugin insert, input streams = %1, match using %2\n", in, _match.method));
332
333         if (_match.method == Split) {
334
335                 /* we are splitting 1 processor input to multiple plugin inputs,
336                    so we have a maximum of 1 stream of each type.
337                 */
338                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
339                         if (in.get (*t) > 1) {
340                                 in.set (*t, 1);
341                         }
342                 }
343                 return in;
344
345         } else if (_match.method == Hide) {
346
347                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
348                         in.set (*t, in.get (*t) - _match.hide.get (*t));
349                 }
350                 return in;
351
352         } else {
353
354                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
355                         in.set (*t, in.get (*t) * _plugins.size ());
356                 }
357
358                 return in;
359         }
360 }
361
362 ChanCount
363 PluginInsert::natural_output_streams() const
364 {
365 #ifdef MIXBUS
366         if (is_channelstrip ()) {
367                 return ChanCount::min (_configured_out, ChanCount (DataType::AUDIO, 2));
368         }
369 #endif
370         return _plugins[0]->get_info()->n_outputs;
371 }
372
373 ChanCount
374 PluginInsert::natural_input_streams() const
375 {
376 #ifdef MIXBUS
377         if (is_channelstrip ()) {
378                 return ChanCount::min (_configured_in, ChanCount (DataType::AUDIO, 2));
379         }
380 #endif
381         return _plugins[0]->get_info()->n_inputs;
382 }
383
384 ChanCount
385 PluginInsert::sidechain_input_pins() const
386 {
387         return _cached_sidechain_pins;
388 }
389
390 bool
391 PluginInsert::has_no_inputs() const
392 {
393         return _plugins[0]->get_info()->n_inputs == ChanCount::ZERO;
394 }
395
396 bool
397 PluginInsert::has_no_audio_inputs() const
398 {
399         return _plugins[0]->get_info()->n_inputs.n_audio() == 0;
400 }
401
402 samplecnt_t
403 PluginInsert::plugin_latency () const {
404         return _plugins.front()->signal_latency ();
405 }
406
407 bool
408 PluginInsert::is_instrument() const
409 {
410         PluginInfoPtr pip = _plugins[0]->get_info();
411         return (pip->is_instrument ());
412 }
413
414 bool
415 PluginInsert::has_output_presets (ChanCount in, ChanCount out)
416 {
417         if (!_configured && _plugins[0]->get_info ()->reconfigurable_io ()) {
418                 // collect possible configurations, prefer given in/out
419                 _plugins[0]->can_support_io_configuration (in, out);
420         }
421
422         PluginOutputConfiguration ppc (_plugins[0]->possible_output ());
423
424         if (ppc.size () == 0) {
425                 return false;
426         }
427         if (!strict_io () && ppc.size () == 1) {
428                 return false;
429         }
430
431         if (strict_io () && ppc.size () == 1) {
432                 // "stereo" is currently preferred default for instruments
433                 if (ppc.find (2) != ppc.end ()) {
434                         return false;
435                 }
436         }
437
438         if (ppc.size () == 1 && ppc.find (0) != ppc.end () && !_plugins[0]->get_info ()->reconfigurable_io ()) {
439                 // some midi-sequencer (e.g. QMidiArp) or other midi-out plugin
440                 // pretending to be an "Instrument"
441                 return false;
442         }
443
444         if (!is_instrument ()) {
445                         return false;
446         }
447         return true;
448 }
449
450 void
451 PluginInsert::create_automatable_parameters ()
452 {
453         assert (!_plugins.empty());
454
455         boost::shared_ptr<Plugin> plugin = _plugins.front();
456         set<Evoral::Parameter> a = _plugins.front()->automatable ();
457
458         const uint32_t limit_automatables = Config->get_limit_n_automatables ();
459
460         for (uint32_t i = 0; i < plugin->parameter_count(); ++i) {
461                 if (!plugin->parameter_is_control (i)) {
462                         continue;
463                 }
464
465                 ParameterDescriptor desc;
466                 plugin->get_parameter_descriptor(i, desc);
467
468                 if (!plugin->parameter_is_input (i)) {
469                         _control_outputs[i] = boost::shared_ptr<ReadOnlyControl> (new ReadOnlyControl (plugin, desc, i));
470                         continue;
471                 }
472                 Evoral::Parameter param (PluginAutomation, 0, i);
473
474                 const bool automatable = a.find(param) != a.end();
475
476                 boost::shared_ptr<AutomationList> list(new AutomationList(param, desc));
477                 boost::shared_ptr<AutomationControl> c (new PluginControl(this, param, desc, list));
478                 if (!automatable || (limit_automatables > 0 && i > limit_automatables)) {
479                         c->set_flags (Controllable::Flag ((int)c->flags() | Controllable::NotAutomatable));
480                 }
481                 add_control (c);
482                 plugin->set_automation_control (i, c);
483         }
484
485
486         const Plugin::PropertyDescriptors& pdl (plugin->get_supported_properties ());
487         for (Plugin::PropertyDescriptors::const_iterator p = pdl.begin(); p != pdl.end(); ++p) {
488                 Evoral::Parameter param (PluginPropertyAutomation, 0, p->first);
489                 const ParameterDescriptor& desc = plugin->get_property_descriptor(param.id());
490                 if (desc.datatype != Variant::NOTHING) {
491                         boost::shared_ptr<AutomationList> list;
492                         if (Variant::type_is_numeric(desc.datatype)) {
493                                 list = boost::shared_ptr<AutomationList>(new AutomationList(param, desc));
494                         }
495                         boost::shared_ptr<AutomationControl> c (new PluginPropertyControl(this, param, desc, list));
496                         if (!Variant::type_is_numeric(desc.datatype)) {
497                                 c->set_flags (Controllable::Flag ((int)c->flags() | Controllable::NotAutomatable));
498                         }
499                         add_control (c);
500                 }
501         }
502
503         _bypass_port = plugin->designated_bypass_port ();
504
505         /* special case VST effSetBypass */
506         if (_bypass_port == UINT32_MAX -1) {
507                 // emulate VST Bypass
508                 Evoral::Parameter param (PluginAutomation, 0, _bypass_port);
509                 ParameterDescriptor desc;
510                 desc.label = _("Plugin Enable");
511                 desc.toggled  = true;
512                 desc.normal = 1;
513                 desc.lower  = 0;
514                 desc.upper  = 1;
515                 boost::shared_ptr<AutomationList> list(new AutomationList(param, desc));
516                 boost::shared_ptr<AutomationControl> c (new PluginControl(this, param, desc, list));
517                 add_control (c);
518         }
519
520         if (_bypass_port != UINT32_MAX) {
521                 boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter (PluginAutomation, 0, _bypass_port));
522                 if (0 == (ac->flags () & Controllable::NotAutomatable)) {
523                         ac->alist()->automation_state_changed.connect_same_thread (*this, boost::bind (&PluginInsert::bypassable_changed, this));
524                         ac->Changed.connect_same_thread (*this, boost::bind (&PluginInsert::enable_changed, this));
525                 }
526         }
527         plugin->PresetPortSetValue.connect_same_thread (*this, boost::bind (&PluginInsert::preset_load_set_value, this, _1, _2));
528 }
529
530 /** Called when something outside of this host has modified a plugin
531  * parameter. Responsible for propagating the change to two places:
532  *
533  *   1) anything listening to the Control itself
534  *   2) any replicated plugins that make up this PluginInsert.
535  *
536  * The PluginInsert is connected to the ParameterChangedExternally signal for
537  * the first (primary) plugin, and here broadcasts that change to any others.
538  *
539  * XXX We should probably drop this whole replication idea (Paul, October 2015)
540  * since it isn't used by sensible plugin APIs (AU, LV2).
541  */
542 void
543 PluginInsert::parameter_changed_externally (uint32_t which, float val)
544 {
545         boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter (PluginAutomation, 0, which));
546
547         /* First propagation: alter the underlying value of the control,
548          * without telling the plugin(s) that own/use it to set it.
549          */
550
551         if (!ac) {
552                 return;
553         }
554
555         boost::shared_ptr<PluginControl> pc = boost::dynamic_pointer_cast<PluginControl> (ac);
556
557         if (pc) {
558                 pc->catch_up_with_external_value (val);
559         }
560
561         /* Second propagation: tell all plugins except the first to
562            update the value of this parameter. For sane plugin APIs,
563            there are no other plugins, so this is a no-op in those
564            cases.
565         */
566
567         Plugins::iterator i = _plugins.begin();
568
569         /* don't set the first plugin, just all the slaves */
570
571         if (i != _plugins.end()) {
572                 ++i;
573                 for (; i != _plugins.end(); ++i) {
574                         (*i)->set_parameter (which, val);
575                 }
576         }
577 }
578
579 int
580 PluginInsert::set_block_size (pframes_t nframes)
581 {
582         int ret = 0;
583         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
584                 if ((*i)->set_block_size (nframes) != 0) {
585                         ret = -1;
586                 }
587         }
588         return ret;
589 }
590
591 void
592 PluginInsert::automation_run (samplepos_t start, pframes_t nframes)
593 {
594         // XXX does not work when rolling backwards
595         if (_loop_location && nframes > 0) {
596                 const samplepos_t loop_start = _loop_location->start ();
597                 const samplepos_t loop_end   = _loop_location->end ();
598                 const samplecnt_t looplen    = loop_end - loop_start;
599
600                 samplecnt_t remain = nframes;
601                 samplepos_t start_pos = start;
602
603                 while (remain > 0) {
604                         if (start_pos >= loop_end) {
605                                 sampleoffset_t start_off = (start_pos - loop_start) % looplen;
606                                 start_pos = loop_start + start_off;
607                         }
608                         samplecnt_t move = std::min ((samplecnt_t)nframes, loop_end - start_pos);
609
610                         Automatable::automation_run (start_pos, move);
611                         remain -= move;
612                         start_pos += move;
613                 }
614                 return;
615         }
616         Automatable::automation_run (start, nframes);
617 }
618
619 bool
620 PluginInsert::find_next_event (double now, double end, Evoral::ControlEvent& next_event, bool only_active) const
621 {
622         bool rv = Automatable::find_next_event (now, end, next_event, only_active);
623
624         if (_loop_location && now < end) {
625                 if (rv) {
626                         end = ceil (next_event.when);
627                 }
628                 const samplepos_t loop_end = _loop_location->end ();
629                 assert (now < loop_end); // due to map_loop_range ()
630                 if (end > loop_end) {
631                         next_event.when = loop_end;
632                         rv = true;
633                 }
634         }
635         return rv;
636 }
637
638 void
639 PluginInsert::activate ()
640 {
641         _timing_stats.reset ();
642         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
643                 (*i)->activate ();
644         }
645
646         Processor::activate ();
647         /* when setting state e.g ProcessorBox::paste_processor_state ()
648          * the plugin is not yet owned by a route.
649          * but no matter.  Route::add_processors() will call activate () again
650          */
651         if (!owner ()) {
652                 return;
653         }
654         if (_plugin_signal_latency != signal_latency ()) {
655                 _plugin_signal_latency = signal_latency ();
656                 latency_changed ();
657         }
658 }
659
660 void
661 PluginInsert::deactivate ()
662 {
663 #ifdef MIXBUS
664         if (is_nonbypassable ()) {
665                 return;
666         }
667 #endif
668         _timing_stats.reset ();
669         Processor::deactivate ();
670
671         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
672                 (*i)->deactivate ();
673         }
674         if (_plugin_signal_latency != signal_latency ()) {
675                 _plugin_signal_latency = signal_latency ();
676                 latency_changed ();
677         }
678 }
679
680 void
681 PluginInsert::flush ()
682 {
683         for (vector<boost::shared_ptr<Plugin> >::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
684                 (*i)->flush ();
685         }
686 }
687
688 void
689 PluginInsert::enable (bool yn)
690 {
691         if (_bypass_port == UINT32_MAX) {
692                 if (yn) {
693                         activate ();
694                 } else {
695                         deactivate ();
696                 }
697         } else {
698                 if (!_pending_active) {
699                         activate ();
700                 }
701                 boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter (PluginAutomation, 0, _bypass_port));
702                 const double val = yn ? 1.0 : 0.0;
703                 ac->set_value (val, Controllable::NoGroup);
704
705 #ifdef ALLOW_VST_BYPASS_TO_FAIL // yet unused, see also vst_plugin.cc
706                 /* special case VST.. bypass may fail */
707                 if (_bypass_port == UINT32_MAX - 1) {
708                         /* check if bypass worked */
709                         if (ac->get_value () != val) {
710                                 warning << _("PluginInsert: VST Bypass failed, falling back to host bypass.") << endmsg;
711                                 // set plugin to enabled (not-byassed)
712                                 ac->set_value (1.0, Controllable::NoGroup);
713                                 // ..and use host-provided hard-bypass
714                                 if (yn) {
715                                         activate ();
716                                 } else {
717                                         deactivate ();
718                                 }
719                                 return;
720                         }
721                 }
722 #endif
723                 ActiveChanged ();
724         }
725 }
726
727 bool
728 PluginInsert::enabled () const
729 {
730         if (_bypass_port == UINT32_MAX) {
731                 return Processor::enabled ();
732         } else {
733                 boost::shared_ptr<const AutomationControl> ac = boost::const_pointer_cast<AutomationControl> (automation_control (Evoral::Parameter (PluginAutomation, 0, _bypass_port)));
734                 return (ac->get_value () > 0 && _pending_active);
735         }
736 }
737
738 bool
739 PluginInsert::bypassable () const
740 {
741         if (_bypass_port == UINT32_MAX) {
742                 return true;
743         } else {
744                 boost::shared_ptr<const AutomationControl> ac = boost::const_pointer_cast<AutomationControl> (automation_control (Evoral::Parameter (PluginAutomation, 0, _bypass_port)));
745
746                 return !ac->automation_playback ();
747         }
748 }
749
750 void
751 PluginInsert::enable_changed ()
752 {
753         ActiveChanged ();
754 }
755
756 void
757 PluginInsert::bypassable_changed ()
758 {
759         BypassableChanged ();
760 }
761
762 bool
763 PluginInsert::write_immediate_event (size_t size, const uint8_t* buf)
764 {
765         bool rv = true;
766         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
767                 if (!(*i)->write_immediate_event (size, buf)) {
768                         rv = false;
769                 }
770         }
771         return rv;
772 }
773
774 void
775 PluginInsert::preset_load_set_value (uint32_t p, float v)
776 {
777         boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter(PluginAutomation, 0, p));
778         if (!ac) {
779                 return;
780         }
781
782         if (ac->automation_state() & Play) {
783                 return;
784         }
785
786         start_touch (p);
787         ac->set_value (v, Controllable::NoGroup);
788         end_touch (p);
789 }
790
791 void
792 PluginInsert::inplace_silence_unconnected (BufferSet& bufs, const PinMappings& out_map, samplecnt_t nframes, samplecnt_t offset) const
793 {
794         // TODO optimize: store "unconnected" in a fixed set.
795         // it only changes on reconfiguration.
796         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
797                 for (uint32_t out = 0; out < bufs.count().get (*t); ++out) {
798                         bool mapped = false;
799                         if (*t == DataType::MIDI && out == 0 && has_midi_bypass ()) {
800                                 mapped = true; // in-place Midi bypass
801                         }
802                         for (uint32_t pc = 0; pc < get_count() && !mapped; ++pc) {
803                                 PinMappings::const_iterator i = out_map.find (pc);
804                                 if (i == out_map.end ()) {
805                                         continue;
806                                 }
807                                 const ChanMapping& outmap (i->second);
808                                 for (uint32_t o = 0; o < natural_output_streams().get (*t); ++o) {
809                                         bool valid;
810                                         uint32_t idx = outmap.get (*t, o, &valid);
811                                         if (valid && idx == out) {
812                                                 mapped = true;
813                                                 break;
814                                         }
815                                 }
816                         }
817                         if (!mapped) {
818                                 bufs.get (*t, out).silence (nframes, offset);
819                         }
820                 }
821         }
822 }
823
824 void
825 PluginInsert::connect_and_run (BufferSet& bufs, samplepos_t start, samplepos_t end, double speed, pframes_t nframes, samplecnt_t offset, bool with_auto)
826 {
827         // TODO: atomically copy maps & _no_inplace
828         PinMappings in_map (_in_map);
829         PinMappings out_map (_out_map);
830         ChanMapping thru_map (_thru_map);
831         if (_mapping_changed) { // ToDo use a counters, increment until match.
832                 _no_inplace = check_inplace ();
833                 _mapping_changed = false;
834         }
835
836         if (_latency_changed) {
837                 /* delaylines are configured with the max possible latency (as reported by the plugin)
838                  * so this won't allocate memory (unless the plugin lied about its max latency)
839                  * It may still 'click' though, since the fixed delaylines are not de-clicked.
840                  * Then again plugin-latency changes are not click-free to begin with.
841                  *
842                  * This is also worst case, there is currently no concept of per-stream latency.
843                  *
844                  * e.g.  Two identical latent plugins:
845                  *   1st plugin: process left (latent), bypass right.
846                  *   2nd plugin: bypass left, process right (latent).
847                  * -> currently this yields 2 times latency of the plugin,
848                  */
849                 _latency_changed = false;
850                 _delaybuffers.set (ChanCount::max(bufs.count(), _configured_out), plugin_latency ());
851         }
852
853         if (_match.method == Split && !_no_inplace) {
854                 // TODO: also use this optimization if one source-buffer
855                 // feeds _all_ *connected* inputs.
856                 // currently this is *first* buffer to all only --
857                 // see PluginInsert::check_inplace
858                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
859                         if (_configured_internal.get (*t) == 0) {
860                                 continue;
861                         }
862                         bool valid;
863                         uint32_t first_idx = in_map[0].get (*t, 0, &valid);
864                         assert (valid && first_idx == 0); // check_inplace ensures this
865                         /* copy the first stream's buffer contents to the others */
866                         for (uint32_t i = 1; i < natural_input_streams ().get (*t); ++i) {
867                                 uint32_t idx = in_map[0].get (*t, i, &valid);
868                                 if (valid) {
869                                         assert (idx == 0);
870                                         bufs.get (*t, i).read_from (bufs.get (*t, first_idx), nframes, offset, offset);
871                                 }
872                         }
873                 }
874                 /* the copy operation produces a linear monotonic input map */
875                 in_map[0] = ChanMapping (natural_input_streams ());
876         }
877
878         bufs.set_count(ChanCount::max(bufs.count(), _configured_internal));
879         bufs.set_count(ChanCount::max(bufs.count(), _configured_out));
880
881         if (with_auto) {
882
883                 uint32_t n = 0;
884
885                 for (Controls::iterator li = controls().begin(); li != controls().end(); ++li, ++n) {
886
887                         boost::shared_ptr<AutomationControl> c
888                                 = boost::dynamic_pointer_cast<AutomationControl>(li->second);
889
890                         if (c->list() && c->automation_playback()) {
891                                 bool valid;
892
893                                 const float val = c->list()->rt_safe_eval (start, valid);
894
895                                 if (valid) {
896                                         /* This is the ONLY place where we are
897                                          *  allowed to call
898                                          *  AutomationControl::set_value_unchecked(). We
899                                          *  know that the control is in
900                                          *  automation playback mode, so no
901                                          *  check on writable() is required
902                                          *  (which must be done in AutomationControl::set_value()
903                                          *
904                                          */
905                                         c->set_value_unchecked(val);
906                                 }
907
908                         }
909                 }
910         }
911
912         /* Calculate if, and how many samples we need to collect for analysis */
913         samplecnt_t collect_signal_nframes = (_signal_analysis_collect_nframes_max -
914                                              _signal_analysis_collected_nframes);
915         if (nframes < collect_signal_nframes) { // we might not get all samples now
916                 collect_signal_nframes = nframes;
917         }
918
919         if (collect_signal_nframes > 0) {
920                 // collect input
921                 //std::cerr << "collect input, bufs " << bufs.count().n_audio() << " count,  " << bufs.available().n_audio() << " available" << std::endl;
922                 //std::cerr << "               streams " << internal_input_streams().n_audio() << std::endl;
923                 //std::cerr << "filling buffer with " << collect_signal_nframes << " samples at " << _signal_analysis_collected_nframes << std::endl;
924
925                 _signal_analysis_inputs.set_count(input_streams());
926
927                 for (uint32_t i = 0; i < input_streams().n_audio(); ++i) {
928                         _signal_analysis_inputs.get_audio(i).read_from (
929                                 bufs.get_audio(i),
930                                 collect_signal_nframes,
931                                 _signal_analysis_collected_nframes); // offset is for target buffer
932                 }
933
934         }
935 #ifdef MIXBUS
936         if (is_channelstrip ()) {
937                 if (_configured_in.n_audio() > 0) {
938                         ChanMapping mb_in_map (ChanCount::min (_configured_in, ChanCount (DataType::AUDIO, 2)));
939                         ChanMapping mb_out_map (ChanCount::min (_configured_out, ChanCount (DataType::AUDIO, 2)));
940
941                         _plugins.front()->connect_and_run (bufs, start, end, speed, mb_in_map, mb_out_map, nframes, offset);
942
943                         for (uint32_t out = _configured_in.n_audio (); out < bufs.count().get (DataType::AUDIO); ++out) {
944                                 bufs.get (DataType::AUDIO, out).silence (nframes, offset);
945                         }
946                 }
947         } else
948 #endif
949         if (_no_inplace) {
950                 // TODO optimize -- build maps once.
951                 uint32_t pc = 0;
952                 BufferSet& inplace_bufs  = _session.get_noinplace_buffers();
953                 ARDOUR::ChanMapping used_outputs;
954
955                 assert (inplace_bufs.count () >= natural_input_streams () + _configured_out);
956
957                 /* build used-output map */
958                 for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i, ++pc) {
959                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
960                                 for (uint32_t out = 0; out < natural_output_streams().get (*t); ++out) {
961                                         bool valid;
962                                         uint32_t out_idx = out_map[pc].get (*t, out, &valid);
963                                         if (valid) {
964                                                 used_outputs.set (*t, out_idx, 1); // mark as used
965                                         }
966                                 }
967                         }
968                 }
969                 /* copy thru data to outputs before processing in-place */
970                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
971                         for (uint32_t out = 0; out < bufs.count().get (*t); ++out) {
972                                 bool valid;
973                                 uint32_t in_idx = thru_map.get (*t, out, &valid);
974                                 uint32_t m = out + natural_input_streams ().get (*t);
975                                 if (valid) {
976                                         _delaybuffers.delay (*t, out, inplace_bufs.get (*t, m), bufs.get (*t, in_idx), nframes, offset, offset);
977                                         used_outputs.set (*t, out, 1); // mark as used
978                                 } else {
979                                         used_outputs.get (*t, out, &valid);
980                                         if (valid) {
981                                                 /* the plugin is expected to write here, but may not :(
982                                                  * (e.g. drumgizmo w/o kit loaded)
983                                                  */
984                                                 inplace_bufs.get (*t, m).silence (nframes);
985                                         }
986                                 }
987                         }
988                 }
989
990                 pc = 0;
991                 for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i, ++pc) {
992
993                         ARDOUR::ChanMapping i_in_map (natural_input_streams());
994                         ARDOUR::ChanMapping i_out_map (out_map[pc]);
995                         ARDOUR::ChanCount mapped;
996
997                         /* map inputs sequentially */
998                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
999                                 for (uint32_t in = 0; in < natural_input_streams().get (*t); ++in) {
1000                                         bool valid;
1001                                         uint32_t in_idx = in_map[pc].get (*t, in, &valid);
1002                                         uint32_t m = mapped.get (*t);
1003                                         if (valid) {
1004                                                 inplace_bufs.get (*t, m).read_from (bufs.get (*t, in_idx), nframes, offset, offset);
1005                                         } else {
1006                                                 inplace_bufs.get (*t, m).silence (nframes, offset);
1007                                         }
1008                                         mapped.set (*t, m + 1);
1009                                 }
1010                         }
1011
1012                         /* outputs are mapped to inplace_bufs after the inputs */
1013                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1014                                 i_out_map.offset_to (*t, natural_input_streams ().get (*t));
1015                         }
1016
1017                         if ((*i)->connect_and_run (inplace_bufs, start, end, speed, i_in_map, i_out_map, nframes, offset)) {
1018                                 deactivate ();
1019                         }
1020                 }
1021
1022                 /* all instances have completed, now copy data that was written
1023                  * and zero unconnected buffers */
1024                 ARDOUR::ChanMapping nonzero_out (used_outputs);
1025                 if (has_midi_bypass ()) {
1026                         nonzero_out.set (DataType::MIDI, 0, 1); // Midi bypass.
1027                 }
1028                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1029                         for (uint32_t out = 0; out < bufs.count().get (*t); ++out) {
1030                                 bool valid;
1031                                 used_outputs.get (*t, out, &valid);
1032                                 if (!valid) {
1033                                         nonzero_out.get (*t, out, &valid);
1034                                         if (!valid) {
1035                                                 bufs.get (*t, out).silence (nframes, offset);
1036                                         }
1037                                 } else {
1038                                         uint32_t m = out + natural_input_streams ().get (*t);
1039                                         bufs.get (*t, out).read_from (inplace_bufs.get (*t, m), nframes, offset, offset);
1040                                 }
1041                         }
1042                 }
1043         } else {
1044                 /* in-place processing */
1045                 uint32_t pc = 0;
1046                 for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i, ++pc) {
1047                         if ((*i)->connect_and_run(bufs, start, end, speed, in_map[pc], out_map[pc], nframes, offset)) {
1048                                 deactivate ();
1049                         }
1050                 }
1051                 // now silence unconnected outputs
1052                 inplace_silence_unconnected (bufs, _out_map, nframes, offset);
1053         }
1054
1055         if (collect_signal_nframes > 0) {
1056                 // collect output
1057                 //std::cerr << "       output, bufs " << bufs.count().n_audio() << " count,  " << bufs.available().n_audio() << " available" << std::endl;
1058                 //std::cerr << "               streams " << internal_output_streams().n_audio() << std::endl;
1059
1060                 _signal_analysis_outputs.set_count(output_streams());
1061
1062                 for (uint32_t i = 0; i < output_streams().n_audio(); ++i) {
1063                         _signal_analysis_outputs.get_audio(i).read_from(
1064                                 bufs.get_audio(i),
1065                                 collect_signal_nframes,
1066                                 _signal_analysis_collected_nframes); // offset is for target buffer
1067                 }
1068
1069                 _signal_analysis_collected_nframes += collect_signal_nframes;
1070                 assert(_signal_analysis_collected_nframes <= _signal_analysis_collect_nframes_max);
1071
1072                 if (_signal_analysis_collected_nframes == _signal_analysis_collect_nframes_max) {
1073                         _signal_analysis_collect_nframes_max = 0;
1074                         _signal_analysis_collected_nframes   = 0;
1075
1076                         AnalysisDataGathered(&_signal_analysis_inputs,
1077                                              &_signal_analysis_outputs);
1078                 }
1079         }
1080
1081         if (_plugin_signal_latency != signal_latency ()) {
1082                 _plugin_signal_latency = signal_latency ();
1083                 latency_changed ();
1084         }
1085 }
1086
1087 void
1088 PluginInsert::bypass (BufferSet& bufs, pframes_t nframes)
1089 {
1090         /* bypass the plugin(s) not the whole processor.
1091          * -> use mappings just like connect_and_run
1092          */
1093
1094         // TODO: atomically copy maps & _no_inplace
1095         const ChanMapping in_map (no_sc_input_map ());
1096         const ChanMapping out_map (output_map ());
1097         if (_mapping_changed) {
1098                 _no_inplace = check_inplace ();
1099                 _mapping_changed = false;
1100         }
1101
1102         bufs.set_count(ChanCount::max(bufs.count(), _configured_internal));
1103         bufs.set_count(ChanCount::max(bufs.count(), _configured_out));
1104
1105         if (_no_inplace) {
1106                 ChanMapping thru_map (_thru_map);
1107
1108                 BufferSet& inplace_bufs  = _session.get_noinplace_buffers();
1109                 // copy all inputs
1110                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1111                         for (uint32_t in = 0; in < _configured_internal.get (*t); ++in) {
1112                                 inplace_bufs.get (*t, in).read_from (bufs.get (*t, in), nframes, 0, 0);
1113                         }
1114                 }
1115                 ARDOUR::ChanMapping used_outputs;
1116                 // copy thru
1117                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1118                         for (uint32_t out = 0; out < _configured_out.get (*t); ++out) {
1119                                 bool valid;
1120                                 uint32_t in_idx = thru_map.get (*t, out, &valid);
1121                                 if (valid) {
1122                                         bufs.get (*t, out).read_from (inplace_bufs.get (*t, in_idx), nframes, 0, 0);
1123                                         used_outputs.set (*t, out, 1); // mark as used
1124                                 }
1125                         }
1126                 }
1127                 // plugin no-op: assume every plugin has an internal identity map
1128                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1129                         for (uint32_t out = 0; out < _configured_out.get (*t); ++out) {
1130                                 bool valid;
1131                                 uint32_t src_idx = out_map.get_src (*t, out, &valid);
1132                                 if (!valid) {
1133                                         continue;
1134                                 }
1135                                 uint32_t in_idx = in_map.get (*t, src_idx, &valid);
1136                                 if (!valid) {
1137                                         continue;
1138                                 }
1139                                 bufs.get (*t, out).read_from (inplace_bufs.get (*t, in_idx), nframes, 0, 0);
1140                                 used_outputs.set (*t, out, 1); // mark as used
1141                         }
1142                 }
1143                 // now silence all unused outputs
1144                 if (has_midi_bypass ()) {
1145                         used_outputs.set (DataType::MIDI, 0, 1); // Midi bypass.
1146                 }
1147                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1148                         for (uint32_t out = 0; out < _configured_out.get (*t); ++out) {
1149                                 bool valid;
1150                                 used_outputs.get (*t, out, &valid);
1151                                 if (!valid) {
1152                                                 bufs.get (*t, out).silence (nframes, 0);
1153                                 }
1154                         }
1155                 }
1156         } else {
1157                 if (_match.method == Split) {
1158                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1159                                 if (_configured_internal.get (*t) == 0) {
1160                                         continue;
1161                                 }
1162                                 // copy/feeds _all_ *connected* inputs, copy the first buffer
1163                                 bool valid;
1164                                 uint32_t first_idx = in_map.get (*t, 0, &valid);
1165                                 assert (valid && first_idx == 0); // check_inplace ensures this
1166                                 for (uint32_t i = 1; i < natural_input_streams ().get (*t); ++i) {
1167                                         uint32_t idx = in_map.get (*t, i, &valid);
1168                                         if (valid) {
1169                                                 assert (idx == 0);
1170                                                 bufs.get (*t, i).read_from (bufs.get (*t, first_idx), nframes, 0, 0);
1171                                         }
1172                                 }
1173                         }
1174                 }
1175
1176                 // apply output map and/or monotonic but not identity i/o mappings
1177                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1178                         for (uint32_t out = 0; out < _configured_out.get (*t); ++out) {
1179                                 bool valid;
1180                                 uint32_t src_idx = out_map.get_src (*t, out, &valid);
1181                                 if (!valid) {
1182                                         bufs.get (*t, out).silence (nframes, 0);
1183                                         continue;
1184                                 }
1185                                 uint32_t in_idx = in_map.get (*t, src_idx, &valid);
1186                                 if (!valid) {
1187                                         bufs.get (*t, out).silence (nframes, 0);
1188                                         continue;
1189                                 }
1190                                 if (in_idx != src_idx) {
1191                                         bufs.get (*t, out).read_from (bufs.get (*t, in_idx), nframes, 0, 0);
1192                                 }
1193                         }
1194                 }
1195         }
1196 }
1197
1198 void
1199 PluginInsert::silence (samplecnt_t nframes, samplepos_t start_sample)
1200 {
1201         automation_run (start_sample, nframes); // evaluate automation only
1202
1203         if (!active ()) {
1204                 // XXX delaybuffers need to be offset by nframes
1205                 return;
1206         }
1207
1208         _delaybuffers.flush ();
1209
1210         ChanMapping in_map (natural_input_streams ());
1211         ChanMapping out_map (natural_output_streams ());
1212         ChanCount maxbuf = ChanCount::max (natural_input_streams (), natural_output_streams());
1213 #ifdef MIXBUS
1214         if (is_channelstrip ()) {
1215                 if (_configured_in.n_audio() > 0) {
1216                         _plugins.front()->connect_and_run (_session.get_scratch_buffers (maxbuf, true), start_sample, start_sample + nframes, 1.0, in_map, out_map, nframes, 0);
1217                 }
1218         } else
1219 #endif
1220         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1221                 (*i)->connect_and_run (_session.get_scratch_buffers (maxbuf, true), start_sample, start_sample + nframes, 1.0, in_map, out_map, nframes, 0);
1222         }
1223 }
1224
1225 void
1226 PluginInsert::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_sample, double speed, pframes_t nframes, bool)
1227 {
1228         if (_sidechain) {
1229                 // collect sidechain input for complete cycle (!)
1230                 // TODO we need delaylines here for latency compensation
1231                 _sidechain->run (bufs, start_sample, end_sample, speed, nframes, true);
1232         }
1233
1234         if (g_atomic_int_compare_and_exchange (&_stat_reset, 1, 0)) {
1235                 _timing_stats.reset ();
1236         }
1237
1238         if (_pending_active) {
1239                 _timing_stats.start ();
1240                 /* run as normal if we are active or moving from inactive to active */
1241
1242                 if (_session.transport_rolling() || _session.bounce_processing()) {
1243                         automate_and_run (bufs, start_sample, end_sample, speed, nframes);
1244                 } else {
1245                         Glib::Threads::Mutex::Lock lm (control_lock(), Glib::Threads::TRY_LOCK);
1246                         connect_and_run (bufs, start_sample, end_sample, speed, nframes, 0, lm.locked());
1247                 }
1248                 _timing_stats.update ();
1249
1250         } else {
1251                 _timing_stats.reset ();
1252                 // XXX should call ::silence() to run plugin(s) for consistent load.
1253                 // We'll need to change this anyway when bypass can be automated
1254                 bypass (bufs, nframes);
1255                 automation_run (start_sample, nframes); // evaluate automation only
1256                 _delaybuffers.flush ();
1257         }
1258
1259         _active = _pending_active;
1260
1261         /* we have no idea whether the plugin generated silence or not, so mark
1262          * all buffers appropriately.
1263          */
1264 }
1265
1266 void
1267 PluginInsert::automate_and_run (BufferSet& bufs, samplepos_t start, samplepos_t end, double speed, pframes_t nframes)
1268 {
1269         Evoral::ControlEvent next_event (0, 0.0f);
1270         samplecnt_t offset = 0;
1271
1272         Glib::Threads::Mutex::Lock lm (control_lock(), Glib::Threads::TRY_LOCK);
1273
1274         if (!lm.locked()) {
1275                 connect_and_run (bufs, start, end, speed, nframes, offset, false);
1276                 return;
1277         }
1278
1279         /* map start back into loop-range, adjust end */
1280         map_loop_range (start, end);
1281
1282         if (!find_next_event (start, end, next_event) || _plugins.front()->requires_fixed_sized_buffers()) {
1283
1284                 /* no events have a time within the relevant range */
1285
1286                 connect_and_run (bufs, start, end, speed, nframes, offset, true);
1287                 return;
1288         }
1289
1290         while (nframes) {
1291
1292                 samplecnt_t cnt = min (((samplecnt_t) ceil (next_event.when) - start), (samplecnt_t) nframes);
1293
1294                 connect_and_run (bufs, start, start + cnt, speed, cnt, offset, true); // XXX (start + cnt) * speed
1295
1296                 nframes -= cnt;
1297                 offset += cnt;
1298                 start += cnt;
1299
1300                 map_loop_range (start, end);
1301
1302                 if (!find_next_event (start, end, next_event)) {
1303                         break;
1304                 }
1305         }
1306
1307         /* cleanup anything that is left to do */
1308
1309         if (nframes) {
1310                 connect_and_run (bufs, start, start + nframes, speed, nframes, offset, true);
1311         }
1312 }
1313
1314 float
1315 PluginInsert::default_parameter_value (const Evoral::Parameter& param)
1316 {
1317         if (param.type() != PluginAutomation)
1318                 return 1.0;
1319
1320         if (_plugins.empty()) {
1321                 fatal << _("programming error: ") << X_("PluginInsert::default_parameter_value() called with no plugin")
1322                       << endmsg;
1323                 abort(); /*NOTREACHED*/
1324         }
1325
1326         return _plugins[0]->default_value (param.id());
1327 }
1328
1329
1330 bool
1331 PluginInsert::can_reset_all_parameters ()
1332 {
1333         bool all = true;
1334         uint32_t params = 0;
1335         for (uint32_t par = 0; par < _plugins[0]->parameter_count(); ++par) {
1336                 bool ok=false;
1337                 const uint32_t cid = _plugins[0]->nth_parameter (par, ok);
1338
1339                 if (!ok || !_plugins[0]->parameter_is_input(cid)) {
1340                         continue;
1341                 }
1342
1343                 boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter(PluginAutomation, 0, cid));
1344                 if (!ac) {
1345                         continue;
1346                 }
1347
1348                 ++params;
1349                 if (ac->automation_state() & Play) {
1350                         all = false;
1351                         break;
1352                 }
1353         }
1354         return all && (params > 0);
1355 }
1356
1357 bool
1358 PluginInsert::reset_parameters_to_default ()
1359 {
1360         bool all = true;
1361
1362         for (uint32_t par = 0; par < _plugins[0]->parameter_count(); ++par) {
1363                 bool ok=false;
1364                 const uint32_t cid = _plugins[0]->nth_parameter (par, ok);
1365
1366                 if (!ok || !_plugins[0]->parameter_is_input(cid)) {
1367                         continue;
1368                 }
1369
1370                 const float dflt = _plugins[0]->default_value (cid);
1371                 const float curr = _plugins[0]->get_parameter (cid);
1372
1373                 if (dflt == curr) {
1374                         continue;
1375                 }
1376
1377                 boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter(PluginAutomation, 0, cid));
1378                 if (!ac) {
1379                         continue;
1380                 }
1381
1382                 if (ac->automation_state() & Play) {
1383                         all = false;
1384                         continue;
1385                 }
1386
1387                 ac->set_value (dflt, Controllable::NoGroup);
1388         }
1389         return all;
1390 }
1391
1392 boost::shared_ptr<Plugin>
1393 PluginInsert::plugin_factory (boost::shared_ptr<Plugin> other)
1394 {
1395         boost::shared_ptr<LadspaPlugin> lp;
1396         boost::shared_ptr<LuaProc> lua;
1397 #ifdef LV2_SUPPORT
1398         boost::shared_ptr<LV2Plugin> lv2p;
1399 #endif
1400 #ifdef WINDOWS_VST_SUPPORT
1401         boost::shared_ptr<WindowsVSTPlugin> vp;
1402 #endif
1403 #ifdef LXVST_SUPPORT
1404         boost::shared_ptr<LXVSTPlugin> lxvp;
1405 #endif
1406 #ifdef MACVST_SUPPORT
1407         boost::shared_ptr<MacVSTPlugin> mvp;
1408 #endif
1409 #ifdef AUDIOUNIT_SUPPORT
1410         boost::shared_ptr<AUPlugin> ap;
1411 #endif
1412
1413         if ((lp = boost::dynamic_pointer_cast<LadspaPlugin> (other)) != 0) {
1414                 return boost::shared_ptr<Plugin> (new LadspaPlugin (*lp));
1415         } else if ((lua = boost::dynamic_pointer_cast<LuaProc> (other)) != 0) {
1416                 return boost::shared_ptr<Plugin> (new LuaProc (*lua));
1417 #ifdef LV2_SUPPORT
1418         } else if ((lv2p = boost::dynamic_pointer_cast<LV2Plugin> (other)) != 0) {
1419                 return boost::shared_ptr<Plugin> (new LV2Plugin (*lv2p));
1420 #endif
1421 #ifdef WINDOWS_VST_SUPPORT
1422         } else if ((vp = boost::dynamic_pointer_cast<WindowsVSTPlugin> (other)) != 0) {
1423                 return boost::shared_ptr<Plugin> (new WindowsVSTPlugin (*vp));
1424 #endif
1425 #ifdef LXVST_SUPPORT
1426         } else if ((lxvp = boost::dynamic_pointer_cast<LXVSTPlugin> (other)) != 0) {
1427                 return boost::shared_ptr<Plugin> (new LXVSTPlugin (*lxvp));
1428 #endif
1429 #ifdef MACVST_SUPPORT
1430         } else if ((mvp = boost::dynamic_pointer_cast<MacVSTPlugin> (other)) != 0) {
1431                 return boost::shared_ptr<Plugin> (new MacVSTPlugin (*mvp));
1432 #endif
1433 #ifdef AUDIOUNIT_SUPPORT
1434         } else if ((ap = boost::dynamic_pointer_cast<AUPlugin> (other)) != 0) {
1435                 return boost::shared_ptr<Plugin> (new AUPlugin (*ap));
1436 #endif
1437         }
1438
1439         fatal << string_compose (_("programming error: %1"),
1440                           X_("unknown plugin type in PluginInsert::plugin_factory"))
1441               << endmsg;
1442         abort(); /*NOTREACHED*/
1443         return boost::shared_ptr<Plugin> ((Plugin*) 0);
1444 }
1445
1446 void
1447 PluginInsert::set_input_map (uint32_t num, ChanMapping m) {
1448         if (num < _in_map.size()) {
1449                 bool changed = _in_map[num] != m;
1450                 _in_map[num] = m;
1451                 changed |= sanitize_maps ();
1452                 if (changed) {
1453                         PluginMapChanged (); /* EMIT SIGNAL */
1454                         _mapping_changed = true;
1455                         _session.set_dirty();
1456                 }
1457         }
1458 }
1459
1460 void
1461 PluginInsert::set_output_map (uint32_t num, ChanMapping m) {
1462         if (num < _out_map.size()) {
1463                 bool changed = _out_map[num] != m;
1464                 _out_map[num] = m;
1465                 changed |= sanitize_maps ();
1466                 if (changed) {
1467                         PluginMapChanged (); /* EMIT SIGNAL */
1468                         _mapping_changed = true;
1469                         _session.set_dirty();
1470                 }
1471         }
1472 }
1473
1474 void
1475 PluginInsert::set_thru_map (ChanMapping m) {
1476         bool changed = _thru_map != m;
1477         _thru_map = m;
1478         changed |= sanitize_maps ();
1479         if (changed) {
1480                 PluginMapChanged (); /* EMIT SIGNAL */
1481                 _mapping_changed = true;
1482                 _session.set_dirty();
1483         }
1484 }
1485
1486 bool
1487 PluginInsert::pre_seed (const ChanCount& in, const ChanCount& out,
1488                 const ChanMapping& im, const ChanMapping& om, const ChanMapping& tm)
1489 {
1490         if (_configured) { return false; }
1491         _configured_in = in;
1492         _configured_out = out;
1493         _in_map[0] = im;
1494         _out_map[0] = om;
1495         _thru_map = tm;
1496         _maps_from_state = in.n_total () > 0 && out.n_total () > 0;
1497         return true;
1498 }
1499
1500 ChanMapping
1501 PluginInsert::input_map () const
1502 {
1503         ChanMapping rv;
1504         uint32_t pc = 0;
1505         for (PinMappings::const_iterator i = _in_map.begin (); i != _in_map.end (); ++i, ++pc) {
1506                 ChanMapping m (i->second);
1507                 const ChanMapping::Mappings& mp ((*i).second.mappings());
1508                 for (ChanMapping::Mappings::const_iterator tm = mp.begin(); tm != mp.end(); ++tm) {
1509                         for (ChanMapping::TypeMapping::const_iterator i = tm->second.begin(); i != tm->second.end(); ++i) {
1510                                 rv.set (tm->first, i->first + pc * natural_input_streams().get(tm->first), i->second);
1511                         }
1512                 }
1513         }
1514         return rv;
1515 }
1516
1517
1518 ChanMapping
1519 PluginInsert::no_sc_input_map () const
1520 {
1521         ChanMapping rv;
1522         uint32_t pc = 0;
1523         for (PinMappings::const_iterator i = _in_map.begin (); i != _in_map.end (); ++i, ++pc) {
1524                 ChanMapping m (i->second);
1525                 const ChanMapping::Mappings& mp ((*i).second.mappings());
1526                 for (ChanMapping::Mappings::const_iterator tm = mp.begin(); tm != mp.end(); ++tm) {
1527                         uint32_t ins = natural_input_streams().get(tm->first) - _cached_sidechain_pins.get(tm->first);
1528                         for (ChanMapping::TypeMapping::const_iterator i = tm->second.begin(); i != tm->second.end(); ++i) {
1529                                 if (i->first < ins) {
1530                                         rv.set (tm->first, i->first + pc * ins, i->second);
1531                                 }
1532                         }
1533                 }
1534         }
1535         return rv;
1536 }
1537
1538 ChanMapping
1539 PluginInsert::output_map () const
1540 {
1541         ChanMapping rv;
1542         uint32_t pc = 0;
1543         for (PinMappings::const_iterator i = _out_map.begin (); i != _out_map.end (); ++i, ++pc) {
1544                 ChanMapping m (i->second);
1545                 const ChanMapping::Mappings& mp ((*i).second.mappings());
1546                 for (ChanMapping::Mappings::const_iterator tm = mp.begin(); tm != mp.end(); ++tm) {
1547                         for (ChanMapping::TypeMapping::const_iterator i = tm->second.begin(); i != tm->second.end(); ++i) {
1548                                 rv.set (tm->first, i->first + pc * natural_output_streams().get(tm->first), i->second);
1549                         }
1550                 }
1551         }
1552         if (has_midi_bypass ()) {
1553                 rv.set (DataType::MIDI, 0, 0);
1554         }
1555
1556         return rv;
1557 }
1558
1559 bool
1560 PluginInsert::has_midi_bypass () const
1561 {
1562         if (_configured_in.n_midi () == 1 && _configured_out.n_midi () == 1
1563                         && natural_output_streams ().n_midi () == 0) {
1564                 return true;
1565         }
1566         return false;
1567 }
1568
1569 bool
1570 PluginInsert::has_midi_thru () const
1571 {
1572         if (_configured_in.n_midi () == 1 && _configured_out.n_midi () == 1
1573                         && natural_input_streams ().n_midi () == 0 && natural_output_streams ().n_midi () == 0) {
1574                 return true;
1575         }
1576         return false;
1577 }
1578
1579 #ifdef MIXBUS
1580 bool
1581 PluginInsert::is_channelstrip () const {
1582         return _plugins.front()->is_channelstrip();
1583 }
1584 bool
1585 PluginInsert::is_nonbypassable () const {
1586         return _plugins.front()->is_nonbypassable ();
1587 }
1588 #endif
1589
1590 bool
1591 PluginInsert::check_inplace ()
1592 {
1593         bool inplace_ok = !_plugins.front()->inplace_broken ();
1594
1595         if (_thru_map.n_total () > 0) {
1596                 // TODO once midi-bypass is part of the mapping, ignore it
1597                 inplace_ok = false;
1598         }
1599
1600         if (_match.method == Split && inplace_ok) {
1601                 assert (get_count() == 1);
1602                 assert (_in_map.size () == 1);
1603                 if (!_out_map[0].is_monotonic ()) {
1604                         inplace_ok = false;
1605                 }
1606                 if (_configured_internal != _configured_in) {
1607                         /* no sidechain -- TODO we could allow this with
1608                          * some more logic in PluginInsert::connect_and_run().
1609                          *
1610                          * PluginInsert::reset_map() already maps it.
1611                          */
1612                         inplace_ok = false;
1613                 }
1614                 /* check mapping */
1615                 for (DataType::iterator t = DataType::begin(); t != DataType::end() && inplace_ok; ++t) {
1616                         if (_configured_internal.get (*t) == 0) {
1617                                 continue;
1618                         }
1619                         bool valid;
1620                         uint32_t first_idx = _in_map[0].get (*t, 0, &valid);
1621                         if (!valid || first_idx != 0) {
1622                                 // so far only allow to copy the *first* stream's buffer to others
1623                                 inplace_ok = false;
1624                         } else {
1625                                 for (uint32_t i = 1; i < natural_input_streams ().get (*t); ++i) {
1626                                         uint32_t idx = _in_map[0].get (*t, i, &valid);
1627                                         if (valid && idx != first_idx) {
1628                                                 inplace_ok = false;
1629                                                 break;
1630                                         }
1631                                 }
1632                         }
1633                 }
1634
1635                 if (inplace_ok) {
1636                         DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: In Place Split Map\n", name()));
1637                         return false;
1638                 }
1639         }
1640
1641         for (uint32_t pc = 0; pc < get_count() && inplace_ok ; ++pc) {
1642                 if (!_in_map[pc].is_monotonic ()) {
1643                         inplace_ok = false;
1644                 }
1645                 if (!_out_map[pc].is_monotonic ()) {
1646                         inplace_ok = false;
1647                 }
1648         }
1649
1650         if (inplace_ok) {
1651                 /* check if every output is fed by the corresponding input
1652                  *
1653                  * this prevents  in-port 1 -> sink-pin 2  ||  source-pin 1 -> out port 1, source-pin 2 -> out port 2
1654                  * (with in-place,  source-pin 1 -> out port 1 overwrites in-port 1)
1655                  *
1656                  * but allows     in-port 1 -> sink-pin 2  ||  source-pin 2 -> out port 1
1657                  */
1658                 ChanMapping in_map (input_map ());
1659                 const ChanMapping::Mappings out_m (output_map ().mappings ());
1660                 for (ChanMapping::Mappings::const_iterator t = out_m.begin (); t != out_m.end () && inplace_ok; ++t) {
1661                         for (ChanMapping::TypeMapping::const_iterator c = (*t).second.begin (); c != (*t).second.end () ; ++c) {
1662                                 /* src-pin: c->first, out-port: c->second */
1663                                 bool valid;
1664                                 uint32_t in_port = in_map.get (t->first, c->first, &valid);
1665                                 if (valid && in_port != c->second) {
1666                                         inplace_ok = false;
1667                                         break;
1668                                 }
1669                         }
1670                 }
1671         }
1672
1673         DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: %2\n", name(), inplace_ok ? "In-Place" : "No Inplace Processing"));
1674         return !inplace_ok; // no-inplace
1675 }
1676
1677 bool
1678 PluginInsert::sanitize_maps ()
1679 {
1680         bool changed = false;
1681         /* strip dead wood */
1682         PinMappings new_ins;
1683         PinMappings new_outs;
1684         ChanMapping new_thru;
1685
1686         for (uint32_t pc = 0; pc < get_count(); ++pc) {
1687                 ChanMapping new_in;
1688                 ChanMapping new_out;
1689                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1690                         for (uint32_t i = 0; i < natural_input_streams().get (*t); ++i) {
1691                                 bool valid;
1692                                 uint32_t idx = _in_map[pc].get (*t, i, &valid);
1693                                 if (valid && idx < _configured_internal.get (*t)) {
1694                                         new_in.set (*t, i, idx);
1695                                 }
1696                         }
1697                         for (uint32_t o = 0; o < natural_output_streams().get (*t); ++o) {
1698                                 bool valid;
1699                                 uint32_t idx = _out_map[pc].get (*t, o, &valid);
1700                                 if (valid && idx < _configured_out.get (*t)) {
1701                                         new_out.set (*t, o, idx);
1702                                 }
1703                         }
1704                 }
1705                 if (_in_map[pc] != new_in || _out_map[pc] != new_out) {
1706                         changed = true;
1707                 }
1708                 new_ins[pc] = new_in;
1709                 new_outs[pc] = new_out;
1710         }
1711
1712         /* prevent dup output assignments */
1713         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1714                 for (uint32_t o = 0; o < _configured_out.get (*t); ++o) {
1715                         bool mapped = false;
1716                         for (uint32_t pc = 0; pc < get_count(); ++pc) {
1717                                 bool valid;
1718                                 uint32_t idx = new_outs[pc].get_src (*t, o, &valid);
1719                                 if (valid && mapped) {
1720                                         new_outs[pc].unset (*t, idx);
1721                                 } else if (valid) {
1722                                         mapped = true;
1723                                 }
1724                         }
1725                 }
1726         }
1727
1728         /* remove excess thru */
1729         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1730                 for (uint32_t o = 0; o < _configured_out.get (*t); ++o) {
1731                         bool valid;
1732                         uint32_t idx = _thru_map.get (*t, o, &valid);
1733                         if (valid && idx < _configured_internal.get (*t)) {
1734                                 new_thru.set (*t, o, idx);
1735                         }
1736                 }
1737         }
1738
1739         /* prevent out + thru,  existing plugin outputs override thru */
1740         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1741                 for (uint32_t o = 0; o < _configured_out.get (*t); ++o) {
1742                         bool mapped = false;
1743                         bool valid;
1744                         for (uint32_t pc = 0; pc < get_count(); ++pc) {
1745                                 new_outs[pc].get_src (*t, o, &mapped);
1746                                 if (mapped) { break; }
1747                         }
1748                         if (!mapped) { continue; }
1749                         uint32_t idx = new_thru.get (*t, o, &valid);
1750                         if (mapped) {
1751                                 new_thru.unset (*t, idx);
1752                         }
1753                 }
1754         }
1755
1756         if (has_midi_bypass ()) {
1757                 // TODO: include midi-bypass in the thru set,
1758                 // remove dedicated handling.
1759                 new_thru.unset (DataType::MIDI, 0);
1760         }
1761
1762         if (_in_map != new_ins || _out_map != new_outs || _thru_map != new_thru) {
1763                 changed = true;
1764         }
1765         _in_map = new_ins;
1766         _out_map = new_outs;
1767         _thru_map = new_thru;
1768
1769         return changed;
1770 }
1771
1772 bool
1773 PluginInsert::reset_map (bool emit)
1774 {
1775         const PinMappings old_in (_in_map);
1776         const PinMappings old_out (_out_map);
1777
1778         _in_map.clear ();
1779         _out_map.clear ();
1780         _thru_map = ChanMapping ();
1781
1782         /* build input map */
1783         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1784                 uint32_t sc = 0; // side-chain round-robin (all instances)
1785                 uint32_t pc = 0;
1786                 for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i, ++pc) {
1787                         const uint32_t nis = natural_input_streams ().get(*t);
1788                         const uint32_t stride = nis - sidechain_input_pins().get (*t);
1789
1790                         /* SC inputs are last in the plugin-insert.. */
1791                         const uint32_t sc_start = _configured_in.get (*t);
1792                         const uint32_t sc_len = _configured_internal.get (*t) - sc_start;
1793                         /* ...but may not be at the end of the plugin ports.
1794                          * in case the side-chain is not the last port, shift connections back.
1795                          * and connect to side-chain
1796                          */
1797                         uint32_t shift = 0;
1798                         uint32_t ic = 0; // split inputs
1799                         const uint32_t cend = _configured_in.get (*t);
1800
1801                         for (uint32_t in = 0; in < nis; ++in) {
1802                                 const Plugin::IOPortDescription& iod (_plugins[pc]->describe_io_port (*t, true, in));
1803                                 if (iod.is_sidechain) {
1804                                         /* connect sidechain sinks to sidechain inputs in round-robin fashion */
1805                                         if (sc_len > 0) {// side-chain may be hidden
1806                                                 _in_map[pc].set (*t, in, sc_start + sc);
1807                                                 sc = (sc + 1) % sc_len;
1808                                         }
1809                                         ++shift;
1810                                 } else {
1811                                         if (_match.method == Split) {
1812                                                 if (cend == 0) { continue; }
1813                                                 if (_strict_io && ic + stride * pc >= cend) {
1814                                                         break;
1815                                                 }
1816                                                 /* connect *no* sidechain sinks in round-robin fashion */
1817                                                 _in_map[pc].set (*t, in, ic + stride * pc);
1818                                                 if (_strict_io && (ic + 1) == cend) {
1819                                                         break;
1820                                                 }
1821                                                 ic = (ic + 1) % cend;
1822                                         } else {
1823                                                 uint32_t s = in - shift;
1824                                                 if (stride * pc + s < cend) {
1825                                                         _in_map[pc].set (*t, in, s + stride * pc);
1826                                                 }
1827                                         }
1828                                 }
1829                         }
1830                 }
1831         }
1832
1833         /* build output map */
1834         uint32_t pc = 0;
1835         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i, ++pc) {
1836                 _out_map[pc] = ChanMapping (ChanCount::min (natural_output_streams(), _configured_out));
1837                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1838                         _out_map[pc].offset_to(*t, pc * natural_output_streams().get(*t));
1839                 }
1840         }
1841
1842         sanitize_maps ();
1843         if (old_in == _in_map && old_out == _out_map) {
1844                 return false;
1845         }
1846         if (emit) {
1847                 PluginMapChanged (); /* EMIT SIGNAL */
1848                 _mapping_changed = true;
1849                 _session.set_dirty();
1850         }
1851         return true;
1852 }
1853
1854 bool
1855 PluginInsert::configure_io (ChanCount in, ChanCount out)
1856 {
1857         Match old_match = _match;
1858         ChanCount old_in;
1859         ChanCount old_internal;
1860         ChanCount old_out;
1861         ChanCount old_pins;
1862
1863         old_pins = natural_input_streams();
1864         old_in = _configured_in;
1865         old_out = _configured_out;
1866         old_internal = _configured_internal;
1867
1868         _configured_in = in;
1869         _configured_internal = in;
1870         _configured_out = out;
1871
1872         if (_sidechain) {
1873                 /* TODO hide midi-bypass, and custom outs. Best /fake/ "out" here.
1874                  * (currently _sidechain->configure_io always succeeds
1875                  *  since Processor::configure_io() succeeds)
1876                  */
1877                 if (!_sidechain->configure_io (in, out)) {
1878                         DEBUG_TRACE (DEBUG::ChanMapping, "Sidechain configuration failed\n");
1879                         return false;
1880                 }
1881                 _configured_internal += _sidechain->input()->n_ports();
1882
1883                 // include (static_cast<Route*>owner())->name() ??
1884                 _sidechain->input ()-> set_pretty_name (string_compose (_("SC %1"), name ()));
1885         }
1886
1887         /* get plugin configuration */
1888         _match = private_can_support_io_configuration (in, out);
1889 #ifndef NDEBUG
1890         if (DEBUG_ENABLED(DEBUG::ChanMapping)) {
1891                 DEBUG_STR_DECL(a);
1892                 DEBUG_STR_APPEND(a, string_compose ("%1: ",  name()));
1893                 DEBUG_STR_APPEND(a, _match);
1894                 DEBUG_TRACE (DEBUG::ChanMapping, DEBUG_STR(a).str());
1895         }
1896 #endif
1897
1898         /* set the matching method and number of plugins that we will use to meet this configuration */
1899         if (set_count (_match.plugins) == false) {
1900                 PluginIoReConfigure (); /* EMIT SIGNAL */
1901                 _configured = false;
1902                 return false;
1903         }
1904
1905         /* configure plugins */
1906         switch (_match.method) {
1907         case Split:
1908         case Hide:
1909                 if (_plugins.front()->configure_io (natural_input_streams(), out) == false) {
1910                         PluginIoReConfigure (); /* EMIT SIGNAL */
1911                         _configured = false;
1912                         return false;
1913                 }
1914                 break;
1915         case Delegate:
1916                 {
1917                         ChanCount din (_configured_internal);
1918                         ChanCount dout (din); // hint
1919                         if (_custom_cfg) {
1920                                 if (_custom_sinks.n_total () > 0) {
1921                                         din = _custom_sinks;
1922                                 }
1923                                 dout = _custom_out;
1924                         } else if (_preset_out.n_audio () > 0) {
1925                                 dout.set (DataType::AUDIO, _preset_out.n_audio ());
1926                         } else if (dout.n_midi () > 0 && dout.n_audio () == 0) {
1927                                 dout.set (DataType::AUDIO, 2);
1928                         }
1929                         if (out.n_audio () == 0) { out.set (DataType::AUDIO, 1); }
1930                         ChanCount useins;
1931                         DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: Delegate lookup : %2 %3\n", name(), din, dout));
1932                         bool const r = _plugins.front()->can_support_io_configuration (din, dout, &useins);
1933                         assert (r);
1934                         if (useins.n_audio() == 0) {
1935                                 useins = din;
1936                         }
1937                         DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: Delegate configuration: %2 %3\n", name(), useins, dout));
1938
1939                         if (_plugins.front()->configure_io (useins, dout) == false) {
1940                                 PluginIoReConfigure (); /* EMIT SIGNAL */
1941                                 _configured = false;
1942                                 return false;
1943                         }
1944                         if (!_custom_cfg) {
1945                                 _custom_sinks = din;
1946                         }
1947                 }
1948                 break;
1949         default:
1950                 if (_plugins.front()->configure_io (in, out) == false) {
1951                         PluginIoReConfigure (); /* EMIT SIGNAL */
1952                         _configured = false;
1953                         return false;
1954                 }
1955                 break;
1956         }
1957
1958         DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: cfg:%2 state:%3 chn-in:%4 chn-out:%5 inpin:%6 match:%7 cust:%8 size-in:%9 size-out:%10\n",
1959                                 name (),
1960                                 _configured ? "Y" : "N",
1961                                 _maps_from_state ? "Y" : "N",
1962                                 old_in == in ? "==" : "!=",
1963                                 old_out == out ? "==" : "!=",
1964                                 old_pins == natural_input_streams () ? "==" : "!=",
1965                                 old_match.method == _match.method ? "==" : "!=",
1966                                 old_match.custom_cfg == _match.custom_cfg ? "==" : "!=",
1967                                 _in_map.size() == get_count () ? "==" : "!=",
1968                                 _out_map.size() == get_count () ? "==" : "!="
1969                                 ));
1970
1971         bool mapping_changed = false;
1972         if (old_in == in && old_out == out
1973                         && _configured
1974                         && old_pins == natural_input_streams ()
1975                         && old_match.method == _match.method
1976                         && old_match.custom_cfg == _match.custom_cfg
1977                         && _in_map.size() == _out_map.size()
1978                         && _in_map.size() == get_count ()
1979                  ) {
1980                 /* If the configuration has not changed, keep the mapping */
1981                 mapping_changed = sanitize_maps ();
1982         } else if (_match.custom_cfg && _configured) {
1983                 /* don't touch the map in manual mode */
1984                 mapping_changed = sanitize_maps ();
1985         } else {
1986 #ifdef MIXBUS
1987                 if (is_channelstrip ()) {
1988                         /* fake channel map - for wire display */
1989                         _in_map.clear ();
1990                         _out_map.clear ();
1991                         _thru_map = ChanMapping ();
1992                         _in_map[0] = ChanMapping (ChanCount::min (_configured_in, ChanCount (DataType::AUDIO, 2)));
1993                         _out_map[0] = ChanMapping (ChanCount::min (_configured_out, ChanCount (DataType::AUDIO, 2)));
1994                         /* set "thru" map for in-place forward of audio */
1995                         for (uint32_t i = 2; i < _configured_in.n_audio(); ++i) {
1996                                 _thru_map.set (DataType::AUDIO, i, i);
1997                         }
1998                         /* and midi (after implicit 1st channel bypass) */
1999                         for (uint32_t i = 1; i < _configured_in.n_midi(); ++i) {
2000                                 _thru_map.set (DataType::MIDI, i, i);
2001                         }
2002                 } else
2003 #endif
2004                 if (_maps_from_state && old_in == in && old_out == out) {
2005                         mapping_changed = true;
2006                         sanitize_maps ();
2007                 } else {
2008                         /* generate a new mapping */
2009                         mapping_changed = reset_map (false);
2010                 }
2011                 _maps_from_state = false;
2012         }
2013
2014         if (mapping_changed) {
2015                 PluginMapChanged (); /* EMIT SIGNAL */
2016
2017 #ifndef NDEBUG
2018                 if (DEBUG_ENABLED(DEBUG::ChanMapping)) {
2019                         uint32_t pc = 0;
2020                         DEBUG_STR_DECL(a);
2021                         DEBUG_STR_APPEND(a, "\n--------<<--------\n");
2022                         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i, ++pc) {
2023                                 if (pc > 0) {
2024                         DEBUG_STR_APPEND(a, "----><----\n");
2025                                 }
2026                                 DEBUG_STR_APPEND(a, string_compose ("Channel Map for %1 plugin %2\n", name(), pc));
2027                                 DEBUG_STR_APPEND(a, " * Inputs:\n");
2028                                 DEBUG_STR_APPEND(a, _in_map[pc]);
2029                                 DEBUG_STR_APPEND(a, " * Outputs:\n");
2030                                 DEBUG_STR_APPEND(a, _out_map[pc]);
2031                         }
2032                         DEBUG_STR_APPEND(a, " * Thru:\n");
2033                         DEBUG_STR_APPEND(a, _thru_map);
2034                         DEBUG_STR_APPEND(a, "-------->>--------\n");
2035                         DEBUG_TRACE (DEBUG::ChanMapping, DEBUG_STR(a).str());
2036                 }
2037 #endif
2038         }
2039
2040         _no_inplace = check_inplace ();
2041         _mapping_changed = false;
2042
2043         /* only the "noinplace_buffers" thread buffers need to be this large,
2044          * this can be optimized. other buffers are fine with
2045          * ChanCount::max (natural_input_streams (), natural_output_streams())
2046          * and route.cc's max (configured_in, configured_out)
2047          *
2048          * no-inplace copies "thru" outputs (to emulate in-place) for
2049          * all outputs (to prevent overwrite) into a temporary space
2050          * which also holds input buffers (in case the plugin does process
2051          * in-place and overwrites those).
2052          *
2053          * this buffers need to be at least as
2054          *   natural_input_streams () + possible outputs.
2055          *
2056          * sidechain inputs add a constraint on the input:
2057          * configured input + sidechain (=_configured_internal)
2058          *
2059          * NB. this also satisfies
2060          * max (natural_input_streams(), natural_output_streams())
2061          * which is needed for silence runs
2062          */
2063         _required_buffers = ChanCount::max (_configured_internal,
2064                         natural_input_streams () + ChanCount::max (_configured_out, natural_output_streams () * get_count ()));
2065
2066         if (old_in != in || old_out != out || old_internal != _configured_internal
2067                         || old_pins != natural_input_streams ()
2068                         || (old_match.method != _match.method && (old_match.method == Split || _match.method == Split))
2069                  ) {
2070                 PluginIoReConfigure (); /* EMIT SIGNAL */
2071         }
2072
2073         _delaybuffers.configure (_configured_out, _plugins.front ()->max_latency ());
2074         _latency_changed = true;
2075
2076         // we don't know the analysis window size, so we must work with the
2077         // current buffer size here. each request for data fills in these
2078         // buffers and the analyser makes sure it gets enough data for the
2079         // analysis window
2080         session().ensure_buffer_set (_signal_analysis_inputs, in);
2081         _signal_analysis_inputs.set_count (in);
2082
2083         session().ensure_buffer_set (_signal_analysis_outputs, out);
2084         _signal_analysis_outputs.set_count (out);
2085
2086         // std::cerr << "set counts to i" << in.n_audio() << "/o" << out.n_audio() << std::endl;
2087
2088         _configured = true;
2089         return Processor::configure_io (in, out);
2090 }
2091
2092 /** Decide whether this PluginInsert can support a given IO configuration.
2093  *  To do this, we run through a set of possible solutions in rough order of
2094  *  preference.
2095  *
2096  *  @param in Required input channel count.
2097  *  @param out Filled in with the output channel count if we return true.
2098  *  @return true if the given IO configuration can be supported.
2099  */
2100 bool
2101 PluginInsert::can_support_io_configuration (const ChanCount& in, ChanCount& out)
2102 {
2103         if (_sidechain) {
2104                 _sidechain->can_support_io_configuration (in, out); // never fails, sets "out"
2105         }
2106         return private_can_support_io_configuration (in, out).method != Impossible;
2107 }
2108
2109 PluginInsert::Match
2110 PluginInsert::private_can_support_io_configuration (ChanCount const& in, ChanCount& out) const
2111 {
2112         if (!_custom_cfg && _preset_out.n_audio () > 0) {
2113                 // preseed hint (for variable i/o)
2114                 out.set (DataType::AUDIO, _preset_out.n_audio ());
2115         }
2116
2117         Match rv = internal_can_support_io_configuration (in, out);
2118
2119         if (!_custom_cfg && _preset_out.n_audio () > 0) {
2120                 DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: using output preset: %2\n", name(), _preset_out));
2121                 out.set (DataType::AUDIO, _preset_out.n_audio ());
2122         }
2123         return rv;
2124 }
2125
2126 /** A private version of can_support_io_configuration which returns the method
2127  *  by which the configuration can be matched, rather than just whether or not
2128  *  it can be.
2129  */
2130 PluginInsert::Match
2131 PluginInsert::internal_can_support_io_configuration (ChanCount const & inx, ChanCount& out) const
2132 {
2133         if (_plugins.empty()) {
2134                 return Match();
2135         }
2136
2137 #ifdef MIXBUS
2138         if (is_channelstrip ()) {
2139                 out = inx;
2140                 return Match (ExactMatch, 1);
2141         }
2142 #endif
2143
2144         /* if a user specified a custom cfg, so be it. */
2145         if (_custom_cfg) {
2146                 PluginInfoPtr info = _plugins.front()->get_info();
2147                 out = _custom_out;
2148                 if (info->reconfigurable_io()) {
2149                         return Match (Delegate, 1, _strict_io, true);
2150                 } else {
2151                         return Match (ExactMatch, get_count(), _strict_io, true);
2152                 }
2153         }
2154
2155         /* try automatic configuration */
2156         Match m = PluginInsert::automatic_can_support_io_configuration (inx, out);
2157
2158         PluginInfoPtr info = _plugins.front()->get_info();
2159         ChanCount inputs  = info->n_inputs;
2160         ChanCount outputs = info->n_outputs;
2161
2162         /* handle case strict-i/o */
2163         if (_strict_io && m.method != Impossible) {
2164                 m.strict_io = true;
2165
2166                 /* special case MIDI instruments */
2167                 if (is_instrument ()) {
2168                         // output = midi-bypass + at most master-out channels.
2169                         ChanCount max_out (DataType::AUDIO, 2); // TODO use master-out
2170                         max_out.set (DataType::MIDI, out.get(DataType::MIDI));
2171                         out = ChanCount::min (out, max_out);
2172                         DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: special case strict-i/o instrument\n", name()));
2173                         return m;
2174                 }
2175
2176                 switch (m.method) {
2177                         case NoInputs:
2178                                 if (inx.n_audio () != out.n_audio ()) { // ignore midi bypass
2179                                         /* replicate processor to match output count (generators and such)
2180                                          * at least enough to feed every output port. */
2181                                         uint32_t f = 1; // at least one. e.g. control data filters, no in, no out.
2182                                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2183                                                 uint32_t nout = outputs.get (*t);
2184                                                 if (nout == 0 || inx.get(*t) == 0) { continue; }
2185                                                 f = max (f, (uint32_t) ceil (inx.get(*t) / (float)nout));
2186                                         }
2187                                         out = inx;
2188                                         DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: special case strict-i/o for generator\n", name()));
2189                                         return Match (Replicate, f, _strict_io);
2190                                 }
2191                                 break;
2192                         default:
2193                                 break;
2194                 }
2195
2196                 out = inx;
2197                 return m;
2198         }
2199
2200         if (m.method != Impossible) {
2201                 return m;
2202         }
2203
2204         ChanCount ns_inputs  = inputs - sidechain_input_pins ();
2205
2206         DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: resolving 'Impossible' match...\n", name()));
2207
2208         if (info->reconfigurable_io()) {
2209                 ChanCount useins;
2210                 out = inx; // hint
2211                 if (out.n_midi () > 0 && out.n_audio () == 0) { out.set (DataType::AUDIO, 2); }
2212                 if (out.n_audio () == 0) { out.set (DataType::AUDIO, 1); }
2213                 bool const r = _plugins.front()->can_support_io_configuration (inx + sidechain_input_pins (), out, &useins);
2214                 if (!r) {
2215                         // houston, we have a problem.
2216                         return Match (Impossible, 0);
2217                 }
2218                 // midi bypass
2219                 if (inx.n_midi () > 0 && out.n_midi () == 0) { out.set (DataType::MIDI, 1); }
2220                 return Match (Delegate, 1, _strict_io);
2221         }
2222
2223         ChanCount midi_bypass;
2224         if (inx.get(DataType::MIDI) == 1 && outputs.get(DataType::MIDI) == 0) {
2225                 midi_bypass.set (DataType::MIDI, 1);
2226         }
2227
2228         // add at least as many plugins so that output count matches input count (w/o sidechain pins)
2229         uint32_t f = 0;
2230         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2231                 uint32_t nin = ns_inputs.get (*t);
2232                 uint32_t nout = outputs.get (*t);
2233                 if (nin == 0 || inx.get(*t) == 0) { continue; }
2234                 // prefer floor() so the count won't overly increase IFF (nin < nout)
2235                 f = max (f, (uint32_t) floor (inx.get(*t) / (float)nout));
2236         }
2237         if (f > 0 && outputs * f >= _configured_out) {
2238                 out = outputs * f + midi_bypass;
2239                 return Match (Replicate, f, _strict_io);
2240         }
2241
2242         // add at least as many plugins needed to connect all inputs (w/o sidechain pins)
2243         f = 0;
2244         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2245                 uint32_t nin = ns_inputs.get (*t);
2246                 if (nin == 0 || inx.get(*t) == 0) { continue; }
2247                 f = max (f, (uint32_t) ceil (inx.get(*t) / (float)nin));
2248         }
2249         if (f > 0) {
2250                 out = outputs * f + midi_bypass;
2251                 return Match (Replicate, f, _strict_io);
2252         }
2253
2254         // add at least as many plugins needed to connect all inputs
2255         f = 1;
2256         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2257                 uint32_t nin = inputs.get (*t);
2258                 if (nin == 0 || inx.get(*t) == 0) { continue; }
2259                 f = max (f, (uint32_t) ceil (inx.get(*t) / (float)nin));
2260         }
2261         out = outputs * f + midi_bypass;
2262         return Match (Replicate, f, _strict_io);
2263 }
2264
2265 /* this is the original Ardour 3/4 behavior, mainly for backwards compatibility */
2266 PluginInsert::Match
2267 PluginInsert::automatic_can_support_io_configuration (ChanCount const & inx, ChanCount& out) const
2268 {
2269         if (_plugins.empty()) {
2270                 return Match();
2271         }
2272
2273         PluginInfoPtr info = _plugins.front()->get_info();
2274         ChanCount in; in += inx;
2275         ChanCount midi_bypass;
2276
2277         if (info->reconfigurable_io()) {
2278                 /* Plugin has flexible I/O, so delegate to it
2279                  * pre-seed outputs, plugin tries closest match
2280                  */
2281                 out = in; // hint
2282                 if (out.n_midi () > 0 && out.n_audio () == 0) { out.set (DataType::AUDIO, 2); }
2283                 if (out.n_audio () == 0) { out.set (DataType::AUDIO, 1); }
2284                 bool const r = _plugins.front()->can_support_io_configuration (in + sidechain_input_pins (), out);
2285                 if (!r) {
2286                         return Match (Impossible, 0);
2287                 }
2288                 // midi bypass
2289                 if (in.n_midi () > 0 && out.n_midi () == 0) { out.set (DataType::MIDI, 1); }
2290                 return Match (Delegate, 1);
2291         }
2292
2293         ChanCount inputs  = info->n_inputs;
2294         ChanCount outputs = info->n_outputs;
2295         ChanCount ns_inputs  = inputs - sidechain_input_pins ();
2296
2297         if (in.get(DataType::MIDI) == 1 && outputs.get(DataType::MIDI) == 0) {
2298                 DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: bypassing midi-data\n", name()));
2299                 midi_bypass.set (DataType::MIDI, 1);
2300         }
2301         if (in.get(DataType::MIDI) == 1 && inputs.get(DataType::MIDI) == 0) {
2302                 DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: hiding midi-port from plugin\n", name()));
2303                 in.set(DataType::MIDI, 0);
2304         }
2305
2306         // add internally provided sidechain ports
2307         ChanCount insc = in + sidechain_input_ports ();
2308
2309         bool no_inputs = true;
2310         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2311                 if (inputs.get (*t) != 0) {
2312                         no_inputs = false;
2313                         break;
2314                 }
2315         }
2316
2317         if (no_inputs) {
2318                 /* no inputs so we can take any input configuration since we throw it away */
2319                 out = outputs + midi_bypass;
2320                 return Match (NoInputs, 1);
2321         }
2322
2323         /* Plugin inputs match requested inputs + side-chain-ports exactly */
2324         if (inputs == insc) {
2325                 out = outputs + midi_bypass;
2326                 return Match (ExactMatch, 1);
2327         }
2328
2329         /* Plugin inputs matches without side-chain-pins */
2330         if (ns_inputs == in) {
2331                 out = outputs + midi_bypass;
2332                 return Match (ExactMatch, 1);
2333         }
2334
2335         /* We may be able to run more than one copy of the plugin within this insert
2336            to cope with the insert having more inputs than the plugin.
2337            We allow replication only for plugins with either zero or 1 inputs and outputs
2338            for every valid data type.
2339         */
2340
2341         uint32_t f             = 0;
2342         bool     can_replicate = true;
2343         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2344
2345                 // ignore side-chains
2346                 uint32_t nin = ns_inputs.get (*t);
2347
2348                 // No inputs of this type
2349                 if (nin == 0 && in.get(*t) == 0) {
2350                         continue;
2351                 }
2352
2353                 if (nin != 1 || outputs.get (*t) != 1) {
2354                         can_replicate = false;
2355                         break;
2356                 }
2357
2358                 // Potential factor not set yet
2359                 if (f == 0) {
2360                         f = in.get(*t) / nin;
2361                 }
2362
2363                 // Factor for this type does not match another type, can not replicate
2364                 if (f != (in.get(*t) / nin)) {
2365                         can_replicate = false;
2366                         break;
2367                 }
2368         }
2369
2370         if (can_replicate && f > 0) {
2371                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2372                         out.set (*t, outputs.get(*t) * f);
2373                 }
2374                 out += midi_bypass;
2375                 return Match (Replicate, f);
2376         }
2377
2378         /* If the processor has exactly one input of a given type, and
2379            the plugin has more, we can feed the single processor input
2380            to some or all of the plugin inputs.  This is rather
2381            special-case-y, but the 1-to-many case is by far the
2382            simplest.  How do I split thy 2 processor inputs to 3
2383            plugin inputs?  Let me count the ways ...
2384         */
2385
2386         bool can_split = true;
2387         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2388
2389                 bool const can_split_type = (in.get (*t) == 1 && ns_inputs.get (*t) > 1);
2390                 bool const nothing_to_do_for_type = (in.get (*t) == 0 && inputs.get (*t) == 0);
2391
2392                 if (!can_split_type && !nothing_to_do_for_type) {
2393                         can_split = false;
2394                 }
2395         }
2396
2397         if (can_split) {
2398                 out = outputs + midi_bypass;
2399                 return Match (Split, 1);
2400         }
2401
2402         /* If the plugin has more inputs than we want, we can `hide' some of them
2403            by feeding them silence.
2404         */
2405
2406         bool could_hide = false;
2407         bool cannot_hide = false;
2408         ChanCount hide_channels;
2409
2410         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2411                 if (inputs.get(*t) > in.get(*t)) {
2412                         /* there is potential to hide, since the plugin has more inputs of type t than the insert */
2413                         hide_channels.set (*t, inputs.get(*t) - in.get(*t));
2414                         could_hide = true;
2415                 } else if (inputs.get(*t) < in.get(*t)) {
2416                         /* we definitely cannot hide, since the plugin has fewer inputs of type t than the insert */
2417                         cannot_hide = true;
2418                 }
2419         }
2420
2421         if (could_hide && !cannot_hide) {
2422                 out = outputs + midi_bypass;
2423                 return Match (Hide, 1, false, false, hide_channels);
2424         }
2425
2426         return Match (Impossible, 0);
2427 }
2428
2429
2430 XMLNode&
2431 PluginInsert::state ()
2432 {
2433         XMLNode& node = Processor::state ();
2434
2435         node.set_property("type", _plugins[0]->state_node_name());
2436         node.set_property("unique-id", _plugins[0]->unique_id());
2437         node.set_property("count", (uint32_t)_plugins.size());
2438
2439         /* remember actual i/o configuration (for later placeholder
2440          * in case the plugin goes missing) */
2441         node.add_child_nocopy (* _configured_in.state (X_("ConfiguredInput")));
2442         node.add_child_nocopy (* _custom_sinks.state (X_("CustomSinks")));
2443         node.add_child_nocopy (* _configured_out.state (X_("ConfiguredOutput")));
2444         node.add_child_nocopy (* _preset_out.state (X_("PresetOutput")));
2445
2446         /* save custom i/o config */
2447         node.set_property("custom", _custom_cfg);
2448         for (uint32_t pc = 0; pc < get_count(); ++pc) {
2449                 char tmp[128];
2450                 snprintf (tmp, sizeof(tmp), "InputMap-%d", pc);
2451                 node.add_child_nocopy (* _in_map[pc].state (tmp));
2452                 snprintf (tmp, sizeof(tmp), "OutputMap-%d", pc);
2453                 node.add_child_nocopy (* _out_map[pc].state (tmp));
2454         }
2455         node.add_child_nocopy (* _thru_map.state ("ThruMap"));
2456
2457         if (_sidechain) {
2458                 node.add_child_nocopy (_sidechain->get_state ());
2459         }
2460
2461         _plugins[0]->set_insert_id(this->id());
2462         node.add_child_nocopy (_plugins[0]->get_state());
2463
2464         for (Controls::iterator c = controls().begin(); c != controls().end(); ++c) {
2465                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl> ((*c).second);
2466                 if (ac) {
2467                         node.add_child_nocopy (ac->get_state());
2468                 }
2469         }
2470
2471         return node;
2472 }
2473
2474 void
2475 PluginInsert::set_control_ids (const XMLNode& node, int version)
2476 {
2477         const XMLNodeList& nlist = node.children();
2478         XMLNodeConstIterator iter;
2479         set<Evoral::Parameter>::const_iterator p;
2480
2481         for (iter = nlist.begin(); iter != nlist.end(); ++iter) {
2482                 if ((*iter)->name() == Controllable::xml_node_name) {
2483
2484                         uint32_t p = (uint32_t)-1;
2485 #ifdef LV2_SUPPORT
2486                         std::string str;
2487                         if ((*iter)->get_property (X_("symbol"), str)) {
2488                                 boost::shared_ptr<LV2Plugin> lv2plugin = boost::dynamic_pointer_cast<LV2Plugin> (_plugins[0]);
2489                                 if (lv2plugin) {
2490                                         p = lv2plugin->port_index(str.c_str());
2491                                 }
2492                         }
2493 #endif
2494                         if (p == (uint32_t)-1) {
2495                                 (*iter)->get_property (X_("parameter"), p);
2496                         }
2497
2498                         if (p != (uint32_t)-1) {
2499
2500                                 /* this may create the new controllable */
2501
2502                                 boost::shared_ptr<Evoral::Control> c = control (Evoral::Parameter (PluginAutomation, 0, p));
2503
2504 #ifndef NO_PLUGIN_STATE
2505                                 if (!c) {
2506                                         continue;
2507                                 }
2508                                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl> (c);
2509                                 if (ac) {
2510                                         ac->set_state (**iter, version);
2511                                 }
2512 #endif
2513                         }
2514                 }
2515         }
2516 }
2517
2518 int
2519 PluginInsert::set_state(const XMLNode& node, int version)
2520 {
2521         XMLNodeList nlist = node.children();
2522         XMLNodeIterator niter;
2523         XMLPropertyList plist;
2524         ARDOUR::PluginType type;
2525
2526         std::string str;
2527         if (!node.get_property ("type", str)) {
2528                 error << _("XML node describing plugin is missing the `type' field") << endmsg;
2529                 return -1;
2530         }
2531
2532         if (str == X_("ladspa") || str == X_("Ladspa")) { /* handle old school sessions */
2533                 type = ARDOUR::LADSPA;
2534         } else if (str == X_("lv2")) {
2535                 type = ARDOUR::LV2;
2536         } else if (str == X_("windows-vst")) {
2537                 type = ARDOUR::Windows_VST;
2538         } else if (str == X_("lxvst")) {
2539                 type = ARDOUR::LXVST;
2540         } else if (str == X_("mac-vst")) {
2541                 type = ARDOUR::MacVST;
2542         } else if (str == X_("audiounit")) {
2543                 type = ARDOUR::AudioUnit;
2544         } else if (str == X_("luaproc")) {
2545                 type = ARDOUR::Lua;
2546         } else {
2547                 error << string_compose (_("unknown plugin type %1 in plugin insert state"), str) << endmsg;
2548                 return -1;
2549         }
2550
2551         XMLProperty const * prop = node.property ("unique-id");
2552
2553         if (prop == 0) {
2554 #ifdef WINDOWS_VST_SUPPORT
2555                 /* older sessions contain VST plugins with only an "id" field.  */
2556                 if (type == ARDOUR::Windows_VST) {
2557                         prop = node.property ("id");
2558                 }
2559 #endif
2560
2561 #ifdef LXVST_SUPPORT
2562                 /*There shouldn't be any older sessions with linuxVST support.. but anyway..*/
2563                 if (type == ARDOUR::LXVST) {
2564                         prop = node.property ("id");
2565                 }
2566 #endif
2567
2568                 /* recheck  */
2569
2570                 if (prop == 0) {
2571                         error << _("Plugin has no unique ID field") << endmsg;
2572                         return -1;
2573                 }
2574         }
2575
2576         boost::shared_ptr<Plugin> plugin = find_plugin (_session, prop->value(), type);
2577         bool any_vst = false;
2578
2579         /* treat VST plugins equivalent if they have the same uniqueID
2580          * allow to move sessions windows <> linux */
2581 #ifdef LXVST_SUPPORT
2582         if (plugin == 0 && (type == ARDOUR::Windows_VST || type == ARDOUR::MacVST)) {
2583                 type = ARDOUR::LXVST;
2584                 plugin = find_plugin (_session, prop->value(), type);
2585                 if (plugin) { any_vst = true; }
2586         }
2587 #endif
2588
2589 #ifdef WINDOWS_VST_SUPPORT
2590         if (plugin == 0 && (type == ARDOUR::LXVST || type == ARDOUR::MacVST)) {
2591                 type = ARDOUR::Windows_VST;
2592                 plugin = find_plugin (_session, prop->value(), type);
2593                 if (plugin) { any_vst = true; }
2594         }
2595 #endif
2596
2597 #ifdef MACVST_SUPPORT
2598         if (plugin == 0 && (type == ARDOUR::Windows_VST || type == ARDOUR::LXVST)) {
2599                 type = ARDOUR::MacVST;
2600                 plugin = find_plugin (_session, prop->value(), type);
2601                 if (plugin) { any_vst = true; }
2602         }
2603 #endif
2604
2605         if (plugin == 0 && type == ARDOUR::Lua) {
2606                 /* unique ID (sha1 of script) was not found,
2607                  * load the plugin from the serialized version in the
2608                  * session-file instead.
2609                  */
2610                 boost::shared_ptr<LuaProc> lp (new LuaProc (_session.engine(), _session, ""));
2611                 XMLNode *ls = node.child (lp->state_node_name().c_str());
2612                 if (ls && lp) {
2613                         lp->set_script_from_state (*ls);
2614                         plugin = lp;
2615                 }
2616         }
2617
2618         if (plugin == 0) {
2619                 error << string_compose(
2620                         _("Found a reference to a plugin (\"%1\") that is unknown.\n"
2621                           "Perhaps it was removed or moved since it was last used."),
2622                         prop->value())
2623                       << endmsg;
2624                 return -1;
2625         }
2626
2627         // The name of the PluginInsert comes from the plugin, nothing else
2628         _name = plugin->get_info()->name;
2629
2630         uint32_t count = 1;
2631
2632         // Processor::set_state() will set this, but too late
2633         // for it to be available when setting up plugin
2634         // state. We can't call Processor::set_state() until
2635         // the plugins themselves are created and added.
2636
2637         set_id (node);
2638
2639         if (_plugins.empty()) {
2640                 /* if we are adding the first plugin, we will need to set
2641                    up automatable controls.
2642                 */
2643                 add_plugin (plugin);
2644                 create_automatable_parameters ();
2645                 set_control_ids (node, version);
2646         }
2647
2648         node.get_property ("count", count);
2649
2650         if (_plugins.size() != count) {
2651                 for (uint32_t n = 1; n < count; ++n) {
2652                         add_plugin (plugin_factory (plugin));
2653                 }
2654         }
2655
2656         Processor::set_state (node, version);
2657
2658         PBD::ID new_id = this->id();
2659         PBD::ID old_id = this->id();
2660
2661         node.get_property ("id", old_id);
2662
2663         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2664
2665                 /* find the node with the type-specific node name ("lv2", "ladspa", etc)
2666                    and set all plugins to the same state.
2667                 */
2668
2669                 if (   ((*niter)->name() == plugin->state_node_name())
2670                     || (any_vst && ((*niter)->name() == "lxvst" || (*niter)->name() == "windows-vst" || (*niter)->name() == "mac-vst"))
2671                    ) {
2672
2673                         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
2674                                 /* Plugin state can include external files which are named after the ID.
2675                                  *
2676                                  * If regenerate_xml_or_string_ids() is set, the ID will already have
2677                                  * been changed, so we need to use the old ID from the XML to load the
2678                                  * state and then update the ID.
2679                                  *
2680                                  * When copying a plugin-state, route_ui takes care of of updating the ID,
2681                                  * but we need to call set_insert_id() to clear the cached plugin-state
2682                                  * and force a change.
2683                                  */
2684                                 if (!regenerate_xml_or_string_ids ()) {
2685                                         (*i)->set_insert_id (new_id);
2686                                 } else {
2687                                         (*i)->set_insert_id (old_id);
2688                                 }
2689
2690                                 (*i)->set_state (**niter, version);
2691
2692                                 if (regenerate_xml_or_string_ids ()) {
2693                                         (*i)->set_insert_id (new_id);
2694                                 }
2695                         }
2696
2697                         /* when copying plugin state, notify UI */
2698                         for (Controls::const_iterator li = controls().begin(); li != controls().end(); ++li) {
2699                                 boost::shared_ptr<PBD::Controllable> c = boost::dynamic_pointer_cast<PBD::Controllable> (li->second);
2700                                 if (c) {
2701                                         c->Changed (false, Controllable::NoGroup); /* EMIT SIGNAL */
2702                                 }
2703                         }
2704
2705                         break;
2706                 }
2707         }
2708
2709         if (version < 3000) {
2710
2711                 /* Only 2.X sessions need a call to set_parameter_state() - in 3.X and above
2712                    this is all handled by Automatable
2713                 */
2714
2715                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2716                         if ((*niter)->name() == "Redirect") {
2717                                 /* XXX do we need to tackle placement? i think not (pd; oct 16 2009) */
2718                                 Processor::set_state (**niter, version);
2719                                 break;
2720                         }
2721                 }
2722
2723                 set_parameter_state_2X (node, version);
2724         }
2725
2726         node.get_property (X_("custom"), _custom_cfg);
2727
2728         uint32_t in_maps = 0;
2729         uint32_t out_maps = 0;
2730         XMLNodeList kids = node.children ();
2731         for (XMLNodeIterator i = kids.begin(); i != kids.end(); ++i) {
2732                 if ((*i)->name() == X_("ConfiguredInput")) {
2733                         _configured_in = ChanCount(**i);
2734                 }
2735                 if ((*i)->name() == X_("CustomSinks")) {
2736                         _custom_sinks = ChanCount(**i);
2737                 }
2738                 if ((*i)->name() == X_("ConfiguredOutput")) {
2739                         _custom_out = ChanCount(**i);
2740                         _configured_out = ChanCount(**i);
2741                 }
2742                 if ((*i)->name() == X_("PresetOutput")) {
2743                         _preset_out = ChanCount(**i);
2744                 }
2745                 if (strncmp ((*i)->name ().c_str(), X_("InputMap-"), 9) == 0) {
2746                         long pc = atol (&((*i)->name().c_str()[9]));
2747                         if (pc >= 0 && pc <= (long) get_count()) {
2748                                 _in_map[pc] = ChanMapping (**i);
2749                                 ++in_maps;
2750                         }
2751                 }
2752                 if (strncmp ((*i)->name ().c_str(), X_("OutputMap-"), 10) == 0) {
2753                         long pc = atol (&((*i)->name().c_str()[10]));
2754                         if (pc >= 0 && pc <= (long) get_count()) {
2755                                 _out_map[pc] = ChanMapping (**i);
2756                                 ++out_maps;
2757                         }
2758                 }
2759                 if ((*i)->name () ==  "ThruMap") {
2760                                 _thru_map = ChanMapping (**i);
2761                 }
2762
2763                 // sidechain is a Processor (IO)
2764                 if ((*i)->name () ==  Processor::state_node_name) {
2765                         if (!_sidechain) {
2766                                 if (regenerate_xml_or_string_ids ()) {
2767                                         add_sidechain_from_xml (**i, version);
2768                                 } else {
2769                                         add_sidechain (0);
2770                                 }
2771                         }
2772                         if (!regenerate_xml_or_string_ids ()) {
2773                                 _sidechain->set_state (**i, version);
2774                         } else {
2775                                 update_sidechain_name ();
2776                         }
2777                 }
2778         }
2779
2780         if (in_maps == out_maps && out_maps >0 && out_maps == get_count()) {
2781                 _maps_from_state = true;
2782         }
2783
2784         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
2785                 if (active()) {
2786                         (*i)->activate ();
2787                 } else {
2788                         (*i)->deactivate ();
2789                 }
2790         }
2791
2792         PluginConfigChanged (); /* EMIT SIGNAL */
2793         return 0;
2794 }
2795
2796 void
2797 PluginInsert::update_id (PBD::ID id)
2798 {
2799         set_id (id.to_s());
2800         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
2801                 (*i)->set_insert_id (id);
2802         }
2803 }
2804
2805 void
2806 PluginInsert::set_owner (SessionObject* o)
2807 {
2808         Processor::set_owner (o);
2809         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
2810                 (*i)->set_owner (o);
2811         }
2812 }
2813
2814 void
2815 PluginInsert::set_state_dir (const std::string& d)
2816 {
2817         // state() only saves the state of the first plugin
2818         _plugins[0]->set_state_dir (d);
2819 }
2820
2821 void
2822 PluginInsert::set_parameter_state_2X (const XMLNode& node, int version)
2823 {
2824         XMLNodeList nlist = node.children();
2825         XMLNodeIterator niter;
2826
2827         /* look for port automation node */
2828
2829         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2830
2831                 if ((*niter)->name() != port_automation_node_name) {
2832                         continue;
2833                 }
2834
2835                 XMLNodeList cnodes;
2836                 XMLNodeConstIterator iter;
2837                 XMLNode *child;
2838                 uint32_t port_id;
2839
2840                 cnodes = (*niter)->children ("port");
2841
2842                 for (iter = cnodes.begin(); iter != cnodes.end(); ++iter){
2843
2844                         child = *iter;
2845
2846                         if (!child->get_property("number", port_id)) {
2847                                 warning << _("PluginInsert: Auto: no ladspa port number") << endmsg;
2848                                 continue;
2849                         }
2850
2851                         if (port_id >= _plugins[0]->parameter_count()) {
2852                                 warning << _("PluginInsert: Auto: port id out of range") << endmsg;
2853                                 continue;
2854                         }
2855
2856                         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(
2857                                         control(Evoral::Parameter(PluginAutomation, 0, port_id), true));
2858
2859                         if (c && c->alist()) {
2860                                 if (!child->children().empty()) {
2861                                         c->alist()->set_state (*child->children().front(), version);
2862                                 }
2863                         } else {
2864                                 error << string_compose (_("PluginInsert: automatable control %1 not found - ignored"), port_id) << endmsg;
2865                         }
2866                 }
2867
2868                 /* done */
2869
2870                 break;
2871         }
2872 }
2873
2874 boost::shared_ptr<ReadOnlyControl>
2875 PluginInsert::control_output (uint32_t num) const
2876 {
2877         CtrlOutMap::const_iterator i = _control_outputs.find (num);
2878         if (i == _control_outputs.end ()) {
2879                 return boost::shared_ptr<ReadOnlyControl> ();
2880         } else {
2881                 return (*i).second;
2882         }
2883 }
2884
2885 string
2886 PluginInsert::describe_parameter (Evoral::Parameter param)
2887 {
2888         if (param.type() == PluginAutomation) {
2889                 return _plugins[0]->describe_parameter (param);
2890         } else if (param.type() == PluginPropertyAutomation) {
2891                 boost::shared_ptr<AutomationControl> c(automation_control(param));
2892                 if (c && !c->desc().label.empty()) {
2893                         return c->desc().label;
2894                 }
2895         }
2896         return Automatable::describe_parameter(param);
2897 }
2898
2899 ARDOUR::samplecnt_t
2900 PluginInsert::signal_latency() const
2901 {
2902         if (!_pending_active) {
2903                 return 0;
2904         }
2905         if (_user_latency) {
2906                 return _user_latency;
2907         }
2908
2909         return _plugins[0]->signal_latency ();
2910 }
2911
2912 ARDOUR::PluginType
2913 PluginInsert::type ()
2914 {
2915        return plugin()->get_info()->type;
2916 }
2917
2918 PluginInsert::PluginControl::PluginControl (PluginInsert*                     p,
2919                                             const Evoral::Parameter&          param,
2920                                             const ParameterDescriptor&        desc,
2921                                             boost::shared_ptr<AutomationList> list)
2922         : AutomationControl (p->session(), param, desc, list, p->describe_parameter(param))
2923         , _plugin (p)
2924 {
2925         if (alist()) {
2926                 if (desc.toggled) {
2927                         list->set_interpolation(Evoral::ControlList::Discrete);
2928                 }
2929         }
2930 }
2931
2932 /** @param val `user' value */
2933
2934 void
2935 PluginInsert::PluginControl::actually_set_value (double user_val, PBD::Controllable::GroupControlDisposition group_override)
2936 {
2937         /* FIXME: probably should be taking out some lock here.. */
2938
2939         for (Plugins::iterator i = _plugin->_plugins.begin(); i != _plugin->_plugins.end(); ++i) {
2940                 (*i)->set_parameter (_list->parameter().id(), user_val);
2941         }
2942
2943         boost::shared_ptr<Plugin> iasp = _plugin->_impulseAnalysisPlugin.lock();
2944         if (iasp) {
2945                 iasp->set_parameter (_list->parameter().id(), user_val);
2946         }
2947
2948         AutomationControl::actually_set_value (user_val, group_override);
2949 }
2950
2951 void
2952 PluginInsert::PluginControl::catch_up_with_external_value (double user_val)
2953 {
2954         AutomationControl::actually_set_value (user_val, Controllable::NoGroup);
2955 }
2956
2957 XMLNode&
2958 PluginInsert::PluginControl::get_state ()
2959 {
2960         XMLNode& node (AutomationControl::get_state());
2961         node.set_property (X_("parameter"), parameter().id());
2962 #ifdef LV2_SUPPORT
2963         boost::shared_ptr<LV2Plugin> lv2plugin = boost::dynamic_pointer_cast<LV2Plugin> (_plugin->_plugins[0]);
2964         if (lv2plugin) {
2965                 node.set_property (X_("symbol"), lv2plugin->port_symbol (parameter().id()));
2966         }
2967 #endif
2968
2969         return node;
2970 }
2971
2972 /** @return `user' val */
2973 double
2974 PluginInsert::PluginControl::get_value () const
2975 {
2976         boost::shared_ptr<Plugin> plugin = _plugin->plugin (0);
2977
2978         if (!plugin) {
2979                 return 0.0;
2980         }
2981
2982         return plugin->get_parameter (_list->parameter().id());
2983 }
2984
2985 PluginInsert::PluginPropertyControl::PluginPropertyControl (PluginInsert*                     p,
2986                                                             const Evoral::Parameter&          param,
2987                                                             const ParameterDescriptor&        desc,
2988                                                             boost::shared_ptr<AutomationList> list)
2989         : AutomationControl (p->session(), param, desc, list)
2990         , _plugin (p)
2991 {
2992 }
2993
2994 void
2995 PluginInsert::PluginPropertyControl::actually_set_value (double user_val, Controllable::GroupControlDisposition gcd)
2996 {
2997         /* Old numeric set_value(), coerce to appropriate datatype if possible.
2998            This is lossy, but better than nothing until Ardour's automation system
2999            can handle various datatypes all the way down. */
3000         const Variant value(_desc.datatype, user_val);
3001         if (value.type() == Variant::NOTHING) {
3002                 error << "set_value(double) called for non-numeric property" << endmsg;
3003                 return;
3004         }
3005
3006         for (Plugins::iterator i = _plugin->_plugins.begin(); i != _plugin->_plugins.end(); ++i) {
3007                 (*i)->set_property(_list->parameter().id(), value);
3008         }
3009
3010         _value = value;
3011
3012         AutomationControl::actually_set_value (user_val, gcd);
3013 }
3014
3015 XMLNode&
3016 PluginInsert::PluginPropertyControl::get_state ()
3017 {
3018         XMLNode& node (AutomationControl::get_state());
3019         node.set_property (X_("property"), parameter().id());
3020         node.remove_property (X_("value"));
3021
3022         return node;
3023 }
3024
3025 double
3026 PluginInsert::PluginPropertyControl::get_value () const
3027 {
3028         return _value.to_double();
3029 }
3030
3031 boost::shared_ptr<Plugin>
3032 PluginInsert::get_impulse_analysis_plugin()
3033 {
3034         boost::shared_ptr<Plugin> ret;
3035         if (_impulseAnalysisPlugin.expired()) {
3036                 // LV2 in particular uses various _session params
3037                 // during init() -- most notably block_size..
3038                 // not great.
3039                 ret = plugin_factory(_plugins[0]);
3040                 ChanCount out (internal_output_streams ());
3041                 if (ret->get_info ()->reconfigurable_io ()) {
3042                         // populate get_info ()->n_inputs and ->n_outputs
3043                         ChanCount useins;
3044                         ret->can_support_io_configuration (internal_input_streams (), out, &useins);
3045                         assert (out == internal_output_streams ());
3046                 }
3047                 ret->configure_io (internal_input_streams (), out);
3048                 ret->set_owner (_owner);
3049                 _impulseAnalysisPlugin = ret;
3050         } else {
3051                 ret = _impulseAnalysisPlugin.lock();
3052         }
3053
3054         return ret;
3055 }
3056
3057 void
3058 PluginInsert::collect_signal_for_analysis (samplecnt_t nframes)
3059 {
3060         // called from outside the audio thread, so this should be safe
3061         // only do audio as analysis is (currently) only for audio plugins
3062         _signal_analysis_inputs.ensure_buffers (DataType::AUDIO, input_streams().n_audio(),  nframes);
3063         _signal_analysis_outputs.ensure_buffers (DataType::AUDIO, output_streams().n_audio(), nframes);
3064
3065         _signal_analysis_collected_nframes   = 0;
3066         _signal_analysis_collect_nframes_max = nframes;
3067 }
3068
3069 /** Add a plugin to our list */
3070 void
3071 PluginInsert::add_plugin (boost::shared_ptr<Plugin> plugin)
3072 {
3073         plugin->set_insert_id (this->id());
3074         plugin->set_owner (_owner);
3075
3076         if (_plugins.empty()) {
3077                 /* first (and probably only) plugin instance - connect to relevant signals */
3078
3079                 plugin->ParameterChangedExternally.connect_same_thread (*this, boost::bind (&PluginInsert::parameter_changed_externally, this, _1, _2));
3080                 plugin->StartTouch.connect_same_thread (*this, boost::bind (&PluginInsert::start_touch, this, _1));
3081                 plugin->EndTouch.connect_same_thread (*this, boost::bind (&PluginInsert::end_touch, this, _1));
3082                 _custom_sinks = plugin->get_info()->n_inputs;
3083                 // cache sidechain port count
3084                 _cached_sidechain_pins.reset ();
3085                 const ChanCount& nis (plugin->get_info()->n_inputs);
3086                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3087                         for (uint32_t in = 0; in < nis.get (*t); ++in) {
3088                                 const Plugin::IOPortDescription& iod (plugin->describe_io_port (*t, true, in));
3089                                 if (iod.is_sidechain) {
3090                                         _cached_sidechain_pins.set (*t, 1 + _cached_sidechain_pins.n(*t));
3091                                 }
3092                         }
3093                 }
3094         }
3095 #if (defined WINDOWS_VST_SUPPORT || defined LXVST_SUPPORT || defined MACVST_SUPPORT)
3096         boost::shared_ptr<VSTPlugin> vst = boost::dynamic_pointer_cast<VSTPlugin> (plugin);
3097         if (vst) {
3098                 vst->set_insert (this, _plugins.size ());
3099         }
3100 #endif
3101
3102         _plugins.push_back (plugin);
3103 }
3104
3105 void
3106 PluginInsert::add_sidechain_from_xml (const XMLNode& node, int version)
3107 {
3108         if (version < 3000) {
3109                 return;
3110         }
3111
3112         XMLNodeList nlist = node.children();
3113
3114         if (nlist.size() == 0) {
3115                 return;
3116         }
3117
3118         uint32_t audio = 0;
3119         uint32_t midi = 0;
3120
3121         XMLNodeConstIterator it = nlist.front()->children().begin();
3122         for ( ; it != nlist.front()->children().end(); ++ it) {
3123                 if ((*it)->name() == "Port") {
3124                         DataType type(DataType::NIL);
3125                         (*it)->get_property ("type", type);
3126                         if (type == DataType::AUDIO) {
3127                                 ++audio;
3128                         } else if (type == DataType::MIDI) {
3129                                 ++midi;
3130                         }
3131                 }
3132         }
3133
3134         ChanCount in_cc = ChanCount();
3135         in_cc.set (DataType::AUDIO, audio);
3136         in_cc.set (DataType::MIDI, midi);
3137
3138         add_sidechain (audio, midi);
3139 }
3140
3141 bool
3142 PluginInsert::load_preset (ARDOUR::Plugin::PresetRecord pr)
3143 {
3144         bool ok = true;
3145         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
3146                 if (! (*i)->load_preset (pr)) {
3147                         ok = false;
3148                 }
3149         }
3150         return ok;
3151 }
3152
3153 void
3154 PluginInsert::realtime_handle_transport_stopped ()
3155 {
3156         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
3157                 (*i)->realtime_handle_transport_stopped ();
3158         }
3159 }
3160
3161 void
3162 PluginInsert::realtime_locate ()
3163 {
3164         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
3165                 (*i)->realtime_locate ();
3166         }
3167 }
3168
3169 void
3170 PluginInsert::monitoring_changed ()
3171 {
3172         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
3173                 (*i)->monitoring_changed ();
3174         }
3175 }
3176
3177 void
3178 PluginInsert::latency_changed ()
3179 {
3180         // this is called in RT context, LatencyChanged is emitted after run()
3181         _latency_changed = true;
3182         // XXX This also needs a proper API not an owner() hack.
3183         assert (owner ());
3184         static_cast<Route*>(owner ())->processor_latency_changed (); /* EMIT SIGNAL */
3185 }
3186
3187 void
3188 PluginInsert::start_touch (uint32_t param_id)
3189 {
3190         boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter (PluginAutomation, 0, param_id));
3191         if (ac) {
3192                 // ToDo subtract _plugin_signal_latency  from audible_sample() when rolling, assert > 0
3193                 ac->start_touch (session().audible_sample());
3194         }
3195 }
3196
3197 void
3198 PluginInsert::end_touch (uint32_t param_id)
3199 {
3200         boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter (PluginAutomation, 0, param_id));
3201         if (ac) {
3202                 // ToDo subtract _plugin_signal_latency  from audible_sample() when rolling, assert > 0
3203                 ac->stop_touch (session().audible_sample());
3204         }
3205 }
3206
3207 bool
3208 PluginInsert::get_stats (uint64_t& min, uint64_t& max, double& avg, double& dev) const
3209 {
3210         /* TODO: consider taking a try/lock: Don't run concurrently with
3211          * TimingStats::update, TimingStats::reset.
3212          */
3213         return _timing_stats.get_stats (min, max, avg, dev);
3214 }
3215
3216 void
3217 PluginInsert::clear_stats ()
3218 {
3219         g_atomic_int_set (&_stat_reset, 1);
3220 }
3221
3222 std::ostream& operator<<(std::ostream& o, const ARDOUR::PluginInsert::Match& m)
3223 {
3224         switch (m.method) {
3225                 case PluginInsert::Impossible: o << "Impossible"; break;
3226                 case PluginInsert::Delegate:   o << "Delegate"; break;
3227                 case PluginInsert::NoInputs:   o << "NoInputs"; break;
3228                 case PluginInsert::ExactMatch: o << "ExactMatch"; break;
3229                 case PluginInsert::Replicate:  o << "Replicate"; break;
3230                 case PluginInsert::Split:      o << "Split"; break;
3231                 case PluginInsert::Hide:       o << "Hide"; break;
3232         }
3233         o << " cnt: " << m.plugins
3234                 << (m.strict_io ? " strict-io" : "")
3235                 << (m.custom_cfg ? " custom-cfg" : "");
3236         if (m.method == PluginInsert::Hide) {
3237                 o << " hide: " << m.hide;
3238         }
3239         o << "\n";
3240         return o;
3241 }