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