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