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