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