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