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