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