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