2 Copyright (C) 2008-2012 Paul Davis
3 Author: David Robillard
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.
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.
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.
28 #include <giomm/file.h>
29 #include <glib/gprintf.h>
32 #include <boost/utility.hpp>
34 #include "pbd/pathscanner.h"
35 #include "pbd/compose.h"
36 #include "pbd/error.h"
37 #include "pbd/xml++.h"
39 #include "libardour-config.h"
41 #include "ardour/audio_buffer.h"
42 #include "ardour/audioengine.h"
43 #include "ardour/debug.h"
44 #include "ardour/lv2_plugin.h"
45 #include "ardour/session.h"
46 #include "ardour/tempo.h"
47 #include "ardour/types.h"
48 #include "ardour/utils.h"
49 #include "ardour/worker.h"
50 #include "ardour/lv2_bundled_search_path.h"
55 #include <lilv/lilv.h>
57 #include "lv2/lv2plug.in/ns/ext/atom/atom.h"
58 #include "lv2/lv2plug.in/ns/ext/atom/forge.h"
59 #include "lv2/lv2plug.in/ns/ext/log/log.h"
60 #include "lv2/lv2plug.in/ns/ext/midi/midi.h"
61 #include "lv2/lv2plug.in/ns/ext/port-props/port-props.h"
62 #include "lv2/lv2plug.in/ns/ext/presets/presets.h"
63 #include "lv2/lv2plug.in/ns/ext/state/state.h"
64 #include "lv2/lv2plug.in/ns/ext/time/time.h"
65 #include "lv2/lv2plug.in/ns/ext/worker/worker.h"
66 #include "lv2/lv2plug.in/ns/ext/resize-port/resize-port.h"
67 #include "lv2/lv2plug.in/ns/extensions/ui/ui.h"
69 #include "lv2/lv2plug.in/ns/ext/buf-size/buf-size.h"
70 #include "lv2/lv2plug.in/ns/ext/options/options.h"
73 #include "lv2_evbuf.h"
76 #include <suil/suil.h>
79 /** The number of MIDI buffers that will fit in a UI/worker comm buffer.
80 This needs to be roughly the number of cycles the UI will get around to
81 actually processing the traffic. Lower values are flakier but save memory.
83 static const size_t NBUFS = 4;
86 using namespace ARDOUR;
89 URIMap LV2Plugin::_uri_map;
91 LV2Plugin::URIDs LV2Plugin::urids = {
92 _uri_map.uri_to_id(LV2_ATOM__Chunk),
93 _uri_map.uri_to_id(LV2_ATOM__Path),
94 _uri_map.uri_to_id(LV2_ATOM__Sequence),
95 _uri_map.uri_to_id(LV2_ATOM__eventTransfer),
96 _uri_map.uri_to_id(LV2_LOG__Error),
97 _uri_map.uri_to_id(LV2_LOG__Note),
98 _uri_map.uri_to_id(LV2_LOG__Warning),
99 _uri_map.uri_to_id(LV2_MIDI__MidiEvent),
100 _uri_map.uri_to_id(LV2_TIME__Position),
101 _uri_map.uri_to_id(LV2_TIME__bar),
102 _uri_map.uri_to_id(LV2_TIME__barBeat),
103 _uri_map.uri_to_id(LV2_TIME__beatUnit),
104 _uri_map.uri_to_id(LV2_TIME__beatsPerBar),
105 _uri_map.uri_to_id(LV2_TIME__beatsPerMinute),
106 _uri_map.uri_to_id(LV2_TIME__frame),
107 _uri_map.uri_to_id(LV2_TIME__speed)
110 class LV2World : boost::noncopyable {
115 void load_bundled_plugins();
119 LilvNode* atom_AtomPort;
120 LilvNode* atom_Chunk;
121 LilvNode* atom_Sequence;
122 LilvNode* atom_bufferType;
123 LilvNode* atom_eventTransfer;
124 LilvNode* atom_supports;
125 LilvNode* ev_EventPort;
126 LilvNode* ext_logarithmic;
127 LilvNode* ext_notOnGUI;
128 LilvNode* lv2_AudioPort;
129 LilvNode* lv2_ControlPort;
130 LilvNode* lv2_InputPort;
131 LilvNode* lv2_OutputPort;
132 LilvNode* lv2_enumeration;
133 LilvNode* lv2_freewheeling;
134 LilvNode* lv2_inPlaceBroken;
135 LilvNode* lv2_integer;
136 LilvNode* lv2_reportsLatency;
137 LilvNode* lv2_sampleRate;
138 LilvNode* lv2_toggled;
139 LilvNode* midi_MidiEvent;
140 LilvNode* rdfs_comment;
141 LilvNode* rsz_minimumSize;
142 LilvNode* time_Position;
144 LilvNode* ui_external;
145 LilvNode* ui_externalkx;
146 LilvNode* units_unit;
147 LilvNode* units_midiNote;
150 bool _bundle_checked;
153 static LV2World _world;
155 /* worker extension */
157 /** Called by the plugin to schedule non-RT work. */
158 static LV2_Worker_Status
159 work_schedule(LV2_Worker_Schedule_Handle handle,
163 LV2Plugin* plugin = (LV2Plugin*)handle;
164 if (plugin->session().engine().freewheeling()) {
165 // Freewheeling, do the work immediately in this (audio) thread
166 return (LV2_Worker_Status)plugin->work(size, data);
168 // Enqueue message for the worker thread
169 return plugin->worker()->schedule(size, data) ?
170 LV2_WORKER_SUCCESS : LV2_WORKER_ERR_UNKNOWN;
174 /** Called by the plugin to respond to non-RT work. */
175 static LV2_Worker_Status
176 work_respond(LV2_Worker_Respond_Handle handle,
180 LV2Plugin* plugin = (LV2Plugin*)handle;
181 if (plugin->session().engine().freewheeling()) {
182 // Freewheeling, respond immediately in this (audio) thread
183 return (LV2_Worker_Status)plugin->work_response(size, data);
185 // Enqueue response for the worker
186 return plugin->worker()->respond(size, data) ?
187 LV2_WORKER_SUCCESS : LV2_WORKER_ERR_UNKNOWN;
194 log_vprintf(LV2_Log_Handle /*handle*/,
200 const int ret = g_vasprintf(&str, fmt, args);
201 if (type == LV2Plugin::urids.log_Error) {
202 error << str << endmsg;
203 } else if (type == LV2Plugin::urids.log_Warning) {
204 warning << str << endmsg;
205 } else if (type == LV2Plugin::urids.log_Note) {
206 info << str << endmsg;
208 // TODO: Toggleable log:Trace message support
213 log_printf(LV2_Log_Handle handle,
215 const char* fmt, ...)
219 const int ret = log_vprintf(handle, type, fmt, args);
224 struct LV2Plugin::Impl {
225 Impl() : plugin(0), ui(0), ui_type(0), name(0), author(0), instance(0)
230 /** Find the LV2 input port with the given designation.
231 * If found, bufptrs[port_index] will be set to bufptr.
233 const LilvPort* designated_input (const char* uri, void** bufptrs[], void** bufptr);
235 const LilvPlugin* plugin;
237 const LilvNode* ui_type;
240 LilvInstance* instance;
241 const LV2_Worker_Interface* work_iface;
243 LV2_Atom_Forge forge;
246 LV2Plugin::LV2Plugin (AudioEngine& engine,
248 const void* c_plugin,
250 : Plugin (engine, session)
257 init(c_plugin, rate);
260 LV2Plugin::LV2Plugin (const LV2Plugin& other)
266 , _insert_id(other._insert_id)
268 init(other._impl->plugin, other._sample_rate);
270 for (uint32_t i = 0; i < parameter_count(); ++i) {
271 _control_data[i] = other._shadow_data[i];
272 _shadow_data[i] = other._shadow_data[i];
277 LV2Plugin::init(const void* c_plugin, framecnt_t rate)
279 DEBUG_TRACE(DEBUG::LV2, "init\n");
281 _impl->plugin = (const LilvPlugin*)c_plugin;
283 _impl->ui_type = NULL;
288 _atom_ev_buffers = 0;
290 _bpm_control_port = 0;
291 _freewheel_control_port = 0;
292 _latency_control_port = 0;
293 _next_cycle_start = std::numeric_limits<framepos_t>::max();
294 _next_cycle_speed = 1.0;
295 _block_length = _engine.samples_per_cycle();
296 _seq_size = _engine.raw_buffer_size(DataType::MIDI);
298 _was_activated = false;
299 _has_state_interface = false;
301 _instance_access_feature.URI = "http://lv2plug.in/ns/ext/instance-access";
302 _data_access_feature.URI = "http://lv2plug.in/ns/ext/data-access";
303 _make_path_feature.URI = LV2_STATE__makePath;
304 _log_feature.URI = LV2_LOG__log;
305 _work_schedule_feature.URI = LV2_WORKER__schedule;
306 _work_schedule_feature.data = NULL;
307 _def_state_feature.URI = LV2_STATE_PREFIX "loadDefaultState"; // Post LV2-1.2.0
308 _def_state_feature.data = NULL;
310 const LilvPlugin* plugin = _impl->plugin;
312 LilvNode* state_iface_uri = lilv_new_uri(_world.world, LV2_STATE__interface);
313 LilvNode* state_uri = lilv_new_uri(_world.world, LV2_STATE_URI);
314 _has_state_interface =
315 // What plugins should have (lv2:extensionData state:Interface)
316 lilv_plugin_has_extension_data(plugin, state_iface_uri)
317 // What some outdated/incorrect ones have
318 || lilv_plugin_has_feature(plugin, state_uri);
319 lilv_node_free(state_uri);
320 lilv_node_free(state_iface_uri);
322 _features = (LV2_Feature**)calloc(11, sizeof(LV2_Feature*));
323 _features[0] = &_instance_access_feature;
324 _features[1] = &_data_access_feature;
325 _features[2] = &_make_path_feature;
326 _features[3] = _uri_map.uri_map_feature();
327 _features[4] = _uri_map.urid_map_feature();
328 _features[5] = _uri_map.urid_unmap_feature();
329 _features[6] = &_log_feature;
331 unsigned n_features = 7;
333 _features[n_features++] = &_def_state_feature;
336 lv2_atom_forge_init(&_impl->forge, _uri_map.urid_map());
339 LV2_URID atom_Int = _uri_map.uri_to_id(LV2_ATOM__Int);
340 LV2_Options_Option options[] = {
341 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__minBlockLength),
342 sizeof(int32_t), atom_Int, &_block_length },
343 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__maxBlockLength),
344 sizeof(int32_t), atom_Int, &_block_length },
345 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__sequenceSize),
346 sizeof(int32_t), atom_Int, &_seq_size },
347 { LV2_OPTIONS_INSTANCE, 0, 0, 0, 0, NULL }
350 _options_feature.URI = LV2_OPTIONS__options;
351 _options_feature.data = options;
352 _features[n_features++] = &_options_feature;
355 LV2_State_Make_Path* make_path = (LV2_State_Make_Path*)malloc(
356 sizeof(LV2_State_Make_Path));
357 make_path->handle = this;
358 make_path->path = &lv2_state_make_path;
359 _make_path_feature.data = make_path;
361 LV2_Log_Log* log = (LV2_Log_Log*)malloc(sizeof(LV2_Log_Log));
363 log->printf = &log_printf;
364 log->vprintf = &log_vprintf;
365 _log_feature.data = log;
367 LilvNode* worker_schedule = lilv_new_uri(_world.world, LV2_WORKER__schedule);
368 if (lilv_plugin_has_feature(plugin, worker_schedule)) {
369 LV2_Worker_Schedule* schedule = (LV2_Worker_Schedule*)malloc(
370 sizeof(LV2_Worker_Schedule));
371 size_t buf_size = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
372 _worker = new Worker(this, buf_size);
373 schedule->handle = this;
374 schedule->schedule_work = work_schedule;
375 _work_schedule_feature.data = schedule;
376 _features[n_features++] = &_work_schedule_feature;
378 lilv_node_free(worker_schedule);
380 _impl->instance = lilv_plugin_instantiate(plugin, rate, _features);
381 _impl->name = lilv_plugin_get_name(plugin);
382 _impl->author = lilv_plugin_get_author_name(plugin);
384 if (_impl->instance == 0) {
385 error << _("LV2: Failed to instantiate plugin ") << uri() << endmsg;
386 throw failed_constructor();
389 _instance_access_feature.data = (void*)_impl->instance->lv2_handle;
390 _data_access_extension_data.extension_data = _impl->instance->lv2_descriptor->extension_data;
391 _data_access_feature.data = &_data_access_extension_data;
393 LilvNode* worker_iface_uri = lilv_new_uri(_world.world, LV2_WORKER__interface);
394 if (lilv_plugin_has_extension_data(plugin, worker_iface_uri)) {
395 _impl->work_iface = (const LV2_Worker_Interface*)extension_data(
396 LV2_WORKER__interface);
398 lilv_node_free(worker_iface_uri);
400 if (lilv_plugin_has_feature(plugin, _world.lv2_inPlaceBroken)) {
401 error << string_compose(
402 _("LV2: \"%1\" cannot be used, since it cannot do inplace processing"),
403 lilv_node_as_string(_impl->name)) << endmsg;
404 lilv_node_free(_impl->name);
405 lilv_node_free(_impl->author);
406 throw failed_constructor();
410 // Load default state
411 LilvState* state = lilv_state_new_from_world(
412 _world.world, _uri_map.urid_map(), lilv_plugin_get_uri(_impl->plugin));
413 if (state && _has_state_interface) {
414 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
420 const uint32_t num_ports = this->num_ports();
421 for (uint32_t i = 0; i < num_ports; ++i) {
422 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, i);
424 size_t minimumSize = 0;
426 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_OutputPort)) {
427 flags |= PORT_OUTPUT;
428 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_InputPort)) {
431 error << string_compose(
432 "LV2: \"%1\" port %2 is neither input nor output",
433 lilv_node_as_string(_impl->name), i) << endmsg;
434 throw failed_constructor();
437 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_ControlPort)) {
438 flags |= PORT_CONTROL;
439 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_AudioPort)) {
441 } else if (lilv_port_is_a(_impl->plugin, port, _world.ev_EventPort)) {
443 flags |= PORT_MIDI; // We assume old event API ports are for MIDI
444 } else if (lilv_port_is_a(_impl->plugin, port, _world.atom_AtomPort)) {
445 LilvNodes* buffer_types = lilv_port_get_value(
446 _impl->plugin, port, _world.atom_bufferType);
447 LilvNodes* atom_supports = lilv_port_get_value(
448 _impl->plugin, port, _world.atom_supports);
450 if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)) {
451 flags |= PORT_SEQUENCE;
452 if (lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
455 if (lilv_nodes_contains(atom_supports, _world.time_Position)) {
456 flags |= PORT_POSITION;
459 LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
460 LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
461 if (min_size && lilv_node_is_int(min_size)) {
462 minimumSize = lilv_node_as_int(min_size);
464 lilv_nodes_free(min_size_v);
465 lilv_nodes_free(buffer_types);
466 lilv_nodes_free(atom_supports);
468 error << string_compose(
469 "LV2: \"%1\" port %2 has no known data type",
470 lilv_node_as_string(_impl->name), i) << endmsg;
471 throw failed_constructor();
474 _port_flags.push_back(flags);
475 _port_minimumSize.push_back(minimumSize);
478 _control_data = new float[num_ports];
479 _shadow_data = new float[num_ports];
480 _defaults = new float[num_ports];
481 _ev_buffers = new LV2_Evbuf*[num_ports];
482 memset(_ev_buffers, 0, sizeof(LV2_Evbuf*) * num_ports);
484 const bool latent = lilv_plugin_has_latency(plugin);
485 const uint32_t latency_index = (latent)
486 ? lilv_plugin_get_latency_port_index(plugin)
489 // Build an array of pointers to special parameter buffers
490 void*** params = new void**[num_ports];
491 for (uint32_t i = 0; i < num_ports; ++i) {
494 _impl->designated_input (LV2_TIME__beatsPerMinute, params, (void**)&_bpm_control_port);
495 _impl->designated_input (LV2_CORE__freeWheeling, params, (void**)&_freewheel_control_port);
497 for (uint32_t i = 0; i < num_ports; ++i) {
498 const LilvPort* port = lilv_plugin_get_port_by_index(plugin, i);
499 const LilvNode* sym = lilv_port_get_symbol(plugin, port);
501 // Store index in map so we can look up index by symbol
502 _port_indices.insert(std::make_pair(lilv_node_as_string(sym), i));
504 // Get range and default value if applicable
505 if (parameter_is_control(i)) {
507 lilv_port_get_range(plugin, port, &def, NULL, NULL);
508 _defaults[i] = def ? lilv_node_as_float(def) : 0.0f;
509 if (lilv_port_has_property (plugin, port, _world.lv2_sampleRate)) {
510 _defaults[i] *= _session.frame_rate ();
514 lilv_instance_connect_port(_impl->instance, i, &_control_data[i]);
516 if (latent && i == latency_index) {
517 _latency_control_port = &_control_data[i];
518 *_latency_control_port = 0;
521 if (parameter_is_input(i)) {
522 _shadow_data[i] = default_value(i);
524 *params[i] = (void*)&_shadow_data[i];
534 LilvUIs* uis = lilv_plugin_get_uis(plugin);
535 if (lilv_uis_size(uis) > 0) {
537 // Look for embeddable UI
538 LILV_FOREACH(uis, u, uis) {
539 const LilvUI* this_ui = lilv_uis_get(uis, u);
540 const LilvNode* this_ui_type = NULL;
541 if (lilv_ui_is_supported(this_ui,
545 // TODO: Multiple UI support
547 _impl->ui_type = this_ui_type;
552 // Look for Gtk native 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_GtkUI)) {
557 _impl->ui_type = _world.ui_GtkUI;
563 // If Gtk UI is not available, try to find external UI
565 LILV_FOREACH(uis, i, uis) {
566 const LilvUI* ui = lilv_uis_get(uis, i);
567 if (lilv_ui_is_a(ui, _world.ui_externalkx)) {
569 _impl->ui_type = _world.ui_external;
572 if (lilv_ui_is_a(ui, _world.ui_external)) {
574 _impl->ui_type = _world.ui_external;
580 allocate_atom_event_buffers();
581 latency_compute_run();
584 LV2Plugin::~LV2Plugin ()
586 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 destroy\n", name()));
591 lilv_instance_free(_impl->instance);
592 lilv_node_free(_impl->name);
593 lilv_node_free(_impl->author);
596 free(_make_path_feature.data);
597 free(_work_schedule_feature.data);
603 if (_atom_ev_buffers) {
604 LV2_Evbuf** b = _atom_ev_buffers;
609 free(_atom_ev_buffers);
612 delete [] _control_data;
613 delete [] _shadow_data;
614 delete [] _ev_buffers;
618 LV2Plugin::is_external_ui() const
623 return lilv_ui_is_a(_impl->ui, _world.ui_external) || lilv_ui_is_a(_impl->ui, _world.ui_externalkx);
627 LV2Plugin::is_external_kx() const
632 return lilv_ui_is_a(_impl->ui, _world.ui_externalkx);
636 LV2Plugin::ui_is_resizable () const
638 const LilvNode* s = lilv_ui_get_uri(_impl->ui);
639 LilvNode* p = lilv_new_uri(_world.world, LV2_CORE__optionalFeature);
640 LilvNode* fs = lilv_new_uri(_world.world, LV2_UI__fixedSize);
641 LilvNode* nrs = lilv_new_uri(_world.world, LV2_UI__noUserResize);
643 LilvNodes* fs_matches = lilv_world_find_nodes(_world.world, s, p, fs);
644 LilvNodes* nrs_matches = lilv_world_find_nodes(_world.world, s, p, nrs);
646 lilv_nodes_free(nrs_matches);
647 lilv_nodes_free(fs_matches);
652 return !fs_matches && !nrs_matches;
656 LV2Plugin::unique_id() const
658 return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
662 LV2Plugin::uri() const
664 return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
668 LV2Plugin::label() const
670 return lilv_node_as_string(_impl->name);
674 LV2Plugin::name() const
676 return lilv_node_as_string(_impl->name);
680 LV2Plugin::maker() const
682 return _impl->author ? lilv_node_as_string (_impl->author) : "Unknown";
686 LV2Plugin::num_ports() const
688 return lilv_plugin_get_num_ports(_impl->plugin);
692 LV2Plugin::parameter_count() const
694 return lilv_plugin_get_num_ports(_impl->plugin);
698 LV2Plugin::default_value(uint32_t port)
700 return _defaults[port];
704 LV2Plugin::port_symbol(uint32_t index) const
706 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, index);
708 error << name() << ": Invalid port index " << index << endmsg;
711 const LilvNode* sym = lilv_port_get_symbol(_impl->plugin, port);
712 return lilv_node_as_string(sym);
716 LV2Plugin::port_index (const char* symbol) const
718 const map<string, uint32_t>::const_iterator i = _port_indices.find(symbol);
719 if (i != _port_indices.end()) {
722 warning << string_compose(_("LV2: Unknown port %1"), symbol) << endmsg;
728 LV2Plugin::set_parameter(uint32_t which, float val)
730 DEBUG_TRACE(DEBUG::LV2, string_compose(
731 "%1 set parameter %2 to %3\n", name(), which, val));
733 if (which < lilv_plugin_get_num_ports(_impl->plugin)) {
734 if (get_parameter (which) == val) {
738 _shadow_data[which] = val;
740 warning << string_compose(
741 _("Illegal parameter number used with plugin \"%1\". "
742 "This is a bug in either %2 or the LV2 plugin <%3>"),
743 name(), PROGRAM_NAME, unique_id()) << endmsg;
746 Plugin::set_parameter(which, val);
750 LV2Plugin::get_parameter(uint32_t which) const
752 if (parameter_is_input(which)) {
753 return (float)_shadow_data[which];
755 return (float)_control_data[which];
761 LV2Plugin::get_docs() const
763 LilvNodes* comments = lilv_plugin_get_value(_impl->plugin, _world.rdfs_comment);
765 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
766 lilv_nodes_free(comments);
774 LV2Plugin::get_parameter_docs(uint32_t which) const
776 LilvNodes* comments = lilv_port_get_value(
778 lilv_plugin_get_port_by_index(_impl->plugin, which),
779 _world.rdfs_comment);
782 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
783 lilv_nodes_free(comments);
791 LV2Plugin::nth_parameter(uint32_t n, bool& ok) const
794 for (uint32_t c = 0, x = 0; x < lilv_plugin_get_num_ports(_impl->plugin); ++x) {
795 if (parameter_is_control(x)) {
807 LV2Plugin::extension_data(const char* uri) const
809 return lilv_instance_get_extension_data(_impl->instance, uri);
813 LV2Plugin::c_plugin()
815 return _impl->plugin;
821 return (const void*)_impl->ui;
825 LV2Plugin::c_ui_type()
827 return (const void*)_impl->ui_type;
830 /** Directory for all plugin state. */
832 LV2Plugin::plugin_dir() const
834 return Glib::build_filename(_session.plugins_dir(), _insert_id.to_s());
837 /** Directory for files created by the plugin (except during save). */
839 LV2Plugin::scratch_dir() const
841 return Glib::build_filename(plugin_dir(), "scratch");
844 /** Directory for snapshots of files in the scratch directory. */
846 LV2Plugin::file_dir() const
848 return Glib::build_filename(plugin_dir(), "files");
851 /** Directory to save state snapshot version @c num into. */
853 LV2Plugin::state_dir(unsigned num) const
855 return Glib::build_filename(plugin_dir(), string_compose("state%1", num));
858 /** Implementation of state:makePath for files created at instantiation time.
859 * Note this is not used for files created at save time (Lilv deals with that).
862 LV2Plugin::lv2_state_make_path(LV2_State_Make_Path_Handle handle,
865 LV2Plugin* me = (LV2Plugin*)handle;
866 if (me->_insert_id == PBD::ID("0")) {
867 warning << string_compose(
868 "File path \"%1\" requested but LV2 %2 has no insert ID",
869 path, me->name()) << endmsg;
870 return g_strdup(path);
873 const std::string abs_path = Glib::build_filename(me->scratch_dir(), path);
874 const std::string dirname = Glib::path_get_dirname(abs_path);
875 g_mkdir_with_parents(dirname.c_str(), 0744);
877 DEBUG_TRACE(DEBUG::LV2, string_compose("new file path %1 => %2\n",
880 return g_strndup(abs_path.c_str(), abs_path.length());
884 remove_directory(const std::string& path)
886 if (!Glib::file_test(path, Glib::FILE_TEST_IS_DIR)) {
887 warning << string_compose("\"%1\" is not a directory", path) << endmsg;
891 Glib::RefPtr<Gio::File> dir = Gio::File::create_for_path(path);
892 Glib::RefPtr<Gio::FileEnumerator> e = dir->enumerate_children();
893 Glib::RefPtr<Gio::FileInfo> fi;
894 while ((fi = e->next_file())) {
895 if (fi->get_type() == Gio::FILE_TYPE_DIRECTORY) {
896 remove_directory(fi->get_name());
898 dir->get_child(fi->get_name())->remove();
905 LV2Plugin::add_state(XMLNode* root) const
907 assert(_insert_id != PBD::ID("0"));
911 LocaleGuard lg(X_("POSIX"));
913 for (uint32_t i = 0; i < parameter_count(); ++i) {
914 if (parameter_is_input(i) && parameter_is_control(i)) {
915 child = new XMLNode("Port");
916 child->add_property("symbol", port_symbol(i));
917 snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
918 child->add_property("value", string(buf));
919 root->add_child_nocopy(*child);
923 if (_has_state_interface) {
924 // Provisionally increment state version and create directory
925 const std::string new_dir = state_dir(++_state_version);
926 g_mkdir_with_parents(new_dir.c_str(), 0744);
928 LilvState* state = lilv_state_new_from_instance(
932 scratch_dir().c_str(),
934 _session.externals_dir().c_str(),
937 const_cast<LV2Plugin*>(this),
941 if (!_impl->state || !lilv_state_equals(state, _impl->state)) {
942 lilv_state_save(_world.world,
944 _uri_map.urid_unmap(),
950 lilv_state_free(_impl->state);
951 _impl->state = state;
953 // State is identical, decrement version and nuke directory
954 lilv_state_free(state);
955 remove_directory(new_dir);
959 root->add_property("state-dir", string_compose("state%1", _state_version));
963 static inline const LilvNode*
964 get_value(LilvWorld* world, const LilvNode* subject, const LilvNode* predicate)
966 LilvNodes* vs = lilv_world_find_nodes(world, subject, predicate, NULL);
967 return vs ? lilv_nodes_get_first(vs) : NULL;
971 LV2Plugin::find_presets()
973 LilvNode* lv2_appliesTo = lilv_new_uri(_world.world, LV2_CORE__appliesTo);
974 LilvNode* pset_Preset = lilv_new_uri(_world.world, LV2_PRESETS__Preset);
975 LilvNode* rdfs_label = lilv_new_uri(_world.world, LILV_NS_RDFS "label");
977 LilvNodes* presets = lilv_plugin_get_related(_impl->plugin, pset_Preset);
978 LILV_FOREACH(nodes, i, presets) {
979 const LilvNode* preset = lilv_nodes_get(presets, i);
980 lilv_world_load_resource(_world.world, preset);
981 const LilvNode* name = get_value(_world.world, preset, rdfs_label);
983 _presets.insert(std::make_pair(lilv_node_as_string(preset),
984 Plugin::PresetRecord(
985 lilv_node_as_string(preset),
986 lilv_node_as_string(name))));
988 warning << string_compose(
989 _("Plugin \"%1\" preset \"%2\" is missing a label\n"),
990 lilv_node_as_string(lilv_plugin_get_uri(_impl->plugin)),
991 lilv_node_as_string(preset)) << endmsg;
994 lilv_nodes_free(presets);
996 lilv_node_free(rdfs_label);
997 lilv_node_free(pset_Preset);
998 lilv_node_free(lv2_appliesTo);
1002 set_port_value(const char* port_symbol,
1008 LV2Plugin* self = (LV2Plugin*)user_data;
1009 if (type != 0 && type != self->_uri_map.uri_to_id(LV2_ATOM__Float)) {
1010 return; // TODO: Support non-float ports
1013 const uint32_t port_index = self->port_index(port_symbol);
1014 if (port_index != (uint32_t)-1) {
1015 self->set_parameter(port_index, *(const float*)value);
1020 LV2Plugin::load_preset(PresetRecord r)
1022 LilvWorld* world = _world.world;
1023 LilvNode* pset = lilv_new_uri(world, r.uri.c_str());
1024 LilvState* state = lilv_state_new_from_world(world, _uri_map.urid_map(), pset);
1027 lilv_state_restore(state, _impl->instance, set_port_value, this, 0, NULL);
1028 lilv_state_free(state);
1031 lilv_node_free(pset);
1036 ARDOUR::lv2plugin_get_port_value(const char* port_symbol,
1041 LV2Plugin *plugin = (LV2Plugin *) user_data;
1043 uint32_t index = plugin->port_index(port_symbol);
1044 if (index != (uint32_t) -1) {
1045 if (plugin->parameter_is_input(index) && plugin->parameter_is_control(index)) {
1047 *size = sizeof(float);
1048 *type = plugin->_uri_map.uri_to_id(LV2_ATOM__Float);
1049 value = &plugin->_shadow_data[index];
1061 LV2Plugin::do_save_preset(string name)
1063 const string base_name = legalize_for_uri(name);
1064 const string file_name = base_name + ".ttl";
1065 const string bundle = Glib::build_filename(
1066 Glib::get_home_dir(),
1067 Glib::build_filename(".lv2", base_name + ".lv2"));
1069 LilvState* state = lilv_state_new_from_instance(
1072 _uri_map.urid_map(),
1073 scratch_dir().c_str(), // file_dir
1074 bundle.c_str(), // copy_dir
1075 bundle.c_str(), // link_dir
1076 bundle.c_str(), // save_dir
1077 lv2plugin_get_port_value, // get_value
1078 (void*)this, // user_data
1079 LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE, // flags
1080 _features // features
1083 lilv_state_set_label(state, name.c_str());
1085 _world.world, // world
1086 _uri_map.urid_map(), // map
1087 _uri_map.urid_unmap(), // unmap
1089 NULL, // uri (NULL = use file URI)
1090 bundle.c_str(), // dir
1091 file_name.c_str() // filename
1094 lilv_state_free(state);
1096 std::string uri = Glib::filename_to_uri(Glib::build_filename(bundle, file_name));
1097 LilvNode *node_bundle = lilv_new_uri(_world.world, Glib::filename_to_uri(Glib::build_filename(bundle, "/")).c_str());
1098 LilvNode *node_preset = lilv_new_uri(_world.world, uri.c_str());
1099 lilv_world_load_bundle(_world.world, node_bundle);
1100 lilv_world_load_resource(_world.world, node_preset);
1101 lilv_node_free(node_bundle);
1102 lilv_node_free(node_preset);
1107 LV2Plugin::do_remove_preset(string name)
1109 string preset_file = Glib::build_filename(
1110 Glib::get_home_dir(),
1111 Glib::build_filename(
1112 Glib::build_filename(".lv2", "presets"),
1116 unlink(preset_file.c_str());
1120 LV2Plugin::has_editor() const
1122 return _impl->ui != NULL;
1126 LV2Plugin::has_message_output() const
1128 for (uint32_t i = 0; i < num_ports(); ++i) {
1129 if ((_port_flags[i] & PORT_SEQUENCE) &&
1130 (_port_flags[i] & PORT_OUTPUT)) {
1138 LV2Plugin::write_to(RingBuffer<uint8_t>* dest,
1142 const uint8_t* body)
1144 const uint32_t buf_size = sizeof(UIMessage) + size;
1145 uint8_t buf[buf_size];
1147 UIMessage* msg = (UIMessage*)buf;
1149 msg->protocol = protocol;
1151 memcpy(msg + 1, body, size);
1153 return (dest->write(buf, buf_size) == buf_size);
1157 LV2Plugin::write_from_ui(uint32_t index,
1160 const uint8_t* body)
1163 size_t rbs = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
1164 /* buffer data communication from plugin UI to plugin instance.
1165 * this buffer needs to potentially hold
1166 * (port's minimumSize) * (audio-periods) / (UI-periods)
1169 * e.g 48kSPS / 128fpp -> audio-periods = 375 Hz
1170 * ui-periods = 25 Hz (SuperRapidScreenUpdate)
1171 * default minimumSize = 32K (see LV2Plugin::allocate_atom_event_buffers()
1173 * it is NOT safe to overflow (msg.size will be misinterpreted)
1175 uint32_t bufsiz = 32768;
1176 if (_atom_ev_buffers && _atom_ev_buffers[0]) {
1177 bufsiz = lv2_evbuf_get_capacity(_atom_ev_buffers[0]);
1179 rbs = max((size_t) bufsiz * 8, rbs);
1180 _from_ui = new RingBuffer<uint8_t>(rbs);
1183 if (!write_to(_from_ui, index, protocol, size, body)) {
1184 error << "Error writing from UI to plugin" << endmsg;
1191 LV2Plugin::write_to_ui(uint32_t index,
1194 const uint8_t* body)
1196 if (!write_to(_to_ui, index, protocol, size, body)) {
1197 error << "Error writing from plugin to UI" << endmsg;
1204 LV2Plugin::enable_ui_emmission()
1207 /* see note in LV2Plugin::write_from_ui() */
1208 uint32_t bufsiz = 32768;
1209 if (_atom_ev_buffers && _atom_ev_buffers[0]) {
1210 bufsiz = lv2_evbuf_get_capacity(_atom_ev_buffers[0]);
1212 size_t rbs = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
1213 rbs = max((size_t) bufsiz * 8, rbs);
1214 _to_ui = new RingBuffer<uint8_t>(rbs);
1219 LV2Plugin::emit_to_ui(void* controller, UIMessageSink sink)
1225 uint32_t read_space = _to_ui->read_space();
1226 while (read_space > sizeof(UIMessage)) {
1228 if (_to_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1229 error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1232 uint8_t body[msg.size];
1233 if (_to_ui->read(body, msg.size) != msg.size) {
1234 error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1238 sink(controller, msg.index, msg.size, msg.protocol, body);
1240 read_space -= sizeof(msg) + msg.size;
1245 LV2Plugin::work(uint32_t size, const void* data)
1247 return _impl->work_iface->work(
1248 _impl->instance->lv2_handle, work_respond, this, size, data);
1252 LV2Plugin::work_response(uint32_t size, const void* data)
1254 return _impl->work_iface->work_response(
1255 _impl->instance->lv2_handle, size, data);
1259 LV2Plugin::set_insert_info(const PluginInsert* insert)
1261 _insert_id = insert->id();
1265 LV2Plugin::set_state(const XMLNode& node, int version)
1268 const XMLProperty* prop;
1269 XMLNodeConstIterator iter;
1274 LocaleGuard lg(X_("POSIX"));
1276 if (node.name() != state_node_name()) {
1277 error << _("Bad node sent to LV2Plugin::set_state") << endmsg;
1281 #ifndef NO_PLUGIN_STATE
1283 if (version < 3000) {
1284 nodes = node.children("port");
1286 nodes = node.children("Port");
1289 for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
1293 if ((prop = child->property("symbol")) != 0) {
1294 sym = prop->value().c_str();
1296 warning << _("LV2: port has no symbol, ignored") << endmsg;
1300 map<string, uint32_t>::iterator i = _port_indices.find(sym);
1302 if (i != _port_indices.end()) {
1303 port_id = i->second;
1305 warning << _("LV2: port has unknown index, ignored") << endmsg;
1309 if ((prop = child->property("value")) != 0) {
1310 value = prop->value().c_str();
1312 warning << _("LV2: port has no value, ignored") << endmsg;
1316 set_parameter(port_id, atof(value));
1320 if ((prop = node.property("state-dir")) != 0) {
1321 if (sscanf(prop->value().c_str(), "state%u", &_state_version) != 1) {
1322 error << string_compose(
1323 "LV2: failed to parse state version from \"%1\"",
1324 prop->value()) << endmsg;
1327 std::string state_file = Glib::build_filename(
1329 Glib::build_filename(prop->value(), "state.ttl"));
1331 LilvState* state = lilv_state_new_from_file(
1332 _world.world, _uri_map.urid_map(), NULL, state_file.c_str());
1334 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
1337 latency_compute_run();
1340 return Plugin::set_state(node, version);
1344 LV2Plugin::get_parameter_descriptor(uint32_t which, ParameterDescriptor& desc) const
1346 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, which);
1348 LilvNodes* portunits;
1349 LilvNode *def, *min, *max;
1350 lilv_port_get_range(_impl->plugin, port, &def, &min, &max);
1351 portunits = lilv_port_get_value(_impl->plugin, port, _world.units_unit);
1353 desc.integer_step = lilv_port_has_property(_impl->plugin, port, _world.lv2_integer);
1354 desc.toggled = lilv_port_has_property(_impl->plugin, port, _world.lv2_toggled);
1355 desc.logarithmic = lilv_port_has_property(_impl->plugin, port, _world.ext_logarithmic);
1356 desc.sr_dependent = lilv_port_has_property(_impl->plugin, port, _world.lv2_sampleRate);
1357 desc.label = lilv_node_as_string(lilv_port_get_name(_impl->plugin, port));
1358 desc.lower = min ? lilv_node_as_float(min) : 0.0f;
1359 desc.upper = max ? lilv_node_as_float(max) : 1.0f;
1360 desc.midinote = lilv_nodes_contains(portunits, _world.units_midiNote);
1362 if (desc.sr_dependent) {
1363 desc.lower *= _session.frame_rate ();
1364 desc.upper *= _session.frame_rate ();
1367 desc.min_unbound = false; // TODO: LV2 extension required
1368 desc.max_unbound = false; // TODO: LV2 extension required
1370 if (desc.integer_step) {
1372 desc.smallstep = 0.1;
1373 desc.largestep = 10.0;
1375 const float delta = desc.upper - desc.lower;
1376 desc.step = delta / 1000.0f;
1377 desc.smallstep = delta / 10000.0f;
1378 desc.largestep = delta / 10.0f;
1381 desc.enumeration = lilv_port_has_property(_impl->plugin, port, _world.lv2_enumeration);
1383 lilv_node_free(def);
1384 lilv_node_free(min);
1385 lilv_node_free(max);
1386 lilv_nodes_free(portunits);
1392 LV2Plugin::describe_parameter(Evoral::Parameter which)
1394 if (( which.type() == PluginAutomation) && ( which.id() < parameter_count()) ) {
1396 if (lilv_port_has_property(_impl->plugin,
1397 lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.ext_notOnGUI)) {
1398 return X_("hidden");
1401 if (lilv_port_has_property(_impl->plugin,
1402 lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_freewheeling)) {
1403 return X_("hidden");
1406 if (lilv_port_has_property(_impl->plugin,
1407 lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_reportsLatency)) {
1408 return X_("latency");
1411 LilvNode* name = lilv_port_get_name(_impl->plugin,
1412 lilv_plugin_get_port_by_index(_impl->plugin, which.id()));
1413 string ret(lilv_node_as_string(name));
1414 lilv_node_free(name);
1422 LV2Plugin::signal_latency() const
1424 if (_latency_control_port) {
1425 return (framecnt_t)floor(*_latency_control_port);
1431 set<Evoral::Parameter>
1432 LV2Plugin::automatable() const
1434 set<Evoral::Parameter> ret;
1436 for (uint32_t i = 0; i < parameter_count(); ++i) {
1437 if (parameter_is_input(i) && parameter_is_control(i)) {
1438 ret.insert(ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
1446 LV2Plugin::activate()
1448 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 activate\n", name()));
1450 if (!_was_activated) {
1451 lilv_instance_activate(_impl->instance);
1452 _was_activated = true;
1457 LV2Plugin::deactivate()
1459 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 deactivate\n", name()));
1461 if (_was_activated) {
1462 lilv_instance_deactivate(_impl->instance);
1463 _was_activated = false;
1468 LV2Plugin::cleanup()
1470 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 cleanup\n", name()));
1474 lilv_instance_free(_impl->instance);
1475 _impl->instance = NULL;
1479 LV2Plugin::allocate_atom_event_buffers()
1481 /* reserve local scratch buffers for ATOM event-queues */
1482 const LilvPlugin* p = _impl->plugin;
1484 /* count non-MIDI atom event-ports
1485 * TODO: nicely ask drobilla to make a lilv_ call for that
1487 int count_atom_out = 0;
1488 int count_atom_in = 0;
1489 int minimumSize = 32768; // TODO use a per-port minimum-size
1490 for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
1491 const LilvPort* port = lilv_plugin_get_port_by_index(p, i);
1492 if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
1493 LilvNodes* buffer_types = lilv_port_get_value(
1494 p, port, _world.atom_bufferType);
1495 LilvNodes* atom_supports = lilv_port_get_value(
1496 p, port, _world.atom_supports);
1498 if (!lilv_nodes_contains(buffer_types, _world.atom_Sequence)
1499 || !lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
1500 if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
1503 if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
1506 LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
1507 LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
1508 if (min_size && lilv_node_is_int(min_size)) {
1509 minimumSize = std::max(minimumSize, lilv_node_as_int(min_size));
1511 lilv_nodes_free(min_size_v);
1513 lilv_nodes_free(buffer_types);
1514 lilv_nodes_free(atom_supports);
1518 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 need buffers for %2 atom-in and %3 atom-out event-ports\n",
1519 name(), count_atom_in, count_atom_out));
1521 const int total_atom_buffers = (count_atom_in + count_atom_out);
1522 if (_atom_ev_buffers || total_atom_buffers == 0) {
1526 DEBUG_TRACE(DEBUG::LV2, string_compose("allocate %1 atom_ev_buffers of %d bytes\n", total_atom_buffers, minimumSize));
1527 _atom_ev_buffers = (LV2_Evbuf**) malloc((total_atom_buffers + 1) * sizeof(LV2_Evbuf*));
1528 for (int i = 0; i < total_atom_buffers; ++i ) {
1529 _atom_ev_buffers[i] = lv2_evbuf_new(minimumSize, LV2_EVBUF_ATOM,
1530 LV2Plugin::urids.atom_Chunk, LV2Plugin::urids.atom_Sequence);
1532 _atom_ev_buffers[total_atom_buffers] = 0;
1536 /** Write an ardour position/time/tempo/meter as an LV2 event.
1537 * @return true on success.
1540 write_position(LV2_Atom_Forge* forge,
1542 const TempoMetric& t,
1543 Timecode::BBT_Time& bbt,
1545 framepos_t position,
1548 uint8_t pos_buf[256];
1549 lv2_atom_forge_set_buffer(forge, pos_buf, sizeof(pos_buf));
1550 LV2_Atom_Forge_Frame frame;
1551 lv2_atom_forge_blank(forge, &frame, 1, LV2Plugin::urids.time_Position);
1552 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_frame, 0);
1553 lv2_atom_forge_long(forge, position);
1554 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_speed, 0);
1555 lv2_atom_forge_float(forge, speed);
1556 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_barBeat, 0);
1557 lv2_atom_forge_float(forge, bbt.beats - 1 +
1558 (bbt.ticks / Timecode::BBT_Time::ticks_per_beat));
1559 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_bar, 0);
1560 lv2_atom_forge_long(forge, bbt.bars - 1);
1561 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_beatUnit, 0);
1562 lv2_atom_forge_int(forge, t.meter().note_divisor());
1563 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_beatsPerBar, 0);
1564 lv2_atom_forge_float(forge, t.meter().divisions_per_bar());
1565 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_beatsPerMinute, 0);
1566 lv2_atom_forge_float(forge, t.tempo().beats_per_minute());
1568 LV2_Evbuf_Iterator end = lv2_evbuf_end(buf);
1569 const LV2_Atom* const atom = (const LV2_Atom*)pos_buf;
1570 return lv2_evbuf_write(&end, offset, 0, atom->type, atom->size,
1571 (const uint8_t*)(atom + 1));
1575 LV2Plugin::connect_and_run(BufferSet& bufs,
1576 ChanMapping in_map, ChanMapping out_map,
1577 pframes_t nframes, framecnt_t offset)
1579 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 run %2 offset %3\n", name(), nframes, offset));
1580 Plugin::connect_and_run(bufs, in_map, out_map, nframes, offset);
1582 cycles_t then = get_cycles();
1584 TempoMap& tmap = _session.tempo_map();
1585 Metrics::const_iterator metric_i = tmap.metrics_end();
1586 TempoMetric tmetric = tmap.metric_at(_session.transport_frame(), &metric_i);
1588 if (_freewheel_control_port) {
1589 *_freewheel_control_port = _session.engine().freewheeling();
1592 if (_bpm_control_port) {
1593 *_bpm_control_port = tmetric.tempo().beats_per_minute();
1596 ChanCount bufs_count;
1597 bufs_count.set(DataType::AUDIO, 1);
1598 bufs_count.set(DataType::MIDI, 1);
1599 BufferSet& silent_bufs = _session.get_silent_buffers(bufs_count);
1600 BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
1601 uint32_t const num_ports = parameter_count();
1602 uint32_t const nil_index = std::numeric_limits<uint32_t>::max();
1604 uint32_t audio_in_index = 0;
1605 uint32_t audio_out_index = 0;
1606 uint32_t midi_in_index = 0;
1607 uint32_t midi_out_index = 0;
1608 uint32_t atom_port_index = 0;
1609 for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
1611 uint32_t index = nil_index;
1612 PortFlags flags = _port_flags[port_index];
1614 if (flags & PORT_AUDIO) {
1615 if (flags & PORT_INPUT) {
1616 index = in_map.get(DataType::AUDIO, audio_in_index++, &valid);
1618 ? bufs.get_audio(index).data(offset)
1619 : silent_bufs.get_audio(0).data(offset);
1621 index = out_map.get(DataType::AUDIO, audio_out_index++, &valid);
1623 ? bufs.get_audio(index).data(offset)
1624 : scratch_bufs.get_audio(0).data(offset);
1626 } else if (flags & (PORT_EVENT|PORT_SEQUENCE)) {
1627 /* FIXME: The checks here for bufs.count().n_midi() > index shouldn't
1628 be necessary, but the mapping is illegal in some cases. Ideally
1629 that should be fixed, but this is easier...
1631 if (flags & PORT_MIDI) {
1632 if (flags & PORT_INPUT) {
1633 index = in_map.get(DataType::MIDI, midi_in_index++, &valid);
1635 index = out_map.get(DataType::MIDI, midi_out_index++, &valid);
1637 if (valid && bufs.count().n_midi() > index) {
1638 /* Note, ensure_lv2_bufsize() is not RT safe!
1639 * However free()/alloc() is only called if a
1640 * plugin requires a rsz:minimumSize buffersize
1641 * and the existing buffer if smaller.
1643 bufs.ensure_lv2_bufsize((flags & PORT_INPUT), index, _port_minimumSize[port_index]);
1644 _ev_buffers[port_index] = bufs.get_lv2_midi(
1645 (flags & PORT_INPUT), index, (flags & PORT_EVENT));
1647 } else if ((flags & PORT_POSITION) && (flags & PORT_INPUT)) {
1648 lv2_evbuf_reset(_atom_ev_buffers[atom_port_index], true);
1649 _ev_buffers[port_index] = _atom_ev_buffers[atom_port_index++];
1653 if (valid && (flags & PORT_INPUT)) {
1654 Timecode::BBT_Time bbt;
1655 if ((flags & PORT_POSITION)) {
1656 if (_session.transport_frame() != _next_cycle_start ||
1657 _session.transport_speed() != _next_cycle_speed) {
1658 // Transport has changed, write position at cycle start
1659 tmap.bbt_time(_session.transport_frame(), bbt);
1660 write_position(&_impl->forge, _ev_buffers[port_index],
1661 tmetric, bbt, _session.transport_speed(),
1662 _session.transport_frame(), 0);
1666 // Get MIDI iterator range (empty range if no MIDI)
1667 MidiBuffer::iterator m = (index != nil_index)
1668 ? bufs.get_midi(index).begin()
1669 : silent_bufs.get_midi(0).end();
1670 MidiBuffer::iterator m_end = (index != nil_index)
1671 ? bufs.get_midi(index).end()
1674 // Now merge MIDI and any transport events into the buffer
1675 const uint32_t type = LV2Plugin::urids.midi_MidiEvent;
1676 const framepos_t tend = _session.transport_frame() + nframes;
1678 while (m != m_end || (metric_i != tmap.metrics_end() &&
1679 (*metric_i)->frame() < tend)) {
1680 MetricSection* metric = (metric_i != tmap.metrics_end())
1682 if (m != m_end && (!metric || metric->frame() > (*m).time())) {
1683 const Evoral::MIDIEvent<framepos_t> ev(*m, false);
1684 LV2_Evbuf_Iterator eend = lv2_evbuf_end(_ev_buffers[port_index]);
1685 lv2_evbuf_write(&eend, ev.time(), 0, type, ev.size(), ev.buffer());
1688 tmetric.set_metric(metric);
1689 bbt = metric->start();
1690 write_position(&_impl->forge, _ev_buffers[port_index],
1691 tmetric, bbt, _session.transport_speed(),
1693 metric->frame() - _session.transport_frame());
1697 } else if (!valid) {
1698 // Nothing we understand or care about, connect to scratch
1699 // see note for midi-buffer size above
1700 scratch_bufs.ensure_lv2_bufsize((flags & PORT_INPUT),
1701 0, _port_minimumSize[port_index]);
1702 _ev_buffers[port_index] = scratch_bufs.get_lv2_midi(
1703 (flags & PORT_INPUT), 0, (flags & PORT_EVENT));
1705 buf = lv2_evbuf_get_buffer(_ev_buffers[port_index]);
1707 continue; // Control port, leave buffer alone
1709 lilv_instance_connect_port(_impl->instance, port_index, buf);
1712 // Read messages from UI and push into appropriate buffers
1714 uint32_t read_space = _from_ui->read_space();
1715 while (read_space > sizeof(UIMessage)) {
1717 if (_from_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1718 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
1721 uint8_t body[msg.size];
1722 if (_from_ui->read(body, msg.size) != msg.size) {
1723 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
1726 if (msg.protocol == urids.atom_eventTransfer) {
1727 LV2_Evbuf* buf = _ev_buffers[msg.index];
1728 LV2_Evbuf_Iterator i = lv2_evbuf_end(buf);
1729 const LV2_Atom* const atom = (const LV2_Atom*)body;
1730 if (!lv2_evbuf_write(&i, nframes, 0, atom->type, atom->size,
1731 (const uint8_t*)(atom + 1))) {
1732 error << "Failed to write data to LV2 event buffer\n";
1735 error << "Received unknown message type from UI" << endmsg;
1737 read_space -= sizeof(UIMessage) + msg.size;
1744 for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
1745 PortFlags flags = _port_flags[port_index];
1748 /* TODO ask drobilla about comment
1749 * "Make Ardour event buffers generic so plugins can communicate"
1750 * in libs/ardour/buffer_set.cc:310
1752 * ideally the user could choose which of the following two modes
1753 * to use (e.g. instrument/effect chains MIDI OUT vs MIDI TRHU).
1755 * This implementation follows the discussion on IRC Mar 16 2013 16:47 UTC
1756 * 16:51 < drobilla> rgareus: [..] i.e always replace with MIDI output [of LV2 plugin] if it's there
1757 * 16:52 < drobilla> rgareus: That would probably be good enough [..] to make users not complain
1758 * for quite a while at least ;)
1760 // copy output of LV2 plugin's MIDI port to Ardour MIDI buffers -- MIDI OUT
1761 if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE|PORT_MIDI))) {
1762 const uint32_t buf_index = out_map.get(
1763 DataType::MIDI, midi_out_index++, &valid);
1765 bufs.forward_lv2_midi(_ev_buffers[port_index], buf_index);
1768 // Flush MIDI (write back to Ardour MIDI buffers) -- MIDI THRU
1769 else if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
1770 const uint32_t buf_index = out_map.get(
1771 DataType::MIDI, midi_out_index++, &valid);
1773 bufs.flush_lv2_midi(true, buf_index);
1777 // Write messages to UI
1778 if (_to_ui && (flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
1779 LV2_Evbuf* buf = _ev_buffers[port_index];
1780 for (LV2_Evbuf_Iterator i = lv2_evbuf_begin(buf);
1781 lv2_evbuf_is_valid(i);
1782 i = lv2_evbuf_next(i)) {
1783 uint32_t frames, subframes, type, size;
1785 lv2_evbuf_get(i, &frames, &subframes, &type, &size, &data);
1786 write_to_ui(port_index, urids.atom_eventTransfer,
1787 size + sizeof(LV2_Atom),
1788 data - sizeof(LV2_Atom));
1793 cycles_t now = get_cycles();
1794 set_cycles((uint32_t)(now - then));
1796 // Update expected transport information for next cycle so we can detect changes
1797 _next_cycle_speed = _session.transport_speed();
1798 _next_cycle_start = _session.transport_frame() + (nframes * _next_cycle_speed);
1804 LV2Plugin::parameter_is_control(uint32_t param) const
1806 assert(param < _port_flags.size());
1807 return _port_flags[param] & PORT_CONTROL;
1811 LV2Plugin::parameter_is_audio(uint32_t param) const
1813 assert(param < _port_flags.size());
1814 return _port_flags[param] & PORT_AUDIO;
1818 LV2Plugin::parameter_is_event(uint32_t param) const
1820 assert(param < _port_flags.size());
1821 return _port_flags[param] & PORT_EVENT;
1825 LV2Plugin::parameter_is_output(uint32_t param) const
1827 assert(param < _port_flags.size());
1828 return _port_flags[param] & PORT_OUTPUT;
1832 LV2Plugin::parameter_is_input(uint32_t param) const
1834 assert(param < _port_flags.size());
1835 return _port_flags[param] & PORT_INPUT;
1839 LV2Plugin::print_parameter(uint32_t param, char* buf, uint32_t len) const
1842 if (param < parameter_count()) {
1843 snprintf(buf, len, "%.3f", get_parameter(param));
1850 boost::shared_ptr<Plugin::ScalePoints>
1851 LV2Plugin::get_scale_points(uint32_t port_index) const
1853 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, port_index);
1854 LilvScalePoints* points = lilv_port_get_scale_points(_impl->plugin, port);
1856 boost::shared_ptr<Plugin::ScalePoints> ret;
1861 ret = boost::shared_ptr<Plugin::ScalePoints>(new ScalePoints());
1863 LILV_FOREACH(scale_points, i, points) {
1864 const LilvScalePoint* p = lilv_scale_points_get(points, i);
1865 const LilvNode* label = lilv_scale_point_get_label(p);
1866 const LilvNode* value = lilv_scale_point_get_value(p);
1867 if (label && (lilv_node_is_float(value) || lilv_node_is_int(value))) {
1868 ret->insert(make_pair(lilv_node_as_string(label),
1869 lilv_node_as_float(value)));
1873 lilv_scale_points_free(points);
1878 LV2Plugin::run(pframes_t nframes)
1880 uint32_t const N = parameter_count();
1881 for (uint32_t i = 0; i < N; ++i) {
1882 if (parameter_is_control(i) && parameter_is_input(i)) {
1883 _control_data[i] = _shadow_data[i];
1887 lilv_instance_run(_impl->instance, nframes);
1889 if (_impl->work_iface) {
1890 _worker->emit_responses();
1891 if (_impl->work_iface->end_run) {
1892 _impl->work_iface->end_run(_impl->instance->lv2_handle);
1898 LV2Plugin::latency_compute_run()
1900 if (!_latency_control_port) {
1904 // Run the plugin so that it can set its latency parameter
1908 uint32_t port_index = 0;
1909 uint32_t in_index = 0;
1910 uint32_t out_index = 0;
1912 const framecnt_t bufsize = 1024;
1913 float buffer[bufsize];
1915 memset(buffer, 0, sizeof(float) * bufsize);
1917 // FIXME: Ensure plugins can handle in-place processing
1921 while (port_index < parameter_count()) {
1922 if (parameter_is_audio(port_index)) {
1923 if (parameter_is_input(port_index)) {
1924 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1926 } else if (parameter_is_output(port_index)) {
1927 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1939 LV2Plugin::Impl::designated_input (const char* uri, void** bufptrs[], void** bufptr)
1941 const LilvPort* port = NULL;
1942 LilvNode* designation = lilv_new_uri(_world.world, uri);
1943 port = lilv_plugin_get_port_by_designation(
1944 plugin, _world.lv2_InputPort, designation);
1945 lilv_node_free(designation);
1947 bufptrs[lilv_port_get_index(plugin, port)] = bufptr;
1952 static bool lv2_filter (const string& str, void* /*arg*/)
1954 /* Not a dotfile, has a prefix before a period, suffix is "lv2" */
1956 return str[0] != '.' && (str.length() > 3 && str.find (".lv2") == (str.length() - 4));
1960 LV2World::LV2World()
1961 : world(lilv_world_new())
1962 , _bundle_checked(false)
1964 lilv_world_load_all(world);
1966 atom_AtomPort = lilv_new_uri(world, LV2_ATOM__AtomPort);
1967 atom_Chunk = lilv_new_uri(world, LV2_ATOM__Chunk);
1968 atom_Sequence = lilv_new_uri(world, LV2_ATOM__Sequence);
1969 atom_bufferType = lilv_new_uri(world, LV2_ATOM__bufferType);
1970 atom_supports = lilv_new_uri(world, LV2_ATOM__supports);
1971 atom_eventTransfer = lilv_new_uri(world, LV2_ATOM__eventTransfer);
1972 ev_EventPort = lilv_new_uri(world, LILV_URI_EVENT_PORT);
1973 ext_logarithmic = lilv_new_uri(world, LV2_PORT_PROPS__logarithmic);
1974 ext_notOnGUI = lilv_new_uri(world, LV2_PORT_PROPS__notOnGUI);
1975 lv2_AudioPort = lilv_new_uri(world, LILV_URI_AUDIO_PORT);
1976 lv2_ControlPort = lilv_new_uri(world, LILV_URI_CONTROL_PORT);
1977 lv2_InputPort = lilv_new_uri(world, LILV_URI_INPUT_PORT);
1978 lv2_OutputPort = lilv_new_uri(world, LILV_URI_OUTPUT_PORT);
1979 lv2_inPlaceBroken = lilv_new_uri(world, LV2_CORE__inPlaceBroken);
1980 lv2_integer = lilv_new_uri(world, LV2_CORE__integer);
1981 lv2_reportsLatency = lilv_new_uri(world, LV2_CORE__reportsLatency);
1982 lv2_sampleRate = lilv_new_uri(world, LV2_CORE__sampleRate);
1983 lv2_toggled = lilv_new_uri(world, LV2_CORE__toggled);
1984 lv2_enumeration = lilv_new_uri(world, LV2_CORE__enumeration);
1985 lv2_freewheeling = lilv_new_uri(world, LV2_CORE__freeWheeling);
1986 midi_MidiEvent = lilv_new_uri(world, LILV_URI_MIDI_EVENT);
1987 rdfs_comment = lilv_new_uri(world, LILV_NS_RDFS "comment");
1988 rsz_minimumSize = lilv_new_uri(world, LV2_RESIZE_PORT__minimumSize);
1989 time_Position = lilv_new_uri(world, LV2_TIME__Position);
1990 ui_GtkUI = lilv_new_uri(world, LV2_UI__GtkUI);
1991 ui_external = lilv_new_uri(world, "http://lv2plug.in/ns/extensions/ui#external");
1992 ui_externalkx = lilv_new_uri(world, "http://kxstudio.sf.net/ns/lv2ext/external-ui#Widget");
1993 units_unit = lilv_new_uri(world, "http://lv2plug.in/ns/extensions/units#unit");
1994 units_midiNote = lilv_new_uri(world, "http://lv2plug.in/ns/extensions/units#midiNote");
1997 LV2World::~LV2World()
1999 lilv_node_free(units_midiNote);
2000 lilv_node_free(units_unit);
2001 lilv_node_free(ui_externalkx);
2002 lilv_node_free(ui_external);
2003 lilv_node_free(ui_GtkUI);
2004 lilv_node_free(time_Position);
2005 lilv_node_free(rsz_minimumSize);
2006 lilv_node_free(rdfs_comment);
2007 lilv_node_free(midi_MidiEvent);
2008 lilv_node_free(lv2_enumeration);
2009 lilv_node_free(lv2_freewheeling);
2010 lilv_node_free(lv2_toggled);
2011 lilv_node_free(lv2_sampleRate);
2012 lilv_node_free(lv2_reportsLatency);
2013 lilv_node_free(lv2_integer);
2014 lilv_node_free(lv2_inPlaceBroken);
2015 lilv_node_free(lv2_OutputPort);
2016 lilv_node_free(lv2_InputPort);
2017 lilv_node_free(lv2_ControlPort);
2018 lilv_node_free(lv2_AudioPort);
2019 lilv_node_free(ext_notOnGUI);
2020 lilv_node_free(ext_logarithmic);
2021 lilv_node_free(ev_EventPort);
2022 lilv_node_free(atom_supports);
2023 lilv_node_free(atom_eventTransfer);
2024 lilv_node_free(atom_bufferType);
2025 lilv_node_free(atom_Sequence);
2026 lilv_node_free(atom_Chunk);
2027 lilv_node_free(atom_AtomPort);
2031 LV2World::load_bundled_plugins()
2033 if (!_bundle_checked) {
2034 cout << "Scanning folders for bundled LV2s: " << ARDOUR::lv2_bundled_search_path().to_string() << endl;
2035 PathScanner scanner;
2036 vector<string *> *plugin_objects = scanner (ARDOUR::lv2_bundled_search_path().to_string(), lv2_filter, 0, true, true);
2037 if (plugin_objects) {
2038 for ( vector<string *>::iterator x = plugin_objects->begin(); x != plugin_objects->end (); ++x) {
2040 string uri = "file:///" + **x + "/";
2042 string uri = "file://" + **x + "/";
2044 LilvNode *node = lilv_new_uri(world, uri.c_str());
2045 lilv_world_load_bundle(world, node);
2046 lilv_node_free(node);
2049 delete (plugin_objects);
2051 _bundle_checked = true;
2055 LV2PluginInfo::LV2PluginInfo (const void* c_plugin)
2056 : _c_plugin(c_plugin)
2061 LV2PluginInfo::~LV2PluginInfo()
2065 LV2PluginInfo::load(Session& session)
2070 plugin.reset(new LV2Plugin(session.engine(), session,
2071 (const LilvPlugin*)_c_plugin,
2072 session.frame_rate()));
2074 plugin->set_info(PluginInfoPtr(new LV2PluginInfo(*this)));
2076 } catch (failed_constructor& err) {
2077 return PluginPtr((Plugin*)0);
2084 LV2PluginInfo::discover()
2086 _world.load_bundled_plugins();
2088 PluginInfoList* plugs = new PluginInfoList;
2089 const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
2091 info << "LV2: Discovering " << lilv_plugins_size(plugins) << " plugins" << endmsg;
2093 LILV_FOREACH(plugins, i, plugins) {
2094 const LilvPlugin* p = lilv_plugins_get(plugins, i);
2095 LV2PluginInfoPtr info(new LV2PluginInfo((const void*)p));
2097 LilvNode* name = lilv_plugin_get_name(p);
2098 if (!name || !lilv_plugin_get_port_by_index(p, 0)) {
2099 warning << "Ignoring invalid LV2 plugin "
2100 << lilv_node_as_string(lilv_plugin_get_uri(p))
2107 info->name = string(lilv_node_as_string(name));
2108 lilv_node_free(name);
2110 const LilvPluginClass* pclass = lilv_plugin_get_class(p);
2111 const LilvNode* label = lilv_plugin_class_get_label(pclass);
2112 info->category = lilv_node_as_string(label);
2114 LilvNode* author_name = lilv_plugin_get_author_name(p);
2115 info->creator = author_name ? string(lilv_node_as_string(author_name)) : "Unknown";
2116 lilv_node_free(author_name);
2118 info->path = "/NOPATH"; // Meaningless for LV2
2120 /* count atom-event-ports that feature
2121 * atom:supports <http://lv2plug.in/ns/ext/midi#MidiEvent>
2123 * TODO: nicely ask drobilla to make a lilv_ call for that
2125 int count_midi_out = 0;
2126 int count_midi_in = 0;
2127 for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
2128 const LilvPort* port = lilv_plugin_get_port_by_index(p, i);
2129 if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
2130 LilvNodes* buffer_types = lilv_port_get_value(
2131 p, port, _world.atom_bufferType);
2132 LilvNodes* atom_supports = lilv_port_get_value(
2133 p, port, _world.atom_supports);
2135 if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)
2136 && lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
2137 if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
2140 if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
2144 lilv_nodes_free(buffer_types);
2145 lilv_nodes_free(atom_supports);
2149 info->n_inputs.set_audio(
2150 lilv_plugin_get_num_ports_of_class(
2151 p, _world.lv2_InputPort, _world.lv2_AudioPort, NULL));
2152 info->n_inputs.set_midi(
2153 lilv_plugin_get_num_ports_of_class(
2154 p, _world.lv2_InputPort, _world.ev_EventPort, NULL)
2157 info->n_outputs.set_audio(
2158 lilv_plugin_get_num_ports_of_class(
2159 p, _world.lv2_OutputPort, _world.lv2_AudioPort, NULL));
2160 info->n_outputs.set_midi(
2161 lilv_plugin_get_num_ports_of_class(
2162 p, _world.lv2_OutputPort, _world.ev_EventPort, NULL)
2165 info->unique_id = lilv_node_as_uri(lilv_plugin_get_uri(p));
2166 info->index = 0; // Meaningless for LV2
2168 plugs->push_back(info);