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