Fix compilation with older lilv (0.5.0)
[ardour.git] / libs / ardour / lv2_plugin.cc
1 /*
2     Copyright (C) 2008-2011 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_event_buffer.h"
45 #include "ardour/lv2_plugin.h"
46 #include "ardour/session.h"
47
48 #include "i18n.h"
49 #include <locale.h>
50
51 #include <lilv/lilv.h>
52
53 #include "lv2/lv2plug.in/ns/ext/state/state.h"
54 #include "rdff.h"
55 #ifdef HAVE_SUIL
56 #include <suil/suil.h>
57 #endif
58
59 #define NS_DC      "http://dublincore.org/documents/dcmi-namespace/"
60 #define NS_OLDPSET "http://lv2plug.in/ns/dev/presets#"
61 #define NS_PSET    "http://lv2plug.in/ns/ext/presets#"
62 #define NS_UI      "http://lv2plug.in/ns/extensions/ui#"
63
64 using namespace std;
65 using namespace ARDOUR;
66 using namespace PBD;
67
68 URIMap LV2Plugin::_uri_map;
69 uint32_t LV2Plugin::_midi_event_type = _uri_map.uri_to_id(
70         "http://lv2plug.in/ns/ext/event",
71         "http://lv2plug.in/ns/ext/midi#MidiEvent");
72 uint32_t LV2Plugin::_state_path_type = _uri_map.uri_to_id(
73         NULL, LV2_STATE_PATH_URI);
74
75 class LV2World : boost::noncopyable {
76 public:
77         LV2World ();
78         ~LV2World ();
79
80         LilvWorld* world;
81         LilvNode*  input_class;      ///< Input port
82         LilvNode*  output_class;     ///< Output port
83         LilvNode*  audio_class;      ///< Audio port
84         LilvNode*  control_class;    ///< Control port
85         LilvNode*  event_class;      ///< Event port
86         LilvNode*  midi_class;       ///< MIDI event
87         LilvNode*  in_place_broken;
88         LilvNode*  integer;
89         LilvNode*  toggled;
90         LilvNode*  srate;
91         LilvNode*  gtk_gui;
92         LilvNode*  external_gui;
93         LilvNode*  logarithmic;
94 };
95
96 static LV2World _world;
97
98 struct LV2Plugin::Impl {
99         Impl() : plugin(0), ui(0), ui_type(0), name(0), author(0), instance(0)
100 #ifdef HAVE_NEW_LILV
101                , state(0)
102 #endif
103         {}
104         LilvPlugin*     plugin;
105         const LilvUI*   ui;
106         const LilvNode* ui_type;
107         LilvNode*       name;
108         LilvNode*       author;
109         LilvInstance*   instance;
110 #ifdef HAVE_NEW_LILV
111         LilvState*      state;
112 #endif
113 };
114
115 LV2Plugin::LV2Plugin (AudioEngine& engine,
116                       Session&     session,
117                       void*        c_plugin,
118                       framecnt_t   rate)
119         : Plugin(engine, session)
120         , _impl(new Impl())
121         , _features(NULL)
122         , _insert_id("0")
123 {
124         init(c_plugin, rate);
125 }
126
127 LV2Plugin::LV2Plugin (const LV2Plugin& other)
128         : Plugin(other)
129         , _impl(new Impl())
130         , _features(NULL)
131         , _insert_id(other._insert_id)
132 {
133         init(other._impl->plugin, other._sample_rate);
134
135         for (uint32_t i = 0; i < parameter_count(); ++i) {
136                 _control_data[i] = other._shadow_data[i];
137                 _shadow_data[i]  = other._shadow_data[i];
138         }
139 }
140
141 void
142 LV2Plugin::init(void* c_plugin, framecnt_t rate)
143 {
144         DEBUG_TRACE(DEBUG::LV2, "init\n");
145
146         _impl->plugin         = (LilvPlugin*)c_plugin;
147         _impl->ui             = NULL;
148         _impl->ui_type        = NULL;
149         _control_data         = 0;
150         _shadow_data          = 0;
151         _latency_control_port = 0;
152         _state_version        = 0;
153         _was_activated        = false;
154         _has_state_interface  = false;
155         
156         _instance_access_feature.URI = "http://lv2plug.in/ns/ext/instance-access";
157         _data_access_feature.URI     = "http://lv2plug.in/ns/ext/data-access";
158         _make_path_feature.URI       = LV2_STATE_MAKE_PATH_URI;
159
160         LilvPlugin* plugin = _impl->plugin;
161
162 #ifdef HAVE_NEW_LILV
163         LilvNode* state_iface_uri = lilv_new_uri(_world.world, LV2_STATE_INTERFACE_URI);
164         LilvNode* state_uri       = lilv_new_uri(_world.world, LV2_STATE_URI);
165         _has_state_interface =
166                 // What plugins should have (lv2:extensionData state:Interface)
167                 lilv_plugin_has_extension_data(plugin, state_iface_uri)
168                 // What some outdated/incorrect ones have
169                 || lilv_plugin_has_feature(plugin, state_uri);
170         lilv_node_free(state_uri);
171         lilv_node_free(state_iface_uri);
172 #endif
173
174         _features    = (LV2_Feature**)malloc(sizeof(LV2_Feature*) * 7);
175         _features[0] = &_instance_access_feature;
176         _features[1] = &_data_access_feature;
177         _features[2] = &_make_path_feature;
178         _features[3] = _uri_map.uri_map_feature();
179         _features[4] = _uri_map.urid_map_feature();
180         _features[5] = _uri_map.urid_unmap_feature();
181         _features[6] = NULL;
182
183         LV2_State_Make_Path* make_path = (LV2_State_Make_Path*)malloc(
184                 sizeof(LV2_State_Make_Path));
185         make_path->handle = this;
186         make_path->path = &lv2_state_make_path;
187         _make_path_feature.data = make_path;
188
189         _impl->instance = lilv_plugin_instantiate(plugin, rate, _features);
190         _impl->name     = lilv_plugin_get_name(plugin);
191         _impl->author   = lilv_plugin_get_author_name(plugin);
192
193         if (_impl->instance == 0) {
194                 error << _("LV2: Failed to instantiate plugin ") << uri() << endmsg;
195                 throw failed_constructor();
196         }
197
198         _instance_access_feature.data              = (void*)_impl->instance->lv2_handle;
199         _data_access_extension_data.extension_data = _impl->instance->lv2_descriptor->extension_data;
200         _data_access_feature.data                  = &_data_access_extension_data;
201
202         if (lilv_plugin_has_feature(plugin, _world.in_place_broken)) {
203                 error << string_compose(
204                     _("LV2: \"%1\" cannot be used, since it cannot do inplace processing"),
205                     lilv_node_as_string(_impl->name)) << endmsg;
206                 lilv_node_free(_impl->name);
207                 lilv_node_free(_impl->author);
208                 throw failed_constructor();
209         }
210
211         _sample_rate = rate;
212
213         const uint32_t num_ports    = this->num_ports();
214
215         for (uint32_t i = 0; i < num_ports; ++i) {
216                 const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, i);
217                 _port_is_control.push_back(lilv_port_is_a(_impl->plugin, port, _world.control_class));
218                 _port_is_audio.push_back(lilv_port_is_a(_impl->plugin, port, _world.audio_class));
219                 _port_is_midi.push_back(lilv_port_is_a(_impl->plugin, port, _world.event_class));
220                 _port_is_output.push_back(lilv_port_is_a(_impl->plugin, port, _world.output_class));
221                 _port_is_input.push_back(lilv_port_is_a(_impl->plugin, port, _world.input_class));
222         }
223         
224         const bool     latent       = lilv_plugin_has_latency(plugin);
225         const uint32_t latency_port = (latent)
226             ? lilv_plugin_get_latency_port_index(plugin)
227                 : 0;
228
229         _control_data = new float[num_ports];
230         _shadow_data  = new float[num_ports];
231         _defaults     = new float[num_ports];
232
233         for (uint32_t i = 0; i < num_ports; ++i) {
234                 const LilvPort* port = lilv_plugin_get_port_by_index(plugin, i);
235                 const LilvNode* sym  = lilv_port_get_symbol(plugin, port);
236
237                 // Store index in map so we can look up index by symbol
238                 _port_indices.insert(std::make_pair(lilv_node_as_string(sym), i));
239
240                 // Get range and default value if applicable
241                 if (parameter_is_control(i)) {
242                         LilvNode* def;
243                         lilv_port_get_range(plugin, port, &def, NULL, NULL);
244                         _defaults[i] = def ? lilv_node_as_float(def) : 0.0f;
245                         if (lilv_port_has_property (plugin, port, _world.srate)) {
246                                 _defaults[i] *= _session.frame_rate ();
247                         }
248                         lilv_node_free(def);
249
250                         lilv_instance_connect_port(_impl->instance, i, &_control_data[i]);
251
252                         if (latent && ( i == latency_port) ) {
253                                 _latency_control_port  = &_control_data[i];
254                                 *_latency_control_port = 0;
255                         }
256
257                         if (parameter_is_input(i)) {
258                                 _shadow_data[i] = default_value(i);
259                         }
260                 } else {
261                         _defaults[i] = 0.0f;
262                 }
263         }
264
265         LilvUIs* uis = lilv_plugin_get_uis(plugin);
266         if (lilv_uis_size(uis) > 0) {
267 #ifdef HAVE_SUIL
268                 // Look for embeddable UI
269                 LILV_FOREACH(uis, u, uis) {
270                         const LilvUI*   this_ui      = lilv_uis_get(uis, u);
271                         const LilvNode* this_ui_type = NULL;
272                         if (lilv_ui_is_supported(this_ui,
273                                                  suil_ui_supported,
274                                                  _world.gtk_gui,
275                                                  &this_ui_type)) {
276                                 // TODO: Multiple UI support
277                                 _impl->ui      = this_ui;
278                                 _impl->ui_type = this_ui_type;
279                                 break;
280                         }
281                 }
282 #else
283                 // Look for Gtk native UI
284                 LILV_FOREACH(uis, i, uis) {
285                         const LilvUI* ui = lilv_uis_get(uis, i);
286                         if (lilv_ui_is_a(ui, _world.gtk_gui)) {
287                                 _impl->ui      = ui;
288                                 _impl->ui_type = _world.gtk_gui;
289                                 break;
290                         }
291                 }
292 #endif
293
294                 // If Gtk UI is not available, try to find external UI
295                 if (!_impl->ui) {
296                         LILV_FOREACH(uis, i, uis) {
297                                 const LilvUI* ui = lilv_uis_get(uis, i);
298                                 if (lilv_ui_is_a(ui, _world.external_gui)) {
299                                         _impl->ui      = ui;
300                                         _impl->ui_type = _world.external_gui;
301                                         break;
302                                 }
303                         }
304                 }
305         }
306
307         latency_compute_run();
308 }
309
310 LV2Plugin::~LV2Plugin ()
311 {
312         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 destroy\n", name()));
313
314         deactivate();
315         cleanup();
316
317         lilv_instance_free(_impl->instance);
318         lilv_node_free(_impl->name);
319         lilv_node_free(_impl->author);
320
321         delete [] _control_data;
322         delete [] _shadow_data;
323 }
324
325 bool
326 LV2Plugin::is_external_ui() const
327 {
328         if (!_impl->ui) {
329                 return false;
330         }
331         return lilv_ui_is_a(_impl->ui, _world.external_gui);
332 }
333
334 string
335 LV2Plugin::unique_id() const
336 {
337         return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
338 }
339
340 const char*
341 LV2Plugin::uri() const
342 {
343         return lilv_node_as_uri(lilv_plugin_get_uri(_impl->plugin));
344 }
345
346 const char*
347 LV2Plugin::label() const
348 {
349         return lilv_node_as_string(_impl->name);
350 }
351
352 const char*
353 LV2Plugin::name() const
354 {
355         return lilv_node_as_string(_impl->name);
356 }
357
358 const char*
359 LV2Plugin::maker() const
360 {
361         return _impl->author ? lilv_node_as_string (_impl->author) : "Unknown";
362 }
363
364 uint32_t
365 LV2Plugin::num_ports() const
366 {
367         return lilv_plugin_get_num_ports(_impl->plugin);
368 }
369
370 uint32_t
371 LV2Plugin::parameter_count() const
372 {
373         return lilv_plugin_get_num_ports(_impl->plugin);
374 }
375
376 float
377 LV2Plugin::default_value(uint32_t port)
378 {
379         return _defaults[port];
380 }
381
382 const char*
383 LV2Plugin::port_symbol(uint32_t index) const
384 {
385         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, index);
386         if (!port) {
387                 error << name() << ": Invalid port index " << index << endmsg;
388         }
389
390         const LilvNode* sym = lilv_port_get_symbol(_impl->plugin, port);
391         return lilv_node_as_string(sym);
392 }
393
394 void
395 LV2Plugin::set_parameter(uint32_t which, float val)
396 {
397         DEBUG_TRACE(DEBUG::LV2, string_compose(
398                             "%1 set parameter %2 to %3\n", name(), which, val));
399
400         if (which < lilv_plugin_get_num_ports(_impl->plugin)) {
401                 _shadow_data[which] = val;
402         } else {
403                 warning << string_compose(
404                     _("Illegal parameter number used with plugin \"%1\". "
405                       "This is a bug in either %2 or the LV2 plugin <%3>"),
406                     name(), PROGRAM_NAME, unique_id()) << endmsg;
407         }
408
409         Plugin::set_parameter(which, val);
410 }
411
412 float
413 LV2Plugin::get_parameter(uint32_t which) const
414 {
415         if (parameter_is_input(which)) {
416                 return (float)_shadow_data[which];
417         } else {
418                 return (float)_control_data[which];
419         }
420         return 0.0f;
421 }
422
423 uint32_t
424 LV2Plugin::nth_parameter(uint32_t n, bool& ok) const
425 {
426         ok = false;
427         for (uint32_t c = 0, x = 0; x < lilv_plugin_get_num_ports(_impl->plugin); ++x) {
428                 if (parameter_is_control(x)) {
429                         if (c++ == n) {
430                                 ok = true;
431                                 return x;
432                         }
433                 }
434         }
435
436         return 0;
437 }
438
439 const void*
440 LV2Plugin::extension_data (const char* uri) const
441 {
442         return lilv_instance_get_extension_data(_impl->instance, uri);
443 }
444
445 void*
446 LV2Plugin::c_plugin ()
447 {
448         return _impl->plugin;
449 }
450
451 void*
452 LV2Plugin::c_ui ()
453 {
454         return (void*)_impl->ui;
455 }
456
457 void*
458 LV2Plugin::c_ui_type ()
459 {
460         return (void*)_impl->ui_type;
461 }
462
463 /** Directory for files created by the plugin (except during save). */
464 const std::string
465 LV2Plugin::scratch_dir() const
466 {
467         return Glib::build_filename(
468                 _session.plugins_dir(), _insert_id.to_s(), "scratch");
469 }
470
471 /** Directory for snapshots of files in the scratch directory. */
472 const std::string
473 LV2Plugin::file_dir() const
474 {
475         return Glib::build_filename(
476                 _session.plugins_dir(), _insert_id.to_s(), "files");
477 }
478
479 /** Directory to save state snapshot version @c num into. */
480 const std::string
481 LV2Plugin::state_dir(unsigned num) const
482 {
483         return Glib::build_filename(_session.plugins_dir(),
484                                     _insert_id.to_s(),
485                                     string_compose("state%1", num));
486 }
487
488 /** Implementation of state:makePath for files created at instantiation time.
489  * Note this is not used for files created at save time (Lilv deals with that).
490  */
491 char*
492 LV2Plugin::lv2_state_make_path(LV2_State_Make_Path_Handle handle,
493                                const char*                path)
494 {
495         LV2Plugin* me = (LV2Plugin*)handle;
496         if (me->_insert_id == PBD::ID("0")) {
497                 warning << string_compose(
498                         "File path \"%1\" requested but LV2 %2 has no insert ID",
499                         path, me->name()) << endmsg;
500                 return g_strdup(path);
501         }
502
503         const std::string abs_path = Glib::build_filename(me->scratch_dir(), path);
504         const std::string dirname  = Glib::path_get_dirname(abs_path);
505         g_mkdir_with_parents(dirname.c_str(), 0744);
506
507         DEBUG_TRACE(DEBUG::LV2, string_compose("new file path %1 => %2\n",
508                                                path, abs_path));
509
510         std::cerr << "MAKE PATH " << path
511                   << " => " << g_strndup(abs_path.c_str(), abs_path.length())
512                   << std::endl;
513         return g_strndup(abs_path.c_str(), abs_path.length());
514 }
515
516 static void
517 remove_directory(const std::string& path)
518 {
519         if (!Glib::file_test(path, Glib::FILE_TEST_IS_DIR)) {
520                 warning << string_compose("\"%1\" is not a directory", path) << endmsg;
521                 return;
522         }
523
524         Glib::RefPtr<Gio::File>           dir = Gio::File::create_for_path(path);
525         Glib::RefPtr<Gio::FileEnumerator> e   = dir->enumerate_children();
526         Glib::RefPtr<Gio::FileInfo>       fi;
527         while ((fi = e->next_file())) {
528                 if (fi->get_type() == Gio::FILE_TYPE_DIRECTORY) {
529                         remove_directory(fi->get_name());
530                 } else {
531                         dir->get_child(fi->get_name())->remove();
532                 }
533         }
534         dir->remove();
535 }
536
537 void
538 LV2Plugin::add_state(XMLNode* root) const
539 {
540         assert(_insert_id != PBD::ID("0"));
541
542         XMLNode*    child;
543         char        buf[16];
544         LocaleGuard lg(X_("POSIX"));
545
546         for (uint32_t i = 0; i < parameter_count(); ++i) {
547                 if (parameter_is_input(i) && parameter_is_control(i)) {
548                         child = new XMLNode("Port");
549                         child->add_property("symbol", port_symbol(i));
550                         snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
551                         child->add_property("value", string(buf));
552                         root->add_child_nocopy(*child);
553                 }
554         }
555
556         if (_has_state_interface) {
557                 cout << "LV2 " << name() << " has state interface" << endl;
558 #ifdef HAVE_NEW_LILV
559                 // Provisionally increment state version and create directory
560                 const std::string new_dir = state_dir(++_state_version);
561                 g_mkdir_with_parents(new_dir.c_str(), 0744);
562
563                 cout << "NEW DIR: " << new_dir << endl;
564
565                 LilvState* state = lilv_state_new_from_instance(
566                         _impl->plugin,
567                         _impl->instance,
568                         _uri_map.urid_map(),
569                         scratch_dir().c_str(),
570                         file_dir().c_str(),
571                         _session.externals_dir().c_str(),
572                         new_dir.c_str(),
573                         NULL,
574                         (void*)this,
575                         0,
576                         NULL);
577
578                 if (!_impl->state || !lilv_state_equals(state, _impl->state)) {
579                         lilv_state_save(_world.world,
580                                         _uri_map.urid_unmap(),
581                                         state,
582                                         NULL,
583                                         new_dir.c_str(),
584                                         "state.ttl",
585                                         NULL);
586
587                         lilv_state_free(_impl->state);
588                         _impl->state = state;
589
590                         cout << "Saved LV2 state to " << state_dir(_state_version) << endl;
591                 } else {
592                         // State is identical, decrement version and nuke directory
593                         cout << "LV2 state identical, not saving" << endl;
594                         lilv_state_free(state);
595                         remove_directory(new_dir);
596                         --_state_version;
597                 }
598
599                 root->add_property("state-dir", string_compose("state%1", _state_version));
600
601 #else  /* !HAVE_NEW_LILV */
602                 warning << string_compose(
603                         _("Plugin \"%1\" has state, but Lilv is too old to save it"),
604                         unique_id()) << endmsg;
605 #endif  /* HAVE_NEW_LILV */
606         } else {
607                 cout << "LV2 " << name() << " has no state interface." << endl;
608         }
609 }
610
611 static inline const LilvNode*
612 get_value(LilvWorld* world, const LilvNode* subject, const LilvNode* predicate)
613 {
614         LilvNodes* vs = lilv_world_find_nodes(world, subject, predicate, NULL);
615         return vs ? lilv_nodes_get_first(vs) : NULL;
616 }
617
618 static void
619 find_presets_helper(LilvWorld*                                   world,
620                     LilvPlugin*                                  plugin,
621                     std::map<std::string, Plugin::PresetRecord>& out,
622                     LilvNode*                                    preset_pred,
623                     LilvNode*                                    title_pred)
624 {
625         LilvNodes* presets = lilv_plugin_get_value(plugin, preset_pred);
626         LILV_FOREACH(nodes, i, presets) {
627                 const LilvNode* preset = lilv_nodes_get(presets, i);
628                 const LilvNode* name   = get_value(world, preset, title_pred);
629                 if (name) {
630                         out.insert(std::make_pair(lilv_node_as_string(preset),
631                                                   Plugin::PresetRecord(
632                                                           lilv_node_as_string(preset),
633                                                           lilv_node_as_string(name))));
634                 } else {
635                         warning << string_compose(
636                             _("Plugin \"%1\% preset \"%2%\" is missing a label\n"),
637                             lilv_node_as_string(lilv_plugin_get_uri(plugin)),
638                             lilv_node_as_string(preset)) << endmsg;
639                 }
640         }
641         lilv_nodes_free(presets);
642 }
643
644 void
645 LV2Plugin::find_presets()
646 {
647         LilvNode* dc_title          = lilv_new_uri(_world.world, NS_DC   "title");
648         LilvNode* oldpset_hasPreset = lilv_new_uri(_world.world, NS_OLDPSET "hasPreset");
649         LilvNode* pset_hasPreset    = lilv_new_uri(_world.world, NS_PSET "hasPreset");
650         LilvNode* rdfs_label        = lilv_new_uri(_world.world, LILV_NS_RDFS "label");
651
652         find_presets_helper(_world.world, _impl->plugin, _presets,
653                             oldpset_hasPreset, dc_title);
654
655         find_presets_helper(_world.world, _impl->plugin, _presets,
656                             pset_hasPreset, rdfs_label);
657
658         lilv_node_free(rdfs_label);
659         lilv_node_free(pset_hasPreset);
660         lilv_node_free(oldpset_hasPreset);
661         lilv_node_free(dc_title);
662 }
663
664 bool
665 LV2Plugin::load_preset(PresetRecord r)
666 {
667         Plugin::load_preset(r);
668
669         LilvNode* lv2_port      = lilv_new_uri(_world.world, LILV_NS_LV2 "port");
670         LilvNode* lv2_symbol    = lilv_new_uri(_world.world, LILV_NS_LV2 "symbol");
671         LilvNode* oldpset_value = lilv_new_uri(_world.world, NS_OLDPSET "value");
672         LilvNode* preset        = lilv_new_uri(_world.world, r.uri.c_str());
673         LilvNode* pset_value    = lilv_new_uri(_world.world, NS_PSET "value");
674
675         LilvNodes* ports = lilv_world_find_nodes(_world.world, preset, lv2_port, NULL);
676         LILV_FOREACH(nodes, i, ports) {
677                 const LilvNode* port   = lilv_nodes_get(ports, i);
678                 const LilvNode* symbol = get_value(_world.world, port, lv2_symbol);
679                 const LilvNode* value  = get_value(_world.world, port, pset_value);
680                 if (!value) {
681                         value = get_value(_world.world, port, oldpset_value);
682                 }
683                 if (value && lilv_node_is_float(value)) {
684                         set_parameter(_port_indices[lilv_node_as_string(symbol)],
685                                       lilv_node_as_float(value));
686                 }
687         }
688         lilv_nodes_free(ports);
689
690         lilv_node_free(pset_value);
691         lilv_node_free(preset);
692         lilv_node_free(oldpset_value);
693         lilv_node_free(lv2_symbol);
694         lilv_node_free(lv2_port);
695
696         return true;
697 }
698
699 std::string
700 LV2Plugin::do_save_preset(string /*name*/)
701 {
702         return "";
703 }
704
705 void
706 LV2Plugin::do_remove_preset(string /*name*/)
707 {}
708
709 bool
710 LV2Plugin::has_editor() const
711 {
712         return _impl->ui != NULL;
713 }
714
715 void
716 LV2Plugin::set_insert_info(const PluginInsert* insert)
717 {
718         _insert_id = insert->id();
719 }
720
721 int
722 LV2Plugin::set_state(const XMLNode& node, int version)
723 {
724         XMLNodeList          nodes;
725         const XMLProperty*   prop;
726         XMLNodeConstIterator iter;
727         XMLNode*             child;
728         const char*          sym;
729         const char*          value;
730         uint32_t             port_id;
731         LocaleGuard          lg(X_("POSIX"));
732
733         if (node.name() != state_node_name()) {
734                 error << _("Bad node sent to LV2Plugin::set_state") << endmsg;
735                 return -1;
736         }
737
738         if (version < 3000) {
739                 nodes = node.children("port");
740         } else {
741                 nodes = node.children("Port");
742         }
743
744         for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
745
746                 child = *iter;
747
748                 if ((prop = child->property("symbol")) != 0) {
749                         sym = prop->value().c_str();
750                 } else {
751                         warning << _("LV2: port has no symbol, ignored") << endmsg;
752                         continue;
753                 }
754
755                 map<string, uint32_t>::iterator i = _port_indices.find(sym);
756
757                 if (i != _port_indices.end()) {
758                         port_id = i->second;
759                 } else {
760                         warning << _("LV2: port has unknown index, ignored") << endmsg;
761                         continue;
762                 }
763
764                 if ((prop = child->property("value")) != 0) {
765                         value = prop->value().c_str();
766                 } else {
767                         warning << _("LV2: port has no value, ignored") << endmsg;
768                         continue;
769                 }
770
771                 set_parameter(port_id, atof(value));
772         }
773
774 #ifdef HAVE_NEW_LILV
775         _state_version = 0;
776         if ((prop = node.property("state-dir")) != 0) {
777                 if (sscanf(prop->value().c_str(), "state%u", &_state_version) != 1) {
778                         error << string_compose(
779                                 "LV2: failed to parse state version from \"%1\"",
780                                 prop->value()) << endmsg;
781                 }
782
783                 std::string state_file = Glib::build_filename(_session.plugins_dir(),
784                                                               _insert_id.to_s(),
785                                                               prop->value(),
786                                                               "state.ttl");
787
788                 cout << "Loading LV2 state from " << state_file << endl;
789                 LilvState* state = lilv_state_new_from_file(
790                         _world.world, _uri_map.urid_map(), NULL, state_file.c_str());
791
792                 lilv_state_restore(state, _impl->instance, NULL, NULL, 0, NULL);
793         }
794 #endif
795
796         latency_compute_run();
797
798         return Plugin::set_state(node, version);
799 }
800
801 int
802 LV2Plugin::get_parameter_descriptor(uint32_t which, ParameterDescriptor& desc) const
803 {
804         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, which);
805
806         LilvNode *def, *min, *max;
807         lilv_port_get_range(_impl->plugin, port, &def, &min, &max);
808
809         desc.integer_step = lilv_port_has_property(_impl->plugin, port, _world.integer);
810         desc.toggled      = lilv_port_has_property(_impl->plugin, port, _world.toggled);
811         desc.logarithmic  = lilv_port_has_property(_impl->plugin, port, _world.logarithmic);
812         desc.sr_dependent = lilv_port_has_property(_impl->plugin, port, _world.srate);
813         desc.label        = lilv_node_as_string(lilv_port_get_name(_impl->plugin, port));
814         desc.lower        = min ? lilv_node_as_float(min) : 0.0f;
815         desc.upper        = max ? lilv_node_as_float(max) : 1.0f;
816         if (desc.sr_dependent) {
817                 desc.lower *= _session.frame_rate ();
818                 desc.upper *= _session.frame_rate ();
819         }
820
821         desc.min_unbound  = false; // TODO: LV2 extension required
822         desc.max_unbound  = false; // TODO: LV2 extension required
823
824         if (desc.integer_step) {
825                 desc.step      = 1.0;
826                 desc.smallstep = 0.1;
827                 desc.largestep = 10.0;
828         } else {
829                 const float delta = desc.upper - desc.lower;
830                 desc.step      = delta / 1000.0f;
831                 desc.smallstep = delta / 10000.0f;
832                 desc.largestep = delta / 10.0f;
833         }
834
835         lilv_node_free(def);
836         lilv_node_free(min);
837         lilv_node_free(max);
838
839         return 0;
840 }
841
842 string
843 LV2Plugin::describe_parameter(Evoral::Parameter which)
844 {
845         if (( which.type() == PluginAutomation) && ( which.id() < parameter_count()) ) {
846                 LilvNode* name = lilv_port_get_name(_impl->plugin,
847                                                     lilv_plugin_get_port_by_index(_impl->plugin, which.id()));
848                 string ret(lilv_node_as_string(name));
849                 lilv_node_free(name);
850                 return ret;
851         } else {
852                 return "??";
853         }
854 }
855
856 framecnt_t
857 LV2Plugin::signal_latency() const
858 {
859         if (_latency_control_port) {
860                 return (framecnt_t)floor(*_latency_control_port);
861         } else {
862                 return 0;
863         }
864 }
865
866 set<Evoral::Parameter>
867 LV2Plugin::automatable() const
868 {
869         set<Evoral::Parameter> ret;
870
871         for (uint32_t i = 0; i < parameter_count(); ++i) {
872                 if (parameter_is_input(i) && parameter_is_control(i)) {
873                         ret.insert(ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
874                 }
875         }
876
877         return ret;
878 }
879
880 void
881 LV2Plugin::activate()
882 {
883         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 activate\n", name()));
884
885         if (!_was_activated) {
886                 lilv_instance_activate(_impl->instance);
887                 _was_activated = true;
888         }
889 }
890
891 void
892 LV2Plugin::deactivate()
893 {
894         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 deactivate\n", name()));
895
896         if (_was_activated) {
897                 lilv_instance_deactivate(_impl->instance);
898                 _was_activated = false;
899         }
900 }
901
902 void
903 LV2Plugin::cleanup()
904 {
905         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 cleanup\n", name()));
906
907         activate();
908         deactivate();
909         lilv_instance_free(_impl->instance);
910         _impl->instance = NULL;
911 }
912
913 int
914 LV2Plugin::connect_and_run(BufferSet& bufs,
915         ChanMapping in_map, ChanMapping out_map,
916         pframes_t nframes, framecnt_t offset)
917 {
918         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 run %2 offset %3\n", name(), nframes, offset));
919         Plugin::connect_and_run(bufs, in_map, out_map, nframes, offset);
920
921         cycles_t then = get_cycles();
922
923         ChanCount bufs_count;
924         bufs_count.set(DataType::AUDIO, 1);
925         bufs_count.set(DataType::MIDI, 1);
926         BufferSet& silent_bufs  = _session.get_silent_buffers(bufs_count);
927         BufferSet& scratch_bufs = _session.get_silent_buffers(bufs_count);
928         uint32_t const num_ports = parameter_count();
929
930         uint32_t audio_in_index  = 0;
931         uint32_t audio_out_index = 0;
932         uint32_t midi_in_index   = 0;
933         uint32_t midi_out_index  = 0;
934         bool valid;
935         for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
936                 if (parameter_is_audio(port_index)) {
937                         if (parameter_is_input(port_index)) {
938                                 const uint32_t buf_index = in_map.get(DataType::AUDIO, audio_in_index++, &valid);
939                                 lilv_instance_connect_port(_impl->instance, port_index,
940                                                            valid ? bufs.get_audio(buf_index).data(offset)
941                                                                  : silent_bufs.get_audio(0).data(offset));
942                         } else if (parameter_is_output(port_index)) {
943                                 const uint32_t buf_index = out_map.get(DataType::AUDIO, audio_out_index++, &valid);
944                                 //cerr << port_index << " : " << " AUDIO OUT " << buf_index << endl;
945                                 lilv_instance_connect_port(_impl->instance, port_index,
946                                                            valid ? bufs.get_audio(buf_index).data(offset)
947                                                                  : scratch_bufs.get_audio(0).data(offset));
948                         }
949                 } else if (parameter_is_midi(port_index)) {
950                         /* FIXME: The checks here for bufs.count().n_midi() > buf_index shouldn't
951                            be necessary, but the mapping is illegal in some cases.  Ideally
952                            that should be fixed, but this is easier...
953                         */
954                         if (parameter_is_input(port_index)) {
955                                 const uint32_t buf_index = in_map.get(DataType::MIDI, midi_in_index++, &valid);
956                                 if (valid && bufs.count().n_midi() > buf_index) {
957                                         lilv_instance_connect_port(_impl->instance, port_index,
958                                                                    bufs.get_lv2_midi(true, buf_index).data());
959                                 } else {
960                                         lilv_instance_connect_port(_impl->instance, port_index,
961                                                                    silent_bufs.get_lv2_midi(true, 0).data());
962                                 }
963                         } else if (parameter_is_output(port_index)) {
964                                 const uint32_t buf_index = out_map.get(DataType::MIDI, midi_out_index++, &valid);
965                                 if (valid && bufs.count().n_midi() > buf_index) {
966                                         lilv_instance_connect_port(_impl->instance, port_index,
967                                                                    bufs.get_lv2_midi(false, buf_index).data());
968                                 } else {
969                                         lilv_instance_connect_port(_impl->instance, port_index,
970                                                                    scratch_bufs.get_lv2_midi(true, 0).data());
971                                 }
972                         }
973                 } else if (!parameter_is_control(port_index)) {
974                         // Optional port (it'd better be if we've made it this far...)
975                         lilv_instance_connect_port(_impl->instance, port_index, NULL);
976                 }
977         }
978
979         run(nframes);
980
981         midi_out_index = 0;
982         for (uint32_t port_index = 0; port_index < num_ports; ++port_index) {
983                 if (parameter_is_midi(port_index) && parameter_is_output(port_index)) {
984                         const uint32_t buf_index = out_map.get(DataType::MIDI, midi_out_index++, &valid);
985                         if (valid) {
986                                 bufs.flush_lv2_midi(true, buf_index);
987                         }
988                 }
989         }
990
991         cycles_t now = get_cycles();
992         set_cycles((uint32_t)(now - then));
993
994         return 0;
995 }
996
997 bool
998 LV2Plugin::parameter_is_control(uint32_t param) const
999 {
1000         assert(param < _port_is_control.size());
1001         return _port_is_control[param];
1002 }
1003
1004 bool
1005 LV2Plugin::parameter_is_audio(uint32_t param) const
1006 {
1007         assert(param < _port_is_audio.size());
1008         return _port_is_audio[param];
1009 }
1010
1011 bool
1012 LV2Plugin::parameter_is_midi(uint32_t param) const
1013 {
1014         assert(param < _port_is_midi.size());
1015         return _port_is_midi[param];
1016 }
1017
1018 bool
1019 LV2Plugin::parameter_is_output(uint32_t param) const
1020 {
1021         assert(param < _port_is_output.size());
1022         return _port_is_output[param];
1023 }
1024
1025 bool
1026 LV2Plugin::parameter_is_input(uint32_t param) const
1027 {
1028         assert(param < _port_is_input.size());
1029         return _port_is_input[param];
1030 }
1031
1032 void
1033 LV2Plugin::print_parameter(uint32_t param, char* buf, uint32_t len) const
1034 {
1035         if (buf && len) {
1036                 if (param < parameter_count()) {
1037                         snprintf(buf, len, "%.3f", get_parameter(param));
1038                 } else {
1039                         strcat(buf, "0");
1040                 }
1041         }
1042 }
1043
1044 boost::shared_ptr<Plugin::ScalePoints>
1045 LV2Plugin::get_scale_points(uint32_t port_index) const
1046 {
1047         const LilvPort*  port   = lilv_plugin_get_port_by_index(_impl->plugin, port_index);
1048         LilvScalePoints* points = lilv_port_get_scale_points(_impl->plugin, port);
1049
1050         boost::shared_ptr<Plugin::ScalePoints> ret;
1051         if (!points) {
1052                 return ret;
1053         }
1054
1055         ret = boost::shared_ptr<Plugin::ScalePoints>(new ScalePoints());
1056
1057         LILV_FOREACH(scale_points, i, points) {
1058                 const LilvScalePoint* p     = lilv_scale_points_get(points, i);
1059                 const LilvNode*       label = lilv_scale_point_get_label(p);
1060                 const LilvNode*       value = lilv_scale_point_get_value(p);
1061                 if (label && (lilv_node_is_float(value) || lilv_node_is_int(value))) {
1062                         ret->insert(make_pair(lilv_node_as_string(label),
1063                                               lilv_node_as_float(value)));
1064                 }
1065         }
1066
1067         lilv_scale_points_free(points);
1068         return ret;
1069 }
1070
1071 void
1072 LV2Plugin::run(pframes_t nframes)
1073 {
1074         uint32_t const N = parameter_count();
1075         for (uint32_t i = 0; i < N; ++i) {
1076                 if (parameter_is_control(i) && parameter_is_input(i)) {
1077                         _control_data[i] = _shadow_data[i];
1078                 }
1079         }
1080
1081         lilv_instance_run(_impl->instance, nframes);
1082 }
1083
1084 void
1085 LV2Plugin::latency_compute_run()
1086 {
1087         if (!_latency_control_port) {
1088                 return;
1089         }
1090
1091         // Run the plugin so that it can set its latency parameter
1092
1093         activate();
1094
1095         uint32_t port_index = 0;
1096         uint32_t in_index   = 0;
1097         uint32_t out_index  = 0;
1098
1099         const framecnt_t bufsize = 1024;
1100         float            buffer[bufsize];
1101
1102         memset(buffer, 0, sizeof(float) * bufsize);
1103
1104         // FIXME: Ensure plugins can handle in-place processing
1105
1106         port_index = 0;
1107
1108         while (port_index < parameter_count()) {
1109                 if (parameter_is_audio(port_index)) {
1110                         if (parameter_is_input(port_index)) {
1111                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1112                                 in_index++;
1113                         } else if (parameter_is_output(port_index)) {
1114                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1115                                 out_index++;
1116                         }
1117                 }
1118                 port_index++;
1119         }
1120
1121         run(bufsize);
1122         deactivate();
1123 }
1124
1125 LV2World::LV2World()
1126         : world(lilv_world_new())
1127 {
1128         lilv_world_load_all(world);
1129         input_class     = lilv_new_uri(world, LILV_URI_INPUT_PORT);
1130         output_class    = lilv_new_uri(world, LILV_URI_OUTPUT_PORT);
1131         control_class   = lilv_new_uri(world, LILV_URI_CONTROL_PORT);
1132         audio_class     = lilv_new_uri(world, LILV_URI_AUDIO_PORT);
1133         event_class     = lilv_new_uri(world, LILV_URI_EVENT_PORT);
1134         midi_class      = lilv_new_uri(world, LILV_URI_MIDI_EVENT);
1135         in_place_broken = lilv_new_uri(world, LILV_NS_LV2 "inPlaceBroken");
1136         integer         = lilv_new_uri(world, LILV_NS_LV2 "integer");
1137         toggled         = lilv_new_uri(world, LILV_NS_LV2 "toggled");
1138         srate           = lilv_new_uri(world, LILV_NS_LV2 "sampleRate");
1139         gtk_gui         = lilv_new_uri(world, NS_UI "GtkUI");
1140         external_gui    = lilv_new_uri(world, NS_UI "external");
1141         logarithmic     = lilv_new_uri(world, "http://lv2plug.in/ns/dev/extportinfo#logarithmic");
1142 }
1143
1144 LV2World::~LV2World()
1145 {
1146         lilv_node_free(input_class);
1147         lilv_node_free(output_class);
1148         lilv_node_free(control_class);
1149         lilv_node_free(audio_class);
1150         lilv_node_free(event_class);
1151         lilv_node_free(midi_class);
1152         lilv_node_free(in_place_broken);
1153 }
1154
1155 LV2PluginInfo::LV2PluginInfo (void* c_plugin)
1156         : _c_plugin(c_plugin)
1157 {
1158         type = ARDOUR::LV2;
1159 }
1160
1161 LV2PluginInfo::~LV2PluginInfo()
1162 {}
1163
1164 PluginPtr
1165 LV2PluginInfo::load(Session& session)
1166 {
1167         try {
1168                 PluginPtr plugin;
1169
1170                 plugin.reset(new LV2Plugin(session.engine(), session,
1171                                            (LilvPlugin*)_c_plugin,
1172                                            session.frame_rate()));
1173
1174                 plugin->set_info(PluginInfoPtr(new LV2PluginInfo(*this)));
1175                 return plugin;
1176         } catch (failed_constructor& err) {
1177                 return PluginPtr((Plugin*)0);
1178         }
1179
1180         return PluginPtr();
1181 }
1182
1183 PluginInfoList*
1184 LV2PluginInfo::discover()
1185 {
1186         PluginInfoList*    plugs   = new PluginInfoList;
1187         const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
1188
1189         cerr << "LV2: Discovering " << lilv_plugins_size(plugins) << " plugins" << endl;
1190
1191         LILV_FOREACH(plugins, i, plugins) {
1192                 const LilvPlugin* p = lilv_plugins_get(plugins, i);
1193                 LV2PluginInfoPtr  info(new LV2PluginInfo((void*)p));
1194
1195                 LilvNode* name = lilv_plugin_get_name(p);
1196                 if (!name) {
1197                         cerr << "LV2: invalid plugin\n";
1198                         continue;
1199                 }
1200
1201                 info->type = LV2;
1202
1203                 info->name = string(lilv_node_as_string(name));
1204                 lilv_node_free(name);
1205
1206                 const LilvPluginClass* pclass = lilv_plugin_get_class(p);
1207                 const LilvNode*        label  = lilv_plugin_class_get_label(pclass);
1208                 info->category = lilv_node_as_string(label);
1209
1210                 LilvNode* author_name = lilv_plugin_get_author_name(p);
1211                 info->creator = author_name ? string(lilv_node_as_string(author_name)) : "Unknown";
1212                 lilv_node_free(author_name);
1213
1214                 info->path = "/NOPATH"; // Meaningless for LV2
1215
1216                 info->n_inputs.set_audio(
1217                         lilv_plugin_get_num_ports_of_class(
1218                                 p, _world.input_class, _world.audio_class, NULL));
1219                 info->n_inputs.set_midi(
1220                         lilv_plugin_get_num_ports_of_class(
1221                                 p, _world.input_class, _world.event_class, NULL));
1222
1223                 info->n_outputs.set_audio(
1224                         lilv_plugin_get_num_ports_of_class(
1225                                 p, _world.output_class, _world.audio_class, NULL));
1226                 info->n_outputs.set_midi(
1227                         lilv_plugin_get_num_ports_of_class(
1228                                 p, _world.output_class, _world.event_class, NULL));
1229
1230                 info->unique_id = lilv_node_as_uri(lilv_plugin_get_uri(p));
1231                 info->index     = 0; // Meaningless for LV2
1232
1233                 plugs->push_back(info);
1234         }
1235
1236         cerr << "Done LV2 discovery" << endl;
1237
1238         return plugs;
1239 }