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