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