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