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