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