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