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