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