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