Implement latest buf-size extension via new options extension.
[ardour.git] / libs / ardour / lv2_plugin.cc
1 /*
2     Copyright (C) 2008-2012 Paul Davis
3     Author: David Robillard
4
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.
9
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.
14
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.
18 */
19
20 #include <string>
21 #include <vector>
22
23 #include <cmath>
24 #include <cstdlib>
25 #include <cstring>
26
27 #include <giomm/file.h>
28 #include <glib/gprintf.h>
29 #include <glibmm.h>
30
31 #include <boost/utility.hpp>
32
33 #include "pbd/compose.h"
34 #include "pbd/error.h"
35 #include "pbd/xml++.h"
36
37 #include "libardour-config.h"
38
39 #include "ardour/types.h"
40 #include "ardour/audio_buffer.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/debug.h"
43 #include "ardour/lv2_plugin.h"
44 #include "ardour/session.h"
45 #include "ardour/tempo.h"
46 #include "ardour/worker.h"
47
48 #include "i18n.h"
49 #include <locale.h>
50
51 #include <lilv/lilv.h>
52
53 #include "lv2/lv2plug.in/ns/ext/atom/atom.h"
54 #include "lv2/lv2plug.in/ns/ext/log/log.h"
55 #include "lv2/lv2plug.in/ns/ext/options/options.h"
56 #include "lv2/lv2plug.in/ns/ext/port-props/port-props.h"
57 #include "lv2/lv2plug.in/ns/ext/presets/presets.h"
58 #include "lv2/lv2plug.in/ns/ext/state/state.h"
59 #include "lv2/lv2plug.in/ns/ext/time/time.h"
60 #include "lv2/lv2plug.in/ns/ext/worker/worker.h"
61 #include "lv2/lv2plug.in/ns/extensions/ui/ui.h"
62 #ifdef HAVE_NEW_LV2
63 #include "lv2/lv2plug.in/ns/ext/buf-size/buf-size.h"
64 #endif
65
66 #include "lv2_evbuf.h"
67
68 #ifdef HAVE_SUIL
69 #include <suil/suil.h>
70 #endif
71
72 using namespace std;
73 using namespace ARDOUR;
74 using namespace PBD;
75
76 URIMap LV2Plugin::_uri_map;
77 uint32_t LV2Plugin::_midi_event_type = _uri_map.uri_to_id(
78         "http://lv2plug.in/ns/ext/midi#MidiEvent");
79 uint32_t LV2Plugin::_chunk_type = _uri_map.uri_to_id(
80         LV2_ATOM__Chunk);
81 uint32_t LV2Plugin::_sequence_type = _uri_map.uri_to_id(
82         LV2_ATOM__Sequence);
83 uint32_t LV2Plugin::_event_transfer_type = _uri_map.uri_to_id(
84         LV2_ATOM__eventTransfer);
85 uint32_t LV2Plugin::_path_type = _uri_map.uri_to_id(
86         LV2_ATOM__Path);
87 uint32_t LV2Plugin::_log_Error = _uri_map.uri_to_id(
88         LV2_LOG__Error);
89 uint32_t LV2Plugin::_log_Warning = _uri_map.uri_to_id(
90         LV2_LOG__Warning);
91 uint32_t LV2Plugin::_log_Note = _uri_map.uri_to_id(
92         LV2_LOG__Note);
93
94 class LV2World : boost::noncopyable {
95 public:
96         LV2World ();
97         ~LV2World ();
98
99         LilvWorld* world;
100
101         LilvNode* atom_AtomPort;
102         LilvNode* atom_Chunk;
103         LilvNode* atom_Sequence;
104         LilvNode* atom_bufferType;
105         LilvNode* atom_supports;
106         LilvNode* atom_eventTransfer;
107         LilvNode* ev_EventPort;
108         LilvNode* ext_logarithmic;
109         LilvNode* lv2_AudioPort;
110         LilvNode* lv2_ControlPort;
111         LilvNode* lv2_InputPort;
112         LilvNode* lv2_OutputPort;
113         LilvNode* lv2_enumeration;
114         LilvNode* lv2_inPlaceBroken;
115         LilvNode* lv2_integer;
116         LilvNode* lv2_sampleRate;
117         LilvNode* lv2_toggled;
118         LilvNode* midi_MidiEvent;
119         LilvNode* rdfs_comment;
120         LilvNode* ui_GtkUI;
121         LilvNode* ui_external;
122 };
123
124 static LV2World _world;
125
126 /* worker extension */
127
128 /** Called by the plugin to schedule non-RT work. */
129 static LV2_Worker_Status
130 work_schedule(LV2_Worker_Schedule_Handle handle,
131               uint32_t                   size,
132               const void*                data)
133 {
134         LV2Plugin* plugin = (LV2Plugin*)handle;
135         if (plugin->session().engine().freewheeling()) {
136                 // Freewheeling, do the work immediately in this (audio) thread
137                 return (LV2_Worker_Status)plugin->work(size, data);
138         } else {
139                 // Enqueue message for the worker thread
140                 return plugin->worker()->schedule(size, data) ?
141                         LV2_WORKER_SUCCESS : LV2_WORKER_ERR_UNKNOWN;
142         }
143 }
144
145 /** Called by the plugin to respond to non-RT work. */
146 static LV2_Worker_Status
147 work_respond(LV2_Worker_Respond_Handle handle,
148              uint32_t                  size,
149              const void*               data)
150 {
151         LV2Plugin* plugin = (LV2Plugin*)handle;
152         if (plugin->session().engine().freewheeling()) {
153                 // Freewheeling, respond immediately in this (audio) thread
154                 return (LV2_Worker_Status)plugin->work_response(size, data);
155         } else {
156                 // Enqueue response for the worker
157                 return plugin->worker()->respond(size, data) ?
158                         LV2_WORKER_SUCCESS : LV2_WORKER_ERR_UNKNOWN;
159         }
160 }
161
162 /* log extension */
163
164 static int
165 log_vprintf(LV2_Log_Handle handle,
166             LV2_URID       type,
167             const char*    fmt,
168             va_list        args)
169 {
170         char* str = NULL;
171         const int ret = g_vasprintf(&str, fmt, args);
172         if (type == LV2Plugin::_log_Error) {
173                 error << str << endmsg;
174         } else if (type == LV2Plugin::_log_Warning) {
175                 warning << str << endmsg;
176         } else if (type == LV2Plugin::_log_Note) {
177                 info << str << endmsg;
178         }
179         // TODO: Togglable log:Trace message support
180         return ret;
181 }
182
183 static int
184 log_printf(LV2_Log_Handle handle,
185            LV2_URID       type,
186            const char*    fmt, ...)
187 {
188         va_list args;
189         va_start(args, fmt);
190         const int ret = log_vprintf(handle, type, fmt, args);
191         va_end(args);
192         return ret;
193 }
194
195 struct LV2Plugin::Impl {
196         Impl() : plugin(0), ui(0), ui_type(0), name(0), author(0), instance(0)
197                , work_iface(0)
198                , state(0)
199         {}
200
201         /** Find the LV2 input port with the given designation.
202          * If found, bufptrs[port_index] will be set to bufptr.
203          */
204         LilvPort* designated_input (const char* uri, void** bufptrs[], void** bufptr);
205
206         const LilvPlugin*           plugin;
207         const LilvUI*               ui;
208         const LilvNode*             ui_type;
209         LilvNode*                   name;
210         LilvNode*                   author;
211         LilvInstance*               instance;
212         const LV2_Worker_Interface* work_iface;
213         LilvState*                  state;
214 };
215
216 LV2Plugin::LV2Plugin (AudioEngine& engine,
217                       Session&     session,
218                       const void*  c_plugin,
219                       framecnt_t   rate)
220         : Plugin (engine, session)
221         , Workee ()
222         , _impl(new Impl())
223         , _features(NULL)
224         , _worker(NULL)
225         , _insert_id("0")
226 {
227         init(c_plugin, rate);
228 }
229
230 LV2Plugin::LV2Plugin (const LV2Plugin& other)
231         : Plugin (other)
232         , Workee ()
233         , _impl(new Impl())
234         , _features(NULL)
235         , _worker(NULL)
236         , _insert_id(other._insert_id)
237 {
238         init(other._impl->plugin, other._sample_rate);
239
240         for (uint32_t i = 0; i < parameter_count(); ++i) {
241                 _control_data[i] = other._shadow_data[i];
242                 _shadow_data[i]  = other._shadow_data[i];
243         }
244 }
245
246 void
247 LV2Plugin::init(const void* c_plugin, framecnt_t rate)
248 {
249         DEBUG_TRACE(DEBUG::LV2, "init\n");
250
251         _impl->plugin           = (const LilvPlugin*)c_plugin;
252         _impl->ui               = NULL;
253         _impl->ui_type          = NULL;
254         _to_ui                  = NULL;
255         _from_ui                = NULL;
256         _control_data           = 0;
257         _shadow_data            = 0;
258         _atom_ev_buffers        = 0;
259         _ev_buffers             = 0;
260         _bpm_control_port       = 0;
261         _freewheel_control_port = 0;
262         _latency_control_port   = 0;
263         _block_length           = _engine.frames_per_cycle();
264         _seq_size               = _engine.raw_buffer_size(DataType::MIDI);
265         _state_version          = 0;
266         _was_activated          = false;
267         _has_state_interface    = false;
268
269         _instance_access_feature.URI = "http://lv2plug.in/ns/ext/instance-access";
270         _data_access_feature.URI     = "http://lv2plug.in/ns/ext/data-access";
271         _make_path_feature.URI       = LV2_STATE__makePath;
272         _log_feature.URI             = LV2_LOG__log;
273         _work_schedule_feature.URI   = LV2_WORKER__schedule;
274         _work_schedule_feature.data  = NULL;
275
276         const LilvPlugin* plugin = _impl->plugin;
277
278         LilvNode* state_iface_uri = lilv_new_uri(_world.world, LV2_STATE__interface);
279         LilvNode* state_uri       = lilv_new_uri(_world.world, LV2_STATE_URI);
280         _has_state_interface =
281                 // What plugins should have (lv2:extensionData state:Interface)
282                 lilv_plugin_has_extension_data(plugin, state_iface_uri)
283                 // What some outdated/incorrect ones have
284                 || lilv_plugin_has_feature(plugin, state_uri);
285         lilv_node_free(state_uri);
286         lilv_node_free(state_iface_uri);
287
288         _features    = (LV2_Feature**)calloc(10, sizeof(LV2_Feature*));
289         _features[0] = &_instance_access_feature;
290         _features[1] = &_data_access_feature;
291         _features[2] = &_make_path_feature;
292         _features[3] = _uri_map.uri_map_feature();
293         _features[4] = _uri_map.urid_map_feature();
294         _features[5] = _uri_map.urid_unmap_feature();
295         _features[6] = &_log_feature;
296
297         unsigned n_features = 7;
298 #ifdef HAVE_NEW_LV2
299         LV2_URID atom_Int = _uri_map.uri_to_id(LV2_ATOM__Int);
300         LV2_Options_Option options[] = {
301                 { _uri_map.uri_to_id(LV2_BUF_SIZE__minBlockLength),
302                   sizeof(int32_t), atom_Int, &_block_length },
303                 { _uri_map.uri_to_id(LV2_BUF_SIZE__maxBlockLength),
304                   sizeof(int32_t), atom_Int, &_block_length },
305                 { _uri_map.uri_to_id(LV2_BUF_SIZE__sequenceSize),
306                   sizeof(int32_t), atom_Int, &_seq_size },
307                 { 0, 0, 0, NULL }
308         };
309
310         _options_feature.URI    = LV2_OPTIONS__options;
311         _options_feature.data   = options;
312         _features[n_features++] = &_options_feature;
313 #endif
314
315         LV2_State_Make_Path* make_path = (LV2_State_Make_Path*)malloc(
316                 sizeof(LV2_State_Make_Path));
317         make_path->handle = this;
318         make_path->path = &lv2_state_make_path;
319         _make_path_feature.data = make_path;
320
321         LV2_Log_Log* log = (LV2_Log_Log*)malloc(sizeof(LV2_Log_Log));
322         log->handle  = this;
323         log->printf  = &log_printf;
324         log->vprintf = &log_vprintf;
325         _log_feature.data = log;
326
327         LilvNode* worker_schedule = lilv_new_uri(_world.world, LV2_WORKER__schedule);
328         if (lilv_plugin_has_feature(plugin, worker_schedule)) {
329                 LV2_Worker_Schedule* schedule = (LV2_Worker_Schedule*)malloc(
330                         sizeof(LV2_Worker_Schedule));
331                 _worker                     = new Worker(this, 4096);
332                 schedule->handle            = this;
333                 schedule->schedule_work     = work_schedule;
334                 _work_schedule_feature.data = schedule;
335                 _features[n_features++]     = &_work_schedule_feature;
336         }
337         lilv_node_free(worker_schedule);
338
339         _impl->instance = lilv_plugin_instantiate(plugin, rate, _features);
340         _impl->name     = lilv_plugin_get_name(plugin);
341         _impl->author   = lilv_plugin_get_author_name(plugin);
342
343         if (_impl->instance == 0) {
344                 error << _("LV2: Failed to instantiate plugin ") << uri() << endmsg;
345                 throw failed_constructor();
346         }
347
348         _instance_access_feature.data              = (void*)_impl->instance->lv2_handle;
349         _data_access_extension_data.extension_data = _impl->instance->lv2_descriptor->extension_data;
350         _data_access_feature.data                  = &_data_access_extension_data;
351
352         _impl->work_iface = (const LV2_Worker_Interface*)extension_data(
353                 LV2_WORKER__interface);
354
355         if (lilv_plugin_has_feature(plugin, _world.lv2_inPlaceBroken)) {
356                 error << string_compose(
357                     _("LV2: \"%1\" cannot be used, since it cannot do inplace processing"),
358                     lilv_node_as_string(_impl->name)) << endmsg;
359                 lilv_node_free(_impl->name);
360                 lilv_node_free(_impl->author);
361                 throw failed_constructor();
362         }
363
364         _sample_rate = rate;
365
366         const uint32_t num_ports = this->num_ports();
367         for (uint32_t i = 0; i < num_ports; ++i) {
368                 const LilvPort* port  = lilv_plugin_get_port_by_index(_impl->plugin, i);
369                 PortFlags       flags = 0;
370
371                 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_OutputPort)) {
372                         flags |= PORT_OUTPUT;
373                 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_InputPort)) {
374                         flags |= PORT_INPUT;
375                 } else {
376                         error << string_compose(
377                                 "LV2: \"%1\" port %2 is neither input nor output",
378                                 lilv_node_as_string(_impl->name), i) << endmsg;
379                         throw failed_constructor();
380                 }
381
382                 if (lilv_port_is_a(_impl->plugin, port, _world.lv2_ControlPort)) {
383                         flags |= PORT_CONTROL;
384                 } else if (lilv_port_is_a(_impl->plugin, port, _world.lv2_AudioPort)) {
385                         flags |= PORT_AUDIO;
386                 } else if (lilv_port_is_a(_impl->plugin, port, _world.ev_EventPort)) {
387                         flags |= PORT_EVENT;
388                 } else if (lilv_port_is_a(_impl->plugin, port, _world.atom_AtomPort)) {
389                         LilvNodes* buffer_types = lilv_port_get_value(
390                                 _impl->plugin, port, _world.atom_bufferType);
391                         LilvNodes* atom_supports = lilv_port_get_value(
392                                 _impl->plugin, port, _world.atom_supports);
393
394                                 if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)
395                                                 && lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)
396                                                 ) {
397                                         flags |= PORT_MESSAGE;
398                                 } else {
399                                         flags |= PORT_ATOM;
400                                 }
401                         lilv_nodes_free(buffer_types);
402                         lilv_nodes_free(atom_supports);
403                 } else {
404                         error << string_compose(
405                                 "LV2: \"%1\" port %2 has no known data type",
406                                 lilv_node_as_string(_impl->name), i) << endmsg;
407                         throw failed_constructor();
408                 }
409
410                 _port_flags.push_back(flags);
411         }
412
413         _control_data = new float[num_ports];
414         _shadow_data  = new float[num_ports];
415         _defaults     = new float[num_ports];
416         _ev_buffers   = new LV2_Evbuf*[num_ports];
417         memset(_ev_buffers, 0, sizeof(LV2_Evbuf*) * num_ports);
418
419         const bool     latent        = lilv_plugin_has_latency(plugin);
420         const uint32_t latency_index = (latent)
421                 ? lilv_plugin_get_latency_port_index(plugin)
422                 : 0;
423
424         // Build an array of pointers to special parameter buffers
425         void*** params = new void**[num_ports];
426         for (uint32_t i = 0; i < num_ports; ++i) {
427                 params[i] = NULL;
428         }
429         _impl->designated_input (LV2_TIME__beatsPerMinute, params, (void**)&_bpm_control_port);
430         _impl->designated_input (LV2_CORE__freeWheeling, params, (void**)&_freewheel_control_port);
431
432         for (uint32_t i = 0; i < num_ports; ++i) {
433                 const LilvPort* port = lilv_plugin_get_port_by_index(plugin, i);
434                 const LilvNode* sym  = lilv_port_get_symbol(plugin, port);
435
436                 // Store index in map so we can look up index by symbol
437                 _port_indices.insert(std::make_pair(lilv_node_as_string(sym), i));
438
439                 // Get range and default value if applicable
440                 if (parameter_is_control(i)) {
441                         LilvNode* def;
442                         lilv_port_get_range(plugin, port, &def, NULL, NULL);
443                         _defaults[i] = def ? lilv_node_as_float(def) : 0.0f;
444                         if (lilv_port_has_property (plugin, port, _world.lv2_sampleRate)) {
445                                 _defaults[i] *= _session.frame_rate ();
446                         }
447                         lilv_node_free(def);
448
449                         lilv_instance_connect_port(_impl->instance, i, &_control_data[i]);
450
451                         if (latent && i == latency_index) {
452                                 _latency_control_port  = &_control_data[i];
453                                 *_latency_control_port = 0;
454                         }
455
456                         if (parameter_is_input(i)) {
457                                 _shadow_data[i] = default_value(i);
458                                 if (params[i]) {
459                                         *params[i] = (void*)&_shadow_data[i];
460                                 }
461                         }
462                 } else {
463                         _defaults[i] = 0.0f;
464                 }
465         }
466
467         delete[] params;
468
469         LilvUIs* uis = lilv_plugin_get_uis(plugin);
470         if (lilv_uis_size(uis) > 0) {
471 #ifdef HAVE_SUIL
472                 // Look for embeddable UI
473                 LILV_FOREACH(uis, u, uis) {
474                         const LilvUI*   this_ui      = lilv_uis_get(uis, u);
475                         const LilvNode* this_ui_type = NULL;
476                         if (lilv_ui_is_supported(this_ui,
477                                                  suil_ui_supported,
478                                                  _world.ui_GtkUI,
479                                                  &this_ui_type)) {
480                                 // TODO: Multiple UI support
481                                 _impl->ui      = this_ui;
482                                 _impl->ui_type = this_ui_type;
483                                 break;
484                         }
485                 }
486 #else
487                 // Look for Gtk native UI
488                 LILV_FOREACH(uis, i, uis) {
489                         const LilvUI* ui = lilv_uis_get(uis, i);
490                         if (lilv_ui_is_a(ui, _world.ui_GtkUI)) {
491                                 _impl->ui      = ui;
492                                 _impl->ui_type = _world.ui_GtkUI;
493                                 break;
494                         }
495                 }
496 #endif
497
498                 // If Gtk UI is not available, try to find external UI
499                 if (!_impl->ui) {
500                         LILV_FOREACH(uis, i, uis) {
501                                 const LilvUI* ui = lilv_uis_get(uis, i);
502                                 if (lilv_ui_is_a(ui, _world.ui_external)) {
503                                         _impl->ui      = ui;
504                                         _impl->ui_type = _world.ui_external;
505                                         break;
506                                 }
507                         }
508                 }
509         }
510
511         allocate_atom_event_buffers();
512         latency_compute_run();
513 }
514
515 LV2Plugin::~LV2Plugin ()
516 {
517         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 destroy\n", name()));
518
519         deactivate();
520         cleanup();
521
522         lilv_instance_free(_impl->instance);
523         lilv_node_free(_impl->name);
524         lilv_node_free(_impl->author);
525
526         free(_features);
527         free(_make_path_feature.data);
528         free(_work_schedule_feature.data);
529
530         delete _to_ui;
531         delete _from_ui;
532         delete _worker;
533
534         if (_atom_ev_buffers) {
535                 LV2_Evbuf**  b = _atom_ev_buffers;
536                 while (*b) {
537                         free(*b);
538                         b++;
539                 }
540                 free(_atom_ev_buffers);
541         }
542
543         delete [] _control_data;
544         delete [] _shadow_data;
545         delete [] _ev_buffers;
546 }
547
548 bool
549 LV2Plugin::is_external_ui() const
550 {
551         if (!_impl->ui) {
552                 return false;
553         }
554         return lilv_ui_is_a(_impl->ui, _world.ui_external);
555 }
556
557 bool
558 LV2Plugin::ui_is_resizable () const
559 {
560         const LilvNode* s   = lilv_ui_get_uri(_impl->ui);
561         LilvNode*       p   = lilv_new_uri(_world.world, LV2_CORE__optionalFeature);
562         LilvNode*       fs  = lilv_new_uri(_world.world, LV2_UI__fixedSize);
563         LilvNode*       nrs = lilv_new_uri(_world.world, LV2_UI__noUserResize);
564
565         LilvNodes* fs_matches = lilv_world_find_nodes(_world.world, s, p, fs);
566         LilvNodes* nrs_matches = lilv_world_find_nodes(_world.world, s, p, nrs);
567
568         lilv_nodes_free(nrs_matches);
569         lilv_nodes_free(fs_matches);
570         lilv_node_free(nrs);
571         lilv_node_free(fs);
572         lilv_node_free(p);
573
574         return !fs_matches && !nrs_matches;
575 }
576
577 string
578 LV2Plugin::unique_id() const
579 {
580         return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
581 }
582
583 const char*
584 LV2Plugin::uri() const
585 {
586         return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
587 }
588
589 const char*
590 LV2Plugin::label() const
591 {
592         return lilv_node_as_string(_impl->name);
593 }
594
595 const char*
596 LV2Plugin::name() const
597 {
598         return lilv_node_as_string(_impl->name);
599 }
600
601 const char*
602 LV2Plugin::maker() const
603 {
604         return _impl->author ? lilv_node_as_string (_impl->author) : "Unknown";
605 }
606
607 uint32_t
608 LV2Plugin::num_ports() const
609 {
610         return lilv_plugin_get_num_ports(_impl->plugin);
611 }
612
613 uint32_t
614 LV2Plugin::parameter_count() const
615 {
616         return lilv_plugin_get_num_ports(_impl->plugin);
617 }
618
619 float
620 LV2Plugin::default_value(uint32_t port)
621 {
622         return _defaults[port];
623 }
624
625 const char*
626 LV2Plugin::port_symbol(uint32_t index) const
627 {
628         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, index);
629         if (!port) {
630                 error << name() << ": Invalid port index " << index << endmsg;
631         }
632
633         const LilvNode* sym = lilv_port_get_symbol(_impl->plugin, port);
634         return lilv_node_as_string(sym);
635 }
636
637 uint32_t
638 LV2Plugin::port_index (const char* symbol) const
639 {
640         const map<string, uint32_t>::const_iterator i = _port_indices.find(symbol);
641         if (i != _port_indices.end()) {
642                 return  i->second;
643         } else {
644                 warning << string_compose(_("LV2: Unknown port %1"), symbol) << endmsg;
645                 return (uint32_t)-1;
646         }
647 }
648
649 void
650 LV2Plugin::set_parameter(uint32_t which, float val)
651 {
652         DEBUG_TRACE(DEBUG::LV2, string_compose(
653                             "%1 set parameter %2 to %3\n", name(), which, val));
654
655         if (which < lilv_plugin_get_num_ports(_impl->plugin)) {
656                 if (get_parameter (which) == val) {
657                         return;
658                 }
659
660                 _shadow_data[which] = val;
661         } else {
662                 warning << string_compose(
663                     _("Illegal parameter number used with plugin \"%1\". "
664                       "This is a bug in either %2 or the LV2 plugin <%3>"),
665                     name(), PROGRAM_NAME, unique_id()) << endmsg;
666         }
667
668         Plugin::set_parameter(which, val);
669 }
670
671 float
672 LV2Plugin::get_parameter(uint32_t which) const
673 {
674         if (parameter_is_input(which)) {
675                 return (float)_shadow_data[which];
676         } else {
677                 return (float)_control_data[which];
678         }
679         return 0.0f;
680 }
681
682 std::string
683 LV2Plugin::get_docs() const
684 {
685         LilvNodes* comments = lilv_plugin_get_value(_impl->plugin, _world.rdfs_comment);
686         if (comments) {
687                 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
688                 lilv_nodes_free(comments);
689                 return docs;
690         }
691
692         return "";
693 }
694
695 std::string
696 LV2Plugin::get_parameter_docs(uint32_t which) const
697 {
698         LilvNodes* comments = lilv_port_get_value(
699                 _impl->plugin,
700                 lilv_plugin_get_port_by_index(_impl->plugin, which),
701                 _world.rdfs_comment);
702
703         if (comments) {
704                 const std::string docs(lilv_node_as_string(lilv_nodes_get_first(comments)));
705                 lilv_nodes_free(comments);
706                 return docs;
707         }
708
709         return "";
710 }
711
712 uint32_t
713 LV2Plugin::nth_parameter(uint32_t n, bool& ok) const
714 {
715         ok = false;
716         for (uint32_t c = 0, x = 0; x < lilv_plugin_get_num_ports(_impl->plugin); ++x) {
717                 if (parameter_is_control(x)) {
718                         if (c++ == n) {
719                                 ok = true;
720                                 return x;
721                         }
722                 }
723         }
724
725         return 0;
726 }
727
728 const void*
729 LV2Plugin::extension_data (const char* uri) const
730 {
731         return lilv_instance_get_extension_data(_impl->instance, uri);
732 }
733
734 const void*
735 LV2Plugin::c_plugin ()
736 {
737         return _impl->plugin;
738 }
739
740 const void*
741 LV2Plugin::c_ui ()
742 {
743         return (const void*)_impl->ui;
744 }
745
746 const void*
747 LV2Plugin::c_ui_type ()
748 {
749         return (const void*)_impl->ui_type;
750 }
751
752 /** Directory for all plugin state. */
753 const std::string
754 LV2Plugin::plugin_dir() const
755 {
756         return Glib::build_filename(_session.plugins_dir(), _insert_id.to_s());
757 }
758
759 /** Directory for files created by the plugin (except during save). */
760 const std::string
761 LV2Plugin::scratch_dir() const
762 {
763         return Glib::build_filename(plugin_dir(), "scratch");
764 }
765
766 /** Directory for snapshots of files in the scratch directory. */
767 const std::string
768 LV2Plugin::file_dir() const
769 {
770         return Glib::build_filename(plugin_dir(), "files");
771 }
772
773 /** Directory to save state snapshot version @c num into. */
774 const std::string
775 LV2Plugin::state_dir(unsigned num) const
776 {
777         return Glib::build_filename(plugin_dir(), string_compose("state%1", num));
778 }
779
780 /** Implementation of state:makePath for files created at instantiation time.
781  * Note this is not used for files created at save time (Lilv deals with that).
782  */
783 char*
784 LV2Plugin::lv2_state_make_path(LV2_State_Make_Path_Handle handle,
785                                const char*                path)
786 {
787         LV2Plugin* me = (LV2Plugin*)handle;
788         if (me->_insert_id == PBD::ID("0")) {
789                 warning << string_compose(
790                         "File path \"%1\" requested but LV2 %2 has no insert ID",
791                         path, me->name()) << endmsg;
792                 return g_strdup(path);
793         }
794
795         const std::string abs_path = Glib::build_filename(me->scratch_dir(), path);
796         const std::string dirname  = Glib::path_get_dirname(abs_path);
797         g_mkdir_with_parents(dirname.c_str(), 0744);
798
799         DEBUG_TRACE(DEBUG::LV2, string_compose("new file path %1 => %2\n",
800                                                path, abs_path));
801
802         std::cerr << "MAKE PATH " << path
803                   << " => " << g_strndup(abs_path.c_str(), abs_path.length())
804                   << std::endl;
805         return g_strndup(abs_path.c_str(), abs_path.length());
806 }
807
808 static void
809 remove_directory(const std::string& path)
810 {
811         if (!Glib::file_test(path, Glib::FILE_TEST_IS_DIR)) {
812                 warning << string_compose("\"%1\" is not a directory", path) << endmsg;
813                 return;
814         }
815
816         Glib::RefPtr<Gio::File>           dir = Gio::File::create_for_path(path);
817         Glib::RefPtr<Gio::FileEnumerator> e   = dir->enumerate_children();
818         Glib::RefPtr<Gio::FileInfo>       fi;
819         while ((fi = e->next_file())) {
820                 if (fi->get_type() == Gio::FILE_TYPE_DIRECTORY) {
821                         remove_directory(fi->get_name());
822                 } else {
823                         dir->get_child(fi->get_name())->remove();
824                 }
825         }
826         dir->remove();
827 }
828
829 void
830 LV2Plugin::add_state(XMLNode* root) const
831 {
832         assert(_insert_id != PBD::ID("0"));
833
834         XMLNode*    child;
835         char        buf[16];
836         LocaleGuard lg(X_("POSIX"));
837
838         for (uint32_t i = 0; i < parameter_count(); ++i) {
839                 if (parameter_is_input(i) && parameter_is_control(i)) {
840                         child = new XMLNode("Port");
841                         child->add_property("symbol", port_symbol(i));
842                         snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
843                         child->add_property("value", string(buf));
844                         root->add_child_nocopy(*child);
845                 }
846         }
847
848         if (_has_state_interface) {
849                 cout << "LV2 " << name() << " has state interface" << endl;
850                 // Provisionally increment state version and create directory
851                 const std::string new_dir = state_dir(++_state_version);
852                 g_mkdir_with_parents(new_dir.c_str(), 0744);
853
854                 cout << "NEW DIR: " << new_dir << endl;
855
856                 LilvState* state = lilv_state_new_from_instance(
857                         _impl->plugin,
858                         _impl->instance,
859                         _uri_map.urid_map(),
860                         scratch_dir().c_str(),
861                         file_dir().c_str(),
862                         _session.externals_dir().c_str(),
863                         new_dir.c_str(),
864                         NULL,
865                         (void*)this,
866                         0,
867                         NULL);
868
869                 if (!_impl->state || !lilv_state_equals(state, _impl->state)) {
870                         lilv_state_save(_world.world,
871                                         _uri_map.urid_map(),
872                                         _uri_map.urid_unmap(),
873                                         state,
874                                         NULL,
875                                         new_dir.c_str(),
876                                         "state.ttl");
877
878                         lilv_state_free(_impl->state);
879                         _impl->state = state;
880
881                         cout << "Saved LV2 state to " << state_dir(_state_version) << endl;
882                 } else {
883                         // State is identical, decrement version and nuke directory
884                         cout << "LV2 state identical, not saving" << endl;
885                         lilv_state_free(state);
886                         remove_directory(new_dir);
887                         --_state_version;
888                 }
889
890                 root->add_property("state-dir", string_compose("state%1", _state_version));
891         } else {
892                 cout << "LV2 " << name() << " has no state interface." << endl;
893         }
894 }
895
896 static inline const LilvNode*
897 get_value(LilvWorld* world, const LilvNode* subject, const LilvNode* predicate)
898 {
899         LilvNodes* vs = lilv_world_find_nodes(world, subject, predicate, NULL);
900         return vs ? lilv_nodes_get_first(vs) : NULL;
901 }
902
903 void
904 LV2Plugin::find_presets()
905 {
906         LilvNode* lv2_appliesTo = lilv_new_uri(_world.world, LV2_CORE__appliesTo);
907         LilvNode* pset_Preset   = lilv_new_uri(_world.world, LV2_PRESETS__Preset);
908         LilvNode* rdfs_label    = lilv_new_uri(_world.world, LILV_NS_RDFS "label");
909
910         LilvNodes* presets = lilv_plugin_get_related(_impl->plugin, pset_Preset);
911         LILV_FOREACH(nodes, i, presets) {
912                 const LilvNode* preset = lilv_nodes_get(presets, i);
913                 lilv_world_load_resource(_world.world, preset);
914                 const LilvNode* name = get_value(_world.world, preset, rdfs_label);
915                 if (name) {
916                         _presets.insert(std::make_pair(lilv_node_as_string(preset),
917                                                        Plugin::PresetRecord(
918                                                                lilv_node_as_string(preset),
919                                                                lilv_node_as_string(name))));
920                 } else {
921                         warning << string_compose(
922                             _("Plugin \"%1\% preset \"%2%\" is missing a label\n"),
923                             lilv_node_as_string(lilv_plugin_get_uri(_impl->plugin)),
924                             lilv_node_as_string(preset)) << endmsg;
925                 }
926         }
927         lilv_nodes_free(presets);
928
929         lilv_node_free(rdfs_label);
930         lilv_node_free(pset_Preset);
931         lilv_node_free(lv2_appliesTo);
932 }
933
934 bool
935 LV2Plugin::load_preset(PresetRecord r)
936 {
937         std::map<std::string,uint32_t>::iterator it;
938
939         LilvNode* lv2_port   = lilv_new_uri(_world.world, LILV_NS_LV2 "port");
940         LilvNode* lv2_symbol = lilv_new_uri(_world.world, LILV_NS_LV2 "symbol");
941         LilvNode* preset     = lilv_new_uri(_world.world, r.uri.c_str());
942         LilvNode* pset_value = lilv_new_uri(_world.world, LV2_PRESETS__value);
943
944         LilvNodes* ports = lilv_world_find_nodes(_world.world, preset, lv2_port, NULL);
945         LILV_FOREACH(nodes, i, ports) {
946                 const LilvNode* port   = lilv_nodes_get(ports, i);
947                 const LilvNode* symbol = get_value(_world.world, port, lv2_symbol);
948                 const LilvNode* value  = get_value(_world.world, port, pset_value);
949                 if (value && lilv_node_is_float(value)) {
950                         it = _port_indices.find(lilv_node_as_string(symbol));
951                         if (it != _port_indices.end()) {
952                                 set_parameter(it->second,lilv_node_as_float(value));
953                         }
954                 }
955         }
956         lilv_nodes_free(ports);
957
958         lilv_node_free(pset_value);
959         lilv_node_free(preset);
960         lilv_node_free(lv2_symbol);
961         lilv_node_free(lv2_port);
962
963         Plugin::load_preset(r);
964
965         return true;
966 }
967
968 const void*
969 ARDOUR::lv2plugin_get_port_value(const char* port_symbol,
970                                  void*       user_data,
971                                  uint32_t*   size,
972                                  uint32_t*   type)
973 {
974         // cerr << "get_port_value(" << port_symbol << ", ...) ... ";
975         LV2Plugin *plugin = (LV2Plugin *) user_data;
976
977         uint32_t index = plugin->port_index(port_symbol);
978         if (index != (uint32_t) -1) {
979                 if (plugin->parameter_is_input(index) && plugin->parameter_is_control(index)) {
980                         float *value;
981                         *size = sizeof(float);
982                         *type = plugin->_uri_map.uri_to_id(LV2_ATOM__Float);
983                         value = &plugin->_shadow_data[index];
984                         // cerr << "index="<< index << ",*size=" << *size << ",*type=" << *type << ",*value=" << *value << endl;
985
986                         return value;
987                 }
988                 // cerr << "port is not input control port! ";
989         }
990
991         // cerr << "returning NULL!" << endl;
992         *size = *type = 0;
993         return NULL;
994 }
995
996
997 std::string
998 LV2Plugin::do_save_preset(string name)
999 {
1000         // cerr << "LV2Plugin::do_save_preset(" << name << ")" << endl;
1001
1002         string pset_uri = uri();
1003         pset_uri += "#";
1004         pset_uri += name;
1005
1006         string save_dir = Glib::build_filename(
1007                 Glib::get_home_dir(),
1008                 Glib::build_filename(".lv2", "presets")
1009         );
1010
1011         LilvState* state = lilv_state_new_from_instance(
1012                 _impl->plugin,
1013                 _impl->instance,
1014                 _uri_map.urid_map(),
1015                 scratch_dir().c_str(),                  // file_dir
1016                 NULL,                                   // copy_dir
1017                 NULL,                                   // link_dir
1018                 save_dir.c_str(),                       // save_dir
1019                 lv2plugin_get_port_value,               // get_value
1020                 (void*) this,                           // user_data
1021                 LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE, // flags
1022                 _features                               // features
1023         );
1024
1025         lilv_state_set_label(state, name.c_str());
1026         lilv_state_save(
1027                 _world.world,           // world
1028                 _uri_map.urid_map(),    // map
1029                 _uri_map.urid_unmap(),  // unmap
1030                 state,                  // state
1031                 pset_uri.c_str(),       // uri
1032                 save_dir.c_str(),       // dir
1033                 (name + ".ttl").c_str() // filename
1034         );
1035
1036         lilv_state_free(state);
1037         return pset_uri;
1038 }
1039
1040 void
1041 LV2Plugin::do_remove_preset(string name)
1042 {
1043         string preset_file = Glib::build_filename(
1044                 Glib::get_home_dir(),
1045                 Glib::build_filename(
1046                         Glib::build_filename(".lv2", "presets"),
1047                         name + ".ttl"
1048                 )
1049         );
1050         unlink(preset_file.c_str());
1051 }
1052
1053 bool
1054 LV2Plugin::has_editor() const
1055 {
1056         return _impl->ui != NULL;
1057 }
1058
1059 bool
1060 LV2Plugin::has_message_output() const
1061 {
1062         for (uint32_t i = 0; i < num_ports(); ++i) {
1063                 if ((_port_flags[i] & (PORT_MESSAGE|PORT_ATOM)) && _port_flags[i] & PORT_OUTPUT) {
1064                         return true;
1065                 }
1066         }
1067         return false;
1068 }
1069
1070 uint32_t
1071 LV2Plugin::atom_eventTransfer() const
1072 {
1073         return _event_transfer_type;
1074 }
1075
1076 void
1077 LV2Plugin::write_to(RingBuffer<uint8_t>* dest,
1078                     uint32_t             index,
1079                     uint32_t             protocol,
1080                     uint32_t             size,
1081                     const uint8_t*       body)
1082 {
1083         const uint32_t buf_size = sizeof(UIMessage) + size;
1084         uint8_t        buf[buf_size];
1085
1086         UIMessage* msg = (UIMessage*)buf;
1087         msg->index    = index;
1088         msg->protocol = protocol;
1089         msg->size     = size;
1090         memcpy(msg + 1, body, size);
1091
1092         if (dest->write(buf, buf_size) != buf_size) {
1093                 error << "Error writing to UI=>Plugin RingBuffer" << endmsg;
1094         }
1095 }
1096
1097 void
1098 LV2Plugin::write_from_ui(uint32_t       index,
1099                          uint32_t       protocol,
1100                          uint32_t       size,
1101                          const uint8_t* body)
1102 {
1103         if (!_from_ui) {
1104                 _from_ui = new RingBuffer<uint8_t>(4096);
1105         }
1106
1107         write_to(_from_ui, index, protocol, size, body);
1108 }
1109
1110 void
1111 LV2Plugin::write_to_ui(uint32_t       index,
1112                        uint32_t       protocol,
1113                        uint32_t       size,
1114                        const uint8_t* body)
1115 {
1116         write_to(_to_ui, index, protocol, size, body);
1117 }
1118
1119 void
1120 LV2Plugin::enable_ui_emmission()
1121 {
1122         if (!_to_ui) {
1123                 _to_ui = new RingBuffer<uint8_t>(4096);
1124         }
1125 }
1126
1127 void
1128 LV2Plugin::emit_to_ui(void* controller, UIMessageSink sink)
1129 {
1130         if (!_to_ui) {
1131                 return;
1132         }
1133
1134         uint32_t read_space = _to_ui->read_space();
1135         while (read_space > sizeof(UIMessage)) {
1136                 UIMessage msg;
1137                 if (_to_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1138                         error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1139                         break;
1140                 }
1141                 uint8_t body[msg.size];
1142                 if (_to_ui->read(body, msg.size) != msg.size) {
1143                         error << "Error reading from Plugin=>UI RingBuffer" << endmsg;
1144                         break;
1145                 }
1146
1147                 sink(controller, msg.index, msg.size, msg.protocol, body);
1148
1149                 read_space -= sizeof(msg) + msg.size;
1150         }
1151 }
1152
1153 int
1154 LV2Plugin::work(uint32_t size, const void* data)
1155 {
1156         return _impl->work_iface->work(
1157                 _impl->instance->lv2_handle, work_respond, this, size, data);
1158 }
1159
1160 int
1161 LV2Plugin::work_response(uint32_t size, const void* data)
1162 {
1163         return _impl->work_iface->work_response(
1164                 _impl->instance->lv2_handle, size, data);
1165 }
1166
1167 void
1168 LV2Plugin::set_insert_info(const PluginInsert* insert)
1169 {
1170         _insert_id = insert->id();
1171 }
1172
1173 int
1174 LV2Plugin::set_state(const XMLNode& node, int version)
1175 {
1176         XMLNodeList          nodes;
1177         const XMLProperty*   prop;
1178         XMLNodeConstIterator iter;
1179         XMLNode*             child;
1180         const char*          sym;
1181         const char*          value;
1182         uint32_t             port_id;
1183         LocaleGuard          lg(X_("POSIX"));
1184
1185         if (node.name() != state_node_name()) {
1186                 error << _("Bad node sent to LV2Plugin::set_state") << endmsg;
1187                 return -1;
1188         }
1189
1190         if (version < 3000) {
1191                 nodes = node.children("port");
1192         } else {
1193                 nodes = node.children("Port");
1194         }
1195
1196         for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
1197
1198                 child = *iter;
1199
1200                 if ((prop = child->property("symbol")) != 0) {
1201                         sym = prop->value().c_str();
1202                 } else {
1203                         warning << _("LV2: port has no symbol, ignored") << endmsg;
1204                         continue;
1205                 }
1206
1207                 map<string, uint32_t>::iterator i = _port_indices.find(sym);
1208
1209                 if (i != _port_indices.end()) {
1210                         port_id = i->second;
1211                 } else {
1212                         warning << _("LV2: port has unknown index, ignored") << endmsg;
1213                         continue;
1214                 }
1215
1216                 if ((prop = child->property("value")) != 0) {
1217                         value = prop->value().c_str();
1218                 } else {
1219                         warning << _("LV2: port has no value, ignored") << endmsg;
1220                         continue;
1221                 }
1222
1223                 set_parameter(port_id, atof(value));
1224         }
1225
1226         _state_version = 0;
1227         if ((prop = node.property("state-dir")) != 0) {
1228                 if (sscanf(prop->value().c_str(), "state%u", &_state_version) != 1) {
1229                         error << string_compose(
1230                                 "LV2: failed to parse state version from \"%1\"",
1231                                 prop->value()) << endmsg;
1232                 }
1233
1234                 std::string state_file = Glib::build_filename(
1235                         plugin_dir(),
1236                         Glib::build_filename(prop->value(), "state.ttl"));
1237
1238                 cout << "Loading LV2 state from " << state_file << endl;
1239                 LilvState* state = lilv_state_new_from_file(
1240                         _world.world, _uri_map.urid_map(), NULL, state_file.c_str());
1241
1242                 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
1243         }
1244
1245         latency_compute_run();
1246
1247         return Plugin::set_state(node, version);
1248 }
1249
1250 int
1251 LV2Plugin::get_parameter_descriptor(uint32_t which, ParameterDescriptor& desc) const
1252 {
1253         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, which);
1254
1255         LilvNode *def, *min, *max;
1256         lilv_port_get_range(_impl->plugin, port, &def, &min, &max);
1257
1258         desc.integer_step = lilv_port_has_property(_impl->plugin, port, _world.lv2_integer);
1259         desc.toggled      = lilv_port_has_property(_impl->plugin, port, _world.lv2_toggled);
1260         desc.logarithmic  = lilv_port_has_property(_impl->plugin, port, _world.ext_logarithmic);
1261         desc.sr_dependent = lilv_port_has_property(_impl->plugin, port, _world.lv2_sampleRate);
1262         desc.label        = lilv_node_as_string(lilv_port_get_name(_impl->plugin, port));
1263         desc.lower        = min ? lilv_node_as_float(min) : 0.0f;
1264         desc.upper        = max ? lilv_node_as_float(max) : 1.0f;
1265         if (desc.sr_dependent) {
1266                 desc.lower *= _session.frame_rate ();
1267                 desc.upper *= _session.frame_rate ();
1268         }
1269
1270         desc.min_unbound  = false; // TODO: LV2 extension required
1271         desc.max_unbound  = false; // TODO: LV2 extension required
1272
1273         if (desc.integer_step) {
1274                 desc.step      = 1.0;
1275                 desc.smallstep = 0.1;
1276                 desc.largestep = 10.0;
1277         } else {
1278                 const float delta = desc.upper - desc.lower;
1279                 desc.step      = delta / 1000.0f;
1280                 desc.smallstep = delta / 10000.0f;
1281                 desc.largestep = delta / 10.0f;
1282         }
1283
1284         desc.enumeration = lilv_port_has_property(_impl->plugin, port, _world.lv2_enumeration);
1285
1286         lilv_node_free(def);
1287         lilv_node_free(min);
1288         lilv_node_free(max);
1289
1290         return 0;
1291 }
1292
1293 string
1294 LV2Plugin::describe_parameter(Evoral::Parameter which)
1295 {
1296         if (( which.type() == PluginAutomation) && ( which.id() < parameter_count()) ) {
1297                 LilvNode* name = lilv_port_get_name(_impl->plugin,
1298                                                     lilv_plugin_get_port_by_index(_impl->plugin, which.id()));
1299                 string ret(lilv_node_as_string(name));
1300                 lilv_node_free(name);
1301                 return ret;
1302         } else {
1303                 return "??";
1304         }
1305 }
1306
1307 framecnt_t
1308 LV2Plugin::signal_latency() const
1309 {
1310         if (_latency_control_port) {
1311                 return (framecnt_t)floor(*_latency_control_port);
1312         } else {
1313                 return 0;
1314         }
1315 }
1316
1317 set<Evoral::Parameter>
1318 LV2Plugin::automatable() const
1319 {
1320         set<Evoral::Parameter> ret;
1321
1322         for (uint32_t i = 0; i < parameter_count(); ++i) {
1323                 if (parameter_is_input(i) && parameter_is_control(i)) {
1324                         ret.insert(ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
1325                 }
1326         }
1327
1328         return ret;
1329 }
1330
1331 void
1332 LV2Plugin::activate()
1333 {
1334         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 activate\n", name()));
1335
1336         if (!_was_activated) {
1337                 lilv_instance_activate(_impl->instance);
1338                 _was_activated = true;
1339         }
1340 }
1341
1342 void
1343 LV2Plugin::deactivate()
1344 {
1345         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 deactivate\n", name()));
1346
1347         if (_was_activated) {
1348                 lilv_instance_deactivate(_impl->instance);
1349                 _was_activated = false;
1350         }
1351 }
1352
1353 void
1354 LV2Plugin::cleanup()
1355 {
1356         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 cleanup\n", name()));
1357
1358         activate();
1359         deactivate();
1360         lilv_instance_free(_impl->instance);
1361         _impl->instance = NULL;
1362 }
1363
1364 void
1365 LV2Plugin::allocate_atom_event_buffers () {
1366         /* reserve local scratch buffers for ATOM event-queues */
1367         const LilvPlugin* p = _impl->plugin;
1368
1369         /* count non-MIDI atom event-ports
1370          * TODO: nicely ask drobilla to make a lilv_ call for that
1371          */
1372         int count_atom_out = 0;
1373         int count_atom_in = 0;
1374         for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
1375                 const LilvPort* port  = lilv_plugin_get_port_by_index(p, i);
1376                 if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
1377                         LilvNodes* buffer_types = lilv_port_get_value(
1378                                 p, port, _world.atom_bufferType);
1379                         LilvNodes* atom_supports = lilv_port_get_value(
1380                                 p, port, _world.atom_supports);
1381
1382                         if (!lilv_nodes_contains(buffer_types, _world.atom_Sequence)
1383                                         || !lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
1384                                 if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
1385                                         count_atom_in++;
1386                                 }
1387                                 if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
1388                                         count_atom_out++;
1389                                 }
1390                         }
1391                         lilv_nodes_free(buffer_types);
1392                         lilv_nodes_free(atom_supports);
1393                 }
1394         }
1395
1396         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 need buffers for %2 atom-in and %3 atom-out event-ports\n",
1397                                 name(), count_atom_in, count_atom_out));
1398
1399         const int total_atom_buffers = (count_atom_in + count_atom_out);
1400         if (_atom_ev_buffers || total_atom_buffers == 0) {
1401                 return;
1402         }
1403
1404         DEBUG_TRACE(DEBUG::LV2, string_compose("allocate %1 atom_ev_buffers\n", total_atom_buffers));
1405         _atom_ev_buffers = (LV2_Evbuf**) malloc((total_atom_buffers + 1) * sizeof(LV2_Evbuf*));
1406         for (int i = 0; i < total_atom_buffers; ++i ) {
1407                 _atom_ev_buffers[i] = lv2_evbuf_new(32768, LV2_EVBUF_ATOM,
1408                                 LV2Plugin::_chunk_type, LV2Plugin::_sequence_type);
1409         }
1410         _atom_ev_buffers[total_atom_buffers] = 0;
1411         return;
1412 }
1413
1414 int
1415 LV2Plugin::connect_and_run(BufferSet& bufs,
1416         ChanMapping in_map, ChanMapping out_map,
1417         pframes_t nframes, framecnt_t offset)
1418 {
1419         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 run %2 offset %3\n", name(), nframes, offset));
1420         Plugin::connect_and_run(bufs, in_map, out_map, nframes, offset);
1421
1422         cycles_t then = get_cycles();
1423
1424         if (_freewheel_control_port) {
1425                 *_freewheel_control_port = _session.engine().freewheeling ();
1426         }
1427
1428         if (_bpm_control_port) {
1429                 TempoMap& tmap (_session.tempo_map ());
1430                 Tempo tempo = tmap.tempo_at (_session.transport_frame () + offset);
1431                 *_bpm_control_port = tempo.beats_per_minute ();
1432         }
1433
1434         ChanCount bufs_count;
1435         bufs_count.set(DataType::AUDIO, 1);
1436         bufs_count.set(DataType::MIDI, 1);
1437         BufferSet& silent_bufs  = _session.get_silent_buffers(bufs_count);
1438         BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
1439         uint32_t const num_ports = parameter_count();
1440
1441         uint32_t audio_in_index  = 0;
1442         uint32_t audio_out_index = 0;
1443         uint32_t midi_in_index   = 0;
1444         uint32_t midi_out_index  = 0;
1445         uint32_t atom_port_index = 0;
1446         bool valid;
1447         for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
1448                 void*     buf   = NULL;
1449                 uint32_t  index = 0;
1450                 PortFlags flags = _port_flags[port_index];
1451                 if (flags & PORT_AUDIO) {
1452                         if (flags & PORT_INPUT) {
1453                                 index = in_map.get(DataType::AUDIO, audio_in_index++, &valid);
1454                                 buf = (valid)
1455                                         ? bufs.get_audio(index).data(offset)
1456                                         : silent_bufs.get_audio(0).data(offset);
1457                         } else {
1458                                 index = out_map.get(DataType::AUDIO, audio_out_index++, &valid);
1459                                 buf = (valid)
1460                                         ? bufs.get_audio(index).data(offset)
1461                                         : scratch_bufs.get_audio(0).data(offset);
1462                         }
1463                 } else if (flags & (PORT_EVENT|PORT_MESSAGE)) {
1464                         /* FIXME: The checks here for bufs.count().n_midi() > index shouldn't
1465                            be necessary, but the mapping is illegal in some cases.  Ideally
1466                            that should be fixed, but this is easier...
1467                         */
1468                         if (flags & PORT_INPUT) {
1469                                 index = in_map.get(DataType::MIDI, midi_in_index++, &valid);
1470                                 _ev_buffers[port_index] = (valid && bufs.count().n_midi() > index)
1471                                         ? bufs.get_lv2_midi(true, index, flags & PORT_EVENT)
1472                                         : silent_bufs.get_lv2_midi(true, 0, flags & PORT_EVENT);
1473                                 buf = lv2_evbuf_get_buffer(_ev_buffers[port_index]);
1474                         } else {
1475                                 index = out_map.get(DataType::MIDI, midi_out_index++, &valid);
1476                                 _ev_buffers[port_index] = (valid && bufs.count().n_midi() > index)
1477                                         ? bufs.get_lv2_midi(false, index, flags & PORT_EVENT)
1478                                         : scratch_bufs.get_lv2_midi(false, 0, flags & PORT_EVENT);
1479                                 buf = lv2_evbuf_get_buffer(_ev_buffers[port_index]);
1480                         }
1481                 } else if (flags & (PORT_ATOM)) {
1482                         assert(_atom_ev_buffers && _atom_ev_buffers[atom_port_index]);
1483                         if (flags & PORT_INPUT) {
1484                                 lv2_evbuf_reset(_atom_ev_buffers[atom_port_index], true);
1485                                 _ev_buffers[port_index] = _atom_ev_buffers[atom_port_index++];
1486                         } else {
1487                                 lv2_evbuf_reset(_atom_ev_buffers[atom_port_index], false);
1488                                 _ev_buffers[port_index] = _atom_ev_buffers[atom_port_index++];
1489                         }
1490                         buf = lv2_evbuf_get_buffer(_ev_buffers[port_index]);
1491                         assert(buf);
1492                 } else {
1493                         continue;  // Control port, leave buffer alone
1494                 }
1495                 lilv_instance_connect_port(_impl->instance, port_index, buf);
1496         }
1497
1498         // Read messages from UI and push into appropriate buffers
1499         if (_from_ui) {
1500                 uint32_t read_space = _from_ui->read_space();
1501                 while (read_space > sizeof(UIMessage)) {
1502                         UIMessage msg;
1503                         if (_from_ui->read((uint8_t*)&msg, sizeof(msg)) != sizeof(msg)) {
1504                                 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
1505                                 break;
1506                         }
1507                         uint8_t body[msg.size];
1508                         if (_from_ui->read(body, msg.size) != msg.size) {
1509                                 error << "Error reading from UI=>Plugin RingBuffer" << endmsg;
1510                                 break;
1511                         }
1512                         if (msg.protocol == _event_transfer_type) {
1513                                 LV2_Evbuf*            buf  = _ev_buffers[msg.index];
1514                                 LV2_Evbuf_Iterator    i    = lv2_evbuf_end(buf);
1515                                 const LV2_Atom* const atom = (const LV2_Atom*)body;
1516                                 if (!lv2_evbuf_write(&i, nframes, 0, atom->type, atom->size,
1517                                                 (const uint8_t*)(atom + 1))) {
1518                                         cerr << "LV2: failed to write data to event buffer\n";
1519                                 }
1520                         } else {
1521                                 error << "Received unknown message type from UI" << endmsg;
1522                         }
1523                         read_space -= sizeof(UIMessage) + msg.size;
1524                 }
1525         }
1526
1527         run(nframes);
1528
1529         midi_out_index = 0;
1530         for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
1531                 PortFlags flags = _port_flags[port_index];
1532
1533                 // Flush MIDI (write back to Ardour MIDI buffers)
1534                 if ((flags & PORT_OUTPUT) && (flags & (PORT_EVENT|PORT_MESSAGE))) {
1535                         const uint32_t buf_index = out_map.get(
1536                                 DataType::MIDI, midi_out_index++, &valid);
1537                         if (valid) {
1538                                 bufs.flush_lv2_midi(true, buf_index);
1539                         }
1540                 }
1541
1542                 // Write messages to UI
1543                 if (_to_ui && (flags & PORT_OUTPUT) && (flags & (PORT_MESSAGE|PORT_ATOM))) {
1544                         LV2_Evbuf* buf = _ev_buffers[port_index];
1545                         for (LV2_Evbuf_Iterator i = lv2_evbuf_begin(buf);
1546                              lv2_evbuf_is_valid(i);
1547                              i = lv2_evbuf_next(i)) {
1548                                 uint32_t frames, subframes, type, size;
1549                                 uint8_t* data;
1550                                 lv2_evbuf_get(i, &frames, &subframes, &type, &size, &data);
1551                                 write_to_ui(port_index, _event_transfer_type,
1552                                             size + sizeof(LV2_Atom),
1553                                             data - sizeof(LV2_Atom));
1554                         }
1555                 }
1556         }
1557
1558         cycles_t now = get_cycles();
1559         set_cycles((uint32_t)(now - then));
1560
1561         return 0;
1562 }
1563
1564 bool
1565 LV2Plugin::parameter_is_control(uint32_t param) const
1566 {
1567         assert(param < _port_flags.size());
1568         return _port_flags[param] & PORT_CONTROL;
1569 }
1570
1571 bool
1572 LV2Plugin::parameter_is_audio(uint32_t param) const
1573 {
1574         assert(param < _port_flags.size());
1575         return _port_flags[param] & PORT_AUDIO;
1576 }
1577
1578 bool
1579 LV2Plugin::parameter_is_event(uint32_t param) const
1580 {
1581         assert(param < _port_flags.size());
1582         return _port_flags[param] & PORT_EVENT;
1583 }
1584
1585 bool
1586 LV2Plugin::parameter_is_output(uint32_t param) const
1587 {
1588         assert(param < _port_flags.size());
1589         return _port_flags[param] & PORT_OUTPUT;
1590 }
1591
1592 bool
1593 LV2Plugin::parameter_is_input(uint32_t param) const
1594 {
1595         assert(param < _port_flags.size());
1596         return _port_flags[param] & PORT_INPUT;
1597 }
1598
1599 void
1600 LV2Plugin::print_parameter(uint32_t param, char* buf, uint32_t len) const
1601 {
1602         if (buf && len) {
1603                 if (param < parameter_count()) {
1604                         snprintf(buf, len, "%.3f", get_parameter(param));
1605                 } else {
1606                         strcat(buf, "0");
1607                 }
1608         }
1609 }
1610
1611 boost::shared_ptr<Plugin::ScalePoints>
1612 LV2Plugin::get_scale_points(uint32_t port_index) const
1613 {
1614         const LilvPort*  port   = lilv_plugin_get_port_by_index(_impl->plugin, port_index);
1615         LilvScalePoints* points = lilv_port_get_scale_points(_impl->plugin, port);
1616
1617         boost::shared_ptr<Plugin::ScalePoints> ret;
1618         if (!points) {
1619                 return ret;
1620         }
1621
1622         ret = boost::shared_ptr<Plugin::ScalePoints>(new ScalePoints());
1623
1624         LILV_FOREACH(scale_points, i, points) {
1625                 const LilvScalePoint* p     = lilv_scale_points_get(points, i);
1626                 const LilvNode*       label = lilv_scale_point_get_label(p);
1627                 const LilvNode*       value = lilv_scale_point_get_value(p);
1628                 if (label && (lilv_node_is_float(value) || lilv_node_is_int(value))) {
1629                         ret->insert(make_pair(lilv_node_as_string(label),
1630                                               lilv_node_as_float(value)));
1631                 }
1632         }
1633
1634         lilv_scale_points_free(points);
1635         return ret;
1636 }
1637
1638 void
1639 LV2Plugin::run(pframes_t nframes)
1640 {
1641         uint32_t const N = parameter_count();
1642         for (uint32_t i = 0; i < N; ++i) {
1643                 if (parameter_is_control(i) && parameter_is_input(i)) {
1644                         _control_data[i] = _shadow_data[i];
1645                 }
1646         }
1647
1648         lilv_instance_run(_impl->instance, nframes);
1649
1650         if (_impl->work_iface) {
1651                 _worker->emit_responses();
1652                 if (_impl->work_iface->end_run) {
1653                         _impl->work_iface->end_run(_impl->instance->lv2_handle);
1654                 }
1655         }
1656 }
1657
1658 void
1659 LV2Plugin::latency_compute_run()
1660 {
1661         if (!_latency_control_port) {
1662                 return;
1663         }
1664
1665         // Run the plugin so that it can set its latency parameter
1666
1667         activate();
1668
1669         uint32_t port_index = 0;
1670         uint32_t in_index   = 0;
1671         uint32_t out_index  = 0;
1672
1673         const framecnt_t bufsize = 1024;
1674         float            buffer[bufsize];
1675
1676         memset(buffer, 0, sizeof(float) * bufsize);
1677
1678         // FIXME: Ensure plugins can handle in-place processing
1679
1680         port_index = 0;
1681
1682         while (port_index < parameter_count()) {
1683                 if (parameter_is_audio(port_index)) {
1684                         if (parameter_is_input(port_index)) {
1685                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1686                                 in_index++;
1687                         } else if (parameter_is_output(port_index)) {
1688                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1689                                 out_index++;
1690                         }
1691                 }
1692                 port_index++;
1693         }
1694
1695         run(bufsize);
1696         deactivate();
1697 }
1698
1699 LilvPort*
1700 LV2Plugin::Impl::designated_input (const char* uri, void** bufptrs[], void** bufptr)
1701 {
1702         LilvPort* port        = NULL;
1703         LilvNode* designation = lilv_new_uri(_world.world, uri);
1704         port = lilv_plugin_get_port_by_designation(
1705                 plugin, _world.lv2_InputPort, designation);
1706         lilv_node_free(designation);
1707         if (port) {
1708                 bufptrs[lilv_port_get_index(plugin, port)] = bufptr;
1709         }
1710         return port;
1711 }
1712
1713 LV2World::LV2World()
1714         : world(lilv_world_new())
1715 {
1716         lilv_world_load_all(world);
1717         atom_AtomPort      = lilv_new_uri(world, LV2_ATOM__AtomPort);
1718         atom_Chunk         = lilv_new_uri(world, LV2_ATOM__Chunk);
1719         atom_Sequence      = lilv_new_uri(world, LV2_ATOM__Sequence);
1720         atom_bufferType    = lilv_new_uri(world, LV2_ATOM__bufferType);
1721         atom_supports      = lilv_new_uri(world, LV2_ATOM__supports);
1722         atom_eventTransfer = lilv_new_uri(world, LV2_ATOM__eventTransfer);
1723         ev_EventPort       = lilv_new_uri(world, LILV_URI_EVENT_PORT);
1724         ext_logarithmic    = lilv_new_uri(world, LV2_PORT_PROPS__logarithmic);
1725         lv2_AudioPort      = lilv_new_uri(world, LILV_URI_AUDIO_PORT);
1726         lv2_ControlPort    = lilv_new_uri(world, LILV_URI_CONTROL_PORT);
1727         lv2_InputPort      = lilv_new_uri(world, LILV_URI_INPUT_PORT);
1728         lv2_OutputPort     = lilv_new_uri(world, LILV_URI_OUTPUT_PORT);
1729         lv2_inPlaceBroken  = lilv_new_uri(world, LV2_CORE__inPlaceBroken);
1730         lv2_integer        = lilv_new_uri(world, LV2_CORE__integer);
1731         lv2_sampleRate     = lilv_new_uri(world, LV2_CORE__sampleRate);
1732         lv2_toggled        = lilv_new_uri(world, LV2_CORE__toggled);
1733         lv2_enumeration    = lilv_new_uri(world, LV2_CORE__enumeration);
1734         midi_MidiEvent     = lilv_new_uri(world, LILV_URI_MIDI_EVENT);
1735         rdfs_comment       = lilv_new_uri(world, LILV_NS_RDFS "comment");
1736         ui_GtkUI           = lilv_new_uri(world, LV2_UI__GtkUI);
1737         ui_external        = lilv_new_uri(world, "http://lv2plug.in/ns/extensions/ui#external");
1738 }
1739
1740 LV2World::~LV2World()
1741 {
1742         lilv_node_free(ui_external);
1743         lilv_node_free(ui_GtkUI);
1744         lilv_node_free(midi_MidiEvent);
1745         lilv_node_free(lv2_toggled);
1746         lilv_node_free(lv2_sampleRate);
1747         lilv_node_free(lv2_integer);
1748         lilv_node_free(lv2_inPlaceBroken);
1749         lilv_node_free(lv2_OutputPort);
1750         lilv_node_free(lv2_InputPort);
1751         lilv_node_free(lv2_ControlPort);
1752         lilv_node_free(lv2_AudioPort);
1753         lilv_node_free(ext_logarithmic);
1754         lilv_node_free(ev_EventPort);
1755         lilv_node_free(atom_eventTransfer);
1756         lilv_node_free(atom_bufferType);
1757         lilv_node_free(atom_Sequence);
1758         lilv_node_free(atom_Chunk);
1759         lilv_node_free(atom_AtomPort);
1760 }
1761
1762 LV2PluginInfo::LV2PluginInfo (const void* c_plugin)
1763         : _c_plugin(c_plugin)
1764 {
1765         type = ARDOUR::LV2;
1766 }
1767
1768 LV2PluginInfo::~LV2PluginInfo()
1769 {}
1770
1771 PluginPtr
1772 LV2PluginInfo::load(Session& session)
1773 {
1774         try {
1775                 PluginPtr plugin;
1776
1777                 plugin.reset(new LV2Plugin(session.engine(), session,
1778                                            (const LilvPlugin*)_c_plugin,
1779                                            session.frame_rate()));
1780
1781                 plugin->set_info(PluginInfoPtr(new LV2PluginInfo(*this)));
1782                 return plugin;
1783         } catch (failed_constructor& err) {
1784                 return PluginPtr((Plugin*)0);
1785         }
1786
1787         return PluginPtr();
1788 }
1789
1790 PluginInfoList*
1791 LV2PluginInfo::discover()
1792 {
1793         PluginInfoList*    plugs   = new PluginInfoList;
1794         const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
1795
1796         info << "LV2: Discovering " << lilv_plugins_size(plugins) << " plugins" << endmsg;
1797
1798         LILV_FOREACH(plugins, i, plugins) {
1799                 const LilvPlugin* p = lilv_plugins_get(plugins, i);
1800                 LV2PluginInfoPtr  info(new LV2PluginInfo((const void*)p));
1801
1802                 LilvNode* name = lilv_plugin_get_name(p);
1803                 if (!name) {
1804                         cerr << "LV2: invalid plugin\n";
1805                         continue;
1806                 }
1807
1808                 info->type = LV2;
1809
1810                 info->name = string(lilv_node_as_string(name));
1811                 lilv_node_free(name);
1812
1813                 const LilvPluginClass* pclass = lilv_plugin_get_class(p);
1814                 const LilvNode*        label  = lilv_plugin_class_get_label(pclass);
1815                 info->category = lilv_node_as_string(label);
1816
1817                 LilvNode* author_name = lilv_plugin_get_author_name(p);
1818                 info->creator = author_name ? string(lilv_node_as_string(author_name)) : "Unknown";
1819                 lilv_node_free(author_name);
1820
1821                 info->path = "/NOPATH"; // Meaningless for LV2
1822
1823                 /* count atom-event-ports that feature
1824                  * atom:supports <http://lv2plug.in/ns/ext/midi#MidiEvent>
1825                  *
1826                  * TODO: nicely ask drobilla to make a lilv_ call for that
1827                  */
1828                 int count_midi_out = 0;
1829                 int count_midi_in = 0;
1830                 for (uint32_t i = 0; i < lilv_plugin_get_num_ports(p); ++i) {
1831                         const LilvPort* port  = lilv_plugin_get_port_by_index(p, i);
1832                         if (lilv_port_is_a(p, port, _world.atom_AtomPort)) {
1833                                 LilvNodes* buffer_types = lilv_port_get_value(
1834                                         p, port, _world.atom_bufferType);
1835                                 LilvNodes* atom_supports = lilv_port_get_value(
1836                                         p, port, _world.atom_supports);
1837
1838                                 if (lilv_nodes_contains(buffer_types, _world.atom_Sequence)
1839                                                 && lilv_nodes_contains(atom_supports, _world.midi_MidiEvent)) {
1840                                         if (lilv_port_is_a(p, port, _world.lv2_InputPort)) {
1841                                                 count_midi_in++;
1842                                         }
1843                                         if (lilv_port_is_a(p, port, _world.lv2_OutputPort)) {
1844                                                 count_midi_out++;
1845                                         }
1846                                 }
1847                                 lilv_nodes_free(buffer_types);
1848                                 lilv_nodes_free(atom_supports);
1849                         }
1850                 }
1851
1852                 info->n_inputs.set_audio(
1853                         lilv_plugin_get_num_ports_of_class(
1854                                 p, _world.lv2_InputPort, _world.lv2_AudioPort, NULL));
1855                 info->n_inputs.set_midi(
1856                         lilv_plugin_get_num_ports_of_class(
1857                                 p, _world.lv2_InputPort, _world.ev_EventPort, NULL)
1858                         + count_midi_in);
1859
1860                 info->n_outputs.set_audio(
1861                         lilv_plugin_get_num_ports_of_class(
1862                                 p, _world.lv2_OutputPort, _world.lv2_AudioPort, NULL));
1863                 info->n_outputs.set_midi(
1864                         lilv_plugin_get_num_ports_of_class(
1865                                 p, _world.lv2_OutputPort, _world.ev_EventPort, NULL)
1866                         + count_midi_out);
1867
1868                 info->unique_id = lilv_node_as_uri(lilv_plugin_get_uri(p));
1869                 info->index     = 0; // Meaningless for LV2
1870
1871                 plugs->push_back(info);
1872         }
1873
1874         return plugs;
1875 }