Use ISC license for RDFF (same idea, MIT style, just prettier).
[ardour.git] / libs / ardour / lv2_plugin.cc
1 /*
2     Copyright (C) 2008-2011 Paul Davis
3     Author: David Robillard
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 #include <string>
22 #include <vector>
23
24 #include <cmath>
25 #include <cstdlib>
26 #include <cstring>
27
28 #include <glibmm.h>
29
30 #include <boost/utility.hpp>
31
32 #include "pbd/compose.h"
33 #include "pbd/error.h"
34 #include "pbd/pathscanner.h"
35 #include "pbd/stl_delete.h"
36 #include "pbd/xml++.h"
37
38 #include "libardour-config.h"
39
40 #include "ardour/ardour.h"
41 #include "ardour/audio_buffer.h"
42 #include "ardour/audioengine.h"
43 #include "ardour/debug.h"
44 #include "ardour/lv2_event_buffer.h"
45 #include "ardour/lv2_plugin.h"
46 #include "ardour/lv2_state.h"
47 #include "ardour/session.h"
48
49 #include "i18n.h"
50 #include <locale.h>
51
52 #include <slv2/slv2.h>
53
54 #include "lv2ext/lv2_files.h"
55 #include "lv2ext/lv2_persist.h"
56 #include "rdff.h"
57 #ifdef HAVE_SUIL
58 #include <suil/suil.h>
59 #endif
60
61 #define NS_DC   "http://dublincore.org/documents/dcmi-namespace/"
62 #define NS_LV2  "http://lv2plug.in/ns/lv2core#"
63 #define NS_PSET "http://lv2plug.in/ns/dev/presets#"
64 #define NS_UI   "http://lv2plug.in/ns/extensions/ui#"
65
66 using namespace std;
67 using namespace ARDOUR;
68 using namespace PBD;
69
70 URIMap LV2Plugin::_uri_map;
71 uint32_t LV2Plugin::_midi_event_type = _uri_map.uri_to_id(
72         "http://lv2plug.in/ns/ext/event",
73         "http://lv2plug.in/ns/ext/midi#MidiEvent");
74
75 class LV2World : boost::noncopyable {
76 public:
77         LV2World ();
78         ~LV2World ();
79
80         SLV2World world;
81         SLV2Value input_class; ///< Input port
82         SLV2Value output_class; ///< Output port
83         SLV2Value audio_class; ///< Audio port
84         SLV2Value control_class; ///< Control port
85         SLV2Value event_class; ///< Event port
86         SLV2Value midi_class; ///< MIDI event
87         SLV2Value in_place_broken;
88         SLV2Value integer;
89         SLV2Value toggled;
90         SLV2Value srate;
91         SLV2Value gtk_gui;
92         SLV2Value external_gui;
93         SLV2Value logarithmic;
94 };
95
96 static LV2World _world;
97
98 struct LV2Plugin::Impl {
99         Impl() : plugin(0), ui(0), ui_type(0), name(0), author(0), instance(0) {}
100         SLV2Plugin   plugin;
101         SLV2UI       ui;
102         SLV2Value    ui_type;
103         SLV2Value    name;
104         SLV2Value    author;
105         SLV2Instance instance;
106 };
107
108 LV2Plugin::LV2Plugin (AudioEngine& engine,
109                       Session&     session,
110                       void*        c_plugin,
111                       framecnt_t   rate)
112         : Plugin(engine, session)
113         , _impl(new Impl())
114         , _features(NULL)
115         , _insert_id("0")
116 {
117         init(c_plugin, rate);
118 }
119
120 LV2Plugin::LV2Plugin (const LV2Plugin& other)
121         : Plugin(other)
122         , _impl(new Impl())
123         , _features(NULL)
124         , _insert_id(other._insert_id)
125 {
126         init(other._impl->plugin, other._sample_rate);
127
128         for (uint32_t i = 0; i < parameter_count(); ++i) {
129                 _control_data[i] = other._shadow_data[i];
130                 _shadow_data[i]  = other._shadow_data[i];
131         }
132 }
133
134 void
135 LV2Plugin::init(void* c_plugin, framecnt_t rate)
136 {
137         DEBUG_TRACE(DEBUG::LV2, "init\n");
138
139         _impl->plugin          = (SLV2Plugin)c_plugin;
140         _impl->ui              = NULL;
141         _impl->ui_type         = NULL;
142         _control_data         = 0;
143         _shadow_data          = 0;
144         _latency_control_port = 0;
145         _was_activated        = false;
146
147         _instance_access_feature.URI  = "http://lv2plug.in/ns/ext/instance-access";
148         _data_access_feature.URI      = "http://lv2plug.in/ns/ext/data-access";
149         _path_support_feature.URI     = LV2_FILES_PATH_SUPPORT_URI;
150         _new_file_support_feature.URI = LV2_FILES_NEW_FILE_SUPPORT_URI;
151         _persist_feature.URI          = "http://lv2plug.in/ns/ext/persist";
152         _persist_feature.data         = NULL;
153
154         SLV2Plugin plugin = _impl->plugin;
155
156         SLV2Value persist_uri = slv2_value_new_uri(_world.world, _persist_feature.URI);
157         _supports_persist = slv2_plugin_has_feature(plugin, persist_uri);
158         slv2_value_free(persist_uri);
159
160         _features    = (LV2_Feature**)malloc(sizeof(LV2_Feature*) * 7);
161         _features[0] = &_instance_access_feature;
162         _features[1] = &_data_access_feature;
163         _features[2] = &_path_support_feature;
164         _features[3] = &_new_file_support_feature;
165         _features[4] = &_persist_feature;
166         _features[5] = _uri_map.feature();
167         _features[6] = NULL;
168
169         LV2_Files_Path_Support* path_support = (LV2_Files_Path_Support*)malloc(
170                 sizeof(LV2_Files_Path_Support));
171         path_support->host_data = this;
172         path_support->abstract_path = &lv2_files_abstract_path;
173         path_support->absolute_path = &lv2_files_absolute_path;
174         _path_support_feature.data = path_support;
175
176         LV2_Files_New_File_Support* new_file_support = (LV2_Files_New_File_Support*)malloc(
177                 sizeof(LV2_Files_New_File_Support));
178         new_file_support->host_data = this;
179         new_file_support->new_file_path = &lv2_files_new_file_path;
180         _new_file_support_feature.data = new_file_support;
181
182         _impl->instance = slv2_plugin_instantiate(plugin, rate, _features);
183         _impl->name     = slv2_plugin_get_name(plugin);
184         _impl->author   = slv2_plugin_get_author_name(plugin);
185
186         if (_impl->instance == 0) {
187                 error << _("LV2: Failed to instantiate plugin ") << uri() << endmsg;
188                 throw failed_constructor();
189         }
190
191         _instance_access_feature.data              = (void*)_impl->instance->lv2_handle;
192         _data_access_extension_data.extension_data = _impl->instance->lv2_descriptor->extension_data;
193         _data_access_feature.data                  = &_data_access_extension_data;
194
195         if (slv2_plugin_has_feature(plugin, _world.in_place_broken)) {
196                 error << string_compose(
197                     _("LV2: \"%1\" cannot be used, since it cannot do inplace processing"),
198                     slv2_value_as_string(_impl->name)) << endmsg;
199                 slv2_value_free(_impl->name);
200                 slv2_value_free(_impl->author);
201                 throw failed_constructor();
202         }
203
204         _sample_rate = rate;
205
206         const uint32_t num_ports    = this->num_ports();
207         const bool     latent       = slv2_plugin_has_latency(plugin);
208         const uint32_t latency_port = (latent)
209             ? slv2_plugin_get_latency_port_index(plugin)
210                 : 0;
211
212         _control_data = new float[num_ports];
213         _shadow_data  = new float[num_ports];
214         _defaults     = new float[num_ports];
215
216         for (uint32_t i = 0; i < num_ports; ++i) {
217                 SLV2Port  port = slv2_plugin_get_port_by_index(plugin, i);
218                 SLV2Value sym  = slv2_port_get_symbol(plugin, port);
219
220                 // Store index in map so we can look up index by symbol
221                 _port_indices.insert(std::make_pair(slv2_value_as_string(sym), i));
222
223                 // Get range and default value if applicable
224                 if (parameter_is_control(i)) {
225                         SLV2Value def;
226                         slv2_port_get_range(plugin, port, &def, NULL, NULL);
227                         _defaults[i] = def ? slv2_value_as_float(def) : 0.0f;
228                         slv2_value_free(def);
229
230                         slv2_instance_connect_port(_impl->instance, i, &_control_data[i]);
231
232                         if (latent && ( i == latency_port) ) {
233                                 _latency_control_port  = &_control_data[i];
234                                 *_latency_control_port = 0;
235                         }
236
237                         if (parameter_is_input(i)) {
238                                 _shadow_data[i] = default_value(i);
239                         }
240                 } else {
241                         _defaults[i] = 0.0f;
242                 }
243         }
244
245         SLV2UIs uis = slv2_plugin_get_uis(plugin);
246         if (slv2_uis_size(uis) > 0) {
247 #if defined(HAVE_NEW_SLV2) and defined(HAVE_SUIL)
248                 // Look for embeddable UI
249                 SLV2Value ui_type = NULL;
250                 SLV2_FOREACH(uis, u, uis) {
251                         SLV2UI    this_ui      = slv2_uis_get(uis, u);
252                         SLV2Value this_ui_type = NULL;
253                         if (slv2_ui_is_supported(this_ui,
254                                                  suil_ui_supported,
255                                                  _world.gtk_gui,
256                                                  &this_ui_type)) {
257                                 // TODO: Multiple UI support
258                                 _ui      = this_ui;
259                                 _ui_type = this_ui_type;
260                                 break;
261                         } 
262                 }
263 #else
264                 // Look for Gtk native UI
265                 for (unsigned i = 0; i < slv2_uis_size(uis); ++i) {
266                         SLV2UI ui = slv2_uis_get_at(uis, i);
267                         if (slv2_ui_is_a(ui, _world.gtk_gui)) {
268                                 _impl->ui      = ui;
269                                 _impl->ui_type = _world.gtk_gui;
270                                 break;
271                         }
272                 }
273 #endif
274
275                 // If Gtk UI is not available, try to find external UI
276                 if (!_impl->ui) {
277                         for (unsigned i = 0; i < slv2_uis_size(uis); ++i) {
278                                 SLV2UI ui = slv2_uis_get_at(uis, i);
279                                 if (slv2_ui_is_a(ui, _world.external_gui)) {
280                                         _impl->ui      = ui;
281                                         _impl->ui_type = _world.external_gui;
282                                         break;
283                                 }
284                         }
285                 }
286         }
287
288         latency_compute_run();
289 }
290
291 LV2Plugin::~LV2Plugin ()
292 {
293         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 destroy\n", name()));
294
295         deactivate();
296         cleanup();
297
298         slv2_instance_free(_impl->instance);
299         slv2_value_free(_impl->name);
300         slv2_value_free(_impl->author);
301 #if defined(HAVE_NEW_SLV2) and defined(HAVE_SUIL)
302         slv2_value_free(_impl->ui_type);
303 #else
304         /* _ui_type points to a global, so leave it alone */
305 #endif
306         delete [] _control_data;
307         delete [] _shadow_data;
308 }
309
310 bool
311 LV2Plugin::is_external_ui() const
312 {
313         if (!_impl->ui) {
314                 return false;
315         }
316         return slv2_ui_is_a(_impl->ui, _world.external_gui);
317 }
318
319 string
320 LV2Plugin::unique_id() const
321 {
322         return slv2_value_as_uri(slv2_plugin_get_uri(_impl->plugin));
323 }
324
325 const char*
326 LV2Plugin::uri() const
327 {
328         return slv2_value_as_uri(slv2_plugin_get_uri(_impl->plugin));
329 }
330
331 const char*
332 LV2Plugin::label() const
333 {
334         return slv2_value_as_string(_impl->name);
335 }
336
337 const char*
338 LV2Plugin::name() const
339 {
340         return slv2_value_as_string(_impl->name);
341 }
342
343 const char*
344 LV2Plugin::maker() const
345 {
346         return _impl->author ? slv2_value_as_string (_impl->author) : "Unknown";
347 }
348
349 uint32_t
350 LV2Plugin::num_ports() const
351 {
352         return slv2_plugin_get_num_ports(_impl->plugin);
353 }
354
355 uint32_t
356 LV2Plugin::parameter_count() const
357 {
358         return slv2_plugin_get_num_ports(_impl->plugin);
359 }
360
361 float
362 LV2Plugin::default_value(uint32_t port)
363 {
364         return _defaults[port];
365 }
366
367 const char*
368 LV2Plugin::port_symbol(uint32_t index) const
369 {
370         SLV2Port port = slv2_plugin_get_port_by_index(_impl->plugin, index);
371         if (!port) {
372                 error << name() << ": Invalid port index " << index << endmsg;
373         }
374
375         SLV2Value sym = slv2_port_get_symbol(_impl->plugin, port);
376         return slv2_value_as_string(sym);
377 }
378
379 void
380 LV2Plugin::set_parameter(uint32_t which, float val)
381 {
382         DEBUG_TRACE(DEBUG::LV2, string_compose(
383                             "%1 set parameter %2 to %3\n", name(), which, val));
384
385         if (which < slv2_plugin_get_num_ports(_impl->plugin)) {
386                 _shadow_data[which] = val;
387         } else {
388                 warning << string_compose(
389                     _("Illegal parameter number used with plugin \"%1\". "
390                       "This is a bug in either %2 or the LV2 plugin <%3>"),
391                     name(), PROGRAM_NAME, unique_id()) << endmsg;
392         }
393
394         Plugin::set_parameter(which, val);
395 }
396
397 float
398 LV2Plugin::get_parameter(uint32_t which) const
399 {
400         if (parameter_is_input(which)) {
401                 return (float)_shadow_data[which];
402         } else {
403                 return (float)_control_data[which];
404         }
405         return 0.0f;
406 }
407
408 uint32_t
409 LV2Plugin::nth_parameter(uint32_t n, bool& ok) const
410 {
411         ok = false;
412         for (uint32_t c = 0, x = 0; x < slv2_plugin_get_num_ports(_impl->plugin); ++x) {
413                 if (parameter_is_control(x)) {
414                         if (c++ == n) {
415                                 ok = true;
416                                 return x;
417                         }
418                 }
419         }
420
421         return 0;
422 }
423
424 const void*
425 LV2Plugin::extension_data (const char* uri) const
426 {
427         return slv2_instance_get_extension_data(_impl->instance, uri);
428 }
429
430 void*
431 LV2Plugin::c_plugin ()
432 {
433         return _impl->plugin;
434 }
435
436 void*
437 LV2Plugin::c_ui ()
438 {
439         return _impl->ui;
440 }
441
442 void*
443 LV2Plugin::c_ui_type ()
444 {
445         return _impl->ui_type;
446 }
447
448 int
449 LV2Plugin::lv2_persist_store_callback(void*       host_data,
450                                       uint32_t    key,
451                                       const void* value,
452                                       size_t      size,
453                                       uint32_t    type,
454                                       uint32_t    flags)
455 {
456         DEBUG_TRACE(DEBUG::LV2, string_compose(
457                             "persist store %1 (size: %2, type: %3)\n",
458                             _uri_map.id_to_uri(NULL, key),
459                             size,
460                             _uri_map.id_to_uri(NULL, type)));
461
462         LV2PersistState* state = (LV2PersistState*)host_data;
463         state->add_uri(key,  _uri_map.id_to_uri(NULL, key)); 
464         state->add_uri(type, _uri_map.id_to_uri(NULL, type)); 
465         return state->add_value(key, value, size, type, flags);
466 }
467
468 const void*
469 LV2Plugin::lv2_persist_retrieve_callback(void*     host_data,
470                                          uint32_t  key,
471                                          size_t*   size,
472                                          uint32_t* type,
473                                          uint32_t* flags)
474 {
475         LV2PersistState* state = (LV2PersistState*)host_data;
476         LV2PersistState::Values::const_iterator i = state->values.find(key);
477         if (i == state->values.end()) {
478                 warning << "LV2 plugin attempted to retrieve nonexistent key: "
479                         << _uri_map.id_to_uri(NULL, key) << endmsg;
480                 return NULL;
481         }
482         *size = i->second.size;
483         *type = i->second.type;
484         *flags = LV2_PERSIST_IS_POD | LV2_PERSIST_IS_PORTABLE; // FIXME
485         DEBUG_TRACE(DEBUG::LV2, string_compose(
486                             "persist retrieve %1 = %2 (size: %3, type: %4)\n",
487                             _uri_map.id_to_uri(NULL, key),
488                             i->second.value, *size, *type));
489         return i->second.value;
490 }
491
492 char*
493 LV2Plugin::lv2_files_abstract_path(LV2_Files_Host_Data host_data,
494                                    const char*         absolute_path)
495 {
496         LV2Plugin* me = (LV2Plugin*)host_data;
497         if (me->_insert_id == PBD::ID("0")) {
498                 return g_strdup(absolute_path);
499         }
500
501         const std::string state_dir = Glib::build_filename(me->_session.plugins_dir(),
502                                                            me->_insert_id.to_s());
503
504         char* ret = NULL;
505         if (strncmp(absolute_path, state_dir.c_str(), state_dir.length())) {
506                 ret = g_strdup(absolute_path);
507         } else {
508                 const std::string path(absolute_path + state_dir.length() + 1);
509                 ret = g_strndup(path.c_str(), path.length());
510         }
511
512         DEBUG_TRACE(DEBUG::LV2, string_compose("abstract path %1 => %2\n",
513                                                absolute_path, ret));
514
515         return ret;
516 }
517
518 char*
519 LV2Plugin::lv2_files_absolute_path(LV2_Files_Host_Data host_data,
520                                    const char*         abstract_path)
521 {
522         LV2Plugin* me = (LV2Plugin*)host_data;
523         if (me->_insert_id == PBD::ID("0")) {
524                 return g_strdup(abstract_path);
525         }
526
527         char* ret = NULL;
528         if (g_path_is_absolute(abstract_path)) {
529                 ret = g_strdup(abstract_path);
530         } else {
531                 const std::string apath(abstract_path);
532                 const std::string state_dir = Glib::build_filename(me->_session.plugins_dir(),
533                                                                    me->_insert_id.to_s());
534                 const std::string path = Glib::build_filename(state_dir,
535                                                               apath);
536                 ret = g_strndup(path.c_str(), path.length());
537         }
538
539         DEBUG_TRACE(DEBUG::LV2, string_compose("absolute path %1 => %2\n",
540                                                abstract_path, ret));
541
542         return ret;
543 }
544
545 char*
546 LV2Plugin::lv2_files_new_file_path(LV2_Files_Host_Data host_data,
547                                    const char*         relative_path)
548 {
549         LV2Plugin* me = (LV2Plugin*)host_data;
550         if (me->_insert_id == PBD::ID("0")) {
551                 return g_strdup(relative_path);
552         }
553
554         const std::string state_dir = Glib::build_filename(me->_session.plugins_dir(),
555                                                            me->_insert_id.to_s());
556         const std::string path = Glib::build_filename(state_dir,
557                                                       relative_path);
558
559         char* dirname = g_path_get_dirname(path.c_str());
560         g_mkdir_with_parents(dirname, 0744);
561         free(dirname);
562
563         DEBUG_TRACE(DEBUG::LV2, string_compose("new file path %1 => %2\n",
564                                                relative_path, path));
565         
566         return g_strndup(path.c_str(), path.length());
567 }
568
569 void
570 LV2Plugin::add_state(XMLNode* root) const
571 {
572         assert(_insert_id != PBD::ID("0"));
573
574         XMLNode*    child;
575         char        buf[16];
576         LocaleGuard lg(X_("POSIX"));
577
578         for (uint32_t i = 0; i < parameter_count(); ++i) {
579                 if (parameter_is_input(i) && parameter_is_control(i)) {
580                         child = new XMLNode("Port");
581                         child->add_property("symbol", port_symbol(i));
582                         snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
583                         child->add_property("value", string(buf));
584                         root->add_child_nocopy(*child);
585                 }
586         }
587
588         if (_supports_persist) {
589                 // Create state directory for this plugin instance
590                 const std::string state_filename = _insert_id.to_s() + ".rdff";
591                 const std::string state_path     = Glib::build_filename(
592                         _session.plugins_dir(), state_filename);
593
594                 cout << "Saving LV2 plugin state to " << state_path << endl;
595
596                 // Get LV2 Persist extension data from plugin instance
597                 LV2_Persist* persist = (LV2_Persist*)extension_data(
598                         "http://lv2plug.in/ns/ext/persist");
599                 if (!persist) {
600                         warning << string_compose(
601                             _("Plugin \"%1\% failed to return LV2 persist data"),
602                             unique_id());
603                         return;
604                 }
605
606                 // Save plugin state to state object
607                 LV2PersistState state(_uri_map);
608                 persist->save(_impl->instance->lv2_handle,
609                               &LV2Plugin::lv2_persist_store_callback,
610                               &state);
611
612                 // Write state object to RDFF file
613                 RDFF file = rdff_open(state_path.c_str(), true);
614                 state.write(file);
615                 rdff_close(file);
616
617                 root->add_property("state-file", state_filename);
618         }
619 }
620
621 static inline SLV2Value
622 get_value(SLV2Plugin p, SLV2Value subject, SLV2Value predicate)
623 {
624         SLV2Values vs = slv2_plugin_get_value_for_subject(p, subject, predicate);
625         return vs ? slv2_values_get_at(vs, 0) : NULL;
626 }
627
628 void
629 LV2Plugin::find_presets()
630 {
631         SLV2Value dc_title       = slv2_value_new_uri(_world.world, NS_DC   "title");
632         SLV2Value pset_hasPreset = slv2_value_new_uri(_world.world, NS_PSET "hasPreset");
633
634         SLV2Values presets = slv2_plugin_get_value(_impl->plugin, pset_hasPreset);
635         for (unsigned i = 0; i < slv2_values_size(presets); ++i) {
636                 SLV2Value preset = slv2_values_get_at(presets, i);
637                 SLV2Value name   = get_value(_impl->plugin, preset, dc_title);
638                 if (name) {
639                         _presets.insert(std::make_pair(slv2_value_as_string(preset),
640                                                        PresetRecord(
641                                                            slv2_value_as_string(preset),
642                                                            slv2_value_as_string(name))));
643                 } else {
644                         warning << string_compose(
645                             _("Plugin \"%1\% preset \"%2%\" is missing a dc:title\n"),
646                             unique_id(), slv2_value_as_string(preset));
647                 }
648         }
649         slv2_values_free(presets);
650
651         slv2_value_free(pset_hasPreset);
652         slv2_value_free(dc_title);
653 }
654
655 bool
656 LV2Plugin::load_preset(PresetRecord r)
657 {
658         Plugin::load_preset(r);
659
660 #ifdef HAVE_NEW_SLV2
661         // New (>= 0.7.0) slv2 no longer supports SPARQL, but exposes blank nodes
662         // so querying ports is possible with the simple/fast API
663         SLV2Value lv2_port   = slv2_value_new_uri(_world.world, NS_LV2 "port");
664         SLV2Value lv2_symbol = slv2_value_new_uri(_world.world, NS_LV2 "symbol");
665         SLV2Value pset_value = slv2_value_new_uri(_world.world, NS_PSET "value");
666         SLV2Value preset     = slv2_value_new_uri(_world.world, r.uri.c_str());
667
668         SLV2Values ports = slv2_plugin_get_value_for_subject(_impl->plugin, preset, lv2_port);
669         for (unsigned i = 0; i < slv2_values_size(ports); ++i) {
670                 SLV2Value port   = slv2_values_get_at(ports, i);
671                 SLV2Value symbol = get_value(_impl->plugin, port, lv2_symbol);
672                 SLV2Value value  = get_value(_impl->plugin, port, pset_value);
673                 if (value && slv2_value_is_float(value)) {
674                         set_parameter(_port_indices[slv2_value_as_string(symbol)],
675                                       slv2_value_as_float(value));
676                 }
677         }
678         slv2_values_free(ports);
679
680         slv2_value_free(preset);
681         slv2_value_free(pset_value);
682         slv2_value_free(lv2_symbol);
683         slv2_value_free(lv2_port);
684 #else
685         const string query = string(
686                 "PREFIX lv2p: <http://lv2plug.in/ns/dev/presets#>\n"
687                 "PREFIX dc:  <http://dublincore.org/documents/dcmi-namespace/>\n"
688                 "SELECT ?sym ?val WHERE { <") + r.uri + "> lv2:port ?port . "
689             " ?port lv2:symbol ?sym ; lv2p:value ?val . }";
690         SLV2Results values = slv2_plugin_query_sparql(_impl->plugin, query.c_str());
691         for (; !slv2_results_finished(values); slv2_results_next(values)) {
692                 SLV2Value sym = slv2_results_get_binding_value(values, 0);
693                 SLV2Value val = slv2_results_get_binding_value(values, 1);
694                 if (slv2_value_is_float(val)) {
695                         uint32_t index = _port_indices[slv2_value_as_string(sym)];
696                         set_parameter(index, slv2_value_as_float(val));
697                 }
698         }
699         slv2_results_free(values);
700 #endif
701         return true;
702 }
703
704 std::string
705 LV2Plugin::do_save_preset(string /*name*/)
706 {
707         return "";
708 }
709
710 void
711 LV2Plugin::do_remove_preset(string /*name*/)
712 {}
713
714 bool
715 LV2Plugin::has_editor() const
716 {
717         return _impl->ui != NULL;
718 }
719
720 void
721 LV2Plugin::set_insert_info(const PluginInsert* insert)
722 {
723         _insert_id = insert->id();
724 }
725
726 int
727 LV2Plugin::set_state(const XMLNode& node, int version)
728 {
729         XMLNodeList          nodes;
730         const XMLProperty*   prop;
731         XMLNodeConstIterator iter;
732         XMLNode*             child;
733         const char*          sym;
734         const char*          value;
735         uint32_t             port_id;
736         LocaleGuard          lg(X_("POSIX"));
737
738         if (node.name() != state_node_name()) {
739                 error << _("Bad node sent to LV2Plugin::set_state") << endmsg;
740                 return -1;
741         }
742
743         if (version < 3000) {
744                 nodes = node.children("port");
745         } else {
746                 nodes = node.children("Port");
747         }
748
749         for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
750
751                 child = *iter;
752
753                 if ((prop = child->property("symbol")) != 0) {
754                         sym = prop->value().c_str();
755                 } else {
756                         warning << _("LV2: port has no symbol, ignored") << endmsg;
757                         continue;
758                 }
759
760                 map<string, uint32_t>::iterator i = _port_indices.find(sym);
761
762                 if (i != _port_indices.end()) {
763                         port_id = i->second;
764                 } else {
765                         warning << _("LV2: port has unknown index, ignored") << endmsg;
766                         continue;
767                 }
768
769                 if ((prop = child->property("value")) != 0) {
770                         value = prop->value().c_str();
771                 } else {
772                         warning << _("LV2: port has no value, ignored") << endmsg;
773                         continue;
774                 }
775
776                 set_parameter(port_id, atof(value));
777         }
778
779         if ((prop = node.property("state-file")) != 0) {
780                 std::string state_path = Glib::build_filename(_session.plugins_dir(),
781                                                               prop->value());
782
783                 cout << "LV2 state path " << state_path << endl;
784
785                 // Get LV2 Persist extension data from plugin instance
786                 LV2_Persist* persist = (LV2_Persist*)extension_data(
787                         "http://lv2plug.in/ns/ext/persist");
788                 if (persist) {
789                         cout << "Loading LV2 state from " << state_path << endl;
790                         RDFF            file = rdff_open(state_path.c_str(), false);
791                         LV2PersistState state(_uri_map);
792                         state.read(file);
793                         persist->restore(_impl->instance->lv2_handle,
794                                          &LV2Plugin::lv2_persist_retrieve_callback,
795                                          &state);
796                         rdff_close(file);
797                 } else {
798                         warning << string_compose(
799                             _("Plugin \"%1\% failed to return LV2 persist data"),
800                             unique_id());
801                 }
802         }
803
804         latency_compute_run();
805
806         return Plugin::set_state(node, version);
807 }
808
809 int
810 LV2Plugin::get_parameter_descriptor(uint32_t which, ParameterDescriptor& desc) const
811 {
812         SLV2Port port = slv2_plugin_get_port_by_index(_impl->plugin, which);
813
814         SLV2Value def, min, max;
815         slv2_port_get_range(_impl->plugin, port, &def, &min, &max);
816
817         desc.integer_step = slv2_port_has_property(_impl->plugin, port, _world.integer);
818         desc.toggled      = slv2_port_has_property(_impl->plugin, port, _world.toggled);
819         desc.logarithmic  = slv2_port_has_property(_impl->plugin, port, _world.logarithmic);
820         desc.sr_dependent = slv2_port_has_property(_impl->plugin, port, _world.srate);
821         desc.label        = slv2_value_as_string(slv2_port_get_name(_impl->plugin, port));
822         desc.lower        = min ? slv2_value_as_float(min) : 0.0f;
823         desc.upper        = max ? slv2_value_as_float(max) : 1.0f;
824         desc.min_unbound  = false; // TODO: LV2 extension required
825         desc.max_unbound  = false; // TODO: LV2 extension required
826
827         if (desc.integer_step) {
828                 desc.step      = 1.0;
829                 desc.smallstep = 0.1;
830                 desc.largestep = 10.0;
831         } else {
832                 const float delta = desc.upper - desc.lower;
833                 desc.step      = delta / 1000.0f;
834                 desc.smallstep = delta / 10000.0f;
835                 desc.largestep = delta / 10.0f;
836         }
837
838         slv2_value_free(def);
839         slv2_value_free(min);
840         slv2_value_free(max);
841
842         return 0;
843 }
844
845 string
846 LV2Plugin::describe_parameter(Evoral::Parameter which)
847 {
848         if (( which.type() == PluginAutomation) && ( which.id() < parameter_count()) ) {
849                 SLV2Value name = slv2_port_get_name(_impl->plugin,
850                                                     slv2_plugin_get_port_by_index(_impl->plugin, which.id()));
851                 string ret(slv2_value_as_string(name));
852                 slv2_value_free(name);
853                 return ret;
854         } else {
855                 return "??";
856         }
857 }
858
859 framecnt_t
860 LV2Plugin::signal_latency() const
861 {
862         if (_latency_control_port) {
863                 return (framecnt_t)floor(*_latency_control_port);
864         } else {
865                 return 0;
866         }
867 }
868
869 set<Evoral::Parameter>
870 LV2Plugin::automatable() const
871 {
872         set<Evoral::Parameter> ret;
873
874         for (uint32_t i = 0; i < parameter_count(); ++i) {
875                 if (parameter_is_input(i) && parameter_is_control(i)) {
876                         ret.insert(ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
877                 }
878         }
879
880         return ret;
881 }
882
883 void
884 LV2Plugin::activate()
885 {
886         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 activate\n", name()));
887
888         if (!_was_activated) {
889                 slv2_instance_activate(_impl->instance);
890                 _was_activated = true;
891         }
892 }
893
894 void
895 LV2Plugin::deactivate()
896 {
897         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 deactivate\n", name()));
898
899         if (_was_activated) {
900                 slv2_instance_deactivate(_impl->instance);
901                 _was_activated = false;
902         }
903 }
904
905 void
906 LV2Plugin::cleanup()
907 {
908         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 cleanup\n", name()));
909
910         activate();
911         deactivate();
912         slv2_instance_free(_impl->instance);
913         _impl->instance = NULL;
914 }
915
916 int
917 LV2Plugin::connect_and_run(BufferSet& bufs,
918         ChanMapping in_map, ChanMapping out_map,
919         pframes_t nframes, framecnt_t offset)
920 {
921         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 run %2 offset %3\n", name(), nframes, offset));
922         Plugin::connect_and_run(bufs, in_map, out_map, nframes, offset);
923
924         cycles_t then = get_cycles();
925
926         uint32_t audio_in_index  = 0;
927         uint32_t audio_out_index = 0;
928         uint32_t midi_in_index   = 0;
929         uint32_t midi_out_index  = 0;
930         for (uint32_t port_index = 0; port_index < parameter_count(); ++port_index) {
931                 if (parameter_is_audio(port_index)) {
932                         if (parameter_is_input(port_index)) {
933                                 const uint32_t buf_index = in_map.get(DataType::AUDIO, audio_in_index++);
934                                 slv2_instance_connect_port(_impl->instance, port_index,
935                                                            bufs.get_audio(buf_index).data(offset));
936                         } else if (parameter_is_output(port_index)) {
937                                 const uint32_t buf_index = out_map.get(DataType::AUDIO, audio_out_index++);
938                                 //cerr << port_index << " : " << " AUDIO OUT " << buf_index << endl;
939                                 slv2_instance_connect_port(_impl->instance, port_index,
940                                                            bufs.get_audio(buf_index).data(offset));
941                         }
942                 } else if (parameter_is_midi(port_index)) {
943                         if (parameter_is_input(port_index)) {
944                                 const uint32_t buf_index = in_map.get(DataType::MIDI, midi_in_index++);
945                                 slv2_instance_connect_port(_impl->instance, port_index,
946                                                            bufs.get_lv2_midi(true, buf_index).data());
947                         } else if (parameter_is_output(port_index)) {
948                                 const uint32_t buf_index = out_map.get(DataType::MIDI, midi_out_index++);
949                                 slv2_instance_connect_port(_impl->instance, port_index,
950                                                            bufs.get_lv2_midi(false, buf_index).data());
951                         }
952                 } else if (!parameter_is_control(port_index)) {
953                         // Optional port (it'd better be if we've made it this far...)
954                         slv2_instance_connect_port(_impl->instance, port_index, NULL);
955                 }
956         }
957
958         run(nframes);
959
960         midi_out_index = 0;
961         for (uint32_t port_index = 0; port_index < parameter_count(); ++port_index) {
962                 if (parameter_is_midi(port_index) && parameter_is_output(port_index)) {
963                         const uint32_t buf_index = out_map.get(DataType::MIDI, midi_out_index++);
964                         bufs.flush_lv2_midi(true, buf_index);
965                 }
966         }
967
968         cycles_t now = get_cycles();
969         set_cycles((uint32_t)(now - then));
970
971         return 0;
972 }
973
974 bool
975 LV2Plugin::parameter_is_control(uint32_t param) const
976 {
977         SLV2Port port = slv2_plugin_get_port_by_index(_impl->plugin, param);
978         return slv2_port_is_a(_impl->plugin, port, _world.control_class);
979 }
980
981 bool
982 LV2Plugin::parameter_is_audio(uint32_t param) const
983 {
984         SLV2Port port = slv2_plugin_get_port_by_index(_impl->plugin, param);
985         return slv2_port_is_a(_impl->plugin, port, _world.audio_class);
986 }
987
988 bool
989 LV2Plugin::parameter_is_midi(uint32_t param) const
990 {
991         SLV2Port port = slv2_plugin_get_port_by_index(_impl->plugin, param);
992         return slv2_port_is_a(_impl->plugin, port, _world.event_class);
993         //      && slv2_port_supports_event(_impl->plugin, port, _world.midi_class);
994 }
995
996 bool
997 LV2Plugin::parameter_is_output(uint32_t param) const
998 {
999         SLV2Port port = slv2_plugin_get_port_by_index(_impl->plugin, param);
1000         return slv2_port_is_a(_impl->plugin, port, _world.output_class);
1001 }
1002
1003 bool
1004 LV2Plugin::parameter_is_input(uint32_t param) const
1005 {
1006         SLV2Port port = slv2_plugin_get_port_by_index(_impl->plugin, param);
1007         return slv2_port_is_a(_impl->plugin, port, _world.input_class);
1008 }
1009
1010 void
1011 LV2Plugin::print_parameter(uint32_t param, char* buf, uint32_t len) const
1012 {
1013         if (buf && len) {
1014                 if (param < parameter_count()) {
1015                         snprintf(buf, len, "%.3f", get_parameter(param));
1016                 } else {
1017                         strcat(buf, "0");
1018                 }
1019         }
1020 }
1021
1022 boost::shared_ptr<Plugin::ScalePoints>
1023 LV2Plugin::get_scale_points(uint32_t port_index) const
1024 {
1025         SLV2Port        port   = slv2_plugin_get_port_by_index(_impl->plugin, port_index);
1026         SLV2ScalePoints points = slv2_port_get_scale_points(_impl->plugin, port);
1027
1028         boost::shared_ptr<Plugin::ScalePoints> ret;
1029         if (!points) {
1030                 return ret;
1031         }
1032
1033         ret = boost::shared_ptr<Plugin::ScalePoints>(new ScalePoints());
1034
1035         for (unsigned i = 0; i < slv2_scale_points_size(points); ++i) {
1036                 SLV2ScalePoint p     = slv2_scale_points_get_at(points, i);
1037                 SLV2Value      label = slv2_scale_point_get_label(p);
1038                 SLV2Value      value = slv2_scale_point_get_value(p);
1039                 if (label && (slv2_value_is_float(value) || slv2_value_is_int(value))) {
1040                         ret->insert(make_pair(slv2_value_as_string(label),
1041                                               slv2_value_as_float(value)));
1042                 }
1043         }
1044
1045         slv2_scale_points_free(points);
1046         return ret;
1047 }
1048
1049 void
1050 LV2Plugin::run(pframes_t nframes)
1051 {
1052         for (uint32_t i = 0; i < parameter_count(); ++i) {
1053                 if (parameter_is_control(i) && parameter_is_input(i)) {
1054                         _control_data[i] = _shadow_data[i];
1055                 }
1056         }
1057
1058         slv2_instance_run(_impl->instance, nframes);
1059 }
1060
1061 void
1062 LV2Plugin::latency_compute_run()
1063 {
1064         if (!_latency_control_port) {
1065                 return;
1066         }
1067
1068         // Run the plugin so that it can set its latency parameter
1069
1070         activate();
1071
1072         uint32_t port_index = 0;
1073         uint32_t in_index   = 0;
1074         uint32_t out_index  = 0;
1075
1076         const framecnt_t bufsize = 1024;
1077         float            buffer[bufsize];
1078
1079         memset(buffer, 0, sizeof(float) * bufsize);
1080
1081         // FIXME: Ensure plugins can handle in-place processing
1082
1083         port_index = 0;
1084
1085         while (port_index < parameter_count()) {
1086                 if (parameter_is_audio(port_index)) {
1087                         if (parameter_is_input(port_index)) {
1088                                 slv2_instance_connect_port(_impl->instance, port_index, buffer);
1089                                 in_index++;
1090                         } else if (parameter_is_output(port_index)) {
1091                                 slv2_instance_connect_port(_impl->instance, port_index, buffer);
1092                                 out_index++;
1093                         }
1094                 }
1095                 port_index++;
1096         }
1097
1098         run(bufsize);
1099         deactivate();
1100 }
1101
1102 LV2World::LV2World()
1103         : world(slv2_world_new())
1104 {
1105         slv2_world_load_all(world);
1106         input_class     = slv2_value_new_uri(world, SLV2_PORT_CLASS_INPUT);
1107         output_class    = slv2_value_new_uri(world, SLV2_PORT_CLASS_OUTPUT);
1108         control_class   = slv2_value_new_uri(world, SLV2_PORT_CLASS_CONTROL);
1109         audio_class     = slv2_value_new_uri(world, SLV2_PORT_CLASS_AUDIO);
1110         event_class     = slv2_value_new_uri(world, SLV2_PORT_CLASS_EVENT);
1111         midi_class      = slv2_value_new_uri(world, SLV2_EVENT_CLASS_MIDI);
1112         in_place_broken = slv2_value_new_uri(world, SLV2_NAMESPACE_LV2 "inPlaceBroken");
1113         integer         = slv2_value_new_uri(world, SLV2_NAMESPACE_LV2 "integer");
1114         toggled         = slv2_value_new_uri(world, SLV2_NAMESPACE_LV2 "toggled");
1115         srate           = slv2_value_new_uri(world, SLV2_NAMESPACE_LV2 "sampleRate");
1116         gtk_gui         = slv2_value_new_uri(world, NS_UI "GtkUI");
1117         external_gui    = slv2_value_new_uri(world, NS_UI "external");
1118         logarithmic     = slv2_value_new_uri(world, "http://lv2plug.in/ns/dev/extportinfo#logarithmic");
1119 }
1120
1121 LV2World::~LV2World()
1122 {
1123         slv2_value_free(input_class);
1124         slv2_value_free(output_class);
1125         slv2_value_free(control_class);
1126         slv2_value_free(audio_class);
1127         slv2_value_free(event_class);
1128         slv2_value_free(midi_class);
1129         slv2_value_free(in_place_broken);
1130 }
1131
1132 LV2PluginInfo::LV2PluginInfo (void* c_plugin)
1133         : _c_plugin(c_plugin)
1134 {
1135         type = ARDOUR::LV2;
1136 }
1137
1138 LV2PluginInfo::~LV2PluginInfo()
1139 {}
1140
1141 PluginPtr
1142 LV2PluginInfo::load(Session& session)
1143 {
1144         try {
1145                 PluginPtr plugin;
1146
1147                 plugin.reset(new LV2Plugin(session.engine(), session,
1148                                            (SLV2Plugin)_c_plugin,
1149                                            session.frame_rate()));
1150
1151                 plugin->set_info(PluginInfoPtr(new LV2PluginInfo(*this)));
1152                 return plugin;
1153         } catch (failed_constructor& err) {
1154                 return PluginPtr((Plugin*)0);
1155         }
1156
1157         return PluginPtr();
1158 }
1159
1160 PluginInfoList*
1161 LV2PluginInfo::discover()
1162 {
1163         PluginInfoList* plugs   = new PluginInfoList;
1164         SLV2Plugins     plugins = slv2_world_get_all_plugins(_world.world);
1165
1166         cerr << "LV2: Discovering " << slv2_plugins_size(plugins) << " plugins" << endl;
1167
1168         for (unsigned i = 0; i < slv2_plugins_size(plugins); ++i) {
1169                 SLV2Plugin       p = slv2_plugins_get_at(plugins, i);
1170                 LV2PluginInfoPtr info(new LV2PluginInfo(p));
1171
1172                 SLV2Value name = slv2_plugin_get_name(p);
1173
1174                 if (!name) {
1175                         cerr << "LV2: invalid plugin\n";
1176                         continue;
1177                 }
1178
1179                 info->type = LV2;
1180
1181                 info->name = string(slv2_value_as_string(name));
1182                 slv2_value_free(name);
1183
1184                 SLV2PluginClass pclass = slv2_plugin_get_class(p);
1185                 SLV2Value       label  = slv2_plugin_class_get_label(pclass);
1186                 info->category = slv2_value_as_string(label);
1187
1188                 SLV2Value author_name = slv2_plugin_get_author_name(p);
1189                 info->creator = author_name ? string(slv2_value_as_string(author_name)) : "Unknown";
1190                 slv2_value_free(author_name);
1191
1192                 info->path = "/NOPATH"; // Meaningless for LV2
1193
1194                 info->n_inputs.set_audio(
1195                         slv2_plugin_get_num_ports_of_class(
1196                                 p, _world.input_class, _world.audio_class, NULL));
1197                 info->n_inputs.set_midi(
1198                         slv2_plugin_get_num_ports_of_class(
1199                                 p, _world.input_class, _world.event_class, NULL));
1200
1201                 info->n_outputs.set_audio(
1202                         slv2_plugin_get_num_ports_of_class(
1203                                 p, _world.output_class, _world.audio_class, NULL));
1204                 info->n_outputs.set_midi(
1205                         slv2_plugin_get_num_ports_of_class(
1206                                 p, _world.output_class, _world.event_class, NULL));
1207
1208                 info->unique_id = slv2_value_as_uri(slv2_plugin_get_uri(p));
1209                 info->index     = 0; // Meaningless for LV2
1210
1211                 plugs->push_back(info);
1212         }
1213
1214         cerr << "Done LV2 discovery" << endl;
1215
1216         return plugs;
1217 }