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