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