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/compose.h"
35 #include "pbd/error.h"
36 #include "pbd/xml++.h"
38 #include "libardour-config.h"
40 #include "ardour/audio_buffer.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/debug.h"
43 #include "ardour/lv2_plugin.h"
44 #include "ardour/session.h"
45 #include "ardour/tempo.h"
46 #include "ardour/types.h"
47 #include "ardour/utils.h"
48 #include "ardour/worker.h"
53 #include <lilv/lilv.h>
55 #include "lv2/lv2plug.in/ns/ext/atom/atom.h"
56 #include "lv2/lv2plug.in/ns/ext/atom/forge.h"
57 #include "lv2/lv2plug.in/ns/ext/log/log.h"
58 #include "lv2/lv2plug.in/ns/ext/midi/midi.h"
59 #include "lv2/lv2plug.in/ns/ext/port-props/port-props.h"
60 #include "lv2/lv2plug.in/ns/ext/presets/presets.h"
61 #include "lv2/lv2plug.in/ns/ext/state/state.h"
62 #include "lv2/lv2plug.in/ns/ext/time/time.h"
63 #include "lv2/lv2plug.in/ns/ext/worker/worker.h"
64 #include "lv2/lv2plug.in/ns/ext/resize-port/resize-port.h"
65 #include "lv2/lv2plug.in/ns/extensions/ui/ui.h"
67 #include "lv2/lv2plug.in/ns/ext/buf-size/buf-size.h"
68 #include "lv2/lv2plug.in/ns/ext/options/options.h"
71 #include "lv2_evbuf.h"
74 #include <suil/suil.h>
77 /** The number of MIDI buffers that will fit in a UI/worker comm buffer.
78 This needs to be roughly the number of cycles the UI will get around to
79 actually processing the traffic. Lower values are flakier but save memory.
81 static const size_t NBUFS = 4;
84 using namespace ARDOUR;
87 URIMap LV2Plugin::_uri_map;
89 LV2Plugin::URIDs LV2Plugin::urids = {
90 _uri_map.uri_to_id(LV2_ATOM__Chunk),
91 _uri_map.uri_to_id(LV2_ATOM__Path),
92 _uri_map.uri_to_id(LV2_ATOM__Sequence),
93 _uri_map.uri_to_id(LV2_ATOM__eventTransfer),
94 _uri_map.uri_to_id(LV2_LOG__Error),
95 _uri_map.uri_to_id(LV2_LOG__Note),
96 _uri_map.uri_to_id(LV2_LOG__Warning),
97 _uri_map.uri_to_id(LV2_MIDI__MidiEvent),
98 _uri_map.uri_to_id(LV2_TIME__Position),
99 _uri_map.uri_to_id(LV2_TIME__bar),
100 _uri_map.uri_to_id(LV2_TIME__barBeat),
101 _uri_map.uri_to_id(LV2_TIME__beatUnit),
102 _uri_map.uri_to_id(LV2_TIME__beatsPerBar),
103 _uri_map.uri_to_id(LV2_TIME__beatsPerMinute),
104 _uri_map.uri_to_id(LV2_TIME__frame),
105 _uri_map.uri_to_id(LV2_TIME__speed)
108 class LV2World : boost::noncopyable {
115 LilvNode* atom_AtomPort;
116 LilvNode* atom_Chunk;
117 LilvNode* atom_Sequence;
118 LilvNode* atom_bufferType;
119 LilvNode* atom_eventTransfer;
120 LilvNode* atom_supports;
121 LilvNode* ev_EventPort;
122 LilvNode* ext_logarithmic;
123 LilvNode* ext_notOnGUI;
124 LilvNode* lv2_AudioPort;
125 LilvNode* lv2_ControlPort;
126 LilvNode* lv2_InputPort;
127 LilvNode* lv2_OutputPort;
128 LilvNode* lv2_enumeration;
129 LilvNode* lv2_freewheeling;
130 LilvNode* lv2_inPlaceBroken;
131 LilvNode* lv2_integer;
132 LilvNode* lv2_reportsLatency;
133 LilvNode* lv2_sampleRate;
134 LilvNode* lv2_toggled;
135 LilvNode* midi_MidiEvent;
136 LilvNode* rdfs_comment;
137 LilvNode* rsz_minimumSize;
138 LilvNode* time_Position;
140 LilvNode* ui_external;
143 static LV2World _world;
145 /* worker extension */
147 /** Called by the plugin to schedule non-RT work. */
148 static LV2_Worker_Status
149 work_schedule(LV2_Worker_Schedule_Handle handle,
153 LV2Plugin* plugin = (LV2Plugin*)handle;
154 if (plugin->session().engine().freewheeling()) {
155 // Freewheeling, do the work immediately in this (audio) thread
156 return (LV2_Worker_Status)plugin->work(size, data);
158 // Enqueue message for the worker thread
159 return plugin->worker()->schedule(size, data) ?
160 LV2_WORKER_SUCCESS : LV2_WORKER_ERR_UNKNOWN;
164 /** Called by the plugin to respond to non-RT work. */
165 static LV2_Worker_Status
166 work_respond(LV2_Worker_Respond_Handle handle,
170 LV2Plugin* plugin = (LV2Plugin*)handle;
171 if (plugin->session().engine().freewheeling()) {
172 // Freewheeling, respond immediately in this (audio) thread
173 return (LV2_Worker_Status)plugin->work_response(size, data);
175 // Enqueue response for the worker
176 return plugin->worker()->respond(size, data) ?
177 LV2_WORKER_SUCCESS : LV2_WORKER_ERR_UNKNOWN;
184 log_vprintf(LV2_Log_Handle /*handle*/,
190 const int ret = g_vasprintf(&str, fmt, args);
191 if (type == LV2Plugin::urids.log_Error) {
192 error << str << endmsg;
193 } else if (type == LV2Plugin::urids.log_Warning) {
194 warning << str << endmsg;
195 } else if (type == LV2Plugin::urids.log_Note) {
196 info << str << endmsg;
198 // TODO: Toggleable log:Trace message support
203 log_printf(LV2_Log_Handle handle,
205 const char* fmt, ...)
209 const int ret = log_vprintf(handle, type, fmt, args);
214 struct LV2Plugin::Impl {
215 Impl() : plugin(0), ui(0), ui_type(0), name(0), author(0), instance(0)
220 /** Find the LV2 input port with the given designation.
221 * If found, bufptrs[port_index] will be set to bufptr.
223 const LilvPort* designated_input (const char* uri, void** bufptrs[], void** bufptr);
225 const LilvPlugin* plugin;
227 const LilvNode* ui_type;
230 LilvInstance* instance;
231 const LV2_Worker_Interface* work_iface;
233 LV2_Atom_Forge forge;
236 LV2Plugin::LV2Plugin (AudioEngine& engine,
238 const void* c_plugin,
240 : Plugin (engine, session)
247 init(c_plugin, rate);
250 LV2Plugin::LV2Plugin (const LV2Plugin& other)
256 , _insert_id(other._insert_id)
258 init(other._impl->plugin, other._sample_rate);
260 for (uint32_t i = 0; i < parameter_count(); ++i) {
261 _control_data[i] = other._shadow_data[i];
262 _shadow_data[i] = other._shadow_data[i];
267 LV2Plugin::init(const void* c_plugin, framecnt_t rate)
269 DEBUG_TRACE(DEBUG::LV2, "init\n");
271 _impl->plugin = (const LilvPlugin*)c_plugin;
273 _impl->ui_type = NULL;
278 _atom_ev_buffers = 0;
280 _bpm_control_port = 0;
281 _freewheel_control_port = 0;
282 _latency_control_port = 0;
283 _next_cycle_start = std::numeric_limits<framepos_t>::max();
284 _next_cycle_speed = 1.0;
285 _block_length = _engine.frames_per_cycle();
286 _seq_size = _engine.raw_buffer_size(DataType::MIDI);
288 _was_activated = false;
289 _has_state_interface = false;
291 _instance_access_feature.URI = "http://lv2plug.in/ns/ext/instance-access";
292 _data_access_feature.URI = "http://lv2plug.in/ns/ext/data-access";
293 _make_path_feature.URI = LV2_STATE__makePath;
294 _log_feature.URI = LV2_LOG__log;
295 _work_schedule_feature.URI = LV2_WORKER__schedule;
296 _work_schedule_feature.data = NULL;
297 _def_state_feature.URI = LV2_STATE_PREFIX "loadDefaultState"; // Post LV2-1.2.0
298 _def_state_feature.data = NULL;
300 const LilvPlugin* plugin = _impl->plugin;
302 LilvNode* state_iface_uri = lilv_new_uri(_world.world, LV2_STATE__interface);
303 LilvNode* state_uri = lilv_new_uri(_world.world, LV2_STATE_URI);
304 _has_state_interface =
305 // What plugins should have (lv2:extensionData state:Interface)
306 lilv_plugin_has_extension_data(plugin, state_iface_uri)
307 // What some outdated/incorrect ones have
308 || lilv_plugin_has_feature(plugin, state_uri);
309 lilv_node_free(state_uri);
310 lilv_node_free(state_iface_uri);
312 _features = (LV2_Feature**)calloc(11, sizeof(LV2_Feature*));
313 _features[0] = &_instance_access_feature;
314 _features[1] = &_data_access_feature;
315 _features[2] = &_make_path_feature;
316 _features[3] = _uri_map.uri_map_feature();
317 _features[4] = _uri_map.urid_map_feature();
318 _features[5] = _uri_map.urid_unmap_feature();
319 _features[6] = &_log_feature;
321 unsigned n_features = 7;
323 _features[n_features++] = &_def_state_feature;
326 lv2_atom_forge_init(&_impl->forge, _uri_map.urid_map());
329 LV2_URID atom_Int = _uri_map.uri_to_id(LV2_ATOM__Int);
330 LV2_Options_Option options[] = {
331 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__minBlockLength),
332 sizeof(int32_t), atom_Int, &_block_length },
333 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__maxBlockLength),
334 sizeof(int32_t), atom_Int, &_block_length },
335 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__sequenceSize),
336 sizeof(int32_t), atom_Int, &_seq_size },
337 { LV2_OPTIONS_INSTANCE, 0, 0, 0, 0, NULL }
340 _options_feature.URI = LV2_OPTIONS__options;
341 _options_feature.data = options;
342 _features[n_features++] = &_options_feature;
345 LV2_State_Make_Path* make_path = (LV2_State_Make_Path*)malloc(
346 sizeof(LV2_State_Make_Path));
347 make_path->handle = this;
348 make_path->path = &lv2_state_make_path;
349 _make_path_feature.data = make_path;
351 LV2_Log_Log* log = (LV2_Log_Log*)malloc(sizeof(LV2_Log_Log));
353 log->printf = &log_printf;
354 log->vprintf = &log_vprintf;
355 _log_feature.data = log;
357 LilvNode* worker_schedule = lilv_new_uri(_world.world, LV2_WORKER__schedule);
358 if (lilv_plugin_has_feature(plugin, worker_schedule)) {
359 LV2_Worker_Schedule* schedule = (LV2_Worker_Schedule*)malloc(
360 sizeof(LV2_Worker_Schedule));
361 size_t buf_size = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
362 _worker = new Worker(this, buf_size);
363 schedule->handle = this;
364 schedule->schedule_work = work_schedule;
365 _work_schedule_feature.data = schedule;
366 _features[n_features++] = &_work_schedule_feature;
368 lilv_node_free(worker_schedule);
370 _impl->instance = lilv_plugin_instantiate(plugin, rate, _features);
371 _impl->name = lilv_plugin_get_name(plugin);
372 _impl->author = lilv_plugin_get_author_name(plugin);
374 if (_impl->instance == 0) {
375 error << _("LV2: Failed to instantiate plugin ") << uri() << endmsg;
376 throw failed_constructor();
379 _instance_access_feature.data = (void*)_impl->instance->lv2_handle;
380 _data_access_extension_data.extension_data = _impl->instance->lv2_descriptor->extension_data;
381 _data_access_feature.data = &_data_access_extension_data;
383 LilvNode* worker_iface_uri = lilv_new_uri(_world.world, LV2_WORKER__interface);
384 if (lilv_plugin_has_extension_data(plugin, worker_iface_uri)) {
385 _impl->work_iface = (const LV2_Worker_Interface*)extension_data(
386 LV2_WORKER__interface);
388 lilv_node_free(worker_iface_uri);
390 if (lilv_plugin_has_feature(plugin, _world.lv2_inPlaceBroken)) {
391 error << string_compose(
392 _("LV2: \"%1\" cannot be used, since it cannot do inplace processing"),
393 lilv_node_as_string(_impl->name)) << endmsg;
394 lilv_node_free(_impl->name);
395 lilv_node_free(_impl->author);
396 throw failed_constructor();
400 // Load default state
401 LilvState* state = lilv_state_new_from_world(
402 _world.world, _uri_map.urid_map(), lilv_plugin_get_uri(_impl->plugin));
403 if (state && _has_state_interface) {
404 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
410 const uint32_t num_ports = this->num_ports();
411 for (uint32_t i = 0; i < num_ports; ++i) {
412 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, i);
414 size_t minimumSize = 0;
416 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_OutputPort)) {
417 flags |= PORT_OUTPUT;
418 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_InputPort)) {
421 error << string_compose(
422 "LV2: \"%1\" port %2 is neither input nor output",
423 lilv_node_as_string(_impl->name), i) << endmsg;
424 throw failed_constructor();
427 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_ControlPort)) {
428 flags |= PORT_CONTROL;
429 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_AudioPort)) {
431 } else if (lilv_port_is_a(_impl->plugin, port, _world.ev_EventPort)) {
433 flags |= PORT_MIDI; // We assume old event API ports are for MIDI
434 } else if (lilv_port_is_a(_impl->plugin, port, _world.atom_AtomPort)) {
435 LilvNodes* buffer_types = lilv_port_get_value(
436 _impl->plugin, port, _world.atom_bufferType);
437 LilvNodes* atom_supports = lilv_port_get_value(
438 _impl->plugin, port, _world.atom_supports);
440 if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)) {
441 flags |= PORT_SEQUENCE;
442 if (lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
445 if (lilv_nodes_contains(atom_supports, _world.time_Position)) {
446 flags |= PORT_POSITION;
449 LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
450 LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
451 if (min_size && lilv_node_is_int(min_size)) {
452 minimumSize = lilv_node_as_int(min_size);
454 lilv_nodes_free(min_size_v);
455 lilv_nodes_free(buffer_types);
456 lilv_nodes_free(atom_supports);
458 error << string_compose(
459 "LV2: \"%1\" port %2 has no known data type",
460 lilv_node_as_string(_impl->name), i) << endmsg;
461 throw failed_constructor();
464 _port_flags.push_back(flags);
465 _port_minimumSize.push_back(minimumSize);
468 _control_data = new float[num_ports];
469 _shadow_data = new float[num_ports];
470 _defaults = new float[num_ports];
471 _ev_buffers = new LV2_Evbuf*[num_ports];
472 memset(_ev_buffers, 0, sizeof(LV2_Evbuf*) * num_ports);
474 const bool latent = lilv_plugin_has_latency(plugin);
475 const uint32_t latency_index = (latent)
476 ? lilv_plugin_get_latency_port_index(plugin)
479 // Build an array of pointers to special parameter buffers
480 void*** params = new void**[num_ports];
481 for (uint32_t i = 0; i < num_ports; ++i) {
484 _impl->designated_input (LV2_TIME__beatsPerMinute, params, (void**)&_bpm_control_port);
485 _impl->designated_input (LV2_CORE__freeWheeling, params, (void**)&_freewheel_control_port);
487 for (uint32_t i = 0; i < num_ports; ++i) {
488 const LilvPort* port = lilv_plugin_get_port_by_index(plugin, i);
489 const LilvNode* sym = lilv_port_get_symbol(plugin, port);
491 // Store index in map so we can look up index by symbol
492 _port_indices.insert(std::make_pair(lilv_node_as_string(sym), i));
494 // Get range and default value if applicable
495 if (parameter_is_control(i)) {
497 lilv_port_get_range(plugin, port, &def, NULL, NULL);
498 _defaults[i] = def ? lilv_node_as_float(def) : 0.0f;
499 if (lilv_port_has_property (plugin, port, _world.lv2_sampleRate)) {
500 _defaults[i] *= _session.frame_rate ();
504 lilv_instance_connect_port(_impl->instance, i, &_control_data[i]);
506 if (latent && i == latency_index) {
507 _latency_control_port = &_control_data[i];
508 *_latency_control_port = 0;
511 if (parameter_is_input(i)) {
512 _shadow_data[i] = default_value(i);
514 *params[i] = (void*)&_shadow_data[i];
524 LilvUIs* uis = lilv_plugin_get_uis(plugin);
525 if (lilv_uis_size(uis) > 0) {
527 // Look for embeddable UI
528 LILV_FOREACH(uis, u, uis) {
529 const LilvUI* this_ui = lilv_uis_get(uis, u);
530 const LilvNode* this_ui_type = NULL;
531 if (lilv_ui_is_supported(this_ui,
535 // TODO: Multiple UI support
537 _impl->ui_type = this_ui_type;
542 // Look for Gtk native UI
543 LILV_FOREACH(uis, i, uis) {
544 const LilvUI* ui = lilv_uis_get(uis, i);
545 if (lilv_ui_is_a(ui, _world.ui_GtkUI)) {
547 _impl->ui_type = _world.ui_GtkUI;
553 // If Gtk UI is not available, try to find external UI
555 LILV_FOREACH(uis, i, uis) {
556 const LilvUI* ui = lilv_uis_get(uis, i);
557 if (lilv_ui_is_a(ui, _world.ui_external)) {
559 _impl->ui_type = _world.ui_external;
566 allocate_atom_event_buffers();
567 latency_compute_run();
570 LV2Plugin::~LV2Plugin ()
572 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 destroy\n", name()));
577 lilv_instance_free(_impl->instance);
578 lilv_node_free(_impl->name);
579 lilv_node_free(_impl->author);
582 free(_make_path_feature.data);
583 free(_work_schedule_feature.data);
589 if (_atom_ev_buffers) {
590 LV2_Evbuf** b = _atom_ev_buffers;
595 free(_atom_ev_buffers);
598 delete [] _control_data;
599 delete [] _shadow_data;
600 delete [] _ev_buffers;
604 LV2Plugin::is_external_ui() const
609 return lilv_ui_is_a(_impl->ui, _world.ui_external);
613 LV2Plugin::ui_is_resizable () const
615 const LilvNode* s = lilv_ui_get_uri(_impl->ui);
616 LilvNode* p = lilv_new_uri(_world.world, LV2_CORE__optionalFeature);
617 LilvNode* fs = lilv_new_uri(_world.world, LV2_UI__fixedSize);
618 LilvNode* nrs = lilv_new_uri(_world.world, LV2_UI__noUserResize);
620 LilvNodes* fs_matches = lilv_world_find_nodes(_world.world, s, p, fs);
621 LilvNodes* nrs_matches = lilv_world_find_nodes(_world.world, s, p, nrs);
623 lilv_nodes_free(nrs_matches);
624 lilv_nodes_free(fs_matches);
629 return !fs_matches && !nrs_matches;
633 LV2Plugin::unique_id() const
635 return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
639 LV2Plugin::uri() const
641 return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
645 LV2Plugin::label() const
647 return lilv_node_as_string(_impl->name);
651 LV2Plugin::name() const
653 return lilv_node_as_string(_impl->name);
657 LV2Plugin::maker() const
659 return _impl->author ? lilv_node_as_string (_impl->author) : "Unknown";
663 LV2Plugin::num_ports() const
665 return lilv_plugin_get_num_ports(_impl->plugin);
669 LV2Plugin::parameter_count() const
671 return lilv_plugin_get_num_ports(_impl->plugin);
675 LV2Plugin::default_value(uint32_t port)
677 return _defaults[port];
681 LV2Plugin::port_symbol(uint32_t index) const
683 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, index);
685 error << name() << ": Invalid port index " << index << endmsg;
688 const LilvNode* sym = lilv_port_get_symbol(_impl->plugin, port);
689 return lilv_node_as_string(sym);
693 LV2Plugin::port_index (const char* symbol) const
695 const map<string, uint32_t>::const_iterator i = _port_indices.find(symbol);
696 if (i != _port_indices.end()) {
699 warning << string_compose(_("LV2: Unknown port %1"), symbol) << endmsg;
705 LV2Plugin::set_parameter(uint32_t which, float val)
707 DEBUG_TRACE(DEBUG::LV2, string_compose(
708 "%1 set parameter %2 to %3\n", name(), which, val));
710 if (which < lilv_plugin_get_num_ports(_impl->plugin)) {
711 if (get_parameter (which) == val) {
715 _shadow_data[which] = val;
717 warning << string_compose(
718 _("Illegal parameter number used with plugin \"%1\". "
719 "This is a bug in either %2 or the LV2 plugin <%3>"),
720 name(), PROGRAM_NAME, unique_id()) << endmsg;
723 Plugin::set_parameter(which, val);
727 LV2Plugin::get_parameter(uint32_t which) const
729 if (parameter_is_input(which)) {
730 return (float)_shadow_data[which];
732 return (float)_control_data[which];
738 LV2Plugin::get_docs() const
740 LilvNodes* comments = lilv_plugin_get_value(_impl->plugin, _world.rdfs_comment);
742 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
743 lilv_nodes_free(comments);
751 LV2Plugin::get_parameter_docs(uint32_t which) const
753 LilvNodes* comments = lilv_port_get_value(
755 lilv_plugin_get_port_by_index(_impl->plugin, which),
756 _world.rdfs_comment);
759 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
760 lilv_nodes_free(comments);
768 LV2Plugin::nth_parameter(uint32_t n, bool& ok) const
771 for (uint32_t c = 0, x = 0; x < lilv_plugin_get_num_ports(_impl->plugin); ++x) {
772 if (parameter_is_control(x)) {
784 LV2Plugin::extension_data(const char* uri) const
786 return lilv_instance_get_extension_data(_impl->instance, uri);
790 LV2Plugin::c_plugin()
792 return _impl->plugin;
798 return (const void*)_impl->ui;
802 LV2Plugin::c_ui_type()
804 return (const void*)_impl->ui_type;
807 /** Directory for all plugin state. */
809 LV2Plugin::plugin_dir() const
811 return Glib::build_filename(_session.plugins_dir(), _insert_id.to_s());
814 /** Directory for files created by the plugin (except during save). */
816 LV2Plugin::scratch_dir() const
818 return Glib::build_filename(plugin_dir(), "scratch");
821 /** Directory for snapshots of files in the scratch directory. */
823 LV2Plugin::file_dir() const
825 return Glib::build_filename(plugin_dir(), "files");
828 /** Directory to save state snapshot version @c num into. */
830 LV2Plugin::state_dir(unsigned num) const
832 return Glib::build_filename(plugin_dir(), string_compose("state%1", num));
835 /** Implementation of state:makePath for files created at instantiation time.
836 * Note this is not used for files created at save time (Lilv deals with that).
839 LV2Plugin::lv2_state_make_path(LV2_State_Make_Path_Handle handle,
842 LV2Plugin* me = (LV2Plugin*)handle;
843 if (me->_insert_id == PBD::ID("0")) {
844 warning << string_compose(
845 "File path \"%1\" requested but LV2 %2 has no insert ID",
846 path, me->name()) << endmsg;
847 return g_strdup(path);
850 const std::string abs_path = Glib::build_filename(me->scratch_dir(), path);
851 const std::string dirname = Glib::path_get_dirname(abs_path);
852 g_mkdir_with_parents(dirname.c_str(), 0744);
854 DEBUG_TRACE(DEBUG::LV2, string_compose("new file path %1 => %2\n",
857 return g_strndup(abs_path.c_str(), abs_path.length());
861 remove_directory(const std::string& path)
863 if (!Glib::file_test(path, Glib::FILE_TEST_IS_DIR)) {
864 warning << string_compose("\"%1\" is not a directory", path) << endmsg;
868 Glib::RefPtr<Gio::File> dir = Gio::File::create_for_path(path);
869 Glib::RefPtr<Gio::FileEnumerator> e = dir->enumerate_children();
870 Glib::RefPtr<Gio::FileInfo> fi;
871 while ((fi = e->next_file())) {
872 if (fi->get_type() == Gio::FILE_TYPE_DIRECTORY) {
873 remove_directory(fi->get_name());
875 dir->get_child(fi->get_name())->remove();
882 LV2Plugin::add_state(XMLNode* root) const
884 assert(_insert_id != PBD::ID("0"));
888 LocaleGuard lg(X_("POSIX"));
890 for (uint32_t i = 0; i < parameter_count(); ++i) {
891 if (parameter_is_input(i) && parameter_is_control(i)) {
892 child = new XMLNode("Port");
893 child->add_property("symbol", port_symbol(i));
894 snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
895 child->add_property("value", string(buf));
896 root->add_child_nocopy(*child);
900 if (_has_state_interface) {
901 // Provisionally increment state version and create directory
902 const std::string new_dir = state_dir(++_state_version);
903 g_mkdir_with_parents(new_dir.c_str(), 0744);
905 LilvState* state = lilv_state_new_from_instance(
909 scratch_dir().c_str(),
911 _session.externals_dir().c_str(),
914 const_cast<LV2Plugin*>(this),
918 if (!_impl->state || !lilv_state_equals(state, _impl->state)) {
919 lilv_state_save(_world.world,
921 _uri_map.urid_unmap(),
927 lilv_state_free(_impl->state);
928 _impl->state = state;
930 // State is identical, decrement version and nuke directory
931 lilv_state_free(state);
932 remove_directory(new_dir);
936 root->add_property("state-dir", string_compose("state%1", _state_version));
940 static inline const LilvNode*
941 get_value(LilvWorld* world, const LilvNode* subject, const LilvNode* predicate)
943 LilvNodes* vs = lilv_world_find_nodes(world, subject, predicate, NULL);
944 return vs ? lilv_nodes_get_first(vs) : NULL;
948 LV2Plugin::find_presets()
950 LilvNode* lv2_appliesTo = lilv_new_uri(_world.world, LV2_CORE__appliesTo);
951 LilvNode* pset_Preset = lilv_new_uri(_world.world, LV2_PRESETS__Preset);
952 LilvNode* rdfs_label = lilv_new_uri(_world.world, LILV_NS_RDFS "label");
954 LilvNodes* presets = lilv_plugin_get_related(_impl->plugin, pset_Preset);
955 LILV_FOREACH(nodes, i, presets) {
956 const LilvNode* preset = lilv_nodes_get(presets, i);
957 lilv_world_load_resource(_world.world, preset);
958 const LilvNode* name = get_value(_world.world, preset, rdfs_label);
960 _presets.insert(std::make_pair(lilv_node_as_string(preset),
961 Plugin::PresetRecord(
962 lilv_node_as_string(preset),
963 lilv_node_as_string(name))));
965 warning << string_compose(
966 _("Plugin \"%1\% preset \"%2%\" is missing a label\n"),
967 lilv_node_as_string(lilv_plugin_get_uri(_impl->plugin)),
968 lilv_node_as_string(preset)) << endmsg;
971 lilv_nodes_free(presets);
973 lilv_node_free(rdfs_label);
974 lilv_node_free(pset_Preset);
975 lilv_node_free(lv2_appliesTo);
979 set_port_value(const char* port_symbol,
985 LV2Plugin* self = (LV2Plugin*)user_data;
986 if (type != 0 && type != self->_uri_map.uri_to_id(LV2_ATOM__Float)) {
987 return; // TODO: Support non-float ports
990 const uint32_t port_index = self->port_index(port_symbol);
991 if (port_index != (uint32_t)-1) {
992 self->set_parameter(port_index, *(const float*)value);
997 LV2Plugin::load_preset(PresetRecord r)
999 LilvWorld* world = _world.world;
1000 LilvNode* pset = lilv_new_uri(world, r.uri.c_str());
1001 LilvState* state = lilv_state_new_from_world(world, _uri_map.urid_map(), pset);
1004 lilv_state_restore(state, _impl->instance, set_port_value, this, 0, NULL);
1005 lilv_state_free(state);
1008 lilv_node_free(pset);
1013 ARDOUR::lv2plugin_get_port_value(const char* port_symbol,
1018 LV2Plugin *plugin = (LV2Plugin *) user_data;
1020 uint32_t index = plugin->port_index(port_symbol);
1021 if (index != (uint32_t) -1) {
1022 if (plugin->parameter_is_input(index) && plugin->parameter_is_control(index)) {
1024 *size = sizeof(float);
1025 *type = plugin->_uri_map.uri_to_id(LV2_ATOM__Float);
1026 value = &plugin->_shadow_data[index];
1038 LV2Plugin::do_save_preset(string name)
1040 const string base_name = legalize_for_uri(name);
1041 const string file_name = base_name + ".ttl";
1042 const string bundle = Glib::build_filename(
1043 Glib::get_home_dir(),
1044 Glib::build_filename(".lv2", base_name + ".lv2"));
1046 LilvState* state = lilv_state_new_from_instance(
1049 _uri_map.urid_map(),
1050 scratch_dir().c_str(), // file_dir
1051 bundle.c_str(), // copy_dir
1052 bundle.c_str(), // link_dir
1053 bundle.c_str(), // save_dir
1054 lv2plugin_get_port_value, // get_value
1055 (void*)this, // user_data
1056 LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE, // flags
1057 _features // features
1060 lilv_state_set_label(state, name.c_str());
1062 _world.world, // world
1063 _uri_map.urid_map(), // map
1064 _uri_map.urid_unmap(), // unmap
1066 NULL, // uri (NULL = use file URI)
1067 bundle.c_str(), // dir
1068 file_name.c_str() // filename
1071 lilv_state_free(state);
1073 return Glib::filename_to_uri(Glib::build_filename(bundle, file_name));
1077 LV2Plugin::do_remove_preset(string name)
1079 string preset_file = Glib::build_filename(
1080 Glib::get_home_dir(),
1081 Glib::build_filename(
1082 Glib::build_filename(".lv2", "presets"),
1086 unlink(preset_file.c_str());
1090 LV2Plugin::has_editor() const
1092 return _impl->ui != NULL;
1096 LV2Plugin::has_message_output() const
1098 for (uint32_t i = 0; i < num_ports(); ++i) {
1099 if ((_port_flags[i] & PORT_SEQUENCE) &&
1100 (_port_flags[i] & PORT_OUTPUT)) {
1108 LV2Plugin::write_to(RingBuffer<uint8_t>* dest,
1112 const uint8_t* body)
1114 const uint32_t buf_size = sizeof(UIMessage) + size;
1115 uint8_t buf[buf_size];
1117 UIMessage* msg = (UIMessage*)buf;
1119 msg->protocol = protocol;
1121 memcpy(msg + 1, body, size);
1123 return (dest->write(buf, buf_size) == buf_size);
1127 LV2Plugin::write_from_ui(uint32_t index,
1130 const uint8_t* body)
1133 _from_ui = new RingBuffer<uint8_t>(
1134 _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS);
1137 if (!write_to(_from_ui, index, protocol, size, body)) {
1138 error << "Error writing from UI to plugin" << endmsg;
1145 LV2Plugin::write_to_ui(uint32_t index,
1148 const uint8_t* body)
1150 if (!write_to(_to_ui, index, protocol, size, body)) {
1151 error << "Error writing from plugin to UI" << endmsg;
1158 LV2Plugin::enable_ui_emmission()
1161 _to_ui = new RingBuffer<uint8_t>(
1162 _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS);
1167 LV2Plugin::emit_to_ui(void* controller, UIMessageSink sink)
1173 uint32_t read_space = _to_ui->read_space();
1174 while (read_space > sizeof(UIMessage)) {
1176 if (_to_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1177 error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1180 uint8_t body[msg.size];
1181 if (_to_ui->read(body, msg.size) != msg.size) {
1182 error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1186 sink(controller, msg.index, msg.size, msg.protocol, body);
1188 read_space -= sizeof(msg) + msg.size;
1193 LV2Plugin::work(uint32_t size, const void* data)
1195 return _impl->work_iface->work(
1196 _impl->instance->lv2_handle, work_respond, this, size, data);
1200 LV2Plugin::work_response(uint32_t size, const void* data)
1202 return _impl->work_iface->work_response(
1203 _impl->instance->lv2_handle, size, data);
1207 LV2Plugin::set_insert_info(const PluginInsert* insert)
1209 _insert_id = insert->id();
1213 LV2Plugin::set_state(const XMLNode& node, int version)
1216 const XMLProperty* prop;
1217 XMLNodeConstIterator iter;
1222 LocaleGuard lg(X_("POSIX"));
1224 if (node.name() != state_node_name()) {
1225 error << _("Bad node sent to LV2Plugin::set_state") << endmsg;
1229 if (version < 3000) {
1230 nodes = node.children("port");
1232 nodes = node.children("Port");
1235 for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
1239 if ((prop = child->property("symbol")) != 0) {
1240 sym = prop->value().c_str();
1242 warning << _("LV2: port has no symbol, ignored") << endmsg;
1246 map<string, uint32_t>::iterator i = _port_indices.find(sym);
1248 if (i != _port_indices.end()) {
1249 port_id = i->second;
1251 warning << _("LV2: port has unknown index, ignored") << endmsg;
1255 if ((prop = child->property("value")) != 0) {
1256 value = prop->value().c_str();
1258 warning << _("LV2: port has no value, ignored") << endmsg;
1262 set_parameter(port_id, atof(value));
1266 if ((prop = node.property("state-dir")) != 0) {
1267 if (sscanf(prop->value().c_str(), "state%u", &_state_version) != 1) {
1268 error << string_compose(
1269 "LV2: failed to parse state version from \"%1\"",
1270 prop->value()) << endmsg;
1273 std::string state_file = Glib::build_filename(
1275 Glib::build_filename(prop->value(), "state.ttl"));
1277 LilvState* state = lilv_state_new_from_file(
1278 _world.world, _uri_map.urid_map(), NULL, state_file.c_str());
1280 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
1283 latency_compute_run();
1285 return Plugin::set_state(node, version);
1289 LV2Plugin::get_parameter_descriptor(uint32_t which, ParameterDescriptor& desc) const
1291 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, which);
1293 LilvNode *def, *min, *max;
1294 lilv_port_get_range(_impl->plugin, port, &def, &min, &max);
1296 desc.integer_step = lilv_port_has_property(_impl->plugin, port, _world.lv2_integer);
1297 desc.toggled = lilv_port_has_property(_impl->plugin, port, _world.lv2_toggled);
1298 desc.logarithmic = lilv_port_has_property(_impl->plugin, port, _world.ext_logarithmic);
1299 desc.sr_dependent = lilv_port_has_property(_impl->plugin, port, _world.lv2_sampleRate);
1300 desc.label = lilv_node_as_string(lilv_port_get_name(_impl->plugin, port));
1301 desc.lower = min ? lilv_node_as_float(min) : 0.0f;
1302 desc.upper = max ? lilv_node_as_float(max) : 1.0f;
1303 if (desc.sr_dependent) {
1304 desc.lower *= _session.frame_rate ();
1305 desc.upper *= _session.frame_rate ();
1308 desc.min_unbound = false; // TODO: LV2 extension required
1309 desc.max_unbound = false; // TODO: LV2 extension required
1311 if (desc.integer_step) {
1313 desc.smallstep = 0.1;
1314 desc.largestep = 10.0;
1316 const float delta = desc.upper - desc.lower;
1317 desc.step = delta / 1000.0f;
1318 desc.smallstep = delta / 10000.0f;
1319 desc.largestep = delta / 10.0f;
1322 desc.enumeration = lilv_port_has_property(_impl->plugin, port, _world.lv2_enumeration);
1324 lilv_node_free(def);
1325 lilv_node_free(min);
1326 lilv_node_free(max);
1332 LV2Plugin::describe_parameter(Evoral::Parameter which)
1334 if (( which.type() == PluginAutomation) && ( which.id() < parameter_count()) ) {
1336 if (lilv_port_has_property(_impl->plugin,
1337 lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.ext_notOnGUI)) {
1338 return X_("hidden");
1341 if (lilv_port_has_property(_impl->plugin,
1342 lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_freewheeling)) {
1343 return X_("hidden");
1346 if (lilv_port_has_property(_impl->plugin,
1347 lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_sampleRate)) {
1348 return X_("hidden");
1351 if (lilv_port_has_property(_impl->plugin,
1352 lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_reportsLatency)) {
1353 return X_("latency");
1356 LilvNode* name = lilv_port_get_name(_impl->plugin,
1357 lilv_plugin_get_port_by_index(_impl->plugin, which.id()));
1358 string ret(lilv_node_as_string(name));
1359 lilv_node_free(name);
1367 LV2Plugin::signal_latency() const
1369 if (_latency_control_port) {
1370 return (framecnt_t)floor(*_latency_control_port);
1376 set<Evoral::Parameter>
1377 LV2Plugin::automatable() const
1379 set<Evoral::Parameter> ret;
1381 for (uint32_t i = 0; i < parameter_count(); ++i) {
1382 if (parameter_is_input(i) && parameter_is_control(i)) {
1383 ret.insert(ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
1391 LV2Plugin::activate()
1393 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 activate\n", name()));
1395 if (!_was_activated) {
1396 lilv_instance_activate(_impl->instance);
1397 _was_activated = true;
1402 LV2Plugin::deactivate()
1404 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 deactivate\n", name()));
1406 if (_was_activated) {
1407 lilv_instance_deactivate(_impl->instance);
1408 _was_activated = false;
1413 LV2Plugin::cleanup()
1415 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 cleanup\n", name()));
1419 lilv_instance_free(_impl->instance);
1420 _impl->instance = NULL;
1424 LV2Plugin::allocate_atom_event_buffers()
1426 /* reserve local scratch buffers for ATOM event-queues */
1427 const LilvPlugin* p = _impl->plugin;
1429 /* count non-MIDI atom event-ports
1430 * TODO: nicely ask drobilla to make a lilv_ call for that
1432 int count_atom_out = 0;
1433 int count_atom_in = 0;
1434 int minimumSize = 32768; // TODO use a per-port minimum-size
1435 for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
1436 const LilvPort* port = lilv_plugin_get_port_by_index(p, i);
1437 if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
1438 LilvNodes* buffer_types = lilv_port_get_value(
1439 p, port, _world.atom_bufferType);
1440 LilvNodes* atom_supports = lilv_port_get_value(
1441 p, port, _world.atom_supports);
1443 if (!lilv_nodes_contains(buffer_types, _world.atom_Sequence)
1444 || !lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
1445 if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
1448 if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
1451 LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
1452 LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
1453 if (min_size && lilv_node_is_int(min_size)) {
1454 minimumSize = std::max(minimumSize, lilv_node_as_int(min_size));
1456 lilv_nodes_free(min_size_v);
1458 lilv_nodes_free(buffer_types);
1459 lilv_nodes_free(atom_supports);
1463 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 need buffers for %2 atom-in and %3 atom-out event-ports\n",
1464 name(), count_atom_in, count_atom_out));
1466 const int total_atom_buffers = (count_atom_in + count_atom_out);
1467 if (_atom_ev_buffers || total_atom_buffers == 0) {
1471 DEBUG_TRACE(DEBUG::LV2, string_compose("allocate %1 atom_ev_buffers\n", total_atom_buffers));
1472 _atom_ev_buffers = (LV2_Evbuf**) malloc((total_atom_buffers + 1) * sizeof(LV2_Evbuf*));
1473 for (int i = 0; i < total_atom_buffers; ++i ) {
1474 _atom_ev_buffers[i] = lv2_evbuf_new(minimumSize, LV2_EVBUF_ATOM,
1475 LV2Plugin::urids.atom_Chunk, LV2Plugin::urids.atom_Sequence);
1477 _atom_ev_buffers[total_atom_buffers] = 0;
1481 /** Write an ardour position/time/tempo/meter as an LV2 event.
1482 * @return true on success.
1485 write_position(LV2_Atom_Forge* forge,
1487 const TempoMetric& t,
1488 Timecode::BBT_Time& bbt,
1490 framepos_t position,
1493 uint8_t pos_buf[256];
1494 lv2_atom_forge_set_buffer(forge, pos_buf, sizeof(pos_buf));
1495 LV2_Atom_Forge_Frame frame;
1496 lv2_atom_forge_blank(forge, &frame, 1, LV2Plugin::urids.time_Position);
1497 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_frame, 0);
1498 lv2_atom_forge_long(forge, position);
1499 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_speed, 0);
1500 lv2_atom_forge_float(forge, speed);
1501 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_barBeat, 0);
1502 lv2_atom_forge_float(forge, bbt.beats - 1 +
1503 (bbt.ticks / Timecode::BBT_Time::ticks_per_beat));
1504 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_bar, 0);
1505 lv2_atom_forge_long(forge, bbt.bars - 1);
1506 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_beatUnit, 0);
1507 lv2_atom_forge_int(forge, t.meter().note_divisor());
1508 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_beatsPerBar, 0);
1509 lv2_atom_forge_float(forge, t.meter().divisions_per_bar());
1510 lv2_atom_forge_property_head(forge, LV2Plugin::urids.time_beatsPerMinute, 0);
1511 lv2_atom_forge_float(forge, t.tempo().beats_per_minute());
1513 LV2_Evbuf_Iterator end = lv2_evbuf_end(buf);
1514 const LV2_Atom* const atom = (const LV2_Atom*)pos_buf;
1515 return lv2_evbuf_write(&end, offset, 0, atom->type, atom->size,
1516 (const uint8_t*)(atom + 1));
1520 LV2Plugin::connect_and_run(BufferSet& bufs,
1521 ChanMapping in_map, ChanMapping out_map,
1522 pframes_t nframes, framecnt_t offset)
1524 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 run %2 offset %3\n", name(), nframes, offset));
1525 Plugin::connect_and_run(bufs, in_map, out_map, nframes, offset);
1527 cycles_t then = get_cycles();
1529 TempoMap& tmap = _session.tempo_map();
1530 Metrics::const_iterator metric_i = tmap.metrics_end();
1531 TempoMetric tmetric = tmap.metric_at(_session.transport_frame(), &metric_i);
1533 if (_freewheel_control_port) {
1534 *_freewheel_control_port = _session.engine().freewheeling();
1537 if (_bpm_control_port) {
1538 *_bpm_control_port = tmetric.tempo().beats_per_minute();
1541 ChanCount bufs_count;
1542 bufs_count.set(DataType::AUDIO, 1);
1543 bufs_count.set(DataType::MIDI, 1);
1544 BufferSet& silent_bufs = _session.get_silent_buffers(bufs_count);
1545 BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
1546 uint32_t const num_ports = parameter_count();
1547 uint32_t const nil_index = std::numeric_limits<uint32_t>::max();
1549 uint32_t audio_in_index = 0;
1550 uint32_t audio_out_index = 0;
1551 uint32_t midi_in_index = 0;
1552 uint32_t midi_out_index = 0;
1553 uint32_t atom_port_index = 0;
1554 for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
1556 uint32_t index = nil_index;
1557 PortFlags flags = _port_flags[port_index];
1559 if (flags & PORT_AUDIO) {
1560 if (flags & PORT_INPUT) {
1561 index = in_map.get(DataType::AUDIO, audio_in_index++, &valid);
1563 ? bufs.get_audio(index).data(offset)
1564 : silent_bufs.get_audio(0).data(offset);
1566 index = out_map.get(DataType::AUDIO, audio_out_index++, &valid);
1568 ? bufs.get_audio(index).data(offset)
1569 : scratch_bufs.get_audio(0).data(offset);
1571 } else if (flags & (PORT_EVENT|PORT_SEQUENCE)) {
1572 /* FIXME: The checks here for bufs.count().n_midi() > index shouldn't
1573 be necessary, but the mapping is illegal in some cases. Ideally
1574 that should be fixed, but this is easier...
1576 if (flags & PORT_MIDI) {
1577 if (flags & PORT_INPUT) {
1578 index = in_map.get(DataType::MIDI, midi_in_index++, &valid);
1580 index = out_map.get(DataType::MIDI, midi_out_index++, &valid);
1582 if (valid && bufs.count().n_midi() > index) {
1583 /* Note, ensure_lv2_bufsize() is not RT safe!
1584 * However free()/alloc() is only called if a
1585 * plugin requires a rsz:minimumSize buffersize
1586 * and the existing buffer if smaller.
1588 bufs.ensure_lv2_bufsize((flags & PORT_INPUT), index, _port_minimumSize[port_index]);
1589 _ev_buffers[port_index] = bufs.get_lv2_midi(
1590 (flags & PORT_INPUT), index, (flags & PORT_EVENT));
1592 } else if ((flags & PORT_POSITION) && (flags & PORT_INPUT)) {
1593 lv2_evbuf_reset(_atom_ev_buffers[atom_port_index], true);
1594 _ev_buffers[port_index] = _atom_ev_buffers[atom_port_index++];
1598 if (valid && (flags & PORT_INPUT)) {
1599 Timecode::BBT_Time bbt;
1600 if ((flags & PORT_POSITION)) {
1601 if (_session.transport_frame() != _next_cycle_start ||
1602 _session.transport_speed() != _next_cycle_speed) {
1603 // Transport has changed, write position at cycle start
1604 tmap.bbt_time(_session.transport_frame(), bbt);
1605 write_position(&_impl->forge, _ev_buffers[port_index],
1606 tmetric, bbt, _session.transport_speed(),
1607 _session.transport_frame(), 0);
1611 // Get MIDI iterator range (empty range if no MIDI)
1612 MidiBuffer::iterator m = (index != nil_index)
1613 ? bufs.get_midi(index).begin()
1614 : silent_bufs.get_midi(0).end();
1615 MidiBuffer::iterator m_end = (index != nil_index)
1616 ? bufs.get_midi(index).end()
1619 // Now merge MIDI and any transport events into the buffer
1620 const uint32_t type = LV2Plugin::urids.midi_MidiEvent;
1621 const framepos_t tend = _session.transport_frame() + nframes;
1623 while (m != m_end || (metric_i != tmap.metrics_end() &&
1624 (*metric_i)->frame() < tend)) {
1625 MetricSection* metric = (metric_i != tmap.metrics_end())
1627 if (m != m_end && (!metric || metric->frame() > (*m).time())) {
1628 const Evoral::MIDIEvent<framepos_t> ev(*m, false);
1629 LV2_Evbuf_Iterator eend = lv2_evbuf_end(_ev_buffers[port_index]);
1630 lv2_evbuf_write(&eend, ev.time(), 0, type, ev.size(), ev.buffer());
1633 tmetric.set_metric(metric);
1634 bbt = metric->start();
1635 write_position(&_impl->forge, _ev_buffers[port_index],
1636 tmetric, bbt, _session.transport_speed(),
1638 metric->frame() - _session.transport_frame());
1642 } else if (!valid) {
1643 // Nothing we understand or care about, connect to scratch
1644 _ev_buffers[port_index] = silent_bufs.get_lv2_midi(
1645 (flags & PORT_INPUT), 0, (flags & PORT_EVENT));
1647 buf = lv2_evbuf_get_buffer(_ev_buffers[port_index]);
1649 continue; // Control port, leave buffer alone
1651 lilv_instance_connect_port(_impl->instance, port_index, buf);
1654 // Read messages from UI and push into appropriate buffers
1656 uint32_t read_space = _from_ui->read_space();
1657 while (read_space > sizeof(UIMessage)) {
1659 if (_from_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1660 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
1663 uint8_t body[msg.size];
1664 if (_from_ui->read(body, msg.size) != msg.size) {
1665 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
1668 if (msg.protocol == urids.atom_eventTransfer) {
1669 LV2_Evbuf* buf = _ev_buffers[msg.index];
1670 LV2_Evbuf_Iterator i = lv2_evbuf_end(buf);
1671 const LV2_Atom* const atom = (const LV2_Atom*)body;
1672 if (!lv2_evbuf_write(&i, nframes, 0, atom->type, atom->size,
1673 (const uint8_t*)(atom + 1))) {
1674 error << "Failed to write data to LV2 event buffer\n";
1677 error << "Received unknown message type from UI" << endmsg;
1679 read_space -= sizeof(UIMessage) + msg.size;
1686 for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
1687 PortFlags flags = _port_flags[port_index];
1690 /* TODO ask drobilla about comment
1691 * "Make Ardour event buffers generic so plugins can communicate"
1692 * in libs/ardour/buffer_set.cc:310
1694 * ideally the user could choose which of the following two modes
1695 * to use (e.g. instrument/effect chains MIDI OUT vs MIDI TRHU).
1697 * This implementation follows the discussion on IRC Mar 16 2013 16:47 UTC
1698 * 16:51 < drobilla> rgareus: [..] i.e always replace with MIDI output [of LV2 plugin] if it's there
1699 * 16:52 < drobilla> rgareus: That would probably be good enough [..] to make users not complain
1700 * for quite a while at least ;)
1702 // copy output of LV2 plugin's MIDI port to Ardour MIDI buffers -- MIDI OUT
1703 if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE|PORT_MIDI))) {
1704 const uint32_t buf_index = out_map.get(
1705 DataType::MIDI, midi_out_index++, &valid);
1707 bufs.forward_lv2_midi(_ev_buffers[port_index], buf_index);
1710 // Flush MIDI (write back to Ardour MIDI buffers) -- MIDI THRU
1711 else if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
1712 const uint32_t buf_index = out_map.get(
1713 DataType::MIDI, midi_out_index++, &valid);
1715 bufs.flush_lv2_midi(true, buf_index);
1719 // Write messages to UI
1720 if (_to_ui && (flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
1721 LV2_Evbuf* buf = _ev_buffers[port_index];
1722 for (LV2_Evbuf_Iterator i = lv2_evbuf_begin(buf);
1723 lv2_evbuf_is_valid(i);
1724 i = lv2_evbuf_next(i)) {
1725 uint32_t frames, subframes, type, size;
1727 lv2_evbuf_get(i, &frames, &subframes, &type, &size, &data);
1728 write_to_ui(port_index, urids.atom_eventTransfer,
1729 size + sizeof(LV2_Atom),
1730 data - sizeof(LV2_Atom));
1735 cycles_t now = get_cycles();
1736 set_cycles((uint32_t)(now - then));
1738 // Update expected transport information for next cycle so we can detect changes
1739 _next_cycle_speed = _session.transport_speed();
1740 _next_cycle_start = _session.transport_frame() + (nframes * _next_cycle_speed);
1746 LV2Plugin::parameter_is_control(uint32_t param) const
1748 assert(param < _port_flags.size());
1749 return _port_flags[param] & PORT_CONTROL;
1753 LV2Plugin::parameter_is_audio(uint32_t param) const
1755 assert(param < _port_flags.size());
1756 return _port_flags[param] & PORT_AUDIO;
1760 LV2Plugin::parameter_is_event(uint32_t param) const
1762 assert(param < _port_flags.size());
1763 return _port_flags[param] & PORT_EVENT;
1767 LV2Plugin::parameter_is_output(uint32_t param) const
1769 assert(param < _port_flags.size());
1770 return _port_flags[param] & PORT_OUTPUT;
1774 LV2Plugin::parameter_is_input(uint32_t param) const
1776 assert(param < _port_flags.size());
1777 return _port_flags[param] & PORT_INPUT;
1781 LV2Plugin::print_parameter(uint32_t param, char* buf, uint32_t len) const
1784 if (param < parameter_count()) {
1785 snprintf(buf, len, "%.3f", get_parameter(param));
1792 boost::shared_ptr<Plugin::ScalePoints>
1793 LV2Plugin::get_scale_points(uint32_t port_index) const
1795 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, port_index);
1796 LilvScalePoints* points = lilv_port_get_scale_points(_impl->plugin, port);
1798 boost::shared_ptr<Plugin::ScalePoints> ret;
1803 ret = boost::shared_ptr<Plugin::ScalePoints>(new ScalePoints());
1805 LILV_FOREACH(scale_points, i, points) {
1806 const LilvScalePoint* p = lilv_scale_points_get(points, i);
1807 const LilvNode* label = lilv_scale_point_get_label(p);
1808 const LilvNode* value = lilv_scale_point_get_value(p);
1809 if (label && (lilv_node_is_float(value) || lilv_node_is_int(value))) {
1810 ret->insert(make_pair(lilv_node_as_string(label),
1811 lilv_node_as_float(value)));
1815 lilv_scale_points_free(points);
1820 LV2Plugin::run(pframes_t nframes)
1822 uint32_t const N = parameter_count();
1823 for (uint32_t i = 0; i < N; ++i) {
1824 if (parameter_is_control(i) && parameter_is_input(i)) {
1825 _control_data[i] = _shadow_data[i];
1829 lilv_instance_run(_impl->instance, nframes);
1831 if (_impl->work_iface) {
1832 _worker->emit_responses();
1833 if (_impl->work_iface->end_run) {
1834 _impl->work_iface->end_run(_impl->instance->lv2_handle);
1840 LV2Plugin::latency_compute_run()
1842 if (!_latency_control_port) {
1846 // Run the plugin so that it can set its latency parameter
1850 uint32_t port_index = 0;
1851 uint32_t in_index = 0;
1852 uint32_t out_index = 0;
1854 const framecnt_t bufsize = 1024;
1855 float buffer[bufsize];
1857 memset(buffer, 0, sizeof(float) * bufsize);
1859 // FIXME: Ensure plugins can handle in-place processing
1863 while (port_index < parameter_count()) {
1864 if (parameter_is_audio(port_index)) {
1865 if (parameter_is_input(port_index)) {
1866 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1868 } else if (parameter_is_output(port_index)) {
1869 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1881 LV2Plugin::Impl::designated_input (const char* uri, void** bufptrs[], void** bufptr)
1883 const LilvPort* port = NULL;
1884 LilvNode* designation = lilv_new_uri(_world.world, uri);
1885 port = lilv_plugin_get_port_by_designation(
1886 plugin, _world.lv2_InputPort, designation);
1887 lilv_node_free(designation);
1889 bufptrs[lilv_port_get_index(plugin, port)] = bufptr;
1894 LV2World::LV2World()
1895 : world(lilv_world_new())
1897 lilv_world_load_all(world);
1898 atom_AtomPort = lilv_new_uri(world, LV2_ATOM__AtomPort);
1899 atom_Chunk = lilv_new_uri(world, LV2_ATOM__Chunk);
1900 atom_Sequence = lilv_new_uri(world, LV2_ATOM__Sequence);
1901 atom_bufferType = lilv_new_uri(world, LV2_ATOM__bufferType);
1902 atom_supports = lilv_new_uri(world, LV2_ATOM__supports);
1903 atom_eventTransfer = lilv_new_uri(world, LV2_ATOM__eventTransfer);
1904 ev_EventPort = lilv_new_uri(world, LILV_URI_EVENT_PORT);
1905 ext_logarithmic = lilv_new_uri(world, LV2_PORT_PROPS__logarithmic);
1906 ext_notOnGUI = lilv_new_uri(world, LV2_PORT_PROPS__notOnGUI);
1907 lv2_AudioPort = lilv_new_uri(world, LILV_URI_AUDIO_PORT);
1908 lv2_ControlPort = lilv_new_uri(world, LILV_URI_CONTROL_PORT);
1909 lv2_InputPort = lilv_new_uri(world, LILV_URI_INPUT_PORT);
1910 lv2_OutputPort = lilv_new_uri(world, LILV_URI_OUTPUT_PORT);
1911 lv2_inPlaceBroken = lilv_new_uri(world, LV2_CORE__inPlaceBroken);
1912 lv2_integer = lilv_new_uri(world, LV2_CORE__integer);
1913 lv2_reportsLatency = lilv_new_uri(world, LV2_CORE__reportsLatency);
1914 lv2_sampleRate = lilv_new_uri(world, LV2_CORE__sampleRate);
1915 lv2_toggled = lilv_new_uri(world, LV2_CORE__toggled);
1916 lv2_enumeration = lilv_new_uri(world, LV2_CORE__enumeration);
1917 lv2_freewheeling = lilv_new_uri(world, LV2_CORE__freeWheeling);
1918 midi_MidiEvent = lilv_new_uri(world, LILV_URI_MIDI_EVENT);
1919 rdfs_comment = lilv_new_uri(world, LILV_NS_RDFS "comment");
1920 rsz_minimumSize = lilv_new_uri(world, LV2_RESIZE_PORT__minimumSize);
1921 time_Position = lilv_new_uri(world, LV2_TIME__Position);
1922 ui_GtkUI = lilv_new_uri(world, LV2_UI__GtkUI);
1923 ui_external = lilv_new_uri(world, "http://lv2plug.in/ns/extensions/ui#external");
1926 LV2World::~LV2World()
1928 lilv_node_free(ui_external);
1929 lilv_node_free(ui_GtkUI);
1930 lilv_node_free(time_Position);
1931 lilv_node_free(rsz_minimumSize);
1932 lilv_node_free(rdfs_comment);
1933 lilv_node_free(midi_MidiEvent);
1934 lilv_node_free(lv2_enumeration);
1935 lilv_node_free(lv2_freewheeling);
1936 lilv_node_free(lv2_toggled);
1937 lilv_node_free(lv2_sampleRate);
1938 lilv_node_free(lv2_reportsLatency);
1939 lilv_node_free(lv2_integer);
1940 lilv_node_free(lv2_inPlaceBroken);
1941 lilv_node_free(lv2_OutputPort);
1942 lilv_node_free(lv2_InputPort);
1943 lilv_node_free(lv2_ControlPort);
1944 lilv_node_free(lv2_AudioPort);
1945 lilv_node_free(ext_notOnGUI);
1946 lilv_node_free(ext_logarithmic);
1947 lilv_node_free(ev_EventPort);
1948 lilv_node_free(atom_supports);
1949 lilv_node_free(atom_eventTransfer);
1950 lilv_node_free(atom_bufferType);
1951 lilv_node_free(atom_Sequence);
1952 lilv_node_free(atom_Chunk);
1953 lilv_node_free(atom_AtomPort);
1956 LV2PluginInfo::LV2PluginInfo (const void* c_plugin)
1957 : _c_plugin(c_plugin)
1962 LV2PluginInfo::~LV2PluginInfo()
1966 LV2PluginInfo::load(Session& session)
1971 plugin.reset(new LV2Plugin(session.engine(), session,
1972 (const LilvPlugin*)_c_plugin,
1973 session.frame_rate()));
1975 plugin->set_info(PluginInfoPtr(new LV2PluginInfo(*this)));
1977 } catch (failed_constructor& err) {
1978 return PluginPtr((Plugin*)0);
1985 LV2PluginInfo::discover()
1987 PluginInfoList* plugs = new PluginInfoList;
1988 const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
1990 info << "LV2: Discovering " << lilv_plugins_size(plugins) << " plugins" << endmsg;
1992 LILV_FOREACH(plugins, i, plugins) {
1993 const LilvPlugin* p = lilv_plugins_get(plugins, i);
1994 LV2PluginInfoPtr info(new LV2PluginInfo((const void*)p));
1996 LilvNode* name = lilv_plugin_get_name(p);
1997 if (!name || !lilv_plugin_get_port_by_index(p, 0)) {
1998 warning << "Ignoring invalid LV2 plugin "
1999 << lilv_node_as_string(lilv_plugin_get_uri(p))
2006 info->name = string(lilv_node_as_string(name));
2007 lilv_node_free(name);
2009 const LilvPluginClass* pclass = lilv_plugin_get_class(p);
2010 const LilvNode* label = lilv_plugin_class_get_label(pclass);
2011 info->category = lilv_node_as_string(label);
2013 LilvNode* author_name = lilv_plugin_get_author_name(p);
2014 info->creator = author_name ? string(lilv_node_as_string(author_name)) : "Unknown";
2015 lilv_node_free(author_name);
2017 info->path = "/NOPATH"; // Meaningless for LV2
2019 /* count atom-event-ports that feature
2020 * atom:supports <http://lv2plug.in/ns/ext/midi#MidiEvent>
2022 * TODO: nicely ask drobilla to make a lilv_ call for that
2024 int count_midi_out = 0;
2025 int count_midi_in = 0;
2026 for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
2027 const LilvPort* port = lilv_plugin_get_port_by_index(p, i);
2028 if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
2029 LilvNodes* buffer_types = lilv_port_get_value(
2030 p, port, _world.atom_bufferType);
2031 LilvNodes* atom_supports = lilv_port_get_value(
2032 p, port, _world.atom_supports);
2034 if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)
2035 && lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
2036 if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
2039 if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
2043 lilv_nodes_free(buffer_types);
2044 lilv_nodes_free(atom_supports);
2048 info->n_inputs.set_audio(
2049 lilv_plugin_get_num_ports_of_class(
2050 p, _world.lv2_InputPort, _world.lv2_AudioPort, NULL));
2051 info->n_inputs.set_midi(
2052 lilv_plugin_get_num_ports_of_class(
2053 p, _world.lv2_InputPort, _world.ev_EventPort, NULL)
2056 info->n_outputs.set_audio(
2057 lilv_plugin_get_num_ports_of_class(
2058 p, _world.lv2_OutputPort, _world.lv2_AudioPort, NULL));
2059 info->n_outputs.set_midi(
2060 lilv_plugin_get_num_ports_of_class(
2061 p, _world.lv2_OutputPort, _world.ev_EventPort, NULL)
2064 info->unique_id = lilv_node_as_uri(lilv_plugin_get_uri(p));
2065 info->index = 0; // Meaningless for LV2
2067 plugs->push_back(info);