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