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