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