Expose a new lua hook for resetting a plugin processor ( convenience func only: this...
[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::build_filename (lua_State *L)
507 {
508         std::vector<std::string> elem;
509         int top = lua_gettop (L);
510         if (top < 1) {
511                 return luaL_argerror (L, 1, "invalid number of arguments, build_filename (path, ...)");
512         }
513         for (int i = 1; i <= top; ++i) {
514                 int lt = lua_type (L, i);
515                 if (lt != LUA_TSTRING) {
516                         return luaL_argerror (L, i, "invalid argument type, expected string");
517                 }
518                 elem.push_back (luaL_checkstring (L, i));
519         }
520
521         luabridge::Stack<std::string>::push (L, Glib::build_filename (elem));
522         return 1;
523 }
524
525 luabridge::LuaRef::Proxy&
526 luabridge::LuaRef::Proxy::clone_instance (const void* classkey, void* p) {
527         lua_rawgeti (m_L, LUA_REGISTRYINDEX, m_tableRef);
528         lua_rawgeti (m_L, LUA_REGISTRYINDEX, m_keyRef);
529
530         luabridge::UserdataPtr::push_raw (m_L, p, classkey);
531
532         lua_rawset (m_L, -3);
533         lua_pop (m_L, 1);
534         return *this;
535 }
536
537 LuaTableRef::LuaTableRef () {}
538 LuaTableRef::~LuaTableRef () {}
539
540 int
541 LuaTableRef::get (lua_State* L)
542 {
543         luabridge::LuaRef rv (luabridge::newTable (L));
544         for (std::vector<LuaTableEntry>::const_iterator i = _data.begin (); i != _data.end (); ++i) {
545                 switch ((*i).keytype) {
546                         case LUA_TSTRING:
547                                 assign (&rv, i->k_s, *i);
548                                 break;
549                         case LUA_TNUMBER:
550                                 assign (&rv, i->k_n, *i);
551                                 break;
552                 }
553         }
554         luabridge::push (L, rv);
555         return 1;
556 }
557
558 int
559 LuaTableRef::set (lua_State* L)
560 {
561         if (!lua_istable (L, -1)) { return luaL_error (L, "argument is not a table"); }
562         _data.clear ();
563
564         lua_pushvalue (L, -1);
565         lua_pushnil (L);
566         while (lua_next (L, -2)) {
567                 lua_pushvalue (L, -2);
568
569                 LuaTableEntry s (lua_type (L, -1), lua_type (L, -2));
570                 switch (lua_type (L, -1)) {
571                         case LUA_TSTRING:
572                                 s.k_s = luabridge::Stack<std::string>::get (L, -1);
573                                 break;
574                                 ;
575                         case LUA_TNUMBER:
576                                 s.k_n = luabridge::Stack<unsigned int>::get (L, -1);
577                                 break;
578                         default:
579                                 // invalid key
580                                 lua_pop (L, 2);
581                                 continue;
582                 }
583
584                 switch (lua_type (L, -2)) {
585                         case LUA_TSTRING:
586                                 s.s = luabridge::Stack<std::string>::get (L, -2);
587                                 break;
588                         case LUA_TBOOLEAN:
589                                 s.b = lua_toboolean (L, -2);
590                                 break;
591                         case LUA_TNUMBER:
592                                 s.n = lua_tonumber (L, -2);
593                                 break;
594                         case LUA_TUSERDATA:
595                                 {
596                                         bool ok = false;
597                                         lua_getmetatable (L, -2);
598                                         lua_rawgetp (L, -1, luabridge::getIdentityKey ());
599                                         if (lua_isboolean (L, -1)) {
600                                                 lua_pop (L, 1);
601                                                 const void* key = lua_topointer (L, -1);
602                                                 lua_pop (L, 1);
603                                                 void const* classkey = findclasskey (L, key);
604
605                                                 if (classkey) {
606                                                         ok = true;
607                                                         s.c = classkey;
608                                                         s.p = luabridge::Userdata::get_ptr (L, -2);
609                                                 }
610                                         } else {
611                                                 lua_pop (L, 2);
612                                         }
613
614                                         if (ok) {
615                                                 break;
616                                         }
617                                         // invalid userdata -- fall through
618                                 }
619                                 // no break
620                         case LUA_TFUNCTION: // no support -- we could... string.format("%q", string.dump(value, true))
621                         case LUA_TTABLE: // no nested tables, sorry.
622                         case LUA_TNIL: // fallthrough
623                         default:
624                                 // invalid value
625                                 lua_pop (L, 2);
626                                 continue;
627                 }
628
629                 _data.push_back (s);
630                 lua_pop (L, 2);
631         }
632         return 0;
633 }
634
635 void*
636 LuaTableRef::findclasskey (lua_State *L, const void* key)
637 {
638         lua_pushvalue (L, LUA_REGISTRYINDEX);
639         lua_pushnil (L);
640         while (lua_next (L, -2)) {
641                 lua_pushvalue (L, -2);
642                 if (lua_topointer (L, -2) == key) {
643                         void* rv = lua_touserdata (L, -1);
644                         lua_pop (L, 4);
645                         return rv;
646                 }
647                 lua_pop (L, 2);
648         }
649         lua_pop (L, 1);
650         return NULL;
651 }
652
653 template<typename T>
654 void LuaTableRef::assign (luabridge::LuaRef* rv, T key, const LuaTableEntry& s)
655 {
656         switch (s.valuetype) {
657                 case LUA_TSTRING:
658                         (*rv)[key] = s.s;
659                         break;
660                 case LUA_TBOOLEAN:
661                         (*rv)[key] = s.b;
662                         break;
663                 case LUA_TNUMBER:
664                         (*rv)[key] = s.n;
665                         break;
666                 case LUA_TUSERDATA:
667                         (*rv)[key].clone_instance (s.c, s.p);
668                         break;
669                 default:
670                         assert (0);
671                         break;
672         }
673 }
674
675 std::vector<std::string>
676 LuaAPI::Vamp::list_plugins ()
677 {
678         using namespace ::Vamp::HostExt;
679         PluginLoader* loader (PluginLoader::getInstance());
680         return loader->listPlugins ();
681 }
682
683 LuaAPI::Vamp::Vamp (const std::string& key, float sample_rate)
684         : _plugin (0)
685         , _sample_rate (sample_rate)
686         , _bufsize (1024)
687         , _stepsize (1024)
688         , _initialized (false)
689 {
690         using namespace ::Vamp::HostExt;
691
692         PluginLoader* loader (PluginLoader::getInstance());
693         _plugin = loader->loadPlugin (key, _sample_rate, PluginLoader::ADAPT_ALL_SAFE);
694
695         if (!_plugin) {
696                 PBD::error << string_compose (_("VAMP Plugin \"%1\" could not be loaded"), key) << endmsg;
697                 throw failed_constructor ();
698         }
699
700         size_t bs = _plugin->getPreferredBlockSize ();
701         size_t ss = _plugin->getPreferredStepSize ();
702
703         if (bs > 0 && ss > 0 && bs <= 8192 && ss <= 8192) {
704                 _bufsize = bs;
705                 _stepsize = bs;
706         }
707 }
708
709 LuaAPI::Vamp::~Vamp ()
710 {
711         delete _plugin;
712 }
713
714 void
715 LuaAPI::Vamp::reset ()
716 {
717         _initialized = false;
718         if (_plugin) {
719                 _plugin->reset ();
720         }
721 }
722
723 bool
724 LuaAPI::Vamp::initialize ()
725 {
726         if (!_plugin || _plugin->getMinChannelCount() > 1) {
727                 return false;
728         }
729         if (!_plugin->initialise (1, _stepsize, _bufsize)) {
730                 return false;
731         }
732         _initialized = true;
733         return true;
734 }
735
736 int
737 LuaAPI::Vamp::analyze (boost::shared_ptr<ARDOUR::Readable> r, uint32_t channel, luabridge::LuaRef cb)
738 {
739         if (!_initialized) {
740                 if (!initialize ()) {
741                         return -1;
742                 }
743         }
744         assert (_initialized);
745
746         ::Vamp::Plugin::FeatureSet features;
747         float* data = new float[_bufsize];
748         float* bufs[1] = { data };
749
750         framecnt_t len = r->readable_length();
751         framepos_t pos = 0;
752
753         int rv = 0;
754         while (1) {
755                 framecnt_t to_read = std::min ((len - pos), _bufsize);
756                 if (r->read (data, pos, to_read, channel) != to_read) {
757                         rv = -1;
758                         break;
759                 }
760                 if (to_read != _bufsize) {
761                         memset (data + to_read, 0, (_bufsize - to_read) * sizeof (float));
762                 }
763
764                 features = _plugin->process (bufs, ::Vamp::RealTime::fromSeconds ((double) pos / _sample_rate));
765
766                 if (cb.type () == LUA_TFUNCTION) {
767                         cb (&features, pos);
768                 }
769
770                 pos += std::min (_stepsize, to_read);
771
772                 if (pos >= len) {
773                         break;
774                 }
775         }
776
777         delete [] data;
778         return rv;
779 }
780
781 ::Vamp::Plugin::FeatureSet
782 LuaAPI::Vamp::process (const std::vector<float*>& d, ::Vamp::RealTime rt)
783 {
784         if (!_plugin || d.size() == 0) {
785                 return ::Vamp::Plugin::FeatureSet ();
786         }
787         const float* const* bufs = &d[0];
788         return _plugin->process (bufs, rt);
789 }
790
791 boost::shared_ptr<Evoral::Note<Evoral::Beats> >
792 LuaAPI::new_noteptr (uint8_t chan, Evoral::Beats beat_time, Evoral::Beats length, uint8_t note, uint8_t velocity)
793 {
794         return boost::shared_ptr<Evoral::Note<Evoral::Beats> > (new Evoral::Note<Evoral::Beats>(chan, beat_time, length, note, velocity));
795 }