Merged with trunk R992.
[ardour.git] / libs / ardour / ladspa_plugin.cc
1 /*
2     Copyright (C) 2000-2006 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     $Id$
19 */
20
21 #define __STDC_FORMAT_MACROS 1
22 #include <inttypes.h>
23
24 #include <vector>
25 #include <string>
26
27 #include <cstdlib>
28 #include <cstdio> // so libraptor doesn't complain
29 #include <cmath>
30 #include <dirent.h>
31 #include <sys/stat.h>
32 #include <cerrno>
33
34 #include <lrdf.h>
35
36 #include <pbd/compose.h>
37 #include <pbd/error.h>
38 #include <pbd/pathscanner.h>
39 #include <pbd/xml++.h>
40
41 #include <midi++/manager.h>
42
43 #include <ardour/ardour.h>
44 #include <ardour/session.h>
45 #include <ardour/audioengine.h>
46 #include <ardour/ladspa_plugin.h>
47 #include <ardour/buffer_set.h>
48
49 #include <pbd/stl_delete.h>
50
51 #include "i18n.h"
52 #include <locale.h>
53
54 using namespace std;
55 using namespace ARDOUR;
56 using namespace PBD;
57
58 LadspaPlugin::LadspaPlugin (void *mod, AudioEngine& e, Session& session, uint32_t index, nframes_t rate)
59         : Plugin (e, session)
60 {
61         init (mod, index, rate);
62 }
63
64 LadspaPlugin::LadspaPlugin (const LadspaPlugin &other)
65         : Plugin (other)
66 {
67         init (other.module, other._index, other.sample_rate);
68
69         for (uint32_t i = 0; i < parameter_count(); ++i) {
70                 control_data[i] = other.shadow_data[i];
71                 shadow_data[i] = other.shadow_data[i];
72         }
73 }
74
75 void
76 LadspaPlugin::init (void *mod, uint32_t index, nframes_t rate)
77 {
78         LADSPA_Descriptor_Function dfunc;
79         uint32_t i, port_cnt;
80         const char *errstr;
81
82         module = mod;
83         control_data = 0;
84         shadow_data = 0;
85         latency_control_port = 0;
86         was_activated = false;
87
88         dfunc = (LADSPA_Descriptor_Function) dlsym (module, "ladspa_descriptor");
89
90         if ((errstr = dlerror()) != NULL) {
91                 error << _("LADSPA: module has no descriptor function.") << endmsg;
92                 throw failed_constructor();
93         }
94
95         if ((descriptor = dfunc (index)) == 0) {
96                 error << _("LADSPA: plugin has gone away since discovery!") << endmsg;
97                 throw failed_constructor();
98         }
99
100         _index = index;
101
102         if (LADSPA_IS_INPLACE_BROKEN(descriptor->Properties)) {
103                 error << string_compose(_("LADSPA: \"%1\" cannot be used, since it cannot do inplace processing"), descriptor->Name) << endmsg;
104                 throw failed_constructor();
105         }
106         
107         sample_rate = rate;
108
109         if (descriptor->instantiate == 0) {
110                 throw failed_constructor();
111         }
112
113         if ((handle = descriptor->instantiate (descriptor, rate)) == 0) {
114                 throw failed_constructor();
115         }
116
117         port_cnt = parameter_count();
118
119         control_data = new LADSPA_Data[port_cnt];
120         shadow_data = new LADSPA_Data[port_cnt];
121
122         for (i = 0; i < port_cnt; ++i) {
123                 if (LADSPA_IS_PORT_CONTROL(port_descriptor (i))) {
124                         connect_port (i, &control_data[i]);
125                         
126                         if (LADSPA_IS_PORT_OUTPUT(port_descriptor (i)) &&
127                             strcmp (port_names()[i], X_("latency")) == 0) {
128                                 latency_control_port = &control_data[i];
129                                 *latency_control_port = 0;
130                         }
131
132                         if (!LADSPA_IS_PORT_INPUT(port_descriptor (i))) {
133                                 continue;
134                         }
135                 
136                         shadow_data[i] = default_value (i);
137                 }
138         }
139
140         Plugin::setup_controls ();
141
142         latency_compute_run ();
143 }
144
145 LadspaPlugin::~LadspaPlugin ()
146 {
147         deactivate ();
148         cleanup ();
149
150         GoingAway (); /* EMIT SIGNAL */
151         
152         /* XXX who should close a plugin? */
153
154         // dlclose (module);
155
156         if (control_data) {
157                 delete [] control_data;
158         }
159
160         if (shadow_data) {
161                 delete [] shadow_data;
162         }
163 }
164
165 void
166 LadspaPlugin::store_state (PluginState& state)
167 {
168         state.parameters.clear ();
169         
170         for (uint32_t i = 0; i < parameter_count(); ++i){
171
172                 if (LADSPA_IS_PORT_INPUT(port_descriptor (i)) && 
173                     LADSPA_IS_PORT_CONTROL(port_descriptor (i))){
174                         pair<uint32_t,float> datum;
175
176                         datum.first = i;
177                         datum.second = shadow_data[i];
178
179                         state.parameters.insert (datum);
180                 }
181         }
182 }
183
184 void
185 LadspaPlugin::restore_state (PluginState& state)
186 {
187         for (map<uint32_t,float>::iterator i = state.parameters.begin(); i != state.parameters.end(); ++i) {
188                 set_parameter (i->first, i->second);
189         }
190 }
191
192 float
193 LadspaPlugin::default_value (uint32_t port)
194 {
195         const LADSPA_PortRangeHint *prh = port_range_hints();
196         float ret = 0.0f;
197         bool bounds_given = false;
198         bool sr_scaling = false;
199
200         /* defaults - case 1 */
201         
202         if (LADSPA_IS_HINT_HAS_DEFAULT(prh[port].HintDescriptor)) {
203                 if (LADSPA_IS_HINT_DEFAULT_MINIMUM(prh[port].HintDescriptor)) {
204                         ret = prh[port].LowerBound;
205                         bounds_given = true;
206                         sr_scaling = true;
207                 }
208                 
209                 /* FIXME: add support for logarithmic defaults */
210                 
211                 else if (LADSPA_IS_HINT_DEFAULT_LOW(prh[port].HintDescriptor)) {
212                         ret = prh[port].LowerBound * 0.75f + prh[port].UpperBound * 0.25f;
213                         bounds_given = true;
214                         sr_scaling = true;
215                 }
216                 else if (LADSPA_IS_HINT_DEFAULT_MIDDLE(prh[port].HintDescriptor)) {
217                         ret = prh[port].LowerBound * 0.50f + prh[port].UpperBound * 0.50f;
218                         bounds_given = true;
219                         sr_scaling = true;
220                 }
221                 else if (LADSPA_IS_HINT_DEFAULT_HIGH(prh[port].HintDescriptor)) {
222                         ret = prh[port].LowerBound * 0.25f + prh[port].UpperBound * 0.75f;
223                         bounds_given = true;
224                         sr_scaling = true;
225                 }
226                 else if (LADSPA_IS_HINT_DEFAULT_MAXIMUM(prh[port].HintDescriptor)) {
227                         ret = prh[port].UpperBound;
228                         bounds_given = true;
229                         sr_scaling = true;
230                 }
231                 else if (LADSPA_IS_HINT_DEFAULT_0(prh[port].HintDescriptor)) {
232                         ret = 0.0f;
233                 }
234                 else if (LADSPA_IS_HINT_DEFAULT_1(prh[port].HintDescriptor)) {
235                         ret = 1.0f;
236                 }
237                 else if (LADSPA_IS_HINT_DEFAULT_100(prh[port].HintDescriptor)) {
238                         ret = 100.0f;
239                 }
240                 else if (LADSPA_IS_HINT_DEFAULT_440(prh[port].HintDescriptor)) {
241                         ret = 440.0f;
242                 }
243                 else {
244                         /* no hint found */
245                         ret = 0.0f;
246                 }
247         }
248         
249         /* defaults - case 2 */
250         else if (LADSPA_IS_HINT_BOUNDED_BELOW(prh[port].HintDescriptor) &&
251                  !LADSPA_IS_HINT_BOUNDED_ABOVE(prh[port].HintDescriptor)) {
252                 
253                 if (prh[port].LowerBound < 0) {
254                         ret = 0.0f;
255                 } else {
256                         ret = prh[port].LowerBound;
257                 }
258
259                 bounds_given = true;
260                 sr_scaling = true;
261         }
262         
263         /* defaults - case 3 */
264         else if (!LADSPA_IS_HINT_BOUNDED_BELOW(prh[port].HintDescriptor) &&
265                  LADSPA_IS_HINT_BOUNDED_ABOVE(prh[port].HintDescriptor)) {
266                 
267                 if (prh[port].UpperBound > 0) {
268                         ret = 0.0f;
269                 } else {
270                         ret = prh[port].UpperBound;
271                 }
272
273                 bounds_given = true;
274                 sr_scaling = true;
275         }
276         
277         /* defaults - case 4 */
278         else if (LADSPA_IS_HINT_BOUNDED_BELOW(prh[port].HintDescriptor) &&
279                  LADSPA_IS_HINT_BOUNDED_ABOVE(prh[port].HintDescriptor)) {
280                 
281                 if (prh[port].LowerBound < 0 && prh[port].UpperBound > 0) {
282                         ret = 0.0f;
283                 } else if (prh[port].LowerBound < 0 && prh[port].UpperBound < 0) {
284                         ret = prh[port].UpperBound;
285                 } else {
286                         ret = prh[port].LowerBound;
287                 }
288                 bounds_given = true;    
289                 sr_scaling = true;
290         }
291         
292         /* defaults - case 5 */
293                 
294         if (LADSPA_IS_HINT_SAMPLE_RATE(prh[port].HintDescriptor)) {
295                 if (bounds_given) {
296                         if (sr_scaling) {
297                                 ret *= sample_rate;
298                         }
299                 } else {
300                         ret = sample_rate;
301                 }
302         }
303
304         return ret;
305 }       
306
307 void
308 LadspaPlugin::set_parameter (uint32_t which, float val)
309 {
310         if (which < descriptor->PortCount) {
311                 shadow_data[which] = (LADSPA_Data) val;
312                 ParameterChanged (which, val); /* EMIT SIGNAL */
313
314                 if (which < parameter_count() && controls[which]) {
315                         controls[which]->Changed ();
316                 }
317                 
318         } else {
319                 warning << string_compose (_("illegal parameter number used with plugin \"%1\". This may"
320                                              "indicate a change in the plugin design, and presets may be"
321                                              "invalid"), name())
322                         << endmsg;
323         }
324 }
325
326 float
327 LadspaPlugin::get_parameter (uint32_t which) const
328 {
329         if (LADSPA_IS_PORT_INPUT(port_descriptor (which))) {
330                 return (float) shadow_data[which];
331         } else {
332                 return (float) control_data[which];
333         }
334 }
335
336 uint32_t
337 LadspaPlugin::nth_parameter (uint32_t n, bool& ok) const
338 {
339         uint32_t x, c;
340
341         ok = false;
342
343         for (c = 0, x = 0; x < descriptor->PortCount; ++x) {
344                 if (LADSPA_IS_PORT_CONTROL (port_descriptor (x))) {
345                         if (c++ == n) {
346                                 ok = true;
347                                 return x;
348                         }
349                 }
350         }
351         return 0;
352 }
353
354 XMLNode&
355 LadspaPlugin::get_state()
356 {
357         XMLNode *root = new XMLNode(state_node_name());
358         XMLNode *child;
359         char buf[16];
360         LocaleGuard lg (X_("POSIX"));
361
362         for (uint32_t i = 0; i < parameter_count(); ++i){
363
364                 if (LADSPA_IS_PORT_INPUT(port_descriptor (i)) && 
365                     LADSPA_IS_PORT_CONTROL(port_descriptor (i))){
366
367                         child = new XMLNode("port");
368                         snprintf(buf, sizeof(buf), "%u", i);
369                         child->add_property("number", string(buf));
370                         snprintf(buf, sizeof(buf), "%+f", shadow_data[i]);
371                         child->add_property("value", string(buf));
372                         root->add_child_nocopy (*child);
373                 }
374         }
375
376         return *root;
377 }
378
379 bool
380 LadspaPlugin::save_preset (string name)
381 {
382         return Plugin::save_preset (name, "ladspa");
383 }
384
385 int
386 LadspaPlugin::set_state(const XMLNode& node)
387 {
388         XMLNodeList nodes;
389         XMLProperty *prop;
390         XMLNodeConstIterator iter;
391         XMLNode *child;
392         const char *port;
393         const char *data;
394         uint32_t port_id;
395         LocaleGuard lg (X_("POSIX"));
396
397         if (node.name() != state_node_name()) {
398                 error << _("Bad node sent to LadspaPlugin::set_state") << endmsg;
399                 return -1;
400         }
401
402         nodes = node.children ("port");
403
404         for(iter = nodes.begin(); iter != nodes.end(); ++iter){
405
406                 child = *iter;
407
408                 if ((prop = child->property("number")) != 0) {
409                         port = prop->value().c_str();
410                 } else {
411                         warning << _("LADSPA: no ladspa port number") << endmsg;
412                         continue;
413                 }
414                 if ((prop = child->property("value")) != 0) {
415                         data = prop->value().c_str();
416                 } else {
417                         warning << _("LADSPA: no ladspa port data") << endmsg;
418                         continue;
419                 }
420
421                 sscanf (port, "%" PRIu32, &port_id);
422                 set_parameter (port_id, atof(data));
423         }
424
425         latency_compute_run ();
426
427         return 0;
428 }
429
430 int
431 LadspaPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& desc) const
432 {
433         LADSPA_PortRangeHint prh;
434
435         prh  = port_range_hints()[which];
436         
437
438         if (LADSPA_IS_HINT_BOUNDED_BELOW(prh.HintDescriptor)) {
439                 desc.min_unbound = false;
440                 if (LADSPA_IS_HINT_SAMPLE_RATE(prh.HintDescriptor)) {
441                         desc.lower = prh.LowerBound * _session.frame_rate();
442                 } else {
443                         desc.lower = prh.LowerBound;
444                 }
445         } else {
446                 desc.min_unbound = true;
447                 desc.lower = 0;
448         }
449         
450
451         if (LADSPA_IS_HINT_BOUNDED_ABOVE(prh.HintDescriptor)) {
452                 desc.max_unbound = false;
453                 if (LADSPA_IS_HINT_SAMPLE_RATE(prh.HintDescriptor)) {
454                         desc.upper = prh.UpperBound * _session.frame_rate();
455                 } else {
456                         desc.upper = prh.UpperBound;
457                 }
458         } else {
459                 desc.max_unbound = true;
460                 desc.upper = 4; /* completely arbitrary */
461         }
462         
463         if (LADSPA_IS_HINT_INTEGER (prh.HintDescriptor)) {
464                 desc.step = 1.0;
465                 desc.smallstep = 0.1;
466                 desc.largestep = 10.0;
467         } else {
468                 float delta = desc.upper - desc.lower;
469                 desc.step = delta / 1000.0f;
470                 desc.smallstep = delta / 10000.0f;
471                 desc.largestep = delta/10.0f;
472         }
473         
474         desc.toggled = LADSPA_IS_HINT_TOGGLED (prh.HintDescriptor);
475         desc.logarithmic = LADSPA_IS_HINT_LOGARITHMIC (prh.HintDescriptor);
476         desc.sr_dependent = LADSPA_IS_HINT_SAMPLE_RATE (prh.HintDescriptor);
477         desc.integer_step = LADSPA_IS_HINT_INTEGER (prh.HintDescriptor);
478
479         desc.label = port_names()[which];
480
481
482         return 0;
483 }
484
485
486 string
487 LadspaPlugin::describe_parameter (uint32_t which)
488 {
489         if (which < parameter_count()) {
490                 return port_names()[which];
491         } else {
492                 return "??";
493         }
494 }
495
496 ARDOUR::nframes_t
497 LadspaPlugin::latency () const
498 {
499         if (latency_control_port) {
500                 return (nframes_t) floor (*latency_control_port);
501         } else {
502                 return 0;
503         }
504 }
505
506 set<uint32_t>
507 LadspaPlugin::automatable () const
508 {
509         set<uint32_t> ret;
510
511         for (uint32_t i = 0; i < parameter_count(); ++i){
512                 if (LADSPA_IS_PORT_INPUT(port_descriptor (i)) && 
513                     LADSPA_IS_PORT_CONTROL(port_descriptor (i))){
514                         
515                         ret.insert (ret.end(), i);
516                 }
517         }
518
519         return ret;
520 }
521
522 int
523 LadspaPlugin::connect_and_run (BufferSet& bufs, uint32_t& in_index, uint32_t& out_index, nframes_t nframes, nframes_t offset)
524 {
525         uint32_t port_index = 0;
526         cycles_t then, now;
527
528         then = get_cycles ();
529
530         const uint32_t nbufs = bufs.count().get(DataType::AUDIO);
531
532         while (port_index < parameter_count()) {
533                 if (LADSPA_IS_PORT_AUDIO (port_descriptor(port_index))) {
534                         if (LADSPA_IS_PORT_INPUT (port_descriptor(port_index))) {
535                                 const size_t index = min(in_index, nbufs - 1);
536                                 connect_port (port_index, bufs.get_audio(index).data(nframes, offset));
537                                 //cerr << this << ' ' << name() << " @ " << offset << " inport " << in_index << " = buf " 
538                                 //     << min((uint32_t)in_index,nbufs) << " = " << &bufs[min((uint32_t)in_index,nbufs)][offset] << endl;
539                                 in_index++;
540
541
542                         } else if (LADSPA_IS_PORT_OUTPUT (port_descriptor (port_index))) {
543                                 const size_t index = min(out_index,nbufs - 1);
544                                 connect_port (port_index, bufs.get_audio(index).data(nframes, offset));
545                                 // cerr << this << ' ' << name() << " @ " << offset << " outport " << out_index << " = buf " 
546                                 //     << min((uint32_t)out_index,nbufs) << " = " << &bufs[min((uint32_t)out_index,nbufs)][offset] << endl;
547                                 out_index++;
548                         }
549                 }
550                 port_index++;
551         }
552         
553         run (nframes);
554         now = get_cycles ();
555         set_cycles ((uint32_t) (now - then));
556
557         return 0;
558 }
559
560 bool
561 LadspaPlugin::parameter_is_control (uint32_t param) const
562 {
563         return LADSPA_IS_PORT_CONTROL(port_descriptor (param));
564 }
565
566 bool
567 LadspaPlugin::parameter_is_audio (uint32_t param) const
568 {
569         return LADSPA_IS_PORT_AUDIO(port_descriptor (param));
570 }
571
572 bool
573 LadspaPlugin::parameter_is_output (uint32_t param) const
574 {
575         return LADSPA_IS_PORT_OUTPUT(port_descriptor (param));
576 }
577
578 bool
579 LadspaPlugin::parameter_is_input (uint32_t param) const
580 {
581         return LADSPA_IS_PORT_INPUT(port_descriptor (param));
582 }
583
584 void
585 LadspaPlugin::print_parameter (uint32_t param, char *buf, uint32_t len) const
586 {
587         if (buf && len) {
588                 if (param < parameter_count()) {
589                         snprintf (buf, len, "%.3f", get_parameter (param));
590                 } else {
591                         strcat (buf, "0");
592                 }
593         }
594 }
595
596 void
597 LadspaPlugin::run (nframes_t nframes)
598 {
599         for (uint32_t i = 0; i < parameter_count(); ++i) {
600                 if (LADSPA_IS_PORT_INPUT(port_descriptor (i)) && LADSPA_IS_PORT_CONTROL(port_descriptor (i))) {
601                         control_data[i] = shadow_data[i];
602                 }
603         }
604         descriptor->run (handle, nframes);
605 }
606
607 void
608 LadspaPlugin::latency_compute_run ()
609 {
610         if (!latency_control_port) {
611                 return;
612         }
613
614         /* we need to run the plugin so that it can set its latency
615            parameter.
616         */
617         
618         activate ();
619         
620         uint32_t port_index = 0;
621         uint32_t in_index = 0;
622         uint32_t out_index = 0;
623         const nframes_t bufsize = 1024;
624         LADSPA_Data buffer[bufsize];
625
626         memset(buffer,0,sizeof(LADSPA_Data)*bufsize);
627                 
628         /* Note that we've already required that plugins
629            be able to handle in-place processing.
630         */
631         
632         port_index = 0;
633         
634         while (port_index < parameter_count()) {
635                 if (LADSPA_IS_PORT_AUDIO (port_descriptor (port_index))) {
636                         if (LADSPA_IS_PORT_INPUT (port_descriptor (port_index))) {
637                                 connect_port (port_index, buffer);
638                                 in_index++;
639                         } else if (LADSPA_IS_PORT_OUTPUT (port_descriptor (port_index))) {
640                                 connect_port (port_index, buffer);
641                                 out_index++;
642                         }
643                 }
644                 port_index++;
645         }
646         
647         run (bufsize);
648         deactivate ();
649 }
650
651 PluginPtr
652 LadspaPluginInfo::load (Session& session)
653 {
654         try {
655                 PluginPtr plugin;
656                 void *module;
657
658                 if ((module = dlopen (path.c_str(), RTLD_NOW)) == 0) {
659                         error << string_compose(_("LADSPA: cannot load module from \"%1\""), path) << endmsg;
660                         error << dlerror() << endmsg;
661                 } else {
662                         plugin.reset (new LadspaPlugin (module, session.engine(), session, index, session.frame_rate()));
663                 }
664
665                 plugin->set_info(PluginInfoPtr(new LadspaPluginInfo(*this)));
666                 return plugin;
667         }
668
669         catch (failed_constructor &err) {
670                 return PluginPtr ((Plugin*) 0);
671         }       
672 }