Merge upstream PC input and dual-screen updates

This commit is contained in:
Delete228 committed 2026-11-05 00:00:34 +03:00
commit 68b0396dfe
819 files changed
+43953 -6186

No files matched your search

-2
View File
@@ -45,7 +45,6 @@ static void android_volume_set(pa_sink *sink) {
unsigned requested = PA_MIN(pa_cvolume_max(&sink->real_volume), PA_VOLUME_NORM);
level = ((uint64_t)requested * maximum + PA_VOLUME_NORM / 2) / PA_VOLUME_NORM;
pa_cvolume_set(&sink->real_volume, sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum);
/* Android applies media gain to both PulseAudio and DirectAudio streams. */
pa_cvolume_reset(&sink->soft_volume, sink->sample_spec.channels);
android_volume_request(sink, "volume", level);
}
@@ -88,7 +87,6 @@ static void android_volume_refresh(pa_mainloop_api *api, pa_time_event *event, c
pa_xfree(mute_request);
pa_xfree(processing);
pa_xfree(mute_processing);
/* A held volume key steps Android every ~50 ms; sampling at 100 ms hands Steam uneven multi-step jumps. */
unsigned delay_ms = ANDROID_VOLUME_IDLE_MS;
if (bridge->active_ticks) {
bridge->active_ticks--;
+37 -6
View File
@@ -41,11 +41,15 @@ if [[ ! -x "${java_dir}/bin/java" ]]; then
echo "Java 17 not found at ${java_dir}; set JAVA_HOME." >&2
exit 1
fi
if [[ ! -f "${repo_root}/external/MaliBridge/scripts/build-client-linux.sh" ]]; then
echo "external/MaliBridge is empty; run: git submodule update --init" >&2
exit 1
fi
if ! command -v docker >/dev/null 2>&1; then
echo "Docker is required to cross-compile the glibc ARM64 preload libraries." >&2
exit 1
fi
for tool in curl tar zstd shasum unzip python3; do
for tool in curl tar zstd shasum unzip python3 go; do
if ! command -v "${tool}" >/dev/null 2>&1; then
echo "${tool} is required to build the CI-equivalent APK." >&2
exit 1
@@ -86,8 +90,6 @@ trap 'exit 143' TERM
cache_dir=${DROIDDECK_BUILD_CACHE:-"${HOME}/.cache/droiddeck-build"}
mkdir -p "${cache_dir}"
# Steps whose output depends only on tracked sources are kept per input hash in the
# shared cache, so a rerun or a fresh worktree copies them instead of rebuilding.
inputs_hash() {
(cd "${repo_root}" && { printf '%s\n' "$1"; shift; find "$@" -type f ! -name '*.pyc' | LC_ALL=C sort | xargs shasum -a 256; }) \
| shasum -a 256 | cut -d' ' -f1
@@ -105,7 +107,6 @@ save_step() {
part=$(mktemp -d "${stored}.part.XXXXXX")
(cd "$3" && tar -cf - .) | tar -xf - -C "${part}"
touch "${part}/.complete"
# Another checkout may have published the same key meanwhile; its copy is equivalent.
if [[ -e "${stored}" ]]; then rm -rf "${part}"; else mv "${part}" "${stored}" || rm -rf "${part}"; fi
}
@@ -114,9 +115,10 @@ image_id=$(docker image inspect --format '{{.Id}}' "${image_name}")
rm -rf -- "${linuxfs_dir}"
mkdir -p "${linuxfs_dir}"
git_common=$(git -C "${repo_root}" rev-parse --path-format=absolute --git-common-dir)
docker run --rm --platform "${docker_platform}" \
--user "$(id -u):$(id -g)" \
-v "${repo_root}:/src" -w /src "${image_name}" bash -lc '
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src "${image_name}" bash -lc '
set -euo pipefail
d=app/src/main/assets/linuxfs
mkdir -p "$d"
@@ -138,6 +140,7 @@ docker run --rm --platform "${docker_platform}" \
-o "$d/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libssbs.so"
mkdir -p "$d/usr/local/bin"
external/MaliBridge/scripts/build-client-linux.sh "$d" aarch64-linux-gnu-gcc
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$d/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-clipboard"
for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
@@ -161,7 +164,7 @@ x86_key=$(inputs_hash bullseye tools/linuxfs/build-x86-preloads.sh tools/linuxfs
x86_stage="${staging_dir}/x86-preloads"
if restore_step x86-preloads "${x86_key}" "${linuxfs_dir}"; then :; else
docker run --rm --platform linux/amd64 \
-v "${repo_root}:/src" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c '
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c '
set -euo pipefail
printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
apt-get -o Acquire::Check-Valid-Until=false update -qq
@@ -181,6 +184,13 @@ if ! restore_step vr "${vr_key}" "${vr_out}"; then
save_step vr "${vr_key}" "${vr_out}"
fi
gpuload_out="${linuxfs_dir}/usr/local/lib/droiddeck-gpuload"
gpuload_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/gpuload)
if ! restore_step gpuload "${gpuload_key}" "${gpuload_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/gpuload/build.sh" "${gpuload_out}"
save_step gpuload "${gpuload_key}" "${gpuload_out}"
fi
github_repo=${DROIDDECK_GITHUB_REPOSITORY:-}
if [[ -z "${github_repo}" ]]; then
origin_url=$(git -C "${repo_root}" remote get-url origin)
@@ -337,6 +347,27 @@ else
(cd "${proot_out}" && shasum -a 256 libproot.so libproot-loader.so > .proot-outputs)
fi
syncthing_src="${repo_root}/tools/syncthing/syncthing-android/syncthing/src/github.com/syncthing/syncthing"
git -C "${repo_root}" submodule update --init --recursive tools/syncthing/syncthing-android
syncthing_inputs=$(printf '%s\n' "$(cd "${repo_root}" && shasum -a 256 tools/syncthing/build.sh \
tools/syncthing/syncthing-android/gradle/libs.versions.toml)" \
"$(git -C "${syncthing_src}" rev-parse HEAD)" \
"$(git -C "${syncthing_src}" diff --binary HEAD | shasum -a 256)" \
"$(cd "${syncthing_src}" && git ls-files -z --others --exclude-standard | xargs -0 shasum -a 256)" \
"${ndk_version}" | shasum -a 256 | cut -d' ' -f1)
if [[ -f "${proot_out}/libsyncthingnative.so" \
&& "$(cat "${proot_out}/.syncthing-inputs" 2>/dev/null)" = "${syncthing_inputs}" ]]; then
echo "syncthing: sources unchanged, keeping ${proot_out}/libsyncthingnative.so"
else
syncthing_stage="${staging_dir}/syncthing"
if ! restore_step syncthing "${syncthing_inputs}" "${syncthing_stage}"; then
"${repo_root}/tools/syncthing/build.sh" "${syncthing_stage}"
save_step syncthing "${syncthing_inputs}" "${syncthing_stage}"
fi
install -m755 "${syncthing_stage}/libsyncthingnative.so" "${proot_out}/"
echo "${syncthing_inputs}" > "${proot_out}/.syncthing-inputs"
fi
bundle_dir="${staging_dir}/pulseaudio-bundle"
mkdir -p "${bundle_dir}"
zstd -dc "${bundle_asset}" | tar -xf - -C "${bundle_dir}"
-2
View File
@@ -45,8 +45,6 @@ int main(void) {
cardboard_push_constants(&q, pose, 0, 0, 0, 0, pc);
CHECK(isfinite(pc[17]) && isfinite(pc[19]));
// Narrow optical profiles and the lower SteamVR slider values must reach
// the projection unchanged, rather than all becoming a 30-degree view.
const float glasses_fovs[] = {22.0f, 23.3f, 24.0f, 25.8f, 29.0f};
for (unsigned i = 0; i < sizeof(glasses_fovs) / sizeof(glasses_fovs[0]); i++) {
q.fov_deg = glasses_fovs[i];
-1
View File
@@ -156,7 +156,6 @@ def main():
read(0,0,width,height,0x1908,0x1401,actual)
samples = []
for x, y in coords:
# Readback is GL bottom-up; coordinates below are image top-left.
offset = ((height-1-y)*width+x)*4
rgb = list(actual[offset:offset+3])
eye = 0 if mono or x < width/2 else 1
+2 -1
View File
@@ -6,7 +6,8 @@ image=${DROIDDECK_BUILD_IMAGE}
platform=${DROIDDECK_DOCKER_PLATFORM}
rust_cache="${HOME}/.cache/droiddeck-comet-rust${platform#linux/amd64}"
rust_cache=${rust_cache/\/arm64/-arm64}
docker run --rm --platform "$platform" -v "$repo:/src" \
git_common=$(git -C "$repo" rev-parse --path-format=absolute --git-common-dir)
docker run --rm --platform "$platform" -v "$repo:/src" -v "$git_common:$git_common" \
-v "${rust_cache}:/rust" -w /src \
-e CARGO_HOME=/rust/cargo -e RUSTUP_HOME=/rust/rustup "$image" bash -lc '
set -euo pipefail
-2
View File
@@ -1,4 +1,3 @@
"""Reuse reviewed preload snapshots; changed snapshots must prove their main-build origin."""
import argparse
import gzip
import http.client
@@ -147,7 +146,6 @@ def producer_sources(group, commit, root=ROOT):
name = 'arm64-preloads' if group == 'arm64' else 'x86-preloads'
patterns = definitions[name]['source_inputs']
else:
# Older approved builds kept ARM64 commands inline, before the Vulkan/VR build.
if group == 'arm64':
text = run('git', 'show', f'{commit}:.github/workflows/build.yml', root=root).decode()
text = text[text.index(' aarch64-linux-gnu-g++ -shared'):]
+3 -1
View File
@@ -1,4 +1,3 @@
"""One entry point for runtime recipes, cache identities and verified job handoff."""
import argparse
import hashlib
import json
@@ -35,6 +34,9 @@ def identity(name, root=ROOT):
for name_ in sorted(set(paths)):
if '__pycache__' in name_ or name_.endswith(('.pyc', '.md')):
continue
if (root / name_).is_dir():
values[name_] = subprocess.check_output(['git', 'ls-files', '--stage', '--', name_], cwd=root, text=True).split()[1]
continue
content = (root / name_).read_bytes()
if b'\0' not in content:
content = content.replace(b'\r\n', b'\n')
+33 -1
View File
@@ -14,6 +14,7 @@
"tools/msitools",
"tools/pipewire",
"tools/vr",
"tools/gpuload",
"app/src/main/cpp/waylandcomp/generated",
"app/src/main/cpp/waylandcomp/src/headpose_shm.h",
"app/src/main/cpp/waylandcomp/src/spatialpose_shm.h",
@@ -21,7 +22,8 @@
],
"outputs": [
"app/src/main/assets/linuxfs/usr/local/bin/gamescope",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-vr/droiddeck/bin/linuxarm64/driver_droiddeck.so"
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-vr/droiddeck/bin/linuxarm64/driver_droiddeck.so",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so"
],
"ndk": true,
"packages": [
@@ -222,5 +224,35 @@
"cmake",
"xz-utils"
]
},
"vkbridge": {
"script": "tools/components/recipes/vkbridge.sh",
"inputs": [
"external/MaliBridge",
"tools/components/recipes/vkbridge.sh"
],
"outputs": [
"app/src/main/assets/linuxfs/usr/local/lib/vkbridge/libvulkan_droidbridge.so",
"app/src/main/assets/linuxfs/usr/local/share/vkbridge/droidbridge_icd.json",
"app/src/main/assets/linuxfs/usr/local/bin/droiddeck-vkbridge-smoke"
],
"packages": [
"gcc-aarch64-linux-gnu"
]
},
"dirt-ws2": {
"script": "tools/components/recipes/dirt-ws2.sh",
"inputs": [
"tools/dirt-ws2",
"tools/components/recipes/dirt-ws2.sh"
],
"outputs": [
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-dirt/ws2_32.dll"
],
"packages": [
"clang",
"lld",
"llvm"
]
}
}
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
set -euo pipefail
bash tools/dirt-ws2/build.sh app/src/main/assets/linuxfs/usr/local/lib/droiddeck-dirt
+2
View File
@@ -4,6 +4,8 @@ D=app/src/main/assets/linuxfs
mkdir -p "$D"
VK_INCLUDE=$(ls -d "${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"/toolchains/llvm/prebuilt/*/sysroot/usr/include | head -1) \
tools/vr/build.sh --native "$D/usr/local/lib/droiddeck-vr"
VK_INCLUDE=$(ls -d "${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"/toolchains/llvm/prebuilt/*/sysroot/usr/include | head -1) \
tools/gpuload/build.sh --native "$D/usr/local/lib/droiddeck-gpuload"
for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
install -Dm644 "$script" "$D/usr/local/bin/$(basename "$script")"
done
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
test -f external/MaliBridge/scripts/build-client-linux.sh
bash external/MaliBridge/scripts/build-client-linux.sh app/src/main/assets/linuxfs aarch64-linux-gnu-gcc
-6
View File
@@ -63,7 +63,6 @@ def graft_targets():
def changed_paths(donor_commit):
"""Return {path: status} for the checkout, uncommitted and untracked files included."""
changes = {}
fields = git('diff', '--name-status', '-z', '--no-renames', donor_commit).decode().split('\0')
for status, path in zip(fields[0::2], fields[1::2]):
@@ -74,7 +73,6 @@ def changed_paths(donor_commit):
def classify(changes, targets, donor_entries):
"""Split changes into grafts {path: asset}, ignored paths and blockers {path: reason}."""
grafts, ignored, blocked = {}, [], {}
for path, status in sorted(changes.items()):
if is_ignored(path):
@@ -96,7 +94,6 @@ def helper_bytes(path):
def graft(donor, replacements, output):
"""Copy the donor with entries replaced, dropping its signature so it can be re-signed."""
with ZipFile(donor) as source, ZipFile(output, 'w') as target:
for info in source.infolist():
name = info.filename
@@ -200,7 +197,6 @@ def pwsh():
def signing_env():
"""The .signing.env build_local.sh uses: the override, else the checkout's own, else the main checkout's."""
common = Path(git('rev-parse', '--path-format=absolute', '--git-common-dir').decode().strip())
for candidate in (os.environ.get('DROIDDECK_SIGNING_ENV'), ROOT / '.signing.env', common.parent / '.signing.env'):
if candidate and Path(candidate).is_file():
@@ -218,7 +214,6 @@ def sign_with_env(env_file, unsigned, signed):
build_tools = sorted(complete, key=version_key, reverse=True)
if not build_tools:
raise Refused('no build-tools with aapt, zipalign and apksigner under ' + str(sdk_root() / 'build-tools'))
# BUILD_TOOLS is assigned after the env file is sourced so the file cannot replace the chosen SDK.
script = 'set -a; cd "$(dirname "$1")"; . "$1"; set +a; BUILD_TOOLS="$5" exec "$2" "$3" standard "$4"'
result = subprocess.run(['bash', '-c', script, 'sign', str(env_file), str(ROOT / 'tools/release/sign-apk.sh'),
str(unsigned), str(signed), str(build_tools[0].parent.resolve())],
@@ -230,7 +225,6 @@ def sign_with_env(env_file, unsigned, signed):
def sign(unsigned, signed):
if not SIGNER.is_file() and (env_file := signing_env()):
return sign_with_env(env_file, unsigned, signed)
# Microsoft Store Python virtualizes AppData for child processes too and hides the signer; use a python.org install.
def quoted(value):
return "'" + str(value).replace("'", "''") + "'"
command = (f"if (-not (Test-Path -LiteralPath {quoted(SIGNER)})) {{ Write-Error 'Local signer not found'; exit 1 }}; "
-8
View File
@@ -1,11 +1,4 @@
#!/usr/bin/env python3
"""The packages the KDE desktop package ships: the dependency closure of the seeds over Arch Linux
ARM's extracted repository databases, minus what the runtime already has at a version that serves.
closure.py <db dir with x_core, x_extra, x_alarm> <runtime-packages.txt> <seeds.txt>
Prints one "repo/filename sha256" per package to ship (the sha256 the repository database gives).
"""
import collections
import os
import re
@@ -107,7 +100,6 @@ def main():
providers[pname].append((name, pver or pkgs[name]["version"]))
def resolve(dep):
"""The package to take for a dependency string, and whether the runtime's copy serves."""
name, op, want = parse_dep(dep)
if name in runtime and satisfies(runtime[name], op, want):
return name, True
@@ -1,13 +1,12 @@
--- a/src/backends/wayland/wayland_backend.cpp
+++ b/src/backends/wayland/wayland_backend.cpp
@@ -455,6 +455,20 @@
@@ -455,6 +455,19 @@
if (WaylandClient::LinuxDmabufV1 *dmabuf = m_display->linuxDmabuf()) {
m_renderDevice = GpuManager::self()->compatibleRenderDevice(dmabuf->mainDevice());
+ if (!m_renderDevice && qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) {
+ const auto nodes = GpuManager::splitPathList(qEnvironmentVariable("KWIN_RENDER_NODES"));
+ const auto &devices = GpuManager::self()->renderDevices();
+ // Android's KGSL host cannot name a DRM device in its dmabuf feedback.
+ if (nodes.size() == 1) {
+ for (const auto &device : devices) {
+ if (device->path() == nodes.constFirst()) {
-11
View File
@@ -1,15 +1,4 @@
#!/usr/bin/env python3
"""Generate removal inventories from checksum-pinned published archives.
Usage: removal-manifests.py <LXQt tar.zst> <KDE r1 tar.zst> <KDE r2 tar.zst>
<emulators tar.zst> <verified KDE package cache> <output dir>
<verified LXQt package cache>
removal-manifests.py --add <KDE tar.zst> <tag> <sha256> <verified KDE package cache> <output dir>
Removal includes desktop applications/themes and our overlay, not their shared dependencies.
The KDE cache is verified against the published desktop-kde.packages.txt before use.
The LXQt cache contains the signed application packages listed by desktop.packages.txt;
verify their Arch Linux ARM Build System signatures before generating the inventory.
"""
import gzip
import hashlib
import json
+28 -24
View File
@@ -1,26 +1,31 @@
#!/usr/bin/env bash
# Smoke test of a DroidDeck build on a real device, over plain adb (no python, no root).
#
# What it does, in order, and restores afterwards:
# 1. prints the device (model, Android, kernel, page size, SoC);
# 2. installs --apk when given and launches the app;
# 3. checks that the app starts and that nothing in the crash buffer belongs to it;
# 4. changes the display density and the window size and checks the app keeps its process
# (and does not recreate the activity that is on top);
# 5. on a foldable cycles the device state (half-opened, and with --closed also closed) through
# `cmd device_state`, then puts the original state back;
# 6. reads the newest session folder of a debug build: first frame, last frame rate, the
# memory page size, the proot that session ran, and the last process exits.
#
# Usage: tools/device-smoke.sh [--serial SERIAL] [--apk FILE] [--pkg PACKAGE]
# [--no-density] [--no-size] [--no-fold] [--closed]
# Exit status: 0 when no check failed, 1 when one did, 2 for a usage or device problem.
#
# Not a replacement for tools/droiddeck-scenario, which drives a game through the agent bridge;
# this covers what that does not: display changes and foldable states.
set -u
export MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*'
usage() {
cat <<'EOF'
Smoke test of a DroidDeck build on a real device, over plain adb (no python, no root).
What it does, in order, and restores afterwards:
1. prints the device (model, Android, kernel, page size, SoC);
2. installs --apk when given and launches the app;
3. checks that the app starts and that nothing in the crash buffer belongs to it;
4. changes the display density and the window size and checks the app keeps its process
(and does not recreate the activity that is on top);
5. on a foldable cycles the device state (half-opened, and with --closed also closed) through
`cmd device_state`, then puts the original state back;
6. reads the newest session folder of a debug build: first frame, last frame rate, the
memory page size, the proot that session ran, and the last process exits.
Usage: tools/device-smoke.sh [--serial SERIAL] [--apk FILE] [--pkg PACKAGE]
[--no-density] [--no-size] [--no-fold] [--closed]
Exit status: 0 when no check failed, 1 when one did, 2 for a usage or device problem.
Not a replacement for tools/droiddeck-scenario, which drives a game through the agent bridge;
this covers what that does not: display changes and foldable states.
EOF
}
pkg=com.droiddeck.launcher
serial=${ANDROID_SERIAL:-}
apk=
@@ -39,7 +44,7 @@ while [ $# -gt 0 ]; do
--no-size) do_size=0 ;;
--no-fold) do_fold=0 ;;
--closed) do_closed=1 ;;
-h|--help) sed -n '2,22p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
-h|--help) usage; exit 0 ;;
*) echo "unknown option: $1" >&2; exit 2 ;;
esac
shift
@@ -96,7 +101,6 @@ restore_size() {
echo "$current" | grep -q 'Physical size:' || return 1
[ "$(echo "$current" | wm_override size)" = "$override_size" ]
}
# An override that was already in place (a test lab pins one) is put back; otherwise the request is cancelled.
restore_fold() { if [ -n "$pre_override" ]; then sh_ cmd device_state state "$pre_override" >/dev/null; else sh_ cmd device_state state reset >/dev/null; fi; }
restore() {
@@ -133,7 +137,7 @@ app_crashes() {
pat=$(printf '%s' "$pkg" | sed 's/[.[\*^$]/\\&/g')
printf '%s\n' "$out" | grep -c -E "(Process: |Cmdline: |>>> )$pat([ ,<:]|$)" || true
}
relaunches_of() { # $1 = activity class fragment
relaunches_of() {
sh_ logcat -b events -d 2>/dev/null | grep -E 'wm_(relaunch|destroy|create)_activity' | grep -c "$1"
}
@@ -214,7 +218,7 @@ if [ "$do_size" = 1 ]; then
phys=$(echo "$size_snapshot" | sed -n 's/.*Physical size: \([0-9]*\)x\([0-9]*\).*/\1 \2/p' | head -1)
set -- $phys
if [ -n "${1:-}" ]; then
w=$(( ($2 * 2 / 3) / 2 * 2 )); h=$1 # a narrower, taller window, like a cover screen
w=$(( ($2 * 2 / 3) / 2 * 2 )); h=$1
pid0=$(app_pid)
size_changed=1
wm_status=0
@@ -250,7 +254,7 @@ if [ "$do_fold" = 1 ]; then
else
id_of() { echo "$states" | sed -n "s/.*identifier=\([0-9]*\), name='$1'.*/\1/p" | head -1; }
half=$(id_of HALF_OPENED); closed=$(id_of CLOSED)
cycle() { # $1 name $2 id
cycle() {
pid0=$(app_pid)
fold_changed=1
sh_ cmd device_state state "$2" >/dev/null; sleep 8
+43 -114
View File
@@ -1,49 +1,10 @@
/* DirectAudio relay - the contract between the driver and the relay helper.
*
/*
* Copyright 2026 The412Banner
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* WHY THIS EXISTS. The driver's whole premise is an in-process AAudio client:
* the guest's WASAPI buffers are mixed and handed to Android's audio server
* from inside the game, no daemon in the path. That is only possible when the
* game process is a bionic process. Under a glibc runtime (the Linux Steam
* client, where the game runs inside a proot'd Arch rootfs on Valve's own
* ARM64 Proton) libaaudio cannot be loaded at all: it is a bionic library and
* the rootfs's dynamic linker does not know how to bring it into a glibc
* process. The game side therefore has to stop at a boundary it CAN cross, and
* the only thing both worlds agree on is the kernel: a unix socket, a memfd and
* a futex word.
*
* SHAPE. One helper process (directaudio-relay, bionic, links libaaudio) runs
* on the Android side and listens on a unix socket. Each game process that
* needs audio connects once, sends its launch config (the same knobs the
* in-process build reads from BANNER_AUDIO_DIRECT_*), and gets back one or two
* shared rings (memfds passed with SCM_RIGHTS):
*
* render ring game (producer) -> helper (consumer) -> AAudio OUTPUT
* capture ring helper (producer, AAudio INPUT) -> game (consumer)
*
* The driver keeps its mixer and its per-voice WASAPI rings exactly as in the
* in-process build; what used to be the AAudio data callback is now a pump
* thread that keeps the render ring topped up, and the capture callback is a
* pump that drains the capture ring into the capture voices. Everything that
* needs an AAudioStream (open, adaptive buffer growth and decay, route-change
* reopen, the stalled-callback watchdog, the live-config mailbox) moves to the
* helper unchanged in spirit.
*
* COST. One extra hand-off: the ring. The helper's callback pulls a burst from
* the ring, so the ring must hold at least one burst at every callback; the
* driver keeps DA_RING_TARGET_BURSTS bursts queued and the helper raises that
* target when a callback finds the ring short. Everything else - the AAudio
* buffer, AudioFlinger's own latency - is what the in-process build pays too.
*
* WIRE FORMAT. Fixed-width, native-endian, same-machine only. The two sides are
* different libcs but the same CPU, so no marshalling beyond fixed-size structs.
* Bump DA_RELAY_VERSION on any layout change; the helper refuses a mismatch.
*/
#ifndef DA_RELAY_PROTO_H
#define DA_RELAY_PROTO_H
@@ -52,34 +13,20 @@
#include <stddef.h>
#define DA_RELAY_VERSION 1
#define DA_RING_MAGIC 0x44415247u /* 'DARG' */
#define DA_HELLO_MAGIC 0x44414831u /* 'DAH1' */
#define DA_ACK_MAGIC 0x44414131u /* 'DAA1' */
#define DA_RING_MAGIC 0x44415247u
#define DA_HELLO_MAGIC 0x44414831u
#define DA_ACK_MAGIC 0x44414131u
/* Socket path. The driver reads BANNER_AUDIO_DIRECT_RELAY; when unset it falls
* back to $XDG_RUNTIME_DIR/DA_RELAY_DEFAULT_NAME, which a host that already
* hands its runtime dir into the session gets for free. */
#define DA_RELAY_ENV "BANNER_AUDIO_DIRECT_RELAY"
#define DA_RELAY_DEFAULT_NAME "directaudio-relay"
/* Both rings carry float32 interleaved stereo. The render ring is always
* 48 kHz (the mixer's output rate); the capture ring runs at whatever rate the
* input stream was granted, published in da_ring.rate, and the driver resamples
* per voice as the in-process build already does. */
#define DA_RING_RATE 48000
#define DA_RING_CHANNELS 2
/* Render ring sizing. Capacity is the ceiling adaptive growth can reach; the
* initial target is what the driver keeps queued. Two bursts: the helper's
* callback consumes one burst and wakes the pump, which then has a full burst
* period to refill before the next callback. */
#define DA_RING_CAP_MS 250
#define DA_RING_TARGET_BURSTS 2
#define DA_RING_MAX_TARGET_MS 100
/* Capture ring: 200 ms is far more than a game ever leaves queued; on overrun
* the helper drops the newest block, matching the in-process "guest is not
* draining" behaviour of dropping data rather than blocking the mic thread. */
#define DA_CAPTURE_RING_MS 200
enum da_ring_state
@@ -93,35 +40,27 @@ struct da_ring
{
uint32_t magic;
uint32_t version;
uint32_t cap_frames; /* ring capacity in frames */
uint32_t rate; /* frames per second of the data in this ring */
uint32_t channels; /* DA_RING_CHANNELS */
uint32_t cap_frames;
uint32_t rate;
uint32_t channels;
uint32_t _pad0;
/* Single producer, single consumer; monotonic frame totals, wrap-safe with
* unsigned arithmetic. Producer writes widx with RELEASE after the data;
* consumer writes ridx with RELEASE after it has copied the data out. */
volatile uint32_t widx;
volatile uint32_t ridx;
/* Futex word the CONSUMER of a render ring / PRODUCER of a capture ring
* bumps after each block, so the other side can sleep on it instead of
* polling. Waiters always use a timeout, so a missed wake only costs one
* period. */
volatile uint32_t wake;
volatile uint32_t quit; /* either side: tear down */
volatile uint32_t state; /* enum da_ring_state, helper-owned */
volatile uint32_t quit;
volatile uint32_t state;
/* Render ring only, helper-owned, read by the driver: */
volatile int32_t target_frames; /* keep at least this many queued */
volatile int32_t hw_buf_frames; /* AAudio buffer size right now (get_latency) */
volatile int32_t hw_burst; /* frames per burst of the output stream */
volatile uint32_t underruns; /* callbacks that found fewer than they needed */
volatile uint32_t cb_count; /* data callbacks so far (liveness) */
volatile int32_t target_frames;
volatile int32_t hw_buf_frames;
volatile int32_t hw_burst;
volatile uint32_t underruns;
volatile uint32_t cb_count;
uint32_t _pad1[3];
float data[]; /* cap_frames * channels */
float data[];
};
static inline size_t da_ring_bytes(uint32_t cap_frames)
@@ -141,62 +80,52 @@ static inline uint32_t da_ring_space(const struct da_ring *r)
return r->cap_frames - da_ring_avail(r);
}
/* ---- wire messages ------------------------------------------------------- */
#define DA_HELLO_MIC 0x01u /* also open an INPUT stream + capture ring */
#define DA_HELLO_EXCLUSIVE 0x02u /* AAUDIO_SHARING_MODE_EXCLUSIVE requested */
#define DA_HELLO_MIC 0x01u
#define DA_HELLO_EXCLUSIVE 0x02u
#define DA_HELLO_ADAPTIVE 0x04u
#define DA_HELLO_DECAY 0x08u
#define DA_HELLO_WATCHDOG 0x10u
/* First message on a fresh connection, driver -> helper. Mirrors the launch
* config the in-process build derives from BANNER_AUDIO_DIRECT_* so a preset
* means the same thing under both runtimes. */
struct da_hello
{
uint32_t magic; /* DA_HELLO_MAGIC */
uint32_t version; /* DA_RELAY_VERSION */
uint32_t flags; /* DA_HELLO_* */
int32_t perf; /* 0 NONE, 1 LOW_LATENCY, 2 POWER_SAVING (host convention) */
int32_t target_ms; /* AAudio buffer, ms; 0 = use target_frames or the default */
int32_t max_ms; /* adaptive ceiling, ms; 0 = max_frames or the default */
int32_t target_frames; /* frame forms, used only when the ms forms are 0 */
uint32_t magic;
uint32_t version;
uint32_t flags;
int32_t perf;
int32_t target_ms;
int32_t max_ms;
int32_t target_frames;
int32_t max_frames;
uint32_t stall_ms; /* watchdog: callback silent this long => rebuild */
uint32_t quiet_ms; /* decay pacing, see the driver */
uint32_t stall_ms;
uint32_t quiet_ms;
uint32_t punish_ms;
uint32_t max_backoff;
int32_t pid; /* the game process, for the log */
uint32_t log; /* BANNER_AUDIO_DIRECT_LOG */
char runtime_path[256]; /* BANNER_AUDIO_DIRECT_RUNTIME mailbox, "" = none */
char name[64]; /* process name, for the log */
int32_t pid;
uint32_t log;
char runtime_path[256];
char name[64];
};
#define DA_ACK_MIC_FAILED 0x01u /* mic asked for, input stream would not open */
#define DA_ACK_MIC_FAILED 0x01u
/* Reply, helper -> driver, followed by SCM_RIGHTS carrying the ring fds:
* fd[0] = render ring, fd[1] = capture ring (present iff in_cap_frames > 0). */
struct da_ack
{
uint32_t magic; /* DA_ACK_MAGIC */
int32_t status; /* 0 = ok, else an AAudio error code (negative) */
int32_t rate; /* output stream rate (48000) */
int32_t burst; /* output frames per burst */
int32_t buf_frames; /* output buffer size as opened */
int32_t out_cap_frames; /* render ring capacity */
int32_t in_cap_frames; /* capture ring capacity, 0 = no capture ring */
int32_t in_rate; /* rate of the capture ring's data */
uint32_t flags; /* DA_ACK_* */
uint32_t magic;
int32_t status;
int32_t rate;
int32_t burst;
int32_t buf_frames;
int32_t out_cap_frames;
int32_t in_cap_frames;
int32_t in_rate;
uint32_t flags;
uint32_t _pad;
};
/* Subsequent messages, driver -> helper, on the same socket. The helper never
* writes after the ack; everything it has to say is in the ring header. EOF on
* the socket is how the helper learns the game is gone. */
enum da_msg_type
{
DA_MSG_MIC_START = 1, /* first capture voice started: make the mic hot */
DA_MSG_MIC_STOP = 2, /* last capture voice gone: stop (keep open) */
DA_MSG_MIC_START = 1,
DA_MSG_MIC_STOP = 2,
DA_MSG_PING = 3,
};
@@ -206,4 +135,4 @@ struct da_msg
int32_t arg;
};
#endif /* DA_RELAY_PROTO_H */
#endif
@@ -1,24 +1,5 @@
/*
* module-directaudio-native-sink: a PulseAudio 13 sink that is DirectAudio's AAudio engine,
* in-process. For the native Linux Steam client on Android (DroidDeck, Bannerlator's Linux
* session), whose sound can only ever reach a PulseAudio daemon: this module is where that
* daemon's mixed output meets Android, one step away from AudioFlinger, with the same engine the
* game driver has - adaptive device buffer that grows a burst on every xrun, optional decay with a
* remembered floor, a primed ring with fades instead of clicks, route-change / error reopen on a
* fresh stream, and a stall watchdog.
*
* It is the relay helper's per-client OUTPUT engine (directaudio-relay.c) with the socket and the
* shared-memory ring replaced by a ring in this process, fed by the sink's IO thread exactly as
* module-directaudio-sink feeds the relay. Compared with that module there is no second process
* and no 40 ms proot safety margin: the ring here only has to cover the IO thread's own
* scheduling jitter, so it starts at two bursts and grows only if a callback finds it short.
*
* The daemon must run on the Android side (the host app's process), not inside proot, for AAudio
* to be reachable at all - which is where both host apps already run it.
*
* Field fixes carried from the relay (MaxsTechReview, Droid-Deck/DroidDeck#338): prime before
* playing, fade on an underrun, one consumer per ring across a reopen, a device buffer of at
* least two bursts.
* Derived from the AAudio engine of DirectAudio's relay helper (directaudio-relay.c) by The412Banner.
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
@@ -52,7 +33,7 @@
#include <pulsecore/thread-mq.h>
#include <pulsecore/thread.h>
#include "da_relay_proto.h" /* struct da_ring + the ring helpers; nothing of the socket protocol */
#include "da_relay_proto.h"
PA_MODULE_AUTHOR("The412Banner");
PA_MODULE_DESCRIPTION("Android audio output: DirectAudio's AAudio engine, in-process");
@@ -77,7 +58,6 @@ PA_MODULE_USAGE(
#define WATCHDOG_TICK_USEC (1 * PA_USEC_PER_SEC)
#define AUDIO_NICE (-16)
/* ---- tunables: the in-process driver's, same defaults ----------------------- */
#define DA_KNEE 0.75f
#define DA_DEFAULT_MS 12
#define DA_DEFAULT_MAX_MS 100
@@ -112,17 +92,14 @@ struct userdata {
pa_sample_spec ss;
size_t frame_size;
/* configuration */
aaudio_performance_mode_t perf;
int32_t target_ms, max_ms, ring_ms;
bool adaptive, decay, limiter, watchdog_on;
/* the ring: this process's, same layout as the relay's so the engine is shared */
struct da_ring *ring;
int32_t burst;
int32_t ring_max_target;
/* the one OUTPUT stream and its adaptive state (the relay's struct client, minus the socket) */
AAudioStream *aq;
pthread_mutex_t lock;
int32_t last_xrun;
@@ -134,7 +111,6 @@ struct userdata {
int suspended;
volatile int dead;
/* what the IO thread last logged, so engine changes made on the AAudio thread get a line */
int32_t seen_target, seen_hw_buf;
uint32_t seen_underruns;
pa_usec_t next_watchdog, settled_at, stats_at;
@@ -152,8 +128,6 @@ static uint64_t now_ns(void) {
static void request_reopen(struct userdata *u, const char *why);
/* ---- the engine: the relay's out_cb / open_output / reopen / watchdog, on a local ring ---- */
static void fade(float *p, uint32_t frames, int in) {
uint32_t i, ch;
@@ -165,8 +139,6 @@ static void fade(float *p, uint32_t frames, int in) {
}
}
/* The driver's soft-knee limiter: below DA_KNEE the signal is untouched, so ordinary material is
* bit-identical; above it a smooth knee folds the overshoot back under full scale. */
static void limit(float *p, uint32_t samples) {
uint32_t i;
@@ -193,7 +165,6 @@ static aaudio_data_callback_result_t out_cb(AAudioStream *aq, void *user, void *
int fade_in = 0, short_read = 0, starving = 0;
uint64_t now;
/* Only the promoted stream reads the ring; an outgoing one during a reopen plays silence. */
if ((live && aq != live) || __atomic_exchange_n(&u->consuming, 1, __ATOMIC_ACQUIRE)) {
memset(out, 0, (size_t) frames * DA_RING_CHANNELS * sizeof(float));
return AAUDIO_CALLBACK_RESULT_CONTINUE;
@@ -248,8 +219,6 @@ static aaudio_data_callback_result_t out_cb(AAudioStream *aq, void *user, void *
__atomic_add_fetch(&u->cb_count, 1, __ATOMIC_SEQ_CST);
__atomic_store_n(&r->cb_count, u->cb_count, __ATOMIC_RELAXED);
/* The ring's own adaptive step: a short ring means the IO thread did not get scheduled in
* time - an xrun one stage earlier - so keep one more burst queued. Only grows. */
if (short_read)
__atomic_add_fetch(&r->underruns, 1, __ATOMIC_RELAXED);
if ((short_read || starving) && u->adaptive) {
@@ -262,8 +231,6 @@ static aaudio_data_callback_result_t out_cb(AAudioStream *aq, void *user, void *
__atomic_store_n(&r->target_frames, want, __ATOMIC_RELEASE);
}
/* The device buffer: grow a burst per xrun; decay a burst after a quiet spell, never below
* the floor a punished decay taught us. */
if (u->adaptive) {
int32_t xruns = AAudioStream_getXRunCount(aq);
int32_t burst = AAudioStream_getFramesPerBurst(aq);
@@ -312,8 +279,6 @@ static void out_error_cb(AAudioStream *aq, void *user, aaudio_result_t error) {
if (aq != __atomic_load_n(&u->aq, __ATOMIC_SEQ_CST)) return;
if (__atomic_load_n(&u->suspended, __ATOMIC_SEQ_CST)) return;
/* A disconnected stream (headphones plugged or unplugged, a Bluetooth route coming or going)
* can never be restarted: it has to be closed and a new one opened on the current route. */
if (error != AAUDIO_ERROR_DISCONNECTED &&
error != AAUDIO_ERROR_INVALID_STATE &&
error != AAUDIO_ERROR_INVALID_HANDLE &&
@@ -322,8 +287,6 @@ static void out_error_cb(AAudioStream *aq, void *user, aaudio_result_t error) {
request_reopen(u, "stream error");
}
/* 48 kHz / float / stereo, buffer from the ms form rounded up to a burst and never below two,
* capacity from the ceiling. The ring target floor is two bursts or ring_ms, whichever is more. */
static aaudio_result_t open_output(struct userdata *u, AAudioStream **out) {
AAudioStreamBuilder *builder = NULL;
AAudioStream *aq = NULL;
@@ -446,7 +409,6 @@ static void request_reopen(struct userdata *u, const char *why) {
}
}
/* Ticked once a second from the IO thread: a callback silent for a second is a dead stream. */
static void watchdog(struct userdata *u) {
uint64_t now = now_ns(), last_cb, prev_tick;
unsigned int cb;
@@ -484,13 +446,10 @@ static void close_output(struct userdata *u) {
AAudioStream_requestStop(aq);
AAudioStream_close(aq);
}
/* A reopen still in flight sees u->dead and stops; give it a moment to let go of u. */
while (__atomic_load_n(&u->reopen_running, __ATOMIC_SEQ_CST))
usleep(10000);
}
/* ---- the PulseAudio side: module-directaudio-sink's producer, on the local ring ---- */
static pa_usec_t frames_to_usec(const struct userdata *u, int64_t frames) {
return (pa_usec_t) (frames * (int64_t) PA_USEC_PER_SEC / (int64_t) u->ss.rate);
}
@@ -528,7 +487,6 @@ static void produce(struct userdata *u, uint32_t frames) {
__atomic_store_n(&r->widx, w + frames, __ATOMIC_RELEASE);
}
/* Tops the ring up to the engine's target and narrates what the engine changed. */
static void service_ring(struct userdata *u) {
struct da_ring *r = u->ring;
uint32_t avail, space;
@@ -587,8 +545,6 @@ static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offse
return pa_sink_process_msg(o, code, data, offset, chunk);
}
/* A started AAudio stream keeps audioserver's AudioMix wake lock held, so the device never
* suspends while the session sleeps: stop it, and the IO thread's timer, until the sink reopens. */
static int sink_set_state_in_io_thread_cb(pa_sink *s, pa_sink_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
struct userdata *u = s->userdata;
aaudio_result_t res = AAUDIO_OK;
@@ -629,9 +585,6 @@ static void thread_func(void *userdata) {
for (;;) {
int ret;
/* Half a burst between visits, never blocking on the stream: clients' audio reaches this
* thread as messages pa_rtpoll_run handles, and a thread stuck in a write or a wait lets
* them run dry (the crackle #338 fixed). */
if (!u->suspended) {
service_ring(u);
pa_rtpoll_set_timer_relative(u->rtpoll, PA_MAX(frames_to_usec(u, u->burst) / 2, PA_USEC_PER_MSEC));
@@ -719,7 +672,6 @@ int pa__init(pa_module *m) {
pthread_mutex_init(&u->lock, NULL);
pa_channel_map_init_stereo(&map);
/* The ring: the relay's layout in this process's memory. */
cap_frames = DA_RING_CAP_MS_LOCAL * DA_RING_RATE / 1000;
u->ring = pa_xmalloc0(da_ring_bytes(cap_frames));
u->ring->magic = DA_RING_MAGIC;
@@ -774,8 +726,6 @@ int pa__init(pa_module *m) {
pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
pa_sink_set_rtpoll(u->sink, u->rtpoll);
pa_sink_set_max_request(u->sink, (size_t) u->ring->target_frames * u->frame_size);
/* What clients should keep queued on their side: the ring's starting target plus the device
* buffer. Grows are reported live through GET_LATENCY. */
pa_sink_set_fixed_latency(u->sink, frames_to_usec(u, (int64_t) u->ring->target_frames + u->base_buf_frames));
if (!(u->thread = pa_thread_new("directaudio-native-sink", thread_func, u))) {
+19
View File
@@ -0,0 +1,19 @@
# DiRT 3 / DiRT Showdown ws2_32 stand-in
DiRT 3 (`dirt3_game.exe`) and DiRT Showdown (`showdown.exe`, `showdown_avx.exe`) close their motion telemetry UDP
socket at the end of a race, and when leaving Joyride, but keep calling `sendto()` on it. `sendto()` fails with
WSAENOTSOCK and the game stops with "sendto failed with error 10038". The same happens on Windows.
`ws2_32.dll` here is a 32-bit stand-in: every export jumps to the same-ordinal export of Wine's own `ws2_32.dll`;
only a `sendto()` that fails with 10038 reports 0 bytes sent instead. Same behaviour as
[DiRTTelemetryErrorFix](https://github.com/RoccoC/DiRTTelemetryErrorFix) by RoccoC (MIT), based on the original fix
by Carsten Gottschling.
Wine loads `ws2_32` as a KnownDLL, so a copy beside the game is ignored. `droiddeck-game-env` puts the stand-in in
place of the prefix's `syswow64/ws2_32.dll` for these games while their telemetry output is on, adds
`WINEDLLOVERRIDES=ws2_32=n,b`, and puts Wine's file back when the game exits. It skips the swap when the game's
Proton already has the fix in its own `ws2_32.dll` (DroidDeck-Proton patch
`dirt-telemetry-sendto-closed-socket.patch`).
`build.sh OUT` builds it with clang, lld and llvm-dlltool and checks its exports against `ws2_32-exports.txt`
(taken from Wine 11's `ws2_32.dll`).
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
mkdir -p "$1"
out=$(cd "$1" && pwd)
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
tool() {
local found
found=$(command -v "$1" || ls /usr/lib/llvm-*/bin/"$1" 2>/dev/null | sort -V | tail -n1 || true)
[ -n "$found" ] || { echo "dirt-ws2: $1 not found" >&2; exit 1; }
echo "$found"
}
clang=$(tool clang)
dlltool=$(tool llvm-dlltool)
tool ld.lld > /dev/null
python3 "$here/gen.py" generate "$here" "$work"
"$dlltool" -m i386 -k -d "$here/kernel32.def" -l "$work/libkernel32.a"
"$clang" --target=i686-w64-mingw32 -O2 -Wall -Wextra -Werror -ffreestanding -fno-stack-protector -fno-builtin \
-nostdlib -shared -fuse-ld=lld -o "$work/ws2_32.dll" "$here/ws2_32.c" "$work/thunks.c" "$work/ws2_32.def" \
-L"$work" -lkernel32 -Wl,--entry,DllMain@12 -Wl,--no-insert-timestamp
python3 "$here/gen.py" verify "$here" "$work/ws2_32.dll"
install -m 644 "$work/ws2_32.dll" "$out/ws2_32.dll"
+69
View File
@@ -0,0 +1,69 @@
import struct
import sys
from pathlib import Path
def exports_list(src):
rows = []
for line in (Path(src) / 'ws2_32-exports.txt').read_text().splitlines():
ordinal, name = line.split()
rows.append((int(ordinal), name))
return rows
def generate(src, out):
rows = exports_list(src)
passed = [(o, n) for o, n in rows if n != 'sendto']
c = ['/* Generated by tools/dirt-ws2/gen.py. */',
'const unsigned short dirtfix_ordinals[%d] = {%s};' % (len(passed), ', '.join(str(o) for o, _ in passed)),
'const unsigned int dirtfix_count = %d;' % len(passed),
'void *dirtfix_real[%d];' % len(passed),
'__asm__(".text\\n"']
for i, (o, _) in enumerate(passed):
c.append(' ".globl _dirtfix_t%d\\n_dirtfix_t%d:\\n\\tjmp *_dirtfix_real+%d\\n"' % (o, o, 4 * i))
c.append(');')
(Path(out) / 'thunks.c').write_text('\n'.join(c) + '\n')
d = ['LIBRARY ws2_32.dll', 'EXPORTS']
d += [' %s=%s @%d' % (n, 'dirtfix_sendto@24' if n == 'sendto' else 'dirtfix_t%d' % o, o) for o, n in rows]
(Path(out) / 'ws2_32.def').write_text('\n'.join(d) + '\n')
def pe_exports(path):
data = Path(path).read_bytes()
pe = struct.unpack_from('<I', data, 0x3c)[0]
machine, sections = struct.unpack_from('<HH', data, pe + 4)
optional_size = struct.unpack_from('<H', data, pe + 20)[0]
optional = pe + 24
export_rva = struct.unpack_from('<I', data, optional + 96)[0]
table = [struct.unpack_from('<IIII', data, optional + optional_size + 40 * i + 8) for i in range(sections)]
def offset(rva):
for size, address, raw_size, raw in table:
if address <= rva < address + max(size, raw_size):
return rva - address + raw
raise ValueError('RVA %#x outside the sections' % rva)
base, functions, names, function_rva, name_rva, ordinal_rva = struct.unpack_from('<IIIIII', data, offset(export_rva) + 16)
named = {}
for i in range(names):
text = struct.unpack_from('<I', data, offset(name_rva) + 4 * i)[0]
index = struct.unpack_from('<H', data, offset(ordinal_rva) + 2 * i)[0]
named[index] = data[offset(text):].split(b'\0')[0].decode()
result = [(base + i, named.get(i)) for i in range(functions) if struct.unpack_from('<I', data, offset(function_rva) + 4 * i)[0]]
return machine, result
def verify(src, dll):
machine, found = pe_exports(dll)
if machine != 0x14c:
sys.exit('%s is not a 32-bit x86 DLL (machine %#x)' % (dll, machine))
expected = exports_list(src)
if found != expected:
sys.exit('%s exports differ from ws2_32-exports.txt: %d found, %d expected' % (dll, len(found), len(expected)))
if b'droiddeck-dirt-ws2_32' not in Path(dll).read_bytes():
sys.exit('%s lacks the stand-in marker' % dll)
print('%s: %d exports match, marker present' % (dll, len(found)))
if __name__ == '__main__':
{'generate': generate, 'verify': verify}[sys.argv[1]](sys.argv[2], sys.argv[3])
+7
View File
@@ -0,0 +1,7 @@
LIBRARY kernel32.dll
EXPORTS
LoadLibraryW@4
GetProcAddress@8
GetSystemDirectoryW@8
GetEnvironmentVariableW@12
GetFileAttributesW@4
+135
View File
@@ -0,0 +1,135 @@
1 accept
2 bind
3 closesocket
4 connect
5 getpeername
6 getsockname
7 getsockopt
8 htonl
9 htons
10 ioctlsocket
11 inet_addr
12 inet_ntoa
13 listen
14 ntohl
15 ntohs
16 recv
17 recvfrom
18 select
19 send
20 sendto
21 setsockopt
22 shutdown
23 socket
24 FreeAddrInfoEx
25 FreeAddrInfoExW
26 FreeAddrInfoW
27 GetAddrInfoExCancel
28 GetAddrInfoExOverlappedResult
29 GetAddrInfoExW
30 GetAddrInfoW
31 GetHostNameW
32 GetNameInfoW
33 InetNtopW
34 InetPtonW
35 WSApSetPostRoutine
36 WPUCompleteOverlappedRequest
37 WSAAccept
38 WSAAddressToStringA
39 WSAAddressToStringW
40 WSACloseEvent
41 WSAConnect
42 WSAConnectByNameA
43 WSAConnectByNameW
44 WSACreateEvent
45 WSADuplicateSocketA
46 WSADuplicateSocketW
47 WSAEnumNameSpaceProvidersA
48 WSAEnumNameSpaceProvidersW
49 WSAEnumNetworkEvents
50 WSAEnumProtocolsA
51 gethostbyaddr
52 gethostbyname
53 getprotobyname
54 getprotobynumber
55 getservbyname
56 getservbyport
57 gethostname
58 WSAEnumProtocolsW
59 WSAEventSelect
60 WSAGetOverlappedResult
61 WSAGetQOSByName
62 WSAGetServiceClassInfoA
63 WSAGetServiceClassInfoW
64 WSAGetServiceClassNameByClassIdA
65 WSAGetServiceClassNameByClassIdW
66 WSAHtonl
67 WSAHtons
68 WSAInstallServiceClassA
69 WSAInstallServiceClassW
70 WSAIoctl
71 WSAJoinLeaf
72 WSALookupServiceBeginA
73 WSALookupServiceBeginW
74 WSALookupServiceEnd
75 WSALookupServiceNextA
76 WSALookupServiceNextW
77 WSANSPIoctl
78 WSANtohl
79 WSANtohs
80 WSAPoll
81 WSAProviderConfigChange
82 WSARecv
83 WSARecvDisconnect
84 WSARecvFrom
85 WSARemoveServiceClass
86 WSAResetEvent
87 WSASend
88 WSASendDisconnect
89 WSASendMsg
90 WSASendTo
91 WSASetEvent
92 WSASetServiceA
93 WSASetServiceW
94 WSASocketA
95 WSASocketW
96 WSAStringToAddressA
97 WSAStringToAddressW
98 WSAWaitForMultipleEvents
99 WSCDeinstallProvider
100 WSCEnableNSProvider
101 WSAAsyncSelect
102 WSAAsyncGetHostByAddr
103 WSAAsyncGetHostByName
104 WSAAsyncGetProtoByNumber
105 WSAAsyncGetProtoByName
106 WSAAsyncGetServByPort
107 WSAAsyncGetServByName
108 WSACancelAsyncRequest
109 WSASetBlockingHook
110 WSAUnhookBlockingHook
111 WSAGetLastError
112 WSASetLastError
113 WSACancelBlockingCall
114 WSAIsBlocking
115 WSAStartup
116 WSACleanup
117 WSCEnumProtocols
118 WSCEnumProtocols32
119 WSCGetApplicationCategory
120 WSCGetProviderInfo
121 WSCGetProviderPath
122 WSCInstallNameSpace
123 WSCInstallProvider
124 WSCSetApplicationCategory
125 WSCUnInstallNameSpace
126 WSCUpdateProvider
127 WSCWriteNameSpaceOrder
128 WSCWriteProviderOrder
129 freeaddrinfo
130 getaddrinfo
131 getnameinfo
132 inet_ntop
133 inet_pton
151 __WSAFDIsSet
500 WEP
+95
View File
@@ -0,0 +1,95 @@
/* Same behaviour as DiRTTelemetryErrorFix by RoccoC (MIT), based on the fix by Carsten Gottschling. */
typedef unsigned short WCHAR;
typedef unsigned long DWORD;
typedef unsigned int UINT;
typedef unsigned int UINT_PTR;
typedef int BOOL;
typedef void *HMODULE;
#define WINAPI __attribute__((stdcall))
#define WSAENOTSOCK 10038
#define ORDINAL(n) ((const char *)(UINT_PTR)(n))
__attribute__((dllimport)) HMODULE WINAPI LoadLibraryW(const WCHAR *name);
__attribute__((dllimport)) void *WINAPI GetProcAddress(HMODULE module, const char *name);
__attribute__((dllimport)) UINT WINAPI GetSystemDirectoryW(WCHAR *buffer, UINT size);
__attribute__((dllimport)) DWORD WINAPI GetEnvironmentVariableW(const WCHAR *name, WCHAR *buffer, DWORD size);
__attribute__((dllimport)) DWORD WINAPI GetFileAttributesW(const WCHAR *name);
__attribute__((used)) const char dirtfix_marker[] = "droiddeck-dirt-ws2_32";
extern const unsigned short dirtfix_ordinals[];
extern const unsigned int dirtfix_count;
extern void *dirtfix_real[];
static int (WINAPI *real_sendto)(UINT_PTR, const char *, int, int, const void *, int);
static int (WINAPI *real_WSAGetLastError)(void);
static void (WINAPI *real_WSASetLastError)(int);
int WINAPI dirtfix_sendto(UINT_PTR s, const char *buf, int len, int flags, const void *to, int tolen)
{
int ret = real_sendto(s, buf, len, flags, to, tolen);
if (ret == -1 && real_WSAGetLastError() == WSAENOTSOCK)
{
real_WSASetLastError(0);
return 0;
}
return ret;
}
static void append(WCHAR *dst, const char *src)
{
while (*dst) dst++;
while ((*dst++ = (WCHAR)(unsigned char)*src++));
}
static void append_number(WCHAR *dst, UINT n)
{
char digits[12];
int i = 11;
digits[i] = 0;
do digits[--i] = (char)('0' + n % 10); while (n /= 10);
append(dst, digits + i);
}
static HMODULE load_wine_ws2_32(HMODULE self)
{
WCHAR name[24], path[600];
HMODULE real;
UINT n, d;
for (d = 0; d < 16; d++)
{
name[0] = 0;
append(name, "WINEDLLDIR");
append_number(name, d);
n = GetEnvironmentVariableW(name, path, 500);
if (!n || n >= 500) continue;
if (path[0] == '\\' && path[1] == '?' && path[2] == '?' && path[3] == '\\') path[1] = '\\';
append(path, "\\i386-windows\\ws2_32.dll");
if (GetFileAttributesW(path) == (DWORD)-1) continue;
if ((real = LoadLibraryW(path)) && real != self) return real;
}
n = GetSystemDirectoryW(path, 280);
if (!n || n >= 280) return 0;
path[n] = 0;
append(path, "\\ws2_32.dll");
real = LoadLibraryW(path);
return real != self ? real : 0;
}
BOOL WINAPI DllMain(HMODULE self, DWORD reason, void *reserved)
{
HMODULE real;
UINT i;
(void)reserved;
if (reason != 1) return 1;
if (!(real = load_wine_ws2_32(self))) return 0;
for (i = 0; i < dirtfix_count; i++) dirtfix_real[i] = GetProcAddress(real, ORDINAL(dirtfix_ordinals[i]));
real_sendto = GetProcAddress(real, ORDINAL(20));
real_WSAGetLastError = GetProcAddress(real, ORDINAL(111));
real_WSASetLastError = GetProcAddress(real, ORDINAL(112));
return real_sendto && real_WSAGetLastError && real_WSASetLastError;
}
-1
View File
@@ -1,4 +1,3 @@
# Sourced by the build scripts: picks the Docker platform and the matching cross-build image.
docker_platform=${DROIDDECK_DOCKER_PLATFORM:-}
if [[ -z "${docker_platform}" ]]; then
case "$(uname -m)" in arm64|aarch64) docker_platform=linux/arm64 ;; *) docker_platform=linux/amd64 ;; esac
+1 -2
View File
@@ -1,4 +1,3 @@
"""Check the engine before modifying build assets; never rebuild for a daemon error."""
import os
from pathlib import Path
import subprocess
@@ -18,7 +17,7 @@ if __name__ == '__main__':
sys.exit('Docker is unavailable: ' + engine.stderr.strip())
image = run('image', 'inspect', sys.argv[1])
if image.returncode:
if 'No such image' not in image.stderr and 'image not known' not in image.stderr: # Docker, Podman
if 'No such image' not in image.stderr and 'image not known' not in image.stderr:
sys.exit('Cannot inspect the build image: ' + image.stderr.strip())
repo = Path(__file__).resolve().parents[1]
subprocess.run(['docker', 'build', '--platform', os.environ.get('DROIDDECK_DOCKER_PLATFORM', 'linux/amd64'), '-t', sys.argv[1],
-1
View File
@@ -146,7 +146,6 @@ class Runner:
log.append(entry)
def evidence(self, folder: Path) -> dict:
"""What a failed run leaves behind: the screen, gamescope's focus, the session's logs."""
found = {}
for name, action in (
("screenshot", lambda: ctl.screenshot(self.adb, self.serial, str(folder / "failure.png"), None)),
+56 -20
View File
@@ -24,7 +24,6 @@ from adb_device import DeviceResolutionError, resolve_serial
from proot_profile import report as proot_profile_report
# tools/release/variants.txt: the same app also ships as other packages (e.g. com.antutu.benchmark.full).
PACKAGE = os.environ.get("DROIDDECK_PACKAGE", "com.droiddeck.launcher")
AUTHORITY = f"content://{PACKAGE}.agent"
PACKAGE_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+")
@@ -115,7 +114,6 @@ def provider_call(adb: str, serial: str, method: str, arg: str | None = None, re
def checked(response: dict, default_code: str) -> dict:
"""A provider or guest answer, raised as a ControlError when it carries ok: false."""
if response.get("ok") is False:
error = response.get("error", {})
raise ControlError(error.get("message", default_code), error.get("code", default_code))
@@ -166,7 +164,6 @@ def get_state(adb: str, serial: str) -> dict:
def wait_until(adb: str, serial: str, describe: str, done, timeout: float, poll: float = 1.0) -> dict:
"""Poll state until done(state) is true. A failed session ends the wait at once."""
deadline = time.monotonic() + timeout
while True:
state = get_state(adb, serial)
@@ -203,8 +200,6 @@ def wait_for_phase(adb: str, serial: str, wanted: str, timeout: float) -> dict:
def focused(state: dict, app_id: int | None) -> bool:
"""The game has focus the way a player sees it: gamescope focuses it and it is in the list the
Steam client orders the base layer from. app_id None means any game (not the client)."""
focus = state.get("session", {}).get("focus") or {}
current = focus.get("focusedApp")
if app_id is None:
@@ -232,7 +227,6 @@ def add_serial(response: dict, serial: str) -> dict:
def displays(adb: str, serial: str) -> list[dict]:
"""Logical displays with the SurfaceFlinger (physical) id screencap and screenrecord want."""
result = run_adb(adb, serial, "shell", "dumpsys", "display", timeout=30)
text = result.stdout.decode(errors="replace")
devices = dict(re.findall(r'DisplayDeviceInfo\{"([^"]+)": uniqueId="local:(\d+)"', text))
@@ -300,14 +294,6 @@ def record(adb: str, serial: str, path: str, seconds: float, display: int | None
def pacing_summary(text: str, package: str = PACKAGE) -> dict:
"""What reached the panel, from a `dumpsys SurfaceFlinger --timestats -dump`.
The game is on the compositor's own layer (droiddeck_wayland_game) when it has one, otherwise on
the session's SurfaceView. SurfaceFlinger keeps one record per layer AND refresh rate, so a panel
that switches between 60 and 120 Hz mid-capture splits the same layer into several records: they
are summed. A game's own fps counter does not show any of this - it counts frames handed over, not
frames shown, and 60 handed over can be 48 on screen with one in four held for two refreshes.
"""
records = {"game": [], "surface": []}
for part in re.split(r"^displayRefreshRate = ", text, flags=re.M)[1:]:
rate = re.match(r"(\d+)", part)
@@ -329,7 +315,6 @@ def pacing_summary(text: str, package: str = PACKAGE) -> dict:
for ms, count in bins.items():
histogram[ms] = histogram.get(ms, 0) + count
if bins:
# SurfaceFlinger bins by whole milliseconds, so one cadence spans two buckets (16.7 ms: 16 and 17).
mode = max(bins, key=bins.get)
off += sum(count for ms, count in bins.items() if abs(ms - mode) > 1)
intervals = sum(histogram.values())
@@ -346,7 +331,6 @@ def pacing_summary(text: str, package: str = PACKAGE) -> dict:
def pacing(adb: str, serial: str, seconds: float) -> dict:
"""Frames on screen and their intervals over `seconds`, from SurfaceFlinger's timestats."""
seconds = max(1.0, min(600.0, seconds))
timestats = ("shell", "dumpsys", "SurfaceFlinger", "--timestats")
try:
@@ -378,6 +362,50 @@ def pacing(adb: str, serial: str, seconds: float) -> dict:
return {"ok": True, "command": "pacing", "seconds": round(elapsed, 1), **summary}
THERMAL_STATUS = ["NONE", "LIGHT", "MODERATE", "SEVERE", "CRITICAL", "EMERGENCY", "SHUTDOWN"]
CPUFREQ = "/sys/devices/system/cpu/cpufreq"
def thermal_summary(battery: str, service: str, cpufreq: str) -> dict:
tenths = re.search(r"^\s*temperature:\s*(-?\d+)", battery, re.M)
status = re.search(r"^\s*Thermal Status:\s*(\d+)", service, re.M)
level = int(status.group(1)) if status else None
cpu: dict[str, dict] = {}
for policy, name, khz in re.findall(r"/(policy\d+)/(scaling_max_freq|cpuinfo_max_freq):(\d+)", cpufreq):
cpu.setdefault(policy, {})["maxKHz" if name == "scaling_max_freq" else "hardwareMaxKHz"] = int(khz)
for limits in cpu.values():
if "maxKHz" in limits and "hardwareMaxKHz" in limits:
limits["capped"] = limits["maxKHz"] < limits["hardwareMaxKHz"]
return {
"batteryC": int(tenths.group(1)) / 10 if tenths else None,
"status": level,
"statusName": THERMAL_STATUS[level] if level is not None and level < len(THERMAL_STATUS) else None,
"cpu": dict(sorted(cpu.items(), key=lambda item: int(item[0][6:]))),
}
def thermal(adb: str, serial: str) -> dict:
def shell(*command: str) -> str:
return run_adb(adb, serial, "shell", *command).stdout.decode(errors="replace")
summary = thermal_summary(shell("dumpsys", "battery"), shell("dumpsys", "thermalservice"),
shell("grep", ".", f"{CPUFREQ}/policy*/scaling_max_freq", f"{CPUFREQ}/policy*/cpuinfo_max_freq"))
return {"ok": True, "command": "thermal", **summary}
def wait_cool(adb: str, serial: str, below: float, timeout: float) -> dict:
started = time.monotonic()
while True:
reading = thermal(adb, serial)
if reading["batteryC"] is None:
raise ControlError("dumpsys battery reports no temperature", "THERMAL_FAILED")
if reading["batteryC"] < below:
return {**reading, "command": "wait", "waitedSeconds": round(time.monotonic() - started, 1)}
remaining = started + timeout - time.monotonic()
if remaining <= 0:
raise ControlError(f"Battery still at {reading['batteryC']:g} °C after {timeout:g} s, wanted below {below:g}",
"TIMEOUT")
time.sleep(min(10.0, remaining))
def start_session(adb: str, serial: str, request: dict) -> dict:
if request.get("mode") == "run":
@@ -487,7 +515,6 @@ def xr_capture(adb: str, serial: str, destination: Path, timeout: float) -> dict
except (OSError, EOFError, zlib.error) as error:
raise ControlError('Incomplete compressed XR image', 'XR_CAPTURE_FAILED') from error
images[eye] = xr_ppm_to_png(pixels, linear=eye == 'source' and metadata.get('sourceColorSpace') == 'linear')
# Detect overlapping captures before publishing images with another request's metadata.
check = run_adb(adb, serial, 'shell', 'cat', remote + '.json')
try:
unchanged = json.loads(check.stdout).get('id') == token
@@ -548,6 +575,10 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
"sessionId": session.get("id"), "phase": session.get("phase")}, serial)
if command == "wait":
if args.phase == "cool":
if args.below is None:
raise ControlError("wait cool needs --below <°C>", "INVALID_ARGUMENTS")
return add_serial(wait_cool(adb, serial, args.below, args.timeout), serial)
if args.phase == "focused":
if args.app_id is None:
raise ControlError("wait focused needs an app id", "INVALID_ARGUMENTS")
@@ -721,6 +752,9 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
if command == "pacing":
return add_serial(pacing(adb, serial, args.seconds), serial)
if command == "thermal":
return add_serial(thermal(adb, serial), serial)
if command == "wake":
run_adb(adb, serial, "shell", "input", "keyevent", "KEYCODE_WAKEUP")
run_adb(adb, serial, "shell", "wm", "dismiss-keyguard")
@@ -756,9 +790,10 @@ def build_parser() -> argparse.ArgumentParser:
run.add_argument("program")
run.add_argument("arguments", nargs=argparse.REMAINDER)
wait = commands.add_parser("wait", help="wait for a session phase, or for a game to have focus")
wait.add_argument("phase", choices=["ready", "idle", "failed", "focused", "game"])
wait = commands.add_parser("wait", help="wait for a session phase, for a game to have focus, or for the battery to cool")
wait.add_argument("phase", choices=["ready", "idle", "failed", "focused", "game", "cool"])
wait.add_argument("app_id", nargs="?", type=int, help="with focused: the Steam app id")
wait.add_argument("--below", type=float, help="with cool: the battery temperature to get under, in °C")
wait.add_argument("--timeout", type=float, default=90)
stop = commands.add_parser("stop", help="stop the session and wait for IDLE")
@@ -923,6 +958,7 @@ def build_parser() -> argparse.ArgumentParser:
pace = commands.add_parser("pacing", help="frames that reached the screen and their intervals (SurfaceFlinger)")
pace.add_argument("--seconds", type=float, default=30)
commands.add_parser("thermal", help="battery temperature, thermal status and CPU frequency caps")
commands.add_parser("displays", help="the device's displays and their capture ids")
commands.add_parser("wake", help="wake the device and dismiss the keyguard")
return parser
@@ -961,7 +997,7 @@ def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
serial = None
try:
if not PACKAGE_NAME.fullmatch(PACKAGE): # it reaches the device shell through `am start` and `content call`
if not PACKAGE_NAME.fullmatch(PACKAGE):
raise ControlError(f"DROIDDECK_PACKAGE is not an Android package name: {PACKAGE!r}", "INVALID_REQUEST")
if args.command == "proot-profile" and args.profile_op == "report":
if args.limit < 1:
-9
View File
@@ -1,6 +1,4 @@
#!/usr/bin/bash
# Runs inside an Arch Linux ARM container (menci/archlinuxarm:base-devel) on an arm64 runner. Arch Linux ARM ships
# no FEX package and FEX publishes no Linux binaries.
set -euxo pipefail
VERSION=${FEX_VERSION:-FEX-2610}
WORK=/work
@@ -10,7 +8,6 @@ grep -q '^DisableSandbox' /etc/pacman.conf || sed -i 's/^\[options\]/[options]\n
mv /etc/pacman.d/mirrorlist.new /etc/pacman.d/mirrorlist
pacman -Syu --noconfirm --needed git zstd binutils cmake ninja clang lld llvm python squashfs-tools file patchelf xxhash
# The x86 sysroot is Arch x86_64 and multilib i686 packages unpacked by pacman, never run: no scriptlets or signature checks.
THUNKS=${FEX_THUNKS:-0}
X86ROOT=$WORK/x86root
if [ "$THUNKS" = 1 ]; then
@@ -40,15 +37,12 @@ fi
rm -rf fex-src out && git clone -q --depth 1 --branch "$VERSION" --recurse-submodules --shallow-submodules https://github.com/FEX-Emu/FEX.git fex-src
for p in tools/fex/patches/*.patch; do patch -d fex-src -p1 --no-backup-if-mismatch < "$p"; done
# FEX's x86 toolchain files assume an x86 build machine; here the guest thunks need the x86 sysroot too.
# Arch's clang adds stack protection; its canary load in a guest thunk's prologue clobbered r11 (the host function).
if [ "$THUNKS" = 1 ]; then
for t in fex-src/Data/CMake/toolchain_x86_64.cmake fex-src/Data/CMake/toolchain_x86_32.cmake; do
printf '\nif (X86_DEV_ROOTFS AND NOT X86_DEV_ROOTFS STREQUAL "/")\n set(CMAKE_SYSROOT "${X86_DEV_ROOTFS}")\nendif()\n' >> "$t"
printf '\nset(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-stack-protector")\nset(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-stack-protector")\n' >> "$t"
done
fi
# TUNE_CPU none: the default (native) would tune for the runner's Neoverse cores, not the device.
cmake -S fex-src -B fex-build -G Ninja \
-DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local \
-DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DUSE_LINKER=lld \
@@ -60,8 +54,6 @@ cmake -S fex-src -B fex-build -G Ninja \
ninja -C fex-build
DESTDIR="$WORK/out" ninja -C fex-build install
install -Dm755 /usr/bin/unsquashfs out/usr/local/bin/unsquashfs
# The Linux runtime has no xxhash and no ld.so.cache: the library goes beside libFEXCore and the programs
# that need it find it through RUNPATH.
install -Dm644 "$(readlink -f /usr/lib/libxxhash.so.0)" out/usr/local/lib/libxxhash.so.0
bundled=$(cd out/usr/local/lib && ls -- *.so* | sort -u)
for f in out/usr/local/bin/*; do
@@ -70,7 +62,6 @@ for f in out/usr/local/bin/*; do
readelf -d "$f" | awk '/NEEDED/ { gsub(/[\[\]]/, "", $5); print $5 }' | grep -qxF "$bundled" \
&& patchelf --set-rpath '$ORIGIN/../lib' "$f"
done
# Every NEEDED soname must resolve in a stock guest: bundled here or provided by the runtime (runtime-libs.txt).
for f in out/usr/local/bin/* out/usr/local/lib/*.so* out/usr/local/lib/fex-emu/HostThunks*/*.so; do
[ -f "$f" ] && file "$f" | grep -q ELF || continue
readelf -d "$f" | awk '/NEEDED/ { gsub(/[\[\]]/, "", $5); print $5 }'
@@ -10,7 +10,7 @@ index 7172460..2c80dca 100644
#include <linux/openat2.h>
#include <fcntl.h>
#include <filesystem>
@@ -632,6 +633,163 @@ static bool ShouldSkipOpenInEmu(int flags) {
@@ -632,6 +633,157 @@ static bool ShouldSkipOpenInEmu(int flags) {
return false;
}
@@ -26,19 +26,15 @@ index 7172460..2c80dca 100644
+ return Result;
+}
+
+// openat2() with RESOLVE_IN_ROOT, walked one component at a time: PRoot has no openat2 and fails it with ENOSYS.
+// DirFD is AT_FDCWD only for thunk overlays, which never resolve in the root.
+static int OpenatWithoutOpenat2(int DirFD, const char* Pathname, int Flags, uint32_t Mode) {
+ if (DirFD == AT_FDCWD) {
+ return ::syscall(SYSCALL_DEF(openat), DirFD, Pathname, Flags, Mode);
+ }
+
+ // The kernel's MAXSYMLINKS.
+ constexpr uint32_t MaxSymlinks = 40;
+ uint32_t Symlinks {};
+ std::optional<dev_t> RootDev {};
+
+ // O_NOFOLLOW and O_CREAT | O_EXCL leave a final symlink alone, unless a trailing slash follows it.
+ const bool NoFollow = (Flags & O_NOFOLLOW) || (Flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
+
+ char Resolved[PATH_MAX];
@@ -116,7 +112,6 @@ index 7172460..2c80dca 100644
+ }
+
+ if (Buffer.st_dev != *RootDev && IsOnProcFS(DirFD, Resolved)) {
+ // Only procfs has magic links. RESOLVE_IN_ROOT fails them with EXDEV and the callers then open without it.
+ return ::syscall(SYSCALL_DEF(openat), DirFD, Pathname, Flags, Mode);
+ }
+
@@ -145,7 +140,6 @@ index 7172460..2c80dca 100644
+ }
+
+ if (Last) {
+ // openat reports on the final component, which O_CREAT may create.
+ ResolvedLen = CandidateLen;
+ if (TrailingSlash) {
+ Resolved[ResolvedLen++] = '/';
@@ -174,7 +168,7 @@ index 7172460..2c80dca 100644
bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) {
char Tmp[PATH_MAX + 1];
@@ -678,6 +836,8 @@ uint64_t FileManager::Open(const char* pathname, int flags, uint32_t mode) {
@@ -678,6 +830,8 @@ uint64_t FileManager::Open(const char* pathname, int flags, uint32_t mode) {
// This means a magic symlink (/proc/foo) was involved. In this case we
// just punt and do the access without RESOLVE_IN_ROOT.
fd = ::syscall(SYSCALL_DEF(openat), Path.FD, Path.Path, flags, mode);
@@ -183,7 +177,7 @@ index 7172460..2c80dca 100644
}
}
@@ -931,6 +1091,8 @@ uint64_t FileManager::Openat([[maybe_unused]] int dirfs, const char* pathname, i
@@ -931,6 +1085,8 @@ uint64_t FileManager::Openat([[maybe_unused]] int dirfs, const char* pathname, i
// This means a magic symlink (/proc/foo) was involved. In this case we
// just punt and do the access without RESOLVE_IN_ROOT.
fd = ::syscall(SYSCALL_DEF(openat), Path.FD, Path.Path, flags, mode);
@@ -192,7 +186,7 @@ index 7172460..2c80dca 100644
}
}
@@ -967,6 +1129,8 @@ uint64_t FileManager::Openat2(int dirfs, const char* pathname, FEX::HLE::open_ho
@@ -967,6 +1123,8 @@ uint64_t FileManager::Openat2(int dirfs, const char* pathname, FEX::HLE::open_ho
// This means a magic symlink (/proc/foo) was involved. In this case we
// just punt and do the access without RESOLVE_IN_ROOT.
fd = ::syscall(SYSCALL_DEF(openat2), Path.FD, Path.Path, how, usize);
@@ -26,11 +26,10 @@ index 60b0ef1..4a94009 100644
using FindHandler = uint64_t (MemAllocator32Bit::*)(uint64_t Start, size_t Pages) const;
FindHandler FindPageRangePtr {};
};
@@ -132,6 +135,37 @@ uint64_t MemAllocator32Bit::FindPageRange_TopDown(uint64_t Start, size_t Pages)
@@ -132,6 +135,36 @@ uint64_t MemAllocator32Bit::FindPageRange_TopDown(uint64_t Start, size_t Pages)
return 0;
}
+// Marks each run of host mappings that overlaps the range as used, in full. Returns false if none overlaps.
+bool MemAllocator32Bit::SetHostMappedPages(uint64_t PageAddr, size_t PagesLength) {
+ const int MapsFD = ::open("/proc/self/maps", O_RDONLY | O_CLOEXEC);
+ if (MapsFD == -1) {
@@ -64,7 +63,7 @@ index 60b0ef1..4a94009 100644
void* MemAllocator32Bit::Mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) {
std::scoped_lock<std::mutex> lk {AllocMutex};
size_t PagesLength = FEXCore::AlignUp(length, FEXCore::Utils::FEX_PAGE_SIZE) >> FEXCore::Utils::FEX_PAGE_SHIFT;
@@ -175,11 +209,17 @@ void* MemAllocator32Bit::Mmap(void* addr, size_t length, int prot, int flags, in
@@ -175,11 +208,16 @@ void* MemAllocator32Bit::Mmap(void* addr, size_t length, int prot, int flags, in
auto AllocateNoHint = [&]() -> void* {
bool Wrapped = false;
@@ -74,7 +73,6 @@ index 60b0ef1..4a94009 100644
// Linear range scan
uint64_t LowerPage = (this->*FindPageRangePtr)(BottomPage, PagesLength);
if (LowerPage == 0) {
+ // A second scan from the start found nothing either: the range is full, as the kernel would say.
+ if (Restarted) {
+ return reinterpret_cast<void*>(-ENOMEM);
+ }
@@ -82,15 +80,12 @@ index 60b0ef1..4a94009 100644
// Try again but this time from the start
BottomPage = Map32Bit ? LastKeyLocation32Bit : LastKeyLocation;
LowerPage = (this->*FindPageRangePtr)(BottomPage, PagesLength);
@@ -206,7 +246,17 @@ restart: {
@@ -206,7 +244,14 @@ restart: {
return (void*)(uintptr_t)-errno;
} else {
// Try again
- if (SearchDown) {
+ if (Map32Bit) {
+ // MAP_32BIT from a 64-bit guest, whose other mappings bypass this allocator: once Counter-Strike 2 had reserved the
+ // low 2GB, stepping one page at a time scanned for ever. Record what the host holds there and rescan the range, or
+ // move past it if that mapping is gone.
+ const bool Marked = SetHostMappedPages(LowerPage, PagesLength);
+ if (SearchDown) {
+ BottomPage = Marked ? UpperPage - 1 : LowerPage - 1;
+57
View File
@@ -209,3 +209,60 @@ the connector's windows (`mangoapp_nudge_app_frame`). With `DROIDDECK_HUD_FRAMES
sets `/run/droiddeck-hud/frames`), gamescope maps that file and writes the same commits of connector 0,
whether or not a mangoapp runs, plus the focused pid, output size, refresh, Steam focus and engine name.
The layout is in the comment above `droiddeck_hud_frames_map`; the app reads it in `hudframes.c`.
## 0126 steamcompmgr: a topmost focus window keeps other processes' windows beneath it
EA games on Steam start through the EA app. Its Steam launcher (`EASteamLauncher.exe`) shows the
game's splash as a layered tool window, and the EA app (`EADesktop.exe`, another process) opens its
sign-in window `WS_EX_TOPMOST`. gamescope took the splash as the sign-in's override window, so it was
painted over most of the sign-in and became gamescope's keyboard focus window (Burnout Paradise
Remastered, `gamescopectl focus_info`). On Windows a topmost window stays above every window that is neither topmost nor
owned by it, so a window from another process that is neither is no longer an override candidate for
a topmost focus window. Both windows' pids must be known; gamescope keeps -1 when XRes cannot name the
client, which says nothing about the process. Same-process popups, topmost popups (WebView2 and CEF menus) and windows
transient for the focus window are unchanged. gamescope read `_WINE_HWND_EXSTYLE` only from a
PropertyNotify, and it listens for those from map on, so the style Wine sets before mapping a window
was never known; `map_win` now reads it with the other properties, which the layered-launcher and
Xalia rules rely on too. `tools/tests/test_gamescope_override_stacking.py` compiles the rule from
this patch.
## 0127 steamcompmgr: a three way relative mouse switch
`relative_mouse` is read where the decision is made: 0 leaves it to the rule below, 1 forces relative
motion for the focused game except Steam's own windows and composites the cursor, 2 never goes relative.
For games that confine a visible cursor and warp it, which the automatic rule cannot see.
## 0128 steamcompmgr: a hidden cursor under any pointer constraint is relative
The rule only counted a lock with a cursor position hint. A game that hides the cursor and confines the
pointer through a grab (Wine's ClipCursor) has a constraint with no hint, so the nested pointer stayed
absolute, the constraint held the X pointer still and no raw motion was produced: the camera froze.
## 0129 steamcompmgr, wayland: release a pointer lock at the game's pointer
A game can move the X pointer while it holds the lock (Wine's ClipCursor recentres it), and the nested host
never hears about it. On unlock the host's next absolute motion dropped the pointer back at its old position,
often near a corner. The unlock now sends the X pointer as a cursor position hint and commits it first. A cursor
forced On by `relative_mouse` also stays visible while idle, since the host cursor is hidden during the lock.
## 0130 steamcompmgr: fit the X screen to a larger fullscreen window
A game can open a fullscreen window larger than its X screen (Valheim at 1366x768 on 1280x720). The X server
keeps the pointer inside the screen, so the outer part of the window could not be reached and motion past the
edge had to be undone. The server's mode now follows such a window, and returns once the focused window fits,
focus moves to Steam or no window has focus.
## 0131 steamcompmgr, wlserver: follow a game's pointer warps
Under a nested host the seat's absolute position came from the host, so a game that warped a visible X pointer
to the screen centre read the distance back to the host's position on the next motion, and the view spun. When
the X pointer stays far from the seat position while input moves, gamescope takes the host's lock and applies
each frame's motion to the X pointer itself until the game stops warping. Absolute motion also sends relative
motion, as a real compositor does, so XInput2 raw motion reaches games that read only that. A touch moves the
pointer without relative motion, so tapping the screen does not turn the camera.
## 0132 sdl, steamcompmgr: follow a game's window mode
With `--follow-game-window-mode`, the outer window of a nested SDL gamescope follows the focused game window. A window
asking for `_NET_WM_STATE_FULLSCREEN`, or a Steam game covering the X screen without minimise or maximise functions or
decorations in `_MOTIF_WM_HINTS`, makes the outer window fullscreen on the desktop. Anything else makes it a normal window of the
game window's size, or a maximised one when that size does not fit the desktop with its title bar and panel. A change is applied only when the wanted mode changes, so a manual resize or Super+F stays.
-1
View File
@@ -49,7 +49,6 @@ tar --use-compress-program=unzstd -xf "$PKG" -C out --strip-components=2 usr/bin
mv out/gamescope out/usr/local/bin/gamescope
chmod 755 out/usr/local/bin/gamescope
strip --strip-unneeded out/usr/local/bin/gamescope || true
# The WSI layer carries patches too (0117); the runtime's stock copy is replaced.
mkdir -p out/usr/lib
tar --use-compress-program=unzstd -xf "$PKG" -C out usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so
strip --strip-unneeded out/usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so || true
@@ -1,12 +1,9 @@
--- a/src/wlserver.cpp
+++ b/src/wlserver.cpp
@@ -203,6 +203,12 @@
@@ -203,6 +203,9 @@
}
void xwayland_surface_commit(struct wlr_surface *wlr_surface) {
+ // Cursor surfaces never acquire an X11/xdg window association. Keeping their
+ // commits in g_PendingCommits pins every old SHM buffer until the cursor
+ // surface is destroyed. X11 cursor images are handled by MouseCursor.
+ if ( wlr_surface->role && strcmp( wlr_surface->role->name, "wl_pointer-cursor" ) == 0 )
+ return;
+
@@ -9,12 +9,10 @@
#include <sys/stat.h>
// For limiter file.
#include <time.h>
@@ -476,6 +478,34 @@
@@ -476,6 +478,32 @@
// Cached for comparison.
std::optional<VkRect2D> cachedWindowRect;
+ // canBypassXWayland costs several X round trips; at present time it is refreshed at most
+ // every DROIDDECK_WSI_BYPASS_CHECK_MS (default 0 = every present; DroidDeck's Performance mode sets 100).
+ std::optional<bool> presentBypass;
+ bool presentBypassHdr = false;
+ uint64_t presentBypassNs = 0;
@@ -44,7 +42,7 @@
bool isWayland() const {
// Is native Wayland?
return connection == nullptr;
@@ -1597,7 +1627,7 @@
@@ -1597,7 +1625,7 @@
continue;
}
@@ -2,13 +2,10 @@ diff --git a/layer/VkLayer_FROG_gamescope_wsi.cpp b/layer/VkLayer_FROG_gamescope
index ea4ba84..46d086c 100644
--- a/layer/VkLayer_FROG_gamescope_wsi.cpp
+++ b/layer/VkLayer_FROG_gamescope_wsi.cpp
@@ -201,6 +201,13 @@ namespace GamescopeWSILayer {
@@ -201,6 +201,10 @@ namespace GamescopeWSILayer {
return s_minImageCount;
}
+ // The raised count keeps an uncapped game drawing while gamescope turns its buffers around.
+ // Under the frame limiter's FIFO the extra images only queue frames ahead of the screen,
+ // so a limited swapchain gets the default count.
+ static uint32_t getMinImageCount(bool forcingFifo) {
+ return forcingFifo ? std::min(getMinImageCount(), 3u) : getMinImageCount();
+ }
@@ -16,7 +13,7 @@ index ea4ba84..46d086c 100644
static bool getEnsureMinImageCount() {
static bool s_ensureMinImageCount = []() -> bool {
if (auto ensure = parseEnv<bool>("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT")) {
@@ -984,7 +991,7 @@ namespace GamescopeWSILayer {
@@ -984,7 +988,7 @@ namespace GamescopeWSILayer {
pSurfaceCapabilities->currentExtent = rect->extent;
}
@@ -25,7 +22,7 @@ index ea4ba84..46d086c 100644
return VK_SUCCESS;
}
@@ -1027,7 +1034,7 @@ namespace GamescopeWSILayer {
@@ -1027,7 +1031,7 @@ namespace GamescopeWSILayer {
pSurfaceCapabilities->surfaceCapabilities.currentExtent = rect->extent;
}
@@ -34,7 +31,7 @@ index ea4ba84..46d086c 100644
return VK_SUCCESS;
}
@@ -1305,7 +1312,7 @@ namespace GamescopeWSILayer {
@@ -1305,7 +1309,7 @@ namespace GamescopeWSILayer {
uint32_t minImageCount = swapchainInfo.minImageCount;
if (getEnsureMinImageCount())
@@ -43,12 +40,10 @@ index ea4ba84..46d086c 100644
swapchainInfo.minImageCount = minImageCount;
fprintf(stderr, "[Gamescope WSI] Creating swapchain for xid: 0x%0x - oldSwapchain: %p - provided minImageCount: %u - minImageCount: %u - format: %s - colorspace: %s - flip: %s\n",
@@ -1627,6 +1634,13 @@ namespace GamescopeWSILayer {
@@ -1627,6 +1631,11 @@ namespace GamescopeWSILayer {
continue;
}
+ // Other apps keep their swapchain when the limiter changes; ask them to recreate it so
+ // the image count follows the limiter as well.
+ if (!frameLimiterAware && gamescopeSwapchain->forceFifo != forceFifo &&
+ getMinImageCount(true) != getMinImageCount(false) &&
+ !(gamescopeSurface->flags & GamescopeLayerClient::Flag::NoSuboptimal))
@@ -2,13 +2,10 @@ diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index 40164ba..1b85e63 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -1698,6 +1698,52 @@ namespace gamescope
@@ -1698,6 +1698,46 @@ namespace gamescope
}
}
+ // -r sets the refresh gamescope starts with. With GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST=1 a refresh
+ // the host compositor reports later replaces it, so pacing and the frame limiter follow a panel
+ // switched to another mode during the session.
+ static bool NestedRefreshFollowsHost()
+ {
+ static const bool s_bFollow = []
@@ -19,9 +16,6 @@ index 40164ba..1b85e63 100644
+ return s_bFollow;
+ }
+
+ // A mode switch on the host can report a passing rate for a few frames (72 Hz between 144 and
+ // 120 on an AYANEO Pocket FIT); a new rate is taken once it has been reported for 300 ms.
+ // Until then gamescope keeps presenting, so a still screen also gets the feedback that takes it.
+ static bool HostRefreshChanged( int32_t nRefreshmHz, uint64_t ulPresentedNs )
+ {
+ static int32_t s_nPendingmHz = 0;
@@ -55,7 +49,7 @@ index 40164ba..1b85e63 100644
void CWaylandPlane::UpdateVRRRefreshRate()
{
if ( m_pParent )
@@ -1724,6 +1770,7 @@ namespace gamescope
@@ -1724,6 +1764,7 @@ namespace gamescope
// TODO(strategy): We should pick the largest refresh rate.
xdg_log.infof( "Changed refresh to: %.3fhz", ConvertmHzToHz( (float) nLargestRefreshRateMhz ) );
g_nOutputRefresh = nLargestRefreshRateMhz;
@@ -63,7 +57,7 @@ index 40164ba..1b85e63 100644
}
}
@@ -1794,10 +1841,11 @@ namespace gamescope
@@ -1794,10 +1835,11 @@ namespace gamescope
if ( uRefreshCycle )
{
int32_t nRefresh = RefreshCycleTomHz( uRefreshCycle );
@@ -76,11 +70,10 @@ index 40164ba..1b85e63 100644
}
m_pConnector->SetHostCompositorIsCurrentlyVRR( false );
@@ -2636,6 +2684,9 @@ namespace gamescope
@@ -2636,6 +2678,8 @@ namespace gamescope
}
void CWaylandBackend::Wayland_Output_Mode( wl_output *pOutput, uint32_t uFlags, int32_t nWidth, int32_t nHeight, int32_t nRefresh )
{
+ // The followed rate comes from presentation feedback, so a still screen presents once for it.
+ if ( NestedRefreshFollowsHost() && m_pOutputs[ pOutput ].nRefresh != nRefresh )
+ force_repaint();
m_pOutputs[ pOutput ].nRefresh = nRefresh;
@@ -90,12 +83,11 @@ diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index 6c9299d..5fb9086 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -9254,6 +9254,15 @@ void update_vrr_atoms(xwayland_ctx_t *root_ctx, bool force, bool* needs_flush =
@@ -9254,6 +9254,14 @@ void update_vrr_atoms(xwayland_ctx_t *root_ctx, bool force, bool* needs_flush =
g_nCurrentRefreshRate_CachedValue = g_nOutputRefresh;
if (needs_flush)
*needs_flush = true;
+
+ // Steam reads the display's refresh rates from gamescope_control when it binds; send them again.
+ if ( !force )
+ {
+ wlserver_lock();
@@ -11,12 +11,10 @@ index 9a027a2..e6d8e31 100644
};
std::mutex g_wlserver_xdg_shell_windows_lock;
@@ -800,6 +802,20 @@ static void gamescope_swapchain_destroy_co( struct wl_resource *resource );
@@ -800,6 +802,18 @@ static void gamescope_swapchain_destroy_co( struct wl_resource *resource );
void gamescope_xwayland_server_t::handle_override_window_content( struct wl_client *client, struct wl_resource *gamescope_swapchain_resource, struct wlr_surface *surface, uint32_t x11_window )
{
+ // The WSI layer sends this on every present. Finding the top level walks the X tree with a
+ // round trip per level, so a swapchain repeating the same window skips it for 100 ms.
+ const uint64_t ulNow = get_time_in_nanos();
+ if ( gamescope_swapchain_resource )
+ {
@@ -32,7 +30,7 @@ index 9a027a2..e6d8e31 100644
x11_window = x11_find_toplevel_for_xid( this->ctx->dpy, x11_window );
wlserver_x11_surface_info *x11_surface = lookup_x11_surface_info_from_xid( this, x11_window );
@@ -813,7 +829,11 @@ void gamescope_xwayland_server_t::handle_override_window_content( struct wl_clie
@@ -813,7 +827,11 @@ void gamescope_xwayland_server_t::handle_override_window_content( struct wl_clie
if ( content_overrides.count( x11_window ) ) {
if ( content_overrides[x11_window]->gamescope_swapchain == gamescope_swapchain_resource )
@@ -44,7 +42,7 @@ index 9a027a2..e6d8e31 100644
#ifdef GAMESCOPE_SWAPCHAIN_DEBUG
wl_log.infof( "handle_override_window_content: (2) DESTROYING x11_window: 0x%x old_swapchain: %p new_swapchain: %p", x11_window, content_overrides[x11_window]->gamescope_swapchain, gamescope_swapchain_resource );
#endif
@@ -830,6 +850,8 @@ void gamescope_xwayland_server_t::handle_override_window_content( struct wl_clie
@@ -830,6 +848,8 @@ void gamescope_xwayland_server_t::handle_override_window_content( struct wl_clie
co->surface = surface;
co->x11_window = x11_window;
co->gamescope_swapchain = gamescope_swapchain_resource;
@@ -2,12 +2,11 @@ diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index 1b85e63..370661d 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -2977,6 +2977,9 @@ namespace gamescope
@@ -2977,6 +2977,8 @@ namespace gamescope
LogDisplayError( "Failed to read events on input thread", m_pBackend->GetDisplay() );
abort();
}
+
+ // Reading also queues releases and presentation feedback for steamcompmgr.
+ nudge_steamcompmgr();
}
}
@@ -36,12 +36,11 @@ index 22aa907..0aef598 100644
void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, steamcompmgr_win_t *w, ResListEntry_t& reslistentry)
{
struct wlr_buffer *buf = reslistentry.buf;
@@ -8602,7 +8629,11 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
@@ -8602,7 +8629,10 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
struct wlr_dmabuf_attributes dmabuf = {0};
if ( wlr_buffer_get_dmabuf( buf, &dmabuf ) )
{
- fence = dup( dmabuf.fd[0] );
+ // A finished buffer needs no fence of its own.
+ if ( cv_commit_ready_check && commit_fence_ready_now( dmabuf.fd[0] ) )
+ bKnownReady = true;
+ else
@@ -49,7 +48,7 @@ index 22aa907..0aef598 100644
}
else
{
@@ -8610,11 +8641,22 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
@@ -8610,11 +8640,22 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
}
}
@@ -72,12 +71,11 @@ index 22aa907..0aef598 100644
else
g_ImageWaiter.AddWaitable( newCommit.get() );
}
@@ -9400,6 +9442,13 @@ void steamcompmgr_check_xdg(bool vblank, uint64_t vblank_idx)
@@ -9400,6 +9441,12 @@ void steamcompmgr_check_xdg(bool vblank, uint64_t vblank_idx)
}
check_new_xdg_res();
+
+ // Commits marked done at import: handle them now rather than on the next wake. FIFO commits still wait for a vblank.
+ if ( s_bXdgCommitsDoneAtImport )
+ {
+ s_bXdgCommitsDoneAtImport = false;
@@ -86,12 +84,11 @@ index 22aa907..0aef598 100644
}
void update_edid_prop()
@@ -10512,6 +10561,14 @@ steamcompmgr_main(int argc, char **argv)
@@ -10512,6 +10559,13 @@ steamcompmgr_main(int argc, char **argv)
gamescope_xwayland_server_t *server = NULL;
for (size_t i = 0; (server = wlserver_get_xwayland_server(i)); i++)
check_new_xwayland_res(server->ctx.get());
+
+ // Commits marked done at import: handle them now rather than on the next wake. FIFO commits still wait for a vblank.
+ if ( s_bXwaylandCommitsDoneAtImport )
+ {
+ s_bXwaylandCommitsDoneAtImport = false;
@@ -69,11 +69,10 @@ index 0aef598..1473148 100644
gamescope::ConVar<bool> cv_commit_ready_check( "commit_ready_check", true, "Check a new commit's fence at import; a finished frame is marked done in the same pass instead of through the image waiter." );
// Set when update_wayland_res marks a commit done itself, so the main loop handles it in the same pass.
@@ -8519,6 +8522,16 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
@@ -8519,6 +8522,15 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
uMangoMsgType = pMangoFocus->externalOverlayWindow->uMangoappMsgType;
}
+ // The commits the typed stream of connector 0 counts, whether or not a mangoapp runs.
+ bool bDroidDeckHudFrame = false;
+ if ( pUpscaleFocus && !w->isSteamStreamingClient )
+ bDroidDeckHudFrame = pUpscaleFocus->ulVirtualFocusKey == 0;
@@ -86,7 +85,7 @@ index 0aef598..1473148 100644
bool bValidPreemptiveScale = reslistentry.pAcquirePoint && pUpscaleFocus && cv_upscale_preemptive;
bool bPreemptiveUpscale = bValidPreemptiveScale && newCommit->ShouldPreemptivelyUpscale( pUpscaleFocus->eUpscaleFilter, pUpscaleFocus->eUpscaleScaler );
@@ -8650,7 +8663,7 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
@@ -8650,7 +8662,7 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
gpuvis_trace_printf( "pushing wait for commit %lu win %lx", newCommit->commitID, w->type == steamcompmgr_win_type_t::XWAYLAND ? w->xwayland().id : 0 );
{
@@ -95,18 +94,10 @@ index 0aef598..1473148 100644
if ( bKnownReady )
{
newCommit->Signal();
@@ -9865,6 +9878,109 @@ static void publish_mangoapp_connector_snapshots()
@@ -9865,6 +9877,100 @@ static void publish_mangoapp_connector_snapshots()
}
}
+// DroidDeck's own HUD reads the frame times DroidDeck's mangoapp shows from a shared file named by
+// DROIDDECK_HUD_FRAMES, also while no mangoapp runs. That mangoapp (Valve's 20260902.1 build) reads the
+// field at byte 16 of each message as its frame time, which is app_frametime_ns here: one time per
+// signalled commit of the connector's windows (mangoapp_nudge_app_frame). The file gets the same commits
+// of connector 0. Little-endian: 0 magic, 4 version, 8 capacity, 12 pid, 16 frames written (u64),
+// 24 info sequence (odd while the info is written), 28 output width, 32 height, 36 refresh mHz, 40 Steam
+// focused, 44 engine (40 bytes), then from 128 one { frametime ns, monotonic time ns } pair per frame,
+// a ring of capacity.
+static constexpr uint32_t k_uDroidDeckHudFramesMagic = 0x46484444;
+static constexpr uint32_t k_uDroidDeckHudFramesVersion = 1;
+static constexpr uint32_t k_uDroidDeckHudFramesCapacity = 1024;
@@ -157,7 +148,6 @@ index 0aef598..1473148 100644
+ return droiddeck_hud_frames_map() != nullptr;
+}
+
+// Signal() runs on the image waiter thread or, for a frame finished at import, on steamcompmgr's.
+void droiddeck_hud_app_frame( uint64_t ulNow )
+{
+ std::unique_lock lock( s_DroidDeckHudFramesMutex );
@@ -205,7 +195,7 @@ index 0aef598..1473148 100644
// mangohudctl posts one control message for every instance to act on.
static void relay_mangoapp_control()
{
@@ -10843,6 +10959,7 @@ steamcompmgr_main(int argc, char **argv)
@@ -10843,6 +10949,7 @@ steamcompmgr_main(int argc, char **argv)
publish_mangoapp_snapshot();
publish_mangoapp_connector_snapshots();
@@ -0,0 +1,43 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -4220,6 +4220,21 @@ static bool is_same_app_override_decorat
( candidate->hwndStyleEx & uDecorationStyle ) == uDecorationStyle;
}
+// Windows keeps a topmost window above every window that is neither topmost nor owned by it,
+// so another process's splash cannot cover a topmost sign-in (the EA app's, over its Steam launcher).
+static bool is_stacked_below_focus( steamcompmgr_win_t *candidate, steamcompmgr_win_t *focus )
+{
+ if ( candidate->pid <= 0 || focus->pid <= 0 || candidate->pid == focus->pid ||
+ !candidate->hasHwndStyleEx || !focus->hasHwndStyleEx )
+ return false;
+
+ if ( candidate->type == steamcompmgr_win_type_t::XWAYLAND && focus->type == steamcompmgr_win_type_t::XWAYLAND &&
+ candidate->xwayland().transientFor == focus->xwayland().id )
+ return false;
+
+ return ( focus->hwndStyleEx & WS_EX_TOPMOST ) && !( candidate->hwndStyleEx & WS_EX_TOPMOST );
+}
+
static bool is_good_override_candidate( steamcompmgr_win_t *override, steamcompmgr_win_t* focus )
{
// Some Chrome/Edge dropdowns (ie. FH5 xbox login) will automatically close themselves if you
@@ -4235,6 +4250,9 @@ static bool is_good_override_candidate(
if ( is_same_app_override_decoration( override, focus ) )
return false;
+ if ( is_stacked_below_focus( override, focus ) )
+ return false;
+
if ( override->pid != focus->pid && !windows_share_app( override, focus ) )
return false;
@@ -5836,6 +5854,7 @@ map_win(xwayland_ctx_t* ctx, Window id,
w->isSteamStreamingClient = get_prop(ctx, w->xwayland().id, ctx->atoms.steamStreamingClientAtom, 0);
w->isSteamStreamingClientVideo = get_prop(ctx, w->xwayland().id, ctx->atoms.steamStreamingClientVideoAtom, 0);
w->steamAppID = get_prop(ctx, w->xwayland().id, ctx->atoms.gameAtom, 0);
+ w->hwndStyleEx = get_prop(ctx, w->xwayland().id, ctx->atoms.wineHwndStyleEx, 0, &w->hasHwndStyleEx);
if ( steamMode == true )
{
@@ -0,0 +1,30 @@
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -3062,8 +3062,13 @@
#endif
gamescope::ConVar<int> cv_cursor_composite{ "cursor_composite", 1, "0 = Never composite a cursor. 1 = Composite cursor when not nested. 2 = Always composite a cursor manually" };
+static gamescope::ConVar<int> cv_relative_mouse( "relative_mouse", 0,
+"0 = Leave it to the game and the nested hints. 1 = Send host pointer motion as relative movement, for games that confine the cursor and warp it back to read movement. 2 = Never go relative." );
bool ShouldDrawCursor()
{
+ if ( cv_relative_mouse.Get() == 1 )
+ return true;
+
global_focus_t *pFocus = GetCurrentFocus();
gamescope::INestedHints *pNestedHints = pFocus ? pFocus->GetNestedHints() : nullptr;
return gamescope::CursorShouldBeComposited( cv_cursor_composite.Get(), g_bForceRelativeMouse,
@@ -10810,7 +10815,12 @@
const bool bExcludedAppId = uAppId && gamescope::Algorithm::Contains( s_uRelativeMouseFilteredAppids, uAppId );
- const bool bRelativeMouseMode = bImageEmpty && bHasPointerConstraint && !bExcludedAppId;
+ const int nRelativeMouse = cv_relative_mouse.Get();
+ const bool bForcedRelativeMouse = nRelativeMouse == 1 && !window_is_steam( pPaintFocus->inputFocusWindow );
+
+ const bool bRelativeMouseMode = nRelativeMouse == 2
+ ? false
+ : ( bForcedRelativeMouse || ( bImageEmpty && bHasPointerConstraint && !bExcludedAppId ) );
pPaintFocus->GetNestedHints()->SetRelativeMouseMode( bRelativeMouseMode );
}
@@ -0,0 +1,12 @@
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -10804,7 +10804,8 @@
( pPaintFocus->cursor && pPaintFocus->cursor->imageEmpty() ) &&
( !window_is_steam( pPaintFocus->inputFocusWindow ) );
- const bool bHasPointerConstraint = pPaintFocus->cursor && pPaintFocus->cursor->IsConstrained();
+ const bool bHasPointerConstraint = pPaintFocus->cursor &&
+ ( pPaintFocus->cursor->IsConstrained() || wlserver.HasMouseConstraint() );
uint32_t uAppId = pPaintFocus->inputFocusWindow
? pPaintFocus->inputFocusWindow->appID
@@ -0,0 +1,145 @@
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index 953765a..572fb0e 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -464,6 +464,7 @@ namespace gamescope
virtual void SetCursorImage( std::shared_ptr<INestedHints::CursorInfo> info ) override;
virtual void SetRelativeMouseMode( bool bRelative ) override;
+ virtual void SetCursorPositionHint( double flX, double flY ) override;
virtual void SetVisible( bool bVisible ) override;
virtual void SetTitle( std::shared_ptr<std::string> szTitle ) override;
virtual void SetIcon( std::shared_ptr<std::vector<uint32_t>> uIconPixels ) override;
@@ -719,6 +720,7 @@ namespace gamescope
void SetCursorImage( std::shared_ptr<INestedHints::CursorInfo> info );
void SetRelativeMouseMode( wl_surface *pSurface, bool bRelative );
+ void SetCursorPositionHint( wl_fixed_t fSurfaceX, wl_fixed_t fSurfaceY );
void UpdateCursor();
friend CWaylandConnector;
@@ -1270,6 +1272,16 @@ namespace gamescope
// TODO: Do more tracking across multiple connectors, and activity here if we ever want to use this.
m_pBackend->SetRelativeMouseMode( m_Planes[0].GetSurface(), bRelative );
}
+ void CWaylandConnector::SetCursorPositionHint( double flX, double flY )
+ {
+ auto oState = m_Planes[0].GetCurrentState();
+ if ( !oState || !oState->uFractionalScale )
+ return;
+
+ const double flSurfaceX = ( flX * g_nOutputWidth - oState->nDestX ) * 120.0 / oState->uFractionalScale;
+ const double flSurfaceY = ( flY * g_nOutputHeight - oState->nDestY ) * 120.0 / oState->uFractionalScale;
+ m_pBackend->SetCursorPositionHint( wl_fixed_from_double( flSurfaceX ), wl_fixed_from_double( flSurfaceY ) );
+ }
void CWaylandConnector::SetVisible( bool bVisible )
{
if ( m_bVisible == bVisible )
@@ -2484,6 +2496,15 @@ namespace gamescope
UpdateCursor();
}
+ void CWaylandBackend::SetCursorPositionHint( wl_fixed_t fSurfaceX, wl_fixed_t fSurfaceY )
+ {
+ if ( !m_pLockedPointer )
+ return;
+
+ zwp_locked_pointer_v1_set_cursor_position_hint( m_pLockedPointer, fSurfaceX, fSurfaceY );
+ wl_surface_commit( m_pLockedSurface );
+ }
+
void CWaylandBackend::SetRelativeMouseMode( wl_surface *pSurface, bool bRelative )
{
if ( !m_pPointer )
diff --git a/src/backend.h b/src/backend.h
index d264917..37b936e 100644
--- a/src/backend.h
+++ b/src/backend.h
@@ -271,6 +271,7 @@ namespace gamescope
virtual void SetCursorImage( std::shared_ptr<CursorInfo> info ) = 0;
virtual void SetRelativeMouseMode( bool bRelative ) = 0;
+ virtual void SetCursorPositionHint( double flX, double flY ) {}
virtual void SetVisible( bool bVisible ) = 0;
virtual void SetTitle( std::shared_ptr<std::string> szTitle ) = 0;
virtual void SetIcon( std::shared_ptr<std::vector<uint32_t>> uIconPixels ) = 0;
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index f1346e5..2c92afe 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -2078,6 +2078,18 @@ void MouseCursor::UpdatePosition()
}
}
+void MouseCursor::QueryRootPosition( int *pX, int *pY )
+{
+ Window root_ret, child_ret;
+ int win_x = 0, win_y = 0;
+ unsigned int mask;
+ *pX = m_x;
+ *pY = m_y;
+ XQueryPointer( m_ctx->dpy, DefaultRootWindow( m_ctx->dpy ), &root_ret, &child_ret, pX, pY, &win_x, &win_y, &mask );
+}
+
+static bool relative_mouse_forced();
+
void MouseCursor::checkSuspension()
{
getTexture();
@@ -2085,7 +2097,12 @@ void MouseCursor::checkSuspension()
if ( ShouldDrawCursor() )
{
const bool suspended = int64_t( get_time_in_nanos() ) - int64_t( wlserver.ulLastMovedCursorTime ) > int64_t( cursorHideTime );
- if (!wlserver.bCursorHidden && suspended) {
+ if ( relative_mouse_forced() && wlserver.bCursorHidden )
+ {
+ wlserver.bCursorHidden = false;
+ hasRepaintNonBasePlane = true;
+ }
+ if (!wlserver.bCursorHidden && suspended && !relative_mouse_forced()) {
wlserver.bCursorHidden = true;
steamcompmgr_win_t *window = m_ctx->focus.inputFocusWindow;
@@ -3064,6 +3081,11 @@ static void paint_pipewire()
gamescope::ConVar<int> cv_cursor_composite{ "cursor_composite", 1, "0 = Never composite a cursor. 1 = Composite cursor when not nested. 2 = Always composite a cursor manually" };
static gamescope::ConVar<int> cv_relative_mouse( "relative_mouse", 0,
"0 = Leave it to the game and the nested hints. 1 = Send host pointer motion as relative movement, for games that confine the cursor and warp it back to read movement. 2 = Never go relative." );
+static bool relative_mouse_forced()
+{
+ return cv_relative_mouse.Get() == 1;
+}
+
bool ShouldDrawCursor()
{
if ( cv_relative_mouse.Get() == 1 )
@@ -10828,6 +10850,18 @@ steamcompmgr_main(int argc, char **argv)
? false
: ( bForcedRelativeMouse || ( bImageEmpty && bHasPointerConstraint && !bExcludedAppId ) );
+ static bool s_bRelativeMouseMode = false;
+ if ( s_bRelativeMouseMode && !bRelativeMouseMode && pPaintFocus->cursor &&
+ g_nOutputWidth && g_nOutputHeight && focusedWindowScaleX > 0.0f && focusedWindowScaleY > 0.0f )
+ {
+ int nRootX, nRootY;
+ pPaintFocus->cursor->QueryRootPosition( &nRootX, &nRootY );
+ pPaintFocus->GetNestedHints()->SetCursorPositionHint(
+ ( nRootX / focusedWindowScaleX - focusedWindowOffsetX ) / g_nOutputWidth,
+ ( nRootY / focusedWindowScaleY - focusedWindowOffsetY ) / g_nOutputHeight );
+ }
+ s_bRelativeMouseMode = bRelativeMouseMode;
+
pPaintFocus->GetNestedHints()->SetRelativeMouseMode( bRelativeMouseMode );
}
diff --git a/src/steamcompmgr.hpp b/src/steamcompmgr.hpp
index 7a7119f..ff54d8e 100644
--- a/src/steamcompmgr.hpp
+++ b/src/steamcompmgr.hpp
@@ -85,6 +85,7 @@ public:
}
void UpdatePosition();
+ void QueryRootPosition( int *pX, int *pY );
bool isHidden() { return wlserver.bCursorHidden || m_imageEmpty; }
bool imageEmpty() const { return m_imageEmpty; }
@@ -0,0 +1,94 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index 2c92afe..17bae3a 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -4662,6 +4662,49 @@ static void set_wm_state( xwayland_ctx_t *ctx, Window win, uint32_t state )
sizeof(wmState) / sizeof(wmState[0]));
}
+static void
+fit_root_to_focus_window( xwayland_ctx_t *ctx )
+{
+ steamcompmgr_win_t *w = ctx->focus.focusWindow;
+ const bool bGame = w && !window_is_steam( w );
+ const int nWindowX = bGame ? w->xwayland().a.x : 0;
+ const int nWindowY = bGame ? w->xwayland().a.y : 0;
+ const int nWindowWidth = bGame ? w->xwayland().a.width : 0;
+ const int nWindowHeight = bGame ? w->xwayland().a.height : 0;
+ const int nBaseWidth = ctx->nFitRestoreWidth ? ctx->nFitRestoreWidth : ctx->root_width;
+ const int nBaseHeight = ctx->nFitRestoreWidth ? ctx->nFitRestoreHeight : ctx->root_height;
+ const bool bCoversBase = nWindowX == 0 && nWindowY == 0 && nWindowWidth >= nBaseWidth && nWindowHeight >= nBaseHeight;
+ const bool bPlausible = nWindowWidth <= 8192 && nWindowHeight <= 8192;
+
+ int nWidth = 0;
+ int nHeight = 0;
+ if ( bGame && bCoversBase && bPlausible && ( nWindowWidth > nBaseWidth || nWindowHeight > nBaseHeight ) )
+ {
+ if ( !ctx->nFitRestoreWidth )
+ {
+ ctx->nFitRestoreWidth = ctx->root_width;
+ ctx->nFitRestoreHeight = ctx->root_height;
+ }
+ nWidth = nWindowWidth;
+ nHeight = nWindowHeight;
+ }
+ else if ( ctx->nFitRestoreWidth && nWindowWidth <= ctx->nFitRestoreWidth && nWindowHeight <= ctx->nFitRestoreHeight )
+ {
+ nWidth = ctx->nFitRestoreWidth;
+ nHeight = ctx->nFitRestoreHeight;
+ ctx->nFitRestoreWidth = 0;
+ ctx->nFitRestoreHeight = 0;
+ }
+
+ if ( !nWidth || ( nWidth == ctx->root_width && nHeight == ctx->root_height ) )
+ return;
+
+ ctx->bFitPending = true;
+ wlserver_lock();
+ wlserver_set_xwayland_server_mode( ctx->xwayland_server->get_index(), nWidth, nHeight, g_nOutputRefresh );
+ wlserver_unlock();
+}
+
void xwayland_ctx_t::DetermineAndApplyFocus( const std::vector< steamcompmgr_win_t* > &vecPossibleFocusWindows )
{
xwayland_ctx_t *ctx = this;
@@ -4736,6 +4779,8 @@ void xwayland_ctx_t::DetermineAndApplyFocus( const std::vector< steamcompmgr_win
inputFocus = ctx->focus.focusWindow;
}
+ fit_root_to_focus_window( ctx );
+
if ( ctx->focus.focusWindow )
{
if ( prevFocusWindow != ctx->focus.focusWindow )
@@ -5001,7 +5046,7 @@ void xwayland_ctx_t::DetermineAndApplyFocus( const std::vector< steamcompmgr_win
fs_width = ctx->root_width * steam_height_scale;
}
- if ( w->GetGeometry().nWidth != fs_width || w->GetGeometry().nHeight != fs_height || globalScaleRatio != 1.0f )
+ if ( !ctx->bFitPending && ( w->GetGeometry().nWidth != fs_width || w->GetGeometry().nHeight != fs_height || globalScaleRatio != 1.0f ) )
XResizeWindow(ctx->dpy, ctx->focus.focusWindow->xwayland().id, fs_width, fs_height);
}
else
@@ -6232,6 +6277,7 @@ configure_win(xwayland_ctx_t *ctx, XConfigureEvent *ce)
{
if (ce->window == ctx->root)
{
+ ctx->bFitPending = false;
ctx->root_width = ce->width;
ctx->root_height = ce->height;
MakeFocusDirty();
diff --git a/src/xwayland_ctx.hpp b/src/xwayland_ctx.hpp
index 3a75650..15c2e6b 100644
--- a/src/xwayland_ctx.hpp
+++ b/src/xwayland_ctx.hpp
@@ -87,6 +87,9 @@ struct xwayland_ctx_t final : public gamescope::IWaitable
Window ourWindow;
focus_t focus;
+ int nFitRestoreWidth = 0;
+ int nFitRestoreHeight = 0;
+ bool bFitPending = false;
Window currentKeyboardFocusWindow;
Window focusControlWindow;
@@ -0,0 +1,216 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index 17bae3a..c468fb3 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -32,6 +32,7 @@
#include "backend.h"
#include "gamescope_shared.h"
#include "xwayland_ctx.hpp"
+#include <cmath>
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xcursor/Xcursor.h>
@@ -2088,6 +2089,7 @@ void MouseCursor::QueryRootPosition( int *pX, int *pY )
XQueryPointer( m_ctx->dpy, DefaultRootWindow( m_ctx->dpy ), &root_ret, &child_ret, pX, pY, &win_x, &win_y, &mask );
}
+static bool s_bFollowClientPointer = false;
static bool relative_mouse_forced();
void MouseCursor::checkSuspension()
@@ -3083,12 +3085,89 @@ static gamescope::ConVar<int> cv_relative_mouse( "relative_mouse", 0,
"0 = Leave it to the game and the nested hints. 1 = Send host pointer motion as relative movement, for games that confine the cursor and warp it back to read movement. 2 = Never go relative." );
static bool relative_mouse_forced()
{
- return cv_relative_mouse.Get() == 1;
+ return cv_relative_mouse.Get() == 1 || s_bFollowClientPointer;
+}
+
+static void update_client_pointer_follow( global_focus_t *pFocus, bool bAllowed )
+{
+ static int s_nAwayFrames = 0;
+ static int s_nQuietFrames = 0;
+ static uint64_t s_ulLastAway = 0;
+ static double s_flLastX = 0.0;
+ static double s_flLastY = 0.0;
+
+ int nRootX = 0;
+ int nRootY = 0;
+ if ( bAllowed && pFocus->cursor )
+ pFocus->cursor->QueryRootPosition( &nRootX, &nRootY );
+ else
+ bAllowed = false;
+
+ wlserver_lock();
+ const double flX = wlserver.mouse_surface_cursorx;
+ const double flY = wlserver.mouse_surface_cursory;
+ if ( !bAllowed )
+ {
+ s_nAwayFrames = 0;
+ s_bFollowClientPointer = false;
+ wlserver.bFollowClientPointer = false;
+ }
+ else if ( !s_bFollowClientPointer )
+ {
+ const bool bMoved = flX != s_flLastX || flY != s_flLastY;
+ if ( bMoved && ( std::abs( nRootX - flX ) > 48.0 || std::abs( nRootY - flY ) > 48.0 ) )
+ {
+ const uint64_t ulNow = get_time_in_nanos();
+ if ( ulNow - s_ulLastAway > 500'000'000ul )
+ s_nAwayFrames = 0;
+ s_ulLastAway = ulNow;
+ s_nAwayFrames++;
+ }
+
+ if ( s_nAwayFrames >= 3 )
+ {
+ s_nAwayFrames = 0;
+ s_nQuietFrames = 0;
+ s_bFollowClientPointer = true;
+ wlserver.bFollowClientPointer = true;
+ wlserver.flFollowDX = 0.0;
+ wlserver.flFollowDY = 0.0;
+ wlserver_mousewarp( nRootX, nRootY, 0, true );
+ }
+ }
+ else
+ {
+ const bool bWarped = std::abs( nRootX - flX ) > 2.0 || std::abs( nRootY - flY ) > 2.0;
+ const double flDX = std::trunc( wlserver.flFollowDX );
+ const double flDY = std::trunc( wlserver.flFollowDY );
+ if ( bWarped )
+ s_nQuietFrames = 0;
+ else if ( flDX != 0.0 || flDY != 0.0 )
+ s_nQuietFrames++;
+
+ if ( flDX != 0.0 || flDY != 0.0 || bWarped )
+ {
+ wlserver.flFollowDX -= flDX;
+ wlserver.flFollowDY -= flDY;
+ wlserver_mousewarp( nRootX, nRootY, 0, true );
+ if ( flDX != 0.0 || flDY != 0.0 )
+ wlserver_mousewarp( nRootX + flDX, nRootY + flDY, 0, true );
+ }
+
+ if ( s_nQuietFrames >= 60 )
+ {
+ s_bFollowClientPointer = false;
+ wlserver.bFollowClientPointer = false;
+ }
+ }
+ s_flLastX = wlserver.mouse_surface_cursorx;
+ s_flLastY = wlserver.mouse_surface_cursory;
+ wlserver_unlock();
}
bool ShouldDrawCursor()
{
- if ( cv_relative_mouse.Get() == 1 )
+ if ( relative_mouse_forced() )
return true;
global_focus_t *pFocus = GetCurrentFocus();
@@ -10892,9 +10971,15 @@ steamcompmgr_main(int argc, char **argv)
const int nRelativeMouse = cv_relative_mouse.Get();
const bool bForcedRelativeMouse = nRelativeMouse == 1 && !window_is_steam( pPaintFocus->inputFocusWindow );
+ if ( vblank )
+ {
+ update_client_pointer_follow( pPaintFocus,
+ nRelativeMouse != 2 && !bExcludedAppId && !bHasPointerConstraint && !window_is_steam( pPaintFocus->inputFocusWindow ) );
+ }
+
const bool bRelativeMouseMode = nRelativeMouse == 2
? false
- : ( bForcedRelativeMouse || ( bImageEmpty && bHasPointerConstraint && !bExcludedAppId ) );
+ : ( bForcedRelativeMouse || s_bFollowClientPointer || ( bImageEmpty && bHasPointerConstraint && !bExcludedAppId ) );
static bool s_bRelativeMouseMode = false;
if ( s_bRelativeMouseMode && !bRelativeMouseMode && pPaintFocus->cursor &&
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
index 5733871..cc75f8a 100644
--- a/src/wlserver.cpp
+++ b/src/wlserver.cpp
@@ -1,3 +1,4 @@
+#include <cmath>
#include <xkbcommon/xkbcommon-keysyms.h>
#define _GNU_SOURCE 1
@@ -3086,6 +3087,16 @@ void wlserver_mousemotion( double dx, double dy, uint32_t time )
wlserver_perform_rel_pointer_motion( dx, dy );
+ if ( wlserver.bFollowClientPointer )
+ {
+ wlserver.flFollowDX += dx;
+ wlserver.flFollowDY += dy;
+ wlserver.ulLastMovedCursorTime = get_time_in_nanos();
+ wlserver.bCursorHidden = !wlserver.bCursorHasImage;
+ wlr_seat_pointer_notify_frame( wlserver.wlr.seat );
+ return;
+ }
+
if ( !wlserver_apply_constraint( &dx, &dy ) )
{
wlr_seat_pointer_notify_frame( wlserver.wlr.seat );
@@ -3110,10 +3121,18 @@ void wlserver_mousemotion( double dx, double dy, uint32_t time )
wlr_seat_pointer_notify_frame( wlserver.wlr.seat );
}
-void wlserver_mousewarp( double x, double y, uint32_t time, bool bSynthetic )
+void wlserver_mousewarp( double x, double y, uint32_t time, bool bSynthetic, bool bFromTouch )
{
assert( wlserver_is_lock_held() );
+ if ( !bSynthetic && wlserver.bFollowClientPointer )
+ return;
+
+ const double flStepX = x - wlserver.mouse_surface_cursorx;
+ const double flStepY = y - wlserver.mouse_surface_cursory;
+ if ( !bSynthetic && !bFromTouch && ( flStepX != 0.0 || flStepY != 0.0 ) && std::abs( flStepX ) < 256.0 && std::abs( flStepY ) < 256.0 )
+ wlserver_perform_rel_pointer_motion( flStepX, flStepY );
+
wlserver.mouse_surface_cursorx = x;
wlserver.mouse_surface_cursory = y;
@@ -3304,7 +3323,7 @@ void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool
{
g_bPendingTouchMovement = true;
- wlserver_mousewarp( tx, ty, time, false );
+ wlserver_mousewarp( tx, ty, time, false, !bAlwaysWarpCursor );
}
}
@@ -3352,7 +3371,7 @@ void wlserver_touchdown( double x, double y, int touch_id, uint32_t time, gamesc
if ( eMode != gamescope::TouchClickModes::Trackpad )
{
- wlserver_mousewarp( tx, ty, time, false );
+ wlserver_mousewarp( tx, ty, time, false, true );
}
uint32_t button = TouchClickModeToLinuxButton( eMode );
diff --git a/src/wlserver.hpp b/src/wlserver.hpp
index 79a0723..ca8d015 100644
--- a/src/wlserver.hpp
+++ b/src/wlserver.hpp
@@ -168,6 +168,9 @@ struct wlserver_t {
uint64_t ulLastMovedCursorTime = 0;
bool bCursorHidden = true;
bool bCursorHasImage = true;
+ bool bFollowClientPointer = false;
+ double flFollowDX = 0.0;
+ double flFollowDY = 0.0;
bool button_held[ WLSERVER_BUTTON_COUNT ];
std::set <uint32_t> touch_down_ids;
@@ -271,7 +274,7 @@ void wlserver_clear_dropdowns();
void wlserver_notify_dropdown( struct wlr_surface *wlrsurface, int nX, int nY );
void wlserver_mousemotion( double x, double y, uint32_t time );
void wlserver_mousehide();
-void wlserver_mousewarp( double x, double y, uint32_t time, bool bSynthetic );
+void wlserver_mousewarp( double x, double y, uint32_t time, bool bSynthetic, bool bFromTouch = false );
void wlserver_mousebutton( int button, bool press, uint32_t time );
void wlserver_mousewheel( double x, double y, uint32_t time );
bool wlserver_input_held();
@@ -0,0 +1,254 @@
diff --git a/src/Backends/SDLBackend.cpp b/src/Backends/SDLBackend.cpp
index 58af150..b050183 100644
--- a/src/Backends/SDLBackend.cpp
+++ b/src/Backends/SDLBackend.cpp
@@ -51,6 +51,7 @@ namespace gamescope
GAMESCOPE_SDL_EVENT_VISIBLE,
GAMESCOPE_SDL_EVENT_GRAB,
GAMESCOPE_SDL_EVENT_CURSOR,
+ GAMESCOPE_SDL_EVENT_WINDOW_MODE,
GAMESCOPE_SDL_EVENT_COUNT,
};
@@ -114,6 +115,7 @@ namespace gamescope
virtual void SetCursorImage( std::shared_ptr<INestedHints::CursorInfo> info ) override;
virtual void SetRelativeMouseMode( bool bRelative ) override;
virtual void SetVisible( bool bVisible ) override;
+ virtual void SetWindowMode( bool bFullscreen, int nWidth, int nHeight ) override;
virtual void SetTitle( std::shared_ptr<std::string> szTitle ) override;
virtual void SetIcon( std::shared_ptr<std::vector<uint32_t>> uIconPixels ) override;
virtual void SetSelection( std::shared_ptr<std::string> szContents, GamescopeSelection eSelection ) override;
@@ -179,6 +181,7 @@ namespace gamescope
void SetCursorImage( std::shared_ptr<INestedHints::CursorInfo> info );
void SetRelativeMouseMode( bool bRelative );
void SetVisible( bool bVisible );
+ void SetWindowMode( bool bFullscreen, int nWidth, int nHeight );
void SetTitle( std::shared_ptr<std::string> szTitle );
void SetIcon( std::shared_ptr<std::vector<uint32_t>> uIconPixels );
void SetSelection( std::shared_ptr<std::string> szContents, GamescopeSelection eSelection );
@@ -193,6 +196,12 @@ namespace gamescope
bool m_bShown = false;
CSDLConnector m_Connector; // Window.
uint32_t m_uUserEventIdBase = 0u;
+ std::atomic<bool> m_bWantFullscreen = { false };
+ std::atomic<int> m_nWantWidth = { 0 };
+ std::atomic<int> m_nWantHeight = { 0 };
+ bool m_bAppliedFullscreen = false;
+ int m_nAppliedWidth = 0;
+ int m_nAppliedHeight = 0;
std::vector<const char *> m_pszInstanceExtensions;
std::thread m_SDLThread;
@@ -372,6 +381,10 @@ namespace gamescope
{
m_pBackend->SetVisible( bVisible );
}
+ void CSDLConnector::SetWindowMode( bool bFullscreen, int nWidth, int nHeight )
+ {
+ m_pBackend->SetWindowMode( bFullscreen, nWidth, nHeight );
+ }
void CSDLConnector::SetTitle( std::shared_ptr<std::string> szTitle )
{
m_pBackend->SetTitle( std::move( szTitle ) );
@@ -544,6 +557,13 @@ namespace gamescope
m_bApplicationVisible = bVisible;
PushUserEvent( GAMESCOPE_SDL_EVENT_VISIBLE );
}
+ void CSDLBackend::SetWindowMode( bool bFullscreen, int nWidth, int nHeight )
+ {
+ m_bWantFullscreen = bFullscreen;
+ m_nWantWidth = nWidth;
+ m_nWantHeight = nHeight;
+ PushUserEvent( GAMESCOPE_SDL_EVENT_WINDOW_MODE );
+ }
void CSDLBackend::SetTitle( std::shared_ptr<std::string> szTitle )
{
m_pApplicationTitle = szTitle;
@@ -894,6 +914,38 @@ namespace gamescope
}
}
}
+ else if ( event.type == GetUserEventIndex( GAMESCOPE_SDL_EVENT_WINDOW_MODE ) )
+ {
+ const bool bFullscreen = m_bWantFullscreen;
+ const int nWidth = bFullscreen ? 0 : m_nWantWidth.load();
+ const int nHeight = bFullscreen ? 0 : m_nWantHeight.load();
+
+ if ( bFullscreen != m_bAppliedFullscreen || nWidth != m_nAppliedWidth || nHeight != m_nAppliedHeight )
+ {
+ m_bAppliedFullscreen = bFullscreen;
+ m_nAppliedWidth = nWidth;
+ m_nAppliedHeight = nHeight;
+ g_bFullscreen = bFullscreen;
+ SDL_SetWindowFullscreen( m_Connector.GetSDLWindow(), bFullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0 );
+ if ( !bFullscreen )
+ {
+ static constexpr int k_nDesktopChromeHeight = 96;
+
+ SDL_Rect usable = {};
+ const int nDisplay = SDL_GetWindowDisplayIndex( m_Connector.GetSDLWindow() );
+ const bool bKnown = SDL_GetDisplayUsableBounds( nDisplay, &usable ) == 0;
+ if ( bKnown && ( nWidth > usable.w || nHeight + k_nDesktopChromeHeight > usable.h ) )
+ {
+ SDL_MaximizeWindow( m_Connector.GetSDLWindow() );
+ }
+ else
+ {
+ SDL_RestoreWindow( m_Connector.GetSDLWindow() );
+ SDL_SetWindowSize( m_Connector.GetSDLWindow(), nWidth, nHeight );
+ }
+ }
+ }
+ }
else if ( event.type == GetUserEventIndex( GAMESCOPE_SDL_EVENT_TITLE ) )
{
std::shared_ptr<std::string> pAppTitle = m_pApplicationTitle;
diff --git a/src/backend.h b/src/backend.h
index 37b936e..fbfa7c7 100644
--- a/src/backend.h
+++ b/src/backend.h
@@ -273,6 +273,7 @@ namespace gamescope
virtual void SetRelativeMouseMode( bool bRelative ) = 0;
virtual void SetCursorPositionHint( double flX, double flY ) {}
virtual void SetVisible( bool bVisible ) = 0;
+ virtual void SetWindowMode( bool bFullscreen, int nWidth, int nHeight ) {}
virtual void SetTitle( std::shared_ptr<std::string> szTitle ) = 0;
virtual void SetIcon( std::shared_ptr<std::vector<uint32_t>> uIconPixels ) = 0;
virtual void SetSelection( std::shared_ptr<std::string> szContents, GamescopeSelection eSelection ) = 0;
diff --git a/src/main.cpp b/src/main.cpp
index eef4264..8f0ddd3 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -73,6 +73,7 @@ const struct option *gamescope_options = (struct option[]){
{ "rt", no_argument, nullptr, 0 },
{ "prefer-vk-device", required_argument, 0 },
{ "expose-wayland", no_argument, 0 },
+ { "follow-game-window-mode", no_argument, 0 },
{ "mouse-sensitivity", required_argument, nullptr, 's' },
{ "mangoapp", no_argument, nullptr, 0 },
{ "adaptive-sync", no_argument, nullptr, 0 },
@@ -700,6 +701,7 @@ static void UpdateCompatEnvVars()
int g_nPreferredOutputWidth = 0;
int g_nPreferredOutputHeight = 0;
bool g_bExposeWayland = false;
+bool g_bFollowGameWindowMode = false;
const char *g_sOutputName = nullptr;
bool g_bDebugLayers = false;
bool g_bForceDisableColorMgmt = false;
@@ -838,6 +840,8 @@ int main(int argc, char **argv)
cv_adaptive_sync = true;
} else if (strcmp(opt_name, "expose-wayland") == 0) {
g_bExposeWayland = true;
+ } else if (strcmp(opt_name, "follow-game-window-mode") == 0) {
+ g_bFollowGameWindowMode = true;
} else if (strcmp(opt_name, "backend") == 0) {
eCurrentBackend = parse_backend_name( optarg );
} else if (strcmp(opt_name, "cursor-scale-height") == 0) {
diff --git a/src/main.hpp b/src/main.hpp
index b2a169f..48929f2 100644
--- a/src/main.hpp
+++ b/src/main.hpp
@@ -134,6 +134,7 @@ extern int g_upscaleFilterSharpness;
extern bool g_bBorderlessOutputWindow;
extern bool g_bExposeWayland;
+extern bool g_bFollowGameWindowMode;
extern bool g_bRt;
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index c468fb3..3188b74 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -4741,6 +4741,54 @@ static void set_wm_state( xwayland_ctx_t *ctx, Window win, uint32_t state )
sizeof(wmState) / sizeof(wmState[0]));
}
+static bool
+window_offers_frame_controls( xwayland_ctx_t *ctx, steamcompmgr_win_t *w )
+{
+ static constexpr unsigned long k_ulMotifFunctions = 1ul << 0;
+ static constexpr unsigned long k_ulMotifMinimize = 1ul << 3;
+ static constexpr unsigned long k_ulMotifMaximize = 1ul << 4;
+ static constexpr unsigned long k_ulMotifDecorations = 1ul << 1;
+
+ Atom type;
+ int format;
+ unsigned long nitems;
+ unsigned long bytesAfter;
+ unsigned char *data = nullptr;
+ if ( XGetWindowProperty( ctx->dpy, w->xwayland().id, ctx->atoms.motifWMHintsAtom, 0, 3, false,
+ AnyPropertyType, &type, &format, &nitems, &bytesAfter, &data ) != Success )
+ return false;
+
+ bool bControls = false;
+ if ( data && format == 32 && nitems >= 3 )
+ {
+ const long *hints = (const long *)data;
+ bControls = ( ( hints[0] & k_ulMotifFunctions ) && ( hints[1] & ( k_ulMotifMinimize | k_ulMotifMaximize ) ) ) ||
+ ( ( hints[0] & k_ulMotifDecorations ) && hints[2] );
+ }
+ if ( data )
+ XFree( data );
+ return bControls;
+}
+
+static void
+apply_game_window_mode( global_focus_t *pFocus )
+{
+ static constexpr int k_nSmallestFollowedWindow = 64;
+
+ steamcompmgr_win_t *w = pFocus->focusWindow;
+ if ( !g_bFollowGameWindowMode || !pFocus->GetNestedHints() || !w || w->type != steamcompmgr_win_type_t::XWAYLAND )
+ return;
+
+ xwayland_ctx_t *ctx = w->xwayland().ctx;
+ const XWindowAttributes &a = w->xwayland().a;
+ if ( a.width < k_nSmallestFollowedWindow || a.height < k_nSmallestFollowedWindow )
+ return;
+
+ const bool bCoversScreen = a.x == 0 && a.y == 0 && a.width >= ctx->root_width && a.height >= ctx->root_height;
+ const bool bFullscreen = w->isFullscreen || ( w->appID && bCoversScreen && !window_offers_frame_controls( ctx, w ) );
+ pFocus->GetNestedHints()->SetWindowMode( bFullscreen, a.width, a.height );
+}
+
static void
fit_root_to_focus_window( xwayland_ctx_t *ctx )
{
@@ -5739,6 +5787,7 @@ determine_and_apply_focus( global_focus_t *pFocus )
if ( pFocus->focusWindow )
{
pFocus->GetNestedHints()->SetVisible( true );
+ apply_game_window_mode( pFocus );
if ( previousLocalFocus.focusWindow != pFocus->focusWindow )
{
pFocus->GetNestedHints()->SetTitle( pFocus->focusWindow->title );
@@ -7083,6 +7132,8 @@ static inline float santitize_float( float f )
static void
handle_property_notify(xwayland_ctx_t *ctx, XPropertyEvent *ev)
{
+ if (ev->atom == ctx->atoms.motifWMHintsAtom)
+ MakeFocusDirty();
/* check if Trans property was changed */
if (ev->atom == ctx->atoms.opacityAtom)
{
@@ -9216,6 +9267,7 @@ void init_xwayland_ctx(uint32_t serverId, gamescope_xwayland_server_t *xwayland_
ctx->atoms.winNormalAtom = XInternAtom(ctx->dpy, "_NET_WM_WINDOW_TYPE_NORMAL", false);
ctx->atoms.sizeHintsAtom = XInternAtom(ctx->dpy, "WM_NORMAL_HINTS", false);
ctx->atoms.netWMStateFullscreenAtom = XInternAtom(ctx->dpy, "_NET_WM_STATE_FULLSCREEN", false);
+ ctx->atoms.motifWMHintsAtom = XInternAtom(ctx->dpy, "_MOTIF_WM_HINTS", false);
ctx->atoms.netActiveWindowAtom = XInternAtom(ctx->dpy, "_NET_ACTIVE_WINDOW", false);
ctx->atoms.netWMStateAtom = XInternAtom(ctx->dpy, "_NET_WM_STATE", false);
ctx->atoms.WMTransientForAtom = XInternAtom(ctx->dpy, "WM_TRANSIENT_FOR", false);
diff --git a/src/xwayland_ctx.hpp b/src/xwayland_ctx.hpp
index 15c2e6b..525b155 100644
--- a/src/xwayland_ctx.hpp
+++ b/src/xwayland_ctx.hpp
@@ -128,6 +128,7 @@ struct xwayland_ctx_t final : public gamescope::IWaitable
Atom winNormalAtom;
Atom sizeHintsAtom;
Atom netWMStateFullscreenAtom;
+ Atom motifWMHintsAtom;
Atom netActiveWindowAtom;
Atom netWMStateAtom;
Atom WMTransientForAtom;
+2 -2
View File
@@ -1,3 +1,3 @@
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
GAMESCOPE_TAG=gamescope-3.16.29-p19
GAMESCOPE_SHA256=e7333c6a2b95708b199c2c5bd0973e3f0e711e2dc746950cc648c2515ea2926b
GAMESCOPE_TAG=gamescope-3.16.29-p21
GAMESCOPE_SHA256=c34d2728eb31a5ded35e5cb874e68dd4932a7fba4bcce5f99edf654108f97018
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# Builds VK_LAYER_DROIDDECK_gpu_load for the arm64 guest: tools/gpuload/build.sh [--native] OUT
# OUT gets libVkLayer_droiddeck_gpuload.so and its implicit-layer manifest.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
repo=$(cd "$here/../.." && pwd)
. "$repo/tools/docker_platform.sh"
native=0
if [ "${1:-}" = --native ]; then native=1; shift; fi
out=${1:?usage: tools/gpuload/build.sh [--native] OUT}
case "$out" in /*) ;; *) out="$PWD/$out" ;; esac
vkinc=${VK_INCLUDE:-}
if [ -z "$vkinc" ]; then
ndks=("${NDK:-}" "${ANDROID_NDK_HOME:-}" "${ANDROID_NDK_LATEST_HOME:-}")
sdk_ndks=("${ANDROID_HOME:-$HOME/Library/Android/sdk}"/ndk/*)
for ((i = ${#sdk_ndks[@]} - 1; i >= 0; i--)); do ndks+=("${sdk_ndks[i]}"); done
for ndk in "${ndks[@]}"; do
[ -n "$ndk" ] && [ -d "$ndk" ] || continue
for cand in "$ndk"/toolchains/llvm/prebuilt/*/sysroot/usr/include; do
if [ -f "$cand/vulkan/vk_layer.h" ]; then vkinc=$cand; break 2; fi
done
done
fi
[ -n "$vkinc" ] && [ -f "$vkinc/vulkan/vulkan_core.h" ] || { echo "tools/gpuload/build.sh: no Vulkan headers (set VK_INCLUDE)" >&2; exit 1; }
work="$repo/build/gpuload"
rm -rf "$work" && mkdir -p "$work/include" "$work/out"
cp -R "$vkinc/vulkan" "$work/include/"
if [ -d "$vkinc/vk_video" ]; then cp -R "$vkinc/vk_video" "$work/include/"; fi
cmd=(sh -c '
set -e
cc -std=c11 -O2 -Wall -Wextra -Werror -Itools/gpuload/src -o build/gpuload/test_gpuload_busy tools/gpuload/tests/test_gpuload_busy.c
build/gpuload/test_gpuload_busy
cc -std=c11 -O2 -Wall -Wextra -Werror -Ibuild/gpuload/include -Itools/gpuload/src -o build/gpuload/test_gpuload_ring tools/gpuload/tests/test_gpuload_ring.c
build/gpuload/test_gpuload_ring
aarch64-linux-gnu-gcc -std=c11 -shared -fPIC -O2 -Wall -Wextra -Werror -Wno-unused-parameter -Wno-missing-field-initializers \
-fvisibility=hidden -pthread -Wl,-z,defs -Ibuild/gpuload/include -Itools/gpuload/src \
-o build/gpuload/out/libVkLayer_droiddeck_gpuload.so tools/gpuload/src/vk_layer_droiddeck_gpuload.c
aarch64-linux-gnu-strip --strip-unneeded build/gpuload/out/libVkLayer_droiddeck_gpuload.so')
if [ "$native" = 1 ]; then
(cd "$repo" && "${cmd[@]}")
else
docker run --rm --platform "${DROIDDECK_DOCKER_PLATFORM:-linux/amd64}" --user "$(id -u):$(id -g)" -v "$repo:/src" -w /src \
"${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v3}" "${cmd[@]}"
fi
cp "$here/layer/VK_LAYER_DROIDDECK_gpu_load.json" "$work/out/"
mkdir -p "$out"
cp "$work/out/libVkLayer_droiddeck_gpuload.so" "$work/out/VK_LAYER_DROIDDECK_gpu_load.json" "$out/"
echo "built $out"
@@ -0,0 +1,20 @@
{
"file_format_version": "1.2.0",
"layer": {
"name": "VK_LAYER_DROIDDECK_gpu_load",
"type": "GLOBAL",
"library_path": "/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so",
"api_version": "1.3.0",
"implementation_version": "1",
"description": "Times this process's GPU work for DroidDeck's HUD where Android hides the GPU load; idle unless a HUD is shown",
"functions": {
"vkNegotiateLoaderLayerInterfaceVersion": "DroidDeckGpuLoad_NegotiateLoaderLayerInterfaceVersion"
},
"enable_environment": {
"DROIDDECK_GPU_LOAD": "1"
},
"disable_environment": {
"DROIDDECK_GPU_LOAD_DISABLE": "1"
}
}
}
+22
View File
@@ -0,0 +1,22 @@
// Busy-time bookkeeping shared by VK_LAYER_DROIDDECK_gpu_load and DroidDeck's compositor, kept free of Vulkan so it
// can be tested on its own.
#ifndef DROIDDECK_GPULOAD_BUSY_H
#define DROIDDECK_GPULOAD_BUSY_H
#include <stdint.h>
// GPU ticks between the timestamp written before a batch and the one written after it. Batches on one queue run one
// after the other, so these add up without overlap. Ticks are never compared across batches: on Adreno the always-on
// counter behind the timestamps restarts when the GPU powers down between batches (seen on the Retroid Pocket Duo).
// Anything backwards or longer than max_ticks is a bogus pair and counts as nothing.
static inline uint64_t gpuload_interval(uint64_t start, uint64_t end, uint64_t max_ticks) {
return end > start && end - start <= max_ticks ? end - start : 0;
}
// A timestamp query slot is reused once its end is available; until the GPU runs the slot's reset again the
// query still shows the previous end, so a result equal to the last one harvested is the old one.
static inline int gpuload_result_is_new(uint64_t start_avail, uint64_t end_avail, uint64_t end, uint64_t last_end) {
return start_avail && end_avail && end != last_end;
}
#endif
+215
View File
@@ -0,0 +1,215 @@
// Timestamp ring shared by VK_LAYER_DROIDDECK_gpu_load (guest) and DroidDeck's compositor (app): each submit batch
// that has command buffers gets one of the ring's command buffers in front (resets a query pair, writes a TOP_OF_PIPE
// timestamp) and one behind (BOTTOM_OF_PIPE timestamp). Finished pairs are read back without waiting.
// The start timestamp sits after the batch's semaphore waits only because Turnip and Qualcomm's driver on kgsl hold a
// whole batch until its waits signal; a driver that starts TOP_OF_PIPE work earlier would count the wait as busy.
// Callers serialize access to one ring (a queue's submits are externally synchronized anyway).
#ifndef DROIDDECK_GPULOAD_RING_H
#define DROIDDECK_GPULOAD_RING_H
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <vulkan/vulkan.h>
#include "gpuload_busy.h"
#define GPULOAD_RING 64
typedef VkResult(VKAPI_PTR *gpuload_set_data_fn)(VkDevice device, void *object);
struct gpuload_vk {
VkDevice device;
PFN_vkCreateCommandPool create_pool;
PFN_vkDestroyCommandPool destroy_pool;
PFN_vkAllocateCommandBuffers alloc_cmds;
PFN_vkBeginCommandBuffer begin;
PFN_vkEndCommandBuffer end;
PFN_vkCmdResetQueryPool cmd_reset;
PFN_vkCmdWriteTimestamp cmd_timestamp;
PFN_vkCreateQueryPool create_queries;
PFN_vkDestroyQueryPool destroy_queries;
PFN_vkGetQueryPoolResults results;
gpuload_set_data_fn set_data; // a layer must give the loader every command buffer it allocates; NULL elsewhere
double period_ns;
uint64_t max_ticks;
};
struct gpuload_slot {
VkCommandBuffer start, end;
uint64_t last_end;
};
struct gpuload_ring {
int state; // 0 not set up, 1 timing, -1 cannot time
VkCommandPool pool;
VkQueryPool queries;
uint64_t mask;
uint32_t next, oldest, inflight;
struct gpuload_slot slot[GPULOAD_RING];
};
#define GPULOAD_LONGEST_BATCH_NS 2000000000.0
static inline void gpuload_vk_period(struct gpuload_vk *v, float timestamp_period) {
v->period_ns = timestamp_period;
v->max_ticks = timestamp_period > 0 ? (uint64_t)(GPULOAD_LONGEST_BATCH_NS / timestamp_period) : 0;
}
static inline int gpuload_vk_complete(const struct gpuload_vk *v) {
return v->device && v->create_pool && v->destroy_pool && v->alloc_cmds && v->begin && v->end && v->cmd_reset &&
v->cmd_timestamp && v->create_queries && v->destroy_queries && v->results && v->period_ns > 0;
}
static inline void gpuload_ring_release(struct gpuload_ring *r, const struct gpuload_vk *v) {
if (r->queries) v->destroy_queries(v->device, r->queries, NULL);
if (r->pool) v->destroy_pool(v->device, r->pool, NULL);
r->queries = VK_NULL_HANDLE;
r->pool = VK_NULL_HANDLE;
r->next = r->oldest = r->inflight = 0;
}
static inline int gpuload_ring_record(struct gpuload_ring *r, const struct gpuload_vk *v, uint32_t i) {
const VkCommandBufferBeginInfo begin = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
struct gpuload_slot *s = &r->slot[i];
if (v->begin(s->start, &begin) != VK_SUCCESS) return 0;
v->cmd_reset(s->start, r->queries, 2 * i, 2);
v->cmd_timestamp(s->start, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, r->queries, 2 * i);
if (v->end(s->start) != VK_SUCCESS) return 0;
if (v->begin(s->end, &begin) != VK_SUCCESS) return 0;
v->cmd_timestamp(s->end, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, r->queries, 2 * i + 1);
return v->end(s->end) == VK_SUCCESS;
}
// Sets the ring up for a queue of this family; returns 1 when it can time it (r->state says the same afterwards).
static inline int gpuload_ring_setup(struct gpuload_ring *r, const struct gpuload_vk *v, uint32_t family,
uint32_t timestamp_bits) {
r->state = -1;
if (!timestamp_bits || !gpuload_vk_complete(v)) return 0;
r->mask = timestamp_bits >= 64 ? ~0ull : (1ull << timestamp_bits) - 1;
const VkCommandPoolCreateInfo pool = {.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, .queueFamilyIndex = family};
const VkQueryPoolCreateInfo queries = {.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,
.queryType = VK_QUERY_TYPE_TIMESTAMP, .queryCount = 2 * GPULOAD_RING};
VkCommandBuffer cmds[2 * GPULOAD_RING];
if (v->create_pool(v->device, &pool, NULL, &r->pool) != VK_SUCCESS) { r->pool = VK_NULL_HANDLE; goto fail; }
if (v->create_queries(v->device, &queries, NULL, &r->queries) != VK_SUCCESS) { r->queries = VK_NULL_HANDLE; goto fail; }
const VkCommandBufferAllocateInfo alloc = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, .commandPool = r->pool,
.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, .commandBufferCount = 2 * GPULOAD_RING};
if (v->alloc_cmds(v->device, &alloc, cmds) != VK_SUCCESS) goto fail;
for (uint32_t i = 0; i < 2 * GPULOAD_RING; i++)
if (v->set_data && v->set_data(v->device, cmds[i]) != VK_SUCCESS) goto fail;
for (uint32_t i = 0; i < GPULOAD_RING; i++) {
r->slot[i].start = cmds[2 * i];
r->slot[i].end = cmds[2 * i + 1];
r->slot[i].last_end = 0;
if (!gpuload_ring_record(r, v, i)) goto fail;
}
r->next = r->oldest = r->inflight = 0;
r->state = 1;
return 1;
fail:
gpuload_ring_release(r, v);
r->state = -1;
return 0;
}
// Nanoseconds of GPU time in the batches that finished since the last call. Slots are taken in ring order and a
// queue runs its batches in order, so the oldest slot finishes first.
static inline uint64_t gpuload_ring_harvest(struct gpuload_ring *r, const struct gpuload_vk *v) {
uint64_t ticks = 0;
while (r->inflight) {
struct gpuload_slot *s = &r->slot[r->oldest];
uint64_t q[4] = {0, 0, 0, 0};
VkResult res = v->results(v->device, r->queries, 2 * r->oldest, 2, sizeof(q), q, 2 * sizeof(uint64_t),
VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WITH_AVAILABILITY_BIT);
if (res != VK_SUCCESS && res != VK_NOT_READY) break;
uint64_t start = q[0] & r->mask, end = q[2] & r->mask;
if (!gpuload_result_is_new(q[1], q[3], end, s->last_end)) break;
s->last_end = end;
r->oldest = (r->oldest + 1) % GPULOAD_RING;
r->inflight--;
ticks += gpuload_interval(start, end, v->max_ticks);
}
return (uint64_t)((double)ticks * v->period_ns);
}
static inline int gpuload_plain_batch(const void *next) {
for (const VkBaseInStructure *s = (const VkBaseInStructure *)next; s; s = s->pNext) {
if (s->sType == VK_STRUCTURE_TYPE_DEVICE_GROUP_SUBMIT_INFO) return 0;
if (s->sType == VK_STRUCTURE_TYPE_PROTECTED_SUBMIT_INFO && ((const VkProtectedSubmitInfo *)s)->protectedSubmit)
return 0;
}
return 1;
}
static inline struct gpuload_slot *gpuload_ring_take(struct gpuload_ring *r) {
if (r->inflight >= GPULOAD_RING) return NULL;
struct gpuload_slot *s = &r->slot[r->next];
r->next = (r->next + 1) % GPULOAD_RING;
r->inflight++;
return s;
}
// Gives back the slots of a submit that failed.
static inline void gpuload_ring_unwind(struct gpuload_ring *r, uint32_t used) {
r->next = (r->next + GPULOAD_RING - used) % GPULOAD_RING;
r->inflight -= used;
}
// A copy of the batches with the ring's command buffers around each one that has command buffers (free() it after
// the submit), or NULL to submit the originals. *used counts the slots taken, for gpuload_ring_unwind.
static inline VkSubmitInfo *gpuload_ring_wrap(struct gpuload_ring *r, uint32_t count, const VkSubmitInfo *infos,
uint32_t *used) {
*used = 0;
size_t cmds = 0;
for (uint32_t i = 0; i < count; i++) cmds += infos[i].commandBufferCount + 2;
VkSubmitInfo *mine = (VkSubmitInfo *)malloc(count * sizeof(*mine) + cmds * sizeof(VkCommandBuffer));
if (!mine) return NULL;
VkCommandBuffer *list = (VkCommandBuffer *)(mine + count);
for (uint32_t i = 0; i < count; i++) {
uint32_t n = infos[i].commandBufferCount;
mine[i] = infos[i];
if (!n || !gpuload_plain_batch(infos[i].pNext)) continue;
struct gpuload_slot *s = gpuload_ring_take(r);
if (!s) continue;
list[0] = s->start;
memcpy(list + 1, infos[i].pCommandBuffers, n * sizeof(VkCommandBuffer));
list[n + 1] = s->end;
mine[i].pCommandBuffers = list;
mine[i].commandBufferCount = n + 2;
list += n + 2;
(*used)++;
}
return mine;
}
static inline VkSubmitInfo2 *gpuload_ring_wrap2(struct gpuload_ring *r, uint32_t count, const VkSubmitInfo2 *infos,
uint32_t *used) {
*used = 0;
size_t cmds = 0;
for (uint32_t i = 0; i < count; i++) cmds += infos[i].commandBufferInfoCount + 2;
VkSubmitInfo2 *mine = (VkSubmitInfo2 *)malloc(count * sizeof(*mine) + cmds * sizeof(VkCommandBufferSubmitInfo));
if (!mine) return NULL;
VkCommandBufferSubmitInfo *list = (VkCommandBufferSubmitInfo *)(mine + count);
for (uint32_t i = 0; i < count; i++) {
uint32_t n = infos[i].commandBufferInfoCount;
mine[i] = infos[i];
if (!n || (infos[i].flags & VK_SUBMIT_PROTECTED_BIT) || !gpuload_plain_batch(infos[i].pNext)) continue;
struct gpuload_slot *s = gpuload_ring_take(r);
if (!s) continue;
memset(&list[0], 0, sizeof(list[0]));
list[0].sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_SUBMIT_INFO;
list[0].commandBuffer = s->start;
memcpy(list + 1, infos[i].pCommandBufferInfos, n * sizeof(VkCommandBufferSubmitInfo));
memset(&list[n + 1], 0, sizeof(list[n + 1]));
list[n + 1].sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_SUBMIT_INFO;
list[n + 1].commandBuffer = s->end;
mine[i].pCommandBufferInfos = list;
mine[i].commandBufferInfoCount = n + 2;
list += n + 2;
(*used)++;
}
return mine;
}
#endif
@@ -0,0 +1,410 @@
// VK_LAYER_DROIDDECK_gpu_load: this process's GPU busy time for the HUD where Android keeps the GPU load from apps
// (kgsl sysfs SELinux-blocked, perfcounter reads refused while /sys/class/kgsl/kgsl-3d0/perfcounter is 0).
// The process total in nanoseconds goes to $DROIDDECK_GPU_LOAD_DIR/<pid>; nothing is timed while
// $DROIDDECK_GPU_LOAD_DIR/on is missing (the app removes it while no HUD is shown).
#define _GNU_SOURCE
#include <vulkan/vulkan.h>
#include <vulkan/vk_layer.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include "gpuload_ring.h"
#define EXPORT __attribute__((visibility("default")))
#define MAX_FAMILIES 32
#define WANTED_CHECK_NS 500000000ull
#define WRITE_EVERY_NS 100000000ull
static const char *g_dir;
static void say(const char *what) {
// FEX leaves program_invocation_short_name empty for x86 programs.
fprintf(stderr, "[droiddeck-gpu-load] %s (pid %d): %s\n", program_invocation_short_name, (int)getpid(), what);
}
__attribute__((constructor)) static void init(void) {
const char *dir = getenv("DROIDDECK_GPU_LOAD_DIR");
g_dir = dir && *dir ? dir : NULL;
}
static uint64_t now_ns(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
}
struct inst {
struct inst *next_in_list;
VkInstance handle;
PFN_vkGetInstanceProcAddr gipa;
PFN_vkDestroyInstance destroy;
PFN_vkGetPhysicalDeviceProperties props;
PFN_vkGetPhysicalDeviceQueueFamilyProperties families;
};
struct dev {
struct dev *next_in_list;
VkDevice handle;
PFN_vkGetDeviceProcAddr gdpa;
PFN_vkDestroyDevice destroy;
PFN_vkGetDeviceQueue get_queue;
PFN_vkGetDeviceQueue2 get_queue2;
PFN_vkQueueSubmit submit;
PFN_vkQueueSubmit2 submit2;
PFN_vkQueueSubmit2 submit2_khr;
struct gpuload_vk vk;
uint32_t family_count;
uint32_t timestamp_bits[MAX_FAMILIES];
};
struct queue {
struct queue *next_in_list;
VkQueue handle;
struct dev *dev;
uint32_t family;
uint32_t epoch;
struct gpuload_ring ring;
};
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
static struct inst *g_insts;
static struct dev *g_devs;
static struct queue *g_queues;
static void *key(const void *obj) { return *(void *const *)obj; }
static struct inst *inst_for(const void *obj) {
struct inst *r;
pthread_mutex_lock(&g_lock);
for (r = g_insts; r && key(r->handle) != key(obj); r = r->next_in_list) {}
pthread_mutex_unlock(&g_lock);
return r;
}
static struct dev *dev_for(const void *obj) {
struct dev *r;
pthread_mutex_lock(&g_lock);
for (r = g_devs; r && key(r->handle) != key(obj); r = r->next_in_list) {}
pthread_mutex_unlock(&g_lock);
return r;
}
static struct queue *queue_for(VkQueue handle) {
struct queue *r;
pthread_mutex_lock(&g_lock);
for (r = g_queues; r && r->handle != handle; r = r->next_in_list) {}
pthread_mutex_unlock(&g_lock);
return r;
}
static void note_queue(struct dev *d, VkQueue handle, uint32_t family) {
if (!handle || queue_for(handle)) return;
struct queue *q = calloc(1, sizeof(*q));
if (!q) return;
q->handle = handle;
q->dev = d;
q->family = family;
pthread_mutex_lock(&g_lock);
q->next_in_list = g_queues;
g_queues = q;
pthread_mutex_unlock(&g_lock);
}
// ---- process total ---------------------------------------------------------------------------------------------
static _Atomic uint64_t g_busy_ns;
static _Atomic uint64_t g_wanted_at;
static _Atomic int g_wanted;
static _Atomic uint32_t g_epoch = 1; // bumped each time the HUD comes back
static pthread_mutex_t g_write_lock = PTHREAD_MUTEX_INITIALIZER;
static uint64_t g_written_at;
static int g_fd = -1;
static pid_t g_fd_pid;
static int g_announced;
static int wanted(uint64_t now) {
uint64_t at = atomic_load(&g_wanted_at);
if (at && now - at < WANTED_CHECK_NS) return atomic_load(&g_wanted);
atomic_store(&g_wanted_at, now);
char path[512];
snprintf(path, sizeof(path), "%s/on", g_dir);
int on = access(path, F_OK) == 0;
if (on && !atomic_exchange(&g_wanted, on)) atomic_fetch_add(&g_epoch, 1);
if (!on) atomic_store(&g_wanted, 0);
return on;
}
static void publish(uint64_t now) {
if (pthread_mutex_trylock(&g_write_lock)) return;
if (now - g_written_at >= WRITE_EVERY_NS) {
g_written_at = now;
pid_t pid = getpid();
struct stat st;
// The app deletes files that stopped changing; a forked child needs its own.
if (g_fd >= 0 && (g_fd_pid != pid || fstat(g_fd, &st) || st.st_nlink == 0)) { close(g_fd); g_fd = -1; }
if (g_fd < 0) {
char path[512];
snprintf(path, sizeof(path), "%s/%d", g_dir, (int)pid);
g_fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
g_fd_pid = pid;
}
if (g_fd >= 0) {
char line[80];
int n = snprintf(line, sizeof(line), "%20llu %-32.32s\n", (unsigned long long)atomic_load(&g_busy_ns),
program_invocation_short_name);
if (pwrite(g_fd, line, (size_t)n, 0) != n) { close(g_fd); g_fd = -1; }
}
}
pthread_mutex_unlock(&g_write_lock);
}
// The queue to time this submit on, or NULL to pass it through.
static struct queue *measuring(VkQueue handle) {
if (!g_dir) return NULL;
struct queue *q = queue_for(handle);
if (!q) return NULL;
uint64_t now = now_ns();
if (!wanted(now)) return NULL;
struct dev *d = q->dev;
if (q->ring.state == 0) {
uint32_t bits = q->family < d->family_count ? d->timestamp_bits[q->family] : 0;
if (gpuload_ring_setup(&q->ring, &d->vk, q->family, bits)) {
if (!__atomic_exchange_n(&g_announced, 1, __ATOMIC_RELAXED)) say("timing this process's GPU work for the HUD");
} else {
say(bits ? "cannot set up GPU timing on this queue" : "this queue family has no timestamps");
}
q->epoch = atomic_load(&g_epoch);
}
if (q->ring.state != 1) return NULL;
uint64_t ns = gpuload_ring_harvest(&q->ring, &d->vk);
uint32_t epoch = atomic_load(&g_epoch);
if (q->epoch == epoch) atomic_fetch_add(&g_busy_ns, ns);
else q->epoch = epoch; // timed before the HUD went away
publish(now);
return q;
}
static VkResult VKAPI_CALL QueueSubmit(VkQueue queue, uint32_t count, const VkSubmitInfo *infos, VkFence fence) {
struct dev *d = dev_for(queue);
if (!d) return VK_ERROR_DEVICE_LOST;
struct queue *q = count ? measuring(queue) : NULL;
uint32_t used = 0;
VkSubmitInfo *mine = q ? gpuload_ring_wrap(&q->ring, count, infos, &used) : NULL;
VkResult r = d->submit(queue, count, mine ? mine : infos, fence);
if (mine && r != VK_SUCCESS) gpuload_ring_unwind(&q->ring, used);
free(mine);
return r;
}
static VkResult submit2(PFN_vkQueueSubmit2 next, VkQueue queue, uint32_t count, const VkSubmitInfo2 *infos, VkFence fence) {
struct queue *q = count ? measuring(queue) : NULL;
uint32_t used = 0;
VkSubmitInfo2 *mine = q ? gpuload_ring_wrap2(&q->ring, count, infos, &used) : NULL;
VkResult r = next(queue, count, mine ? mine : infos, fence);
if (mine && r != VK_SUCCESS) gpuload_ring_unwind(&q->ring, used);
free(mine);
return r;
}
static VkResult VKAPI_CALL QueueSubmit2(VkQueue queue, uint32_t count, const VkSubmitInfo2 *infos, VkFence fence) {
struct dev *d = dev_for(queue);
return d ? submit2(d->submit2, queue, count, infos, fence) : VK_ERROR_DEVICE_LOST;
}
static VkResult VKAPI_CALL QueueSubmit2KHR(VkQueue queue, uint32_t count, const VkSubmitInfo2 *infos, VkFence fence) {
struct dev *d = dev_for(queue);
return d ? submit2(d->submit2_khr, queue, count, infos, fence) : VK_ERROR_DEVICE_LOST;
}
static void VKAPI_CALL GetDeviceQueue(VkDevice device, uint32_t family, uint32_t index, VkQueue *out) {
struct dev *d = dev_for(device);
if (!d) return;
d->get_queue(device, family, index, out);
if (out && *out) note_queue(d, *out, family);
}
static void VKAPI_CALL GetDeviceQueue2(VkDevice device, const VkDeviceQueueInfo2 *info, VkQueue *out) {
struct dev *d = dev_for(device);
if (!d) return;
d->get_queue2(device, info, out);
if (out && *out) note_queue(d, *out, info->queueFamilyIndex);
}
// ---- instance and device ---------------------------------------------------------------------------------------
static VkResult VKAPI_CALL CreateInstance(const VkInstanceCreateInfo *ci, const VkAllocationCallbacks *alloc, VkInstance *out) {
VkLayerInstanceCreateInfo *link = (VkLayerInstanceCreateInfo *)ci->pNext;
while (link && !(link->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && link->function == VK_LAYER_LINK_INFO))
link = (VkLayerInstanceCreateInfo *)link->pNext;
if (!link) return VK_ERROR_INITIALIZATION_FAILED;
PFN_vkGetInstanceProcAddr next_gipa = link->u.pLayerInfo->pfnNextGetInstanceProcAddr;
link->u.pLayerInfo = link->u.pLayerInfo->pNext;
PFN_vkCreateInstance create = (PFN_vkCreateInstance)next_gipa(VK_NULL_HANDLE, "vkCreateInstance");
if (!create) return VK_ERROR_INITIALIZATION_FAILED;
struct inst *in = calloc(1, sizeof(*in));
if (!in) return VK_ERROR_OUT_OF_HOST_MEMORY;
VkResult r = create(ci, alloc, out);
if (r != VK_SUCCESS) { free(in); return r; }
in->handle = *out;
in->gipa = next_gipa;
in->destroy = (PFN_vkDestroyInstance)next_gipa(*out, "vkDestroyInstance");
in->props = (PFN_vkGetPhysicalDeviceProperties)next_gipa(*out, "vkGetPhysicalDeviceProperties");
in->families = (PFN_vkGetPhysicalDeviceQueueFamilyProperties)next_gipa(*out, "vkGetPhysicalDeviceQueueFamilyProperties");
pthread_mutex_lock(&g_lock);
in->next_in_list = g_insts;
g_insts = in;
pthread_mutex_unlock(&g_lock);
return VK_SUCCESS;
}
static void VKAPI_CALL DestroyInstance(VkInstance instance, const VkAllocationCallbacks *alloc) {
struct inst *in = inst_for(instance);
if (!in) return;
PFN_vkDestroyInstance destroy = in->destroy;
pthread_mutex_lock(&g_lock);
for (struct inst **p = &g_insts; *p; p = &(*p)->next_in_list)
if (*p == in) { *p = in->next_in_list; break; }
pthread_mutex_unlock(&g_lock);
free(in);
if (destroy) destroy(instance, alloc);
}
static VkLayerDeviceCreateInfo *device_chain(const VkDeviceCreateInfo *ci, VkLayerFunction function) {
VkLayerDeviceCreateInfo *c = (VkLayerDeviceCreateInfo *)ci->pNext;
while (c && !(c->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO && c->function == function))
c = (VkLayerDeviceCreateInfo *)c->pNext;
return c;
}
static VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice pd, const VkDeviceCreateInfo *ci, const VkAllocationCallbacks *alloc,
VkDevice *out) {
VkLayerDeviceCreateInfo *link = device_chain(ci, VK_LAYER_LINK_INFO);
if (!link) return VK_ERROR_INITIALIZATION_FAILED;
VkLayerDeviceCreateInfo *callback = device_chain(ci, VK_LOADER_DATA_CALLBACK);
PFN_vkGetInstanceProcAddr next_gipa = link->u.pLayerInfo->pfnNextGetInstanceProcAddr;
PFN_vkGetDeviceProcAddr next_gdpa = link->u.pLayerInfo->pfnNextGetDeviceProcAddr;
link->u.pLayerInfo = link->u.pLayerInfo->pNext;
struct inst *in = inst_for(pd);
PFN_vkCreateDevice create = (PFN_vkCreateDevice)next_gipa(in ? in->handle : VK_NULL_HANDLE, "vkCreateDevice");
if (!create) return VK_ERROR_INITIALIZATION_FAILED;
struct dev *d = calloc(1, sizeof(*d));
if (!d) return VK_ERROR_OUT_OF_HOST_MEMORY;
VkResult r = create(pd, ci, alloc, out);
if (r != VK_SUCCESS) { free(d); return r; }
d->handle = *out;
d->gdpa = next_gdpa;
#define LOAD(field, type, name) d->field = (type)next_gdpa(*out, name)
LOAD(destroy, PFN_vkDestroyDevice, "vkDestroyDevice");
LOAD(get_queue, PFN_vkGetDeviceQueue, "vkGetDeviceQueue");
LOAD(get_queue2, PFN_vkGetDeviceQueue2, "vkGetDeviceQueue2");
LOAD(submit, PFN_vkQueueSubmit, "vkQueueSubmit");
LOAD(submit2, PFN_vkQueueSubmit2, "vkQueueSubmit2");
LOAD(submit2_khr, PFN_vkQueueSubmit2, "vkQueueSubmit2KHR");
LOAD(vk.create_pool, PFN_vkCreateCommandPool, "vkCreateCommandPool");
LOAD(vk.destroy_pool, PFN_vkDestroyCommandPool, "vkDestroyCommandPool");
LOAD(vk.alloc_cmds, PFN_vkAllocateCommandBuffers, "vkAllocateCommandBuffers");
LOAD(vk.begin, PFN_vkBeginCommandBuffer, "vkBeginCommandBuffer");
LOAD(vk.end, PFN_vkEndCommandBuffer, "vkEndCommandBuffer");
LOAD(vk.cmd_reset, PFN_vkCmdResetQueryPool, "vkCmdResetQueryPool");
LOAD(vk.cmd_timestamp, PFN_vkCmdWriteTimestamp, "vkCmdWriteTimestamp");
LOAD(vk.create_queries, PFN_vkCreateQueryPool, "vkCreateQueryPool");
LOAD(vk.destroy_queries, PFN_vkDestroyQueryPool, "vkDestroyQueryPool");
LOAD(vk.results, PFN_vkGetQueryPoolResults, "vkGetQueryPoolResults");
#undef LOAD
d->vk.device = *out;
d->vk.set_data = callback ? (gpuload_set_data_fn)callback->u.pfnSetDeviceLoaderData : NULL;
if (in && in->props && in->families) {
VkPhysicalDeviceProperties props;
in->props(pd, &props);
gpuload_vk_period(&d->vk, props.limits.timestampPeriod);
uint32_t n = 0;
in->families(pd, &n, NULL);
VkQueueFamilyProperties families[MAX_FAMILIES];
if (n > MAX_FAMILIES) n = MAX_FAMILIES;
in->families(pd, &n, families);
d->family_count = n;
for (uint32_t i = 0; i < n; i++) d->timestamp_bits[i] = families[i].timestampValidBits;
}
// Without the loader callback our command buffers would lack the loader's dispatch pointer.
if (!d->vk.set_data) d->family_count = 0;
pthread_mutex_lock(&g_lock);
d->next_in_list = g_devs;
g_devs = d;
pthread_mutex_unlock(&g_lock);
return VK_SUCCESS;
}
static void VKAPI_CALL DestroyDevice(VkDevice device, const VkAllocationCallbacks *alloc) {
struct dev *d = dev_for(device);
if (!d) return;
struct queue *mine = NULL;
pthread_mutex_lock(&g_lock);
for (struct queue **p = &g_queues; *p;) {
struct queue *q = *p;
if (q->dev == d) { *p = q->next_in_list; q->next_in_list = mine; mine = q; } else p = &q->next_in_list;
}
for (struct dev **p = &g_devs; *p; p = &(*p)->next_in_list)
if (*p == d) { *p = d->next_in_list; break; }
pthread_mutex_unlock(&g_lock);
while (mine) {
struct queue *q = mine;
mine = q->next_in_list;
gpuload_ring_release(&q->ring, &d->vk);
free(q);
}
PFN_vkDestroyDevice destroy = d->destroy;
free(d);
if (destroy) destroy(device, alloc);
}
// ---- dispatch --------------------------------------------------------------------------------------------------
EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL DroidDeckGpuLoad_GetDeviceProcAddr(VkDevice device, const char *name);
static PFN_vkVoidFunction device_hook(struct dev *d, const char *name) {
if (!g_dir) return NULL;
if (!strcmp(name, "vkGetDeviceQueue") && d->get_queue) return (PFN_vkVoidFunction)GetDeviceQueue;
if (!strcmp(name, "vkGetDeviceQueue2") && d->get_queue2) return (PFN_vkVoidFunction)GetDeviceQueue2;
if (!strcmp(name, "vkQueueSubmit") && d->submit) return (PFN_vkVoidFunction)QueueSubmit;
if (!strcmp(name, "vkQueueSubmit2") && d->submit2) return (PFN_vkVoidFunction)QueueSubmit2;
if (!strcmp(name, "vkQueueSubmit2KHR") && d->submit2_khr) return (PFN_vkVoidFunction)QueueSubmit2KHR;
return NULL;
}
EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL DroidDeckGpuLoad_GetInstanceProcAddr(VkInstance instance, const char *name) {
if (!strcmp(name, "vkCreateInstance")) return (PFN_vkVoidFunction)CreateInstance;
if (!strcmp(name, "vkDestroyInstance")) return (PFN_vkVoidFunction)DestroyInstance;
if (!strcmp(name, "vkCreateDevice")) return (PFN_vkVoidFunction)CreateDevice;
if (!strcmp(name, "vkGetInstanceProcAddr")) return (PFN_vkVoidFunction)DroidDeckGpuLoad_GetInstanceProcAddr;
if (!strcmp(name, "vkGetDeviceProcAddr")) return (PFN_vkVoidFunction)DroidDeckGpuLoad_GetDeviceProcAddr;
if (!instance) return NULL;
struct inst *in = inst_for(instance);
return in ? in->gipa(instance, name) : NULL;
}
EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL DroidDeckGpuLoad_GetDeviceProcAddr(VkDevice device, const char *name) {
if (!strcmp(name, "vkGetDeviceProcAddr")) return (PFN_vkVoidFunction)DroidDeckGpuLoad_GetDeviceProcAddr;
if (!strcmp(name, "vkDestroyDevice")) return (PFN_vkVoidFunction)DestroyDevice;
struct dev *d = dev_for(device);
if (!d) return NULL;
PFN_vkVoidFunction mine = device_hook(d, name);
return mine ? mine : d->gdpa(device, name);
}
EXPORT VKAPI_ATTR VkResult VKAPI_CALL DroidDeckGpuLoad_NegotiateLoaderLayerInterfaceVersion(VkNegotiateLayerInterface *v) {
if (v->loaderLayerInterfaceVersion > 2) v->loaderLayerInterfaceVersion = 2;
v->pfnGetInstanceProcAddr = DroidDeckGpuLoad_GetInstanceProcAddr;
v->pfnGetDeviceProcAddr = DroidDeckGpuLoad_GetDeviceProcAddr;
v->pfnGetPhysicalDeviceProcAddr = NULL;
return VK_SUCCESS;
}
+24
View File
@@ -0,0 +1,24 @@
#include <assert.h>
#include <stdio.h>
#include "gpuload_busy.h"
int main(void) {
const uint64_t max = 1000;
assert(gpuload_interval(10, 20, max) == 10);
// Each batch counts on its own, even when the counter restarted in between (later batch has smaller ticks).
assert(gpuload_interval(900000, 900400, max) == 400);
assert(gpuload_interval(50, 350, max) == 300);
// Backwards, empty or too long: nothing.
assert(gpuload_interval(60, 50, max) == 0);
assert(gpuload_interval(70, 70, max) == 0);
assert(gpuload_interval(100, 100 + max + 1, max) == 0);
assert(gpuload_interval(100, 100 + max, max) == max);
// Query results: both halves available and an end that differs from the last harvested one.
assert(gpuload_result_is_new(1, 1, 500, 400));
assert(!gpuload_result_is_new(1, 1, 400, 400));
assert(!gpuload_result_is_new(1, 0, 500, 400));
assert(!gpuload_result_is_new(0, 1, 500, 400));
puts("test_gpuload_busy: ok");
return 0;
}
+96
View File
@@ -0,0 +1,96 @@
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include "gpuload_ring.h"
// A fake device: query results come from this table, [start, start available, end, end available] per slot.
static uint64_t g_result[GPULOAD_RING][4];
static uintptr_t g_next_handle = 0x1000;
static VkResult VKAPI_CALL create_pool(VkDevice d, const VkCommandPoolCreateInfo *ci, const VkAllocationCallbacks *a, VkCommandPool *out) {
(void)d; (void)ci; (void)a; *out = (VkCommandPool)(g_next_handle++); return VK_SUCCESS;
}
static void VKAPI_CALL destroy_pool(VkDevice d, VkCommandPool p, const VkAllocationCallbacks *a) { (void)d; (void)p; (void)a; }
static VkResult VKAPI_CALL alloc_cmds(VkDevice d, const VkCommandBufferAllocateInfo *ai, VkCommandBuffer *out) {
(void)d;
for (uint32_t i = 0; i < ai->commandBufferCount; i++) out[i] = (VkCommandBuffer)(g_next_handle++);
return VK_SUCCESS;
}
static VkResult VKAPI_CALL begin(VkCommandBuffer c, const VkCommandBufferBeginInfo *bi) { (void)c; (void)bi; return VK_SUCCESS; }
static VkResult VKAPI_CALL end(VkCommandBuffer c) { (void)c; return VK_SUCCESS; }
static void VKAPI_CALL cmd_reset(VkCommandBuffer c, VkQueryPool q, uint32_t first, uint32_t n) { (void)c; (void)q; (void)first; (void)n; }
static void VKAPI_CALL cmd_timestamp(VkCommandBuffer c, VkPipelineStageFlagBits s, VkQueryPool q, uint32_t i) { (void)c; (void)s; (void)q; (void)i; }
static VkResult VKAPI_CALL create_queries(VkDevice d, const VkQueryPoolCreateInfo *ci, const VkAllocationCallbacks *a, VkQueryPool *out) {
(void)d; (void)a; assert(ci->queryCount == 2 * GPULOAD_RING); *out = (VkQueryPool)(g_next_handle++); return VK_SUCCESS;
}
static void VKAPI_CALL destroy_queries(VkDevice d, VkQueryPool q, const VkAllocationCallbacks *a) { (void)d; (void)q; (void)a; }
static VkResult VKAPI_CALL results(VkDevice d, VkQueryPool q, uint32_t first, uint32_t n, size_t size, void *data,
VkDeviceSize stride, VkQueryResultFlags flags) {
(void)d; (void)q; (void)size;
assert(n == 2 && stride == 2 * sizeof(uint64_t) && (flags & VK_QUERY_RESULT_WITH_AVAILABILITY_BIT));
uint64_t *out = data;
for (int k = 0; k < 4; k++) out[k] = g_result[first / 2][k];
return out[1] && out[3] ? VK_SUCCESS : VK_NOT_READY;
}
static void finish(uint32_t slot, uint64_t start, uint64_t end) {
g_result[slot][0] = start; g_result[slot][1] = 1; g_result[slot][2] = end; g_result[slot][3] = 1;
}
int main(void) {
struct gpuload_vk v = {
.device = (VkDevice)(uintptr_t)1, .create_pool = create_pool, .destroy_pool = destroy_pool, .alloc_cmds = alloc_cmds,
.begin = begin, .end = end, .cmd_reset = cmd_reset, .cmd_timestamp = cmd_timestamp,
.create_queries = create_queries, .destroy_queries = destroy_queries, .results = results,
};
struct gpuload_ring r = {0};
assert(!gpuload_ring_setup(&r, &v, 0, 64) && r.state == -1); // no timestamp period yet
gpuload_vk_period(&v, 52.083f);
assert(!gpuload_ring_setup(&r, &v, 0, 0) && r.state == -1); // family without timestamps
assert(gpuload_ring_setup(&r, &v, 0, 64) && r.state == 1);
VkCommandBuffer app[2] = {(VkCommandBuffer)(uintptr_t)0xa1, (VkCommandBuffer)(uintptr_t)0xa2};
VkProtectedSubmitInfo prot = {.sType = VK_STRUCTURE_TYPE_PROTECTED_SUBMIT_INFO, .protectedSubmit = VK_TRUE};
VkSubmitInfo batches[3] = {
{.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 2, .pCommandBuffers = app},
{.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO}, // semaphores only
{.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .pNext = &prot, .commandBufferCount = 1, .pCommandBuffers = app},
};
uint32_t used = 0;
VkSubmitInfo *mine = gpuload_ring_wrap(&r, 3, batches, &used);
assert(mine && used == 1 && r.inflight == 1);
assert(mine[0].commandBufferCount == 4 && mine[0].pCommandBuffers[0] == r.slot[0].start &&
mine[0].pCommandBuffers[1] == app[0] && mine[0].pCommandBuffers[2] == app[1] &&
mine[0].pCommandBuffers[3] == r.slot[0].end);
assert(mine[1].commandBufferCount == 0 && mine[2].commandBufferCount == 1 && mine[2].pCommandBuffers == app);
free(mine);
assert(gpuload_ring_harvest(&r, &v) == 0 && r.inflight == 1); // not finished yet
finish(0, 1000, 1192); // 192 ticks = 10 us
assert(gpuload_ring_harvest(&r, &v) == 9999 && r.inflight == 0);
// A failed submit gives its slot back.
mine = gpuload_ring_wrap(&r, 1, batches, &used);
assert(used == 1 && r.inflight == 1);
gpuload_ring_unwind(&r, used);
assert(r.inflight == 0 && r.next == 1);
free(mine);
// Fill the ring: the 65th batch goes out untimed.
for (int i = 0; i < GPULOAD_RING; i++) { mine = gpuload_ring_wrap(&r, 1, batches, &used); assert(used == 1); free(mine); }
mine = gpuload_ring_wrap(&r, 1, batches, &used);
assert(used == 0 && mine[0].commandBufferCount == 2);
free(mine);
// Slot 0 comes round again: until the GPU resets it, it still shows the old pair, which must not count twice.
// Slots 1..63 finish after a counter restart (smaller ticks than slot 0's old pair); each still counts.
for (uint32_t s = 1; s < GPULOAD_RING; s++) finish(s, 10 * s, 10 * s + 4);
assert(gpuload_ring_harvest(&r, &v) == (uint64_t)(63 * 4 * 52.083f) && r.inflight == 1 && r.oldest == 0);
finish(0, 5, 9);
assert(gpuload_ring_harvest(&r, &v) == (uint64_t)(4 * 52.083f) && r.inflight == 0);
gpuload_ring_release(&r, &v);
puts("test_gpuload_ring: ok");
return 0;
}
+12 -3
View File
@@ -31,6 +31,13 @@ export BL_DESKTOP=1
ln -sf /usr/local/bin/droiddeck-steam-launch /usr/local/bin/steamdeck-steam 2>/dev/null
ln -sf /usr/local/bin/droiddeck-steam-shim /usr/local/bin/steam 2>/dev/null
python3 /usr/local/bin/droiddeck-desktop-games 2>&1 | sed 's/^/[games] /'
# startplasma applies this file over the session environment, and keeps what an earlier session wrote.
kwriteconfig6 --file plasma-localerc --group Formats --key LANG "${LANG:-C.UTF-8}"
if [ -n "${LANGUAGE:-}" ]; then
kwriteconfig6 --file plasma-localerc --group Translations --key LANGUAGE "$LANGUAGE"
else
kwriteconfig6 --file plasma-localerc --group Translations --key LANGUAGE --delete
fi
cat > /usr/share/applications/droiddeck-steam-x64.desktop <<'ENTRY'
[Desktop Entry]
Type=Application
@@ -107,8 +114,10 @@ fi
if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then
unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND
export KWIN_COMPOSE=O2 MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=true
if [ -z "${KWIN_RENDER_NODES:-}" ] && [ -c /dev/dri/renderD0 ]; then
export KWIN_RENDER_NODES=/dev/dri/renderD0
if [ -z "${KWIN_RENDER_NODES:-}" ]; then
for node in /dev/dri/renderD0 /dev/dri/renderD307 /dev/dri/renderD*; do
if [ -c "$node" ]; then export KWIN_RENDER_NODES="$node"; break; fi
done
fi
mkdir -p /run/droiddeck/kwin
printf '#!/bin/sh\nGALLIUM_THREAD=0 exec /usr/bin/kwin_wayland "$@"\n' > /run/droiddeck/kwin/kwin_wayland
@@ -119,7 +128,7 @@ echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"
dbus-run-session -- startplasma-wayland
rc=$?
echo "== droiddeck-desktop: Plasma ended ($rc)"
if [ "$rc" -eq 0 ]; then
if [ "$rc" -eq 0 ] && [ -z "${BL_BOTTOM_DESKTOP:-}" ]; then
/usr/local/bin/droiddeck-steam-launch bigpicture
sleep 30
fi
@@ -19,7 +19,6 @@ def enabled():
def main_group(text):
"""The [Desktop Entry] group's lines, and everything after it."""
lines = text.splitlines()
start = next((i for i, l in enumerate(lines) if l.strip() == "[Desktop Entry]"), None)
if start is None:
@@ -56,8 +55,6 @@ def chromium_exec(exec_line):
def gpu_exec(exec_line):
"""The Exec that runs a program on the GPU; a Flatpak app goes through its launcher, which
keeps it on gamescope's X server instead of the desktop's Wayland socket."""
if exec_line.startswith("/usr/bin/flatpak run ") or exec_line.startswith("flatpak run "):
exec_line = "/usr/local/bin/droiddeck-flatpak-run " + exec_line.split(" run ", 1)[1]
return "droiddeck-gpu " + exec_line
+1 -1
View File
@@ -10,7 +10,7 @@ window=0
if [ "${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")
args=(--backend sdl --expose-wayland --follow-game-window-mode -W "$width" -H "$height" -w "$width" -h "$height")
else
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height")
fi
-1
View File
@@ -19,7 +19,6 @@ typedef struct {
typedef VkResult (*Enumerate)(const char *, unsigned int *, VkExtensionProperties *);
typedef Function (*ProcAddr)(void *, const char *);
/* The driver cannot enumerate devices for an instance with VK_KHR_display, and gamescope's WSI layer aborts on that. */
static const char *const hidden_extensions[] = {
"VK_KHR_display",
"VK_KHR_get_display_properties2",
@@ -1,7 +1,4 @@
#!/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 "$@"
@@ -1,22 +1,4 @@
#!/usr/bin/python3
"""The guest side of the agent bridge (docs/agent-control.md).
Started by droiddeck-session inside the session, so whatever it runs has the session's own
environment: DISPLAY, the games' Xwayland, XDG_RUNTIME_DIR, and the preloads every guest process
gets - which is what lets it reach the Steam client's DevTools port, open to guest processes only.
The app talks to it through files under $BL_LAUNCH_DIR/agent (the session root, the same path on
both sides):
req/<id>.json a request the app wrote (tmp + rename)
resp/<id>.json the answer, written the same way
hello.json this daemon is up: pid, version, what it can do
focus.json gamescope's focus and every server's top-level windows, rewritten on change
cdp-port the client's DevTools port, written by droiddeck-session
Requests: ping, exec, focus, cdp, quit. Each answer is {"ok": true, ...} or
{"ok": false, "error": {"code", "message"}}.
"""
import base64
import json
@@ -72,7 +54,6 @@ class AgentError(Exception):
class X:
"""One connection to an Xwayland server. The rootfs has xprop but no python X library."""
def __init__(self, display):
num = display.lstrip(":").split(".")[0]
@@ -116,7 +97,6 @@ class X:
return buf
def request(self, data):
"""Send one request and return its reply, or None for an X error (a window that went)."""
self.s.sendall(data)
while True:
head = self._read(32)
@@ -186,7 +166,6 @@ class X:
def windows(x):
"""Top-level windows that are mapped or carry an app id: what gamescope picks focus from."""
out = []
for win in x.children(x.root):
attrs = x.attributes(win)
@@ -230,9 +209,6 @@ def displays():
def focus_snapshot():
"""gamescope's focus as Steam sees it (root properties on the client's server) and every
server's windows. GAMESCOPE_FOCUSABLE_WINDOWS is the list the client orders the base layer
from: a game missing there stays behind the client however healthy its window looks."""
shown = displays()
if not shown:
raise AgentError("NO_DISPLAY", "This session has no X display")
@@ -349,7 +325,6 @@ def tag_game_windows(snap, proc=Path("/proc")):
def vr_scene_app(path=Path('/run/droiddeck/droiddeck-steamvr/scene-focus.json'), proc=Path('/proc')):
"""Only a live SteamVR scene with its dashboard hidden may claim game focus."""
try:
state = json.loads(path.read_text())
server, scene = int(state['serverPid']), int(state['scenePid'])
@@ -385,8 +360,6 @@ class VrSceneFocus:
class FocusWatcher(threading.Thread):
"""Rewrites focus.json when gamescope's focus properties change, and every few seconds when
the windows do (a window can change without any root property moving)."""
def __init__(self, path):
super().__init__(daemon=True, name="focus")
@@ -450,7 +423,6 @@ class FocusWatcher(threading.Thread):
class WebSocket:
"""A minimal RFC 6455 client: text frames out, text frames in. Enough for CDP."""
def __init__(self, url, timeout):
target = urllib.parse.urlsplit(url)
@@ -887,11 +859,6 @@ def steam_selection(agent_dir, timeout=5):
def steam_shortcut_app_id(game_id):
"""Return the 32-bit app id in Steam's shortcut CGameID form, or None for other ids.
DroidDeck's shortcut IDs are `(appid << 32) | 0x02000000`. The URL still needs that full
CGameID for RunGame; the app-details API separately needs the unsigned 32-bit app id.
"""
if not isinstance(game_id, str) or not game_id.isascii() or not game_id.isdigit():
return None
try:
@@ -907,7 +874,6 @@ def steam_shortcut_app_id(game_id):
def wait_for_steam_shortcut_overview(agent_dir, game_id, timeout=45):
"""Wait until Steam can map a shortcut CGameID to its 32-bit app overview."""
app_id = steam_shortcut_app_id(game_id)
if app_id is None:
return {"supported": False, "ready": False}
@@ -962,8 +928,6 @@ def steam_shortcut_state(agent_dir, game_id, timeout=6):
def game_pids(app_id):
"""Our processes started for this Steam app (Steam sets SteamAppId / SteamGameId in their
environment, and Proton's wine processes inherit it)."""
wanted = [("SteamAppId=%s" % app_id).encode(), ("SteamGameId=%s" % app_id).encode()]
me = os.getpid()
pids = []
@@ -1022,8 +986,6 @@ VR_ACTIONS = ("status", "install", "start", "stop")
def steamvr(req):
"""Cardboard mode's SteamVR: a fixed helper with four actions, unlike exec (no command line from
the request). install downloads 571 MB, so it runs detached and status reports it."""
action = req.get("action", "status")
if action not in VR_ACTIONS:
raise AgentError("INVALID_REQUEST", "vr action must be one of " + ", ".join(VR_ACTIONS))
@@ -1244,11 +1206,10 @@ def main(argv):
if len(argv) != 2 or not argv[1].isascii() or not argv[1].isdecimal():
print("usage: droiddeck-agent --steam-supports-vr <appid>", file=sys.stderr)
return 2
# Optional-VR games (Thumper, VRChat) carry vr_supported without vr_only.
expression = ("(o => o ? (o.vr_supported === true || o.vr_only === true) : null)"
"(window.appStore?.GetAppOverviewByGameID?.(%s))" % json.dumps(argv[1]))
value = None
deadline = time.monotonic() + 12 # Steam's UI is busiest while a game starts.
deadline = time.monotonic() + 12
while value is None and time.monotonic() < deadline:
try:
value = cdp_eval(Path(base) / "agent", expression, await_promise=False, timeout=8).get("value")
@@ -52,7 +52,7 @@ CLIENT_WAIT = 300
GAME_GRACE = 15
LAUNCH_WAIT = 15
LAUNCH_ASKS = 3
CLIENT_PATH = re.compile(r"[a-z]:\\(program files \(x86\)|programdata)\\battle\.net\\")
CLIENT_PATH = re.compile(r"[a-z]:\\(program files \(x86\)\\battle\.net\\([^\\]+$|battle\.net\.\d+\\)|programdata\\battle\.net\\)")
IDLE = {"agent.exe", "conhost.exe", "explorer.exe", "lsass.exe", "plugplay.exe", "rpcss.exe", "services.exe",
"start.exe", "steam.exe", "svchost.exe", "tabtip.exe", "winedevice.exe", "wineserver"}
NOT_GAME = IDLE | {"rundll32.exe", "wineboot.exe", "winemenubuilder.exe"}
@@ -322,7 +322,14 @@ def wallpaper_bmp(width, height):
def reg_value(reg, key, name, value):
line = '"%s"="%s"' % (name, value.replace("\\", "\\\\").replace('"', '\\"'))
return reg_line(reg, key, name, '"%s"="%s"' % (name, value.replace("\\", "\\\\").replace('"', '\\"')))
def reg_dword(reg, key, name, number):
return reg_line(reg, key, name, '"%s"=dword:%08x' % (name, number))
def reg_line(reg, key, name, line):
try:
with open(reg, encoding="utf-8", errors="replace") as f:
rows = f.read().splitlines()
@@ -347,6 +354,16 @@ def desktop_size():
return 1280, 720
def desktop_dpi():
width, height = desktop_size()
return 96 * max(4, int(min(width / 1920.0, height / 1080.0) * 4)) // 4
def dpi(root):
reg = os.path.join(prefix(root), "pfx", "user.reg")
return os.path.isfile(reg) and reg_dword(reg, DESKTOP_KEY, "LogPixels", desktop_dpi())
def wallpaper(root):
width, height = desktop_size()
shrink = min(1.0, WALLPAPER_MAX[0] / width, WALLPAPER_MAX[1] / height)
@@ -492,6 +509,10 @@ def configure(root, library=None):
wallpaper(root)
except OSError as error:
say("Battle.net's desktop wallpaper not set: %s" % error)
try:
dpi(root)
except OSError as error:
say("Battle.net's desktop scale not set: %s" % error)
wow_settings(root)
if change == "first":
say("wrote Battle.net's first config: hardware acceleration off, streaming off, closing itself as it launches a game, "
@@ -0,0 +1,51 @@
#!/bin/bash
# KDE Plasma on a dual-screen handheld's bottom screen, next to the session on the top one.
set -u
export HOME=${HOME:-/root}
if [ -n "${BL_DEBUG_DIR:-}" ]; then
mkdir -p "$BL_DEBUG_DIR" 2>/dev/null || true
exec >>"$BL_DEBUG_DIR/bottom-desktop.log" 2>&1
fi
echo "== droiddeck-bottom-desktop $(date -u '+%Y-%m-%d %H:%M:%S UTC') ${BL_WIDTH:-?}x${BL_HEIGHT:-?} beside a ${BL_TOP_SESSION:-?} session"
[ -x /usr/local/bin/droiddeck-desktop ] || { echo "== the desktop package is not installed"; exit 66; }
# Launch requests would reach the top session's watcher and could replace it.
unset BL_LAUNCH_DIR BL_LOG
export BL_BOTTOM_DESKTOP=1
for _ in $(seq 1 100); do
wayland-info >/dev/null 2>&1 && break
sleep 0.1
done
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1 \
&& ! pgrep -f 'dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf' >/dev/null 2>&1; then
mkdir -p /run/dbus /usr/local/share/droiddeck
cat > /usr/local/share/droiddeck/system-bus.conf <<'BUSCONF'
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<type>system</type>
<listen>unix:path=/run/dbus/system_bus_socket</listen>
<auth>EXTERNAL</auth>
<servicedir>/usr/share/droiddeck/system-services</servicedir>
<policy context="default">
<allow user="*"/>
<allow own="*"/>
<allow send_destination="*"/>
<allow receive_sender="*"/>
</policy>
</busconfig>
BUSCONF
rm -f /run/dbus/system_bus_socket
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
for _ in $(seq 1 50); do
[ -S /run/dbus/system_bus_socket ] && break
sleep 0.1
done
[ -S /run/dbus/system_bus_socket ] && droiddeck-login1 --with-netmanager &
fi
# The game on the top screen keeps the CPU first.
renice -n 5 $$ >/dev/null 2>&1 || true
exec /usr/local/bin/droiddeck-desktop
@@ -6,6 +6,7 @@ import os
import signal
import socket
import struct
import subprocess
import sys
SOCKET_FILE = "/etc/droiddeck/bwrap-socket"
@@ -23,6 +24,11 @@ def socket_name():
SOCKET = socket_name()
FEX_DIR = "/run/droiddeck-fex"
OWN_FEX = "/usr/local"
X86_MACHINES = (3, 62)
ARM_LIBS = "/usr/lib/aarch64-linux-gnu"
ARM_LOADER = "/usr/lib/ld-linux-aarch64.so.1"
VERSION = "bubblewrap 0.11.0 (droiddeck)"
NO_ARG = {
@@ -62,7 +68,6 @@ def fd_path(fd):
def expand(argv):
"""argv with every --args FD replaced by the NUL-separated arguments read from FD."""
out = []
i = 0
while i < len(argv):
@@ -91,6 +96,7 @@ class Spec:
self.lock_files = []
self.command = []
self.argv0 = None
self.env_tool = None
def parse(argv):
@@ -181,7 +187,6 @@ def real(path):
def remaps_nothing(s):
"""True when every path in the sandbox is what it is out here already."""
for op in s.ops:
t = op["t"]
if t == "bind":
@@ -217,6 +222,134 @@ def host_path(s, path):
return path
def sandbox_link(s, path):
for op in reversed(s.ops):
if op.get("dest", "").rstrip("/") != path:
continue
if op["t"] == "symlink":
return op["target"]
if op["t"] == "bind":
return None
break
here = sandbox_source(s, path)
return os.readlink(here) if os.path.islink(here) else None
def sandbox_source(s, path):
for op in reversed(s.ops):
if op["t"] != "bind":
continue
dest = op["dest"].rstrip("/")
if path == dest or path.startswith(dest + "/"):
return real(op["src"]).rstrip("/") + path[len(dest):]
return path
def sandbox_file(s, path):
parts = [p for p in path.split("/") if p]
done = "/"
hops = 0
i = 0
while i < len(parts):
step = os.path.join(done, parts[i])
link = sandbox_link(s, step)
if link is None:
done = step
i += 1
continue
hops += 1
if hops > 40:
return None
base = "/" if link.startswith("/") else done
parts = [p for p in os.path.normpath(os.path.join(base, link)).split("/") if p] + parts[i + 1:]
done = "/"
i = 0
here = sandbox_source(s, done)
return here if os.path.isfile(here) else None
def program_path(s, program):
if "/" in program:
return os.path.normpath(os.path.join(s.cwd or "/", program))
for folder in s.env.get("PATH", "/usr/bin:/bin").split(":"):
if not folder:
continue
candidate = os.path.normpath(os.path.join(s.cwd or "/", folder, program))
if sandbox_file(s, candidate):
return candidate
return None
def machine(s, path, depth=0):
here = sandbox_file(s, path)
if here is None:
return None
try:
with open(here, "rb") as f:
head = f.read(256)
except OSError:
return None
if head[:4] == b"\x7fELF" and len(head) >= 20:
return struct.unpack("<H" if head[5] == 1 else ">H", head[18:20])[0]
if head[:2] == b"#!" and depth < 4:
words = head[2:].split(b"\n")[0].split()
if words:
return machine(s, words[0].decode("utf-8", "replace"), depth + 1)
return None
def own_fex():
return all(os.access(os.path.join(OWN_FEX, "bin", name), os.X_OK) for name in ("FEX", "FEXServer")) \
and os.path.isfile(os.path.join(OWN_FEX, "lib", "libxxhash.so.0"))
def fex_ready():
if own_fex():
return True
try:
subprocess.call([os.path.join(OWN_FEX, "bin", "droiddeck-fex-update")], stdout=sys.stderr)
except OSError:
return False
return own_fex()
def start_fex_server():
try:
subprocess.Popen([os.path.join(OWN_FEX, "bin", "FEXServer"), "-p", "30"], stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
except OSError as e:
sys.stderr.write("bwrap: could not start FEXServer: %s\n" % e)
def through_fex(s):
program = program_path(s, s.command[0])
if program is None or machine(s, program) not in X86_MACHINES:
return False
if not fex_ready():
sys.stderr.write("bwrap: %s is an x86 program and FEX is not installed\n" % program)
return False
for src, dest in ((os.path.join(OWN_FEX, "bin", "FEX"), FEX_DIR + "/bin/FEX"),
(os.path.join(OWN_FEX, "bin", "FEXServer"), FEX_DIR + "/bin/FEXServer"),
(os.path.join(OWN_FEX, "lib", "libxxhash.so.0"), FEX_DIR + "/lib/libxxhash.so.0"),
("/usr/bin/env", FEX_DIR + "/bin/env"),
(ARM_LIBS, ARM_LIBS),
(real(ARM_LOADER), ARM_LOADER)):
s.ops.append({"t": "bind", "src": src, "dest": dest, "try": False, "ro": True})
data = s.env.get("XDG_CACHE_HOME") or "/tmp"
s.env["FEX_APP_CONFIG_LOCATION"] = FEX_DIR + "/config/"
s.env["FEX_APP_DATA_LOCATION"] = data + "/droiddeck-fex/"
s.env["FEX_APP_CACHE_LOCATION"] = data + "/droiddeck-fex/cache/"
for name in ("FEX_ROOTFS", "FEX_THUNKHOSTLIBS", "FEX_THUNKGUESTLIBS", "FEX_THUNKCONFIG", "FEX_PORTABLE",
"GLIBC_TUNABLES", "MESA_LOADER_DRIVER_OVERRIDE", "GALLIUM_DRIVER", "VK_ICD_FILENAMES",
"VK_DRIVER_FILES"):
s.env.pop(name, None)
s.command = [FEX_DIR + "/bin/FEX", program] + s.command[1:]
s.argv0 = None
s.env_tool = FEX_DIR + "/bin/env"
start_fex_server()
return True
def hold_locks(s):
for path in s.lock_files:
try:
@@ -290,6 +423,8 @@ def run_by_app(s):
if s.argv0:
argv[0] = s.argv0
request = {"argv": argv, "env": s.env, "cwd": s.cwd or "/", "ops": ops}
if s.env_tool:
request["envTool"] = s.env_tool
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.connect(SOCKET)
@@ -333,8 +468,9 @@ def main():
hold_locks(s)
if remaps_nothing(s):
run_here(s)
else:
run_by_app(s)
return
through_fex(s)
run_by_app(s)
if __name__ == "__main__":
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
"""Expose available Steam libraries in Dolphin, retaining the old PCManFM bookmark."""
import hashlib
import json
import os
@@ -13,6 +12,7 @@ import xml.etree.ElementTree as ET
LIBRARY = Path("/mnt/droiddeck-sd")
ADDED = Path("/mnt/droiddeck-lib")
URI = "file:///mnt/droiddeck-sd"
KDE_OWNER = "http://www.kde.org"
MARK = "DroidDeckSteamLibrary"
@@ -43,7 +43,7 @@ def steam_libraries(home, data):
if not isinstance(path, str):
continue
path = Path(re.sub(r'\\(["\\])', r'\1', path))
managed = path == LIBRARY or path.is_relative_to(home / "Games")
managed = path == LIBRARY or path.is_relative_to(home / "Games") or path.is_relative_to(ADDED)
if selected is not None and managed and path not in selected:
continue
if path == LIBRARY and selected is None and not os.environ.get("BL_LIBRARY_LABEL"):
@@ -54,7 +54,6 @@ def icon_for(appid):
def client_entries():
"""App ids the client already wrote a menu entry for."""
found = set()
if not os.path.isdir(APPS_DIR):
return found
@@ -329,7 +329,6 @@ def mirror(source, provider, name, target):
def build_rootfs(base, provider):
"""The runtime with glibc and libstdc++ taken from a newer one, which FEX's GL and Vulkan thunks are built against."""
base_files, provider_files = os.path.join(base, "files"), os.path.join(provider, "files")
rootfs = os.path.join(STATE, "rootfs")
stamp = "%d\n%s\n%s%s\n%s" % (ROOTFS_LAYOUT, os.path.realpath(base), read_text(os.path.join(base_files, MARKER)) or "",
@@ -431,8 +430,6 @@ def link_steam_sdk():
def link_guest_sdk(root):
# Proton's lsteamclient only looks in $HOME/.steam/sdk64; on ARM Steam that is the arm64 client, so
# the x86 runtime gets its own link, which FEX resolves before the host path.
for sdk, candidates in (("sdk64", ("linux64", "ubuntu12_64")), ("sdk32", ("linux32", "ubuntu12_32"))):
want = "x86_64" if sdk == "sdk64" else "i386"
directory = next((os.path.join(STEAM_ROOT, candidate) for candidate in candidates
@@ -612,17 +609,13 @@ def guest_environment(fex, env):
result["FEX_APP_CONFIG_LOCATION"] = CONFIG_DIR + "/"
result["FEX_APP_DATA_LOCATION"] = data + "/"
result["FEX_APP_CACHE_LOCATION"] = CACHE_DIR + "/"
# Valve's FEX-Emu binds its server socket under $STEAM_COMPAT_DATA_PATH/fex-emu whatever FEX_APP_DATA_LOCATION or
# FEX_SERVERSOCKETPATH say, and sun_path is 108 bytes: compatdata under the app's data folder is too long.
if result.get("STEAM_COMPAT_DATA_PATH"):
short = data if data != DATA_DIR else "/tmp/fex"
os.makedirs(short, exist_ok=True)
result["STEAM_COMPAT_DATA_PATH"] = short
result.setdefault("FEX_SILENTLOG", "0")
result.setdefault("FEX_OUTPUTLOG", "stderr")
# The session's tunables are for the host libc; an x86 ld.so copying them under FEX fails in sbrk.
result.pop("GLIBC_TUNABLES", None)
# Mono's incremental Boehm collector corrupts its heap under FEX, so Unity games crash at their first collections.
result.setdefault("GC_DISABLE_INCREMENTAL", "1")
if fex["portable"]:
result["FEX_PORTABLE"] = "1"
@@ -713,7 +706,6 @@ def launch(command, env, mode, decide=None):
folder = decide if decide and os.path.isdir(decide) else os.path.dirname(program)
if thunks == "on" and x86_64 and os.path.isfile(os.path.join(PRELOADS, "x86_64", VULKAN_PIN)) \
and vulkan_thunk_loads(fex, folder):
# Any LD_AUDIT module makes Mono's garbage collector crash under FEX, so the Vulkan thunk is pinned by search path.
guest["LD_LIBRARY_PATH"] = ":".join(["/usr/" + VULKAN_PIN_DIR] + split_paths(guest.get("LD_LIBRARY_PATH")))
thunks = "on, its own Vulkan loader too"
say("running %s with %s (runtime %s, thunks %s)" % (program, fex["bin"], guest.get("FEX_ROOTFS", "none"), thunks))
@@ -3,7 +3,6 @@ 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
@@ -13,8 +12,6 @@ fex_loads() {
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)
@@ -54,8 +51,6 @@ fex_install() {
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)
@@ -1,7 +1,15 @@
#!/usr/bin/python3
import json
import os
import re
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import time
import urllib.parse
os.environ.setdefault("FLATPAK_BWRAP", "/usr/local/bin/droiddeck-bwrap")
@@ -11,13 +19,25 @@ gi.require_version("Flatpak", "1.0")
from gi.repository import Flatpak, Gio, GLib
REMOTE = "flathub"
SYSTEM_BUS = "/run/dbus/system_bus_socket"
BUS_COMMANDS = ("install", "install-bundle", "uninstall", "update", "prune")
BUS_CONFIG = """<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<type>system</type>
<listen>unix:path=%s</listen>
<auth>EXTERNAL</auth>
<policy context="default">
<allow user="*"/>
<allow own="*"/>
<allow send_destination="*"/>
<allow receive_sender="*"/>
</policy>
</busconfig>
"""
def prepare_rootfs():
"""Some runtimes (KDE 6.10) ship etc/resolv.conf as a link to /run/host/monitor/resolv.conf.
Deploying one, Flatpak removes that link only if GIO reports it existing, and GIO follows it:
dangling here, it was left in place and making Flatpak's own link failed ("File exists").
With the target present in the rootfs the link resolves and the deploy goes through."""
target = "/run/host/monitor/resolv.conf"
try:
if not os.path.exists(target):
@@ -33,6 +53,116 @@ def prepare_rootfs():
emit(e="warning", message="could not prepare %s: %s" % (target, err))
def bus_reachable(path):
if isinstance(path, tuple):
try:
socket.create_connection(path, timeout=1).close()
return True
except (OSError, ValueError):
return False
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.connect(path)
return True
except OSError:
return False
finally:
sock.close()
def system_bus_paths():
address = os.environ.get("DBUS_SYSTEM_BUS_ADDRESS", "")
if not address:
return [SYSTEM_BUS]
paths = []
for entry in filter(None, address.split(";")):
found = None
kind, _, params = entry.partition(":")
values = dict(part.partition("=")[::2] for part in params.split(","))
if kind == "unix":
if values.get("path"):
found = urllib.parse.unquote_to_bytes(values["path"])
elif values.get("abstract"):
found = b"\0" + urllib.parse.unquote_to_bytes(values["abstract"])
elif kind == "tcp":
port = urllib.parse.unquote(values.get("port", ""))
digits = port.lstrip("0")
if not re.fullmatch(r"[0-9]+", port, re.ASCII) or not 0 < len(digits) <= 5 or int(digits) > 65535:
continue
found = (urllib.parse.unquote(values.get("host", "localhost")), int(digits))
if found is None:
return None
paths.append(found)
return paths
def system_bus_reachable():
paths = system_bus_paths()
return paths is None or any(bus_reachable(path) for path in paths)
def stop_system_bus(bus):
if not bus:
return
proc, work, conf, path = bus
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
remove_bus_files(work, conf, path)
def remove_bus_files(work, conf, path):
for name in (path, conf):
try:
os.unlink(name)
except OSError:
pass
try:
os.rmdir(work)
except OSError:
pass
def private_system_bus():
if system_bus_reachable():
return None
daemon = shutil.which("dbus-daemon")
if not daemon:
emit(e="warning", message="no system bus and no dbus-daemon to start one")
return None
try:
work = tempfile.mkdtemp(prefix="droiddeck-flatpak-bus-")
except OSError as err:
emit(e="warning", message="could not start a private system bus: %s" % err)
return None
conf = os.path.join(work, "bus.conf")
path = os.path.join(work, "bus")
try:
with open(conf, "w") as f:
f.write(BUS_CONFIG % path)
proc = subprocess.Popen([daemon, "--config-file=" + conf, "--nofork", "--nopidfile"],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except OSError as err:
remove_bus_files(work, conf, path)
emit(e="warning", message="could not start a private system bus: %s" % err)
return None
bus = (proc, work, conf, path)
for _ in range(50):
if bus_reachable(path) or proc.poll() is not None:
break
time.sleep(0.1)
if not bus_reachable(path):
stop_system_bus(bus)
emit(e="warning", message="the private system bus did not start")
return None
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:path=" + path
return bus
def emit(**kw):
sys.stdout.write(json.dumps(kw) + "\n")
sys.stdout.flush()
@@ -43,7 +173,6 @@ def installation():
def app_ref(inst, app_id):
"""The installed ref of an app, or None."""
for ref in inst.list_installed_refs_by_kind(Flatpak.RefKind.APP, None):
if ref.get_name() == app_id:
return ref
@@ -109,21 +238,31 @@ def run(t, state, report_done=True):
return 0
def arches():
native = Flatpak.get_default_arch()
return [native, "x86_64"] if native == "aarch64" else [native]
def install(app_id):
inst = installation()
arch = Flatpak.get_default_arch()
if app_ref(inst, app_id) is not None:
emit(e="done", note="already installed")
return 0
branch, last = None, None
for candidate in ("stable", "master"):
try:
branch = inst.fetch_remote_ref_sync(REMOTE, Flatpak.RefKind.APP, app_id, arch, candidate, None).get_branch()
arch, branch, last = None, None, None
for candidate_arch in arches():
for candidate in ("stable", "master"):
try:
branch = inst.fetch_remote_ref_sync(REMOTE, Flatpak.RefKind.APP, app_id, candidate_arch, candidate,
None).get_branch()
arch = candidate_arch
break
except GLib.Error as err:
last = err
if branch is not None:
break
except GLib.Error as err:
last = err
if branch is None:
emit(e="error", message="%s is not on Flathub for %s (%s)" % (app_id, arch, last.message if last else "no branch"))
emit(e="error", message="%s is not on Flathub for %s (%s)" % (app_id, " or ".join(arches()),
last.message if last else "no branch"))
return 1
t, state = transaction(inst)
t.add_install(REMOTE, "app/%s/%s/%s" % (app_id, arch, branch), None)
@@ -137,14 +276,18 @@ def install(app_id):
def install_bundle(path):
"""A single-file bundle (flatpak build-bundle), for apps Flathub does not carry."""
inst = installation()
bundle = Gio.File.new_for_path(path)
try:
app_id = Flatpak.BundleRef.new(bundle).get_name()
ref = Flatpak.BundleRef.new(bundle)
app_id = ref.get_name()
except GLib.Error as err:
emit(e="error", message="%s is not a Flatpak bundle (%s)" % (os.path.basename(path), err.message))
return 1
if ref.get_arch() not in arches():
emit(e="error", code="arch", id=app_id, arch=ref.get_arch(),
message="%s is built for %s, not %s" % (app_id, ref.get_arch(), " or ".join(arches())))
return 1
if app_ref(inst, app_id) is not None:
emit(e="done", id=app_id, note="already installed")
return 0
@@ -242,6 +385,16 @@ def main():
cmd, args = sys.argv[1], sys.argv[2:]
if cmd in ("install", "install-bundle", "update"):
prepare_rootfs()
bus = private_system_bus() if cmd in BUS_COMMANDS else None
if bus:
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(128 + signum))
try:
return command(cmd, args)
finally:
stop_system_bus(bus)
def command(cmd, args):
if cmd == "install" and args:
return install(args[0])
if cmd == "install-bundle" and args:
@@ -4,6 +4,7 @@ import json
import os
import re
import runpy
import signal
import subprocess
import sys
import tempfile
@@ -34,12 +35,10 @@ DOTNET_FEX = {
"FEX_MEMCPYSETTSOENABLED": "1",
"FEX_HALFBARRIERTSOENABLED": "1",
"FEX_X87REDUCEDPRECISION": "0",
"FEX_MULTIBLOCK": "0",
}
def game_files(exe):
"""Lower-cased names of the files next to the game's executable and one directory below."""
names = set()
folder = os.path.dirname(exe)
try:
@@ -58,7 +57,6 @@ def game_files(exe):
class Game:
"""What a fix gets to look at: the executable, its launch arguments and the files beside it."""
def __init__(self, exe, args):
self.exe = exe
@@ -85,7 +83,7 @@ def is_godot(game):
@fix
def dotnet_memory_ordering(game):
if "coreclr.dll" in game.files:
return DOTNET_FEX, [], ".NET runtime: FEX with full TSO and without multiblock"
return DOTNET_FEX, [], ".NET runtime: FEX with full TSO"
@fix
@@ -109,9 +107,6 @@ def godot_sentry(game):
@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)"
@@ -124,13 +119,22 @@ def deep_rock_gdk_raytracing(game):
@fix
def arkham_city_x87(game):
"""Batman: Arkham City (BatmanAC.exe, also started through BmLauncher.exe beside it) leans on x87
and stops with Unreal's "Fatal error!" right after start when FEX reduces its precision."""
if "batmanac.exe" in game.files:
return {"FEX_X87REDUCEDPRECISION": "0"}, [], "Batman: Arkham City: FEX with full x87 precision"
@fix
def doom_2016_swapchain_images(game):
if "doomx64vk.exe" in game.files and game.stem in ("doomx64", "doomx64vk"):
images = {
"GAMESCOPE_WSI_MIN_IMAGE_COUNT": None,
"GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT": None,
"vk_x11_strict_image_count": "true",
}
return images, [], "DOOM (2016): the swapchain keeps the image count the game asks for"
@fix
def teardown_vsync(game):
if game.stem == "teardown":
@@ -143,6 +147,12 @@ def protonfixes_off(game):
return {"PROTONFIXES_DISABLE": "1"}, [], "umu-protonfixes off (its ALSA audio and VC++ installer steps fail here)"
@fix
def little_nightmares_threads(game):
if game.stem == "littlenightmares":
return {"PROTONFIXES_DISABLE": "1"}, [], "Little Nightmares: umu-protonfixes off (its -onethread puts the game and renderer on one thread)"
@fix
def caravan_sandwitch_feature_level(game):
if "caravansandwitch.exe" in game.files or game.stem == "caravansandwitch-win64-shipping":
@@ -151,8 +161,6 @@ def caravan_sandwitch_feature_level(game):
@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"
@@ -172,10 +180,6 @@ def cyberpunk_feature_level(game):
return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "Cyberpunk 2077: D3D12 feature level 12_1"
def skip_red_launcher(command):
"""Cyberpunk 2077's prelauncher opens REDlauncher, a Qt WebEngine window that hands over to the
game half a minute later and then stays up beside it, well over a core busy for as long as the
game runs. The game is started itself instead; the prelauncher's own --launcher-skip started it
twice."""
if len(command) > 2 and os.path.basename(command[2]).lower() == "redprelauncher.exe":
game = os.path.join(os.path.dirname(command[2]), "bin", "x64", "Cyberpunk2077.exe")
if os.path.isfile(game):
@@ -239,8 +243,60 @@ def ubisoft_overlay_off(env):
print("droiddeck-game-env: Ubisoft Connect overlay left as is (%s)" % error, file=sys.stderr)
PZ_JVM_FLAGS = ("-XX:+UseG1GC", "-XX:TieredStopAtLevel=1")
def zomboid_vm_args(args):
updated = [arg for arg in args if not re.fullmatch(r"-XX:\+Use\w*GC", arg) or arg == "-XX:+UseG1GC"]
for flag in PZ_JVM_FLAGS:
if flag not in updated:
updated.append(flag)
return updated
def zomboid_rewrite(node):
changed = False
if isinstance(node, dict):
for key, value in node.items():
if key == "vmArgs" and isinstance(value, list) and all(isinstance(arg, str) for arg in value):
updated = zomboid_vm_args(value)
if updated != value:
node[key] = updated
changed = True
elif isinstance(value, dict):
changed |= zomboid_rewrite(value)
return changed
def project_zomboid_jvm(command):
if len(command) <= 2:
return
exe = Path(command[2])
if not exe.stem.lower().startswith("projectzomboid"):
return
settings = exe.with_suffix(".json")
try:
with settings.open(encoding="utf-8-sig") as source:
data = json.load(source)
if not zomboid_rewrite(data):
return
handle, staged = tempfile.mkstemp(prefix=".droiddeck-", dir=settings.parent)
try:
with os.fdopen(handle, "w", encoding="utf-8") as target:
json.dump(data, target, indent=4)
target.write("\n")
os.chmod(staged, settings.stat().st_mode & 0o7777)
os.replace(staged, settings)
except BaseException:
os.unlink(staged)
raise
print("droiddeck-game-env: Project Zomboid: G1 garbage collector and C1 JIT only (ZGC overheats and stalls here)",
file=sys.stderr)
except (OSError, ValueError, AttributeError) as error:
print("droiddeck-game-env: Project Zomboid JVM settings left as is (%s)" % error, file=sys.stderr)
def offline_without_anticheat(command, env):
"""Start the configured game executable when the player opts into launching without EAC."""
if (env.get("DROIDDECK_ANTICHEAT_OFFLINE") != "1" or len(command) <= 2
or command[1] != "waitforexitandrun"
or not re.fullmatch(r"start_protected_game(?:_?x64|_?64)?\.exe",
@@ -258,7 +314,6 @@ def offline_without_anticheat(command, env):
game = os.path.join(folder, relative)
if os.path.isabs(relative) or relative.startswith("..") or not os.path.isfile(game):
return command
# Resolve symlinks before accepting an executable inside the game directory.
root = os.path.realpath(folder)
if os.path.commonpath((root, os.path.realpath(game))) != root:
return command
@@ -269,7 +324,6 @@ def offline_without_anticheat(command, env):
def engine_fixes(exe, args):
"""Environment and extra arguments a game needs because of what it is built with."""
game = Game(exe, args)
env, extra, notes = {}, [], []
for check in FIXES:
@@ -285,7 +339,6 @@ def engine_fixes(exe, args):
def win_components(compat, app_id):
"""The game's Windows components put into its prefix; returns their WINEDLLOVERRIDES entries."""
if not compat:
return ""
try:
@@ -312,7 +365,6 @@ def game_gpu(env):
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
@@ -324,7 +376,6 @@ def vram_cap(env):
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)
@@ -347,7 +398,6 @@ def online_cores():
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
@@ -364,7 +414,6 @@ def game_cores(env):
def core_speeds(cores, root="/sys/devices/system/cpu"):
"""Each core's capacity, else its top clock; None when some core reports neither."""
for name in ("cpu_capacity", "cpufreq/cpuinfo_max_freq"):
speeds = {}
for core in cores:
@@ -379,14 +428,12 @@ def core_speeds(cores, root="/sys/devices/system/cpu"):
def fastest_first(cores):
"""The cores, fastest first; cores of equal or unknown speed keep their numeric order."""
cores = sorted(cores)
speeds = core_speeds(cores)
return sorted(cores, key=lambda core: -speeds[core]) if speeds else cores
def proton_cpu_limit(command, env):
"""This game's entry in Proton's own default_cpu_limit list: a core count, another value such as "P" as text, or None."""
app_id = env.get("SteamGameId", "")
if not command or not app_id.isdigit():
return None
@@ -406,7 +453,6 @@ def proton_cpu_limit(command, env):
def cpu_topology(env, command=()):
"""Windows sees the game's cores fastest first, so a thread a game pins to CPU 0 runs on the fastest core."""
if "PROTON_CPU_TOPOLOGY" in env:
return
if "WINE_CPU_TOPOLOGY" in env:
@@ -439,9 +485,6 @@ def cpu_topology(env, command=()):
def gl_vsync(env):
"""OpenGL stops waiting for each screen refresh; Steam's Frame Limit still holds the game through gamescope."""
# Wine asks for interval 1 on every GL window, and WineD3D's front-buffer drawing (DirectDraw,
# Direct3D 1-7) never lowers it, so those games ran at the refresh rate with no limit set.
if "vblank_mode" in env or game_id(env) is None:
return False
env["vblank_mode"] = "0"
@@ -488,6 +531,39 @@ def apply_config(env, config, app_id, fixes=None):
return result
def render_path_defaults(command, env):
if len(command) < 3 or command[1] != "waitforexitandrun" or Path(command[2]).name.lower() != "spintires.exe":
return None
own = env.get("DXVK_CONFIG", "")
if re.search(r"(?:^|;)\s*dxvk\.tilerMode\s*=", own) or env.get("DXVK_CONFIG_FILE"):
return None
if Path("dxvk.conf").is_file() or Path(command[2]).with_name("dxvk.conf").is_file():
return None
driver = env.get("VK_DRIVER_FILES", env.get("VK_ICD_FILENAMES", ""))
if Path(driver).parent.name != "DD-Turnip_v0.4.0":
return None
try:
if Path("/sys/class/kgsl/kgsl-3d0/gpu_model").read_text().strip() != "Adreno722":
return None
with open(driver, encoding="utf-8") as source:
library = json.load(source)["ICD"]["library_path"]
if Path(library).name != "libvulkan_freedreno.so":
return None
except (OSError, ValueError, KeyError, TypeError):
return None
own = own.strip().rstrip(";").strip()
env["DXVK_CONFIG"] = own + "; dxvk.tilerMode = False" if own else "dxvk.tilerMode = False"
return "Spintires: DXVK tiler heuristics off on Adreno 722"
def bridge_feature_level(env):
if env.get("BL_VKBRIDGE") != "1" or env.get("VKD3D_FEATURE_LEVEL") not in ("12_1", "12_2"):
return None
was = env["VKD3D_FEATURE_LEVEL"]
env["VKD3D_FEATURE_LEVEL"] = "12_0"
return "Mali bridge: VKD3D_FEATURE_LEVEL %s capped at 12_0 (no ray tracing or mesh shaders)" % was
GAME_DEBUG_CHANNELS = (
"timestamp", "pid", "tid", "seh", "unwind", "threadname", "debugstr", "loaddll", "mscoree",
)
@@ -495,7 +571,6 @@ WINE_DEBUG_SELECTOR = re.compile(r"(?:(trace|warn|err|fixme))?([+-])([A-Za-z_][A
def game_debug_channels(*values):
"""Normalize Wine selectors, retaining custom channels before required diagnostics."""
selectors = {}
for value in values:
if not isinstance(value, str) or "\0" in value or len(value) > 8192:
@@ -506,8 +581,6 @@ def game_debug_channels(*values):
if match is None:
continue
key = (match[1] or "", match[3])
# Move the last value to the end: global +/-all and per-class selectors
# have ordered semantics, so replacing a value in its old position is wrong.
selectors.pop(key, None)
selectors[key] = part
for channel in GAME_DEBUG_CHANNELS:
@@ -521,7 +594,6 @@ def game_debug_channels(*values):
def apply_game_debug_logs(env, config, debug_dir):
"""Apply app-owned diagnostics to a real game, without editing its launch command."""
if not isinstance(config, dict) or config.get("version") != 1 or config.get("gameDebugLogs") is not True:
return env
if (not isinstance(debug_dir, str) or "\0" in debug_dir or len(debug_dir) > 8192
@@ -593,10 +665,6 @@ SSBS_LIB = "/usr/local/lib/libssbs.so"
def force_ssbs(command, env):
"""DROIDDECK_FORCE_SSBS=1 (a game's or the shared environment): preload libssbs.so into this
Proton's Wine, which then keeps PSTATE.SSBS set across signal returns - speculative store
bypass stays allowed, as force_ssbs.diff does inside a rebuilt ntdll. ARM64 Protons only: the
library is aarch64 and only arm64 Wine has the signal path it fixes."""
if env.get("DROIDDECK_FORCE_SSBS", "").lower() not in ("1", "on", "true", "yes"):
return env
proton = os.path.dirname(command[0]) if command else ""
@@ -617,10 +685,6 @@ EVALUATOR_SCRIPT = re.compile(r"(?:^|[\\/])evaluatorscript_[0-9]+\.vdf$", re.IGN
def mark_install_scripts(command, env):
"""The client is about to run a game's install scripts (iscriptevaluator.exe): mark every process
in them but a Vulkan runtime installer as already run first, so no redistributable installer
starts - on first launch the shared ones may still be downloading, and on ARM64 Proton the VC++
ones stop with an error."""
if not any(arg.lower().replace("\\", "/").endswith("iscriptevaluator.exe") for arg in command):
return []
root = env.get("BL_X64_STEAM_ROOT") or env.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or str(Path.home() / ".local/share/Steam")
@@ -727,7 +791,198 @@ def record_install_scripts(digest, env):
print("droiddeck-game-env: install scripts not recorded (%s)" % error, file=sys.stderr)
def start(launch, launch_env, digest):
def directaudio_settings(env):
if "directaudio" not in env.get("WINE_AUDIO_DRIVER", "").split(","):
return env
for name, value in list(env.items()):
if name.startswith("AUDIO_DIRECT_"):
env["BANNER_" + name] = value
return env
DIRT_GAMES = {"dirt3_game": "dirt3", "showdown": "dirtshowdown", "showdown_avx": "dirtshowdown"}
DIRT_WS2 = "/usr/local/lib/droiddeck-dirt/ws2_32.dll"
DIRT_MARKER = b"droiddeck-dirt-ws2_32"
DIRT_FIXED = "showdown_avx.exe".encode("utf-16-le")
DIRT_SAVED = ".droiddeck-original"
def dirt_telemetry_on(prefix, game):
try:
folders = [f for f in (Path(prefix) / "pfx/drive_c/users/steamuser/Documents/My Games").iterdir()
if f.name.lower().replace(" ", "") == game]
except OSError:
return False
for folder in folders:
try:
text = (folder / "hardwaresettings/hardware_settings_config.xml").read_text(encoding="latin-1")
except OSError:
continue
for tag in ("udp", "motion"):
element = re.search(r"<%s\s[^>]*>" % tag, text)
if element:
attrs = dict(re.findall(r'\s(\w+)="([^"]*)"', element.group(0)))
return attrs.get("enabled") == "true" and attrs.get("ip", "").lower() not in ("", "dbox")
return False
def proton_ws2(proton):
return Path(proton).parent / "files/lib/wine/i386-windows/ws2_32.dll"
def proton_has_dirt_fix(proton):
try:
return DIRT_FIXED in proton_ws2(proton).read_bytes()
except OSError:
return False
WINE_DLL_DIRS = ("/lib/wine/i386-windows", "/lib/wine/x86_64-windows", "/lib/wine/aarch64-windows", "/lib/wine",
"/lib/wine/fakedlls", "/lib64/wine", "/lib64/wine/fakedlls", "/lib64/wine/x86_64-windows")
def is_wine_dll_link(path):
try:
return os.path.islink(path) and os.path.dirname(os.readlink(path)).endswith(WINE_DLL_DIRS)
except OSError:
return False
def prefix_ws2(prefix):
return Path(prefix) / "pfx/drive_c/windows/syswow64/ws2_32.dll"
def is_dirt_stand_in(path):
try:
return not path.is_symlink() and DIRT_MARKER in path.read_bytes()
except OSError:
return False
def dirt_ws2_wanted(command, env):
prefix = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
if len(command) < 3 or not prefix or not os.path.isfile(DIRT_WS2):
return None
game = DIRT_GAMES.get(os.path.splitext(os.path.basename(command[2]))[0].lower())
if not game or not dirt_telemetry_on(prefix, game) or proton_has_dirt_fix(command[0]):
return None
return prefix if os.path.lexists(prefix_ws2(prefix)) else None
def swap_dirt_ws2(prefix):
target = prefix_ws2(prefix)
saved = target.with_name(target.name + DIRT_SAVED)
data = Path(DIRT_WS2).read_bytes()
if not is_dirt_stand_in(target):
if os.path.lexists(saved):
os.unlink(saved)
os.replace(target, saved)
staged = target.with_name(target.name + ".droiddeck-tmp")
staged.write_bytes(data)
os.replace(staged, target)
def restore_dirt_ws2(prefix, proton):
target = prefix_ws2(prefix)
saved = target.with_name(target.name + DIRT_SAVED)
own = proton_ws2(proton)
had_saved = os.path.lexists(saved)
if had_saved:
if os.path.lexists(target) and not is_dirt_stand_in(target):
os.unlink(saved)
return False
if not own.is_file() or not is_wine_dll_link(saved) or os.path.realpath(saved) == os.path.realpath(own):
os.replace(saved, target)
return True
os.unlink(saved)
if own.is_file() and (is_dirt_stand_in(target) or (had_saved and not os.path.lexists(target))):
link = target.with_name(target.name + ".droiddeck-tmp")
if os.path.lexists(link):
os.unlink(link)
os.symlink(own, link)
os.replace(link, target)
return True
return False
EGO_RESTRICTIONS = "system/hardware_settings_restrictions.xml"
EGO_CORE_RULE = re.compile(r'[ \t]*<restrict_if name="cores" op="(int_[a-z]+)" value="(\d+)">.*?</restrict_if>[ \t]*\r?\n', re.S)
EGO_OPS = {"int_eq": int.__eq__, "int_ne": int.__ne__, "int_ge": int.__ge__, "int_gt": int.__gt__,
"int_le": int.__le__, "int_lt": int.__lt__}
def windows_core_count(env):
count = (env.get("WINE_CPU_TOPOLOGY") or "").split(":", 1)[0]
return int(count) if count.isascii() and count.isdigit() and int(count) > 0 else None
def ego_core_plan(command, env):
count = windows_core_count(env)
if not count or len(command) < 3:
return None
folder = Path(command[2]).parent
path = folder / EGO_RESTRICTIONS
try:
raw = path.read_bytes()
except OSError:
return None
text = raw.decode("latin-1")
start, end = text.find("<cpu>"), text.find("</cpu>")
if start < 0 or end < start:
return None
rules = list(EGO_CORE_RULE.finditer(text, start, end))
if not rules or any(EGO_OPS.get(rule.group(1), lambda a, b: True)(count, int(rule.group(2))) for rule in rules):
return None
smaller = [rule for rule in rules if rule.group(1) == "int_eq" and int(rule.group(2)) < count]
if not smaller:
return None
source = max(smaller, key=lambda rule: int(rule.group(2)))
worker_map = re.search(r'workerMapFile="([^"]+)"', source.group(0))
if worker_map and not (folder / worker_map.group(1)).is_file():
return None
plan = source.group(0).replace('value="%s"' % source.group(2), 'value="%d"' % count, 1)
saved = path.with_name(path.name + DIRT_SAVED)
if not os.path.lexists(saved):
saved.write_bytes(raw)
handle, staged = tempfile.mkstemp(prefix=path.name + ".", suffix=".droiddeck-tmp", dir=str(path.parent))
try:
with os.fdopen(handle, "wb") as out:
out.write((text[:source.end()] + plan + text[source.end():]).encode("latin-1"))
os.replace(staged, path)
except BaseException:
if os.path.lexists(staged):
os.unlink(staged)
raise
return "%s had no thread plan for %d cores; added a copy of its %s-core plan" % (EGO_RESTRICTIONS, count, source.group(2))
def wait_forwarding_signals(process):
def forward(signum, frame):
try:
process.send_signal(signum)
except OSError:
pass
previous = {signum: signal.signal(signum, forward) for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP)}
try:
code = process.wait()
finally:
for signum, handler in previous.items():
signal.signal(signum, handler)
return 128 - code if code < 0 else code
def start(launch, launch_env, digest, after=None):
if after:
process = subprocess.Popen(launch, env=launch_env)
try:
return wait_forwarding_signals(process)
finally:
try:
after()
except OSError as error:
print("droiddeck-game-env: DiRT telemetry fix: prefix ws2_32 not put back (%s); the next launch does it" % error,
file=sys.stderr)
if digest:
code = subprocess.run(launch, env=launch_env, check=False).returncode
if code == 0:
@@ -752,6 +1007,7 @@ def main():
except OSError:
digest = None
app_id = game_id(env)
dirt_prefix = None
if app_id:
gl_default = gl_vsync(env)
waiting = len(command) > 1 and command[1] == "waitforexitandrun"
@@ -761,6 +1017,7 @@ def main():
if waiting:
command = skip_red_launcher(command)
ubisoft_overlay_off(env)
project_zomboid_jvm(command)
fixes, extra, notes = engine_fixes(command[2], command[3:]) if len(command) > 2 else ({}, [], [])
if not gl_default:
fixes.pop("vblank_mode", None)
@@ -771,6 +1028,10 @@ def main():
if components:
own = fixes.get("WINEDLLOVERRIDES")
fixes["WINEDLLOVERRIDES"] = components + ";" + own if own else components
dirt_prefix = dirt_ws2_wanted(command, env)
if dirt_prefix:
own = fixes.get("WINEDLLOVERRIDES")
fixes["WINEDLLOVERRIDES"] = own + ";ws2_32=n,b" if own else "ws2_32=n,b"
path = Path.home() / ".config/droiddeck/game-environment.json"
config = {}
try:
@@ -797,11 +1058,25 @@ def main():
if app_id and len(command) > 1 and command[1] == "waitforexitandrun":
command = offline_without_anticheat(command, env)
if mic_enabled == "0":
env["BANNER_AUDIO_DIRECT_MIC"] = "0"
env["AUDIO_DIRECT_MIC"] = "0"
env = directaudio_settings(env)
env = vram_cap(env)
note = render_path_defaults(command, env) if app_id else None
if note:
print("droiddeck-game-env: " + note, file=sys.stderr)
note = bridge_feature_level(env)
if note:
print("droiddeck-game-env: " + note, file=sys.stderr)
env = force_ssbs(command, env)
game_cores(env)
cpu_topology(env, command)
if app_id and len(command) > 2 and command[1] == "waitforexitandrun":
try:
note = ego_core_plan(command, env)
except OSError as error:
note = "no thread plan added for this core count (%s)" % error
if note:
print("droiddeck-game-env: " + note, file=sys.stderr)
try:
xbox = runpy.run_path(str(Path(__file__).with_name("droiddeck-xbox")))
except Exception as error:
@@ -814,16 +1089,45 @@ def main():
return 1
if xbox_result is not None:
return xbox_result
after = None
prefix = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
if app_id and prefix and len(command) > 1 and command[1] == "waitforexitandrun":
try:
if dirt_prefix:
after = lambda: restore_dirt_ws2(dirt_prefix, command[0])
swap_dirt_ws2(dirt_prefix)
print("droiddeck-game-env: DiRT telemetry fix: ws2_32 stand-in in the prefix until the game exits",
file=sys.stderr)
elif restore_dirt_ws2(prefix, command[0]):
print("droiddeck-game-env: DiRT telemetry fix: put the prefix's own ws2_32 back", file=sys.stderr)
except OSError as error:
print("droiddeck-game-env: DiRT telemetry fix not applied (%s)" % error, file=sys.stderr)
if after:
after = None
try:
restore_dirt_ws2(dirt_prefix, command[0])
except OSError as undo:
print("droiddeck-game-env: DiRT telemetry fix: prefix ws2_32 not put back (%s); Wine uses its own copy "
"and the next launch puts the file back" % undo, file=sys.stderr)
sync = load_sync()
launch, launch_env = select_sync(command, env, sync)
if launch[0] != command[0]:
try:
return start(launch, launch_env, digest)
return start(launch, launch_env, digest, after)
except OSError as error:
print("droiddeck-game-env: %s could not start (%s); stock launch" % (launch[0], error), file=sys.stderr)
launch, launch_env = command, without_pack(launch_env, env)
record_stock(sync, launch, launch_env)
return start(launch, launch_env, digest)
try:
return start(launch, launch_env, digest, after)
except OSError:
if after:
try:
after()
except OSError as error:
print("droiddeck-game-env: DiRT telemetry fix: prefix ws2_32 not put back (%s); the next launch does it" % error,
file=sys.stderr)
raise
if __name__ == "__main__":
@@ -1,5 +1,4 @@
#!/usr/bin/python3
"""GOG patch installers and the lease shared by maintenance and game launches."""
import fcntl
import errno
import json
@@ -133,7 +132,6 @@ def runner(folder, appid, game, graphical=False):
base = desktop_environment(os.environ) if graphical else dict(os.environ)
env = run["environment"](base, target, tool, root, window=base.get("BL_DESKTOP") == "1")
env["DROIDDECK_GOG_MAINTENANCE"] = "1"
# Installer copy routines use x87 integer loads/stores; reduced precision corrupts paths (FEX #5827).
env["FEX_X87REDUCEDPRECISION"] = "0"
env.pop("BL_STORE_EXIT", None)
return str(Path(tool) / command), env, target.compatdata
@@ -1,5 +1,4 @@
#!/usr/bin/python3
"""Let GTK draw close buttons inside gamescope, which supplies no window decorations."""
import ctypes as c
import os
import signal
@@ -85,7 +85,7 @@ def connect():
def main():
launch = os.environ.get("BL_LAUNCH_DIR", "")
report = Report(os.path.join(launch, "agent") if launch else "")
report = Report(os.environ.get("BL_IME_DIR") or (os.path.join(launch, "agent") if launch else ""))
conn = Connection(connect())
conn.send(DISPLAY_ID, 1, struct.pack("<I", REGISTRY_ID))
contexts = {}
@@ -1,20 +1,4 @@
#!/usr/bin/python3
"""Holds a game launcher's hidden web interface on one slow core while something else has focus.
Rockstar's launcher keeps drawing its Chromium interface (SocialClubHelper.exe: a renderer, and a
GPU process compositing through DXVK) for as long as it runs, hidden behind the game too, and at a
higher priority than the game's (Wine passes Chromium's on: the GPU process ran at nice -10). With
Red Dead Redemption 2 in front on the RedMagic that was 1.3 to 2.5 cores under FEX, on a phone
already held back by its temperature, for a page nobody sees. Held, riding at the throttle limit
went from 46.5 to 48.7 fps, 1% lows from 27.5 to 32.6. So while the focused window belongs to
anything but the launcher, every helper thread runs on one core of the slowest cluster at nice 19;
when the launcher's own window has focus again (signing in, the game closed) each thread gets its
own mask and priority back. Stopping the helpers instead would not hold: proot, the tracer of every
guest process, resumes a stopped tracee.
Focus comes from droiddeck-agent's focus.json (the path is the argument), which the agent rewrites
whenever gamescope's focus changes. droiddeck-session starts this for Steam sessions;
BL_LAUNCHER_CORES=0 leaves the launchers alone."""
import json
import os
import signal
@@ -35,7 +19,6 @@ def log(message):
def image(proc, pid):
"""A process's program as Wine names it (argv[0]), lower case with backslashes, or None."""
try:
with open(proc / str(pid) / "cmdline", "rb") as stream:
first = stream.read(4096).split(b"\0", 1)[0]
@@ -56,7 +39,6 @@ def tasks(proc, pid):
class Cores:
"""The kernel calls, apart so a test can stand in for them."""
def own(self):
return os.sched_getaffinity(0)
@@ -81,8 +63,6 @@ class Holder:
self.core = None
def slow_core(self):
"""The last core of the slowest cluster the session has - not of the game's cores, which
the launcher inherits when BL_GAME_CPUS is set: the core the game misses least."""
def top(cpu):
try:
return int((self.cpufreq / f"cpu{cpu}/cpufreq/cpuinfo_max_freq").read_text())
@@ -98,8 +78,6 @@ class Holder:
yield int(name)
def hold(self):
"""Every helper thread onto the slow core at NICE: new ones, and held ones the program has
moved since (Chromium sets its threads' priorities, and Wine passes that on)."""
if self.core is None:
self.core = self.slow_core()
hold = ({self.core}, NICE)
@@ -125,8 +103,6 @@ class Holder:
return None
def release(self):
"""Every held thread back to its own mask and priority; one started during the hold gets
what its process had."""
for pid, before in self.held.items():
default = before.get(pid) or self.first()
for tid in tasks(self.proc, pid):
@@ -141,7 +117,6 @@ class Holder:
def focused(snapshot):
"""(app id, pid) of the window gamescope has focused, from droiddeck-agent's snapshot."""
window = snapshot.get("focusedWindow")
for entry in snapshot.get("focusableWindows") or []:
if entry.get("window") == window:
@@ -1,10 +1,4 @@
#!/usr/bin/python3
"""Steam's login1 sleep notifications, backed by DroidDeck's session pause.
Android owns device power. Suspend here pauses the guest through SessionService;
the app's Resume action thaws it and completes PrepareForSleep(false). Steam
must see this service before startup or it can stay black after its idle timer.
"""
import importlib.machinery
import importlib.util
import os
@@ -1,32 +1,4 @@
#!/usr/bin/python3
"""Installs a Windows Installer package (.msi) the way Wine's own msiexec would, without running it.
droiddeck-msi-install <package.msi | installer.exe> <component dir>
droiddeck-msi-install --unpack <archive | installer.exe | cabinet> <dir>
A .msi is a database: which files go to which folder, which registry values to write, which .NET
and side-by-side assemblies to register. This reads those tables (msiinfo), unpacks the package's
cabinets (cabextract, which knows every compression a cabinet can use) and lays the result out
for droiddeck-wincomponents, which puts it into a game's prefix at launch:
<component dir>/drive_c/... the files, at the paths they get on 64-bit Windows
<component dir>/registry.json the registry values, in the view (32/64-bit) Windows uses
An installer .exe is opened the same way when it is a wrapper around packages: a WiX bundle
(Visual C++ 2012 and later, the .NET Core and 5+ runtimes: the packages sit in a cabinet the
bundle's own header locates, named in its manifest), a self-extracting cabinet (Visual C++ 2005
to 2010) or a self-extracting 7-Zip archive (.NET Framework 4.0 to 4.8). The packages inside are
laid out one after the other into the same component dir; the 32- and 64-bit ones both, an ARM64
one never. An .exe that is its own setup program (NSIS, InnoSetup) holds no package: an error says so.
What a package does by running its own code (custom actions such as DXSETUP, self-registering
DLLs) cannot be done this way; each is named in the notes, so nothing is left out silently.
--unpack opens an archive or installer for the caller to take files out of (cabextract for a
cabinet or self-extracting cabinet, 7-Zip for the rest) and prints the files it found.
Prints "progress <text>" lines while it works and ends with "result <json>": the counts and notes.
"""
import json
import os
import re
@@ -47,7 +19,6 @@ SKIP_PLATFORMS = ("arm64", "arm")
def tool_env():
"""The environment the tools run in: their own libraries (libmsi, libgsf, libgcab) beside them."""
env = dict(os.environ)
env["LD_LIBRARY_PATH"] = ":".join(p for p in (str(TOOLS), env.get("LD_LIBRARY_PATH", "")) if p)
return env
@@ -95,7 +66,6 @@ class MsiError(Exception):
def progress(text, fraction=None):
"""A progress line: "progress <text>", or "progress NN% <text>" when how far along is known."""
if fraction is None:
print("progress " + text, flush=True)
else:
@@ -103,7 +73,6 @@ def progress(text, fraction=None):
class Span:
"""The slice of the whole job one package's progress maps into (a wrapper runs several)."""
def __init__(self, lo=0.0, hi=1.0):
self.lo, self.hi = lo, hi
@@ -137,7 +106,6 @@ class Package:
self.summary[name.strip().lower()] = value.strip()
def table(self, name):
"""The table's rows as dicts by column name; an absent table has none."""
if name in self._tables:
return self._tables[name]
rows = []
@@ -158,7 +126,6 @@ class Package:
def long_name(value):
"""A Directory/File name column: "short|long", the long one when there are two."""
return value.split("|")[-1]
@@ -176,7 +143,6 @@ KEYWORDS = {"not", "and", "or", "xor", "eqv", "imp"}
class Conditions:
"""Windows Installer's condition language, enough of it for what packages ask at install time."""
def __init__(self, props, feature_state=None, component_state=None):
self.props = props
@@ -318,7 +284,6 @@ class Conditions:
def win_to_rel(path):
"""C:\\windows\\x\\ -> drive_c/windows/x; None for a path off drive C or a folder left out."""
if not path:
return None
match = re.match(r"^[Cc]:\\?(.*)$", path)
@@ -341,7 +306,6 @@ def clean_version(version):
def clr_version(path):
"""The .NET runtime an assembly was built for ("v4.0.30319"), from its metadata header."""
try:
data = Path(path).read_bytes()
except OSError:
@@ -389,7 +353,6 @@ class Installer:
return 3 if name in self.included_components else -1
def directory(self, key):
"""The folder a Directory key resolves to, as drive_c/..., or None when it is left out."""
if key in self._resolving:
return None
value = self.props.get(key)
@@ -414,7 +377,6 @@ class Installer:
return parent + "/" + default
def format(self, text):
"""Formatted text: [Property], [Folder], [#file], [$component], [%env], [\\x], [~]."""
if not text:
return text
@@ -449,7 +411,6 @@ class Installer:
def run_set_actions(self):
"""The property/folder-setting custom actions, in sequence order; the rest go to the notes."""
actions = {row["Action"]: row for row in self.pkg.table("CustomAction")}
sequence = {}
for table in ("InstallUISequence", "InstallExecuteSequence"):
@@ -506,7 +467,6 @@ class Installer:
self.included_components.add(name)
def assemblies(self):
"""Component -> where its files go when it is a global assembly (the GAC or winsxs)."""
names = {}
for row in self.pkg.table("MsiAssemblyName"):
names.setdefault(row["Component_"], {})[row["Name"].lower()] = row["Value"]
@@ -535,7 +495,6 @@ class Installer:
@staticmethod
def sxs_names(ident):
"""Wine's winsxs names for a side-by-side assembly: its folder and, for a policy, the policy folder."""
arch = ident.get("processorarchitecture", "x86").lower() or "x86"
name = ident.get("name", "").lower()
token = ident.get("publickeytoken", "").lower()
@@ -548,7 +507,6 @@ class Installer:
return "assembly", "%s_%s_%s_%s_none_deadbeef" % (arch, name, token, version), version
def unpack(self, work):
"""Every cabinet in the package, unpacked; returns File key -> unpacked file."""
found = {}
media = [row for row in self.pkg.table("Media") if row.get("Cabinet", "")]
for index, row in enumerate(media):
@@ -656,7 +614,6 @@ class Installer:
self.registry.append({"hive": hive, "key": key, "name": name, "type": kind, "data": data})
def registry_data(self, raw):
"""A Registry table Value: (type, data) as droiddeck-wincomponents writes them."""
if raw is None or raw == "":
return "sz", ""
if raw.startswith("#x") or raw.startswith("#X"):
@@ -773,7 +730,6 @@ class Installer:
def sibling(path, name):
"""A file next to [path] called [name], whatever its case; None when there is none."""
folder = path.parent
candidate = folder / name
if candidate.is_file():
@@ -786,7 +742,6 @@ def sibling(path, name):
def kind_of(path):
"""What a file is by its first bytes: msi, exe, cab or other."""
with open(path, "rb") as source:
head = source.read(8)
if head.startswith(MSI_MAGIC):
@@ -806,9 +761,6 @@ def run_tool(args, timeout=1800):
def burn_containers(data):
"""A WiX bundle's containers as (offset, size) pairs: the .wixburn section of the stub names
their sizes; each is a cabinet laid out after the stub, found by its header since signing can
move them. None when the file is no bundle."""
try:
pe = struct.unpack_from("<I", data, 0x3C)[0]
if data[pe:pe + 4] != b"PE\0\0":
@@ -845,8 +797,6 @@ def burn_containers(data):
def unpack_burn(path, dest, containers):
"""Unpacks a bundle's containers into [dest] and gives the payloads the names its manifest
lists (a9 -> packages/vcRuntimeMinimum_amd64/vc_runtimeMinimum_x64.msi)."""
data = path.read_bytes()
names = {}
for index, (start, size) in enumerate(containers):
@@ -877,8 +827,6 @@ def unpack_burn(path, dest, containers):
def unpack_installer(path, dest):
"""Opens an installer or archive into [dest]: a bundle by its header, a cabinet (or
self-extracting one) with cabextract, anything else with 7-Zip."""
kind = kind_of(path)
if kind == "exe":
containers = burn_containers(path.read_bytes())
@@ -900,7 +848,6 @@ def unpack_installer(path, dest):
def packages_in(root):
"""The Windows Installer packages an unpacked installer holds, shallowest first, by name."""
found = []
for entry in sorted(root.rglob("*")):
if entry.is_file() and kind_of(entry) == "msi":
@@ -910,11 +857,6 @@ def packages_in(root):
def choose_packages(found, root):
"""Which packages make up the install: the ones at the top of the installer (a bundle keeps
each in its own folder, so there every level counts), for the x86 and x64 platforms. The .NET
Framework 4.5+ installers carry a complete product (netfx_Full_*) beside the 4.0 parts they
patch (netfx_Core_*, netfx_Extended_*) and per-Windows-version copies in NetFx* folders: the
complete product wins, the copies are left out."""
if not found:
return []
depth = min(len(entry.relative_to(root).parts) for entry in found)
@@ -933,7 +875,6 @@ def choose_packages(found, root):
def install_wrapper(path, out):
"""Lays out every package inside an installer wrapper; the result is the sum of them."""
total = {"product": "", "version": "", "counts": {"files": 0, "assemblies": 0, "registry": 0}, "notes": [], "packages": []}
with tempfile.TemporaryDirectory(dir=str(out.parent), prefix=".unpack-") as work:
dest = Path(work) / "x"
@@ -968,9 +909,6 @@ NESTED_SUFFIXES = (".7z", ".zip", ".cab", ".exe", ".msi", ".rar", ".xz", ".gz",
def open_nested(dest, depth=0):
"""Archives inside an unpacked installer (QuickTime's cabinets, an NSIS pack's payloads) are
opened in place, one "<name>.nested" folder per archive, two levels deep: the same layout the
component recordings (winlator-contents tools/snapshot/record.py) map their file sources to."""
if depth > 1:
return 0
opened = 0
@@ -1,19 +1,4 @@
#!/usr/bin/python3
"""Runs a program from the desktop: a Windows program through the Proton Steam has chosen, a Linux
program (x86 ones under FEX), an AppImage, or a script (under FEX beside x86 programs, as a game's
start script is). Shared storage is noexec: FEX runs x86 programs there where they lie (libblsession's
noexec.c), while a native one is copied - alone into the cache, or with its folder by the app once (as
Add an app does) when that holds native programs or libraries. A Steam library's games are Steam's.
droiddeck-open [--window | --terminal] FILE [ARGS...] the file manager's Run entries
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 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
import hashlib
import os
@@ -120,7 +105,6 @@ def for_x86(script):
def runnable(path):
"""The program itself, or a copy in the cache of a native one on noexec storage."""
if not noexec(path) or machine(head(path)) in EMULATED:
return path
st = os.stat(path)
@@ -141,7 +125,6 @@ def runnable(path):
def appimage(path):
"""The image unpacked once into the cache, laid out as droiddeck-appimage-run expects."""
st = os.stat(path)
real = os.path.realpath(path)
key = hashlib.sha1(("%s\0%d\0%d" % (real, st.st_size, st.st_mtime_ns)).encode("utf-8")).hexdigest()[:16]
@@ -150,7 +133,6 @@ def appimage(path):
def once(key, make):
"""[make]() for [key] one start at a time: a second start waits for the first, then finds it done."""
locks = os.path.join(CACHE, "locks")
os.makedirs(locks, exist_ok=True)
with open(os.path.join(locks, key), "w") as lock:
@@ -203,8 +185,6 @@ def import_of(key, what):
def imported(what, real, key, name):
"""[real] added by the app instead, as Add an app adds it (to the menu too): an AppImage whose hard
links (sharun's) only the app's own proot can make, or a folder of native programs off noexec storage."""
launch = os.environ.get("BL_LAUNCH_DIR")
if not launch or not os.path.isdir(launch):
raise RuntimeError("%s cannot run from here; add it in DroidDeck with Add an app." % name)
@@ -235,9 +215,6 @@ def imported(what, real, key, name):
def game_folder(path):
"""The folder of [path] when it runs only from a copy: on noexec storage, holding native programs or
libraries (besides [path]) that it starts or loads. Not the storage itself, one of Android's folders
or a Steam library."""
real = os.path.realpath(path)
folder = os.path.dirname(real)
if in_steam_library(real) or not noexec(folder):
@@ -263,12 +240,10 @@ def game_folder(path):
def in_steam_library(path):
"""Whether [path] is in a Steam library: its games are Steam's to start, never copied in."""
return "steamapps" in os.path.realpath(path).lower().split(os.sep)
def storage_root(folder):
"""The top of the storage [folder] is on: the last folder above it on the same file system."""
top = folder
try:
dev = os.stat(folder).st_dev
@@ -280,7 +255,6 @@ def storage_root(folder):
def copied_in(path):
"""The app's copy of [path]'s folder, added (once) for it."""
real = os.path.realpath(path)
key = hashlib.sha1(("folder\0%s" % real).encode("utf-8")).hexdigest()[:16]
name = os.path.basename(os.path.dirname(real))
@@ -288,7 +262,6 @@ def copied_in(path):
def steam_title(path):
"""The Steam game [path] is the program of: Steam starts it, with the client most games need."""
try:
run = runpy.run_path(PROTON_RUN)
root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or run["STEAM_ROOT"]
@@ -299,7 +272,6 @@ def steam_title(path):
def command(path, args, what, window=False, appid=None):
"""(command, working directory) that runs [path] in place."""
folder = os.path.dirname(path)
if what == "steam":
return [STEAM_LAUNCH, "desktop", appid], folder
@@ -321,7 +293,6 @@ def on_desktop(env):
def unattended(env):
"""Nobody reads the output: it goes to /dev/null or the desktop's log, as from Dolphin or the menu."""
try:
out = os.fstat(1)
except OSError:
@@ -337,7 +308,6 @@ def unattended(env):
def placed(cmd, what, mode, env):
"""[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,11 +1,4 @@
#!/usr/bin/python3
"""A game's web links to Android: Wine's winebrowser starts this (named as the browser in the
prefix's HKCU\\Software\\Wine\\WineBrowser, and as xdg-open first on a game's PATH), and an
http(s) address goes to the app, which opens it in Android's browser - so an EOS sign-in step or a
store page can be finished on the phone. Anything else goes on to the system's own xdg-open.
The session channel is $BL_LAUNCH_DIR/stores; Wine may not pass that variable on to what it
starts, so droiddeck-proton also leaves it in LAUNCH_DIR_FILE."""
import json
import os
@@ -25,7 +18,6 @@ def hand_over(url, launch_dir):
def where(url):
"""scheme://host only, for the log: no path, no query."""
from urllib.parse import urlsplit
try:
u = urlsplit(url)
@@ -89,7 +89,6 @@ def rpcs3_shader_mode():
def ini_section(lines, name):
"""(start, end) line indices of [name]'s body, or None."""
start = None
for i, l in enumerate(lines):
t = l.strip()
@@ -102,9 +101,6 @@ def ini_section(lines, name):
def patch_ini_section(path, section, body, what, needle="SDL-", require=None, done="Player 1 on the controller"):
"""Add body's lines to [section] of an ini the emulator wrote itself, unless the section
already binds a controller (needle). Missing file: nothing - the emulator writes its own
defaults on first run and this runs again."""
if not os.path.isfile(path):
return
with open(path, encoding="utf-8", errors="replace") as f:
@@ -178,7 +174,6 @@ def ini_get(path, section, key):
def ini_set(path, section, key, value):
"""Sets one key (the first of that name) in [section], adding either as needed."""
with open(path, encoding="utf-8", errors="replace") as f:
lines = f.read().splitlines()
span = ini_section(lines, section)
@@ -440,9 +435,6 @@ def armsx2():
def armsx2_bios(ini):
"""PCSX2 boots the one BIOS file named in [Filenames] BIOS (inside [Folders] Bios); its first-time
setup is what names it. With that skipped, the first dump in the folder is named here - a US one
first - while none is named or the named one is gone. A choice made in ARMSX2 is kept."""
folder = ini_get(ini, "Folders", "Bios") or ps2_bios_folder()
if not os.path.isabs(folder):
folder = os.path.join(os.path.dirname(os.path.dirname(ini)), folder)
@@ -518,12 +510,6 @@ DOLPHIN_DATA = "/usr/share/dolphin-emu"
def dolphin_data():
"""The Dolphin build in the catalog finds its own data - the GameCube fonts, the per-game fixes
(GameSettings: GUT.ini puts Ultimate Spider-Man on the MMU), its icons and shaders - only at the
fixed /usr/share/dolphin-emu it was built for; there is no setting or variable to move it. Here it
runs from a copy unpacked under /tmp (no FUSE), so it found none of it: a GameCube game stopped
on "Windows-1252 fonts are not loaded", another on an invalid write the missing game fix would
have prevented. So the folder is unpacked from the AppImage to that path, once per AppImage."""
import shutil, subprocess, tempfile
try:
st = os.stat(DOLPHIN_APPIMAGE)
@@ -716,7 +702,6 @@ def melonds_geometry():
def toml_get(lines, table, key):
"""The raw value of key in [table], or None."""
inside = False
for l in lines:
t = l.strip()
@@ -728,7 +713,6 @@ def toml_get(lines, table, key):
def toml_set(lines, table, key, value):
"""key = value in [table]; the table is added at the end when missing."""
start = None
for i, l in enumerate(lines):
t = l.strip()
@@ -1,5 +1,4 @@
#!/bin/sh
# Audio stays on the session's PulseAudio, so WirePlumber runs its upstream video-only profile.
set -u
bundle=/usr/local/lib/droiddeck-pipewire.tzst
@@ -31,7 +31,6 @@ def fetch_json(url):
def pick_asset(source):
"""(release tag, asset url, sha512 url or None) for the newest full release with an ARM64 build."""
repo, pattern = SOURCES[source]
for release in fetch_json(RELEASES % repo + "?per_page=15"):
if release.get("draft") or release.get("prerelease"):
@@ -58,8 +57,6 @@ def release_asset(source, tag):
def download(url, path):
"""Resumable, because this is hundreds of megabytes over a phone's connection. curl is used
rather than urllib so a retry continues rather than starting again."""
log("downloading %s" % os.path.basename(path))
rc = subprocess.call([
"curl", "-fL", "--retry", "5", "--retry-delay", "3", "--retry-connrefused",
@@ -1,25 +1,4 @@
#!/usr/bin/python3
"""Runs a Windows program with the Proton the Steam client has chosen for it.
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
sits in one's drive_c, or to a non-Steam shortcut that names it; any other program gets a prefix of
its own, under the id the client gives a new shortcut. That title's CompatToolMapping entry in
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 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). Without
--options it takes the launch options set in the client's Properties for that game or shortcut.
"""
import json
import os
import re
@@ -91,7 +70,6 @@ def mapping(root):
def tools(root):
"""Windows compatibility tools this runtime can start, by the name config.vdf uses."""
found = {}
for base in [os.path.join(root, "compatibilitytools.d")] + list(SYSTEM_TOOLS):
try:
@@ -121,7 +99,6 @@ def state_default():
def choose_tool(appid, current, available):
"""(tool name, why) from the client's mapping, else the session's own default."""
for key, why in ((appid, "Steam's choice for this title"), ("0", "Steam's default")):
name = current.get(key)
if name in available:
@@ -144,7 +121,6 @@ class Target:
def ancestors(path):
"""(folder, the entry below it on the way to path) from the program's folder up to /."""
child, folder = path, os.path.dirname(path)
while True:
yield folder, os.path.basename(child)
@@ -211,7 +187,6 @@ def same_file(a, b):
def shortcut_entries(root):
"""(appid, exe, start dir) of the client's non-Steam shortcuts and the app's added games."""
entries = []
try:
tool = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-steam-shortcuts"))
@@ -239,7 +214,6 @@ def shortcut_entries(root):
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))
@@ -267,7 +241,6 @@ def vdf_string(token):
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)
@@ -305,7 +278,6 @@ def shortcut(program, root):
def own_id(program):
"""The id the client gives a new shortcut: the CRC of its quoted target and its name."""
name = os.path.splitext(os.path.basename(program))[0]
return zlib.crc32(('"%s"%s' % (program, name)).encode("utf-8")) | SHORTCUT_BIT
@@ -337,8 +309,6 @@ def split_words(text):
def split_options(text):
"""A shortcut's launch options: NAME=value words before %command% go to the environment, the words
after it - or all of them, without %command% - are the program's arguments."""
words = split_words(text)
if "%command%" not in words:
return {}, words
@@ -352,7 +322,6 @@ def split_options(text):
def find_file(base, relative):
"""base/relative, matching each part without regard to case as Windows does."""
path = base
for part in [p for p in relative.replace("\\", "/").split("/") if p and p != "."]:
exact = os.path.join(path, part)
@@ -379,7 +348,6 @@ def steam_install(appid, root):
def steam_launch(appid, root):
"""(target, program, arguments) for a Steam game's default Windows launch option, or None."""
library, install = steam_install(appid, root)
if not install or not os.path.isdir(install):
return None
@@ -406,7 +374,6 @@ def shortcut_target(appid, program, start, root):
def steam_launches(target, program, root):
"""Whether a launch option of the Steam game starts [program]: then Steam should start it."""
if target.kind != "steam":
return False
entry = compat()["appinfo_entries"](os.path.join(root, "appcache", "appinfo.vdf")).get(target.appid, {})
@@ -24,7 +24,7 @@ read_scripts() { xargs -0 -r awk -v want="${1:-redists}" '
proc[depth] = 1
program = tolower(part[4])
sub(/.*[\\\/]/, "", program)
if (program ~ /vulkan|uplay|ubisoft/) vulkan[depth] = 1
if (program ~ /vulkan|uplay|ubisoft|eaapp/) vulkan[depth] = 1
next
}
if (n == 3) pending = part[2]
@@ -144,8 +144,6 @@ unseed() {
return 1
}
# The ledger lines whose values the registry still holds, in both views where we wrote both. A Proton
# update replaces its default_pfx system.reg but not our ledger beside it, and new prefixes copy both.
present() { awk -F'\t' -v hive="$hive" '
NR == FNR {
path = $1
@@ -192,10 +190,14 @@ present() { awk -F'\t' -v hive="$hive" '
regs=()
for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/mnt/droiddeck-sd/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/mnt/droiddeck-lib/*/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/mnt/droiddeck-lib/*/x86-64/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/root/Games/*/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
"$steam_root"/compatibilitytools.d/*/files/share/default_pfx*/system.reg \
"$steam_root"/steamapps/compatdata/*/pfx/system.reg \
/mnt/droiddeck-sd/steamapps/compatdata/*/pfx/system.reg \
/mnt/droiddeck-lib/*/steamapps/compatdata/*/pfx/system.reg \
/mnt/droiddeck-lib/*/x86-64/steamapps/compatdata/*/pfx/system.reg \
/root/Games/*/steamapps/compatdata/*/pfx/system.reg; do
[ -f "$reg" ] && regs+=("$reg")
done
@@ -243,7 +245,7 @@ for system in "${regs[@]}"; do
had=()
for line in "${kept[@]}"; do had[$line]=1; done
printf '%s\n' "${other[@]}" "${kept[@]}" >"$seeded"
echo "== took Vulkan runtime and Ubisoft Connect markers out of $reg"
echo "== took Vulkan runtime, Ubisoft Connect and EA app markers out of $reg"
fi
if [ ${#had[@]} -gt 0 ] && { [ -z "$id" ] || [ "$id" != "$prev" ]; }; then
declare -A held=()
@@ -99,6 +99,8 @@ clear_stale_tmp() {
[ -z "${BL_INSIDE:-}" ] && clear_stale_tmp
if [ -z "${BL_INSIDE:-}" ]; then
if [ "${BL_ZRAM:-0}" = 1 ]; then printf 0 > /tmp/.bl-zram; else rm -f /tmp/.bl-zram; fi
rm -f /tmp/.bl-clock
head -c 8 /dev/zero > /tmp/.bl-clock
fi
steam_devtools() {
@@ -136,7 +138,6 @@ run_gamescope() (
local status_file child_status compositor_status
status_file=$(mktemp "${XDG_RUNTIME_DIR:-/tmp}/droiddeck-steam-exit.XXXXXX") || exit 73
trap 'rm -f "$status_file"' EXIT
# Gamescope can return success when its primary child crashed.
BL_STEAM_EXIT_FILE="$status_file" gamescope "$@"
compositor_status=$?
if read -r child_status < "$status_file" && [[ $child_status =~ ^[0-9]{1,3}$ ]] \
@@ -159,7 +160,7 @@ collect_steam_logs() {
cp "$fex_state/status.json" "$fex_state/config/Config.json" "$BL_DEBUG_DIR/droiddeck-fex/" 2>/dev/null
fi
}
trap 'collect_steam_logs 2>/dev/null || true' TERM INT HUP
trap 'bl_stopping=1; collect_steam_logs 2>/dev/null || true' TERM INT HUP
if [ -n "${BL_VK_DRIVER:-}" ]; then
bl_icd_lib=$(sed -n 's/.*"library_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$BL_VK_DRIVER" 2>/dev/null | head -1)
bl_icd_lib=$(printf '%s' "$bl_icd_lib" | sed 's|\\/|/|g')
@@ -176,6 +177,83 @@ if [ -n "${BL_VK_DRIVER:-}" ]; then
fi
unset bl_icd_lib
fi
bl_webhelper_layout() {
if [ -n "${BL_VKBRIDGE_WEBHELPER_ARGS:-}" ]; then
printf '%s\n' "$BL_VKBRIDGE_WEBHELPER_ARGS"
elif [ -z "${BL_VKBRIDGE_CEF_ANGLE:-}" ]; then
echo stock
elif [ "$BL_VKBRIDGE_CEF_ANGLE" = vulkan ] && [ "${BL_VKBRIDGE_CEF_VULKAN:-1}" != 0 ]; then
echo "--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan"
else
echo "--use-gl=angle --use-angle=$BL_VKBRIDGE_CEF_ANGLE"
fi
}
bl_now_ms() {
if [ -n "${EPOCHREALTIME:-}" ]; then
local t=${EPOCHREALTIME/[.,]/}
echo $((10#$t / 1000))
else
date +%s%3N
fi
}
vkbridge_wait_socket() {
local sock=$1 limit=${2:-10000} start now waited
[ -n "$sock" ] || return 1
if [ -S "$sock" ]; then
echo "== vkbridge: server socket ready (waited 0 ms)"
return 0
fi
start=$(bl_now_ms)
while :; do
now=$(bl_now_ms)
waited=$((now - start))
if [ -S "$sock" ]; then
echo "== vkbridge: server socket ready (waited $waited ms; the server listens after its startup probe)"
return 0
fi
if [ -n "${bl_stopping:-}" ]; then
echo "== vkbridge: no server socket after $waited ms; the session is stopping"
return 1
fi
if [ "$waited" -ge "$limit" ]; then
echo "== vkbridge: no server socket after $waited ms (gave up at $limit ms)"
return 1
fi
sleep 0.05
done
}
if [ "${BL_VKBRIDGE:-0}" = 1 ]; then
bl_vkb_icd=/usr/local/share/vkbridge/droidbridge_icd.json
[ -z "${BL_INSIDE:-}" ] && vkbridge_wait_socket "${VKBRIDGE_SOCKET:-}" "${BL_VKBRIDGE_WAIT_MS:-10000}"
bl_vkb_missing=
[ -r "$bl_vkb_icd" ] || bl_vkb_missing="$bl_vkb_missing icd"
[ -r /usr/local/lib/vkbridge/libvulkan_droidbridge.so ] || bl_vkb_missing="$bl_vkb_missing library"
[ -S "${VKBRIDGE_SOCKET:-}" ] || bl_vkb_missing="$bl_vkb_missing socket"
if [ -z "$bl_vkb_missing" ]; then
export VK_DRIVER_FILES=$bl_vkb_icd VK_ICD_FILENAMES=$bl_vkb_icd
export VKBRIDGE_SOCKET VKBRIDGE_CLIENT_LOG
if [ -r /root/.vkbridge-env ]; then
while IFS='=' read -r _k _v; do
case "$_k" in VKBRIDGE_*|BL_VKBRIDGE_*) export "$_k=$_v" ;; esac
done < /root/.vkbridge-env
[ -z "${BL_INSIDE:-}" ] && echo "== vkbridge: development settings from /root/.vkbridge-env: $(cut -d= -f1 /root/.vkbridge-env | tr '\n' ' ')"
fi
export VKD3D_FEATURE_LEVEL=${VKD3D_FEATURE_LEVEL:-12_0}
unset TU_DEBUG
if [ -z "${BL_INSIDE:-}" ]; then
step "vkbridge self-test"
timeout 60 /usr/local/bin/droiddeck-vkbridge-smoke 2>&1 | sed 's/^/== vkbridge: /'
if command -v vulkaninfo >/dev/null 2>&1; then
timeout 30 vulkaninfo --summary 2>&1 | sed -n '/^Devices:/,$p' | head -40 | sed 's/^/== vulkaninfo: /'
fi
fi
echo "== vulkan driver: Mali bridge ($bl_vkb_icd, server at $VKBRIDGE_SOCKET)"
else
echo "== vulkan driver: Mali bridge requested but NOT usable (icd $bl_vkb_icd, socket ${VKBRIDGE_SOCKET:-unset}; missing:$bl_vkb_missing)"
[ -n "${BL_INSIDE:-}" ] || exit 69
fi
unset bl_vkb_icd bl_vkb_missing
fi
export GAMESCOPE_FORCE_VULKAN_REALTIME=${BL_GAMESCOPE_REALTIME:-0}
start_agent() {
@@ -303,11 +381,16 @@ if [ -z "${BL_INSIDE:-}" ]; then
echo "== gamescope: games at ${nested}x${nested_h} stretched to the ${width}x${height} output"
fi
fi
# Off unless Performance asks for it. Compositing the cursor here adds a second
# plane on the phone's compositor; a controller-driven cursor is the reason to turn it on.
if [ "$mode" = steam ] && [ "${BL_CURSOR_COMPOSITE:-0}" = 1 ]; then
export gamescope_cursor_composite=2
fi
# Through the Mali bridge, Steam's UI flickered while gamescope handed its layers to the phone's
# compositor as separate planes, for a reason not yet found; one composited image does not
# (Mali-G76 MC4: 145 footer flips in 6 s at rest, 0 composited).
if [ "$mode" = steam ] && [ "${BL_VKBRIDGE:-0}" = 1 ] && [ -z "${gamescope_composite_force:-}" ]; then
export gamescope_composite_force=1
echo "== gamescope: composites every frame (Mali bridge: the Steam UI flickers on separate planes)"
fi
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h")
if [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; then
args+=(-S stretch)
@@ -315,7 +398,6 @@ if [ -z "${BL_INSIDE:-}" ]; then
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)
@@ -334,10 +416,8 @@ if [ -z "${BL_INSIDE:-}" ]; then
args+=(--mangoapp)
echo "== gamescope: mangoapp on ($(command -v mangoapp), config $MANGOHUD_CONFIGFILE)"
fi
# gamescope writes the frame times the app's HUD shows here (patch 0125).
mkdir -p /run/droiddeck-hud && export DROIDDECK_HUD_FRAMES=/run/droiddeck-hud/frames
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"
@@ -467,7 +547,6 @@ case $mode in
steam_cef_gpu=1
if [ "$steam_x64" = 1 ]; then
step "checking the Steam client's arm64 parts (first run downloads them, ~1-2 min)"
# droiddeck-steam-install removes the repair request: read it first so Repair Steam covers both clients.
_bl_x64_repair=0
[ -e "$HOME/.bl-steam-repair" ] && _bl_x64_repair=1
droiddeck-steam-install || steam_setup_failed $?
@@ -538,7 +617,7 @@ case $mode in
fi
if [ "${BL_ZRAM:-0}" = 1 ]; then
step "zRAM compression: on"
[ "${BL_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam and the hidden Epic Games Launcher are not compressed while games run (turned off in Performance)"
[ "${BL_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam, the hidden Epic Games Launcher and Battle.net are not compressed while games run (turned off in Performance)"
_bl_ram_cap=0
case ${BL_RAM_CAP_MB:-} in
''|0) ;;
@@ -548,11 +627,10 @@ case $mode in
(
bl_zram_scan() {
_bl_game=0 _bl_pids=() _bl_others=() _bl_apps=
local _d _c _args _name _a _id _fex
local _d _c _args _name _a _id _fex _lower _bnet=() _bnet_game=0
for _d in /proc/[0-9]*; do
[ "${_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]} _fex=0
@@ -573,14 +651,34 @@ case $mode in
;;
steam|steamwebhelper) _bl_pids+=("${_d##*/}") ;;
*)
_lower=${_name,,}
if [ "$_fex" = 1 ] && grep -qz '^DROIDDECK_EPIC_HIDDEN=1$' "$_d/environ" 2>/dev/null; then
_bl_pids+=("${_d##*/}")
elif [[ $_lower == [a-z]:[\\/]'program files (x86)'[\\/]battle.net[\\/]* ||
$_lower == [a-z]:[\\/]programdata[\\/]battle.net[\\/]* ]]; then
_bnet+=("${_d##*/}")
else
_bl_others+=("${_d##*/}")
if [[ $_lower == [a-z]:[\\/]* ]]; then
case ${_lower##*[\\/]} in
agent.exe|conhost.exe|explorer.exe|lsass.exe|plugplay.exe|rpcss.exe|services.exe|start.exe|\
steam.exe|svchost.exe|tabtip.exe|winedevice.exe|rundll32.exe|wineboot.exe|winemenubuilder.exe) ;;
*)
for _a in "${_args[@]:1}"; do
[ "${_a,,}" = -uid ] && _bnet_game=1
done
;;
esac
fi
fi
;;
esac
done
if [ "$_bnet_game" = 1 ]; then
_bl_pids+=("${_bnet[@]}")
else
_bl_others+=("${_bnet[@]}")
fi
}
bl_zram_usage() {
local _p _k _v _u _rss=0 _swap=0
@@ -592,7 +690,6 @@ case $mode in
_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=()
@@ -608,8 +705,6 @@ case $mode in
_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
@@ -637,9 +732,6 @@ case $mode in
bl_zram_pick "$_which"
step "zRAM: done ($(bl_zram_usage "${_pids[@]}"))"
}
# 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
@@ -668,7 +760,6 @@ case $mode in
bl_zram_scan
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
@@ -857,14 +948,11 @@ case $mode in
until [ "$(_bl_focused)" = 769 ] || [ "$SECONDS" -ge "$_bl_end" ]; do
sleep 1
done
# Shortcut CGameIDs are 64-bit; Steam app ids fit in 32 bits and keep the old short delay.
[ "${#game}" -gt 10 ] && shortcut=1
[ -n "$shortcut" ] || sleep 4
echo "== steam: interface up; launching the requested game $game"
_bl_hand_off
[ -n "$shortcut" ] || return 0
# Steam can drop a shortcut launch it gets before the shortcut's overview exists (large libraries).
# A launch can be running before it creates its first window.
while [ "$(_bl_focused)" = 769 ] && [ "$waited" -lt 20 ]; do
sleep 1
waited=$((waited + 1))
@@ -956,13 +1044,11 @@ case $mode in
exit 69
fi
# The UI bridge launches SteamVR, which needs the guest agent's library environment.
_bl_compat_env=(env -u LD_LIBRARY_PATH -u STEAM_RUNTIME -u STEAM_STEAMRT_RECURSION_GUARD)
[ "${LD_LIBRARY_PATH+x}" ] && _bl_compat_env+=("LD_LIBRARY_PATH=$LD_LIBRARY_PATH")
[ "${STEAM_RUNTIME+x}" ] && _bl_compat_env+=("STEAM_RUNTIME=$STEAM_RUNTIME")
[ "${STEAM_STEAMRT_RECURSION_GUARD+x}" ] && _bl_compat_env+=("STEAM_STEAMRT_RECURSION_GUARD=$STEAM_STEAMRT_RECURSION_GUARD")
export STEAM_RUNTIME=1
# A containerized client re-executes itself through pressure-vessel-wrap (bwrap) unless told it is already inside.
export STEAM_STEAMRT_RECURSION_GUARD=1
export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
export SDL_VIDEO_X11_DGAMOUSE=0
@@ -1021,6 +1107,28 @@ case $mode in
_bl_cef=(-cef-disable-gpu)
_bl_ui=(-nobigpicture)
fi
if [ "${BL_VKBRIDGE:-0}" = 1 ]; then
# On the GPU the Steam UI held about 400 MB through the bridge (Mali-G76 MC4, 3 GB of RAM); with
# a game loading beside it, Android's low-memory killer took the whole session down.
if [ -z "${BL_VKBRIDGE_CEF_GPU:-}" ]; then
_bl_mem_kb=$(awk '/^MemTotal:/ {print $2}' /proc/meminfo 2>/dev/null)
if [ "${_bl_mem_kb:-0}" -gt 0 ] && [ "$_bl_mem_kb" -lt 4194304 ]; then
BL_VKBRIDGE_CEF_GPU=0
echo "== steam: $((_bl_mem_kb / 1024)) MB of RAM: the browser UI draws in software to leave games the memory"
fi
fi
if [ "${BL_VKBRIDGE_CEF_GPU:-1}" = 0 ]; then
_bl_cef=(-cef-disable-gpu -cef-disable-gpu-compositing)
echo "== steam: browser UI in software (Mali bridge)"
elif [ "${_bl_cef[0]}" = -cef-force-gpu ]; then
_bl_cef=(-cef-force-gpu -cef-use-gl=angle -cef-use-angle="${BL_VKBRIDGE_CEF_ANGLE:-vulkan}")
fi
[ "${BL_VKBRIDGE_CEF_LOG:-0}" = 1 ] && _bl_cef+=(-cef-enable-logging=stderr -cef-v=1)
[ -n "${BL_VKBRIDGE_CEF_EXTRA:-}" ] && read -r -a _bl_cef_extra <<<"$BL_VKBRIDGE_CEF_EXTRA" && _bl_cef+=("${_bl_cef_extra[@]}")
BL_WEBHELPER_ARGS=$(bl_webhelper_layout)
export BL_WEBHELPER_ARGS
echo "== steam: web helper process layout: $BL_WEBHELPER_ARGS (Mali bridge)"
fi
if [ "${BL_STEAM_UI:-}" != desktop ]; then
if [ "$steam_x64" = 0 ] || [ "${BL_X64_DECK:-1}" != 0 ]; then
_bl_ui+=(-steamdeck -steamos3)
@@ -1215,13 +1323,12 @@ case $mode in
: > "$compat_restarted"
compat_restarts=0
compat_settled() {
local app m flags r card=/mnt/droiddeck-sd
# The arm64 card library may hold that client's copy of the same title.
[ "$steam_x64" = 1 ] && card=/mnt/droiddeck-sd/x86-64
local app m flags r card=/mnt/droiddeck-sd added=(/mnt/droiddeck-lib/*)
[ "$steam_x64" = 1 ] && { card=/mnt/droiddeck-sd/x86-64; added=(/mnt/droiddeck-lib/*/x86-64); }
while read -r app; do
[ -n "$app" ] || continue
m=
for r in "$steam_root" "$card"; do
for r in "$steam_root" "$card" "${added[@]}"; do
[ -f "$r/steamapps/appmanifest_$app.acf" ] && { m=$r/steamapps/appmanifest_$app.acf; break; }
done
[ -n "$m" ] || return 1
@@ -1290,7 +1397,7 @@ case $mode in
done
fi
if [ "$beat" -le 720 ] && [ "$((beat % 3))" -eq 0 ] && { [ -z "$library_job" ] || ! kill -0 "$library_job" 2>/dev/null; }; then
libraries=("$steam_root/steamapps" /mnt/droiddeck/steamapps /mnt/droiddeck-sd/steamapps /root/Games/*/steamapps)
libraries=("$steam_root/steamapps" /mnt/droiddeck/steamapps /mnt/droiddeck-sd/steamapps /mnt/droiddeck-lib/*/steamapps /mnt/droiddeck-lib/*/x86-64/steamapps /root/Games/*/steamapps)
seed=; compat=
seed_due && seed=1
compat_due && compat=1
@@ -1333,7 +1440,6 @@ case $mode in
lossless_left=0
elif ! pgrep -x wineserver >/dev/null 2>&1; then
(
# The probe reaches the x86-64 client through the arm64 client's steamclient.so, as the import watcher does.
if [ "$steam_x64" = 1 ]; then export BL_STEAMCLIENT=$XDG_DATA_HOME/Steam/steamrtarm64/steamclient.so; fi
answer=$(droiddeck-steam-games probe "$steam_root" 993090 2>/dev/null) || exit 0
case $answer in
@@ -1393,7 +1499,6 @@ case $mode in
BL_COMPAT_TOOL=$_bl_x64_tool droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
fi
fi
# The x86-64 client rewrote config.vdf from memory on exit, over the live passes' mapping.
if [ "$steam_x64" = 1 ]; then
[ -z "${_bl_x64_tool:-}" ] ||
BL_COMPAT_TOOL=$_bl_x64_tool steam-compatibility "$steam_root" --x64 >/dev/null 2>&1 || true
@@ -1439,6 +1544,12 @@ case $mode in
set --
continue
fi
if [ "$steam_x64" = 1 ] && [ "$rc" -eq 132 ] && [ -z "${_bl_x64_sigill:-}" ]; then
_bl_x64_sigill=1
echo "== steam: the x86-64 client stopped on an illegal instruction after it updated itself; starting it again once"
set --
continue
fi
[ "$rc" -eq 42 ] || break
if steam_update_stuck "$steam_ran"; then
echo "== steam: asked to restart for an update $steam_updates times and it is not installing; the session stops here rather than loop"
@@ -18,6 +18,19 @@ COMPAT = runpy.run_path(os.path.join(HERE, "steam-compatibility"))
BINDING = "droiddeckCompatChanged"
BRIGHTNESS_BINDING = "droiddeckBrightnessChanged"
CONTROLS_DIR = "/etc/droiddeck-device-controls"
LIBRARY_ART_JS = r"""
(() => {
if (window.__droiddeckLibraryArt) return "present";
const store = typeof appStore === "object" ? appStore : null;
if (typeof store?.BHasCachedLibraryAsset !== "function") return "unavailable";
// The client reports which cached assets exist only after a logon that reaches Steam; before that every app reads as
// uncached and the UI asks the CDN, which is blank offline. The native check still runs, so misses are still reported.
const native = store.BHasCachedLibraryAsset.bind(store);
store.BHasCachedLibraryAsset = (appid, version, type) => native(appid, version, type) || !version;
window.__droiddeckLibraryArt = true;
return "installed";
})()
"""
BRIGHTNESS_JS = r"""
(() => {
if (window.__droiddeckBrightness) return "present";
@@ -233,10 +246,6 @@ SWITCH_JS = r"""
})()
""".replace("__BINDING__", SWITCH_BINDING)
SESSION_SELECT = "/usr/bin/steamos-session-select"
# Steam opens its Steam Controller welcome tour at every start while the client setting
# controller_show_ibex_tour (CMsgClientSettings field 140014) is on, and only a finished tour turns it
# off; closing it leaves it on. The app's pad is an emulated controller, so the tour never applies.
# A pending firmware update still opens Steam's updater, which checks the update priority instead.
TOUR_JS = r"""
(() => {
let key = 140014 * 8;
@@ -247,13 +256,6 @@ 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";
@@ -426,7 +428,6 @@ VR_JS = r"""
def launch_steamvr():
"""Keep downloads/startup off the Steam UI bridge's event loop."""
say("SteamVR library launch: using the DroidDeck ARM64 helper")
state = os.path.join(os.environ.get("XDG_RUNTIME_DIR", "/tmp"), "droiddeck-steamvr")
try:
@@ -780,7 +781,6 @@ class Helper:
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:
@@ -806,8 +806,6 @@ class Helper:
self.finish_chooser(ident, None)
return
command = [sys.executable, os.path.realpath(__file__), "--choose-file"]
# 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")
@@ -866,6 +864,7 @@ class Helper:
if self.files_only:
page.call("Runtime.addBinding", {"name": FILE_BINDING})
page.evaluate(FILE_JS)
page.evaluate(LIBRARY_ART_JS)
self.page = page
self.controls_state = None
self.controls_installed = False
@@ -876,10 +875,10 @@ class Helper:
page.evaluate(VR_JS)
page.call("Runtime.addBinding", {"name": FILE_BINDING})
page.evaluate(FILE_JS)
page.evaluate(LIBRARY_ART_JS)
try:
page.evaluate(TOUR_JS)
except RuntimeError:
# The optional tour setting must not block the compat bridge.
pass
if not self.steamos:
page.call("Runtime.addBinding", {"name": SWITCH_BINDING})
@@ -916,7 +915,6 @@ class Helper:
prior_auto = state.get("auto", {})
if not isinstance(prior_auto, dict):
prior_auto = {}
# "native" from earlier builds also lists dual-platform games nobody chose to run natively.
prior_native = state.get("native_choices", ())
native_choices = set(prior_native if isinstance(prior_native, (list, tuple, set)) else ())
picked = COMPAT["picked_apps"](state)
@@ -948,7 +946,6 @@ class Helper:
else:
for app in set(native) | native_choices:
if app in raw_mapping:
# The client shows an explicit native choice as the tool it inherits, and writes config.vdf late.
if raw_mapping[app] == "" or current.get(app) not in self.known:
current[app] = raw_mapping[app]
elif app in prior_auto or app in native_choices or app in picked and (
@@ -981,7 +978,6 @@ class Helper:
COMPAT["write_json"](state_file, state)
def ensure_tools(self):
"""Proton, FEX and the runtimes FEX needs are fetched as soon as the client is up, never left pending."""
now = time.monotonic()
if self.tools_checked is not None and now - self.tools_checked < TOOL_CHECK_SECONDS:
return
@@ -1007,7 +1003,6 @@ class Helper:
return isinstance(request.get("seq"), int) and request["seq"] > int(state.get("applied", 0) or 0)
def drain(self):
"""The page's events; a switch to the desktop is acted on as it comes."""
events = self.page.drain()
if any(called(e, SWITCH_BINDING) for e in events):
switch_to_desktop()
@@ -1,5 +1,4 @@
#!/usr/bin/python3
"""Honor a desktop launch even when Steam remembers Big Picture from its last session."""
import os
from pathlib import Path
import runpy
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
"""Resolve added games against the signed-in Steam client's licenses."""
import ctypes as C
import json
import os
@@ -12,6 +11,7 @@ import time
import unicodedata
import urllib.parse
import urllib.request
import zlib
STATE = ".droiddeck-games.json"
TRIED = ".droiddeck-import-tried.json"
@@ -20,6 +20,7 @@ LIBRARY = "/mnt/droiddeck-sd"
LEGACY_LIBRARY = "/mnt/bannerlator-sd"
PARKED = ".droiddeck-parked"
BASE_ID = 76561197960265728
SPACEWAR = 480
def read_json(path, default):
@@ -65,8 +66,6 @@ def source_stamp(game):
def store_game(game):
"""Games a store client installed belong to that store: the Steam copy of the same title is
another license with its own files, and an import would let Steam update over the store's."""
return bool(game.get("store"))
@@ -86,14 +85,14 @@ def identify(game):
folder = Path(game["folder"])
steamapps = folder.parent.parent
for library in ([steamapps] if folder.parent.name == "common" and steamapps.name == "steamapps" else []) + [folder.parent / WINNATIVE]:
matches = manifest_ids(library, folder.name)
matches = [appid for appid in manifest_ids(library, folder.name) if appid != SPACEWAR]
if matches:
return matches[0] if len(matches) == 1 else None
ids = set()
for parent in {folder, Path(game["exe"]).parent}:
try:
appid = int((parent / "steam_appid.txt").read_text().strip())
if 0 < appid < 0x80000000:
if 0 < appid < 0x80000000 and appid != SPACEWAR:
ids.add(appid)
except (OSError, ValueError):
pass
@@ -107,7 +106,7 @@ def identify(game):
ids = {int(item["id"]) for item in items
if key(item.get("name", "")) == key(game["name"]) and key(game["name"])}
if ids:
return next(iter(ids)) if len(ids) == 1 else None
return next(iter(ids)) if len(ids) == 1 and SPACEWAR not in ids else None
return None
except (OSError, ValueError, KeyError):
return None
@@ -149,7 +148,6 @@ def probe(steam_root, ids):
def game_running():
"""Whether a Proton game is up: a wineserver is there for as long as any prefix is in use."""
try:
pids = [p for p in os.listdir("/proc") if p.isdigit()]
except OSError:
@@ -172,8 +170,6 @@ def downloads_idle(steam_root):
def request_restart(steam_root):
"""The client reads manifests and shortcuts only at start, so an import needs one restart;
the session's loop runs the importer between the exit and the next start."""
Path(os.environ.get("HOME", "/root"), ".bl-restart-once").touch()
command = shlex.split(os.environ.get("BL_STEAM_SHUTDOWN", "")) or [str(Path(steam_root) / "steamrtarm64/steam"), "-shutdown"]
subprocess.run(command,
@@ -181,7 +177,6 @@ def request_restart(steam_root):
def ask_restart(names, timeout=600, clock=None, sleep=None):
"""The app asks whether to restart the client now; anything but "now" leaves the import to the next start."""
clock, sleep = clock or time.monotonic, sleep or time.sleep
folder = Path(os.environ.get("HOME", "/root"), ".cache/droiddeck")
ask, answer = folder / "steam-import.json", folder / "steam-import.answer"
@@ -295,8 +290,6 @@ def watch(steam_root, listing):
def installed_build(folder, appid, installdir):
"""The build another Steam client recorded for these files, so Steam updates from it
instead of verifying every file."""
try:
text = (folder.parent / WINNATIVE / f"appmanifest_{appid}.acf").read_text()
install = re.search(r'("installdir"\s*")([^"\\]*)(")', text, re.I)
@@ -309,15 +302,76 @@ def installed_build(folder, appid, installdir):
if not (folder / ".download_complete").is_file():
return None
try:
ids = json.loads((folder / ".DepotDownloader/depot.config").read_text())["installedManifestIDs"]
depots = sorted((int(depot), int(gid)) for depot, gid in ids.items())
except (OSError, ValueError, KeyError, TypeError, AttributeError):
return None
depots = config_depots((folder / ".DepotDownloader/depot.config").read_bytes())
except OSError:
depots = None
if not depots:
depots = completed_depots(folder / ".DepotDownloader/completed")
if not depots or not all(0 < depot < 0x80000000 and 0 < gid < 0x7FFFFFFFFFFFFFFF for depot, gid in depots):
return None
return "".join(f' "{depot}"\n {{\n "manifest" "{gid}"\n }}\n' for depot, gid in depots)
def varint(data, i):
value = shift = 0
while True:
byte = data[i]
i += 1
value |= (byte & 0x7F) << shift
shift += 7
if byte < 0x80:
return value, i
def proto_fields(data):
i = 0
while i < len(data):
key, i = varint(data, i)
kind = key & 7
if kind == 0:
value, i = varint(data, i)
elif kind == 2:
size, i = varint(data, i)
value, i = data[i:i + size], i + size
elif kind in (1, 5):
value, i = None, i + (8 if kind == 1 else 4)
else:
raise ValueError
yield key >> 3, kind, value
def config_depots(data):
try:
ids = json.loads(data.decode())["installedManifestIDs"]
return sorted((int(depot), int(gid)) for depot, gid in ids.items())
except (ValueError, KeyError, TypeError, AttributeError):
pass
try:
depots = {}
for number, kind, entry in proto_fields(zlib.decompress(data, -15)):
if number == 1 and kind == 2:
fields = {n: v for n, k, v in proto_fields(entry) if k == 0}
if 1 in fields and 2 in fields:
depots[fields[1]] = fields[2]
return sorted(depots.items()) or None
except (zlib.error, ValueError, IndexError):
return None
def completed_depots(completed):
newest = {}
try:
for manifest in completed.iterdir():
match = re.fullmatch(r"(\d+)_(\d+)\.manifest", manifest.name)
if match and manifest.is_file():
depot, gid, mtime = int(match[1]), int(match[2]), manifest.stat().st_mtime
if depot not in newest or mtime > newest[depot][0]:
newest[depot] = (mtime, gid)
except OSError:
return []
return sorted((depot, gid) for depot, (_, gid) in newest.items())
def update_not_started(text, steamapps, appid, installdir):
fields = dict(re.findall(r'^\s*"(\w+)"\s*"([^"]*)"', text, re.M))
return (fields.get("installdir") == installdir and fields.get("buildid", "0") == "0"
@@ -423,20 +477,18 @@ def seed_install(steam_root, game, appid):
return True
def release(steam_root, game):
"""Undoes an import made before store games were skipped. Only our symlink and manifest go;
the store's folder stays where it is."""
def release(steam_root, game, stale, reason):
steamapps = Path(steam_root) / "steamapps"
sources = {game.get("folder", ""), legacy_path(game.get("folder", ""))}
for target in sorted((steamapps / "common").glob("DroidDeck-*")):
appid = target.name.removeprefix("DroidDeck-")
if not (appid.isdigit() and target.is_symlink() and os.readlink(target) in sources):
if not (appid.isdigit() and target.is_symlink() and os.readlink(target) in sources and stale(int(appid))):
continue
for manifest in (steamapps / f"appmanifest_{appid}.acf", steamapps / PARKED / f"appmanifest_{appid}.acf"):
if manifest.is_file() and ours(manifest, appid):
manifest.unlink()
target.unlink()
print(f"droiddeck-steam-games: {game.get('name', appid)} came from {game['store']}; it is a shortcut again, not Steam app {appid}")
print(f"droiddeck-steam-games: {game.get('name', appid)} {reason}; it is no longer Steam app {appid}")
def route(steam_root, acct, games):
@@ -457,7 +509,7 @@ def route(steam_root, acct, games):
for game in games:
if store_game(game):
try:
release(steam_root, game)
release(steam_root, game, lambda old: True, f"came from {game['store']}")
except OSError as error:
print(f"droiddeck-steam-games: store import not undone ({error})")
shortcuts.append(game)
@@ -469,9 +521,14 @@ def route(steam_root, acct, games):
appid = candidates.get(folder, candidates.get(legacy_path(folder)))
stamp = source_stamp(game)
recorded = sources.get(folder, sources.get(legacy_path(folder)))
confirmed = (isinstance(appid, int) and 0 < appid < 0x80000000
and owned.get(str(appid)) is True and stamp is not None
and recorded in (stamp, [stamp[0], legacy_path(stamp[1])] + stamp[2:]))
current = stamp is not None and recorded in (stamp, [stamp[0], legacy_path(stamp[1])] + stamp[2:])
named = isinstance(appid, int) and 0 < appid < 0x80000000 and appid != SPACEWAR
try:
release(steam_root, game, lambda old: old == SPACEWAR or (current and named and old != appid),
"names another Steam app now")
except OSError as error:
print(f"droiddeck-steam-games: earlier import not undone ({error})")
confirmed = named and current and owned.get(str(appid)) is True
if confirmed:
try:
if seed_install(steam_root, game, appid):
@@ -480,7 +537,7 @@ def route(steam_root, acct, games):
print(f"droiddeck-steam-games: {game.get('name', appid)} stays a shortcut this session: it could not be linked as Steam app {appid}")
except OSError as error:
print(f"droiddeck-steam-games: import unavailable ({error})")
elif isinstance(appid, int) and 0 < appid < 0x80000000 and seeded(steamapps, game, appid):
elif named and seeded(steamapps, game, appid):
routes[str(game["appid"])] = appid
continue
shortcuts.append(game)
@@ -227,7 +227,6 @@ mkdir -p "$HOME/.steam"
ln -sfn "$steam_root" "$HOME/.steam/root"
ln -sfn "$steam_root" "$HOME/.steam/steam"
ln -sfn "$steam_root/steamrtarm64" "$HOME/.steam/bin64"
# sdk64 is where x86_64 Steamworks looks for steamclient.so; arm64 builds look in sdkarm64.
ln -sfn "$steam_root/linux64" "$HOME/.steam/sdk64"
ln -sfn "$steam_root/linuxarm64" "$HOME/.steam/sdkarm64"
ln -sfn "$steam_root/steamrtarm64" "$HOME/.steam/binarm64"
@@ -1,18 +1,4 @@
#!/usr/bin/python3
"""Sets the Steam client's interface language to the app's, before the client starts.
droiddeck-steam-language <home> <language>
<language> is one of the client's language names (english, spanish, latam, japanese, koreana,
schinese, tchinese, ...). The client reads it from <home>/.steam/registry.vdf, under
HKCU/Software/Valve/Steam and again under .../Steamsteamglobal: that second key is copied over the
first at every start, so setting only the first is undone by the old value. Its update window
reads the first key alone, and nothing reads LANG. exportedsettings.json is what the client writes
beside them when its own setting changes. The session also passes -language, which the interface
honours over the file; the file is still what the update window shows itself in.
Run only while the client is stopped: it keeps the registry in memory and writes it back on exit.
"""
import json
import os
import re
@@ -63,7 +49,6 @@ def serialize(tokens):
def block_end(tokens, start):
"""Index of the '}' closing the block whose '{' is at start."""
depth = 0
for i in range(start, len(tokens)):
if tokens[i] == "{":
@@ -76,8 +61,6 @@ def block_end(tokens, start):
def child(tokens, start, end, name):
"""Index of the '{' of the block called name directly inside tokens[start:end], or None.
Keys are matched without case, as the client does."""
i = start
while i < end:
if tokens[i] in ("{", "}"):
@@ -93,7 +76,6 @@ def child(tokens, start, end, name):
def ensure_block(tokens, path):
"""The '{' of the block at path, creating it and any missing parent at the end of its parent."""
start, end = 0, len(tokens)
for depth, name in enumerate(path):
found = child(tokens, start, end, name)
@@ -25,6 +25,14 @@ if [ "$ui" = desktop ] && [ "${BL_DESKTOP:-}" = 1 ]; then
client_home=$HOME
client=("$steam_root/steamrtarm64/steam")
fi
if [ "${BL_BOTTOM_DESKTOP:-}" = 1 ]; then
pid=$(cat "$client_home/.steam/steam.pid" 2>/dev/null || true)
if [ -p "$client_home/.steam/steam.pipe" ] && [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then
# The top screen's client takes the request, so games open there.
exec "${client[@]}" -nobigpicture -no-cef-sandbox \
-cef-ozone-platform=x11 -cef-disable-gpu "${url:-steam://open/library}"
fi
fi
mkdir -p "${XDG_CACHE_HOME:-$HOME/.cache}/droiddeck"
exec 9>"${XDG_CACHE_HOME:-$HOME/.cache}/droiddeck/steam-desktop.lock"
if ! flock -n 9; then
@@ -9,9 +9,6 @@ MAIN_LABEL = "Internal Storage"
def register(steam_root, library, label):
"""Adds one library folder to the client's list; the client then offers it as an install
location as well as reading the games already in it. Registered even when empty: a new user
should be able to install straight into it."""
steamapps = os.path.join(library, "steamapps")
if not os.path.isdir(steamapps):
return 0
@@ -58,8 +55,6 @@ RENAMED = (("/mnt/bannerlator-sd", "/mnt/droiddeck-sd"),)
def rename(steam_root, old, new):
"""Moves a library registered under an earlier mount point to the current one, keeping its
entry (content id, app sizes) rather than registering it anew."""
path = os.path.join(steam_root, "steamapps", "libraryfolders.vdf")
if not os.path.isfile(path):
return
@@ -77,8 +72,6 @@ def rename(steam_root, old, new):
def forget(steam_root, library):
"""Removes a library folder earlier builds registered and this one no longer binds, so the
client does not keep offering a location that is not there."""
path = os.path.join(steam_root, "steamapps", "libraryfolders.vdf")
if not os.path.isfile(path):
return
@@ -107,10 +100,6 @@ def forget(steam_root, library):
def relabel(steam_root, target, label):
"""Names a library for what it is. The client writes its own entry with an empty label and
falls back to showing the mount point - "Local Drive (/)" - so the install dialog gives no
clue which of the two places is the phone and which is the card. A library registered on an
earlier run keeps whatever label it was given then, so both are named here every time."""
path = os.path.join(steam_root, "steamapps", "libraryfolders.vdf")
if not os.path.isfile(path):
return
@@ -153,6 +142,7 @@ def relabel(steam_root, target, label):
GAMES_DIR = "/root/Games/"
ADDED_DIR = "/mnt/droiddeck-lib/"
def wanted():
@@ -193,7 +183,7 @@ def main():
if managed:
keep = {library for library, _ in libraries}
for library in registered(steam_root):
if library not in keep and (library == LIBRARIES[0][0] or library.startswith(GAMES_DIR)):
if library not in keep and (library == LIBRARIES[0][0] or library.startswith((GAMES_DIR, ADDED_DIR))):
forget(steam_root, library)
@@ -1,12 +1,4 @@
#!/usr/bin/python3
"""Sets the Steam client's shader pre-caching (Settings > Downloads), before the client starts.
droiddeck-steam-shaders <0|1> <steam root>...
The client stores the toggle as InstallConfigStore/Software/Valve/Steam/ShaderCacheManager/
DisableShaderCache in config/config.vdf: "1" when off, "0" when on. It keeps the setting in memory
and writes config.vdf back on exit, so this runs only while the client is stopped. The launcher
passes a value only after its own toggle changes; otherwise the client's toggle stays the user's."""
from pathlib import Path
import runpy
import sys
@@ -16,7 +16,6 @@ TAG = "droiddeck-app"
def account_dir(steam_root):
"""The most recent account's userdata folder, else the only one that is not 0."""
users = os.path.join(steam_root, "config", "loginusers.vdf")
recent, best = None, None
try:
@@ -243,9 +242,6 @@ ART_SLOTS = (("p", "p"), ("header", ""), ("hero", "_hero"), ("logo", "_logo"))
def install_art(acct, games):
"""Copies each game's art into the client's grid folder under the names it looks for. A file
the client already has that this script did not write (art the user set in the client) is
left alone; ours are replaced when the source changed and removed when the game lost its art."""
grid = os.path.join(acct, "config", "grid")
os.makedirs(grid, exist_ok=True)
manifest_path = os.path.join(grid, ART_MANIFEST)
@@ -354,7 +350,6 @@ def main():
if x64_tool:
protect = {compat.first_key(os.path.join(tools, e, "compatibilitytool.vdf"), ["compatibilitytools", "compat_tools"]) or e: e
for e in (os.listdir(tools) if os.path.isdir(tools) else [])}
# Its own state: the arm64 client's state.json lists which of that client's titles follow its default.
own = {"default": x64_tool,
"directory": os.path.join(os.path.dirname(os.path.abspath(steam_root)), "droiddeck-compat"),
"linux_tool": "droiddeck-direct"}
@@ -1,16 +1,4 @@
#!/usr/bin/python3
"""Initialize Steam's own display settings once; subsequent choices belong to Steam.
The UI scale, and native resolution: the client treats our gamescope as an external display and,
unless "Enable Native Resolution on External Displays" is on, draws itself at 1920x1080 on any
larger output - a 2340x1080 session came up as 16:9 with bars. The session's size is already the
user's Resolution choice, so the client should use all of it.
And the screensaver over a running game. The client's defaults (steamui.so's settings descriptor)
show screensavers while a game runs, after 300 s on AC power with no button pressed - and a stick or
trigger held is no press. Red Dead Redemption 2's cutscenes run longer than that: the slideshow
covered the game, and the button that woke it reached the game as well (B asked to quit to the
desktop). Customization > Screensaver > "Show screensavers when playing a game" still turns it on."""
import math
import os
from pathlib import Path
@@ -116,8 +104,6 @@ def seed_text(text, scale):
def seed_value(text, path, value):
"""InstallConfigStore/<path> = value, unless the client already has a value there (the
user's), adding only the blocks that are missing."""
root = parse(text).get('InstallConfigStore')
if not isinstance(root, Block):
raise ValueError("missing InstallConfigStore")
@@ -170,9 +156,6 @@ def initialize(steam_root, width, height):
def seed_once(steam_root, marker_name, seed, message):
"""Applies seed to config.vdf the first time only: the marker keeps a later choice - including
a return to the client's own default, which the client may store by dropping the key - the
user's."""
config = Path(steam_root) / 'config/config.vdf'
marker = config.with_name(marker_name)
if marker.exists():
@@ -3,7 +3,6 @@ set -eu
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
# Must match the -clientbeta droiddeck-session starts this client with (steam_channel).
X64_CHANNEL=steamdeck_publicbeta
MANIFEST=steam_client_${X64_CHANNEL}_steamrt64
@@ -78,14 +77,17 @@ x64_sync_client() {
rm -rf "$work"
}
# The client rewrites config.vdf from memory as it exits: the mapping is written only while no x86 client runs.
x64_map_direct() {
local mode=write
[ "${1:-}" = --live ] && mode=live
[ -f "$STEAM_X64/config/config.vdf" ] || return 0
if [ "$mode" = write ] && pgrep -f 'steamrt64/steam( |$)' >/dev/null 2>&1; then return 0; fi
local libraries="$STEAM_X64/steamapps:/mnt/droiddeck-sd/x86-64/steamapps:$X64_HOME/shared/arm64/steamapps" library
for library in /mnt/droiddeck-lib/*/x86-64/steamapps; do
[ -d "$library" ] && libraries="$libraries:$library"
done
python3 - "$mode" "$STEAM_X64/config/config.vdf" "$STEAM_X64/appcache/appinfo.vdf" "$X64_HOME/direct-auto.json" \
"$X64_HOME/direct-sniper" "$STEAM_X64/steamapps:/mnt/droiddeck-sd/x86-64/steamapps:$X64_HOME/shared/arm64/steamapps" "$(x64_default_tool)" \
"$X64_HOME/direct-sniper" "$libraries" "$(x64_default_tool)" \
"$REAL_HOME/.bl-compat-pending" ${BL_X64_DIRECT_APPS:-550} \
<<'PY' || { [ "$mode" = live ] || step "could not map titles to DroidDeck direct"; }
# Steam does not swap an installed build when the tool changes: a title installed for Windows stays on Proton.
@@ -317,7 +319,6 @@ print("droiddeck-steam-x64: %d Linux title(s) on DroidDeck direct (%d on the new
PY
}
# 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
total=$(curl -fsSIL "$url" 2>/dev/null | tr -d '\r' | awk 'tolower($1) == "content-length:" { v = $2 } END { print v + 0 }')
@@ -336,11 +337,9 @@ x64_fetch() {
x64_prepare() {
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"
if [ ! -f "$ROOTFS/.droiddeck-complete" ]; then
# Resumes a part-done download; a finished one answers 416, which is not a failure here.
x64_fetch "$ROOTFS_URL" "$X64_HOME/rootfs.sqsh" "downloading FEX's Ubuntu 24.04 x86 rootfs" || {
rc=$?
[ "$rc" = 22 ] && [ -s "$X64_HOME/rootfs.sqsh" ] || { step "rootfs download failed (curl $rc)"; exit 1; }
@@ -356,13 +355,9 @@ if [ ! -f "$ROOTFS/.droiddeck-complete" ]; then
touch "$ROOTFS/.droiddeck-complete"
fi
echo "== x86-64 rootfs: $(sed -n 's|.*/download/\([^/]*\)/.*|\1|p' <<<"$ROOTFS_URL") (sha256 ${ROOTFS_SHA256:0:12})" >&2
# FEX falls back to the guest's own /etc/ld.so.preload (arm64 libraries) when the rootfs has none. The x86
# session shim provides System V IPC, which Android kernels lack and the client's tier0 needs to start.
: > "$ROOTFS/etc/ld.so.preload"
for lib in libblsession libfakeinput; do
have=0
# 32-bit libfakeinput crashes SDL2 games (a NULL udev attribute reaches strdup), so only the x86_64 copy
# is preloaded, by full path: with $LIB, FEX falls through to the session's own i386 copy.
arches="x86_64 i386"; [ "$lib" = libfakeinput ] && arches=x86_64
rm -f "$ROOTFS/usr/local/lib/i386-linux-gnu/libfakeinput.so"
for arch in $arches; do
@@ -439,7 +434,6 @@ if [ -f "$scout/steam-runtime.tar.xz" ] &&
fi
[ -L "$STEAM_X64/steamapps" ] && rm -f "$STEAM_X64/steamapps"
mkdir -p "$STEAM_X64/steamapps"
# FEX looks in the rootfs first: an empty dev/dri there hides the session's KGSL node, which x86 programs spin on.
mkdir -p "$ROOTFS/dev/dri"
mkdir -p "$X64_HOME/.steam"
ln -sfn "$STEAM_X64" "$X64_HOME/.steam/root"
@@ -448,9 +442,7 @@ ln -sfn "$STEAM_X64/ubuntu12_32" "$X64_HOME/.steam/bin32"
ln -sfn "$STEAM_X64/ubuntu12_64" "$X64_HOME/.steam/bin64"
ln -sfn "$STEAM_X64/linux32" "$X64_HOME/.steam/sdk32"
ln -sfn "$STEAM_X64/linux64" "$X64_HOME/.steam/sdk64"
# Valve's Steam Runtime container needs user namespaces and a session-bus launcher; steamrt-shim stands in for both.
droiddeck-steamrt-shim "$STEAM_X64/steamrt64" "$X64_HOME/steamrt-shim" || rm -rf "$X64_HOME/steamrt-shim"
# Valve's platform libraries ship without soname links (pressure-vessel makes them); ldconfig adds them here.
srt_libs=$X64_HOME/steamrt-libs
rm -rf "$srt_libs"
mkdir -p "$srt_libs"
@@ -460,13 +452,11 @@ for d in "$STEAM_X64"/steamrt64/pv-runtime/steam-runtime-steamrt/steamrt3c_platf
for f in "$d"/*.so*; do [ -e "$srt_libs/$(basename "$f")" ] || ln -s "$f" "$srt_libs/"; done
done
FEX_ROOTFS=$ROOTFS /usr/local/bin/FEX "$ROOTFS/usr/sbin/ldconfig.real" -n "$srt_libs" >>"$LOG" 2>&1 || step "ldconfig on $srt_libs failed"
# The rootfs's HarfBuzz needs a newer FreeType than some games bundle (Counter-Strike 2): use Valve's runtime one.
sniper_compat=$X64_HOME/sniper-compat
rm -rf "$sniper_compat"
mkdir -p "$sniper_compat"
hb=$(ls "$srt_libs"/libharfbuzz.so.0.* 2>/dev/null | head -n 1)
if [ -n "$hb" ]; then ln -s "$hb" "$sniper_compat/libharfbuzz.so.0"; else step "warning: no HarfBuzz in Valve's runtime for the newer-runtime titles"; fi
# LD_LIBRARY_PATH beats the system folders whatever its order: Valve's older glibc must not shadow the rootfs's.
for f in "$srt_libs"/*; do
n=$(basename "$f")
if [ -e "$ROOTFS/usr/lib/x86_64-linux-gnu/$n" ] || [ -e "$ROOTFS/lib/x86_64-linux-gnu/$n" ]; then rm -f "$f"; fi
@@ -540,7 +530,6 @@ RUN
fi
x64_share x86-64
x64_map_direct
# Each wrapper execs droiddeck-x64-arm-proton through an arm64 binary, which FEX hands straight to the CPU.
arm_tools=$ARM_STEAM/compatibilitytools.d
mkdir -p "$X64_HOME/arm64"
cp -f /usr/bin/env "$X64_HOME/arm64/env"
@@ -552,7 +541,6 @@ RUN
for src in "$arm_tools"/*/; do
src=${src%/}; name=${src##*/}
[ -f "$src/compatibilitytool.vdf" ] && [ -f "$src/toolmanifest.vdf" ] || continue
# A droiddeck-fex wrapper made the arm64 client install Valve's FEX when this client probed its tools after logon.
case $name in droiddeck-direct|droiddeck-fex) continue ;; esac
dst=$STEAM_X64/compatibilitytools.d/$name
mkdir -p "$dst"
@@ -585,7 +573,6 @@ VDF
chmod 755 "$dst/run"
done
x64_sync_login
# Each client keeps its own libraries; written only while no x86 client runs, as it rewrites these on exit.
if ! pgrep -f 'steamrt64/steam( |$)' >/dev/null 2>&1; then
listing_ok=0
if BL_X64_SHARED=$X64_HOME/shared/arm64 python3 - "$STEAM_X64" "${BL_X64_STEAM_LIBRARIES:-}" "$STEAM_X64/config/libraryfolders.vdf" "$STEAM_X64/steamapps/libraryfolders.vdf" <<'PY'; then
@@ -634,7 +621,6 @@ PY
step "could not add the card to the x86-64 client's library folders"
fi
fi
# default-tool is the default this script set: titles still on it move along; a user's choice is kept.
default=$(x64_default_dir)
if [ -f "$default/compatibilitytool.vdf" ] && [ -f "$STEAM_X64/config/config.vdf" ] &&
! pgrep -f 'steamrt64/steam( |$)' >/dev/null 2>&1; then
@@ -709,7 +695,6 @@ s = s[:steam.end()] + movie.group(0) + s[steam.end():]
open(path, "w", encoding="utf-8", errors="surrogateescape").write(s)
PY
fi
# FEX takes its rootfs from FEXServer, and one started without FEX_ROOTFS serves none: stop it while no x86 client runs.
if ! pgrep -f 'steamrt64/steam( |$)' >/dev/null 2>&1; then
FEX_ROOTFS=$ROOTFS /usr/local/bin/FEXServer -k >/dev/null 2>&1 || true
fi
@@ -724,7 +709,6 @@ x64_webhelper_gpu() {
}
x64_env() {
# droiddeck-x64-arm-proton restores this arm64 environment before Proton runs.
export -p | grep -v -E '^declare -x (PWD|OLDPWD|SHLVL|_)=' > "$X64_HOME/arm-session.env.new" || true
mv -f "$X64_HOME/arm-session.env.new" "$X64_HOME/arm-session.env"
unset LD_LIBRARY_PATH LD_PRELOAD STEAM_RUNTIME STEAM_RUNTIME_PREFER_HOST_LIBRARIES
@@ -746,7 +730,6 @@ if x64_gpu && [ "${BL_X64_CLIENT_SOFTWARE:-0}" != 1 ]; then
else
unset FEX_THUNKCONFIG $gpu_vars
export LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
# Over DRI3 the X server hands out the GPU node, and Mesa's software path loops on KMS dumb buffers on it.
export LIBGL_DRI3_DISABLE=1
fi
[ "${BL_X64_FP_OFF:-0}" = 1 ] && export PROOT_FP_OFF=1
@@ -759,12 +742,9 @@ export FEX_ROOTFS=$ROOTFS
export STEAM_EXTRA_COMPAT_TOOLS_PATHS=
export STEAM_RUNTIME=1
[ -d "$X64_HOME/steamrt-shim" ] && export STEAM_RUNTIME_STEAMRT=$X64_HOME/steamrt-shim
# The client starts commands via steam-runtime-launch-client; Valve's needs a session-bus service, the shim's runs them.
[ -d "$X64_HOME/steamrt-shim/bin" ] && export PATH=$X64_HOME/steamrt-shim/bin:$PATH
export LD_LIBRARY_PATH=$STEAM_X64/steamrt64:$STEAM_X64/steamrt64/panorama:$X64_HOME/steamrt-libs
# After an update the client re-executes itself through pressure-vessel-wrap (bwrap) unless this guard is set.
export STEAM_STEAMRT_RECURSION_GUARD=1
# proot is a tracer: tier0 takes it for a debugger and breaks into it with int3 on its first failed assertion.
export BL_WEBHELPER_HIDE_TRACER=1
}
@@ -774,7 +754,6 @@ x64_manifest_version() {
awk -F'"' '$2 == "version" { print $4; exit }' "$STEAM_X64/package/steam_client_${chan}_$1.manifest" 2>/dev/null || echo "?"
}
# What x86 GL and Vulkan look like through FEX's thunks, for a session whose menus failed on the GPU.
x64_gpu_probe() {
local fex=${BL_FEX:-/usr/local/bin/FEX}
echo "== x86-64 GPU probe (x86 glxinfo and vulkaninfo through FEX):"
@@ -786,8 +765,6 @@ x64_gpu_probe() {
) | sed 's/^/ /'
}
# Steam's menus come from the web helper; when its GPU process keeps exiting, Chromium gives up on the GPU and
# the menus never appear. Says so once in the session log, with the probe above.
x64_gpu_watch() {
local log=$STEAM_X64/logs/console-linux.txt from n codes
from=$(( $(wc -l 2>/dev/null < "$log" || echo 0) + 1 ))
@@ -801,7 +778,6 @@ x64_gpu_watch() {
x64_arm_webhelper_cpu_supported() {
local status=0
# Valve's native ARM web helper contains LSE atomics; missing CPU data cannot establish incompatibility.
awk -F: '
$1 ~ /^[[:space:]]*Features[[:space:]]*$/ {
if ($2 !~ /(^|[[:space:]])atomics([[:space:]]|$)/) unsupported = 1
@@ -814,8 +790,6 @@ x64_arm_webhelper_cpu_supported() {
x64_exec() {
x64_env
cd "$STEAM_X64"
# The client checksums its files at start and reinstalls over edited ones, so the session shim (preload/net.c)
# swaps the web helper at exec. The arm64 helper only comes up against a client of the same build.
if [ "${BL_X64_X86_WEBHELPER:-0}" != 1 ] && [ -x /usr/local/bin/droiddeck-x64-arm-webhelper ] &&
[ -x "$ARM_STEAM/steamrtarm64/steamwebhelper" ] && x64_arm_webhelper_cpu_supported; then
local chan x86_build arm_build
@@ -829,7 +803,6 @@ x64_exec() {
fi
fi
if [ -z "${BL_X64_ARM_WEBHELPER:-}" ] && x64_webhelper_gpu; then
# Not --in-process-gpu (the preload's default): a GPU crash there takes the whole helper down.
export BL_WEBHELPER_ARGS="--ignore-gpu-blocklist --use-gl=angle --use-angle=gl --ozone-platform=x11"
[ -x /usr/local/bin/droiddeck-x64-webhelper ] && export BL_X64_ARM_WEBHELPER=/usr/local/bin/droiddeck-x64-webhelper
elif [ -z "${BL_X64_ARM_WEBHELPER:-}" ]; then
@@ -860,7 +833,6 @@ x64_share() {
step "could not share the games between the clients"
}
# Steam renews its token every few days and refuses old copies: copy the newest every start, never while a client runs.
x64_sync_login() {
pgrep -f 'steamrt64/steam( |$)' >/dev/null 2>&1 && return 0
pgrep -f 'steamrtarm64/steam( |$)' >/dev/null 2>&1 && return 0
@@ -996,7 +968,6 @@ if [ -n "${BL_FEXSERVER_LOG:-}" ]; then
FEX_ROOTFS=$ROOTFS "$(dirname "${BL_FEX:-/usr/local/bin/FEX}")/FEXServer" -f -p 600 >"$BL_FEXSERVER_LOG" 2>&1 &
sleep 1
fi
# The client's connection status comes from NetworkManager on the system bus; a desktop has no system bus.
x64_bus= x64_nm= x64_pin=
x64_cleanup() {
[ -n "$x64_pin" ] && kill "$x64_pin" 2>/dev/null
@@ -1035,7 +1006,6 @@ BUSCONF
step "network: the system bus did not come up; the client will show no connection"
fi
fi
# Left by a killed client: .crash opens the update UI on its spinner; stale Singleton* locks can blank the UI.
if ! pgrep -f 'steamrt64/steam( |$)' >/dev/null 2>&1; then
for f in "$STEAM_X64/.crash" "$STEAM_X64/steam.pid" "$STEAM_X64/config/htmlcache/SingletonLock" \
"$STEAM_X64/config/htmlcache/SingletonCookie" "$STEAM_X64/config/htmlcache/SingletonSocket"; do
@@ -1053,7 +1023,6 @@ if [ -n "${BL_CLIENT_CPUS:-}" ] && command -v taskset >/dev/null 2>&1; then
x64_pin=$!
fi
for attempt in 1 2 3 4 5; do
# The branch on disk must match -clientbeta before every start, or the client loops on rc=42.
echo "$X64_CHANNEL" > "$STEAM_X64/package/beta"
step "starting the x86-64 SteamRT3 client under FEX (attempt $attempt): $*"
rc=0
@@ -1,7 +1,4 @@
#!/bin/bash
# droiddeck-steamrt-shim <client runtime dir> <shim dir>
# Builds <shim dir> from the Steam Runtime container the client carries and exits 0, or removes it and exits 1
# when the client carries none.
set -eu
client=$1
shim=$2
@@ -25,13 +22,11 @@ for e in "$srt_real"/bin/*; do
[ -e "$e" ] || continue
ln -s "$e" "$shim/bin/$(basename "$e")"
done
# The client's bwrap probe (steam-runtime-check-requirements) needs user namespaces, which no Android app has.
rm -f "$shim/bin/steam-runtime-check-requirements"
printf '#!/bin/sh
exit 0
' > "$shim/bin/steam-runtime-check-requirements"
chmod 755 "$shim/bin/steam-runtime-check-requirements"
# Valve's launcher asks a service on the session bus; proot is already the container, so the command runs here.
rm -f "$shim/bin/steam-runtime-launch-client"
cat > "$shim/bin/steam-runtime-launch-client" <<'LAUNCH'
#!/bin/sh
@@ -26,7 +26,6 @@ quest_settings() {
configure_graphics() {
case "$(cat /sys/class/kgsl/kgsl-3d0/gpu_model 2>/dev/null)" in
Adreno840*)
# The session's forced sysmem mode loses the Vulkan device in SteamVR.
export TU_DEBUG="$(
IFS=', '
set -f
@@ -41,8 +40,6 @@ configure_graphics() {
esac
}
# Any OpenXR probe (Steam runs one through Proton at every client start) starts vrserver
# while a runtime is registered, so SteamVR is registered only during a DroidDeck VR session.
unregister() {
if grep -qF "\"$steamvr\"" "$HOME/.config/openvr/openvrpaths.vrpath" 2>/dev/null; then
rm -f "$HOME/.config/openvr/openvrpaths.vrpath"
@@ -78,7 +75,6 @@ stop() {
case "${1:-status}" in
launch)
# Library/URL entry point: use the same installer and start path as the app.
exec 8>"$state/launch.lock"
flock -n 8 || exit 0
if ! installed; then
@@ -221,7 +217,6 @@ JSON
quest_settings apply || exit 1
startup_handed_off=0
trap '[ "$startup_handed_off" = 1 ] || quest_settings restore' EXIT
# The pinned Frame package's CVP constructor exits on Quest's unsupported SoC.
cvp=$steamvr/drivers/cv/bin/linuxarm64/libArcturusPerception.so
if [ -f "$cvp" ]; then
disabled=$cvp.droiddeck-disabled
@@ -1,10 +1,6 @@
#!/bin/sh
# Exit 0 when this game run should open as a SteamVR panel: SteamVR is running and Steam
# lists no VR support for the app, optional or required. Under SteamVR, Steam stacks a flat game's window behind
# its own, so without the panel the game plays unseen.
[ "${1:-}" = waitforexitandrun ] || exit 1
[ -z "${DROIDDECK_STEAMVR_PANEL:-}" ] || exit 1
# Non-Steam shortcuts run with SteamAppId=0 and their CGameID in SteamGameId.
app=${SteamAppId:-}
[ "$app" = 0 ] && app=${SteamGameId:-}
case $app in '' | 0 | *[!0-9]*) exit 1 ;; esac
@@ -6,13 +6,11 @@ pgrep -x vrserver >/dev/null 2>&1 || {
echo 'Start SteamVR before launching a game with droiddeck-steamvr-game.' >&2
exit 1
}
# droiddeck-steamvr-flat skips a run that a launch option already wrapped.
export DROIDDECK_STEAMVR_PANEL=1
vrdir=${DROIDDECK_VR_DIR:-/usr/local/lib/droiddeck-vr}
export VK_LAYER_PATH="$vrdir/layer${VK_LAYER_PATH:+:$VK_LAYER_PATH}"
export VK_INSTANCE_LAYERS="VK_LAYER_DROIDDECK_vr${VK_INSTANCE_LAYERS:+:$VK_INSTANCE_LAYERS}"
export VK_LOADER_LAYERS_DISABLE="${VK_LOADER_LAYERS_DISABLE:-~implicit~}"
# Quest's guest GPU images use Vulkan sharing rather than DMA-BUF modifiers.
if [ -S "/run/droiddeck/droiddeck-xr-frames" ]; then
export gamescope_vr_use_modifiers=${gamescope_vr_use_modifiers:-false}
fi
Loaded 100 of 819 files, more files were not shown because too many files have changed in this diff. Show more