honor LV2 rsz:minimumSize for Atom Event buffers
[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 <string>
21 #include <vector>
22 #include <limits>
23
24 #include <cmath>
25 #include <cstdlib>
26 #include <cstring>
27
28 #include <giomm/file.h>
29 #include <glib/gprintf.h>
30 #include <glibmm.h>
31
32 #include <boost/utility.hpp>
33
34 #include "pbd/compose.h"
35 #include "pbd/error.h"
36 #include "pbd/xml++.h"
37
38 #include "libardour-config.h"
39
40 #include "ardour/audio_buffer.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/debug.h"
43 #include "ardour/lv2_plugin.h"
44 #include "ardour/session.h"
45 #include "ardour/tempo.h"
46 #include "ardour/types.h"
47 #include "ardour/utils.h"
48 #include "ardour/worker.h"
49
50 #include "i18n.h"
51 #include <locale.h>
52
53 #include <lilv/lilv.h>
54
55 #include "lv2/lv2plug.in/ns/ext/atom/atom.h"
56 #include "lv2/lv2plug.in/ns/ext/atom/forge.h"
57 #include "lv2/lv2plug.in/ns/ext/log/log.h"
58 #include "lv2/lv2plug.in/ns/ext/midi/midi.h"
59 #include "lv2/lv2plug.in/ns/ext/port-props/port-props.h"
60 #include "lv2/lv2plug.in/ns/ext/presets/presets.h"
61 #include "lv2/lv2plug.in/ns/ext/state/state.h"
62 #include "lv2/lv2plug.in/ns/ext/time/time.h"
63 #include "lv2/lv2plug.in/ns/ext/worker/worker.h"
64 #include "lv2/lv2plug.in/ns/ext/resize-port/resize-port.h"
65 #include "lv2/lv2plug.in/ns/extensions/ui/ui.h"
66 #ifdef HAVE_NEW_LV2
67 #include "lv2/lv2plug.in/ns/ext/buf-size/buf-size.h"
68 #include "lv2/lv2plug.in/ns/ext/options/options.h"
69 #endif
70
71 #include "lv2_evbuf.h"
72
73 #ifdef HAVE_SUIL
74 #include <suil/suil.h>
75 #endif
76
77 /** The number of MIDI buffers that will fit in a UI/worker comm buffer.
78     This needs to be roughly the number of cycles the UI will get around to
79     actually processing the traffic.  Lower values are flakier but save memory.
80 */
81 static const size_t NBUFS = 4;
82
83 using namespace std;
84 using namespace ARDOUR;
85 using namespace PBD;
86
87 URIMap LV2Plugin::_uri_map;
88
89 LV2Plugin::URIDs LV2Plugin::urids = {
90         _uri_map.uri_to_id(LV2_ATOM__Chunk),
91         _uri_map.uri_to_id(LV2_ATOM__Path),
92         _uri_map.uri_to_id(LV2_ATOM__Sequence),
93         _uri_map.uri_to_id(LV2_ATOM__eventTransfer),
94         _uri_map.uri_to_id(LV2_LOG__Error),
95         _uri_map.uri_to_id(LV2_LOG__Note),
96         _uri_map.uri_to_id(LV2_LOG__Warning),
97         _uri_map.uri_to_id(LV2_MIDI__MidiEvent),
98         _uri_map.uri_to_id(LV2_TIME__Position),
99         _uri_map.uri_to_id(LV2_TIME__bar),
100         _uri_map.uri_to_id(LV2_TIME__barBeat),
101         _uri_map.uri_to_id(LV2_TIME__beatUnit),
102         _uri_map.uri_to_id(LV2_TIME__beatsPerBar),
103         _uri_map.uri_to_id(LV2_TIME__beatsPerMinute),
104         _uri_map.uri_to_id(LV2_TIME__frame),
105         _uri_map.uri_to_id(LV2_TIME__speed)
106 };
107
108 class LV2World : boost::noncopyable {
109 public:
110         LV2World ();
111         ~LV2World ();
112
113         LilvWorld* world;
114
115         LilvNode* atom_AtomPort;
116         LilvNode* atom_Chunk;
117         LilvNode* atom_Sequence;
118         LilvNode* atom_bufferType;
119         LilvNode* atom_eventTransfer;
120         LilvNode* atom_supports;
121         LilvNode* ev_EventPort;
122         LilvNode* ext_logarithmic;
123         LilvNode* ext_notOnGUI;
124         LilvNode* lv2_AudioPort;
125         LilvNode* lv2_ControlPort;
126         LilvNode* lv2_InputPort;
127         LilvNode* lv2_OutputPort;
128         LilvNode* lv2_enumeration;
129         LilvNode* lv2_inPlaceBroken;
130         LilvNode* lv2_integer;
131         LilvNode* lv2_reportsLatency;
132         LilvNode* lv2_sampleRate;
133         LilvNode* lv2_toggled;
134         LilvNode* midi_MidiEvent;
135         LilvNode* rdfs_comment;
136         LilvNode* rsz_minimumSize;
137         LilvNode* time_Position;
138         LilvNode* ui_GtkUI;
139         LilvNode* ui_external;
140 };
141
142 static LV2World _world;
143
144 /* worker extension */
145
146 /** Called by the plugin to schedule non-RT work. */
147 static LV2_Worker_Status
148 work_schedule(LV2_Worker_Schedule_Handle handle,
149               uint32_t                   size,
150               const void*                data)
151 {
152         LV2Plugin* plugin = (LV2Plugin*)handle;
153         if (plugin->session().engine().freewheeling()) {
154                 // Freewheeling, do the work immediately in this (audio) thread
155                 return (LV2_Worker_Status)plugin->work(size, data);
156         } else {
157                 // Enqueue message for the worker thread
158                 return plugin->worker()->schedule(size, data) ?
159                         LV2_WORKER_SUCCESS : LV2_WORKER_ERR_UNKNOWN;
160         }
161 }
162
163 /** Called by the plugin to respond to non-RT work. */
164 static LV2_Worker_Status
165 work_respond(LV2_Worker_Respond_Handle handle,
166              uint32_t                  size,
167              const void*               data)
168 {
169         LV2Plugin* plugin = (LV2Plugin*)handle;
170         if (plugin->session().engine().freewheeling()) {
171                 // Freewheeling, respond immediately in this (audio) thread
172                 return (LV2_Worker_Status)plugin->work_response(size, data);
173         } else {
174                 // Enqueue response for the worker
175                 return plugin->worker()->respond(size, data) ?
176                         LV2_WORKER_SUCCESS : LV2_WORKER_ERR_UNKNOWN;
177         }
178 }
179
180 /* log extension */
181
182 static int
183 log_vprintf(LV2_Log_Handle /*handle*/,
184             LV2_URID       type,
185             const char*    fmt,
186             va_list        args)
187 {
188         char* str = NULL;
189         const int ret = g_vasprintf(&str, fmt, args);
190         if (type == LV2Plugin::urids.log_Error) {
191                 error << str << endmsg;
192         } else if (type == LV2Plugin::urids.log_Warning) {
193                 warning << str << endmsg;
194         } else if (type == LV2Plugin::urids.log_Note) {
195                 info << str << endmsg;
196         }
197         // TODO: Toggleable log:Trace message support
198         return ret;
199 }
200
201 static int
202 log_printf(LV2_Log_Handle handle,
203            LV2_URID       type,
204            const char*    fmt, ...)
205 {
206         va_list args;
207         va_start(args, fmt);
208         const int ret = log_vprintf(handle, type, fmt, args);
209         va_end(args);
210         return ret;
211 }
212
213 struct LV2Plugin::Impl {
214         Impl() : plugin(0), ui(0), ui_type(0), name(0), author(0), instance(0)
215                , work_iface(0)
216                , state(0)
217         {}
218
219         /** Find the LV2 input port with the given designation.
220          * If found, bufptrs[port_index] will be set to bufptr.
221          */
222         const LilvPort* designated_input (const char* uri, void** bufptrs[], void** bufptr);
223
224         const LilvPlugin*           plugin;
225         const LilvUI*               ui;
226         const LilvNode*             ui_type;
227         LilvNode*                   name;
228         LilvNode*                   author;
229         LilvInstance*               instance;
230         const LV2_Worker_Interface* work_iface;
231         LilvState*                  state;
232         LV2_Atom_Forge              forge;
233 };
234
235 LV2Plugin::LV2Plugin (AudioEngine& engine,
236                       Session&     session,
237                       const void*  c_plugin,
238                       framecnt_t   rate)
239         : Plugin (engine, session)
240         , Workee ()
241         , _impl(new Impl())
242         , _features(NULL)
243         , _worker(NULL)
244         , _insert_id("0")
245 {
246         init(c_plugin, rate);
247 }
248
249 LV2Plugin::LV2Plugin (const LV2Plugin& other)
250         : Plugin (other)
251         , Workee ()
252         , _impl(new Impl())
253         , _features(NULL)
254         , _worker(NULL)
255         , _insert_id(other._insert_id)
256 {
257         init(other._impl->plugin, other._sample_rate);
258
259         for (uint32_t i = 0; i < parameter_count(); ++i) {
260                 _control_data[i] = other._shadow_data[i];
261                 _shadow_data[i]  = other._shadow_data[i];
262         }
263 }
264
265 void
266 LV2Plugin::init(const void* c_plugin, framecnt_t rate)
267 {
268         DEBUG_TRACE(DEBUG::LV2, "init\n");
269
270         _impl->plugin           = (const LilvPlugin*)c_plugin;
271         _impl->ui               = NULL;
272         _impl->ui_type          = NULL;
273         _to_ui                  = NULL;
274         _from_ui                = NULL;
275         _control_data           = 0;
276         _shadow_data            = 0;
277         _atom_ev_buffers        = 0;
278         _ev_buffers             = 0;
279         _bpm_control_port       = 0;
280         _freewheel_control_port = 0;
281         _latency_control_port   = 0;
282         _next_cycle_start       = std::numeric_limits<framepos_t>::max();
283         _next_cycle_speed       = 1.0;
284         _block_length           = _engine.frames_per_cycle();
285         _seq_size               = _engine.raw_buffer_size(DataType::MIDI);
286         _state_version          = 0;
287         _was_activated          = false;
288         _has_state_interface    = false;
289
290         _instance_access_feature.URI = "http://lv2plug.in/ns/ext/instance-access";
291         _data_access_feature.URI     = "http://lv2plug.in/ns/ext/data-access";
292         _make_path_feature.URI       = LV2_STATE__makePath;
293         _log_feature.URI             = LV2_LOG__log;
294         _work_schedule_feature.URI   = LV2_WORKER__schedule;
295         _work_schedule_feature.data  = NULL;
296         _def_state_feature.URI       = LV2_STATE_PREFIX "loadDefaultState";  // Post LV2-1.2.0
297         _def_state_feature.data      = NULL;
298
299         const LilvPlugin* plugin = _impl->plugin;
300
301         LilvNode* state_iface_uri = lilv_new_uri(_world.world, LV2_STATE__interface);
302         LilvNode* state_uri       = lilv_new_uri(_world.world, LV2_STATE_URI);
303         _has_state_interface =
304                 // What plugins should have (lv2:extensionData state:Interface)
305                 lilv_plugin_has_extension_data(plugin, state_iface_uri)
306                 // What some outdated/incorrect ones have
307                 || lilv_plugin_has_feature(plugin, state_uri);
308         lilv_node_free(state_uri);
309         lilv_node_free(state_iface_uri);
310
311         _features    = (LV2_Feature**)calloc(11, sizeof(LV2_Feature*));
312         _features[0] = &_instance_access_feature;
313         _features[1] = &_data_access_feature;
314         _features[2] = &_make_path_feature;
315         _features[3] = _uri_map.uri_map_feature();
316         _features[4] = _uri_map.urid_map_feature();
317         _features[5] = _uri_map.urid_unmap_feature();
318         _features[6] = &_log_feature;
319
320         unsigned n_features = 7;
321 #ifdef HAVE_NEW_LV2
322         _features[n_features++] = &_def_state_feature;
323 #endif
324
325         lv2_atom_forge_init(&_impl->forge, _uri_map.urid_map());
326
327 #ifdef HAVE_NEW_LV2
328         LV2_URID atom_Int = _uri_map.uri_to_id(LV2_ATOM__Int);
329         LV2_Options_Option options[] = {
330                 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__minBlockLength),
331                   sizeof(int32_t), atom_Int, &_block_length },
332                 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__maxBlockLength),
333                   sizeof(int32_t), atom_Int, &_block_length },
334                 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__sequenceSize),
335                   sizeof(int32_t), atom_Int, &_seq_size },
336                 { LV2_OPTIONS_INSTANCE, 0, 0, 0, 0, NULL }
337         };
338
339         _options_feature.URI    = LV2_OPTIONS__options;
340         _options_feature.data   = options;
341         _features[n_features++] = &_options_feature;
342 #endif
343
344         LV2_State_Make_Path* make_path = (LV2_State_Make_Path*)malloc(
345                 sizeof(LV2_State_Make_Path));
346         make_path->handle = this;
347         make_path->path = &lv2_state_make_path;
348         _make_path_feature.data = make_path;
349
350         LV2_Log_Log* log = (LV2_Log_Log*)malloc(sizeof(LV2_Log_Log));
351         log->handle  = this;
352         log->printf  = &log_printf;
353         log->vprintf = &log_vprintf;
354         _log_feature.data = log;
355
356         LilvNode* worker_schedule = lilv_new_uri(_world.world, LV2_WORKER__schedule);
357         if (lilv_plugin_has_feature(plugin, worker_schedule)) {
358                 LV2_Worker_Schedule* schedule = (LV2_Worker_Schedule*)malloc(
359                         sizeof(LV2_Worker_Schedule));
360                 size_t buf_size = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
361                 _worker                     = new Worker(this, buf_size);
362                 schedule->handle            = this;
363                 schedule->schedule_work     = work_schedule;
364                 _work_schedule_feature.data = schedule;
365                 _features[n_features++]     = &_work_schedule_feature;
366         }
367         lilv_node_free(worker_schedule);
368
369         _impl->instance = lilv_plugin_instantiate(plugin, rate, _features);
370         _impl->name     = lilv_plugin_get_name(plugin);
371         _impl->author   = lilv_plugin_get_author_name(plugin);
372
373         if (_impl->instance == 0) {
374                 error << _("LV2: Failed to instantiate plugin ") << uri() << endmsg;
375                 throw failed_constructor();
376         }
377
378         _instance_access_feature.data              = (void*)_impl->instance->lv2_handle;
379         _data_access_extension_data.extension_data = _impl->instance->lv2_descriptor->extension_data;
380         _data_access_feature.data                  = &_data_access_extension_data;
381
382         LilvNode* worker_iface_uri = lilv_new_uri(_world.world, LV2_WORKER__interface);
383         if (lilv_plugin_has_extension_data(plugin, worker_iface_uri)) {
384                 _impl->work_iface = (const LV2_Worker_Interface*)extension_data(
385                         LV2_WORKER__interface);
386         }
387         lilv_node_free(worker_iface_uri);
388
389         if (lilv_plugin_has_feature(plugin, _world.lv2_inPlaceBroken)) {
390                 error << string_compose(
391                     _("LV2: \"%1\" cannot be used, since it cannot do inplace processing"),
392                     lilv_node_as_string(_impl->name)) << endmsg;
393                 lilv_node_free(_impl->name);
394                 lilv_node_free(_impl->author);
395                 throw failed_constructor();
396         }
397
398 #ifdef HAVE_NEW_LILV
399         // Load default state
400         LilvState* state = lilv_state_new_from_world(
401                 _world.world, _uri_map.urid_map(), lilv_plugin_get_uri(_impl->plugin));
402         if (state && _has_state_interface) {
403                 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
404         }
405 #endif
406
407         _sample_rate = rate;
408
409         const uint32_t num_ports = this->num_ports();
410         for (uint32_t i = 0; i < num_ports; ++i) {
411                 const LilvPort* port  = lilv_plugin_get_port_by_index(_impl->plugin, i);
412                 PortFlags       flags = 0;
413                 size_t          minimumSize = 0;
414
415                 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_OutputPort)) {
416                         flags |= PORT_OUTPUT;
417                 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_InputPort)) {
418                         flags |= PORT_INPUT;
419                 } else {
420                         error << string_compose(
421                                 "LV2: \"%1\" port %2 is neither input nor output",
422                                 lilv_node_as_string(_impl->name), i) << endmsg;
423                         throw failed_constructor();
424                 }
425
426                 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_ControlPort)) {
427                         flags |= PORT_CONTROL;
428                 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_AudioPort)) {
429                         flags |= PORT_AUDIO;
430                 } else if (lilv_port_is_a(_impl->plugin, port, _world.ev_EventPort)) {
431                         flags |= PORT_EVENT;
432                         flags |= PORT_MIDI;  // We assume old event API ports are for MIDI
433                 } else if (lilv_port_is_a(_impl->plugin, port, _world.atom_AtomPort)) {
434                         LilvNodes* buffer_types = lilv_port_get_value(
435                                 _impl->plugin, port, _world.atom_bufferType);
436                         LilvNodes* atom_supports = lilv_port_get_value(
437                                 _impl->plugin, port, _world.atom_supports);
438
439                         if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)) {
440                                 flags |= PORT_SEQUENCE;
441                                 if (lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
442                                         flags |= PORT_MIDI;
443                                 }
444                                 if (lilv_nodes_contains(atom_supports, _world.time_Position)) {
445                                         flags |= PORT_POSITION;
446                                 }
447                         }
448                         LilvNode* min_size = lilv_port_get(_impl->plugin, port, _world.rsz_minimumSize);
449                         if (min_size && lilv_node_is_int(min_size)) {
450                                 minimumSize = lilv_node_as_int(min_size);
451                         }
452                         lilv_node_free(min_size);
453                         lilv_nodes_free(buffer_types);
454                         lilv_nodes_free(atom_supports);
455                 } else {
456                         error << string_compose(
457                                 "LV2: \"%1\" port %2 has no known data type",
458                                 lilv_node_as_string(_impl->name), i) << endmsg;
459                         throw failed_constructor();
460                 }
461
462                 _port_flags.push_back(flags);
463                 _port_minimumSize.push_back(minimumSize);
464         }
465
466         _control_data = new float[num_ports];
467         _shadow_data  = new float[num_ports];
468         _defaults     = new float[num_ports];
469         _ev_buffers   = new LV2_Evbuf*[num_ports];
470         memset(_ev_buffers, 0, sizeof(LV2_Evbuf*) * num_ports);
471
472         const bool     latent        = lilv_plugin_has_latency(plugin);
473         const uint32_t latency_index = (latent)
474                 ? lilv_plugin_get_latency_port_index(plugin)
475                 : 0;
476
477         // Build an array of pointers to special parameter buffers
478         void*** params = new void**[num_ports];
479         for (uint32_t i = 0; i < num_ports; ++i) {
480                 params[i] = NULL;
481         }
482         _impl->designated_input (LV2_TIME__beatsPerMinute, params, (void**)&_bpm_control_port);
483         _impl->designated_input (LV2_CORE__freeWheeling, params, (void**)&_freewheel_control_port);
484
485         for (uint32_t i = 0; i < num_ports; ++i) {
486                 const LilvPort* port = lilv_plugin_get_port_by_index(plugin, i);
487                 const LilvNode* sym  = lilv_port_get_symbol(plugin, port);
488
489                 // Store index in map so we can look up index by symbol
490                 _port_indices.insert(std::make_pair(lilv_node_as_string(sym), i));
491
492                 // Get range and default value if applicable
493                 if (parameter_is_control(i)) {
494                         LilvNode* def;
495                         lilv_port_get_range(plugin, port, &def, NULL, NULL);
496                         _defaults[i] = def ? lilv_node_as_float(def) : 0.0f;
497                         if (lilv_port_has_property (plugin, port, _world.lv2_sampleRate)) {
498                                 _defaults[i] *= _session.frame_rate ();
499                         }
500                         lilv_node_free(def);
501
502                         lilv_instance_connect_port(_impl->instance, i, &_control_data[i]);
503
504                         if (latent && i == latency_index) {
505                                 _latency_control_port  = &_control_data[i];
506                                 *_latency_control_port = 0;
507                         }
508
509                         if (parameter_is_input(i)) {
510                                 _shadow_data[i] = default_value(i);
511                                 if (params[i]) {
512                                         *params[i] = (void*)&_shadow_data[i];
513                                 }
514                         }
515                 } else {
516                         _defaults[i] = 0.0f;
517                 }
518         }
519
520         delete[] params;
521
522         LilvUIs* uis = lilv_plugin_get_uis(plugin);
523         if (lilv_uis_size(uis) > 0) {
524 #ifdef HAVE_SUIL
525                 // Look for embeddable UI
526                 LILV_FOREACH(uis, u, uis) {
527                         const LilvUI*   this_ui      = lilv_uis_get(uis, u);
528                         const LilvNode* this_ui_type = NULL;
529                         if (lilv_ui_is_supported(this_ui,
530                                                  suil_ui_supported,
531                                                  _world.ui_GtkUI,
532                                                  &this_ui_type)) {
533                                 // TODO: Multiple UI support
534                                 _impl->ui      = this_ui;
535                                 _impl->ui_type = this_ui_type;
536                                 break;
537                         }
538                 }
539 #else
540                 // Look for Gtk native UI
541                 LILV_FOREACH(uis, i, uis) {
542                         const LilvUI* ui = lilv_uis_get(uis, i);
543                         if (lilv_ui_is_a(ui, _world.ui_GtkUI)) {
544                                 _impl->ui      = ui;
545                                 _impl->ui_type = _world.ui_GtkUI;
546                                 break;
547                         }
548                 }
549 #endif
550
551                 // If Gtk UI is not available, try to find external UI
552                 if (!_impl->ui) {
553                         LILV_FOREACH(uis, i, uis) {
554                                 const LilvUI* ui = lilv_uis_get(uis, i);
555                                 if (lilv_ui_is_a(ui, _world.ui_external)) {
556                                         _impl->ui      = ui;
557                                         _impl->ui_type = _world.ui_external;
558                                         break;
559                                 }
560                         }
561                 }
562         }
563
564         allocate_atom_event_buffers();
565         latency_compute_run();
566 }
567
568 LV2Plugin::~LV2Plugin ()
569 {
570         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 destroy\n", name()));
571
572         deactivate();
573         cleanup();
574
575         lilv_instance_free(_impl->instance);
576         lilv_node_free(_impl->name);
577         lilv_node_free(_impl->author);
578
579         free(_features);
580         free(_make_path_feature.data);
581         free(_work_schedule_feature.data);
582
583         delete _to_ui;
584         delete _from_ui;
585         delete _worker;
586
587         if (_atom_ev_buffers) {
588                 LV2_Evbuf**  b = _atom_ev_buffers;
589                 while (*b) {
590                         free(*b);
591                         b++;
592                 }
593                 free(_atom_ev_buffers);
594         }
595
596         delete [] _control_data;
597         delete [] _shadow_data;
598         delete [] _ev_buffers;
599 }
600
601 bool
602 LV2Plugin::is_external_ui() const
603 {
604         if (!_impl->ui) {
605                 return false;
606         }
607         return lilv_ui_is_a(_impl->ui, _world.ui_external);
608 }
609
610 bool
611 LV2Plugin::ui_is_resizable () const
612 {
613         const LilvNode* s   = lilv_ui_get_uri(_impl->ui);
614         LilvNode*       p   = lilv_new_uri(_world.world, LV2_CORE__optionalFeature);
615         LilvNode*       fs  = lilv_new_uri(_world.world, LV2_UI__fixedSize);
616         LilvNode*       nrs = lilv_new_uri(_world.world, LV2_UI__noUserResize);
617
618         LilvNodes* fs_matches = lilv_world_find_nodes(_world.world, s, p, fs);
619         LilvNodes* nrs_matches = lilv_world_find_nodes(_world.world, s, p, nrs);
620
621         lilv_nodes_free(nrs_matches);
622         lilv_nodes_free(fs_matches);
623         lilv_node_free(nrs);
624         lilv_node_free(fs);
625         lilv_node_free(p);
626
627         return !fs_matches && !nrs_matches;
628 }
629
630 string
631 LV2Plugin::unique_id() const
632 {
633         return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
634 }
635
636 const char*
637 LV2Plugin::uri() const
638 {
639         return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
640 }
641
642 const char*
643 LV2Plugin::label() const
644 {
645         return lilv_node_as_string(_impl->name);
646 }
647
648 const char*
649 LV2Plugin::name() const
650 {
651         return lilv_node_as_string(_impl->name);
652 }
653
654 const char*
655 LV2Plugin::maker() const
656 {
657         return _impl->author ? lilv_node_as_string (_impl->author) : "Unknown";
658 }
659
660 uint32_t
661 LV2Plugin::num_ports() const
662 {
663         return lilv_plugin_get_num_ports(_impl->plugin);
664 }
665
666 uint32_t
667 LV2Plugin::parameter_count() const
668 {
669         return lilv_plugin_get_num_ports(_impl->plugin);
670 }
671
672 float
673 LV2Plugin::default_value(uint32_t port)
674 {
675         return _defaults[port];
676 }
677
678 const char*
679 LV2Plugin::port_symbol(uint32_t index) const
680 {
681         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, index);
682         if (!port) {
683                 error << name() << ": Invalid port index " << index << endmsg;
684         }
685
686         const LilvNode* sym = lilv_port_get_symbol(_impl->plugin, port);
687         return lilv_node_as_string(sym);
688 }
689
690 uint32_t
691 LV2Plugin::port_index (const char* symbol) const
692 {
693         const map<string, uint32_t>::const_iterator i = _port_indices.find(symbol);
694         if (i != _port_indices.end()) {
695                 return  i->second;
696         } else {
697                 warning << string_compose(_("LV2: Unknown port %1"), symbol) << endmsg;
698                 return (uint32_t)-1;
699         }
700 }
701
702 void
703 LV2Plugin::set_parameter(uint32_t which, float val)
704 {
705         DEBUG_TRACE(DEBUG::LV2, string_compose(
706                             "%1 set parameter %2 to %3\n", name(), which, val));
707
708         if (which < lilv_plugin_get_num_ports(_impl->plugin)) {
709                 if (get_parameter (which) == val) {
710                         return;
711                 }
712
713                 _shadow_data[which] = val;
714         } else {
715                 warning << string_compose(
716                     _("Illegal parameter number used with plugin \"%1\". "
717                       "This is a bug in either %2 or the LV2 plugin <%3>"),
718                     name(), PROGRAM_NAME, unique_id()) << endmsg;
719         }
720
721         Plugin::set_parameter(which, val);
722 }
723
724 float
725 LV2Plugin::get_parameter(uint32_t which) const
726 {
727         if (parameter_is_input(which)) {
728                 return (float)_shadow_data[which];
729         } else {
730                 return (float)_control_data[which];
731         }
732         return 0.0f;
733 }
734
735 std::string
736 LV2Plugin::get_docs() const
737 {
738         LilvNodes* comments = lilv_plugin_get_value(_impl->plugin, _world.rdfs_comment);
739         if (comments) {
740                 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
741                 lilv_nodes_free(comments);
742                 return docs;
743         }
744
745         return "";
746 }
747
748 std::string
749 LV2Plugin::get_parameter_docs(uint32_t which) const
750 {
751         LilvNodes* comments = lilv_port_get_value(
752                 _impl->plugin,
753                 lilv_plugin_get_port_by_index(_impl->plugin, which),
754                 _world.rdfs_comment);
755
756         if (comments) {
757                 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
758                 lilv_nodes_free(comments);
759                 return docs;
760         }
761
762         return "";
763 }
764
765 uint32_t
766 LV2Plugin::nth_parameter(uint32_t n, bool& ok) const
767 {
768         ok = false;
769         for (uint32_t c = 0, x = 0; x < lilv_plugin_get_num_ports(_impl->plugin); ++x) {
770                 if (parameter_is_control(x)) {
771                         if (c++ == n) {
772                                 ok = true;
773                                 return x;
774                         }
775                 }
776         }
777
778         return 0;
779 }
780
781 const void*
782 LV2Plugin::extension_data(const char* uri) const
783 {
784         return lilv_instance_get_extension_data(_impl->instance, uri);
785 }
786
787 const void*
788 LV2Plugin::c_plugin()
789 {
790         return _impl->plugin;
791 }
792
793 const void*
794 LV2Plugin::c_ui()
795 {
796         return (const void*)_impl->ui;
797 }
798
799 const void*
800 LV2Plugin::c_ui_type()
801 {
802         return (const void*)_impl->ui_type;
803 }
804
805 /** Directory for all plugin state. */
806 const std::string
807 LV2Plugin::plugin_dir() const
808 {
809         return Glib::build_filename(_session.plugins_dir(), _insert_id.to_s());
810 }
811
812 /** Directory for files created by the plugin (except during save). */
813 const std::string
814 LV2Plugin::scratch_dir() const
815 {
816         return Glib::build_filename(plugin_dir(), "scratch");
817 }
818
819 /** Directory for snapshots of files in the scratch directory. */
820 const std::string
821 LV2Plugin::file_dir() const
822 {
823         return Glib::build_filename(plugin_dir(), "files");
824 }
825
826 /** Directory to save state snapshot version @c num into. */
827 const std::string
828 LV2Plugin::state_dir(unsigned num) const
829 {
830         return Glib::build_filename(plugin_dir(), string_compose("state%1", num));
831 }
832
833 /** Implementation of state:makePath for files created at instantiation time.
834  * Note this is not used for files created at save time (Lilv deals with that).
835  */
836 char*
837 LV2Plugin::lv2_state_make_path(LV2_State_Make_Path_Handle handle,
838                                const char*                path)
839 {
840         LV2Plugin* me = (LV2Plugin*)handle;
841         if (me->_insert_id == PBD::ID("0")) {
842                 warning << string_compose(
843                         "File path \"%1\" requested but LV2 %2 has no insert ID",
844                         path, me->name()) << endmsg;
845                 return g_strdup(path);
846         }
847
848         const std::string abs_path = Glib::build_filename(me->scratch_dir(), path);
849         const std::string dirname  = Glib::path_get_dirname(abs_path);
850         g_mkdir_with_parents(dirname.c_str(), 0744);
851
852         DEBUG_TRACE(DEBUG::LV2, string_compose("new file path %1 => %2\n",
853                                                path, abs_path));
854
855         return g_strndup(abs_path.c_str(), abs_path.length());
856 }
857
858 static void
859 remove_directory(const std::string& path)
860 {
861         if (!Glib::file_test(path, Glib::FILE_TEST_IS_DIR)) {
862                 warning << string_compose("\"%1\" is not a directory", path) << endmsg;
863                 return;
864         }
865
866         Glib::RefPtr<Gio::File>           dir = Gio::File::create_for_path(path);
867         Glib::RefPtr<Gio::FileEnumerator> e   = dir->enumerate_children();
868         Glib::RefPtr<Gio::FileInfo>       fi;
869         while ((fi = e->next_file())) {
870                 if (fi->get_type() == Gio::FILE_TYPE_DIRECTORY) {
871                         remove_directory(fi->get_name());
872                 } else {
873                         dir->get_child(fi->get_name())->remove();
874                 }
875         }
876         dir->remove();
877 }
878
879 void
880 LV2Plugin::add_state(XMLNode* root) const
881 {
882         assert(_insert_id != PBD::ID("0"));
883
884         XMLNode*    child;
885         char        buf[16];
886         LocaleGuard lg(X_("POSIX"));
887
888         for (uint32_t i = 0; i < parameter_count(); ++i) {
889                 if (parameter_is_input(i) && parameter_is_control(i)) {
890                         child = new XMLNode("Port");
891                         child->add_property("symbol", port_symbol(i));
892                         snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
893                         child->add_property("value", string(buf));
894                         root->add_child_nocopy(*child);
895                 }
896         }
897
898         if (_has_state_interface) {
899                 // Provisionally increment state version and create directory
900                 const std::string new_dir = state_dir(++_state_version);
901                 g_mkdir_with_parents(new_dir.c_str(), 0744);
902
903                 LilvState* state = lilv_state_new_from_instance(
904                         _impl->plugin,
905                         _impl->instance,
906                         _uri_map.urid_map(),
907                         scratch_dir().c_str(),
908                         file_dir().c_str(),
909                         _session.externals_dir().c_str(),
910                         new_dir.c_str(),
911                         NULL,
912                         const_cast<LV2Plugin*>(this),
913                         0,
914                         NULL);
915
916                 if (!_impl->state || !lilv_state_equals(state, _impl->state)) {
917                         lilv_state_save(_world.world,
918                                         _uri_map.urid_map(),
919                                         _uri_map.urid_unmap(),
920                                         state,
921                                         NULL,
922                                         new_dir.c_str(),
923                                         "state.ttl");
924
925                         lilv_state_free(_impl->state);
926                         _impl->state = state;
927                 } else {
928                         // State is identical, decrement version and nuke directory
929                         lilv_state_free(state);
930                         remove_directory(new_dir);
931                         --_state_version;
932                 }
933
934                 root->add_property("state-dir", string_compose("state%1", _state_version));
935         }
936 }
937
938 static inline const LilvNode*
939 get_value(LilvWorld* world, const LilvNode* subject, const LilvNode* predicate)
940 {
941         LilvNodes* vs = lilv_world_find_nodes(world, subject, predicate, NULL);
942         return vs ? lilv_nodes_get_first(vs) : NULL;
943 }
944
945 void
946 LV2Plugin::find_presets()
947 {
948         LilvNode* lv2_appliesTo = lilv_new_uri(_world.world, LV2_CORE__appliesTo);
949         LilvNode* pset_Preset   = lilv_new_uri(_world.world, LV2_PRESETS__Preset);
950         LilvNode* rdfs_label    = lilv_new_uri(_world.world, LILV_NS_RDFS "label");
951
952         LilvNodes* presets = lilv_plugin_get_related(_impl->plugin, pset_Preset);
953         LILV_FOREACH(nodes, i, presets) {
954                 const LilvNode* preset = lilv_nodes_get(presets, i);
955                 lilv_world_load_resource(_world.world, preset);
956                 const LilvNode* name = get_value(_world.world, preset, rdfs_label);
957                 if (name) {
958                         _presets.insert(std::make_pair(lilv_node_as_string(preset),
959                                                        Plugin::PresetRecord(
960                                                                lilv_node_as_string(preset),
961                                                                lilv_node_as_string(name))));
962                 } else {
963                         warning << string_compose(
964                             _("Plugin \"%1\% preset \"%2%\" is missing a label\n"),
965                             lilv_node_as_string(lilv_plugin_get_uri(_impl->plugin)),
966                             lilv_node_as_string(preset)) << endmsg;
967                 }
968         }
969         lilv_nodes_free(presets);
970
971         lilv_node_free(rdfs_label);
972         lilv_node_free(pset_Preset);
973         lilv_node_free(lv2_appliesTo);
974 }
975
976 static void
977 set_port_value(const char* port_symbol,
978                void*       user_data,
979                const void* value,
980                uint32_t    /*size*/,
981                uint32_t    type)
982 {
983         LV2Plugin* self = (LV2Plugin*)user_data;
984         if (type != 0 && type != self->_uri_map.uri_to_id(LV2_ATOM__Float)) {
985                 return;  // TODO: Support non-float ports
986         }
987
988         const uint32_t port_index = self->port_index(port_symbol);
989         if (port_index != (uint32_t)-1) {
990                 self->set_parameter(port_index, *(const float*)value);
991         }
992 }
993
994 bool
995 LV2Plugin::load_preset(PresetRecord r)
996 {
997         LilvWorld* world = _world.world;
998         LilvNode*  pset  = lilv_new_uri(world, r.uri.c_str());
999         LilvState* state = lilv_state_new_from_world(world, _uri_map.urid_map(), pset);
1000
1001         if (state) {
1002                 lilv_state_restore(state, _impl->instance, set_port_value, this, 0, NULL);
1003                 lilv_state_free(state);
1004         }
1005
1006         lilv_node_free(pset);
1007         return state;
1008 }
1009
1010 const void*
1011 ARDOUR::lv2plugin_get_port_value(const char* port_symbol,
1012                                  void*       user_data,
1013                                  uint32_t*   size,
1014                                  uint32_t*   type)
1015 {
1016         LV2Plugin *plugin = (LV2Plugin *) user_data;
1017
1018         uint32_t index = plugin->port_index(port_symbol);
1019         if (index != (uint32_t) -1) {
1020                 if (plugin->parameter_is_input(index) && plugin->parameter_is_control(index)) {
1021                         float *value;
1022                         *size = sizeof(float);
1023                         *type = plugin->_uri_map.uri_to_id(LV2_ATOM__Float);
1024                         value = &plugin->_shadow_data[index];
1025
1026                         return value;
1027                 }
1028         }
1029
1030         *size = *type = 0;
1031         return NULL;
1032 }
1033
1034
1035 std::string
1036 LV2Plugin::do_save_preset(string name)
1037 {
1038         const string base_name = legalize_for_uri(name);
1039         const string file_name = base_name + ".ttl";
1040         const string bundle    = Glib::build_filename(
1041                 Glib::get_home_dir(),
1042                 Glib::build_filename(".lv2", base_name + ".lv2"));
1043
1044         LilvState* state = lilv_state_new_from_instance(
1045                 _impl->plugin,
1046                 _impl->instance,
1047                 _uri_map.urid_map(),
1048                 scratch_dir().c_str(),                   // file_dir
1049                 bundle.c_str(),                          // copy_dir
1050                 bundle.c_str(),                          // link_dir
1051                 bundle.c_str(),                          // save_dir
1052                 lv2plugin_get_port_value,                // get_value
1053                 (void*)this,                             // user_data
1054                 LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE,  // flags
1055                 _features                                // features
1056         );
1057
1058         lilv_state_set_label(state, name.c_str());
1059         lilv_state_save(
1060                 _world.world,           // world
1061                 _uri_map.urid_map(),    // map
1062                 _uri_map.urid_unmap(),  // unmap
1063                 state,                  // state
1064                 NULL,                   // uri (NULL = use file URI)
1065                 bundle.c_str(),         // dir
1066                 file_name.c_str()       // filename
1067         );
1068
1069         lilv_state_free(state);
1070
1071         return Glib::filename_to_uri(Glib::build_filename(bundle, file_name));
1072 }
1073
1074 void
1075 LV2Plugin::do_remove_preset(string name)
1076 {
1077         string preset_file = Glib::build_filename(
1078                 Glib::get_home_dir(),
1079                 Glib::build_filename(
1080                         Glib::build_filename(".lv2", "presets"),
1081                         name + ".ttl"
1082                 )
1083         );
1084         unlink(preset_file.c_str());
1085 }
1086
1087 bool
1088 LV2Plugin::has_editor() const
1089 {
1090         return _impl->ui != NULL;
1091 }
1092
1093 bool
1094 LV2Plugin::has_message_output() const
1095 {
1096         for (uint32_t i = 0; i < num_ports(); ++i) {
1097                 if ((_port_flags[i] & PORT_SEQUENCE) &&
1098                     (_port_flags[i] & PORT_OUTPUT)) {
1099                         return true;
1100                 }
1101         }
1102         return false;
1103 }
1104
1105 bool
1106 LV2Plugin::write_to(RingBuffer<uint8_t>* dest,
1107                     uint32_t             index,
1108                     uint32_t             protocol,
1109                     uint32_t             size,
1110                     const uint8_t*       body)
1111 {
1112         const uint32_t buf_size = sizeof(UIMessage) + size;
1113         uint8_t        buf[buf_size];
1114
1115         UIMessage* msg = (UIMessage*)buf;
1116         msg->index    = index;
1117         msg->protocol = protocol;
1118         msg->size     = size;
1119         memcpy(msg + 1, body, size);
1120
1121         return (dest->write(buf, buf_size) == buf_size);
1122 }
1123
1124 bool
1125 LV2Plugin::write_from_ui(uint32_t       index,
1126                          uint32_t       protocol,
1127                          uint32_t       size,
1128                          const uint8_t* body)
1129 {
1130         if (!_from_ui) {
1131                 _from_ui = new RingBuffer<uint8_t>(
1132                         _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS);
1133         }
1134
1135         if (!write_to(_from_ui, index, protocol, size, body)) {
1136                 error << "Error writing from UI to plugin" << endmsg;
1137                 return false;
1138         }
1139         return true;
1140 }
1141
1142 bool
1143 LV2Plugin::write_to_ui(uint32_t       index,
1144                        uint32_t       protocol,
1145                        uint32_t       size,
1146                        const uint8_t* body)
1147 {
1148         if (!write_to(_to_ui, index, protocol, size, body)) {
1149                 error << "Error writing from plugin to UI" << endmsg;
1150                 return false;
1151         }
1152         return true;
1153 }
1154
1155 void
1156 LV2Plugin::enable_ui_emmission()
1157 {
1158         if (!_to_ui) {
1159                 _to_ui = new RingBuffer<uint8_t>(
1160                         _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS);
1161         }
1162 }
1163
1164 void
1165 LV2Plugin::emit_to_ui(void* controller, UIMessageSink sink)
1166 {
1167         if (!_to_ui) {
1168                 return;
1169         }
1170
1171         uint32_t read_space = _to_ui->read_space();
1172         while (read_space > sizeof(UIMessage)) {
1173                 UIMessage msg;
1174                 if (_to_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1175                         error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1176                         break;
1177                 }
1178                 uint8_t body[msg.size];
1179                 if (_to_ui->read(body, msg.size) != msg.size) {
1180                         error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1181                         break;
1182                 }
1183
1184                 sink(controller, msg.index, msg.size, msg.protocol, body);
1185
1186                 read_space -= sizeof(msg) + msg.size;
1187         }
1188 }
1189
1190 int
1191 LV2Plugin::work(uint32_t size, const void* data)
1192 {
1193         return _impl->work_iface->work(
1194                 _impl->instance->lv2_handle, work_respond, this, size, data);
1195 }
1196
1197 int
1198 LV2Plugin::work_response(uint32_t size, const void* data)
1199 {
1200         return _impl->work_iface->work_response(
1201                 _impl->instance->lv2_handle, size, data);
1202 }
1203
1204 void
1205 LV2Plugin::set_insert_info(const PluginInsert* insert)
1206 {
1207         _insert_id = insert->id();
1208 }
1209
1210 int
1211 LV2Plugin::set_state(const XMLNode& node, int version)
1212 {
1213         XMLNodeList          nodes;
1214         const XMLProperty*   prop;
1215         XMLNodeConstIterator iter;
1216         XMLNode*             child;
1217         const char*          sym;
1218         const char*          value;
1219         uint32_t             port_id;
1220         LocaleGuard          lg(X_("POSIX"));
1221
1222         if (node.name() != state_node_name()) {
1223                 error << _("Bad node sent to LV2Plugin::set_state") << endmsg;
1224                 return -1;
1225         }
1226
1227         if (version < 3000) {
1228                 nodes = node.children("port");
1229         } else {
1230                 nodes = node.children("Port");
1231         }
1232
1233         for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
1234
1235                 child = *iter;
1236
1237                 if ((prop = child->property("symbol")) != 0) {
1238                         sym = prop->value().c_str();
1239                 } else {
1240                         warning << _("LV2: port has no symbol, ignored") << endmsg;
1241                         continue;
1242                 }
1243
1244                 map<string, uint32_t>::iterator i = _port_indices.find(sym);
1245
1246                 if (i != _port_indices.end()) {
1247                         port_id = i->second;
1248                 } else {
1249                         warning << _("LV2: port has unknown index, ignored") << endmsg;
1250                         continue;
1251                 }
1252
1253                 if ((prop = child->property("value")) != 0) {
1254                         value = prop->value().c_str();
1255                 } else {
1256                         warning << _("LV2: port has no value, ignored") << endmsg;
1257                         continue;
1258                 }
1259
1260                 set_parameter(port_id, atof(value));
1261         }
1262
1263         _state_version = 0;
1264         if ((prop = node.property("state-dir")) != 0) {
1265                 if (sscanf(prop->value().c_str(), "state%u", &_state_version) != 1) {
1266                         error << string_compose(
1267                                 "LV2: failed to parse state version from \"%1\"",
1268                                 prop->value()) << endmsg;
1269                 }
1270
1271                 std::string state_file = Glib::build_filename(
1272                         plugin_dir(),
1273                         Glib::build_filename(prop->value(), "state.ttl"));
1274
1275                 LilvState* state = lilv_state_new_from_file(
1276                         _world.world, _uri_map.urid_map(), NULL, state_file.c_str());
1277
1278                 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
1279         }
1280
1281         latency_compute_run();
1282
1283         return Plugin::set_state(node, version);
1284 }
1285
1286 int
1287 LV2Plugin::get_parameter_descriptor(uint32_t which, ParameterDescriptor& desc) const
1288 {
1289         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, which);
1290
1291         LilvNode *def, *min, *max;
1292         lilv_port_get_range(_impl->plugin, port, &def, &min, &max);
1293
1294         desc.integer_step = lilv_port_has_property(_impl->plugin, port, _world.lv2_integer);
1295         desc.toggled      = lilv_port_has_property(_impl->plugin, port, _world.lv2_toggled);
1296         desc.logarithmic  = lilv_port_has_property(_impl->plugin, port, _world.ext_logarithmic);
1297         desc.sr_dependent = lilv_port_has_property(_impl->plugin, port, _world.lv2_sampleRate);
1298         desc.label        = lilv_node_as_string(lilv_port_get_name(_impl->plugin, port));
1299         desc.lower        = min ? lilv_node_as_float(min) : 0.0f;
1300         desc.upper        = max ? lilv_node_as_float(max) : 1.0f;
1301         if (desc.sr_dependent) {
1302                 desc.lower *= _session.frame_rate ();
1303                 desc.upper *= _session.frame_rate ();
1304         }
1305
1306         desc.min_unbound  = false; // TODO: LV2 extension required
1307         desc.max_unbound  = false; // TODO: LV2 extension required
1308
1309         if (desc.integer_step) {
1310                 desc.step      = 1.0;
1311                 desc.smallstep = 0.1;
1312                 desc.largestep = 10.0;
1313         } else {
1314                 const float delta = desc.upper - desc.lower;
1315                 desc.step      = delta / 1000.0f;
1316                 desc.smallstep = delta / 10000.0f;
1317                 desc.largestep = delta / 10.0f;
1318         }
1319
1320         desc.enumeration = lilv_port_has_property(_impl->plugin, port, _world.lv2_enumeration);
1321
1322         lilv_node_free(def);
1323         lilv_node_free(min);
1324         lilv_node_free(max);
1325
1326         return 0;
1327 }
1328
1329 string
1330 LV2Plugin::describe_parameter(Evoral::Parameter which)
1331 {
1332         if (( which.type() == PluginAutomation) && ( which.id() < parameter_count()) ) {
1333
1334                 if (lilv_port_has_property(_impl->plugin,
1335                                         lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.ext_notOnGUI)) {
1336                         return X_("hidden");
1337                 }
1338                 if (lilv_port_has_property(_impl->plugin,
1339                                         lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_reportsLatency)) {
1340                         return X_("latency");
1341                 }
1342
1343                 LilvNode* name = lilv_port_get_name(_impl->plugin,
1344                                                     lilv_plugin_get_port_by_index(_impl->plugin, which.id()));
1345                 string ret(lilv_node_as_string(name));
1346                 lilv_node_free(name);
1347                 return ret;
1348         } else {
1349                 return "??";
1350         }
1351 }
1352
1353 framecnt_t
1354 LV2Plugin::signal_latency() const
1355 {
1356         if (_latency_control_port) {
1357                 return (framecnt_t)floor(*_latency_control_port);
1358         } else {
1359                 return 0;
1360         }
1361 }
1362
1363 set<Evoral::Parameter>
1364 LV2Plugin::automatable() const
1365 {
1366         set<Evoral::Parameter> ret;
1367
1368         for (uint32_t i = 0; i < parameter_count(); ++i) {
1369                 if (parameter_is_input(i) && parameter_is_control(i)) {
1370                         ret.insert(ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
1371                 }
1372         }
1373
1374         return ret;
1375 }
1376
1377 void
1378 LV2Plugin::activate()
1379 {
1380         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 activate\n", name()));
1381
1382         if (!_was_activated) {
1383                 lilv_instance_activate(_impl->instance);
1384                 _was_activated = true;
1385         }
1386 }
1387
1388 void
1389 LV2Plugin::deactivate()
1390 {
1391         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 deactivate\n", name()));
1392
1393         if (_was_activated) {
1394                 lilv_instance_deactivate(_impl->instance);
1395                 _was_activated = false;
1396         }
1397 }
1398
1399 void
1400 LV2Plugin::cleanup()
1401 {
1402         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 cleanup\n", name()));
1403
1404         activate();
1405         deactivate();
1406         lilv_instance_free(_impl->instance);
1407         _impl->instance = NULL;
1408 }
1409
1410 void
1411 LV2Plugin::allocate_atom_event_buffers()
1412 {
1413         /* reserve local scratch buffers for ATOM event-queues */
1414         const LilvPlugin* p = _impl->plugin;
1415
1416         /* count non-MIDI atom event-ports
1417          * TODO: nicely ask drobilla to make a lilv_ call for that
1418          */
1419         int count_atom_out = 0;
1420         int count_atom_in = 0;
1421         int minimumSize = 32768; // TODO use a per-port minimum-size
1422         for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
1423                 const LilvPort* port  = lilv_plugin_get_port_by_index(p, i);
1424                 if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
1425                         LilvNodes* buffer_types = lilv_port_get_value(
1426                                 p, port, _world.atom_bufferType);
1427                         LilvNodes* atom_supports = lilv_port_get_value(
1428                                 p, port, _world.atom_supports);
1429
1430                         if (!lilv_nodes_contains(buffer_types, _world.atom_Sequence)
1431                                         || !lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
1432                                 if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
1433                                         count_atom_in++;
1434                                 }
1435                                 if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
1436                                         count_atom_out++;
1437                                 }
1438                                 LilvNode* min_size = lilv_port_get(_impl->plugin, port, _world.rsz_minimumSize);
1439                                 if (min_size && lilv_node_is_int(min_size)) {
1440                                         minimumSize = std::max(minimumSize, lilv_node_as_int(min_size));
1441                                 }
1442                         }
1443                         lilv_nodes_free(buffer_types);
1444                         lilv_nodes_free(atom_supports);
1445                 }
1446         }
1447
1448         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 need buffers for %2 atom-in and %3 atom-out event-ports\n",
1449                                 name(), count_atom_in, count_atom_out));
1450
1451         const int total_atom_buffers = (count_atom_in + count_atom_out);
1452         if (_atom_ev_buffers || total_atom_buffers == 0) {
1453                 return;
1454         }
1455
1456         DEBUG_TRACE(DEBUG::LV2, string_compose("allocate %1 atom_ev_buffers\n", total_atom_buffers));
1457         _atom_ev_buffers = (LV2_Evbuf**) malloc((total_atom_buffers + 1) * sizeof(LV2_Evbuf*));
1458         for (int i = 0; i < total_atom_buffers; ++i ) {
1459                 _atom_ev_buffers[i] = lv2_evbuf_new(minimumSize, LV2_EVBUF_ATOM,
1460                                 LV2Plugin::urids.atom_Chunk, LV2Plugin::urids.atom_Sequence);
1461         }
1462         _atom_ev_buffers[total_atom_buffers] = 0;
1463         return;
1464 }
1465
1466 /** Write an ardour position/time/tempo/meter as an LV2 event.
1467  * @return true on success.
1468  */
1469 static bool
1470 write_position(LV2_Atom_Forge*     forge,
1471                LV2_Evbuf*          buf,
1472                const TempoMetric&  t,
1473                Timecode::BBT_Time& bbt,
1474                double              speed,
1475                framepos_t          position,
1476                framecnt_t          offset)
1477 {
1478         uint8_t pos_buf[256];
1479         lv2_atom_forge_set_buffer(forge, pos_buf, sizeof(pos_buf));
1480         LV2_Atom_Forge_Frame frame;
1481         lv2_atom_forge_blank(forge, &frame, 1, LV2Plugin::urids.time_Position);
1482         lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_frame, 0);
1483         lv2_atom_forge_long(forge, position);
1484         lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_speed, 0);
1485         lv2_atom_forge_float(forge, speed);
1486         lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_barBeat, 0);
1487         lv2_atom_forge_float(forge, bbt.beats - 1 +
1488                              (bbt.ticks / Timecode::BBT_Time::ticks_per_beat));
1489         lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_bar, 0);
1490         lv2_atom_forge_long(forge, bbt.bars - 1);
1491         lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_beatUnit, 0);
1492         lv2_atom_forge_int(forge, t.meter().note_divisor());
1493         lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_beatsPerBar, 0);
1494         lv2_atom_forge_float(forge, t.meter().divisions_per_bar());
1495         lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_beatsPerMinute, 0);
1496         lv2_atom_forge_float(forge, t.tempo().beats_per_minute());
1497
1498         LV2_Evbuf_Iterator    end  = lv2_evbuf_end(buf);
1499         const LV2_Atom* const atom = (const LV2_Atom*)pos_buf;
1500         return lv2_evbuf_write(&end, offset, 0, atom->type, atom->size,
1501                                (const uint8_t*)(atom + 1));
1502 }
1503
1504 int
1505 LV2Plugin::connect_and_run(BufferSet& bufs,
1506         ChanMapping in_map, ChanMapping out_map,
1507         pframes_t nframes, framecnt_t offset)
1508 {
1509         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 run %2 offset %3\n", name(), nframes, offset));
1510         Plugin::connect_and_run(bufs, in_map, out_map, nframes, offset);
1511
1512         cycles_t then = get_cycles();
1513
1514         TempoMap&               tmap     = _session.tempo_map();
1515         Metrics::const_iterator metric_i = tmap.metrics_end();
1516         TempoMetric             tmetric  = tmap.metric_at(_session.transport_frame(), &metric_i);
1517
1518         if (_freewheel_control_port) {
1519                 *_freewheel_control_port = _session.engine().freewheeling();
1520         }
1521
1522         if (_bpm_control_port) {
1523                 *_bpm_control_port = tmetric.tempo().beats_per_minute();
1524         }
1525
1526         ChanCount bufs_count;
1527         bufs_count.set(DataType::AUDIO, 1);
1528         bufs_count.set(DataType::MIDI, 1);
1529         BufferSet& silent_bufs  = _session.get_silent_buffers(bufs_count);
1530         BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
1531         uint32_t const num_ports = parameter_count();
1532         uint32_t const nil_index = std::numeric_limits<uint32_t>::max();
1533
1534         uint32_t audio_in_index  = 0;
1535         uint32_t audio_out_index = 0;
1536         uint32_t midi_in_index   = 0;
1537         uint32_t midi_out_index  = 0;
1538         uint32_t atom_port_index = 0;
1539         for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
1540                 void*     buf   = NULL;
1541                 uint32_t  index = nil_index;
1542                 PortFlags flags = _port_flags[port_index];
1543                 bool      valid = false;
1544                 if (flags & PORT_AUDIO) {
1545                         if (flags & PORT_INPUT) {
1546                                 index = in_map.get(DataType::AUDIO, audio_in_index++, &valid);
1547                                 buf = (valid)
1548                                         ? bufs.get_audio(index).data(offset)
1549                                         : silent_bufs.get_audio(0).data(offset);
1550                         } else {
1551                                 index = out_map.get(DataType::AUDIO, audio_out_index++, &valid);
1552                                 buf = (valid)
1553                                         ? bufs.get_audio(index).data(offset)
1554                                         : scratch_bufs.get_audio(0).data(offset);
1555                         }
1556                 } else if (flags & (PORT_EVENT|PORT_SEQUENCE)) {
1557                         /* FIXME: The checks here for bufs.count().n_midi() > index shouldn't
1558                            be necessary, but the mapping is illegal in some cases.  Ideally
1559                            that should be fixed, but this is easier...
1560                         */
1561                         if (flags & PORT_MIDI) {
1562                                 if (flags & PORT_INPUT) {
1563                                         index = in_map.get(DataType::MIDI, midi_in_index++, &valid);
1564                                 } else {
1565                                         index = out_map.get(DataType::MIDI, midi_out_index++, &valid);
1566                                 }
1567                                 if (valid && bufs.count().n_midi() > index) {
1568                                         /* Note, ensure_lv2_bufsize() is not RT safe!
1569                                          * However free()/alloc() is only called if a
1570                                          * plugin requires a rsz:minimumSize buffersize
1571                                          * and the existing buffer if smaller.
1572                                          */
1573                                         bufs.ensure_lv2_bufsize((flags & PORT_INPUT), index, _port_minimumSize[port_index]);
1574                                         _ev_buffers[port_index] = bufs.get_lv2_midi(
1575                                                 (flags & PORT_INPUT), index, (flags & PORT_EVENT));
1576                                 }
1577                         } else if ((flags & PORT_POSITION) && (flags & PORT_INPUT)) {
1578                                 lv2_evbuf_reset(_atom_ev_buffers[atom_port_index], true);
1579                                 _ev_buffers[port_index] = _atom_ev_buffers[atom_port_index++];
1580                                 valid                   = true;
1581                         }
1582
1583                         if (valid && (flags & PORT_INPUT)) {
1584                                 Timecode::BBT_Time bbt;
1585                                 if ((flags & PORT_POSITION)) {
1586                                         if (_session.transport_frame() != _next_cycle_start ||
1587                                             _session.transport_speed() != _next_cycle_speed) {
1588                                                 // Transport has changed, write position at cycle start
1589                                                 tmap.bbt_time(_session.transport_frame(), bbt);
1590                                                 write_position(&_impl->forge, _ev_buffers[port_index],
1591                                                                tmetric, bbt, _session.transport_speed(),
1592                                                                _session.transport_frame(), 0);
1593                                         }
1594                                 }
1595
1596                                 // Get MIDI iterator range (empty range if no MIDI)
1597                                 MidiBuffer::iterator m = (index != nil_index)
1598                                         ? bufs.get_midi(index).begin()
1599                                         : silent_bufs.get_midi(0).end();
1600                                 MidiBuffer::iterator m_end = (index != nil_index)
1601                                         ? bufs.get_midi(index).end()
1602                                         : m;
1603
1604                                 // Now merge MIDI and any transport events into the buffer
1605                                 const uint32_t     type = LV2Plugin::urids.midi_MidiEvent;
1606                                 const framepos_t   tend = _session.transport_frame() + nframes;
1607                                 ++metric_i;
1608                                 while (m != m_end || (metric_i != tmap.metrics_end() &&
1609                                                       (*metric_i)->frame() < tend)) {
1610                                         MetricSection* metric = (metric_i != tmap.metrics_end())
1611                                                 ? *metric_i : NULL;
1612                                         if (m != m_end && (!metric || metric->frame() > (*m).time())) {
1613                                                 const Evoral::MIDIEvent<framepos_t> ev(*m, false);
1614                                                 LV2_Evbuf_Iterator eend = lv2_evbuf_end(_ev_buffers[port_index]);
1615                                                 lv2_evbuf_write(&eend, ev.time(), 0, type, ev.size(), ev.buffer());
1616                                                 ++m;
1617                                         } else {
1618                                                 tmetric.set_metric(metric);
1619                                                 bbt = metric->start();
1620                                                 write_position(&_impl->forge, _ev_buffers[port_index],
1621                                                                tmetric, bbt, _session.transport_speed(),
1622                                                                metric->frame(),
1623                                                                metric->frame() - _session.transport_frame());
1624                                                 ++metric_i;
1625                                         }
1626                                 }
1627                         } else if (!valid) {
1628                                 // Nothing we understand or care about, connect to scratch
1629                                 _ev_buffers[port_index] = silent_bufs.get_lv2_midi(
1630                                         (flags & PORT_INPUT), 0, (flags & PORT_EVENT));
1631                         }
1632                         buf = lv2_evbuf_get_buffer(_ev_buffers[port_index]);
1633                 } else {
1634                         continue;  // Control port, leave buffer alone
1635                 }
1636                 lilv_instance_connect_port(_impl->instance, port_index, buf);
1637         }
1638
1639         // Read messages from UI and push into appropriate buffers
1640         if (_from_ui) {
1641                 uint32_t read_space = _from_ui->read_space();
1642                 while (read_space > sizeof(UIMessage)) {
1643                         UIMessage msg;
1644                         if (_from_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1645                                 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
1646                                 break;
1647                         }
1648                         uint8_t body[msg.size];
1649                         if (_from_ui->read(body, msg.size) != msg.size) {
1650                                 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
1651                                 break;
1652                         }
1653                         if (msg.protocol == urids.atom_eventTransfer) {
1654                                 LV2_Evbuf*            buf  = _ev_buffers[msg.index];
1655                                 LV2_Evbuf_Iterator    i    = lv2_evbuf_end(buf);
1656                                 const LV2_Atom* const atom = (const LV2_Atom*)body;
1657                                 if (!lv2_evbuf_write(&i, nframes, 0, atom->type, atom->size,
1658                                                 (const uint8_t*)(atom + 1))) {
1659                                         error << "Failed to write data to LV2 event buffer\n";
1660                                 }
1661                         } else {
1662                                 error << "Received unknown message type from UI" << endmsg;
1663                         }
1664                         read_space -= sizeof(UIMessage) + msg.size;
1665                 }
1666         }
1667
1668         run(nframes);
1669
1670         midi_out_index = 0;
1671         for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
1672                 PortFlags flags = _port_flags[port_index];
1673                 bool      valid = false;
1674
1675                 /* TODO ask drobilla about comment
1676                  * "Make Ardour event buffers generic so plugins can communicate"
1677                  * in libs/ardour/buffer_set.cc:310
1678                  *
1679                  * ideally the user could choose which of the following two modes
1680                  * to use (e.g. instrument/effect chains  MIDI OUT vs MIDI TRHU).
1681                  *
1682                  * This implementation follows the discussion on IRC Mar 16 2013 16:47 UTC
1683                  * 16:51 < drobilla> rgareus: [..] i.e always replace with MIDI output [of LV2 plugin] if it's there
1684                  * 16:52 < drobilla> rgareus: That would probably be good enough [..] to make users not complain
1685                  *                            for quite a while at least ;)
1686                  */
1687                 // copy output of LV2 plugin's MIDI port to Ardour MIDI buffers -- MIDI OUT
1688                 if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE|PORT_MIDI))) {
1689                         const uint32_t buf_index = out_map.get(
1690                                 DataType::MIDI, midi_out_index++, &valid);
1691                         if (valid) {
1692                                 bufs.forward_lv2_midi(_ev_buffers[port_index], buf_index);
1693                         }
1694                 }
1695                 // Flush MIDI (write back to Ardour MIDI buffers) -- MIDI THRU
1696                 else if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
1697                         const uint32_t buf_index = out_map.get(
1698                                 DataType::MIDI, midi_out_index++, &valid);
1699                         if (valid) {
1700                                 bufs.flush_lv2_midi(true, buf_index);
1701                         }
1702                 }
1703
1704                 // Write messages to UI
1705                 if (_to_ui && (flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
1706                         LV2_Evbuf* buf = _ev_buffers[port_index];
1707                         for (LV2_Evbuf_Iterator i = lv2_evbuf_begin(buf);
1708                              lv2_evbuf_is_valid(i);
1709                              i = lv2_evbuf_next(i)) {
1710                                 uint32_t frames, subframes, type, size;
1711                                 uint8_t* data;
1712                                 lv2_evbuf_get(i, &frames, &subframes, &type, &size, &data);
1713                                 write_to_ui(port_index, urids.atom_eventTransfer,
1714                                             size + sizeof(LV2_Atom),
1715                                             data - sizeof(LV2_Atom));
1716                         }
1717                 }
1718         }
1719
1720         cycles_t now = get_cycles();
1721         set_cycles((uint32_t)(now - then));
1722
1723         // Update expected transport information for next cycle so we can detect changes
1724         _next_cycle_speed = _session.transport_speed();
1725         _next_cycle_start = _session.transport_frame() + (nframes * _next_cycle_speed);
1726
1727         return 0;
1728 }
1729
1730 bool
1731 LV2Plugin::parameter_is_control(uint32_t param) const
1732 {
1733         assert(param < _port_flags.size());
1734         return _port_flags[param] & PORT_CONTROL;
1735 }
1736
1737 bool
1738 LV2Plugin::parameter_is_audio(uint32_t param) const
1739 {
1740         assert(param < _port_flags.size());
1741         return _port_flags[param] & PORT_AUDIO;
1742 }
1743
1744 bool
1745 LV2Plugin::parameter_is_event(uint32_t param) const
1746 {
1747         assert(param < _port_flags.size());
1748         return _port_flags[param] & PORT_EVENT;
1749 }
1750
1751 bool
1752 LV2Plugin::parameter_is_output(uint32_t param) const
1753 {
1754         assert(param < _port_flags.size());
1755         return _port_flags[param] & PORT_OUTPUT;
1756 }
1757
1758 bool
1759 LV2Plugin::parameter_is_input(uint32_t param) const
1760 {
1761         assert(param < _port_flags.size());
1762         return _port_flags[param] & PORT_INPUT;
1763 }
1764
1765 void
1766 LV2Plugin::print_parameter(uint32_t param, char* buf, uint32_t len) const
1767 {
1768         if (buf && len) {
1769                 if (param < parameter_count()) {
1770                         snprintf(buf, len, "%.3f", get_parameter(param));
1771                 } else {
1772                         strcat(buf, "0");
1773                 }
1774         }
1775 }
1776
1777 boost::shared_ptr<Plugin::ScalePoints>
1778 LV2Plugin::get_scale_points(uint32_t port_index) const
1779 {
1780         const LilvPort*  port   = lilv_plugin_get_port_by_index(_impl->plugin, port_index);
1781         LilvScalePoints* points = lilv_port_get_scale_points(_impl->plugin, port);
1782
1783         boost::shared_ptr<Plugin::ScalePoints> ret;
1784         if (!points) {
1785                 return ret;
1786         }
1787
1788         ret = boost::shared_ptr<Plugin::ScalePoints>(new ScalePoints());
1789
1790         LILV_FOREACH(scale_points, i, points) {
1791                 const LilvScalePoint* p     = lilv_scale_points_get(points, i);
1792                 const LilvNode*       label = lilv_scale_point_get_label(p);
1793                 const LilvNode*       value = lilv_scale_point_get_value(p);
1794                 if (label && (lilv_node_is_float(value) || lilv_node_is_int(value))) {
1795                         ret->insert(make_pair(lilv_node_as_string(label),
1796                                               lilv_node_as_float(value)));
1797                 }
1798         }
1799
1800         lilv_scale_points_free(points);
1801         return ret;
1802 }
1803
1804 void
1805 LV2Plugin::run(pframes_t nframes)
1806 {
1807         uint32_t const N = parameter_count();
1808         for (uint32_t i = 0; i < N; ++i) {
1809                 if (parameter_is_control(i) && parameter_is_input(i)) {
1810                         _control_data[i] = _shadow_data[i];
1811                 }
1812         }
1813
1814         lilv_instance_run(_impl->instance, nframes);
1815
1816         if (_impl->work_iface) {
1817                 _worker->emit_responses();
1818                 if (_impl->work_iface->end_run) {
1819                         _impl->work_iface->end_run(_impl->instance->lv2_handle);
1820                 }
1821         }
1822 }
1823
1824 void
1825 LV2Plugin::latency_compute_run()
1826 {
1827         if (!_latency_control_port) {
1828                 return;
1829         }
1830
1831         // Run the plugin so that it can set its latency parameter
1832
1833         activate();
1834
1835         uint32_t port_index = 0;
1836         uint32_t in_index   = 0;
1837         uint32_t out_index  = 0;
1838
1839         const framecnt_t bufsize = 1024;
1840         float            buffer[bufsize];
1841
1842         memset(buffer, 0, sizeof(float) * bufsize);
1843
1844         // FIXME: Ensure plugins can handle in-place processing
1845
1846         port_index = 0;
1847
1848         while (port_index < parameter_count()) {
1849                 if (parameter_is_audio(port_index)) {
1850                         if (parameter_is_input(port_index)) {
1851                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1852                                 in_index++;
1853                         } else if (parameter_is_output(port_index)) {
1854                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1855                                 out_index++;
1856                         }
1857                 }
1858                 port_index++;
1859         }
1860
1861         run(bufsize);
1862         deactivate();
1863 }
1864
1865 const LilvPort*
1866 LV2Plugin::Impl::designated_input (const char* uri, void** bufptrs[], void** bufptr)
1867 {
1868         const LilvPort* port = NULL;
1869         LilvNode* designation = lilv_new_uri(_world.world, uri);
1870         port = lilv_plugin_get_port_by_designation(
1871                 plugin, _world.lv2_InputPort, designation);
1872         lilv_node_free(designation);
1873         if (port) {
1874                 bufptrs[lilv_port_get_index(plugin, port)] = bufptr;
1875         }
1876         return port;
1877 }
1878
1879 LV2World::LV2World()
1880         : world(lilv_world_new())
1881 {
1882         lilv_world_load_all(world);
1883         atom_AtomPort      = lilv_new_uri(world, LV2_ATOM__AtomPort);
1884         atom_Chunk         = lilv_new_uri(world, LV2_ATOM__Chunk);
1885         atom_Sequence      = lilv_new_uri(world, LV2_ATOM__Sequence);
1886         atom_bufferType    = lilv_new_uri(world, LV2_ATOM__bufferType);
1887         atom_supports      = lilv_new_uri(world, LV2_ATOM__supports);
1888         atom_eventTransfer = lilv_new_uri(world, LV2_ATOM__eventTransfer);
1889         ev_EventPort       = lilv_new_uri(world, LILV_URI_EVENT_PORT);
1890         ext_logarithmic    = lilv_new_uri(world, LV2_PORT_PROPS__logarithmic);
1891         ext_notOnGUI       = lilv_new_uri(world, LV2_PORT_PROPS__notOnGUI);
1892         lv2_AudioPort      = lilv_new_uri(world, LILV_URI_AUDIO_PORT);
1893         lv2_ControlPort    = lilv_new_uri(world, LILV_URI_CONTROL_PORT);
1894         lv2_InputPort      = lilv_new_uri(world, LILV_URI_INPUT_PORT);
1895         lv2_OutputPort     = lilv_new_uri(world, LILV_URI_OUTPUT_PORT);
1896         lv2_inPlaceBroken  = lilv_new_uri(world, LV2_CORE__inPlaceBroken);
1897         lv2_integer        = lilv_new_uri(world, LV2_CORE__integer);
1898         lv2_reportsLatency = lilv_new_uri(world, LV2_CORE__reportsLatency);
1899         lv2_sampleRate     = lilv_new_uri(world, LV2_CORE__sampleRate);
1900         lv2_toggled        = lilv_new_uri(world, LV2_CORE__toggled);
1901         lv2_enumeration    = lilv_new_uri(world, LV2_CORE__enumeration);
1902         midi_MidiEvent     = lilv_new_uri(world, LILV_URI_MIDI_EVENT);
1903         rdfs_comment       = lilv_new_uri(world, LILV_NS_RDFS "comment");
1904         rsz_minimumSize    = lilv_new_uri(world, LV2_RESIZE_PORT__minimumSize);
1905         time_Position      = lilv_new_uri(world, LV2_TIME__Position);
1906         ui_GtkUI           = lilv_new_uri(world, LV2_UI__GtkUI);
1907         ui_external        = lilv_new_uri(world, "http://lv2plug.in/ns/extensions/ui#external");
1908 }
1909
1910 LV2World::~LV2World()
1911 {
1912         lilv_node_free(ui_external);
1913         lilv_node_free(ui_GtkUI);
1914         lilv_node_free(midi_MidiEvent);
1915         lilv_node_free(lv2_toggled);
1916         lilv_node_free(lv2_sampleRate);
1917         lilv_node_free(lv2_integer);
1918         lilv_node_free(lv2_reportsLatency);
1919         lilv_node_free(lv2_inPlaceBroken);
1920         lilv_node_free(lv2_OutputPort);
1921         lilv_node_free(lv2_InputPort);
1922         lilv_node_free(lv2_ControlPort);
1923         lilv_node_free(lv2_AudioPort);
1924         lilv_node_free(ext_logarithmic);
1925         lilv_node_free(ext_notOnGUI);
1926         lilv_node_free(ev_EventPort);
1927         lilv_node_free(rsz_minimumSize);
1928         lilv_node_free(atom_eventTransfer);
1929         lilv_node_free(atom_bufferType);
1930         lilv_node_free(atom_Sequence);
1931         lilv_node_free(atom_Chunk);
1932         lilv_node_free(atom_AtomPort);
1933 }
1934
1935 LV2PluginInfo::LV2PluginInfo (const void* c_plugin)
1936         : _c_plugin(c_plugin)
1937 {
1938         type = ARDOUR::LV2;
1939 }
1940
1941 LV2PluginInfo::~LV2PluginInfo()
1942 {}
1943
1944 PluginPtr
1945 LV2PluginInfo::load(Session& session)
1946 {
1947         try {
1948                 PluginPtr plugin;
1949
1950                 plugin.reset(new LV2Plugin(session.engine(), session,
1951                                            (const LilvPlugin*)_c_plugin,
1952                                            session.frame_rate()));
1953
1954                 plugin->set_info(PluginInfoPtr(new LV2PluginInfo(*this)));
1955                 return plugin;
1956         } catch (failed_constructor& err) {
1957                 return PluginPtr((Plugin*)0);
1958         }
1959
1960         return PluginPtr();
1961 }
1962
1963 PluginInfoList*
1964 LV2PluginInfo::discover()
1965 {
1966         PluginInfoList*    plugs   = new PluginInfoList;
1967         const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
1968
1969         info << "LV2: Discovering " << lilv_plugins_size(plugins) << " plugins" << endmsg;
1970
1971         LILV_FOREACH(plugins, i, plugins) {
1972                 const LilvPlugin* p = lilv_plugins_get(plugins, i);
1973                 LV2PluginInfoPtr  info(new LV2PluginInfo((const void*)p));
1974
1975                 LilvNode* name = lilv_plugin_get_name(p);
1976                 if (!name || !lilv_plugin_get_port_by_index(p, 0)) {
1977                         warning << "Ignoring invalid LV2 plugin "
1978                                 << lilv_node_as_string(lilv_plugin_get_uri(p))
1979                                 << endmsg;
1980                         continue;
1981                 }
1982
1983                 info->type = LV2;
1984
1985                 info->name = string(lilv_node_as_string(name));
1986                 lilv_node_free(name);
1987
1988                 const LilvPluginClass* pclass = lilv_plugin_get_class(p);
1989                 const LilvNode*        label  = lilv_plugin_class_get_label(pclass);
1990                 info->category = lilv_node_as_string(label);
1991
1992                 LilvNode* author_name = lilv_plugin_get_author_name(p);
1993                 info->creator = author_name ? string(lilv_node_as_string(author_name)) : "Unknown";
1994                 lilv_node_free(author_name);
1995
1996                 info->path = "/NOPATH"; // Meaningless for LV2
1997
1998                 /* count atom-event-ports that feature
1999                  * atom:supports <http://lv2plug.in/ns/ext/midi#MidiEvent>
2000                  *
2001                  * TODO: nicely ask drobilla to make a lilv_ call for that
2002                  */
2003                 int count_midi_out = 0;
2004                 int count_midi_in = 0;
2005                 for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
2006                         const LilvPort* port  = lilv_plugin_get_port_by_index(p, i);
2007                         if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
2008                                 LilvNodes* buffer_types = lilv_port_get_value(
2009                                         p, port, _world.atom_bufferType);
2010                                 LilvNodes* atom_supports = lilv_port_get_value(
2011                                         p, port, _world.atom_supports);
2012
2013                                 if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)
2014                                                 && lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
2015                                         if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
2016                                                 count_midi_in++;
2017                                         }
2018                                         if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
2019                                                 count_midi_out++;
2020                                         }
2021                                 }
2022                                 lilv_nodes_free(buffer_types);
2023                                 lilv_nodes_free(atom_supports);
2024                         }
2025                 }
2026
2027                 info->n_inputs.set_audio(
2028                         lilv_plugin_get_num_ports_of_class(
2029                                 p, _world.lv2_InputPort, _world.lv2_AudioPort, NULL));
2030                 info->n_inputs.set_midi(
2031                         lilv_plugin_get_num_ports_of_class(
2032                                 p, _world.lv2_InputPort, _world.ev_EventPort, NULL)
2033                         + count_midi_in);
2034
2035                 info->n_outputs.set_audio(
2036                         lilv_plugin_get_num_ports_of_class(
2037                                 p, _world.lv2_OutputPort, _world.lv2_AudioPort, NULL));
2038                 info->n_outputs.set_midi(
2039                         lilv_plugin_get_num_ports_of_class(
2040                                 p, _world.lv2_OutputPort, _world.ev_EventPort, NULL)
2041                         + count_midi_out);
2042
2043                 info->unique_id = lilv_node_as_uri(lilv_plugin_get_uri(p));
2044                 info->index     = 0; // Meaningless for LV2
2045
2046                 plugs->push_back(info);
2047         }
2048
2049         return plugs;
2050 }