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