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