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