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