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