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