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