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