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