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