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