changes for OS X support: change waf config define to COREAUDIO_SUPPORT, remove Plugi...
[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/plugin.h"
37 #include "ardour/plugin_insert.h"
38 #include "ardour/port.h"
39 #include "ardour/route.h"
40
41 #ifdef LV2_SUPPORT
42 #include "ardour/lv2_plugin.h"
43 #endif
44
45 #ifdef VST_SUPPORT
46 #include "ardour/vst_plugin.h"
47 #endif
48
49 #ifdef LXVST_SUPPORT
50 #include "ardour/lxvst_plugin.h"
51 #endif
52
53 #ifdef AUDIOUNIT_SUPPORT
54 #include "ardour/audio_unit.h"
55 #endif
56
57 #include "ardour/audioengine.h"
58 #include "ardour/session.h"
59 #include "ardour/types.h"
60
61 #include "i18n.h"
62
63 using namespace std;
64 using namespace ARDOUR;
65 using namespace PBD;
66
67 const string PluginInsert::port_automation_node_name = "PortAutomation";
68
69 PluginInsert::PluginInsert (Session& s, boost::shared_ptr<Plugin> plug)
70         : Processor (s, (plug ? plug->name() : string ("toBeRenamed")))
71         , _signal_analysis_collected_nframes(0)
72         , _signal_analysis_collect_nframes_max(0)
73 {
74         /* the first is the master */
75
76         if (plug) {
77                 add_plugin (plug);
78                 create_automatable_parameters ();
79         }
80 }
81
82 bool
83 PluginInsert::set_count (uint32_t num)
84 {
85         bool require_state = !_plugins.empty();
86
87         /* this is a bad idea.... we shouldn't do this while active.
88            only a route holding their redirect_lock should be calling this
89         */
90
91         if (num == 0) {
92                 return false;
93         } else if (num > _plugins.size()) {
94                 uint32_t diff = num - _plugins.size();
95
96                 for (uint32_t n = 0; n < diff; ++n) {
97                         add_plugin_with_activation (plugin_factory (_plugins[0]));
98
99                         if (require_state) {
100                                 /* XXX do something */
101                         }
102                 }
103
104         } else if (num < _plugins.size()) {
105                 uint32_t diff = _plugins.size() - num;
106                 for (uint32_t n= 0; n < diff; ++n) {
107                         _plugins.pop_back();
108                 }
109         }
110
111         return true;
112 }
113
114 PluginInsert::~PluginInsert ()
115 {
116 }
117
118 void
119 PluginInsert::control_list_automation_state_changed (Evoral::Parameter which, AutoState s)
120 {
121         if (which.type() != PluginAutomation)
122                 return;
123
124         boost::shared_ptr<AutomationControl> c
125                         = boost::dynamic_pointer_cast<AutomationControl>(control (which));
126
127         if (c && s != Off) {
128                 _plugins[0]->set_parameter (which.id(), c->list()->eval (_session.transport_frame()));
129         }
130 }
131
132 ChanCount
133 PluginInsert::output_streams() const
134 {
135         ChanCount out = _plugins.front()->get_info()->n_outputs;
136
137         DEBUG_TRACE (DEBUG::Processors, string_compose ("Plugin insert, static output streams = %1\n", out));
138
139         if (out == ChanCount::INFINITE) {
140                 return _plugins.front()->output_streams ();
141         } else {
142                 out.set_audio (out.n_audio() * _plugins.size());
143                 out.set_midi (out.n_midi() * _plugins.size());
144                 return out;
145         }
146 }
147
148 ChanCount
149 PluginInsert::input_streams() const
150 {
151         ChanCount in = _plugins[0]->get_info()->n_inputs;
152
153         DEBUG_TRACE (DEBUG::Processors, string_compose ("Plugin insert, static input streams = %1, match using %2\n", in, _match.method));
154         
155         if (_match.method == Split) {
156
157                 /* we are splitting 1 processor input to multiple plugin inputs,
158                    so we have a maximum of 1 stream of each type.
159                 */
160                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
161                         if (in.get (*t) > 1) {
162                                 in.set (*t, 1);
163                         }
164                 }
165                 return in;
166
167         } else if (_match.method == Hide) {
168
169                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
170                         in.set (*t, in.get (*t) - _match.hide.get (*t));
171                 }
172                 return in;
173
174         } else if (in == ChanCount::INFINITE) {
175                 
176                 return _plugins[0]->input_streams ();
177
178         } else {
179                 
180                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
181                         in.set (*t, in.get (*t) * _plugins.size ());
182                 }
183                 return in;
184                 
185         }
186 }
187
188 ChanCount
189 PluginInsert::natural_output_streams() const
190 {
191         return _plugins[0]->get_info()->n_outputs;
192 }
193
194 ChanCount
195 PluginInsert::natural_input_streams() const
196 {
197         return _plugins[0]->get_info()->n_inputs;
198 }
199
200 bool
201 PluginInsert::has_no_inputs() const
202 {
203         return _plugins[0]->get_info()->n_inputs == ChanCount::ZERO;
204 }
205
206 bool
207 PluginInsert::has_no_audio_inputs() const
208 {
209         return _plugins[0]->get_info()->n_inputs.n_audio() == 0;
210 }
211
212 bool
213 PluginInsert::is_midi_instrument() const
214 {
215         /* XXX more finesse is possible here. VST plugins have a
216            a specific "instrument" flag, for example.
217          */
218         PluginInfoPtr pi = _plugins[0]->get_info();
219
220         return pi->n_inputs.n_midi() != 0 &&
221                 pi->n_outputs.n_audio() > 0;
222 }
223
224 void
225 PluginInsert::create_automatable_parameters ()
226 {
227         assert (!_plugins.empty());
228
229         set<Evoral::Parameter> a = _plugins.front()->automatable ();
230
231         Plugin::ParameterDescriptor desc;
232
233         for (set<Evoral::Parameter>::iterator i = a.begin(); i != a.end(); ++i) {
234                 if (i->type() == PluginAutomation) {
235
236                         Evoral::Parameter param(*i);
237
238                         _plugins.front()->get_parameter_descriptor(i->id(), desc);
239
240                         /* the Parameter belonging to the actual plugin doesn't have its range set
241                            but we want the Controllable related to this Parameter to have those limits.
242                         */
243
244                         param.set_range (desc.lower, desc.upper, _plugins.front()->default_value(i->id()), desc.toggled);
245                         can_automate (param);
246                         boost::shared_ptr<AutomationList> list(new AutomationList(param));
247                         add_control (boost::shared_ptr<AutomationControl> (new PluginControl(this, param, list)));
248                 }
249         }
250 }
251
252 void
253 PluginInsert::parameter_changed (Evoral::Parameter which, float val)
254 {
255         if (which.type() != PluginAutomation)
256                 return;
257
258         Plugins::iterator i = _plugins.begin();
259
260         /* don't set the first plugin, just all the slaves */
261
262         if (i != _plugins.end()) {
263                 ++i;
264                 for (; i != _plugins.end(); ++i) {
265                         (*i)->set_parameter (which, val);
266                 }
267         }
268 }
269
270 int
271 PluginInsert::set_block_size (pframes_t nframes)
272 {
273         int ret = 0;
274         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
275                 if ((*i)->set_block_size (nframes) != 0) {
276                         ret = -1;
277                 }
278         }
279         return ret;
280 }
281
282 void
283 PluginInsert::activate ()
284 {
285         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
286                 (*i)->activate ();
287         }
288
289         Processor::activate ();
290 }
291
292 void
293 PluginInsert::deactivate ()
294 {
295         Processor::deactivate ();
296
297         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
298                 (*i)->deactivate ();
299         }
300 }
301
302 void
303 PluginInsert::flush ()
304 {
305         for (vector<boost::shared_ptr<Plugin> >::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
306                 (*i)->flush ();
307         }
308 }
309
310 void
311 PluginInsert::connect_and_run (BufferSet& bufs, pframes_t nframes, framecnt_t offset, bool with_auto, framepos_t now)
312 {
313         // Calculate if, and how many frames we need to collect for analysis
314         framecnt_t collect_signal_nframes = (_signal_analysis_collect_nframes_max -
315                                              _signal_analysis_collected_nframes);
316         if (nframes < collect_signal_nframes) { // we might not get all frames now
317                 collect_signal_nframes = nframes;
318         }
319
320         ChanCount const in_streams = input_streams ();
321         ChanCount const out_streams = output_streams ();
322
323         ChanMapping in_map (in_streams);
324         ChanMapping out_map (out_streams);
325
326         if (_match.method == Split) {
327                 /* fix the input mapping so that we have maps for each of the plugin's inputs */
328                 in_map = ChanMapping (natural_input_streams ());
329
330                 /* copy the first stream's buffer contents to the others */
331                 /* XXX: audio only */
332                 Sample const * mono = bufs.get_audio (in_map.get (DataType::AUDIO, 0)).data (offset);
333                 for (uint32_t i = in_streams.n_audio(); i < natural_input_streams().n_audio(); ++i) {
334                         memcpy (bufs.get_audio (in_map.get (DataType::AUDIO, i)).data (offset), mono, sizeof (Sample) * nframes);
335                 }
336         }
337
338         if (_match.method == Hide) {
339                 /* Silence the hidden input buffers */
340                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
341                         for (uint32_t i = in_streams.get(*t); i < (in_streams.get(*t) + _match.hide.get(*t)); ++i) {
342                                 bufs.get(*t, i).silence (nframes);
343                         }
344                 }
345         }
346
347         /* Note that we've already required that plugins
348            be able to handle in-place processing.
349         */
350
351         if (with_auto) {
352
353                 uint32_t n = 0;
354
355                 for (Controls::iterator li = controls().begin(); li != controls().end(); ++li, ++n) {
356
357                         boost::shared_ptr<AutomationControl> c
358                                 = boost::dynamic_pointer_cast<AutomationControl>(li->second);
359
360                         if (c->parameter().type() == PluginAutomation && c->automation_playback()) {
361                                 bool valid;
362
363                                 const float val = c->list()->rt_safe_eval (now, valid);
364
365                                 if (valid) {
366                                         c->set_value(val);
367                                 }
368
369                         }
370                 }
371         }
372
373         if (collect_signal_nframes > 0) {
374                 // collect input
375                 //std::cerr << "collect input, bufs " << bufs.count().n_audio() << " count,  " << bufs.available().n_audio() << " available" << std::endl;
376                 //std::cerr << "               streams " << input_streams().n_audio() << std::endl;
377                 //std::cerr << "filling buffer with " << collect_signal_nframes << " frames at " << _signal_analysis_collected_nframes << std::endl;
378
379                 _signal_analysis_inputs.set_count(input_streams());
380
381                 for (uint32_t i = 0; i < input_streams().n_audio(); ++i) {
382                         _signal_analysis_inputs.get_audio(i).read_from(
383                                 bufs.get_audio(i),
384                                 collect_signal_nframes,
385                                 _signal_analysis_collected_nframes); // offset is for target buffer
386                 }
387
388         }
389
390         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
391                 (*i)->connect_and_run(bufs, in_map, out_map, nframes, offset);
392                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
393                         in_map.offset_to(*t, natural_input_streams().get(*t));
394                         out_map.offset_to(*t, natural_output_streams().get(*t));
395                 }
396         }
397
398         if (collect_signal_nframes > 0) {
399                 // collect output
400                 //std::cerr << "       output, bufs " << bufs.count().n_audio() << " count,  " << bufs.available().n_audio() << " available" << std::endl;
401                 //std::cerr << "               streams " << output_streams().n_audio() << std::endl;
402
403                 _signal_analysis_outputs.set_count(output_streams());
404
405                 for (uint32_t i = 0; i < output_streams().n_audio(); ++i) {
406                         _signal_analysis_outputs.get_audio(i).read_from(
407                                 bufs.get_audio(i),
408                                 collect_signal_nframes,
409                                 _signal_analysis_collected_nframes); // offset is for target buffer
410                 }
411
412                 _signal_analysis_collected_nframes += collect_signal_nframes;
413                 assert(_signal_analysis_collected_nframes <= _signal_analysis_collect_nframes_max);
414
415                 if (_signal_analysis_collected_nframes == _signal_analysis_collect_nframes_max) {
416                         _signal_analysis_collect_nframes_max = 0;
417                         _signal_analysis_collected_nframes   = 0;
418
419                         AnalysisDataGathered(&_signal_analysis_inputs,
420                                              &_signal_analysis_outputs);
421                 }
422         }
423         /* leave remaining channel buffers alone */
424 }
425
426 void
427 PluginInsert::silence (framecnt_t nframes)
428 {
429         if (!active ()) {
430                 return;
431         }
432
433         ChanMapping in_map(input_streams());
434         ChanMapping out_map(output_streams());
435
436         if (_match.method == Split) {
437                 /* fix the input mapping so that we have maps for each of the plugin's inputs */
438                 in_map = ChanMapping (natural_input_streams ());
439         }
440
441         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
442                 (*i)->connect_and_run (_session.get_silent_buffers ((*i)->get_info()->n_inputs), in_map, out_map, nframes, 0);
443         }
444 }
445
446 void
447 PluginInsert::run (BufferSet& bufs, framepos_t /*start_frame*/, framepos_t /*end_frame*/, pframes_t nframes, bool)
448 {
449         if (_pending_active) {
450                 /* run as normal if we are active or moving from inactive to active */
451
452                 if (_session.transport_rolling()) {
453                         automation_run (bufs, nframes);
454                 } else {
455                         connect_and_run (bufs, nframes, 0, false);
456                 }
457
458         } else {
459
460                 if (has_no_audio_inputs()) {
461
462                         /* silence all (audio) outputs. Should really declick
463                          * at the transitions of "active"
464                          */
465
466                         uint32_t out = _plugins[0]->get_info()->n_outputs.n_audio();
467
468                         for (uint32_t n = 0; n < out; ++n) {
469                                 bufs.get_audio (n).silence (nframes);
470                         }
471
472                         bufs.count().set_audio (out);
473
474                 } else {
475
476                         /* does this need to be done with MIDI? it appears not */
477
478                         uint32_t in = _plugins[0]->get_info()->n_inputs.n_audio();
479                         uint32_t out = _plugins[0]->get_info()->n_outputs.n_audio();
480
481                         if (out > in) {
482
483                                 /* not active, but something has make up for any channel count increase */
484
485                                 for (uint32_t n = out - in; n < out; ++n) {
486                                         memcpy (bufs.get_audio(n).data(), bufs.get_audio(in - 1).data(), sizeof (Sample) * nframes);
487                                 }
488                         }
489
490                         bufs.count().set_audio (out);
491                 }
492         }
493
494         _active = _pending_active;
495 }
496
497 void
498 PluginInsert::set_parameter (Evoral::Parameter param, float val)
499 {
500         if (param.type() != PluginAutomation) {
501                 return;
502         }
503
504         /* the others will be set from the event triggered by this */
505
506         _plugins[0]->set_parameter (param.id(), val);
507
508         boost::shared_ptr<AutomationControl> ac
509                         = boost::dynamic_pointer_cast<AutomationControl>(control(param));
510
511         if (ac) {
512                 ac->set_value(val);
513         } else {
514                 warning << "set_parameter called for nonexistant parameter "
515                         << EventTypeMap::instance().to_symbol(param) << endmsg;
516         }
517
518         _session.set_dirty();
519 }
520
521 float
522 PluginInsert::get_parameter (Evoral::Parameter param)
523 {
524         if (param.type() != PluginAutomation) {
525                 return 0.0;
526         } else {
527                 assert (!_plugins.empty ());
528                 return _plugins[0]->get_parameter (param.id());
529         }
530 }
531
532 void
533 PluginInsert::automation_run (BufferSet& bufs, pframes_t nframes)
534 {
535         Evoral::ControlEvent next_event (0, 0.0f);
536         framepos_t now = _session.transport_frame ();
537         framepos_t end = now + nframes;
538         framecnt_t offset = 0;
539
540         Glib::Mutex::Lock lm (control_lock(), Glib::TRY_LOCK);
541
542         if (!lm.locked()) {
543                 connect_and_run (bufs, nframes, offset, false);
544                 return;
545         }
546
547         if (!find_next_event (now, end, next_event) || requires_fixed_sized_buffers()) {
548
549                 /* no events have a time within the relevant range */
550
551                 connect_and_run (bufs, nframes, offset, true, now);
552                 return;
553         }
554
555         while (nframes) {
556
557                 framecnt_t cnt = min (((framecnt_t) ceil (next_event.when) - now), (framecnt_t) nframes);
558
559                 connect_and_run (bufs, cnt, offset, true, now);
560
561                 nframes -= cnt;
562                 offset += cnt;
563                 now += cnt;
564
565                 if (!find_next_event (now, end, next_event)) {
566                         break;
567                 }
568         }
569
570         /* cleanup anything that is left to do */
571
572         if (nframes) {
573                 connect_and_run (bufs, nframes, offset, true, now);
574         }
575 }
576
577 float
578 PluginInsert::default_parameter_value (const Evoral::Parameter& param)
579 {
580         if (param.type() != PluginAutomation)
581                 return 1.0;
582
583         if (_plugins.empty()) {
584                 fatal << _("programming error: ") << X_("PluginInsert::default_parameter_value() called with no plugin")
585                       << endmsg;
586                 /*NOTREACHED*/
587         }
588
589         return _plugins[0]->default_value (param.id());
590 }
591
592 boost::shared_ptr<Plugin>
593 PluginInsert::plugin_factory (boost::shared_ptr<Plugin> other)
594 {
595         boost::shared_ptr<LadspaPlugin> lp;
596 #ifdef LV2_SUPPORT
597         boost::shared_ptr<LV2Plugin> lv2p;
598 #endif
599 #ifdef VST_SUPPORT
600         boost::shared_ptr<VSTPlugin> vp;
601 #endif
602 #ifdef LXVST_SUPPORT
603         boost::shared_ptr<LXVSTPlugin> lxvp;
604 #endif
605 #ifdef AUDIOUNIT_SUPPORT
606         boost::shared_ptr<AUPlugin> ap;
607 #endif
608
609         if ((lp = boost::dynamic_pointer_cast<LadspaPlugin> (other)) != 0) {
610                 return boost::shared_ptr<Plugin> (new LadspaPlugin (*lp));
611 #ifdef LV2_SUPPORT
612         } else if ((lv2p = boost::dynamic_pointer_cast<LV2Plugin> (other)) != 0) {
613                 return boost::shared_ptr<Plugin> (new LV2Plugin (*lv2p));
614 #endif
615 #ifdef VST_SUPPORT
616         } else if ((vp = boost::dynamic_pointer_cast<VSTPlugin> (other)) != 0) {
617                 return boost::shared_ptr<Plugin> (new VSTPlugin (*vp));
618 #endif
619 #ifdef LXVST_SUPPORT
620         } else if ((lxvp = boost::dynamic_pointer_cast<LXVSTPlugin> (other)) != 0) {
621                 return boost::shared_ptr<Plugin> (new LXVSTPlugin (*lxvp));
622 #endif
623 #ifdef AUDIOUNIT_SUPPORT
624         } else if ((ap = boost::dynamic_pointer_cast<AUPlugin> (other)) != 0) {
625                 return boost::shared_ptr<Plugin> (new AUPlugin (*ap));
626 #endif
627         }
628
629         fatal << string_compose (_("programming error: %1"),
630                           X_("unknown plugin type in PluginInsert::plugin_factory"))
631               << endmsg;
632         /*NOTREACHED*/
633         return boost::shared_ptr<Plugin> ((Plugin*) 0);
634 }
635
636 bool
637 PluginInsert::configure_io (ChanCount in, ChanCount out)
638 {
639         Match old_match = _match;
640
641         /* set the matching method and number of plugins that we will use to meet this configuration */
642         _match = private_can_support_io_configuration (in, out);
643         if (set_count (_match.plugins) == false) {
644                 return false;
645         }
646
647         /* a signal needs emitting if we start or stop splitting */
648         if (old_match.method != _match.method && (old_match.method == Split || _match.method == Split)) {
649                 SplittingChanged (); /* EMIT SIGNAL */
650         }
651
652         /* configure plugins */
653         switch (_match.method) {
654         case Split:
655         case Hide:
656                 if (_plugins.front()->configure_io (_plugins.front()->get_info()->n_inputs, out)) {
657                         return false;
658                 }
659                 break;
660
661         default:
662                 if (_plugins.front()->configure_io (in, out) == false) {
663                         return false;
664                 }
665                 break;
666         }
667
668         // we don't know the analysis window size, so we must work with the
669         // current buffer size here. each request for data fills in these
670         // buffers and the analyser makes sure it gets enough data for the
671         // analysis window
672         session().ensure_buffer_set (_signal_analysis_inputs, in);
673         //_signal_analysis_inputs.set_count (in);
674
675         session().ensure_buffer_set (_signal_analysis_outputs, out);
676         //_signal_analysis_outputs.set_count (out);
677
678         // std::cerr << "set counts to i" << in.n_audio() << "/o" << out.n_audio() << std::endl;
679
680         return Processor::configure_io (in, out);
681 }
682
683 /** Decide whether this PluginInsert can support a given IO configuration.
684  *  To do this, we run through a set of possible solutions in rough order of
685  *  preference.
686  *
687  *  @param in Required input channel count.
688  *  @param out Filled in with the output channel count if we return true.
689  *  @return true if the given IO configuration can be supported.
690  */
691 bool
692 PluginInsert::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
693 {
694         return private_can_support_io_configuration (in, out).method != Impossible;
695 }
696
697 /** A private version of can_support_io_configuration which returns the method
698  *  by which the configuration can be matched, rather than just whether or not
699  *  it can be.
700  */
701 PluginInsert::Match
702 PluginInsert::private_can_support_io_configuration (ChanCount const & in, ChanCount& out) const
703 {
704         if (_plugins.front()->reconfigurable_io()) {
705                 /* Plugin has flexible I/O, so delegate to it */
706                 bool const r = _plugins.front()->can_support_io_configuration (in, out);
707                 if (!r) {
708                         return Match (Impossible, 0);
709                 }
710
711                 return Match (Delegate, 1);
712         }
713
714         ChanCount inputs  = _plugins[0]->get_info()->n_inputs;
715         ChanCount outputs = _plugins[0]->get_info()->n_outputs;
716
717         bool no_inputs = true;
718         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
719                 if (inputs.get (*t) != 0) {
720                         no_inputs = false;
721                         break;
722                 }
723         }
724
725         if (no_inputs) {
726                 /* no inputs so we can take any input configuration since we throw it away */
727                 out = outputs;
728                 return Match (NoInputs, 1);
729         }
730
731         /* Plugin inputs match requested inputs exactly */
732         if (inputs == in) {
733                 out = outputs;
734                 return Match (ExactMatch, 1);
735         }
736
737         /* We may be able to run more than one copy of the plugin within this insert
738            to cope with the insert having more inputs than the plugin.
739            We allow replication only for plugins with either zero or 1 inputs and outputs
740            for every valid data type.
741         */
742         
743         uint32_t f             = 0;
744         bool     can_replicate = true;
745         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
746
747                 uint32_t nin = inputs.get (*t);
748
749                 // No inputs of this type
750                 if (nin == 0 && in.get(*t) == 0) {
751                         continue;
752                 }
753
754                 if (nin != 1 || outputs.get (*t) != 1) {
755                         can_replicate = false;
756                         break;
757                 }
758
759                 // Potential factor not set yet
760                 if (f == 0) {
761                         f = in.get(*t) / nin;
762                 }
763
764                 // Factor for this type does not match another type, can not replicate
765                 if (f != (in.get(*t) / nin)) {
766                         can_replicate = false;
767                         break;
768                 }
769         }
770
771         if (can_replicate) {
772                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
773                         out.set (*t, outputs.get(*t) * f);
774                 }
775                 return Match (Replicate, f);
776         }
777
778         /* If the processor has exactly one input of a given type, and
779            the plugin has more, we can feed the single processor input
780            to some or all of the plugin inputs.  This is rather
781            special-case-y, but the 1-to-many case is by far the
782            simplest.  How do I split thy 2 processor inputs to 3
783            plugin inputs?  Let me count the ways ...
784         */
785
786         bool can_split = true;
787         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
788
789                 bool const can_split_type = (in.get (*t) == 1 && inputs.get (*t) > 1);
790                 bool const nothing_to_do_for_type = (in.get (*t) == 0 && inputs.get (*t) == 0);
791
792                 if (!can_split_type && !nothing_to_do_for_type) {
793                         can_split = false;
794                 }
795         }
796
797         if (can_split) {
798                 out = outputs;
799                 return Match (Split, 1);
800         }
801
802         /* If the plugin has more inputs than we want, we can `hide' some of them
803            by feeding them silence.
804         */
805
806         bool can_hide = false;
807         ChanCount hide_channels;
808         
809         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
810                 if (inputs.get(*t) > in.get(*t)) {
811                         hide_channels.set (*t, inputs.get(*t) - in.get(*t));
812                         can_hide = true;
813                 }
814         }
815
816         if (can_hide) {
817                 out = outputs;
818                 return Match (Hide, 1, hide_channels);
819         }
820
821         return Match (Impossible, 0);
822 }
823
824 XMLNode&
825 PluginInsert::get_state ()
826 {
827         return state (true);
828 }
829
830 XMLNode&
831 PluginInsert::state (bool full)
832 {
833         XMLNode& node = Processor::state (full);
834
835         node.add_property("type", _plugins[0]->state_node_name());
836         node.add_property("unique-id", _plugins[0]->unique_id());
837         node.add_property("count", string_compose("%1", _plugins.size()));
838         node.add_child_nocopy (_plugins[0]->get_state());
839
840         for (Controls::iterator c = controls().begin(); c != controls().end(); ++c) {
841                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl> ((*c).second);
842                 if (ac) {
843                         node.add_child_nocopy (ac->get_state());
844                 }
845         }
846
847         return node;
848 }
849
850 void
851 PluginInsert::set_control_ids (const XMLNode& node, int version)
852 {
853         const XMLNodeList& nlist = node.children();
854         XMLNodeConstIterator iter;
855         set<Evoral::Parameter>::const_iterator p;
856
857         for (iter = nlist.begin(); iter != nlist.end(); ++iter) {
858                 if ((*iter)->name() == Controllable::xml_node_name) {
859                         const XMLProperty* prop;
860
861                         if ((prop = (*iter)->property (X_("parameter"))) != 0) {
862                                 uint32_t p = atoi (prop->value());
863                                 boost::shared_ptr<Evoral::Control> c = control (Evoral::Parameter (PluginAutomation, 0, p));
864                                 if (!c) {
865                                         continue;
866                                 }
867                                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl> (c);
868                                 if (ac) {
869                                         ac->set_state (**iter, version);
870                                 }
871                         }
872                 }
873         }
874 }
875
876 int
877 PluginInsert::set_state(const XMLNode& node, int version)
878 {
879         XMLNodeList nlist = node.children();
880         XMLNodeIterator niter;
881         XMLPropertyList plist;
882         const XMLProperty *prop;
883         ARDOUR::PluginType type;
884
885         if ((prop = node.property ("type")) == 0) {
886                 error << _("XML node describing plugin is missing the `type' field") << endmsg;
887                 return -1;
888         }
889
890         if (prop->value() == X_("ladspa") || prop->value() == X_("Ladspa")) { /* handle old school sessions */
891                 type = ARDOUR::LADSPA;
892         } else if (prop->value() == X_("lv2")) {
893                 type = ARDOUR::LV2;
894         } else if (prop->value() == X_("vst")) {
895                 type = ARDOUR::VST;
896         } else if (prop->value() == X_("lxvst")) {
897                 type = ARDOUR::LXVST;
898         } else if (prop->value() == X_("audiounit")) {
899                 type = ARDOUR::AudioUnit;
900         } else {
901                 error << string_compose (_("unknown plugin type %1 in plugin insert state"),
902                                   prop->value())
903                       << endmsg;
904                 return -1;
905         }
906
907         prop = node.property ("unique-id");
908
909         if (prop == 0) {
910 #ifdef VST_SUPPORT
911                 /* older sessions contain VST plugins with only an "id" field.
912                  */
913
914                 if (type == ARDOUR::VST) {
915                         prop = node.property ("id");
916                 }
917 #endif
918
919 #ifdef LXVST_SUPPORT
920                 /*There shouldn't be any older sessions with linuxVST support.. but anyway..*/
921
922                 if (type == ARDOUR::LXVST) {
923                         prop = node.property ("id");
924                 }
925 #endif
926                 /* recheck  */
927
928                 if (prop == 0) {
929                         error << _("Plugin has no unique ID field") << endmsg;
930                         return -1;
931                 }
932         }
933
934         boost::shared_ptr<Plugin> plugin = find_plugin (_session, prop->value(), type);
935
936         if (plugin == 0) {
937                 error << string_compose(
938                         _("Found a reference to a plugin (\"%1\") that is unknown.\n"
939                           "Perhaps it was removed or moved since it was last used."),
940                         prop->value())
941                       << endmsg;
942                 return -1;
943         }
944
945         // The name of the PluginInsert comes from the plugin, nothing else
946         _name = plugin->get_info()->name;
947
948         uint32_t count = 1;
949
950         // Processor::set_state() will set this, but too late
951         // for it to be available when setting up plugin
952         // state. We can't call Processor::set_state() until
953         // the plugins themselves are created and added.
954
955         set_id (node);
956
957         if (_plugins.empty()) {
958                 /* if we are adding the first plugin, we will need to set
959                    up automatable controls.
960                 */
961                 add_plugin (plugin);
962                 create_automatable_parameters ();
963                 set_control_ids (node, version);
964         }
965
966         if ((prop = node.property ("count")) != 0) {
967                 sscanf (prop->value().c_str(), "%u", &count);
968         }
969
970         if (_plugins.size() != count) {
971                 for (uint32_t n = 1; n < count; ++n) {
972                         add_plugin (plugin_factory (plugin));
973                 }
974         }
975
976         Processor::set_state (node, version);
977
978         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
979
980                 /* find the node with the type-specific node name ("lv2", "ladspa", etc)
981                    and set all plugins to the same state.
982                 */
983
984                 if ((*niter)->name() == plugin->state_node_name()) {
985
986                         plugin->set_state (**niter, version);
987
988                         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
989                                 (*i)->set_state (**niter, version);
990                         }
991
992                         break;
993                 }
994         }
995
996         if (version < 3000) {
997
998                 /* Only 2.X sessions need a call to set_parameter_state() - in 3.X and above
999                    this is all handled by Automatable
1000                 */
1001
1002                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1003                         if ((*niter)->name() == "Redirect") {
1004                                 /* XXX do we need to tackle placement? i think not (pd; oct 16 2009) */
1005                                 Processor::set_state (**niter, version);
1006                                 break;
1007                         }
1008                 }
1009
1010                 set_parameter_state_2X (node, version);
1011         }
1012
1013         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1014                 if (active()) {
1015                         (*i)->activate ();
1016                 } else {
1017                         (*i)->deactivate ();
1018                 }
1019         }
1020
1021         return 0;
1022 }
1023
1024 void
1025 PluginInsert::set_parameter_state_2X (const XMLNode& node, int version)
1026 {
1027         XMLNodeList nlist = node.children();
1028         XMLNodeIterator niter;
1029
1030         /* look for port automation node */
1031
1032         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1033
1034                 if ((*niter)->name() != port_automation_node_name) {
1035                         continue;
1036                 }
1037
1038                 XMLNodeList cnodes;
1039                 XMLProperty *cprop;
1040                 XMLNodeConstIterator iter;
1041                 XMLNode *child;
1042                 const char *port;
1043                 uint32_t port_id;
1044
1045                 cnodes = (*niter)->children ("port");
1046
1047                 for (iter = cnodes.begin(); iter != cnodes.end(); ++iter){
1048
1049                         child = *iter;
1050
1051                         if ((cprop = child->property("number")) != 0) {
1052                                 port = cprop->value().c_str();
1053                         } else {
1054                                 warning << _("PluginInsert: Auto: no ladspa port number") << endmsg;
1055                                 continue;
1056                         }
1057
1058                         sscanf (port, "%" PRIu32, &port_id);
1059
1060                         if (port_id >= _plugins[0]->parameter_count()) {
1061                                 warning << _("PluginInsert: Auto: port id out of range") << endmsg;
1062                                 continue;
1063                         }
1064
1065                         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(
1066                                         control(Evoral::Parameter(PluginAutomation, 0, port_id), true));
1067
1068                         if (c) {
1069                                 if (!child->children().empty()) {
1070                                         c->alist()->set_state (*child->children().front(), version);
1071
1072                                         /* In some cases 2.X saves lists with min_yval and max_yval
1073                                            being FLT_MIN and FLT_MAX respectively.  This causes problems
1074                                            in A3 because these min/max values are used to compute
1075                                            where GUI control points should be drawn.  If we see such
1076                                            values, `correct' them to the min/max of the appropriate
1077                                            parameter.
1078                                         */
1079
1080                                         float min_y = c->alist()->get_min_y ();
1081                                         float max_y = c->alist()->get_max_y ();
1082
1083                                         Plugin::ParameterDescriptor desc;
1084                                         _plugins.front()->get_parameter_descriptor (port_id, desc);
1085
1086                                         if (min_y == FLT_MIN) {
1087                                                 min_y = desc.lower;
1088                                         }
1089
1090                                         if (max_y == FLT_MAX) {
1091                                                 max_y = desc.upper;
1092                                         }
1093
1094                                         c->alist()->set_yrange (min_y, max_y);
1095                                 }
1096                         } else {
1097                                 error << string_compose (_("PluginInsert: automatable control %1 not found - ignored"), port_id) << endmsg;
1098                         }
1099                 }
1100
1101                 /* done */
1102
1103                 break;
1104         }
1105 }
1106
1107
1108 string
1109 PluginInsert::describe_parameter (Evoral::Parameter param)
1110 {
1111         if (param.type() != PluginAutomation) {
1112                 return Automatable::describe_parameter(param);
1113         }
1114
1115         return _plugins[0]->describe_parameter (param);
1116 }
1117
1118 ARDOUR::framecnt_t
1119 PluginInsert::signal_latency() const
1120 {
1121         if (_user_latency) {
1122                 return _user_latency;
1123         }
1124
1125         return _plugins[0]->signal_latency ();
1126 }
1127
1128 ARDOUR::PluginType
1129 PluginInsert::type ()
1130 {
1131        return plugin()->get_info()->type;
1132 }
1133
1134 PluginInsert::PluginControl::PluginControl (PluginInsert* p, const Evoral::Parameter &param, boost::shared_ptr<AutomationList> list)
1135         : AutomationControl (p->session(), param, list, p->describe_parameter(param))
1136         , _plugin (p)
1137 {
1138         Plugin::ParameterDescriptor desc;
1139         p->plugin(0)->get_parameter_descriptor (param.id(), desc);
1140         _logarithmic = desc.logarithmic;
1141         _sr_dependent = desc.sr_dependent;
1142         _toggled = desc.toggled;
1143 }
1144
1145 /** @param val `user' value */
1146 void
1147 PluginInsert::PluginControl::set_value (double user_val)
1148 {
1149         /* FIXME: probably should be taking out some lock here.. */
1150
1151         double const plugin_val = user_to_plugin (user_val);
1152
1153         for (Plugins::iterator i = _plugin->_plugins.begin(); i != _plugin->_plugins.end(); ++i) {
1154                 (*i)->set_parameter (_list->parameter().id(), plugin_val);
1155         }
1156
1157         boost::shared_ptr<Plugin> iasp = _plugin->_impulseAnalysisPlugin.lock();
1158         if (iasp) {
1159                 iasp->set_parameter (_list->parameter().id(), plugin_val);
1160         }
1161
1162         AutomationControl::set_value (user_val);
1163 }
1164
1165 double
1166 PluginInsert::PluginControl::user_to_plugin (double val) const
1167 {
1168         /* no known transformations at this time */
1169         return val;
1170 }
1171
1172 double
1173 PluginInsert::PluginControl::user_to_ui (double val) const
1174 {
1175         if (_logarithmic) {
1176                 if (val > 0) {
1177                         val = log (val);
1178                 } else {
1179                         val = 0;
1180                 }
1181         }
1182
1183         return val;
1184 }
1185
1186 double
1187 PluginInsert::PluginControl::ui_to_user (double val) const
1188 {
1189         if (_logarithmic) {
1190                 val = exp (val);
1191         }
1192
1193         return val;
1194 }
1195
1196 /** Convert plugin values to UI values.  See pbd/controllable.h */
1197 double
1198 PluginInsert::PluginControl::plugin_to_ui (double val) const
1199 {
1200         return user_to_ui (plugin_to_user (val));
1201 }
1202
1203 double
1204 PluginInsert::PluginControl::plugin_to_user (double val) const
1205 {
1206         /* no known transformations at this time */
1207         return val;
1208 }
1209
1210 XMLNode&
1211 PluginInsert::PluginControl::get_state ()
1212 {
1213         stringstream ss;
1214
1215         XMLNode& node (AutomationControl::get_state());
1216         ss << parameter().id();
1217         node.add_property (X_("parameter"), ss.str());
1218
1219         return node;
1220 }
1221
1222 /** @return `user' val */
1223 double
1224 PluginInsert::PluginControl::get_value () const
1225 {
1226         /* FIXME: probably should be taking out some lock here.. */
1227
1228         return plugin_to_user (_plugin->get_parameter (_list->parameter()));
1229 }
1230
1231 boost::shared_ptr<Plugin>
1232 PluginInsert::get_impulse_analysis_plugin()
1233 {
1234         boost::shared_ptr<Plugin> ret;
1235         if (_impulseAnalysisPlugin.expired()) {
1236                 ret = plugin_factory(_plugins[0]);
1237                 _impulseAnalysisPlugin = ret;
1238         } else {
1239                 ret = _impulseAnalysisPlugin.lock();
1240         }
1241
1242         return ret;
1243 }
1244
1245 void
1246 PluginInsert::collect_signal_for_analysis (framecnt_t nframes)
1247 {
1248         // called from outside the audio thread, so this should be safe
1249         // only do audio as analysis is (currently) only for audio plugins
1250         _signal_analysis_inputs.ensure_buffers(  DataType::AUDIO, input_streams().n_audio(),  nframes);
1251         _signal_analysis_outputs.ensure_buffers( DataType::AUDIO, output_streams().n_audio(), nframes);
1252
1253         _signal_analysis_collected_nframes   = 0;
1254         _signal_analysis_collect_nframes_max = nframes;
1255 }
1256
1257 /** Add a plugin to our list and activate it if we have already been activated */
1258 void
1259 PluginInsert::add_plugin_with_activation (boost::shared_ptr<Plugin> plugin)
1260 {
1261         plugin->set_insert_info (this);
1262         _plugins.push_back (plugin);
1263         if (active()) {
1264                 plugin->activate ();
1265         }
1266 }
1267
1268 /** Add a plugin to our list */
1269 void
1270 PluginInsert::add_plugin (boost::shared_ptr<Plugin> plugin)
1271 {
1272         plugin->set_insert_info (this);
1273         _plugins.push_back (plugin);
1274 }
1275
1276 void
1277 PluginInsert::realtime_handle_transport_stopped ()
1278 {
1279         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1280                 (*i)->realtime_handle_transport_stopped ();
1281         }
1282 }