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