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