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