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