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