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