Add convenience Lua bindings to access plugin controls
[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
21 #include "pbd/error.h"
22 #include "pbd/compose.h"
23
24 #include "ardour/lua_api.h"
25 #include "ardour/luaproc.h"
26 #include "ardour/luascripting.h"
27 #include "ardour/plugin.h"
28 #include "ardour/plugin_insert.h"
29 #include "ardour/plugin_manager.h"
30
31 #include "LuaBridge/LuaBridge.h"
32
33 #include "pbd/i18n.h"
34
35 using namespace ARDOUR;
36 using namespace PBD;
37 using namespace std;
38
39 int
40 ARDOUR::LuaAPI::datatype_ctor_null (lua_State *L)
41 {
42         DataType dt (DataType::NIL);
43         luabridge::Stack <DataType>::push (L, dt);
44         return 1;
45 }
46
47 int
48 ARDOUR::LuaAPI::datatype_ctor_audio (lua_State *L)
49 {
50         DataType dt (DataType::AUDIO);
51         // NB luabridge will copy construct the object and manage lifetime.
52         luabridge::Stack <DataType>::push (L, dt);
53         return 1;
54 }
55
56 int
57 ARDOUR::LuaAPI::datatype_ctor_midi (lua_State *L)
58 {
59         DataType dt (DataType::MIDI);
60         luabridge::Stack <DataType>::push (L, dt);
61         return 1;
62 }
63
64 boost::shared_ptr<Processor>
65 ARDOUR::LuaAPI::nil_processor ()
66 {
67         return boost::shared_ptr<Processor> ();
68 }
69
70 boost::shared_ptr<Processor>
71 ARDOUR::LuaAPI::new_luaproc (Session *s, const string& name)
72 {
73         if (!s) {
74                 return boost::shared_ptr<Processor> ();
75         }
76
77         LuaScriptInfoPtr spi;
78         ARDOUR::LuaScriptList & _scripts (LuaScripting::instance ().scripts (LuaScriptInfo::DSP));
79         for (LuaScriptList::const_iterator i = _scripts.begin(); i != _scripts.end(); ++i) {
80                 if (name == (*i)->name) {
81                         spi = *i;
82                         break;
83                 }
84         }
85
86         if (!spi) {
87                 warning << _("Script with given name was not found\n");
88                 return boost::shared_ptr<Processor> ();
89         }
90
91         PluginPtr p;
92         try {
93                 LuaPluginInfoPtr lpi (new LuaPluginInfo(spi));
94                 p = (lpi->load (*s));
95         } catch (...) {
96                 warning << _("Failed to instantiate Lua Processor\n");
97                 return boost::shared_ptr<Processor> ();
98         }
99
100         return boost::shared_ptr<Processor> (new PluginInsert (*s, p));
101 }
102
103 PluginInfoPtr
104 ARDOUR::LuaAPI::new_plugin_info (const string& name, ARDOUR::PluginType type)
105 {
106         PluginManager& manager = PluginManager::instance();
107         PluginInfoList all_plugs;
108         all_plugs.insert(all_plugs.end(), manager.ladspa_plugin_info().begin(), manager.ladspa_plugin_info().end());
109         all_plugs.insert(all_plugs.end(), manager.lua_plugin_info().begin(), manager.lua_plugin_info().end());
110 #ifdef WINDOWS_VST_SUPPORT
111         all_plugs.insert(all_plugs.end(), manager.windows_vst_plugin_info().begin(), manager.windows_vst_plugin_info().end());
112 #endif
113 #ifdef LXVST_SUPPORT
114         all_plugs.insert(all_plugs.end(), manager.lxvst_plugin_info().begin(), manager.lxvst_plugin_info().end());
115 #endif
116 #ifdef AUDIOUNIT_SUPPORT
117         all_plugs.insert(all_plugs.end(), manager.au_plugin_info().begin(), manager.au_plugin_info().end());
118 #endif
119 #ifdef LV2_SUPPORT
120         all_plugs.insert(all_plugs.end(), manager.lv2_plugin_info().begin(), manager.lv2_plugin_info().end());
121 #endif
122
123         for (PluginInfoList::const_iterator i = all_plugs.begin(); i != all_plugs.end(); ++i) {
124                 if (((*i)->name == name || (*i)->unique_id == name) && (*i)->type == type) {
125                         return *i;
126                 }
127         }
128         return PluginInfoPtr ();
129 }
130
131 boost::shared_ptr<Processor>
132 ARDOUR::LuaAPI::new_plugin (Session *s, const string& name, ARDOUR::PluginType type, const string& preset)
133 {
134         if (!s) {
135                 return boost::shared_ptr<Processor> ();
136         }
137
138         PluginInfoPtr pip = new_plugin_info (name, type);
139
140         if (!pip) {
141                 return boost::shared_ptr<Processor> ();
142         }
143
144         PluginPtr p = pip->load (*s);
145         if (!p) {
146                 return boost::shared_ptr<Processor> ();
147         }
148
149         if (!preset.empty()) {
150                 const Plugin::PresetRecord *pr = p->preset_by_label (preset);
151                 if (pr) {
152                         p->load_preset (*pr);
153                 }
154         }
155
156         return boost::shared_ptr<Processor> (new PluginInsert (*s, p));
157 }
158
159 bool
160 ARDOUR::LuaAPI::set_plugin_input_parameter_value_named(boost::shared_ptr<Processor> proc, const string& name, float val)
161 {
162         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (proc);
163         if (!pi) { return false; }
164         boost::shared_ptr<Plugin> plugin = pi->plugin();
165         if (!plugin) { return false; }
166
167         bool test=false;
168         uint32_t controlid=0;
169         ParameterDescriptor pd;
170
171         for (uint32_t param_index = 0; param_index < plugin->parameter_count(); ++param_index)
172         {
173                 controlid = plugin->nth_parameter (param_index, test);
174                 if (!test)
175                 {
176                         break;
177                 }
178                 else
179                 {
180                         //skip output ports
181                         if (!plugin->parameter_is_input (controlid)) { continue; }
182                         string param_name=pi->describe_parameter(Evoral::Parameter(PluginAutomation, 0, controlid));
183                         if (param_name.compare(name) != 0) { continue; }
184                         if (plugin->get_parameter_descriptor (controlid, pd) != 0) { continue; }
185                         if (val < pd.lower || val > pd.upper) { break; }
186                         boost::shared_ptr<AutomationControl> c = pi->automation_control (Evoral::Parameter(PluginAutomation, 0, controlid));
187                         c->set_value (val, PBD::Controllable::NoGroup);
188                         return true;
189                 }
190         }
191         return false;
192 }
193
194 float
195 ARDOUR::LuaAPI::get_plugin_parameter_value_named(boost::shared_ptr<Processor> proc, int type, const string& name, bool &ok)
196 {
197         ok=false;
198         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (proc);
199         if (!pi) { return 0; }
200         boost::shared_ptr<Plugin> plugin = pi->plugin();
201         if (!plugin) { return 0; }
202
203         bool test=false;
204         uint32_t controlid=0;
205         ParameterDescriptor pd;
206
207         for (uint32_t param_index = 0; param_index < plugin->parameter_count(); ++param_index)
208         {
209                 controlid = plugin->nth_parameter (param_index, test);
210                 if (!test)
211                 {
212                         return 0;
213                 }
214                 else
215                 {
216                         if(type==0) //input
217                         {
218                                 //skip output ports
219                                 if (!plugin->parameter_is_input (controlid)) { continue; }
220                         }
221                         else if(type==1) //output
222                         {
223                                 //skip input ports
224                                 if (plugin->parameter_is_input (controlid)) { continue; }
225                         }
226                         else
227                         {
228                                 return 0;
229                         }
230                         string param_name=pi->describe_parameter(Evoral::Parameter(PluginAutomation, 0, controlid));
231                         if (param_name.compare(name) != 0) { continue; }
232                         ok=true;
233                         return plugin->get_parameter ( controlid );
234                 }
235         }
236         return 0;
237 }
238
239 float
240 ARDOUR::LuaAPI::get_plugin_input_parameter_value_named(boost::shared_ptr<Processor> proc, const string& name, bool &ok)
241 {
242         return get_plugin_parameter_value_named(proc,0,name,ok);
243 }
244
245 float
246 ARDOUR::LuaAPI::get_plugin_output_parameter_value_named(boost::shared_ptr<Processor> proc, const string& name, bool &ok)
247 {
248         return get_plugin_parameter_value_named(proc,1,name,ok);
249 }
250
251 bool
252 ARDOUR::LuaAPI::set_plugin_insert_param (boost::shared_ptr<PluginInsert> pi, uint32_t which, float val)
253 {
254         boost::shared_ptr<Plugin> plugin = pi->plugin();
255         if (!plugin) { return false; }
256
257         bool ok=false;
258         uint32_t controlid = plugin->nth_parameter (which, ok);
259         if (!ok) { return false; }
260         if (!plugin->parameter_is_input (controlid)) { return false; }
261
262         ParameterDescriptor pd;
263         if (plugin->get_parameter_descriptor (controlid, pd) != 0) { return false; }
264         if (val < pd.lower || val > pd.upper) { return false; }
265
266         boost::shared_ptr<AutomationControl> c = pi->automation_control (Evoral::Parameter(PluginAutomation, 0, controlid));
267         c->set_value (val, PBD::Controllable::NoGroup);
268         return true;
269 }
270
271 float
272 ARDOUR::LuaAPI::get_plugin_insert_param (boost::shared_ptr<PluginInsert> pi, uint32_t which, bool &ok)
273 {
274         ok=false;
275         boost::shared_ptr<Plugin> plugin = pi->plugin();
276         if (!plugin) { return 0; }
277         uint32_t controlid = plugin->nth_parameter (which, ok);
278         if (!ok) { return 0; }
279         return plugin->get_parameter ( controlid );
280 }
281
282 bool
283 ARDOUR::LuaAPI::set_processor_param (boost::shared_ptr<Processor> proc, uint32_t which, float val)
284 {
285         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (proc);
286         if (!pi) { return false; }
287         return set_plugin_insert_param (pi, which, val);
288 }
289
290 float
291 ARDOUR::LuaAPI::get_processor_param (boost::shared_ptr<Processor> proc, uint32_t which, bool &ok)
292 {
293         ok=false;
294         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (proc);
295         if (!pi) { return false; }
296         return get_plugin_insert_param (pi, which, ok);
297 }
298
299 int
300 ARDOUR::LuaAPI::plugin_automation (lua_State *L)
301 {
302         typedef boost::shared_ptr<Processor> T;
303
304         int top = lua_gettop(L);
305         if (top < 2) {
306                 return luaL_argerror (L, 1, "invalid number of arguments, :plugin_automation (plugin, parameter_number)");
307         }
308         T* const p = luabridge::Userdata::get<T>(L, 1, false);
309         uint32_t which = luabridge::Stack<uint32_t>::get (L, 2);
310         if (!p) {
311                 return luaL_error (L, "Invalid pointer to Ardour:Processor");
312         }
313         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (*p);
314         if (!pi) {
315                 return luaL_error (L, "Given Processor is not a Plugin Insert");
316         }
317         boost::shared_ptr<Plugin> plugin = pi->plugin();
318         if (!plugin) {
319                 return luaL_error (L, "Given Processor is not a Plugin");
320         }
321
322         bool ok=false;
323         uint32_t controlid = plugin->nth_parameter (which, ok);
324         if (!ok) {
325                 return luaL_error (L, "Invalid Parameter");
326         }
327         if (!plugin->parameter_is_input (controlid)) {
328                 return luaL_error (L, "Given Parameter is not an input");
329         }
330
331         ParameterDescriptor pd;
332         if (plugin->get_parameter_descriptor (controlid, pd) != 0) {
333                 return luaL_error (L, "Cannot describe parameter");
334         }
335
336         boost::shared_ptr<AutomationControl> c = pi->automation_control (Evoral::Parameter(PluginAutomation, 0, controlid));
337
338         luabridge::Stack<boost::shared_ptr<AutomationList> >::push (L, c->alist());
339         luabridge::Stack<boost::shared_ptr<Evoral::ControlList> >::push (L, c->list());
340         luabridge::Stack<ParameterDescriptor>::push (L, pd);
341         return 3;
342 }
343
344 int
345 ARDOUR::LuaOSC::Address::send (lua_State *L)
346 {
347         Address * const luaosc = luabridge::Userdata::get <Address> (L, 1, false);
348         if (!luaosc) {
349                 return luaL_error (L, "Invalid pointer to OSC.Address");
350         }
351         if (!luaosc->_addr) {
352                 return luaL_error (L, "Invalid Destination Address");
353         }
354
355         int top = lua_gettop(L);
356         if (top < 3) {
357                 return luaL_argerror (L, 1, "invalid number of arguments, :send (path, type, ...)");
358         }
359
360         const char* path = luaL_checkstring (L, 2);
361         const char* type = luaL_checkstring (L, 3);
362         assert (path && type);
363
364         if ((int) strlen(type) != top - 3) {
365                 return luaL_argerror (L, 3, "type description does not match arguments");
366         }
367
368         lo_message msg = lo_message_new ();
369
370         for (int i = 4; i <= top; ++i) {
371                 char t = type[i - 4];
372                 int lt = lua_type(L, i);
373                 int ok = -1;
374                 switch(lt) {
375                         case LUA_TSTRING:
376                                 if (t == LO_STRING) {
377                                         ok = lo_message_add_string (msg, luaL_checkstring(L, i));
378                                 } else if (t == LO_CHAR) {
379                                         char c = luaL_checkstring (L, i) [0];
380                                         ok = lo_message_add_char (msg, c);
381                                 }
382                                 break;
383                         case LUA_TBOOLEAN:
384                                 if (t == LO_TRUE || t == LO_FALSE) {
385                                         if (lua_toboolean (L, i)) {
386                                                 ok = lo_message_add_true (msg);
387                                         } else {
388                                                 ok = lo_message_add_false (msg);
389                                         }
390                                 }
391                                 break;
392                         case LUA_TNUMBER:
393                                 if (t == LO_INT32) {
394                                         ok = lo_message_add_int32 (msg, (int32_t) luaL_checkinteger(L, i));
395                                 }
396                                 else if (t == LO_FLOAT) {
397                                         ok = lo_message_add_float (msg, (float) luaL_checknumber(L, i));
398                                 }
399                                 else if (t == LO_DOUBLE) {
400                                         ok = lo_message_add_double (msg, (double) luaL_checknumber(L, i));
401                                 }
402                                 else if (t == LO_INT64) {
403                                         ok = lo_message_add_double (msg, (int64_t) luaL_checknumber(L, i));
404                                 }
405                                 break;
406                         default:
407                                 break;
408                 }
409                 if (ok != 0) {
410                         return luaL_argerror (L, i, "type description does not match parameter");
411                 }
412         }
413
414         int rv = lo_send_message (luaosc->_addr, path, msg);
415         lo_message_free (msg);
416         luabridge::Stack<bool>::push (L, (rv == 0));
417         return 1;
418 }
419
420 static double hue2rgb (const double p, const double q, double t) {
421         if (t < 0.0) t += 1.0;
422         if (t > 1.0) t -= 1.0;
423         if (t < 1.0 / 6.0) return p + (q - p) * 6.0 * t;
424         if (t < 1.0 / 2.0) return q;
425         if (t < 2.0 / 3.0) return p + (q - p) * (2.0 / 3.0 - t) * 6.0;
426         return p;
427 }
428
429 int
430 ARDOUR::LuaAPI::hsla_to_rgba (lua_State *L)
431 {
432         int top = lua_gettop(L);
433         if (top < 3) {
434                 return luaL_argerror (L, 1, "invalid number of arguments, :hsla_to_rgba (h, s, l [,a])");
435         }
436         double h = luabridge::Stack<double>::get (L, 1);
437         double s = luabridge::Stack<double>::get (L, 2);
438         double l = luabridge::Stack<double>::get (L, 3);
439         double a = 1.0;
440         if (top > 3) {
441                 a = luabridge::Stack<double>::get (L, 4);
442         }
443
444         // we can't use ArdourCanvas::hsva_to_color here
445         // besides we want HSL not HSV and without intermediate
446         // color_to_rgba (rgba_to_color ())
447         double r,g,b;
448         const double cq = l < 0.5 ? l * (1 + s) : l + s - l * s;
449         const double cp = 2.f * l - cq;
450         r = hue2rgb (cp, cq, h + 1.0 / 3.0);
451         g = hue2rgb (cp, cq, h);
452         b = hue2rgb (cp, cq, h - 1.0 / 3.0);
453
454         luabridge::Stack<double>::push (L, r);
455         luabridge::Stack<double>::push (L, g);
456         luabridge::Stack<double>::push (L, b);
457         luabridge::Stack<double>::push (L, a);
458         return 4;
459 }
460
461 int
462 ARDOUR::LuaAPI::build_filename (lua_State *L)
463 {
464         std::vector<std::string> elem;
465         int top = lua_gettop(L);
466         if (top < 1) {
467                 return luaL_argerror (L, 1, "invalid number of arguments, build_filename (path, ...)");
468         }
469         for (int i = 1; i <= top; ++i) {
470                 int lt = lua_type (L, i);
471                 if (lt != LUA_TSTRING) {
472                         return luaL_argerror (L, i, "invalid argument type, expected string");
473                 }
474                 elem.push_back (luaL_checkstring(L, i));
475         }
476
477         luabridge::Stack<std::string>::push (L, Glib::build_filename (elem));
478         return 1;
479 }
480
481 luabridge::LuaRef::Proxy&
482 luabridge::LuaRef::Proxy::clone_instance (const void* classkey, void* p) {
483         lua_rawgeti (m_L, LUA_REGISTRYINDEX, m_tableRef);
484         lua_rawgeti (m_L, LUA_REGISTRYINDEX, m_keyRef);
485
486         luabridge::UserdataPtr::push_raw (m_L, p, classkey);
487
488         lua_rawset (m_L, -3);
489         lua_pop (m_L, 1);
490         return *this;
491 }
492
493 LuaTableRef::LuaTableRef () {}
494 LuaTableRef::~LuaTableRef () {}
495
496 int
497 LuaTableRef::get (lua_State* L)
498 {
499         luabridge::LuaRef rv (luabridge::newTable (L));
500         for (std::vector<LuaTableEntry>::const_iterator i = _data.begin (); i != _data.end (); ++i) {
501                 switch ((*i).keytype) {
502                         case LUA_TSTRING:
503                                 assign(&rv, i->k_s, *i);
504                                 break;
505                         case LUA_TNUMBER:
506                                 assign(&rv, i->k_n, *i);
507                                 break;
508                 }
509         }
510         luabridge::push (L, rv);
511         return 1;
512 }
513
514 int
515 LuaTableRef::set (lua_State* L)
516 {
517         if (!lua_istable (L, -1)) { return luaL_error (L, "argument is not a table"); }
518         _data.clear ();
519
520         lua_pushvalue (L, -1);
521         lua_pushnil (L);
522         while (lua_next (L, -2)) {
523                 lua_pushvalue (L, -2);
524
525                 LuaTableEntry s (lua_type(L, -1), lua_type(L, -2));
526                 switch (lua_type(L, -1)) {
527                         case LUA_TSTRING:
528                                 s.k_s = luabridge::Stack<std::string>::get (L, -1);
529                                 break;
530                                 ;
531                         case LUA_TNUMBER:
532                                 s.k_n = luabridge::Stack<unsigned int>::get (L, -1);
533                                 break;
534                         default:
535                                 // invalid key
536                                 lua_pop (L, 2);
537                                 continue;
538                 }
539
540                 switch(lua_type(L, -2)) {
541                         case LUA_TSTRING:
542                                 s.s = luabridge::Stack<std::string>::get (L, -2);
543                                 break;
544                         case LUA_TBOOLEAN:
545                                 s.b = lua_toboolean (L, -2);
546                                 break;
547                         case LUA_TNUMBER:
548                                 s.n = lua_tonumber (L, -2);
549                                 break;
550                         case LUA_TUSERDATA:
551                                 {
552                                         bool ok = false;
553                                         lua_getmetatable (L, -2);
554                                         lua_rawgetp (L, -1, luabridge::getIdentityKey ());
555                                         if (lua_isboolean (L, -1)) {
556                                                 lua_pop (L, 1);
557                                                 const void* key = lua_topointer (L, -1);
558                                                 lua_pop (L, 1);
559                                                 void const* classkey = findclasskey (L, key);
560
561                                                 if (classkey) {
562                                                         ok = true;
563                                                         s.c = classkey;
564                                                         s.p = luabridge::Userdata::get_ptr (L, -2);
565                                                 }
566                                         } else {
567                                                 lua_pop (L, 2);
568                                         }
569
570                                         if (ok) {
571                                                 break;
572                                         }
573                                         // invalid userdata -- fall through
574                                 }
575                                 // no break
576                         case LUA_TFUNCTION: // no support -- we could... string.format("%q", string.dump(value, true))
577                         case LUA_TTABLE: // no nested tables, sorry.
578                         case LUA_TNIL: // fallthrough
579                         default:
580                                 // invalid value
581                                 lua_pop (L, 2);
582                                 continue;
583                 }
584
585                 _data.push_back(s);
586                 lua_pop (L, 2);
587         }
588         return 0;
589 }
590
591 void*
592 LuaTableRef::findclasskey (lua_State *L, const void* key)
593 {
594         lua_pushvalue(L, LUA_REGISTRYINDEX);
595         lua_pushnil (L);
596         while (lua_next (L, -2)) {
597                 lua_pushvalue (L, -2);
598                 if (lua_topointer(L, -2) == key) {
599                         void* rv = lua_touserdata (L, -1);
600                         lua_pop (L, 4);
601                         return rv;
602                 }
603                 lua_pop (L, 2);
604         }
605         lua_pop (L, 1);
606         return NULL;
607 }
608
609 template<typename T>
610 void LuaTableRef::assign (luabridge::LuaRef* rv, T key, const LuaTableEntry& s)
611 {
612         switch (s.valuetype) {
613                 case LUA_TSTRING:
614                         (*rv)[key] = s.s;
615                         break;
616                 case LUA_TBOOLEAN:
617                         (*rv)[key] = s.b;
618                         break;
619                 case LUA_TNUMBER:
620                         (*rv)[key] = s.n;
621                         break;
622                 case LUA_TUSERDATA:
623                         (*rv)[key].clone_instance (s.c, s.p);
624                         break;
625                 default:
626                         assert (0);
627                         break;
628         }
629 }