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