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