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