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