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