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 <glibmm/miscutils.h>
22 #include <glibmm/fileutils.h>
24 #include "pbd/gstdio_compat.h"
26 #include "pbd/pthread_utils.h"
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"
38 #include "LuaBridge/LuaBridge.h"
42 using namespace ARDOUR;
45 LuaProc::LuaProc (AudioEngine& engine,
47 const std::string &script)
48 : Plugin (engine, session)
49 , _mempool ("LuaProc", 1048576) // 1 MB is plenty. (64K would be enough)
50 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
53 , _lua_does_channelmapping (false)
54 , _lua_has_inline_display (false)
57 , _has_midi_input (false)
58 , _has_midi_output (false)
62 /* when loading a session, or pasing a processor,
63 * the script is set during set_state();
65 if (!_script.empty () && load_script ()) {
66 throw failed_constructor ();
70 LuaProc::LuaProc (const LuaProc &other)
72 , _mempool ("LuaProc", 1048576) // 1 MB is plenty. (64K would be enough)
73 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
75 , _script (other.script ())
76 , _lua_does_channelmapping (false)
77 , _lua_has_inline_display (false)
80 , _has_midi_input (false)
81 , _has_midi_output (false)
86 throw failed_constructor ();
89 for (uint32_t i = 0; i < parameter_count (); ++i) {
90 _control_data[i] = other._shadow_data[i];
91 _shadow_data[i] = other._shadow_data[i];
95 LuaProc::~LuaProc () {
96 #ifdef WITH_LUAPROC_STATS
97 if (_info && _stats_cnt > 0) {
98 printf ("LuaProc: '%s' run() avg: %.3f max: %.3f [ms]\n",
100 0.0001f * _stats_avg[0] / (float) _stats_cnt,
101 0.0001f * _stats_max[0]);
102 printf ("LuaProc: '%s' gc() avg: %.3f max: %.3f [ms]\n",
103 _info->name.c_str (),
104 0.0001f * _stats_avg[1] / (float) _stats_cnt,
105 0.0001f * _stats_max[1]);
108 lua.do_command ("collectgarbage();");
110 delete [] _control_data;
111 delete [] _shadow_data;
117 #ifdef WITH_LUAPROC_STATS
118 _stats_avg[0] = _stats_avg[1] = _stats_max[0] = _stats_max[1] = _stats_cnt = 0;
121 lua.Print.connect (sigc::mem_fun (*this, &LuaProc::lua_print));
122 // register session object
123 lua_State* L = lua.getState ();
124 LuaBindings::stddef (L);
125 LuaBindings::common (L);
126 LuaBindings::dsp (L);
128 luabridge::getGlobalNamespace (L)
129 .beginNamespace ("Ardour")
130 .beginClass <LuaProc> ("LuaProc")
131 .addFunction ("queue_draw", &LuaProc::queue_draw)
132 .addFunction ("shmem", &LuaProc::instance_shm)
136 // add session to global lua namespace
137 luabridge::push <Session *> (L, &_session);
138 lua_setglobal (L, "Session");
141 luabridge::push <LuaProc *> (L, this);
142 lua_setglobal (L, "self");
145 lua.do_command ("io = nil os = nil loadfile = nil require = nil dofile = nil package = nil debug = nil");
147 lua.do_command ("for n in pairs(_G) do print(n) end print ('----')"); // print global env
149 lua.do_command ("function ardour () end");
153 LuaProc::lua_print (std::string s) {
154 std::cout <<"LuaProc: " << s << "\n";
155 PBD::error << "LuaProc: " << s << "\n";
159 LuaProc::load_script ()
161 assert (!_lua_dsp); // don't allow to re-initialize
162 LuaPluginInfoPtr lpi;
164 // TODO: refine APIs; function arguments..
165 // - perform channel-map in ardour (silent/scratch buffers) ?
166 // - control-port API (explicit get/set functions ??)
167 // - latency reporting (global var? ctrl-port? set-function ?)
168 // - MIDI -> sparse table of events
169 // { [sample] => { Event }, .. }
170 // or { { sample, Event }, .. }
173 LuaScriptInfoPtr lsi = LuaScripting::script_info (_script);
174 lpi = LuaPluginInfoPtr (new LuaPluginInfo (lsi));
177 _mempool.set_name ("LuaProc: " + lsi->name);
178 _docs = lsi->description;
179 } catch (failed_constructor& err) {
183 lua_State* L = lua.getState ();
184 lua.do_command (_script);
186 // check if script has a DSP callback
187 luabridge::LuaRef lua_dsp_run = luabridge::getGlobal (L, "dsp_run");
188 luabridge::LuaRef lua_dsp_map = luabridge::getGlobal (L, "dsp_runmap");
190 if ((lua_dsp_run.type () != LUA_TFUNCTION) == (lua_dsp_map.type () != LUA_TFUNCTION)) {
194 if (lua_dsp_run.type () == LUA_TFUNCTION) {
195 _lua_dsp = new luabridge::LuaRef (lua_dsp_run);
197 else if (lua_dsp_map.type () == LUA_TFUNCTION) {
198 _lua_dsp = new luabridge::LuaRef (lua_dsp_map);
199 _lua_does_channelmapping = true;
205 // initialize the DSP if needed
206 luabridge::LuaRef lua_dsp_init = luabridge::getGlobal (L, "dsp_init");
207 if (lua_dsp_init.type () == LUA_TFUNCTION) {
209 lua_dsp_init (_session.nominal_frame_rate ());
210 } catch (luabridge::LuaException const& e) {
216 luabridge::LuaRef lua_dsp_has_midi_in = luabridge::getGlobal (L, "dsp_has_midi_input");
217 if (lua_dsp_has_midi_in.type () == LUA_TFUNCTION) {
219 _has_midi_input = lua_dsp_has_midi_in ();
220 } catch (luabridge::LuaException const& e) {
225 luabridge::LuaRef lua_dsp_has_midi_out = luabridge::getGlobal (L, "dsp_has_midi_output");
226 if (lua_dsp_has_midi_out.type () == LUA_TFUNCTION) {
228 _has_midi_output = lua_dsp_has_midi_out ();
229 } catch (luabridge::LuaException const& e) {
234 _ctrl_params.clear ();
236 luabridge::LuaRef lua_render = luabridge::getGlobal (L, "render_inline");
237 if (lua_render.isFunction ()) {
238 _lua_has_inline_display = true;
241 luabridge::LuaRef lua_params = luabridge::getGlobal (L, "dsp_params");
242 if (lua_params.isFunction ()) {
244 // call function // add try {} catch (luabridge::LuaException const& e)
245 luabridge::LuaRef params = lua_params ();
247 if (params.isTable ()) {
249 for (luabridge::Iterator i (params); !i.isNil (); ++i) {
251 if (!i.key ().isNumber ()) { return false; }
252 if (!i.value ().isTable ()) { return false; }
253 if (!i.value ()["type"].isString ()) { return false; }
254 if (!i.value ()["name"].isString ()) { return false; }
255 if (!i.value ()["min"].isNumber ()) { return false; }
256 if (!i.value ()["max"].isNumber ()) { return false; }
258 int pn = i.key ().cast<int> ();
259 std::string type = i.value ()["type"].cast<std::string> ();
260 if (type == "input") {
261 if (!i.value ()["default"].isNumber ()) { return false; }
262 _ctrl_params.push_back (std::make_pair (false, pn));
264 else if (type == "output") {
265 _ctrl_params.push_back (std::make_pair (true, pn));
269 assert (pn == (int) _ctrl_params.size ());
271 //_param_desc[pn] = boost::shared_ptr<ParameterDescriptor> (new ParameterDescriptor());
272 luabridge::LuaRef lr = i.value ();
274 if (type == "input") {
275 _param_desc[pn].normal = lr["default"].cast<float> ();
277 _param_desc[pn].normal = lr["min"].cast<float> (); // output-port, no default
279 _param_desc[pn].lower = lr["min"].cast<float> ();
280 _param_desc[pn].upper = lr["max"].cast<float> ();
281 _param_desc[pn].toggled = lr["toggled"].isBoolean () && (lr["toggled"]).cast<bool> ();
282 _param_desc[pn].logarithmic = lr["logarithmic"].isBoolean () && (lr["logarithmic"]).cast<bool> ();
283 _param_desc[pn].integer_step = lr["integer"].isBoolean () && (lr["integer"]).cast<bool> ();
284 _param_desc[pn].sr_dependent = lr["ratemult"].isBoolean () && (lr["ratemult"]).cast<bool> ();
285 _param_desc[pn].enumeration = lr["enum"].isBoolean () && (lr["enum"]).cast<bool> ();
287 if (lr["unit"].isString ()) {
288 std::string unit = lr["unit"].cast<std::string> ();
289 if (unit == "dB") { _param_desc[pn].unit = ParameterDescriptor::DB; }
290 else if (unit == "Hz") { _param_desc[pn].unit = ParameterDescriptor::HZ; }
291 else if (unit == "Midi Note") { _param_desc[pn].unit = ParameterDescriptor::MIDI_NOTE; }
293 _param_desc[pn].label = (lr["name"]).cast<std::string> ();
294 _param_desc[pn].scale_points = parse_scale_points (&lr);
296 luabridge::LuaRef doc = lr["doc"];
297 if (doc.isString ()) {
298 _param_doc[pn] = doc.cast<std::string> ();
302 assert (!(_param_desc[pn].toggled && _param_desc[pn].logarithmic));
307 _control_data = new float[parameter_count ()];
308 _shadow_data = new float[parameter_count ()];
310 for (uint32_t i = 0; i < parameter_count (); ++i) {
311 if (parameter_is_input (i)) {
312 _control_data[i] = _shadow_data[i] = default_value (i);
316 // expose ctrl-ports to global lua namespace
317 luabridge::push <float *> (L, _control_data);
318 lua_setglobal (L, "CtrlPorts");
320 return false; // no error
324 LuaProc::can_support_io_configuration (const ChanCount& in, ChanCount& out, ChanCount* imprecise)
326 // caller must hold process lock (no concurrent calls to interpreter
327 _output_configs.clear ();
329 if (in.n_midi() > 0 && !_has_midi_input && !imprecise) {
333 lua_State* L = lua.getState ();
334 luabridge::LuaRef ioconfig = luabridge::getGlobal (L, "dsp_ioconfig");
335 if (!ioconfig.isFunction ()) {
339 luabridge::LuaRef *_iotable = NULL; // can't use reference :(
341 luabridge::LuaRef iotable = ioconfig ();
342 if (iotable.isTable ()) {
343 _iotable = new luabridge::LuaRef (iotable);
345 } catch (luabridge::LuaException const& e) {
353 // now we can reference it.
354 luabridge::LuaRef iotable (*_iotable);
357 if ((iotable).length () < 1) {
362 bool exact_match = false;
363 const int32_t audio_in = in.n_audio ();
364 int32_t midi_out = _has_midi_output ? 1 : 0;
366 // preferred setting (provided by plugin_insert)
367 assert (out.n_audio () > 0 || midi_out > 0);
368 const int preferred_out = out.n_audio ();
370 for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
371 assert (i.value ().type () == LUA_TTABLE);
372 luabridge::LuaRef io (i.value ());
374 int possible_in = io["audio_in"];
375 int possible_out = io["audio_out"];
378 if ((possible_in == audio_in) && (possible_out == preferred_out)) {
379 _output_configs.insert (preferred_out);
386 /* now allow potentially "imprecise" matches */
387 int32_t audio_out = -1;
388 float penalty = 9999;
390 #define FOUNDCFG(nch) { \
391 float p = fabsf ((float)(nch) - preferred_out); \
392 _output_configs.insert (nch); \
393 if ((nch) > preferred_out) { p *= 1.1; } \
401 #define ANYTHINGGOES \
402 _output_configs.insert (0);
404 #define UPTO(nch) { \
405 for (int n = 1; n < nch; ++n) { \
406 _output_configs.insert (n); \
410 for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
411 assert (i.value ().type () == LUA_TTABLE);
412 luabridge::LuaRef io (i.value ());
414 int possible_in = io["audio_in"];
415 int possible_out = io["audio_out"];
417 if (possible_out == 0) {
418 if (possible_in == 0) {
419 if (_has_midi_output && audio_in == 0) {
420 // special case midi filters & generators
429 if (possible_in == 0) {
430 /* no inputs, generators & instruments */
431 if (possible_out == -1) {
432 /* any configuration possible, stereo output */
433 FOUNDCFG (preferred_out);
435 } else if (possible_out == -2) {
436 /* invalid, should be (0, -1) */
437 FOUNDCFG (preferred_out);
439 } else if (possible_out < -2) {
440 /* variable number of outputs up to -N, */
441 FOUNDCFG (min (-possible_out, preferred_out));
442 UPTO (-possible_out);
444 /* exact number of outputs */
445 FOUNDCFG (possible_out);
449 if (possible_in == -1) {
450 /* wildcard for input */
451 if (possible_out == -1) {
452 /* out must match in */
454 } else if (possible_out == -2) {
455 /* any configuration possible, pick matching */
456 FOUNDCFG (preferred_out);
458 } else if (possible_out < -2) {
459 /* explicitly variable number of outputs, pick maximum */
460 FOUNDCFG (max (-possible_out, preferred_out));
461 /* and try min, too, in case the penalty is lower */
462 FOUNDCFG (min (-possible_out, preferred_out));
465 /* exact number of outputs */
466 FOUNDCFG (possible_out);
470 if (possible_in == -2) {
471 if (possible_out == -1) {
472 /* any configuration possible, pick matching */
473 FOUNDCFG (preferred_out);
475 } else if (possible_out == -2) {
476 /* invalid. interpret as (-1, -1) */
477 FOUNDCFG (preferred_out);
479 } else if (possible_out < -2) {
480 /* invalid, interpret as (<-2, <-2)
481 * variable number of outputs up to -N, */
482 FOUNDCFG (min (-possible_out, preferred_out));
485 /* exact number of outputs */
486 FOUNDCFG (possible_out);
490 if (possible_in < -2) {
491 /* explicit variable number of inputs */
492 if (audio_in > -possible_in && imprecise != NULL) {
494 imprecise->set (DataType::AUDIO, -possible_in);
497 if (audio_in > -possible_in && imprecise == NULL) {
498 /* request is too large */
499 } else if (possible_out == -1) {
500 /* any output configuration possible */
501 FOUNDCFG (preferred_out);
503 } else if (possible_out == -2) {
504 /* invalid. interpret as (<-2, -1) */
505 FOUNDCFG (preferred_out);
507 } else if (possible_out < -2) {
508 /* variable number of outputs up to -N, */
509 FOUNDCFG (min (-possible_out, preferred_out));
512 /* exact number of outputs */
513 FOUNDCFG (possible_out);
517 if (possible_in && (possible_in == audio_in)) {
518 /* exact number of inputs ... must match obviously */
519 if (possible_out == -1) {
520 /* any output configuration possible */
521 FOUNDCFG (preferred_out);
523 } else if (possible_out == -2) {
524 /* invalid. interpret as (>0, -1) */
525 FOUNDCFG (preferred_out);
527 } else if (possible_out < -2) {
528 /* > 0, < -2 is not specified
529 * interpret as up to -N */
530 FOUNDCFG (min (-possible_out, preferred_out));
533 /* exact number of outputs */
534 FOUNDCFG (possible_out);
539 if (!found && imprecise) {
541 for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
542 assert (i.value ().type () == LUA_TTABLE);
543 luabridge::LuaRef io (i.value ());
545 int possible_in = io["audio_in"];
546 int possible_out = io["audio_out"];
548 if (possible_out == 0 && possible_in == 0 && _has_midi_output) {
549 assert (audio_in > 0); // no input is handled above
550 // TODO hide audio input from plugin
551 imprecise->set (DataType::AUDIO, 0);
557 assert (possible_in > 0); // all other cases will have been matched above
558 assert (possible_out !=0 || possible_in !=0); // already handled above
560 imprecise->set (DataType::AUDIO, possible_in);
561 if (possible_out == -1 || possible_out == -2) {
563 } else if (possible_out < -2) {
564 /* explicitly variable number of outputs, pick maximum */
565 FOUNDCFG (min (-possible_out, preferred_out));
567 /* exact number of outputs */
568 FOUNDCFG (possible_out);
570 // ideally we'll also find the closest, best matching
571 // input configuration with minimal output penalty...
580 out.set (DataType::MIDI, midi_out);
581 out.set (DataType::AUDIO, preferred_out);
583 out.set (DataType::MIDI, midi_out);
584 out.set (DataType::AUDIO, audio_out);
590 LuaProc::configure_io (ChanCount in, ChanCount out)
593 _configured_out = out;
595 _configured_in.set (DataType::MIDI, _has_midi_input ? 1 : 0);
596 _configured_out.set (DataType::MIDI, _has_midi_output ? 1 : 0);
598 // configure the DSP if needed
599 lua_State* L = lua.getState ();
600 luabridge::LuaRef lua_dsp_configure = luabridge::getGlobal (L, "dsp_configure");
601 if (lua_dsp_configure.type () == LUA_TFUNCTION) {
603 lua_dsp_configure (&in, &out);
604 } catch (luabridge::LuaException const& e) {
609 _info->n_inputs = _configured_in;
610 _info->n_outputs = _configured_out;
615 LuaProc::connect_and_run (BufferSet& bufs,
616 ChanMapping in, ChanMapping out,
617 pframes_t nframes, framecnt_t offset)
623 Plugin::connect_and_run (bufs, in, out, nframes, offset);
625 // This is needed for ARDOUR::Session requests :(
626 if (! SessionEvent::has_per_thread_pool ()) {
628 snprintf (name, 64, "Proc-%p", this);
629 pthread_set_name (name);
630 SessionEvent::create_per_thread_pool (name, 64);
631 PBD::notify_event_loops_about_thread_creation (pthread_self(), name, 64);
634 uint32_t const n = parameter_count ();
635 for (uint32_t i = 0; i < n; ++i) {
636 if (parameter_is_control (i) && parameter_is_input (i)) {
637 _control_data[i] = _shadow_data[i];
641 #ifdef WITH_LUAPROC_STATS
642 int64_t t0 = g_get_monotonic_time ();
646 if (_lua_does_channelmapping) {
647 // run the DSP function
648 (*_lua_dsp)(&bufs, in, out, nframes, offset);
651 BufferSet& silent_bufs = _session.get_silent_buffers (ChanCount (DataType::AUDIO, 1));
652 BufferSet& scratch_bufs = _session.get_scratch_buffers (ChanCount (DataType::AUDIO, 1));
654 lua_State* L = lua.getState ();
655 luabridge::LuaRef in_map (luabridge::newTable (L));
656 luabridge::LuaRef out_map (luabridge::newTable (L));
658 const uint32_t audio_in = _configured_in.n_audio ();
659 const uint32_t audio_out = _configured_out.n_audio ();
660 const uint32_t midi_in = _configured_in.n_midi ();
662 for (uint32_t ap = 0; ap < audio_in; ++ap) {
664 const uint32_t buf_index = in.get(DataType::AUDIO, ap, &valid);
666 in_map[ap + 1] = bufs.get_audio (buf_index).data (offset);
668 in_map[ap + 1] = silent_bufs.get_audio (0).data (offset);
671 for (uint32_t ap = 0; ap < audio_out; ++ap) {
673 const uint32_t buf_index = out.get(DataType::AUDIO, ap, &valid);
675 out_map[ap + 1] = bufs.get_audio (buf_index).data (offset);
677 out_map[ap + 1] = scratch_bufs.get_audio (0).data (offset);
681 luabridge::LuaRef lua_midi_src_tbl (luabridge::newTable (L));
682 int e = 1; // > 1 port, we merge events (unsorted)
683 for (uint32_t mp = 0; mp < midi_in; ++mp) {
685 const uint32_t idx = in.get(DataType::MIDI, mp, &valid);
687 for (MidiBuffer::iterator m = bufs.get_midi(idx).begin();
688 m != bufs.get_midi(idx).end(); ++m, ++e) {
689 const Evoral::MIDIEvent<framepos_t> ev(*m, false);
690 luabridge::LuaRef lua_midi_data (luabridge::newTable (L));
691 const uint8_t* data = ev.buffer();
692 for (uint32_t i = 0; i < ev.size(); ++i) {
693 lua_midi_data [i + 1] = data[i];
695 luabridge::LuaRef lua_midi_event (luabridge::newTable (L));
696 lua_midi_event["time"] = 1 + (*m).time();
697 lua_midi_event["data"] = lua_midi_data;
698 lua_midi_src_tbl[e] = lua_midi_event;
703 if (_has_midi_input) {
704 // XXX TODO This needs a better solution than global namespace
705 luabridge::push (L, lua_midi_src_tbl);
706 lua_setglobal (L, "midiin");
709 luabridge::LuaRef lua_midi_sink_tbl (luabridge::newTable (L));
710 if (_has_midi_output) {
711 luabridge::push (L, lua_midi_sink_tbl);
712 lua_setglobal (L, "midiout");
715 // run the DSP function
716 (*_lua_dsp)(in_map, out_map, nframes);
718 // copy back midi events
719 if (_has_midi_output && lua_midi_sink_tbl.isTable ()) {
721 const uint32_t idx = out.get(DataType::MIDI, 0, &valid);
722 if (valid && bufs.count().n_midi() > idx) {
723 MidiBuffer& mbuf = bufs.get_midi(idx);
725 for (luabridge::Iterator i (lua_midi_sink_tbl); !i.isNil (); ++i) {
726 if (!i.key ().isNumber ()) { continue; }
727 if (!i.value ()["time"].isNumber ()) { continue; }
728 if (!i.value ()["data"].isTable ()) { continue; }
729 luabridge::LuaRef data_tbl (i.value ()["data"]);
730 framepos_t tme = i.value ()["time"];
731 if (tme < 1 || tme > nframes) { continue; }
734 for (luabridge::Iterator di (data_tbl); !di.isNil () && size < sizeof(data); ++di, ++size) {
735 data[size] = di.value ();
737 if (size > 0 && size < 64) {
738 mbuf.push_back(tme - 1, size, data);
745 } catch (luabridge::LuaException const& e) {
746 PBD::error << "LuaException: " << e.what () << "\n";
748 std::cerr << "LuaException: " << e.what () << "\n";
752 #ifdef WITH_LUAPROC_STATS
753 int64_t t1 = g_get_monotonic_time ();
755 lua.collect_garbage (); // rt-safe, slight *regular* performance overhead
756 #ifdef WITH_LUAPROC_STATS
758 int64_t t2 = g_get_monotonic_time ();
759 int64_t ela0 = t1 - t0;
760 int64_t ela1 = t2 - t1;
761 if (ela0 > _stats_max[0]) _stats_max[0] = ela0;
762 if (ela1 > _stats_max[1]) _stats_max[1] = ela1;
763 _stats_avg[0] += ela0;
764 _stats_avg[1] += ela1;
771 LuaProc::add_state (XMLNode* root) const
777 gchar* b64 = g_base64_encode ((const guchar*)_script.c_str (), _script.size ());
778 std::string b64s (b64);
780 XMLNode* script_node = new XMLNode (X_("script"));
781 script_node->add_property (X_("lua"), LUA_VERSION);
782 script_node->add_content (b64s);
783 root->add_child_nocopy (*script_node);
785 for (uint32_t i = 0; i < parameter_count(); ++i) {
786 if (parameter_is_input(i) && parameter_is_control(i)) {
787 child = new XMLNode("Port");
788 snprintf(buf, sizeof(buf), "%u", i);
789 child->add_property("id", std::string(buf));
790 snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
791 child->add_property("value", std::string(buf));
792 root->add_child_nocopy(*child);
798 LuaProc::set_script_from_state (const XMLNode& node)
801 if (node.name () != state_node_name ()) {
805 if ((child = node.child (X_("script"))) != 0) {
806 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
807 if (!(*n)->is_content ()) { continue; }
809 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
810 _script = std::string ((const char*)buf, size);
812 if (load_script ()) {
813 PBD::error << _("Failed to load Lua script from session state.") << endmsg;
815 std::cerr << "Failed Lua Script: " << _script << std::endl;
822 if (_script.empty ()) {
823 PBD::error << _("Session State for LuaProcessor did not include a Lua script.") << endmsg;
827 PBD::error << _("Invalid/incompatible Lua script found for LuaProcessor.") << endmsg;
834 LuaProc::set_state (const XMLNode& node, int version)
836 #ifndef NO_PLUGIN_STATE
838 XMLProperty const * prop;
839 XMLNodeConstIterator iter;
847 if (_script.empty ()) {
848 if (set_script_from_state (node)) {
853 #ifndef NO_PLUGIN_STATE
854 if (node.name() != state_node_name()) {
855 error << _("Bad node sent to LuaProc::set_state") << endmsg;
859 nodes = node.children ("Port");
860 for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
862 if ((prop = child->property("id")) != 0) {
863 port = prop->value().c_str();
865 warning << _("LuaProc: port has no symbol, ignored") << endmsg;
868 if ((prop = child->property("value")) != 0) {
869 value = prop->value().c_str();
871 warning << _("LuaProc: port has no value, ignored") << endmsg;
874 sscanf (port, "%" PRIu32, &port_id);
875 set_parameter (port_id, atof(value));
879 return Plugin::set_state (node, version);
883 LuaProc::parameter_count () const
885 return _ctrl_params.size ();
889 LuaProc::default_value (uint32_t port)
891 if (_ctrl_params[port].first) {
895 int lp = _ctrl_params[port].second;
896 return _param_desc[lp].normal;
900 LuaProc::set_parameter (uint32_t port, float val)
902 assert (port < parameter_count ());
903 if (get_parameter (port) == val) {
906 _shadow_data[port] = val;
907 Plugin::set_parameter (port, val);
911 LuaProc::get_parameter (uint32_t port) const
913 if (parameter_is_input (port)) {
914 return _shadow_data[port];
916 return _control_data[port];
921 LuaProc::get_parameter_descriptor (uint32_t port, ParameterDescriptor& desc) const
923 assert (port <= parameter_count ());
924 int lp = _ctrl_params[port].second;
925 const ParameterDescriptor& d (_param_desc.find(lp)->second);
927 desc.lower = d.lower;
928 desc.upper = d.upper;
929 desc.normal = d.normal;
930 desc.toggled = d.toggled;
931 desc.logarithmic = d.logarithmic;
932 desc.integer_step = d.integer_step;
933 desc.sr_dependent = d.sr_dependent;
934 desc.enumeration = d.enumeration;
936 desc.label = d.label;
937 desc.scale_points = d.scale_points;
939 desc.update_steps ();
944 LuaProc::get_parameter_docs (uint32_t port) const {
945 assert (port <= parameter_count ());
946 int lp = _ctrl_params[port].second;
947 return _param_doc.find(lp)->second;
951 LuaProc::nth_parameter (uint32_t port, bool& ok) const
953 if (port < _ctrl_params.size ()) {
962 LuaProc::parameter_is_input (uint32_t port) const
964 assert (port < _ctrl_params.size ());
965 return (!_ctrl_params[port].first);
969 LuaProc::parameter_is_output (uint32_t port) const
971 assert (port < _ctrl_params.size ());
972 return (_ctrl_params[port].first);
975 std::set<Evoral::Parameter>
976 LuaProc::automatable () const
978 std::set<Evoral::Parameter> automatables;
979 for (uint32_t i = 0; i < _ctrl_params.size (); ++i) {
980 if (parameter_is_input (i)) {
981 automatables.insert (automatables.end (), Evoral::Parameter (PluginAutomation, 0, i));
988 LuaProc::describe_parameter (Evoral::Parameter param)
990 if (param.type () == PluginAutomation && param.id () < parameter_count ()) {
991 int lp = _ctrl_params[param.id ()].second;
992 return _param_desc[lp].label;
998 LuaProc::print_parameter (uint32_t param, char* buf, uint32_t len) const
1001 if (param < parameter_count ()) {
1002 snprintf (buf, len, "%.3f", get_parameter (param));
1009 boost::shared_ptr<ScalePoints>
1010 LuaProc::parse_scale_points (luabridge::LuaRef* lr)
1012 if (!(*lr)["scalepoints"].isTable()) {
1013 return boost::shared_ptr<ScalePoints> ();
1017 boost::shared_ptr<ScalePoints> rv = boost::shared_ptr<ScalePoints>(new ScalePoints());
1018 luabridge::LuaRef scalepoints ((*lr)["scalepoints"]);
1020 for (luabridge::Iterator i (scalepoints); !i.isNil (); ++i) {
1021 if (!i.key ().isString ()) { continue; }
1022 if (!i.value ().isNumber ()) { continue; }
1023 rv->insert(make_pair(i.key ().cast<std::string> (),
1024 i.value ().cast<float> ()));
1028 if (rv->size() > 0) {
1031 return boost::shared_ptr<ScalePoints> ();
1034 boost::shared_ptr<ScalePoints>
1035 LuaProc::get_scale_points (uint32_t port) const
1037 int lp = _ctrl_params[port].second;
1038 return _param_desc.find(lp)->second.scale_points;
1042 LuaProc::setup_lua_inline_gui (LuaState *lua_gui)
1044 lua_State* LG = lua_gui->getState ();
1045 LuaBindings::stddef (LG);
1046 LuaBindings::common (LG);
1047 LuaBindings::dsp (LG);
1049 lua_gui->Print.connect (sigc::mem_fun (*this, &LuaProc::lua_print));
1050 lua_gui->do_command ("function ardour () end");
1051 lua_gui->do_command (_script);
1053 // TODO think: use a weak-pointer here ?
1054 // (the GUI itself uses a shared ptr to this plugin, so we should be good)
1055 luabridge::getGlobalNamespace (LG)
1056 .beginNamespace ("Ardour")
1057 .beginClass <LuaProc> ("LuaProc")
1058 .addFunction ("shmem", &LuaProc::instance_shm)
1062 luabridge::push <LuaProc *> (LG, this);
1063 lua_setglobal (LG, "self");
1065 luabridge::push <float *> (LG, _shadow_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) {
1129 XMLProperty const * label = (*i)->property (X_("label"));
1131 if (label->value() != r.label) {
1135 for (XMLNodeList::const_iterator j = (*i)->children().begin(); j != (*i)->children().end(); ++j) {
1136 if ((*j)->name() == X_("Parameter")) {
1137 XMLProperty const * index = (*j)->property (X_("index"));
1138 XMLProperty const * value = (*j)->property (X_("value"));
1141 set_parameter (atoi (index->value().c_str()), atof (value->value().c_str ()));
1150 LuaProc::do_save_preset (std::string name) {
1152 boost::shared_ptr<XMLTree> t (presets_tree ());
1157 std::string uri (preset_name_to_uri (name));
1159 XMLNode* p = new XMLNode (X_("Preset"));
1160 p->add_property (X_("uri"), uri);
1161 p->add_property (X_("label"), name);
1163 for (uint32_t i = 0; i < parameter_count(); ++i) {
1164 if (parameter_is_input (i)) {
1165 XMLNode* c = new XMLNode (X_("Parameter"));
1166 c->add_property (X_("index"), string_compose ("%1", i));
1167 c->add_property (X_("value"), string_compose ("%1", get_parameter (i)));
1168 p->add_child_nocopy (*c);
1171 t->root()->add_child_nocopy (*p);
1173 std::string f = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
1174 f = Glib::build_filename (f, presets_file ());
1181 LuaProc::do_remove_preset (std::string name)
1183 boost::shared_ptr<XMLTree> t (presets_tree ());
1187 t->root()->remove_nodes_and_delete (X_("label"), name);
1188 std::string f = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
1189 f = Glib::build_filename (f, presets_file ());
1194 LuaProc::find_presets ()
1196 boost::shared_ptr<XMLTree> t (presets_tree ());
1198 XMLNode* root = t->root ();
1199 for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
1201 XMLProperty const * uri = (*i)->property (X_("uri"));
1202 XMLProperty const * label = (*i)->property (X_("label"));
1207 PresetRecord r (uri->value(), label->value(), true);
1208 _presets.insert (make_pair (r.uri, r));
1213 ////////////////////////////////////////////////////////////////////////////////
1215 LuaPluginInfo::LuaPluginInfo (LuaScriptInfoPtr lsi) {
1216 if (lsi->type != LuaScriptInfo::DSP) {
1217 throw failed_constructor ();
1222 creator = lsi->author;
1223 category = lsi->category;
1224 unique_id = lsi->unique_id;
1226 n_inputs.set (DataType::AUDIO, 1);
1227 n_outputs.set (DataType::AUDIO, 1);
1230 _is_instrument = category == "Instrument";
1234 LuaPluginInfo::load (Session& session)
1236 std::string script = "";
1237 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
1238 return PluginPtr ();
1242 script = Glib::file_get_contents (path);
1243 } catch (Glib::FileError err) {
1244 return PluginPtr ();
1247 if (script.empty ()) {
1248 return PluginPtr ();
1252 PluginPtr plugin (new LuaProc (session.engine (), session, script));
1254 } catch (failed_constructor& err) {
1257 return PluginPtr ();
1260 std::vector<Plugin::PresetRecord>
1261 LuaPluginInfo::get_presets (bool /*user_only*/) const
1263 std::vector<Plugin::PresetRecord> p;
1264 XMLTree* t = new XMLTree;
1265 std::string pf = Glib::build_filename (ARDOUR::user_config_directory (), "presets", string_compose ("lua-%1", unique_id));
1266 if (Glib::file_test (pf, Glib::FILE_TEST_EXISTS)) {
1267 t->set_filename (pf);
1269 XMLNode* root = t->root ();
1270 for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
1271 XMLProperty const * uri = (*i)->property (X_("uri"));
1272 XMLProperty const * label = (*i)->property (X_("label"));
1273 p.push_back (Plugin::PresetRecord (uri->value(), label->value(), true));