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