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