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