remove Session::AudioMidiSetupRequired signal (no longer necessary)
[ardour.git] / libs / ardour / ladspa_plugin.cc
1 /*
2  * Copyright (C) 2000-2017 Paul Davis <paul@linuxaudiosystems.com>
3  * Copyright (C) 2005-2006 Sampo Savolainen <v2@iki.fi>
4  * Copyright (C) 2005-2006 Taybin Rutkin <taybin@taybin.com>
5  * Copyright (C) 2006-2014 David Robillard <d@drobilla.net>
6  * Copyright (C) 2007-2017 Tim Mayberry <mojofunk@gmail.com>
7  * Copyright (C) 2008-2012 Carl Hetherington <carl@carlh.net>
8  * Copyright (C) 2013-2019 Robin Gareus <robin@gareus.org>
9  * Copyright (C) 2013 John Emmas <john@creativepost.co.uk>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License along
22  * with this program; if not, write to the Free Software Foundation, Inc.,
23  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24  */
25
26 #ifdef WAF_BUILD
27 #include "libardour-config.h"
28 #endif
29
30 #include <inttypes.h>
31
32 #include <vector>
33 #include <string>
34
35 #include <cstdlib>
36 #include <cstdio> // so libraptor doesn't complain
37 #include <cmath>
38 #ifndef COMPILER_MSVC
39 #include <dirent.h>
40 #endif
41 #include <sys/stat.h>
42 #include <cerrno>
43
44 #ifdef HAVE_LRDF
45 #include <lrdf.h>
46 #endif
47
48 #include "pbd/compose.h"
49 #include "pbd/error.h"
50 #include "pbd/locale_guard.h"
51 #include "pbd/xml++.h"
52 #include "pbd/stacktrace.h"
53
54 #include "ardour/session.h"
55 #include "ardour/ladspa_plugin.h"
56 #include "ardour/buffer_set.h"
57 #include "ardour/audio_buffer.h"
58
59 #include "pbd/stl_delete.h"
60
61 #include "pbd/i18n.h"
62 #include <locale.h>
63
64 using namespace std;
65 using namespace ARDOUR;
66 using namespace PBD;
67
68 LadspaPlugin::LadspaPlugin (string module_path, AudioEngine& e, Session& session, uint32_t index, samplecnt_t rate)
69         : Plugin (e, session)
70 {
71         init (module_path, index, rate);
72 }
73
74 LadspaPlugin::LadspaPlugin (const LadspaPlugin &other)
75         : Plugin (other)
76 {
77         init (other._module_path, other._index, other._sample_rate);
78
79         for (uint32_t i = 0; i < parameter_count(); ++i) {
80                 _control_data[i] = other._shadow_data[i];
81                 _shadow_data[i] = other._shadow_data[i];
82         }
83 }
84
85 void
86 LadspaPlugin::init (string module_path, uint32_t index, samplecnt_t rate)
87 {
88         void* func;
89         LADSPA_Descriptor_Function dfunc;
90         uint32_t i, port_cnt;
91
92         _module_path = module_path;
93         _module = new Glib::Module(_module_path);
94         _control_data = 0;
95         _shadow_data = 0;
96         _latency_control_port = 0;
97         _was_activated = false;
98
99         if (!(*_module)) {
100                 warning << _("LADSPA: Unable to open module: ") << Glib::Module::get_last_error() << endmsg;
101                 delete _module;
102                 throw failed_constructor();
103         }
104
105         if (!_module->get_symbol("ladspa_descriptor", func)) {
106                 warning << _("LADSPA: module has no descriptor function.") << endmsg;
107                 throw failed_constructor();
108         }
109
110         dfunc = (LADSPA_Descriptor_Function)func;
111
112         if ((_descriptor = dfunc (index)) == 0) {
113                 warning << _("LADSPA: plugin has gone away since discovery!") << endmsg;
114                 throw failed_constructor();
115         }
116
117         _index = index;
118
119         if (LADSPA_IS_INPLACE_BROKEN(_descriptor->Properties)) {
120                 info << string_compose(_("LADSPA: \"%1\" cannot be used, since it cannot do inplace processing"), _descriptor->Name) << endmsg;
121                 throw failed_constructor();
122         }
123
124         _sample_rate = rate;
125
126         if (_descriptor->instantiate == 0) {
127                 throw failed_constructor();
128         }
129
130         if ((_handle = _descriptor->instantiate (_descriptor, rate)) == 0) {
131                 throw failed_constructor();
132         }
133
134         port_cnt = parameter_count();
135
136         _control_data = new LADSPA_Data[port_cnt];
137         memset (_control_data, 0, sizeof (LADSPA_Data) * port_cnt);
138         _shadow_data = new LADSPA_Data[port_cnt];
139         memset (_shadow_data, 0, sizeof (LADSPA_Data) * port_cnt);
140
141         for (i = 0; i < port_cnt; ++i) {
142                 if (LADSPA_IS_PORT_CONTROL(port_descriptor (i))) {
143                         connect_port (i, &_control_data[i]);
144
145                         if (LADSPA_IS_PORT_OUTPUT(port_descriptor (i)) &&
146                             strcmp (port_names()[i], X_("latency")) == 0) {
147                                 _latency_control_port = &_control_data[i];
148                                 *_latency_control_port = 0;
149                         }
150
151                         _shadow_data[i] = _default_value (i);
152                         _control_data[i] = _shadow_data[i];
153                 }
154         }
155
156         latency_compute_run ();
157 }
158
159 LadspaPlugin::~LadspaPlugin ()
160 {
161         deactivate ();
162         cleanup ();
163
164         // glib has internal reference counting on modules so this is ok
165         delete _module;
166
167         delete [] _control_data;
168         delete [] _shadow_data;
169 }
170
171 string
172 LadspaPlugin::unique_id() const
173 {
174         char buf[32];
175         snprintf (buf, sizeof (buf), "%lu", _descriptor->UniqueID);
176         return string (buf);
177 }
178
179 float
180 LadspaPlugin::_default_value (uint32_t port) const
181 {
182         const LADSPA_PortRangeHint *prh = port_range_hints();
183         float ret = 0.0f;
184         bool bounds_given = false;
185         bool sr_scaling = false;
186         bool earlier_hint = false;
187
188         /* defaults - case 1 */
189
190         if (LADSPA_IS_HINT_HAS_DEFAULT(prh[port].HintDescriptor)) {
191                 if (LADSPA_IS_HINT_DEFAULT_MINIMUM(prh[port].HintDescriptor)) {
192                         ret = prh[port].LowerBound;
193                         bounds_given = true;
194                         sr_scaling = true;
195                 }
196
197                 else if (LADSPA_IS_HINT_DEFAULT_LOW(prh[port].HintDescriptor)) {
198                         ret = prh[port].LowerBound * 0.75f + prh[port].UpperBound * 0.25f;
199                         bounds_given = true;
200                         sr_scaling = true;
201                 }
202                 else if (LADSPA_IS_HINT_DEFAULT_MIDDLE(prh[port].HintDescriptor)) {
203                         ret = prh[port].LowerBound * 0.5f + prh[port].UpperBound * 0.5f;
204                         bounds_given = true;
205                         sr_scaling = true;
206                 }
207                 else if (LADSPA_IS_HINT_DEFAULT_HIGH(prh[port].HintDescriptor)) {
208                         ret = prh[port].LowerBound * 0.25f + prh[port].UpperBound * 0.75f;
209                         bounds_given = true;
210                         sr_scaling = true;
211                 }
212                 else if (LADSPA_IS_HINT_DEFAULT_MAXIMUM(prh[port].HintDescriptor)) {
213                         ret = prh[port].UpperBound;
214                         bounds_given = true;
215                         sr_scaling = true;
216                 }
217                 else if (LADSPA_IS_HINT_DEFAULT_0(prh[port].HintDescriptor)) {
218                         ret = 0.0f;
219                         earlier_hint = true;
220                 }
221                 else if (LADSPA_IS_HINT_DEFAULT_1(prh[port].HintDescriptor)) {
222                         ret = 1.0f;
223                         earlier_hint = true;
224                 }
225                 else if (LADSPA_IS_HINT_DEFAULT_100(prh[port].HintDescriptor)) {
226                         ret = 100.0f;
227                         earlier_hint = true;
228                 }
229                 else if (LADSPA_IS_HINT_DEFAULT_440(prh[port].HintDescriptor)) {
230                         ret = 440.0f;
231                         earlier_hint = true;
232                 }
233                 else {
234                         /* no hint found */
235                         ret = 0.0f;
236                 }
237         }
238
239         /* defaults - case 2 */
240         else if (LADSPA_IS_HINT_BOUNDED_BELOW(prh[port].HintDescriptor) &&
241                  !LADSPA_IS_HINT_BOUNDED_ABOVE(prh[port].HintDescriptor)) {
242
243                 if (prh[port].LowerBound < 0) {
244                         ret = 0.0f;
245                 } else {
246                         ret = prh[port].LowerBound;
247                 }
248
249                 bounds_given = true;
250                 sr_scaling = true;
251         }
252
253         /* defaults - case 3 */
254         else if (!LADSPA_IS_HINT_BOUNDED_BELOW(prh[port].HintDescriptor) &&
255                  LADSPA_IS_HINT_BOUNDED_ABOVE(prh[port].HintDescriptor)) {
256
257                 if (prh[port].UpperBound > 0) {
258                         ret = 0.0f;
259                 } else {
260                         ret = prh[port].UpperBound;
261                 }
262
263                 bounds_given = true;
264                 sr_scaling = true;
265         }
266
267         /* defaults - case 4 */
268         else if (LADSPA_IS_HINT_BOUNDED_BELOW(prh[port].HintDescriptor) &&
269                  LADSPA_IS_HINT_BOUNDED_ABOVE(prh[port].HintDescriptor)) {
270
271                 if (prh[port].LowerBound < 0 && prh[port].UpperBound > 0) {
272                         ret = 0.0f;
273                 } else if (prh[port].LowerBound < 0 && prh[port].UpperBound < 0) {
274                         ret = prh[port].UpperBound;
275                 } else {
276                         ret = prh[port].LowerBound;
277                 }
278                 bounds_given = true;
279                 sr_scaling = true;
280         }
281
282         /* defaults - case 5 */
283
284         if (LADSPA_IS_HINT_SAMPLE_RATE(prh[port].HintDescriptor) && !earlier_hint) {
285                 if (bounds_given) {
286                         if (sr_scaling) {
287                                 ret *= _sample_rate;
288                         }
289                 } else {
290                         ret = _sample_rate;
291                 }
292         }
293
294         return ret;
295 }
296
297 void
298 LadspaPlugin::set_parameter (uint32_t which, float val)
299 {
300         if (which < _descriptor->PortCount) {
301
302                 if (get_parameter (which) == val) {
303                         return;
304                 }
305
306                 _shadow_data[which] = (LADSPA_Data) val;
307
308 #if 0
309                 if (which < parameter_count() && controls[which]) {
310                         controls[which]->Changed ();
311                 }
312 #endif
313
314         } else {
315                 warning << string_compose (_("illegal parameter number used with plugin \"%1\". This may "
316                                              "indicate a change in the plugin design, and presets may be "
317                                              "invalid"), name())
318                         << endmsg;
319         }
320
321         Plugin::set_parameter (which, val);
322 }
323
324 /** @return `plugin' value */
325 float
326 LadspaPlugin::get_parameter (uint32_t which) const
327 {
328         if (LADSPA_IS_PORT_INPUT(port_descriptor (which))) {
329                 return (float) _shadow_data[which];
330         } else {
331                 return (float) _control_data[which];
332         }
333 }
334
335 uint32_t
336 LadspaPlugin::nth_parameter (uint32_t n, bool& ok) const
337 {
338         uint32_t x, c;
339
340         ok = false;
341
342         for (c = 0, x = 0; x < _descriptor->PortCount; ++x) {
343                 if (LADSPA_IS_PORT_CONTROL (port_descriptor (x))) {
344                         if (c++ == n) {
345                                 ok = true;
346                                 return x;
347                         }
348                 }
349         }
350         return 0;
351 }
352
353 void
354 LadspaPlugin::add_state (XMLNode* root) const
355 {
356         XMLNode *child;
357
358         for (uint32_t i = 0; i < parameter_count(); ++i){
359
360                 if (LADSPA_IS_PORT_INPUT(port_descriptor (i)) &&
361                     LADSPA_IS_PORT_CONTROL(port_descriptor (i))){
362
363                         child = new XMLNode("Port");
364                         child->set_property("number", i);
365                         child->set_property("value", _shadow_data[i]);
366                         root->add_child_nocopy (*child);
367                 }
368         }
369 }
370
371 int
372 LadspaPlugin::set_state (const XMLNode& node, int version)
373 {
374         if (version < 3000) {
375                 return set_state_2X (node, version);
376         }
377
378         XMLNodeList nodes;
379         XMLNodeConstIterator iter;
380         XMLNode *child;
381
382         if (node.name() != state_node_name()) {
383                 error << _("Bad node sent to LadspaPlugin::set_state") << endmsg;
384                 return -1;
385         }
386
387         nodes = node.children ("Port");
388
389         for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
390
391                 child = *iter;
392
393                 uint32_t port_id;
394                 float value;
395
396                 if (!child->get_property ("number", port_id)) {
397                         warning << _("LADSPA: no ladspa port number") << endmsg;
398                         continue;
399                 }
400
401                 if (!child->get_property ("value", value)) {
402                         warning << _("LADSPA: no ladspa port data") << endmsg;
403                         continue;
404                 }
405
406                 set_parameter (port_id, value);
407         }
408
409         latency_compute_run ();
410
411         return Plugin::set_state (node, version);
412 }
413
414 int
415 LadspaPlugin::set_state_2X (const XMLNode& node, int /* version */)
416 {
417         XMLNodeList nodes;
418         XMLProperty const * prop;
419         XMLNodeConstIterator iter;
420         XMLNode *child;
421         const char *port;
422         const char *data;
423         uint32_t port_id;
424         LocaleGuard lg;
425
426         if (node.name() != state_node_name()) {
427                 error << _("Bad node sent to LadspaPlugin::set_state") << endmsg;
428                 return -1;
429         }
430
431         nodes = node.children ("port");
432
433         for(iter = nodes.begin(); iter != nodes.end(); ++iter){
434
435                 child = *iter;
436
437                 if ((prop = child->property("number")) != 0) {
438                         port = prop->value().c_str();
439                 } else {
440                         warning << _("LADSPA: no ladspa port number") << endmsg;
441                         continue;
442                 }
443                 if ((prop = child->property("value")) != 0) {
444                         data = prop->value().c_str();
445                 } else {
446                         warning << _("LADSPA: no ladspa port data") << endmsg;
447                         continue;
448                 }
449
450                 sscanf (port, "%" PRIu32, &port_id);
451                 set_parameter (port_id, atof(data));
452         }
453
454         latency_compute_run ();
455
456         return 0;
457 }
458
459 int
460 LadspaPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& desc) const
461 {
462         LADSPA_PortRangeHint prh;
463
464         prh  = port_range_hints()[which];
465
466
467         if (LADSPA_IS_HINT_BOUNDED_BELOW(prh.HintDescriptor)) {
468                 if (LADSPA_IS_HINT_SAMPLE_RATE(prh.HintDescriptor)) {
469                         desc.lower = prh.LowerBound * _session.sample_rate();
470                 } else {
471                         desc.lower = prh.LowerBound;
472                 }
473         } else {
474                 desc.lower = 0;
475         }
476
477
478         if (LADSPA_IS_HINT_BOUNDED_ABOVE(prh.HintDescriptor)) {
479                 if (LADSPA_IS_HINT_SAMPLE_RATE(prh.HintDescriptor)) {
480                         desc.upper = prh.UpperBound * _session.sample_rate();
481                 } else {
482                         desc.upper = prh.UpperBound;
483                 }
484         } else {
485                 if (LADSPA_IS_HINT_TOGGLED (prh.HintDescriptor)) {
486                         desc.upper = 1;
487                 } else {
488                         desc.upper = 4; /* completely arbitrary */
489                 }
490         }
491
492         if (LADSPA_IS_HINT_HAS_DEFAULT (prh.HintDescriptor)) {
493                 desc.normal = _default_value(which);
494         } else {
495                 /* if there is no explicit hint for the default
496                  * value, use lower bound. This is not great but
497                  * better than just assuming '0' which may be out-of range.
498                  */
499                 desc.normal = desc.lower;
500         }
501
502         desc.toggled = LADSPA_IS_HINT_TOGGLED (prh.HintDescriptor);
503         desc.logarithmic = LADSPA_IS_HINT_LOGARITHMIC (prh.HintDescriptor);
504         desc.sr_dependent = LADSPA_IS_HINT_SAMPLE_RATE (prh.HintDescriptor);
505         desc.integer_step = LADSPA_IS_HINT_INTEGER (prh.HintDescriptor);
506
507         desc.label = port_names()[which];
508
509         desc.scale_points = get_scale_points(which);
510         desc.update_steps();
511
512         return 0;
513 }
514
515 string
516 LadspaPlugin::describe_parameter (Evoral::Parameter which)
517 {
518         if (which.type() == PluginAutomation && which.id() < parameter_count()) {
519                 return port_names()[which.id()];
520         } else {
521                 return "??";
522         }
523 }
524
525 ARDOUR::samplecnt_t
526 LadspaPlugin::plugin_latency () const
527 {
528         if (_latency_control_port) {
529                 return (samplecnt_t) floor (*_latency_control_port);
530         } else {
531                 return 0;
532         }
533 }
534
535 set<Evoral::Parameter>
536 LadspaPlugin::automatable () const
537 {
538         set<Evoral::Parameter> ret;
539
540         for (uint32_t i = 0; i < parameter_count(); ++i){
541                 if (LADSPA_IS_PORT_INPUT(port_descriptor (i)) &&
542                     LADSPA_IS_PORT_CONTROL(port_descriptor (i))){
543
544                         ret.insert (ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
545                 }
546         }
547
548         return ret;
549 }
550
551 int
552 LadspaPlugin::connect_and_run (BufferSet& bufs,
553                 samplepos_t start, samplepos_t end, double speed,
554                 ChanMapping const& in_map, ChanMapping const& out_map,
555                 pframes_t nframes, samplecnt_t offset)
556 {
557         Plugin::connect_and_run (bufs, start, end, speed, in_map, out_map, nframes, offset);
558
559         cycles_t now;
560         cycles_t then = get_cycles ();
561
562         BufferSet& silent_bufs  = _session.get_silent_buffers(ChanCount(DataType::AUDIO, 1));
563         BufferSet& scratch_bufs = _session.get_scratch_buffers(ChanCount(DataType::AUDIO, 1));
564
565         uint32_t audio_in_index  = 0;
566         uint32_t audio_out_index = 0;
567         bool valid;
568         for (uint32_t port_index = 0; port_index < parameter_count(); ++port_index) {
569                 if (LADSPA_IS_PORT_AUDIO(port_descriptor(port_index))) {
570                         if (LADSPA_IS_PORT_INPUT(port_descriptor(port_index))) {
571                                 const uint32_t buf_index = in_map.get(DataType::AUDIO, audio_in_index++, &valid);
572                                 connect_port(port_index,
573                                              valid ? bufs.get_audio(buf_index).data(offset)
574                                                    : silent_bufs.get_audio(0).data(offset));
575                         } else if (LADSPA_IS_PORT_OUTPUT(port_descriptor(port_index))) {
576                                 const uint32_t buf_index = out_map.get(DataType::AUDIO, audio_out_index++, &valid);
577                                 connect_port(port_index,
578                                              valid ? bufs.get_audio(buf_index).data(offset)
579                                                    : scratch_bufs.get_audio(0).data(offset));
580                         }
581                 }
582         }
583
584         run_in_place (nframes);
585         now = get_cycles ();
586         set_cycles ((uint32_t) (now - then));
587
588         return 0;
589 }
590
591 bool
592 LadspaPlugin::parameter_is_control (uint32_t param) const
593 {
594         return LADSPA_IS_PORT_CONTROL(port_descriptor (param));
595 }
596
597 bool
598 LadspaPlugin::parameter_is_audio (uint32_t param) const
599 {
600         return LADSPA_IS_PORT_AUDIO(port_descriptor (param));
601 }
602
603 bool
604 LadspaPlugin::parameter_is_output (uint32_t param) const
605 {
606         return LADSPA_IS_PORT_OUTPUT(port_descriptor (param));
607 }
608
609 bool
610 LadspaPlugin::parameter_is_input (uint32_t param) const
611 {
612         return LADSPA_IS_PORT_INPUT(port_descriptor (param));
613 }
614
615 boost::shared_ptr<ScalePoints>
616 LadspaPlugin::get_scale_points(uint32_t port_index) const
617 {
618         boost::shared_ptr<ScalePoints> ret;
619 #ifdef HAVE_LRDF
620         const uint32_t id     = atol(unique_id().c_str());
621         lrdf_defaults* points = lrdf_get_scale_values(id, port_index);
622
623         if (!points) {
624                 return ret;
625         }
626
627         ret = boost::shared_ptr<ScalePoints>(new ScalePoints());
628
629         for (uint32_t i = 0; i < points->count; ++i) {
630                 ret->insert(make_pair(points->items[i].label,
631                                       points->items[i].value));
632         }
633
634         lrdf_free_setting_values(points);
635 #endif
636         return ret;
637 }
638
639 void
640 LadspaPlugin::run_in_place (pframes_t nframes)
641 {
642         for (uint32_t i = 0; i < parameter_count(); ++i) {
643                 if (LADSPA_IS_PORT_INPUT(port_descriptor (i)) && LADSPA_IS_PORT_CONTROL(port_descriptor (i))) {
644                         _control_data[i] = _shadow_data[i];
645                 }
646         }
647
648         assert (_was_activated);
649
650         _descriptor->run (_handle, nframes);
651 }
652
653 void
654 LadspaPlugin::latency_compute_run ()
655 {
656         if (!_latency_control_port) {
657                 return;
658         }
659
660         /* we need to run the plugin so that it can set its latency
661            parameter.
662         */
663
664         activate ();
665
666         uint32_t port_index = 0;
667         uint32_t in_index = 0;
668         uint32_t out_index = 0;
669         const samplecnt_t bufsize = 1024;
670         LADSPA_Data buffer[bufsize];
671
672         memset(buffer,0,sizeof(LADSPA_Data)*bufsize);
673
674         /* Note that we've already required that plugins
675            be able to handle in-place processing.
676         */
677
678         port_index = 0;
679
680         while (port_index < parameter_count()) {
681                 if (LADSPA_IS_PORT_AUDIO (port_descriptor (port_index))) {
682                         if (LADSPA_IS_PORT_INPUT (port_descriptor (port_index))) {
683                                 connect_port (port_index, buffer);
684                                 in_index++;
685                         } else if (LADSPA_IS_PORT_OUTPUT (port_descriptor (port_index))) {
686                                 connect_port (port_index, buffer);
687                                 out_index++;
688                         }
689                 }
690                 port_index++;
691         }
692
693         run_in_place (bufsize);
694         deactivate ();
695 }
696
697 PluginPtr
698 LadspaPluginInfo::load (Session& session)
699 {
700         try {
701                 PluginPtr plugin (new LadspaPlugin (path, session.engine(), session, index, session.sample_rate()));
702                 plugin->set_info(PluginInfoPtr(new LadspaPluginInfo(*this)));
703                 return plugin;
704         }
705
706         catch (failed_constructor &err) {
707                 return PluginPtr ((Plugin*) 0);
708         }
709 }
710
711 std::vector<Plugin::PresetRecord>
712 LadspaPluginInfo::get_presets (bool /*user_only*/) const
713 {
714         std::vector<Plugin::PresetRecord> p;
715 #ifdef HAVE_LRDF
716         if (!isdigit (unique_id[0])) {
717                 return p;
718         }
719         uint32_t id = atol (unique_id);
720         lrdf_uris* set_uris = lrdf_get_setting_uris(id);
721
722         if (set_uris) {
723                 for (uint32_t i = 0; i < (uint32_t) set_uris->count; ++i) {
724                         if (char* label = lrdf_get_label (set_uris->items[i])) {
725                                 p.push_back (Plugin::PresetRecord (set_uris->items[i], label));
726                         }
727                 }
728                 lrdf_free_uris(set_uris);
729         }
730 #endif
731         return p;
732 }
733
734 LadspaPluginInfo::LadspaPluginInfo()
735 {
736        type = ARDOUR::LADSPA;
737 }
738
739
740 void
741 LadspaPlugin::find_presets ()
742 {
743 #ifdef HAVE_LRDF
744         uint32_t id;
745         std::string unique (unique_id());
746
747         if (!isdigit (unique[0])) {
748                 return;
749         }
750
751         id = atol (unique.c_str());
752
753         lrdf_uris* set_uris = lrdf_get_setting_uris(id);
754
755         if (set_uris) {
756                 for (uint32_t i = 0; i < (uint32_t) set_uris->count; ++i) {
757                         if (char* label = lrdf_get_label(set_uris->items[i])) {
758                                 PresetRecord rec (set_uris->items[i], label);
759                                 _presets.insert (make_pair (set_uris->items[i], rec));
760                         }
761                 }
762                 lrdf_free_uris(set_uris);
763         }
764 #endif
765 }
766
767
768 bool
769 LadspaPlugin::load_preset (PresetRecord r)
770 {
771 #ifdef HAVE_LRDF
772         lrdf_defaults* defs = lrdf_get_setting_values (r.uri.c_str());
773
774         if (defs) {
775                 for (uint32_t i = 0; i < (uint32_t) defs->count; ++i) {
776                         if (parameter_is_input (defs->items[i].pid)) {
777                                 set_parameter(defs->items[i].pid, defs->items[i].value);
778                                 PresetPortSetValue (defs->items[i].pid, defs->items[i].value); /* EMIT SIGNAL */
779                         }
780                 }
781                 lrdf_free_setting_values(defs);
782         }
783
784         Plugin::load_preset (r);
785 #endif
786         return true;
787 }
788
789 #ifdef HAVE_LRDF
790 /* XXX: should be in liblrdf */
791 static void
792 lrdf_remove_preset (const char* /*source*/, const char *setting_uri)
793 {
794         lrdf_statement p;
795         lrdf_statement *q;
796         lrdf_statement *i;
797         char setting_uri_copy[64];
798         char buf[64];
799
800         strncpy(setting_uri_copy, setting_uri, sizeof(setting_uri_copy));
801
802         p.subject = setting_uri_copy;
803         strncpy(buf, LADSPA_BASE "hasPortValue", sizeof(buf));
804         p.predicate = buf;
805         p.object = NULL;
806         q = lrdf_matches(&p);
807
808         p.predicate = NULL;
809         p.object = NULL;
810         for (i = q; i; i = i->next) {
811                 p.subject = i->object;
812                 lrdf_remove_matches(&p);
813         }
814
815         lrdf_free_statements(q);
816
817         p.subject = NULL;
818         strncpy(buf, LADSPA_BASE "hasSetting", sizeof(buf));
819         p.predicate = buf;
820         p.object = setting_uri_copy;
821         lrdf_remove_matches(&p);
822
823         p.subject = setting_uri_copy;
824         p.predicate = NULL;
825         p.object = NULL;
826         lrdf_remove_matches (&p);
827 }
828 #endif
829
830 void
831 LadspaPlugin::do_remove_preset (string name)
832 {
833 #ifdef HAVE_LRDF
834         string const envvar = preset_envvar ();
835         if (envvar.empty()) {
836                 warning << _("Could not locate HOME.  Preset not removed.") << endmsg;
837                 return;
838         }
839
840         Plugin::PresetRecord const * p = preset_by_label (name);
841         if (!p) {
842                 return;
843         }
844
845         string const source = preset_source (envvar);
846         lrdf_remove_preset (source.c_str(), p->uri.c_str ());
847
848         write_preset_file (envvar);
849 #endif
850 }
851
852 string
853 LadspaPlugin::preset_envvar () const
854 {
855         char* envvar;
856         if ((envvar = getenv ("HOME")) == 0) {
857                 return "";
858         }
859
860         return envvar;
861 }
862
863 string
864 LadspaPlugin::preset_source (string envvar) const
865 {
866         return string_compose ("file:%1/.ladspa/rdf/ardour-presets.n3", envvar);
867 }
868
869 bool
870 LadspaPlugin::write_preset_file (string envvar)
871 {
872 #ifdef HAVE_LRDF
873         string path = string_compose("%1/.ladspa", envvar);
874         if (g_mkdir_with_parents (path.c_str(), 0775)) {
875                 warning << string_compose(_("Could not create %1.  Preset not saved. (%2)"), path, strerror(errno)) << endmsg;
876                 return false;
877         }
878
879         path += "/rdf";
880         if (g_mkdir_with_parents (path.c_str(), 0775)) {
881                 warning << string_compose(_("Could not create %1.  Preset not saved. (%2)"), path, strerror(errno)) << endmsg;
882                 return false;
883         }
884
885         string const source = preset_source (envvar);
886
887         if (lrdf_export_by_source (source.c_str(), source.substr(5).c_str())) {
888                 warning << string_compose(_("Error saving presets file %1."), source) << endmsg;
889                 return false;
890         }
891
892         return true;
893 #else
894         return false;
895 #endif
896 }
897
898 string
899 LadspaPlugin::do_save_preset (string name)
900 {
901 #ifdef HAVE_LRDF
902         /* make a vector of pids that are input parameters */
903         vector<int> input_parameter_pids;
904         for (uint32_t i = 0; i < parameter_count(); ++i) {
905                 if (parameter_is_input (i)) {
906                         input_parameter_pids.push_back (i);
907                 }
908         }
909
910         std::string unique (unique_id());
911
912         if (!isdigit (unique[0])) {
913                 return "";
914         }
915
916         uint32_t const id = atol (unique.c_str());
917
918         lrdf_defaults defaults;
919         defaults.count = input_parameter_pids.size ();
920         std::vector<lrdf_portvalue> portvalues(input_parameter_pids.size());
921         defaults.items = &portvalues[0];
922
923         for (vector<int>::size_type i = 0; i < input_parameter_pids.size(); ++i) {
924                 portvalues[i].pid = input_parameter_pids[i];
925                 portvalues[i].value = get_parameter (input_parameter_pids[i]);
926         }
927
928         string const envvar = preset_envvar ();
929         if (envvar.empty()) {
930                 warning << _("Could not locate HOME.  Preset not saved.") << endmsg;
931                 return "";
932         }
933
934         string const source = preset_source (envvar);
935
936         char* uri_char = lrdf_add_preset (source.c_str(), name.c_str(), id, &defaults);
937         string uri (uri_char);
938         free (uri_char);
939
940         if (!write_preset_file (envvar)) {
941                 return "";
942         }
943
944         return uri;
945 #else
946         return string();
947 #endif
948 }
949
950 LADSPA_PortDescriptor
951 LadspaPlugin::port_descriptor (uint32_t i) const
952 {
953         if (i < _descriptor->PortCount) {
954                 return _descriptor->PortDescriptors[i];
955         }
956
957         warning << "LADSPA plugin port index " << i << " out of range." << endmsg;
958         return 0;
959 }
960
961
962