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