Merge org main 0f839bef into the non-Adreno test branch

Conflicts resolved:
- build.yml: main's proot pack pin check and the Venus component fetch both kept.
- compositor.c: main's unpaced release goes through send_buffer_release (DMA-BUF quarantine).
- PulseAudioComponent: the AAudio retry loop stays; both sinks get main's control_dir.
- SessionService: main's add-on pack and proot checks, then the PowerVR driver setup and staging.
- droiddeck-session: main's stretch and refresh arguments with the selectable backend.
- droiddeck-gpu: main's desktop window mode on the wayland backend; PowerVR's sdl backend stays full screen.
- gamescope/release.env: the non-Adreno build stays pinned until the next one is published.
- FrontEndActivity/FrontEndScreen/SessionActivity/SessionFiles/SessionPrefs/LinuxRuntime/strings: both sides kept.
- test_gamescope_backend: the desktop backend test turns window mode off.
This commit is contained in:
The412Banner committed 2026-10-27 12:25:25 +00:00
commit 941cde30f2
394 files changed
+28009 -3092

No files matched your search

+3
View File
@@ -12,6 +12,9 @@ export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
export MOZ_SHM_NO_SEALS=1
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
[ -e /etc/mpv/mpv.conf ] || { mkdir -p /etc/mpv && echo gpu-sw=yes >/etc/mpv/mpv.conf; } 2>/dev/null
for conf in client client-rt; do
mkdir -p "/etc/pipewire/$conf.conf.d" && printf 'context.properties = {\n module.rt = false\n}\n' >"/etc/pipewire/$conf.conf.d/droiddeck-rt.conf"
done 2>/dev/null
export DROIDDECK_NESTED_SCALE=1
export DROIDDECK_GLTHREAD=${mesa_glthread:-}
unset MESA_LOADER_DRIVER_OVERRIDE LIBGL_KOPPER_DRI2 mesa_glthread
+25 -4
View File
@@ -11,22 +11,43 @@ case "$backend" in
wayland|sdl) ;;
*) echo "== unsupported gamescope backend: $backend" >&2; exit 64 ;;
esac
args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height")
window=0
if [ "$backend" = wayland ] && [ "${BL_DESKTOP_GPU_WINDOW:-1}" != 0 ] && [ -n "${WAYLAND_DISPLAY:-}" ] && [ "$WAYLAND_DISPLAY" != wayland-0 ]; then
window=1
parent=$WAYLAND_DISPLAY
args=(--backend sdl --expose-wayland -W "$width" -H "$height" -w "$width" -h "$height")
else
args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height")
fi
if [ "${BL_FPS:-0}" -gt 0 ]; then
args+=(-r "$BL_FPS")
elif [ "${BL_REFRESH:-0}" -gt 0 ]; then
args+=(-r "$BL_REFRESH")
fi
[ "${BL_HDR:-0}" = 1 ] && args+=(--hdr-enabled)
echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (gamescope ${width}x${height} on wayland-0)"
export WAYLAND_DISPLAY=wayland-0
if [ "$window" = 1 ]; then
echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (gamescope ${width}x${height} in a window on $parent)"
else
echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (gamescope ${width}x${height} on wayland-0)"
export WAYLAND_DISPLAY=wayland-0
fi
export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11
[ "$backend" = sdl ] && export SDL_VIDEODRIVER=wayland
unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND KWIN_COMPOSE
wsi=",${MESA_VK_WSI_DEBUG:-},"
while [[ $wsi == *,sw,* ]]; do wsi=${wsi//,sw,/,}; done
wsi=${wsi#,}; wsi=${wsi%,}
if [ -n "$wsi" ]; then export MESA_VK_WSI_DEBUG=$wsi; else unset MESA_VK_WSI_DEBUG; fi
export BL_DESKTOP_GPU_CHILD=1
export MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=true
[ -n "${DROIDDECK_GLTHREAD:-}" ] && export mesa_glthread=$DROIDDECK_GLTHREAD
export APPIMAGE_EXTRACT_AND_RUN=1
gamescope "${args[@]}" -- env SDL_VIDEODRIVER=x11 /usr/local/bin/droiddeck-gpu-window "$@"
if [ "$window" = 1 ]; then
export BL_GPU_CHILD_WSI=${MESA_VK_WSI_DEBUG:-}
SDL_VIDEODRIVER=wayland MESA_VK_WSI_DEBUG=sw gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@"
else
gamescope "${args[@]}" -- env SDL_VIDEODRIVER=x11 /usr/local/bin/droiddeck-gpu-window "$@"
fi
rc=$?
echo "== droiddeck-gpu $(date -u +%H:%M:%S): exited $rc"
exit $rc
@@ -0,0 +1,7 @@
#!/bin/sh
# Runs DroidDeck's bundled innoextract with its own boost libraries. The guest's
# env -i startup has no LD_LIBRARY_PATH, and the rootfs must not grow a second
# copy of boost for the installer fallback.
LD_LIBRARY_PATH=/usr/local/lib/droiddeck-inno
export LD_LIBRARY_PATH
exec /usr/local/lib/droiddeck-inno/innoextract "$@"
@@ -0,0 +1,23 @@
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,18 @@
Copyright (C) 2011-2020 Daniel Scharrer <daniel@constexpr.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the author(s) be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
File diff suppressed because it is too large. Load diff
@@ -11,6 +11,7 @@ import shutil
import struct
import subprocess
import sys
import time
HOME = os.environ.get("HOME") or "/root"
STEAM_ROOT = os.path.join(HOME, ".local", "share", "Steam")
@@ -27,6 +28,8 @@ PRELOADS = "/usr/local/lib/droiddeck-fex"
URUNTIME = "/usr/local/lib/droiddeck/uruntime"
HOST_PRELOAD = "/etc/ld.so.preload"
FEX_APPID = "3127680"
OWN_FEX = "/usr/local"
OWN_FEX_TAG = os.path.join(OWN_FEX, "share", "fex-emu", ".droiddeck-tag")
SNIPER_APPID = "1628350"
SLR4_APPID = "4183110"
INSTALL_DIRS = {FEX_APPID: "FEX-Emu", SNIPER_APPID: "SteamLinuxRuntime_sniper", SLR4_APPID: "SteamLinuxRuntime_4"}
@@ -152,8 +155,52 @@ def first_dir(prefix, candidates):
return None
def own_fex_loads():
for name in ("FEX", "FEXServer"):
binary = os.path.join(OWN_FEX, "bin", name)
if not os.access(binary, os.X_OK):
return False
try:
listed = subprocess.run(["/usr/lib/ld-linux-aarch64.so.1", "--list", binary],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=20)
except (OSError, subprocess.TimeoutExpired):
return False
if listed.returncode != 0 or b"not found" in listed.stdout:
return False
return True
def update_own_fex():
wanted = os.environ.get("BL_FEX_TAG")
if not wanted:
return
if (read_text(OWN_FEX_TAG) or "").strip() == wanted and own_fex_loads():
return
failed = os.path.join(STATE, "update-failed")
try:
if (read_text(failed) or "").strip() == wanted and time.time() - os.path.getmtime(failed) < 3600:
return
except OSError:
pass
say("installing DroidDeck's FEX build %s" % wanted)
try:
code = subprocess.call([os.path.join(BIN_DIR, "droiddeck-fex-update")], stdout=sys.stderr)
except OSError:
code = 1
if code == 0:
with contextlib.suppress(OSError):
os.remove(failed)
return
with contextlib.suppress(OSError):
with open(failed, "w", encoding="utf-8") as handle:
handle.write(wanted + "\n")
say("DroidDeck's FEX build %s did not install; using the FEX already here" % wanted)
def fex_install():
prefixes = []
if os.path.isfile(OWN_FEX_TAG) and own_fex_loads():
prefixes.append((OWN_FEX, False))
tool = app_dir(FEX_APPID)
if tool:
prefixes += [(os.path.join(tool, sub), True) for sub in ("usr", "", "files/usr", "files")]
@@ -445,6 +492,7 @@ def describe(fex, platform, graphics=None):
def prepare(app=SNIPER_APPID):
with locked():
update_own_fex()
fex = fex_install()
platform = runtime_platform(app)
status = describe(fex, platform)
@@ -730,6 +778,7 @@ def extracted():
def want_fex():
with locked():
update_own_fex()
status = describe(fex_install(), runtime_platform(), graphics_platform())
if not status["ready"]:
request_install()
+81
View File
@@ -0,0 +1,81 @@
#!/bin/bash
FEX_TAG=fex-2610-r5
FEX_SHA256=0fc1ca2ba13817ad70d1ea157119a75c9c02446b57d166e6d676cce0807c19c4
FEX_URL=https://github.com/Droid-Deck/DroidDeck-Components/releases/download/$FEX_TAG/fex.tzst
# Whether every program in the FEX tree at $1 finds its libraries (r4 did not without libxxhash).
fex_loads() {
local b out
for b in FEX FEXServer unsquashfs; do
out=$(/usr/lib/ld-linux-aarch64.so.1 --list "$1/usr/local/bin/$b" 2>&1) && ! grep -q "not found" <<<"$out" && continue
echo "== FEX check: $b: $(grep -E "not found|error" <<<"$out" | tr -s '\t ' ' ' | tr '\n' ';')" >&2
return 1
done
}
# Installs one FEX build only once its archive matches the sha256 and it loads. The files it replaces are kept
# until the installed copy loads too, and put back otherwise; the tag is written last.
fex_install() {
local tag=$1 sha=$2 urls=$3 dst=/ tmp u f
tmp=$(mktemp -d)
for u in $urls; do
curl -fsSL --retry 2 --connect-timeout 20 --speed-limit 1024 --speed-time 60 "$u" -o "$tmp/fex.tzst" && echo "$sha $tmp/fex.tzst" | sha256sum -c --quiet >/dev/null 2>&1 && break
rm -f "$tmp/fex.tzst"
done
if [ ! -s "$tmp/fex.tzst" ]; then
echo "== FEX $tag: no source gave the archive with sha256 ${sha:0:12}" >&2
rm -rf "$tmp"
return 1
fi
if ! { mkdir "$tmp/root" && zstd -dc "$tmp/fex.tzst" | tar -C "$tmp/root" -x && fex_loads "$tmp/root"; }; then
rm -rf "$tmp"
return 1
fi
(cd "$tmp/root" && find . ! -type d) > "$tmp/files"
mkdir "$tmp/old"
while IFS= read -r f; do
f=${f#./}
if [ -e "$dst$f" ] || [ -L "$dst$f" ]; then
cp -a --parents "$dst$f" "$tmp/old" || { echo "== FEX $tag: could not keep $dst$f aside" >&2; rm -rf "$tmp"; return 1; }
fi
done < "$tmp/files"
if tar -C "$tmp/root" -c . | tar -C "$dst" -x && fex_loads "$dst" &&
mkdir -p "${dst}usr/local/share/fex-emu" && echo "$tag" > "${dst}usr/local/share/fex-emu/.droiddeck-tag"; then
rm -rf "$tmp"
return 0
fi
echo "== FEX $tag: the installed copy did not load or its tag was not written; putting the previous files back" >&2
while IFS= read -r f; do
f=${f#./}
[ -e "$tmp/old/$dst$f" ] || [ -L "$tmp/old/$dst$f" ] || rm -f "$dst$f"
done < "$tmp/files"
tar -C "$tmp/old$dst" -c . | tar -C "$dst" -x || echo "== FEX $tag: could not put the previous files back" >&2
rm -rf "$tmp"
return 1
}
# The build DroidDeck-Components' fex.json names (the app passes it as BL_FEX_*) comes first, then a working
# installed one, then FEX_TAG above. Sets FEX_NOW and FEX_FROM.
fex_ready() {
local have ok=
have=$(cat /usr/local/share/fex-emu/.droiddeck-tag 2>/dev/null || true)
[ -x /usr/local/bin/FEX ] && fex_loads / && ok=1
if [ -n "${BL_FEX_TAG:-}" ]; then
if [ -n "$ok" ] && [ "$have" = "$BL_FEX_TAG" ]; then FEX_NOW=$have FEX_FROM=catalog; return 0; fi
step "downloading FEX ($BL_FEX_TAG)"
if fex_install "$BL_FEX_TAG" "${BL_FEX_SHA256:-}" "${BL_FEX_URLS:-}"; then FEX_NOW=$BL_FEX_TAG FEX_FROM=catalog; return 0; fi
if [ -n "$ok" ]; then FEX_NOW=$have FEX_FROM="kept; $BL_FEX_TAG did not install"; return 0; fi
fi
if [ -n "$ok" ] && [ "$have" = "$FEX_TAG" ]; then FEX_NOW=$have FEX_FROM=built-in; return 0; fi
step "downloading FEX ($FEX_TAG)"
if fex_install "$FEX_TAG" "$FEX_SHA256" "$FEX_URL"; then FEX_NOW=$FEX_TAG FEX_FROM=built-in; return 0; fi
if [ -n "$ok" ]; then FEX_NOW=$have FEX_FROM="kept; $FEX_TAG did not install"; return 0; fi
return 1
}
if [ "${BASH_SOURCE[0]}" = "$0" ]; then
set -eu
step() { echo "== STEP $*" >&2; }
fex_ready || exit 1
echo "$FEX_NOW ($FEX_FROM)"
fi
@@ -3,6 +3,7 @@ set -u
export LANG=C.UTF-8
step() { echo "== STEP $*"; }
fail() { echo "== FAIL $*"; exit 1; }
[ "$(id -u)" = 0 ] || fail "needs root: install Flatpak from the launcher's Store, which runs this as root"
PACKAGES="flatpak ostree appstream libxmlb libmalcontent libfyaml accountsservice composefs xdg-dbus-proxy"
while read -r pkg probe; do
@@ -24,6 +25,7 @@ NEEDS
WORK=/var/cache/droiddeck-flatpak
CONF=$WORK/pacman.conf
mkdir -p "$WORK/pkg" "$WORK/db" || fail "cannot create $WORK"
exec 9>"$WORK/setup.lock" && flock -n 9 || fail "another Flatpak setup is still running"
OVERSEAS="https://ca.us.mirror.archlinuxarm.org https://fl.us.mirror.archlinuxarm.org https://de3.mirror.archlinuxarm.org https://nl.mirror.archlinuxarm.org"
MAINLAND=""
@@ -48,10 +50,14 @@ if [ ! -f /etc/pacman.d/gnupg/pubring.gpg ] && [ ! -f /etc/pacman.d/gnupg/pubrin
fi
step "Reading the package lists"
pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy >/dev/null 2>&1 \
|| pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy 2>&1 | tail -3 \
|| fail "could not reach the Arch Linux ARM mirrors"
[ -f "$WORK/db/sync/extra.db" ] || fail "could not reach the Arch Linux ARM mirrors"
rm -f "$WORK/db/db.lck"
sync_log=$(pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy 2>&1) \
|| sync_log=$(pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy 2>&1)
if [ ! -f "$WORK/db/sync/extra.db" ]; then
printf '%s\n' "$sync_log" | tail -3
reason=$(printf '%s\n' "$sync_log" | grep -m1 -i '^error' | cut -c1-160)
fail "could not reach the Arch Linux ARM mirrors${reason:+ ($reason)}"
fi
step "Downloading Flatpak"
out=$(pacman --config "$CONF" --dbpath "$WORK/db" --cachedir "$WORK/pkg" --noconfirm -Sw -dd $PACKAGES 2>&1)
@@ -103,10 +103,19 @@ def godot_vulkan(game):
@fix
def godot_sentry(game):
sentry = sorted(n[:-4] for n in game.files if n.startswith("libsentry.windows.") and n.endswith(".dll"))
if is_godot(game) and sentry:
if is_godot(game) and sentry and ("coreclr.dll" in game.files or "godotsharp.dll" in game.files):
return {"WINEDLLOVERRIDES": ";".join(n + "=d" for n in sentry)}, [], "Godot: Sentry crash handler off"
@fix
def d3dgear_hook(game):
"""D3DGear's capture DLL left beside a game (The Crew 2) is loaded by it and hooks the DXGI swapchain;
under Wine the hook faults over a thousand times within seconds and the game never presents again:
black screen while the sound keeps playing."""
if "d3dgear64.dll" in game.files:
return {"WINEDLLOVERRIDES": "d3dgear64=d"}, [], "D3DGear capture hook off (it stops the game drawing)"
@fix
def deep_rock_gdk_raytracing(game):
if game.stem == "fsd-wingdk-shipping" and not any(game.has_arg(arg) for arg in ("-raytracing", "-noraytracing")):
@@ -122,12 +131,32 @@ def arkham_city_x87(game):
@fix
def protonfixes_off(game):
if game.stem in ("blackops3", "darksoulsremastered"):
return {"PROTONFIXES_DISABLE": "1"}, [], "umu-protonfixes off (its ALSA audio and VC++ installer steps fail here)"
@fix
def caravan_sandwitch_feature_level(game):
if "caravansandwitch.exe" in game.files or game.stem == "caravansandwitch-win64-shipping":
return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "Caravan SandWitch: D3D12 feature level 12_1 (12_2 hands it mesh shader pipelines vkd3d-proton cannot build)"
@fix
def robocop_rogue_city_feature_level(game):
"""vkd3d-proton turns mesh shaders off on Adreno, but 12_2 still advertises them, and UE5 then builds mesh
pipelines with no pipeline layout that crash Turnip on launch."""
if "robocop.exe" in game.files or game.stem == "robocop-win64-shipping":
return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "RoboCop: Rogue City: D3D12 feature level 12_1"
@fix
def reskate_feature_level(game):
if "skate.exe" in game.files and "reskate.dll" in game.files:
return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "ReSkate (skate.): D3D12 feature level 12_1"
@fix
def cyberpunk_feature_level(game):
if game.stem == "cyberpunk2077" or (
@@ -240,7 +269,10 @@ def engine_fixes(exe, args):
for check in FIXES:
found = check(game)
if found:
env.update(found[0])
for name, value in found[0].items():
if name == "WINEDLLOVERRIDES" and env.get(name):
value = env[name] + ";" + value
env[name] = value
extra += found[1]
notes.append(found[2])
return env, extra, notes
@@ -273,6 +305,78 @@ def game_gpu(env):
return result
def vram_cap(env):
"""Puts the session's VRAM cap ahead of the game's own DXVK settings, so a game profile can still raise it."""
value = env.get("BL_VRAM_MB", "")
if not re.fullmatch(r"[1-9][0-9]{0,6}", value):
return env
result = env.copy()
cap = "dxgi.maxDeviceMemory = %d" % int(value)
own = result.get("DXVK_CONFIG", "").strip().strip(";").strip()
result["DXVK_CONFIG"] = cap + "; " + own if own else cap
return result
def parse_cores(text):
"""CPU numbers from a list such as "0-3,6"; None when the text is not one."""
cores = set()
for part in text.replace(" ", "").split(","):
match = re.fullmatch(r"(\d{1,3})(?:-(\d{1,3}))?", part)
if not match:
return None
first, last = int(match.group(1)), int(match.group(2) or match.group(1))
if last < first:
return None
cores.update(range(first, last + 1))
return cores or None
def online_cores():
try:
with open("/sys/devices/system/cpu/online") as f:
cores = parse_cores(f.read().strip())
except OSError:
cores = None
return cores or os.sched_getaffinity(0) | set(range(os.cpu_count() or 0))
def game_cores(env):
"""Pins the game to the cores its profile names, in place of the session's game cores."""
text = env.get("DROIDDECK_GAME_CORES", "").strip()
if not text:
return
cores = parse_cores(text)
chosen = cores & online_cores() if cores else None
if not chosen:
print("droiddeck-game-env: ignoring game cores %r" % text, file=sys.stderr)
return
try:
os.sched_setaffinity(0, chosen)
print("droiddeck-game-env: game cores %s" % ",".join(map(str, sorted(chosen))), file=sys.stderr)
except OSError as error:
print("droiddeck-game-env: could not use game cores %r (%s)" % (text, error), file=sys.stderr)
def cpu_topology(env):
if "PROTON_CPU_TOPOLOGY" in env:
return
if "WINE_CPU_TOPOLOGY" in env:
if env["WINE_CPU_TOPOLOGY"]:
env["PROTON_CPU_TOPOLOGY"] = env["WINE_CPU_TOPOLOGY"]
return
if not (env.get("DROIDDECK_GAME_CORES", "").strip() or env.get("BL_GAME_CPUS", "").strip()):
return
try:
cores = sorted(os.sched_getaffinity(0))
except OSError:
return
online = online_cores()
if not cores or set(cores) >= online or cores[-1] >= len(online):
return
env["WINE_CPU_TOPOLOGY"] = env["PROTON_CPU_TOPOLOGY"] = "%d:%s" % (len(cores), ",".join(map(str, cores)))
print("droiddeck-game-env: Windows sees %d cores (%s)" % (len(cores), env["WINE_CPU_TOPOLOGY"]), file=sys.stderr)
def apply_config(env, config, app_id, fixes=None):
if config.get("version") != 1:
raise ValueError("unsupported environment configuration")
@@ -660,7 +764,10 @@ def main():
env = game_logs(command, env, app_id)
if mic_enabled == "0":
env["BANNER_AUDIO_DIRECT_MIC"] = "0"
env = vram_cap(env)
env = force_ssbs(command, env)
game_cores(env)
cpu_topology(env)
try:
xbox = runpy.run_path(str(Path(__file__).with_name("droiddeck-xbox")))
except Exception as error:
@@ -45,6 +45,13 @@ def advertise_compositing():
if __name__ == '__main__':
if len(sys.argv) < 2:
raise SystemExit('usage: droiddeck-gpu-window <program> [args...]')
if 'BL_GPU_CHILD_WSI' in os.environ:
wsi = os.environ.pop('BL_GPU_CHILD_WSI')
if wsi:
os.environ['MESA_VK_WSI_DEBUG'] = wsi
else:
os.environ.pop('MESA_VK_WSI_DEBUG', None)
os.environ['SDL_VIDEODRIVER'] = 'x11'
os.environ.setdefault('GTK_CSD', '1')
try:
connection = advertise_compositing()
@@ -9,9 +9,9 @@ Add an app does) when that holds native programs or libraries. A Steam library's
droiddeck-open --exec FILE [ARGS...] an exec the kernel refused (libblsession)
droiddeck-open --install the Run entries and default handlers
The desktop composites in software, so a program started from it goes full screen on the GPU
(droiddeck-gpu), as the menu's games do: --window keeps it in a desktop window instead, --terminal
runs it in Konsole. A plain script stays on the desktop, and an exec whose output is read (a terminal,
The desktop composites in software, so a program started from it runs on the GPU in a window of its
own (droiddeck-gpu), as the menu's games do: --window keeps it on the desktop's software drawing
instead, --terminal runs it in Konsole. A plain script stays on the desktop, and an exec whose output is read (a terminal,
a pipe, a file) stays where it was started.
"""
import fcntl
@@ -337,7 +337,7 @@ def unattended(env):
def placed(cmd, what, mode, env):
"""[cmd] where it shows: full screen on the GPU from the desktop, else where it was started."""
"""[cmd] where it shows: on the GPU from the desktop, else where it was started."""
if mode == "terminal" and what not in ("windows", "steam") and shutil.which("konsole"):
return ["konsole", "--hold", "-e"] + cmd
if mode == "window" or what in ("script", "steam") or not on_desktop(env):
@@ -1,7 +1,7 @@
#!/usr/bin/python3
"""Runs a Windows program with the Proton the Steam client has chosen for it.
droiddeck-proton-run [--window] PROGRAM [ARGS...]
droiddeck-proton-run [--window] [--prefix ID] [--verb run] [--game-id ID] [--desktop WxH] PROGRAM [ARGS...]
droiddeck-proton-run --app ID [--dir FOLDER] [--options TEXT] [PROGRAM [ARGS...]]
The program belongs to an installed Steam game when it sits in one's folder, to a prefix when it
@@ -10,10 +10,15 @@ its own, under the id the client gives a new shortcut. That title's CompatToolMa
config.vdf picks the tool, else the client's default for all other titles ("0"). The tool is
started as the client starts it - its toolmanifest's command line, the waitforexitandrun verb and
the STEAM_COMPAT_* environment - so its wrapper applies the game's settings, components and audio.
--window keeps the program in the desktop's own window, drawn with WineD3D.
--window keeps the program in the desktop's own window, drawn with WineD3D on the desktop's software
GL (llvmpipe): KWin there composites in software, and the session's zink finds no device.
--prefix ID puts the program in compatdata/ID whatever it is. --verb run starts it beside what already
runs in the prefix, which waitforexitandrun would wait for; the wrapper's launch-time steps are skipped.
--game-id ID keeps the id of the launch it runs for: gamescope shows the windows that carry the id Steam launched.
--app starts one game without the Steam client (its Start without Steam): a Steam game's default
Windows launch option from appinfo.vdf when no program is given, else the program in that
shortcut's own prefix, started in --dir with the shortcut's launch options (--options).
shortcut's own prefix, started in --dir with the shortcut's launch options (--options). Without
--options it takes the launch options set in the client's Properties for that game or shortcut.
"""
import json
import os
@@ -30,7 +35,10 @@ BIN_DIR = os.path.dirname(os.path.abspath(__file__))
STATE = os.path.join(HOME, ".local", "share", "droiddeck-compat", "state.json")
EXTRA_LIBRARIES = ("/mnt/droiddeck", "/mnt/droiddeck-sd")
SYSTEM_TOOLS = ("/usr/share/steam/compatibilitytools.d", "/usr/local/share/steam/compatibilitytools.d")
DESKTOP_GL = {"LIBGL_ALWAYS_SOFTWARE": "1", "GALLIUM_DRIVER": "llvmpipe"}
NOT_DESKTOP_GL = ("MESA_LOADER_DRIVER_OVERRIDE", "LIBGL_KOPPER_DRI2")
VERB = "waitforexitandrun"
VERBS = (VERB, "run")
SHORTCUT_BIT = 0x80000000
STEAM_APP_LIMIT = 2 ** 31
@@ -185,9 +193,9 @@ def steam_game(program, libs):
def prefix_of(program):
for folder, below in ancestors(program):
parent = os.path.dirname(folder)
if below == "pfx" and os.path.basename(parent) == "compatdata" and os.path.basename(folder).isdigit():
if below == "pfx" and os.path.basename(parent) == "compatdata" and re.fullmatch(r"-?[0-9]+", os.path.basename(folder)):
library = os.path.dirname(os.path.dirname(parent))
return Target(os.path.basename(folder), folder, os.path.dirname(program), library, "prefix")
return Target(str(int(os.path.basename(folder)) % 2 ** 32), folder, os.path.dirname(program), library, "prefix")
return None
@@ -230,10 +238,68 @@ def shortcut_entries(root):
return entries
def prefix_folder(root, appid):
"""The prefix folder the client made for [appid], under either spelling of the id."""
folder = os.path.join(root, "steamapps", "compatdata")
try:
names = sorted(os.listdir(folder))
except OSError:
names = []
candidates = []
for name in names:
if not re.fullmatch(r"-?[0-9]+", name):
continue
try:
matches = int(name) % 2 ** 32 == appid % 2 ** 32
except ValueError:
continue
match = os.path.join(folder, name)
if matches and os.path.isdir(match):
candidates.append((os.path.isdir(os.path.join(match, "pfx")),
name == str(appid % 2 ** 32), name, match))
if candidates:
return min(candidates, key=lambda item: (not item[0], not item[1], item[2]))[3]
return os.path.join(folder, str(appid % 2 ** 32))
def vdf_string(token):
return re.sub(r'\\(.)', r'\1', token[1:-1]) if token.startswith('"') else ""
def steam_options(app, root):
"""The launch options the client keeps for a game (localconfig.vdf) or a shortcut (shortcuts.vdf)."""
try:
tool = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-steam-shortcuts"))
account = tool["account_dir"](root)
if not account:
return ""
if int(app) >= STEAM_APP_LIMIT:
with open(os.path.join(account, "config", "shortcuts.vdf"), "rb") as f:
shortcuts = tool["parse"](f.read()).get("shortcuts", {})
for value in shortcuts.values():
if isinstance(value, dict) and (value.get("appid", value.get("AppId")) or 0) & 0xFFFFFFFF == int(app):
options = value.get("LaunchOptions", value.get("launchoptions", ""))
return options if isinstance(options, str) else ""
return ""
tokens = compat()["tokenize"](read_text(os.path.join(account, "config", "localconfig.vdf")) or "")
start = compat()["find_block"](tokens, ["UserLocalConfigStore", "Software", "Valve", "Steam", "apps", app])
if start is None:
return ""
end, depth = compat()["block_end"](tokens, start), 0
for i in range(start + 1, end):
if tokens[i] in ("{", "}"):
depth += 1 if tokens[i] == "{" else -1
elif depth == 0 and tokens[i].lower() == '"launchoptions"' and i + 1 < end:
return vdf_string(tokens[i + 1])
except (OSError, ValueError, IndexError, KeyError, TypeError, AttributeError, struct.error):
pass
return ""
def shortcut(program, root):
for appid, exe, start in shortcut_entries(root):
if same_file(program, exe):
return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)),
return Target(appid, prefix_folder(root, appid),
os.path.dirname(program), root, "shortcut", start if os.path.isdir(start) else None)
return None
@@ -250,10 +316,19 @@ def locate(program, root):
if found:
return found
appid = own_id(program)
return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)),
return Target(appid, prefix_folder(root, appid),
os.path.dirname(program), root, "own")
def fixed(program, root, appid):
return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)),
os.path.dirname(program), root, "fixed")
def prefix_id(value):
return value if value.isdigit() and not value.startswith("0") and int(value) <= 0xFFFFFFFF else None
def split_words(text):
try:
return shlex.split(text or "")
@@ -325,7 +400,8 @@ def steam_launch(appid, root):
def shortcut_target(appid, program, start, root):
return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)), os.path.dirname(program), root,
appid = int(appid) % 2 ** 32
return Target(str(appid), prefix_folder(root, appid), os.path.dirname(program), root,
"shortcut", start if start and os.path.isdir(start) else None)
@@ -337,7 +413,7 @@ def steam_launches(target, program, root):
return os.path.relpath(program, target.install).replace(os.sep, "/").lower() in entry.get("launch", ())
def environment(env, target, tool_folder, root, window=False):
def environment(env, target, tool_folder, root, window=False, game_id=None):
env = dict(env)
steamapps = [os.path.join(lib, "steamapps") for lib in libraries(root)]
env.update({
@@ -355,28 +431,52 @@ def environment(env, target, tool_folder, root, window=False):
else:
game = str(number << 32 | 0x02000000)
env.update(SteamAppId="0", STEAM_COMPAT_APP_ID="0", SteamGameId=game, SteamOverlayGameId=game)
if game_id:
env.update(SteamGameId=game_id, SteamOverlayGameId=game_id)
if window:
env.setdefault("PROTON_USE_WINED3D", "1")
env.update(DESKTOP_GL)
for name in NOT_DESKTOP_GL:
env.pop(name, None)
return env
def windows_path(path):
def windows_path(path, compatdata=None):
if compatdata:
drive = os.path.join(compatdata, "pfx", "drive_c")
inside = os.path.relpath(path, drive)
if inside != "." and not inside.startswith(".."):
return "C:\\" + inside.replace("/", "\\")
return "Z:" + path.replace("/", "\\")
def arguments(program, args):
def arguments(program, args, desktop=None, compatdata=None):
if program.lower().endswith(".msi"):
return ["msiexec", "/i", windows_path(program)] + args
if desktop:
return ["explorer.exe", "/desktop=droiddeck,%s" % desktop, windows_path(program, compatdata)] + args
return [program] + args
def main(argv):
window = False
app, start, options = None, None, ""
prefix = None
verb = VERB
game_id = None
desktop = None
app, start, options = None, None, None
while argv and argv[0].startswith("--"):
option = argv.pop(0)
if option == "--window":
window = True
elif option == "--prefix" and argv and prefix_id(argv[0]):
prefix = argv.pop(0)
elif option == "--verb" and argv and argv[0] in VERBS:
verb = argv.pop(0)
elif option == "--game-id" and argv and argv[0].isdigit() and argv[0] != "0":
game_id = argv.pop(0)
elif option == "--desktop" and argv and re.fullmatch(r"[1-9][0-9]{2,4}x[1-9][0-9]{2,4}", argv[0]):
desktop = argv.pop(0)
elif option in ("--app", "--dir", "--options") and argv:
value = argv.pop(0)
if option == "--app":
@@ -394,9 +494,11 @@ def main(argv):
say("%s is not an app id" % app)
return 2
if not argv and app is None:
say("usage: droiddeck-proton-run [--window] PROGRAM [ARGS...]")
say("usage: droiddeck-proton-run [--window] [--prefix ID] [--verb run] [--game-id ID] [--desktop WxH] PROGRAM [ARGS...]")
return 2
root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or STEAM_ROOT
if options is None:
options = steam_options(app, root) if app is not None else ""
extra, args = split_options(options)
if not argv:
if int(app) >= STEAM_APP_LIMIT:
@@ -416,6 +518,8 @@ def main(argv):
args = args + argv[1:]
if app is not None and int(app) >= STEAM_APP_LIMIT:
target = shortcut_target(app, program, start, root)
elif prefix:
target = fixed(program, root, prefix)
else:
target = locate(program, root)
available = tools(root)
@@ -425,7 +529,7 @@ def main(argv):
return 69
folder, command = available[name]
os.makedirs(target.compatdata, exist_ok=True)
env = environment(os.environ, target, folder, root, window)
env = environment(os.environ, target, folder, root, window, game_id)
env.update(extra)
say("%s with %s (%s), %s prefix %s%s" % (program, name, why, target.kind, target.compatdata,
", without the Steam client" if app is not None else ""))
@@ -434,7 +538,7 @@ def main(argv):
except OSError:
os.chdir(os.path.dirname(program))
entry = os.path.join(folder, command)
os.execve(entry, [entry, VERB] + arguments(program, args), env)
os.execve(entry, [entry, verb] + arguments(program, args, desktop, target.compatdata), env)
if __name__ == "__main__":
@@ -26,7 +26,7 @@ if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then
fi
exec > >({ dd of="$BL_LOG" oflag=append conv=notrunc iflag=count_bytes count="${BL_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
echo "== droiddeck-session $(date) mode=$mode $*"
echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} fps=${BL_FPS:-0} icd=${VK_ICD_FILENAMES:-none}"
echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}"
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)"
fi
@@ -390,13 +390,19 @@ if [ -z "${BL_INSIDE:-}" ]; then
width=${BL_WIDTH:-1280}
height=${BL_HEIGHT:-720}
nested=$width
nested_h=$height
if [ "${BL_FOLLOW_OUTPUT:-0}" = 1 ]; then
echo "== gamescope: the output follows the screen (${width}x${height} to start)"
elif [ "$mode" = steam ] && [ "${BL_GAMESCOPE_STRETCH_16X9:-0}" = 1 ]; then
wide=$(( (height * 16 + 4) / 9 / 2 * 2 ))
tall=$(( (width * 9 + 8) / 16 / 2 * 2 ))
if [ "$wide" -gt "$width" ]; then
nested=$wide
echo "== gamescope: games at ${nested}x${height} stretched to the ${width}x${height} output"
elif [ "$tall" -gt "$height" ]; then
nested_h=$tall
fi
if [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; then
echo "== gamescope: games at ${nested}x${nested_h} stretched to the ${width}x${height} output"
fi
fi
backend=${BL_GAMESCOPE_BACKEND:-wayland}
@@ -410,12 +416,15 @@ if [ -z "${BL_INSIDE:-}" ]; then
if [ "$mode" = steam ] && [ "${BL_CURSOR_COMPOSITE:-0}" = 1 ]; then
export gamescope_cursor_composite=2
fi
args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$height")
[ "$nested" != "$width" ] && args+=(-S stretch) && export BL_STRETCHED=1
if [ "${BL_FPS:-0}" -gt 0 ]; then
args+=(-r "$BL_FPS")
elif [ "${BL_REFRESH:-0}" -gt 0 ]; then
args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h")
if [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; then
args+=(-S stretch)
export BL_STRETCHED=1
fi
if [ "${BL_REFRESH:-0}" -gt 0 ]; then
args+=(-r "$BL_REFRESH")
# -r is the starting rate; gamescope follows the panel when it switches modes later.
export GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST=1
fi
[ "$mode" = steam ] && [ "${BL_STEAM_UI:-}" != desktop ] && args+=(-e)
if [ "$mode" = steam ] && [ "${BL_XWAYLAND_COUNT:-2}" -gt 1 ]; then
@@ -434,6 +443,10 @@ if [ -z "${BL_INSIDE:-}" ]; then
echo "== gamescope: mangoapp on ($(command -v mangoapp), config $MANGOHUD_CONFIGFILE)"
fi
export BL_INSIDE=1
# A fixed path: left to itself gamescope creates a new limiter state file on every start.
rm -f "${XDG_RUNTIME_DIR:-/tmp}"/gamescope-limiter-*
export GAMESCOPE_LIMITER_FILE="${XDG_RUNTIME_DIR:-/tmp}/droiddeck-gamescope-limiter"
rm -f "$GAMESCOPE_LIMITER_FILE"
if [ "$mode" = steam ]; then
if /usr/local/bin/droiddeck-pipewire start; then
eval "$(/usr/local/bin/droiddeck-pipewire env)"
@@ -631,49 +644,172 @@ case $mode in
fi
if [ "${BL_ZRAM:-0}" = 1 ]; then
step "zRAM compression: on"
[ "${BL_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam is not compressed while games run (turned off in Performance)"
_bl_ram_cap=0
case ${BL_RAM_CAP_MB:-} in
''|0) ;;
*[!0-9]*|0*|???????*) step "RAM cap: ignored invalid value '$BL_RAM_CAP_MB'" ;;
*) _bl_ram_cap=$((BL_RAM_CAP_MB * 1024)); step "RAM cap: ${BL_RAM_CAP_MB} MB" ;;
esac
(
bl_zram_scan() {
_bl_game=0 _bl_pids=()
_bl_game=0 _bl_pids=() _bl_others=() _bl_apps=
local _d _c _args _name _a _id
for _d in /proc/[0-9]*; do
# Under FEX the program is FEX's first argument.
{ IFS= read -r -d '' _c && case ${_c##*/} in FEX|FEXInterpreter) IFS= read -r -d '' _c ;; esac; } \
2>/dev/null < "$_d/cmdline" || continue
case ${_c##*/} in
reaper) _bl_game=1 ;;
steam|steamwebhelper) _bl_pids+=("${_d#/proc/}") ;;
[ "${_d##*/}" != "$BASHPID" ] || continue
_args=()
# Under FEX the program is FEX's first argument. AppId= is its own argument.
while IFS= read -r -d '' _c; do _args+=("$_c"); done 2>/dev/null < "$_d/cmdline" || true
[ "${#_args[@]}" -gt 0 ] || continue
_name=${_args[0]}
if [ "${#_args[@]}" -gt 1 ]; then
case ${_name##*/} in FEX|FEXInterpreter) _name=${_args[1]} ;; esac
fi
case ${_name##*/} in
reaper)
for _a in "${_args[@]}"; do
case $_a in
AppId=769) ;;
AppId=[0-9]*)
_id=${_a#AppId=}
case $_id in *[!0-9]*) ;; *) _bl_game=1; _bl_apps="$_bl_apps $_id" ;; esac
;;
esac
done
;;
steam|steamwebhelper) _bl_pids+=("${_d##*/}") ;;
*) _bl_others+=("${_d##*/}") ;;
esac
done
}
bl_zram_usage() {
local _p _k _v _u _rss=0 _swap=0
for _p in "${_bl_pids[@]}"; do
for _p in "$@"; do
while read -r _k _v _u; do
case $_k in VmRSS:) _rss=$((_rss + _v)) ;; VmSwap:) _swap=$((_swap + _v)) ;; esac
done 2>/dev/null < "/proc/$_p/status"
done
echo "${#_bl_pids[@]} processes, resident $((_rss / 1024)) MB, in zram $((_swap / 1024)) MB"
_bl_rss=$_rss
echo "$# processes, resident $((_rss / 1024)) MB, in zram $((_swap / 1024)) MB"
}
# Only processes that loaded libblsession are the session's own and answer SIGURG.
bl_session_others() {
local _p
_bl_session=()
for _p in "${_bl_others[@]}"; do
grep -q -m1 '/libblsession\.so$' "/proc/$_p/maps" 2>/dev/null && _bl_session+=("$_p")
done
}
bl_zram_pick() {
if [ "$1" = session ]; then
bl_session_others
_pids=("${_bl_session[@]}")
else
_pids=("${_bl_pids[@]}")
fi
}
# Same protocol as SessionSuspendController: an empty ack when the page-out starts, a byte when it is done.
# A process whose SIGURG handler was replaced never acks, so it is not waited for after the first 2 s.
bl_zram_wait() {
local _p _left _start=$SECONDS
while [ $((SECONDS - _start)) -lt 12 ]; do
_left=0
for _p in "$@"; do
[ -s "/tmp/.bl-zram.ack.$_p" ] && continue
[ -d "/proc/$_p" ] || continue
[ $((SECONDS - _start)) -ge 2 ] && [ ! -e "/tmp/.bl-zram.ack.$_p" ] && continue
_left=1
done
[ "$_left" = 1 ] || break
nap 0.2
done
for _p in "$@"; do rm -f "/tmp/.bl-zram.ack.$_p"; done
}
bl_zram_send() {
step "zRAM: $2 ($(bl_zram_usage))"
printf '%s' "$1" > /tmp/.bl-zram
[ "${#_bl_pids[@]}" = 0 ] || kill -URG "${_bl_pids[@]}" 2>/dev/null
nap 5
local _mode=$1 _what=$2 _which=$3 _pids _p
bl_zram_pick "$_which"
step "zRAM: $_what ($(bl_zram_usage "${_pids[@]}"))"
for _p in "${_pids[@]}"; do rm -f "/tmp/.bl-zram.ack.$_p"; done
printf '%s' "$_mode" > /tmp/.bl-zram
[ "${#_pids[@]}" = 0 ] || kill -URG "${_pids[@]}" 2>/dev/null
if [ "$_mode" = 1 ]; then bl_zram_wait "${_pids[@]}"; else nap 5; fi
bl_zram_scan
step "zRAM: done ($(bl_zram_usage))"
bl_zram_pick "$_which"
step "zRAM: done ($(bl_zram_usage "${_pids[@]}"))"
}
_bl_since=-1 _bl_packed=-1
# Proton starts its reaper before the game window; compressing during launch stalls it.
# Desktop Steam has no focus.json, so it still uses the game process as its trigger.
# A configured RAM cap can still force compression while a game is launching.
bl_game_focused() {
if [ "${BL_DESKTOP:-}" = 1 ] || [ -z "${BL_LAUNCH_DIR:-}" ]; then
return 0
fi
local id
id=$(sed -n 's/.*"focusedApp"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' \
"$BL_LAUNCH_DIR/agent/focus.json" 2>/dev/null | head -1)
[ -n "$id" ] || return 1
case " ${_bl_apps-} " in
*" $id "*) return 0 ;;
esac
return 1
}
bl_over_cap() {
[ "$_bl_ram_cap" -gt 0 ] || return 1
_bl_measured=$SECONDS
bl_session_others
bl_zram_usage "${_bl_pids[@]}" "${_bl_session[@]}" > /dev/null
[ "$_bl_rss" -gt "$_bl_ram_cap" ]
}
bl_cap_due() {
[ "$_bl_ram_cap" -gt 0 ] && { [ "$_bl_measured" -lt 0 ] || [ $((SECONDS - _bl_measured)) -ge 30 ]; }
}
_bl_since=-1 _bl_since_apps= _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=30
while kill -0 $$ 2>/dev/null; do
bl_zram_scan
if [ "$_bl_game" = 1 ]; then
[ "$_bl_since" -ge 0 ] || _bl_since=$SECONDS
if [ $((SECONDS - _bl_since)) -ge 20 ] && [ "${#_bl_pids[@]}" -gt 0 ] &&
if bl_cap_due; then
if bl_over_cap; then
# A cap below the game's working set cannot be met; paging out again every 30 s only churns.
if [ "$_bl_capped" -lt 0 ] || [ $((SECONDS - _bl_capped)) -ge "$_bl_backoff" ]; then
bl_zram_usage "${_bl_pids[@]}" > /dev/null
if [ "$_bl_rss" -ge $((512 * 1024)) ]; then
bl_zram_send 1 "over the ${BL_RAM_CAP_MB} MB RAM cap, compressing the client" client
[ "$_bl_game" = 1 ] && _bl_packed=$SECONDS
else
step "RAM cap: over, client already small ($((_bl_rss / 1024)) MB resident), skipping it"
fi
bl_over_cap && bl_zram_send 1 "still over the RAM cap, compressing the rest of the session" session
if bl_over_cap; then
_bl_backoff=$((_bl_backoff * 2 > 600 ? 600 : _bl_backoff * 2))
step "RAM cap: still over after paging out, next try in ${_bl_backoff} s"
else
_bl_backoff=30
fi
_bl_capped=$SECONDS
fi
else
_bl_backoff=30
if [ "$_bl_unpack" = 1 ] && [ "$_bl_game" = 0 ]; then
bl_zram_send 0 "back under the RAM cap, reading the client back" client
_bl_unpack=0
fi
fi
fi
if [ "$_bl_game" = 1 ] && bl_game_focused; then
if [ "$_bl_since" -lt 0 ] || [ "$_bl_since_apps" != "$_bl_apps" ]; then
_bl_since=$SECONDS _bl_since_apps=$_bl_apps
fi
if [ "${BL_ZRAM_CLIENT:-1}" = 1 ] && [ $((SECONDS - _bl_since)) -ge 20 ] && [ "${#_bl_pids[@]}" -gt 0 ] &&
{ [ "$_bl_packed" -lt 0 ] || [ $((SECONDS - _bl_packed)) -ge 300 ]; }; then
bl_zram_send 1 "compressing the client"
bl_zram_send 1 "compressing the client" client
_bl_packed=$SECONDS
fi
elif [ "$_bl_since" -ge 0 ]; then
[ "$_bl_packed" -lt 0 ] || bl_zram_send 0 "game closed, reading the client back"
elif [ "$_bl_game" != 1 ]; then
if [ "$_bl_packed" -ge 0 ]; then
if bl_over_cap; then _bl_unpack=1; else bl_zram_send 0 "game closed, reading the client back" client; _bl_unpack=0; fi
fi
_bl_since=-1 _bl_packed=-1
else
_bl_since=-1
fi
nap 5
done
@@ -1007,7 +1143,11 @@ BUSCONF
echo "== steam: devtools port $BL_CDP_PORT, guest processes only"
fi
[ -n "${BL_LAUNCH_DIR:-}" ] && mkdir -p "$BL_LAUNCH_DIR/agent" && echo "$BL_CDP_PORT" > "$BL_LAUNCH_DIR/agent/cdp-port"
[ "$steam_x64" = 1 ] || { "${_bl_compat_env[@]}" droiddeck-steam-compat "$steam_root" 2>&1 & }
if [ "$steam_x64" = 1 ]; then
{ droiddeck-steam-compat --files-only "$steam_root" 2>&1 & }
else
{ "${_bl_compat_env[@]}" droiddeck-steam-compat "$steam_root" 2>&1 & }
fi
_bl_ui=(-gamepadui)
[ "${BL_STEAM_UI:-}" = desktop ] && _bl_ui=()
# bl_steam_angle / bl_steam_presentation (set above) default to the Adreno values (vulkan,
@@ -2,6 +2,7 @@
import base64
import ctypes
import json
import math
import os
import runpy
import select
@@ -15,6 +16,50 @@ import time
HERE = os.path.dirname(os.path.realpath(__file__))
COMPAT = runpy.run_path(os.path.join(HERE, "steam-compatibility"))
BINDING = "droiddeckCompatChanged"
BRIGHTNESS_BINDING = "droiddeckBrightnessChanged"
CONTROLS_DIR = "/etc/droiddeck-device-controls"
BRIGHTNESS_JS = r"""
(() => {
if (window.__droiddeckBrightness) return "present";
const display = SteamClient.System?.Display;
if (!display?.RegisterForBrightnessChanges || !display?.SetBrightness) return "unavailable";
const self = { expected: null, updating: true, revision: 0 };
self.set = value => {
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) return;
if (!self.updating && self.expected !== null && Math.abs(value - self.expected) < 0.0001) return;
self.expected = value;
self.updating = true;
const revision = ++self.revision;
setTimeout(() => { if (self.revision === revision) self.updating = false; }, 500);
display.SetBrightness(value);
};
self.subscription = display.RegisterForBrightnessChanges(state => {
const value = state?.flBrightness;
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1 || self.expected === null) return;
if (Math.abs(value - self.expected) < 0.0001) { self.updating = false; return; }
if (self.updating) { self.updating = false; return; }
self.expected = value;
if (typeof window.__BINDING__ === "function") window.__BINDING__(String(value));
});
window.__droiddeckBrightness = self;
return "installed";
})()
""".replace("__BINDING__", BRIGHTNESS_BINDING)
def brightness_request(payload, directory=CONTROLS_DIR):
try:
value = float(payload)
if not math.isfinite(value) or not 0 <= value <= 1:
return
path = os.path.join(directory, "brightness.request")
with open(path + ".tmp", "w") as target:
target.write(str(value) + "\n")
os.replace(path + ".tmp", path)
except (ValueError, TypeError, OSError):
return
INSTALL_JS = r"""
(() => {
if (window.__droiddeckCompat) return "present";
@@ -196,6 +241,74 @@ TOUR_JS = r"""
return "off";
})()
"""
# Steam keeps the Quick Access Frame Limit as the client setting gamescope_app_target_framerate
# (CMsgClientSettings field 21002) and offers the values gamescope's display state lists in
# active_display_info.supported_frame_rates. When the panel's refresh rate changes, a remembered
# limit that is not one of the new values leaves the slider on its first value while the game runs
# at the old limit. The limit is kept when it is still offered and moved to the highest value
# otherwise. Choices are read once they have been unchanged for a moment, since a mode switch can
# report a passing rate first.
FRAME_LIMIT_JS = r"""
(() => {
if (window.__droiddeckFrameLimit) return "present";
const settings = window.settingsStore;
let service = null;
try {
// Steam's webpack does not expose its module cache; the gamescope service client is found by
// the calls its module makes and loaded by id.
let require;
window.webpackChunksteamui.push([[Symbol("droiddeck-frame-limit")], {}, r => { require = r; }]);
for (const id of Object.keys(require.m || {})) {
const source = String(require.m[id]);
if (!source.includes("SetBlurParams") || !source.includes("RegisterForNotifyStateChanged")) continue;
let exports;
try { exports = require(id); } catch (e) { continue; }
if (!exports || typeof exports !== "object") continue;
service = Object.values(exports).find(value => value && typeof value.GetState === "function" &&
typeof value.RegisterForNotifyStateChanged === "function" && typeof value.SetBlurParams === "function");
if (service) break;
}
} catch (e) {
service = null;
}
if (!service || !settings?.clientSettings || typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable";
const self = { timer: null };
const write = value => {
const bytes = [];
for (let n of [21002 * 8, value]) {
while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); }
bytes.push(n);
}
return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes)));
};
self.check = async () => {
let rates;
try {
const reply = await service.GetState({});
if (!reply.BSuccess()) return;
rates = reply.Body().toObject().state?.active_display_info?.supported_frame_rates;
} catch (e) {
return;
}
if (!Array.isArray(rates) || rates.length === 0) return;
const current = settings.clientSettings;
if (!current.gamescope_enable_app_target_framerate || rates.includes(current.gamescope_app_target_framerate)) return;
try {
await write(Math.max(...rates));
} catch (e) {
}
};
self.schedule = () => {
clearTimeout(self.timer);
self.timer = setTimeout(self.check, 1500);
};
self.subscription = service.RegisterForNotifyStateChanged(self.schedule);
self.interval = setInterval(self.schedule, 5000);
self.schedule();
window.__droiddeckFrameLimit = self;
return "installed";
})()
"""
FILE_BINDING = "droiddeckOpenFileDialog"
FILE_JS = r"""
(() => {
@@ -620,10 +733,11 @@ class Watcher:
class Helper:
def __init__(self, steam_root, port, steamos=False):
def __init__(self, steam_root, port, steamos=False, files_only=False):
self.steam_root = steam_root
self.port = port
self.steamos = steamos
self.files_only = files_only
self.page = None
self.known = set()
self.installed = None
@@ -632,6 +746,44 @@ class Helper:
self.tools_checked = None
self.vr_launch = None
self.chooser = None
self.controls_state = None
self.controls_installed = False
self.frame_limit_state = None
self.frame_limit_retry = 0
def sync_controls(self):
try:
with open(os.path.join(CONTROLS_DIR, "state.json")) as source:
state = json.load(source)
value = state.get("brightness")
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not 0 <= value <= 1:
return
if not self.controls_installed:
self.page.call("Runtime.addBinding", {"name": BRIGHTNESS_BINDING})
self.controls_installed = self.page.evaluate(BRIGHTNESS_JS) in ("installed", "present")
if not self.controls_installed:
return
if state != self.controls_state:
if self.page.evaluate("!!window.__droiddeckBrightness && (window.__droiddeckBrightness.set(%s), true)" % json.dumps(value)) is True:
self.controls_state = state
else:
self.controls_installed = False
self.controls_state = None
except (OSError, ValueError, TypeError):
pass
def sync_frame_limit(self):
# Steam can still be loading its settings and gamescope state when the helper attaches.
if self.frame_limit_state in ("installed", "present") or time.monotonic() < self.frame_limit_retry:
return
try:
state = self.page.evaluate(FRAME_LIMIT_JS)
except RuntimeError as e:
state = "failed (%s)" % e
if state != self.frame_limit_state:
say("frame limit sync: %s" % state)
self.frame_limit_state = state
self.frame_limit_retry = time.monotonic() + 10
def open_chooser(self, payload):
try:
@@ -647,9 +799,14 @@ class Helper:
self.finish_chooser(ident, None)
return
command = [sys.executable, os.path.realpath(__file__), "--choose-file"]
reaper = os.path.join(self.steam_root, "steamrtarm64", "reaper")
if os.access(reaper, os.X_OK):
command = [reaper, "SteamLaunch", "AppId=769", "--"] + command
# Gamescope shows the dialog over the client by the AppId on a reaper above it; the x86-64 client has no
# native reaper, so the arm64 client's is borrowed when it is installed.
data = os.environ.get("XDG_DATA_HOME") or os.path.join(os.path.expanduser("~"), ".local", "share")
for root in (self.steam_root, os.path.join(data, "Steam")):
reaper = os.path.join(root, "steamrtarm64", "reaper")
if os.access(reaper, os.X_OK):
command = [reaper, "SteamLaunch", "AppId=769", "--"] + command
break
try:
proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, start_new_session=True)
@@ -699,6 +856,14 @@ class Helper:
try:
if page.evaluate("typeof SteamClient === 'object' && typeof SteamClient.WebUITransport === 'object'") is not True:
raise LookupError("SteamClient is not ready")
if self.files_only:
page.call("Runtime.addBinding", {"name": FILE_BINDING})
page.evaluate(FILE_JS)
self.page = page
self.controls_state = None
self.controls_installed = False
self.sync_controls()
return True
page.call("Runtime.addBinding", {"name": BINDING})
page.call("Runtime.addBinding", {"name": VR_BINDING})
page.evaluate(VR_JS)
@@ -717,6 +882,11 @@ class Helper:
page.ws.close()
raise
self.page = page
self.controls_state = None
self.controls_installed = False
self.frame_limit_state = None
self.frame_limit_retry = 0
self.sync_controls()
return True
def reconcile(self):
@@ -843,21 +1013,40 @@ class Helper:
say("preparing SteamVR for library app(s): " + ", ".join(sorted(vr_games)))
self.vr_launch = launch_steamvr()
for e in events:
if called(e, BRIGHTNESS_BINDING):
brightness_request(e.get("params", {}).get("payload"))
if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str):
self.open_chooser(e["params"]["payload"])
return events
def serve_files(self):
say("attached to the client on port %d for its file dialogs" % self.port)
while True:
self.sync_controls()
sources = [self.page.ws] + ([self.chooser[1].stdout] if self.chooser is not None else [])
queued = self.page.ws.pending() or bool(self.page.events)
ready = [self.page.ws] if queued else select.select(sources, [], [], 0.25)[0]
if self.chooser is not None and self.chooser[1].stdout in ready:
self.chooser_done()
if self.page.ws in ready or self.page.events:
self.drain()
def serve(self, watcher):
if self.files_only:
return self.serve_files()
with open(COMPAT["state_path"]("live.pid"), "w") as f:
f.write("%d\n" % os.getpid())
say("attached to the client on port %d" % self.port)
self.reconcile()
self.ensure_tools()
while True:
self.sync_controls()
self.sync_frame_limit()
sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else [])
if self.chooser is not None:
sources.append(self.chooser[1].stdout)
ready = [self.page.ws] if self.page.ws.pending() else select.select(sources, [], [], 30 if watcher.fileno() >= 0 else 2)[0]
queued = self.page.ws.pending() or bool(self.page.events)
ready = [self.page.ws] if queued else select.select(sources, [], [], 0.25)[0]
if self.chooser is not None and self.chooser[1].stdout in ready:
self.chooser_done()
due = False
@@ -903,12 +1092,29 @@ def chooser_main():
def main():
steam_root = sys.argv[1]
files_only = sys.argv[1:2] == ["--files-only"]
steam_root = sys.argv[2 if files_only else 1]
try:
port = int(os.environ.get("BL_CDP_PORT", ""))
except ValueError:
say("no devtools port for this session; the client's mapping is kept through config.vdf")
return 0
if files_only:
helper = Helper(steam_root, port, files_only=True)
failures = 0
while True:
try:
helper.attach()
failures = 0
helper.serve(None)
except Exception as e:
helper.close_chooser()
if helper.page is not None:
say("lost the client (%s); reattaching" % e)
helper.page.ws.close()
helper.page = None
failures += 1
time.sleep(min(2 * max(failures, 1), 10))
os.makedirs(COMPAT["COMPAT_DIR"], exist_ok=True)
watcher = Watcher([COMPAT["state_path"]("request.json"), COMPAT["state_path"]("games.json")] +
[os.path.join(lib, "steamapps", "libraryfolders.vdf") for lib in (steam_root, COMPAT["LIBRARY"] + "-sd")])
@@ -943,4 +1149,5 @@ if __name__ == "__main__":
try:
sys.exit(main())
finally:
detach()
if sys.argv[1:2] != ["--files-only"]:
detach()
@@ -1,8 +1,5 @@
#!/bin/bash
set -eu
FEX_TAG=fex-2610-r5
FEX_SHA256=0fc1ca2ba13817ad70d1ea157119a75c9c02446b57d166e6d676cce0807c19c4
FEX_URL=https://github.com/Droid-Deck/DroidDeck-Components/releases/download/$FEX_TAG/fex.tzst
ROOTFS_URL=https://github.com/Droid-Deck/DroidDeck-Components/releases/download/fex-rootfs-ubuntu-24.04-2026-08-11/Ubuntu_24_04.sqsh
ROOTFS_SHA256=2854b06d3ff1b8f6e526135bfb6dd5b7b30ab3ab73e79ae933a3d9fed959a178
CDN=https://client-update.fastly.steamstatic.com
@@ -18,6 +15,7 @@ ARM_STEAM=${XDG_DATA_HOME:-$REAL_HOME/.local/share}/Steam
LOG=$X64_HOME/steam-x64.log
mkdir -p "$X64_HOME"
step() { echo "== STEP $(date -u +%H:%M:%S) $*" | tee -a "$LOG"; }
. "${BASH_SOURCE[0]%/*}/droiddeck-fex-update"
x64_default_dir() {
local d
@@ -319,76 +317,6 @@ print("droiddeck-steam-x64: %d Linux title(s) on DroidDeck direct (%d on the new
PY
}
# Whether every program in the FEX tree at $1 finds its libraries (r4 did not without libxxhash).
fex_loads() {
local b out
for b in FEX FEXServer unsquashfs; do
out=$(/usr/lib/ld-linux-aarch64.so.1 --list "$1/usr/local/bin/$b" 2>&1) && ! grep -q "not found" <<<"$out" && continue
echo "== FEX check: $b: $(grep -E "not found|error" <<<"$out" | tr -s '\t ' ' ' | tr '\n' ';')" >&2
return 1
done
}
# Installs one FEX build only once its archive matches the sha256 and it loads. The files it replaces are kept
# until the installed copy loads too, and put back otherwise; the tag is written last.
fex_install() {
local tag=$1 sha=$2 urls=$3 dst=/ tmp u f
tmp=$(mktemp -d)
for u in $urls; do
curl -fsSL --retry 2 "$u" -o "$tmp/fex.tzst" && echo "$sha $tmp/fex.tzst" | sha256sum -c --quiet >/dev/null 2>&1 && break
rm -f "$tmp/fex.tzst"
done
if [ ! -s "$tmp/fex.tzst" ]; then
echo "== FEX $tag: no source gave the archive with sha256 ${sha:0:12}" >&2
rm -rf "$tmp"
return 1
fi
if ! { mkdir "$tmp/root" && zstd -dc "$tmp/fex.tzst" | tar -C "$tmp/root" -x && fex_loads "$tmp/root"; }; then
rm -rf "$tmp"
return 1
fi
(cd "$tmp/root" && find . ! -type d) > "$tmp/files"
mkdir "$tmp/old"
while IFS= read -r f; do
f=${f#./}
if [ -e "$dst$f" ] || [ -L "$dst$f" ]; then
cp -a --parents "$dst$f" "$tmp/old" || { echo "== FEX $tag: could not keep $dst$f aside" >&2; rm -rf "$tmp"; return 1; }
fi
done < "$tmp/files"
if tar -C "$tmp/root" -c . | tar -C "$dst" -x && fex_loads "$dst" &&
mkdir -p "${dst}usr/local/share/fex-emu" && echo "$tag" > "${dst}usr/local/share/fex-emu/.droiddeck-tag"; then
rm -rf "$tmp"
return 0
fi
echo "== FEX $tag: the installed copy did not load or its tag was not written; putting the previous files back" >&2
while IFS= read -r f; do
f=${f#./}
[ -e "$tmp/old/$dst$f" ] || [ -L "$tmp/old/$dst$f" ] || rm -f "$dst$f"
done < "$tmp/files"
tar -C "$tmp/old$dst" -c . | tar -C "$dst" -x || echo "== FEX $tag: could not put the previous files back" >&2
rm -rf "$tmp"
return 1
}
# The build DroidDeck-Components' fex.json names (the app passes it as BL_FEX_*) comes first, then a working
# installed one, then FEX_TAG above. Sets FEX_NOW and FEX_FROM.
x64_fex() {
local have ok=
have=$(cat /usr/local/share/fex-emu/.droiddeck-tag 2>/dev/null || true)
[ -x /usr/local/bin/FEX ] && fex_loads / && ok=1
if [ -n "${BL_FEX_TAG:-}" ]; then
if [ -n "$ok" ] && [ "$have" = "$BL_FEX_TAG" ]; then FEX_NOW=$have FEX_FROM=catalog; return 0; fi
step "downloading FEX ($BL_FEX_TAG)"
if fex_install "$BL_FEX_TAG" "${BL_FEX_SHA256:-}" "${BL_FEX_URLS:-}"; then FEX_NOW=$BL_FEX_TAG FEX_FROM=catalog; return 0; fi
if [ -n "$ok" ]; then FEX_NOW=$have FEX_FROM="kept; $BL_FEX_TAG did not install"; return 0; fi
fi
if [ -n "$ok" ] && [ "$have" = "$FEX_TAG" ]; then FEX_NOW=$have FEX_FROM=built-in; return 0; fi
step "downloading FEX ($FEX_TAG)"
if fex_install "$FEX_TAG" "$FEX_SHA256" "$FEX_URL"; then FEX_NOW=$FEX_TAG FEX_FROM=built-in; return 0; fi
if [ -n "$ok" ]; then FEX_NOW=$have FEX_FROM="kept; $FEX_TAG did not install"; return 0; fi
return 1
}
# A resumable download that reports every tenth of its size as a step.
x64_fetch() {
local url=$1 out=$2 label=$3 total pid rc=0 last=-1 pct
@@ -406,7 +334,7 @@ x64_fetch() {
}
x64_prepare() {
x64_fex || { step "FEX could not be installed; see $LOG"; exit 1; }
fex_ready || { step "FEX could not be installed; see $LOG"; exit 1; }
step "FEX ready ($FEX_NOW, $FEX_FROM)"
# The client's opt-in to its SteamRT3 build; without it, it re-executes through steam.sh, whose checks fail under proot.
mkdir -p "$STEAM_X64" && : > "$STEAM_X64/.steam-enable-steamrt64-client"
@@ -25,6 +25,8 @@ Android: an EOS sign-in step that falls back to a browser (a consent Epic asks f
is finished there. An EOS overlay pointer (HKCU\Software\Epic Games\EOS "OverlayPath") an earlier
build wrote is removed - with it the game exited while loading.
Battle.net.exe in Battle.net's prefix is handed to droiddeck-battlenet, which runs the whole launch.
droiddeck-store-launch <the arguments Steam gave the compat tool>
"""
@@ -291,6 +293,27 @@ def create_prefix(compat_data, proton, timeout=120):
CLOUD_TIMEOUT = 15.0
CLOUD_STORES = ("gog", "epic")
STORE_GAME = 10
RAN = 11
RAN_FAILED = 12
BATTLENET = "/usr/local/bin/droiddeck-battlenet"
BATTLENET_EXE = re.compile(r"(?i)/compatdata/2596113170/pfx/drive_c/Program Files \(x86\)/Battle\.net/Battle\.net\.exe$")
BATTLENET_LAUNCH = re.compile(r'(?i)^--exec=\s*"?launch\s+([A-Za-z0-9_]{1,16})"?$')
def battlenet(argv, env=os.environ):
if env.get("BL_BATTLENET"):
return None
exe, code = False, None
for raw in argv:
arg = raw.strip().strip('"').strip("'")
if BATTLENET_EXE.search(arg.replace("\\", "/")):
exe = True
found = BATTLENET_LAUNCH.match(arg)
if found:
code = found.group(1)
if not exe:
return None
return [BATTLENET, "launch", code] if code else [BATTLENET, "open"]
def cloud_on(sidecar):
@@ -511,6 +534,10 @@ def main(argv):
pass
rest = rest[2:]
return exited(rest, code)
command = battlenet(argv)
if command is not None:
log("battlenet " + " ".join(command[1:]))
return RAN if subprocess.call(command) == 0 else RAN_FAILED
found = find_store_game(argv)
if found is None:
return 0
@@ -27,6 +27,7 @@ CLASSES = {
'Windows.Storage.Streams.DataWriter'),
}
CLASS_KEY = 'Software\\Microsoft\\WindowsRuntime\\ActivatableClassId\\'
VIEW_DRIVES = 'xwvutsrqponmlkjihgfe'
def bridge(upstream):
@@ -137,6 +138,29 @@ def register_classes(proton, prefix, env):
print('droiddeck-xbox: Windows Runtime class registration failed; launching without it', file=sys.stderr)
def view_drive(prefix, exe):
path = Path(exe)
view = next((parent for parent in path.parents if parent.name.startswith('droiddeck-xbox-')), None)
if not path.is_absolute() or view is None:
return exe, None
devices = prefix / 'dosdevices'
for letter in VIEW_DRIVES:
link = devices / (letter + ':')
staged = devices / ('.%s-%s' % (letter, secrets.token_hex(4)))
try:
if os.path.lexists(link) and (os.path.exists(link) or not os.readlink(link).startswith(str(view.parent.parent) + '/')):
continue
devices.mkdir(parents=True, exist_ok=True)
staged.symlink_to(view)
os.replace(staged, link)
except OSError:
if os.path.lexists(staged):
staged.unlink()
continue
return letter.upper() + ':\\' + str(path.relative_to(view)).replace('/', '\\'), link
return exe, None
def wine(argv, source_env=None):
source_env = os.environ if source_env is None else source_env
with open(source_env['DROIDDECK_XBOX_COMMAND_FILE'], encoding='utf-8') as file:
@@ -163,7 +187,15 @@ def wine(argv, source_env=None):
register_classes(command[0], prefix, env)
overrides = ';'.join(name[:-4] + '=n' for name in DLLS if name != 'libnghttp2.dll')
env['WINEDLLOVERRIDES'] = overrides + ';' + env.get('WINEDLLOVERRIDES', '')
return subprocess.call([*command[:2], argv[0], *command[3:]], env=env)
exe, drive = view_drive(prefix, argv[0])
try:
return subprocess.call([*command[:2], exe, *command[3:]], env=env)
finally:
if drive is not None:
try:
drive.unlink()
except OSError:
pass
def renew_lease(ask, channel, product, lease, stopped):
@@ -69,7 +69,10 @@ bl_store_launch() {
fi
[ -x /usr/local/bin/droiddeck-store-launch ] || return 0
/usr/local/bin/droiddeck-store-launch "$@"
[ $? -eq 10 ] && BL_STORE_EXIT=1
rc=$?
[ $rc -eq 10 ] && BL_STORE_EXIT=1
[ $rc -eq 11 ] && exit 0
[ $rc -eq 12 ] && exit 1
return 0
}
@@ -87,6 +90,34 @@ bl_run() {
}
"""
BL_DESKTOP_GPU_SETUP = """
bl_desktop_gpu() {
local name saved gpu=/usr/local/bin/droiddeck-gpu
local names=(LD_PRELOAD LD_LIBRARY_PATH ENABLE_VK_LAYER_VALVE_steam_overlay_1 ENABLE_VK_LAYER_VALVE_steam_fossilize_1)
if [ -n "${BL_DESKTOP_GPU_CHILD:-}" ]; then
for name in "${names[@]}"; do
saved=BL_GPU_SAVED_$name
[ -n "${!saved+x}" ] || continue
export "$name=${!saved}"
unset "$saved"
done
return 0
fi
[ "${BL_DESKTOP:-}" = 1 ] && [ "${verb:-}" = waitforexitandrun ] && [ -x "$gpu" ] || return 0
local choice=${BL_DESKTOP_GPU:-on}
case "${choice,,}" in off | 0 | no | false) return 0 ;; esac
case " $* " in *iscriptevaluator*) return 0 ;; esac
local clear=()
for name in "${names[@]}"; do
[ -n "${!name+x}" ] || continue
export "BL_GPU_SAVED_$name=${!name}"
clear+=(-u "$name")
done
echo "droiddeck-gpu: the desktop starts this game on the GPU" >&2
exec env "${clear[@]}" "$gpu" "$0" "$verb" "$@"
}
bl_desktop_gpu "$@"
"""
BL_COMPONENTS_SETUP = """
bl_components() {
base=$1
@@ -380,7 +411,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH
def launcher_sh(sources=SOURCES):
return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace(
"verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
"verb=$1; shift", "verb=$1; shift\n" + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
@@ -469,7 +500,7 @@ verb=$1; shift
case $verb in
getcompatpath | getnativepath) printf '%s\\n' "$1"; exit 0 ;;
esac
""" + BL_GAME_CPUS_SETUP + """
""" + BL_DESKTOP_GPU_SETUP + BL_GAME_CPUS_SETUP + """
bl_game_cpus
if [ -x /usr/local/bin/droiddeck-steamvr-flat ] && /usr/local/bin/droiddeck-steamvr-flat "$verb"; then
exec /usr/local/bin/droiddeck-steamvr-game ${BL_TASKSET:-} /usr/local/bin/droiddeck-fex steam "$verb" "$@"
@@ -652,7 +683,7 @@ def adopt_extras(tools):
try:
body = (EXTRA_WRAPPER_SH % entry_point).replace(
'here=$(dirname "$0")',
'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
'here=$(dirname "$0")\n' + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
write_changed(wrapper, body, 0o755)
write_changed(manifest, EXTRA_MANIFEST_VDF)
@@ -1222,6 +1253,32 @@ def requested_games(requests, catalog, runnable=None):
return resolved
OWN_PROTON = "DroidDeck-Proton"
ARCH_WORDS = re.compile(r"(?i)aarch64|arm64|x86_64|x86-64|amd64")
def own_builds(tools):
return [t for t in tools if isinstance(t, dict) and not t.get("valve") and
isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name")]
def build_key(name):
return [int(n) for n in re.findall(r"\d+", ARCH_WORDS.sub(" ", name))]
def own_proton_moves(state, catalog):
names = {t["name"] for t in catalog}
before = state.get("tools") if isinstance(state.get("tools"), list) else ()
seen = state.get("own_builds") if isinstance(state.get("own_builds"), list) else []
known = {n for n in seen if isinstance(n, str)} | {t["name"] for t in own_builds(before)} | {t["name"] for t in own_builds(catalog)}
state["own_builds"] = sorted(known)
builds = own_builds(catalog)
if not builds:
return None, set()
newest = max(builds, key=lambda t: (build_key(t["dir"]), t["dir"]))["name"]
return newest, known - names
def now_ms():
import time
return int(time.time() * 1000)
@@ -1382,11 +1439,26 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
catalog = tool_catalog(os.path.dirname(os.path.dirname(os.path.abspath(config_path))),
dict(protect) if isinstance(protect, dict) else {name: name for name in protect})
names = [t["name"] for t in catalog]
newest, gone = own_proton_moves(state, catalog)
previous, applied, chosen = state.get("default"), state.get("applied"), state.get("seq")
if default is None:
if settle:
default, state = choose_default(current.get("0", ""), state, read_json(state_path("request.json", directory)), catalog)
else:
default = state.get("default") if state.get("default") in names else TOOL
if settle and newest and default == TOOL and state.get("applied") == applied and state.get("seq") == chosen and (
previous in gone or not state.get("own_proton")):
default = newest
state.update(default=newest, seq=now_ms(), source="update")
if settle and newest:
state["own_proton"] = True
if newest:
for app, name in list(current.items()):
if app != "0" and name in gone:
set_mapping(tokens, mapping, app, newest)
current[app] = newest
if isinstance(state.get("auto"), dict):
state["auto"] = {app: newest if name in gone else name for app, name in state["auto"].items()}
steam_root = os.path.dirname(os.path.dirname(os.path.abspath(config_path)))
requests = settled_game_requests(state, current, catalog, not steam_running(), directory)
overrides = requested_games(requests or {}, catalog)
+2
View File
@@ -407,6 +407,7 @@ int bl_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long
int bl_ntsync_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
int bl_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
int bl_venc_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
int bl_vdec_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
int bl_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
void *arg, void *caller, int *rc) __attribute__((visibility("hidden")));
int bl_writewatch_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg,
@@ -423,6 +424,7 @@ int ioctl(int fd, unsigned long request, ...) {
int rc;
if (bl_ntsync_ioctl(fd, request, arg, &rc)) return rc;
if (bl_venc_ioctl(fd, request, arg, &rc)) return rc;
if (bl_vdec_ioctl(fd, request, arg, &rc)) return rc;
if (bl_drm_gem_close(fd, request, arg, &rc)) return rc;
if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl");
if (bl_winebus_rumble_ioctl(real, fd, request, arg, __builtin_return_address(0), &rc)) return rc;
+2
View File
@@ -1459,10 +1459,12 @@ ssize_t recvmsg(int fd, struct msghdr *msg, int flags) {
void bl_fsync_fds_closed(unsigned int first, unsigned int last) __attribute__((visibility("hidden")));
void bl_venc_closed(int fd) __attribute__((visibility("hidden")));
void bl_vdec_closed(int fd) __attribute__((visibility("hidden")));
int close(int fd) {
if (fd >= 0) bl_fsync_fds_closed((unsigned int)fd, (unsigned int)fd);
bl_venc_closed(fd);
bl_vdec_closed(fd);
uint64_t *t = __atomic_load_n(&ns_fdt, __ATOMIC_ACQUIRE);
if (t && fd >= 0 && fd < NS_FDS && __atomic_load_n(&t[fd], __ATOMIC_ACQUIRE)) ns_forget(fd);
return ns_close_fd(fd);
+3
View File
@@ -16,6 +16,7 @@ int bl_writable_retry(int dirfd, const char *path, int flags) __attribute__((vis
int bl_ntsync_open(const char *path, int flags) __attribute__((visibility("hidden")));
const char *bl_oom_adj_redirect(const char *path, int writing) __attribute__((visibility("hidden")));
int bl_venc_open(const char *path, int flags) __attribute__((visibility("hidden")));
int bl_vdec_open(const char *path, int flags) __attribute__((visibility("hidden")));
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden")));
@@ -57,6 +58,7 @@ int open(const char *path, int flags, ...) {
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
if ((fd = bl_ntsync_open(path, flags)) != -2) return fd;
if ((fd = bl_venc_open(path, flags)) != -2) return fd;
if ((fd = bl_vdec_open(path, flags)) != -2) return fd;
if (real_open == NULL) real_open = dlsym(RTLD_NEXT, "open");
if (real_open == NULL) {
errno = ENOSYS;
@@ -84,6 +86,7 @@ int openat(int dirfd, const char *path, int flags, ...) {
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
if ((fd = bl_ntsync_open(path, flags)) != -2) return fd;
if ((fd = bl_venc_open(path, flags)) != -2) return fd;
if ((fd = bl_vdec_open(path, flags)) != -2) return fd;
if (real_openat == NULL) real_openat = dlsym(RTLD_NEXT, "openat");
if (real_openat == NULL) {
errno = ENOSYS;
+978
View File
@@ -0,0 +1,978 @@
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <poll.h>
#include <stddef.h>
#if defined(__aarch64__) || defined(BL_VDEC_ANY_ARCH)
#include <fcntl.h>
#include <linux/videodev2.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include "../../../app/src/main/cpp/venc/venc_proto.h"
#define VDEC_DEVICE "/dev/video-dec0"
#define VDEC_INSTANCES 4
#define VDEC_BUFFERS 16
#define VDEC_BITSTREAM_SIZE (4u << 20)
#define VDEC_PADDING 64
#define VDEC_DUMB 64
struct vd_dma_heap_alloc {
uint64_t len;
uint32_t fd;
uint32_t fd_flags;
uint64_t heap_flags;
};
#define VD_DMA_HEAP_IOCTL_ALLOC _IOWR('H', 0x0, struct vd_dma_heap_alloc)
struct vd_dma_buf_sync {
uint64_t flags;
};
#define VD_DMA_BUF_SYNC_WRITE 2u
#define VD_DMA_BUF_SYNC_START 0u
#define VD_DMA_BUF_SYNC_END 4u
#define VD_DMA_BUF_IOCTL_SYNC _IOW('b', 0, struct vd_dma_buf_sync)
struct vd_create_dumb {
uint32_t height, width, bpp, flags, handle, pitch;
uint64_t size;
};
struct vd_destroy_dumb {
uint32_t handle;
};
struct vd_prime_handle {
uint32_t handle, flags;
int32_t fd;
};
#define VD_IOCTL_MODE_CREATE_DUMB _IOWR('d', 0xB2, struct vd_create_dumb)
#define VD_IOCTL_MODE_DESTROY_DUMB _IOWR('d', 0xB4, struct vd_destroy_dumb)
#define VD_IOCTL_PRIME_HANDLE_TO_FD _IOWR('d', 0x2d, struct vd_prime_handle)
struct vd_mode_info {
uint32_t clock;
uint16_t hdisplay, hsync_start, hsync_end, htotal, hskew;
uint16_t vdisplay, vsync_start, vsync_end, vtotal, vscan;
uint32_t vrefresh, flags, type;
char name[32];
};
struct vd_res {
int count_fbs;
uint32_t *fbs;
int count_crtcs;
uint32_t *crtcs;
int count_connectors;
uint32_t *connectors;
int count_encoders;
uint32_t *encoders;
uint32_t min_width, max_width, min_height, max_height;
};
struct vd_connector {
uint32_t connector_id, encoder_id, connector_type, connector_type_id;
int connection;
uint32_t mm_width, mm_height;
int subpixel;
int count_modes;
struct vd_mode_info *modes;
int count_props;
uint32_t *props;
uint64_t *prop_values;
int count_encoders;
uint32_t *encoders;
};
struct vd_encoder {
uint32_t encoder_id, encoder_type, crtc_id, possible_crtcs, possible_clones;
};
struct vd_crtc {
uint32_t crtc_id, buffer_id, x, y, width, height;
int mode_valid;
struct vd_mode_info mode;
int gamma_size;
};
struct vd_device {
char **nodes;
int available_nodes;
int bustype;
void *businfo;
void *deviceinfo;
};
struct vd_capture {
int fd;
ino_t ino;
uint8_t *map;
size_t len;
};
struct vd_done {
uint32_t index;
struct timeval timestamp;
};
struct vdec {
int used, fd;
uint32_t fourcc, width, height;
uint32_t cap_width, cap_height, bpl, cap_size;
uint8_t *bitstream;
uint32_t out_count;
uint32_t out_done[VDEC_BUFFERS], n_out_done;
struct vd_capture cap[VDEC_BUFFERS];
uint32_t cap_count;
uint32_t cap_queue[VDEC_BUFFERS], n_cap_queue;
struct vd_done cap_done[VDEC_BUFFERS];
uint32_t n_cap_done;
int out_on, cap_on;
int sock, hw, hw_failed;
int64_t pts;
void *ctx, *packet, *frame;
uint8_t *packet_data;
size_t packet_capacity;
int last;
uint32_t frames, slow;
double decode_ms;
};
static struct {
void *(*find_decoder_by_name)(const char *);
void *(*alloc_context3)(const void *);
int (*open2)(void *, const void *, void **);
void (*free_context)(void **);
int (*send_packet)(void *, const void *);
int (*receive_frame)(void *, void *);
void (*flush_buffers)(void *);
void *(*packet_alloc)(void);
void (*packet_free)(void **);
void *(*frame_alloc)(void);
void (*frame_free)(void **);
void (*frame_unref)(void *);
int (*dict_set)(void **, const char *, const char *, int);
void (*dict_free)(void **);
const char *(*pix_fmt_name)(int);
} av;
static pthread_mutex_t vd_lock = PTHREAD_MUTEX_INITIALIZER;
static struct vdec vd_all[VDEC_INSTANCES];
static int vd_open_count;
static int vd_state;
static int vd_ffmpeg;
static int vd_heap = -1;
static int vd_dumb_fd[VDEC_DUMB];
static char vd_drm_handle;
static void vd_log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
static void vd_log(const char *fmt, ...) {
va_list ap;
char line[256];
va_start(ap, fmt);
int n = vsnprintf(line, sizeof line - 1, fmt, ap);
va_end(ap);
if (n < 0) return;
if (n > (int)sizeof line - 2) n = sizeof line - 2;
line[n++] = '\n';
if (write(2, "droiddeck-vdec: ", 16) < 0 || write(2, line, n) < 0) return;
}
static int vd_load_ffmpeg(void) {
void *codec = dlopen("libavcodec.so.62", RTLD_LAZY | RTLD_LOCAL);
void *util = codec ? dlopen("libavutil.so.60", RTLD_LAZY | RTLD_LOCAL) : NULL;
if (codec == NULL || util == NULL) {
vd_log("FFmpeg 8 is not available (%s), Remote Play decoding stays off", dlerror());
return 0;
}
#define VD_SYM(lib, field, name) \
if ((*(void **)&av.field = dlsym(lib, name)) == NULL) { \
vd_log("FFmpeg has no %s, Remote Play decoding stays off", name); \
return 0; \
}
VD_SYM(codec, find_decoder_by_name, "avcodec_find_decoder_by_name")
VD_SYM(codec, alloc_context3, "avcodec_alloc_context3")
VD_SYM(codec, open2, "avcodec_open2")
VD_SYM(codec, free_context, "avcodec_free_context")
VD_SYM(codec, send_packet, "avcodec_send_packet")
VD_SYM(codec, receive_frame, "avcodec_receive_frame")
VD_SYM(codec, flush_buffers, "avcodec_flush_buffers")
VD_SYM(codec, packet_alloc, "av_packet_alloc")
VD_SYM(codec, packet_free, "av_packet_free")
VD_SYM(util, frame_alloc, "av_frame_alloc")
VD_SYM(util, frame_free, "av_frame_free")
VD_SYM(util, frame_unref, "av_frame_unref")
VD_SYM(util, dict_set, "av_dict_set")
VD_SYM(util, dict_free, "av_dict_free")
VD_SYM(util, pix_fmt_name, "av_get_pix_fmt_name")
#undef VD_SYM
return 1;
}
static int vd_have_ffmpeg(void) {
if (vd_ffmpeg == 0) vd_ffmpeg = vd_load_ffmpeg() ? 1 : -1;
return vd_ffmpeg > 0;
}
__attribute__((visibility("hidden"))) int bl_venc_connect(void);
static int vd_enabled(void) {
pthread_mutex_lock(&vd_lock);
if (vd_state == 0) {
const char *flag = getenv("BL_REMOTE_PLAY_DECODE"), *socket = getenv("BL_VENC_SOCKET");
vd_state = -1;
if (strcmp(program_invocation_short_name, "streaming_client") == 0 && (flag == NULL || strcmp(flag, "0") != 0)) {
vd_heap = open("/dev/dma_heap/system", O_RDONLY | O_CLOEXEC);
if (vd_heap < 0) vd_log("no /dev/dma_heap/system (%s), Remote Play decoding stays off", strerror(errno));
else if ((socket && *socket) || vd_have_ffmpeg()) vd_state = 1;
for (int i = 0; i < VDEC_DUMB; i++) vd_dumb_fd[i] = -1;
}
}
int on = vd_state > 0;
pthread_mutex_unlock(&vd_lock);
return on;
}
static struct vdec *vd_find(int fd) {
if (fd < 0 || __atomic_load_n(&vd_open_count, __ATOMIC_ACQUIRE) == 0) return NULL;
for (int i = 0; i < VDEC_INSTANCES; i++) if (vd_all[i].used && vd_all[i].fd == fd) return &vd_all[i];
return NULL;
}
__attribute__((visibility("hidden"))) int bl_vdec_open(const char *path, int flags) {
(void)flags;
if (path == NULL || strcmp(path, VDEC_DEVICE) != 0 || !vd_enabled()) return -2;
int fd = memfd_create("droiddeck-vdec", 0);
if (fd < 0) return -1;
pthread_mutex_lock(&vd_lock);
struct vdec *v = NULL;
for (int i = 0; i < VDEC_INSTANCES && v == NULL; i++) if (!vd_all[i].used) v = &vd_all[i];
if (v == NULL) {
pthread_mutex_unlock(&vd_lock);
close(fd);
errno = EBUSY;
return -1;
}
memset(v, 0, sizeof *v);
v->used = 1;
v->fd = fd;
v->fourcc = V4L2_PIX_FMT_H264;
v->last = -1;
v->sock = -1;
for (int i = 0; i < VDEC_BUFFERS; i++) v->cap[i].fd = -1;
__atomic_add_fetch(&vd_open_count, 1, __ATOMIC_RELEASE);
pthread_mutex_unlock(&vd_lock);
return fd;
}
static void vd_close_decoder(struct vdec *v) {
if (v->frames) {
vd_log("%u frames, %.1f ms each on average, %u over 25 ms", v->frames, v->decode_ms / v->frames, v->slow);
}
if (v->sock >= 0) close(v->sock);
v->sock = -1;
v->hw = 0;
if (v->ctx) av.free_context(&v->ctx);
if (v->packet) av.packet_free(&v->packet);
if (v->frame) av.frame_free(&v->frame);
free(v->packet_data);
v->packet_data = NULL;
v->packet_capacity = 0;
v->frames = v->slow = 0;
v->decode_ms = 0;
v->last = -1;
}
static int vd_send(int sock, const void *msg, size_t len, int fd) {
struct iovec iov = { .iov_base = (void *)msg, .iov_len = len };
char control[CMSG_SPACE(sizeof(int))];
struct msghdr m = { .msg_iov = &iov, .msg_iovlen = 1 };
if (fd >= 0) {
memset(control, 0, sizeof control);
m.msg_control = control;
m.msg_controllen = sizeof control;
struct cmsghdr *c = CMSG_FIRSTHDR(&m);
c->cmsg_level = SOL_SOCKET;
c->cmsg_type = SCM_RIGHTS;
c->cmsg_len = CMSG_LEN(sizeof(int));
memcpy(CMSG_DATA(c), &fd, sizeof fd);
}
return sendmsg(sock, &m, MSG_NOSIGNAL) == (ssize_t)len ? 0 : -1;
}
static void vd_send_capture(struct vdec *v, uint32_t index) {
struct vdec_capture c = { .type = VDEC_CAPTURE, .index = index, .size = (uint32_t)v->cap[index].len };
if (v->sock >= 0 && v->cap[index].map && vd_send(v->sock, &c, sizeof c, v->cap[index].fd) != 0)
vd_log("could not hand capture buffer %u to the app: %s", index, strerror(errno));
}
static int vd_open_hardware(struct vdec *v) {
if (v->hw_failed) return -1;
int sock = bl_venc_connect();
if (sock < 0) return -1;
struct vdec_config c = {
.type = VDEC_CONFIG, .codec = v->fourcc == V4L2_PIX_FMT_HEVC ? VENC_HEVC : VENC_H264,
.width = v->width ? v->width : v->cap_width, .height = v->height ? v->height : v->cap_height,
.stride = v->bpl, .rows = v->cap_height, .bitstreams = v->out_count, .bitstream_size = VDEC_BITSTREAM_SIZE,
};
struct vdec_result r;
if (vd_send(sock, &c, sizeof c, v->fd) != 0 || recv(sock, &r, sizeof r, 0) != (ssize_t)sizeof r ||
r.type != VDEC_RESULT || r.status != 0) {
vd_log("the app has no %s decoder for %ux%u", c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height);
close(sock);
v->hw_failed = 1;
return -1;
}
v->sock = sock;
v->hw = 1;
for (uint32_t i = 0; i < v->cap_count; i++) vd_send_capture(v, i);
vd_log("decoding %s %ux%u with the app's MediaCodec into %ux%u NV12 dma-bufs",
c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height, v->cap_width, v->cap_height);
return 0;
}
static int vd_open_decoder(struct vdec *v) {
if (vd_open_hardware(v) == 0) return 0;
if (!vd_have_ffmpeg()) return -1;
const char *name = v->fourcc == V4L2_PIX_FMT_HEVC ? "hevc" : "h264";
const void *codec = av.find_decoder_by_name(name);
if (codec == NULL) {
vd_log("FFmpeg has no %s decoder", name);
return -1;
}
v->ctx = av.alloc_context3(codec);
v->packet = av.packet_alloc();
v->frame = av.frame_alloc();
void *options = NULL;
long cores = sysconf(_SC_NPROCESSORS_ONLN);
char threads[8];
snprintf(threads, sizeof threads, "%ld", cores > 4 ? 4L : cores < 1 ? 1L : cores);
av.dict_set(&options, "threads", threads, 0);
av.dict_set(&options, "thread_type", "slice", 0);
av.dict_set(&options, "flags", "+low_delay", 0);
av.dict_set(&options, "flags2", "+fast", 0);
int r = v->ctx && v->packet && v->frame ? av.open2(v->ctx, codec, &options) : -1;
av.dict_free(&options);
if (r < 0) {
vd_log("could not open the %s decoder (%d)", name, r);
vd_close_decoder(v);
return -1;
}
vd_log("decoding %s %ux%u in software into %ux%u NV12 dma-bufs", v->fourcc == V4L2_PIX_FMT_HEVC ? "HEVC" : "H.264",
v->width, v->height, v->cap_width, v->cap_height);
return 0;
}
static void vd_unmap_capture(struct vdec *v) {
for (uint32_t i = 0; i < VDEC_BUFFERS; i++) {
if (v->cap[i].map) munmap(v->cap[i].map, v->cap[i].len);
v->cap[i] = (struct vd_capture){ .fd = -1 };
}
v->cap_count = v->n_cap_queue = v->n_cap_done = 0;
v->last = -1;
}
static void vd_sync(int fd, uint64_t flags) {
struct vd_dma_buf_sync s = { .flags = flags | VD_DMA_BUF_SYNC_WRITE };
ioctl(fd, VD_DMA_BUF_IOCTL_SYNC, &s);
}
static void vd_blank(struct vdec *v, struct vd_capture *c) {
size_t luma = (size_t)v->bpl * v->cap_height;
if (luma + luma / 2 > c->len) return;
vd_sync(c->fd, VD_DMA_BUF_SYNC_START);
memset(c->map, 16, luma);
memset(c->map + luma, 128, luma / 2);
vd_sync(c->fd, VD_DMA_BUF_SYNC_END);
}
static int vd_map_capture(struct vdec *v, uint32_t index, int fd) {
struct stat st;
if (fd < 0 || fstat(fd, &st) != 0) return -EINVAL;
struct vd_capture *c = &v->cap[index];
if (c->map && c->ino == st.st_ino) {
c->fd = fd;
return 0;
}
if (c->map) {
munmap(c->map, c->len);
*c = (struct vd_capture){ .fd = -1 };
if (v->last == (int)index) v->last = -1;
}
off_t len = lseek(fd, 0, SEEK_END);
if (len < (off_t)v->cap_size) return -EINVAL;
void *p = mmap(NULL, (size_t)len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (p == MAP_FAILED) {
vd_log("could not map capture buffer %u: %s", index, strerror(errno));
*c = (struct vd_capture){ .fd = -1 };
return -EINVAL;
}
*c = (struct vd_capture){ .fd = fd, .ino = st.st_ino, .map = p, .len = (size_t)len };
vd_blank(v, c);
if (v->hw) vd_send_capture(v, index);
return 0;
}
static int vd_write_frame(struct vdec *v, struct vd_capture *c) {
uint8_t **data = (uint8_t **)v->frame;
int *linesize = (int *)((uint8_t *)v->frame + 64);
int width = *(int *)((uint8_t *)v->frame + 104), height = *(int *)((uint8_t *)v->frame + 108);
const char *format = av.pix_fmt_name(*(int *)((uint8_t *)v->frame + 116));
if (format == NULL || width <= 0 || height <= 0) return -1;
int nv12 = strcmp(format, "nv12") == 0;
if (!nv12 && strcmp(format, "yuv420p") != 0 && strcmp(format, "yuvj420p") != 0) {
static int warned;
if (!warned++) vd_log("cannot show %s frames", format);
return -1;
}
uint32_t w = (uint32_t)width < v->bpl ? (uint32_t)width : v->bpl;
uint32_t h = (uint32_t)height < v->cap_height ? (uint32_t)height : v->cap_height;
uint8_t *y = c->map, *uv = c->map + (size_t)v->bpl * v->cap_height;
vd_sync(c->fd, VD_DMA_BUF_SYNC_START);
for (uint32_t row = 0; row < h; row++) memcpy(y + (size_t)row * v->bpl, data[0] + (size_t)row * linesize[0], w);
for (uint32_t row = 0; row < (h + 1) / 2; row++) {
uint8_t *dst = uv + (size_t)row * v->bpl;
if (nv12) {
memcpy(dst, data[1] + (size_t)row * linesize[1], w & ~1u);
continue;
}
const uint8_t *u = data[1] + (size_t)row * linesize[1], *vv = data[2] + (size_t)row * linesize[2];
for (uint32_t x = 0; x < w / 2; x++) {
dst[2 * x] = u[x];
dst[2 * x + 1] = vv[x];
}
}
vd_sync(c->fd, VD_DMA_BUF_SYNC_END);
return 0;
}
static void vd_copy_last(struct vdec *v, struct vd_capture *c) {
if (v->last < 0 || v->cap[v->last].map == NULL || &v->cap[v->last] == c) return;
size_t size = v->cap_size < c->len ? v->cap_size : c->len;
vd_sync(c->fd, VD_DMA_BUF_SYNC_START);
memcpy(c->map, v->cap[v->last].map, size);
vd_sync(c->fd, VD_DMA_BUF_SYNC_END);
}
static double vd_now_ms(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6;
}
static void vd_deliver(struct vdec *v, int written, double start, struct timeval timestamp) {
uint32_t target = v->cap_queue[0];
if (!written) {
if (v->last < 0) return;
vd_copy_last(v, &v->cap[target]);
}
double ms = vd_now_ms() - start;
v->frames++;
v->decode_ms += ms;
if (ms > 25.0) v->slow++;
memmove(v->cap_queue, v->cap_queue + 1, --v->n_cap_queue * sizeof v->cap_queue[0]);
v->cap_done[v->n_cap_done++] = (struct vd_done){ .index = target, .timestamp = timestamp };
v->last = (int)target;
}
static void vd_decode_hardware(struct vdec *v, uint32_t index, uint32_t bytes, struct timeval timestamp) {
double start = vd_now_ms();
v->pts += 16667;
struct vdec_packet p = { .type = VDEC_PACKET, .input = index, .bytes = bytes, .capture = v->cap_queue[0], .pts_us = v->pts };
struct vdec_result r;
if (vd_send(v->sock, &p, sizeof p, -1) != 0 || recv(v->sock, &r, sizeof r, 0) != (ssize_t)sizeof r ||
r.type != VDEC_RESULT) {
vd_log("lost the app's decoder (%s), switching to software", strerror(errno));
vd_close_decoder(v);
v->hw_failed = 1;
return;
}
vd_deliver(v, r.status == 0 && r.frame, start, timestamp);
}
static void vd_decode(struct vdec *v, uint32_t index, uint32_t bytes, struct timeval timestamp) {
if (!v->cap_on || v->n_cap_queue == 0) return;
if (v->ctx == NULL && !v->hw && vd_open_decoder(v) != 0) return;
if (v->hw) {
vd_decode_hardware(v, index, bytes, timestamp);
return;
}
if (v->packet_capacity < bytes + VDEC_PADDING) {
free(v->packet_data);
v->packet_capacity = bytes + VDEC_PADDING + (64u << 10);
v->packet_data = malloc(v->packet_capacity);
if (v->packet_data == NULL) {
v->packet_capacity = 0;
return;
}
}
memcpy(v->packet_data, v->bitstream + (size_t)index * VDEC_BITSTREAM_SIZE, bytes);
memset(v->packet_data + bytes, 0, VDEC_PADDING);
*(uint8_t **)((uint8_t *)v->packet + 24) = v->packet_data;
*(int *)((uint8_t *)v->packet + 32) = (int)bytes;
double start = vd_now_ms();
uint32_t target = v->cap_queue[0];
struct vd_capture *c = &v->cap[target];
int written = 0;
if (av.send_packet(v->ctx, v->packet) >= 0) {
while (av.receive_frame(v->ctx, v->frame) >= 0) {
if (vd_write_frame(v, c) == 0) written = 1;
av.frame_unref(v->frame);
}
}
*(uint8_t **)((uint8_t *)v->packet + 24) = NULL;
*(int *)((uint8_t *)v->packet + 32) = 0;
vd_deliver(v, written, start, timestamp);
}
static int is_output(uint32_t type) { return type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE || type == V4L2_BUF_TYPE_VIDEO_OUTPUT; }
static int is_capture(uint32_t type) { return type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE || type == V4L2_BUF_TYPE_VIDEO_CAPTURE; }
static void vd_fill_format(struct vdec *v, struct v4l2_format *f) {
struct v4l2_pix_format_mplane *p = &f->fmt.pix_mp;
memset(p, 0, sizeof *p);
p->field = V4L2_FIELD_NONE;
p->num_planes = 1;
p->colorspace = V4L2_COLORSPACE_REC709;
if (is_output(f->type)) {
p->width = v->width;
p->height = v->height;
p->pixelformat = v->fourcc;
p->plane_fmt[0].sizeimage = VDEC_BITSTREAM_SIZE;
} else {
p->width = v->cap_width;
p->height = v->cap_height;
p->pixelformat = V4L2_PIX_FMT_NV12;
p->plane_fmt[0].bytesperline = v->bpl;
p->plane_fmt[0].sizeimage = v->cap_size;
}
}
static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) {
struct v4l2_pix_format_mplane *p = &f->fmt.pix_mp;
if (f->type != V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE && f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return -EINVAL;
struct vdec t = *v;
if (is_output(f->type)) {
if (p->pixelformat != V4L2_PIX_FMT_H264 && p->pixelformat != V4L2_PIX_FMT_HEVC) return -EINVAL;
t.fourcc = p->pixelformat;
t.width = p->width;
t.height = p->height;
} else {
uint32_t w = p->width > t.width ? p->width : t.width, h = p->height > t.height ? p->height : t.height;
if (w < 16 || h < 16 || w > 8192 || h > 8192) return -EINVAL;
t.cap_width = (w + 15) & ~15u;
t.cap_height = (h + 15) & ~15u;
t.bpl = t.cap_width;
t.cap_size = t.bpl * t.cap_height * 3 / 2;
}
if (apply) {
if (t.fourcc != v->fourcc || (t.hw && (t.bpl != v->bpl || t.cap_height != v->cap_height))) vd_close_decoder(&t);
*v = t;
}
vd_fill_format(&t, f);
return 0;
}
static int vd_reqbufs(struct vdec *v, struct v4l2_requestbuffers *r) {
uint32_t n = r->count > VDEC_BUFFERS ? VDEC_BUFFERS : r->count;
if (r->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE && r->memory == V4L2_MEMORY_MMAP) {
if (v->bitstream) munmap(v->bitstream, (size_t)v->out_count * VDEC_BITSTREAM_SIZE);
v->bitstream = NULL;
v->out_count = v->n_out_done = 0;
if (n && ftruncate(v->fd, (off_t)n * VDEC_BITSTREAM_SIZE) != 0) return -ENOMEM;
if (n) {
void *p = mmap(NULL, (size_t)n * VDEC_BITSTREAM_SIZE, PROT_READ, MAP_SHARED, v->fd, 0);
if (p == MAP_FAILED) return -ENOMEM;
v->bitstream = p;
}
v->out_count = n;
} else if (r->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE && r->memory == V4L2_MEMORY_DMABUF) {
if (v->hw) vd_close_decoder(v);
vd_unmap_capture(v);
v->cap_count = n;
} else {
return -EINVAL;
}
r->count = n;
r->capabilities = r->memory == V4L2_MEMORY_MMAP ? V4L2_BUF_CAP_SUPPORTS_MMAP : V4L2_BUF_CAP_SUPPORTS_DMABUF;
return 0;
}
static int vd_querybuf(struct vdec *v, struct v4l2_buffer *b) {
if (b->type != V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE || b->index >= v->out_count || b->m.planes == NULL || b->length < 1)
return -EINVAL;
b->memory = V4L2_MEMORY_MMAP;
b->flags = V4L2_BUF_FLAG_MAPPED;
b->length = 1;
b->m.planes[0].length = VDEC_BITSTREAM_SIZE;
b->m.planes[0].m.mem_offset = b->index * VDEC_BITSTREAM_SIZE;
return 0;
}
static int vd_qbuf(struct vdec *v, struct v4l2_buffer *b) {
if (b->m.planes == NULL || b->length < 1) return -EINVAL;
if (b->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
if (b->index >= v->out_count || v->n_out_done >= VDEC_BUFFERS) return -EINVAL;
uint32_t bytes = b->m.planes[0].bytesused;
if (bytes > VDEC_BITSTREAM_SIZE) bytes = VDEC_BITSTREAM_SIZE;
if (v->out_on && bytes) vd_decode(v, b->index, bytes, b->timestamp);
v->out_done[v->n_out_done++] = b->index;
} else if (b->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
if (b->index >= v->cap_count || v->cap_size == 0) return -EINVAL;
int r = vd_map_capture(v, b->index, b->m.planes[0].m.fd);
if (r < 0) return r;
for (uint32_t i = 0; i < v->n_cap_queue; i++) if (v->cap_queue[i] == b->index) return 0;
if (v->n_cap_queue >= VDEC_BUFFERS) return -EINVAL;
v->cap_queue[v->n_cap_queue++] = b->index;
} else {
return -EINVAL;
}
b->flags |= V4L2_BUF_FLAG_QUEUED;
return 0;
}
static int vd_dqbuf(struct vdec *v, struct v4l2_buffer *b) {
if (b->m.planes == NULL || b->length < 1) return -EINVAL;
if (b->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
if (v->n_out_done == 0) return -EAGAIN;
b->index = v->out_done[0];
memmove(v->out_done, v->out_done + 1, --v->n_out_done * sizeof v->out_done[0]);
b->memory = V4L2_MEMORY_MMAP;
b->flags = V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_MAPPED;
b->length = 1;
b->m.planes[0].bytesused = 0;
b->m.planes[0].length = VDEC_BITSTREAM_SIZE;
b->m.planes[0].m.mem_offset = b->index * VDEC_BITSTREAM_SIZE;
return 0;
}
if (b->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return -EINVAL;
if (v->n_cap_done == 0) return -EAGAIN;
struct vd_done d = v->cap_done[0];
memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d);
b->index = d.index;
b->memory = V4L2_MEMORY_DMABUF;
b->flags = V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_TIMESTAMP_COPY;
b->field = V4L2_FIELD_NONE;
b->timestamp = d.timestamp;
b->length = 1;
b->m.planes[0].bytesused = v->cap_size;
b->m.planes[0].length = v->cap_size;
b->m.planes[0].m.fd = v->cap[d.index].fd;
return 0;
}
static int vd_ioctl(struct vdec *v, unsigned long req, void *arg) {
switch (req) {
case VIDIOC_QUERYCAP: {
struct v4l2_capability *c = arg;
memset(c, 0, sizeof *c);
strcpy((char *)c->driver, "droiddeck_vdec");
strcpy((char *)c->card, "DroidDeck video decoder");
strcpy((char *)c->bus_info, "platform:droiddeck-vdec");
c->version = 0x00060000;
c->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING;
c->capabilities = c->device_caps | V4L2_CAP_DEVICE_CAPS;
return 0;
}
case VIDIOC_ENUM_FMT: {
struct v4l2_fmtdesc *d = arg;
static const uint32_t coded[] = { V4L2_PIX_FMT_H264, V4L2_PIX_FMT_HEVC };
if (is_capture(d->type) && d->index == 0) {
d->pixelformat = V4L2_PIX_FMT_NV12;
strcpy((char *)d->description, "Y/CbCr 4:2:0");
d->flags = 0;
} else if (is_output(d->type) && d->index < 2) {
d->pixelformat = coded[d->index];
strcpy((char *)d->description, d->index ? "HEVC" : "H.264");
d->flags = V4L2_FMT_FLAG_COMPRESSED;
} else {
return -EINVAL;
}
return 0;
}
case VIDIOC_G_FMT: {
struct v4l2_format *f = arg;
if (!is_output(f->type) && !is_capture(f->type)) return -EINVAL;
vd_fill_format(v, f);
return 0;
}
case VIDIOC_S_FMT: return vd_set_format(v, arg, 1);
case VIDIOC_TRY_FMT: return vd_set_format(v, arg, 0);
case VIDIOC_REQBUFS: return vd_reqbufs(v, arg);
case VIDIOC_QUERYBUF: return vd_querybuf(v, arg);
case VIDIOC_QBUF: return vd_qbuf(v, arg);
case VIDIOC_DQBUF: return vd_dqbuf(v, arg);
case VIDIOC_STREAMON:
case VIDIOC_STREAMOFF: {
uint32_t type = *(uint32_t *)arg;
int on = req == VIDIOC_STREAMON;
if (is_output(type)) {
v->out_on = on;
if (!on) {
v->n_out_done = 0;
if (v->ctx) av.flush_buffers(v->ctx);
}
} else if (is_capture(type)) {
v->cap_on = on;
if (!on) v->n_cap_queue = v->n_cap_done = 0;
} else {
return -EINVAL;
}
if (v->out_on && v->cap_on && v->ctx == NULL && !v->hw && v->out_count && v->cap_size) vd_open_decoder(v);
return 0;
}
case VIDIOC_SUBSCRIBE_EVENT:
case VIDIOC_UNSUBSCRIBE_EVENT:
case VIDIOC_DECODER_CMD:
case VIDIOC_TRY_DECODER_CMD:
return 0;
case VIDIOC_DQEVENT:
return -ENOENT;
default:
vd_log("unhandled ioctl 0x%lx", req);
return -ENOTTY;
}
}
__attribute__((visibility("hidden"))) int bl_vdec_ioctl(int fd, unsigned long req, void *arg, int *rc) {
struct vdec *v = vd_find(fd);
if (v == NULL) return 0;
pthread_mutex_lock(&vd_lock);
int r = arg ? vd_ioctl(v, req, arg) : -EFAULT;
pthread_mutex_unlock(&vd_lock);
if (r < 0) {
errno = -r;
*rc = -1;
} else {
*rc = 0;
}
return 1;
}
__attribute__((visibility("hidden"))) void bl_vdec_closed(int fd) {
struct vdec *v = vd_find(fd);
if (v == NULL) return;
pthread_mutex_lock(&vd_lock);
vd_close_decoder(v);
vd_unmap_capture(v);
if (v->bitstream) munmap(v->bitstream, (size_t)v->out_count * VDEC_BITSTREAM_SIZE);
v->bitstream = NULL;
v->used = 0;
__atomic_sub_fetch(&vd_open_count, 1, __ATOMIC_RELEASE);
pthread_mutex_unlock(&vd_lock);
}
__attribute__((visibility("hidden"))) int bl_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms,
int (*real)(struct pollfd *, nfds_t, int), int *ret) {
if (n != 1 || vd_find(fds[0].fd) == NULL) return 0;
struct vdec *v = vd_find(fds[0].fd);
pthread_mutex_lock(&vd_lock);
short ready = (v->n_cap_done ? POLLIN | POLLRDNORM : 0) | (v->n_out_done ? POLLOUT | POLLWRNORM : 0);
pthread_mutex_unlock(&vd_lock);
fds[0].revents = ready & fds[0].events;
if (fds[0].revents == 0 && timeout_ms != 0) real(NULL, 0, timeout_ms < 0 || timeout_ms > 1000 ? 1000 : timeout_ms);
*ret = fds[0].revents ? 1 : 0;
return 1;
}
static int drm_get_devices2(uint32_t flags, struct vd_device **devices, int max) {
(void)flags;
static char *nodes[3] = { "/dev/null", NULL, NULL };
static struct vd_device device = { .nodes = nodes, .available_nodes = 1 };
if (devices == NULL || max < 1) return 1;
devices[0] = &device;
return 1;
}
static void drm_free_devices(struct vd_device **devices, int count) { (void)devices; (void)count; }
static struct vd_mode_info drm_mode = {
.clock = 148500, .hdisplay = 1920, .hsync_start = 2008, .hsync_end = 2052, .htotal = 2200,
.vdisplay = 1080, .vsync_start = 1084, .vsync_end = 1089, .vtotal = 1125, .vrefresh = 60, .name = "1920x1080",
};
static uint32_t drm_crtc_ids[1] = { 1 }, drm_connector_ids[1] = { 2 }, drm_encoder_ids[1] = { 3 };
static struct vd_res *drm_get_resources(int fd) {
(void)fd;
static struct vd_res res = {
.count_crtcs = 1, .crtcs = drm_crtc_ids, .count_connectors = 1, .connectors = drm_connector_ids,
.count_encoders = 1, .encoders = drm_encoder_ids, .max_width = 8192, .max_height = 8192,
};
return &res;
}
static struct vd_connector *drm_get_connector(int fd, uint32_t id) {
(void)fd;
static struct vd_connector connector = {
.connector_id = 2, .encoder_id = 3, .connector_type = 14, .connection = 1, .count_modes = 1,
.modes = &drm_mode, .count_encoders = 1, .encoders = drm_encoder_ids,
};
return id == 2 ? &connector : NULL;
}
static struct vd_encoder *drm_get_encoder(int fd, uint32_t id) {
(void)fd;
static struct vd_encoder encoder = { .encoder_id = 3, .encoder_type = 8, .crtc_id = 1, .possible_crtcs = 1 };
return id == 3 ? &encoder : NULL;
}
static struct vd_crtc *drm_get_crtc(int fd, uint32_t id) {
(void)fd;
static struct vd_crtc crtc;
if (id != 1) return NULL;
crtc = (struct vd_crtc){ .crtc_id = 1, .width = 1920, .height = 1080, .mode_valid = 1, .mode = drm_mode };
return &crtc;
}
static void drm_free(void *p) { (void)p; }
static void *drm_null(void) { return NULL; }
static int drm_fail(void) { return -EINVAL; }
static int drm_dumb_slot(uint32_t handle) { return handle >= 1 && handle <= VDEC_DUMB ? (int)handle - 1 : -1; }
static int drm_ioctl(int fd, unsigned long request, void *arg) {
(void)fd;
int r = -EINVAL;
pthread_mutex_lock(&vd_lock);
if (request == VD_IOCTL_MODE_CREATE_DUMB && arg) {
struct vd_create_dumb *c = arg;
uint64_t pitch = ((uint64_t)c->width * c->bpp + 7) / 8;
uint64_t size = (pitch * c->height + 4095) & ~4095ull;
int slot = -1;
for (int i = 0; i < VDEC_DUMB && slot < 0; i++) if (vd_dumb_fd[i] < 0) slot = i;
struct vd_dma_heap_alloc a = { .len = size, .fd_flags = O_RDWR | O_CLOEXEC };
if (slot < 0 || size == 0 || size > (512ull << 20)) {
r = -ENOMEM;
} else if (ioctl(vd_heap, VD_DMA_HEAP_IOCTL_ALLOC, &a) != 0) {
r = -errno;
vd_log("dma-heap allocation of %llu bytes failed: %s", (unsigned long long)size, strerror(errno));
} else {
vd_dumb_fd[slot] = (int)a.fd;
c->handle = (uint32_t)slot + 1;
c->pitch = (uint32_t)pitch;
c->size = size;
r = 0;
}
} else if (request == VD_IOCTL_PRIME_HANDLE_TO_FD && arg) {
struct vd_prime_handle *h = arg;
int slot = drm_dumb_slot(h->handle);
int dup_fd = slot >= 0 && vd_dumb_fd[slot] >= 0 ? fcntl(vd_dumb_fd[slot], F_DUPFD_CLOEXEC, 0) : -1;
if (dup_fd >= 0) {
h->fd = dup_fd;
r = 0;
} else {
r = slot >= 0 ? -errno : -ENOENT;
}
} else if (request == VD_IOCTL_MODE_DESTROY_DUMB && arg) {
int slot = drm_dumb_slot(((struct vd_destroy_dumb *)arg)->handle);
if (slot >= 0 && vd_dumb_fd[slot] >= 0) {
close(vd_dumb_fd[slot]);
vd_dumb_fd[slot] = -1;
r = 0;
} else {
r = -ENOENT;
}
}
pthread_mutex_unlock(&vd_lock);
if (r < 0) {
errno = -r;
return -1;
}
return 0;
}
static const struct {
const char *name;
void *fn;
} drm_table[] = {
{ "drmGetDevices2", (void *)drm_get_devices2 },
{ "drmFreeDevices", (void *)drm_free_devices },
{ "drmSetMaster", (void *)drm_fail },
{ "drmSetClientCap", (void *)drm_fail },
{ "drmModeGetResources", (void *)drm_get_resources },
{ "drmModeFreeResources", (void *)drm_free },
{ "drmModeGetConnector", (void *)drm_get_connector },
{ "drmModeFreeConnector", (void *)drm_free },
{ "drmModeGetEncoder", (void *)drm_get_encoder },
{ "drmModeFreeEncoder", (void *)drm_free },
{ "drmModeGetCrtc", (void *)drm_get_crtc },
{ "drmModeSetCrtc", (void *)drm_fail },
{ "drmModeFreeCrtc", (void *)drm_free },
{ "drmModeGetPlaneResources", (void *)drm_null },
{ "drmModeFreePlaneResources", (void *)drm_free },
{ "drmModeGetPlane", (void *)drm_null },
{ "drmModeFreePlane", (void *)drm_free },
{ "drmModeObjectGetProperties", (void *)drm_null },
{ "drmModeFreeObjectProperties", (void *)drm_free },
{ "drmModeGetProperty", (void *)drm_null },
{ "drmModeFreeProperty", (void *)drm_free },
{ "drmModeAddFB2", (void *)drm_fail },
{ "drmModeAddFB2WithModifiers", (void *)drm_fail },
{ "drmModeRmFB", (void *)drm_fail },
{ "drmModeAtomicAlloc", (void *)drm_null },
{ "drmModeAtomicFree", (void *)drm_free },
{ "drmModeAtomicAddProperty", (void *)drm_fail },
{ "drmModeAtomicCommit", (void *)drm_fail },
{ "drmIoctl", (void *)drm_ioctl },
};
void *SDL_LoadObject(const char *name) {
static void *(*real)(const char *);
if (name && strcmp(name, "libdrm.so.2") == 0 && vd_enabled()) return &vd_drm_handle;
if (!real) real = (void *(*)(const char *))dlsym(RTLD_NEXT, "SDL_LoadObject");
return real ? real(name) : NULL;
}
void *SDL_LoadFunction(void *handle, const char *name) {
static void *(*real)(void *, const char *);
if (handle == &vd_drm_handle) {
for (size_t i = 0; name && i < sizeof drm_table / sizeof drm_table[0]; i++)
if (strcmp(drm_table[i].name, name) == 0) return drm_table[i].fn;
return NULL;
}
if (!real) real = (void *(*)(void *, const char *))dlsym(RTLD_NEXT, "SDL_LoadFunction");
return real ? real(handle, name) : NULL;
}
void SDL_UnloadObject(void *handle) {
static void (*real)(void *);
if (handle == &vd_drm_handle) return;
if (!real) real = (void (*)(void *))dlsym(RTLD_NEXT, "SDL_UnloadObject");
if (real) real(handle);
}
#else
__attribute__((visibility("hidden"))) int bl_vdec_open(const char *path, int flags) {
(void)path;
(void)flags;
return -2;
}
__attribute__((visibility("hidden"))) int bl_vdec_ioctl(int fd, unsigned long req, void *arg, int *rc) {
(void)fd;
(void)req;
(void)arg;
(void)rc;
return 0;
}
__attribute__((visibility("hidden"))) void bl_vdec_closed(int fd) { (void)fd; }
__attribute__((visibility("hidden"))) int bl_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms,
int (*real)(struct pollfd *, nfds_t, int), int *ret) {
(void)fds;
(void)n;
(void)timeout_ms;
(void)real;
(void)ret;
return 0;
}
#endif
+5
View File
@@ -625,9 +625,14 @@ static int vn_poll(struct pollfd *fds, nfds_t n, int timeout_ms, int (*real)(str
return r + ready;
}
__attribute__((weak, visibility("hidden"))) int bl_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms,
int (*real)(struct pollfd *, nfds_t, int), int *ret);
int poll(struct pollfd *fds, nfds_t n, int timeout_ms) {
static int (*real)(struct pollfd *, nfds_t, int);
if (!real) real = (int (*)(struct pollfd *, nfds_t, int))dlsym(RTLD_NEXT, "poll");
int ret;
if (bl_vdec_poll && bl_vdec_poll(fds, n, timeout_ms, real, &ret)) return ret;
if (__atomic_load_n(&vn_open_count, __ATOMIC_ACQUIRE) == 0) return real(fds, n, timeout_ms);
return vn_poll(fds, n, timeout_ms, real);
}