Fix plugin parameter controllers again (#3767).
[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
27 #include "pbd/failed_constructor.h"
28 #include "pbd/xml++.h"
29 #include "pbd/convert.h"
30
31 #include "ardour/audio_buffer.h"
32 #include "ardour/automation_list.h"
33 #include "ardour/buffer_set.h"
34 #include "ardour/event_type_map.h"
35 #include "ardour/ladspa_plugin.h"
36 #include "ardour/plugin.h"
37 #include "ardour/plugin_insert.h"
38 #include "ardour/port.h"
39 #include "ardour/route.h"
40
41 #ifdef HAVE_SLV2
42 #include "ardour/lv2_plugin.h"
43 #endif
44
45 #ifdef VST_SUPPORT
46 #include "ardour/vst_plugin.h"
47 #endif
48
49 #ifdef HAVE_AUDIOUNITS
50 #include "ardour/audio_unit.h"
51 #endif
52
53 #include "ardour/audioengine.h"
54 #include "ardour/session.h"
55 #include "ardour/types.h"
56
57 #include "i18n.h"
58
59 using namespace std;
60 using namespace ARDOUR;
61 using namespace PBD;
62
63 const string PluginInsert::port_automation_node_name = "PortAutomation";
64
65 PluginInsert::PluginInsert (Session& s, boost::shared_ptr<Plugin> plug)
66         : Processor (s, (plug ? plug->name() : string ("toBeRenamed")))
67         , _signal_analysis_collected_nframes(0)
68         , _signal_analysis_collect_nframes_max(0)
69         , _splitting (false)
70 {
71         /* the first is the master */
72
73         if (plug) {
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 (_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                 /* FIXME: type, audio only */
417
418                 uint32_t in = _plugins[0]->get_info()->n_inputs.n_audio();
419                 uint32_t out = _plugins[0]->get_info()->n_outputs.n_audio();
420
421                 if (out > in) {
422
423                         /* not active, but something has make up for any channel count increase */
424
425                         for (uint32_t n = out - in; n < out; ++n) {
426                                 memcpy (bufs.get_audio(n).data(), bufs.get_audio(in - 1).data(), sizeof (Sample) * nframes);
427                         }
428                 }
429
430                 bufs.count().set_audio(out);
431         }
432
433         _active = _pending_active;
434 }
435
436 void
437 PluginInsert::set_parameter (Evoral::Parameter param, float val)
438 {
439         if (param.type() != PluginAutomation) {
440                 return;
441         }
442
443         /* the others will be set from the event triggered by this */
444
445         _plugins[0]->set_parameter (param.id(), val);
446
447         boost::shared_ptr<AutomationControl> ac
448                         = boost::dynamic_pointer_cast<AutomationControl>(control(param));
449
450         if (ac) {
451                 ac->set_value(val);
452         } else {
453                 warning << "set_parameter called for nonexistant parameter "
454                         << EventTypeMap::instance().to_symbol(param) << endmsg;
455         }
456
457         _session.set_dirty();
458 }
459
460 float
461 PluginInsert::get_parameter (Evoral::Parameter param)
462 {
463         if (param.type() != PluginAutomation) {
464                 return 0.0;
465         } else {
466                 assert (!_plugins.empty ());
467                 return _plugins[0]->get_parameter (param.id());
468         }
469 }
470
471 void
472 PluginInsert::automation_run (BufferSet& bufs, pframes_t nframes)
473 {
474         Evoral::ControlEvent next_event (0, 0.0f);
475         framepos_t now = _session.transport_frame ();
476         framepos_t end = now + nframes;
477         framecnt_t offset = 0;
478
479         Glib::Mutex::Lock lm (control_lock(), Glib::TRY_LOCK);
480
481         if (!lm.locked()) {
482                 connect_and_run (bufs, nframes, offset, false);
483                 return;
484         }
485
486         if (!find_next_event (now, end, next_event) || requires_fixed_sized_buffers()) {
487
488                 /* no events have a time within the relevant range */
489
490                 connect_and_run (bufs, nframes, offset, true, now);
491                 return;
492         }
493
494         while (nframes) {
495
496                 framecnt_t cnt = min (((framecnt_t) ceil (next_event.when) - now), (framecnt_t) nframes);
497
498                 connect_and_run (bufs, cnt, offset, true, now);
499
500                 nframes -= cnt;
501                 offset += cnt;
502                 now += cnt;
503
504                 if (!find_next_event (now, end, next_event)) {
505                         break;
506                 }
507         }
508
509         /* cleanup anything that is left to do */
510
511         if (nframes) {
512                 connect_and_run (bufs, nframes, offset, true, now);
513         }
514 }
515
516 float
517 PluginInsert::default_parameter_value (const Evoral::Parameter& param)
518 {
519         if (param.type() != PluginAutomation)
520                 return 1.0;
521
522         if (_plugins.empty()) {
523                 fatal << _("programming error: ") << X_("PluginInsert::default_parameter_value() called with no plugin")
524                       << endmsg;
525                 /*NOTREACHED*/
526         }
527
528         return _plugins[0]->default_value (param.id());
529 }
530
531 boost::shared_ptr<Plugin>
532 PluginInsert::plugin_factory (boost::shared_ptr<Plugin> other)
533 {
534         boost::shared_ptr<LadspaPlugin> lp;
535 #ifdef HAVE_SLV2
536         boost::shared_ptr<LV2Plugin> lv2p;
537 #endif
538 #ifdef VST_SUPPORT
539         boost::shared_ptr<VSTPlugin> vp;
540 #endif
541 #ifdef HAVE_AUDIOUNITS
542         boost::shared_ptr<AUPlugin> ap;
543 #endif
544
545         if ((lp = boost::dynamic_pointer_cast<LadspaPlugin> (other)) != 0) {
546                 return boost::shared_ptr<Plugin> (new LadspaPlugin (*lp));
547 #ifdef HAVE_SLV2
548         } else if ((lv2p = boost::dynamic_pointer_cast<LV2Plugin> (other)) != 0) {
549                 return boost::shared_ptr<Plugin> (new LV2Plugin (*lv2p));
550 #endif
551 #ifdef VST_SUPPORT
552         } else if ((vp = boost::dynamic_pointer_cast<VSTPlugin> (other)) != 0) {
553                 return boost::shared_ptr<Plugin> (new VSTPlugin (*vp));
554 #endif
555 #ifdef HAVE_AUDIOUNITS
556         } else if ((ap = boost::dynamic_pointer_cast<AUPlugin> (other)) != 0) {
557                 return boost::shared_ptr<Plugin> (new AUPlugin (*ap));
558 #endif
559         }
560
561         fatal << string_compose (_("programming error: %1"),
562                           X_("unknown plugin type in PluginInsert::plugin_factory"))
563               << endmsg;
564         /*NOTREACHED*/
565         return boost::shared_ptr<Plugin> ((Plugin*) 0);
566 }
567
568 bool
569 PluginInsert::configure_io (ChanCount in, ChanCount out)
570 {
571         if (set_count (count_for_configuration (in, out)) == false) {
572                 set_splitting (false);
573                 return false;
574         }
575
576         if (_plugins.front()->get_info()->n_inputs <= in) {
577                 set_splitting (false);
578                 if (_plugins.front()->configure_io (in, out) == false) {
579                         return false;
580                 }
581         } else {
582                 /* we must be splitting a single processor input to
583                    multiple plugin inputs
584                 */
585                 set_splitting (true);
586                 _plugins.front()->configure_io (_plugins.front()->get_info()->n_inputs, out);
587         }
588
589         // we don't know the analysis window size, so we must work with the
590         // current buffer size here. each request for data fills in these
591         // buffers and the analyser makes sure it gets enough data for the
592         // analysis window
593         session().ensure_buffer_set (_signal_analysis_inputs, in);
594         //_signal_analysis_inputs.set_count (in);
595
596         session().ensure_buffer_set (_signal_analysis_outputs, out);
597         //_signal_analysis_outputs.set_count (out);
598
599         // std::cerr << "set counts to i" << in.n_audio() << "/o" << out.n_audio() << std::endl;
600
601         return Processor::configure_io (in, out);
602 }
603
604 bool
605 PluginInsert::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
606 {
607         // Plugin has flexible I/O, so delegate to it
608         if (_plugins.front()->reconfigurable_io()) {
609                 return _plugins.front()->can_support_io_configuration (in, out);
610         }
611
612         ChanCount inputs  = _plugins[0]->get_info()->n_inputs;
613         ChanCount outputs = _plugins[0]->get_info()->n_outputs;
614
615         // Plugin inputs match requested inputs exactly
616         if (inputs == in) {
617                 out = outputs;
618                 return true;
619         }
620
621         // See if replication is possible
622         // We allow replication only for plugins with either zero or 1 inputs and outputs
623         // for every valid data type.
624         uint32_t f             = 0;
625         bool     can_replicate = true;
626         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
627                 // No inputs of this type
628                 if (inputs.get(*t) == 0 && in.get(*t) == 0) {
629                         continue;
630                 }
631
632                 if (inputs.get(*t) != 1 || outputs.get (*t) != 1) {
633                         can_replicate = false;
634                         break;
635                 }
636
637                 // Potential factor not set yet
638
639                 if (f == 0) {
640                         f = in.get(*t) / inputs.get(*t);;
641                 }
642
643                 // Factor for this type does not match another type, can not replicate
644                 if (f != (in.get(*t) / inputs.get(*t))) {
645                         can_replicate = false;
646                         break;
647                 }
648         }
649
650         if (can_replicate) {
651                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
652                         out.set (*t, outputs.get(*t) * f);
653                 }
654                 return true;
655         }
656
657         /* If the processor has exactly one input of a given type, and
658            the plugin has more, we can feed the single processor input
659            to some or all of the plugin inputs.  This is rather
660            special-case-y, but the 1-to-many case is by far the
661            simplest.  How do I split thy 2 processor inputs to 3
662            plugin inputs?  Let me count the ways ...
663         */
664
665         bool can_split = true;
666         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
667
668                 bool const can_split_type = (in.get (*t) == 1 && inputs.get (*t) > 1);
669                 bool const nothing_to_do_for_type = (in.get (*t) == 0 && inputs.get (*t) == 0);
670
671                 if (!can_split_type && !nothing_to_do_for_type) {
672                         can_split = false;
673                 }
674         }
675
676         if (can_split) {
677                 out = outputs;
678                 return true;
679         }
680
681         return false;
682 }
683
684 /* Number of plugin instances required to support a given channel configuration.
685  * (private helper)
686  */
687 int32_t
688 PluginInsert::count_for_configuration (ChanCount in, ChanCount /*out*/) const
689 {
690         if (_plugins.front()->reconfigurable_io()) {
691                 /* plugin has flexible I/O, so the answer is always 1 */
692                 /* this could change if we ever decide to replicate AU's */
693                 return 1;
694         }
695
696         // FIXME: take 'out' into consideration
697
698         ChanCount outputs = _plugins[0]->get_info()->n_outputs;
699         ChanCount inputs = _plugins[0]->get_info()->n_inputs;
700
701         if (inputs.n_total() == 0) {
702                 /* instrument plugin, always legal, but throws away any existing streams */
703                 return 1;
704         }
705
706         if (inputs.n_total() == 1 && outputs == inputs
707                         && ((inputs.n_audio() == 0 && in.n_audio() == 0)
708                                 || (inputs.n_midi() == 0 && in.n_midi() == 0))) {
709                 /* mono plugin, replicate as needed to match in */
710                 return in.n_total();
711         }
712
713         if (inputs == in) {
714                 /* exact match */
715                 return 1;
716         }
717
718         if (inputs > in) {
719                 /* more plugin inputs than processor inputs, so we are splitting */
720                 return 1;
721         }
722
723         // assumes in is valid, so we must be replicating
724         if (inputs.n_total() < in.n_total()
725                         && (in.n_total() % inputs.n_total() == 0)) {
726
727                 return in.n_total() / inputs.n_total();
728         }
729
730         /* err... */
731         return 0;
732 }
733
734 XMLNode&
735 PluginInsert::get_state(void)
736 {
737         return state (true);
738 }
739
740 XMLNode&
741 PluginInsert::state (bool full)
742 {
743         XMLNode& node = Processor::state (full);
744
745         node.add_property("type", _plugins[0]->state_node_name());
746         node.add_property("unique-id", _plugins[0]->unique_id());
747         node.add_property("count", string_compose("%1", _plugins.size()));
748         node.add_child_nocopy (_plugins[0]->get_state());
749
750         for (Controls::iterator c = controls().begin(); c != controls().end(); ++c) {
751                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl> ((*c).second);
752                 if (ac) {
753                         node.add_child_nocopy (ac->get_state());
754                 }
755         }
756
757         return node;
758 }
759
760 void
761 PluginInsert::set_control_ids (const XMLNode& node, int version)
762 {
763         const XMLNodeList& nlist = node.children();
764         XMLNodeConstIterator iter;
765         set<Evoral::Parameter>::const_iterator p;
766
767         for (iter = nlist.begin(); iter != nlist.end(); ++iter) {
768                 if ((*iter)->name() == Controllable::xml_node_name) {
769                         const XMLProperty* prop;
770
771                         if ((prop = (*iter)->property (X_("parameter"))) != 0) {
772                                 uint32_t p = atoi (prop->value());
773                                 boost::shared_ptr<Evoral::Control> c = control (Evoral::Parameter (PluginAutomation, 0, p));
774                                 if (!c) {
775                                         continue;
776                                 }
777                                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl> (c);
778                                 if (ac) {
779                                         ac->set_state (**iter, version);
780                                 }
781                         }
782                 }
783         }
784 }
785 int
786 PluginInsert::set_state(const XMLNode& node, int version)
787 {
788         XMLNodeList nlist = node.children();
789         XMLNodeIterator niter;
790         XMLPropertyList plist;
791         const XMLProperty *prop;
792         ARDOUR::PluginType type;
793
794         if ((prop = node.property ("type")) == 0) {
795                 error << _("XML node describing plugin is missing the `type' field") << endmsg;
796                 return -1;
797         }
798
799         if (prop->value() == X_("ladspa") || prop->value() == X_("Ladspa")) { /* handle old school sessions */
800                 type = ARDOUR::LADSPA;
801         } else if (prop->value() == X_("lv2")) {
802                 type = ARDOUR::LV2;
803         } else if (prop->value() == X_("vst")) {
804                 type = ARDOUR::VST;
805         } else if (prop->value() == X_("audiounit")) {
806                 type = ARDOUR::AudioUnit;
807         } else {
808                 error << string_compose (_("unknown plugin type %1 in plugin insert state"),
809                                   prop->value())
810                       << endmsg;
811                 return -1;
812         }
813
814         prop = node.property ("unique-id");
815
816         if (prop == 0) {
817 #ifdef VST_SUPPORT
818                 /* older sessions contain VST plugins with only an "id" field.
819                  */
820                 
821                 if (type == ARDOUR::VST) {
822                         prop = node.property ("id");
823                 }
824 #endif          
825                 /* recheck  */
826
827                 if (prop == 0) {
828                         error << _("Plugin has no unique ID field") << endmsg;
829                         return -1;
830                 }
831         }
832
833         boost::shared_ptr<Plugin> plugin;
834
835         plugin = find_plugin (_session, prop->value(), type);
836
837         if (plugin == 0) {
838                 error << string_compose(_("Found a reference to a plugin (\"%1\") that is unknown.\n"
839                                    "Perhaps it was removed or moved since it was last used."), prop->value())
840                       << endmsg;
841                 return -1;
842         }
843
844         uint32_t count = 1;
845         bool need_automatables = true;
846
847         if (_plugins.empty()) {
848                 /* if we are adding the first plugin, we will need to set
849                    up automatable controls.
850                 */
851                 need_automatables = true;
852         }
853
854         if ((prop = node.property ("count")) != 0) {
855                 sscanf (prop->value().c_str(), "%u", &count);
856         }
857
858         if (_plugins.size() != count) {
859
860                 add_plugin_with_activation (plugin);
861
862                 for (uint32_t n = 1; n < count; ++n) {
863                         add_plugin_with_activation (plugin_factory (plugin));
864                 }
865         }
866
867         if (need_automatables) {
868                 set_automatable ();
869                 set_control_ids (node, version);
870         }
871
872         /* Handle the node list for this Processor (or Insert if an A2 session) */
873         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
874
875                 if ((*niter)->name() == plugin->state_node_name()) {
876
877                         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
878                                 (*i)->set_state (**niter, version);
879                         }
880                         break;
881                 }
882         }
883
884         Processor::set_state (node, version);
885
886         if (version < 3000) {
887
888                 /* Only 2.X sessions need a call to set_parameter_state() - in 3.X and above
889                    this is all handled by Automatable
890                 */
891
892                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
893                         if ((*niter)->name() == "Redirect") {
894                                 /* XXX do we need to tackle placement? i think not (pd; oct 16 2009) */
895                                 Processor::set_state (**niter, version);
896                                 break;
897                         }
898                 }
899                 
900                 set_parameter_state_2X (node, version);
901         }
902
903         // The name of the PluginInsert comes from the plugin, nothing else
904         _name = plugin->get_info()->name;
905
906         /* catch up on I/O */
907
908         {
909                 Glib::Mutex::Lock em (_session.engine().process_lock());
910                 IO::PortCountChanged (max(input_streams(), output_streams()));
911         }
912
913         return 0;
914 }
915
916 void
917 PluginInsert::set_parameter_state_2X (const XMLNode& node, int version)
918 {
919         XMLNodeList nlist = node.children();
920         XMLNodeIterator niter;
921
922         /* look for port automation node */
923         
924         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
925
926                 if ((*niter)->name() != port_automation_node_name) {
927                         continue;
928                 }
929
930                 XMLNodeList cnodes;
931                 XMLProperty *cprop;
932                 XMLNodeConstIterator iter;
933                 XMLNode *child;
934                 const char *port;
935                 uint32_t port_id;
936
937                 cnodes = (*niter)->children ("port");
938
939                 for (iter = cnodes.begin(); iter != cnodes.end(); ++iter){
940                         
941                         child = *iter;
942                         
943                         if ((cprop = child->property("number")) != 0) {
944                                 port = cprop->value().c_str();
945                         } else {
946                                 warning << _("PluginInsert: Auto: no ladspa port number") << endmsg;
947                                 continue;
948                         }
949                         
950                         sscanf (port, "%" PRIu32, &port_id);
951                         
952                         if (port_id >= _plugins[0]->parameter_count()) {
953                                 warning << _("PluginInsert: Auto: port id out of range") << endmsg;
954                                 continue;
955                         }
956
957                         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(
958                                         control(Evoral::Parameter(PluginAutomation, 0, port_id), true));
959
960                         if (c) {
961                                 if (!child->children().empty()) {
962                                         c->alist()->set_state (*child->children().front(), version);
963
964                                         /* In some cases 2.X saves lists with min_yval and max_yval
965                                            being FLT_MIN and FLT_MAX respectively.  This causes problems
966                                            in A3 because these min/max values are used to compute
967                                            where GUI control points should be drawn.  If we see such
968                                            values, `correct' them to the min/max of the appropriate
969                                            parameter.
970                                         */
971
972                                         float min_y = c->alist()->get_min_y ();
973                                         float max_y = c->alist()->get_max_y ();
974
975                                         Plugin::ParameterDescriptor desc;
976                                         _plugins.front()->get_parameter_descriptor (port_id, desc);
977
978                                         if (min_y == FLT_MIN) {
979                                                 min_y = desc.lower;
980                                         }
981                                         
982                                         if (max_y == FLT_MAX) {
983                                                 max_y = desc.upper;
984                                         }
985
986                                         c->alist()->set_yrange (min_y, max_y);
987                                 }
988                         } else {
989                                 error << string_compose (_("PluginInsert: automatable control %1 not found - ignored"), port_id) << endmsg;
990                         }
991                 }
992                 
993                 /* done */
994                 
995                 break;
996         } 
997 }
998
999
1000 string
1001 PluginInsert::describe_parameter (Evoral::Parameter param)
1002 {
1003         if (param.type() != PluginAutomation) {
1004                 return Automatable::describe_parameter(param);
1005         }
1006
1007         return _plugins[0]->describe_parameter (param);
1008 }
1009
1010 ARDOUR::framecnt_t
1011 PluginInsert::signal_latency() const
1012 {
1013         if (_user_latency) {
1014                 return _user_latency;
1015         }
1016
1017         return _plugins[0]->signal_latency ();
1018 }
1019
1020 ARDOUR::PluginType
1021 PluginInsert::type ()
1022 {
1023        return plugin()->get_info()->type;
1024 }
1025
1026 PluginInsert::PluginControl::PluginControl (PluginInsert* p, const Evoral::Parameter &param, boost::shared_ptr<AutomationList> list)
1027         : AutomationControl (p->session(), param, list, p->describe_parameter(param))
1028         , _plugin (p)
1029 {
1030         Plugin::ParameterDescriptor desc;
1031         p->plugin(0)->get_parameter_descriptor (param.id(), desc);
1032         _logarithmic = desc.logarithmic;
1033         _sr_dependent = desc.sr_dependent;
1034         _toggled = desc.toggled;
1035 }
1036
1037 /** @param val `user' value */
1038 void
1039 PluginInsert::PluginControl::set_value (double user_val)
1040 {
1041         /* FIXME: probably should be taking out some lock here.. */
1042
1043         double const plugin_val = user_to_plugin (user_val);
1044
1045         for (Plugins::iterator i = _plugin->_plugins.begin(); i != _plugin->_plugins.end(); ++i) {
1046                 (*i)->set_parameter (_list->parameter().id(), plugin_val);
1047         }
1048
1049         boost::shared_ptr<Plugin> iasp = _plugin->_impulseAnalysisPlugin.lock();
1050         if (iasp) {
1051                 iasp->set_parameter (_list->parameter().id(), plugin_val);
1052         }
1053
1054         AutomationControl::set_value (user_val);
1055 }
1056
1057 double
1058 PluginInsert::PluginControl::user_to_plugin (double val) const
1059 {
1060         if (_sr_dependent) {
1061                 val /= _session.frame_rate ();
1062         }
1063         
1064         return val;
1065 }
1066
1067 double
1068 PluginInsert::PluginControl::user_to_ui (double val) const
1069 {
1070         if (_logarithmic) {
1071                 if (val > 0) {
1072                         val = log (val);
1073                 } else {
1074                         val = 0;
1075                 }
1076         }
1077
1078         return val;
1079 }
1080
1081 double
1082 PluginInsert::PluginControl::ui_to_user (double val) const
1083 {
1084         if (_logarithmic) {
1085                 val = exp (val);
1086         }
1087
1088         return val;
1089 }
1090
1091 /** Convert plugin values to UI values.  See pbd/controllable.h */
1092 double
1093 PluginInsert::PluginControl::plugin_to_ui (double val) const
1094 {
1095         return user_to_ui (plugin_to_user (val));
1096 }
1097
1098 double
1099 PluginInsert::PluginControl::plugin_to_user (double val) const
1100 {
1101         if (_sr_dependent) {
1102                 val = val * _session.frame_rate ();
1103         }
1104
1105         return val;
1106 }
1107
1108 XMLNode&
1109 PluginInsert::PluginControl::get_state ()
1110 {
1111         stringstream ss;
1112
1113         XMLNode& node (AutomationControl::get_state());
1114         ss << parameter().id();
1115         node.add_property (X_("parameter"), ss.str());
1116
1117         return node;
1118 }
1119
1120 /** @return `user' val */
1121 double
1122 PluginInsert::PluginControl::get_value () const
1123 {
1124         /* FIXME: probably should be taking out some lock here.. */
1125
1126         return plugin_to_user (_plugin->get_parameter (_list->parameter()));
1127 }
1128
1129 boost::shared_ptr<Plugin>
1130 PluginInsert::get_impulse_analysis_plugin()
1131 {
1132         boost::shared_ptr<Plugin> ret;
1133         if (_impulseAnalysisPlugin.expired()) {
1134                 ret = plugin_factory(_plugins[0]);
1135                 _impulseAnalysisPlugin = ret;
1136         } else {
1137                 ret = _impulseAnalysisPlugin.lock();
1138         }
1139
1140         return ret;
1141 }
1142
1143 void
1144 PluginInsert::collect_signal_for_analysis (framecnt_t nframes)
1145 {
1146         // called from outside the audio thread, so this should be safe
1147         // only do audio as analysis is (currently) only for audio plugins
1148         _signal_analysis_inputs.ensure_buffers(  DataType::AUDIO, input_streams().n_audio(),  nframes);
1149         _signal_analysis_outputs.ensure_buffers( DataType::AUDIO, output_streams().n_audio(), nframes);
1150
1151         _signal_analysis_collected_nframes   = 0;
1152         _signal_analysis_collect_nframes_max = nframes;
1153 }
1154
1155 /** Add a plugin to our list and activate it if we have already been activated */
1156 void
1157 PluginInsert::add_plugin_with_activation (boost::shared_ptr<Plugin> plugin)
1158 {
1159         _plugins.push_back (plugin);
1160         if (active()) {
1161                 plugin->activate ();
1162         }
1163 }
1164
1165 void
1166 PluginInsert::realtime_handle_transport_stopped ()
1167 {
1168         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
1169                 (*i)->realtime_handle_transport_stopped ();
1170         }
1171 }
1172
1173 void
1174 PluginInsert::set_splitting (bool s)
1175 {
1176         if (_splitting == s) {
1177                 return;
1178         }
1179                         
1180         _splitting = s;
1181         SplittingChanged (); /* EMIT SIGNAL */
1182 }