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