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