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