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", 2097152)
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", 2097152)
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;
122 lua.Print.connect (sigc::mem_fun (*this, &LuaProc::lua_print));
123 // register session object
124 lua_State* L = lua.getState ();
125 LuaBindings::stddef (L);
126 LuaBindings::common (L);
127 LuaBindings::dsp (L);
129 luabridge::getGlobalNamespace (L)
130 .beginNamespace ("Ardour")
131 .beginClass <LuaProc> ("LuaProc")
132 .addFunction ("queue_draw", &LuaProc::queue_draw)
133 .addFunction ("shmem", &LuaProc::instance_shm)
134 .addFunction ("table", &LuaProc::instance_ref)
138 // add session to global lua namespace
139 luabridge::push <Session *> (L, &_session);
140 lua_setglobal (L, "Session");
143 luabridge::push <LuaProc *> (L, this);
144 lua_setglobal (L, "self");
147 lua.do_command ("io = nil os = nil loadfile = nil require = nil dofile = nil package = nil debug = nil");
149 lua.do_command ("for n in pairs(_G) do print(n) end print ('----')"); // print global env
151 lua.do_command ("function ardour () end");
155 LuaProc::lua_print (std::string s) {
156 std::cout <<"LuaProc: " << s << "\n";
157 PBD::error << "LuaProc: " << s << "\n";
161 LuaProc::load_script ()
163 assert (!_lua_dsp); // don't allow to re-initialize
164 LuaPluginInfoPtr lpi;
166 // TODO: refine APIs; function arguments..
167 // - perform channel-map in ardour (silent/scratch buffers) ?
168 // - control-port API (explicit get/set functions ??)
169 // - latency reporting (global var? ctrl-port? set-function ?)
170 // - MIDI -> sparse table of events
171 // { [sample] => { Event }, .. }
172 // or { { sample, Event }, .. }
175 LuaScriptInfoPtr lsi = LuaScripting::script_info (_script);
176 lpi = LuaPluginInfoPtr (new LuaPluginInfo (lsi));
179 _mempool.set_name ("LuaProc: " + lsi->name);
180 _docs = lsi->description;
181 } catch (failed_constructor& err) {
185 lua_State* L = lua.getState ();
186 lua.do_command (_script);
188 // check if script has a DSP callback
189 luabridge::LuaRef lua_dsp_run = luabridge::getGlobal (L, "dsp_run");
190 luabridge::LuaRef lua_dsp_map = luabridge::getGlobal (L, "dsp_runmap");
192 if ((lua_dsp_run.type () != LUA_TFUNCTION) == (lua_dsp_map.type () != LUA_TFUNCTION)) {
196 if (lua_dsp_run.type () == LUA_TFUNCTION) {
197 _lua_dsp = new luabridge::LuaRef (lua_dsp_run);
199 else if (lua_dsp_map.type () == LUA_TFUNCTION) {
200 _lua_dsp = new luabridge::LuaRef (lua_dsp_map);
201 _lua_does_channelmapping = true;
207 // initialize the DSP if needed
208 luabridge::LuaRef lua_dsp_init = luabridge::getGlobal (L, "dsp_init");
209 if (lua_dsp_init.type () == LUA_TFUNCTION) {
211 lua_dsp_init (_session.nominal_frame_rate ());
212 } catch (luabridge::LuaException const& e) {
218 luabridge::LuaRef lua_dsp_has_midi_in = luabridge::getGlobal (L, "dsp_has_midi_input");
219 if (lua_dsp_has_midi_in.type () == LUA_TFUNCTION) {
221 _has_midi_input = lua_dsp_has_midi_in ();
222 } catch (luabridge::LuaException const& e) {
227 luabridge::LuaRef lua_dsp_has_midi_out = luabridge::getGlobal (L, "dsp_has_midi_output");
228 if (lua_dsp_has_midi_out.type () == LUA_TFUNCTION) {
230 _has_midi_output = lua_dsp_has_midi_out ();
231 } catch (luabridge::LuaException const& e) {
236 _ctrl_params.clear ();
238 luabridge::LuaRef lua_render = luabridge::getGlobal (L, "render_inline");
239 if (lua_render.isFunction ()) {
240 _lua_has_inline_display = true;
243 luabridge::LuaRef lua_params = luabridge::getGlobal (L, "dsp_params");
244 if (lua_params.isFunction ()) {
246 // call function // add try {} catch (luabridge::LuaException const& e)
247 luabridge::LuaRef params = lua_params ();
249 if (params.isTable ()) {
251 for (luabridge::Iterator i (params); !i.isNil (); ++i) {
253 if (!i.key ().isNumber ()) { return false; }
254 if (!i.value ().isTable ()) { return false; }
255 if (!i.value ()["type"].isString ()) { return false; }
256 if (!i.value ()["name"].isString ()) { return false; }
257 if (!i.value ()["min"].isNumber ()) { return false; }
258 if (!i.value ()["max"].isNumber ()) { return false; }
260 int pn = i.key ().cast<int> ();
261 std::string type = i.value ()["type"].cast<std::string> ();
262 if (type == "input") {
263 if (!i.value ()["default"].isNumber ()) { return false; }
264 _ctrl_params.push_back (std::make_pair (false, pn));
266 else if (type == "output") {
267 _ctrl_params.push_back (std::make_pair (true, pn));
271 assert (pn == (int) _ctrl_params.size ());
273 //_param_desc[pn] = boost::shared_ptr<ParameterDescriptor> (new ParameterDescriptor());
274 luabridge::LuaRef lr = i.value ();
276 if (type == "input") {
277 _param_desc[pn].normal = lr["default"].cast<float> ();
279 _param_desc[pn].normal = lr["min"].cast<float> (); // output-port, no default
281 _param_desc[pn].lower = lr["min"].cast<float> ();
282 _param_desc[pn].upper = lr["max"].cast<float> ();
283 _param_desc[pn].toggled = lr["toggled"].isBoolean () && (lr["toggled"]).cast<bool> ();
284 _param_desc[pn].logarithmic = lr["logarithmic"].isBoolean () && (lr["logarithmic"]).cast<bool> ();
285 _param_desc[pn].integer_step = lr["integer"].isBoolean () && (lr["integer"]).cast<bool> ();
286 _param_desc[pn].sr_dependent = lr["ratemult"].isBoolean () && (lr["ratemult"]).cast<bool> ();
287 _param_desc[pn].enumeration = lr["enum"].isBoolean () && (lr["enum"]).cast<bool> ();
289 if (lr["unit"].isString ()) {
290 std::string unit = lr["unit"].cast<std::string> ();
291 if (unit == "dB") { _param_desc[pn].unit = ParameterDescriptor::DB; }
292 else if (unit == "Hz") { _param_desc[pn].unit = ParameterDescriptor::HZ; }
293 else if (unit == "Midi Note") { _param_desc[pn].unit = ParameterDescriptor::MIDI_NOTE; }
295 _param_desc[pn].label = (lr["name"]).cast<std::string> ();
296 _param_desc[pn].scale_points = parse_scale_points (&lr);
298 luabridge::LuaRef doc = lr["doc"];
299 if (doc.isString ()) {
300 _param_doc[pn] = doc.cast<std::string> ();
304 assert (!(_param_desc[pn].toggled && _param_desc[pn].logarithmic));
309 _control_data = new float[parameter_count ()];
310 _shadow_data = new float[parameter_count ()];
312 for (uint32_t i = 0; i < parameter_count (); ++i) {
313 if (parameter_is_input (i)) {
314 _control_data[i] = _shadow_data[i] = default_value (i);
318 // expose ctrl-ports to global lua namespace
319 luabridge::push <float *> (L, _control_data);
320 lua_setglobal (L, "CtrlPorts");
322 return false; // no error
326 LuaProc::can_support_io_configuration (const ChanCount& in, ChanCount& out, ChanCount* imprecise)
328 // caller must hold process lock (no concurrent calls to interpreter
329 _output_configs.clear ();
331 if (in.n_midi() > 0 && !_has_midi_input && !imprecise) {
335 lua_State* L = lua.getState ();
336 luabridge::LuaRef ioconfig = luabridge::getGlobal (L, "dsp_ioconfig");
337 if (!ioconfig.isFunction ()) {
341 luabridge::LuaRef *_iotable = NULL; // can't use reference :(
343 luabridge::LuaRef iotable = ioconfig ();
344 if (iotable.isTable ()) {
345 _iotable = new luabridge::LuaRef (iotable);
347 } catch (luabridge::LuaException const& e) {
355 // now we can reference it.
356 luabridge::LuaRef iotable (*_iotable);
359 if ((iotable).length () < 1) {
364 bool exact_match = false;
365 const int32_t audio_in = in.n_audio ();
366 int32_t midi_out = _has_midi_output ? 1 : 0;
368 // preferred setting (provided by plugin_insert)
369 assert (out.n_audio () > 0 || midi_out > 0);
370 const int preferred_out = out.n_audio ();
372 for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
373 assert (i.value ().type () == LUA_TTABLE);
374 luabridge::LuaRef io (i.value ());
376 int possible_in = io["audio_in"];
377 int possible_out = io["audio_out"];
380 if ((possible_in == audio_in) && (possible_out == preferred_out)) {
381 _output_configs.insert (preferred_out);
388 /* now allow potentially "imprecise" matches */
389 int32_t audio_out = -1;
390 float penalty = 9999;
392 #define FOUNDCFG(nch) { \
393 float p = fabsf ((float)(nch) - preferred_out); \
394 _output_configs.insert (nch); \
395 if ((nch) > preferred_out) { p *= 1.1; } \
403 #define ANYTHINGGOES \
404 _output_configs.insert (0);
406 #define UPTO(nch) { \
407 for (int n = 1; n < nch; ++n) { \
408 _output_configs.insert (n); \
412 for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
413 assert (i.value ().type () == LUA_TTABLE);
414 luabridge::LuaRef io (i.value ());
416 int possible_in = io["audio_in"];
417 int possible_out = io["audio_out"];
419 if (possible_out == 0) {
420 if (possible_in == 0) {
421 if (_has_midi_output && audio_in == 0) {
422 // special case midi filters & generators
431 if (possible_in == 0) {
432 /* no inputs, generators & instruments */
433 if (possible_out == -1) {
434 /* any configuration possible, stereo output */
435 FOUNDCFG (preferred_out);
437 } else if (possible_out == -2) {
438 /* invalid, should be (0, -1) */
439 FOUNDCFG (preferred_out);
441 } else if (possible_out < -2) {
442 /* variable number of outputs up to -N, */
443 FOUNDCFG (min (-possible_out, preferred_out));
444 UPTO (-possible_out);
446 /* exact number of outputs */
447 FOUNDCFG (possible_out);
451 if (possible_in == -1) {
452 /* wildcard for input */
453 if (possible_out == -1) {
454 /* out must match in */
456 } else if (possible_out == -2) {
457 /* any configuration possible, pick matching */
458 FOUNDCFG (preferred_out);
460 } else if (possible_out < -2) {
461 /* explicitly variable number of outputs, pick maximum */
462 FOUNDCFG (max (-possible_out, preferred_out));
463 /* and try min, too, in case the penalty is lower */
464 FOUNDCFG (min (-possible_out, preferred_out));
467 /* exact number of outputs */
468 FOUNDCFG (possible_out);
472 if (possible_in == -2) {
473 if (possible_out == -1) {
474 /* any configuration possible, pick matching */
475 FOUNDCFG (preferred_out);
477 } else if (possible_out == -2) {
478 /* invalid. interpret as (-1, -1) */
479 FOUNDCFG (preferred_out);
481 } else if (possible_out < -2) {
482 /* invalid, interpret as (<-2, <-2)
483 * variable number of outputs up to -N, */
484 FOUNDCFG (min (-possible_out, preferred_out));
487 /* exact number of outputs */
488 FOUNDCFG (possible_out);
492 if (possible_in < -2) {
493 /* explicit variable number of inputs */
494 if (audio_in > -possible_in && imprecise != NULL) {
496 imprecise->set (DataType::AUDIO, -possible_in);
499 if (audio_in > -possible_in && imprecise == NULL) {
500 /* request is too large */
501 } else if (possible_out == -1) {
502 /* any output configuration possible */
503 FOUNDCFG (preferred_out);
505 } else if (possible_out == -2) {
506 /* invalid. interpret as (<-2, -1) */
507 FOUNDCFG (preferred_out);
509 } else if (possible_out < -2) {
510 /* variable number of outputs up to -N, */
511 FOUNDCFG (min (-possible_out, preferred_out));
514 /* exact number of outputs */
515 FOUNDCFG (possible_out);
519 if (possible_in && (possible_in == audio_in)) {
520 /* exact number of inputs ... must match obviously */
521 if (possible_out == -1) {
522 /* any output configuration possible */
523 FOUNDCFG (preferred_out);
525 } else if (possible_out == -2) {
526 /* invalid. interpret as (>0, -1) */
527 FOUNDCFG (preferred_out);
529 } else if (possible_out < -2) {
530 /* > 0, < -2 is not specified
531 * interpret as up to -N */
532 FOUNDCFG (min (-possible_out, preferred_out));
535 /* exact number of outputs */
536 FOUNDCFG (possible_out);
541 if (!found && imprecise) {
543 for (luabridge::Iterator i (iotable); !i.isNil (); ++i) {
544 assert (i.value ().type () == LUA_TTABLE);
545 luabridge::LuaRef io (i.value ());
547 int possible_in = io["audio_in"];
548 int possible_out = io["audio_out"];
550 if (possible_out == 0 && possible_in == 0 && _has_midi_output) {
551 assert (audio_in > 0); // no input is handled above
552 // TODO hide audio input from plugin
553 imprecise->set (DataType::AUDIO, 0);
559 assert (possible_in > 0); // all other cases will have been matched above
560 assert (possible_out !=0 || possible_in !=0); // already handled above
562 imprecise->set (DataType::AUDIO, possible_in);
563 if (possible_out == -1 || possible_out == -2) {
565 } else if (possible_out < -2) {
566 /* explicitly variable number of outputs, pick maximum */
567 FOUNDCFG (min (-possible_out, preferred_out));
569 /* exact number of outputs */
570 FOUNDCFG (possible_out);
572 // ideally we'll also find the closest, best matching
573 // input configuration with minimal output penalty...
582 out.set (DataType::MIDI, midi_out);
583 out.set (DataType::AUDIO, preferred_out);
585 out.set (DataType::MIDI, midi_out);
586 out.set (DataType::AUDIO, audio_out);
592 LuaProc::configure_io (ChanCount in, ChanCount out)
594 in.set (DataType::MIDI, _has_midi_input ? 1 : 0);
595 out.set (DataType::MIDI, _has_midi_output ? 1 : 0);
597 // configure the DSP if needed
598 if (in != _configured_in || out != _configured_out) {
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) {
605 PBD::error << "LuaException: " << e.what () << "\n";
607 std::cerr << "LuaException: " << e.what () << "\n";
615 _configured_out = out;
617 _info->n_inputs = _configured_in;
618 _info->n_outputs = _configured_out;
623 LuaProc::connect_and_run (BufferSet& bufs,
624 framepos_t start, framepos_t end, double speed,
625 ChanMapping in, ChanMapping out,
626 pframes_t nframes, framecnt_t offset)
632 Plugin::connect_and_run (bufs, start, end, speed, in, out, nframes, offset);
634 // This is needed for ARDOUR::Session requests :(
635 if (! SessionEvent::has_per_thread_pool ()) {
637 snprintf (name, 64, "Proc-%p", this);
638 pthread_set_name (name);
639 SessionEvent::create_per_thread_pool (name, 64);
640 PBD::notify_event_loops_about_thread_creation (pthread_self(), name, 64);
643 uint32_t const n = parameter_count ();
644 for (uint32_t i = 0; i < n; ++i) {
645 if (parameter_is_control (i) && parameter_is_input (i)) {
646 _control_data[i] = _shadow_data[i];
650 #ifdef WITH_LUAPROC_STATS
651 int64_t t0 = g_get_monotonic_time ();
655 if (_lua_does_channelmapping) {
656 // run the DSP function
657 (*_lua_dsp)(&bufs, in, out, nframes, offset);
660 BufferSet& silent_bufs = _session.get_silent_buffers (ChanCount (DataType::AUDIO, 1));
661 BufferSet& scratch_bufs = _session.get_scratch_buffers (ChanCount (DataType::AUDIO, 1));
663 lua_State* L = lua.getState ();
664 luabridge::LuaRef in_map (luabridge::newTable (L));
665 luabridge::LuaRef out_map (luabridge::newTable (L));
667 const uint32_t audio_in = _configured_in.n_audio ();
668 const uint32_t audio_out = _configured_out.n_audio ();
669 const uint32_t midi_in = _configured_in.n_midi ();
671 for (uint32_t ap = 0; ap < audio_in; ++ap) {
673 const uint32_t buf_index = in.get(DataType::AUDIO, ap, &valid);
675 in_map[ap + 1] = bufs.get_audio (buf_index).data (offset);
677 in_map[ap + 1] = silent_bufs.get_audio (0).data (offset);
680 for (uint32_t ap = 0; ap < audio_out; ++ap) {
682 const uint32_t buf_index = out.get(DataType::AUDIO, ap, &valid);
684 out_map[ap + 1] = bufs.get_audio (buf_index).data (offset);
686 out_map[ap + 1] = scratch_bufs.get_audio (0).data (offset);
690 luabridge::LuaRef lua_midi_src_tbl (luabridge::newTable (L));
691 int e = 1; // > 1 port, we merge events (unsorted)
692 for (uint32_t mp = 0; mp < midi_in; ++mp) {
694 const uint32_t idx = in.get(DataType::MIDI, mp, &valid);
696 for (MidiBuffer::iterator m = bufs.get_midi(idx).begin();
697 m != bufs.get_midi(idx).end(); ++m, ++e) {
698 const Evoral::MIDIEvent<framepos_t> ev(*m, false);
699 luabridge::LuaRef lua_midi_data (luabridge::newTable (L));
700 const uint8_t* data = ev.buffer();
701 for (uint32_t i = 0; i < ev.size(); ++i) {
702 lua_midi_data [i + 1] = data[i];
704 luabridge::LuaRef lua_midi_event (luabridge::newTable (L));
705 lua_midi_event["time"] = 1 + (*m).time();
706 lua_midi_event["data"] = lua_midi_data;
707 lua_midi_src_tbl[e] = lua_midi_event;
712 if (_has_midi_input) {
713 // XXX TODO This needs a better solution than global namespace
714 luabridge::push (L, lua_midi_src_tbl);
715 lua_setglobal (L, "midiin");
718 luabridge::LuaRef lua_midi_sink_tbl (luabridge::newTable (L));
719 if (_has_midi_output) {
720 luabridge::push (L, lua_midi_sink_tbl);
721 lua_setglobal (L, "midiout");
724 // run the DSP function
725 (*_lua_dsp)(in_map, out_map, nframes);
727 // copy back midi events
728 if (_has_midi_output && lua_midi_sink_tbl.isTable ()) {
730 const uint32_t idx = out.get(DataType::MIDI, 0, &valid);
731 if (valid && bufs.count().n_midi() > idx) {
732 MidiBuffer& mbuf = bufs.get_midi(idx);
734 for (luabridge::Iterator i (lua_midi_sink_tbl); !i.isNil (); ++i) {
735 if (!i.key ().isNumber ()) { continue; }
736 if (!i.value ()["time"].isNumber ()) { continue; }
737 if (!i.value ()["data"].isTable ()) { continue; }
738 luabridge::LuaRef data_tbl (i.value ()["data"]);
739 framepos_t tme = i.value ()["time"];
740 if (tme < 1 || tme > nframes) { continue; }
743 for (luabridge::Iterator di (data_tbl); !di.isNil () && size < sizeof(data); ++di, ++size) {
744 data[size] = di.value ();
746 if (size > 0 && size < 64) {
747 mbuf.push_back(tme - 1, size, data);
754 } catch (luabridge::LuaException const& e) {
755 PBD::error << "LuaException: " << e.what () << "\n";
757 std::cerr << "LuaException: " << e.what () << "\n";
761 #ifdef WITH_LUAPROC_STATS
762 int64_t t1 = g_get_monotonic_time ();
765 lua.collect_garbage_step ();
766 #ifdef WITH_LUAPROC_STATS
768 int64_t t2 = g_get_monotonic_time ();
769 int64_t ela0 = t1 - t0;
770 int64_t ela1 = t2 - t1;
771 if (ela0 > _stats_max[0]) _stats_max[0] = ela0;
772 if (ela1 > _stats_max[1]) _stats_max[1] = ela1;
773 _stats_avg[0] += ela0;
774 _stats_avg[1] += ela1;
781 LuaProc::add_state (XMLNode* root) const
787 gchar* b64 = g_base64_encode ((const guchar*)_script.c_str (), _script.size ());
788 std::string b64s (b64);
790 XMLNode* script_node = new XMLNode (X_("script"));
791 script_node->add_property (X_("lua"), LUA_VERSION);
792 script_node->add_content (b64s);
793 root->add_child_nocopy (*script_node);
795 for (uint32_t i = 0; i < parameter_count(); ++i) {
796 if (parameter_is_input(i) && parameter_is_control(i)) {
797 child = new XMLNode("Port");
798 snprintf(buf, sizeof(buf), "%u", i);
799 child->add_property("id", std::string(buf));
800 snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
801 child->add_property("value", std::string(buf));
802 root->add_child_nocopy(*child);
808 LuaProc::set_script_from_state (const XMLNode& node)
811 if (node.name () != state_node_name ()) {
815 if ((child = node.child (X_("script"))) != 0) {
816 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
817 if (!(*n)->is_content ()) { continue; }
819 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
820 _script = std::string ((const char*)buf, size);
822 if (load_script ()) {
823 PBD::error << _("Failed to load Lua script from session state.") << endmsg;
825 std::cerr << "Failed Lua Script: " << _script << std::endl;
832 if (_script.empty ()) {
833 PBD::error << _("Session State for LuaProcessor did not include a Lua script.") << endmsg;
837 PBD::error << _("Invalid/incompatible Lua script found for LuaProcessor.") << endmsg;
844 LuaProc::set_state (const XMLNode& node, int version)
846 #ifndef NO_PLUGIN_STATE
848 XMLProperty const * prop;
849 XMLNodeConstIterator iter;
857 if (_script.empty ()) {
858 if (set_script_from_state (node)) {
863 #ifndef NO_PLUGIN_STATE
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) {
872 if ((prop = child->property("id")) != 0) {
873 port = prop->value().c_str();
875 warning << _("LuaProc: port has no symbol, ignored") << endmsg;
878 if ((prop = child->property("value")) != 0) {
879 value = prop->value().c_str();
881 warning << _("LuaProc: port has no value, ignored") << endmsg;
884 sscanf (port, "%" PRIu32, &port_id);
885 set_parameter (port_id, atof(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;
1008 LuaProc::print_parameter (uint32_t param, char* buf, uint32_t len) const
1011 if (param < parameter_count ()) {
1012 snprintf (buf, len, "%.3f", get_parameter (param));
1019 boost::shared_ptr<ScalePoints>
1020 LuaProc::parse_scale_points (luabridge::LuaRef* lr)
1022 if (!(*lr)["scalepoints"].isTable()) {
1023 return boost::shared_ptr<ScalePoints> ();
1027 boost::shared_ptr<ScalePoints> rv = boost::shared_ptr<ScalePoints>(new ScalePoints());
1028 luabridge::LuaRef scalepoints ((*lr)["scalepoints"]);
1030 for (luabridge::Iterator i (scalepoints); !i.isNil (); ++i) {
1031 if (!i.key ().isString ()) { continue; }
1032 if (!i.value ().isNumber ()) { continue; }
1033 rv->insert(make_pair(i.key ().cast<std::string> (),
1034 i.value ().cast<float> ()));
1038 if (rv->size() > 0) {
1041 return boost::shared_ptr<ScalePoints> ();
1044 boost::shared_ptr<ScalePoints>
1045 LuaProc::get_scale_points (uint32_t port) const
1047 int lp = _ctrl_params[port].second;
1048 return _param_desc.find(lp)->second.scale_points;
1052 LuaProc::setup_lua_inline_gui (LuaState *lua_gui)
1054 lua_State* LG = lua_gui->getState ();
1055 LuaBindings::stddef (LG);
1056 LuaBindings::common (LG);
1057 LuaBindings::dsp (LG);
1059 lua_gui->Print.connect (sigc::mem_fun (*this, &LuaProc::lua_print));
1060 lua_gui->do_command ("function ardour () end");
1061 lua_gui->do_command (_script);
1063 // TODO think: use a weak-pointer here ?
1064 // (the GUI itself uses a shared ptr to this plugin, so we should be good)
1065 luabridge::getGlobalNamespace (LG)
1066 .beginNamespace ("Ardour")
1067 .beginClass <LuaProc> ("LuaProc")
1068 .addFunction ("shmem", &LuaProc::instance_shm)
1069 .addFunction ("table", &LuaProc::instance_ref)
1073 luabridge::push <LuaProc *> (LG, this);
1074 lua_setglobal (LG, "self");
1076 luabridge::push <float *> (LG, _shadow_data);
1077 lua_setglobal (LG, "CtrlPorts");
1079 ////////////////////////////////////////////////////////////////////////////////
1081 #include "ardour/search_paths.h"
1085 LuaProc::preset_name_to_uri (const std::string& name) const
1087 std::string uri ("urn:lua:");
1091 sha1_write (&s, (const uint8_t *) name.c_str(), name.size ());
1092 sha1_write (&s, (const uint8_t *) _script.c_str(), _script.size ());
1093 sha1_result_hash (&s, hash);
1098 LuaProc::presets_file () const
1100 return string_compose ("lua-%1", _info->unique_id);
1104 LuaProc::presets_tree () const
1106 XMLTree* t = new XMLTree;
1107 std::string p = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
1109 if (!Glib::file_test (p, Glib::FILE_TEST_IS_DIR)) {
1110 if (g_mkdir_with_parents (p.c_str(), 0755) != 0) {
1111 error << _("Unable to create LuaProc presets directory") << endmsg;
1115 p = Glib::build_filename (p, presets_file ());
1117 if (!Glib::file_test (p, Glib::FILE_TEST_EXISTS)) {
1118 t->set_root (new XMLNode (X_("LuaPresets")));
1122 t->set_filename (p);
1131 LuaProc::load_preset (PresetRecord r)
1133 boost::shared_ptr<XMLTree> t (presets_tree ());
1138 XMLNode* root = t->root ();
1139 for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
1140 XMLProperty const * label = (*i)->property (X_("label"));
1142 if (label->value() != r.label) {
1146 for (XMLNodeList::const_iterator j = (*i)->children().begin(); j != (*i)->children().end(); ++j) {
1147 if ((*j)->name() == X_("Parameter")) {
1148 XMLProperty const * index = (*j)->property (X_("index"));
1149 XMLProperty const * value = (*j)->property (X_("value"));
1152 set_parameter (atoi (index->value().c_str()), atof (value->value().c_str ()));
1161 LuaProc::do_save_preset (std::string name) {
1163 boost::shared_ptr<XMLTree> t (presets_tree ());
1168 std::string uri (preset_name_to_uri (name));
1170 XMLNode* p = new XMLNode (X_("Preset"));
1171 p->add_property (X_("uri"), uri);
1172 p->add_property (X_("label"), name);
1174 for (uint32_t i = 0; i < parameter_count(); ++i) {
1175 if (parameter_is_input (i)) {
1176 XMLNode* c = new XMLNode (X_("Parameter"));
1177 c->add_property (X_("index"), string_compose ("%1", i));
1178 c->add_property (X_("value"), string_compose ("%1", get_parameter (i)));
1179 p->add_child_nocopy (*c);
1182 t->root()->add_child_nocopy (*p);
1184 std::string f = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
1185 f = Glib::build_filename (f, presets_file ());
1192 LuaProc::do_remove_preset (std::string name)
1194 boost::shared_ptr<XMLTree> t (presets_tree ());
1198 t->root()->remove_nodes_and_delete (X_("label"), name);
1199 std::string f = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
1200 f = Glib::build_filename (f, presets_file ());
1205 LuaProc::find_presets ()
1207 boost::shared_ptr<XMLTree> t (presets_tree ());
1209 XMLNode* root = t->root ();
1210 for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
1212 XMLProperty const * uri = (*i)->property (X_("uri"));
1213 XMLProperty const * label = (*i)->property (X_("label"));
1218 PresetRecord r (uri->value(), label->value(), true);
1219 _presets.insert (make_pair (r.uri, r));
1224 ////////////////////////////////////////////////////////////////////////////////
1226 LuaPluginInfo::LuaPluginInfo (LuaScriptInfoPtr lsi) {
1227 if (lsi->type != LuaScriptInfo::DSP) {
1228 throw failed_constructor ();
1233 creator = lsi->author;
1234 category = lsi->category;
1235 unique_id = lsi->unique_id;
1237 n_inputs.set (DataType::AUDIO, 1);
1238 n_outputs.set (DataType::AUDIO, 1);
1241 _is_instrument = category == "Instrument";
1245 LuaPluginInfo::load (Session& session)
1247 std::string script = "";
1248 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
1249 return PluginPtr ();
1253 script = Glib::file_get_contents (path);
1254 } catch (Glib::FileError err) {
1255 return PluginPtr ();
1258 if (script.empty ()) {
1259 return PluginPtr ();
1263 PluginPtr plugin (new LuaProc (session.engine (), session, script));
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));