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