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