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