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