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 <glib/gstdio.h>
29 #include <giomm/file.h>
30 #include <glib/gprintf.h>
33 #include <boost/utility.hpp>
35 #include "pbd/pathscanner.h"
36 #include "pbd/compose.h"
37 #include "pbd/error.h"
38 #include "pbd/xml++.h"
40 #include "libardour-config.h"
42 #include "ardour/audio_buffer.h"
43 #include "ardour/audioengine.h"
44 #include "ardour/debug.h"
45 #include "ardour/lv2_plugin.h"
46 #include "ardour/session.h"
47 #include "ardour/tempo.h"
48 #include "ardour/types.h"
49 #include "ardour/utils.h"
50 #include "ardour/worker.h"
51 #include "ardour/search_paths.h"
56 #include <lilv/lilv.h>
58 #include "lv2/lv2plug.in/ns/ext/atom/atom.h"
59 #include "lv2/lv2plug.in/ns/ext/atom/forge.h"
60 #include "lv2/lv2plug.in/ns/ext/log/log.h"
61 #include "lv2/lv2plug.in/ns/ext/midi/midi.h"
62 #include "lv2/lv2plug.in/ns/ext/port-props/port-props.h"
63 #include "lv2/lv2plug.in/ns/ext/presets/presets.h"
64 #include "lv2/lv2plug.in/ns/ext/state/state.h"
65 #include "lv2/lv2plug.in/ns/ext/time/time.h"
66 #include "lv2/lv2plug.in/ns/ext/worker/worker.h"
67 #include "lv2/lv2plug.in/ns/ext/resize-port/resize-port.h"
68 #include "lv2/lv2plug.in/ns/extensions/ui/ui.h"
70 #include "lv2/lv2plug.in/ns/ext/buf-size/buf-size.h"
71 #include "lv2/lv2plug.in/ns/ext/options/options.h"
74 #include "lv2_evbuf.h"
77 #include <suil/suil.h>
80 /** The number of MIDI buffers that will fit in a UI/worker comm buffer.
81 This needs to be roughly the number of cycles the UI will get around to
82 actually processing the traffic. Lower values are flakier but save memory.
84 static const size_t NBUFS = 4;
87 using namespace ARDOUR;
90 URIMap LV2Plugin::_uri_map;
92 LV2Plugin::URIDs LV2Plugin::urids = {
93 _uri_map.uri_to_id(LV2_ATOM__Chunk),
94 _uri_map.uri_to_id(LV2_ATOM__Path),
95 _uri_map.uri_to_id(LV2_ATOM__Sequence),
96 _uri_map.uri_to_id(LV2_ATOM__eventTransfer),
97 _uri_map.uri_to_id(LV2_LOG__Error),
98 _uri_map.uri_to_id(LV2_LOG__Note),
99 _uri_map.uri_to_id(LV2_LOG__Warning),
100 _uri_map.uri_to_id(LV2_MIDI__MidiEvent),
101 _uri_map.uri_to_id(LV2_TIME__Position),
102 _uri_map.uri_to_id(LV2_TIME__bar),
103 _uri_map.uri_to_id(LV2_TIME__barBeat),
104 _uri_map.uri_to_id(LV2_TIME__beatUnit),
105 _uri_map.uri_to_id(LV2_TIME__beatsPerBar),
106 _uri_map.uri_to_id(LV2_TIME__beatsPerMinute),
107 _uri_map.uri_to_id(LV2_TIME__frame),
108 _uri_map.uri_to_id(LV2_TIME__speed)
111 class LV2World : boost::noncopyable {
116 void load_bundled_plugins();
120 LilvNode* atom_AtomPort;
121 LilvNode* atom_Chunk;
122 LilvNode* atom_Sequence;
123 LilvNode* atom_bufferType;
124 LilvNode* atom_eventTransfer;
125 LilvNode* atom_supports;
126 LilvNode* ev_EventPort;
127 LilvNode* ext_logarithmic;
128 LilvNode* ext_notOnGUI;
129 LilvNode* lv2_AudioPort;
130 LilvNode* lv2_ControlPort;
131 LilvNode* lv2_InputPort;
132 LilvNode* lv2_OutputPort;
133 LilvNode* lv2_enumeration;
134 LilvNode* lv2_freewheeling;
135 LilvNode* lv2_inPlaceBroken;
136 LilvNode* lv2_integer;
137 LilvNode* lv2_reportsLatency;
138 LilvNode* lv2_sampleRate;
139 LilvNode* lv2_toggled;
140 LilvNode* midi_MidiEvent;
141 LilvNode* rdfs_comment;
142 LilvNode* rsz_minimumSize;
143 LilvNode* time_Position;
145 LilvNode* ui_external;
146 LilvNode* ui_externalkx;
147 LilvNode* units_unit;
148 LilvNode* units_midiNote;
151 bool _bundle_checked;
154 static LV2World _world;
156 /* worker extension */
158 /** Called by the plugin to schedule non-RT work. */
159 static LV2_Worker_Status
160 work_schedule(LV2_Worker_Schedule_Handle handle,
164 LV2Plugin* plugin = (LV2Plugin*)handle;
165 if (plugin->session().engine().freewheeling()) {
166 // Freewheeling, do the work immediately in this (audio) thread
167 return (LV2_Worker_Status)plugin->work(size, data);
169 // Enqueue message for the worker thread
170 return plugin->worker()->schedule(size, data) ?
171 LV2_WORKER_SUCCESS : LV2_WORKER_ERR_UNKNOWN;
175 /** Called by the plugin to respond to non-RT work. */
176 static LV2_Worker_Status
177 work_respond(LV2_Worker_Respond_Handle handle,
181 LV2Plugin* plugin = (LV2Plugin*)handle;
182 if (plugin->session().engine().freewheeling()) {
183 // Freewheeling, respond immediately in this (audio) thread
184 return (LV2_Worker_Status)plugin->work_response(size, data);
186 // Enqueue response for the worker
187 return plugin->worker()->respond(size, data) ?
188 LV2_WORKER_SUCCESS : LV2_WORKER_ERR_UNKNOWN;
195 log_vprintf(LV2_Log_Handle /*handle*/,
201 const int ret = g_vasprintf(&str, fmt, args);
202 if (type == LV2Plugin::urids.log_Error) {
203 error << str << endmsg;
204 } else if (type == LV2Plugin::urids.log_Warning) {
205 warning << str << endmsg;
206 } else if (type == LV2Plugin::urids.log_Note) {
207 info << str << endmsg;
209 // TODO: Toggleable log:Trace message support
214 log_printf(LV2_Log_Handle handle,
216 const char* fmt, ...)
220 const int ret = log_vprintf(handle, type, fmt, args);
225 struct LV2Plugin::Impl {
226 Impl() : plugin(0), ui(0), ui_type(0), name(0), author(0), instance(0)
231 /** Find the LV2 input port with the given designation.
232 * If found, bufptrs[port_index] will be set to bufptr.
234 const LilvPort* designated_input (const char* uri, void** bufptrs[], void** bufptr);
236 const LilvPlugin* plugin;
238 const LilvNode* ui_type;
241 LilvInstance* instance;
242 const LV2_Worker_Interface* work_iface;
244 LV2_Atom_Forge forge;
247 LV2Plugin::LV2Plugin (AudioEngine& engine,
249 const void* c_plugin,
251 : Plugin (engine, session)
258 init(c_plugin, rate);
261 LV2Plugin::LV2Plugin (const LV2Plugin& other)
267 , _insert_id(other._insert_id)
269 init(other._impl->plugin, other._sample_rate);
271 for (uint32_t i = 0; i < parameter_count(); ++i) {
272 _control_data[i] = other._shadow_data[i];
273 _shadow_data[i] = other._shadow_data[i];
278 LV2Plugin::init(const void* c_plugin, framecnt_t rate)
280 DEBUG_TRACE(DEBUG::LV2, "init\n");
282 _impl->plugin = (const LilvPlugin*)c_plugin;
284 _impl->ui_type = NULL;
289 _atom_ev_buffers = 0;
291 _bpm_control_port = 0;
292 _freewheel_control_port = 0;
293 _latency_control_port = 0;
294 _next_cycle_start = std::numeric_limits<framepos_t>::max();
295 _next_cycle_speed = 1.0;
296 _block_length = _engine.samples_per_cycle();
297 _seq_size = _engine.raw_buffer_size(DataType::MIDI);
299 _was_activated = false;
300 _has_state_interface = false;
302 _instance_access_feature.URI = "http://lv2plug.in/ns/ext/instance-access";
303 _data_access_feature.URI = "http://lv2plug.in/ns/ext/data-access";
304 _make_path_feature.URI = LV2_STATE__makePath;
305 _log_feature.URI = LV2_LOG__log;
306 _work_schedule_feature.URI = LV2_WORKER__schedule;
307 _work_schedule_feature.data = NULL;
308 _def_state_feature.URI = LV2_STATE_PREFIX "loadDefaultState"; // Post LV2-1.2.0
309 _def_state_feature.data = NULL;
311 const LilvPlugin* plugin = _impl->plugin;
313 LilvNode* state_iface_uri = lilv_new_uri(_world.world, LV2_STATE__interface);
314 LilvNode* state_uri = lilv_new_uri(_world.world, LV2_STATE_URI);
315 _has_state_interface =
316 // What plugins should have (lv2:extensionData state:Interface)
317 lilv_plugin_has_extension_data(plugin, state_iface_uri)
318 // What some outdated/incorrect ones have
319 || lilv_plugin_has_feature(plugin, state_uri);
320 lilv_node_free(state_uri);
321 lilv_node_free(state_iface_uri);
323 _features = (LV2_Feature**)calloc(11, sizeof(LV2_Feature*));
324 _features[0] = &_instance_access_feature;
325 _features[1] = &_data_access_feature;
326 _features[2] = &_make_path_feature;
327 _features[3] = _uri_map.uri_map_feature();
328 _features[4] = _uri_map.urid_map_feature();
329 _features[5] = _uri_map.urid_unmap_feature();
330 _features[6] = &_log_feature;
332 unsigned n_features = 7;
334 _features[n_features++] = &_def_state_feature;
337 lv2_atom_forge_init(&_impl->forge, _uri_map.urid_map());
340 LV2_URID atom_Int = _uri_map.uri_to_id(LV2_ATOM__Int);
341 LV2_Options_Option options[] = {
342 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__minBlockLength),
343 sizeof(int32_t), atom_Int, &_block_length },
344 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__maxBlockLength),
345 sizeof(int32_t), atom_Int, &_block_length },
346 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__sequenceSize),
347 sizeof(int32_t), atom_Int, &_seq_size },
348 { LV2_OPTIONS_INSTANCE, 0, 0, 0, 0, NULL }
351 _options_feature.URI = LV2_OPTIONS__options;
352 _options_feature.data = options;
353 _features[n_features++] = &_options_feature;
356 LV2_State_Make_Path* make_path = (LV2_State_Make_Path*)malloc(
357 sizeof(LV2_State_Make_Path));
358 make_path->handle = this;
359 make_path->path = &lv2_state_make_path;
360 _make_path_feature.data = make_path;
362 LV2_Log_Log* log = (LV2_Log_Log*)malloc(sizeof(LV2_Log_Log));
364 log->printf = &log_printf;
365 log->vprintf = &log_vprintf;
366 _log_feature.data = log;
368 LilvNode* worker_schedule = lilv_new_uri(_world.world, LV2_WORKER__schedule);
369 if (lilv_plugin_has_feature(plugin, worker_schedule)) {
370 LV2_Worker_Schedule* schedule = (LV2_Worker_Schedule*)malloc(
371 sizeof(LV2_Worker_Schedule));
372 size_t buf_size = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
373 _worker = new Worker(this, buf_size);
374 schedule->handle = this;
375 schedule->schedule_work = work_schedule;
376 _work_schedule_feature.data = schedule;
377 _features[n_features++] = &_work_schedule_feature;
379 lilv_node_free(worker_schedule);
381 _impl->instance = lilv_plugin_instantiate(plugin, rate, _features);
382 _impl->name = lilv_plugin_get_name(plugin);
383 _impl->author = lilv_plugin_get_author_name(plugin);
385 if (_impl->instance == 0) {
386 error << _("LV2: Failed to instantiate plugin ") << uri() << endmsg;
387 throw failed_constructor();
390 _instance_access_feature.data = (void*)_impl->instance->lv2_handle;
391 _data_access_extension_data.extension_data = _impl->instance->lv2_descriptor->extension_data;
392 _data_access_feature.data = &_data_access_extension_data;
394 LilvNode* worker_iface_uri = lilv_new_uri(_world.world, LV2_WORKER__interface);
395 if (lilv_plugin_has_extension_data(plugin, worker_iface_uri)) {
396 _impl->work_iface = (const LV2_Worker_Interface*)extension_data(
397 LV2_WORKER__interface);
399 lilv_node_free(worker_iface_uri);
401 if (lilv_plugin_has_feature(plugin, _world.lv2_inPlaceBroken)) {
402 error << string_compose(
403 _("LV2: \"%1\" cannot be used, since it cannot do inplace processing"),
404 lilv_node_as_string(_impl->name)) << endmsg;
405 lilv_node_free(_impl->name);
406 lilv_node_free(_impl->author);
407 throw failed_constructor();
411 // Load default state
412 LilvState* state = lilv_state_new_from_world(
413 _world.world, _uri_map.urid_map(), lilv_plugin_get_uri(_impl->plugin));
414 if (state && _has_state_interface) {
415 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
421 const uint32_t num_ports = this->num_ports();
422 for (uint32_t i = 0; i < num_ports; ++i) {
423 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, i);
425 size_t minimumSize = 0;
427 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_OutputPort)) {
428 flags |= PORT_OUTPUT;
429 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_InputPort)) {
432 error << string_compose(
433 "LV2: \"%1\" port %2 is neither input nor output",
434 lilv_node_as_string(_impl->name), i) << endmsg;
435 throw failed_constructor();
438 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_ControlPort)) {
439 flags |= PORT_CONTROL;
440 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_AudioPort)) {
442 } else if (lilv_port_is_a(_impl->plugin, port, _world.ev_EventPort)) {
444 flags |= PORT_MIDI; // We assume old event API ports are for MIDI
445 } else if (lilv_port_is_a(_impl->plugin, port, _world.atom_AtomPort)) {
446 LilvNodes* buffer_types = lilv_port_get_value(
447 _impl->plugin, port, _world.atom_bufferType);
448 LilvNodes* atom_supports = lilv_port_get_value(
449 _impl->plugin, port, _world.atom_supports);
451 if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)) {
452 flags |= PORT_SEQUENCE;
453 if (lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
456 if (lilv_nodes_contains(atom_supports, _world.time_Position)) {
457 flags |= PORT_POSITION;
460 LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
461 LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
462 if (min_size && lilv_node_is_int(min_size)) {
463 minimumSize = lilv_node_as_int(min_size);
465 lilv_nodes_free(min_size_v);
466 lilv_nodes_free(buffer_types);
467 lilv_nodes_free(atom_supports);
469 error << string_compose(
470 "LV2: \"%1\" port %2 has no known data type",
471 lilv_node_as_string(_impl->name), i) << endmsg;
472 throw failed_constructor();
475 _port_flags.push_back(flags);
476 _port_minimumSize.push_back(minimumSize);
479 _control_data = new float[num_ports];
480 _shadow_data = new float[num_ports];
481 _defaults = new float[num_ports];
482 _ev_buffers = new LV2_Evbuf*[num_ports];
483 memset(_ev_buffers, 0, sizeof(LV2_Evbuf*) * num_ports);
485 const bool latent = lilv_plugin_has_latency(plugin);
486 const uint32_t latency_index = (latent)
487 ? lilv_plugin_get_latency_port_index(plugin)
490 // Build an array of pointers to special parameter buffers
491 void*** params = new void**[num_ports];
492 for (uint32_t i = 0; i < num_ports; ++i) {
495 _impl->designated_input (LV2_TIME__beatsPerMinute, params, (void**)&_bpm_control_port);
496 _impl->designated_input (LV2_CORE__freeWheeling, params, (void**)&_freewheel_control_port);
498 for (uint32_t i = 0; i < num_ports; ++i) {
499 const LilvPort* port = lilv_plugin_get_port_by_index(plugin, i);
500 const LilvNode* sym = lilv_port_get_symbol(plugin, port);
502 // Store index in map so we can look up index by symbol
503 _port_indices.insert(std::make_pair(lilv_node_as_string(sym), i));
505 // Get range and default value if applicable
506 if (parameter_is_control(i)) {
508 lilv_port_get_range(plugin, port, &def, NULL, NULL);
509 _defaults[i] = def ? lilv_node_as_float(def) : 0.0f;
510 if (lilv_port_has_property (plugin, port, _world.lv2_sampleRate)) {
511 _defaults[i] *= _session.frame_rate ();
515 lilv_instance_connect_port(_impl->instance, i, &_control_data[i]);
517 if (latent && i == latency_index) {
518 _latency_control_port = &_control_data[i];
519 *_latency_control_port = 0;
522 if (parameter_is_input(i)) {
523 _shadow_data[i] = default_value(i);
525 *params[i] = (void*)&_shadow_data[i];
535 LilvUIs* uis = lilv_plugin_get_uis(plugin);
536 if (lilv_uis_size(uis) > 0) {
538 // Look for embeddable UI
539 LILV_FOREACH(uis, u, uis) {
540 const LilvUI* this_ui = lilv_uis_get(uis, u);
541 const LilvNode* this_ui_type = NULL;
542 if (lilv_ui_is_supported(this_ui,
546 // TODO: Multiple UI support
548 _impl->ui_type = this_ui_type;
553 // Look for Gtk native UI
554 LILV_FOREACH(uis, i, uis) {
555 const LilvUI* ui = lilv_uis_get(uis, i);
556 if (lilv_ui_is_a(ui, _world.ui_GtkUI)) {
558 _impl->ui_type = _world.ui_GtkUI;
564 // If Gtk UI is not available, try to find external UI
566 LILV_FOREACH(uis, i, uis) {
567 const LilvUI* ui = lilv_uis_get(uis, i);
568 if (lilv_ui_is_a(ui, _world.ui_externalkx)) {
570 _impl->ui_type = _world.ui_external;
573 if (lilv_ui_is_a(ui, _world.ui_external)) {
575 _impl->ui_type = _world.ui_external;
581 allocate_atom_event_buffers();
582 latency_compute_run();
585 LV2Plugin::~LV2Plugin ()
587 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 destroy\n", name()));
592 lilv_instance_free(_impl->instance);
593 lilv_node_free(_impl->name);
594 lilv_node_free(_impl->author);
597 free(_make_path_feature.data);
598 free(_work_schedule_feature.data);
604 if (_atom_ev_buffers) {
605 LV2_Evbuf** b = _atom_ev_buffers;
610 free(_atom_ev_buffers);
613 delete [] _control_data;
614 delete [] _shadow_data;
615 delete [] _ev_buffers;
619 LV2Plugin::is_external_ui() const
624 return lilv_ui_is_a(_impl->ui, _world.ui_external) || lilv_ui_is_a(_impl->ui, _world.ui_externalkx);
628 LV2Plugin::is_external_kx() const
633 return lilv_ui_is_a(_impl->ui, _world.ui_externalkx);
637 LV2Plugin::ui_is_resizable () const
639 const LilvNode* s = lilv_ui_get_uri(_impl->ui);
640 LilvNode* p = lilv_new_uri(_world.world, LV2_CORE__optionalFeature);
641 LilvNode* fs = lilv_new_uri(_world.world, LV2_UI__fixedSize);
642 LilvNode* nrs = lilv_new_uri(_world.world, LV2_UI__noUserResize);
644 LilvNodes* fs_matches = lilv_world_find_nodes(_world.world, s, p, fs);
645 LilvNodes* nrs_matches = lilv_world_find_nodes(_world.world, s, p, nrs);
647 lilv_nodes_free(nrs_matches);
648 lilv_nodes_free(fs_matches);
653 return !fs_matches && !nrs_matches;
657 LV2Plugin::unique_id() const
659 return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
663 LV2Plugin::uri() const
665 return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
669 LV2Plugin::label() const
671 return lilv_node_as_string(_impl->name);
675 LV2Plugin::name() const
677 return lilv_node_as_string(_impl->name);
681 LV2Plugin::maker() const
683 return _impl->author ? lilv_node_as_string (_impl->author) : "Unknown";
687 LV2Plugin::num_ports() const
689 return lilv_plugin_get_num_ports(_impl->plugin);
693 LV2Plugin::parameter_count() const
695 return lilv_plugin_get_num_ports(_impl->plugin);
699 LV2Plugin::default_value(uint32_t port)
701 return _defaults[port];
705 LV2Plugin::port_symbol(uint32_t index) const
707 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, index);
709 error << name() << ": Invalid port index " << index << endmsg;
712 const LilvNode* sym = lilv_port_get_symbol(_impl->plugin, port);
713 return lilv_node_as_string(sym);
717 LV2Plugin::port_index (const char* symbol) const
719 const map<string, uint32_t>::const_iterator i = _port_indices.find(symbol);
720 if (i != _port_indices.end()) {
723 warning << string_compose(_("LV2: Unknown port %1"), symbol) << endmsg;
729 LV2Plugin::set_parameter(uint32_t which, float val)
731 DEBUG_TRACE(DEBUG::LV2, string_compose(
732 "%1 set parameter %2 to %3\n", name(), which, val));
734 if (which < lilv_plugin_get_num_ports(_impl->plugin)) {
735 if (get_parameter (which) == val) {
739 _shadow_data[which] = val;
741 warning << string_compose(
742 _("Illegal parameter number used with plugin \"%1\". "
743 "This is a bug in either %2 or the LV2 plugin <%3>"),
744 name(), PROGRAM_NAME, unique_id()) << endmsg;
747 Plugin::set_parameter(which, val);
751 LV2Plugin::get_parameter(uint32_t which) const
753 if (parameter_is_input(which)) {
754 return (float)_shadow_data[which];
756 return (float)_control_data[which];
762 LV2Plugin::get_docs() const
764 LilvNodes* comments = lilv_plugin_get_value(_impl->plugin, _world.rdfs_comment);
766 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
767 lilv_nodes_free(comments);
775 LV2Plugin::get_parameter_docs(uint32_t which) const
777 LilvNodes* comments = lilv_port_get_value(
779 lilv_plugin_get_port_by_index(_impl->plugin, which),
780 _world.rdfs_comment);
783 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
784 lilv_nodes_free(comments);
792 LV2Plugin::nth_parameter(uint32_t n, bool& ok) const
795 for (uint32_t c = 0, x = 0; x < lilv_plugin_get_num_ports(_impl->plugin); ++x) {
796 if (parameter_is_control(x)) {
808 LV2Plugin::extension_data(const char* uri) const
810 return lilv_instance_get_extension_data(_impl->instance, uri);
814 LV2Plugin::c_plugin()
816 return _impl->plugin;
822 return (const void*)_impl->ui;
826 LV2Plugin::c_ui_type()
828 return (const void*)_impl->ui_type;
831 /** Directory for all plugin state. */
833 LV2Plugin::plugin_dir() const
835 return Glib::build_filename(_session.plugins_dir(), _insert_id.to_s());
838 /** Directory for files created by the plugin (except during save). */
840 LV2Plugin::scratch_dir() const
842 return Glib::build_filename(plugin_dir(), "scratch");
845 /** Directory for snapshots of files in the scratch directory. */
847 LV2Plugin::file_dir() const
849 return Glib::build_filename(plugin_dir(), "files");
852 /** Directory to save state snapshot version @c num into. */
854 LV2Plugin::state_dir(unsigned num) const
856 return Glib::build_filename(plugin_dir(), string_compose("state%1", num));
859 /** Implementation of state:makePath for files created at instantiation time.
860 * Note this is not used for files created at save time (Lilv deals with that).
863 LV2Plugin::lv2_state_make_path(LV2_State_Make_Path_Handle handle,
866 LV2Plugin* me = (LV2Plugin*)handle;
867 if (me->_insert_id == PBD::ID("0")) {
868 warning << string_compose(
869 "File path \"%1\" requested but LV2 %2 has no insert ID",
870 path, me->name()) << endmsg;
871 return g_strdup(path);
874 const std::string abs_path = Glib::build_filename(me->scratch_dir(), path);
875 const std::string dirname = Glib::path_get_dirname(abs_path);
876 g_mkdir_with_parents(dirname.c_str(), 0744);
878 DEBUG_TRACE(DEBUG::LV2, string_compose("new file path %1 => %2\n",
881 return g_strndup(abs_path.c_str(), abs_path.length());
885 remove_directory(const std::string& path)
887 if (!Glib::file_test(path, Glib::FILE_TEST_IS_DIR)) {
888 warning << string_compose("\"%1\" is not a directory", path) << endmsg;
892 Glib::RefPtr<Gio::File> dir = Gio::File::create_for_path(path);
893 Glib::RefPtr<Gio::FileEnumerator> e = dir->enumerate_children();
894 Glib::RefPtr<Gio::FileInfo> fi;
895 while ((fi = e->next_file())) {
896 if (fi->get_type() == Gio::FILE_TYPE_DIRECTORY) {
897 remove_directory(fi->get_name());
899 dir->get_child(fi->get_name())->remove();
906 LV2Plugin::add_state(XMLNode* root) const
908 assert(_insert_id != PBD::ID("0"));
912 LocaleGuard lg(X_("POSIX"));
914 for (uint32_t i = 0; i < parameter_count(); ++i) {
915 if (parameter_is_input(i) && parameter_is_control(i)) {
916 child = new XMLNode("Port");
917 child->add_property("symbol", port_symbol(i));
918 snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
919 child->add_property("value", string(buf));
920 root->add_child_nocopy(*child);
924 if (_has_state_interface) {
925 // Provisionally increment state version and create directory
926 const std::string new_dir = state_dir(++_state_version);
927 g_mkdir_with_parents(new_dir.c_str(), 0744);
929 LilvState* state = lilv_state_new_from_instance(
933 scratch_dir().c_str(),
935 _session.externals_dir().c_str(),
938 const_cast<LV2Plugin*>(this),
942 if (!_impl->state || !lilv_state_equals(state, _impl->state)) {
943 lilv_state_save(_world.world,
945 _uri_map.urid_unmap(),
951 lilv_state_free(_impl->state);
952 _impl->state = state;
954 // State is identical, decrement version and nuke directory
955 lilv_state_free(state);
956 remove_directory(new_dir);
960 root->add_property("state-dir", string_compose("state%1", _state_version));
964 static inline const LilvNode*
965 get_value(LilvWorld* world, const LilvNode* subject, const LilvNode* predicate)
967 LilvNodes* vs = lilv_world_find_nodes(world, subject, predicate, NULL);
968 return vs ? lilv_nodes_get_first(vs) : NULL;
972 LV2Plugin::find_presets()
974 LilvNode* lv2_appliesTo = lilv_new_uri(_world.world, LV2_CORE__appliesTo);
975 LilvNode* pset_Preset = lilv_new_uri(_world.world, LV2_PRESETS__Preset);
976 LilvNode* rdfs_label = lilv_new_uri(_world.world, LILV_NS_RDFS "label");
978 LilvNodes* presets = lilv_plugin_get_related(_impl->plugin, pset_Preset);
979 LILV_FOREACH(nodes, i, presets) {
980 const LilvNode* preset = lilv_nodes_get(presets, i);
981 lilv_world_load_resource(_world.world, preset);
982 const LilvNode* name = get_value(_world.world, preset, rdfs_label);
984 _presets.insert(std::make_pair(lilv_node_as_string(preset),
985 Plugin::PresetRecord(
986 lilv_node_as_string(preset),
987 lilv_node_as_string(name))));
989 warning << string_compose(
990 _("Plugin \"%1\" preset \"%2\" is missing a label\n"),
991 lilv_node_as_string(lilv_plugin_get_uri(_impl->plugin)),
992 lilv_node_as_string(preset)) << endmsg;
995 lilv_nodes_free(presets);
997 lilv_node_free(rdfs_label);
998 lilv_node_free(pset_Preset);
999 lilv_node_free(lv2_appliesTo);
1003 set_port_value(const char* port_symbol,
1009 LV2Plugin* self = (LV2Plugin*)user_data;
1010 if (type != 0 && type != self->_uri_map.uri_to_id(LV2_ATOM__Float)) {
1011 return; // TODO: Support non-float ports
1014 const uint32_t port_index = self->port_index(port_symbol);
1015 if (port_index != (uint32_t)-1) {
1016 self->set_parameter(port_index, *(const float*)value);
1021 LV2Plugin::load_preset(PresetRecord r)
1023 LilvWorld* world = _world.world;
1024 LilvNode* pset = lilv_new_uri(world, r.uri.c_str());
1025 LilvState* state = lilv_state_new_from_world(world, _uri_map.urid_map(), pset);
1028 lilv_state_restore(state, _impl->instance, set_port_value, this, 0, NULL);
1029 lilv_state_free(state);
1030 Plugin::load_preset(r);
1033 lilv_node_free(pset);
1038 ARDOUR::lv2plugin_get_port_value(const char* port_symbol,
1043 LV2Plugin *plugin = (LV2Plugin *) user_data;
1045 uint32_t index = plugin->port_index(port_symbol);
1046 if (index != (uint32_t) -1) {
1047 if (plugin->parameter_is_input(index) && plugin->parameter_is_control(index)) {
1049 *size = sizeof(float);
1050 *type = plugin->_uri_map.uri_to_id(LV2_ATOM__Float);
1051 value = &plugin->_shadow_data[index];
1063 LV2Plugin::do_save_preset(string name)
1065 const string base_name = legalize_for_uri(name);
1066 const string file_name = base_name + ".ttl";
1067 const string bundle = Glib::build_filename(
1068 Glib::get_home_dir(),
1069 Glib::build_filename(".lv2", base_name + ".lv2"));
1071 LilvState* state = lilv_state_new_from_instance(
1074 _uri_map.urid_map(),
1075 scratch_dir().c_str(), // file_dir
1076 bundle.c_str(), // copy_dir
1077 bundle.c_str(), // link_dir
1078 bundle.c_str(), // save_dir
1079 lv2plugin_get_port_value, // get_value
1080 (void*)this, // user_data
1081 LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE, // flags
1082 _features // features
1085 lilv_state_set_label(state, name.c_str());
1087 _world.world, // world
1088 _uri_map.urid_map(), // map
1089 _uri_map.urid_unmap(), // unmap
1091 NULL, // uri (NULL = use file URI)
1092 bundle.c_str(), // dir
1093 file_name.c_str() // filename
1096 lilv_state_free(state);
1098 std::string uri = Glib::filename_to_uri(Glib::build_filename(bundle, file_name));
1099 LilvNode *node_bundle = lilv_new_uri(_world.world, Glib::filename_to_uri(Glib::build_filename(bundle, "/")).c_str());
1100 LilvNode *node_preset = lilv_new_uri(_world.world, uri.c_str());
1101 lilv_world_load_bundle(_world.world, node_bundle);
1102 lilv_world_load_resource(_world.world, node_preset);
1103 lilv_node_free(node_bundle);
1104 lilv_node_free(node_preset);
1109 LV2Plugin::do_remove_preset(string name)
1111 string preset_file = Glib::build_filename(
1112 Glib::get_home_dir(),
1113 Glib::build_filename(
1114 Glib::build_filename(".lv2", "presets"),
1118 ::g_unlink(preset_file.c_str());
1122 LV2Plugin::has_editor() const
1124 return _impl->ui != NULL;
1128 LV2Plugin::has_message_output() const
1130 for (uint32_t i = 0; i < num_ports(); ++i) {
1131 if ((_port_flags[i] & PORT_SEQUENCE) &&
1132 (_port_flags[i] & PORT_OUTPUT)) {
1140 LV2Plugin::write_to(RingBuffer<uint8_t>* dest,
1144 const uint8_t* body)
1146 const uint32_t buf_size = sizeof(UIMessage) + size;
1147 vector<uint8_t> buf(buf_size);
1149 UIMessage* msg = (UIMessage*)&buf[0];
1151 msg->protocol = protocol;
1153 memcpy(msg + 1, body, size);
1155 return (dest->write(&buf[0], buf_size) == buf_size);
1159 LV2Plugin::write_from_ui(uint32_t index,
1162 const uint8_t* body)
1165 size_t rbs = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
1166 /* buffer data communication from plugin UI to plugin instance.
1167 * this buffer needs to potentially hold
1168 * (port's minimumSize) * (audio-periods) / (UI-periods)
1171 * e.g 48kSPS / 128fpp -> audio-periods = 375 Hz
1172 * ui-periods = 25 Hz (SuperRapidScreenUpdate)
1173 * default minimumSize = 32K (see LV2Plugin::allocate_atom_event_buffers()
1175 * it is NOT safe to overflow (msg.size will be misinterpreted)
1177 uint32_t bufsiz = 32768;
1178 if (_atom_ev_buffers && _atom_ev_buffers[0]) {
1179 bufsiz = lv2_evbuf_get_capacity(_atom_ev_buffers[0]);
1181 rbs = max((size_t) bufsiz * 8, rbs);
1182 _from_ui = new RingBuffer<uint8_t>(rbs);
1185 if (!write_to(_from_ui, index, protocol, size, body)) {
1186 error << "Error writing from UI to plugin" << endmsg;
1193 LV2Plugin::write_to_ui(uint32_t index,
1196 const uint8_t* body)
1198 if (!write_to(_to_ui, index, protocol, size, body)) {
1199 error << "Error writing from plugin to UI" << endmsg;
1206 LV2Plugin::enable_ui_emmission()
1209 /* see note in LV2Plugin::write_from_ui() */
1210 uint32_t bufsiz = 32768;
1211 if (_atom_ev_buffers && _atom_ev_buffers[0]) {
1212 bufsiz = lv2_evbuf_get_capacity(_atom_ev_buffers[0]);
1214 size_t rbs = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
1215 rbs = max((size_t) bufsiz * 8, rbs);
1216 _to_ui = new RingBuffer<uint8_t>(rbs);
1221 LV2Plugin::emit_to_ui(void* controller, UIMessageSink sink)
1227 uint32_t read_space = _to_ui->read_space();
1228 while (read_space > sizeof(UIMessage)) {
1230 if (_to_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1231 error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1234 vector<uint8_t> body(msg.size);
1235 if (_to_ui->read(&body[0], msg.size) != msg.size) {
1236 error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1240 sink(controller, msg.index, msg.size, msg.protocol, &body[0]);
1242 read_space -= sizeof(msg) + msg.size;
1247 LV2Plugin::work(uint32_t size, const void* data)
1249 return _impl->work_iface->work(
1250 _impl->instance->lv2_handle, work_respond, this, size, data);
1254 LV2Plugin::work_response(uint32_t size, const void* data)
1256 return _impl->work_iface->work_response(
1257 _impl->instance->lv2_handle, size, data);
1261 LV2Plugin::set_insert_info(const PluginInsert* insert)
1263 _insert_id = insert->id();
1267 LV2Plugin::set_state(const XMLNode& node, int version)
1270 const XMLProperty* prop;
1271 XMLNodeConstIterator iter;
1276 LocaleGuard lg(X_("POSIX"));
1278 if (node.name() != state_node_name()) {
1279 error << _("Bad node sent to LV2Plugin::set_state") << endmsg;
1283 #ifndef NO_PLUGIN_STATE
1285 if (version < 3000) {
1286 nodes = node.children("port");
1288 nodes = node.children("Port");
1291 for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
1295 if ((prop = child->property("symbol")) != 0) {
1296 sym = prop->value().c_str();
1298 warning << _("LV2: port has no symbol, ignored") << endmsg;
1302 map<string, uint32_t>::iterator i = _port_indices.find(sym);
1304 if (i != _port_indices.end()) {
1305 port_id = i->second;
1307 warning << _("LV2: port has unknown index, ignored") << endmsg;
1311 if ((prop = child->property("value")) != 0) {
1312 value = prop->value().c_str();
1314 warning << _("LV2: port has no value, ignored") << endmsg;
1318 set_parameter(port_id, atof(value));
1322 if ((prop = node.property("state-dir")) != 0) {
1323 if (sscanf(prop->value().c_str(), "state%u", &_state_version) != 1) {
1324 error << string_compose(
1325 "LV2: failed to parse state version from \"%1\"",
1326 prop->value()) << endmsg;
1329 std::string state_file = Glib::build_filename(
1331 Glib::build_filename(prop->value(), "state.ttl"));
1333 LilvState* state = lilv_state_new_from_file(
1334 _world.world, _uri_map.urid_map(), NULL, state_file.c_str());
1336 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
1339 latency_compute_run();
1342 return Plugin::set_state(node, version);
1346 LV2Plugin::get_parameter_descriptor(uint32_t which, ParameterDescriptor& desc) const
1348 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, which);
1350 LilvNodes* portunits;
1351 LilvNode *def, *min, *max;
1352 lilv_port_get_range(_impl->plugin, port, &def, &min, &max);
1353 portunits = lilv_port_get_value(_impl->plugin, port, _world.units_unit);
1355 desc.integer_step = lilv_port_has_property(_impl->plugin, port, _world.lv2_integer);
1356 desc.toggled = lilv_port_has_property(_impl->plugin, port, _world.lv2_toggled);
1357 desc.logarithmic = lilv_port_has_property(_impl->plugin, port, _world.ext_logarithmic);
1358 desc.sr_dependent = lilv_port_has_property(_impl->plugin, port, _world.lv2_sampleRate);
1359 desc.label = lilv_node_as_string(lilv_port_get_name(_impl->plugin, port));
1360 desc.lower = min ? lilv_node_as_float(min) : 0.0f;
1361 desc.upper = max ? lilv_node_as_float(max) : 1.0f;
1362 desc.midinote = lilv_nodes_contains(portunits, _world.units_midiNote);
1364 if (desc.sr_dependent) {
1365 desc.lower *= _session.frame_rate ();
1366 desc.upper *= _session.frame_rate ();
1369 desc.min_unbound = false; // TODO: LV2 extension required
1370 desc.max_unbound = false; // TODO: LV2 extension required
1372 if (desc.integer_step) {
1374 desc.smallstep = 0.1;
1375 desc.largestep = 10.0;
1377 const float delta = desc.upper - desc.lower;
1378 desc.step = delta / 1000.0f;
1379 desc.smallstep = delta / 10000.0f;
1380 desc.largestep = delta / 10.0f;
1383 desc.enumeration = lilv_port_has_property(_impl->plugin, port, _world.lv2_enumeration);
1385 lilv_node_free(def);
1386 lilv_node_free(min);
1387 lilv_node_free(max);
1388 lilv_nodes_free(portunits);
1394 LV2Plugin::describe_parameter(Evoral::Parameter which)
1396 if (( which.type() == PluginAutomation) && ( which.id() < parameter_count()) ) {
1398 if (lilv_port_has_property(_impl->plugin,
1399 lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.ext_notOnGUI)) {
1400 return X_("hidden");
1403 if (lilv_port_has_property(_impl->plugin,
1404 lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_freewheeling)) {
1405 return X_("hidden");
1408 if (lilv_port_has_property(_impl->plugin,
1409 lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_reportsLatency)) {
1410 return X_("latency");
1413 LilvNode* name = lilv_port_get_name(_impl->plugin,
1414 lilv_plugin_get_port_by_index(_impl->plugin, which.id()));
1415 string ret(lilv_node_as_string(name));
1416 lilv_node_free(name);
1424 LV2Plugin::signal_latency() const
1426 if (_latency_control_port) {
1427 return (framecnt_t)floor(*_latency_control_port);
1433 set<Evoral::Parameter>
1434 LV2Plugin::automatable() const
1436 set<Evoral::Parameter> ret;
1438 for (uint32_t i = 0; i < parameter_count(); ++i) {
1439 if (parameter_is_input(i) && parameter_is_control(i)) {
1440 ret.insert(ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
1448 LV2Plugin::activate()
1450 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 activate\n", name()));
1452 if (!_was_activated) {
1453 lilv_instance_activate(_impl->instance);
1454 _was_activated = true;
1459 LV2Plugin::deactivate()
1461 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 deactivate\n", name()));
1463 if (_was_activated) {
1464 lilv_instance_deactivate(_impl->instance);
1465 _was_activated = false;
1470 LV2Plugin::cleanup()
1472 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 cleanup\n", name()));
1476 lilv_instance_free(_impl->instance);
1477 _impl->instance = NULL;
1481 LV2Plugin::allocate_atom_event_buffers()
1483 /* reserve local scratch buffers for ATOM event-queues */
1484 const LilvPlugin* p = _impl->plugin;
1486 /* count non-MIDI atom event-ports
1487 * TODO: nicely ask drobilla to make a lilv_ call for that
1489 int count_atom_out = 0;
1490 int count_atom_in = 0;
1491 int minimumSize = 32768; // TODO use a per-port minimum-size
1492 for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
1493 const LilvPort* port = lilv_plugin_get_port_by_index(p, i);
1494 if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
1495 LilvNodes* buffer_types = lilv_port_get_value(
1496 p, port, _world.atom_bufferType);
1497 LilvNodes* atom_supports = lilv_port_get_value(
1498 p, port, _world.atom_supports);
1500 if (!lilv_nodes_contains(buffer_types, _world.atom_Sequence)
1501 || !lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
1502 if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
1505 if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
1508 LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
1509 LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
1510 if (min_size && lilv_node_is_int(min_size)) {
1511 minimumSize = std::max(minimumSize, lilv_node_as_int(min_size));
1513 lilv_nodes_free(min_size_v);
1515 lilv_nodes_free(buffer_types);
1516 lilv_nodes_free(atom_supports);
1520 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 need buffers for %2 atom-in and %3 atom-out event-ports\n",
1521 name(), count_atom_in, count_atom_out));
1523 const int total_atom_buffers = (count_atom_in + count_atom_out);
1524 if (_atom_ev_buffers || total_atom_buffers == 0) {
1528 DEBUG_TRACE(DEBUG::LV2, string_compose("allocate %1 atom_ev_buffers of %d bytes\n", total_atom_buffers, minimumSize));
1529 _atom_ev_buffers = (LV2_Evbuf**) malloc((total_atom_buffers + 1) * sizeof(LV2_Evbuf*));
1530 for (int i = 0; i < total_atom_buffers; ++i ) {
1531 _atom_ev_buffers[i] = lv2_evbuf_new(minimumSize, LV2_EVBUF_ATOM,
1532 LV2Plugin::urids.atom_Chunk, LV2Plugin::urids.atom_Sequence);
1534 _atom_ev_buffers[total_atom_buffers] = 0;
1538 /** Write an ardour position/time/tempo/meter as an LV2 event.
1539 * @return true on success.
1542 write_position(LV2_Atom_Forge* forge,
1544 const TempoMetric& t,
1545 Timecode::BBT_Time& bbt,
1547 framepos_t position,
1550 uint8_t pos_buf[256];
1551 lv2_atom_forge_set_buffer(forge, pos_buf, sizeof(pos_buf));
1552 LV2_Atom_Forge_Frame frame;
1553 lv2_atom_forge_blank(forge, &frame, 1, LV2Plugin::urids.time_Position);
1554 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_frame, 0);
1555 lv2_atom_forge_long(forge, position);
1556 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_speed, 0);
1557 lv2_atom_forge_float(forge, speed);
1558 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_barBeat, 0);
1559 lv2_atom_forge_float(forge, bbt.beats - 1 +
1560 (bbt.ticks / Timecode::BBT_Time::ticks_per_beat));
1561 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_bar, 0);
1562 lv2_atom_forge_long(forge, bbt.bars - 1);
1563 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_beatUnit, 0);
1564 lv2_atom_forge_int(forge, t.meter().note_divisor());
1565 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_beatsPerBar, 0);
1566 lv2_atom_forge_float(forge, t.meter().divisions_per_bar());
1567 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_beatsPerMinute, 0);
1568 lv2_atom_forge_float(forge, t.tempo().beats_per_minute());
1570 LV2_Evbuf_Iterator end = lv2_evbuf_end(buf);
1571 const LV2_Atom* const atom = (const LV2_Atom*)pos_buf;
1572 return lv2_evbuf_write(&end, offset, 0, atom->type, atom->size,
1573 (const uint8_t*)(atom + 1));
1577 LV2Plugin::connect_and_run(BufferSet& bufs,
1578 ChanMapping in_map, ChanMapping out_map,
1579 pframes_t nframes, framecnt_t offset)
1581 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 run %2 offset %3\n", name(), nframes, offset));
1582 Plugin::connect_and_run(bufs, in_map, out_map, nframes, offset);
1584 cycles_t then = get_cycles();
1586 TempoMap& tmap = _session.tempo_map();
1587 Metrics::const_iterator metric_i = tmap.metrics_end();
1588 TempoMetric tmetric = tmap.metric_at(_session.transport_frame(), &metric_i);
1590 if (_freewheel_control_port) {
1591 *_freewheel_control_port = _session.engine().freewheeling();
1594 if (_bpm_control_port) {
1595 *_bpm_control_port = tmetric.tempo().beats_per_minute();
1598 ChanCount bufs_count;
1599 bufs_count.set(DataType::AUDIO, 1);
1600 bufs_count.set(DataType::MIDI, 1);
1601 BufferSet& silent_bufs = _session.get_silent_buffers(bufs_count);
1602 BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
1603 uint32_t const num_ports = parameter_count();
1604 uint32_t const nil_index = std::numeric_limits<uint32_t>::max();
1606 uint32_t audio_in_index = 0;
1607 uint32_t audio_out_index = 0;
1608 uint32_t midi_in_index = 0;
1609 uint32_t midi_out_index = 0;
1610 uint32_t atom_port_index = 0;
1611 for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
1613 uint32_t index = nil_index;
1614 PortFlags flags = _port_flags[port_index];
1616 if (flags & PORT_AUDIO) {
1617 if (flags & PORT_INPUT) {
1618 index = in_map.get(DataType::AUDIO, audio_in_index++, &valid);
1620 ? bufs.get_audio(index).data(offset)
1621 : silent_bufs.get_audio(0).data(offset);
1623 index = out_map.get(DataType::AUDIO, audio_out_index++, &valid);
1625 ? bufs.get_audio(index).data(offset)
1626 : scratch_bufs.get_audio(0).data(offset);
1628 } else if (flags & (PORT_EVENT|PORT_SEQUENCE)) {
1629 /* FIXME: The checks here for bufs.count().n_midi() > index shouldn't
1630 be necessary, but the mapping is illegal in some cases. Ideally
1631 that should be fixed, but this is easier...
1633 if (flags & PORT_MIDI) {
1634 if (flags & PORT_INPUT) {
1635 index = in_map.get(DataType::MIDI, midi_in_index++, &valid);
1637 index = out_map.get(DataType::MIDI, midi_out_index++, &valid);
1639 if (valid && bufs.count().n_midi() > index) {
1640 /* Note, ensure_lv2_bufsize() is not RT safe!
1641 * However free()/alloc() is only called if a
1642 * plugin requires a rsz:minimumSize buffersize
1643 * and the existing buffer if smaller.
1645 bufs.ensure_lv2_bufsize((flags & PORT_INPUT), index, _port_minimumSize[port_index]);
1646 _ev_buffers[port_index] = bufs.get_lv2_midi(
1647 (flags & PORT_INPUT), index, (flags & PORT_EVENT));
1649 } else if ((flags & PORT_POSITION) && (flags & PORT_INPUT)) {
1650 lv2_evbuf_reset(_atom_ev_buffers[atom_port_index], true);
1651 _ev_buffers[port_index] = _atom_ev_buffers[atom_port_index++];
1655 if (valid && (flags & PORT_INPUT)) {
1656 Timecode::BBT_Time bbt;
1657 if ((flags & PORT_POSITION)) {
1658 if (_session.transport_frame() != _next_cycle_start ||
1659 _session.transport_speed() != _next_cycle_speed) {
1660 // Transport has changed, write position at cycle start
1661 tmap.bbt_time(_session.transport_frame(), bbt);
1662 write_position(&_impl->forge, _ev_buffers[port_index],
1663 tmetric, bbt, _session.transport_speed(),
1664 _session.transport_frame(), 0);
1668 // Get MIDI iterator range (empty range if no MIDI)
1669 MidiBuffer::iterator m = (index != nil_index)
1670 ? bufs.get_midi(index).begin()
1671 : silent_bufs.get_midi(0).end();
1672 MidiBuffer::iterator m_end = (index != nil_index)
1673 ? bufs.get_midi(index).end()
1676 // Now merge MIDI and any transport events into the buffer
1677 const uint32_t type = LV2Plugin::urids.midi_MidiEvent;
1678 const framepos_t tend = _session.transport_frame() + nframes;
1680 while (m != m_end || (metric_i != tmap.metrics_end() &&
1681 (*metric_i)->frame() < tend)) {
1682 MetricSection* metric = (metric_i != tmap.metrics_end())
1684 if (m != m_end && (!metric || metric->frame() > (*m).time())) {
1685 const Evoral::MIDIEvent<framepos_t> ev(*m, false);
1686 LV2_Evbuf_Iterator eend = lv2_evbuf_end(_ev_buffers[port_index]);
1687 lv2_evbuf_write(&eend, ev.time(), 0, type, ev.size(), ev.buffer());
1690 tmetric.set_metric(metric);
1691 bbt = metric->start();
1692 write_position(&_impl->forge, _ev_buffers[port_index],
1693 tmetric, bbt, _session.transport_speed(),
1695 metric->frame() - _session.transport_frame());
1699 } else if (!valid) {
1700 // Nothing we understand or care about, connect to scratch
1701 // see note for midi-buffer size above
1702 scratch_bufs.ensure_lv2_bufsize((flags & PORT_INPUT),
1703 0, _port_minimumSize[port_index]);
1704 _ev_buffers[port_index] = scratch_bufs.get_lv2_midi(
1705 (flags & PORT_INPUT), 0, (flags & PORT_EVENT));
1707 buf = lv2_evbuf_get_buffer(_ev_buffers[port_index]);
1709 continue; // Control port, leave buffer alone
1711 lilv_instance_connect_port(_impl->instance, port_index, buf);
1714 // Read messages from UI and push into appropriate buffers
1716 uint32_t read_space = _from_ui->read_space();
1717 while (read_space > sizeof(UIMessage)) {
1719 if (_from_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1720 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
1723 vector<uint8_t> body(msg.size);
1724 if (_from_ui->read(&body[0], msg.size) != msg.size) {
1725 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
1728 if (msg.protocol == urids.atom_eventTransfer) {
1729 LV2_Evbuf* buf = _ev_buffers[msg.index];
1730 LV2_Evbuf_Iterator i = lv2_evbuf_end(buf);
1731 const LV2_Atom* const atom = (const LV2_Atom*)&body[0];
1732 if (!lv2_evbuf_write(&i, nframes, 0, atom->type, atom->size,
1733 (const uint8_t*)(atom + 1))) {
1734 error << "Failed to write data to LV2 event buffer\n";
1737 error << "Received unknown message type from UI" << endmsg;
1739 read_space -= sizeof(UIMessage) + msg.size;
1746 for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
1747 PortFlags flags = _port_flags[port_index];
1750 /* TODO ask drobilla about comment
1751 * "Make Ardour event buffers generic so plugins can communicate"
1752 * in libs/ardour/buffer_set.cc:310
1754 * ideally the user could choose which of the following two modes
1755 * to use (e.g. instrument/effect chains MIDI OUT vs MIDI TRHU).
1757 * This implementation follows the discussion on IRC Mar 16 2013 16:47 UTC
1758 * 16:51 < drobilla> rgareus: [..] i.e always replace with MIDI output [of LV2 plugin] if it's there
1759 * 16:52 < drobilla> rgareus: That would probably be good enough [..] to make users not complain
1760 * for quite a while at least ;)
1762 // copy output of LV2 plugin's MIDI port to Ardour MIDI buffers -- MIDI OUT
1763 if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE|PORT_MIDI))) {
1764 const uint32_t buf_index = out_map.get(
1765 DataType::MIDI, midi_out_index++, &valid);
1767 bufs.forward_lv2_midi(_ev_buffers[port_index], buf_index);
1770 // Flush MIDI (write back to Ardour MIDI buffers) -- MIDI THRU
1771 else if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
1772 const uint32_t buf_index = out_map.get(
1773 DataType::MIDI, midi_out_index++, &valid);
1775 bufs.flush_lv2_midi(true, buf_index);
1779 // Write messages to UI
1780 if (_to_ui && (flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
1781 LV2_Evbuf* buf = _ev_buffers[port_index];
1782 for (LV2_Evbuf_Iterator i = lv2_evbuf_begin(buf);
1783 lv2_evbuf_is_valid(i);
1784 i = lv2_evbuf_next(i)) {
1785 uint32_t frames, subframes, type, size;
1787 lv2_evbuf_get(i, &frames, &subframes, &type, &size, &data);
1788 write_to_ui(port_index, urids.atom_eventTransfer,
1789 size + sizeof(LV2_Atom),
1790 data - sizeof(LV2_Atom));
1795 cycles_t now = get_cycles();
1796 set_cycles((uint32_t)(now - then));
1798 // Update expected transport information for next cycle so we can detect changes
1799 _next_cycle_speed = _session.transport_speed();
1800 _next_cycle_start = _session.transport_frame() + (nframes * _next_cycle_speed);
1806 LV2Plugin::parameter_is_control(uint32_t param) const
1808 assert(param < _port_flags.size());
1809 return _port_flags[param] & PORT_CONTROL;
1813 LV2Plugin::parameter_is_audio(uint32_t param) const
1815 assert(param < _port_flags.size());
1816 return _port_flags[param] & PORT_AUDIO;
1820 LV2Plugin::parameter_is_event(uint32_t param) const
1822 assert(param < _port_flags.size());
1823 return _port_flags[param] & PORT_EVENT;
1827 LV2Plugin::parameter_is_output(uint32_t param) const
1829 assert(param < _port_flags.size());
1830 return _port_flags[param] & PORT_OUTPUT;
1834 LV2Plugin::parameter_is_input(uint32_t param) const
1836 assert(param < _port_flags.size());
1837 return _port_flags[param] & PORT_INPUT;
1841 LV2Plugin::print_parameter(uint32_t param, char* buf, uint32_t len) const
1844 if (param < parameter_count()) {
1845 snprintf(buf, len, "%.3f", get_parameter(param));
1852 boost::shared_ptr<Plugin::ScalePoints>
1853 LV2Plugin::get_scale_points(uint32_t port_index) const
1855 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, port_index);
1856 LilvScalePoints* points = lilv_port_get_scale_points(_impl->plugin, port);
1858 boost::shared_ptr<Plugin::ScalePoints> ret;
1863 ret = boost::shared_ptr<Plugin::ScalePoints>(new ScalePoints());
1865 LILV_FOREACH(scale_points, i, points) {
1866 const LilvScalePoint* p = lilv_scale_points_get(points, i);
1867 const LilvNode* label = lilv_scale_point_get_label(p);
1868 const LilvNode* value = lilv_scale_point_get_value(p);
1869 if (label && (lilv_node_is_float(value) || lilv_node_is_int(value))) {
1870 ret->insert(make_pair(lilv_node_as_string(label),
1871 lilv_node_as_float(value)));
1875 lilv_scale_points_free(points);
1880 LV2Plugin::run(pframes_t nframes)
1882 uint32_t const N = parameter_count();
1883 for (uint32_t i = 0; i < N; ++i) {
1884 if (parameter_is_control(i) && parameter_is_input(i)) {
1885 _control_data[i] = _shadow_data[i];
1889 lilv_instance_run(_impl->instance, nframes);
1891 if (_impl->work_iface) {
1892 _worker->emit_responses();
1893 if (_impl->work_iface->end_run) {
1894 _impl->work_iface->end_run(_impl->instance->lv2_handle);
1900 LV2Plugin::latency_compute_run()
1902 if (!_latency_control_port) {
1906 // Run the plugin so that it can set its latency parameter
1910 uint32_t port_index = 0;
1911 uint32_t in_index = 0;
1912 uint32_t out_index = 0;
1914 const framecnt_t bufsize = 1024;
1915 float buffer[bufsize];
1917 memset(buffer, 0, sizeof(float) * bufsize);
1919 // FIXME: Ensure plugins can handle in-place processing
1923 while (port_index < parameter_count()) {
1924 if (parameter_is_audio(port_index)) {
1925 if (parameter_is_input(port_index)) {
1926 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1928 } else if (parameter_is_output(port_index)) {
1929 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1941 LV2Plugin::Impl::designated_input (const char* uri, void** bufptrs[], void** bufptr)
1943 const LilvPort* port = NULL;
1944 LilvNode* designation = lilv_new_uri(_world.world, uri);
1945 port = lilv_plugin_get_port_by_designation(
1946 plugin, _world.lv2_InputPort, designation);
1947 lilv_node_free(designation);
1949 bufptrs[lilv_port_get_index(plugin, port)] = bufptr;
1954 static bool lv2_filter (const string& str, void* /*arg*/)
1956 /* Not a dotfile, has a prefix before a period, suffix is "lv2" */
1958 return str[0] != '.' && (str.length() > 3 && str.find (".lv2") == (str.length() - 4));
1962 LV2World::LV2World()
1963 : world(lilv_world_new())
1964 , _bundle_checked(false)
1966 lilv_world_load_all(world);
1968 atom_AtomPort = lilv_new_uri(world, LV2_ATOM__AtomPort);
1969 atom_Chunk = lilv_new_uri(world, LV2_ATOM__Chunk);
1970 atom_Sequence = lilv_new_uri(world, LV2_ATOM__Sequence);
1971 atom_bufferType = lilv_new_uri(world, LV2_ATOM__bufferType);
1972 atom_supports = lilv_new_uri(world, LV2_ATOM__supports);
1973 atom_eventTransfer = lilv_new_uri(world, LV2_ATOM__eventTransfer);
1974 ev_EventPort = lilv_new_uri(world, LILV_URI_EVENT_PORT);
1975 ext_logarithmic = lilv_new_uri(world, LV2_PORT_PROPS__logarithmic);
1976 ext_notOnGUI = lilv_new_uri(world, LV2_PORT_PROPS__notOnGUI);
1977 lv2_AudioPort = lilv_new_uri(world, LILV_URI_AUDIO_PORT);
1978 lv2_ControlPort = lilv_new_uri(world, LILV_URI_CONTROL_PORT);
1979 lv2_InputPort = lilv_new_uri(world, LILV_URI_INPUT_PORT);
1980 lv2_OutputPort = lilv_new_uri(world, LILV_URI_OUTPUT_PORT);
1981 lv2_inPlaceBroken = lilv_new_uri(world, LV2_CORE__inPlaceBroken);
1982 lv2_integer = lilv_new_uri(world, LV2_CORE__integer);
1983 lv2_reportsLatency = lilv_new_uri(world, LV2_CORE__reportsLatency);
1984 lv2_sampleRate = lilv_new_uri(world, LV2_CORE__sampleRate);
1985 lv2_toggled = lilv_new_uri(world, LV2_CORE__toggled);
1986 lv2_enumeration = lilv_new_uri(world, LV2_CORE__enumeration);
1987 lv2_freewheeling = lilv_new_uri(world, LV2_CORE__freeWheeling);
1988 midi_MidiEvent = lilv_new_uri(world, LILV_URI_MIDI_EVENT);
1989 rdfs_comment = lilv_new_uri(world, LILV_NS_RDFS "comment");
1990 rsz_minimumSize = lilv_new_uri(world, LV2_RESIZE_PORT__minimumSize);
1991 time_Position = lilv_new_uri(world, LV2_TIME__Position);
1992 ui_GtkUI = lilv_new_uri(world, LV2_UI__GtkUI);
1993 ui_external = lilv_new_uri(world, "http://lv2plug.in/ns/extensions/ui#external");
1994 ui_externalkx = lilv_new_uri(world, "http://kxstudio.sf.net/ns/lv2ext/external-ui#Widget");
1995 units_unit = lilv_new_uri(world, "http://lv2plug.in/ns/extensions/units#unit");
1996 units_midiNote = lilv_new_uri(world, "http://lv2plug.in/ns/extensions/units#midiNote");
1999 LV2World::~LV2World()
2001 lilv_node_free(units_midiNote);
2002 lilv_node_free(units_unit);
2003 lilv_node_free(ui_externalkx);
2004 lilv_node_free(ui_external);
2005 lilv_node_free(ui_GtkUI);
2006 lilv_node_free(time_Position);
2007 lilv_node_free(rsz_minimumSize);
2008 lilv_node_free(rdfs_comment);
2009 lilv_node_free(midi_MidiEvent);
2010 lilv_node_free(lv2_enumeration);
2011 lilv_node_free(lv2_freewheeling);
2012 lilv_node_free(lv2_toggled);
2013 lilv_node_free(lv2_sampleRate);
2014 lilv_node_free(lv2_reportsLatency);
2015 lilv_node_free(lv2_integer);
2016 lilv_node_free(lv2_inPlaceBroken);
2017 lilv_node_free(lv2_OutputPort);
2018 lilv_node_free(lv2_InputPort);
2019 lilv_node_free(lv2_ControlPort);
2020 lilv_node_free(lv2_AudioPort);
2021 lilv_node_free(ext_notOnGUI);
2022 lilv_node_free(ext_logarithmic);
2023 lilv_node_free(ev_EventPort);
2024 lilv_node_free(atom_supports);
2025 lilv_node_free(atom_eventTransfer);
2026 lilv_node_free(atom_bufferType);
2027 lilv_node_free(atom_Sequence);
2028 lilv_node_free(atom_Chunk);
2029 lilv_node_free(atom_AtomPort);
2033 LV2World::load_bundled_plugins()
2035 if (!_bundle_checked) {
2036 cout << "Scanning folders for bundled LV2s: " << ARDOUR::lv2_bundled_search_path().to_string() << endl;
2037 PathScanner scanner;
2038 vector<string *> *plugin_objects = scanner (ARDOUR::lv2_bundled_search_path().to_string(), lv2_filter, 0, true, true);
2039 if (plugin_objects) {
2040 for ( vector<string *>::iterator x = plugin_objects->begin(); x != plugin_objects->end (); ++x) {
2041 #ifdef PLATFORM_WINDOWS
2042 string uri = "file:///" + **x + "/";
2044 string uri = "file://" + **x + "/";
2046 LilvNode *node = lilv_new_uri(world, uri.c_str());
2047 lilv_world_load_bundle(world, node);
2048 lilv_node_free(node);
2051 delete (plugin_objects);
2053 _bundle_checked = true;
2057 LV2PluginInfo::LV2PluginInfo (const void* c_plugin)
2058 : _c_plugin(c_plugin)
2063 LV2PluginInfo::~LV2PluginInfo()
2067 LV2PluginInfo::load(Session& session)
2072 plugin.reset(new LV2Plugin(session.engine(), session,
2073 (const LilvPlugin*)_c_plugin,
2074 session.frame_rate()));
2076 plugin->set_info(PluginInfoPtr(new LV2PluginInfo(*this)));
2078 } catch (failed_constructor& err) {
2079 return PluginPtr((Plugin*)0);
2086 LV2PluginInfo::discover()
2088 _world.load_bundled_plugins();
2090 PluginInfoList* plugs = new PluginInfoList;
2091 const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
2093 if (!Config->get_show_plugin_scan_window()) {
2094 info << "LV2: Discovering " << lilv_plugins_size(plugins) << " plugins" << endmsg;
2097 LILV_FOREACH(plugins, i, plugins) {
2098 const LilvPlugin* p = lilv_plugins_get(plugins, i);
2099 LV2PluginInfoPtr info(new LV2PluginInfo((const void*)p));
2101 LilvNode* name = lilv_plugin_get_name(p);
2102 if (!name || !lilv_plugin_get_port_by_index(p, 0)) {
2103 warning << "Ignoring invalid LV2 plugin "
2104 << lilv_node_as_string(lilv_plugin_get_uri(p))
2111 info->name = string(lilv_node_as_string(name));
2112 lilv_node_free(name);
2113 ARDOUR::PluginScanMessage(_("LV2"), info->name, false);
2115 const LilvPluginClass* pclass = lilv_plugin_get_class(p);
2116 const LilvNode* label = lilv_plugin_class_get_label(pclass);
2117 info->category = lilv_node_as_string(label);
2119 LilvNode* author_name = lilv_plugin_get_author_name(p);
2120 info->creator = author_name ? string(lilv_node_as_string(author_name)) : "Unknown";
2121 lilv_node_free(author_name);
2123 info->path = "/NOPATH"; // Meaningless for LV2
2125 /* count atom-event-ports that feature
2126 * atom:supports <http://lv2plug.in/ns/ext/midi#MidiEvent>
2128 * TODO: nicely ask drobilla to make a lilv_ call for that
2130 int count_midi_out = 0;
2131 int count_midi_in = 0;
2132 for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
2133 const LilvPort* port = lilv_plugin_get_port_by_index(p, i);
2134 if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
2135 LilvNodes* buffer_types = lilv_port_get_value(
2136 p, port, _world.atom_bufferType);
2137 LilvNodes* atom_supports = lilv_port_get_value(
2138 p, port, _world.atom_supports);
2140 if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)
2141 && lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
2142 if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
2145 if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
2149 lilv_nodes_free(buffer_types);
2150 lilv_nodes_free(atom_supports);
2154 info->n_inputs.set_audio(
2155 lilv_plugin_get_num_ports_of_class(
2156 p, _world.lv2_InputPort, _world.lv2_AudioPort, NULL));
2157 info->n_inputs.set_midi(
2158 lilv_plugin_get_num_ports_of_class(
2159 p, _world.lv2_InputPort, _world.ev_EventPort, NULL)
2162 info->n_outputs.set_audio(
2163 lilv_plugin_get_num_ports_of_class(
2164 p, _world.lv2_OutputPort, _world.lv2_AudioPort, NULL));
2165 info->n_outputs.set_midi(
2166 lilv_plugin_get_num_ports_of_class(
2167 p, _world.lv2_OutputPort, _world.ev_EventPort, NULL)
2170 info->unique_id = lilv_node_as_uri(lilv_plugin_get_uri(p));
2171 info->index = 0; // Meaningless for LV2
2173 plugs->push_back(info);