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