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