26442aa32e45a8affe7f87b40f13c4d6926e5d79
[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 <glibmm/miscutils.h>
22 #include <glibmm/fileutils.h>
23
24 #include "pbd/gstdio_compat.h"
25
26 #include "pbd/pthread_utils.h"
27
28 #include "ardour/audio_buffer.h"
29 #include "ardour/buffer_set.h"
30 #include "ardour/filesystem_paths.h"
31 #include "ardour/luabindings.h"
32 #include "ardour/luaproc.h"
33 #include "ardour/luascripting.h"
34 #include "ardour/midi_buffer.h"
35 #include "ardour/plugin.h"
36 #include "ardour/session.h"
37
38 #include "LuaBridge/LuaBridge.h"
39
40 #include "i18n.h"
41
42 using namespace ARDOUR;
43 using namespace PBD;
44
45 LuaProc::LuaProc (AudioEngine& engine,
46                   Session& session,
47                   const std::string &script)
48         : Plugin (engine, session)
49         , _mempool ("LuaProc", 2097152)
50         , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
51         , _lua_dsp (0)
52         , _script (script)
53         , _lua_does_channelmapping (false)
54         , _lua_has_inline_display (false)
55         , _control_data (0)
56         , _shadow_data (0)
57         , _has_midi_input (false)
58         , _has_midi_output (false)
59 {
60         init ();
61
62         /* when loading a session, or pasing a processor,
63          * the script is set during set_state();
64          */
65         if (!_script.empty () && load_script ()) {
66                 throw failed_constructor ();
67         }
68 }
69
70 LuaProc::LuaProc (const LuaProc &other)
71         : Plugin (other)
72         , _mempool ("LuaProc", 2097152)
73         , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
74         , _lua_dsp (0)
75         , _script (other.script ())
76         , _lua_does_channelmapping (false)
77         , _lua_has_inline_display (false)
78         , _control_data (0)
79         , _shadow_data (0)
80         , _has_midi_input (false)
81         , _has_midi_output (false)
82 {
83         init ();
84
85         if (load_script ()) {
86                 throw failed_constructor ();
87         }
88
89         for (uint32_t i = 0; i < parameter_count (); ++i) {
90                 _control_data[i] = other._shadow_data[i];
91                 _shadow_data[i]  = other._shadow_data[i];
92         }
93 }
94
95 LuaProc::~LuaProc () {
96 #ifdef WITH_LUAPROC_STATS
97         if (_info && _stats_cnt > 0) {
98                 printf ("LuaProc: '%s' run()  avg: %.3f  max: %.3f [ms]\n",
99                                 _info->name.c_str (),
100                                 0.0001f * _stats_avg[0] / (float) _stats_cnt,
101                                 0.0001f * _stats_max[0]);
102                 printf ("LuaProc: '%s' gc()   avg: %.3f  max: %.3f [ms]\n",
103                                 _info->name.c_str (),
104                                 0.0001f * _stats_avg[1] / (float) _stats_cnt,
105                                 0.0001f * _stats_max[1]);
106         }
107 #endif
108         lua.do_command ("collectgarbage();");
109         delete (_lua_dsp);
110         delete [] _control_data;
111         delete [] _shadow_data;
112 }
113
114 void
115 LuaProc::init ()
116 {
117 #ifdef WITH_LUAPROC_STATS
118         _stats_avg[0] = _stats_avg[1] = _stats_max[0] = _stats_max[1] = _stats_cnt = 0;
119 #endif
120
121         lua.tweak_rt_gc ();
122         lua.Print.connect (sigc::mem_fun (*this, &LuaProc::lua_print));
123         // register session object
124         lua_State* L = lua.getState ();
125         LuaBindings::stddef (L);
126         LuaBindings::common (L);
127         LuaBindings::dsp (L);
128
129         luabridge::getGlobalNamespace (L)
130                 .beginNamespace ("Ardour")
131                 .beginClass <LuaProc> ("LuaProc")
132                 .addFunction ("queue_draw", &LuaProc::queue_draw)
133                 .addFunction ("shmem", &LuaProc::instance_shm)
134                 .addFunction ("table", &LuaProc::instance_ref)
135                 .endClass ()
136                 .endNamespace ();
137
138         // add session to global lua namespace
139         luabridge::push <Session *> (L, &_session);
140         lua_setglobal (L, "Session");
141
142         // instance
143         luabridge::push <LuaProc *> (L, this);
144         lua_setglobal (L, "self");
145
146         // sandbox
147         lua.do_command ("io = nil os = nil loadfile = nil require = nil dofile = nil package = nil debug = nil");
148 #if 0
149         lua.do_command ("for n in pairs(_G) do print(n) end print ('----')"); // print global env
150 #endif
151         lua.do_command ("function ardour () end");
152 }
153
154 void
155 LuaProc::lua_print (std::string s) {
156         std::cout <<"LuaProc: " << s << "\n";
157         PBD::error << "LuaProc: " << s << "\n";
158 }
159
160 bool
161 LuaProc::load_script ()
162 {
163         assert (!_lua_dsp); // don't allow to re-initialize
164         LuaPluginInfoPtr lpi;
165
166         // TODO: refine APIs; function arguments..
167         // - perform channel-map in ardour (silent/scratch buffers) ?
168         // - control-port API (explicit get/set functions ??)
169         // - latency reporting (global var? ctrl-port? set-function ?)
170         // - MIDI -> sparse table of events
171         //     { [sample] => { Event }, .. }
172         //   or  { { sample, Event }, .. }
173
174         try {
175                 LuaScriptInfoPtr lsi = LuaScripting::script_info (_script);
176                 lpi = LuaPluginInfoPtr (new LuaPluginInfo (lsi));
177                 assert (lpi);
178                 set_info (lpi);
179                 _mempool.set_name ("LuaProc: " + lsi->name);
180                 _docs = lsi->description;
181         } catch (failed_constructor& err) {
182                 return true;
183         }
184
185         lua_State* L = lua.getState ();
186         lua.do_command (_script);
187
188         // check if script has a DSP callback
189         luabridge::LuaRef lua_dsp_run = luabridge::getGlobal (L, "dsp_run");
190         luabridge::LuaRef lua_dsp_map = luabridge::getGlobal (L, "dsp_runmap");
191
192         if ((lua_dsp_run.type () != LUA_TFUNCTION) == (lua_dsp_map.type () != LUA_TFUNCTION)) {
193                 return true;
194         }
195
196         if (lua_dsp_run.type () == LUA_TFUNCTION) {
197                 _lua_dsp = new luabridge::LuaRef (lua_dsp_run);
198         }
199         else if (lua_dsp_map.type () == LUA_TFUNCTION) {
200                 _lua_dsp = new luabridge::LuaRef (lua_dsp_map);
201                 _lua_does_channelmapping = true;
202         }
203         else {
204                 assert (0);
205         }
206
207         // initialize the DSP if needed
208         luabridge::LuaRef lua_dsp_init = luabridge::getGlobal (L, "dsp_init");
209         if (lua_dsp_init.type () == LUA_TFUNCTION) {
210                 try {
211                         lua_dsp_init (_session.nominal_frame_rate ());
212                 } catch (luabridge::LuaException const& e) {
213                         ;
214                 }
215         }
216
217         // query midi i/o
218         luabridge::LuaRef lua_dsp_has_midi_in = luabridge::getGlobal (L, "dsp_has_midi_input");
219         if (lua_dsp_has_midi_in.type () == LUA_TFUNCTION) {
220                 try {
221                         _has_midi_input = lua_dsp_has_midi_in ();
222                 } catch (luabridge::LuaException const& e) {
223                         ;
224                 }
225         }
226
227         luabridge::LuaRef lua_dsp_has_midi_out = luabridge::getGlobal (L, "dsp_has_midi_output");
228         if (lua_dsp_has_midi_out.type () == LUA_TFUNCTION) {
229                 try {
230                         _has_midi_output = lua_dsp_has_midi_out ();
231                 } catch (luabridge::LuaException const& e) {
232                         ;
233                 }
234         }
235
236         _ctrl_params.clear ();
237
238         luabridge::LuaRef lua_render = luabridge::getGlobal (L, "render_inline");
239         if (lua_render.isFunction ()) {
240                 _lua_has_inline_display = true;
241         }
242
243         luabridge::LuaRef lua_params = luabridge::getGlobal (L, "dsp_params");
244         if (lua_params.isFunction ()) {
245
246                 // call function // add try {} catch (luabridge::LuaException const& e)
247                 luabridge::LuaRef params = lua_params ();
248
249                 if (params.isTable ()) {
250
251                         for (luabridge::Iterator i (params); !i.isNil (); ++i) {
252                                 // required fields
253                                 if (!i.key ().isNumber ())           { return false; }
254                                 if (!i.value ().isTable ())          { return false; }
255                                 if (!i.value ()["type"].isString ()) { return false; }
256                                 if (!i.value ()["name"].isString ()) { return false; }
257                                 if (!i.value ()["min"].isNumber ())  { return false; }
258                                 if (!i.value ()["max"].isNumber ())  { return false; }
259
260                                 int pn = i.key ().cast<int> ();
261                                 std::string type = i.value ()["type"].cast<std::string> ();
262                                 if (type == "input") {
263                                         if (!i.value ()["default"].isNumber ()) { return false; }
264                                         _ctrl_params.push_back (std::make_pair (false, pn));
265                                 }
266                                 else if (type == "output") {
267                                         _ctrl_params.push_back (std::make_pair (true, pn));
268                                 } else {
269                                         return false;
270                                 }
271                                 assert (pn == (int) _ctrl_params.size ());
272
273                                 //_param_desc[pn] = boost::shared_ptr<ParameterDescriptor> (new ParameterDescriptor());
274                                 luabridge::LuaRef lr = i.value ();
275
276                                 if (type == "input") {
277                                         _param_desc[pn].normal     = lr["default"].cast<float> ();
278                                 } else {
279                                         _param_desc[pn].normal     = lr["min"].cast<float> (); // output-port, no default
280                                 }
281                                 _param_desc[pn].lower        = lr["min"].cast<float> ();
282                                 _param_desc[pn].upper        = lr["max"].cast<float> ();
283                                 _param_desc[pn].toggled      = lr["toggled"].isBoolean () && (lr["toggled"]).cast<bool> ();
284                                 _param_desc[pn].logarithmic  = lr["logarithmic"].isBoolean () && (lr["logarithmic"]).cast<bool> ();
285                                 _param_desc[pn].integer_step = lr["integer"].isBoolean () && (lr["integer"]).cast<bool> ();
286                                 _param_desc[pn].sr_dependent = lr["ratemult"].isBoolean () && (lr["ratemult"]).cast<bool> ();
287                                 _param_desc[pn].enumeration  = lr["enum"].isBoolean () && (lr["enum"]).cast<bool> ();
288
289                                 if (lr["unit"].isString ()) {
290                                         std::string unit = lr["unit"].cast<std::string> ();
291                                         if (unit == "dB")             { _param_desc[pn].unit = ParameterDescriptor::DB; }
292                                         else if (unit == "Hz")        { _param_desc[pn].unit = ParameterDescriptor::HZ; }
293                                         else if (unit == "Midi Note") { _param_desc[pn].unit = ParameterDescriptor::MIDI_NOTE; }
294                                 }
295                                 _param_desc[pn].label        = (lr["name"]).cast<std::string> ();
296                                 _param_desc[pn].scale_points = parse_scale_points (&lr);
297
298                                 luabridge::LuaRef doc = lr["doc"];
299                                 if (doc.isString ()) {
300                                         _param_doc[pn] = doc.cast<std::string> ();
301                                 } else {
302                                         _param_doc[pn] = "";
303                                 }
304                                 assert (!(_param_desc[pn].toggled && _param_desc[pn].logarithmic));
305                         }
306                 }
307         }
308
309         _control_data = new float[parameter_count ()];
310         _shadow_data  = new float[parameter_count ()];
311
312         for (uint32_t i = 0; i < parameter_count (); ++i) {
313                 if (parameter_is_input (i)) {
314                         _control_data[i] = _shadow_data[i] = default_value (i);
315                 }
316         }
317
318         // expose ctrl-ports to global lua namespace
319         luabridge::push <float *> (L, _control_data);
320         lua_setglobal (L, "CtrlPorts");
321
322         return false; // no error
323 }
324
325 bool
326 LuaProc::can_support_io_configuration (const ChanCount& in, ChanCount& out, ChanCount* imprecise)
327 {
328         // caller must hold process lock (no concurrent calls to interpreter
329         _output_configs.clear ();
330
331         if (in.n_midi() > 0 && !_has_midi_input && !imprecise) {
332                 return false;
333         }
334
335         lua_State* L = lua.getState ();
336         luabridge::LuaRef ioconfig = luabridge::getGlobal (L, "dsp_ioconfig");
337         if (!ioconfig.isFunction ()) {
338                 return false;
339         }
340
341         luabridge::LuaRef *_iotable = NULL; // can't use reference :(
342         try {
343                 luabridge::LuaRef iotable = ioconfig ();
344                 if (iotable.isTable ()) {
345                         _iotable = new luabridge::LuaRef (iotable);
346                 }
347         } catch (luabridge::LuaException const& e) {
348                 return false;
349         }
350
351         if (!_iotable) {
352                 return false;
353         }
354
355         // now we can reference it.
356         luabridge::LuaRef iotable (*_iotable);
357         delete _iotable;
358
359         if ((iotable).length () < 1) {
360                 return false;
361         }
362
363         bool found = false;
364         bool exact_match = false;
365         const int32_t audio_in = in.n_audio ();
366         int32_t midi_out = _has_midi_output ? 1 : 0;
367
368         // preferred setting (provided by plugin_insert)
369         assert (out.n_audio () > 0 || midi_out > 0);
370         const int preferred_out = out.n_audio ();
371
372         for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
373                 assert (i.value ().type () == LUA_TTABLE);
374                 luabridge::LuaRef io (i.value ());
375
376                 int possible_in = io["audio_in"];
377                 int possible_out = io["audio_out"];
378
379                 // exact match
380                 if ((possible_in == audio_in) && (possible_out == preferred_out)) {
381                         _output_configs.insert (preferred_out);
382                         exact_match = true;
383                         found = true;
384                         break;
385                 }
386         }
387
388         /* now allow potentially "imprecise" matches */
389         int32_t audio_out = -1;
390         float penalty = 9999;
391
392 #define FOUNDCFG(nch) {                            \
393   float p = fabsf ((float)(nch) - preferred_out);  \
394   _output_configs.insert (nch);                    \
395   if ((nch) > preferred_out) { p *= 1.1; }         \
396   if (p < penalty) {                               \
397     audio_out = (nch);                             \
398     penalty = p;                                   \
399     found = true;                                  \
400   }                                                \
401 }
402
403 #define ANYTHINGGOES                               \
404   _output_configs.insert (0);
405
406 #define UPTO(nch) {                                \
407   for (int n = 1; n < nch; ++n) {                  \
408     _output_configs.insert (n);                    \
409   }                                                \
410 }
411
412         for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
413                 assert (i.value ().type () == LUA_TTABLE);
414                 luabridge::LuaRef io (i.value ());
415
416                 int possible_in = io["audio_in"];
417                 int possible_out = io["audio_out"];
418
419                 if (possible_out == 0) {
420                         if (possible_in == 0) {
421                                 if (_has_midi_output && audio_in == 0) {
422                                         // special case midi filters & generators
423                                         audio_out = 0;
424                                         found = true;
425                                         break;
426                                 }
427                         }
428                         continue;
429                 }
430
431                 if (possible_in == 0) {
432                         /* no inputs, generators & instruments */
433                         if (possible_out == -1) {
434                                 /* any configuration possible, stereo output */
435                                 FOUNDCFG (preferred_out);
436                                 ANYTHINGGOES;
437                         } else if (possible_out == -2) {
438                                 /* invalid, should be (0, -1) */
439                                 FOUNDCFG (preferred_out);
440                                 ANYTHINGGOES;
441                         } else if (possible_out < -2) {
442                                 /* variable number of outputs up to -N, */
443                                 FOUNDCFG (min (-possible_out, preferred_out));
444                                 UPTO (-possible_out);
445                         } else {
446                                 /* exact number of outputs */
447                                 FOUNDCFG (possible_out);
448                         }
449                 }
450
451                 if (possible_in == -1) {
452                         /* wildcard for input */
453                         if (possible_out == -1) {
454                                 /* out must match in */
455                                 FOUNDCFG (audio_in);
456                         } else if (possible_out == -2) {
457                                 /* any configuration possible, pick matching */
458                                 FOUNDCFG (preferred_out);
459                                 ANYTHINGGOES;
460                         } else if (possible_out < -2) {
461                                 /* explicitly variable number of outputs, pick maximum */
462                                 FOUNDCFG (max (-possible_out, preferred_out));
463                                 /* and try min, too, in case the penalty is lower */
464                                 FOUNDCFG (min (-possible_out, preferred_out));
465                                 UPTO (-possible_out)
466                         } else {
467                                 /* exact number of outputs */
468                                 FOUNDCFG (possible_out);
469                         }
470                 }
471
472                 if (possible_in == -2) {
473                         if (possible_out == -1) {
474                                 /* any configuration possible, pick matching */
475                                 FOUNDCFG (preferred_out);
476                                 ANYTHINGGOES;
477                         } else if (possible_out == -2) {
478                                 /* invalid. interpret as (-1, -1) */
479                                 FOUNDCFG (preferred_out);
480                                 ANYTHINGGOES;
481                         } else if (possible_out < -2) {
482                                 /* invalid,  interpret as (<-2, <-2)
483                                  * variable number of outputs up to -N, */
484                                 FOUNDCFG (min (-possible_out, preferred_out));
485                                 UPTO (-possible_out)
486                         } else {
487                                 /* exact number of outputs */
488                                 FOUNDCFG (possible_out);
489                         }
490                 }
491
492                 if (possible_in < -2) {
493                         /* explicit variable number of inputs */
494                         if (audio_in > -possible_in && imprecise != NULL) {
495                                 // hide inputs ports
496                                 imprecise->set (DataType::AUDIO, -possible_in);
497                         }
498
499                         if (audio_in > -possible_in && imprecise == NULL) {
500                                 /* request is too large */
501                         } else if (possible_out == -1) {
502                                 /* any output configuration possible */
503                                 FOUNDCFG (preferred_out);
504                                 ANYTHINGGOES;
505                         } else if (possible_out == -2) {
506                                 /* invalid. interpret as (<-2, -1) */
507                                 FOUNDCFG (preferred_out);
508                                 ANYTHINGGOES;
509                         } else if (possible_out < -2) {
510                                 /* variable number of outputs up to -N, */
511                                 FOUNDCFG (min (-possible_out, preferred_out));
512                                 UPTO (-possible_out)
513                         } else {
514                                 /* exact number of outputs */
515                                 FOUNDCFG (possible_out);
516                         }
517                 }
518
519                 if (possible_in && (possible_in == audio_in)) {
520                         /* exact number of inputs ... must match obviously */
521                         if (possible_out == -1) {
522                                 /* any output configuration possible */
523                                 FOUNDCFG (preferred_out);
524                                 ANYTHINGGOES;
525                         } else if (possible_out == -2) {
526                                 /* invalid. interpret as (>0, -1) */
527                                 FOUNDCFG (preferred_out);
528                                 ANYTHINGGOES;
529                         } else if (possible_out < -2) {
530                                 /* > 0, < -2 is not specified
531                                  * interpret as up to -N */
532                                 FOUNDCFG (min (-possible_out, preferred_out));
533                                 UPTO (-possible_out)
534                         } else {
535                                 /* exact number of outputs */
536                                 FOUNDCFG (possible_out);
537                         }
538                 }
539         }
540
541         if (!found && imprecise) {
542                 /* try harder */
543                 for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
544                         assert (i.value ().type () == LUA_TTABLE);
545                         luabridge::LuaRef io (i.value ());
546
547                         int possible_in = io["audio_in"];
548                         int possible_out = io["audio_out"];
549
550                         if (possible_out == 0 && possible_in == 0 && _has_midi_output) {
551                                 assert (audio_in > 0); // no input is handled above
552                                 // TODO hide audio input from plugin
553                                 imprecise->set (DataType::AUDIO, 0);
554                                 audio_out = 0;
555                                 found = true;
556                                 continue;
557                         }
558
559                         assert (possible_in > 0); // all other cases will have been matched above
560                         assert (possible_out !=0 || possible_in !=0); // already handled above
561
562                         imprecise->set (DataType::AUDIO, possible_in);
563                         if (possible_out == -1 || possible_out == -2) {
564                                 FOUNDCFG (2);
565                         } else if (possible_out < -2) {
566                                 /* explicitly variable number of outputs, pick maximum */
567                                 FOUNDCFG (min (-possible_out, preferred_out));
568                         } else {
569                                 /* exact number of outputs */
570                                 FOUNDCFG (possible_out);
571                         }
572                         // ideally we'll also find the closest, best matching
573                         // input configuration with minimal output penalty...
574                 }
575         }
576
577         if (!found) {
578                 return false;
579         }
580
581         if (exact_match) {
582                 out.set (DataType::MIDI, midi_out);
583                 out.set (DataType::AUDIO, preferred_out);
584         } else {
585                 out.set (DataType::MIDI, midi_out);
586                 out.set (DataType::AUDIO, audio_out);
587         }
588         return true;
589 }
590
591 bool
592 LuaProc::configure_io (ChanCount in, ChanCount out)
593 {
594         in.set (DataType::MIDI, _has_midi_input ? 1 : 0);
595         out.set (DataType::MIDI, _has_midi_output ? 1 : 0);
596
597         // configure the DSP if needed
598         if (in != _configured_in || out != _configured_out) {
599                 lua_State* L = lua.getState ();
600                 luabridge::LuaRef lua_dsp_configure = luabridge::getGlobal (L, "dsp_configure");
601                 if (lua_dsp_configure.type () == LUA_TFUNCTION) {
602                         try {
603                                 lua_dsp_configure (&in, &out);
604                         } catch (luabridge::LuaException const& e) {
605                                 PBD::error << "LuaException: " << e.what () << "\n";
606 #ifndef NDEBUG
607                                 std::cerr << "LuaException: " << e.what () << "\n";
608 #endif
609                                 return false;
610                         }
611                 }
612         }
613
614         _configured_in = in;
615         _configured_out = out;
616
617         _info->n_inputs = _configured_in;
618         _info->n_outputs = _configured_out;
619         return true;
620 }
621
622 int
623 LuaProc::connect_and_run (BufferSet& bufs,
624                 framepos_t start, framepos_t end, double speed,
625                 ChanMapping in, ChanMapping out,
626                 pframes_t nframes, framecnt_t offset)
627 {
628         if (!_lua_dsp) {
629                 return 0;
630         }
631
632         Plugin::connect_and_run (bufs, start, end, speed, in, out, nframes, offset);
633
634         // This is needed for ARDOUR::Session requests :(
635         if (! SessionEvent::has_per_thread_pool ()) {
636                 char name[64];
637                 snprintf (name, 64, "Proc-%p", this);
638                 pthread_set_name (name);
639                 SessionEvent::create_per_thread_pool (name, 64);
640                 PBD::notify_event_loops_about_thread_creation (pthread_self(), name, 64);
641         }
642
643         uint32_t const n = parameter_count ();
644         for (uint32_t i = 0; i < n; ++i) {
645                 if (parameter_is_control (i) && parameter_is_input (i)) {
646                         _control_data[i] = _shadow_data[i];
647                 }
648         }
649
650 #ifdef WITH_LUAPROC_STATS
651         int64_t t0 = g_get_monotonic_time ();
652 #endif
653
654         try {
655                 if (_lua_does_channelmapping) {
656                         // run the DSP function
657                         (*_lua_dsp)(&bufs, in, out, nframes, offset);
658                 } else {
659                         // map buffers
660                         BufferSet& silent_bufs  = _session.get_silent_buffers (ChanCount (DataType::AUDIO, 1));
661                         BufferSet& scratch_bufs = _session.get_scratch_buffers (ChanCount (DataType::AUDIO, 1));
662
663                         lua_State* L = lua.getState ();
664                         luabridge::LuaRef in_map (luabridge::newTable (L));
665                         luabridge::LuaRef out_map (luabridge::newTable (L));
666
667                         const uint32_t audio_in = _configured_in.n_audio ();
668                         const uint32_t audio_out = _configured_out.n_audio ();
669                         const uint32_t midi_in = _configured_in.n_midi ();
670
671                         for (uint32_t ap = 0; ap < audio_in; ++ap) {
672                                 bool valid;
673                                 const uint32_t buf_index = in.get(DataType::AUDIO, ap, &valid);
674                                 if (valid) {
675                                         in_map[ap + 1] = bufs.get_audio (buf_index).data (offset);
676                                 } else {
677                                         in_map[ap + 1] = silent_bufs.get_audio (0).data (offset);
678                                 }
679                         }
680                         for (uint32_t ap = 0; ap < audio_out; ++ap) {
681                                 bool valid;
682                                 const uint32_t buf_index = out.get(DataType::AUDIO, ap, &valid);
683                                 if (valid) {
684                                         out_map[ap + 1] = bufs.get_audio (buf_index).data (offset);
685                                 } else {
686                                         out_map[ap + 1] = scratch_bufs.get_audio (0).data (offset);
687                                 }
688                         }
689
690                         luabridge::LuaRef lua_midi_src_tbl (luabridge::newTable (L));
691                         int e = 1; // > 1 port, we merge events (unsorted)
692                         for (uint32_t mp = 0; mp < midi_in; ++mp) {
693                                 bool valid;
694                                 const uint32_t idx = in.get(DataType::MIDI, mp, &valid);
695                                 if (valid) {
696                                         for (MidiBuffer::iterator m = bufs.get_midi(idx).begin();
697                                                         m != bufs.get_midi(idx).end(); ++m, ++e) {
698                                                 const Evoral::MIDIEvent<framepos_t> ev(*m, false);
699                                                 luabridge::LuaRef lua_midi_data (luabridge::newTable (L));
700                                                 const uint8_t* data = ev.buffer();
701                                                 for (uint32_t i = 0; i < ev.size(); ++i) {
702                                                         lua_midi_data [i + 1] = data[i];
703                                                 }
704                                                 luabridge::LuaRef lua_midi_event (luabridge::newTable (L));
705                                                 lua_midi_event["time"] = 1 + (*m).time();
706                                                 lua_midi_event["data"] = lua_midi_data;
707                                                 lua_midi_src_tbl[e] = lua_midi_event;
708                                         }
709                                 }
710                         }
711
712                         if (_has_midi_input) {
713                                 // XXX TODO This needs a better solution than global namespace
714                                 luabridge::push (L, lua_midi_src_tbl);
715                                 lua_setglobal (L, "midiin");
716                         }
717
718                         luabridge::LuaRef lua_midi_sink_tbl (luabridge::newTable (L));
719                         if (_has_midi_output) {
720                                 luabridge::push (L, lua_midi_sink_tbl);
721                                 lua_setglobal (L, "midiout");
722                         }
723
724                         // run the DSP function
725                         (*_lua_dsp)(in_map, out_map, nframes);
726
727                         // copy back midi events
728                         if (_has_midi_output && lua_midi_sink_tbl.isTable ()) {
729                                 bool valid;
730                                 const uint32_t idx = out.get(DataType::MIDI, 0, &valid);
731                                 if (valid && bufs.count().n_midi() > idx) {
732                                         MidiBuffer& mbuf = bufs.get_midi(idx);
733                                         mbuf.silence(0, 0);
734                                         for (luabridge::Iterator i (lua_midi_sink_tbl); !i.isNil (); ++i) {
735                                                 if (!i.key ().isNumber ()) { continue; }
736                                                 if (!i.value ()["time"].isNumber ()) { continue; }
737                                                 if (!i.value ()["data"].isTable ()) { continue; }
738                                                 luabridge::LuaRef data_tbl (i.value ()["data"]);
739                                                 framepos_t tme = i.value ()["time"];
740                                                 if (tme < 1 || tme > nframes) { continue; }
741                                                 uint8_t data[64];
742                                                 size_t size = 0;
743                                                 for (luabridge::Iterator di (data_tbl); !di.isNil () && size < sizeof(data); ++di, ++size) {
744                                                         data[size] = di.value ();
745                                                 }
746                                                 if (size > 0 && size < 64) {
747                                                         mbuf.push_back(tme - 1, size, data);
748                                                 }
749                                         }
750
751                                 }
752                         }
753                 }
754         } catch (luabridge::LuaException const& e) {
755                 PBD::error << "LuaException: " << e.what () << "\n";
756 #ifndef NDEBUG
757                 std::cerr << "LuaException: " << e.what () << "\n";
758 #endif
759                 return -1;
760         }
761 #ifdef WITH_LUAPROC_STATS
762         int64_t t1 = g_get_monotonic_time ();
763 #endif
764
765         lua.collect_garbage_step ();
766 #ifdef WITH_LUAPROC_STATS
767         ++_stats_cnt;
768         int64_t t2 = g_get_monotonic_time ();
769         int64_t ela0 = t1 - t0;
770         int64_t ela1 = t2 - t1;
771         if (ela0 > _stats_max[0]) _stats_max[0] = ela0;
772         if (ela1 > _stats_max[1]) _stats_max[1] = ela1;
773         _stats_avg[0] += ela0;
774         _stats_avg[1] += ela1;
775 #endif
776         return 0;
777 }
778
779
780 void
781 LuaProc::add_state (XMLNode* root) const
782 {
783         XMLNode*    child;
784         char        buf[32];
785         LocaleGuard lg;
786
787         gchar* b64 = g_base64_encode ((const guchar*)_script.c_str (), _script.size ());
788         std::string b64s (b64);
789         g_free (b64);
790         XMLNode* script_node = new XMLNode (X_("script"));
791         script_node->add_property (X_("lua"), LUA_VERSION);
792         script_node->add_content (b64s);
793         root->add_child_nocopy (*script_node);
794
795         for (uint32_t i = 0; i < parameter_count(); ++i) {
796                 if (parameter_is_input(i) && parameter_is_control(i)) {
797                         child = new XMLNode("Port");
798                         snprintf(buf, sizeof(buf), "%u", i);
799                         child->add_property("id", std::string(buf));
800                         snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
801                         child->add_property("value", std::string(buf));
802                         root->add_child_nocopy(*child);
803                 }
804         }
805 }
806
807 int
808 LuaProc::set_script_from_state (const XMLNode& node)
809 {
810         XMLNode* child;
811         if (node.name () != state_node_name ()) {
812                 return -1;
813         }
814
815         if ((child = node.child (X_("script"))) != 0) {
816                 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
817                         if (!(*n)->is_content ()) { continue; }
818                         gsize size;
819                         guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
820                         _script = std::string ((const char*)buf, size);
821                         g_free (buf);
822                         if (load_script ()) {
823                                 PBD::error << _("Failed to load Lua script from session state.") << endmsg;
824 #ifndef NDEBUG
825                                 std::cerr << "Failed Lua Script: " << _script << std::endl;
826 #endif
827                                 _script = "";
828                         }
829                         break;
830                 }
831         }
832         if (_script.empty ()) {
833                 PBD::error << _("Session State for LuaProcessor did not include a Lua script.") << endmsg;
834                 return -1;
835         }
836         if (!_lua_dsp) {
837                 PBD::error << _("Invalid/incompatible Lua script found for LuaProcessor.") << endmsg;
838                 return -1;
839         }
840         return 0;
841 }
842
843 int
844 LuaProc::set_state (const XMLNode& node, int version)
845 {
846 #ifndef NO_PLUGIN_STATE
847         XMLNodeList nodes;
848         XMLProperty const * prop;
849         XMLNodeConstIterator iter;
850         XMLNode *child;
851         const char *value;
852         const char *port;
853         uint32_t port_id;
854 #endif
855         LocaleGuard lg;
856
857         if (_script.empty ()) {
858                 if (set_script_from_state (node)) {
859                         return -1;
860                 }
861         }
862
863 #ifndef NO_PLUGIN_STATE
864         if (node.name() != state_node_name()) {
865                 error << _("Bad node sent to LuaProc::set_state") << endmsg;
866                 return -1;
867         }
868
869         nodes = node.children ("Port");
870         for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
871                 child = *iter;
872                 if ((prop = child->property("id")) != 0) {
873                         port = prop->value().c_str();
874                 } else {
875                         warning << _("LuaProc: port has no symbol, ignored") << endmsg;
876                         continue;
877                 }
878                 if ((prop = child->property("value")) != 0) {
879                         value = prop->value().c_str();
880                 } else {
881                         warning << _("LuaProc: port has no value, ignored") << endmsg;
882                         continue;
883                 }
884                 sscanf (port, "%" PRIu32, &port_id);
885                 set_parameter (port_id, atof(value));
886         }
887 #endif
888
889         return Plugin::set_state (node, version);
890 }
891
892 uint32_t
893 LuaProc::parameter_count () const
894 {
895         return _ctrl_params.size ();
896 }
897
898 float
899 LuaProc::default_value (uint32_t port)
900 {
901         if (_ctrl_params[port].first) {
902                 assert (0);
903                 return 0;
904         }
905         int lp = _ctrl_params[port].second;
906         return _param_desc[lp].normal;
907 }
908
909 void
910 LuaProc::set_parameter (uint32_t port, float val)
911 {
912         assert (port < parameter_count ());
913         if (get_parameter (port) == val) {
914                 return;
915         }
916         _shadow_data[port] = val;
917         Plugin::set_parameter (port, val);
918 }
919
920 float
921 LuaProc::get_parameter (uint32_t port) const
922 {
923         if (parameter_is_input (port)) {
924                 return _shadow_data[port];
925         } else {
926                 return _control_data[port];
927         }
928 }
929
930 int
931 LuaProc::get_parameter_descriptor (uint32_t port, ParameterDescriptor& desc) const
932 {
933         assert (port <= parameter_count ());
934         int lp = _ctrl_params[port].second;
935         const ParameterDescriptor& d (_param_desc.find(lp)->second);
936
937         desc.lower        = d.lower;
938         desc.upper        = d.upper;
939         desc.normal       = d.normal;
940         desc.toggled      = d.toggled;
941         desc.logarithmic  = d.logarithmic;
942         desc.integer_step = d.integer_step;
943         desc.sr_dependent = d.sr_dependent;
944         desc.enumeration  = d.enumeration;
945         desc.unit         = d.unit;
946         desc.label        = d.label;
947         desc.scale_points = d.scale_points;
948
949         desc.update_steps ();
950         return 0;
951 }
952
953 std::string
954 LuaProc::get_parameter_docs (uint32_t port) const {
955         assert (port <= parameter_count ());
956         int lp = _ctrl_params[port].second;
957         return _param_doc.find(lp)->second;
958 }
959
960 uint32_t
961 LuaProc::nth_parameter (uint32_t port, bool& ok) const
962 {
963         if (port < _ctrl_params.size ()) {
964                 ok = true;
965                 return port;
966         }
967         ok = false;
968         return 0;
969 }
970
971 bool
972 LuaProc::parameter_is_input (uint32_t port) const
973 {
974         assert (port < _ctrl_params.size ());
975         return (!_ctrl_params[port].first);
976 }
977
978 bool
979 LuaProc::parameter_is_output (uint32_t port) const
980 {
981         assert (port < _ctrl_params.size ());
982         return (_ctrl_params[port].first);
983 }
984
985 std::set<Evoral::Parameter>
986 LuaProc::automatable () const
987 {
988         std::set<Evoral::Parameter> automatables;
989         for (uint32_t i = 0; i < _ctrl_params.size (); ++i) {
990                 if (parameter_is_input (i)) {
991                         automatables.insert (automatables.end (), Evoral::Parameter (PluginAutomation, 0, i));
992                 }
993         }
994         return automatables;
995 }
996
997 std::string
998 LuaProc::describe_parameter (Evoral::Parameter param)
999 {
1000         if (param.type () == PluginAutomation && param.id () < parameter_count ()) {
1001                 int lp = _ctrl_params[param.id ()].second;
1002                 return _param_desc[lp].label;
1003         }
1004         return "??";
1005 }
1006
1007 void
1008 LuaProc::print_parameter (uint32_t param, char* buf, uint32_t len) const
1009 {
1010         if (buf && len) {
1011                 if (param < parameter_count ()) {
1012                         snprintf (buf, len, "%.3f", get_parameter (param));
1013                 } else {
1014                         strcat (buf, "0");
1015                 }
1016         }
1017 }
1018
1019 boost::shared_ptr<ScalePoints>
1020 LuaProc::parse_scale_points (luabridge::LuaRef* lr)
1021 {
1022         if (!(*lr)["scalepoints"].isTable()) {
1023                 return boost::shared_ptr<ScalePoints> ();
1024         }
1025
1026         int cnt = 0;
1027         boost::shared_ptr<ScalePoints> rv = boost::shared_ptr<ScalePoints>(new ScalePoints());
1028         luabridge::LuaRef scalepoints ((*lr)["scalepoints"]);
1029
1030         for (luabridge::Iterator i (scalepoints); !i.isNil (); ++i) {
1031                 if (!i.key ().isString ())    { continue; }
1032                 if (!i.value ().isNumber ())  { continue; }
1033                 rv->insert(make_pair(i.key ().cast<std::string> (),
1034                                         i.value ().cast<float> ()));
1035                 ++cnt;
1036         }
1037
1038         if (rv->size() > 0) {
1039                 return rv;
1040         }
1041         return boost::shared_ptr<ScalePoints> ();
1042 }
1043
1044 boost::shared_ptr<ScalePoints>
1045 LuaProc::get_scale_points (uint32_t port) const
1046 {
1047         int lp = _ctrl_params[port].second;
1048         return _param_desc.find(lp)->second.scale_points;
1049 }
1050
1051 void
1052 LuaProc::setup_lua_inline_gui (LuaState *lua_gui)
1053 {
1054         lua_State* LG = lua_gui->getState ();
1055         LuaBindings::stddef (LG);
1056         LuaBindings::common (LG);
1057         LuaBindings::dsp (LG);
1058
1059         lua_gui->Print.connect (sigc::mem_fun (*this, &LuaProc::lua_print));
1060         lua_gui->do_command ("function ardour () end");
1061         lua_gui->do_command (_script);
1062
1063         // TODO think: use a weak-pointer here ?
1064         // (the GUI itself uses a shared ptr to this plugin, so we should be good)
1065         luabridge::getGlobalNamespace (LG)
1066                 .beginNamespace ("Ardour")
1067                 .beginClass <LuaProc> ("LuaProc")
1068                 .addFunction ("shmem", &LuaProc::instance_shm)
1069                 .addFunction ("table", &LuaProc::instance_ref)
1070                 .endClass ()
1071                 .endNamespace ();
1072
1073         luabridge::push <LuaProc *> (LG, this);
1074         lua_setglobal (LG, "self");
1075
1076         luabridge::push <float *> (LG, _shadow_data);
1077         lua_setglobal (LG, "CtrlPorts");
1078 }
1079 ////////////////////////////////////////////////////////////////////////////////
1080
1081 #include "ardour/search_paths.h"
1082 #include "sha1.c"
1083
1084 std::string
1085 LuaProc::preset_name_to_uri (const std::string& name) const
1086 {
1087         std::string uri ("urn:lua:");
1088         char hash[41];
1089         Sha1Digest s;
1090         sha1_init (&s);
1091         sha1_write (&s, (const uint8_t *) name.c_str(), name.size ());
1092         sha1_write (&s, (const uint8_t *) _script.c_str(), _script.size ());
1093         sha1_result_hash (&s, hash);
1094         return uri + hash;
1095 }
1096
1097 std::string
1098 LuaProc::presets_file () const
1099 {
1100         return string_compose ("lua-%1", _info->unique_id);
1101 }
1102
1103 XMLTree*
1104 LuaProc::presets_tree () const
1105 {
1106         XMLTree* t = new XMLTree;
1107         std::string p = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
1108
1109         if (!Glib::file_test (p, Glib::FILE_TEST_IS_DIR)) {
1110                 if (g_mkdir_with_parents (p.c_str(), 0755) != 0) {
1111                         error << _("Unable to create LuaProc presets directory") << endmsg;
1112                 };
1113         }
1114
1115         p = Glib::build_filename (p, presets_file ());
1116
1117         if (!Glib::file_test (p, Glib::FILE_TEST_EXISTS)) {
1118                 t->set_root (new XMLNode (X_("LuaPresets")));
1119                 return t;
1120         }
1121
1122         t->set_filename (p);
1123         if (!t->read ()) {
1124                 delete t;
1125                 return 0;
1126         }
1127         return t;
1128 }
1129
1130 bool
1131 LuaProc::load_preset (PresetRecord r)
1132 {
1133         boost::shared_ptr<XMLTree> t (presets_tree ());
1134         if (t == 0) {
1135                 return false;
1136         }
1137
1138         XMLNode* root = t->root ();
1139         for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
1140                 XMLProperty const * label = (*i)->property (X_("label"));
1141                 assert (label);
1142                 if (label->value() != r.label) {
1143                         continue;
1144                 }
1145
1146                 for (XMLNodeList::const_iterator j = (*i)->children().begin(); j != (*i)->children().end(); ++j) {
1147                         if ((*j)->name() == X_("Parameter")) {
1148                                 XMLProperty const * index = (*j)->property (X_("index"));
1149                                 XMLProperty const * value = (*j)->property (X_("value"));
1150                                 assert (index);
1151                                 assert (value);
1152                                 set_parameter (atoi (index->value().c_str()), atof (value->value().c_str ()));
1153                         }
1154                 }
1155                 return true;
1156         }
1157         return false;
1158 }
1159
1160 std::string
1161 LuaProc::do_save_preset (std::string name) {
1162
1163         boost::shared_ptr<XMLTree> t (presets_tree ());
1164         if (t == 0) {
1165                 return "";
1166         }
1167
1168         std::string uri (preset_name_to_uri (name));
1169
1170         XMLNode* p = new XMLNode (X_("Preset"));
1171         p->add_property (X_("uri"), uri);
1172         p->add_property (X_("label"), name);
1173
1174         for (uint32_t i = 0; i < parameter_count(); ++i) {
1175                 if (parameter_is_input (i)) {
1176                         XMLNode* c = new XMLNode (X_("Parameter"));
1177                         c->add_property (X_("index"), string_compose ("%1", i));
1178                         c->add_property (X_("value"), string_compose ("%1", get_parameter (i)));
1179                         p->add_child_nocopy (*c);
1180                 }
1181         }
1182         t->root()->add_child_nocopy (*p);
1183
1184         std::string f = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
1185         f = Glib::build_filename (f, presets_file ());
1186
1187         t->write (f);
1188         return uri;
1189 }
1190
1191 void
1192 LuaProc::do_remove_preset (std::string name)
1193 {
1194         boost::shared_ptr<XMLTree> t (presets_tree ());
1195         if (t == 0) {
1196                 return;
1197         }
1198         t->root()->remove_nodes_and_delete (X_("label"), name);
1199         std::string f = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
1200         f = Glib::build_filename (f, presets_file ());
1201         t->write (f);
1202 }
1203
1204 void
1205 LuaProc::find_presets ()
1206 {
1207         boost::shared_ptr<XMLTree> t (presets_tree ());
1208         if (t) {
1209                 XMLNode* root = t->root ();
1210                 for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
1211
1212                         XMLProperty const * uri = (*i)->property (X_("uri"));
1213                         XMLProperty const * label = (*i)->property (X_("label"));
1214
1215                         assert (uri);
1216                         assert (label);
1217
1218                         PresetRecord r (uri->value(), label->value(), true);
1219                         _presets.insert (make_pair (r.uri, r));
1220                 }
1221         }
1222 }
1223
1224 ////////////////////////////////////////////////////////////////////////////////
1225
1226 LuaPluginInfo::LuaPluginInfo (LuaScriptInfoPtr lsi) {
1227         if (lsi->type != LuaScriptInfo::DSP) {
1228                 throw failed_constructor ();
1229         }
1230
1231         path = lsi->path;
1232         name = lsi->name;
1233         creator = lsi->author;
1234         category = lsi->category;
1235         unique_id = lsi->unique_id;
1236
1237         n_inputs.set (DataType::AUDIO, 1);
1238         n_outputs.set (DataType::AUDIO, 1);
1239         type = Lua;
1240
1241         _is_instrument = category == "Instrument";
1242 }
1243
1244 PluginPtr
1245 LuaPluginInfo::load (Session& session)
1246 {
1247         std::string script = "";
1248         if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
1249                 return PluginPtr ();
1250         }
1251
1252         try {
1253                 script = Glib::file_get_contents (path);
1254         } catch (Glib::FileError err) {
1255                 return PluginPtr ();
1256         }
1257
1258         if (script.empty ()) {
1259                 return PluginPtr ();
1260         }
1261
1262         try {
1263                 PluginPtr plugin (new LuaProc (session.engine (), session, script));
1264                 return plugin;
1265         } catch (failed_constructor& err) {
1266                 ;
1267         }
1268         return PluginPtr ();
1269 }
1270
1271 std::vector<Plugin::PresetRecord>
1272 LuaPluginInfo::get_presets (bool /*user_only*/) const
1273 {
1274         std::vector<Plugin::PresetRecord> p;
1275         XMLTree* t = new XMLTree;
1276         std::string pf = Glib::build_filename (ARDOUR::user_config_directory (), "presets", string_compose ("lua-%1", unique_id));
1277         if (Glib::file_test (pf, Glib::FILE_TEST_EXISTS)) {
1278                 t->set_filename (pf);
1279                 if (t->read ()) {
1280                         XMLNode* root = t->root ();
1281                         for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
1282                                 XMLProperty const * uri = (*i)->property (X_("uri"));
1283                                 XMLProperty const * label = (*i)->property (X_("label"));
1284                                 p.push_back (Plugin::PresetRecord (uri->value(), label->value(), true));
1285                         }
1286                 }
1287         }
1288         delete t;
1289         return p;
1290 }