add Lua bindings for Timecode conversion
[ardour.git] / libs / ardour / lua_api.cc
1 /*
2  * Copyright (C) 2016 Robin Gareus <robin@gareus.org>
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17  *
18  */
19 #include <cstring>
20 #include <vamp-hostsdk/PluginLoader.h>
21
22 #include "pbd/compose.h"
23 #include "pbd/error.h"
24 #include "pbd/failed_constructor.h"
25
26 #include "ardour/lua_api.h"
27 #include "ardour/luaproc.h"
28 #include "ardour/luascripting.h"
29 #include "ardour/plugin.h"
30 #include "ardour/plugin_insert.h"
31 #include "ardour/plugin_manager.h"
32 #include "ardour/readable.h"
33
34 #include "LuaBridge/LuaBridge.h"
35
36 #include "pbd/i18n.h"
37
38 using namespace ARDOUR;
39 using namespace PBD;
40 using namespace std;
41
42 int
43 ARDOUR::LuaAPI::datatype_ctor_null (lua_State *L)
44 {
45         DataType dt (DataType::NIL);
46         luabridge::Stack <DataType>::push (L, dt);
47         return 1;
48 }
49
50 int
51 ARDOUR::LuaAPI::datatype_ctor_audio (lua_State *L)
52 {
53         DataType dt (DataType::AUDIO);
54         // NB luabridge will copy construct the object and manage lifetime.
55         luabridge::Stack <DataType>::push (L, dt);
56         return 1;
57 }
58
59 int
60 ARDOUR::LuaAPI::datatype_ctor_midi (lua_State *L)
61 {
62         DataType dt (DataType::MIDI);
63         luabridge::Stack <DataType>::push (L, dt);
64         return 1;
65 }
66
67 boost::shared_ptr<Processor>
68 ARDOUR::LuaAPI::nil_processor ()
69 {
70         return boost::shared_ptr<Processor> ();
71 }
72
73 boost::shared_ptr<Processor>
74 ARDOUR::LuaAPI::new_luaproc (Session *s, const string& name)
75 {
76         if (!s) {
77                 return boost::shared_ptr<Processor> ();
78         }
79
80         LuaScriptInfoPtr spi;
81         ARDOUR::LuaScriptList & _scripts (LuaScripting::instance ().scripts (LuaScriptInfo::DSP));
82         for (LuaScriptList::const_iterator i = _scripts.begin (); i != _scripts.end (); ++i) {
83                 if (name == (*i)->name) {
84                         spi = *i;
85                         break;
86                 }
87         }
88
89         if (!spi) {
90                 warning << _("Script with given name was not found\n");
91                 return boost::shared_ptr<Processor> ();
92         }
93
94         PluginPtr p;
95         try {
96                 LuaPluginInfoPtr lpi (new LuaPluginInfo (spi));
97                 p = (lpi->load (*s));
98         } catch (...) {
99                 warning << _("Failed to instantiate Lua Processor\n");
100                 return boost::shared_ptr<Processor> ();
101         }
102
103         return boost::shared_ptr<Processor> (new PluginInsert (*s, p));
104 }
105
106 PluginInfoPtr
107 ARDOUR::LuaAPI::new_plugin_info (const string& name, ARDOUR::PluginType type)
108 {
109         PluginManager& manager = PluginManager::instance ();
110         PluginInfoList all_plugs;
111         all_plugs.insert (all_plugs.end (), manager.ladspa_plugin_info ().begin (), manager.ladspa_plugin_info ().end ());
112         all_plugs.insert (all_plugs.end (), manager.lua_plugin_info ().begin (), manager.lua_plugin_info ().end ());
113 #ifdef WINDOWS_VST_SUPPORT
114         all_plugs.insert (all_plugs.end (), manager.windows_vst_plugin_info ().begin (), manager.windows_vst_plugin_info ().end ());
115 #endif
116 #ifdef LXVST_SUPPORT
117         all_plugs.insert (all_plugs.end (), manager.lxvst_plugin_info ().begin (), manager.lxvst_plugin_info ().end ());
118 #endif
119 #ifdef AUDIOUNIT_SUPPORT
120         all_plugs.insert (all_plugs.end (), manager.au_plugin_info ().begin (), manager.au_plugin_info ().end ());
121 #endif
122 #ifdef LV2_SUPPORT
123         all_plugs.insert (all_plugs.end (), manager.lv2_plugin_info ().begin (), manager.lv2_plugin_info ().end ());
124 #endif
125
126         for (PluginInfoList::const_iterator i = all_plugs.begin (); i != all_plugs.end (); ++i) {
127                 if (((*i)->name == name || (*i)->unique_id == name) && (*i)->type == type) {
128                         return *i;
129                 }
130         }
131         return PluginInfoPtr ();
132 }
133
134 boost::shared_ptr<Processor>
135 ARDOUR::LuaAPI::new_plugin (Session *s, const string& name, ARDOUR::PluginType type, const string& preset)
136 {
137         if (!s) {
138                 return boost::shared_ptr<Processor> ();
139         }
140
141         PluginInfoPtr pip = new_plugin_info (name, type);
142
143         if (!pip) {
144                 return boost::shared_ptr<Processor> ();
145         }
146
147         PluginPtr p = pip->load (*s);
148         if (!p) {
149                 return boost::shared_ptr<Processor> ();
150         }
151
152         if (!preset.empty ()) {
153                 const Plugin::PresetRecord *pr = p->preset_by_label (preset);
154                 if (pr) {
155                         p->load_preset (*pr);
156                 }
157         }
158
159         return boost::shared_ptr<Processor> (new PluginInsert (*s, p));
160 }
161
162 bool
163 ARDOUR::LuaAPI::set_plugin_insert_param (boost::shared_ptr<PluginInsert> pi, uint32_t which, float val)
164 {
165         boost::shared_ptr<Plugin> plugin = pi->plugin ();
166         if (!plugin) { return false; }
167
168         bool ok=false;
169         uint32_t controlid = plugin->nth_parameter (which, ok);
170         if (!ok) { return false; }
171         if (!plugin->parameter_is_input (controlid)) { return false; }
172
173         ParameterDescriptor pd;
174         if (plugin->get_parameter_descriptor (controlid, pd) != 0) { return false; }
175         if (val < pd.lower || val > pd.upper) { return false; }
176
177         boost::shared_ptr<AutomationControl> c = pi->automation_control (Evoral::Parameter (PluginAutomation, 0, controlid));
178         c->set_value (val, PBD::Controllable::NoGroup);
179         return true;
180 }
181
182 float
183 ARDOUR::LuaAPI::get_plugin_insert_param (boost::shared_ptr<PluginInsert> pi, uint32_t which, bool &ok)
184 {
185         ok=false;
186         boost::shared_ptr<Plugin> plugin = pi->plugin ();
187         if (!plugin) { return 0; }
188         uint32_t controlid = plugin->nth_parameter (which, ok);
189         if (!ok) { return 0; }
190         return plugin->get_parameter ( controlid );
191 }
192
193 bool
194 ARDOUR::LuaAPI::set_processor_param (boost::shared_ptr<Processor> proc, uint32_t which, float val)
195 {
196         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (proc);
197         if (!pi) { return false; }
198         return set_plugin_insert_param (pi, which, val);
199 }
200
201 float
202 ARDOUR::LuaAPI::get_processor_param (boost::shared_ptr<Processor> proc, uint32_t which, bool &ok)
203 {
204         ok=false;
205         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (proc);
206         if (!pi) { return false; }
207         return get_plugin_insert_param (pi, which, ok);
208 }
209
210 int
211 ARDOUR::LuaAPI::plugin_automation (lua_State *L)
212 {
213         typedef boost::shared_ptr<Processor> T;
214
215         int top = lua_gettop (L);
216         if (top < 2) {
217                 return luaL_argerror (L, 1, "invalid number of arguments, :plugin_automation (plugin, parameter_number)");
218         }
219         T* const p = luabridge::Userdata::get<T> (L, 1, false);
220         uint32_t which = luabridge::Stack<uint32_t>::get (L, 2);
221         if (!p) {
222                 return luaL_error (L, "Invalid pointer to Ardour:Processor");
223         }
224         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (*p);
225         if (!pi) {
226                 return luaL_error (L, "Given Processor is not a Plugin Insert");
227         }
228         boost::shared_ptr<Plugin> plugin = pi->plugin ();
229         if (!plugin) {
230                 return luaL_error (L, "Given Processor is not a Plugin");
231         }
232
233         bool ok=false;
234         uint32_t controlid = plugin->nth_parameter (which, ok);
235         if (!ok) {
236                 return luaL_error (L, "Invalid Parameter");
237         }
238         if (!plugin->parameter_is_input (controlid)) {
239                 return luaL_error (L, "Given Parameter is not an input");
240         }
241
242         ParameterDescriptor pd;
243         if (plugin->get_parameter_descriptor (controlid, pd) != 0) {
244                 return luaL_error (L, "Cannot describe parameter");
245         }
246
247         boost::shared_ptr<AutomationControl> c = pi->automation_control (Evoral::Parameter (PluginAutomation, 0, controlid));
248
249         luabridge::Stack<boost::shared_ptr<AutomationList> >::push (L, c->alist ());
250         luabridge::Stack<boost::shared_ptr<Evoral::ControlList> >::push (L, c->list ());
251         luabridge::Stack<ParameterDescriptor>::push (L, pd);
252         return 3;
253 }
254
255 int
256 ARDOUR::LuaAPI::sample_to_timecode (lua_State *L)
257 {
258         int top = lua_gettop (L);
259         if (top < 3) {
260                 return luaL_argerror (L, 1, "invalid number of arguments sample_to_timecode (TimecodeFormat, sample_rate, sample)");
261         }
262         typedef Timecode::TimecodeFormat T;
263         T tf = luabridge::Stack<T>::get (L, 1);
264         double sample_rate = luabridge::Stack<double>::get (L, 2);
265         int64_t sample = luabridge::Stack<int64_t>::get (L, 3);
266
267         Timecode::Time timecode;
268
269         Timecode::sample_to_timecode (
270                         sample, timecode, false, false,
271                         Timecode::timecode_to_frames_per_second (tf),
272                         Timecode::timecode_has_drop_frames (tf),
273                         sample_rate,
274                         0, false, 0);
275
276         luabridge::Stack<uint32_t>::push (L, timecode.hours);
277         luabridge::Stack<uint32_t>::push (L, timecode.minutes);
278         luabridge::Stack<uint32_t>::push (L, timecode.seconds);
279         luabridge::Stack<uint32_t>::push (L, timecode.frames);
280         return 4;
281 }
282
283 int
284 ARDOUR::LuaAPI::timecode_to_sample (lua_State *L)
285 {
286         int top = lua_gettop (L);
287         if (top < 6) {
288                 return luaL_argerror (L, 1, "invalid number of arguments sample_to_timecode (TimecodeFormat, sample_rate, hh, mm, ss, ff)");
289         }
290         typedef Timecode::TimecodeFormat T;
291         T tf = luabridge::Stack<T>::get (L, 1);
292         double sample_rate = luabridge::Stack<double>::get (L, 2);
293         int hh = luabridge::Stack<int>::get (L, 3);
294         int mm = luabridge::Stack<int>::get (L, 4);
295         int ss = luabridge::Stack<int>::get (L, 5);
296         int ff = luabridge::Stack<int>::get (L, 6);
297
298         Timecode::Time timecode;
299         timecode.negative = false;
300         timecode.hours = hh;
301         timecode.minutes = mm;
302         timecode.seconds = ss;
303         timecode.frames = ff;
304         timecode.subframes = 0;
305         timecode.rate = Timecode::timecode_to_frames_per_second (tf);
306         timecode.drop = Timecode::timecode_has_drop_frames (tf);
307
308         int64_t sample;
309
310         Timecode::timecode_to_sample (
311                         timecode, sample, false, false,
312                         sample_rate, 0, false, 0);
313
314         luabridge::Stack<int64_t>::push (L, sample);
315         return 1;
316 }
317
318 int
319 ARDOUR::LuaAPI::sample_to_timecode_lua (lua_State *L)
320 {
321         int top = lua_gettop (L);
322         if (top < 2) {
323                 return luaL_argerror (L, 1, "invalid number of arguments sample_to_timecode (sample)");
324         }
325         Session const* const s = luabridge::Userdata::get <Session> (L, 1, true);
326         int64_t sample = luabridge::Stack<int64_t>::get (L, 2);
327
328         Timecode::Time timecode;
329
330         Timecode::sample_to_timecode (
331                         sample, timecode, false, false,
332                         s->timecode_frames_per_second (),
333                         s->timecode_drop_frames (),
334                         s->frame_rate (),
335                         0, false, 0);
336
337         luabridge::Stack<uint32_t>::push (L, timecode.hours);
338         luabridge::Stack<uint32_t>::push (L, timecode.minutes);
339         luabridge::Stack<uint32_t>::push (L, timecode.seconds);
340         luabridge::Stack<uint32_t>::push (L, timecode.frames);
341         return 4;
342 }
343 int
344 ARDOUR::LuaAPI::timecode_to_sample_lua (lua_State *L)
345 {
346         int top = lua_gettop (L);
347         if (top < 5) {
348                 return luaL_argerror (L, 1, "invalid number of arguments sample_to_timecode (hh, mm, ss, ff)");
349         }
350         Session const* const s = luabridge::Userdata::get <Session> (L, 1, true);
351         int hh = luabridge::Stack<int>::get (L, 2);
352         int mm = luabridge::Stack<int>::get (L, 3);
353         int ss = luabridge::Stack<int>::get (L, 4);
354         int ff = luabridge::Stack<int>::get (L, 5);
355
356         Timecode::Time timecode;
357         timecode.negative = false;
358         timecode.hours = hh;
359         timecode.minutes = mm;
360         timecode.seconds = ss;
361         timecode.frames = ff;
362         timecode.subframes = 0;
363         timecode.rate = s->timecode_frames_per_second ();
364         timecode.drop = s->timecode_drop_frames ();
365
366         int64_t sample;
367
368         Timecode::timecode_to_sample (
369                         timecode, sample, false, false,
370                         s->frame_rate (),
371                         0, false, 0);
372
373         luabridge::Stack<int64_t>::push (L, sample);
374         return 1;
375 }
376
377 int
378 ARDOUR::LuaOSC::Address::send (lua_State *L)
379 {
380         Address * const luaosc = luabridge::Userdata::get <Address> (L, 1, false);
381         if (!luaosc) {
382                 return luaL_error (L, "Invalid pointer to OSC.Address");
383         }
384         if (!luaosc->_addr) {
385                 return luaL_error (L, "Invalid Destination Address");
386         }
387
388         int top = lua_gettop (L);
389         if (top < 3) {
390                 return luaL_argerror (L, 1, "invalid number of arguments, :send (path, type, ...)");
391         }
392
393         const char* path = luaL_checkstring (L, 2);
394         const char* type = luaL_checkstring (L, 3);
395         assert (path && type);
396
397         if ((int) strlen (type) != top - 3) {
398                 return luaL_argerror (L, 3, "type description does not match arguments");
399         }
400
401         lo_message msg = lo_message_new ();
402
403         for (int i = 4; i <= top; ++i) {
404                 char t = type[i - 4];
405                 int lt = lua_type (L, i);
406                 int ok = -1;
407                 switch (lt) {
408                         case LUA_TSTRING:
409                                 if (t == LO_STRING) {
410                                         ok = lo_message_add_string (msg, luaL_checkstring (L, i));
411                                 } else if (t == LO_CHAR) {
412                                         char c = luaL_checkstring (L, i) [0];
413                                         ok = lo_message_add_char (msg, c);
414                                 }
415                                 break;
416                         case LUA_TBOOLEAN:
417                                 if (t == LO_TRUE || t == LO_FALSE) {
418                                         if (lua_toboolean (L, i)) {
419                                                 ok = lo_message_add_true (msg);
420                                         } else {
421                                                 ok = lo_message_add_false (msg);
422                                         }
423                                 }
424                                 break;
425                         case LUA_TNUMBER:
426                                 if (t == LO_INT32) {
427                                         ok = lo_message_add_int32 (msg, (int32_t) luaL_checkinteger (L, i));
428                                 }
429                                 else if (t == LO_FLOAT) {
430                                         ok = lo_message_add_float (msg, (float) luaL_checknumber (L, i));
431                                 }
432                                 else if (t == LO_DOUBLE) {
433                                         ok = lo_message_add_double (msg, (double) luaL_checknumber (L, i));
434                                 }
435                                 else if (t == LO_INT64) {
436                                         ok = lo_message_add_double (msg, (int64_t) luaL_checknumber (L, i));
437                                 }
438                                 break;
439                         default:
440                                 break;
441                 }
442                 if (ok != 0) {
443                         return luaL_argerror (L, i, "type description does not match parameter");
444                 }
445         }
446
447         int rv = lo_send_message (luaosc->_addr, path, msg);
448         lo_message_free (msg);
449         luabridge::Stack<bool>::push (L, (rv == 0));
450         return 1;
451 }
452
453 static double hue2rgb (const double p, const double q, double t) {
454         if (t < 0.0) t += 1.0;
455         if (t > 1.0) t -= 1.0;
456         if (t < 1.0 / 6.0) return p + (q - p) * 6.0 * t;
457         if (t < 1.0 / 2.0) return q;
458         if (t < 2.0 / 3.0) return p + (q - p) * (2.0 / 3.0 - t) * 6.0;
459         return p;
460 }
461
462 int
463 ARDOUR::LuaAPI::hsla_to_rgba (lua_State *L)
464 {
465         int top = lua_gettop (L);
466         if (top < 3) {
467                 return luaL_argerror (L, 1, "invalid number of arguments, :hsla_to_rgba (h, s, l [,a])");
468         }
469         double h = luabridge::Stack<double>::get (L, 1);
470         double s = luabridge::Stack<double>::get (L, 2);
471         double l = luabridge::Stack<double>::get (L, 3);
472         double a = 1.0;
473         if (top > 3) {
474                 a = luabridge::Stack<double>::get (L, 4);
475         }
476
477         // we can't use ArdourCanvas::hsva_to_color here
478         // besides we want HSL not HSV and without intermediate
479         // color_to_rgba (rgba_to_color ())
480         double r, g, b;
481         const double cq = l < 0.5 ? l * (1 + s) : l + s - l * s;
482         const double cp = 2.f * l - cq;
483         r = hue2rgb (cp, cq, h + 1.0 / 3.0);
484         g = hue2rgb (cp, cq, h);
485         b = hue2rgb (cp, cq, h - 1.0 / 3.0);
486
487         luabridge::Stack<double>::push (L, r);
488         luabridge::Stack<double>::push (L, g);
489         luabridge::Stack<double>::push (L, b);
490         luabridge::Stack<double>::push (L, a);
491         return 4;
492 }
493
494 int
495 ARDOUR::LuaAPI::build_filename (lua_State *L)
496 {
497         std::vector<std::string> elem;
498         int top = lua_gettop (L);
499         if (top < 1) {
500                 return luaL_argerror (L, 1, "invalid number of arguments, build_filename (path, ...)");
501         }
502         for (int i = 1; i <= top; ++i) {
503                 int lt = lua_type (L, i);
504                 if (lt != LUA_TSTRING) {
505                         return luaL_argerror (L, i, "invalid argument type, expected string");
506                 }
507                 elem.push_back (luaL_checkstring (L, i));
508         }
509
510         luabridge::Stack<std::string>::push (L, Glib::build_filename (elem));
511         return 1;
512 }
513
514 luabridge::LuaRef::Proxy&
515 luabridge::LuaRef::Proxy::clone_instance (const void* classkey, void* p) {
516         lua_rawgeti (m_L, LUA_REGISTRYINDEX, m_tableRef);
517         lua_rawgeti (m_L, LUA_REGISTRYINDEX, m_keyRef);
518
519         luabridge::UserdataPtr::push_raw (m_L, p, classkey);
520
521         lua_rawset (m_L, -3);
522         lua_pop (m_L, 1);
523         return *this;
524 }
525
526 LuaTableRef::LuaTableRef () {}
527 LuaTableRef::~LuaTableRef () {}
528
529 int
530 LuaTableRef::get (lua_State* L)
531 {
532         luabridge::LuaRef rv (luabridge::newTable (L));
533         for (std::vector<LuaTableEntry>::const_iterator i = _data.begin (); i != _data.end (); ++i) {
534                 switch ((*i).keytype) {
535                         case LUA_TSTRING:
536                                 assign (&rv, i->k_s, *i);
537                                 break;
538                         case LUA_TNUMBER:
539                                 assign (&rv, i->k_n, *i);
540                                 break;
541                 }
542         }
543         luabridge::push (L, rv);
544         return 1;
545 }
546
547 int
548 LuaTableRef::set (lua_State* L)
549 {
550         if (!lua_istable (L, -1)) { return luaL_error (L, "argument is not a table"); }
551         _data.clear ();
552
553         lua_pushvalue (L, -1);
554         lua_pushnil (L);
555         while (lua_next (L, -2)) {
556                 lua_pushvalue (L, -2);
557
558                 LuaTableEntry s (lua_type (L, -1), lua_type (L, -2));
559                 switch (lua_type (L, -1)) {
560                         case LUA_TSTRING:
561                                 s.k_s = luabridge::Stack<std::string>::get (L, -1);
562                                 break;
563                                 ;
564                         case LUA_TNUMBER:
565                                 s.k_n = luabridge::Stack<unsigned int>::get (L, -1);
566                                 break;
567                         default:
568                                 // invalid key
569                                 lua_pop (L, 2);
570                                 continue;
571                 }
572
573                 switch (lua_type (L, -2)) {
574                         case LUA_TSTRING:
575                                 s.s = luabridge::Stack<std::string>::get (L, -2);
576                                 break;
577                         case LUA_TBOOLEAN:
578                                 s.b = lua_toboolean (L, -2);
579                                 break;
580                         case LUA_TNUMBER:
581                                 s.n = lua_tonumber (L, -2);
582                                 break;
583                         case LUA_TUSERDATA:
584                                 {
585                                         bool ok = false;
586                                         lua_getmetatable (L, -2);
587                                         lua_rawgetp (L, -1, luabridge::getIdentityKey ());
588                                         if (lua_isboolean (L, -1)) {
589                                                 lua_pop (L, 1);
590                                                 const void* key = lua_topointer (L, -1);
591                                                 lua_pop (L, 1);
592                                                 void const* classkey = findclasskey (L, key);
593
594                                                 if (classkey) {
595                                                         ok = true;
596                                                         s.c = classkey;
597                                                         s.p = luabridge::Userdata::get_ptr (L, -2);
598                                                 }
599                                         } else {
600                                                 lua_pop (L, 2);
601                                         }
602
603                                         if (ok) {
604                                                 break;
605                                         }
606                                         // invalid userdata -- fall through
607                                 }
608                                 // no break
609                         case LUA_TFUNCTION: // no support -- we could... string.format("%q", string.dump(value, true))
610                         case LUA_TTABLE: // no nested tables, sorry.
611                         case LUA_TNIL: // fallthrough
612                         default:
613                                 // invalid value
614                                 lua_pop (L, 2);
615                                 continue;
616                 }
617
618                 _data.push_back (s);
619                 lua_pop (L, 2);
620         }
621         return 0;
622 }
623
624 void*
625 LuaTableRef::findclasskey (lua_State *L, const void* key)
626 {
627         lua_pushvalue (L, LUA_REGISTRYINDEX);
628         lua_pushnil (L);
629         while (lua_next (L, -2)) {
630                 lua_pushvalue (L, -2);
631                 if (lua_topointer (L, -2) == key) {
632                         void* rv = lua_touserdata (L, -1);
633                         lua_pop (L, 4);
634                         return rv;
635                 }
636                 lua_pop (L, 2);
637         }
638         lua_pop (L, 1);
639         return NULL;
640 }
641
642 template<typename T>
643 void LuaTableRef::assign (luabridge::LuaRef* rv, T key, const LuaTableEntry& s)
644 {
645         switch (s.valuetype) {
646                 case LUA_TSTRING:
647                         (*rv)[key] = s.s;
648                         break;
649                 case LUA_TBOOLEAN:
650                         (*rv)[key] = s.b;
651                         break;
652                 case LUA_TNUMBER:
653                         (*rv)[key] = s.n;
654                         break;
655                 case LUA_TUSERDATA:
656                         (*rv)[key].clone_instance (s.c, s.p);
657                         break;
658                 default:
659                         assert (0);
660                         break;
661         }
662 }
663
664 std::vector<std::string>
665 LuaAPI::Vamp::list_plugins ()
666 {
667         using namespace ::Vamp::HostExt;
668         PluginLoader* loader (PluginLoader::getInstance());
669         return loader->listPlugins ();
670 }
671
672 LuaAPI::Vamp::Vamp (const std::string& key, float sample_rate)
673         : _plugin (0)
674         , _sample_rate (sample_rate)
675         , _bufsize (1024)
676         , _stepsize (1024)
677         , _initialized (false)
678 {
679         using namespace ::Vamp::HostExt;
680
681         PluginLoader* loader (PluginLoader::getInstance());
682         _plugin = loader->loadPlugin (key, _sample_rate, PluginLoader::ADAPT_ALL_SAFE);
683
684         if (!_plugin) {
685                 PBD::error << string_compose (_("VAMP Plugin \"%1\" could not be loaded"), key) << endmsg;
686                 throw failed_constructor ();
687         }
688
689         size_t bs = _plugin->getPreferredBlockSize ();
690         size_t ss = _plugin->getPreferredStepSize ();
691
692         if (bs > 0 && ss > 0 && bs <= 8192 && ss <= 8192) {
693                 _bufsize = bs;
694                 _stepsize = bs;
695         }
696 }
697
698 LuaAPI::Vamp::~Vamp ()
699 {
700         delete _plugin;
701 }
702
703 void
704 LuaAPI::Vamp::reset ()
705 {
706         _initialized = false;
707         if (_plugin) {
708                 _plugin->reset ();
709         }
710 }
711
712 bool
713 LuaAPI::Vamp::initialize ()
714 {
715         if (!_plugin || _plugin->getMinChannelCount() > 1) {
716                 return false;
717         }
718         if (!_plugin->initialise (1, _stepsize, _bufsize)) {
719                 return false;
720         }
721         _initialized = true;
722         return true;
723 }
724
725 int
726 LuaAPI::Vamp::analyze (boost::shared_ptr<ARDOUR::Readable> r, uint32_t channel, luabridge::LuaRef cb)
727 {
728         if (!_initialized) {
729                 if (!initialize ()) {
730                         return -1;
731                 }
732         }
733         assert (_initialized);
734
735         ::Vamp::Plugin::FeatureSet features;
736         float* data = new float[_bufsize];
737         float* bufs[1] = { data };
738
739         framecnt_t len = r->readable_length();
740         framepos_t pos = 0;
741
742         int rv = 0;
743         while (1) {
744                 framecnt_t to_read = std::min ((len - pos), _bufsize);
745                 if (r->read (data, pos, to_read, channel) != to_read) {
746                         rv = -1;
747                         break;
748                 }
749                 if (to_read != _bufsize) {
750                         memset (data + to_read, 0, (_bufsize - to_read) * sizeof (float));
751                 }
752
753                 features = _plugin->process (bufs, ::Vamp::RealTime::fromSeconds ((double) pos / _sample_rate));
754
755                 if (cb.type () == LUA_TFUNCTION) {
756                         cb (&features, pos);
757                 }
758
759                 pos += std::min (_stepsize, to_read);
760
761                 if (pos >= len) {
762                         break;
763                 }
764         }
765
766         delete [] data;
767         return rv;
768 }
769
770 ::Vamp::Plugin::FeatureSet
771 LuaAPI::Vamp::process (const std::vector<float*>& d, ::Vamp::RealTime rt)
772 {
773         if (!_plugin || d.size() == 0) {
774                 return ::Vamp::Plugin::FeatureSet ();
775         }
776         const float* const* bufs = &d[0];
777         return _plugin->process (bufs, rt);
778 }
779
780 boost::shared_ptr<Evoral::Note<Evoral::Beats> >
781 LuaAPI::new_noteptr (uint8_t chan, Evoral::Beats beat_time, Evoral::Beats length, uint8_t note, uint8_t velocity)
782 {
783         return boost::shared_ptr<Evoral::Note<Evoral::Beats> > (new Evoral::Note<Evoral::Beats>(chan, beat_time, length, note, velocity));
784 }