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