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