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