Plasma+Wayland: Script to set refresh rate to match Core FPS

The following scripts set all of the connected monitors to the closest supported refresh rate reported by the core.

For it to work:

  • Retroarch frontend logging level has to be set at least to INFO
  • Monitor has to support a refresh rate that is “close enough” to the core FPS.
  • kscreenctl (part of Plasma 6.8) needs to be present.
  • Edit retroarch.resswitch.wrap.sh and change
    CHANGE_REFRESH_SCRIPT="/home/koko/scripts/refresh.rate.set.plasma.wayland.sh"
    …so that CHANGE_REFRESH_SCRIPT points to the location where you will place the attached refresh.rate.set.plasma.wayland.sh
  • Make both scripts executable
  • Use: /path/to/retroarch.resswitch.wrap.sh retroarch

Altough Retroarch already offers a way to switch to PAL/NTSC this also:

  • Works in fullscreen or windowed mode
  • Will set the initial refresh rate (taken from the first screen only) on exit.
  • Will switch to any supported refresh rate, not just PAL/NTSC
  • Will switch refresh rate even if the core changes it while it is running.

The main wrapper script:

retroarch.resswitch.wrap.sh
#!/bin/bash

RAEXE="$1"
shift

CHANGE_REFRESH_SCRIPT="/home/koko/scripts/refresh.rate.set.plasma.wayland.sh"

SAVED_HZ=$(kscreenctl active-output list-modes | awk -F '[@*]' '/\*/ {print $2}')

set_rate(){
    "$CHANGE_REFRESH_SCRIPT" "$1"
}

onexit(){
    set_rate $SAVED_HZ
}

trap 'onexit' EXIT
trap 'onexit' INT
trap 'onexit' TERM

last_fps=""
stdbuf -oL -eL "$RAEXE" "$@" -v 2>&1 |
while IFS= read -r line; do
    printf '%s\n' "$line"

    if [[ "$line" =~ FPS:\ ([0-9]+([.][0-9]+)?) ]]; then
        fps="${BASH_REMATCH[1]}"

        if [[ "$fps" != "$last_fps" ]]; then
            echo "Core FPS changed $fps — Updating monitor(s) refresh"
            set_rate "$fps"
            last_fps="$fps"
        fi
    fi
done

The refresh rate helper script, for plasma 6.8+Wayland:

refresh.rate.set.plasma.wayland.sh
#!/bin/bash

fps="$1"

while read -r monitor; do
    modes=$(kscreenctl "$monitor" list-modes)

    res=$(awk '/\*/ {sub(/^[0-9]+:/,""); sub(/@.*/,""); print; exit}' <<< "$modes")

    result=$(awk -v fps="$fps" -v res="$res" '
    {
        if (match($0,/^[0-9]+:[0-9]+x[0-9]+@[0-9.]+/)) {
            split(substr($0,1,RLENGTH),a,/[:@]/)
            if (a[2] == res) {
                d = a[3]-fps
                if (d < 0) d = -d
                if (!found || d < best) {
                    found=1
                    best=d
                    idx=a[1]
                    hz=a[3]
                }
            }
        }
    }
    END {
        if(found) print idx, hz
    }
    ' <<< "$modes")

    if [[ -n "$result" ]]; then
        read -r mode hz <<< "$result"
        echo "$monitor: $res -> ${hz} Hz"
        kscreenctl "$monitor" set-mode "$mode"
    fi
done < <(kscreenctl list-outputs --enabled --names)