2 * Copyright (C) 2016-2017 Paul Davis <paul@linuxaudiosystems.com>
3 * Copyright (C) 2016-2019 Robin Gareus <robin@gareus.org>
4 * Copyright (C) 2016 Julien "_FrnchFrgg_" RIVAUD <frnchfrgg@free.fr>
5 * Copyright (C) 2016 Tim Mayberry <mojofunk@gmail.com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include <glibmm/miscutils.h>
24 #include <glibmm/fileutils.h>
26 #include "pbd/gstdio_compat.h"
27 #include "pbd/pthread_utils.h"
29 #include "ardour/audio_buffer.h"
30 #include "ardour/buffer_set.h"
31 #include "ardour/filesystem_paths.h"
32 #include "ardour/luabindings.h"
33 #include "ardour/luaproc.h"
34 #include "ardour/luascripting.h"
35 #include "ardour/midi_buffer.h"
36 #include "ardour/plugin.h"
37 #include "ardour/session.h"
39 #include "LuaBridge/LuaBridge.h"
43 using namespace ARDOUR;
46 LuaProc::LuaProc (AudioEngine& engine,
48 const std::string &script)
49 : Plugin (engine, session)
50 , _mempool ("LuaProc", 3145728)
52 , lua (lua_newstate (&PBD::TLSF::lalloc, &_mempool))
53 #elif defined USE_MALLOC
56 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
61 , _lua_does_channelmapping (false)
62 , _lua_has_inline_display (false)
63 , _designated_bypass_port (UINT32_MAX)
68 , _has_midi_input (false)
69 , _has_midi_output (false)
73 /* when loading a session, or pasing a processor,
74 * the script is set during set_state();
76 if (!_script.empty () && load_script ()) {
77 throw failed_constructor ();
81 LuaProc::LuaProc (const LuaProc &other)
83 , _mempool ("LuaProc", 3145728)
85 , lua (lua_newstate (&PBD::TLSF::lalloc, &_mempool))
86 #elif defined USE_MALLOC
89 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
93 , _script (other.script ())
94 , _origin (other._origin)
95 , _lua_does_channelmapping (false)
96 , _lua_has_inline_display (false)
97 , _designated_bypass_port (UINT32_MAX)
101 , _configured (false)
102 , _has_midi_input (false)
103 , _has_midi_output (false)
107 if (load_script ()) {
108 throw failed_constructor ();
111 for (uint32_t i = 0; i < parameter_count (); ++i) {
112 _control_data[i] = other._shadow_data[i];
113 _shadow_data[i] = other._shadow_data[i];
117 LuaProc::~LuaProc () {
118 #ifdef WITH_LUAPROC_STATS
119 if (_info && _stats_cnt > 0) {
120 printf ("LuaProc: '%s' run() avg: %.3f max: %.3f [ms] p: %.1f\n",
121 _info->name.c_str (),
122 0.0001f * _stats_avg[0] / (float) _stats_cnt,
123 0.0001f * _stats_max[0],
124 _stats_max[0] * (float)_stats_cnt / _stats_avg[0]);
125 printf ("LuaProc: '%s' gc() avg: %.3f max: %.3f [ms] p: %.1f\n",
126 _info->name.c_str (),
127 0.0001f * _stats_avg[1] / (float) _stats_cnt,
128 0.0001f * _stats_max[1],
129 _stats_max[1] * (float)_stats_cnt / _stats_avg[1]);
132 lua.do_command ("collectgarbage();");
134 delete (_lua_latency);
135 delete [] _control_data;
136 delete [] _shadow_data;
142 #ifdef WITH_LUAPROC_STATS
143 _stats_avg[0] = _stats_avg[1] = _stats_max[0] = _stats_max[1] = 0;
147 lua.Print.connect (sigc::mem_fun (*this, &LuaProc::lua_print));
148 // register session object
149 lua_State* L = lua.getState ();
151 LuaBindings::stddef (L);
152 LuaBindings::common (L);
153 LuaBindings::dsp (L);
155 luabridge::getGlobalNamespace (L)
156 .beginNamespace ("Ardour")
157 .deriveClass <LuaProc, PBD::StatefulDestructible> ("LuaProc")
158 .addFunction ("queue_draw", &LuaProc::queue_draw)
159 .addFunction ("shmem", &LuaProc::instance_shm)
160 .addFunction ("table", &LuaProc::instance_ref)
161 .addFunction ("route", &LuaProc::route)
162 .addFunction ("unique_id", &LuaProc::unique_id)
163 .addFunction ("name", &LuaProc::name)
168 // add session to global lua namespace
169 luabridge::push <Session *> (L, &_session);
170 lua_setglobal (L, "Session");
173 luabridge::push <LuaProc *> (L, this);
174 lua_setglobal (L, "self");
179 lua.do_command ("for n in pairs(_G) do print(n) end print ('----')"); // print global env
181 lua.do_command ("function ardour () end");
184 boost::weak_ptr<Route>
185 LuaProc::route () const
188 return boost::weak_ptr<Route>();
190 return static_cast<Route*>(_owner)->weakroute ();
194 LuaProc::lua_print (std::string s) {
195 std::cout <<"LuaProc: " << s << "\n";
196 PBD::error << "LuaProc: " << s << "\n";
200 LuaProc::load_script ()
202 if (_script.empty ()) {
205 assert (!_lua_dsp); // don't allow to re-initialize
206 LuaPluginInfoPtr lpi;
208 // TODO: refine APIs; function arguments..
209 // - perform channel-map in ardour (silent/scratch buffers) ?
210 // - control-port API (explicit get/set functions ??)
211 // - latency reporting (global var? ctrl-port? set-function ?)
212 // - MIDI -> sparse table of events
213 // { [sample] => { Event }, .. }
214 // or { { sample, Event }, .. }
217 LuaScriptInfoPtr lsi = LuaScripting::script_info (_script);
218 lpi = LuaPluginInfoPtr (new LuaPluginInfo (lsi));
221 _mempool.set_name ("LuaProc: " + lsi->name);
222 _docs = lsi->description;
223 } catch (failed_constructor& err) {
227 lua_State* L = lua.getState ();
228 lua.do_command (_script);
230 // check if script has a DSP callback
231 luabridge::LuaRef lua_dsp_run = luabridge::getGlobal (L, "dsp_run");
232 luabridge::LuaRef lua_dsp_map = luabridge::getGlobal (L, "dsp_runmap");
234 if ((lua_dsp_run.type () != LUA_TFUNCTION) == (lua_dsp_map.type () != LUA_TFUNCTION)) {
238 if (lua_dsp_run.type () == LUA_TFUNCTION) {
239 _lua_dsp = new luabridge::LuaRef (lua_dsp_run);
241 else if (lua_dsp_map.type () == LUA_TFUNCTION) {
242 _lua_dsp = new luabridge::LuaRef (lua_dsp_map);
243 _lua_does_channelmapping = true;
250 luabridge::LuaRef lua_dsp_latency = luabridge::getGlobal (L, "dsp_latency");
251 if (lua_dsp_latency.type () == LUA_TFUNCTION) {
252 _lua_latency = new luabridge::LuaRef (lua_dsp_latency);
255 // initialize the DSP if needed
256 luabridge::LuaRef lua_dsp_init = luabridge::getGlobal (L, "dsp_init");
257 if (lua_dsp_init.type () == LUA_TFUNCTION) {
259 lua_dsp_init (_session.nominal_sample_rate ());
260 } catch (luabridge::LuaException const& e) {
261 return true; // error
267 _ctrl_params.clear ();
269 luabridge::LuaRef lua_render = luabridge::getGlobal (L, "render_inline");
270 if (lua_render.isFunction ()) {
271 _lua_has_inline_display = true;
274 luabridge::LuaRef lua_params = luabridge::getGlobal (L, "dsp_params");
275 if (lua_params.isFunction ()) {
277 // call function // add try {} catch (luabridge::LuaException const& e)
278 luabridge::LuaRef params = lua_params ();
280 if (params.isTable ()) {
282 for (luabridge::Iterator i (params); !i.isNil (); ++i) {
284 if (!i.key ().isNumber ()) { return true; }
285 if (!i.value ().isTable ()) { return true; }
286 if (!i.value ()["type"].isString ()) { return true; }
287 if (!i.value ()["name"].isString ()) { return true; }
288 if (!i.value ()["min"].isNumber ()) { return true; }
289 if (!i.value ()["max"].isNumber ()) { return true; }
291 int pn = i.key ().cast<int> ();
292 std::string type = i.value ()["type"].cast<std::string> ();
293 if (type == "input") {
294 if (!i.value ()["default"].isNumber ()) {
295 return true; // error
297 _ctrl_params.push_back (std::make_pair (false, pn));
299 else if (type == "output") {
300 _ctrl_params.push_back (std::make_pair (true, pn));
302 return true; // error
304 assert (pn == (int) _ctrl_params.size ());
306 //_param_desc[pn] = boost::shared_ptr<ParameterDescriptor> (new ParameterDescriptor());
307 luabridge::LuaRef lr = i.value ();
309 if (type == "input") {
310 _param_desc[pn].normal = lr["default"].cast<float> ();
312 _param_desc[pn].normal = lr["min"].cast<float> (); // output-port, no default
314 _param_desc[pn].lower = lr["min"].cast<float> ();
315 _param_desc[pn].upper = lr["max"].cast<float> ();
316 _param_desc[pn].toggled = lr["toggled"].isBoolean () && (lr["toggled"]).cast<bool> ();
317 _param_desc[pn].logarithmic = lr["logarithmic"].isBoolean () && (lr["logarithmic"]).cast<bool> ();
318 _param_desc[pn].integer_step = lr["integer"].isBoolean () && (lr["integer"]).cast<bool> ();
319 _param_desc[pn].sr_dependent = lr["ratemult"].isBoolean () && (lr["ratemult"]).cast<bool> ();
320 _param_desc[pn].enumeration = lr["enum"].isBoolean () && (lr["enum"]).cast<bool> ();
322 if (lr["bypass"].isBoolean () && (lr["bypass"]).cast<bool> ()) {
323 _designated_bypass_port = pn - 1; // lua table starts at 1.
326 if (lr["unit"].isString ()) {
327 std::string unit = lr["unit"].cast<std::string> ();
328 if (unit == "dB") { _param_desc[pn].unit = ParameterDescriptor::DB; }
329 else if (unit == "Hz") { _param_desc[pn].unit = ParameterDescriptor::HZ; }
330 else if (unit == "Midi Note") { _param_desc[pn].unit = ParameterDescriptor::MIDI_NOTE; }
332 _param_desc[pn].label = (lr["name"]).cast<std::string> ();
333 _param_desc[pn].scale_points = parse_scale_points (&lr);
335 luabridge::LuaRef doc = lr["doc"];
336 if (doc.isString ()) {
337 _param_doc[pn] = doc.cast<std::string> ();
341 assert (!(_param_desc[pn].toggled && _param_desc[pn].logarithmic));
346 _control_data = new float[parameter_count ()];
347 _shadow_data = new float[parameter_count ()];
349 for (uint32_t i = 0; i < parameter_count (); ++i) {
350 if (parameter_is_input (i)) {
351 _control_data[i] = _shadow_data[i] = default_value (i);
355 // expose ctrl-ports to global lua namespace
356 luabridge::push <float *> (L, _control_data);
357 lua_setglobal (L, "CtrlPorts");
359 return false; // no error
363 LuaProc::can_support_io_configuration (const ChanCount& in, ChanCount& out, ChanCount* imprecise)
365 // caller must hold process lock (no concurrent calls to interpreter
366 _output_configs.clear ();
368 lua_State* L = lua.getState ();
369 luabridge::LuaRef ioconfig = luabridge::getGlobal (L, "dsp_ioconfig");
371 luabridge::LuaRef *_iotable = NULL; // can't use reference :(
373 if (ioconfig.isFunction ()) {
375 luabridge::LuaRef iotable = ioconfig ();
376 if (iotable.isTable ()) {
377 _iotable = new luabridge::LuaRef (iotable);
379 } catch (luabridge::LuaException const& e) {
387 /* empty table as default */
388 luabridge::LuaRef iotable = luabridge::newTable(L);
389 _iotable = new luabridge::LuaRef (iotable);
392 // now we can reference it.
393 luabridge::LuaRef iotable (*_iotable);
396 if ((iotable).length () < 1) {
397 /* empty table as only config, to get default values */
398 luabridge::LuaRef ioconf = luabridge::newTable(L);
402 const int audio_in = in.n_audio ();
403 const int midi_in = in.n_midi ();
405 // preferred setting (provided by plugin_insert)
406 const int preferred_out = out.n_audio ();
407 const int preferred_midiout = out.n_midi ();
411 float penalty = 9999;
414 #define FOUNDCFG_PENALTY(in, out, p) { \
415 _output_configs.insert (out); \
418 midi_out = possible_midiout; \
420 imprecise->set (DataType::AUDIO, (in)); \
421 imprecise->set (DataType::MIDI, possible_midiin); \
423 _has_midi_input = (possible_midiin > 0); \
424 _has_midi_output = (possible_midiout > 0); \
430 #define FOUNDCFG_IMPRECISE(in, out) { \
431 const float p = fabsf ((float)(out) - preferred_out) * \
432 (((out) > preferred_out) ? 1.1 : 1) \
433 + fabsf ((float)possible_midiout - preferred_midiout) * \
434 ((possible_midiout - preferred_midiout) ? 0.6 : 0.5) \
435 + fabsf ((float)(in) - audio_in) * \
436 (((in) > audio_in) ? 275 : 250) \
437 + fabsf ((float)possible_midiin - midi_in) * \
438 ((possible_midiin - midi_in) ? 100 : 110); \
439 FOUNDCFG_PENALTY(in, out, p); \
442 #define FOUNDCFG(out) \
443 FOUNDCFG_IMPRECISE(audio_in, out)
445 #define ANYTHINGGOES \
446 _output_configs.insert (0);
448 #define UPTO(nch) { \
449 for (int n = 1; n < nch; ++n) { \
450 _output_configs.insert (n); \
458 for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
459 luabridge::LuaRef io (i.value ());
464 int possible_in = io["audio_in"].isNumber() ? io["audio_in"] : -1;
465 int possible_out = io["audio_out"].isNumber() ? io["audio_out"] : -1;
466 int possible_midiin = io["midi_in"].isNumber() ? io["midi_in"] : 0;
467 int possible_midiout = io["midi_out"].isNumber() ? io["midi_out"] : 0;
469 if (midi_in != possible_midiin && !imprecise) {
474 if ((possible_in == audio_in) && (possible_out == preferred_out)) {
475 /* Set penalty so low that this output configuration
476 * will trump any other one */
477 FOUNDCFG_PENALTY(audio_in, preferred_out, -1);
480 if (possible_out == 0 && possible_midiout == 0) {
481 /* skip configurations with no output at all */
485 if (possible_in == -1 || possible_in == -2) {
486 /* wildcard for input */
487 if (possible_out == possible_in) {
488 /* either both -1 or both -2 (invalid and
489 * interpreted as both -1): out must match in */
491 } else if (possible_out == -3 - possible_in) {
492 /* one is -1, the other is -2: any output configuration
493 * possible, pick what the insert prefers */
494 FOUNDCFG (preferred_out);
496 } else if (possible_out < -2) {
497 /* variable number of outputs up to -N,
498 * invalid if in == -2 but we accept it anyway */
499 FOUNDCFG (min (-possible_out, preferred_out));
502 /* exact number of outputs */
503 FOUNDCFG (possible_out);
507 if (possible_in < -2 || possible_in >= 0) {
508 /* specified number, exact or up to */
510 if (possible_in >= 0) {
511 /* configuration can only match possible_in */
512 desired_in = possible_in;
514 /* configuration can match up to -possible_in */
515 desired_in = min (-possible_in, audio_in);
517 if (!imprecise && audio_in != desired_in) {
518 /* skip that configuration, it cannot match
519 * the required audio input count, and we
520 * cannot ask for change via \imprecise */
521 } else if (possible_out == -1 || possible_out == -2) {
522 /* any output configuration possible
523 * out == -2 is invalid, interpreted as out == -1.
524 * Really imprecise only if desired_in != audio_in */
525 FOUNDCFG_IMPRECISE (desired_in, preferred_out);
527 } else if (possible_out < -2) {
528 /* variable number of outputs up to -N
529 * not specified if in > 0, but we accept it anyway.
530 * Really imprecise only if desired_in != audio_in */
531 FOUNDCFG_IMPRECISE (desired_in, min (-possible_out, preferred_out));
534 /* exact number of outputs
535 * Really imprecise only if desired_in != audio_in */
536 FOUNDCFG_IMPRECISE (desired_in, possible_out);
547 _selected_in = *imprecise;
552 out.set (DataType::MIDI, midi_out);
553 out.set (DataType::AUDIO, audio_out);
560 LuaProc::configure_io (ChanCount in, ChanCount out)
562 in.set (DataType::MIDI, _has_midi_input ? 1 : 0);
563 out.set (DataType::MIDI, _has_midi_output ? 1 : 0);
565 _info->n_inputs = _selected_in;
566 _info->n_outputs = _selected_out;
568 // configure the DSP if needed
569 if (in != _configured_in || out != _configured_out || !_configured) {
570 lua_State* L = lua.getState ();
571 luabridge::LuaRef lua_dsp_configure = luabridge::getGlobal (L, "dsp_configure");
572 if (lua_dsp_configure.type () == LUA_TFUNCTION) {
574 luabridge::LuaRef io = lua_dsp_configure (&in, &out);
576 ChanCount lin (_selected_in);
577 ChanCount lout (_selected_out);
579 if (io["audio_in"].type() == LUA_TNUMBER) {
580 const int c = io["audio_in"].cast<int> ();
582 lin.set (DataType::AUDIO, c);
585 if (io["audio_out"].type() == LUA_TNUMBER) {
586 const int c = io["audio_out"].cast<int> ();
588 lout.set (DataType::AUDIO, c);
591 if (io["midi_in"].type() == LUA_TNUMBER) {
592 const int c = io["midi_in"].cast<int> ();
594 lin.set (DataType::MIDI, c);
597 if (io["midi_out"].type() == LUA_TNUMBER) {
598 const int c = io["midi_out"].cast<int> ();
600 lout.set (DataType::MIDI, c);
603 _info->n_inputs = lin;
604 _info->n_outputs = lout;
607 } catch (luabridge::LuaException const& e) {
608 PBD::error << "LuaException: " << e.what () << "\n";
610 std::cerr << "LuaException: " << e.what () << "\n";
620 _configured_out = out;
626 LuaProc::connect_and_run (BufferSet& bufs,
627 samplepos_t start, samplepos_t end, double speed,
628 ChanMapping const& in, ChanMapping const& out,
629 pframes_t nframes, samplecnt_t offset)
635 Plugin::connect_and_run (bufs, start, end, speed, in, out, nframes, offset);
637 // This is needed for ARDOUR::Session requests :(
638 assert (SessionEvent::has_per_thread_pool ());
640 uint32_t const n = parameter_count ();
641 for (uint32_t i = 0; i < n; ++i) {
642 if (parameter_is_control (i) && parameter_is_input (i)) {
643 _control_data[i] = _shadow_data[i];
647 #ifdef WITH_LUAPROC_STATS
648 int64_t t0 = g_get_monotonic_time ();
652 if (_lua_does_channelmapping) {
653 // run the DSP function
654 (*_lua_dsp)(&bufs, in, out, nframes, offset);
657 BufferSet& silent_bufs = _session.get_silent_buffers (ChanCount (DataType::AUDIO, 1));
658 BufferSet& scratch_bufs = _session.get_scratch_buffers (ChanCount (DataType::AUDIO, 1));
660 lua_State* L = lua.getState ();
661 luabridge::LuaRef in_map (luabridge::newTable (L));
662 luabridge::LuaRef out_map (luabridge::newTable (L));
664 const uint32_t audio_in = _configured_in.n_audio ();
665 const uint32_t audio_out = _configured_out.n_audio ();
666 const uint32_t midi_in = _configured_in.n_midi ();
668 for (uint32_t ap = 0; ap < audio_in; ++ap) {
670 const uint32_t buf_index = in.get(DataType::AUDIO, ap, &valid);
672 in_map[ap + 1] = bufs.get_audio (buf_index).data (offset);
674 in_map[ap + 1] = silent_bufs.get_audio (0).data (offset);
677 for (uint32_t ap = 0; ap < audio_out; ++ap) {
679 const uint32_t buf_index = out.get(DataType::AUDIO, ap, &valid);
681 out_map[ap + 1] = bufs.get_audio (buf_index).data (offset);
683 out_map[ap + 1] = scratch_bufs.get_audio (0).data (offset);
687 luabridge::LuaRef lua_midi_src_tbl (luabridge::newTable (L));
688 int e = 1; // > 1 port, we merge events (unsorted)
689 for (uint32_t mp = 0; mp < midi_in; ++mp) {
691 const uint32_t idx = in.get(DataType::MIDI, mp, &valid);
693 for (MidiBuffer::iterator m = bufs.get_midi(idx).begin();
694 m != bufs.get_midi(idx).end(); ++m, ++e) {
695 const Evoral::Event<samplepos_t> ev(*m, false);
696 luabridge::LuaRef lua_midi_data (luabridge::newTable (L));
697 const uint8_t* data = ev.buffer();
698 for (uint32_t i = 0; i < ev.size(); ++i) {
699 lua_midi_data [i + 1] = data[i];
701 luabridge::LuaRef lua_midi_event (luabridge::newTable (L));
702 lua_midi_event["time"] = 1 + (*m).time();
703 lua_midi_event["data"] = lua_midi_data;
704 lua_midi_event["bytes"] = data;
705 lua_midi_event["size"] = ev.size();
706 lua_midi_src_tbl[e] = lua_midi_event;
711 if (_has_midi_input) {
712 // XXX TODO This needs a better solution than global namespace
713 luabridge::push (L, lua_midi_src_tbl);
714 lua_setglobal (L, "midiin");
717 luabridge::LuaRef lua_midi_sink_tbl (luabridge::newTable (L));
718 if (_has_midi_output) {
719 luabridge::push (L, lua_midi_sink_tbl);
720 lua_setglobal (L, "midiout");
723 // run the DSP function
724 (*_lua_dsp)(in_map, out_map, nframes);
726 // copy back midi events
727 if (_has_midi_output && lua_midi_sink_tbl.isTable ()) {
729 const uint32_t idx = out.get(DataType::MIDI, 0, &valid);
730 if (valid && bufs.count().n_midi() > idx) {
731 MidiBuffer& mbuf = bufs.get_midi(idx);
733 for (luabridge::Iterator i (lua_midi_sink_tbl); !i.isNil (); ++i) {
734 if (!i.key ().isNumber ()) { continue; }
735 if (!i.value ()["time"].isNumber ()) { continue; }
736 if (!i.value ()["data"].isTable ()) { continue; }
737 luabridge::LuaRef data_tbl (i.value ()["data"]);
738 samplepos_t tme = i.value ()["time"];
739 if (tme < 1 || tme > nframes) { continue; }
742 for (luabridge::Iterator di (data_tbl); !di.isNil () && size < sizeof(data); ++di, ++size) {
743 data[size] = di.value ();
745 if (size > 0 && size < 64) {
746 mbuf.push_back(tme - 1, size, data);
755 _signal_latency = (*_lua_latency)();
758 } catch (luabridge::LuaException const& e) {
759 PBD::error << "LuaException: " << e.what () << "\n";
761 std::cerr << "LuaException: " << e.what () << "\n";
767 #ifdef WITH_LUAPROC_STATS
768 int64_t t1 = g_get_monotonic_time ();
771 lua.collect_garbage_step ();
772 #ifdef WITH_LUAPROC_STATS
773 if (++_stats_cnt > 0) {
774 int64_t t2 = g_get_monotonic_time ();
775 int64_t ela0 = t1 - t0;
776 int64_t ela1 = t2 - t1;
777 if (ela0 > _stats_max[0]) _stats_max[0] = ela0;
778 if (ela1 > _stats_max[1]) _stats_max[1] = ela1;
779 _stats_avg[0] += ela0;
780 _stats_avg[1] += ela1;
788 LuaProc::add_state (XMLNode* root) const
792 gchar* b64 = g_base64_encode ((const guchar*)_script.c_str (), _script.size ());
793 std::string b64s (b64);
795 XMLNode* script_node = new XMLNode (X_("script"));
796 script_node->set_property (X_("lua"), LUA_VERSION);
797 script_node->set_property (X_("origin"), _origin);
798 script_node->add_content (b64s);
799 root->add_child_nocopy (*script_node);
801 for (uint32_t i = 0; i < parameter_count(); ++i) {
802 if (parameter_is_input(i) && parameter_is_control(i)) {
803 child = new XMLNode("Port");
804 child->set_property("id", i);
805 child->set_property("value", _shadow_data[i]);
806 root->add_child_nocopy(*child);
812 LuaProc::set_script_from_state (const XMLNode& node)
815 if (node.name () != state_node_name ()) {
819 if ((child = node.child (X_("script"))) != 0) {
820 XMLProperty const* prop;
821 if ((prop = node.property ("origin")) != 0) {
822 _origin = prop->value();
824 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
825 if (!(*n)->is_content ()) { continue; }
827 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
828 _script = std::string ((const char*)buf, size);
830 if (load_script ()) {
831 PBD::error << _("Failed to load Lua script from session state.") << endmsg;
833 std::cerr << "Failed Lua Script: " << _script << std::endl;
840 if (_script.empty ()) {
841 PBD::error << _("Session State for LuaProcessor did not include a Lua script.") << endmsg;
845 PBD::error << _("Invalid/incompatible Lua script found for LuaProcessor.") << endmsg;
852 LuaProc::set_state (const XMLNode& node, int version)
855 XMLNodeConstIterator iter;
858 if (_script.empty ()) {
859 if (set_script_from_state (node)) {
864 if (node.name() != state_node_name()) {
865 error << _("Bad node sent to LuaProc::set_state") << endmsg;
869 nodes = node.children ("Port");
870 for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
876 if (!child->get_property("id", port_id)) {
877 warning << _("LuaProc: port has no symbol, ignored") << endmsg;
881 if (!child->get_property("value", value)) {
882 warning << _("LuaProc: port has no value, ignored") << endmsg;
886 set_parameter (port_id, value);
889 return Plugin::set_state (node, version);
893 LuaProc::parameter_count () const
895 return _ctrl_params.size ();
899 LuaProc::default_value (uint32_t port)
901 if (_ctrl_params[port].first) {
905 int lp = _ctrl_params[port].second;
906 return _param_desc[lp].normal;
910 LuaProc::set_parameter (uint32_t port, float val)
912 assert (port < parameter_count ());
913 if (get_parameter (port) == val) {
916 _shadow_data[port] = val;
917 Plugin::set_parameter (port, val);
921 LuaProc::get_parameter (uint32_t port) const
923 if (parameter_is_input (port)) {
924 return _shadow_data[port];
926 return _control_data[port];
931 LuaProc::get_parameter_descriptor (uint32_t port, ParameterDescriptor& desc) const
933 assert (port <= parameter_count ());
934 int lp = _ctrl_params[port].second;
935 const ParameterDescriptor& d (_param_desc.find(lp)->second);
937 desc.lower = d.lower;
938 desc.upper = d.upper;
939 desc.normal = d.normal;
940 desc.toggled = d.toggled;
941 desc.logarithmic = d.logarithmic;
942 desc.integer_step = d.integer_step;
943 desc.sr_dependent = d.sr_dependent;
944 desc.enumeration = d.enumeration;
946 desc.label = d.label;
947 desc.scale_points = d.scale_points;
949 desc.update_steps ();
954 LuaProc::get_parameter_docs (uint32_t port) const {
955 assert (port <= parameter_count ());
956 int lp = _ctrl_params[port].second;
957 return _param_doc.find(lp)->second;
961 LuaProc::nth_parameter (uint32_t port, bool& ok) const
963 if (port < _ctrl_params.size ()) {
972 LuaProc::parameter_is_input (uint32_t port) const
974 assert (port < _ctrl_params.size ());
975 return (!_ctrl_params[port].first);
979 LuaProc::parameter_is_output (uint32_t port) const
981 assert (port < _ctrl_params.size ());
982 return (_ctrl_params[port].first);
985 std::set<Evoral::Parameter>
986 LuaProc::automatable () const
988 std::set<Evoral::Parameter> automatables;
989 for (uint32_t i = 0; i < _ctrl_params.size (); ++i) {
990 if (parameter_is_input (i)) {
991 automatables.insert (automatables.end (), Evoral::Parameter (PluginAutomation, 0, i));
998 LuaProc::describe_parameter (Evoral::Parameter param)
1000 if (param.type () == PluginAutomation && param.id () < parameter_count ()) {
1001 int lp = _ctrl_params[param.id ()].second;
1002 return _param_desc[lp].label;
1007 boost::shared_ptr<ScalePoints>
1008 LuaProc::parse_scale_points (luabridge::LuaRef* lr)
1010 if (!(*lr)["scalepoints"].isTable()) {
1011 return boost::shared_ptr<ScalePoints> ();
1015 boost::shared_ptr<ScalePoints> rv = boost::shared_ptr<ScalePoints>(new ScalePoints());
1016 luabridge::LuaRef scalepoints ((*lr)["scalepoints"]);
1018 for (luabridge::Iterator i (scalepoints); !i.isNil (); ++i) {
1019 if (!i.key ().isString ()) { continue; }
1020 if (!i.value ().isNumber ()) { continue; }
1021 rv->insert(make_pair(i.key ().cast<std::string> (),
1022 i.value ().cast<float> ()));
1026 if (rv->size() > 0) {
1029 return boost::shared_ptr<ScalePoints> ();
1032 boost::shared_ptr<ScalePoints>
1033 LuaProc::get_scale_points (uint32_t port) const
1035 int lp = _ctrl_params[port].second;
1036 return _param_desc.find(lp)->second.scale_points;
1040 LuaProc::setup_lua_inline_gui (LuaState *lua_gui)
1042 lua_State* LG = lua_gui->getState ();
1043 LuaBindings::stddef (LG);
1044 LuaBindings::common (LG);
1045 LuaBindings::dsp (LG);
1046 LuaBindings::osc (LG);
1048 lua_gui->Print.connect (sigc::mem_fun (*this, &LuaProc::lua_print));
1049 lua_gui->do_command ("function ardour () end");
1050 lua_gui->do_command (_script);
1052 // TODO think: use a weak-pointer here ?
1053 // (the GUI itself uses a shared ptr to this plugin, so we should be good)
1054 luabridge::getGlobalNamespace (LG)
1055 .beginNamespace ("Ardour")
1056 .beginClass <LuaProc> ("LuaProc")
1057 .addFunction ("shmem", &LuaProc::instance_shm)
1058 .addFunction ("table", &LuaProc::instance_ref)
1062 luabridge::push <LuaProc *> (LG, this);
1063 lua_setglobal (LG, "self");
1065 luabridge::push <float *> (LG, _control_data);
1066 lua_setglobal (LG, "CtrlPorts");
1068 ////////////////////////////////////////////////////////////////////////////////
1070 #include "ardour/search_paths.h"
1074 LuaProc::preset_name_to_uri (const std::string& name) const
1076 std::string uri ("urn:lua:");
1080 sha1_write (&s, (const uint8_t *) name.c_str(), name.size ());
1081 sha1_write (&s, (const uint8_t *) _script.c_str(), _script.size ());
1082 sha1_result_hash (&s, hash);
1087 LuaProc::presets_file () const
1089 return string_compose ("lua-%1", _info->unique_id);
1093 LuaProc::presets_tree () const
1095 XMLTree* t = new XMLTree;
1096 std::string p = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
1098 if (!Glib::file_test (p, Glib::FILE_TEST_IS_DIR)) {
1099 if (g_mkdir_with_parents (p.c_str(), 0755) != 0) {
1100 error << _("Unable to create LuaProc presets directory") << endmsg;
1104 p = Glib::build_filename (p, presets_file ());
1106 if (!Glib::file_test (p, Glib::FILE_TEST_EXISTS)) {
1107 t->set_root (new XMLNode (X_("LuaPresets")));
1111 t->set_filename (p);
1120 LuaProc::load_preset (PresetRecord r)
1122 boost::shared_ptr<XMLTree> t (presets_tree ());
1127 XMLNode* root = t->root ();
1128 for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
1130 if (!(*i)->get_property (X_("label"), str)) {
1133 if (str != r.label) {
1137 for (XMLNodeList::const_iterator j = (*i)->children().begin(); j != (*i)->children().end(); ++j) {
1138 if ((*j)->name() == X_("Parameter")) {
1141 if (!(*j)->get_property (X_("index"), index) ||
1142 !(*j)->get_property (X_("value"), value)) {
1145 set_parameter (index, value);
1146 PresetPortSetValue (index, value); /* EMIT SIGNAL */
1149 return Plugin::load_preset(r);
1155 LuaProc::do_save_preset (std::string name) {
1157 boost::shared_ptr<XMLTree> t (presets_tree ());
1162 // prevent dups -- just in case
1163 t->root()->remove_nodes_and_delete (X_("label"), name);
1165 std::string uri (preset_name_to_uri (name));
1167 XMLNode* p = new XMLNode (X_("Preset"));
1168 p->set_property (X_("uri"), uri);
1169 p->set_property (X_("label"), name);
1171 for (uint32_t i = 0; i < parameter_count(); ++i) {
1172 if (parameter_is_input (i)) {
1173 XMLNode* c = new XMLNode (X_("Parameter"));
1174 c->set_property (X_("index"), i);
1175 c->set_property (X_("value"), get_parameter (i));
1176 p->add_child_nocopy (*c);
1179 t->root()->add_child_nocopy (*p);
1181 std::string f = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
1182 f = Glib::build_filename (f, presets_file ());
1189 LuaProc::do_remove_preset (std::string name)
1191 boost::shared_ptr<XMLTree> t (presets_tree ());
1195 t->root()->remove_nodes_and_delete (X_("label"), name);
1196 std::string f = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
1197 f = Glib::build_filename (f, presets_file ());
1202 LuaProc::find_presets ()
1204 boost::shared_ptr<XMLTree> t (presets_tree ());
1206 XMLNode* root = t->root ();
1207 for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
1211 if (!(*i)->get_property (X_("uri"), uri) || !(*i)->get_property (X_("label"), label)) {
1215 PresetRecord r (uri, label, true);
1216 _presets.insert (make_pair (r.uri, r));
1221 ////////////////////////////////////////////////////////////////////////////////
1223 LuaPluginInfo::LuaPluginInfo (LuaScriptInfoPtr lsi) {
1224 if (lsi->type != LuaScriptInfo::DSP) {
1225 throw failed_constructor ();
1230 creator = lsi->author;
1231 category = lsi->category;
1232 unique_id = lsi->unique_id;
1234 n_inputs.set (DataType::AUDIO, 1);
1235 n_outputs.set (DataType::AUDIO, 1);
1238 // TODO, parse script, get 'dsp_ioconfig', see can_support_io_configuration()
1243 LuaPluginInfo::load (Session& session)
1245 std::string script = "";
1246 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
1247 return PluginPtr ();
1251 script = Glib::file_get_contents (path);
1252 } catch (Glib::FileError const& err) {
1253 return PluginPtr ();
1256 if (script.empty ()) {
1257 return PluginPtr ();
1261 LuaProc* lp = new LuaProc (session.engine (), session, script);
1262 lp->set_origin (path);
1263 PluginPtr plugin (lp);
1265 } catch (failed_constructor& err) {
1268 return PluginPtr ();
1271 std::vector<Plugin::PresetRecord>
1272 LuaPluginInfo::get_presets (bool /*user_only*/) const
1274 std::vector<Plugin::PresetRecord> p;
1275 XMLTree* t = new XMLTree;
1276 std::string pf = Glib::build_filename (ARDOUR::user_config_directory (), "presets", string_compose ("lua-%1", unique_id));
1277 if (Glib::file_test (pf, Glib::FILE_TEST_EXISTS)) {
1278 t->set_filename (pf);
1280 XMLNode* root = t->root ();
1281 for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
1282 XMLProperty const * uri = (*i)->property (X_("uri"));
1283 XMLProperty const * label = (*i)->property (X_("label"));
1284 p.push_back (Plugin::PresetRecord (uri->value(), label->value(), true));