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