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