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