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