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