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