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