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