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