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