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