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