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