fix ChanCount min/max
[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         , _pending_no_inplace (false)
76 {
77         /* the first is the master */
78
79         if (plug) {
80                 add_plugin (plug);
81                 create_automatable_parameters ();
82         }
83 }
84
85 PluginInsert::~PluginInsert ()
86 {
87 }
88
89 bool
90 PluginInsert::set_count (uint32_t num)
91 {
92         bool require_state = !_plugins.empty();
93
94         /* this is a bad idea.... we shouldn't do this while active.
95            only a route holding their redirect_lock should be calling this
96         */
97
98         if (num == 0) {
99                 return false;
100         } else if (num > _plugins.size()) {
101                 uint32_t diff = num - _plugins.size();
102
103                 for (uint32_t n = 0; n < diff; ++n) {
104                         boost::shared_ptr<Plugin> p = plugin_factory (_plugins[0]);
105                         add_plugin (p);
106                         if (active ()) {
107                                 p->activate ();
108                         }
109
110                         if (require_state) {
111                                 /* XXX do something */
112                         }
113                 }
114
115         } else if (num < _plugins.size()) {
116                 uint32_t diff = _plugins.size() - num;
117                 for (uint32_t n= 0; n < diff; ++n) {
118                         _plugins.pop_back();
119                 }
120         }
121
122         return true;
123 }
124
125
126 void
127 PluginInsert::set_outputs (const ChanCount& c)
128 {
129         _custom_out = c;
130 }
131
132 void
133 PluginInsert::control_list_automation_state_changed (Evoral::Parameter which, AutoState s)
134 {
135         if (which.type() != PluginAutomation)
136                 return;
137
138         boost::shared_ptr<AutomationControl> c
139                         = boost::dynamic_pointer_cast<AutomationControl>(control (which));
140
141         if (c && s != Off) {
142                 _plugins[0]->set_parameter (which.id(), c->list()->eval (_session.transport_frame()));
143         }
144 }
145
146 ChanCount
147 PluginInsert::output_streams() const
148 {
149         assert (_configured);
150         return _configured_out;
151 }
152
153 ChanCount
154 PluginInsert::input_streams() const
155 {
156         assert (_configured);
157         return _configured_in;
158 }
159
160 ChanCount
161 PluginInsert::internal_output_streams() const
162 {
163         assert (!_plugins.empty());
164
165         PluginInfoPtr info = _plugins.front()->get_info();
166
167         if (info->reconfigurable_io()) {
168                 ChanCount out = _plugins.front()->output_streams ();
169                 // DEBUG_TRACE (DEBUG::Processors, string_compose ("Plugin insert, reconfigur(able) output streams = %1\n", out));
170                 return out;
171         } else {
172                 ChanCount out = info->n_outputs;
173                 // DEBUG_TRACE (DEBUG::Processors, string_compose ("Plugin insert, static output streams = %1 for %2 plugins\n", out, _plugins.size()));
174                 out.set_audio (out.n_audio() * _plugins.size());
175                 out.set_midi (out.n_midi() * _plugins.size());
176                 return out;
177         }
178 }
179
180 ChanCount
181 PluginInsert::internal_input_streams() const
182 {
183         assert (!_plugins.empty());
184
185         ChanCount in;
186
187         PluginInfoPtr info = _plugins.front()->get_info();
188
189         if (info->reconfigurable_io()) {
190                 assert (_plugins.size() == 1);
191                 in = _plugins.front()->input_streams();
192         } else {
193                 in = info->n_inputs;
194         }
195
196         DEBUG_TRACE (DEBUG::Processors, string_compose ("Plugin insert, input streams = %1, match using %2\n", in, _match.method));
197
198         if (_match.method == Split) {
199
200                 /* we are splitting 1 processor input to multiple plugin inputs,
201                    so we have a maximum of 1 stream of each type.
202                 */
203                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
204                         if (in.get (*t) > 1) {
205                                 in.set (*t, 1);
206                         }
207                 }
208                 return in;
209
210         } else if (_match.method == Hide) {
211
212                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
213                         in.set (*t, in.get (*t) - _match.hide.get (*t));
214                 }
215                 return in;
216
217         } else {
218
219                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
220                         in.set (*t, in.get (*t) * _plugins.size ());
221                 }
222
223                 return in;
224         }
225 }
226
227 ChanCount
228 PluginInsert::natural_output_streams() const
229 {
230         return _plugins[0]->get_info()->n_outputs;
231 }
232
233 ChanCount
234 PluginInsert::natural_input_streams() const
235 {
236         return _plugins[0]->get_info()->n_inputs;
237 }
238
239 bool
240 PluginInsert::has_no_inputs() const
241 {
242         return _plugins[0]->get_info()->n_inputs == ChanCount::ZERO;
243 }
244
245 bool
246 PluginInsert::has_no_audio_inputs() const
247 {
248         return _plugins[0]->get_info()->n_inputs.n_audio() == 0;
249 }
250
251 bool
252 PluginInsert::is_midi_instrument() const
253 {
254         /* XXX more finesse is possible here. VST plugins have a
255            a specific "instrument" flag, for example.
256          */
257         PluginInfoPtr pi = _plugins[0]->get_info();
258
259         return pi->n_inputs.n_midi() != 0 &&
260                 pi->n_outputs.n_audio() > 0;
261 }
262
263 void
264 PluginInsert::create_automatable_parameters ()
265 {
266         assert (!_plugins.empty());
267
268         set<Evoral::Parameter> a = _plugins.front()->automatable ();
269
270         for (set<Evoral::Parameter>::iterator i = a.begin(); i != a.end(); ++i) {
271                 if (i->type() == PluginAutomation) {
272
273                         Evoral::Parameter param(*i);
274
275                         ParameterDescriptor desc;
276                         _plugins.front()->get_parameter_descriptor(i->id(), desc);
277
278                         can_automate (param);
279                         boost::shared_ptr<AutomationList> list(new AutomationList(param, desc));
280                         boost::shared_ptr<AutomationControl> c (new PluginControl(this, param, desc, list));
281                         add_control (c);
282                         _plugins.front()->set_automation_control (i->id(), c);
283                 } else if (i->type() == PluginPropertyAutomation) {
284                         Evoral::Parameter param(*i);
285                         const ParameterDescriptor& desc = _plugins.front()->get_property_descriptor(param.id());
286                         if (desc.datatype != Variant::NOTHING) {
287                                 boost::shared_ptr<AutomationList> list;
288                                 if (Variant::type_is_numeric(desc.datatype)) {
289                                         list = boost::shared_ptr<AutomationList>(new AutomationList(param, desc));
290                                 }
291                                 add_control (boost::shared_ptr<AutomationControl> (new PluginPropertyControl(this, param, desc, list)));
292                         }
293                 }
294         }
295 }
296 /** Called when something outside of this host has modified a plugin
297  * parameter. Responsible for propagating the change to two places:
298  *
299  *   1) anything listening to the Control itself
300  *   2) any replicated plugins that make up this PluginInsert.
301  *
302  * The PluginInsert is connected to the ParameterChangedExternally signal for
303  * the first (primary) plugin, and here broadcasts that change to any others.
304  *
305  * XXX We should probably drop this whole replication idea (Paul, October 2015)
306  * since it isn't used by sensible plugin APIs (AU, LV2).
307  */
308 void
309 PluginInsert::parameter_changed_externally (uint32_t which, float val)
310 {
311         boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter (PluginAutomation, 0, which));
312
313         /* First propagation: alter the underlying value of the control,
314          * without telling the plugin(s) that own/use it to set it.
315          */
316
317         if (!ac) {
318                 return;
319         }
320
321         boost::shared_ptr<PluginControl> pc = boost::dynamic_pointer_cast<PluginControl> (ac);
322
323         if (pc) {
324                 pc->catch_up_with_external_value (val);
325         }
326
327         /* Second propagation: tell all plugins except the first to
328            update the value of this parameter. For sane plugin APIs,
329            there are no other plugins, so this is a no-op in those
330            cases.
331         */
332
333         Plugins::iterator i = _plugins.begin();
334
335         /* don't set the first plugin, just all the slaves */
336
337         if (i != _plugins.end()) {
338                 ++i;
339                 for (; i != _plugins.end(); ++i) {
340                         (*i)->set_parameter (which, val);
341                 }
342         }
343 }
344
345 int
346 PluginInsert::set_block_size (pframes_t nframes)
347 {
348         int ret = 0;
349         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
350                 if ((*i)->set_block_size (nframes) != 0) {
351                         ret = -1;
352                 }
353         }
354         return ret;
355 }
356
357 void
358 PluginInsert::activate ()
359 {
360         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
361                 (*i)->activate ();
362         }
363
364         Processor::activate ();
365 }
366
367 void
368 PluginInsert::deactivate ()
369 {
370         Processor::deactivate ();
371
372         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
373                 (*i)->deactivate ();
374         }
375 }
376
377 void
378 PluginInsert::flush ()
379 {
380         for (vector<boost::shared_ptr<Plugin> >::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
381                 (*i)->flush ();
382         }
383 }
384
385 void
386 PluginInsert::connect_and_run (BufferSet& bufs, pframes_t nframes, framecnt_t offset, bool with_auto, framepos_t now)
387 {
388         PinMappings in_map (_in_map);
389         PinMappings out_map (_out_map);
390
391 #if 1
392         // auto-detect if inplace processing is possible
393         // TODO: do this once. during configure_io and every time the
394         // plugin-count or mapping changes.
395         bool inplace_ok = true;
396         for (uint32_t pc = 0; pc < get_count() && inplace_ok ; ++pc) {
397                 if (!in_map[pc].is_monotonic ()) {
398                         inplace_ok = false;
399                 }
400                 if (!out_map[pc].is_monotonic ()) {
401                         inplace_ok = false;
402                 }
403         }
404
405         if (_pending_no_inplace != !inplace_ok) {
406 #ifndef NDEBUG // this 'cerr' needs to go ASAP.
407                 cerr << name () << " automatically set : " << (inplace_ok ? "Use Inplace" : "No Inplace") << "\n"; // XXX
408 #endif
409                 _pending_no_inplace = !inplace_ok;
410         }
411 #endif
412
413         _no_inplace = _pending_no_inplace || _plugins.front()->inplace_broken ();
414
415
416 #if 1
417         // TODO optimize special case.
418         // Currently this never triggers because the in_map for "Split" triggeres no_inplace.
419         if (_match.method == Split && !_no_inplace) {
420                 assert (in_map.size () == 1);
421                 in_map[0] = ChanMapping (ChanCount::max (natural_input_streams (), _configured_in));
422                 ChanCount const in_streams = internal_input_streams ();
423                 /* copy the first stream's audio buffer contents to the others */
424                 bool valid;
425                 uint32_t first_idx = in_map[0].get (DataType::AUDIO, 0, &valid);
426                 if (valid) {
427                         for (uint32_t i = in_streams.n_audio(); i < natural_input_streams().n_audio(); ++i) {
428                                 uint32_t idx = in_map[0].get (DataType::AUDIO, i, &valid);
429                                 if (valid) {
430                                         bufs.get_audio(idx).read_from(bufs.get_audio(first_idx), nframes, offset, offset);
431                                 }
432                         }
433                 }
434         }
435 #endif
436
437         bufs.set_count(ChanCount::max(bufs.count(), _configured_in));
438         bufs.set_count(ChanCount::max(bufs.count(), _configured_out));
439
440         if (with_auto) {
441
442                 uint32_t n = 0;
443
444                 for (Controls::iterator li = controls().begin(); li != controls().end(); ++li, ++n) {
445
446                         boost::shared_ptr<AutomationControl> c
447                                 = boost::dynamic_pointer_cast<AutomationControl>(li->second);
448
449                         if (c->list() && c->automation_playback()) {
450                                 bool valid;
451
452                                 const float val = c->list()->rt_safe_eval (now, valid);
453
454                                 if (valid) {
455                                         /* This is the ONLY place where we are
456                                          *  allowed to call
457                                          *  AutomationControl::set_value_unchecked(). We
458                                          *  know that the control is in
459                                          *  automation playback mode, so no
460                                          *  check on writable() is required
461                                          *  (which must be done in AutomationControl::set_value()
462                                          *
463                                          */
464                                         c->set_value_unchecked(val);
465                                 }
466
467                         }
468                 }
469         }
470
471         /* Calculate if, and how many frames we need to collect for analysis */
472         framecnt_t collect_signal_nframes = (_signal_analysis_collect_nframes_max -
473                                              _signal_analysis_collected_nframes);
474         if (nframes < collect_signal_nframes) { // we might not get all frames now
475                 collect_signal_nframes = nframes;
476         }
477
478         if (collect_signal_nframes > 0) {
479                 // collect input
480                 //std::cerr << "collect input, bufs " << bufs.count().n_audio() << " count,  " << bufs.available().n_audio() << " available" << std::endl;
481                 //std::cerr << "               streams " << internal_input_streams().n_audio() << std::endl;
482                 //std::cerr << "filling buffer with " << collect_signal_nframes << " frames at " << _signal_analysis_collected_nframes << std::endl;
483
484                 _signal_analysis_inputs.set_count(internal_input_streams());
485
486                 for (uint32_t i = 0; i < internal_input_streams().n_audio(); ++i) {
487                         _signal_analysis_inputs.get_audio(i).read_from(
488                                 bufs.get_audio(i),
489                                 collect_signal_nframes,
490                                 _signal_analysis_collected_nframes); // offset is for target buffer
491                 }
492
493         }
494 #ifdef MIXBUS
495         if (_plugins.front()->is_channelstrip() ) {
496                 if (_configured_in.n_audio() > 0) {
497                         ChanMapping mb_in_map (ChanCount::min (_configured_in, ChanCount (DataType::AUDIO, 2)));
498                         ChanMapping mb_out_map (ChanCount::min (_configured_out, ChanCount (DataType::AUDIO, 2)));
499
500                         _plugins.front()->connect_and_run (bufs, mb_in_map, mb_out_map, nframes, offset);
501
502                         for (uint32_t out = _configured_in.n_audio; out < bufs.count().get (DataType::AUDIO); ++out) {
503                                 bufs.get (DataType::AUDIO, out).silence (nframes, offset);
504                         }
505                 }
506         } else
507 #endif
508         if (_no_inplace) {
509                 BufferSet& inplace_bufs  = _session.get_noinplace_buffers();
510                 ARDOUR::ChanMapping used_outputs;
511
512                 uint32_t pc = 0;
513                 // TODO optimize this flow. prepare during configure_io()
514                 for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i, ++pc) {
515
516                         ARDOUR::ChanMapping i_in_map (natural_input_streams());
517                         ARDOUR::ChanMapping i_out_map;
518                         ARDOUR::ChanCount mapped;
519                         ARDOUR::ChanCount backmap;
520
521                         // map inputs sequentially
522                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
523                                 for (uint32_t in = 0; in < natural_input_streams().get (*t); ++in) {
524                                         bool valid;
525                                         uint32_t in_idx = in_map[pc].get (*t, in, &valid);
526                                         uint32_t m = mapped.get (*t);
527                                         if (valid) {
528                                                 inplace_bufs.get (*t, m).read_from (bufs.get (*t, in_idx), nframes, offset, offset);
529                                         } else {
530                                                 inplace_bufs.get (*t, m).silence (nframes, offset);
531                                         }
532                                         mapped.set (*t, m + 1);
533                                 }
534                         }
535
536                         // TODO use map_offset_to()  instead ??
537                         backmap = mapped;
538
539                         // map outputs
540                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
541                                 for (uint32_t out = 0; out < natural_output_streams().get (*t); ++out) {
542                                         uint32_t m = mapped.get (*t);
543                                         inplace_bufs.get (*t, m).silence (nframes, offset);
544                                         i_out_map.set (*t, out, m);
545                                         mapped.set (*t, m + 1);
546                                 }
547                         }
548
549                         if ((*i)->connect_and_run(inplace_bufs, i_in_map, i_out_map, nframes, offset)) {
550                                 deactivate ();
551                         }
552
553                         // copy back outputs
554                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
555                                 for (uint32_t out = 0; out < natural_output_streams().get (*t); ++out) {
556                                         uint32_t m = backmap.get (*t);
557                                         bool valid;
558                                         uint32_t out_idx = out_map[pc].get (*t, out, &valid);
559                                         if (valid) {
560                                                 bufs.get (*t, out_idx).read_from (inplace_bufs.get (*t, m), nframes, offset, offset);
561                                                 used_outputs.set (*t, out_idx, 1); // mark as used
562                                         }
563                                         backmap.set (*t, m + 1);
564                                 }
565                         }
566                 }
567                 /* all instances have completed, now clear outputs that have not been written to.
568                  * (except midi bypass)
569                  */
570                 if (bufs.count().n_midi() == 1 && natural_output_streams().get(DataType::MIDI) == 0) {
571                         used_outputs.set (DataType::MIDI, 0, 1); // Midi bypass.
572                 }
573                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
574                         for (uint32_t out = 0; out < bufs.count().get (*t); ++out) {
575                                 bool valid;
576                                 used_outputs.get (*t, out, &valid);
577                                 if (valid) { continue; }
578                                 bufs.get (*t, out).silence (nframes, offset);
579                         }
580                 }
581
582         } else {
583                 uint32_t pc = 0;
584                 for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i, ++pc) {
585                         if ((*i)->connect_and_run(bufs, in_map[pc], out_map[pc], nframes, offset)) {
586                                 deactivate ();
587                         }
588                 }
589
590                 // TODO optimize: store "unconnected" in a fixed set.
591                 // it only changes on reconfiguration.
592                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
593                         for (uint32_t out = 0; out < bufs.count().get (*t); ++out) {
594                                 bool mapped = false;
595                                 for (uint32_t pc = 0; pc < get_count() && !mapped; ++pc) {
596                                         for (uint32_t o = 0; o < natural_output_streams().get (*t); ++o) {
597                                                 bool valid;
598                                                 uint32_t idx = out_map[pc].get (*t, o, &valid);
599                                                 if (valid && idx == out) {
600                                                         mapped = true;
601                                                         break;
602                                                 }
603                                         }
604                                 }
605                                 if (!mapped) {
606                                         bufs.get (*t, out).silence (nframes, offset);
607                                 }
608                         }
609                 }
610         }
611
612         if (collect_signal_nframes > 0) {
613                 // collect output
614                 //std::cerr << "       output, bufs " << bufs.count().n_audio() << " count,  " << bufs.available().n_audio() << " available" << std::endl;
615                 //std::cerr << "               streams " << internal_output_streams().n_audio() << std::endl;
616
617                 _signal_analysis_outputs.set_count(internal_output_streams());
618
619                 for (uint32_t i = 0; i < internal_output_streams().n_audio(); ++i) {
620                         _signal_analysis_outputs.get_audio(i).read_from(
621                                 bufs.get_audio(i),
622                                 collect_signal_nframes,
623                                 _signal_analysis_collected_nframes); // offset is for target buffer
624                 }
625
626                 _signal_analysis_collected_nframes += collect_signal_nframes;
627                 assert(_signal_analysis_collected_nframes <= _signal_analysis_collect_nframes_max);
628
629                 if (_signal_analysis_collected_nframes == _signal_analysis_collect_nframes_max) {
630                         _signal_analysis_collect_nframes_max = 0;
631                         _signal_analysis_collected_nframes   = 0;
632
633                         AnalysisDataGathered(&_signal_analysis_inputs,
634                                              &_signal_analysis_outputs);
635                 }
636         }
637 }
638
639 void
640 PluginInsert::silence (framecnt_t nframes)
641 {
642         if (!active ()) {
643                 return;
644         }
645
646         ChanMapping in_map (natural_input_streams ());
647         ChanMapping out_map (natural_output_streams ());
648
649         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
650                 (*i)->connect_and_run (_session.get_scratch_buffers ((*i)->get_info()->n_inputs, true), in_map, out_map, nframes, 0);
651         }
652 }
653
654 void
655 PluginInsert::run (BufferSet& bufs, framepos_t start_frame, framepos_t /*end_frame*/, pframes_t nframes, bool)
656 {
657         if (_pending_active) {
658                 /* run as normal if we are active or moving from inactive to active */
659
660                 if (_session.transport_rolling() || _session.bounce_processing()) {
661                         automation_run (bufs, start_frame, nframes);
662                 } else {
663                         connect_and_run (bufs, nframes, 0, false);
664                 }
665
666         } else {
667                 // TODO use mapping in bypassed mode ?!
668                 // -> do we bypass the processor or the plugin
669
670                 uint32_t in = input_streams ().n_audio ();
671                 uint32_t out = output_streams().n_audio ();
672
673                 if (has_no_audio_inputs() || in == 0) {
674
675                         /* silence all (audio) outputs. Should really declick
676                          * at the transitions of "active"
677                          */
678
679                         for (uint32_t n = 0; n < out; ++n) {
680                                 bufs.get_audio (n).silence (nframes);
681                         }
682
683                 } else if (out > in) {
684
685                         /* not active, but something has make up for any channel count increase
686                          * for now , simply replicate last buffer
687                          */
688                         for (uint32_t n = in; n < out; ++n) {
689                                 bufs.get_audio(n).read_from(bufs.get_audio(in - 1), nframes);
690                         }
691                 }
692
693                 bufs.count().set_audio (out);
694         }
695
696         _active = _pending_active;
697
698         /* we have no idea whether the plugin generated silence or not, so mark
699          * all buffers appropriately.
700          */
701 }
702
703 void
704 PluginInsert::automation_run (BufferSet& bufs, framepos_t start, pframes_t nframes)
705 {
706         Evoral::ControlEvent next_event (0, 0.0f);
707         framepos_t now = start;
708         framepos_t end = now + nframes;
709         framecnt_t offset = 0;
710
711         Glib::Threads::Mutex::Lock lm (control_lock(), Glib::Threads::TRY_LOCK);
712
713         if (!lm.locked()) {
714                 connect_and_run (bufs, nframes, offset, false);
715                 return;
716         }
717
718         if (!find_next_event (now, end, next_event) || _plugins.front()->requires_fixed_sized_buffers()) {
719
720                 /* no events have a time within the relevant range */
721
722                 connect_and_run (bufs, nframes, offset, true, now);
723                 return;
724         }
725
726         while (nframes) {
727
728                 framecnt_t cnt = min (((framecnt_t) ceil (next_event.when) - now), (framecnt_t) nframes);
729
730                 connect_and_run (bufs, cnt, offset, true, now);
731
732                 nframes -= cnt;
733                 offset += cnt;
734                 now += cnt;
735
736                 if (!find_next_event (now, end, next_event)) {
737                         break;
738                 }
739         }
740
741         /* cleanup anything that is left to do */
742
743         if (nframes) {
744                 connect_and_run (bufs, nframes, offset, true, now);
745         }
746 }
747
748 float
749 PluginInsert::default_parameter_value (const Evoral::Parameter& param)
750 {
751         if (param.type() != PluginAutomation)
752                 return 1.0;
753
754         if (_plugins.empty()) {
755                 fatal << _("programming error: ") << X_("PluginInsert::default_parameter_value() called with no plugin")
756                       << endmsg;
757                 abort(); /*NOTREACHED*/
758         }
759
760         return _plugins[0]->default_value (param.id());
761 }
762
763
764 bool
765 PluginInsert::can_reset_all_parameters ()
766 {
767         bool all = true;
768         uint32_t params = 0;
769         for (uint32_t par = 0; par < _plugins[0]->parameter_count(); ++par) {
770                 bool ok=false;
771                 const uint32_t cid = _plugins[0]->nth_parameter (par, ok);
772
773                 if (!ok || !_plugins[0]->parameter_is_input(cid)) {
774                         continue;
775                 }
776
777                 boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter(PluginAutomation, 0, cid));
778                 if (!ac) {
779                         continue;
780                 }
781
782                 ++params;
783                 if (ac->automation_state() & Play) {
784                         all = false;
785                         break;
786                 }
787         }
788         return all && (params > 0);
789 }
790
791 bool
792 PluginInsert::reset_parameters_to_default ()
793 {
794         bool all = true;
795
796         for (uint32_t par = 0; par < _plugins[0]->parameter_count(); ++par) {
797                 bool ok=false;
798                 const uint32_t cid = _plugins[0]->nth_parameter (par, ok);
799
800                 if (!ok || !_plugins[0]->parameter_is_input(cid)) {
801                         continue;
802                 }
803
804                 const float dflt = _plugins[0]->default_value (cid);
805                 const float curr = _plugins[0]->get_parameter (cid);
806
807                 if (dflt == curr) {
808                         continue;
809                 }
810
811                 boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter(PluginAutomation, 0, cid));
812                 if (!ac) {
813                         continue;
814                 }
815
816                 if (ac->automation_state() & Play) {
817                         all = false;
818                         continue;
819                 }
820
821                 ac->set_value (dflt, Controllable::NoGroup);
822         }
823         return all;
824 }
825
826 boost::shared_ptr<Plugin>
827 PluginInsert::plugin_factory (boost::shared_ptr<Plugin> other)
828 {
829         boost::shared_ptr<LadspaPlugin> lp;
830         boost::shared_ptr<LuaProc> lua;
831 #ifdef LV2_SUPPORT
832         boost::shared_ptr<LV2Plugin> lv2p;
833 #endif
834 #ifdef WINDOWS_VST_SUPPORT
835         boost::shared_ptr<WindowsVSTPlugin> vp;
836 #endif
837 #ifdef LXVST_SUPPORT
838         boost::shared_ptr<LXVSTPlugin> lxvp;
839 #endif
840 #ifdef AUDIOUNIT_SUPPORT
841         boost::shared_ptr<AUPlugin> ap;
842 #endif
843
844         if ((lp = boost::dynamic_pointer_cast<LadspaPlugin> (other)) != 0) {
845                 return boost::shared_ptr<Plugin> (new LadspaPlugin (*lp));
846         } else if ((lua = boost::dynamic_pointer_cast<LuaProc> (other)) != 0) {
847                 return boost::shared_ptr<Plugin> (new LuaProc (*lua));
848 #ifdef LV2_SUPPORT
849         } else if ((lv2p = boost::dynamic_pointer_cast<LV2Plugin> (other)) != 0) {
850                 return boost::shared_ptr<Plugin> (new LV2Plugin (*lv2p));
851 #endif
852 #ifdef WINDOWS_VST_SUPPORT
853         } else if ((vp = boost::dynamic_pointer_cast<WindowsVSTPlugin> (other)) != 0) {
854                 return boost::shared_ptr<Plugin> (new WindowsVSTPlugin (*vp));
855 #endif
856 #ifdef LXVST_SUPPORT
857         } else if ((lxvp = boost::dynamic_pointer_cast<LXVSTPlugin> (other)) != 0) {
858                 return boost::shared_ptr<Plugin> (new LXVSTPlugin (*lxvp));
859 #endif
860 #ifdef AUDIOUNIT_SUPPORT
861         } else if ((ap = boost::dynamic_pointer_cast<AUPlugin> (other)) != 0) {
862                 return boost::shared_ptr<Plugin> (new AUPlugin (*ap));
863 #endif
864         }
865
866         fatal << string_compose (_("programming error: %1"),
867                           X_("unknown plugin type in PluginInsert::plugin_factory"))
868               << endmsg;
869         abort(); /*NOTREACHED*/
870         return boost::shared_ptr<Plugin> ((Plugin*) 0);
871 }
872
873 void
874 PluginInsert::set_input_map (uint32_t num, ChanMapping m) {
875         if (num < _in_map.size()) {
876                 bool changed = _in_map[num] != m;
877                 _in_map[num] = m;
878                 if (changed) {
879                         PluginMapChanged (); /* EMIT SIGNAL */
880                 }
881         }
882 }
883
884 void
885 PluginInsert::set_output_map (uint32_t num, ChanMapping m) {
886         if (num < _out_map.size()) {
887                 bool changed = _out_map[num] != m;
888                 _out_map[num] = m;
889                 if (changed) {
890                         PluginMapChanged (); /* EMIT SIGNAL */
891                 }
892         }
893 }
894
895 bool
896 PluginInsert::configure_io (ChanCount in, ChanCount out)
897 {
898         Match old_match = _match;
899         ChanCount old_in;
900         ChanCount old_out;
901
902         if (_configured) {
903                 old_in = _configured_in;
904                 old_out = _configured_out;
905         }
906
907         _configured_in = in;
908         _configured_out = out;
909
910         /* get plugin configuration */
911         _match = private_can_support_io_configuration (in, out);
912 #ifndef NDEBUG // XXX
913         cout << "Match '" << name() << "': " << _match;
914 #endif
915
916         /* set the matching method and number of plugins that we will use to meet this configuration */
917         if (set_count (_match.plugins) == false) {
918                 PluginIoReConfigure (); /* EMIT SIGNAL */
919                 _configured = false;
920                 return false;
921         }
922
923         /* configure plugins */
924         switch (_match.method) {
925         case Split:
926         case Hide:
927                 if (_plugins.front()->configure_io (natural_input_streams(), out) == false) {
928                         PluginIoReConfigure (); /* EMIT SIGNAL */
929                         _configured = false;
930                         return false;
931                 }
932                 break;
933         case Delegate:
934                 {
935                         ChanCount dout;
936                         ChanCount useins;
937                         bool const r = _plugins.front()->can_support_io_configuration (in, dout, &useins);
938                         assert (r);
939                         assert (_match.strict_io || dout.n_audio() == out.n_audio()); // sans midi bypass
940                         if (useins.n_audio() == 0) {
941                                 useins = in;
942                         }
943                         if (_plugins.front()->configure_io (useins, dout) == false) {
944                                 PluginIoReConfigure (); /* EMIT SIGNAL */
945                                 _configured = false;
946                                 return false;
947                         }
948                 }
949                 break;
950         default:
951                 if (_plugins.front()->configure_io (in, out) == false) {
952                         PluginIoReConfigure (); /* EMIT SIGNAL */
953                         _configured = false;
954                         return false;
955                 }
956                 break;
957         }
958
959         bool mapping_changed = false;
960         if (old_in == in && old_out == out && _configured
961                         && old_match.method == _match.method
962                         && _in_map.size() == _out_map.size()
963                         && _in_map.size() == get_count ()
964                  ) {
965                 /* If the configuraton has not changed, keep the mapping */
966         } else if (_match.custom_cfg && _configured) {
967                 /* strip dead wood */
968                 for (uint32_t pc = 0; pc < get_count(); ++pc) {
969                         ChanMapping new_in;
970                         ChanMapping new_out;
971                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
972                                 for (uint32_t i = 0; i < natural_input_streams().get (*t); ++i) {
973                                         bool valid;
974                                         uint32_t idx = _in_map[pc].get (*t, i, &valid);
975                                         if (valid && idx <= in.get (*t)) {
976                                                 new_in.set (*t, i, idx);
977                                         }
978                                 }
979                                 for (uint32_t o = 0; o < natural_output_streams().get (*t); ++o) {
980                                         bool valid;
981                                         uint32_t idx = _out_map[pc].get (*t, o, &valid);
982                                         if (valid && idx <= out.get (*t)) {
983                                                 new_out.set (*t, o, idx);
984                                         }
985                                 }
986                         }
987                         if (_in_map[pc] != new_in || _out_map[pc] != new_out) {
988                                 mapping_changed = true;
989                         }
990                         _in_map[pc] = new_in;
991                         _out_map[pc] = new_out;
992                 }
993         } else {
994                 /* generate a new mapping */
995                 uint32_t pc = 0;
996                 _in_map.clear ();
997                 _out_map.clear ();
998                 for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i, ++pc) {
999                         if (_match.method == Split) {
1000                                 _in_map[pc] = ChanMapping ();
1001                                 /* connect inputs in round-robin fashion */
1002                                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1003                                         const uint32_t cend = _configured_in.get (*t);
1004                                         if (cend == 0) { continue; }
1005                                         uint32_t c = 0;
1006                                         for (uint32_t in = 0; in < natural_input_streams().get (*t); ++in) {
1007                                                 _in_map[pc].set (*t, in, c);
1008                                                 c = c + 1 % cend;
1009                                         }
1010                                 }
1011                         } else {
1012                                 _in_map[pc] = ChanMapping (ChanCount::min (natural_input_streams (), in));
1013                         }
1014                         _out_map[pc] = ChanMapping (ChanCount::min (natural_output_streams(), out));
1015
1016                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1017                                 _in_map[pc].offset_to(*t, pc * natural_input_streams().get(*t));
1018                                 _out_map[pc].offset_to(*t, pc * natural_output_streams().get(*t));
1019                         }
1020                         mapping_changed = true;
1021                 }
1022         }
1023
1024         if (mapping_changed) {
1025                 PluginMapChanged (); /* EMIT SIGNAL */
1026 #ifndef NDEBUG // XXX
1027                 uint32_t pc = 0;
1028                 cout << "----<<----\n";
1029                 for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i, ++pc) {
1030                         cout << "Channel Map for " << name() << " plugin " << pc << "\n";
1031                         cout << " * Inputs:\n" << _in_map[pc];
1032                         cout << " * Outputs:\n" << _out_map[pc];
1033                 }
1034                 cout << "---->>----\n";
1035 #endif
1036         }
1037
1038         if (old_in != in || old_out != out
1039                         || (old_match.method != _match.method && (old_match.method == Split || _match.method == Split))
1040                  ) {
1041                 PluginIoReConfigure (); /* EMIT SIGNAL */
1042         }
1043
1044         // we don't know the analysis window size, so we must work with the
1045         // current buffer size here. each request for data fills in these
1046         // buffers and the analyser makes sure it gets enough data for the
1047         // analysis window
1048         session().ensure_buffer_set (_signal_analysis_inputs, in);
1049         //_signal_analysis_inputs.set_count (in);
1050
1051         session().ensure_buffer_set (_signal_analysis_outputs, out);
1052         //_signal_analysis_outputs.set_count (out);
1053
1054         // std::cerr << "set counts to i" << in.n_audio() << "/o" << out.n_audio() << std::endl;
1055
1056         _configured = true;
1057         return Processor::configure_io (in, out);
1058 }
1059
1060 /** Decide whether this PluginInsert can support a given IO configuration.
1061  *  To do this, we run through a set of possible solutions in rough order of
1062  *  preference.
1063  *
1064  *  @param in Required input channel count.
1065  *  @param out Filled in with the output channel count if we return true.
1066  *  @return true if the given IO configuration can be supported.
1067  */
1068 bool
1069 PluginInsert::can_support_io_configuration (const ChanCount& in, ChanCount& out)
1070 {
1071         return private_can_support_io_configuration (in, out).method != Impossible;
1072 }
1073
1074 /** A private version of can_support_io_configuration which returns the method
1075  *  by which the configuration can be matched, rather than just whether or not
1076  *  it can be.
1077  */
1078 PluginInsert::Match
1079 PluginInsert::private_can_support_io_configuration (ChanCount const & inx, ChanCount& out) const
1080 {
1081         if (_plugins.empty()) {
1082                 return Match();
1083         }
1084
1085         /* if a user specified a custom cfg, so be it. */
1086         if (_custom_cfg) {
1087                 out = _custom_out;
1088                 return Match (ExactMatch, get_count(), false, true); // XXX
1089         }
1090
1091         /* try automatic configuration next */
1092         Match m = PluginInsert::automatic_can_support_io_configuration (inx, out);
1093
1094
1095         PluginInfoPtr info = _plugins.front()->get_info();
1096         ChanCount inputs  = info->n_inputs;
1097         ChanCount outputs = info->n_outputs;
1098         ChanCount midi_bypass;
1099
1100         /* handle case strict-i/o */
1101         if (_strict_io && m.method != Impossible) {
1102                 m.strict_io = true;
1103
1104                 /* special case MIDI instruments */
1105                 if (is_midi_instrument()) {
1106                         // output = midi-bypass + at most master-out channels.
1107                         ChanCount max_out (DataType::AUDIO, 2); // TODO use master-out
1108                         max_out.set (DataType::MIDI, out.get(DataType::MIDI));
1109                         out = ChanCount::min (out, max_out);
1110                         return m;
1111                 }
1112
1113                 switch (m.method) {
1114                         case NoInputs:
1115                                 if (inx != out) {
1116                                         /* replicate processor to match output count (generators and such)
1117                                          * at least enough to feed every output port. */
1118                                         uint32_t f = 1; // at least one. e.g. control data filters, no in, no out.
1119                                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1120                                                 uint32_t nin = inputs.get (*t);
1121                                                 if (nin == 0 || inx.get(*t) == 0) { continue; }
1122                                                 f = max (f, (uint32_t) ceil (inx.get(*t) / (float)nin));
1123                                         }
1124                                         out = inx;
1125                                         return Match (Replicate, f);
1126                                 }
1127                                 break;
1128                         case Split:
1129                                 break;
1130                         default:
1131                                 break;
1132                 }
1133                 if (inx == out) { return m; }
1134
1135                 out = inx;
1136                 if (inx.get(DataType::MIDI) == 1
1137                                 && out.get (DataType::MIDI) == 0
1138                                 && outputs.get(DataType::MIDI) == 0) {
1139                         out += ChanCount (DataType::MIDI, 1);
1140                 }
1141                 return m;
1142         }
1143
1144         if (m.method != Impossible) {
1145                 return m;
1146         }
1147
1148         if (info->reconfigurable_io()) {
1149                 ChanCount useins;
1150                 bool const r = _plugins.front()->can_support_io_configuration (inx, out, &useins);
1151                 if (!r) {
1152                         // houston, we have a problem.
1153                         return Match (Impossible, 0);
1154                 }
1155                 return Match (Delegate, 1);
1156         }
1157
1158         // add at least as many plugins so that output count matches input count
1159         uint32_t f = 0;
1160         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1161                 uint32_t nin = inputs.get (*t);
1162                 uint32_t nout = outputs.get (*t);
1163                 if (nin == 0 || inx.get(*t) == 0) { continue; }
1164                 // prefer floor() so the count won't overly increase IFF (nin < nout)
1165                 f = max (f, (uint32_t) floor (inx.get(*t) / (float)nout));
1166         }
1167         if (f > 0 && outputs * f >= _configured_out) {
1168                 out = outputs * f;
1169                 return Match (Replicate, f);
1170         }
1171
1172         // add at least as many plugins needed to connect all inputs
1173         f = 1;
1174         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1175                 uint32_t nin = inputs.get (*t);
1176                 if (nin == 0 || inx.get(*t) == 0) { continue; }
1177                 f = max (f, (uint32_t) ceil (inx.get(*t) / (float)nin));
1178         }
1179         out = outputs * f;
1180         return Match (Replicate, f);
1181 }
1182
1183 /* this is the original Ardour 3/4 behavior, mainly for backwards compatibility */
1184 PluginInsert::Match
1185 PluginInsert::automatic_can_support_io_configuration (ChanCount const & inx, ChanCount& out) const
1186 {
1187         if (_plugins.empty()) {
1188                 return Match();
1189         }
1190
1191         PluginInfoPtr info = _plugins.front()->get_info();
1192         ChanCount in; in += inx;
1193         ChanCount midi_bypass;
1194
1195         if (info->reconfigurable_io()) {
1196                 /* Plugin has flexible I/O, so delegate to it */
1197                 bool const r = _plugins.front()->can_support_io_configuration (in, out);
1198                 if (!r) {
1199                         return Match (Impossible, 0);
1200                 }
1201                 return Match (Delegate, 1);
1202         }
1203
1204         ChanCount inputs  = info->n_inputs;
1205         ChanCount outputs = info->n_outputs;
1206
1207         if (in.get(DataType::MIDI) == 1 && outputs.get(DataType::MIDI) == 0) {
1208                 DEBUG_TRACE ( DEBUG::Processors, string_compose ("bypassing midi-data around %1\n", name()));
1209                 midi_bypass.set(DataType::MIDI, 1);
1210         }
1211         if (in.get(DataType::MIDI) == 1 && inputs.get(DataType::MIDI) == 0) {
1212                 DEBUG_TRACE ( DEBUG::Processors, string_compose ("hiding midi-port from plugin %1\n", name()));
1213                 in.set(DataType::MIDI, 0);
1214         }
1215
1216         bool no_inputs = true;
1217         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1218                 if (inputs.get (*t) != 0) {
1219                         no_inputs = false;
1220                         break;
1221                 }
1222         }
1223
1224         if (no_inputs) {
1225                 /* no inputs so we can take any input configuration since we throw it away */
1226                 out = outputs + midi_bypass;
1227                 return Match (NoInputs, 1);
1228         }
1229
1230         /* Plugin inputs match requested inputs exactly */
1231         if (inputs == in) {
1232                 out = outputs + midi_bypass;
1233                 return Match (ExactMatch, 1);
1234         }
1235
1236         /* We may be able to run more than one copy of the plugin within this insert
1237            to cope with the insert having more inputs than the plugin.
1238            We allow replication only for plugins with either zero or 1 inputs and outputs
1239            for every valid data type.
1240         */
1241
1242         uint32_t f             = 0;
1243         bool     can_replicate = true;
1244         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1245
1246                 uint32_t nin = inputs.get (*t);
1247
1248                 // No inputs of this type
1249                 if (nin == 0 && in.get(*t) == 0) {
1250                         continue;
1251                 }
1252
1253                 if (nin != 1 || outputs.get (*t) != 1) {
1254                         can_replicate = false;
1255                         break;
1256                 }
1257
1258                 // Potential factor not set yet
1259                 if (f == 0) {
1260                         f = in.get(*t) / nin;
1261                 }
1262
1263                 // Factor for this type does not match another type, can not replicate
1264                 if (f != (in.get(*t) / nin)) {
1265                         can_replicate = false;
1266                         break;
1267                 }
1268         }
1269
1270         if (can_replicate) {
1271                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1272                         out.set (*t, outputs.get(*t) * f);
1273                 }
1274                 out += midi_bypass;
1275                 return Match (Replicate, f);
1276         }
1277
1278         /* If the processor has exactly one input of a given type, and
1279            the plugin has more, we can feed the single processor input
1280            to some or all of the plugin inputs.  This is rather
1281            special-case-y, but the 1-to-many case is by far the
1282            simplest.  How do I split thy 2 processor inputs to 3
1283            plugin inputs?  Let me count the ways ...
1284         */
1285
1286         bool can_split = true;
1287         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1288
1289                 bool const can_split_type = (in.get (*t) == 1 && inputs.get (*t) > 1);
1290                 bool const nothing_to_do_for_type = (in.get (*t) == 0 && inputs.get (*t) == 0);
1291
1292                 if (!can_split_type && !nothing_to_do_for_type) {
1293                         can_split = false;
1294                 }
1295         }
1296
1297         if (can_split) {
1298                 out = outputs + midi_bypass;
1299                 return Match (Split, 1);
1300         }
1301
1302         /* If the plugin has more inputs than we want, we can `hide' some of them
1303            by feeding them silence.
1304         */
1305
1306         bool could_hide = false;
1307         bool cannot_hide = false;
1308         ChanCount hide_channels;
1309
1310         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1311                 if (inputs.get(*t) > in.get(*t)) {
1312                         /* there is potential to hide, since the plugin has more inputs of type t than the insert */
1313                         hide_channels.set (*t, inputs.get(*t) - in.get(*t));
1314                         could_hide = true;
1315                 } else if (inputs.get(*t) < in.get(*t)) {
1316                         /* we definitely cannot hide, since the plugin has fewer inputs of type t than the insert */
1317                         cannot_hide = true;
1318                 }
1319         }
1320
1321         if (could_hide && !cannot_hide) {
1322                 out = outputs + midi_bypass;
1323                 return Match (Hide, 1, false, false, hide_channels);
1324         }
1325
1326         midi_bypass.reset();
1327         return Match (Impossible, 0);
1328 }
1329
1330
1331 XMLNode&
1332 PluginInsert::get_state ()
1333 {
1334         return state (true);
1335 }
1336
1337 XMLNode&
1338 PluginInsert::state (bool full)
1339 {
1340         XMLNode& node = Processor::state (full);
1341
1342         node.add_property("type", _plugins[0]->state_node_name());
1343         node.add_property("unique-id", _plugins[0]->unique_id());
1344         node.add_property("count", string_compose("%1", _plugins.size()));
1345
1346         /* remember actual i/o configuration (for later placeholder
1347          * in case the plugin goes missing) */
1348         node.add_child_nocopy (* _configured_in.state (X_("ConfiguredInput")));
1349         node.add_child_nocopy (* _configured_out.state (X_("ConfiguredOutput")));
1350
1351         /* save custom i/o config */
1352         node.add_property("custom", _custom_cfg ? "yes" : "no");
1353         if (_custom_cfg) {
1354                 assert (_custom_out == _configured_out); // redundant
1355                 for (uint32_t pc = 0; pc < get_count(); ++pc) {
1356                         // TODO save _in_map[pc], _out_map[pc]
1357                 }
1358         }
1359
1360         _plugins[0]->set_insert_id(this->id());
1361         node.add_child_nocopy (_plugins[0]->get_state());
1362
1363         for (Controls::iterator c = controls().begin(); c != controls().end(); ++c) {
1364                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl> ((*c).second);
1365                 if (ac) {
1366                         node.add_child_nocopy (ac->get_state());
1367                 }
1368         }
1369
1370         return node;
1371 }
1372
1373 void
1374 PluginInsert::set_control_ids (const XMLNode& node, int version)
1375 {
1376         const XMLNodeList& nlist = node.children();
1377         XMLNodeConstIterator iter;
1378         set<Evoral::Parameter>::const_iterator p;
1379
1380         for (iter = nlist.begin(); iter != nlist.end(); ++iter) {
1381                 if ((*iter)->name() == Controllable::xml_node_name) {
1382                         const XMLProperty* prop;
1383
1384                         uint32_t p = (uint32_t)-1;
1385 #ifdef LV2_SUPPORT
1386                         if ((prop = (*iter)->property (X_("symbol"))) != 0) {
1387                                 boost::shared_ptr<LV2Plugin> lv2plugin = boost::dynamic_pointer_cast<LV2Plugin> (_plugins[0]);
1388                                 if (lv2plugin) {
1389                                         p = lv2plugin->port_index(prop->value().c_str());
1390                                 }
1391                         }
1392 #endif
1393                         if (p == (uint32_t)-1 && (prop = (*iter)->property (X_("parameter"))) != 0) {
1394                                 p = atoi (prop->value());
1395                         }
1396
1397                         if (p != (uint32_t)-1) {
1398
1399                                 /* this may create the new controllable */
1400
1401                                 boost::shared_ptr<Evoral::Control> c = control (Evoral::Parameter (PluginAutomation, 0, p));
1402
1403 #ifndef NO_PLUGIN_STATE
1404                                 if (!c) {
1405                                         continue;
1406                                 }
1407                                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl> (c);
1408                                 if (ac) {
1409                                         ac->set_state (**iter, version);
1410                                 }
1411 #endif
1412                         }
1413                 }
1414         }
1415 }
1416
1417 int
1418 PluginInsert::set_state(const XMLNode& node, int version)
1419 {
1420         XMLNodeList nlist = node.children();
1421         XMLNodeIterator niter;
1422         XMLPropertyList plist;
1423         const XMLProperty *prop;
1424         ARDOUR::PluginType type;
1425
1426         if ((prop = node.property ("type")) == 0) {
1427                 error << _("XML node describing plugin is missing the `type' field") << endmsg;
1428                 return -1;
1429         }
1430
1431         if (prop->value() == X_("ladspa") || prop->value() == X_("Ladspa")) { /* handle old school sessions */
1432                 type = ARDOUR::LADSPA;
1433         } else if (prop->value() == X_("lv2")) {
1434                 type = ARDOUR::LV2;
1435         } else if (prop->value() == X_("windows-vst")) {
1436                 type = ARDOUR::Windows_VST;
1437         } else if (prop->value() == X_("lxvst")) {
1438                 type = ARDOUR::LXVST;
1439         } else if (prop->value() == X_("audiounit")) {
1440                 type = ARDOUR::AudioUnit;
1441         } else if (prop->value() == X_("luaproc")) {
1442                 type = ARDOUR::Lua;
1443         } else {
1444                 error << string_compose (_("unknown plugin type %1 in plugin insert state"),
1445                                   prop->value())
1446                       << endmsg;
1447                 return -1;
1448         }
1449
1450         prop = node.property ("unique-id");
1451
1452         if (prop == 0) {
1453 #ifdef WINDOWS_VST_SUPPORT
1454                 /* older sessions contain VST plugins with only an "id" field.
1455                  */
1456
1457                 if (type == ARDOUR::Windows_VST) {
1458                         prop = node.property ("id");
1459                 }
1460 #endif
1461
1462 #ifdef LXVST_SUPPORT
1463                 /*There shouldn't be any older sessions with linuxVST support.. but anyway..*/
1464
1465                 if (type == ARDOUR::LXVST) {
1466                         prop = node.property ("id");
1467                 }
1468 #endif
1469                 /* recheck  */
1470
1471                 if (prop == 0) {
1472                         error << _("Plugin has no unique ID field") << endmsg;
1473                         return -1;
1474                 }
1475         }
1476
1477         boost::shared_ptr<Plugin> plugin = find_plugin (_session, prop->value(), type);
1478
1479         /* treat linux and windows VST plugins equivalent if they have the same uniqueID
1480          * allow to move sessions windows <> linux */
1481 #ifdef LXVST_SUPPORT
1482         if (plugin == 0 && type == ARDOUR::Windows_VST) {
1483                 type = ARDOUR::LXVST;
1484                 plugin = find_plugin (_session, prop->value(), type);
1485         }
1486 #endif
1487
1488 #ifdef WINDOWS_VST_SUPPORT
1489         if (plugin == 0 && type == ARDOUR::LXVST) {
1490                 type = ARDOUR::Windows_VST;
1491                 plugin = find_plugin (_session, prop->value(), type);
1492         }
1493 #endif
1494
1495         if (plugin == 0) {
1496                 error << string_compose(
1497                         _("Found a reference to a plugin (\"%1\") that is unknown.\n"
1498                           "Perhaps it was removed or moved since it was last used."),
1499                         prop->value())
1500                       << endmsg;
1501                 return -1;
1502         }
1503
1504         if (type == ARDOUR::Lua) {
1505                 XMLNode *ls = node.child (plugin->state_node_name().c_str());
1506                 // we need to load the script to set the name and parameters.
1507                 boost::shared_ptr<LuaProc> lp = boost::dynamic_pointer_cast<LuaProc>(plugin);
1508                 if (ls && lp) {
1509                         lp->set_script_from_state (*ls);
1510                 }
1511         }
1512
1513         // The name of the PluginInsert comes from the plugin, nothing else
1514         _name = plugin->get_info()->name;
1515
1516         uint32_t count = 1;
1517
1518         // Processor::set_state() will set this, but too late
1519         // for it to be available when setting up plugin
1520         // state. We can't call Processor::set_state() until
1521         // the plugins themselves are created and added.
1522
1523         set_id (node);
1524
1525         if (_plugins.empty()) {
1526                 /* if we are adding the first plugin, we will need to set
1527                    up automatable controls.
1528                 */
1529                 add_plugin (plugin);
1530                 create_automatable_parameters ();
1531                 set_control_ids (node, version);
1532         }
1533
1534         if ((prop = node.property ("count")) != 0) {
1535                 sscanf (prop->value().c_str(), "%u", &count);
1536         }
1537
1538         if (_plugins.size() != count) {
1539                 for (uint32_t n = 1; n < count; ++n) {
1540                         add_plugin (plugin_factory (plugin));
1541                 }
1542         }
1543
1544         Processor::set_state (node, version);
1545
1546         PBD::ID new_id = this->id();
1547         PBD::ID old_id = this->id();
1548
1549         if ((prop = node.property ("id")) != 0) {
1550                 old_id = prop->value ();
1551         }
1552
1553         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1554
1555                 /* find the node with the type-specific node name ("lv2", "ladspa", etc)
1556                    and set all plugins to the same state.
1557                 */
1558
1559                 if ((*niter)->name() == plugin->state_node_name()) {
1560
1561                         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1562                                 /* Plugin state can include external files which are named after the ID.
1563                                  *
1564                                  * If regenerate_xml_or_string_ids() is set, the ID will already have
1565                                  * been changed, so we need to use the old ID from the XML to load the
1566                                  * state and then update the ID.
1567                                  *
1568                                  * When copying a plugin-state, route_ui takes care of of updating the ID,
1569                                  * but we need to call set_insert_id() to clear the cached plugin-state
1570                                  * and force a change.
1571                                  */
1572                                 if (!regenerate_xml_or_string_ids ()) {
1573                                         (*i)->set_insert_id (new_id);
1574                                 } else {
1575                                         (*i)->set_insert_id (old_id);
1576                                 }
1577
1578                                 (*i)->set_state (**niter, version);
1579
1580                                 if (regenerate_xml_or_string_ids ()) {
1581                                         (*i)->set_insert_id (new_id);
1582                                 }
1583                         }
1584
1585                         break;
1586                 }
1587         }
1588
1589         if (version < 3000) {
1590
1591                 /* Only 2.X sessions need a call to set_parameter_state() - in 3.X and above
1592                    this is all handled by Automatable
1593                 */
1594
1595                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1596                         if ((*niter)->name() == "Redirect") {
1597                                 /* XXX do we need to tackle placement? i think not (pd; oct 16 2009) */
1598                                 Processor::set_state (**niter, version);
1599                                 break;
1600                         }
1601                 }
1602
1603                 set_parameter_state_2X (node, version);
1604         }
1605
1606         if ((prop = node.property (X_("custom"))) != 0) {
1607                 _custom_cfg = string_is_affirmative (prop->value());
1608         }
1609
1610         XMLNodeList kids = node.children ();
1611         for (XMLNodeIterator i = kids.begin(); i != kids.end(); ++i) {
1612                 if ((*i)->name() == X_("ConfiguredOutput")) {
1613                         _custom_out = ChanCount(**i);
1614                 }
1615                 // TODO restore mappings for all 0 .. count.
1616         }
1617
1618
1619
1620         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1621                 if (active()) {
1622                         (*i)->activate ();
1623                 } else {
1624                         (*i)->deactivate ();
1625                 }
1626         }
1627
1628         return 0;
1629 }
1630
1631 void
1632 PluginInsert::update_id (PBD::ID id)
1633 {
1634         set_id (id.to_s());
1635         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1636                 (*i)->set_insert_id (id);
1637         }
1638 }
1639
1640 void
1641 PluginInsert::set_state_dir (const std::string& d)
1642 {
1643         // state() only saves the state of the first plugin
1644         _plugins[0]->set_state_dir (d);
1645 }
1646
1647 void
1648 PluginInsert::set_parameter_state_2X (const XMLNode& node, int version)
1649 {
1650         XMLNodeList nlist = node.children();
1651         XMLNodeIterator niter;
1652
1653         /* look for port automation node */
1654
1655         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1656
1657                 if ((*niter)->name() != port_automation_node_name) {
1658                         continue;
1659                 }
1660
1661                 XMLNodeList cnodes;
1662                 XMLProperty *cprop;
1663                 XMLNodeConstIterator iter;
1664                 XMLNode *child;
1665                 const char *port;
1666                 uint32_t port_id;
1667
1668                 cnodes = (*niter)->children ("port");
1669
1670                 for (iter = cnodes.begin(); iter != cnodes.end(); ++iter){
1671
1672                         child = *iter;
1673
1674                         if ((cprop = child->property("number")) != 0) {
1675                                 port = cprop->value().c_str();
1676                         } else {
1677                                 warning << _("PluginInsert: Auto: no ladspa port number") << endmsg;
1678                                 continue;
1679                         }
1680
1681                         sscanf (port, "%" PRIu32, &port_id);
1682
1683                         if (port_id >= _plugins[0]->parameter_count()) {
1684                                 warning << _("PluginInsert: Auto: port id out of range") << endmsg;
1685                                 continue;
1686                         }
1687
1688                         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(
1689                                         control(Evoral::Parameter(PluginAutomation, 0, port_id), true));
1690
1691                         if (c && c->alist()) {
1692                                 if (!child->children().empty()) {
1693                                         c->alist()->set_state (*child->children().front(), version);
1694
1695                                         /* In some cases 2.X saves lists with min_yval and max_yval
1696                                            being FLT_MIN and FLT_MAX respectively.  This causes problems
1697                                            in A3 because these min/max values are used to compute
1698                                            where GUI control points should be drawn.  If we see such
1699                                            values, `correct' them to the min/max of the appropriate
1700                                            parameter.
1701                                         */
1702
1703                                         float min_y = c->alist()->get_min_y ();
1704                                         float max_y = c->alist()->get_max_y ();
1705
1706                                         ParameterDescriptor desc;
1707                                         _plugins.front()->get_parameter_descriptor (port_id, desc);
1708
1709                                         if (min_y == FLT_MIN) {
1710                                                 min_y = desc.lower;
1711                                         }
1712
1713                                         if (max_y == FLT_MAX) {
1714                                                 max_y = desc.upper;
1715                                         }
1716
1717                                         c->alist()->set_yrange (min_y, max_y);
1718                                 }
1719                         } else {
1720                                 error << string_compose (_("PluginInsert: automatable control %1 not found - ignored"), port_id) << endmsg;
1721                         }
1722                 }
1723
1724                 /* done */
1725
1726                 break;
1727         }
1728 }
1729
1730
1731 string
1732 PluginInsert::describe_parameter (Evoral::Parameter param)
1733 {
1734         if (param.type() == PluginAutomation) {
1735                 return _plugins[0]->describe_parameter (param);
1736         } else if (param.type() == PluginPropertyAutomation) {
1737                 boost::shared_ptr<AutomationControl> c(automation_control(param));
1738                 if (c && !c->desc().label.empty()) {
1739                         return c->desc().label;
1740                 }
1741         }
1742         return Automatable::describe_parameter(param);
1743 }
1744
1745 ARDOUR::framecnt_t
1746 PluginInsert::signal_latency() const
1747 {
1748         if (_user_latency) {
1749                 return _user_latency;
1750         }
1751
1752         return _plugins[0]->signal_latency ();
1753 }
1754
1755 ARDOUR::PluginType
1756 PluginInsert::type ()
1757 {
1758        return plugin()->get_info()->type;
1759 }
1760
1761 PluginInsert::PluginControl::PluginControl (PluginInsert*                     p,
1762                                             const Evoral::Parameter&          param,
1763                                             const ParameterDescriptor&        desc,
1764                                             boost::shared_ptr<AutomationList> list)
1765         : AutomationControl (p->session(), param, desc, list, p->describe_parameter(param))
1766         , _plugin (p)
1767 {
1768         if (alist()) {
1769                 alist()->reset_default (desc.normal);
1770                 if (desc.toggled) {
1771                         list->set_interpolation(Evoral::ControlList::Discrete);
1772                 }
1773         }
1774
1775         if (desc.toggled) {
1776                 set_flags(Controllable::Toggle);
1777         }
1778 }
1779
1780 /** @param val `user' value */
1781 void
1782 PluginInsert::PluginControl::set_value (double user_val, PBD::Controllable::GroupControlDisposition group_override)
1783 {
1784         if (writable()) {
1785                 _set_value (user_val, group_override);
1786         }
1787 }
1788 void
1789 PluginInsert::PluginControl::set_value_unchecked (double user_val)
1790 {
1791         /* used only by automation playback */
1792         _set_value (user_val, Controllable::NoGroup);
1793 }
1794
1795 void
1796 PluginInsert::PluginControl::_set_value (double user_val, PBD::Controllable::GroupControlDisposition group_override)
1797 {
1798         /* FIXME: probably should be taking out some lock here.. */
1799
1800         for (Plugins::iterator i = _plugin->_plugins.begin(); i != _plugin->_plugins.end(); ++i) {
1801                 (*i)->set_parameter (_list->parameter().id(), user_val);
1802         }
1803
1804         boost::shared_ptr<Plugin> iasp = _plugin->_impulseAnalysisPlugin.lock();
1805         if (iasp) {
1806                 iasp->set_parameter (_list->parameter().id(), user_val);
1807         }
1808
1809         AutomationControl::set_value (user_val, group_override);
1810 }
1811
1812 void
1813 PluginInsert::PluginControl::catch_up_with_external_value (double user_val)
1814 {
1815         AutomationControl::set_value (user_val, Controllable::NoGroup);
1816 }
1817
1818 XMLNode&
1819 PluginInsert::PluginControl::get_state ()
1820 {
1821         stringstream ss;
1822
1823         XMLNode& node (AutomationControl::get_state());
1824         ss << parameter().id();
1825         node.add_property (X_("parameter"), ss.str());
1826 #ifdef LV2_SUPPORT
1827         boost::shared_ptr<LV2Plugin> lv2plugin = boost::dynamic_pointer_cast<LV2Plugin> (_plugin->_plugins[0]);
1828         if (lv2plugin) {
1829                 node.add_property (X_("symbol"), lv2plugin->port_symbol (parameter().id()));
1830         }
1831 #endif
1832
1833         return node;
1834 }
1835
1836 /** @return `user' val */
1837 double
1838 PluginInsert::PluginControl::get_value () const
1839 {
1840         boost::shared_ptr<Plugin> plugin = _plugin->plugin (0);
1841
1842         if (!plugin) {
1843                 return 0.0;
1844         }
1845
1846         return plugin->get_parameter (_list->parameter().id());
1847 }
1848
1849 PluginInsert::PluginPropertyControl::PluginPropertyControl (PluginInsert*                     p,
1850                                                             const Evoral::Parameter&          param,
1851                                                             const ParameterDescriptor&        desc,
1852                                                             boost::shared_ptr<AutomationList> list)
1853         : AutomationControl (p->session(), param, desc, list)
1854         , _plugin (p)
1855 {
1856         if (alist()) {
1857                 alist()->set_yrange (desc.lower, desc.upper);
1858                 alist()->reset_default (desc.normal);
1859         }
1860
1861         if (desc.toggled) {
1862                 set_flags(Controllable::Toggle);
1863         }
1864 }
1865
1866 void
1867 PluginInsert::PluginPropertyControl::set_value (double user_val, PBD::Controllable::GroupControlDisposition /* group_override*/)
1868 {
1869         if (writable()) {
1870                 set_value_unchecked (user_val);
1871         }
1872 }
1873
1874 void
1875 PluginInsert::PluginPropertyControl::set_value_unchecked (double user_val)
1876 {
1877         /* Old numeric set_value(), coerce to appropriate datatype if possible.
1878            This is lossy, but better than nothing until Ardour's automation system
1879            can handle various datatypes all the way down. */
1880         const Variant value(_desc.datatype, user_val);
1881         if (value.type() == Variant::NOTHING) {
1882                 error << "set_value(double) called for non-numeric property" << endmsg;
1883                 return;
1884         }
1885
1886         for (Plugins::iterator i = _plugin->_plugins.begin(); i != _plugin->_plugins.end(); ++i) {
1887                 (*i)->set_property(_list->parameter().id(), value);
1888         }
1889
1890         _value = value;
1891         AutomationControl::set_value (user_val, Controllable::NoGroup);
1892 }
1893
1894 XMLNode&
1895 PluginInsert::PluginPropertyControl::get_state ()
1896 {
1897         stringstream ss;
1898
1899         XMLNode& node (AutomationControl::get_state());
1900         ss << parameter().id();
1901         node.add_property (X_("property"), ss.str());
1902         node.remove_property (X_("value"));
1903
1904         return node;
1905 }
1906
1907 double
1908 PluginInsert::PluginPropertyControl::get_value () const
1909 {
1910         return _value.to_double();
1911 }
1912
1913 boost::shared_ptr<Plugin>
1914 PluginInsert::get_impulse_analysis_plugin()
1915 {
1916         boost::shared_ptr<Plugin> ret;
1917         if (_impulseAnalysisPlugin.expired()) {
1918                 ret = plugin_factory(_plugins[0]);
1919                 ret->configure_io (internal_input_streams (), internal_output_streams ());
1920                 _impulseAnalysisPlugin = ret;
1921         } else {
1922                 ret = _impulseAnalysisPlugin.lock();
1923         }
1924
1925         return ret;
1926 }
1927
1928 void
1929 PluginInsert::collect_signal_for_analysis (framecnt_t nframes)
1930 {
1931         // called from outside the audio thread, so this should be safe
1932         // only do audio as analysis is (currently) only for audio plugins
1933         _signal_analysis_inputs.ensure_buffers(  DataType::AUDIO, internal_input_streams().n_audio(),  nframes);
1934         _signal_analysis_outputs.ensure_buffers( DataType::AUDIO, internal_output_streams().n_audio(), nframes);
1935
1936         _signal_analysis_collected_nframes   = 0;
1937         _signal_analysis_collect_nframes_max = nframes;
1938 }
1939
1940 /** Add a plugin to our list */
1941 void
1942 PluginInsert::add_plugin (boost::shared_ptr<Plugin> plugin)
1943 {
1944         plugin->set_insert_id (this->id());
1945
1946         if (_plugins.empty()) {
1947                 /* first (and probably only) plugin instance - connect to relevant signals
1948                  */
1949
1950                 plugin->ParameterChangedExternally.connect_same_thread (*this, boost::bind (&PluginInsert::parameter_changed_externally, this, _1, _2));
1951                 plugin->StartTouch.connect_same_thread (*this, boost::bind (&PluginInsert::start_touch, this, _1));
1952                 plugin->EndTouch.connect_same_thread (*this, boost::bind (&PluginInsert::end_touch, this, _1));
1953         }
1954
1955         _plugins.push_back (plugin);
1956 }
1957
1958 void
1959 PluginInsert::realtime_handle_transport_stopped ()
1960 {
1961         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1962                 (*i)->realtime_handle_transport_stopped ();
1963         }
1964 }
1965
1966 void
1967 PluginInsert::realtime_locate ()
1968 {
1969         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1970                 (*i)->realtime_locate ();
1971         }
1972 }
1973
1974 void
1975 PluginInsert::monitoring_changed ()
1976 {
1977         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1978                 (*i)->monitoring_changed ();
1979         }
1980 }
1981
1982 void
1983 PluginInsert::start_touch (uint32_t param_id)
1984 {
1985         boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter (PluginAutomation, 0, param_id));
1986         if (ac) {
1987                 ac->start_touch (session().audible_frame());
1988         }
1989 }
1990
1991 void
1992 PluginInsert::end_touch (uint32_t param_id)
1993 {
1994         boost::shared_ptr<AutomationControl> ac = automation_control (Evoral::Parameter (PluginAutomation, 0, param_id));
1995         if (ac) {
1996                 ac->stop_touch (true, session().audible_frame());
1997         }
1998 }
1999
2000 std::ostream& operator<<(std::ostream& o, const ARDOUR::PluginInsert::Match& m)
2001 {
2002         switch (m.method) {
2003                 case PluginInsert::Impossible: o << "Impossible"; break;
2004                 case PluginInsert::Delegate:   o << "Delegate"; break;
2005                 case PluginInsert::NoInputs:   o << "NoInputs"; break;
2006                 case PluginInsert::ExactMatch: o << "ExactMatch"; break;
2007                 case PluginInsert::Replicate:  o << "Replicate"; break;
2008                 case PluginInsert::Split:      o << "Split"; break;
2009                 case PluginInsert::Hide:       o << "Hide"; break;
2010         }
2011         o << " cnt: " << m.plugins
2012                 << (m.strict_io ? " strict-io" : "")
2013                 << (m.custom_cfg ? " custom-cfg" : "");
2014         if (m.method == PluginInsert::Hide) {
2015                 o << " hide: " << m.hide;
2016         }
2017         o << "\n";
2018         return o;
2019 }