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