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