2 Copyright (C) 2016 Robin Gareus <robin@gareus.org>
3 Copyright (C) 2006 Paul Davis
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)
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
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.
21 #include "pbd/gstdio_compat.h"
23 #include "pbd/pthread_utils.h"
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"
34 #include "LuaBridge/LuaBridge.h"
38 using namespace ARDOUR;
41 LuaProc::LuaProc (AudioEngine& engine,
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))
49 , _lua_does_channelmapping (false)
50 , _lua_has_inline_display (false)
53 , _has_midi_input (false)
54 , _has_midi_output (false)
58 /* when loading a session, or pasing a processor,
59 * the script is set during set_state();
61 if (!_script.empty () && load_script ()) {
62 throw failed_constructor ();
66 LuaProc::LuaProc (const LuaProc &other)
68 , _mempool ("LuaProc", 1048576) // 1 MB is plenty. (64K would be enough)
69 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
71 , _script (other.script ())
72 , _lua_does_channelmapping (false)
73 , _lua_has_inline_display (false)
76 , _has_midi_input (false)
77 , _has_midi_output (false)
82 throw failed_constructor ();
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];
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",
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",
100 0.0001f * _stats_avg[1] / (float) _stats_cnt,
101 0.0001f * _stats_max[1]);
104 lua.do_command ("collectgarbage();");
106 delete [] _control_data;
107 delete [] _shadow_data;
113 #ifdef WITH_LUAPROC_STATS
114 _stats_avg[0] = _stats_avg[1] = _stats_max[0] = _stats_max[1] = _stats_cnt = 0;
118 lua.Print.connect (sigc::mem_fun (*this, &LuaProc::lua_print));
120 // register session object
121 lua_State* L = lua.getState ();
122 LuaBindings::stddef (L);
123 LuaBindings::common (L);
124 LuaBindings::dsp (L);
126 luabridge::getGlobalNamespace (L)
127 .beginNamespace ("Ardour")
128 .beginClass <LuaProc> ("LuaProc")
129 .addFunction ("queue_draw", &LuaProc::queue_draw)
130 .addFunction ("shmem", &LuaProc::instance_shm)
134 // add session to global lua namespace
135 luabridge::push <Session *> (L, &_session);
136 lua_setglobal (L, "Session");
139 luabridge::push <LuaProc *> (L, this);
140 lua_setglobal (L, "self");
143 lua.do_command ("io = nil os = nil loadfile = nil require = nil dofile = nil package = nil debug = nil");
145 lua.do_command ("for n in pairs(_G) do print(n) end print ('----')"); // print global env
147 lua.do_command ("function ardour () end");
151 LuaProc::lua_print (std::string s) {
152 std::cout <<"LuaProc: " << s << "\n";
156 LuaProc::load_script ()
158 assert (!_lua_dsp); // don't allow to re-initialize
159 LuaPluginInfoPtr lpi;
161 // TODO: refine APIs; function arguments..
162 // - perform channel-map in ardour (silent/scratch buffers) ?
163 // - control-port API (explicit get/set functions ??)
164 // - latency reporting (global var? ctrl-port? set-function ?)
165 // - MIDI -> sparse table of events
166 // { [sample] => { Event }, .. }
167 // or { { sample, Event }, .. }
170 LuaScriptInfoPtr lsi = LuaScripting::script_info (_script);
171 lpi = LuaPluginInfoPtr (new LuaPluginInfo (lsi));
174 _mempool.set_name ("LuaProc: " + lsi->name);
175 _docs = lsi->description;
176 } catch (failed_constructor& err) {
180 lua_State* L = lua.getState ();
181 lua.do_command (_script);
183 // check if script has a DSP callback
184 luabridge::LuaRef lua_dsp_run = luabridge::getGlobal (L, "dsp_run");
185 luabridge::LuaRef lua_dsp_map = luabridge::getGlobal (L, "dsp_runmap");
187 if ((lua_dsp_run.type () != LUA_TFUNCTION) == (lua_dsp_map.type () != LUA_TFUNCTION)) {
191 if (lua_dsp_run.type () == LUA_TFUNCTION) {
192 _lua_dsp = new luabridge::LuaRef (lua_dsp_run);
194 else if (lua_dsp_map.type () == LUA_TFUNCTION) {
195 _lua_dsp = new luabridge::LuaRef (lua_dsp_map);
196 _lua_does_channelmapping = true;
202 // initialize the DSP if needed
203 luabridge::LuaRef lua_dsp_init = luabridge::getGlobal (L, "dsp_init");
204 if (lua_dsp_init.type () == LUA_TFUNCTION) {
206 lua_dsp_init (_session.nominal_frame_rate ());
207 } catch (luabridge::LuaException const& e) {
212 luabridge::LuaRef lua_dsp_midi_in = luabridge::getGlobal (L, "dsp_midi_input");
213 if (lua_dsp_midi_in.type () == LUA_TFUNCTION) {
215 _has_midi_input = lua_dsp_midi_in ();
216 } catch (luabridge::LuaException const& e) {
220 lpi->_is_instrument = _has_midi_input;
222 _ctrl_params.clear ();
224 luabridge::LuaRef lua_render = luabridge::getGlobal (L, "render_inline");
225 if (lua_render.isFunction ()) {
226 _lua_has_inline_display = true;
229 luabridge::LuaRef lua_params = luabridge::getGlobal (L, "dsp_params");
230 if (lua_params.isFunction ()) {
232 // call function // add try {} catch (luabridge::LuaException const& e)
233 luabridge::LuaRef params = lua_params ();
235 if (params.isTable ()) {
237 for (luabridge::Iterator i (params); !i.isNil (); ++i) {
239 if (!i.key ().isNumber ()) { return false; }
240 if (!i.value ().isTable ()) { return false; }
241 if (!i.value ()["type"].isString ()) { return false; }
242 if (!i.value ()["name"].isString ()) { return false; }
243 if (!i.value ()["min"].isNumber ()) { return false; }
244 if (!i.value ()["max"].isNumber ()) { return false; }
246 int pn = i.key ().cast<int> ();
247 std::string type = i.value ()["type"].cast<std::string> ();
248 if (type == "input") {
249 if (!i.value ()["default"].isNumber ()) { return false; }
250 _ctrl_params.push_back (std::make_pair (false, pn));
252 else if (type == "output") {
253 _ctrl_params.push_back (std::make_pair (true, pn));
257 assert (pn == (int) _ctrl_params.size ());
259 //_param_desc[pn] = boost::shared_ptr<ParameterDescriptor> (new ParameterDescriptor());
260 luabridge::LuaRef lr = i.value ();
262 if (type == "input") {
263 _param_desc[pn].normal = lr["default"].cast<float> ();
265 _param_desc[pn].normal = lr["min"].cast<float> (); // output-port, no default
267 _param_desc[pn].lower = lr["min"].cast<float> ();
268 _param_desc[pn].upper = lr["max"].cast<float> ();
269 _param_desc[pn].toggled = lr["toggled"].isBoolean () && (lr["toggled"]).cast<bool> ();
270 _param_desc[pn].logarithmic = lr["logarithmic"].isBoolean () && (lr["logarithmic"]).cast<bool> ();
271 _param_desc[pn].integer_step = lr["integer"].isBoolean () && (lr["integer"]).cast<bool> ();
272 _param_desc[pn].sr_dependent = lr["ratemult"].isBoolean () && (lr["ratemult"]).cast<bool> ();
273 _param_desc[pn].enumeration = lr["enum"].isBoolean () && (lr["enum"]).cast<bool> ();
275 if (lr["unit"].isString ()) {
276 std::string unit = lr["unit"].cast<std::string> ();
277 if (unit == "dB") { _param_desc[pn].unit = ParameterDescriptor::DB; }
278 else if (unit == "Hz") { _param_desc[pn].unit = ParameterDescriptor::HZ; }
279 else if (unit == "Midi Note") { _param_desc[pn].unit = ParameterDescriptor::MIDI_NOTE; }
281 _param_desc[pn].label = (lr["name"]).cast<std::string> ();
282 _param_desc[pn].scale_points = parse_scale_points (&lr);
284 luabridge::LuaRef doc = lr["doc"];
285 if (doc.isString ()) {
286 _param_doc[pn] = doc.cast<std::string> ();
290 assert (!(_param_desc[pn].toggled && _param_desc[pn].logarithmic));
295 _control_data = new float[parameter_count ()];
296 _shadow_data = new float[parameter_count ()];
298 for (uint32_t i = 0; i < parameter_count (); ++i) {
299 if (parameter_is_input (i)) {
300 _control_data[i] = _shadow_data[i] = default_value (i);
304 // expose ctrl-ports to global lua namespace
305 luabridge::push <float *> (L, _control_data);
306 lua_setglobal (L, "CtrlPorts");
308 return false; // no error
312 LuaProc::can_support_io_configuration (const ChanCount& in, ChanCount& out, ChanCount* imprecise)
314 // caller must hold process lock (no concurrent calls to interpreter
316 if (in.n_midi() > 0 && !_has_midi_input && !imprecise) {
320 lua_State* L = lua.getState ();
321 luabridge::LuaRef ioconfig = luabridge::getGlobal (L, "dsp_ioconfig");
322 if (!ioconfig.isFunction ()) {
326 luabridge::LuaRef table = luabridge::getGlobal (L, "table"); //lua std lib
327 luabridge::LuaRef tablesort = table["sort"];
328 assert (tablesort.isFunction ());
330 luabridge::LuaRef *_iotable = NULL; // can't use reference :(
332 luabridge::LuaRef iotable = ioconfig ();
334 if (iotable.isTable ()) {
335 _iotable = new luabridge::LuaRef (iotable);
337 } catch (luabridge::LuaException const& e) {
345 // now we can reference it.
346 luabridge::LuaRef iotable (*_iotable);
349 if ((iotable).length () < 1) {
353 const int32_t audio_in = in.n_audio ();
355 int32_t midi_out = 0; // TODO handle _has_midi_output
357 // preferred setting (provided by plugin_insert)
358 assert (out.n_audio () > 0);
359 audio_out = out.n_audio ();
361 for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
362 assert (i.value ().type () == LUA_TTABLE);
363 luabridge::LuaRef io (i.value ());
365 int possible_in = io["audio_in"];
366 int possible_out = io["audio_out"];
369 if ((possible_in == audio_in) && (possible_out == audio_out)) {
370 out.set (DataType::MIDI, 0);
371 out.set (DataType::AUDIO, audio_out);
376 /* now allow potentially "imprecise" matches */
380 float penalty = 9999;
381 const int preferred_out = out.n_audio ();
383 #define FOUNDCFG(nch) { \
384 float p = fabsf ((float)(nch) - preferred_out); \
385 if ((nch) > preferred_out) { p *= 1.1; } \
393 for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
394 assert (i.value ().type () == LUA_TTABLE);
395 luabridge::LuaRef io (i.value ());
397 int possible_in = io["audio_in"];
398 int possible_out = io["audio_out"];
400 if (possible_out == 0) {
403 if (possible_in == 0) {
404 /* no inputs, generators & instruments */
405 if (possible_out == -1) {
406 /* any configuration possible, stereo output */
407 FOUNDCFG (preferred_out);
408 } else if (possible_out == -2) {
409 /* invalid, should be (0, -1) */
410 FOUNDCFG (preferred_out);
411 } else if (possible_out < -2) {
412 /* variable number of outputs up to -N, */
413 FOUNDCFG (min (-possible_out, preferred_out));
415 /* exact number of outputs */
416 FOUNDCFG (possible_out);
420 if (possible_in == -1) {
421 /* wildcard for input */
422 if (possible_out == -1) {
423 /* out must match in */
425 } else if (possible_out == -2) {
426 /* any configuration possible, pick matching */
427 FOUNDCFG (preferred_out);
428 } else if (possible_out < -2) {
429 /* explicitly variable number of outputs, pick maximum */
430 FOUNDCFG (max (-possible_out, preferred_out));
431 /* and try min, too, in case the penalty is lower */
432 FOUNDCFG (min (-possible_out, preferred_out));
434 /* exact number of outputs */
435 FOUNDCFG (possible_out);
439 if (possible_in == -2) {
441 if (possible_out == -1) {
442 /* any configuration possible, pick matching */
443 FOUNDCFG (preferred_out);
444 } else if (possible_out == -2) {
445 /* invalid. interpret as (-1, -1) */
446 FOUNDCFG (preferred_out);
447 } else if (possible_out < -2) {
448 /* invalid, interpret as (<-2, <-2)
449 * variable number of outputs up to -N, */
450 FOUNDCFG (min (-possible_out, preferred_out));
452 /* exact number of outputs */
453 FOUNDCFG (possible_out);
457 if (possible_in < -2) {
458 /* explicit variable number of inputs */
459 if (audio_in > -possible_in && imprecise != NULL) {
461 imprecise->set (DataType::AUDIO, -possible_in);
464 if (audio_in > -possible_in && imprecise == NULL) {
465 /* request is too large */
466 } else if (possible_out == -1) {
467 /* any output configuration possible */
468 FOUNDCFG (preferred_out);
469 } else if (possible_out == -2) {
470 /* invalid. interpret as (<-2, -1) */
471 FOUNDCFG (preferred_out);
472 } else if (possible_out < -2) {
473 /* variable number of outputs up to -N, */
474 FOUNDCFG (min (-possible_out, preferred_out));
476 /* exact number of outputs */
477 FOUNDCFG (possible_out);
481 if (possible_in && (possible_in == audio_in)) {
482 /* exact number of inputs ... must match obviously */
483 if (possible_out == -1) {
484 /* any output configuration possible */
485 FOUNDCFG (preferred_out);
486 } else if (possible_out == -2) {
487 /* invalid. interpret as (>0, -1) */
488 FOUNDCFG (preferred_out);
489 } else if (possible_out < -2) {
490 /* > 0, < -2 is not specified
491 * interpret as up to -N */
492 FOUNDCFG (min (-possible_out, preferred_out));
494 /* exact number of outputs */
495 FOUNDCFG (possible_out);
500 if (!found && imprecise) {
502 for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
503 assert (i.value ().type () == LUA_TTABLE);
504 luabridge::LuaRef io (i.value ());
506 int possible_in = io["audio_in"];
507 int possible_out = io["audio_out"];
509 assert (possible_in > 0); // all other cases will have been matched above
510 assert (possible_out !=0 || possible_in !=0); // already handled above
512 imprecise->set (DataType::AUDIO, possible_in);
513 if (possible_out == -1 || possible_out == -2) {
515 } else if (possible_out < -2) {
516 /* explicitly variable number of outputs, pick maximum */
517 FOUNDCFG (min (-possible_out, preferred_out));
519 /* exact number of outputs */
520 FOUNDCFG (possible_out);
522 // ideally we'll also find the closest, best matching
523 // input configuration with minimal output penalty...
532 out.set (DataType::MIDI, midi_out); // currently always zero
533 out.set (DataType::AUDIO, audio_out);
538 LuaProc::configure_io (ChanCount in, ChanCount out)
541 _configured_out = out;
543 _configured_in.set (DataType::MIDI, _has_midi_input ? 1 : 0);
544 _configured_out.set (DataType::MIDI, _has_midi_output ? 1 : 0);
546 // configure the DSP if needed
547 lua_State* L = lua.getState ();
548 luabridge::LuaRef lua_dsp_configure = luabridge::getGlobal (L, "dsp_configure");
549 if (lua_dsp_configure.type () == LUA_TFUNCTION) {
551 lua_dsp_configure (&in, &out);
552 } catch (luabridge::LuaException const& e) {
557 _info->n_inputs = _configured_in;
558 _info->n_outputs = _configured_out;
563 LuaProc::connect_and_run (BufferSet& bufs,
564 ChanMapping in, ChanMapping out,
565 pframes_t nframes, framecnt_t offset)
571 Plugin::connect_and_run (bufs, in, out, nframes, offset);
573 // This is needed for ARDOUR::Session requests :(
574 if (! SessionEvent::has_per_thread_pool ()) {
576 snprintf (name, 64, "Proc-%p", this);
577 pthread_set_name (name);
578 SessionEvent::create_per_thread_pool (name, 64);
579 PBD::notify_event_loops_about_thread_creation (pthread_self(), name, 64);
582 uint32_t const n = parameter_count ();
583 for (uint32_t i = 0; i < n; ++i) {
584 if (parameter_is_control (i) && parameter_is_input (i)) {
585 _control_data[i] = _shadow_data[i];
589 #ifdef WITH_LUAPROC_STATS
590 int64_t t0 = g_get_monotonic_time ();
594 if (_lua_does_channelmapping) {
595 // run the DSP function
596 (*_lua_dsp)(&bufs, in, out, nframes, offset);
599 BufferSet& silent_bufs = _session.get_silent_buffers (ChanCount (DataType::AUDIO, 1));
600 BufferSet& scratch_bufs = _session.get_scratch_buffers (ChanCount (DataType::AUDIO, 1));
602 lua_State* L = lua.getState ();
603 luabridge::LuaRef in_map (luabridge::newTable (L));
604 luabridge::LuaRef out_map (luabridge::newTable (L));
606 const uint32_t audio_in = _configured_in.n_audio ();
607 const uint32_t audio_out = _configured_out.n_audio ();
608 const uint32_t midi_in = _configured_in.n_midi ();
610 for (uint32_t ap = 0; ap < audio_in; ++ap) {
612 const uint32_t buf_index = in.get(DataType::AUDIO, ap, &valid);
614 in_map[ap + 1] = bufs.get_audio (buf_index).data (offset);
616 in_map[ap + 1] = silent_bufs.get_audio (0).data (offset);
619 for (uint32_t ap = 0; ap < audio_out; ++ap) {
621 const uint32_t buf_index = out.get(DataType::AUDIO, ap, &valid);
623 out_map[ap + 1] = bufs.get_audio (buf_index).data (offset);
625 out_map[ap + 1] = scratch_bufs.get_audio (0).data (offset);
629 luabridge::LuaRef lua_midi_tbl (luabridge::newTable (L));
630 int e = 1; // > 1 port, we merge events (unsorted)
631 for (uint32_t mp = 0; mp < midi_in; ++mp) {
633 const uint32_t idx = in.get(DataType::MIDI, mp, &valid);
635 for (MidiBuffer::iterator m = bufs.get_midi(idx).begin();
636 m != bufs.get_midi(idx).end(); ++m, ++e) {
637 const Evoral::MIDIEvent<framepos_t> ev(*m, false);
638 luabridge::LuaRef lua_midi_data (luabridge::newTable (L));
639 const uint8_t* data = ev.buffer();
640 for (uint32_t i = 0; i < ev.size(); ++i) {
641 lua_midi_data [i + 1] = data[i];
643 luabridge::LuaRef lua_midi_event (luabridge::newTable (L));
644 lua_midi_event["time"] = 1 + (*m).time();
645 lua_midi_event["data"] = lua_midi_data;
646 lua_midi_tbl[e] = lua_midi_event;
651 if (_has_midi_input) {
652 // XXX TODO This needs a better solution than global namespace
653 luabridge::push (L, lua_midi_tbl);
654 lua_setglobal (L, "mididata");
658 // run the DSP function
659 (*_lua_dsp)(in_map, out_map, nframes);
661 } catch (luabridge::LuaException const& e) {
663 printf ("LuaException: %s\n", e.what ());
667 #ifdef WITH_LUAPROC_STATS
668 int64_t t1 = g_get_monotonic_time ();
670 lua.collect_garbage (); // rt-safe, slight *regular* performance overhead
671 #ifdef WITH_LUAPROC_STATS
673 int64_t t2 = g_get_monotonic_time ();
674 int64_t ela0 = t1 - t0;
675 int64_t ela1 = t2 - t1;
676 if (ela0 > _stats_max[0]) _stats_max[0] = ela0;
677 if (ela1 > _stats_max[1]) _stats_max[1] = ela1;
678 _stats_avg[0] += ela0;
679 _stats_avg[1] += ela1;
686 LuaProc::add_state (XMLNode* root) const
690 LocaleGuard lg(X_("C"));
692 gchar* b64 = g_base64_encode ((const guchar*)_script.c_str (), _script.size ());
693 std::string b64s (b64);
695 XMLNode* script_node = new XMLNode (X_("script"));
696 script_node->add_property (X_("lua"), LUA_VERSION);
697 script_node->add_content (b64s);
698 root->add_child_nocopy (*script_node);
700 for (uint32_t i = 0; i < parameter_count(); ++i) {
701 if (parameter_is_input(i) && parameter_is_control(i)) {
702 child = new XMLNode("Port");
703 snprintf(buf, sizeof(buf), "%u", i);
704 child->add_property("id", std::string(buf));
705 snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
706 child->add_property("value", std::string(buf));
707 root->add_child_nocopy(*child);
713 LuaProc::set_script_from_state (const XMLNode& node)
716 if (node.name () != state_node_name ()) {
720 if ((child = node.child (X_("script"))) != 0) {
721 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
722 if (!(*n)->is_content ()) { continue; }
724 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
725 _script = std::string ((const char*)buf, size);
727 if (load_script ()) {
728 PBD::error << _("Failed to load Lua script from session state.") << endmsg;
730 std::cerr << "Failed Lua Script: " << _script << std::endl;
737 if (_script.empty ()) {
738 PBD::error << _("Session State for LuaProcessor did not include a Lua script.") << endmsg;
742 PBD::error << _("Invalid/incompatible Lua script found for LuaProcessor.") << endmsg;
749 LuaProc::set_state (const XMLNode& node, int version)
751 #ifndef NO_PLUGIN_STATE
754 XMLNodeConstIterator iter;
760 LocaleGuard lg (X_("C"));
762 if (_script.empty ()) {
763 if (set_script_from_state (node)) {
768 #ifndef NO_PLUGIN_STATE
769 if (node.name() != state_node_name()) {
770 error << _("Bad node sent to LuaProc::set_state") << endmsg;
774 nodes = node.children ("Port");
775 for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
777 if ((prop = child->property("id")) != 0) {
778 port = prop->value().c_str();
780 warning << _("LuaProc: port has no symbol, ignored") << endmsg;
783 if ((prop = child->property("value")) != 0) {
784 value = prop->value().c_str();
786 warning << _("LuaProc: port has no value, ignored") << endmsg;
789 sscanf (port, "%" PRIu32, &port_id);
790 set_parameter (port_id, atof(value));
794 return Plugin::set_state (node, version);
798 LuaProc::parameter_count () const
800 return _ctrl_params.size ();
804 LuaProc::default_value (uint32_t port)
806 if (_ctrl_params[port].first) {
810 int lp = _ctrl_params[port].second;
811 return _param_desc[lp].normal;
815 LuaProc::set_parameter (uint32_t port, float val)
817 assert (port < parameter_count ());
818 if (get_parameter (port) == val) {
821 _shadow_data[port] = val;
822 Plugin::set_parameter (port, val);
826 LuaProc::get_parameter (uint32_t port) const
828 if (parameter_is_input (port)) {
829 return _shadow_data[port];
831 return _control_data[port];
836 LuaProc::get_parameter_descriptor (uint32_t port, ParameterDescriptor& desc) const
838 assert (port <= parameter_count ());
839 int lp = _ctrl_params[port].second;
840 const ParameterDescriptor& d (_param_desc.find(lp)->second);
842 desc.lower = d.lower;
843 desc.upper = d.upper;
844 desc.normal = d.normal;
845 desc.toggled = d.toggled;
846 desc.logarithmic = d.logarithmic;
847 desc.integer_step = d.integer_step;
848 desc.sr_dependent = d.sr_dependent;
849 desc.enumeration = d.enumeration;
851 desc.label = d.label;
852 desc.scale_points = d.scale_points;
854 desc.update_steps ();
859 LuaProc::get_parameter_docs (uint32_t port) const {
860 assert (port <= parameter_count ());
861 int lp = _ctrl_params[port].second;
862 return _param_doc.find(lp)->second;
866 LuaProc::nth_parameter (uint32_t port, bool& ok) const
868 if (port < _ctrl_params.size ()) {
877 LuaProc::parameter_is_input (uint32_t port) const
879 assert (port < _ctrl_params.size ());
880 return (!_ctrl_params[port].first);
884 LuaProc::parameter_is_output (uint32_t port) const
886 assert (port < _ctrl_params.size ());
887 return (_ctrl_params[port].first);
890 std::set<Evoral::Parameter>
891 LuaProc::automatable () const
893 std::set<Evoral::Parameter> automatables;
894 for (uint32_t i = 0; i < _ctrl_params.size (); ++i) {
895 if (parameter_is_input (i)) {
896 automatables.insert (automatables.end (), Evoral::Parameter (PluginAutomation, 0, i));
903 LuaProc::describe_parameter (Evoral::Parameter param)
905 if (param.type () == PluginAutomation && param.id () < parameter_count ()) {
906 int lp = _ctrl_params[param.id ()].second;
907 return _param_desc[lp].label;
913 LuaProc::print_parameter (uint32_t param, char* buf, uint32_t len) const
916 if (param < parameter_count ()) {
917 snprintf (buf, len, "%.3f", get_parameter (param));
924 boost::shared_ptr<ScalePoints>
925 LuaProc::parse_scale_points (luabridge::LuaRef* lr)
927 if (!(*lr)["scalepoints"].isTable()) {
928 return boost::shared_ptr<ScalePoints> ();
932 boost::shared_ptr<ScalePoints> rv = boost::shared_ptr<ScalePoints>(new ScalePoints());
933 luabridge::LuaRef scalepoints ((*lr)["scalepoints"]);
935 for (luabridge::Iterator i (scalepoints); !i.isNil (); ++i) {
936 if (!i.key ().isString ()) { continue; }
937 if (!i.value ().isNumber ()) { continue; }
938 rv->insert(make_pair(i.key ().cast<std::string> (),
939 i.value ().cast<float> ()));
943 if (rv->size() > 0) {
946 return boost::shared_ptr<ScalePoints> ();
949 boost::shared_ptr<ScalePoints>
950 LuaProc::get_scale_points (uint32_t port) const
952 int lp = _ctrl_params[port].second;
953 return _param_desc.find(lp)->second.scale_points;
957 LuaProc::setup_lua_inline_gui (LuaState *lua_gui)
959 lua_State* LG = lua_gui->getState ();
960 LuaBindings::stddef (LG);
961 LuaBindings::common (LG);
962 LuaBindings::dsp (LG);
965 lua_gui->Print.connect (sigc::mem_fun (*this, &LuaProc::lua_print));
968 lua_gui->do_command ("function ardour () end");
969 lua_gui->do_command (_script);
971 // TODO think: use a weak-pointer here ?
972 // (the GUI itself uses a shared ptr to this plugin, so we should be good)
973 luabridge::getGlobalNamespace (LG)
974 .beginNamespace ("Ardour")
975 .beginClass <LuaProc> ("LuaProc")
976 .addFunction ("shmem", &LuaProc::instance_shm)
980 luabridge::push <LuaProc *> (LG, this);
981 lua_setglobal (LG, "self");
983 luabridge::push <float *> (LG, _shadow_data);
984 lua_setglobal (LG, "CtrlPorts");
987 ////////////////////////////////////////////////////////////////////////////////
988 #include <glibmm/miscutils.h>
989 #include <glibmm/fileutils.h>
991 LuaPluginInfo::LuaPluginInfo (LuaScriptInfoPtr lsi) {
992 if (lsi->type != LuaScriptInfo::DSP) {
993 throw failed_constructor ();
998 creator = lsi->author;
999 category = lsi->category;
1000 unique_id = "luascript"; // the interpreter is not unique.
1002 n_inputs.set (DataType::AUDIO, 1);
1003 n_outputs.set (DataType::AUDIO, 1);
1008 LuaPluginInfo::load (Session& session)
1010 std::string script = "";
1011 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
1012 return PluginPtr ();
1016 script = Glib::file_get_contents (path);
1017 } catch (Glib::FileError err) {
1018 return PluginPtr ();
1021 if (script.empty ()) {
1022 return PluginPtr ();
1026 PluginPtr plugin (new LuaProc (session.engine (), session, script));
1028 } catch (failed_constructor& err) {
1031 return PluginPtr ();
1034 std::vector<Plugin::PresetRecord>
1035 LuaPluginInfo::get_presets (bool /*user_only*/) const
1037 std::vector<Plugin::PresetRecord> p;