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