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