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/midi_patch_manager.h"
49 #include "ardour/session.h"
50 #include "ardour/tempo.h"
51 #include "ardour/types.h"
52 #include "ardour/utils.h"
53 #include "ardour/worker.h"
54 #include "ardour/search_paths.h"
59 #include <lilv/lilv.h>
61 #include "lv2/lv2plug.in/ns/ext/atom/atom.h"
62 #include "lv2/lv2plug.in/ns/ext/atom/forge.h"
63 #include "lv2/lv2plug.in/ns/ext/log/log.h"
64 #include "lv2/lv2plug.in/ns/ext/midi/midi.h"
65 #include "lv2/lv2plug.in/ns/ext/port-props/port-props.h"
66 #include "lv2/lv2plug.in/ns/ext/presets/presets.h"
67 #include "lv2/lv2plug.in/ns/ext/state/state.h"
68 #include "lv2/lv2plug.in/ns/ext/time/time.h"
69 #include "lv2/lv2plug.in/ns/ext/worker/worker.h"
70 #include "lv2/lv2plug.in/ns/ext/resize-port/resize-port.h"
71 #include "lv2/lv2plug.in/ns/extensions/ui/ui.h"
72 #include "lv2/lv2plug.in/ns/extensions/units/units.h"
73 #include "lv2/lv2plug.in/ns/ext/patch/patch.h"
74 #include "lv2/lv2plug.in/ns/ext/port-groups/port-groups.h"
76 #include "lv2/lv2plug.in/ns/ext/buf-size/buf-size.h"
77 #include "lv2/lv2plug.in/ns/ext/options/options.h"
80 #include "lv2_evbuf.h"
83 #include <suil/suil.h>
86 // Compatibility for old LV2
87 #ifndef LV2_ATOM_CONTENTS_CONST
88 #define LV2_ATOM_CONTENTS_CONST(type, atom) \
89 ((const void*)((const uint8_t*)(atom) + sizeof(type)))
91 #ifndef LV2_ATOM_BODY_CONST
92 #define LV2_ATOM_BODY_CONST(atom) LV2_ATOM_CONTENTS_CONST(LV2_Atom, atom)
94 #ifndef LV2_PATCH__property
95 #define LV2_PATCH__property LV2_PATCH_PREFIX "property"
97 #ifndef LV2_PATCH__value
98 #define LV2_PATCH__value LV2_PATCH_PREFIX "value"
100 #ifndef LV2_PATCH__writable
101 #define LV2_PATCH__writable LV2_PATCH_PREFIX "writable"
104 /** The number of MIDI buffers that will fit in a UI/worker comm buffer.
105 This needs to be roughly the number of cycles the UI will get around to
106 actually processing the traffic. Lower values are flakier but save memory.
108 static const size_t NBUFS = 4;
111 using namespace ARDOUR;
114 bool LV2Plugin::force_state_save = false;
116 class LV2World : boost::noncopyable {
121 void load_bundled_plugins(bool verbose=false);
125 LilvNode* atom_AtomPort;
126 LilvNode* atom_Chunk;
127 LilvNode* atom_Sequence;
128 LilvNode* atom_bufferType;
129 LilvNode* atom_eventTransfer;
130 LilvNode* atom_supports;
131 LilvNode* ev_EventPort;
132 LilvNode* ext_logarithmic;
133 LilvNode* ext_notOnGUI;
134 LilvNode* ext_expensive;
135 LilvNode* ext_causesArtifacts;
136 LilvNode* ext_notAutomatic;
137 LilvNode* ext_rangeSteps;
138 LilvNode* groups_group;
139 LilvNode* groups_element;
140 LilvNode* lv2_AudioPort;
141 LilvNode* lv2_ControlPort;
142 LilvNode* lv2_InputPort;
143 LilvNode* lv2_OutputPort;
144 LilvNode* lv2_designation;
145 LilvNode* lv2_enumeration;
146 LilvNode* lv2_freewheeling;
147 LilvNode* lv2_inPlaceBroken;
148 LilvNode* lv2_isSideChain;
150 LilvNode* lv2_integer;
151 LilvNode* lv2_default;
152 LilvNode* lv2_minimum;
153 LilvNode* lv2_maximum;
154 LilvNode* lv2_reportsLatency;
155 LilvNode* lv2_sampleRate;
156 LilvNode* lv2_toggled;
157 LilvNode* midi_MidiEvent;
158 LilvNode* rdfs_comment;
159 LilvNode* rdfs_label;
160 LilvNode* rdfs_range;
161 LilvNode* rsz_minimumSize;
162 LilvNode* time_Position;
164 LilvNode* ui_external;
165 LilvNode* ui_externalkx;
168 LilvNode* units_unit;
169 LilvNode* units_render;
170 LilvNode* units_midiNote;
171 LilvNode* patch_writable;
172 LilvNode* patch_Message;
173 #ifdef HAVE_LV2_1_2_0
174 LilvNode* bufz_powerOf2BlockLength;
175 LilvNode* bufz_fixedBlockLength;
176 LilvNode* bufz_nominalBlockLength;
177 LilvNode* bufz_coarseBlockLength;
180 #ifdef HAVE_LV2_1_10_0
182 LilvNode* atom_float;
183 LilvNode* atom_object; // new in 1.8
184 LilvNode* atom_vector;
187 LilvNode* lv2_noSampleAccurateCtrl;
188 LilvNode* auto_can_write_automatation; // lv2:optionalFeature
189 LilvNode* auto_automation_control; // atom:supports
190 LilvNode* auto_automation_controlled; // lv2:portProperty
191 LilvNode* auto_automation_controller; // lv2:portProperty
195 bool _bundle_checked;
198 static LV2World _world;
200 /* worker extension */
202 /** Called by the plugin to schedule non-RT work. */
203 static LV2_Worker_Status
204 work_schedule(LV2_Worker_Schedule_Handle handle,
208 return (((Worker*)handle)->schedule(size, data)
210 : LV2_WORKER_ERR_UNKNOWN);
213 /** Called by the plugin to respond to non-RT work. */
214 static LV2_Worker_Status
215 work_respond(LV2_Worker_Respond_Handle handle,
219 return (((Worker*)handle)->respond(size, data)
221 : LV2_WORKER_ERR_UNKNOWN);
225 /* inline display extension */
227 queue_draw (LV2_Inline_Display_Handle handle)
229 LV2Plugin* plugin = (LV2Plugin*)handle;
230 plugin->QueueDraw(); /* EMIT SIGNAL */
234 midnam_update (LV2_Midnam_Handle handle)
236 LV2Plugin* plugin = (LV2Plugin*)handle;
237 plugin->UpdateMidnam (); /* EMIT SIGNAL */
244 log_vprintf(LV2_Log_Handle /*handle*/,
250 const int ret = g_vasprintf(&str, fmt, args);
251 /* strip trailing whitespace */
252 while (strlen (str) > 0 && isspace (str[strlen (str) - 1])) {
253 str[strlen (str) - 1] = '\0';
255 if (strlen (str) == 0) {
259 if (type == URIMap::instance().urids.log_Error) {
260 error << str << endmsg;
261 } else if (type == URIMap::instance().urids.log_Warning) {
262 warning << str << endmsg;
263 } else if (type == URIMap::instance().urids.log_Note) {
264 info << str << endmsg;
265 } else if (type == URIMap::instance().urids.log_Trace) {
266 DEBUG_TRACE(DEBUG::LV2, str);
272 log_printf(LV2_Log_Handle handle,
274 const char* fmt, ...)
278 const int ret = log_vprintf(handle, type, fmt, args);
283 struct LV2Plugin::Impl {
284 Impl() : plugin(0), ui(0), ui_type(0), name(0), author(0), instance(0)
286 #ifdef HAVE_LV2_1_2_0
291 #ifdef HAVE_LV2_1_2_0
300 /** Find the LV2 input port with the given designation.
301 * If found, bufptrs[port_index] will be set to bufptr.
303 const LilvPort* designated_input (const char* uri, void** bufptrs[], void** bufptr);
305 const LilvPlugin* plugin;
307 const LilvNode* ui_type;
310 LilvInstance* instance;
311 const LV2_Worker_Interface* work_iface;
312 #ifdef HAVE_LV2_1_2_0
313 const LV2_Options_Interface* opts_iface;
316 LV2_Atom_Forge forge;
317 LV2_Atom_Forge ui_forge;
318 int32_t block_length;
319 #ifdef HAVE_LV2_1_2_0
320 LV2_Options_Option* options;
323 LV2_Inline_Display* queue_draw;
328 LV2Plugin::LV2Plugin (AudioEngine& engine,
330 const void* c_plugin,
332 : Plugin (engine, session)
337 , _state_worker(NULL)
339 , _patch_port_in_index((uint32_t)-1)
340 , _patch_port_out_index((uint32_t)-1)
341 , _uri_map(URIMap::instance())
342 , _no_sample_accurate_ctrl (false)
344 init(c_plugin, rate);
347 LV2Plugin::LV2Plugin (const LV2Plugin& other)
353 , _state_worker(NULL)
354 , _insert_id(other._insert_id)
355 , _patch_port_in_index((uint32_t)-1)
356 , _patch_port_out_index((uint32_t)-1)
357 , _uri_map(URIMap::instance())
358 , _no_sample_accurate_ctrl (false)
360 init(other._impl->plugin, other._sample_rate);
362 for (uint32_t i = 0; i < parameter_count(); ++i) {
363 _control_data[i] = other._shadow_data[i];
364 _shadow_data[i] = other._shadow_data[i];
369 LV2Plugin::init(const void* c_plugin, framecnt_t rate)
371 DEBUG_TRACE(DEBUG::LV2, "init\n");
373 _impl->plugin = (const LilvPlugin*)c_plugin;
375 _impl->ui_type = NULL;
380 _atom_ev_buffers = 0;
382 _bpm_control_port = 0;
383 _freewheel_control_port = 0;
384 _latency_control_port = 0;
385 _next_cycle_start = std::numeric_limits<framepos_t>::max();
386 _next_cycle_speed = 1.0;
387 _seq_size = _engine.raw_buffer_size(DataType::MIDI);
389 _was_activated = false;
390 _has_state_interface = false;
391 _can_write_automation = false;
393 _current_latency = 0;
394 _impl->block_length = _session.get_block_size();
396 _instance_access_feature.URI = "http://lv2plug.in/ns/ext/instance-access";
397 _data_access_feature.URI = "http://lv2plug.in/ns/ext/data-access";
398 _make_path_feature.URI = LV2_STATE__makePath;
399 _log_feature.URI = LV2_LOG__log;
400 _work_schedule_feature.URI = LV2_WORKER__schedule;
401 _work_schedule_feature.data = NULL;
402 _def_state_feature.URI = LV2_STATE_PREFIX "loadDefaultState"; // Post LV2-1.2.0
403 _def_state_feature.data = NULL;
405 const LilvPlugin* plugin = _impl->plugin;
407 LilvNode* state_iface_uri = lilv_new_uri(_world.world, LV2_STATE__interface);
408 LilvNode* state_uri = lilv_new_uri(_world.world, LV2_STATE_URI);
409 _has_state_interface =
410 // What plugins should have (lv2:extensionData state:Interface)
411 lilv_plugin_has_extension_data(plugin, state_iface_uri)
412 // What some outdated/incorrect ones have
413 || lilv_plugin_has_feature(plugin, state_uri);
414 lilv_node_free(state_uri);
415 lilv_node_free(state_iface_uri);
417 _features = (LV2_Feature**)calloc(13, sizeof(LV2_Feature*));
418 _features[0] = &_instance_access_feature;
419 _features[1] = &_data_access_feature;
420 _features[2] = &_make_path_feature;
421 _features[3] = _uri_map.uri_map_feature();
422 _features[4] = _uri_map.urid_map_feature();
423 _features[5] = _uri_map.urid_unmap_feature();
424 _features[6] = &_log_feature;
426 unsigned n_features = 7;
427 #ifdef HAVE_LV2_1_2_0
428 _features[n_features++] = &_def_state_feature;
431 lv2_atom_forge_init(&_impl->forge, _uri_map.urid_map());
432 lv2_atom_forge_init(&_impl->ui_forge, _uri_map.urid_map());
435 _impl->queue_draw = (LV2_Inline_Display*)
436 malloc (sizeof(LV2_Inline_Display));
437 _impl->queue_draw->handle = this;
438 _impl->queue_draw->queue_draw = queue_draw;
440 _queue_draw_feature.URI = LV2_INLINEDISPLAY__queue_draw;
441 _queue_draw_feature.data = _impl->queue_draw;
442 _features[n_features++] = &_queue_draw_feature;
444 _impl->midnam = (LV2_Midnam*)
445 malloc (sizeof(LV2_Midnam));
446 _impl->midnam->handle = this;
447 _impl->midnam->update = midnam_update;
449 _midnam_feature.URI = LV2_MIDNAM__update;
450 _midnam_feature.data = _impl->midnam;
451 _features[n_features++] = &_midnam_feature;
454 #ifdef HAVE_LV2_1_2_0
455 LV2_URID atom_Int = _uri_map.uri_to_id(LV2_ATOM__Int);
456 static const int32_t _min_block_length = 1; // may happen during split-cycles
457 static const int32_t _max_block_length = 8192; // max possible (with all engines and during export)
458 /* Consider updating max-block-size whenever the buffersize changes.
459 * It requires re-instantiating the plugin (which is a non-realtime operation),
460 * so it should be done lightly and only for plugins that require it.
462 * given that the block-size can change at any time (split-cycles) ardour currently
463 * does not support plugins that require bufz_fixedBlockLength.
465 LV2_Options_Option options[] = {
466 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__minBlockLength),
467 sizeof(int32_t), atom_Int, &_min_block_length },
468 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__maxBlockLength),
469 sizeof(int32_t), atom_Int, &_max_block_length },
470 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id(LV2_BUF_SIZE__sequenceSize),
471 sizeof(int32_t), atom_Int, &_seq_size },
472 { LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id("http://lv2plug.in/ns/ext/buf-size#nominalBlockLength"),
473 sizeof(int32_t), atom_Int, &_impl->block_length },
474 { LV2_OPTIONS_INSTANCE, 0, 0, 0, 0, NULL }
477 _impl->options = (LV2_Options_Option*) malloc (sizeof (options));
478 memcpy ((void*) _impl->options, (void*) options, sizeof (options));
480 _options_feature.URI = LV2_OPTIONS__options;
481 _options_feature.data = _impl->options;
482 _features[n_features++] = &_options_feature;
485 LV2_State_Make_Path* make_path = (LV2_State_Make_Path*)malloc(
486 sizeof(LV2_State_Make_Path));
487 make_path->handle = this;
488 make_path->path = &lv2_state_make_path;
489 _make_path_feature.data = make_path;
491 LV2_Log_Log* log = (LV2_Log_Log*)malloc(sizeof(LV2_Log_Log));
493 log->printf = &log_printf;
494 log->vprintf = &log_vprintf;
495 _log_feature.data = log;
497 const size_t ring_size = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
498 LilvNode* worker_schedule = lilv_new_uri(_world.world, LV2_WORKER__schedule);
499 if (lilv_plugin_has_feature(plugin, worker_schedule)) {
500 LV2_Worker_Schedule* schedule = (LV2_Worker_Schedule*)malloc(
501 sizeof(LV2_Worker_Schedule));
502 _worker = new Worker(this, ring_size);
503 schedule->handle = _worker;
504 schedule->schedule_work = work_schedule;
505 _work_schedule_feature.data = schedule;
506 _features[n_features++] = &_work_schedule_feature;
508 lilv_node_free(worker_schedule);
510 if (_has_state_interface) {
511 // Create a non-threaded worker for use by state restore
512 _state_worker = new Worker(this, ring_size, false);
515 _impl->instance = lilv_plugin_instantiate(plugin, rate, _features);
516 _impl->name = lilv_plugin_get_name(plugin);
517 _impl->author = lilv_plugin_get_author_name(plugin);
519 if (_impl->instance == 0) {
520 error << _("LV2: Failed to instantiate plugin ") << uri() << endmsg;
521 throw failed_constructor();
524 _instance_access_feature.data = (void*)_impl->instance->lv2_handle;
525 _data_access_extension_data.extension_data = _impl->instance->lv2_descriptor->extension_data;
526 _data_access_feature.data = &_data_access_extension_data;
528 LilvNode* worker_iface_uri = lilv_new_uri(_world.world, LV2_WORKER__interface);
529 if (lilv_plugin_has_extension_data(plugin, worker_iface_uri)) {
530 _impl->work_iface = (const LV2_Worker_Interface*)extension_data(
531 LV2_WORKER__interface);
533 lilv_node_free(worker_iface_uri);
536 #ifdef HAVE_LV2_1_2_0
537 LilvNode* options_iface_uri = lilv_new_uri(_world.world, LV2_OPTIONS__interface);
538 if (lilv_plugin_has_extension_data(plugin, options_iface_uri)) {
539 _impl->opts_iface = (const LV2_Options_Interface*)extension_data(
540 LV2_OPTIONS__interface);
542 lilv_node_free(options_iface_uri);
546 _display_interface = (const LV2_Inline_Display_Interface*)
547 extension_data (LV2_INLINEDISPLAY__interface);
549 _midname_interface = (const LV2_Midnam_Interface*)
550 extension_data (LV2_MIDNAM__interface);
551 if (_midname_interface) {
556 if (lilv_plugin_has_feature(plugin, _world.lv2_inPlaceBroken)) {
557 error << string_compose(
558 _("LV2: \"%1\" cannot be used, since it cannot do inplace processing."),
559 lilv_node_as_string(_impl->name)) << endmsg;
560 lilv_node_free(_impl->name);
561 lilv_node_free(_impl->author);
562 throw failed_constructor();
565 #ifdef HAVE_LV2_1_2_0
566 LilvNodes *required_features = lilv_plugin_get_required_features (plugin);
567 if (lilv_nodes_contains (required_features, _world.bufz_powerOf2BlockLength) ||
568 lilv_nodes_contains (required_features, _world.bufz_fixedBlockLength)
570 error << string_compose(
571 _("LV2: \"%1\" buffer-size requirements cannot be satisfied."),
572 lilv_node_as_string(_impl->name)) << endmsg;
573 lilv_node_free(_impl->name);
574 lilv_node_free(_impl->author);
575 lilv_nodes_free(required_features);
576 throw failed_constructor();
578 lilv_nodes_free(required_features);
581 LilvNodes* optional_features = lilv_plugin_get_optional_features (plugin);
582 #ifdef HAVE_LV2_1_2_0
583 if (lilv_nodes_contains (optional_features, _world.bufz_coarseBlockLength)) {
584 _no_sample_accurate_ctrl = true;
588 if (lilv_nodes_contains (optional_features, _world.lv2_noSampleAccurateCtrl)) {
589 /* deprecated 2016-Sep-18 in favor of bufz_coarseBlockLength */
590 _no_sample_accurate_ctrl = true;
592 if (lilv_nodes_contains (optional_features, _world.auto_can_write_automatation)) {
593 _can_write_automation = true;
595 lilv_nodes_free(optional_features);
598 #ifdef HAVE_LILV_0_16_0
599 // Load default state
601 /* immediately schedule any work,
602 * so that state restore later will not find a busy
603 * worker. latency_compute_run() flushes any replies
605 _worker->set_synchronous(true);
607 LilvState* state = lilv_state_new_from_world(
608 _world.world, _uri_map.urid_map(), lilv_plugin_get_uri(_impl->plugin));
609 if (state && _has_state_interface) {
610 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
612 lilv_state_free(state);
617 const uint32_t num_ports = this->num_ports();
618 for (uint32_t i = 0; i < num_ports; ++i) {
619 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, i);
621 size_t minimumSize = 0;
623 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_OutputPort)) {
624 flags |= PORT_OUTPUT;
625 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_InputPort)) {
628 error << string_compose(
629 "LV2: \"%1\" port %2 is neither input nor output",
630 lilv_node_as_string(_impl->name), i) << endmsg;
631 throw failed_constructor();
634 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_ControlPort)) {
635 flags |= PORT_CONTROL;
636 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_AudioPort)) {
638 } else if (lilv_port_is_a(_impl->plugin, port, _world.ev_EventPort)) {
640 flags |= PORT_MIDI; // We assume old event API ports are for MIDI
641 } else if (lilv_port_is_a(_impl->plugin, port, _world.atom_AtomPort)) {
642 LilvNodes* buffer_types = lilv_port_get_value(
643 _impl->plugin, port, _world.atom_bufferType);
644 LilvNodes* atom_supports = lilv_port_get_value(
645 _impl->plugin, port, _world.atom_supports);
647 if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)) {
648 flags |= PORT_SEQUENCE;
649 if (lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
652 if (lilv_nodes_contains(atom_supports, _world.time_Position)) {
653 flags |= PORT_POSITION;
656 if (lilv_nodes_contains(atom_supports, _world.auto_automation_control)) {
657 flags |= PORT_AUTOCTRL;
660 if (lilv_nodes_contains(atom_supports, _world.patch_Message)) {
661 flags |= PORT_PATCHMSG;
662 if (flags & PORT_INPUT) {
663 _patch_port_in_index = i;
665 _patch_port_out_index = i;
669 LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
670 LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
671 if (min_size && lilv_node_is_int(min_size)) {
672 minimumSize = lilv_node_as_int(min_size);
674 lilv_nodes_free(min_size_v);
675 lilv_nodes_free(buffer_types);
676 lilv_nodes_free(atom_supports);
678 error << string_compose(
679 "LV2: \"%1\" port %2 has no known data type",
680 lilv_node_as_string(_impl->name), i) << endmsg;
681 throw failed_constructor();
684 if ((flags & PORT_INPUT) && (flags & PORT_CONTROL)) {
685 if (lilv_port_has_property(_impl->plugin, port, _world.ext_causesArtifacts)) {
686 flags |= PORT_NOAUTO;
688 if (lilv_port_has_property(_impl->plugin, port, _world.ext_notAutomatic)) {
689 flags |= PORT_NOAUTO;
691 if (lilv_port_has_property(_impl->plugin, port, _world.ext_expensive)) {
692 flags |= PORT_NOAUTO;
696 if (lilv_port_has_property(_impl->plugin, port, _world.auto_automation_controlled)) {
697 if ((flags & PORT_INPUT) && (flags & PORT_CONTROL)) {
698 flags |= PORT_CTRLED;
701 if (lilv_port_has_property(_impl->plugin, port, _world.auto_automation_controller)) {
702 if ((flags & PORT_INPUT) && (flags & PORT_CONTROL)) {
703 flags |= PORT_CTRLER;
708 _port_flags.push_back(flags);
709 _port_minimumSize.push_back(minimumSize);
710 DEBUG_TRACE(DEBUG::LV2, string_compose("port %1 buffer %2 bytes\n", i, minimumSize));
713 _control_data = new float[num_ports];
714 _shadow_data = new float[num_ports];
715 _defaults = new float[num_ports];
716 _ev_buffers = new LV2_Evbuf*[num_ports];
717 memset(_ev_buffers, 0, sizeof(LV2_Evbuf*) * num_ports);
719 const bool latent = lilv_plugin_has_latency(plugin);
720 const uint32_t latency_index = (latent)
721 ? lilv_plugin_get_latency_port_index(plugin)
724 // Build an array of pointers to special parameter buffers
725 void*** params = new void**[num_ports];
726 for (uint32_t i = 0; i < num_ports; ++i) {
729 _impl->designated_input (LV2_TIME__beatsPerMinute, params, (void**)&_bpm_control_port);
730 _impl->designated_input (LV2_CORE__freeWheeling, params, (void**)&_freewheel_control_port);
732 for (uint32_t i = 0; i < num_ports; ++i) {
733 const LilvPort* port = lilv_plugin_get_port_by_index(plugin, i);
734 const LilvNode* sym = lilv_port_get_symbol(plugin, port);
736 // Store index in map so we can look up index by symbol
737 _port_indices.insert(std::make_pair(lilv_node_as_string(sym), i));
739 // Get range and default value if applicable
740 if (parameter_is_control(i)) {
742 lilv_port_get_range(plugin, port, &def, NULL, NULL);
743 _defaults[i] = def ? lilv_node_as_float(def) : 0.0f;
744 if (lilv_port_has_property (plugin, port, _world.lv2_sampleRate)) {
745 _defaults[i] *= _session.frame_rate ();
749 lilv_instance_connect_port(_impl->instance, i, &_control_data[i]);
751 if (latent && i == latency_index) {
753 lilv_port_get_range(_impl->plugin, port, NULL, NULL, &max);
754 _max_latency = max ? lilv_node_as_float(max) : .02 * _sample_rate;
755 _latency_control_port = &_control_data[i];
756 *_latency_control_port = 0;
759 if (parameter_is_input(i)) {
760 _shadow_data[i] = default_value(i);
762 *params[i] = (void*)&_shadow_data[i];
772 LilvUIs* uis = lilv_plugin_get_uis(plugin);
773 if (lilv_uis_size(uis) > 0) {
775 // Look for embeddable UI
776 LILV_FOREACH(uis, u, uis) {
777 const LilvUI* this_ui = lilv_uis_get(uis, u);
778 const LilvNode* this_ui_type = NULL;
779 if (lilv_ui_is_supported(this_ui,
783 // TODO: Multiple UI support
785 _impl->ui_type = this_ui_type;
790 // Look for Gtk native UI
791 LILV_FOREACH(uis, i, uis) {
792 const LilvUI* ui = lilv_uis_get(uis, i);
793 if (lilv_ui_is_a(ui, _world.ui_GtkUI)) {
795 _impl->ui_type = _world.ui_GtkUI;
801 // If Gtk UI is not available, try to find external UI
803 LILV_FOREACH(uis, i, uis) {
804 const LilvUI* ui = lilv_uis_get(uis, i);
805 if (lilv_ui_is_a(ui, _world.ui_externalkx)) {
807 _impl->ui_type = _world.ui_external;
810 if (lilv_ui_is_a(ui, _world.ui_external)) {
812 _impl->ui_type = _world.ui_external;
818 load_supported_properties(_property_descriptors);
819 allocate_atom_event_buffers();
820 latency_compute_run();
824 LV2Plugin::set_block_size (pframes_t nframes)
826 #ifdef HAVE_LV2_1_2_0
827 if (_impl->opts_iface) {
828 LV2_URID atom_Int = _uri_map.uri_to_id(LV2_ATOM__Int);
829 _impl->block_length = nframes;
830 LV2_Options_Option block_size_option = {
831 LV2_OPTIONS_INSTANCE, 0, _uri_map.uri_to_id ("http://lv2plug.in/ns/ext/buf-size#nominalBlockLength"),
832 sizeof(int32_t), atom_Int, (void*)&_impl->block_length
834 _impl->opts_iface->set (_impl->instance->lv2_handle, &block_size_option);
841 LV2Plugin::requires_fixed_sized_buffers () const
843 /* This controls if Ardour will split the plugin's run()
844 * on automation events in order to pass sample-accurate automation
845 * via standard control-ports.
847 * When returning true Ardour will *not* sub-divide the process-cycle.
848 * Automation events that happen between cycle-start and cycle-end will be
849 * ignored (ctrl values are interpolated to cycle-start).
850 * NB. Atom Sequences are still sample accurate.
852 * Note: This does not guarantee a fixed block-size.
853 * e.g The process cycle may be split when looping, also
854 * the period-size may change any time: see set_block_size()
856 if (get_info()->n_inputs.n_midi() > 0) {
857 /* we don't yet implement midi buffer offsets (for split cycles).
858 * Also connect_and_run() also uses _session.transport_frame() directly
859 * (for BBT) which is not offset for plugin cycle split.
863 return _no_sample_accurate_ctrl;
866 LV2Plugin::~LV2Plugin ()
868 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 destroy\n", name()));
875 std::stringstream ss;
878 MIDI::Name::MidiPatchManager::instance().remove_custom_midnam (ss.str());
882 lilv_instance_free(_impl->instance);
883 lilv_state_free(_impl->state);
884 lilv_node_free(_impl->name);
885 lilv_node_free(_impl->author);
886 #ifdef HAVE_LV2_1_2_0
887 free(_impl->options);
890 free(_impl->queue_draw);
895 free(_log_feature.data);
896 free(_make_path_feature.data);
897 free(_work_schedule_feature.data);
902 delete _state_worker;
904 if (_atom_ev_buffers) {
905 LV2_Evbuf** b = _atom_ev_buffers;
910 free(_atom_ev_buffers);
913 delete [] _control_data;
914 delete [] _shadow_data;
916 delete [] _ev_buffers;
921 LV2Plugin::is_external_ui() const
926 return lilv_ui_is_a(_impl->ui, _world.ui_external) || lilv_ui_is_a(_impl->ui, _world.ui_externalkx);
930 LV2Plugin::is_external_kx() const
935 return lilv_ui_is_a(_impl->ui, _world.ui_externalkx);
939 LV2Plugin::ui_is_resizable () const
941 const LilvNode* s = lilv_ui_get_uri(_impl->ui);
942 LilvNode* p = lilv_new_uri(_world.world, LV2_CORE__optionalFeature);
943 LilvNode* fs = lilv_new_uri(_world.world, LV2_UI__fixedSize);
944 LilvNode* nrs = lilv_new_uri(_world.world, LV2_UI__noUserResize);
946 LilvNodes* fs_matches = lilv_world_find_nodes(_world.world, s, p, fs);
947 LilvNodes* nrs_matches = lilv_world_find_nodes(_world.world, s, p, nrs);
949 lilv_nodes_free(nrs_matches);
950 lilv_nodes_free(fs_matches);
955 return !fs_matches && !nrs_matches;
960 LV2Plugin::has_inline_display () {
961 return _display_interface ? true : false;
964 Plugin::Display_Image_Surface*
965 LV2Plugin::render_inline_display (uint32_t w, uint32_t h) {
966 if (_display_interface) {
967 /* Plugin::Display_Image_Surface is identical to
968 * LV2_Inline_Display_Image_Surface */
969 return (Plugin::Display_Image_Surface*) _display_interface->render ((void*)_impl->instance->lv2_handle, w, h);
975 LV2Plugin::has_midnam () {
976 return _midname_interface ? true : false;
980 LV2Plugin::read_midnam () {
982 if (!_midname_interface) {
985 char* midnam = _midname_interface->midnam ((void*)_impl->instance->lv2_handle);
987 std::stringstream ss;
990 rv = MIDI::Name::MidiPatchManager::instance().update_custom_midnam (ss.str(), midnam);
994 info << string_compose(_("LV2: update midnam for plugin '%1'"), name ()) << endmsg;
996 warning << string_compose(_("LV2: Failed to parse midnam of plugin '%1'"), name ()) << endmsg;
999 _midname_interface->free (midnam);
1004 LV2Plugin::midnam_model () {
1006 if (!_midname_interface) {
1009 char* model = _midname_interface->model ((void*)_impl->instance->lv2_handle);
1013 _midname_interface->free (model);
1019 LV2Plugin::unique_id() const
1021 return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
1025 LV2Plugin::uri() const
1027 return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
1031 LV2Plugin::label() const
1033 return lilv_node_as_string(_impl->name);
1037 LV2Plugin::name() const
1039 return lilv_node_as_string(_impl->name);
1043 LV2Plugin::maker() const
1045 return _impl->author ? lilv_node_as_string (_impl->author) : "Unknown";
1049 LV2Plugin::num_ports() const
1051 return lilv_plugin_get_num_ports(_impl->plugin);
1055 LV2Plugin::parameter_count() const
1057 return lilv_plugin_get_num_ports(_impl->plugin);
1061 LV2Plugin::default_value(uint32_t port)
1063 return _defaults[port];
1067 LV2Plugin::port_symbol(uint32_t index) const
1069 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, index);
1071 error << name() << ": Invalid port index " << index << endmsg;
1074 const LilvNode* sym = lilv_port_get_symbol(_impl->plugin, port);
1075 return lilv_node_as_string(sym);
1079 LV2Plugin::port_index (const char* symbol) const
1081 const map<string, uint32_t>::const_iterator i = _port_indices.find(symbol);
1082 if (i != _port_indices.end()) {
1085 warning << string_compose(_("LV2: Unknown port %1"), symbol) << endmsg;
1086 return (uint32_t)-1;
1091 LV2Plugin::set_parameter(uint32_t which, float val)
1093 DEBUG_TRACE(DEBUG::LV2, string_compose(
1094 "%1 set parameter %2 to %3\n", name(), which, val));
1096 if (which < lilv_plugin_get_num_ports(_impl->plugin)) {
1097 if (get_parameter (which) == val) {
1101 _shadow_data[which] = val;
1103 warning << string_compose(
1104 _("Illegal parameter number used with plugin \"%1\". "
1105 "This is a bug in either %2 or the LV2 plugin <%3>"),
1106 name(), PROGRAM_NAME, unique_id()) << endmsg;
1109 Plugin::set_parameter(which, val);
1113 LV2Plugin::get_parameter(uint32_t which) const
1115 if (parameter_is_input(which)) {
1116 return (float)_shadow_data[which];
1118 return (float)_control_data[which];
1124 LV2Plugin::get_docs() const
1126 LilvNodes* comments = lilv_plugin_get_value(_impl->plugin, _world.rdfs_comment);
1128 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
1129 lilv_nodes_free(comments);
1137 LV2Plugin::get_parameter_docs(uint32_t which) const
1139 LilvNodes* comments = lilv_port_get_value(
1141 lilv_plugin_get_port_by_index(_impl->plugin, which),
1142 _world.rdfs_comment);
1145 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
1146 lilv_nodes_free(comments);
1154 LV2Plugin::get_layout (uint32_t which, UILayoutHint& h) const
1156 /// TODO lookup port-properties
1157 if (unique_id () != "urn:ardour:a-eq") {
1162 case 0: h.x0 = 0; h.x1 = 1; h.y0 = 2; h.y1 = 3; break; // Frequency L
1163 case 1: h.x0 = 0; h.x1 = 1; h.y0 = 0; h.y1 = 1; break; // Gain L
1164 case 17: h.x0 = 0; h.x1 = 1; h.y0 = 5; h.y1 = 6; break; // enable L
1166 case 2: h.x0 = 1; h.x1 = 3; h.y0 = 2; h.y1 = 3; break; // Frequency 1
1167 case 3: h.x0 = 1; h.x1 = 3; h.y0 = 0; h.y1 = 1; break; // Gain 1
1168 case 4: h.x0 = 1; h.x1 = 3; h.y0 = 1; h.y1 = 2; break; // Bandwidth 1
1169 case 18: h.x0 = 1; h.x1 = 4; h.y0 = 5; h.y1 = 6; break; // enable 1
1171 case 5: h.x0 = 4; h.x1 = 6; h.y0 = 2; h.y1 = 3; break; // Frequency 2
1172 case 6: h.x0 = 4; h.x1 = 6; h.y0 = 0; h.y1 = 1; break; // Gain 2
1173 case 7: h.x0 = 4; h.x1 = 6; h.y0 = 1; h.y1 = 2; break; // Bandwidth 2
1174 case 19: h.x0 = 4; h.x1 = 7; h.y0 = 5; h.y1 = 6; break; // enable 2
1176 case 8: h.x0 = 7; h.x1 = 9; h.y0 = 2; h.y1 = 3; break; // Frequency 3
1177 case 9: h.x0 = 7; h.x1 = 9; h.y0 = 0; h.y1 = 1; break; // Gain 3
1178 case 10: h.x0 = 7; h.x1 = 9; h.y0 = 1; h.y1 = 2; break; // Bandwidth 3
1179 case 20: h.x0 = 7; h.x1 = 10; h.y0 = 5; h.y1 = 6; break; // enable 3
1181 case 11: h.x0 = 10; h.x1 = 12; h.y0 = 2; h.y1 = 3; break; // Frequency 4
1182 case 12: h.x0 = 10; h.x1 = 12; h.y0 = 0; h.y1 = 1; break; // Gain 4
1183 case 13: h.x0 = 10; h.x1 = 12; h.y0 = 1; h.y1 = 2; break; // Bandwidth 4
1184 case 21: h.x0 = 10; h.x1 = 13; h.y0 = 5; h.y1 = 6; break; // enable 4
1186 case 14: h.x0 = 13; h.x1 = 14; h.y0 = 2; h.y1 = 3; break; // Frequency H
1187 case 15: h.x0 = 13; h.x1 = 14; h.y0 = 0; h.y1 = 1; break; // Gain H
1188 case 22: h.x0 = 13; h.x1 = 14; h.y0 = 5; h.y1 = 6; break; // enable H
1190 case 16: h.x0 = 14; h.x1 = 15; h.y0 = 1; h.y1 = 3; break; // Master Gain
1191 case 23: h.x0 = 14; h.x1 = 15; h.y0 = 5; h.y1 = 6; break; // Master Enable
1199 LV2Plugin::nth_parameter(uint32_t n, bool& ok) const
1202 for (uint32_t c = 0, x = 0; x < lilv_plugin_get_num_ports(_impl->plugin); ++x) {
1203 if (parameter_is_control(x)) {
1215 LV2Plugin::extension_data(const char* uri) const
1217 return lilv_instance_get_extension_data(_impl->instance, uri);
1221 LV2Plugin::c_plugin()
1223 return _impl->plugin;
1229 return (const void*)_impl->ui;
1233 LV2Plugin::c_ui_type()
1235 return (const void*)_impl->ui_type;
1238 /** Directory for all plugin state. */
1240 LV2Plugin::plugin_dir() const
1242 if (!_plugin_state_dir.empty ()){
1243 return Glib::build_filename(_plugin_state_dir, _insert_id.to_s());
1245 return Glib::build_filename(_session.plugins_dir(), _insert_id.to_s());
1249 /** Directory for files created by the plugin (except during save). */
1251 LV2Plugin::scratch_dir() const
1253 return Glib::build_filename(plugin_dir(), "scratch");
1256 /** Directory for snapshots of files in the scratch directory. */
1258 LV2Plugin::file_dir() const
1260 return Glib::build_filename(plugin_dir(), "files");
1263 /** Directory to save state snapshot version @c num into. */
1265 LV2Plugin::state_dir(unsigned num) const
1267 return Glib::build_filename(plugin_dir(), string("state") + PBD::to_string (num));
1270 /** Implementation of state:makePath for files created at instantiation time.
1271 * Note this is not used for files created at save time (Lilv deals with that).
1274 LV2Plugin::lv2_state_make_path(LV2_State_Make_Path_Handle handle,
1277 LV2Plugin* me = (LV2Plugin*)handle;
1278 if (me->_insert_id == PBD::ID("0")) {
1279 warning << string_compose(
1280 "File path \"%1\" requested but LV2 %2 has no insert ID",
1281 path, me->name()) << endmsg;
1282 return g_strdup(path);
1285 const std::string abs_path = Glib::build_filename(me->scratch_dir(), path);
1286 const std::string dirname = Glib::path_get_dirname(abs_path);
1287 g_mkdir_with_parents(dirname.c_str(), 0744);
1289 DEBUG_TRACE(DEBUG::LV2, string_compose("new file path %1 => %2\n",
1292 return g_strndup(abs_path.c_str(), abs_path.length());
1296 LV2Plugin::add_state(XMLNode* root) const
1298 assert(_insert_id != PBD::ID("0"));
1303 for (uint32_t i = 0; i < parameter_count(); ++i) {
1304 if (parameter_is_input(i) && parameter_is_control(i)) {
1305 child = new XMLNode("Port");
1306 child->set_property("symbol", port_symbol(i));
1307 child->set_property("value", _shadow_data[i]);
1308 root->add_child_nocopy(*child);
1312 if (!_plugin_state_dir.empty()) {
1313 root->set_property("template-dir", _plugin_state_dir);
1316 if (_has_state_interface) {
1317 // Provisionally increment state version and create directory
1318 const std::string new_dir = state_dir(++_state_version);
1319 // and keep track of it (for templates & archive)
1320 unsigned int saved_state = _state_version;;
1321 g_mkdir_with_parents(new_dir.c_str(), 0744);
1323 LilvState* state = lilv_state_new_from_instance(
1326 _uri_map.urid_map(),
1327 scratch_dir().c_str(),
1329 _session.externals_dir().c_str(),
1332 const_cast<LV2Plugin*>(this),
1336 if (!_plugin_state_dir.empty() || force_state_save
1338 || !lilv_state_equals(state, _impl->state)) {
1339 lilv_state_save(_world.world,
1340 _uri_map.urid_map(),
1341 _uri_map.urid_unmap(),
1347 if (force_state_save) {
1348 // archive or save-as
1349 lilv_state_free(state);
1352 else if (_plugin_state_dir.empty()) {
1353 // normal session save
1354 lilv_state_free(_impl->state);
1355 _impl->state = state;
1357 // template save (dedicated state-dir)
1358 lilv_state_free(state);
1362 // State is identical, decrement version and nuke directory
1363 lilv_state_free(state);
1364 PBD::remove_directory(new_dir);
1366 saved_state = _state_version;
1369 root->set_property("state-dir", string("state") + PBD::to_string (saved_state));
1373 // TODO: Once we can rely on lilv 0.16.0, lilv_world_get can replace this
1375 get_value(LilvWorld* world, const LilvNode* subject, const LilvNode* predicate)
1377 LilvNodes* vs = lilv_world_find_nodes(world, subject, predicate, NULL);
1379 LilvNode* node = lilv_node_duplicate(lilv_nodes_get_first(vs));
1380 lilv_nodes_free(vs);
1387 LV2Plugin::find_presets()
1389 LilvNode* lv2_appliesTo = lilv_new_uri(_world.world, LV2_CORE__appliesTo);
1390 LilvNode* pset_Preset = lilv_new_uri(_world.world, LV2_PRESETS__Preset);
1391 LilvNode* rdfs_label = lilv_new_uri(_world.world, LILV_NS_RDFS "label");
1393 LilvNodes* presets = lilv_plugin_get_related(_impl->plugin, pset_Preset);
1394 LILV_FOREACH(nodes, i, presets) {
1395 const LilvNode* preset = lilv_nodes_get(presets, i);
1396 lilv_world_load_resource(_world.world, preset);
1397 LilvNode* name = get_value(_world.world, preset, rdfs_label);
1398 bool userpreset = true; // TODO
1400 _presets.insert(std::make_pair(lilv_node_as_string(preset),
1401 Plugin::PresetRecord(
1402 lilv_node_as_string(preset),
1403 lilv_node_as_string(name),
1405 lilv_node_free(name);
1407 warning << string_compose(
1408 _("Plugin \"%1\" preset \"%2\" is missing a label\n"),
1409 lilv_node_as_string(lilv_plugin_get_uri(_impl->plugin)),
1410 lilv_node_as_string(preset)) << endmsg;
1413 lilv_nodes_free(presets);
1415 lilv_node_free(rdfs_label);
1416 lilv_node_free(pset_Preset);
1417 lilv_node_free(lv2_appliesTo);
1421 set_port_value(const char* port_symbol,
1427 LV2Plugin* self = (LV2Plugin*)user_data;
1428 if (type != 0 && type != URIMap::instance().urids.atom_Float) {
1429 return; // TODO: Support non-float ports
1432 const uint32_t port_index = self->port_index(port_symbol);
1433 if (port_index != (uint32_t)-1) {
1434 self->set_parameter(port_index, *(const float*)value);
1435 self->PresetPortSetValue (port_index, *(const float*)value); /* EMIT SIGNAL */
1440 LV2Plugin::load_preset(PresetRecord r)
1442 LilvWorld* world = _world.world;
1443 LilvNode* pset = lilv_new_uri(world, r.uri.c_str());
1444 LilvState* state = lilv_state_new_from_world(world, _uri_map.urid_map(), pset);
1446 const LV2_Feature* state_features[2] = { NULL, NULL };
1447 LV2_Worker_Schedule schedule = { _state_worker, work_schedule };
1448 const LV2_Feature state_sched_feature = { LV2_WORKER__schedule, &schedule };
1449 if (_state_worker) {
1450 state_features[0] = &state_sched_feature;
1454 lilv_state_restore(state, _impl->instance, set_port_value, this, 0, state_features);
1455 lilv_state_free(state);
1456 Plugin::load_preset(r);
1459 lilv_node_free(pset);
1464 ARDOUR::lv2plugin_get_port_value(const char* port_symbol,
1469 LV2Plugin *plugin = (LV2Plugin *) user_data;
1471 uint32_t index = plugin->port_index(port_symbol);
1472 if (index != (uint32_t) -1) {
1473 if (plugin->parameter_is_input(index) && plugin->parameter_is_control(index)) {
1475 *size = sizeof(float);
1476 *type = plugin->_uri_map.uri_to_id(LV2_ATOM__Float);
1477 value = &plugin->_shadow_data[index];
1489 LV2Plugin::do_save_preset(string name)
1491 LilvNode* plug_name = lilv_plugin_get_name(_impl->plugin);
1492 const string prefix = legalize_for_uri(lilv_node_as_string(plug_name));
1493 const string base_name = legalize_for_uri(name);
1494 const string file_name = base_name + ".ttl";
1495 const string bundle = Glib::build_filename(
1496 Glib::get_home_dir(),
1497 Glib::build_filename(".lv2", prefix + "_" + base_name + ".lv2"));
1499 #ifdef HAVE_LILV_0_21_3
1500 /* delete reference to old preset (if any) */
1501 const PresetRecord* r = preset_by_label(name);
1503 LilvNode* pset = lilv_new_uri (_world.world, r->uri.c_str());
1505 lilv_world_unload_resource (_world.world, pset);
1506 lilv_node_free(pset);
1511 LilvState* state = lilv_state_new_from_instance(
1514 _uri_map.urid_map(),
1515 scratch_dir().c_str(), // file_dir
1516 bundle.c_str(), // copy_dir
1517 bundle.c_str(), // link_dir
1518 bundle.c_str(), // save_dir
1519 lv2plugin_get_port_value, // get_value
1520 (void*)this, // user_data
1521 LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE, // flags
1522 _features // features
1525 lilv_state_set_label(state, name.c_str());
1527 _world.world, // world
1528 _uri_map.urid_map(), // map
1529 _uri_map.urid_unmap(), // unmap
1531 NULL, // uri (NULL = use file URI)
1532 bundle.c_str(), // dir
1533 file_name.c_str() // filename
1536 lilv_state_free(state);
1538 std::string uri = Glib::filename_to_uri(Glib::build_filename(bundle, file_name));
1539 LilvNode *node_bundle = lilv_new_uri(_world.world, Glib::filename_to_uri(Glib::build_filename(bundle, "/")).c_str());
1540 LilvNode *node_preset = lilv_new_uri(_world.world, uri.c_str());
1541 #ifdef HAVE_LILV_0_21_3
1542 lilv_world_unload_resource(_world.world, node_preset);
1543 lilv_world_unload_bundle(_world.world, node_bundle);
1545 lilv_world_load_bundle(_world.world, node_bundle);
1546 lilv_world_load_resource(_world.world, node_preset);
1547 lilv_node_free(node_bundle);
1548 lilv_node_free(node_preset);
1549 lilv_node_free(plug_name);
1554 LV2Plugin::do_remove_preset(string name)
1556 #ifdef HAVE_LILV_0_21_3
1557 /* Look up preset record by label (FIXME: ick, label as ID) */
1558 const PresetRecord* r = preset_by_label(name);
1563 /* Load a LilvState for the preset. */
1564 LilvWorld* world = _world.world;
1565 LilvNode* pset = lilv_new_uri(world, r->uri.c_str());
1566 LilvState* state = lilv_state_new_from_world(world, _uri_map.urid_map(), pset);
1568 lilv_node_free(pset);
1572 /* Unload preset from world. */
1573 lilv_world_unload_resource(world, pset);
1575 /* Delete it from the file system. This will remove the preset file and the entry
1576 from the manifest. If this results in an empty manifest (i.e. the
1577 preset is the only thing in the bundle), then the bundle is removed. */
1578 lilv_state_delete(world, state);
1580 lilv_state_free(state);
1581 lilv_node_free(pset);
1583 /* Without lilv_state_delete(), we could delete the preset file, but this
1584 would leave a broken bundle/manifest around, so the preset would still
1585 be visible, but broken. Naively deleting a bundle is too dangerous, so
1586 we simply do not support preset deletion with older Lilv */
1590 LV2Plugin::has_editor() const
1592 return _impl->ui != NULL;
1596 LV2Plugin::has_message_output() const
1598 for (uint32_t i = 0; i < num_ports(); ++i) {
1599 if ((_port_flags[i] & PORT_SEQUENCE) &&
1600 (_port_flags[i] & PORT_OUTPUT)) {
1608 LV2Plugin::write_to(RingBuffer<uint8_t>* dest,
1612 const uint8_t* body)
1614 const uint32_t buf_size = sizeof(UIMessage) + size;
1615 vector<uint8_t> buf(buf_size);
1617 UIMessage* msg = (UIMessage*)&buf[0];
1619 msg->protocol = protocol;
1621 memcpy(msg + 1, body, size);
1623 return (dest->write(&buf[0], buf_size) == buf_size);
1627 LV2Plugin::write_from_ui(uint32_t index,
1630 const uint8_t* body)
1633 size_t rbs = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
1634 /* buffer data communication from plugin UI to plugin instance.
1635 * this buffer needs to potentially hold
1636 * (port's minimumSize) * (audio-periods) / (UI-periods)
1639 * e.g 48kSPS / 128fpp -> audio-periods = 375 Hz
1640 * ui-periods = 25 Hz (SuperRapidScreenUpdate)
1641 * default minimumSize = 32K (see LV2Plugin::allocate_atom_event_buffers()
1643 * it is NOT safe to overflow (msg.size will be misinterpreted)
1645 uint32_t bufsiz = 32768;
1646 if (_atom_ev_buffers && _atom_ev_buffers[0]) {
1647 bufsiz = lv2_evbuf_get_capacity(_atom_ev_buffers[0]);
1649 int fact = ceilf(_session.frame_rate () / 3000.f);
1650 rbs = max((size_t) bufsiz * std::max (8, fact), rbs);
1651 _from_ui = new RingBuffer<uint8_t>(rbs);
1654 if (!write_to(_from_ui, index, protocol, size, body)) {
1655 error << "Error writing from UI to plugin" << endmsg;
1662 LV2Plugin::write_to_ui(uint32_t index,
1665 const uint8_t* body)
1667 if (!write_to(_to_ui, index, protocol, size, body)) {
1668 error << "Error writing from plugin to UI" << endmsg;
1675 forge_variant(LV2_Atom_Forge* forge, const Variant& value)
1677 switch (value.type()) {
1678 case Variant::NOTHING:
1680 case Variant::BEATS:
1681 // No atom type for this, just forge a double
1682 lv2_atom_forge_double(forge, value.get_beats().to_double());
1685 lv2_atom_forge_bool(forge, value.get_bool());
1687 case Variant::DOUBLE:
1688 lv2_atom_forge_double(forge, value.get_double());
1690 case Variant::FLOAT:
1691 lv2_atom_forge_float(forge, value.get_float());
1694 lv2_atom_forge_int(forge, value.get_int());
1697 lv2_atom_forge_long(forge, value.get_long());
1700 lv2_atom_forge_path(
1701 forge, value.get_path().c_str(), value.get_path().size());
1703 case Variant::STRING:
1704 lv2_atom_forge_string(
1705 forge, value.get_string().c_str(), value.get_string().size());
1709 forge, value.get_uri().c_str(), value.get_uri().size());
1714 /** Get a variant type from a URI, return false iff no match found. */
1716 uri_to_variant_type(const std::string& uri, Variant::Type& type)
1718 if (uri == LV2_ATOM__Bool) {
1719 type = Variant::BOOL;
1720 } else if (uri == LV2_ATOM__Double) {
1721 type = Variant::DOUBLE;
1722 } else if (uri == LV2_ATOM__Float) {
1723 type = Variant::FLOAT;
1724 } else if (uri == LV2_ATOM__Int) {
1725 type = Variant::INT;
1726 } else if (uri == LV2_ATOM__Long) {
1727 type = Variant::LONG;
1728 } else if (uri == LV2_ATOM__Path) {
1729 type = Variant::PATH;
1730 } else if (uri == LV2_ATOM__String) {
1731 type = Variant::STRING;
1732 } else if (uri == LV2_ATOM__URI) {
1733 type = Variant::URI;
1741 LV2Plugin::set_property(uint32_t key, const Variant& value)
1743 if (_patch_port_in_index == (uint32_t)-1) {
1744 error << "LV2: set_property called with unset patch_port_in_index" << endmsg;
1746 } else if (value.type() == Variant::NOTHING) {
1747 error << "LV2: set_property called with void value" << endmsg;
1751 // Set up forge to write to temporary buffer on the stack
1752 LV2_Atom_Forge* forge = &_impl->ui_forge;
1753 LV2_Atom_Forge_Frame frame;
1754 uint8_t buf[PATH_MAX]; // Ought to be enough for anyone...
1756 lv2_atom_forge_set_buffer(forge, buf, sizeof(buf));
1758 // Serialize patch:Set message to set property
1759 #ifdef HAVE_LV2_1_10_0
1760 lv2_atom_forge_object(forge, &frame, 0, _uri_map.urids.patch_Set);
1761 lv2_atom_forge_key(forge, _uri_map.urids.patch_property);
1762 lv2_atom_forge_urid(forge, key);
1763 lv2_atom_forge_key(forge, _uri_map.urids.patch_value);
1765 lv2_atom_forge_blank(forge, &frame, 0, _uri_map.urids.patch_Set);
1766 lv2_atom_forge_property_head(forge, _uri_map.urids.patch_property, 0);
1767 lv2_atom_forge_urid(forge, key);
1768 lv2_atom_forge_property_head(forge, _uri_map.urids.patch_value, 0);
1771 forge_variant(forge, value);
1773 // Write message to UI=>Plugin ring
1774 const LV2_Atom* const atom = (const LV2_Atom*)buf;
1775 write_from_ui(_patch_port_in_index,
1776 _uri_map.urids.atom_eventTransfer,
1777 lv2_atom_total_size(atom),
1778 (const uint8_t*)atom);
1781 const ParameterDescriptor&
1782 LV2Plugin::get_property_descriptor(uint32_t id) const
1784 PropertyDescriptors::const_iterator p = _property_descriptors.find(id);
1785 if (p != _property_descriptors.end()) {
1788 return Plugin::get_property_descriptor(id);
1792 load_parameter_descriptor_units(LilvWorld* lworld, ParameterDescriptor& desc, const LilvNodes* units)
1794 if (lilv_nodes_contains(units, _world.units_midiNote)) {
1795 desc.unit = ParameterDescriptor::MIDI_NOTE;
1796 } else if (lilv_nodes_contains(units, _world.units_db)) {
1797 desc.unit = ParameterDescriptor::DB;
1798 } else if (lilv_nodes_contains(units, _world.units_hz)) {
1799 desc.unit = ParameterDescriptor::HZ;
1801 if (lilv_nodes_size(units) > 0) {
1802 const LilvNode* unit = lilv_nodes_get_first(units);
1803 LilvNode* render = get_value(lworld, unit, _world.units_render);
1805 desc.print_fmt = lilv_node_as_string(render);
1806 replace_all (desc.print_fmt, "%f", "%.2f");
1807 lilv_node_free(render);
1813 load_parameter_descriptor(LV2World& world,
1814 ParameterDescriptor& desc,
1815 Variant::Type datatype,
1816 const LilvNode* subject)
1818 LilvWorld* lworld = _world.world;
1819 LilvNode* label = get_value(lworld, subject, _world.rdfs_label);
1820 LilvNode* def = get_value(lworld, subject, _world.lv2_default);
1821 LilvNode* minimum = get_value(lworld, subject, _world.lv2_minimum);
1822 LilvNode* maximum = get_value(lworld, subject, _world.lv2_maximum);
1823 LilvNodes* units = lilv_world_find_nodes(lworld, subject, _world.units_unit, NULL);
1825 desc.label = lilv_node_as_string(label);
1828 if (lilv_node_is_float(def)) {
1829 desc.normal = lilv_node_as_float(def);
1830 } else if (lilv_node_is_int(def)) {
1831 desc.normal = lilv_node_as_int(def);
1835 if (lilv_node_is_float(minimum)) {
1836 desc.lower = lilv_node_as_float(minimum);
1837 } else if (lilv_node_is_int(minimum)) {
1838 desc.lower = lilv_node_as_int(minimum);
1842 if (lilv_node_is_float(maximum)) {
1843 desc.upper = lilv_node_as_float(maximum);
1844 } else if (lilv_node_is_int(maximum)) {
1845 desc.upper = lilv_node_as_int(maximum);
1848 load_parameter_descriptor_units(lworld, desc, units);
1849 desc.datatype = datatype;
1850 desc.toggled |= datatype == Variant::BOOL;
1851 desc.integer_step |= datatype == Variant::INT || datatype == Variant::LONG;
1852 desc.update_steps();
1854 lilv_nodes_free(units);
1855 lilv_node_free(label);
1856 lilv_node_free(def);
1857 lilv_node_free(minimum);
1858 lilv_node_free(maximum);
1862 LV2Plugin::load_supported_properties(PropertyDescriptors& descs)
1864 LilvWorld* lworld = _world.world;
1865 const LilvNode* subject = lilv_plugin_get_uri(_impl->plugin);
1866 LilvNodes* properties = lilv_world_find_nodes(
1867 lworld, subject, _world.patch_writable, NULL);
1868 LILV_FOREACH(nodes, p, properties) {
1869 // Get label and range
1870 const LilvNode* prop = lilv_nodes_get(properties, p);
1871 LilvNode* range = get_value(lworld, prop, _world.rdfs_range);
1873 warning << string_compose(_("LV2: property <%1> has no range datatype, ignoring"),
1874 lilv_node_as_uri(prop)) << endmsg;
1878 // Convert range to variant type (TODO: support for multiple range types)
1879 Variant::Type datatype;
1880 if (!uri_to_variant_type(lilv_node_as_uri(range), datatype)) {
1881 error << string_compose(_("LV2: property <%1> has unsupported datatype <%1>"),
1882 lilv_node_as_uri(prop), lilv_node_as_uri(range)) << endmsg;
1886 // Add description to result
1887 ParameterDescriptor desc;
1888 desc.key = _uri_map.uri_to_id(lilv_node_as_uri(prop));
1889 desc.datatype = datatype;
1890 load_parameter_descriptor(_world, desc, datatype, prop);
1891 descs.insert(std::make_pair(desc.key, desc));
1893 lilv_node_free(range);
1895 lilv_nodes_free(properties);
1899 LV2Plugin::announce_property_values()
1901 if (_patch_port_in_index == (uint32_t)-1) {
1905 // Set up forge to write to temporary buffer on the stack
1906 LV2_Atom_Forge* forge = &_impl->ui_forge;
1907 LV2_Atom_Forge_Frame frame;
1908 uint8_t buf[PATH_MAX]; // Ought to be enough for anyone...
1910 lv2_atom_forge_set_buffer(forge, buf, sizeof(buf));
1912 // Serialize patch:Get message with no subject (implicitly plugin instance)
1913 #ifdef HAVE_LV2_1_10_0
1914 lv2_atom_forge_object(forge, &frame, 0, _uri_map.urids.patch_Get);
1916 lv2_atom_forge_blank(forge, &frame, 0, _uri_map.urids.patch_Get);
1919 // Write message to UI=>Plugin ring
1920 const LV2_Atom* const atom = (const LV2_Atom*)buf;
1921 write_from_ui(_patch_port_in_index,
1922 _uri_map.urids.atom_eventTransfer,
1923 lv2_atom_total_size(atom),
1924 (const uint8_t*)atom);
1928 LV2Plugin::enable_ui_emission()
1931 /* see note in LV2Plugin::write_from_ui() */
1932 uint32_t bufsiz = 32768;
1933 if (_atom_ev_buffers && _atom_ev_buffers[0]) {
1934 bufsiz = lv2_evbuf_get_capacity(_atom_ev_buffers[0]);
1936 size_t rbs = _session.engine().raw_buffer_size(DataType::MIDI) * NBUFS;
1937 rbs = max((size_t) bufsiz * 8, rbs);
1938 _to_ui = new RingBuffer<uint8_t>(rbs);
1943 LV2Plugin::emit_to_ui(void* controller, UIMessageSink sink)
1949 uint32_t read_space = _to_ui->read_space();
1950 while (read_space > sizeof(UIMessage)) {
1952 if (_to_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1953 error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1956 vector<uint8_t> body(msg.size);
1957 if (_to_ui->read(&body[0], msg.size) != msg.size) {
1958 error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1962 sink(controller, msg.index, msg.size, msg.protocol, &body[0]);
1964 read_space -= sizeof(msg) + msg.size;
1969 LV2Plugin::work(Worker& worker, uint32_t size, const void* data)
1971 Glib::Threads::Mutex::Lock lm(_work_mutex);
1972 return _impl->work_iface->work(
1973 _impl->instance->lv2_handle, work_respond, &worker, size, data);
1977 LV2Plugin::work_response(uint32_t size, const void* data)
1979 return _impl->work_iface->work_response(
1980 _impl->instance->lv2_handle, size, data);
1984 LV2Plugin::set_insert_id(PBD::ID id)
1986 if (_insert_id == "0") {
1988 } else if (_insert_id != id) {
1989 lilv_state_free(_impl->state);
1990 _impl->state = NULL;
1996 LV2Plugin::set_state_dir (const std::string& d)
1998 _plugin_state_dir = d;
2002 LV2Plugin::set_state(const XMLNode& node, int version)
2005 XMLNodeConstIterator iter;
2009 if (node.name() != state_node_name()) {
2010 error << _("Bad node sent to LV2Plugin::set_state") << endmsg;
2014 #ifndef NO_PLUGIN_STATE
2016 if (version < 3000) {
2017 nodes = node.children("port");
2019 nodes = node.children("Port");
2022 for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
2027 if (!child->get_property("symbol", sym)) {
2028 warning << _("LV2: port has no symbol, ignored") << endmsg;
2032 map<string, uint32_t>::iterator i = _port_indices.find(sym);
2036 if (i != _port_indices.end()) {
2037 port_id = i->second;
2039 warning << _("LV2: port has unknown index, ignored") << endmsg;
2044 if (!child->get_property("value", val)) {
2045 warning << _("LV2: port has no value, ignored") << endmsg;
2049 set_parameter(port_id, val);
2052 std::string template_dir;
2053 if (node.get_property("template-dir", template_dir)) {
2054 set_state_dir (template_dir);
2058 std::string state_dir;
2059 if (node.get_property("state-dir", state_dir) != 0) {
2060 if (sscanf(state_dir.c_str(), "state%u", &_state_version) != 1) {
2061 error << string_compose(
2062 "LV2: failed to parse state version from \"%1\"",
2063 state_dir) << endmsg;
2066 std::string state_file = Glib::build_filename(
2068 Glib::build_filename(state_dir, "state.ttl"));
2070 LilvState* state = lilv_state_new_from_file(
2071 _world.world, _uri_map.urid_map(), NULL, state_file.c_str());
2073 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
2074 lilv_state_free(_impl->state);
2075 _impl->state = state;
2078 if (!_plugin_state_dir.empty ()) {
2079 // force save with session, next time (increment counter)
2080 lilv_state_free (_impl->state);
2081 _impl->state = NULL;
2085 latency_compute_run();
2088 return Plugin::set_state(node, version);
2092 LV2Plugin::get_parameter_descriptor(uint32_t which, ParameterDescriptor& desc) const
2094 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, which);
2096 error << string_compose("LV2: get descriptor of non-existent port %1", which)
2101 LilvNodes* portunits;
2102 LilvNode *def, *min, *max;
2103 lilv_port_get_range(_impl->plugin, port, &def, &min, &max);
2104 portunits = lilv_port_get_value(_impl->plugin, port, _world.units_unit);
2106 LilvNode* steps = lilv_port_get(_impl->plugin, port, _world.ext_rangeSteps);
2108 // TODO: Once we can rely on lilv 0.18.0 being present,
2109 // load_parameter_descriptor() can be used for ports as well
2110 desc.integer_step = lilv_port_has_property(_impl->plugin, port, _world.lv2_integer);
2111 desc.toggled = lilv_port_has_property(_impl->plugin, port, _world.lv2_toggled);
2112 desc.logarithmic = lilv_port_has_property(_impl->plugin, port, _world.ext_logarithmic);
2113 desc.sr_dependent = lilv_port_has_property(_impl->plugin, port, _world.lv2_sampleRate);
2114 desc.label = lilv_node_as_string(lilv_port_get_name(_impl->plugin, port));
2115 desc.normal = def ? lilv_node_as_float(def) : 0.0f;
2116 desc.lower = min ? lilv_node_as_float(min) : 0.0f;
2117 desc.upper = max ? lilv_node_as_float(max) : 1.0f;
2118 load_parameter_descriptor_units(_world.world, desc, portunits);
2120 if (desc.sr_dependent) {
2121 desc.lower *= _session.frame_rate ();
2122 desc.upper *= _session.frame_rate ();
2125 desc.enumeration = lilv_port_has_property(_impl->plugin, port, _world.lv2_enumeration);
2126 desc.scale_points = get_scale_points(which);
2129 desc.rangesteps = lilv_node_as_float (steps);
2132 desc.update_steps();
2134 lilv_node_free(def);
2135 lilv_node_free(min);
2136 lilv_node_free(max);
2137 lilv_node_free(steps);
2138 lilv_nodes_free(portunits);
2143 Plugin::IOPortDescription
2144 LV2Plugin::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
2146 PortFlags match = 0;
2148 case DataType::AUDIO:
2151 case DataType::MIDI:
2152 match = PORT_SEQUENCE | PORT_MIDI; // ignore old PORT_EVENT
2155 return Plugin::IOPortDescription ("?");
2159 match |= PORT_INPUT;
2161 match |= PORT_OUTPUT;
2165 uint32_t idx = UINT32_MAX;
2167 uint32_t const num_ports = parameter_count();
2168 for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
2169 PortFlags flags = _port_flags[port_index];
2170 if ((flags & match) == match) {
2177 if (idx == UINT32_MAX) {
2178 return Plugin::IOPortDescription ("?");
2181 const LilvPort* pport = lilv_plugin_get_port_by_index (_impl->plugin, idx);
2183 LilvNode* name = lilv_port_get_name(_impl->plugin, pport);
2184 Plugin::IOPortDescription iod (lilv_node_as_string (name));
2185 lilv_node_free(name);
2187 /* get the port's pg:group */
2188 LilvNodes* groups = lilv_port_get_value (_impl->plugin, pport, _world.groups_group);
2189 if (lilv_nodes_size (groups) > 0) {
2190 const LilvNode* group = lilv_nodes_get_first (groups);
2191 LilvNodes* grouplabel = lilv_world_find_nodes (_world.world, group, _world.rdfs_label, NULL);
2193 /* get the name of the port-group */
2194 if (lilv_nodes_size (grouplabel) > 0) {
2195 const LilvNode* grpname = lilv_nodes_get_first (grouplabel);
2196 iod.group_name = lilv_node_as_string (grpname);
2198 lilv_nodes_free (grouplabel);
2200 /* get all port designations.
2201 * we're interested in e.g. lv2:designation pg:right */
2202 LilvNodes* designations = lilv_port_get_value (_impl->plugin, pport, _world.lv2_designation);
2203 if (lilv_nodes_size (designations) > 0) {
2204 /* get all pg:elements of the pg:group */
2205 LilvNodes* group_childs = lilv_world_find_nodes (_world.world, group, _world.groups_element, NULL);
2206 if (lilv_nodes_size (group_childs) > 0) {
2207 /* iterate over all port designations .. */
2208 LILV_FOREACH (nodes, i, designations) {
2209 const LilvNode* designation = lilv_nodes_get (designations, i);
2210 /* match the lv2:designation's element against the port-group's element */
2211 LILV_FOREACH (nodes, j, group_childs) {
2212 const LilvNode* group_element = lilv_nodes_get (group_childs, j);
2213 LilvNodes* elem = lilv_world_find_nodes (_world.world, group_element, _world.lv2_designation, designation);
2214 /* found it. Now look up the index (channel-number) of the pg:Element */
2215 if (lilv_nodes_size (elem) > 0) {
2216 LilvNodes* idx = lilv_world_find_nodes (_world.world, lilv_nodes_get_first (elem), _world.lv2_index, NULL);
2217 if (lilv_node_is_int (lilv_nodes_get_first (idx))) {
2218 iod.group_channel = lilv_node_as_int(lilv_nodes_get_first (idx));
2225 lilv_nodes_free (groups);
2226 lilv_nodes_free (designations);
2229 if (lilv_port_has_property(_impl->plugin, pport, _world.lv2_isSideChain)) {
2230 iod.is_sidechain = true;
2236 LV2Plugin::describe_parameter(Evoral::Parameter which)
2238 if (( which.type() == PluginAutomation) && ( which.id() < parameter_count()) ) {
2240 if (lilv_port_has_property(_impl->plugin,
2241 lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.ext_notOnGUI)) {
2242 return X_("hidden");
2245 if (lilv_port_has_property(_impl->plugin,
2246 lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_freewheeling)) {
2247 return X_("hidden");
2250 if (lilv_port_has_property(_impl->plugin,
2251 lilv_plugin_get_port_by_index(_impl->plugin, which.id()), _world.lv2_reportsLatency)) {
2252 return X_("latency");
2255 LilvNode* name = lilv_port_get_name(_impl->plugin,
2256 lilv_plugin_get_port_by_index(_impl->plugin, which.id()));
2257 string ret(lilv_node_as_string(name));
2258 lilv_node_free(name);
2266 LV2Plugin::max_latency () const
2268 return _max_latency;
2272 LV2Plugin::signal_latency() const
2274 if (_latency_control_port) {
2275 return (framecnt_t)floor(*_latency_control_port);
2281 set<Evoral::Parameter>
2282 LV2Plugin::automatable() const
2284 set<Evoral::Parameter> ret;
2286 for (uint32_t i = 0; i < parameter_count(); ++i) {
2287 if (parameter_is_input(i) && parameter_is_control(i) && !(_port_flags[i] & PORT_NOAUTO)) {
2288 ret.insert(ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
2292 for (PropertyDescriptors::const_iterator p = _property_descriptors.begin();
2293 p != _property_descriptors.end();
2295 ret.insert(ret.end(), Evoral::Parameter(PluginPropertyAutomation, 0, p->first));
2301 LV2Plugin::set_automation_control (uint32_t i, boost::shared_ptr<AutomationControl> c)
2303 if ((_port_flags[i] & (PORT_CTRLED | PORT_CTRLER))) {
2304 DEBUG_TRACE(DEBUG::LV2Automate, string_compose ("Ctrl Port %1\n", i));
2305 _ctrl_map [i] = AutomationCtrlPtr (new AutomationCtrl(c));
2309 LV2Plugin::AutomationCtrlPtr
2310 LV2Plugin::get_automation_control (uint32_t i)
2312 if (_ctrl_map.find (i) == _ctrl_map.end()) {
2313 return AutomationCtrlPtr ();
2315 return _ctrl_map[i];
2319 LV2Plugin::activate()
2321 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 activate\n", name()));
2323 if (!_was_activated) {
2324 lilv_instance_activate(_impl->instance);
2325 _was_activated = true;
2330 LV2Plugin::deactivate()
2332 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 deactivate\n", name()));
2334 if (_was_activated) {
2335 lilv_instance_deactivate(_impl->instance);
2336 _was_activated = false;
2341 LV2Plugin::cleanup()
2343 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 cleanup\n", name()));
2346 lilv_instance_free(_impl->instance);
2347 _impl->instance = NULL;
2351 LV2Plugin::allocate_atom_event_buffers()
2353 /* reserve local scratch buffers for ATOM event-queues */
2354 const LilvPlugin* p = _impl->plugin;
2356 /* count non-MIDI atom event-ports
2357 * TODO: nicely ask drobilla to make a lilv_ call for that
2359 int count_atom_out = 0;
2360 int count_atom_in = 0;
2361 int minimumSize = 32768; // TODO use a per-port minimum-size
2362 for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
2363 const LilvPort* port = lilv_plugin_get_port_by_index(p, i);
2364 if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
2365 LilvNodes* buffer_types = lilv_port_get_value(
2366 p, port, _world.atom_bufferType);
2367 LilvNodes* atom_supports = lilv_port_get_value(
2368 p, port, _world.atom_supports);
2370 if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)) {
2371 if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
2374 if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
2377 LilvNodes* min_size_v = lilv_port_get_value(_impl->plugin, port, _world.rsz_minimumSize);
2378 LilvNode* min_size = min_size_v ? lilv_nodes_get_first(min_size_v) : NULL;
2379 if (min_size && lilv_node_is_int(min_size)) {
2380 minimumSize = std::max(minimumSize, lilv_node_as_int(min_size));
2382 lilv_nodes_free(min_size_v);
2384 lilv_nodes_free(buffer_types);
2385 lilv_nodes_free(atom_supports);
2389 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 need buffers for %2 atom-in and %3 atom-out event-ports\n",
2390 name(), count_atom_in, count_atom_out));
2392 const int total_atom_buffers = (count_atom_in + count_atom_out);
2393 if (_atom_ev_buffers || total_atom_buffers == 0) {
2397 DEBUG_TRACE(DEBUG::LV2, string_compose("allocate %1 atom_ev_buffers of %2 bytes\n", total_atom_buffers, minimumSize));
2398 _atom_ev_buffers = (LV2_Evbuf**) malloc((total_atom_buffers + 1) * sizeof(LV2_Evbuf*));
2399 for (int i = 0; i < total_atom_buffers; ++i ) {
2400 _atom_ev_buffers[i] = lv2_evbuf_new(minimumSize, LV2_EVBUF_ATOM,
2401 _uri_map.urids.atom_Chunk, _uri_map.urids.atom_Sequence);
2403 _atom_ev_buffers[total_atom_buffers] = 0;
2407 /** Write an ardour position/time/tempo/meter as an LV2 event.
2408 * @return true on success.
2411 write_position(LV2_Atom_Forge* forge,
2413 const TempoMetric& t,
2414 Timecode::BBT_Time& bbt,
2417 framepos_t position,
2420 const URIMap::URIDs& urids = URIMap::instance().urids;
2422 uint8_t pos_buf[256];
2423 lv2_atom_forge_set_buffer(forge, pos_buf, sizeof(pos_buf));
2424 LV2_Atom_Forge_Frame frame;
2425 #ifdef HAVE_LV2_1_10_0
2426 lv2_atom_forge_object(forge, &frame, 0, urids.time_Position);
2427 lv2_atom_forge_key(forge, urids.time_frame);
2428 lv2_atom_forge_long(forge, position);
2429 lv2_atom_forge_key(forge, urids.time_speed);
2430 lv2_atom_forge_float(forge, speed);
2431 lv2_atom_forge_key(forge, urids.time_barBeat);
2432 lv2_atom_forge_float(forge, bbt.beats - 1 +
2433 (bbt.ticks / Timecode::BBT_Time::ticks_per_beat));
2434 lv2_atom_forge_key(forge, urids.time_bar);
2435 lv2_atom_forge_long(forge, bbt.bars - 1);
2436 lv2_atom_forge_key(forge, urids.time_beatUnit);
2437 lv2_atom_forge_int(forge, t.meter().note_divisor());
2438 lv2_atom_forge_key(forge, urids.time_beatsPerBar);
2439 lv2_atom_forge_float(forge, t.meter().divisions_per_bar());
2440 lv2_atom_forge_key(forge, urids.time_beatsPerMinute);
2441 lv2_atom_forge_float(forge, bpm);
2443 lv2_atom_forge_blank(forge, &frame, 1, urids.time_Position);
2444 lv2_atom_forge_property_head(forge, urids.time_frame, 0);
2445 lv2_atom_forge_long(forge, position);
2446 lv2_atom_forge_property_head(forge, urids.time_speed, 0);
2447 lv2_atom_forge_float(forge, speed);
2448 lv2_atom_forge_property_head(forge, urids.time_barBeat, 0);
2449 lv2_atom_forge_float(forge, bbt.beats - 1 +
2450 (bbt.ticks / Timecode::BBT_Time::ticks_per_beat));
2451 lv2_atom_forge_property_head(forge, urids.time_bar, 0);
2452 lv2_atom_forge_long(forge, bbt.bars - 1);
2453 lv2_atom_forge_property_head(forge, urids.time_beatUnit, 0);
2454 lv2_atom_forge_int(forge, t.meter().note_divisor());
2455 lv2_atom_forge_property_head(forge, urids.time_beatsPerBar, 0);
2456 lv2_atom_forge_float(forge, t.meter().divisions_per_bar());
2457 lv2_atom_forge_property_head(forge, urids.time_beatsPerMinute, 0);
2458 lv2_atom_forge_float(forge, bpm);
2461 LV2_Evbuf_Iterator end = lv2_evbuf_end(buf);
2462 const LV2_Atom* const atom = (const LV2_Atom*)pos_buf;
2463 return lv2_evbuf_write(&end, offset, 0, atom->type, atom->size,
2464 (const uint8_t*)(atom + 1));
2468 LV2Plugin::connect_and_run(BufferSet& bufs,
2469 framepos_t start, framepos_t end, double speed,
2470 ChanMapping in_map, ChanMapping out_map,
2471 pframes_t nframes, framecnt_t offset)
2473 DEBUG_TRACE(DEBUG::LV2, string_compose("%1 run %2 offset %3\n", name(), nframes, offset));
2474 Plugin::connect_and_run(bufs, start, end, speed, in_map, out_map, nframes, offset);
2476 cycles_t then = get_cycles();
2478 TempoMap& tmap = _session.tempo_map();
2479 Metrics::const_iterator metric_i = tmap.metrics_end();
2480 TempoMetric tmetric = tmap.metric_at(start, &metric_i);
2482 if (_freewheel_control_port) {
2483 *_freewheel_control_port = _session.engine().freewheeling() ? 1.f : 0.f;
2486 if (_bpm_control_port) {
2487 *_bpm_control_port = tmap.tempo_at_frame (start).note_types_per_minute();
2491 if (_can_write_automation && start != _next_cycle_start) {
2492 // add guard-points after locating
2493 for (AutomationCtrlMap::iterator i = _ctrl_map.begin(); i != _ctrl_map.end(); ++i) {
2494 i->second->guard = true;
2499 ChanCount bufs_count;
2500 bufs_count.set(DataType::AUDIO, 1);
2501 bufs_count.set(DataType::MIDI, 1);
2502 BufferSet& silent_bufs = _session.get_silent_buffers(bufs_count);
2503 BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
2504 uint32_t const num_ports = parameter_count();
2505 uint32_t const nil_index = std::numeric_limits<uint32_t>::max();
2507 uint32_t audio_in_index = 0;
2508 uint32_t audio_out_index = 0;
2509 uint32_t midi_in_index = 0;
2510 uint32_t midi_out_index = 0;
2511 uint32_t atom_port_index = 0;
2512 for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
2514 uint32_t index = nil_index;
2515 PortFlags flags = _port_flags[port_index];
2517 if (flags & PORT_AUDIO) {
2518 if (flags & PORT_INPUT) {
2519 index = in_map.get(DataType::AUDIO, audio_in_index++, &valid);
2521 ? bufs.get_audio(index).data(offset)
2522 : silent_bufs.get_audio(0).data(offset);
2524 index = out_map.get(DataType::AUDIO, audio_out_index++, &valid);
2526 ? bufs.get_audio(index).data(offset)
2527 : scratch_bufs.get_audio(0).data(offset);
2529 } else if (flags & (PORT_EVENT|PORT_SEQUENCE)) {
2530 /* FIXME: The checks here for bufs.count().n_midi() > index shouldn't
2531 be necessary, but the mapping is illegal in some cases. Ideally
2532 that should be fixed, but this is easier...
2534 if (flags & PORT_MIDI) {
2535 if (flags & PORT_INPUT) {
2536 index = in_map.get(DataType::MIDI, midi_in_index++, &valid);
2538 index = out_map.get(DataType::MIDI, midi_out_index++, &valid);
2540 if (valid && bufs.count().n_midi() > index) {
2541 /* Note, ensure_lv2_bufsize() is not RT safe!
2542 * However free()/alloc() is only called if a
2543 * plugin requires a rsz:minimumSize buffersize
2544 * and the existing buffer if smaller.
2546 bufs.ensure_lv2_bufsize((flags & PORT_INPUT), index, _port_minimumSize[port_index]);
2547 _ev_buffers[port_index] = bufs.get_lv2_midi(
2548 (flags & PORT_INPUT), index, (flags & PORT_EVENT));
2550 } else if ((flags & PORT_POSITION) && (flags & PORT_INPUT)) {
2551 lv2_evbuf_reset(_atom_ev_buffers[atom_port_index], true);
2552 _ev_buffers[port_index] = _atom_ev_buffers[atom_port_index++];
2556 if (valid && (flags & PORT_INPUT)) {
2557 if ((flags & PORT_POSITION)) {
2558 Timecode::BBT_Time bbt (tmap.bbt_at_frame (start));
2559 double bpm = tmap.tempo_at_frame (start).note_types_per_minute();
2560 double beatpos = (bbt.bars - 1) * tmetric.meter().divisions_per_bar()
2562 + (bbt.ticks / Timecode::BBT_Time::ticks_per_beat);
2563 beatpos *= tmetric.meter().note_divisor() / 4.0;
2564 if (start != _next_cycle_start ||
2565 speed != _next_cycle_speed ||
2566 rint (1000 * beatpos) != rint(1000 * _next_cycle_beat) ||
2567 bpm != _current_bpm) {
2568 // Transport or Tempo has changed, write position at cycle start
2569 write_position(&_impl->forge, _ev_buffers[port_index],
2570 tmetric, bbt, speed, bpm, start, 0);
2574 // Get MIDI iterator range (empty range if no MIDI)
2575 MidiBuffer::iterator m = (index != nil_index)
2576 ? bufs.get_midi(index).begin()
2577 : silent_bufs.get_midi(0).end();
2578 MidiBuffer::iterator m_end = (index != nil_index)
2579 ? bufs.get_midi(index).end()
2582 // Now merge MIDI and any transport events into the buffer
2583 const uint32_t type = _uri_map.urids.midi_MidiEvent;
2584 const framepos_t tend = end;
2586 while (m != m_end || (metric_i != tmap.metrics_end() &&
2587 (*metric_i)->frame() < tend)) {
2588 MetricSection* metric = (metric_i != tmap.metrics_end())
2590 if (m != m_end && (!metric || metric->frame() > (*m).time())) {
2591 const Evoral::Event<framepos_t> ev(*m, false);
2592 if (ev.time() < nframes) {
2593 LV2_Evbuf_Iterator eend = lv2_evbuf_end(_ev_buffers[port_index]);
2594 lv2_evbuf_write(&eend, ev.time(), 0, type, ev.size(), ev.buffer());
2598 tmetric.set_metric(metric);
2599 Timecode::BBT_Time bbt;
2600 bbt = tmap.bbt_at_frame (metric->frame());
2601 double bpm = tmap.tempo_at_frame (start/*XXX*/).note_types_per_minute();
2602 write_position(&_impl->forge, _ev_buffers[port_index],
2603 tmetric, bbt, speed, bpm,
2605 metric->frame() - start);
2609 } else if (!valid) {
2610 // Nothing we understand or care about, connect to scratch
2611 // see note for midi-buffer size above
2612 scratch_bufs.ensure_lv2_bufsize((flags & PORT_INPUT),
2613 0, _port_minimumSize[port_index]);
2614 _ev_buffers[port_index] = scratch_bufs.get_lv2_midi(
2615 (flags & PORT_INPUT), 0, (flags & PORT_EVENT));
2618 buf = lv2_evbuf_get_buffer(_ev_buffers[port_index]);
2620 continue; // Control port, leave buffer alone
2622 lilv_instance_connect_port(_impl->instance, port_index, buf);
2625 // Read messages from UI and push into appropriate buffers
2627 uint32_t read_space = _from_ui->read_space();
2628 while (read_space > sizeof(UIMessage)) {
2630 if (_from_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
2631 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
2634 vector<uint8_t> body(msg.size);
2635 if (_from_ui->read(&body[0], msg.size) != msg.size) {
2636 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
2639 if (msg.protocol == URIMap::instance().urids.atom_eventTransfer) {
2640 LV2_Evbuf* buf = _ev_buffers[msg.index];
2641 LV2_Evbuf_Iterator i = lv2_evbuf_end(buf);
2642 const LV2_Atom* const atom = (const LV2_Atom*)&body[0];
2643 if (!lv2_evbuf_write(&i, nframes - 1, 0, atom->type, atom->size,
2644 (const uint8_t*)(atom + 1))) {
2645 error << "Failed to write data to LV2 event buffer\n";
2648 error << "Received unknown message type from UI" << endmsg;
2650 read_space -= sizeof(UIMessage) + msg.size;
2657 for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
2658 PortFlags flags = _port_flags[port_index];
2661 /* TODO ask drobilla about comment
2662 * "Make Ardour event buffers generic so plugins can communicate"
2663 * in libs/ardour/buffer_set.cc:310
2665 * ideally the user could choose which of the following two modes
2666 * to use (e.g. instrument/effect chains MIDI OUT vs MIDI TRHU).
2668 * This implementation follows the discussion on IRC Mar 16 2013 16:47 UTC
2669 * 16:51 < drobilla> rgareus: [..] i.e always replace with MIDI output [of LV2 plugin] if it's there
2670 * 16:52 < drobilla> rgareus: That would probably be good enough [..] to make users not complain
2671 * for quite a while at least ;)
2673 // copy output of LV2 plugin's MIDI port to Ardour MIDI buffers -- MIDI OUT
2674 if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE|PORT_MIDI))) {
2675 const uint32_t buf_index = out_map.get(
2676 DataType::MIDI, midi_out_index++, &valid);
2678 bufs.forward_lv2_midi(_ev_buffers[port_index], buf_index);
2681 // Flush MIDI (write back to Ardour MIDI buffers) -- MIDI THRU
2682 else if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
2683 const uint32_t buf_index = out_map.get(
2684 DataType::MIDI, midi_out_index++, &valid);
2686 bufs.flush_lv2_midi(true, buf_index);
2690 // Write messages to UI
2691 if ((_to_ui || _can_write_automation || _patch_port_out_index != (uint32_t)-1) &&
2692 (flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_SEQUENCE))) {
2693 LV2_Evbuf* buf = _ev_buffers[port_index];
2694 for (LV2_Evbuf_Iterator i = lv2_evbuf_begin(buf);
2695 lv2_evbuf_is_valid(i);
2696 i = lv2_evbuf_next(i)) {
2697 uint32_t frames, subframes, type, size;
2699 lv2_evbuf_get(i, &frames, &subframes, &type, &size, &data);
2702 // Intercept Automation Write Events
2703 if ((flags & PORT_AUTOCTRL)) {
2704 LV2_Atom* atom = (LV2_Atom*)(data - sizeof(LV2_Atom));
2705 if (atom->type == _uri_map.urids.atom_Blank ||
2706 atom->type == _uri_map.urids.atom_Object) {
2707 LV2_Atom_Object* obj = (LV2_Atom_Object*)atom;
2708 if (obj->body.otype == _uri_map.urids.auto_event) {
2709 // only if transport_rolling ??
2710 const LV2_Atom* parameter = NULL;
2711 const LV2_Atom* value = NULL;
2712 lv2_atom_object_get(obj,
2713 _uri_map.urids.auto_parameter, ¶meter,
2714 _uri_map.urids.auto_value, &value,
2716 if (parameter && value) {
2717 const uint32_t p = ((const LV2_Atom_Int*)parameter)->body;
2718 const float v = ((const LV2_Atom_Float*)value)->body;
2719 // -> add automation event..
2720 DEBUG_TRACE(DEBUG::LV2Automate,
2721 string_compose ("Event p: %1 t: %2 v: %3\n", p, frames, v));
2722 AutomationCtrlPtr c = get_automation_control (p);
2724 (c->ac->automation_state() == Touch || c->ac->automation_state() == Write)
2726 framepos_t when = std::max ((framepos_t) 0, start + frames - _current_latency);
2727 assert (start + frames - _current_latency >= 0);
2730 c->ac->list()->add (when, v, true, true);
2732 c->ac->set_double (v, when, true);
2737 else if (obj->body.otype == _uri_map.urids.auto_setup) {
2738 // TODO optional arguments, for now we assume the plugin
2739 // writes automation for its own inputs
2740 // -> put them in "touch" mode (preferably "exclusive plugin touch(TM)"
2741 for (AutomationCtrlMap::iterator i = _ctrl_map.begin(); i != _ctrl_map.end(); ++i) {
2742 if (_port_flags[i->first] & PORT_CTRLED) {
2743 DEBUG_TRACE(DEBUG::LV2Automate,
2744 string_compose ("Setup p: %1\n", i->first));
2745 i->second->ac->set_automation_state (Touch);
2749 else if (obj->body.otype == _uri_map.urids.auto_finalize) {
2750 // set [touched] parameters to "play" ??
2751 // allow plugin to change its mode (from analyze to apply)
2752 const LV2_Atom* parameter = NULL;
2753 const LV2_Atom* value = NULL;
2754 lv2_atom_object_get(obj,
2755 _uri_map.urids.auto_parameter, ¶meter,
2756 _uri_map.urids.auto_value, &value,
2758 if (parameter && value) {
2759 const uint32_t p = ((const LV2_Atom_Int*)parameter)->body;
2760 const float v = ((const LV2_Atom_Float*)value)->body;
2761 AutomationCtrlPtr c = get_automation_control (p);
2762 DEBUG_TRACE(DEBUG::LV2Automate,
2763 string_compose ("Finalize p: %1 v: %2\n", p, v));
2764 if (c && _port_flags[p] & PORT_CTRLER) {
2765 c->ac->set_value(v, Controllable::NoGroup);
2768 DEBUG_TRACE(DEBUG::LV2Automate, "Finalize\n");
2770 for (AutomationCtrlMap::iterator i = _ctrl_map.begin(); i != _ctrl_map.end(); ++i) {
2771 // guard will be false if an event was written
2772 if ((_port_flags[i->first] & PORT_CTRLED) && !i->second->guard) {
2773 DEBUG_TRACE(DEBUG::LV2Automate,
2774 string_compose ("Thin p: %1\n", i->first));
2775 i->second->ac->alist ()->thin (20);
2779 else if (obj->body.otype == _uri_map.urids.auto_start) {
2780 const LV2_Atom* parameter = NULL;
2781 lv2_atom_object_get(obj,
2782 _uri_map.urids.auto_parameter, ¶meter,
2785 const uint32_t p = ((const LV2_Atom_Int*)parameter)->body;
2786 AutomationCtrlPtr c = get_automation_control (p);
2787 DEBUG_TRACE(DEBUG::LV2Automate, string_compose ("Start Touch p: %1\n", p));
2789 c->ac->start_touch (std::max ((framepos_t)0, start - _current_latency));
2794 else if (obj->body.otype == _uri_map.urids.auto_end) {
2795 const LV2_Atom* parameter = NULL;
2796 lv2_atom_object_get(obj,
2797 _uri_map.urids.auto_parameter, ¶meter,
2800 const uint32_t p = ((const LV2_Atom_Int*)parameter)->body;
2801 AutomationCtrlPtr c = get_automation_control (p);
2802 DEBUG_TRACE(DEBUG::LV2Automate, string_compose ("End Touch p: %1\n", p));
2804 c->ac->stop_touch (true, std::max ((framepos_t)0, start - _current_latency));
2811 // Intercept state dirty message
2812 if (_has_state_interface /* && (flags & PORT_DIRTYMSG)*/) {
2813 LV2_Atom* atom = (LV2_Atom*)(data - sizeof(LV2_Atom));
2814 if (atom->type == _uri_map.urids.atom_Blank ||
2815 atom->type == _uri_map.urids.atom_Object) {
2816 LV2_Atom_Object* obj = (LV2_Atom_Object*)atom;
2817 if (obj->body.otype == _uri_map.urids.state_StateChanged) {
2818 _session.set_dirty ();
2823 // Intercept patch change messages to emit PropertyChanged signal
2824 if ((flags & PORT_PATCHMSG)) {
2825 LV2_Atom* atom = (LV2_Atom*)(data - sizeof(LV2_Atom));
2826 if (atom->type == _uri_map.urids.atom_Blank ||
2827 atom->type == _uri_map.urids.atom_Object) {
2828 LV2_Atom_Object* obj = (LV2_Atom_Object*)atom;
2829 if (obj->body.otype == _uri_map.urids.patch_Set) {
2830 const LV2_Atom* property = NULL;
2831 const LV2_Atom* value = NULL;
2832 lv2_atom_object_get(obj,
2833 _uri_map.urids.patch_property, &property,
2834 _uri_map.urids.patch_value, &value,
2837 if (property && value &&
2838 property->type == _uri_map.urids.atom_URID &&
2839 value->type == _uri_map.urids.atom_Path) {
2840 const uint32_t prop_id = ((const LV2_Atom_URID*)property)->body;
2841 const char* path = (const char*)LV2_ATOM_BODY_CONST(value);
2843 // Emit PropertyChanged signal for UI
2844 // TODO: This should emit the control's Changed signal
2845 PropertyChanged(prop_id, Variant(Variant::PATH, path));
2847 std::cerr << "warning: patch:Set for unknown property" << std::endl;
2853 if (!_to_ui) continue;
2854 write_to_ui(port_index, URIMap::instance().urids.atom_eventTransfer,
2855 size + sizeof(LV2_Atom),
2856 data - sizeof(LV2_Atom));
2861 cycles_t now = get_cycles();
2862 set_cycles((uint32_t)(now - then));
2864 // Update expected transport information for next cycle so we can detect changes
2865 _next_cycle_speed = speed;
2866 _next_cycle_start = end;
2869 /* keep track of lv2:timePosition like plugins can do.
2870 * Note: for no-midi plugins, we only ever send information at cycle-start,
2871 * so it needs to be realative to that.
2873 TempoMetric t = tmap.metric_at(start);
2874 _current_bpm = tmap.tempo_at_frame (start).note_types_per_minute();
2875 Timecode::BBT_Time bbt (tmap.bbt_at_frame (start));
2876 double beatpos = (bbt.bars - 1) * t.meter().divisions_per_bar()
2878 + (bbt.ticks / Timecode::BBT_Time::ticks_per_beat);
2879 beatpos *= tmetric.meter().note_divisor() / 4.0;
2880 _next_cycle_beat = beatpos + nframes * speed * _current_bpm / (60.f * _session.frame_rate());
2883 if (_latency_control_port) {
2884 framecnt_t new_latency = signal_latency ();
2885 _current_latency = new_latency;
2891 LV2Plugin::parameter_is_control(uint32_t param) const
2893 assert(param < _port_flags.size());
2894 return _port_flags[param] & PORT_CONTROL;
2898 LV2Plugin::parameter_is_audio(uint32_t param) const
2900 assert(param < _port_flags.size());
2901 return _port_flags[param] & PORT_AUDIO;
2905 LV2Plugin::parameter_is_event(uint32_t param) const
2907 assert(param < _port_flags.size());
2908 return _port_flags[param] & PORT_EVENT;
2912 LV2Plugin::parameter_is_output(uint32_t param) const
2914 assert(param < _port_flags.size());
2915 return _port_flags[param] & PORT_OUTPUT;
2919 LV2Plugin::parameter_is_input(uint32_t param) const
2921 assert(param < _port_flags.size());
2922 return _port_flags[param] & PORT_INPUT;
2926 LV2Plugin::designated_bypass_port ()
2928 const LilvPort* port = NULL;
2929 LilvNode* designation = lilv_new_uri (_world.world, LV2_CORE_PREFIX "enabled");
2930 port = lilv_plugin_get_port_by_designation (
2931 _impl->plugin, _world.lv2_InputPort, designation);
2932 lilv_node_free(designation);
2934 return lilv_port_get_index (_impl->plugin, port);
2937 /* deprecated on 2016-Sep-18 in favor of lv2:enabled */
2938 designation = lilv_new_uri (_world.world, LV2_PROCESSING_URI__enable);
2939 port = lilv_plugin_get_port_by_designation (
2940 _impl->plugin, _world.lv2_InputPort, designation);
2941 lilv_node_free(designation);
2943 return lilv_port_get_index (_impl->plugin, port);
2950 LV2Plugin::print_parameter(uint32_t param, char* buf, uint32_t len) const
2953 if (param < parameter_count()) {
2954 snprintf(buf, len, "%.3f", get_parameter(param));
2961 boost::shared_ptr<ScalePoints>
2962 LV2Plugin::get_scale_points(uint32_t port_index) const
2964 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, port_index);
2965 LilvScalePoints* points = lilv_port_get_scale_points(_impl->plugin, port);
2967 boost::shared_ptr<ScalePoints> ret;
2972 ret = boost::shared_ptr<ScalePoints>(new ScalePoints());
2974 LILV_FOREACH(scale_points, i, points) {
2975 const LilvScalePoint* p = lilv_scale_points_get(points, i);
2976 const LilvNode* label = lilv_scale_point_get_label(p);
2977 const LilvNode* value = lilv_scale_point_get_value(p);
2978 if (label && (lilv_node_is_float(value) || lilv_node_is_int(value))) {
2979 ret->insert(make_pair(lilv_node_as_string(label),
2980 lilv_node_as_float(value)));
2984 lilv_scale_points_free(points);
2989 LV2Plugin::run(pframes_t nframes, bool sync_work)
2991 uint32_t const N = parameter_count();
2992 for (uint32_t i = 0; i < N; ++i) {
2993 if (parameter_is_control(i) && parameter_is_input(i)) {
2994 _control_data[i] = _shadow_data[i];
2999 // Execute work synchronously if we're freewheeling (export)
3000 _worker->set_synchronous(sync_work || session().engine().freewheeling());
3003 // Run the plugin for this cycle
3004 lilv_instance_run(_impl->instance, nframes);
3006 // Emit any queued worker responses (calls a plugin callback)
3007 if (_state_worker) {
3008 _state_worker->emit_responses();
3011 _worker->emit_responses();
3014 // Notify the plugin that a work run cycle is complete
3015 if (_impl->work_iface) {
3016 if (_impl->work_iface->end_run) {
3017 _impl->work_iface->end_run(_impl->instance->lv2_handle);
3023 LV2Plugin::latency_compute_run()
3025 if (!_latency_control_port) {
3029 // Run the plugin so that it can set its latency parameter
3031 bool was_activated = _was_activated;
3034 uint32_t port_index = 0;
3035 uint32_t in_index = 0;
3036 uint32_t out_index = 0;
3038 // this is done in the main thread. non realtime.
3039 const framecnt_t bufsize = _engine.samples_per_cycle();
3040 float *buffer = (float*) malloc(_engine.samples_per_cycle() * sizeof(float));
3042 memset(buffer, 0, sizeof(float) * bufsize);
3044 // FIXME: Ensure plugins can handle in-place processing
3048 while (port_index < parameter_count()) {
3049 if (parameter_is_audio(port_index)) {
3050 if (parameter_is_input(port_index)) {
3051 lilv_instance_connect_port(_impl->instance, port_index, buffer);
3053 } else if (parameter_is_output(port_index)) {
3054 lilv_instance_connect_port(_impl->instance, port_index, buffer);
3063 if (was_activated) {
3070 LV2Plugin::Impl::designated_input (const char* uri, void** bufptrs[], void** bufptr)
3072 const LilvPort* port = NULL;
3073 LilvNode* designation = lilv_new_uri(_world.world, uri);
3074 port = lilv_plugin_get_port_by_designation(
3075 plugin, _world.lv2_InputPort, designation);
3076 lilv_node_free(designation);
3078 bufptrs[lilv_port_get_index(plugin, port)] = bufptr;
3083 static bool lv2_filter (const string& str, void* /*arg*/)
3085 /* Not a dotfile, has a prefix before a period, suffix is "lv2" */
3087 return str[0] != '.' && (str.length() > 3 && str.find (".lv2") == (str.length() - 4));
3091 LV2World::LV2World()
3092 : world(lilv_world_new())
3093 , _bundle_checked(false)
3095 atom_AtomPort = lilv_new_uri(world, LV2_ATOM__AtomPort);
3096 atom_Chunk = lilv_new_uri(world, LV2_ATOM__Chunk);
3097 atom_Sequence = lilv_new_uri(world, LV2_ATOM__Sequence);
3098 atom_bufferType = lilv_new_uri(world, LV2_ATOM__bufferType);
3099 atom_supports = lilv_new_uri(world, LV2_ATOM__supports);
3100 atom_eventTransfer = lilv_new_uri(world, LV2_ATOM__eventTransfer);
3101 ev_EventPort = lilv_new_uri(world, LILV_URI_EVENT_PORT);
3102 ext_logarithmic = lilv_new_uri(world, LV2_PORT_PROPS__logarithmic);
3103 ext_notOnGUI = lilv_new_uri(world, LV2_PORT_PROPS__notOnGUI);
3104 ext_expensive = lilv_new_uri(world, LV2_PORT_PROPS__expensive);
3105 ext_causesArtifacts= lilv_new_uri(world, LV2_PORT_PROPS__causesArtifacts);
3106 ext_notAutomatic = lilv_new_uri(world, LV2_PORT_PROPS__notAutomatic);
3107 ext_rangeSteps = lilv_new_uri(world, LV2_PORT_PROPS__rangeSteps);
3108 groups_group = lilv_new_uri(world, LV2_PORT_GROUPS__group);
3109 groups_element = lilv_new_uri(world, LV2_PORT_GROUPS__element);
3110 lv2_AudioPort = lilv_new_uri(world, LILV_URI_AUDIO_PORT);
3111 lv2_ControlPort = lilv_new_uri(world, LILV_URI_CONTROL_PORT);
3112 lv2_InputPort = lilv_new_uri(world, LILV_URI_INPUT_PORT);
3113 lv2_OutputPort = lilv_new_uri(world, LILV_URI_OUTPUT_PORT);
3114 lv2_inPlaceBroken = lilv_new_uri(world, LV2_CORE__inPlaceBroken);
3115 lv2_isSideChain = lilv_new_uri(world, LV2_CORE_PREFIX "isSideChain");
3116 lv2_index = lilv_new_uri(world, LV2_CORE__index);
3117 lv2_integer = lilv_new_uri(world, LV2_CORE__integer);
3118 lv2_default = lilv_new_uri(world, LV2_CORE__default);
3119 lv2_minimum = lilv_new_uri(world, LV2_CORE__minimum);
3120 lv2_maximum = lilv_new_uri(world, LV2_CORE__maximum);
3121 lv2_reportsLatency = lilv_new_uri(world, LV2_CORE__reportsLatency);
3122 lv2_sampleRate = lilv_new_uri(world, LV2_CORE__sampleRate);
3123 lv2_toggled = lilv_new_uri(world, LV2_CORE__toggled);
3124 lv2_designation = lilv_new_uri(world, LV2_CORE__designation);
3125 lv2_enumeration = lilv_new_uri(world, LV2_CORE__enumeration);
3126 lv2_freewheeling = lilv_new_uri(world, LV2_CORE__freeWheeling);
3127 midi_MidiEvent = lilv_new_uri(world, LILV_URI_MIDI_EVENT);
3128 rdfs_comment = lilv_new_uri(world, LILV_NS_RDFS "comment");
3129 rdfs_label = lilv_new_uri(world, LILV_NS_RDFS "label");
3130 rdfs_range = lilv_new_uri(world, LILV_NS_RDFS "range");
3131 rsz_minimumSize = lilv_new_uri(world, LV2_RESIZE_PORT__minimumSize);
3132 time_Position = lilv_new_uri(world, LV2_TIME__Position);
3133 ui_GtkUI = lilv_new_uri(world, LV2_UI__GtkUI);
3134 ui_external = lilv_new_uri(world, "http://lv2plug.in/ns/extensions/ui#external");
3135 ui_externalkx = lilv_new_uri(world, "http://kxstudio.sf.net/ns/lv2ext/external-ui#Widget");
3136 units_unit = lilv_new_uri(world, LV2_UNITS__unit);
3137 units_render = lilv_new_uri(world, LV2_UNITS__render);
3138 units_hz = lilv_new_uri(world, LV2_UNITS__hz);
3139 units_midiNote = lilv_new_uri(world, LV2_UNITS__midiNote);
3140 units_db = lilv_new_uri(world, LV2_UNITS__db);
3141 patch_writable = lilv_new_uri(world, LV2_PATCH__writable);
3142 patch_Message = lilv_new_uri(world, LV2_PATCH__Message);
3144 lv2_noSampleAccurateCtrl = lilv_new_uri(world, "http://ardour.org/lv2/ext#noSampleAccurateControls"); // deprecated 2016-09-18
3145 auto_can_write_automatation = lilv_new_uri(world, LV2_AUTOMATE_URI__can_write);
3146 auto_automation_control = lilv_new_uri(world, LV2_AUTOMATE_URI__control);
3147 auto_automation_controlled = lilv_new_uri(world, LV2_AUTOMATE_URI__controlled);
3148 auto_automation_controller = lilv_new_uri(world, LV2_AUTOMATE_URI__controller);
3150 #ifdef HAVE_LV2_1_2_0
3151 bufz_powerOf2BlockLength = lilv_new_uri(world, LV2_BUF_SIZE__powerOf2BlockLength);
3152 bufz_fixedBlockLength = lilv_new_uri(world, LV2_BUF_SIZE__fixedBlockLength);
3153 bufz_nominalBlockLength = lilv_new_uri(world, "http://lv2plug.in/ns/ext/buf-size#nominalBlockLength");
3154 bufz_coarseBlockLength = lilv_new_uri(world, "http://lv2plug.in/ns/ext/buf-size#coarseBlockLength");
3159 LV2World::~LV2World()
3164 #ifdef HAVE_LV2_1_2_0
3165 lilv_node_free(bufz_coarseBlockLength);
3166 lilv_node_free(bufz_nominalBlockLength);
3167 lilv_node_free(bufz_fixedBlockLength);
3168 lilv_node_free(bufz_powerOf2BlockLength);
3171 lilv_node_free(lv2_noSampleAccurateCtrl);
3172 lilv_node_free(auto_can_write_automatation);
3173 lilv_node_free(auto_automation_control);
3174 lilv_node_free(auto_automation_controlled);
3175 lilv_node_free(auto_automation_controller);
3177 lilv_node_free(patch_Message);
3178 lilv_node_free(patch_writable);
3179 lilv_node_free(units_hz);
3180 lilv_node_free(units_midiNote);
3181 lilv_node_free(units_db);
3182 lilv_node_free(units_unit);
3183 lilv_node_free(units_render);
3184 lilv_node_free(ui_externalkx);
3185 lilv_node_free(ui_external);
3186 lilv_node_free(ui_GtkUI);
3187 lilv_node_free(time_Position);
3188 lilv_node_free(rsz_minimumSize);
3189 lilv_node_free(rdfs_comment);
3190 lilv_node_free(rdfs_label);
3191 lilv_node_free(rdfs_range);
3192 lilv_node_free(midi_MidiEvent);
3193 lilv_node_free(lv2_designation);
3194 lilv_node_free(lv2_enumeration);
3195 lilv_node_free(lv2_freewheeling);
3196 lilv_node_free(lv2_toggled);
3197 lilv_node_free(lv2_sampleRate);
3198 lilv_node_free(lv2_reportsLatency);
3199 lilv_node_free(lv2_index);
3200 lilv_node_free(lv2_integer);
3201 lilv_node_free(lv2_isSideChain);
3202 lilv_node_free(lv2_inPlaceBroken);
3203 lilv_node_free(lv2_OutputPort);
3204 lilv_node_free(lv2_InputPort);
3205 lilv_node_free(lv2_ControlPort);
3206 lilv_node_free(lv2_AudioPort);
3207 lilv_node_free(groups_group);
3208 lilv_node_free(groups_element);
3209 lilv_node_free(ext_rangeSteps);
3210 lilv_node_free(ext_notAutomatic);
3211 lilv_node_free(ext_causesArtifacts);
3212 lilv_node_free(ext_expensive);
3213 lilv_node_free(ext_notOnGUI);
3214 lilv_node_free(ext_logarithmic);
3215 lilv_node_free(ev_EventPort);
3216 lilv_node_free(atom_supports);
3217 lilv_node_free(atom_eventTransfer);
3218 lilv_node_free(atom_bufferType);
3219 lilv_node_free(atom_Sequence);
3220 lilv_node_free(atom_Chunk);
3221 lilv_node_free(atom_AtomPort);
3222 lilv_world_free(world);
3227 LV2World::load_bundled_plugins(bool verbose)
3229 if (!_bundle_checked) {
3231 cout << "Scanning folders for bundled LV2s: " << ARDOUR::lv2_bundled_search_path().to_string() << endl;
3234 vector<string> plugin_objects;
3235 find_paths_matching_filter (plugin_objects, ARDOUR::lv2_bundled_search_path(), lv2_filter, 0, true, true, true);
3236 for ( vector<string>::iterator x = plugin_objects.begin(); x != plugin_objects.end (); ++x) {
3237 #ifdef PLATFORM_WINDOWS
3238 string uri = "file:///" + *x + "/";
3240 string uri = "file://" + *x + "/";
3242 LilvNode *node = lilv_new_uri(world, uri.c_str());
3243 lilv_world_load_bundle(world, node);
3244 lilv_node_free(node);
3247 lilv_world_load_all(world);
3248 _bundle_checked = true;
3252 LV2PluginInfo::LV2PluginInfo (const char* plugin_uri)
3255 _plugin_uri = strdup(plugin_uri);
3258 LV2PluginInfo::~LV2PluginInfo()
3265 LV2PluginInfo::load(Session& session)
3269 const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
3270 LilvNode* uri = lilv_new_uri(_world.world, _plugin_uri);
3271 if (!uri) { throw failed_constructor(); }
3272 const LilvPlugin* lp = lilv_plugins_get_by_uri(plugins, uri);
3273 if (!lp) { throw failed_constructor(); }
3274 plugin.reset(new LV2Plugin(session.engine(), session, lp, session.frame_rate()));
3275 lilv_node_free(uri);
3276 plugin->set_info(PluginInfoPtr(shared_from_this ()));
3278 } catch (failed_constructor& err) {
3279 return PluginPtr((Plugin*)0);
3285 std::vector<Plugin::PresetRecord>
3286 LV2PluginInfo::get_presets (bool /*user_only*/) const
3288 std::vector<Plugin::PresetRecord> p;
3289 #ifndef NO_PLUGIN_STATE
3290 const LilvPlugin* lp = NULL;
3293 const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
3294 LilvNode* uri = lilv_new_uri(_world.world, _plugin_uri);
3295 if (!uri) { throw failed_constructor(); }
3296 lp = lilv_plugins_get_by_uri(plugins, uri);
3297 if (!lp) { throw failed_constructor(); }
3298 lilv_node_free(uri);
3299 } catch (failed_constructor& err) {
3303 // see LV2Plugin::find_presets
3304 LilvNode* lv2_appliesTo = lilv_new_uri(_world.world, LV2_CORE__appliesTo);
3305 LilvNode* pset_Preset = lilv_new_uri(_world.world, LV2_PRESETS__Preset);
3306 LilvNode* rdfs_label = lilv_new_uri(_world.world, LILV_NS_RDFS "label");
3308 LilvNodes* presets = lilv_plugin_get_related(lp, pset_Preset);
3309 LILV_FOREACH(nodes, i, presets) {
3310 const LilvNode* preset = lilv_nodes_get(presets, i);
3311 lilv_world_load_resource(_world.world, preset);
3312 LilvNode* name = get_value(_world.world, preset, rdfs_label);
3313 bool userpreset = true; // TODO
3315 p.push_back (Plugin::PresetRecord (lilv_node_as_string(preset), lilv_node_as_string(name), userpreset));
3316 lilv_node_free(name);
3319 lilv_nodes_free(presets);
3320 lilv_node_free(rdfs_label);
3321 lilv_node_free(pset_Preset);
3322 lilv_node_free(lv2_appliesTo);
3328 LV2PluginInfo::in_category (const std::string &c) const
3330 // TODO use untranslated lilv_plugin_get_class()
3331 // match gtk2_ardour/plugin_selector.cc
3332 return category == c;
3336 LV2PluginInfo::is_instrument () const
3338 if (category == "Instrument") {
3342 /* until we make sure that category remains untranslated in the lv2.ttl spec
3343 * and until most instruments also classify themselves as such, there's a 2nd check:
3345 if (n_inputs.n_midi() > 0 && n_inputs.n_audio() == 0 && n_outputs.n_audio() > 0) {
3353 LV2PluginInfo::discover()
3356 world.load_bundled_plugins();
3357 _world.load_bundled_plugins(true);
3359 PluginInfoList* plugs = new PluginInfoList;
3360 const LilvPlugins* plugins = lilv_world_get_all_plugins(world.world);
3362 LILV_FOREACH(plugins, i, plugins) {
3363 const LilvPlugin* p = lilv_plugins_get(plugins, i);
3364 const LilvNode* pun = lilv_plugin_get_uri(p);
3366 LV2PluginInfoPtr info(new LV2PluginInfo(lilv_node_as_string(pun)));
3368 LilvNode* name = lilv_plugin_get_name(p);
3369 if (!name || !lilv_plugin_get_port_by_index(p, 0)) {
3370 warning << "Ignoring invalid LV2 plugin "
3371 << lilv_node_as_string(lilv_plugin_get_uri(p))
3376 if (lilv_plugin_has_feature(p, world.lv2_inPlaceBroken)) {
3377 warning << string_compose(
3378 _("Ignoring LV2 plugin \"%1\" since it cannot do inplace processing."),
3379 lilv_node_as_string(name)) << endmsg;
3380 lilv_node_free(name);
3384 #ifdef HAVE_LV2_1_2_0
3385 LilvNodes *required_features = lilv_plugin_get_required_features (p);
3386 if (lilv_nodes_contains (required_features, world.bufz_powerOf2BlockLength) ||
3387 lilv_nodes_contains (required_features, world.bufz_fixedBlockLength)
3389 warning << string_compose(
3390 _("Ignoring LV2 plugin \"%1\" because its buffer-size requirements cannot be satisfied."),
3391 lilv_node_as_string(name)) << endmsg;
3392 lilv_nodes_free(required_features);
3393 lilv_node_free(name);
3396 lilv_nodes_free(required_features);
3401 info->name = string(lilv_node_as_string(name));
3402 lilv_node_free(name);
3403 ARDOUR::PluginScanMessage(_("LV2"), info->name, false);
3405 const LilvPluginClass* pclass = lilv_plugin_get_class(p);
3406 const LilvNode* label = lilv_plugin_class_get_label(pclass);
3407 info->category = lilv_node_as_string(label);
3409 LilvNode* author_name = lilv_plugin_get_author_name(p);
3410 info->creator = author_name ? string(lilv_node_as_string(author_name)) : "Unknown";
3411 lilv_node_free(author_name);
3413 info->path = "/NOPATH"; // Meaningless for LV2
3415 /* count atom-event-ports that feature
3416 * atom:supports <http://lv2plug.in/ns/ext/midi#MidiEvent>
3418 * TODO: nicely ask drobilla to make a lilv_ call for that
3420 int count_midi_out = 0;
3421 int count_midi_in = 0;
3422 for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
3423 const LilvPort* port = lilv_plugin_get_port_by_index(p, i);
3424 if (lilv_port_is_a(p, port, world.atom_AtomPort)) {
3425 LilvNodes* buffer_types = lilv_port_get_value(
3426 p, port, world.atom_bufferType);
3427 LilvNodes* atom_supports = lilv_port_get_value(
3428 p, port, world.atom_supports);
3430 if (lilv_nodes_contains(buffer_types, world.atom_Sequence)
3431 && lilv_nodes_contains(atom_supports, world.midi_MidiEvent)) {
3432 if (lilv_port_is_a(p, port, world.lv2_InputPort)) {
3435 if (lilv_port_is_a(p, port, world.lv2_OutputPort)) {
3439 lilv_nodes_free(buffer_types);
3440 lilv_nodes_free(atom_supports);
3444 info->n_inputs.set_audio(
3445 lilv_plugin_get_num_ports_of_class(
3446 p, world.lv2_InputPort, world.lv2_AudioPort, NULL));
3447 info->n_inputs.set_midi(
3448 lilv_plugin_get_num_ports_of_class(
3449 p, world.lv2_InputPort, world.ev_EventPort, NULL)
3452 info->n_outputs.set_audio(
3453 lilv_plugin_get_num_ports_of_class(
3454 p, world.lv2_OutputPort, world.lv2_AudioPort, NULL));
3455 info->n_outputs.set_midi(
3456 lilv_plugin_get_num_ports_of_class(
3457 p, world.lv2_OutputPort, world.ev_EventPort, NULL)
3460 info->unique_id = lilv_node_as_uri(lilv_plugin_get_uri(p));
3461 info->index = 0; // Meaningless for LV2
3463 plugs->push_back(info);