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