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