How do i... Lua: get a script to run after each session load?

So i have this script /usr/scripts/pin_ardour which, as the name suggests, pins ardour’s processes to the correct cores for optimal performance. For now my ardour start script just runs this after a 10 sec delay in the background, it’s also bound to a key combination in my window manager.

I’m guessing with the lua API there’s a way to have this run on certain events in ardour, such as on session load, new session, etc. So far my attempts have been unsuccessful.

Any ideas on how i can accomplish this? Thanks in advance!

1 Like

There’s an example here:

and you may also find ardour/share/scripts/_system_exec.lua at master · Ardour/ardour · GitHub handy.

You can add that script via Menu > Edit > Lua > Script Manager under “Hook/Callbacks”

Wanna share the script? I’m curious :blush:

sure, here’s the shell script. It has the lua snippet (and where to put it) in the comments. Got some help from Perplexity for the ‘ps’ syntax.

#!/bin/bash
# NOTE TO SELF: adjust "cpu" and "cpu_gui" to each machine
#
# to hook this into ardour with the lua API:
# Save as ~/.config/ardour9/scripts/pin_ardour_threads.lua --->
#
# ardour {
# 	["type"]    = "EditorHook",
# 	name        = "Load Session Hook Example",
# 	author      = "Ardour Team",
# 	description = "Run a script on session load/create",
# }
# 
# -- subscribe to signals
# -- http://manual.ardour.org/lua-scripting/class_reference/#LuaSignal.LuaSignal
# function signals ()
# 	s = LuaSignal.Set()
# 	s:add ({[LuaSignal.SetSession] = true})
# 	return s
# end
# 
# -- create callback functions
# function factory () return function ()
#   os.execute ("/usr/scripts/pin_ardour")
# end end

cpu="0,2,4,6,8,10" # performance/fast cores, 1 thread each
cpu_gui="12-21"    # other cores

#PID="$(pgrep -f '/[Aa]rdour-[0-9]' | head -n1)"
#[ -n "$PID" ] || { echo "Ardour not running"; exit 1; }

pgrep -f '/[Aa]rdour-[0-9]' | while read -r PID; do
  notify-send "$(basename "$0")" "Pinning ardour process ID $PID"
  # process-level priority
  renice -n -18 -p "$PID"
  ionice -c2 -n0 -p "$PID"

  # child processes
  for P in $(pgrep -P "$PID"); do
    renice -n -18 -p "$P"
    ionice -c2 -n0 -p "$P"
  done

  ps -L -p "$PID" -o tid=,comm= | while read -r tid comm; do
    case "$comm" in
      IO-*|RT-*|*AudioEngine*)
        echo "RT thread:      tid=$tid, comm=$comm"
        taskset -pc "$cpu"     "$tid" >/dev/null
      ;;
      
      *LV2Worker*)
        echo "worker thread:  tid=$tid, comm=$comm"
        taskset -pc "$cpu_gui" "$tid" >/dev/null
      ;;
      
      *)
        echo "non-RT thread:  tid=$tid, comm=$comm"
        taskset -pc "$cpu_gui" "$tid" >/dev/null
      ;;
    esac
  done
done
1 Like