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