Bash script: RetroArch Attract Mode Playlist Shuffler

RetroArch Attract Mode Playlist Shuffler


This script randomly selects games from a RetroArch playlist, starts them in an infinite loop and every game is displayed for a configurable amount of time.

Script behaviour is configurable by the following commandline arguments:

-p /path/to/your/RetroArch/playlist.lpl (load a playlist)
-t timeout (in seconds, amount of time to run each game)
-h (show an help message)

Anything following those arguments will be executed in place of the default retroarch executable, so you can do something like this:

./script.sh -p /tmp/myplaylist.lpl -t 30 /usr/local/bin/retroarch-nightly --set-shader /path/to/my/custom/shader.slangp

That command would shuffle /tmp/myplaylist.lpl displaying each game for 30 seconds through a retroarch executable in /usr/local/bin named retroarch-nightly which applies a custom shader taken from /path/to/my/custom/shader.slangp

Note that --set-shader is a RetroArch option and multiple options are allowed.

There are other things you can change by editing the script, like displaying a big/little scrolling or fixed banner (FIXED_BANNER variable), or forcing a specific core file (FORCE_CORE variable).

You can also pause the shuffling if you find a game worth playing or skipping to the next one without waiting.

Very useful if you’re bored :slight_smile:

Version 0.5.1: Avoid multiple reads due to special keys

Version 0.5.1, Expand
#!/bin/bash

# This software is released into the public domain.
#
# You are free to use, modify, distribute, and sell this software
# for any purpose, without restriction.
#
# This software is provided "AS IS", without warranty of any kind.


# RetroArch Attract Mode Playlist Shuffler

# Version 0.5.1
# Changelog:
# Avoid multiple reads due to special keys

PLAYLIST="/path/to/playlist.lpl" # Shuffle this playlist, can also be overridden by the command line
FORCE_CORE=""                    # Optional, override playlist core. Can be blank or a full path to a core
TIMEOUT=60                       # How much seconds before the next title
FIXED_BANNER="yes"               # "yes": fixed banner, "no": scrolling banner
BIG_BANNER="yes"                 # "yes": use a big banner, "no": use a little banner


#--------- config ends here ----------

#--------- command line arguments ----

RETROARCH_CMD=()

usage() {
    echo
    printf 'Usage: %s [-p playlist.lpl] [-h] [command [arguments...]]\n' "$0"
    echo
    echo   "  -p FILE       RetroArch playlist"
    echo   "  -t TIMEOUT    How much seconds before the next title"
    echo   "  -h            Show this help"
    echo
    echo   "Anything after those arguments are executed in place of the default retroarch executable."
    printf 'eg: %s -p /tmp/myplaylist.lpl /path/to/my/custom/retroarch --set-shader myshader-slangp \n'
}

while (($#)); do
    case "$1" in
        -p)
            if [[ -z "$2" || "$2" == -* ]]; then
                echo "Error: Option -p requires a playlist path."
                usage
                exit 1
            fi
            PLAYLIST="$2"
            PLAYLIST_FROM_CLI="yes"
            shift 2
            ;;

        -t)
            if [[ ! "$2" =~ ^[0-9]+$ ]]; then
                echo "Error: Option -t requires a valid positive integer value."
                usage
                exit 1
            fi
            TIMEOUT="$2"
            shift 2
            ;;

        -h)
            usage
            exit 0
            ;;

        --)
            shift
            RETROARCH_CMD=("$@")
            break
            ;;

        *)
            RETROARCH_CMD=("$@")
            break
            ;;
    esac
done

