Compare commits
63
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e30805490 | ||
|
|
7312f0ddba | ||
|
|
e7ebaf591c | ||
|
|
010949fead | ||
|
|
f5931650e0 | ||
|
|
519d004cab | ||
|
|
46201fd9c3 | ||
|
|
f320f4b465 | ||
|
|
89eb031cd6 | ||
|
|
2991001fe4 | ||
|
|
19df33e0f7 | ||
|
|
c920204184 | ||
|
|
6f4613e146 | ||
|
|
96f75f4e52 | ||
|
|
3b08da11ff | ||
|
|
3ee88bb8cf | ||
|
|
4c5b97cfe4 | ||
|
|
773eea24d9 | ||
|
|
3b5c95959b | ||
|
|
a2bc9a2bdc | ||
|
|
4beee17953 | ||
|
|
4ad0055416 | ||
|
|
db9cd40079 | ||
|
|
cb07a8f983 | ||
|
|
c63e8cee39 | ||
|
|
b670b5d844 | ||
|
|
11abff5343 | ||
|
|
064ea3de7d | ||
|
|
ec278c0478 | ||
|
|
5d91176500 | ||
|
|
cf7baf3ba8 | ||
|
|
551d0c3294 | ||
|
|
7f77fa68af | ||
|
|
ece8b16a78 | ||
|
|
2b91339cb8 | ||
|
|
ffa4577793 | ||
|
|
4a32c8fb36 | ||
|
|
9bb8d84f12 | ||
|
|
f42aca690f | ||
|
|
34a02fdac5 | ||
|
|
8670b412c7 | ||
|
|
539ac2f2a5 | ||
|
|
f5a75d9edc | ||
|
|
430499bdab | ||
|
|
92578803c2 | ||
|
|
ca2ff7093a | ||
|
|
a2dc011200 | ||
|
|
48eeae7527 | ||
|
|
0df4ca957f | ||
|
|
13aa11355e | ||
|
|
e989d7457f | ||
|
|
b05bb1dd48 | ||
|
|
2898f6b049 | ||
|
|
4eb4e3465b | ||
|
|
44cd5bfd81 | ||
|
|
8977228a4b | ||
|
|
fc3b2d0328 | ||
|
|
1c1fd7d9bc | ||
|
|
1c60e641b3 | ||
|
|
eda4b7ebd2 | ||
|
|
730ac43169 | ||
|
|
c9a76287d8 | ||
|
|
cbd3d02817 |
@@ -171,6 +171,13 @@ jobs:
|
||||
- name: Rust Android targets (no-op unless the toolchain pin outran the image)
|
||||
run: rustup target add aarch64-linux-android armv7-linux-androideabi x86_64-linux-android
|
||||
|
||||
# Must precede every cargo step below: skia-bindings' ~19 MB prebuilt download runs inside
|
||||
# a build script with no retry, and a truncated transfer here does not surface as a network
|
||||
# error — it silently becomes a from-source Skia build that dies in the container. See the
|
||||
# script for the measured failure.
|
||||
- name: curl with retries (skia-bindings' prebuilt fetch has none)
|
||||
run: sh scripts/ci/install-retrying-curl.sh
|
||||
|
||||
# Same key namespace as ci.yml/deb.yml ON PURPOSE: identical Cargo.lock, identical
|
||||
# CARGO_HOME layout (/usr/local/cargo), so the registry/git downloads dedupe with
|
||||
# the rest of the fleet in the central cache. target/ is deliberately NOT cached
|
||||
@@ -209,9 +216,25 @@ jobs:
|
||||
# The task lints arm64-v8a AND armeabi-v7a, and reuses the build task's exact cargo-ndk
|
||||
# environment — see the long note on `registerCargoNdkClippy` in kit/build.gradle.kts for why
|
||||
# both pointer widths are load-bearing and why the environment must not be duplicated here.
|
||||
# The `STARTING A FULL BUILD` check turns the manual rule in this workflow's `env:` block
|
||||
# ("Every ABI's log must show DOWNLOAD AND INSTALL SUCCEEDED") into something that fails the
|
||||
# job by itself. Without it a missed prebuilt reads as a Gradle stack trace with the real
|
||||
# cause ~1,800 lines up — which is exactly how 2026-08-22 spent a week looking like a lint
|
||||
# failure. This is the first cargo step in the job, so it catches the drop earliest.
|
||||
#
|
||||
# No pipefail: the runner is dash. Capture, then decide.
|
||||
- name: Clippy (Android target, deny warnings)
|
||||
working-directory: clients/android
|
||||
run: ./gradlew :kit:cargoNdkClippy --stacktrace
|
||||
run: |
|
||||
set -e
|
||||
rc=0
|
||||
./gradlew :kit:cargoNdkClippy --stacktrace > /tmp/android-clippy.log 2>&1 || rc=$?
|
||||
cat /tmp/android-clippy.log
|
||||
if grep -q "STARTING A FULL BUILD" /tmp/android-clippy.log; then
|
||||
echo "::error::skia-bindings did not get its prebuilt archive and started building Skia from source — the download was dropped (see DOWNLOAD AND INSTALL FAILED above). This is a fetch failure, not a lint failure."
|
||||
exit 1
|
||||
fi
|
||||
exit $rc
|
||||
|
||||
# The kit's JVM unit tests — the pure parsers, migrations and feedback policies. They were
|
||||
# running nowhere: this workflow only assembled, and android-screenshots.yml runs the :app
|
||||
|
||||
@@ -107,6 +107,12 @@ jobs:
|
||||
# registry/git are download caches, target/ the incremental build. The target key
|
||||
# carries the rustc version — resolved via `rustc --version` (below) rather than parsed
|
||||
# from rust-toolchain.toml, so a pin bump there invalidates stale incremental state too.
|
||||
# `pf-console-ui` pulls skia-safe, so a target-cache miss makes this job download a prebuilt
|
||||
# Skia from the same no-retry build-script fetch that took the android job out on
|
||||
# 2026-08-22, over the same load-shedding runner network. Cheap insurance; see the script.
|
||||
- name: curl with retries (skia-bindings' prebuilt fetch has none)
|
||||
run: sh scripts/ci/install-retrying-curl.sh
|
||||
|
||||
- name: Cache keys
|
||||
run: echo "rustc=$(rustc --version | cut -d' ' -f2)" >> "$GITHUB_ENV"
|
||||
- uses: actions/cache@v4
|
||||
@@ -270,6 +276,12 @@ jobs:
|
||||
- name: sccache (no-op once the image bakes it)
|
||||
run: sh scripts/ci/ensure-sccache.sh
|
||||
|
||||
# `pf-console-ui` pulls skia-safe, so a target-cache miss makes this job download a prebuilt
|
||||
# Skia from the same no-retry build-script fetch that took the android job out on
|
||||
# 2026-08-22, over the same load-shedding runner network. Cheap insurance; see the script.
|
||||
- name: curl with retries (skia-bindings' prebuilt fetch has none)
|
||||
run: sh scripts/ci/install-retrying-curl.sh
|
||||
|
||||
- name: Cache keys
|
||||
run: echo "rustc=$(rustc --version | cut -d' ' -f2)" >> "$GITHUB_ENV"
|
||||
- uses: actions/cache@v4
|
||||
|
||||
@@ -50,7 +50,10 @@ on:
|
||||
- 'crates/pf-vaadec/**'
|
||||
- 'packaging/flatpak/**'
|
||||
- 'Cargo.lock'
|
||||
# Both halves of this job's correctness, not of the bundle's content: a change to either
|
||||
# can only be proven by a real run, and there is no other trigger that would give it one.
|
||||
- '.gitea/workflows/flatpak.yml'
|
||||
- 'scripts/ci/flatpak-deps-present.sh'
|
||||
tags: ['v*']
|
||||
workflow_dispatch:
|
||||
|
||||
@@ -270,12 +273,13 @@ jobs:
|
||||
|
||||
- name: Prefetch deps + sources (retried — the network phase, split off the build)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# All of the job's heavy network I/O happens HERE, retried, so a dropped DNS lookup
|
||||
# or TCP dial costs a backoff-retry instead of the whole (long) compile:
|
||||
# 1) --install-deps-only pulls everything the manifest declares from Flathub: the
|
||||
# GNOME 50 runtime/SDK + the rust-stable (//25.08, rustc 1.96) and llvm20 SDK
|
||||
# extensions. (No codec extension: the client links no FFmpeg — see the
|
||||
# manifest header.)
|
||||
# 1) the Flathub deps the manifest declares — the GNOME 50 runtime/SDK + the
|
||||
# rust-stable (//25.08, rustc 1.96) and llvm20 SDK extensions — but ONLY the ones
|
||||
# genuinely MISSING; see the block below. (No codec extension: the client links no
|
||||
# FFmpeg — see the manifest header.)
|
||||
# 2) --download-only fetches every source (all crates in cargo-sources.json) into
|
||||
# the .flatpak-builder state dir. Both are resumable/idempotent, so re-running
|
||||
# after a partial failure is safe and cheap.
|
||||
@@ -288,9 +292,40 @@ jobs:
|
||||
# for the mechanism.
|
||||
# 10 attempts (~9min budget), matching the remote-add bootstrap above — same shared,
|
||||
# load-sensitive runner, same flathub.org resolution path.
|
||||
bash scripts/ci/retry.sh 10 flatpak-builder --user --force-clean --disable-rofiles-fuse \
|
||||
--install-deps-from=flathub --install-deps-only \
|
||||
"$PWD/build-dir" "$MANIFEST"
|
||||
#
|
||||
# WHY THIS IS NOT AN UNCONDITIONAL `--install-deps-only` ANY MORE (2026-08-22):
|
||||
# that flag does not install what is missing, it UPDATES what is present.
|
||||
# builder_manifest_install_dep() branches on `flatpak info --show-commit <ref>` succeeding
|
||||
# and runs `flatpak update` for every dep already installed — with no fallback to a
|
||||
# plain install when that update fails — and ci/flatpak-ci.Dockerfile bakes
|
||||
# the entire runtime set, so on a healthy run it was a pure no-op that nonetheless made
|
||||
# every build depend on Flathub being healthy at that minute. It bit on 2026-08-22:
|
||||
# Updating runtime/org.freedesktop.Sdk.Extension.rust-stable/x86_64/25.08
|
||||
# Error: Failed to update org.freedesktop.Sdk.Extension.rust-stable: While pulling …
|
||||
# .filez: Server returned HTTP 404
|
||||
# dl.flathub.org served a 404 for one object of the then-current rust-stable//25.08
|
||||
# commit, deterministically — all 10 retry.sh attempts died on the SAME object over
|
||||
# ~9 min — and flatpak-builder SEGFAULTED on its own error path (rc=139), so retry.sh
|
||||
# saw a crash rather than a clean "this will never work" either. The build never wanted
|
||||
# that newer commit: the manifest pins a runtime VERSION, not a commit, and the baked
|
||||
# one satisfies it. Updating bought nothing and imported an upstream outage.
|
||||
#
|
||||
# So: assert what the image already has, and reach for Flathub only on a real miss —
|
||||
# the same "guard, don't install on top of a stale image" doctrine as the Tooling step.
|
||||
# The check lives in scripts/ci/flatpak-deps-present.sh (run its --self-test after
|
||||
# touching it): a bug in it that reports "satisfied" when it is not would build against
|
||||
# whatever runtime happened to be lying around, which is worth more than an inline
|
||||
# if-statement. It deliberately fails OPEN — anything it cannot parse takes the slow
|
||||
# install path below.
|
||||
if bash scripts/ci/flatpak-deps-present.sh "$MANIFEST"; then
|
||||
echo "deps satisfied by the baked image — not touching Flathub"
|
||||
flatpak list --user --columns=ref
|
||||
else
|
||||
echo "::warning::$MANIFEST declares deps punktfunk-flatpak-ci does not have — pulling from Flathub (~1.5 GB). Bump GNOME_VERSION/FREEDESKTOP_VERSION in ci/flatpak-ci.Dockerfile so this stays off the hot path."
|
||||
bash scripts/ci/retry.sh 10 flatpak-builder --user --force-clean --disable-rofiles-fuse \
|
||||
--install-deps-from=flathub --install-deps-only \
|
||||
"$PWD/build-dir" "$MANIFEST"
|
||||
fi
|
||||
bash scripts/ci/retry.sh 10 flatpak-builder --user --force-clean --disable-rofiles-fuse \
|
||||
--download-only --disable-updates \
|
||||
"$PWD/build-dir" "$MANIFEST"
|
||||
@@ -298,7 +333,17 @@ jobs:
|
||||
- name: Build the flatpak (offline — deps + sources prefetched above)
|
||||
run: |
|
||||
# Everything is already local (state dir warmed by the prefetch step), so this long
|
||||
# step needs no network; --install-deps-from stays as a no-op safety net.
|
||||
# step needs no network.
|
||||
#
|
||||
# --install-deps-from=flathub USED to sit here, commented as "a no-op safety net". It
|
||||
# was neither. builder-main.c calls builder_manifest_install_deps() whenever that flag
|
||||
# is set — --install-deps-only only decides whether it EXITS afterwards — so this step
|
||||
# re-ran the same `flatpak update` of the runtimes that killed the prefetch step on
|
||||
# 2026-08-22 (Flathub HTTP 404 on a rust-stable//25.08 object; see there). A live pull
|
||||
# of multi-GB runtimes is a strange thing to call a safety net in the step whose whole
|
||||
# design is to be offline, and it could only ever fire if the prefetch step above had
|
||||
# already failed the job. Dropped: the prefetch step is the one place that talks to
|
||||
# Flathub, and it is the one place with retries.
|
||||
#
|
||||
# --disable-updates is LOAD-BEARING, not tidiness: without it this step was never
|
||||
# actually offline. flatpak-builder runs the DOWNLOAD PHASE again as part of every
|
||||
@@ -326,7 +371,6 @@ jobs:
|
||||
flatpak-builder --user --force-clean --disable-rofiles-fuse \
|
||||
--default-branch="$FLATPAK_BRANCH" \
|
||||
--disable-updates \
|
||||
--install-deps-from=flathub \
|
||||
--repo="$PWD/repo" \
|
||||
"$PWD/build-dir" "$MANIFEST"
|
||||
|
||||
|
||||
+1013
File diff suppressed because it is too large
Load Diff
Generated
+38
-38
@@ -1090,7 +1090,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cursor-probe"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"pf-capture",
|
||||
@@ -1222,7 +1222,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "display-disturb"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"pf-win-display",
|
||||
"windows 0.62.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
@@ -1959,9 +1959,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "h2"
|
||||
version = "0.4.15"
|
||||
version = "0.4.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155"
|
||||
checksum = "839c0e8a181239723652be9062bb56ca5bf5f64011f73b623f6f4fc59086a228"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"bytes",
|
||||
@@ -2343,7 +2343,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "latency-probe"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
@@ -2446,7 +2446,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "libvpl-sys"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"bindgen",
|
||||
"cmake",
|
||||
@@ -2475,7 +2475,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
||||
|
||||
[[package]]
|
||||
name = "loss-harness"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"punktfunk-core",
|
||||
]
|
||||
@@ -2967,7 +2967,7 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
|
||||
|
||||
[[package]]
|
||||
name = "pf-bitstream"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"cros-codecs",
|
||||
"tracing",
|
||||
@@ -2975,7 +2975,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-capture"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ashpd",
|
||||
@@ -2996,7 +2996,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-client-core"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ash",
|
||||
@@ -3032,7 +3032,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-clipboard"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ashpd",
|
||||
@@ -3050,7 +3050,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-console-ui"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ash",
|
||||
@@ -3073,7 +3073,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-dxvadec"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"cros-codecs",
|
||||
"pf-bitstream",
|
||||
@@ -3083,7 +3083,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-encode"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ash",
|
||||
@@ -3109,7 +3109,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-frame"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"libc",
|
||||
@@ -3122,7 +3122,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-gpu"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"pf-host-config",
|
||||
@@ -3136,11 +3136,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-host-config"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
|
||||
[[package]]
|
||||
name = "pf-inject"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ashpd",
|
||||
@@ -3169,14 +3169,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-paths"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pf-presenter"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ash",
|
||||
@@ -3191,7 +3191,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-update"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -3199,7 +3199,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-update-check"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"aws-lc-rs",
|
||||
@@ -3211,7 +3211,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-vaadec"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"cros-codecs",
|
||||
"pf-bitstream",
|
||||
@@ -3220,7 +3220,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-vdisplay"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ashpd",
|
||||
@@ -3253,7 +3253,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-vkdecode"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"ash",
|
||||
"cros-codecs",
|
||||
@@ -3264,7 +3264,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-win-display"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"pf-paths",
|
||||
"punktfunk-core",
|
||||
@@ -3275,7 +3275,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-zerocopy"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ash",
|
||||
@@ -3487,7 +3487,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-cli"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"pf-client-core",
|
||||
"punktfunk-core",
|
||||
@@ -3497,7 +3497,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-client-android"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"android_logger",
|
||||
"anyhow",
|
||||
@@ -3521,7 +3521,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-client-linux"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-channel",
|
||||
@@ -3538,7 +3538,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-client-session"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"log",
|
||||
"pf-client-core",
|
||||
@@ -3554,7 +3554,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-client-windows"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"mdns-sd",
|
||||
@@ -3572,7 +3572,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-core"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"cbindgen",
|
||||
@@ -3605,7 +3605,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-encode-worker"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"pf-encode",
|
||||
"tracing",
|
||||
@@ -3614,7 +3614,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-host"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"aes-gcm",
|
||||
@@ -3684,7 +3684,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-probe"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"mdns-sd",
|
||||
@@ -3698,7 +3698,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-tray"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ksni",
|
||||
@@ -3722,7 +3722,7 @@ checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
||||
|
||||
[[package]]
|
||||
name = "pyrowave-sys"
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
dependencies = [
|
||||
"bindgen",
|
||||
"cmake",
|
||||
|
||||
+1
-1
@@ -65,7 +65,7 @@ exclude = [
|
||||
ndk = { path = "clients/android/native/vendor/ndk" }
|
||||
|
||||
[workspace.package]
|
||||
version = "0.31.0"
|
||||
version = "0.31.3"
|
||||
edition = "2024"
|
||||
rust-version = "1.85"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
+97
-4
@@ -10,7 +10,7 @@
|
||||
"name": "MIT OR Apache-2.0",
|
||||
"identifier": "MIT OR Apache-2.0"
|
||||
},
|
||||
"version": "0.31.0"
|
||||
"version": "0.31.3"
|
||||
},
|
||||
"paths": {
|
||||
"/api/v1/client-logs": {
|
||||
@@ -364,6 +364,77 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"patch": {
|
||||
"tags": [
|
||||
"clients"
|
||||
],
|
||||
"summary": "Rename a paired client",
|
||||
"description": "Sets or clears the operator-visible display name for one paired Moonlight client. This is\npurely cosmetic — it touches no certificate and no trust decision — but it is the only way to\ntell paired devices apart: every moonlight-common-c client self-signs with the identical\nsubject `CN=NVIDIA GameStream Client`, so an unnamed list is a row of clones distinguishable\nonly by fingerprint. The name is stored beside the pairing store and survives host restarts;\nunpairing the device forgets it.",
|
||||
"operationId": "renameClient",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "fingerprint",
|
||||
"in": "path",
|
||||
"description": "Hex SHA-256 fingerprint of the client certificate DER (64 chars, case-insensitive)",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/RenameClient"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "The client as it now reads",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PairedClient"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Malformed fingerprint",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ApiError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Missing or invalid bearer token",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ApiError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "No paired client with that fingerprint",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ApiError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/compositors": {
|
||||
@@ -6688,7 +6759,7 @@
|
||||
},
|
||||
"HostInfo": {
|
||||
"type": "object",
|
||||
"description": "Host identity and advertised capabilities (static for the life of the process).",
|
||||
"description": "Host identity and advertised capabilities (static for the life of the process, except\n`local_ip`).",
|
||||
"required": [
|
||||
"hostname",
|
||||
"uniqueid",
|
||||
@@ -6734,7 +6805,7 @@
|
||||
},
|
||||
"local_ip": {
|
||||
"type": "string",
|
||||
"description": "Best-effort primary LAN IP."
|
||||
"description": "Best-effort primary LAN IP, read fresh on every request — a host that started before its\nnetwork did (cold boot) reports `127.0.0.1` only until it actually has an address, and a\nhost that moves networks reports the new one. Poll it rather than caching it."
|
||||
},
|
||||
"os": {
|
||||
"type": "string",
|
||||
@@ -7375,6 +7446,14 @@
|
||||
"description": "Lowercase hex SHA-256 of the client certificate DER — the client's stable id here.",
|
||||
"example": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
|
||||
},
|
||||
"label": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
],
|
||||
"description": "Operator-assigned display name for this device, if one has been set (`PATCH /clients/{fp}`).\n\nThis is the ONLY thing that can tell two paired Moonlight devices apart in a list, because\ntheir certificates cannot: see [`Self::subject`]. Absent until somebody names the device.",
|
||||
"example": "Living Room TV"
|
||||
},
|
||||
"not_after_unix": {
|
||||
"type": [
|
||||
"integer",
|
||||
@@ -7396,7 +7475,7 @@
|
||||
"string",
|
||||
"null"
|
||||
],
|
||||
"description": "Certificate subject (e.g. `CN=NVIDIA GameStream Client`), if the DER parses."
|
||||
"description": "Certificate subject (e.g. `CN=NVIDIA GameStream Client`), if the DER parses.\n\nDo not display this as a device name. Every moonlight-common-c client self-signs with that\nsame fixed subject, so it identifies the *protocol*, not the device — a list of paired\nphones, TVs and handhelds all read identically. [`Self::label`] is the field to show."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -7949,6 +8028,20 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"RenameClient": {
|
||||
"type": "object",
|
||||
"description": "Body of `PATCH /clients/{fingerprint}` — the device's display name.",
|
||||
"properties": {
|
||||
"label": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
],
|
||||
"description": "The name to show for this device. `null` (or an empty/whitespace-only string) clears it and\nthe device goes back to being listed by fingerprint alone.\n\nScrubbed before storage by the same sanitizer the native plane runs on device names:\ncontrol characters and Unicode bidi overrides are stripped (they could make one paired\ndevice impersonate another in this very list), whitespace collapsed, and the result capped\nat 64 characters.",
|
||||
"example": "Living Room TV"
|
||||
}
|
||||
}
|
||||
},
|
||||
"RunningTitle": {
|
||||
"type": "object",
|
||||
"description": "One running title in a provider's liveness report.",
|
||||
|
||||
@@ -932,6 +932,10 @@ private val TEST_BUTTONS = listOf(
|
||||
"Select" to KeyEvent.KEYCODE_BUTTON_SELECT,
|
||||
"Start" to KeyEvent.KEYCODE_BUTTON_START,
|
||||
"Guide" to KeyEvent.KEYCODE_BUTTON_MODE,
|
||||
// The two buttons Android has no keycode for, on the keycodes [Gamepad.buttonBit] borrows for
|
||||
// them. Only a driverless Sony pad reaches these; every other controller leaves them dark.
|
||||
"Touch" to KeyEvent.KEYCODE_BUTTON_15,
|
||||
"Mute" to KeyEvent.KEYCODE_BUTTON_16,
|
||||
"↑" to KeyEvent.KEYCODE_DPAD_UP,
|
||||
"↓" to KeyEvent.KEYCODE_DPAD_DOWN,
|
||||
"←" to KeyEvent.KEYCODE_DPAD_LEFT,
|
||||
|
||||
@@ -515,8 +515,21 @@ class MainActivity : ComponentActivity() {
|
||||
else -> KeyEvent.KEYCODE_DPAD_RIGHT
|
||||
}
|
||||
|
||||
/** Resolve the panel's highest-refresh mode (same resolution) once, for [setConsoleHighRefreshRate]. */
|
||||
/**
|
||||
* Resolve the panel's highest-refresh mode (same resolution) once, for [setConsoleHighRefreshRate].
|
||||
*
|
||||
* NEVER on a TV, which leaves the id at `0` and makes every [setConsoleHighRefreshRate] call a
|
||||
* no-op. The pin exists for phone refresh governors that cap third-party apps at 60 Hz; a TV has
|
||||
* no such governor, and there it does active harm. `display.mode` is what [nativeDisplayMode]
|
||||
* reads to resolve "Native" refresh at connect, so a menu-time pin makes the session negotiate
|
||||
* the PINNED rate rather than the TV's real HDMI output — and [StreamScreen] then releases the
|
||||
* pin on TV (the decoder's own mode switch governs there), dropping the panel back to 60 while
|
||||
* the host is already serving 120. Every frame then waits out that mismatch, which is the
|
||||
* "latency explodes unless I set the refresh by hand" field report: picking a refresh explicitly
|
||||
* is precisely what bypasses the corrupted `nativeDisplayMode` answer.
|
||||
*/
|
||||
private fun resolveHighRefreshMode() {
|
||||
if (isTvDevice(this)) return
|
||||
@Suppress("DEPRECATION")
|
||||
val disp = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) display else windowManager.defaultDisplay
|
||||
highRefreshModeId = disp?.supportedModes?.maxWithOrNull(
|
||||
@@ -615,7 +628,7 @@ class MainActivity : ComponentActivity() {
|
||||
// keyboard arrows and belong to the VK path below — and BACK, which is how a pad with
|
||||
// no BUTTON_SELECT scancode delivers its Select: see [Gamepad.padButtonBit], which is
|
||||
// why this asks it rather than `buttonBit`).
|
||||
if (event.isFromSource(InputDevice.SOURCE_GAMEPAD)) {
|
||||
if (fromPad(event)) {
|
||||
val bit = Gamepad.padButtonBit(Gamepad.padKeyCode(event), event.flags)
|
||||
if (bit != 0) {
|
||||
// The router forwards the bit on this device's own wire pad index and tracks held
|
||||
@@ -697,7 +710,7 @@ class MainActivity : ComponentActivity() {
|
||||
// D-pad is not from SOURCE_GAMEPAD; a pad's face buttons / D-pad are) — and, for a real
|
||||
// pad, WHICH pad family, so the glyphs wear its lettering/shapes.
|
||||
if (event.action == KeyEvent.ACTION_DOWN && isConsoleNavKey(event.keyCode)) {
|
||||
lastPadIsGamepad = event.isFromSource(InputDevice.SOURCE_GAMEPAD)
|
||||
lastPadIsGamepad = fromPad(event)
|
||||
if (lastPadIsGamepad) {
|
||||
lastPadStyle = Gamepad.styleFor(event.device)
|
||||
lastPadDeviceId = event.deviceId
|
||||
@@ -705,7 +718,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
// The Controllers debug screen sees pad events before the navigation remap below.
|
||||
padKeyProbe?.let { if (it(event)) return true }
|
||||
if (event.isFromSource(InputDevice.SOURCE_GAMEPAD)) {
|
||||
if (fromPad(event)) {
|
||||
// Not streaming: a game controller drives the Compose UI (TV + phone). Map the face
|
||||
// buttons to the navigation the focus system / back stack understand; D-pad *keys*
|
||||
// already move focus on their own, so they fall through to super untouched. Read
|
||||
@@ -728,6 +741,32 @@ class MainActivity : ComponentActivity() {
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
|
||||
/**
|
||||
* Did this key event come from a controller — the question every pad branch here actually
|
||||
* means when it asks `isFromSource(SOURCE_GAMEPAD)`.
|
||||
*
|
||||
* The event's source class is the platform's per-EVENT guess, and some boxes get it wrong:
|
||||
* Fire OS is reported to deliver a Bluetooth DualSense's Triangle, touchpad and Mode/PS with
|
||||
* standard `KEYCODE_BUTTON_*` keycodes but a SOURCE_KEYBOARD tag, and the plain gate then
|
||||
* drops them before anything can map them. The DEVICE's source classes are the fact, so widen
|
||||
* to the device — but only for keycodes that cannot be anything BUT a gamepad button.
|
||||
*
|
||||
* That restriction is the whole safety of this. [KeyEvent.isGamepadButton] is exactly the
|
||||
* `KEYCODE_BUTTON_*` block — no `KEYCODE_DPAD_*`, no `KEYCODE_BACK` — and both exclusions are
|
||||
* load-bearing: a keyboard's arrow keys share the D-pad keycodes and belong to the VK path
|
||||
* ([Gamepad.buttonBit]), and a remote's or keyboard's BACK shares `KEYCODE_BACK` and has to
|
||||
* keep leaving the stream, which for a device with no pad on it is the documented way out
|
||||
* ([Gamepad.padButtonBit]). Widening on the device alone — or on its vendor id, which for
|
||||
* `0x045E`/`0x054C` covers those vendors' keyboards and mice too — routes both into the pad
|
||||
* branch and breaks them.
|
||||
*
|
||||
* The RAW keycode is what is asked: routing happens before [Gamepad.padKeyCode]'s correction,
|
||||
* and both the raw and the corrected keycode are in this block for every button concerned.
|
||||
*/
|
||||
private fun fromPad(event: KeyEvent): Boolean =
|
||||
event.isFromSource(InputDevice.SOURCE_GAMEPAD) ||
|
||||
(KeyEvent.isGamepadButton(event.keyCode) && Gamepad.isPad(event.device))
|
||||
|
||||
/**
|
||||
* `true` (back) / `false` (forward) when this key event is a MOUSE side button, null when it is
|
||||
* anything else — including a remote's or keyboard's BACK, which must keep exiting the stream.
|
||||
|
||||
@@ -114,6 +114,22 @@ data class Settings(
|
||||
* A TV (leanback) is always in this mode regardless (its remote/pad is the only input).
|
||||
*/
|
||||
val gamepadUiEnabled: Boolean = true,
|
||||
/**
|
||||
* Draw the console UI at 1080p and let the display scale it up, instead of at the panel's own
|
||||
* resolution. Off by default — this is a deliberate sharpness-for-smoothness trade, not
|
||||
* something to impose on a device that does not need it.
|
||||
*
|
||||
* It exists for 4K TVs and projectors. Their graphics chips are chosen to decode and composite
|
||||
* video, not to shade a UI, and are far slower than a phone's; at 4K every pass the console
|
||||
* draws — the mesh backdrop above all — costs four times what it does at 1080p on hardware
|
||||
* that is nowhere near four times faster. A "premium" 4K box is MORE likely to want this than
|
||||
* a cheap 1080p stick, which never had the extra pixels to begin with.
|
||||
*
|
||||
* Read by [io.unom.punktfunk.console.SkiaConsoleShell], which applies it with
|
||||
* `SurfaceHolder.setFixedSize` — the compositor then scales the smaller buffer up for free.
|
||||
* The stream is untouched; that has its own `renderScale`.
|
||||
*/
|
||||
val reduceUiResolution: Boolean = false,
|
||||
/**
|
||||
* When [gamepadUiEnabled] actually takes over — the cross-client `gamepad_ui_mode` pair,
|
||||
* mirroring the Apple client's `gamepadUIMode`: `"connected"` (default, and what the switch
|
||||
@@ -329,6 +345,7 @@ class SettingsStore(context: Context) {
|
||||
// Migration: the pre-enum Boolean "trackpad_mode" (true = trackpad, false = direct).
|
||||
?: if (prefs.getBoolean(K_TRACKPAD, true)) TouchMode.TRACKPAD else TouchMode.POINTER,
|
||||
gamepadUiEnabled = prefs.getBoolean(K_GAMEPAD_UI, true),
|
||||
reduceUiResolution = prefs.getBoolean(K_REDUCE_UI_RES, false),
|
||||
gamepadUiMode = prefs.getString(K_GAMEPAD_UI_MODE, GAMEPAD_UI_WHEN_CONNECTED)
|
||||
?: GAMEPAD_UI_WHEN_CONNECTED,
|
||||
libraryEnabled = prefs.getBoolean(K_LIBRARY, true),
|
||||
@@ -373,6 +390,7 @@ class SettingsStore(context: Context) {
|
||||
.putString(K_STATS_VERBOSITY, s.statsVerbosity.name)
|
||||
.putString(K_TOUCH_MODE, s.touchMode.name)
|
||||
.putBoolean(K_GAMEPAD_UI, s.gamepadUiEnabled)
|
||||
.putBoolean(K_REDUCE_UI_RES, s.reduceUiResolution)
|
||||
.putString(K_GAMEPAD_UI_MODE, s.gamepadUiMode)
|
||||
.putBoolean(K_LIBRARY, s.libraryEnabled)
|
||||
.putString(K_UI_PALETTE, s.uiPalette)
|
||||
@@ -415,6 +433,7 @@ class SettingsStore(context: Context) {
|
||||
const val K_HUD = "stats_hud_enabled"
|
||||
const val K_TOUCH_MODE = "touch_mode"
|
||||
const val K_GAMEPAD_UI = "gamepad_ui_enabled"
|
||||
const val K_REDUCE_UI_RES = "reduce_ui_resolution"
|
||||
const val K_GAMEPAD_UI_MODE = "gamepad_ui_mode"
|
||||
const val K_LIBRARY = "library_enabled"
|
||||
const val K_UI_PALETTE = "ui_palette"
|
||||
@@ -478,7 +497,12 @@ fun nativeDisplayMode(context: Context): Triple<Int, Int, Int> {
|
||||
val mode = display.mode
|
||||
val w = mode.physicalWidth
|
||||
val h = mode.physicalHeight
|
||||
val hz = mode.refreshRate.toInt().coerceAtLeast(1)
|
||||
// ROUNDED, not truncated: TVs report the fractional NTSC rates over HDMI (59.94, 29.97,
|
||||
// 23.976), and `toInt()` turns 59.94 into 59 — a rate no display mode anywhere has, which the
|
||||
// host then serves by clamping DOWN to the highest mode it advertises at or below it. Rounding
|
||||
// also keeps this agreeing with `MainActivity.streamPanelFps`, which already rounds; the two
|
||||
// describe the same panel and must not disagree.
|
||||
val hz = kotlin.math.round(mode.refreshRate).toInt().coerceAtLeast(1)
|
||||
return Triple(maxOf(w, h), minOf(w, h), hz)
|
||||
}
|
||||
|
||||
|
||||
@@ -317,16 +317,21 @@ internal object ConsoleJson {
|
||||
j.put("invert_scroll", s.invertScroll)
|
||||
j.put("pad_haptics", s.padHaptics)
|
||||
j.put("pad_speaker", if (s.padSpeaker) "pad" else "off")
|
||||
// Android-only rows ride `extra` (WP5 gives them RowIds); nothing on the desktop reads them.
|
||||
val extra = j.optJSONObject("extra") ?: JSONObject()
|
||||
extra.put("android.low_latency", s.lowLatencyMode)
|
||||
extra.put("android.rumble_on_phone", s.rumbleOnPhone)
|
||||
extra.put("android.gyro_on_phone", s.gyroOnPhone)
|
||||
extra.put("android.sc2_capture", s.sc2Capture)
|
||||
extra.put("android.ds_capture", s.dsCapture)
|
||||
extra.put("android.gamepad_ui_mode", s.gamepadUiMode)
|
||||
extra.put("android.gamepad_ui_enabled", s.gamepadUiEnabled)
|
||||
j.put("extra", extra)
|
||||
// Android-only rows ride `Settings::extra`, which is `#[serde(flatten)]` — so they are
|
||||
// TOP-LEVEL keys of this document, not a nested `extra` object. Nesting them put the
|
||||
// whole object into the map under the literal key "extra", where no console row could
|
||||
// read it and every value the console wrote came straight back as the one we had sent.
|
||||
j.put("android.low_latency", s.lowLatencyMode)
|
||||
j.put("android.rumble_on_phone", s.rumbleOnPhone)
|
||||
j.put("android.gyro_on_phone", s.gyroOnPhone)
|
||||
j.put("android.sc2_capture", s.sc2Capture)
|
||||
j.put("android.ds_capture", s.dsCapture)
|
||||
j.put("android.gamepad_ui_mode", s.gamepadUiMode)
|
||||
j.put("android.gamepad_ui_enabled", s.gamepadUiEnabled)
|
||||
j.put("android.reduce_ui_resolution", s.reduceUiResolution)
|
||||
// A store written by the nesting build carries the stale wrapper; drop it rather than
|
||||
// round-trip a copy of these keys that nothing reads for the life of the install.
|
||||
j.remove("extra")
|
||||
return j
|
||||
}
|
||||
|
||||
@@ -336,7 +341,8 @@ internal object ConsoleJson {
|
||||
*/
|
||||
fun applySettings(s: Settings, j: JSONObject): Settings {
|
||||
fun str(k: String, cur: String) = j.optString(k, cur).ifEmpty { cur }
|
||||
val extra = j.optJSONObject("extra") ?: JSONObject()
|
||||
// The `android.*` keys are TOP-LEVEL here, not nested: `Settings::extra` is
|
||||
// `#[serde(flatten)]`, so the console writes them beside `width` and `codec`.
|
||||
return s.copy(
|
||||
width = j.optInt("width", s.width),
|
||||
height = j.optInt("height", s.height),
|
||||
@@ -373,14 +379,15 @@ internal object ConsoleJson {
|
||||
"off" -> false
|
||||
else -> s.padSpeaker
|
||||
},
|
||||
lowLatencyMode = extra.optBoolean("android.low_latency", s.lowLatencyMode),
|
||||
rumbleOnPhone = extra.optBoolean("android.rumble_on_phone", s.rumbleOnPhone),
|
||||
gyroOnPhone = extra.optBoolean("android.gyro_on_phone", s.gyroOnPhone),
|
||||
sc2Capture = extra.optBoolean("android.sc2_capture", s.sc2Capture),
|
||||
dsCapture = extra.optBoolean("android.ds_capture", s.dsCapture),
|
||||
gamepadUiMode = extra.optString("android.gamepad_ui_mode", s.gamepadUiMode)
|
||||
lowLatencyMode = j.optBoolean("android.low_latency", s.lowLatencyMode),
|
||||
rumbleOnPhone = j.optBoolean("android.rumble_on_phone", s.rumbleOnPhone),
|
||||
gyroOnPhone = j.optBoolean("android.gyro_on_phone", s.gyroOnPhone),
|
||||
sc2Capture = j.optBoolean("android.sc2_capture", s.sc2Capture),
|
||||
dsCapture = j.optBoolean("android.ds_capture", s.dsCapture),
|
||||
gamepadUiMode = j.optString("android.gamepad_ui_mode", s.gamepadUiMode)
|
||||
.ifEmpty { s.gamepadUiMode },
|
||||
gamepadUiEnabled = extra.optBoolean("android.gamepad_ui_enabled", s.gamepadUiEnabled),
|
||||
gamepadUiEnabled = j.optBoolean("android.gamepad_ui_enabled", s.gamepadUiEnabled),
|
||||
reduceUiResolution = j.optBoolean("android.reduce_ui_resolution", s.reduceUiResolution),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalLayoutDirection
|
||||
@@ -137,13 +138,53 @@ fun SkiaConsoleShell(
|
||||
// Phone) still read a step too small in the hand: the floor is what sets the phone scale
|
||||
// (the couch term only wins on tablets and TVs), so this is a phones-only bump.
|
||||
val tv = remember { io.unom.punktfunk.isTvDevice(context) }
|
||||
val scale = if (tv) 0f else {
|
||||
val dm = context.resources.displayMetrics
|
||||
val couch = minOf(dm.widthPixels, dm.heightPixels) / 800f
|
||||
maxOf(couch, density.density * 0.75f).coerceIn(0.75f, 3f)
|
||||
// The SurfaceView's own laid-out size, fed back by `onSizeChanged` below — deliberately not
|
||||
// `displayMetrics`. The reduced buffer's aspect ratio has to match the RECT it is scaled into
|
||||
// or the compositor stretches the whole interface, and while those two normally agree,
|
||||
// `displayMetrics` has a long history of disagreeing with a view's real size by a system bar
|
||||
// depending on the version and on who is currently hiding what. "Normally agree" is not
|
||||
// something to hang picture geometry on. Zero until the first layout, which is exactly what
|
||||
// `render` wants: the surface comes up at its natural size and is re-fixed a frame later.
|
||||
var viewW by remember { mutableStateOf(0) }
|
||||
var viewH by remember { mutableStateOf(0) }
|
||||
// "Reduce interface resolution" (`Settings.reduceUiResolution`): cap the console's BUFFER at
|
||||
// 1920 on its long edge and let the compositor scale it up to the panel. 1 means "draw at the
|
||||
// panel's own resolution" — the setting is off, or the display is already at or under 1080p
|
||||
// and there is nothing to give back.
|
||||
//
|
||||
// ONE factor on both axes, so the aspect ratio survives exactly and no layout can stretch.
|
||||
// Everything else in this function that speaks in SURFACE pixels multiplies by it — the insets
|
||||
// and design-unit scale just below, the pointer coordinates further down — because
|
||||
// `setFixedSize` shrinks the buffer WITHOUT shrinking the view: a mouse still reports its
|
||||
// position in view pixels, and handing those straight to a half-size surface would land the
|
||||
// cursor at twice its true offset.
|
||||
val render = if (!settings.reduceUiResolution) 1f else {
|
||||
val long = maxOf(viewW, viewH)
|
||||
if (long > 1920) 1920f / long else 1f
|
||||
}
|
||||
LaunchedEffect(handle, left, top, right, bottom, scale) {
|
||||
if (handle != 0L) NativeBridge.nativeConsoleSetViewport(handle, left, top, right, bottom, scale)
|
||||
// The pointer listeners below are installed in `factory`, which runs ONCE — capturing `render`
|
||||
// directly would freeze them at its first-composition value (1, before the first layout has
|
||||
// reported a size), and a mouse would keep reporting view pixels into a half-size surface for
|
||||
// the rest of the session. Same reason `platformUp` is held this way.
|
||||
val currentRender by rememberUpdatedState(render)
|
||||
val dm = context.resources.displayMetrics
|
||||
val scale = if (tv) 0f else {
|
||||
val couch = minOf(dm.widthPixels, dm.heightPixels) / 800f
|
||||
// `render` too: the design-unit scale is in SURFACE pixels, so shrinking the buffer without
|
||||
// shrinking this would draw the type larger on screen than the same phone draws it today.
|
||||
maxOf(couch, density.density * 0.75f).coerceIn(0.75f, 3f) * render
|
||||
}
|
||||
LaunchedEffect(handle, left, top, right, bottom, scale, render) {
|
||||
if (handle != 0L) {
|
||||
NativeBridge.nativeConsoleSetViewport(
|
||||
handle,
|
||||
left * render,
|
||||
top * render,
|
||||
right * render,
|
||||
bottom * render,
|
||||
scale,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// The pad, raw, before MainActivity's B→Back and stick→D-pad synthesis: face buttons and the
|
||||
@@ -272,7 +313,9 @@ fun SkiaConsoleShell(
|
||||
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.onSizeChanged { viewW = it.width; viewH = it.height },
|
||||
factory = { ctx ->
|
||||
SurfaceView(ctx).apply {
|
||||
// The console draws opaque, edge to edge; Compose overlays sit above it.
|
||||
@@ -305,7 +348,8 @@ fun SkiaConsoleShell(
|
||||
MotionEvent.ACTION_CANCEL -> 5
|
||||
else -> return@setOnTouchListener false
|
||||
}
|
||||
NativeBridge.nativeConsolePointer(handle, kind, ev.x, ev.y, 0f)
|
||||
// View pixels → SURFACE pixels (see `render` above).
|
||||
NativeBridge.nativeConsolePointer(handle, kind, ev.x * currentRender, ev.y * currentRender, 0f)
|
||||
if (ev.actionMasked == MotionEvent.ACTION_UP) v.performClick()
|
||||
true
|
||||
}
|
||||
@@ -313,13 +357,27 @@ fun SkiaConsoleShell(
|
||||
if (handle != 0L && ev.actionMasked == MotionEvent.ACTION_SCROLL &&
|
||||
ev.isFromSource(InputDevice.SOURCE_CLASS_POINTER)
|
||||
) {
|
||||
NativeBridge.nativeConsolePointer(handle, 4, ev.x, ev.y, ev.getAxisValue(MotionEvent.AXIS_VSCROLL))
|
||||
NativeBridge.nativeConsolePointer(handle, 4, ev.x * currentRender, ev.y * currentRender, ev.getAxisValue(MotionEvent.AXIS_VSCROLL))
|
||||
true
|
||||
} else false
|
||||
}
|
||||
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
|
||||
}
|
||||
},
|
||||
// Applied here rather than in `factory` so flipping the setting takes effect without
|
||||
// leaving the console: `setFixedSize` re-creates the buffer and the render thread
|
||||
// re-wraps it through the ordinary surfaceChanged path. `setSizeFromLayout` is the
|
||||
// documented way back to "the view's own size" when the setting goes off again.
|
||||
update = { view ->
|
||||
if (render < 1f) {
|
||||
view.holder.setFixedSize(
|
||||
(viewW * render).roundToInt().coerceAtLeast(1),
|
||||
(viewH * render).roundToInt().coerceAtLeast(1),
|
||||
)
|
||||
} else {
|
||||
view.holder.setSizeFromLayout()
|
||||
}
|
||||
},
|
||||
)
|
||||
when (platformScreen) {
|
||||
"licenses" -> ConsoleLicensesScreen(onBack = { platformScreen = null }, navActive = true)
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package io.unom.punktfunk
|
||||
|
||||
import io.unom.punktfunk.console.ConsoleJson
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* The Android-only console settings ride `trust::Settings::extra`, which is `#[serde(flatten)]`:
|
||||
* they are TOP-LEVEL keys of the settings document, beside `width` and `codec`.
|
||||
*
|
||||
* They were written and read nested under an `"extra"` object instead. Serde put that whole
|
||||
* object into the map under the literal key `"extra"`, so no console row ever found
|
||||
* `android.gamepad_ui_enabled` — and the value the console saved came back to Kotlin as the one
|
||||
* Kotlin had just sent. On glass that was a "Controller-optimized UI" switch you could turn off
|
||||
* with nothing happening: the console stayed up, because the setting never moved.
|
||||
*/
|
||||
class ConsoleSettingsExtraTest {
|
||||
@Test
|
||||
fun androidKeysAreWrittenFlat() {
|
||||
val j = ConsoleJson.settings(Settings(gamepadUiEnabled = false, lowLatencyMode = false), null)
|
||||
assertTrue("the console reads this key at the top level", j.has("android.gamepad_ui_enabled"))
|
||||
assertFalse(j.getBoolean("android.gamepad_ui_enabled"))
|
||||
assertFalse(j.getBoolean("android.low_latency"))
|
||||
assertFalse("a nested wrapper is what serde swallows whole", j.has("extra"))
|
||||
}
|
||||
|
||||
/** A store written by the nesting build must not keep echoing its dead wrapper. */
|
||||
@Test
|
||||
fun aStaleNestedWrapperIsDropped() {
|
||||
val base = JSONObject().put(
|
||||
"extra",
|
||||
JSONObject().put("android.gamepad_ui_enabled", true),
|
||||
)
|
||||
assertFalse(ConsoleJson.settings(Settings(gamepadUiEnabled = false), base).has("extra"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theConsolesOwnSaveIsReadBack() {
|
||||
val saved = JSONObject()
|
||||
.put("android.gamepad_ui_enabled", false)
|
||||
.put("android.gamepad_ui_mode", GAMEPAD_UI_ALWAYS)
|
||||
.put("android.ds_capture", false)
|
||||
val next = ConsoleJson.applySettings(Settings(), saved)
|
||||
assertFalse("turning the console off must reach the store", next.gamepadUiEnabled)
|
||||
assertEquals(GAMEPAD_UI_ALWAYS, next.gamepadUiMode)
|
||||
assertFalse(next.dsCapture)
|
||||
}
|
||||
|
||||
/** Both halves against each other — the shape only holds if they agree. */
|
||||
@Test
|
||||
fun theRoundTripKeepsEveryAndroidRow() {
|
||||
val want = Settings(
|
||||
gamepadUiEnabled = false,
|
||||
gamepadUiMode = GAMEPAD_UI_ALWAYS,
|
||||
lowLatencyMode = false,
|
||||
rumbleOnPhone = true,
|
||||
gyroOnPhone = true,
|
||||
sc2Capture = false,
|
||||
dsCapture = false,
|
||||
)
|
||||
val got = ConsoleJson.applySettings(Settings(), ConsoleJson.settings(want, null))
|
||||
assertEquals(want.gamepadUiEnabled, got.gamepadUiEnabled)
|
||||
assertEquals(want.gamepadUiMode, got.gamepadUiMode)
|
||||
assertEquals(want.lowLatencyMode, got.lowLatencyMode)
|
||||
assertEquals(want.rumbleOnPhone, got.rumbleOnPhone)
|
||||
assertEquals(want.gyroOnPhone, got.gyroOnPhone)
|
||||
assertEquals(want.sc2Capture, got.sc2Capture)
|
||||
assertEquals(want.dsCapture, got.dsCapture)
|
||||
}
|
||||
}
|
||||
@@ -282,6 +282,17 @@ object Gamepad {
|
||||
* `KEYCODE_DPAD_*` are included but must only be routed here when the event is from a gamepad
|
||||
* (a keyboard's arrow keys share these keycodes and belong to the VK path) — see MainActivity.
|
||||
* L2/R2 are forwarded as the analog trigger axes, never as buttons.
|
||||
*
|
||||
* [BTN_TOUCHPAD] and [BTN_MISC1] have no Android keycode at all, so
|
||||
* [PadButtons.GENERIC_SONY] BORROWS the last two rows of `Generic.kl`'s joystick block for
|
||||
* them ([KEYCODE_BUTTON_15][KeyEvent.KEYCODE_BUTTON_15] / `_16`, evdev `BTN_BASE5`/`BTN_BASE6`)
|
||||
* — see there. This table is global, so a device that genuinely presses one of those two
|
||||
* emits the bit as well. That is the cost of the borrow, and it is why the borrow is at the
|
||||
* TOP of the block rather than at `BUTTON_1`/`BUTTON_2`: those are a flight stick's trigger
|
||||
* and thumb button, which any joystick-usage HID device reports, whereas reaching `BUTTON_15`
|
||||
* takes a pad that declares fifteen. The residual case — a fifteen-button HOTAS whose button
|
||||
* 16 also toggles the client's mic — is the one this leaves on the table; narrowing it
|
||||
* further needs per-device knowledge the router does not have (see `GamepadRouter`).
|
||||
*/
|
||||
fun buttonBit(keyCode: Int): Int = when (keyCode) {
|
||||
KeyEvent.KEYCODE_BUTTON_A -> BTN_A
|
||||
@@ -295,6 +306,8 @@ object Gamepad {
|
||||
KeyEvent.KEYCODE_BUTTON_START -> BTN_START
|
||||
KeyEvent.KEYCODE_BUTTON_SELECT -> BTN_BACK
|
||||
KeyEvent.KEYCODE_BUTTON_MODE -> BTN_GUIDE
|
||||
KeyEvent.KEYCODE_BUTTON_15 -> BTN_TOUCHPAD // borrowed — see the KDoc
|
||||
KeyEvent.KEYCODE_BUTTON_16 -> BTN_MISC1 // borrowed — see the KDoc
|
||||
KeyEvent.KEYCODE_DPAD_UP -> BTN_DPAD_UP
|
||||
KeyEvent.KEYCODE_DPAD_DOWN -> BTN_DPAD_DOWN
|
||||
KeyEvent.KEYCODE_DPAD_LEFT -> BTN_DPAD_LEFT
|
||||
@@ -404,9 +417,12 @@ object Gamepad {
|
||||
|
||||
/**
|
||||
* A Sony pad numbering straight through with no kernel driver behind it: □ ✕ ○ △ L1 R1
|
||||
* L2 R2 Create Options L3 R3 PS, i.e. `0x130`..`0x13c` in that order. The analog trigger
|
||||
* value rides `AXIS_RX`/`AXIS_RY` on such a pad, so the digital L2/R2 fold to keycodes
|
||||
* [buttonBit] deliberately drops — the wire carries the axis, never both.
|
||||
* L2 R2 Create Options L3 R3 PS touchpad mute, i.e. `0x130`..`0x13e` in that order. The
|
||||
* analog trigger value rides `AXIS_RX`/`AXIS_RY` on such a pad, so the digital L2/R2 fold
|
||||
* to keycodes [buttonBit] deliberately drops — the wire carries the axis, never both.
|
||||
*
|
||||
* This order — and ONLY this order — is where `0x13d`/`0x13e` mean the touchpad click and
|
||||
* the mute button. Everywhere else they are L3/R3.
|
||||
*/
|
||||
GENERIC_SONY,
|
||||
|
||||
@@ -453,7 +469,23 @@ object Gamepad {
|
||||
0x13a -> KeyEvent.KEYCODE_BUTTON_THUMBL
|
||||
0x13b -> KeyEvent.KEYCODE_BUTTON_THUMBR
|
||||
0x13c -> KeyEvent.KEYCODE_BUTTON_MODE // PS
|
||||
// 0x13d touchpad click / 0x13e mute: no wire button, dropped as before.
|
||||
// Touchpad click and mute. The wire has bits for both ([BTN_TOUCHPAD] /
|
||||
// [BTN_MISC1]) and Android has no keycode for either, so these two borrow
|
||||
// BUTTON_15/BUTTON_16 to reach [buttonBit] — see its KDoc for the cost.
|
||||
//
|
||||
// ONLY here. `0x13d`/`0x13e` are BTN_THUMBL/BTN_THUMBR (L3/R3) in the standard
|
||||
// Linux mapping — [genericKeyCode] says so itself — and they mean touchpad and
|
||||
// mute purely because a driverless DualSense enumerates its buttons straight
|
||||
// through in its own report order, which is what GENERIC_SONY IS. Hoisting
|
||||
// this above `padMap(dev)` would put L3 on the touchpad and R3 on the mic for
|
||||
// every Xbox pad, Switch Pro, 8BitDo, Steam Deck and `hid-playstation`
|
||||
// DualSense on the couch. There is no scancode that means the same button on
|
||||
// all pads; that is the entire reason this enum exists.
|
||||
0x13d -> KeyEvent.KEYCODE_BUTTON_15 // touchpad click → BTN_TOUCHPAD
|
||||
0x13e -> KeyEvent.KEYCODE_BUTTON_16 // mute → BTN_MISC1
|
||||
// Unreachable with the guard above in force (it only lets `0x130`..`0x13e`
|
||||
// through, and every one of those is now named), and KEYCODE_UNKNOWN is the
|
||||
// safe answer if that ever changes.
|
||||
else -> KeyEvent.KEYCODE_UNKNOWN
|
||||
}
|
||||
GENERIC_XBOX -> when (scan) {
|
||||
|
||||
@@ -101,6 +101,18 @@ class GamepadRouter(
|
||||
* the whole session. The capture-link pads carry the same flag on [ExternalPad].
|
||||
*/
|
||||
val motionReaches: Boolean = true,
|
||||
/**
|
||||
* Whether [Gamepad.BTN_MISC1] means a MUTE button on this particular pad — the one bit
|
||||
* whose physical meaning differs per controller, and the gate on the mic toggle in
|
||||
* [slotButton].
|
||||
*
|
||||
* A DualSense has one; a Steam Controller 2 puts its QAM button on the same wire bit
|
||||
* (`Sc2Device`), and QAM must not mute anyone's microphone. Asked once at open, off the
|
||||
* fact each path actually knows: the report order for an [InputDevice] (only
|
||||
* [Gamepad.PadButtons.GENERIC_SONY] mints this bit there), the declared pad kind for a
|
||||
* capture link.
|
||||
*/
|
||||
val hasMuteButton: Boolean = false,
|
||||
) {
|
||||
/** Forwarded button bits currently held (Gamepad.BTN_*) — for release-on-close + chord detection. */
|
||||
var held = 0
|
||||
@@ -160,7 +172,8 @@ class GamepadRouter(
|
||||
|
||||
/**
|
||||
* Invoked (main thread) each time the mic-mute chord ([MIC_CHORD], Select + Y) is COMPLETED on
|
||||
* a pad — the couch equivalent of the stream's on-screen mute button, which a gamepad user
|
||||
* a pad, or a pad's own mute button ([Gamepad.BTN_MISC1] — a DualSense's) is pressed — the
|
||||
* couch equivalent of the stream's on-screen mute button, which a gamepad user
|
||||
* cannot reach. `StreamScreen` wires it to the mute toggle. Unlike the exit chord this fires
|
||||
* immediately: muting is the kind of thing you want to have already happened, and the on-screen
|
||||
* indicator makes an accidental toggle self-evident. The buttons still go to the host — the
|
||||
@@ -234,15 +247,40 @@ class GamepadRouter(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this bit's WIRE SEND kept with this device, though the bit is otherwise tracked normally?
|
||||
*
|
||||
* Exactly one is: a real mute button ([Slot.hasMuteButton]) under the "local" [systemForward]
|
||||
* policy. It is tracked — the mic toggle in [slotButton] is edge-triggered off held state —
|
||||
* but not forwarded, so every send site has to ask, including [releaseHeld]'s close-time
|
||||
* flush, or a mute held across a disconnect would put a release on the wire for a press that
|
||||
* never went out. Every other system button under that policy leaves [slotButton] at the top
|
||||
* and never reaches a send at all.
|
||||
*/
|
||||
private fun localOnly(slot: Slot, bit: Int): Boolean =
|
||||
!systemForward && bit == Gamepad.BTN_MISC1 && slot.hasMuteButton
|
||||
|
||||
/**
|
||||
* One button transition on [slot] — the shared body behind [onButton] and an [ExternalPad]'s
|
||||
* transitions: forward the wire event, track held state, arm/disarm the exit chord, and fire
|
||||
* the instant chords ([MIC_CHORD], [STATS_CHORD]).
|
||||
* the instant chords ([MIC_CHORD], [STATS_CHORD], and the mute button's own mic toggle).
|
||||
*/
|
||||
private fun slotButton(slot: Slot, bit: Int, down: Boolean, send: Boolean) {
|
||||
// Raw system buttons stay local under the "local" policy — no wire send and no held
|
||||
// tracking, symmetric on both edges so nothing leaks into the chords either.
|
||||
if (!systemForward && (bit == Gamepad.BTN_GUIDE || bit == Gamepad.BTN_MISC1)) return
|
||||
// tracking, symmetric on both edges so nothing leaks into the chords either. A Steam
|
||||
// Controller 2's QAM button is BTN_MISC1 and keeps exactly that behaviour.
|
||||
//
|
||||
// A real MUTE button ([Slot.hasMuteButton]) is deliberately exempt: that policy's own
|
||||
// words are "keeps them entirely with this device", and toggling this device's microphone
|
||||
// is precisely what a mute button does with itself. Returning here would have left the
|
||||
// button present and silently dead under `local`, for a reason nobody would ever find. It
|
||||
// loses its wire send instead (see [localOnly]) and keeps the held tracking the toggle's
|
||||
// edge-trigger reads. It cannot leak into a chord — MISC1 is in none of them.
|
||||
if (!systemForward &&
|
||||
(bit == Gamepad.BTN_GUIDE || (bit == Gamepad.BTN_MISC1 && !slot.hasMuteButton))
|
||||
) {
|
||||
return
|
||||
}
|
||||
if (down) {
|
||||
if (guideGesture && send) {
|
||||
// A Select pressed ALONE is held back until it resolves: a tap (delivered
|
||||
@@ -258,7 +296,7 @@ class GamepadRouter(
|
||||
}
|
||||
flushPendingSelect(slot)
|
||||
}
|
||||
if (send && forwarding) {
|
||||
if (send && forwarding && !localOnly(slot, bit)) {
|
||||
NativeBridge.nativeSendGamepadButton(handle, bit, true, slot.index)
|
||||
}
|
||||
val wasHeld = slot.held
|
||||
@@ -268,11 +306,26 @@ class GamepadRouter(
|
||||
// Mic mute and the stats-tier cycle, each edge-triggered on the button that COMPLETES
|
||||
// its chord (see [completesChord]) — the two meanings this client gives Select plus a
|
||||
// face button. Both leave the press on the wire: the game still gets its buttons.
|
||||
if (completesChord(wasHeld, bit, MIC_CHORD)) onMicChord?.invoke()
|
||||
//
|
||||
// A pad's own mute button is a second trigger for the SAME toggle, not a new
|
||||
// mechanism — so it gets the same edge-trigger, expressed as the one-button chord it
|
||||
// is. That is load-bearing rather than tidy: [onButton] deliberately still calls this
|
||||
// with `down = true` on auto-repeat and suppresses only `send` (its repeatCount
|
||||
// guard), so an unguarded `bit == BTN_MISC1` would flap the mic for as long as the
|
||||
// button is held down.
|
||||
//
|
||||
// [Slot.hasMuteButton] is the other half, and it is not belt-and-braces: BTN_MISC1 is
|
||||
// the wire's misc/QAM bit, and `Sc2Device` puts a Steam Controller 2's QAM button on
|
||||
// it. Reading "any MISC1" as mute would mute the microphone on every QAM press.
|
||||
if (completesChord(wasHeld, bit, MIC_CHORD) ||
|
||||
(slot.hasMuteButton && completesChord(wasHeld, bit, Gamepad.BTN_MISC1))
|
||||
) {
|
||||
onMicChord?.invoke()
|
||||
}
|
||||
if (completesChord(wasHeld, bit, STATS_CHORD)) onStatsChord?.invoke()
|
||||
} else {
|
||||
val owned = guideGesture && bit == Gamepad.BTN_BACK && consumeSelectRelease(slot)
|
||||
if (!owned && send && forwarding) {
|
||||
if (!owned && send && forwarding && !localOnly(slot, bit)) {
|
||||
NativeBridge.nativeSendGamepadButton(handle, bit, false, slot.index)
|
||||
}
|
||||
slot.held = slot.held and bit.inv()
|
||||
@@ -543,7 +596,15 @@ class GamepadRouter(
|
||||
// time. Cheap enough to ask unconditionally; the answer holds for the pad's lifetime.
|
||||
val motionReaches = NativeBridge.nativePadMotionReaches(handle, pref)
|
||||
if (forwarding && hasGyro && !motionReaches) onMotionUnreachable?.invoke()
|
||||
slots[syntheticId] = Slot(index, Gamepad.AxisMapper(handle, index))
|
||||
// `DsDevice` raises BTN_MISC1 from the DualSense report's mute bit; `Sc2Device` raises the
|
||||
// same bit from the Steam Controller 2's QAM button, which must not touch the microphone.
|
||||
// The declared kind separates them (a DualShock 4 has no mute button either).
|
||||
val hasMute = pref == Gamepad.PREF_DUALSENSE || pref == Gamepad.PREF_DUALSENSEEDGE
|
||||
slots[syntheticId] = Slot(
|
||||
index,
|
||||
Gamepad.AxisMapper(handle, index),
|
||||
hasMuteButton = hasMute,
|
||||
)
|
||||
return ExternalPad(syntheticId, index, motionReaches)
|
||||
}
|
||||
|
||||
@@ -603,10 +664,15 @@ class GamepadRouter(
|
||||
// Asked here, off the kind this pad just DECLARED — not off the session's resolved backend,
|
||||
// which under Automatic answers for whichever pad happened to be active at dial time. Held
|
||||
// for the slot's life; the sensor path reads it on every sample.
|
||||
val map = Gamepad.padMap(dev)
|
||||
val slot = Slot(
|
||||
index,
|
||||
Gamepad.AxisMapper(handle, index, Gamepad.padMap(dev)),
|
||||
Gamepad.AxisMapper(handle, index, map),
|
||||
NativeBridge.nativePadMotionReaches(handle, pref),
|
||||
// The only route to BTN_MISC1 on this path is GENERIC_SONY's `0x13e` row, so the
|
||||
// report order IS the answer — and unlike `pref` it survives the user pinning every
|
||||
// pad to one type, which would otherwise cost a DualSense its mute button.
|
||||
hasMuteButton = map.buttons == Gamepad.PadButtons.GENERIC_SONY,
|
||||
)
|
||||
slots[dev.id] = slot
|
||||
// After the table holds the slot, so a listener that sends on this device the moment it is
|
||||
@@ -652,7 +718,9 @@ class GamepadRouter(
|
||||
var bits = slot.held
|
||||
while (bits != 0) {
|
||||
val bit = bits and -bits // lowest set bit
|
||||
if (forwarding) NativeBridge.nativeSendGamepadButton(handle, bit, false, slot.index)
|
||||
if (forwarding && !localOnly(slot, bit)) {
|
||||
NativeBridge.nativeSendGamepadButton(handle, bit, false, slot.index)
|
||||
}
|
||||
bits = bits and bit.inv()
|
||||
}
|
||||
slot.held = 0
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.unom.punktfunk.kit
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
@@ -155,6 +156,44 @@ class GamepadChordTest {
|
||||
assertEquals(instantChords, pad.press(Gamepad.BTN_BACK))
|
||||
}
|
||||
|
||||
/**
|
||||
* A pad's own mute button (a DualSense's) is a second trigger for the mic toggle, and
|
||||
* `slotButton` reads it through the SAME edge rule expressed as a one-button chord.
|
||||
*
|
||||
* That is not decoration. `onButton` deliberately still calls `slotButton(down = true)` on
|
||||
* auto-repeat and suppresses only the wire send (its repeatCount guard), so a plain
|
||||
* `bit == BTN_MISC1` would toggle the mic on every repeat — hold the button and the mic
|
||||
* flaps. `completesChord` against a single-bit mask is exactly "a fresh press of it".
|
||||
*
|
||||
* The other half is which buttons must NOT reach it. `0x13e` is R3 on every pad but a
|
||||
* driverless Sony one, so a mapping that leaked touchpad/mute meanings outside
|
||||
* [Gamepad.PadButtons.GENERIC_SONY] would put the mic toggle on every R3 press in the house.
|
||||
*
|
||||
* `slotButton` ANDs this rule with `Slot.hasMuteButton`, because BTN_MISC1 is the wire's
|
||||
* misc/QAM bit and a Steam Controller 2's QAM button rides it too. That term needs a live
|
||||
* `Slot`, which needs an InputManager and a main Looper, so it is out of reach from here —
|
||||
* the edge rule below is the half a unit test can hold.
|
||||
*/
|
||||
@Test
|
||||
fun `the mute button toggles the mic once per press`() {
|
||||
fun fires(wasHeld: Int, bit: Int) =
|
||||
GamepadRouter.completesChord(wasHeld, bit, Gamepad.BTN_MISC1)
|
||||
|
||||
assertTrue("a fresh press must toggle", fires(0, Gamepad.BTN_MISC1))
|
||||
assertFalse("auto-repeat re-fired the toggle", fires(Gamepad.BTN_MISC1, Gamepad.BTN_MISC1))
|
||||
assertTrue(
|
||||
"a press while other buttons are held is still a fresh press",
|
||||
fires(Gamepad.BTN_A or Gamepad.BTN_BACK, Gamepad.BTN_MISC1),
|
||||
)
|
||||
for (other in listOf(
|
||||
Gamepad.BTN_A, Gamepad.BTN_X, Gamepad.BTN_Y, Gamepad.BTN_BACK,
|
||||
Gamepad.BTN_LS_CLICK, Gamepad.BTN_RS_CLICK, Gamepad.BTN_GUIDE, Gamepad.BTN_TOUCHPAD,
|
||||
)) {
|
||||
assertFalse("$other toggled the mic", fires(0, other))
|
||||
assertFalse("$other toggled the mic under a held mute", fires(Gamepad.BTN_MISC1, other))
|
||||
}
|
||||
}
|
||||
|
||||
/** The chord bits are the wire's, so they must stay inside the 32-bit button mask. */
|
||||
@Test
|
||||
fun `chord masks are wire button bits`() {
|
||||
|
||||
@@ -64,12 +64,44 @@ class PadButtonsTest {
|
||||
assertEquals(KeyEvent.KEYCODE_BUTTON_MODE, sony(0x13c)) // PS
|
||||
}
|
||||
|
||||
/** The touchpad click and mute have no wire button; they must resolve to nothing, not to R3. */
|
||||
/**
|
||||
* The touchpad click and the mute button reach the wire, on the two bits that exist for them.
|
||||
* Android has no keycode for either, so [Gamepad.PadButtons.GENERIC_SONY] borrows BUTTON_15
|
||||
* and BUTTON_16 to carry them into [Gamepad.buttonBit] — the keycode is an implementation
|
||||
* detail of that hop, the BIT is the contract, so both halves are pinned here.
|
||||
*/
|
||||
@Test
|
||||
fun `a DualSense's touchpad and mute are dropped rather than mistaken`() {
|
||||
assertEquals(KeyEvent.KEYCODE_UNKNOWN, sony(0x13d))
|
||||
assertEquals(KeyEvent.KEYCODE_UNKNOWN, sony(0x13e))
|
||||
assertEquals(0, Gamepad.buttonBit(sony(0x13d)))
|
||||
fun `a DualSense's touchpad and mute reach their wire buttons`() {
|
||||
assertEquals(KeyEvent.KEYCODE_BUTTON_15, sony(0x13d))
|
||||
assertEquals(KeyEvent.KEYCODE_BUTTON_16, sony(0x13e))
|
||||
assertEquals(Gamepad.BTN_TOUCHPAD, Gamepad.buttonBit(sony(0x13d)))
|
||||
assertEquals(Gamepad.BTN_MISC1, Gamepad.buttonBit(sony(0x13e)))
|
||||
}
|
||||
|
||||
/**
|
||||
* The regression the touchpad/mute mapping is one hoist away from causing, and the reason it
|
||||
* lives inside GENERIC_SONY rather than anywhere above `padMap(dev)`.
|
||||
*
|
||||
* `0x13d`/`0x13e` are `BTN_THUMBL`/`BTN_THUMBR` — L3 and R3 — in the standard Linux/AOSP
|
||||
* mapping, which is what [Gamepad.genericKeyCode] says they are. They mean touchpad click and
|
||||
* mute ONLY inside the straight-through enumeration a driverless Sony pad uses. Read as
|
||||
* touchpad and mute anywhere else, every Xbox pad, Switch Pro, 8BitDo, Steam Deck and
|
||||
* `hid-playstation` DualSense loses both stick clicks — and R3 starts toggling the microphone.
|
||||
*/
|
||||
@Test
|
||||
fun `every other pad keeps L3 and R3 on those scancodes`() {
|
||||
for (p in listOf(
|
||||
Gamepad.PadButtons.NATIVE,
|
||||
Gamepad.PadButtons.GENERIC_XBOX,
|
||||
Gamepad.PadButtons.SONY_MODERN,
|
||||
)) {
|
||||
val l3 = p.correct(0x13d, Gamepad.genericKeyCode(0x13d))
|
||||
val r3 = p.correct(0x13e, Gamepad.genericKeyCode(0x13e))
|
||||
assertEquals("$p L3", KeyEvent.KEYCODE_BUTTON_THUMBL, l3)
|
||||
assertEquals("$p R3", KeyEvent.KEYCODE_BUTTON_THUMBR, r3)
|
||||
assertEquals("$p L3 bit", Gamepad.BTN_LS_CLICK, Gamepad.buttonBit(l3))
|
||||
assertEquals("$p R3 bit", Gamepad.BTN_RS_CLICK, Gamepad.buttonBit(r3))
|
||||
}
|
||||
}
|
||||
|
||||
/** An Xbox-layout pad numbering straight through: A B X Y LB RB View Menu LS RS. */
|
||||
@@ -116,6 +148,30 @@ class PadButtonsTest {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The guard's NEGATIVE path — the half that decides anything.
|
||||
*
|
||||
* The cases above all deliver the keycode `Generic.kl` would have produced, so the guard is
|
||||
* transparent in every one of them and the assertions would hold with it deleted. These are
|
||||
* the ones that fail without it: a device-specific key layout answering something the table
|
||||
* disagrees with, on a scancode the table has an opinion about. The layout wins — it knows
|
||||
* this controller, and the table is only ever a guess about a pad nothing knew.
|
||||
*/
|
||||
@Test
|
||||
fun `a device layout outranks the table on a scancode the table would have rewritten`() {
|
||||
// `Generic.kl` calls 0x134 BUTTON_Y, and GENERIC_SONY/GENERIC_XBOX both rewrite that
|
||||
// scancode to BUTTON_L1. A layout that says BUTTON_X must survive both.
|
||||
for (p in listOf(Gamepad.PadButtons.GENERIC_SONY, Gamepad.PadButtons.GENERIC_XBOX)) {
|
||||
assertEquals("$p", KeyEvent.KEYCODE_BUTTON_X, p.correct(0x134, KeyEvent.KEYCODE_BUTTON_X))
|
||||
}
|
||||
// And the two rows added for the touchpad and mute are no different: a pad whose layout
|
||||
// resolved 0x13d itself keeps that answer rather than the borrowed BUTTON_15.
|
||||
assertEquals(
|
||||
KeyEvent.KEYCODE_BUTTON_1,
|
||||
Gamepad.PadButtons.GENERIC_SONY.correct(0x13d, KeyEvent.KEYCODE_BUTTON_1),
|
||||
)
|
||||
}
|
||||
|
||||
/** Correcting twice is correcting once — the output is never itself a generic-layout answer. */
|
||||
@Test
|
||||
fun `correction is idempotent`() {
|
||||
|
||||
@@ -223,6 +223,7 @@ impl ConsoleHost {
|
||||
let thread = std::thread::Builder::new()
|
||||
.name("pf-console".into())
|
||||
.spawn(move || {
|
||||
boost_thread_priority();
|
||||
let run = || -> Result<()> {
|
||||
let console = Console::new(opts, entry, &thread_handles)?;
|
||||
render_loop(console, thread_shared.clone(), thread_store)
|
||||
@@ -249,6 +250,34 @@ impl ConsoleHost {
|
||||
}
|
||||
}
|
||||
|
||||
/// Best-effort: lift the console's render thread off the default nice band, the same way
|
||||
/// `decode::setup::boost_thread_priority` lifts the decode thread. This thread IS the console's
|
||||
/// frame loop — every menu press waits on it — and at default priority a TV box's scheduler is
|
||||
/// free to park it on a little core behind whatever else the system is doing, which reads as a
|
||||
/// UI that lags the remote. `-8` rather than the decode path's `-10`: a stream's frames are the
|
||||
/// harder deadline, and the two should not compete when the console is up during a session.
|
||||
///
|
||||
/// Non-fatal if the platform refuses (the exact floor a foreground app may set is policy).
|
||||
fn boost_thread_priority() {
|
||||
// SAFETY: `gettid`/`setpriority` on the calling thread are always-safe syscalls; PRIO_PROCESS
|
||||
// with a TID targets that one task on Linux — the idiom `Process.setThreadPriority` uses.
|
||||
unsafe {
|
||||
let tid = libc::gettid();
|
||||
if libc::setpriority(libc::PRIO_PROCESS, tid as libc::id_t, -8) != 0 {
|
||||
log::debug!(
|
||||
"console: setpriority(-8) failed (non-fatal): {}",
|
||||
std::io::Error::last_os_error()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How often the render loop reports what a frame is costing it. Nothing in a bug report from a
|
||||
/// TV said whether the console was drawing at 4K or at 60 Hz, so "it feels sluggish" could not be
|
||||
/// triaged from a log bundle at all — this is that missing line. One line a minute is cheap
|
||||
/// enough to leave on for everyone, and the answer is only useful from the box that is slow.
|
||||
const FRAME_REPORT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// No input for this long = the console is being looked at, not used — halve the redraw
|
||||
/// rate (`IDLE_FRAME_STEP` slept between swaps). 60 s keeps every interaction and its
|
||||
/// afterglow at full smoothness and only calms a genuinely parked screen.
|
||||
@@ -283,6 +312,9 @@ fn render_loop(mut console: Console, shared: Arc<Shared>, store: Arc<SnapshotSto
|
||||
// SurfaceView forever. Dying raises `Dead`, and Kotlin answers with the touch UI.
|
||||
let mut gl_failures = 0u32;
|
||||
const GL_FAILURE_LIMIT: u32 = 3;
|
||||
// What a frame is costing, reported once a `FRAME_REPORT` window (see there).
|
||||
let (mut frames, mut frame_time, mut frame_peak) = (0u32, Duration::ZERO, Duration::ZERO);
|
||||
let mut report_at = Instant::now();
|
||||
|
||||
loop {
|
||||
// Take everything queued. With no surface up, block until something arrives.
|
||||
@@ -446,8 +478,17 @@ fn render_loop(mut console: Console, shared: Arc<Shared>, store: Arc<SnapshotSto
|
||||
skia = None;
|
||||
match g.wrap_window(&egl, w, h) {
|
||||
Ok(surf) => {
|
||||
// The console's real render resolution — the one number a bug report
|
||||
// from a TV never carried. A 4K panel is 4× the fragment work of 1080p
|
||||
// for every pass the shell draws.
|
||||
log::info!("console: drawing at {w}×{h}");
|
||||
skia = Some((surf, w, h));
|
||||
gl_failures = 0;
|
||||
// Start the frame window here, not at loop entry: the console parks
|
||||
// with no surface while a stream is up, and a window that had been
|
||||
// open across that would report its first frame as "1 frame in 20 min".
|
||||
(frames, frame_time, frame_peak, report_at) =
|
||||
(0, Duration::ZERO, Duration::ZERO, Instant::now());
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("console: {e:#}");
|
||||
@@ -462,6 +503,11 @@ fn render_loop(mut console: Console, shared: Arc<Shared>, store: Arc<SnapshotSto
|
||||
insets,
|
||||
scale,
|
||||
};
|
||||
// Around the DRAW only, not the swap: `eglSwapBuffers` blocks on vsync, so
|
||||
// wall-clock per iteration is always ~the panel period and says nothing. What
|
||||
// matters is how much of that period the shell spends building the frame —
|
||||
// once that passes the period, the console is missing vsyncs.
|
||||
let drew = Instant::now();
|
||||
console.frame(
|
||||
surf.canvas(),
|
||||
&viewport,
|
||||
@@ -470,6 +516,20 @@ fn render_loop(mut console: Console, shared: Arc<Shared>, store: Arc<SnapshotSto
|
||||
&pads,
|
||||
);
|
||||
g.context.flush_and_submit();
|
||||
let cost = drew.elapsed();
|
||||
frame_time += cost;
|
||||
frame_peak = frame_peak.max(cost);
|
||||
frames += 1;
|
||||
if report_at.elapsed() >= FRAME_REPORT {
|
||||
log::info!(
|
||||
"console: {w}×{h}, {frames} frames in {:?} — {:.1} ms/frame mean, {:.1} ms peak",
|
||||
report_at.elapsed(),
|
||||
frame_time.as_secs_f64() * 1000.0 / f64::from(frames),
|
||||
frame_peak.as_secs_f64() * 1000.0,
|
||||
);
|
||||
(frames, frame_time, frame_peak, report_at) =
|
||||
(0, Duration::ZERO, Duration::ZERO, Instant::now());
|
||||
}
|
||||
if let Err(e) = s.swap() {
|
||||
// The window went away under us; wait for the next surface.
|
||||
log::warn!("console: {e:#} — dropping the surface");
|
||||
|
||||
@@ -21,6 +21,25 @@
|
||||
//! handle early at worst reuses a buffer a touch soon (a visible tear), never a use-after-free. The
|
||||
//! fences are the correctness of *timing*, not of memory — which is what lets this ship behind an
|
||||
//! auto-fallback with the residual risk being visual, not a crash.
|
||||
//!
|
||||
//! **The acquire fence must come from `acquireNextImageAsync`, never `acquireLatestImageAsync`.**
|
||||
//! `AImageReader::acquireLatestImage` (`NdkImageReader.cpp`, unfixed as of AOSP main) drains with
|
||||
//! one `int*` out-param it overwrites per image, then releases each dropped image with whatever the
|
||||
//! out-param currently holds — the *successor's* fence:
|
||||
//!
|
||||
//! ```text
|
||||
//! acquireImageLocked(&prev, fd) → *fd = F1 (prev = img1)
|
||||
//! acquireImageLocked(&next, fd) → *fd = F2 (next = img2; F1 overwritten and leaked)
|
||||
//! prev->close(*fd) → reader adopts F2 as img1's release fence, then closes it
|
||||
//! acquireImageLocked(&next, fd) → no buffer; leaves *fd alone
|
||||
//! returns img2 with *fd = F2 ← already given away and closed
|
||||
//! ```
|
||||
//!
|
||||
//! So the moment a burst gives it two images to collapse, the caller is handed a stale fd plus one
|
||||
//! leaked fd per extra drop. Passing that stale fd to `setBuffer` transfers it to SurfaceFlinger,
|
||||
//! which closes it again — an `fdsan` `SIGABRT` on the decode thread, either at `Fence::Fence(int)`
|
||||
//! inside `setBuffer` (the number was already re-owned) or at the end of `Transaction::apply` when
|
||||
//! the layer state is torn down. `AscBackend::drain_reader` therefore does newest-wins itself.
|
||||
|
||||
use ndk::hardware_buffer::HardwareBuffer;
|
||||
use ndk::media::image_reader::{AcquireResult, Image, ImageFormat, ImageReader};
|
||||
@@ -376,19 +395,24 @@ impl AscBackend {
|
||||
true
|
||||
}
|
||||
|
||||
/// Acquire newly rendered images out of the reader: latency keeps only the newest (older are
|
||||
/// dropped back to the pool by `acquireLatest`); smooth keeps order up to capacity.
|
||||
/// Acquire newly rendered images out of the reader: latency keeps only the newest (older ones
|
||||
/// drop back to the pool as they are superseded); smooth keeps order up to capacity.
|
||||
///
|
||||
/// Both modes drain with `acquireNextImageAsync`, one image at a time. `acquireLatestImageAsync`
|
||||
/// is the obvious newest-wins call and is NOT usable — see the acquire-fence note at the top of
|
||||
/// this module.
|
||||
fn drain_reader(&mut self) {
|
||||
if self.fifo_capacity == 0 {
|
||||
// Newest-wins: one acquire-latest collapses the whole burst to the freshest buffer.
|
||||
if let Some(acq) = self.acquire(true) {
|
||||
// Newest-wins: collapse the burst to the freshest buffer ourselves. Each superseded
|
||||
// candidate drops here — its image returns to the pool, its own acquire fence closes.
|
||||
while let Some(acq) = self.acquire() {
|
||||
if self.candidate.replace(acq).is_some() {
|
||||
self.skipped += 1; // an un-presented candidate was superseded
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Smooth: pull every ready image in order into the FIFO, evicting the oldest past cap.
|
||||
while let Some(acq) = self.acquire(false) {
|
||||
while let Some(acq) = self.acquire() {
|
||||
self.fifo.push_back(acq);
|
||||
while self.fifo.len() > self.fifo_capacity {
|
||||
self.fifo.pop_front();
|
||||
@@ -398,19 +422,13 @@ impl AscBackend {
|
||||
}
|
||||
}
|
||||
|
||||
/// Acquire one image (`latest` drops older, else FIFO) and pair its decode stamps + cadence due.
|
||||
/// `None` when the reader is empty or a transient acquire error occurs.
|
||||
fn acquire(&mut self, latest: bool) -> Option<Acquired> {
|
||||
/// Acquire the next image and pair its decode stamps + cadence due. `None` when the reader is
|
||||
/// empty or a transient acquire error occurs.
|
||||
fn acquire(&mut self) -> Option<Acquired> {
|
||||
// SAFETY: we never touch the image's pixels — the acquire fence is handed straight to
|
||||
// SurfaceFlinger via `setBuffer`, which is exactly the "await before access" the async
|
||||
// acquire requires.
|
||||
let res = unsafe {
|
||||
if latest {
|
||||
self.reader.acquire_latest_image_async()
|
||||
} else {
|
||||
self.reader.acquire_next_image_async()
|
||||
}
|
||||
};
|
||||
let res = unsafe { self.reader.acquire_next_image_async() };
|
||||
let (image, fence) = match res {
|
||||
Ok(AcquireResult::Image(pair)) => pair,
|
||||
Ok(_) => return None, // no buffer available / max acquired
|
||||
|
||||
@@ -317,6 +317,12 @@ impl ImageReader {
|
||||
/// If the returned file descriptor is not [`None`], it must be awaited before attempting to
|
||||
/// access the [`Image`] returned.
|
||||
///
|
||||
/// **The returned fence is unsound whenever the platform actually drops an older image.**
|
||||
/// `AImageReader::acquireLatestImage` reuses one out-param across the drain and releases each
|
||||
/// dropped image with the *successor's* fence fd, so the fd handed back has already been given
|
||||
/// to the reader (and closed by it) — adopting it here yields a double close and an `fdsan`
|
||||
/// abort. Drain with [`ImageReader::acquire_next_image_async()`] and pick the newest yourself.
|
||||
///
|
||||
/// <https://developer.android.com/ndk/reference/group/media#aimagereader_acquirelatestimageasync>
|
||||
#[cfg(feature = "api-level-26")]
|
||||
#[doc(alias = "AImageReader_acquireLatestImageAsync")]
|
||||
|
||||
@@ -80,6 +80,12 @@ enum RowId {
|
||||
/// beside the palette row for the same reason it does: both are presentation, and the
|
||||
/// effect of stepping this one is visible on the backdrop behind it.
|
||||
ReduceMotion,
|
||||
/// Draw the console at 1080p and let the display scale it up, instead of at the panel's
|
||||
/// own resolution. Android-only, and beside [`RowId::ReduceMotion`] on purpose: both are
|
||||
/// "give up some fidelity for a smoother console", and this is the one that matters on a
|
||||
/// 4K TV or projector, where every pass the shell draws costs four times what it does at
|
||||
/// 1080p on a GPU that is not four times faster.
|
||||
ReduceUiResolution,
|
||||
/// How the game library arranges its titles — see `library::LibraryView`. The library
|
||||
/// changes it in place now, from the bar over its own field, which is where an
|
||||
/// arrangement you want to SEE the effect of belongs; this row stays because both
|
||||
@@ -128,6 +134,7 @@ mod android_keys {
|
||||
pub const DS_CAPTURE: &str = "android.ds_capture";
|
||||
pub const GAMEPAD_UI_MODE: &str = "android.gamepad_ui_mode";
|
||||
pub const GAMEPAD_UI: &str = "android.gamepad_ui_enabled";
|
||||
pub const REDUCE_UI_RES: &str = "android.reduce_ui_resolution";
|
||||
}
|
||||
|
||||
/// The Android console-UI mode's stored values (`GamepadUi.kt`).
|
||||
@@ -247,6 +254,7 @@ const TABS: [(&str, &[RowId]); 7] = [
|
||||
&[
|
||||
RowId::Palette,
|
||||
RowId::ReduceMotion,
|
||||
RowId::ReduceUiResolution,
|
||||
RowId::LibraryView,
|
||||
RowId::LibraryCollections,
|
||||
RowId::Stats,
|
||||
@@ -685,6 +693,7 @@ fn row_on(id: RowId, platform: crate::platform::Platform) -> bool {
|
||||
| RowId::DsCapture
|
||||
| RowId::GamepadUi
|
||||
| RowId::GamepadUiMode
|
||||
| RowId::ReduceUiResolution
|
||||
| RowId::Controllers
|
||||
| RowId::Licenses
|
||||
);
|
||||
@@ -936,6 +945,11 @@ fn row_spec(id: RowId, ctx: &Ctx, profiles: &[(String, String)]) -> RowSpec {
|
||||
// Phrased as the thing that is ON, not as the suppression, so "On" means the
|
||||
// reduction is in effect — the same way every other toggle on this screen reads.
|
||||
RowId::ReduceMotion => (None, "Reduce motion", on_off(s.reduce_motion).into()),
|
||||
RowId::ReduceUiResolution => (
|
||||
None,
|
||||
"Reduce interface resolution",
|
||||
on_off(extra_bool(s, android_keys::REDUCE_UI_RES, false)).into(),
|
||||
),
|
||||
RowId::LibraryView => (
|
||||
None,
|
||||
"Library view",
|
||||
@@ -1131,6 +1145,12 @@ fn detail(id: RowId, platform: crate::platform::Platform) -> &'static str {
|
||||
fades. Also the gentler choice on an OLED, where a still field can sit for \
|
||||
hours."
|
||||
}
|
||||
RowId::ReduceUiResolution => {
|
||||
"Draws the menus at 1080p and lets the display scale them up. Text goes a \
|
||||
little softer; the console gets much smoother on a 4K TV or projector, whose \
|
||||
graphics chip is far slower than the panel in front of it. Nothing about a \
|
||||
stream changes — this is the interface only."
|
||||
}
|
||||
RowId::LibraryView => {
|
||||
"Shelf shows one cover at a time, big. Grid shows about eighteen at once — \
|
||||
for when you already know what you are looking for. The library's own bar \
|
||||
@@ -1396,6 +1416,9 @@ fn adjust(id: RowId, delta: i32, wrap: bool, ctx: &mut Ctx) -> bool {
|
||||
step_option(cur, all.len(), delta, wrap).map(|i| s.ui_palette = all[i].id.to_string())
|
||||
}
|
||||
RowId::ReduceMotion => toggle(&mut s.reduce_motion, delta, wrap),
|
||||
RowId::ReduceUiResolution => {
|
||||
toggle_extra(s, android_keys::REDUCE_UI_RES, false, delta, wrap)
|
||||
}
|
||||
RowId::LibraryView => {
|
||||
let all = &crate::library::LibraryView::ALL;
|
||||
let cur = crate::library::LibraryView::parse(&s.library_view);
|
||||
@@ -2155,6 +2178,9 @@ pub(super) mod tests {
|
||||
RowId::Sc2Passthrough,
|
||||
RowId::DsCapture,
|
||||
RowId::Controllers,
|
||||
// Between the Input tab's rows and the rest of Interface: this one sits under
|
||||
// Reduce motion, which is earlier in that tab than the console-UI switch.
|
||||
RowId::ReduceUiResolution,
|
||||
RowId::GamepadUi,
|
||||
RowId::GamepadUiMode,
|
||||
RowId::Licenses,
|
||||
@@ -2250,11 +2276,12 @@ pub(super) mod tests {
|
||||
// 2026-08 sweep found them bridged but unreachable) later passes added, minus the
|
||||
// game-library toggle: this screen never read it, and the library is offered on any
|
||||
// paired host now.
|
||||
// 35 desktop rows + the nine Android-only ones (design android-skia-console-port.md
|
||||
// D3): seven `extra`-backed settings and two platform-screen action rows.
|
||||
assert_eq!(seen.len(), 44, "{seen:?}");
|
||||
// 35 desktop rows + the ten Android-only ones (design android-skia-console-port.md
|
||||
// D3): eight `extra`-backed settings and two platform-screen action rows.
|
||||
assert_eq!(seen.len(), 45, "{seen:?}");
|
||||
assert!(seen.contains(&RowId::Palette));
|
||||
assert!(seen.contains(&RowId::ReduceMotion));
|
||||
assert!(seen.contains(&RowId::ReduceUiResolution));
|
||||
assert!(seen.contains(&RowId::AudioFormat));
|
||||
// The catalog rows belong to the trailing tab, which builds them at render time.
|
||||
assert!(TABS[PROFILES_TAB].1.is_empty());
|
||||
|
||||
@@ -163,8 +163,19 @@ impl Shell {
|
||||
let bw = lead + tw + pad_x;
|
||||
let bx = (w - bw) / 2.0;
|
||||
let by = h - BOTTOM_BAND * k - bh - 8.0 * k + (1.0 - slide) * 12.0 * k;
|
||||
canvas.save_layer_alpha_f(None, alpha);
|
||||
let rect = Rect::from_xywh(bx as f32, by as f32, bw as f32, bh as f32);
|
||||
// BOUNDED to the pill. Unbounded, `save_layer` allocates an offscreen the size of
|
||||
// the whole SURFACE and composites it back — on a 4K TV that is a 33 MB render
|
||||
// target raised and torn down every frame, for four seconds, to fade a 34 dp pill
|
||||
// (and on a box whose whole Skia budget is 64 MB, it evicts real work to do it).
|
||||
//
|
||||
// Everything drawn inside is inside `rect`: the pill fill, `theme::panel`'s
|
||||
// hairline ON that rect, the kind mark centred in it, and text that ends a `pad_x`
|
||||
// short of its right edge. There is no blur to reach further, so the outset is
|
||||
// slack for the stroke rather than a computed reach — `screens::home` needs 36 k
|
||||
// for the same layer only because it wraps a σ = 10 k halo.
|
||||
let bounds = rect.with_outset((12.0 * k as f32, 12.0 * k as f32));
|
||||
canvas.save_layer_alpha_f(Some(bounds), alpha);
|
||||
canvas.draw_rrect(
|
||||
skia_safe::RRect::new_rect_xy(rect, (bh / 2.0) as f32, (bh / 2.0) as f32),
|
||||
&fill(crate::theme::shade(0.6)),
|
||||
|
||||
@@ -67,6 +67,8 @@ impl Shell {
|
||||
}
|
||||
None => dt,
|
||||
};
|
||||
// The shaped-paragraph cache's clock, before anything asks it to draw.
|
||||
fonts.begin_frame();
|
||||
self.sync();
|
||||
// Publish the palette's ink before ANYTHING draws — every widget, glyph and panel in
|
||||
// the crate reads it (see `theme::set_ink`), so a frame that skipped this would paint
|
||||
@@ -80,10 +82,14 @@ impl Shell {
|
||||
crate::theme::set_reduce_motion(reduce);
|
||||
self.pads = pads.to_vec();
|
||||
self.glyphs = GlyphStyle::from_pref(pad_pref);
|
||||
self.chip = Some(pad.map_or_else(
|
||||
|| "No controller — keyboard works too".to_string(),
|
||||
str::to_owned,
|
||||
));
|
||||
// Compared before it is rebuilt: this string changes when someone plugs a controller
|
||||
// in, and was being re-allocated 60 times a second to say so. (`pads` above is left
|
||||
// alone — it is at most a handful of small structs, and `PadInfo` would have to grow a
|
||||
// `PartialEq` in another crate to be worth the same treatment.)
|
||||
let chip = pad.unwrap_or("No controller — keyboard works too");
|
||||
if self.chip.as_deref() != Some(chip) {
|
||||
self.chip = Some(chip.to_owned());
|
||||
}
|
||||
|
||||
let (full_w, full_h) = (f64::from(viewport.width), f64::from(viewport.height));
|
||||
let ins = viewport.insets;
|
||||
@@ -353,7 +359,26 @@ impl LayerEnv<'_> {
|
||||
scale: f64,
|
||||
) -> Vec<(crate::glyphs::HintKey, Rect)> {
|
||||
let canvas = self.canvas;
|
||||
canvas.save_layer_alpha_f(None, alpha.clamp(0.0, 1.0) as f32);
|
||||
// Only RAISE the layer when it carries something. A settled screen is painted at full
|
||||
// alpha, unscaled and unslid, and an unbounded `save_layer` allocates an offscreen the
|
||||
// size of the whole SURFACE and composites it back — so the console was paying for one
|
||||
// full-screen offscreen on every frame it sat still, to apply an alpha of 1. Skia does
|
||||
// not elide it either: `SkCanvas::saveLayerAlphaf` forwards alpha ≥ 1 straight to
|
||||
// `saveLayer(bounds, nullptr)`, whose only early-out is an empty clip.
|
||||
//
|
||||
// Dropping the layer is pixel-identical rather than merely close: nothing in this crate
|
||||
// draws with a blend mode other than `SrcOver`, and `SrcOver` is associative, so
|
||||
// compositing the draws into a transparent layer and then over the backdrop lands on
|
||||
// exactly the value drawing them straight onto the backdrop does. (It is also why the
|
||||
// text stays grayscale-AA — no LCD subpixel text to gain or lose an isolation.) Same
|
||||
// reasoning `screens::home` already bounds its per-tile layer by.
|
||||
let layered = alpha < 0.999 || (scale - 1.0).abs() > 0.001 || dy.abs() > 0.001;
|
||||
if layered {
|
||||
canvas.save_layer_alpha_f(None, alpha.clamp(0.0, 1.0) as f32);
|
||||
} else {
|
||||
// Still a save: the transform below is undone by the same `restore`.
|
||||
canvas.save();
|
||||
}
|
||||
canvas.translate((0.0, dy as f32));
|
||||
let (cx, cy) = ((self.w / 2.0) as f32, (self.h / 2.0) as f32);
|
||||
canvas.translate((cx, cy));
|
||||
|
||||
@@ -7,12 +7,15 @@
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use skia_safe::textlayout::{
|
||||
FontCollection, ParagraphBuilder, ParagraphStyle, TextAlign, TextStyle, TypefaceFontProvider,
|
||||
FontCollection, Paragraph, ParagraphBuilder, ParagraphStyle, TextAlign, TextStyle,
|
||||
TypefaceFontProvider,
|
||||
};
|
||||
use skia_safe::{
|
||||
gradient, Canvas, Color4f, Font, FontMgr, FontStyle, MaskFilter, Paint, PathEffect, Point,
|
||||
RRect, Rect, TileMode, Typeface,
|
||||
};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
|
||||
// --- Paint ----------------------------------------------------------------------------------
|
||||
|
||||
@@ -396,9 +399,16 @@ pub(crate) fn panel_highlight(canvas: &Canvas, rect: Rect, corner: f32, k: f32)
|
||||
),
|
||||
None,
|
||||
));
|
||||
canvas.draw_rrect(RRect::new_rect_xy(inset, corner * k, corner * k), &p);
|
||||
// Concentric, the same rule the halo states: pulled in by half a unit, so the radius
|
||||
// comes in by half a unit too or the lit edge crosses the panel's own corner arc.
|
||||
let r = ((corner - 0.5) * k).max(0.0);
|
||||
canvas.draw_rrect(RRect::new_rect_xy(inset, r, r), &p);
|
||||
}
|
||||
|
||||
/// How far [`focus_halo`] is grown past the card on every side, in design units. Both the
|
||||
/// rect AND the corner radius take it — see the draw there.
|
||||
const HALO_OUTSET: f32 = 4.0;
|
||||
|
||||
/// An accent-tinted glow under the focused card — the palette-aware mark that says "this
|
||||
/// one" from across a room, where a 2 % scale difference says nothing at all. Drawn behind
|
||||
/// [`drop_shadow`], and only ever for the ONE focused tile, so it costs a single extra
|
||||
@@ -439,8 +449,13 @@ pub(crate) fn focus_halo(canvas: &Canvas, rect: Rect, corner: f32, k: f32, f: f3
|
||||
// it overran the coverflow's 58 dp focused-to-neighbour gap, and since the strip paints
|
||||
// farthest-first the focused card's corona landed on top of its neighbours — which is
|
||||
// what made every card look like it was glowing.
|
||||
let spread = rect.with_outset((4.0 * k, 4.0 * k));
|
||||
canvas.draw_rrect(RRect::new_rect_xy(spread, corner * k, corner * k), &p);
|
||||
let spread = rect.with_outset((HALO_OUTSET * k, HALO_OUTSET * k));
|
||||
// Concentric: a shape grown by `d` on every side keeps its corners parallel to the
|
||||
// original's only if its radius grows by `d` too (the two arcs then share a centre).
|
||||
// Reusing the card's own radius left the halo squarer than the card it sits under, so
|
||||
// it read as a misaligned outline at the four corners and a clean glow along the edges.
|
||||
let r = (corner + HALO_OUTSET) * k;
|
||||
canvas.draw_rrect(RRect::new_rect_xy(spread, r, r), &p);
|
||||
}
|
||||
|
||||
pub(crate) fn drop_shadow(canvas: &Canvas, rect: Rect, corner: f32, k: f32, alpha: f32) {
|
||||
@@ -509,7 +524,7 @@ pub(crate) const EDGE_INSET: f64 = 24.0;
|
||||
// --- Typography ---------------------------------------------------------------------------
|
||||
|
||||
/// Geist weights the console uses (matching the Apple client's `.geist(size, weight)`).
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub(crate) enum W {
|
||||
Regular,
|
||||
Medium,
|
||||
@@ -526,6 +541,111 @@ pub(crate) struct Fonts {
|
||||
semibold: Typeface,
|
||||
bold: Typeface,
|
||||
collection: FontCollection,
|
||||
/// Shaped paragraphs, keyed by everything that shapes one ([`ParaKey`]).
|
||||
///
|
||||
/// `Paragraph::layout` runs the whole shaper — HarfBuzz, line breaking, font fallback —
|
||||
/// and the shell re-built every paragraph on screen from scratch EVERY frame, which on a
|
||||
/// TV box is the largest CPU cost in the frame. Position is deliberately not part of the
|
||||
/// key (`paint` takes it), so one shaped paragraph serves a string wherever it moves to:
|
||||
/// a scrolling shelf and a screen transition both re-use it rather than re-shaping.
|
||||
///
|
||||
/// `RefCell` because every draw path here takes `&self` and the console's shell is
|
||||
/// single-threaded by construction (one render thread owns it on all three ABIs).
|
||||
paragraphs: RefCell<HashMap<ParaKey, Cached>>,
|
||||
/// The frame counter [`Fonts::begin_frame`] bumps — the cache's liveness clock.
|
||||
frame: Cell<u64>,
|
||||
}
|
||||
|
||||
/// The three paragraph shapes the console draws. A single tag rather than a loose
|
||||
/// `(TextAlign, Option<usize>)` pair because it is half of a hash key, and because those two
|
||||
/// were never independent — every call site picks one of these three.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
enum Para {
|
||||
/// Centred, wrapping freely.
|
||||
Centered,
|
||||
/// Left-aligned, wrapping freely.
|
||||
Leading,
|
||||
/// Left-aligned, clamped to one ellipsized line.
|
||||
Heading,
|
||||
}
|
||||
|
||||
impl Para {
|
||||
/// The paragraph style this shape asks for: alignment, and the line clamp if it has one.
|
||||
fn style(self) -> (TextAlign, Option<usize>) {
|
||||
match self {
|
||||
Para::Centered => (TextAlign::Center, None),
|
||||
Para::Leading => (TextAlign::Left, None),
|
||||
Para::Heading => (TextAlign::Left, Some(1)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything [`shape`] bakes into a laid-out `Paragraph` — change any of it and the shaped
|
||||
/// result differs, so all of it is in the key.
|
||||
///
|
||||
/// The floats ride as bits: the sizes and widths are all `k`-scaled, so they are never whole
|
||||
/// numbers, and `f64`/`f32` are not `Hash`. Bit equality is the right test anyway — the same
|
||||
/// `k` produces the same bits, and a different `k` must re-shape.
|
||||
#[derive(PartialEq, Eq, Hash)]
|
||||
struct ParaKey {
|
||||
text: String,
|
||||
kind: Para,
|
||||
weight: W,
|
||||
size: u64,
|
||||
max_w: u32,
|
||||
/// ARGB, as `[a, r, g, b]`.
|
||||
color: [u8; 4],
|
||||
}
|
||||
|
||||
/// One shaped paragraph and the frame it was last drawn on.
|
||||
struct Cached {
|
||||
para: Paragraph,
|
||||
used: u64,
|
||||
}
|
||||
|
||||
/// How many shaped paragraphs stay resident before the cold ones are dropped. A screen draws
|
||||
/// well under this; the ceiling exists for the library, where paging a large catalogue walks
|
||||
/// through thousands of titles and every one of them would otherwise be kept forever.
|
||||
const PARA_CACHE_MAX: usize = 512;
|
||||
|
||||
/// Build and lay out one paragraph — the shaping [`Fonts::draw_paragraph`]'s cache exists to
|
||||
/// do exactly once per distinct key.
|
||||
///
|
||||
/// A free function rather than a method because the cache hands it a `&ParaKey` borrowed out
|
||||
/// of the map it is inserting into, which rules out holding `&self` across the call.
|
||||
fn shape(collection: &FontCollection, key: &ParaKey) -> Paragraph {
|
||||
let (align, clamp) = key.kind.style();
|
||||
let mut style = ParagraphStyle::new();
|
||||
style.set_text_align(align);
|
||||
if let Some(lines) = clamp {
|
||||
style.set_max_lines(lines);
|
||||
style.set_ellipsis("\u{2026}");
|
||||
}
|
||||
let mut ts = TextStyle::new();
|
||||
ts.set_font_families(&["Geist"]);
|
||||
ts.set_font_size(f64::from_bits(key.size) as f32);
|
||||
let [a, r, g, b] = key.color;
|
||||
ts.set_color(skia_safe::Color::from_argb(a, r, g, b));
|
||||
ts.set_font_style(match key.weight {
|
||||
W::Regular => FontStyle::normal(),
|
||||
W::Medium => FontStyle::new(
|
||||
skia_safe::font_style::Weight::MEDIUM,
|
||||
skia_safe::font_style::Width::NORMAL,
|
||||
skia_safe::font_style::Slant::Upright,
|
||||
),
|
||||
W::SemiBold => FontStyle::new(
|
||||
skia_safe::font_style::Weight::SEMI_BOLD,
|
||||
skia_safe::font_style::Width::NORMAL,
|
||||
skia_safe::font_style::Slant::Upright,
|
||||
),
|
||||
W::Bold => FontStyle::bold(),
|
||||
});
|
||||
style.set_text_style(&ts);
|
||||
let mut builder = ParagraphBuilder::new(&style, collection.clone());
|
||||
builder.add_text(&key.text);
|
||||
let mut p = builder.build();
|
||||
p.layout(f32::from_bits(key.max_w));
|
||||
p
|
||||
}
|
||||
|
||||
/// The Geist faces ride in the binary — the console must look right on a bare gamescope
|
||||
@@ -562,6 +682,8 @@ pub(crate) fn build_fonts() -> Result<Fonts> {
|
||||
semibold,
|
||||
bold,
|
||||
collection,
|
||||
paragraphs: RefCell::new(HashMap::new()),
|
||||
frame: Cell::new(0),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -629,50 +751,59 @@ impl Fonts {
|
||||
}
|
||||
}
|
||||
|
||||
/// `clamp` caps the paragraph at that many lines and ellipsizes what doesn't fit; `None`
|
||||
/// wraps freely. A heading has to clamp — an over-long one used to grow DOWNWARD into the
|
||||
/// screen's content, which is why both other clients pin theirs to one line.
|
||||
/// Start a frame — the paragraph cache's clock. Anything not drawn on this frame or the
|
||||
/// one before it becomes a candidate for eviction, so the live set is exactly "what the
|
||||
/// last two frames drew". The shell calls this once per `render_in`.
|
||||
pub(crate) fn begin_frame(&self) {
|
||||
self.frame.set(self.frame.get().wrapping_add(1));
|
||||
}
|
||||
|
||||
/// Draw a shaped paragraph, building and laying it out only the first time this exact
|
||||
/// (text, shape, weight, size, width, colour) is asked for — see [`Fonts::paragraphs`].
|
||||
/// `at` is the paragraph's TOP-LEFT, and is deliberately not part of the key.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn paragraph(
|
||||
fn draw_paragraph(
|
||||
&self,
|
||||
canvas: &Canvas,
|
||||
text: &str,
|
||||
kind: Para,
|
||||
w: W,
|
||||
size: f64,
|
||||
color: Color4f,
|
||||
align: TextAlign,
|
||||
max_w: f64,
|
||||
clamp: Option<usize>,
|
||||
) -> skia_safe::textlayout::Paragraph {
|
||||
let mut style = ParagraphStyle::new();
|
||||
style.set_text_align(align);
|
||||
if let Some(lines) = clamp {
|
||||
style.set_max_lines(lines);
|
||||
style.set_ellipsis("\u{2026}");
|
||||
}
|
||||
let mut ts = TextStyle::new();
|
||||
ts.set_font_families(&["Geist"]);
|
||||
ts.set_font_size(size as f32);
|
||||
ts.set_color(color.to_color());
|
||||
ts.set_font_style(match w {
|
||||
W::Regular => FontStyle::normal(),
|
||||
W::Medium => FontStyle::new(
|
||||
skia_safe::font_style::Weight::MEDIUM,
|
||||
skia_safe::font_style::Width::NORMAL,
|
||||
skia_safe::font_style::Slant::Upright,
|
||||
),
|
||||
W::SemiBold => FontStyle::new(
|
||||
skia_safe::font_style::Weight::SEMI_BOLD,
|
||||
skia_safe::font_style::Width::NORMAL,
|
||||
skia_safe::font_style::Slant::Upright,
|
||||
),
|
||||
W::Bold => FontStyle::bold(),
|
||||
at: Point,
|
||||
) {
|
||||
let frame = self.frame.get();
|
||||
// ponytail: the key owns its text, so a HIT still costs one small `String` allocation
|
||||
// where a borrowed-key lookup would cost none. Deliberate — it is a rounding error
|
||||
// against the shape it replaces, and the alternatives (hash-only keys, `hashbrown`'s
|
||||
// raw entry) trade a real collision risk or a dependency for it. Revisit only if a
|
||||
// profile ever puts this line on the board.
|
||||
let key = ParaKey {
|
||||
text: text.to_owned(),
|
||||
kind,
|
||||
weight: w,
|
||||
size: size.to_bits(),
|
||||
max_w: (max_w as f32).to_bits(),
|
||||
color: {
|
||||
// The 8-bit ARGB the paragraph actually bakes, not the `Color4f` it came
|
||||
// from — two float colours that round to the same pixel share an entry.
|
||||
let c = color.to_color();
|
||||
[c.a(), c.r(), c.g(), c.b()]
|
||||
},
|
||||
};
|
||||
let mut cache = self.paragraphs.borrow_mut();
|
||||
let entry = cache.entry(key).or_insert_with_key(|k| Cached {
|
||||
para: shape(&self.collection, k),
|
||||
used: frame,
|
||||
});
|
||||
style.set_text_style(&ts);
|
||||
let mut b = ParagraphBuilder::new(&style, self.collection.clone());
|
||||
b.add_text(text);
|
||||
let mut p = b.build();
|
||||
p.layout(max_w as f32);
|
||||
p
|
||||
entry.used = frame;
|
||||
entry.para.paint(canvas, at);
|
||||
// Drop what the last two frames did not draw. Every entry still on screen is
|
||||
// re-stamped above on the frame it appears in, so this only reaps strings that left.
|
||||
if cache.len() > PARA_CACHE_MAX {
|
||||
cache.retain(|_, c| c.used + 1 >= frame);
|
||||
}
|
||||
}
|
||||
|
||||
/// Centered, wrapping paragraph with `y` as its TOP edge (shaping + CJK fallback).
|
||||
@@ -688,8 +819,8 @@ impl Fonts {
|
||||
y: f64,
|
||||
max_w: f64,
|
||||
) {
|
||||
let p = self.paragraph(text, w, size, color, TextAlign::Center, max_w, None);
|
||||
p.paint(canvas, Point::new((cx - max_w / 2.0) as f32, y as f32));
|
||||
let at = Point::new((cx - max_w / 2.0) as f32, y as f32);
|
||||
self.draw_paragraph(canvas, text, Para::Centered, w, size, color, max_w, at);
|
||||
}
|
||||
|
||||
/// [`centered`](Self::centered)'s LEFT-ALIGNED twin: `x` is the text's left edge, `y` its
|
||||
@@ -707,8 +838,8 @@ impl Fonts {
|
||||
y: f64,
|
||||
max_w: f64,
|
||||
) {
|
||||
let p = self.paragraph(text, w, size, color, TextAlign::Left, max_w, None);
|
||||
p.paint(canvas, Point::new(x as f32, y as f32));
|
||||
let at = Point::new(x as f32, y as f32);
|
||||
self.draw_paragraph(canvas, text, Para::Leading, w, size, color, max_w, at);
|
||||
}
|
||||
|
||||
/// A screen's heading: left-aligned at `x`, top edge at `y`, clamped to ONE ellipsized
|
||||
@@ -731,8 +862,8 @@ impl Fonts {
|
||||
y: f64,
|
||||
max_w: f64,
|
||||
) {
|
||||
let p = self.paragraph(text, w, size, color, TextAlign::Left, max_w, Some(1));
|
||||
p.paint(canvas, Point::new(x as f32, y as f32));
|
||||
let at = Point::new(x as f32, y as f32);
|
||||
self.draw_paragraph(canvas, text, Para::Heading, w, size, color, max_w, at);
|
||||
}
|
||||
|
||||
/// A single shaped line, middle-ellipsized to `max_w`, drawn at a baseline. For
|
||||
@@ -758,8 +889,12 @@ impl Fonts {
|
||||
let ell_w = font.measure_str(ell, None).0;
|
||||
let mut fitted = String::new();
|
||||
let mut used = 0.0f32;
|
||||
// The char goes onto the stack to be measured, not into a fresh `String` per character:
|
||||
// this runs for every over-long title on screen, every frame, and the allocation was
|
||||
// the bulk of it. `encode_utf8` writes the same bytes `to_string` would have.
|
||||
let mut buf = [0u8; 4];
|
||||
for ch in text.chars() {
|
||||
let cw = font.measure_str(ch.to_string().as_str(), None).0;
|
||||
let cw = font.measure_str(&*ch.encode_utf8(&mut buf), None).0;
|
||||
if used + cw + ell_w > max_w as f32 {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -367,6 +367,38 @@ fn takeover_state_is_live(state: &TakeoverState) -> bool {
|
||||
|| state.forced_screen_env
|
||||
}
|
||||
|
||||
/// Restart the box's own autologin gaming session(s) after a leftover idle drop-in was swept off
|
||||
/// a host that died holding one ([`restore_takeover_on_startup`]).
|
||||
///
|
||||
/// Gated on the box actually being dark ([`box_session_live`]): if the user is already in game mode
|
||||
/// or on a desktop, the drop-in we removed was inert and bouncing their session would be the bug.
|
||||
/// Only an ACTIVE instance is restarted — under a just-removed idle drop-in, active means "running
|
||||
/// the sleep"; an inactive one is a leftover the display manager will handle on its own.
|
||||
fn hand_back_idled_units_after_crash() {
|
||||
if box_session_live() {
|
||||
return; // something is already drawing — the drop-in was inert
|
||||
}
|
||||
let units: Vec<String> = listed_autologin_units()
|
||||
.into_iter()
|
||||
.filter(|(_, active)| active == "active")
|
||||
.map(|(unit, _)| unit)
|
||||
.collect();
|
||||
if units.is_empty() {
|
||||
return;
|
||||
}
|
||||
tracing::warn!(
|
||||
?units,
|
||||
"gamescope: the box's Game Mode is running the dead host's idle placeholder and its panel \
|
||||
is dark — restarting it"
|
||||
);
|
||||
for unit in &units {
|
||||
if let RestoreVerb::Failed(why) = issue_restore_verb(&["restart", unit]) {
|
||||
tracing::error!(unit, status = %why, "gamescope: could not restart it");
|
||||
}
|
||||
}
|
||||
ensure_box_session_or_escalate(&units);
|
||||
}
|
||||
|
||||
/// On host startup, restore the TV's gaming session if a previous host instance took it over and
|
||||
/// crashed before restoring (`design/gamemode-and-dedicated-sessions.md` A3). Loads the persisted
|
||||
/// [`TakeoverState`] into the statics and schedules a restore after a short reconnect grace (so a
|
||||
@@ -399,6 +431,13 @@ pub fn restore_takeover_on_startup() {
|
||||
"gamescope: removed a leftover idle drop-in from a previous host instance — the box's \
|
||||
own Game Mode session would have started and then done nothing"
|
||||
);
|
||||
// Removing the FILE does not touch the unit RUNNING under it. That unit's `ExecStart` was
|
||||
// replaced with a sleep, so it is `active` and drawing nothing, and nothing below will
|
||||
// restart it: the takeover file may be absent, unparseable, or not `takeover_state_is_live`
|
||||
// — and all three of those exits used to leave the box sitting on a dark panel with its
|
||||
// Game Mode "running". A host killed mid-stream (SIGKILL, OOM, a yanked update) lands
|
||||
// exactly there, and on glass it is indistinguishable from broken hardware. Hand it back.
|
||||
hand_back_idled_units_after_crash();
|
||||
}
|
||||
let Ok(bytes) = std::fs::read(takeover_state_path()) else {
|
||||
return; // no takeover file — clean start
|
||||
@@ -2984,6 +3023,48 @@ fn replay_switch_under_restored_dm(dm: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The box's autologin gaming instances and their ACTIVE state, as `(unit, active)` pairs — the
|
||||
/// `--plain` columns are UNIT LOAD ACTIVE SUB DESCRIPTION, so the state is the third.
|
||||
///
|
||||
/// An unanswered query reads as "none listed", which is the safe direction for both callers: the
|
||||
/// takeover then frees nothing rather than killing a session it could not see properly, and the
|
||||
/// crash hand-back restarts nothing rather than bouncing one.
|
||||
fn listed_autologin_units() -> Vec<(String, String)> {
|
||||
let Ok(out) = crate::proc::output_within(
|
||||
Command::new("systemctl").args([
|
||||
"--user",
|
||||
"list-units",
|
||||
"--type=service",
|
||||
"--all",
|
||||
"--no-legend",
|
||||
"--plain",
|
||||
"gamescope-session-plus@*.service",
|
||||
]),
|
||||
UNIT_QUERY_BUDGET,
|
||||
) else {
|
||||
return Vec::new();
|
||||
};
|
||||
parse_listed_units(&String::from_utf8_lossy(&out.stdout))
|
||||
}
|
||||
|
||||
/// [`listed_autologin_units`]'s parser (the unit-testable core). Which column the ACTIVE state is
|
||||
/// in decides whether the takeover can tell a live gaming session from a dead leftover, and
|
||||
/// getting that wrong is silent in both directions — a live session read as dead leaves Steam
|
||||
/// holding the instance our own launch then collides with, and a dead one read as live idles a
|
||||
/// session nobody was in.
|
||||
fn parse_listed_units(stdout: &str) -> Vec<(String, String)> {
|
||||
stdout
|
||||
.lines()
|
||||
.filter_map(|l| {
|
||||
let mut cols = l.split_whitespace();
|
||||
let unit = cols.next()?;
|
||||
let active = cols.nth(1).unwrap_or("");
|
||||
(unit.starts_with("gamescope-session-plus@") && unit.ends_with(".service"))
|
||||
.then(|| (unit.to_string(), active.to_string()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Stop every autologin gaming-mode session (`gamescope-session-plus@*.service`) so its
|
||||
/// single-instance Steam is free for our own host-managed session. Records the units so
|
||||
/// [`schedule_restore_tv_session`] can restart them on disconnect. Our own session is the transient
|
||||
@@ -3011,33 +3092,9 @@ fn replay_switch_under_restored_dm(dm: &str) {
|
||||
/// The ORDER is therefore load-bearing and not a style choice: stop the DM, bail if it did not
|
||||
/// land, and only then mask. A mask laid before a stop that never arrives is the storm.
|
||||
fn stop_autologin_sessions() -> Result<()> {
|
||||
let Ok(out) = crate::proc::output_within(
|
||||
Command::new("systemctl").args([
|
||||
"--user",
|
||||
"list-units",
|
||||
"--type=service",
|
||||
"--all",
|
||||
"--no-legend",
|
||||
"--plain",
|
||||
"gamescope-session-plus@*.service",
|
||||
]),
|
||||
UNIT_QUERY_BUDGET,
|
||||
) else {
|
||||
return Ok(());
|
||||
};
|
||||
// `(unit, ACTIVE state)` — the `--plain` columns are UNIT LOAD ACTIVE SUB DESCRIPTION.
|
||||
let listed: Vec<(String, String)> = String::from_utf8_lossy(&out.stdout)
|
||||
.lines()
|
||||
.filter_map(|l| {
|
||||
let mut cols = l.split_whitespace();
|
||||
let unit = cols.next()?;
|
||||
let active = cols.nth(1).unwrap_or("");
|
||||
(unit.starts_with("gamescope-session-plus@") && unit.ends_with(".service"))
|
||||
.then(|| (unit.to_string(), active.to_string()))
|
||||
})
|
||||
.collect();
|
||||
let listed = listed_autologin_units();
|
||||
if listed.is_empty() {
|
||||
return Ok(()); // nothing autologged in — Steam is already free
|
||||
return Ok(()); // nothing autologged in (or the query failed) — Steam is already free
|
||||
}
|
||||
let dm = display_manager_unit();
|
||||
// Only a LIVE instance holds Steam / justifies touching the DM. A loaded-but-inactive
|
||||
@@ -3439,7 +3496,13 @@ pub fn restore_takeover_now() {
|
||||
}
|
||||
*PENDING_RESTORE.lock().unwrap_or_else(|e| e.into_inner()) = None; // doing it right here
|
||||
tracing::info!("gamescope: host is shutting down — restoring the box's own session first");
|
||||
do_restore_tv_session();
|
||||
// `verify: false` — the escalation ladder waits up to a minute, and this runs inside
|
||||
// `native.rs`'s 20 s `SHUTDOWN_RESTORE_GRACE`, after which `exit(0)` runs no destructors.
|
||||
// Spending that grace watching instead of restoring would COST the hand-back, not check it.
|
||||
// The next host start is what covers a shutdown that left the box dark
|
||||
// ([`restore_takeover_on_startup`], which now hands the box back rather than only sweeping the
|
||||
// drop-in off it).
|
||||
do_restore_tv_session(false);
|
||||
}
|
||||
|
||||
/// What a bounded `systemctl --user` lifecycle verb on the RESTORE path actually did. Three states,
|
||||
@@ -3503,11 +3566,168 @@ fn connected_connector_under(base: &std::path::Path) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// How long a hand-back waits for the box to show something on its own panel before it starts
|
||||
/// escalating. Generous on purpose: the unit's `ExecStart` is a whole gamescope + Steam start, and
|
||||
/// on a cold box that is not quick — while a false escalation costs the user a session bounce.
|
||||
const HANDBACK_GRACE: Duration = Duration::from_secs(25);
|
||||
|
||||
/// How long each escalation rung gets. Shorter than [`HANDBACK_GRACE`]: by the time a rung runs,
|
||||
/// the ordinary start has already had its full grace and not delivered.
|
||||
const HANDBACK_RUNG_GRACE: Duration = Duration::from_secs(15);
|
||||
|
||||
/// Poll slice for the two waits above.
|
||||
const HANDBACK_POLL: Duration = Duration::from_millis(500);
|
||||
|
||||
/// Is ANYTHING driving the box's own panel right now — its game mode, or a desktop it switched to?
|
||||
///
|
||||
/// [`super::detect_active_session`] answers precisely the question the symptom asks: it reports the
|
||||
/// running compositor of our uid, and [`super::ActiveKind::None`] means nothing is drawing
|
||||
/// anywhere. Only sound AFTER `stop_session(SESSION_UNIT)` has killed our own managed session —
|
||||
/// that kill is a synchronous SIGKILL ([`kill_unit`]), so by the restore's escalation point our
|
||||
/// gamescope cannot still be answering for the box.
|
||||
fn box_session_live() -> bool {
|
||||
super::detect_active_session().kind != super::ActiveKind::None
|
||||
}
|
||||
|
||||
/// Poll [`box_session_live`] until it is true or `grace` runs out. [`HandbackWait::Superseded`]
|
||||
/// means a client reconnected and took the box over again — the hand-back we were checking is moot,
|
||||
/// and every remedy below would now be fighting a live stream for the box's session.
|
||||
enum HandbackWait {
|
||||
Live,
|
||||
Superseded,
|
||||
TimedOut,
|
||||
}
|
||||
|
||||
fn wait_for_box_session(grace: Duration) -> HandbackWait {
|
||||
let deadline = Instant::now() + grace;
|
||||
loop {
|
||||
if takeover_live() {
|
||||
return HandbackWait::Superseded;
|
||||
}
|
||||
if box_session_live() {
|
||||
return HandbackWait::Live;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return HandbackWait::TimedOut;
|
||||
}
|
||||
std::thread::sleep(HANDBACK_POLL);
|
||||
}
|
||||
}
|
||||
|
||||
/// **The hand-back's last line of defence for a dark panel**, and the only part of this file that
|
||||
/// checks whether the restore it just performed actually WORKED.
|
||||
///
|
||||
/// Everything above issues a lifecycle verb and reports what systemd said about the JOB. That is
|
||||
/// not the same question as "does the box show a picture again", and the gap between the two is
|
||||
/// where every "my screen stays black after disconnecting" report lives — including ones whose
|
||||
/// trigger nobody has reproduced. So stop inferring the outcome and measure it: if nothing is
|
||||
/// driving the panel a full [`HANDBACK_GRACE`] after the hand-back, climb a ladder of remedies,
|
||||
/// each of which is a mechanism measured on both distro families (Bazzite `44.20260818`, Nobara
|
||||
/// f44, 2026-08-22), and say loudly at every rung what is happening.
|
||||
///
|
||||
/// 1. **`stop` the autologin unit.** Its login session's script is parked on
|
||||
/// `systemctl --user --wait start <unit>` (verified on both images), so stopping the unit
|
||||
/// releases that wait, the session exits, and `Relogin=true` logs straight back in — starting
|
||||
/// the unit inside a fresh login session with a seat. `stop`, never `restart`: a restart does
|
||||
/// NOT release the parked waiter (measured), which is exactly why it cannot rescue a box the
|
||||
/// ordinary restart already failed to bring back.
|
||||
/// 2. **Restart the display manager.** What the pre-0.31.0 takeover did on every disconnect, and
|
||||
/// proven to return the box to game mode. Needs privilege, so it can honestly fail.
|
||||
/// 3. **`PUNKTFUNK_RECOVER_SESSION_CMD`**, then an ERROR naming the command a human must run.
|
||||
///
|
||||
/// **Detached**, and that is not incidental. The restore runs under [`RESTORE_FLIGHT`], which a
|
||||
/// reconnecting client must take before it can re-take the box; watching for up to a minute while
|
||||
/// holding it would put that whole wait in front of every reconnect. So the caller fires this and
|
||||
/// returns, and the watcher stands down by itself the moment [`takeover_live`] says a new takeover
|
||||
/// armed — the box belongs to that stream now, and a remedy fired into it would be the bug.
|
||||
/// Call it AFTER `clear_takeover()`, or the very first poll reads our own finished takeover as a
|
||||
/// new one and stands down immediately.
|
||||
///
|
||||
/// A box that was already fine costs one [`box_session_live`] call and the thread exits.
|
||||
fn ensure_box_session_or_escalate(units: &[String]) {
|
||||
let units: Vec<String> = units.to_vec();
|
||||
std::thread::spawn(move || handback_watch(&units));
|
||||
}
|
||||
|
||||
fn handback_watch(units: &[String]) {
|
||||
match wait_for_box_session(HANDBACK_GRACE) {
|
||||
HandbackWait::Live => {
|
||||
tracing::info!(
|
||||
"gamescope: the box is driving its own panel again — hand-back complete"
|
||||
);
|
||||
return;
|
||||
}
|
||||
HandbackWait::Superseded => return,
|
||||
HandbackWait::TimedOut => {}
|
||||
}
|
||||
tracing::warn!(
|
||||
secs = HANDBACK_GRACE.as_secs(),
|
||||
units = ?units,
|
||||
"gamescope: NOTHING is driving the box's panel {}s after the hand-back — its screen is \
|
||||
dark. Escalating: stopping the autologin unit so the display manager relogins into a \
|
||||
session with a seat",
|
||||
HANDBACK_GRACE.as_secs()
|
||||
);
|
||||
// Rung 1 — release the login session's parked `--wait start` and let the DM relogin.
|
||||
for unit in units {
|
||||
if let RestoreVerb::Failed(why) = issue_restore_verb(&["stop", unit]) {
|
||||
tracing::warn!(unit, status = %why, "gamescope: could not stop the autologin unit");
|
||||
}
|
||||
}
|
||||
match wait_for_box_session(HANDBACK_RUNG_GRACE) {
|
||||
HandbackWait::Live => {
|
||||
tracing::info!(
|
||||
"gamescope: the display manager relogged the box into its own session — panel back"
|
||||
);
|
||||
return;
|
||||
}
|
||||
HandbackWait::Superseded => return,
|
||||
HandbackWait::TimedOut => {}
|
||||
}
|
||||
// Rung 2 — put the display manager itself through a restart.
|
||||
if let Some(dm) = display_manager_unit() {
|
||||
tracing::warn!(
|
||||
%dm,
|
||||
"gamescope: the box is still dark — restarting its display manager"
|
||||
);
|
||||
match restore_display_manager(&dm) {
|
||||
Ok(()) => match wait_for_box_session(HANDBACK_RUNG_GRACE) {
|
||||
HandbackWait::Live => {
|
||||
tracing::info!(%dm, "gamescope: the display manager brought the box back");
|
||||
return;
|
||||
}
|
||||
HandbackWait::Superseded => return,
|
||||
HandbackWait::TimedOut => {}
|
||||
},
|
||||
Err(why) => tracing::warn!(
|
||||
%dm,
|
||||
shape = why.shape(),
|
||||
reason = %why,
|
||||
"gamescope: could not restart the display manager"
|
||||
),
|
||||
}
|
||||
}
|
||||
// Rung 3 — the operator's own escape hatch, then say what is left to do by hand.
|
||||
if crate::try_recover_session() {
|
||||
tracing::warn!(
|
||||
"gamescope: fired PUNKTFUNK_RECOVER_SESSION_CMD to bring the box's session back"
|
||||
);
|
||||
return;
|
||||
}
|
||||
tracing::error!(
|
||||
units = ?units,
|
||||
"gamescope: the box has NO session driving its panel and every automatic remedy failed — \
|
||||
its screen stays dark until someone runs `systemctl --user restart <unit>` for one of \
|
||||
these, or `sudo systemctl restart display-manager.service`. Set \
|
||||
PUNKTFUNK_RECOVER_SESSION_CMD to let the host do this itself"
|
||||
);
|
||||
}
|
||||
|
||||
/// Tear down our host-managed session (freeing Steam) and restart the autologin gaming session(s)
|
||||
/// we stopped on connect — so the TV returns to gaming mode when no one is streaming. Invoked by
|
||||
/// [`start_restore_worker`] once the debounce deadline passes; takes the stopped-unit list so a
|
||||
/// cancelled+reconnected window keeps the list for a later real restore.
|
||||
fn do_restore_tv_session() {
|
||||
fn do_restore_tv_session(verify: bool) {
|
||||
// SteamOS: we reconfigured `gamescope-session.target` headless via a drop-in. Restore = remove
|
||||
// the drop-in + restart the target (back to the physical panel) — unless the user switched to a
|
||||
// desktop session meanwhile, in which case drop the override and leave the desktop alone.
|
||||
@@ -3574,6 +3794,9 @@ fn do_restore_tv_session() {
|
||||
),
|
||||
}
|
||||
clear_takeover(); // A3: consumed — after the restart, not before it
|
||||
if verify {
|
||||
ensure_box_session_or_escalate(&[STEAMOS_SESSION_TARGET.to_string()]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -3699,14 +3922,14 @@ fn do_restore_tv_session() {
|
||||
}
|
||||
// (The idle drop-in is already gone — removed above every early return, so the restarts
|
||||
// below bring the box's real session back rather than another idle one.)
|
||||
for unit in units {
|
||||
for unit in &units {
|
||||
// Checked, not discarded: this call and the SteamOS `restart` above were the two places
|
||||
// that logged an unconditional success over a thrown-away exit status. A `--user start`
|
||||
// fails for reasons an operator can act on (the unit is masked, its start limit tripped),
|
||||
// and the DM branch thirty lines up already shows the shape — say what happened.
|
||||
// `restart`, not `start`: the idle takeover leaves the unit ACTIVE, and `start` on an
|
||||
// active unit is a no-op that would report success over a session still running nothing.
|
||||
match issue_restore_verb(&["restart", &unit]) {
|
||||
match issue_restore_verb(&["restart", unit]) {
|
||||
RestoreVerb::Done => tracing::info!(
|
||||
unit,
|
||||
"restored the TV's autologin gaming session (debounce elapsed, no client)"
|
||||
@@ -3731,6 +3954,12 @@ fn do_restore_tv_session() {
|
||||
}
|
||||
}
|
||||
clear_takeover(); // A3: consumed — and only now, with the restarts actually issued
|
||||
// …and CHECK that the restart above actually put a picture back on the box's panel, rather
|
||||
// than trusting the job status to mean that. AFTER `clear_takeover`, which is what makes a
|
||||
// later `takeover_live()` mean "a client reconnected" — see [`ensure_box_session_or_escalate`].
|
||||
if verify {
|
||||
ensure_box_session_or_escalate(&units);
|
||||
}
|
||||
}
|
||||
|
||||
/// Host-lifetime worker that fires a pending [`schedule_restore_tv_session`] once its debounce
|
||||
@@ -3767,7 +3996,10 @@ pub fn start_restore_worker() -> std::sync::Arc<()> {
|
||||
}
|
||||
};
|
||||
if still_due {
|
||||
do_restore_tv_session();
|
||||
// The disconnect restore: verified. This is the path the field reports
|
||||
// are about, it is on a worker thread with no deadline over it, and a box
|
||||
// left dark here stays dark until someone walks up to it.
|
||||
do_restore_tv_session(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5334,12 +5566,12 @@ mod tests {
|
||||
classify_output_size, connected_connector_under, display_manager_unit_under, dm_plan,
|
||||
game_hz, gamescope_output_size, hdr_args, idle_dropin_body, idle_dropin_path,
|
||||
install_idle_dropin, is_steam_launch, mask_unit, missing_flags, mode_mismatch,
|
||||
nested_wrapper_script, our_wsi_layer_dir, plan_bind, release_autologin_mask,
|
||||
remove_idle_dropin, script_hardcodes_gamescope, sentinel_advanced, shape_dedicated_command,
|
||||
switch_ends_mask_window, takeover_state_is_live, unmask_unit, xwayland_refusal_marker,
|
||||
BindOff, BindPlan, BoxOutputSize, DmHelperError, SessionBind, TakeoverState, WsiPlan,
|
||||
AUTOLOGIN_MASKED, DISTRO_GAMESCOPE_PATH, PENDING_RESTORE, RESTORE_FLIGHT,
|
||||
STOPPED_AUTOLOGIN, WSI_OFF_ENV, X11_SOCKET_DIR,
|
||||
nested_wrapper_script, our_wsi_layer_dir, parse_listed_units, plan_bind,
|
||||
release_autologin_mask, remove_idle_dropin, script_hardcodes_gamescope, sentinel_advanced,
|
||||
shape_dedicated_command, switch_ends_mask_window, takeover_state_is_live, unmask_unit,
|
||||
xwayland_refusal_marker, BindOff, BindPlan, BoxOutputSize, DmHelperError, SessionBind,
|
||||
TakeoverState, WsiPlan, AUTOLOGIN_MASKED, DISTRO_GAMESCOPE_PATH, PENDING_RESTORE,
|
||||
RESTORE_FLIGHT, STOPPED_AUTOLOGIN, WSI_OFF_ENV, X11_SOCKET_DIR,
|
||||
};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -5538,6 +5770,39 @@ mod tests {
|
||||
/// drop-in APPENDS the sleep to the box's own session command and both run — the takeover
|
||||
/// would then be fighting the very Steam it set out to free, and nothing on the box would say
|
||||
/// why. Pins the reset, its order, and that the resolved `sleep` is the one that gets run.
|
||||
/// The `--plain` column the ACTIVE state lives in, pinned against real `systemctl --user
|
||||
/// list-units` output from both distro families. Read the wrong column and a live gaming
|
||||
/// session looks dead (Steam stays held, and our launch collides with it) or a dead leftover
|
||||
/// looks live (the takeover idles a session nobody was in) — both silent on glass.
|
||||
#[test]
|
||||
fn listed_units_take_the_active_column_not_the_load_column() {
|
||||
// Bazzite 44.20260818 and Nobara f44, verbatim (unit / LOAD / ACTIVE / SUB / description).
|
||||
let out = "gamescope-session-plus@ogui-steam.service loaded active running Gamescope Session Plus\n\
|
||||
gamescope-session-plus@steam.service loaded inactive dead Gamescope Session Plus\n";
|
||||
assert_eq!(
|
||||
parse_listed_units(out),
|
||||
vec![
|
||||
(
|
||||
"gamescope-session-plus@ogui-steam.service".to_string(),
|
||||
"active".to_string()
|
||||
),
|
||||
(
|
||||
"gamescope-session-plus@steam.service".to_string(),
|
||||
"inactive".to_string()
|
||||
),
|
||||
]
|
||||
);
|
||||
// `loaded` is the LOAD column and must never be mistaken for the state — that is the
|
||||
// off-by-one this pins.
|
||||
assert!(parse_listed_units(out).iter().all(|(_, a)| a != "loaded"));
|
||||
// Anything that is not one of our template's instances is not ours to touch.
|
||||
assert!(
|
||||
parse_listed_units("plasma-plasmashell.service loaded active running Shell\n")
|
||||
.is_empty()
|
||||
);
|
||||
assert!(parse_listed_units("").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_dropin_replaces_exec_start_rather_than_appending() {
|
||||
let body = idle_dropin_body("/usr/bin/sleep");
|
||||
|
||||
@@ -483,7 +483,12 @@ fn gamescope_patch_level() -> u32 {
|
||||
cursor composited into the capture stream"
|
||||
);
|
||||
} else {
|
||||
tracing::debug!(
|
||||
// INFO, not DEBUG: this is the whole reason a box streams SDR, and the branch above
|
||||
// announces the good news at INFO. A field report ("HDR stopped working after the
|
||||
// update") cost a deep dive because the handshake's `capture_supports_hdr=false` was
|
||||
// visible at INFO while the ONE line saying why sat a level below it. Fires once per
|
||||
// process — the answer is cached in `LEVEL`.
|
||||
tracing::info!(
|
||||
bin = %gamescope_bin(),
|
||||
"gamescope has no {PFHDR_MARKER} marker — sessions on this backend stay 8-bit SDR \
|
||||
with a host-composited cursor (install punktfunk-gamescope for HDR)"
|
||||
|
||||
@@ -128,18 +128,31 @@ impl DataPump {
|
||||
// becomes the climb ceiling and slow start does the rest. Old hosts decline (all-zero
|
||||
// reply) or never answer (timeout clears the state so LossReports resume) — either way
|
||||
// the ceiling stays negotiated, exactly the old behavior. PUNKTFUNK_ABR_PROBE=0 opts out.
|
||||
// `PUNKTFUNK_ABR_PROBE_KBPS` lowers the burst target (unset/0/garbage → the 2 Gbps
|
||||
// default): the target is deliberately far above any plausible link so the burst measures
|
||||
// the link and not itself, but on links the burst DISTURBS that backfires — a constrained
|
||||
// Wi-Fi link can black-hole under 2 Gbps (measured on webOS: the probe hitting the 6 s
|
||||
// timeout delayed first video to 14 s, and a "successful" one still reported
|
||||
// send_dropped=20211), and a 2-3 core TV client starves decoding the firehose. An
|
||||
// embedder that caps its own speed test wants this capped to match.
|
||||
// The burst target is DERIVED from `stream_cap_kbps`, not set "far above any plausible
|
||||
// link". It used to be a flat 2 Gbps on that reasoning — the burst must measure the link
|
||||
// and not itself — but the ABR already discards every bit measured above what the session
|
||||
// could use: `set_ceiling` clamps to the stream cap set a few lines up, so everything past
|
||||
// `stream_cap_kbps / 0.7` is thrown away the moment it lands. All that height bought was
|
||||
// bufferbloat for a number nothing reads, and on links the burst DISTURBS it backfires — a
|
||||
// constrained Wi-Fi link can black-hole under 2 Gbps (measured on webOS: the probe hitting
|
||||
// the 6 s timeout delayed first video to 14 s, and a "successful" one still reported
|
||||
// send_dropped=20211; the same shape is reported on a Fire TV Stick 4K Max), and a 2-3
|
||||
// core TV client starves decoding the firehose.
|
||||
//
|
||||
// ×2 is the smallest multiplier that still PROVES the cap: the measured ceiling is
|
||||
// `delivered × 0.7`, so reaching `stream_cap_kbps` needs `delivered ≥ cap × 1.43` and the
|
||||
// rest is margin. Deriving it this way cannot cap anyone — a session whose mode and codec
|
||||
// justify a high ceiling asks for a correspondingly high target by itself, and a mode we
|
||||
// cannot size (`stream_ceiling_kbps` → `u32::MAX`) still gets the old 2 Gbps. It also
|
||||
// fixes webOS and every other constrained client, not just the box that reported it.
|
||||
//
|
||||
// `PUNKTFUNK_ABR_PROBE_KBPS` overrides the target outright (unset/0/garbage → the derived
|
||||
// one). An embedder that caps its own speed test wants this capped to match.
|
||||
let capacity_probe_kbps: u32 = std::env::var("PUNKTFUNK_ABR_PROBE_KBPS")
|
||||
.ok()
|
||||
.and_then(|v| v.trim().parse::<u32>().ok())
|
||||
.filter(|&v| v > 0)
|
||||
.unwrap_or(2_000_000);
|
||||
.unwrap_or_else(|| probe_target_kbps(stream_cap_kbps));
|
||||
const CAPACITY_PROBE_MS: u32 = 800;
|
||||
const CAPACITY_PROBE_DELAY: Duration = Duration::from_secs(2);
|
||||
const CAPACITY_PROBE_TIMEOUT: Duration = Duration::from_secs(6);
|
||||
@@ -154,6 +167,9 @@ impl DataPump {
|
||||
// in; the embedder path had neither, so an unanswered request wedged the report tick and a
|
||||
// finished one left the ABR window anchored before the burst.
|
||||
let mut was_probing = false;
|
||||
// `frames_completed` as the burst began, so the probe-end block below can ask "did ANY
|
||||
// frame survive this burst" rather than only "has one ever arrived" — see there.
|
||||
let mut frames_at_probe_start: u64 = 0;
|
||||
// The window this closes is discarded outright: no LossReport, no standing-latency close,
|
||||
// no ABR feed. Two causes, both of them "this window's signals describe something other
|
||||
// than the link, and one bogus congestion verdict here ends slow start for good":
|
||||
@@ -289,6 +305,24 @@ impl DataPump {
|
||||
last_report = Instant::now();
|
||||
discard_abr_window = true;
|
||||
flush_in_window = false;
|
||||
// …and if the burst swallowed the video with it, re-anchor the decoder. This runs
|
||||
// on EVERY probe end — a successful one, a timed-out one, an embedder "Test
|
||||
// connection" — and the frame-count guard is what makes it a no-op the rest of the
|
||||
// time: a burst the link couldn't hold can take the keyframe down with it, and
|
||||
// then nothing re-requests one, so the client sits on black until some unrelated
|
||||
// recovery path happens to fire. That is the reported Fire TV / webOS black
|
||||
// screen. Compared against the count SNAPSHOTTED at the burst's leading edge
|
||||
// rather than against 0: at startup the two are the same test, but this one also
|
||||
// catches a burst that kills an already-running stream (an embedder speed test
|
||||
// mid-session), which the cumulative counter never could. At most one request per
|
||||
// probe, and it funnels through the control task's coalescer like the other two
|
||||
// emitters in this file, so it cannot IDR-storm.
|
||||
if st.frames_completed == frames_at_probe_start {
|
||||
let _ = ctrl_tx.try_send(CtrlRequest::Keyframe);
|
||||
tracing::warn!(
|
||||
"no frame survived the capacity probe — requested a keyframe to re-anchor"
|
||||
);
|
||||
}
|
||||
}
|
||||
// Arm a watchdog on the leading edge of ANY probe, so a host that silently ignores
|
||||
// `ProbeRequest` (an old build — anticipated, see the capacity-probe timeout below)
|
||||
@@ -296,6 +330,7 @@ impl DataPump {
|
||||
if !was_probing && probe_active {
|
||||
let burst = Duration::from_millis(pump_probe.lock().unwrap().duration_ms as u64);
|
||||
probe_watchdog = Some(Instant::now() + burst + CAPACITY_PROBE_TIMEOUT);
|
||||
frames_at_probe_start = st.frames_completed;
|
||||
}
|
||||
if !probe_active {
|
||||
probe_watchdog = None;
|
||||
@@ -797,6 +832,18 @@ fn should_report_delivery(packets_received: u64, confirmed: &mut bool) -> bool {
|
||||
owed
|
||||
}
|
||||
|
||||
/// The capacity probe's burst target for a session bounded at `stream_cap_kbps`, in kbps — the
|
||||
/// default `PUNKTFUNK_ABR_PROBE_KBPS` overrides. See the probe's comment in the pump for why it is
|
||||
/// derived rather than fixed: `BitrateController::set_ceiling` clamps the measurement to the
|
||||
/// stream cap, so every bit measured above `cap / 0.7` is discarded, and bursting for it only
|
||||
/// buys bufferbloat. ×2 clears that `1.43×` bar with margin.
|
||||
///
|
||||
/// `u32::MAX` in (a mode [`crate::abr::stream_ceiling_kbps`] declines to size) keeps the historic
|
||||
/// 2 Gbps, which is also the ceiling on the whole derivation: this can only ever lower the target.
|
||||
fn probe_target_kbps(stream_cap_kbps: u32) -> u32 {
|
||||
stream_cap_kbps.saturating_mul(2).min(2_000_000)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -836,6 +883,40 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The burst has to be big enough to PROVE the stream cap and no bigger. Anything the burst
|
||||
/// measures above `cap / 0.7` is discarded by `BitrateController::set_ceiling` (pinned by
|
||||
/// `abr::tests::the_stream_bound_clamps_a_learned_ceiling_only`) and paid for in bufferbloat.
|
||||
#[test]
|
||||
fn the_probe_target_proves_the_stream_cap_without_overshooting_it() {
|
||||
// Real modes, from the smallest a session runs to the largest — including 1440p120, the
|
||||
// field session that walked to 657 Mbps and taught the ABR the cap in the first place.
|
||||
for (w, h, hz, codec, depth) in [
|
||||
(1280, 720, 60, crate::quic::CODEC_HEVC, 8),
|
||||
(1920, 1080, 60, crate::quic::CODEC_H264, 8),
|
||||
(2560, 1440, 120, crate::quic::CODEC_HEVC, 8),
|
||||
(3840, 2160, 120, crate::quic::CODEC_HEVC, 10),
|
||||
] {
|
||||
let cap = crate::abr::stream_ceiling_kbps(w, h, hz, codec, depth, 0);
|
||||
let target = probe_target_kbps(cap);
|
||||
// Enough: a link that delivers the whole burst measures `delivered × 0.7`, and that
|
||||
// has to reach the cap or the session can never climb to what its mode allows.
|
||||
assert!(
|
||||
target.saturating_mul(7) / 10 >= cap,
|
||||
"{w}x{h}@{hz}: a {target} kbps burst cannot prove a {cap} kbps cap"
|
||||
);
|
||||
// …and no more: a target that overshoots what the clamp keeps is pure bufferbloat.
|
||||
// (The old flat 2 Gbps overshot 1440p120 by 6×.)
|
||||
assert!(
|
||||
target <= cap.saturating_mul(2),
|
||||
"{w}x{h}@{hz}: {target} kbps chases capacity the clamp discards"
|
||||
);
|
||||
}
|
||||
// A mode `stream_ceiling_kbps` declines to size (`u32::MAX`) keeps the historic 2 Gbps,
|
||||
// which is also the hard ceiling on the derivation — it can only ever lower the target.
|
||||
assert_eq!(probe_target_kbps(u32::MAX), 2_000_000);
|
||||
assert_eq!(probe_target_kbps(1_500_000), 2_000_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pipeline_gap_is_taken_exactly_once() {
|
||||
let slot = AtomicU32::new(0);
|
||||
|
||||
@@ -26,17 +26,26 @@
|
||||
|
||||
use super::{audio_control, audio_probe, minted, pad_endpoint as pe};
|
||||
use anyhow::Result;
|
||||
use windows::Win32::Devices::DeviceAndDriverInstallation::SetupDiEnumDeviceInfo;
|
||||
use windows::Win32::Devices::DeviceAndDriverInstallation::{
|
||||
SetupDiEnumDeviceInfo, SPDRP_HARDWAREID,
|
||||
};
|
||||
|
||||
/// The `Device Parameters` REG_DWORD each punktfunk-minted devnode family stamps on itself. The
|
||||
/// VALUE is what differs per family; presence of the NAME is "this one is ours", which is all a
|
||||
/// sweep needs.
|
||||
const OWNER_MARKERS: [&str; 3] = [
|
||||
pub(crate) const OWNER_MARKERS: [&str; 3] = [
|
||||
pe::PAD_INDEX_VALUE,
|
||||
minted::ROLE_MARKER,
|
||||
audio_probe::PROBE_MARKER,
|
||||
];
|
||||
|
||||
/// The Steam streaming hardware ids every audio devnode this product mints is created with —
|
||||
/// the second half of the ABANDONED-devnode test in [`owned_devnodes`].
|
||||
const MINTED_HWIDS: [&str; 2] = [
|
||||
"ROOT\\SteamStreamingSpeakers",
|
||||
"ROOT\\SteamStreamingMicrophone",
|
||||
];
|
||||
|
||||
/// What one sweep removed. `endpoint_records` is counted separately from `devnodes` because the
|
||||
/// registry half is best-effort by design — see [`delete_endpoint_record`].
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -117,11 +126,91 @@ fn owned_devnodes() -> Result<Vec<String>> {
|
||||
.any(|m| pe::read_devparam_dword(&set, &did, m).is_some())
|
||||
{
|
||||
out.push(inst);
|
||||
continue;
|
||||
}
|
||||
// ABANDONED: `ROOT\MEDIA\NNNN` carrying one of our minting hardware ids but no marker at
|
||||
// all — a devnode registered by a host that died before the marker write landed. It is
|
||||
// still bound and still serving endpoints, so leaving it behind is the "uninstalling
|
||||
// punktfunk left Sound settings full of Punktfunk devices forever" report all over again.
|
||||
//
|
||||
// The instance prefix is what makes this safe, and it is NOT redundant with
|
||||
// [`is_removable_instance`]: Steam's own devnodes carry these very hardware ids and are
|
||||
// ROOT-enumerated too, but live under `ROOT\SteamStreamingSpeakers\*` /
|
||||
// `ROOT\SteamStreamingMicrophone\*`. Only `ROOT\MEDIA\*` can have come from our
|
||||
// `SetupDiCreateDeviceInfoW(… DICD_GENERATE_ID)`.
|
||||
if is_abandoned_mint(
|
||||
&inst,
|
||||
&pe::devnode_multi_sz_prop(&set, &did, SPDRP_HARDWAREID),
|
||||
) {
|
||||
out.push(inst);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The ABANDONED-devnode test, split out from the PnP enumeration so the rule that keeps this
|
||||
/// sweep off VALVE'S OWN devices is checkable without a live devinfo set. See [`owned_devnodes`].
|
||||
fn is_abandoned_mint(instance_id: &str, hwids: &[String]) -> bool {
|
||||
instance_id
|
||||
.to_ascii_uppercase()
|
||||
.starts_with("ROOT\\MEDIA\\")
|
||||
&& MINTED_HWIDS
|
||||
.iter()
|
||||
.any(|want| hwids.iter().any(|h| h.eq_ignore_ascii_case(want)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod abandoned_tests {
|
||||
use super::is_abandoned_mint;
|
||||
|
||||
fn hw(s: &str) -> Vec<String> {
|
||||
vec![s.to_string()]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adopts_our_own_unmarked_devnodes() {
|
||||
// What a host that died mid-mint leaves behind, either role.
|
||||
assert!(is_abandoned_mint(
|
||||
r"ROOT\MEDIA\0004",
|
||||
&hw(r"ROOT\SteamStreamingMicrophone")
|
||||
));
|
||||
assert!(is_abandoned_mint(
|
||||
r"ROOT\MEDIA\0002",
|
||||
&hw(r"ROOT\SteamStreamingSpeakers")
|
||||
));
|
||||
// PnP casing is not guaranteed on either half.
|
||||
assert!(is_abandoned_mint(
|
||||
r"root\media\0009",
|
||||
&hw(r"root\steamstreamingspeakers")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_matches_valves_own_devices() {
|
||||
// THE safety rule: Steam's devnodes carry the very same hardware ids and are ROOT-
|
||||
// enumerated too — only the instance prefix separates them from ours.
|
||||
assert!(!is_abandoned_mint(
|
||||
r"ROOT\STEAMSTREAMINGMICROPHONE\0000",
|
||||
&hw(r"ROOT\SteamStreamingMicrophone")
|
||||
));
|
||||
assert!(!is_abandoned_mint(
|
||||
r"ROOT\STEAMSTREAMINGSPEAKERS\0000",
|
||||
&hw(r"ROOT\SteamStreamingSpeakers")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_matches_other_vendors_or_real_hardware() {
|
||||
// VB-Cable mints ROOT\MEDIA devnodes too — a different hardware id is all that saves it.
|
||||
assert!(!is_abandoned_mint(r"ROOT\MEDIA\0000", &hw("VBAudioVACWDM")));
|
||||
assert!(!is_abandoned_mint(
|
||||
r"HDAUDIO\FUNC_01&VEN_10EC&DEV_0897",
|
||||
&hw(r"ROOT\SteamStreamingSpeakers")
|
||||
));
|
||||
assert!(!is_abandoned_mint(r"ROOT\MEDIA\0001", &[]));
|
||||
}
|
||||
}
|
||||
|
||||
/// A devnode this sweep is allowed to remove: ROOT-enumerated, i.e. software-created.
|
||||
///
|
||||
/// Every devnode we mint comes from `SetupDiCreateDeviceInfoW(… DICD_GENERATE_ID)` on the MEDIA
|
||||
|
||||
@@ -275,13 +275,22 @@ fn ensure_role(role: Role) -> Result<(String, String, Option<String>)> {
|
||||
let (hwid, inf) = discover_driver(role.needle(), role.inf_name())?;
|
||||
let devnode = match find_role_devnode(role)? {
|
||||
Some(inst) => inst,
|
||||
None => {
|
||||
let inst = pe::create_media_devnode(role.desc(), &hwid, |set, did| {
|
||||
pe::write_devparam_dword(set, did, ROLE_MARKER, role.value())
|
||||
})?;
|
||||
tracing::info!(role = role.label(), devnode = %inst, "minted an audio devnode");
|
||||
inst
|
||||
}
|
||||
// Before minting a SECOND devnode, reclaim an abandoned one. Minting is two PnP steps
|
||||
// (register, then mark), and a host that dies between them — the 0.30.0 teardown abort
|
||||
// did exactly this, five times on one box — leaves a registered, driver-bound, endpoint-
|
||||
// serving devnode that carries no marker. Nothing then resolves it: the next pass mints
|
||||
// a fresh one and the orphan lingers as a duplicate "Punktfunk Speakers"/"Punktfunk
|
||||
// Microphone" in the Sound zoo, invisible to the marker-matched uninstall sweep.
|
||||
None => match adopt_orphan_devnode(role, &hwid)? {
|
||||
Some(inst) => inst,
|
||||
None => {
|
||||
let inst = pe::create_media_devnode(role.desc(), &hwid, |set, did| {
|
||||
pe::write_devparam_dword(set, did, ROLE_MARKER, role.value())
|
||||
})?;
|
||||
tracing::info!(role = role.label(), devnode = %inst, "minted an audio devnode");
|
||||
inst
|
||||
}
|
||||
},
|
||||
};
|
||||
pe::bind_driver(&hwid, &inf)?;
|
||||
|
||||
@@ -531,6 +540,61 @@ fn find_role_devnode(role: Role) -> Result<Option<String>> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Reclaim an ABANDONED punktfunk devnode for `role`, re-marking it so it resolves normally from
|
||||
/// here on; `None` when there is nothing to adopt (the ordinary first-mint path).
|
||||
///
|
||||
/// The shape adopted is `ROOT\MEDIA\NNNN` + the role's Steam hardware id + NO owner marker.
|
||||
/// That triple can only be ours: `ROOT\MEDIA\NNNN` is what
|
||||
/// `SetupDiCreateDeviceInfoW(… DICD_GENERATE_ID)` on the MEDIA class yields, and STEAM'S OWN
|
||||
/// devnodes are enumerated under `ROOT\SteamStreamingSpeakers\*` /
|
||||
/// `ROOT\SteamStreamingMicrophone\*` — they carry the same hardware id but never that instance
|
||||
/// prefix, which is precisely what keeps this from adopting (and later sweeping) Steam's devices.
|
||||
/// A marker of ANY family is left alone: it is a live devnode, ours but spoken for.
|
||||
///
|
||||
/// Which family the orphan came from does not matter. Every one is a plain instance of the same
|
||||
/// Valve driver; roles are ours to assign, and re-marking it here is what makes the assignment
|
||||
/// stick across restarts.
|
||||
fn adopt_orphan_devnode(role: Role, hwid: &str) -> Result<Option<String>> {
|
||||
use windows::Win32::Devices::DeviceAndDriverInstallation::{
|
||||
SetupDiEnumDeviceInfo, SPDRP_HARDWAREID,
|
||||
};
|
||||
let set = pe::media_class_devs()?;
|
||||
for i in 0.. {
|
||||
let mut did = pe::devinfo_data();
|
||||
// SAFETY: live set; `did` is a live out-param with cbSize set.
|
||||
if unsafe { SetupDiEnumDeviceInfo(set.0, i, &mut did) }.is_err() {
|
||||
break; // ERROR_NO_MORE_ITEMS
|
||||
}
|
||||
let Some(inst) = pe::instance_id(&set, &did) else {
|
||||
continue;
|
||||
};
|
||||
if !inst.to_ascii_uppercase().starts_with("ROOT\\MEDIA\\") {
|
||||
continue;
|
||||
}
|
||||
if !pe::devnode_multi_sz_prop(&set, &did, SPDRP_HARDWAREID)
|
||||
.iter()
|
||||
.any(|h| h.eq_ignore_ascii_case(hwid))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if super::devnode_cleanup::OWNER_MARKERS
|
||||
.iter()
|
||||
.any(|m| pe::read_devparam_dword(&set, &did, m).is_some())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
pe::write_devparam_dword(&set, &mut did, ROLE_MARKER, role.value())?;
|
||||
tracing::warn!(
|
||||
role = role.label(),
|
||||
devnode = %inst,
|
||||
"adopted an abandoned audio devnode — one of ours whose owner marker never landed \
|
||||
(a host that died mid-mint). Re-marked and reused instead of minting a duplicate"
|
||||
);
|
||||
return Ok(Some(inst));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Find the (exact hardware id, INF path) for one of Steam's streaming drivers: prefer any
|
||||
/// installed devnode whose hardware-id list contains `needle` (its `oemNN.inf` is the driver
|
||||
/// Windows already trusts), else fall back to Steam's driver directory. Shared with the
|
||||
|
||||
@@ -1192,6 +1192,17 @@ fn grant_system_full_control(subkey_path: &str) -> Result<()> {
|
||||
result
|
||||
}
|
||||
|
||||
/// The MMDevices hive an endpoint's record lives in, chosen by the direction its id encodes
|
||||
/// (`{0.0.1.…}` = capture, anything else = render). Render is the safe default: it is what every
|
||||
/// non-capture id resolves to, and the pad program only ever has render endpoints.
|
||||
fn mmdev_path_for(endpoint_id: &str) -> &'static str {
|
||||
if endpoint_id.starts_with(CAPTURE_ENDPOINT_ID_PREFIX) {
|
||||
MMDEV_CAPTURE_PATH
|
||||
} else {
|
||||
MMDEV_RENDER_PATH
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw-registry stamp route: repair the Properties key ACL, then write the serialized
|
||||
/// values (see [`reg_registry_value`]). Values written here are STORED but possibly not
|
||||
/// SERVED until an AudioEndpointBuilder restart — the caller's read-back decides.
|
||||
@@ -1199,7 +1210,14 @@ fn registry_stamp(endpoint_id: &str, stamps: &[&Stamp]) -> Result<()> {
|
||||
use winreg::enums::HKEY_LOCAL_MACHINE;
|
||||
use winreg::RegKey;
|
||||
let guid = endpoint_guid_part(endpoint_id)?;
|
||||
let path = format!(r"{MMDEV_RENDER_PATH}\{guid}\Properties");
|
||||
// The hive follows the endpoint's DIRECTION. This was hardcoded to Render, which is
|
||||
// invisible for the pad program (its endpoints are render-only) but wrong for the minted
|
||||
// provider, which stamps the virtual microphone's CAPTURE endpoint through the same
|
||||
// writer: the fallback then reached for `…\Render\{capture-guid}\Properties`, a key that
|
||||
// cannot exist, so every registry-route stamp of a capture endpoint failed on a box where
|
||||
// the property store was denied — silently, since the caller degrades to "keeps the
|
||||
// driver's default name".
|
||||
let path = format!(r"{}\{guid}\Properties", mmdev_path_for(endpoint_id));
|
||||
grant_system_full_control(&path)
|
||||
.with_context(|| format!("make {path} writable (registry stamp route)"))?;
|
||||
let key = RegKey::predef(HKEY_LOCAL_MACHINE)
|
||||
@@ -2109,6 +2127,23 @@ fn pad_capture_thread(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The registry stamp route must reach for the hive matching the endpoint's DIRECTION —
|
||||
/// it was hardcoded to Render, so a capture endpoint's fallback stamp could never land.
|
||||
#[test]
|
||||
fn registry_stamp_hive_follows_the_endpoint_direction() {
|
||||
assert_eq!(
|
||||
mmdev_path_for("{0.0.1.00000000}.{2753f927-2093-4ab4-aa90-9d880e959128}"),
|
||||
MMDEV_CAPTURE_PATH,
|
||||
"the minted microphone's capture endpoint records under Capture"
|
||||
);
|
||||
assert_eq!(
|
||||
mmdev_path_for("{0.0.0.00000000}.{5da9b5c9-8a10-4b54-8cf6-ce02b8354f16}"),
|
||||
MMDEV_RENDER_PATH,
|
||||
);
|
||||
// Anything unrecognised keeps the old behaviour rather than inventing a hive.
|
||||
assert_eq!(mmdev_path_for("nonsense"), MMDEV_RENDER_PATH);
|
||||
}
|
||||
|
||||
/// The serialized container blob for pad 0 must be byte-for-byte the on-glass-measured
|
||||
/// value, and byte 23 must be the pad index.
|
||||
#[test]
|
||||
|
||||
@@ -573,6 +573,29 @@ pub fn dualsense_windows_test(args: &[String]) -> Result<()> {
|
||||
// (device_type 3, the MI_02-promoted identity) — watch Steam claim it live.
|
||||
let edge = args.iter().any(|a| a == "--edge");
|
||||
let deck = args.iter().any(|a| a == "--deck");
|
||||
// `--idle-after N` drives normally for N seconds, then STOPS sending state frames while still
|
||||
// pumping. That is Moonlight's cadence: moonlight-common-c sends a controller packet only on
|
||||
// CHANGE, so an untouched pad produces no wire events at all. The native plane never sees this
|
||||
// because punktfunk's own client re-sends every live pad's snapshot every 100 ms (the
|
||||
// `input_task.rs` refresh tick) — which is exactly why a manager that needs a periodic re-emit
|
||||
// can look healthy on one plane and die on the other.
|
||||
let idle_after: u64 = args
|
||||
.iter()
|
||||
.skip_while(|a| *a != "--idle-after")
|
||||
.nth(1)
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
// `--resume-after M` ends the silence at M seconds and drives again. That is the half that
|
||||
// actually answers the question: enumeration surviving a silence proves nothing, because a pad
|
||||
// can stay listed and still deliver no input. What matters is whether a report written AFTER
|
||||
// the silence still reaches a consumer — check it with `win-input-matrix --watch` while this
|
||||
// runs, and watch whether the timestamps start advancing again.
|
||||
let resume_after: u64 = args
|
||||
.iter()
|
||||
.skip_while(|a| *a != "--resume-after")
|
||||
.nth(1)
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let extra_buttons: u32 = if edge || deck {
|
||||
punktfunk_core::input::gamepad::BTN_PADDLE1 | punktfunk_core::input::gamepad::BTN_PADDLE2
|
||||
} else {
|
||||
@@ -612,6 +635,9 @@ pub fn dualsense_windows_test(args: &[String]) -> Result<()> {
|
||||
$label
|
||||
);
|
||||
let deadline = Instant::now() + Duration::from_secs(secs);
|
||||
let started = Instant::now();
|
||||
let mut announced_silence = false;
|
||||
let mut announced_resume = false;
|
||||
let (mut i, mut last) = (0i32, Instant::now());
|
||||
while Instant::now() < deadline {
|
||||
mgr.pump(
|
||||
@@ -620,7 +646,27 @@ pub fn dualsense_windows_test(args: &[String]) -> Result<()> {
|
||||
),
|
||||
|o| println!(" hid output from game: {o:?}"),
|
||||
);
|
||||
if last.elapsed() >= Duration::from_millis(400) {
|
||||
let el = started.elapsed();
|
||||
let resumed =
|
||||
resume_after != 0 && el >= Duration::from_secs(resume_after.max(idle_after));
|
||||
let silent =
|
||||
idle_after != 0 && el >= Duration::from_secs(idle_after) && !resumed;
|
||||
if silent && !announced_silence {
|
||||
announced_silence = true;
|
||||
println!(
|
||||
" --- going SILENT (no more state frames, still pumping) at {}s ---",
|
||||
idle_after
|
||||
);
|
||||
}
|
||||
if resumed && !announced_resume {
|
||||
announced_resume = true;
|
||||
println!(
|
||||
" --- RESUMING state frames at {}s (after {}s of silence) ---",
|
||||
resume_after,
|
||||
resume_after.saturating_sub(idle_after)
|
||||
);
|
||||
}
|
||||
if !silent && last.elapsed() >= Duration::from_millis(400) {
|
||||
last = Instant::now();
|
||||
i += 1;
|
||||
let buttons = if i % 2 == 0 {
|
||||
|
||||
@@ -25,7 +25,9 @@
|
||||
use anyhow::{Context, Result};
|
||||
use mdns_sd::{ServiceDaemon, ServiceInfo};
|
||||
use std::collections::HashMap;
|
||||
use std::net::IpAddr;
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
/// The native-protocol mDNS service type. Clients browse this to find punktfunk/1 hosts.
|
||||
pub const NATIVE_SERVICE: &str = "_punktfunk._udp.local.";
|
||||
@@ -81,9 +83,78 @@ pub(crate) fn dns_label(name: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Holds the mDNS daemon; dropping it unregisters the service.
|
||||
/// Holds the mDNS daemon; dropping it unregisters the service and stops the re-announce loop.
|
||||
pub struct Advert {
|
||||
_daemon: ServiceDaemon,
|
||||
/// Never sent on. Dropping it disconnects the channel the re-announce thread waits on, which
|
||||
/// wakes that thread immediately and ends it — so an `Advert` takes its loop with it instead
|
||||
/// of leaving one behind polling for a service nobody advertises.
|
||||
_stop: mpsc::Sender<()>,
|
||||
}
|
||||
|
||||
/// How often a live advert re-checks the address it is announcing.
|
||||
const IP_RECHECK: Duration = Duration::from_secs(10);
|
||||
|
||||
/// The address to advertise right now — loopback only while the machine still has none.
|
||||
fn current_ip() -> IpAddr {
|
||||
crate::gamestream::primary_local_ip().unwrap_or(IpAddr::V4(Ipv4Addr::LOCALHOST))
|
||||
}
|
||||
|
||||
/// Register `build(ip)` for the host's current address, and re-register it whenever that address
|
||||
/// changes. Shared by both adverts ([`advertise_native`] and [`crate::gamestream::mdns`]).
|
||||
///
|
||||
/// mDNS records are PUSHED, not polled: whatever address was true at `register()` keeps being
|
||||
/// announced until something registers a newer one. The host process comes up during boot, which
|
||||
/// on a cold start is before the machine has an address — so the first registration could be
|
||||
/// `127.0.0.1`, and it stayed that way until the host was restarted by hand. `mdns-sd` documents a
|
||||
/// second `register()` of the same fullname as an update, so re-announcing is just calling it
|
||||
/// again.
|
||||
///
|
||||
/// Polls the *routed* address rather than subscribing to the daemon's `IpAdd` events, because the
|
||||
/// boot race usually resolves without one: the NIC often has its address before we register and
|
||||
/// only the default route lands late, so no interface event ever fires.
|
||||
pub(crate) fn advertise_live(
|
||||
service: &'static str,
|
||||
build: impl Fn(IpAddr) -> Result<ServiceInfo> + Send + 'static,
|
||||
) -> Result<Advert> {
|
||||
let daemon = ServiceDaemon::new().context("create mDNS daemon")?;
|
||||
let registered = current_ip();
|
||||
daemon
|
||||
.register(build(registered)?)
|
||||
.with_context(|| format!("register {service} mDNS service"))?;
|
||||
|
||||
let (stop_tx, stop_rx) = mpsc::channel::<()>();
|
||||
let bg_daemon = daemon.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut announced = registered;
|
||||
// Doubles as the sleep: times out every `IP_RECHECK` to re-check, and returns
|
||||
// `Disconnected` the moment the `Advert` drops its sender, which ends the loop.
|
||||
while matches!(
|
||||
stop_rx.recv_timeout(IP_RECHECK),
|
||||
Err(mpsc::RecvTimeoutError::Timeout)
|
||||
) {
|
||||
let now = current_ip();
|
||||
if now == announced {
|
||||
continue;
|
||||
}
|
||||
match build(now)
|
||||
.and_then(|info| bg_daemon.register(info).context("re-register mDNS service"))
|
||||
{
|
||||
Ok(()) => {
|
||||
tracing::info!(service, from = %announced, to = %now, "host address changed — re-announced");
|
||||
announced = now;
|
||||
}
|
||||
// Leave the previous record standing and retry next tick rather than going dark.
|
||||
Err(e) => {
|
||||
tracing::warn!(service, error = %format!("{e:#}"), "mDNS re-announce failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(Advert {
|
||||
_daemon: daemon,
|
||||
_stop: stop_tx,
|
||||
})
|
||||
}
|
||||
|
||||
/// Advertise the native host on the LAN. `fingerprint` is the host cert SHA-256 (lowercase hex);
|
||||
@@ -95,7 +166,6 @@ pub struct Advert {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn advertise_native(
|
||||
hostname: &str,
|
||||
ip: IpAddr,
|
||||
port: u16,
|
||||
fingerprint: &str,
|
||||
require_pairing: bool,
|
||||
@@ -103,14 +173,17 @@ pub fn advertise_native(
|
||||
mgmt_port: Option<u16>,
|
||||
os_chain: &str,
|
||||
) -> Result<Advert> {
|
||||
let daemon = ServiceDaemon::new().context("create mDNS daemon")?;
|
||||
// `hostname` is the DISPLAY name (the instance label clients read back); the A-record target
|
||||
// has to be a legal DNS name, hence the separate sanitized label.
|
||||
let host_name = format!("{}.local.", dns_label(hostname));
|
||||
let mut props: HashMap<String, String> = HashMap::new();
|
||||
props.insert("proto".into(), NATIVE_PROTO.into());
|
||||
props.insert("fp".into(), fingerprint.to_string());
|
||||
props.insert(
|
||||
// Owned, because the record is rebuilt whenever the host's address changes — see
|
||||
// [`advertise_live`]. Everything except the address (and the MACs derived from it) is fixed,
|
||||
// so it is computed once here and moved into the builder.
|
||||
let instance = hostname.to_string();
|
||||
let mut fixed: HashMap<String, String> = HashMap::new();
|
||||
fixed.insert("proto".into(), NATIVE_PROTO.into());
|
||||
fixed.insert("fp".into(), fingerprint.to_string());
|
||||
fixed.insert(
|
||||
"pair".into(),
|
||||
if require_pairing {
|
||||
"required"
|
||||
@@ -119,31 +192,14 @@ pub fn advertise_native(
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
props.insert("id".into(), uniqueid.to_string());
|
||||
fixed.insert("id".into(), uniqueid.to_string());
|
||||
if let Some(mgmt) = mgmt_port {
|
||||
props.insert("mgmt".into(), mgmt.to_string());
|
||||
fixed.insert("mgmt".into(), mgmt.to_string());
|
||||
}
|
||||
// `os` — advisory OS-identity chain for the client's host-card icon (see module doc).
|
||||
if !os_chain.is_empty() {
|
||||
props.insert("os".into(), os_chain.to_string());
|
||||
fixed.insert("os".into(), os_chain.to_string());
|
||||
}
|
||||
// `mac` — the host's wake-capable NIC MAC(s), comma-separated `aa:bb:cc:dd:ee:ff`, routed NIC
|
||||
// first. A client persists these while the host is awake so it can send a Wake-on-LAN magic
|
||||
// packet to wake it later (when it's asleep and no longer advertising). Unauthenticated like
|
||||
// the rest of the advert, but a wrong MAC only makes a wake fail — the magic packet is inert
|
||||
// and the cert fingerprint still gates the actual connection. Omitted when none can be read.
|
||||
let macs = crate::wol::wake_macs(ip);
|
||||
if !macs.is_empty() {
|
||||
props.insert("mac".into(), macs.join(","));
|
||||
}
|
||||
// Detect & warn (never modifies) if the routed NIC isn't armed to wake — the usual reason WoL
|
||||
// silently fails.
|
||||
crate::wol::warn_if_not_armed(ip);
|
||||
let service = ServiceInfo::new(NATIVE_SERVICE, hostname, &host_name, ip, port, props)
|
||||
.context("build native mDNS ServiceInfo")?;
|
||||
daemon
|
||||
.register(service)
|
||||
.context("register native mDNS service")?;
|
||||
tracing::info!(
|
||||
service = "_punktfunk._udp",
|
||||
port,
|
||||
@@ -151,7 +207,26 @@ pub fn advertise_native(
|
||||
pair = if require_pairing { "required" } else { "optional" },
|
||||
"native punktfunk/1 mDNS advertising"
|
||||
);
|
||||
Ok(Advert { _daemon: daemon })
|
||||
advertise_live(NATIVE_SERVICE, move |ip| {
|
||||
let mut props = fixed.clone();
|
||||
// `mac` — the host's wake-capable NIC MAC(s), comma-separated `aa:bb:cc:dd:ee:ff`, routed
|
||||
// NIC first. A client persists these while the host is awake so it can send a
|
||||
// Wake-on-LAN magic packet to wake it later (when it's asleep and no longer advertising).
|
||||
// Unauthenticated like the rest of the advert, but a wrong MAC only makes a wake fail —
|
||||
// the magic packet is inert and the cert fingerprint still gates the actual connection.
|
||||
// Omitted when none can be read, which is what a host that came up before its network did
|
||||
// used to report forever.
|
||||
let macs = crate::wol::wake_macs(ip);
|
||||
if !macs.is_empty() {
|
||||
props.insert("mac".into(), macs.join(","));
|
||||
}
|
||||
// Detect & warn (never modifies) if the routed NIC isn't armed to wake — the usual reason
|
||||
// WoL silently fails. Re-checked on an address change because the routed NIC may be a
|
||||
// different one now.
|
||||
crate::wol::warn_if_not_armed(ip);
|
||||
ServiceInfo::new(NATIVE_SERVICE, &instance, &host_name, ip, port, props)
|
||||
.context("build native mDNS ServiceInfo")
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -590,6 +590,9 @@ fn watch(
|
||||
|
||||
// ---- Phase 1: wait for the game to show up. ----
|
||||
let start_deadline = spawned_at + START_GRACE;
|
||||
// How long the scan has *continuously* seen something for this title — the scan-side twin of
|
||||
// [`SHIM_WINDOW`]. See `scan_settled` below for what it is protecting against.
|
||||
let mut seen_since: Option<Instant> = None;
|
||||
loop {
|
||||
if cancelled() {
|
||||
return;
|
||||
@@ -713,12 +716,39 @@ fn watch(
|
||||
&& (child.is_some() || spawned.is_some())
|
||||
&& spawned_at.elapsed() >= SHIM_WINDOW;
|
||||
let live = scanner.find(&shared.spec, shared.launch_stamp);
|
||||
// The same rule for what the *scan* finds, and for the same reason. A store's launch is a
|
||||
// chain of process trees, and the ones that run before the game carry the signals the game
|
||||
// carries: Steam wraps its shader pre-caching and its Proton prefix work in the very
|
||||
// `reaper SteamLaunch AppId=<appid>` the game gets, so the first poll of a launch can match
|
||||
// a tree that was never the game.
|
||||
//
|
||||
// Latching on one poll is what costs, because the two phases are patient in opposite ways.
|
||||
// This one waits [`START_GRACE`] — five minutes — and ending it never ends the session.
|
||||
// Phase 2 waits [`EXIT_CONFIRM`] — three seconds — and ending it *does*. A single sighting
|
||||
// flips the lease from the first to the second, permanently; when that tree then exits with
|
||||
// the real game not yet started, the stream drops mid-launch. On Linux that ended a Rocket
|
||||
// League session 10 s after launch, while Steam was still compiling its shaders, and the
|
||||
// player had to launch a second time to get one that stayed up (field report 2026-08-22).
|
||||
//
|
||||
// Requiring the sighting to persist buys that back for a few seconds of `GameRunning`
|
||||
// latency and nothing else — exit detection is untouched. ⚠ It is a window, not a proof: a
|
||||
// pre-launch tree that outlives the window still latches. Signals sharp enough to tell one
|
||||
// from the other belong in [`crate::procscan`] (where Steam's shader job is already excluded
|
||||
// by name); this bounds what no signal caught.
|
||||
let scan_settled = if live.is_empty() {
|
||||
seen_since = None;
|
||||
false
|
||||
} else {
|
||||
seen_since.get_or_insert_with(Instant::now).elapsed() >= SHIM_WINDOW
|
||||
};
|
||||
// A provider saying so is as good as seeing it — better, for a title there is nothing to
|
||||
// see: it is the launcher that started the game telling us it did. This is the only way a
|
||||
// [`LeaseKind::Reported`] lease ever leaves this phase, and for a `Matched` one it just
|
||||
// gets there sooner than the scan would.
|
||||
// gets there sooner than the scan would. Not gated by the window above: a report is the
|
||||
// launcher's own statement about the game, not an inference from a process that resembles
|
||||
// it, so there is nothing to wait out.
|
||||
let said_running = reported().is_some_and(|l| l.running);
|
||||
if !live.is_empty() || child_alive || said_running {
|
||||
if scan_settled || child_alive || said_running {
|
||||
known = live.clone();
|
||||
publish(&live);
|
||||
shared.was_running.store(true, Ordering::Relaxed);
|
||||
@@ -731,6 +761,8 @@ fn watch(
|
||||
title = %shared.game.title,
|
||||
kind = kind.as_str(),
|
||||
procs = live.len(),
|
||||
// Which processes, not just how many: see [`crate::procscan::names`].
|
||||
names = ?crate::procscan::names(&live),
|
||||
"the launched game is running"
|
||||
);
|
||||
break;
|
||||
@@ -2019,6 +2051,78 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// 🛑 The 2026-08-22 field report: a **pre-launch** process tree must not be mistaken for the
|
||||
/// game.
|
||||
///
|
||||
/// Steam wraps its shader pre-caching in the same `SteamLaunch AppId=` reaper the game itself
|
||||
/// gets, so the first poll of a launch matches a tree that was never the game. What shipped
|
||||
/// latched on that single sighting: the lease left the start phase immediately, and when the
|
||||
/// compile finished and that tree exited — with Rocket League still starting — the exit watch
|
||||
/// called it the game exiting and closed the session with `APP_EXITED`, 10 s after launch. On
|
||||
/// the player's screen the stream dropped mid-"Processing Vulkan shaders"; their workaround was
|
||||
/// to launch the game twice.
|
||||
///
|
||||
/// The scanner now knows Steam's replayer by name ([`crate::procscan`]). This pins the bound
|
||||
/// behind that: a matched process that does not outlive [`SHIM_WINDOW`] never arms the exit
|
||||
/// watch, whatever it was — which is what covers the pre-launch trees nobody has named yet.
|
||||
///
|
||||
/// Ignored by default: it outlives the shim window and then waits out [`EXIT_CONFIRM`], ~11 s.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
#[ignore = "drives a real process for ~11s (shim window + exit confirmation)"]
|
||||
fn a_pre_launch_tree_that_exits_never_ends_the_session() {
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
|
||||
// The stand-in has to keep the name `sleep`: coreutils is a multi-call binary that
|
||||
// dispatches on `argv[0]`, and under any other name it exits instantly — which would pass
|
||||
// this test for entirely the wrong reason. (Same trap as the live matcher test in
|
||||
// [`crate::procscan`].)
|
||||
let td = tempfile::tempdir().expect("tempdir");
|
||||
let stand_in = td.path().join("sleep");
|
||||
std::fs::copy("/bin/sleep", &stand_in).expect("copy a stand-in pre-launch binary");
|
||||
let launch_stamp = launch_clock();
|
||||
|
||||
// Alive for less than the shim window — Steam's shader job, in miniature.
|
||||
let mut child = std::process::Command::new(&stand_in)
|
||||
.arg("3")
|
||||
.spawn()
|
||||
.expect("spawn the fake pre-launch tree");
|
||||
// Reaped on its own thread: a zombie keeps its `/proc` entry with an unchanged start time,
|
||||
// so the scan would call it alive forever and the exit under test never happen.
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
});
|
||||
|
||||
static PRE_EXITS: AtomicUsize = AtomicUsize::new(0);
|
||||
PRE_EXITS.store(0, Ordering::SeqCst);
|
||||
let lease = open(
|
||||
LeaseRequest {
|
||||
launch_stamp,
|
||||
// No child and no pid: the scan is the only signal, which is the field-report shape
|
||||
// (`steam steam://rungameid/…` had already handed off and exited).
|
||||
..req("steam:pre-launch", DetectSpec::dir(td.path()), false)
|
||||
},
|
||||
Box::new(|| {
|
||||
PRE_EXITS.fetch_add(1, Ordering::SeqCst);
|
||||
}),
|
||||
);
|
||||
let shared = lease.shared();
|
||||
assert!(matches!(shared.kind(), LeaseKind::Matched));
|
||||
|
||||
std::thread::sleep(SHIM_WINDOW + EXIT_CONFIRM + Duration::from_secs(3));
|
||||
assert_eq!(
|
||||
PRE_EXITS.load(Ordering::SeqCst),
|
||||
0,
|
||||
"a tree that ran before the game must not end the session when it exits — this is the \
|
||||
field report"
|
||||
);
|
||||
assert_ne!(
|
||||
shared.state(),
|
||||
GameState::Exited,
|
||||
"the game never started, so nothing of it can have exited"
|
||||
);
|
||||
}
|
||||
|
||||
/// The whole point of the module, against a real process: a `Child` lease sees its game running,
|
||||
/// notices when it exits, and reports that exit exactly once.
|
||||
///
|
||||
|
||||
@@ -3,37 +3,34 @@
|
||||
|
||||
use super::Host;
|
||||
use anyhow::{Context, Result};
|
||||
use mdns_sd::{ServiceDaemon, ServiceInfo};
|
||||
use mdns_sd::ServiceInfo;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Holds the mDNS daemon; dropping it unregisters the service.
|
||||
pub struct Advert {
|
||||
_daemon: ServiceDaemon,
|
||||
}
|
||||
// One `Advert` for both service types: holds the mDNS daemon plus the re-announce loop that
|
||||
// keeps the record pointed at the host's current address.
|
||||
use crate::discovery::Advert;
|
||||
|
||||
const SERVICE: &str = "_nvstream._tcp.local.";
|
||||
|
||||
pub fn advertise(host: &Host) -> Result<Advert> {
|
||||
let daemon = ServiceDaemon::new().context("create mDNS daemon")?;
|
||||
// Instance name = the display name (what Moonlight lists); A-record target = the sanitized
|
||||
// DNS label, so a free-text `PUNKTFUNK_HOST_NAME` can't produce an illegal record.
|
||||
let host_name = format!("{}.local.", crate::discovery::dns_label(&host.hostname));
|
||||
// No TXT records are required for Moonlight discovery; it resolves the A record and then
|
||||
// GETs /serverinfo for capabilities.
|
||||
let props: HashMap<String, String> = HashMap::new();
|
||||
let service = ServiceInfo::new(
|
||||
"_nvstream._tcp.local.",
|
||||
&host.hostname,
|
||||
&host_name,
|
||||
host.local_ip,
|
||||
host.http_port,
|
||||
props,
|
||||
)
|
||||
.context("build mDNS ServiceInfo")?;
|
||||
daemon.register(service).context("register mDNS service")?;
|
||||
let instance = host.hostname.clone();
|
||||
let port = host.http_port;
|
||||
tracing::info!(
|
||||
service = "_nvstream._tcp",
|
||||
port = host.http_port,
|
||||
port,
|
||||
host = %host_name,
|
||||
"mDNS advertising"
|
||||
);
|
||||
Ok(Advert { _daemon: daemon })
|
||||
// The advertised address is supplied per-registration so the record follows the host onto a
|
||||
// network that only came up after boot — see [`crate::discovery::advertise_live`].
|
||||
crate::discovery::advertise_live(SERVICE, move |ip| {
|
||||
// No TXT records are required for Moonlight discovery; it resolves the A record and then
|
||||
// GETs /serverinfo for capabilities.
|
||||
let props: HashMap<String, String> = HashMap::new();
|
||||
ServiceInfo::new(SERVICE, &instance, &host_name, ip, port, props)
|
||||
.context("build mDNS ServiceInfo")
|
||||
})
|
||||
}
|
||||
|
||||
@@ -138,7 +138,6 @@ pub struct Host {
|
||||
pub hostname: String,
|
||||
/// Stable per-host id (persisted), echoed in serverinfo + matched on pairing.
|
||||
pub uniqueid: String,
|
||||
pub local_ip: IpAddr,
|
||||
pub http_port: u16,
|
||||
pub https_port: u16,
|
||||
/// OS identity chain (`windows` | `macos` | `linux[/<family>][/<id>]`), advertised in the
|
||||
@@ -155,13 +154,25 @@ impl Host {
|
||||
Ok(Host {
|
||||
hostname: hostname_string(),
|
||||
uniqueid: load_or_create_uniqueid()?,
|
||||
local_ip: primary_local_ip().unwrap_or(IpAddr::V4(Ipv4Addr::LOCALHOST)),
|
||||
http_port: HTTP_PORT,
|
||||
https_port: HTTPS_PORT,
|
||||
os_chain: os.chain.clone(),
|
||||
os_name: os.pretty.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Best-effort primary LAN IP, re-read on every call.
|
||||
///
|
||||
/// Deliberately NOT a field: [`Host::detect`] runs as the host process starts, which on a cold
|
||||
/// boot is before the machine has an address at all, and a snapshot taken there used to stick
|
||||
/// for the life of the process — the host then advertised itself over mDNS as `127.0.0.1`,
|
||||
/// handed Moonlight an `rtsp://127.0.0.1` session URL, and dropped its Wake-on-LAN MAC record,
|
||||
/// until someone restarted it by hand. Reading live costs a `connect(2)` on an unconnected UDP
|
||||
/// socket (no packets are sent), which is nothing beside the HTTP responses it is serialized
|
||||
/// into. Loopback here means "still no LAN address", not a stale one.
|
||||
pub fn local_ip(&self) -> IpAddr {
|
||||
primary_local_ip().unwrap_or(IpAddr::V4(Ipv4Addr::LOCALHOST))
|
||||
}
|
||||
}
|
||||
|
||||
/// The stream parameters a client passes at `/launch`, shared with the RTSP + media stages.
|
||||
@@ -432,7 +443,7 @@ pub fn serve(
|
||||
tracing::info!(
|
||||
hostname = %state.host.hostname,
|
||||
uniqueid = %state.host.uniqueid,
|
||||
ip = %state.host.local_ip,
|
||||
ip = %state.host.local_ip(),
|
||||
native_port = native.port,
|
||||
require_pairing = native.require_pairing,
|
||||
gamestream,
|
||||
@@ -656,10 +667,43 @@ fn load_or_create_uniqueid() -> Result<String> {
|
||||
|
||||
/// Best-effort primary LAN IP: open a UDP socket "toward" a public address and read the
|
||||
/// local address the OS would route through. No packets are actually sent.
|
||||
fn primary_local_ip() -> Option<IpAddr> {
|
||||
let sock = UdpSocket::bind("0.0.0.0:0").ok()?;
|
||||
sock.connect("8.8.8.8:80").ok()?;
|
||||
sock.local_addr().ok().map(|a| a.ip())
|
||||
///
|
||||
/// Returns `None` — never loopback — when the machine has no LAN address yet, so callers have to
|
||||
/// decide what "unknown" means instead of silently inheriting `127.0.0.1`. During a cold boot the
|
||||
/// route probe fails outright (the host outruns DHCP: the Windows service is `AutoStart` with no
|
||||
/// network dependency), so it falls back to the first non-loopback interface address, which the
|
||||
/// NIC has as soon as it is configured even if the default route is not installed yet.
|
||||
pub(crate) fn primary_local_ip() -> Option<IpAddr> {
|
||||
let routed = UdpSocket::bind("0.0.0.0:0")
|
||||
.and_then(|sock| {
|
||||
sock.connect("8.8.8.8:80")?;
|
||||
sock.local_addr()
|
||||
})
|
||||
.ok()
|
||||
.map(|a| a.ip())
|
||||
.filter(|ip| usable_lan_ip(*ip));
|
||||
routed.or_else(first_lan_ipv4)
|
||||
}
|
||||
|
||||
/// First reachable IPv4 an interface holds, ignoring the routing table entirely.
|
||||
///
|
||||
/// Split out because this is the branch the boot race actually takes, and the one nothing would
|
||||
/// otherwise exercise: the route probe above needs a default route, which lands *after* the NIC
|
||||
/// has its address on a cold boot. Between those two moments the old code had no answer and fell
|
||||
/// back to loopback for good.
|
||||
fn first_lan_ipv4() -> Option<IpAddr> {
|
||||
if_addrs::get_if_addrs()
|
||||
.ok()?
|
||||
.into_iter()
|
||||
.map(|i| i.ip())
|
||||
.find(|ip| ip.is_ipv4() && usable_lan_ip(*ip))
|
||||
}
|
||||
|
||||
/// Is `ip` an address a client could actually reach this host on? Loopback and the unspecified
|
||||
/// address are both "we don't know yet" dressed up as an answer, and advertising either is the
|
||||
/// boot race that made a freshly-restarted host publish itself as `127.0.0.1`.
|
||||
fn usable_lan_ip(ip: IpAddr) -> bool {
|
||||
!ip.is_loopback() && !ip.is_unspecified()
|
||||
}
|
||||
|
||||
/// Where the paired-client allow-list persists (survives host restarts, like Sunshine).
|
||||
@@ -716,6 +760,106 @@ pub(crate) fn save_paired(paired: &[Vec<u8>]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the operator's per-client display labels persist, keyed by certificate fingerprint.
|
||||
///
|
||||
/// A SIDECAR to [`paired_path`] rather than a field inside it, for two reasons. `paired.json` is a
|
||||
/// bare `Vec<Vec<u8>>` of certificate DERs — giving it a shape would be a migration on the one file
|
||||
/// that decides who may connect — and a label is not part of that trust decision, so a corrupt or
|
||||
/// missing label file must never be able to lock anybody out. Losing this file loses names, nothing
|
||||
/// else.
|
||||
///
|
||||
/// Why labels have to exist at all: every moonlight-common-c client self-signs with the SAME
|
||||
/// subject (`CN=NVIDIA GameStream Client`), so the certificate carries no device identity
|
||||
/// whatsoever. Without an operator-supplied name, a list of five paired devices is five identical
|
||||
/// rows and the only way to tell them apart — or to know which one to unpair — is the fingerprint.
|
||||
fn labels_path() -> Option<std::path::PathBuf> {
|
||||
Some(pf_paths::config_dir().join("client-labels.json"))
|
||||
}
|
||||
|
||||
/// Serializes the read-modify-write in [`set_client_label`]. Two concurrent renames would
|
||||
/// otherwise race on a whole-file rewrite and silently drop one of the two names.
|
||||
static LABELS_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// Load the fingerprint → label map (empty on first run, unreadable file, or parse failure — a
|
||||
/// label is cosmetic, so every failure degrades to "no names" and never to an error).
|
||||
pub(crate) fn load_client_labels() -> std::collections::BTreeMap<String, String> {
|
||||
let Some(path) = labels_path() else {
|
||||
return Default::default();
|
||||
};
|
||||
let Ok(raw) = std::fs::read(&path) else {
|
||||
return Default::default();
|
||||
};
|
||||
serde_json::from_slice(&raw).unwrap_or_else(|e| {
|
||||
tracing::warn!(error = %e, "client-labels.json unreadable — listing clients without names");
|
||||
Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// Set (`Some`) or clear (`None`) one client's label, persisted atomically. Returns the stored
|
||||
/// label. Fingerprints are normalized to lowercase hex so a rename and a later lookup agree
|
||||
/// regardless of how the caller cased the path parameter.
|
||||
pub(crate) fn set_client_label(fp_hex: &str, label: Option<&str>) -> Option<String> {
|
||||
let _guard = LABELS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let fp = fp_hex.to_ascii_lowercase();
|
||||
let mut labels = load_client_labels();
|
||||
let stored = match label {
|
||||
Some(l) => {
|
||||
let clean = crate::native_pairing::sanitize_device_name(l, &fp);
|
||||
labels.insert(fp, clean.clone());
|
||||
Some(clean)
|
||||
}
|
||||
None => {
|
||||
labels.remove(&fp);
|
||||
None
|
||||
}
|
||||
};
|
||||
save_client_labels(&labels);
|
||||
stored
|
||||
}
|
||||
|
||||
/// Drop the labels of fingerprints that are no longer paired. Called from the unpair paths so the
|
||||
/// file cannot grow without bound as devices come and go, and so a re-pairing of the same
|
||||
/// certificate starts unnamed rather than inheriting a stranger's name.
|
||||
pub(crate) fn retain_client_labels(still_paired: &[Vec<u8>]) {
|
||||
use sha2::{Digest, Sha256};
|
||||
let _guard = LABELS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let live: std::collections::BTreeSet<String> = still_paired
|
||||
.iter()
|
||||
.map(|der| hex::encode(Sha256::digest(der)))
|
||||
.collect();
|
||||
let mut labels = load_client_labels();
|
||||
let before = labels.len();
|
||||
labels.retain(|fp, _| live.contains(fp));
|
||||
if labels.len() != before {
|
||||
save_client_labels(&labels);
|
||||
}
|
||||
}
|
||||
|
||||
/// Persist the label map — same atomic temp-file + rename as [`save_paired`], so a crash mid-write
|
||||
/// cannot truncate it.
|
||||
fn save_client_labels(labels: &std::collections::BTreeMap<String, String>) {
|
||||
let Some(path) = labels_path() else { return };
|
||||
if let Some(dir) = path.parent() {
|
||||
let _ = pf_paths::create_private_dir(dir);
|
||||
}
|
||||
let bytes = match serde_json::to_vec(labels) {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "serializing client labels failed");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
if let Err(e) = pf_paths::write_secret_file(&tmp, &bytes) {
|
||||
tracing::warn!(error = %e, "persisting client labels failed (temp write)");
|
||||
return;
|
||||
}
|
||||
if let Err(e) = std::fs::rename(&tmp, &path) {
|
||||
tracing::warn!(error = %e, "persisting client labels failed (rename)");
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod host_name_tests {
|
||||
use super::sanitize_display_name;
|
||||
@@ -740,6 +884,52 @@ mod host_name_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod local_ip_tests {
|
||||
use super::{first_lan_ipv4, primary_local_ip, usable_lan_ip};
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
|
||||
#[test]
|
||||
fn loopback_and_unspecified_are_never_advertisable() {
|
||||
// The bug: a host that started before its network did advertised these as its address and
|
||||
// kept doing so for the life of the process.
|
||||
for unusable in [
|
||||
IpAddr::V4(Ipv4Addr::LOCALHOST),
|
||||
IpAddr::V4(Ipv4Addr::UNSPECIFIED),
|
||||
IpAddr::V6(Ipv6Addr::LOCALHOST),
|
||||
IpAddr::V6(Ipv6Addr::UNSPECIFIED),
|
||||
] {
|
||||
assert!(
|
||||
!usable_lan_ip(unusable),
|
||||
"{unusable} must not be advertised"
|
||||
);
|
||||
}
|
||||
for usable in [
|
||||
IpAddr::V4(Ipv4Addr::new(192, 168, 1, 173)),
|
||||
IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2)),
|
||||
IpAddr::V6(Ipv6Addr::new(0xfd00, 0, 0, 0, 0, 0, 0, 1)),
|
||||
] {
|
||||
assert!(usable_lan_ip(usable), "{usable} is reachable and must pass");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_reports_no_address_rather_than_loopback() {
|
||||
// Holds on a networked box and on an isolated CI runner alike: either we found a real LAN
|
||||
// address, or we admit we have none. `None` is what lets `Host::local_ip()` and the mDNS
|
||||
// advert keep retrying instead of freezing a wrong answer in place.
|
||||
assert!(primary_local_ip().is_none_or(usable_lan_ip));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_fallback_never_offers_loopback() {
|
||||
// The branch a cold boot takes, before the default route exists. It may legitimately find
|
||||
// nothing (a machine with no NIC up, e.g. an isolated CI container) — what it must never
|
||||
// do is hand back the loopback that `get_if_addrs` also reports.
|
||||
assert!(first_lan_ipv4().is_none_or(usable_lan_ip));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod session_tests {
|
||||
use super::*;
|
||||
@@ -748,7 +938,6 @@ mod session_tests {
|
||||
let host = Host {
|
||||
hostname: "test-host".into(),
|
||||
uniqueid: "deadbeef".into(),
|
||||
local_ip: IpAddr::V4(Ipv4Addr::LOCALHOST),
|
||||
http_port: HTTP_PORT,
|
||||
https_port: HTTPS_PORT,
|
||||
os_chain: "linux".into(),
|
||||
|
||||
@@ -250,7 +250,7 @@ async fn h_launch(
|
||||
fps = session.fps,
|
||||
rikeyid = session.rikeyid,
|
||||
"launch — session created; RTSP at rtsp://{}:{RTSP_PORT}",
|
||||
st.host.local_ip
|
||||
st.host.local_ip()
|
||||
);
|
||||
xml(session_url_xml(&st, "gamesession")).into_response()
|
||||
}
|
||||
@@ -405,7 +405,7 @@ fn gamestream_admission(
|
||||
fn session_url_xml(st: &AppState, tag: &str) -> String {
|
||||
format!(
|
||||
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root status_code=\"200\">\n<sessionUrl0>rtsp://{}:{RTSP_PORT}</sessionUrl0>\n<{tag}>1</{tag}>\n</root>\n",
|
||||
st.host.local_ip
|
||||
st.host.local_ip()
|
||||
)
|
||||
}
|
||||
|
||||
@@ -485,13 +485,11 @@ fn error_xml() -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
|
||||
fn test_state() -> Arc<AppState> {
|
||||
let host = super::super::Host {
|
||||
hostname: "t".into(),
|
||||
uniqueid: "id".into(),
|
||||
local_ip: IpAddr::V4(Ipv4Addr::LOCALHOST),
|
||||
http_port: HTTP_PORT,
|
||||
https_port: HTTPS_PORT,
|
||||
os_chain: "linux".into(),
|
||||
|
||||
@@ -39,7 +39,7 @@ pub fn serverinfo_xml(host: &Host, https: bool, paired: bool) -> String {
|
||||
uniqueid = host.uniqueid,
|
||||
https_port = host.https_port,
|
||||
http_port = host.http_port,
|
||||
local_ip = host.local_ip,
|
||||
local_ip = host.local_ip(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -205,7 +205,6 @@ mod tests {
|
||||
let host = Host {
|
||||
hostname: "test".into(),
|
||||
uniqueid: "uid".into(),
|
||||
local_ip: std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
|
||||
http_port: 47989,
|
||||
https_port: 47984,
|
||||
os_chain: "linux".into(),
|
||||
|
||||
@@ -1111,6 +1111,21 @@ fn spawn_sender(
|
||||
|
||||
use crate::send_pacing::percentile;
|
||||
|
||||
/// How long to ignore further keyframe requests after emitting one.
|
||||
///
|
||||
/// The window bounds IDR emission in TIME, so it needs an absolute floor rather than a frame
|
||||
/// count: it has to outlast the round trip in which the client receives and decodes the IDR it
|
||||
/// already asked for. The original `frame_interval * 2` closes long before that at high refresh —
|
||||
/// 16.7 ms at 120 fps, while a Moonlight client under loss re-asks every ~30 ms — so every request
|
||||
/// passed the gate and the stream became ~32 full IDRs/s, whose bulk causes the very loss that
|
||||
/// prompts the next request. That storm sustains itself and reads as stutter at a flat latency
|
||||
/// (field log, AMD RX 7800 XT / Bazzite 44 HEVC, 2026-08-22: 1118 requests, 1115 honoured, 3
|
||||
/// coalesced). 100 ms matches the encoder-reset backoff below and is about one IDR's service time
|
||||
/// on a saturated link.
|
||||
fn keyframe_coalesce_window(frame_interval: Duration) -> Duration {
|
||||
(frame_interval * 2).max(Duration::from_millis(100))
|
||||
}
|
||||
|
||||
/// The encode → packetize loop, over a borrowed capturer. Sending runs on a dedicated thread
|
||||
/// (see [`spawn_sender`]) so a send spike can never stall capture/encode.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -1194,6 +1209,11 @@ fn stream_body(
|
||||
// also fails safe when nobody tells it, but pass the REAL depth: `idd_depth` is configurable
|
||||
// and a deeper ring is free pipelining the fallback would forfeit.
|
||||
enc.set_input_ring_depth(capturer.pipeline_depth().max(1));
|
||||
// What `enc` was opened against. The capture source can change size/format UNDER this loop with
|
||||
// nothing negotiating it (see the follow-the-source guard below); tracked so the loop can notice.
|
||||
// Both sites that swap `enc` re-bind `frame` with it, so this is always
|
||||
// `(frame.format, frame.width, frame.height)` right after one.
|
||||
let mut enc_src = (frame.format, frame.width, frame.height);
|
||||
// FEC overhead percent (Sunshine default 20). Override with PUNKTFUNK_FEC_PCT (0 = data-only).
|
||||
let fec_pct: u8 = std::env::var("PUNKTFUNK_FEC_PCT")
|
||||
.ok()
|
||||
@@ -1273,9 +1293,9 @@ fn stream_body(
|
||||
// RFI (VAAPI/AMD — `supports_rfi=false`) each one becomes a full IDR, so an un-coalesced request
|
||||
// stream turns EVERY frame into a 4K IDR, saturates the send path, and collapses the session
|
||||
// instead of recovering. One fresh IDR already resolves all pending loss, so after emitting one
|
||||
// we ignore further keyframe requests for a short in-flight window (~2 frames). NVENC
|
||||
// ref-invalidation (cheap, no IDR spike) is never rate-limited — only full keyframes are.
|
||||
let keyframe_coalesce = frame_interval * 2;
|
||||
// we ignore further keyframe requests for the in-flight window below. NVENC ref-invalidation
|
||||
// (cheap, no IDR spike) is never rate-limited — only full keyframes are.
|
||||
let keyframe_coalesce = keyframe_coalesce_window(frame_interval);
|
||||
let mut last_keyframe: Option<Instant> = None;
|
||||
// A frame dropped at the pipeline head (below) breaks the reference chain for the following
|
||||
// P-frames: the client never receives it, but the encoder advanced its references past it, and —
|
||||
@@ -1362,6 +1382,7 @@ fn stream_body(
|
||||
.context("reopen encoder after rebuild")?;
|
||||
// A rebuilt encoder starts unconfigured — same reason as the first open above.
|
||||
enc.set_input_ring_depth(capturer.pipeline_depth().max(1));
|
||||
enc_src = (frame.format, frame.width, frame.height);
|
||||
supports_rfi = enc.caps().supports_rfi;
|
||||
enc.request_keyframe();
|
||||
last_keyframe = Some(Instant::now());
|
||||
@@ -1375,6 +1396,82 @@ fn stream_body(
|
||||
}
|
||||
}
|
||||
let t_cap = tick.elapsed();
|
||||
// Follow an AUTONOMOUS source mode change — one nothing negotiated. The IDD-push capturer
|
||||
// re-opens its ring on a confirmed display-descriptor change (a fullscreen game mode-setting
|
||||
// the virtual display, or an HDR flip changing the format), and the encoder is the one
|
||||
// component that cannot follow a resolution change in place. Every `submit` below then
|
||||
// refuses the frame ("captured WxH != encoder AxB"), and the submit ladder only rebuilds the
|
||||
// encoder IN PLACE — at the SAME configured size — which cannot fix a size the source has
|
||||
// already left, so all five resets burn on it and the stream ends (native/stream.rs carried
|
||||
// the identical gap; a 2026-08-22 field report hit it there at 4K→1080p).
|
||||
//
|
||||
// GameStream has no mid-stream mode-change message, so the client is NOT told: Moonlight
|
||||
// decodes a bitstream that disagrees with the resolution it configured its decoder from.
|
||||
// That is the same bargain the first open above already takes whenever the captured size
|
||||
// differs from the negotiated one (the monitor-mirror case) — tolerant decoders re-init off
|
||||
// the SPS and scale, a strict one (Media Foundation on Xbox) may stall and drop the session.
|
||||
// Taking it here too is strictly better than the alternative, which is ending every stream
|
||||
// the moment a game changes mode.
|
||||
if enc_src != (frame.format, frame.width, frame.height) {
|
||||
match encode::open_video(
|
||||
cfg.codec,
|
||||
frame.format,
|
||||
frame.width,
|
||||
frame.height,
|
||||
cfg.fps,
|
||||
cfg.bitrate_kbps as u64 * 1000,
|
||||
frame.is_cuda(),
|
||||
// Derived from the delivered format, so an HDR flip re-opens at the right depth.
|
||||
gs_bit_depth(frame.format),
|
||||
encode::ChromaFormat::Yuv420, // GameStream stays 4:2:0 — see the first open
|
||||
cursor_blend, // same capture cursor mode — see the first open
|
||||
cfg.slices, // client slicing ceiling — see the first open
|
||||
) {
|
||||
Ok(e) => {
|
||||
tracing::info!(
|
||||
from = %format!("{}x{} {:?}", enc_src.1, enc_src.2, enc_src.0),
|
||||
to = %format!("{}x{} {:?}", frame.width, frame.height, frame.format),
|
||||
negotiated = ?(cfg.width, cfg.height),
|
||||
"gamestream: the capture source changed mode mid-stream — reopened the \
|
||||
encoder at the delivered size (the client is not told; a strict decoder \
|
||||
may not follow — see the note at this guard)"
|
||||
);
|
||||
enc = e;
|
||||
enc_src = (frame.format, frame.width, frame.height);
|
||||
// A rebuilt encoder starts unconfigured — same reasons as the first open.
|
||||
enc.set_input_ring_depth(capturer.pipeline_depth().max(1));
|
||||
supports_rfi = enc.caps().supports_rfi;
|
||||
enc.request_keyframe();
|
||||
last_keyframe = Some(Instant::now());
|
||||
// The old encoder died with its in-flight submissions — their AUs will never
|
||||
// arrive, so the numbering prediction restarts at `au_seq` (same reasoning as
|
||||
// the capture rebuild above). Restart the stall clock for the fresh encoder and
|
||||
// give it the full reset budget.
|
||||
enc_inflight = 0;
|
||||
encoder_resets = 0;
|
||||
last_au_at = Instant::now();
|
||||
}
|
||||
Err(e) => {
|
||||
// Don't spend the stream on the FIRST failed open: the mode-set that triggered
|
||||
// this is exactly the kind of event that leaves the driver settling, which is
|
||||
// what the submit ladder's backoff exists for. Spend the shared reset budget at
|
||||
// the same exponential pace, re-entering this guard each round — the old encoder
|
||||
// stays installed and mismatched meanwhile, so it simply keeps failing submit.
|
||||
encoder_resets += 1;
|
||||
if encoder_resets > MAX_ENCODER_RESETS {
|
||||
return Err(e).context("reopen encoder at the source's new mode");
|
||||
}
|
||||
let backoff = frame_interval
|
||||
.max(Duration::from_millis(100u64 << (encoder_resets - 1).min(4)));
|
||||
tracing::warn!(error = %format!("{e:#}"), reset = encoder_resets,
|
||||
max = MAX_ENCODER_RESETS,
|
||||
"gamestream: reopening the encoder at the source's new mode failed — retrying");
|
||||
next_frame = Instant::now() + backoff;
|
||||
std::thread::sleep(backoff);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Honor a client recovery request. Prefer reference-frame invalidation (the encoder
|
||||
// re-references an older still-valid frame — no costly IDR spike); if the encoder can't
|
||||
// invalidate (range too old, or no NVENC RFI) it returns false and we force a keyframe.
|
||||
@@ -1716,6 +1813,27 @@ mod tests {
|
||||
assert_eq!(t.game.title, "/opt/game/run");
|
||||
}
|
||||
|
||||
/// The coalesce window must bound forced IDRs in time, not in frames. A frame-scaled window
|
||||
/// vanishes exactly where it matters most — at high refresh, where a client's recovery spam
|
||||
/// arrives far slower than two frame intervals and so passes the gate every time.
|
||||
#[test]
|
||||
fn keyframe_coalesce_window_outlasts_a_clients_request_cadence() {
|
||||
// The observed storm: a 120 fps session against a client re-asking every ~30 ms. The
|
||||
// pre-floor window was 16.7 ms, so every request became a full IDR.
|
||||
let at_120 = keyframe_coalesce_window(Duration::from_secs_f64(1.0 / 120.0));
|
||||
assert!(
|
||||
at_120 >= Duration::from_millis(100),
|
||||
"120 fps window {at_120:?} does not outlast a ~30 ms request cadence"
|
||||
);
|
||||
// 60 fps was under the floor too (33.3 ms), which is why this is not a 120-only fix.
|
||||
assert!(keyframe_coalesce_window(Duration::from_secs_f64(1.0 / 60.0)) >= at_120);
|
||||
// A slow stream keeps the frame-scaled window — the floor only ever raises it.
|
||||
assert_eq!(
|
||||
keyframe_coalesce_window(Duration::from_millis(200)),
|
||||
Duration::from_millis(400)
|
||||
);
|
||||
}
|
||||
|
||||
/// End-to-end check of the send thread: batches pushed on the channel arrive, complete and
|
||||
/// byte-identical, at a peer socket via the paced sendmmsg path.
|
||||
#[test]
|
||||
|
||||
@@ -55,7 +55,14 @@ pub struct DetectSpec {
|
||||
/// Steam appid, for titles Steam itself installed (never for non-Steam shortcuts, whose reaper
|
||||
/// appid semantics differ — those carry an [`exe`](Self::exe) instead). On Linux this is the
|
||||
/// sharpest signal available: Steam wraps every launch — native or Proton — in
|
||||
/// `reaper SteamLaunch AppId=<appid>`, whose lifetime is exactly the game's.
|
||||
/// `reaper SteamLaunch AppId=<appid>`.
|
||||
///
|
||||
/// ⚠ That reaper is the *appid's*, not the game's. Steam wraps its **pre-launch** work for a
|
||||
/// title in one too — shader pre-caching most visibly — so a launch is a chain of reaper trees
|
||||
/// and only the last of them is the game. Reading the first as the game is what dropped a
|
||||
/// stream 10 s into a Rocket League launch, mid-shader-compile (field report 2026-08-22); the
|
||||
/// shader job is excluded by name in [`crate::procscan`], and [`crate::gamelease`] waits out a
|
||||
/// window before believing any of them.
|
||||
pub steam_appid: Option<u32>,
|
||||
/// A launcher-stamped environment marker.
|
||||
pub env_marker: Option<EnvMarker>,
|
||||
|
||||
@@ -328,7 +328,8 @@ fn api_router_parts() -> (Router<Arc<MgmtState>>, utoipa::openapi::OpenApi) {
|
||||
clients::list_paired_clients,
|
||||
clients::unpair_all_clients
|
||||
))
|
||||
.routes(routes!(clients::unpair_client));
|
||||
// DELETE and PATCH share `/clients/{fingerprint}` — one `routes!`, same rule as above.
|
||||
.routes(routes!(clients::unpair_client, clients::rename_client));
|
||||
// The GameStream PIN flow exists only when the compat planes do (WP19) — a native-only
|
||||
// build's API (and its OpenAPI document) simply has no such endpoints.
|
||||
#[cfg(feature = "gamestream")]
|
||||
|
||||
@@ -11,7 +11,17 @@ pub(crate) struct PairedClient {
|
||||
#[schema(example = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08")]
|
||||
fingerprint: String,
|
||||
/// Certificate subject (e.g. `CN=NVIDIA GameStream Client`), if the DER parses.
|
||||
///
|
||||
/// Do not display this as a device name. Every moonlight-common-c client self-signs with that
|
||||
/// same fixed subject, so it identifies the *protocol*, not the device — a list of paired
|
||||
/// phones, TVs and handhelds all read identically. [`Self::label`] is the field to show.
|
||||
subject: Option<String>,
|
||||
/// Operator-assigned display name for this device, if one has been set (`PATCH /clients/{fp}`).
|
||||
///
|
||||
/// This is the ONLY thing that can tell two paired Moonlight devices apart in a list, because
|
||||
/// their certificates cannot: see [`Self::subject`]. Absent until somebody names the device.
|
||||
#[schema(example = "Living Room TV")]
|
||||
label: Option<String>,
|
||||
/// Certificate validity start (unix seconds).
|
||||
not_before_unix: Option<i64>,
|
||||
/// Certificate validity end (unix seconds).
|
||||
@@ -55,27 +65,112 @@ pub(crate) async fn list_paired_clients(
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.clone();
|
||||
Json(ders.iter().map(|der| client_info(der)).collect())
|
||||
// One read of the label sidecar for the whole list, not one per row.
|
||||
let labels = crate::gamestream::load_client_labels();
|
||||
Json(ders.iter().map(|der| client_info(der, &labels)).collect())
|
||||
}
|
||||
|
||||
pub(crate) fn client_info(der: &[u8]) -> PairedClient {
|
||||
pub(crate) fn client_info(
|
||||
der: &[u8],
|
||||
labels: &std::collections::BTreeMap<String, String>,
|
||||
) -> PairedClient {
|
||||
let fingerprint = hex::encode(Sha256::digest(der));
|
||||
let label = labels.get(&fingerprint).cloned();
|
||||
match x509_parser::parse_x509_certificate(der) {
|
||||
Ok((_, x509)) => PairedClient {
|
||||
fingerprint,
|
||||
subject: Some(x509.subject().to_string()),
|
||||
not_before_unix: Some(x509.validity().not_before.timestamp()),
|
||||
not_after_unix: Some(x509.validity().not_after.timestamp()),
|
||||
label,
|
||||
fingerprint,
|
||||
},
|
||||
Err(_) => PairedClient {
|
||||
fingerprint,
|
||||
subject: None,
|
||||
not_before_unix: None,
|
||||
not_after_unix: None,
|
||||
label,
|
||||
fingerprint,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Body of `PATCH /clients/{fingerprint}` — the device's display name.
|
||||
#[derive(Deserialize, ToSchema)]
|
||||
pub(crate) struct RenameClient {
|
||||
/// The name to show for this device. `null` (or an empty/whitespace-only string) clears it and
|
||||
/// the device goes back to being listed by fingerprint alone.
|
||||
///
|
||||
/// Scrubbed before storage by the same sanitizer the native plane runs on device names:
|
||||
/// control characters and Unicode bidi overrides are stripped (they could make one paired
|
||||
/// device impersonate another in this very list), whitespace collapsed, and the result capped
|
||||
/// at 64 characters.
|
||||
#[schema(example = "Living Room TV")]
|
||||
label: Option<String>,
|
||||
}
|
||||
|
||||
/// Rename a paired client
|
||||
///
|
||||
/// Sets or clears the operator-visible display name for one paired Moonlight client. This is
|
||||
/// purely cosmetic — it touches no certificate and no trust decision — but it is the only way to
|
||||
/// tell paired devices apart: every moonlight-common-c client self-signs with the identical
|
||||
/// subject `CN=NVIDIA GameStream Client`, so an unnamed list is a row of clones distinguishable
|
||||
/// only by fingerprint. The name is stored beside the pairing store and survives host restarts;
|
||||
/// unpairing the device forgets it.
|
||||
#[utoipa::path(
|
||||
patch,
|
||||
path = "/clients/{fingerprint}",
|
||||
tag = "clients",
|
||||
operation_id = "renameClient",
|
||||
params(
|
||||
("fingerprint" = String, Path,
|
||||
description = "Hex SHA-256 fingerprint of the client certificate DER (64 chars, case-insensitive)")
|
||||
),
|
||||
request_body = RenameClient,
|
||||
responses(
|
||||
(status = OK, description = "The client as it now reads", body = PairedClient),
|
||||
(status = BAD_REQUEST, description = "Malformed fingerprint", body = ApiError),
|
||||
(status = UNAUTHORIZED, description = "Missing or invalid bearer token", body = ApiError),
|
||||
(status = NOT_FOUND, description = "No paired client with that fingerprint", body = ApiError),
|
||||
)
|
||||
)]
|
||||
pub(crate) async fn rename_client(
|
||||
State(st): State<Arc<MgmtState>>,
|
||||
Path(fingerprint): Path<String>,
|
||||
Json(body): Json<RenameClient>,
|
||||
) -> Response {
|
||||
if fingerprint.len() != 64 || !fingerprint.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return api_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"fingerprint must be the 64-char hex SHA-256 of the client certificate DER",
|
||||
);
|
||||
}
|
||||
// Only name a device that is actually paired: a label for an unknown fingerprint would be
|
||||
// invisible (nothing lists it) and would sit in the file forever, since the unpair cleanup
|
||||
// only ever removes labels whose device WAS paired.
|
||||
let paired = st.app.paired.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Some(der) = paired
|
||||
.iter()
|
||||
.find(|der| hex::encode(Sha256::digest(der)).eq_ignore_ascii_case(&fingerprint))
|
||||
.cloned()
|
||||
else {
|
||||
return api_error(
|
||||
StatusCode::NOT_FOUND,
|
||||
"no paired client with that fingerprint",
|
||||
);
|
||||
};
|
||||
drop(paired);
|
||||
// An all-whitespace name is a cleared name, not a device called " ": the sanitizer would
|
||||
// otherwise turn it into the "device <fp8>" fallback and the row would look renamed.
|
||||
let wanted = body
|
||||
.label
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty());
|
||||
crate::gamestream::set_client_label(&fingerprint, wanted);
|
||||
let labels = crate::gamestream::load_client_labels();
|
||||
(StatusCode::OK, Json(client_info(&der, &labels))).into_response()
|
||||
}
|
||||
|
||||
/// Unpair a client
|
||||
///
|
||||
/// Removes the client's certificate from the pairing store (persisted — the removal survives a
|
||||
@@ -119,6 +214,9 @@ pub(crate) async fn unpair_client(
|
||||
// restart, which now also matters below: a resurrected pairing would silently
|
||||
// re-open the control port.
|
||||
crate::gamestream::save_paired(&paired);
|
||||
// Forget this device's display name with it, so the file can't grow without bound and a
|
||||
// later re-pairing of the same certificate starts unnamed.
|
||||
crate::gamestream::retain_client_labels(&paired);
|
||||
drop(paired);
|
||||
// Revocation reaches a LIVE session too: a mid-stream client whose pairing was just
|
||||
// removed must not keep streaming until it chooses to leave. Clearing the launch makes
|
||||
@@ -187,6 +285,8 @@ pub(crate) async fn unpair_all_clients(State(st): State<Arc<MgmtState>>) -> Resp
|
||||
// Persist under the lock, as the single unpair does: a pairing resurrected by a restart would
|
||||
// silently re-open the control port.
|
||||
crate::gamestream::save_paired(&paired);
|
||||
// Nothing is paired any more, so no label can still belong to anyone.
|
||||
crate::gamestream::retain_client_labels(&paired);
|
||||
drop(paired);
|
||||
// A mid-stream client must not keep streaming once its pairing is gone. Clearing the launch
|
||||
// makes the ENet control thread send the standard TERMINATION+disconnect. (An owner-less
|
||||
|
||||
@@ -23,13 +23,16 @@ pub(crate) struct Health {
|
||||
abi_version: u32,
|
||||
}
|
||||
|
||||
/// Host identity and advertised capabilities (static for the life of the process).
|
||||
/// Host identity and advertised capabilities (static for the life of the process, except
|
||||
/// `local_ip`).
|
||||
#[derive(Serialize, ToSchema)]
|
||||
pub(crate) struct HostInfo {
|
||||
hostname: String,
|
||||
/// Stable per-host id (persisted across restarts), matched on pairing.
|
||||
uniqueid: String,
|
||||
/// Best-effort primary LAN IP.
|
||||
/// Best-effort primary LAN IP, read fresh on every request — a host that started before its
|
||||
/// network did (cold boot) reports `127.0.0.1` only until it actually has an address, and a
|
||||
/// host that moves networks reports the new one. Poll it rather than caching it.
|
||||
local_ip: String,
|
||||
/// `punktfunk-host` crate version.
|
||||
version: String,
|
||||
@@ -324,7 +327,7 @@ pub(crate) async fn get_host_info(State(st): State<Arc<MgmtState>>) -> Json<Host
|
||||
Json(HostInfo {
|
||||
hostname: h.hostname.clone(),
|
||||
uniqueid: h.uniqueid.clone(),
|
||||
local_ip: h.local_ip.to_string(),
|
||||
local_ip: h.local_ip().to_string(),
|
||||
version: env!("PUNKTFUNK_VERSION").into(),
|
||||
abi_version: punktfunk_core::ABI_VERSION,
|
||||
app_version: APP_VERSION.into(),
|
||||
|
||||
@@ -47,7 +47,6 @@ use axum::body::Body;
|
||||
use axum::http::StatusCode;
|
||||
use http_body_util::BodyExt;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
use std::sync::atomic::Ordering;
|
||||
use tower::ServiceExt;
|
||||
|
||||
@@ -73,7 +72,6 @@ fn test_state() -> Arc<AppState> {
|
||||
let host = Host {
|
||||
hostname: "test-host".into(),
|
||||
uniqueid: "deadbeef".into(),
|
||||
local_ip: IpAddr::V4(Ipv4Addr::LOCALHOST),
|
||||
http_port: HTTP_PORT,
|
||||
https_port: HTTPS_PORT,
|
||||
os_chain: "linux/arch/steamos".into(),
|
||||
@@ -821,6 +819,54 @@ async fn status_reflects_runtime_state() {
|
||||
assert!(!body.to_string().contains("gcm"));
|
||||
}
|
||||
|
||||
/// Point `PUNKTFUNK_CONFIG_DIR` at a throwaway tempdir for the body of a test, and put the previous
|
||||
/// value back on drop even if an assertion panics.
|
||||
///
|
||||
/// ONE of these for the whole file on purpose. Mutating the process environment is safe to call and
|
||||
/// unsound from a live multithreaded process, so `check-unsafe-hygiene.sh` (gate C) holds this file
|
||||
/// to a fixed count of such call sites — and counts plain prose mentions too, deliberately, since
|
||||
/// its grep is the contract. A second test that copy-pastes the dance trips it, which is exactly
|
||||
/// what it is for. This also bundles the serialization: the lock is a FIELD, so it cannot be
|
||||
/// forgotten, and `Drop::drop` runs before any field drops, meaning the environment is restored
|
||||
/// while this still holds the lock.
|
||||
struct ConfigDirOverride {
|
||||
tmp: tempfile::TempDir,
|
||||
prev: Option<std::ffi::OsString>,
|
||||
_serial: std::sync::MutexGuard<'static, ()>,
|
||||
}
|
||||
|
||||
impl ConfigDirOverride {
|
||||
fn new() -> ConfigDirOverride {
|
||||
let _serial = crate::identity::CONFIG_DIR_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let prev = std::env::var_os("PUNKTFUNK_CONFIG_DIR");
|
||||
// SAFETY: `_serial` holds CONFIG_DIR_TEST_LOCK, which serializes every test in this binary
|
||||
// that reads or writes this variable.
|
||||
unsafe { std::env::set_var("PUNKTFUNK_CONFIG_DIR", tmp.path()) };
|
||||
ConfigDirOverride { tmp, prev, _serial }
|
||||
}
|
||||
|
||||
/// The throwaway config dir itself — used verbatim by `pf_paths`, with no `punktfunk`
|
||||
/// subdirectory appended.
|
||||
fn path(&self) -> &std::path::Path {
|
||||
self.tmp.path()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ConfigDirOverride {
|
||||
fn drop(&mut self) {
|
||||
match self.prev.take() {
|
||||
// SAFETY: `self._serial` is still alive here (fields drop after `Drop::drop`), so this
|
||||
// runs under the same serialization as the `set_var` in `new`.
|
||||
Some(v) => unsafe { std::env::set_var("PUNKTFUNK_CONFIG_DIR", v) },
|
||||
// SAFETY: as above.
|
||||
None => unsafe { std::env::remove_var("PUNKTFUNK_CONFIG_DIR") },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Holding `CONFIG_DIR_TEST_LOCK` across the awaits is the POINT: the env override must cover
|
||||
// the whole test body, and `#[tokio::test]` is a single-threaded runtime — nothing else can
|
||||
// need the executor while we hold it.
|
||||
@@ -830,26 +876,7 @@ async fn paired_clients_list_and_unpair() {
|
||||
// Unpair PERSISTS (save_paired → paired.json in the config dir), so point the config dir
|
||||
// at a throwaway tempdir — this test must never rewrite the dev box's real pairing store.
|
||||
// The guard restores the previous value even if an assertion below panics.
|
||||
struct EnvGuard(Option<std::ffi::OsString>);
|
||||
impl Drop for EnvGuard {
|
||||
fn drop(&mut self) {
|
||||
match self.0.take() {
|
||||
// SAFETY: dropped while this test still holds CONFIG_DIR_TEST_LOCK, which
|
||||
// serializes every test that writes or reads this variable in the binary.
|
||||
Some(v) => unsafe { std::env::set_var("PUNKTFUNK_CONFIG_DIR", v) },
|
||||
// SAFETY: as above.
|
||||
None => unsafe { std::env::remove_var("PUNKTFUNK_CONFIG_DIR") },
|
||||
}
|
||||
}
|
||||
}
|
||||
let _serial = crate::identity::CONFIG_DIR_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let _env = EnvGuard(std::env::var_os("PUNKTFUNK_CONFIG_DIR"));
|
||||
// SAFETY: `_serial` holds CONFIG_DIR_TEST_LOCK (taken above), serializing every test that
|
||||
// writes or reads this variable in the binary.
|
||||
unsafe { std::env::set_var("PUNKTFUNK_CONFIG_DIR", tmp.path()) };
|
||||
let tmp = ConfigDirOverride::new();
|
||||
|
||||
let state = test_state();
|
||||
let app = test_app(state.clone(), None);
|
||||
@@ -1003,6 +1030,137 @@ async fn paired_clients_list_and_unpair() {
|
||||
assert_eq!(body["unpaired"], 0);
|
||||
}
|
||||
|
||||
/// Renaming a paired Moonlight client: the round trip, the scrub, the clear, and the cleanup.
|
||||
///
|
||||
/// Worth a test because the label is the ONLY thing that distinguishes two paired Moonlight
|
||||
/// devices — their certificates all carry the same subject — so "the name silently didn't stick"
|
||||
/// is indistinguishable from "the device is the other one" in the console.
|
||||
#[allow(clippy::await_holding_lock)]
|
||||
#[tokio::test]
|
||||
async fn client_label_round_trips_scrubs_and_is_forgotten_on_unpair() {
|
||||
let tmp = ConfigDirOverride::new();
|
||||
|
||||
let state = test_state();
|
||||
let app = test_app(state.clone(), None);
|
||||
let stand_in = crate::identity::ephemeral().unwrap();
|
||||
let (_, pem) = x509_parser::pem::parse_x509_pem(stand_in.cert_pem.as_bytes()).unwrap();
|
||||
let der = pem.contents.clone();
|
||||
let fingerprint = hex::encode(Sha256::digest(&der));
|
||||
{
|
||||
let mut p = state.paired.lock().unwrap();
|
||||
p.clear();
|
||||
p.push(der.clone());
|
||||
}
|
||||
|
||||
let patch = |fp: String, body: serde_json::Value| {
|
||||
axum::http::Request::patch(format!("/api/v1/clients/{fp}"))
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(body.to_string()))
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
// Unnamed until somebody names it — the field is absent, not an empty string.
|
||||
let (_, body) = send(&app, get_req("/api/v1/clients")).await;
|
||||
assert!(body[0]["label"].is_null());
|
||||
|
||||
// Name it (uppercase fingerprint must match too — the path is documented case-insensitive).
|
||||
let (status, body) = send(
|
||||
&app,
|
||||
patch(
|
||||
fingerprint.to_uppercase(),
|
||||
serde_json::json!({ "label": "Living Room TV" }),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body["label"], "Living Room TV");
|
||||
let (_, body) = send(&app, get_req("/api/v1/clients")).await;
|
||||
assert_eq!(body[0]["label"], "Living Room TV");
|
||||
|
||||
// The scrub runs: a bidi override could make one paired device read like another in the very
|
||||
// list an operator uses to decide what to unpair, and the whitespace collapse keeps the name
|
||||
// one line. (`\u{202E}` = RIGHT-TO-LEFT OVERRIDE.)
|
||||
let (_, body) = send(
|
||||
&app,
|
||||
patch(
|
||||
fingerprint.clone(),
|
||||
serde_json::json!({ "label": " Deck\u{202E}evil\n\nx " }),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["label"], "Deckevil x");
|
||||
|
||||
// Whitespace-only clears rather than storing a device called " " (or the sanitizer's
|
||||
// "device <fp8>" fallback, which would look like a successful rename).
|
||||
let (_, body) = send(
|
||||
&app,
|
||||
patch(fingerprint.clone(), serde_json::json!({ "label": " " })),
|
||||
)
|
||||
.await;
|
||||
assert!(body["label"].is_null());
|
||||
|
||||
// …and an explicit null clears too.
|
||||
send(
|
||||
&app,
|
||||
patch(
|
||||
fingerprint.clone(),
|
||||
serde_json::json!({ "label": "Bedroom" }),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let (_, body) = send(
|
||||
&app,
|
||||
patch(fingerprint.clone(), serde_json::json!({ "label": null })),
|
||||
)
|
||||
.await;
|
||||
assert!(body["label"].is_null());
|
||||
|
||||
// Malformed fingerprint → 400; unknown-but-well-formed → 404 (naming a device that is not
|
||||
// paired would write a label nothing can ever list or clean up).
|
||||
assert_eq!(
|
||||
send(
|
||||
&app,
|
||||
patch("zz".into(), serde_json::json!({ "label": "x" }))
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
assert_eq!(
|
||||
send(
|
||||
&app,
|
||||
patch("aa".repeat(32), serde_json::json!({ "label": "x" }))
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
|
||||
// Unpairing forgets the name: it must not survive to be inherited by a later re-pairing of
|
||||
// the same certificate.
|
||||
send(
|
||||
&app,
|
||||
patch(
|
||||
fingerprint.clone(),
|
||||
serde_json::json!({ "label": "Living Room TV" }),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let del = axum::http::Request::delete(format!("/api/v1/clients/{fingerprint}"))
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
assert_eq!(send(&app, del).await.0, StatusCode::NO_CONTENT);
|
||||
let on_disk: std::collections::BTreeMap<String, String> =
|
||||
std::fs::read(tmp.path().join("client-labels.json"))
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice(&b).ok())
|
||||
.unwrap_or_default();
|
||||
assert!(
|
||||
!on_disk.contains_key(&fingerprint),
|
||||
"unpair must forget the device's label, got {on_disk:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "gamestream")]
|
||||
#[tokio::test]
|
||||
async fn submit_pin_validates_and_requires_pending_pairing() {
|
||||
@@ -1380,6 +1538,12 @@ fn every_route_is_classified_for_the_plugin_and_cert_lanes() {
|
||||
// roster's read permission must never carry over to emptying it.
|
||||
("DELETE", "/api/v1/clients", false, false),
|
||||
("DELETE", "/api/v1/clients/{fingerprint}", false, false),
|
||||
// Renaming is cosmetic but NOT harmless, so it takes the same lanes as removal rather than
|
||||
// the roster's read permission: the label is the only thing distinguishing one paired
|
||||
// Moonlight device from another in the console, so anything that could set it could dress
|
||||
// its own device up as the operator's TV — and be trusted, or spared an unpair, on that
|
||||
// basis. Sharing a path with the plugin-forbidden DELETE, it needs its own row anyway.
|
||||
("PATCH", "/api/v1/clients/{fingerprint}", false, false),
|
||||
("GET", "/api/v1/native/clients", true, false),
|
||||
("DELETE", "/api/v1/native/clients", false, false),
|
||||
(
|
||||
|
||||
@@ -156,9 +156,33 @@ pub struct Punktfunk1Options {
|
||||
/// the client's reported address, no hole-punch"; `false` (random port, or a busy fixed port) means
|
||||
/// "hole-punch". The socket is held from the handshake through streaming — no drop-then-rebind
|
||||
/// window in which a concurrent session could steal a fixed port.
|
||||
fn bind_data_socket(data_port: Option<u16>) -> std::io::Result<(std::net::UdpSocket, bool)> {
|
||||
///
|
||||
/// `local_ip` is the address the client's QUIC connection was RECEIVED on (`Connection::local_ip`),
|
||||
/// and binding to it is load-bearing on a multi-homed host. The client's data socket is
|
||||
/// `connect`ed to the host IP it dialed, so its kernel accepts video only from THAT source
|
||||
/// address; a wildcard bind here lets the routing table pick the egress interface independently of
|
||||
/// the one the control plane arrived on, and the two differ whenever a host has two paths to the
|
||||
/// client — Ethernet and Wi-Fi both up on the same LAN is the everyday case. Every video datagram
|
||||
/// is then dropped by the client's kernel before userspace: nothing counts it, `loss_ppm` stays 0
|
||||
/// (no packets, no gaps), the hole-punch still arrives so the host logs `punched=true`, and the
|
||||
/// control plane — which quinn pins to the right local address — stays perfectly healthy. That is
|
||||
/// the "connects fine, black screen forever" shape with every gauge green, and it is invisible on
|
||||
/// both ends. `None` (platform can't report it) or a bind failure falls back to the wildcard.
|
||||
fn bind_data_socket(
|
||||
data_port: Option<u16>,
|
||||
local_ip: Option<std::net::IpAddr>,
|
||||
) -> std::io::Result<(std::net::UdpSocket, bool)> {
|
||||
// An IPv4-mapped v6 local address (dual-stack endpoint) must be unmapped before it can bind a
|
||||
// socket that will `connect` to a v4 peer — the families have to match.
|
||||
let local_ip = local_ip.map(|ip| match ip {
|
||||
std::net::IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(ip, std::net::IpAddr::V4),
|
||||
v4 => v4,
|
||||
});
|
||||
let wildcard = |ip: Option<std::net::IpAddr>| {
|
||||
ip.unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED))
|
||||
};
|
||||
if let Some(p) = data_port.filter(|p| *p != 0) {
|
||||
match std::net::UdpSocket::bind(("0.0.0.0", p)) {
|
||||
match std::net::UdpSocket::bind((wildcard(local_ip), p)) {
|
||||
Ok(sock) => return Ok((sock, true)),
|
||||
Err(e) => tracing::warn!(
|
||||
data_port = p,
|
||||
@@ -168,7 +192,23 @@ fn bind_data_socket(data_port: Option<u16>) -> std::io::Result<(std::net::UdpSoc
|
||||
),
|
||||
}
|
||||
}
|
||||
Ok((std::net::UdpSocket::bind("0.0.0.0:0")?, false))
|
||||
match std::net::UdpSocket::bind((wildcard(local_ip), 0)) {
|
||||
Ok(sock) => Ok((sock, false)),
|
||||
// The control plane arrived on this address moments ago, so a failure here means it just
|
||||
// went away (an adapter dropped mid-handshake). The wildcard still reaches a client the
|
||||
// routing table can route to — degraded, not dead — so take it and say why.
|
||||
Err(e) if local_ip.is_some() => {
|
||||
tracing::warn!(
|
||||
local_ip = ?local_ip,
|
||||
error = %e,
|
||||
"could not bind the data plane to the address the control connection arrived on \
|
||||
— falling back to the wildcard. On a multi-homed host video may now egress from \
|
||||
a different interface than the client dialed, which it silently drops."
|
||||
);
|
||||
Ok((std::net::UdpSocket::bind("0.0.0.0:0")?, false))
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// The native (punktfunk/1) trust store + on-demand arming PIN, shared with the management API.
|
||||
@@ -365,7 +405,6 @@ pub(crate) async fn serve(
|
||||
match crate::gamestream::Host::detect() {
|
||||
Ok(h) => crate::discovery::advertise_native(
|
||||
&h.hostname,
|
||||
h.local_ip,
|
||||
opts.port,
|
||||
&fingerprint_hex(&fingerprint),
|
||||
opts.require_pairing,
|
||||
@@ -2057,6 +2096,10 @@ async fn serve_session(
|
||||
// stages ride the same per-session trace; resizes write their totals into the shared slot.
|
||||
let bringup_dp = bringup.clone();
|
||||
let resize_ms_dp = resize_ms.clone();
|
||||
// The address the control connection arrived on, for the data plane's source-address check
|
||||
// below — the one comparison that distinguishes "the client is filtering our video" from
|
||||
// "the video never left". Captured here because the send loop runs on a blocking thread.
|
||||
let control_local_ip = conn.local_ip();
|
||||
let result: Result<()> = async {
|
||||
let stream_thread = tokio::task::spawn_blocking(move || -> Result<()> {
|
||||
// Bring up the (already-bound) data-plane socket. Default: hole-punch — wait briefly
|
||||
@@ -2091,15 +2134,44 @@ async fn serve_session(
|
||||
}
|
||||
};
|
||||
bringup_dp.mark("punch_done");
|
||||
// Post-`connect`, `local_addr` reports the source address the kernel will actually
|
||||
// stamp on every video datagram — the number that has to match the host IP the client
|
||||
// dialed, because its data socket is connected and its kernel drops anything else
|
||||
// before userspace. Logged unconditionally: a black-screen report is unanswerable
|
||||
// without it (this session's showed only the port).
|
||||
let local = transport.local_addr().ok();
|
||||
tracing::info!(
|
||||
%client_udp,
|
||||
udp_port,
|
||||
direct,
|
||||
punched,
|
||||
local = ?local,
|
||||
"data plane bound (direct=true → fixed --data-port, streaming to the reported \
|
||||
address with no hole-punch; else punched=true → the client's observed source, \
|
||||
false → no punch seen, the reported address)"
|
||||
);
|
||||
// A video source address that isn't the one the control plane arrived on means the
|
||||
// client will discard every datagram we send, however healthy this end looks.
|
||||
if let (Some(l), Some(c)) = (local.map(|a| a.ip()), control_local_ip) {
|
||||
let c = match c {
|
||||
std::net::IpAddr::V6(v6) => {
|
||||
v6.to_ipv4_mapped().map_or(c, std::net::IpAddr::V4)
|
||||
}
|
||||
v4 => v4,
|
||||
};
|
||||
if !l.is_unspecified() && l != c {
|
||||
tracing::warn!(
|
||||
video_source_ip = %l,
|
||||
control_local_ip = %c,
|
||||
"the video data plane egresses from a DIFFERENT host address than the one \
|
||||
this client connected to — its data socket is connected to the address it \
|
||||
dialed, so its kernel drops every video datagram before userspace: black \
|
||||
screen, zero reported loss, healthy control plane. Usual cause is two \
|
||||
live paths to the client (Ethernet and Wi-Fi both up on the same LAN, or \
|
||||
a VPN/overlay adapter claiming the route)"
|
||||
);
|
||||
}
|
||||
}
|
||||
// A punch that never arrives is not a routine fallback — it is the fingerprint of a
|
||||
// data port the client cannot reach INBOUND, and every client punches (5/s for the
|
||||
// first three seconds, then every two). Video then goes to an address the client only
|
||||
@@ -2515,7 +2587,7 @@ mod tests {
|
||||
// No fixed port (and the explicit-0 alias) → a random ephemeral port, and NOT direct: the
|
||||
// caller hole-punches.
|
||||
for req in [None, Some(0)] {
|
||||
let (sock, direct) = bind_data_socket(req).expect("bind random data socket");
|
||||
let (sock, direct) = bind_data_socket(req, None).expect("bind random data socket");
|
||||
assert!(!direct, "req={req:?} must hole-punch, not stream direct");
|
||||
assert_ne!(sock.local_addr().unwrap().port(), 0);
|
||||
}
|
||||
@@ -2532,13 +2604,14 @@ mod tests {
|
||||
.port();
|
||||
|
||||
// A free fixed port binds exactly it, in DIRECT mode (no hole-punch).
|
||||
let (held, direct) = bind_data_socket(Some(free)).expect("bind fixed data socket");
|
||||
let (held, direct) = bind_data_socket(Some(free), None).expect("bind fixed data socket");
|
||||
assert!(direct, "a fixed --data-port must stream direct");
|
||||
assert_eq!(held.local_addr().unwrap().port(), free);
|
||||
|
||||
// While it's held, a second session on the same fixed port can't bind it → it must fall
|
||||
// back to a random port + hole-punch rather than fail (so concurrency never regresses).
|
||||
let (fallback, direct2) = bind_data_socket(Some(free)).expect("busy fixed port falls back");
|
||||
let (fallback, direct2) =
|
||||
bind_data_socket(Some(free), None).expect("busy fixed port falls back");
|
||||
assert!(!direct2, "a busy fixed port must fall back to hole-punch");
|
||||
assert_ne!(
|
||||
fallback.local_addr().unwrap().port(),
|
||||
@@ -2547,6 +2620,30 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The multi-homed black screen: video must egress from the address the client's control
|
||||
/// connection arrived on, because the client's data socket is connected to the host address it
|
||||
/// dialed and its kernel drops every datagram from any other source — silently, before
|
||||
/// userspace, so nothing on either end counts it. A wildcard bind here lets the routing table
|
||||
/// choose a different interface whenever the host has two paths to the client.
|
||||
#[test]
|
||||
fn data_socket_binds_the_address_the_control_plane_arrived_on() {
|
||||
let loopback = std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST);
|
||||
let (sock, direct) =
|
||||
bind_data_socket(None, Some(loopback)).expect("bind pinned data socket");
|
||||
assert!(!direct);
|
||||
assert_eq!(sock.local_addr().unwrap().ip(), loopback);
|
||||
|
||||
// An IPv4-mapped v6 local address (a dual-stack QUIC endpoint reports one) has to be
|
||||
// unmapped, or the socket binds v6 and can never `connect` to the v4 client.
|
||||
let mapped = std::net::IpAddr::V6(std::net::Ipv4Addr::LOCALHOST.to_ipv6_mapped());
|
||||
let (sock, _) = bind_data_socket(None, Some(mapped)).expect("bind mapped data socket");
|
||||
assert_eq!(sock.local_addr().unwrap().ip(), loopback);
|
||||
|
||||
// No reported local address (platform can't say) keeps the old wildcard behaviour.
|
||||
let (sock, _) = bind_data_socket(None, None).expect("bind wildcard data socket");
|
||||
assert!(sock.local_addr().unwrap().ip().is_unspecified());
|
||||
}
|
||||
|
||||
/// Freeze the gamepad wire contract: every button bit + axis id pinned to its exact value in
|
||||
/// `punktfunk_core::input::gamepad` — the single source both the punktfunk/1 native wire and the
|
||||
/// GameStream/Limelight wire read from (they are one and the same). Renumbering a bit in core
|
||||
|
||||
@@ -780,7 +780,9 @@ pub(super) async fn negotiate(
|
||||
// bind→read→drop→rebind window a concurrent session could race for a fixed port). A fixed
|
||||
// `--data-port` yields `direct = true` (stream straight to the client's reported address,
|
||||
// no punch-wait); otherwise a random ephemeral port + hole-punch.
|
||||
let (data_sock, direct) = bind_data_socket(data_port)?;
|
||||
// Bound to the address THIS connection arrived on, not the wildcard: the client only accepts
|
||||
// video from the host IP it dialed (see `bind_data_socket`).
|
||||
let (data_sock, direct) = bind_data_socket(data_port, conn.local_ip())?;
|
||||
let udp_port = data_sock.local_addr()?.port();
|
||||
|
||||
// The session's video geometry (see the `shard_payload` field below). Resolved before the
|
||||
|
||||
@@ -1875,6 +1875,14 @@ pub(super) fn virtual_stream(ctx: SessionContext, prepared: Option<PreparedDispl
|
||||
mut cur_display_gen,
|
||||
built_bitrate,
|
||||
) = pipe;
|
||||
// What `enc` was opened against. The capture source can change format/size UNDER this loop with
|
||||
// no client `Reconfigure` at all — the IDD-push capturer re-opens its ring on a confirmed
|
||||
// display-descriptor change (a fullscreen game mode-setting the virtual display, an HDR flip) —
|
||||
// and every backend's `submit` then refuses the frame. Tracked so the loop can FOLLOW the
|
||||
// source (see the guard in the submit path) instead of dying against an error no in-place
|
||||
// encoder reset can fix. Every site below that swaps `enc` re-binds `frame` with it, so this is
|
||||
// always `(frame.format, frame.width, frame.height)` immediately after one.
|
||||
let mut enc_src = (frame.format, frame.width, frame.height);
|
||||
// The display exists now, so the portal has answered: settle the cursor plan against what it
|
||||
// actually negotiated rather than what this session asked for (see `settle_portal_cursor`).
|
||||
// `mut`: every capture-loss rebuild re-runs `create`, hence re-negotiates.
|
||||
@@ -2613,6 +2621,7 @@ pub(super) fn virtual_stream(ctx: SessionContext, prepared: Option<PreparedDispl
|
||||
);
|
||||
cur_mode = new_mode;
|
||||
next = std::time::Instant::now();
|
||||
enc_src = (frame.format, frame.width, frame.height);
|
||||
// H2/H3: the backend may have honored a different mode than requested — KWin caps
|
||||
// a virtual output's refresh, or Windows pf-vdisplay rejects a resolution its
|
||||
// running monitor doesn't advertise and the host falls back to the actual display
|
||||
@@ -2695,6 +2704,7 @@ pub(super) fn virtual_stream(ctx: SessionContext, prepared: Option<PreparedDispl
|
||||
trace.as_ref(),
|
||||
true,
|
||||
) {
|
||||
enc_src = (frame.format, frame.width, frame.height);
|
||||
// The owed AUs died with the old encoder — same bookkeeping as a resize.
|
||||
inflight.clear();
|
||||
last_au_at = std::time::Instant::now();
|
||||
@@ -3034,11 +3044,19 @@ pub(super) fn virtual_stream(ctx: SessionContext, prepared: Option<PreparedDispl
|
||||
counted here, so the picture is black and every keyframe we force is \
|
||||
wasted. The control plane is healthy (this report arrived on it), so \
|
||||
the session looks alive: audio, input and the library keep working. \
|
||||
This is a PATH problem, not decode — check that inbound UDP to this \
|
||||
host's per-session data port is allowed (the 'data plane bound' line \
|
||||
above shows `punched=false` when the client's hole-punch never \
|
||||
arrived, which is the fingerprint), and that no other host or \
|
||||
firewall is intercepting it"
|
||||
READ THE 'data plane bound' LINE ABOVE — it says which leg failed, \
|
||||
and this line cannot. `punched=false`: the client's hole-punch never \
|
||||
arrived, so inbound UDP to this host's per-session data port is \
|
||||
blocked — open it (the ports are ephemeral, so the rule must be \
|
||||
program-scoped, not port-scoped). `punched=true`: inbound is FINE and \
|
||||
the failure is on the return leg — compare that line's `local=` \
|
||||
source address against the host address this client dialed, because \
|
||||
its data socket is connected and its kernel silently drops video from \
|
||||
any other source. If those match, the datagrams left this host \
|
||||
correctly and the client either never received them (a hop on the \
|
||||
path) or received them and could not open them: this counter is \
|
||||
incremented AFTER decrypt and replay checks, so a session whose every \
|
||||
datagram failed to open reports exactly this same zero"
|
||||
);
|
||||
} else if matches_client_recovery_cooldown(period) {
|
||||
if client_rx == u32::MAX {
|
||||
@@ -3380,6 +3398,7 @@ pub(super) fn virtual_stream(ctx: SessionContext, prepared: Option<PreparedDispl
|
||||
interval = new_interval;
|
||||
cur_node_id = new_node_id;
|
||||
cur_display_gen = new_display_gen;
|
||||
enc_src = (frame.format, frame.width, frame.height);
|
||||
// The rebuild re-ran `create`, so the portal answered again — possibly a different
|
||||
// backend's portal (the retarget above), possibly with a different verdict. Settle
|
||||
// the cursor plan against THIS display, exactly as bring-up did: the retarget arm
|
||||
@@ -3642,6 +3661,106 @@ pub(super) fn virtual_stream(ctx: SessionContext, prepared: Option<PreparedDispl
|
||||
// exactly that volume, so host apps already tone-mapped the content into it and the honest
|
||||
// mastering description IS the client's panel. (The IDD capturer only knows the generic
|
||||
// baseline; if the driver ever forwards per-content IDDCX_HDR10_METADATA, prefer that here.)
|
||||
// Follow an AUTONOMOUS source change — one no client `Reconfigure` announced. The IDD-push
|
||||
// capturer re-opens its ring on a confirmed display-descriptor change: a fullscreen game
|
||||
// mode-setting the virtual display (2026-08-22 field report: a 4K60 HEVC session, the game
|
||||
// switched the display to 1080p mid-play), or an HDR flip changing the frame format. The
|
||||
// encoder is the one component that cannot follow that in place (same note as
|
||||
// `try_inplace_resize`), so every `submit` below refuses the frame — and the submit-error
|
||||
// path only rebuilds the encoder IN PLACE, at the SAME configured size, which cannot fix a
|
||||
// size the source has already left. All five resets burn on it and the session ends while
|
||||
// audio keeps running. Reopen at what the source actually delivers instead; the client
|
||||
// learns the new mode from the `Reconfigured` below and its decoder from the opening IDR.
|
||||
if enc_src != (frame.format, frame.width, frame.height) {
|
||||
let actual = delivered_mode(frame.width, frame.height, interval);
|
||||
// Same per-mode pin the client-initiated resize re-resolves: PyroWave's Automatic rate
|
||||
// IS a function of the mode, so carrying the old one across a source-driven mode change
|
||||
// hands it the wrong operating point. H.26x rates are mode-independent (ABR owns them),
|
||||
// and an explicit client rate is never second-guessed.
|
||||
let src_kbps = if bitrate_auto && plan.codec == crate::encode::Codec::PyroWave {
|
||||
resolve_bitrate_kbps_for(plan.codec, 0, &actual, plan.chroma, plan.bit_depth)
|
||||
} else {
|
||||
bitrate_kbps
|
||||
};
|
||||
let opened = crate::encode::open_video(
|
||||
plan.codec,
|
||||
frame.format,
|
||||
frame.width,
|
||||
frame.height,
|
||||
actual.refresh_hz,
|
||||
src_kbps as u64 * 1000,
|
||||
frame.is_cuda(),
|
||||
bit_depth,
|
||||
plan.chroma,
|
||||
plan.cursor_blend,
|
||||
plan.max_slices,
|
||||
)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"the capture source changed to {}x{} {:?} mid-session and the encoder could not \
|
||||
be reopened at it",
|
||||
frame.width, frame.height, frame.format
|
||||
)
|
||||
});
|
||||
let mut new_enc = match opened {
|
||||
Ok(e) => e,
|
||||
Err(e) => {
|
||||
// Don't spend the session on the FIRST failed open. The mode-set that triggered
|
||||
// this is exactly the kind of event that leaves the driver settling — the same
|
||||
// transient the submit path's backoff exists for ("NVENC session open failing
|
||||
// after a codec switch", 2026-07) — so spend the shared reset budget on it at
|
||||
// the same exponential pace, re-entering this guard each round. The old encoder
|
||||
// is still installed and still mismatched; it simply keeps failing submit until
|
||||
// an open succeeds or the budget runs out.
|
||||
encoder_resets += 1;
|
||||
if encoder_resets > MAX_ENCODER_RESETS {
|
||||
return Err(e).context("encoder reopen at the source's new mode");
|
||||
}
|
||||
let backoff = std::cmp::max(
|
||||
interval,
|
||||
std::time::Duration::from_millis(100u64 << (encoder_resets - 1).min(4)),
|
||||
);
|
||||
tracing::warn!(error = %format!("{e:#}"), reset = encoder_resets,
|
||||
max = MAX_ENCODER_RESETS,
|
||||
"reopening the encoder at the source's new mode failed — retrying");
|
||||
next = std::time::Instant::now() + backoff;
|
||||
std::thread::sleep(backoff);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Some(c) = plan.wire_chunk {
|
||||
new_enc.set_wire_chunking(c);
|
||||
}
|
||||
// A rebuilt encoder starts with the ring bound unset — re-report it, as every other
|
||||
// rebuild site does, or an in-place backend can encode a texture the capturer has
|
||||
// already rotated and overwritten.
|
||||
new_enc.set_input_ring_depth(capturer.pipeline_depth().max(1));
|
||||
tracing::info!(
|
||||
from = %format!("{}x{} {:?}", enc_src.1, enc_src.2, enc_src.0),
|
||||
to = %format!("{}x{} {:?}", frame.width, frame.height, frame.format),
|
||||
"the capture source changed mode mid-session with no client reconfigure — reopened \
|
||||
the encoder at the delivered size"
|
||||
);
|
||||
enc = new_enc;
|
||||
enc_src = (frame.format, frame.width, frame.height);
|
||||
adopt_built_bitrate(&mut bitrate_kbps, src_kbps, &live_bitrate, &retarget_tx);
|
||||
// The owed AUs died with the old encoder — same bookkeeping as a resize.
|
||||
inflight.clear();
|
||||
last_au_at = std::time::Instant::now();
|
||||
encoder_resets = 0;
|
||||
// A fresh encoder opens on an IDR — anchor the cooldown.
|
||||
last_forced_idr = Some(std::time::Instant::now());
|
||||
// The client's mode slot still says the old size, and its stats/aspect follow it.
|
||||
// Publish what it is really decoding now, exactly as an accepted resize does.
|
||||
live_mode.store(
|
||||
pack_mode(actual.width, actual.height, actual.refresh_hz),
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
let _ = reconfig_result_tx.send(Reconfigured {
|
||||
accepted: true,
|
||||
mode: actual,
|
||||
});
|
||||
}
|
||||
let hdr_meta = capturer.hdr_meta().map(|m| client_hdr.unwrap_or(m));
|
||||
enc.set_hdr_meta(hdr_meta);
|
||||
let mut resend_meta = hdr_meta != last_hdr_meta;
|
||||
|
||||
@@ -87,6 +87,26 @@ pub fn resolve(pid: u32) -> Option<ProcRef> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Short names for the processes a lease adopted, in `procs` order.
|
||||
///
|
||||
/// Diagnostics only — nothing decides anything on these, and they are deliberately not part of
|
||||
/// [`ProcRef`], which is compared for equality. They exist because a launch that adopted the game
|
||||
/// and a launch that adopted a *pre-launch* tree logged identically (`procs=1`), which is what left
|
||||
/// the 2026-08-22 field report unclosable from its log: the one question worth asking of that line
|
||||
/// is which process the lease latched onto.
|
||||
pub fn names(procs: &[ProcRef]) -> Vec<String> {
|
||||
#[cfg(any(target_os = "linux", windows))]
|
||||
{
|
||||
let scanner = Scanner::system();
|
||||
procs.iter().map(|p| scanner.name_of(*p)).collect()
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", windows)))]
|
||||
{
|
||||
let _ = procs;
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// An out-of-band opinion on whether a spec's game is still running, independent of the process scan.
|
||||
///
|
||||
/// Consulted **only to veto** declaring a game gone — never to declare it running, and never as the
|
||||
|
||||
@@ -126,6 +126,14 @@ impl Scanner {
|
||||
Some(ProcRef { pid, start })
|
||||
}
|
||||
|
||||
/// This process's `comm` — its short name, as `ps` shows it. Diagnostics only (see
|
||||
/// [`super::names`]); `?` for a process that has already gone, which is routine.
|
||||
pub fn name_of(&self, p: ProcRef) -> String {
|
||||
std::fs::read_to_string(self.root.join(p.pid.to_string()).join("comm"))
|
||||
.map(|s| s.trim().to_string())
|
||||
.unwrap_or_else(|_| "?".into())
|
||||
}
|
||||
|
||||
/// Which of `procs` are still the same live processes — pid present **and** start time unchanged,
|
||||
/// so a recycled pid is never reported alive (rule 2).
|
||||
pub fn alive(&self, procs: &[ProcRef]) -> Vec<ProcRef> {
|
||||
@@ -180,16 +188,29 @@ impl Scanner {
|
||||
if let Some(tok) = steam_tok {
|
||||
// Both tokens together, exact-matched, so `AppId=57` never satisfies appid 570 and
|
||||
// Steam's own (non-reaper) helper steps aren't mistaken for the game.
|
||||
//
|
||||
// …with one exception, because the reaper is *not* only the game's: Steam wraps its
|
||||
// shader pre-caching for a title in the same `SteamLaunch AppId=<appid>` reaper it
|
||||
// wraps the game in, so that job satisfies this recipe exactly while the game has
|
||||
// not started yet. Adopting it points the lease at a tree that exits when the
|
||||
// compile finishes, which reads as the game exiting — on Linux that dropped a
|
||||
// Rocket League stream 10 s into a launch, mid-"Processing Vulkan shaders", and the
|
||||
// player had to launch a second time to get a session that stayed up (field report
|
||||
// 2026-08-22). The payload names itself: `fossilize_replay` is Steam's replayer and
|
||||
// is never a game.
|
||||
let mut launch = false;
|
||||
let mut appid = false;
|
||||
let mut shader = false;
|
||||
for arg in cmdline.split(|&b| b == 0) {
|
||||
if arg == b"SteamLaunch" {
|
||||
launch = true;
|
||||
} else if arg == tok.as_bytes() {
|
||||
appid = true;
|
||||
} else if program_name(arg) == b"fossilize_replay" {
|
||||
shader = true;
|
||||
}
|
||||
}
|
||||
if launch && appid {
|
||||
if launch && appid && !shader {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -247,6 +268,15 @@ impl Scanner {
|
||||
}
|
||||
}
|
||||
|
||||
/// The last `/`-separated component of an argv entry — the program's own name, when the entry is a
|
||||
/// path to one. Bytes rather than `str` because an argv entry is not required to be UTF-8.
|
||||
fn program_name(arg: &[u8]) -> &[u8] {
|
||||
match arg.iter().rposition(|&b| b == b'/') {
|
||||
Some(i) => &arg[i + 1..],
|
||||
None => arg,
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a `/proc` blob with a hard size cap (see [`MAX_PROC_BLOB`]). `None` when the process vanished
|
||||
/// or the file is unreadable — both routine during a scan.
|
||||
fn read_capped(path: &Path) -> Option<Vec<u8>> {
|
||||
@@ -472,6 +502,42 @@ mod tests {
|
||||
assert_eq!(pids(s.find(&DetectSpec::steam(57), None)), vec![31]);
|
||||
}
|
||||
|
||||
/// The 2026-08-22 field report: Steam's **shader pre-caching** runs under the game's own
|
||||
/// `SteamLaunch AppId=` reaper, so it satisfies the appid recipe while the game has not started.
|
||||
///
|
||||
/// Adopting it is what dropped a Rocket League stream 10 s into a launch — the lease called that
|
||||
/// tree the game, and its exit (the compile finishing) the game exiting. The reaper's payload is
|
||||
/// the whole tell, and it is only ever Steam's replayer.
|
||||
#[test]
|
||||
fn steam_shader_pre_caching_is_not_the_game() {
|
||||
let td = fake_proc_root(
|
||||
1000.0,
|
||||
&[
|
||||
// The shader job for this very appid — the game is still being brought up.
|
||||
FakeProc::new(35, 50_000).cmdline(&[
|
||||
"/home/p/.steam/ubuntu12_32/reaper",
|
||||
"SteamLaunch",
|
||||
"AppId=252950",
|
||||
"--",
|
||||
"/home/p/.steam/steamapps/common/SteamLinuxRuntime/fossilize_replay",
|
||||
"/home/p/.steam/steamapps/shadercache/252950/fozpipelinesv6/steamapprun_pipeline_cache.foz",
|
||||
]),
|
||||
// The game itself, same appid, same reaper. This one IS the game.
|
||||
FakeProc::new(36, 50_000).cmdline(&[
|
||||
"/home/p/.steam/ubuntu12_32/reaper",
|
||||
"SteamLaunch",
|
||||
"AppId=252950",
|
||||
"--",
|
||||
"/home/p/.steam/steamapps/common/Proton/proton",
|
||||
"waitforexitandrun",
|
||||
"/home/p/.steam/steamapps/common/rocketleague/RocketLeague.exe",
|
||||
]),
|
||||
],
|
||||
);
|
||||
let s = scanner(td.path());
|
||||
assert_eq!(pids(s.find(&DetectSpec::steam(252_950), None)), vec![36]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_env_marker_by_exact_value_or_presence() {
|
||||
let td = fake_proc_root(
|
||||
|
||||
@@ -120,6 +120,14 @@ impl Scanner {
|
||||
Some(ProcRef { pid, start })
|
||||
}
|
||||
|
||||
/// This process's image file name. Diagnostics only (see [`super::names`]); `?` for a process
|
||||
/// that has already gone or cannot be opened, which is routine.
|
||||
pub fn name_of(&self, p: ProcRef) -> String {
|
||||
process_start_and_image(p.pid)
|
||||
.and_then(|(_, image)| image.file_name().map(|n| n.to_string_lossy().into_owned()))
|
||||
.unwrap_or_else(|| "?".into())
|
||||
}
|
||||
|
||||
/// Which of `procs` are still the same live processes — pid present **and** creation time
|
||||
/// unchanged, so a recycled pid is never reported alive (rule 2). Windows reuses pids briskly, so
|
||||
/// this check is what makes signalling a remembered pid safe at all.
|
||||
|
||||
@@ -770,8 +770,24 @@ fn web_setup(args: &[String]) -> Result<()> {
|
||||
// (security-review 2026-08-05 H-3). Same host, same certificate, different port — which is
|
||||
// what makes it a different origin to the browser while staying same-site for the session
|
||||
// cookie. Without this rule, plugin interfaces simply do not load from another device.
|
||||
// Both rules are scoped to the bundled bun binary that actually listens on them, not left
|
||||
// open to any program: a port-only `dir=in action=allow` rule admits whatever binds the port
|
||||
// first, needs no elevation to do so, and suppresses the Windows prompt that would otherwise
|
||||
// be the only way in (see `service::fw_add_rule_args`). The console child is
|
||||
// `<app>/bun/bun.exe` — the same path `service.rs`'s supervisor spawns — so the rule follows
|
||||
// it. If that binary isn't there, fall back to the port-only rule rather than leaving the
|
||||
// console unreachable, and say which happened.
|
||||
let fw_profile =
|
||||
crate::service::firewall_profile_arg(crate::service::allow_public_network(args)?);
|
||||
let bun = app_dir.join("bun").join("bun.exe");
|
||||
let program = bun.exists().then_some(bun.as_path());
|
||||
if program.is_none() {
|
||||
eprintln!(
|
||||
"warning: {} not found — the console firewall rules stay open to any program on those \
|
||||
ports instead of only the console",
|
||||
bun.display()
|
||||
);
|
||||
}
|
||||
for (name, port) in [
|
||||
("Punktfunk web console (TCP 47992)", "47992"),
|
||||
("Punktfunk plugin UIs (TCP 47993)", "47993"),
|
||||
@@ -786,21 +802,13 @@ fn web_setup(args: &[String]) -> Result<()> {
|
||||
&format!("name={name}"),
|
||||
],
|
||||
);
|
||||
if !run_quiet(
|
||||
"netsh",
|
||||
&[
|
||||
"advfirewall",
|
||||
"firewall",
|
||||
"add",
|
||||
"rule",
|
||||
&format!("name={name}"),
|
||||
"dir=in",
|
||||
"action=allow",
|
||||
"protocol=TCP",
|
||||
&format!("localport={port}"),
|
||||
fw_profile,
|
||||
],
|
||||
) {
|
||||
if !crate::service::run_netsh(&crate::service::fw_add_rule_args(
|
||||
name,
|
||||
"TCP",
|
||||
Some(port),
|
||||
program,
|
||||
fw_profile,
|
||||
)) {
|
||||
eprintln!("warning: could not add the firewall rule for TCP {port}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1550,14 +1550,79 @@ pub(crate) fn allow_public_network(args: &[String]) -> Result<bool> {
|
||||
Ok(fw_public_marker().exists())
|
||||
}
|
||||
|
||||
/// Build the `netsh advfirewall firewall add rule` argument vector for one inbound allow rule.
|
||||
///
|
||||
/// `program` is the whole point of this helper existing. A `dir=in action=allow` rule carrying only
|
||||
/// `localport=` admits **any process on the machine** on those ports, and binding a high port on
|
||||
/// Windows needs no elevation — so such a rule is a standing hole that any unprivileged program can
|
||||
/// step into simply by binding first, and it does so *silently*, because our rule is exactly what
|
||||
/// suppresses the "Allow this app to communicate on…" prompt Windows would otherwise raise (that
|
||||
/// prompt is the UAC gate; without a matching rule there is no way in without one). Naming the
|
||||
/// owning executable keeps the ports open for punktfunk and no one else. Reported by a user on
|
||||
/// 2026-08-21, and correct: the fixed rules were the last any-program ones we shipped.
|
||||
///
|
||||
/// `ports` stays alongside it rather than being replaced by it — program AND port is strictly
|
||||
/// tighter than either alone, and it is only ever dropped where the port genuinely cannot be known
|
||||
/// in advance ([`add_data_plane_firewall_rule`], whose port is ephemeral per session).
|
||||
///
|
||||
/// `None` for `program` reproduces the old any-program rule, and every caller falls back to it
|
||||
/// rather than skipping the rule when it cannot resolve its executable: a looser rule still streams,
|
||||
/// no rule at all is a black screen.
|
||||
pub(crate) fn fw_add_rule_args(
|
||||
name: &str,
|
||||
proto: &str,
|
||||
ports: Option<&str>,
|
||||
program: Option<&std::path::Path>,
|
||||
profile: &str,
|
||||
) -> Vec<String> {
|
||||
let mut args: Vec<String> = ["advfirewall", "firewall", "add", "rule"]
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
args.push(format!("name={name}"));
|
||||
args.push("dir=in".into());
|
||||
args.push("action=allow".into());
|
||||
args.push(format!("protocol={proto}"));
|
||||
if let Some(p) = ports {
|
||||
args.push(format!("localport={p}"));
|
||||
}
|
||||
if let Some(exe) = program {
|
||||
args.push(format!("program={}", exe.display()));
|
||||
}
|
||||
args.push(profile.to_string());
|
||||
args
|
||||
}
|
||||
|
||||
/// [`run_quiet`] for an arg vector built by [`fw_add_rule_args`].
|
||||
pub(crate) fn run_netsh(args: &[String]) -> bool {
|
||||
let borrowed: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
run_quiet("netsh", &borrowed)
|
||||
}
|
||||
|
||||
/// Inbound firewall rules for the streaming + mgmt ports (best-effort; logs but never fails the
|
||||
/// install). Scoped by [`firewall_profile_arg`]: Domain + Private by default, all profiles when
|
||||
/// `allow_public`. TCP 47990 is deliberate: `serve` binds the mgmt/library REST API to all interfaces
|
||||
/// so paired clients can browse the game library over mTLS, and off-loopback `mgmt::require_auth`
|
||||
/// exposes only the read-only status/library allowlist to a paired client cert — the bearer-token
|
||||
/// admin surface stays loopback-only regardless of the bind — so opening it adds no admin exposure.
|
||||
/// `allow_public`, and — since 2026-08-21 — to this host executable, so the ports below are open to
|
||||
/// punktfunk rather than to anything on the machine that binds them first (see
|
||||
/// [`fw_add_rule_args`]). TCP 47990 is deliberate: `serve` binds the mgmt/library REST API to all
|
||||
/// interfaces so paired clients can browse the game library over mTLS, and off-loopback
|
||||
/// `mgmt::require_auth` exposes only the read-only status/library allowlist to a paired client cert
|
||||
/// — the bearer-token admin surface stays loopback-only regardless of the bind — so opening it adds
|
||||
/// no admin exposure.
|
||||
fn add_firewall_rules(allow_public: bool) {
|
||||
let profile = firewall_profile_arg(allow_public);
|
||||
// Resolved once and shared with the data-plane rule below. `service install` re-runs this whole
|
||||
// remove-then-add on every upgrade, so a path recorded here cannot go stale behind a moved
|
||||
// install — which is what previously argued for leaving these rules unscoped.
|
||||
let exe = match std::env::current_exe() {
|
||||
Ok(p) => Some(p),
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"warning: could not resolve the host executable path ({e}) — the rules below stay \
|
||||
open to any program on those ports, and the per-session data-plane rule is skipped"
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
// (name suffix, protocol, ports). 47990 = mgmt/library (LAN = read-only, paired-cert only); the
|
||||
// rest are the GameStream (47984/47989/48010, 47998-48010) + native (9777) + mDNS (5353) ports.
|
||||
let rules = [
|
||||
@@ -1566,28 +1631,35 @@ fn add_firewall_rules(allow_public: bool) {
|
||||
];
|
||||
for (suffix, proto, ports) in rules {
|
||||
let name = format!("Punktfunk {suffix}");
|
||||
let ok = run_quiet(
|
||||
"netsh",
|
||||
&[
|
||||
"advfirewall",
|
||||
"firewall",
|
||||
"add",
|
||||
"rule",
|
||||
&format!("name={name}"),
|
||||
"dir=in",
|
||||
"action=allow",
|
||||
&format!("protocol={proto}"),
|
||||
&format!("localport={ports}"),
|
||||
profile,
|
||||
],
|
||||
);
|
||||
let ok = run_netsh(&fw_add_rule_args(
|
||||
&name,
|
||||
proto,
|
||||
Some(ports),
|
||||
exe.as_deref(),
|
||||
profile,
|
||||
));
|
||||
if ok {
|
||||
println!("Firewall rule added: {name} ({ports}) [{profile}]");
|
||||
let scope = match &exe {
|
||||
Some(p) => format!(" for {}", p.display()),
|
||||
None => String::new(),
|
||||
};
|
||||
println!("Firewall rule added: {name} ({ports}{scope}) [{profile}]");
|
||||
} else {
|
||||
eprintln!("warning: could not add firewall rule '{name}' (add it manually if needed)");
|
||||
}
|
||||
}
|
||||
add_data_plane_firewall_rule(profile);
|
||||
add_data_plane_firewall_rule(profile, exe.as_deref());
|
||||
// 5353 is now ours alone. Anything else on this machine that answered mDNS through the old
|
||||
// any-program rule needs its own — say so, because it is the one externally visible change.
|
||||
// Only when the scoping actually happened: with no exe path these rules are still wide open,
|
||||
// and claiming otherwise in installer output is worse than saying nothing.
|
||||
if exe.is_some() {
|
||||
println!(
|
||||
"Note: these rules are scoped to the punktfunk host executable, so they no longer open \
|
||||
those ports to every program on this machine. Another mDNS/GameStream application \
|
||||
that relied on punktfunk's rules to be reachable now needs a rule of its own."
|
||||
);
|
||||
}
|
||||
if !allow_public {
|
||||
println!(
|
||||
"Note: streaming ports are open on Private/Domain networks only. On a network Windows \
|
||||
@@ -1613,35 +1685,29 @@ const FW_DATA_PLANE_RULE: &str = "Punktfunk UDP (data plane)";
|
||||
///
|
||||
/// Program-scoped rather than a pinned port: it covers whatever port the session picks, needs no
|
||||
/// second rule when the range moves, and cannot collide with another host (a pinned data port in
|
||||
/// 47998-48010 would land on Sunshine/Apollo's GameStream range). The port rules above are kept as
|
||||
/// they are — an install whose recorded exe path later moves still has its fixed ports open.
|
||||
fn add_data_plane_firewall_rule(profile: &str) {
|
||||
let exe = match std::env::current_exe() {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"warning: could not resolve the host executable path ({e}) — skipping the \
|
||||
data-plane firewall rule; streams may show a black picture behind a healthy \
|
||||
connection on networks that need the client's hole-punch to open the path"
|
||||
);
|
||||
return;
|
||||
}
|
||||
/// 47998-48010 would land on Sunshine/Apollo's GameStream range). This rule is the pattern the
|
||||
/// fixed-port rules above now follow too — it is only the `localport=` they keep and this one
|
||||
/// cannot have.
|
||||
///
|
||||
/// `exe` is resolved once by the caller and shared; `None` means it could not be resolved, and this
|
||||
/// rule is skipped rather than widened, because a program-less "any inbound UDP on any port" rule is
|
||||
/// not a looser version of this — it is an open host.
|
||||
fn add_data_plane_firewall_rule(profile: &str, exe: Option<&std::path::Path>) {
|
||||
let Some(exe) = exe else {
|
||||
eprintln!(
|
||||
"warning: no host executable path — skipping the data-plane firewall rule; streams may \
|
||||
show a black picture behind a healthy connection on networks that need the client's \
|
||||
hole-punch to open the path"
|
||||
);
|
||||
return;
|
||||
};
|
||||
let ok = run_quiet(
|
||||
"netsh",
|
||||
&[
|
||||
"advfirewall",
|
||||
"firewall",
|
||||
"add",
|
||||
"rule",
|
||||
&format!("name={FW_DATA_PLANE_RULE}"),
|
||||
"dir=in",
|
||||
"action=allow",
|
||||
"protocol=UDP",
|
||||
&format!("program={}", exe.to_string_lossy()),
|
||||
profile,
|
||||
],
|
||||
);
|
||||
let ok = run_netsh(&fw_add_rule_args(
|
||||
FW_DATA_PLANE_RULE,
|
||||
"UDP",
|
||||
None,
|
||||
Some(exe),
|
||||
profile,
|
||||
));
|
||||
if ok {
|
||||
println!(
|
||||
"Firewall rule added: {FW_DATA_PLANE_RULE} (any UDP port for {}) [{profile}]",
|
||||
@@ -1872,3 +1938,55 @@ fn maybe_boot_loop_rollback(restarts: u32, attempted: &mut bool) {
|
||||
Err(e) => tracing::error!(error = %e, "failed to spawn the rollback installer"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod firewall_tests {
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
|
||||
/// Every fixed-port rule must carry BOTH `program=` and `localport=`. Dropping the program
|
||||
/// scope is the regression that matters: the rule still works, streaming still works, and the
|
||||
/// only visible difference is that any unprivileged process on the machine can bind those
|
||||
/// ports and be reachable from the LAN without ever raising a Windows prompt.
|
||||
#[test]
|
||||
fn fixed_port_rules_are_scoped_to_the_program_and_the_ports() {
|
||||
let exe = Path::new(r"C:\Program Files\Punktfunk\punktfunk-host.exe");
|
||||
let args = fw_add_rule_args(
|
||||
"Punktfunk UDP",
|
||||
"UDP",
|
||||
Some("47998-48010,9777,5353"),
|
||||
Some(exe),
|
||||
"profile=domain,private",
|
||||
);
|
||||
assert!(args.contains(&format!("program={}", exe.display())));
|
||||
assert!(args.contains(&"localport=47998-48010,9777,5353".to_string()));
|
||||
assert!(args.contains(&"dir=in".to_string()));
|
||||
assert!(args.contains(&"action=allow".to_string()));
|
||||
assert!(args.contains(&"profile=domain,private".to_string()));
|
||||
assert_eq!(&args[..4], &["advfirewall", "firewall", "add", "rule"]);
|
||||
}
|
||||
|
||||
/// The data plane is the one rule that legitimately has no port: its socket binds `0.0.0.0:0`
|
||||
/// per session. It must therefore never lose its program scope — a program-less "any inbound
|
||||
/// UDP on any port" rule is not a looser version of this rule, it is an open host.
|
||||
#[test]
|
||||
fn the_data_plane_rule_has_a_program_but_no_port() {
|
||||
let exe = Path::new(r"C:\Program Files\Punktfunk\punktfunk-host.exe");
|
||||
let args = fw_add_rule_args(FW_DATA_PLANE_RULE, "UDP", None, Some(exe), "profile=any");
|
||||
assert!(args.contains(&format!("program={}", exe.display())));
|
||||
assert!(
|
||||
!args.iter().any(|a| a.starts_with("localport=")),
|
||||
"the per-session data port is ephemeral — pinning one would close the others"
|
||||
);
|
||||
}
|
||||
|
||||
/// An unresolvable executable falls back to the old any-program rule rather than to no rule:
|
||||
/// a looser rule still streams, a missing one is a black screen. Pinned so the fallback stays
|
||||
/// deliberate rather than becoming an accident.
|
||||
#[test]
|
||||
fn a_missing_program_falls_back_to_the_port_only_rule() {
|
||||
let args = fw_add_rule_args("Punktfunk TCP", "TCP", Some("47990"), None, "profile=any");
|
||||
assert!(!args.iter().any(|a| a.starts_with("program=")));
|
||||
assert!(args.contains(&"localport=47990".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,6 +252,16 @@ the route where there are no face buttons to press, such as an Android TV remote
|
||||
names whichever your device has; the Apple TV carries it in ordinary Settings next to **Show it**
|
||||
instead, so it's reachable from the Siri Remote.
|
||||
|
||||
**Reduce interface resolution** — *default: off.* Android only, in the controller-optimized
|
||||
settings. Draws the menus at 1080p and lets the display scale them up, instead of drawing at the
|
||||
panel's own resolution. Text goes a little softer; the interface gets much smoother. It is for 4K
|
||||
televisions and projectors, whose graphics chips are built to decode and composite video rather
|
||||
than to draw a moving interface, and are far slower than the ones in phones — at 4K every part of
|
||||
the interface costs four times what it does at 1080p, on hardware nowhere near four times faster.
|
||||
A premium 4K box is *more* likely to want this than a cheap 1080p stick, which never had the extra
|
||||
pixels in the first place. Nothing about a stream changes: picture quality is
|
||||
[**Resolution** and **Bitrate**](#video), and this is the interface only.
|
||||
|
||||
## Overlay
|
||||
|
||||
**Statistics overlay** — *default: Normal.* Four tiers — Off, Compact, Normal, Detailed — each a
|
||||
|
||||
@@ -282,7 +282,7 @@ table, where client and host read the *same* variable name for their own half of
|
||||
| `PUNKTFUNK_PRESENTER` | `arrival` | Turn the frame-pacing engine off for this run: frames present the instant they decode, exactly as they did before the **Prioritize** setting existed. A diagnostic — if a pacing change is suspected of causing judder or added delay, this switches it off without reinstalling anything. Linux and Windows clients. |
|
||||
| `PUNKTFUNK_VRR_FIFO` | `1` | Force the display mode used to follow a **variable-refresh (VRR / FreeSync / G-Sync)** screen, on graphics drivers too old to offer the modern one. You almost certainly don't need this: where the driver supports the modern mode — which is what **Follow variable refresh rate** in [client settings](/docs/client-settings#video) uses — following the panel is already automatic and costs almost nothing. On an older driver the only way to follow the panel is a mode that measured roughly 27 ms *worse* on a fixed-refresh screen, so it stays off unless you ask for it, and it's only worth asking if you genuinely have a VRR screen and play fullscreen. Check the Detailed [stats overlay](/docs/stats): `vrr yes` means the panel really is following the stream. Linux and Windows clients. |
|
||||
| `PUNKTFUNK_PRESENT_DEBUG` | `1` | Log the presenter's own 1-second summary (display mode, buffer drops, pacing counters) every second, even when nothing is going wrong. Without it the line appears only when there is something to report. |
|
||||
| `PUNKTFUNK_ABR_PROBE_KBPS` | kbps, e.g. `900000` | The startup link-capacity probe's burst target (default 2 Gbps — deliberately above any plausible link so the burst measures the link, not itself). Lower it on links the burst shouldn't slam, or when the measured ceiling comes out wrong for your setup. |
|
||||
| `PUNKTFUNK_ABR_PROBE_KBPS` | kbps, e.g. `90000` | The startup link-capacity probe's burst target. By default it's derived from the session — twice what your resolution, refresh rate and codec could plausibly use, which is the most the climb ceiling is ever allowed to reach — and capped at 2 Gbps. Lower it further on links the burst shouldn't slam, or when the measured ceiling comes out wrong for your setup. |
|
||||
| `PUNKTFUNK_ABR_PROBE` | `0` | Skip the startup link-capacity probe entirely. The adaptive-bitrate climb ceiling then stays at the negotiated starting rate — a blunt instrument; prefer `PUNKTFUNK_ABR_MAX_MBPS`. |
|
||||
| `PUNKTFUNK_ABR_MAX_MBPS` | Mbps, e.g. `300` | Hard cap on the adaptive bitrate's climb ceiling, whatever the startup probe measured. The escape hatch when adaptive sessions keep climbing past what your client's **decoder** can sustain (periodic hitch + "receive backlog stopped draining" in the client log). An explicit bitrate setting still bypasses ABR entirely. |
|
||||
|
||||
|
||||
@@ -44,9 +44,13 @@ from the [stats overlay](/docs/stats), so it shows even with stats off.
|
||||
|
||||
The mute lasts for that stream only — the next session starts unmuted; nothing is written to your
|
||||
settings. With **Stream microphone** off in [client settings](/docs/client-settings#audio) the
|
||||
shortcut does nothing and no badge appears. **Linux and Windows** clients only (a Steam Deck stream
|
||||
is the Linux client, so an attached keyboard gets the chord); on Apple and Android turn **Stream
|
||||
microphone** off in settings instead.
|
||||
shortcut does nothing and no badge appears.
|
||||
|
||||
The **keyboard** chord is **Linux and Windows** only (a Steam Deck stream is the Linux client, so an
|
||||
attached keyboard gets it). On **Android** a controller can reach the same toggle: **Select + Y**,
|
||||
and on a DualSense the pad's own **Mute** button does it too — one toggle per press, and the badge
|
||||
is the same. On **Apple** clients there is no shortcut; turn **Stream microphone** off in settings
|
||||
instead.
|
||||
|
||||
Alt-Tabbing away releases input on its own and takes it back when you return. A release you asked
|
||||
for with the chord stays released until you opt back in. Either way, keys and buttons you were
|
||||
|
||||
@@ -52,6 +52,12 @@ The console lists every paired device with its access (and a live countdown for
|
||||
From there you can change the level, extend or cut the expiry, or **remove** the device — removing
|
||||
revokes it immediately, even mid-session. Re-pairing a removed device is just the PIN ceremony again.
|
||||
|
||||
**Naming a Moonlight device.** Every Moonlight-compatible client identifies itself with the same
|
||||
built-in name, so several of them look identical in the list. Use the pencil on the row to give it
|
||||
one of your own ("Living room TV") — the name is stored on the host, so every browser sees it, and
|
||||
removing the device forgets it. Devices paired with Punktfunk's own apps send a real name already
|
||||
and have no pencil.
|
||||
|
||||
Can't pair at all? [Troubleshooting → Pairing is rejected](/docs/troubleshooting#pairing-is-rejected--the-client-cant-connect).
|
||||
|
||||
## How it works, briefly
|
||||
|
||||
@@ -17,9 +17,12 @@ list; the install guides quote the one or two lines that apply to each distro.
|
||||
one](/docs/web-console#two-ports-not-one)).
|
||||
- **`punktfunk-gamestream`** is needed only once you turn on Moonlight compat
|
||||
(`PUNKTFUNK_GAMESTREAM=1` in `host.env` — [Moonlight](/docs/moonlight)).
|
||||
- **Video needs nothing opened.** The data plane uses an ephemeral UDP port the *client* opens with a
|
||||
hole-punch; the host streams back through the path the client opened, so only outbound UDP has to
|
||||
be allowed (the default in both ufw and firewalld).
|
||||
- **Video needs nothing opened on Linux.** The data plane uses an ephemeral UDP port the *client*
|
||||
opens with a hole-punch; the host streams back through the path the client opened, so only
|
||||
outbound UDP has to be allowed (the default in both ufw and firewalld). **Windows is the
|
||||
exception** — it drops the client's hole-punch, which is why `service install` adds an inbound UDP
|
||||
rule scoped to the host executable rather than to a port number (no fixed rule can cover a port
|
||||
chosen fresh each session).
|
||||
|
||||
## Enabling the profiles
|
||||
|
||||
@@ -40,6 +43,15 @@ Stock Arch and Debian ship no firewall; Ubuntu installs ufw but leaves it inacti
|
||||
and most Fedora-family spins run firewalld; CachyOS enables ufw. On **NixOS** the module's
|
||||
`openFirewall = true` does all of this; on **Windows** the installer registers the rules.
|
||||
|
||||
<Callout type="warn">
|
||||
**Windows: the rules are scoped to Punktfunk from 0.31.2 on.** Each rule names the executable that
|
||||
listens on it as well as the port, so those ports are open to Punktfunk rather than to anything on
|
||||
the machine that binds them first — before 0.31.2 they named only the port. The one thing this can
|
||||
change for you is **5353**: if something else on that PC relied on Punktfunk's rule to answer
|
||||
discovery, it now needs a rule of its own. `service install` re-applies the rules on every upgrade,
|
||||
so a normal update is enough.
|
||||
</Callout>
|
||||
|
||||
## Moving a port
|
||||
|
||||
Two are configurable, and both are how you share a machine with another streaming host — see
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"name": "MIT OR Apache-2.0",
|
||||
"identifier": "MIT OR Apache-2.0"
|
||||
},
|
||||
"version": "0.31.0"
|
||||
"version": "0.31.3"
|
||||
},
|
||||
"paths": {
|
||||
"/api/v1/client-logs": {
|
||||
@@ -364,6 +364,77 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"patch": {
|
||||
"tags": [
|
||||
"clients"
|
||||
],
|
||||
"summary": "Rename a paired client",
|
||||
"description": "Sets or clears the operator-visible display name for one paired Moonlight client. This is\npurely cosmetic — it touches no certificate and no trust decision — but it is the only way to\ntell paired devices apart: every moonlight-common-c client self-signs with the identical\nsubject `CN=NVIDIA GameStream Client`, so an unnamed list is a row of clones distinguishable\nonly by fingerprint. The name is stored beside the pairing store and survives host restarts;\nunpairing the device forgets it.",
|
||||
"operationId": "renameClient",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "fingerprint",
|
||||
"in": "path",
|
||||
"description": "Hex SHA-256 fingerprint of the client certificate DER (64 chars, case-insensitive)",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/RenameClient"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "The client as it now reads",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PairedClient"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Malformed fingerprint",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ApiError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Missing or invalid bearer token",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ApiError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "No paired client with that fingerprint",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ApiError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/compositors": {
|
||||
@@ -6688,7 +6759,7 @@
|
||||
},
|
||||
"HostInfo": {
|
||||
"type": "object",
|
||||
"description": "Host identity and advertised capabilities (static for the life of the process).",
|
||||
"description": "Host identity and advertised capabilities (static for the life of the process, except\n`local_ip`).",
|
||||
"required": [
|
||||
"hostname",
|
||||
"uniqueid",
|
||||
@@ -6734,7 +6805,7 @@
|
||||
},
|
||||
"local_ip": {
|
||||
"type": "string",
|
||||
"description": "Best-effort primary LAN IP."
|
||||
"description": "Best-effort primary LAN IP, read fresh on every request — a host that started before its\nnetwork did (cold boot) reports `127.0.0.1` only until it actually has an address, and a\nhost that moves networks reports the new one. Poll it rather than caching it."
|
||||
},
|
||||
"os": {
|
||||
"type": "string",
|
||||
@@ -7375,6 +7446,14 @@
|
||||
"description": "Lowercase hex SHA-256 of the client certificate DER — the client's stable id here.",
|
||||
"example": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
|
||||
},
|
||||
"label": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
],
|
||||
"description": "Operator-assigned display name for this device, if one has been set (`PATCH /clients/{fp}`).\n\nThis is the ONLY thing that can tell two paired Moonlight devices apart in a list, because\ntheir certificates cannot: see [`Self::subject`]. Absent until somebody names the device.",
|
||||
"example": "Living Room TV"
|
||||
},
|
||||
"not_after_unix": {
|
||||
"type": [
|
||||
"integer",
|
||||
@@ -7396,7 +7475,7 @@
|
||||
"string",
|
||||
"null"
|
||||
],
|
||||
"description": "Certificate subject (e.g. `CN=NVIDIA GameStream Client`), if the DER parses."
|
||||
"description": "Certificate subject (e.g. `CN=NVIDIA GameStream Client`), if the DER parses.\n\nDo not display this as a device name. Every moonlight-common-c client self-signs with that\nsame fixed subject, so it identifies the *protocol*, not the device — a list of paired\nphones, TVs and handhelds all read identically. [`Self::label`] is the field to show."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -7949,6 +8028,20 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"RenameClient": {
|
||||
"type": "object",
|
||||
"description": "Body of `PATCH /clients/{fingerprint}` — the device's display name.",
|
||||
"properties": {
|
||||
"label": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
],
|
||||
"description": "The name to show for this device. `null` (or an empty/whitespace-only string) clears it and\nthe device goes back to being listed by fingerprint alone.\n\nScrubbed before storage by the same sanitizer the native plane runs on device names:\ncontrol characters and Unicode bidi overrides are stripped (they could make one paired\ndevice impersonate another in this very list), whitespace collapsed, and the result capped\nat 64 characters.",
|
||||
"example": "Living Room TV"
|
||||
}
|
||||
}
|
||||
},
|
||||
"RunningTitle": {
|
||||
"type": "object",
|
||||
"description": "One running title in a provider's liveness report.",
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
Wire-compatible with 0.31.x — everything you have already paired keeps working, and you can update one side at a time. Nothing here changes how a host and a client agree on what to send each other, so an old client on a new host, or the other way round, streams exactly as it does today.
|
||||
|
||||
This is a fix release, and the largest thing in it has been wrong on every Windows host since there have been Windows hosts: the port your video actually travels on was never opened in the firewall, so on any network that needs your client to knock first, the connection succeeded, every health signal stayed green, and the picture never arrived. Two more are about controllers that were connected, correctly identified, and doing the wrong thing anyway — Moonlight-compatible sessions on Windows were building the one kind of virtual controller Steam and most games cannot see, and on a Fire TV a DualSense's L2 was arriving as L1. The rest is Android: a console that could not be dismissed, a picture that sat in the top-left corner, and a television remote that could not reach Settings or your library. There is one new thing too — a library add-on can now tell your host which of its games are running, which is how a game your host cannot find on disk finally ends its own session.
|
||||
|
||||
## TL;DR
|
||||
|
||||
- **Windows: streams that connected and then stayed black.** The per-session video port was never covered by any firewall rule, on any Windows host, ever. Update with the installer and the rule is added for you — see *Before you update*.
|
||||
- **Windows: controllers did nothing in Moonlight-compatible sessions.** Every client, every device, same result. Those sessions built a virtual controller most games cannot enumerate; they now build the same one ordinary Punktfunk sessions do.
|
||||
- **Android: controllers Android has no layout for pressed the wrong buttons.** A DualSense or an Xbox Elite Series 2 over Bluetooth on a Fire TV had L2 arriving as L1, with Circle and R1 doing nothing at all.
|
||||
- **Android: the controller console would not go away, and the picture sat in the corner.** Both fixed — and the console now carries its own switch for turning itself off.
|
||||
- **A television remote can reach Settings and your library again.** Both were on controller face buttons a remote does not have.
|
||||
- **Android: every setting that only exists in the controller console did nothing when you changed it.** Low latency, the phone's own rumble and motion, controller capture — all saved to somewhere nothing read back.
|
||||
- **Nobara hosts: "Switch to Desktop" during a stream threw you straight back into the stream.** And on Steam Deck-style hosts, a mid-stream switch could leave Gaming Mode unable to start afterwards.
|
||||
- **NixOS: the host installed a compositor that was not there.** The package shipped the small launcher and deleted the program it launches.
|
||||
- **Games your host cannot see on disk can now end their own session.** A library add-on can tell the host which of its titles are running, which is the missing half for anything launched by handing off to another program — emulated titles, manually added ones.
|
||||
|
||||
## Before you update
|
||||
|
||||
- **Windows hosts: run the installer rather than replacing the program by hand.** The black-picture fix is a new firewall rule, and it is added by the host's own service-install step, which the installer runs for you on every update. If you run the host some other way, run `punktfunk-host service install` once as an administrator — or add an inbound rule for `punktfunk-host.exe` yourself. Uninstalling Punktfunk removes the rule again. Nothing on the client side needs doing.
|
||||
- **NixOS hosts: expect a rebuild.** The compositor is now pinned to the exact version every other packaging channel ships, rather than to whatever the packages you happened to have carried, so its build inputs change. The binary cache added in 0.31.0 covers it if you have it configured.
|
||||
- **Add-on authors: `@punktfunk/plugin-kit` 0.4.4 is what you depend on for the running-report above.** The call and its types were reachable only through a deep import path before, so nothing could reach them from the package root. Nothing else in the add-on contract moved.
|
||||
- **Arch and SteamOS hosts: this release finally offers you a compositor upgrade you have been owed since 0.30.0.** The package's declared version had been left behind while the program inside it moved on, so your package manager saw nothing to do — which is why non-US keyboard layouts kept typing US characters on those machines even after the fix shipped.
|
||||
|
||||
## New
|
||||
|
||||
- **A library add-on can tell your host which of its games are running.** Your host normally works out whether a game is still going by looking for it on the machine — which needs something recognisable there to look for. A title that Playnite launches by handing off to another program has none: an emulated game, a manually added one, anything whose add-on records no folder. So the host never noticed those ending, your session stayed open on a game that had already exited, and anything set to happen when a game ends did not. The add-on knew the whole time, and can now say so. It is deliberately hard to get stuck on: a report expires unless it is repeated, so an add-on that crashes or is uninstalled stops speaking for your games within a minute and your host goes back to looking for itself. **This is the host's half.** It does something for you once an add-on sends those reports — the Playnite one is the first and updates separately, on its own schedule.
|
||||
- **The controller console can switch itself off.** On an Android phone or tablet the console's own Settings now carries a Controller-optimized UI switch, so you can leave the console from inside it and land back on the touch interface immediately. Until now that switch existed only in the touch settings — which someone stuck inside the console had no way to reach, and since 0.31.0 the console is the only interface Android shows when a controller is attached. It appears only where switching off has somewhere to land: not on a television, and not on the desktop console, where turning it off would leave you with nothing.
|
||||
|
||||
## Improved
|
||||
|
||||
- **A host can tell a silent connection from a perfect one.** Packet loss is a proportion of what arrived, so a link delivering nothing and a flawless link both reported zero loss — and the host read the silence as perfection, complete with confident wording about the client's network in the log. Clients now also report how much they have actually received, so a host that is sending into a void says so, and names the video path rather than blaming the client. A client too old to answer gets a warning that says as much instead of a guess.
|
||||
- **The Connected controllers page can be trusted again.** It read your button presses the same wrong way the stream did, so it agreed with the bug and confirmed a mistranslated pad as correct. It now shows what the controller actually reported alongside what Android made of it, and names the layout it resolved — which is also what makes an unrecognised pad fixable from a bug report, without the hardware in hand.
|
||||
|
||||
## Fixed
|
||||
|
||||
- **A Windows host could stream into a black screen with nothing anywhere saying why.** One field host sent 1,919 frames of video that were never seen while its own log blamed the client's network. The cause: the firewall rules Punktfunk installs cover fixed port numbers, but the video itself travels on a port chosen fresh for each session — a port no such rule can ever cover. So Windows dropped the client's opening knock on **every session on every Windows host**, including ones that worked; those worked only because nothing on the path needed the client to open the way first. When something did — many home routers, most mobile networks, anything doing address translation in front of the host — the control connection stayed perfectly healthy and the video went nowhere. The host now installs a rule that follows the program instead of the port number, so whichever port a session picks is covered. It is scoped to the program deliberately: pinning a port would have collided with Sunshine and Apollo on machines running both.
|
||||
- **Controllers did nothing at all in Moonlight-compatible sessions on Windows**, reported across every client and every device someone tried, which is what showed it was not a client problem. Windows has two ways to present a virtual Xbox controller, and only one of them is visible to Steam, to games using the common input libraries, and to the Windows Game Controllers panel. Ordinary Punktfunk sessions moved to that one over a year of reports; Moonlight-compatible sessions kept the invisible one purely because both were reached by the same internal name. They now make the same choice, and switching them both back is still one setting if you need it.
|
||||
- **Controllers pressed the wrong buttons on devices Android has no layout for.** Reported from a Fire TV Stick 4K Max with a DualSense and an Xbox Elite Series 2, both over Bluetooth, both identified by name and both wrong under the fingers: L2 arrived as L1, and Circle and R1 were dropped entirely. Android names a controller's buttons from a file matched to that exact model, and when there is no such file it falls back to guessing by the order the buttons appear in the controller's own report — which is only right if that order happens to match. Neither pad has a file on a Fire TV. Punktfunk now reads the button's position in the controller's report directly, which is what the controller means rather than what the guess made of it, and does so only where the guess was in play, so a device that already worked is untouched. Triggers get the same treatment: on a pad Android never mapped they sit on raw axes, which is why pulling a trigger could swing the right stick instead. Whether a trigger rests at zero or at the bottom of its range is now measured from the device rather than assumed. **Not yet confirmed on the reporter's own hardware** — the fix is proven against what those two controllers report, but a Fire TV is the test that settles it, so please say if yours still misbehaves. One thing stays broken and cannot be fixed here: the Xbox pad's Guide button is delivered by Android as the Home key, which it never passes to an app.
|
||||
- **The controller console could not be dismissed on some Android phones.** Turning it off is a matter of no controller being attached, and the app decided that by asking whether a device claimed to be a gamepad — which is the right question for routing a button press and the wrong one for knowing a pad is in the room. Manufacturer game-mode overlays and gaming-phone shoulder triggers make that claim without being controllers, and one of them was enough to pin the console on forever, because a pad that was never there can never be unplugged. The app now also asks whether the hardware is there behind the claim — a stick, a directional pad or real face buttons — and the new switch above is the guaranteed way out either way.
|
||||
- **Changing an Android-only setting inside the controller console did nothing.** Low latency, the phone's own rumble and motion controls, the controller capture switches and the console's own display mode could each be changed in the console, and each quietly went nowhere: the console filed those settings one level deeper than the settings file keeps them, so nothing ever read one back. The row showed its own default, your change came back as the value it had just been handed, and nothing downstream ever heard that anything had moved — which is also why the new off switch above needed this fixed before it could work at all. Settings written by the previous build carry a dead wrapper; it is discarded the next time anything is saved rather than followed around for the life of the install.
|
||||
- **The glow behind a focused card was squarer than the card.** The halo grows the card by a few units on every side but kept the card's own corner radius, and a shape grown outward only stays parallel if its corners grow with it — so the two arcs stopped sharing a centre and the corners read as a badly drawn outline instead of light spilling out from behind. Every card in the console goes through that path: the home tiles, the library grid, the coverflow and the collections deck.
|
||||
- **The picture sat in the top-left corner of an Android screen.** The video layer took the size of the view once, at the moment it was created — and the stream screen hides the system bars and expands into the display cutout a frame or two later, each of which grows the view underneath a layer that never hears about it. The size is now read fresh for every frame, which also means rotating the phone and multi-window both simply work.
|
||||
- **Settings and your game library could not be reached with a television remote.** A remote has a directional pad, OK and Back, and the console had put Settings and the library shelf on controller face buttons it does not have — so on an Android TV neither could be opened at all. Pressing down on the home row now opens Settings, and the library has joined each machine's own options menu, which is where the documentation had been telling you to find it all along. The on-screen hints name whichever route the device in your hand actually has.
|
||||
- **On Nobara, "Switch to Desktop" during a stream threw you straight back into the stream.** The switch takes the picture away, Punktfunk reads that as a problem and rebuilds the session, and the rebuild put Gaming Mode back over the desktop that was trying to start. 0.31.0 changed how the host takes Gaming Mode over and left nothing watching for the switch, which Steam Deck and Bazzite machines never noticed because they follow it another way — Nobara has neither. Also fixed on both: a mid-stream switch used to leave Gaming Mode replaced by a placeholder, so the machine's own "Return to Gaming Mode" afterwards started something that did nothing. Both routes now hand the machine back intact.
|
||||
- **On NixOS the host installed a compositor consisting only of its launcher.** The packaging trims the installed programs down to the one that is needed and had been matching it by name — but the program with that name is a small launcher that sets things up and then runs the real compositor, which the trim deleted. What shipped was a launcher pointing at nothing. That is the true cause of the version banner printing nothing, the marker "missing from the binary", and every HDR-related NixOS failure chased alongside them. Separately, NixOS was the only channel not pinning which compositor version it patches, so a package update could and did break the build outright — and since HDR is on by default, that failure landed on anyone enabling the host at all.
|
||||
|
||||
## Thanks
|
||||
|
||||
Every fix above came from someone describing precisely what did not happen. The Windows black screen was found in two field logs from a host that looked healthy in every respect; the dead controllers in Moonlight-compatible sessions were reported with the detail that made them findable, that it reproduced on every client and device tried; the Fire TV report named which button arrived as which; and one Android user sent two reports in a day that turned out to be the same mistake made twice. Thank you — that is what makes a fault findable rather than merely believable.
|
||||
|
||||
## For developers
|
||||
|
||||
Protocol, ABI, driver and embedder detail — including the version table — is in [CHANGELOG.md](https://git.unom.io/unom/punktfunk/src/tag/v0.31.1/CHANGELOG.md).
|
||||
|
||||
The short version: the streaming protocol, the embedding interface, the driver protocol and the gamepad channel are all exactly where 0.31.0 left them, so nothing needs rebuilding, re-pairing or re-packaging in any direction. The management API and the add-on toolkit each gain one thing by pure addition — the running-report route above, and the toolkit call for it in 0.4.4 — and an add-on that ignores both keeps working unchanged. One control message is added to the wire — clients reporting how much they have received, which is what lets a host tell a dead video path from a clean one — but it takes a spare message number rather than changing an existing message, and an older host on the other end ignores it after one note in its log.
|
||||
@@ -0,0 +1,42 @@
|
||||
Wire-compatible with 0.31.x — everything you have already paired keeps working, and you can update one side at a time. Nothing here changes how a host and a client agree on what to send each other, so an old client on a new host, or the other way round, streams exactly as it does today.
|
||||
|
||||
This is a fix release, and most of it continues the hunt 0.31.1 started: a stream that connects, reports itself perfectly healthy at every gauge, and shows you a black screen. Two more causes end here, and both are about which of your host's addresses it used — video that left the host by whichever network connection the machine happened to prefer rather than the one your client actually dialled, and a host that started up faster than its own network and then spent the rest of the day telling everyone to connect to an address that only ever means "this machine". The other half is Windows security: the firewall rules Punktfunk installs named ports but not programs, which left those ports open to anything running on that PC — they name Punktfunk now, and that is the one change here that can affect another program on the same machine. On Android, the controller fix from 0.31.1 turned out to be firing on controllers that never needed it, breaking buttons that had been correct all along.
|
||||
|
||||
## TL;DR
|
||||
|
||||
- **A host with two ways to reach your client streamed into a black screen.** Ethernet and Wi-Fi both connected, or a VPN adapter installed, was enough: the video left by whichever one the machine preferred, and your client discarded every packet of it. Nothing else about the session was wrong, which is exactly why it was so hard to see.
|
||||
- **A host that started before its network was ready never recovered.** It advertised an address meaning "this machine", so clients listed it and could not connect to it, Moonlight-compatible sessions could not stream, and Wake-on-LAN silently stopped working. Restarting the host was the only cure; now there is nothing to cure.
|
||||
- **Windows: Punktfunk's firewall rules were open to every program on your PC.** They named only port numbers, so any program — with no administrator rights and no prompt — could take one of those ports and be reachable from your network through a rule meant for Punktfunk. **Read *Before you update*: one thing on that machine may now need a rule of its own.**
|
||||
- **Android: 0.31.1's controller fix broke controllers that were already correct.** On a GameSir G8+ and an Xbox Elite Series 2 over Bluetooth, X answered Y, Y answered the left shoulder, and both shoulders answered menu buttons.
|
||||
- **Your host now follows its own address when it changes** — a new lease from your router, or a machine moved between Wi-Fi and Ethernet — instead of announcing the address it had at startup forever.
|
||||
|
||||
## Before you update
|
||||
|
||||
- **Windows hosts: run the installer rather than replacing the program by hand.** The firewall fix rewrites the rules Punktfunk installs, and that happens in the host's own service-install step, which the installer runs for you on every update. If you run the host some other way, run `punktfunk-host service install` once as an administrator. Skipping it leaves the old wide-open rules in place; nothing on the client side needs doing.
|
||||
- **Windows hosts: something else on that machine may need its own firewall rule now.** Punktfunk's rule for the discovery port (5353) used to be open to every program, so anything else on that PC that answers discovery — another streaming host, a media server, a printer or scanner utility — could have been reachable through Punktfunk's rule without ever having one of its own. That ends with this release. If something else on the machine stops being discoverable after you update, give it its own rule. The installer prints a note saying exactly this while it works.
|
||||
|
||||
## Improved
|
||||
|
||||
- **Your host keeps up with its own address instead of freezing it at startup.** The address a host publishes for clients to dial was worked out once, when the host process started, and then never looked at again. Now it is re-read as things change and the published address is updated to match — so a new lease from your router, or a laptop host carried from Wi-Fi to Ethernet, no longer leaves your clients dialling somewhere the host has not been for hours. This is the general form of the cold-boot fix below, and it covers the cases nobody had got round to reporting yet.
|
||||
- **When a stream does go black, the host's log now tells you the truth about it.** The message it printed used to name a cause with real confidence — and was wrong often enough to send people to the wrong place entirely, including at least one investigation that went to the firewall while the actual fault was the network card. It no longer asserts a cause it cannot know, and it now records which network connection the video is actually leaving by, and says so plainly when that is not the one the client arrived on. That single line is what turns the black screen above from a mystery into something a log answers.
|
||||
|
||||
## Fixed
|
||||
|
||||
- **A host with more than one live path to your client sent the video down the wrong one, and you got a black screen with every indicator green.** Two network connections up on the same network — the very common Ethernet-and-Wi-Fi-both-on — or a VPN or overlay adapter that claims to know a better route, and the host let the machine choose which one the video left by. That choice was made with no reference at all to how your client had reached it. Your client only listens for video from the address it dialled, so it threw away everything arriving from the other one, in the part of the system that counts nothing and reports nothing. Meanwhile the connection was made, sound and controller input flowed perfectly, and the host's own loss figure sat at zero — because loss is measured over packets that arrived, and none did. The host now sends the video from the same address the client reached it on.
|
||||
- **A host that started before its network was ready advertised itself as unreachable, and stayed that way until it was restarted.** Cold-booting a machine is a race, and the host wins it: it starts without waiting for the network, asks which address it should publish, gets no answer because there is no network yet, and falls back to the address that means "this machine and nothing else". Then it kept that answer for the entire life of the process. Everything that reads that address broke together — the host appeared in your client's list but could not be connected to, Moonlight-compatible sessions were handed the same useless address after launching a game, Wake-on-LAN quietly stopped working because the host could no longer identify the network hardware to record for it, and the web console displayed the wrong address to anyone who looked. Users found the workaround themselves, which was to restart the host once the machine had settled. The host now refuses that fallback answer entirely: if the usual method cannot say which address to use, it takes the first real network address it can find, which exists as soon as the network card is configured — well before the machine finishes working out how to route anything.
|
||||
- **Windows: the firewall rules Punktfunk installs opened those ports to every program on the machine, not to Punktfunk.** Each rule named a port and nothing else, and a rule like that admits whatever is listening on that port — Punktfunk or otherwise. Nothing about it required administrator rights to exploit: taking a high-numbered port on Windows needs no privileges at all, so any program that started first could sit on one of Punktfunk's ports and be reachable from your whole network. Worse, it happened without any of the usual signs, because the pop-up asking whether to let a program communicate on your network is precisely what a matching rule suppresses — Punktfunk's rule was answering that question on another program's behalf. Every rule now names the program that is genuinely meant to be listening on it, and keeps the port restriction as well, so both must match. The affected ports were the streaming, discovery, management and console ports. If Punktfunk cannot work out its own location on disk it keeps the old broader rule rather than leaving you with no rule at all, since a rule that is too generous still streams and a missing one is a black screen.
|
||||
- **Android: controllers that had always worked started pressing the wrong buttons.** This is a regression from 0.31.1, reported the same day on a GameSir G8+ and an Xbox Elite Series 2: X answered Y, Y answered the left shoulder, and the two shoulder buttons answered menu buttons, with everything else correct. 0.31.1 fixed controllers Android has no layout file for by reading each button's position in the controller's own report instead of trusting Android's guess — the right fix, applied to too many controllers. It decided which controllers needed it by asking what the device *claimed* to have, and that claim turns out to be true of any controller with six or more buttons, including every controller that was already perfectly correct. So it corrected pads that needed no correcting, and moved their buttons off the marks. It is now decided on the triggers instead: a controller that describes its triggers properly is one Android has a real layout for, and it is left completely alone — no correction to its buttons or its sticks. That is the same signal Moonlight uses for the same decision, and it matches the reports precisely, down to the fact that the very same model needed correcting on a Fire TV and was broken by it here: an Xbox Wireless Controller describes its triggers one way after a firmware update and the other way before it, and only the older one was ever wrong.
|
||||
|
||||
## Known issue
|
||||
|
||||
- **A DualSense with a dead Triangle button is not fixed here.** It was reported alongside the two controllers above and looks related, but it is not the same fault — Triangle reaching neither the stream nor Punktfunk's own controller display is a different failure from a button arriving as the wrong one, and nothing in the fix above produces it. The Connected controllers page prints exactly what each press reports; that line from an affected pad is what will pin it down.
|
||||
|
||||
## Thanks
|
||||
|
||||
Every fix in this release came from someone reporting what actually happened rather than what they assumed. Both black-screen causes were found in field logs from hosts that looked entirely healthy — and the firewall hole was reported by a user on the same day, immediately after the first of those fixes cleared their black screen and left them looking at the rules. The Android controller regression came back within a day of the release that caused it, from two people who named which button answered which, which is the difference between a report that can be fixed and one that can only be believed. Thank you.
|
||||
|
||||
## For developers
|
||||
|
||||
Protocol, ABI, driver and embedder detail — including the version table — is in [CHANGELOG.md](https://git.unom.io/unom/punktfunk/src/tag/v0.31.2/CHANGELOG.md).
|
||||
|
||||
The short version: nothing versioned moves at all. The streaming protocol, the embedding interface, the driver protocol, the gamepad channel and the add-on contract are exactly where 0.31.1 left them, no message or function changed shape, and no header, package or plugin needs rebuilding, re-pairing or re-publishing in any direction. Two things worth knowing: on Windows the firewall rules provisioned at install are now scoped to the executable that listens on each port, which is the one change here that can affect another program on the same machine; and the host's reported address in the management API is now read fresh on every request instead of being fixed for the life of the process, so poll it rather than caching it.
|
||||
@@ -0,0 +1,50 @@
|
||||
Wire-compatible with 0.31.x — everything you have already paired keeps working, and you can update one side at a time. Nothing here changes how a host and a client agree on what to send each other, so an old client on a new host, or the other way round, streams exactly as it does today.
|
||||
|
||||
This is a fix release about streams that ended, froze, stuttered or never arrived while everything involved was doing something perfectly ordinary. Launching a Steam game that had shaders to process dropped the stream about ten seconds in, so people learned to launch everything twice. A fullscreen game that picks its own screen resolution mid-play froze the picture on a Windows host and ended the video a few seconds later with the sound still running. On an Android TV or a Fire Stick the app was quietly asking your host for a frame rate your television does not actually output, which is where the latency people had been working around by hand was coming from. And on a slower connection the very first thing a client does — a quick burst to measure what the link can carry — was big enough to choke the link it was measuring, delaying the picture by many seconds or losing it entirely. There is new work too: your Moonlight devices can be given names, and a 4K television or projector can now run the on-screen interface at a lower resolution to keep it smooth.
|
||||
|
||||
## TL;DR
|
||||
|
||||
- **A Steam game with shaders to process dropped the stream about ten seconds into launching it.** You watched the "Processing Vulkan shaders" dialog, lost the stream, reconnected and launched again — and the second launch worked, which is why this looked like bad luck rather than a bug.
|
||||
- **Android TV and Fire Stick: the app negotiated a frame rate your TV does not output.** Setting the refresh rate by hand was the known workaround; it is no longer needed, and the latency it was papering over is gone.
|
||||
- **A slow first picture, or none at all, on a constrained connection.** The startup speed test was so large it could black-hole the very link it was measuring — one case took fourteen seconds to show video. It is now sized to the session, and if the test does swallow the opening frame the client asks for a new one instead of sitting on black.
|
||||
- **Windows: a game that changed your screen resolution mid-stream froze the picture and then ended the session.** The sound carried on throughout, which is exactly what makes this look like a problem at the client's end.
|
||||
- **Fire TV: a DualSense had buttons that never reached the game**, and its touchpad click and Mute button did nothing. Mute now mutes your microphone.
|
||||
- **New:** name your Moonlight devices instead of a list of identical rows, and — on a 4K TV or projector — **Reduce interface resolution** for a smoother on-screen interface.
|
||||
|
||||
## Before you update
|
||||
|
||||
- **Steam Deck, and only if you installed the host from source: re-run your update after taking this release.** A source install builds a patched compositor, and that build has been failing since mid-August because of a missing system package. The failure was silent — it reported success, and quietly dropped back to the system's own compositor, which is why HDR disappeared on boxes that had been streaming it minutes earlier. The missing package is added here, so the next build succeeds. Nothing to do on a packaged install.
|
||||
|
||||
## New
|
||||
|
||||
- **Give your Moonlight-paired devices names.** This is not a display bug being fixed: every Moonlight-compatible client identifies itself with the same built-in name, so it says which *app* is connecting and nothing about which device. Until now that name was all the console could show, and someone who had paired a phone, a television and a handheld saw three rows reading identically. Each Moonlight row now has a pencil next to it — name it "Living room TV", and that is what the list says from then on, including when you are choosing which device to remove. Devices paired with Punktfunk's own apps already send a real name and are left alone. Names live on the host, so every browser you open the console in sees the same ones, and removing a device forgets its name.
|
||||
- **Reduce interface resolution, for a 4K television or projector.** The on-screen interface is drawn at whatever resolution the panel hands it, and on a 4K set that is four times the work of 1080p on a chip built to decode video rather than to draw a moving interface — which is why the premium 4K boxes are the ones that feel sluggish, not the cheap 1080p sticks that never had the extra pixels. The new switch sits directly under Reduce motion, because it is the same kind of bargain: text goes a little softer, the interface gets smoother. It is off by default. **It changes the interface only and does nothing to your stream** — picture quality is still Resolution and Bitrate, which are separate settings and untouched by this.
|
||||
|
||||
## Improved
|
||||
|
||||
- **The on-screen interface got substantially cheaper to draw, on every device.** Independently of the switch above, it was doing a surprising amount of work on every single frame whether or not anything had changed: re-measuring and re-laying-out every piece of text on screen sixty times a second, and allocating a full-screen scratch image to apply an effect that did nothing whenever the interface was sitting still. On a 4K panel that scratch image alone was larger than the memory budget the whole interface is allowed on a 2 GB box, so it was evicting real work in order to do nothing. Both are gone, and the result is pixel-for-pixel identical. The interface also now gets a scheduling priority just below the stream's, so a TV box cannot park it behind background work and leave it lagging your remote.
|
||||
- **When the interface is slow, the logs can now say so.** It recorded which graphics version it had and how much memory it was allowed, and never what resolution it was drawing at or how long a frame took — so "it feels sluggish" could not be looked into from a log bundle at all. It now reports both.
|
||||
|
||||
## Fixed
|
||||
|
||||
- **Launching a Steam game dropped the stream while it was still starting, so you had to launch it twice.** Reported on Rocket League: the stream showed the "Processing Vulkan shaders" dialog and then ended about ten seconds in, every time, with a second launch working fine. The host was doing this to itself. Steam does its preparation work for a game — processing shaders, most visibly — under the same marker it uses for the game itself, so a launch is a short chain of things that all look like your game, and only the last one is. The host accepted the first one, and from that moment it was no longer waiting for a game to start but watching for one to exit; when the preparation step finished a few seconds later, that was read as the game exiting and the session was closed. Two things change. The shader step is now recognised for what it is and never mistaken for a game. And anything else must be seen continuously for a few seconds before the host will believe it is your game — the rule it already applied to programs a launcher starts, now applied to what it finds by looking. The cost is a few seconds' delay before the host says a game is running; nothing about detecting a game *exiting* changes, so a game you quit still ends the session as promptly as before.
|
||||
- **Android TV and Fire Stick: the app asked your host for a frame rate the television does not output, and the latency went through the roof.** People had already found the workaround — set the refresh rate by hand — without knowing what it was working around. The app pins the panel to its highest refresh rate while you are in the on-screen interface; that exists for phones whose systems otherwise cap apps at 60, and no television needs it. But when the stream started, the app read the panel's *pinned* rate rather than what the TV genuinely outputs over HDMI, negotiated the session at that — and then released the pin, because on a TV the video decoder is what should be driving the HDMI mode. The result was a 120-frame stream arriving at a 60 Hz output, by construction, on exactly the two kinds of device in the reports. The pin is no longer applied on a television at all. A TV that really can do 120 still gets it by choosing it. In the same chain: a TV that reports the fractional broadcast rates (59.94, 29.97, 23.976) had them cut down to 59, 29 and 23 — rates no display actually has — and they are rounded properly now.
|
||||
- **A slow first picture, or a black screen, on a constrained connection.** Before any video, a client sends a short burst to work out how much the link can carry. That burst was a fixed, very large size on the reasoning that it should measure the link rather than itself — but the result is capped afterwards to what the session could plausibly use, so everything above that was measured and immediately thrown away. What it bought was nothing; what it cost was a flooded link. On a constrained Wi-Fi connection it could black-hole outright: one measured case spent six seconds timing out and took fourteen seconds to show any video, and the same shape came in from a Fire TV Stick 4K Max. The burst is now sized from what the session can actually use, which can never come out lower than what is needed to prove the ceiling. And the second half of the black screen is closed too: if the burst takes the opening frame down with it, the client now asks for another one instead of waiting for some unrelated recovery to happen along.
|
||||
- **Windows: a game that changed your screen resolution during a stream froze the picture and then ended the session.** Reported from a 4K session where the game switched the display to 1080p while it ran. A fullscreen game is allowed to choose its own resolution, and your host followed it — but the part of the host that compresses the picture cannot change size while it is running, and it was being rebuilt over and over at the size the game had already left. After about three seconds of that, the video ended while the sound kept playing, so you were left with a frozen picture, working audio and no option but to reconnect. The host now rebuilds at the size the game actually chose and tells your client about the new one, exactly as it does when *you* change the resolution from the client. The same fix covers a game that switches HDR on or off mid-play, which failed in the same way. If a rebuild does not take the first time — a display that has just changed mode is often still settling — it is retried for the same few seconds rather than the session being given up on immediately.
|
||||
- **The same resolution change in a Moonlight-compatible session ended it too, and now does not.** One caveat worth knowing, because it is a real trade: the protocol Moonlight speaks has no way for a host to announce a resolution change once a stream is running, so your client is not told. Most clients notice from the picture itself and adjust; a strict one — Media Foundation on Xbox is the known example — may stall instead and need reconnecting. That is the same bargain these sessions already take whenever the host's picture and the client's request disagree, and it is strictly better than what it replaces, which was every such stream ending.
|
||||
- **Moonlight-compatible sessions stuttered at high frame rates, and the host was doing it to itself.** When a client loses its place in the video it asks the host for a complete picture to start again from, and the host is supposed to ignore repeat requests that arrive too quickly. The gap it waited for was measured in frames rather than in time, which at 120 frames a second is about a sixtieth of a second — far shorter than the time a client needs to ask, receive and decode — so the requests never looked like repeats and nearly all of them were honoured. One field session recorded 1,118 such requests in 91 seconds and honoured 1,115: a complete picture roughly every tenth frame, each one large enough to saturate the connection, causing the loss that prompted the next request. It reads as heavy stutter while every latency figure stays flat, because frames are being lost rather than delayed. It also looked like a codec fault, because the same session's H.264 stream — encoded by a different part of the host — asked twice in the whole session and was completely clean. The host now waits a fixed tenth of a second before honouring another request. The field case was a 120-frame session, but the old window was too short at 60 as well, so this is not only a fix for high-refresh displays.
|
||||
- **Fire TV: a DualSense had buttons that never reached the game, and its touchpad click and Mute button did nothing.** Three separate faults on one controller, all reported together over Bluetooth. Some of its buttons were being labelled by the system as coming from a keyboard rather than a controller, and the app was dropping them on that basis — it now trusts what the *device* is rather than the system's per-press guess, and only ever for keycodes that are genuinely controller buttons, so a remote's Back button and a keyboard's arrow keys are untouched. The touchpad click and the Mute button had nowhere to go at all and were simply discarded; both now travel to your game. And Mute genuinely mutes your microphone, once per press — held down, it no longer flickers the microphone on and off — on controllers that actually have the button.
|
||||
- **Android: the app could crash outright while playing, most often on an NVIDIA Shield.** The system call the app used to pick up the newest video frame hands back a resource it has already given away when more than one frame arrives at once, which the system's own safety check then catches by killing the app. It is a bug in Android that is still unfixed upstream, so the app stops using that call and picks the newest frame itself.
|
||||
- **Linux: after disconnecting, the box's own screen could stay black.** Reported on both Bazzite and Nobara. The hand-back at the end of a session asked the system to bring the desktop session back and then walked away the moment the request was accepted — but "the request was accepted" and "the screen is showing something" are different questions, and nothing had ever asked the second one, so every way of ending up dark looked identical to success. It now checks: if the box is still dark twenty-five seconds after the hand-back, it works through a ladder of increasingly firm remedies, each of which was measured on real machines of both families, and if it still cannot fix it, it says exactly what a human should run. This is not a guess at one trigger — the specific fault people reported could not be reproduced. It closes the gap that lets *any* trigger end as a dark panel.
|
||||
- **Windows: duplicate "Punktfunk Speakers" and "Punktfunk Microphone" devices piled up in your sound settings.** Creating one of these is two steps, and a host that died between them left behind a fully working device with no ownership mark on it. Nothing ever recognised that afterwards, so the next start created a second one and the stray outlived it — and because uninstalling also went by the ownership mark, uninstalling did not remove it either. One field machine showed exactly this. The host now recognises a stray from a previous run and adopts it instead of creating another, and uninstalling sweeps up ones already on the machine. Separately, on machines where the usual naming route is blocked, the microphone's name was being written to a location that only exists for speakers, so it silently kept the driver's default name.
|
||||
- **Steam Deck: HDR stopped working after updating to 0.31.2 on a source install.** Two faults with one symptom. The build of the patched compositor had been failing since mid-August on a missing system package — added here — and the failure path then went on to *unlink the compositor that was already installed and working*. A build that never produced anything replaced nothing, so removing the perfectly good previous one meant the host fell back to the system's own compositor and fixed the session at 8-bit, which cannot be taken back once a session has started. A failed build now leaves the working installation alone.
|
||||
|
||||
## Thanks
|
||||
|
||||
Almost everything above came from someone reporting exactly what they saw and on what — the game they launched and the dialog it hung on, the two 4K boxes that felt slow, the make of controller and which button did nothing, the card and the frame rate, the fourteen seconds before a picture appeared. Two entries are worth calling out for a different reason. The Linux black-screen fix ships *without* a reproduction: five scenarios were run across both distributions on real machines, the mechanism first proposed was disproved, and rather than guess, the fix closes the gap that lets any cause end the same way. And the DualSense work was re-implemented from a contributor's diagnosis rather than merged as sent — all three faults were real and correctly identified, but each proposed fix reached further than the hardware that needed it. The diagnosis was the hard part and it was right. Thank you.
|
||||
|
||||
## For developers
|
||||
|
||||
Protocol, ABI, driver and embedder detail — including the version table — is in [CHANGELOG.md](https://git.unom.io/unom/punktfunk/src/tag/v0.31.3/CHANGELOG.md).
|
||||
|
||||
The short version: nothing versioned moves. The streaming protocol, the embedding interface, the driver protocol, the gamepad channel and the add-on contract are exactly where 0.31.2 left them — `include/punktfunk_core.h` has no diff at all against the v0.31.2 tag — and no header, package or plugin needs rebuilding, re-pairing or re-publishing in any direction. The one surface that grows is the management API, additively: a `PATCH /api/v1/clients/{fingerprint}` route sets or clears a paired client's label, and `GET /clients` gains a `label` field alongside the existing certificate subject. Nothing existing changed shape, so a consumer that ignores both is unaffected. The TypeScript SDK is re-cut as `@punktfunk/host` 0.1.6 so an add-on can actually reach the generated types for that route; the add-on toolkit is unchanged. One dependency moves for a security advisory (`h2`, lockfile-only), and one behaviour worth knowing about if you integrate: the host now reports a game as running a few seconds later than it used to when it identifies that game by scanning processes rather than by a plugin's own report.
|
||||
@@ -0,0 +1,4 @@
|
||||
• Fixes every console-only setting doing nothing when you changed it — low latency, rumble, motion and controller capture all went nowhere.
|
||||
• Fixes controllers pressing the wrong buttons on boxes Android has no layout for — on a Fire TV a DualSense's L2 arrived as L1.
|
||||
• The controller console can now be switched off from inside it, and a TV remote can reach Settings and your library.
|
||||
• The picture no longer sits in the top-left corner.
|
||||
@@ -0,0 +1,2 @@
|
||||
• Fixes controllers pressing the wrong buttons after the last update — on a GameSir G8+ and an Xbox Elite Series 2 over Bluetooth, X answered Y and both shoulders answered menu buttons.
|
||||
• The button correction from the last release now applies only to controllers Android has no layout for, so a pad that worked before this update is left exactly as it was.
|
||||
@@ -0,0 +1,4 @@
|
||||
• Fixes the big latency jump on Android TV and Fire Stick — the app was asking your host for a frame rate your TV doesn't actually output. Setting the refresh by hand is no longer needed.
|
||||
• A DualSense on Fire TV: buttons that never reached your game now do, and Mute mutes your mic.
|
||||
• Fixes an app crash while streaming, most often on NVIDIA Shield.
|
||||
• Smoother interface on 4K TVs and projectors, plus a new Reduce interface resolution switch.
|
||||
@@ -19,7 +19,7 @@ pkgname=punktfunk-gamescope
|
||||
# bump it with the marker so pacman sees a new version when only our patches moved.
|
||||
_gsver=3.16.25
|
||||
_gsrev=5fb8dce4a09d0a68d097b9faf9513782106bc843
|
||||
pkgver="${_gsver}.pfhdr7"
|
||||
pkgver="${_gsver}.pfhdr8"
|
||||
# 2: patch 0006 (never destroy the Vulkan device/output at exit). No capability moved, so the
|
||||
# `.pfhdrN` level deliberately stays put — see README.md.
|
||||
# 3: pin moved 8c676c39 -> 5fb8dce4 (3.16.25-1 -> 3.16.25-11), which brings upstream's own
|
||||
@@ -45,6 +45,11 @@ pkgver="${_gsver}.pfhdr7"
|
||||
# racing steamcompmgr's vulkan_screenshot on the same device — a SIGSEGV precisely in the linger
|
||||
# window, so a kept display was dead and reconnect lost the game session. No capability the host
|
||||
# probes for, but "reconnect lost my game" triage has to read the difference off the banner.
|
||||
#
|
||||
# pfhdr8 / rel 1: patch 0010 gives the seat's stub keyboard the compiled `XKB_DEFAULT_*` keymap, so
|
||||
# a session follows the box's configured layout instead of typing US characters. The host PROBES the
|
||||
# banner for this one (`>= 8`), so the level HAS to move here too — leaving it at pfhdr7 made pacman
|
||||
# see no upgrade at all, and every Arch/SteamOS host kept a compositor the probe rejects.
|
||||
pkgrel=1
|
||||
pkgdesc="gamescope with 10-bit BT.2020/PQ PipeWire capture, for punktfunk HDR streaming"
|
||||
arch=('x86_64' 'aarch64')
|
||||
|
||||
@@ -109,6 +109,16 @@ echo "==> configuring"
|
||||
# (gamescope's own meson.build hard-errors if libliftoff/vkroots are missing from this list, so
|
||||
# all three go together.)
|
||||
#
|
||||
# **libdisplay-info is in the list for exactly the wlroots reason**, learned the hard way on the
|
||||
# SteamOS VM 2026-08-23: it is a vendored submodule too, so a build box that merely HAS
|
||||
# libdisplay-info-dev makes meson link it SHARED, and the binary then dies on SteamOS with
|
||||
# `libdisplay-info.so.2: cannot open shared object file` — it builds, it installs, it prints its
|
||||
# +pfhdr banner in the box, and build-gamescope.sh's on-glass check is the only thing between that
|
||||
# and a host promising HDR it cannot deliver. Debian trixie has the -dev package, Fedora and Arch
|
||||
# have it too, and any of them can pull it in transitively, so "don't install it" is not a fix
|
||||
# that holds. Pinning the fallback makes the outcome the same everywhere, which is the whole
|
||||
# point of this list.
|
||||
#
|
||||
# The C++ runtime goes STATIC for the same reason wlroots does: this binary is built on a ROLLING
|
||||
# distro and has to start on a FROZEN one. Arch's gcc (16.1.1 when this was written) makes the
|
||||
# compositor require `GLIBCXX_3.4.35`, and SteamOS 3.8.16 ships libstdc++ 3.4.34 — so the published
|
||||
@@ -124,7 +134,7 @@ export LDFLAGS="${LDFLAGS:-} -static-libstdc++ -static-libgcc"
|
||||
meson setup "$BUILD" "$SRCDIR" \
|
||||
--prefix="$PREFIX" \
|
||||
--buildtype=release \
|
||||
-Dforce_fallback_for="libliftoff,vkroots,wlroots${EXTRA_FALLBACK:+,$EXTRA_FALLBACK}" \
|
||||
-Dforce_fallback_for="libliftoff,vkroots,wlroots,libdisplay-info${EXTRA_FALLBACK:+,$EXTRA_FALLBACK}" \
|
||||
-Dpipewire=enabled \
|
||||
-Denable_tests=false \
|
||||
-Denable_openvr_support=false \
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
# shellcheck shell=bash
|
||||
# Does this box already have every Flathub dep a flatpak manifest declares?
|
||||
# bash scripts/ci/flatpak-deps-present.sh <manifest.yml> -> exit 0 = yes, 1 = no
|
||||
# bash scripts/ci/flatpak-deps-present.sh --self-test -> run the asserts below
|
||||
#
|
||||
# WHY THIS EXISTS: flatpak.yml used to prefetch deps with `flatpak-builder --install-deps-only`,
|
||||
# which does NOT mean "install what is missing". builder_manifest_install_dep() branches on
|
||||
# `flatpak info --show-commit <ref>` succeeding and runs `flatpak update` for every dep that IS
|
||||
# installed (a failed update is fatal there — it never falls back to install) — and
|
||||
# ci/flatpak-ci.Dockerfile bakes the whole runtime set, so on a healthy run that flag did nothing
|
||||
# except make the build depend on Flathub being up at that minute. On 2026-08-22 it took the job
|
||||
# down: dl.flathub.org returned HTTP 404 for one .filez object of the then-current
|
||||
# rust-stable//25.08 commit, identically on all 10 retry.sh attempts (~9 min), and flatpak-builder
|
||||
# segfaulted on its own error path (rc=139) so the retry wrapper could not tell a dead end from a
|
||||
# blip. Nothing about the build wanted that newer commit: the manifest pins a runtime VERSION, not
|
||||
# a commit, and the baked one satisfies it.
|
||||
#
|
||||
# So the workflow asks this first and only reaches for Flathub on a real miss.
|
||||
#
|
||||
# FAILS OPEN, deliberately: an unreadable/unexpected manifest reports "not present" (1), so the
|
||||
# caller does the full install. Silently skipping the install on a manifest we stopped
|
||||
# understanding is how you build against the wrong runtime.
|
||||
set -uo pipefail
|
||||
|
||||
deps_present() {
|
||||
local manifest="$1" runtime rt_ver sdk exts e
|
||||
|
||||
runtime=$(sed -n 's/^runtime: *//p' "$manifest" | head -1)
|
||||
rt_ver=$(sed -n 's/^runtime-version: *//p' "$manifest" | tr -d "\"'" | head -1)
|
||||
sdk=$(sed -n 's/^sdk: *//p' "$manifest" | head -1)
|
||||
exts=$(sed -n '/^sdk-extensions:/,/^[^ #-]/p' "$manifest" | sed -n 's/^ *- *//p')
|
||||
|
||||
[ -n "$runtime" ] && [ -n "$rt_ver" ] && [ -n "$sdk" ] && [ -n "$exts" ] || return 1
|
||||
|
||||
flatpak info --user "$runtime//$rt_ver" >/dev/null 2>&1 || return 1
|
||||
flatpak info --user "$sdk//$rt_ver" >/dev/null 2>&1 || return 1
|
||||
# Extensions are checked for PRESENCE, not version: flatpak-builder resolves their version from
|
||||
# the SDK's own metadata (it prints "Dependency Extension: … 25.08"), never from the manifest.
|
||||
# Any bump that moves them moves runtime-version too, which the two checks above already catch.
|
||||
for e in $exts; do
|
||||
flatpak info --user "$e" >/dev/null 2>&1 || return 1
|
||||
done
|
||||
}
|
||||
|
||||
self_test() {
|
||||
local rc fails=0 full
|
||||
# NOT `local`: the EXIT trap fires after this function has returned.
|
||||
SELFTEST_TMP=$(mktemp -d) || return 1
|
||||
trap 'rm -rf "$SELFTEST_TMP"' EXIT
|
||||
local tmp="$SELFTEST_TMP"
|
||||
|
||||
cat > "$tmp/ok.yml" <<'YML'
|
||||
runtime: org.gnome.Platform
|
||||
runtime-version: '50'
|
||||
sdk: org.gnome.Sdk
|
||||
sdk-extensions:
|
||||
- org.freedesktop.Sdk.Extension.rust-stable
|
||||
- org.freedesktop.Sdk.Extension.llvm20
|
||||
command: punktfunk-client
|
||||
YML
|
||||
# A manifest this script cannot read (the fail-open case).
|
||||
printf 'app-id: io.unom.Punktfunk\n' > "$tmp/unparseable.yml"
|
||||
|
||||
# Stub `flatpak`: $INSTALLED is the newline-separated set of refs it admits to having.
|
||||
mkdir -p "$tmp/bin"
|
||||
cat > "$tmp/bin/flatpak" <<'STUB'
|
||||
#!/usr/bin/env bash
|
||||
# only `flatpak info --user <ref>` is exercised here
|
||||
# args are: info --user <ref>
|
||||
[ "$1" = info ] || exit 0
|
||||
printf '%s\n' "$INSTALLED" | grep -qxF "$3"
|
||||
STUB
|
||||
chmod +x "$tmp/bin/flatpak"
|
||||
PATH="$tmp/bin:$PATH"
|
||||
|
||||
check() { # <expected rc> <label> <installed set> <manifest>
|
||||
INSTALLED="$3" deps_present "$4"; rc=$?
|
||||
if [ "$rc" != "$1" ]; then
|
||||
echo "FAIL: $2 (expected rc=$1, got $rc)" >&2; fails=$((fails + 1))
|
||||
else
|
||||
echo "ok: $2"
|
||||
fi
|
||||
}
|
||||
|
||||
full='org.gnome.Platform//50
|
||||
org.gnome.Sdk//50
|
||||
org.freedesktop.Sdk.Extension.rust-stable
|
||||
org.freedesktop.Sdk.Extension.llvm20'
|
||||
|
||||
check 0 "everything baked -> skip Flathub" "$full" "$tmp/ok.yml"
|
||||
check 1 "cold box -> install" "" "$tmp/ok.yml"
|
||||
check 1 "runtime missing -> install" "${full/org.gnome.Platform\/\/50/x}" "$tmp/ok.yml"
|
||||
check 1 "sdk missing -> install" "${full/org.gnome.Sdk\/\/50/x}" "$tmp/ok.yml"
|
||||
# The regression that started all this: llvm20 fine, rust-stable not.
|
||||
check 1 "one sdk-extension missing -> install" "${full/*.rust-stable/x}" "$tmp/ok.yml"
|
||||
# A runtime installed at ANOTHER version must not pass just because the name matches.
|
||||
check 1 "runtime at the wrong version" 'org.gnome.Platform//51
|
||||
org.gnome.Sdk//51
|
||||
org.freedesktop.Sdk.Extension.rust-stable
|
||||
org.freedesktop.Sdk.Extension.llvm20' "$tmp/ok.yml"
|
||||
check 1 "unreadable manifest -> fail open" "$full" "$tmp/unparseable.yml"
|
||||
|
||||
[ "$fails" = 0 ] || { echo "$fails check(s) failed" >&2; return 1; }
|
||||
echo "all checks passed"
|
||||
}
|
||||
|
||||
case "${1:---help}" in
|
||||
--self-test) self_test ;;
|
||||
--help|-h) sed -n '2,4p' "$0"; exit 2 ;;
|
||||
*) deps_present "$1" ;;
|
||||
esac
|
||||
Executable
+62
@@ -0,0 +1,62 @@
|
||||
#!/bin/sh
|
||||
# Put a retrying `curl` first on PATH for the rest of the job.
|
||||
#
|
||||
# WHY THIS EXISTS: `scripts/ci/retry.sh` already wraps every single-shot network command in CI,
|
||||
# for the reason documented there — the runner box runs many jobs in parallel and its network
|
||||
# drops packets under that load. But one of the biggest fetches in this workspace is NOT ours to
|
||||
# wrap: skia-bindings downloads ~19 MB of prebuilt Skia per target from inside its build script,
|
||||
# with a bare `curl -sS -f -L` and no retry at all (build_support/binary_cache/utils.rs).
|
||||
#
|
||||
# When that transfer truncates the job does not fail with a network error. skia-bindings'
|
||||
# `try_prepare_download` swallows it, prints `DOWNLOAD AND INSTALL FAILED`, and falls through to
|
||||
# `STARTING A FULL BUILD` — a from-source Skia build that the CI containers carry no deps for.
|
||||
# What the operator sees is a Gradle stack trace under "Clippy (Android target)" with the real
|
||||
# cause 1,800 lines up. Measured on main 2026-08-22:
|
||||
#
|
||||
# DOWNLOAD AND INSTALL FAILED: curl error code: "18"
|
||||
# curl stderr: "curl: (18) end of response with 17054400 bytes missing"
|
||||
#
|
||||
# (19,057,024 bytes on the wire; it got 2 MB before git.unom.io closed the connection. The same
|
||||
# asset pulls fine from a dev box, so this is the load-shedding retry.sh was written for.)
|
||||
#
|
||||
# A shim is the only lever that reaches inside a build script. It is also the cheapest correct
|
||||
# one: skia-bindings already passes `-C -` (resume) and caches the part-file under
|
||||
# OUT_DIR/.cache, so a retry CONTINUES the truncated transfer instead of restarting it.
|
||||
#
|
||||
# Applies to every curl in the job, which is what we want — the workspace's other build-script
|
||||
# fetches are single-shot too.
|
||||
#
|
||||
# POSIX sh on purpose: Gitea's act_runner executes a step's `run:` under `sh -e` (dash) inside
|
||||
# the Linux job containers — see the shader-gate note in ci.yml for what assuming bash cost.
|
||||
#
|
||||
# Usage: sh scripts/ci/install-retrying-curl.sh
|
||||
set -e
|
||||
|
||||
# Resolve the REAL curl before the shim is on PATH, and bake the absolute path into the shim —
|
||||
# a shim that re-resolves `curl` by name would exec itself.
|
||||
real_curl=$(command -v curl || true)
|
||||
if [ -z "$real_curl" ]; then
|
||||
echo "::warning::no curl on PATH — skipping the retrying-curl shim"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# RUNNER_TEMP (not /usr/local/bin): the job containers run as root but the macOS runner is a
|
||||
# persistent host where a system dir is neither writable nor ours to litter.
|
||||
shim_dir="${RUNNER_TEMP:-/tmp}/pf-retrying-curl"
|
||||
mkdir -p "$shim_dir"
|
||||
|
||||
# --retry-all-errors is what makes this cover error 18: a truncated transfer is a *transfer*
|
||||
# failure, not an HTTP status, so plain --retry (which only retries transient HTTP codes and
|
||||
# connection errors) would let it through. Needs curl >= 7.71; the CI images are well past it.
|
||||
cat > "$shim_dir/curl" <<EOF
|
||||
#!/bin/sh
|
||||
exec $real_curl --retry 5 --retry-delay 3 --retry-all-errors "\$@"
|
||||
EOF
|
||||
chmod +x "$shim_dir/curl"
|
||||
|
||||
if [ -n "${GITHUB_PATH:-}" ]; then
|
||||
echo "$shim_dir" >> "$GITHUB_PATH"
|
||||
echo "retrying curl installed: $shim_dir/curl -> $real_curl"
|
||||
else
|
||||
echo "::warning::GITHUB_PATH unset — shim written to $shim_dir but not on PATH"
|
||||
fi
|
||||
@@ -68,6 +68,22 @@ log "Building punktfunk-gamescope (HDR 10-bit capture; ~5-10 min, best-effort)"
|
||||
# the two lists in step). Provisioned here, not in install.sh's main pass, so a dep problem can
|
||||
# only ever cost this feature. glm/stb come in as meson wraps; wlroots/libliftoff/vkroots/
|
||||
# libdisplay-info are vendored submodules — none of those need packages.
|
||||
#
|
||||
# ⚠ The last two names are the WSI LAYER's, and x11-xcb's absence is why this leg failed on every
|
||||
# Deck from 2026-08-13 (3ac4548c turned `-Denable_gamescope_wsi_layer=true` on) until it was
|
||||
# noticed as "HDR stopped working after an update". It does NOT fail the compositor build — it
|
||||
# fails layer/meson.build, and build-punktfunk-gamescope.sh treats a missing layer as a hard
|
||||
# error, so the whole build exits non-zero. ci/gamescope-trixie.Dockerfile walked into the
|
||||
# identical trap one release later (1b28a7f7, v0.28.1) and now asserts x11-xcb at image build;
|
||||
# this list never got the same fix.
|
||||
#
|
||||
# ⚠ Do NOT "sync this list with the CI image". That one is for a .deb that RUNS on Debian; this
|
||||
# one builds in trixie for a binary that must run on SteamOS. Taking libdisplay-info-dev from it
|
||||
# (tried on the lab VM, 2026-08-23) built, installed and printed its +pfhdr banner in the box —
|
||||
# then died on glass with `libdisplay-info.so.2: cannot open shared object file`, because meson
|
||||
# had preferred the system lib over gamescope's vendored submodule and linked it SHARED. The
|
||||
# durable fix is the force_fallback_for pin in build-punktfunk-gamescope.sh, next to wlroots;
|
||||
# the package has no reason to be here. Only add a name whose soname SteamOS itself ships.
|
||||
if ! distrobox enter "$BOX" -- bash -lc '
|
||||
set -e
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
@@ -85,7 +101,8 @@ sudo apt-get install -y -qq --no-install-recommends \
|
||||
libvulkan-dev libglm-dev libpixman-1-dev libeis-dev \
|
||||
libavif-dev libdecor-0-dev hwdata libluajit-5.1-dev \
|
||||
libpipewire-0.3-dev libspa-0.2-dev libsdl2-dev \
|
||||
xwayland liblcms2-dev >/dev/null
|
||||
xwayland liblcms2-dev \
|
||||
libx11-xcb-dev libxkbcommon-x11-dev >/dev/null
|
||||
' ; then
|
||||
warn "could not provision gamescope build deps in '$BOX' — sessions stay SDR (re-run update.sh to retry)"
|
||||
exit 0
|
||||
@@ -94,8 +111,20 @@ if ! distrobox enter "$BOX" -- bash -lc "
|
||||
set -e
|
||||
bash '$PKGDIR/build-punktfunk-gamescope.sh' --prefix \"\$HOME/.local\" --no-setcap
|
||||
"; then
|
||||
warn "punktfunk-gamescope failed to build — sessions stay SDR (re-run update.sh to retry)"
|
||||
unwire
|
||||
# A failed build REPLACED NOTHING — the previously installed binary is untouched on disk. If it
|
||||
# still passes the on-glass check it is the very binary that was streaming HDR before this run,
|
||||
# so keep it wired and say it is stale. Unwiring here took HDR away from boxes whose compositor
|
||||
# still worked, on an update that changed nothing about it (field report: HDR "lost" going to
|
||||
# 0.31.2, host.env silently missing PUNKTFUNK_GAMESCOPE_BIN afterwards). `unwire` belongs only
|
||||
# where the binary itself fails `verifies` — the else branch at the bottom, which also removes
|
||||
# it. `wire` re-arms a box a previous run of this bug already unwired.
|
||||
if verifies; then
|
||||
warn "punktfunk-gamescope failed to build — keeping the installed $("$GS_BIN" --version 2>&1 | head -1) (stale; re-run update.sh to retry)"
|
||||
wire
|
||||
else
|
||||
warn "punktfunk-gamescope failed to build and none is installed — sessions stay SDR (re-run update.sh to retry)"
|
||||
unwire
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@punktfunk/host",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.6",
|
||||
"description": "TypeScript SDK for the punktfunk streaming host: typed management-API client + lifecycle event stream, built on Effect.",
|
||||
"type": "module",
|
||||
"license": "MIT OR Apache-2.0",
|
||||
|
||||
+379
-62
File diff suppressed because one or more lines are too long
+1
-1
@@ -8,4 +8,4 @@
|
||||
*
|
||||
* `version.test.ts` fails if this and `package.json` disagree, so the duplication cannot rot.
|
||||
*/
|
||||
export const SDK_VERSION = "0.1.5";
|
||||
export const SDK_VERSION = "0.1.6";
|
||||
|
||||
@@ -119,6 +119,7 @@
|
||||
"action_request_idr": "Keyframe anfordern",
|
||||
"action_unpair": "Entkoppeln",
|
||||
"action_unpair_all": "Alle entkoppeln",
|
||||
"action_rename": "Umbenennen",
|
||||
"connect_title": "Gerät verbinden",
|
||||
"connect_help": "Gib die Adresse in einem Punktfunk-Client ein — oder öffne den Link auf einem Gerät, auf dem bereits einer installiert ist: er führt direkt zu diesem Host. Gekoppelt wird auf der Seite „Kopplung“.",
|
||||
"connect_address": "Host-Adresse",
|
||||
@@ -246,6 +247,10 @@
|
||||
"display_discard_confirm": "Du hast nicht gespeicherte eigene Einstellungen. Verwerfen?",
|
||||
"clients_name": "Name",
|
||||
"clients_fingerprint": "Fingerabdruck",
|
||||
"clients_rename_title": "Gerät umbenennen",
|
||||
"clients_rename_body": "Moonlight-Clients melden sich alle gleich, deshalb vergibst du diesen Namen selbst. Leer lassen, um ihn zu entfernen.",
|
||||
"clients_rename_label": "Anzeigename",
|
||||
"clients_rename_failed": "Gerät konnte nicht umbenannt werden",
|
||||
"pairing_title": "Kopplung",
|
||||
"pairing_idle": "Keine Kopplung aktiv. Starte die Kopplung in einem Moonlight-Client und gib hier die PIN ein.",
|
||||
"pairing_waiting": "Ein Gerät wartet auf Kopplung. Gib die angezeigte PIN ein:",
|
||||
|
||||
@@ -119,6 +119,7 @@
|
||||
"action_request_idr": "Request keyframe",
|
||||
"action_unpair": "Unpair",
|
||||
"action_unpair_all": "Unpair all",
|
||||
"action_rename": "Rename",
|
||||
"connect_title": "Connect a device",
|
||||
"connect_help": "Type the address into a punktfunk client, or open the link on a device that already has one installed — it opens straight onto this host. Pair from the Pairing page.",
|
||||
"connect_address": "Host address",
|
||||
@@ -246,6 +247,10 @@
|
||||
"display_discard_confirm": "You have unsaved custom settings. Discard them?",
|
||||
"clients_name": "Name",
|
||||
"clients_fingerprint": "Fingerprint",
|
||||
"clients_rename_title": "Rename device",
|
||||
"clients_rename_body": "Moonlight clients all identify themselves the same way, so this name is yours to set. Leave it empty to remove it.",
|
||||
"clients_rename_label": "Display name",
|
||||
"clients_rename_failed": "Could not rename the device",
|
||||
"pairing_title": "Pairing",
|
||||
"pairing_idle": "No pairing in progress. Start pairing from a Moonlight client, then enter its PIN here.",
|
||||
"pairing_waiting": "A client is waiting to pair. Enter the PIN it shows:",
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "@unom/ui/toast";
|
||||
import { SlidersHorizontal, Trash2 } from "lucide-react";
|
||||
import { Pencil, SlidersHorizontal, Trash2 } from "lucide-react";
|
||||
import { type FC, useState } from "react";
|
||||
import {
|
||||
getListPairedClientsQueryKey,
|
||||
useListPairedClients,
|
||||
useRenameClient,
|
||||
useUnpairAllClients,
|
||||
useUnpairClient,
|
||||
} from "@/api/gen/clients/clients";
|
||||
@@ -40,8 +41,18 @@ export type PairedProtocol = "native" | "moonlight";
|
||||
export interface PairedRow {
|
||||
protocol: PairedProtocol;
|
||||
fingerprint: string;
|
||||
/** Native devices carry a name; Moonlight clients carry a cert subject; either may be empty. */
|
||||
/**
|
||||
* What to show in the Name column. Native devices carry a name from pairing; a Moonlight client
|
||||
* shows its operator-given label if it has one, and otherwise falls back to its cert subject —
|
||||
* which is the same fixed string for every Moonlight client alive, hence [`label`].
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* The operator-assigned label, Moonlight rows only — `null` when the device has never been
|
||||
* named. Distinct from `name` because the rename dialog must open on the label alone: seeding
|
||||
* it with the `CN=…` fallback would make every rename start by deleting boilerplate.
|
||||
*/
|
||||
label?: string | null;
|
||||
/**
|
||||
* Access fields — native rows only, and only from hosts that have them (the console pairs
|
||||
* against older hosts: all four stay `undefined` then, and the Access column shows "—").
|
||||
@@ -67,13 +78,14 @@ const hasAccess = (r: PairedRow): boolean =>
|
||||
*/
|
||||
export const PairedDevicesSection: FC = () => {
|
||||
const qc = useQueryClient();
|
||||
const { confirm } = useDialogs();
|
||||
const { confirm, promptText } = useDialogs();
|
||||
const native = useListNativeClients();
|
||||
const moonlight = useListPairedClients();
|
||||
const unpairNative = useUnpairNativeClient();
|
||||
const unpairMoonlight = useUnpairClient();
|
||||
const unpairAllNative = useUnpairAllNativeClients();
|
||||
const unpairAllMoonlight = useUnpairAllClients();
|
||||
const renameMoonlight = useRenameClient();
|
||||
const patchAccess = useUpdateNativeClientAccess();
|
||||
// One clock for every countdown in the card AND the sheet — recomputed client-side from
|
||||
// `expires_unix`, so the tick never refetches anything.
|
||||
@@ -97,7 +109,8 @@ export const PairedDevicesSection: FC = () => {
|
||||
(c): PairedRow => ({
|
||||
protocol: "moonlight",
|
||||
fingerprint: c.fingerprint,
|
||||
name: c.subject ?? "",
|
||||
name: c.label ?? c.subject ?? "",
|
||||
label: c.label,
|
||||
}),
|
||||
),
|
||||
];
|
||||
@@ -129,6 +142,32 @@ export const PairedDevicesSection: FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Name a Moonlight device. Every Moonlight client presents the identical certificate subject,
|
||||
* so without this the list is a column of `CN=NVIDIA GameStream Client` rows and the only way
|
||||
* to tell a phone from a TV — or to know which one you are about to unpair — is the
|
||||
* fingerprint. Submitting an empty field clears the name (the host reads that as "unnamed"),
|
||||
* which is why cancel (`null`) and empty are handled differently here.
|
||||
*/
|
||||
const onRename = async (row: PairedRow) => {
|
||||
const next = await promptText({
|
||||
title: m.clients_rename_title(),
|
||||
description: m.clients_rename_body(),
|
||||
label: m.clients_rename_label(),
|
||||
defaultValue: row.label ?? "",
|
||||
confirmLabel: m.action_rename(),
|
||||
});
|
||||
if (next === null) return;
|
||||
renameMoonlight.mutate(
|
||||
{ fingerprint: row.fingerprint, data: { label: next.trim() || null } },
|
||||
{
|
||||
onSuccess: () =>
|
||||
qc.invalidateQueries({ queryKey: getListPairedClientsQueryKey() }),
|
||||
onError: () => toast.error(m.clients_rename_failed()),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const savedAccess = () => {
|
||||
setEditing(null);
|
||||
qc.invalidateQueries({ queryKey: getListNativeClientsQueryKey() });
|
||||
@@ -218,6 +257,7 @@ export const PairedDevicesSection: FC = () => {
|
||||
expiresUnix: r.expiresUnix,
|
||||
})
|
||||
}
|
||||
onRename={onRename}
|
||||
onUnpair={onUnpair}
|
||||
onUnpairAll={onUnpairAll}
|
||||
pendingFingerprint={pendingFingerprint}
|
||||
@@ -246,6 +286,11 @@ export const PairedDevices: FC<{
|
||||
nowUnix: number;
|
||||
/** Open the access editor for a native row (only offered where `hasAccess`). */
|
||||
onEditAccess: (row: PairedRow) => void;
|
||||
/**
|
||||
* Name a Moonlight row. Offered only on those: a native device already carries the name it gave
|
||||
* at pairing, while a Moonlight certificate carries nothing that identifies the device at all.
|
||||
*/
|
||||
onRename: (row: PairedRow) => void;
|
||||
onUnpair: (protocol: PairedProtocol, fingerprint: string) => void;
|
||||
/** Unpair every row, behind one confirmation. */
|
||||
onUnpairAll: () => void;
|
||||
@@ -260,6 +305,7 @@ export const PairedDevices: FC<{
|
||||
refetch,
|
||||
nowUnix,
|
||||
onEditAccess,
|
||||
onRename,
|
||||
onUnpair,
|
||||
onUnpairAll,
|
||||
pendingFingerprint,
|
||||
@@ -342,6 +388,20 @@ export const PairedDevices: FC<{
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex justify-end">
|
||||
{r.protocol === "moonlight" && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={m.action_rename()}
|
||||
disabled={
|
||||
isUnpairingAll ||
|
||||
pendingFingerprint === r.fingerprint
|
||||
}
|
||||
onClick={() => onRename(r)}
|
||||
>
|
||||
<Pencil className="size-4" />
|
||||
</Button>
|
||||
)}
|
||||
{hasAccess(r) && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
|
||||
@@ -29,7 +29,8 @@ const nativeRows: PairedRow[] = nativeClients.map((c) => ({
|
||||
const moonlightRows: PairedRow[] = pairedClients.map((c) => ({
|
||||
protocol: "moonlight" as const,
|
||||
fingerprint: c.fingerprint,
|
||||
name: c.subject ?? "",
|
||||
name: c.label ?? c.subject ?? "",
|
||||
label: c.label,
|
||||
}));
|
||||
|
||||
// Renders the REAL page layout (PairingView) — the same component index.tsx uses. The live page
|
||||
@@ -84,6 +85,7 @@ export const Armed: Story = {
|
||||
refetch={noop}
|
||||
nowUnix={accessNowUnix}
|
||||
onEditAccess={noop}
|
||||
onRename={noop}
|
||||
onUnpair={noop}
|
||||
onUnpairAll={noop}
|
||||
pendingFingerprint={null}
|
||||
|
||||
@@ -25,7 +25,8 @@ const nativeRows: PairedRow[] = nativeClients.map((c) => ({
|
||||
const moonlightRows: PairedRow[] = pairedClients.map((c) => ({
|
||||
protocol: "moonlight" as const,
|
||||
fingerprint: c.fingerprint,
|
||||
name: c.subject ?? "",
|
||||
name: c.label ?? c.subject ?? "",
|
||||
label: c.label,
|
||||
}));
|
||||
|
||||
// Per-client access states, separate from Pages/Pairing: these stories render single components
|
||||
@@ -106,6 +107,7 @@ export const AccessColumn: Story = {
|
||||
refetch={noop}
|
||||
nowUnix={accessNowUnix}
|
||||
onEditAccess={noop}
|
||||
onRename={noop}
|
||||
onUnpair={noop}
|
||||
onUnpairAll={noop}
|
||||
pendingFingerprint={null}
|
||||
|
||||
@@ -120,6 +120,9 @@ export const pairedClients: PairedClient[] = [
|
||||
fingerprint:
|
||||
"ff00eeddccbbaa998877665544332211009f8e7d6c5b4a39281706f5e4d3c2b1",
|
||||
subject: "living-room-tv",
|
||||
// Named by the operator — the row that shows what a rename buys you next to a sibling that
|
||||
// still reads as its (identical-for-everyone) certificate subject.
|
||||
label: "Living Room TV",
|
||||
not_before_unix: 1_718_500_000,
|
||||
not_after_unix: 2_030_000_000,
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user