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