# Default executable
if ((${#RETROARCH_CMD[@]} == 0)); then
    RETROARCH_CMD=(retroarch)
fi

#-------------------------------------


# Terminal colors
if [[ -t 1 ]]; then
    BOLD='\033[1m'
    DIM='\033[2m'
    RED='\033[31m'
    GREEN='\033[32m'
    YELLOW='\033[33m'
    BLUE='\033[34m'
    CYAN='\033[36m'
    RESET='\033[0m'
    BLINK='\033[5m'
else
    BOLD='' DIM='' RED='' GREEN='' YELLOW='' BLUE='' CYAN='' RESET=''
fi

echo_bold()   { printf '%b%s%b\n' "$BOLD"   "$*" "$RESET"; }
echo_dim()    { printf '%b%s%b\n' "$DIM"    "$*" "$RESET"; }
echo_red()    { printf '%b%s%b\n' "$RED"    "$*" "$RESET"; }
echo_green()  { printf '%b%s%b\n' "$GREEN"  "$*" "$RESET"; }
echo_yellow() { printf '%b%s%b\n' "$YELLOW" "$*" "$RESET"; }
echo_blue()   { printf '%b%s%b\n' "$BLUE"   "$*" "$RESET"; }
echo_cyan()   { printf '%b%s%b\n' "$CYAN"   "$*" "$RESET"; }
echo_blnk()   { printf '%b%b%s%b\n' "$BOLD" "$BLINK" "$*" "$RESET"; }

# Startup banner
do_little_banner(){
    BANNER_LINES=12
    BANNER_WIDTH=42
    echo_cyan '              ___       ___'
    echo_cyan '              \  \     /  /'
    echo_cyan '    ___   _____\  \___/  /_____   ___'
    echo_cyan '   /  /  /    __         __    \  \  \'
    echo_cyan '  /  /__/    |__|       |__|    \__\  \'
    echo_cyan ' /                                     \'
    echo_cyan '/_____                             _____\'
    echo_cyan '     /______    _________    ______\'
    echo_cyan '           /   /         \   \'
    echo_cyan '          /___/           \___\'
    echo
    echo_blnk ' .:: RetroArch Playlist Attract Mode ::.'
    echo
}

# Startup banner
    do_big_banner(){
        BANNER_LINES=21
        BANNER_WIDTH=65
        echo_cyan '                     _____           _____'
        echo_cyan '                     \    \         /    /'
        echo_cyan '                      \    \       /    /'
        echo_cyan '      _____    ________\    \_____/    /________    _____'
        echo_cyan '     /    /   /                                 \   \    \'
        echo_cyan '    /    /   /       ____             ____       \   \    \'
        echo_cyan '   /    /___/       |    |           |    |       \___\    \'
        echo_cyan '  /                 |____|           |____|                 \'
        echo_cyan ' /                                                           \'
        echo_cyan '/_________                                             _______\'
        echo_cyan '         /                                             \'
        echo_cyan '        /_________       ______________       __________\'
        echo_cyan '                 /      /              \      \'
        echo_cyan '                /      /                \      \'
        echo_cyan '               /      /                  \      \'
        echo_cyan '              /______/                    \______\'
        echo
        echo
        echo_blnk "            .:: RetroArch Playlist Attract Mode ::."
        echo_dim  "            ---------------------------------------"
        echo
    }


    do_banner(){
        [[ "$FIXED_BANNER" == "yes" ]] && printf '\033[1;1H' #cursor at 1,1
        if [[ "$BIG_BANNER" == "yes" ]] ; then
            do_big_banner
        else
            do_little_banner
        fi
    }

    do_narrow_banner(){
        printf '\033[1;1H' #cursor at 1,1
        for ((i = 0; i < BANNER_LINES; i++)); do
            echo
        done
    }

    set_scroll_region() {
        printf '\033[%dr' "$((BANNER_LINES + 1))"
    }

    redraw_banner() {

        # Clear previous banner
        for ((i = 1; i <= BANNER_LINES; i++)); do
            printf '\033[%d;1H\033[2K' "$i"
        done

        #redraw thew banner without overwriting underlying content
        if (( $(tput cols) >= BANNER_WIDTH )) ; then
            do_banner
        else
            do_narrow_banner
        fi

        # restore "scrolling" area
        set_scroll_region

        # put the cursor back to the start of the scroling area
        printf '\033[%d;1H' "$((BANNER_LINES + 1))"
    }

    init_screen() {
        # Clear the screen and move curor to top left
        printf '\033[2J\033[H'
        set_scroll_region
        redraw_banner
    }


# Restore terminal behaviour
    reset_screen() {
        printf '\033[r\033[?25h'              # Reset scrolling region and show cursor
        printf '\033[%d;1H' "$(tput lines)"   # Move cursor to the first column of the last terminal row
    }


is_udp_port_busy(){
    ss -ulnp|grep ":$1" &>/dev/null
}

is_file(){
    [[ -n "$1" && -f "$1" && -s "$1" && -r "$1" ]]
}


# Draw banner?
if [[ "$FIXED_BANNER" == "yes" ]]; then
    init_screen
    trap redraw_banner WINCH
else
    do_banner
fi

# Sanity checks
echo
echo_bold "INITIALIZATION"

if ! command -v "${RETROARCH_CMD[0]}" &>/dev/null; then
    echo_red "Error: Invalid RetroArch executable:"
    echo "${RETROARCH_CMD[0]}"
    exit 1
fi

if ! "${RETROARCH_CMD[@]}" --command "LOAD_CONTENT" &>/dev/null ; then
    echo_red "Error: RetroArch does not support LOAD_CONTENT command."
    exit 1
fi

if [[ -n "$PLAYLIST" ]]; then
    [ "_$PLAYLIST_FROM_CLI" = "_" ] && PLSMSG="from script"
    echo_blue "Using playlist $PLSMSG: $PLAYLIST"
fi

if [[ -z "$PLAYLIST" ]] ; then
    echo_red "Error: No playlist specified."
    exit 1
fi

if ! is_file "$PLAYLIST" ; then
    echo_red "Error: Playlist file \"$PLAYLIST\" is not readable."
    exit 1
fi

#Find a free upd port with ss or exit
    if ! which ss &>/dev/null ; then
        echo "Error: ss executable is required, but missing."
        exit 1
    fi

echo_blue "Searching for a free UDP port..."

for P in $(seq 54000 55300) ; do
    if ! is_udp_port_busy "$P" ; then
        UDP_PORT="$P"
        break
    fi
done

if [[ -z "$UDP_PORT" ]]; then
    echo_red "Unable to find a free UDP port."
    exit 1
fi

echo_green "Using UDP port: $UDP_PORT"

retroarch_remote_cmd(){
    "${RETROARCH_CMD[@]}" --command "$1;127.0.0.1;$UDP_PORT" &>/dev/null
}

# Cleanup on exit
# Hook to Kill remote retroarch on exit
    cleanup() {
        trap - EXIT SIGINT SIGTERM # remove the hook, do not trap twice
        echo
        rm "$TEMP_CONFIG" &>/dev/null
        reset_screen

        #Since retroarch kill us on exit we have to stop it as the last operation here.
        echo_blue "Stopping remote instance..."
        retroarch_remote_cmd "QUIT"
        sleep 0.1
        retroarch_remote_cmd "QUIT"
        exit 0
    }
    trap cleanup EXIT SIGINT SIGTERM

# Run Retroarch in a separate shell which kills the parent (me) when it exits.
    retroarch_parent_killer() {
        "${RETROARCH_CMD[@]}" "$@" &>/dev/null
        echo ; echo_red "RetroArch is dead, long live RetroArch!"
        kill -TERM "$$"
    }

# Temporary RetroArch configuration
TEMP_CONFIG=$(mktemp)

    echo 'history_list_enable = "false"'          >  "$TEMP_CONFIG"
    echo 'network_cmd_enable = "true"'            >> "$TEMP_CONFIG"
    echo 'network_cmd_port = "'$UDP_PORT'"'       >> "$TEMP_CONFIG"
    echo 'network_cmd_bind_address = "127.0.0.1"' >> "$TEMP_CONFIG"
    echo 'config_save_on_exit = "false"'          >> "$TEMP_CONFIG"

# Start RetroArch
echo
echo_bold "STARTING RETROARCH"

retroarch_parent_killer --appendconfig "$TEMP_CONFIG" &

# Wait for UDP socket
UDP_OK=""

for i in $(seq 1 20) ; do
    echo_blue "Waiting for RetroArch to open the UDP port..."
    sleep 1.0
    if is_udp_port_busy "$UDP_PORT" ; then
        UDP_OK="1"
        break
    fi
done

if [[ "$UDP_OK" != "1" ]] ; then
    echo_red "Timeout waiting for RetroArch to open the UDP port."
    exit 1
fi

echo_green "RetroArch is ready."
echo

echo_red "Configuration will NOT be saved on exit."
echo_red "It is NOT advised to manually save either."
echo

# Playlist parsing

DEFAULT_CORE=$(grep '"default_core_path"' "$PLAYLIST" | cut -d '"' -f 4 | head -n 1)


mapfile -t USEFUL_PLAYLIST < <(                        # Reformat the playlist: and make an array
    tr -d '\n' < "$PLAYLIST"                         | # Put everything on one line
    tr '}' '\n'                                      | # Add new lines in place of '}'
    grep -E ' "path": | "core_path": | "label": '    | # Skip lines not containing all the needed keys
    shuf                                               # Shuffle
)

NUM_TITLES=${#USEFUL_PLAYLIST[@]}
echo_green "Found $NUM_TITLES titles."

TITL=0


# Main loop
IFS=$'\n'
i=0
while (( i < $NUM_TITLES )); do

    (( i >= NUM_TITLES )) && i=0 # Defensive

    line=${USEFUL_PLAYLIST[i]}

    USEFUL_KEYS=$(                          # Reformat each line to be easilly parsable.
        echo -E "$line"                   | #
        sed 's/", /\n/g'                  | # we have now: "key": "value", "key": "value", so replace every '", ' with a new line
        cut -d \" -f 2-                   | # strip everything before "key, and have key": "value
        grep -E '^path|^core_path|^label' | # keep only required keys
        sed 's/ "//'  # we have now: key": "value, strip leading space+double quotes.
    )

    #we have now: key: value; the first ":" is the separator, finally extract values.
        ROM=$(   echo "$USEFUL_KEYS" | grep ^path  | cut -d ":" -f 2)
        LABEL=$( echo "$USEFUL_KEYS" | grep ^label | cut -d ":" -f 2)
        CORE=$(  echo "$USEFUL_KEYS" | grep ^core  | cut -d ":" -f 2)


    CORE_SOURCE="Specific to title."

    if [[ -n "$FORCE_CORE" ]] ; then
        CORE="$FORCE_CORE"
        CORE_SOURCE="Forced by the script."
    else
        if [[ "$CORE" = "DETECT" ]] ; then
            CORE="$DEFAULT_CORE"
            CORE_SOURCE="Default core playlist."

            if [[ -z "$CORE" ]]; then
                echo
                echo_yellow "Core set to DETECT for $LABEL"
                echo_yellow "But no default core was set in the playlist."
                echo_blue "Skipping..."
                continue
            fi
        fi
    fi

    echo
    echo_dim "----------------------------------------"
    echo_bold "TITLE $(($i+1)) / $NUM_TITLES"
    echo_dim "----------------------------------------"

    echo_bold "NAME:  $LABEL"
    echo_bold "ROM:   $(basename "$ROM")"
    echo_bold "CORE:  $CORE"
    echo_dim  "       ($CORE_SOURCE)"
    echo_dim "----------------------------------------"

    if ! is_file "$CORE" ; then
        echo_red "Core file is not readable, skipping."
        continue
    fi

    retroarch_remote_cmd "LOAD_CONTENT $CORE|$ROM" &

    echo
    echo_yellow "Wanna play $LABEL?"

    read -sp "Enter to play, p for previous, any other to skip, or wait $TIMEOUT seconds..." -t "$TIMEOUT" -n 1
    while read -rs -t 0.05 -n 1 discard; do :; done #discard pending characters (some keys generates multiple ones)

    if [[ "$REPLY" = "" ]] ; then
        echo
        echo_green "Have fun!"
        echo_blue "Hit ENTER for the next title"
        read -s
        ((i++))

    elif [[ "$REPLY" = "p"  ]] ; then
        (( i > 0 )) && ((i--))

    else
        ((i++))

    fi

    (( i >= NUM_TITLES )) && i=0

done

5 Likes

I’ve tested your script. Edit: Never mind. My RetroArch configuration didn’t have a the needed settings enabled in order to function this. With the new update of the script, I understand how its working and the rest of my comment is completely useless.

old suggestions, that are no longer needed to do for me

For me the games does not run after I press y. The command retroarch --command "LOAD_CONTENT $CORE|$ROM" does not work. However replacing it with retroarch -L "$CORE" -- "$ROM" runs the game.

Also there seems to be no mechanism to exit the loop, if any other key is pressed. I added a an else to break out of the loop. Also I placed retroarch command in the if…else statement, to not run first game automatically:

    read -r -p "Wanna play $LABEL? ('y' to play, any other to skip, or wait $TIMEOUT seconds...) " -t $TIMEOUT -n 1
    if [ "$REPLY" = "y" ]; then
        echo -e "\nHave fun!"
        echo "Hit ENTER for the next game."
        retroarch -L "$CORE" -- "$ROM"
    else
        break
    fi

Also added the -r to read and changed the "y" to 'y'. I have some thoughts and suggestions:

  • just an idea, but instead removing the history file, you could specify an alternative history file that is used for random games only, in example instead deleting the file you could mv "${RANDOM_HISTORY}" "${HISTORY_FILE}" to use the random history file and later instead removing it it could be put back to its place, but be careful with the cleanup routine then
  • what happens to those files if in example by accident another instance of the script is run or if retroarch is run otherwise?
  • you should use quoting in echo "ROM: $(basename $ROM)", because it runs the command, the extra quoting works because it is inside $() command and does not need or should be escaped: echo "ROM: $(basename "$ROM")"
  • read command without option -r will mangle backslashes, so always use read -r unless you know exactly it won’t be a problem, I guess in this case its alright but wanted to mention this as I made a habit out of it

Meanwhile I also wrote an alternative script with different approach. This one uses the jq command, a common tool but not preinstalled on most machines. It reads the file format as json file, in which we can do a more safe operation. The disadvantage is, its not a standard tool that everyone has.

My approach is just reading the file a few times without temporary file actions. A big advantage the default core path is used if no core path is specified for the game entry. That way we don’t have to specify any core, it will be read from the file entry. Another advantage is, that we can pass any playlist file as an argument, otherwise it defaults to what’s specified in the script. This is possible, because the core is read from the entry.

Another point is, that the read-menu only appears, if we are in a terminal. So if the script is run through automated method (let’s say a keyboard shortcut to invoke the script), then no such menu appears and the game is run.

I just wanted provide an alternative, as your script was very inspiring.

randomretroarch :

#!/usr/bin/env bash

# Random RetroArch
#   Play a random game from a RetroArch playlist.
#
# Requires `jq` and off course `retroarch`.
#
# Examples:
#
#   randomretroarch
#   randomretroarch ~"/.config/retroarch/playlists/Arcade - MAME.lpl"

# Your default RetroArch playlist if no argument is given.
default_playlist_path="~/.config/retroarch/playlists/builtin/content_history.lpl"

# Default wait time in seconds. Cancels if timeout passed without user interaction.
timeout=60

# If no argument is given, use default value.
playlist_path="${1:-${default_playlist_path}}"

# Expand leading tilde with users home directory.
playlist_path="${playlist_path/#\~/${HOME}}"

# Read how many game entries are listed in the file.
number_of_games="$(jq '.items | length' -- "${playlist_path}")"

# Generate a random number based on how many games are available.
random_number="$(shuf -i 1-"${number_of_games}" -n 1)"

# Extract Rom file and core path at the specified position in list entry.
# The index must be 0-based, so decrease by one before access.
index="$((random_number - 1))"
game_path="$(jq --raw-output ".items.[${index}] .path" -- "${playlist_path}")"
core_path="$(jq --raw-output ".items.[${index}] .core_path" -- "${playlist_path}")"
label="$(jq --raw-output ".items.[${index}] .label" -- "${playlist_path}")"

# In case core path is not set, use playlists default value.
if [[ "${core_path}" == "DETECT" ]] ||
    [[ "${core_path}" == "" ]]; then
    core_path="$(jq --raw-output '.default_core_path' -- "${playlist_path}")"
fi

# Extract core filename without directory and extension.
core_name="${core_path##*/}"
core_name="${core_name%.*}"
core_name="${core_name/_libretro/}"

# If script is run interactively in a terminal by the user, then ask to
# play. Otherwise assume script is run non interactive without a terminal
# and start playing immadiately.
if [[ -t 0 ]]; then
    printf "Game:\t'%s'\n" "${label}"
    printf "Rom: \t'%s'\n" "${game_path}"
    printf "Core:\t'%s'\n" "${core_name}"
    printf "\nDo you want play?\nPress Enter-key or 'y' to start, or any other key to cancel.\n\n"
    read -r -n 1 -t "${timeout}" -p "$ "
else
    REPLY=""
fi
if [[ "${REPLY}" == "" || "${REPLY}" == "y" ]]; then
    retroarch -L "${core_path}" -- "${game_path}"
fi
printf "\nretroarch -L '%s' -- '%s'\n" "${core_path}" "${game_path}"

You’re missing the very first step"s":

The script leverages a running retroarch ability to be remotely controlled via UDP messages via another retroarch; so, the main window opens once and then stay in place; there’s no need to close and restart it for every game.

I’ll make another version which starts retroarch and the script to controls it, with a trap to kill it on exit.

You need a nightly build for that to work, as the LOAD_CONTENT remote command has been added recently.

Just CTRL-C or close the shell window is enough and keep the script simpler.

The historty managment is indeed not perfect; I will tell retroarch to disable history managment; this requires passing another “piece” of configuration file to it via --appendconfig PATH; however, since retroarch saves settings on exit, that would be part of the new configuration.
We could still write the parameter/value: config_save_on_exit = “false” in the appended config (check that suggestion in man retroarch); that way the history would be preserved; however the user will be unable to save on exit and should be warned to NOT save manually.

Will update the main script later on…

1 Like

Done:

  • the script will start retroarch main instance, and other instances to talk to it.
  • It will also append a temporary config, not saved, to disable history managment
  • Search for a free free udp port via “ss” (checked for its presence at start too) so that you can have other udp-enabled retroarch instances as well
  • You can still shuffle and see your history by configuring that playlist in the PLAYLIST var; however the core managment is still fixed.
  • Closing the retroarch window will cause the script to exit too before the next cycle iteration.
1 Like

Ah I completely misunderstood how this works. Didn’t got that RetroArch has to run in the background for listening for incoming commands. I see it’s a server/client approach, that’s cool! I have the network_cmd_enabled set to false in my configuration, so it was never going to work for me without knowing why.

For automated stuff like this, I think the best way is using appendconfig with save on exit set to false is probably the safest and best way. All needed settings are taken care off, without the user needing to explicitly enabling or disabling them. The only thing to have in mind is, that configuration changes during this session are not saved. Given the nature of the script, this is the correct approach to me.

Now the updated version works very clean as expected, and it is more clear what and how it works. I had no need to alter the script, other than the initial personalization in the header. Thanks for the update.

1 Like

This is a neat idea — a shuffle attract mode is a great way to rediscover games sitting in a playlist. The updated version sounds much cleaner too, with RetroArch starting itself and history disabled for the session. Thanks for sharing the script and refining it based on feedback.

1 Like

Updated the script with more funcionalities as per @thingsiplay ideas.

Now it is possible to either set the playlist to shuffle in the script (PLAYLIST=) or as the first argument to the command line itself.

Core can be forced in the script (CORE=) or can be left blank and the script would follow the playlist logic, using the default playlist configured core for any item with “DETECT” as core value or the core specified for the specific game.

I also added several checks.

1 Like

Added blinking text, bolds, colors, done!

I’m currently trying the script, its pretty cool. It runs the next game every 5 seconds until I accept it with y. This interactivity is an interesting concept I have to learn doing it myself. :smiley: Also very nice it can detect the default core and be used with any playlist, and all of that without an external non standard tool.

just little things i noticed in code

Just a note that the latest update (after text color) is not in a code box in the post.

I also have noticed that retroarch --appendconfig $TEMP_CONFIG &>/dev/null & the variable is not in quotes (which most likely doesn’t matter as you use mktemp, but just mentioning this as all other cases are in quotes).

Wops,. 5 seconds are not that much, i was just testing lol…

will fix those things!

I’m also trying to make the banner static and let the text scroll under it

-edit

Ah you are using 5 seconds :slight_smile:

Oh no, you just forgot the 5s in the script (edit history ;-)). t was quite fun actually.

When I close RetroArch, could it detect it instantly and stop the script? Right now when I close RetroArch, the script still waits. Not a big deal, just a little thing.

I find the colors a bit too much busy. I get it, its fun :smiley: but maybe a little bit less color and use it sparingly. Otherwise the red warnings doesn’t look like warnings.

In general the playlist parsing could be a little bit more solid, but it works for now, so not big deal either.

Yeah, playlist parsing works as long as the playlist is correct.

Script can detect if something is not right when it does not find 3 items per game, but a more rigid parsing via jq would be needed; anyway it works for almost everything.

Colors? I honestly like them, green is an ok message, white is neutral and yellow something that requires attention.

Anyway I just updated it, and the main invaders logo stay still on the screen as long as the terminal is wide enough; the text scrolls in a region under it. I understood it could be not desiderable, so I added an option do remove the banner; maybe I can add another to make it scroll, but I’m almost fried for today :laughing:

1 Like

I wrote just for fun a little parser in a more traditional way. However this approach is still not really failsafe, and worse, its actually very slow. This is only apparent with huge files like MAME playlists. Your approach is much faster, because it does not pre-parse entire file at once. Script reads every key and value and assigns it to dedicated variables. It uses Bash integrated Regex on each line.

I just had fun and want to post it here so anyone who wants to could study it, because it is relevant. Not suggesting to use it in any way here.

lpl2vars

On the “close RetroArch and stop waiting” point: if the script starts RetroArch in the background, save its PID (ra_pid=$!) and use a short poll instead of a plain fixed sleep, e.g. while kill -0 “$ra_pid” 2>/dev/null; do sleep 0.2; done, while also checking your timeout counter. Then break to the prompt as soon as the process is gone. Running RetroArch in the foreground and using its exit status is the simpler alternative.

Hi, I am unable to figure that, but I found this:

https://linuxbash.sh/post/handle-sigchld-to-asynchronously-monitor-child-processes

I was experimenting too and did a different approach. But it does not really stop script when I end RetroArch, it just keeps waiting on the read command. Will post the attempt anyway, maybe there is something useful hidden in there:

# retroarch --appendconfig "$TEMP_CONFIG" &>/dev/null &
# RA_PID=$!

retroarch_check_pid() {
    retroarch --appendconfig "$TEMP_CONFIG" &>/dev/null
    exit 0
}
retroarch_check_pid &
sleep 0.5
RA_PID=$!
sleep 0.5

Idea: Put RetroArch behind a function and let it wait before end. To not block the main script, put the function behind a background process. So we get the best of both worlds. And it even can catch the PID it seems, I have checked it with cat -- "/proc/${RA_PID}/cmdline" (remember, everything is a file in UNIX). In theory in should work, but it doesn’t. (edit: Just noticed the function name is wrong, its an artifact from earlier experiments.)

1 Like

SIGCHLD should work ok.

I will test later, and I’ve an idea for fast and robust playlist parsing too.

I think I found a working solution. Just add kill self pid of script, but that is not enough. Also use remote QUIT command to RetroArch. At least closing RetroArch works and also Ctrl+c on script in terminal too. I don’t know if there are any quirks or if the SIGCHLD method would work better. Current experiment looks like this:

retroarch_wait() {
    retroarch --appendconfig "$TEMP_CONFIG" &>/dev/null
    retroarch_remote_cmd "QUIT"
    kill -- "${$}"
    exit 0
}
retroarch_wait &
sleep 0.5
RA_PID=$!
sleep 0.5
1 Like

Uuh, smart!

I was scratching my head on SIGCHLD, because it seems it is not raised while read is blocking, for some reason i could not understand.

Your approach reverts the logic, probably what @noahnelson was referring to with “Runniung Retroarch in the foreground”, thanks, I’ll try.

I’m missing why you send the QUIT command tho.

edit: retroarch_parent_killer() seems to work fine :wink:

I’ll update the main post when i’m done with the improved parsing.

1 Like