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