do not offer combine operation for MIDI (see comment in libs/ardour/midi_playlist_sou...
[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                 const std::string state_filename = _insert_id.to_s() + ".rdff";
586                 const std::string state_path     = Glib::build_filename(
587                         _session.plugins_dir(), state_filename);
588
589                 cout << "Saving LV2 plugin state to " << state_path << endl;
590
591                 // Get LV2 Persist extension data from plugin instance
592                 LV2_Persist* persist = (LV2_Persist*)extension_data(
593                         "http://lv2plug.in/ns/ext/persist");
594                 if (!persist) {
595                         warning << string_compose(
596                             _("Plugin \"%1\% failed to return LV2 persist data"),
597                             unique_id());
598                         return;
599                 }
600
601                 // Save plugin state to state object
602                 LV2PersistState state(_uri_map);
603                 persist->save(_impl->instance->lv2_handle,
604                               &LV2Plugin::lv2_persist_store_callback,
605                               &state);
606
607                 // Write state object to RDFF file
608                 RDFF file = rdff_open(state_path.c_str(), true);
609                 state.write(file);
610                 rdff_close(file);
611
612                 root->add_property("state-file", state_filename);
613         }
614 }
615
616 static inline const LilvNode*
617 get_value(LilvWorld* world, const LilvNode* subject, const LilvNode* predicate)
618 {
619         LilvNodes* vs = lilv_world_find_nodes(world, subject, predicate, NULL);
620         return vs ? lilv_nodes_get_first(vs) : NULL;
621 }
622
623 void
624 LV2Plugin::find_presets()
625 {
626         LilvNode* dc_title       = lilv_new_uri(_world.world, NS_DC   "title");
627         LilvNode* pset_hasPreset = lilv_new_uri(_world.world, NS_PSET "hasPreset");
628
629         LilvNodes* presets = lilv_plugin_get_value(_impl->plugin, pset_hasPreset);
630         LILV_FOREACH(nodes, i, presets) {
631                 const LilvNode* preset = lilv_nodes_get(presets, i);
632                 const LilvNode* name   = get_value(_world.world, preset, dc_title);
633                 if (name) {
634                         _presets.insert(std::make_pair(lilv_node_as_string(preset),
635                                                        PresetRecord(
636                                                            lilv_node_as_string(preset),
637                                                            lilv_node_as_string(name))));
638                 } else {
639                         warning << string_compose(
640                             _("Plugin \"%1\% preset \"%2%\" is missing a dc:title\n"),
641                             unique_id(), lilv_node_as_string(preset));
642                 }
643         }
644         lilv_nodes_free(presets);
645
646         lilv_node_free(pset_hasPreset);
647         lilv_node_free(dc_title);
648 }
649
650 bool
651 LV2Plugin::load_preset(PresetRecord r)
652 {
653         Plugin::load_preset(r);
654
655         LilvNode* lv2_port   = lilv_new_uri(_world.world, NS_LV2 "port");
656         LilvNode* lv2_symbol = lilv_new_uri(_world.world, NS_LV2 "symbol");
657         LilvNode* pset_value = lilv_new_uri(_world.world, NS_PSET "value");
658         LilvNode* preset     = lilv_new_uri(_world.world, r.uri.c_str());
659
660         LilvNodes* ports = lilv_world_find_nodes(_world.world, preset, lv2_port, NULL);
661         LILV_FOREACH(nodes, i, ports) {
662                 const LilvNode* port   = lilv_nodes_get(ports, i);
663                 const LilvNode* symbol = get_value(_world.world, port, lv2_symbol);
664                 const LilvNode* value  = get_value(_world.world, port, pset_value);
665                 if (value && lilv_node_is_float(value)) {
666                         set_parameter(_port_indices[lilv_node_as_string(symbol)],
667                                       lilv_node_as_float(value));
668                 }
669         }
670         lilv_nodes_free(ports);
671
672         lilv_node_free(preset);
673         lilv_node_free(pset_value);
674         lilv_node_free(lv2_symbol);
675         lilv_node_free(lv2_port);
676
677         return true;
678 }
679
680 std::string
681 LV2Plugin::do_save_preset(string /*name*/)
682 {
683         return "";
684 }
685
686 void
687 LV2Plugin::do_remove_preset(string /*name*/)
688 {}
689
690 bool
691 LV2Plugin::has_editor() const
692 {
693         return _impl->ui != NULL;
694 }
695
696 void
697 LV2Plugin::set_insert_info(const PluginInsert* insert)
698 {
699         _insert_id = insert->id();
700 }
701
702 int
703 LV2Plugin::set_state(const XMLNode& node, int version)
704 {
705         XMLNodeList          nodes;
706         const XMLProperty*   prop;
707         XMLNodeConstIterator iter;
708         XMLNode*             child;
709         const char*          sym;
710         const char*          value;
711         uint32_t             port_id;
712         LocaleGuard          lg(X_("POSIX"));
713
714         if (node.name() != state_node_name()) {
715                 error << _("Bad node sent to LV2Plugin::set_state") << endmsg;
716                 return -1;
717         }
718
719         if (version < 3000) {
720                 nodes = node.children("port");
721         } else {
722                 nodes = node.children("Port");
723         }
724
725         for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
726
727                 child = *iter;
728
729                 if ((prop = child->property("symbol")) != 0) {
730                         sym = prop->value().c_str();
731                 } else {
732                         warning << _("LV2: port has no symbol, ignored") << endmsg;
733                         continue;
734                 }
735
736                 map<string, uint32_t>::iterator i = _port_indices.find(sym);
737
738                 if (i != _port_indices.end()) {
739                         port_id = i->second;
740                 } else {
741                         warning << _("LV2: port has unknown index, ignored") << endmsg;
742                         continue;
743                 }
744
745                 if ((prop = child->property("value")) != 0) {
746                         value = prop->value().c_str();
747                 } else {
748                         warning << _("LV2: port has no value, ignored") << endmsg;
749                         continue;
750                 }
751
752                 set_parameter(port_id, atof(value));
753         }
754
755         if ((prop = node.property("state-file")) != 0) {
756                 std::string state_path = Glib::build_filename(_session.plugins_dir(),
757                                                               prop->value());
758
759                 cout << "LV2 state path " << state_path << endl;
760
761                 // Get LV2 Persist extension data from plugin instance
762                 LV2_Persist* persist = (LV2_Persist*)extension_data(
763                         "http://lv2plug.in/ns/ext/persist");
764                 if (persist) {
765                         cout << "Loading LV2 state from " << state_path << endl;
766                         RDFF            file = rdff_open(state_path.c_str(), false);
767                         LV2PersistState state(_uri_map);
768                         state.read(file);
769                         persist->restore(_impl->instance->lv2_handle,
770                                          &LV2Plugin::lv2_persist_retrieve_callback,
771                                          &state);
772                         rdff_close(file);
773                 } else {
774                         warning << string_compose(
775                             _("Plugin \"%1\% failed to return LV2 persist data"),
776                             unique_id());
777                 }
778         }
779
780         latency_compute_run();
781
782         return Plugin::set_state(node, version);
783 }
784
785 int
786 LV2Plugin::get_parameter_descriptor(uint32_t which, ParameterDescriptor& desc) const
787 {
788         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, which);
789
790         LilvNode *def, *min, *max;
791         lilv_port_get_range(_impl->plugin, port, &def, &min, &max);
792
793         desc.integer_step = lilv_port_has_property(_impl->plugin, port, _world.integer);
794         desc.toggled      = lilv_port_has_property(_impl->plugin, port, _world.toggled);
795         desc.logarithmic  = lilv_port_has_property(_impl->plugin, port, _world.logarithmic);
796         desc.sr_dependent = lilv_port_has_property(_impl->plugin, port, _world.srate);
797         desc.label        = lilv_node_as_string(lilv_port_get_name(_impl->plugin, port));
798         desc.lower        = min ? lilv_node_as_float(min) : 0.0f;
799         desc.upper        = max ? lilv_node_as_float(max) : 1.0f;
800         desc.min_unbound  = false; // TODO: LV2 extension required
801         desc.max_unbound  = false; // TODO: LV2 extension required
802
803         if (desc.integer_step) {
804                 desc.step      = 1.0;
805                 desc.smallstep = 0.1;
806                 desc.largestep = 10.0;
807         } else {
808                 const float delta = desc.upper - desc.lower;
809                 desc.step      = delta / 1000.0f;
810                 desc.smallstep = delta / 10000.0f;
811                 desc.largestep = delta / 10.0f;
812         }
813
814         lilv_node_free(def);
815         lilv_node_free(min);
816         lilv_node_free(max);
817
818         return 0;
819 }
820
821 string
822 LV2Plugin::describe_parameter(Evoral::Parameter which)
823 {
824         if (( which.type() == PluginAutomation) && ( which.id() < parameter_count()) ) {
825                 LilvNode* name = lilv_port_get_name(_impl->plugin,
826                                                     lilv_plugin_get_port_by_index(_impl->plugin, which.id()));
827                 string ret(lilv_node_as_string(name));
828                 lilv_node_free(name);
829                 return ret;
830         } else {
831                 return "??";
832         }
833 }
834
835 framecnt_t
836 LV2Plugin::signal_latency() const
837 {
838         if (_latency_control_port) {
839                 return (framecnt_t)floor(*_latency_control_port);
840         } else {
841                 return 0;
842         }
843 }
844
845 set<Evoral::Parameter>
846 LV2Plugin::automatable() const
847 {
848         set<Evoral::Parameter> ret;
849
850         for (uint32_t i = 0; i < parameter_count(); ++i) {
851                 if (parameter_is_input(i) && parameter_is_control(i)) {
852                         ret.insert(ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
853                 }
854         }
855
856         return ret;
857 }
858
859 void
860 LV2Plugin::activate()
861 {
862         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 activate\n", name()));
863
864         if (!_was_activated) {
865                 lilv_instance_activate(_impl->instance);
866                 _was_activated = true;
867         }
868 }
869
870 void
871 LV2Plugin::deactivate()
872 {
873         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 deactivate\n", name()));
874
875         if (_was_activated) {
876                 lilv_instance_deactivate(_impl->instance);
877                 _was_activated = false;
878         }
879 }
880
881 void
882 LV2Plugin::cleanup()
883 {
884         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 cleanup\n", name()));
885
886         activate();
887         deactivate();
888         lilv_instance_free(_impl->instance);
889         _impl->instance = NULL;
890 }
891
892 int
893 LV2Plugin::connect_and_run(BufferSet& bufs,
894         ChanMapping in_map, ChanMapping out_map,
895         pframes_t nframes, framecnt_t offset)
896 {
897         DEBUG_TRACE(DEBUG::LV2, string_compose("%1 run %2 offset %3\n", name(), nframes, offset));
898         Plugin::connect_and_run(bufs, in_map, out_map, nframes, offset);
899
900         cycles_t then = get_cycles();
901
902         uint32_t audio_in_index  = 0;
903         uint32_t audio_out_index = 0;
904         uint32_t midi_in_index   = 0;
905         uint32_t midi_out_index  = 0;
906         for (uint32_t port_index = 0; port_index < parameter_count(); ++port_index) {
907                 if (parameter_is_audio(port_index)) {
908                         if (parameter_is_input(port_index)) {
909                                 const uint32_t buf_index = in_map.get(DataType::AUDIO, audio_in_index++);
910                                 lilv_instance_connect_port(_impl->instance, port_index,
911                                                            bufs.get_audio(buf_index).data(offset));
912                         } else if (parameter_is_output(port_index)) {
913                                 const uint32_t buf_index = out_map.get(DataType::AUDIO, audio_out_index++);
914                                 //cerr << port_index << " : " << " AUDIO OUT " << buf_index << endl;
915                                 lilv_instance_connect_port(_impl->instance, port_index,
916                                                            bufs.get_audio(buf_index).data(offset));
917                         }
918                 } else if (parameter_is_midi(port_index)) {
919                         if (parameter_is_input(port_index)) {
920                                 const uint32_t buf_index = in_map.get(DataType::MIDI, midi_in_index++);
921                                 lilv_instance_connect_port(_impl->instance, port_index,
922                                                            bufs.get_lv2_midi(true, buf_index).data());
923                         } else if (parameter_is_output(port_index)) {
924                                 const uint32_t buf_index = out_map.get(DataType::MIDI, midi_out_index++);
925                                 lilv_instance_connect_port(_impl->instance, port_index,
926                                                            bufs.get_lv2_midi(false, buf_index).data());
927                         }
928                 } else if (!parameter_is_control(port_index)) {
929                         // Optional port (it'd better be if we've made it this far...)
930                         lilv_instance_connect_port(_impl->instance, port_index, NULL);
931                 }
932         }
933
934         run(nframes);
935
936         midi_out_index = 0;
937         for (uint32_t port_index = 0; port_index < parameter_count(); ++port_index) {
938                 if (parameter_is_midi(port_index) && parameter_is_output(port_index)) {
939                         const uint32_t buf_index = out_map.get(DataType::MIDI, midi_out_index++);
940                         bufs.flush_lv2_midi(true, buf_index);
941                 }
942         }
943
944         cycles_t now = get_cycles();
945         set_cycles((uint32_t)(now - then));
946
947         return 0;
948 }
949
950 bool
951 LV2Plugin::parameter_is_control(uint32_t param) const
952 {
953         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, param);
954         return lilv_port_is_a(_impl->plugin, port, _world.control_class);
955 }
956
957 bool
958 LV2Plugin::parameter_is_audio(uint32_t param) const
959 {
960         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, param);
961         return lilv_port_is_a(_impl->plugin, port, _world.audio_class);
962 }
963
964 bool
965 LV2Plugin::parameter_is_midi(uint32_t param) const
966 {
967         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, param);
968         return lilv_port_is_a(_impl->plugin, port, _world.event_class);
969         //      && lilv_port_supports_event(_impl->plugin, port, _world.midi_class);
970 }
971
972 bool
973 LV2Plugin::parameter_is_output(uint32_t param) const
974 {
975         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, param);
976         return lilv_port_is_a(_impl->plugin, port, _world.output_class);
977 }
978
979 bool
980 LV2Plugin::parameter_is_input(uint32_t param) const
981 {
982         const LilvPort* port = lilv_plugin_get_port_by_index(_impl->plugin, param);
983         return lilv_port_is_a(_impl->plugin, port, _world.input_class);
984 }
985
986 void
987 LV2Plugin::print_parameter(uint32_t param, char* buf, uint32_t len) const
988 {
989         if (buf && len) {
990                 if (param < parameter_count()) {
991                         snprintf(buf, len, "%.3f", get_parameter(param));
992                 } else {
993                         strcat(buf, "0");
994                 }
995         }
996 }
997
998 boost::shared_ptr<Plugin::ScalePoints>
999 LV2Plugin::get_scale_points(uint32_t port_index) const
1000 {
1001         const LilvPort*  port   = lilv_plugin_get_port_by_index(_impl->plugin, port_index);
1002         LilvScalePoints* points = lilv_port_get_scale_points(_impl->plugin, port);
1003
1004         boost::shared_ptr<Plugin::ScalePoints> ret;
1005         if (!points) {
1006                 return ret;
1007         }
1008
1009         ret = boost::shared_ptr<Plugin::ScalePoints>(new ScalePoints());
1010
1011         LILV_FOREACH(scale_points, i, points) {
1012                 const LilvScalePoint* p     = lilv_scale_points_get(points, i);
1013                 const LilvNode*       label = lilv_scale_point_get_label(p);
1014                 const LilvNode*       value = lilv_scale_point_get_value(p);
1015                 if (label && (lilv_node_is_float(value) || lilv_node_is_int(value))) {
1016                         ret->insert(make_pair(lilv_node_as_string(label),
1017                                               lilv_node_as_float(value)));
1018                 }
1019         }
1020
1021         lilv_scale_points_free(points);
1022         return ret;
1023 }
1024
1025 void
1026 LV2Plugin::run(pframes_t nframes)
1027 {
1028         for (uint32_t i = 0; i < parameter_count(); ++i) {
1029                 if (parameter_is_control(i) && parameter_is_input(i)) {
1030                         _control_data[i] = _shadow_data[i];
1031                 }
1032         }
1033
1034         lilv_instance_run(_impl->instance, nframes);
1035 }
1036
1037 void
1038 LV2Plugin::latency_compute_run()
1039 {
1040         if (!_latency_control_port) {
1041                 return;
1042         }
1043
1044         // Run the plugin so that it can set its latency parameter
1045
1046         activate();
1047
1048         uint32_t port_index = 0;
1049         uint32_t in_index   = 0;
1050         uint32_t out_index  = 0;
1051
1052         const framecnt_t bufsize = 1024;
1053         float            buffer[bufsize];
1054
1055         memset(buffer, 0, sizeof(float) * bufsize);
1056
1057         // FIXME: Ensure plugins can handle in-place processing
1058
1059         port_index = 0;
1060
1061         while (port_index < parameter_count()) {
1062                 if (parameter_is_audio(port_index)) {
1063                         if (parameter_is_input(port_index)) {
1064                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1065                                 in_index++;
1066                         } else if (parameter_is_output(port_index)) {
1067                                 lilv_instance_connect_port(_impl->instance, port_index, buffer);
1068                                 out_index++;
1069                         }
1070                 }
1071                 port_index++;
1072         }
1073
1074         run(bufsize);
1075         deactivate();
1076 }
1077
1078 LV2World::LV2World()
1079         : world(lilv_world_new())
1080 {
1081         lilv_world_load_all(world);
1082         input_class     = lilv_new_uri(world, LILV_URI_INPUT_PORT);
1083         output_class    = lilv_new_uri(world, LILV_URI_OUTPUT_PORT);
1084         control_class   = lilv_new_uri(world, LILV_URI_CONTROL_PORT);
1085         audio_class     = lilv_new_uri(world, LILV_URI_AUDIO_PORT);
1086         event_class     = lilv_new_uri(world, LILV_URI_EVENT_PORT);
1087         midi_class      = lilv_new_uri(world, LILV_URI_MIDI_EVENT);
1088         in_place_broken = lilv_new_uri(world, LILV_NS_LV2 "inPlaceBroken");
1089         integer         = lilv_new_uri(world, LILV_NS_LV2 "integer");
1090         toggled         = lilv_new_uri(world, LILV_NS_LV2 "toggled");
1091         srate           = lilv_new_uri(world, LILV_NS_LV2 "sampleRate");
1092         gtk_gui         = lilv_new_uri(world, NS_UI "GtkUI");
1093         external_gui    = lilv_new_uri(world, NS_UI "external");
1094         logarithmic     = lilv_new_uri(world, "http://lv2plug.in/ns/dev/extportinfo#logarithmic");
1095 }
1096
1097 LV2World::~LV2World()
1098 {
1099         lilv_node_free(input_class);
1100         lilv_node_free(output_class);
1101         lilv_node_free(control_class);
1102         lilv_node_free(audio_class);
1103         lilv_node_free(event_class);
1104         lilv_node_free(midi_class);
1105         lilv_node_free(in_place_broken);
1106 }
1107
1108 LV2PluginInfo::LV2PluginInfo (void* c_plugin)
1109         : _c_plugin(c_plugin)
1110 {
1111         type = ARDOUR::LV2;
1112 }
1113
1114 LV2PluginInfo::~LV2PluginInfo()
1115 {}
1116
1117 PluginPtr
1118 LV2PluginInfo::load(Session& session)
1119 {
1120         try {
1121                 PluginPtr plugin;
1122
1123                 plugin.reset(new LV2Plugin(session.engine(), session,
1124                                            (LilvPlugin*)_c_plugin,
1125                                            session.frame_rate()));
1126
1127                 plugin->set_info(PluginInfoPtr(new LV2PluginInfo(*this)));
1128                 return plugin;
1129         } catch (failed_constructor& err) {
1130                 return PluginPtr((Plugin*)0);
1131         }
1132
1133         return PluginPtr();
1134 }
1135
1136 PluginInfoList*
1137 LV2PluginInfo::discover()
1138 {
1139         PluginInfoList*    plugs   = new PluginInfoList;
1140         const LilvPlugins* plugins = lilv_world_get_all_plugins(_world.world);
1141
1142         cerr << "LV2: Discovering " << lilv_plugins_size(plugins) << " plugins" << endl;
1143
1144         LILV_FOREACH(plugins, i, plugins) {
1145                 const LilvPlugin* p = lilv_plugins_get(plugins, i);
1146                 LV2PluginInfoPtr  info(new LV2PluginInfo((void*)p));
1147
1148                 LilvNode* name = lilv_plugin_get_name(p);
1149                 if (!name) {
1150                         cerr << "LV2: invalid plugin\n";
1151                         continue;
1152                 }
1153
1154                 info->type = LV2;
1155
1156                 info->name = string(lilv_node_as_string(name));
1157                 lilv_node_free(name);
1158
1159                 const LilvPluginClass* pclass = lilv_plugin_get_class(p);
1160                 const LilvNode*        label  = lilv_plugin_class_get_label(pclass);
1161                 info->category = lilv_node_as_string(label);
1162
1163                 LilvNode* author_name = lilv_plugin_get_author_name(p);
1164                 info->creator = author_name ? string(lilv_node_as_string(author_name)) : "Unknown";
1165                 lilv_node_free(author_name);
1166
1167                 info->path = "/NOPATH"; // Meaningless for LV2
1168
1169                 info->n_inputs.set_audio(
1170                         lilv_plugin_get_num_ports_of_class(
1171                                 p, _world.input_class, _world.audio_class, NULL));
1172                 info->n_inputs.set_midi(
1173                         lilv_plugin_get_num_ports_of_class(
1174                                 p, _world.input_class, _world.event_class, NULL));
1175
1176                 info->n_outputs.set_audio(
1177                         lilv_plugin_get_num_ports_of_class(
1178                                 p, _world.output_class, _world.audio_class, NULL));
1179                 info->n_outputs.set_midi(
1180                         lilv_plugin_get_num_ports_of_class(
1181                                 p, _world.output_class, _world.event_class, NULL));
1182
1183                 info->unique_id = lilv_node_as_uri(lilv_plugin_get_uri(p));
1184                 info->index     = 0; // Meaningless for LV2
1185
1186                 plugs->push_back(info);
1187         }
1188
1189         cerr << "Done LV2 discovery" << endl;
1190
1191         return plugs;
1192 }