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