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)
592 in.set (DataType::MIDI, _has_midi_input ? 1 : 0);
593 out.set (DataType::MIDI, _has_midi_output ? 1 : 0);
595 // configure the DSP if needed
596 if (in != _configured_in || out != _configured_out) {
597 lua_State* L = lua.getState ();
598 luabridge::LuaRef lua_dsp_configure = luabridge::getGlobal (L, "dsp_configure");
599 if (lua_dsp_configure.type () == LUA_TFUNCTION) {
601 lua_dsp_configure (&in, &out);
602 } catch (luabridge::LuaException const& e) {
603 PBD::error << "LuaException: " << e.what () << "\n";
605 std::cerr << "LuaException: " << e.what () << "\n";
613 _configured_out = out;
615 _info->n_inputs = _configured_in;
616 _info->n_outputs = _configured_out;
621 LuaProc::connect_and_run (BufferSet& bufs,
622 framepos_t start, framepos_t end, double speed,
623 ChanMapping in, ChanMapping out,
624 pframes_t nframes, framecnt_t offset)
630 Plugin::connect_and_run (bufs, start, end, speed, in, out, nframes, offset);
632 // This is needed for ARDOUR::Session requests :(
633 if (! SessionEvent::has_per_thread_pool ()) {
635 snprintf (name, 64, "Proc-%p", this);
636 pthread_set_name (name);
637 SessionEvent::create_per_thread_pool (name, 64);
638 PBD::notify_event_loops_about_thread_creation (pthread_self(), name, 64);
641 uint32_t const n = parameter_count ();
642 for (uint32_t i = 0; i < n; ++i) {
643 if (parameter_is_control (i) && parameter_is_input (i)) {
644 _control_data[i] = _shadow_data[i];
648 #ifdef WITH_LUAPROC_STATS
649 int64_t t0 = g_get_monotonic_time ();
653 if (_lua_does_channelmapping) {
654 // run the DSP function
655 (*_lua_dsp)(&bufs, in, out, nframes, offset);
658 BufferSet& silent_bufs = _session.get_silent_buffers (ChanCount (DataType::AUDIO, 1));
659 BufferSet& scratch_bufs = _session.get_scratch_buffers (ChanCount (DataType::AUDIO, 1));
661 lua_State* L = lua.getState ();
662 luabridge::LuaRef in_map (luabridge::newTable (L));
663 luabridge::LuaRef out_map (luabridge::newTable (L));
665 const uint32_t audio_in = _configured_in.n_audio ();
666 const uint32_t audio_out = _configured_out.n_audio ();
667 const uint32_t midi_in = _configured_in.n_midi ();
669 for (uint32_t ap = 0; ap < audio_in; ++ap) {
671 const uint32_t buf_index = in.get(DataType::AUDIO, ap, &valid);
673 in_map[ap + 1] = bufs.get_audio (buf_index).data (offset);
675 in_map[ap + 1] = silent_bufs.get_audio (0).data (offset);
678 for (uint32_t ap = 0; ap < audio_out; ++ap) {
680 const uint32_t buf_index = out.get(DataType::AUDIO, ap, &valid);
682 out_map[ap + 1] = bufs.get_audio (buf_index).data (offset);
684 out_map[ap + 1] = scratch_bufs.get_audio (0).data (offset);
688 luabridge::LuaRef lua_midi_src_tbl (luabridge::newTable (L));
689 int e = 1; // > 1 port, we merge events (unsorted)
690 for (uint32_t mp = 0; mp < midi_in; ++mp) {
692 const uint32_t idx = in.get(DataType::MIDI, mp, &valid);
694 for (MidiBuffer::iterator m = bufs.get_midi(idx).begin();
695 m != bufs.get_midi(idx).end(); ++m, ++e) {
696 const Evoral::MIDIEvent<framepos_t> ev(*m, false);
697 luabridge::LuaRef lua_midi_data (luabridge::newTable (L));
698 const uint8_t* data = ev.buffer();
699 for (uint32_t i = 0; i < ev.size(); ++i) {
700 lua_midi_data [i + 1] = data[i];
702 luabridge::LuaRef lua_midi_event (luabridge::newTable (L));
703 lua_midi_event["time"] = 1 + (*m).time();
704 lua_midi_event["data"] = lua_midi_data;
705 lua_midi_src_tbl[e] = lua_midi_event;
710 if (_has_midi_input) {
711 // XXX TODO This needs a better solution than global namespace
712 luabridge::push (L, lua_midi_src_tbl);
713 lua_setglobal (L, "midiin");
716 luabridge::LuaRef lua_midi_sink_tbl (luabridge::newTable (L));
717 if (_has_midi_output) {
718 luabridge::push (L, lua_midi_sink_tbl);
719 lua_setglobal (L, "midiout");
722 // run the DSP function
723 (*_lua_dsp)(in_map, out_map, nframes);
725 // copy back midi events
726 if (_has_midi_output && lua_midi_sink_tbl.isTable ()) {
728 const uint32_t idx = out.get(DataType::MIDI, 0, &valid);
729 if (valid && bufs.count().n_midi() > idx) {
730 MidiBuffer& mbuf = bufs.get_midi(idx);
732 for (luabridge::Iterator i (lua_midi_sink_tbl); !i.isNil (); ++i) {
733 if (!i.key ().isNumber ()) { continue; }
734 if (!i.value ()["time"].isNumber ()) { continue; }
735 if (!i.value ()["data"].isTable ()) { continue; }
736 luabridge::LuaRef data_tbl (i.value ()["data"]);
737 framepos_t tme = i.value ()["time"];
738 if (tme < 1 || tme > nframes) { continue; }
741 for (luabridge::Iterator di (data_tbl); !di.isNil () && size < sizeof(data); ++di, ++size) {
742 data[size] = di.value ();
744 if (size > 0 && size < 64) {
745 mbuf.push_back(tme - 1, size, data);
752 } catch (luabridge::LuaException const& e) {
753 PBD::error << "LuaException: " << e.what () << "\n";
755 std::cerr << "LuaException: " << e.what () << "\n";
759 #ifdef WITH_LUAPROC_STATS
760 int64_t t1 = g_get_monotonic_time ();
762 lua.collect_garbage (); // rt-safe, slight *regular* performance overhead
763 #ifdef WITH_LUAPROC_STATS
765 int64_t t2 = g_get_monotonic_time ();
766 int64_t ela0 = t1 - t0;
767 int64_t ela1 = t2 - t1;
768 if (ela0 > _stats_max[0]) _stats_max[0] = ela0;
769 if (ela1 > _stats_max[1]) _stats_max[1] = ela1;
770 _stats_avg[0] += ela0;
771 _stats_avg[1] += ela1;
778 LuaProc::add_state (XMLNode* root) const
784 gchar* b64 = g_base64_encode ((const guchar*)_script.c_str (), _script.size ());
785 std::string b64s (b64);
787 XMLNode* script_node = new XMLNode (X_("script"));
788 script_node->add_property (X_("lua"), LUA_VERSION);
789 script_node->add_content (b64s);
790 root->add_child_nocopy (*script_node);
792 for (uint32_t i = 0; i < parameter_count(); ++i) {
793 if (parameter_is_input(i) && parameter_is_control(i)) {
794 child = new XMLNode("Port");
795 snprintf(buf, sizeof(buf), "%u", i);
796 child->add_property("id", std::string(buf));
797 snprintf(buf, sizeof(buf), "%+f", _shadow_data[i]);
798 child->add_property("value", std::string(buf));
799 root->add_child_nocopy(*child);
805 LuaProc::set_script_from_state (const XMLNode& node)
808 if (node.name () != state_node_name ()) {
812 if ((child = node.child (X_("script"))) != 0) {
813 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
814 if (!(*n)->is_content ()) { continue; }
816 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
817 _script = std::string ((const char*)buf, size);
819 if (load_script ()) {
820 PBD::error << _("Failed to load Lua script from session state.") << endmsg;
822 std::cerr << "Failed Lua Script: " << _script << std::endl;
829 if (_script.empty ()) {
830 PBD::error << _("Session State for LuaProcessor did not include a Lua script.") << endmsg;
834 PBD::error << _("Invalid/incompatible Lua script found for LuaProcessor.") << endmsg;
841 LuaProc::set_state (const XMLNode& node, int version)
843 #ifndef NO_PLUGIN_STATE
845 XMLProperty const * prop;
846 XMLNodeConstIterator iter;
854 if (_script.empty ()) {
855 if (set_script_from_state (node)) {
860 #ifndef NO_PLUGIN_STATE
861 if (node.name() != state_node_name()) {
862 error << _("Bad node sent to LuaProc::set_state") << endmsg;
866 nodes = node.children ("Port");
867 for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
869 if ((prop = child->property("id")) != 0) {
870 port = prop->value().c_str();
872 warning << _("LuaProc: port has no symbol, ignored") << endmsg;
875 if ((prop = child->property("value")) != 0) {
876 value = prop->value().c_str();
878 warning << _("LuaProc: port has no value, ignored") << endmsg;
881 sscanf (port, "%" PRIu32, &port_id);
882 set_parameter (port_id, atof(value));
886 return Plugin::set_state (node, version);
890 LuaProc::parameter_count () const
892 return _ctrl_params.size ();
896 LuaProc::default_value (uint32_t port)
898 if (_ctrl_params[port].first) {
902 int lp = _ctrl_params[port].second;
903 return _param_desc[lp].normal;
907 LuaProc::set_parameter (uint32_t port, float val)
909 assert (port < parameter_count ());
910 if (get_parameter (port) == val) {
913 _shadow_data[port] = val;
914 Plugin::set_parameter (port, val);
918 LuaProc::get_parameter (uint32_t port) const
920 if (parameter_is_input (port)) {
921 return _shadow_data[port];
923 return _control_data[port];
928 LuaProc::get_parameter_descriptor (uint32_t port, ParameterDescriptor& desc) const
930 assert (port <= parameter_count ());
931 int lp = _ctrl_params[port].second;
932 const ParameterDescriptor& d (_param_desc.find(lp)->second);
934 desc.lower = d.lower;
935 desc.upper = d.upper;
936 desc.normal = d.normal;
937 desc.toggled = d.toggled;
938 desc.logarithmic = d.logarithmic;
939 desc.integer_step = d.integer_step;
940 desc.sr_dependent = d.sr_dependent;
941 desc.enumeration = d.enumeration;
943 desc.label = d.label;
944 desc.scale_points = d.scale_points;
946 desc.update_steps ();
951 LuaProc::get_parameter_docs (uint32_t port) const {
952 assert (port <= parameter_count ());
953 int lp = _ctrl_params[port].second;
954 return _param_doc.find(lp)->second;
958 LuaProc::nth_parameter (uint32_t port, bool& ok) const
960 if (port < _ctrl_params.size ()) {
969 LuaProc::parameter_is_input (uint32_t port) const
971 assert (port < _ctrl_params.size ());
972 return (!_ctrl_params[port].first);
976 LuaProc::parameter_is_output (uint32_t port) const
978 assert (port < _ctrl_params.size ());
979 return (_ctrl_params[port].first);
982 std::set<Evoral::Parameter>
983 LuaProc::automatable () const
985 std::set<Evoral::Parameter> automatables;
986 for (uint32_t i = 0; i < _ctrl_params.size (); ++i) {
987 if (parameter_is_input (i)) {
988 automatables.insert (automatables.end (), Evoral::Parameter (PluginAutomation, 0, i));
995 LuaProc::describe_parameter (Evoral::Parameter param)
997 if (param.type () == PluginAutomation && param.id () < parameter_count ()) {
998 int lp = _ctrl_params[param.id ()].second;
999 return _param_desc[lp].label;
1005 LuaProc::print_parameter (uint32_t param, char* buf, uint32_t len) const
1008 if (param < parameter_count ()) {
1009 snprintf (buf, len, "%.3f", get_parameter (param));
1016 boost::shared_ptr<ScalePoints>
1017 LuaProc::parse_scale_points (luabridge::LuaRef* lr)
1019 if (!(*lr)["scalepoints"].isTable()) {
1020 return boost::shared_ptr<ScalePoints> ();
1024 boost::shared_ptr<ScalePoints> rv = boost::shared_ptr<ScalePoints>(new ScalePoints());
1025 luabridge::LuaRef scalepoints ((*lr)["scalepoints"]);
1027 for (luabridge::Iterator i (scalepoints); !i.isNil (); ++i) {
1028 if (!i.key ().isString ()) { continue; }
1029 if (!i.value ().isNumber ()) { continue; }
1030 rv->insert(make_pair(i.key ().cast<std::string> (),
1031 i.value ().cast<float> ()));
1035 if (rv->size() > 0) {
1038 return boost::shared_ptr<ScalePoints> ();
1041 boost::shared_ptr<ScalePoints>
1042 LuaProc::get_scale_points (uint32_t port) const
1044 int lp = _ctrl_params[port].second;
1045 return _param_desc.find(lp)->second.scale_points;
1049 LuaProc::setup_lua_inline_gui (LuaState *lua_gui)
1051 lua_State* LG = lua_gui->getState ();
1052 LuaBindings::stddef (LG);
1053 LuaBindings::common (LG);
1054 LuaBindings::dsp (LG);
1056 lua_gui->Print.connect (sigc::mem_fun (*this, &LuaProc::lua_print));
1057 lua_gui->do_command ("function ardour () end");
1058 lua_gui->do_command (_script);
1060 // TODO think: use a weak-pointer here ?
1061 // (the GUI itself uses a shared ptr to this plugin, so we should be good)
1062 luabridge::getGlobalNamespace (LG)
1063 .beginNamespace ("Ardour")
1064 .beginClass <LuaProc> ("LuaProc")
1065 .addFunction ("shmem", &LuaProc::instance_shm)
1069 luabridge::push <LuaProc *> (LG, this);
1070 lua_setglobal (LG, "self");
1072 luabridge::push <float *> (LG, _shadow_data);
1073 lua_setglobal (LG, "CtrlPorts");
1075 ////////////////////////////////////////////////////////////////////////////////
1077 #include "ardour/search_paths.h"
1081 LuaProc::preset_name_to_uri (const std::string& name) const
1083 std::string uri ("urn:lua:");
1087 sha1_write (&s, (const uint8_t *) name.c_str(), name.size ());
1088 sha1_write (&s, (const uint8_t *) _script.c_str(), _script.size ());
1089 sha1_result_hash (&s, hash);
1094 LuaProc::presets_file () const
1096 return string_compose ("lua-%1", _info->unique_id);
1100 LuaProc::presets_tree () const
1102 XMLTree* t = new XMLTree;
1103 std::string p = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
1105 if (!Glib::file_test (p, Glib::FILE_TEST_IS_DIR)) {
1106 if (g_mkdir_with_parents (p.c_str(), 0755) != 0) {
1107 error << _("Unable to create LuaProc presets directory") << endmsg;
1111 p = Glib::build_filename (p, presets_file ());
1113 if (!Glib::file_test (p, Glib::FILE_TEST_EXISTS)) {
1114 t->set_root (new XMLNode (X_("LuaPresets")));
1118 t->set_filename (p);
1127 LuaProc::load_preset (PresetRecord r)
1129 boost::shared_ptr<XMLTree> t (presets_tree ());
1134 XMLNode* root = t->root ();
1135 for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
1136 XMLProperty const * label = (*i)->property (X_("label"));
1138 if (label->value() != r.label) {
1142 for (XMLNodeList::const_iterator j = (*i)->children().begin(); j != (*i)->children().end(); ++j) {
1143 if ((*j)->name() == X_("Parameter")) {
1144 XMLProperty const * index = (*j)->property (X_("index"));
1145 XMLProperty const * value = (*j)->property (X_("value"));
1148 set_parameter (atoi (index->value().c_str()), atof (value->value().c_str ()));
1157 LuaProc::do_save_preset (std::string name) {
1159 boost::shared_ptr<XMLTree> t (presets_tree ());
1164 std::string uri (preset_name_to_uri (name));
1166 XMLNode* p = new XMLNode (X_("Preset"));
1167 p->add_property (X_("uri"), uri);
1168 p->add_property (X_("label"), name);
1170 for (uint32_t i = 0; i < parameter_count(); ++i) {
1171 if (parameter_is_input (i)) {
1172 XMLNode* c = new XMLNode (X_("Parameter"));
1173 c->add_property (X_("index"), string_compose ("%1", i));
1174 c->add_property (X_("value"), string_compose ("%1", get_parameter (i)));
1175 p->add_child_nocopy (*c);
1178 t->root()->add_child_nocopy (*p);
1180 std::string f = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
1181 f = Glib::build_filename (f, presets_file ());
1188 LuaProc::do_remove_preset (std::string name)
1190 boost::shared_ptr<XMLTree> t (presets_tree ());
1194 t->root()->remove_nodes_and_delete (X_("label"), name);
1195 std::string f = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
1196 f = Glib::build_filename (f, presets_file ());
1201 LuaProc::find_presets ()
1203 boost::shared_ptr<XMLTree> t (presets_tree ());
1205 XMLNode* root = t->root ();
1206 for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
1208 XMLProperty const * uri = (*i)->property (X_("uri"));
1209 XMLProperty const * label = (*i)->property (X_("label"));
1214 PresetRecord r (uri->value(), label->value(), true);
1215 _presets.insert (make_pair (r.uri, r));
1220 ////////////////////////////////////////////////////////////////////////////////
1222 LuaPluginInfo::LuaPluginInfo (LuaScriptInfoPtr lsi) {
1223 if (lsi->type != LuaScriptInfo::DSP) {
1224 throw failed_constructor ();
1229 creator = lsi->author;
1230 category = lsi->category;
1231 unique_id = lsi->unique_id;
1233 n_inputs.set (DataType::AUDIO, 1);
1234 n_outputs.set (DataType::AUDIO, 1);
1237 _is_instrument = category == "Instrument";
1241 LuaPluginInfo::load (Session& session)
1243 std::string script = "";
1244 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
1245 return PluginPtr ();
1249 script = Glib::file_get_contents (path);
1250 } catch (Glib::FileError err) {
1251 return PluginPtr ();
1254 if (script.empty ()) {
1255 return PluginPtr ();
1259 PluginPtr plugin (new LuaProc (session.engine (), session, script));
1261 } catch (failed_constructor& err) {
1264 return PluginPtr ();
1267 std::vector<Plugin::PresetRecord>
1268 LuaPluginInfo::get_presets (bool /*user_only*/) const
1270 std::vector<Plugin::PresetRecord> p;
1271 XMLTree* t = new XMLTree;
1272 std::string pf = Glib::build_filename (ARDOUR::user_config_directory (), "presets", string_compose ("lua-%1", unique_id));
1273 if (Glib::file_test (pf, Glib::FILE_TEST_EXISTS)) {
1274 t->set_filename (pf);
1276 XMLNode* root = t->root ();
1277 for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
1278 XMLProperty const * uri = (*i)->property (X_("uri"));
1279 XMLProperty const * label = (*i)->property (X_("label"));
1280 p.push_back (Plugin::PresetRecord (uri->value(), label->value(), true));