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.
29 #include "pbd/gstdio_compat.h"
30 #include <glib/gprintf.h>
33 #include <boost/utility.hpp>
35 #include "pbd/file_utils.h"
36 #include "pbd/stl_delete.h"
37 #include "pbd/compose.h"
38 #include "pbd/error.h"
39 #include "pbd/replace_all.h"
40 #include "pbd/xml++.h"
42 #include "libardour-config.h"
44 #include "ardour/audio_buffer.h"
45 #include "ardour/audioengine.h"
46 #include "ardour/debug.h"
47 #include "ardour/lv2_plugin.h"
48 #include "ardour/session.h"
49 #include "ardour/tempo.h"
50 #include "ardour/types.h"
51 #include "ardour/utils.h"
52 #include "ardour/worker.h"
53 #include "ardour/search_paths.h"
58 #include <lilv/lilv.h>
60 #include "lv2/lv2plug.in/ns/ext/atom/atom.h"
61 #include "lv2/lv2plug.in/ns/ext/atom/forge.h"
62 #include "lv2/lv2plug.in/ns/ext/log/log.h"
63 #include "lv2/lv2plug.in/ns/ext/midi/midi.h"
64 #include "lv2/lv2plug.in/ns/ext/port-props/port-props.h"
65 #include "lv2/lv2plug.in/ns/ext/presets/presets.h"
66 #include "lv2/lv2plug.in/ns/ext/state/state.h"
67 #include "lv2/lv2plug.in/ns/ext/time/time.h"
68 #include "lv2/lv2plug.in/ns/ext/worker/worker.h"
69 #include "lv2/lv2plug.in/ns/ext/resize-port/resize-port.h"
70 #include "lv2/lv2plug.in/ns/extensions/ui/ui.h"
71 #include "lv2/lv2plug.in/ns/extensions/units/units.h"
72 #include "lv2/lv2plug.in/ns/ext/patch/patch.h"
74 #include "lv2/lv2plug.in/ns/ext/buf-size/buf-size.h"
75 #include "lv2/lv2plug.in/ns/ext/options/options.h"
78 #include "lv2_evbuf.h"
81 #include <suil/suil.h>
84 // Compatibility for old LV2
85 #ifndef LV2_ATOM_CONTENTS_CONST
86 #define LV2_ATOM_CONTENTS_CONST(type, atom) \
87 ((const void*)((const uint8_t*)(atom) + sizeof(type)))
89 #ifndef LV2_ATOM_BODY_CONST
90 #define LV2_ATOM_BODY_CONST(atom) LV2_ATOM_CONTENTS_CONST(LV2_Atom, atom)
92 #ifndef LV2_PATCH__property
93 #define LV2_PATCH__property LV2_PATCH_PREFIX "property"
95 #ifndef LV2_PATCH__value
96 #define LV2_PATCH__value LV2_PATCH_PREFIX "value"
98 #ifndef LV2_PATCH__writable
99 #define LV2_PATCH__writable LV2_PATCH_PREFIX "writable"
102 /** The number of MIDI buffers that will fit in a UI/worker comm buffer.
103 This needs to be roughly the number of cycles the UI will get around to
104 actually processing the traffic. Lower values are flakier but save memory.
106 static const size_t NBUFS = 4;
109 using namespace ARDOUR;
112 class LV2World : boost::noncopyable {
117 void load_bundled_plugins(bool verbose=false);
121 LilvNode* atom_AtomPort;
122 LilvNode* atom_Chunk;
123 LilvNode* atom_Sequence;
124 LilvNode* atom_bufferType;
125 LilvNode* atom_eventTransfer;
126 LilvNode* atom_supports;
127 LilvNode* ev_EventPort;
128 LilvNode* ext_logarithmic;
129 LilvNode* ext_notOnGUI;
130 LilvNode* ext_expensive;
131 LilvNode* ext_causesArtifacts;
132 LilvNode* ext_notAutomatic;
133 LilvNode* ext_rangeSteps;
134 LilvNode* lv2_AudioPort;
135 LilvNode* lv2_ControlPort;
136 LilvNode* lv2_InputPort;
137 LilvNode* lv2_OutputPort;
138 LilvNode* lv2_enumeration;
139 LilvNode* lv2_freewheeling;
140 LilvNode* lv2_inPlaceBroken;
141 LilvNode* lv2_isSideChain;
142 LilvNode* lv2_integer;
143 LilvNode* lv2_default;
144 LilvNode* lv2_minimum;
145 LilvNode* lv2_maximum;
146 LilvNode* lv2_reportsLatency;
147 LilvNode* lv2_sampleRate;
148 LilvNode* lv2_toggled;
149 LilvNode* midi_MidiEvent;
150 LilvNode* rdfs_comment;
151 LilvNode* rdfs_label;
152 LilvNode* rdfs_range;
153 LilvNode* rsz_minimumSize;
154 LilvNode* time_Position;
156 LilvNode* ui_external;
157 LilvNode* ui_externalkx;
160 LilvNode* units_unit;
161 LilvNode* units_render;
162 LilvNode* units_midiNote;
163 LilvNode* patch_writable;
164 LilvNode* patch_Message;
165 #ifdef HAVE_LV2_1_2_0
166 LilvNode* bufz_powerOf2BlockLength;
167 LilvNode* bufz_fixedBlockLength;
168 LilvNode* bufz_nominalBlockLength;
171 #ifdef HAVE_LV2_1_10_0
173 LilvNode* atom_float;
174 LilvNode* atom_object; // new in 1.8
175 LilvNode* atom_vector;
178 LilvNode* lv2_noSampleAccurateCtrl;
179 LilvNode* auto_can_write_automatation; // lv2:optionalFeature
180 LilvNode* auto_automation_control; // atom:supports
181 LilvNode* auto_automation_controlled; // lv2:portProperty
182 LilvNode* auto_automation_controller; // lv2:portProperty
186 bool _bundle_checked;
189 static LV2World _world;
191 /* worker extension */
193 /** Called by the plugin to schedule non-RT work. */
194 static LV2_Worker_Status
195 work_schedule(LV2_Worker_Schedule_Handle handle,
199 return (((Worker*)handle)->schedule(size, data)
201 : LV2_WORKER_ERR_UNKNOWN);
204 /** Called by the plugin to respond to non-RT work. */
205 static LV2_Worker_Status
206 work_respond(LV2_Worker_Respond_Handle handle,
210 return (((Worker*)handle)->respond(size, data)
212 : LV2_WORKER_ERR_UNKNOWN);
216 /* inline display extension */
218 queue_draw (LV2_Inline_Display_Handle handle)
220 LV2Plugin* plugin = (LV2Plugin*)handle;
221 plugin->QueueDraw(); /* EMIT SIGNAL */
228 log_vprintf(LV2_Log_Handle /*handle*/,
234 const int ret = g_vasprintf(&str, fmt, args);
235 /* strip trailing whitespace */
236 while (strlen (str) > 0 && isspace (str[strlen (str) - 1])) {
237 str[strlen (str) - 1] = '\0';
239 if (strlen (str) == 0) {
243 if (type == URIMap::instance().urids.log_Error) {
244 error << str << endmsg;
245 } else if (type == URIMap::instance().urids.log_Warning) {
246 warning << str << endmsg;
247 } else if (type == URIMap::instance().urids.log_Note) {
248 info << str << endmsg;
249 } else if (type == URIMap::instance().urids.log_Trace) {
250 DEBUG_TRACE(DEBUG::LV2, str);
256 log_printf(LV2_Log_Handle handle,
258 const char* fmt, ...)
262 const int ret = log_vprintf(handle, type, fmt, args);
267 struct LV2Plugin::Impl {
268 Impl() : plugin(0), ui(0), ui_type(0), name(0), author(0), instance(0)
270 #ifdef HAVE_LV2_1_2_0
275 #ifdef HAVE_LV2_1_2_0
283 /** Find the LV2 input port with the given designation.
284 * If found, bufptrs[port_index] will be set to bufptr.
286 const LilvPort* designated_input (const char* uri, void** bufptrs[], void** bufptr);
288 const LilvPlugin* plugin;
290 const LilvNode* ui_type;
293 LilvInstance* instance;
294 const LV2_Worker_Interface* work_iface;
295 #ifdef HAVE_LV2_1_2_0
296 const LV2_Options_Interface* opts_iface;
299 LV2_Atom_Forge forge;
300 LV2_Atom_Forge ui_forge;
301 int32_t block_length;
302 #ifdef HAVE_LV2_1_2_0
303 LV2_Options_Option* options;
306 LV2_Inline_Display* queue_draw;
310 LV2Plugin::LV2Plugin (AudioEngine& engine,
312 const void* c_plugin,
314 : Plugin (engine, session)
319 , _state_worker(NULL)
321 , _patch_port_in_index((uint32_t)-1)
322 , _patch_port_out_index((uint32_t)-1)
323 , _uri_map(URIMap::instance())
324 , _no_sample_accurate_ctrl (false)
326 init(c_plugin, rate);
329 LV2Plugin::LV2Plugin (const LV2Plugin& other)
335 , _state_worker(NULL)
336 , _insert_id(other._insert_id)
337 , _patch_port_in_index((uint32_t)-1)
338 , _patch_port_out_index((uint32_t)-1)
339 , _uri_map(URIMap::instance())
340 , _no_sample_accurate_ctrl (false)
342 init(other._impl->plugin, other._sample_rate);
344 for (uint32_t i = 0; i < parameter_count(); ++i) {
345 _control_data[i] = other._shadow_data[i];
346 _shadow_data[i] = other._shadow_data[i];
351 LV2Plugin::init(const void* c_plugin, framecnt_t rate)
353 DEBUG_TRACE(DEBUG::LV2, "init\n");
355 _impl->plugin = (const LilvPlugin*)c_plugin;
357 _impl->ui_type = NULL;
362 _atom_ev_buffers = 0;
364 _bpm_control_port = 0;
365 _freewheel_control_port = 0;
366 _latency_control_port = 0;
367 _next_cycle_start = std::numeric_limits<framepos_t>::max();
368 _next_cycle_speed = 1.0;
369 _seq_size = _engine.raw_buffer_size(DataType::MIDI);
371 _was_activated = false;
372 _has_state_interface = false;
373 _can_write_automation = false;
375 _current_latency = 0;
376 _impl->block_length = _session.get_block_size();
378 _instance_access_feature.URI = "http://lv2plug.in/ns/ext/instance-access";
379 _data_access_feature.URI = "http://lv2plug.in/ns/ext/data-access";
380 _make_path_feature.URI = LV2_STATE__makePath;
381 _log_feature.URI = LV2_LOG__log;
382 _work_schedule_feature.URI = LV2_WORKER__schedule;
383 _work_schedule_feature.data = NULL;
384 _def_state_feature.URI = LV2_STATE_PREFIX "loadDefaultState"; // Post LV2-1.2.0
385 _def_state_feature.data = NULL;
387 const LilvPlugin* plugin = _impl->plugin;
389 LilvNode* state_iface_uri = lilv_new_uri(_world.world, LV2_STATE__interface);
390 LilvNode* state_uri = lilv_new_uri(_world.world, LV2_STATE_URI);
391 _has_state_interface =
392 // What plugins should have (lv2:extensionData state:Interface)
393 lilv_plugin_has_extension_data(plugin, state_iface_uri)
394 // What some outdated/incorrect ones have
395 || lilv_plugin_has_feature(plugin, state_uri);
396 lilv_node_free(state_uri);
397 lilv_node_free(state_iface_uri);
399 _features = (LV2_Feature**)calloc(12, sizeof(LV2_Feature*));
400 _features[0] = &_instance_access_feature;
401 _features[1] = &_data_access_feature;
402 _features[2] = &_make_path_feature;
403 _features[3] = _uri_map.uri_map_feature();
404 _features[4] = _uri_map.urid_map_feature();
405 _features[5] = _uri_map.urid_unmap_feature();
406 _features[6] = &_log_feature;
408 unsigned n_features = 7;
409 #ifdef HAVE_LV2_1_2_0
410 _features[n_features++] = &_def_state_feature;
413 lv2_atom_forge_init(&_impl->forge, _uri_map.urid_map());
414 lv2_atom_forge_init(&_impl->ui_forge, _uri_map.urid_map());
417 _impl->queue_draw = (LV2_Inline_Display*)
418 malloc (sizeof(LV2_Inline_Display));
419 _impl->queue_draw->handle = this;
420 _impl->queue_draw->queue_draw = queue_draw;
422 _queue_draw_feature.URI = LV2_INLINEDISPLAY__queue_draw;
423 _queue_draw_feature.data = _impl->queue_draw;
424 _features[n_features++] = &_queue_draw_feature;
427 #ifdef HAVE_LV2_1_2_0
428 LV2_URID atom_Int = _uri_map.uri_to_id(LV2_ATOM__Int);
429 static const int32_t _min_block_length = 1; // may happen during split-cycles
430 static const int32_t _max_block_length = 8192; // max possible (with all engines and during export)
431 /* Consider updating max-block-size whenever the buffersize changes.
432 * It requires re-instantiating the plugin (which is a non-realtime operation),
433 * so it should be done lightly and only for plugins that require it.
435 * given that the block-size can change at any time (split-cycles) ardour currently
436 * does not support plugins that require bufz_fixedBlockLength.
438 LV2_Options_Option options[] = {
439 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__minBlockLength),
440 sizeof(int32_t), atom_Int, &_min_block_length },
441 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__maxBlockLength),
442 sizeof(int32_t), atom_Int, &_max_block_length },
443 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__sequenceSize),
444 sizeof(int32_t), atom_Int, &_seq_size },
445 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id("http://lv2plug.in/ns/ext/buf-size#nominalBlockLength"),
446 sizeof(int32_t), atom_Int, &_impl->block_length },
447 { LV2_OPTIONS_INSTANCE, 0, 0, 0, 0, NULL }
450 _impl->options = (LV2_Options_Option*) malloc (sizeof (options));
451 memcpy ((void*) _impl->options, (void*) options, sizeof (options));
453 _options_feature.URI = LV2_OPTIONS__options;
454 _options_feature.data = _impl->options;
455 _features[n_features++] = &_options_feature;
458 LV2_State_Make_Path* make_path = (LV2_State_Make_Path*)malloc(
459 sizeof(LV2_State_Make_Path));
460 make_path->handle = this;
461 make_path->path = &lv2_state_make_path;
462 _make_path_feature.data = make_path;
464 LV2_Log_Log* log = (LV2_Log_Log*)malloc(sizeof(LV2_Log_Log));
466 log->printf = &log_printf;
467 log->vprintf = &log_vprintf;
468 _log_feature.data = log;
470 const size_t ring_size = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
471 LilvNode* worker_schedule = lilv_new_uri(_world.world, LV2_WORKER__schedule);
472 if (lilv_plugin_has_feature(plugin, worker_schedule)) {
473 LV2_Worker_Schedule* schedule = (LV2_Worker_Schedule*)malloc(
474 sizeof(LV2_Worker_Schedule));
475 _worker = new Worker(this, ring_size);
476 schedule->handle = _worker;
477 schedule->schedule_work = work_schedule;
478 _work_schedule_feature.data = schedule;
479 _features[n_features++] = &_work_schedule_feature;
481 lilv_node_free(worker_schedule);
483 if (_has_state_interface) {
484 // Create a non-threaded worker for use by state restore
485 _state_worker = new Worker(this, ring_size, false);
488 _impl->instance = lilv_plugin_instantiate(plugin, rate, _features);
489 _impl->name = lilv_plugin_get_name(plugin);
490 _impl->author = lilv_plugin_get_author_name(plugin);
492 if (_impl->instance == 0) {
493 error << _("LV2: Failed to instantiate plugin ") << uri() << endmsg;
494 throw failed_constructor();
497 _instance_access_feature.data = (void*)_impl->instance->lv2_handle;
498 _data_access_extension_data.extension_data = _impl->instance->lv2_descriptor->extension_data;
499 _data_access_feature.data = &_data_access_extension_data;
501 LilvNode* worker_iface_uri = lilv_new_uri(_world.world, LV2_WORKER__interface);
502 if (lilv_plugin_has_extension_data(plugin, worker_iface_uri)) {
503 _impl->work_iface = (const LV2_Worker_Interface*)extension_data(
504 LV2_WORKER__interface);
506 lilv_node_free(worker_iface_uri);
509 #ifdef HAVE_LV2_1_2_0
510 LilvNode* options_iface_uri = lilv_new_uri(_world.world, LV2_OPTIONS__interface);
511 if (lilv_plugin_has_extension_data(plugin, options_iface_uri)) {
512 _impl->opts_iface = (const LV2_Options_Interface*)extension_data(
513 LV2_OPTIONS__interface);
515 lilv_node_free(options_iface_uri);
519 _display_interface = (const LV2_Inline_Display_Interface*)
520 extension_data (LV2_INLINEDISPLAY__interface);
523 if (lilv_plugin_has_feature(plugin, _world.lv2_inPlaceBroken)) {
524 error << string_compose(
525 _("LV2: \"%1\" cannot be used, since it cannot do inplace processing."),
526 lilv_node_as_string(_impl->name)) << endmsg;
527 lilv_node_free(_impl->name);
528 lilv_node_free(_impl->author);
529 throw failed_constructor();
532 #ifdef HAVE_LV2_1_2_0
533 LilvNodes *required_features = lilv_plugin_get_required_features (plugin);
534 if (lilv_nodes_contains (required_features, _world.bufz_powerOf2BlockLength) ||
535 lilv_nodes_contains (required_features, _world.bufz_fixedBlockLength)
537 error << string_compose(
538 _("LV2: \"%1\" buffer-size requirements cannot be satisfied."),
539 lilv_node_as_string(_impl->name)) << endmsg;
540 lilv_node_free(_impl->name);
541 lilv_node_free(_impl->author);
542 lilv_nodes_free(required_features);
543 throw failed_constructor();
545 lilv_nodes_free(required_features);
549 LilvNodes* optional_features = lilv_plugin_get_optional_features (plugin);
550 if (lilv_nodes_contains (optional_features, _world.lv2_noSampleAccurateCtrl)) {
551 _no_sample_accurate_ctrl = true;
553 if (lilv_nodes_contains (optional_features, _world.auto_can_write_automatation)) {
554 _can_write_automation = true;
556 lilv_nodes_free(optional_features);
559 #ifdef HAVE_LILV_0_16_0
560 // Load default state
562 /* immediately schedule any work,
563 * so that state restore later will not find a busy
564 * worker. latency_compute_run() flushes any replies
566 _worker->set_synchronous(true);
568 LilvState* state = lilv_state_new_from_world(
569 _world.world, _uri_map.urid_map(), lilv_plugin_get_uri(_impl->plugin));
570 if (state && _has_state_interface) {
571 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
573 lilv_state_free(state);
578 const uint32_t num_ports = this->num_ports();
579 for (uint32_t i = 0; i < num_ports; ++i) {
580 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, i);
582 size_t minimumSize = 0;
584 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_OutputPort)) {
585 flags |= PORT_OUTPUT;
586 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_InputPort)) {
589 error << string_compose(
590 "LV2: \"%1\" port %2 is neither input nor output",
591 lilv_node_as_string(_impl->name), i) << endmsg;
592 throw failed_constructor();
595 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_ControlPort)) {
596 flags |= PORT_CONTROL;
597 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_AudioPort)) {
599 } else if (lilv_port_is_a(_impl->plugin, port, _world.ev_EventPort)) {
601 flags |= PORT_MIDI; // We assume old event API ports are for MIDI
602 } else if (lilv_port_is_a(_impl->plugin, port, _world.atom_AtomPort)) {
603 LilvNodes* buffer_types = lilv_port_get_value(
604 _impl->plugin, port, _world.atom_bufferType);
605 LilvNodes* atom_supports = lilv_port_get_value(
606 _impl->plugin, port, _world.atom_supports);
608 if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)) {
609 flags |= PORT_SEQUENCE;
610 if (lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
613 if (lilv_nodes_contains(atom_supports, _world.time_Position)) {
614 flags |= PORT_POSITION;
617 if (lilv_nodes_contains(atom_supports, _world.auto_automation_control)) {
618 flags |= PORT_AUTOCTRL;
621 if (lilv_nodes_contains(atom_supports, _world.patch_Message)) {
622 flags |= PORT_PATCHMSG;
623 if (flags & PORT_INPUT) {
624 _patch_port_in_index = i;
626 _patch_port_out_index = i;
630 LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
631 LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
632 if (min_size && lilv_node_is_int(min_size)) {
633 minimumSize = lilv_node_as_int(min_size);
635 lilv_nodes_free(min_size_v);
636 lilv_nodes_free(buffer_types);
637 lilv_nodes_free(atom_supports);
639 error << string_compose(
640 "LV2: \"%1\" port %2 has no known data type",
641 lilv_node_as_string(_impl->name), i) << endmsg;
642 throw failed_constructor();
645 if ((flags & PORT_INPUT) && (flags & PORT_CONTROL)) {
646 if (lilv_port_has_property(_impl->plugin, port, _world.ext_causesArtifacts)) {
647 flags |= PORT_NOAUTO;
649 if (lilv_port_has_property(_impl->plugin, port, _world.ext_notAutomatic)) {
650 flags |= PORT_NOAUTO;
652 if (lilv_port_has_property(_impl->plugin, port, _world.ext_expensive)) {
653 flags |= PORT_NOAUTO;
657 if (lilv_port_has_property(_impl->plugin, port, _world.auto_automation_controlled)) {
658 if ((flags & PORT_INPUT) && (flags & PORT_CONTROL)) {
659 flags |= PORT_CTRLED;
662 if (lilv_port_has_property(_impl->plugin, port, _world.auto_automation_controller)) {
663 if ((flags & PORT_INPUT) && (flags & PORT_CONTROL)) {
664 flags |= PORT_CTRLER;
669 _port_flags.push_back(flags);
670 _port_minimumSize.push_back(minimumSize);
671 DEBUG_TRACE(DEBUG::LV2, string_compose("port %1 buffer %2 bytes\n", i, minimumSize));
674 _control_data = new float[num_ports];
675 _shadow_data = new float[num_ports];
676 _defaults = new float[num_ports];
677 _ev_buffers = new LV2_Evbuf*[num_ports];
678 memset(_ev_buffers, 0, sizeof(LV2_Evbuf*) * num_ports);
680 const bool latent = lilv_plugin_has_latency(plugin);
681 const uint32_t latency_index = (latent)
682 ? lilv_plugin_get_latency_port_index(plugin)
685 // Build an array of pointers to special parameter buffers
686 void*** params = new void**[num_ports];
687 for (uint32_t i = 0; i < num_ports; ++i) {
690 _impl->designated_input (LV2_TIME__beatsPerMinute, params, (void**)&_bpm_control_port);
691 _impl->designated_input (LV2_CORE__freeWheeling, params, (void**)&_freewheel_control_port);
693 for (uint32_t i = 0; i < num_ports; ++i) {
694 const LilvPort* port = lilv_plugin_get_port_by_index(plugin, i);
695 const LilvNode* sym = lilv_port_get_symbol(plugin, port);
697 // Store index in map so we can look up index by symbol
698 _port_indices.insert(std::make_pair(lilv_node_as_string(sym), i));
700 // Get range and default value if applicable
701 if (parameter_is_control(i)) {
703 lilv_port_get_range(plugin, port, &def, NULL, NULL);
704 _defaults[i] = def ? lilv_node_as_float(def) : 0.0f;
705 if (lilv_port_has_property (plugin, port, _world.lv2_sampleRate)) {
706 _defaults[i] *= _session.frame_rate ();
710 lilv_instance_connect_port(_impl->instance, i, &_control_data[i]);
712 if (latent && i == latency_index) {
714 lilv_port_get_range(_impl->plugin, port, NULL, NULL, &max);
715 _max_latency = max ? lilv_node_as_float(max) : .02 * _sample_rate;
716 _latency_control_port = &_control_data[i];
717 *_latency_control_port = 0;
720 if (parameter_is_input(i)) {
721 _shadow_data[i] = default_value(i);
723 *params[i] = (void*)&_shadow_data[i];
733 LilvUIs* uis = lilv_plugin_get_uis(plugin);
734 if (lilv_uis_size(uis) > 0) {
736 // Look for embeddable UI
737 LILV_FOREACH(uis, u, uis) {
738 const LilvUI* this_ui = lilv_uis_get(uis, u);
739 const LilvNode* this_ui_type = NULL;
740 if (lilv_ui_is_supported(this_ui,
744 // TODO: Multiple UI support
746 _impl->ui_type = this_ui_type;
751 // Look for Gtk native UI
752 LILV_FOREACH(uis, i, uis) {
753 const LilvUI* ui = lilv_uis_get(uis, i);
754 if (lilv_ui_is_a(ui, _world.ui_GtkUI)) {
756 _impl->ui_type = _world.ui_GtkUI;
762 // If Gtk UI is not available, try to find external UI
764 LILV_FOREACH(uis, i, uis) {
765 const LilvUI* ui = lilv_uis_get(uis, i);
766 if (lilv_ui_is_a(ui, _world.ui_externalkx)) {
768 _impl->ui_type = _world.ui_external;
771 if (lilv_ui_is_a(ui, _world.ui_external)) {
773 _impl->ui_type = _world.ui_external;
779 load_supported_properties(_property_descriptors);
780 allocate_atom_event_buffers();
781 latency_compute_run();
785 LV2Plugin::set_block_size (pframes_t nframes)
787 #ifdef HAVE_LV2_1_2_0
788 if (_impl->opts_iface) {
789 LV2_URID atom_Int = _uri_map.uri_to_id(LV2_ATOM__Int);
790 _impl->block_length = nframes;
791 LV2_Options_Option block_size_option = {
792 LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id ("http://lv2plug.in/ns/ext/buf-size#nominalBlockLength"),
793 sizeof(int32_t), atom_Int, (void*)&_impl->block_length
795 _impl->opts_iface->set (_impl->instance->lv2_handle, &block_size_option);
802 LV2Plugin::requires_fixed_sized_buffers () const
804 /* This controls if Ardour will split the plugin's run()
805 * on automation events in order to pass sample-accurate automation
806 * via standard control-ports.
808 * When returning true Ardour will *not* sub-divide the process-cycle.
809 * Automation events that happen between cycle-start and cycle-end will be
810 * ignored (ctrl values are interpolated to cycle-start).
811 * NB. Atom Sequences are still sample accurate.
813 * Note: This does not guarantee a fixed block-size.
814 * e.g The process cycle may be split when looping, also
815 * the period-size may change any time: see set_block_size()
817 if (get_info()->n_inputs.n_midi() > 0) {
818 /* we don't yet implement midi buffer offsets (for split cycles).
819 * Also connect_and_run() also uses _session.transport_frame() directly
820 * (for BBT) which is not offset for plugin cycle split.
824 return _no_sample_accurate_ctrl;
827 LV2Plugin::~LV2Plugin ()
829 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 destroy\n", name()));
834 lilv_instance_free(_impl->instance);
835 lilv_state_free(_impl->state);
836 lilv_node_free(_impl->name);
837 lilv_node_free(_impl->author);
838 #ifdef HAVE_LV2_1_2_0
839 free(_impl->options);
842 free(_impl->queue_draw);
846 free(_log_feature.data);
847 free(_make_path_feature.data);
848 free(_work_schedule_feature.data);
853 delete _state_worker;
855 if (_atom_ev_buffers) {
856 LV2_Evbuf** b = _atom_ev_buffers;
861 free(_atom_ev_buffers);
864 delete [] _control_data;
865 delete [] _shadow_data;
867 delete [] _ev_buffers;
872 LV2Plugin::is_external_ui() const
877 return lilv_ui_is_a(_impl->ui, _world.ui_external) || lilv_ui_is_a(_impl->ui, _world.ui_externalkx);
881 LV2Plugin::is_external_kx() const
886 return lilv_ui_is_a(_impl->ui, _world.ui_externalkx);
890 LV2Plugin::ui_is_resizable () const
892 const LilvNode* s = lilv_ui_get_uri(_impl->ui);
893 LilvNode* p = lilv_new_uri(_world.world, LV2_CORE__optionalFeature);
894 LilvNode* fs = lilv_new_uri(_world.world, LV2_UI__fixedSize);
895 LilvNode* nrs = lilv_new_uri(_world.world, LV2_UI__noUserResize);
897 LilvNodes* fs_matches = lilv_world_find_nodes(_world.world, s, p, fs);
898 LilvNodes* nrs_matches = lilv_world_find_nodes(_world.world, s, p, nrs);
900 lilv_nodes_free(nrs_matches);
901 lilv_nodes_free(fs_matches);
906 return !fs_matches && !nrs_matches;
911 LV2Plugin::has_inline_display () {
912 return _display_interface ? true : false;
915 Plugin::Display_Image_Surface*
916 LV2Plugin::render_inline_display (uint32_t w, uint32_t h) {
917 if (_display_interface) {
918 /* Plugin::Display_Image_Surface is identical to
919 * LV2_Inline_Display_Image_Surface */
920 return (Plugin::Display_Image_Surface*) _display_interface->render ((void*)_impl->instance->lv2_handle, w, h);
927 LV2Plugin::unique_id() const
929 return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
933 LV2Plugin::uri() const
935 return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
939 LV2Plugin::label() const
941 return lilv_node_as_string(_impl->name);
945 LV2Plugin::name() const
947 return lilv_node_as_string(_impl->name);
951 LV2Plugin::maker() const
953 return _impl->author ? lilv_node_as_string (_impl->author) : "Unknown";
957 LV2Plugin::num_ports() const
959 return lilv_plugin_get_num_ports(_impl->plugin);
963 LV2Plugin::parameter_count() const
965 return lilv_plugin_get_num_ports(_impl->plugin);
969 LV2Plugin::default_value(uint32_t port)
971 return _defaults[port];
975 LV2Plugin::port_symbol(uint32_t index) const
977 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, index);
979 error << name() << ": Invalid port index " << index << endmsg;
982 const LilvNode* sym = lilv_port_get_symbol(_impl->plugin, port);
983 return lilv_node_as_string(sym);
987 LV2Plugin::port_index (const char* symbol) const
989 const map<string, uint32_t>::const_iterator i = _port_indices.find(symbol);
990 if (i != _port_indices.end()) {
993 warning << string_compose(_("LV2: Unknown port %1"), symbol) << endmsg;
999 LV2Plugin::set_parameter(uint32_t which, float val)
1001 DEBUG_TRACE(DEBUG::LV2, string_compose(
1002 "%1 set parameter %2 to %3\n", name(), which, val));
1004 if (which < lilv_plugin_get_num_ports(_impl->plugin)) {
1005 if (get_parameter (which) == val) {
1009 _shadow_data[which] = val;
1011 warning << string_compose(
1012 _("Illegal parameter number used with plugin \"%1\". "
1013 "This is a bug in either %2 or the LV2 plugin <%3>"),
1014 name(), PROGRAM_NAME, unique_id()) << endmsg;
1017 Plugin::set_parameter(which, val);
1021 LV2Plugin::get_parameter(uint32_t which) const
1023 if (parameter_is_input(which)) {
1024 return (float)_shadow_data[which];
1026 return (float)_control_data[which];
1032 LV2Plugin::get_docs() const
1034 LilvNodes* comments = lilv_plugin_get_value(_impl->plugin, _world.rdfs_comment);
1036 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
1037 lilv_nodes_free(comments);
1045 LV2Plugin::get_parameter_docs(uint32_t which) const
1047 LilvNodes* comments = lilv_port_get_value(
1049 lilv_plugin_get_port_by_index(_impl->plugin, which),
1050 _world.rdfs_comment);
1053 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
1054 lilv_nodes_free(comments);
1062 LV2Plugin::get_layout (uint32_t which, UILayoutHint& h) const
1064 /// TODO lookup port-properties
1065 if (unique_id () != "urn:ardour:a-eq") {
1070 case 0: h.x0 = 0; h.x1 = 1; h.y0 = 2; h.y1 = 3; break; // Frequency L
1071 case 1: h.x0 = 0; h.x1 = 1; h.y0 = 0; h.y1 = 1; break; // Gain L
1072 case 17: h.x0 = 0; h.x1 = 1; h.y0 = 5; h.y1 = 6; break; // enable L
1074 case 2: h.x0 = 1; h.x1 = 3; h.y0 = 2; h.y1 = 3; break; // Frequency 1
1075 case 3: h.x0 = 1; h.x1 = 3; h.y0 = 0; h.y1 = 1; break; // Gain 1
1076 case 4: h.x0 = 2; h.x1 = 4; h.y0 = 1; h.y1 = 2; break; // Bandwidth 1
1077 case 18: h.x0 = 1; h.x1 = 4; h.y0 = 5; h.y1 = 6; break; // enable 1
1079 case 5: h.x0 = 4; h.x1 = 6; h.y0 = 2; h.y1 = 3; break; // Frequency 2
1080 case 6: h.x0 = 4; h.x1 = 6; h.y0 = 0; h.y1 = 1; break; // Gain 2
1081 case 7: h.x0 = 5; h.x1 = 7; h.y0 = 1; h.y1 = 2; break; // Bandwidth 2
1082 case 19: h.x0 = 4; h.x1 = 7; h.y0 = 5; h.y1 = 6; break; // enable 2
1084 case 8: h.x0 = 7; h.x1 = 9; h.y0 = 2; h.y1 = 3; break; // Frequency 3
1085 case 9: h.x0 = 7; h.x1 = 9; h.y0 = 0; h.y1 = 1; break; // Gain 3
1086 case 10: h.x0 = 8; h.x1 = 10; h.y0 = 1; h.y1 = 2; break; // Bandwidth 3
1087 case 20: h.x0 = 7; h.x1 = 10; h.y0 = 5; h.y1 = 6; break; // enable 3
1089 case 11: h.x0 = 10; h.x1 = 12; h.y0 = 2; h.y1 = 3; break; // Frequency 4
1090 case 12: h.x0 = 10; h.x1 = 12; h.y0 = 0; h.y1 = 1; break; // Gain 4
1091 case 13: h.x0 = 11; h.x1 = 13; h.y0 = 1; h.y1 = 2; break; // Bandwidth 4
1092 case 21: h.x0 = 10; h.x1 = 13; h.y0 = 5; h.y1 = 6; break; // enable 4
1094 case 14: h.x0 = 13; h.x1 = 14; h.y0 = 2; h.y1 = 3; break; // Frequency H
1095 case 15: h.x0 = 13; h.x1 = 14; h.y0 = 0; h.y1 = 1; break; // Gain H
1096 case 22: h.x0 = 13; h.x1 = 14; h.y0 = 5; h.y1 = 6; break; // enable H
1098 case 16: h.x0 = 14; h.x1 = 15; h.y0 = 1; h.y1 = 3; break; // Master Gain
1099 case 23: h.x0 = 14; h.x1 = 15; h.y0 = 5; h.y1 = 6; break; // Master Enable
1107 LV2Plugin::nth_parameter(uint32_t n, bool& ok) const
1110 for (uint32_t c = 0, x = 0; x < lilv_plugin_get_num_ports(_impl->plugin); ++x) {
1111 if (parameter_is_control(x)) {
1123 LV2Plugin::extension_data(const char* uri) const
1125 return lilv_instance_get_extension_data(_impl->instance, uri);
1129 LV2Plugin::c_plugin()
1131 return _impl->plugin;
1137 return (const void*)_impl->ui;
1141 LV2Plugin::c_ui_type()
1143 return (const void*)_impl->ui_type;
1146 /** Directory for all plugin state. */
1148 LV2Plugin::plugin_dir() const
1150 if (!_plugin_state_dir.empty ()){
1151 return Glib::build_filename(_plugin_state_dir, _insert_id.to_s());
1153 return Glib::build_filename(_session.plugins_dir(), _insert_id.to_s());
1157 /** Directory for files created by the plugin (except during save). */
1159 LV2Plugin::scratch_dir() const
1161 return Glib::build_filename(plugin_dir(), "scratch");
1164 /** Directory for snapshots of files in the scratch directory. */
1166 LV2Plugin::file_dir() const
1168 return Glib::build_filename(plugin_dir(), "files");
1171 /** Directory to save state snapshot version @c num into. */
1173 LV2Plugin::state_dir(unsigned num) const
1175 return Glib::build_filename(plugin_dir(), string_compose("state%1", num));
1178 /** Implementation of state:makePath for files created at instantiation time.
1179 * Note this is not used for files created at save time (Lilv deals with that).
1182 LV2Plugin::lv2_state_make_path(LV2_State_Make_Path_Handle handle,
1185 LV2Plugin* me = (LV2Plugin*)handle;
1186 if (me->_insert_id == PBD::ID("0")) {
1187 warning << string_compose(
1188 "File path \"%1\" requested but LV2 %2 has no insert ID",
1189 path, me->name()) << endmsg;
1190 return g_strdup(path);
1193 const std::string abs_path = Glib::build_filename(me->scratch_dir(), path);
1194 const std::string dirname = Glib::path_get_dirname(abs_path);
1195 g_mkdir_with_parents(dirname.c_str(), 0744);
1197 DEBUG_TRACE(DEBUG::LV2, string_compose("new file path %1 => %2\n",
1200 return g_strndup(abs_path.c_str(), abs_path.length());
1204 LV2Plugin::add_state(XMLNode* root) const
1206 assert(_insert_id != PBD::ID("0"));
1212 for (uint32_t i = 0; i < parameter_count(); ++i) {
1213 if (parameter_is_input(i) && parameter_is_control(i)) {
1214 child = new XMLNode("Port");
1215 child->add_property("symbol", port_symbol(i));
1216 snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
1217 child->add_property("value", string(buf));
1218 root->add_child_nocopy(*child);
1222 if (!_plugin_state_dir.empty()) {
1223 root->add_property("template-dir", _plugin_state_dir);
1226 if (_has_state_interface) {
1227 // Provisionally increment state version and create directory
1228 const std::string new_dir = state_dir(++_state_version);
1229 g_mkdir_with_parents(new_dir.c_str(), 0744);
1231 LilvState* state = lilv_state_new_from_instance(
1234 _uri_map.urid_map(),
1235 scratch_dir().c_str(),
1237 _session.externals_dir().c_str(),
1240 const_cast<LV2Plugin*>(this),
1244 if (!_plugin_state_dir.empty()
1246 || !lilv_state_equals(state, _impl->state)) {
1247 lilv_state_save(_world.world,
1248 _uri_map.urid_map(),
1249 _uri_map.urid_unmap(),
1255 if (_plugin_state_dir.empty()) {
1256 // normal session save
1257 lilv_state_free(_impl->state);
1258 _impl->state = state;
1260 // template save (dedicated state-dir)
1261 lilv_state_free(state);
1264 // State is identical, decrement version and nuke directory
1265 lilv_state_free(state);
1266 PBD::remove_directory(new_dir);
1270 root->add_property("state-dir", string_compose("state%1", _state_version));
1274 // TODO: Once we can rely on lilv 0.16.0, lilv_world_get can replace this
1276 get_value(LilvWorld* world, const LilvNode* subject, const LilvNode* predicate)
1278 LilvNodes* vs = lilv_world_find_nodes(world, subject, predicate, NULL);
1280 LilvNode* node = lilv_node_duplicate(lilv_nodes_get_first(vs));
1281 lilv_nodes_free(vs);
1288 LV2Plugin::find_presets()
1290 LilvNode* lv2_appliesTo = lilv_new_uri(_world.world, LV2_CORE__appliesTo);
1291 LilvNode* pset_Preset = lilv_new_uri(_world.world, LV2_PRESETS__Preset);
1292 LilvNode* rdfs_label = lilv_new_uri(_world.world, LILV_NS_RDFS "label");
1294 LilvNodes* presets = lilv_plugin_get_related(_impl->plugin, pset_Preset);
1295 LILV_FOREACH(nodes, i, presets) {
1296 const LilvNode* preset = lilv_nodes_get(presets, i);
1297 lilv_world_load_resource(_world.world, preset);
1298 LilvNode* name = get_value(_world.world, preset, rdfs_label);
1299 bool userpreset = true; // TODO
1301 _presets.insert(std::make_pair(lilv_node_as_string(preset),
1302 Plugin::PresetRecord(
1303 lilv_node_as_string(preset),
1304 lilv_node_as_string(name),
1306 lilv_node_free(name);
1308 warning << string_compose(
1309 _("Plugin \"%1\" preset \"%2\" is missing a label\n"),
1310 lilv_node_as_string(lilv_plugin_get_uri(_impl->plugin)),
1311 lilv_node_as_string(preset)) << endmsg;
1314 lilv_nodes_free(presets);
1316 lilv_node_free(rdfs_label);
1317 lilv_node_free(pset_Preset);
1318 lilv_node_free(lv2_appliesTo);
1322 set_port_value(const char* port_symbol,
1328 LV2Plugin* self = (LV2Plugin*)user_data;
1329 if (type != 0 && type != URIMap::instance().urids.atom_Float) {
1330 return; // TODO: Support non-float ports
1333 const uint32_t port_index = self->port_index(port_symbol);
1334 if (port_index != (uint32_t)-1) {
1335 self->set_parameter(port_index, *(const float*)value);
1340 LV2Plugin::load_preset(PresetRecord r)
1342 LilvWorld* world = _world.world;
1343 LilvNode* pset = lilv_new_uri(world, r.uri.c_str());
1344 LilvState* state = lilv_state_new_from_world(world, _uri_map.urid_map(), pset);
1346 const LV2_Feature* state_features[2] = { NULL, NULL };
1347 LV2_Worker_Schedule schedule = { _state_worker, work_schedule };
1348 const LV2_Feature state_sched_feature = { LV2_WORKER__schedule, &schedule };
1349 if (_state_worker) {
1350 state_features[0] = &state_sched_feature;
1354 lilv_state_restore(state, _impl->instance, set_port_value, this, 0, state_features);
1355 lilv_state_free(state);
1356 Plugin::load_preset(r);
1359 lilv_node_free(pset);
1364 ARDOUR::lv2plugin_get_port_value(const char* port_symbol,
1369 LV2Plugin *plugin = (LV2Plugin *) user_data;
1371 uint32_t index = plugin->port_index(port_symbol);
1372 if (index != (uint32_t) -1) {
1373 if (plugin->parameter_is_input(index) && plugin->parameter_is_control(index)) {
1375 *size = sizeof(float);
1376 *type = plugin->_uri_map.uri_to_id(LV2_ATOM__Float);
1377 value = &plugin->_shadow_data[index];
1389 LV2Plugin::do_save_preset(string name)
1391 LilvNode* plug_name = lilv_plugin_get_name(_impl->plugin);
1392 const string prefix = legalize_for_uri(lilv_node_as_string(plug_name));
1393 const string base_name = legalize_for_uri(name);
1394 const string file_name = base_name + ".ttl";
1395 const string bundle = Glib::build_filename(
1396 Glib::get_home_dir(),
1397 Glib::build_filename(".lv2", prefix + "_" + base_name + ".lv2"));
1399 #ifdef HAVE_LILV_0_21_3
1400 /* delete reference to old preset (if any) */
1401 const PresetRecord* r = preset_by_label(name);
1403 LilvNode* pset = lilv_new_uri (_world.world, r->uri.c_str());
1405 lilv_world_unload_resource (_world.world, pset);
1406 lilv_node_free(pset);
1411 LilvState* state = lilv_state_new_from_instance(
1414 _uri_map.urid_map(),
1415 scratch_dir().c_str(), // file_dir
1416 bundle.c_str(), // copy_dir
1417 bundle.c_str(), // link_dir
1418 bundle.c_str(), // save_dir
1419 lv2plugin_get_port_value, // get_value
1420 (void*)this, // user_data
1421 LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE, // flags
1422 _features // features
1425 lilv_state_set_label(state, name.c_str());
1427 _world.world, // world
1428 _uri_map.urid_map(), // map
1429 _uri_map.urid_unmap(), // unmap
1431 NULL, // uri (NULL = use file URI)
1432 bundle.c_str(), // dir
1433 file_name.c_str() // filename
1436 lilv_state_free(state);
1438 std::string uri = Glib::filename_to_uri(Glib::build_filename(bundle, file_name));
1439 LilvNode *node_bundle = lilv_new_uri(_world.world, Glib::filename_to_uri(Glib::build_filename(bundle, "/")).c_str());
1440 LilvNode *node_preset = lilv_new_uri(_world.world, uri.c_str());
1441 #ifdef HAVE_LILV_0_21_3
1442 lilv_world_unload_resource(_world.world, node_preset);
1443 lilv_world_unload_bundle(_world.world, node_bundle);
1445 lilv_world_load_bundle(_world.world, node_bundle);
1446 lilv_world_load_resource(_world.world, node_preset);
1447 lilv_node_free(node_bundle);
1448 lilv_node_free(node_preset);
1449 lilv_node_free(plug_name);
1454 LV2Plugin::do_remove_preset(string name)
1456 #ifdef HAVE_LILV_0_21_3
1457 /* Look up preset record by label (FIXME: ick, label as ID) */
1458 const PresetRecord* r = preset_by_label(name);
1463 /* Load a LilvState for the preset. */
1464 LilvWorld* world = _world.world;
1465 LilvNode* pset = lilv_new_uri(world, r->uri.c_str());
1466 LilvState* state = lilv_state_new_from_world(world, _uri_map.urid_map(), pset);
1468 lilv_node_free(pset);
1472 /* Unload preset from world. */
1473 lilv_world_unload_resource(world, pset);
1475 /* Delete it from the file system. This will remove the preset file and the entry
1476 from the manifest. If this results in an empty manifest (i.e. the
1477 preset is the only thing in the bundle), then the bundle is removed. */
1478 lilv_state_delete(world, state);
1480 lilv_state_free(state);
1481 lilv_node_free(pset);
1483 /* Without lilv_state_delete(), we could delete the preset file, but this
1484 would leave a broken bundle/manifest around, so the preset would still
1485 be visible, but broken. Naively deleting a bundle is too dangerous, so
1486 we simply do not support preset deletion with older Lilv */
1490 LV2Plugin::has_editor() const
1492 return _impl->ui != NULL;
1496 LV2Plugin::has_message_output() const
1498 for (uint32_t i = 0; i < num_ports(); ++i) {
1499 if ((_port_flags[i] & PORT_SEQUENCE) &&
1500 (_port_flags[i] & PORT_OUTPUT)) {
1508 LV2Plugin::write_to(RingBuffer<uint8_t>* dest,
1512 const uint8_t* body)
1514 const uint32_t buf_size = sizeof(UIMessage) + size;
1515 vector<uint8_t> buf(buf_size);
1517 UIMessage* msg = (UIMessage*)&buf[0];
1519 msg->protocol = protocol;
1521 memcpy(msg + 1, body, size);
1523 return (dest->write(&buf[0], buf_size) == buf_size);
1527 LV2Plugin::write_from_ui(uint32_t index,
1530 const uint8_t* body)
1533 size_t rbs = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
1534 /* buffer data communication from plugin UI to plugin instance.
1535 * this buffer needs to potentially hold
1536 * (port's minimumSize) * (audio-periods) / (UI-periods)
1539 * e.g 48kSPS / 128fpp -> audio-periods = 375 Hz
1540 * ui-periods = 25 Hz (SuperRapidScreenUpdate)
1541 * default minimumSize = 32K (see LV2Plugin::allocate_atom_event_buffers()
1543 * it is NOT safe to overflow (msg.size will be misinterpreted)
1545 uint32_t bufsiz = 32768;
1546 if (_atom_ev_buffers && _atom_ev_buffers[0]) {
1547 bufsiz = lv2_evbuf_get_capacity(_atom_ev_buffers[0]);
1549 rbs = max((size_t) bufsiz * 8, rbs);
1550 _from_ui = new RingBuffer<uint8_t>(rbs);
1553 if (!write_to(_from_ui, index, protocol, size, body)) {
1554 error << "Error writing from UI to plugin" << endmsg;
1561 LV2Plugin::write_to_ui(uint32_t index,
1564 const uint8_t* body)
1566 if (!write_to(_to_ui, index, protocol, size, body)) {
1567 error << "Error writing from plugin to UI" << endmsg;
1574 forge_variant(LV2_Atom_Forge* forge, const Variant& value)
1576 switch (value.type()) {
1577 case Variant::NOTHING:
1579 case Variant::BEATS:
1580 // No atom type for this, just forge a double
1581 lv2_atom_forge_double(forge, value.get_beats().to_double());
1584 lv2_atom_forge_bool(forge, value.get_bool());
1586 case Variant::DOUBLE:
1587 lv2_atom_forge_double(forge, value.get_double());
1589 case Variant::FLOAT:
1590 lv2_atom_forge_float(forge, value.get_float());
1593 lv2_atom_forge_int(forge, value.get_int());
1596 lv2_atom_forge_long(forge, value.get_long());
1599 lv2_atom_forge_path(
1600 forge, value.get_path().c_str(), value.get_path().size());
1602 case Variant::STRING:
1603 lv2_atom_forge_string(
1604 forge, value.get_string().c_str(), value.get_string().size());
1608 forge, value.get_uri().c_str(), value.get_uri().size());
1613 /** Get a variant type from a URI, return false iff no match found. */
1615 uri_to_variant_type(const std::string& uri, Variant::Type& type)
1617 if (uri == LV2_ATOM__Bool) {
1618 type = Variant::BOOL;
1619 } else if (uri == LV2_ATOM__Double) {
1620 type = Variant::DOUBLE;
1621 } else if (uri == LV2_ATOM__Float) {
1622 type = Variant::FLOAT;
1623 } else if (uri == LV2_ATOM__Int) {
1624 type = Variant::INT;
1625 } else if (uri == LV2_ATOM__Long) {
1626 type = Variant::LONG;
1627 } else if (uri == LV2_ATOM__Path) {
1628 type = Variant::PATH;
1629 } else if (uri == LV2_ATOM__String) {
1630 type = Variant::STRING;
1631 } else if (uri == LV2_ATOM__URI) {
1632 type = Variant::URI;
1640 LV2Plugin::set_property(uint32_t key, const Variant& value)
1642 if (_patch_port_in_index == (uint32_t)-1) {
1643 error << "LV2: set_property called with unset patch_port_in_index" << endmsg;
1645 } else if (value.type() == Variant::NOTHING) {
1646 error << "LV2: set_property called with void value" << endmsg;
1650 // Set up forge to write to temporary buffer on the stack
1651 LV2_Atom_Forge* forge = &_impl->ui_forge;
1652 LV2_Atom_Forge_Frame frame;
1653 uint8_t buf[PATH_MAX]; // Ought to be enough for anyone...
1655 lv2_atom_forge_set_buffer(forge, buf, sizeof(buf));
1657 // Serialize patch:Set message to set property
1658 #ifdef HAVE_LV2_1_10_0
1659 lv2_atom_forge_object(forge, &frame, 1, _uri_map.urids.patch_Set);
1660 lv2_atom_forge_key(forge, _uri_map.urids.patch_property);
1661 lv2_atom_forge_urid(forge, key);
1662 lv2_atom_forge_key(forge, _uri_map.urids.patch_value);
1664 lv2_atom_forge_blank(forge, &frame, 1, _uri_map.urids.patch_Set);
1665 lv2_atom_forge_property_head(forge, _uri_map.urids.patch_property, 0);
1666 lv2_atom_forge_urid(forge, key);
1667 lv2_atom_forge_property_head(forge, _uri_map.urids.patch_value, 0);
1670 forge_variant(forge, value);
1672 // Write message to UI=>Plugin ring
1673 const LV2_Atom* const atom = (const LV2_Atom*)buf;
1674 write_from_ui(_patch_port_in_index,
1675 _uri_map.urids.atom_eventTransfer,
1676 lv2_atom_total_size(atom),
1677 (const uint8_t*)atom);
1680 const ParameterDescriptor&
1681 LV2Plugin::get_property_descriptor(uint32_t id) const
1683 PropertyDescriptors::const_iterator p = _property_descriptors.find(id);
1684 if (p != _property_descriptors.end()) {
1687 return Plugin::get_property_descriptor(id);
1691 load_parameter_descriptor_units(LilvWorld* lworld, ParameterDescriptor& desc, const LilvNodes* units)
1693 if (lilv_nodes_contains(units, _world.units_midiNote)) {
1694 desc.unit = ParameterDescriptor::MIDI_NOTE;
1695 } else if (lilv_nodes_contains(units, _world.units_db)) {
1696 desc.unit = ParameterDescriptor::DB;
1697 } else if (lilv_nodes_contains(units, _world.units_hz)) {
1698 desc.unit = ParameterDescriptor::HZ;
1700 if (lilv_nodes_size(units) > 0) {
1701 const LilvNode* unit = lilv_nodes_get_first(units);
1702 LilvNode* render = get_value(lworld, unit, _world.units_render);
1704 desc.print_fmt = lilv_node_as_string(render);
1705 replace_all (desc.print_fmt, "%f", "%.2f");
1706 lilv_node_free(render);
1712 load_parameter_descriptor(LV2World& world,
1713 ParameterDescriptor& desc,
1714 Variant::Type datatype,
1715 const LilvNode* subject)
1717 LilvWorld* lworld = _world.world;
1718 LilvNode* label = get_value(lworld, subject, _world.rdfs_label);
1719 LilvNode* def = get_value(lworld, subject, _world.lv2_default);
1720 LilvNode* minimum = get_value(lworld, subject, _world.lv2_minimum);
1721 LilvNode* maximum = get_value(lworld, subject, _world.lv2_maximum);
1722 LilvNodes* units = lilv_world_find_nodes(lworld, subject, _world.units_unit, NULL);
1724 desc.label = lilv_node_as_string(label);
1726 if (def && lilv_node_is_float(def)) {
1727 desc.normal = lilv_node_as_float(def);
1729 if (minimum && lilv_node_is_float(minimum)) {
1730 desc.lower = lilv_node_as_float(minimum);
1732 if (maximum && lilv_node_is_float(maximum)) {
1733 desc.upper = lilv_node_as_float(maximum);
1735 load_parameter_descriptor_units(lworld, desc, units);
1736 desc.datatype = datatype;
1737 desc.toggled |= datatype == Variant::BOOL;
1738 desc.integer_step |= datatype == Variant::INT || datatype == Variant::LONG;
1739 desc.update_steps();
1741 lilv_nodes_free(units);
1742 lilv_node_free(label);
1743 lilv_node_free(def);
1744 lilv_node_free(minimum);
1745 lilv_node_free(maximum);
1749 LV2Plugin::load_supported_properties(PropertyDescriptors& descs)
1751 LilvWorld* lworld = _world.world;
1752 const LilvNode* subject = lilv_plugin_get_uri(_impl->plugin);
1753 LilvNodes* properties = lilv_world_find_nodes(
1754 lworld, subject, _world.patch_writable, NULL);
1755 LILV_FOREACH(nodes, p, properties) {
1756 // Get label and range
1757 const LilvNode* prop = lilv_nodes_get(properties, p);
1758 LilvNode* range = get_value(lworld, prop, _world.rdfs_range);
1760 warning << string_compose(_("LV2: property <%1> has no range datatype, ignoring"),
1761 lilv_node_as_uri(prop)) << endmsg;
1765 // Convert range to variant type (TODO: support for multiple range types)
1766 Variant::Type datatype;
1767 if (!uri_to_variant_type(lilv_node_as_uri(range), datatype)) {
1768 error << string_compose(_("LV2: property <%1> has unsupported datatype <%1>"),
1769 lilv_node_as_uri(prop), lilv_node_as_uri(range)) << endmsg;
1773 // Add description to result
1774 ParameterDescriptor desc;
1775 desc.key = _uri_map.uri_to_id(lilv_node_as_uri(prop));
1776 desc.datatype = datatype;
1777 load_parameter_descriptor(_world, desc, datatype, prop);
1778 descs.insert(std::make_pair(desc.key, desc));
1780 lilv_node_free(range);
1782 lilv_nodes_free(properties);
1786 LV2Plugin::announce_property_values()
1788 if (_patch_port_in_index == (uint32_t)-1) {
1792 // Set up forge to write to temporary buffer on the stack
1793 LV2_Atom_Forge* forge = &_impl->ui_forge;
1794 LV2_Atom_Forge_Frame frame;
1795 uint8_t buf[PATH_MAX]; // Ought to be enough for anyone...
1797 lv2_atom_forge_set_buffer(forge, buf, sizeof(buf));
1799 // Serialize patch:Get message with no subject (implicitly plugin instance)
1800 #ifdef HAVE_LV2_1_10_0
1801 lv2_atom_forge_object(forge, &frame, 1, _uri_map.urids.patch_Get);
1803 lv2_atom_forge_blank(forge, &frame, 1, _uri_map.urids.patch_Get);
1806 // Write message to UI=>Plugin ring
1807 const LV2_Atom* const atom = (const LV2_Atom*)buf;
1808 write_from_ui(_patch_port_in_index,
1809 _uri_map.urids.atom_eventTransfer,
1810 lv2_atom_total_size(atom),
1811 (const uint8_t*)atom);
1815 LV2Plugin::enable_ui_emission()
1818 /* see note in LV2Plugin::write_from_ui() */
1819 uint32_t bufsiz = 32768;
1820 if (_atom_ev_buffers && _atom_ev_buffers[0]) {
1821 bufsiz = lv2_evbuf_get_capacity(_atom_ev_buffers[0]);
1823 size_t rbs = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
1824 rbs = max((size_t) bufsiz * 8, rbs);
1825 _to_ui = new RingBuffer<uint8_t>(rbs);
1830 LV2Plugin::emit_to_ui(void* controller, UIMessageSink sink)
1836 uint32_t read_space = _to_ui->read_space();
1837 while (read_space > sizeof(UIMessage)) {
1839 if (_to_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1840 error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1843 vector<uint8_t> body(msg.size);
1844 if (_to_ui->read(&body[0], msg.size) != msg.size) {
1845 error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1849 sink(controller, msg.index, msg.size, msg.protocol, &body[0]);
1851 read_space -= sizeof(msg) + msg.size;
1856 LV2Plugin::work(Worker& worker, uint32_t size, const void* data)
1858 Glib::Threads::Mutex::Lock lm(_work_mutex);
1859 return _impl->work_iface->work(
1860 _impl->instance->lv2_handle, work_respond, &worker, size, data);
1864 LV2Plugin::work_response(uint32_t size, const void* data)
1866 return _impl->work_iface->work_response(
1867 _impl->instance->lv2_handle, size, data);
1871 LV2Plugin::set_insert_id(PBD::ID id)
1873 if (_insert_id == "0") {
1875 } else if (_insert_id != id) {
1876 lilv_state_free(_impl->state);
1877 _impl->state = NULL;
1883 LV2Plugin::set_state_dir (const std::string& d)
1885 _plugin_state_dir = d;
1889 LV2Plugin::set_state(const XMLNode& node, int version)
1892 XMLProperty const * prop;
1893 XMLNodeConstIterator iter;
1900 if (node.name() != state_node_name()) {
1901 error << _("Bad node sent to LV2Plugin::set_state") << endmsg;
1905 #ifndef NO_PLUGIN_STATE
1907 if (version < 3000) {
1908 nodes = node.children("port");
1910 nodes = node.children("Port");
1913 for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
1917 if ((prop = child->property("symbol")) != 0) {
1918 sym = prop->value().c_str();
1920 warning << _("LV2: port has no symbol, ignored") << endmsg;
1924 map<string, uint32_t>::iterator i = _port_indices.find(sym);
1926 if (i != _port_indices.end()) {
1927 port_id = i->second;
1929 warning << _("LV2: port has unknown index, ignored") << endmsg;
1933 if ((prop = child->property("value")) != 0) {
1934 value = prop->value().c_str();
1936 warning << _("LV2: port has no value, ignored") << endmsg;
1940 set_parameter(port_id, atof(value));
1943 if ((prop = node.property("template-dir")) != 0) {
1944 set_state_dir (prop->value ());
1948 if ((prop = node.property("state-dir")) != 0) {
1949 if (sscanf(prop->value().c_str(), "state%u", &_state_version) != 1) {
1950 error << string_compose(
1951 "LV2: failed to parse state version from \"%1\"",
1952 prop->value()) << endmsg;
1955 std::string state_file = Glib::build_filename(
1957 Glib::build_filename(prop->value(), "state.ttl"));
1959 LilvState* state = lilv_state_new_from_file(
1960 _world.world, _uri_map.urid_map(), NULL, state_file.c_str());
1962 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
1963 lilv_state_free(_impl->state);
1964 _impl->state = state;
1967 if (!_plugin_state_dir.empty ()) {
1968 // force save with session, next time (increment counter)
1969 lilv_state_free (_impl->state);
1970 _impl->state = NULL;
1974 latency_compute_run();
1977 return Plugin::set_state(node, version);
1981 LV2Plugin::get_parameter_descriptor(uint32_t which, ParameterDescriptor& desc) const
1983 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, which);
1985 error << string_compose("LV2: get descriptor of non-existent port %1", which)
1990 LilvNodes* portunits;
1991 LilvNode *def, *min, *max;
1992 lilv_port_get_range(_impl->plugin, port, &def, &min, &max);
1993 portunits = lilv_port_get_value(_impl->plugin, port, _world.units_unit);
1995 LilvNode* steps = lilv_port_get(_impl->plugin, port, _world.ext_rangeSteps);
1997 // TODO: Once we can rely on lilv 0.18.0 being present,
1998 // load_parameter_descriptor() can be used for ports as well
1999 desc.integer_step = lilv_port_has_property(_impl->plugin, port, _world.lv2_integer);
2000 desc.toggled = lilv_port_has_property(_impl->plugin, port, _world.lv2_toggled);
2001 desc.logarithmic = lilv_port_has_property(_impl->plugin, port, _world.ext_logarithmic);
2002 desc.sr_dependent = lilv_port_has_property(_impl->plugin, port, _world.lv2_sampleRate);
2003 desc.label = lilv_node_as_string(lilv_port_get_name(_impl->plugin, port));
2004 desc.normal = def ? lilv_node_as_float(def) : 0.0f;
2005 desc.lower = min ? lilv_node_as_float(min) : 0.0f;
2006 desc.upper = max ? lilv_node_as_float(max) : 1.0f;
2007 load_parameter_descriptor_units(_world.world, desc, portunits);
2009 if (desc.sr_dependent) {
2010 desc.lower *= _session.frame_rate ();
2011 desc.upper *= _session.frame_rate ();
2014 desc.min_unbound = false; // TODO: LV2 extension required
2015 desc.max_unbound = false; // TODO: LV2 extension required
2017 desc.enumeration = lilv_port_has_property(_impl->plugin, port, _world.lv2_enumeration);
2018 desc.scale_points = get_scale_points(which);
2020 desc.update_steps();
2023 //override auto-calculated steps in update_steps()
2024 float s = lilv_node_as_float (steps);
2025 const float delta = desc.upper - desc.lower;
2027 desc.step = desc.smallstep = (delta / s);
2028 desc.largestep = std::min ((delta / 5.0f), 10.f * desc.smallstep);
2030 if (desc.logarithmic) {
2031 // TODO marry AutomationControl::internal_to_interface () with
2032 // http://lv2plug.in/ns/ext/port-props/#rangeSteps
2033 desc.smallstep = desc.smallstep / logf(s);
2034 desc.step = desc.step / logf(s);
2035 desc.largestep = desc.largestep / logf(s);
2036 } else if (desc.integer_step) {
2037 desc.smallstep = 1.0;
2038 desc.step = std::max(1.f, rintf (desc.step));
2039 desc.largestep = std::max(1.f, rintf (desc.largestep));
2041 DEBUG_TRACE(DEBUG::LV2, string_compose("parameter %1 small: %2, step: %3 largestep: %4\n",
2042 which, desc.smallstep, desc.step, desc.largestep));
2046 lilv_node_free(def);
2047 lilv_node_free(min);
2048 lilv_node_free(max);
2049 lilv_node_free(steps);
2050 lilv_nodes_free(portunits);
2055 Plugin::IOPortDescription
2056 LV2Plugin::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
2058 PortFlags match = 0;
2060 case DataType::AUDIO:
2063 case DataType::MIDI:
2064 match = PORT_SEQUENCE | PORT_MIDI; // ignore old PORT_EVENT
2067 return Plugin::IOPortDescription ("?");
2071 match |= PORT_INPUT;
2073 match |= PORT_OUTPUT;
2077 uint32_t idx = UINT32_MAX;
2079 uint32_t const num_ports = parameter_count();
2080 for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
2081 PortFlags flags = _port_flags[port_index];
2082 if ((flags & match) == match) {
2089 if (idx == UINT32_MAX) {
2090 return Plugin::IOPortDescription ("?");
2093 LilvNode* name = lilv_port_get_name(_impl->plugin,
2094 lilv_plugin_get_port_by_index(_impl->plugin, idx));
2095 Plugin::IOPortDescription iod (lilv_node_as_string (name));
2096 lilv_node_free(name);
2098 if (lilv_port_has_property(_impl->plugin,
2099 lilv_plugin_get_port_by_index(_impl->plugin, idx), _world.lv2_isSideChain)) {
2100 iod.is_sidechain = true;
2106 LV2Plugin::describe_parameter(Evoral::Parameter which)
2108 if (( which.type() == PluginAutomation) && ( which.id() < parameter_count()) ) {
2110 if (lilv_port_has_property(_impl->plugin,
2111 lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.ext_notOnGUI)) {
2112 return X_("hidden");
2115 if (lilv_port_has_property(_impl->plugin,
2116 lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_freewheeling)) {
2117 return X_("hidden");
2120 if (lilv_port_has_property(_impl->plugin,
2121 lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_reportsLatency)) {
2122 return X_("latency");
2125 LilvNode* name = lilv_port_get_name(_impl->plugin,
2126 lilv_plugin_get_port_by_index(_impl->plugin, which.id()));
2127 string ret(lilv_node_as_string(name));
2128 lilv_node_free(name);
2136 LV2Plugin::max_latency () const
2138 return _max_latency;
2142 LV2Plugin::signal_latency() const
2144 if (_latency_control_port) {
2145 return (framecnt_t)floor(*_latency_control_port);
2151 set<Evoral::Parameter>
2152 LV2Plugin::automatable() const
2154 set<Evoral::Parameter> ret;
2156 for (uint32_t i = 0; i < parameter_count(); ++i) {
2157 if (parameter_is_input(i) && parameter_is_control(i) && !(_port_flags[i] & PORT_NOAUTO)) {
2158 ret.insert(ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
2162 for (PropertyDescriptors::const_iterator p = _property_descriptors.begin();
2163 p != _property_descriptors.end();
2165 ret.insert(ret.end(), Evoral::Parameter(PluginPropertyAutomation, 0, p->first));
2171 LV2Plugin::set_automation_control (uint32_t i, boost::shared_ptr<AutomationControl> c)
2173 if ((_port_flags[i] & (PORT_CTRLED | PORT_CTRLER))) {
2174 DEBUG_TRACE(DEBUG::LV2Automate, string_compose ("Ctrl Port %1\n", i));
2175 _ctrl_map [i] = AutomationCtrlPtr (new AutomationCtrl(c));
2179 LV2Plugin::AutomationCtrlPtr
2180 LV2Plugin::get_automation_control (uint32_t i)
2182 if (_ctrl_map.find (i) == _ctrl_map.end()) {
2183 return AutomationCtrlPtr ();
2185 return _ctrl_map[i];
2189 LV2Plugin::activate()
2191 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 activate\n", name()));
2193 if (!_was_activated) {
2194 lilv_instance_activate(_impl->instance);
2195 _was_activated = true;
2200 LV2Plugin::deactivate()
2202 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 deactivate\n", name()));
2204 if (_was_activated) {
2205 lilv_instance_deactivate(_impl->instance);
2206 _was_activated = false;
2211 LV2Plugin::cleanup()
2213 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 cleanup\n", name()));
2216 lilv_instance_free(_impl->instance);
2217 _impl->instance = NULL;
2221 LV2Plugin::allocate_atom_event_buffers()
2223 /* reserve local scratch buffers for ATOM event-queues */
2224 const LilvPlugin* p = _impl->plugin;
2226 /* count non-MIDI atom event-ports
2227 * TODO: nicely ask drobilla to make a lilv_ call for that
2229 int count_atom_out = 0;
2230 int count_atom_in = 0;
2231 int minimumSize = 32768; // TODO use a per-port minimum-size
2232 for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
2233 const LilvPort* port = lilv_plugin_get_port_by_index(p, i);
2234 if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
2235 LilvNodes* buffer_types = lilv_port_get_value(
2236 p, port, _world.atom_bufferType);
2237 LilvNodes* atom_supports = lilv_port_get_value(
2238 p, port, _world.atom_supports);
2240 if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)) {
2241 if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
2244 if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
2247 LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
2248 LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
2249 if (min_size && lilv_node_is_int(min_size)) {
2250 minimumSize = std::max(minimumSize, lilv_node_as_int(min_size));
2252 lilv_nodes_free(min_size_v);
2254 lilv_nodes_free(buffer_types);
2255 lilv_nodes_free(atom_supports);
2259 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 need buffers for %2 atom-in and %3 atom-out event-ports\n",
2260 name(), count_atom_in, count_atom_out));
2262 const int total_atom_buffers = (count_atom_in + count_atom_out);
2263 if (_atom_ev_buffers || total_atom_buffers == 0) {
2267 DEBUG_TRACE(DEBUG::LV2, string_compose("allocate %1 atom_ev_buffers of %2 bytes\n", total_atom_buffers, minimumSize));
2268 _atom_ev_buffers = (LV2_Evbuf**) malloc((total_atom_buffers + 1) * sizeof(LV2_Evbuf*));
2269 for (int i = 0; i < total_atom_buffers; ++i ) {
2270 _atom_ev_buffers[i] = lv2_evbuf_new(minimumSize, LV2_EVBUF_ATOM,
2271 _uri_map.urids.atom_Chunk, _uri_map.urids.atom_Sequence);
2273 _atom_ev_buffers[total_atom_buffers] = 0;
2277 /** Write an ardour position/time/tempo/meter as an LV2 event.
2278 * @return true on success.
2281 write_position(LV2_Atom_Forge* forge,
2283 const TempoMetric& t,
2284 Timecode::BBT_Time& bbt,
2287 framepos_t position,
2290 const URIMap::URIDs& urids = URIMap::instance().urids;
2292 uint8_t pos_buf[256];
2293 lv2_atom_forge_set_buffer(forge, pos_buf, sizeof(pos_buf));
2294 LV2_Atom_Forge_Frame frame;
2295 #ifdef HAVE_LV2_1_10_0
2296 lv2_atom_forge_object(forge, &frame, 1, urids.time_Position);
2297 lv2_atom_forge_key(forge, urids.time_frame);
2298 lv2_atom_forge_long(forge, position);
2299 lv2_atom_forge_key(forge, urids.time_speed);
2300 lv2_atom_forge_float(forge, speed);
2301 lv2_atom_forge_key(forge, urids.time_barBeat);
2302 lv2_atom_forge_float(forge, bbt.beats - 1 +
2303 (bbt.ticks / Timecode::BBT_Time::ticks_per_beat));
2304 lv2_atom_forge_key(forge, urids.time_bar);
2305 lv2_atom_forge_long(forge, bbt.bars - 1);
2306 lv2_atom_forge_key(forge, urids.time_beatUnit);
2307 lv2_atom_forge_int(forge, t.meter().note_divisor());
2308 lv2_atom_forge_key(forge, urids.time_beatsPerBar);
2309 lv2_atom_forge_float(forge, t.meter().divisions_per_bar());
2310 lv2_atom_forge_key(forge, urids.time_beatsPerMinute);
2311 lv2_atom_forge_float(forge, bpm);
2313 lv2_atom_forge_blank(forge, &frame, 1, urids.time_Position);
2314 lv2_atom_forge_property_head(forge, urids.time_frame, 0);
2315 lv2_atom_forge_long(forge, position);
2316 lv2_atom_forge_property_head(forge, urids.time_speed, 0);
2317 lv2_atom_forge_float(forge, speed);
2318 lv2_atom_forge_property_head(forge, urids.time_barBeat, 0);
2319 lv2_atom_forge_float(forge, bbt.beats - 1 +
2320 (bbt.ticks / Timecode::BBT_Time::ticks_per_beat));
2321 lv2_atom_forge_property_head(forge, urids.time_bar, 0);
2322 lv2_atom_forge_long(forge, bbt.bars - 1);
2323 lv2_atom_forge_property_head(forge, urids.time_beatUnit, 0);
2324 lv2_atom_forge_int(forge, t.meter().note_divisor());
2325 lv2_atom_forge_property_head(forge, urids.time_beatsPerBar, 0);
2326 lv2_atom_forge_float(forge, t.meter().divisions_per_bar());
2327 lv2_atom_forge_property_head(forge, urids.time_beatsPerMinute, 0);
2328 lv2_atom_forge_float(forge, bpm);
2331 LV2_Evbuf_Iterator end = lv2_evbuf_end(buf);
2332 const LV2_Atom* const atom = (const LV2_Atom*)pos_buf;
2333 return lv2_evbuf_write(&end, offset, 0, atom->type, atom->size,
2334 (const uint8_t*)(atom + 1));
2338 LV2Plugin::connect_and_run(BufferSet& bufs,
2339 framepos_t start, framepos_t end, double speed,
2340 ChanMapping in_map, ChanMapping out_map,
2341 pframes_t nframes, framecnt_t offset)
2343 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 run %2 offset %3\n", name(), nframes, offset));
2344 Plugin::connect_and_run(bufs, start, end, speed, in_map, out_map, nframes, offset);
2346 cycles_t then = get_cycles();
2348 TempoMap& tmap = _session.tempo_map();
2349 Metrics::const_iterator metric_i = tmap.metrics_end();
2350 TempoMetric tmetric = tmap.metric_at(start, &metric_i);
2352 if (_freewheel_control_port) {
2353 *_freewheel_control_port = _session.engine().freewheeling() ? 1.f : 0.f;
2356 if (_bpm_control_port) {
2357 *_bpm_control_port = tmap.tempo_at_frame (start).beats_per_minute();
2361 if (_can_write_automation && start != _next_cycle_start) {
2362 // add guard-points after locating
2363 for (AutomationCtrlMap::iterator i = _ctrl_map.begin(); i != _ctrl_map.end(); ++i) {
2364 i->second->guard = true;
2369 ChanCount bufs_count;
2370 bufs_count.set(DataType::AUDIO, 1);
2371 bufs_count.set(DataType::MIDI, 1);
2372 BufferSet& silent_bufs = _session.get_silent_buffers(bufs_count);
2373 BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
2374 uint32_t const num_ports = parameter_count();
2375 uint32_t const nil_index = std::numeric_limits<uint32_t>::max();
2377 uint32_t audio_in_index = 0;
2378 uint32_t audio_out_index = 0;
2379 uint32_t midi_in_index = 0;
2380 uint32_t midi_out_index = 0;
2381 uint32_t atom_port_index = 0;
2382 for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
2384 uint32_t index = nil_index;
2385 PortFlags flags = _port_flags[port_index];
2387 if (flags & PORT_AUDIO) {
2388 if (flags & PORT_INPUT) {
2389 index = in_map.get(DataType::AUDIO, audio_in_index++, &valid);
2391 ? bufs.get_audio(index).data(offset)
2392 : silent_bufs.get_audio(0).data(offset);
2394 index = out_map.get(DataType::AUDIO, audio_out_index++, &valid);
2396 ? bufs.get_audio(index).data(offset)
2397 : scratch_bufs.get_audio(0).data(offset);
2399 } else if (flags & (PORT_EVENT|PORT_SEQUENCE)) {
2400 /* FIXME: The checks here for bufs.count().n_midi() > index shouldn't
2401 be necessary, but the mapping is illegal in some cases. Ideally
2402 that should be fixed, but this is easier...
2404 if (flags & PORT_MIDI) {
2405 if (flags & PORT_INPUT) {
2406 index = in_map.get(DataType::MIDI, midi_in_index++, &valid);
2408 index = out_map.get(DataType::MIDI, midi_out_index++, &valid);
2410 if (valid && bufs.count().n_midi() > index) {
2411 /* Note, ensure_lv2_bufsize() is not RT safe!
2412 * However free()/alloc() is only called if a
2413 * plugin requires a rsz:minimumSize buffersize
2414 * and the existing buffer if smaller.
2416 bufs.ensure_lv2_bufsize((flags & PORT_INPUT), index, _port_minimumSize[port_index]);
2417 _ev_buffers[port_index] = bufs.get_lv2_midi(
2418 (flags & PORT_INPUT), index, (flags & PORT_EVENT));
2420 } else if ((flags & PORT_POSITION) && (flags & PORT_INPUT)) {
2421 lv2_evbuf_reset(_atom_ev_buffers[atom_port_index], true);
2422 _ev_buffers[port_index] = _atom_ev_buffers[atom_port_index++];
2426 if (valid && (flags & PORT_INPUT)) {
2427 if ((flags & PORT_POSITION)) {
2428 Timecode::BBT_Time bbt (tmap.bbt_at_frame (start));
2429 double bpm = tmap.tempo_at_frame (start).beats_per_minute();
2430 double beatpos = (bbt.bars - 1) * tmetric.meter().divisions_per_bar()
2432 + (bbt.ticks / Timecode::BBT_Time::ticks_per_beat);
2433 beatpos *= tmetric.meter().note_divisor() / 4.0;
2434 if (start != _next_cycle_start ||
2435 speed != _next_cycle_speed ||
2436 rint (1000 * beatpos) != rint(1000 * _next_cycle_beat) ||
2437 bpm != _current_bpm) {
2438 // Transport or Tempo has changed, write position at cycle start
2439 write_position(&_impl->forge, _ev_buffers[port_index],
2440 tmetric, bbt, speed, bpm, start, 0);
2444 // Get MIDI iterator range (empty range if no MIDI)
2445 MidiBuffer::iterator m = (index != nil_index)
2446 ? bufs.get_midi(index).begin()
2447 : silent_bufs.get_midi(0).end();
2448 MidiBuffer::iterator m_end = (index != nil_index)
2449 ? bufs.get_midi(index).end()
2452 // Now merge MIDI and any transport events into the buffer
2453 const uint32_t type = _uri_map.urids.midi_MidiEvent;
2454 const framepos_t tend = end;
2456 while (m != m_end || (metric_i != tmap.metrics_end() &&
2457 (*metric_i)->frame() < tend)) {
2458 MetricSection* metric = (metric_i != tmap.metrics_end())
2460 if (m != m_end && (!metric || metric->frame() > (*m).time())) {
2461 const Evoral::MIDIEvent<framepos_t> ev(*m, false);
2462 if (ev.time() < nframes) {
2463 LV2_Evbuf_Iterator eend = lv2_evbuf_end(_ev_buffers[port_index]);
2464 lv2_evbuf_write(&eend, ev.time(), 0, type, ev.size(), ev.buffer());
2468 tmetric.set_metric(metric);
2469 Timecode::BBT_Time bbt;
2470 bbt = tmap.bbt_at_pulse (metric->pulse());
2471 double bpm = tmap.tempo_at_frame (start/*XXX*/).beats_per_minute();
2472 write_position(&_impl->forge, _ev_buffers[port_index],
2473 tmetric, bbt, speed, bpm,
2475 metric->frame() - start);
2479 } else if (!valid) {
2480 // Nothing we understand or care about, connect to scratch
2481 // see note for midi-buffer size above
2482 scratch_bufs.ensure_lv2_bufsize((flags & PORT_INPUT),
2483 0, _port_minimumSize[port_index]);
2484 _ev_buffers[port_index] = scratch_bufs.get_lv2_midi(
2485 (flags & PORT_INPUT), 0, (flags & PORT_EVENT));
2488 buf = lv2_evbuf_get_buffer(_ev_buffers[port_index]);
2490 continue; // Control port, leave buffer alone
2492 lilv_instance_connect_port(_impl->instance, port_index, buf);
2495 // Read messages from UI and push into appropriate buffers
2497 uint32_t read_space = _from_ui->read_space();
2498 while (read_space > sizeof(UIMessage)) {
2500 if (_from_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
2501 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
2504 vector<uint8_t> body(msg.size);
2505 if (_from_ui->read(&body[0], msg.size) != msg.size) {
2506 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
2509 if (msg.protocol == URIMap::instance().urids.atom_eventTransfer) {
2510 LV2_Evbuf* buf = _ev_buffers[msg.index];
2511 LV2_Evbuf_Iterator i = lv2_evbuf_end(buf);
2512 const LV2_Atom* const atom = (const LV2_Atom*)&body[0];
2513 if (!lv2_evbuf_write(&i, nframes - 1, 0, atom->type, atom->size,
2514 (const uint8_t*)(atom + 1))) {
2515 error << "Failed to write data to LV2 event buffer\n";
2518 error << "Received unknown message type from UI" << endmsg;
2520 read_space -= sizeof(UIMessage) + msg.size;
2527 for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
2528 PortFlags flags = _port_flags[port_index];
2531 /* TODO ask drobilla about comment
2532 * "Make Ardour event buffers generic so plugins can communicate"
2533 * in libs/ardour/buffer_set.cc:310
2535 * ideally the user could choose which of the following two modes
2536 * to use (e.g. instrument/effect chains MIDI OUT vs MIDI TRHU).
2538 * This implementation follows the discussion on IRC Mar 16 2013 16:47 UTC
2539 * 16:51 < drobilla> rgareus: [..] i.e always replace with MIDI output [of LV2 plugin] if it's there
2540 * 16:52 < drobilla> rgareus: That would probably be good enough [..] to make users not complain
2541 * for quite a while at least ;)
2543 // copy output of LV2 plugin's MIDI port to Ardour MIDI buffers -- MIDI OUT
2544 if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE|PORT_MIDI))) {
2545 const uint32_t buf_index = out_map.get(
2546 DataType::MIDI, midi_out_index++, &valid);
2548 bufs.forward_lv2_midi(_ev_buffers[port_index], buf_index);
2551 // Flush MIDI (write back to Ardour MIDI buffers) -- MIDI THRU
2552 else if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
2553 const uint32_t buf_index = out_map.get(
2554 DataType::MIDI, midi_out_index++, &valid);
2556 bufs.flush_lv2_midi(true, buf_index);
2560 // Write messages to UI
2561 if ((_to_ui || _can_write_automation || _patch_port_out_index != (uint32_t)-1) &&
2562 (flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
2563 LV2_Evbuf* buf = _ev_buffers[port_index];
2564 for (LV2_Evbuf_Iterator i = lv2_evbuf_begin(buf);
2565 lv2_evbuf_is_valid(i);
2566 i = lv2_evbuf_next(i)) {
2567 uint32_t frames, subframes, type, size;
2569 lv2_evbuf_get(i, &frames, &subframes, &type, &size, &data);
2572 // Intercept Automation Write Events
2573 if ((flags & PORT_AUTOCTRL)) {
2574 LV2_Atom* atom = (LV2_Atom*)(data - sizeof(LV2_Atom));
2575 if (atom->type == _uri_map.urids.atom_Blank ||
2576 atom->type == _uri_map.urids.atom_Object) {
2577 LV2_Atom_Object* obj = (LV2_Atom_Object*)atom;
2578 if (obj->body.otype == _uri_map.urids.auto_event) {
2579 // only if transport_rolling ??
2580 const LV2_Atom* parameter = NULL;
2581 const LV2_Atom* value = NULL;
2582 lv2_atom_object_get(obj,
2583 _uri_map.urids.auto_parameter, ¶meter,
2584 _uri_map.urids.auto_value, &value,
2586 if (parameter && value) {
2587 const uint32_t p = ((const LV2_Atom_Int*)parameter)->body;
2588 const float v = ((const LV2_Atom_Float*)value)->body;
2589 // -> add automation event..
2590 DEBUG_TRACE(DEBUG::LV2Automate,
2591 string_compose ("Event p: %1 t: %2 v: %3\n", p, frames, v));
2592 AutomationCtrlPtr c = get_automation_control (p);
2594 (c->ac->automation_state() == Touch || c->ac->automation_state() == Write)
2596 framepos_t when = std::max ((framepos_t) 0, start + frames - _current_latency);
2597 assert (start + frames - _current_latency >= 0);
2600 c->ac->list()->add (when, v, true, true);
2602 c->ac->set_double (v, when, true);
2607 else if (obj->body.otype == _uri_map.urids.auto_setup) {
2608 // TODO optional arguments, for now we assume the plugin
2609 // writes automation for its own inputs
2610 // -> put them in "touch" mode (preferably "exclusive plugin touch(TM)"
2611 for (AutomationCtrlMap::iterator i = _ctrl_map.begin(); i != _ctrl_map.end(); ++i) {
2612 if (_port_flags[i->first] & PORT_CTRLED) {
2613 DEBUG_TRACE(DEBUG::LV2Automate,
2614 string_compose ("Setup p: %1\n", i->first));
2615 i->second->ac->set_automation_state (Touch);
2619 else if (obj->body.otype == _uri_map.urids.auto_finalize) {
2620 // set [touched] parameters to "play" ??
2621 // allow plugin to change its mode (from analyze to apply)
2622 const LV2_Atom* parameter = NULL;
2623 const LV2_Atom* value = NULL;
2624 lv2_atom_object_get(obj,
2625 _uri_map.urids.auto_parameter, ¶meter,
2626 _uri_map.urids.auto_value, &value,
2628 if (parameter && value) {
2629 const uint32_t p = ((const LV2_Atom_Int*)parameter)->body;
2630 const float v = ((const LV2_Atom_Float*)value)->body;
2631 AutomationCtrlPtr c = get_automation_control (p);
2632 DEBUG_TRACE(DEBUG::LV2Automate,
2633 string_compose ("Finalize p: %1 v: %2\n", p, v));
2634 if (c && _port_flags[p] & PORT_CTRLER) {
2635 c->ac->set_value(v, Controllable::NoGroup);
2638 DEBUG_TRACE(DEBUG::LV2Automate, "Finalize\n");
2640 for (AutomationCtrlMap::iterator i = _ctrl_map.begin(); i != _ctrl_map.end(); ++i) {
2641 // guard will be false if an event was written
2642 if ((_port_flags[i->first] & PORT_CTRLED) && !i->second->guard) {
2643 DEBUG_TRACE(DEBUG::LV2Automate,
2644 string_compose ("Thin p: %1\n", i->first));
2645 i->second->ac->alist ()->thin (20);
2649 else if (obj->body.otype == _uri_map.urids.auto_start) {
2650 const LV2_Atom* parameter = NULL;
2651 lv2_atom_object_get(obj,
2652 _uri_map.urids.auto_parameter, ¶meter,
2655 const uint32_t p = ((const LV2_Atom_Int*)parameter)->body;
2656 AutomationCtrlPtr c = get_automation_control (p);
2657 DEBUG_TRACE(DEBUG::LV2Automate, string_compose ("Start Touch p: %1\n", p));
2659 c->ac->start_touch (std::max ((framepos_t)0, start - _current_latency));
2664 else if (obj->body.otype == _uri_map.urids.auto_end) {
2665 const LV2_Atom* parameter = NULL;
2666 lv2_atom_object_get(obj,
2667 _uri_map.urids.auto_parameter, ¶meter,
2670 const uint32_t p = ((const LV2_Atom_Int*)parameter)->body;
2671 AutomationCtrlPtr c = get_automation_control (p);
2672 DEBUG_TRACE(DEBUG::LV2Automate, string_compose ("End Touch p: %1\n", p));
2674 c->ac->stop_touch (true, std::max ((framepos_t)0, start - _current_latency));
2682 // Intercept patch change messages to emit PropertyChanged signal
2683 if ((flags & PORT_PATCHMSG)) {
2684 LV2_Atom* atom = (LV2_Atom*)(data - sizeof(LV2_Atom));
2685 if (atom->type == _uri_map.urids.atom_Blank ||
2686 atom->type == _uri_map.urids.atom_Object) {
2687 LV2_Atom_Object* obj = (LV2_Atom_Object*)atom;
2688 if (obj->body.otype == _uri_map.urids.patch_Set) {
2689 const LV2_Atom* property = NULL;
2690 const LV2_Atom* value = NULL;
2691 lv2_atom_object_get(obj,
2692 _uri_map.urids.patch_property, &property,
2693 _uri_map.urids.patch_value, &value,
2696 if (property && value &&
2697 property->type == _uri_map.urids.atom_URID &&
2698 value->type == _uri_map.urids.atom_Path) {
2699 const uint32_t prop_id = ((const LV2_Atom_URID*)property)->body;
2700 const char* path = (const char*)LV2_ATOM_BODY_CONST(value);
2702 // Emit PropertyChanged signal for UI
2703 // TODO: This should emit the control's Changed signal
2704 PropertyChanged(prop_id, Variant(Variant::PATH, path));
2706 std::cerr << "warning: patch:Set for unknown property" << std::endl;
2712 if (!_to_ui) continue;
2713 write_to_ui(port_index, URIMap::instance().urids.atom_eventTransfer,
2714 size + sizeof(LV2_Atom),
2715 data - sizeof(LV2_Atom));
2720 cycles_t now = get_cycles();
2721 set_cycles((uint32_t)(now - then));
2723 // Update expected transport information for next cycle so we can detect changes
2724 _next_cycle_speed = speed;
2725 _next_cycle_start = end;
2728 /* keep track of lv2:timePosition like plugins can do.
2729 * Note: for no-midi plugins, we only ever send information at cycle-start,
2730 * so it needs to be realative to that.
2732 TempoMetric t = tmap.metric_at(start);
2733 _current_bpm = tmap.tempo_at_frame (start).beats_per_minute();
2734 Timecode::BBT_Time bbt (tmap.bbt_at_frame (start));
2735 double beatpos = (bbt.bars - 1) * t.meter().divisions_per_bar()
2737 + (bbt.ticks / Timecode::BBT_Time::ticks_per_beat);
2738 beatpos *= tmetric.meter().note_divisor() / 4.0;
2739 _next_cycle_beat = beatpos + nframes * speed * _current_bpm / (60.f * _session.frame_rate());
2742 if (_latency_control_port) {
2743 framecnt_t new_latency = signal_latency ();
2744 _current_latency = new_latency;
2750 LV2Plugin::parameter_is_control(uint32_t param) const
2752 assert(param < _port_flags.size());
2753 return _port_flags[param] & PORT_CONTROL;
2757 LV2Plugin::parameter_is_audio(uint32_t param) const
2759 assert(param < _port_flags.size());
2760 return _port_flags[param] & PORT_AUDIO;
2764 LV2Plugin::parameter_is_event(uint32_t param) const
2766 assert(param < _port_flags.size());
2767 return _port_flags[param] & PORT_EVENT;
2771 LV2Plugin::parameter_is_output(uint32_t param) const
2773 assert(param < _port_flags.size());
2774 return _port_flags[param] & PORT_OUTPUT;
2778 LV2Plugin::parameter_is_input(uint32_t param) const
2780 assert(param < _port_flags.size());
2781 return _port_flags[param] & PORT_INPUT;
2785 LV2Plugin::designated_bypass_port ()
2788 const LilvPort* port = NULL;
2789 LilvNode* designation = lilv_new_uri (_world.world, LV2_PROCESSING_URI__enable);
2790 port = lilv_plugin_get_port_by_designation (
2791 _impl->plugin, _world.lv2_InputPort, designation);
2792 lilv_node_free(designation);
2794 return lilv_port_get_index (_impl->plugin, port);
2801 LV2Plugin::print_parameter(uint32_t param, char* buf, uint32_t len) const
2804 if (param < parameter_count()) {
2805 snprintf(buf, len, "%.3f", get_parameter(param));
2812 boost::shared_ptr<ScalePoints>
2813 LV2Plugin::get_scale_points(uint32_t port_index) const
2815 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, port_index);
2816 LilvScalePoints* points = lilv_port_get_scale_points(_impl->plugin, port);
2818 boost::shared_ptr<ScalePoints> ret;
2823 ret = boost::shared_ptr<ScalePoints>(new ScalePoints());
2825 LILV_FOREACH(scale_points, i, points) {
2826 const LilvScalePoint* p = lilv_scale_points_get(points, i);
2827 const LilvNode* label = lilv_scale_point_get_label(p);
2828 const LilvNode* value = lilv_scale_point_get_value(p);
2829 if (label && (lilv_node_is_float(value) || lilv_node_is_int(value))) {
2830 ret->insert(make_pair(lilv_node_as_string(label),
2831 lilv_node_as_float(value)));
2835 lilv_scale_points_free(points);
2840 LV2Plugin::run(pframes_t nframes, bool sync_work)
2842 uint32_t const N = parameter_count();
2843 for (uint32_t i = 0; i < N; ++i) {
2844 if (parameter_is_control(i) && parameter_is_input(i)) {
2845 _control_data[i] = _shadow_data[i];
2850 // Execute work synchronously if we're freewheeling (export)
2851 _worker->set_synchronous(sync_work || session().engine().freewheeling());
2854 // Run the plugin for this cycle
2855 lilv_instance_run(_impl->instance, nframes);
2857 // Emit any queued worker responses (calls a plugin callback)
2858 if (_state_worker) {
2859 _state_worker->emit_responses();
2862 _worker->emit_responses();
2865 // Notify the plugin that a work run cycle is complete
2866 if (_impl->work_iface) {
2867 if (_impl->work_iface->end_run) {
2868 _impl->work_iface->end_run(_impl->instance->lv2_handle);
2874 LV2Plugin::latency_compute_run()
2876 if (!_latency_control_port) {
2880 // Run the plugin so that it can set its latency parameter
2882 bool was_activated = _was_activated;
2885 uint32_t port_index = 0;
2886 uint32_t in_index = 0;
2887 uint32_t out_index = 0;
2889 // this is done in the main thread. non realtime.
2890 const framecnt_t bufsize = _engine.samples_per_cycle();
2891 float *buffer = (float*) malloc(_engine.samples_per_cycle() * sizeof(float));
2893 memset(buffer, 0, sizeof(float) * bufsize);
2895 // FIXME: Ensure plugins can handle in-place processing
2899 while (port_index < parameter_count()) {
2900 if (parameter_is_audio(port_index)) {
2901 if (parameter_is_input(port_index)) {
2902 lilv_instance_connect_port(_impl->instance, port_index, buffer);
2904 } else if (parameter_is_output(port_index)) {
2905 lilv_instance_connect_port(_impl->instance, port_index, buffer);
2914 if (was_activated) {
2921 LV2Plugin::Impl::designated_input (const char* uri, void** bufptrs[], void** bufptr)
2923 const LilvPort* port = NULL;
2924 LilvNode* designation = lilv_new_uri(_world.world, uri);
2925 port = lilv_plugin_get_port_by_designation(
2926 plugin, _world.lv2_InputPort, designation);
2927 lilv_node_free(designation);
2929 bufptrs[lilv_port_get_index(plugin, port)] = bufptr;
2934 static bool lv2_filter (const string& str, void* /*arg*/)
2936 /* Not a dotfile, has a prefix before a period, suffix is "lv2" */
2938 return str[0] != '.' && (str.length() > 3 && str.find (".lv2") == (str.length() - 4));
2942 LV2World::LV2World()
2943 : world(lilv_world_new())
2944 , _bundle_checked(false)
2946 atom_AtomPort = lilv_new_uri(world, LV2_ATOM__AtomPort);
2947 atom_Chunk = lilv_new_uri(world, LV2_ATOM__Chunk);
2948 atom_Sequence = lilv_new_uri(world, LV2_ATOM__Sequence);
2949 atom_bufferType = lilv_new_uri(world, LV2_ATOM__bufferType);
2950 atom_supports = lilv_new_uri(world, LV2_ATOM__supports);
2951 atom_eventTransfer = lilv_new_uri(world, LV2_ATOM__eventTransfer);
2952 ev_EventPort = lilv_new_uri(world, LILV_URI_EVENT_PORT);
2953 ext_logarithmic = lilv_new_uri(world, LV2_PORT_PROPS__logarithmic);
2954 ext_notOnGUI = lilv_new_uri(world, LV2_PORT_PROPS__notOnGUI);
2955 ext_expensive = lilv_new_uri(world, LV2_PORT_PROPS__expensive);
2956 ext_causesArtifacts= lilv_new_uri(world, LV2_PORT_PROPS__causesArtifacts);
2957 ext_notAutomatic = lilv_new_uri(world, LV2_PORT_PROPS__notAutomatic);
2958 ext_rangeSteps = lilv_new_uri(world, LV2_PORT_PROPS__rangeSteps);
2959 lv2_AudioPort = lilv_new_uri(world, LILV_URI_AUDIO_PORT);
2960 lv2_ControlPort = lilv_new_uri(world, LILV_URI_CONTROL_PORT);
2961 lv2_InputPort = lilv_new_uri(world, LILV_URI_INPUT_PORT);
2962 lv2_OutputPort = lilv_new_uri(world, LILV_URI_OUTPUT_PORT);
2963 lv2_inPlaceBroken = lilv_new_uri(world, LV2_CORE__inPlaceBroken);
2964 lv2_isSideChain = lilv_new_uri(world, LV2_CORE_PREFIX "isSideChain");
2965 lv2_integer = lilv_new_uri(world, LV2_CORE__integer);
2966 lv2_default = lilv_new_uri(world, LV2_CORE__default);
2967 lv2_minimum = lilv_new_uri(world, LV2_CORE__minimum);
2968 lv2_maximum = lilv_new_uri(world, LV2_CORE__maximum);
2969 lv2_reportsLatency = lilv_new_uri(world, LV2_CORE__reportsLatency);
2970 lv2_sampleRate = lilv_new_uri(world, LV2_CORE__sampleRate);
2971 lv2_toggled = lilv_new_uri(world, LV2_CORE__toggled);
2972 lv2_enumeration = lilv_new_uri(world, LV2_CORE__enumeration);
2973 lv2_freewheeling = lilv_new_uri(world, LV2_CORE__freeWheeling);
2974 midi_MidiEvent = lilv_new_uri(world, LILV_URI_MIDI_EVENT);
2975 rdfs_comment = lilv_new_uri(world, LILV_NS_RDFS "comment");
2976 rdfs_label = lilv_new_uri(world, LILV_NS_RDFS "label");
2977 rdfs_range = lilv_new_uri(world, LILV_NS_RDFS "range");
2978 rsz_minimumSize = lilv_new_uri(world, LV2_RESIZE_PORT__minimumSize);
2979 time_Position = lilv_new_uri(world, LV2_TIME__Position);
2980 ui_GtkUI = lilv_new_uri(world, LV2_UI__GtkUI);
2981 ui_external = lilv_new_uri(world, "http://lv2plug.in/ns/extensions/ui#external");
2982 ui_externalkx = lilv_new_uri(world, "http://kxstudio.sf.net/ns/lv2ext/external-ui#Widget");
2983 units_unit = lilv_new_uri(world, LV2_UNITS__unit);
2984 units_render = lilv_new_uri(world, LV2_UNITS__render);
2985 units_hz = lilv_new_uri(world, LV2_UNITS__hz);
2986 units_midiNote = lilv_new_uri(world, LV2_UNITS__midiNote);
2987 units_db = lilv_new_uri(world, LV2_UNITS__db);
2988 patch_writable = lilv_new_uri(world, LV2_PATCH__writable);
2989 patch_Message = lilv_new_uri(world, LV2_PATCH__Message);
2991 lv2_noSampleAccurateCtrl = lilv_new_uri(world, "http://ardour.org/lv2/ext#noSampleAccurateControls");
2992 auto_can_write_automatation = lilv_new_uri(world, LV2_AUTOMATE_URI__can_write);
2993 auto_automation_control = lilv_new_uri(world, LV2_AUTOMATE_URI__control);
2994 auto_automation_controlled = lilv_new_uri(world, LV2_AUTOMATE_URI__controlled);
2995 auto_automation_controller = lilv_new_uri(world, LV2_AUTOMATE_URI__controller);
2997 #ifdef HAVE_LV2_1_2_0
2998 bufz_powerOf2BlockLength = lilv_new_uri(world, LV2_BUF_SIZE__powerOf2BlockLength);
2999 bufz_fixedBlockLength = lilv_new_uri(world, LV2_BUF_SIZE__fixedBlockLength);
3000 bufz_nominalBlockLength = lilv_new_uri(world, "http://lv2plug.in/ns/ext/buf-size#nominalBlockLength");
3005 LV2World::~LV2World()
3010 #ifdef HAVE_LV2_1_2_0
3011 lilv_node_free(bufz_nominalBlockLength);
3012 lilv_node_free(bufz_fixedBlockLength);
3013 lilv_node_free(bufz_powerOf2BlockLength);
3016 lilv_node_free(lv2_noSampleAccurateCtrl);
3017 lilv_node_free(auto_can_write_automatation);
3018 lilv_node_free(auto_automation_control);
3019 lilv_node_free(auto_automation_controlled);
3020 lilv_node_free(auto_automation_controller);
3022 lilv_node_free(patch_Message);
3023 lilv_node_free(patch_writable);
3024 lilv_node_free(units_hz);
3025 lilv_node_free(units_midiNote);
3026 lilv_node_free(units_db);
3027 lilv_node_free(units_unit);
3028 lilv_node_free(units_render);
3029 lilv_node_free(ui_externalkx);
3030 lilv_node_free(ui_external);
3031 lilv_node_free(ui_GtkUI);
3032 lilv_node_free(time_Position);
3033 lilv_node_free(rsz_minimumSize);
3034 lilv_node_free(rdfs_comment);
3035 lilv_node_free(rdfs_label);
3036 lilv_node_free(rdfs_range);
3037 lilv_node_free(midi_MidiEvent);
3038 lilv_node_free(lv2_enumeration);
3039 lilv_node_free(lv2_freewheeling);
3040 lilv_node_free(lv2_toggled);
3041 lilv_node_free(lv2_sampleRate);
3042 lilv_node_free(lv2_reportsLatency);
3043 lilv_node_free(lv2_integer);
3044 lilv_node_free(lv2_isSideChain);
3045 lilv_node_free(lv2_inPlaceBroken);
3046 lilv_node_free(lv2_OutputPort);
3047 lilv_node_free(lv2_InputPort);
3048 lilv_node_free(lv2_ControlPort);
3049 lilv_node_free(lv2_AudioPort);
3050 lilv_node_free(ext_rangeSteps);
3051 lilv_node_free(ext_notAutomatic);
3052 lilv_node_free(ext_causesArtifacts);
3053 lilv_node_free(ext_expensive);
3054 lilv_node_free(ext_notOnGUI);
3055 lilv_node_free(ext_logarithmic);
3056 lilv_node_free(ev_EventPort);
3057 lilv_node_free(atom_supports);
3058 lilv_node_free(atom_eventTransfer);
3059 lilv_node_free(atom_bufferType);
3060 lilv_node_free(atom_Sequence);
3061 lilv_node_free(atom_Chunk);
3062 lilv_node_free(atom_AtomPort);
3063 lilv_world_free(world);
3068 LV2World::load_bundled_plugins(bool verbose)
3070 if (!_bundle_checked) {
3072 cout << "Scanning folders for bundled LV2s: " << ARDOUR::lv2_bundled_search_path().to_string() << endl;
3075 vector<string> plugin_objects;
3076 find_paths_matching_filter (plugin_objects, ARDOUR::lv2_bundled_search_path(), lv2_filter, 0, true, true, true);
3077 for ( vector<string>::iterator x = plugin_objects.begin(); x != plugin_objects.end (); ++x) {
3078 #ifdef PLATFORM_WINDOWS
3079 string uri = "file:///" + *x + "/";
3081 string uri = "file://" + *x + "/";
3083 LilvNode *node = lilv_new_uri(world, uri.c_str());
3084 lilv_world_load_bundle(world, node);
3085 lilv_node_free(node);
3088 lilv_world_load_all(world);
3089 _bundle_checked = true;
3093 LV2PluginInfo::LV2PluginInfo (const char* plugin_uri)
3096 _plugin_uri = strdup(plugin_uri);
3099 LV2PluginInfo::~LV2PluginInfo()
3106 LV2PluginInfo::load(Session& session)
3110 const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
3111 LilvNode* uri = lilv_new_uri(_world.world, _plugin_uri);
3112 if (!uri) { throw failed_constructor(); }
3113 const LilvPlugin* lp = lilv_plugins_get_by_uri(plugins, uri);
3114 if (!lp) { throw failed_constructor(); }
3115 plugin.reset(new LV2Plugin(session.engine(), session, lp, session.frame_rate()));
3116 lilv_node_free(uri);
3117 plugin->set_info(PluginInfoPtr(shared_from_this ()));
3119 } catch (failed_constructor& err) {
3120 return PluginPtr((Plugin*)0);
3126 std::vector<Plugin::PresetRecord>
3127 LV2PluginInfo::get_presets (bool /*user_only*/) const
3129 std::vector<Plugin::PresetRecord> p;
3130 #ifndef NO_PLUGIN_STATE
3131 const LilvPlugin* lp = NULL;
3134 const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
3135 LilvNode* uri = lilv_new_uri(_world.world, _plugin_uri);
3136 if (!uri) { throw failed_constructor(); }
3137 lp = lilv_plugins_get_by_uri(plugins, uri);
3138 if (!lp) { throw failed_constructor(); }
3139 lilv_node_free(uri);
3140 } catch (failed_constructor& err) {
3144 // see LV2Plugin::find_presets
3145 LilvNode* lv2_appliesTo = lilv_new_uri(_world.world, LV2_CORE__appliesTo);
3146 LilvNode* pset_Preset = lilv_new_uri(_world.world, LV2_PRESETS__Preset);
3147 LilvNode* rdfs_label = lilv_new_uri(_world.world, LILV_NS_RDFS "label");
3149 LilvNodes* presets = lilv_plugin_get_related(lp, pset_Preset);
3150 LILV_FOREACH(nodes, i, presets) {
3151 const LilvNode* preset = lilv_nodes_get(presets, i);
3152 lilv_world_load_resource(_world.world, preset);
3153 LilvNode* name = get_value(_world.world, preset, rdfs_label);
3154 bool userpreset = true; // TODO
3156 p.push_back (Plugin::PresetRecord (lilv_node_as_string(preset), lilv_node_as_string(name), userpreset));
3157 lilv_node_free(name);
3160 lilv_nodes_free(presets);
3161 lilv_node_free(rdfs_label);
3162 lilv_node_free(pset_Preset);
3163 lilv_node_free(lv2_appliesTo);
3169 LV2PluginInfo::in_category (const std::string &c) const
3171 // TODO use untranslated lilv_plugin_get_class()
3172 // match gtk2_ardour/plugin_selector.cc
3173 if (category == c) {
3180 LV2PluginInfo::is_instrument () const
3182 if (category == "Instrument") {
3186 /* until we make sure that category remains untranslated in the lv2.ttl spec
3187 * and until most instruments also classify themselves as such, there's a 2nd check:
3189 if (n_inputs.n_midi() > 0 && n_inputs.n_audio() == 0 && n_outputs.n_audio() > 0) {
3197 LV2PluginInfo::discover()
3200 world.load_bundled_plugins();
3201 _world.load_bundled_plugins(true);
3203 PluginInfoList* plugs = new PluginInfoList;
3204 const LilvPlugins* plugins = lilv_world_get_all_plugins(world.world);
3206 LILV_FOREACH(plugins, i, plugins) {
3207 const LilvPlugin* p = lilv_plugins_get(plugins, i);
3208 const LilvNode* pun = lilv_plugin_get_uri(p);
3210 LV2PluginInfoPtr info(new LV2PluginInfo(lilv_node_as_string(pun)));
3212 LilvNode* name = lilv_plugin_get_name(p);
3213 if (!name || !lilv_plugin_get_port_by_index(p, 0)) {
3214 warning << "Ignoring invalid LV2 plugin "
3215 << lilv_node_as_string(lilv_plugin_get_uri(p))
3220 if (lilv_plugin_has_feature(p, world.lv2_inPlaceBroken)) {
3221 warning << string_compose(
3222 _("Ignoring LV2 plugin \"%1\" since it cannot do inplace processing."),
3223 lilv_node_as_string(name)) << endmsg;
3224 lilv_node_free(name);
3228 #ifdef HAVE_LV2_1_2_0
3229 LilvNodes *required_features = lilv_plugin_get_required_features (p);
3230 if (lilv_nodes_contains (required_features, world.bufz_powerOf2BlockLength) ||
3231 lilv_nodes_contains (required_features, world.bufz_fixedBlockLength)
3233 warning << string_compose(
3234 _("Ignoring LV2 plugin \"%1\" because its buffer-size requirements cannot be satisfied."),
3235 lilv_node_as_string(name)) << endmsg;
3236 lilv_nodes_free(required_features);
3237 lilv_node_free(name);
3240 lilv_nodes_free(required_features);
3245 info->name = string(lilv_node_as_string(name));
3246 lilv_node_free(name);
3247 ARDOUR::PluginScanMessage(_("LV2"), info->name, false);
3249 const LilvPluginClass* pclass = lilv_plugin_get_class(p);
3250 const LilvNode* label = lilv_plugin_class_get_label(pclass);
3251 info->category = lilv_node_as_string(label);
3253 LilvNode* author_name = lilv_plugin_get_author_name(p);
3254 info->creator = author_name ? string(lilv_node_as_string(author_name)) : "Unknown";
3255 lilv_node_free(author_name);
3257 info->path = "/NOPATH"; // Meaningless for LV2
3259 /* count atom-event-ports that feature
3260 * atom:supports <http://lv2plug.in/ns/ext/midi#MidiEvent>
3262 * TODO: nicely ask drobilla to make a lilv_ call for that
3264 int count_midi_out = 0;
3265 int count_midi_in = 0;
3266 for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
3267 const LilvPort* port = lilv_plugin_get_port_by_index(p, i);
3268 if (lilv_port_is_a(p, port, world.atom_AtomPort)) {
3269 LilvNodes* buffer_types = lilv_port_get_value(
3270 p, port, world.atom_bufferType);
3271 LilvNodes* atom_supports = lilv_port_get_value(
3272 p, port, world.atom_supports);
3274 if (lilv_nodes_contains(buffer_types, world.atom_Sequence)
3275 && lilv_nodes_contains(atom_supports, world.midi_MidiEvent)) {
3276 if (lilv_port_is_a(p, port, world.lv2_InputPort)) {
3279 if (lilv_port_is_a(p, port, world.lv2_OutputPort)) {
3283 lilv_nodes_free(buffer_types);
3284 lilv_nodes_free(atom_supports);
3288 info->n_inputs.set_audio(
3289 lilv_plugin_get_num_ports_of_class(
3290 p, world.lv2_InputPort, world.lv2_AudioPort, NULL));
3291 info->n_inputs.set_midi(
3292 lilv_plugin_get_num_ports_of_class(
3293 p, world.lv2_InputPort, world.ev_EventPort, NULL)
3296 info->n_outputs.set_audio(
3297 lilv_plugin_get_num_ports_of_class(
3298 p, world.lv2_OutputPort, world.lv2_AudioPort, NULL));
3299 info->n_outputs.set_midi(
3300 lilv_plugin_get_num_ports_of_class(
3301 p, world.lv2_OutputPort, world.ev_EventPort, NULL)
3304 info->unique_id = lilv_node_as_uri(lilv_plugin_get_uri(p));
3305 info->index = 0; // Meaningless for LV2
3307 plugs->push_back(info);