hopefully fix the build, and actually use the options
[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()) {
381
382                 if (_session.transport_rolling()) {
383                         automation_run (bufs, nframes);
384                 } else {
385                         connect_and_run (bufs, nframes, 0, false);
386                 }
387         } else {
388
389                 /* FIXME: type, audio only */
390
391                 uint32_t in = _plugins[0]->get_info()->n_inputs.n_audio();
392                 uint32_t out = _plugins[0]->get_info()->n_outputs.n_audio();
393
394                 if (out > in) {
395
396                         /* not active, but something has make up for any channel count increase */
397                         
398                         for (uint32_t n = out - in; n < out; ++n) {
399                                 memcpy (bufs.get_audio(n).data(), bufs.get_audio(in - 1).data(), sizeof (Sample) * nframes);
400                         }
401                 }
402
403                 bufs.count().set_audio(out);
404         }
405 }
406
407 void
408 PluginInsert::set_parameter (Evoral::Parameter param, float val)
409 {
410         if (param.type() != PluginAutomation)
411                 return;
412
413         /* the others will be set from the event triggered by this */
414
415         _plugins[0]->set_parameter (param.id(), val);
416         
417         boost::shared_ptr<AutomationControl> ac
418                         = boost::dynamic_pointer_cast<AutomationControl>(data().control(param));
419         
420         if (ac) {
421                 ac->set_value(val);
422         } else {
423                 warning << "set_parameter called for nonexistant parameter "
424                         << EventTypeMap::instance().to_symbol(param) << endmsg;
425         }
426
427         _session.set_dirty();
428 }
429
430 float
431 PluginInsert::get_parameter (Evoral::Parameter param)
432 {
433         if (param.type() != PluginAutomation)
434                 return 0.0;
435         else
436                 return
437                 _plugins[0]->get_parameter (param.id());
438 }
439
440 void
441 PluginInsert::automation_run (BufferSet& bufs, nframes_t nframes)
442 {
443         Evoral::ControlEvent next_event (0, 0.0f);
444         nframes_t now = _session.transport_frame ();
445         nframes_t end = now + nframes;
446         nframes_t offset = 0;
447
448         Glib::Mutex::Lock lm (data().control_lock(), Glib::TRY_LOCK);
449
450         if (!lm.locked()) {
451                 connect_and_run (bufs, nframes, offset, false);
452                 return;
453         }
454         
455         if (!data().find_next_event (now, end, next_event)) {
456                 
457                 /* no events have a time within the relevant range */
458                 
459                 connect_and_run (bufs, nframes, offset, true, now);
460                 return;
461         }
462         
463         while (nframes) {
464
465                 nframes_t cnt = min (((nframes_t) ceil (next_event.when) - now), nframes);
466   
467                 connect_and_run (bufs, cnt, offset, true, now);
468                 
469                 nframes -= cnt;
470                 offset += cnt;
471                 now += cnt;
472
473                 if (!data().find_next_event (now, end, next_event)) {
474                         break;
475                 }
476         }
477   
478         /* cleanup anything that is left to do */
479   
480         if (nframes) {
481                 connect_and_run (bufs, nframes, offset, true, now);
482         }
483 }       
484
485 float
486 PluginInsert::default_parameter_value (const Evoral::Parameter& param)
487 {
488         if (param.type() != PluginAutomation)
489                 return 1.0;
490
491         if (_plugins.empty()) {
492                 fatal << _("programming error: ") << X_("PluginInsert::default_parameter_value() called with no plugin")
493                       << endmsg;
494                 /*NOTREACHED*/
495         }
496
497         return _plugins[0]->default_value (param.id());
498 }
499
500 boost::shared_ptr<Plugin>
501 PluginInsert::plugin_factory (boost::shared_ptr<Plugin> other)
502 {
503         boost::shared_ptr<LadspaPlugin> lp;
504 #ifdef HAVE_SLV2
505         boost::shared_ptr<LV2Plugin> lv2p;
506 #endif
507 #ifdef VST_SUPPORT
508         boost::shared_ptr<VSTPlugin> vp;
509 #endif
510 #ifdef HAVE_AUDIOUNITS
511         boost::shared_ptr<AUPlugin> ap;
512 #endif
513
514         if ((lp = boost::dynamic_pointer_cast<LadspaPlugin> (other)) != 0) {
515                 return boost::shared_ptr<Plugin> (new LadspaPlugin (*lp));
516 #ifdef HAVE_SLV2
517         } else if ((lv2p = boost::dynamic_pointer_cast<LV2Plugin> (other)) != 0) {
518                 return boost::shared_ptr<Plugin> (new LV2Plugin (*lv2p));
519 #endif
520 #ifdef VST_SUPPORT
521         } else if ((vp = boost::dynamic_pointer_cast<VSTPlugin> (other)) != 0) {
522                 return boost::shared_ptr<Plugin> (new VSTPlugin (*vp));
523 #endif
524 #ifdef HAVE_AUDIOUNITS
525         } else if ((ap = boost::dynamic_pointer_cast<AUPlugin> (other)) != 0) {
526                 return boost::shared_ptr<Plugin> (new AUPlugin (*ap));
527 #endif
528         }
529
530         fatal << string_compose (_("programming error: %1"),
531                           X_("unknown plugin type in PluginInsert::plugin_factory"))
532               << endmsg;
533         /*NOTREACHED*/
534         return boost::shared_ptr<Plugin> ((Plugin*) 0);
535 }
536
537 bool
538 PluginInsert::configure_io (ChanCount in, ChanCount out)
539 {
540         if (set_count (count_for_configuration (in, out)) < 0) {
541                 return false;
542         }
543
544         /* if we're running replicated plugins, each plugin has
545            the same i/o configuration and we may need to announce how many
546            output streams there are.
547
548            if we running a single plugin, we need to configure it.
549         */
550
551         if (_plugins.front()->configure_io (in, out) < 0) {
552                 return false;
553         }
554
555         // we don't know the analysis window size, so we must work with the
556         // current buffer size here. each request for data fills in these
557         // buffers and the analyser makes sure it gets enough data for the 
558         // analysis window
559         session().ensure_buffer_set (_signal_analysis_inputs, in);
560         //_signal_analysis_inputs.set_count (in);
561         
562         session().ensure_buffer_set (_signal_analysis_outputs, out);
563         //_signal_analysis_outputs.set_count (out);
564
565         // std::cerr << "set counts to i" << in.n_audio() << "/o" << out.n_audio() << std::endl;
566
567         return Processor::configure_io (in, out);
568 }
569
570 bool
571 PluginInsert::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
572 {
573         // Plugin has flexible I/O, so delegate to it
574         if (_plugins.front()->reconfigurable_io()) {
575                 return _plugins.front()->can_support_io_configuration (in, out);
576         }
577
578         ChanCount inputs  = _plugins[0]->get_info()->n_inputs;
579         ChanCount outputs = _plugins[0]->get_info()->n_outputs;
580
581         // Plugin inputs match requested inputs exactly
582         if (inputs == in) {
583                 out = outputs;
584                 return true;
585         }
586
587         // See if replication is possible
588         // We can replicate if there exists a single factor f such that, for every type,
589         // the number of plugin inputs * f = the requested number of inputs
590         uint32_t f             = 0;
591         bool     can_replicate = true;
592         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
593                 // No inputs of this type
594                 if (inputs.get(*t) == 0 && in.get(*t) == 0) {
595                         continue;
596
597                 // Plugin has more inputs than requested, can not replicate
598                 } else if (inputs.get(*t) >= in.get(*t)) {
599                         can_replicate = false;
600                         break;
601                 
602                 // Plugin inputs is not a factor of requested inputs, can not replicate
603                 } else if (inputs.get(*t) == 0 || in.get(*t) % inputs.get(*t) != 0) {
604                         can_replicate = false;
605                         break;
606                 
607                 // Potential factor not set yet
608                 } else if (f == 0) {
609                         f = in.get(*t) / inputs.get(*t);;
610                 }
611
612                 // Factor for this type does not match another type, can not replicate
613                 if (f != (in.get(*t) / inputs.get(*t))) {
614                         can_replicate = false;
615                         break;
616                 }
617         }
618
619         if (can_replicate) {
620                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
621                         out.set (*t, outputs.get(*t) * f);
622                 }
623                 return true;
624         } else {
625                 return false;
626         }
627 }
628
629 /* Number of plugin instances required to support a given channel configuration.
630  * (private helper)
631  */
632 int32_t
633 PluginInsert::count_for_configuration (ChanCount in, ChanCount out) const
634 {
635         if (_plugins.front()->reconfigurable_io()) {
636                 /* plugin has flexible I/O, so the answer is always 1 */
637                 /* this could change if we ever decide to replicate AU's */
638                 return 1;
639         }
640
641         // FIXME: take 'out' into consideration
642         
643         ChanCount outputs = _plugins[0]->get_info()->n_outputs;
644         ChanCount inputs = _plugins[0]->get_info()->n_inputs;
645
646         if (inputs.n_total() == 0) {
647                 /* instrument plugin, always legal, but throws away any existing streams */
648                 return 1;
649         }
650
651         if (inputs.n_total() == 1 && outputs == inputs
652                         && ((inputs.n_audio() == 0 && in.n_audio() == 0)
653                                 || (inputs.n_midi() == 0 && in.n_midi() == 0))) {
654                 /* mono plugin, replicate as needed to match in */
655                 return in.n_total();
656         }
657
658         if (inputs == in) {
659                 /* exact match */
660                 return 1;
661         }
662
663         // assumes in is valid, so we must be replicating
664         if (inputs.n_total() < in.n_total()
665                         && (in.n_total() % inputs.n_total() == 0)) {
666
667                 return in.n_total() / inputs.n_total();
668         }
669
670         /* err... */
671         return 0;
672 }
673
674 XMLNode&
675 PluginInsert::get_state(void)
676 {
677         return state (true);
678 }
679
680 XMLNode&
681 PluginInsert::state (bool full)
682 {
683         XMLNode& node = Processor::state (full);
684
685         node.add_property("type", _plugins[0]->state_node_name());
686         node.add_property("unique-id", _plugins[0]->unique_id());
687         node.add_property("count", string_compose("%1", _plugins.size()));
688         node.add_child_nocopy (_plugins[0]->get_state());
689
690         /* add port automation state */
691         //XMLNode *autonode = new XMLNode(port_automation_node_name);
692         set<Evoral::Parameter> automatable = _plugins[0]->automatable();
693         
694         for (set<Evoral::Parameter>::iterator x = automatable.begin(); x != automatable.end(); ++x) {
695                 
696                 /*XMLNode* child = new XMLNode("port");
697                 snprintf(buf, sizeof(buf), "%" PRIu32, *x);
698                 child->add_property("number", string(buf));
699                 
700                 child->add_child_nocopy (automation_list (*x).state (full));
701                 autonode->add_child_nocopy (*child);
702                 */
703                 //autonode->add_child_nocopy (((AutomationList*)data().control(*x)->list().get())->state (full));
704         }
705
706         //node.add_child_nocopy (*autonode);
707         
708         return node;
709 }
710
711 int
712 PluginInsert::set_state(const XMLNode& node)
713 {
714         XMLNodeList nlist = node.children();
715         XMLNodeIterator niter;
716         XMLPropertyList plist;
717         const XMLProperty *prop;
718         ARDOUR::PluginType type;
719
720         if ((prop = node.property ("type")) == 0) {
721                 error << _("XML node describing insert is missing the `type' field") << endmsg;
722                 return -1;
723         }
724
725         if (prop->value() == X_("ladspa") || prop->value() == X_("Ladspa")) { /* handle old school sessions */
726                 type = ARDOUR::LADSPA;
727         } else if (prop->value() == X_("lv2")) {
728                 type = ARDOUR::LV2;
729         } else if (prop->value() == X_("vst")) {
730                 type = ARDOUR::VST;
731         } else {
732                 error << string_compose (_("unknown plugin type %1 in plugin insert state"),
733                                   prop->value())
734                       << endmsg;
735                 return -1;
736         }
737         
738         prop = node.property ("unique-id");
739         if (prop == 0) {
740                 error << _("Plugin has no unique ID field") << endmsg;
741                 return -1;
742         }
743
744         boost::shared_ptr<Plugin> plugin;
745         
746         plugin = find_plugin (_session, prop->value(), type);   
747
748         if (plugin == 0) {
749                 error << string_compose(_("Found a reference to a plugin (\"%1\") that is unknown.\n"
750                                    "Perhaps it was removed or moved since it was last used."), prop->value()) 
751                       << endmsg;
752                 return -1;
753         }
754
755         uint32_t count = 1;
756
757         if ((prop = node.property ("count")) != 0) {
758                 sscanf (prop->value().c_str(), "%u", &count);
759         }
760
761         if (_plugins.size() != count) {
762                 
763                 _plugins.push_back (plugin);
764                 
765                 for (uint32_t n=1; n < count; ++n) {
766                         _plugins.push_back (plugin_factory (plugin));
767                 }
768         }
769         
770         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
771                 if ((*niter)->name() == plugin->state_node_name()) {
772                         for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
773                                 (*i)->set_state (**niter);
774                         }
775                         break;
776                 }
777         } 
778
779         const XMLNode* insert_node = &node;
780
781         // legacy sessions: search for child IOProcessor node
782         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
783                 if ((*niter)->name() == "IOProcessor") {
784                         insert_node = *niter;
785                         break;
786                 }
787         }
788         
789         Processor::set_state (*insert_node);
790
791         /* look for port automation node */
792         
793         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
794
795                 if ((*niter)->name() != port_automation_node_name) {
796                         continue;
797                 }
798
799                 XMLNodeList cnodes;
800                 XMLProperty *cprop;
801                 XMLNodeConstIterator iter;
802                 XMLNode *child;
803                 const char *port;
804                 uint32_t port_id;
805                 
806                 cnodes = (*niter)->children ("Port");
807                 
808                 for (iter = cnodes.begin(); iter != cnodes.end(); ++iter) {
809                         
810                         child = *iter;
811                         
812                         if ((cprop = child->property("number")) != 0) {
813                                 port = cprop->value().c_str();
814                         } else {
815                                 warning << _("PluginInsert: Auto: no plugin port number") << endmsg;
816                                 continue;
817                         }
818                         
819                         sscanf (port, "%" PRIu32, &port_id);
820                         
821                         if (port_id >= _plugins[0]->parameter_count()) {
822                                 warning << _("PluginInsert: Auto: port id out of range") << endmsg;
823                                 continue;
824                         }
825
826                         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(
827                                         data().control(Evoral::Parameter(PluginAutomation, 0, port_id), true));
828
829                         if (!child->children().empty()) {
830                                 c->alist()->set_state (*child->children().front());
831                         } else {
832                                 if ((cprop = child->property("auto")) != 0) {
833                                         
834                                         /* old school */
835
836                                         int x;
837                                         sscanf (cprop->value().c_str(), "0x%x", &x);
838                                         c->alist()->set_automation_state (AutoState (x));
839
840                                 } else {
841                                         
842                                         /* missing */
843                                         
844                                         c->alist()->set_automation_state (Off);
845                                 }
846                         }
847
848                 }
849
850                 /* done */
851
852                 break;
853         } 
854
855         // The name of the PluginInsert comes from the plugin, nothing else
856         _name = plugin->get_info()->name;
857         
858         return 0;
859 }
860
861 string
862 PluginInsert::describe_parameter (Evoral::Parameter param)
863 {
864         if (param.type() != PluginAutomation)
865                 return Automatable::describe_parameter(param);
866
867         return _plugins[0]->describe_parameter (param);
868 }
869
870 ARDOUR::nframes_t 
871 PluginInsert::signal_latency() const
872 {
873         if (_user_latency) {
874                 return _user_latency;
875         }
876
877         return _plugins[0]->signal_latency ();
878 }
879
880 ARDOUR::PluginType
881 PluginInsert::type ()
882 {
883         boost::shared_ptr<LadspaPlugin> lp;
884 #ifdef VST_SUPPORT
885         boost::shared_ptr<VSTPlugin> vp;
886 #endif
887 #ifdef HAVE_AUDIOUNITS
888         boost::shared_ptr<AUPlugin> ap;
889 #endif
890         
891         PluginPtr other = plugin ();
892
893         if ((lp = boost::dynamic_pointer_cast<LadspaPlugin> (other)) != 0) {
894                 return ARDOUR::LADSPA;
895 #ifdef VST_SUPPORT
896         } else if ((vp = boost::dynamic_pointer_cast<VSTPlugin> (other)) != 0) {
897                 return ARDOUR::VST;
898 #endif
899 #ifdef HAVE_AUDIOUNITS
900         } else if ((ap = boost::dynamic_pointer_cast<AUPlugin> (other)) != 0) {
901                 return ARDOUR::AudioUnit;
902 #endif
903         } else {
904                 /* NOT REACHED */
905                 return (ARDOUR::PluginType) 0;
906         }
907 }
908
909 PluginInsert::PluginControl::PluginControl (PluginInsert* p, const Evoral::Parameter &param, boost::shared_ptr<AutomationList> list)
910         : AutomationControl (p->session(), param, list, p->describe_parameter(param))
911         , _plugin (p)
912 {
913         Plugin::ParameterDescriptor desc;
914         p->plugin(0)->get_parameter_descriptor (param.id(), desc);
915         _logarithmic = desc.logarithmic;
916         _toggled = desc.toggled;
917 }
918          
919 void
920 PluginInsert::PluginControl::set_value (float val)
921 {
922         /* FIXME: probably should be taking out some lock here.. */
923         
924         if (_toggled) {
925                 if (val > 0.5) {
926                         val = 1.0;
927                 } else {
928                         val = 0.0;
929                 }
930         } else {
931                         
932                 /*const float range = _list->get_max_y() - _list->get_min_y();
933                 const float lower = _list->get_min_y();
934
935                 if (!_logarithmic) {
936                         val = lower + (range * val);
937                 } else {
938                         float log_lower = 0.0f;
939                         if (lower > 0.0f) {
940                                 log_lower = log(lower);
941                         }
942
943                         val = exp(log_lower + log(range) * val);
944                 }*/
945
946         }
947
948         for (Plugins::iterator i = _plugin->_plugins.begin();
949                         i != _plugin->_plugins.end(); ++i) {
950                 (*i)->set_parameter (_list->parameter().id(), val);
951         }
952
953         boost::shared_ptr<Plugin> iasp = _plugin->_impulseAnalysisPlugin.lock();
954         if (iasp) {
955                 iasp->set_parameter (_list->parameter().id(), val);
956         }
957
958         AutomationControl::set_value(val);
959 }
960
961 float
962 PluginInsert::PluginControl::get_value (void) const
963 {
964         /* FIXME: probably should be taking out some lock here.. */
965         
966         float val = _plugin->get_parameter (_list->parameter());
967
968         return val;
969
970         /*if (_toggled) {
971                 
972                 return val;
973                 
974         } else {
975                 
976                 if (_logarithmic) {
977                         val = log(val);
978                 }
979                 
980                 return ((val - lower) / range);
981         }*/
982 }
983
984 boost::shared_ptr<Plugin>
985 PluginInsert::get_impulse_analysis_plugin()
986 {
987         boost::shared_ptr<Plugin> ret;
988         if (_impulseAnalysisPlugin.expired()) {
989                 ret = plugin_factory(_plugins[0]);
990                 _impulseAnalysisPlugin = ret;
991         } else {
992                 ret = _impulseAnalysisPlugin.lock();
993         }
994
995         return ret;
996 }
997
998 void
999 PluginInsert::collect_signal_for_analysis(nframes_t nframes)
1000 {
1001         // called from outside the audio thread, so this should be safe
1002         // only do audio as analysis is (currently) only for audio plugins
1003         _signal_analysis_inputs.ensure_buffers(  DataType::AUDIO, input_streams().n_audio(),  nframes); 
1004         _signal_analysis_outputs.ensure_buffers( DataType::AUDIO, output_streams().n_audio(), nframes); 
1005
1006         _signal_analysis_collected_nframes   = 0;
1007         _signal_analysis_collect_nframes_max = nframes; 
1008 }
1009