7da81b29658108b6955e7dc2c7f28bb62301bb1a
[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 bool
211 ARDOUR::LuaAPI::reset_processor_to_default ( boost::shared_ptr<Processor> proc )
212 {
213         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (proc);
214         if (pi) {
215                 pi->reset_parameters_to_default();
216                 return true;
217         }
218         return false;
219 }
220
221 int
222 ARDOUR::LuaAPI::plugin_automation (lua_State *L)
223 {
224         typedef boost::shared_ptr<Processor> T;
225
226         int top = lua_gettop (L);
227         if (top < 2) {
228                 return luaL_argerror (L, 1, "invalid number of arguments, :plugin_automation (plugin, parameter_number)");
229         }
230         T* const p = luabridge::Userdata::get<T> (L, 1, false);
231         uint32_t which = luabridge::Stack<uint32_t>::get (L, 2);
232         if (!p) {
233                 return luaL_error (L, "Invalid pointer to Ardour:Processor");
234         }
235         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (*p);
236         if (!pi) {
237                 return luaL_error (L, "Given Processor is not a Plugin Insert");
238         }
239         boost::shared_ptr<Plugin> plugin = pi->plugin ();
240         if (!plugin) {
241                 return luaL_error (L, "Given Processor is not a Plugin");
242         }
243
244         bool ok=false;
245         uint32_t controlid = plugin->nth_parameter (which, ok);
246         if (!ok) {
247                 return luaL_error (L, "Invalid Parameter");
248         }
249         if (!plugin->parameter_is_input (controlid)) {
250                 return luaL_error (L, "Given Parameter is not an input");
251         }
252
253         ParameterDescriptor pd;
254         if (plugin->get_parameter_descriptor (controlid, pd) != 0) {
255                 return luaL_error (L, "Cannot describe parameter");
256         }
257
258         boost::shared_ptr<AutomationControl> c = pi->automation_control (Evoral::Parameter (PluginAutomation, 0, controlid));
259
260         luabridge::Stack<boost::shared_ptr<AutomationList> >::push (L, c->alist ());
261         luabridge::Stack<boost::shared_ptr<Evoral::ControlList> >::push (L, c->list ());
262         luabridge::Stack<ParameterDescriptor>::push (L, pd);
263         return 3;
264 }
265
266 int
267 ARDOUR::LuaAPI::sample_to_timecode (lua_State *L)
268 {
269         int top = lua_gettop (L);
270         if (top < 3) {
271                 return luaL_argerror (L, 1, "invalid number of arguments sample_to_timecode (TimecodeFormat, sample_rate, sample)");
272         }
273         typedef Timecode::TimecodeFormat T;
274         T tf = luabridge::Stack<T>::get (L, 1);
275         double sample_rate = luabridge::Stack<double>::get (L, 2);
276         int64_t sample = luabridge::Stack<int64_t>::get (L, 3);
277
278         Timecode::Time timecode;
279
280         Timecode::sample_to_timecode (
281                         sample, timecode, false, false,
282                         Timecode::timecode_to_frames_per_second (tf),
283                         Timecode::timecode_has_drop_frames (tf),
284                         sample_rate,
285                         0, false, 0);
286
287         luabridge::Stack<uint32_t>::push (L, timecode.hours);
288         luabridge::Stack<uint32_t>::push (L, timecode.minutes);
289         luabridge::Stack<uint32_t>::push (L, timecode.seconds);
290         luabridge::Stack<uint32_t>::push (L, timecode.frames);
291         return 4;
292 }
293
294 int
295 ARDOUR::LuaAPI::timecode_to_sample (lua_State *L)
296 {
297         int top = lua_gettop (L);
298         if (top < 6) {
299                 return luaL_argerror (L, 1, "invalid number of arguments sample_to_timecode (TimecodeFormat, sample_rate, hh, mm, ss, ff)");
300         }
301         typedef Timecode::TimecodeFormat T;
302         T tf = luabridge::Stack<T>::get (L, 1);
303         double sample_rate = luabridge::Stack<double>::get (L, 2);
304         int hh = luabridge::Stack<int>::get (L, 3);
305         int mm = luabridge::Stack<int>::get (L, 4);
306         int ss = luabridge::Stack<int>::get (L, 5);
307         int ff = luabridge::Stack<int>::get (L, 6);
308
309         Timecode::Time timecode;
310         timecode.negative = false;
311         timecode.hours = hh;
312         timecode.minutes = mm;
313         timecode.seconds = ss;
314         timecode.frames = ff;
315         timecode.subframes = 0;
316         timecode.rate = Timecode::timecode_to_frames_per_second (tf);
317         timecode.drop = Timecode::timecode_has_drop_frames (tf);
318
319         int64_t sample;
320
321         Timecode::timecode_to_sample (
322                         timecode, sample, false, false,
323                         sample_rate, 0, false, 0);
324
325         luabridge::Stack<int64_t>::push (L, sample);
326         return 1;
327 }
328
329 int
330 ARDOUR::LuaAPI::sample_to_timecode_lua (lua_State *L)
331 {
332         int top = lua_gettop (L);
333         if (top < 2) {
334                 return luaL_argerror (L, 1, "invalid number of arguments sample_to_timecode (sample)");
335         }
336         Session const* const s = luabridge::Userdata::get <Session> (L, 1, true);
337         int64_t sample = luabridge::Stack<int64_t>::get (L, 2);
338
339         Timecode::Time timecode;
340
341         Timecode::sample_to_timecode (
342                         sample, timecode, false, false,
343                         s->timecode_frames_per_second (),
344                         s->timecode_drop_frames (),
345                         s->frame_rate (),
346                         0, false, 0);
347
348         luabridge::Stack<uint32_t>::push (L, timecode.hours);
349         luabridge::Stack<uint32_t>::push (L, timecode.minutes);
350         luabridge::Stack<uint32_t>::push (L, timecode.seconds);
351         luabridge::Stack<uint32_t>::push (L, timecode.frames);
352         return 4;
353 }
354 int
355 ARDOUR::LuaAPI::timecode_to_sample_lua (lua_State *L)
356 {
357         int top = lua_gettop (L);
358         if (top < 5) {
359                 return luaL_argerror (L, 1, "invalid number of arguments sample_to_timecode (hh, mm, ss, ff)");
360         }
361         Session const* const s = luabridge::Userdata::get <Session> (L, 1, true);
362         int hh = luabridge::Stack<int>::get (L, 2);
363         int mm = luabridge::Stack<int>::get (L, 3);
364         int ss = luabridge::Stack<int>::get (L, 4);
365         int ff = luabridge::Stack<int>::get (L, 5);
366
367         Timecode::Time timecode;
368         timecode.negative = false;
369         timecode.hours = hh;
370         timecode.minutes = mm;
371         timecode.seconds = ss;
372         timecode.frames = ff;
373         timecode.subframes = 0;
374         timecode.rate = s->timecode_frames_per_second ();
375         timecode.drop = s->timecode_drop_frames ();
376
377         int64_t sample;
378
379         Timecode::timecode_to_sample (
380                         timecode, sample, false, false,
381                         s->frame_rate (),
382                         0, false, 0);
383
384         luabridge::Stack<int64_t>::push (L, sample);
385         return 1;
386 }
387
388 int
389 ARDOUR::LuaOSC::Address::send (lua_State *L)
390 {
391         Address * const luaosc = luabridge::Userdata::get <Address> (L, 1, false);
392         if (!luaosc) {
393                 return luaL_error (L, "Invalid pointer to OSC.Address");
394         }
395         if (!luaosc->_addr) {
396                 return luaL_error (L, "Invalid Destination Address");
397         }
398
399         int top = lua_gettop (L);
400         if (top < 3) {
401                 return luaL_argerror (L, 1, "invalid number of arguments, :send (path, type, ...)");
402         }
403
404         const char* path = luaL_checkstring (L, 2);
405         const char* type = luaL_checkstring (L, 3);
406         assert (path && type);
407
408         if ((int) strlen (type) != top - 3) {
409                 return luaL_argerror (L, 3, "type description does not match arguments");
410         }
411
412         lo_message msg = lo_message_new ();
413
414         for (int i = 4; i <= top; ++i) {
415                 char t = type[i - 4];
416                 int lt = lua_type (L, i);
417                 int ok = -1;
418                 switch (lt) {
419                         case LUA_TSTRING:
420                                 if (t == LO_STRING) {
421                                         ok = lo_message_add_string (msg, luaL_checkstring (L, i));
422                                 } else if (t == LO_CHAR) {
423                                         char c = luaL_checkstring (L, i) [0];
424                                         ok = lo_message_add_char (msg, c);
425                                 }
426                                 break;
427                         case LUA_TBOOLEAN:
428                                 if (t == LO_TRUE || t == LO_FALSE) {
429                                         if (lua_toboolean (L, i)) {
430                                                 ok = lo_message_add_true (msg);
431                                         } else {
432                                                 ok = lo_message_add_false (msg);
433                                         }
434                                 }
435                                 break;
436                         case LUA_TNUMBER:
437                                 if (t == LO_INT32) {
438                                         ok = lo_message_add_int32 (msg, (int32_t) luaL_checkinteger (L, i));
439                                 }
440                                 else if (t == LO_FLOAT) {
441                                         ok = lo_message_add_float (msg, (float) luaL_checknumber (L, i));
442                                 }
443                                 else if (t == LO_DOUBLE) {
444                                         ok = lo_message_add_double (msg, (double) luaL_checknumber (L, i));
445                                 }
446                                 else if (t == LO_INT64) {
447                                         ok = lo_message_add_double (msg, (int64_t) luaL_checknumber (L, i));
448                                 }
449                                 break;
450                         default:
451                                 break;
452                 }
453                 if (ok != 0) {
454                         return luaL_argerror (L, i, "type description does not match parameter");
455                 }
456         }
457
458         int rv = lo_send_message (luaosc->_addr, path, msg);
459         lo_message_free (msg);
460         luabridge::Stack<bool>::push (L, (rv == 0));
461         return 1;
462 }
463
464 static double hue2rgb (const double p, const double q, double t) {
465         if (t < 0.0) t += 1.0;
466         if (t > 1.0) t -= 1.0;
467         if (t < 1.0 / 6.0) return p + (q - p) * 6.0 * t;
468         if (t < 1.0 / 2.0) return q;
469         if (t < 2.0 / 3.0) return p + (q - p) * (2.0 / 3.0 - t) * 6.0;
470         return p;
471 }
472
473 int
474 ARDOUR::LuaAPI::hsla_to_rgba (lua_State *L)
475 {
476         int top = lua_gettop (L);
477         if (top < 3) {
478                 return luaL_argerror (L, 1, "invalid number of arguments, :hsla_to_rgba (h, s, l [,a])");
479         }
480         double h = luabridge::Stack<double>::get (L, 1);
481         double s = luabridge::Stack<double>::get (L, 2);
482         double l = luabridge::Stack<double>::get (L, 3);
483         double a = 1.0;
484         if (top > 3) {
485                 a = luabridge::Stack<double>::get (L, 4);
486         }
487
488         // we can't use ArdourCanvas::hsva_to_color here
489         // besides we want HSL not HSV and without intermediate
490         // color_to_rgba (rgba_to_color ())
491         double r, g, b;
492         const double cq = l < 0.5 ? l * (1 + s) : l + s - l * s;
493         const double cp = 2.f * l - cq;
494         r = hue2rgb (cp, cq, h + 1.0 / 3.0);
495         g = hue2rgb (cp, cq, h);
496         b = hue2rgb (cp, cq, h - 1.0 / 3.0);
497
498         luabridge::Stack<double>::push (L, r);
499         luabridge::Stack<double>::push (L, g);
500         luabridge::Stack<double>::push (L, b);
501         luabridge::Stack<double>::push (L, a);
502         return 4;
503 }
504
505 int
506 ARDOUR::LuaAPI::color_to_rgba (lua_State *L)
507 {
508         int top = lua_gettop (L);
509         if (top < 1) {
510                 return luaL_argerror (L, 1, "invalid number of arguments, color_to_rgba (uint32_t)");
511         }
512         uint32_t color = luabridge::Stack<uint32_t>::get (L, 1);
513         double r, g, b, a;
514
515         /* libardour is no user of libcanvas, otherwise
516          * we could just call
517          * ArdourCanvas::color_to_rgba (color, r, g, b, a);
518          */
519         r = ((color >> 24) & 0xff) / 255.0;
520         g = ((color >> 16) & 0xff) / 255.0;
521         b = ((color >>  8) & 0xff) / 255.0;
522         a = ((color >>  0) & 0xff) / 255.0;
523
524         luabridge::Stack <double>::push (L, r);
525         luabridge::Stack <double>::push (L, g);
526         luabridge::Stack <double>::push (L, b);
527         luabridge::Stack <double>::push (L, a);
528         return 4;
529 }
530
531 int
532 ARDOUR::LuaAPI::build_filename (lua_State *L)
533 {
534         std::vector<std::string> elem;
535         int top = lua_gettop (L);
536         if (top < 1) {
537                 return luaL_argerror (L, 1, "invalid number of arguments, build_filename (path, ...)");
538         }
539         for (int i = 1; i <= top; ++i) {
540                 int lt = lua_type (L, i);
541                 if (lt != LUA_TSTRING) {
542                         return luaL_argerror (L, i, "invalid argument type, expected string");
543                 }
544                 elem.push_back (luaL_checkstring (L, i));
545         }
546
547         luabridge::Stack<std::string>::push (L, Glib::build_filename (elem));
548         return 1;
549 }
550
551 luabridge::LuaRef::Proxy&
552 luabridge::LuaRef::Proxy::clone_instance (const void* classkey, void* p) {
553         lua_rawgeti (m_L, LUA_REGISTRYINDEX, m_tableRef);
554         lua_rawgeti (m_L, LUA_REGISTRYINDEX, m_keyRef);
555
556         luabridge::UserdataPtr::push_raw (m_L, p, classkey);
557
558         lua_rawset (m_L, -3);
559         lua_pop (m_L, 1);
560         return *this;
561 }
562
563 LuaTableRef::LuaTableRef () {}
564 LuaTableRef::~LuaTableRef () {}
565
566 int
567 LuaTableRef::get (lua_State* L)
568 {
569         luabridge::LuaRef rv (luabridge::newTable (L));
570         for (std::vector<LuaTableEntry>::const_iterator i = _data.begin (); i != _data.end (); ++i) {
571                 switch ((*i).keytype) {
572                         case LUA_TSTRING:
573                                 assign (&rv, i->k_s, *i);
574                                 break;
575                         case LUA_TNUMBER:
576                                 assign (&rv, i->k_n, *i);
577                                 break;
578                 }
579         }
580         luabridge::push (L, rv);
581         return 1;
582 }
583
584 int
585 LuaTableRef::set (lua_State* L)
586 {
587         if (!lua_istable (L, -1)) { return luaL_error (L, "argument is not a table"); }
588         _data.clear ();
589
590         lua_pushvalue (L, -1);
591         lua_pushnil (L);
592         while (lua_next (L, -2)) {
593                 lua_pushvalue (L, -2);
594
595                 LuaTableEntry s (lua_type (L, -1), lua_type (L, -2));
596                 switch (lua_type (L, -1)) {
597                         case LUA_TSTRING:
598                                 s.k_s = luabridge::Stack<std::string>::get (L, -1);
599                                 break;
600                                 ;
601                         case LUA_TNUMBER:
602                                 s.k_n = luabridge::Stack<unsigned int>::get (L, -1);
603                                 break;
604                         default:
605                                 // invalid key
606                                 lua_pop (L, 2);
607                                 continue;
608                 }
609
610                 switch (lua_type (L, -2)) {
611                         case LUA_TSTRING:
612                                 s.s = luabridge::Stack<std::string>::get (L, -2);
613                                 break;
614                         case LUA_TBOOLEAN:
615                                 s.b = lua_toboolean (L, -2);
616                                 break;
617                         case LUA_TNUMBER:
618                                 s.n = lua_tonumber (L, -2);
619                                 break;
620                         case LUA_TUSERDATA:
621                                 {
622                                         bool ok = false;
623                                         lua_getmetatable (L, -2);
624                                         lua_rawgetp (L, -1, luabridge::getIdentityKey ());
625                                         if (lua_isboolean (L, -1)) {
626                                                 lua_pop (L, 1);
627                                                 const void* key = lua_topointer (L, -1);
628                                                 lua_pop (L, 1);
629                                                 void const* classkey = findclasskey (L, key);
630
631                                                 if (classkey) {
632                                                         ok = true;
633                                                         s.c = classkey;
634                                                         s.p = luabridge::Userdata::get_ptr (L, -2);
635                                                 }
636                                         } else {
637                                                 lua_pop (L, 2);
638                                         }
639
640                                         if (ok) {
641                                                 break;
642                                         }
643                                         // invalid userdata -- fall through
644                                 }
645                                 // no break
646                         case LUA_TFUNCTION: // no support -- we could... string.format("%q", string.dump(value, true))
647                         case LUA_TTABLE: // no nested tables, sorry.
648                         case LUA_TNIL: // fallthrough
649                         default:
650                                 // invalid value
651                                 lua_pop (L, 2);
652                                 continue;
653                 }
654
655                 _data.push_back (s);
656                 lua_pop (L, 2);
657         }
658         return 0;
659 }
660
661 void*
662 LuaTableRef::findclasskey (lua_State *L, const void* key)
663 {
664         lua_pushvalue (L, LUA_REGISTRYINDEX);
665         lua_pushnil (L);
666         while (lua_next (L, -2)) {
667                 lua_pushvalue (L, -2);
668                 if (lua_topointer (L, -2) == key) {
669                         void* rv = lua_touserdata (L, -1);
670                         lua_pop (L, 4);
671                         return rv;
672                 }
673                 lua_pop (L, 2);
674         }
675         lua_pop (L, 1);
676         return NULL;
677 }
678
679 template<typename T>
680 void LuaTableRef::assign (luabridge::LuaRef* rv, T key, const LuaTableEntry& s)
681 {
682         switch (s.valuetype) {
683                 case LUA_TSTRING:
684                         (*rv)[key] = s.s;
685                         break;
686                 case LUA_TBOOLEAN:
687                         (*rv)[key] = s.b;
688                         break;
689                 case LUA_TNUMBER:
690                         (*rv)[key] = s.n;
691                         break;
692                 case LUA_TUSERDATA:
693                         (*rv)[key].clone_instance (s.c, s.p);
694                         break;
695                 default:
696                         assert (0);
697                         break;
698         }
699 }
700
701 std::vector<std::string>
702 LuaAPI::Vamp::list_plugins ()
703 {
704         using namespace ::Vamp::HostExt;
705         PluginLoader* loader (PluginLoader::getInstance());
706         return loader->listPlugins ();
707 }
708
709 LuaAPI::Vamp::Vamp (const std::string& key, float sample_rate)
710         : _plugin (0)
711         , _sample_rate (sample_rate)
712         , _bufsize (1024)
713         , _stepsize (1024)
714         , _initialized (false)
715 {
716         using namespace ::Vamp::HostExt;
717
718         PluginLoader* loader (PluginLoader::getInstance());
719         _plugin = loader->loadPlugin (key, _sample_rate, PluginLoader::ADAPT_ALL_SAFE);
720
721         if (!_plugin) {
722                 PBD::error << string_compose (_("VAMP Plugin \"%1\" could not be loaded"), key) << endmsg;
723                 throw failed_constructor ();
724         }
725
726         size_t bs = _plugin->getPreferredBlockSize ();
727         size_t ss = _plugin->getPreferredStepSize ();
728
729         if (bs > 0 && ss > 0 && bs <= 8192 && ss <= 8192) {
730                 _bufsize = bs;
731                 _stepsize = bs;
732         }
733 }
734
735 LuaAPI::Vamp::~Vamp ()
736 {
737         delete _plugin;
738 }
739
740 void
741 LuaAPI::Vamp::reset ()
742 {
743         _initialized = false;
744         if (_plugin) {
745                 _plugin->reset ();
746         }
747 }
748
749 bool
750 LuaAPI::Vamp::initialize ()
751 {
752         if (!_plugin || _plugin->getMinChannelCount() > 1) {
753                 return false;
754         }
755         if (!_plugin->initialise (1, _stepsize, _bufsize)) {
756                 return false;
757         }
758         _initialized = true;
759         return true;
760 }
761
762 int
763 LuaAPI::Vamp::analyze (boost::shared_ptr<ARDOUR::Readable> r, uint32_t channel, luabridge::LuaRef cb)
764 {
765         if (!_initialized) {
766                 if (!initialize ()) {
767                         return -1;
768                 }
769         }
770         assert (_initialized);
771
772         ::Vamp::Plugin::FeatureSet features;
773         float* data = new float[_bufsize];
774         float* bufs[1] = { data };
775
776         framecnt_t len = r->readable_length();
777         framepos_t pos = 0;
778
779         int rv = 0;
780         while (1) {
781                 framecnt_t to_read = std::min ((len - pos), _bufsize);
782                 if (r->read (data, pos, to_read, channel) != to_read) {
783                         rv = -1;
784                         break;
785                 }
786                 if (to_read != _bufsize) {
787                         memset (data + to_read, 0, (_bufsize - to_read) * sizeof (float));
788                 }
789
790                 features = _plugin->process (bufs, ::Vamp::RealTime::fromSeconds ((double) pos / _sample_rate));
791
792                 if (cb.type () == LUA_TFUNCTION) {
793                         cb (&features, pos);
794                 }
795
796                 pos += std::min (_stepsize, to_read);
797
798                 if (pos >= len) {
799                         break;
800                 }
801         }
802
803         delete [] data;
804         return rv;
805 }
806
807 ::Vamp::Plugin::FeatureSet
808 LuaAPI::Vamp::process (const std::vector<float*>& d, ::Vamp::RealTime rt)
809 {
810         if (!_plugin || d.size() == 0) {
811                 return ::Vamp::Plugin::FeatureSet ();
812         }
813         const float* const* bufs = &d[0];
814         return _plugin->process (bufs, rt);
815 }
816
817 boost::shared_ptr<Evoral::Note<Evoral::Beats> >
818 LuaAPI::new_noteptr (uint8_t chan, Evoral::Beats beat_time, Evoral::Beats length, uint8_t note, uint8_t velocity)
819 {
820         return boost::shared_ptr<Evoral::Note<Evoral::Beats> > (new Evoral::Note<Evoral::Beats>(chan, beat_time, length, note, velocity));
821 }