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