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