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