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