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