Merge branch 'master' into cairocanvas
[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 <string>
21 #include <vector>
22 #include <limits>
23
24 #include <cmath>
25 #include <cstdlib>
26 #include <cstring>
27
28 #include <giomm/file.h>
29 #include <glib/gprintf.h>
30 #include <glibmm.h>
31
32 #include <boost/utility.hpp>
33
34 #include "pbd/compose.h"
35 #include "pbd/error.h"
36 #include "pbd/xml++.h"
37
38 #include "libardour-config.h"
39
40 #include "ardour/audio_buffer.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/debug.h"
43 #include "ardour/lv2_plugin.h"
44 #include "ardour/session.h"
45 #include "ardour/tempo.h"
46 #include "ardour/types.h"
47 #include "ardour/utils.h"
48 #include "ardour/worker.h"
49
50 #include "i18n.h"
51 #include <locale.h>
52
53 #include <lilv/lilv.h>
54
55 #include "lv2/lv2plug.in/ns/ext/atom/atom.h"
56 #include "lv2/lv2plug.in/ns/ext/atom/forge.h"
57 #include "lv2/lv2plug.in/ns/ext/log/log.h"
58 #include "lv2/lv2plug.in/ns/ext/midi/midi.h"
59 #include "lv2/lv2plug.in/ns/ext/port-props/port-props.h"
60 #include "lv2/lv2plug.in/ns/ext/presets/presets.h"
61 #include "lv2/lv2plug.in/ns/ext/state/state.h"
62 #include "lv2/lv2plug.in/ns/ext/time/time.h"
63 #include "lv2/lv2plug.in/ns/ext/worker/worker.h"
64 #include "lv2/lv2plug.in/ns/ext/resize-port/resize-port.h"
65 #include "lv2/lv2plug.in/ns/extensions/ui/ui.h"
66 #ifdef HAVE_NEW_LV2
67 #include "lv2/lv2plug.in/ns/ext/buf-size/buf-size.h"
68 #include "lv2/lv2plug.in/ns/ext/options/options.h"
69 #endif
70
71 #include "lv2_evbuf.h"
72
73 #ifdef HAVE_SUIL
74 #include <suil/suil.h>
75 #endif
76
77 /** The number of MIDI buffers that will fit in a UI/worker comm buffer.
78     This needs to be roughly the number of cycles the UI will get around to
79     actually processing the traffic.  Lower values are flakier but save memory.
80 */
81 static const size_t NBUFS = 4;
82
83 using namespace std;
84 using namespace ARDOUR;
85 using namespace PBD;
86
87 URIMap LV2Plugin::_uri_map;
88
89 LV2Plugin::URIDs LV2Plugin::urids = {
90         _uri_map.uri_to_id(LV2_ATOM__Chunk),
91         _uri_map.uri_to_id(LV2_ATOM__Path),
92         _uri_map.uri_to_id(LV2_ATOM__Sequence),
93         _uri_map.uri_to_id(LV2_ATOM__eventTransfer),
94         _uri_map.uri_to_id(LV2_LOG__Error),
95         _uri_map.uri_to_id(LV2_LOG__Note),
96         _uri_map.uri_to_id(LV2_LOG__Warning),
97         _uri_map.uri_to_id(LV2_MIDI__MidiEvent),
98         _uri_map.uri_to_id(LV2_TIME__Position),
99         _uri_map.uri_to_id(LV2_TIME__bar),
100         _uri_map.uri_to_id(LV2_TIME__barBeat),
101         _uri_map.uri_to_id(LV2_TIME__beatUnit),
102         _uri_map.uri_to_id(LV2_TIME__beatsPerBar),
103         _uri_map.uri_to_id(LV2_TIME__beatsPerMinute),
104         _uri_map.uri_to_id(LV2_TIME__frame),
105         _uri_map.uri_to_id(LV2_TIME__speed)
106 };
107
108 class LV2World : boost::noncopyable {
109 public:
110         LV2World ();
111         ~LV2World ();
112
113         LilvWorld* world;
114
115         LilvNode* atom_AtomPort;
116         LilvNode* atom_Chunk;
117         LilvNode* atom_Sequence;
118         LilvNode* atom_bufferType;
119         LilvNode* atom_eventTransfer;
120         LilvNode* atom_supports;
121         LilvNode* ev_EventPort;
122         LilvNode* ext_logarithmic;
123         LilvNode* ext_notOnGUI;
124         LilvNode* lv2_AudioPort;
125         LilvNode* lv2_ControlPort;
126         LilvNode* lv2_InputPort;
127         LilvNode* lv2_OutputPort;
128         LilvNode* lv2_enumeration;
129         LilvNode* lv2_freewheeling;
130         LilvNode* lv2_inPlaceBroken;
131         LilvNode* lv2_integer;
132         LilvNode* lv2_reportsLatency;
133         LilvNode* lv2_sampleRate;
134         LilvNode* lv2_toggled;
135         LilvNode* midi_MidiEvent;
136         LilvNode* rdfs_comment;
137         LilvNode* rsz_minimumSize;
138         LilvNode* time_Position;
139         LilvNode* ui_GtkUI;
140         LilvNode* ui_external;
141 };
142
143 static LV2World _world;
144
145 /* worker extension */
146
147 /** Called by the plugin to schedule non-RT work. */
148 static LV2_Worker_Status
149 work_schedule(LV2_Worker_Schedule_Handle handle,
150               uint32_t                   size,
151               const void*                data)
152 {
153         LV2Plugin* plugin = (LV2Plugin*)handle;
154         if (plugin->session().engine().freewheeling()) {
155                 // Freewheeling, do the work immediately in this (audio) thread
156                 return (LV2_Worker_Status)plugin->work(size, data);
157         } else {
158                 // Enqueue message for the worker thread
159                 return plugin->worker()->schedule(size, data) ?
160                         LV2_WORKER_SUCCESS : LV2_WORKER_ERR_UNKNOWN;
161         }
162 }
163
164 /** Called by the plugin to respond to non-RT work. */
165 static LV2_Worker_Status
166 work_respond(LV2_Worker_Respond_Handle handle,
167              uint32_t                  size,
168              const void*               data)
169 {
170         LV2Plugin* plugin = (LV2Plugin*)handle;
171         if (plugin->session().engine().freewheeling()) {
172                 // Freewheeling, respond immediately in this (audio) thread
173                 return (LV2_Worker_Status)plugin->work_response(size, data);
174         } else {
175                 // Enqueue response for the worker
176                 return plugin->worker()->respond(size, data) ?
177                         LV2_WORKER_SUCCESS : LV2_WORKER_ERR_UNKNOWN;
178         }
179 }
180
181 /* log extension */
182
183 static int
184 log_vprintf(LV2_Log_Handle /*handle*/,
185             LV2_URID       type,
186             const char*    fmt,
187             va_list        args)
188 {
189         char* str = NULL;
190         const int ret = g_vasprintf(&str, fmt, args);
191         if (type == LV2Plugin::urids.log_Error) {
192                 error << str << endmsg;
193         } else if (type == LV2Plugin::urids.log_Warning) {
194                 warning << str << endmsg;
195         } else if (type == LV2Plugin::urids.log_Note) {
196                 info << str << endmsg;
197         }
198         // TODO: Toggleable log:Trace message support
199         return ret;
200 }
201
202 static int
203 log_printf(LV2_Log_Handle handle,
204            LV2_URID       type,
205            const char*    fmt, ...)
206 {
207         va_list args;
208         va_start(args, fmt);
209         const int ret = log_vprintf(handle, type, fmt, args);
210         va_end(args);
211         return ret;
212 }
213
214 struct LV2Plugin::Impl {
215         Impl() : plugin(0), ui(0), ui_type(0), name(0), author(0), instance(0)
216                , work_iface(0)
217                , state(0)
218         {}
219
220         /** Find the LV2 input port with the given designation.
221          * If found, bufptrs[port_index] will be set to bufptr.
222          */
223         const LilvPort* designated_input (const char* uri, void** bufptrs[], void** bufptr);
224
225         const LilvPlugin*           plugin;
226         const LilvUI*               ui;
227         const LilvNode*             ui_type;
228         LilvNode*                   name;
229         LilvNode*                   author;
230         LilvInstance*               instance;
231         const LV2_Worker_Interface* work_iface;
232         LilvState*                  state;
233         LV2_Atom_Forge              forge;
234 };
235
236 LV2Plugin::LV2Plugin (AudioEngine& engine,
237                       Session&     session,
238                       const void*  c_plugin,
239                       framecnt_t   rate)
240         : Plugin (engine, session)
241         , Workee ()
242         , _impl(new Impl())
243         , _features(NULL)
244         , _worker(NULL)
245         , _insert_id("0")
246 {
247         init(c_plugin, rate);
248 }
249
250 LV2Plugin::LV2Plugin (const LV2Plugin& other)
251         : Plugin (other)
252         , Workee ()
253         , _impl(new Impl())
254         , _features(NULL)
255         , _worker(NULL)
256         , _insert_id(other._insert_id)
257 {
258         init(other._impl->plugin, other._sample_rate);
259
260         for (uint32_t i = 0; i < parameter_count(); ++i) {
261                 _control_data[i] = other._shadow_data[i];
262                 _shadow_data[i]  = other._shadow_data[i];
263         }
264 }
265
266 void
267 LV2Plugin::init(const void* c_plugin, framecnt_t rate)
268 {
269         DEBUG_TRACE(DEBUG::LV2, "init\n");
270
271         _impl->plugin           = (const LilvPlugin*)c_plugin;
272         _impl->ui               = NULL;
273         _impl->ui_type          = NULL;
274         _to_ui                  = NULL;
275         _from_ui                = NULL;
276         _control_data           = 0;
277         _shadow_data            = 0;
278         _atom_ev_buffers        = 0;
279         _ev_buffers             = 0;
280         _bpm_control_port       = 0;
281         _freewheel_control_port = 0;
282         _latency_control_port   = 0;
283         _next_cycle_start       = std::numeric_limits<framepos_t>::max();
284         _next_cycle_speed       = 1.0;
285         _block_length           = _engine.frames_per_cycle();
286         _seq_size               = _engine.raw_buffer_size(DataType::MIDI);
287         _state_version          = 0;
288         _was_activated          = false;
289         _has_state_interface    = false;
290
291         _instance_access_feature.URI = "http://lv2plug.in/ns/ext/instance-access";
292         _data_access_feature.URI     = "http://lv2plug.in/ns/ext/data-access";
293         _make_path_feature.URI       = LV2_STATE__makePath;
294         _log_feature.URI             = LV2_LOG__log;
295         _work_schedule_feature.URI   = LV2_WORKER__schedule;
296         _work_schedule_feature.data  = NULL;
297         _def_state_feature.URI       = LV2_STATE_PREFIX "loadDefaultState";  // Post LV2-1.2.0
298         _def_state_feature.data      = NULL;
299
300         const LilvPlugin* plugin = _impl->plugin;
301
302         LilvNode* state_iface_uri = lilv_new_uri(_world.world, LV2_STATE__interface);
303         LilvNode* state_uri       = lilv_new_uri(_world.world, LV2_STATE_URI);
304         _has_state_interface =
305                 // What plugins should have (lv2:extensionData state:Interface)
306                 lilv_plugin_has_extension_data(plugin, state_iface_uri)
307                 // What some outdated/incorrect ones have
308                 || lilv_plugin_has_feature(plugin, state_uri);
309         lilv_node_free(state_uri);
310         lilv_node_free(state_iface_uri);
311
312         _features    = (LV2_Feature**)calloc(11, sizeof(LV2_Feature*));
313         _features[0] = &_instance_access_feature;
314         _features[1] = &_data_access_feature;
315         _features[2] = &_make_path_feature;
316         _features[3] = _uri_map.uri_map_feature();
317         _features[4] = _uri_map.urid_map_feature();
318         _features[5] = _uri_map.urid_unmap_feature();
319         _features[6] = &_log_feature;
320
321         unsigned n_features = 7;
322 #ifdef HAVE_NEW_LV2
323         _features[n_features++] = &_def_state_feature;
324 #endif
325
326         lv2_atom_forge_init(&_impl->forge, _uri_map.urid_map());
327
328 #ifdef HAVE_NEW_LV2
329         LV2_URID atom_Int = _uri_map.uri_to_id(LV2_ATOM__Int);
330         LV2_Options_Option options[] = {
331                 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__minBlockLength),
332                   sizeof(int32_t), atom_Int, &_block_length },
333                 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__maxBlockLength),
334                   sizeof(int32_t), atom_Int, &_block_length },
335                 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__sequenceSize),
336                   sizeof(int32_t), atom_Int, &_seq_size },
337                 { LV2_OPTIONS_INSTANCE, 0, 0, 0, 0, NULL }
338         };
339
340         _options_feature.URI    = LV2_OPTIONS__options;
341         _options_feature.data   = options;
342         _features[n_features++] = &_options_feature;
343 #endif
344
345         LV2_State_Make_Path* make_path = (LV2_State_Make_Path*)malloc(
346                 sizeof(LV2_State_Make_Path));
347         make_path->handle = this;
348         make_path->path = &lv2_state_make_path;
349         _make_path_feature.data = make_path;
350
351         LV2_Log_Log* log = (LV2_Log_Log*)malloc(sizeof(LV2_Log_Log));
352         log->handle  = this;
353         log->printf  = &log_printf;
354         log->vprintf = &log_vprintf;
355         _log_feature.data = log;
356
357         LilvNode* worker_schedule = lilv_new_uri(_world.world, LV2_WORKER__schedule);
358         if (lilv_plugin_has_feature(plugin, worker_schedule)) {
359                 LV2_Worker_Schedule* schedule = (LV2_Worker_Schedule*)malloc(
360                         sizeof(LV2_Worker_Schedule));
361                 size_t buf_size = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
362                 _worker                     = new Worker(this, buf_size);
363                 schedule->handle            = this;
364                 schedule->schedule_work     = work_schedule;
365                 _work_schedule_feature.data = schedule;
366                 _features[n_features++]     = &_work_schedule_feature;
367         }
368         lilv_node_free(worker_schedule);
369
370         _impl->instance = lilv_plugin_instantiate(plugin, rate, _features);
371         _impl->name     = lilv_plugin_get_name(plugin);
372         _impl->author   = lilv_plugin_get_author_name(plugin);
373
374         if (_impl->instance == 0) {
375                 error << _("LV2: Failed to instantiate plugin ") << uri() << endmsg;
376                 throw failed_constructor();
377         }
378
379         _instance_access_feature.data              = (void*)_impl->instance->lv2_handle;
380         _data_access_extension_data.extension_data = _impl->instance->lv2_descriptor->extension_data;
381         _data_access_feature.data                  = &_data_access_extension_data;
382
383         LilvNode* worker_iface_uri = lilv_new_uri(_world.world, LV2_WORKER__interface);
384         if (lilv_plugin_has_extension_data(plugin, worker_iface_uri)) {
385                 _impl->work_iface = (const LV2_Worker_Interface*)extension_data(
386                         LV2_WORKER__interface);
387         }
388         lilv_node_free(worker_iface_uri);
389
390         if (lilv_plugin_has_feature(plugin, _world.lv2_inPlaceBroken)) {
391                 error << string_compose(
392                     _("LV2: \"%1\" cannot be used, since it cannot do inplace processing"),
393                     lilv_node_as_string(_impl->name)) << endmsg;
394                 lilv_node_free(_impl->name);
395                 lilv_node_free(_impl->author);
396                 throw failed_constructor();
397         }
398
399 #ifdef HAVE_NEW_LILV
400         // Load default state
401         LilvState* state = lilv_state_new_from_world(
402                 _world.world, _uri_map.urid_map(), lilv_plugin_get_uri(_impl->plugin));
403         if (state && _has_state_interface) {
404                 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
405         }
406 #endif
407
408         _sample_rate = rate;
409
410         const uint32_t num_ports = this->num_ports();
411         for (uint32_t i = 0; i < num_ports; ++i) {
412                 const LilvPort* port  = lilv_plugin_get_port_by_index(_impl->plugin, i);
413                 PortFlags       flags = 0;
414                 size_t          minimumSize = 0;
415
416                 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_OutputPort)) {
417                         flags |= PORT_OUTPUT;
418                 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_InputPort)) {
419                         flags |= PORT_INPUT;
420                 } else {
421                         error << string_compose(
422                                 "LV2: \"%1\" port %2 is neither input nor output",
423                                 lilv_node_as_string(_impl->name), i) << endmsg;
424                         throw failed_constructor();
425                 }
426
427                 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_ControlPort)) {
428                         flags |= PORT_CONTROL;
429                 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_AudioPort)) {
430                         flags |= PORT_AUDIO;
431                 } else if (lilv_port_is_a(_impl->plugin, port, _world.ev_EventPort)) {
432                         flags |= PORT_EVENT;
433                         flags |= PORT_MIDI;  // We assume old event API ports are for MIDI
434                 } else if (lilv_port_is_a(_impl->plugin, port, _world.atom_AtomPort)) {
435                         LilvNodes* buffer_types = lilv_port_get_value(
436                                 _impl->plugin, port, _world.atom_bufferType);
437                         LilvNodes* atom_supports = lilv_port_get_value(
438                                 _impl->plugin, port, _world.atom_supports);
439
440                         if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)) {
441                                 flags |= PORT_SEQUENCE;
442                                 if (lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
443                                         flags |= PORT_MIDI;
444                                 }
445                                 if (lilv_nodes_contains(atom_supports, _world.time_Position)) {
446                                         flags |= PORT_POSITION;
447                                 }
448                         }
449                         LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
450                         LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
451                         if (min_size && lilv_node_is_int(min_size)) {
452                                 minimumSize = lilv_node_as_int(min_size);
453                         }
454                         lilv_nodes_free(min_size_v);
455                         lilv_nodes_free(buffer_types);
456                         lilv_nodes_free(atom_supports);
457                 } else {
458                         error << string_compose(
459                                 "LV2: \"%1\" port %2 has no known data type",
460                                 lilv_node_as_string(_impl->name), i) << endmsg;
461                         throw failed_constructor();
462                 }
463
464                 _port_flags.push_back(flags);
465                 _port_minimumSize.push_back(minimumSize);
466         }
467
468         _control_data = new float[num_ports];
469         _shadow_data  = new float[num_ports];
470         _defaults     = new float[num_ports];
471         _ev_buffers   = new LV2_Evbuf*[num_ports];
472         memset(_ev_buffers, 0, sizeof(LV2_Evbuf*) * num_ports);
473
474         const bool     latent        = lilv_plugin_has_latency(plugin);
475         const uint32_t latency_index = (latent)
476                 ? lilv_plugin_get_latency_port_index(plugin)
477                 : 0;
478
479         // Build an array of pointers to special parameter buffers
480         void*** params = new void**[num_ports];
481         for (uint32_t i = 0; i < num_ports; ++i) {
482                 params[i] = NULL;
483         }
484         _impl->designated_input (LV2_TIME__beatsPerMinute, params, (void**)&_bpm_control_port);
485         _impl->designated_input (LV2_CORE__freeWheeling, params, (void**)&_freewheel_control_port);
486
487         for (uint32_t i = 0; i < num_ports; ++i) {
488                 const LilvPort* port = lilv_plugin_get_port_by_index(plugin, i);
489                 const LilvNode* sym  = lilv_port_get_symbol(plugin, port);
490
491                 // Store index in map so we can look up index by symbol
492                 _port_indices.insert(std::make_pair(lilv_node_as_string(sym), i));
493
494                 // Get range and default value if applicable
495                 if (parameter_is_control(i)) {
496                         LilvNode* def;
497                         lilv_port_get_range(plugin, port, &def, NULL, NULL);
498                         _defaults[i] = def ? lilv_node_as_float(def) : 0.0f;
499                         if (lilv_port_has_property (plugin, port, _world.lv2_sampleRate)) {
500                                 _defaults[i] *= _session.frame_rate ();
501                         }
502                         lilv_node_free(def);
503
504                         lilv_instance_connect_port(_impl->instance, i, &_control_data[i]);
505
506                         if (latent && i == latency_index) {
507                                 _latency_control_port  = &_control_data[i];
508                                 *_latency_control_port = 0;
509                         }
510
511                         if (parameter_is_input(i)) {
512                                 _shadow_data[i] = default_value(i);
513                                 if (params[i]) {
514                                         *params[i] = (void*)&_shadow_data[i];
515                                 }
516                         }
517                 } else {
518                         _defaults[i] = 0.0f;
519                 }
520         }
521
522         delete[] params;
523
524         LilvUIs* uis = lilv_plugin_get_uis(plugin);
525         if (lilv_uis_size(uis) > 0) {
526 #ifdef HAVE_SUIL
527                 // Look for embeddable UI
528                 LILV_FOREACH(uis, u, uis) {
529                         const LilvUI*   this_ui      = lilv_uis_get(uis, u);
530                         const LilvNode* this_ui_type = NULL;
531                         if (lilv_ui_is_supported(this_ui,
532                                                  suil_ui_supported,
533                                                  _world.ui_GtkUI,
534                                                  &this_ui_type)) {
535                                 // TODO: Multiple UI support
536                                 _impl->ui      = this_ui;
537                                 _impl->ui_type = this_ui_type;
538                                 break;
539                         }
540                 }
541 #else
542                 // Look for Gtk native UI
543                 LILV_FOREACH(uis, i, uis) {
544                         const LilvUI* ui = lilv_uis_get(uis, i);
545                         if (lilv_ui_is_a(ui, _world.ui_GtkUI)) {
546                                 _impl->ui      = ui;
547                                 _impl->ui_type = _world.ui_GtkUI;
548                                 break;
549                         }
550                 }
551 #endif
552
553                 // If Gtk UI is not available, try to find external UI
554                 if (!_impl->ui) {
555                         LILV_FOREACH(uis, i, uis) {
556                                 const LilvUI* ui = lilv_uis_get(uis, i);
557                                 if (lilv_ui_is_a(ui, _world.ui_external)) {
558                                         _impl->ui      = ui;
559                                         _impl->ui_type = _world.ui_external;
560                                         break;
561                                 }
562                         }
563                 }
564         }
565
566         allocate_atom_event_buffers();
567         latency_compute_run();
568 }
569
570 LV2Plugin::~LV2Plugin ()
571 {
572         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 destroy\n", name()));
573
574         deactivate();
575         cleanup();
576
577         lilv_instance_free(_impl->instance);
578         lilv_node_free(_impl->name);
579         lilv_node_free(_impl->author);
580
581         free(_features);
582         free(_make_path_feature.data);
583         free(_work_schedule_feature.data);
584
585         delete _to_ui;
586         delete _from_ui;
587         delete _worker;
588
589         if (_atom_ev_buffers) {
590                 LV2_Evbuf**  b = _atom_ev_buffers;
591                 while (*b) {
592                         free(*b);
593                         b++;
594                 }
595                 free(_atom_ev_buffers);
596         }
597
598         delete [] _control_data;
599         delete [] _shadow_data;
600         delete [] _ev_buffers;
601 }
602
603 bool
604 LV2Plugin::is_external_ui() const
605 {
606         if (!_impl->ui) {
607                 return false;
608         }
609         return lilv_ui_is_a(_impl->ui, _world.ui_external);
610 }
611
612 bool
613 LV2Plugin::ui_is_resizable () const
614 {
615         const LilvNode* s   = lilv_ui_get_uri(_impl->ui);
616         LilvNode*       p   = lilv_new_uri(_world.world, LV2_CORE__optionalFeature);
617         LilvNode*       fs  = lilv_new_uri(_world.world, LV2_UI__fixedSize);
618         LilvNode*       nrs = lilv_new_uri(_world.world, LV2_UI__noUserResize);
619
620         LilvNodes* fs_matches = lilv_world_find_nodes(_world.world, s, p, fs);
621         LilvNodes* nrs_matches = lilv_world_find_nodes(_world.world, s, p, nrs);
622
623         lilv_nodes_free(nrs_matches);
624         lilv_nodes_free(fs_matches);
625         lilv_node_free(nrs);
626         lilv_node_free(fs);
627         lilv_node_free(p);
628
629         return !fs_matches && !nrs_matches;
630 }
631
632 string
633 LV2Plugin::unique_id() const
634 {
635         return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
636 }
637
638 const char*
639 LV2Plugin::uri() const
640 {
641         return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
642 }
643
644 const char*
645 LV2Plugin::label() const
646 {
647         return lilv_node_as_string(_impl->name);
648 }
649
650 const char*
651 LV2Plugin::name() const
652 {
653         return lilv_node_as_string(_impl->name);
654 }
655
656 const char*
657 LV2Plugin::maker() const
658 {
659         return _impl->author ? lilv_node_as_string (_impl->author) : "Unknown";
660 }
661
662 uint32_t
663 LV2Plugin::num_ports() const
664 {
665         return lilv_plugin_get_num_ports(_impl->plugin);
666 }
667
668 uint32_t
669 LV2Plugin::parameter_count() const
670 {
671         return lilv_plugin_get_num_ports(_impl->plugin);
672 }
673
674 float
675 LV2Plugin::default_value(uint32_t port)
676 {
677         return _defaults[port];
678 }
679
680 const char*
681 LV2Plugin::port_symbol(uint32_t index) const
682 {
683         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, index);
684         if (!port) {
685                 error << name() << ": Invalid port index " << index << endmsg;
686         }
687
688         const LilvNode* sym = lilv_port_get_symbol(_impl->plugin, port);
689         return lilv_node_as_string(sym);
690 }
691
692 uint32_t
693 LV2Plugin::port_index (const char* symbol) const
694 {
695         const map<string, uint32_t>::const_iterator i = _port_indices.find(symbol);
696         if (i != _port_indices.end()) {
697                 return  i->second;
698         } else {
699                 warning << string_compose(_("LV2: Unknown port %1"), symbol) << endmsg;
700                 return (uint32_t)-1;
701         }
702 }
703
704 void
705 LV2Plugin::set_parameter(uint32_t which, float val)
706 {
707         DEBUG_TRACE(DEBUG::LV2, string_compose(
708                             "%1 set parameter %2 to %3\n", name(), which, val));
709
710         if (which < lilv_plugin_get_num_ports(_impl->plugin)) {
711                 if (get_parameter (which) == val) {
712                         return;
713                 }
714
715                 _shadow_data[which] = val;
716         } else {
717                 warning << string_compose(
718                     _("Illegal parameter number used with plugin \"%1\". "
719                       "This is a bug in either %2 or the LV2 plugin <%3>"),
720                     name(), PROGRAM_NAME, unique_id()) << endmsg;
721         }
722
723         Plugin::set_parameter(which, val);
724 }
725
726 float
727 LV2Plugin::get_parameter(uint32_t which) const
728 {
729         if (parameter_is_input(which)) {
730                 return (float)_shadow_data[which];
731         } else {
732                 return (float)_control_data[which];
733         }
734         return 0.0f;
735 }
736
737 std::string
738 LV2Plugin::get_docs() const
739 {
740         LilvNodes* comments = lilv_plugin_get_value(_impl->plugin, _world.rdfs_comment);
741         if (comments) {
742                 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
743                 lilv_nodes_free(comments);
744                 return docs;
745         }
746
747         return "";
748 }
749
750 std::string
751 LV2Plugin::get_parameter_docs(uint32_t which) const
752 {
753         LilvNodes* comments = lilv_port_get_value(
754                 _impl->plugin,
755                 lilv_plugin_get_port_by_index(_impl->plugin, which),
756                 _world.rdfs_comment);
757
758         if (comments) {
759                 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
760                 lilv_nodes_free(comments);
761                 return docs;
762         }
763
764         return "";
765 }
766
767 uint32_t
768 LV2Plugin::nth_parameter(uint32_t n, bool& ok) const
769 {
770         ok = false;
771         for (uint32_t c = 0, x = 0; x < lilv_plugin_get_num_ports(_impl->plugin); ++x) {
772                 if (parameter_is_control(x)) {
773                         if (c++ == n) {
774                                 ok = true;
775                                 return x;
776                         }
777                 }
778         }
779
780         return 0;
781 }
782
783 const void*
784 LV2Plugin::extension_data(const char* uri) const
785 {
786         return lilv_instance_get_extension_data(_impl->instance, uri);
787 }
788
789 const void*
790 LV2Plugin::c_plugin()
791 {
792         return _impl->plugin;
793 }
794
795 const void*
796 LV2Plugin::c_ui()
797 {
798         return (const void*)_impl->ui;
799 }
800
801 const void*
802 LV2Plugin::c_ui_type()
803 {
804         return (const void*)_impl->ui_type;
805 }
806
807 /** Directory for all plugin state. */
808 const std::string
809 LV2Plugin::plugin_dir() const
810 {
811         return Glib::build_filename(_session.plugins_dir(), _insert_id.to_s());
812 }
813
814 /** Directory for files created by the plugin (except during save). */
815 const std::string
816 LV2Plugin::scratch_dir() const
817 {
818         return Glib::build_filename(plugin_dir(), "scratch");
819 }
820
821 /** Directory for snapshots of files in the scratch directory. */
822 const std::string
823 LV2Plugin::file_dir() const
824 {
825         return Glib::build_filename(plugin_dir(), "files");
826 }
827
828 /** Directory to save state snapshot version @c num into. */
829 const std::string
830 LV2Plugin::state_dir(unsigned num) const
831 {
832         return Glib::build_filename(plugin_dir(), string_compose("state%1", num));
833 }
834
835 /** Implementation of state:makePath for files created at instantiation time.
836  * Note this is not used for files created at save time (Lilv deals with that).
837  */
838 char*
839 LV2Plugin::lv2_state_make_path(LV2_State_Make_Path_Handle handle,
840                                const char*                path)
841 {
842         LV2Plugin* me = (LV2Plugin*)handle;
843         if (me->_insert_id == PBD::ID("0")) {
844                 warning << string_compose(
845                         "File path \"%1\" requested but LV2 %2 has no insert ID",
846                         path, me->name()) << endmsg;
847                 return g_strdup(path);
848         }
849
850         const std::string abs_path = Glib::build_filename(me->scratch_dir(), path);
851         const std::string dirname  = Glib::path_get_dirname(abs_path);
852         g_mkdir_with_parents(dirname.c_str(), 0744);
853
854         DEBUG_TRACE(DEBUG::LV2, string_compose("new file path %1 => %2\n",
855                                                path, abs_path));
856
857         return g_strndup(abs_path.c_str(), abs_path.length());
858 }
859
860 static void
861 remove_directory(const std::string& path)
862 {
863         if (!Glib::file_test(path, Glib::FILE_TEST_IS_DIR)) {
864                 warning << string_compose("\"%1\" is not a directory", path) << endmsg;
865                 return;
866         }
867
868         Glib::RefPtr<Gio::File>           dir = Gio::File::create_for_path(path);
869         Glib::RefPtr<Gio::FileEnumerator> e   = dir->enumerate_children();
870         Glib::RefPtr<Gio::FileInfo>       fi;
871         while ((fi = e->next_file())) {
872                 if (fi->get_type() == Gio::FILE_TYPE_DIRECTORY) {
873                         remove_directory(fi->get_name());
874                 } else {
875                         dir->get_child(fi->get_name())->remove();
876                 }
877         }
878         dir->remove();
879 }
880
881 void
882 LV2Plugin::add_state(XMLNode* root) const
883 {
884         assert(_insert_id != PBD::ID("0"));
885
886         XMLNode*    child;
887         char        buf[16];
888         LocaleGuard lg(X_("POSIX"));
889
890         for (uint32_t i = 0; i < parameter_count(); ++i) {
891                 if (parameter_is_input(i) && parameter_is_control(i)) {
892                         child = new XMLNode("Port");
893                         child->add_property("symbol", port_symbol(i));
894                         snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
895                         child->add_property("value", string(buf));
896                         root->add_child_nocopy(*child);
897                 }
898         }
899
900         if (_has_state_interface) {
901                 // Provisionally increment state version and create directory
902                 const std::string new_dir = state_dir(++_state_version);
903                 g_mkdir_with_parents(new_dir.c_str(), 0744);
904
905                 LilvState* state = lilv_state_new_from_instance(
906                         _impl->plugin,
907                         _impl->instance,
908                         _uri_map.urid_map(),
909                         scratch_dir().c_str(),
910                         file_dir().c_str(),
911                         _session.externals_dir().c_str(),
912                         new_dir.c_str(),
913                         NULL,
914                         const_cast<LV2Plugin*>(this),
915                         0,
916                         NULL);
917
918                 if (!_impl->state || !lilv_state_equals(state, _impl->state)) {
919                         lilv_state_save(_world.world,
920                                         _uri_map.urid_map(),
921                                         _uri_map.urid_unmap(),
922                                         state,
923                                         NULL,
924                                         new_dir.c_str(),
925                                         "state.ttl");
926
927                         lilv_state_free(_impl->state);
928                         _impl->state = state;
929                 } else {
930                         // State is identical, decrement version and nuke directory
931                         lilv_state_free(state);
932                         remove_directory(new_dir);
933                         --_state_version;
934                 }
935
936                 root->add_property("state-dir", string_compose("state%1", _state_version));
937         }
938 }
939
940 static inline const LilvNode*
941 get_value(LilvWorld* world, const LilvNode* subject, const LilvNode* predicate)
942 {
943         LilvNodes* vs = lilv_world_find_nodes(world, subject, predicate, NULL);
944         return vs ? lilv_nodes_get_first(vs) : NULL;
945 }
946
947 void
948 LV2Plugin::find_presets()
949 {
950         LilvNode* lv2_appliesTo = lilv_new_uri(_world.world, LV2_CORE__appliesTo);
951         LilvNode* pset_Preset   = lilv_new_uri(_world.world, LV2_PRESETS__Preset);
952         LilvNode* rdfs_label    = lilv_new_uri(_world.world, LILV_NS_RDFS "label");
953
954         LilvNodes* presets = lilv_plugin_get_related(_impl->plugin, pset_Preset);
955         LILV_FOREACH(nodes, i, presets) {
956                 const LilvNode* preset = lilv_nodes_get(presets, i);
957                 lilv_world_load_resource(_world.world, preset);
958                 const LilvNode* name = get_value(_world.world, preset, rdfs_label);
959                 if (name) {
960                         _presets.insert(std::make_pair(lilv_node_as_string(preset),
961                                                        Plugin::PresetRecord(
962                                                                lilv_node_as_string(preset),
963                                                                lilv_node_as_string(name))));
964                 } else {
965                         warning << string_compose(
966                             _("Plugin \"%1\% preset \"%2%\" is missing a label\n"),
967                             lilv_node_as_string(lilv_plugin_get_uri(_impl->plugin)),
968                             lilv_node_as_string(preset)) << endmsg;
969                 }
970         }
971         lilv_nodes_free(presets);
972
973         lilv_node_free(rdfs_label);
974         lilv_node_free(pset_Preset);
975         lilv_node_free(lv2_appliesTo);
976 }
977
978 static void
979 set_port_value(const char* port_symbol,
980                void*       user_data,
981                const void* value,
982                uint32_t    /*size*/,
983                uint32_t    type)
984 {
985         LV2Plugin* self = (LV2Plugin*)user_data;
986         if (type != 0 && type != self->_uri_map.uri_to_id(LV2_ATOM__Float)) {
987                 return;  // TODO: Support non-float ports
988         }
989
990         const uint32_t port_index = self->port_index(port_symbol);
991         if (port_index != (uint32_t)-1) {
992                 self->set_parameter(port_index, *(const float*)value);
993         }
994 }
995
996 bool
997 LV2Plugin::load_preset(PresetRecord r)
998 {
999         LilvWorld* world = _world.world;
1000         LilvNode*  pset  = lilv_new_uri(world, r.uri.c_str());
1001         LilvState* state = lilv_state_new_from_world(world, _uri_map.urid_map(), pset);
1002
1003         if (state) {
1004                 lilv_state_restore(state, _impl->instance, set_port_value, this, 0, NULL);
1005                 lilv_state_free(state);
1006         }
1007
1008         lilv_node_free(pset);
1009         return state;
1010 }
1011
1012 const void*
1013 ARDOUR::lv2plugin_get_port_value(const char* port_symbol,
1014                                  void*       user_data,
1015                                  uint32_t*   size,
1016                                  uint32_t*   type)
1017 {
1018         LV2Plugin *plugin = (LV2Plugin *) user_data;
1019
1020         uint32_t index = plugin->port_index(port_symbol);
1021         if (index != (uint32_t) -1) {
1022                 if (plugin->parameter_is_input(index) && plugin->parameter_is_control(index)) {
1023                         float *value;
1024                         *size = sizeof(float);
1025                         *type = plugin->_uri_map.uri_to_id(LV2_ATOM__Float);
1026                         value = &plugin->_shadow_data[index];
1027
1028                         return value;
1029                 }
1030         }
1031
1032         *size = *type = 0;
1033         return NULL;
1034 }
1035
1036
1037 std::string
1038 LV2Plugin::do_save_preset(string name)
1039 {
1040         const string base_name = legalize_for_uri(name);
1041         const string file_name = base_name + ".ttl";
1042         const string bundle    = Glib::build_filename(
1043                 Glib::get_home_dir(),
1044                 Glib::build_filename(".lv2", base_name + ".lv2"));
1045
1046         LilvState* state = lilv_state_new_from_instance(
1047                 _impl->plugin,
1048                 _impl->instance,
1049                 _uri_map.urid_map(),
1050                 scratch_dir().c_str(),                   // file_dir
1051                 bundle.c_str(),                          // copy_dir
1052                 bundle.c_str(),                          // link_dir
1053                 bundle.c_str(),                          // save_dir
1054                 lv2plugin_get_port_value,                // get_value
1055                 (void*)this,                             // user_data
1056                 LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE,  // flags
1057                 _features                                // features
1058         );
1059
1060         lilv_state_set_label(state, name.c_str());
1061         lilv_state_save(
1062                 _world.world,           // world
1063                 _uri_map.urid_map(),    // map
1064                 _uri_map.urid_unmap(),  // unmap
1065                 state,                  // state
1066                 NULL,                   // uri (NULL = use file URI)
1067                 bundle.c_str(),         // dir
1068                 file_name.c_str()       // filename
1069         );
1070
1071         lilv_state_free(state);
1072
1073         return Glib::filename_to_uri(Glib::build_filename(bundle, file_name));
1074 }
1075
1076 void
1077 LV2Plugin::do_remove_preset(string name)
1078 {
1079         string preset_file = Glib::build_filename(
1080                 Glib::get_home_dir(),
1081                 Glib::build_filename(
1082                         Glib::build_filename(".lv2", "presets"),
1083                         name + ".ttl"
1084                 )
1085         );
1086         unlink(preset_file.c_str());
1087 }
1088
1089 bool
1090 LV2Plugin::has_editor() const
1091 {
1092         return _impl->ui != NULL;
1093 }
1094
1095 bool
1096 LV2Plugin::has_message_output() const
1097 {
1098         for (uint32_t i = 0; i < num_ports(); ++i) {
1099                 if ((_port_flags[i] & PORT_SEQUENCE) &&
1100                     (_port_flags[i] & PORT_OUTPUT)) {
1101                         return true;
1102                 }
1103         }
1104         return false;
1105 }
1106
1107 bool
1108 LV2Plugin::write_to(RingBuffer<uint8_t>* dest,
1109                     uint32_t             index,
1110                     uint32_t             protocol,
1111                     uint32_t             size,
1112                     const uint8_t*       body)
1113 {
1114         const uint32_t buf_size = sizeof(UIMessage) + size;
1115         uint8_t        buf[buf_size];
1116
1117         UIMessage* msg = (UIMessage*)buf;
1118         msg->index    = index;
1119         msg->protocol = protocol;
1120         msg->size     = size;
1121         memcpy(msg + 1, body, size);
1122
1123         return (dest->write(buf, buf_size) == buf_size);
1124 }
1125
1126 bool
1127 LV2Plugin::write_from_ui(uint32_t       index,
1128                          uint32_t       protocol,
1129                          uint32_t       size,
1130                          const uint8_t* body)
1131 {
1132         if (!_from_ui) {
1133                 _from_ui = new RingBuffer<uint8_t>(
1134                         _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS);
1135         }
1136
1137         if (!write_to(_from_ui, index, protocol, size, body)) {
1138                 error << "Error writing from UI to plugin" << endmsg;
1139                 return false;
1140         }
1141         return true;
1142 }
1143
1144 bool
1145 LV2Plugin::write_to_ui(uint32_t       index,
1146                        uint32_t       protocol,
1147                        uint32_t       size,
1148                        const uint8_t* body)
1149 {
1150         if (!write_to(_to_ui, index, protocol, size, body)) {
1151                 error << "Error writing from plugin to UI" << endmsg;
1152                 return false;
1153         }
1154         return true;
1155 }
1156
1157 void
1158 LV2Plugin::enable_ui_emmission()
1159 {
1160         if (!_to_ui) {
1161                 _to_ui = new RingBuffer<uint8_t>(
1162                         _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS);
1163         }
1164 }
1165
1166 void
1167 LV2Plugin::emit_to_ui(void* controller, UIMessageSink sink)
1168 {
1169         if (!_to_ui) {
1170                 return;
1171         }
1172
1173         uint32_t read_space = _to_ui->read_space();
1174         while (read_space > sizeof(UIMessage)) {
1175                 UIMessage msg;
1176                 if (_to_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1177                         error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1178                         break;
1179                 }
1180                 uint8_t body[msg.size];
1181                 if (_to_ui->read(body, msg.size) != msg.size) {
1182                         error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1183                         break;
1184                 }
1185
1186                 sink(controller, msg.index, msg.size, msg.protocol, body);
1187
1188                 read_space -= sizeof(msg) + msg.size;
1189         }
1190 }
1191
1192 int
1193 LV2Plugin::work(uint32_t size, const void* data)
1194 {
1195         return _impl->work_iface->work(
1196                 _impl->instance->lv2_handle, work_respond, this, size, data);
1197 }
1198
1199 int
1200 LV2Plugin::work_response(uint32_t size, const void* data)
1201 {
1202         return _impl->work_iface->work_response(
1203                 _impl->instance->lv2_handle, size, data);
1204 }
1205
1206 void
1207 LV2Plugin::set_insert_info(const PluginInsert* insert)
1208 {
1209         _insert_id = insert->id();
1210 }
1211
1212 int
1213 LV2Plugin::set_state(const XMLNode& node, int version)
1214 {
1215         XMLNodeList          nodes;
1216         const XMLProperty*   prop;
1217         XMLNodeConstIterator iter;
1218         XMLNode*             child;
1219         const char*          sym;
1220         const char*          value;
1221         uint32_t             port_id;
1222         LocaleGuard          lg(X_("POSIX"));
1223
1224         if (node.name() != state_node_name()) {
1225                 error << _("Bad node sent to LV2Plugin::set_state") << endmsg;
1226                 return -1;
1227         }
1228
1229         if (version < 3000) {
1230                 nodes = node.children("port");
1231         } else {
1232                 nodes = node.children("Port");
1233         }
1234
1235         for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
1236
1237                 child = *iter;
1238
1239                 if ((prop = child->property("symbol")) != 0) {
1240                         sym = prop->value().c_str();
1241                 } else {
1242                         warning << _("LV2: port has no symbol, ignored") << endmsg;
1243                         continue;
1244                 }
1245
1246                 map<string, uint32_t>::iterator i = _port_indices.find(sym);
1247
1248                 if (i != _port_indices.end()) {
1249                         port_id = i->second;
1250                 } else {
1251                         warning << _("LV2: port has unknown index, ignored") << endmsg;
1252                         continue;
1253                 }
1254
1255                 if ((prop = child->property("value")) != 0) {
1256                         value = prop->value().c_str();
1257                 } else {
1258                         warning << _("LV2: port has no value, ignored") << endmsg;
1259                         continue;
1260                 }
1261
1262                 set_parameter(port_id, atof(value));
1263         }
1264
1265         _state_version = 0;
1266         if ((prop = node.property("state-dir")) != 0) {
1267                 if (sscanf(prop->value().c_str(), "state%u", &_state_version) != 1) {
1268                         error << string_compose(
1269                                 "LV2: failed to parse state version from \"%1\"",
1270                                 prop->value()) << endmsg;
1271                 }
1272
1273                 std::string state_file = Glib::build_filename(
1274                         plugin_dir(),
1275                         Glib::build_filename(prop->value(), "state.ttl"));
1276
1277                 LilvState* state = lilv_state_new_from_file(
1278                         _world.world, _uri_map.urid_map(), NULL, state_file.c_str());
1279
1280                 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
1281         }
1282
1283         latency_compute_run();
1284
1285         return Plugin::set_state(node, version);
1286 }
1287
1288 int
1289 LV2Plugin::get_parameter_descriptor(uint32_t which, ParameterDescriptor& desc) const
1290 {
1291         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, which);
1292
1293         LilvNode *def, *min, *max;
1294         lilv_port_get_range(_impl->plugin, port, &def, &min, &max);
1295
1296         desc.integer_step = lilv_port_has_property(_impl->plugin, port, _world.lv2_integer);
1297         desc.toggled      = lilv_port_has_property(_impl->plugin, port, _world.lv2_toggled);
1298         desc.logarithmic  = lilv_port_has_property(_impl->plugin, port, _world.ext_logarithmic);
1299         desc.sr_dependent = lilv_port_has_property(_impl->plugin, port, _world.lv2_sampleRate);
1300         desc.label        = lilv_node_as_string(lilv_port_get_name(_impl->plugin, port));
1301         desc.lower        = min ? lilv_node_as_float(min) : 0.0f;
1302         desc.upper        = max ? lilv_node_as_float(max) : 1.0f;
1303         if (desc.sr_dependent) {
1304                 desc.lower *= _session.frame_rate ();
1305                 desc.upper *= _session.frame_rate ();
1306         }
1307
1308         desc.min_unbound  = false; // TODO: LV2 extension required
1309         desc.max_unbound  = false; // TODO: LV2 extension required
1310
1311         if (desc.integer_step) {
1312                 desc.step      = 1.0;
1313                 desc.smallstep = 0.1;
1314                 desc.largestep = 10.0;
1315         } else {
1316                 const float delta = desc.upper - desc.lower;
1317                 desc.step      = delta / 1000.0f;
1318                 desc.smallstep = delta / 10000.0f;
1319                 desc.largestep = delta / 10.0f;
1320         }
1321
1322         desc.enumeration = lilv_port_has_property(_impl->plugin, port, _world.lv2_enumeration);
1323
1324         lilv_node_free(def);
1325         lilv_node_free(min);
1326         lilv_node_free(max);
1327
1328         return 0;
1329 }
1330
1331 string
1332 LV2Plugin::describe_parameter(Evoral::Parameter which)
1333 {
1334         if (( which.type() == PluginAutomation) && ( which.id() < parameter_count()) ) {
1335
1336                 if (lilv_port_has_property(_impl->plugin,
1337                                         lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.ext_notOnGUI)) {
1338                         return X_("hidden");
1339                 }
1340
1341                 if (lilv_port_has_property(_impl->plugin,
1342                                         lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_freewheeling)) {
1343                         return X_("hidden");
1344                 }
1345
1346                 if (lilv_port_has_property(_impl->plugin,
1347                                         lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_sampleRate)) {
1348                         return X_("hidden");
1349                 }
1350
1351                 if (lilv_port_has_property(_impl->plugin,
1352                                         lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_reportsLatency)) {
1353                         return X_("latency");
1354                 }
1355
1356                 LilvNode* name = lilv_port_get_name(_impl->plugin,
1357                                                     lilv_plugin_get_port_by_index(_impl->plugin, which.id()));
1358                 string ret(lilv_node_as_string(name));
1359                 lilv_node_free(name);
1360                 return ret;
1361         } else {
1362                 return "??";
1363         }
1364 }
1365
1366 framecnt_t
1367 LV2Plugin::signal_latency() const
1368 {
1369         if (_latency_control_port) {
1370                 return (framecnt_t)floor(*_latency_control_port);
1371         } else {
1372                 return 0;
1373         }
1374 }
1375
1376 set<Evoral::Parameter>
1377 LV2Plugin::automatable() const
1378 {
1379         set<Evoral::Parameter> ret;
1380
1381         for (uint32_t i = 0; i < parameter_count(); ++i) {
1382                 if (parameter_is_input(i) && parameter_is_control(i)) {
1383                         ret.insert(ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
1384                 }
1385         }
1386
1387         return ret;
1388 }
1389
1390 void
1391 LV2Plugin::activate()
1392 {
1393         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 activate\n", name()));
1394
1395         if (!_was_activated) {
1396                 lilv_instance_activate(_impl->instance);
1397                 _was_activated = true;
1398         }
1399 }
1400
1401 void
1402 LV2Plugin::deactivate()
1403 {
1404         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 deactivate\n", name()));
1405
1406         if (_was_activated) {
1407                 lilv_instance_deactivate(_impl->instance);
1408                 _was_activated = false;
1409         }
1410 }
1411
1412 void
1413 LV2Plugin::cleanup()
1414 {
1415         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 cleanup\n", name()));
1416
1417         activate();
1418         deactivate();
1419         lilv_instance_free(_impl->instance);
1420         _impl->instance = NULL;
1421 }
1422
1423 void
1424 LV2Plugin::allocate_atom_event_buffers()
1425 {
1426         /* reserve local scratch buffers for ATOM event-queues */
1427         const LilvPlugin* p = _impl->plugin;
1428
1429         /* count non-MIDI atom event-ports
1430          * TODO: nicely ask drobilla to make a lilv_ call for that
1431          */
1432         int count_atom_out = 0;
1433         int count_atom_in = 0;
1434         int minimumSize = 32768; // TODO use a per-port minimum-size
1435         for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
1436                 const LilvPort* port  = lilv_plugin_get_port_by_index(p, i);
1437                 if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
1438                         LilvNodes* buffer_types = lilv_port_get_value(
1439                                 p, port, _world.atom_bufferType);
1440                         LilvNodes* atom_supports = lilv_port_get_value(
1441                                 p, port, _world.atom_supports);
1442
1443                         if (!lilv_nodes_contains(buffer_types, _world.atom_Sequence)
1444                                         || !lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
1445                                 if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
1446                                         count_atom_in++;
1447                                 }
1448                                 if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
1449                                         count_atom_out++;
1450                                 }
1451                                 LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
1452                                 LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
1453                                 if (min_size && lilv_node_is_int(min_size)) {
1454                                         minimumSize = std::max(minimumSize, lilv_node_as_int(min_size));
1455                                 }
1456                                 lilv_nodes_free(min_size_v);
1457                         }
1458                         lilv_nodes_free(buffer_types);
1459                         lilv_nodes_free(atom_supports);
1460                 }
1461         }
1462
1463         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 need buffers for %2 atom-in and %3 atom-out event-ports\n",
1464                                 name(), count_atom_in, count_atom_out));
1465
1466         const int total_atom_buffers = (count_atom_in + count_atom_out);
1467         if (_atom_ev_buffers || total_atom_buffers == 0) {
1468                 return;
1469         }
1470
1471         DEBUG_TRACE(DEBUG::LV2, string_compose("allocate %1 atom_ev_buffers\n", total_atom_buffers));
1472         _atom_ev_buffers = (LV2_Evbuf**) malloc((total_atom_buffers + 1) * sizeof(LV2_Evbuf*));
1473         for (int i = 0; i < total_atom_buffers; ++i ) {
1474                 _atom_ev_buffers[i] = lv2_evbuf_new(minimumSize, LV2_EVBUF_ATOM,
1475                                 LV2Plugin::urids.atom_Chunk, LV2Plugin::urids.atom_Sequence);
1476         }
1477         _atom_ev_buffers[total_atom_buffers] = 0;
1478         return;
1479 }
1480
1481 /** Write an ardour position/time/tempo/meter as an LV2 event.
1482  * @return true on success.
1483  */
1484 static bool
1485 write_position(LV2_Atom_Forge*     forge,
1486                LV2_Evbuf*          buf,
1487                const TempoMetric&  t,
1488                Timecode::BBT_Time& bbt,
1489                double              speed,
1490                framepos_t          position,
1491                framecnt_t          offset)
1492 {
1493         uint8_t pos_buf[256];
1494         lv2_atom_forge_set_buffer(forge, pos_buf, sizeof(pos_buf));
1495         LV2_Atom_Forge_Frame frame;
1496         lv2_atom_forge_blank(forge, &frame, 1, LV2Plugin::urids.time_Position);
1497         lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_frame, 0);
1498         lv2_atom_forge_long(forge, position);
1499         lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_speed, 0);
1500         lv2_atom_forge_float(forge, speed);
1501         lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_barBeat, 0);
1502         lv2_atom_forge_float(forge, bbt.beats - 1 +
1503                              (bbt.ticks / Timecode::BBT_Time::ticks_per_beat));
1504         lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_bar, 0);
1505         lv2_atom_forge_long(forge, bbt.bars - 1);
1506         lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_beatUnit, 0);
1507         lv2_atom_forge_int(forge, t.meter().note_divisor());
1508         lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_beatsPerBar, 0);
1509         lv2_atom_forge_float(forge, t.meter().divisions_per_bar());
1510         lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_beatsPerMinute, 0);
1511         lv2_atom_forge_float(forge, t.tempo().beats_per_minute());
1512
1513         LV2_Evbuf_Iterator    end  = lv2_evbuf_end(buf);
1514         const LV2_Atom* const atom = (const LV2_Atom*)pos_buf;
1515         return lv2_evbuf_write(&end, offset, 0, atom->type, atom->size,
1516                                (const uint8_t*)(atom + 1));
1517 }
1518
1519 int
1520 LV2Plugin::connect_and_run(BufferSet& bufs,
1521         ChanMapping in_map, ChanMapping out_map,
1522         pframes_t nframes, framecnt_t offset)
1523 {
1524         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 run %2 offset %3\n", name(), nframes, offset));
1525         Plugin::connect_and_run(bufs, in_map, out_map, nframes, offset);
1526
1527         cycles_t then = get_cycles();
1528
1529         TempoMap&               tmap     = _session.tempo_map();
1530         Metrics::const_iterator metric_i = tmap.metrics_end();
1531         TempoMetric             tmetric  = tmap.metric_at(_session.transport_frame(), &metric_i);
1532
1533         if (_freewheel_control_port) {
1534                 *_freewheel_control_port = _session.engine().freewheeling();
1535         }
1536
1537         if (_bpm_control_port) {
1538                 *_bpm_control_port = tmetric.tempo().beats_per_minute();
1539         }
1540
1541         ChanCount bufs_count;
1542         bufs_count.set(DataType::AUDIO, 1);
1543         bufs_count.set(DataType::MIDI, 1);
1544         BufferSet& silent_bufs  = _session.get_silent_buffers(bufs_count);
1545         BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
1546         uint32_t const num_ports = parameter_count();
1547         uint32_t const nil_index = std::numeric_limits<uint32_t>::max();
1548
1549         uint32_t audio_in_index  = 0;
1550         uint32_t audio_out_index = 0;
1551         uint32_t midi_in_index   = 0;
1552         uint32_t midi_out_index  = 0;
1553         uint32_t atom_port_index = 0;
1554         for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
1555                 void*     buf   = NULL;
1556                 uint32_t  index = nil_index;
1557                 PortFlags flags = _port_flags[port_index];
1558                 bool      valid = false;
1559                 if (flags & PORT_AUDIO) {
1560                         if (flags & PORT_INPUT) {
1561                                 index = in_map.get(DataType::AUDIO, audio_in_index++, &valid);
1562                                 buf = (valid)
1563                                         ? bufs.get_audio(index).data(offset)
1564                                         : silent_bufs.get_audio(0).data(offset);
1565                         } else {
1566                                 index = out_map.get(DataType::AUDIO, audio_out_index++, &valid);
1567                                 buf = (valid)
1568                                         ? bufs.get_audio(index).data(offset)
1569                                         : scratch_bufs.get_audio(0).data(offset);
1570                         }
1571                 } else if (flags & (PORT_EVENT|PORT_SEQUENCE)) {
1572                         /* FIXME: The checks here for bufs.count().n_midi() > index shouldn't
1573                            be necessary, but the mapping is illegal in some cases.  Ideally
1574                            that should be fixed, but this is easier...
1575                         */
1576                         if (flags & PORT_MIDI) {
1577                                 if (flags & PORT_INPUT) {
1578                                         index = in_map.get(DataType::MIDI, midi_in_index++, &valid);
1579                                 } else {
1580                                         index = out_map.get(DataType::MIDI, midi_out_index++, &valid);
1581                                 }
1582                                 if (valid && bufs.count().n_midi() > index) {
1583                                         /* Note, ensure_lv2_bufsize() is not RT safe!
1584                                          * However free()/alloc() is only called if a
1585                                          * plugin requires a rsz:minimumSize buffersize
1586                                          * and the existing buffer if smaller.
1587                                          */
1588                                         bufs.ensure_lv2_bufsize((flags & PORT_INPUT), index, _port_minimumSize[port_index]);
1589                                         _ev_buffers[port_index] = bufs.get_lv2_midi(
1590                                                 (flags & PORT_INPUT), index, (flags & PORT_EVENT));
1591                                 }
1592                         } else if ((flags & PORT_POSITION) && (flags & PORT_INPUT)) {
1593                                 lv2_evbuf_reset(_atom_ev_buffers[atom_port_index], true);
1594                                 _ev_buffers[port_index] = _atom_ev_buffers[atom_port_index++];
1595                                 valid                   = true;
1596                         }
1597
1598                         if (valid && (flags & PORT_INPUT)) {
1599                                 Timecode::BBT_Time bbt;
1600                                 if ((flags & PORT_POSITION)) {
1601                                         if (_session.transport_frame() != _next_cycle_start ||
1602                                             _session.transport_speed() != _next_cycle_speed) {
1603                                                 // Transport has changed, write position at cycle start
1604                                                 tmap.bbt_time(_session.transport_frame(), bbt);
1605                                                 write_position(&_impl->forge, _ev_buffers[port_index],
1606                                                                tmetric, bbt, _session.transport_speed(),
1607                                                                _session.transport_frame(), 0);
1608                                         }
1609                                 }
1610
1611                                 // Get MIDI iterator range (empty range if no MIDI)
1612                                 MidiBuffer::iterator m = (index != nil_index)
1613                                         ? bufs.get_midi(index).begin()
1614                                         : silent_bufs.get_midi(0).end();
1615                                 MidiBuffer::iterator m_end = (index != nil_index)
1616                                         ? bufs.get_midi(index).end()
1617                                         : m;
1618
1619                                 // Now merge MIDI and any transport events into the buffer
1620                                 const uint32_t     type = LV2Plugin::urids.midi_MidiEvent;
1621                                 const framepos_t   tend = _session.transport_frame() + nframes;
1622                                 ++metric_i;
1623                                 while (m != m_end || (metric_i != tmap.metrics_end() &&
1624                                                       (*metric_i)->frame() < tend)) {
1625                                         MetricSection* metric = (metric_i != tmap.metrics_end())
1626                                                 ? *metric_i : NULL;
1627                                         if (m != m_end && (!metric || metric->frame() > (*m).time())) {
1628                                                 const Evoral::MIDIEvent<framepos_t> ev(*m, false);
1629                                                 LV2_Evbuf_Iterator eend = lv2_evbuf_end(_ev_buffers[port_index]);
1630                                                 lv2_evbuf_write(&eend, ev.time(), 0, type, ev.size(), ev.buffer());
1631                                                 ++m;
1632                                         } else {
1633                                                 tmetric.set_metric(metric);
1634                                                 bbt = metric->start();
1635                                                 write_position(&_impl->forge, _ev_buffers[port_index],
1636                                                                tmetric, bbt, _session.transport_speed(),
1637                                                                metric->frame(),
1638                                                                metric->frame() - _session.transport_frame());
1639                                                 ++metric_i;
1640                                         }
1641                                 }
1642                         } else if (!valid) {
1643                                 // Nothing we understand or care about, connect to scratch
1644                                 _ev_buffers[port_index] = silent_bufs.get_lv2_midi(
1645                                         (flags & PORT_INPUT), 0, (flags & PORT_EVENT));
1646                         }
1647                         buf = lv2_evbuf_get_buffer(_ev_buffers[port_index]);
1648                 } else {
1649                         continue;  // Control port, leave buffer alone
1650                 }
1651                 lilv_instance_connect_port(_impl->instance, port_index, buf);
1652         }
1653
1654         // Read messages from UI and push into appropriate buffers
1655         if (_from_ui) {
1656                 uint32_t read_space = _from_ui->read_space();
1657                 while (read_space > sizeof(UIMessage)) {
1658                         UIMessage msg;
1659                         if (_from_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1660                                 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
1661                                 break;
1662                         }
1663                         uint8_t body[msg.size];
1664                         if (_from_ui->read(body, msg.size) != msg.size) {
1665                                 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
1666                                 break;
1667                         }
1668                         if (msg.protocol == urids.atom_eventTransfer) {
1669                                 LV2_Evbuf*            buf  = _ev_buffers[msg.index];
1670                                 LV2_Evbuf_Iterator    i    = lv2_evbuf_end(buf);
1671                                 const LV2_Atom* const atom = (const LV2_Atom*)body;
1672                                 if (!lv2_evbuf_write(&i, nframes, 0, atom->type, atom->size,
1673                                                 (const uint8_t*)(atom + 1))) {
1674                                         error << "Failed to write data to LV2 event buffer\n";
1675                                 }
1676                         } else {
1677                                 error << "Received unknown message type from UI" << endmsg;
1678                         }
1679                         read_space -= sizeof(UIMessage) + msg.size;
1680                 }
1681         }
1682
1683         run(nframes);
1684
1685         midi_out_index = 0;
1686         for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
1687                 PortFlags flags = _port_flags[port_index];
1688                 bool      valid = false;
1689
1690                 /* TODO ask drobilla about comment
1691                  * "Make Ardour event buffers generic so plugins can communicate"
1692                  * in libs/ardour/buffer_set.cc:310
1693                  *
1694                  * ideally the user could choose which of the following two modes
1695                  * to use (e.g. instrument/effect chains  MIDI OUT vs MIDI TRHU).
1696                  *
1697                  * This implementation follows the discussion on IRC Mar 16 2013 16:47 UTC
1698                  * 16:51 < drobilla> rgareus: [..] i.e always replace with MIDI output [of LV2 plugin] if it's there
1699                  * 16:52 < drobilla> rgareus: That would probably be good enough [..] to make users not complain
1700                  *                            for quite a while at least ;)
1701                  */
1702                 // copy output of LV2 plugin's MIDI port to Ardour MIDI buffers -- MIDI OUT
1703                 if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE|PORT_MIDI))) {
1704                         const uint32_t buf_index = out_map.get(
1705                                 DataType::MIDI, midi_out_index++, &valid);
1706                         if (valid) {
1707                                 bufs.forward_lv2_midi(_ev_buffers[port_index], buf_index);
1708                         }
1709                 }
1710                 // Flush MIDI (write back to Ardour MIDI buffers) -- MIDI THRU
1711                 else if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
1712                         const uint32_t buf_index = out_map.get(
1713                                 DataType::MIDI, midi_out_index++, &valid);
1714                         if (valid) {
1715                                 bufs.flush_lv2_midi(true, buf_index);
1716                         }
1717                 }
1718
1719                 // Write messages to UI
1720                 if (_to_ui && (flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
1721                         LV2_Evbuf* buf = _ev_buffers[port_index];
1722                         for (LV2_Evbuf_Iterator i = lv2_evbuf_begin(buf);
1723                              lv2_evbuf_is_valid(i);
1724                              i = lv2_evbuf_next(i)) {
1725                                 uint32_t frames, subframes, type, size;
1726                                 uint8_t* data;
1727                                 lv2_evbuf_get(i, &frames, &subframes, &type, &size, &data);
1728                                 write_to_ui(port_index, urids.atom_eventTransfer,
1729                                             size + sizeof(LV2_Atom),
1730                                             data - sizeof(LV2_Atom));
1731                         }
1732                 }
1733         }
1734
1735         cycles_t now = get_cycles();
1736         set_cycles((uint32_t)(now - then));
1737
1738         // Update expected transport information for next cycle so we can detect changes
1739         _next_cycle_speed = _session.transport_speed();
1740         _next_cycle_start = _session.transport_frame() + (nframes * _next_cycle_speed);
1741
1742         return 0;
1743 }
1744
1745 bool
1746 LV2Plugin::parameter_is_control(uint32_t param) const
1747 {
1748         assert(param < _port_flags.size());
1749         return _port_flags[param] & PORT_CONTROL;
1750 }
1751
1752 bool
1753 LV2Plugin::parameter_is_audio(uint32_t param) const
1754 {
1755         assert(param < _port_flags.size());
1756         return _port_flags[param] & PORT_AUDIO;
1757 }
1758
1759 bool
1760 LV2Plugin::parameter_is_event(uint32_t param) const
1761 {
1762         assert(param < _port_flags.size());
1763         return _port_flags[param] & PORT_EVENT;
1764 }
1765
1766 bool
1767 LV2Plugin::parameter_is_output(uint32_t param) const
1768 {
1769         assert(param < _port_flags.size());
1770         return _port_flags[param] & PORT_OUTPUT;
1771 }
1772
1773 bool
1774 LV2Plugin::parameter_is_input(uint32_t param) const
1775 {
1776         assert(param < _port_flags.size());
1777         return _port_flags[param] & PORT_INPUT;
1778 }
1779
1780 void
1781 LV2Plugin::print_parameter(uint32_t param, char* buf, uint32_t len) const
1782 {
1783         if (buf && len) {
1784                 if (param < parameter_count()) {
1785                         snprintf(buf, len, "%.3f", get_parameter(param));
1786                 } else {
1787                         strcat(buf, "0");
1788                 }
1789         }
1790 }
1791
1792 boost::shared_ptr<Plugin::ScalePoints>
1793 LV2Plugin::get_scale_points(uint32_t port_index) const
1794 {
1795         const LilvPort*  port   = lilv_plugin_get_port_by_index(_impl->plugin, port_index);
1796         LilvScalePoints* points = lilv_port_get_scale_points(_impl->plugin, port);
1797
1798         boost::shared_ptr<Plugin::ScalePoints> ret;
1799         if (!points) {
1800                 return ret;
1801         }
1802
1803         ret = boost::shared_ptr<Plugin::ScalePoints>(new ScalePoints());
1804
1805         LILV_FOREACH(scale_points, i, points) {
1806                 const LilvScalePoint* p     = lilv_scale_points_get(points, i);
1807                 const LilvNode*       label = lilv_scale_point_get_label(p);
1808                 const LilvNode*       value = lilv_scale_point_get_value(p);
1809                 if (label && (lilv_node_is_float(value) || lilv_node_is_int(value))) {
1810                         ret->insert(make_pair(lilv_node_as_string(label),
1811                                               lilv_node_as_float(value)));
1812                 }
1813         }
1814
1815         lilv_scale_points_free(points);
1816         return ret;
1817 }
1818
1819 void
1820 LV2Plugin::run(pframes_t nframes)
1821 {
1822         uint32_t const N = parameter_count();
1823         for (uint32_t i = 0; i < N; ++i) {
1824                 if (parameter_is_control(i) && parameter_is_input(i)) {
1825                         _control_data[i] = _shadow_data[i];
1826                 }
1827         }
1828
1829         lilv_instance_run(_impl->instance, nframes);
1830
1831         if (_impl->work_iface) {
1832                 _worker->emit_responses();
1833                 if (_impl->work_iface->end_run) {
1834                         _impl->work_iface->end_run(_impl->instance->lv2_handle);
1835                 }
1836         }
1837 }
1838
1839 void
1840 LV2Plugin::latency_compute_run()
1841 {
1842         if (!_latency_control_port) {
1843                 return;
1844         }
1845
1846         // Run the plugin so that it can set its latency parameter
1847
1848         activate();
1849
1850         uint32_t port_index = 0;
1851         uint32_t in_index   = 0;
1852         uint32_t out_index  = 0;
1853
1854         const framecnt_t bufsize = 1024;
1855         float            buffer[bufsize];
1856
1857         memset(buffer, 0, sizeof(float) * bufsize);
1858
1859         // FIXME: Ensure plugins can handle in-place processing
1860
1861         port_index = 0;
1862
1863         while (port_index < parameter_count()) {
1864                 if (parameter_is_audio(port_index)) {
1865                         if (parameter_is_input(port_index)) {
1866                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1867                                 in_index++;
1868                         } else if (parameter_is_output(port_index)) {
1869                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1870                                 out_index++;
1871                         }
1872                 }
1873                 port_index++;
1874         }
1875
1876         run(bufsize);
1877         deactivate();
1878 }
1879
1880 const LilvPort*
1881 LV2Plugin::Impl::designated_input (const char* uri, void** bufptrs[], void** bufptr)
1882 {
1883         const LilvPort* port = NULL;
1884         LilvNode* designation = lilv_new_uri(_world.world, uri);
1885         port = lilv_plugin_get_port_by_designation(
1886                 plugin, _world.lv2_InputPort, designation);
1887         lilv_node_free(designation);
1888         if (port) {
1889                 bufptrs[lilv_port_get_index(plugin, port)] = bufptr;
1890         }
1891         return port;
1892 }
1893
1894 LV2World::LV2World()
1895         : world(lilv_world_new())
1896 {
1897         lilv_world_load_all(world);
1898         atom_AtomPort      = lilv_new_uri(world, LV2_ATOM__AtomPort);
1899         atom_Chunk         = lilv_new_uri(world, LV2_ATOM__Chunk);
1900         atom_Sequence      = lilv_new_uri(world, LV2_ATOM__Sequence);
1901         atom_bufferType    = lilv_new_uri(world, LV2_ATOM__bufferType);
1902         atom_supports      = lilv_new_uri(world, LV2_ATOM__supports);
1903         atom_eventTransfer = lilv_new_uri(world, LV2_ATOM__eventTransfer);
1904         ev_EventPort       = lilv_new_uri(world, LILV_URI_EVENT_PORT);
1905         ext_logarithmic    = lilv_new_uri(world, LV2_PORT_PROPS__logarithmic);
1906         ext_notOnGUI       = lilv_new_uri(world, LV2_PORT_PROPS__notOnGUI);
1907         lv2_AudioPort      = lilv_new_uri(world, LILV_URI_AUDIO_PORT);
1908         lv2_ControlPort    = lilv_new_uri(world, LILV_URI_CONTROL_PORT);
1909         lv2_InputPort      = lilv_new_uri(world, LILV_URI_INPUT_PORT);
1910         lv2_OutputPort     = lilv_new_uri(world, LILV_URI_OUTPUT_PORT);
1911         lv2_inPlaceBroken  = lilv_new_uri(world, LV2_CORE__inPlaceBroken);
1912         lv2_integer        = lilv_new_uri(world, LV2_CORE__integer);
1913         lv2_reportsLatency = lilv_new_uri(world, LV2_CORE__reportsLatency);
1914         lv2_sampleRate     = lilv_new_uri(world, LV2_CORE__sampleRate);
1915         lv2_toggled        = lilv_new_uri(world, LV2_CORE__toggled);
1916         lv2_enumeration    = lilv_new_uri(world, LV2_CORE__enumeration);
1917         lv2_freewheeling   = lilv_new_uri(world, LV2_CORE__freeWheeling);
1918         midi_MidiEvent     = lilv_new_uri(world, LILV_URI_MIDI_EVENT);
1919         rdfs_comment       = lilv_new_uri(world, LILV_NS_RDFS "comment");
1920         rsz_minimumSize    = lilv_new_uri(world, LV2_RESIZE_PORT__minimumSize);
1921         time_Position      = lilv_new_uri(world, LV2_TIME__Position);
1922         ui_GtkUI           = lilv_new_uri(world, LV2_UI__GtkUI);
1923         ui_external        = lilv_new_uri(world, "http://lv2plug.in/ns/extensions/ui#external");
1924 }
1925
1926 LV2World::~LV2World()
1927 {
1928         lilv_node_free(ui_external);
1929         lilv_node_free(ui_GtkUI);
1930         lilv_node_free(time_Position);
1931         lilv_node_free(rsz_minimumSize);
1932         lilv_node_free(rdfs_comment);
1933         lilv_node_free(midi_MidiEvent);
1934         lilv_node_free(lv2_enumeration);
1935         lilv_node_free(lv2_freewheeling);
1936         lilv_node_free(lv2_toggled);
1937         lilv_node_free(lv2_sampleRate);
1938         lilv_node_free(lv2_reportsLatency);
1939         lilv_node_free(lv2_integer);
1940         lilv_node_free(lv2_inPlaceBroken);
1941         lilv_node_free(lv2_OutputPort);
1942         lilv_node_free(lv2_InputPort);
1943         lilv_node_free(lv2_ControlPort);
1944         lilv_node_free(lv2_AudioPort);
1945         lilv_node_free(ext_notOnGUI);
1946         lilv_node_free(ext_logarithmic);
1947         lilv_node_free(ev_EventPort);
1948         lilv_node_free(atom_supports);
1949         lilv_node_free(atom_eventTransfer);
1950         lilv_node_free(atom_bufferType);
1951         lilv_node_free(atom_Sequence);
1952         lilv_node_free(atom_Chunk);
1953         lilv_node_free(atom_AtomPort);
1954 }
1955
1956 LV2PluginInfo::LV2PluginInfo (const void* c_plugin)
1957         : _c_plugin(c_plugin)
1958 {
1959         type = ARDOUR::LV2;
1960 }
1961
1962 LV2PluginInfo::~LV2PluginInfo()
1963 {}
1964
1965 PluginPtr
1966 LV2PluginInfo::load(Session& session)
1967 {
1968         try {
1969                 PluginPtr plugin;
1970
1971                 plugin.reset(new LV2Plugin(session.engine(), session,
1972                                            (const LilvPlugin*)_c_plugin,
1973                                            session.frame_rate()));
1974
1975                 plugin->set_info(PluginInfoPtr(new LV2PluginInfo(*this)));
1976                 return plugin;
1977         } catch (failed_constructor& err) {
1978                 return PluginPtr((Plugin*)0);
1979         }
1980
1981         return PluginPtr();
1982 }
1983
1984 PluginInfoList*
1985 LV2PluginInfo::discover()
1986 {
1987         PluginInfoList*    plugs   = new PluginInfoList;
1988         const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
1989
1990         info << "LV2: Discovering " << lilv_plugins_size(plugins) << " plugins" << endmsg;
1991
1992         LILV_FOREACH(plugins, i, plugins) {
1993                 const LilvPlugin* p = lilv_plugins_get(plugins, i);
1994                 LV2PluginInfoPtr  info(new LV2PluginInfo((const void*)p));
1995
1996                 LilvNode* name = lilv_plugin_get_name(p);
1997                 if (!name || !lilv_plugin_get_port_by_index(p, 0)) {
1998                         warning << "Ignoring invalid LV2 plugin "
1999                                 << lilv_node_as_string(lilv_plugin_get_uri(p))
2000                                 << endmsg;
2001                         continue;
2002                 }
2003
2004                 info->type = LV2;
2005
2006                 info->name = string(lilv_node_as_string(name));
2007                 lilv_node_free(name);
2008
2009                 const LilvPluginClass* pclass = lilv_plugin_get_class(p);
2010                 const LilvNode*        label  = lilv_plugin_class_get_label(pclass);
2011                 info->category = lilv_node_as_string(label);
2012
2013                 LilvNode* author_name = lilv_plugin_get_author_name(p);
2014                 info->creator = author_name ? string(lilv_node_as_string(author_name)) : "Unknown";
2015                 lilv_node_free(author_name);
2016
2017                 info->path = "/NOPATH"; // Meaningless for LV2
2018
2019                 /* count atom-event-ports that feature
2020                  * atom:supports <http://lv2plug.in/ns/ext/midi#MidiEvent>
2021                  *
2022                  * TODO: nicely ask drobilla to make a lilv_ call for that
2023                  */
2024                 int count_midi_out = 0;
2025                 int count_midi_in = 0;
2026                 for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
2027                         const LilvPort* port  = lilv_plugin_get_port_by_index(p, i);
2028                         if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
2029                                 LilvNodes* buffer_types = lilv_port_get_value(
2030                                         p, port, _world.atom_bufferType);
2031                                 LilvNodes* atom_supports = lilv_port_get_value(
2032                                         p, port, _world.atom_supports);
2033
2034                                 if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)
2035                                                 && lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
2036                                         if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
2037                                                 count_midi_in++;
2038                                         }
2039                                         if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
2040                                                 count_midi_out++;
2041                                         }
2042                                 }
2043                                 lilv_nodes_free(buffer_types);
2044                                 lilv_nodes_free(atom_supports);
2045                         }
2046                 }
2047
2048                 info->n_inputs.set_audio(
2049                         lilv_plugin_get_num_ports_of_class(
2050                                 p, _world.lv2_InputPort, _world.lv2_AudioPort, NULL));
2051                 info->n_inputs.set_midi(
2052                         lilv_plugin_get_num_ports_of_class(
2053                                 p, _world.lv2_InputPort, _world.ev_EventPort, NULL)
2054                         + count_midi_in);
2055
2056                 info->n_outputs.set_audio(
2057                         lilv_plugin_get_num_ports_of_class(
2058                                 p, _world.lv2_OutputPort, _world.lv2_AudioPort, NULL));
2059                 info->n_outputs.set_midi(
2060                         lilv_plugin_get_num_ports_of_class(
2061                                 p, _world.lv2_OutputPort, _world.ev_EventPort, NULL)
2062                         + count_midi_out);
2063
2064                 info->unique_id = lilv_node_as_uri(lilv_plugin_get_uri(p));
2065                 info->index     = 0; // Meaningless for LV2
2066
2067                 plugs->push_back(info);
2068         }
2069
2070         return plugs;
2071 }