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