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