we always only use the "C" locale when saving.
[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 "pbd/gstdio_compat.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/extensions/units/units.h"
70 #include "lv2/lv2plug.in/ns/ext/patch/patch.h"
71 #ifdef HAVE_LV2_1_2_0
72 #include "lv2/lv2plug.in/ns/ext/buf-size/buf-size.h"
73 #include "lv2/lv2plug.in/ns/ext/options/options.h"
74 #endif
75
76 #include "lv2_evbuf.h"
77
78 #ifdef HAVE_SUIL
79 #include <suil/suil.h>
80 #endif
81
82 // Compatibility for old LV2
83 #ifndef LV2_ATOM_CONTENTS_CONST
84 #define LV2_ATOM_CONTENTS_CONST(type, atom) \
85         ((const void*)((const uint8_t*)(atom) + sizeof(type)))
86 #endif
87 #ifndef LV2_ATOM_BODY_CONST
88 #define LV2_ATOM_BODY_CONST(atom) LV2_ATOM_CONTENTS_CONST(LV2_Atom, atom)
89 #endif
90 #ifndef LV2_PATCH__property
91 #define LV2_PATCH__property LV2_PATCH_PREFIX "property"
92 #endif
93 #ifndef LV2_PATCH__value
94 #define LV2_PATCH__value LV2_PATCH_PREFIX "value"
95 #endif
96 #ifndef LV2_PATCH__writable
97 #define LV2_PATCH__writable LV2_PATCH_PREFIX "writable"
98 #endif
99
100 /** The number of MIDI buffers that will fit in a UI/worker comm buffer.
101     This needs to be roughly the number of cycles the UI will get around to
102     actually processing the traffic.  Lower values are flakier but save memory.
103 */
104 static const size_t NBUFS = 4;
105
106 using namespace std;
107 using namespace ARDOUR;
108 using namespace PBD;
109
110 class LV2World : boost::noncopyable {
111 public:
112         LV2World ();
113         ~LV2World ();
114
115         void load_bundled_plugins(bool verbose=false);
116
117         LilvWorld* world;
118
119         LilvNode* atom_AtomPort;
120         LilvNode* atom_Chunk;
121         LilvNode* atom_Sequence;
122         LilvNode* atom_bufferType;
123         LilvNode* atom_eventTransfer;
124         LilvNode* atom_supports;
125         LilvNode* ev_EventPort;
126         LilvNode* ext_logarithmic;
127         LilvNode* ext_notOnGUI;
128         LilvNode* lv2_AudioPort;
129         LilvNode* lv2_ControlPort;
130         LilvNode* lv2_InputPort;
131         LilvNode* lv2_OutputPort;
132         LilvNode* lv2_enumeration;
133         LilvNode* lv2_freewheeling;
134         LilvNode* lv2_inPlaceBroken;
135         LilvNode* lv2_isSideChain;
136         LilvNode* lv2_integer;
137         LilvNode* lv2_default;
138         LilvNode* lv2_minimum;
139         LilvNode* lv2_maximum;
140         LilvNode* lv2_reportsLatency;
141         LilvNode* lv2_sampleRate;
142         LilvNode* lv2_toggled;
143         LilvNode* midi_MidiEvent;
144         LilvNode* rdfs_comment;
145         LilvNode* rdfs_label;
146         LilvNode* rdfs_range;
147         LilvNode* rsz_minimumSize;
148         LilvNode* time_Position;
149         LilvNode* ui_GtkUI;
150         LilvNode* ui_external;
151         LilvNode* ui_externalkx;
152         LilvNode* units_hz;
153         LilvNode* units_db;
154         LilvNode* units_unit;
155         LilvNode* units_render;
156         LilvNode* units_midiNote;
157         LilvNode* patch_writable;
158         LilvNode* patch_Message;
159 #ifdef HAVE_LV2_1_2_0
160         LilvNode* bufz_powerOf2BlockLength;
161         LilvNode* bufz_fixedBlockLength;
162         LilvNode* bufz_nominalBlockLength;
163 #endif
164
165 #ifdef HAVE_LV2_1_10_0
166         LilvNode* atom_int;
167         LilvNode* atom_float;
168         LilvNode* atom_object; // new in 1.8
169         LilvNode* atom_vector;
170 #endif
171 #ifdef LV2_EXTENDED
172         LilvNode* lv2_noSampleAccurateCtrl;
173         LilvNode* auto_can_write_automatation; // lv2:optionalFeature
174         LilvNode* auto_automation_control; // atom:supports
175         LilvNode* auto_automation_controlled; // lv2:portProperty
176 #endif
177
178 private:
179         bool _bundle_checked;
180 };
181
182 static LV2World _world;
183
184 /* worker extension */
185
186 /** Called by the plugin to schedule non-RT work. */
187 static LV2_Worker_Status
188 work_schedule(LV2_Worker_Schedule_Handle handle,
189               uint32_t                   size,
190               const void*                data)
191 {
192         LV2Plugin* plugin = (LV2Plugin*)handle;
193         if (plugin->session().engine().freewheeling()) {
194                 // Freewheeling, do the work immediately in this (audio) thread
195                 return (LV2_Worker_Status)plugin->work(size, data);
196         } else {
197                 // Enqueue message for the worker thread
198                 return plugin->worker()->schedule(size, data) ?
199                         LV2_WORKER_SUCCESS : LV2_WORKER_ERR_UNKNOWN;
200         }
201 }
202
203 /** Called by the plugin to respond to non-RT work. */
204 static LV2_Worker_Status
205 work_respond(LV2_Worker_Respond_Handle handle,
206              uint32_t                  size,
207              const void*               data)
208 {
209         LV2Plugin* plugin = (LV2Plugin*)handle;
210         if (plugin->session().engine().freewheeling()) {
211                 // Freewheeling, respond immediately in this (audio) thread
212                 return (LV2_Worker_Status)plugin->work_response(size, data);
213         } else {
214                 // Enqueue response for the worker
215                 return plugin->worker()->respond(size, data) ?
216                         LV2_WORKER_SUCCESS : LV2_WORKER_ERR_UNKNOWN;
217         }
218 }
219
220 #ifdef LV2_EXTENDED
221 /* inline display extension */
222 static void
223 queue_draw (LV2_Inline_Display_Handle handle)
224 {
225         LV2Plugin* plugin = (LV2Plugin*)handle;
226         plugin->QueueDraw(); /* EMIT SIGNAL */
227 }
228 #endif
229
230 /* log extension */
231
232 static int
233 log_vprintf(LV2_Log_Handle /*handle*/,
234             LV2_URID       type,
235             const char*    fmt,
236             va_list        args)
237 {
238         char* str = NULL;
239         const int ret = g_vasprintf(&str, fmt, args);
240         if (type == URIMap::instance().urids.log_Error) {
241                 error << str << endmsg;
242         } else if (type == URIMap::instance().urids.log_Warning) {
243                 warning << str << endmsg;
244         } else if (type == URIMap::instance().urids.log_Note) {
245                 info << str << endmsg;
246         }
247         // TODO: Toggleable log:Trace message support
248         return ret;
249 }
250
251 static int
252 log_printf(LV2_Log_Handle handle,
253            LV2_URID       type,
254            const char*    fmt, ...)
255 {
256         va_list args;
257         va_start(args, fmt);
258         const int ret = log_vprintf(handle, type, fmt, args);
259         va_end(args);
260         return ret;
261 }
262
263 struct LV2Plugin::Impl {
264         Impl() : plugin(0), ui(0), ui_type(0), name(0), author(0), instance(0)
265                , work_iface(0)
266 #ifdef HAVE_LV2_1_2_0
267                , opts_iface(0)
268 #endif
269                , state(0)
270                , block_length(0)
271 #ifdef HAVE_LV2_1_2_0
272                , options(0)
273 #endif
274 #ifdef LV2_EXTENDED
275                , queue_draw(0)
276 #endif
277         {}
278
279         /** Find the LV2 input port with the given designation.
280          * If found, bufptrs[port_index] will be set to bufptr.
281          */
282         const LilvPort* designated_input (const char* uri, void** bufptrs[], void** bufptr);
283
284         const LilvPlugin*            plugin;
285         const LilvUI*                ui;
286         const LilvNode*              ui_type;
287         LilvNode*                    name;
288         LilvNode*                    author;
289         LilvInstance*                instance;
290         const LV2_Worker_Interface*  work_iface;
291 #ifdef HAVE_LV2_1_2_0
292         const LV2_Options_Interface* opts_iface;
293 #endif
294         LilvState*                   state;
295         LV2_Atom_Forge               forge;
296         LV2_Atom_Forge               ui_forge;
297         int32_t                      block_length;
298 #ifdef HAVE_LV2_1_2_0
299         LV2_Options_Option*          options;
300 #endif
301 #ifdef LV2_EXTENDED
302         LV2_Inline_Display*          queue_draw;
303 #endif
304 };
305
306 LV2Plugin::LV2Plugin (AudioEngine& engine,
307                       Session&     session,
308                       const void*  c_plugin,
309                       framecnt_t   rate)
310         : Plugin (engine, session)
311         , Workee ()
312         , _impl(new Impl())
313         , _features(NULL)
314         , _worker(NULL)
315         , _insert_id("0")
316         , _patch_port_in_index((uint32_t)-1)
317         , _patch_port_out_index((uint32_t)-1)
318         , _uri_map(URIMap::instance())
319         , _no_sample_accurate_ctrl (false)
320 {
321         init(c_plugin, rate);
322 }
323
324 LV2Plugin::LV2Plugin (const LV2Plugin& other)
325         : Plugin (other)
326         , Workee ()
327         , _impl(new Impl())
328         , _features(NULL)
329         , _worker(NULL)
330         , _insert_id(other._insert_id)
331         , _patch_port_in_index((uint32_t)-1)
332         , _patch_port_out_index((uint32_t)-1)
333         , _uri_map(URIMap::instance())
334         , _no_sample_accurate_ctrl (false)
335 {
336         init(other._impl->plugin, other._sample_rate);
337
338         for (uint32_t i = 0; i < parameter_count(); ++i) {
339                 _control_data[i] = other._shadow_data[i];
340                 _shadow_data[i]  = other._shadow_data[i];
341         }
342 }
343
344 void
345 LV2Plugin::init(const void* c_plugin, framecnt_t rate)
346 {
347         DEBUG_TRACE(DEBUG::LV2, "init\n");
348
349         _impl->plugin           = (const LilvPlugin*)c_plugin;
350         _impl->ui               = NULL;
351         _impl->ui_type          = NULL;
352         _to_ui                  = NULL;
353         _from_ui                = NULL;
354         _control_data           = 0;
355         _shadow_data            = 0;
356         _atom_ev_buffers        = 0;
357         _ev_buffers             = 0;
358         _bpm_control_port       = 0;
359         _freewheel_control_port = 0;
360         _latency_control_port   = 0;
361         _next_cycle_start       = std::numeric_limits<framepos_t>::max();
362         _next_cycle_speed       = 1.0;
363         _seq_size               = _engine.raw_buffer_size(DataType::MIDI);
364         _state_version          = 0;
365         _was_activated          = false;
366         _has_state_interface    = false;
367         _can_write_automation   = false;
368         _max_latency            = 0;
369         _current_latency        = 0;
370         _impl->block_length     = _session.get_block_size();
371
372         _instance_access_feature.URI = "http://lv2plug.in/ns/ext/instance-access";
373         _data_access_feature.URI     = "http://lv2plug.in/ns/ext/data-access";
374         _make_path_feature.URI       = LV2_STATE__makePath;
375         _log_feature.URI             = LV2_LOG__log;
376         _work_schedule_feature.URI   = LV2_WORKER__schedule;
377         _work_schedule_feature.data  = NULL;
378         _def_state_feature.URI       = LV2_STATE_PREFIX "loadDefaultState";  // Post LV2-1.2.0
379         _def_state_feature.data      = NULL;
380
381         const LilvPlugin* plugin = _impl->plugin;
382
383         LilvNode* state_iface_uri = lilv_new_uri(_world.world, LV2_STATE__interface);
384         LilvNode* state_uri       = lilv_new_uri(_world.world, LV2_STATE_URI);
385         _has_state_interface =
386                 // What plugins should have (lv2:extensionData state:Interface)
387                 lilv_plugin_has_extension_data(plugin, state_iface_uri)
388                 // What some outdated/incorrect ones have
389                 || lilv_plugin_has_feature(plugin, state_uri);
390         lilv_node_free(state_uri);
391         lilv_node_free(state_iface_uri);
392
393         _features    = (LV2_Feature**)calloc(12, sizeof(LV2_Feature*));
394         _features[0] = &_instance_access_feature;
395         _features[1] = &_data_access_feature;
396         _features[2] = &_make_path_feature;
397         _features[3] = _uri_map.uri_map_feature();
398         _features[4] = _uri_map.urid_map_feature();
399         _features[5] = _uri_map.urid_unmap_feature();
400         _features[6] = &_log_feature;
401
402         unsigned n_features = 7;
403 #ifdef HAVE_LV2_1_2_0
404         _features[n_features++] = &_def_state_feature;
405 #endif
406
407         lv2_atom_forge_init(&_impl->forge, _uri_map.urid_map());
408         lv2_atom_forge_init(&_impl->ui_forge, _uri_map.urid_map());
409
410 #ifdef LV2_EXTENDED
411         _impl->queue_draw = (LV2_Inline_Display*)
412                 malloc (sizeof(LV2_Inline_Display));
413         _impl->queue_draw->handle     = this;
414         _impl->queue_draw->queue_draw = queue_draw;
415
416         _queue_draw_feature.URI  = LV2_INLINEDISPLAY__queue_draw;
417         _queue_draw_feature.data = _impl->queue_draw;
418         _features[n_features++]  = &_queue_draw_feature;
419 #endif
420
421 #ifdef HAVE_LV2_1_2_0
422         LV2_URID atom_Int = _uri_map.uri_to_id(LV2_ATOM__Int);
423         static const int32_t _min_block_length = 1;   // may happen during split-cycles
424         static const int32_t _max_block_length = 8192; // max possible (with all engines and during export)
425         /* Consider updating max-block-size whenever the buffersize changes.
426          * It requires re-instantiating the plugin (which is a non-realtime operation),
427          * so it should be done lightly and only for plugins that require it.
428          *
429          * given that the block-size can change at any time (split-cycles) ardour currently
430          * does not support plugins that require bufz_fixedBlockLength.
431          */
432         LV2_Options_Option options[] = {
433                 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__minBlockLength),
434                   sizeof(int32_t), atom_Int, &_min_block_length },
435                 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__maxBlockLength),
436                   sizeof(int32_t), atom_Int, &_max_block_length },
437                 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__sequenceSize),
438                   sizeof(int32_t), atom_Int, &_seq_size },
439                 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id("http://lv2plug.in/ns/ext/buf-size#nominalBlockLength"),
440                   sizeof(int32_t), atom_Int, &_impl->block_length },
441                 { LV2_OPTIONS_INSTANCE, 0, 0, 0, 0, NULL }
442         };
443
444         _impl->options = (LV2_Options_Option*) malloc (sizeof (options));
445         memcpy ((void*) _impl->options, (void*) options, sizeof (options));
446
447         _options_feature.URI    = LV2_OPTIONS__options;
448         _options_feature.data   = _impl->options;
449         _features[n_features++] = &_options_feature;
450 #endif
451
452         LV2_State_Make_Path* make_path = (LV2_State_Make_Path*)malloc(
453                 sizeof(LV2_State_Make_Path));
454         make_path->handle = this;
455         make_path->path = &lv2_state_make_path;
456         _make_path_feature.data = make_path;
457
458         LV2_Log_Log* log = (LV2_Log_Log*)malloc(sizeof(LV2_Log_Log));
459         log->handle  = this;
460         log->printf  = &log_printf;
461         log->vprintf = &log_vprintf;
462         _log_feature.data = log;
463
464         LilvNode* worker_schedule = lilv_new_uri(_world.world, LV2_WORKER__schedule);
465         if (lilv_plugin_has_feature(plugin, worker_schedule)) {
466                 LV2_Worker_Schedule* schedule = (LV2_Worker_Schedule*)malloc(
467                         sizeof(LV2_Worker_Schedule));
468                 size_t buf_size = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
469                 _worker                     = new Worker(this, buf_size);
470                 schedule->handle            = this;
471                 schedule->schedule_work     = work_schedule;
472                 _work_schedule_feature.data = schedule;
473                 _features[n_features++]     = &_work_schedule_feature;
474         }
475         lilv_node_free(worker_schedule);
476
477         _impl->instance = lilv_plugin_instantiate(plugin, rate, _features);
478         _impl->name     = lilv_plugin_get_name(plugin);
479         _impl->author   = lilv_plugin_get_author_name(plugin);
480
481         if (_impl->instance == 0) {
482                 error << _("LV2: Failed to instantiate plugin ") << uri() << endmsg;
483                 throw failed_constructor();
484         }
485
486         _instance_access_feature.data              = (void*)_impl->instance->lv2_handle;
487         _data_access_extension_data.extension_data = _impl->instance->lv2_descriptor->extension_data;
488         _data_access_feature.data                  = &_data_access_extension_data;
489
490         LilvNode* worker_iface_uri = lilv_new_uri(_world.world, LV2_WORKER__interface);
491         if (lilv_plugin_has_extension_data(plugin, worker_iface_uri)) {
492                 _impl->work_iface = (const LV2_Worker_Interface*)extension_data(
493                         LV2_WORKER__interface);
494         }
495         lilv_node_free(worker_iface_uri);
496
497
498 #ifdef HAVE_LV2_1_2_0
499         LilvNode* options_iface_uri = lilv_new_uri(_world.world, LV2_OPTIONS__interface);
500         if (lilv_plugin_has_extension_data(plugin, options_iface_uri)) {
501                 _impl->opts_iface = (const LV2_Options_Interface*)extension_data(
502                         LV2_OPTIONS__interface);
503         }
504         lilv_node_free(options_iface_uri);
505 #endif
506
507 #ifdef LV2_EXTENDED
508         _display_interface = (const LV2_Inline_Display_Interface*)
509                 extension_data (LV2_INLINEDISPLAY__interface);
510 #endif
511
512         if (lilv_plugin_has_feature(plugin, _world.lv2_inPlaceBroken)) {
513                 error << string_compose(
514                     _("LV2: \"%1\" cannot be used, since it cannot do inplace processing."),
515                     lilv_node_as_string(_impl->name)) << endmsg;
516                 lilv_node_free(_impl->name);
517                 lilv_node_free(_impl->author);
518                 throw failed_constructor();
519         }
520
521 #ifdef HAVE_LV2_1_2_0
522         LilvNodes *required_features = lilv_plugin_get_required_features (plugin);
523         if (lilv_nodes_contains (required_features, _world.bufz_powerOf2BlockLength) ||
524                         lilv_nodes_contains (required_features, _world.bufz_fixedBlockLength)
525            ) {
526                 error << string_compose(
527                     _("LV2: \"%1\" buffer-size requirements cannot be satisfied."),
528                     lilv_node_as_string(_impl->name)) << endmsg;
529                 lilv_node_free(_impl->name);
530                 lilv_node_free(_impl->author);
531                 lilv_nodes_free(required_features);
532                 throw failed_constructor();
533         }
534         lilv_nodes_free(required_features);
535 #endif
536
537 #ifdef LV2_EXTENDED
538         LilvNodes* optional_features = lilv_plugin_get_optional_features (plugin);
539         if (lilv_nodes_contains (optional_features, _world.lv2_noSampleAccurateCtrl)) {
540                 _no_sample_accurate_ctrl = true;
541         }
542         if (lilv_nodes_contains (optional_features, _world.auto_can_write_automatation)) {
543                 _can_write_automation = true;
544         }
545         lilv_nodes_free(optional_features);
546 #endif
547
548 #ifdef HAVE_LILV_0_16_0
549         // Load default state
550         LilvState* state = lilv_state_new_from_world(
551                 _world.world, _uri_map.urid_map(), lilv_plugin_get_uri(_impl->plugin));
552         if (state && _has_state_interface) {
553                 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
554         }
555         lilv_state_free(state);
556 #endif
557
558         _sample_rate = rate;
559
560         const uint32_t num_ports = this->num_ports();
561         for (uint32_t i = 0; i < num_ports; ++i) {
562                 const LilvPort* port  = lilv_plugin_get_port_by_index(_impl->plugin, i);
563                 PortFlags       flags = 0;
564                 size_t          minimumSize = 0;
565
566                 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_OutputPort)) {
567                         flags |= PORT_OUTPUT;
568                 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_InputPort)) {
569                         flags |= PORT_INPUT;
570                 } else {
571                         error << string_compose(
572                                 "LV2: \"%1\" port %2 is neither input nor output",
573                                 lilv_node_as_string(_impl->name), i) << endmsg;
574                         throw failed_constructor();
575                 }
576
577                 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_ControlPort)) {
578                         flags |= PORT_CONTROL;
579                 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_AudioPort)) {
580                         flags |= PORT_AUDIO;
581                 } else if (lilv_port_is_a(_impl->plugin, port, _world.ev_EventPort)) {
582                         flags |= PORT_EVENT;
583                         flags |= PORT_MIDI;  // We assume old event API ports are for MIDI
584                 } else if (lilv_port_is_a(_impl->plugin, port, _world.atom_AtomPort)) {
585                         LilvNodes* buffer_types = lilv_port_get_value(
586                                 _impl->plugin, port, _world.atom_bufferType);
587                         LilvNodes* atom_supports = lilv_port_get_value(
588                                 _impl->plugin, port, _world.atom_supports);
589
590                         if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)) {
591                                 flags |= PORT_SEQUENCE;
592                                 if (lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
593                                         flags |= PORT_MIDI;
594                                 }
595                                 if (lilv_nodes_contains(atom_supports, _world.time_Position)) {
596                                         flags |= PORT_POSITION;
597                                 }
598 #ifdef LV2_EXTENDED
599                                 if (lilv_nodes_contains(atom_supports, _world.auto_automation_control)) {
600                                         flags |= PORT_AUTOCTRL;
601                                 }
602 #endif
603                                 if (lilv_nodes_contains(atom_supports, _world.patch_Message)) {
604                                         flags |= PORT_PATCHMSG;
605                                         if (flags & PORT_INPUT) {
606                                                 _patch_port_in_index = i;
607                                         } else {
608                                                 _patch_port_out_index = i;
609                                         }
610                                 }
611                         }
612                         LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
613                         LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
614                         if (min_size && lilv_node_is_int(min_size)) {
615                                 minimumSize = lilv_node_as_int(min_size);
616                         }
617                         lilv_nodes_free(min_size_v);
618                         lilv_nodes_free(buffer_types);
619                         lilv_nodes_free(atom_supports);
620                 } else {
621                         error << string_compose(
622                                 "LV2: \"%1\" port %2 has no known data type",
623                                 lilv_node_as_string(_impl->name), i) << endmsg;
624                         throw failed_constructor();
625                 }
626
627 #ifdef LV2_EXTENDED
628                 if (lilv_port_has_property(_impl->plugin, port, _world.auto_automation_controlled)) {
629                         if ((flags & PORT_INPUT) && (flags & PORT_CONTROL)) {
630                                 flags |= PORT_CTRLED;
631                         }
632                 }
633 #endif
634
635                 _port_flags.push_back(flags);
636                 _port_minimumSize.push_back(minimumSize);
637                 DEBUG_TRACE(DEBUG::LV2, string_compose("port %1 buffer %2 bytes\n", i, minimumSize));
638         }
639
640         _control_data = new float[num_ports];
641         _shadow_data  = new float[num_ports];
642         _defaults     = new float[num_ports];
643         _ev_buffers   = new LV2_Evbuf*[num_ports];
644         memset(_ev_buffers, 0, sizeof(LV2_Evbuf*) * num_ports);
645
646         const bool     latent        = lilv_plugin_has_latency(plugin);
647         const uint32_t latency_index = (latent)
648                 ? lilv_plugin_get_latency_port_index(plugin)
649                 : 0;
650
651         // Build an array of pointers to special parameter buffers
652         void*** params = new void**[num_ports];
653         for (uint32_t i = 0; i < num_ports; ++i) {
654                 params[i] = NULL;
655         }
656         _impl->designated_input (LV2_TIME__beatsPerMinute, params, (void**)&_bpm_control_port);
657         _impl->designated_input (LV2_CORE__freeWheeling, params, (void**)&_freewheel_control_port);
658
659         for (uint32_t i = 0; i < num_ports; ++i) {
660                 const LilvPort* port = lilv_plugin_get_port_by_index(plugin, i);
661                 const LilvNode* sym  = lilv_port_get_symbol(plugin, port);
662
663                 // Store index in map so we can look up index by symbol
664                 _port_indices.insert(std::make_pair(lilv_node_as_string(sym), i));
665
666                 // Get range and default value if applicable
667                 if (parameter_is_control(i)) {
668                         LilvNode* def;
669                         lilv_port_get_range(plugin, port, &def, NULL, NULL);
670                         _defaults[i] = def ? lilv_node_as_float(def) : 0.0f;
671                         if (lilv_port_has_property (plugin, port, _world.lv2_sampleRate)) {
672                                 _defaults[i] *= _session.frame_rate ();
673                         }
674                         lilv_node_free(def);
675
676                         lilv_instance_connect_port(_impl->instance, i, &_control_data[i]);
677
678                         if (latent && i == latency_index) {
679                                 LilvNode *max;
680                                 lilv_port_get_range(_impl->plugin, port, NULL, NULL, &max);
681                                 _max_latency = max ? lilv_node_as_float(max) : .02 * _sample_rate;
682                                 _latency_control_port  = &_control_data[i];
683                                 *_latency_control_port = 0;
684                         }
685
686                         if (parameter_is_input(i)) {
687                                 _shadow_data[i] = default_value(i);
688                                 if (params[i]) {
689                                         *params[i] = (void*)&_shadow_data[i];
690                                 }
691                         }
692                 } else {
693                         _defaults[i] = 0.0f;
694                 }
695         }
696
697         delete[] params;
698
699         LilvUIs* uis = lilv_plugin_get_uis(plugin);
700         if (lilv_uis_size(uis) > 0) {
701 #ifdef HAVE_SUIL
702                 // Look for embeddable UI
703                 LILV_FOREACH(uis, u, uis) {
704                         const LilvUI*   this_ui      = lilv_uis_get(uis, u);
705                         const LilvNode* this_ui_type = NULL;
706                         if (lilv_ui_is_supported(this_ui,
707                                                  suil_ui_supported,
708                                                  _world.ui_GtkUI,
709                                                  &this_ui_type)) {
710                                 // TODO: Multiple UI support
711                                 _impl->ui      = this_ui;
712                                 _impl->ui_type = this_ui_type;
713                                 break;
714                         }
715                 }
716 #else
717                 // Look for Gtk native UI
718                 LILV_FOREACH(uis, i, uis) {
719                         const LilvUI* ui = lilv_uis_get(uis, i);
720                         if (lilv_ui_is_a(ui, _world.ui_GtkUI)) {
721                                 _impl->ui      = ui;
722                                 _impl->ui_type = _world.ui_GtkUI;
723                                 break;
724                         }
725                 }
726 #endif
727
728                 // If Gtk UI is not available, try to find external UI
729                 if (!_impl->ui) {
730                         LILV_FOREACH(uis, i, uis) {
731                                 const LilvUI* ui = lilv_uis_get(uis, i);
732                                 if (lilv_ui_is_a(ui, _world.ui_externalkx)) {
733                                         _impl->ui      = ui;
734                                         _impl->ui_type = _world.ui_external;
735                                         break;
736                                 }
737                                 if (lilv_ui_is_a(ui, _world.ui_external)) {
738                                         _impl->ui      = ui;
739                                         _impl->ui_type = _world.ui_external;
740                                 }
741                         }
742                 }
743         }
744
745         load_supported_properties(_property_descriptors);
746         allocate_atom_event_buffers();
747         latency_compute_run();
748 }
749
750 int
751 LV2Plugin::set_block_size (pframes_t nframes)
752 {
753 #ifdef HAVE_LV2_1_2_0
754         if (_impl->opts_iface) {
755                 LV2_URID atom_Int = _uri_map.uri_to_id(LV2_ATOM__Int);
756                 _impl->block_length = nframes;
757                 LV2_Options_Option block_size_option = {
758                         LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id ("http://lv2plug.in/ns/ext/buf-size#nominalBlockLength"),
759                         sizeof(int32_t), atom_Int, (void*)&_impl->block_length
760                 };
761                 _impl->opts_iface->set (_impl->instance->lv2_handle, &block_size_option);
762         }
763 #endif
764         return 0;
765 }
766
767 bool
768 LV2Plugin::requires_fixed_sized_buffers () const
769 {
770         /* This controls if Ardour will split the plugin's run()
771          * on automation events in order to pass sample-accurate automation
772          * via standard control-ports.
773          *
774          * When returning true Ardour will *not* sub-divide the process-cycle.
775          * Automation events that happen between cycle-start and cycle-end will be
776          * ignored (ctrl values are interpolated to cycle-start).
777          * NB. Atom Sequences are still sample accurate.
778          *
779          * Note: This does not guarantee a fixed block-size.
780          * e.g The process cycle may be split when looping, also
781          * the period-size may change any time: see set_block_size()
782          */
783         if (get_info()->n_inputs.n_midi() > 0) {
784                 /* we don't yet implement midi buffer offsets (for split cycles).
785                  * Also connect_and_run() also uses _session.transport_frame() directly
786                  * (for BBT) which is not offset for plugin cycle split.
787                  */
788                 return true;
789         }
790         return _no_sample_accurate_ctrl;
791 }
792
793 LV2Plugin::~LV2Plugin ()
794 {
795         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 destroy\n", name()));
796
797         deactivate();
798         cleanup();
799
800         lilv_instance_free(_impl->instance);
801         lilv_state_free(_impl->state);
802         lilv_node_free(_impl->name);
803         lilv_node_free(_impl->author);
804 #ifdef HAVE_LV2_1_2_0
805         free(_impl->options);
806 #endif
807 #ifdef LV2_EXTENDED
808         free(_impl->queue_draw);
809 #endif
810
811         free(_features);
812         free(_log_feature.data);
813         free(_make_path_feature.data);
814         free(_work_schedule_feature.data);
815
816         delete _to_ui;
817         delete _from_ui;
818         delete _worker;
819
820         if (_atom_ev_buffers) {
821                 LV2_Evbuf**  b = _atom_ev_buffers;
822                 while (*b) {
823                         free(*b);
824                         b++;
825                 }
826                 free(_atom_ev_buffers);
827         }
828
829         delete [] _control_data;
830         delete [] _shadow_data;
831         delete [] _defaults;
832         delete [] _ev_buffers;
833         delete _impl;
834 }
835
836 bool
837 LV2Plugin::is_external_ui() const
838 {
839         if (!_impl->ui) {
840                 return false;
841         }
842         return lilv_ui_is_a(_impl->ui, _world.ui_external) || lilv_ui_is_a(_impl->ui, _world.ui_externalkx);
843 }
844
845 bool
846 LV2Plugin::is_external_kx() const
847 {
848         if (!_impl->ui) {
849                 return false;
850         }
851         return lilv_ui_is_a(_impl->ui, _world.ui_externalkx);
852 }
853
854 bool
855 LV2Plugin::ui_is_resizable () const
856 {
857         const LilvNode* s   = lilv_ui_get_uri(_impl->ui);
858         LilvNode*       p   = lilv_new_uri(_world.world, LV2_CORE__optionalFeature);
859         LilvNode*       fs  = lilv_new_uri(_world.world, LV2_UI__fixedSize);
860         LilvNode*       nrs = lilv_new_uri(_world.world, LV2_UI__noUserResize);
861
862         LilvNodes* fs_matches = lilv_world_find_nodes(_world.world, s, p, fs);
863         LilvNodes* nrs_matches = lilv_world_find_nodes(_world.world, s, p, nrs);
864
865         lilv_nodes_free(nrs_matches);
866         lilv_nodes_free(fs_matches);
867         lilv_node_free(nrs);
868         lilv_node_free(fs);
869         lilv_node_free(p);
870
871         return !fs_matches && !nrs_matches;
872 }
873
874 #ifdef LV2_EXTENDED
875 bool
876 LV2Plugin::has_inline_display () {
877         return _display_interface ? true : false;
878 }
879
880 Plugin::Display_Image_Surface*
881 LV2Plugin::render_inline_display (uint32_t w, uint32_t h) {
882         if (_display_interface) {
883                 /* Plugin::Display_Image_Surface is identical to
884                  * LV2_Inline_Display_Image_Surface */
885                 return (Plugin::Display_Image_Surface*) _display_interface->render ((void*)_impl->instance->lv2_handle, w, h);
886         }
887         return NULL;
888 }
889 #endif
890
891 string
892 LV2Plugin::unique_id() const
893 {
894         return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
895 }
896
897 const char*
898 LV2Plugin::uri() const
899 {
900         return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
901 }
902
903 const char*
904 LV2Plugin::label() const
905 {
906         return lilv_node_as_string(_impl->name);
907 }
908
909 const char*
910 LV2Plugin::name() const
911 {
912         return lilv_node_as_string(_impl->name);
913 }
914
915 const char*
916 LV2Plugin::maker() const
917 {
918         return _impl->author ? lilv_node_as_string (_impl->author) : "Unknown";
919 }
920
921 uint32_t
922 LV2Plugin::num_ports() const
923 {
924         return lilv_plugin_get_num_ports(_impl->plugin);
925 }
926
927 uint32_t
928 LV2Plugin::parameter_count() const
929 {
930         return lilv_plugin_get_num_ports(_impl->plugin);
931 }
932
933 float
934 LV2Plugin::default_value(uint32_t port)
935 {
936         return _defaults[port];
937 }
938
939 const char*
940 LV2Plugin::port_symbol(uint32_t index) const
941 {
942         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, index);
943         if (!port) {
944                 error << name() << ": Invalid port index " << index << endmsg;
945         }
946
947         const LilvNode* sym = lilv_port_get_symbol(_impl->plugin, port);
948         return lilv_node_as_string(sym);
949 }
950
951 uint32_t
952 LV2Plugin::port_index (const char* symbol) const
953 {
954         const map<string, uint32_t>::const_iterator i = _port_indices.find(symbol);
955         if (i != _port_indices.end()) {
956                 return  i->second;
957         } else {
958                 warning << string_compose(_("LV2: Unknown port %1"), symbol) << endmsg;
959                 return (uint32_t)-1;
960         }
961 }
962
963 void
964 LV2Plugin::set_parameter(uint32_t which, float val)
965 {
966         DEBUG_TRACE(DEBUG::LV2, string_compose(
967                             "%1 set parameter %2 to %3\n", name(), which, val));
968
969         if (which < lilv_plugin_get_num_ports(_impl->plugin)) {
970                 if (get_parameter (which) == val) {
971                         return;
972                 }
973
974                 _shadow_data[which] = val;
975         } else {
976                 warning << string_compose(
977                     _("Illegal parameter number used with plugin \"%1\". "
978                       "This is a bug in either %2 or the LV2 plugin <%3>"),
979                     name(), PROGRAM_NAME, unique_id()) << endmsg;
980         }
981
982         Plugin::set_parameter(which, val);
983 }
984
985 float
986 LV2Plugin::get_parameter(uint32_t which) const
987 {
988         if (parameter_is_input(which)) {
989                 return (float)_shadow_data[which];
990         } else {
991                 return (float)_control_data[which];
992         }
993         return 0.0f;
994 }
995
996 std::string
997 LV2Plugin::get_docs() const
998 {
999         LilvNodes* comments = lilv_plugin_get_value(_impl->plugin, _world.rdfs_comment);
1000         if (comments) {
1001                 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
1002                 lilv_nodes_free(comments);
1003                 return docs;
1004         }
1005
1006         return "";
1007 }
1008
1009 std::string
1010 LV2Plugin::get_parameter_docs(uint32_t which) const
1011 {
1012         LilvNodes* comments = lilv_port_get_value(
1013                 _impl->plugin,
1014                 lilv_plugin_get_port_by_index(_impl->plugin, which),
1015                 _world.rdfs_comment);
1016
1017         if (comments) {
1018                 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
1019                 lilv_nodes_free(comments);
1020                 return docs;
1021         }
1022
1023         return "";
1024 }
1025
1026 uint32_t
1027 LV2Plugin::nth_parameter(uint32_t n, bool& ok) const
1028 {
1029         ok = false;
1030         for (uint32_t c = 0, x = 0; x < lilv_plugin_get_num_ports(_impl->plugin); ++x) {
1031                 if (parameter_is_control(x)) {
1032                         if (c++ == n) {
1033                                 ok = true;
1034                                 return x;
1035                         }
1036                 }
1037         }
1038
1039         return 0;
1040 }
1041
1042 const void*
1043 LV2Plugin::extension_data(const char* uri) const
1044 {
1045         return lilv_instance_get_extension_data(_impl->instance, uri);
1046 }
1047
1048 const void*
1049 LV2Plugin::c_plugin()
1050 {
1051         return _impl->plugin;
1052 }
1053
1054 const void*
1055 LV2Plugin::c_ui()
1056 {
1057         return (const void*)_impl->ui;
1058 }
1059
1060 const void*
1061 LV2Plugin::c_ui_type()
1062 {
1063         return (const void*)_impl->ui_type;
1064 }
1065
1066 /** Directory for all plugin state. */
1067 const std::string
1068 LV2Plugin::plugin_dir() const
1069 {
1070         if (!_plugin_state_dir.empty ()){
1071                 return Glib::build_filename(_plugin_state_dir, _insert_id.to_s());
1072         } else {
1073                 return Glib::build_filename(_session.plugins_dir(), _insert_id.to_s());
1074         }
1075 }
1076
1077 /** Directory for files created by the plugin (except during save). */
1078 const std::string
1079 LV2Plugin::scratch_dir() const
1080 {
1081         return Glib::build_filename(plugin_dir(), "scratch");
1082 }
1083
1084 /** Directory for snapshots of files in the scratch directory. */
1085 const std::string
1086 LV2Plugin::file_dir() const
1087 {
1088         return Glib::build_filename(plugin_dir(), "files");
1089 }
1090
1091 /** Directory to save state snapshot version @c num into. */
1092 const std::string
1093 LV2Plugin::state_dir(unsigned num) const
1094 {
1095         return Glib::build_filename(plugin_dir(), string_compose("state%1", num));
1096 }
1097
1098 /** Implementation of state:makePath for files created at instantiation time.
1099  * Note this is not used for files created at save time (Lilv deals with that).
1100  */
1101 char*
1102 LV2Plugin::lv2_state_make_path(LV2_State_Make_Path_Handle handle,
1103                                const char*                path)
1104 {
1105         LV2Plugin* me = (LV2Plugin*)handle;
1106         if (me->_insert_id == PBD::ID("0")) {
1107                 warning << string_compose(
1108                         "File path \"%1\" requested but LV2 %2 has no insert ID",
1109                         path, me->name()) << endmsg;
1110                 return g_strdup(path);
1111         }
1112
1113         const std::string abs_path = Glib::build_filename(me->scratch_dir(), path);
1114         const std::string dirname  = Glib::path_get_dirname(abs_path);
1115         g_mkdir_with_parents(dirname.c_str(), 0744);
1116
1117         DEBUG_TRACE(DEBUG::LV2, string_compose("new file path %1 => %2\n",
1118                                                path, abs_path));
1119
1120         return g_strndup(abs_path.c_str(), abs_path.length());
1121 }
1122
1123 void
1124 LV2Plugin::add_state(XMLNode* root) const
1125 {
1126         assert(_insert_id != PBD::ID("0"));
1127
1128         XMLNode*    child;
1129         char        buf[32];
1130         LocaleGuard lg ();
1131
1132         for (uint32_t i = 0; i < parameter_count(); ++i) {
1133                 if (parameter_is_input(i) && parameter_is_control(i)) {
1134                         child = new XMLNode("Port");
1135                         child->add_property("symbol", port_symbol(i));
1136                         snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
1137                         child->add_property("value", string(buf));
1138                         root->add_child_nocopy(*child);
1139                 }
1140         }
1141
1142         if (!_plugin_state_dir.empty()) {
1143                 root->add_property("template-dir", _plugin_state_dir);
1144         }
1145
1146         if (_has_state_interface) {
1147                 // Provisionally increment state version and create directory
1148                 const std::string new_dir = state_dir(++_state_version);
1149                 g_mkdir_with_parents(new_dir.c_str(), 0744);
1150
1151                 LilvState* state = lilv_state_new_from_instance(
1152                         _impl->plugin,
1153                         _impl->instance,
1154                         _uri_map.urid_map(),
1155                         scratch_dir().c_str(),
1156                         file_dir().c_str(),
1157                         _session.externals_dir().c_str(),
1158                         new_dir.c_str(),
1159                         NULL,
1160                         const_cast<LV2Plugin*>(this),
1161                         0,
1162                         NULL);
1163
1164                 if (!_plugin_state_dir.empty()
1165                     || !_impl->state
1166                     || !lilv_state_equals(state, _impl->state)) {
1167                         lilv_state_save(_world.world,
1168                                         _uri_map.urid_map(),
1169                                         _uri_map.urid_unmap(),
1170                                         state,
1171                                         NULL,
1172                                         new_dir.c_str(),
1173                                         "state.ttl");
1174
1175                         if (_plugin_state_dir.empty()) {
1176                                 // normal session save
1177                                 lilv_state_free(_impl->state);
1178                                 _impl->state = state;
1179                         } else {
1180                                 // template save (dedicated state-dir)
1181                                 lilv_state_free(state);
1182                         }
1183                 } else {
1184                         // State is identical, decrement version and nuke directory
1185                         lilv_state_free(state);
1186                         PBD::remove_directory(new_dir);
1187                         --_state_version;
1188                 }
1189
1190                 root->add_property("state-dir", string_compose("state%1", _state_version));
1191         }
1192 }
1193
1194 // TODO: Once we can rely on lilv 0.16.0, lilv_world_get can replace this
1195 static LilvNode*
1196 get_value(LilvWorld* world, const LilvNode* subject, const LilvNode* predicate)
1197 {
1198         LilvNodes* vs = lilv_world_find_nodes(world, subject, predicate, NULL);
1199         if (vs) {
1200                 LilvNode* node = lilv_node_duplicate(lilv_nodes_get_first(vs));
1201                 lilv_nodes_free(vs);
1202                 return node;
1203         }
1204         return NULL;
1205 }
1206
1207 void
1208 LV2Plugin::find_presets()
1209 {
1210         LilvNode* lv2_appliesTo = lilv_new_uri(_world.world, LV2_CORE__appliesTo);
1211         LilvNode* pset_Preset   = lilv_new_uri(_world.world, LV2_PRESETS__Preset);
1212         LilvNode* rdfs_label    = lilv_new_uri(_world.world, LILV_NS_RDFS "label");
1213
1214         LilvNodes* presets = lilv_plugin_get_related(_impl->plugin, pset_Preset);
1215         LILV_FOREACH(nodes, i, presets) {
1216                 const LilvNode* preset = lilv_nodes_get(presets, i);
1217                 lilv_world_load_resource(_world.world, preset);
1218                 LilvNode* name = get_value(_world.world, preset, rdfs_label);
1219                 bool userpreset = true; // TODO
1220                 if (name) {
1221                         _presets.insert(std::make_pair(lilv_node_as_string(preset),
1222                                                        Plugin::PresetRecord(
1223                                                                lilv_node_as_string(preset),
1224                                                                lilv_node_as_string(name),
1225                                                                userpreset)));
1226                         lilv_node_free(name);
1227                 } else {
1228                         warning << string_compose(
1229                             _("Plugin \"%1\" preset \"%2\" is missing a label\n"),
1230                             lilv_node_as_string(lilv_plugin_get_uri(_impl->plugin)),
1231                             lilv_node_as_string(preset)) << endmsg;
1232                 }
1233         }
1234         lilv_nodes_free(presets);
1235
1236         lilv_node_free(rdfs_label);
1237         lilv_node_free(pset_Preset);
1238         lilv_node_free(lv2_appliesTo);
1239 }
1240
1241 static void
1242 set_port_value(const char* port_symbol,
1243                void*       user_data,
1244                const void* value,
1245                uint32_t    /*size*/,
1246                uint32_t    type)
1247 {
1248         LV2Plugin* self = (LV2Plugin*)user_data;
1249         if (type != 0 && type != URIMap::instance().urids.atom_Float) {
1250                 return;  // TODO: Support non-float ports
1251         }
1252
1253         const uint32_t port_index = self->port_index(port_symbol);
1254         if (port_index != (uint32_t)-1) {
1255                 self->set_parameter(port_index, *(const float*)value);
1256         }
1257 }
1258
1259 bool
1260 LV2Plugin::load_preset(PresetRecord r)
1261 {
1262         LilvWorld* world = _world.world;
1263         LilvNode*  pset  = lilv_new_uri(world, r.uri.c_str());
1264         LilvState* state = lilv_state_new_from_world(world, _uri_map.urid_map(), pset);
1265
1266         if (state) {
1267                 lilv_state_restore(state, _impl->instance, set_port_value, this, 0, NULL);
1268                 lilv_state_free(state);
1269                 Plugin::load_preset(r);
1270         }
1271
1272         lilv_node_free(pset);
1273         return state;
1274 }
1275
1276 const void*
1277 ARDOUR::lv2plugin_get_port_value(const char* port_symbol,
1278                                  void*       user_data,
1279                                  uint32_t*   size,
1280                                  uint32_t*   type)
1281 {
1282         LV2Plugin *plugin = (LV2Plugin *) user_data;
1283
1284         uint32_t index = plugin->port_index(port_symbol);
1285         if (index != (uint32_t) -1) {
1286                 if (plugin->parameter_is_input(index) && plugin->parameter_is_control(index)) {
1287                         float *value;
1288                         *size = sizeof(float);
1289                         *type = plugin->_uri_map.uri_to_id(LV2_ATOM__Float);
1290                         value = &plugin->_shadow_data[index];
1291
1292                         return value;
1293                 }
1294         }
1295
1296         *size = *type = 0;
1297         return NULL;
1298 }
1299
1300
1301 std::string
1302 LV2Plugin::do_save_preset(string name)
1303 {
1304         LilvNode*    plug_name = lilv_plugin_get_name(_impl->plugin);
1305         const string prefix    = legalize_for_uri(lilv_node_as_string(plug_name));
1306         const string base_name = legalize_for_uri(name);
1307         const string file_name = base_name + ".ttl";
1308         const string bundle    = Glib::build_filename(
1309                 Glib::get_home_dir(),
1310                 Glib::build_filename(".lv2", prefix + "_" + base_name + ".lv2"));
1311
1312 #ifdef HAVE_LILV_0_21_3
1313         /* delete reference to old preset (if any) */
1314         const PresetRecord* r = preset_by_label(name);
1315         if (r) {
1316                 LilvNode*  pset  = lilv_new_uri (_world.world, r->uri.c_str());
1317                 if (pset) {
1318                         lilv_world_unload_resource (_world.world, pset);
1319                         lilv_node_free(pset);
1320                 }
1321         }
1322 #endif
1323
1324         LilvState* state = lilv_state_new_from_instance(
1325                 _impl->plugin,
1326                 _impl->instance,
1327                 _uri_map.urid_map(),
1328                 scratch_dir().c_str(),                   // file_dir
1329                 bundle.c_str(),                          // copy_dir
1330                 bundle.c_str(),                          // link_dir
1331                 bundle.c_str(),                          // save_dir
1332                 lv2plugin_get_port_value,                // get_value
1333                 (void*)this,                             // user_data
1334                 LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE,  // flags
1335                 _features                                // features
1336         );
1337
1338         lilv_state_set_label(state, name.c_str());
1339         lilv_state_save(
1340                 _world.world,           // world
1341                 _uri_map.urid_map(),    // map
1342                 _uri_map.urid_unmap(),  // unmap
1343                 state,                  // state
1344                 NULL,                   // uri (NULL = use file URI)
1345                 bundle.c_str(),         // dir
1346                 file_name.c_str()       // filename
1347         );
1348
1349         lilv_state_free(state);
1350
1351         std::string uri = Glib::filename_to_uri(Glib::build_filename(bundle, file_name));
1352         LilvNode *node_bundle = lilv_new_uri(_world.world, Glib::filename_to_uri(Glib::build_filename(bundle, "/")).c_str());
1353         LilvNode *node_preset = lilv_new_uri(_world.world, uri.c_str());
1354 #ifdef HAVE_LILV_0_21_3
1355         lilv_world_unload_resource(_world.world, node_preset);
1356         lilv_world_unload_bundle(_world.world, node_bundle);
1357 #endif
1358         lilv_world_load_bundle(_world.world, node_bundle);
1359         lilv_world_load_resource(_world.world, node_preset);
1360         lilv_node_free(node_bundle);
1361         lilv_node_free(node_preset);
1362         lilv_node_free(plug_name);
1363         return uri;
1364 }
1365
1366 void
1367 LV2Plugin::do_remove_preset(string name)
1368 {
1369 #ifdef HAVE_LILV_0_21_3
1370         /* Look up preset record by label (FIXME: ick, label as ID) */
1371         const PresetRecord* r = preset_by_label(name);
1372         if (!r) {
1373                 return;
1374         }
1375
1376         /* Load a LilvState for the preset. */
1377         LilvWorld* world = _world.world;
1378         LilvNode*  pset  = lilv_new_uri(world, r->uri.c_str());
1379         LilvState* state = lilv_state_new_from_world(world, _uri_map.urid_map(), pset);
1380         if (!state) {
1381                 lilv_node_free(pset);
1382                 return;
1383         }
1384
1385         /* Unload preset from world. */
1386         lilv_world_unload_resource(world, pset);
1387
1388         /* Delete it from the file system.  This will remove the preset file and the entry
1389            from the manifest.  If this results in an empty manifest (i.e. the
1390            preset is the only thing in the bundle), then the bundle is removed. */
1391         lilv_state_delete(world, state);
1392
1393         lilv_state_free(state);
1394         lilv_node_free(pset);
1395 #endif
1396         /* Without lilv_state_delete(), we could delete the preset file, but this
1397            would leave a broken bundle/manifest around, so the preset would still
1398            be visible, but broken.  Naively deleting a bundle is too dangerous, so
1399            we simply do not support preset deletion with older Lilv */
1400 }
1401
1402 bool
1403 LV2Plugin::has_editor() const
1404 {
1405         return _impl->ui != NULL;
1406 }
1407
1408 bool
1409 LV2Plugin::has_message_output() const
1410 {
1411         for (uint32_t i = 0; i < num_ports(); ++i) {
1412                 if ((_port_flags[i] & PORT_SEQUENCE) &&
1413                     (_port_flags[i] & PORT_OUTPUT)) {
1414                         return true;
1415                 }
1416         }
1417         return false;
1418 }
1419
1420 bool
1421 LV2Plugin::write_to(RingBuffer<uint8_t>* dest,
1422                     uint32_t             index,
1423                     uint32_t             protocol,
1424                     uint32_t             size,
1425                     const uint8_t*       body)
1426 {
1427         const uint32_t  buf_size = sizeof(UIMessage) + size;
1428         vector<uint8_t> buf(buf_size);
1429
1430         UIMessage* msg = (UIMessage*)&buf[0];
1431         msg->index    = index;
1432         msg->protocol = protocol;
1433         msg->size     = size;
1434         memcpy(msg + 1, body, size);
1435
1436         return (dest->write(&buf[0], buf_size) == buf_size);
1437 }
1438
1439 bool
1440 LV2Plugin::write_from_ui(uint32_t       index,
1441                          uint32_t       protocol,
1442                          uint32_t       size,
1443                          const uint8_t* body)
1444 {
1445         if (!_from_ui) {
1446                 size_t rbs = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
1447                 /* buffer data communication from plugin UI to plugin instance.
1448                  * this buffer needs to potentially hold
1449                  *   (port's minimumSize) * (audio-periods) / (UI-periods)
1450                  * bytes.
1451                  *
1452                  *  e.g 48kSPS / 128fpp -> audio-periods = 375 Hz
1453                  *  ui-periods = 25 Hz (SuperRapidScreenUpdate)
1454                  *  default minimumSize = 32K (see LV2Plugin::allocate_atom_event_buffers()
1455                  *
1456                  * it is NOT safe to overflow (msg.size will be misinterpreted)
1457                  */
1458                 uint32_t bufsiz = 32768;
1459                 if (_atom_ev_buffers && _atom_ev_buffers[0]) {
1460                         bufsiz =  lv2_evbuf_get_capacity(_atom_ev_buffers[0]);
1461                 }
1462                 rbs = max((size_t) bufsiz * 8, rbs);
1463                 _from_ui = new RingBuffer<uint8_t>(rbs);
1464         }
1465
1466         if (!write_to(_from_ui, index, protocol, size, body)) {
1467                 error << "Error writing from UI to plugin" << endmsg;
1468                 return false;
1469         }
1470         return true;
1471 }
1472
1473 bool
1474 LV2Plugin::write_to_ui(uint32_t       index,
1475                        uint32_t       protocol,
1476                        uint32_t       size,
1477                        const uint8_t* body)
1478 {
1479         if (!write_to(_to_ui, index, protocol, size, body)) {
1480                 error << "Error writing from plugin to UI" << endmsg;
1481                 return false;
1482         }
1483         return true;
1484 }
1485
1486 static void
1487 forge_variant(LV2_Atom_Forge* forge, const Variant& value)
1488 {
1489         switch (value.type()) {
1490         case Variant::NOTHING:
1491                 break;
1492         case Variant::BEATS:
1493                 // No atom type for this, just forge a double
1494                 lv2_atom_forge_double(forge, value.get_beats().to_double());
1495                 break;
1496         case Variant::BOOL:
1497                 lv2_atom_forge_bool(forge, value.get_bool());
1498                 break;
1499         case Variant::DOUBLE:
1500                 lv2_atom_forge_double(forge, value.get_double());
1501                 break;
1502         case Variant::FLOAT:
1503                 lv2_atom_forge_float(forge, value.get_float());
1504                 break;
1505         case Variant::INT:
1506                 lv2_atom_forge_int(forge, value.get_int());
1507                 break;
1508         case Variant::LONG:
1509                 lv2_atom_forge_long(forge, value.get_long());
1510                 break;
1511         case Variant::PATH:
1512                 lv2_atom_forge_path(
1513                         forge, value.get_path().c_str(), value.get_path().size());
1514                 break;
1515         case Variant::STRING:
1516                 lv2_atom_forge_string(
1517                         forge, value.get_string().c_str(), value.get_string().size());
1518                 break;
1519         case Variant::URI:
1520                 lv2_atom_forge_uri(
1521                         forge, value.get_uri().c_str(), value.get_uri().size());
1522                 break;
1523         }
1524 }
1525
1526 /** Get a variant type from a URI, return false iff no match found. */
1527 static bool
1528 uri_to_variant_type(const std::string& uri, Variant::Type& type)
1529 {
1530         if (uri == LV2_ATOM__Bool) {
1531                 type = Variant::BOOL;
1532         } else if (uri == LV2_ATOM__Double) {
1533                 type = Variant::DOUBLE;
1534         } else if (uri == LV2_ATOM__Float) {
1535                 type = Variant::FLOAT;
1536         } else if (uri == LV2_ATOM__Int) {
1537                 type = Variant::INT;
1538         } else if (uri == LV2_ATOM__Long) {
1539                 type = Variant::LONG;
1540         } else if (uri == LV2_ATOM__Path) {
1541                 type = Variant::PATH;
1542         } else if (uri == LV2_ATOM__String) {
1543                 type = Variant::STRING;
1544         } else if (uri == LV2_ATOM__URI) {
1545                 type = Variant::URI;
1546         } else {
1547                 return false;
1548         }
1549         return true;
1550 }
1551
1552 void
1553 LV2Plugin::set_property(uint32_t key, const Variant& value)
1554 {
1555         if (_patch_port_in_index == (uint32_t)-1) {
1556                 error << "LV2: set_property called with unset patch_port_in_index" << endmsg;
1557                 return;
1558         } else if (value.type() == Variant::NOTHING) {
1559                 error << "LV2: set_property called with void value" << endmsg;
1560                 return;
1561         }
1562
1563         // Set up forge to write to temporary buffer on the stack
1564         LV2_Atom_Forge*      forge = &_impl->ui_forge;
1565         LV2_Atom_Forge_Frame frame;
1566         uint8_t              buf[PATH_MAX];  // Ought to be enough for anyone...
1567
1568         lv2_atom_forge_set_buffer(forge, buf, sizeof(buf));
1569
1570         // Serialize patch:Set message to set property
1571 #ifdef HAVE_LV2_1_10_0
1572         lv2_atom_forge_object(forge, &frame, 1, _uri_map.urids.patch_Set);
1573         lv2_atom_forge_key(forge, _uri_map.urids.patch_property);
1574         lv2_atom_forge_urid(forge, key);
1575         lv2_atom_forge_key(forge, _uri_map.urids.patch_value);
1576 #else
1577         lv2_atom_forge_blank(forge, &frame, 1, _uri_map.urids.patch_Set);
1578         lv2_atom_forge_property_head(forge, _uri_map.urids.patch_property, 0);
1579         lv2_atom_forge_urid(forge, key);
1580         lv2_atom_forge_property_head(forge, _uri_map.urids.patch_value, 0);
1581 #endif
1582
1583         forge_variant(forge, value);
1584
1585         // Write message to UI=>Plugin ring
1586         const LV2_Atom* const atom = (const LV2_Atom*)buf;
1587         write_from_ui(_patch_port_in_index,
1588                       _uri_map.urids.atom_eventTransfer,
1589                       lv2_atom_total_size(atom),
1590                       (const uint8_t*)atom);
1591 }
1592
1593 const ParameterDescriptor&
1594 LV2Plugin::get_property_descriptor(uint32_t id) const
1595 {
1596         PropertyDescriptors::const_iterator p = _property_descriptors.find(id);
1597         if (p != _property_descriptors.end()) {
1598                 return p->second;
1599         }
1600         return Plugin::get_property_descriptor(id);
1601 }
1602
1603 static void
1604 load_parameter_descriptor_units(LilvWorld* lworld, ParameterDescriptor& desc, const LilvNodes* units)
1605 {
1606         if (lilv_nodes_contains(units, _world.units_midiNote)) {
1607                 desc.unit = ParameterDescriptor::MIDI_NOTE;
1608         } else if (lilv_nodes_contains(units, _world.units_db)) {
1609                 desc.unit = ParameterDescriptor::DB;
1610         } else if (lilv_nodes_contains(units, _world.units_hz)) {
1611                 desc.unit = ParameterDescriptor::HZ;
1612         }
1613         if (lilv_nodes_size(units) > 0) {
1614                 const LilvNode* unit = lilv_nodes_get_first(units);
1615                 LilvNode* render = get_value(lworld, unit, _world.units_render);
1616                 if (render) {
1617                         desc.print_fmt = lilv_node_as_string(render);
1618                         lilv_node_free(render);
1619                 }
1620         }
1621 }
1622
1623 static void
1624 load_parameter_descriptor(LV2World&            world,
1625                           ParameterDescriptor& desc,
1626                           Variant::Type        datatype,
1627                           const LilvNode*      subject)
1628 {
1629         LilvWorld* lworld  = _world.world;
1630         LilvNode*  label   = get_value(lworld, subject, _world.rdfs_label);
1631         LilvNode*  def     = get_value(lworld, subject, _world.lv2_default);
1632         LilvNode*  minimum = get_value(lworld, subject, _world.lv2_minimum);
1633         LilvNode*  maximum = get_value(lworld, subject, _world.lv2_maximum);
1634         LilvNodes* units   = lilv_world_find_nodes(lworld, subject, _world.units_unit, NULL);
1635         if (label) {
1636                 desc.label = lilv_node_as_string(label);
1637         }
1638         if (def && lilv_node_is_float(def)) {
1639                 desc.normal = lilv_node_as_float(def);
1640         }
1641         if (minimum && lilv_node_is_float(minimum)) {
1642                 desc.lower = lilv_node_as_float(minimum);
1643         }
1644         if (maximum && lilv_node_is_float(maximum)) {
1645                 desc.upper = lilv_node_as_float(maximum);
1646         }
1647         load_parameter_descriptor_units(lworld, desc, units);
1648         desc.datatype      = datatype;
1649         desc.toggled      |= datatype == Variant::BOOL;
1650         desc.integer_step |= datatype == Variant::INT || datatype == Variant::LONG;
1651         desc.update_steps();
1652
1653         lilv_nodes_free(units);
1654         lilv_node_free(label);
1655         lilv_node_free(def);
1656         lilv_node_free(minimum);
1657         lilv_node_free(maximum);
1658 }
1659
1660 void
1661 LV2Plugin::load_supported_properties(PropertyDescriptors& descs)
1662 {
1663         LilvWorld*       lworld     = _world.world;
1664         const LilvNode*  subject    = lilv_plugin_get_uri(_impl->plugin);
1665         LilvNodes*       properties = lilv_world_find_nodes(
1666                 lworld, subject, _world.patch_writable, NULL);
1667         LILV_FOREACH(nodes, p, properties) {
1668                 // Get label and range
1669                 const LilvNode* prop  = lilv_nodes_get(properties, p);
1670                 LilvNode*       range = get_value(lworld, prop, _world.rdfs_range);
1671                 if (!range) {
1672                         warning << string_compose(_("LV2: property <%1> has no range datatype, ignoring"),
1673                                                   lilv_node_as_uri(prop)) << endmsg;
1674                         continue;
1675                 }
1676
1677                 // Convert range to variant type (TODO: support for multiple range types)
1678                 Variant::Type datatype;
1679                 if (!uri_to_variant_type(lilv_node_as_uri(range), datatype)) {
1680                         error << string_compose(_("LV2: property <%1> has unsupported datatype <%1>"),
1681                                                 lilv_node_as_uri(prop), lilv_node_as_uri(range)) << endmsg;
1682                         continue;
1683                 }
1684
1685                 // Add description to result
1686                 ParameterDescriptor desc;
1687                 desc.key      = _uri_map.uri_to_id(lilv_node_as_uri(prop));
1688                 desc.datatype = datatype;
1689                 load_parameter_descriptor(_world, desc, datatype, prop);
1690                 descs.insert(std::make_pair(desc.key, desc));
1691
1692                 lilv_node_free(range);
1693         }
1694         lilv_nodes_free(properties);
1695 }
1696
1697 void
1698 LV2Plugin::announce_property_values()
1699 {
1700         if (_patch_port_in_index == (uint32_t)-1) {
1701                 return;
1702         }
1703
1704         // Set up forge to write to temporary buffer on the stack
1705         LV2_Atom_Forge*      forge = &_impl->ui_forge;
1706         LV2_Atom_Forge_Frame frame;
1707         uint8_t              buf[PATH_MAX];  // Ought to be enough for anyone...
1708
1709         lv2_atom_forge_set_buffer(forge, buf, sizeof(buf));
1710
1711         // Serialize patch:Get message with no subject (implicitly plugin instance)
1712 #ifdef HAVE_LV2_1_10_0
1713         lv2_atom_forge_object(forge, &frame, 1, _uri_map.urids.patch_Get);
1714 #else
1715         lv2_atom_forge_blank(forge, &frame, 1, _uri_map.urids.patch_Get);
1716 #endif
1717
1718         // Write message to UI=>Plugin ring
1719         const LV2_Atom* const atom = (const LV2_Atom*)buf;
1720         write_from_ui(_patch_port_in_index,
1721                       _uri_map.urids.atom_eventTransfer,
1722                       lv2_atom_total_size(atom),
1723                       (const uint8_t*)atom);
1724 }
1725
1726 void
1727 LV2Plugin::enable_ui_emission()
1728 {
1729         if (!_to_ui) {
1730                 /* see note in LV2Plugin::write_from_ui() */
1731                 uint32_t bufsiz = 32768;
1732                 if (_atom_ev_buffers && _atom_ev_buffers[0]) {
1733                         bufsiz =  lv2_evbuf_get_capacity(_atom_ev_buffers[0]);
1734                 }
1735                 size_t rbs = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
1736                 rbs = max((size_t) bufsiz * 8, rbs);
1737                 _to_ui = new RingBuffer<uint8_t>(rbs);
1738         }
1739 }
1740
1741 void
1742 LV2Plugin::emit_to_ui(void* controller, UIMessageSink sink)
1743 {
1744         if (!_to_ui) {
1745                 return;
1746         }
1747
1748         uint32_t read_space = _to_ui->read_space();
1749         while (read_space > sizeof(UIMessage)) {
1750                 UIMessage msg;
1751                 if (_to_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1752                         error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1753                         break;
1754                 }
1755                 vector<uint8_t> body(msg.size);
1756                 if (_to_ui->read(&body[0], msg.size) != msg.size) {
1757                         error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1758                         break;
1759                 }
1760
1761                 sink(controller, msg.index, msg.size, msg.protocol, &body[0]);
1762
1763                 read_space -= sizeof(msg) + msg.size;
1764         }
1765 }
1766
1767 int
1768 LV2Plugin::work(uint32_t size, const void* data)
1769 {
1770         return _impl->work_iface->work(
1771                 _impl->instance->lv2_handle, work_respond, this, size, data);
1772 }
1773
1774 int
1775 LV2Plugin::work_response(uint32_t size, const void* data)
1776 {
1777         return _impl->work_iface->work_response(
1778                 _impl->instance->lv2_handle, size, data);
1779 }
1780
1781 void
1782 LV2Plugin::set_insert_id(PBD::ID id)
1783 {
1784         if (_insert_id == "0") {
1785                 _insert_id = id;
1786         } else if (_insert_id != id) {
1787                 lilv_state_free(_impl->state);
1788                 _impl->state = NULL;
1789                 _insert_id   = id;
1790         }
1791 }
1792
1793 void
1794 LV2Plugin::set_state_dir (const std::string& d)
1795 {
1796         _plugin_state_dir = d;
1797 }
1798
1799 int
1800 LV2Plugin::set_state(const XMLNode& node, int version)
1801 {
1802         XMLNodeList          nodes;
1803         XMLProperty const * prop;
1804         XMLNodeConstIterator iter;
1805         XMLNode*             child;
1806         const char*          sym;
1807         const char*          value;
1808         uint32_t             port_id;
1809         LocaleGuard          lg ();
1810
1811         if (node.name() != state_node_name()) {
1812                 error << _("Bad node sent to LV2Plugin::set_state") << endmsg;
1813                 return -1;
1814         }
1815
1816 #ifndef NO_PLUGIN_STATE
1817
1818         if (version < 3000) {
1819                 nodes = node.children("port");
1820         } else {
1821                 nodes = node.children("Port");
1822         }
1823
1824         for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
1825
1826                 child = *iter;
1827
1828                 if ((prop = child->property("symbol")) != 0) {
1829                         sym = prop->value().c_str();
1830                 } else {
1831                         warning << _("LV2: port has no symbol, ignored") << endmsg;
1832                         continue;
1833                 }
1834
1835                 map<string, uint32_t>::iterator i = _port_indices.find(sym);
1836
1837                 if (i != _port_indices.end()) {
1838                         port_id = i->second;
1839                 } else {
1840                         warning << _("LV2: port has unknown index, ignored") << endmsg;
1841                         continue;
1842                 }
1843
1844                 if ((prop = child->property("value")) != 0) {
1845                         value = prop->value().c_str();
1846                 } else {
1847                         warning << _("LV2: port has no value, ignored") << endmsg;
1848                         continue;
1849                 }
1850
1851                 set_parameter(port_id, atof(value));
1852         }
1853
1854         if ((prop = node.property("template-dir")) != 0) {
1855                 set_state_dir (prop->value ());
1856         }
1857
1858         _state_version = 0;
1859         if ((prop = node.property("state-dir")) != 0) {
1860                 if (sscanf(prop->value().c_str(), "state%u", &_state_version) != 1) {
1861                         error << string_compose(
1862                                 "LV2: failed to parse state version from \"%1\"",
1863                                 prop->value()) << endmsg;
1864                 }
1865
1866                 std::string state_file = Glib::build_filename(
1867                         plugin_dir(),
1868                         Glib::build_filename(prop->value(), "state.ttl"));
1869
1870                 LilvState* state = lilv_state_new_from_file(
1871                         _world.world, _uri_map.urid_map(), NULL, state_file.c_str());
1872
1873                 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
1874                 lilv_state_free(_impl->state);
1875                 _impl->state = state;
1876         }
1877
1878         if (!_plugin_state_dir.empty ()) {
1879                 // force save with session, next time (increment counter)
1880                 lilv_state_free (_impl->state);
1881                 _impl->state = NULL;
1882                 set_state_dir ("");
1883         }
1884
1885         latency_compute_run();
1886 #endif
1887
1888         return Plugin::set_state(node, version);
1889 }
1890
1891 int
1892 LV2Plugin::get_parameter_descriptor(uint32_t which, ParameterDescriptor& desc) const
1893 {
1894         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, which);
1895         if (!port) {
1896                 error << string_compose("LV2: get descriptor of non-existent port %1", which)
1897                       << endmsg;
1898                 return 1;
1899         }
1900
1901         LilvNodes* portunits;
1902         LilvNode *def, *min, *max;
1903         lilv_port_get_range(_impl->plugin, port, &def, &min, &max);
1904         portunits = lilv_port_get_value(_impl->plugin, port, _world.units_unit);
1905
1906         // TODO: Once we can rely on lilv 0.18.0 being present,
1907         // load_parameter_descriptor() can be used for ports as well
1908         desc.integer_step = lilv_port_has_property(_impl->plugin, port, _world.lv2_integer);
1909         desc.toggled      = lilv_port_has_property(_impl->plugin, port, _world.lv2_toggled);
1910         desc.logarithmic  = lilv_port_has_property(_impl->plugin, port, _world.ext_logarithmic);
1911         desc.sr_dependent = lilv_port_has_property(_impl->plugin, port, _world.lv2_sampleRate);
1912         desc.label        = lilv_node_as_string(lilv_port_get_name(_impl->plugin, port));
1913         desc.normal       = def ? lilv_node_as_float(def) : 0.0f;
1914         desc.lower        = min ? lilv_node_as_float(min) : 0.0f;
1915         desc.upper        = max ? lilv_node_as_float(max) : 1.0f;
1916         load_parameter_descriptor_units(_world.world, desc, portunits);
1917
1918         if (desc.sr_dependent) {
1919                 desc.lower *= _session.frame_rate ();
1920                 desc.upper *= _session.frame_rate ();
1921         }
1922
1923         desc.min_unbound  = false; // TODO: LV2 extension required
1924         desc.max_unbound  = false; // TODO: LV2 extension required
1925
1926         desc.enumeration = lilv_port_has_property(_impl->plugin, port, _world.lv2_enumeration);
1927         desc.scale_points = get_scale_points(which);
1928
1929         desc.update_steps();
1930
1931         lilv_node_free(def);
1932         lilv_node_free(min);
1933         lilv_node_free(max);
1934         lilv_nodes_free(portunits);
1935
1936         return 0;
1937 }
1938
1939 Plugin::IOPortDescription
1940 LV2Plugin::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
1941 {
1942         PortFlags match = 0;
1943         switch (dt) {
1944                 case DataType::AUDIO:
1945                         match = PORT_AUDIO;
1946                         break;
1947                 case DataType::MIDI:
1948                         match = PORT_SEQUENCE | PORT_MIDI; // ignore old PORT_EVENT
1949                         break;
1950                 default:
1951                         return Plugin::IOPortDescription ("?");
1952                         break;
1953         }
1954         if (input) {
1955                 match |= PORT_INPUT;
1956         } else {
1957                 match |= PORT_OUTPUT;
1958         }
1959
1960         uint32_t p = 0;
1961         uint32_t idx = UINT32_MAX;
1962
1963         uint32_t const num_ports = parameter_count();
1964         for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
1965                 PortFlags flags = _port_flags[port_index];
1966                 if ((flags & match) == match) {
1967                         if (p == id) {
1968                                 idx = port_index;
1969                         }
1970                         ++p;
1971                 }
1972         }
1973         if (idx == UINT32_MAX) {
1974                 return Plugin::IOPortDescription ("?");
1975         }
1976
1977         LilvNode* name = lilv_port_get_name(_impl->plugin,
1978                         lilv_plugin_get_port_by_index(_impl->plugin, idx));
1979         Plugin::IOPortDescription iod (lilv_node_as_string (name));
1980         lilv_node_free(name);
1981
1982         if (lilv_port_has_property(_impl->plugin,
1983                                 lilv_plugin_get_port_by_index(_impl->plugin, idx), _world.lv2_isSideChain)) {
1984                 iod.is_sidechain = true;
1985         }
1986         return iod;
1987 }
1988
1989 string
1990 LV2Plugin::describe_parameter(Evoral::Parameter which)
1991 {
1992         if (( which.type() == PluginAutomation) && ( which.id() < parameter_count()) ) {
1993
1994                 if (lilv_port_has_property(_impl->plugin,
1995                                         lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.ext_notOnGUI)) {
1996                         return X_("hidden");
1997                 }
1998
1999                 if (lilv_port_has_property(_impl->plugin,
2000                                         lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_freewheeling)) {
2001                         return X_("hidden");
2002                 }
2003
2004                 if (lilv_port_has_property(_impl->plugin,
2005                                         lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_reportsLatency)) {
2006                         return X_("latency");
2007                 }
2008
2009                 LilvNode* name = lilv_port_get_name(_impl->plugin,
2010                                                     lilv_plugin_get_port_by_index(_impl->plugin, which.id()));
2011                 string ret(lilv_node_as_string(name));
2012                 lilv_node_free(name);
2013                 return ret;
2014         } else {
2015                 return "??";
2016         }
2017 }
2018
2019 framecnt_t
2020 LV2Plugin::max_latency () const
2021 {
2022         return _max_latency;
2023 }
2024
2025 framecnt_t
2026 LV2Plugin::signal_latency() const
2027 {
2028         if (_latency_control_port) {
2029                 return (framecnt_t)floor(*_latency_control_port);
2030         } else {
2031                 return 0;
2032         }
2033 }
2034
2035 set<Evoral::Parameter>
2036 LV2Plugin::automatable() const
2037 {
2038         set<Evoral::Parameter> ret;
2039
2040         for (uint32_t i = 0; i < parameter_count(); ++i) {
2041                 if (parameter_is_input(i) && parameter_is_control(i)) {
2042                         ret.insert(ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
2043                 }
2044         }
2045
2046         for (PropertyDescriptors::const_iterator p = _property_descriptors.begin();
2047              p != _property_descriptors.end();
2048              ++p) {
2049                 ret.insert(ret.end(), Evoral::Parameter(PluginPropertyAutomation, 0, p->first));
2050         }
2051         return ret;
2052 }
2053
2054 void
2055 LV2Plugin::set_automation_control (uint32_t i, boost::shared_ptr<AutomationControl> c)
2056 {
2057         if ((_port_flags[i] & PORT_CTRLED)) {
2058                 _ctrl_map [i] = AutomationCtrlPtr (new AutomationCtrl(c));
2059         }
2060 }
2061
2062 LV2Plugin::AutomationCtrlPtr
2063 LV2Plugin::get_automation_control (uint32_t i)
2064 {
2065         if (_ctrl_map.find (i) == _ctrl_map.end()) {
2066                 return AutomationCtrlPtr ();
2067         }
2068         return _ctrl_map[i];
2069 }
2070
2071 void
2072 LV2Plugin::activate()
2073 {
2074         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 activate\n", name()));
2075
2076         if (!_was_activated) {
2077                 lilv_instance_activate(_impl->instance);
2078                 _was_activated = true;
2079         }
2080 }
2081
2082 void
2083 LV2Plugin::deactivate()
2084 {
2085         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 deactivate\n", name()));
2086
2087         if (_was_activated) {
2088                 lilv_instance_deactivate(_impl->instance);
2089                 _was_activated = false;
2090         }
2091 }
2092
2093 void
2094 LV2Plugin::cleanup()
2095 {
2096         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 cleanup\n", name()));
2097
2098         deactivate();
2099         lilv_instance_free(_impl->instance);
2100         _impl->instance = NULL;
2101 }
2102
2103 void
2104 LV2Plugin::allocate_atom_event_buffers()
2105 {
2106         /* reserve local scratch buffers for ATOM event-queues */
2107         const LilvPlugin* p = _impl->plugin;
2108
2109         /* count non-MIDI atom event-ports
2110          * TODO: nicely ask drobilla to make a lilv_ call for that
2111          */
2112         int count_atom_out = 0;
2113         int count_atom_in = 0;
2114         int minimumSize = 32768; // TODO use a per-port minimum-size
2115         for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
2116                 const LilvPort* port  = lilv_plugin_get_port_by_index(p, i);
2117                 if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
2118                         LilvNodes* buffer_types = lilv_port_get_value(
2119                                 p, port, _world.atom_bufferType);
2120                         LilvNodes* atom_supports = lilv_port_get_value(
2121                                 p, port, _world.atom_supports);
2122
2123                         if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)) {
2124                                 if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
2125                                         count_atom_in++;
2126                                 }
2127                                 if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
2128                                         count_atom_out++;
2129                                 }
2130                                 LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
2131                                 LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
2132                                 if (min_size && lilv_node_is_int(min_size)) {
2133                                         minimumSize = std::max(minimumSize, lilv_node_as_int(min_size));
2134                                 }
2135                                 lilv_nodes_free(min_size_v);
2136                         }
2137                         lilv_nodes_free(buffer_types);
2138                         lilv_nodes_free(atom_supports);
2139                 }
2140         }
2141
2142         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 need buffers for %2 atom-in and %3 atom-out event-ports\n",
2143                                 name(), count_atom_in, count_atom_out));
2144
2145         const int total_atom_buffers = (count_atom_in + count_atom_out);
2146         if (_atom_ev_buffers || total_atom_buffers == 0) {
2147                 return;
2148         }
2149
2150         DEBUG_TRACE(DEBUG::LV2, string_compose("allocate %1 atom_ev_buffers of %2 bytes\n", total_atom_buffers, minimumSize));
2151         _atom_ev_buffers = (LV2_Evbuf**) malloc((total_atom_buffers + 1) * sizeof(LV2_Evbuf*));
2152         for (int i = 0; i < total_atom_buffers; ++i ) {
2153                 _atom_ev_buffers[i] = lv2_evbuf_new(minimumSize, LV2_EVBUF_ATOM,
2154                                 _uri_map.urids.atom_Chunk, _uri_map.urids.atom_Sequence);
2155         }
2156         _atom_ev_buffers[total_atom_buffers] = 0;
2157         return;
2158 }
2159
2160 /** Write an ardour position/time/tempo/meter as an LV2 event.
2161  * @return true on success.
2162  */
2163 static bool
2164 write_position(LV2_Atom_Forge*     forge,
2165                LV2_Evbuf*          buf,
2166                const TempoMetric&  t,
2167                Timecode::BBT_Time& bbt,
2168                double              speed,
2169                framepos_t          position,
2170                framecnt_t          offset)
2171 {
2172         const URIMap::URIDs& urids = URIMap::instance().urids;
2173
2174         uint8_t pos_buf[256];
2175         lv2_atom_forge_set_buffer(forge, pos_buf, sizeof(pos_buf));
2176         LV2_Atom_Forge_Frame frame;
2177 #ifdef HAVE_LV2_1_10_0
2178         lv2_atom_forge_object(forge, &frame, 1, urids.time_Position);
2179         lv2_atom_forge_key(forge, urids.time_frame);
2180         lv2_atom_forge_long(forge, position);
2181         lv2_atom_forge_key(forge, urids.time_speed);
2182         lv2_atom_forge_float(forge, speed);
2183         lv2_atom_forge_key(forge, urids.time_barBeat);
2184         lv2_atom_forge_float(forge, bbt.beats - 1 +
2185                              (bbt.ticks / Timecode::BBT_Time::ticks_per_beat));
2186         lv2_atom_forge_key(forge, urids.time_bar);
2187         lv2_atom_forge_long(forge, bbt.bars - 1);
2188         lv2_atom_forge_key(forge, urids.time_beatUnit);
2189         lv2_atom_forge_int(forge, t.meter().note_divisor());
2190         lv2_atom_forge_key(forge, urids.time_beatsPerBar);
2191         lv2_atom_forge_float(forge, t.meter().divisions_per_bar());
2192         lv2_atom_forge_key(forge, urids.time_beatsPerMinute);
2193         lv2_atom_forge_float(forge, t.tempo().beats_per_minute());
2194 #else
2195         lv2_atom_forge_blank(forge, &frame, 1, urids.time_Position);
2196         lv2_atom_forge_property_head(forge, urids.time_frame, 0);
2197         lv2_atom_forge_long(forge, position);
2198         lv2_atom_forge_property_head(forge, urids.time_speed, 0);
2199         lv2_atom_forge_float(forge, speed);
2200         lv2_atom_forge_property_head(forge, urids.time_barBeat, 0);
2201         lv2_atom_forge_float(forge, bbt.beats - 1 +
2202                              (bbt.ticks / Timecode::BBT_Time::ticks_per_beat));
2203         lv2_atom_forge_property_head(forge, urids.time_bar, 0);
2204         lv2_atom_forge_long(forge, bbt.bars - 1);
2205         lv2_atom_forge_property_head(forge, urids.time_beatUnit, 0);
2206         lv2_atom_forge_int(forge, t.meter().note_divisor());
2207         lv2_atom_forge_property_head(forge, urids.time_beatsPerBar, 0);
2208         lv2_atom_forge_float(forge, t.meter().divisions_per_bar());
2209         lv2_atom_forge_property_head(forge, urids.time_beatsPerMinute, 0);
2210         lv2_atom_forge_float(forge, t.tempo().beats_per_minute());
2211 #endif
2212
2213         LV2_Evbuf_Iterator    end  = lv2_evbuf_end(buf);
2214         const LV2_Atom* const atom = (const LV2_Atom*)pos_buf;
2215         return lv2_evbuf_write(&end, offset, 0, atom->type, atom->size,
2216                                (const uint8_t*)(atom + 1));
2217 }
2218
2219 int
2220 LV2Plugin::connect_and_run(BufferSet& bufs,
2221         ChanMapping in_map, ChanMapping out_map,
2222         pframes_t nframes, framecnt_t offset)
2223 {
2224         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 run %2 offset %3\n", name(), nframes, offset));
2225         Plugin::connect_and_run(bufs, in_map, out_map, nframes, offset);
2226
2227         cycles_t then = get_cycles();
2228
2229         TempoMap&               tmap     = _session.tempo_map();
2230         Metrics::const_iterator metric_i = tmap.metrics_end();
2231         TempoMetric             tmetric  = tmap.metric_at(_session.transport_frame(), &metric_i);
2232
2233         if (_freewheel_control_port) {
2234                 *_freewheel_control_port = _session.engine().freewheeling() ? 1.f : 0.f;
2235         }
2236
2237         if (_bpm_control_port) {
2238                 *_bpm_control_port = tmetric.tempo().beats_per_minute();
2239         }
2240
2241 #ifdef LV2_EXTENDED
2242         if (_can_write_automation && _session.transport_frame() != _next_cycle_start) {
2243                 // add guard-points after locating
2244                 for (AutomationCtrlMap::iterator i = _ctrl_map.begin(); i != _ctrl_map.end(); ++i) {
2245                         i->second->guard = true;
2246                 }
2247         }
2248 #endif
2249
2250         ChanCount bufs_count;
2251         bufs_count.set(DataType::AUDIO, 1);
2252         bufs_count.set(DataType::MIDI, 1);
2253         BufferSet& silent_bufs  = _session.get_silent_buffers(bufs_count);
2254         BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
2255         uint32_t const num_ports = parameter_count();
2256         uint32_t const nil_index = std::numeric_limits<uint32_t>::max();
2257
2258         uint32_t audio_in_index  = 0;
2259         uint32_t audio_out_index = 0;
2260         uint32_t midi_in_index   = 0;
2261         uint32_t midi_out_index  = 0;
2262         uint32_t atom_port_index = 0;
2263         for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
2264                 void*     buf   = NULL;
2265                 uint32_t  index = nil_index;
2266                 PortFlags flags = _port_flags[port_index];
2267                 bool      valid = false;
2268                 if (flags & PORT_AUDIO) {
2269                         if (flags & PORT_INPUT) {
2270                                 index = in_map.get(DataType::AUDIO, audio_in_index++, &valid);
2271                                 buf = (valid)
2272                                         ? bufs.get_audio(index).data(offset)
2273                                         : silent_bufs.get_audio(0).data(offset);
2274                         } else {
2275                                 index = out_map.get(DataType::AUDIO, audio_out_index++, &valid);
2276                                 buf = (valid)
2277                                         ? bufs.get_audio(index).data(offset)
2278                                         : scratch_bufs.get_audio(0).data(offset);
2279                         }
2280                 } else if (flags & (PORT_EVENT|PORT_SEQUENCE)) {
2281                         /* FIXME: The checks here for bufs.count().n_midi() > index shouldn't
2282                            be necessary, but the mapping is illegal in some cases.  Ideally
2283                            that should be fixed, but this is easier...
2284                         */
2285                         if (flags & PORT_MIDI) {
2286                                 if (flags & PORT_INPUT) {
2287                                         index = in_map.get(DataType::MIDI, midi_in_index++, &valid);
2288                                 } else {
2289                                         index = out_map.get(DataType::MIDI, midi_out_index++, &valid);
2290                                 }
2291                                 if (valid && bufs.count().n_midi() > index) {
2292                                         /* Note, ensure_lv2_bufsize() is not RT safe!
2293                                          * However free()/alloc() is only called if a
2294                                          * plugin requires a rsz:minimumSize buffersize
2295                                          * and the existing buffer if smaller.
2296                                          */
2297                                         bufs.ensure_lv2_bufsize((flags & PORT_INPUT), index, _port_minimumSize[port_index]);
2298                                         _ev_buffers[port_index] = bufs.get_lv2_midi(
2299                                                 (flags & PORT_INPUT), index, (flags & PORT_EVENT));
2300                                 }
2301                         } else if ((flags & PORT_POSITION) && (flags & PORT_INPUT)) {
2302                                 lv2_evbuf_reset(_atom_ev_buffers[atom_port_index], true);
2303                                 _ev_buffers[port_index] = _atom_ev_buffers[atom_port_index++];
2304                                 valid                   = true;
2305                         }
2306
2307                         if (valid && (flags & PORT_INPUT)) {
2308                                 Timecode::BBT_Time bbt;
2309                                 if ((flags & PORT_POSITION)) {
2310                                         if (_session.transport_frame() != _next_cycle_start ||
2311                                             _session.transport_speed() != _next_cycle_speed) {
2312                                                 // Transport has changed, write position at cycle start
2313                                                 tmap.bbt_time(_session.transport_frame(), bbt);
2314                                                 write_position(&_impl->forge, _ev_buffers[port_index],
2315                                                                tmetric, bbt, _session.transport_speed(),
2316                                                                _session.transport_frame(), 0);
2317                                         }
2318                                 }
2319
2320                                 // Get MIDI iterator range (empty range if no MIDI)
2321                                 MidiBuffer::iterator m = (index != nil_index)
2322                                         ? bufs.get_midi(index).begin()
2323                                         : silent_bufs.get_midi(0).end();
2324                                 MidiBuffer::iterator m_end = (index != nil_index)
2325                                         ? bufs.get_midi(index).end()
2326                                         : m;
2327
2328                                 // Now merge MIDI and any transport events into the buffer
2329                                 const uint32_t     type = _uri_map.urids.midi_MidiEvent;
2330                                 const framepos_t   tend = _session.transport_frame() + nframes;
2331                                 ++metric_i;
2332                                 while (m != m_end || (metric_i != tmap.metrics_end() &&
2333                                                       (*metric_i)->frame() < tend)) {
2334                                         MetricSection* metric = (metric_i != tmap.metrics_end())
2335                                                 ? *metric_i : NULL;
2336                                         if (m != m_end && (!metric || metric->frame() > (*m).time())) {
2337                                                 const Evoral::MIDIEvent<framepos_t> ev(*m, false);
2338                                                 if (ev.time() < nframes) {
2339                                                         LV2_Evbuf_Iterator eend = lv2_evbuf_end(_ev_buffers[port_index]);
2340                                                         lv2_evbuf_write(&eend, ev.time(), 0, type, ev.size(), ev.buffer());
2341                                                 }
2342                                                 ++m;
2343                                         } else {
2344                                                 tmetric.set_metric(metric);
2345                                                 bbt = metric->start();
2346                                                 write_position(&_impl->forge, _ev_buffers[port_index],
2347                                                                tmetric, bbt, _session.transport_speed(),
2348                                                                metric->frame(),
2349                                                                metric->frame() - _session.transport_frame());
2350                                                 ++metric_i;
2351                                         }
2352                                 }
2353                         } else if (!valid) {
2354                                 // Nothing we understand or care about, connect to scratch
2355                                 // see note for midi-buffer size above
2356                                 scratch_bufs.ensure_lv2_bufsize((flags & PORT_INPUT),
2357                                                 0, _port_minimumSize[port_index]);
2358                                 _ev_buffers[port_index] = scratch_bufs.get_lv2_midi(
2359                                         (flags & PORT_INPUT), 0, (flags & PORT_EVENT));
2360                         }
2361
2362                         buf = lv2_evbuf_get_buffer(_ev_buffers[port_index]);
2363                 } else {
2364                         continue;  // Control port, leave buffer alone
2365                 }
2366                 lilv_instance_connect_port(_impl->instance, port_index, buf);
2367         }
2368
2369         // Read messages from UI and push into appropriate buffers
2370         if (_from_ui) {
2371                 uint32_t read_space = _from_ui->read_space();
2372                 while (read_space > sizeof(UIMessage)) {
2373                         UIMessage msg;
2374                         if (_from_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
2375                                 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
2376                                 break;
2377                         }
2378                         vector<uint8_t> body(msg.size);
2379                         if (_from_ui->read(&body[0], msg.size) != msg.size) {
2380                                 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
2381                                 break;
2382                         }
2383                         if (msg.protocol == URIMap::instance().urids.atom_eventTransfer) {
2384                                 LV2_Evbuf*            buf  = _ev_buffers[msg.index];
2385                                 LV2_Evbuf_Iterator    i    = lv2_evbuf_end(buf);
2386                                 const LV2_Atom* const atom = (const LV2_Atom*)&body[0];
2387                                 if (!lv2_evbuf_write(&i, nframes - 1, 0, atom->type, atom->size,
2388                                                 (const uint8_t*)(atom + 1))) {
2389                                         error << "Failed to write data to LV2 event buffer\n";
2390                                 }
2391                         } else {
2392                                 error << "Received unknown message type from UI" << endmsg;
2393                         }
2394                         read_space -= sizeof(UIMessage) + msg.size;
2395                 }
2396         }
2397
2398         run(nframes);
2399
2400         midi_out_index = 0;
2401         for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
2402                 PortFlags flags = _port_flags[port_index];
2403                 bool      valid = false;
2404
2405                 /* TODO ask drobilla about comment
2406                  * "Make Ardour event buffers generic so plugins can communicate"
2407                  * in libs/ardour/buffer_set.cc:310
2408                  *
2409                  * ideally the user could choose which of the following two modes
2410                  * to use (e.g. instrument/effect chains  MIDI OUT vs MIDI TRHU).
2411                  *
2412                  * This implementation follows the discussion on IRC Mar 16 2013 16:47 UTC
2413                  * 16:51 < drobilla> rgareus: [..] i.e always replace with MIDI output [of LV2 plugin] if it's there
2414                  * 16:52 < drobilla> rgareus: That would probably be good enough [..] to make users not complain
2415                  *                            for quite a while at least ;)
2416                  */
2417                 // copy output of LV2 plugin's MIDI port to Ardour MIDI buffers -- MIDI OUT
2418                 if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE|PORT_MIDI))) {
2419                         const uint32_t buf_index = out_map.get(
2420                                 DataType::MIDI, midi_out_index++, &valid);
2421                         if (valid) {
2422                                 bufs.forward_lv2_midi(_ev_buffers[port_index], buf_index);
2423                         }
2424                 }
2425                 // Flush MIDI (write back to Ardour MIDI buffers) -- MIDI THRU
2426                 else if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
2427                         const uint32_t buf_index = out_map.get(
2428                                 DataType::MIDI, midi_out_index++, &valid);
2429                         if (valid) {
2430                                 bufs.flush_lv2_midi(true, buf_index);
2431                         }
2432                 }
2433
2434                 // Write messages to UI
2435                 if ((_to_ui || _can_write_automation || _patch_port_out_index != (uint32_t)-1) &&
2436                     (flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
2437                         LV2_Evbuf* buf = _ev_buffers[port_index];
2438                         for (LV2_Evbuf_Iterator i = lv2_evbuf_begin(buf);
2439                              lv2_evbuf_is_valid(i);
2440                              i = lv2_evbuf_next(i)) {
2441                                 uint32_t frames, subframes, type, size;
2442                                 uint8_t* data;
2443                                 lv2_evbuf_get(i, &frames, &subframes, &type, &size, &data);
2444
2445 #ifdef LV2_EXTENDED
2446                                 // Intercept Automation Write Events
2447                                 if ((flags & PORT_AUTOCTRL)) {
2448                                         LV2_Atom* atom = (LV2_Atom*)(data - sizeof(LV2_Atom));
2449                                         if (atom->type == _uri_map.urids.atom_Blank ||
2450                                                         atom->type == _uri_map.urids.atom_Object) {
2451                                                 LV2_Atom_Object* obj = (LV2_Atom_Object*)atom;
2452                                                 if (obj->body.otype == _uri_map.urids.auto_event) {
2453                                                         // only if transport_rolling ??
2454                                                         const LV2_Atom* parameter = NULL;
2455                                                         const LV2_Atom* value    = NULL;
2456                                                         lv2_atom_object_get(obj,
2457                                                                             _uri_map.urids.auto_parameter, &parameter,
2458                                                                             _uri_map.urids.auto_value,     &value,
2459                                                                             0);
2460                                                         if (parameter && value) {
2461                                                                 const uint32_t p = ((const LV2_Atom_Int*)parameter)->body;
2462                                                                 const float v = ((const LV2_Atom_Float*)value)->body;
2463                                                                 // -> add automation event..
2464                                                                 AutomationCtrlPtr c = get_automation_control (p);
2465                                                                 if (c && c->ac->automation_state() == Touch) {
2466                                                                         if (c->guard) {
2467                                                                                 c->guard = false;
2468                                                                                 c->ac->list()->add (_session.transport_frame() + frames, v, true, true);
2469                                                                         } else {
2470                                                                                 c->ac->set_double (v, _session.transport_frame() + frames, true);
2471                                                                         }
2472                                                                 }
2473                                                         }
2474                                                 }
2475                                                 else if (obj->body.otype == _uri_map.urids.auto_setup) {
2476                                                         // TODO optional arguments, for now we assume the plugin
2477                                                         // writes automation for its own inputs
2478                                                         // -> put them in "touch" mode (preferably "exclusive plugin touch(TM)"
2479                                                         for (AutomationCtrlMap::iterator i = _ctrl_map.begin(); i != _ctrl_map.end(); ++i) {
2480                                                                 i->second->ac->set_automation_state (Touch);
2481                                                         }
2482                                                 }
2483                                                 else if (obj->body.otype == _uri_map.urids.auto_finalize) {
2484                                                         // set [touched] parameters to "play" ??
2485                                                 }
2486                                                 else if (obj->body.otype == _uri_map.urids.auto_start) {
2487                                                         const LV2_Atom* parameter = NULL;
2488                                                         lv2_atom_object_get(obj,
2489                                                                             _uri_map.urids.auto_parameter, &parameter,
2490                                                                             0);
2491                                                         if (parameter) {
2492                                                                 const uint32_t p = ((const LV2_Atom_Int*)parameter)->body;
2493                                                                 AutomationCtrlPtr c = get_automation_control (p);
2494                                                                 if (c) {
2495                                                                         c->ac->start_touch (_session.transport_frame());
2496                                                                         c->guard = true;
2497                                                                 }
2498                                                         }
2499                                                 }
2500                                                 else if (obj->body.otype == _uri_map.urids.auto_end) {
2501                                                         const LV2_Atom* parameter = NULL;
2502                                                         lv2_atom_object_get(obj,
2503                                                                             _uri_map.urids.auto_parameter, &parameter,
2504                                                                             0);
2505                                                         if (parameter) {
2506                                                                 const uint32_t p = ((const LV2_Atom_Int*)parameter)->body;
2507                                                                 AutomationCtrlPtr c = get_automation_control (p);
2508                                                                 if (c) {
2509                                                                         c->ac->stop_touch (true, _session.transport_frame());
2510                                                                 }
2511                                                         }
2512                                                 }
2513                                         }
2514                                 }
2515 #endif
2516
2517                                 // Intercept patch change messages to emit PropertyChanged signal
2518                                 if ((flags & PORT_PATCHMSG)) {
2519                                         LV2_Atom* atom = (LV2_Atom*)(data - sizeof(LV2_Atom));
2520                                         if (atom->type == _uri_map.urids.atom_Blank ||
2521                                             atom->type == _uri_map.urids.atom_Object) {
2522                                                 LV2_Atom_Object* obj = (LV2_Atom_Object*)atom;
2523                                                 if (obj->body.otype == _uri_map.urids.patch_Set) {
2524                                                         const LV2_Atom* property = NULL;
2525                                                         const LV2_Atom* value    = NULL;
2526                                                         lv2_atom_object_get(obj,
2527                                                                             _uri_map.urids.patch_property, &property,
2528                                                                             _uri_map.urids.patch_value,    &value,
2529                                                                             0);
2530
2531                                                         if (property && value &&
2532                                                             property->type == _uri_map.urids.atom_URID &&
2533                                                             value->type    == _uri_map.urids.atom_Path) {
2534                                                                 const uint32_t prop_id = ((const LV2_Atom_URID*)property)->body;
2535                                                                 const char*    path    = (const char*)LV2_ATOM_BODY_CONST(value);
2536
2537                                                                 // Emit PropertyChanged signal for UI
2538                                                                 // TODO: This should emit the control's Changed signal
2539                                                                 PropertyChanged(prop_id, Variant(Variant::PATH, path));
2540                                                         } else {
2541                                                                 std::cerr << "warning: patch:Set for unknown property" << std::endl;
2542                                                         }
2543                                                 }
2544                                         }
2545                                 }
2546
2547                                 if (!_to_ui) continue;
2548                                 write_to_ui(port_index, URIMap::instance().urids.atom_eventTransfer,
2549                                             size + sizeof(LV2_Atom),
2550                                             data - sizeof(LV2_Atom));
2551                         }
2552                 }
2553         }
2554
2555         cycles_t now = get_cycles();
2556         set_cycles((uint32_t)(now - then));
2557
2558         // Update expected transport information for next cycle so we can detect changes
2559         _next_cycle_speed = _session.transport_speed();
2560         _next_cycle_start = _session.transport_frame() + (nframes * _next_cycle_speed);
2561
2562         if (_latency_control_port) {
2563                 framecnt_t new_latency = signal_latency ();
2564                 if (_current_latency != new_latency) {
2565                         LatencyChanged (_current_latency, new_latency); /* EMIT SIGNAL */
2566                 }
2567                 _current_latency = new_latency;
2568         }
2569         return 0;
2570 }
2571
2572 bool
2573 LV2Plugin::parameter_is_control(uint32_t param) const
2574 {
2575         assert(param < _port_flags.size());
2576         return _port_flags[param] & PORT_CONTROL;
2577 }
2578
2579 bool
2580 LV2Plugin::parameter_is_audio(uint32_t param) const
2581 {
2582         assert(param < _port_flags.size());
2583         return _port_flags[param] & PORT_AUDIO;
2584 }
2585
2586 bool
2587 LV2Plugin::parameter_is_event(uint32_t param) const
2588 {
2589         assert(param < _port_flags.size());
2590         return _port_flags[param] & PORT_EVENT;
2591 }
2592
2593 bool
2594 LV2Plugin::parameter_is_output(uint32_t param) const
2595 {
2596         assert(param < _port_flags.size());
2597         return _port_flags[param] & PORT_OUTPUT;
2598 }
2599
2600 bool
2601 LV2Plugin::parameter_is_input(uint32_t param) const
2602 {
2603         assert(param < _port_flags.size());
2604         return _port_flags[param] & PORT_INPUT;
2605 }
2606
2607 void
2608 LV2Plugin::print_parameter(uint32_t param, char* buf, uint32_t len) const
2609 {
2610         if (buf && len) {
2611                 if (param < parameter_count()) {
2612                         snprintf(buf, len, "%.3f", get_parameter(param));
2613                 } else {
2614                         strcat(buf, "0");
2615                 }
2616         }
2617 }
2618
2619 boost::shared_ptr<ScalePoints>
2620 LV2Plugin::get_scale_points(uint32_t port_index) const
2621 {
2622         const LilvPort*  port   = lilv_plugin_get_port_by_index(_impl->plugin, port_index);
2623         LilvScalePoints* points = lilv_port_get_scale_points(_impl->plugin, port);
2624
2625         boost::shared_ptr<ScalePoints> ret;
2626         if (!points) {
2627                 return ret;
2628         }
2629
2630         ret = boost::shared_ptr<ScalePoints>(new ScalePoints());
2631
2632         LILV_FOREACH(scale_points, i, points) {
2633                 const LilvScalePoint* p     = lilv_scale_points_get(points, i);
2634                 const LilvNode*       label = lilv_scale_point_get_label(p);
2635                 const LilvNode*       value = lilv_scale_point_get_value(p);
2636                 if (label && (lilv_node_is_float(value) || lilv_node_is_int(value))) {
2637                         ret->insert(make_pair(lilv_node_as_string(label),
2638                                               lilv_node_as_float(value)));
2639                 }
2640         }
2641
2642         lilv_scale_points_free(points);
2643         return ret;
2644 }
2645
2646 void
2647 LV2Plugin::run(pframes_t nframes)
2648 {
2649         uint32_t const N = parameter_count();
2650         for (uint32_t i = 0; i < N; ++i) {
2651                 if (parameter_is_control(i) && parameter_is_input(i)) {
2652                         _control_data[i] = _shadow_data[i];
2653                 }
2654         }
2655
2656         lilv_instance_run(_impl->instance, nframes);
2657
2658         if (_impl->work_iface) {
2659                 _worker->emit_responses();
2660                 if (_impl->work_iface->end_run) {
2661                         _impl->work_iface->end_run(_impl->instance->lv2_handle);
2662                 }
2663         }
2664 }
2665
2666 void
2667 LV2Plugin::latency_compute_run()
2668 {
2669         if (!_latency_control_port) {
2670                 return;
2671         }
2672
2673         // Run the plugin so that it can set its latency parameter
2674
2675         bool was_activated = _was_activated;
2676         activate();
2677
2678         uint32_t port_index = 0;
2679         uint32_t in_index   = 0;
2680         uint32_t out_index  = 0;
2681
2682         // this is done in the main thread. non realtime.
2683         const framecnt_t bufsize = _engine.samples_per_cycle();
2684         float            *buffer = (float*) malloc(_engine.samples_per_cycle() * sizeof(float));
2685
2686         memset(buffer, 0, sizeof(float) * bufsize);
2687
2688         // FIXME: Ensure plugins can handle in-place processing
2689
2690         port_index = 0;
2691
2692         while (port_index < parameter_count()) {
2693                 if (parameter_is_audio(port_index)) {
2694                         if (parameter_is_input(port_index)) {
2695                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
2696                                 in_index++;
2697                         } else if (parameter_is_output(port_index)) {
2698                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
2699                                 out_index++;
2700                         }
2701                 }
2702                 port_index++;
2703         }
2704
2705         run(bufsize);
2706         deactivate();
2707         if (was_activated) {
2708                 activate();
2709         }
2710         free(buffer);
2711 }
2712
2713 const LilvPort*
2714 LV2Plugin::Impl::designated_input (const char* uri, void** bufptrs[], void** bufptr)
2715 {
2716         const LilvPort* port = NULL;
2717         LilvNode* designation = lilv_new_uri(_world.world, uri);
2718         port = lilv_plugin_get_port_by_designation(
2719                 plugin, _world.lv2_InputPort, designation);
2720         lilv_node_free(designation);
2721         if (port) {
2722                 bufptrs[lilv_port_get_index(plugin, port)] = bufptr;
2723         }
2724         return port;
2725 }
2726
2727 static bool lv2_filter (const string& str, void* /*arg*/)
2728 {
2729         /* Not a dotfile, has a prefix before a period, suffix is "lv2" */
2730
2731         return str[0] != '.' && (str.length() > 3 && str.find (".lv2") == (str.length() - 4));
2732 }
2733
2734
2735 LV2World::LV2World()
2736         : world(lilv_world_new())
2737         , _bundle_checked(false)
2738 {
2739         atom_AtomPort      = lilv_new_uri(world, LV2_ATOM__AtomPort);
2740         atom_Chunk         = lilv_new_uri(world, LV2_ATOM__Chunk);
2741         atom_Sequence      = lilv_new_uri(world, LV2_ATOM__Sequence);
2742         atom_bufferType    = lilv_new_uri(world, LV2_ATOM__bufferType);
2743         atom_supports      = lilv_new_uri(world, LV2_ATOM__supports);
2744         atom_eventTransfer = lilv_new_uri(world, LV2_ATOM__eventTransfer);
2745         ev_EventPort       = lilv_new_uri(world, LILV_URI_EVENT_PORT);
2746         ext_logarithmic    = lilv_new_uri(world, LV2_PORT_PROPS__logarithmic);
2747         ext_notOnGUI       = lilv_new_uri(world, LV2_PORT_PROPS__notOnGUI);
2748         lv2_AudioPort      = lilv_new_uri(world, LILV_URI_AUDIO_PORT);
2749         lv2_ControlPort    = lilv_new_uri(world, LILV_URI_CONTROL_PORT);
2750         lv2_InputPort      = lilv_new_uri(world, LILV_URI_INPUT_PORT);
2751         lv2_OutputPort     = lilv_new_uri(world, LILV_URI_OUTPUT_PORT);
2752         lv2_inPlaceBroken  = lilv_new_uri(world, LV2_CORE__inPlaceBroken);
2753         lv2_isSideChain    = lilv_new_uri(world, LV2_CORE_PREFIX "isSideChain");
2754         lv2_integer        = lilv_new_uri(world, LV2_CORE__integer);
2755         lv2_default        = lilv_new_uri(world, LV2_CORE__default);
2756         lv2_minimum        = lilv_new_uri(world, LV2_CORE__minimum);
2757         lv2_maximum        = lilv_new_uri(world, LV2_CORE__maximum);
2758         lv2_reportsLatency = lilv_new_uri(world, LV2_CORE__reportsLatency);
2759         lv2_sampleRate     = lilv_new_uri(world, LV2_CORE__sampleRate);
2760         lv2_toggled        = lilv_new_uri(world, LV2_CORE__toggled);
2761         lv2_enumeration    = lilv_new_uri(world, LV2_CORE__enumeration);
2762         lv2_freewheeling   = lilv_new_uri(world, LV2_CORE__freeWheeling);
2763         midi_MidiEvent     = lilv_new_uri(world, LILV_URI_MIDI_EVENT);
2764         rdfs_comment       = lilv_new_uri(world, LILV_NS_RDFS "comment");
2765         rdfs_label         = lilv_new_uri(world, LILV_NS_RDFS "label");
2766         rdfs_range         = lilv_new_uri(world, LILV_NS_RDFS "range");
2767         rsz_minimumSize    = lilv_new_uri(world, LV2_RESIZE_PORT__minimumSize);
2768         time_Position      = lilv_new_uri(world, LV2_TIME__Position);
2769         ui_GtkUI           = lilv_new_uri(world, LV2_UI__GtkUI);
2770         ui_external        = lilv_new_uri(world, "http://lv2plug.in/ns/extensions/ui#external");
2771         ui_externalkx      = lilv_new_uri(world, "http://kxstudio.sf.net/ns/lv2ext/external-ui#Widget");
2772         units_unit         = lilv_new_uri(world, LV2_UNITS__unit);
2773         units_render       = lilv_new_uri(world, LV2_UNITS__render);
2774         units_hz           = lilv_new_uri(world, LV2_UNITS__hz);
2775         units_midiNote     = lilv_new_uri(world, LV2_UNITS__midiNote);
2776         units_db           = lilv_new_uri(world, LV2_UNITS__db);
2777         patch_writable     = lilv_new_uri(world, LV2_PATCH__writable);
2778         patch_Message      = lilv_new_uri(world, LV2_PATCH__Message);
2779 #ifdef LV2_EXTENDED
2780         lv2_noSampleAccurateCtrl    = lilv_new_uri(world, "http://ardour.org/lv2/ext#noSampleAccurateControls");
2781         auto_can_write_automatation = lilv_new_uri(world, LV2_AUTOMATE_URI__can_write);
2782         auto_automation_control     = lilv_new_uri(world, LV2_AUTOMATE_URI__control);
2783         auto_automation_controlled  = lilv_new_uri(world, LV2_AUTOMATE_URI__controlled);
2784 #endif
2785 #ifdef HAVE_LV2_1_2_0
2786         bufz_powerOf2BlockLength = lilv_new_uri(world, LV2_BUF_SIZE__powerOf2BlockLength);
2787         bufz_fixedBlockLength    = lilv_new_uri(world, LV2_BUF_SIZE__fixedBlockLength);
2788         bufz_nominalBlockLength  = lilv_new_uri(world, "http://lv2plug.in/ns/ext/buf-size#nominalBlockLength");
2789 #endif
2790
2791 }
2792
2793 LV2World::~LV2World()
2794 {
2795         if (!world) {
2796                 return;
2797         }
2798 #ifdef HAVE_LV2_1_2_0
2799         lilv_node_free(bufz_nominalBlockLength);
2800         lilv_node_free(bufz_fixedBlockLength);
2801         lilv_node_free(bufz_powerOf2BlockLength);
2802 #endif
2803 #ifdef LV2_EXTENDED
2804         lilv_node_free(lv2_noSampleAccurateCtrl);
2805         lilv_node_free(auto_can_write_automatation);
2806         lilv_node_free(auto_automation_control);
2807         lilv_node_free(auto_automation_controlled);
2808 #endif
2809         lilv_node_free(patch_Message);
2810         lilv_node_free(patch_writable);
2811         lilv_node_free(units_hz);
2812         lilv_node_free(units_midiNote);
2813         lilv_node_free(units_db);
2814         lilv_node_free(units_unit);
2815         lilv_node_free(units_render);
2816         lilv_node_free(ui_externalkx);
2817         lilv_node_free(ui_external);
2818         lilv_node_free(ui_GtkUI);
2819         lilv_node_free(time_Position);
2820         lilv_node_free(rsz_minimumSize);
2821         lilv_node_free(rdfs_comment);
2822         lilv_node_free(rdfs_label);
2823         lilv_node_free(rdfs_range);
2824         lilv_node_free(midi_MidiEvent);
2825         lilv_node_free(lv2_enumeration);
2826         lilv_node_free(lv2_freewheeling);
2827         lilv_node_free(lv2_toggled);
2828         lilv_node_free(lv2_sampleRate);
2829         lilv_node_free(lv2_reportsLatency);
2830         lilv_node_free(lv2_integer);
2831         lilv_node_free(lv2_isSideChain);
2832         lilv_node_free(lv2_inPlaceBroken);
2833         lilv_node_free(lv2_OutputPort);
2834         lilv_node_free(lv2_InputPort);
2835         lilv_node_free(lv2_ControlPort);
2836         lilv_node_free(lv2_AudioPort);
2837         lilv_node_free(ext_notOnGUI);
2838         lilv_node_free(ext_logarithmic);
2839         lilv_node_free(ev_EventPort);
2840         lilv_node_free(atom_supports);
2841         lilv_node_free(atom_eventTransfer);
2842         lilv_node_free(atom_bufferType);
2843         lilv_node_free(atom_Sequence);
2844         lilv_node_free(atom_Chunk);
2845         lilv_node_free(atom_AtomPort);
2846         lilv_world_free(world);
2847         world = NULL;
2848 }
2849
2850 void
2851 LV2World::load_bundled_plugins(bool verbose)
2852 {
2853         if (!_bundle_checked) {
2854                 if (verbose) {
2855                         cout << "Scanning folders for bundled LV2s: " << ARDOUR::lv2_bundled_search_path().to_string() << endl;
2856                 }
2857
2858                 vector<string> plugin_objects;
2859                 find_paths_matching_filter (plugin_objects, ARDOUR::lv2_bundled_search_path(), lv2_filter, 0, true, true, true);
2860                 for ( vector<string>::iterator x = plugin_objects.begin(); x != plugin_objects.end (); ++x) {
2861 #ifdef PLATFORM_WINDOWS
2862                         string uri = "file:///" + *x + "/";
2863 #else
2864                         string uri = "file://" + *x + "/";
2865 #endif
2866                         LilvNode *node = lilv_new_uri(world, uri.c_str());
2867                         lilv_world_load_bundle(world, node);
2868                         lilv_node_free(node);
2869                 }
2870
2871                 lilv_world_load_all(world);
2872                 _bundle_checked = true;
2873         }
2874 }
2875
2876 LV2PluginInfo::LV2PluginInfo (const char* plugin_uri)
2877 {
2878         type = ARDOUR::LV2;
2879         _plugin_uri = strdup(plugin_uri);
2880 }
2881
2882 LV2PluginInfo::~LV2PluginInfo()
2883 {
2884         free(_plugin_uri);
2885         _plugin_uri = NULL;
2886 }
2887
2888 PluginPtr
2889 LV2PluginInfo::load(Session& session)
2890 {
2891         try {
2892                 PluginPtr plugin;
2893                 const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
2894                 LilvNode* uri = lilv_new_uri(_world.world, _plugin_uri);
2895                 if (!uri) { throw failed_constructor(); }
2896                 const LilvPlugin* lp = lilv_plugins_get_by_uri(plugins, uri);
2897                 if (!lp) { throw failed_constructor(); }
2898                 plugin.reset(new LV2Plugin(session.engine(), session, lp, session.frame_rate()));
2899                 lilv_node_free(uri);
2900                 plugin->set_info(PluginInfoPtr(shared_from_this ()));
2901                 return plugin;
2902         } catch (failed_constructor& err) {
2903                 return PluginPtr((Plugin*)0);
2904         }
2905
2906         return PluginPtr();
2907 }
2908
2909 std::vector<Plugin::PresetRecord>
2910 LV2PluginInfo::get_presets (bool /*user_only*/) const
2911 {
2912         std::vector<Plugin::PresetRecord> p;
2913 #ifndef NO_PLUGIN_STATE
2914         const LilvPlugin* lp = NULL;
2915         try {
2916                 PluginPtr plugin;
2917                 const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
2918                 LilvNode* uri = lilv_new_uri(_world.world, _plugin_uri);
2919                 if (!uri) { throw failed_constructor(); }
2920                 lp = lilv_plugins_get_by_uri(plugins, uri);
2921                 if (!lp) { throw failed_constructor(); }
2922                 lilv_node_free(uri);
2923         } catch (failed_constructor& err) {
2924                 return p;
2925         }
2926         assert (lp);
2927         // see LV2Plugin::find_presets
2928         LilvNode* lv2_appliesTo = lilv_new_uri(_world.world, LV2_CORE__appliesTo);
2929         LilvNode* pset_Preset   = lilv_new_uri(_world.world, LV2_PRESETS__Preset);
2930         LilvNode* rdfs_label    = lilv_new_uri(_world.world, LILV_NS_RDFS "label");
2931
2932         LilvNodes* presets = lilv_plugin_get_related(lp, pset_Preset);
2933         LILV_FOREACH(nodes, i, presets) {
2934                 const LilvNode* preset = lilv_nodes_get(presets, i);
2935                 lilv_world_load_resource(_world.world, preset);
2936                 LilvNode* name = get_value(_world.world, preset, rdfs_label);
2937                 bool userpreset = true; // TODO
2938                 if (name) {
2939                         p.push_back (Plugin::PresetRecord (lilv_node_as_string(preset), lilv_node_as_string(name), userpreset));
2940                         lilv_node_free(name);
2941                 }
2942         }
2943         lilv_nodes_free(presets);
2944         lilv_node_free(rdfs_label);
2945         lilv_node_free(pset_Preset);
2946         lilv_node_free(lv2_appliesTo);
2947 #endif
2948         return p;
2949 }
2950
2951 bool
2952 LV2PluginInfo::in_category (const std::string &c) const
2953 {
2954         // TODO use untranslated lilv_plugin_get_class()
2955         // match gtk2_ardour/plugin_selector.cc
2956         if (category == c) {
2957                 return true;
2958         }
2959         return false;
2960 }
2961
2962 bool
2963 LV2PluginInfo::is_instrument () const
2964 {
2965         if (category == "Instrument") {
2966                 return true;
2967         }
2968 #if 1
2969         /* until we make sure that category remains untranslated in the lv2.ttl spec
2970          * and until most instruments also classify themselves as such, there's a 2nd check:
2971          */
2972         if (n_inputs.n_midi() > 0 && n_inputs.n_audio() == 0 && n_outputs.n_audio() > 0) {
2973                 return true;
2974         }
2975 #endif
2976         return false;
2977 }
2978
2979 PluginInfoList*
2980 LV2PluginInfo::discover()
2981 {
2982         LV2World world;
2983         world.load_bundled_plugins();
2984         _world.load_bundled_plugins(true);
2985
2986         PluginInfoList*    plugs   = new PluginInfoList;
2987         const LilvPlugins* plugins = lilv_world_get_all_plugins(world.world);
2988
2989         LILV_FOREACH(plugins, i, plugins) {
2990                 const LilvPlugin* p = lilv_plugins_get(plugins, i);
2991                 const LilvNode* pun = lilv_plugin_get_uri(p);
2992                 if (!pun) continue;
2993                 LV2PluginInfoPtr info(new LV2PluginInfo(lilv_node_as_string(pun)));
2994
2995                 LilvNode* name = lilv_plugin_get_name(p);
2996                 if (!name || !lilv_plugin_get_port_by_index(p, 0)) {
2997                         warning << "Ignoring invalid LV2 plugin "
2998                                 << lilv_node_as_string(lilv_plugin_get_uri(p))
2999                                 << endmsg;
3000                         continue;
3001                 }
3002
3003                 if (lilv_plugin_has_feature(p, world.lv2_inPlaceBroken)) {
3004                         warning << string_compose(
3005                             _("Ignoring LV2 plugin \"%1\" since it cannot do inplace processing."),
3006                             lilv_node_as_string(name)) << endmsg;
3007                         lilv_node_free(name);
3008                         continue;
3009                 }
3010
3011 #ifdef HAVE_LV2_1_2_0
3012                 LilvNodes *required_features = lilv_plugin_get_required_features (p);
3013                 if (lilv_nodes_contains (required_features, world.bufz_powerOf2BlockLength) ||
3014                                 lilv_nodes_contains (required_features, world.bufz_fixedBlockLength)
3015                    ) {
3016                         warning << string_compose(
3017                             _("Ignoring LV2 plugin \"%1\" because its buffer-size requirements cannot be satisfied."),
3018                             lilv_node_as_string(name)) << endmsg;
3019                         lilv_nodes_free(required_features);
3020                         lilv_node_free(name);
3021                         continue;
3022                 }
3023                 lilv_nodes_free(required_features);
3024 #endif
3025
3026                 info->type = LV2;
3027
3028                 info->name = string(lilv_node_as_string(name));
3029                 lilv_node_free(name);
3030                 ARDOUR::PluginScanMessage(_("LV2"), info->name, false);
3031
3032                 const LilvPluginClass* pclass = lilv_plugin_get_class(p);
3033                 const LilvNode*        label  = lilv_plugin_class_get_label(pclass);
3034                 info->category = lilv_node_as_string(label);
3035
3036                 LilvNode* author_name = lilv_plugin_get_author_name(p);
3037                 info->creator = author_name ? string(lilv_node_as_string(author_name)) : "Unknown";
3038                 lilv_node_free(author_name);
3039
3040                 info->path = "/NOPATH"; // Meaningless for LV2
3041
3042                 /* count atom-event-ports that feature
3043                  * atom:supports <http://lv2plug.in/ns/ext/midi#MidiEvent>
3044                  *
3045                  * TODO: nicely ask drobilla to make a lilv_ call for that
3046                  */
3047                 int count_midi_out = 0;
3048                 int count_midi_in = 0;
3049                 for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
3050                         const LilvPort* port  = lilv_plugin_get_port_by_index(p, i);
3051                         if (lilv_port_is_a(p, port, world.atom_AtomPort)) {
3052                                 LilvNodes* buffer_types = lilv_port_get_value(
3053                                         p, port, world.atom_bufferType);
3054                                 LilvNodes* atom_supports = lilv_port_get_value(
3055                                         p, port, world.atom_supports);
3056
3057                                 if (lilv_nodes_contains(buffer_types, world.atom_Sequence)
3058                                                 && lilv_nodes_contains(atom_supports, world.midi_MidiEvent)) {
3059                                         if (lilv_port_is_a(p, port, world.lv2_InputPort)) {
3060                                                 count_midi_in++;
3061                                         }
3062                                         if (lilv_port_is_a(p, port, world.lv2_OutputPort)) {
3063                                                 count_midi_out++;
3064                                         }
3065                                 }
3066                                 lilv_nodes_free(buffer_types);
3067                                 lilv_nodes_free(atom_supports);
3068                         }
3069                 }
3070
3071                 info->n_inputs.set_audio(
3072                         lilv_plugin_get_num_ports_of_class(
3073                                 p, world.lv2_InputPort, world.lv2_AudioPort, NULL));
3074                 info->n_inputs.set_midi(
3075                         lilv_plugin_get_num_ports_of_class(
3076                                 p, world.lv2_InputPort, world.ev_EventPort, NULL)
3077                         + count_midi_in);
3078
3079                 info->n_outputs.set_audio(
3080                         lilv_plugin_get_num_ports_of_class(
3081                                 p, world.lv2_OutputPort, world.lv2_AudioPort, NULL));
3082                 info->n_outputs.set_midi(
3083                         lilv_plugin_get_num_ports_of_class(
3084                                 p, world.lv2_OutputPort, world.ev_EventPort, NULL)
3085                         + count_midi_out);
3086
3087                 info->unique_id = lilv_node_as_uri(lilv_plugin_get_uri(p));
3088                 info->index     = 0; // Meaningless for LV2
3089
3090                 plugs->push_back(info);
3091         }
3092
3093         return plugs;
3094 }