Fix deleting and re-saving LV2 presets.
[ardour.git] / libs / ardour / lv2_plugin.cc
1 /*
2     Copyright (C) 2008-2012 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 #include <limits>
23
24 #include <cmath>
25 #include <cstdlib>
26 #include <cstring>
27
28 #include <glib/gstdio.h>
29 #include <glib/gprintf.h>
30 #include <glibmm.h>
31
32 #include <boost/utility.hpp>
33
34 #include "pbd/file_utils.h"
35 #include "pbd/stl_delete.h"
36 #include "pbd/compose.h"
37 #include "pbd/error.h"
38 #include "pbd/xml++.h"
39
40 #include "libardour-config.h"
41
42 #include "ardour/audio_buffer.h"
43 #include "ardour/audioengine.h"
44 #include "ardour/debug.h"
45 #include "ardour/lv2_plugin.h"
46 #include "ardour/session.h"
47 #include "ardour/tempo.h"
48 #include "ardour/types.h"
49 #include "ardour/utils.h"
50 #include "ardour/worker.h"
51 #include "ardour/search_paths.h"
52
53 #include "i18n.h"
54 #include <locale.h>
55
56 #include <lilv/lilv.h>
57
58 #include "lv2/lv2plug.in/ns/ext/atom/atom.h"
59 #include "lv2/lv2plug.in/ns/ext/atom/forge.h"
60 #include "lv2/lv2plug.in/ns/ext/log/log.h"
61 #include "lv2/lv2plug.in/ns/ext/midi/midi.h"
62 #include "lv2/lv2plug.in/ns/ext/port-props/port-props.h"
63 #include "lv2/lv2plug.in/ns/ext/presets/presets.h"
64 #include "lv2/lv2plug.in/ns/ext/state/state.h"
65 #include "lv2/lv2plug.in/ns/ext/time/time.h"
66 #include "lv2/lv2plug.in/ns/ext/worker/worker.h"
67 #include "lv2/lv2plug.in/ns/ext/resize-port/resize-port.h"
68 #include "lv2/lv2plug.in/ns/extensions/ui/ui.h"
69 #include "lv2/lv2plug.in/ns/extensions/units/units.h"
70 #include "lv2/lv2plug.in/ns/ext/patch/patch.h"
71 #ifdef HAVE_LV2_1_2_0
72 #include "lv2/lv2plug.in/ns/ext/buf-size/buf-size.h"
73 #include "lv2/lv2plug.in/ns/ext/options/options.h"
74 #endif
75
76 #include "lv2_evbuf.h"
77
78 #ifdef HAVE_SUIL
79 #include <suil/suil.h>
80 #endif
81
82 // Compatibility for old LV2
83 #ifndef LV2_ATOM_CONTENTS_CONST
84 #define LV2_ATOM_CONTENTS_CONST(type, atom) \
85         ((const void*)((const uint8_t*)(atom) + sizeof(type)))
86 #endif
87 #ifndef LV2_ATOM_BODY_CONST
88 #define LV2_ATOM_BODY_CONST(atom) LV2_ATOM_CONTENTS_CONST(LV2_Atom, atom)
89 #endif
90 #ifndef LV2_PATCH__property
91 #define LV2_PATCH__property LV2_PATCH_PREFIX "property"
92 #endif
93 #ifndef LV2_PATCH__value
94 #define LV2_PATCH__value LV2_PATCH_PREFIX "value"
95 #endif
96 #ifndef LV2_PATCH__writable
97 #define LV2_PATCH__writable LV2_PATCH_PREFIX "writable"
98 #endif
99
100 /** The number of MIDI buffers that will fit in a UI/worker comm buffer.
101     This needs to be roughly the number of cycles the UI will get around to
102     actually processing the traffic.  Lower values are flakier but save memory.
103 */
104 static const size_t NBUFS = 4;
105
106 using namespace std;
107 using namespace ARDOUR;
108 using namespace PBD;
109
110 class LV2World : boost::noncopyable {
111 public:
112         LV2World ();
113         ~LV2World ();
114
115         void load_bundled_plugins(bool verbose=false);
116
117         LilvWorld* world;
118
119         LilvNode* atom_AtomPort;
120         LilvNode* atom_Chunk;
121         LilvNode* atom_Sequence;
122         LilvNode* atom_bufferType;
123         LilvNode* atom_eventTransfer;
124         LilvNode* atom_supports;
125         LilvNode* ev_EventPort;
126         LilvNode* ext_logarithmic;
127         LilvNode* ext_notOnGUI;
128         LilvNode* lv2_AudioPort;
129         LilvNode* lv2_ControlPort;
130         LilvNode* lv2_InputPort;
131         LilvNode* lv2_OutputPort;
132         LilvNode* lv2_enumeration;
133         LilvNode* lv2_freewheeling;
134         LilvNode* lv2_inPlaceBroken;
135         LilvNode* lv2_integer;
136         LilvNode* lv2_default;
137         LilvNode* lv2_minimum;
138         LilvNode* lv2_maximum;
139         LilvNode* lv2_reportsLatency;
140         LilvNode* lv2_sampleRate;
141         LilvNode* lv2_toggled;
142         LilvNode* midi_MidiEvent;
143         LilvNode* rdfs_comment;
144         LilvNode* rdfs_label;
145         LilvNode* rdfs_range;
146         LilvNode* rsz_minimumSize;
147         LilvNode* time_Position;
148         LilvNode* ui_GtkUI;
149         LilvNode* ui_external;
150         LilvNode* ui_externalkx;
151         LilvNode* units_hz;
152         LilvNode* units_db;
153         LilvNode* units_unit;
154         LilvNode* units_render;
155         LilvNode* units_midiNote;
156         LilvNode* patch_writable;
157         LilvNode* patch_Message;
158
159 private:
160         bool _bundle_checked;
161 };
162
163 static LV2World _world;
164
165 /* worker extension */
166
167 /** Called by the plugin to schedule non-RT work. */
168 static LV2_Worker_Status
169 work_schedule(LV2_Worker_Schedule_Handle handle,
170               uint32_t                   size,
171               const void*                data)
172 {
173         LV2Plugin* plugin = (LV2Plugin*)handle;
174         if (plugin->session().engine().freewheeling()) {
175                 // Freewheeling, do the work immediately in this (audio) thread
176                 return (LV2_Worker_Status)plugin->work(size, data);
177         } else {
178                 // Enqueue message for the worker thread
179                 return plugin->worker()->schedule(size, data) ?
180                         LV2_WORKER_SUCCESS : LV2_WORKER_ERR_UNKNOWN;
181         }
182 }
183
184 /** Called by the plugin to respond to non-RT work. */
185 static LV2_Worker_Status
186 work_respond(LV2_Worker_Respond_Handle handle,
187              uint32_t                  size,
188              const void*               data)
189 {
190         LV2Plugin* plugin = (LV2Plugin*)handle;
191         if (plugin->session().engine().freewheeling()) {
192                 // Freewheeling, respond immediately in this (audio) thread
193                 return (LV2_Worker_Status)plugin->work_response(size, data);
194         } else {
195                 // Enqueue response for the worker
196                 return plugin->worker()->respond(size, data) ?
197                         LV2_WORKER_SUCCESS : LV2_WORKER_ERR_UNKNOWN;
198         }
199 }
200
201 /* log extension */
202
203 static int
204 log_vprintf(LV2_Log_Handle /*handle*/,
205             LV2_URID       type,
206             const char*    fmt,
207             va_list        args)
208 {
209         char* str = NULL;
210         const int ret = g_vasprintf(&str, fmt, args);
211         if (type == URIMap::instance().urids.log_Error) {
212                 error << str << endmsg;
213         } else if (type == URIMap::instance().urids.log_Warning) {
214                 warning << str << endmsg;
215         } else if (type == URIMap::instance().urids.log_Note) {
216                 info << str << endmsg;
217         }
218         // TODO: Toggleable log:Trace message support
219         return ret;
220 }
221
222 static int
223 log_printf(LV2_Log_Handle handle,
224            LV2_URID       type,
225            const char*    fmt, ...)
226 {
227         va_list args;
228         va_start(args, fmt);
229         const int ret = log_vprintf(handle, type, fmt, args);
230         va_end(args);
231         return ret;
232 }
233
234 struct LV2Plugin::Impl {
235         Impl() : plugin(0), ui(0), ui_type(0), name(0), author(0), instance(0)
236                , work_iface(0)
237                , state(0)
238         {}
239
240         /** Find the LV2 input port with the given designation.
241          * If found, bufptrs[port_index] will be set to bufptr.
242          */
243         const LilvPort* designated_input (const char* uri, void** bufptrs[], void** bufptr);
244
245         const LilvPlugin*           plugin;
246         const LilvUI*               ui;
247         const LilvNode*             ui_type;
248         LilvNode*                   name;
249         LilvNode*                   author;
250         LilvInstance*               instance;
251         const LV2_Worker_Interface* work_iface;
252         LilvState*                  state;
253         LV2_Atom_Forge              forge;
254         LV2_Atom_Forge              ui_forge;
255 };
256
257 LV2Plugin::LV2Plugin (AudioEngine& engine,
258                       Session&     session,
259                       const void*  c_plugin,
260                       framecnt_t   rate)
261         : Plugin (engine, session)
262         , Workee ()
263         , _impl(new Impl())
264         , _features(NULL)
265         , _worker(NULL)
266         , _insert_id("0")
267         , _patch_port_in_index((uint32_t)-1)
268         , _patch_port_out_index((uint32_t)-1)
269         , _uri_map(URIMap::instance())
270 {
271         init(c_plugin, rate);
272 }
273
274 LV2Plugin::LV2Plugin (const LV2Plugin& other)
275         : Plugin (other)
276         , Workee ()
277         , _impl(new Impl())
278         , _features(NULL)
279         , _worker(NULL)
280         , _insert_id(other._insert_id)
281         , _patch_port_in_index((uint32_t)-1)
282         , _patch_port_out_index((uint32_t)-1)
283         , _uri_map(URIMap::instance())
284 {
285         init(other._impl->plugin, other._sample_rate);
286
287         for (uint32_t i = 0; i < parameter_count(); ++i) {
288                 _control_data[i] = other._shadow_data[i];
289                 _shadow_data[i]  = other._shadow_data[i];
290         }
291 }
292
293 void
294 LV2Plugin::init(const void* c_plugin, framecnt_t rate)
295 {
296         DEBUG_TRACE(DEBUG::LV2, "init\n");
297
298         _impl->plugin           = (const LilvPlugin*)c_plugin;
299         _impl->ui               = NULL;
300         _impl->ui_type          = NULL;
301         _to_ui                  = NULL;
302         _from_ui                = NULL;
303         _control_data           = 0;
304         _shadow_data            = 0;
305         _atom_ev_buffers        = 0;
306         _ev_buffers             = 0;
307         _bpm_control_port       = 0;
308         _freewheel_control_port = 0;
309         _latency_control_port   = 0;
310         _next_cycle_start       = std::numeric_limits<framepos_t>::max();
311         _next_cycle_speed       = 1.0;
312         _block_length           = _engine.samples_per_cycle();
313         _seq_size               = _engine.raw_buffer_size(DataType::MIDI);
314         _state_version          = 0;
315         _was_activated          = false;
316         _has_state_interface    = false;
317
318         _instance_access_feature.URI = "http://lv2plug.in/ns/ext/instance-access";
319         _data_access_feature.URI     = "http://lv2plug.in/ns/ext/data-access";
320         _make_path_feature.URI       = LV2_STATE__makePath;
321         _log_feature.URI             = LV2_LOG__log;
322         _work_schedule_feature.URI   = LV2_WORKER__schedule;
323         _work_schedule_feature.data  = NULL;
324         _def_state_feature.URI       = LV2_STATE_PREFIX "loadDefaultState";  // Post LV2-1.2.0
325         _def_state_feature.data      = NULL;
326
327         const LilvPlugin* plugin = _impl->plugin;
328
329         LilvNode* state_iface_uri = lilv_new_uri(_world.world, LV2_STATE__interface);
330         LilvNode* state_uri       = lilv_new_uri(_world.world, LV2_STATE_URI);
331         _has_state_interface =
332                 // What plugins should have (lv2:extensionData state:Interface)
333                 lilv_plugin_has_extension_data(plugin, state_iface_uri)
334                 // What some outdated/incorrect ones have
335                 || lilv_plugin_has_feature(plugin, state_uri);
336         lilv_node_free(state_uri);
337         lilv_node_free(state_iface_uri);
338
339         _features    = (LV2_Feature**)calloc(11, sizeof(LV2_Feature*));
340         _features[0] = &_instance_access_feature;
341         _features[1] = &_data_access_feature;
342         _features[2] = &_make_path_feature;
343         _features[3] = _uri_map.uri_map_feature();
344         _features[4] = _uri_map.urid_map_feature();
345         _features[5] = _uri_map.urid_unmap_feature();
346         _features[6] = &_log_feature;
347
348         unsigned n_features = 7;
349 #ifdef HAVE_LV2_1_2_0
350         _features[n_features++] = &_def_state_feature;
351 #endif
352
353         lv2_atom_forge_init(&_impl->forge, _uri_map.urid_map());
354         lv2_atom_forge_init(&_impl->ui_forge, _uri_map.urid_map());
355
356 #ifdef HAVE_LV2_1_2_0
357         LV2_URID atom_Int = _uri_map.uri_to_id(LV2_ATOM__Int);
358         LV2_Options_Option options[] = {
359                 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__minBlockLength),
360                   sizeof(int32_t), atom_Int, &_block_length },
361                 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__maxBlockLength),
362                   sizeof(int32_t), atom_Int, &_block_length },
363                 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__sequenceSize),
364                   sizeof(int32_t), atom_Int, &_seq_size },
365                 { LV2_OPTIONS_INSTANCE, 0, 0, 0, 0, NULL }
366         };
367
368         _options_feature.URI    = LV2_OPTIONS__options;
369         _options_feature.data   = options;
370         _features[n_features++] = &_options_feature;
371 #endif
372
373         LV2_State_Make_Path* make_path = (LV2_State_Make_Path*)malloc(
374                 sizeof(LV2_State_Make_Path));
375         make_path->handle = this;
376         make_path->path = &lv2_state_make_path;
377         _make_path_feature.data = make_path;
378
379         LV2_Log_Log* log = (LV2_Log_Log*)malloc(sizeof(LV2_Log_Log));
380         log->handle  = this;
381         log->printf  = &log_printf;
382         log->vprintf = &log_vprintf;
383         _log_feature.data = log;
384
385         LilvNode* worker_schedule = lilv_new_uri(_world.world, LV2_WORKER__schedule);
386         if (lilv_plugin_has_feature(plugin, worker_schedule)) {
387                 LV2_Worker_Schedule* schedule = (LV2_Worker_Schedule*)malloc(
388                         sizeof(LV2_Worker_Schedule));
389                 size_t buf_size = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
390                 _worker                     = new Worker(this, buf_size);
391                 schedule->handle            = this;
392                 schedule->schedule_work     = work_schedule;
393                 _work_schedule_feature.data = schedule;
394                 _features[n_features++]     = &_work_schedule_feature;
395         }
396         lilv_node_free(worker_schedule);
397
398         _impl->instance = lilv_plugin_instantiate(plugin, rate, _features);
399         _impl->name     = lilv_plugin_get_name(plugin);
400         _impl->author   = lilv_plugin_get_author_name(plugin);
401
402         if (_impl->instance == 0) {
403                 error << _("LV2: Failed to instantiate plugin ") << uri() << endmsg;
404                 throw failed_constructor();
405         }
406
407         _instance_access_feature.data              = (void*)_impl->instance->lv2_handle;
408         _data_access_extension_data.extension_data = _impl->instance->lv2_descriptor->extension_data;
409         _data_access_feature.data                  = &_data_access_extension_data;
410
411         LilvNode* worker_iface_uri = lilv_new_uri(_world.world, LV2_WORKER__interface);
412         if (lilv_plugin_has_extension_data(plugin, worker_iface_uri)) {
413                 _impl->work_iface = (const LV2_Worker_Interface*)extension_data(
414                         LV2_WORKER__interface);
415         }
416         lilv_node_free(worker_iface_uri);
417
418         if (lilv_plugin_has_feature(plugin, _world.lv2_inPlaceBroken)) {
419                 error << string_compose(
420                     _("LV2: \"%1\" cannot be used, since it cannot do inplace processing"),
421                     lilv_node_as_string(_impl->name)) << endmsg;
422                 lilv_node_free(_impl->name);
423                 lilv_node_free(_impl->author);
424                 throw failed_constructor();
425         }
426
427 #ifdef HAVE_LILV_0_16_0
428         // Load default state
429         LilvState* state = lilv_state_new_from_world(
430                 _world.world, _uri_map.urid_map(), lilv_plugin_get_uri(_impl->plugin));
431         if (state && _has_state_interface) {
432                 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
433         }
434 #endif
435
436         _sample_rate = rate;
437
438         const uint32_t num_ports = this->num_ports();
439         for (uint32_t i = 0; i < num_ports; ++i) {
440                 const LilvPort* port  = lilv_plugin_get_port_by_index(_impl->plugin, i);
441                 PortFlags       flags = 0;
442                 size_t          minimumSize = 0;
443
444                 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_OutputPort)) {
445                         flags |= PORT_OUTPUT;
446                 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_InputPort)) {
447                         flags |= PORT_INPUT;
448                 } else {
449                         error << string_compose(
450                                 "LV2: \"%1\" port %2 is neither input nor output",
451                                 lilv_node_as_string(_impl->name), i) << endmsg;
452                         throw failed_constructor();
453                 }
454
455                 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_ControlPort)) {
456                         flags |= PORT_CONTROL;
457                 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_AudioPort)) {
458                         flags |= PORT_AUDIO;
459                 } else if (lilv_port_is_a(_impl->plugin, port, _world.ev_EventPort)) {
460                         flags |= PORT_EVENT;
461                         flags |= PORT_MIDI;  // We assume old event API ports are for MIDI
462                 } else if (lilv_port_is_a(_impl->plugin, port, _world.atom_AtomPort)) {
463                         LilvNodes* buffer_types = lilv_port_get_value(
464                                 _impl->plugin, port, _world.atom_bufferType);
465                         LilvNodes* atom_supports = lilv_port_get_value(
466                                 _impl->plugin, port, _world.atom_supports);
467
468                         if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)) {
469                                 flags |= PORT_SEQUENCE;
470                                 if (lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
471                                         flags |= PORT_MIDI;
472                                 }
473                                 if (lilv_nodes_contains(atom_supports, _world.time_Position)) {
474                                         flags |= PORT_POSITION;
475                                 }
476                                 if (lilv_nodes_contains(atom_supports, _world.patch_Message)) {
477                                         flags |= PORT_PATCHMSG;
478                                         if (flags & PORT_INPUT) {
479                                                 _patch_port_in_index = i;
480                                         } else {
481                                                 _patch_port_out_index = i;
482                                         }
483                                 }
484                         }
485                         LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
486                         LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
487                         if (min_size && lilv_node_is_int(min_size)) {
488                                 minimumSize = lilv_node_as_int(min_size);
489                         }
490                         lilv_nodes_free(min_size_v);
491                         lilv_nodes_free(buffer_types);
492                         lilv_nodes_free(atom_supports);
493                 } else {
494                         error << string_compose(
495                                 "LV2: \"%1\" port %2 has no known data type",
496                                 lilv_node_as_string(_impl->name), i) << endmsg;
497                         throw failed_constructor();
498                 }
499
500                 _port_flags.push_back(flags);
501                 _port_minimumSize.push_back(minimumSize);
502         }
503
504         _control_data = new float[num_ports];
505         _shadow_data  = new float[num_ports];
506         _defaults     = new float[num_ports];
507         _ev_buffers   = new LV2_Evbuf*[num_ports];
508         memset(_ev_buffers, 0, sizeof(LV2_Evbuf*) * num_ports);
509
510         const bool     latent        = lilv_plugin_has_latency(plugin);
511         const uint32_t latency_index = (latent)
512                 ? lilv_plugin_get_latency_port_index(plugin)
513                 : 0;
514
515         // Build an array of pointers to special parameter buffers
516         void*** params = new void**[num_ports];
517         for (uint32_t i = 0; i < num_ports; ++i) {
518                 params[i] = NULL;
519         }
520         _impl->designated_input (LV2_TIME__beatsPerMinute, params, (void**)&_bpm_control_port);
521         _impl->designated_input (LV2_CORE__freeWheeling, params, (void**)&_freewheel_control_port);
522
523         for (uint32_t i = 0; i < num_ports; ++i) {
524                 const LilvPort* port = lilv_plugin_get_port_by_index(plugin, i);
525                 const LilvNode* sym  = lilv_port_get_symbol(plugin, port);
526
527                 // Store index in map so we can look up index by symbol
528                 _port_indices.insert(std::make_pair(lilv_node_as_string(sym), i));
529
530                 // Get range and default value if applicable
531                 if (parameter_is_control(i)) {
532                         LilvNode* def;
533                         lilv_port_get_range(plugin, port, &def, NULL, NULL);
534                         _defaults[i] = def ? lilv_node_as_float(def) : 0.0f;
535                         if (lilv_port_has_property (plugin, port, _world.lv2_sampleRate)) {
536                                 _defaults[i] *= _session.frame_rate ();
537                         }
538                         lilv_node_free(def);
539
540                         lilv_instance_connect_port(_impl->instance, i, &_control_data[i]);
541
542                         if (latent && i == latency_index) {
543                                 _latency_control_port  = &_control_data[i];
544                                 *_latency_control_port = 0;
545                         }
546
547                         if (parameter_is_input(i)) {
548                                 _shadow_data[i] = default_value(i);
549                                 if (params[i]) {
550                                         *params[i] = (void*)&_shadow_data[i];
551                                 }
552                         }
553                 } else {
554                         _defaults[i] = 0.0f;
555                 }
556         }
557
558         delete[] params;
559
560         LilvUIs* uis = lilv_plugin_get_uis(plugin);
561         if (lilv_uis_size(uis) > 0) {
562 #ifdef HAVE_SUIL
563                 // Look for embeddable UI
564                 LILV_FOREACH(uis, u, uis) {
565                         const LilvUI*   this_ui      = lilv_uis_get(uis, u);
566                         const LilvNode* this_ui_type = NULL;
567                         if (lilv_ui_is_supported(this_ui,
568                                                  suil_ui_supported,
569                                                  _world.ui_GtkUI,
570                                                  &this_ui_type)) {
571                                 // TODO: Multiple UI support
572                                 _impl->ui      = this_ui;
573                                 _impl->ui_type = this_ui_type;
574                                 break;
575                         }
576                 }
577 #else
578                 // Look for Gtk native UI
579                 LILV_FOREACH(uis, i, uis) {
580                         const LilvUI* ui = lilv_uis_get(uis, i);
581                         if (lilv_ui_is_a(ui, _world.ui_GtkUI)) {
582                                 _impl->ui      = ui;
583                                 _impl->ui_type = _world.ui_GtkUI;
584                                 break;
585                         }
586                 }
587 #endif
588
589                 // If Gtk UI is not available, try to find external UI
590                 if (!_impl->ui) {
591                         LILV_FOREACH(uis, i, uis) {
592                                 const LilvUI* ui = lilv_uis_get(uis, i);
593                                 if (lilv_ui_is_a(ui, _world.ui_externalkx)) {
594                                         _impl->ui      = ui;
595                                         _impl->ui_type = _world.ui_external;
596                                         break;
597                                 }
598                                 if (lilv_ui_is_a(ui, _world.ui_external)) {
599                                         _impl->ui      = ui;
600                                         _impl->ui_type = _world.ui_external;
601                                 }
602                         }
603                 }
604         }
605
606         load_supported_properties(_property_descriptors);
607         allocate_atom_event_buffers();
608         latency_compute_run();
609 }
610
611 LV2Plugin::~LV2Plugin ()
612 {
613         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 destroy\n", name()));
614
615         deactivate();
616         cleanup();
617
618         lilv_instance_free(_impl->instance);
619         lilv_node_free(_impl->name);
620         lilv_node_free(_impl->author);
621
622         free(_features);
623         free(_make_path_feature.data);
624         free(_work_schedule_feature.data);
625
626         delete _to_ui;
627         delete _from_ui;
628         delete _worker;
629
630         if (_atom_ev_buffers) {
631                 LV2_Evbuf**  b = _atom_ev_buffers;
632                 while (*b) {
633                         free(*b);
634                         b++;
635                 }
636                 free(_atom_ev_buffers);
637         }
638
639         delete [] _control_data;
640         delete [] _shadow_data;
641         delete [] _ev_buffers;
642 }
643
644 bool
645 LV2Plugin::is_external_ui() const
646 {
647         if (!_impl->ui) {
648                 return false;
649         }
650         return lilv_ui_is_a(_impl->ui, _world.ui_external) || lilv_ui_is_a(_impl->ui, _world.ui_externalkx);
651 }
652
653 bool
654 LV2Plugin::is_external_kx() const
655 {
656         if (!_impl->ui) {
657                 return false;
658         }
659         return lilv_ui_is_a(_impl->ui, _world.ui_externalkx);
660 }
661
662 bool
663 LV2Plugin::ui_is_resizable () const
664 {
665         const LilvNode* s   = lilv_ui_get_uri(_impl->ui);
666         LilvNode*       p   = lilv_new_uri(_world.world, LV2_CORE__optionalFeature);
667         LilvNode*       fs  = lilv_new_uri(_world.world, LV2_UI__fixedSize);
668         LilvNode*       nrs = lilv_new_uri(_world.world, LV2_UI__noUserResize);
669
670         LilvNodes* fs_matches = lilv_world_find_nodes(_world.world, s, p, fs);
671         LilvNodes* nrs_matches = lilv_world_find_nodes(_world.world, s, p, nrs);
672
673         lilv_nodes_free(nrs_matches);
674         lilv_nodes_free(fs_matches);
675         lilv_node_free(nrs);
676         lilv_node_free(fs);
677         lilv_node_free(p);
678
679         return !fs_matches && !nrs_matches;
680 }
681
682 string
683 LV2Plugin::unique_id() const
684 {
685         return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
686 }
687
688 const char*
689 LV2Plugin::uri() const
690 {
691         return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
692 }
693
694 const char*
695 LV2Plugin::label() const
696 {
697         return lilv_node_as_string(_impl->name);
698 }
699
700 const char*
701 LV2Plugin::name() const
702 {
703         return lilv_node_as_string(_impl->name);
704 }
705
706 const char*
707 LV2Plugin::maker() const
708 {
709         return _impl->author ? lilv_node_as_string (_impl->author) : "Unknown";
710 }
711
712 uint32_t
713 LV2Plugin::num_ports() const
714 {
715         return lilv_plugin_get_num_ports(_impl->plugin);
716 }
717
718 uint32_t
719 LV2Plugin::parameter_count() const
720 {
721         return lilv_plugin_get_num_ports(_impl->plugin);
722 }
723
724 float
725 LV2Plugin::default_value(uint32_t port)
726 {
727         return _defaults[port];
728 }
729
730 const char*
731 LV2Plugin::port_symbol(uint32_t index) const
732 {
733         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, index);
734         if (!port) {
735                 error << name() << ": Invalid port index " << index << endmsg;
736         }
737
738         const LilvNode* sym = lilv_port_get_symbol(_impl->plugin, port);
739         return lilv_node_as_string(sym);
740 }
741
742 uint32_t
743 LV2Plugin::port_index (const char* symbol) const
744 {
745         const map<string, uint32_t>::const_iterator i = _port_indices.find(symbol);
746         if (i != _port_indices.end()) {
747                 return  i->second;
748         } else {
749                 warning << string_compose(_("LV2: Unknown port %1"), symbol) << endmsg;
750                 return (uint32_t)-1;
751         }
752 }
753
754 void
755 LV2Plugin::set_parameter(uint32_t which, float val)
756 {
757         DEBUG_TRACE(DEBUG::LV2, string_compose(
758                             "%1 set parameter %2 to %3\n", name(), which, val));
759
760         if (which < lilv_plugin_get_num_ports(_impl->plugin)) {
761                 if (get_parameter (which) == val) {
762                         return;
763                 }
764
765                 _shadow_data[which] = val;
766         } else {
767                 warning << string_compose(
768                     _("Illegal parameter number used with plugin \"%1\". "
769                       "This is a bug in either %2 or the LV2 plugin <%3>"),
770                     name(), PROGRAM_NAME, unique_id()) << endmsg;
771         }
772
773         Plugin::set_parameter(which, val);
774 }
775
776 float
777 LV2Plugin::get_parameter(uint32_t which) const
778 {
779         if (parameter_is_input(which)) {
780                 return (float)_shadow_data[which];
781         } else {
782                 return (float)_control_data[which];
783         }
784         return 0.0f;
785 }
786
787 std::string
788 LV2Plugin::get_docs() const
789 {
790         LilvNodes* comments = lilv_plugin_get_value(_impl->plugin, _world.rdfs_comment);
791         if (comments) {
792                 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
793                 lilv_nodes_free(comments);
794                 return docs;
795         }
796
797         return "";
798 }
799
800 std::string
801 LV2Plugin::get_parameter_docs(uint32_t which) const
802 {
803         LilvNodes* comments = lilv_port_get_value(
804                 _impl->plugin,
805                 lilv_plugin_get_port_by_index(_impl->plugin, which),
806                 _world.rdfs_comment);
807
808         if (comments) {
809                 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
810                 lilv_nodes_free(comments);
811                 return docs;
812         }
813
814         return "";
815 }
816
817 uint32_t
818 LV2Plugin::nth_parameter(uint32_t n, bool& ok) const
819 {
820         ok = false;
821         for (uint32_t c = 0, x = 0; x < lilv_plugin_get_num_ports(_impl->plugin); ++x) {
822                 if (parameter_is_control(x)) {
823                         if (c++ == n) {
824                                 ok = true;
825                                 return x;
826                         }
827                 }
828         }
829
830         return 0;
831 }
832
833 const void*
834 LV2Plugin::extension_data(const char* uri) const
835 {
836         return lilv_instance_get_extension_data(_impl->instance, uri);
837 }
838
839 const void*
840 LV2Plugin::c_plugin()
841 {
842         return _impl->plugin;
843 }
844
845 const void*
846 LV2Plugin::c_ui()
847 {
848         return (const void*)_impl->ui;
849 }
850
851 const void*
852 LV2Plugin::c_ui_type()
853 {
854         return (const void*)_impl->ui_type;
855 }
856
857 /** Directory for all plugin state. */
858 const std::string
859 LV2Plugin::plugin_dir() const
860 {
861         return Glib::build_filename(_session.plugins_dir(), _insert_id.to_s());
862 }
863
864 /** Directory for files created by the plugin (except during save). */
865 const std::string
866 LV2Plugin::scratch_dir() const
867 {
868         return Glib::build_filename(plugin_dir(), "scratch");
869 }
870
871 /** Directory for snapshots of files in the scratch directory. */
872 const std::string
873 LV2Plugin::file_dir() const
874 {
875         return Glib::build_filename(plugin_dir(), "files");
876 }
877
878 /** Directory to save state snapshot version @c num into. */
879 const std::string
880 LV2Plugin::state_dir(unsigned num) const
881 {
882         return Glib::build_filename(plugin_dir(), string_compose("state%1", num));
883 }
884
885 /** Implementation of state:makePath for files created at instantiation time.
886  * Note this is not used for files created at save time (Lilv deals with that).
887  */
888 char*
889 LV2Plugin::lv2_state_make_path(LV2_State_Make_Path_Handle handle,
890                                const char*                path)
891 {
892         LV2Plugin* me = (LV2Plugin*)handle;
893         if (me->_insert_id == PBD::ID("0")) {
894                 warning << string_compose(
895                         "File path \"%1\" requested but LV2 %2 has no insert ID",
896                         path, me->name()) << endmsg;
897                 return g_strdup(path);
898         }
899
900         const std::string abs_path = Glib::build_filename(me->scratch_dir(), path);
901         const std::string dirname  = Glib::path_get_dirname(abs_path);
902         g_mkdir_with_parents(dirname.c_str(), 0744);
903
904         DEBUG_TRACE(DEBUG::LV2, string_compose("new file path %1 => %2\n",
905                                                path, abs_path));
906
907         return g_strndup(abs_path.c_str(), abs_path.length());
908 }
909
910 void
911 LV2Plugin::add_state(XMLNode* root) const
912 {
913         assert(_insert_id != PBD::ID("0"));
914
915         XMLNode*    child;
916         char        buf[16];
917         LocaleGuard lg(X_("C"));
918
919         for (uint32_t i = 0; i < parameter_count(); ++i) {
920                 if (parameter_is_input(i) && parameter_is_control(i)) {
921                         child = new XMLNode("Port");
922                         child->add_property("symbol", port_symbol(i));
923                         snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
924                         child->add_property("value", string(buf));
925                         root->add_child_nocopy(*child);
926                 }
927         }
928
929         if (_has_state_interface) {
930                 // Provisionally increment state version and create directory
931                 const std::string new_dir = state_dir(++_state_version);
932                 g_mkdir_with_parents(new_dir.c_str(), 0744);
933
934                 LilvState* state = lilv_state_new_from_instance(
935                         _impl->plugin,
936                         _impl->instance,
937                         _uri_map.urid_map(),
938                         scratch_dir().c_str(),
939                         file_dir().c_str(),
940                         _session.externals_dir().c_str(),
941                         new_dir.c_str(),
942                         NULL,
943                         const_cast<LV2Plugin*>(this),
944                         0,
945                         NULL);
946
947                 if (!_impl->state || !lilv_state_equals(state, _impl->state)) {
948                         lilv_state_save(_world.world,
949                                         _uri_map.urid_map(),
950                                         _uri_map.urid_unmap(),
951                                         state,
952                                         NULL,
953                                         new_dir.c_str(),
954                                         "state.ttl");
955
956                         lilv_state_free(_impl->state);
957                         _impl->state = state;
958                 } else {
959                         // State is identical, decrement version and nuke directory
960                         lilv_state_free(state);
961                         PBD::remove_directory(new_dir);
962                         --_state_version;
963                 }
964
965                 root->add_property("state-dir", string_compose("state%1", _state_version));
966         }
967 }
968
969 // TODO: Once we can rely on lilv 0.16.0, lilv_world_get can replace this
970 static LilvNode*
971 get_value(LilvWorld* world, const LilvNode* subject, const LilvNode* predicate)
972 {
973         LilvNodes* vs = lilv_world_find_nodes(world, subject, predicate, NULL);
974         if (vs) {
975                 LilvNode* node = lilv_node_duplicate(lilv_nodes_get_first(vs));
976                 lilv_nodes_free(vs);
977                 return node;
978         }
979         return NULL;
980 }
981
982 void
983 LV2Plugin::find_presets()
984 {
985         LilvNode* lv2_appliesTo = lilv_new_uri(_world.world, LV2_CORE__appliesTo);
986         LilvNode* pset_Preset   = lilv_new_uri(_world.world, LV2_PRESETS__Preset);
987         LilvNode* rdfs_label    = lilv_new_uri(_world.world, LILV_NS_RDFS "label");
988
989         LilvNodes* presets = lilv_plugin_get_related(_impl->plugin, pset_Preset);
990         LILV_FOREACH(nodes, i, presets) {
991                 const LilvNode* preset = lilv_nodes_get(presets, i);
992                 lilv_world_load_resource(_world.world, preset);
993                 LilvNode* name = get_value(_world.world, preset, rdfs_label);
994                 if (name) {
995                         _presets.insert(std::make_pair(lilv_node_as_string(preset),
996                                                        Plugin::PresetRecord(
997                                                                lilv_node_as_string(preset),
998                                                                lilv_node_as_string(name))));
999                         lilv_node_free(name);
1000                 } else {
1001                         warning << string_compose(
1002                             _("Plugin \"%1\" preset \"%2\" is missing a label\n"),
1003                             lilv_node_as_string(lilv_plugin_get_uri(_impl->plugin)),
1004                             lilv_node_as_string(preset)) << endmsg;
1005                 }
1006         }
1007         lilv_nodes_free(presets);
1008
1009         lilv_node_free(rdfs_label);
1010         lilv_node_free(pset_Preset);
1011         lilv_node_free(lv2_appliesTo);
1012 }
1013
1014 static void
1015 set_port_value(const char* port_symbol,
1016                void*       user_data,
1017                const void* value,
1018                uint32_t    /*size*/,
1019                uint32_t    type)
1020 {
1021         LV2Plugin* self = (LV2Plugin*)user_data;
1022         if (type != 0 && type != URIMap::instance().urids.atom_Float) {
1023                 return;  // TODO: Support non-float ports
1024         }
1025
1026         const uint32_t port_index = self->port_index(port_symbol);
1027         if (port_index != (uint32_t)-1) {
1028                 self->set_parameter(port_index, *(const float*)value);
1029         }
1030 }
1031
1032 bool
1033 LV2Plugin::load_preset(PresetRecord r)
1034 {
1035         LilvWorld* world = _world.world;
1036         LilvNode*  pset  = lilv_new_uri(world, r.uri.c_str());
1037         LilvState* state = lilv_state_new_from_world(world, _uri_map.urid_map(), pset);
1038
1039         if (state) {
1040                 lilv_state_restore(state, _impl->instance, set_port_value, this, 0, NULL);
1041                 lilv_state_free(state);
1042                 Plugin::load_preset(r);
1043         }
1044
1045         lilv_node_free(pset);
1046         return state;
1047 }
1048
1049 const void*
1050 ARDOUR::lv2plugin_get_port_value(const char* port_symbol,
1051                                  void*       user_data,
1052                                  uint32_t*   size,
1053                                  uint32_t*   type)
1054 {
1055         LV2Plugin *plugin = (LV2Plugin *) user_data;
1056
1057         uint32_t index = plugin->port_index(port_symbol);
1058         if (index != (uint32_t) -1) {
1059                 if (plugin->parameter_is_input(index) && plugin->parameter_is_control(index)) {
1060                         float *value;
1061                         *size = sizeof(float);
1062                         *type = plugin->_uri_map.uri_to_id(LV2_ATOM__Float);
1063                         value = &plugin->_shadow_data[index];
1064
1065                         return value;
1066                 }
1067         }
1068
1069         *size = *type = 0;
1070         return NULL;
1071 }
1072
1073
1074 std::string
1075 LV2Plugin::do_save_preset(string name)
1076 {
1077         LilvNode*    plug_name = lilv_plugin_get_name(_impl->plugin);
1078         const string prefix    = legalize_for_uri(lilv_node_as_string(plug_name));
1079         const string base_name = legalize_for_uri(name);
1080         const string file_name = base_name + ".ttl";
1081         const string bundle    = Glib::build_filename(
1082                 Glib::get_home_dir(),
1083                 Glib::build_filename(".lv2", prefix + "_" + base_name + ".lv2"));
1084
1085         LilvState* state = lilv_state_new_from_instance(
1086                 _impl->plugin,
1087                 _impl->instance,
1088                 _uri_map.urid_map(),
1089                 scratch_dir().c_str(),                   // file_dir
1090                 bundle.c_str(),                          // copy_dir
1091                 bundle.c_str(),                          // link_dir
1092                 bundle.c_str(),                          // save_dir
1093                 lv2plugin_get_port_value,                // get_value
1094                 (void*)this,                             // user_data
1095                 LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE,  // flags
1096                 _features                                // features
1097         );
1098
1099         lilv_state_set_label(state, name.c_str());
1100         lilv_state_save(
1101                 _world.world,           // world
1102                 _uri_map.urid_map(),    // map
1103                 _uri_map.urid_unmap(),  // unmap
1104                 state,                  // state
1105                 NULL,                   // uri (NULL = use file URI)
1106                 bundle.c_str(),         // dir
1107                 file_name.c_str()       // filename
1108         );
1109
1110         lilv_state_free(state);
1111
1112         std::string uri = Glib::filename_to_uri(Glib::build_filename(bundle, file_name));
1113         LilvNode *node_bundle = lilv_new_uri(_world.world, Glib::filename_to_uri(Glib::build_filename(bundle, "/")).c_str());
1114         LilvNode *node_preset = lilv_new_uri(_world.world, uri.c_str());
1115 #ifdef HAVE_LILV_0_21_3
1116         lilv_world_unload_resource(_world.world, node_preset);
1117         lilv_world_unload_bundle(_world.world, node_bundle);
1118 #endif
1119         lilv_world_load_bundle(_world.world, node_bundle);
1120         lilv_world_load_resource(_world.world, node_preset);
1121         lilv_node_free(node_bundle);
1122         lilv_node_free(node_preset);
1123         lilv_node_free(plug_name);
1124         return uri;
1125 }
1126
1127 void
1128 LV2Plugin::do_remove_preset(string name)
1129 {
1130 #ifdef HAVE_LILV_0_21_3
1131         /* Look up preset record by label (FIXME: ick, label as ID) */
1132         const PresetRecord* r = preset_by_label(name);
1133         if (!r) {
1134                 return;
1135         }
1136
1137         /* Load a LilvState for the preset. */
1138         LilvWorld* world = _world.world;
1139         LilvNode*  pset  = lilv_new_uri(world, r->uri.c_str());
1140         LilvState* state = lilv_state_new_from_world(world, _uri_map.urid_map(), pset);
1141         if (!state) {
1142                 lilv_node_free(pset);
1143                 return;
1144         }
1145
1146         /* Unload preset from world. */
1147         lilv_world_unload_resource(world, pset);
1148
1149         /* Delete it from the file system.  This will remove the preset file and the entry
1150            from the manifest.  If this results in an empty manifest (i.e. the
1151            preset is the only thing in the bundle), then the bundle is removed. */
1152         lilv_state_delete(world, state);
1153
1154         lilv_state_free(state);
1155         lilv_node_free(pset);
1156 #endif
1157         /* Without lilv_state_delete(), we could delete the preset file, but this
1158            would leave a broken bundle/manifest around, so the preset would still
1159            be visible, but broken.  Naively deleting a bundle is too dangerous, so
1160            we simply do not support preset deletion with older Lilv */
1161 }
1162
1163 bool
1164 LV2Plugin::has_editor() const
1165 {
1166         return _impl->ui != NULL;
1167 }
1168
1169 bool
1170 LV2Plugin::has_message_output() const
1171 {
1172         for (uint32_t i = 0; i < num_ports(); ++i) {
1173                 if ((_port_flags[i] & PORT_SEQUENCE) &&
1174                     (_port_flags[i] & PORT_OUTPUT)) {
1175                         return true;
1176                 }
1177         }
1178         return false;
1179 }
1180
1181 bool
1182 LV2Plugin::write_to(RingBuffer<uint8_t>* dest,
1183                     uint32_t             index,
1184                     uint32_t             protocol,
1185                     uint32_t             size,
1186                     const uint8_t*       body)
1187 {
1188         const uint32_t  buf_size = sizeof(UIMessage) + size;
1189         vector<uint8_t> buf(buf_size);
1190
1191         UIMessage* msg = (UIMessage*)&buf[0];
1192         msg->index    = index;
1193         msg->protocol = protocol;
1194         msg->size     = size;
1195         memcpy(msg + 1, body, size);
1196
1197         return (dest->write(&buf[0], buf_size) == buf_size);
1198 }
1199
1200 bool
1201 LV2Plugin::write_from_ui(uint32_t       index,
1202                          uint32_t       protocol,
1203                          uint32_t       size,
1204                          const uint8_t* body)
1205 {
1206         if (!_from_ui) {
1207                 size_t rbs = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
1208                 /* buffer data communication from plugin UI to plugin instance.
1209                  * this buffer needs to potentially hold
1210                  *   (port's minimumSize) * (audio-periods) / (UI-periods)
1211                  * bytes.
1212                  *
1213                  *  e.g 48kSPS / 128fpp -> audio-periods = 375 Hz
1214                  *  ui-periods = 25 Hz (SuperRapidScreenUpdate)
1215                  *  default minimumSize = 32K (see LV2Plugin::allocate_atom_event_buffers()
1216                  *
1217                  * it is NOT safe to overflow (msg.size will be misinterpreted)
1218                  */
1219                 uint32_t bufsiz = 32768;
1220                 if (_atom_ev_buffers && _atom_ev_buffers[0]) {
1221                         bufsiz =  lv2_evbuf_get_capacity(_atom_ev_buffers[0]);
1222                 }
1223                 rbs = max((size_t) bufsiz * 8, rbs);
1224                 _from_ui = new RingBuffer<uint8_t>(rbs);
1225         }
1226
1227         if (!write_to(_from_ui, index, protocol, size, body)) {
1228                 error << "Error writing from UI to plugin" << endmsg;
1229                 return false;
1230         }
1231         return true;
1232 }
1233
1234 bool
1235 LV2Plugin::write_to_ui(uint32_t       index,
1236                        uint32_t       protocol,
1237                        uint32_t       size,
1238                        const uint8_t* body)
1239 {
1240         if (!write_to(_to_ui, index, protocol, size, body)) {
1241                 error << "Error writing from plugin to UI" << endmsg;
1242                 return false;
1243         }
1244         return true;
1245 }
1246
1247 static void
1248 forge_variant(LV2_Atom_Forge* forge, const Variant& value)
1249 {
1250         switch (value.type()) {
1251         case Variant::NOTHING:
1252                 break;
1253         case Variant::BEATS:
1254                 // No atom type for this, just forge a double
1255                 lv2_atom_forge_double(forge, value.get_beats().to_double());
1256                 break;
1257         case Variant::BOOL:
1258                 lv2_atom_forge_bool(forge, value.get_bool());
1259                 break;
1260         case Variant::DOUBLE:
1261                 lv2_atom_forge_double(forge, value.get_double());
1262                 break;
1263         case Variant::FLOAT:
1264                 lv2_atom_forge_float(forge, value.get_float());
1265                 break;
1266         case Variant::INT:
1267                 lv2_atom_forge_int(forge, value.get_int());
1268                 break;
1269         case Variant::LONG:
1270                 lv2_atom_forge_long(forge, value.get_long());
1271                 break;
1272         case Variant::PATH:
1273                 lv2_atom_forge_path(
1274                         forge, value.get_path().c_str(), value.get_path().size());
1275                 break;
1276         case Variant::STRING:
1277                 lv2_atom_forge_string(
1278                         forge, value.get_string().c_str(), value.get_string().size());
1279                 break;
1280         case Variant::URI:
1281                 lv2_atom_forge_uri(
1282                         forge, value.get_uri().c_str(), value.get_uri().size());
1283                 break;
1284         }
1285 }
1286
1287 /** Get a variant type from a URI, return false iff no match found. */
1288 static bool
1289 uri_to_variant_type(const std::string& uri, Variant::Type& type)
1290 {
1291         if (uri == LV2_ATOM__Bool) {
1292                 type = Variant::BOOL;
1293         } else if (uri == LV2_ATOM__Double) {
1294                 type = Variant::DOUBLE;
1295         } else if (uri == LV2_ATOM__Float) {
1296                 type = Variant::FLOAT;
1297         } else if (uri == LV2_ATOM__Int) {
1298                 type = Variant::INT;
1299         } else if (uri == LV2_ATOM__Long) {
1300                 type = Variant::LONG;
1301         } else if (uri == LV2_ATOM__Path) {
1302                 type = Variant::PATH;
1303         } else if (uri == LV2_ATOM__String) {
1304                 type = Variant::STRING;
1305         } else if (uri == LV2_ATOM__URI) {
1306                 type = Variant::URI;
1307         } else {
1308                 return false;
1309         }
1310         return true;
1311 }
1312
1313 void
1314 LV2Plugin::set_property(uint32_t key, const Variant& value)
1315 {
1316         if (_patch_port_in_index == (uint32_t)-1) {
1317                 error << "LV2: set_property called with unset patch_port_in_index" << endmsg;
1318                 return;
1319         } else if (value.type() == Variant::NOTHING) {
1320                 error << "LV2: set_property called with void value" << endmsg;
1321                 return;
1322         }
1323
1324         // Set up forge to write to temporary buffer on the stack
1325         LV2_Atom_Forge*      forge = &_impl->ui_forge;
1326         LV2_Atom_Forge_Frame frame;
1327         uint8_t              buf[PATH_MAX];  // Ought to be enough for anyone...
1328
1329         lv2_atom_forge_set_buffer(forge, buf, sizeof(buf));
1330
1331         // Serialize patch:Set message to set property
1332 #ifdef HAVE_LV2_1_10_0
1333         lv2_atom_forge_object(forge, &frame, 1, _uri_map.urids.patch_Set);
1334         lv2_atom_forge_key(forge, _uri_map.urids.patch_property);
1335         lv2_atom_forge_urid(forge, key);
1336         lv2_atom_forge_key(forge, _uri_map.urids.patch_value);
1337 #else
1338         lv2_atom_forge_blank(forge, &frame, 1, _uri_map.urids.patch_Set);
1339         lv2_atom_forge_property_head(forge, _uri_map.urids.patch_property, 0);
1340         lv2_atom_forge_urid(forge, key);
1341         lv2_atom_forge_property_head(forge, _uri_map.urids.patch_value, 0);
1342 #endif
1343
1344         forge_variant(forge, value);
1345
1346         // Write message to UI=>Plugin ring
1347         const LV2_Atom* const atom = (const LV2_Atom*)buf;
1348         write_from_ui(_patch_port_in_index,
1349                       _uri_map.urids.atom_eventTransfer,
1350                       lv2_atom_total_size(atom),
1351                       (const uint8_t*)atom);
1352 }
1353
1354 const ParameterDescriptor&
1355 LV2Plugin::get_property_descriptor(uint32_t id) const
1356 {
1357         PropertyDescriptors::const_iterator p = _property_descriptors.find(id);
1358         if (p != _property_descriptors.end()) {
1359                 return p->second;
1360         }
1361         return Plugin::get_property_descriptor(id);
1362 }
1363
1364 static void
1365 load_parameter_descriptor_units(LilvWorld* lworld, ParameterDescriptor& desc, const LilvNodes* units)
1366 {
1367         if (lilv_nodes_contains(units, _world.units_midiNote)) {
1368                 desc.unit = ParameterDescriptor::MIDI_NOTE;
1369         } else if (lilv_nodes_contains(units, _world.units_db)) {
1370                 desc.unit = ParameterDescriptor::DB;
1371         } else if (lilv_nodes_contains(units, _world.units_hz)) {
1372                 desc.unit = ParameterDescriptor::HZ;
1373         }
1374         if (lilv_nodes_size(units) > 0) {
1375                 const LilvNode* unit = lilv_nodes_get_first(units);
1376                 LilvNode* render = get_value(lworld, unit, _world.units_render);
1377                 if (render) {
1378                         desc.print_fmt = lilv_node_as_string(render);
1379                         lilv_node_free(render);
1380                 }
1381         }
1382 }
1383
1384 static void
1385 load_parameter_descriptor(LV2World&            world,
1386                           ParameterDescriptor& desc,
1387                           Variant::Type        datatype,
1388                           const LilvNode*      subject)
1389 {
1390         LilvWorld* lworld  = _world.world;
1391         LilvNode*  label   = get_value(lworld, subject, _world.rdfs_label);
1392         LilvNode*  def     = get_value(lworld, subject, _world.lv2_default);
1393         LilvNode*  minimum = get_value(lworld, subject, _world.lv2_minimum);
1394         LilvNode*  maximum = get_value(lworld, subject, _world.lv2_maximum);
1395         LilvNodes* units   = lilv_world_find_nodes(lworld, subject, _world.units_unit, NULL);
1396         if (label) {
1397                 desc.label = lilv_node_as_string(label);
1398         }
1399         if (def && lilv_node_is_float(def)) {
1400                 desc.normal = lilv_node_as_float(def);
1401         }
1402         if (minimum && lilv_node_is_float(minimum)) {
1403                 desc.lower = lilv_node_as_float(minimum);
1404         }
1405         if (maximum && lilv_node_is_float(maximum)) {
1406                 desc.upper = lilv_node_as_float(maximum);
1407         }
1408         load_parameter_descriptor_units(lworld, desc, units);
1409         desc.datatype      = datatype;
1410         desc.toggled      |= datatype == Variant::BOOL;
1411         desc.integer_step |= datatype == Variant::INT || datatype == Variant::LONG;
1412         desc.update_steps();
1413
1414         lilv_nodes_free(units);
1415         lilv_node_free(label);
1416         lilv_node_free(def);
1417         lilv_node_free(minimum);
1418         lilv_node_free(maximum);
1419 }
1420
1421 void
1422 LV2Plugin::load_supported_properties(PropertyDescriptors& descs)
1423 {
1424         LilvWorld*       lworld     = _world.world;
1425         const LilvNode*  subject    = lilv_plugin_get_uri(_impl->plugin);
1426         LilvNodes*       properties = lilv_world_find_nodes(
1427                 lworld, subject, _world.patch_writable, NULL);
1428         LILV_FOREACH(nodes, p, properties) {
1429                 // Get label and range
1430                 const LilvNode* prop  = lilv_nodes_get(properties, p);
1431                 LilvNode*       range = get_value(lworld, prop, _world.rdfs_range);
1432                 if (!range) {
1433                         warning << string_compose(_("LV2: property <%1> has no range datatype, ignoring"),
1434                                                   lilv_node_as_uri(prop)) << endmsg;
1435                         continue;
1436                 }
1437
1438                 // Convert range to variant type (TODO: support for multiple range types)
1439                 Variant::Type datatype;
1440                 if (!uri_to_variant_type(lilv_node_as_uri(range), datatype)) {
1441                         error << string_compose(_("LV2: property <%1> has unsupported datatype <%1>"),
1442                                                 lilv_node_as_uri(prop), lilv_node_as_uri(range)) << endmsg;
1443                         continue;
1444                 }
1445
1446                 // Add description to result
1447                 ParameterDescriptor desc;
1448                 desc.key      = _uri_map.uri_to_id(lilv_node_as_uri(prop));
1449                 desc.datatype = datatype;
1450                 load_parameter_descriptor(_world, desc, datatype, prop);
1451                 descs.insert(std::make_pair(desc.key, desc));
1452
1453                 lilv_node_free(range);
1454         }
1455         lilv_nodes_free(properties);
1456 }
1457
1458 void
1459 LV2Plugin::announce_property_values()
1460 {
1461         if (_patch_port_in_index == (uint32_t)-1) {
1462                 return;
1463         }
1464
1465         // Set up forge to write to temporary buffer on the stack
1466         LV2_Atom_Forge*      forge = &_impl->ui_forge;
1467         LV2_Atom_Forge_Frame frame;
1468         uint8_t              buf[PATH_MAX];  // Ought to be enough for anyone...
1469
1470         lv2_atom_forge_set_buffer(forge, buf, sizeof(buf));
1471
1472         // Serialize patch:Get message with no subject (implicitly plugin instance)
1473 #ifdef HAVE_LV2_1_10_0
1474         lv2_atom_forge_object(forge, &frame, 1, _uri_map.urids.patch_Get);
1475 #else
1476         lv2_atom_forge_blank(forge, &frame, 1, _uri_map.urids.patch_Get);
1477 #endif
1478
1479         // Write message to UI=>Plugin ring
1480         const LV2_Atom* const atom = (const LV2_Atom*)buf;
1481         write_from_ui(_patch_port_in_index,
1482                       _uri_map.urids.atom_eventTransfer,
1483                       lv2_atom_total_size(atom),
1484                       (const uint8_t*)atom);
1485 }
1486
1487 void
1488 LV2Plugin::enable_ui_emission()
1489 {
1490         if (!_to_ui) {
1491                 /* see note in LV2Plugin::write_from_ui() */
1492                 uint32_t bufsiz = 32768;
1493                 if (_atom_ev_buffers && _atom_ev_buffers[0]) {
1494                         bufsiz =  lv2_evbuf_get_capacity(_atom_ev_buffers[0]);
1495                 }
1496                 size_t rbs = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
1497                 rbs = max((size_t) bufsiz * 8, rbs);
1498                 _to_ui = new RingBuffer<uint8_t>(rbs);
1499         }
1500 }
1501
1502 void
1503 LV2Plugin::emit_to_ui(void* controller, UIMessageSink sink)
1504 {
1505         if (!_to_ui) {
1506                 return;
1507         }
1508
1509         uint32_t read_space = _to_ui->read_space();
1510         while (read_space > sizeof(UIMessage)) {
1511                 UIMessage msg;
1512                 if (_to_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1513                         error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1514                         break;
1515                 }
1516                 vector<uint8_t> body(msg.size);
1517                 if (_to_ui->read(&body[0], msg.size) != msg.size) {
1518                         error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1519                         break;
1520                 }
1521
1522                 sink(controller, msg.index, msg.size, msg.protocol, &body[0]);
1523
1524                 read_space -= sizeof(msg) + msg.size;
1525         }
1526 }
1527
1528 int
1529 LV2Plugin::work(uint32_t size, const void* data)
1530 {
1531         return _impl->work_iface->work(
1532                 _impl->instance->lv2_handle, work_respond, this, size, data);
1533 }
1534
1535 int
1536 LV2Plugin::work_response(uint32_t size, const void* data)
1537 {
1538         return _impl->work_iface->work_response(
1539                 _impl->instance->lv2_handle, size, data);
1540 }
1541
1542 void
1543 LV2Plugin::set_insert_id(PBD::ID id)
1544 {
1545         _insert_id = id;
1546 }
1547
1548 int
1549 LV2Plugin::set_state(const XMLNode& node, int version)
1550 {
1551         XMLNodeList          nodes;
1552         const XMLProperty*   prop;
1553         XMLNodeConstIterator iter;
1554         XMLNode*             child;
1555         const char*          sym;
1556         const char*          value;
1557         uint32_t             port_id;
1558         LocaleGuard          lg(X_("C"));
1559
1560         if (node.name() != state_node_name()) {
1561                 error << _("Bad node sent to LV2Plugin::set_state") << endmsg;
1562                 return -1;
1563         }
1564
1565 #ifndef NO_PLUGIN_STATE
1566
1567         if (version < 3000) {
1568                 nodes = node.children("port");
1569         } else {
1570                 nodes = node.children("Port");
1571         }
1572
1573         for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
1574
1575                 child = *iter;
1576
1577                 if ((prop = child->property("symbol")) != 0) {
1578                         sym = prop->value().c_str();
1579                 } else {
1580                         warning << _("LV2: port has no symbol, ignored") << endmsg;
1581                         continue;
1582                 }
1583
1584                 map<string, uint32_t>::iterator i = _port_indices.find(sym);
1585
1586                 if (i != _port_indices.end()) {
1587                         port_id = i->second;
1588                 } else {
1589                         warning << _("LV2: port has unknown index, ignored") << endmsg;
1590                         continue;
1591                 }
1592
1593                 if ((prop = child->property("value")) != 0) {
1594                         value = prop->value().c_str();
1595                 } else {
1596                         warning << _("LV2: port has no value, ignored") << endmsg;
1597                         continue;
1598                 }
1599
1600                 set_parameter(port_id, atof(value));
1601         }
1602
1603         _state_version = 0;
1604         if ((prop = node.property("state-dir")) != 0) {
1605                 if (sscanf(prop->value().c_str(), "state%u", &_state_version) != 1) {
1606                         error << string_compose(
1607                                 "LV2: failed to parse state version from \"%1\"",
1608                                 prop->value()) << endmsg;
1609                 }
1610
1611                 std::string state_file = Glib::build_filename(
1612                         plugin_dir(),
1613                         Glib::build_filename(prop->value(), "state.ttl"));
1614
1615                 LilvState* state = lilv_state_new_from_file(
1616                         _world.world, _uri_map.urid_map(), NULL, state_file.c_str());
1617
1618                 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
1619         }
1620
1621         latency_compute_run();
1622 #endif
1623
1624         return Plugin::set_state(node, version);
1625 }
1626
1627 int
1628 LV2Plugin::get_parameter_descriptor(uint32_t which, ParameterDescriptor& desc) const
1629 {
1630         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, which);
1631         if (!port) {
1632                 error << string_compose("LV2: get descriptor of non-existent port %1", which)
1633                       << endmsg;
1634                 return 1;
1635         }
1636
1637         LilvNodes* portunits;
1638         LilvNode *def, *min, *max;
1639         lilv_port_get_range(_impl->plugin, port, &def, &min, &max);
1640         portunits = lilv_port_get_value(_impl->plugin, port, _world.units_unit);
1641
1642         // TODO: Once we can rely on lilv 0.18.0 being present,
1643         // load_parameter_descriptor() can be used for ports as well
1644         desc.integer_step = lilv_port_has_property(_impl->plugin, port, _world.lv2_integer);
1645         desc.toggled      = lilv_port_has_property(_impl->plugin, port, _world.lv2_toggled);
1646         desc.logarithmic  = lilv_port_has_property(_impl->plugin, port, _world.ext_logarithmic);
1647         desc.sr_dependent = lilv_port_has_property(_impl->plugin, port, _world.lv2_sampleRate);
1648         desc.label        = lilv_node_as_string(lilv_port_get_name(_impl->plugin, port));
1649         desc.normal       = def ? lilv_node_as_float(def) : 0.0f;
1650         desc.lower        = min ? lilv_node_as_float(min) : 0.0f;
1651         desc.upper        = max ? lilv_node_as_float(max) : 1.0f;
1652         load_parameter_descriptor_units(_world.world, desc, portunits);
1653
1654         if (desc.sr_dependent) {
1655                 desc.lower *= _session.frame_rate ();
1656                 desc.upper *= _session.frame_rate ();
1657         }
1658
1659         desc.min_unbound  = false; // TODO: LV2 extension required
1660         desc.max_unbound  = false; // TODO: LV2 extension required
1661
1662         desc.enumeration = lilv_port_has_property(_impl->plugin, port, _world.lv2_enumeration);
1663         desc.scale_points = get_scale_points(which);
1664
1665         desc.update_steps();
1666
1667         lilv_node_free(def);
1668         lilv_node_free(min);
1669         lilv_node_free(max);
1670         lilv_nodes_free(portunits);
1671
1672         return 0;
1673 }
1674
1675 string
1676 LV2Plugin::describe_parameter(Evoral::Parameter which)
1677 {
1678         if (( which.type() == PluginAutomation) && ( which.id() < parameter_count()) ) {
1679
1680                 if (lilv_port_has_property(_impl->plugin,
1681                                         lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.ext_notOnGUI)) {
1682                         return X_("hidden");
1683                 }
1684
1685                 if (lilv_port_has_property(_impl->plugin,
1686                                         lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_freewheeling)) {
1687                         return X_("hidden");
1688                 }
1689
1690                 if (lilv_port_has_property(_impl->plugin,
1691                                         lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_reportsLatency)) {
1692                         return X_("latency");
1693                 }
1694
1695                 LilvNode* name = lilv_port_get_name(_impl->plugin,
1696                                                     lilv_plugin_get_port_by_index(_impl->plugin, which.id()));
1697                 string ret(lilv_node_as_string(name));
1698                 lilv_node_free(name);
1699                 return ret;
1700         } else {
1701                 return "??";
1702         }
1703 }
1704
1705 framecnt_t
1706 LV2Plugin::signal_latency() const
1707 {
1708         if (_latency_control_port) {
1709                 return (framecnt_t)floor(*_latency_control_port);
1710         } else {
1711                 return 0;
1712         }
1713 }
1714
1715 set<Evoral::Parameter>
1716 LV2Plugin::automatable() const
1717 {
1718         set<Evoral::Parameter> ret;
1719
1720         for (uint32_t i = 0; i < parameter_count(); ++i) {
1721                 if (parameter_is_input(i) && parameter_is_control(i)) {
1722                         ret.insert(ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
1723                 }
1724         }
1725
1726         for (PropertyDescriptors::const_iterator p = _property_descriptors.begin();
1727              p != _property_descriptors.end();
1728              ++p) {
1729                 ret.insert(ret.end(), Evoral::Parameter(PluginPropertyAutomation, 0, p->first));
1730         }
1731         return ret;
1732 }
1733
1734 void
1735 LV2Plugin::activate()
1736 {
1737         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 activate\n", name()));
1738
1739         if (!_was_activated) {
1740                 lilv_instance_activate(_impl->instance);
1741                 _was_activated = true;
1742         }
1743 }
1744
1745 void
1746 LV2Plugin::deactivate()
1747 {
1748         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 deactivate\n", name()));
1749
1750         if (_was_activated) {
1751                 lilv_instance_deactivate(_impl->instance);
1752                 _was_activated = false;
1753         }
1754 }
1755
1756 void
1757 LV2Plugin::cleanup()
1758 {
1759         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 cleanup\n", name()));
1760
1761         activate();
1762         deactivate();
1763         lilv_instance_free(_impl->instance);
1764         _impl->instance = NULL;
1765 }
1766
1767 void
1768 LV2Plugin::allocate_atom_event_buffers()
1769 {
1770         /* reserve local scratch buffers for ATOM event-queues */
1771         const LilvPlugin* p = _impl->plugin;
1772
1773         /* count non-MIDI atom event-ports
1774          * TODO: nicely ask drobilla to make a lilv_ call for that
1775          */
1776         int count_atom_out = 0;
1777         int count_atom_in = 0;
1778         int minimumSize = 32768; // TODO use a per-port minimum-size
1779         for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
1780                 const LilvPort* port  = lilv_plugin_get_port_by_index(p, i);
1781                 if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
1782                         LilvNodes* buffer_types = lilv_port_get_value(
1783                                 p, port, _world.atom_bufferType);
1784                         LilvNodes* atom_supports = lilv_port_get_value(
1785                                 p, port, _world.atom_supports);
1786
1787                         if (!lilv_nodes_contains(buffer_types, _world.atom_Sequence)
1788                                         || !lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
1789                                 if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
1790                                         count_atom_in++;
1791                                 }
1792                                 if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
1793                                         count_atom_out++;
1794                                 }
1795                                 LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
1796                                 LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
1797                                 if (min_size && lilv_node_is_int(min_size)) {
1798                                         minimumSize = std::max(minimumSize, lilv_node_as_int(min_size));
1799                                 }
1800                                 lilv_nodes_free(min_size_v);
1801                         }
1802                         lilv_nodes_free(buffer_types);
1803                         lilv_nodes_free(atom_supports);
1804                 }
1805         }
1806
1807         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 need buffers for %2 atom-in and %3 atom-out event-ports\n",
1808                                 name(), count_atom_in, count_atom_out));
1809
1810         const int total_atom_buffers = (count_atom_in + count_atom_out);
1811         if (_atom_ev_buffers || total_atom_buffers == 0) {
1812                 return;
1813         }
1814
1815         DEBUG_TRACE(DEBUG::LV2, string_compose("allocate %1 atom_ev_buffers of %d bytes\n", total_atom_buffers, minimumSize));
1816         _atom_ev_buffers = (LV2_Evbuf**) malloc((total_atom_buffers + 1) * sizeof(LV2_Evbuf*));
1817         for (int i = 0; i < total_atom_buffers; ++i ) {
1818                 _atom_ev_buffers[i] = lv2_evbuf_new(minimumSize, LV2_EVBUF_ATOM,
1819                                 _uri_map.urids.atom_Chunk, _uri_map.urids.atom_Sequence);
1820         }
1821         _atom_ev_buffers[total_atom_buffers] = 0;
1822         return;
1823 }
1824
1825 /** Write an ardour position/time/tempo/meter as an LV2 event.
1826  * @return true on success.
1827  */
1828 static bool
1829 write_position(LV2_Atom_Forge*     forge,
1830                LV2_Evbuf*          buf,
1831                const TempoMetric&  t,
1832                Timecode::BBT_Time& bbt,
1833                double              speed,
1834                framepos_t          position,
1835                framecnt_t          offset)
1836 {
1837         const URIMap::URIDs& urids = URIMap::instance().urids;
1838
1839         uint8_t pos_buf[256];
1840         lv2_atom_forge_set_buffer(forge, pos_buf, sizeof(pos_buf));
1841         LV2_Atom_Forge_Frame frame;
1842 #ifdef HAVE_LV2_1_10_0
1843         lv2_atom_forge_object(forge, &frame, 1, urids.time_Position);
1844         lv2_atom_forge_key(forge, urids.time_frame);
1845         lv2_atom_forge_long(forge, position);
1846         lv2_atom_forge_key(forge, urids.time_speed);
1847         lv2_atom_forge_float(forge, speed);
1848         lv2_atom_forge_key(forge, urids.time_barBeat);
1849         lv2_atom_forge_float(forge, bbt.beats - 1 +
1850                              (bbt.ticks / Timecode::BBT_Time::ticks_per_beat));
1851         lv2_atom_forge_key(forge, urids.time_bar);
1852         lv2_atom_forge_long(forge, bbt.bars - 1);
1853         lv2_atom_forge_key(forge, urids.time_beatUnit);
1854         lv2_atom_forge_int(forge, t.meter().note_divisor());
1855         lv2_atom_forge_key(forge, urids.time_beatsPerBar);
1856         lv2_atom_forge_float(forge, t.meter().divisions_per_bar());
1857         lv2_atom_forge_key(forge, urids.time_beatsPerMinute);
1858         lv2_atom_forge_float(forge, t.tempo().beats_per_minute());
1859 #else
1860         lv2_atom_forge_blank(forge, &frame, 1, urids.time_Position);
1861         lv2_atom_forge_property_head(forge, urids.time_frame, 0);
1862         lv2_atom_forge_long(forge, position);
1863         lv2_atom_forge_property_head(forge, urids.time_speed, 0);
1864         lv2_atom_forge_float(forge, speed);
1865         lv2_atom_forge_property_head(forge, urids.time_barBeat, 0);
1866         lv2_atom_forge_float(forge, bbt.beats - 1 +
1867                              (bbt.ticks / Timecode::BBT_Time::ticks_per_beat));
1868         lv2_atom_forge_property_head(forge, urids.time_bar, 0);
1869         lv2_atom_forge_long(forge, bbt.bars - 1);
1870         lv2_atom_forge_property_head(forge, urids.time_beatUnit, 0);
1871         lv2_atom_forge_int(forge, t.meter().note_divisor());
1872         lv2_atom_forge_property_head(forge, urids.time_beatsPerBar, 0);
1873         lv2_atom_forge_float(forge, t.meter().divisions_per_bar());
1874         lv2_atom_forge_property_head(forge, urids.time_beatsPerMinute, 0);
1875         lv2_atom_forge_float(forge, t.tempo().beats_per_minute());
1876 #endif
1877
1878         LV2_Evbuf_Iterator    end  = lv2_evbuf_end(buf);
1879         const LV2_Atom* const atom = (const LV2_Atom*)pos_buf;
1880         return lv2_evbuf_write(&end, offset, 0, atom->type, atom->size,
1881                                (const uint8_t*)(atom + 1));
1882 }
1883
1884 int
1885 LV2Plugin::connect_and_run(BufferSet& bufs,
1886         ChanMapping in_map, ChanMapping out_map,
1887         pframes_t nframes, framecnt_t offset)
1888 {
1889         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 run %2 offset %3\n", name(), nframes, offset));
1890         Plugin::connect_and_run(bufs, in_map, out_map, nframes, offset);
1891
1892         cycles_t then = get_cycles();
1893
1894         TempoMap&               tmap     = _session.tempo_map();
1895         Metrics::const_iterator metric_i = tmap.metrics_end();
1896         TempoMetric             tmetric  = tmap.metric_at(_session.transport_frame(), &metric_i);
1897
1898         if (_freewheel_control_port) {
1899                 *_freewheel_control_port = _session.engine().freewheeling();
1900         }
1901
1902         if (_bpm_control_port) {
1903                 *_bpm_control_port = tmetric.tempo().beats_per_minute();
1904         }
1905
1906         ChanCount bufs_count;
1907         bufs_count.set(DataType::AUDIO, 1);
1908         bufs_count.set(DataType::MIDI, 1);
1909         BufferSet& silent_bufs  = _session.get_silent_buffers(bufs_count);
1910         BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
1911         uint32_t const num_ports = parameter_count();
1912         uint32_t const nil_index = std::numeric_limits<uint32_t>::max();
1913
1914         uint32_t audio_in_index  = 0;
1915         uint32_t audio_out_index = 0;
1916         uint32_t midi_in_index   = 0;
1917         uint32_t midi_out_index  = 0;
1918         uint32_t atom_port_index = 0;
1919         for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
1920                 void*     buf   = NULL;
1921                 uint32_t  index = nil_index;
1922                 PortFlags flags = _port_flags[port_index];
1923                 bool      valid = false;
1924                 if (flags & PORT_AUDIO) {
1925                         if (flags & PORT_INPUT) {
1926                                 index = in_map.get(DataType::AUDIO, audio_in_index++, &valid);
1927                                 buf = (valid)
1928                                         ? bufs.get_audio(index).data(offset)
1929                                         : silent_bufs.get_audio(0).data(offset);
1930                         } else {
1931                                 index = out_map.get(DataType::AUDIO, audio_out_index++, &valid);
1932                                 buf = (valid)
1933                                         ? bufs.get_audio(index).data(offset)
1934                                         : scratch_bufs.get_audio(0).data(offset);
1935                         }
1936                 } else if (flags & (PORT_EVENT|PORT_SEQUENCE)) {
1937                         /* FIXME: The checks here for bufs.count().n_midi() > index shouldn't
1938                            be necessary, but the mapping is illegal in some cases.  Ideally
1939                            that should be fixed, but this is easier...
1940                         */
1941                         if (flags & PORT_MIDI) {
1942                                 if (flags & PORT_INPUT) {
1943                                         index = in_map.get(DataType::MIDI, midi_in_index++, &valid);
1944                                 } else {
1945                                         index = out_map.get(DataType::MIDI, midi_out_index++, &valid);
1946                                 }
1947                                 if (valid && bufs.count().n_midi() > index) {
1948                                         /* Note, ensure_lv2_bufsize() is not RT safe!
1949                                          * However free()/alloc() is only called if a
1950                                          * plugin requires a rsz:minimumSize buffersize
1951                                          * and the existing buffer if smaller.
1952                                          */
1953                                         bufs.ensure_lv2_bufsize((flags & PORT_INPUT), index, _port_minimumSize[port_index]);
1954                                         _ev_buffers[port_index] = bufs.get_lv2_midi(
1955                                                 (flags & PORT_INPUT), index, (flags & PORT_EVENT));
1956                                 }
1957                         } else if ((flags & PORT_POSITION) && (flags & PORT_INPUT)) {
1958                                 lv2_evbuf_reset(_atom_ev_buffers[atom_port_index], true);
1959                                 _ev_buffers[port_index] = _atom_ev_buffers[atom_port_index++];
1960                                 valid                   = true;
1961                         }
1962
1963                         if (valid && (flags & PORT_INPUT)) {
1964                                 Timecode::BBT_Time bbt;
1965                                 if ((flags & PORT_POSITION)) {
1966                                         if (_session.transport_frame() != _next_cycle_start ||
1967                                             _session.transport_speed() != _next_cycle_speed) {
1968                                                 // Transport has changed, write position at cycle start
1969                                                 tmap.bbt_time(_session.transport_frame(), bbt);
1970                                                 write_position(&_impl->forge, _ev_buffers[port_index],
1971                                                                tmetric, bbt, _session.transport_speed(),
1972                                                                _session.transport_frame(), 0);
1973                                         }
1974                                 }
1975
1976                                 // Get MIDI iterator range (empty range if no MIDI)
1977                                 MidiBuffer::iterator m = (index != nil_index)
1978                                         ? bufs.get_midi(index).begin()
1979                                         : silent_bufs.get_midi(0).end();
1980                                 MidiBuffer::iterator m_end = (index != nil_index)
1981                                         ? bufs.get_midi(index).end()
1982                                         : m;
1983
1984                                 // Now merge MIDI and any transport events into the buffer
1985                                 const uint32_t     type = _uri_map.urids.midi_MidiEvent;
1986                                 const framepos_t   tend = _session.transport_frame() + nframes;
1987                                 ++metric_i;
1988                                 while (m != m_end || (metric_i != tmap.metrics_end() &&
1989                                                       (*metric_i)->frame() < tend)) {
1990                                         MetricSection* metric = (metric_i != tmap.metrics_end())
1991                                                 ? *metric_i : NULL;
1992                                         if (m != m_end && (!metric || metric->frame() > (*m).time())) {
1993                                                 const Evoral::MIDIEvent<framepos_t> ev(*m, false);
1994                                                 LV2_Evbuf_Iterator eend = lv2_evbuf_end(_ev_buffers[port_index]);
1995                                                 lv2_evbuf_write(&eend, ev.time(), 0, type, ev.size(), ev.buffer());
1996                                                 ++m;
1997                                         } else {
1998                                                 tmetric.set_metric(metric);
1999                                                 bbt = metric->start();
2000                                                 write_position(&_impl->forge, _ev_buffers[port_index],
2001                                                                tmetric, bbt, _session.transport_speed(),
2002                                                                metric->frame(),
2003                                                                metric->frame() - _session.transport_frame());
2004                                                 ++metric_i;
2005                                         }
2006                                 }
2007                         } else if (!valid) {
2008                                 // Nothing we understand or care about, connect to scratch
2009                                 // see note for midi-buffer size above
2010                                 scratch_bufs.ensure_lv2_bufsize((flags & PORT_INPUT),
2011                                                 0, _port_minimumSize[port_index]);
2012                                 _ev_buffers[port_index] = scratch_bufs.get_lv2_midi(
2013                                         (flags & PORT_INPUT), 0, (flags & PORT_EVENT));
2014                         }
2015
2016                         buf = lv2_evbuf_get_buffer(_ev_buffers[port_index]);
2017                 } else {
2018                         continue;  // Control port, leave buffer alone
2019                 }
2020                 lilv_instance_connect_port(_impl->instance, port_index, buf);
2021         }
2022
2023         // Read messages from UI and push into appropriate buffers
2024         if (_from_ui) {
2025                 uint32_t read_space = _from_ui->read_space();
2026                 while (read_space > sizeof(UIMessage)) {
2027                         UIMessage msg;
2028                         if (_from_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
2029                                 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
2030                                 break;
2031                         }
2032                         vector<uint8_t> body(msg.size);
2033                         if (_from_ui->read(&body[0], msg.size) != msg.size) {
2034                                 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
2035                                 break;
2036                         }
2037                         if (msg.protocol == URIMap::instance().urids.atom_eventTransfer) {
2038                                 LV2_Evbuf*            buf  = _ev_buffers[msg.index];
2039                                 LV2_Evbuf_Iterator    i    = lv2_evbuf_end(buf);
2040                                 const LV2_Atom* const atom = (const LV2_Atom*)&body[0];
2041                                 if (!lv2_evbuf_write(&i, nframes - 1, 0, atom->type, atom->size,
2042                                                 (const uint8_t*)(atom + 1))) {
2043                                         error << "Failed to write data to LV2 event buffer\n";
2044                                 }
2045                         } else {
2046                                 error << "Received unknown message type from UI" << endmsg;
2047                         }
2048                         read_space -= sizeof(UIMessage) + msg.size;
2049                 }
2050         }
2051
2052         run(nframes);
2053
2054         midi_out_index = 0;
2055         for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
2056                 PortFlags flags = _port_flags[port_index];
2057                 bool      valid = false;
2058
2059                 /* TODO ask drobilla about comment
2060                  * "Make Ardour event buffers generic so plugins can communicate"
2061                  * in libs/ardour/buffer_set.cc:310
2062                  *
2063                  * ideally the user could choose which of the following two modes
2064                  * to use (e.g. instrument/effect chains  MIDI OUT vs MIDI TRHU).
2065                  *
2066                  * This implementation follows the discussion on IRC Mar 16 2013 16:47 UTC
2067                  * 16:51 < drobilla> rgareus: [..] i.e always replace with MIDI output [of LV2 plugin] if it's there
2068                  * 16:52 < drobilla> rgareus: That would probably be good enough [..] to make users not complain
2069                  *                            for quite a while at least ;)
2070                  */
2071                 // copy output of LV2 plugin's MIDI port to Ardour MIDI buffers -- MIDI OUT
2072                 if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE|PORT_MIDI))) {
2073                         const uint32_t buf_index = out_map.get(
2074                                 DataType::MIDI, midi_out_index++, &valid);
2075                         if (valid) {
2076                                 bufs.forward_lv2_midi(_ev_buffers[port_index], buf_index);
2077                         }
2078                 }
2079                 // Flush MIDI (write back to Ardour MIDI buffers) -- MIDI THRU
2080                 else if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
2081                         const uint32_t buf_index = out_map.get(
2082                                 DataType::MIDI, midi_out_index++, &valid);
2083                         if (valid) {
2084                                 bufs.flush_lv2_midi(true, buf_index);
2085                         }
2086                 }
2087
2088
2089                 // Write messages to UI
2090                 if ((_to_ui || _patch_port_out_index != (uint32_t)-1) &&
2091                     (flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
2092                         LV2_Evbuf* buf = _ev_buffers[port_index];
2093                         for (LV2_Evbuf_Iterator i = lv2_evbuf_begin(buf);
2094                              lv2_evbuf_is_valid(i);
2095                              i = lv2_evbuf_next(i)) {
2096                                 uint32_t frames, subframes, type, size;
2097                                 uint8_t* data;
2098                                 lv2_evbuf_get(i, &frames, &subframes, &type, &size, &data);
2099
2100                                 // Intercept patch change messages to emit PropertyChanged signal
2101                                 if ((flags & PORT_PATCHMSG)) {
2102                                         LV2_Atom* atom = (LV2_Atom*)(data - sizeof(LV2_Atom));
2103                                         if (atom->type == _uri_map.urids.atom_Blank ||
2104                                             atom->type == _uri_map.urids.atom_Object) {
2105                                                 LV2_Atom_Object* obj = (LV2_Atom_Object*)atom;
2106                                                 if (obj->body.otype == _uri_map.urids.patch_Set) {
2107                                                         const LV2_Atom* property = NULL;
2108                                                         const LV2_Atom* value    = NULL;
2109                                                         lv2_atom_object_get(obj,
2110                                                                             _uri_map.urids.patch_property, &property,
2111                                                                             _uri_map.urids.patch_value,    &value,
2112                                                                             0);
2113
2114                                                         if (!property || !value ||
2115                                                             property->type != _uri_map.urids.atom_URID ||
2116                                                             value->type    != _uri_map.urids.atom_Path) {
2117                                                                 std::cerr << "warning: patch:Set for unknown property" << std::endl;
2118                                                                 continue;
2119                                                         }
2120
2121                                                         const uint32_t prop_id = ((const LV2_Atom_URID*)property)->body;
2122                                                         const char*    path    = (const char*)LV2_ATOM_BODY_CONST(value);
2123
2124                                                         // Emit PropertyChanged signal for UI
2125                                                         // TODO: This should emit the control's Changed signal
2126                                                         PropertyChanged(prop_id, Variant(Variant::PATH, path));
2127                                                 }
2128                                         }
2129                                 }
2130
2131                                 if (!_to_ui) continue;
2132                                 write_to_ui(port_index, URIMap::instance().urids.atom_eventTransfer,
2133                                             size + sizeof(LV2_Atom),
2134                                             data - sizeof(LV2_Atom));
2135                         }
2136                 }
2137         }
2138
2139         cycles_t now = get_cycles();
2140         set_cycles((uint32_t)(now - then));
2141
2142         // Update expected transport information for next cycle so we can detect changes
2143         _next_cycle_speed = _session.transport_speed();
2144         _next_cycle_start = _session.transport_frame() + (nframes * _next_cycle_speed);
2145
2146         return 0;
2147 }
2148
2149 bool
2150 LV2Plugin::parameter_is_control(uint32_t param) const
2151 {
2152         assert(param < _port_flags.size());
2153         return _port_flags[param] & PORT_CONTROL;
2154 }
2155
2156 bool
2157 LV2Plugin::parameter_is_audio(uint32_t param) const
2158 {
2159         assert(param < _port_flags.size());
2160         return _port_flags[param] & PORT_AUDIO;
2161 }
2162
2163 bool
2164 LV2Plugin::parameter_is_event(uint32_t param) const
2165 {
2166         assert(param < _port_flags.size());
2167         return _port_flags[param] & PORT_EVENT;
2168 }
2169
2170 bool
2171 LV2Plugin::parameter_is_output(uint32_t param) const
2172 {
2173         assert(param < _port_flags.size());
2174         return _port_flags[param] & PORT_OUTPUT;
2175 }
2176
2177 bool
2178 LV2Plugin::parameter_is_input(uint32_t param) const
2179 {
2180         assert(param < _port_flags.size());
2181         return _port_flags[param] & PORT_INPUT;
2182 }
2183
2184 void
2185 LV2Plugin::print_parameter(uint32_t param, char* buf, uint32_t len) const
2186 {
2187         if (buf && len) {
2188                 if (param < parameter_count()) {
2189                         snprintf(buf, len, "%.3f", get_parameter(param));
2190                 } else {
2191                         strcat(buf, "0");
2192                 }
2193         }
2194 }
2195
2196 boost::shared_ptr<ScalePoints>
2197 LV2Plugin::get_scale_points(uint32_t port_index) const
2198 {
2199         const LilvPort*  port   = lilv_plugin_get_port_by_index(_impl->plugin, port_index);
2200         LilvScalePoints* points = lilv_port_get_scale_points(_impl->plugin, port);
2201
2202         boost::shared_ptr<ScalePoints> ret;
2203         if (!points) {
2204                 return ret;
2205         }
2206
2207         ret = boost::shared_ptr<ScalePoints>(new ScalePoints());
2208
2209         LILV_FOREACH(scale_points, i, points) {
2210                 const LilvScalePoint* p     = lilv_scale_points_get(points, i);
2211                 const LilvNode*       label = lilv_scale_point_get_label(p);
2212                 const LilvNode*       value = lilv_scale_point_get_value(p);
2213                 if (label && (lilv_node_is_float(value) || lilv_node_is_int(value))) {
2214                         ret->insert(make_pair(lilv_node_as_string(label),
2215                                               lilv_node_as_float(value)));
2216                 }
2217         }
2218
2219         lilv_scale_points_free(points);
2220         return ret;
2221 }
2222
2223 void
2224 LV2Plugin::run(pframes_t nframes)
2225 {
2226         uint32_t const N = parameter_count();
2227         for (uint32_t i = 0; i < N; ++i) {
2228                 if (parameter_is_control(i) && parameter_is_input(i)) {
2229                         _control_data[i] = _shadow_data[i];
2230                 }
2231         }
2232
2233         lilv_instance_run(_impl->instance, nframes);
2234
2235         if (_impl->work_iface) {
2236                 _worker->emit_responses();
2237                 if (_impl->work_iface->end_run) {
2238                         _impl->work_iface->end_run(_impl->instance->lv2_handle);
2239                 }
2240         }
2241 }
2242
2243 void
2244 LV2Plugin::latency_compute_run()
2245 {
2246         if (!_latency_control_port) {
2247                 return;
2248         }
2249
2250         // Run the plugin so that it can set its latency parameter
2251
2252         bool was_activated = _was_activated;
2253         activate();
2254
2255         uint32_t port_index = 0;
2256         uint32_t in_index   = 0;
2257         uint32_t out_index  = 0;
2258
2259         // this is done in the main thread. non realtime.
2260         const framecnt_t bufsize = _engine.samples_per_cycle();
2261         float            *buffer = (float*) malloc(_engine.samples_per_cycle() * sizeof(float));
2262
2263         memset(buffer, 0, sizeof(float) * bufsize);
2264
2265         // FIXME: Ensure plugins can handle in-place processing
2266
2267         port_index = 0;
2268
2269         while (port_index < parameter_count()) {
2270                 if (parameter_is_audio(port_index)) {
2271                         if (parameter_is_input(port_index)) {
2272                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
2273                                 in_index++;
2274                         } else if (parameter_is_output(port_index)) {
2275                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
2276                                 out_index++;
2277                         }
2278                 }
2279                 port_index++;
2280         }
2281
2282         run(bufsize);
2283         deactivate();
2284         if (was_activated) {
2285                 activate();
2286         }
2287         free(buffer);
2288 }
2289
2290 const LilvPort*
2291 LV2Plugin::Impl::designated_input (const char* uri, void** bufptrs[], void** bufptr)
2292 {
2293         const LilvPort* port = NULL;
2294         LilvNode* designation = lilv_new_uri(_world.world, uri);
2295         port = lilv_plugin_get_port_by_designation(
2296                 plugin, _world.lv2_InputPort, designation);
2297         lilv_node_free(designation);
2298         if (port) {
2299                 bufptrs[lilv_port_get_index(plugin, port)] = bufptr;
2300         }
2301         return port;
2302 }
2303
2304 static bool lv2_filter (const string& str, void* /*arg*/)
2305 {
2306         /* Not a dotfile, has a prefix before a period, suffix is "lv2" */
2307         
2308         return str[0] != '.' && (str.length() > 3 && str.find (".lv2") == (str.length() - 4));
2309 }
2310
2311
2312 LV2World::LV2World()
2313         : world(lilv_world_new())
2314         , _bundle_checked(false)
2315 {
2316         atom_AtomPort      = lilv_new_uri(world, LV2_ATOM__AtomPort);
2317         atom_Chunk         = lilv_new_uri(world, LV2_ATOM__Chunk);
2318         atom_Sequence      = lilv_new_uri(world, LV2_ATOM__Sequence);
2319         atom_bufferType    = lilv_new_uri(world, LV2_ATOM__bufferType);
2320         atom_supports      = lilv_new_uri(world, LV2_ATOM__supports);
2321         atom_eventTransfer = lilv_new_uri(world, LV2_ATOM__eventTransfer);
2322         ev_EventPort       = lilv_new_uri(world, LILV_URI_EVENT_PORT);
2323         ext_logarithmic    = lilv_new_uri(world, LV2_PORT_PROPS__logarithmic);
2324         ext_notOnGUI       = lilv_new_uri(world, LV2_PORT_PROPS__notOnGUI);
2325         lv2_AudioPort      = lilv_new_uri(world, LILV_URI_AUDIO_PORT);
2326         lv2_ControlPort    = lilv_new_uri(world, LILV_URI_CONTROL_PORT);
2327         lv2_InputPort      = lilv_new_uri(world, LILV_URI_INPUT_PORT);
2328         lv2_OutputPort     = lilv_new_uri(world, LILV_URI_OUTPUT_PORT);
2329         lv2_inPlaceBroken  = lilv_new_uri(world, LV2_CORE__inPlaceBroken);
2330         lv2_integer        = lilv_new_uri(world, LV2_CORE__integer);
2331         lv2_default        = lilv_new_uri(world, LV2_CORE__default);
2332         lv2_minimum        = lilv_new_uri(world, LV2_CORE__minimum);
2333         lv2_maximum        = lilv_new_uri(world, LV2_CORE__maximum);
2334         lv2_reportsLatency = lilv_new_uri(world, LV2_CORE__reportsLatency);
2335         lv2_sampleRate     = lilv_new_uri(world, LV2_CORE__sampleRate);
2336         lv2_toggled        = lilv_new_uri(world, LV2_CORE__toggled);
2337         lv2_enumeration    = lilv_new_uri(world, LV2_CORE__enumeration);
2338         lv2_freewheeling   = lilv_new_uri(world, LV2_CORE__freeWheeling);
2339         midi_MidiEvent     = lilv_new_uri(world, LILV_URI_MIDI_EVENT);
2340         rdfs_comment       = lilv_new_uri(world, LILV_NS_RDFS "comment");
2341         rdfs_label         = lilv_new_uri(world, LILV_NS_RDFS "label");
2342         rdfs_range         = lilv_new_uri(world, LILV_NS_RDFS "range");
2343         rsz_minimumSize    = lilv_new_uri(world, LV2_RESIZE_PORT__minimumSize);
2344         time_Position      = lilv_new_uri(world, LV2_TIME__Position);
2345         ui_GtkUI           = lilv_new_uri(world, LV2_UI__GtkUI);
2346         ui_external        = lilv_new_uri(world, "http://lv2plug.in/ns/extensions/ui#external");
2347         ui_externalkx      = lilv_new_uri(world, "http://kxstudio.sf.net/ns/lv2ext/external-ui#Widget");
2348         units_unit         = lilv_new_uri(world, LV2_UNITS__unit);
2349         units_render       = lilv_new_uri(world, LV2_UNITS__render);
2350         units_hz           = lilv_new_uri(world, LV2_UNITS__hz);
2351         units_midiNote     = lilv_new_uri(world, LV2_UNITS__midiNote);
2352         units_db           = lilv_new_uri(world, LV2_UNITS__db);
2353         patch_writable     = lilv_new_uri(world, LV2_PATCH__writable);
2354         patch_Message      = lilv_new_uri(world, LV2_PATCH__Message);
2355 }
2356
2357 LV2World::~LV2World()
2358 {
2359         lilv_node_free(patch_Message);
2360         lilv_node_free(patch_writable);
2361         lilv_node_free(units_hz);
2362         lilv_node_free(units_midiNote);
2363         lilv_node_free(units_db);
2364         lilv_node_free(units_unit);
2365         lilv_node_free(units_render);
2366         lilv_node_free(ui_externalkx);
2367         lilv_node_free(ui_external);
2368         lilv_node_free(ui_GtkUI);
2369         lilv_node_free(time_Position);
2370         lilv_node_free(rsz_minimumSize);
2371         lilv_node_free(rdfs_comment);
2372         lilv_node_free(rdfs_label);
2373         lilv_node_free(rdfs_range);
2374         lilv_node_free(midi_MidiEvent);
2375         lilv_node_free(lv2_enumeration);
2376         lilv_node_free(lv2_freewheeling);
2377         lilv_node_free(lv2_toggled);
2378         lilv_node_free(lv2_sampleRate);
2379         lilv_node_free(lv2_reportsLatency);
2380         lilv_node_free(lv2_integer);
2381         lilv_node_free(lv2_inPlaceBroken);
2382         lilv_node_free(lv2_OutputPort);
2383         lilv_node_free(lv2_InputPort);
2384         lilv_node_free(lv2_ControlPort);
2385         lilv_node_free(lv2_AudioPort);
2386         lilv_node_free(ext_notOnGUI);
2387         lilv_node_free(ext_logarithmic);
2388         lilv_node_free(ev_EventPort);
2389         lilv_node_free(atom_supports);
2390         lilv_node_free(atom_eventTransfer);
2391         lilv_node_free(atom_bufferType);
2392         lilv_node_free(atom_Sequence);
2393         lilv_node_free(atom_Chunk);
2394         lilv_node_free(atom_AtomPort);
2395         lilv_world_free(world);
2396 }
2397
2398 void
2399 LV2World::load_bundled_plugins(bool verbose)
2400 {
2401         if (!_bundle_checked) {
2402                 if (verbose) {
2403                         cout << "Scanning folders for bundled LV2s: " << ARDOUR::lv2_bundled_search_path().to_string() << endl;
2404                 }
2405
2406                 vector<string> plugin_objects;
2407                 find_paths_matching_filter (plugin_objects, ARDOUR::lv2_bundled_search_path(), lv2_filter, 0, true, true, true);
2408                 for ( vector<string>::iterator x = plugin_objects.begin(); x != plugin_objects.end (); ++x) {
2409 #ifdef PLATFORM_WINDOWS
2410                         string uri = "file:///" + *x + "/";
2411 #else
2412                         string uri = "file://" + *x + "/";
2413 #endif
2414                         LilvNode *node = lilv_new_uri(world, uri.c_str());
2415                         lilv_world_load_bundle(world, node);
2416                         lilv_node_free(node);
2417                 }
2418
2419                 lilv_world_load_all(world);
2420                 _bundle_checked = true;
2421         }
2422 }
2423
2424 LV2PluginInfo::LV2PluginInfo (const char* plugin_uri)
2425 {
2426         type = ARDOUR::LV2;
2427         _plugin_uri = strdup(plugin_uri);
2428 }
2429
2430 LV2PluginInfo::~LV2PluginInfo()
2431 {
2432         free(_plugin_uri);
2433         _plugin_uri = NULL;
2434 }
2435
2436 PluginPtr
2437 LV2PluginInfo::load(Session& session)
2438 {
2439         try {
2440                 PluginPtr plugin;
2441                 const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
2442                 LilvNode* uri = lilv_new_uri(_world.world, _plugin_uri);
2443                 if (!uri) { throw failed_constructor(); }
2444                 const LilvPlugin* lp = lilv_plugins_get_by_uri(plugins, uri);
2445                 if (!lp) { throw failed_constructor(); }
2446                 plugin.reset(new LV2Plugin(session.engine(), session, lp, session.frame_rate()));
2447                 lilv_node_free(uri);
2448                 plugin->set_info(PluginInfoPtr(shared_from_this ()));
2449                 return plugin;
2450         } catch (failed_constructor& err) {
2451                 return PluginPtr((Plugin*)0);
2452         }
2453
2454         return PluginPtr();
2455 }
2456
2457 PluginInfoList*
2458 LV2PluginInfo::discover()
2459 {
2460         LV2World world;
2461         world.load_bundled_plugins();
2462         _world.load_bundled_plugins(true);
2463
2464         PluginInfoList*    plugs   = new PluginInfoList;
2465         const LilvPlugins* plugins = lilv_world_get_all_plugins(world.world);
2466
2467         LILV_FOREACH(plugins, i, plugins) {
2468                 const LilvPlugin* p = lilv_plugins_get(plugins, i);
2469                 const LilvNode* pun = lilv_plugin_get_uri(p);
2470                 if (!pun) continue;
2471                 LV2PluginInfoPtr info(new LV2PluginInfo(lilv_node_as_string(pun)));
2472
2473                 LilvNode* name = lilv_plugin_get_name(p);
2474                 if (!name || !lilv_plugin_get_port_by_index(p, 0)) {
2475                         warning << "Ignoring invalid LV2 plugin "
2476                                 << lilv_node_as_string(lilv_plugin_get_uri(p))
2477                                 << endmsg;
2478                         continue;
2479                 }
2480
2481                 info->type = LV2;
2482
2483                 info->name = string(lilv_node_as_string(name));
2484                 lilv_node_free(name);
2485                 ARDOUR::PluginScanMessage(_("LV2"), info->name, false);
2486
2487                 const LilvPluginClass* pclass = lilv_plugin_get_class(p);
2488                 const LilvNode*        label  = lilv_plugin_class_get_label(pclass);
2489                 info->category = lilv_node_as_string(label);
2490
2491                 LilvNode* author_name = lilv_plugin_get_author_name(p);
2492                 info->creator = author_name ? string(lilv_node_as_string(author_name)) : "Unknown";
2493                 lilv_node_free(author_name);
2494
2495                 info->path = "/NOPATH"; // Meaningless for LV2
2496
2497                 /* count atom-event-ports that feature
2498                  * atom:supports <http://lv2plug.in/ns/ext/midi#MidiEvent>
2499                  *
2500                  * TODO: nicely ask drobilla to make a lilv_ call for that
2501                  */
2502                 int count_midi_out = 0;
2503                 int count_midi_in = 0;
2504                 for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
2505                         const LilvPort* port  = lilv_plugin_get_port_by_index(p, i);
2506                         if (lilv_port_is_a(p, port, world.atom_AtomPort)) {
2507                                 LilvNodes* buffer_types = lilv_port_get_value(
2508                                         p, port, world.atom_bufferType);
2509                                 LilvNodes* atom_supports = lilv_port_get_value(
2510                                         p, port, world.atom_supports);
2511
2512                                 if (lilv_nodes_contains(buffer_types, world.atom_Sequence)
2513                                                 && lilv_nodes_contains(atom_supports, world.midi_MidiEvent)) {
2514                                         if (lilv_port_is_a(p, port, world.lv2_InputPort)) {
2515                                                 count_midi_in++;
2516                                         }
2517                                         if (lilv_port_is_a(p, port, world.lv2_OutputPort)) {
2518                                                 count_midi_out++;
2519                                         }
2520                                 }
2521                                 lilv_nodes_free(buffer_types);
2522                                 lilv_nodes_free(atom_supports);
2523                         }
2524                 }
2525
2526                 info->n_inputs.set_audio(
2527                         lilv_plugin_get_num_ports_of_class(
2528                                 p, world.lv2_InputPort, world.lv2_AudioPort, NULL));
2529                 info->n_inputs.set_midi(
2530                         lilv_plugin_get_num_ports_of_class(
2531                                 p, world.lv2_InputPort, world.ev_EventPort, NULL)
2532                         + count_midi_in);
2533
2534                 info->n_outputs.set_audio(
2535                         lilv_plugin_get_num_ports_of_class(
2536                                 p, world.lv2_OutputPort, world.lv2_AudioPort, NULL));
2537                 info->n_outputs.set_midi(
2538                         lilv_plugin_get_num_ports_of_class(
2539                                 p, world.lv2_OutputPort, world.ev_EventPort, NULL)
2540                         + count_midi_out);
2541
2542                 info->unique_id = lilv_node_as_uri(lilv_plugin_get_uri(p));
2543                 info->index     = 0; // Meaningless for LV2
2544
2545                 plugs->push_back(info);
2546         }
2547
2548         return plugs;
2549 }