Implement LV2 Inline Display Extension
[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 void*
870 LV2Plugin::render_inline_display (uint32_t w, uint32_t h) {
871         if (_display_interface) {
872                 return _display_interface->render ((void*)_impl->instance->lv2_handle, w, h);
873         }
874         return NULL;
875 }
876 #endif
877
878 string
879 LV2Plugin::unique_id() const
880 {
881         return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
882 }
883
884 const char*
885 LV2Plugin::uri() const
886 {
887         return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
888 }
889
890 const char*
891 LV2Plugin::label() const
892 {
893         return lilv_node_as_string(_impl->name);
894 }
895
896 const char*
897 LV2Plugin::name() const
898 {
899         return lilv_node_as_string(_impl->name);
900 }
901
902 const char*
903 LV2Plugin::maker() const
904 {
905         return _impl->author ? lilv_node_as_string (_impl->author) : "Unknown";
906 }
907
908 uint32_t
909 LV2Plugin::num_ports() const
910 {
911         return lilv_plugin_get_num_ports(_impl->plugin);
912 }
913
914 uint32_t
915 LV2Plugin::parameter_count() const
916 {
917         return lilv_plugin_get_num_ports(_impl->plugin);
918 }
919
920 float
921 LV2Plugin::default_value(uint32_t port)
922 {
923         return _defaults[port];
924 }
925
926 const char*
927 LV2Plugin::port_symbol(uint32_t index) const
928 {
929         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, index);
930         if (!port) {
931                 error << name() << ": Invalid port index " << index << endmsg;
932         }
933
934         const LilvNode* sym = lilv_port_get_symbol(_impl->plugin, port);
935         return lilv_node_as_string(sym);
936 }
937
938 uint32_t
939 LV2Plugin::port_index (const char* symbol) const
940 {
941         const map<string, uint32_t>::const_iterator i = _port_indices.find(symbol);
942         if (i != _port_indices.end()) {
943                 return  i->second;
944         } else {
945                 warning << string_compose(_("LV2: Unknown port %1"), symbol) << endmsg;
946                 return (uint32_t)-1;
947         }
948 }
949
950 void
951 LV2Plugin::set_parameter(uint32_t which, float val)
952 {
953         DEBUG_TRACE(DEBUG::LV2, string_compose(
954                             "%1 set parameter %2 to %3\n", name(), which, val));
955
956         if (which < lilv_plugin_get_num_ports(_impl->plugin)) {
957                 if (get_parameter (which) == val) {
958                         return;
959                 }
960
961                 _shadow_data[which] = val;
962         } else {
963                 warning << string_compose(
964                     _("Illegal parameter number used with plugin \"%1\". "
965                       "This is a bug in either %2 or the LV2 plugin <%3>"),
966                     name(), PROGRAM_NAME, unique_id()) << endmsg;
967         }
968
969         Plugin::set_parameter(which, val);
970 }
971
972 float
973 LV2Plugin::get_parameter(uint32_t which) const
974 {
975         if (parameter_is_input(which)) {
976                 return (float)_shadow_data[which];
977         } else {
978                 return (float)_control_data[which];
979         }
980         return 0.0f;
981 }
982
983 std::string
984 LV2Plugin::get_docs() const
985 {
986         LilvNodes* comments = lilv_plugin_get_value(_impl->plugin, _world.rdfs_comment);
987         if (comments) {
988                 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
989                 lilv_nodes_free(comments);
990                 return docs;
991         }
992
993         return "";
994 }
995
996 std::string
997 LV2Plugin::get_parameter_docs(uint32_t which) const
998 {
999         LilvNodes* comments = lilv_port_get_value(
1000                 _impl->plugin,
1001                 lilv_plugin_get_port_by_index(_impl->plugin, which),
1002                 _world.rdfs_comment);
1003
1004         if (comments) {
1005                 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
1006                 lilv_nodes_free(comments);
1007                 return docs;
1008         }
1009
1010         return "";
1011 }
1012
1013 uint32_t
1014 LV2Plugin::nth_parameter(uint32_t n, bool& ok) const
1015 {
1016         ok = false;
1017         for (uint32_t c = 0, x = 0; x < lilv_plugin_get_num_ports(_impl->plugin); ++x) {
1018                 if (parameter_is_control(x)) {
1019                         if (c++ == n) {
1020                                 ok = true;
1021                                 return x;
1022                         }
1023                 }
1024         }
1025
1026         return 0;
1027 }
1028
1029 const void*
1030 LV2Plugin::extension_data(const char* uri) const
1031 {
1032         return lilv_instance_get_extension_data(_impl->instance, uri);
1033 }
1034
1035 const void*
1036 LV2Plugin::c_plugin()
1037 {
1038         return _impl->plugin;
1039 }
1040
1041 const void*
1042 LV2Plugin::c_ui()
1043 {
1044         return (const void*)_impl->ui;
1045 }
1046
1047 const void*
1048 LV2Plugin::c_ui_type()
1049 {
1050         return (const void*)_impl->ui_type;
1051 }
1052
1053 /** Directory for all plugin state. */
1054 const std::string
1055 LV2Plugin::plugin_dir() const
1056 {
1057         if (!_plugin_state_dir.empty ()){
1058                 return Glib::build_filename(_plugin_state_dir, _insert_id.to_s());
1059         } else {
1060                 return Glib::build_filename(_session.plugins_dir(), _insert_id.to_s());
1061         }
1062 }
1063
1064 /** Directory for files created by the plugin (except during save). */
1065 const std::string
1066 LV2Plugin::scratch_dir() const
1067 {
1068         return Glib::build_filename(plugin_dir(), "scratch");
1069 }
1070
1071 /** Directory for snapshots of files in the scratch directory. */
1072 const std::string
1073 LV2Plugin::file_dir() const
1074 {
1075         return Glib::build_filename(plugin_dir(), "files");
1076 }
1077
1078 /** Directory to save state snapshot version @c num into. */
1079 const std::string
1080 LV2Plugin::state_dir(unsigned num) const
1081 {
1082         return Glib::build_filename(plugin_dir(), string_compose("state%1", num));
1083 }
1084
1085 /** Implementation of state:makePath for files created at instantiation time.
1086  * Note this is not used for files created at save time (Lilv deals with that).
1087  */
1088 char*
1089 LV2Plugin::lv2_state_make_path(LV2_State_Make_Path_Handle handle,
1090                                const char*                path)
1091 {
1092         LV2Plugin* me = (LV2Plugin*)handle;
1093         if (me->_insert_id == PBD::ID("0")) {
1094                 warning << string_compose(
1095                         "File path \"%1\" requested but LV2 %2 has no insert ID",
1096                         path, me->name()) << endmsg;
1097                 return g_strdup(path);
1098         }
1099
1100         const std::string abs_path = Glib::build_filename(me->scratch_dir(), path);
1101         const std::string dirname  = Glib::path_get_dirname(abs_path);
1102         g_mkdir_with_parents(dirname.c_str(), 0744);
1103
1104         DEBUG_TRACE(DEBUG::LV2, string_compose("new file path %1 => %2\n",
1105                                                path, abs_path));
1106
1107         return g_strndup(abs_path.c_str(), abs_path.length());
1108 }
1109
1110 void
1111 LV2Plugin::add_state(XMLNode* root) const
1112 {
1113         assert(_insert_id != PBD::ID("0"));
1114
1115         XMLNode*    child;
1116         char        buf[32];
1117         LocaleGuard lg(X_("C"));
1118
1119         for (uint32_t i = 0; i < parameter_count(); ++i) {
1120                 if (parameter_is_input(i) && parameter_is_control(i)) {
1121                         child = new XMLNode("Port");
1122                         child->add_property("symbol", port_symbol(i));
1123                         snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
1124                         child->add_property("value", string(buf));
1125                         root->add_child_nocopy(*child);
1126                 }
1127         }
1128
1129         if (!_plugin_state_dir.empty()) {
1130                 root->add_property("template-dir", _plugin_state_dir);
1131         }
1132
1133         if (_has_state_interface) {
1134                 // Provisionally increment state version and create directory
1135                 const std::string new_dir = state_dir(++_state_version);
1136                 g_mkdir_with_parents(new_dir.c_str(), 0744);
1137
1138                 LilvState* state = lilv_state_new_from_instance(
1139                         _impl->plugin,
1140                         _impl->instance,
1141                         _uri_map.urid_map(),
1142                         scratch_dir().c_str(),
1143                         file_dir().c_str(),
1144                         _session.externals_dir().c_str(),
1145                         new_dir.c_str(),
1146                         NULL,
1147                         const_cast<LV2Plugin*>(this),
1148                         0,
1149                         NULL);
1150
1151                 if (!_plugin_state_dir.empty()
1152                     || !_impl->state
1153                     || !lilv_state_equals(state, _impl->state)) {
1154                         lilv_state_save(_world.world,
1155                                         _uri_map.urid_map(),
1156                                         _uri_map.urid_unmap(),
1157                                         state,
1158                                         NULL,
1159                                         new_dir.c_str(),
1160                                         "state.ttl");
1161
1162                         if (_plugin_state_dir.empty()) {
1163                                 // normal session save
1164                                 lilv_state_free(_impl->state);
1165                                 _impl->state = state;
1166                         } else {
1167                                 // template save (dedicated state-dir)
1168                                 lilv_state_free(state);
1169                         }
1170                 } else {
1171                         // State is identical, decrement version and nuke directory
1172                         lilv_state_free(state);
1173                         PBD::remove_directory(new_dir);
1174                         --_state_version;
1175                 }
1176
1177                 root->add_property("state-dir", string_compose("state%1", _state_version));
1178         }
1179 }
1180
1181 // TODO: Once we can rely on lilv 0.16.0, lilv_world_get can replace this
1182 static LilvNode*
1183 get_value(LilvWorld* world, const LilvNode* subject, const LilvNode* predicate)
1184 {
1185         LilvNodes* vs = lilv_world_find_nodes(world, subject, predicate, NULL);
1186         if (vs) {
1187                 LilvNode* node = lilv_node_duplicate(lilv_nodes_get_first(vs));
1188                 lilv_nodes_free(vs);
1189                 return node;
1190         }
1191         return NULL;
1192 }
1193
1194 void
1195 LV2Plugin::find_presets()
1196 {
1197         LilvNode* lv2_appliesTo = lilv_new_uri(_world.world, LV2_CORE__appliesTo);
1198         LilvNode* pset_Preset   = lilv_new_uri(_world.world, LV2_PRESETS__Preset);
1199         LilvNode* rdfs_label    = lilv_new_uri(_world.world, LILV_NS_RDFS "label");
1200
1201         LilvNodes* presets = lilv_plugin_get_related(_impl->plugin, pset_Preset);
1202         LILV_FOREACH(nodes, i, presets) {
1203                 const LilvNode* preset = lilv_nodes_get(presets, i);
1204                 lilv_world_load_resource(_world.world, preset);
1205                 LilvNode* name = get_value(_world.world, preset, rdfs_label);
1206                 bool userpreset = true; // TODO
1207                 if (name) {
1208                         _presets.insert(std::make_pair(lilv_node_as_string(preset),
1209                                                        Plugin::PresetRecord(
1210                                                                lilv_node_as_string(preset),
1211                                                                lilv_node_as_string(name),
1212                                                                userpreset)));
1213                         lilv_node_free(name);
1214                 } else {
1215                         warning << string_compose(
1216                             _("Plugin \"%1\" preset \"%2\" is missing a label\n"),
1217                             lilv_node_as_string(lilv_plugin_get_uri(_impl->plugin)),
1218                             lilv_node_as_string(preset)) << endmsg;
1219                 }
1220         }
1221         lilv_nodes_free(presets);
1222
1223         lilv_node_free(rdfs_label);
1224         lilv_node_free(pset_Preset);
1225         lilv_node_free(lv2_appliesTo);
1226 }
1227
1228 static void
1229 set_port_value(const char* port_symbol,
1230                void*       user_data,
1231                const void* value,
1232                uint32_t    /*size*/,
1233                uint32_t    type)
1234 {
1235         LV2Plugin* self = (LV2Plugin*)user_data;
1236         if (type != 0 && type != URIMap::instance().urids.atom_Float) {
1237                 return;  // TODO: Support non-float ports
1238         }
1239
1240         const uint32_t port_index = self->port_index(port_symbol);
1241         if (port_index != (uint32_t)-1) {
1242                 self->set_parameter(port_index, *(const float*)value);
1243         }
1244 }
1245
1246 bool
1247 LV2Plugin::load_preset(PresetRecord r)
1248 {
1249         LilvWorld* world = _world.world;
1250         LilvNode*  pset  = lilv_new_uri(world, r.uri.c_str());
1251         LilvState* state = lilv_state_new_from_world(world, _uri_map.urid_map(), pset);
1252
1253         if (state) {
1254                 lilv_state_restore(state, _impl->instance, set_port_value, this, 0, NULL);
1255                 lilv_state_free(state);
1256                 Plugin::load_preset(r);
1257         }
1258
1259         lilv_node_free(pset);
1260         return state;
1261 }
1262
1263 const void*
1264 ARDOUR::lv2plugin_get_port_value(const char* port_symbol,
1265                                  void*       user_data,
1266                                  uint32_t*   size,
1267                                  uint32_t*   type)
1268 {
1269         LV2Plugin *plugin = (LV2Plugin *) user_data;
1270
1271         uint32_t index = plugin->port_index(port_symbol);
1272         if (index != (uint32_t) -1) {
1273                 if (plugin->parameter_is_input(index) && plugin->parameter_is_control(index)) {
1274                         float *value;
1275                         *size = sizeof(float);
1276                         *type = plugin->_uri_map.uri_to_id(LV2_ATOM__Float);
1277                         value = &plugin->_shadow_data[index];
1278
1279                         return value;
1280                 }
1281         }
1282
1283         *size = *type = 0;
1284         return NULL;
1285 }
1286
1287
1288 std::string
1289 LV2Plugin::do_save_preset(string name)
1290 {
1291         LilvNode*    plug_name = lilv_plugin_get_name(_impl->plugin);
1292         const string prefix    = legalize_for_uri(lilv_node_as_string(plug_name));
1293         const string base_name = legalize_for_uri(name);
1294         const string file_name = base_name + ".ttl";
1295         const string bundle    = Glib::build_filename(
1296                 Glib::get_home_dir(),
1297                 Glib::build_filename(".lv2", prefix + "_" + base_name + ".lv2"));
1298
1299 #ifdef HAVE_LILV_0_21_3
1300         /* delete reference to old preset (if any) */
1301         const PresetRecord* r = preset_by_label(name);
1302         if (r) {
1303                 LilvNode*  pset  = lilv_new_uri (_world.world, r->uri.c_str());
1304                 if (pset) {
1305                         lilv_world_unload_resource (_world.world, pset);
1306                         lilv_node_free(pset);
1307                 }
1308         }
1309 #endif
1310
1311         LilvState* state = lilv_state_new_from_instance(
1312                 _impl->plugin,
1313                 _impl->instance,
1314                 _uri_map.urid_map(),
1315                 scratch_dir().c_str(),                   // file_dir
1316                 bundle.c_str(),                          // copy_dir
1317                 bundle.c_str(),                          // link_dir
1318                 bundle.c_str(),                          // save_dir
1319                 lv2plugin_get_port_value,                // get_value
1320                 (void*)this,                             // user_data
1321                 LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE,  // flags
1322                 _features                                // features
1323         );
1324
1325         lilv_state_set_label(state, name.c_str());
1326         lilv_state_save(
1327                 _world.world,           // world
1328                 _uri_map.urid_map(),    // map
1329                 _uri_map.urid_unmap(),  // unmap
1330                 state,                  // state
1331                 NULL,                   // uri (NULL = use file URI)
1332                 bundle.c_str(),         // dir
1333                 file_name.c_str()       // filename
1334         );
1335
1336         lilv_state_free(state);
1337
1338         std::string uri = Glib::filename_to_uri(Glib::build_filename(bundle, file_name));
1339         LilvNode *node_bundle = lilv_new_uri(_world.world, Glib::filename_to_uri(Glib::build_filename(bundle, "/")).c_str());
1340         LilvNode *node_preset = lilv_new_uri(_world.world, uri.c_str());
1341 #ifdef HAVE_LILV_0_21_3
1342         lilv_world_unload_resource(_world.world, node_preset);
1343         lilv_world_unload_bundle(_world.world, node_bundle);
1344 #endif
1345         lilv_world_load_bundle(_world.world, node_bundle);
1346         lilv_world_load_resource(_world.world, node_preset);
1347         lilv_node_free(node_bundle);
1348         lilv_node_free(node_preset);
1349         lilv_node_free(plug_name);
1350         return uri;
1351 }
1352
1353 void
1354 LV2Plugin::do_remove_preset(string name)
1355 {
1356 #ifdef HAVE_LILV_0_21_3
1357         /* Look up preset record by label (FIXME: ick, label as ID) */
1358         const PresetRecord* r = preset_by_label(name);
1359         if (!r) {
1360                 return;
1361         }
1362
1363         /* Load a LilvState for the preset. */
1364         LilvWorld* world = _world.world;
1365         LilvNode*  pset  = lilv_new_uri(world, r->uri.c_str());
1366         LilvState* state = lilv_state_new_from_world(world, _uri_map.urid_map(), pset);
1367         if (!state) {
1368                 lilv_node_free(pset);
1369                 return;
1370         }
1371
1372         /* Unload preset from world. */
1373         lilv_world_unload_resource(world, pset);
1374
1375         /* Delete it from the file system.  This will remove the preset file and the entry
1376            from the manifest.  If this results in an empty manifest (i.e. the
1377            preset is the only thing in the bundle), then the bundle is removed. */
1378         lilv_state_delete(world, state);
1379
1380         lilv_state_free(state);
1381         lilv_node_free(pset);
1382 #endif
1383         /* Without lilv_state_delete(), we could delete the preset file, but this
1384            would leave a broken bundle/manifest around, so the preset would still
1385            be visible, but broken.  Naively deleting a bundle is too dangerous, so
1386            we simply do not support preset deletion with older Lilv */
1387 }
1388
1389 bool
1390 LV2Plugin::has_editor() const
1391 {
1392         return _impl->ui != NULL;
1393 }
1394
1395 bool
1396 LV2Plugin::has_message_output() const
1397 {
1398         for (uint32_t i = 0; i < num_ports(); ++i) {
1399                 if ((_port_flags[i] & PORT_SEQUENCE) &&
1400                     (_port_flags[i] & PORT_OUTPUT)) {
1401                         return true;
1402                 }
1403         }
1404         return false;
1405 }
1406
1407 bool
1408 LV2Plugin::write_to(RingBuffer<uint8_t>* dest,
1409                     uint32_t             index,
1410                     uint32_t             protocol,
1411                     uint32_t             size,
1412                     const uint8_t*       body)
1413 {
1414         const uint32_t  buf_size = sizeof(UIMessage) + size;
1415         vector<uint8_t> buf(buf_size);
1416
1417         UIMessage* msg = (UIMessage*)&buf[0];
1418         msg->index    = index;
1419         msg->protocol = protocol;
1420         msg->size     = size;
1421         memcpy(msg + 1, body, size);
1422
1423         return (dest->write(&buf[0], buf_size) == buf_size);
1424 }
1425
1426 bool
1427 LV2Plugin::write_from_ui(uint32_t       index,
1428                          uint32_t       protocol,
1429                          uint32_t       size,
1430                          const uint8_t* body)
1431 {
1432         if (!_from_ui) {
1433                 size_t rbs = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
1434                 /* buffer data communication from plugin UI to plugin instance.
1435                  * this buffer needs to potentially hold
1436                  *   (port's minimumSize) * (audio-periods) / (UI-periods)
1437                  * bytes.
1438                  *
1439                  *  e.g 48kSPS / 128fpp -> audio-periods = 375 Hz
1440                  *  ui-periods = 25 Hz (SuperRapidScreenUpdate)
1441                  *  default minimumSize = 32K (see LV2Plugin::allocate_atom_event_buffers()
1442                  *
1443                  * it is NOT safe to overflow (msg.size will be misinterpreted)
1444                  */
1445                 uint32_t bufsiz = 32768;
1446                 if (_atom_ev_buffers && _atom_ev_buffers[0]) {
1447                         bufsiz =  lv2_evbuf_get_capacity(_atom_ev_buffers[0]);
1448                 }
1449                 rbs = max((size_t) bufsiz * 8, rbs);
1450                 _from_ui = new RingBuffer<uint8_t>(rbs);
1451         }
1452
1453         if (!write_to(_from_ui, index, protocol, size, body)) {
1454                 error << "Error writing from UI to plugin" << endmsg;
1455                 return false;
1456         }
1457         return true;
1458 }
1459
1460 bool
1461 LV2Plugin::write_to_ui(uint32_t       index,
1462                        uint32_t       protocol,
1463                        uint32_t       size,
1464                        const uint8_t* body)
1465 {
1466         if (!write_to(_to_ui, index, protocol, size, body)) {
1467                 error << "Error writing from plugin to UI" << endmsg;
1468                 return false;
1469         }
1470         return true;
1471 }
1472
1473 static void
1474 forge_variant(LV2_Atom_Forge* forge, const Variant& value)
1475 {
1476         switch (value.type()) {
1477         case Variant::NOTHING:
1478                 break;
1479         case Variant::BEATS:
1480                 // No atom type for this, just forge a double
1481                 lv2_atom_forge_double(forge, value.get_beats().to_double());
1482                 break;
1483         case Variant::BOOL:
1484                 lv2_atom_forge_bool(forge, value.get_bool());
1485                 break;
1486         case Variant::DOUBLE:
1487                 lv2_atom_forge_double(forge, value.get_double());
1488                 break;
1489         case Variant::FLOAT:
1490                 lv2_atom_forge_float(forge, value.get_float());
1491                 break;
1492         case Variant::INT:
1493                 lv2_atom_forge_int(forge, value.get_int());
1494                 break;
1495         case Variant::LONG:
1496                 lv2_atom_forge_long(forge, value.get_long());
1497                 break;
1498         case Variant::PATH:
1499                 lv2_atom_forge_path(
1500                         forge, value.get_path().c_str(), value.get_path().size());
1501                 break;
1502         case Variant::STRING:
1503                 lv2_atom_forge_string(
1504                         forge, value.get_string().c_str(), value.get_string().size());
1505                 break;
1506         case Variant::URI:
1507                 lv2_atom_forge_uri(
1508                         forge, value.get_uri().c_str(), value.get_uri().size());
1509                 break;
1510         }
1511 }
1512
1513 /** Get a variant type from a URI, return false iff no match found. */
1514 static bool
1515 uri_to_variant_type(const std::string& uri, Variant::Type& type)
1516 {
1517         if (uri == LV2_ATOM__Bool) {
1518                 type = Variant::BOOL;
1519         } else if (uri == LV2_ATOM__Double) {
1520                 type = Variant::DOUBLE;
1521         } else if (uri == LV2_ATOM__Float) {
1522                 type = Variant::FLOAT;
1523         } else if (uri == LV2_ATOM__Int) {
1524                 type = Variant::INT;
1525         } else if (uri == LV2_ATOM__Long) {
1526                 type = Variant::LONG;
1527         } else if (uri == LV2_ATOM__Path) {
1528                 type = Variant::PATH;
1529         } else if (uri == LV2_ATOM__String) {
1530                 type = Variant::STRING;
1531         } else if (uri == LV2_ATOM__URI) {
1532                 type = Variant::URI;
1533         } else {
1534                 return false;
1535         }
1536         return true;
1537 }
1538
1539 void
1540 LV2Plugin::set_property(uint32_t key, const Variant& value)
1541 {
1542         if (_patch_port_in_index == (uint32_t)-1) {
1543                 error << "LV2: set_property called with unset patch_port_in_index" << endmsg;
1544                 return;
1545         } else if (value.type() == Variant::NOTHING) {
1546                 error << "LV2: set_property called with void value" << endmsg;
1547                 return;
1548         }
1549
1550         // Set up forge to write to temporary buffer on the stack
1551         LV2_Atom_Forge*      forge = &_impl->ui_forge;
1552         LV2_Atom_Forge_Frame frame;
1553         uint8_t              buf[PATH_MAX];  // Ought to be enough for anyone...
1554
1555         lv2_atom_forge_set_buffer(forge, buf, sizeof(buf));
1556
1557         // Serialize patch:Set message to set property
1558 #ifdef HAVE_LV2_1_10_0
1559         lv2_atom_forge_object(forge, &frame, 1, _uri_map.urids.patch_Set);
1560         lv2_atom_forge_key(forge, _uri_map.urids.patch_property);
1561         lv2_atom_forge_urid(forge, key);
1562         lv2_atom_forge_key(forge, _uri_map.urids.patch_value);
1563 #else
1564         lv2_atom_forge_blank(forge, &frame, 1, _uri_map.urids.patch_Set);
1565         lv2_atom_forge_property_head(forge, _uri_map.urids.patch_property, 0);
1566         lv2_atom_forge_urid(forge, key);
1567         lv2_atom_forge_property_head(forge, _uri_map.urids.patch_value, 0);
1568 #endif
1569
1570         forge_variant(forge, value);
1571
1572         // Write message to UI=>Plugin ring
1573         const LV2_Atom* const atom = (const LV2_Atom*)buf;
1574         write_from_ui(_patch_port_in_index,
1575                       _uri_map.urids.atom_eventTransfer,
1576                       lv2_atom_total_size(atom),
1577                       (const uint8_t*)atom);
1578 }
1579
1580 const ParameterDescriptor&
1581 LV2Plugin::get_property_descriptor(uint32_t id) const
1582 {
1583         PropertyDescriptors::const_iterator p = _property_descriptors.find(id);
1584         if (p != _property_descriptors.end()) {
1585                 return p->second;
1586         }
1587         return Plugin::get_property_descriptor(id);
1588 }
1589
1590 static void
1591 load_parameter_descriptor_units(LilvWorld* lworld, ParameterDescriptor& desc, const LilvNodes* units)
1592 {
1593         if (lilv_nodes_contains(units, _world.units_midiNote)) {
1594                 desc.unit = ParameterDescriptor::MIDI_NOTE;
1595         } else if (lilv_nodes_contains(units, _world.units_db)) {
1596                 desc.unit = ParameterDescriptor::DB;
1597         } else if (lilv_nodes_contains(units, _world.units_hz)) {
1598                 desc.unit = ParameterDescriptor::HZ;
1599         }
1600         if (lilv_nodes_size(units) > 0) {
1601                 const LilvNode* unit = lilv_nodes_get_first(units);
1602                 LilvNode* render = get_value(lworld, unit, _world.units_render);
1603                 if (render) {
1604                         desc.print_fmt = lilv_node_as_string(render);
1605                         lilv_node_free(render);
1606                 }
1607         }
1608 }
1609
1610 static void
1611 load_parameter_descriptor(LV2World&            world,
1612                           ParameterDescriptor& desc,
1613                           Variant::Type        datatype,
1614                           const LilvNode*      subject)
1615 {
1616         LilvWorld* lworld  = _world.world;
1617         LilvNode*  label   = get_value(lworld, subject, _world.rdfs_label);
1618         LilvNode*  def     = get_value(lworld, subject, _world.lv2_default);
1619         LilvNode*  minimum = get_value(lworld, subject, _world.lv2_minimum);
1620         LilvNode*  maximum = get_value(lworld, subject, _world.lv2_maximum);
1621         LilvNodes* units   = lilv_world_find_nodes(lworld, subject, _world.units_unit, NULL);
1622         if (label) {
1623                 desc.label = lilv_node_as_string(label);
1624         }
1625         if (def && lilv_node_is_float(def)) {
1626                 desc.normal = lilv_node_as_float(def);
1627         }
1628         if (minimum && lilv_node_is_float(minimum)) {
1629                 desc.lower = lilv_node_as_float(minimum);
1630         }
1631         if (maximum && lilv_node_is_float(maximum)) {
1632                 desc.upper = lilv_node_as_float(maximum);
1633         }
1634         load_parameter_descriptor_units(lworld, desc, units);
1635         desc.datatype      = datatype;
1636         desc.toggled      |= datatype == Variant::BOOL;
1637         desc.integer_step |= datatype == Variant::INT || datatype == Variant::LONG;
1638         desc.update_steps();
1639
1640         lilv_nodes_free(units);
1641         lilv_node_free(label);
1642         lilv_node_free(def);
1643         lilv_node_free(minimum);
1644         lilv_node_free(maximum);
1645 }
1646
1647 void
1648 LV2Plugin::load_supported_properties(PropertyDescriptors& descs)
1649 {
1650         LilvWorld*       lworld     = _world.world;
1651         const LilvNode*  subject    = lilv_plugin_get_uri(_impl->plugin);
1652         LilvNodes*       properties = lilv_world_find_nodes(
1653                 lworld, subject, _world.patch_writable, NULL);
1654         LILV_FOREACH(nodes, p, properties) {
1655                 // Get label and range
1656                 const LilvNode* prop  = lilv_nodes_get(properties, p);
1657                 LilvNode*       range = get_value(lworld, prop, _world.rdfs_range);
1658                 if (!range) {
1659                         warning << string_compose(_("LV2: property <%1> has no range datatype, ignoring"),
1660                                                   lilv_node_as_uri(prop)) << endmsg;
1661                         continue;
1662                 }
1663
1664                 // Convert range to variant type (TODO: support for multiple range types)
1665                 Variant::Type datatype;
1666                 if (!uri_to_variant_type(lilv_node_as_uri(range), datatype)) {
1667                         error << string_compose(_("LV2: property <%1> has unsupported datatype <%1>"),
1668                                                 lilv_node_as_uri(prop), lilv_node_as_uri(range)) << endmsg;
1669                         continue;
1670                 }
1671
1672                 // Add description to result
1673                 ParameterDescriptor desc;
1674                 desc.key      = _uri_map.uri_to_id(lilv_node_as_uri(prop));
1675                 desc.datatype = datatype;
1676                 load_parameter_descriptor(_world, desc, datatype, prop);
1677                 descs.insert(std::make_pair(desc.key, desc));
1678
1679                 lilv_node_free(range);
1680         }
1681         lilv_nodes_free(properties);
1682 }
1683
1684 void
1685 LV2Plugin::announce_property_values()
1686 {
1687         if (_patch_port_in_index == (uint32_t)-1) {
1688                 return;
1689         }
1690
1691         // Set up forge to write to temporary buffer on the stack
1692         LV2_Atom_Forge*      forge = &_impl->ui_forge;
1693         LV2_Atom_Forge_Frame frame;
1694         uint8_t              buf[PATH_MAX];  // Ought to be enough for anyone...
1695
1696         lv2_atom_forge_set_buffer(forge, buf, sizeof(buf));
1697
1698         // Serialize patch:Get message with no subject (implicitly plugin instance)
1699 #ifdef HAVE_LV2_1_10_0
1700         lv2_atom_forge_object(forge, &frame, 1, _uri_map.urids.patch_Get);
1701 #else
1702         lv2_atom_forge_blank(forge, &frame, 1, _uri_map.urids.patch_Get);
1703 #endif
1704
1705         // Write message to UI=>Plugin ring
1706         const LV2_Atom* const atom = (const LV2_Atom*)buf;
1707         write_from_ui(_patch_port_in_index,
1708                       _uri_map.urids.atom_eventTransfer,
1709                       lv2_atom_total_size(atom),
1710                       (const uint8_t*)atom);
1711 }
1712
1713 void
1714 LV2Plugin::enable_ui_emission()
1715 {
1716         if (!_to_ui) {
1717                 /* see note in LV2Plugin::write_from_ui() */
1718                 uint32_t bufsiz = 32768;
1719                 if (_atom_ev_buffers && _atom_ev_buffers[0]) {
1720                         bufsiz =  lv2_evbuf_get_capacity(_atom_ev_buffers[0]);
1721                 }
1722                 size_t rbs = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
1723                 rbs = max((size_t) bufsiz * 8, rbs);
1724                 _to_ui = new RingBuffer<uint8_t>(rbs);
1725         }
1726 }
1727
1728 void
1729 LV2Plugin::emit_to_ui(void* controller, UIMessageSink sink)
1730 {
1731         if (!_to_ui) {
1732                 return;
1733         }
1734
1735         uint32_t read_space = _to_ui->read_space();
1736         while (read_space > sizeof(UIMessage)) {
1737                 UIMessage msg;
1738                 if (_to_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1739                         error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1740                         break;
1741                 }
1742                 vector<uint8_t> body(msg.size);
1743                 if (_to_ui->read(&body[0], msg.size) != msg.size) {
1744                         error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1745                         break;
1746                 }
1747
1748                 sink(controller, msg.index, msg.size, msg.protocol, &body[0]);
1749
1750                 read_space -= sizeof(msg) + msg.size;
1751         }
1752 }
1753
1754 int
1755 LV2Plugin::work(uint32_t size, const void* data)
1756 {
1757         return _impl->work_iface->work(
1758                 _impl->instance->lv2_handle, work_respond, this, size, data);
1759 }
1760
1761 int
1762 LV2Plugin::work_response(uint32_t size, const void* data)
1763 {
1764         return _impl->work_iface->work_response(
1765                 _impl->instance->lv2_handle, size, data);
1766 }
1767
1768 void
1769 LV2Plugin::set_insert_id(PBD::ID id)
1770 {
1771         if (_insert_id == "0") {
1772                 _insert_id = id;
1773         } else if (_insert_id != id) {
1774                 lilv_state_free(_impl->state);
1775                 _impl->state = NULL;
1776                 _insert_id   = id;
1777         }
1778 }
1779
1780 void
1781 LV2Plugin::set_state_dir (const std::string& d)
1782 {
1783         _plugin_state_dir = d;
1784 }
1785
1786 int
1787 LV2Plugin::set_state(const XMLNode& node, int version)
1788 {
1789         XMLNodeList          nodes;
1790         const XMLProperty*   prop;
1791         XMLNodeConstIterator iter;
1792         XMLNode*             child;
1793         const char*          sym;
1794         const char*          value;
1795         uint32_t             port_id;
1796         LocaleGuard          lg(X_("C"));
1797
1798         if (node.name() != state_node_name()) {
1799                 error << _("Bad node sent to LV2Plugin::set_state") << endmsg;
1800                 return -1;
1801         }
1802
1803 #ifndef NO_PLUGIN_STATE
1804
1805         if (version < 3000) {
1806                 nodes = node.children("port");
1807         } else {
1808                 nodes = node.children("Port");
1809         }
1810
1811         for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
1812
1813                 child = *iter;
1814
1815                 if ((prop = child->property("symbol")) != 0) {
1816                         sym = prop->value().c_str();
1817                 } else {
1818                         warning << _("LV2: port has no symbol, ignored") << endmsg;
1819                         continue;
1820                 }
1821
1822                 map<string, uint32_t>::iterator i = _port_indices.find(sym);
1823
1824                 if (i != _port_indices.end()) {
1825                         port_id = i->second;
1826                 } else {
1827                         warning << _("LV2: port has unknown index, ignored") << endmsg;
1828                         continue;
1829                 }
1830
1831                 if ((prop = child->property("value")) != 0) {
1832                         value = prop->value().c_str();
1833                 } else {
1834                         warning << _("LV2: port has no value, ignored") << endmsg;
1835                         continue;
1836                 }
1837
1838                 set_parameter(port_id, atof(value));
1839         }
1840
1841         if ((prop = node.property("template-dir")) != 0) {
1842                 set_state_dir (prop->value ());
1843         }
1844
1845         _state_version = 0;
1846         if ((prop = node.property("state-dir")) != 0) {
1847                 if (sscanf(prop->value().c_str(), "state%u", &_state_version) != 1) {
1848                         error << string_compose(
1849                                 "LV2: failed to parse state version from \"%1\"",
1850                                 prop->value()) << endmsg;
1851                 }
1852
1853                 std::string state_file = Glib::build_filename(
1854                         plugin_dir(),
1855                         Glib::build_filename(prop->value(), "state.ttl"));
1856
1857                 LilvState* state = lilv_state_new_from_file(
1858                         _world.world, _uri_map.urid_map(), NULL, state_file.c_str());
1859
1860                 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
1861                 lilv_state_free(_impl->state);
1862                 _impl->state = state;
1863         }
1864
1865         if (!_plugin_state_dir.empty ()) {
1866                 // force save with session, next time (increment counter)
1867                 lilv_state_free (_impl->state);
1868                 _impl->state = NULL;
1869                 set_state_dir ("");
1870         }
1871
1872         latency_compute_run();
1873 #endif
1874
1875         return Plugin::set_state(node, version);
1876 }
1877
1878 int
1879 LV2Plugin::get_parameter_descriptor(uint32_t which, ParameterDescriptor& desc) const
1880 {
1881         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, which);
1882         if (!port) {
1883                 error << string_compose("LV2: get descriptor of non-existent port %1", which)
1884                       << endmsg;
1885                 return 1;
1886         }
1887
1888         LilvNodes* portunits;
1889         LilvNode *def, *min, *max;
1890         lilv_port_get_range(_impl->plugin, port, &def, &min, &max);
1891         portunits = lilv_port_get_value(_impl->plugin, port, _world.units_unit);
1892
1893         // TODO: Once we can rely on lilv 0.18.0 being present,
1894         // load_parameter_descriptor() can be used for ports as well
1895         desc.integer_step = lilv_port_has_property(_impl->plugin, port, _world.lv2_integer);
1896         desc.toggled      = lilv_port_has_property(_impl->plugin, port, _world.lv2_toggled);
1897         desc.logarithmic  = lilv_port_has_property(_impl->plugin, port, _world.ext_logarithmic);
1898         desc.sr_dependent = lilv_port_has_property(_impl->plugin, port, _world.lv2_sampleRate);
1899         desc.label        = lilv_node_as_string(lilv_port_get_name(_impl->plugin, port));
1900         desc.normal       = def ? lilv_node_as_float(def) : 0.0f;
1901         desc.lower        = min ? lilv_node_as_float(min) : 0.0f;
1902         desc.upper        = max ? lilv_node_as_float(max) : 1.0f;
1903         load_parameter_descriptor_units(_world.world, desc, portunits);
1904
1905         if (desc.sr_dependent) {
1906                 desc.lower *= _session.frame_rate ();
1907                 desc.upper *= _session.frame_rate ();
1908         }
1909
1910         desc.min_unbound  = false; // TODO: LV2 extension required
1911         desc.max_unbound  = false; // TODO: LV2 extension required
1912
1913         desc.enumeration = lilv_port_has_property(_impl->plugin, port, _world.lv2_enumeration);
1914         desc.scale_points = get_scale_points(which);
1915
1916         desc.update_steps();
1917
1918         lilv_node_free(def);
1919         lilv_node_free(min);
1920         lilv_node_free(max);
1921         lilv_nodes_free(portunits);
1922
1923         return 0;
1924 }
1925
1926 string
1927 LV2Plugin::describe_parameter(Evoral::Parameter which)
1928 {
1929         if (( which.type() == PluginAutomation) && ( which.id() < parameter_count()) ) {
1930
1931                 if (lilv_port_has_property(_impl->plugin,
1932                                         lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.ext_notOnGUI)) {
1933                         return X_("hidden");
1934                 }
1935
1936                 if (lilv_port_has_property(_impl->plugin,
1937                                         lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_freewheeling)) {
1938                         return X_("hidden");
1939                 }
1940
1941                 if (lilv_port_has_property(_impl->plugin,
1942                                         lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_reportsLatency)) {
1943                         return X_("latency");
1944                 }
1945
1946                 LilvNode* name = lilv_port_get_name(_impl->plugin,
1947                                                     lilv_plugin_get_port_by_index(_impl->plugin, which.id()));
1948                 string ret(lilv_node_as_string(name));
1949                 lilv_node_free(name);
1950                 return ret;
1951         } else {
1952                 return "??";
1953         }
1954 }
1955
1956 framecnt_t
1957 LV2Plugin::signal_latency() const
1958 {
1959         if (_latency_control_port) {
1960                 return (framecnt_t)floor(*_latency_control_port);
1961         } else {
1962                 return 0;
1963         }
1964 }
1965
1966 set<Evoral::Parameter>
1967 LV2Plugin::automatable() const
1968 {
1969         set<Evoral::Parameter> ret;
1970
1971         for (uint32_t i = 0; i < parameter_count(); ++i) {
1972                 if (parameter_is_input(i) && parameter_is_control(i)) {
1973                         ret.insert(ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
1974                 }
1975         }
1976
1977         for (PropertyDescriptors::const_iterator p = _property_descriptors.begin();
1978              p != _property_descriptors.end();
1979              ++p) {
1980                 ret.insert(ret.end(), Evoral::Parameter(PluginPropertyAutomation, 0, p->first));
1981         }
1982         return ret;
1983 }
1984
1985 void
1986 LV2Plugin::set_automation_control (uint32_t i, boost::shared_ptr<AutomationControl> c)
1987 {
1988         if ((_port_flags[i] & PORT_CTRLED)) {
1989                 _ctrl_map [i] = AutomationCtrlPtr (new AutomationCtrl(c));
1990         }
1991 }
1992
1993 LV2Plugin::AutomationCtrlPtr
1994 LV2Plugin::get_automation_control (uint32_t i)
1995 {
1996         if (_ctrl_map.find (i) == _ctrl_map.end()) {
1997                 return AutomationCtrlPtr ();
1998         }
1999         return _ctrl_map[i];
2000 }
2001
2002 void
2003 LV2Plugin::activate()
2004 {
2005         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 activate\n", name()));
2006
2007         if (!_was_activated) {
2008                 lilv_instance_activate(_impl->instance);
2009                 _was_activated = true;
2010         }
2011 }
2012
2013 void
2014 LV2Plugin::deactivate()
2015 {
2016         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 deactivate\n", name()));
2017
2018         if (_was_activated) {
2019                 lilv_instance_deactivate(_impl->instance);
2020                 _was_activated = false;
2021         }
2022 }
2023
2024 void
2025 LV2Plugin::cleanup()
2026 {
2027         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 cleanup\n", name()));
2028
2029         deactivate();
2030         lilv_instance_free(_impl->instance);
2031         _impl->instance = NULL;
2032 }
2033
2034 void
2035 LV2Plugin::allocate_atom_event_buffers()
2036 {
2037         /* reserve local scratch buffers for ATOM event-queues */
2038         const LilvPlugin* p = _impl->plugin;
2039
2040         /* count non-MIDI atom event-ports
2041          * TODO: nicely ask drobilla to make a lilv_ call for that
2042          */
2043         int count_atom_out = 0;
2044         int count_atom_in = 0;
2045         int minimumSize = 32768; // TODO use a per-port minimum-size
2046         for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
2047                 const LilvPort* port  = lilv_plugin_get_port_by_index(p, i);
2048                 if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
2049                         LilvNodes* buffer_types = lilv_port_get_value(
2050                                 p, port, _world.atom_bufferType);
2051                         LilvNodes* atom_supports = lilv_port_get_value(
2052                                 p, port, _world.atom_supports);
2053
2054                         if (!lilv_nodes_contains(buffer_types, _world.atom_Sequence)
2055                                         || !lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
2056                                 if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
2057                                         count_atom_in++;
2058                                 }
2059                                 if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
2060                                         count_atom_out++;
2061                                 }
2062                                 LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
2063                                 LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
2064                                 if (min_size && lilv_node_is_int(min_size)) {
2065                                         minimumSize = std::max(minimumSize, lilv_node_as_int(min_size));
2066                                 }
2067                                 lilv_nodes_free(min_size_v);
2068                         }
2069                         lilv_nodes_free(buffer_types);
2070                         lilv_nodes_free(atom_supports);
2071                 }
2072         }
2073
2074         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 need buffers for %2 atom-in and %3 atom-out event-ports\n",
2075                                 name(), count_atom_in, count_atom_out));
2076
2077         const int total_atom_buffers = (count_atom_in + count_atom_out);
2078         if (_atom_ev_buffers || total_atom_buffers == 0) {
2079                 return;
2080         }
2081
2082         DEBUG_TRACE(DEBUG::LV2, string_compose("allocate %1 atom_ev_buffers of %d bytes\n", total_atom_buffers, minimumSize));
2083         _atom_ev_buffers = (LV2_Evbuf**) malloc((total_atom_buffers + 1) * sizeof(LV2_Evbuf*));
2084         for (int i = 0; i < total_atom_buffers; ++i ) {
2085                 _atom_ev_buffers[i] = lv2_evbuf_new(minimumSize, LV2_EVBUF_ATOM,
2086                                 _uri_map.urids.atom_Chunk, _uri_map.urids.atom_Sequence);
2087         }
2088         _atom_ev_buffers[total_atom_buffers] = 0;
2089         return;
2090 }
2091
2092 /** Write an ardour position/time/tempo/meter as an LV2 event.
2093  * @return true on success.
2094  */
2095 static bool
2096 write_position(LV2_Atom_Forge*     forge,
2097                LV2_Evbuf*          buf,
2098                const TempoMetric&  t,
2099                Timecode::BBT_Time& bbt,
2100                double              speed,
2101                framepos_t          position,
2102                framecnt_t          offset)
2103 {
2104         const URIMap::URIDs& urids = URIMap::instance().urids;
2105
2106         uint8_t pos_buf[256];
2107         lv2_atom_forge_set_buffer(forge, pos_buf, sizeof(pos_buf));
2108         LV2_Atom_Forge_Frame frame;
2109 #ifdef HAVE_LV2_1_10_0
2110         lv2_atom_forge_object(forge, &frame, 1, urids.time_Position);
2111         lv2_atom_forge_key(forge, urids.time_frame);
2112         lv2_atom_forge_long(forge, position);
2113         lv2_atom_forge_key(forge, urids.time_speed);
2114         lv2_atom_forge_float(forge, speed);
2115         lv2_atom_forge_key(forge, urids.time_barBeat);
2116         lv2_atom_forge_float(forge, bbt.beats - 1 +
2117                              (bbt.ticks / Timecode::BBT_Time::ticks_per_beat));
2118         lv2_atom_forge_key(forge, urids.time_bar);
2119         lv2_atom_forge_long(forge, bbt.bars - 1);
2120         lv2_atom_forge_key(forge, urids.time_beatUnit);
2121         lv2_atom_forge_int(forge, t.meter().note_divisor());
2122         lv2_atom_forge_key(forge, urids.time_beatsPerBar);
2123         lv2_atom_forge_float(forge, t.meter().divisions_per_bar());
2124         lv2_atom_forge_key(forge, urids.time_beatsPerMinute);
2125         lv2_atom_forge_float(forge, t.tempo().beats_per_minute());
2126 #else
2127         lv2_atom_forge_blank(forge, &frame, 1, urids.time_Position);
2128         lv2_atom_forge_property_head(forge, urids.time_frame, 0);
2129         lv2_atom_forge_long(forge, position);
2130         lv2_atom_forge_property_head(forge, urids.time_speed, 0);
2131         lv2_atom_forge_float(forge, speed);
2132         lv2_atom_forge_property_head(forge, urids.time_barBeat, 0);
2133         lv2_atom_forge_float(forge, bbt.beats - 1 +
2134                              (bbt.ticks / Timecode::BBT_Time::ticks_per_beat));
2135         lv2_atom_forge_property_head(forge, urids.time_bar, 0);
2136         lv2_atom_forge_long(forge, bbt.bars - 1);
2137         lv2_atom_forge_property_head(forge, urids.time_beatUnit, 0);
2138         lv2_atom_forge_int(forge, t.meter().note_divisor());
2139         lv2_atom_forge_property_head(forge, urids.time_beatsPerBar, 0);
2140         lv2_atom_forge_float(forge, t.meter().divisions_per_bar());
2141         lv2_atom_forge_property_head(forge, urids.time_beatsPerMinute, 0);
2142         lv2_atom_forge_float(forge, t.tempo().beats_per_minute());
2143 #endif
2144
2145         LV2_Evbuf_Iterator    end  = lv2_evbuf_end(buf);
2146         const LV2_Atom* const atom = (const LV2_Atom*)pos_buf;
2147         return lv2_evbuf_write(&end, offset, 0, atom->type, atom->size,
2148                                (const uint8_t*)(atom + 1));
2149 }
2150
2151 int
2152 LV2Plugin::connect_and_run(BufferSet& bufs,
2153         ChanMapping in_map, ChanMapping out_map,
2154         pframes_t nframes, framecnt_t offset)
2155 {
2156         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 run %2 offset %3\n", name(), nframes, offset));
2157         Plugin::connect_and_run(bufs, in_map, out_map, nframes, offset);
2158
2159         cycles_t then = get_cycles();
2160
2161         TempoMap&               tmap     = _session.tempo_map();
2162         Metrics::const_iterator metric_i = tmap.metrics_end();
2163         TempoMetric             tmetric  = tmap.metric_at(_session.transport_frame(), &metric_i);
2164
2165         if (_freewheel_control_port) {
2166                 *_freewheel_control_port = _session.engine().freewheeling() ? 1.f : 0.f;
2167         }
2168
2169         if (_bpm_control_port) {
2170                 *_bpm_control_port = tmetric.tempo().beats_per_minute();
2171         }
2172
2173 #ifdef LV2_EXTENDED
2174         if (_can_write_automation && _session.transport_frame() != _next_cycle_start) {
2175                 // add guard-points after locating
2176                 for (AutomationCtrlMap::iterator i = _ctrl_map.begin(); i != _ctrl_map.end(); ++i) {
2177                         i->second->guard = true;
2178                 }
2179         }
2180 #endif
2181
2182         ChanCount bufs_count;
2183         bufs_count.set(DataType::AUDIO, 1);
2184         bufs_count.set(DataType::MIDI, 1);
2185         BufferSet& silent_bufs  = _session.get_silent_buffers(bufs_count);
2186         BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
2187         uint32_t const num_ports = parameter_count();
2188         uint32_t const nil_index = std::numeric_limits<uint32_t>::max();
2189
2190         uint32_t audio_in_index  = 0;
2191         uint32_t audio_out_index = 0;
2192         uint32_t midi_in_index   = 0;
2193         uint32_t midi_out_index  = 0;
2194         uint32_t atom_port_index = 0;
2195         for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
2196                 void*     buf   = NULL;
2197                 uint32_t  index = nil_index;
2198                 PortFlags flags = _port_flags[port_index];
2199                 bool      valid = false;
2200                 if (flags & PORT_AUDIO) {
2201                         if (flags & PORT_INPUT) {
2202                                 index = in_map.get(DataType::AUDIO, audio_in_index++, &valid);
2203                                 buf = (valid)
2204                                         ? bufs.get_audio(index).data(offset)
2205                                         : silent_bufs.get_audio(0).data(offset);
2206                         } else {
2207                                 index = out_map.get(DataType::AUDIO, audio_out_index++, &valid);
2208                                 buf = (valid)
2209                                         ? bufs.get_audio(index).data(offset)
2210                                         : scratch_bufs.get_audio(0).data(offset);
2211                         }
2212                 } else if (flags & (PORT_EVENT|PORT_SEQUENCE)) {
2213                         /* FIXME: The checks here for bufs.count().n_midi() > index shouldn't
2214                            be necessary, but the mapping is illegal in some cases.  Ideally
2215                            that should be fixed, but this is easier...
2216                         */
2217                         if (flags & PORT_MIDI) {
2218                                 if (flags & PORT_INPUT) {
2219                                         index = in_map.get(DataType::MIDI, midi_in_index++, &valid);
2220                                 } else {
2221                                         index = out_map.get(DataType::MIDI, midi_out_index++, &valid);
2222                                 }
2223                                 if (valid && bufs.count().n_midi() > index) {
2224                                         /* Note, ensure_lv2_bufsize() is not RT safe!
2225                                          * However free()/alloc() is only called if a
2226                                          * plugin requires a rsz:minimumSize buffersize
2227                                          * and the existing buffer if smaller.
2228                                          */
2229                                         bufs.ensure_lv2_bufsize((flags & PORT_INPUT), index, _port_minimumSize[port_index]);
2230                                         _ev_buffers[port_index] = bufs.get_lv2_midi(
2231                                                 (flags & PORT_INPUT), index, (flags & PORT_EVENT));
2232                                 }
2233                         } else if ((flags & PORT_POSITION) && (flags & PORT_INPUT)) {
2234                                 lv2_evbuf_reset(_atom_ev_buffers[atom_port_index], true);
2235                                 _ev_buffers[port_index] = _atom_ev_buffers[atom_port_index++];
2236                                 valid                   = true;
2237                         }
2238
2239                         if (valid && (flags & PORT_INPUT)) {
2240                                 Timecode::BBT_Time bbt;
2241                                 if ((flags & PORT_POSITION)) {
2242                                         if (_session.transport_frame() != _next_cycle_start ||
2243                                             _session.transport_speed() != _next_cycle_speed) {
2244                                                 // Transport has changed, write position at cycle start
2245                                                 tmap.bbt_time(_session.transport_frame(), bbt);
2246                                                 write_position(&_impl->forge, _ev_buffers[port_index],
2247                                                                tmetric, bbt, _session.transport_speed(),
2248                                                                _session.transport_frame(), 0);
2249                                         }
2250                                 }
2251
2252                                 // Get MIDI iterator range (empty range if no MIDI)
2253                                 MidiBuffer::iterator m = (index != nil_index)
2254                                         ? bufs.get_midi(index).begin()
2255                                         : silent_bufs.get_midi(0).end();
2256                                 MidiBuffer::iterator m_end = (index != nil_index)
2257                                         ? bufs.get_midi(index).end()
2258                                         : m;
2259
2260                                 // Now merge MIDI and any transport events into the buffer
2261                                 const uint32_t     type = _uri_map.urids.midi_MidiEvent;
2262                                 const framepos_t   tend = _session.transport_frame() + nframes;
2263                                 ++metric_i;
2264                                 while (m != m_end || (metric_i != tmap.metrics_end() &&
2265                                                       (*metric_i)->frame() < tend)) {
2266                                         MetricSection* metric = (metric_i != tmap.metrics_end())
2267                                                 ? *metric_i : NULL;
2268                                         if (m != m_end && (!metric || metric->frame() > (*m).time())) {
2269                                                 const Evoral::MIDIEvent<framepos_t> ev(*m, false);
2270                                                 if (ev.time() < nframes) {
2271                                                         LV2_Evbuf_Iterator eend = lv2_evbuf_end(_ev_buffers[port_index]);
2272                                                         lv2_evbuf_write(&eend, ev.time(), 0, type, ev.size(), ev.buffer());
2273                                                 }
2274                                                 ++m;
2275                                         } else {
2276                                                 tmetric.set_metric(metric);
2277                                                 bbt = metric->start();
2278                                                 write_position(&_impl->forge, _ev_buffers[port_index],
2279                                                                tmetric, bbt, _session.transport_speed(),
2280                                                                metric->frame(),
2281                                                                metric->frame() - _session.transport_frame());
2282                                                 ++metric_i;
2283                                         }
2284                                 }
2285                         } else if (!valid) {
2286                                 // Nothing we understand or care about, connect to scratch
2287                                 // see note for midi-buffer size above
2288                                 scratch_bufs.ensure_lv2_bufsize((flags & PORT_INPUT),
2289                                                 0, _port_minimumSize[port_index]);
2290                                 _ev_buffers[port_index] = scratch_bufs.get_lv2_midi(
2291                                         (flags & PORT_INPUT), 0, (flags & PORT_EVENT));
2292                         }
2293
2294                         buf = lv2_evbuf_get_buffer(_ev_buffers[port_index]);
2295                 } else {
2296                         continue;  // Control port, leave buffer alone
2297                 }
2298                 lilv_instance_connect_port(_impl->instance, port_index, buf);
2299         }
2300
2301         // Read messages from UI and push into appropriate buffers
2302         if (_from_ui) {
2303                 uint32_t read_space = _from_ui->read_space();
2304                 while (read_space > sizeof(UIMessage)) {
2305                         UIMessage msg;
2306                         if (_from_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
2307                                 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
2308                                 break;
2309                         }
2310                         vector<uint8_t> body(msg.size);
2311                         if (_from_ui->read(&body[0], msg.size) != msg.size) {
2312                                 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
2313                                 break;
2314                         }
2315                         if (msg.protocol == URIMap::instance().urids.atom_eventTransfer) {
2316                                 LV2_Evbuf*            buf  = _ev_buffers[msg.index];
2317                                 LV2_Evbuf_Iterator    i    = lv2_evbuf_end(buf);
2318                                 const LV2_Atom* const atom = (const LV2_Atom*)&body[0];
2319                                 if (!lv2_evbuf_write(&i, nframes - 1, 0, atom->type, atom->size,
2320                                                 (const uint8_t*)(atom + 1))) {
2321                                         error << "Failed to write data to LV2 event buffer\n";
2322                                 }
2323                         } else {
2324                                 error << "Received unknown message type from UI" << endmsg;
2325                         }
2326                         read_space -= sizeof(UIMessage) + msg.size;
2327                 }
2328         }
2329
2330         run(nframes);
2331
2332         midi_out_index = 0;
2333         for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
2334                 PortFlags flags = _port_flags[port_index];
2335                 bool      valid = false;
2336
2337                 /* TODO ask drobilla about comment
2338                  * "Make Ardour event buffers generic so plugins can communicate"
2339                  * in libs/ardour/buffer_set.cc:310
2340                  *
2341                  * ideally the user could choose which of the following two modes
2342                  * to use (e.g. instrument/effect chains  MIDI OUT vs MIDI TRHU).
2343                  *
2344                  * This implementation follows the discussion on IRC Mar 16 2013 16:47 UTC
2345                  * 16:51 < drobilla> rgareus: [..] i.e always replace with MIDI output [of LV2 plugin] if it's there
2346                  * 16:52 < drobilla> rgareus: That would probably be good enough [..] to make users not complain
2347                  *                            for quite a while at least ;)
2348                  */
2349                 // copy output of LV2 plugin's MIDI port to Ardour MIDI buffers -- MIDI OUT
2350                 if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE|PORT_MIDI))) {
2351                         const uint32_t buf_index = out_map.get(
2352                                 DataType::MIDI, midi_out_index++, &valid);
2353                         if (valid) {
2354                                 bufs.forward_lv2_midi(_ev_buffers[port_index], buf_index);
2355                         }
2356                 }
2357                 // Flush MIDI (write back to Ardour MIDI buffers) -- MIDI THRU
2358                 else if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
2359                         const uint32_t buf_index = out_map.get(
2360                                 DataType::MIDI, midi_out_index++, &valid);
2361                         if (valid) {
2362                                 bufs.flush_lv2_midi(true, buf_index);
2363                         }
2364                 }
2365
2366                 // Write messages to UI
2367                 if ((_to_ui || _can_write_automation || _patch_port_out_index != (uint32_t)-1) &&
2368                     (flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
2369                         LV2_Evbuf* buf = _ev_buffers[port_index];
2370                         for (LV2_Evbuf_Iterator i = lv2_evbuf_begin(buf);
2371                              lv2_evbuf_is_valid(i);
2372                              i = lv2_evbuf_next(i)) {
2373                                 uint32_t frames, subframes, type, size;
2374                                 uint8_t* data;
2375                                 lv2_evbuf_get(i, &frames, &subframes, &type, &size, &data);
2376
2377 #ifdef LV2_EXTENDED
2378                                 // Intercept Automation Write Events
2379                                 if ((flags & PORT_AUTOCTRL)) {
2380                                         LV2_Atom* atom = (LV2_Atom*)(data - sizeof(LV2_Atom));
2381                                         if (atom->type == _uri_map.urids.atom_Blank ||
2382                                                         atom->type == _uri_map.urids.atom_Object) {
2383                                                 LV2_Atom_Object* obj = (LV2_Atom_Object*)atom;
2384                                                 if (obj->body.otype == _uri_map.urids.auto_event) {
2385                                                         // only if transport_rolling ??
2386                                                         const LV2_Atom* parameter = NULL;
2387                                                         const LV2_Atom* value    = NULL;
2388                                                         lv2_atom_object_get(obj,
2389                                                                             _uri_map.urids.auto_parameter, &parameter,
2390                                                                             _uri_map.urids.auto_value,     &value,
2391                                                                             0);
2392                                                         if (parameter && value) {
2393                                                                 const uint32_t p = ((const LV2_Atom_Int*)parameter)->body;
2394                                                                 const float v = ((const LV2_Atom_Float*)value)->body;
2395                                                                 // -> add automation event..
2396                                                                 AutomationCtrlPtr c = get_automation_control (p);
2397                                                                 if (c && c->ac->automation_state() == Touch) {
2398                                                                         if (c->guard) {
2399                                                                                 c->guard = false;
2400                                                                                 c->ac->list()->add (_session.transport_frame() + frames, v, true, true);
2401                                                                         } else {
2402                                                                                 c->ac->set_double (v, _session.transport_frame() + frames, true);
2403                                                                         }
2404                                                                 }
2405                                                         }
2406                                                 }
2407                                                 else if (obj->body.otype == _uri_map.urids.auto_setup) {
2408                                                         // TODO optional arguments, for now we assume the plugin
2409                                                         // writes automation for its own inputs
2410                                                         // -> put them in "touch" mode (preferably "exclusive plugin touch(TM)"
2411                                                         for (AutomationCtrlMap::iterator i = _ctrl_map.begin(); i != _ctrl_map.end(); ++i) {
2412                                                                 i->second->ac->set_automation_state (Touch);
2413                                                         }
2414                                                 }
2415                                                 else if (obj->body.otype == _uri_map.urids.auto_finalize) {
2416                                                         // set [touched] parameters to "play" ??
2417                                                 }
2418                                                 else if (obj->body.otype == _uri_map.urids.auto_start) {
2419                                                         const LV2_Atom* parameter = NULL;
2420                                                         lv2_atom_object_get(obj,
2421                                                                             _uri_map.urids.auto_parameter, &parameter,
2422                                                                             0);
2423                                                         if (parameter) {
2424                                                                 const uint32_t p = ((const LV2_Atom_Int*)parameter)->body;
2425                                                                 AutomationCtrlPtr c = get_automation_control (p);
2426                                                                 if (c) {
2427                                                                         c->ac->start_touch (_session.transport_frame());
2428                                                                         c->guard = true;
2429                                                                 }
2430                                                         }
2431                                                 }
2432                                                 else if (obj->body.otype == _uri_map.urids.auto_end) {
2433                                                         const LV2_Atom* parameter = NULL;
2434                                                         lv2_atom_object_get(obj,
2435                                                                             _uri_map.urids.auto_parameter, &parameter,
2436                                                                             0);
2437                                                         if (parameter) {
2438                                                                 const uint32_t p = ((const LV2_Atom_Int*)parameter)->body;
2439                                                                 AutomationCtrlPtr c = get_automation_control (p);
2440                                                                 if (c) {
2441                                                                         c->ac->stop_touch (true, _session.transport_frame());
2442                                                                 }
2443                                                         }
2444                                                 }
2445                                         }
2446                                 }
2447 #endif
2448
2449                                 // Intercept patch change messages to emit PropertyChanged signal
2450                                 if ((flags & PORT_PATCHMSG)) {
2451                                         LV2_Atom* atom = (LV2_Atom*)(data - sizeof(LV2_Atom));
2452                                         if (atom->type == _uri_map.urids.atom_Blank ||
2453                                             atom->type == _uri_map.urids.atom_Object) {
2454                                                 LV2_Atom_Object* obj = (LV2_Atom_Object*)atom;
2455                                                 if (obj->body.otype == _uri_map.urids.patch_Set) {
2456                                                         const LV2_Atom* property = NULL;
2457                                                         const LV2_Atom* value    = NULL;
2458                                                         lv2_atom_object_get(obj,
2459                                                                             _uri_map.urids.patch_property, &property,
2460                                                                             _uri_map.urids.patch_value,    &value,
2461                                                                             0);
2462
2463                                                         if (!property || !value ||
2464                                                             property->type != _uri_map.urids.atom_URID ||
2465                                                             value->type    != _uri_map.urids.atom_Path) {
2466                                                                 std::cerr << "warning: patch:Set for unknown property" << std::endl;
2467                                                                 continue;
2468                                                         }
2469
2470                                                         const uint32_t prop_id = ((const LV2_Atom_URID*)property)->body;
2471                                                         const char*    path    = (const char*)LV2_ATOM_BODY_CONST(value);
2472
2473                                                         // Emit PropertyChanged signal for UI
2474                                                         // TODO: This should emit the control's Changed signal
2475                                                         PropertyChanged(prop_id, Variant(Variant::PATH, path));
2476                                                 }
2477                                         }
2478                                 }
2479
2480                                 if (!_to_ui) continue;
2481                                 write_to_ui(port_index, URIMap::instance().urids.atom_eventTransfer,
2482                                             size + sizeof(LV2_Atom),
2483                                             data - sizeof(LV2_Atom));
2484                         }
2485                 }
2486         }
2487
2488         cycles_t now = get_cycles();
2489         set_cycles((uint32_t)(now - then));
2490
2491         // Update expected transport information for next cycle so we can detect changes
2492         _next_cycle_speed = _session.transport_speed();
2493         _next_cycle_start = _session.transport_frame() + (nframes * _next_cycle_speed);
2494
2495         return 0;
2496 }
2497
2498 bool
2499 LV2Plugin::parameter_is_control(uint32_t param) const
2500 {
2501         assert(param < _port_flags.size());
2502         return _port_flags[param] & PORT_CONTROL;
2503 }
2504
2505 bool
2506 LV2Plugin::parameter_is_audio(uint32_t param) const
2507 {
2508         assert(param < _port_flags.size());
2509         return _port_flags[param] & PORT_AUDIO;
2510 }
2511
2512 bool
2513 LV2Plugin::parameter_is_event(uint32_t param) const
2514 {
2515         assert(param < _port_flags.size());
2516         return _port_flags[param] & PORT_EVENT;
2517 }
2518
2519 bool
2520 LV2Plugin::parameter_is_output(uint32_t param) const
2521 {
2522         assert(param < _port_flags.size());
2523         return _port_flags[param] & PORT_OUTPUT;
2524 }
2525
2526 bool
2527 LV2Plugin::parameter_is_input(uint32_t param) const
2528 {
2529         assert(param < _port_flags.size());
2530         return _port_flags[param] & PORT_INPUT;
2531 }
2532
2533 void
2534 LV2Plugin::print_parameter(uint32_t param, char* buf, uint32_t len) const
2535 {
2536         if (buf && len) {
2537                 if (param < parameter_count()) {
2538                         snprintf(buf, len, "%.3f", get_parameter(param));
2539                 } else {
2540                         strcat(buf, "0");
2541                 }
2542         }
2543 }
2544
2545 boost::shared_ptr<ScalePoints>
2546 LV2Plugin::get_scale_points(uint32_t port_index) const
2547 {
2548         const LilvPort*  port   = lilv_plugin_get_port_by_index(_impl->plugin, port_index);
2549         LilvScalePoints* points = lilv_port_get_scale_points(_impl->plugin, port);
2550
2551         boost::shared_ptr<ScalePoints> ret;
2552         if (!points) {
2553                 return ret;
2554         }
2555
2556         ret = boost::shared_ptr<ScalePoints>(new ScalePoints());
2557
2558         LILV_FOREACH(scale_points, i, points) {
2559                 const LilvScalePoint* p     = lilv_scale_points_get(points, i);
2560                 const LilvNode*       label = lilv_scale_point_get_label(p);
2561                 const LilvNode*       value = lilv_scale_point_get_value(p);
2562                 if (label && (lilv_node_is_float(value) || lilv_node_is_int(value))) {
2563                         ret->insert(make_pair(lilv_node_as_string(label),
2564                                               lilv_node_as_float(value)));
2565                 }
2566         }
2567
2568         lilv_scale_points_free(points);
2569         return ret;
2570 }
2571
2572 void
2573 LV2Plugin::run(pframes_t nframes)
2574 {
2575         uint32_t const N = parameter_count();
2576         for (uint32_t i = 0; i < N; ++i) {
2577                 if (parameter_is_control(i) && parameter_is_input(i)) {
2578                         _control_data[i] = _shadow_data[i];
2579                 }
2580         }
2581
2582         lilv_instance_run(_impl->instance, nframes);
2583
2584         if (_impl->work_iface) {
2585                 _worker->emit_responses();
2586                 if (_impl->work_iface->end_run) {
2587                         _impl->work_iface->end_run(_impl->instance->lv2_handle);
2588                 }
2589         }
2590 }
2591
2592 void
2593 LV2Plugin::latency_compute_run()
2594 {
2595         if (!_latency_control_port) {
2596                 return;
2597         }
2598
2599         // Run the plugin so that it can set its latency parameter
2600
2601         bool was_activated = _was_activated;
2602         activate();
2603
2604         uint32_t port_index = 0;
2605         uint32_t in_index   = 0;
2606         uint32_t out_index  = 0;
2607
2608         // this is done in the main thread. non realtime.
2609         const framecnt_t bufsize = _engine.samples_per_cycle();
2610         float            *buffer = (float*) malloc(_engine.samples_per_cycle() * sizeof(float));
2611
2612         memset(buffer, 0, sizeof(float) * bufsize);
2613
2614         // FIXME: Ensure plugins can handle in-place processing
2615
2616         port_index = 0;
2617
2618         while (port_index < parameter_count()) {
2619                 if (parameter_is_audio(port_index)) {
2620                         if (parameter_is_input(port_index)) {
2621                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
2622                                 in_index++;
2623                         } else if (parameter_is_output(port_index)) {
2624                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
2625                                 out_index++;
2626                         }
2627                 }
2628                 port_index++;
2629         }
2630
2631         run(bufsize);
2632         deactivate();
2633         if (was_activated) {
2634                 activate();
2635         }
2636         free(buffer);
2637 }
2638
2639 const LilvPort*
2640 LV2Plugin::Impl::designated_input (const char* uri, void** bufptrs[], void** bufptr)
2641 {
2642         const LilvPort* port = NULL;
2643         LilvNode* designation = lilv_new_uri(_world.world, uri);
2644         port = lilv_plugin_get_port_by_designation(
2645                 plugin, _world.lv2_InputPort, designation);
2646         lilv_node_free(designation);
2647         if (port) {
2648                 bufptrs[lilv_port_get_index(plugin, port)] = bufptr;
2649         }
2650         return port;
2651 }
2652
2653 static bool lv2_filter (const string& str, void* /*arg*/)
2654 {
2655         /* Not a dotfile, has a prefix before a period, suffix is "lv2" */
2656
2657         return str[0] != '.' && (str.length() > 3 && str.find (".lv2") == (str.length() - 4));
2658 }
2659
2660
2661 LV2World::LV2World()
2662         : world(lilv_world_new())
2663         , _bundle_checked(false)
2664 {
2665         atom_AtomPort      = lilv_new_uri(world, LV2_ATOM__AtomPort);
2666         atom_Chunk         = lilv_new_uri(world, LV2_ATOM__Chunk);
2667         atom_Sequence      = lilv_new_uri(world, LV2_ATOM__Sequence);
2668         atom_bufferType    = lilv_new_uri(world, LV2_ATOM__bufferType);
2669         atom_supports      = lilv_new_uri(world, LV2_ATOM__supports);
2670         atom_eventTransfer = lilv_new_uri(world, LV2_ATOM__eventTransfer);
2671         ev_EventPort       = lilv_new_uri(world, LILV_URI_EVENT_PORT);
2672         ext_logarithmic    = lilv_new_uri(world, LV2_PORT_PROPS__logarithmic);
2673         ext_notOnGUI       = lilv_new_uri(world, LV2_PORT_PROPS__notOnGUI);
2674         lv2_AudioPort      = lilv_new_uri(world, LILV_URI_AUDIO_PORT);
2675         lv2_ControlPort    = lilv_new_uri(world, LILV_URI_CONTROL_PORT);
2676         lv2_InputPort      = lilv_new_uri(world, LILV_URI_INPUT_PORT);
2677         lv2_OutputPort     = lilv_new_uri(world, LILV_URI_OUTPUT_PORT);
2678         lv2_inPlaceBroken  = lilv_new_uri(world, LV2_CORE__inPlaceBroken);
2679         lv2_integer        = lilv_new_uri(world, LV2_CORE__integer);
2680         lv2_default        = lilv_new_uri(world, LV2_CORE__default);
2681         lv2_minimum        = lilv_new_uri(world, LV2_CORE__minimum);
2682         lv2_maximum        = lilv_new_uri(world, LV2_CORE__maximum);
2683         lv2_reportsLatency = lilv_new_uri(world, LV2_CORE__reportsLatency);
2684         lv2_sampleRate     = lilv_new_uri(world, LV2_CORE__sampleRate);
2685         lv2_toggled        = lilv_new_uri(world, LV2_CORE__toggled);
2686         lv2_enumeration    = lilv_new_uri(world, LV2_CORE__enumeration);
2687         lv2_freewheeling   = lilv_new_uri(world, LV2_CORE__freeWheeling);
2688         midi_MidiEvent     = lilv_new_uri(world, LILV_URI_MIDI_EVENT);
2689         rdfs_comment       = lilv_new_uri(world, LILV_NS_RDFS "comment");
2690         rdfs_label         = lilv_new_uri(world, LILV_NS_RDFS "label");
2691         rdfs_range         = lilv_new_uri(world, LILV_NS_RDFS "range");
2692         rsz_minimumSize    = lilv_new_uri(world, LV2_RESIZE_PORT__minimumSize);
2693         time_Position      = lilv_new_uri(world, LV2_TIME__Position);
2694         ui_GtkUI           = lilv_new_uri(world, LV2_UI__GtkUI);
2695         ui_external        = lilv_new_uri(world, "http://lv2plug.in/ns/extensions/ui#external");
2696         ui_externalkx      = lilv_new_uri(world, "http://kxstudio.sf.net/ns/lv2ext/external-ui#Widget");
2697         units_unit         = lilv_new_uri(world, LV2_UNITS__unit);
2698         units_render       = lilv_new_uri(world, LV2_UNITS__render);
2699         units_hz           = lilv_new_uri(world, LV2_UNITS__hz);
2700         units_midiNote     = lilv_new_uri(world, LV2_UNITS__midiNote);
2701         units_db           = lilv_new_uri(world, LV2_UNITS__db);
2702         patch_writable     = lilv_new_uri(world, LV2_PATCH__writable);
2703         patch_Message      = lilv_new_uri(world, LV2_PATCH__Message);
2704 #ifdef LV2_EXTENDED
2705         lv2_noSampleAccurateCtrl    = lilv_new_uri(world, LV2_CORE_PREFIX "noSampleAccurateControls");
2706         auto_can_write_automatation = lilv_new_uri(world, LV2_AUTOMATE_URI__can_write);
2707         auto_automation_control     = lilv_new_uri(world, LV2_AUTOMATE_URI__control);
2708         auto_automation_controlled  = lilv_new_uri(world, LV2_AUTOMATE_URI__controlled);
2709 #endif
2710 #ifdef HAVE_LV2_1_2_0
2711         bufz_powerOf2BlockLength = lilv_new_uri(world, LV2_BUF_SIZE__powerOf2BlockLength);
2712         bufz_fixedBlockLength    = lilv_new_uri(world, LV2_BUF_SIZE__fixedBlockLength);
2713         bufz_nominalBlockLength  = lilv_new_uri(world, "http://lv2plug.in/ns/ext/buf-size#nominalBlockLength");
2714 #endif
2715
2716 }
2717
2718 LV2World::~LV2World()
2719 {
2720         if (!world) {
2721                 return;
2722         }
2723 #ifdef HAVE_LV2_1_2_0
2724         lilv_node_free(bufz_nominalBlockLength);
2725         lilv_node_free(bufz_fixedBlockLength);
2726         lilv_node_free(bufz_powerOf2BlockLength);
2727 #endif
2728 #ifdef LV2_EXTENDED
2729         lilv_node_free(lv2_noSampleAccurateCtrl);
2730         lilv_node_free(auto_can_write_automatation);
2731         lilv_node_free(auto_automation_control);
2732         lilv_node_free(auto_automation_controlled);
2733 #endif
2734         lilv_node_free(patch_Message);
2735         lilv_node_free(patch_writable);
2736         lilv_node_free(units_hz);
2737         lilv_node_free(units_midiNote);
2738         lilv_node_free(units_db);
2739         lilv_node_free(units_unit);
2740         lilv_node_free(units_render);
2741         lilv_node_free(ui_externalkx);
2742         lilv_node_free(ui_external);
2743         lilv_node_free(ui_GtkUI);
2744         lilv_node_free(time_Position);
2745         lilv_node_free(rsz_minimumSize);
2746         lilv_node_free(rdfs_comment);
2747         lilv_node_free(rdfs_label);
2748         lilv_node_free(rdfs_range);
2749         lilv_node_free(midi_MidiEvent);
2750         lilv_node_free(lv2_enumeration);
2751         lilv_node_free(lv2_freewheeling);
2752         lilv_node_free(lv2_toggled);
2753         lilv_node_free(lv2_sampleRate);
2754         lilv_node_free(lv2_reportsLatency);
2755         lilv_node_free(lv2_integer);
2756         lilv_node_free(lv2_inPlaceBroken);
2757         lilv_node_free(lv2_OutputPort);
2758         lilv_node_free(lv2_InputPort);
2759         lilv_node_free(lv2_ControlPort);
2760         lilv_node_free(lv2_AudioPort);
2761         lilv_node_free(ext_notOnGUI);
2762         lilv_node_free(ext_logarithmic);
2763         lilv_node_free(ev_EventPort);
2764         lilv_node_free(atom_supports);
2765         lilv_node_free(atom_eventTransfer);
2766         lilv_node_free(atom_bufferType);
2767         lilv_node_free(atom_Sequence);
2768         lilv_node_free(atom_Chunk);
2769         lilv_node_free(atom_AtomPort);
2770         lilv_world_free(world);
2771         world = NULL;
2772 }
2773
2774 void
2775 LV2World::load_bundled_plugins(bool verbose)
2776 {
2777         if (!_bundle_checked) {
2778                 if (verbose) {
2779                         cout << "Scanning folders for bundled LV2s: " << ARDOUR::lv2_bundled_search_path().to_string() << endl;
2780                 }
2781
2782                 vector<string> plugin_objects;
2783                 find_paths_matching_filter (plugin_objects, ARDOUR::lv2_bundled_search_path(), lv2_filter, 0, true, true, true);
2784                 for ( vector<string>::iterator x = plugin_objects.begin(); x != plugin_objects.end (); ++x) {
2785 #ifdef PLATFORM_WINDOWS
2786                         string uri = "file:///" + *x + "/";
2787 #else
2788                         string uri = "file://" + *x + "/";
2789 #endif
2790                         LilvNode *node = lilv_new_uri(world, uri.c_str());
2791                         lilv_world_load_bundle(world, node);
2792                         lilv_node_free(node);
2793                 }
2794
2795                 lilv_world_load_all(world);
2796                 _bundle_checked = true;
2797         }
2798 }
2799
2800 LV2PluginInfo::LV2PluginInfo (const char* plugin_uri)
2801 {
2802         type = ARDOUR::LV2;
2803         _plugin_uri = strdup(plugin_uri);
2804 }
2805
2806 LV2PluginInfo::~LV2PluginInfo()
2807 {
2808         free(_plugin_uri);
2809         _plugin_uri = NULL;
2810 }
2811
2812 PluginPtr
2813 LV2PluginInfo::load(Session& session)
2814 {
2815         try {
2816                 PluginPtr plugin;
2817                 const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
2818                 LilvNode* uri = lilv_new_uri(_world.world, _plugin_uri);
2819                 if (!uri) { throw failed_constructor(); }
2820                 const LilvPlugin* lp = lilv_plugins_get_by_uri(plugins, uri);
2821                 if (!lp) { throw failed_constructor(); }
2822                 plugin.reset(new LV2Plugin(session.engine(), session, lp, session.frame_rate()));
2823                 lilv_node_free(uri);
2824                 plugin->set_info(PluginInfoPtr(shared_from_this ()));
2825                 return plugin;
2826         } catch (failed_constructor& err) {
2827                 return PluginPtr((Plugin*)0);
2828         }
2829
2830         return PluginPtr();
2831 }
2832
2833 std::vector<Plugin::PresetRecord>
2834 LV2PluginInfo::get_presets (bool /*user_only*/) const
2835 {
2836         std::vector<Plugin::PresetRecord> p;
2837 #ifndef NO_PLUGIN_STATE
2838         const LilvPlugin* lp = NULL;
2839         try {
2840                 PluginPtr plugin;
2841                 const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
2842                 LilvNode* uri = lilv_new_uri(_world.world, _plugin_uri);
2843                 if (!uri) { throw failed_constructor(); }
2844                 lp = lilv_plugins_get_by_uri(plugins, uri);
2845                 if (!lp) { throw failed_constructor(); }
2846                 lilv_node_free(uri);
2847         } catch (failed_constructor& err) {
2848                 return p;
2849         }
2850         assert (lp);
2851         // see LV2Plugin::find_presets
2852         LilvNode* lv2_appliesTo = lilv_new_uri(_world.world, LV2_CORE__appliesTo);
2853         LilvNode* pset_Preset   = lilv_new_uri(_world.world, LV2_PRESETS__Preset);
2854         LilvNode* rdfs_label    = lilv_new_uri(_world.world, LILV_NS_RDFS "label");
2855
2856         LilvNodes* presets = lilv_plugin_get_related(lp, pset_Preset);
2857         LILV_FOREACH(nodes, i, presets) {
2858                 const LilvNode* preset = lilv_nodes_get(presets, i);
2859                 lilv_world_load_resource(_world.world, preset);
2860                 LilvNode* name = get_value(_world.world, preset, rdfs_label);
2861                 bool userpreset = true; // TODO
2862                 if (name) {
2863                         p.push_back (Plugin::PresetRecord (lilv_node_as_string(preset), lilv_node_as_string(name), userpreset));
2864                         lilv_node_free(name);
2865                 }
2866         }
2867         lilv_nodes_free(presets);
2868         lilv_node_free(rdfs_label);
2869         lilv_node_free(pset_Preset);
2870         lilv_node_free(lv2_appliesTo);
2871 #endif
2872         return p;
2873 }
2874
2875 bool
2876 LV2PluginInfo::in_category (const std::string &c) const
2877 {
2878         // TODO use untranslated lilv_plugin_get_class()
2879         // match gtk2_ardour/plugin_selector.cc
2880         if (category == c) {
2881                 return true;
2882         }
2883         return false;
2884 }
2885
2886 bool
2887 LV2PluginInfo::is_instrument () const
2888 {
2889         if (category == "Instrument") {
2890                 return true;
2891         }
2892 #if 1
2893         /* until we make sure that category remains untranslated in the lv2.ttl spec
2894          * and until most instruments also classify themselves as such, there's a 2nd check:
2895          */
2896         if (n_inputs.n_midi() > 0 && n_inputs.n_audio() == 0 && n_outputs.n_audio() > 0) {
2897                 return true;
2898         }
2899 #endif
2900         return false;
2901 }
2902
2903 PluginInfoList*
2904 LV2PluginInfo::discover()
2905 {
2906         LV2World world;
2907         world.load_bundled_plugins();
2908         _world.load_bundled_plugins(true);
2909
2910         PluginInfoList*    plugs   = new PluginInfoList;
2911         const LilvPlugins* plugins = lilv_world_get_all_plugins(world.world);
2912
2913         LILV_FOREACH(plugins, i, plugins) {
2914                 const LilvPlugin* p = lilv_plugins_get(plugins, i);
2915                 const LilvNode* pun = lilv_plugin_get_uri(p);
2916                 if (!pun) continue;
2917                 LV2PluginInfoPtr info(new LV2PluginInfo(lilv_node_as_string(pun)));
2918
2919                 LilvNode* name = lilv_plugin_get_name(p);
2920                 if (!name || !lilv_plugin_get_port_by_index(p, 0)) {
2921                         warning << "Ignoring invalid LV2 plugin "
2922                                 << lilv_node_as_string(lilv_plugin_get_uri(p))
2923                                 << endmsg;
2924                         continue;
2925                 }
2926
2927                 if (lilv_plugin_has_feature(p, world.lv2_inPlaceBroken)) {
2928                         warning << string_compose(
2929                             _("Ignoring LV2 plugin \"%1\" since it cannot do inplace processing."),
2930                             lilv_node_as_string(name)) << endmsg;
2931                         lilv_node_free(name);
2932                         continue;
2933                 }
2934
2935 #ifdef HAVE_LV2_1_2_0
2936                 LilvNodes *required_features = lilv_plugin_get_required_features (p);
2937                 if (lilv_nodes_contains (required_features, world.bufz_powerOf2BlockLength) ||
2938                                 lilv_nodes_contains (required_features, world.bufz_fixedBlockLength)
2939                    ) {
2940                         warning << string_compose(
2941                             _("Ignoring LV2 plugin \"%1\" because its buffer-size requirements cannot be satisfied."),
2942                             lilv_node_as_string(name)) << endmsg;
2943                         lilv_nodes_free(required_features);
2944                         lilv_node_free(name);
2945                         continue;
2946                 }
2947                 lilv_nodes_free(required_features);
2948 #endif
2949
2950                 info->type = LV2;
2951
2952                 info->name = string(lilv_node_as_string(name));
2953                 lilv_node_free(name);
2954                 ARDOUR::PluginScanMessage(_("LV2"), info->name, false);
2955
2956                 const LilvPluginClass* pclass = lilv_plugin_get_class(p);
2957                 const LilvNode*        label  = lilv_plugin_class_get_label(pclass);
2958                 info->category = lilv_node_as_string(label);
2959
2960                 LilvNode* author_name = lilv_plugin_get_author_name(p);
2961                 info->creator = author_name ? string(lilv_node_as_string(author_name)) : "Unknown";
2962                 lilv_node_free(author_name);
2963
2964                 info->path = "/NOPATH"; // Meaningless for LV2
2965
2966                 /* count atom-event-ports that feature
2967                  * atom:supports <http://lv2plug.in/ns/ext/midi#MidiEvent>
2968                  *
2969                  * TODO: nicely ask drobilla to make a lilv_ call for that
2970                  */
2971                 int count_midi_out = 0;
2972                 int count_midi_in = 0;
2973                 for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
2974                         const LilvPort* port  = lilv_plugin_get_port_by_index(p, i);
2975                         if (lilv_port_is_a(p, port, world.atom_AtomPort)) {
2976                                 LilvNodes* buffer_types = lilv_port_get_value(
2977                                         p, port, world.atom_bufferType);
2978                                 LilvNodes* atom_supports = lilv_port_get_value(
2979                                         p, port, world.atom_supports);
2980
2981                                 if (lilv_nodes_contains(buffer_types, world.atom_Sequence)
2982                                                 && lilv_nodes_contains(atom_supports, world.midi_MidiEvent)) {
2983                                         if (lilv_port_is_a(p, port, world.lv2_InputPort)) {
2984                                                 count_midi_in++;
2985                                         }
2986                                         if (lilv_port_is_a(p, port, world.lv2_OutputPort)) {
2987                                                 count_midi_out++;
2988                                         }
2989                                 }
2990                                 lilv_nodes_free(buffer_types);
2991                                 lilv_nodes_free(atom_supports);
2992                         }
2993                 }
2994
2995                 info->n_inputs.set_audio(
2996                         lilv_plugin_get_num_ports_of_class(
2997                                 p, world.lv2_InputPort, world.lv2_AudioPort, NULL));
2998                 info->n_inputs.set_midi(
2999                         lilv_plugin_get_num_ports_of_class(
3000                                 p, world.lv2_InputPort, world.ev_EventPort, NULL)
3001                         + count_midi_in);
3002
3003                 info->n_outputs.set_audio(
3004                         lilv_plugin_get_num_ports_of_class(
3005                                 p, world.lv2_OutputPort, world.lv2_AudioPort, NULL));
3006                 info->n_outputs.set_midi(
3007                         lilv_plugin_get_num_ports_of_class(
3008                                 p, world.lv2_OutputPort, world.ev_EventPort, NULL)
3009                         + count_midi_out);
3010
3011                 info->unique_id = lilv_node_as_uri(lilv_plugin_get_uri(p));
3012                 info->index     = 0; // Meaningless for LV2
3013
3014                 plugs->push_back(info);
3015         }
3016
3017         return plugs;
3018 }