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