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