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