31a5dd8785ea9ded314e97ad6d725e9dcc62a666
[ardour.git] / libs / ardour / luaproc.cc
1 /*
2     Copyright (C) 2016 Robin Gareus <robin@gareus.org>
3     Copyright (C) 2006 Paul Davis
4
5     This program is free software; you can redistribute it and/or modify it
6     under the terms of the GNU General Public License as published by the Free
7     Software Foundation; either version 2 of the License, or (at your option)
8     any later version.
9
10     This program is distributed in the hope that it will be useful, but WITHOUT
11     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13     for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 #include <glib.h>
21 #include "pbd/gstdio_compat.h"
22
23 #include "pbd/pthread_utils.h"
24
25 #include "ardour/audio_buffer.h"
26 #include "ardour/buffer_set.h"
27 #include "ardour/luabindings.h"
28 #include "ardour/luaproc.h"
29 #include "ardour/luascripting.h"
30 #include "ardour/midi_buffer.h"
31 #include "ardour/plugin.h"
32 #include "ardour/session.h"
33
34 #include "LuaBridge/LuaBridge.h"
35
36 #include "i18n.h"
37
38 using namespace ARDOUR;
39 using namespace PBD;
40
41 LuaProc::LuaProc (AudioEngine& engine,
42                   Session& session,
43                   const std::string &script)
44         : Plugin (engine, session)
45         , _mempool ("LuaProc", 1048576) // 1 MB is plenty. (64K would be enough)
46         , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
47         , _lua_dsp (0)
48         , _script (script)
49         , _lua_does_channelmapping (false)
50         , _lua_has_inline_display (false)
51         , _control_data (0)
52         , _shadow_data (0)
53         , _has_midi_input (false)
54         , _has_midi_output (false)
55 {
56         init ();
57
58         /* when loading a session, or pasing a processor,
59          * the script is set during set_state();
60          */
61         if (!_script.empty () && load_script ()) {
62                 throw failed_constructor ();
63         }
64 }
65
66 LuaProc::LuaProc (const LuaProc &other)
67         : Plugin (other)
68         , _mempool ("LuaProc", 1048576) // 1 MB is plenty. (64K would be enough)
69         , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
70         , _lua_dsp (0)
71         , _script (other.script ())
72         , _lua_does_channelmapping (false)
73         , _lua_has_inline_display (false)
74         , _control_data (0)
75         , _shadow_data (0)
76         , _has_midi_input (false)
77         , _has_midi_output (false)
78 {
79         init ();
80
81         if (load_script ()) {
82                 throw failed_constructor ();
83         }
84
85         for (uint32_t i = 0; i < parameter_count (); ++i) {
86                 _control_data[i] = other._shadow_data[i];
87                 _shadow_data[i]  = other._shadow_data[i];
88         }
89 }
90
91 LuaProc::~LuaProc () {
92 #ifdef WITH_LUAPROC_STATS
93         if (_info && _stats_cnt > 0) {
94                 printf ("LuaProc: '%s' run()  avg: %.3f  max: %.3f [ms]\n",
95                                 _info->name.c_str (),
96                                 0.0001f * _stats_avg[0] / (float) _stats_cnt,
97                                 0.0001f * _stats_max[0]);
98                 printf ("LuaProc: '%s' gc()   avg: %.3f  max: %.3f [ms]\n",
99                                 _info->name.c_str (),
100                                 0.0001f * _stats_avg[1] / (float) _stats_cnt,
101                                 0.0001f * _stats_max[1]);
102         }
103 #endif
104         lua.do_command ("collectgarbage();");
105         delete (_lua_dsp);
106         delete [] _control_data;
107         delete [] _shadow_data;
108 }
109
110 void
111 LuaProc::init ()
112 {
113 #ifdef WITH_LUAPROC_STATS
114         _stats_avg[0] = _stats_avg[1] = _stats_max[0] = _stats_max[1] = _stats_cnt = 0;
115 #endif
116
117         lua.Print.connect (sigc::mem_fun (*this, &LuaProc::lua_print));
118         // register session object
119         lua_State* L = lua.getState ();
120         LuaBindings::stddef (L);
121         LuaBindings::common (L);
122         LuaBindings::dsp (L);
123
124         luabridge::getGlobalNamespace (L)
125                 .beginNamespace ("Ardour")
126                 .beginClass <LuaProc> ("LuaProc")
127                 .addFunction ("queue_draw", &LuaProc::queue_draw)
128                 .addFunction ("shmem", &LuaProc::instance_shm)
129                 .endClass ()
130                 .endNamespace ();
131
132         // add session to global lua namespace
133         luabridge::push <Session *> (L, &_session);
134         lua_setglobal (L, "Session");
135
136         // instance
137         luabridge::push <LuaProc *> (L, this);
138         lua_setglobal (L, "self");
139
140         // sandbox
141         lua.do_command ("io = nil os = nil loadfile = nil require = nil dofile = nil package = nil debug = nil");
142 #if 0
143         lua.do_command ("for n in pairs(_G) do print(n) end print ('----')"); // print global env
144 #endif
145         lua.do_command ("function ardour () end");
146 }
147
148 void
149 LuaProc::lua_print (std::string s) {
150         std::cout <<"LuaProc: " << s << "\n";
151         PBD::error << "LuaProc: " << s << "\n";
152 }
153
154 bool
155 LuaProc::load_script ()
156 {
157         assert (!_lua_dsp); // don't allow to re-initialize
158         LuaPluginInfoPtr lpi;
159
160         // TODO: refine APIs; function arguments..
161         // - perform channel-map in ardour (silent/scratch buffers) ?
162         // - control-port API (explicit get/set functions ??)
163         // - latency reporting (global var? ctrl-port? set-function ?)
164         // - MIDI -> sparse table of events
165         //     { [sample] => { Event }, .. }
166         //   or  { { sample, Event }, .. }
167
168         try {
169                 LuaScriptInfoPtr lsi = LuaScripting::script_info (_script);
170                 lpi = LuaPluginInfoPtr (new LuaPluginInfo (lsi));
171                 assert (lpi);
172                 set_info (lpi);
173                 _mempool.set_name ("LuaProc: " + lsi->name);
174                 _docs = lsi->description;
175         } catch (failed_constructor& err) {
176                 return true;
177         }
178
179         lua_State* L = lua.getState ();
180         lua.do_command (_script);
181
182         // check if script has a DSP callback
183         luabridge::LuaRef lua_dsp_run = luabridge::getGlobal (L, "dsp_run");
184         luabridge::LuaRef lua_dsp_map = luabridge::getGlobal (L, "dsp_runmap");
185
186         if ((lua_dsp_run.type () != LUA_TFUNCTION) == (lua_dsp_map.type () != LUA_TFUNCTION)) {
187                 return true;
188         }
189
190         if (lua_dsp_run.type () == LUA_TFUNCTION) {
191                 _lua_dsp = new luabridge::LuaRef (lua_dsp_run);
192         }
193         else if (lua_dsp_map.type () == LUA_TFUNCTION) {
194                 _lua_dsp = new luabridge::LuaRef (lua_dsp_map);
195                 _lua_does_channelmapping = true;
196         }
197         else {
198                 assert (0);
199         }
200
201         // initialize the DSP if needed
202         luabridge::LuaRef lua_dsp_init = luabridge::getGlobal (L, "dsp_init");
203         if (lua_dsp_init.type () == LUA_TFUNCTION) {
204                 try {
205                         lua_dsp_init (_session.nominal_frame_rate ());
206                 } catch (luabridge::LuaException const& e) {
207                         ;
208                 }
209         }
210
211         luabridge::LuaRef lua_dsp_midi_in = luabridge::getGlobal (L, "dsp_midi_input");
212         if (lua_dsp_midi_in.type () == LUA_TFUNCTION) {
213                 try {
214                         _has_midi_input = lua_dsp_midi_in ();
215                 } catch (luabridge::LuaException const& e) {
216                         ;
217                 }
218         }
219         lpi->_is_instrument = _has_midi_input;
220
221         _ctrl_params.clear ();
222
223         luabridge::LuaRef lua_render = luabridge::getGlobal (L, "render_inline");
224         if (lua_render.isFunction ()) {
225                 _lua_has_inline_display = true;
226         }
227
228         luabridge::LuaRef lua_params = luabridge::getGlobal (L, "dsp_params");
229         if (lua_params.isFunction ()) {
230
231                 // call function // add try {} catch (luabridge::LuaException const& e)
232                 luabridge::LuaRef params = lua_params ();
233
234                 if (params.isTable ()) {
235
236                         for (luabridge::Iterator i (params); !i.isNil (); ++i) {
237                                 // required fields
238                                 if (!i.key ().isNumber ())           { return false; }
239                                 if (!i.value ().isTable ())          { return false; }
240                                 if (!i.value ()["type"].isString ()) { return false; }
241                                 if (!i.value ()["name"].isString ()) { return false; }
242                                 if (!i.value ()["min"].isNumber ())  { return false; }
243                                 if (!i.value ()["max"].isNumber ())  { return false; }
244
245                                 int pn = i.key ().cast<int> ();
246                                 std::string type = i.value ()["type"].cast<std::string> ();
247                                 if (type == "input") {
248                                         if (!i.value ()["default"].isNumber ()) { return false; }
249                                         _ctrl_params.push_back (std::make_pair (false, pn));
250                                 }
251                                 else if (type == "output") {
252                                         _ctrl_params.push_back (std::make_pair (true, pn));
253                                 } else {
254                                         return false;
255                                 }
256                                 assert (pn == (int) _ctrl_params.size ());
257
258                                 //_param_desc[pn] = boost::shared_ptr<ParameterDescriptor> (new ParameterDescriptor());
259                                 luabridge::LuaRef lr = i.value ();
260
261                                 if (type == "input") {
262                                         _param_desc[pn].normal     = lr["default"].cast<float> ();
263                                 } else {
264                                         _param_desc[pn].normal     = lr["min"].cast<float> (); // output-port, no default
265                                 }
266                                 _param_desc[pn].lower        = lr["min"].cast<float> ();
267                                 _param_desc[pn].upper        = lr["max"].cast<float> ();
268                                 _param_desc[pn].toggled      = lr["toggled"].isBoolean () && (lr["toggled"]).cast<bool> ();
269                                 _param_desc[pn].logarithmic  = lr["logarithmic"].isBoolean () && (lr["logarithmic"]).cast<bool> ();
270                                 _param_desc[pn].integer_step = lr["integer"].isBoolean () && (lr["integer"]).cast<bool> ();
271                                 _param_desc[pn].sr_dependent = lr["ratemult"].isBoolean () && (lr["ratemult"]).cast<bool> ();
272                                 _param_desc[pn].enumeration  = lr["enum"].isBoolean () && (lr["enum"]).cast<bool> ();
273
274                                 if (lr["unit"].isString ()) {
275                                         std::string unit = lr["unit"].cast<std::string> ();
276                                         if (unit == "dB")             { _param_desc[pn].unit = ParameterDescriptor::DB; }
277                                         else if (unit == "Hz")        { _param_desc[pn].unit = ParameterDescriptor::HZ; }
278                                         else if (unit == "Midi Note") { _param_desc[pn].unit = ParameterDescriptor::MIDI_NOTE; }
279                                 }
280                                 _param_desc[pn].label        = (lr["name"]).cast<std::string> ();
281                                 _param_desc[pn].scale_points = parse_scale_points (&lr);
282
283                                 luabridge::LuaRef doc = lr["doc"];
284                                 if (doc.isString ()) {
285                                         _param_doc[pn] = doc.cast<std::string> ();
286                                 } else {
287                                         _param_doc[pn] = "";
288                                 }
289                                 assert (!(_param_desc[pn].toggled && _param_desc[pn].logarithmic));
290                         }
291                 }
292         }
293
294         _control_data = new float[parameter_count ()];
295         _shadow_data  = new float[parameter_count ()];
296
297         for (uint32_t i = 0; i < parameter_count (); ++i) {
298                 if (parameter_is_input (i)) {
299                         _control_data[i] = _shadow_data[i] = default_value (i);
300                 }
301         }
302
303         // expose ctrl-ports to global lua namespace
304         luabridge::push <float *> (L, _control_data);
305         lua_setglobal (L, "CtrlPorts");
306
307         return false; // no error
308 }
309
310 bool
311 LuaProc::can_support_io_configuration (const ChanCount& in, ChanCount& out, ChanCount* imprecise)
312 {
313         // caller must hold process lock (no concurrent calls to interpreter
314
315         if (in.n_midi() > 0 && !_has_midi_input && !imprecise) {
316                 return false;
317         }
318
319         lua_State* L = lua.getState ();
320         luabridge::LuaRef ioconfig = luabridge::getGlobal (L, "dsp_ioconfig");
321         if (!ioconfig.isFunction ()) {
322                 return false;
323         }
324
325         luabridge::LuaRef table = luabridge::getGlobal (L, "table"); //lua std lib
326         luabridge::LuaRef tablesort = table["sort"];
327         assert (tablesort.isFunction ());
328
329         luabridge::LuaRef *_iotable = NULL; // can't use reference :(
330         try {
331                 luabridge::LuaRef iotable = ioconfig ();
332                 tablesort (iotable);
333                 if (iotable.isTable ()) {
334                         _iotable = new luabridge::LuaRef (iotable);
335                 }
336         } catch (luabridge::LuaException const& e) {
337                 return false;
338         }
339
340         if (!_iotable) {
341                 return false;
342         }
343
344         // now we can reference it.
345         luabridge::LuaRef iotable (*_iotable);
346         delete _iotable;
347
348         if ((iotable).length () < 1) {
349                 return false;
350         }
351
352         const int32_t audio_in = in.n_audio ();
353         int32_t audio_out;
354         int32_t midi_out = 0; // TODO handle  _has_midi_output
355
356         // preferred setting (provided by plugin_insert)
357         assert (out.n_audio () > 0);
358         audio_out = out.n_audio ();
359
360         for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
361                 assert (i.value ().type () == LUA_TTABLE);
362                 luabridge::LuaRef io (i.value ());
363
364                 int possible_in = io["audio_in"];
365                 int possible_out = io["audio_out"];
366
367                 // exact match
368                 if ((possible_in == audio_in) && (possible_out == audio_out)) {
369                         out.set (DataType::MIDI, 0);
370                         out.set (DataType::AUDIO, audio_out);
371                         return true;
372                 }
373         }
374
375         /* now allow potentially "imprecise" matches */
376         audio_out = -1;
377         bool found = false;
378
379         float penalty = 9999;
380         const int preferred_out = out.n_audio ();
381
382 #define FOUNDCFG(nch) {                                  \
383         float p = fabsf ((float)(nch) - preferred_out);  \
384         if ((nch) > preferred_out) { p *= 1.1; }         \
385         if (p < penalty) {                               \
386                 audio_out = (nch);                       \
387                 penalty = p;                             \
388                 found = true;                            \
389         }                                                \
390 }
391
392         for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
393                 assert (i.value ().type () == LUA_TTABLE);
394                 luabridge::LuaRef io (i.value ());
395
396                 int possible_in = io["audio_in"];
397                 int possible_out = io["audio_out"];
398
399                 if (possible_out == 0) {
400                         continue;
401                 }
402                 if (possible_in == 0) {
403                         /* no inputs, generators & instruments */
404                         if (possible_out == -1) {
405                                 /* any configuration possible, stereo output */
406                                 FOUNDCFG (preferred_out);
407                         } else if (possible_out == -2) {
408                                 /* invalid, should be (0, -1) */
409                                 FOUNDCFG (preferred_out);
410                         } else if (possible_out < -2) {
411                                 /* variable number of outputs up to -N, */
412                                 FOUNDCFG (min (-possible_out, preferred_out));
413                         } else {
414                                 /* exact number of outputs */
415                                 FOUNDCFG (possible_out);
416                         }
417                 }
418
419                 if (possible_in == -1) {
420                         /* wildcard for input */
421                         if (possible_out == -1) {
422                                 /* out must match in */
423                                 FOUNDCFG (audio_in);
424                         } else if (possible_out == -2) {
425                                 /* any configuration possible, pick matching */
426                                 FOUNDCFG (preferred_out);
427                         } else if (possible_out < -2) {
428                                 /* explicitly variable number of outputs, pick maximum */
429                                 FOUNDCFG (max (-possible_out, preferred_out));
430                                 /* and try min, too, in case the penalty is lower */
431                                 FOUNDCFG (min (-possible_out, preferred_out));
432                         } else {
433                                 /* exact number of outputs */
434                                 FOUNDCFG (possible_out);
435                         }
436                 }
437
438                 if (possible_in == -2) {
439
440                         if (possible_out == -1) {
441                                 /* any configuration possible, pick matching */
442                                 FOUNDCFG (preferred_out);
443                         } else if (possible_out == -2) {
444                                 /* invalid. interpret as (-1, -1) */
445                                 FOUNDCFG (preferred_out);
446                         } else if (possible_out < -2) {
447                                 /* invalid,  interpret as (<-2, <-2)
448                                  * variable number of outputs up to -N, */
449                                 FOUNDCFG (min (-possible_out, preferred_out));
450                         } else {
451                                 /* exact number of outputs */
452                                 FOUNDCFG (possible_out);
453                         }
454                 }
455
456                 if (possible_in < -2) {
457                         /* explicit variable number of inputs */
458                         if (audio_in > -possible_in && imprecise != NULL) {
459                                 // hide inputs ports
460                                 imprecise->set (DataType::AUDIO, -possible_in);
461                         }
462
463                         if (audio_in > -possible_in && imprecise == NULL) {
464                                 /* request is too large */
465                         } else if (possible_out == -1) {
466                                 /* any output configuration possible */
467                                 FOUNDCFG (preferred_out);
468                         } else if (possible_out == -2) {
469                                 /* invalid. interpret as (<-2, -1) */
470                                 FOUNDCFG (preferred_out);
471                         } else if (possible_out < -2) {
472                                 /* variable number of outputs up to -N, */
473                                 FOUNDCFG (min (-possible_out, preferred_out));
474                         } else {
475                                 /* exact number of outputs */
476                                 FOUNDCFG (possible_out);
477                         }
478                 }
479
480                 if (possible_in && (possible_in == audio_in)) {
481                         /* exact number of inputs ... must match obviously */
482                         if (possible_out == -1) {
483                                 /* any output configuration possible */
484                                 FOUNDCFG (preferred_out);
485                         } else if (possible_out == -2) {
486                                 /* invalid. interpret as (>0, -1) */
487                                 FOUNDCFG (preferred_out);
488                         } else if (possible_out < -2) {
489                                 /* > 0, < -2 is not specified
490                                  * interpret as up to -N */
491                                 FOUNDCFG (min (-possible_out, preferred_out));
492                         } else {
493                                 /* exact number of outputs */
494                                 FOUNDCFG (possible_out);
495                         }
496                 }
497         }
498
499         if (!found && imprecise) {
500                 /* try harder */
501                 for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
502                         assert (i.value ().type () == LUA_TTABLE);
503                         luabridge::LuaRef io (i.value ());
504
505                         int possible_in = io["audio_in"];
506                         int possible_out = io["audio_out"];
507
508                         assert (possible_in > 0); // all other cases will have been matched above
509                         assert (possible_out !=0 || possible_in !=0); // already handled above
510
511                         imprecise->set (DataType::AUDIO, possible_in);
512                         if (possible_out == -1 || possible_out == -2) {
513                                 FOUNDCFG (2);
514                         } else if (possible_out < -2) {
515                                 /* explicitly variable number of outputs, pick maximum */
516                                 FOUNDCFG (min (-possible_out, preferred_out));
517                         } else {
518                                 /* exact number of outputs */
519                                 FOUNDCFG (possible_out);
520                         }
521                         // ideally we'll also find the closest, best matching
522                         // input configuration with minimal output penalty...
523                 }
524         }
525
526
527         if (!found) {
528                 return false;
529         }
530
531         out.set (DataType::MIDI, midi_out); // currently always zero
532         out.set (DataType::AUDIO, audio_out);
533         return true;
534 }
535
536 bool
537 LuaProc::configure_io (ChanCount in, ChanCount out)
538 {
539         _configured_in = in;
540         _configured_out = out;
541
542         _configured_in.set (DataType::MIDI, _has_midi_input ? 1 : 0);
543         _configured_out.set (DataType::MIDI, _has_midi_output ? 1 : 0);
544
545         // configure the DSP if needed
546         lua_State* L = lua.getState ();
547         luabridge::LuaRef lua_dsp_configure = luabridge::getGlobal (L, "dsp_configure");
548         if (lua_dsp_configure.type () == LUA_TFUNCTION) {
549                 try {
550                         lua_dsp_configure (&in, &out);
551                 } catch (luabridge::LuaException const& e) {
552                         return false;
553                 }
554         }
555
556         _info->n_inputs = _configured_in;
557         _info->n_outputs = _configured_out;
558         return true;
559 }
560
561 int
562 LuaProc::connect_and_run (BufferSet& bufs,
563                 ChanMapping in, ChanMapping out,
564                 pframes_t nframes, framecnt_t offset)
565 {
566         if (!_lua_dsp) {
567                 return 0;
568         }
569
570         Plugin::connect_and_run (bufs, in, out, nframes, offset);
571
572         // This is needed for ARDOUR::Session requests :(
573         if (! SessionEvent::has_per_thread_pool ()) {
574                 char name[64];
575                 snprintf (name, 64, "Proc-%p", this);
576                 pthread_set_name (name);
577                 SessionEvent::create_per_thread_pool (name, 64);
578                 PBD::notify_event_loops_about_thread_creation (pthread_self(), name, 64);
579         }
580
581         uint32_t const n = parameter_count ();
582         for (uint32_t i = 0; i < n; ++i) {
583                 if (parameter_is_control (i) && parameter_is_input (i)) {
584                         _control_data[i] = _shadow_data[i];
585                 }
586         }
587
588 #ifdef WITH_LUAPROC_STATS
589         int64_t t0 = g_get_monotonic_time ();
590 #endif
591
592         try {
593                 if (_lua_does_channelmapping) {
594                         // run the DSP function
595                         (*_lua_dsp)(&bufs, in, out, nframes, offset);
596                 } else {
597                         // map buffers
598                         BufferSet& silent_bufs  = _session.get_silent_buffers (ChanCount (DataType::AUDIO, 1));
599                         BufferSet& scratch_bufs = _session.get_scratch_buffers (ChanCount (DataType::AUDIO, 1));
600
601                         lua_State* L = lua.getState ();
602                         luabridge::LuaRef in_map (luabridge::newTable (L));
603                         luabridge::LuaRef out_map (luabridge::newTable (L));
604
605                         const uint32_t audio_in = _configured_in.n_audio ();
606                         const uint32_t audio_out = _configured_out.n_audio ();
607                         const uint32_t midi_in = _configured_in.n_midi ();
608
609                         for (uint32_t ap = 0; ap < audio_in; ++ap) {
610                                 bool valid;
611                                 const uint32_t buf_index = in.get(DataType::AUDIO, ap, &valid);
612                                 if (valid) {
613                                         in_map[ap + 1] = bufs.get_audio (buf_index).data (offset);
614                                 } else {
615                                         in_map[ap + 1] = silent_bufs.get_audio (0).data (offset);
616                                 }
617                         }
618                         for (uint32_t ap = 0; ap < audio_out; ++ap) {
619                                 bool valid;
620                                 const uint32_t buf_index = out.get(DataType::AUDIO, ap, &valid);
621                                 if (valid) {
622                                         out_map[ap + 1] = bufs.get_audio (buf_index).data (offset);
623                                 } else {
624                                         out_map[ap + 1] = scratch_bufs.get_audio (0).data (offset);
625                                 }
626                         }
627
628                         luabridge::LuaRef lua_midi_tbl (luabridge::newTable (L));
629                         int e = 1; // > 1 port, we merge events (unsorted)
630                         for (uint32_t mp = 0; mp < midi_in; ++mp) {
631                                 bool valid;
632                                 const uint32_t idx = in.get(DataType::MIDI, mp, &valid);
633                                 if (valid) {
634                                         for (MidiBuffer::iterator m = bufs.get_midi(idx).begin();
635                                                         m != bufs.get_midi(idx).end(); ++m, ++e) {
636                                                 const Evoral::MIDIEvent<framepos_t> ev(*m, false);
637                                                 luabridge::LuaRef lua_midi_data (luabridge::newTable (L));
638                                                 const uint8_t* data = ev.buffer();
639                                                 for (uint32_t i = 0; i < ev.size(); ++i) {
640                                                         lua_midi_data [i + 1] = data[i];
641                                                 }
642                                                 luabridge::LuaRef lua_midi_event (luabridge::newTable (L));
643                                                 lua_midi_event["time"] = 1 + (*m).time();
644                                                 lua_midi_event["data"] = lua_midi_data;
645                                                 lua_midi_tbl[e] = lua_midi_event;
646                                         }
647                                 }
648                         }
649
650                         if (_has_midi_input) {
651                                 // XXX TODO This needs a better solution than global namespace
652                                 luabridge::push (L, lua_midi_tbl);
653                                 lua_setglobal (L, "mididata");
654                         }
655
656
657                         // run the DSP function
658                         (*_lua_dsp)(in_map, out_map, nframes);
659                 }
660         } catch (luabridge::LuaException const& e) {
661                 PBD::error << "LuaException: " << e.what () << "\n";
662 #ifndef NDEBUG
663                 std::cerr << "LuaException: " << e.what () << "\n";
664 #endif
665                 return -1;
666         }
667 #ifdef WITH_LUAPROC_STATS
668         int64_t t1 = g_get_monotonic_time ();
669 #endif
670         lua.collect_garbage (); // rt-safe, slight *regular* performance overhead
671 #ifdef WITH_LUAPROC_STATS
672         ++_stats_cnt;
673         int64_t t2 = g_get_monotonic_time ();
674         int64_t ela0 = t1 - t0;
675         int64_t ela1 = t2 - t1;
676         if (ela0 > _stats_max[0]) _stats_max[0] = ela0;
677         if (ela1 > _stats_max[1]) _stats_max[1] = ela1;
678         _stats_avg[0] += ela0;
679         _stats_avg[1] += ela1;
680 #endif
681         return 0;
682 }
683
684
685 void
686 LuaProc::add_state (XMLNode* root) const
687 {
688         XMLNode*    child;
689         char        buf[32];
690         LocaleGuard lg(X_("C"));
691
692         gchar* b64 = g_base64_encode ((const guchar*)_script.c_str (), _script.size ());
693         std::string b64s (b64);
694         g_free (b64);
695         XMLNode* script_node = new XMLNode (X_("script"));
696         script_node->add_property (X_("lua"), LUA_VERSION);
697         script_node->add_content (b64s);
698         root->add_child_nocopy (*script_node);
699
700         for (uint32_t i = 0; i < parameter_count(); ++i) {
701                 if (parameter_is_input(i) && parameter_is_control(i)) {
702                         child = new XMLNode("Port");
703                         snprintf(buf, sizeof(buf), "%u", i);
704                         child->add_property("id", std::string(buf));
705                         snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
706                         child->add_property("value", std::string(buf));
707                         root->add_child_nocopy(*child);
708                 }
709         }
710 }
711
712 int
713 LuaProc::set_script_from_state (const XMLNode& node)
714 {
715         XMLNode* child;
716         if (node.name () != state_node_name ()) {
717                 return -1;
718         }
719
720         if ((child = node.child (X_("script"))) != 0) {
721                 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
722                         if (!(*n)->is_content ()) { continue; }
723                         gsize size;
724                         guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
725                         _script = std::string ((const char*)buf, size);
726                         g_free (buf);
727                         if (load_script ()) {
728                                 PBD::error << _("Failed to load Lua script from session state.") << endmsg;
729 #ifndef NDEBUG
730                                 std::cerr << "Failed Lua Script: " << _script << std::endl;
731 #endif
732                                 _script = "";
733                         }
734                         break;
735                 }
736         }
737         if (_script.empty ()) {
738                 PBD::error << _("Session State for LuaProcessor did not include a Lua script.") << endmsg;
739                 return -1;
740         }
741         if (!_lua_dsp) {
742                 PBD::error << _("Invalid/incompatible Lua script found for LuaProcessor.") << endmsg;
743                 return -1;
744         }
745         return 0;
746 }
747
748 int
749 LuaProc::set_state (const XMLNode& node, int version)
750 {
751 #ifndef NO_PLUGIN_STATE
752         XMLNodeList nodes;
753         XMLProperty *prop;
754         XMLNodeConstIterator iter;
755         XMLNode *child;
756         const char *value;
757         const char *port;
758         uint32_t port_id;
759 #endif
760         LocaleGuard lg (X_("C"));
761
762         if (_script.empty ()) {
763                 if (set_script_from_state (node)) {
764                         return -1;
765                 }
766         }
767
768 #ifndef NO_PLUGIN_STATE
769         if (node.name() != state_node_name()) {
770                 error << _("Bad node sent to LuaProc::set_state") << endmsg;
771                 return -1;
772         }
773
774         nodes = node.children ("Port");
775         for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
776                 child = *iter;
777                 if ((prop = child->property("id")) != 0) {
778                         port = prop->value().c_str();
779                 } else {
780                         warning << _("LuaProc: port has no symbol, ignored") << endmsg;
781                         continue;
782                 }
783                 if ((prop = child->property("value")) != 0) {
784                         value = prop->value().c_str();
785                 } else {
786                         warning << _("LuaProc: port has no value, ignored") << endmsg;
787                         continue;
788                 }
789                 sscanf (port, "%" PRIu32, &port_id);
790                 set_parameter (port_id, atof(value));
791         }
792 #endif
793
794         return Plugin::set_state (node, version);
795 }
796
797 uint32_t
798 LuaProc::parameter_count () const
799 {
800         return _ctrl_params.size ();
801 }
802
803 float
804 LuaProc::default_value (uint32_t port)
805 {
806         if (_ctrl_params[port].first) {
807                 assert (0);
808                 return 0;
809         }
810         int lp = _ctrl_params[port].second;
811         return _param_desc[lp].normal;
812 }
813
814 void
815 LuaProc::set_parameter (uint32_t port, float val)
816 {
817         assert (port < parameter_count ());
818         if (get_parameter (port) == val) {
819                 return;
820         }
821         _shadow_data[port] = val;
822         Plugin::set_parameter (port, val);
823 }
824
825 float
826 LuaProc::get_parameter (uint32_t port) const
827 {
828         if (parameter_is_input (port)) {
829                 return _shadow_data[port];
830         } else {
831                 return _control_data[port];
832         }
833 }
834
835 int
836 LuaProc::get_parameter_descriptor (uint32_t port, ParameterDescriptor& desc) const
837 {
838         assert (port <= parameter_count ());
839         int lp = _ctrl_params[port].second;
840         const ParameterDescriptor& d (_param_desc.find(lp)->second);
841
842         desc.lower        = d.lower;
843         desc.upper        = d.upper;
844         desc.normal       = d.normal;
845         desc.toggled      = d.toggled;
846         desc.logarithmic  = d.logarithmic;
847         desc.integer_step = d.integer_step;
848         desc.sr_dependent = d.sr_dependent;
849         desc.enumeration  = d.enumeration;
850         desc.unit         = d.unit;
851         desc.label        = d.label;
852         desc.scale_points = d.scale_points;
853
854         desc.update_steps ();
855         return 0;
856 }
857
858 std::string
859 LuaProc::get_parameter_docs (uint32_t port) const {
860         assert (port <= parameter_count ());
861         int lp = _ctrl_params[port].second;
862         return _param_doc.find(lp)->second;
863 }
864
865 uint32_t
866 LuaProc::nth_parameter (uint32_t port, bool& ok) const
867 {
868         if (port < _ctrl_params.size ()) {
869                 ok = true;
870                 return port;
871         }
872         ok = false;
873         return 0;
874 }
875
876 bool
877 LuaProc::parameter_is_input (uint32_t port) const
878 {
879         assert (port < _ctrl_params.size ());
880         return (!_ctrl_params[port].first);
881 }
882
883 bool
884 LuaProc::parameter_is_output (uint32_t port) const
885 {
886         assert (port < _ctrl_params.size ());
887         return (_ctrl_params[port].first);
888 }
889
890 std::set<Evoral::Parameter>
891 LuaProc::automatable () const
892 {
893         std::set<Evoral::Parameter> automatables;
894         for (uint32_t i = 0; i < _ctrl_params.size (); ++i) {
895                 if (parameter_is_input (i)) {
896                         automatables.insert (automatables.end (), Evoral::Parameter (PluginAutomation, 0, i));
897                 }
898         }
899         return automatables;
900 }
901
902 std::string
903 LuaProc::describe_parameter (Evoral::Parameter param)
904 {
905         if (param.type () == PluginAutomation && param.id () < parameter_count ()) {
906                 int lp = _ctrl_params[param.id ()].second;
907                 return _param_desc[lp].label;
908         }
909         return "??";
910 }
911
912 void
913 LuaProc::print_parameter (uint32_t param, char* buf, uint32_t len) const
914 {
915         if (buf && len) {
916                 if (param < parameter_count ()) {
917                         snprintf (buf, len, "%.3f", get_parameter (param));
918                 } else {
919                         strcat (buf, "0");
920                 }
921         }
922 }
923
924 boost::shared_ptr<ScalePoints>
925 LuaProc::parse_scale_points (luabridge::LuaRef* lr)
926 {
927         if (!(*lr)["scalepoints"].isTable()) {
928                 return boost::shared_ptr<ScalePoints> ();
929         }
930
931         int cnt = 0;
932         boost::shared_ptr<ScalePoints> rv = boost::shared_ptr<ScalePoints>(new ScalePoints());
933         luabridge::LuaRef scalepoints ((*lr)["scalepoints"]);
934
935         for (luabridge::Iterator i (scalepoints); !i.isNil (); ++i) {
936                 if (!i.key ().isString ())    { continue; }
937                 if (!i.value ().isNumber ())  { continue; }
938                 rv->insert(make_pair(i.key ().cast<std::string> (),
939                                         i.value ().cast<float> ()));
940                 ++cnt;
941         }
942
943         if (rv->size() > 0) {
944                 return rv;
945         }
946         return boost::shared_ptr<ScalePoints> ();
947 }
948
949 boost::shared_ptr<ScalePoints>
950 LuaProc::get_scale_points (uint32_t port) const
951 {
952         int lp = _ctrl_params[port].second;
953         return _param_desc.find(lp)->second.scale_points;
954 }
955
956 void
957 LuaProc::setup_lua_inline_gui (LuaState *lua_gui)
958 {
959         lua_State* LG = lua_gui->getState ();
960         LuaBindings::stddef (LG);
961         LuaBindings::common (LG);
962         LuaBindings::dsp (LG);
963
964         lua_gui->Print.connect (sigc::mem_fun (*this, &LuaProc::lua_print));
965         lua_gui->do_command ("function ardour () end");
966         lua_gui->do_command (_script);
967
968         // TODO think: use a weak-pointer here ?
969         // (the GUI itself uses a shared ptr to this plugin, so we should be good)
970         luabridge::getGlobalNamespace (LG)
971                 .beginNamespace ("Ardour")
972                 .beginClass <LuaProc> ("LuaProc")
973                 .addFunction ("shmem", &LuaProc::instance_shm)
974                 .endClass ()
975                 .endNamespace ();
976
977         luabridge::push <LuaProc *> (LG, this);
978         lua_setglobal (LG, "self");
979
980         luabridge::push <float *> (LG, _shadow_data);
981         lua_setglobal (LG, "CtrlPorts");
982 }
983
984 ////////////////////////////////////////////////////////////////////////////////
985 #include <glibmm/miscutils.h>
986 #include <glibmm/fileutils.h>
987
988 LuaPluginInfo::LuaPluginInfo (LuaScriptInfoPtr lsi) {
989         if (lsi->type != LuaScriptInfo::DSP) {
990                 throw failed_constructor ();
991         }
992
993         path = lsi->path;
994         name = lsi->name;
995         creator = lsi->author;
996         category = lsi->category;
997         unique_id = "luascript"; // the interpreter is not unique.
998
999         n_inputs.set (DataType::AUDIO, 1);
1000         n_outputs.set (DataType::AUDIO, 1);
1001         type = Lua;
1002 }
1003
1004 PluginPtr
1005 LuaPluginInfo::load (Session& session)
1006 {
1007         std::string script = "";
1008         if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
1009                 return PluginPtr ();
1010         }
1011
1012         try {
1013                 script = Glib::file_get_contents (path);
1014         } catch (Glib::FileError err) {
1015                 return PluginPtr ();
1016         }
1017
1018         if (script.empty ()) {
1019                 return PluginPtr ();
1020         }
1021
1022         try {
1023                 PluginPtr plugin (new LuaProc (session.engine (), session, script));
1024                 return plugin;
1025         } catch (failed_constructor& err) {
1026                 ;
1027         }
1028         return PluginPtr ();
1029 }
1030
1031 std::vector<Plugin::PresetRecord>
1032 LuaPluginInfo::get_presets (bool /*user_only*/) const
1033 {
1034         std::vector<Plugin::PresetRecord> p;
1035         return p;
1036 }