escape \ as \034 in TOC files
[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 #include <giomm/file.h>
30
31 #include <boost/utility.hpp>
32
33 #include "pbd/compose.h"
34 #include "pbd/error.h"
35 #include "pbd/pathscanner.h"
36 #include "pbd/stl_delete.h"
37 #include "pbd/xml++.h"
38
39 #include "libardour-config.h"
40
41 #include "ardour/ardour.h"
42 #include "ardour/audio_buffer.h"
43 #include "ardour/audioengine.h"
44 #include "ardour/debug.h"
45 #include "ardour/lv2_event_buffer.h"
46 #include "ardour/lv2_plugin.h"
47 #include "ardour/lv2_state.h"
48 #include "ardour/session.h"
49
50 #include "i18n.h"
51 #include <locale.h>
52
53 #include <lilv/lilv.h>
54
55 #include "lv2/lv2plug.in/ns/ext/state/state.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_OLDPSET "http://lv2plug.in/ns/dev/presets#"
64 #define NS_PSET    "http://lv2plug.in/ns/ext/presets#"
65 #define NS_UI      "http://lv2plug.in/ns/extensions/ui#"
66 #define NS_RDFS    "http://www.w3.org/2000/01/rdf-schema#"
67
68 using namespace std;
69 using namespace ARDOUR;
70 using namespace PBD;
71
72 URIMap LV2Plugin::_uri_map;
73 uint32_t LV2Plugin::_midi_event_type = _uri_map.uri_to_id(
74         "http://lv2plug.in/ns/ext/event",
75         "http://lv2plug.in/ns/ext/midi#MidiEvent");
76 uint32_t LV2Plugin::_state_path_type = _uri_map.uri_to_id(
77         NULL, LV2_STATE_PATH_URI);
78
79 class LV2World : boost::noncopyable {
80 public:
81         LV2World ();
82         ~LV2World ();
83
84         LilvWorld* world;
85         LilvNode*  input_class;      ///< Input port
86         LilvNode*  output_class;     ///< Output port
87         LilvNode*  audio_class;      ///< Audio port
88         LilvNode*  control_class;    ///< Control port
89         LilvNode*  event_class;      ///< Event port
90         LilvNode*  midi_class;       ///< MIDI event
91         LilvNode*  in_place_broken;
92         LilvNode*  integer;
93         LilvNode*  toggled;
94         LilvNode*  srate;
95         LilvNode*  gtk_gui;
96         LilvNode*  external_gui;
97         LilvNode*  logarithmic;
98 };
99
100 static LV2World _world;
101
102 struct LV2Plugin::Impl {
103         Impl() : plugin(0), ui(0), ui_type(0), name(0), author(0), instance(0) {}
104         LilvPlugin*     plugin;
105         const LilvUI*   ui;
106         const LilvNode* ui_type;
107         LilvNode*       name;
108         LilvNode*       author;
109         LilvInstance*   instance;
110 };
111
112 LV2Plugin::LV2Plugin (AudioEngine& engine,
113                       Session&     session,
114                       void*        c_plugin,
115                       framecnt_t   rate)
116         : Plugin(engine, session)
117         , _impl(new Impl())
118         , _features(NULL)
119         , _insert_id("0")
120 {
121         init(c_plugin, rate);
122 }
123
124 LV2Plugin::LV2Plugin (const LV2Plugin& other)
125         : Plugin(other)
126         , _impl(new Impl())
127         , _features(NULL)
128         , _insert_id(other._insert_id)
129 {
130         init(other._impl->plugin, other._sample_rate);
131
132         for (uint32_t i = 0; i < parameter_count(); ++i) {
133                 _control_data[i] = other._shadow_data[i];
134                 _shadow_data[i]  = other._shadow_data[i];
135         }
136 }
137
138 void
139 LV2Plugin::init(void* c_plugin, framecnt_t rate)
140 {
141         DEBUG_TRACE(DEBUG::LV2, "init\n");
142
143         _impl->plugin         = (LilvPlugin*)c_plugin;
144         _impl->ui             = NULL;
145         _impl->ui_type        = NULL;
146         _control_data         = 0;
147         _shadow_data          = 0;
148         _latency_control_port = 0;
149         _was_activated        = false;
150
151         _instance_access_feature.URI = "http://lv2plug.in/ns/ext/instance-access";
152         _data_access_feature.URI     = "http://lv2plug.in/ns/ext/data-access";
153         _map_path_feature.URI        = LV2_STATE_MAP_PATH_URI;
154         _make_path_feature.URI       = LV2_STATE_MAKE_PATH_URI;
155
156         LilvPlugin* plugin = _impl->plugin;
157
158         LilvNode* state_iface_uri = lilv_new_uri(_world.world, LV2_STATE_INTERFACE_URI);
159 #ifdef lilv_plugin_has_extension_data
160         _has_state_interface = lilv_plugin_has_extension_data(plugin, state_iface_uri);
161         lilv_node_free(state_iface_uri);
162 #else
163         LilvNode* lv2_extensionData = lilv_new_uri(_world.world, NS_LV2 "extensionData");
164         LilvNodes* extdatas = lilv_plugin_get_value(plugin, lv2_extensionData);
165         LILV_FOREACH(nodes, i, extdatas) {
166                 if (lilv_node_equals(lilv_nodes_get(extdatas, i), state_iface_uri)) {
167                         _has_state_interface = true;
168                         break;
169                 }
170         }
171 #endif
172
173         _features    = (LV2_Feature**)malloc(sizeof(LV2_Feature*) * 8);
174         _features[0] = &_instance_access_feature;
175         _features[1] = &_data_access_feature;
176         _features[2] = &_map_path_feature;
177         _features[3] = &_make_path_feature;
178         _features[4] = _uri_map.uri_map_feature();
179         _features[5] = _uri_map.urid_map_feature();
180         _features[6] = _uri_map.urid_unmap_feature();
181         _features[7] = NULL;
182
183         LV2_State_Map_Path* map_path = (LV2_State_Map_Path*)malloc(
184                 sizeof(LV2_State_Map_Path));
185         map_path->handle = this;
186         map_path->abstract_path = &lv2_state_abstract_path;
187         map_path->absolute_path = &lv2_state_absolute_path;
188         _map_path_feature.data = map_path;
189
190         LV2_State_Make_Path* make_path = (LV2_State_Make_Path*)malloc(
191                 sizeof(LV2_State_Make_Path));
192         make_path->handle = this;
193         make_path->path = &lv2_state_make_path;
194         _make_path_feature.data = make_path;
195
196         _impl->instance = lilv_plugin_instantiate(plugin, rate, _features);
197         _impl->name     = lilv_plugin_get_name(plugin);
198         _impl->author   = lilv_plugin_get_author_name(plugin);
199
200         if (_impl->instance == 0) {
201                 error << _("LV2: Failed to instantiate plugin ") << uri() << endmsg;
202                 throw failed_constructor();
203         }
204
205         _instance_access_feature.data              = (void*)_impl->instance->lv2_handle;
206         _data_access_extension_data.extension_data = _impl->instance->lv2_descriptor->extension_data;
207         _data_access_feature.data                  = &_data_access_extension_data;
208
209         if (lilv_plugin_has_feature(plugin, _world.in_place_broken)) {
210                 error << string_compose(
211                     _("LV2: \"%1\" cannot be used, since it cannot do inplace processing"),
212                     lilv_node_as_string(_impl->name)) << endmsg;
213                 lilv_node_free(_impl->name);
214                 lilv_node_free(_impl->author);
215                 throw failed_constructor();
216         }
217
218         _sample_rate = rate;
219
220         const uint32_t num_ports    = this->num_ports();
221         const bool     latent       = lilv_plugin_has_latency(plugin);
222         const uint32_t latency_port = (latent)
223             ? lilv_plugin_get_latency_port_index(plugin)
224                 : 0;
225
226         _control_data = new float[num_ports];
227         _shadow_data  = new float[num_ports];
228         _defaults     = new float[num_ports];
229
230         for (uint32_t i = 0; i < num_ports; ++i) {
231                 const LilvPort* port = lilv_plugin_get_port_by_index(plugin, i);
232                 const LilvNode* sym  = lilv_port_get_symbol(plugin, port);
233
234                 // Store index in map so we can look up index by symbol
235                 _port_indices.insert(std::make_pair(lilv_node_as_string(sym), i));
236
237                 // Get range and default value if applicable
238                 if (parameter_is_control(i)) {
239                         LilvNode* def;
240                         lilv_port_get_range(plugin, port, &def, NULL, NULL);
241                         _defaults[i] = def ? lilv_node_as_float(def) : 0.0f;
242                         if (lilv_port_has_property (plugin, port, _world.srate)) {
243                                 _defaults[i] *= _session.frame_rate ();
244                         }
245                         lilv_node_free(def);
246
247                         lilv_instance_connect_port(_impl->instance, i, &_control_data[i]);
248
249                         if (latent && ( i == latency_port) ) {
250                                 _latency_control_port  = &_control_data[i];
251                                 *_latency_control_port = 0;
252                         }
253
254                         if (parameter_is_input(i)) {
255                                 _shadow_data[i] = default_value(i);
256                         }
257                 } else {
258                         _defaults[i] = 0.0f;
259                 }
260         }
261
262         LilvUIs* uis = lilv_plugin_get_uis(plugin);
263         if (lilv_uis_size(uis) > 0) {
264 #ifdef HAVE_SUIL
265                 // Look for embeddable UI
266                 LILV_FOREACH(uis, u, uis) {
267                         const LilvUI*   this_ui      = lilv_uis_get(uis, u);
268                         const LilvNode* this_ui_type = NULL;
269                         if (lilv_ui_is_supported(this_ui,
270                                                  suil_ui_supported,
271                                                  _world.gtk_gui,
272                                                  &this_ui_type)) {
273                                 // TODO: Multiple UI support
274                                 _impl->ui      = this_ui;
275                                 _impl->ui_type = this_ui_type;
276                                 break;
277                         }
278                 }
279 #else
280                 // Look for Gtk native UI
281                 LILV_FOREACH(uis, i, uis) {
282                         const LilvUI* ui = lilv_uis_get(uis, i);
283                         if (lilv_ui_is_a(ui, _world.gtk_gui)) {
284                                 _impl->ui      = ui;
285                                 _impl->ui_type = _world.gtk_gui;
286                                 break;
287                         }
288                 }
289 #endif
290
291                 // If Gtk UI is not available, try to find external UI
292                 if (!_impl->ui) {
293                         LILV_FOREACH(uis, i, uis) {
294                                 const LilvUI* ui = lilv_uis_get(uis, i);
295                                 if (lilv_ui_is_a(ui, _world.external_gui)) {
296                                         _impl->ui      = ui;
297                                         _impl->ui_type = _world.external_gui;
298                                         break;
299                                 }
300                         }
301                 }
302         }
303
304         latency_compute_run();
305 }
306
307 LV2Plugin::~LV2Plugin ()
308 {
309         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 destroy\n", name()));
310
311         deactivate();
312         cleanup();
313
314         lilv_instance_free(_impl->instance);
315         lilv_node_free(_impl->name);
316         lilv_node_free(_impl->author);
317
318         delete [] _control_data;
319         delete [] _shadow_data;
320 }
321
322 bool
323 LV2Plugin::is_external_ui() const
324 {
325         if (!_impl->ui) {
326                 return false;
327         }
328         return lilv_ui_is_a(_impl->ui, _world.external_gui);
329 }
330
331 string
332 LV2Plugin::unique_id() const
333 {
334         return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
335 }
336
337 const char*
338 LV2Plugin::uri() const
339 {
340         return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
341 }
342
343 const char*
344 LV2Plugin::label() const
345 {
346         return lilv_node_as_string(_impl->name);
347 }
348
349 const char*
350 LV2Plugin::name() const
351 {
352         return lilv_node_as_string(_impl->name);
353 }
354
355 const char*
356 LV2Plugin::maker() const
357 {
358         return _impl->author ? lilv_node_as_string (_impl->author) : "Unknown";
359 }
360
361 uint32_t
362 LV2Plugin::num_ports() const
363 {
364         return lilv_plugin_get_num_ports(_impl->plugin);
365 }
366
367 uint32_t
368 LV2Plugin::parameter_count() const
369 {
370         return lilv_plugin_get_num_ports(_impl->plugin);
371 }
372
373 float
374 LV2Plugin::default_value(uint32_t port)
375 {
376         return _defaults[port];
377 }
378
379 const char*
380 LV2Plugin::port_symbol(uint32_t index) const
381 {
382         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, index);
383         if (!port) {
384                 error << name() << ": Invalid port index " << index << endmsg;
385         }
386
387         const LilvNode* sym = lilv_port_get_symbol(_impl->plugin, port);
388         return lilv_node_as_string(sym);
389 }
390
391 void
392 LV2Plugin::set_parameter(uint32_t which, float val)
393 {
394         DEBUG_TRACE(DEBUG::LV2, string_compose(
395                             "%1 set parameter %2 to %3\n", name(), which, val));
396
397         if (which < lilv_plugin_get_num_ports(_impl->plugin)) {
398                 _shadow_data[which] = val;
399         } else {
400                 warning << string_compose(
401                     _("Illegal parameter number used with plugin \"%1\". "
402                       "This is a bug in either %2 or the LV2 plugin <%3>"),
403                     name(), PROGRAM_NAME, unique_id()) << endmsg;
404         }
405
406         Plugin::set_parameter(which, val);
407 }
408
409 float
410 LV2Plugin::get_parameter(uint32_t which) const
411 {
412         if (parameter_is_input(which)) {
413                 return (float)_shadow_data[which];
414         } else {
415                 return (float)_control_data[which];
416         }
417         return 0.0f;
418 }
419
420 uint32_t
421 LV2Plugin::nth_parameter(uint32_t n, bool& ok) const
422 {
423         ok = false;
424         for (uint32_t c = 0, x = 0; x < lilv_plugin_get_num_ports(_impl->plugin); ++x) {
425                 if (parameter_is_control(x)) {
426                         if (c++ == n) {
427                                 ok = true;
428                                 return x;
429                         }
430                 }
431         }
432
433         return 0;
434 }
435
436 const void*
437 LV2Plugin::extension_data (const char* uri) const
438 {
439         return lilv_instance_get_extension_data(_impl->instance, uri);
440 }
441
442 void*
443 LV2Plugin::c_plugin ()
444 {
445         return _impl->plugin;
446 }
447
448 void*
449 LV2Plugin::c_ui ()
450 {
451         return (void*)_impl->ui;
452 }
453
454 void*
455 LV2Plugin::c_ui_type ()
456 {
457         return (void*)_impl->ui_type;
458 }
459
460 const std::string
461 LV2Plugin::state_dir() const
462 {
463         return Glib::build_filename(_session.plugins_dir(),
464                                     _insert_id.to_s());
465 }
466
467 int
468 LV2Plugin::lv2_state_store_callback(LV2_State_Handle handle,
469                                     uint32_t         key,
470                                     const void*      value,
471                                     size_t           size,
472                                     uint32_t         type,
473                                     uint32_t         flags)
474 {
475         DEBUG_TRACE(DEBUG::LV2, string_compose(
476                             "state store %1 (size: %2, type: %3, flags: %4)\n",
477                             _uri_map.id_to_uri(NULL, key),
478                             size,
479                             _uri_map.id_to_uri(NULL, type),
480                             flags));
481
482         LV2State* state = (LV2State*)handle;
483         state->add_uri(key,  _uri_map.id_to_uri(NULL, key));
484         state->add_uri(type, _uri_map.id_to_uri(NULL, type));
485
486         if (type == _state_path_type) {
487                 const LV2Plugin&    me = state->plugin;
488                 LV2_State_Map_Path* mp = (LV2_State_Map_Path*)me._map_path_feature.data;
489                 return state->add_value(
490                         key,
491                         lv2_state_abstract_path(mp->handle, (const char*)value),
492                         size, type, flags);
493         } else if ((flags & LV2_STATE_IS_POD) && (flags & LV2_STATE_IS_PORTABLE)) {
494                 return state->add_value(key, value, size, type, flags);
495         } else {
496                 PBD::warning << "LV2 plugin attempted to store non-portable property." << endl;
497                 return -1;
498         }
499 }
500
501 const void*
502 LV2Plugin::lv2_state_retrieve_callback(LV2_State_Handle host_data,
503                                        uint32_t         key,
504                                        size_t*          size,
505                                        uint32_t*        type,
506                                        uint32_t*        flags)
507 {
508         LV2State* state = (LV2State*)host_data;
509         LV2State::Values::const_iterator i = state->values.find(key);
510         if (i == state->values.end()) {
511                 warning << "LV2 plugin attempted to retrieve nonexistent key: "
512                         << _uri_map.id_to_uri(NULL, key) << endmsg;
513                 return NULL;
514         }
515         *size  = i->second.size;
516         *type  = i->second.type;
517         *flags = LV2_STATE_IS_POD | LV2_STATE_IS_PORTABLE;
518         DEBUG_TRACE(DEBUG::LV2, string_compose(
519                             "state retrieve %1 = %2 (size: %3, type: %4)\n",
520                             _uri_map.id_to_uri(NULL, key),
521                             i->second.value, *size, *type));
522         if (*type == _state_path_type) {
523                 const LV2Plugin&    me = state->plugin;
524                 LV2_State_Map_Path* mp = (LV2_State_Map_Path*)me._map_path_feature.data;
525                 return lv2_state_absolute_path(mp->handle, (const char*)i->second.value);
526         } else {
527                 return i->second.value;
528         }
529 }
530
531 char*
532 LV2Plugin::lv2_state_abstract_path(LV2_State_Map_Path_Handle handle,
533                                    const char*               absolute_path)
534 {
535         LV2Plugin* me = (LV2Plugin*)handle;
536         if (me->_insert_id == PBD::ID("0")) {
537                 return g_strdup(absolute_path);
538         }
539
540         const std::string state_dir = me->state_dir();
541
542         char* ret = NULL;
543         if (strncmp(absolute_path, state_dir.c_str(), state_dir.length())) {
544                 // Path outside state directory, make symbolic link
545                 const std::string       name = Glib::path_get_basename(absolute_path);
546                 const std::string       path = Glib::build_filename(state_dir, name);
547                 Gio::File::create_for_path(path)->make_symbolic_link(absolute_path);
548                 ret = g_strndup(path.c_str(), path.length());
549         } else {
550                 // Path inside the state directory, return relative path
551                 const std::string path(absolute_path + state_dir.length() + 1);
552                 ret = g_strndup(path.c_str(), path.length());
553         }
554
555         DEBUG_TRACE(DEBUG::LV2, string_compose("abstract path %1 => %2\n",
556                                                absolute_path, ret));
557
558         return ret;
559 }
560
561 char*
562 LV2Plugin::lv2_state_absolute_path(LV2_State_Map_Path_Handle handle,
563                                    const char*               abstract_path)
564 {
565         LV2Plugin* me = (LV2Plugin*)handle;
566         if (me->_insert_id == PBD::ID("0")) {
567                 return g_strdup(abstract_path);
568         }
569
570         char* ret = NULL;
571         if (g_path_is_absolute(abstract_path)) {
572                 ret = g_strdup(abstract_path);
573         } else {
574                 const std::string apath(abstract_path);
575                 const std::string path = Glib::build_filename(me->state_dir(), apath);
576                 ret = g_strndup(path.c_str(), path.length());
577         }
578
579         DEBUG_TRACE(DEBUG::LV2, string_compose("absolute path %1 => %2\n",
580                                                abstract_path, ret));
581
582         return ret;
583 }
584
585 char*
586 LV2Plugin::lv2_state_make_path(LV2_State_Make_Path_Handle handle,
587                                const char*                path)
588 {
589         LV2Plugin* me = (LV2Plugin*)handle;
590         if (me->_insert_id == PBD::ID("0")) {
591                 return g_strdup(path);
592         }
593
594         const std::string abs_path = Glib::build_filename(me->state_dir(), path);
595         const std::string dirname  = Glib::path_get_dirname(abs_path);
596
597         g_mkdir_with_parents(dirname.c_str(), 0744);
598
599         DEBUG_TRACE(DEBUG::LV2, string_compose("new file path %1 => %2\n",
600                                                path, abs_path));
601
602         return g_strndup(abs_path.c_str(), abs_path.length());
603 }
604
605 static void
606 remove_directory(const std::string& path)
607 {
608         if (!Glib::file_test(path, Glib::FILE_TEST_IS_DIR)) {
609                 return;
610         }
611         
612         Glib::RefPtr<Gio::File>           dir = Gio::File::create_for_path(path);
613         Glib::RefPtr<Gio::FileEnumerator> e   = dir->enumerate_children();
614         Glib::RefPtr<Gio::FileInfo>       fi;
615         while ((fi = e->next_file())) {
616                 if (fi->get_type() == Gio::FILE_TYPE_DIRECTORY) {
617                         remove_directory(fi->get_name());
618                 } else {
619                         dir->get_child(fi->get_name())->remove();
620                 }
621         }
622         dir->remove();
623 }
624
625 void
626 LV2Plugin::add_state(XMLNode* root) const
627 {
628         assert(_insert_id != PBD::ID("0"));
629
630         XMLNode*    child;
631         char        buf[16];
632         LocaleGuard lg(X_("POSIX"));
633
634         for (uint32_t i = 0; i < parameter_count(); ++i) {
635                 if (parameter_is_input(i) && parameter_is_control(i)) {
636                         child = new XMLNode("Port");
637                         child->add_property("symbol", port_symbol(i));
638                         snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
639                         child->add_property("value", string(buf));
640                         root->add_child_nocopy(*child);
641                 }
642         }
643
644         if (_has_state_interface) {
645                 // Create state directory for this plugin instance
646                 cerr << "Create statefile name from ID " << _insert_id << endl;
647                 const std::string state_filename = _insert_id.to_s() + ".rdff";
648                 const std::string state_path     = Glib::build_filename(
649                         _session.plugins_dir(), state_filename);
650
651                 cout << "Saving LV2 plugin state to " << state_path << endl;
652
653                 // Get LV2 State extension data from plugin instance
654                 LV2_State_Interface* state_iface = (LV2_State_Interface*)extension_data(
655                         LV2_STATE_INTERFACE_URI);
656                 if (!state_iface) {
657                         warning << string_compose(
658                             _("Plugin \"%1\% failed to return LV2 state interface"),
659                             unique_id());
660                         return;
661                 }
662
663                 // Remove old state directory (FIXME: should this be preserved?)
664                 remove_directory(state_dir());
665
666                 // Save plugin state to state object
667                 LV2State state(*this, _uri_map);
668                 state_iface->save(_impl->instance->lv2_handle,
669                                   &LV2Plugin::lv2_state_store_callback,
670                                   &state,
671                                   LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE,
672                                   NULL);
673
674                 // Write state object to RDFF file
675                 RDFF file = rdff_open(state_path.c_str(), true);
676                 state.write(file);
677                 rdff_close(file);
678
679                 root->add_property("state-file", state_filename);
680         }
681 }
682
683 static inline const LilvNode*
684 get_value(LilvWorld* world, const LilvNode* subject, const LilvNode* predicate)
685 {
686         LilvNodes* vs = lilv_world_find_nodes(world, subject, predicate, NULL);
687         return vs ? lilv_nodes_get_first(vs) : NULL;
688 }
689
690 static void
691 find_presets_helper(LilvWorld*                                   world,
692                     LilvPlugin*                                  plugin,
693                     std::map<std::string, Plugin::PresetRecord>& out,
694                     LilvNode*                                    preset_pred,
695                     LilvNode*                                    title_pred)
696 {
697         LilvNodes* presets = lilv_plugin_get_value(plugin, preset_pred);
698         LILV_FOREACH(nodes, i, presets) {
699                 const LilvNode* preset = lilv_nodes_get(presets, i);
700                 const LilvNode* name   = get_value(world, preset, title_pred);
701                 if (name) {
702                         out.insert(std::make_pair(lilv_node_as_string(preset),
703                                                   Plugin::PresetRecord(
704                                                           lilv_node_as_string(preset),
705                                                           lilv_node_as_string(name))));
706                 } else {
707                         warning << string_compose(
708                             _("Plugin \"%1\% preset \"%2%\" is missing a label\n"),
709                             lilv_node_as_string(lilv_plugin_get_uri(plugin)),
710                             lilv_node_as_string(preset));
711                 }
712         }
713         lilv_nodes_free(presets);
714 }
715
716 void
717 LV2Plugin::find_presets()
718 {
719         LilvNode* dc_title          = lilv_new_uri(_world.world, NS_DC   "title");
720         LilvNode* oldpset_hasPreset = lilv_new_uri(_world.world, NS_OLDPSET "hasPreset");
721         LilvNode* pset_hasPreset    = lilv_new_uri(_world.world, NS_PSET "hasPreset");
722         LilvNode* rdfs_label        = lilv_new_uri(_world.world, NS_RDFS "label");
723
724         find_presets_helper(_world.world, _impl->plugin, _presets,
725                             oldpset_hasPreset, dc_title);
726
727         find_presets_helper(_world.world, _impl->plugin, _presets,
728                             pset_hasPreset, rdfs_label);
729
730         lilv_node_free(rdfs_label);
731         lilv_node_free(pset_hasPreset);
732         lilv_node_free(oldpset_hasPreset);
733         lilv_node_free(dc_title);
734 }
735
736 bool
737 LV2Plugin::load_preset(PresetRecord r)
738 {
739         Plugin::load_preset(r);
740
741         LilvNode* lv2_port      = lilv_new_uri(_world.world, NS_LV2 "port");
742         LilvNode* lv2_symbol    = lilv_new_uri(_world.world, NS_LV2 "symbol");
743         LilvNode* oldpset_value = lilv_new_uri(_world.world, NS_OLDPSET "value");
744         LilvNode* preset        = lilv_new_uri(_world.world, r.uri.c_str());
745         LilvNode* pset_value    = lilv_new_uri(_world.world, NS_PSET "value");
746
747         LilvNodes* ports = lilv_world_find_nodes(_world.world, preset, lv2_port, NULL);
748         LILV_FOREACH(nodes, i, ports) {
749                 const LilvNode* port   = lilv_nodes_get(ports, i);
750                 const LilvNode* symbol = get_value(_world.world, port, lv2_symbol);
751                 const LilvNode* value  = get_value(_world.world, port, pset_value);
752                 if (!value) {
753                         value = get_value(_world.world, port, oldpset_value);
754                 }
755                 if (value && lilv_node_is_float(value)) {
756                         set_parameter(_port_indices[lilv_node_as_string(symbol)],
757                                       lilv_node_as_float(value));
758                 }
759         }
760         lilv_nodes_free(ports);
761
762         lilv_node_free(pset_value);
763         lilv_node_free(preset);
764         lilv_node_free(oldpset_value);
765         lilv_node_free(lv2_symbol);
766         lilv_node_free(lv2_port);
767
768         return true;
769 }
770
771 std::string
772 LV2Plugin::do_save_preset(string /*name*/)
773 {
774         return "";
775 }
776
777 void
778 LV2Plugin::do_remove_preset(string /*name*/)
779 {}
780
781 bool
782 LV2Plugin::has_editor() const
783 {
784         return _impl->ui != NULL;
785 }
786
787 void
788 LV2Plugin::set_insert_info(const PluginInsert* insert)
789 {
790         _insert_id = insert->id();
791 }
792
793 int
794 LV2Plugin::set_state(const XMLNode& node, int version)
795 {
796         XMLNodeList          nodes;
797         const XMLProperty*   prop;
798         XMLNodeConstIterator iter;
799         XMLNode*             child;
800         const char*          sym;
801         const char*          value;
802         uint32_t             port_id;
803         LocaleGuard          lg(X_("POSIX"));
804
805         if (node.name() != state_node_name()) {
806                 error << _("Bad node sent to LV2Plugin::set_state") << endmsg;
807                 return -1;
808         }
809
810         if (version < 3000) {
811                 nodes = node.children("port");
812         } else {
813                 nodes = node.children("Port");
814         }
815
816         for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
817
818                 child = *iter;
819
820                 if ((prop = child->property("symbol")) != 0) {
821                         sym = prop->value().c_str();
822                 } else {
823                         warning << _("LV2: port has no symbol, ignored") << endmsg;
824                         continue;
825                 }
826
827                 map<string, uint32_t>::iterator i = _port_indices.find(sym);
828
829                 if (i != _port_indices.end()) {
830                         port_id = i->second;
831                 } else {
832                         warning << _("LV2: port has unknown index, ignored") << endmsg;
833                         continue;
834                 }
835
836                 if ((prop = child->property("value")) != 0) {
837                         value = prop->value().c_str();
838                 } else {
839                         warning << _("LV2: port has no value, ignored") << endmsg;
840                         continue;
841                 }
842
843                 set_parameter(port_id, atof(value));
844         }
845
846         if ((prop = node.property("state-file")) != 0) {
847                 std::string state_path = Glib::build_filename(_session.plugins_dir(),
848                                                               prop->value());
849
850                 cout << "LV2 state path " << state_path << endl;
851
852                 // Get LV2 State extension data from plugin instance
853                 LV2_State_Interface* state_iface = (LV2_State_Interface*)extension_data(
854                         LV2_STATE_INTERFACE_URI);
855                 if (state_iface) {
856                         cout << "Loading LV2 state from " << state_path << endl;
857                         RDFF     file = rdff_open(state_path.c_str(), false);
858                         LV2State state(*this, _uri_map);
859                         state.read(file);
860                         state_iface->restore(_impl->instance->lv2_handle,
861                                              &LV2Plugin::lv2_state_retrieve_callback,
862                                              &state,
863                                              LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE,
864                                              NULL);
865                         rdff_close(file);
866                 } else {
867                         warning << string_compose(
868                             _("Plugin \"%1\% failed to return LV2 state interface"),
869                             unique_id());
870                 }
871         }
872
873         latency_compute_run();
874
875         return Plugin::set_state(node, version);
876 }
877
878 int
879 LV2Plugin::get_parameter_descriptor(uint32_t which, ParameterDescriptor& desc) const
880 {
881         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, which);
882
883         LilvNode *def, *min, *max;
884         lilv_port_get_range(_impl->plugin, port, &def, &min, &max);
885
886         desc.integer_step = lilv_port_has_property(_impl->plugin, port, _world.integer);
887         desc.toggled      = lilv_port_has_property(_impl->plugin, port, _world.toggled);
888         desc.logarithmic  = lilv_port_has_property(_impl->plugin, port, _world.logarithmic);
889         desc.sr_dependent = lilv_port_has_property(_impl->plugin, port, _world.srate);
890         desc.label        = lilv_node_as_string(lilv_port_get_name(_impl->plugin, port));
891         desc.lower        = min ? lilv_node_as_float(min) : 0.0f;
892         desc.upper        = max ? lilv_node_as_float(max) : 1.0f;
893         if (desc.sr_dependent) {
894                 desc.lower *= _session.frame_rate ();
895                 desc.upper *= _session.frame_rate ();
896         }
897                 
898         desc.min_unbound  = false; // TODO: LV2 extension required
899         desc.max_unbound  = false; // TODO: LV2 extension required
900
901         if (desc.integer_step) {
902                 desc.step      = 1.0;
903                 desc.smallstep = 0.1;
904                 desc.largestep = 10.0;
905         } else {
906                 const float delta = desc.upper - desc.lower;
907                 desc.step      = delta / 1000.0f;
908                 desc.smallstep = delta / 10000.0f;
909                 desc.largestep = delta / 10.0f;
910         }
911
912         lilv_node_free(def);
913         lilv_node_free(min);
914         lilv_node_free(max);
915
916         return 0;
917 }
918
919 string
920 LV2Plugin::describe_parameter(Evoral::Parameter which)
921 {
922         if (( which.type() == PluginAutomation) && ( which.id() < parameter_count()) ) {
923                 LilvNode* name = lilv_port_get_name(_impl->plugin,
924                                                     lilv_plugin_get_port_by_index(_impl->plugin, which.id()));
925                 string ret(lilv_node_as_string(name));
926                 lilv_node_free(name);
927                 return ret;
928         } else {
929                 return "??";
930         }
931 }
932
933 framecnt_t
934 LV2Plugin::signal_latency() const
935 {
936         if (_latency_control_port) {
937                 return (framecnt_t)floor(*_latency_control_port);
938         } else {
939                 return 0;
940         }
941 }
942
943 set<Evoral::Parameter>
944 LV2Plugin::automatable() const
945 {
946         set<Evoral::Parameter> ret;
947
948         for (uint32_t i = 0; i < parameter_count(); ++i) {
949                 if (parameter_is_input(i) && parameter_is_control(i)) {
950                         ret.insert(ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
951                 }
952         }
953
954         return ret;
955 }
956
957 void
958 LV2Plugin::activate()
959 {
960         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 activate\n", name()));
961
962         if (!_was_activated) {
963                 lilv_instance_activate(_impl->instance);
964                 _was_activated = true;
965         }
966 }
967
968 void
969 LV2Plugin::deactivate()
970 {
971         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 deactivate\n", name()));
972
973         if (_was_activated) {
974                 lilv_instance_deactivate(_impl->instance);
975                 _was_activated = false;
976         }
977 }
978
979 void
980 LV2Plugin::cleanup()
981 {
982         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 cleanup\n", name()));
983
984         activate();
985         deactivate();
986         lilv_instance_free(_impl->instance);
987         _impl->instance = NULL;
988 }
989
990 int
991 LV2Plugin::connect_and_run(BufferSet& bufs,
992         ChanMapping in_map, ChanMapping out_map,
993         pframes_t nframes, framecnt_t offset)
994 {
995         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 run %2 offset %3\n", name(), nframes, offset));
996         Plugin::connect_and_run(bufs, in_map, out_map, nframes, offset);
997
998         cycles_t then = get_cycles();
999
1000         ChanCount bufs_count;
1001         bufs_count.set(DataType::AUDIO, 1);
1002         bufs_count.set(DataType::MIDI, 1);
1003         BufferSet& silent_bufs  = _session.get_silent_buffers(bufs_count);
1004         BufferSet& scratch_bufs = _session.get_silent_buffers(bufs_count);
1005
1006         uint32_t audio_in_index  = 0;
1007         uint32_t audio_out_index = 0;
1008         uint32_t midi_in_index   = 0;
1009         uint32_t midi_out_index  = 0;
1010         bool valid;
1011         for (uint32_t port_index = 0; port_index < parameter_count(); ++port_index) {
1012                 if (parameter_is_audio(port_index)) {
1013                         if (parameter_is_input(port_index)) {
1014                                 const uint32_t buf_index = in_map.get(DataType::AUDIO, audio_in_index++, &valid);
1015                                 lilv_instance_connect_port(_impl->instance, port_index,
1016                                                            valid ? bufs.get_audio(buf_index).data(offset)
1017                                                                  : silent_bufs.get_audio(0).data(offset));
1018                         } else if (parameter_is_output(port_index)) {
1019                                 const uint32_t buf_index = out_map.get(DataType::AUDIO, audio_out_index++, &valid);
1020                                 //cerr << port_index << " : " << " AUDIO OUT " << buf_index << endl;
1021                                 lilv_instance_connect_port(_impl->instance, port_index,
1022                                                            valid ? bufs.get_audio(buf_index).data(offset)
1023                                                                  : scratch_bufs.get_audio(0).data(offset));
1024                         }
1025                 } else if (parameter_is_midi(port_index)) {
1026                         /* FIXME: The checks here for bufs.count().n_midi() > buf_index shouldn't
1027                            be necessary, but the mapping is illegal in some cases.  Ideally
1028                            that should be fixed, but this is easier...
1029                         */
1030                         if (parameter_is_input(port_index)) {
1031                                 const uint32_t buf_index = in_map.get(DataType::MIDI, midi_in_index++, &valid);
1032                                 if (valid && bufs.count().n_midi() > buf_index) {
1033                                         lilv_instance_connect_port(_impl->instance, port_index,
1034                                                                    bufs.get_lv2_midi(true, buf_index).data());
1035                                 } else {
1036                                         lilv_instance_connect_port(_impl->instance, port_index,
1037                                                                    silent_bufs.get_lv2_midi(true, 0).data());
1038                                 }
1039                         } else if (parameter_is_output(port_index)) {
1040                                 const uint32_t buf_index = out_map.get(DataType::MIDI, midi_out_index++, &valid);
1041                                 if (valid && bufs.count().n_midi() > buf_index) {
1042                                         lilv_instance_connect_port(_impl->instance, port_index,
1043                                                                    bufs.get_lv2_midi(false, buf_index).data());
1044                                 } else {
1045                                         lilv_instance_connect_port(_impl->instance, port_index,
1046                                                                    scratch_bufs.get_lv2_midi(true, 0).data());
1047                                 }
1048                         }
1049                 } else if (!parameter_is_control(port_index)) {
1050                         // Optional port (it'd better be if we've made it this far...)
1051                         lilv_instance_connect_port(_impl->instance, port_index, NULL);
1052                 }
1053         }
1054
1055         run(nframes);
1056
1057         midi_out_index = 0;
1058         for (uint32_t port_index = 0; port_index < parameter_count(); ++port_index) {
1059                 if (parameter_is_midi(port_index) && parameter_is_output(port_index)) {
1060                         const uint32_t buf_index = out_map.get(DataType::MIDI, midi_out_index++, &valid);
1061                         if (valid) {
1062                                 bufs.flush_lv2_midi(true, buf_index);
1063                         }
1064                 }
1065         }
1066
1067         cycles_t now = get_cycles();
1068         set_cycles((uint32_t)(now - then));
1069
1070         return 0;
1071 }
1072
1073 bool
1074 LV2Plugin::parameter_is_control(uint32_t param) const
1075 {
1076         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, param);
1077         return lilv_port_is_a(_impl->plugin, port, _world.control_class);
1078 }
1079
1080 bool
1081 LV2Plugin::parameter_is_audio(uint32_t param) const
1082 {
1083         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, param);
1084         return lilv_port_is_a(_impl->plugin, port, _world.audio_class);
1085 }
1086
1087 bool
1088 LV2Plugin::parameter_is_midi(uint32_t param) const
1089 {
1090         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, param);
1091         return lilv_port_is_a(_impl->plugin, port, _world.event_class);
1092         //      && lilv_port_supports_event(_impl->plugin, port, _world.midi_class);
1093 }
1094
1095 bool
1096 LV2Plugin::parameter_is_output(uint32_t param) const
1097 {
1098         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, param);
1099         return lilv_port_is_a(_impl->plugin, port, _world.output_class);
1100 }
1101
1102 bool
1103 LV2Plugin::parameter_is_input(uint32_t param) const
1104 {
1105         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, param);
1106         return lilv_port_is_a(_impl->plugin, port, _world.input_class);
1107 }
1108
1109 void
1110 LV2Plugin::print_parameter(uint32_t param, char* buf, uint32_t len) const
1111 {
1112         if (buf && len) {
1113                 if (param < parameter_count()) {
1114                         snprintf(buf, len, "%.3f", get_parameter(param));
1115                 } else {
1116                         strcat(buf, "0");
1117                 }
1118         }
1119 }
1120
1121 boost::shared_ptr<Plugin::ScalePoints>
1122 LV2Plugin::get_scale_points(uint32_t port_index) const
1123 {
1124         const LilvPort*  port   = lilv_plugin_get_port_by_index(_impl->plugin, port_index);
1125         LilvScalePoints* points = lilv_port_get_scale_points(_impl->plugin, port);
1126
1127         boost::shared_ptr<Plugin::ScalePoints> ret;
1128         if (!points) {
1129                 return ret;
1130         }
1131
1132         ret = boost::shared_ptr<Plugin::ScalePoints>(new ScalePoints());
1133
1134         LILV_FOREACH(scale_points, i, points) {
1135                 const LilvScalePoint* p     = lilv_scale_points_get(points, i);
1136                 const LilvNode*       label = lilv_scale_point_get_label(p);
1137                 const LilvNode*       value = lilv_scale_point_get_value(p);
1138                 if (label && (lilv_node_is_float(value) || lilv_node_is_int(value))) {
1139                         ret->insert(make_pair(lilv_node_as_string(label),
1140                                               lilv_node_as_float(value)));
1141                 }
1142         }
1143
1144         lilv_scale_points_free(points);
1145         return ret;
1146 }
1147
1148 void
1149 LV2Plugin::run(pframes_t nframes)
1150 {
1151         for (uint32_t i = 0; i < parameter_count(); ++i) {
1152                 if (parameter_is_control(i) && parameter_is_input(i)) {
1153                         _control_data[i] = _shadow_data[i];
1154                 }
1155         }
1156
1157         lilv_instance_run(_impl->instance, nframes);
1158 }
1159
1160 void
1161 LV2Plugin::latency_compute_run()
1162 {
1163         if (!_latency_control_port) {
1164                 return;
1165         }
1166
1167         // Run the plugin so that it can set its latency parameter
1168
1169         activate();
1170
1171         uint32_t port_index = 0;
1172         uint32_t in_index   = 0;
1173         uint32_t out_index  = 0;
1174
1175         const framecnt_t bufsize = 1024;
1176         float            buffer[bufsize];
1177
1178         memset(buffer, 0, sizeof(float) * bufsize);
1179
1180         // FIXME: Ensure plugins can handle in-place processing
1181
1182         port_index = 0;
1183
1184         while (port_index < parameter_count()) {
1185                 if (parameter_is_audio(port_index)) {
1186                         if (parameter_is_input(port_index)) {
1187                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1188                                 in_index++;
1189                         } else if (parameter_is_output(port_index)) {
1190                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1191                                 out_index++;
1192                         }
1193                 }
1194                 port_index++;
1195         }
1196
1197         run(bufsize);
1198         deactivate();
1199 }
1200
1201 LV2World::LV2World()
1202         : world(lilv_world_new())
1203 {
1204         lilv_world_load_all(world);
1205         input_class     = lilv_new_uri(world, LILV_URI_INPUT_PORT);
1206         output_class    = lilv_new_uri(world, LILV_URI_OUTPUT_PORT);
1207         control_class   = lilv_new_uri(world, LILV_URI_CONTROL_PORT);
1208         audio_class     = lilv_new_uri(world, LILV_URI_AUDIO_PORT);
1209         event_class     = lilv_new_uri(world, LILV_URI_EVENT_PORT);
1210         midi_class      = lilv_new_uri(world, LILV_URI_MIDI_EVENT);
1211         in_place_broken = lilv_new_uri(world, LILV_NS_LV2 "inPlaceBroken");
1212         integer         = lilv_new_uri(world, LILV_NS_LV2 "integer");
1213         toggled         = lilv_new_uri(world, LILV_NS_LV2 "toggled");
1214         srate           = lilv_new_uri(world, LILV_NS_LV2 "sampleRate");
1215         gtk_gui         = lilv_new_uri(world, NS_UI "GtkUI");
1216         external_gui    = lilv_new_uri(world, NS_UI "external");
1217         logarithmic     = lilv_new_uri(world, "http://lv2plug.in/ns/dev/extportinfo#logarithmic");
1218 }
1219
1220 LV2World::~LV2World()
1221 {
1222         lilv_node_free(input_class);
1223         lilv_node_free(output_class);
1224         lilv_node_free(control_class);
1225         lilv_node_free(audio_class);
1226         lilv_node_free(event_class);
1227         lilv_node_free(midi_class);
1228         lilv_node_free(in_place_broken);
1229 }
1230
1231 LV2PluginInfo::LV2PluginInfo (void* c_plugin)
1232         : _c_plugin(c_plugin)
1233 {
1234         type = ARDOUR::LV2;
1235 }
1236
1237 LV2PluginInfo::~LV2PluginInfo()
1238 {}
1239
1240 PluginPtr
1241 LV2PluginInfo::load(Session& session)
1242 {
1243         try {
1244                 PluginPtr plugin;
1245
1246                 plugin.reset(new LV2Plugin(session.engine(), session,
1247                                            (LilvPlugin*)_c_plugin,
1248                                            session.frame_rate()));
1249
1250                 plugin->set_info(PluginInfoPtr(new LV2PluginInfo(*this)));
1251                 return plugin;
1252         } catch (failed_constructor& err) {
1253                 return PluginPtr((Plugin*)0);
1254         }
1255
1256         return PluginPtr();
1257 }
1258
1259 PluginInfoList*
1260 LV2PluginInfo::discover()
1261 {
1262         PluginInfoList*    plugs   = new PluginInfoList;
1263         const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
1264
1265         cerr << "LV2: Discovering " << lilv_plugins_size(plugins) << " plugins" << endl;
1266
1267         LILV_FOREACH(plugins, i, plugins) {
1268                 const LilvPlugin* p = lilv_plugins_get(plugins, i);
1269                 LV2PluginInfoPtr  info(new LV2PluginInfo((void*)p));
1270
1271                 LilvNode* name = lilv_plugin_get_name(p);
1272                 if (!name) {
1273                         cerr << "LV2: invalid plugin\n";
1274                         continue;
1275                 }
1276
1277                 info->type = LV2;
1278
1279                 info->name = string(lilv_node_as_string(name));
1280                 lilv_node_free(name);
1281
1282                 const LilvPluginClass* pclass = lilv_plugin_get_class(p);
1283                 const LilvNode*        label  = lilv_plugin_class_get_label(pclass);
1284                 info->category = lilv_node_as_string(label);
1285
1286                 LilvNode* author_name = lilv_plugin_get_author_name(p);
1287                 info->creator = author_name ? string(lilv_node_as_string(author_name)) : "Unknown";
1288                 lilv_node_free(author_name);
1289
1290                 info->path = "/NOPATH"; // Meaningless for LV2
1291
1292                 info->n_inputs.set_audio(
1293                         lilv_plugin_get_num_ports_of_class(
1294                                 p, _world.input_class, _world.audio_class, NULL));
1295                 info->n_inputs.set_midi(
1296                         lilv_plugin_get_num_ports_of_class(
1297                                 p, _world.input_class, _world.event_class, NULL));
1298
1299                 info->n_outputs.set_audio(
1300                         lilv_plugin_get_num_ports_of_class(
1301                                 p, _world.output_class, _world.audio_class, NULL));
1302                 info->n_outputs.set_midi(
1303                         lilv_plugin_get_num_ports_of_class(
1304                                 p, _world.output_class, _world.event_class, NULL));
1305
1306                 info->unique_id = lilv_node_as_uri(lilv_plugin_get_uri(p));
1307                 info->index     = 0; // Meaningless for LV2
1308
1309                 plugs->push_back(info);
1310         }
1311
1312         cerr << "Done LV2 discovery" << endl;
1313
1314         return plugs;
1315 }