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