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