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