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;
117 lua.Print.connect (sigc::mem_fun (*this, &LuaProc::lua_print));
118 // register session object
119 lua_State* L = lua.getState ();
120 LuaBindings::stddef (L);
121 LuaBindings::common (L);
122 LuaBindings::dsp (L);
124 luabridge::getGlobalNamespace (L)
125 .beginNamespace ("Ardour")
126 .beginClass <LuaProc> ("LuaProc")
127 .addFunction ("queue_draw", &LuaProc::queue_draw)
128 .addFunction ("shmem", &LuaProc::instance_shm)
132 // add session to global lua namespace
133 luabridge::push <Session *> (L, &_session);
134 lua_setglobal (L, "Session");
137 luabridge::push <LuaProc *> (L, this);
138 lua_setglobal (L, "self");
141 lua.do_command ("io = nil os = nil loadfile = nil require = nil dofile = nil package = nil debug = nil");
143 lua.do_command ("for n in pairs(_G) do print(n) end print ('----')"); // print global env
145 lua.do_command ("function ardour () end");
149 LuaProc::lua_print (std::string s) {
150 std::cout <<"LuaProc: " << s << "\n";
151 PBD::error << "LuaProc: " << s << "\n";
155 LuaProc::load_script ()
157 assert (!_lua_dsp); // don't allow to re-initialize
158 LuaPluginInfoPtr lpi;
160 // TODO: refine APIs; function arguments..
161 // - perform channel-map in ardour (silent/scratch buffers) ?
162 // - control-port API (explicit get/set functions ??)
163 // - latency reporting (global var? ctrl-port? set-function ?)
164 // - MIDI -> sparse table of events
165 // { [sample] => { Event }, .. }
166 // or { { sample, Event }, .. }
169 LuaScriptInfoPtr lsi = LuaScripting::script_info (_script);
170 lpi = LuaPluginInfoPtr (new LuaPluginInfo (lsi));
173 _mempool.set_name ("LuaProc: " + lsi->name);
174 _docs = lsi->description;
175 } catch (failed_constructor& err) {
179 lua_State* L = lua.getState ();
180 lua.do_command (_script);
182 // check if script has a DSP callback
183 luabridge::LuaRef lua_dsp_run = luabridge::getGlobal (L, "dsp_run");
184 luabridge::LuaRef lua_dsp_map = luabridge::getGlobal (L, "dsp_runmap");
186 if ((lua_dsp_run.type () != LUA_TFUNCTION) == (lua_dsp_map.type () != LUA_TFUNCTION)) {
190 if (lua_dsp_run.type () == LUA_TFUNCTION) {
191 _lua_dsp = new luabridge::LuaRef (lua_dsp_run);
193 else if (lua_dsp_map.type () == LUA_TFUNCTION) {
194 _lua_dsp = new luabridge::LuaRef (lua_dsp_map);
195 _lua_does_channelmapping = true;
201 // initialize the DSP if needed
202 luabridge::LuaRef lua_dsp_init = luabridge::getGlobal (L, "dsp_init");
203 if (lua_dsp_init.type () == LUA_TFUNCTION) {
205 lua_dsp_init (_session.nominal_frame_rate ());
206 } catch (luabridge::LuaException const& e) {
211 luabridge::LuaRef lua_dsp_midi_in = luabridge::getGlobal (L, "dsp_midi_input");
212 if (lua_dsp_midi_in.type () == LUA_TFUNCTION) {
214 _has_midi_input = lua_dsp_midi_in ();
215 } catch (luabridge::LuaException const& e) {
219 lpi->_is_instrument = _has_midi_input;
221 _ctrl_params.clear ();
223 luabridge::LuaRef lua_render = luabridge::getGlobal (L, "render_inline");
224 if (lua_render.isFunction ()) {
225 _lua_has_inline_display = true;
228 luabridge::LuaRef lua_params = luabridge::getGlobal (L, "dsp_params");
229 if (lua_params.isFunction ()) {
231 // call function // add try {} catch (luabridge::LuaException const& e)
232 luabridge::LuaRef params = lua_params ();
234 if (params.isTable ()) {
236 for (luabridge::Iterator i (params); !i.isNil (); ++i) {
238 if (!i.key ().isNumber ()) { return false; }
239 if (!i.value ().isTable ()) { return false; }
240 if (!i.value ()["type"].isString ()) { return false; }
241 if (!i.value ()["name"].isString ()) { return false; }
242 if (!i.value ()["min"].isNumber ()) { return false; }
243 if (!i.value ()["max"].isNumber ()) { return false; }
245 int pn = i.key ().cast<int> ();
246 std::string type = i.value ()["type"].cast<std::string> ();
247 if (type == "input") {
248 if (!i.value ()["default"].isNumber ()) { return false; }
249 _ctrl_params.push_back (std::make_pair (false, pn));
251 else if (type == "output") {
252 _ctrl_params.push_back (std::make_pair (true, pn));
256 assert (pn == (int) _ctrl_params.size ());
258 //_param_desc[pn] = boost::shared_ptr<ParameterDescriptor> (new ParameterDescriptor());
259 luabridge::LuaRef lr = i.value ();
261 if (type == "input") {
262 _param_desc[pn].normal = lr["default"].cast<float> ();
264 _param_desc[pn].normal = lr["min"].cast<float> (); // output-port, no default
266 _param_desc[pn].lower = lr["min"].cast<float> ();
267 _param_desc[pn].upper = lr["max"].cast<float> ();
268 _param_desc[pn].toggled = lr["toggled"].isBoolean () && (lr["toggled"]).cast<bool> ();
269 _param_desc[pn].logarithmic = lr["logarithmic"].isBoolean () && (lr["logarithmic"]).cast<bool> ();
270 _param_desc[pn].integer_step = lr["integer"].isBoolean () && (lr["integer"]).cast<bool> ();
271 _param_desc[pn].sr_dependent = lr["ratemult"].isBoolean () && (lr["ratemult"]).cast<bool> ();
272 _param_desc[pn].enumeration = lr["enum"].isBoolean () && (lr["enum"]).cast<bool> ();
274 if (lr["unit"].isString ()) {
275 std::string unit = lr["unit"].cast<std::string> ();
276 if (unit == "dB") { _param_desc[pn].unit = ParameterDescriptor::DB; }
277 else if (unit == "Hz") { _param_desc[pn].unit = ParameterDescriptor::HZ; }
278 else if (unit == "Midi Note") { _param_desc[pn].unit = ParameterDescriptor::MIDI_NOTE; }
280 _param_desc[pn].label = (lr["name"]).cast<std::string> ();
281 _param_desc[pn].scale_points = parse_scale_points (&lr);
283 luabridge::LuaRef doc = lr["doc"];
284 if (doc.isString ()) {
285 _param_doc[pn] = doc.cast<std::string> ();
289 assert (!(_param_desc[pn].toggled && _param_desc[pn].logarithmic));
294 _control_data = new float[parameter_count ()];
295 _shadow_data = new float[parameter_count ()];
297 for (uint32_t i = 0; i < parameter_count (); ++i) {
298 if (parameter_is_input (i)) {
299 _control_data[i] = _shadow_data[i] = default_value (i);
303 // expose ctrl-ports to global lua namespace
304 luabridge::push <float *> (L, _control_data);
305 lua_setglobal (L, "CtrlPorts");
307 return false; // no error
311 LuaProc::can_support_io_configuration (const ChanCount& in, ChanCount& out, ChanCount* imprecise)
313 // caller must hold process lock (no concurrent calls to interpreter
314 _output_configs.clear ();
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 *_iotable = NULL; // can't use reference :(
328 luabridge::LuaRef iotable = ioconfig ();
329 if (iotable.isTable ()) {
330 _iotable = new luabridge::LuaRef (iotable);
332 } catch (luabridge::LuaException const& e) {
340 // now we can reference it.
341 luabridge::LuaRef iotable (*_iotable);
344 if ((iotable).length () < 1) {
349 bool exact_match = false;
350 const int32_t audio_in = in.n_audio ();
351 int32_t midi_out = 0; // TODO handle _has_midi_output
353 // preferred setting (provided by plugin_insert)
354 assert (out.n_audio () > 0);
355 const int preferred_out = out.n_audio ();
357 for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
358 assert (i.value ().type () == LUA_TTABLE);
359 luabridge::LuaRef io (i.value ());
361 int possible_in = io["audio_in"];
362 int possible_out = io["audio_out"];
365 if ((possible_in == audio_in) && (possible_out == preferred_out)) {
366 _output_configs.insert (preferred_out);
373 /* now allow potentially "imprecise" matches */
374 int32_t audio_out = -1;
375 float penalty = 9999;
377 #define FOUNDCFG(nch) { \
378 float p = fabsf ((float)(nch) - preferred_out); \
379 _output_configs.insert (nch); \
380 if ((nch) > preferred_out) { p *= 1.1; } \
388 #define ANYTHINGGOES \
389 _output_configs.insert (0);
391 #define UPTO(nch) { \
392 for (int n = 1; n < nch; ++n) { \
393 _output_configs.insert (n); \
397 for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
398 assert (i.value ().type () == LUA_TTABLE);
399 luabridge::LuaRef io (i.value ());
401 int possible_in = io["audio_in"];
402 int possible_out = io["audio_out"];
404 if (possible_out == 0) {
407 if (possible_in == 0) {
408 /* no inputs, generators & instruments */
409 if (possible_out == -1) {
410 /* any configuration possible, stereo output */
411 FOUNDCFG (preferred_out);
413 } else if (possible_out == -2) {
414 /* invalid, should be (0, -1) */
415 FOUNDCFG (preferred_out);
417 } else if (possible_out < -2) {
418 /* variable number of outputs up to -N, */
419 FOUNDCFG (min (-possible_out, preferred_out));
420 UPTO (-possible_out);
422 /* exact number of outputs */
423 FOUNDCFG (possible_out);
427 if (possible_in == -1) {
428 /* wildcard for input */
429 if (possible_out == -1) {
430 /* out must match in */
432 } else if (possible_out == -2) {
433 /* any configuration possible, pick matching */
434 FOUNDCFG (preferred_out);
436 } else if (possible_out < -2) {
437 /* explicitly variable number of outputs, pick maximum */
438 FOUNDCFG (max (-possible_out, preferred_out));
439 /* and try min, too, in case the penalty is lower */
440 FOUNDCFG (min (-possible_out, preferred_out));
443 /* exact number of outputs */
444 FOUNDCFG (possible_out);
448 if (possible_in == -2) {
449 if (possible_out == -1) {
450 /* any configuration possible, pick matching */
451 FOUNDCFG (preferred_out);
453 } else if (possible_out == -2) {
454 /* invalid. interpret as (-1, -1) */
455 FOUNDCFG (preferred_out);
457 } else if (possible_out < -2) {
458 /* invalid, interpret as (<-2, <-2)
459 * variable number of outputs up to -N, */
460 FOUNDCFG (min (-possible_out, preferred_out));
463 /* exact number of outputs */
464 FOUNDCFG (possible_out);
468 if (possible_in < -2) {
469 /* explicit variable number of inputs */
470 if (audio_in > -possible_in && imprecise != NULL) {
472 imprecise->set (DataType::AUDIO, -possible_in);
475 if (audio_in > -possible_in && imprecise == NULL) {
476 /* request is too large */
477 } else if (possible_out == -1) {
478 /* any output configuration possible */
479 FOUNDCFG (preferred_out);
481 } else if (possible_out == -2) {
482 /* invalid. interpret as (<-2, -1) */
483 FOUNDCFG (preferred_out);
485 } else if (possible_out < -2) {
486 /* variable number of outputs up to -N, */
487 FOUNDCFG (min (-possible_out, preferred_out));
490 /* exact number of outputs */
491 FOUNDCFG (possible_out);
495 if (possible_in && (possible_in == audio_in)) {
496 /* exact number of inputs ... must match obviously */
497 if (possible_out == -1) {
498 /* any output configuration possible */
499 FOUNDCFG (preferred_out);
501 } else if (possible_out == -2) {
502 /* invalid. interpret as (>0, -1) */
503 FOUNDCFG (preferred_out);
505 } else if (possible_out < -2) {
506 /* > 0, < -2 is not specified
507 * interpret as up to -N */
508 FOUNDCFG (min (-possible_out, preferred_out));
511 /* exact number of outputs */
512 FOUNDCFG (possible_out);
517 if (!found && imprecise) {
519 for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
520 assert (i.value ().type () == LUA_TTABLE);
521 luabridge::LuaRef io (i.value ());
523 int possible_in = io["audio_in"];
524 int possible_out = io["audio_out"];
526 assert (possible_in > 0); // all other cases will have been matched above
527 assert (possible_out !=0 || possible_in !=0); // already handled above
529 imprecise->set (DataType::AUDIO, possible_in);
530 if (possible_out == -1 || possible_out == -2) {
532 } else if (possible_out < -2) {
533 /* explicitly variable number of outputs, pick maximum */
534 FOUNDCFG (min (-possible_out, preferred_out));
536 /* exact number of outputs */
537 FOUNDCFG (possible_out);
539 // ideally we'll also find the closest, best matching
540 // input configuration with minimal output penalty...
549 out.set (DataType::MIDI, midi_out); // currently always zero
550 out.set (DataType::AUDIO, preferred_out);
552 out.set (DataType::MIDI, midi_out); // currently always zero
553 out.set (DataType::AUDIO, audio_out);
559 LuaProc::configure_io (ChanCount in, ChanCount out)
562 _configured_out = out;
564 _configured_in.set (DataType::MIDI, _has_midi_input ? 1 : 0);
565 _configured_out.set (DataType::MIDI, _has_midi_output ? 1 : 0);
567 // configure the DSP if needed
568 lua_State* L = lua.getState ();
569 luabridge::LuaRef lua_dsp_configure = luabridge::getGlobal (L, "dsp_configure");
570 if (lua_dsp_configure.type () == LUA_TFUNCTION) {
572 lua_dsp_configure (&in, &out);
573 } catch (luabridge::LuaException const& e) {
578 _info->n_inputs = _configured_in;
579 _info->n_outputs = _configured_out;
584 LuaProc::connect_and_run (BufferSet& bufs,
585 ChanMapping in, ChanMapping out,
586 pframes_t nframes, framecnt_t offset)
592 Plugin::connect_and_run (bufs, in, out, nframes, offset);
594 // This is needed for ARDOUR::Session requests :(
595 if (! SessionEvent::has_per_thread_pool ()) {
597 snprintf (name, 64, "Proc-%p", this);
598 pthread_set_name (name);
599 SessionEvent::create_per_thread_pool (name, 64);
600 PBD::notify_event_loops_about_thread_creation (pthread_self(), name, 64);
603 uint32_t const n = parameter_count ();
604 for (uint32_t i = 0; i < n; ++i) {
605 if (parameter_is_control (i) && parameter_is_input (i)) {
606 _control_data[i] = _shadow_data[i];
610 #ifdef WITH_LUAPROC_STATS
611 int64_t t0 = g_get_monotonic_time ();
615 if (_lua_does_channelmapping) {
616 // run the DSP function
617 (*_lua_dsp)(&bufs, in, out, nframes, offset);
620 BufferSet& silent_bufs = _session.get_silent_buffers (ChanCount (DataType::AUDIO, 1));
621 BufferSet& scratch_bufs = _session.get_scratch_buffers (ChanCount (DataType::AUDIO, 1));
623 lua_State* L = lua.getState ();
624 luabridge::LuaRef in_map (luabridge::newTable (L));
625 luabridge::LuaRef out_map (luabridge::newTable (L));
627 const uint32_t audio_in = _configured_in.n_audio ();
628 const uint32_t audio_out = _configured_out.n_audio ();
629 const uint32_t midi_in = _configured_in.n_midi ();
631 for (uint32_t ap = 0; ap < audio_in; ++ap) {
633 const uint32_t buf_index = in.get(DataType::AUDIO, ap, &valid);
635 in_map[ap + 1] = bufs.get_audio (buf_index).data (offset);
637 in_map[ap + 1] = silent_bufs.get_audio (0).data (offset);
640 for (uint32_t ap = 0; ap < audio_out; ++ap) {
642 const uint32_t buf_index = out.get(DataType::AUDIO, ap, &valid);
644 out_map[ap + 1] = bufs.get_audio (buf_index).data (offset);
646 out_map[ap + 1] = scratch_bufs.get_audio (0).data (offset);
650 luabridge::LuaRef lua_midi_tbl (luabridge::newTable (L));
651 int e = 1; // > 1 port, we merge events (unsorted)
652 for (uint32_t mp = 0; mp < midi_in; ++mp) {
654 const uint32_t idx = in.get(DataType::MIDI, mp, &valid);
656 for (MidiBuffer::iterator m = bufs.get_midi(idx).begin();
657 m != bufs.get_midi(idx).end(); ++m, ++e) {
658 const Evoral::MIDIEvent<framepos_t> ev(*m, false);
659 luabridge::LuaRef lua_midi_data (luabridge::newTable (L));
660 const uint8_t* data = ev.buffer();
661 for (uint32_t i = 0; i < ev.size(); ++i) {
662 lua_midi_data [i + 1] = data[i];
664 luabridge::LuaRef lua_midi_event (luabridge::newTable (L));
665 lua_midi_event["time"] = 1 + (*m).time();
666 lua_midi_event["data"] = lua_midi_data;
667 lua_midi_tbl[e] = lua_midi_event;
672 if (_has_midi_input) {
673 // XXX TODO This needs a better solution than global namespace
674 luabridge::push (L, lua_midi_tbl);
675 lua_setglobal (L, "mididata");
679 // run the DSP function
680 (*_lua_dsp)(in_map, out_map, nframes);
682 } catch (luabridge::LuaException const& e) {
683 PBD::error << "LuaException: " << e.what () << "\n";
685 std::cerr << "LuaException: " << e.what () << "\n";
689 #ifdef WITH_LUAPROC_STATS
690 int64_t t1 = g_get_monotonic_time ();
692 lua.collect_garbage (); // rt-safe, slight *regular* performance overhead
693 #ifdef WITH_LUAPROC_STATS
695 int64_t t2 = g_get_monotonic_time ();
696 int64_t ela0 = t1 - t0;
697 int64_t ela1 = t2 - t1;
698 if (ela0 > _stats_max[0]) _stats_max[0] = ela0;
699 if (ela1 > _stats_max[1]) _stats_max[1] = ela1;
700 _stats_avg[0] += ela0;
701 _stats_avg[1] += ela1;
708 LuaProc::add_state (XMLNode* root) const
712 LocaleGuard lg(X_("C"));
714 gchar* b64 = g_base64_encode ((const guchar*)_script.c_str (), _script.size ());
715 std::string b64s (b64);
717 XMLNode* script_node = new XMLNode (X_("script"));
718 script_node->add_property (X_("lua"), LUA_VERSION);
719 script_node->add_content (b64s);
720 root->add_child_nocopy (*script_node);
722 for (uint32_t i = 0; i < parameter_count(); ++i) {
723 if (parameter_is_input(i) && parameter_is_control(i)) {
724 child = new XMLNode("Port");
725 snprintf(buf, sizeof(buf), "%u", i);
726 child->add_property("id", std::string(buf));
727 snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
728 child->add_property("value", std::string(buf));
729 root->add_child_nocopy(*child);
735 LuaProc::set_script_from_state (const XMLNode& node)
738 if (node.name () != state_node_name ()) {
742 if ((child = node.child (X_("script"))) != 0) {
743 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
744 if (!(*n)->is_content ()) { continue; }
746 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
747 _script = std::string ((const char*)buf, size);
749 if (load_script ()) {
750 PBD::error << _("Failed to load Lua script from session state.") << endmsg;
752 std::cerr << "Failed Lua Script: " << _script << std::endl;
759 if (_script.empty ()) {
760 PBD::error << _("Session State for LuaProcessor did not include a Lua script.") << endmsg;
764 PBD::error << _("Invalid/incompatible Lua script found for LuaProcessor.") << endmsg;
771 LuaProc::set_state (const XMLNode& node, int version)
773 #ifndef NO_PLUGIN_STATE
776 XMLNodeConstIterator iter;
782 LocaleGuard lg (X_("C"));
784 if (_script.empty ()) {
785 if (set_script_from_state (node)) {
790 #ifndef NO_PLUGIN_STATE
791 if (node.name() != state_node_name()) {
792 error << _("Bad node sent to LuaProc::set_state") << endmsg;
796 nodes = node.children ("Port");
797 for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
799 if ((prop = child->property("id")) != 0) {
800 port = prop->value().c_str();
802 warning << _("LuaProc: port has no symbol, ignored") << endmsg;
805 if ((prop = child->property("value")) != 0) {
806 value = prop->value().c_str();
808 warning << _("LuaProc: port has no value, ignored") << endmsg;
811 sscanf (port, "%" PRIu32, &port_id);
812 set_parameter (port_id, atof(value));
816 return Plugin::set_state (node, version);
820 LuaProc::parameter_count () const
822 return _ctrl_params.size ();
826 LuaProc::default_value (uint32_t port)
828 if (_ctrl_params[port].first) {
832 int lp = _ctrl_params[port].second;
833 return _param_desc[lp].normal;
837 LuaProc::set_parameter (uint32_t port, float val)
839 assert (port < parameter_count ());
840 if (get_parameter (port) == val) {
843 _shadow_data[port] = val;
844 Plugin::set_parameter (port, val);
848 LuaProc::get_parameter (uint32_t port) const
850 if (parameter_is_input (port)) {
851 return _shadow_data[port];
853 return _control_data[port];
858 LuaProc::get_parameter_descriptor (uint32_t port, ParameterDescriptor& desc) const
860 assert (port <= parameter_count ());
861 int lp = _ctrl_params[port].second;
862 const ParameterDescriptor& d (_param_desc.find(lp)->second);
864 desc.lower = d.lower;
865 desc.upper = d.upper;
866 desc.normal = d.normal;
867 desc.toggled = d.toggled;
868 desc.logarithmic = d.logarithmic;
869 desc.integer_step = d.integer_step;
870 desc.sr_dependent = d.sr_dependent;
871 desc.enumeration = d.enumeration;
873 desc.label = d.label;
874 desc.scale_points = d.scale_points;
876 desc.update_steps ();
881 LuaProc::get_parameter_docs (uint32_t port) const {
882 assert (port <= parameter_count ());
883 int lp = _ctrl_params[port].second;
884 return _param_doc.find(lp)->second;
888 LuaProc::nth_parameter (uint32_t port, bool& ok) const
890 if (port < _ctrl_params.size ()) {
899 LuaProc::parameter_is_input (uint32_t port) const
901 assert (port < _ctrl_params.size ());
902 return (!_ctrl_params[port].first);
906 LuaProc::parameter_is_output (uint32_t port) const
908 assert (port < _ctrl_params.size ());
909 return (_ctrl_params[port].first);
912 std::set<Evoral::Parameter>
913 LuaProc::automatable () const
915 std::set<Evoral::Parameter> automatables;
916 for (uint32_t i = 0; i < _ctrl_params.size (); ++i) {
917 if (parameter_is_input (i)) {
918 automatables.insert (automatables.end (), Evoral::Parameter (PluginAutomation, 0, i));
925 LuaProc::describe_parameter (Evoral::Parameter param)
927 if (param.type () == PluginAutomation && param.id () < parameter_count ()) {
928 int lp = _ctrl_params[param.id ()].second;
929 return _param_desc[lp].label;
935 LuaProc::print_parameter (uint32_t param, char* buf, uint32_t len) const
938 if (param < parameter_count ()) {
939 snprintf (buf, len, "%.3f", get_parameter (param));
946 boost::shared_ptr<ScalePoints>
947 LuaProc::parse_scale_points (luabridge::LuaRef* lr)
949 if (!(*lr)["scalepoints"].isTable()) {
950 return boost::shared_ptr<ScalePoints> ();
954 boost::shared_ptr<ScalePoints> rv = boost::shared_ptr<ScalePoints>(new ScalePoints());
955 luabridge::LuaRef scalepoints ((*lr)["scalepoints"]);
957 for (luabridge::Iterator i (scalepoints); !i.isNil (); ++i) {
958 if (!i.key ().isString ()) { continue; }
959 if (!i.value ().isNumber ()) { continue; }
960 rv->insert(make_pair(i.key ().cast<std::string> (),
961 i.value ().cast<float> ()));
965 if (rv->size() > 0) {
968 return boost::shared_ptr<ScalePoints> ();
971 boost::shared_ptr<ScalePoints>
972 LuaProc::get_scale_points (uint32_t port) const
974 int lp = _ctrl_params[port].second;
975 return _param_desc.find(lp)->second.scale_points;
979 LuaProc::setup_lua_inline_gui (LuaState *lua_gui)
981 lua_State* LG = lua_gui->getState ();
982 LuaBindings::stddef (LG);
983 LuaBindings::common (LG);
984 LuaBindings::dsp (LG);
986 lua_gui->Print.connect (sigc::mem_fun (*this, &LuaProc::lua_print));
987 lua_gui->do_command ("function ardour () end");
988 lua_gui->do_command (_script);
990 // TODO think: use a weak-pointer here ?
991 // (the GUI itself uses a shared ptr to this plugin, so we should be good)
992 luabridge::getGlobalNamespace (LG)
993 .beginNamespace ("Ardour")
994 .beginClass <LuaProc> ("LuaProc")
995 .addFunction ("shmem", &LuaProc::instance_shm)
999 luabridge::push <LuaProc *> (LG, this);
1000 lua_setglobal (LG, "self");
1002 luabridge::push <float *> (LG, _shadow_data);
1003 lua_setglobal (LG, "CtrlPorts");
1006 ////////////////////////////////////////////////////////////////////////////////
1007 #include <glibmm/miscutils.h>
1008 #include <glibmm/fileutils.h>
1010 LuaPluginInfo::LuaPluginInfo (LuaScriptInfoPtr lsi) {
1011 if (lsi->type != LuaScriptInfo::DSP) {
1012 throw failed_constructor ();
1017 creator = lsi->author;
1018 category = lsi->category;
1019 unique_id = "luascript"; // the interpreter is not unique.
1021 n_inputs.set (DataType::AUDIO, 1);
1022 n_outputs.set (DataType::AUDIO, 1);
1027 LuaPluginInfo::load (Session& session)
1029 std::string script = "";
1030 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
1031 return PluginPtr ();
1035 script = Glib::file_get_contents (path);
1036 } catch (Glib::FileError err) {
1037 return PluginPtr ();
1040 if (script.empty ()) {
1041 return PluginPtr ();
1045 PluginPtr plugin (new LuaProc (session.engine (), session, script));
1047 } catch (failed_constructor& err) {
1050 return PluginPtr ();
1053 std::vector<Plugin::PresetRecord>
1054 LuaPluginInfo::get_presets (bool /*user_only*/) const
1056 std::vector<Plugin::PresetRecord> p;