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