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