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