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