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