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