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