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