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