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