23c9f8eb7ade080209ad41ec68da242375b5a150
[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.at(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.at(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::const_iterator li = controls().begin(); li != controls().end(); ++li, ++n) {
886
887                         /* boost::dynamic_pointer_cast<> has significant overhead, since we know that
888                          * all controls are AutomationControl and their lists - if any - are AutomationList,
889                          * we can use static_cast<>. This yields a speedup of 2.8/4.6 over to the
890                          * previous code (measuerd with VeeSeeVSTRack 10k parameters, optimized build) */
891                         AutomationControl& c = static_cast<AutomationControl&> (*(li->second));
892                         boost::shared_ptr<const Evoral::ControlList> clist (c.list());
893                         if (clist && (static_cast<AutomationList const&> (*clist)).automation_playback ()) {
894                                 bool valid;
895                                 const float val = c.list()->rt_safe_eval (start, valid);
896                                 if (valid) {
897                                         c.set_value_unchecked(val);
898                                 }
899                         }
900                 }
901         }
902
903         /* Calculate if, and how many samples we need to collect for analysis */
904         samplecnt_t collect_signal_nframes = (_signal_analysis_collect_nframes_max -
905                                              _signal_analysis_collected_nframes);
906         if (nframes < collect_signal_nframes) { // we might not get all samples now
907                 collect_signal_nframes = nframes;
908         }
909
910         if (collect_signal_nframes > 0) {
911                 // collect input
912                 //std::cerr << "collect input, bufs " << bufs.count().n_audio() << " count,  " << bufs.available().n_audio() << " available" << std::endl;
913                 //std::cerr << "               streams " << internal_input_streams().n_audio() << std::endl;
914                 //std::cerr << "filling buffer with " << collect_signal_nframes << " samples at " << _signal_analysis_collected_nframes << std::endl;
915
916                 _signal_analysis_inputs.set_count(input_streams());
917
918                 for (uint32_t i = 0; i < input_streams().n_audio(); ++i) {
919                         _signal_analysis_inputs.get_audio(i).read_from (
920                                 bufs.get_audio(i),
921                                 collect_signal_nframes,
922                                 _signal_analysis_collected_nframes); // offset is for target buffer
923                 }
924
925         }
926 #ifdef MIXBUS
927         if (is_channelstrip ()) {
928                 if (_configured_in.n_audio() > 0) {
929                         ChanMapping mb_in_map (ChanCount::min (_configured_in, ChanCount (DataType::AUDIO, 2)));
930                         ChanMapping mb_out_map (ChanCount::min (_configured_out, ChanCount (DataType::AUDIO, 2)));
931
932                         _plugins.front()->connect_and_run (bufs, start, end, speed, mb_in_map, mb_out_map, nframes, offset);
933
934                         for (uint32_t out = _configured_in.n_audio (); out < bufs.count().get (DataType::AUDIO); ++out) {
935                                 bufs.get (DataType::AUDIO, out).silence (nframes, offset);
936                         }
937                 }
938         } else
939 #endif
940         if (_no_inplace) {
941                 // TODO optimize -- build maps once.
942                 uint32_t pc = 0;
943                 BufferSet& inplace_bufs  = _session.get_noinplace_buffers();
944                 ARDOUR::ChanMapping used_outputs;
945
946                 assert (inplace_bufs.count () >= natural_input_streams () + _configured_out);
947
948                 /* build used-output map */
949                 for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i, ++pc) {
950                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
951                                 for (uint32_t out = 0; out < natural_output_streams().get (*t); ++out) {
952                                         bool valid;
953                                         uint32_t out_idx = out_map.at(pc).get (*t, out, &valid);
954                                         if (valid) {
955                                                 used_outputs.set (*t, out_idx, 1); // mark as used
956                                         }
957                                 }
958                         }
959                 }
960                 /* copy thru data to outputs before processing in-place */
961                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
962                         for (uint32_t out = 0; out < bufs.count().get (*t); ++out) {
963                                 bool valid;
964                                 uint32_t in_idx = thru_map.get (*t, out, &valid);
965                                 uint32_t m = out + natural_input_streams ().get (*t);
966                                 if (valid) {
967                                         _delaybuffers.delay (*t, out, inplace_bufs.get (*t, m), bufs.get (*t, in_idx), nframes, offset, offset);
968                                         used_outputs.set (*t, out, 1); // mark as used
969                                 } else {
970                                         used_outputs.get (*t, out, &valid);
971                                         if (valid) {
972                                                 /* the plugin is expected to write here, but may not :(
973                                                  * (e.g. drumgizmo w/o kit loaded)
974                                                  */
975                                                 inplace_bufs.get (*t, m).silence (nframes);
976                                         }
977                                 }
978                         }
979                 }
980
981                 pc = 0;
982                 for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i, ++pc) {
983
984                         ARDOUR::ChanMapping i_in_map (natural_input_streams());
985                         ARDOUR::ChanMapping i_out_map (out_map.at(pc));
986                         ARDOUR::ChanCount mapped;
987
988                         /* map inputs sequentially */
989                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
990                                 for (uint32_t in = 0; in < natural_input_streams().get (*t); ++in) {
991                                         bool valid;
992                                         uint32_t in_idx = in_map.at(pc).get (*t, in, &valid);
993                                         uint32_t m = mapped.get (*t);
994                                         if (valid) {
995                                                 inplace_bufs.get (*t, m).read_from (bufs.get (*t, in_idx), nframes, offset, offset);
996                                         } else {
997                                                 inplace_bufs.get (*t, m).silence (nframes, offset);
998                                         }
999                                         mapped.set (*t, m + 1);
1000                                 }
1001                         }
1002
1003                         /* outputs are mapped to inplace_bufs after the inputs */
1004                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1005                                 i_out_map.offset_to (*t, natural_input_streams ().get (*t));
1006                         }
1007
1008                         if ((*i)->connect_and_run (inplace_bufs, start, end, speed, i_in_map, i_out_map, nframes, offset)) {
1009                                 deactivate ();
1010                         }
1011                 }
1012
1013                 /* all instances have completed, now copy data that was written
1014                  * and zero unconnected buffers */
1015                 ARDOUR::ChanMapping nonzero_out (used_outputs);
1016                 if (has_midi_bypass ()) {
1017                         nonzero_out.set (DataType::MIDI, 0, 1); // Midi bypass.
1018                 }
1019                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1020                         for (uint32_t out = 0; out < bufs.count().get (*t); ++out) {
1021                                 bool valid;
1022                                 used_outputs.get (*t, out, &valid);
1023                                 if (!valid) {
1024                                         nonzero_out.get (*t, out, &valid);
1025                                         if (!valid) {
1026                                                 bufs.get (*t, out).silence (nframes, offset);
1027                                         }
1028                                 } else {
1029                                         uint32_t m = out + natural_input_streams ().get (*t);
1030                                         bufs.get (*t, out).read_from (inplace_bufs.get (*t, m), nframes, offset, offset);
1031                                 }
1032                         }
1033                 }
1034         } else {
1035                 /* in-place processing */
1036                 uint32_t pc = 0;
1037                 for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i, ++pc) {
1038                         if ((*i)->connect_and_run(bufs, start, end, speed, in_map.at(pc), out_map.at(pc), nframes, offset)) {
1039                                 deactivate ();
1040                         }
1041                 }
1042                 // now silence unconnected outputs
1043                 inplace_silence_unconnected (bufs, _out_map, nframes, offset);
1044         }
1045
1046         if (collect_signal_nframes > 0) {
1047                 // collect output
1048                 //std::cerr << "       output, bufs " << bufs.count().n_audio() << " count,  " << bufs.available().n_audio() << " available" << std::endl;
1049                 //std::cerr << "               streams " << internal_output_streams().n_audio() << std::endl;
1050
1051                 _signal_analysis_outputs.set_count(output_streams());
1052
1053                 for (uint32_t i = 0; i < output_streams().n_audio(); ++i) {
1054                         _signal_analysis_outputs.get_audio(i).read_from(
1055                                 bufs.get_audio(i),
1056                                 collect_signal_nframes,
1057                                 _signal_analysis_collected_nframes); // offset is for target buffer
1058                 }
1059
1060                 _signal_analysis_collected_nframes += collect_signal_nframes;
1061                 assert(_signal_analysis_collected_nframes <= _signal_analysis_collect_nframes_max);
1062
1063                 if (_signal_analysis_collected_nframes == _signal_analysis_collect_nframes_max) {
1064                         _signal_analysis_collect_nframes_max = 0;
1065                         _signal_analysis_collected_nframes   = 0;
1066
1067                         AnalysisDataGathered(&_signal_analysis_inputs,
1068                                              &_signal_analysis_outputs);
1069                 }
1070         }
1071
1072         if (_plugin_signal_latency != signal_latency ()) {
1073                 _plugin_signal_latency = signal_latency ();
1074                 latency_changed ();
1075         }
1076 }
1077
1078 void
1079 PluginInsert::bypass (BufferSet& bufs, pframes_t nframes)
1080 {
1081         /* bypass the plugin(s) not the whole processor.
1082          * -> use mappings just like connect_and_run
1083          */
1084
1085         // TODO: atomically copy maps & _no_inplace
1086         const ChanMapping in_map (no_sc_input_map ());
1087         const ChanMapping out_map (output_map ());
1088         if (_mapping_changed) {
1089                 _no_inplace = check_inplace ();
1090                 _mapping_changed = false;
1091         }
1092
1093         bufs.set_count(ChanCount::max(bufs.count(), _configured_internal));
1094         bufs.set_count(ChanCount::max(bufs.count(), _configured_out));
1095
1096         if (_no_inplace) {
1097                 ChanMapping thru_map (_thru_map);
1098
1099                 BufferSet& inplace_bufs  = _session.get_noinplace_buffers();
1100                 // copy all inputs
1101                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1102                         for (uint32_t in = 0; in < _configured_internal.get (*t); ++in) {
1103                                 inplace_bufs.get (*t, in).read_from (bufs.get (*t, in), nframes, 0, 0);
1104                         }
1105                 }
1106                 ARDOUR::ChanMapping used_outputs;
1107                 // copy thru
1108                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1109                         for (uint32_t out = 0; out < _configured_out.get (*t); ++out) {
1110                                 bool valid;
1111                                 uint32_t in_idx = thru_map.get (*t, out, &valid);
1112                                 if (valid) {
1113                                         bufs.get (*t, out).read_from (inplace_bufs.get (*t, in_idx), nframes, 0, 0);
1114                                         used_outputs.set (*t, out, 1); // mark as used
1115                                 }
1116                         }
1117                 }
1118                 // plugin no-op: assume every plugin has an internal identity map
1119                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1120                         for (uint32_t out = 0; out < _configured_out.get (*t); ++out) {
1121                                 bool valid;
1122                                 uint32_t src_idx = out_map.get_src (*t, out, &valid);
1123                                 if (!valid) {
1124                                         continue;
1125                                 }
1126                                 uint32_t in_idx = in_map.get (*t, src_idx, &valid);
1127                                 if (!valid) {
1128                                         continue;
1129                                 }
1130                                 bufs.get (*t, out).read_from (inplace_bufs.get (*t, in_idx), nframes, 0, 0);
1131                                 used_outputs.set (*t, out, 1); // mark as used
1132                         }
1133                 }
1134                 // now silence all unused outputs
1135                 if (has_midi_bypass ()) {
1136                         used_outputs.set (DataType::MIDI, 0, 1); // Midi bypass.
1137                 }
1138                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1139                         for (uint32_t out = 0; out < _configured_out.get (*t); ++out) {
1140                                 bool valid;
1141                                 used_outputs.get (*t, out, &valid);
1142                                 if (!valid) {
1143                                                 bufs.get (*t, out).silence (nframes, 0);
1144                                 }
1145                         }
1146                 }
1147         } else {
1148                 if (_match.method == Split) {
1149                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1150                                 if (_configured_internal.get (*t) == 0) {
1151                                         continue;
1152                                 }
1153                                 // copy/feeds _all_ *connected* inputs, copy the first buffer
1154                                 bool valid;
1155                                 uint32_t first_idx = in_map.get (*t, 0, &valid);
1156                                 assert (valid && first_idx == 0); // check_inplace ensures this
1157                                 for (uint32_t i = 1; i < natural_input_streams ().get (*t); ++i) {
1158                                         uint32_t idx = in_map.get (*t, i, &valid);
1159                                         if (valid) {
1160                                                 assert (idx == 0);
1161                                                 bufs.get (*t, i).read_from (bufs.get (*t, first_idx), nframes, 0, 0);
1162                                         }
1163                                 }
1164                         }
1165                 }
1166
1167                 // apply output map and/or monotonic but not identity i/o mappings
1168                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1169                         for (uint32_t out = 0; out < _configured_out.get (*t); ++out) {
1170                                 bool valid;
1171                                 uint32_t src_idx = out_map.get_src (*t, out, &valid);
1172                                 if (!valid) {
1173                                         bufs.get (*t, out).silence (nframes, 0);
1174                                         continue;
1175                                 }
1176                                 uint32_t in_idx = in_map.get (*t, src_idx, &valid);
1177                                 if (!valid) {
1178                                         bufs.get (*t, out).silence (nframes, 0);
1179                                         continue;
1180                                 }
1181                                 if (in_idx != src_idx) {
1182                                         bufs.get (*t, out).read_from (bufs.get (*t, in_idx), nframes, 0, 0);
1183                                 }
1184                         }
1185                 }
1186         }
1187 }
1188
1189 void
1190 PluginInsert::silence (samplecnt_t nframes, samplepos_t start_sample)
1191 {
1192         automation_run (start_sample, nframes); // evaluate automation only
1193
1194         if (!active ()) {
1195                 // XXX delaybuffers need to be offset by nframes
1196                 return;
1197         }
1198
1199         _delaybuffers.flush ();
1200
1201         ChanMapping in_map (natural_input_streams ());
1202         ChanMapping out_map (natural_output_streams ());
1203         ChanCount maxbuf = ChanCount::max (natural_input_streams (), natural_output_streams());
1204 #ifdef MIXBUS
1205         if (is_channelstrip ()) {
1206                 if (_configured_in.n_audio() > 0) {
1207                         _plugins.front()->connect_and_run (_session.get_scratch_buffers (maxbuf, true), start_sample, start_sample + nframes, 1.0, in_map, out_map, nframes, 0);
1208                 }
1209         } else
1210 #endif
1211         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1212                 (*i)->connect_and_run (_session.get_scratch_buffers (maxbuf, true), start_sample, start_sample + nframes, 1.0, in_map, out_map, nframes, 0);
1213         }
1214 }
1215
1216 void
1217 PluginInsert::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_sample, double speed, pframes_t nframes, bool)
1218 {
1219         if (_sidechain) {
1220                 // collect sidechain input for complete cycle (!)
1221                 // TODO we need delaylines here for latency compensation
1222                 _sidechain->run (bufs, start_sample, end_sample, speed, nframes, true);
1223         }
1224
1225         if (g_atomic_int_compare_and_exchange (&_stat_reset, 1, 0)) {
1226                 _timing_stats.reset ();
1227         }
1228
1229         if (_pending_active) {
1230                 _timing_stats.start ();
1231                 /* run as normal if we are active or moving from inactive to active */
1232
1233                 if (_session.transport_rolling() || _session.bounce_processing()) {
1234                         automate_and_run (bufs, start_sample, end_sample, speed, nframes);
1235                 } else {
1236                         Glib::Threads::Mutex::Lock lm (control_lock(), Glib::Threads::TRY_LOCK);
1237                         connect_and_run (bufs, start_sample, end_sample, speed, nframes, 0, lm.locked());
1238                 }
1239                 _timing_stats.update ();
1240
1241         } else {
1242                 _timing_stats.reset ();
1243                 // XXX should call ::silence() to run plugin(s) for consistent load.
1244                 // We'll need to change this anyway when bypass can be automated
1245                 bypass (bufs, nframes);
1246                 automation_run (start_sample, nframes); // evaluate automation only
1247                 _delaybuffers.flush ();
1248         }
1249
1250         _active = _pending_active;
1251
1252         /* we have no idea whether the plugin generated silence or not, so mark
1253          * all buffers appropriately.
1254          */
1255 }
1256
1257 void
1258 PluginInsert::automate_and_run (BufferSet& bufs, samplepos_t start, samplepos_t end, double speed, pframes_t nframes)
1259 {
1260         Evoral::ControlEvent next_event (0, 0.0f);
1261         samplecnt_t offset = 0;
1262
1263         Glib::Threads::Mutex::Lock lm (control_lock(), Glib::Threads::TRY_LOCK);
1264
1265         if (!lm.locked()) {
1266                 connect_and_run (bufs, start, end, speed, nframes, offset, false);
1267                 return;
1268         }
1269
1270         /* map start back into loop-range, adjust end */
1271         map_loop_range (start, end);
1272
1273         if (!find_next_event (start, end, next_event) || _plugins.front()->requires_fixed_sized_buffers()) {
1274
1275                 /* no events have a time within the relevant range */
1276
1277                 connect_and_run (bufs, start, end, speed, nframes, offset, true);
1278                 return;
1279         }
1280
1281         while (nframes) {
1282
1283                 samplecnt_t cnt = min (((samplecnt_t) ceil (next_event.when) - start), (samplecnt_t) nframes);
1284
1285                 connect_and_run (bufs, start, start + cnt, speed, cnt, offset, true); // XXX (start + cnt) * speed
1286
1287                 nframes -= cnt;
1288                 offset += cnt;
1289                 start += cnt;
1290
1291                 map_loop_range (start, end);
1292
1293                 if (!find_next_event (start, end, next_event)) {
1294                         break;
1295                 }
1296         }
1297
1298         /* cleanup anything that is left to do */
1299
1300         if (nframes) {
1301                 connect_and_run (bufs, start, start + nframes, speed, nframes, offset, true);
1302         }
1303 }
1304
1305 float
1306 PluginInsert::default_parameter_value (const Evoral::Parameter& param)
1307 {
1308         if (param.type() != PluginAutomation)
1309                 return 1.0;
1310
1311         if (_plugins.empty()) {
1312                 fatal << _("programming error: ") << X_("PluginInsert::default_parameter_value() called with no plugin")
1313                       << endmsg;
1314                 abort(); /*NOTREACHED*/
1315         }
1316
1317         return _plugins[0]->default_value (param.id());
1318 }
1319
1320
1321 bool
1322 PluginInsert::can_reset_all_parameters ()
1323 {
1324         bool all = true;
1325         uint32_t params = 0;
1326         for (uint32_t par = 0; par < _plugins[0]->parameter_count(); ++par) {
1327                 bool ok=false;
1328                 const uint32_t cid = _plugins[0]->nth_parameter (par, ok);
1329
1330                 if (!ok || !_plugins[0]->parameter_is_input(cid)) {
1331                         continue;
1332                 }
1333
1334                 boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter(PluginAutomation, 0, cid));
1335                 if (!ac) {
1336                         continue;
1337                 }
1338
1339                 ++params;
1340                 if (ac->automation_state() & Play) {
1341                         all = false;
1342                         break;
1343                 }
1344         }
1345         return all && (params > 0);
1346 }
1347
1348 bool
1349 PluginInsert::reset_parameters_to_default ()
1350 {
1351         bool all = true;
1352
1353         for (uint32_t par = 0; par < _plugins[0]->parameter_count(); ++par) {
1354                 bool ok=false;
1355                 const uint32_t cid = _plugins[0]->nth_parameter (par, ok);
1356
1357                 if (!ok || !_plugins[0]->parameter_is_input(cid)) {
1358                         continue;
1359                 }
1360
1361                 const float dflt = _plugins[0]->default_value (cid);
1362                 const float curr = _plugins[0]->get_parameter (cid);
1363
1364                 if (dflt == curr) {
1365                         continue;
1366                 }
1367
1368                 boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter(PluginAutomation, 0, cid));
1369                 if (!ac) {
1370                         continue;
1371                 }
1372
1373                 if (ac->automation_state() & Play) {
1374                         all = false;
1375                         continue;
1376                 }
1377
1378                 ac->set_value (dflt, Controllable::NoGroup);
1379         }
1380         return all;
1381 }
1382
1383 boost::shared_ptr<Plugin>
1384 PluginInsert::plugin_factory (boost::shared_ptr<Plugin> other)
1385 {
1386         boost::shared_ptr<LadspaPlugin> lp;
1387         boost::shared_ptr<LuaProc> lua;
1388 #ifdef LV2_SUPPORT
1389         boost::shared_ptr<LV2Plugin> lv2p;
1390 #endif
1391 #ifdef WINDOWS_VST_SUPPORT
1392         boost::shared_ptr<WindowsVSTPlugin> vp;
1393 #endif
1394 #ifdef LXVST_SUPPORT
1395         boost::shared_ptr<LXVSTPlugin> lxvp;
1396 #endif
1397 #ifdef MACVST_SUPPORT
1398         boost::shared_ptr<MacVSTPlugin> mvp;
1399 #endif
1400 #ifdef AUDIOUNIT_SUPPORT
1401         boost::shared_ptr<AUPlugin> ap;
1402 #endif
1403
1404         if ((lp = boost::dynamic_pointer_cast<LadspaPlugin> (other)) != 0) {
1405                 return boost::shared_ptr<Plugin> (new LadspaPlugin (*lp));
1406         } else if ((lua = boost::dynamic_pointer_cast<LuaProc> (other)) != 0) {
1407                 return boost::shared_ptr<Plugin> (new LuaProc (*lua));
1408 #ifdef LV2_SUPPORT
1409         } else if ((lv2p = boost::dynamic_pointer_cast<LV2Plugin> (other)) != 0) {
1410                 return boost::shared_ptr<Plugin> (new LV2Plugin (*lv2p));
1411 #endif
1412 #ifdef WINDOWS_VST_SUPPORT
1413         } else if ((vp = boost::dynamic_pointer_cast<WindowsVSTPlugin> (other)) != 0) {
1414                 return boost::shared_ptr<Plugin> (new WindowsVSTPlugin (*vp));
1415 #endif
1416 #ifdef LXVST_SUPPORT
1417         } else if ((lxvp = boost::dynamic_pointer_cast<LXVSTPlugin> (other)) != 0) {
1418                 return boost::shared_ptr<Plugin> (new LXVSTPlugin (*lxvp));
1419 #endif
1420 #ifdef MACVST_SUPPORT
1421         } else if ((mvp = boost::dynamic_pointer_cast<MacVSTPlugin> (other)) != 0) {
1422                 return boost::shared_ptr<Plugin> (new MacVSTPlugin (*mvp));
1423 #endif
1424 #ifdef AUDIOUNIT_SUPPORT
1425         } else if ((ap = boost::dynamic_pointer_cast<AUPlugin> (other)) != 0) {
1426                 return boost::shared_ptr<Plugin> (new AUPlugin (*ap));
1427 #endif
1428         }
1429
1430         fatal << string_compose (_("programming error: %1"),
1431                           X_("unknown plugin type in PluginInsert::plugin_factory"))
1432               << endmsg;
1433         abort(); /*NOTREACHED*/
1434         return boost::shared_ptr<Plugin> ((Plugin*) 0);
1435 }
1436
1437 void
1438 PluginInsert::set_input_map (uint32_t num, ChanMapping m) {
1439         if (num < _in_map.size()) {
1440                 bool changed = _in_map[num] != m;
1441                 _in_map[num] = m;
1442                 changed |= sanitize_maps ();
1443                 if (changed) {
1444                         PluginMapChanged (); /* EMIT SIGNAL */
1445                         _mapping_changed = true;
1446                         _session.set_dirty();
1447                 }
1448         }
1449 }
1450
1451 void
1452 PluginInsert::set_output_map (uint32_t num, ChanMapping m) {
1453         if (num < _out_map.size()) {
1454                 bool changed = _out_map[num] != m;
1455                 _out_map[num] = m;
1456                 changed |= sanitize_maps ();
1457                 if (changed) {
1458                         PluginMapChanged (); /* EMIT SIGNAL */
1459                         _mapping_changed = true;
1460                         _session.set_dirty();
1461                 }
1462         }
1463 }
1464
1465 void
1466 PluginInsert::set_thru_map (ChanMapping m) {
1467         bool changed = _thru_map != m;
1468         _thru_map = m;
1469         changed |= sanitize_maps ();
1470         if (changed) {
1471                 PluginMapChanged (); /* EMIT SIGNAL */
1472                 _mapping_changed = true;
1473                 _session.set_dirty();
1474         }
1475 }
1476
1477 bool
1478 PluginInsert::pre_seed (const ChanCount& in, const ChanCount& out,
1479                 const ChanMapping& im, const ChanMapping& om, const ChanMapping& tm)
1480 {
1481         if (_configured) { return false; }
1482         _configured_in = in;
1483         _configured_out = out;
1484         _in_map[0] = im;
1485         _out_map[0] = om;
1486         _thru_map = tm;
1487         _maps_from_state = in.n_total () > 0 && out.n_total () > 0;
1488         return true;
1489 }
1490
1491 ChanMapping
1492 PluginInsert::input_map () const
1493 {
1494         ChanMapping rv;
1495         uint32_t pc = 0;
1496         for (PinMappings::const_iterator i = _in_map.begin (); i != _in_map.end (); ++i, ++pc) {
1497                 ChanMapping m (i->second);
1498                 const ChanMapping::Mappings& mp ((*i).second.mappings());
1499                 for (ChanMapping::Mappings::const_iterator tm = mp.begin(); tm != mp.end(); ++tm) {
1500                         for (ChanMapping::TypeMapping::const_iterator i = tm->second.begin(); i != tm->second.end(); ++i) {
1501                                 rv.set (tm->first, i->first + pc * natural_input_streams().get(tm->first), i->second);
1502                         }
1503                 }
1504         }
1505         return rv;
1506 }
1507
1508
1509 ChanMapping
1510 PluginInsert::no_sc_input_map () const
1511 {
1512         ChanMapping rv;
1513         uint32_t pc = 0;
1514         for (PinMappings::const_iterator i = _in_map.begin (); i != _in_map.end (); ++i, ++pc) {
1515                 ChanMapping m (i->second);
1516                 const ChanMapping::Mappings& mp ((*i).second.mappings());
1517                 for (ChanMapping::Mappings::const_iterator tm = mp.begin(); tm != mp.end(); ++tm) {
1518                         uint32_t ins = natural_input_streams().get(tm->first) - _cached_sidechain_pins.get(tm->first);
1519                         for (ChanMapping::TypeMapping::const_iterator i = tm->second.begin(); i != tm->second.end(); ++i) {
1520                                 if (i->first < ins) {
1521                                         rv.set (tm->first, i->first + pc * ins, i->second);
1522                                 }
1523                         }
1524                 }
1525         }
1526         return rv;
1527 }
1528
1529 ChanMapping
1530 PluginInsert::output_map () const
1531 {
1532         ChanMapping rv;
1533         uint32_t pc = 0;
1534         for (PinMappings::const_iterator i = _out_map.begin (); i != _out_map.end (); ++i, ++pc) {
1535                 ChanMapping m (i->second);
1536                 const ChanMapping::Mappings& mp ((*i).second.mappings());
1537                 for (ChanMapping::Mappings::const_iterator tm = mp.begin(); tm != mp.end(); ++tm) {
1538                         for (ChanMapping::TypeMapping::const_iterator i = tm->second.begin(); i != tm->second.end(); ++i) {
1539                                 rv.set (tm->first, i->first + pc * natural_output_streams().get(tm->first), i->second);
1540                         }
1541                 }
1542         }
1543         if (has_midi_bypass ()) {
1544                 rv.set (DataType::MIDI, 0, 0);
1545         }
1546
1547         return rv;
1548 }
1549
1550 bool
1551 PluginInsert::has_midi_bypass () const
1552 {
1553         if (_configured_in.n_midi () == 1 && _configured_out.n_midi () == 1
1554                         && natural_output_streams ().n_midi () == 0) {
1555                 return true;
1556         }
1557         return false;
1558 }
1559
1560 bool
1561 PluginInsert::has_midi_thru () const
1562 {
1563         if (_configured_in.n_midi () == 1 && _configured_out.n_midi () == 1
1564                         && natural_input_streams ().n_midi () == 0 && natural_output_streams ().n_midi () == 0) {
1565                 return true;
1566         }
1567         return false;
1568 }
1569
1570 #ifdef MIXBUS
1571 bool
1572 PluginInsert::is_channelstrip () const {
1573         return _plugins.front()->is_channelstrip();
1574 }
1575 bool
1576 PluginInsert::is_nonbypassable () const {
1577         return _plugins.front()->is_nonbypassable ();
1578 }
1579 #endif
1580
1581 bool
1582 PluginInsert::check_inplace ()
1583 {
1584         bool inplace_ok = !_plugins.front()->inplace_broken ();
1585
1586         if (_thru_map.n_total () > 0) {
1587                 // TODO once midi-bypass is part of the mapping, ignore it
1588                 inplace_ok = false;
1589         }
1590
1591         if (_match.method == Split && inplace_ok) {
1592                 assert (get_count() == 1);
1593                 assert (_in_map.size () == 1);
1594                 if (!_out_map[0].is_monotonic ()) {
1595                         inplace_ok = false;
1596                 }
1597                 if (_configured_internal != _configured_in) {
1598                         /* no sidechain -- TODO we could allow this with
1599                          * some more logic in PluginInsert::connect_and_run().
1600                          *
1601                          * PluginInsert::reset_map() already maps it.
1602                          */
1603                         inplace_ok = false;
1604                 }
1605                 /* check mapping */
1606                 for (DataType::iterator t = DataType::begin(); t != DataType::end() && inplace_ok; ++t) {
1607                         if (_configured_internal.get (*t) == 0) {
1608                                 continue;
1609                         }
1610                         bool valid;
1611                         uint32_t first_idx = _in_map[0].get (*t, 0, &valid);
1612                         if (!valid || first_idx != 0) {
1613                                 // so far only allow to copy the *first* stream's buffer to others
1614                                 inplace_ok = false;
1615                         } else {
1616                                 for (uint32_t i = 1; i < natural_input_streams ().get (*t); ++i) {
1617                                         uint32_t idx = _in_map[0].get (*t, i, &valid);
1618                                         if (valid && idx != first_idx) {
1619                                                 inplace_ok = false;
1620                                                 break;
1621                                         }
1622                                 }
1623                         }
1624                 }
1625
1626                 if (inplace_ok) {
1627                         DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: In Place Split Map\n", name()));
1628                         return false;
1629                 }
1630         }
1631
1632         for (uint32_t pc = 0; pc < get_count() && inplace_ok ; ++pc) {
1633                 if (!_in_map[pc].is_monotonic ()) {
1634                         inplace_ok = false;
1635                 }
1636                 if (!_out_map[pc].is_monotonic ()) {
1637                         inplace_ok = false;
1638                 }
1639         }
1640
1641         if (inplace_ok) {
1642                 /* check if every output is fed by the corresponding input
1643                  *
1644                  * this prevents  in-port 1 -> sink-pin 2  ||  source-pin 1 -> out port 1, source-pin 2 -> out port 2
1645                  * (with in-place,  source-pin 1 -> out port 1 overwrites in-port 1)
1646                  *
1647                  * but allows     in-port 1 -> sink-pin 2  ||  source-pin 2 -> out port 1
1648                  */
1649                 ChanMapping in_map (input_map ());
1650                 const ChanMapping::Mappings out_m (output_map ().mappings ());
1651                 for (ChanMapping::Mappings::const_iterator t = out_m.begin (); t != out_m.end () && inplace_ok; ++t) {
1652                         for (ChanMapping::TypeMapping::const_iterator c = (*t).second.begin (); c != (*t).second.end () ; ++c) {
1653                                 /* src-pin: c->first, out-port: c->second */
1654                                 bool valid;
1655                                 uint32_t in_port = in_map.get (t->first, c->first, &valid);
1656                                 if (valid && in_port != c->second) {
1657                                         inplace_ok = false;
1658                                         break;
1659                                 }
1660                         }
1661                 }
1662         }
1663
1664         DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: %2\n", name(), inplace_ok ? "In-Place" : "No Inplace Processing"));
1665         return !inplace_ok; // no-inplace
1666 }
1667
1668 bool
1669 PluginInsert::sanitize_maps ()
1670 {
1671         bool changed = false;
1672         /* strip dead wood */
1673         PinMappings new_ins;
1674         PinMappings new_outs;
1675         ChanMapping new_thru;
1676
1677         for (uint32_t pc = 0; pc < get_count(); ++pc) {
1678                 ChanMapping new_in;
1679                 ChanMapping new_out;
1680                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1681                         for (uint32_t i = 0; i < natural_input_streams().get (*t); ++i) {
1682                                 bool valid;
1683                                 uint32_t idx = _in_map[pc].get (*t, i, &valid);
1684                                 if (valid && idx < _configured_internal.get (*t)) {
1685                                         new_in.set (*t, i, idx);
1686                                 }
1687                         }
1688                         for (uint32_t o = 0; o < natural_output_streams().get (*t); ++o) {
1689                                 bool valid;
1690                                 uint32_t idx = _out_map[pc].get (*t, o, &valid);
1691                                 if (valid && idx < _configured_out.get (*t)) {
1692                                         new_out.set (*t, o, idx);
1693                                 }
1694                         }
1695                 }
1696                 if (_in_map[pc] != new_in || _out_map[pc] != new_out) {
1697                         changed = true;
1698                 }
1699                 new_ins[pc] = new_in;
1700                 new_outs[pc] = new_out;
1701         }
1702
1703         /* prevent dup output assignments */
1704         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1705                 for (uint32_t o = 0; o < _configured_out.get (*t); ++o) {
1706                         bool mapped = false;
1707                         for (uint32_t pc = 0; pc < get_count(); ++pc) {
1708                                 bool valid;
1709                                 uint32_t idx = new_outs[pc].get_src (*t, o, &valid);
1710                                 if (valid && mapped) {
1711                                         new_outs[pc].unset (*t, idx);
1712                                 } else if (valid) {
1713                                         mapped = true;
1714                                 }
1715                         }
1716                 }
1717         }
1718
1719         /* remove excess thru */
1720         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1721                 for (uint32_t o = 0; o < _configured_out.get (*t); ++o) {
1722                         bool valid;
1723                         uint32_t idx = _thru_map.get (*t, o, &valid);
1724                         if (valid && idx < _configured_internal.get (*t)) {
1725                                 new_thru.set (*t, o, idx);
1726                         }
1727                 }
1728         }
1729
1730         /* prevent out + thru,  existing plugin outputs override thru */
1731         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1732                 for (uint32_t o = 0; o < _configured_out.get (*t); ++o) {
1733                         bool mapped = false;
1734                         bool valid;
1735                         for (uint32_t pc = 0; pc < get_count(); ++pc) {
1736                                 new_outs[pc].get_src (*t, o, &mapped);
1737                                 if (mapped) { break; }
1738                         }
1739                         if (!mapped) { continue; }
1740                         uint32_t idx = new_thru.get (*t, o, &valid);
1741                         if (mapped) {
1742                                 new_thru.unset (*t, idx);
1743                         }
1744                 }
1745         }
1746
1747         if (has_midi_bypass ()) {
1748                 // TODO: include midi-bypass in the thru set,
1749                 // remove dedicated handling.
1750                 new_thru.unset (DataType::MIDI, 0);
1751         }
1752
1753         if (_in_map != new_ins || _out_map != new_outs || _thru_map != new_thru) {
1754                 changed = true;
1755         }
1756         _in_map = new_ins;
1757         _out_map = new_outs;
1758         _thru_map = new_thru;
1759
1760         return changed;
1761 }
1762
1763 bool
1764 PluginInsert::reset_map (bool emit)
1765 {
1766         const PinMappings old_in (_in_map);
1767         const PinMappings old_out (_out_map);
1768
1769         _in_map.clear ();
1770         _out_map.clear ();
1771         _thru_map = ChanMapping ();
1772
1773         /* build input map */
1774         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1775                 uint32_t sc = 0; // side-chain round-robin (all instances)
1776                 uint32_t pc = 0;
1777                 for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i, ++pc) {
1778                         const uint32_t nis = natural_input_streams ().get(*t);
1779                         const uint32_t stride = nis - sidechain_input_pins().get (*t);
1780
1781                         /* SC inputs are last in the plugin-insert.. */
1782                         const uint32_t sc_start = _configured_in.get (*t);
1783                         const uint32_t sc_len = _configured_internal.get (*t) - sc_start;
1784                         /* ...but may not be at the end of the plugin ports.
1785                          * in case the side-chain is not the last port, shift connections back.
1786                          * and connect to side-chain
1787                          */
1788                         uint32_t shift = 0;
1789                         uint32_t ic = 0; // split inputs
1790                         const uint32_t cend = _configured_in.get (*t);
1791
1792                         for (uint32_t in = 0; in < nis; ++in) {
1793                                 const Plugin::IOPortDescription& iod (_plugins[pc]->describe_io_port (*t, true, in));
1794                                 if (iod.is_sidechain) {
1795                                         /* connect sidechain sinks to sidechain inputs in round-robin fashion */
1796                                         if (sc_len > 0) {// side-chain may be hidden
1797                                                 _in_map[pc].set (*t, in, sc_start + sc);
1798                                                 sc = (sc + 1) % sc_len;
1799                                         }
1800                                         ++shift;
1801                                 } else {
1802                                         if (_match.method == Split) {
1803                                                 if (cend == 0) { continue; }
1804                                                 if (_strict_io && ic + stride * pc >= cend) {
1805                                                         break;
1806                                                 }
1807                                                 /* connect *no* sidechain sinks in round-robin fashion */
1808                                                 _in_map[pc].set (*t, in, ic + stride * pc);
1809                                                 if (_strict_io && (ic + 1) == cend) {
1810                                                         break;
1811                                                 }
1812                                                 ic = (ic + 1) % cend;
1813                                         } else {
1814                                                 uint32_t s = in - shift;
1815                                                 if (stride * pc + s < cend) {
1816                                                         _in_map[pc].set (*t, in, s + stride * pc);
1817                                                 }
1818                                         }
1819                                 }
1820                         }
1821                 }
1822         }
1823
1824         /* build output map */
1825         uint32_t pc = 0;
1826         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i, ++pc) {
1827                 _out_map[pc] = ChanMapping (ChanCount::min (natural_output_streams(), _configured_out));
1828                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1829                         _out_map[pc].offset_to(*t, pc * natural_output_streams().get(*t));
1830                 }
1831         }
1832
1833         sanitize_maps ();
1834         if (old_in == _in_map && old_out == _out_map) {
1835                 return false;
1836         }
1837         if (emit) {
1838                 PluginMapChanged (); /* EMIT SIGNAL */
1839                 _mapping_changed = true;
1840                 _session.set_dirty();
1841         }
1842         return true;
1843 }
1844
1845 bool
1846 PluginInsert::configure_io (ChanCount in, ChanCount out)
1847 {
1848         Match old_match = _match;
1849         ChanCount old_in;
1850         ChanCount old_internal;
1851         ChanCount old_out;
1852         ChanCount old_pins;
1853
1854         old_pins = natural_input_streams();
1855         old_in = _configured_in;
1856         old_out = _configured_out;
1857         old_internal = _configured_internal;
1858
1859         _configured_in = in;
1860         _configured_internal = in;
1861         _configured_out = out;
1862
1863         if (_sidechain) {
1864                 /* TODO hide midi-bypass, and custom outs. Best /fake/ "out" here.
1865                  * (currently _sidechain->configure_io always succeeds
1866                  *  since Processor::configure_io() succeeds)
1867                  */
1868                 if (!_sidechain->configure_io (in, out)) {
1869                         DEBUG_TRACE (DEBUG::ChanMapping, "Sidechain configuration failed\n");
1870                         return false;
1871                 }
1872                 _configured_internal += _sidechain->input()->n_ports();
1873
1874                 // include (static_cast<Route*>owner())->name() ??
1875                 _sidechain->input ()-> set_pretty_name (string_compose (_("SC %1"), name ()));
1876         }
1877
1878         /* get plugin configuration */
1879         _match = private_can_support_io_configuration (in, out);
1880 #ifndef NDEBUG
1881         if (DEBUG_ENABLED(DEBUG::ChanMapping)) {
1882                 DEBUG_STR_DECL(a);
1883                 DEBUG_STR_APPEND(a, string_compose ("%1: ",  name()));
1884                 DEBUG_STR_APPEND(a, _match);
1885                 DEBUG_TRACE (DEBUG::ChanMapping, DEBUG_STR(a).str());
1886         }
1887 #endif
1888
1889         /* set the matching method and number of plugins that we will use to meet this configuration */
1890         if (set_count (_match.plugins) == false) {
1891                 PluginIoReConfigure (); /* EMIT SIGNAL */
1892                 _configured = false;
1893                 return false;
1894         }
1895
1896         /* configure plugins */
1897         switch (_match.method) {
1898         case Split:
1899         case Hide:
1900                 if (_plugins.front()->configure_io (natural_input_streams(), out) == false) {
1901                         PluginIoReConfigure (); /* EMIT SIGNAL */
1902                         _configured = false;
1903                         return false;
1904                 }
1905                 break;
1906         case Delegate:
1907                 {
1908                         ChanCount din (_configured_internal);
1909                         ChanCount dout (din); // hint
1910                         if (_custom_cfg) {
1911                                 if (_custom_sinks.n_total () > 0) {
1912                                         din = _custom_sinks;
1913                                 }
1914                                 dout = _custom_out;
1915                         } else if (_preset_out.n_audio () > 0) {
1916                                 dout.set (DataType::AUDIO, _preset_out.n_audio ());
1917                         } else if (dout.n_midi () > 0 && dout.n_audio () == 0) {
1918                                 dout.set (DataType::AUDIO, 2);
1919                         }
1920                         if (out.n_audio () == 0) { out.set (DataType::AUDIO, 1); }
1921                         ChanCount useins;
1922                         DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: Delegate lookup : %2 %3\n", name(), din, dout));
1923                         bool const r = _plugins.front()->can_support_io_configuration (din, dout, &useins);
1924                         assert (r);
1925                         if (useins.n_audio() == 0) {
1926                                 useins = din;
1927                         }
1928                         DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: Delegate configuration: %2 %3\n", name(), useins, dout));
1929
1930                         if (_plugins.front()->configure_io (useins, dout) == false) {
1931                                 PluginIoReConfigure (); /* EMIT SIGNAL */
1932                                 _configured = false;
1933                                 return false;
1934                         }
1935                         if (!_custom_cfg) {
1936                                 _custom_sinks = din;
1937                         }
1938                 }
1939                 break;
1940         default:
1941                 if (_plugins.front()->configure_io (in, out) == false) {
1942                         PluginIoReConfigure (); /* EMIT SIGNAL */
1943                         _configured = false;
1944                         return false;
1945                 }
1946                 break;
1947         }
1948
1949         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",
1950                                 name (),
1951                                 _configured ? "Y" : "N",
1952                                 _maps_from_state ? "Y" : "N",
1953                                 old_in == in ? "==" : "!=",
1954                                 old_out == out ? "==" : "!=",
1955                                 old_pins == natural_input_streams () ? "==" : "!=",
1956                                 old_match.method == _match.method ? "==" : "!=",
1957                                 old_match.custom_cfg == _match.custom_cfg ? "==" : "!=",
1958                                 _in_map.size() == get_count () ? "==" : "!=",
1959                                 _out_map.size() == get_count () ? "==" : "!="
1960                                 ));
1961
1962         bool mapping_changed = false;
1963         if (old_in == in && old_out == out
1964                         && _configured
1965                         && old_pins == natural_input_streams ()
1966                         && old_match.method == _match.method
1967                         && old_match.custom_cfg == _match.custom_cfg
1968                         && _in_map.size() == _out_map.size()
1969                         && _in_map.size() == get_count ()
1970                  ) {
1971                 /* If the configuration has not changed, keep the mapping */
1972                 mapping_changed = sanitize_maps ();
1973         } else if (_match.custom_cfg && _configured) {
1974                 /* don't touch the map in manual mode */
1975                 mapping_changed = sanitize_maps ();
1976         } else {
1977 #ifdef MIXBUS
1978                 if (is_channelstrip ()) {
1979                         /* fake channel map - for wire display */
1980                         _in_map.clear ();
1981                         _out_map.clear ();
1982                         _thru_map = ChanMapping ();
1983                         _in_map[0] = ChanMapping (ChanCount::min (_configured_in, ChanCount (DataType::AUDIO, 2)));
1984                         _out_map[0] = ChanMapping (ChanCount::min (_configured_out, ChanCount (DataType::AUDIO, 2)));
1985                         /* set "thru" map for in-place forward of audio */
1986                         for (uint32_t i = 2; i < _configured_in.n_audio(); ++i) {
1987                                 _thru_map.set (DataType::AUDIO, i, i);
1988                         }
1989                         /* and midi (after implicit 1st channel bypass) */
1990                         for (uint32_t i = 1; i < _configured_in.n_midi(); ++i) {
1991                                 _thru_map.set (DataType::MIDI, i, i);
1992                         }
1993                 } else
1994 #endif
1995                 if (_maps_from_state && old_in == in && old_out == out) {
1996                         mapping_changed = true;
1997                         sanitize_maps ();
1998                 } else {
1999                         /* generate a new mapping */
2000                         mapping_changed = reset_map (false);
2001                 }
2002                 _maps_from_state = false;
2003         }
2004
2005         if (mapping_changed) {
2006                 PluginMapChanged (); /* EMIT SIGNAL */
2007
2008 #ifndef NDEBUG
2009                 if (DEBUG_ENABLED(DEBUG::ChanMapping)) {
2010                         uint32_t pc = 0;
2011                         DEBUG_STR_DECL(a);
2012                         DEBUG_STR_APPEND(a, "\n--------<<--------\n");
2013                         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i, ++pc) {
2014                                 if (pc > 0) {
2015                         DEBUG_STR_APPEND(a, "----><----\n");
2016                                 }
2017                                 DEBUG_STR_APPEND(a, string_compose ("Channel Map for %1 plugin %2\n", name(), pc));
2018                                 DEBUG_STR_APPEND(a, " * Inputs:\n");
2019                                 DEBUG_STR_APPEND(a, _in_map[pc]);
2020                                 DEBUG_STR_APPEND(a, " * Outputs:\n");
2021                                 DEBUG_STR_APPEND(a, _out_map[pc]);
2022                         }
2023                         DEBUG_STR_APPEND(a, " * Thru:\n");
2024                         DEBUG_STR_APPEND(a, _thru_map);
2025                         DEBUG_STR_APPEND(a, "-------->>--------\n");
2026                         DEBUG_TRACE (DEBUG::ChanMapping, DEBUG_STR(a).str());
2027                 }
2028 #endif
2029         }
2030
2031         _no_inplace = check_inplace ();
2032         _mapping_changed = false;
2033
2034         /* only the "noinplace_buffers" thread buffers need to be this large,
2035          * this can be optimized. other buffers are fine with
2036          * ChanCount::max (natural_input_streams (), natural_output_streams())
2037          * and route.cc's max (configured_in, configured_out)
2038          *
2039          * no-inplace copies "thru" outputs (to emulate in-place) for
2040          * all outputs (to prevent overwrite) into a temporary space
2041          * which also holds input buffers (in case the plugin does process
2042          * in-place and overwrites those).
2043          *
2044          * this buffers need to be at least as
2045          *   natural_input_streams () + possible outputs.
2046          *
2047          * sidechain inputs add a constraint on the input:
2048          * configured input + sidechain (=_configured_internal)
2049          *
2050          * NB. this also satisfies
2051          * max (natural_input_streams(), natural_output_streams())
2052          * which is needed for silence runs
2053          */
2054         _required_buffers = ChanCount::max (_configured_internal,
2055                         natural_input_streams () + ChanCount::max (_configured_out, natural_output_streams () * get_count ()));
2056
2057         if (old_in != in || old_out != out || old_internal != _configured_internal
2058                         || old_pins != natural_input_streams ()
2059                         || (old_match.method != _match.method && (old_match.method == Split || _match.method == Split))
2060                  ) {
2061                 PluginIoReConfigure (); /* EMIT SIGNAL */
2062         }
2063
2064         _delaybuffers.configure (_configured_out, _plugins.front ()->max_latency ());
2065         _latency_changed = true;
2066
2067         // we don't know the analysis window size, so we must work with the
2068         // current buffer size here. each request for data fills in these
2069         // buffers and the analyser makes sure it gets enough data for the
2070         // analysis window
2071         session().ensure_buffer_set (_signal_analysis_inputs, in);
2072         _signal_analysis_inputs.set_count (in);
2073
2074         session().ensure_buffer_set (_signal_analysis_outputs, out);
2075         _signal_analysis_outputs.set_count (out);
2076
2077         // std::cerr << "set counts to i" << in.n_audio() << "/o" << out.n_audio() << std::endl;
2078
2079         _configured = true;
2080         return Processor::configure_io (in, out);
2081 }
2082
2083 /** Decide whether this PluginInsert can support a given IO configuration.
2084  *  To do this, we run through a set of possible solutions in rough order of
2085  *  preference.
2086  *
2087  *  @param in Required input channel count.
2088  *  @param out Filled in with the output channel count if we return true.
2089  *  @return true if the given IO configuration can be supported.
2090  */
2091 bool
2092 PluginInsert::can_support_io_configuration (const ChanCount& in, ChanCount& out)
2093 {
2094         if (_sidechain) {
2095                 _sidechain->can_support_io_configuration (in, out); // never fails, sets "out"
2096         }
2097         return private_can_support_io_configuration (in, out).method != Impossible;
2098 }
2099
2100 PluginInsert::Match
2101 PluginInsert::private_can_support_io_configuration (ChanCount const& in, ChanCount& out) const
2102 {
2103         if (!_custom_cfg && _preset_out.n_audio () > 0) {
2104                 // preseed hint (for variable i/o)
2105                 out.set (DataType::AUDIO, _preset_out.n_audio ());
2106         }
2107
2108         Match rv = internal_can_support_io_configuration (in, out);
2109
2110         if (!_custom_cfg && _preset_out.n_audio () > 0) {
2111                 DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: using output preset: %2\n", name(), _preset_out));
2112                 out.set (DataType::AUDIO, _preset_out.n_audio ());
2113         }
2114         return rv;
2115 }
2116
2117 /** A private version of can_support_io_configuration which returns the method
2118  *  by which the configuration can be matched, rather than just whether or not
2119  *  it can be.
2120  */
2121 PluginInsert::Match
2122 PluginInsert::internal_can_support_io_configuration (ChanCount const & inx, ChanCount& out) const
2123 {
2124         if (_plugins.empty()) {
2125                 return Match();
2126         }
2127
2128 #ifdef MIXBUS
2129         if (is_channelstrip ()) {
2130                 out = inx;
2131                 return Match (ExactMatch, 1);
2132         }
2133 #endif
2134
2135         /* if a user specified a custom cfg, so be it. */
2136         if (_custom_cfg) {
2137                 PluginInfoPtr info = _plugins.front()->get_info();
2138                 out = _custom_out;
2139                 if (info->reconfigurable_io()) {
2140                         return Match (Delegate, 1, _strict_io, true);
2141                 } else {
2142                         return Match (ExactMatch, get_count(), _strict_io, true);
2143                 }
2144         }
2145
2146         /* try automatic configuration */
2147         Match m = PluginInsert::automatic_can_support_io_configuration (inx, out);
2148
2149         PluginInfoPtr info = _plugins.front()->get_info();
2150         ChanCount inputs  = info->n_inputs;
2151         ChanCount outputs = info->n_outputs;
2152
2153         /* handle case strict-i/o */
2154         if (_strict_io && m.method != Impossible) {
2155                 m.strict_io = true;
2156
2157                 /* special case MIDI instruments */
2158                 if (is_instrument ()) {
2159                         // output = midi-bypass + at most master-out channels.
2160                         ChanCount max_out (DataType::AUDIO, 2); // TODO use master-out
2161                         max_out.set (DataType::MIDI, out.get(DataType::MIDI));
2162                         out = ChanCount::min (out, max_out);
2163                         DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: special case strict-i/o instrument\n", name()));
2164                         return m;
2165                 }
2166
2167                 switch (m.method) {
2168                         case NoInputs:
2169                                 if (inx.n_audio () != out.n_audio ()) { // ignore midi bypass
2170                                         /* replicate processor to match output count (generators and such)
2171                                          * at least enough to feed every output port. */
2172                                         uint32_t f = 1; // at least one. e.g. control data filters, no in, no out.
2173                                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2174                                                 uint32_t nout = outputs.get (*t);
2175                                                 if (nout == 0 || inx.get(*t) == 0) { continue; }
2176                                                 f = max (f, (uint32_t) ceil (inx.get(*t) / (float)nout));
2177                                         }
2178                                         out = inx;
2179                                         DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: special case strict-i/o for generator\n", name()));
2180                                         return Match (Replicate, f, _strict_io);
2181                                 }
2182                                 break;
2183                         default:
2184                                 break;
2185                 }
2186
2187                 out = inx;
2188                 return m;
2189         }
2190
2191         if (m.method != Impossible) {
2192                 return m;
2193         }
2194
2195         ChanCount ns_inputs  = inputs - sidechain_input_pins ();
2196
2197         DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: resolving 'Impossible' match...\n", name()));
2198
2199         if (info->reconfigurable_io()) {
2200                 ChanCount useins;
2201                 out = inx; // hint
2202                 if (out.n_midi () > 0 && out.n_audio () == 0) { out.set (DataType::AUDIO, 2); }
2203                 if (out.n_audio () == 0) { out.set (DataType::AUDIO, 1); }
2204                 bool const r = _plugins.front()->can_support_io_configuration (inx + sidechain_input_pins (), out, &useins);
2205                 if (!r) {
2206                         // houston, we have a problem.
2207                         return Match (Impossible, 0);
2208                 }
2209                 // midi bypass
2210                 if (inx.n_midi () > 0 && out.n_midi () == 0) { out.set (DataType::MIDI, 1); }
2211                 return Match (Delegate, 1, _strict_io);
2212         }
2213
2214         ChanCount midi_bypass;
2215         if (inx.get(DataType::MIDI) == 1 && outputs.get(DataType::MIDI) == 0) {
2216                 midi_bypass.set (DataType::MIDI, 1);
2217         }
2218
2219         // add at least as many plugins so that output count matches input count (w/o sidechain pins)
2220         uint32_t f = 0;
2221         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2222                 uint32_t nin = ns_inputs.get (*t);
2223                 uint32_t nout = outputs.get (*t);
2224                 if (nin == 0 || inx.get(*t) == 0) { continue; }
2225                 // prefer floor() so the count won't overly increase IFF (nin < nout)
2226                 f = max (f, (uint32_t) floor (inx.get(*t) / (float)nout));
2227         }
2228         if (f > 0 && outputs * f >= _configured_out) {
2229                 out = outputs * f + midi_bypass;
2230                 return Match (Replicate, f, _strict_io);
2231         }
2232
2233         // add at least as many plugins needed to connect all inputs (w/o sidechain pins)
2234         f = 0;
2235         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2236                 uint32_t nin = ns_inputs.get (*t);
2237                 if (nin == 0 || inx.get(*t) == 0) { continue; }
2238                 f = max (f, (uint32_t) ceil (inx.get(*t) / (float)nin));
2239         }
2240         if (f > 0) {
2241                 out = outputs * f + midi_bypass;
2242                 return Match (Replicate, f, _strict_io);
2243         }
2244
2245         // add at least as many plugins needed to connect all inputs
2246         f = 1;
2247         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2248                 uint32_t nin = inputs.get (*t);
2249                 if (nin == 0 || inx.get(*t) == 0) { continue; }
2250                 f = max (f, (uint32_t) ceil (inx.get(*t) / (float)nin));
2251         }
2252         out = outputs * f + midi_bypass;
2253         return Match (Replicate, f, _strict_io);
2254 }
2255
2256 /* this is the original Ardour 3/4 behavior, mainly for backwards compatibility */
2257 PluginInsert::Match
2258 PluginInsert::automatic_can_support_io_configuration (ChanCount const & inx, ChanCount& out) const
2259 {
2260         if (_plugins.empty()) {
2261                 return Match();
2262         }
2263
2264         PluginInfoPtr info = _plugins.front()->get_info();
2265         ChanCount in; in += inx;
2266         ChanCount midi_bypass;
2267
2268         if (info->reconfigurable_io()) {
2269                 /* Plugin has flexible I/O, so delegate to it
2270                  * pre-seed outputs, plugin tries closest match
2271                  */
2272                 out = in; // hint
2273                 if (out.n_midi () > 0 && out.n_audio () == 0) { out.set (DataType::AUDIO, 2); }
2274                 if (out.n_audio () == 0) { out.set (DataType::AUDIO, 1); }
2275                 bool const r = _plugins.front()->can_support_io_configuration (in + sidechain_input_pins (), out);
2276                 if (!r) {
2277                         return Match (Impossible, 0);
2278                 }
2279                 // midi bypass
2280                 if (in.n_midi () > 0 && out.n_midi () == 0) { out.set (DataType::MIDI, 1); }
2281                 return Match (Delegate, 1);
2282         }
2283
2284         ChanCount inputs  = info->n_inputs;
2285         ChanCount outputs = info->n_outputs;
2286         ChanCount ns_inputs  = inputs - sidechain_input_pins ();
2287
2288         if (in.get(DataType::MIDI) == 1 && outputs.get(DataType::MIDI) == 0) {
2289                 DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: bypassing midi-data\n", name()));
2290                 midi_bypass.set (DataType::MIDI, 1);
2291         }
2292         if (in.get(DataType::MIDI) == 1 && inputs.get(DataType::MIDI) == 0) {
2293                 DEBUG_TRACE (DEBUG::ChanMapping, string_compose ("%1: hiding midi-port from plugin\n", name()));
2294                 in.set(DataType::MIDI, 0);
2295         }
2296
2297         // add internally provided sidechain ports
2298         ChanCount insc = in + sidechain_input_ports ();
2299
2300         bool no_inputs = true;
2301         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2302                 if (inputs.get (*t) != 0) {
2303                         no_inputs = false;
2304                         break;
2305                 }
2306         }
2307
2308         if (no_inputs) {
2309                 /* no inputs so we can take any input configuration since we throw it away */
2310                 out = outputs + midi_bypass;
2311                 return Match (NoInputs, 1);
2312         }
2313
2314         /* Plugin inputs match requested inputs + side-chain-ports exactly */
2315         if (inputs == insc) {
2316                 out = outputs + midi_bypass;
2317                 return Match (ExactMatch, 1);
2318         }
2319
2320         /* Plugin inputs matches without side-chain-pins */
2321         if (ns_inputs == in) {
2322                 out = outputs + midi_bypass;
2323                 return Match (ExactMatch, 1);
2324         }
2325
2326         /* We may be able to run more than one copy of the plugin within this insert
2327            to cope with the insert having more inputs than the plugin.
2328            We allow replication only for plugins with either zero or 1 inputs and outputs
2329            for every valid data type.
2330         */
2331
2332         uint32_t f             = 0;
2333         bool     can_replicate = true;
2334         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2335
2336                 // ignore side-chains
2337                 uint32_t nin = ns_inputs.get (*t);
2338
2339                 // No inputs of this type
2340                 if (nin == 0 && in.get(*t) == 0) {
2341                         continue;
2342                 }
2343
2344                 if (nin != 1 || outputs.get (*t) != 1) {
2345                         can_replicate = false;
2346                         break;
2347                 }
2348
2349                 // Potential factor not set yet
2350                 if (f == 0) {
2351                         f = in.get(*t) / nin;
2352                 }
2353
2354                 // Factor for this type does not match another type, can not replicate
2355                 if (f != (in.get(*t) / nin)) {
2356                         can_replicate = false;
2357                         break;
2358                 }
2359         }
2360
2361         if (can_replicate && f > 0) {
2362                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2363                         out.set (*t, outputs.get(*t) * f);
2364                 }
2365                 out += midi_bypass;
2366                 return Match (Replicate, f);
2367         }
2368
2369         /* If the processor has exactly one input of a given type, and
2370            the plugin has more, we can feed the single processor input
2371            to some or all of the plugin inputs.  This is rather
2372            special-case-y, but the 1-to-many case is by far the
2373            simplest.  How do I split thy 2 processor inputs to 3
2374            plugin inputs?  Let me count the ways ...
2375         */
2376
2377         bool can_split = true;
2378         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2379
2380                 bool const can_split_type = (in.get (*t) == 1 && ns_inputs.get (*t) > 1);
2381                 bool const nothing_to_do_for_type = (in.get (*t) == 0 && inputs.get (*t) == 0);
2382
2383                 if (!can_split_type && !nothing_to_do_for_type) {
2384                         can_split = false;
2385                 }
2386         }
2387
2388         if (can_split) {
2389                 out = outputs + midi_bypass;
2390                 return Match (Split, 1);
2391         }
2392
2393         /* If the plugin has more inputs than we want, we can `hide' some of them
2394            by feeding them silence.
2395         */
2396
2397         bool could_hide = false;
2398         bool cannot_hide = false;
2399         ChanCount hide_channels;
2400
2401         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2402                 if (inputs.get(*t) > in.get(*t)) {
2403                         /* there is potential to hide, since the plugin has more inputs of type t than the insert */
2404                         hide_channels.set (*t, inputs.get(*t) - in.get(*t));
2405                         could_hide = true;
2406                 } else if (inputs.get(*t) < in.get(*t)) {
2407                         /* we definitely cannot hide, since the plugin has fewer inputs of type t than the insert */
2408                         cannot_hide = true;
2409                 }
2410         }
2411
2412         if (could_hide && !cannot_hide) {
2413                 out = outputs + midi_bypass;
2414                 return Match (Hide, 1, false, false, hide_channels);
2415         }
2416
2417         return Match (Impossible, 0);
2418 }
2419
2420
2421 XMLNode&
2422 PluginInsert::state ()
2423 {
2424         XMLNode& node = Processor::state ();
2425
2426         node.set_property("type", _plugins[0]->state_node_name());
2427         node.set_property("unique-id", _plugins[0]->unique_id());
2428         node.set_property("count", (uint32_t)_plugins.size());
2429
2430         /* remember actual i/o configuration (for later placeholder
2431          * in case the plugin goes missing) */
2432         node.add_child_nocopy (* _configured_in.state (X_("ConfiguredInput")));
2433         node.add_child_nocopy (* _custom_sinks.state (X_("CustomSinks")));
2434         node.add_child_nocopy (* _configured_out.state (X_("ConfiguredOutput")));
2435         node.add_child_nocopy (* _preset_out.state (X_("PresetOutput")));
2436
2437         /* save custom i/o config */
2438         node.set_property("custom", _custom_cfg);
2439         for (uint32_t pc = 0; pc < get_count(); ++pc) {
2440                 char tmp[128];
2441                 snprintf (tmp, sizeof(tmp), "InputMap-%d", pc);
2442                 node.add_child_nocopy (* _in_map[pc].state (tmp));
2443                 snprintf (tmp, sizeof(tmp), "OutputMap-%d", pc);
2444                 node.add_child_nocopy (* _out_map[pc].state (tmp));
2445         }
2446         node.add_child_nocopy (* _thru_map.state ("ThruMap"));
2447
2448         if (_sidechain) {
2449                 node.add_child_nocopy (_sidechain->get_state ());
2450         }
2451
2452         _plugins[0]->set_insert_id(this->id());
2453         node.add_child_nocopy (_plugins[0]->get_state());
2454
2455         for (Controls::iterator c = controls().begin(); c != controls().end(); ++c) {
2456                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl> ((*c).second);
2457                 if (ac) {
2458                         node.add_child_nocopy (ac->get_state());
2459                 }
2460         }
2461
2462         return node;
2463 }
2464
2465 void
2466 PluginInsert::set_control_ids (const XMLNode& node, int version)
2467 {
2468         const XMLNodeList& nlist = node.children();
2469         XMLNodeConstIterator iter;
2470         set<Evoral::Parameter>::const_iterator p;
2471
2472         for (iter = nlist.begin(); iter != nlist.end(); ++iter) {
2473                 if ((*iter)->name() == Controllable::xml_node_name) {
2474
2475                         uint32_t p = (uint32_t)-1;
2476 #ifdef LV2_SUPPORT
2477                         std::string str;
2478                         if ((*iter)->get_property (X_("symbol"), str)) {
2479                                 boost::shared_ptr<LV2Plugin> lv2plugin = boost::dynamic_pointer_cast<LV2Plugin> (_plugins[0]);
2480                                 if (lv2plugin) {
2481                                         p = lv2plugin->port_index(str.c_str());
2482                                 }
2483                         }
2484 #endif
2485                         if (p == (uint32_t)-1) {
2486                                 (*iter)->get_property (X_("parameter"), p);
2487                         }
2488
2489                         if (p != (uint32_t)-1) {
2490
2491                                 /* this may create the new controllable */
2492
2493                                 boost::shared_ptr<Evoral::Control> c = control (Evoral::Parameter (PluginAutomation, 0, p));
2494
2495 #ifndef NO_PLUGIN_STATE
2496                                 if (!c) {
2497                                         continue;
2498                                 }
2499                                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl> (c);
2500                                 if (ac) {
2501                                         ac->set_state (**iter, version);
2502                                 }
2503 #endif
2504                         }
2505                 }
2506         }
2507 }
2508
2509 int
2510 PluginInsert::set_state(const XMLNode& node, int version)
2511 {
2512         XMLNodeList nlist = node.children();
2513         XMLNodeIterator niter;
2514         XMLPropertyList plist;
2515         ARDOUR::PluginType type;
2516
2517         std::string str;
2518         if (!node.get_property ("type", str)) {
2519                 error << _("XML node describing plugin is missing the `type' field") << endmsg;
2520                 return -1;
2521         }
2522
2523         if (str == X_("ladspa") || str == X_("Ladspa")) { /* handle old school sessions */
2524                 type = ARDOUR::LADSPA;
2525         } else if (str == X_("lv2")) {
2526                 type = ARDOUR::LV2;
2527         } else if (str == X_("windows-vst")) {
2528                 type = ARDOUR::Windows_VST;
2529         } else if (str == X_("lxvst")) {
2530                 type = ARDOUR::LXVST;
2531         } else if (str == X_("mac-vst")) {
2532                 type = ARDOUR::MacVST;
2533         } else if (str == X_("audiounit")) {
2534                 type = ARDOUR::AudioUnit;
2535         } else if (str == X_("luaproc")) {
2536                 type = ARDOUR::Lua;
2537         } else {
2538                 error << string_compose (_("unknown plugin type %1 in plugin insert state"), str) << endmsg;
2539                 return -1;
2540         }
2541
2542         XMLProperty const * prop = node.property ("unique-id");
2543
2544         if (prop == 0) {
2545 #ifdef WINDOWS_VST_SUPPORT
2546                 /* older sessions contain VST plugins with only an "id" field.  */
2547                 if (type == ARDOUR::Windows_VST) {
2548                         prop = node.property ("id");
2549                 }
2550 #endif
2551
2552 #ifdef LXVST_SUPPORT
2553                 /*There shouldn't be any older sessions with linuxVST support.. but anyway..*/
2554                 if (type == ARDOUR::LXVST) {
2555                         prop = node.property ("id");
2556                 }
2557 #endif
2558
2559                 /* recheck  */
2560
2561                 if (prop == 0) {
2562                         error << _("Plugin has no unique ID field") << endmsg;
2563                         return -1;
2564                 }
2565         }
2566
2567         boost::shared_ptr<Plugin> plugin = find_plugin (_session, prop->value(), type);
2568         bool any_vst = false;
2569
2570         /* treat VST plugins equivalent if they have the same uniqueID
2571          * allow to move sessions windows <> linux */
2572 #ifdef LXVST_SUPPORT
2573         if (plugin == 0 && (type == ARDOUR::Windows_VST || type == ARDOUR::MacVST)) {
2574                 type = ARDOUR::LXVST;
2575                 plugin = find_plugin (_session, prop->value(), type);
2576                 if (plugin) { any_vst = true; }
2577         }
2578 #endif
2579
2580 #ifdef WINDOWS_VST_SUPPORT
2581         if (plugin == 0 && (type == ARDOUR::LXVST || type == ARDOUR::MacVST)) {
2582                 type = ARDOUR::Windows_VST;
2583                 plugin = find_plugin (_session, prop->value(), type);
2584                 if (plugin) { any_vst = true; }
2585         }
2586 #endif
2587
2588 #ifdef MACVST_SUPPORT
2589         if (plugin == 0 && (type == ARDOUR::Windows_VST || type == ARDOUR::LXVST)) {
2590                 type = ARDOUR::MacVST;
2591                 plugin = find_plugin (_session, prop->value(), type);
2592                 if (plugin) { any_vst = true; }
2593         }
2594 #endif
2595
2596         if (plugin == 0 && type == ARDOUR::Lua) {
2597                 /* unique ID (sha1 of script) was not found,
2598                  * load the plugin from the serialized version in the
2599                  * session-file instead.
2600                  */
2601                 boost::shared_ptr<LuaProc> lp (new LuaProc (_session.engine(), _session, ""));
2602                 XMLNode *ls = node.child (lp->state_node_name().c_str());
2603                 if (ls && lp) {
2604                         lp->set_script_from_state (*ls);
2605                         plugin = lp;
2606                 }
2607         }
2608
2609         if (plugin == 0) {
2610                 error << string_compose(
2611                         _("Found a reference to a plugin (\"%1\") that is unknown.\n"
2612                           "Perhaps it was removed or moved since it was last used."),
2613                         prop->value())
2614                       << endmsg;
2615                 return -1;
2616         }
2617
2618         // The name of the PluginInsert comes from the plugin, nothing else
2619         _name = plugin->get_info()->name;
2620
2621         uint32_t count = 1;
2622
2623         // Processor::set_state() will set this, but too late
2624         // for it to be available when setting up plugin
2625         // state. We can't call Processor::set_state() until
2626         // the plugins themselves are created and added.
2627
2628         set_id (node);
2629
2630         if (_plugins.empty()) {
2631                 /* if we are adding the first plugin, we will need to set
2632                    up automatable controls.
2633                 */
2634                 add_plugin (plugin);
2635                 create_automatable_parameters ();
2636                 set_control_ids (node, version);
2637         }
2638
2639         node.get_property ("count", count);
2640
2641         if (_plugins.size() != count) {
2642                 for (uint32_t n = 1; n < count; ++n) {
2643                         add_plugin (plugin_factory (plugin));
2644                 }
2645         }
2646
2647         Processor::set_state (node, version);
2648
2649         PBD::ID new_id = this->id();
2650         PBD::ID old_id = this->id();
2651
2652         node.get_property ("id", old_id);
2653
2654         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2655
2656                 /* find the node with the type-specific node name ("lv2", "ladspa", etc)
2657                    and set all plugins to the same state.
2658                 */
2659
2660                 if (   ((*niter)->name() == plugin->state_node_name())
2661                     || (any_vst && ((*niter)->name() == "lxvst" || (*niter)->name() == "windows-vst" || (*niter)->name() == "mac-vst"))
2662                    ) {
2663
2664                         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
2665                                 /* Plugin state can include external files which are named after the ID.
2666                                  *
2667                                  * If regenerate_xml_or_string_ids() is set, the ID will already have
2668                                  * been changed, so we need to use the old ID from the XML to load the
2669                                  * state and then update the ID.
2670                                  *
2671                                  * When copying a plugin-state, route_ui takes care of of updating the ID,
2672                                  * but we need to call set_insert_id() to clear the cached plugin-state
2673                                  * and force a change.
2674                                  */
2675                                 if (!regenerate_xml_or_string_ids ()) {
2676                                         (*i)->set_insert_id (new_id);
2677                                 } else {
2678                                         (*i)->set_insert_id (old_id);
2679                                 }
2680
2681                                 (*i)->set_state (**niter, version);
2682
2683                                 if (regenerate_xml_or_string_ids ()) {
2684                                         (*i)->set_insert_id (new_id);
2685                                 }
2686                         }
2687
2688                         /* when copying plugin state, notify UI */
2689                         for (Controls::const_iterator li = controls().begin(); li != controls().end(); ++li) {
2690                                 boost::shared_ptr<PBD::Controllable> c = boost::dynamic_pointer_cast<PBD::Controllable> (li->second);
2691                                 if (c) {
2692                                         c->Changed (false, Controllable::NoGroup); /* EMIT SIGNAL */
2693                                 }
2694                         }
2695
2696                         break;
2697                 }
2698         }
2699
2700         if (version < 3000) {
2701
2702                 /* Only 2.X sessions need a call to set_parameter_state() - in 3.X and above
2703                    this is all handled by Automatable
2704                 */
2705
2706                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2707                         if ((*niter)->name() == "Redirect") {
2708                                 /* XXX do we need to tackle placement? i think not (pd; oct 16 2009) */
2709                                 Processor::set_state (**niter, version);
2710                                 break;
2711                         }
2712                 }
2713
2714                 set_parameter_state_2X (node, version);
2715         }
2716
2717         node.get_property (X_("custom"), _custom_cfg);
2718
2719         uint32_t in_maps = 0;
2720         uint32_t out_maps = 0;
2721         XMLNodeList kids = node.children ();
2722         for (XMLNodeIterator i = kids.begin(); i != kids.end(); ++i) {
2723                 if ((*i)->name() == X_("ConfiguredInput")) {
2724                         _configured_in = ChanCount(**i);
2725                 }
2726                 if ((*i)->name() == X_("CustomSinks")) {
2727                         _custom_sinks = ChanCount(**i);
2728                 }
2729                 if ((*i)->name() == X_("ConfiguredOutput")) {
2730                         _custom_out = ChanCount(**i);
2731                         _configured_out = ChanCount(**i);
2732                 }
2733                 if ((*i)->name() == X_("PresetOutput")) {
2734                         _preset_out = ChanCount(**i);
2735                 }
2736                 if (strncmp ((*i)->name ().c_str(), X_("InputMap-"), 9) == 0) {
2737                         long pc = atol (&((*i)->name().c_str()[9]));
2738                         if (pc >= 0 && pc <= (long) get_count()) {
2739                                 _in_map[pc] = ChanMapping (**i);
2740                                 ++in_maps;
2741                         }
2742                 }
2743                 if (strncmp ((*i)->name ().c_str(), X_("OutputMap-"), 10) == 0) {
2744                         long pc = atol (&((*i)->name().c_str()[10]));
2745                         if (pc >= 0 && pc <= (long) get_count()) {
2746                                 _out_map[pc] = ChanMapping (**i);
2747                                 ++out_maps;
2748                         }
2749                 }
2750                 if ((*i)->name () ==  "ThruMap") {
2751                                 _thru_map = ChanMapping (**i);
2752                 }
2753
2754                 // sidechain is a Processor (IO)
2755                 if ((*i)->name () ==  Processor::state_node_name) {
2756                         if (!_sidechain) {
2757                                 if (regenerate_xml_or_string_ids ()) {
2758                                         add_sidechain_from_xml (**i, version);
2759                                 } else {
2760                                         add_sidechain (0);
2761                                 }
2762                         }
2763                         if (!regenerate_xml_or_string_ids ()) {
2764                                 _sidechain->set_state (**i, version);
2765                         } else {
2766                                 update_sidechain_name ();
2767                         }
2768                 }
2769         }
2770
2771         if (in_maps == out_maps && out_maps >0 && out_maps == get_count()) {
2772                 _maps_from_state = true;
2773         }
2774
2775         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
2776                 if (active()) {
2777                         (*i)->activate ();
2778                 } else {
2779                         (*i)->deactivate ();
2780                 }
2781         }
2782
2783         PluginConfigChanged (); /* EMIT SIGNAL */
2784         return 0;
2785 }
2786
2787 void
2788 PluginInsert::update_id (PBD::ID id)
2789 {
2790         set_id (id.to_s());
2791         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
2792                 (*i)->set_insert_id (id);
2793         }
2794 }
2795
2796 void
2797 PluginInsert::set_owner (SessionObject* o)
2798 {
2799         Processor::set_owner (o);
2800         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
2801                 (*i)->set_owner (o);
2802         }
2803 }
2804
2805 void
2806 PluginInsert::set_state_dir (const std::string& d)
2807 {
2808         // state() only saves the state of the first plugin
2809         _plugins[0]->set_state_dir (d);
2810 }
2811
2812 void
2813 PluginInsert::set_parameter_state_2X (const XMLNode& node, int version)
2814 {
2815         XMLNodeList nlist = node.children();
2816         XMLNodeIterator niter;
2817
2818         /* look for port automation node */
2819
2820         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2821
2822                 if ((*niter)->name() != port_automation_node_name) {
2823                         continue;
2824                 }
2825
2826                 XMLNodeList cnodes;
2827                 XMLNodeConstIterator iter;
2828                 XMLNode *child;
2829                 uint32_t port_id;
2830
2831                 cnodes = (*niter)->children ("port");
2832
2833                 for (iter = cnodes.begin(); iter != cnodes.end(); ++iter){
2834
2835                         child = *iter;
2836
2837                         if (!child->get_property("number", port_id)) {
2838                                 warning << _("PluginInsert: Auto: no ladspa port number") << endmsg;
2839                                 continue;
2840                         }
2841
2842                         if (port_id >= _plugins[0]->parameter_count()) {
2843                                 warning << _("PluginInsert: Auto: port id out of range") << endmsg;
2844                                 continue;
2845                         }
2846
2847                         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(
2848                                         control(Evoral::Parameter(PluginAutomation, 0, port_id), true));
2849
2850                         if (c && c->alist()) {
2851                                 if (!child->children().empty()) {
2852                                         c->alist()->set_state (*child->children().front(), version);
2853                                 }
2854                         } else {
2855                                 error << string_compose (_("PluginInsert: automatable control %1 not found - ignored"), port_id) << endmsg;
2856                         }
2857                 }
2858
2859                 /* done */
2860
2861                 break;
2862         }
2863 }
2864
2865 boost::shared_ptr<ReadOnlyControl>
2866 PluginInsert::control_output (uint32_t num) const
2867 {
2868         CtrlOutMap::const_iterator i = _control_outputs.find (num);
2869         if (i == _control_outputs.end ()) {
2870                 return boost::shared_ptr<ReadOnlyControl> ();
2871         } else {
2872                 return (*i).second;
2873         }
2874 }
2875
2876 string
2877 PluginInsert::describe_parameter (Evoral::Parameter param)
2878 {
2879         if (param.type() == PluginAutomation) {
2880                 return _plugins[0]->describe_parameter (param);
2881         } else if (param.type() == PluginPropertyAutomation) {
2882                 boost::shared_ptr<AutomationControl> c(automation_control(param));
2883                 if (c && !c->desc().label.empty()) {
2884                         return c->desc().label;
2885                 }
2886         }
2887         return Automatable::describe_parameter(param);
2888 }
2889
2890 ARDOUR::samplecnt_t
2891 PluginInsert::signal_latency() const
2892 {
2893         if (!_pending_active) {
2894                 return 0;
2895         }
2896         if (_user_latency) {
2897                 return _user_latency;
2898         }
2899
2900         return _plugins[0]->signal_latency ();
2901 }
2902
2903 ARDOUR::PluginType
2904 PluginInsert::type ()
2905 {
2906        return plugin()->get_info()->type;
2907 }
2908
2909 PluginInsert::PluginControl::PluginControl (PluginInsert*                     p,
2910                                             const Evoral::Parameter&          param,
2911                                             const ParameterDescriptor&        desc,
2912                                             boost::shared_ptr<AutomationList> list)
2913         : AutomationControl (p->session(), param, desc, list, p->describe_parameter(param))
2914         , _plugin (p)
2915 {
2916         if (alist()) {
2917                 if (desc.toggled) {
2918                         list->set_interpolation(Evoral::ControlList::Discrete);
2919                 }
2920         }
2921 }
2922
2923 /** @param val `user' value */
2924
2925 void
2926 PluginInsert::PluginControl::actually_set_value (double user_val, PBD::Controllable::GroupControlDisposition group_override)
2927 {
2928         /* FIXME: probably should be taking out some lock here.. */
2929
2930         for (Plugins::iterator i = _plugin->_plugins.begin(); i != _plugin->_plugins.end(); ++i) {
2931                 (*i)->set_parameter (_list->parameter().id(), user_val);
2932         }
2933
2934         boost::shared_ptr<Plugin> iasp = _plugin->_impulseAnalysisPlugin.lock();
2935         if (iasp) {
2936                 iasp->set_parameter (_list->parameter().id(), user_val);
2937         }
2938
2939         AutomationControl::actually_set_value (user_val, group_override);
2940 }
2941
2942 void
2943 PluginInsert::PluginControl::catch_up_with_external_value (double user_val)
2944 {
2945         AutomationControl::actually_set_value (user_val, Controllable::NoGroup);
2946 }
2947
2948 XMLNode&
2949 PluginInsert::PluginControl::get_state ()
2950 {
2951         XMLNode& node (AutomationControl::get_state());
2952         node.set_property (X_("parameter"), parameter().id());
2953 #ifdef LV2_SUPPORT
2954         boost::shared_ptr<LV2Plugin> lv2plugin = boost::dynamic_pointer_cast<LV2Plugin> (_plugin->_plugins[0]);
2955         if (lv2plugin) {
2956                 node.set_property (X_("symbol"), lv2plugin->port_symbol (parameter().id()));
2957         }
2958 #endif
2959
2960         return node;
2961 }
2962
2963 /** @return `user' val */
2964 double
2965 PluginInsert::PluginControl::get_value () const
2966 {
2967         boost::shared_ptr<Plugin> plugin = _plugin->plugin (0);
2968
2969         if (!plugin) {
2970                 return 0.0;
2971         }
2972
2973         return plugin->get_parameter (_list->parameter().id());
2974 }
2975
2976 PluginInsert::PluginPropertyControl::PluginPropertyControl (PluginInsert*                     p,
2977                                                             const Evoral::Parameter&          param,
2978                                                             const ParameterDescriptor&        desc,
2979                                                             boost::shared_ptr<AutomationList> list)
2980         : AutomationControl (p->session(), param, desc, list)
2981         , _plugin (p)
2982 {
2983 }
2984
2985 void
2986 PluginInsert::PluginPropertyControl::actually_set_value (double user_val, Controllable::GroupControlDisposition gcd)
2987 {
2988         /* Old numeric set_value(), coerce to appropriate datatype if possible.
2989            This is lossy, but better than nothing until Ardour's automation system
2990            can handle various datatypes all the way down. */
2991         const Variant value(_desc.datatype, user_val);
2992         if (value.type() == Variant::NOTHING) {
2993                 error << "set_value(double) called for non-numeric property" << endmsg;
2994                 return;
2995         }
2996
2997         for (Plugins::iterator i = _plugin->_plugins.begin(); i != _plugin->_plugins.end(); ++i) {
2998                 (*i)->set_property(_list->parameter().id(), value);
2999         }
3000
3001         _value = value;
3002
3003         AutomationControl::actually_set_value (user_val, gcd);
3004 }
3005
3006 XMLNode&
3007 PluginInsert::PluginPropertyControl::get_state ()
3008 {
3009         XMLNode& node (AutomationControl::get_state());
3010         node.set_property (X_("property"), parameter().id());
3011         node.remove_property (X_("value"));
3012
3013         return node;
3014 }
3015
3016 double
3017 PluginInsert::PluginPropertyControl::get_value () const
3018 {
3019         return _value.to_double();
3020 }
3021
3022 boost::shared_ptr<Plugin>
3023 PluginInsert::get_impulse_analysis_plugin()
3024 {
3025         boost::shared_ptr<Plugin> ret;
3026         if (_impulseAnalysisPlugin.expired()) {
3027                 // LV2 in particular uses various _session params
3028                 // during init() -- most notably block_size..
3029                 // not great.
3030                 ret = plugin_factory(_plugins[0]);
3031                 ChanCount out (internal_output_streams ());
3032                 if (ret->get_info ()->reconfigurable_io ()) {
3033                         // populate get_info ()->n_inputs and ->n_outputs
3034                         ChanCount useins;
3035                         ret->can_support_io_configuration (internal_input_streams (), out, &useins);
3036                         assert (out == internal_output_streams ());
3037                 }
3038                 ret->configure_io (internal_input_streams (), out);
3039                 ret->set_owner (_owner);
3040                 _impulseAnalysisPlugin = ret;
3041         } else {
3042                 ret = _impulseAnalysisPlugin.lock();
3043         }
3044
3045         return ret;
3046 }
3047
3048 void
3049 PluginInsert::collect_signal_for_analysis (samplecnt_t nframes)
3050 {
3051         // called from outside the audio thread, so this should be safe
3052         // only do audio as analysis is (currently) only for audio plugins
3053         _signal_analysis_inputs.ensure_buffers (DataType::AUDIO, input_streams().n_audio(),  nframes);
3054         _signal_analysis_outputs.ensure_buffers (DataType::AUDIO, output_streams().n_audio(), nframes);
3055
3056         _signal_analysis_collected_nframes   = 0;
3057         _signal_analysis_collect_nframes_max = nframes;
3058 }
3059
3060 /** Add a plugin to our list */
3061 void
3062 PluginInsert::add_plugin (boost::shared_ptr<Plugin> plugin)
3063 {
3064         plugin->set_insert_id (this->id());
3065         plugin->set_owner (_owner);
3066
3067         if (_plugins.empty()) {
3068                 /* first (and probably only) plugin instance - connect to relevant signals */
3069
3070                 plugin->ParameterChangedExternally.connect_same_thread (*this, boost::bind (&PluginInsert::parameter_changed_externally, this, _1, _2));
3071                 plugin->StartTouch.connect_same_thread (*this, boost::bind (&PluginInsert::start_touch, this, _1));
3072                 plugin->EndTouch.connect_same_thread (*this, boost::bind (&PluginInsert::end_touch, this, _1));
3073                 _custom_sinks = plugin->get_info()->n_inputs;
3074                 // cache sidechain port count
3075                 _cached_sidechain_pins.reset ();
3076                 const ChanCount& nis (plugin->get_info()->n_inputs);
3077                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3078                         for (uint32_t in = 0; in < nis.get (*t); ++in) {
3079                                 const Plugin::IOPortDescription& iod (plugin->describe_io_port (*t, true, in));
3080                                 if (iod.is_sidechain) {
3081                                         _cached_sidechain_pins.set (*t, 1 + _cached_sidechain_pins.n(*t));
3082                                 }
3083                         }
3084                 }
3085         }
3086 #if (defined WINDOWS_VST_SUPPORT || defined LXVST_SUPPORT || defined MACVST_SUPPORT)
3087         boost::shared_ptr<VSTPlugin> vst = boost::dynamic_pointer_cast<VSTPlugin> (plugin);
3088         if (vst) {
3089                 vst->set_insert (this, _plugins.size ());
3090         }
3091 #endif
3092
3093         _plugins.push_back (plugin);
3094 }
3095
3096 void
3097 PluginInsert::add_sidechain_from_xml (const XMLNode& node, int version)
3098 {
3099         if (version < 3000) {
3100                 return;
3101         }
3102
3103         XMLNodeList nlist = node.children();
3104
3105         if (nlist.size() == 0) {
3106                 return;
3107         }
3108
3109         uint32_t audio = 0;
3110         uint32_t midi = 0;
3111
3112         XMLNodeConstIterator it = nlist.front()->children().begin();
3113         for ( ; it != nlist.front()->children().end(); ++ it) {
3114                 if ((*it)->name() == "Port") {
3115                         DataType type(DataType::NIL);
3116                         (*it)->get_property ("type", type);
3117                         if (type == DataType::AUDIO) {
3118                                 ++audio;
3119                         } else if (type == DataType::MIDI) {
3120                                 ++midi;
3121                         }
3122                 }
3123         }
3124
3125         ChanCount in_cc = ChanCount();
3126         in_cc.set (DataType::AUDIO, audio);
3127         in_cc.set (DataType::MIDI, midi);
3128
3129         add_sidechain (audio, midi);
3130 }
3131
3132 bool
3133 PluginInsert::load_preset (ARDOUR::Plugin::PresetRecord pr)
3134 {
3135         bool ok = true;
3136         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
3137                 if (! (*i)->load_preset (pr)) {
3138                         ok = false;
3139                 }
3140         }
3141         return ok;
3142 }
3143
3144 void
3145 PluginInsert::realtime_handle_transport_stopped ()
3146 {
3147         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
3148                 (*i)->realtime_handle_transport_stopped ();
3149         }
3150 }
3151
3152 void
3153 PluginInsert::realtime_locate ()
3154 {
3155         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
3156                 (*i)->realtime_locate ();
3157         }
3158 }
3159
3160 void
3161 PluginInsert::monitoring_changed ()
3162 {
3163         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
3164                 (*i)->monitoring_changed ();
3165         }
3166 }
3167
3168 void
3169 PluginInsert::latency_changed ()
3170 {
3171         // this is called in RT context, LatencyChanged is emitted after run()
3172         _latency_changed = true;
3173         // XXX This also needs a proper API not an owner() hack.
3174         assert (owner ());
3175         static_cast<Route*>(owner ())->processor_latency_changed (); /* EMIT SIGNAL */
3176 }
3177
3178 void
3179 PluginInsert::start_touch (uint32_t param_id)
3180 {
3181         boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter (PluginAutomation, 0, param_id));
3182         if (ac) {
3183                 // ToDo subtract _plugin_signal_latency  from audible_sample() when rolling, assert > 0
3184                 ac->start_touch (session().audible_sample());
3185         }
3186 }
3187
3188 void
3189 PluginInsert::end_touch (uint32_t param_id)
3190 {
3191         boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter (PluginAutomation, 0, param_id));
3192         if (ac) {
3193                 // ToDo subtract _plugin_signal_latency  from audible_sample() when rolling, assert > 0
3194                 ac->stop_touch (session().audible_sample());
3195         }
3196 }
3197
3198 bool
3199 PluginInsert::get_stats (uint64_t& min, uint64_t& max, double& avg, double& dev) const
3200 {
3201         /* TODO: consider taking a try/lock: Don't run concurrently with
3202          * TimingStats::update, TimingStats::reset.
3203          */
3204         return _timing_stats.get_stats (min, max, avg, dev);
3205 }
3206
3207 void
3208 PluginInsert::clear_stats ()
3209 {
3210         g_atomic_int_set (&_stat_reset, 1);
3211 }
3212
3213 std::ostream& operator<<(std::ostream& o, const ARDOUR::PluginInsert::Match& m)
3214 {
3215         switch (m.method) {
3216                 case PluginInsert::Impossible: o << "Impossible"; break;
3217                 case PluginInsert::Delegate:   o << "Delegate"; break;
3218                 case PluginInsert::NoInputs:   o << "NoInputs"; break;
3219                 case PluginInsert::ExactMatch: o << "ExactMatch"; break;
3220                 case PluginInsert::Replicate:  o << "Replicate"; break;
3221                 case PluginInsert::Split:      o << "Split"; break;
3222                 case PluginInsert::Hide:       o << "Hide"; break;
3223         }
3224         o << " cnt: " << m.plugins
3225                 << (m.strict_io ? " strict-io" : "")
3226                 << (m.custom_cfg ? " custom-cfg" : "");
3227         if (m.method == PluginInsert::Hide) {
3228                 o << " hide: " << m.hide;
3229         }
3230         o << "\n";
3231         return o;
3232 }