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