Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d15548e38 | ||
|
|
b79ff45bd1 | ||
|
|
d0a3eca7b8 | ||
|
|
bf741f8693 | ||
|
|
ea5afbaa8c | ||
|
|
832a5ffd8d | ||
|
|
76c677a8f8 | ||
|
|
7cb70bf6ea | ||
|
|
b6b3c10cb5 | ||
|
|
1a8fa2282f | ||
|
|
d669064dc0 | ||
|
|
d4ad8be6bf | ||
|
|
e0c10bad85 | ||
|
|
1b28a7f7f1 | ||
|
|
ceb081f045 | ||
|
|
0870f81148 | ||
|
|
f8361f3e6f | ||
|
|
e8bc10bf0c | ||
|
|
4499313749 | ||
|
|
784f880fbf | ||
|
|
8ca4c6eb0e | ||
|
|
13aa59c575 | ||
|
|
652de8b5e0 | ||
|
|
ec36597058 | ||
|
|
e5c0d6b4eb | ||
|
|
0bba8d7f8c | ||
|
|
0ead084838 | ||
|
|
0f9ccfa8b6 | ||
|
|
8d60f1cec0 | ||
|
|
6dd4add11b | ||
|
|
b6cc76c472 | ||
|
|
e2239fd964 | ||
|
|
f17fe1fc2b | ||
|
|
a3a6444e6e | ||
|
|
38631d43df | ||
|
|
4caf2b76e8 | ||
|
|
0f64551c56 | ||
|
|
8fe5acf7f2 | ||
|
|
fb33555059 | ||
|
|
81022bcc80 | ||
|
|
1b167f8e35 | ||
|
|
082c65755f | ||
|
|
9c2c8d1643 | ||
|
|
c591b7b4af | ||
|
|
3ac4548cf8 | ||
|
|
90d13de81e | ||
|
|
1abf5c91b9 | ||
|
|
6fd5769b3b | ||
|
|
ed8c080603 | ||
|
|
a190fdb1ae | ||
|
|
94f049ba70 | ||
|
|
c29e720324 | ||
|
|
e057bd60f4 | ||
|
|
96278eebb5 | ||
|
|
fdf48fcaa1 | ||
|
|
05a08b9804 | ||
|
|
99c245520c | ||
|
|
4ab6a399e6 | ||
|
|
8216f1d92d | ||
|
|
1677d1c0c2 | ||
|
|
9a52d725d5 | ||
|
|
fbbfce9b0e | ||
|
|
c12476736d | ||
|
|
5bcee83c34 | ||
|
|
4ebe7d1185 | ||
|
|
3f738a9989 | ||
|
|
7df321f459 | ||
|
|
c7d0fd2e03 | ||
|
|
9c13335089 | ||
|
|
92db66514b | ||
|
|
86cbbea020 | ||
|
|
3d5d8e2d76 | ||
|
|
8f6eb1494d | ||
|
|
362d532d25 | ||
|
|
b2a9b281f0 | ||
|
|
e568513f74 | ||
|
|
7403450a8d | ||
|
|
0a53457cb7 | ||
|
|
e7af5a5274 |
+21
-10
@@ -676,20 +676,23 @@ jobs:
|
||||
# Skipped on PRs (cost); runs on main pushes + manual dispatch. Needs the build/test job green
|
||||
# first, and is a separate job so a capture hiccup can never red the core signal.
|
||||
#
|
||||
# Scope = the two REQUIRED iOS sizes (iPhone 6.9" + iPad 13"), captured on the Simulator
|
||||
# (`simctl io screenshot`, no Screen Recording grant needed). macOS and tvOS are deliberately
|
||||
# NOT in CI: the self-hosted runner is headless (no window-server session), so the mac window
|
||||
# capture can't run there; tvOS needs the Tier-3 build-std slice. Generate those two locally on
|
||||
# a GUI Mac with `clients/apple/tools/screenshots.sh macos tvos`.
|
||||
# Scope = the two REQUIRED iOS sizes (iPhone 6.9" + iPad 13") + Apple TV (1920×1080), captured
|
||||
# on the Simulator (`simctl io screenshot`, no Screen Recording grant needed). The tvOS slice is
|
||||
# Tier-3 (nightly -Zbuild-std, same as the distribute job — slow cold, cached on the self-hosted
|
||||
# runner). The tvOS scene list is explicit: the gamepad-console scenes are iOS/macOS-only, and an
|
||||
# unknown scene name falls back to a NORMAL app launch — the capture would silently be of the
|
||||
# real empty app. macOS stays deliberately NOT in CI: the runner is headless (no window-server
|
||||
# session), so the mac window capture can't run there — generate it locally on a GUI Mac with
|
||||
# `clients/apple/tools/screenshots.sh macos`.
|
||||
screenshots:
|
||||
needs: swift
|
||||
if: gitea.event_name != 'pull_request'
|
||||
runs-on: macos-arm64
|
||||
timeout-minutes: 75
|
||||
timeout-minutes: 90
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Rust toolchain + iOS Simulator targets
|
||||
- name: Rust toolchain + iOS Simulator targets (+ nightly for the tvOS slices)
|
||||
run: |
|
||||
if ! command -v rustup >/dev/null && [ ! -x "$HOME/.cargo/bin/rustup" ]; then
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
|
||||
@@ -699,6 +702,10 @@ jobs:
|
||||
dirname "$RUSTUP" >> "$GITHUB_PATH"
|
||||
"$RUSTUP" target add aarch64-apple-darwin x86_64-apple-darwin \
|
||||
aarch64-apple-ios aarch64-apple-ios-sim x86_64-apple-ios
|
||||
# tvOS targets are tier-3 (no prebuilt std) — build-xcframework.sh compiles them with
|
||||
# nightly + -Zbuild-std, so ensure nightly + rust-src are present (see the swift job).
|
||||
"$RUSTUP" toolchain install nightly --profile minimal
|
||||
"$RUSTUP" component add rust-src --toolchain nightly
|
||||
|
||||
# Shared compile cache. The script handles the macOS side (user-prefix install +
|
||||
# GITHUB_PATH, bsdtar globbing) — see scripts/ci/ensure-sccache.sh.
|
||||
@@ -735,10 +742,10 @@ jobs:
|
||||
-mtime +7 -exec rm -rf {} + 2>/dev/null || true
|
||||
fi
|
||||
|
||||
- name: Build PunktfunkCore.xcframework (mac + iOS slices)
|
||||
run: BUILD_IOS=1 bash scripts/build-xcframework.sh
|
||||
- name: Build PunktfunkCore.xcframework (mac + iOS + tvOS slices)
|
||||
run: BUILD_IOS=1 BUILD_TVOS=1 bash scripts/build-xcframework.sh
|
||||
|
||||
- name: Capture screenshots (iPhone 6.9" + iPad 13"; auto-creates the Simulators)
|
||||
- name: Capture screenshots (iPhone 6.9" + iPad 13" + Apple TV; auto-creates the Simulators)
|
||||
working-directory: clients/apple
|
||||
env:
|
||||
SETTLE: "8" # Simulators settle slower than a local run
|
||||
@@ -746,6 +753,10 @@ jobs:
|
||||
# Independent invocations: one platform failing skips it, not the other.
|
||||
bash tools/screenshots.sh ios || echo "::warning::iOS (iPhone 6.9\") screenshots skipped"
|
||||
bash tools/screenshots.sh ipad || echo "::warning::iPad 13\" screenshots skipped"
|
||||
# tvOS shoots only the scenes that exist there — the 06–09 gamepad-console scenes are
|
||||
# compiled out on tvOS (native focus engine), and an unknown name = a normal app launch.
|
||||
SCENES="01-stream 02-hosts 05-settings 03-pair" \
|
||||
bash tools/screenshots.sh tvos || echo "::warning::Apple TV screenshots skipped"
|
||||
echo "Produced:"; ls -la screenshots || true
|
||||
|
||||
- name: Shut the Simulators down (leaked booted sims once piled up 846 deep)
|
||||
|
||||
@@ -517,15 +517,17 @@ jobs:
|
||||
bash packaging/gamescope/build-punktfunk-gamescope.sh \
|
||||
--destdir "$PWD/gs-stage" --prefix /usr --jobs "$(nproc)" \
|
||||
--extra-fallback libdisplay-info
|
||||
install -Dm0755 gs-stage/usr/bin/punktfunk-gamescope gs-cache/punktfunk-gamescope
|
||||
# The WHOLE staged tree, not just the binary: it also carries the Vulkan WSI layer built
|
||||
# beside the compositor, which is the only route to an HDR10 swapchain for a nested game.
|
||||
mkdir -p gs-cache && cp -a gs-stage/. gs-cache/
|
||||
|
||||
# The binary must RUN, not merely link: `--version` is what the old job used as its ship
|
||||
# gate, and it is the cheapest proof that the static-libstdc++ trick and the vendored wlroots
|
||||
# actually produced a working compositor.
|
||||
- name: Build the .deb
|
||||
run: |
|
||||
gs-cache/punktfunk-gamescope --version
|
||||
bash packaging/debian/build-gamescope-deb.sh --binary gs-cache/punktfunk-gamescope
|
||||
gs-cache/usr/bin/punktfunk-gamescope --version
|
||||
bash packaging/debian/build-gamescope-deb.sh --stage gs-cache
|
||||
|
||||
- name: Publish to the Gitea apt registry
|
||||
env:
|
||||
|
||||
@@ -293,7 +293,11 @@ jobs:
|
||||
dnf -y install wayland-protocols-devel glm-devel cmake libXcursor-devel || true
|
||||
if bash packaging/gamescope/build-punktfunk-gamescope.sh \
|
||||
--destdir "$PWD/gs-stage" --prefix /usr --jobs "$(nproc)"; then
|
||||
install -Dm0755 gs-stage/usr/bin/punktfunk-gamescope gs-cache/punktfunk-gamescope
|
||||
# The WHOLE staged tree, not just the binary: it also carries the Vulkan WSI layer built
|
||||
# beside the compositor, which is the only thing that can give a nested game an HDR10
|
||||
# swapchain. Caching the tree rather than a file per artifact is what keeps the next
|
||||
# addition from needing a change here as well as in every packaging script.
|
||||
mkdir -p gs-cache && cp -a gs-stage/. gs-cache/
|
||||
else
|
||||
# Warn only, even on a tag — the hard gate is the LAST step of this job. Failing here
|
||||
# would skip the sysext build, the sysext feed, AND the release attach below, so a
|
||||
@@ -311,9 +315,9 @@ jobs:
|
||||
# existing SDR/host-composited path. The spec re-checks the +pfhdr marker itself.
|
||||
- name: Package punktfunk-gamescope as an RPM
|
||||
run: |
|
||||
if [ -x gs-cache/punktfunk-gamescope ] && gs-cache/punktfunk-gamescope --version >/dev/null 2>&1; then
|
||||
if [ -x gs-cache/usr/bin/punktfunk-gamescope ] && gs-cache/usr/bin/punktfunk-gamescope --version >/dev/null 2>&1; then
|
||||
bash packaging/gamescope/build-gamescope-rpm.sh \
|
||||
--binary gs-cache/punktfunk-gamescope \
|
||||
--stage gs-cache \
|
||||
--release "$PF_RELEASE"
|
||||
else
|
||||
# Warn only — see the note on the build step. The gate is the last step of this job.
|
||||
@@ -372,9 +376,9 @@ jobs:
|
||||
# whose runtime libs are missing from this container must cost the image its HDR, not the
|
||||
# image itself.
|
||||
gs=()
|
||||
if [ -x gs-cache/punktfunk-gamescope ] && gs-cache/punktfunk-gamescope --version >/dev/null 2>&1; then
|
||||
gs=(--gamescope gs-cache/punktfunk-gamescope)
|
||||
echo "folding in $(gs-cache/punktfunk-gamescope --version 2>&1 | head -1)"
|
||||
if [ -x gs-cache/usr/bin/punktfunk-gamescope ] && gs-cache/usr/bin/punktfunk-gamescope --version >/dev/null 2>&1; then
|
||||
gs=(--gamescope-stage gs-cache)
|
||||
echo "folding in $(gs-cache/usr/bin/punktfunk-gamescope --version 2>&1 | head -1)"
|
||||
else
|
||||
echo "::warning::no usable punktfunk-gamescope for f${{ matrix.fedver }} — the sysext ships without it (gamescope sessions stay SDR)"
|
||||
fi
|
||||
|
||||
@@ -257,6 +257,19 @@ jobs:
|
||||
if: github.event_name != 'pull_request'
|
||||
shell: pwsh
|
||||
env:
|
||||
# Azure Artifact Signing (formerly Trusted Signing) — takes precedence over MSIX_CERT_*
|
||||
# when all three are set. Not secret: an account/profile name and a regional endpoint,
|
||||
# inert without the credentials below. The profile's verified subject is also the MSIX
|
||||
# manifest Publisher; pack-msix.ps1 reads the signature back and fails on a mismatch.
|
||||
AZURE_CODESIGNING_ENDPOINT: https://neu.codesigning.azure.net/
|
||||
AZURE_CODESIGNING_ACCOUNT: unomsigning
|
||||
AZURE_CODESIGNING_PROFILE: unom-io
|
||||
# Service principal 'punktfunk-ci-signing', holding ONLY the Artifact Signing Certificate
|
||||
# Profile Signer role, scoped to the unom-io profile — it can sign and nothing else.
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
# Legacy self-signed path, kept as the fallback for builds without Azure access.
|
||||
MSIX_CERT_PFX_B64: ${{ secrets.MSIX_CERT_PFX_B64 }}
|
||||
MSIX_CERT_PASSWORD: ${{ secrets.MSIX_CERT_PASSWORD }}
|
||||
run: |
|
||||
|
||||
@@ -20,12 +20,18 @@
|
||||
# main push / dispatch -> <next-minor>.<run_number> (canary; `canary/` alias; base one minor
|
||||
# ahead of the latest stable tag via scripts/ci/pf-version.ps1, run climbs).
|
||||
#
|
||||
# Signing reuses the client's MSIX_CERT_PFX_B64 / MSIX_CERT_PASSWORD secrets (CN=unom). Without them
|
||||
# an ephemeral self-signed cert is generated and its public .cer published next to the installer
|
||||
# (import once to LocalMachine\TrustedPublisher). That fallback is for canary/CI ONLY — on a v* tag
|
||||
# Signing goes through Azure Artifact Signing (account `unomsigning`, profile `unom-io`) — a publicly
|
||||
# trusted CA, so there is no .cer for users to import and no SmartScreen "unknown publisher" prompt.
|
||||
# It falls back to the old MSIX_CERT_PFX_B64 / MSIX_CERT_PASSWORD self-signed cert, and then to an
|
||||
# ephemeral one, for builds without Azure access. Those fallbacks are for canary/CI ONLY — on a v* tag
|
||||
# the pack script FAILS CLOSED rather than ship a release signed by a per-build throwaway cert.
|
||||
# See packaging/windows/pack-host-installer.ps1.
|
||||
#
|
||||
# The bundled DRIVERS are NOT signed by Azure — they keep their own DRIVER_CERT_* cert and are still
|
||||
# trusted by planting that cert in the machine Root store at install time. Independent by design:
|
||||
# Windows checks the installer's signature via SmartScreen/UAC and driver catalogs via PnP, and never
|
||||
# requires a common signer. See packaging/windows/README.md for why that root-plant is still there.
|
||||
#
|
||||
# GPU backends: the host builds with --features nvenc,amf-qsv,qsv = all three vendors in one installer.
|
||||
# - NVENC (NVIDIA, direct SDK): nothing needed at build time — the entry points are resolved at
|
||||
# RUNTIME from the driver's nvEncodeAPI64.dll (a link-time import would kill the binary on
|
||||
@@ -415,12 +421,26 @@ jobs:
|
||||
- name: Pack + sign installer
|
||||
shell: pwsh
|
||||
env:
|
||||
# Azure Artifact Signing (formerly Trusted Signing) — takes precedence over MSIX_CERT_*
|
||||
# when all three of these are set. Not secret: an account/profile name and a regional
|
||||
# endpoint, all inert without the credentials below, so they live here where a reviewer
|
||||
# can see which profile a release was signed by.
|
||||
AZURE_CODESIGNING_ENDPOINT: https://neu.codesigning.azure.net/
|
||||
AZURE_CODESIGNING_ACCOUNT: unomsigning
|
||||
AZURE_CODESIGNING_PROFILE: unom-io
|
||||
# Service principal 'punktfunk-ci-signing', holding ONLY the Artifact Signing Certificate
|
||||
# Profile Signer role, scoped to the unom-io profile — it can sign and nothing else.
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
# Legacy self-signed path, kept as the fallback for builds without Azure access.
|
||||
MSIX_CERT_PFX_B64: ${{ secrets.MSIX_CERT_PFX_B64 }}
|
||||
MSIX_CERT_PASSWORD: ${{ secrets.MSIX_CERT_PASSWORD }}
|
||||
# The DRIVER cert is separate from the host/MSIX one and reaches the two driver build
|
||||
# scripts through the environment (pack-host-installer.ps1 invokes them, they read
|
||||
# $env:DRIVER_CERT_PFX_B64 themselves). Without it they sign with a per-build throwaway,
|
||||
# which the installer then trusts as a machine root — see packaging/windows/README.md.
|
||||
# NOT moved to Azure: driver catalogs are a separate track, see that README.
|
||||
DRIVER_CERT_PFX_B64: ${{ secrets.DRIVER_CERT_PFX_B64 }}
|
||||
DRIVER_CERT_PASSWORD: ${{ secrets.DRIVER_CERT_PASSWORD }}
|
||||
run: |
|
||||
|
||||
+1200
-2
File diff suppressed because it is too large
Load Diff
Generated
+37
-129
@@ -1090,7 +1090,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cursor-probe"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"pf-capture",
|
||||
@@ -1222,7 +1222,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "display-disturb"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"pf-win-display",
|
||||
"windows 0.62.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
@@ -1353,18 +1353,6 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fallible-iterator"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
|
||||
|
||||
[[package]]
|
||||
name = "fallible-streaming-iterator"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
|
||||
|
||||
[[package]]
|
||||
name = "fastbloom"
|
||||
version = "0.17.0"
|
||||
@@ -1999,32 +1987,11 @@ dependencies = [
|
||||
"zerocopy 0.8.56",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.16.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
|
||||
dependencies = [
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
dependencies = [
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashlink"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32069d97bb81e38fa67eab65e3393bf804bb85969f2bc06bf13f64aef5aba248"
|
||||
dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
@@ -2195,7 +2162,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown 0.17.1",
|
||||
"hashbrown",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
@@ -2376,7 +2343,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "latency-probe"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
@@ -2477,20 +2444,9 @@ dependencies = [
|
||||
"system-deps",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libsqlite3-sys"
|
||||
version = "0.38.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libvpl-sys"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"bindgen",
|
||||
"cmake",
|
||||
@@ -2519,7 +2475,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
||||
|
||||
[[package]]
|
||||
name = "loss-harness"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"punktfunk-core",
|
||||
]
|
||||
@@ -3011,7 +2967,7 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
|
||||
|
||||
[[package]]
|
||||
name = "pf-bitstream"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"cros-codecs",
|
||||
"tracing",
|
||||
@@ -3019,7 +2975,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-capture"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ashpd",
|
||||
@@ -3040,7 +2996,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-client-core"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ash",
|
||||
@@ -3075,7 +3031,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-clipboard"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ashpd",
|
||||
@@ -3093,7 +3049,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-console-ui"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ash",
|
||||
@@ -3115,7 +3071,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-dxvadec"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"cros-codecs",
|
||||
"pf-bitstream",
|
||||
@@ -3125,7 +3081,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-encode"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ash",
|
||||
@@ -3151,7 +3107,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-frame"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"libc",
|
||||
@@ -3163,7 +3119,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-gpu"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"pf-host-config",
|
||||
@@ -3177,11 +3133,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-host-config"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
|
||||
[[package]]
|
||||
name = "pf-inject"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ashpd",
|
||||
@@ -3210,14 +3166,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-paths"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pf-presenter"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ash",
|
||||
@@ -3232,7 +3188,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-update"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -3240,7 +3196,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-update-check"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"aws-lc-rs",
|
||||
@@ -3252,7 +3208,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-vaadec"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"cros-codecs",
|
||||
"pf-bitstream",
|
||||
@@ -3261,7 +3217,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-vdisplay"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ashpd",
|
||||
@@ -3294,7 +3250,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-vkdecode"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"ash",
|
||||
"cros-codecs",
|
||||
@@ -3305,7 +3261,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-win-display"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"pf-paths",
|
||||
"punktfunk-core",
|
||||
@@ -3316,7 +3272,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pf-zerocopy"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ash",
|
||||
@@ -3528,7 +3484,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-cli"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"pf-client-core",
|
||||
"punktfunk-core",
|
||||
@@ -3538,7 +3494,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-client-android"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"android_logger",
|
||||
"jni",
|
||||
@@ -3556,7 +3512,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-client-linux"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-channel",
|
||||
@@ -3573,7 +3529,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-client-session"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"pf-client-core",
|
||||
"pf-console-ui",
|
||||
@@ -3587,7 +3543,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-client-windows"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"mdns-sd",
|
||||
@@ -3605,7 +3561,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-core"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"cbindgen",
|
||||
@@ -3637,7 +3593,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-encode-worker"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"pf-encode",
|
||||
"tracing",
|
||||
@@ -3646,7 +3602,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-host"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"aes-gcm",
|
||||
@@ -3688,9 +3644,7 @@ dependencies = [
|
||||
"quinn",
|
||||
"rand 0.9.5",
|
||||
"rcgen",
|
||||
"roxmltree",
|
||||
"rsa",
|
||||
"rusqlite",
|
||||
"rustls",
|
||||
"rusty_enet",
|
||||
"semver",
|
||||
@@ -3718,7 +3672,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-probe"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"mdns-sd",
|
||||
@@ -3732,7 +3686,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "punktfunk-tray"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ksni",
|
||||
@@ -3755,7 +3709,7 @@ checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
||||
|
||||
[[package]]
|
||||
name = "pyrowave-sys"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
dependencies = [
|
||||
"bindgen",
|
||||
"cmake",
|
||||
@@ -4137,15 +4091,6 @@ dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "roxmltree"
|
||||
version = "0.21.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rpkg-config"
|
||||
version = "0.1.2"
|
||||
@@ -4173,31 +4118,6 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rsqlite-vfs"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c"
|
||||
dependencies = [
|
||||
"hashbrown 0.16.1",
|
||||
"thiserror 2.0.20",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rusqlite"
|
||||
version = "0.40.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3"
|
||||
dependencies = [
|
||||
"bitflags 2.13.1",
|
||||
"fallible-iterator",
|
||||
"fallible-streaming-iterator",
|
||||
"hashlink",
|
||||
"libsqlite3-sys",
|
||||
"smallvec",
|
||||
"sqlite-wasm-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "2.1.3"
|
||||
@@ -4769,18 +4689,6 @@ dependencies = [
|
||||
"der",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sqlite-wasm-rs"
|
||||
version = "0.5.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"js-sys",
|
||||
"rsqlite-vfs",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.11.1"
|
||||
|
||||
+1
-1
@@ -65,7 +65,7 @@ exclude = [
|
||||
ndk = { path = "clients/android/native/vendor/ndk" }
|
||||
|
||||
[workspace.package]
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
edition = "2024"
|
||||
rust-version = "1.85"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
+108
-12
@@ -10,7 +10,7 @@
|
||||
"name": "MIT OR Apache-2.0",
|
||||
"identifier": "MIT OR Apache-2.0"
|
||||
},
|
||||
"version": "0.27.0"
|
||||
"version": "0.28.0"
|
||||
},
|
||||
"paths": {
|
||||
"/api/v1/clients": {
|
||||
@@ -45,6 +45,36 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"tags": [
|
||||
"clients"
|
||||
],
|
||||
"summary": "Unpair every client",
|
||||
"description": "The collection form of [`unpair_client`]: empties the pairing store in ONE persisted write,\ncarrying the same revocation guarantees across the whole set. A LIVE GameStream session is\nended (its owning certificate is necessarily one of those just removed), and the ENet control\nport (UDP 47999) closes, because no pairing is left to hold it open.\n\nIdempotent, and so a 200 rather than the single unpair's 204/404 pair: \"unpair everything\" is\nsatisfied by an already-empty store, and the operator still wants to know whether that meant\nthree devices or none.",
|
||||
"operationId": "unpairAllClients",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Every client unpaired (possibly none)",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UnpairAllResult"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Missing or invalid bearer token",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ApiError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/clients/{fingerprint}": {
|
||||
@@ -997,7 +1027,7 @@
|
||||
"library"
|
||||
],
|
||||
"summary": "List the game library",
|
||||
"description": "Every installed-store title (Steam, read from the host's local files — no Steam API key)\nmerged with the user's custom entries, sorted by title. Artwork fields are URLs the client\nfetches directly (the public Steam CDN for Steam titles). `?provider=` narrows to the\nentries a given external provider owns; `?platform=` to one platform (case-insensitive —\ninstalled-store titles are `PC`, custom/provider entries carry whatever was authored).\n\n**The operator's own lane additionally sees the titles they have HIDDEN**, each carrying\n`hidden: true`; every other lane gets them filtered out upstream and cannot tell they exist. The\nconsole needs them to offer \"un-hide\", and it is the only surface that does.",
|
||||
"description": "Every title this host knows about, sorted by title: the entries each installed library plugin\nhas synced (Steam, Lutris, Heroic, Epic, GOG, Xbox, Playnite, ROM managers, …) plus the user's\nown custom entries. Artwork fields are URLs the client fetches directly, except local files on\nthe host, which are rewritten to this API's own art proxy. `?provider=` narrows to the entries a\ngiven external provider owns; `?platform=` to one platform (case-insensitive — whatever the\nsource authored, conventionally `PC` for desktop stores).\n\n**The operator's own lane additionally sees the titles they have HIDDEN**, each carrying\n`hidden: true`; every other lane gets them filtered out upstream and cannot tell they exist. The\nconsole needs them to offer \"un-hide\", and it is the only surface that does.",
|
||||
"operationId": "getLibrary",
|
||||
"parameters": [
|
||||
{
|
||||
@@ -1052,7 +1082,7 @@
|
||||
"library"
|
||||
],
|
||||
"summary": "Fetch one cover-art image for a library entry",
|
||||
"description": "Resolves `kind` (`portrait` | `hero` | `logo` | `header`) for the given library id and streams\nthe image bytes. Any id stored in the host's catalog (manual entries, provider-synced entries,\nand a library plugin's claimed-store entries) serves its local art file. A Steam title falls back\nto the in-host scanner's resolver: the host's own local Steam cache first (exact — it's what the\nuser's Steam client already shows for it), the public Steam CDN's flat URL convention second\n(newer titles' CDN assets can live at a per-asset-hash path the host can't predict, in which case\nthis 404s and the client falls through to its next art candidate).",
|
||||
"description": "Resolves `kind` (`portrait` | `hero` | `logo` | `header`) for the given library id and streams\nthe image bytes. Any id stored in the host's catalog (manual entries, provider-synced entries,\nand a library plugin's claimed-store entries) serves its local art file; anything else 404s and\nthe client falls through to its next art candidate.\n\nThe host fetches nothing here. Art a plugin published as an `http(s)` URL is fetched by the\nclient directly — this proxy exists for the *local* files a plugin finds on the host's own disk\n(a launcher's cover cache), which a client has no way to read.",
|
||||
"operationId": "getLibraryArt",
|
||||
"parameters": [
|
||||
{
|
||||
@@ -1380,7 +1410,7 @@
|
||||
"library"
|
||||
],
|
||||
"summary": "Replace a provider's library entries (declarative reconcile)",
|
||||
"description": "Atomically replaces the full entry set owned by `{provider}` (RFC §8): the payload is the\nprovider's desired list, keyed by its own stable `external_id` — the host diffs, keeps each\nsurviving title's host id stable across reconciles, drops orphans, and never touches manual\nentries or other providers'. An empty array removes everything the provider owns. Emits\n`library.changed` with the provider as `source`.\n\n`?store=` additionally **claims** that store for the provider: its entries then surface with\ndeterministic `<store>:<external_id>` ids and the store's own badge, instead of opaque\n`custom:<id>` ones — which is what lets a library plugin reproduce the entries an in-host scanner\nused to produce, right down to the GameStream app ids and client-side art caches. One provider\nper store; a second claimant gets 409. While a claim is held the matching built-in scanner is\nsuppressed, so the two never double-list. The claim is released by `DELETE`, not by an empty\nreconcile (a store can legitimately have zero installed titles).",
|
||||
"description": "Atomically replaces the full entry set owned by `{provider}` (RFC §8): the payload is the\nprovider's desired list, keyed by its own stable `external_id` — the host diffs, keeps each\nsurviving title's host id stable across reconciles, drops orphans, and never touches manual\nentries or other providers'. An empty array removes everything the provider owns. Emits\n`library.changed` with the provider as `source`.\n\n`?store=` additionally **claims** that store for the provider: its entries then surface with\ndeterministic `<store>:<external_id>` ids and the store's own badge, instead of opaque\n`custom:<id>` ones — which is what let a library plugin reproduce the entries the in-host scanner\nused to produce, right down to the GameStream app ids and client-side art caches, and is why\nremoving those scanners changed nothing downstream. One provider per store; a second claimant\ngets 409. The claim is released by `DELETE`, not by an empty reconcile (a store can legitimately\nhave zero installed titles).",
|
||||
"operationId": "reconcileProviderEntries",
|
||||
"parameters": [
|
||||
{
|
||||
@@ -1538,8 +1568,8 @@
|
||||
"tags": [
|
||||
"library"
|
||||
],
|
||||
"summary": "List the library scanners",
|
||||
"description": "The installed-store scanners this host supports — the list is platform-dependent (Steam\neverywhere; Lutris + Heroic on Linux; Epic, GOG, and Xbox/Game Pass on Windows), so the console\nrenders a toggle only for scanners that can do anything here. Scanners default to enabled;\ndisabling one hides its titles from every library surface from the next read. The user-curated\ncustom store is not a scanner and is always on.",
|
||||
"summary": "List the library sources",
|
||||
"description": "Every game source on this host with its enable state — one row per installed library plugin\n(Steam, Lutris, Heroic, Epic, GOG, Xbox, Playnite, ROM managers, …), so the list reflects what\nthe operator has actually installed rather than what this build happens to support. Sources\ndefault to enabled; disabling one hides its titles from every library surface from the next\nread. The user-curated custom store is not a source and is always on.\n\nOlder hosts (≤ v0.27.x) also listed the six scanners built into the host binary, with\n`origin: \"builtin\"`. Those are gone; every row now reports `origin: \"plugin\"`.",
|
||||
"operationId": "listLibraryScanners",
|
||||
"responses": {
|
||||
"200": {
|
||||
@@ -1573,8 +1603,8 @@
|
||||
"tags": [
|
||||
"library"
|
||||
],
|
||||
"summary": "Enable or disable a library scanner",
|
||||
"description": "Persists the toggle and applies it from the next library read (no restart). Disabling a scanner\nhides its titles everywhere — the console grid, native clients, and the GameStream app list —\nand re-enabling brings them straight back (nothing is deleted; the scan just runs again). Emits\n`library.changed` with the scanner id as `source` when the state changed.",
|
||||
"summary": "Enable or disable a library source",
|
||||
"description": "Persists the toggle and applies it from the next library read (no restart). Disabling a source\nhides its titles everywhere — the console grid, native clients, and the GameStream app list —\nand re-enabling brings them straight back. Nothing is deleted: the plugin may keep reconciling\nwhile its source is off, and those entries simply aren't surfaced. Emits `library.changed` with\nthe source id as `source` when the state changed.",
|
||||
"operationId": "setLibraryScanner",
|
||||
"parameters": [
|
||||
{
|
||||
@@ -1767,6 +1797,56 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"tags": [
|
||||
"native"
|
||||
],
|
||||
"summary": "Unpair every native client",
|
||||
"description": "The collection form of [`unpair_native_client`]: empties the punktfunk/1 trust store in ONE\npersisted write (not a loop of them — a failure partway would leave a half-emptied store), and\nends every live native session the removed clients own.\n\nIdempotent, hence a 200 rather than the single unpair's 204/404: an already-empty store\nsatisfies the request, and the count still tells the operator what it meant.",
|
||||
"operationId": "unpairAllNativeClients",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Every native client unpaired (possibly none)",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UnpairAllResult"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Missing or invalid bearer token",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ApiError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Could not persist the trust store",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ApiError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"503": {
|
||||
"description": "Native host not enabled",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ApiError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/native/clients/{fingerprint}": {
|
||||
@@ -5397,7 +5477,7 @@
|
||||
"string",
|
||||
"null"
|
||||
],
|
||||
"description": "The external provider owning this entry (custom-store entries synced by a provider\nplugin, RFC §8) — `None` for installed-store titles and manual custom entries. The\nconsole uses it for attribution; `GET /library?provider=` filters on it."
|
||||
"description": "The external provider owning this entry (entries synced by a provider plugin, RFC §8) —\n`None` only for the manual entries the operator typed in. The console uses it for\nattribution; `GET /library?provider=` filters on it."
|
||||
},
|
||||
"role": {
|
||||
"$ref": "#/components/schemas/GameRole",
|
||||
@@ -7143,7 +7223,7 @@
|
||||
},
|
||||
"origin": {
|
||||
"$ref": "#/components/schemas/SourceOrigin",
|
||||
"description": "Where the source comes from: `builtin` (a scanner in this host build) or `plugin`."
|
||||
"description": "Where the source comes from. Always `plugin` from this host build onward — see\n[`SourceOrigin`]."
|
||||
},
|
||||
"provider": {
|
||||
"type": [
|
||||
@@ -7163,7 +7243,7 @@
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"type": "boolean",
|
||||
"description": "Whether the scanner should run on this host."
|
||||
"description": "Whether this source should contribute titles on this host."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -7687,6 +7767,22 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"UnpairAllResult": {
|
||||
"type": "object",
|
||||
"description": "What a bulk unpair removed. Shared by the two collection DELETEs (`/clients` and\n`/native/clients`) so the console sees one schema across both pairing planes.\n\nA count rather than 204: \"unpair everything\" is idempotent, so an empty store is a success, and\nthe operator still wants to be told whether that meant three devices or none.",
|
||||
"required": [
|
||||
"unpaired"
|
||||
],
|
||||
"properties": {
|
||||
"unpaired": {
|
||||
"type": "integer",
|
||||
"format": "int32",
|
||||
"description": "Clients removed from the trust store — 0 when nothing was paired.",
|
||||
"example": 3,
|
||||
"minimum": 0
|
||||
}
|
||||
}
|
||||
},
|
||||
"UpdateJobInfo": {
|
||||
"type": "object",
|
||||
"description": "A running apply job (or a spawned installer that hasn't resolved yet).",
|
||||
@@ -7958,7 +8054,7 @@
|
||||
},
|
||||
{
|
||||
"name": "library",
|
||||
"description": "Game library: installed-store titles (Steam) plus user-curated custom entries"
|
||||
"description": "Game library: the titles each installed library plugin syncs, plus user-curated custom entries"
|
||||
},
|
||||
{
|
||||
"name": "stats",
|
||||
|
||||
@@ -51,6 +51,11 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
libxdamage-dev libxcomposite-dev libxrender-dev libxext-dev libxxf86vm-dev \
|
||||
libxtst-dev libx11-dev libxres-dev libxmu-dev libxcursor-dev libxi-dev \
|
||||
libxfixes-dev libxkbcommon-dev libxkbcommon-x11-dev libcap-dev libdrm-dev \
|
||||
# x11-xcb is needed by the VULKAN WSI LAYER (layer/meson.build), not by the compositor — so it
|
||||
# was not missed until v0.28.1 started building the layer beside the binary. Debian is the only
|
||||
# channel that needs it named: Arch's libx11 and Fedora's libX11-devel both carry x11-xcb.pc
|
||||
# themselves, while Debian splits it into its own -dev package.
|
||||
libx11-xcb-dev \
|
||||
libinput-dev libudev-dev libpipewire-0.3-dev libseat-dev libsdl2-dev \
|
||||
libluajit-5.1-dev libavif-dev libdecor-0-dev hwdata libglm-dev libbenchmark-dev \
|
||||
libvulkan-dev libxcb1-dev libxcb-composite0-dev libxcb-xfixes0-dev libxcb-res0-dev \
|
||||
@@ -66,3 +71,13 @@ RUN set -eux; \
|
||||
pkg-config --atleast-version=1.23.1 wayland-server \
|
||||
|| { echo "wayland-server $have < 1.23.1 — the vendored wlroots will not configure" >&2; exit 1; }; \
|
||||
echo "wayland-server $have — OK"
|
||||
|
||||
# The layer's own floor, asserted for the same reason: a missing x11-xcb does not fail the
|
||||
# COMPOSITOR build, it fails `layer/meson.build` — and the layer is the only route to an HDR10
|
||||
# swapchain for a nested game, so losing it silently ships a package that looks healthy and denies
|
||||
# every game HDR. This is exactly how v0.28.1's deb leg broke, one release after the layer was
|
||||
# added; assert it here so the next dep the layer grows fails at image build, not mid-release.
|
||||
RUN set -eux; \
|
||||
pkg-config --exists x11-xcb \
|
||||
|| { echo "x11-xcb absent — the Vulkan WSI layer will not configure (need libx11-xcb-dev)" >&2; exit 1; }; \
|
||||
echo "x11-xcb $(pkg-config --modversion x11-xcb) — OK"
|
||||
|
||||
@@ -32,20 +32,12 @@ import androidx.compose.animation.core.LinearEasing
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.MicOff
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
@@ -57,7 +49,6 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
@@ -130,12 +121,12 @@ fun StreamScreen(session: ActiveSession, onSessionEnded: (SessionEndReason) -> U
|
||||
// it, and survives the same recreate because the composition outlives the surface.
|
||||
var micMuted by remember(handle) { mutableStateOf(false) }
|
||||
// Whether a capture is actually RUNNING, not merely wanted — set from surfaceCreated on what
|
||||
// nativeMicActive reports. A device that refused every AAudio input rung gets no mute control
|
||||
// rather than one that lies about a mic being heard.
|
||||
// nativeMicActive reports. A device that refused every AAudio input rung gets no mute chord and
|
||||
// no chord line in the start banner, rather than an offer to mute a mic nobody is hearing.
|
||||
var micRunning by remember(handle) { mutableStateOf(false) }
|
||||
// Transient confirmation of a mic-chord toggle (null = nothing showing). Only the gamepad path
|
||||
// needs it: the touch button confirms itself by changing under the finger, but a chord has no
|
||||
// on-screen state of its own, and "did that register?" is exactly the doubt to answer.
|
||||
// Transient confirmation of a mic-chord toggle (null = nothing showing). With no standing mic
|
||||
// element on screen, this is mute's only feedback: a chord has no on-screen state of its own,
|
||||
// and "did that register?" is exactly the doubt to answer.
|
||||
var micHint by remember { mutableStateOf<String?>(null) }
|
||||
LaunchedEffect(micHint) {
|
||||
if (micHint != null) {
|
||||
@@ -413,9 +404,9 @@ fun StreamScreen(session: ActiveSession, onSessionEnded: (SessionEndReason) -> U
|
||||
// Show a "hold to quit" hint the moment the chord completes (the router debounces the actual
|
||||
// exit); it clears when the buttons release early or the hold elapses. Runs on the main thread.
|
||||
router.onExitArmed = { armed -> exitArming = armed }
|
||||
// Select + Y toggles the mic — the couch reach for the on-screen mute button, which a
|
||||
// gamepad/TV user has no pointer for. Ignored when no capture is running (there is nothing
|
||||
// to mute, and claiming otherwise would be the lie the control exists to avoid).
|
||||
// Select + Y toggles the mic — with no on-screen mute element, this chord is the whole of
|
||||
// the control. Ignored when no capture is running (there is nothing to mute, and a hint
|
||||
// saying "Microphone muted" over a mic nobody opened would be a lie).
|
||||
// A captured Sony pad whose motion this session cannot carry. Fires once per pad, at the
|
||||
// moment it is claimed, on the main thread.
|
||||
router.onMotionUnreachable = { motionHint = true }
|
||||
@@ -825,7 +816,7 @@ fun StreamScreen(session: ActiveSession, onSessionEnded: (SessionEndReason) -> U
|
||||
?: (runCatching { context.display }.getOrNull()?.refreshRate ?: 0f)
|
||||
.roundToInt(),
|
||||
)
|
||||
NativeBridge.nativeStartAudio(handle, lowLatencyMode)
|
||||
NativeBridge.nativeStartAudio(handle, lowLatencyMode, isTv)
|
||||
if (micWanted) {
|
||||
val sessionId =
|
||||
NativeBridge.nativeStartMic(handle, initialSettings.echoCancel)
|
||||
@@ -981,19 +972,12 @@ fun StreamScreen(session: ActiveSession, onSessionEnded: (SessionEndReason) -> U
|
||||
}
|
||||
},
|
||||
)
|
||||
// Mic mute, LAST in the stack — the one in-stream control, so unlike the purely visual
|
||||
// overlays above it has to sit on top of the gesture layer to receive its own taps (it
|
||||
// costs the stream that small corner of touch area, which is why it exists only while a
|
||||
// capture actually runs). On TV it is the indicator alone: the Select + Y chord is the
|
||||
// control there, and a focusable button would fight the game for the D-pad.
|
||||
if (micRunning && (micMuted || !isTv)) {
|
||||
MicMuteControl(
|
||||
muted = micMuted,
|
||||
onToggle = if (isTv) null else ({ setMicMuted(!micMuted) }),
|
||||
modifier = Modifier.align(Alignment.TopEnd).padding(12.dp),
|
||||
)
|
||||
}
|
||||
// Chord confirmation (gamepad/TV) — the counterpart to the button changing under a finger.
|
||||
// No standing mic element here: the in-stream mute control is deliberately absent until the
|
||||
// on-screen overlay UI lands and can carry it as one of its controls. Mute itself is intact
|
||||
// — the Select + Y chord toggles it, and the hint below is what confirms the toggle.
|
||||
// Chord confirmation (gamepad/TV) — mute has no standing indicator, so this is the whole
|
||||
// of its feedback: a toggle that showed nothing at all would be indistinguishable from one
|
||||
// that never registered.
|
||||
micHint?.let { MicChordHint(it, Modifier.align(Alignment.TopCenter).padding(top = 16.dp)) }
|
||||
// Bottom, not top: this can coincide with a mic-chord confirmation or the exit cue, and a
|
||||
// notice landing on top of one of those would cost the user both.
|
||||
@@ -1030,47 +1014,8 @@ private fun releaseMicEffects(effects: MutableList<AudioEffect>) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The in-stream mic control and its muted indicator, in one element: a dim mic glyph while the
|
||||
* uplink is live, a red **Muted** badge while it isn't — so the state that matters is the loud one,
|
||||
* readable at couch distance and impossible to mistake for the stream's own picture.
|
||||
*
|
||||
* [onToggle] `null` makes it a pure indicator (the TV/gamepad surface, where the Select + Y chord
|
||||
* is the control); non-null makes the badge itself the touch target. Rendering it at all is the
|
||||
* caller's decision — it means a capture is genuinely running.
|
||||
*/
|
||||
@Composable
|
||||
private fun MicMuteControl(muted: Boolean, onToggle: (() -> Unit)?, modifier: Modifier = Modifier) {
|
||||
val shape = RoundedCornerShape(10.dp)
|
||||
Row(
|
||||
modifier = modifier
|
||||
.clip(shape)
|
||||
.background(if (muted) Color(0xE0B3261E) else Color.Black.copy(alpha = 0.45f))
|
||||
.then(if (onToggle != null) Modifier.clickable(onClick = onToggle) else Modifier)
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
imageVector = if (muted) Icons.Filled.MicOff else Icons.Filled.Mic,
|
||||
// Spoken state first, then the action — a talkback user needs to know they are muted
|
||||
// before they need to know how to stop being muted.
|
||||
contentDescription = if (muted) {
|
||||
"Microphone muted. Activate to unmute."
|
||||
} else {
|
||||
"Microphone live. Activate to mute."
|
||||
},
|
||||
tint = Color.White,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
if (muted) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("Muted", color = Color.White, fontSize = 14.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Transient confirmation that the mic chord (Select + Y) registered. The badge above already says
|
||||
* *muted*, but nothing on screen says *un*muted — and "did that press do anything?" is the whole
|
||||
* Transient confirmation that the mic chord (Select + Y) registered. Nothing else on screen says
|
||||
* *muted* or *un*muted, so this pill carries both — "did that press do anything?" is the whole
|
||||
* doubt a chord with no button under the finger creates. Same pill vocabulary as the other
|
||||
* in-stream cues; the caller clears it after a beat.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package io.unom.punktfunk.screenshots
|
||||
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.compose.ui.test.junit4.createAndroidComposeRule
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import com.github.takahirom.roborazzi.captureRoboImage
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
/**
|
||||
* The same Roborazzi harness as ScreenshotTest, at Android TV geometry: 960×540dp in the
|
||||
* `television` UI mode at xhdpi (2.0×) = 1920×1080 px — the Play Store's 16:9 TV screenshot size,
|
||||
* captured 1:1 with no resampling. Only the screens that exist on a TV are shot here: the
|
||||
* gamepad-console shell (what LEANBACK_LAUNCHER opens into) and the in-stream view. Files are
|
||||
* prefixed `tv-` so the artifact separates the form factors.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(sdk = [36], qualifiers = "w960dp-h540dp-television-xhdpi")
|
||||
class TvScreenshotTest {
|
||||
@get:Rule
|
||||
val compose = createAndroidComposeRule<ComponentActivity>()
|
||||
|
||||
private val out = "build/outputs/roborazzi"
|
||||
|
||||
private fun shootRoot(name: String, content: @androidx.compose.runtime.Composable () -> Unit) {
|
||||
compose.mainClock.autoAdvance = false
|
||||
compose.setContent { ShotTheme(content) }
|
||||
compose.mainClock.advanceTimeBy(800)
|
||||
compose.onRoot().captureRoboImage("$out/tv-$name.png")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stream() = shootRoot("stream") { StreamScene(io.unom.punktfunk.StatsVerbosity.COMPACT) }
|
||||
|
||||
@Test
|
||||
fun streamDetailed() =
|
||||
shootRoot("stream-detailed") { StreamScene(io.unom.punktfunk.StatsVerbosity.DETAILED) }
|
||||
|
||||
@Test
|
||||
fun consoleHome() = shootRoot("console-home") { ConsoleHomeScene() }
|
||||
|
||||
@Test
|
||||
fun consoleSettings() = shootRoot("console-settings") { ConsoleSettingsScene() }
|
||||
|
||||
@Test
|
||||
fun consoleControllers() = shootRoot("console-controllers") { ConsoleControllersScene() }
|
||||
|
||||
@Test
|
||||
fun connectingConsole() = shootRoot("connecting-console") { ConnectConsoleScene() }
|
||||
}
|
||||
@@ -302,12 +302,17 @@ object NativeBridge {
|
||||
external fun nativeSetVideoStatsEnabled(handle: Long, enabled: Boolean)
|
||||
|
||||
/**
|
||||
* Start host→client audio: Opus decode → jitter ring → AAudio (LowLatency), all in Rust.
|
||||
* Start host→client audio: Opus decode → jitter ring → AAudio, all in Rust.
|
||||
* [lowLatencyMode] (the experimental toggle) additionally tags the stream usage=Game for the
|
||||
* HAL's game-audio routing. No-op if already started. Best-effort — a failure leaves video
|
||||
* streaming.
|
||||
*
|
||||
* [isTv] steers the AAudio open ladder: a TV box starts at Shared rather than betting the
|
||||
* audio plane on an Exclusive/MMAP path whose routing we cannot verify from inside the
|
||||
* process. Passed from `FEATURE_LEANBACK` (same source as [nativeStartVideo]) because the
|
||||
* native side's own `ro.build.characteristics` check is not answered by every TV device.
|
||||
*/
|
||||
external fun nativeStartAudio(handle: Long, lowLatencyMode: Boolean)
|
||||
external fun nativeStartAudio(handle: Long, lowLatencyMode: Boolean, isTv: Boolean)
|
||||
|
||||
/** Stop + join the audio thread and close AAudio, without closing the session. No-op on `0`. */
|
||||
external fun nativeStopAudio(handle: Long)
|
||||
|
||||
+692
-236
File diff suppressed because it is too large
Load Diff
@@ -357,10 +357,10 @@ pub extern "system" fn Java_io_unom_punktfunk_kit_NativeBridge_nativeSetVideoSta
|
||||
})
|
||||
}
|
||||
|
||||
/// `NativeBridge.nativeStartAudio(handle, lowLatencyMode)` — start the Opus→AAudio playback thread.
|
||||
/// `lowLatencyMode` (the experimental toggle) tags the stream usage=Game for the HAL's game-audio
|
||||
/// routing. No-op if already started or on a `0` handle. Best-effort: a failure leaves video
|
||||
/// streaming.
|
||||
/// `NativeBridge.nativeStartAudio(handle, lowLatencyMode, isTv)` — start the Opus→AAudio playback
|
||||
/// supervisor. `lowLatencyMode` (the experimental toggle) tags the stream usage=Game for the HAL's
|
||||
/// game-audio routing; `isTv` steers the AAudio open ladder (see `crate::audio::open_ladder`).
|
||||
/// No-op if already started or on a `0` handle. Best-effort: a failure leaves video streaming.
|
||||
#[cfg(target_os = "android")]
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "system" fn Java_io_unom_punktfunk_kit_NativeBridge_nativeStartAudio(
|
||||
@@ -368,6 +368,7 @@ pub extern "system" fn Java_io_unom_punktfunk_kit_NativeBridge_nativeStartAudio(
|
||||
_this: JObject,
|
||||
handle: jlong,
|
||||
low_latency_mode: jboolean,
|
||||
is_tv: jboolean,
|
||||
) {
|
||||
if handle == 0 {
|
||||
return;
|
||||
@@ -378,7 +379,7 @@ pub extern "system" fn Java_io_unom_punktfunk_kit_NativeBridge_nativeStartAudio(
|
||||
if guard.is_some() {
|
||||
return; // already playing
|
||||
}
|
||||
match crate::audio::AudioPlayback::start(h.client.clone(), low_latency_mode) {
|
||||
match crate::audio::AudioPlayback::start(h.client.clone(), low_latency_mode, is_tv) {
|
||||
Some(p) => *guard = Some(p),
|
||||
None => log::error!("nativeStartAudio: playback init failed (video unaffected)"),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"filename" : "about-icon@1x.png",
|
||||
"idiom" : "universal",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"filename" : "about-icon@2x.png",
|
||||
"idiom" : "universal",
|
||||
"scale" : "2x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 32 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 87 KiB |
@@ -83,14 +83,6 @@ struct ContentView: View {
|
||||
/// never covers the video.
|
||||
@State private var isFullscreen = false
|
||||
#endif
|
||||
#if os(macOS) || os(tvOS)
|
||||
/// Shows the start-of-stream shortcut banner (the Windows client's discoverability
|
||||
/// pattern): raised on every transition to `.streaming`, dropped by the banner's own
|
||||
/// 6-second task. Independent of the stats HUD so the keys are discoverable even with
|
||||
/// statistics off. On tvOS it carries the ONLY exits (hold Back / the pad chord) plus
|
||||
/// the remote-as-pointer controls, so it must be seen at least once per session.
|
||||
@State private var showShortcutHint = false
|
||||
#endif
|
||||
#if os(iOS)
|
||||
/// The stats-OFF tier's touch-exit disc window (see the overlay in `stream(captureEnabled:)`
|
||||
/// — the disc must LEAVE the hierarchy so nothing composites over the metal layer).
|
||||
@@ -347,9 +339,6 @@ struct ContentView: View {
|
||||
.onChange(of: model.phase) { _, phase in
|
||||
switch phase {
|
||||
case .streaming:
|
||||
#if os(macOS) || os(tvOS)
|
||||
showShortcutHint = true // the 6 s shortcut banner, per session start
|
||||
#endif
|
||||
#if os(iOS)
|
||||
showTouchExit = true // the off-tier exit disc's 8 s window, per session start
|
||||
#endif
|
||||
@@ -453,6 +442,10 @@ struct ContentView: View {
|
||||
LibraryView(store: store, target: shelf, onLaunch: { launchTitle(shelf, $0) })
|
||||
}
|
||||
.frame(minWidth: 940, minHeight: 620)
|
||||
// The stack draws the title, and it sits outside LibraryView's own ink — see the tvOS
|
||||
// cover. Gated, because this sheet is BOTH modes' library on macOS and the touch
|
||||
// grid's title belongs to the system background.
|
||||
.gamepadPaletteInk(gamepadUIActive)
|
||||
}
|
||||
#else
|
||||
// iOS: the cover is the TOUCH UI's presentation only. In gamepad mode the library is one
|
||||
@@ -822,6 +815,7 @@ struct ContentView: View {
|
||||
onPaired: handlePaired, waker: waker,
|
||||
connect: { connect($0, profile: $1) }, connectDiscovered: connectDiscovered,
|
||||
launchTitle: launchTitle,
|
||||
wakeOnly: { wakeOnly($0) },
|
||||
promptActive: consolePromptShowing)
|
||||
} else {
|
||||
HomeView(
|
||||
@@ -841,6 +835,7 @@ struct ContentView: View {
|
||||
onPaired: handlePaired, waker: waker,
|
||||
connect: { connect($0, profile: $1) }, connectDiscovered: connectDiscovered,
|
||||
launchTitle: launchTitle,
|
||||
wakeOnly: { wakeOnly($0) },
|
||||
promptActive: consolePromptShowing)
|
||||
// On tvOS pairing/library normally present from HomeView's navigationDestinations
|
||||
// — which aren't mounted while the gamepad launcher is up. Give the launcher its
|
||||
@@ -851,12 +846,29 @@ struct ContentView: View {
|
||||
.fullScreenCover(item: $pairingTarget) { host in
|
||||
PairSheet(host: host) { fingerprint in handlePaired(host, fingerprint: fingerprint) }
|
||||
.onExitCommand { pairingTarget = nil }
|
||||
// A tvOS cover draws NO background of its own, and this one is attached
|
||||
// outside the launcher's `gamepadPaletteInk` — so the pairing screen used
|
||||
// to render the system's dark chrome directly over the launcher showing
|
||||
// through it, which under a pale palette is white text on a bright field
|
||||
// (the PIN prompt was all but invisible). Give it the console's own field
|
||||
// and the palette's ink, like every other screen the launcher opens. Only
|
||||
// this branch: `HomeView`'s route to the same sheet is the TOUCH UI, which
|
||||
// sits on the system background and has no palette.
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background { GamepadFormBackground() }
|
||||
.gamepadPaletteInk()
|
||||
}
|
||||
.fullScreenCover(item: $libraryTarget) { shelf in
|
||||
NavigationStack {
|
||||
LibraryView(store: store, target: shelf, onLaunch: { launchTitle(shelf, $0) })
|
||||
}
|
||||
.onExitCommand { libraryTarget = nil }
|
||||
// On the STACK, not just inside LibraryView: the navigation title is drawn by
|
||||
// the stack, which wraps that view from outside its own `gamepadPaletteInk` —
|
||||
// so the shelf's name stayed white over a pale field while the content below
|
||||
// it had already gone dark. Unconditional here because this cover only exists
|
||||
// in the launcher's branch, where the console UI is by definition drawing.
|
||||
.gamepadPaletteInk()
|
||||
}
|
||||
#endif
|
||||
} else {
|
||||
@@ -973,9 +985,15 @@ struct ContentView: View {
|
||||
model?.disconnect() // the captured-state ⌃⌥⇧D combo
|
||||
},
|
||||
onFrame: { [meter = model.meter, latency = model.latency,
|
||||
split = model.latencySplit, queue = model.clientQueue,
|
||||
offset = conn.clockOffsetNs] au in
|
||||
split = model.latencySplit, queue = model.clientQueue] au in
|
||||
meter.note(byteCount: au.data.count)
|
||||
// Read the offset PER AU (an atomic load), never in the capture list: a
|
||||
// capture-list `offset =` froze the connect-time estimate for the whole
|
||||
// session, and on a host whose wall clock steps (VM + NTP) that frozen
|
||||
// value shifted hostnet/e2e by ~15 ms between sessions while the meter's
|
||||
// impossible-sample guard hid the damage (field 2026-08-13). See
|
||||
// `PunktfunkConnection.clockOffsetNs`.
|
||||
let offset = conn.clockOffsetNs
|
||||
latency.record(ptsNs: au.ptsNs, offsetNs: offset)
|
||||
// The same receipt, keyed by pts, awaiting its 0xCF host timing (the
|
||||
// host/network split — drained by the 1 s stats tick). receivedNs is
|
||||
@@ -1048,31 +1066,15 @@ struct ContentView: View {
|
||||
.transition(.opacity.combined(with: .scale(scale: 0.9)))
|
||||
}
|
||||
#endif
|
||||
#if os(macOS) || os(tvOS)
|
||||
// The start-of-stream shortcut banner (Windows-client parity): the
|
||||
// The start-of-stream shortcut banner used to sit here (macOS/tvOS): the
|
||||
// platform's reserved controls on a glass pill for the first 6 seconds of
|
||||
// every session — independent of the stats HUD, so the keys are
|
||||
// discoverable even with statistics off. The banner's own task drops it
|
||||
// (cancelled cleanly if the session view goes away first). On tvOS it
|
||||
// carries the ONLY exits — Menu/B is swallowed during a session (the
|
||||
// `.onExitCommand {}` in the tvOS session branch), so the hold gestures
|
||||
// must be told to the user.
|
||||
if captureEnabled && showShortcutHint {
|
||||
Text(shortcutHintText)
|
||||
.font(.geist(Self.shortcutHintFont, relativeTo: .caption))
|
||||
.foregroundStyle(.secondary)
|
||||
.padding(.horizontal, 14)
|
||||
.padding(.vertical, 8)
|
||||
.glassBackground(Capsule())
|
||||
.transition(.opacity)
|
||||
.task {
|
||||
try? await Task.sleep(for: .seconds(6))
|
||||
withAnimation(.easeOut(duration: 0.6)) {
|
||||
showShortcutHint = false
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
// every session. It is now a page you can OPEN — About ▸ Shortcuts, on
|
||||
// both the touch and the controller surface (ShortcutsCatalog) — because
|
||||
// a message that shows once, over the stream you have just connected to,
|
||||
// is unavailable at the moment the question is actually asked. It also
|
||||
// put a composited overlay above the stream for those 6 seconds, which on
|
||||
// this path costs a refresh of display latency (see the iOS exit disc's
|
||||
// note below); the reference page costs nothing during a session.
|
||||
}
|
||||
.padding(.bottom, 24)
|
||||
.animation(.easeOut(duration: 0.2), value: model.micMuted)
|
||||
@@ -1139,23 +1141,10 @@ struct ContentView: View {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS)
|
||||
/// The reserved combos, told once per session. The mute segment appears only when the session
|
||||
/// actually sends a microphone — teaching a shortcut for a mic that isn't on would be a lie.
|
||||
private var shortcutHintText: String {
|
||||
let base =
|
||||
"Click the stream to capture · ⌃⌥⇧Q releases the mouse · ⌃⌥⇧D disconnects · ⌃⌥⇧S stats"
|
||||
return model.micAvailable ? base + " · ⌃⌥⇧A mutes the mic" : base
|
||||
}
|
||||
private static let shortcutHintFont: CGFloat = 12
|
||||
#elseif os(tvOS)
|
||||
private var shortcutHintText: String {
|
||||
"Hold the remote's Back button — or L1+R1+Start+Select on a controller — to disconnect"
|
||||
+ " · Touch surface moves the pointer · press clicks · Play/Pause right-clicks"
|
||||
+ " · Hold Play/Pause, or Select+X on a controller, for statistics"
|
||||
}
|
||||
private static let shortcutHintFont: CGFloat = 22 // read from the couch
|
||||
#endif
|
||||
// The two `shortcutHintText` strings that used to live here — one per platform, told once per
|
||||
// session by the banner above — are now `ShortcutsCatalog.groups`, which both About pages
|
||||
// render. The mic line is still conditional there for the same reason it was here: teaching a
|
||||
// shortcut for a microphone that isn't on would be a lie.
|
||||
|
||||
// MARK: - Connect
|
||||
|
||||
|
||||
@@ -12,7 +12,10 @@ import SwiftUI
|
||||
#if os(iOS) || os(macOS) || os(tvOS)
|
||||
|
||||
struct GamepadAddHostView: View {
|
||||
@Environment(\.gamepadInk) private var ink
|
||||
/// Resolved from the stored palette, NOT from `\.gamepadInk` — this screen publishes that
|
||||
/// value itself and so sits above its own copy (see `GamepadInk.stored`).
|
||||
@AppStorage(DefaultsKey.uiPalette) private var paletteID = "violet"
|
||||
private var ink: GamepadInk { .stored(paletteID) }
|
||||
@Environment(\.gamepadMetrics) private var metrics
|
||||
@Environment(\.displayBottomInset) private var displayBottomInset
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@@ -25,6 +28,18 @@ struct GamepadAddHostView: View {
|
||||
/// Whether this screen owns the controller — false while the shell is mid-transition or the
|
||||
/// connect takeover is up (see GamepadSettingsView's twin).
|
||||
var controllerActive = true
|
||||
/// Non-nil ⇒ this screen is EDITING that saved host rather than registering a new one: the
|
||||
/// fields start on its values and `onAdd` receives it back with only name/address/port
|
||||
/// changed, so the fingerprint, pins, binding and MACs it carries survive the edit. A
|
||||
/// re-typed address is the whole point of the screen (a host that moved), so nothing here
|
||||
/// re-derives identity from it — that is the trust store's job, not this form's.
|
||||
///
|
||||
/// Declared after the closures for the same trailing-closure reason as `close`, and it is a
|
||||
/// plain value besides, so it can never capture one.
|
||||
var editingHost: StoredHost?
|
||||
/// One-shot seed guard: `@State` cannot be initialised from a property without a custom init,
|
||||
/// and a custom init would break every existing trailing-closure call site.
|
||||
@State private var seeded = false
|
||||
|
||||
#if os(iOS)
|
||||
/// `.compact` in a landscape phone window — tighter chrome so the keyboard tray still fits.
|
||||
@@ -57,12 +72,15 @@ struct GamepadAddHostView: View {
|
||||
.safeAreaInset(edge: .top, spacing: 0) {
|
||||
VStack(alignment: .leading, spacing: gamepadHeaderSpacing(compact: compact)) {
|
||||
// Leading, like every gamepad heading — and no close chrome (B is the exit).
|
||||
Text("Add Host")
|
||||
Text(editingHost == nil ? "Add Host" : "Edit Host")
|
||||
.font(.geist(gamepadTitleSize(compact: compact), .bold, relativeTo: .title))
|
||||
.foregroundStyle(ink.fg)
|
||||
if !compact {
|
||||
Text("Hosts on this network appear automatically — add one by address "
|
||||
+ "for everything else.")
|
||||
Text(editingHost == nil
|
||||
? "Hosts on this network appear automatically — add one by address "
|
||||
+ "for everything else."
|
||||
: "Rename this host, or point it at a new address — its pairing and "
|
||||
+ "pinned cards are kept.")
|
||||
.font(.geist(metrics.detailFont, relativeTo: .caption))
|
||||
.foregroundStyle(ink.fg(0.55))
|
||||
.multilineTextAlignment(.leading)
|
||||
@@ -98,6 +116,17 @@ struct GamepadAddHostView: View {
|
||||
.onChange(of: port) { _, value in
|
||||
if value.count > 5 { port = String(value.prefix(5)) }
|
||||
}
|
||||
// Seed the fields from the host being edited, exactly once: re-seeding on a later appear
|
||||
// (the shell re-mounts a layer when the app returns from the background) would silently
|
||||
// throw away whatever had been typed.
|
||||
.onAppear {
|
||||
guard !seeded else { return }
|
||||
seeded = true
|
||||
guard let host = editingHost else { return }
|
||||
name = host.name
|
||||
address = host.address
|
||||
port = String(host.port)
|
||||
}
|
||||
#if !os(tvOS)
|
||||
// The visible close ✕ is gone (a gamepad UI exits with B) — this keeps a hardware
|
||||
// keyboard's Esc and the macOS sheet's cancel working without chrome.
|
||||
@@ -202,7 +231,9 @@ struct GamepadAddHostView: View {
|
||||
Row(id: "name", label: "Name", value: name, placeholder: "Optional — e.g. Living Room"),
|
||||
Row(id: "address", label: "Address", value: address, placeholder: "IP or hostname"),
|
||||
Row(id: "port", label: "Port", value: port, placeholder: "9777"),
|
||||
Row(id: "add", label: "Add Host", isAction: true),
|
||||
Row(
|
||||
id: "add", label: editingHost == nil ? "Add Host" : "Save Changes",
|
||||
isAction: true),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -261,10 +292,21 @@ struct GamepadAddHostView: View {
|
||||
openKeyboard("address")
|
||||
return
|
||||
}
|
||||
onAdd(StoredHost(
|
||||
name: name.trimmingCharacters(in: .whitespaces),
|
||||
address: address.trimmingCharacters(in: .whitespaces),
|
||||
port: UInt16(port) ?? 9777))
|
||||
let typedName = name.trimmingCharacters(in: .whitespaces)
|
||||
let typedAddress = address.trimmingCharacters(in: .whitespaces)
|
||||
let typedPort = UInt16(port) ?? 9777
|
||||
if var host = editingHost {
|
||||
// Mutate a COPY of the stored record rather than building a fresh one: everything
|
||||
// this form does not show — the pinned fingerprint, WoL MACs, pinned profile
|
||||
// cards, the default binding, `addedAt` — has to survive a rename.
|
||||
host.name = typedName
|
||||
host.address = typedAddress
|
||||
host.port = typedPort
|
||||
onAdd(host)
|
||||
} else {
|
||||
onAdd(StoredHost(
|
||||
name: typedName, address: typedAddress, port: typedPort))
|
||||
}
|
||||
performClose()
|
||||
default:
|
||||
openKeyboard(id)
|
||||
|
||||
@@ -48,6 +48,13 @@ struct GamepadCarousel<Item: Identifiable, Card: View>: View where Item.ID: Hash
|
||||
var onTertiary: (() -> Void)?
|
||||
/// B → back/dismiss; nil disables it (e.g. the root launcher has nowhere to go back to).
|
||||
var onBack: (() -> Void)?
|
||||
/// UP → the focused item's own menu (the launcher's host options). Wiring it takes the whole
|
||||
/// VERTICAL axis away from scrolling: up opens the menu and down goes inert, rather than up
|
||||
/// meaning "menu" while down still stepped the strip. A horizontal carousel has no vertical
|
||||
/// travel to spend, and the desktop and Android consoles both read the axis this way — one
|
||||
/// meaning per direction is what makes the gesture learnable across the three of them.
|
||||
/// nil leaves up/down as a second way to step (what every carousel without a menu still does).
|
||||
var onUp: (() -> Void)?
|
||||
/// L1/R1 → jump this many items at once (clamped to the ends); 0 disables the shoulders.
|
||||
var shoulderJump: Int = 0
|
||||
/// Whether this carousel currently owns controller input. A presenting screen (e.g. the host
|
||||
@@ -301,6 +308,17 @@ struct GamepadCarousel<Item: Identifiable, Card: View>: View where Item.ID: Hash
|
||||
// The poll carries only the buttons focus has no concept of: Y/X, the screen actions.
|
||||
input.onSecondary = onSecondary
|
||||
input.onTertiary = onTertiary
|
||||
// UP is the one direction the poll may also read here, and ONLY to open the menu — it
|
||||
// never calls `step`, so it cannot double-move against the focus engine. Routing it
|
||||
// through `.onMoveCommand` instead was the obvious alternative and the wrong one: that
|
||||
// stream is 4-way and its interception is input-source-dependent on real hardware (see
|
||||
// GamepadMenuList's tvOS note), so claiming up there risks left/right focus with it.
|
||||
// Nothing sits above the strip for the engine to move to, so this direction is free.
|
||||
if let onUp {
|
||||
input.onMove = { direction in
|
||||
if direction == .up { onUp() }
|
||||
}
|
||||
}
|
||||
#else
|
||||
input.onMove = { move($0) }
|
||||
input.onConfirm = { activate() }
|
||||
@@ -312,6 +330,14 @@ struct GamepadCarousel<Item: Identifiable, Card: View>: View where Item.ID: Hash
|
||||
}
|
||||
|
||||
private func move(_ direction: GamepadMenuInput.Direction) {
|
||||
// With a menu wired, vertical is the menu's axis, not a second scroll axis — see `onUp`.
|
||||
if let onUp {
|
||||
switch direction {
|
||||
case .up: return onUp()
|
||||
case .down: return
|
||||
case .left, .right: break
|
||||
}
|
||||
}
|
||||
let forward = direction == .right || direction == .down
|
||||
step(by: forward ? 1 : -1, clampAtEnds: false)
|
||||
}
|
||||
|
||||
@@ -430,7 +430,12 @@ private struct HintCellStyle: ButtonStyle {
|
||||
/// can't inflate the caller's layout past the safe area (see the layout note in GamepadHomeView's
|
||||
/// header). Honors Reduce Motion by freezing the field at a fixed phase.
|
||||
struct GamepadScreenBackground: View {
|
||||
@Environment(\.gamepadInk) private var ink
|
||||
/// Resolved from `paletteID` below rather than `\.gamepadInk`: this is mounted as a screen's
|
||||
/// `.background { }`, which the screen attaches BEFORE its own `gamepadPaletteInk()`, so the
|
||||
/// environment here is the screen's parent's — the dark default under a cover or a sheet. It
|
||||
/// only feeds a pale palette's scrim, so the symptom was subtle: the field bleached toward
|
||||
/// white instead of settling onto its own ink. (see `GamepadInk.stored`)
|
||||
private var ink: GamepadInk { .stored(paletteID) }
|
||||
/// How far toward the form screens' quiet the field sits: 0 = the launcher's full aurora,
|
||||
/// 1 = calm, fractional mid-chase. Continuous (not a Bool) so the in-place shell can CHASE
|
||||
/// it during a push/pop — the console does the same with its `bg_mix` — and every
|
||||
|
||||
@@ -64,7 +64,10 @@ private struct HomeTile: Identifiable {
|
||||
}
|
||||
|
||||
struct GamepadHomeView: View {
|
||||
@Environment(\.gamepadInk) private var ink
|
||||
/// Resolved from the stored palette, NOT from `\.gamepadInk` — this screen publishes that
|
||||
/// value itself and so sits above its own copy (see `GamepadInk.stored`).
|
||||
@AppStorage(DefaultsKey.uiPalette) private var paletteID = "violet"
|
||||
private var ink: GamepadInk { .stored(paletteID) }
|
||||
/// Published by ContentView at the app ROOT, so this reads its own window's tier — this screen
|
||||
/// applies `gamepadPaletteInk` itself and so sits above its own copy of the environment.
|
||||
@Environment(\.gamepadMetrics) private var metrics
|
||||
@@ -91,6 +94,10 @@ struct GamepadHomeView: View {
|
||||
/// Launch a library title on a host — the in-place library layer's activate path (iOS; the
|
||||
/// cover/sheet presentations wire ContentView's `launchTitle` into LibraryView themselves).
|
||||
let launchTitle: (LibraryTarget, String) -> Void
|
||||
/// Wake a host WITHOUT connecting (ContentView's `wakeOnly`) — the host menu's Wake row. The
|
||||
/// tile's own A already wakes-and-connects; this is the other half, for bringing a machine up
|
||||
/// to look at it rather than to stream from it right now.
|
||||
let wakeOnly: (StoredHost) -> Void
|
||||
/// A console prompt (GamepadPromptView) is up over the home — it polls the same controller, so
|
||||
/// this screen must stand down for as long as it is. Same handoff contract as the connect
|
||||
/// takeover and the shell's own layers; without it the carousel keeps scrolling underneath the
|
||||
@@ -119,6 +126,11 @@ struct GamepadHomeView: View {
|
||||
@State private var selection: GamepadHomeTarget?
|
||||
@State private var showSettings = false
|
||||
@State private var showAddHost = false
|
||||
/// The card whose options menu is up (UP on a saved tile) — see GamepadHostOptionsView.
|
||||
@State private var hostOptionsTarget: HostOptionsTarget?
|
||||
/// The host being edited. Set from the options menu, which closes itself as it opens this so
|
||||
/// the two are never stacked — depth stays ≤ 1, which is what `GamepadScreen` assumes.
|
||||
@State private var editTarget: StoredHost?
|
||||
/// The console's input drop: true for the transition's 0.26 s, during which NO layer polls
|
||||
/// the controller — a double-tapped A can't push two screens, and the held button that
|
||||
/// caused the change is long released before the next poller starts (whose own
|
||||
@@ -201,19 +213,37 @@ struct GamepadHomeView: View {
|
||||
// shell's layers above ARE the presentation.
|
||||
#if os(macOS)
|
||||
.sheet(isPresented: $showSettings) {
|
||||
GamepadSettingsView(store: store)
|
||||
GamepadSettingsView(store: store, micAvailable: model.micAvailable)
|
||||
.frame(width: 720, height: 640)
|
||||
}
|
||||
.sheet(isPresented: $showAddHost) {
|
||||
GamepadAddHostView { store.add($0) }
|
||||
.frame(width: 660, height: 620)
|
||||
}
|
||||
// Shorter than the forms above: a menu is five rows, and a sheet sized for a settings
|
||||
// screen would be mostly empty field under them.
|
||||
.sheet(item: $hostOptionsTarget) { target in
|
||||
hostOptionsView(target, active: true)
|
||||
.frame(width: 620, height: 460)
|
||||
}
|
||||
.sheet(item: $editTarget) { host in
|
||||
editHostView(host, active: true)
|
||||
.frame(width: 660, height: 620)
|
||||
}
|
||||
.frame(minWidth: 640, minHeight: 420)
|
||||
#elseif os(tvOS)
|
||||
.fullScreenCover(isPresented: $showSettings) { GamepadSettingsView(store: store) }
|
||||
.fullScreenCover(isPresented: $showSettings) {
|
||||
GamepadSettingsView(store: store, micAvailable: model.micAvailable)
|
||||
}
|
||||
.fullScreenCover(isPresented: $showAddHost) {
|
||||
GamepadAddHostView { store.add($0) }
|
||||
}
|
||||
.fullScreenCover(item: $hostOptionsTarget) { target in
|
||||
hostOptionsView(target, active: true)
|
||||
}
|
||||
.fullScreenCover(item: $editTarget) { host in
|
||||
editHostView(host, active: true)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -261,6 +291,10 @@ struct GamepadHomeView: View {
|
||||
// can be raised from ON TOP of the library (launching a title on an unpaired host), where
|
||||
// it has to win. Backing out of it reveals whatever it interrupted.
|
||||
if let host = pairingTarget { return .pair(host) }
|
||||
// Editing leads the menu that raised it: the menu clears itself on the way, so the two are
|
||||
// never both set, and if they somehow were, the screen the user asked for last should win.
|
||||
if let host = editTarget { return .editHost(host) }
|
||||
if let target = hostOptionsTarget { return .hostOptions(target) }
|
||||
if showSettings { return .settings }
|
||||
if showAddHost { return .addHost }
|
||||
if let shelf = libraryTarget { return .library(shelf) }
|
||||
@@ -277,12 +311,17 @@ struct GamepadHomeView: View {
|
||||
GamepadSettingsView(
|
||||
store: store,
|
||||
close: { if !transitioning { showSettings = false } },
|
||||
controllerActive: active)
|
||||
controllerActive: active,
|
||||
micAvailable: model.micAvailable)
|
||||
case .addHost:
|
||||
GamepadAddHostView(
|
||||
onAdd: { store.add($0) },
|
||||
close: { if !transitioning { showAddHost = false } },
|
||||
controllerActive: active)
|
||||
case .hostOptions(let target):
|
||||
hostOptionsView(target, active: active)
|
||||
case .editHost(let host):
|
||||
editHostView(host, active: active)
|
||||
case .pair(let host):
|
||||
GamepadPairView(
|
||||
host: host,
|
||||
@@ -414,6 +453,7 @@ struct GamepadHomeView: View {
|
||||
onActivate: { $0.activate() },
|
||||
onSecondary: { openLibraryForSelected() },
|
||||
onTertiary: { showSettings = true },
|
||||
onUp: { openOptionsForSelected() },
|
||||
isActive: homeOwnsController
|
||||
) { tile, entrance in
|
||||
hostCard(tile, size: CGSize(width: cardWidth, height: cardHeight), entrance: entrance)
|
||||
@@ -469,6 +509,14 @@ struct GamepadHomeView: View {
|
||||
glyph: buttonGlyph(\.buttonY, fallback: "y.circle"), text: "Library",
|
||||
action: { openLibraryForSelected() }))
|
||||
}
|
||||
// Only a saved card has a menu, so the cell appears only where the press does something —
|
||||
// the same honesty rule the Library cell above follows. A direction, not a button, so it
|
||||
// is a plain arrow rather than a `buttonGlyph` (see the settings screen's "Adjust").
|
||||
if case .saved = selected?.id {
|
||||
hints.append(.init(
|
||||
glyph: "arrow.up", text: "Options",
|
||||
action: { openOptionsForSelected() }))
|
||||
}
|
||||
hints.append(.init(
|
||||
glyph: buttonGlyph(\.buttonX, fallback: "x.circle"), text: "Settings",
|
||||
action: { showSettings = true }))
|
||||
@@ -543,6 +591,60 @@ struct GamepadHomeView: View {
|
||||
/// `HostCardView`-only action never offered on `DiscoveredCardView`. A pinned card opens its
|
||||
/// own shelf: the selection already names which card Y was pressed on, and that card's profile
|
||||
/// is what its launches run with.
|
||||
/// The host menu, built once for all three presentations (the iOS shell layer, the macOS
|
||||
/// sheet, the tvOS cover) so the actions can't drift between them.
|
||||
///
|
||||
/// Edit REPLACES this menu rather than stacking on it — `hostOptionsTarget` is cleared as
|
||||
/// `editTarget` is set — which is the desktop console's `Nav::Replace` and what keeps the
|
||||
/// shell's "depth ≤ 1 by construction" claim true.
|
||||
@ViewBuilder
|
||||
private func hostOptionsView(_ target: HostOptionsTarget, active: Bool) -> some View {
|
||||
let host = target.host
|
||||
GamepadHostOptionsView(
|
||||
host: host,
|
||||
pinnedProfile: target.profile,
|
||||
isOnline: discovery.advertises(host) || store.probedOnline.contains(host.id),
|
||||
canWake: autoWakeEnabled && PunktfunkConnection.wakeOnLANAvailable
|
||||
&& !host.wakeMacs.isEmpty,
|
||||
onEdit: {
|
||||
guard !transitioning else { return }
|
||||
hostOptionsTarget = nil
|
||||
editTarget = host
|
||||
},
|
||||
onWake: { wakeOnly(host) },
|
||||
onForgetPairing: { store.forgetIdentity(host) },
|
||||
onRemove: { store.remove(host) },
|
||||
onUnpin: {
|
||||
guard let profile = target.profile else { return }
|
||||
store.setPinned(host.id, profileID: profile.id, pinned: false)
|
||||
},
|
||||
close: { if !transitioning { hostOptionsTarget = nil } },
|
||||
controllerActive: active)
|
||||
}
|
||||
|
||||
/// The add-host form in edit mode. `store.update` writes the record back by id, so the
|
||||
/// fingerprint, MACs, pins and binding the form never shows are preserved.
|
||||
@ViewBuilder
|
||||
private func editHostView(_ host: StoredHost, active: Bool) -> some View {
|
||||
GamepadAddHostView(
|
||||
onAdd: { store.update($0) },
|
||||
close: { if !transitioning { editTarget = nil } },
|
||||
controllerActive: active,
|
||||
editingHost: host)
|
||||
}
|
||||
|
||||
/// UP on a saved tile opens that card's menu. Only SAVED hosts have one: a discovered-but-
|
||||
/// unsaved host is not ours to rename or remove, and the two action tiles have nothing to
|
||||
/// offer — the same `HostOptionsScreen::available` gate the desktop console applies.
|
||||
private func openOptionsForSelected() {
|
||||
guard case .saved(let id, let profileID) = selection,
|
||||
let host = store.hosts.first(where: { $0.id == id })
|
||||
else { return }
|
||||
hostOptionsTarget = HostOptionsTarget(
|
||||
host: host,
|
||||
profile: profileID.flatMap { pid in profiles.profiles.first { $0.id == pid } })
|
||||
}
|
||||
|
||||
private func openLibraryForSelected() {
|
||||
guard libraryEnabled, case .saved(let id, let profileID) = selection,
|
||||
let host = store.hosts.first(where: { $0.id == id })
|
||||
@@ -657,6 +759,12 @@ private struct GamepadHostTile: View {
|
||||
|
||||
private var monogramBadge: some View {
|
||||
let shape = RoundedRectangle(cornerRadius: Self.badgeCorner, style: .continuous)
|
||||
// What the glyph is drawn ON: a filled badge IS the accent, so its mark takes `onAccent`
|
||||
// — the colour picked by the accent's own luminance — exactly as the settings screen's
|
||||
// selected tab pill does. It used to take `fg`, which is chosen against the FIELD, and the
|
||||
// two disagree at both ends of the set: a pale palette put near-black on a deep accent, and
|
||||
// Graphite (accent luma ≈ 0.80) put white on a light grey.
|
||||
let glyph = tile.filled ? ink.onAccent : ink.accent
|
||||
return ZStack {
|
||||
shape.fill(tile.filled
|
||||
? AnyShapeStyle(LinearGradient(
|
||||
@@ -664,7 +772,7 @@ private struct GamepadHostTile: View {
|
||||
startPoint: .top, endPoint: .bottom))
|
||||
: AnyShapeStyle(ink.accent(0.16)))
|
||||
if tile.isConnecting {
|
||||
ProgressView().tint(ink.fg)
|
||||
ProgressView().tint(glyph)
|
||||
} else if let icon = tile.icon {
|
||||
Image(systemName: icon)
|
||||
.font(.system(size: Self.iconFont, weight: .semibold))
|
||||
@@ -676,12 +784,12 @@ private struct GamepadHostTile: View {
|
||||
.resizable()
|
||||
.scaledToFit()
|
||||
.frame(width: Self.monogramFont, height: Self.monogramFont)
|
||||
.foregroundStyle(tile.filled ? ink.fg : ink.accent)
|
||||
.foregroundStyle(glyph)
|
||||
.accessibilityLabel(tile.osChain ?? "")
|
||||
} else {
|
||||
Text(monogram(tile.title))
|
||||
.font(.geistFixed(Self.monogramFont, .bold))
|
||||
.foregroundStyle(tile.filled ? ink.fg : ink.accent)
|
||||
.foregroundStyle(glyph)
|
||||
}
|
||||
}
|
||||
.frame(width: Self.badgeSide, height: Self.badgeSide)
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
// A saved host's own actions — Wake, Copy link, Edit…, Forget pairing, Remove — reached with UP on
|
||||
// its carousel tile. The console's answer to the overflow menu the touch grid hangs off every host
|
||||
// card (HostCardView's context menu), and the Apple port of `pf-console-ui`'s HostOptionsScreen.
|
||||
//
|
||||
// Until now the gamepad UI could add a host and connect to one, and that was all: a renamed machine
|
||||
// or a host typed in with a fat-fingered address stayed wrong forever, because the only surface
|
||||
// that could edit or remove one was the touch UI. The tile is where a host is, so the tile is where
|
||||
// its actions belong.
|
||||
//
|
||||
// UP is the gesture because the carousel is horizontal — left/right are spoken for and up is free —
|
||||
// and because the desktop console and the Android console already do exactly this, so the three are
|
||||
// learned once. A pinned profile card offers only Unpin: it is a shortcut, not a second host, and
|
||||
// offering to remove the host from it would blur precisely the distinction a pin exists to draw.
|
||||
//
|
||||
// Vocabulary note: this screen says "Forget pairing" and "Remove host" where the desktop console
|
||||
// says one word, "Forget". The console has only the one action; Apple has both (HostCardView calls
|
||||
// them `onForget` = drop the pinned fingerprint and `onRemove` = delete the record), and two
|
||||
// different actions cannot share a name on the surface that offers both. The touch card's words
|
||||
// win over the other consoles' here — a user meets both Apple surfaces, and only one of them is
|
||||
// cross-platform.
|
||||
|
||||
import PunktfunkKit
|
||||
import SwiftUI
|
||||
#if os(iOS) || os(macOS) || os(tvOS)
|
||||
|
||||
/// Which card the menu was opened on. Carries the host BY VALUE for the same reason the screen
|
||||
/// does — the carousel is rebuilt on every discovery pass, and a target that re-resolved itself
|
||||
/// could hand "Remove" a different host than the one the user was looking at.
|
||||
struct HostOptionsTarget: Identifiable {
|
||||
let host: StoredHost
|
||||
/// Non-nil ⇒ a pinned profile card rather than the host's own tile.
|
||||
var profile: StreamProfile?
|
||||
|
||||
/// Keyed on the CARD, not the host: a host and each of its pinned cards open different menus,
|
||||
/// and sharing an id would let one stand in for another mid-transition (the same rule
|
||||
/// `GamepadScreen.library` follows).
|
||||
var id: String { "\(host.id.uuidString)-\(profile?.id ?? "")" }
|
||||
}
|
||||
|
||||
struct GamepadHostOptionsView: View {
|
||||
/// Resolved from the stored palette, NOT from `\.gamepadInk` — this screen publishes that
|
||||
/// value itself and so sits above its own copy (see `GamepadInk.stored`).
|
||||
@AppStorage(DefaultsKey.uiPalette) private var paletteID = "violet"
|
||||
private var ink: GamepadInk { .stored(paletteID) }
|
||||
@Environment(\.gamepadMetrics) private var metrics
|
||||
@Environment(\.displayBottomInset) private var displayBottomInset
|
||||
@Environment(\.gamepadHostedInShell) private var hostedInShell
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
|
||||
/// The host this menu was opened on, BY VALUE. Discovery rewrites the carousel on every
|
||||
/// service pass; holding an index or a live lookup would let the menu retarget itself onto
|
||||
/// whichever host slid into that slot, and "Remove" must never be able to do that.
|
||||
let host: StoredHost
|
||||
/// Non-nil ⇒ opened on a pinned profile card rather than the host's own tile.
|
||||
var pinnedProfile: StreamProfile?
|
||||
/// Whether the host is reachable right now — decides whether Wake is worth offering.
|
||||
var isOnline = false
|
||||
/// Whether waking is possible at all (the setting is on, WoL is available, a MAC is known).
|
||||
var canWake = false
|
||||
let onEdit: () -> Void
|
||||
let onWake: () -> Void
|
||||
/// Drop the pinned fingerprint — the host stays saved, and the next connect re-pairs.
|
||||
let onForgetPairing: () -> Void
|
||||
/// Delete the saved record outright.
|
||||
let onRemove: () -> Void
|
||||
let onUnpin: () -> Void
|
||||
var close: (() -> Void)?
|
||||
var controllerActive = true
|
||||
|
||||
#if os(iOS)
|
||||
@Environment(\.verticalSizeClass) private var vSizeClass
|
||||
|
||||
private var compact: Bool { vSizeClass == .compact }
|
||||
#else
|
||||
private let compact = false
|
||||
#endif
|
||||
|
||||
/// Removing is the one action here with no undo, so its row ARMS on the first press and only
|
||||
/// fires on the second. The touch grid removes behind a system confirmation dialog; a console
|
||||
/// is driven by a thumbstick from across a room, which is a good reason to be at least as
|
||||
/// strict as it is, and none at all to be looser.
|
||||
@State private var armed = false
|
||||
@State private var copied = false
|
||||
@State private var focusID: String?
|
||||
|
||||
private enum Action: String {
|
||||
case wake
|
||||
case copyLink
|
||||
case edit
|
||||
case forgetPairing
|
||||
case remove
|
||||
case unpin
|
||||
case cancel
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
GamepadMenuList(
|
||||
items: rows,
|
||||
focusID: $focusID,
|
||||
onActivate: { run($0.action) },
|
||||
onBack: { performClose() },
|
||||
isActive: controllerActive
|
||||
) { row, focused in
|
||||
rowView(row, focused: focused)
|
||||
.frame(maxWidth: metrics.rowMaxWidth)
|
||||
.padding(.horizontal, 24)
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
.safeAreaInset(edge: .top, spacing: 0) {
|
||||
VStack(alignment: .leading, spacing: gamepadHeaderSpacing(compact: compact)) {
|
||||
Text(title)
|
||||
.font(.geist(gamepadTitleSize(compact: compact), .bold, relativeTo: .title))
|
||||
.foregroundStyle(ink.fg)
|
||||
.lineLimit(1)
|
||||
if !compact {
|
||||
Text("\(host.address):\(String(host.port))")
|
||||
.font(.geistFixed(metrics.detailFont, .medium))
|
||||
.foregroundStyle(ink.fg(0.55))
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 24)
|
||||
.padding(.top, gamepadTitleTopPadding(compact: compact))
|
||||
.padding(.bottom, gamepadTitleBottomPadding(compact: compact))
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background { GamepadTrayBlur(edge: .top) }
|
||||
}
|
||||
.safeAreaInset(edge: .bottom, alignment: .leading, spacing: 0) {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text(detail)
|
||||
.font(.geist(metrics.detailFont, relativeTo: .caption))
|
||||
.foregroundStyle(ink.fg(0.55))
|
||||
.lineLimit(2, reservesSpace: true)
|
||||
.animation(.smooth(duration: 0.2), value: focusID)
|
||||
GamepadHintBar(hints: hints)
|
||||
}
|
||||
.padding(.leading, compact ? 12 : 18)
|
||||
.padding(.trailing, 22)
|
||||
.padding(
|
||||
.bottom,
|
||||
gamepadLegendBottomPadding(
|
||||
compact ? 12 : 18, tier: metrics.tier, displayBottom: displayBottomInset))
|
||||
.padding(.top, compact ? 6 : 10)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background { GamepadTrayBlur(edge: .bottom) }
|
||||
}
|
||||
.background {
|
||||
if !hostedInShell { GamepadFormBackground() }
|
||||
}
|
||||
.gamepadPaletteInk()
|
||||
// Moving the focus off the armed Remove row disarms it: an arming that outlives the row it
|
||||
// was made on is a trap, and the thumb that wandered away is exactly the hesitation the
|
||||
// two-press rule exists to catch.
|
||||
.onChange(of: focusID) { _, id in
|
||||
if id != Action.remove.rawValue { armed = false }
|
||||
}
|
||||
#if !os(tvOS)
|
||||
.background {
|
||||
Button("Cancel") { performClose() }
|
||||
.keyboardShortcut(.cancelAction)
|
||||
.buttonStyle(.plain)
|
||||
.frame(width: 0, height: 0)
|
||||
.opacity(0)
|
||||
.accessibilityHidden(true)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
private var title: String {
|
||||
pinnedProfile.map { "\(host.displayName) · \($0.name)" } ?? host.displayName
|
||||
}
|
||||
|
||||
// MARK: - Rows
|
||||
|
||||
private struct Row: Identifiable {
|
||||
let action: Action
|
||||
let label: String
|
||||
var icon: String
|
||||
var isDestructive = false
|
||||
var id: String { action.rawValue }
|
||||
}
|
||||
|
||||
private var rows: [Row] {
|
||||
// A pinned card is a shortcut, not a host: everything host-level is deliberately absent.
|
||||
if pinnedProfile != nil {
|
||||
return [
|
||||
Row(action: .unpin, label: "Unpin card", icon: "pin.slash"),
|
||||
Row(action: .copyLink, label: copied ? "Copied" : "Copy link", icon: "link"),
|
||||
Row(action: .cancel, label: "Cancel", icon: "xmark"),
|
||||
]
|
||||
}
|
||||
var list: [Row] = []
|
||||
// Waking a host that is already answering would just sit there counting seconds.
|
||||
if canWake, !isOnline {
|
||||
list.append(Row(action: .wake, label: "Wake host", icon: "power"))
|
||||
}
|
||||
list.append(Row(action: .copyLink, label: copied ? "Copied" : "Copy link", icon: "link"))
|
||||
list.append(Row(action: .edit, label: "Edit\u{2026}", icon: "pencil"))
|
||||
// Only a paired host has a pairing to drop.
|
||||
if host.pinnedSHA256 != nil {
|
||||
list.append(Row(
|
||||
action: .forgetPairing, label: "Forget pairing", icon: "lock.open"))
|
||||
}
|
||||
list.append(Row(
|
||||
action: .remove,
|
||||
label: armed ? "Remove host \u{2014} press again" : "Remove host",
|
||||
icon: "trash", isDestructive: true))
|
||||
list.append(Row(action: .cancel, label: "Cancel", icon: "xmark"))
|
||||
return list
|
||||
}
|
||||
|
||||
/// The explainer under the list — the same band the settings screen uses, and the only place a
|
||||
/// destructive action can say what it will actually do before it is pressed.
|
||||
private var detail: String {
|
||||
switch rows.first(where: { $0.id == focusID })?.action {
|
||||
case .wake:
|
||||
return "Send a Wake-on-LAN packet and wait for this host to answer."
|
||||
case .copyLink:
|
||||
return "Copy a punktfunk:// link to this host — paste it anywhere to connect."
|
||||
case .edit:
|
||||
return "Rename this host or change its address. Pairing and pinned cards are kept."
|
||||
case .forgetPairing:
|
||||
return "Drop the stored fingerprint. The host stays saved and the next connect "
|
||||
+ "pairs again."
|
||||
case .remove:
|
||||
return armed
|
||||
? "Press again to remove — this cannot be undone."
|
||||
: "Delete this host, its pairing and its pinned cards from this device."
|
||||
case .unpin:
|
||||
return "Remove this profile's card. The profile itself and the host are untouched."
|
||||
case .cancel, .none:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
private var hints: [GamepadHint] {
|
||||
[
|
||||
.init(
|
||||
glyph: buttonGlyph(\.buttonA, fallback: "a.circle"), text: "Select",
|
||||
action: { if let id = focusID, let row = rows.first(where: { $0.id == id }) {
|
||||
run(row.action)
|
||||
} }),
|
||||
.init(
|
||||
glyph: buttonGlyph(\.buttonB, fallback: "b.circle"), text: "Back",
|
||||
action: { performClose() }),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Actions
|
||||
|
||||
private func run(_ action: Action) {
|
||||
switch action {
|
||||
case .wake:
|
||||
onWake()
|
||||
performClose()
|
||||
case .copyLink:
|
||||
LinkClipboard.copy(
|
||||
DeepLink.forHost(host, profile: pinnedProfile?.id).urlString)
|
||||
// No toast machinery on this surface — the row says so itself, which is the same
|
||||
// acknowledgement in the place the user is already looking.
|
||||
withAnimation(.smooth(duration: 0.2)) { copied = true }
|
||||
case .edit:
|
||||
onEdit()
|
||||
case .forgetPairing:
|
||||
onForgetPairing()
|
||||
performClose()
|
||||
case .remove:
|
||||
guard armed else {
|
||||
withAnimation(.smooth(duration: 0.2)) { armed = true }
|
||||
return
|
||||
}
|
||||
onRemove()
|
||||
performClose()
|
||||
case .unpin:
|
||||
onUnpin()
|
||||
performClose()
|
||||
case .cancel:
|
||||
performClose()
|
||||
}
|
||||
}
|
||||
|
||||
private func performClose() {
|
||||
if let close { close() } else { dismiss() }
|
||||
}
|
||||
|
||||
// MARK: - Row rendering
|
||||
|
||||
private func rowView(_ row: Row, focused: Bool) -> some View {
|
||||
let m = metrics
|
||||
// The destructive row wears the warning colour only once ARMED: red on a row that still
|
||||
// needs a second press reads as "this already happened".
|
||||
let danger = row.isDestructive && armed
|
||||
return HStack(spacing: 14) {
|
||||
Image(systemName: row.icon)
|
||||
.font(.system(size: m.iconFont))
|
||||
.foregroundStyle(
|
||||
danger ? GamepadInk.warningRed : (focused ? ink.accent : ink.fg(0.55)))
|
||||
.frame(width: m.iconWidth)
|
||||
Text(row.label)
|
||||
.font(.geist(m.labelFont, .semibold, relativeTo: .body))
|
||||
.foregroundStyle(danger ? GamepadInk.warningRed : ink.fg)
|
||||
.lineLimit(1)
|
||||
Spacer(minLength: 12)
|
||||
}
|
||||
.padding(.horizontal, m.rowHPad)
|
||||
.padding(.vertical, m.rowVPad)
|
||||
.consoleGlass(
|
||||
RoundedRectangle(cornerRadius: m.rowCorner, style: .continuous),
|
||||
tint: focused ? (danger ? GamepadInk.warningRed.opacity(0.3) : ink.accent(0.30)) : nil,
|
||||
interactive: focused)
|
||||
.overlay {
|
||||
RoundedRectangle(cornerRadius: m.rowCorner, style: .continuous)
|
||||
.strokeBorder(
|
||||
danger ? GamepadInk.warningRed.opacity(0.7) : ink.fg(focused ? 0.28 : 0.06),
|
||||
lineWidth: 1)
|
||||
}
|
||||
.scaleEffect(focused ? 1.0 : 0.98)
|
||||
.animation(.smooth(duration: 0.18), value: focused)
|
||||
.animation(.smooth(duration: 0.18), value: armed)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -67,9 +67,32 @@ struct GamepadInk: Equatable, Sendable {
|
||||
/// The shipped dark look — what a preview or a test composition gets.
|
||||
static let dark = GamepadInk.of(GamepadPalette.named("violet"))
|
||||
|
||||
/// The ink for a stored `ui_palette` id, resolved WITHOUT the environment.
|
||||
///
|
||||
/// For the screens that publish their own ink with `gamepadPaletteInk()`. A view's
|
||||
/// `@Environment` resolves against its PARENT — the modifier a screen applies to its own body
|
||||
/// covers its descendants, never the body's own `ink.…` references — so such a screen reads
|
||||
/// whatever was published ABOVE it. Nested inside another gamepad screen (the iOS shell's
|
||||
/// layers) that happens to be right; presented as a cover or a sheet (tvOS, macOS) there is
|
||||
/// nothing above it and it gets the bare dark default. That is precisely how a pale palette
|
||||
/// came out with a WHITE title, white row labels and a violet focus wash on an Apple TV, while
|
||||
/// the child views in the same screen — the hint bar, the host tiles, the glass — were
|
||||
/// correctly dark-on-pale.
|
||||
///
|
||||
/// Declare it beside an `@AppStorage(DefaultsKey.uiPalette)`, which is what re-renders the
|
||||
/// screen when the setting changes (`GamepadInkModifier` reads the same key).
|
||||
static func stored(_ paletteID: String) -> GamepadInk {
|
||||
.of(GamepadPalette.named(paletteID))
|
||||
}
|
||||
|
||||
/// The online pip — deliberately NOT palette-derived: a status colour must not change
|
||||
/// meaning with the wallpaper (the console's rule; this is its `ONLINE_GREEN` verbatim).
|
||||
static let onlineGreen = Color(red: 0.20, green: 0.84, blue: 0.29)
|
||||
/// An armed destructive action (the host menu's Remove). Palette-independent for exactly the
|
||||
/// same reason as the pip above, and the more strongly so: the one colour on this UI that
|
||||
/// means "this does not come back" cannot be allowed to drift toward the wallpaper on a warm
|
||||
/// palette, or read as a highlight on a red one.
|
||||
static let warningRed = Color(red: 0.94, green: 0.28, blue: 0.26)
|
||||
}
|
||||
|
||||
private struct GamepadInkKey: EnvironmentKey {
|
||||
|
||||
@@ -10,7 +10,10 @@ import SwiftUI
|
||||
#if os(iOS)
|
||||
|
||||
struct GamepadLibraryScreen: View {
|
||||
@Environment(\.gamepadInk) private var ink
|
||||
/// Resolved from the stored palette, NOT from `\.gamepadInk` — this screen publishes that
|
||||
/// value itself and so sits above its own copy (see `GamepadInk.stored`).
|
||||
@AppStorage(DefaultsKey.uiPalette) private var paletteID = "violet"
|
||||
private var ink: GamepadInk { .stored(paletteID) }
|
||||
@ObservedObject var store: HostStore
|
||||
let target: LibraryTarget
|
||||
let onLaunch: (String) -> Void
|
||||
|
||||
@@ -21,6 +21,8 @@ import SwiftUI
|
||||
enum GamepadScreen: Identifiable {
|
||||
case settings
|
||||
case addHost
|
||||
case hostOptions(HostOptionsTarget)
|
||||
case editHost(StoredHost)
|
||||
case pair(StoredHost)
|
||||
case library(LibraryTarget)
|
||||
|
||||
@@ -28,6 +30,10 @@ enum GamepadScreen: Identifiable {
|
||||
switch self {
|
||||
case .settings: return "settings"
|
||||
case .addHost: return "addHost"
|
||||
// Keyed on the CARD (host + pinned profile), for the same reason the library is keyed on
|
||||
// the shelf — see `HostOptionsTarget.id`.
|
||||
case .hostOptions(let target): return "hostOptions-\(target.id)"
|
||||
case .editHost(let host): return "editHost-\(host.id.uuidString)"
|
||||
case .pair(let host): return "pair-\(host.id.uuidString)"
|
||||
// Keyed on the SHELF, not the host: a host and each of its pinned cards open different
|
||||
// libraries, and sharing an id would let one stand in for another mid-transition.
|
||||
@@ -39,7 +45,7 @@ enum GamepadScreen: Identifiable {
|
||||
/// (`Bg::Form` in the console); the library keeps the launcher's full aurora.
|
||||
var isForm: Bool {
|
||||
switch self {
|
||||
case .settings, .addHost, .pair: return true
|
||||
case .settings, .addHost, .hostOptions, .editHost, .pair: return true
|
||||
case .library: return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,10 @@ import SwiftUI
|
||||
import GameController
|
||||
|
||||
struct LibraryCoverflowView: View {
|
||||
@Environment(\.gamepadInk) private var ink
|
||||
/// Resolved from the stored palette, NOT from `\.gamepadInk` — this screen publishes that
|
||||
/// value itself and so sits above its own copy (see `GamepadInk.stored`).
|
||||
@AppStorage(DefaultsKey.uiPalette) private var paletteID = "violet"
|
||||
private var ink: GamepadInk { .stored(paletteID) }
|
||||
let games: [GameEntry]
|
||||
let artLoader: LibraryArtLoader?
|
||||
var onLaunch: ((String) -> Void)?
|
||||
|
||||
@@ -94,6 +94,9 @@ struct LibraryView: View {
|
||||
gamepadConnected: gamepadManager.active != nil, enabledSetting: gamepadUIEnabled,
|
||||
mode: gamepadUIMode)
|
||||
}
|
||||
/// True when the iOS shell already draws one persistent field behind its layers — mounting a
|
||||
/// second would double the mesh (the same rule the coverflow and the settings screen follow).
|
||||
@Environment(\.gamepadHostedInShell) private var hostedInShell
|
||||
#endif
|
||||
|
||||
var body: some View {
|
||||
@@ -150,12 +153,13 @@ struct LibraryView: View {
|
||||
|
||||
@ViewBuilder private var content: some View {
|
||||
if loading && games.isEmpty {
|
||||
ProgressView("Loading library…")
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
consoleField(
|
||||
ProgressView("Loading library…")
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity))
|
||||
} else if let errorText, games.isEmpty {
|
||||
errorState(errorText)
|
||||
consoleField(errorState(errorText))
|
||||
} else if games.isEmpty {
|
||||
emptyState
|
||||
consoleField(emptyState)
|
||||
} else {
|
||||
if gamepadUIActive {
|
||||
LibraryCoverflowView(
|
||||
@@ -168,6 +172,24 @@ struct LibraryView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// The console field behind the three states that are NOT the coverflow — loading, error,
|
||||
/// empty. The coverflow mounts its own backdrop; these mounted nothing, so wherever this view
|
||||
/// is a COVER over the launcher (tvOS, macOS) they drew straight onto it: the spinner and its
|
||||
/// label sat on the launcher's own aurora with the host tiles still showing through. The same
|
||||
/// field as the coverflow's (not the calmed form one), so nothing shifts under the content when
|
||||
/// the titles land and the coverflow takes over.
|
||||
///
|
||||
/// Only in gamepad mode: the plain grid's states belong on the system background, as before.
|
||||
@ViewBuilder private func consoleField(_ view: some View) -> some View {
|
||||
#if os(iOS) || os(macOS) || os(tvOS)
|
||||
view.background {
|
||||
if gamepadUIActive, !hostedInShell { GamepadScreenBackground() }
|
||||
}
|
||||
#else
|
||||
view
|
||||
#endif
|
||||
}
|
||||
|
||||
private var grid: some View {
|
||||
// Design D4: launcher entries get their own section above the titles, never interleaved.
|
||||
// Both headers appear only when both groups exist, so a library without launcher entries
|
||||
|
||||
@@ -244,7 +244,8 @@ private struct ShotGamepadHome: View {
|
||||
store: store, model: model, discovery: discovery,
|
||||
libraryTarget: .constant(nil), pairingTarget: .constant(nil),
|
||||
onPaired: { _, _ in }, waker: waker,
|
||||
connect: { _, _ in }, connectDiscovered: { _ in }, launchTitle: { _, _ in })
|
||||
connect: { _, _ in }, connectDiscovered: { _ in }, launchTitle: { _, _ in },
|
||||
wakeOnly: { _ in })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,7 +304,8 @@ private struct ShotConnect: View {
|
||||
store: store, model: model, discovery: discovery,
|
||||
libraryTarget: .constant(nil), pairingTarget: .constant(nil),
|
||||
onPaired: { _, _ in }, waker: waker,
|
||||
connect: { _, _ in }, connectDiscovered: { _ in }, launchTitle: { _, _ in })
|
||||
connect: { _, _ in }, connectDiscovered: { _ in }, launchTitle: { _, _ in },
|
||||
wakeOnly: { _ in })
|
||||
} else {
|
||||
ShotHome()
|
||||
}
|
||||
|
||||
@@ -20,6 +20,18 @@ import SwiftUI
|
||||
/// instrument: any visible overlay forces the metal layer through the compositor, which costs a
|
||||
/// refresh period on the vsync-latched platforms — this is how to measure with it off.
|
||||
private let statsLog = Logger(subsystem: "io.unom.punktfunk", category: "stats")
|
||||
/// Mirror the 1 Hz vitals line to STDOUT as well as the unified log.
|
||||
///
|
||||
/// Exists for **tvOS, where the unified log is unreachable**: `log stream --device` is gone from
|
||||
/// modern macOS, `log collect --device-name` needs root and then fails "Device not configured"
|
||||
/// (an Apple TV has no USB to fall back to), and libimobiledevice pairs against a different
|
||||
/// database than Xcode. Stdout, however, IS bridged — `xcrun devicectl device process launch
|
||||
/// --console -e '{"PUNKTFUNK_STATS_STDOUT":"1"}' io.unom.punktfunk` streams these lines straight
|
||||
/// to the Mac. That is the only way to read a session's numbers with the **stats overlay OFF**,
|
||||
/// which matters because the overlay is itself a composited layer over the Metal one — i.e. a
|
||||
/// plausible cause of the very present-floor inflation the overlay is used to measure.
|
||||
/// Env-gated: no cost, and no stdout noise, unless someone is deliberately measuring.
|
||||
private let statsToStdout = ProcessInfo.processInfo.environment["PUNKTFUNK_STATS_STDOUT"] == "1"
|
||||
|
||||
/// Pump-thread-side frame counters; a 1 Hz main-actor timer drains them into @Published
|
||||
/// values. NSLock instead of an actor — the writer is the (non-async) pump thread.
|
||||
@@ -137,6 +149,25 @@ final class SessionModel: ObservableObject {
|
||||
/// and under stage-1.
|
||||
@Published var osFloorP50Ms = 0.0
|
||||
@Published var osFloorValid = false
|
||||
/// The deadline link's `preferredFrameLatency` ASK beside its property READBACK (see
|
||||
/// `PresentLinkInfo` — it exists because tvOS has no reachable log). ⚠ The readback is NOT
|
||||
/// a grant: it is a plain float property, so it echoes whatever was stored unless the
|
||||
/// system clamps the setter. readback ≠ ask ⇒ a visible clamp (the one signal the API can
|
||||
/// give); readback == ask proves nothing — `osFloorP50Ms` (the measured vend lead) is the
|
||||
/// truth-teller (field 2026-08-13: readback 1.00 beside a 32.5 ms floor).
|
||||
@Published var linkLatencyAskFrames: Float = 0
|
||||
@Published var linkLatencyFrames: Float = 0
|
||||
@Published var linkRangeMinHz: Float = 0
|
||||
@Published var linkRangeMaxHz: Float = 0
|
||||
@Published var linkDrawables = 0
|
||||
@Published var linkInfoValid = false
|
||||
/// Impossible samples the HOST-ANCHORED meters (host+network, end-to-end) refused this
|
||||
/// second (`LatencyMeter.drainTrimmed`). Nonzero means the clock offset is lying and every
|
||||
/// host-anchored p50/p95 this window is a TRUNCATED distribution — the HUD marks the window
|
||||
/// suspect instead of letting a trimmed tail pose as a healthy small number (the field
|
||||
/// "e2e 0–3 ms" reading, 2026-08-13). Client-local stages can't go negative, so they carry
|
||||
/// no such term.
|
||||
@Published var skewTrimPerS = 0
|
||||
/// The AUDIO plane's latency, from the playback ring (`SessionAudio.Stats`): how much decoded
|
||||
/// audio is queued ahead of the speaker, and where that PUTS it relative to the picture
|
||||
/// (positive = audio behind). `audioValid` is false until playback runs.
|
||||
@@ -683,6 +714,10 @@ final class SessionModel: ObservableObject {
|
||||
displayValid = false
|
||||
clientQueueValid = false
|
||||
osFloorValid = false
|
||||
linkInfoValid = false
|
||||
// Drop the previous session's grant too — the shared box outlives the session, and a new
|
||||
// link may never come up (a non-deadline rung has none at all).
|
||||
PresentLinkInfo.shared.clear()
|
||||
audioValid = false
|
||||
lostFrames = 0
|
||||
lostPct = 0
|
||||
@@ -904,6 +939,10 @@ final class SessionModel: ObservableObject {
|
||||
} else {
|
||||
self.endToEndValid = false
|
||||
}
|
||||
// Drained even when the stats drains came back empty — with a badly wrong offset
|
||||
// an entire window is refused and only this counter still tells the story.
|
||||
self.skewTrimPerS =
|
||||
self.latency.drainTrimmed() + self.endToEnd.drainTrimmed()
|
||||
if let d = self.decodeStage.drain() {
|
||||
self.decodeP50Ms = d.p50Ms
|
||||
self.decodeValid = true
|
||||
@@ -923,6 +962,18 @@ final class SessionModel: ObservableObject {
|
||||
} else {
|
||||
self.osFloorValid = false
|
||||
}
|
||||
// The display link's latency ask + property readback (deadline rung only) — a
|
||||
// LEVEL, not a window, so it is read rather than drained.
|
||||
if let l = PresentLinkInfo.shared.snapshot() {
|
||||
self.linkLatencyAskFrames = l.ask
|
||||
self.linkLatencyFrames = l.latency
|
||||
self.linkRangeMinHz = l.rangeMin
|
||||
self.linkRangeMaxHz = l.rangeMax
|
||||
self.linkDrawables = l.drawables
|
||||
self.linkInfoValid = true
|
||||
} else {
|
||||
self.linkInfoValid = false
|
||||
}
|
||||
if let q = self.clientQueue.drain() {
|
||||
self.clientQueueP50Ms = q.p50Ms
|
||||
self.clientQueueValid = true
|
||||
@@ -951,6 +1002,14 @@ final class SessionModel: ObservableObject {
|
||||
// Swift Int is 64-bit → %lld, NOT %d (which is a 32-bit C int); macOS 26's
|
||||
// strict String(format:) validator rejects the %d/Int mismatch and drops
|
||||
// the whole line (a cascade error that also mis-blames the float args).
|
||||
//
|
||||
// ⚠ Every invalid-field fallback below MUST be a typed `-1.0` (or a
|
||||
// `Double(...)`-wrapped value), never a bare `-1`: in this variadic
|
||||
// `CVarArg` context the ternary does NOT unify to Double — the untyped
|
||||
// literal goes in as Int, and `%f` then reads Int64(-1)'s all-ones bit
|
||||
// pattern, which IS a quiet NaN. Field 2026-08-13 (tvOS, stage-1, the
|
||||
// first session ever to have invalid fields while frames flowed): every
|
||||
// fallback printed `nan`. Latent since the line was added.
|
||||
format: "fps=%lld presents=%lld e2e_p50=%.1f e2e_p95=%.1f hostnet_p50=%.1f "
|
||||
+ "decode_p50=%.1f display_p50=%.1f lost=%lld "
|
||||
+ "floor_p50=%.1f display_adj=%.1f e2e_adj=%.1f queue_p50=%.1f "
|
||||
@@ -958,22 +1017,35 @@ final class SessionModel: ObservableObject {
|
||||
// In the log as well as on the HUD because the overlay is only up when
|
||||
// someone thought to turn it on, and the reports that need these
|
||||
// numbers arrive after the fact.
|
||||
+ "audio_buffer=%lld audio_av_offset=%lld",
|
||||
+ "audio_buffer=%lld audio_av_offset=%lld "
|
||||
// The deadline link's latency ask + property readback (both -1 on
|
||||
// non-deadline rungs) — appended so the PUNKTFUNK_FRAME_LATENCY
|
||||
// ladder is readable over the stdout channel with the HUD off,
|
||||
// which is the only honest way to run it on a tvOS device.
|
||||
+ "link_ask=%.2f link_readback=%.2f "
|
||||
// Impossible samples the host-anchored meters refused this window:
|
||||
// nonzero ⇒ the clock offset is lying and e2e/hostnet above are
|
||||
// truncated distributions — disregard their p50/p95.
|
||||
+ "skew_trim=%lld",
|
||||
frames,
|
||||
displayWindow?.count ?? 0,
|
||||
self.endToEndValid ? self.endToEndP50Ms : -1,
|
||||
self.endToEndValid ? self.endToEndP95Ms : -1,
|
||||
self.hostNetworkValid ? self.hostNetworkP50Ms : -1,
|
||||
self.decodeValid ? self.decodeP50Ms : -1,
|
||||
self.displayValid ? self.displayP50Ms : -1,
|
||||
self.endToEndValid ? self.endToEndP50Ms : -1.0,
|
||||
self.endToEndValid ? self.endToEndP95Ms : -1.0,
|
||||
self.hostNetworkValid ? self.hostNetworkP50Ms : -1.0,
|
||||
self.decodeValid ? self.decodeP50Ms : -1.0,
|
||||
self.displayValid ? self.displayP50Ms : -1.0,
|
||||
lost,
|
||||
self.osFloorValid ? self.osFloorP50Ms : -1,
|
||||
self.displayValid ? self.displayAdjP50Ms : -1,
|
||||
self.endToEndValid ? self.endToEndAdjP50Ms : -1,
|
||||
self.clientQueueValid ? self.clientQueueP50Ms : -1,
|
||||
self.osFloorValid ? self.osFloorP50Ms : -1.0,
|
||||
self.displayValid ? self.displayAdjP50Ms : -1.0,
|
||||
self.endToEndValid ? self.endToEndAdjP50Ms : -1.0,
|
||||
self.clientQueueValid ? self.clientQueueP50Ms : -1.0,
|
||||
self.audioValid ? self.audioBufferMs : -1,
|
||||
self.audioValid ? self.audioAvOffsetMs : 0)
|
||||
self.audioValid ? self.audioAvOffsetMs : 0,
|
||||
self.linkInfoValid ? Double(self.linkLatencyAskFrames) : -1.0,
|
||||
self.linkInfoValid ? Double(self.linkLatencyFrames) : -1.0,
|
||||
self.skewTrimPerS)
|
||||
statsLog.info("\(line, privacy: .public)")
|
||||
if statsToStdout { print("pf.stats \(line)") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,6 +128,29 @@ struct StreamHUDView: View {
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.tertiary)
|
||||
}
|
||||
// The deadline link's frame-latency ASK beside its property READBACK. ⚠ The
|
||||
// readback is NOT a grant — the property echoes whatever we stored (field
|
||||
// 2026-08-13: 1.00 beside a 32.5 ms `os present` floor). The line earns its
|
||||
// place because a readback that DIFFERS from the ask is the one clamp signal
|
||||
// the API can give, and on tvOS the screen is the only place to read either
|
||||
// (no log is reachable on an Apple TV; see PresentLinkInfo).
|
||||
if model.linkInfoValid {
|
||||
Text("link latency ask \(model.linkLatencyAskFrames, specifier: "%.2f") readback \(model.linkLatencyFrames, specifier: "%.2f") · range \(model.linkRangeMinHz, specifier: "%.0f")-\(model.linkRangeMaxHz, specifier: "%.0f") Hz · drawables \(model.linkDrawables)")
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.tertiary)
|
||||
}
|
||||
// The clock-offset tripwire: host-anchored meters refused samples as
|
||||
// impossible (≤ 0 after offset correction) this second. When this shows,
|
||||
// e2e and host+network above are TRUNCATED distributions — a wrong skew
|
||||
// offset shifted them and the impossible half was trimmed — so their
|
||||
// p50/p95 flatter the stream (the field "e2e 0–3 ms" reading). Orange on
|
||||
// purpose: every other stat here stays legible-quiet, but a number that
|
||||
// has stopped meaning anything must not.
|
||||
if model.skewTrimPerS > 0 {
|
||||
Text("clock offset suspect — \(model.skewTrimPerS)/s impossible samples trimmed; e2e & host+network unreliable")
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.orange)
|
||||
}
|
||||
// Client-queue wait (reassembly receipt → decode pull, ABI v9 split): ~0 on
|
||||
// a healthy stream and hidden as noise; shown from 2 ms — a persistent value
|
||||
// is a client-side standing backlog that pre-split builds displayed as
|
||||
|
||||
@@ -28,6 +28,10 @@ struct AboutView: View {
|
||||
|
||||
#if !os(tvOS)
|
||||
@State private var showAcknowledgements = false
|
||||
/// The in-session controls. They used to announce themselves in a 6-second banner at the start
|
||||
/// of every stream; that banner is gone, so this page is where they live now — including for
|
||||
/// touch users on a Mac, who saw it too.
|
||||
@State private var showShortcuts = false
|
||||
#endif
|
||||
|
||||
var body: some View {
|
||||
@@ -44,6 +48,9 @@ struct AboutView: View {
|
||||
.listRowInsets(EdgeInsets())
|
||||
.listRowBackground(Color.clear)
|
||||
}
|
||||
Section {
|
||||
shortcutsRow
|
||||
}
|
||||
Section {
|
||||
linkRow("Documentation", systemImage: "book", url: Destination.docs)
|
||||
linkRow("Community", systemImage: "bubble.left.and.bubble.right",
|
||||
@@ -63,6 +70,21 @@ struct AboutView: View {
|
||||
// A SHEET, not a push — on iPad the settings detail column is deliberately not a
|
||||
// NavigationStack (an inner one doubles the title bar), so a NavigationLink from here
|
||||
// pushed into a context with no back button and stranded the licenses on screen.
|
||||
// A sheet for the same reason Acknowledgements is one — see that modifier's note on the
|
||||
// iPad detail column not being a NavigationStack.
|
||||
.sheet(isPresented: $showShortcuts) {
|
||||
NavigationStack {
|
||||
ShortcutsView(micAvailable: ShortcutsCatalog.micPlausible)
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .confirmationAction) {
|
||||
Button("Done") { showShortcuts = false }
|
||||
}
|
||||
}
|
||||
}
|
||||
#if os(macOS)
|
||||
.frame(width: 560, height: 460)
|
||||
#endif
|
||||
}
|
||||
.sheet(isPresented: $showAcknowledgements) {
|
||||
NavigationStack {
|
||||
AcknowledgementsView()
|
||||
@@ -135,6 +157,24 @@ struct AboutView: View {
|
||||
.foregroundStyle(.primary)
|
||||
}
|
||||
|
||||
private var shortcutsRow: some View {
|
||||
Button {
|
||||
showShortcuts = true
|
||||
} label: {
|
||||
HStack {
|
||||
Label("Shortcuts", systemImage: "command")
|
||||
Spacer(minLength: 8)
|
||||
Image(systemName: "chevron.right")
|
||||
.font(.footnote.weight(.semibold))
|
||||
.foregroundStyle(.tertiary)
|
||||
.accessibilityHidden(true)
|
||||
}
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(.primary)
|
||||
}
|
||||
|
||||
private var acknowledgementsRow: some View {
|
||||
Button {
|
||||
showAcknowledgements = true
|
||||
@@ -168,6 +208,11 @@ struct AboutView: View {
|
||||
tvAddress("Community", Destination.community)
|
||||
tvAddress("Source code", Destination.source)
|
||||
}
|
||||
// Both push here: this page really is inside a navigation stack on tvOS, which is
|
||||
// the case the sheets above exist to work around elsewhere.
|
||||
NavigationLink("Shortcuts") {
|
||||
ShortcutsView(micAvailable: false) // tvOS has no app-accessible mic
|
||||
}
|
||||
NavigationLink("Acknowledgements") { AcknowledgementsView() }
|
||||
Text("Punktfunk's source is open under MIT or Apache-2.0.")
|
||||
.font(.geist(20, relativeTo: .caption))
|
||||
@@ -219,21 +264,39 @@ struct AppIconView: View {
|
||||
var body: some View {
|
||||
Group {
|
||||
if let icon = Self.bundleIcon {
|
||||
icon.image
|
||||
.resizable()
|
||||
.interpolation(.high)
|
||||
.aspectRatio(contentMode: .fit)
|
||||
// iOS ships the icon UNMASKED — the springboard applies the rounded shape at
|
||||
// draw time, so used raw it is a hard-cornered square. macOS bakes its own
|
||||
// shape (and margins) into the image, and clipping that would cut into it.
|
||||
.clipShape(RoundedRectangle(
|
||||
cornerRadius: icon.needsMask ? side * Self.iOSCornerRatio : 0,
|
||||
style: .continuous))
|
||||
// The mask is applied ONLY where it is wanted. A `cornerRadius: 0` RoundedRectangle
|
||||
// is not a no-op — it still clips to the layout frame, which crops any art whose
|
||||
// aspect ratio isn't the frame's (the TV's 400x240 icon lost its ends to it).
|
||||
// iOS ships the icon UNMASKED — the springboard applies the rounded shape at draw
|
||||
// time, so used raw it is a hard-cornered square. macOS bakes its own shape (and
|
||||
// margins) into the image, and clipping that would cut into it.
|
||||
if icon.needsMask {
|
||||
icon.image
|
||||
.resizable()
|
||||
.interpolation(.high)
|
||||
.aspectRatio(contentMode: .fit)
|
||||
.clipShape(RoundedRectangle(
|
||||
cornerRadius: side * Self.iOSCornerRatio, style: .continuous))
|
||||
} else {
|
||||
icon.image
|
||||
.resizable()
|
||||
.interpolation(.high)
|
||||
.aspectRatio(contentMode: .fit)
|
||||
}
|
||||
} else {
|
||||
monogram
|
||||
}
|
||||
}
|
||||
// tvOS's icon is a 400×240 rectangle, not a squircle — framing it square would letterbox
|
||||
// it inside a box two thirds empty. `side` means HEIGHT there, and the width follows the
|
||||
// real 5:3 art. A MAX frame rather than a fixed one: with a fixed width the image cannot
|
||||
// shrink when its row is tight, so it overflows and is clipped by whatever is above it
|
||||
// instead — `.fit` inside a max frame gives back the whole icon, just smaller.
|
||||
#if os(tvOS)
|
||||
.frame(maxWidth: side * (400.0 / 240.0), maxHeight: side)
|
||||
#else
|
||||
.frame(width: side, height: side)
|
||||
#endif
|
||||
.accessibilityHidden(true) // the app's name is the next line
|
||||
}
|
||||
|
||||
@@ -267,7 +330,14 @@ struct AppIconView: View {
|
||||
else { return nil }
|
||||
return (Image(uiImage: image), true)
|
||||
#else
|
||||
return nil // tvOS: layered icons have no single image to load
|
||||
// tvOS ships the icon as a parallax image STACK (Back/Circle1/Circle2/Front), which has
|
||||
// no single image to load — which is why this used to return nil and every About page on
|
||||
// the TV drew the "P" monogram instead of the app's own mark. `AboutAppIcon` is those
|
||||
// four layers flattened into one asset, generated from the SAME art the stack uses so it
|
||||
// cannot drift into being a second, subtly different icon. Already masked and composited,
|
||||
// so it needs no rounding of ours.
|
||||
guard let image = UIImage(named: "AboutAppIcon") else { return nil }
|
||||
return (Image(uiImage: image), false)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,14 +42,22 @@ enum GpSettingsTab: String, CaseIterable, Hashable {
|
||||
case controller = "Controller"
|
||||
case interface = "Interface"
|
||||
case profiles = "Profiles"
|
||||
/// Trailing, like Profiles: both are built from something other than the settings store, and
|
||||
/// About is where the strip ends because it is the one section that changes nothing.
|
||||
case about = "About"
|
||||
}
|
||||
|
||||
struct GamepadSettingsView: View {
|
||||
@Environment(\.gamepadInk) private var ink
|
||||
/// Resolved from `paletteID` below, NOT from `\.gamepadInk` — this screen publishes that value
|
||||
/// itself and so sits above its own copy (see `GamepadInk.stored`). Reading the environment
|
||||
/// here is what left the title, the tab pills and every row label white-on-pale on tvOS.
|
||||
private var ink: GamepadInk { .stored(paletteID) }
|
||||
@Environment(\.gamepadMetrics) private var metrics
|
||||
@Environment(\.displayBottomInset) private var displayBottomInset
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@Environment(\.gamepadHostedInShell) private var hostedInShell
|
||||
/// The About section's link rows (never used on tvOS, which has no browser).
|
||||
@Environment(\.openURL) private var openURL
|
||||
/// The saved-host store — the pin picker writes `setPinned` through it and the profile rows
|
||||
/// count pins from its live hosts. Threaded in from GamepadHomeView like the home screen
|
||||
/// itself (ContentView owns the instance).
|
||||
@@ -61,6 +69,9 @@ struct GamepadSettingsView: View {
|
||||
/// console's input drop) and while the connect takeover is up; a system presentation never
|
||||
/// needs the gate and keeps the default.
|
||||
var controllerActive = true
|
||||
/// Whether this device has a microphone at all — passed through to the About page's shortcuts
|
||||
/// reference, which must not list a mute key on a device that can't mute anything.
|
||||
var micAvailable = true
|
||||
@AppStorage(DefaultsKey.streamWidth) private var width = 1920
|
||||
@AppStorage(DefaultsKey.streamHeight) private var height = 1080
|
||||
@AppStorage(DefaultsKey.streamHz) private var hz = 60
|
||||
@@ -132,6 +143,14 @@ struct GamepadSettingsView: View {
|
||||
/// The direction of the last value step (+1 right/forward, -1 left) — picks which edge the
|
||||
/// changed value slides in from, so the animation follows the user's motion.
|
||||
@State private var lastAdjustDelta = 1
|
||||
/// A reading surface opened from the About tab, replacing the row list the way the pin picker
|
||||
/// does. Depth is 1: neither page opens anything further.
|
||||
private enum AboutPage: Equatable {
|
||||
case shortcuts
|
||||
case licenses
|
||||
}
|
||||
|
||||
@State private var aboutPage: AboutPage?
|
||||
|
||||
var body: some View {
|
||||
GamepadMenuList(
|
||||
@@ -157,9 +176,9 @@ struct GamepadSettingsView: View {
|
||||
.foregroundStyle(ink.fg)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(.horizontal, 24)
|
||||
// The picker is one layer deeper — its rows aren't sections of anything, so the
|
||||
// strip would be a control that does nothing while it's up.
|
||||
if pinTarget == nil { tabStrip }
|
||||
// The picker and the About reading pages are one layer deeper — their rows aren't
|
||||
// sections of anything, so the strip would be a control that does nothing.
|
||||
if pinTarget == nil, aboutPage == nil { tabStrip }
|
||||
}
|
||||
.padding(.top, gamepadTitleTopPadding(compact: compact))
|
||||
.padding(.bottom, gamepadTitleBottomPadding(compact: compact))
|
||||
@@ -326,16 +345,62 @@ struct GamepadSettingsView: View {
|
||||
if let close { close() } else { dismiss() }
|
||||
}
|
||||
|
||||
/// Where the product actually lives — kept together so the three can be checked against the
|
||||
/// README in one glance (the touch `AboutView` holds the same three).
|
||||
private enum Destination {
|
||||
static let docs = URL(string: "https://docs.punktfunk.unom.io")!
|
||||
static let community = URL(string: "https://discord.gg/kaPNvzMuGU")!
|
||||
static let source = URL(string: "https://git.unom.io/unom/punktfunk")!
|
||||
}
|
||||
|
||||
/// "Version 0.29.0 (100000)" — the build number only when it says something the version does
|
||||
/// not. Mirrors `AboutView.versionLine`; a bug report is worth more with it.
|
||||
private static var versionLine: String {
|
||||
let info = Bundle.main.infoDictionary
|
||||
let short = info?["CFBundleShortVersionString"] as? String ?? "—"
|
||||
let build = info?["CFBundleVersion"] as? String
|
||||
guard let build, !build.isEmpty, build != short else { return "Version \(short)" }
|
||||
return "Version \(short) (\(build))"
|
||||
}
|
||||
|
||||
/// "Settings", or "Pin “Work”" while the pin picker is up — the title is what says which
|
||||
/// layer the row list currently is.
|
||||
private var title: String {
|
||||
pinTarget.map { "Pin “\($0.name)”" } ?? "Settings"
|
||||
if let profile = pinTarget { return "Pin “\(profile.name)”" }
|
||||
switch aboutPage {
|
||||
case .shortcuts: return "Shortcuts"
|
||||
case .licenses: return "Acknowledgements"
|
||||
case nil: return "Settings"
|
||||
}
|
||||
}
|
||||
|
||||
/// The legend follows the layer: value-editing hints on the settings rows, pin/unpin on the
|
||||
/// picker — where B reads "Back" (it peels to the settings rows, GamepadAddHostView's "one
|
||||
/// layer" rule), and a hostless picker has nothing to pin, so only Back remains.
|
||||
private var hints: [GamepadHint] {
|
||||
// A reading page is scrolled, not operated: offering A would be the same lie a dimmed row
|
||||
// used to tell. Only Back remains.
|
||||
if aboutPage != nil {
|
||||
return [.init(
|
||||
glyph: buttonGlyph(\.buttonB, fallback: "b.circle"), text: "Back",
|
||||
action: { back() })]
|
||||
}
|
||||
// The About rows open things rather than change them, so A reads "Open" and there is no
|
||||
// Adjust cell — left/right genuinely does nothing there.
|
||||
if pinTarget == nil, tab == .about {
|
||||
let sections: [GamepadHint] = showsSectionHint
|
||||
? [.init(glyph: buttonGlyph(\.leftShoulder, fallback: "l1.rectangle.roundedbottom"),
|
||||
text: "Section", action: { step(tabBy: 1) })]
|
||||
: []
|
||||
return sections + [
|
||||
.init(
|
||||
glyph: buttonGlyph(\.buttonA, fallback: "a.circle"), text: "Open",
|
||||
action: { if let focusID { activate(id: focusID) } }),
|
||||
.init(
|
||||
glyph: buttonGlyph(\.buttonB, fallback: "b.circle"), text: "Done",
|
||||
action: { back() }),
|
||||
]
|
||||
}
|
||||
guard pinTarget != nil else {
|
||||
// The shoulders change section, so that cell leads — where it fits and where the
|
||||
// shoulders exist at all (see `showsSectionHint`).
|
||||
@@ -383,6 +448,9 @@ struct GamepadSettingsView: View {
|
||||
if let profile = pinTarget {
|
||||
pinTarget = nil
|
||||
focusID = "profile-\(profile.id)"
|
||||
} else if let page = aboutPage {
|
||||
aboutPage = nil
|
||||
focusID = page == .shortcuts ? "shortcuts" : "licenses"
|
||||
} else {
|
||||
performClose()
|
||||
}
|
||||
@@ -390,7 +458,53 @@ struct GamepadSettingsView: View {
|
||||
|
||||
// MARK: - Row rendering
|
||||
|
||||
@ViewBuilder
|
||||
private func rowView(_ row: Row, focused: Bool) -> some View {
|
||||
switch row.kind {
|
||||
case .control: controlRow(row, focused: focused)
|
||||
case .footer:
|
||||
Text(row.label)
|
||||
.font(.geist(metrics.detailFont, .medium, relativeTo: .caption))
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(ink.fg(focused ? 0.7 : 0.45))
|
||||
.frame(maxWidth: .infinity, alignment: .center)
|
||||
.padding(.top, 18)
|
||||
.animation(.smooth(duration: 0.18), value: focused)
|
||||
case .heading:
|
||||
Text(row.label)
|
||||
.font(.geist(metrics.labelFont, .bold, relativeTo: .headline))
|
||||
.foregroundStyle(ink.fg(0.75))
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(.horizontal, metrics.rowHPad)
|
||||
.padding(.top, 14)
|
||||
.padding(.bottom, 2)
|
||||
case .prose:
|
||||
// Focus here means "this is the part you are scrolled to", not "press A" — so it is a
|
||||
// quiet wash rather than the control rows' full glass.
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(row.label)
|
||||
.font(.geistFixed(metrics.valueFont, .medium))
|
||||
.foregroundStyle(ink.fg(0.95))
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
if !row.value.isEmpty {
|
||||
Text(row.value)
|
||||
.font(.geist(metrics.detailFont, relativeTo: .caption))
|
||||
.foregroundStyle(ink.fg(0.6))
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(.horizontal, metrics.rowHPad)
|
||||
.padding(.vertical, metrics.rowVPad * 0.7)
|
||||
.background {
|
||||
RoundedRectangle(cornerRadius: metrics.rowCorner, style: .continuous)
|
||||
.fill(ink.fg(focused ? 0.08 : 0))
|
||||
}
|
||||
.animation(.smooth(duration: 0.18), value: focused)
|
||||
}
|
||||
}
|
||||
|
||||
private func controlRow(_ row: Row, focused: Bool) -> some View {
|
||||
let m = metrics
|
||||
// No section header: the tab strip names the section now, and repeating it above the
|
||||
// first row of every tab was just a second label saying the same word.
|
||||
@@ -502,10 +616,23 @@ struct GamepadSettingsView: View {
|
||||
/// `activate(id:)`, not per closure, so no row builder can forget it.
|
||||
/// (Android's `GpRow.enabled` and `pf-console-ui`'s `RowSpec.enabled` are the twins.)
|
||||
var enabled = true
|
||||
/// How this row DRAWS. Every tab but About is `.control` — the glass row with a label and
|
||||
/// a value. About is a reading surface as much as a menu, so it also has a heading and a
|
||||
/// block of prose, which are rows only so the focus list can scroll them (the same trick
|
||||
/// `Licenses.chunked` plays for tvOS focus).
|
||||
var kind: Kind = .control
|
||||
/// Left/right step; returns whether the value actually changed (false ⇒ boundary thud).
|
||||
let adjust: (Int) -> Bool
|
||||
/// A — cycle forward (wrapping) / flip.
|
||||
let activate: () -> Void
|
||||
|
||||
enum Kind {
|
||||
case control
|
||||
case heading
|
||||
case prose
|
||||
/// Quiet, centred trailing text — the About tab's version line.
|
||||
case footer
|
||||
}
|
||||
}
|
||||
|
||||
/// Dispatch by id so the focus list's stored input callbacks always act on freshly built rows
|
||||
@@ -527,9 +654,133 @@ struct GamepadSettingsView: View {
|
||||
/// controller wiring and the tvOS focus engine carry over as is).
|
||||
private var rows: [Row] {
|
||||
if let profile = pinTarget { return pinRows(for: profile) }
|
||||
if let page = aboutPage {
|
||||
switch page {
|
||||
case .shortcuts: return shortcutRows
|
||||
case .licenses: return licenseRows
|
||||
}
|
||||
}
|
||||
if tab == .about { return aboutRows }
|
||||
return allRows.filter { $0.tab == tab }
|
||||
}
|
||||
|
||||
// MARK: - About
|
||||
|
||||
/// The About section: the ways out, plus the two reading surfaces. The identity itself (icon,
|
||||
/// name, version, tagline) is the HEADER while this tab is up — see `aboutIdentity` — not a
|
||||
/// row, so the list holds no focus stop that does nothing when pressed.
|
||||
private var aboutRows: [Row] {
|
||||
var list: [Row] = [
|
||||
aboutAction(
|
||||
id: "shortcuts", icon: "command", label: "Shortcuts", value: "While streaming",
|
||||
detail: "What to press during a session on this device — and on a controller.",
|
||||
open: .shortcuts),
|
||||
aboutAction(
|
||||
id: "licenses", icon: "text.document", label: "Acknowledgements",
|
||||
value: "MIT or Apache-2.0",
|
||||
detail: "Punktfunk's own licence and the third-party components it uses.",
|
||||
open: .licenses),
|
||||
]
|
||||
list.append(contentsOf: [
|
||||
aboutLink(id: "docs", icon: "book", label: "Documentation", url: Destination.docs),
|
||||
aboutLink(
|
||||
id: "community", icon: "bubble.left.and.bubble.right", label: "Community",
|
||||
url: Destination.community),
|
||||
aboutLink(
|
||||
id: "source", icon: "chevron.left.forwardslash.chevron.right",
|
||||
label: "Source code", url: Destination.source),
|
||||
])
|
||||
// The version sits UNDER the rows rather than in a header card above them. The card that
|
||||
// used to head this tab carried the app icon, and on tvOS that icon is a 400x240
|
||||
// rectangle that would not survive contact with a layout built for square art — three
|
||||
// attempts at framing it were still cropping it on the real TV. A version string answers
|
||||
// the only question anyone actually opens About to ask, and has no aspect ratio to get
|
||||
// wrong. `.footer` draws it quiet and centred, so it reads as a footer and not a row you
|
||||
// failed to press.
|
||||
list.append(Row(
|
||||
id: "version", tab: .about, icon: "", label: Self.versionLine, value: "",
|
||||
detail: "", adjustable: false, enabled: true, kind: .footer,
|
||||
adjust: { _ in false }, activate: {}))
|
||||
return list
|
||||
}
|
||||
|
||||
private func aboutAction(
|
||||
id: String, icon: String, label: String, value: String, detail: String, open: AboutPage
|
||||
) -> Row {
|
||||
Row(
|
||||
id: id, tab: .about, icon: icon, label: label, value: value, detail: detail,
|
||||
adjustable: false,
|
||||
adjust: { _ in false },
|
||||
activate: {
|
||||
// Focus lands on the page's first row — the focus list's reconcile follows this
|
||||
// id when the row set swaps underneath it (the pin picker's pattern).
|
||||
focusID = open == .shortcuts ? shortcutRows.first?.id : licenseRows.first?.id
|
||||
aboutPage = open
|
||||
})
|
||||
}
|
||||
|
||||
/// tvOS has no browser and no `openURL`, so an address there is text to read off the screen
|
||||
/// rather than a link to nowhere — the same call the touch About page makes.
|
||||
private func aboutLink(id: String, icon: String, label: String, url: URL) -> Row {
|
||||
let shown = url.absoluteString.replacingOccurrences(of: "https://", with: "")
|
||||
#if os(tvOS)
|
||||
return Row(
|
||||
id: id, tab: .about, icon: icon, label: label, value: shown,
|
||||
detail: "Open this address on a phone or computer.",
|
||||
adjustable: false, adjust: { _ in false }, activate: {})
|
||||
#else
|
||||
return Row(
|
||||
id: id, tab: .about, icon: icon, label: label, value: shown,
|
||||
detail: "Opens in your browser.",
|
||||
adjustable: false, adjust: { _ in false }, activate: { openURL(url) })
|
||||
#endif
|
||||
}
|
||||
|
||||
/// The shortcuts reference — the same `ShortcutsCatalog` the touch About page renders, so the
|
||||
/// two can never drift.
|
||||
private var shortcutRows: [Row] {
|
||||
ShortcutsCatalog.groups(micAvailable: micAvailable).flatMap { group -> [Row] in
|
||||
[aboutText(id: "group-\(group.title)", label: group.title, kind: .heading)]
|
||||
+ group.items.map { item in
|
||||
aboutText(
|
||||
id: "sc-\(group.title)-\(item.keys)", label: item.keys, value: item.text,
|
||||
kind: .prose)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The licence wall, one row per pre-chunked page (`Licenses.chunked`, which exists so tvOS
|
||||
/// can page it by focus steps) — so it scrolls with the stick and needs no machinery here.
|
||||
private var licenseRows: [Row] {
|
||||
var list: [Row] = [
|
||||
aboutText(id: "lic-heading", label: "Punktfunk", kind: .heading),
|
||||
aboutText(
|
||||
id: "lic-summary",
|
||||
label: "Punktfunk's source is open under MIT or Apache-2.0. It ships the Geist "
|
||||
+ "typeface under the SIL Open Font License 1.1, and uses the third-party "
|
||||
+ "components below, each under its own license.",
|
||||
kind: .prose),
|
||||
]
|
||||
for (i, chunk) in Licenses.chunked(Licenses.appLicense).enumerated() {
|
||||
list.append(aboutText(id: "lic-app-\(i)", label: chunk, kind: .prose))
|
||||
}
|
||||
list.append(aboutText(
|
||||
id: "lic-third-heading", label: "Third-party software", kind: .heading))
|
||||
for (i, chunk) in Licenses.thirdPartyNoticesChunks.enumerated() {
|
||||
list.append(aboutText(id: "lic-third-\(i)", label: chunk, kind: .prose))
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
private func aboutText(
|
||||
id: String, label: String, value: String = "", kind: Row.Kind
|
||||
) -> Row {
|
||||
Row(
|
||||
id: id, tab: .about, icon: "", label: label, value: value, detail: "",
|
||||
adjustable: false, enabled: true, kind: kind,
|
||||
adjust: { _ in false }, activate: {})
|
||||
}
|
||||
|
||||
/// Every row on the screen, tagged with its section. Built as one list (not per tab) so the
|
||||
/// platform-conditional insertions below can still place a row RELATIVE to another by id.
|
||||
private var allRows: [Row] {
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
// The in-session controls, written down once and read by every surface that shows them.
|
||||
//
|
||||
// This replaced the start-of-stream banner (ContentView's `showShortcutHint`): a 6-second pill
|
||||
// that told you the controls exactly once, while you were busy looking at the thing you had just
|
||||
// connected to, and then never again. A reference you can OPEN answers the question at the moment
|
||||
// it is actually asked — which is the second session, not the first.
|
||||
//
|
||||
// The catalog is data rather than a view so both About pages render the same words: the touch
|
||||
// `AboutView` (a Form) and the controller-first `GamepadAboutView` (a console list). The banner
|
||||
// was macOS/tvOS-only, so deleting it would have cost Mac TOUCH users the one place those keys
|
||||
// were written down — hence the touch surface gets this too, not just the gamepad UI.
|
||||
//
|
||||
// Per-platform by `#if`, because the honest answer really is different: tvOS has no keyboard and
|
||||
// no menu bar, iOS has a touch gesture nothing else has, and macOS is the only one that has to
|
||||
// explain mouse capture. A controller's chords are the one section common to all three — they are
|
||||
// the same buttons on every client (`GamepadCapture.escapeChord` / `.statsChord`), which is the
|
||||
// whole point of a cross-client chord.
|
||||
|
||||
import AVFoundation
|
||||
import PunktfunkKit
|
||||
import SwiftUI
|
||||
|
||||
/// One line of the reference: what you press, and what it does.
|
||||
struct ShortcutItem: Identifiable {
|
||||
/// Stable within its group — the keys are unique per group by construction.
|
||||
var id: String { keys }
|
||||
/// The chord itself, rendered monospaced so ⌃⌥⇧-style runs stay legible.
|
||||
let keys: String
|
||||
let text: String
|
||||
}
|
||||
|
||||
struct ShortcutGroup: Identifiable {
|
||||
var id: String { title }
|
||||
let title: String
|
||||
let items: [ShortcutItem]
|
||||
}
|
||||
|
||||
enum ShortcutsCatalog {
|
||||
/// Whether a mute key is worth listing when no session is running, for the About page reached
|
||||
/// from settings. `SessionModel.micAvailable` is the authority DURING a session — it also
|
||||
/// consults the profile the session actually resolved — but a reference page opened between
|
||||
/// sessions has no session to ask, so it answers the device-level half of the same question:
|
||||
/// a platform with an app-accessible input, the mic setting on, and the OS not refusing.
|
||||
/// `.notDetermined` counts, exactly as it does there: the prompt is simply still pending.
|
||||
static var micPlausible: Bool {
|
||||
#if os(tvOS)
|
||||
return false // no app-accessible microphone
|
||||
#else
|
||||
guard UserDefaults.standard.object(forKey: DefaultsKey.micEnabled) as? Bool ?? true
|
||||
else { return false }
|
||||
switch AVCaptureDevice.authorizationStatus(for: .audio) {
|
||||
case .authorized, .notDetermined: return true
|
||||
default: return false
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// `micAvailable` gates the mute row — a device with no microphone would otherwise be told
|
||||
/// about a key that does nothing, which is the failure the old banner already avoided.
|
||||
static func groups(micAvailable: Bool) -> [ShortcutGroup] {
|
||||
var groups: [ShortcutGroup] = []
|
||||
#if os(macOS)
|
||||
var keyboard: [ShortcutItem] = [
|
||||
.init(keys: "Click", text: "Capture the mouse and keyboard for the stream"),
|
||||
.init(keys: "⌃⌥⇧Q", text: "Release the mouse and keyboard back to this Mac"),
|
||||
.init(keys: "⌃⌥⇧D", text: "Disconnect"),
|
||||
.init(keys: "⌃⌥⇧S", text: "Cycle the statistics overlay"),
|
||||
]
|
||||
if micAvailable {
|
||||
keyboard.append(.init(keys: "⌃⌥⇧A", text: "Mute or unmute the microphone"))
|
||||
}
|
||||
groups.append(.init(title: "Keyboard", items: keyboard))
|
||||
#elseif os(iOS)
|
||||
// iPad with a hardware keyboard gets the same cross-client set as the Mac (StreamCommands
|
||||
// publishes it either way); a phone simply never sees a keyboard to press it on.
|
||||
var keyboard: [ShortcutItem] = [
|
||||
.init(keys: "⌃⌥⇧Q", text: "Release the pointer back to this device"),
|
||||
.init(keys: "⌃⌥⇧D", text: "Disconnect"),
|
||||
.init(keys: "⌃⌥⇧S", text: "Cycle the statistics overlay"),
|
||||
]
|
||||
if micAvailable {
|
||||
keyboard.append(.init(keys: "⌃⌥⇧A", text: "Mute or unmute the microphone"))
|
||||
}
|
||||
groups.append(.init(title: "Hardware keyboard", items: keyboard))
|
||||
groups.append(.init(title: "Touch", items: [
|
||||
.init(keys: "Three-finger tap", text: "Cycle the statistics overlay"),
|
||||
]))
|
||||
#elseif os(tvOS)
|
||||
// The remote section leads on tvOS: it carries the ONLY exits. Menu/B is swallowed during
|
||||
// a session (ContentView's `.onExitCommand {}`), so a user who does not know the hold
|
||||
// gesture is genuinely stuck — which is why this was the one banner that could not simply
|
||||
// be deleted without putting the words somewhere findable first.
|
||||
groups.append(.init(title: "Siri Remote", items: [
|
||||
.init(keys: "Hold Back", text: "Disconnect"),
|
||||
.init(keys: "Touch surface", text: "Move the pointer"),
|
||||
.init(keys: "Press", text: "Click"),
|
||||
.init(keys: "Play/Pause", text: "Right-click"),
|
||||
.init(keys: "Hold Play/Pause", text: "Cycle the statistics overlay"),
|
||||
]))
|
||||
#endif
|
||||
// Every client's controller speaks these two chords — see GamepadCapture.escapeChord and
|
||||
// .statsChord, which a test pins against their GameController element lists.
|
||||
groups.append(.init(title: "Controller", items: [
|
||||
.init(keys: "L1 + R1 + Start + Select", text: "Hold to disconnect"),
|
||||
.init(keys: "Select + X", text: "Cycle the statistics overlay"),
|
||||
.init(keys: "Hold Select", text: "Press the host's guide button"),
|
||||
]))
|
||||
return groups
|
||||
}
|
||||
}
|
||||
|
||||
/// The standard-interface reference — a sheet from `AboutView` on iOS/macOS, a pushed page on
|
||||
/// tvOS — so the keys the start-of-stream banner used to carry are still one press away.
|
||||
/// (The controller-first surface renders the same catalog itself; see `GamepadAboutView`.)
|
||||
struct ShortcutsView: View {
|
||||
let micAvailable: Bool
|
||||
|
||||
var body: some View {
|
||||
#if os(tvOS)
|
||||
// No `Form`/`.formStyle(.grouped)` worth using at 10 feet, and the rows are read, not
|
||||
// operated — a plain scrolling column at TV sizes says the same thing with less chrome.
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 30) {
|
||||
ForEach(ShortcutsCatalog.groups(micAvailable: micAvailable)) { group in
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text(group.title)
|
||||
.font(.geist(28, .semibold, relativeTo: .headline))
|
||||
ForEach(group.items) { item in
|
||||
HStack(alignment: .firstTextBaseline, spacing: 20) {
|
||||
Text(item.keys)
|
||||
.font(.geistFixed(22, .medium))
|
||||
.frame(minWidth: 300, alignment: .leading)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
Text(item.text)
|
||||
.font(.geist(22, relativeTo: .caption))
|
||||
.foregroundStyle(.secondary)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: 1000, alignment: .leading)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(60)
|
||||
}
|
||||
.navigationTitle("Shortcuts")
|
||||
#else
|
||||
form
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !os(tvOS)
|
||||
private var form: some View {
|
||||
Form {
|
||||
ForEach(ShortcutsCatalog.groups(micAvailable: micAvailable)) { group in
|
||||
Section(group.title) {
|
||||
ForEach(group.items) { item in
|
||||
HStack(alignment: .firstTextBaseline, spacing: 12) {
|
||||
Text(item.keys)
|
||||
.font(.geistFixed(13, .medium))
|
||||
.foregroundStyle(.primary)
|
||||
// A fixed column keeps the descriptions aligned; the chords vary
|
||||
// from "Click" to "L1 + R1 + Start + Select".
|
||||
.frame(minWidth: 132, alignment: .leading)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
Text(item.text)
|
||||
.font(.geist(13, relativeTo: .footnote))
|
||||
.foregroundStyle(.secondary)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
.padding(.vertical, 2)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
.navigationTitle("Shortcuts")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -18,7 +18,10 @@ import SwiftUI
|
||||
#if os(iOS) || os(macOS)
|
||||
|
||||
struct GamepadPairView: View {
|
||||
@Environment(\.gamepadInk) private var ink
|
||||
/// Resolved from the stored palette, NOT from `\.gamepadInk` — this screen publishes that
|
||||
/// value itself and so sits above its own copy (see `GamepadInk.stored`).
|
||||
@AppStorage(DefaultsKey.uiPalette) private var paletteID = "violet"
|
||||
private var ink: GamepadInk { .stored(paletteID) }
|
||||
@Environment(\.gamepadMetrics) private var metrics
|
||||
@Environment(\.displayBottomInset) private var displayBottomInset
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
|
||||
@@ -32,8 +32,11 @@ final class AudioDeviceWatcher {
|
||||
/// posts one last change as it is torn down, and other AVAudioEngines in the process are not
|
||||
/// ours to restart.
|
||||
private let isOurs: (AnyObject?) -> Bool
|
||||
/// Delivered on the main queue.
|
||||
private let onChange: (Reason) -> Void
|
||||
/// Delivered on the main queue. The second argument is the engine that posted the change
|
||||
/// (`.engineConfiguration` only; nil for the HAL listener) — the owner needs the OBJECT, not
|
||||
/// just the reason, because an engine that is RUNNING when the notification lands is one the
|
||||
/// owner already restarted: acting on that echo is how a rebuild loop starts.
|
||||
private let onChange: (Reason, AnyObject?) -> Void
|
||||
|
||||
private let lock = NSLock()
|
||||
private var configObserver: NSObjectProtocol?
|
||||
@@ -41,7 +44,7 @@ final class AudioDeviceWatcher {
|
||||
private var defaultOutputListener: AudioObjectPropertyListenerBlock?
|
||||
#endif
|
||||
|
||||
init(isOurs: @escaping (AnyObject?) -> Bool, onChange: @escaping (Reason) -> Void) {
|
||||
init(isOurs: @escaping (AnyObject?) -> Bool, onChange: @escaping (Reason, AnyObject?) -> Void) {
|
||||
self.isOurs = isOurs
|
||||
self.onChange = onChange
|
||||
}
|
||||
@@ -63,7 +66,7 @@ final class AudioDeviceWatcher {
|
||||
let posted = note.object as AnyObject?
|
||||
DispatchQueue.main.async {
|
||||
guard let self, self.isOurs(posted) else { return }
|
||||
self.onChange(.engineConfiguration)
|
||||
self.onChange(.engineConfiguration, posted)
|
||||
}
|
||||
}
|
||||
lock.lock()
|
||||
@@ -77,7 +80,8 @@ final class AudioDeviceWatcher {
|
||||
// (the voice-processing engine, which is the DEFAULT macOS configuration and which no Mac
|
||||
// here can even initialize). The HAL is told either way.
|
||||
let block: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
|
||||
self?.onChange(.defaultOutputDevice) // on the main queue — registered against it below
|
||||
// On the main queue — registered against it below. No engine posted this, so nil.
|
||||
self?.onChange(.defaultOutputDevice, nil)
|
||||
}
|
||||
var address = Self.defaultOutputAddress()
|
||||
let status = AudioObjectAddPropertyListenerBlock(
|
||||
|
||||
@@ -42,7 +42,10 @@ public enum AudioDevices {
|
||||
return channelCount(id, scope: kAudioObjectPropertyScopeInput)
|
||||
}
|
||||
|
||||
private static func defaultInputDevice() -> AudioDeviceID? {
|
||||
/// The device the system is currently capturing from — the key `SessionAudio`'s
|
||||
/// voice-processing gate latches a start failure against (the failure is a property of the
|
||||
/// input device, so a new device earns a fresh attempt).
|
||||
static func defaultInputDevice() -> AudioDeviceID? {
|
||||
systemDevice(kAudioHardwarePropertyDefaultInputDevice)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
// The two policy decisions of the device-change recovery, extracted where a unit test can reach
|
||||
// them. Both exist because of one field incident (2026-08-14, Mac Studio): the voice-processing
|
||||
// engine could not start on a 6-channel input device, every rebuild re-tried it, and the failed
|
||||
// attempt's HAL churn (VPIO builds and tears down an aggregate device) re-stopped the fallback
|
||||
// engines — which posted the configuration change that scheduled the next rebuild. A ~2.5 s
|
||||
// metronome of audio gaps, forever, with each rebuild also stalling the main thread (where macOS
|
||||
// input capture lives), so the stream's INPUT cut out on the same beat. The session-side wiring
|
||||
// lives in `SessionAudio`; the decisions live here because the loop shipped precisely because
|
||||
// they could not be tested without a mic and a session.
|
||||
|
||||
#if os(macOS)
|
||||
import CoreAudio
|
||||
#endif
|
||||
import Foundation
|
||||
|
||||
#if os(macOS)
|
||||
/// Should a rebuild try the combined (voice-processing) topology again?
|
||||
///
|
||||
/// A VPIO start failure is a property of the INPUT DEVICE (its channel count and format), not of
|
||||
/// the moment: retrying it on the same device fails the same way, and the attempt is not free —
|
||||
/// engaging and abandoning the voice processor churns the HAL hard enough to stop the healthy
|
||||
/// fallback engines. So a failure latches until the default input actually changes; a new device
|
||||
/// earns exactly one fresh attempt (it may well support VPIO), and its own failure latches again.
|
||||
struct CombinedTopologyGate {
|
||||
private var failed = false
|
||||
/// The default input device the failure was observed on — nil is a real value here ("failed
|
||||
/// with no resolvable input device"), which is why `failed` is tracked separately.
|
||||
private var failedInput: AudioDeviceID?
|
||||
|
||||
/// The combined topology failed with `input` as the default input device.
|
||||
mutating func noteFailure(input: AudioDeviceID?) {
|
||||
failed = true
|
||||
failedInput = input
|
||||
}
|
||||
|
||||
/// True when the combined topology is worth attempting with `input` as the default input
|
||||
/// device. A device change clears the latch — the answer is about the CURRENT hardware, and
|
||||
/// coming back to a device that failed before earns a fresh attempt too (the failure may have
|
||||
/// been the mid-transition kind, and one attempt per device change cannot loop).
|
||||
mutating func shouldTry(input: AudioDeviceID?) -> Bool {
|
||||
guard failed else { return true }
|
||||
guard input == failedInput else {
|
||||
failed = false
|
||||
failedInput = nil
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// The delay before the next engine rebuild — the base debounce/floor behaviour, plus an
|
||||
/// escalating floor when rebuilds CHAIN (each one retriggered by its predecessor's own fallout).
|
||||
///
|
||||
/// One device switch produces one rebuild: its trigger burst is coalesced upstream, so the next
|
||||
/// trigger normally arrives minutes later and gets the base floor. A trigger that arrives hard on
|
||||
/// the heels of the last rebuild, again and again, is a rebuild answering itself — and since the
|
||||
/// recovery cannot always identify its own echo, the backstop is to keep answering but at a
|
||||
/// doubling floor, so an unforeseen feedback shape costs one audio blip per half-minute instead
|
||||
/// of a metronome. A quiet stretch resets the ladder to full responsiveness.
|
||||
struct RebuildBackoff {
|
||||
/// Let the burst of triggers from one switch land before rebuilding.
|
||||
static let debounce: TimeInterval = 0.15
|
||||
/// Floor between two rebuilds.
|
||||
static let floor: TimeInterval = 0.5
|
||||
/// The escalated floor's cap: looping recoveries settle at one attempt per this interval.
|
||||
static let floorCap: TimeInterval = 30
|
||||
/// A trigger this long after the last rebuild is unrelated to it — the chain resets.
|
||||
static let chainWindow: TimeInterval = 10
|
||||
|
||||
/// Consecutive rebuilds whose trigger arrived within `chainWindow` of the previous rebuild.
|
||||
private(set) var chain = 0
|
||||
private var lastRebuildAt: TimeInterval = -.infinity
|
||||
|
||||
/// The delay to schedule the next rebuild with, for a trigger arriving at `now`
|
||||
/// (`systemUptime`). Mutates the chain accounting: call once per SCHEDULED rebuild, not per
|
||||
/// coalesced trigger.
|
||||
mutating func delay(now: TimeInterval) -> TimeInterval {
|
||||
let since = now - lastRebuildAt
|
||||
chain = since < Self.chainWindow ? chain + 1 : 0
|
||||
let floor = min(Self.floor * pow(2, Double(min(chain, 6))), Self.floorCap)
|
||||
return max(Self.debounce, floor - since)
|
||||
}
|
||||
|
||||
/// The rebuild actually ran at `now` — the reference the next trigger's `delay` measures from.
|
||||
mutating func noteRebuild(at now: TimeInterval) {
|
||||
lastRebuildAt = now
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,18 @@ final class AudioRing: @unchecked Sendable {
|
||||
private static let maxTargetMS = 70
|
||||
private static let headroomMS = 30
|
||||
private static let hardCapMS = 90
|
||||
private static let deprimeAfter = 4
|
||||
/// How long the ring may run short before it goes back to priming, in MILLISECONDS of
|
||||
/// starvation — not a count of callbacks. As a count (it was 4) the hysteresis meant a
|
||||
/// different span of time on every device, because a callback is not a unit of time: 4 of them
|
||||
/// is ~44 ms on a Mac's ~11 ms quantum and **20 ms on iOS**, whose session asks for a short IO
|
||||
/// buffer. A Wi-Fi delivery stall therefore de-primed this ring on every bunching cycle where
|
||||
/// the same policy rode it out elsewhere — measured on the shared Rust policy at 120 audible
|
||||
/// gaps per 10 minutes at a 5 ms quantum, against 3 at 8 ms and 1 at 16 ms on an identical
|
||||
/// link. Mirrors `JitterTuning::COREAUDIO.deprime_ms`.
|
||||
private static let deprimeMS = 60
|
||||
/// Floor in callbacks under `deprimeMS`, so a large-quantum device keeps real hysteresis
|
||||
/// instead of de-priming on the first short read. Mirrors `MIN_DEPRIME_CALLBACKS`.
|
||||
private static let minDeprimeCallbacks = 2
|
||||
/// The protocol's frame: the shed unit, and the slack added over a large device quantum.
|
||||
private static let frameMS = 5
|
||||
/// Depth average must exceed target by this before drift correction fires — the middle of the
|
||||
@@ -93,7 +104,12 @@ final class AudioRing: @unchecked Sendable {
|
||||
private var writeIdx = 0
|
||||
private var primed = false
|
||||
private var renderQuantum = 0
|
||||
/// Consecutive short reads, and the audio they starved for in interleaved samples. BOTH gate
|
||||
/// the de-prime (see `deprimeMS`): the run must be at least that long AND at least
|
||||
/// `minDeprimeCallbacks` callbacks, so the fuse is the same span of time whatever the device's
|
||||
/// quantum without collapsing to a hair trigger on a large-quantum device.
|
||||
private var emptyReads = 0
|
||||
private var emptyRun = 0
|
||||
private var depthAvg: Double = 0
|
||||
private var overRun = 0
|
||||
/// The live target in interleaved samples — `targetMS` grown by underrun pressure
|
||||
@@ -240,8 +256,10 @@ final class AudioRing: @unchecked Sendable {
|
||||
min(target + Self.headroomMS * perMS, Self.hardCapMS * perMS),
|
||||
target + renderQuantum)
|
||||
if writeIdx - readIdx > cap {
|
||||
readIdx = writeIdx - cap
|
||||
depthAvg = Double(cap)
|
||||
// Crossfaded, like the smooth shed — see `dropFront`. This is the correction a
|
||||
// bunching link actually pays, so it is the one that most needs not to click.
|
||||
dropFront(writeIdx - readIdx - cap)
|
||||
depthAvg = Double(writeIdx - readIdx)
|
||||
overRun = 0
|
||||
}
|
||||
}
|
||||
@@ -262,6 +280,7 @@ final class AudioRing: @unchecked Sendable {
|
||||
if available >= target {
|
||||
primed = true
|
||||
emptyReads = 0
|
||||
emptyRun = 0
|
||||
// The refill just banked this much: seed the average with it rather than letting
|
||||
// it climb from wherever the drought left it — a freshly-primed ring would
|
||||
// otherwise read as hollow for the EWMA's whole settling time, and the FIRST
|
||||
@@ -348,15 +367,23 @@ final class AudioRing: @unchecked Sendable {
|
||||
if ranShort {
|
||||
quietRun = 0
|
||||
emptyReads += 1
|
||||
emptyRun += count
|
||||
underrunCount += 1
|
||||
if emptyReads >= Self.deprimeAfter || hollow {
|
||||
// The consecutive-empties hysteresis protects a FULL ring from one late packet.
|
||||
// Starved for `deprimeMS` of audio, over at least `minDeprimeCallbacks` callbacks.
|
||||
// Both, because either alone is wrong at one end of the quantum range: time alone is a
|
||||
// hair trigger on a device whose single quantum already exceeds the window, and a
|
||||
// callback count alone is the device-dependent fuse this replaced.
|
||||
let starved = emptyRun >= Self.deprimeMS * perMS
|
||||
&& emptyReads >= Self.minDeprimeCallbacks
|
||||
if starved || hollow {
|
||||
// The starvation hysteresis protects a FULL ring from one late packet.
|
||||
// A hollow ring is the opposite case: the target has been raised but the depth
|
||||
// never re-banked (growth is a promise; only a re-prime cashes it), and riding
|
||||
// that out is a click per bunching period, forever. The click just heard has
|
||||
// already paid for the refill — take it now.
|
||||
primed = false
|
||||
emptyReads = 0
|
||||
emptyRun = 0
|
||||
}
|
||||
if !restored {
|
||||
underrunsInWindow += 1
|
||||
@@ -375,12 +402,14 @@ final class AudioRing: @unchecked Sendable {
|
||||
// the path above takes over. A near-miss is pressure, not quiet.
|
||||
quietRun = 0
|
||||
emptyReads = 0
|
||||
emptyRun = 0
|
||||
if !nearMissGrown, !restored {
|
||||
nearMissGrown = true
|
||||
targetLive = min(targetLive + Self.growStepMS * perMS, Self.maxTargetMS * perMS)
|
||||
}
|
||||
} else {
|
||||
emptyReads = 0
|
||||
emptyRun = 0
|
||||
quietRun += count
|
||||
// Without a sync request, time is the only evidence that hard-won slack is no longer
|
||||
// needed, so a grown target waits out the long window. A request for less IS evidence,
|
||||
@@ -402,13 +431,21 @@ final class AudioRing: @unchecked Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop one protocol frame from the front, linearly crossfading the seam so the correction is
|
||||
/// inaudible rather than a click. Mirrors `punktfunk_core::audio::crossfade_drop`; caller holds
|
||||
/// the lock.
|
||||
private func shedOneFrame() {
|
||||
let drop = Self.frameMS * perMS
|
||||
/// Drop one protocol frame from the front — the smooth drift correction.
|
||||
private func shedOneFrame() { dropFront(Self.frameMS * perMS) }
|
||||
|
||||
/// Drop `drop` interleaved samples from the front, linearly crossfading the seam so the
|
||||
/// correction is inaudible rather than a click. Mirrors `punktfunk_core::audio::crossfade_drop`;
|
||||
/// caller holds the lock.
|
||||
///
|
||||
/// Used by BOTH corrections. The hard-cap trim in `write` used to splice raw, on the reasoning
|
||||
/// that a ring which blew its ceiling is already a discontinuity — but that describes the
|
||||
/// ARRIVALS, not the samples either side of the seam, which are ordinary continuous audio. It
|
||||
/// is also the drop that actually fires here: a bunching Wi-Fi link trims far more often than
|
||||
/// drift sheds, so the one path left unfaded was the audible one.
|
||||
private func dropFront(_ drop: Int) {
|
||||
let available = writeIdx - readIdx
|
||||
guard available > drop else { return }
|
||||
guard drop > 0, available > drop else { return }
|
||||
let fade = min(Self.crossfadeMS * perMS, min(drop, available - drop))
|
||||
let capacity = buf.count
|
||||
if fade > 0 {
|
||||
|
||||
@@ -63,15 +63,24 @@ public final class SessionAudio {
|
||||
private var micMuted = false
|
||||
/// The playback jitter ring — created by whichever engine starts playback first and KEPT
|
||||
/// across an engine rebuild (the permission-grant upgrade in `startEngines` swaps engines,
|
||||
/// not the ring, so the drain thread never has to be re-pointed). Main-thread confined,
|
||||
/// like every start path.
|
||||
/// not the ring, so the drain thread never has to be re-pointed). Guarded by `stateLock`:
|
||||
/// the start paths run on `engineQueue`, while `stats` reads from the main thread.
|
||||
private var ring: AudioRing?
|
||||
/// Every engine build, start, stop and rebuild runs here, serially — and NOT on the main
|
||||
/// thread. macOS captures and sends input from the main thread, so the seconds a
|
||||
/// voice-processing start can take (~1.9 s measured in the 2026-08-14 field loop) would
|
||||
/// freeze the stream's input for exactly that long — the recovery must never make the main
|
||||
/// thread wait on the audio server. The main queue keeps only the trigger bookkeeping
|
||||
/// (debounce, backoff, retry ladder), which is cheap by construction.
|
||||
private let engineQueue = DispatchQueue(
|
||||
label: "io.unom.punktfunk.audio.engines", qos: .userInitiated)
|
||||
/// The video plane's end-to-end meter (capture→on-glass), if the owner wired one — the
|
||||
/// reference the A/V sync loop steers the ring against. `nil` leaves the loop inert and the
|
||||
/// ring exactly as it was before sync existed, which is also what the stage-1 fallback
|
||||
/// presenter gets: it decodes and presents inside the layer with no per-frame stamp, so it can
|
||||
/// offer no reference, and a loop with no reference must not invent one. Main-thread confined,
|
||||
/// like `ring`; the meter itself is internally locked and read from the drain thread.
|
||||
/// offer no reference, and a loop with no reference must not invent one. Written ONCE in
|
||||
/// `start()` before anything is dispatched (the queue hop orders it for `startDrain`); the
|
||||
/// meter itself is internally locked and read from the drain thread.
|
||||
private var videoLatency: LatencyMeter?
|
||||
#if !os(macOS)
|
||||
/// AVAudioSession `setCategory`/`setActive` are synchronous and block on the audio server, so
|
||||
@@ -99,7 +108,8 @@ public final class SessionAudio {
|
||||
// MARK: - Device changes (see `installDeviceChangeRecovery`)
|
||||
|
||||
/// What `start()` was asked for, so a rebuild can put back the SAME topology the session was
|
||||
/// started with. Main-thread confined, like the start paths that read it.
|
||||
/// started with. Guarded by `stateLock` (written on the caller's thread, read when a rebuild
|
||||
/// fires on the main queue).
|
||||
private var startConfig: StartConfig?
|
||||
private struct StartConfig {
|
||||
let speakerUID: String
|
||||
@@ -110,20 +120,23 @@ public final class SessionAudio {
|
||||
}
|
||||
/// Watches the hardware for us (see `AudioDeviceWatcher`). Guarded by `stateLock`.
|
||||
private var deviceWatcher: AudioDeviceWatcher?
|
||||
/// Whether the engines have been built at least once. Distinguishes "not started yet" (iOS
|
||||
/// starts asynchronously) from "started and dead", which is what the recovery may act on.
|
||||
/// Main-thread confined.
|
||||
/// Whether the engines have been built at least once. Distinguishes "not started yet" (every
|
||||
/// platform starts asynchronously now) from "started and dead", which is what the recovery
|
||||
/// may act on. Guarded by `stateLock` (set on `engineQueue`, read on the main queue).
|
||||
private var enginesAttempted = false
|
||||
/// A rebuild is already on the main queue — one device switch produces a burst of triggers
|
||||
/// and they must collapse into one restart. Main-thread confined.
|
||||
private var rebuildQueued = false
|
||||
/// `systemUptime` of the last rebuild, so a device that renegotiates in a loop cannot spin
|
||||
/// the session. Main-thread confined.
|
||||
private var lastRebuildAt: TimeInterval = 0
|
||||
/// Let the burst of triggers from one switch land before rebuilding.
|
||||
private static let rebuildDebounce: TimeInterval = 0.15
|
||||
/// Floor between two rebuilds.
|
||||
private static let rebuildFloor: TimeInterval = 0.5
|
||||
/// Debounce/floor for the next rebuild, with an escalating floor when rebuilds chain (each
|
||||
/// retriggered by its predecessor — see `RebuildBackoff`). Main-thread confined.
|
||||
private var rebuildBackoff = RebuildBackoff()
|
||||
#if os(macOS)
|
||||
/// Latches a voice-processing start failure per input device, so a rebuild never re-attempts
|
||||
/// a topology that deterministically fails — the retry is what turned one failure into a
|
||||
/// rebuild loop (see `CombinedTopologyGate` and the note on `installDeviceChangeRecovery`).
|
||||
/// `engineQueue`-confined, like the start paths that consult and feed it.
|
||||
private var combinedGate = CombinedTopologyGate()
|
||||
#endif
|
||||
/// Retries when a rebuild's `start()` loses the race with a device that is still going away
|
||||
/// (0.3 s, 0.6 s, 1.2 s). A failed rebuild leaves no engine to post the next notification,
|
||||
/// so this ladder — and, on macOS, the HAL listener — is all that stands between a mistimed
|
||||
@@ -151,11 +164,12 @@ public final class SessionAudio {
|
||||
}
|
||||
|
||||
/// Start playback (and, if enabled+authorized, the mic uplink). Empty UIDs = system default
|
||||
/// device; on iOS the UIDs are ignored entirely (routes are AVAudioSession-managed). On macOS
|
||||
/// the engines start synchronously on the caller's (main) thread. On iOS/tvOS start() is
|
||||
/// ASYNCHRONOUS: it activates the AVAudioSession off the main thread, then starts the engines on
|
||||
/// a later main-queue hop (gated by `!flag.isStopped`) — so playback is live shortly after, not
|
||||
/// on return. The mic may start later still if the permission prompt is pending.
|
||||
/// device; on iOS the UIDs are ignored entirely (routes are AVAudioSession-managed).
|
||||
/// ASYNCHRONOUS on every platform: the engines start on `engineQueue` (iOS/tvOS activate the
|
||||
/// AVAudioSession off the main thread first), gated by `!flag.isStopped` — so playback is
|
||||
/// live shortly after, not on return. An engine start can block on the audio server for
|
||||
/// seconds, and the caller's (main) thread is where macOS input capture lives — it must
|
||||
/// never wait. The mic may start later still if the permission prompt is pending.
|
||||
/// `echoCancel` picks the engine topology — see the header note and `wantsCombined`.
|
||||
///
|
||||
/// `videoLatency` is the session's END-TO-END latency meter (capture→on-glass). Pass it to arm
|
||||
@@ -166,26 +180,33 @@ public final class SessionAudio {
|
||||
speakerUID: String, micUID: String, micChannel: Int, micEnabled: Bool, echoCancel: Bool,
|
||||
videoLatency: LatencyMeter? = nil
|
||||
) {
|
||||
self.videoLatency = videoLatency
|
||||
self.videoLatency = videoLatency // before any dispatch below — startDrain reads it
|
||||
// Before any engine exists: the recovery watches the hardware, not the engines, and the
|
||||
// config it rebuilds from has to be recorded whether or not this start succeeds.
|
||||
stateLock.lock()
|
||||
startConfig = StartConfig(
|
||||
speakerUID: speakerUID, micUID: micUID, micChannel: micChannel,
|
||||
micEnabled: micEnabled, echoCancel: echoCancel)
|
||||
stateLock.unlock()
|
||||
installDeviceChangeRecovery(micEnabled: micEnabled)
|
||||
#if os(macOS)
|
||||
// No AVAudioSession on macOS — start the engines directly (caller's thread, as before).
|
||||
startEngines(
|
||||
speakerUID: speakerUID, micUID: micUID, micChannel: micChannel,
|
||||
micEnabled: micEnabled, echoCancel: echoCancel)
|
||||
// No AVAudioSession on macOS — but the engines start on `engineQueue`, never the
|
||||
// caller's (main) thread: a voice-processing start can block on the audio server for
|
||||
// seconds, and the main thread is where input capture lives.
|
||||
engineQueue.async { [weak self] in
|
||||
guard let self, !self.flag.isStopped else { return }
|
||||
self.startEngines(
|
||||
speakerUID: speakerUID, micUID: micUID, micChannel: micChannel,
|
||||
micEnabled: micEnabled, echoCancel: echoCancel)
|
||||
}
|
||||
#else
|
||||
// Configure + activate the session OFF the main thread (it blocks on the audio server),
|
||||
// then start the engines back on the main thread once it's active — engine routing/format
|
||||
// then start the engines on `engineQueue` once it's active — engine routing/format
|
||||
// depend on the active session. A stop() racing in between is caught by the flag guard.
|
||||
Self.sessionQueue.async { [weak self] in
|
||||
guard let self else { return }
|
||||
self.activateAudioSession(micEnabled: micEnabled)
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self.engineQueue.async { [weak self] in
|
||||
guard let self, !self.flag.isStopped else { return }
|
||||
self.startEngines(
|
||||
speakerUID: speakerUID, micUID: micUID, micChannel: micChannel,
|
||||
@@ -234,11 +255,23 @@ public final class SessionAudio {
|
||||
try session.setCategory(
|
||||
.playAndRecord, mode: .default,
|
||||
options: [.allowBluetoothA2DP, .mixWithOthers])
|
||||
// Uplink latency: ask for 5 ms IO quanta at the wire rate (the default ~10-23 ms
|
||||
// Uplink latency: ask for 10 ms IO quanta at the wire rate (the default ~23 ms
|
||||
// quantum is most of the mic path's burst latency). Best-effort — the hardware
|
||||
// has the final word (a Bluetooth route will ignore both), and whatever quantum
|
||||
// is actually granted, the capture tap handles the buffers it gets.
|
||||
try? session.setPreferredIOBufferDuration(0.005)
|
||||
//
|
||||
// 10 ms, NOT the 5 ms this used to ask for. The IO buffer duration is a property
|
||||
// of the whole IO unit, so a shorter quantum is not free to the PLAYBACK side —
|
||||
// and it bought the uplink nothing, because the encoder frames at 10 ms
|
||||
// (`installMicTap` installs with `bufferSize: 480` and `OpusEncoder` consumes
|
||||
// whole `framesPerPacket` chunks): at a 5 ms quantum the tap simply fired twice
|
||||
// per packet, for the same packet latency. What it did buy was a halved deadline
|
||||
// for the render callback and — because the de-prime fuse used to be a callback
|
||||
// COUNT — half the starvation hysteresis in the jitter ring, on the one platform
|
||||
// whose transport bunches hardest. Both ends of that are fixed now (`AudioRing`
|
||||
// measures the fuse in ms), but there is still no reason to ask for a quantum
|
||||
// finer than the packets we send.
|
||||
try? session.setPreferredIOBufferDuration(0.010)
|
||||
try? session.setPreferredSampleRate(48_000)
|
||||
} else {
|
||||
try session.setCategory(.playback, mode: .default, options: [.mixWithOthers])
|
||||
@@ -247,6 +280,16 @@ public final class SessionAudio {
|
||||
try session.setCategory(.playback, mode: .default, options: [.mixWithOthers])
|
||||
#endif
|
||||
try session.setActive(true)
|
||||
// What we were actually GRANTED, not what we asked for. Both are best-effort, and the
|
||||
// ring's behaviour depends on the quantum it really gets — without this, a report of
|
||||
// audio jitter arrives with no way to tell a 10 ms session from a 5 ms or a 23 ms one,
|
||||
// which is exactly the gap that made the last round of this take a simulation to close.
|
||||
log.info("""
|
||||
AVAudioSession active: io_buffer_ms=\
|
||||
\(session.ioBufferDuration * 1000, format: .fixed(precision: 2)) \
|
||||
sample_rate=\(Int(session.sampleRate)) \
|
||||
route=\(session.currentRoute.outputs.first?.portType.rawValue ?? "none")
|
||||
""")
|
||||
#if os(iOS)
|
||||
// Only the `.playAndRecord` session can land on the earpiece, and only it accepts an
|
||||
// output override — so the mic-off (`.playback`) path deliberately does neither.
|
||||
@@ -320,12 +363,15 @@ public final class SessionAudio {
|
||||
#endif
|
||||
|
||||
/// Build + start the engines — combined (voice-processed) or split, per `wantsCombined` —
|
||||
/// with the mic uplink only when enabled + authorized. Main thread (engine setup); on
|
||||
/// iOS/tvOS the session is already active by the time this runs.
|
||||
/// with the mic uplink only when enabled + authorized. Runs on `engineQueue` (a start can
|
||||
/// block on the audio server for seconds — never the main thread); on iOS/tvOS the session
|
||||
/// is already active by the time this runs.
|
||||
private func startEngines(
|
||||
speakerUID: String, micUID: String, micChannel: Int, micEnabled: Bool, echoCancel: Bool
|
||||
) {
|
||||
stateLock.lock()
|
||||
enginesAttempted = true // even if every path below fails — see `reviveStoppedEngines`
|
||||
stateLock.unlock()
|
||||
#if os(tvOS)
|
||||
// No app-accessible microphone input on tvOS — playback only.
|
||||
startPlayback(speakerUID: speakerUID)
|
||||
@@ -334,9 +380,25 @@ public final class SessionAudio {
|
||||
startPlayback(speakerUID: speakerUID)
|
||||
return
|
||||
}
|
||||
#if os(macOS)
|
||||
// A rebuild must not re-attempt a voice-processing start that already failed on this
|
||||
// input device: the failure repeats, and the failed attempt's HAL churn stops the healthy
|
||||
// fallback engines — the 2026-08-14 rebuild loop (see `CombinedTopologyGate`).
|
||||
var combined = wantsCombined(
|
||||
speakerUID: speakerUID, micUID: micUID, micChannel: micChannel,
|
||||
echoCancel: echoCancel)
|
||||
if combined, !combinedGate.shouldTry(input: AudioDevices.defaultInputDevice()) {
|
||||
log.info("""
|
||||
voice processing already failed on this input device — split engines, no echo \
|
||||
cancellation
|
||||
""")
|
||||
combined = false
|
||||
}
|
||||
#else
|
||||
let combined = wantsCombined(
|
||||
speakerUID: speakerUID, micUID: micUID, micChannel: micChannel,
|
||||
echoCancel: echoCancel)
|
||||
#endif
|
||||
switch AVCaptureDevice.authorizationStatus(for: .audio) {
|
||||
case .authorized:
|
||||
if combined {
|
||||
@@ -352,7 +414,8 @@ public final class SessionAudio {
|
||||
// drain thread carry over — see `makePlaybackChain`).
|
||||
startPlayback(speakerUID: speakerUID)
|
||||
AVCaptureDevice.requestAccess(for: .audio) { [weak self] granted in
|
||||
DispatchQueue.main.async {
|
||||
guard let self else { return }
|
||||
self.engineQueue.async { [weak self] in
|
||||
guard let self, granted, !self.flag.isStopped else { return }
|
||||
if combined {
|
||||
self.stateLock.lock()
|
||||
@@ -491,6 +554,17 @@ public final class SessionAudio {
|
||||
/// - the route-change and media-services-reset notifications, iOS/tvOS, where the session and
|
||||
/// not the device is what moves.
|
||||
///
|
||||
/// And three defenses keep the recovery from ANSWERING ITSELF — a rebuild is not a silent
|
||||
/// act (a voice-processing start builds and tears down HAL aggregates, and every fresh engine
|
||||
/// renegotiates its IO), so its own fallout can retrigger it. The 2026-08-14 field loop was
|
||||
/// exactly that: VPIO failed on a 6-channel mic, every rebuild re-tried it, and the failure's
|
||||
/// churn stopped the fallback engines — audio and (via the main thread) INPUT cutting out
|
||||
/// every ~2.5 s for the whole session. The defenses: a configuration change from an engine
|
||||
/// that is RUNNING is a rebuild's echo and is ignored (`hardwareMoved`); a VPIO failure is
|
||||
/// latched per input device and never re-attempted on it (`CombinedTopologyGate`); and
|
||||
/// rebuilds that chain anyway back off exponentially instead of metronoming
|
||||
/// (`RebuildBackoff`).
|
||||
///
|
||||
/// `micEnabled` only decides whether the mic-bearing session observers are worth installing.
|
||||
/// Main thread.
|
||||
private func installDeviceChangeRecovery(micEnabled: Bool) {
|
||||
@@ -501,7 +575,7 @@ public final class SessionAudio {
|
||||
|
||||
let watcher = AudioDeviceWatcher(
|
||||
isOurs: { [weak self] posted in self?.ownsEngine(posted) ?? false },
|
||||
onChange: { [weak self] reason in self?.hardwareMoved(reason) })
|
||||
onChange: { [weak self] reason, posted in self?.hardwareMoved(reason, posted: posted) })
|
||||
stateLock.lock()
|
||||
deviceWatcher = watcher
|
||||
stateLock.unlock()
|
||||
@@ -527,10 +601,17 @@ public final class SessionAudio {
|
||||
/// question — is playback still where it should be — but they answer it differently: an engine
|
||||
/// that told us it stopped is definitive, while the default device moving might not concern us
|
||||
/// at all.
|
||||
private func hardwareMoved(_ reason: AudioDeviceWatcher.Reason) {
|
||||
private func hardwareMoved(_ reason: AudioDeviceWatcher.Reason, posted: AnyObject?) {
|
||||
guard !flag.isStopped else { return }
|
||||
switch reason {
|
||||
case .engineConfiguration:
|
||||
// The engine stops itself BEFORE posting this — so an engine that is RUNNING when the
|
||||
// notification lands on the main queue is one a rebuild already replaced or restarted:
|
||||
// the notification is the rebuild's own echo, and answering it is how the recovery
|
||||
// loops. A change that stops the engine again after this posts again, and the HAL
|
||||
// backstop checks placement independently, so ignoring a live engine's echo can never
|
||||
// strand a stopped one.
|
||||
if let engine = posted as? AVAudioEngine, engine.isRunning { return }
|
||||
scheduleEngineRebuild(reason: reason.rawValue)
|
||||
case .defaultOutputDevice:
|
||||
#if os(macOS)
|
||||
@@ -550,7 +631,10 @@ public final class SessionAudio {
|
||||
/// output device at the moment it connected — and leaving it silent for good. On iOS the same
|
||||
/// flag keeps this from racing the asynchronous start, where no engine yet is normal.
|
||||
private func reviveStoppedEngines(_ reason: String) {
|
||||
guard !flag.isStopped, enginesAttempted, !playbackIsLive else { return }
|
||||
stateLock.lock()
|
||||
let attempted = enginesAttempted
|
||||
stateLock.unlock()
|
||||
guard !flag.isStopped, attempted, !playbackIsLive else { return }
|
||||
scheduleEngineRebuild(reason: "playback is stopped and \(reason)")
|
||||
}
|
||||
|
||||
@@ -572,15 +656,43 @@ public final class SessionAudio {
|
||||
private func scheduleEngineRebuild(reason: String) {
|
||||
guard !rebuildQueued else { return }
|
||||
rebuildQueued = true
|
||||
let since = ProcessInfo.processInfo.systemUptime - lastRebuildAt
|
||||
let delay = max(Self.rebuildDebounce, Self.rebuildFloor - since)
|
||||
log.info("\(reason) — restarting the audio engines in \(Int(delay * 1000)) ms")
|
||||
let delay = rebuildBackoff.delay(now: ProcessInfo.processInfo.systemUptime)
|
||||
if rebuildBackoff.chain >= 2 {
|
||||
// Each rebuild is retriggering the next — a feedback shape the echo guard and the
|
||||
// topology gate did not identify. Keep answering (a real recovery must not be
|
||||
// abandoned), but say what is happening: this line repeating IS the diagnosis.
|
||||
log.warning("""
|
||||
audio engine rebuilds are chaining (\(self.rebuildBackoff.chain) in a row — \
|
||||
\(reason)); backing off \(Int(delay * 1000)) ms
|
||||
""")
|
||||
} else {
|
||||
log.info("\(reason) — restarting the audio engines in \(Int(delay * 1000)) ms")
|
||||
}
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in
|
||||
self?.rebuildEngines(attempt: 0)
|
||||
self?.rebuildFire(attempt: 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The scheduled rebuild came due (main queue): close out the bookkeeping and hand the
|
||||
/// actual engine work to `engineQueue` — the teardown + start can block on the audio server
|
||||
/// for seconds, and the main thread is where macOS captures and sends the stream's input.
|
||||
/// A trigger arriving while the work is in flight schedules a fresh rebuild rather than
|
||||
/// being swallowed; `engineQueue` is serial, so the two never interleave.
|
||||
private func rebuildFire(attempt: Int) {
|
||||
rebuildQueued = false
|
||||
guard !flag.isStopped else { return }
|
||||
stateLock.lock()
|
||||
let config = startConfig
|
||||
stateLock.unlock()
|
||||
guard let config else { return }
|
||||
rebuildBackoff.noteRebuild(at: ProcessInfo.processInfo.systemUptime)
|
||||
engineQueue.async { [weak self] in
|
||||
self?.performRebuild(config: config, attempt: attempt)
|
||||
}
|
||||
}
|
||||
|
||||
/// Put back the topology this session was started with, on whatever hardware is there now.
|
||||
/// Runs on `engineQueue`.
|
||||
///
|
||||
/// A full rebuild rather than a `start()` on the stopped engine, because the mic side has to
|
||||
/// follow too: `installMicTap` reads the input's live format, and the voice processor
|
||||
@@ -588,10 +700,8 @@ public final class SessionAudio {
|
||||
/// across (`makePlaybackChain` reuses it, `startDrain` is idempotent), so the drain thread
|
||||
/// keeps decoding right through the switch and its overflow policy has already dropped
|
||||
/// everything that went stale while the engine was down.
|
||||
private func rebuildEngines(attempt: Int) {
|
||||
rebuildQueued = false
|
||||
guard !flag.isStopped, let config = startConfig else { return }
|
||||
lastRebuildAt = ProcessInfo.processInfo.systemUptime
|
||||
private func performRebuild(config: StartConfig, attempt: Int) {
|
||||
guard !flag.isStopped else { return }
|
||||
tearDownEngines()
|
||||
startEngines(
|
||||
speakerUID: config.speakerUID, micUID: config.micUID, micChannel: config.micChannel,
|
||||
@@ -604,6 +714,18 @@ public final class SessionAudio {
|
||||
log.info("audio engines restarted on the current device")
|
||||
return
|
||||
}
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.rebuildFailed(attempt: attempt)
|
||||
}
|
||||
}
|
||||
|
||||
/// A rebuild's playback did not come back (main queue) — walk the retry ladder. Retries
|
||||
/// when a rebuild's `start()` loses the race with a device that is still going away
|
||||
/// (0.3 s, 0.6 s, 1.2 s): a failed rebuild leaves no engine to post the next notification,
|
||||
/// so this ladder — and, on macOS, the HAL listener — is all that stands between a mistimed
|
||||
/// switch and a silent session.
|
||||
private func rebuildFailed(attempt: Int) {
|
||||
guard !flag.isStopped else { return }
|
||||
guard attempt < Self.rebuildAttempts else {
|
||||
#if os(macOS)
|
||||
log.error("""
|
||||
@@ -615,10 +737,11 @@ public final class SessionAudio {
|
||||
#endif
|
||||
return
|
||||
}
|
||||
guard !rebuildQueued else { return } // a fresh trigger already queued a full rebuild
|
||||
rebuildQueued = true // holds off a trigger that would only race this ladder
|
||||
let delay = Self.rebuildDebounce * Double(1 << (attempt + 1))
|
||||
let delay = RebuildBackoff.debounce * Double(1 << (attempt + 1))
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in
|
||||
self?.rebuildEngines(attempt: attempt + 1)
|
||||
self?.rebuildFire(attempt: attempt + 1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -764,9 +887,13 @@ public final class SessionAudio {
|
||||
public let avOffsetMS: Int
|
||||
}
|
||||
|
||||
/// A snapshot of `Stats`, or nil before playback starts. Main thread (`ring` is main-confined;
|
||||
/// the ring's own numbers are taken under its lock, so they describe one instant).
|
||||
/// A snapshot of `Stats`, or nil before playback starts. Safe from any thread (the handle is
|
||||
/// taken under `stateLock`; the ring's own numbers are taken under its lock, so they
|
||||
/// describe one instant).
|
||||
public var stats: Stats? {
|
||||
stateLock.lock()
|
||||
let ring = self.ring
|
||||
stateLock.unlock()
|
||||
guard let s = ring?.stats else { return nil }
|
||||
return Stats(bufferMS: s.bufferedMS, avOffsetMS: s.avOffsetMS)
|
||||
}
|
||||
@@ -791,7 +918,7 @@ public final class SessionAudio {
|
||||
/// The playback jitter ring + the source node draining it — shared by the plain playback
|
||||
/// engine and the combined voice-processing engine, and REUSED across an engine rebuild
|
||||
/// (same session, same ring: the drain thread keeps writing right through the swap). nil
|
||||
/// when the host's channel layout can't be expressed (already logged). Main thread.
|
||||
/// when the host's channel layout can't be expressed (already logged). Runs on `engineQueue`.
|
||||
private func makePlaybackChain()
|
||||
-> (ring: AudioRing, source: AVAudioSourceNode, format: AVAudioFormat)?
|
||||
{
|
||||
@@ -801,8 +928,10 @@ public final class SessionAudio {
|
||||
// 1 s interleaved capacity, scaled by the channel count. The de-jitter depth itself is
|
||||
// the ring's own business now (`AudioRing.targetMS`, mirroring `JitterTuning::COREAUDIO`)
|
||||
// rather than a prefill passed in here.
|
||||
stateLock.lock()
|
||||
let ring = self.ring ?? AudioRing(capacity: 48_000 * channels, channels: channels)
|
||||
self.ring = ring
|
||||
stateLock.unlock()
|
||||
|
||||
// Engine-native deinterleaved float; the render block deinterleaves from the ring. Surround
|
||||
// uses an explicit wire-order channel layout; the mixer downmixes to the output device when
|
||||
@@ -961,6 +1090,17 @@ public final class SessionAudio {
|
||||
// MARK: - Mic (mic → host)
|
||||
|
||||
#if !os(tvOS)
|
||||
/// The combined topology failed to come up. On macOS, latch the input device it failed on so
|
||||
/// a rebuild goes straight to the split topology instead of re-running the failure — the
|
||||
/// failed attempt is what churns the HAL and retriggers the recovery (see
|
||||
/// `CombinedTopologyGate`). On iOS routes are session-managed and a VPIO failure is the
|
||||
/// transient route-transition kind, so nothing is latched there.
|
||||
private func noteCombinedFailure() {
|
||||
#if os(macOS)
|
||||
combinedGate.noteFailure(input: AudioDevices.defaultInputDevice())
|
||||
#endif
|
||||
}
|
||||
|
||||
/// One engine, both directions: engage the system voice processor on the shared IO unit
|
||||
/// (AEC + noise suppression + AGC), hang the playback source off its render side and the
|
||||
/// mic tap off its capture side. Every failure falls back to a WORKING configuration —
|
||||
@@ -979,6 +1119,7 @@ public final class SessionAudio {
|
||||
voice processing unavailable (\(error.localizedDescription)) — separate \
|
||||
engines, no echo cancellation
|
||||
""")
|
||||
noteCombinedFailure()
|
||||
startPlayback(speakerUID: speakerUID)
|
||||
startCapture(micUID: micUID, micChannel: micChannel)
|
||||
return
|
||||
@@ -1032,6 +1173,7 @@ public final class SessionAudio {
|
||||
// processor won't engage at all, already does exactly this; this arm used to give up
|
||||
// on the mic instead, which is how a whole session could go silent uplink-only.)
|
||||
engine.stop()
|
||||
noteCombinedFailure()
|
||||
startPlayback(speakerUID: speakerUID)
|
||||
startCapture(micUID: micUID, micChannel: micChannel)
|
||||
return
|
||||
@@ -1042,6 +1184,7 @@ public final class SessionAudio {
|
||||
log.error("combined engine failed to start: \(error.localizedDescription)")
|
||||
engine.inputNode.removeTap(onBus: 0)
|
||||
engine.stop()
|
||||
noteCombinedFailure()
|
||||
// Same rule: a working mic without echo cancellation beats no mic at all.
|
||||
startPlayback(speakerUID: speakerUID)
|
||||
startCapture(micUID: micUID, micChannel: micChannel)
|
||||
|
||||
@@ -382,12 +382,29 @@ public final class PunktfunkConnection {
|
||||
/// the client draws its own (a visible system cursor over the stream).
|
||||
public private(set) var resolvedCompositor: Compositor = .auto
|
||||
|
||||
/// Host clock minus client clock (nanoseconds), from the connect-time wall-clock skew handshake
|
||||
/// (`punktfunk_connection_clock_offset_ns`). Add it to a local `CLOCK_REALTIME` instant to
|
||||
/// express that instant in the host's capture clock — the clock each `AccessUnit.ptsNs` is
|
||||
/// stamped in — so a glass-to-glass latency (present/enqueue time minus `ptsNs`) is valid across
|
||||
/// machines. `0` = no correction (an older host that didn't answer, or synchronized clocks).
|
||||
public private(set) var clockOffsetNs: Int64 = 0
|
||||
/// Host clock minus client clock (nanoseconds) — LIVE: the connect-time skew handshake's
|
||||
/// estimate, kept fresh by the core's mid-stream re-syncs (every 60 s plus immediately on a
|
||||
/// suspected wall-clock step; `punktfunk_connection_clock_offset_now_ns`, ABI v10). Add it to
|
||||
/// a local `CLOCK_REALTIME` instant to express that instant in the host's capture clock — the
|
||||
/// clock each `AccessUnit.ptsNs` is stamped in — so a glass-to-glass latency (present/enqueue
|
||||
/// time minus `ptsNs`) is valid across machines. `0` = no correction (an older host that
|
||||
/// didn't answer, synchronized clocks, or a closed connection).
|
||||
///
|
||||
/// ⚠ LIVE means DO NOT CACHE. Until 2026-08-13 this was a connect-time snapshot, and the
|
||||
/// core's own doc names the failure: "after an NTP step or slow drift the connect-time value
|
||||
/// silently corrupts every capture-clock comparison." The field evidence was stark — two
|
||||
/// sessions minutes apart against the same wired host read hostnet 17–21 ms, then a
|
||||
/// physically impossible 4.4 ms (the host is a VM; VM wall clocks step), and LatencyMeter's
|
||||
/// impossible-sample guard silently trimmed the shifted-negative half, so the HUD showed a
|
||||
/// plausible small number instead of an alarm. Read this property at each use — it is an
|
||||
/// atomic load behind the FFI — and never park it in a `let` or a closure capture list.
|
||||
/// Cross-thread reads follow the `framesDropped()` precedent.
|
||||
public var clockOffsetNs: Int64 {
|
||||
guard let handle else { return 0 }
|
||||
var offset: Int64 = 0
|
||||
_ = punktfunk_connection_clock_offset_now_ns(handle, &offset)
|
||||
return offset
|
||||
}
|
||||
|
||||
/// The video encoder bitrate (kbps) the host actually configured — the requested
|
||||
/// `bitrateKbps` clamped to the host's range ([500, 2 000 000] kbps), or its default
|
||||
@@ -635,9 +652,6 @@ public final class PunktfunkConnection {
|
||||
var comp: UInt32 = 0
|
||||
_ = punktfunk_connection_compositor(handle, &comp)
|
||||
resolvedCompositor = Compositor(rawValue: comp) ?? .auto
|
||||
var offset: Int64 = 0
|
||||
_ = punktfunk_connection_clock_offset_ns(handle, &offset)
|
||||
clockOffsetNs = offset
|
||||
var br: UInt32 = 0
|
||||
_ = punktfunk_connection_bitrate(handle, &br)
|
||||
resolvedBitrateKbps = br
|
||||
|
||||
@@ -15,8 +15,9 @@ import Foundation
|
||||
/// `record(ptsNs:atNs:offsetNs:)` at present.
|
||||
///
|
||||
/// For the host-anchored intervals (capture→…) the sample is `end + offset - pts_ns`, where
|
||||
/// `pts_ns` is the host's capture wall clock (the AU's pts) and the connect-time **clock-skew
|
||||
/// offset** (`PunktfunkConnection.clockOffsetNs`, host minus client) makes the difference valid
|
||||
/// `pts_ns` is the host's capture wall clock (the AU's pts) and the LIVE **clock-skew
|
||||
/// offset** (`PunktfunkConnection.clockOffsetNs`, host minus client, mid-stream re-synced —
|
||||
/// read it per record, never cached) makes the difference valid
|
||||
/// across machines. `offsetNs == 0` means an old host that didn't answer the skew handshake (or
|
||||
/// genuinely synced clocks) — the number is then only meaningful same-host, and the HUD tags the
|
||||
/// end-to-end line `(same-host clock)`.
|
||||
@@ -24,6 +25,8 @@ public final class LatencyMeter: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var samplesUs: [Int64] = []
|
||||
private var skewCorrected = false
|
||||
/// Samples `record` refused as impossible since the last `drainTrimmed` (see the guard).
|
||||
private var trimmed = 0
|
||||
/// The most recent sample and the instant it ended, for `latestSample(asOfNs:maxAgeMs:)` —
|
||||
/// a LEVEL, not a window, so `drain` deliberately leaves both alone.
|
||||
private var latestNs: Int64 = 0
|
||||
@@ -49,8 +52,19 @@ public final class LatencyMeter: @unchecked Sendable {
|
||||
public func record(ptsNs: UInt64, atNs: Int64, offsetNs: Int64) {
|
||||
let latNs = atNs &+ offsetNs &- Int64(bitPattern: ptsNs)
|
||||
// Drop absurd values (a clock step, a wildly wrong offset, garbage pts, or a stage whose
|
||||
// start stamp is missing/after its end) — samples are clamped to (0, 10 s).
|
||||
guard latNs > 0, latNs < 10_000_000_000 else { return }
|
||||
// start stamp is missing/after its end) — samples are clamped to (0, 10 s). COUNTED, not
|
||||
// silent: a cluster of non-positive samples is the signature of a wrong clock offset
|
||||
// (client-local stages can't go negative), and a meter that quietly trims the impossible
|
||||
// half of a shifted distribution presents the surviving tail as a plausible small number
|
||||
// — field 2026-08-13: "e2e 0–3 ms p50 / 23 ms p95" on a session whose true hostnet was
|
||||
// ~18 ms. `drainTrimmed` surfaces the count so the window can be MARKED suspect instead
|
||||
// of looking healthy.
|
||||
guard latNs > 0, latNs < 10_000_000_000 else {
|
||||
lock.lock()
|
||||
trimmed += 1
|
||||
lock.unlock()
|
||||
return
|
||||
}
|
||||
lock.lock()
|
||||
samplesUs.append(latNs / 1000)
|
||||
latestNs = latNs
|
||||
@@ -99,6 +113,18 @@ public final class LatencyMeter: @unchecked Sendable {
|
||||
public let skewCorrected: Bool
|
||||
}
|
||||
|
||||
/// Take-and-reset the count of impossible samples `record` refused (see its guard). Drained
|
||||
/// SEPARATELY from `drain()` on purpose: with a badly wrong offset EVERY sample of a window
|
||||
/// can be non-positive, `drain()` then returns `nil` — and a count folded into `Stats` would
|
||||
/// vanish with it, hiding the very windows that scream loudest. This survives an empty window.
|
||||
public func drainTrimmed() -> Int {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
let n = trimmed
|
||||
trimmed = 0
|
||||
return n
|
||||
}
|
||||
|
||||
/// Percentiles over the samples accumulated since the last drain, then reset the window. `nil`
|
||||
/// when no samples arrived in the interval.
|
||||
public func drain() -> Stats? {
|
||||
|
||||
@@ -56,17 +56,27 @@ enum WindowedPresentMode: String, Sendable {
|
||||
/// 203-nit diffuse white at EDR 1.0 (the display's SDR-white level) and lets the system tone-map the
|
||||
/// brighter highlights into the panel's headroom. This is the missing anchor that made the old HDR path
|
||||
/// render "way too bright" (no `edrMetadata` → no reference-white anchoring); a LARGER value renders
|
||||
/// dimmer. Matches the host's standard PQ reference white.
|
||||
/// dimmer.
|
||||
///
|
||||
/// ⚠️ This is one half of a pair: the host has to map SDR content into the PQ container at the SAME
|
||||
/// luminance, and pins it to 203 in `pf-vdisplay`'s `SDR_REFERENCE_WHITE_NITS`. When they disagree
|
||||
/// every pixel is off by the ratio — a gamescope host left on gamescope's own 400-nit default put
|
||||
/// the stream nearly a stop bright, which read as a glaring, over-saturated Steam UI and washed-out
|
||||
/// HDR game content at the same time. Change one end without the other and that gap re-opens.
|
||||
private let hdrReferenceWhiteNits: Float = 203.0
|
||||
|
||||
/// PUNKTFUNK_SDR_COLORSPACE=srgb — A/B hatch for the SDR layer's colour tag. Today the SDR layer
|
||||
/// ships with `colorspace = nil`, which on macOS means NO colour matching: the BT.709/sRGB-encoded
|
||||
/// stream is displayed with the panel's native primaries — mild oversaturation on every P3 Mac.
|
||||
/// `srgb` tags the layer so CoreAnimation colour-matches it into the panel's gamut (the strictly
|
||||
/// correct rendering). Kept OFF by default until the on-glass A/B confirms it (the nil path is the
|
||||
/// long-proven look, and some users may prefer the vivid rendition); flip the default once verified.
|
||||
private let sdrColorspaceOverride: CGColorSpace? = {
|
||||
guard ProcessInfo.processInfo.environment["PUNKTFUNK_SDR_COLORSPACE"] == "srgb" else {
|
||||
/// The SDR layer's colour tag. `colorspace = nil` means NO colour matching: the BT.709-encoded
|
||||
/// stream is handed to the compositor untagged and drawn in the display's native space. That is
|
||||
/// mild oversaturation on a P3 Mac or iPad, and on a tvOS display composited for HDR it also lifts
|
||||
/// the black floor — the 2026-08-13 field report of greys where blacks should be, which arrived
|
||||
/// with the client's own HDR switch already OFF, so no other stage had tagged those pixels either.
|
||||
/// Tagging lets CoreAnimation colour-match into whatever the output actually is, which is the
|
||||
/// strictly correct rendering, so it is now the default.
|
||||
///
|
||||
/// `PUNKTFUNK_SDR_COLORSPACE=none` restores the old untagged look — the A/B lever if a panel
|
||||
/// regresses, or for anyone who preferred the more vivid rendition.
|
||||
private let sdrColorspace: CGColorSpace? = {
|
||||
guard ProcessInfo.processInfo.environment["PUNKTFUNK_SDR_COLORSPACE"] != "none" else {
|
||||
return nil
|
||||
}
|
||||
return CGColorSpace(name: CGColorSpace.sRGB)
|
||||
@@ -425,6 +435,14 @@ public final class MetalVideoPresenter {
|
||||
/// Render-thread confined once the pipeline runs (Stage2Pipeline.start's one pre-thread
|
||||
/// `configure` call is ordered before the thread starts, so it doesn't race).
|
||||
private var hdrActive = false
|
||||
/// Has `configureColor` run even once? `hdrActive` starts `false`, so a session that is SDR from
|
||||
/// the first frame matches the initial state and used to fall straight through `configure`'s
|
||||
/// guard — the layer then kept `make()`'s bare config, which never assigns a colour space, and
|
||||
/// the SDR stream presented untagged for the whole session. That also made
|
||||
/// `PUNKTFUNK_SDR_COLORSPACE` dead code on exactly the sessions it was meant to fix, so an
|
||||
/// operator A/B-ing it in the field saw nothing change. Same-state calls after the first are
|
||||
/// still no-ops, which is what the guard is for.
|
||||
private var didConfigureColor = false
|
||||
/// tvOS only: whether HDR frames currently present as PQ PASSTHROUGH (display has HDR headroom
|
||||
/// — its own tone-map applies) vs the in-shader tone-map fallback. Render-thread confined;
|
||||
/// derived from the staged display headroom at the top of every `render`.
|
||||
@@ -549,6 +567,11 @@ public final class MetalVideoPresenter {
|
||||
layer.contentsGravity = .resizeAspect
|
||||
// Triple-buffer: more in-flight drawables before `nextDrawable()` (called on the display-link /
|
||||
// MAIN thread) has to block waiting for one to free.
|
||||
// ⚠ This is the STAGE-2/3 depth. Stage-4 (deadline pacing, the iOS/tvOS default) never
|
||||
// calls `nextDrawable()` — the link vends every drawable — so the third slot only gives
|
||||
// the compositor room to queue a second present ahead of scanout, i.e. the two-refresh
|
||||
// present floor. `Stage2Pipeline.startDeadlinePresenter` clamps it to 2 for that pacing;
|
||||
// keep the two in step if this number ever changes.
|
||||
layer.maximumDrawableCount = 3
|
||||
|
||||
return MetalVideoPresenter(
|
||||
@@ -592,13 +615,16 @@ public final class MetalVideoPresenter {
|
||||
stagingLock.lock()
|
||||
let passthrough = stagedDisplayHeadroom > 1.0
|
||||
stagingLock.unlock()
|
||||
guard hdr != hdrActive || (hdr && passthrough != hdrPassthroughActive) else { return }
|
||||
guard !didConfigureColor || hdr != hdrActive
|
||||
|| (hdr && passthrough != hdrPassthroughActive)
|
||||
else { return }
|
||||
hdrActive = hdr
|
||||
hdrPassthroughActive = passthrough
|
||||
#else
|
||||
guard hdr != hdrActive else { return }
|
||||
guard !didConfigureColor || hdr != hdrActive else { return }
|
||||
hdrActive = hdr
|
||||
#endif
|
||||
didConfigureColor = true
|
||||
configureColor(hdr: hdr)
|
||||
}
|
||||
|
||||
@@ -628,9 +654,10 @@ public final class MetalVideoPresenter {
|
||||
layer.colorspace = CGColorSpace(name: CGColorSpace.itur_2100_PQ)
|
||||
} else {
|
||||
// SDR-composited display: PQ would render untone-mapped (blown out) — the
|
||||
// pf_frag_hdr_tv shader tone-maps to SDR instead.
|
||||
// pf_frag_hdr_tv shader tone-maps to SDR instead. Its output is BT.709, so it
|
||||
// carries the same SDR tag as a genuinely SDR session.
|
||||
layer.pixelFormat = .bgra8Unorm
|
||||
layer.colorspace = nil
|
||||
layer.colorspace = sdrColorspace
|
||||
}
|
||||
#else
|
||||
layer.pixelFormat = .rgba16Float
|
||||
@@ -641,12 +668,11 @@ public final class MetalVideoPresenter {
|
||||
layer.edrMetadata = makeEDR(lastHdrMeta)
|
||||
#endif
|
||||
} else {
|
||||
// SDR: gamma-encoded BT.709 [0,1] in an 8-bit drawable. Default: nil colorspace = NO
|
||||
// colour matching on macOS (the panel's native primaries — the long-proven look,
|
||||
// slightly oversaturated on P3 panels); PUNKTFUNK_SDR_COLORSPACE=srgb tags the layer
|
||||
// for correct colour matching instead (A/B pending — see sdrColorspaceOverride).
|
||||
// SDR: gamma-encoded BT.709 [0,1] in an 8-bit drawable, tagged so CoreAnimation
|
||||
// colour-matches it into the output rather than drawing it in the panel's native
|
||||
// space (see sdrColorspace; PUNKTFUNK_SDR_COLORSPACE=none restores untagged).
|
||||
layer.pixelFormat = .bgra8Unorm
|
||||
layer.colorspace = sdrColorspaceOverride
|
||||
layer.colorspace = sdrColorspace
|
||||
#if !os(tvOS)
|
||||
layer.wantsExtendedDynamicRangeContent = false
|
||||
layer.edrMetadata = nil
|
||||
|
||||
@@ -260,13 +260,22 @@ final class SessionPresenter {
|
||||
// value is deliberately ignored). The user-facing choice is the INTENT
|
||||
// (PresentPriority): latency (newest-wins zero-queue store) vs smoothness (a FIFO jitter
|
||||
// buffer; on macOS it additionally paces presents onto the vsync grid so the buffer
|
||||
// drains on display cadence). Stage-1 is reachable only via env in DEBUG; release maps
|
||||
// it back to the default (the stage-1 pump below stays the automatic Metal-missing
|
||||
// fallback).
|
||||
// drains on display cadence). Stage-1 resolves from the persisted picker only in DEBUG;
|
||||
// in release the ENV alone reaches it (the stage-1 pump below stays the automatic
|
||||
// Metal-missing fallback either way).
|
||||
#if DEBUG
|
||||
let allowStage1 = true
|
||||
#else
|
||||
let allowStage1 = false
|
||||
// The gate exists so a LEFTOVER value can't revive the freeze-prone fallback — but the
|
||||
// persisted picker is no longer read at all (setting: nil below), so the only channel
|
||||
// left is the env, and an env var is never leftover: it takes a devicectl/Xcode launch
|
||||
// to exist. It must stay openable on Release because Release is the only build that
|
||||
// measures presentation honestly, and stage-1 is the one rung that presents on the
|
||||
// hardware video plane instead of through the GPU compositor — the A/B for the tvOS
|
||||
// two-refresh present floor (field 2026-08-13: PUNKTFUNK_PRESENTER=stage1 on a Release
|
||||
// build silently ran stage-4, which would have false-negatived that A/B).
|
||||
let allowStage1 =
|
||||
ProcessInfo.processInfo.environment["PUNKTFUNK_PRESENTER"] == "stage1"
|
||||
#endif
|
||||
let explicit = PresenterChoice.explicit(
|
||||
setting: nil, // the legacy DefaultsKey.presenter picker value is no longer read
|
||||
@@ -336,7 +345,7 @@ final class SessionPresenter {
|
||||
} else {
|
||||
let pump = StreamPump()
|
||||
pump.start(
|
||||
connection: connection, layer: baseLayer,
|
||||
connection: connection, layer: baseLayer, endToEndMeter: endToEndMeter,
|
||||
onFrame: onFrame, onSessionEnd: onSessionEnd, onDecodedSize: onDecodedSize)
|
||||
self.pump = pump
|
||||
}
|
||||
|
||||
@@ -271,6 +271,64 @@ final class LatestBox<T>: @unchecked Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// The deadline link's frame-latency ASK and property READBACK, published for the HUD to render.
|
||||
///
|
||||
/// ⚠ A readback is NOT a grant. `preferredFrameLatency` is a plain read-write float
|
||||
/// (CAMetalDisplayLink.h carries no doc contract), so reading it returns whatever we last
|
||||
/// stored unless the system actively clamps the setter — and the 2026-08-13 field run proved
|
||||
/// how misleading that is: it read 1.00 while the measured vend lead sat at 1.95 refresh
|
||||
/// periods. The number that tells the truth about scheduling is the vend lead (the HUD's
|
||||
/// `os present` floor), never this property. The line still earns its place twice over: a
|
||||
/// readback that DIFFERS from the ask is the one clamp signal the API can give, and the ask
|
||||
/// must be visible on screen because **on tvOS no log is reachable** — `log stream --device`
|
||||
/// is gone from modern macOS, `log collect --device-name` needs root and then fails "Device
|
||||
/// not configured" because an Apple TV has no USB to fall back to, and the libimobiledevice
|
||||
/// pairing is a different database from Xcode's. Console.app is a GUI.
|
||||
///
|
||||
/// A process-global rather than a sixth parameter threaded through SessionModel → StreamView →
|
||||
/// controller → SessionPresenter → Stage2Pipeline → delegate: it is write-once-per-session
|
||||
/// diagnostics, and this file already keeps `presentDebug`/`presentLog` at file scope. Reset by
|
||||
/// `clear()` at session start so a stale session's answer can never be read as this one's.
|
||||
public final class PresentLinkInfo: @unchecked Sendable {
|
||||
public static let shared = PresentLinkInfo()
|
||||
private let lock = NSLock()
|
||||
private var ask: Float = 0
|
||||
private var latency: Float = 0
|
||||
private var rangeMin: Float = 0
|
||||
private var rangeMax: Float = 0
|
||||
private var drawables: Int = 0
|
||||
private var present = false
|
||||
|
||||
private init() {}
|
||||
|
||||
func publish(ask: Float, latency: Float, rangeMin: Float, rangeMax: Float, drawables: Int) {
|
||||
lock.lock()
|
||||
self.ask = ask
|
||||
self.latency = latency
|
||||
self.rangeMin = rangeMin
|
||||
self.rangeMax = rangeMax
|
||||
self.drawables = drawables
|
||||
present = true
|
||||
lock.unlock()
|
||||
}
|
||||
|
||||
/// Session start — a link that never comes up must not leave the previous one's answer up.
|
||||
public func clear() {
|
||||
lock.lock()
|
||||
present = false
|
||||
lock.unlock()
|
||||
}
|
||||
|
||||
/// `nil` until the link's first update (or on a non-deadline rung, which has no link).
|
||||
public func snapshot()
|
||||
-> (ask: Float, latency: Float, rangeMin: Float, rangeMax: Float, drawables: Int)?
|
||||
{
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return present ? (ask, latency, rangeMin, rangeMax, drawables) : nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Deadline pacing's staged frame-rate hint. SessionPresenter pushes the stream rate from the
|
||||
/// MAIN thread (session start + every layout/Reconfigure); the link's own thread drains and
|
||||
/// applies it, so the CAMetalDisplayLink is only ever touched from the thread that runs it. The
|
||||
@@ -312,9 +370,24 @@ private final class FrameRateHint: @unchecked Sendable {
|
||||
return p
|
||||
}
|
||||
private static func range(hz: Float, boosted: Bool) -> CAFrameRateRange {
|
||||
#if os(tvOS)
|
||||
// A TV is a FIXED-rate display: there is no ProMotion panel to lift and no Pencil to
|
||||
// sample for, so the `max(hz, 120)` ceiling below asks a 60 Hz Apple TV to accept
|
||||
// anything up to 120. A range is a promise about how variable our cadence may be, and a
|
||||
// scheduler handed 60…120 on a fixed 60 Hz display has every reason to keep a frame of
|
||||
// slack in hand — which is what a two-refresh `targetPresentationTimestamp` IS. Pin all
|
||||
// three bounds to the stream rate so the deadline has nothing to hedge against.
|
||||
// (Field 2026-08-13, Apple TV 4K / tvOS 27: `os present` stuck at ~2 × 16.67 with
|
||||
// `preferredFrameLatency = 1` asked for and re-asserted every update; shrinking the
|
||||
// drawable pool to 2 moved it not at all.) `boosted` is deliberately ignored — it exists
|
||||
// for pen proximity, which tvOS does not have.
|
||||
_ = boosted
|
||||
return CAFrameRateRange(minimum: hz, maximum: hz, preferred: hz)
|
||||
#else
|
||||
let cap = max(hz, 120)
|
||||
let preferred = boosted ? cap : hz
|
||||
return CAFrameRateRange(minimum: preferred, maximum: cap, preferred: preferred)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,18 +508,28 @@ private final class DeadlineLinkDelegate: NSObject, CAMetalDisplayLinkDelegate {
|
||||
private let phase: PhaseReporter?
|
||||
/// The OS-floor sampler (design/apple-presentation-rebuild.md): every update's vend→glass
|
||||
/// lead is recorded so its p50 becomes the "OS present floor" the HUD subtracts from the
|
||||
/// shown display/e2e numbers. Self-adapting — reads ~2 refresh periods composited today,
|
||||
/// would read ~1 under direct-to-display, tracks VRR rate changes.
|
||||
/// shown display/e2e numbers. Self-adapting: ~1 refresh period is the goal, ~2 means the
|
||||
/// compositor is running a frame ahead of us (what a 3-slot drawable pool bought it before
|
||||
/// `startDeadlinePresenter` clamped stage-4 to 2). Tracks VRR rate changes.
|
||||
private let floorMeter: LatencyMeter?
|
||||
/// One-shot: log the link's EFFECTIVE preferredFrameLatency after the first re-assert —
|
||||
/// reads 1 while vendLeadMs sits at ~2 periods ⇒ the scheduler ignores the request while
|
||||
/// the layer is composited (the promotion hunt); reads 2 ⇒ the system clamped it outright.
|
||||
/// The pool depth this session vends from (`startDeadlinePresenter` sets it on the layer).
|
||||
/// Carried only so the one-shot line below reports the two halves of the depth question
|
||||
/// together — a `preferredFrameLatency` of 1 against a 3-slot pool is the configuration that
|
||||
/// measured a two-refresh floor in the field, and reading either number alone hides that.
|
||||
private let drawableCount: Int
|
||||
/// The `preferredFrameLatency` this session asks for — 1 by default, PUNKTFUNK_FRAME_LATENCY
|
||||
/// for the on-device ladder (see `startDeadlinePresenter` for the ladder's design).
|
||||
private let latencyAsk: Float
|
||||
/// One-shot: log the link's preferredFrameLatency READBACK after the first re-assert. A
|
||||
/// readback differing from the ask ⇒ the system clamps the property (the one clamp signal
|
||||
/// it can give); a readback EQUAL to the ask proves nothing — only vendLeadMs does (see
|
||||
/// PresentLinkInfo's doc for the field lesson).
|
||||
private var loggedEffective = false
|
||||
|
||||
init(
|
||||
stash: LatestBox<CAMetalDrawable>, renderSignal: DispatchSemaphore,
|
||||
hint: FrameRateHint, stats: PresentDebugStats?, floorMeter: LatencyMeter?,
|
||||
phase: PhaseReporter?
|
||||
phase: PhaseReporter?, drawableCount: Int, latencyAsk: Float
|
||||
) {
|
||||
self.stash = stash
|
||||
self.renderSignal = renderSignal
|
||||
@@ -454,23 +537,34 @@ private final class DeadlineLinkDelegate: NSObject, CAMetalDisplayLinkDelegate {
|
||||
self.stats = stats
|
||||
self.floorMeter = floorMeter
|
||||
self.phase = phase
|
||||
self.drawableCount = drawableCount
|
||||
self.latencyAsk = latencyAsk
|
||||
}
|
||||
|
||||
func metalDisplayLink(_ link: CAMetalDisplayLink, needsUpdate update: CAMetalDisplayLink.Update) {
|
||||
if let range = hint.drain(), link.preferredFrameRateRange != range {
|
||||
link.preferredFrameRateRange = range
|
||||
}
|
||||
// Re-assert the minimum-latency request every update (cheap compare): it was set once
|
||||
// before add(to:), and whether a pre-add set survives scheduling is exactly the kind of
|
||||
// Re-assert the latency ask every update (cheap compare): it was set once before
|
||||
// add(to:), and whether a pre-add set survives scheduling is exactly the kind of
|
||||
// thing the vendLeadMs stat exists to catch — belt and braces.
|
||||
if link.preferredFrameLatency != 1 { link.preferredFrameLatency = 1 }
|
||||
if link.preferredFrameLatency != latencyAsk { link.preferredFrameLatency = latencyAsk }
|
||||
// Publish every update, not just the first: the range is re-applied from the staged hint
|
||||
// above (mode switch / rate change), and `preferredFrameLatency` is re-asserted right
|
||||
// here — so the readback can change mid-session, and a write-once snapshot would keep
|
||||
// showing the answer to a question we have since asked again. Cheap: five stores under
|
||||
// an uncontended lock, once per refresh.
|
||||
let range = link.preferredFrameRateRange
|
||||
PresentLinkInfo.shared.publish(
|
||||
ask: latencyAsk, latency: link.preferredFrameLatency, rangeMin: range.minimum,
|
||||
rangeMax: range.maximum, drawables: drawableCount)
|
||||
if !loggedEffective {
|
||||
loggedEffective = true
|
||||
let range = link.preferredFrameRateRange
|
||||
let msg = String(
|
||||
format: "deadline link up: effective preferredFrameLatency=%.2f "
|
||||
+ "range=%.0f-%.0f preferred=%.0f",
|
||||
link.preferredFrameLatency, range.minimum, range.maximum, range.preferred ?? 0)
|
||||
format: "deadline link up: preferredFrameLatency ask=%.2f readback=%.2f "
|
||||
+ "maxDrawables=%d range=%.0f-%.0f preferred=%.0f",
|
||||
latencyAsk, link.preferredFrameLatency, drawableCount,
|
||||
range.minimum, range.maximum, range.preferred ?? 0)
|
||||
presentLog.info("\(msg, privacy: .public)")
|
||||
}
|
||||
// The link's own pipeline depth, measured: how far ahead of glass this vend runs.
|
||||
@@ -729,7 +823,13 @@ public final class Stage2Pipeline {
|
||||
/// (which withhold concealed frames) and driven by the pump (arm on a gap, poll per iteration).
|
||||
private let gate = ReanchorGate(framesDropped: 0)
|
||||
private var token = StopFlag()
|
||||
private var offsetNs: Int64 = 0
|
||||
/// LIVE host↔client clock offset, read AT EACH RECORD — never cached per session. Until
|
||||
/// 2026-08-13 this was a `let` snapshot of the connect-time handshake, and on a host whose
|
||||
/// wall clock steps (a VM under NTP) the frozen value silently shifted every host-anchored
|
||||
/// stat — field evidence: hostnet 17–21 ms one session, a physically impossible 4.4 ms the
|
||||
/// next, same wired host. The core re-syncs the estimate mid-stream (60 s + step detection);
|
||||
/// each call is an atomic load behind the FFI.
|
||||
private var clockOffset: () -> Int64 = { 0 }
|
||||
/// Signalled when the pump thread exits, so `stop()` can join it (bounded) before `decoder.reset()`
|
||||
/// — otherwise a pump iteration already past its `token.isStopped` check can rebuild a decode session
|
||||
/// right after the reset (a brief orphan session). `pumpJoinable` is armed by `start`, consumed by
|
||||
@@ -831,7 +931,7 @@ public final class Stage2Pipeline {
|
||||
onSessionEnd: (@Sendable () -> Void)?,
|
||||
onDecodedSize: (@Sendable (Int, Int) -> Void)? = nil
|
||||
) {
|
||||
offsetNs = connection.clockOffsetNs
|
||||
clockOffset = { connection.clockOffsetNs } // live (re-synced) — see the field doc
|
||||
recovery.bind(connection) // arm host-keyframe recovery for this session
|
||||
decodeReport.bind(connection) // arm the Automatic-bitrate decode signal for this session
|
||||
phaseReporter.bind(connection) // arm phase reports (flushed only by the deadline link)
|
||||
@@ -1001,7 +1101,7 @@ public final class Stage2Pipeline {
|
||||
let ring = ring
|
||||
let endToEndMeter = endToEndMeter
|
||||
let displayMeter = displayMeter
|
||||
let offsetNs = offsetNs
|
||||
let clockOffset = clockOffset
|
||||
let renderSignal = renderSignal
|
||||
let renderStopped = renderStopped
|
||||
// Present policy — the user's V-Sync setting (default OFF = immediate, the long-proven
|
||||
@@ -1075,7 +1175,7 @@ public final class Stage2Pipeline {
|
||||
?? Stage2Pipeline.realtimeNs(forDisplayLinkTimestamp: CACurrentMediaTime())
|
||||
// End-to-end = capture→on-glass, measured directly (skew-corrected via the
|
||||
// connect-time clock offset) — the HUD headline.
|
||||
endToEndMeter?.record(ptsNs: frame.ptsNs, atNs: atNs, offsetNs: offsetNs)
|
||||
endToEndMeter?.record(ptsNs: frame.ptsNs, atNs: atNs, offsetNs: clockOffset())
|
||||
// Display stage = decoded → on-glass. Both instants are client CLOCK_REALTIME,
|
||||
// so no skew offset applies.
|
||||
displayMeter?.record(ptsNs: UInt64(frame.decodedNs), atNs: atNs, offsetNs: 0)
|
||||
@@ -1134,11 +1234,52 @@ public final class Stage2Pipeline {
|
||||
let presenter = presenter
|
||||
let endToEndMeter = endToEndMeter
|
||||
let displayMeter = displayMeter
|
||||
let offsetNs = offsetNs
|
||||
let clockOffset = clockOffset
|
||||
let hint = frameRateHint
|
||||
let layer = presenter.layer
|
||||
let stash = LatestBox<CAMetalDrawable>()
|
||||
|
||||
// ⭐ Shrink the drawable pool to 2 for THIS pacing — the measured fix for a present floor
|
||||
// stuck at two refreshes (field 2026-08-13, Apple TV 4K / tvOS 27: `os present +32.5` at
|
||||
// 60 Hz = 1.95 × 16.67, i.e. the system running a whole frame ahead of us).
|
||||
//
|
||||
// `maximumDrawableCount` is 3 from MetalVideoPresenter.make(), and its rationale there —
|
||||
// "more in-flight drawables before nextDrawable() has to block" — is a STAGE-2 concern.
|
||||
// Stage-4 never calls nextDrawable(): every drawable is vended by the link
|
||||
// (`update.drawable` → stash → `render(into:)`), so the third slot buys this path nothing
|
||||
// and costs it a refresh — a pool of 3 is exactly the room the compositor needs to keep
|
||||
// two presents queued ahead of scanout, which is what `preferredFrameLatency = 1` is
|
||||
// asking it not to do. Two slots is the shallowest pool that still double-buffers: one
|
||||
// vended (stashed or being rendered), one being scanned out.
|
||||
//
|
||||
// Set HERE, not on the link thread: this runs before either the render thread or the link
|
||||
// thread exists, so the layer still has a single writer (the render thread owns
|
||||
// drawableSize/format afterwards — see MetalVideoPresenter's threading notes).
|
||||
// PUNKTFUNK_DRAWABLE_COUNT=3 restores the old depth for an on-glass A/B without a
|
||||
// rebuild; values outside 2...3 are ignored (CAMetalLayer's own accepted range).
|
||||
let drawableCount =
|
||||
ProcessInfo.processInfo.environment["PUNKTFUNK_DRAWABLE_COUNT"]
|
||||
.flatMap(Int.init)
|
||||
.flatMap { (2...3).contains($0) ? $0 : nil } ?? 2
|
||||
layer.maximumDrawableCount = drawableCount
|
||||
|
||||
// The frame-latency ASK (default 1 — wake as late as fits: latch the NEXT refresh).
|
||||
// PUNKTFUNK_FRAME_LATENCY overrides it for the on-device ladder. The property is a
|
||||
// FLOAT, so sub-frame asks (0.5) are expressible; whether the scheduler honours them —
|
||||
// or reacts to the property at all — is exactly what the ladder measures. Field
|
||||
// 2026-08-13 (Apple TV 4K, tvOS 27): ask 1 → vend lead 1.95 refresh periods, and the
|
||||
// readback echoed the ask throughout (it is a plain property — see PresentLinkInfo).
|
||||
// The discriminating runs, watching `os present` (the vend lead), are:
|
||||
// ask=2 → lead grows to ~3 ⇒ the property WORKS and the tvOS floor is ~ask+1;
|
||||
// lead stays ~2 ⇒ the property is INERT here — stop pulling this lever.
|
||||
// ask=0.5 → any lead below ~1.9 ⇒ a real in-regime win to then tune.
|
||||
// Clamped to 0...4: negatives/NaN are meaningless, and beyond 4 asked-for frames of
|
||||
// latency nothing is being measured.
|
||||
let latencyAsk =
|
||||
ProcessInfo.processInfo.environment["PUNKTFUNK_FRAME_LATENCY"]
|
||||
.flatMap(Float.init)
|
||||
.flatMap { $0.isFinite ? min(max($0, 0), 4) : nil } ?? 1
|
||||
|
||||
let floorMeter = presentFloorMeter
|
||||
let phaseReporter = phaseReporter
|
||||
// The link starts LAZILY — the render thread triggers this after the FIRST decoded
|
||||
@@ -1151,9 +1292,10 @@ public final class Stage2Pipeline {
|
||||
let linkThread = Thread {
|
||||
let delegate = DeadlineLinkDelegate(
|
||||
stash: stash, renderSignal: renderSignal, hint: hint, stats: debugStats,
|
||||
floorMeter: floorMeter, phase: phaseReporter)
|
||||
floorMeter: floorMeter, phase: phaseReporter,
|
||||
drawableCount: drawableCount, latencyAsk: latencyAsk)
|
||||
let link = CAMetalDisplayLink(metalLayer: layer)
|
||||
link.preferredFrameLatency = 1 // wake as late as fits: latch the NEXT refresh
|
||||
link.preferredFrameLatency = latencyAsk // see the ladder note above
|
||||
if let range = hint.drain() { link.preferredFrameRateRange = range }
|
||||
link.delegate = delegate // weak — this closure is the strong ref
|
||||
link.add(to: RunLoop.current, forMode: .default)
|
||||
@@ -1223,7 +1365,7 @@ public final class Stage2Pipeline {
|
||||
let onGlass: (Int64?) -> Void = { presentedNs in
|
||||
let atNs = presentedNs
|
||||
?? Stage2Pipeline.realtimeNs(forDisplayLinkTimestamp: CACurrentMediaTime())
|
||||
endToEndMeter?.record(ptsNs: frame.ptsNs, atNs: atNs, offsetNs: offsetNs)
|
||||
endToEndMeter?.record(ptsNs: frame.ptsNs, atNs: atNs, offsetNs: clockOffset())
|
||||
displayMeter?.record(ptsNs: UInt64(frame.decodedNs), atNs: atNs, offsetNs: 0)
|
||||
debugStats?.presented(atNs: presentedNs, issuedNs: issuedNs)
|
||||
}
|
||||
|
||||
@@ -17,9 +17,18 @@ final class StreamPump {
|
||||
|
||||
/// Pump thread: pull AUs, wrap, enqueue. Non-IDR AUs before the first format
|
||||
/// description are dropped. `onFrame`/`onSessionEnd` fire on the pump thread.
|
||||
///
|
||||
/// `endToEndMeter` is stage-1's ONLY latency instrument, and it measures capture→ENQUEUE —
|
||||
/// not capture→glass like the Metal rungs: the layer decodes AND presents after our hand-off,
|
||||
/// and AVSampleBufferDisplayLayer has no presented callback, so the tail past enqueue (its
|
||||
/// internal decode + the video-plane flip) is unmeasurable from the app. Cross-rung
|
||||
/// comparisons must read this as e2e MINUS decode+display and settle the remainder on
|
||||
/// camera. It is still worth wiring: matching pre-tail halves between rungs pins any felt
|
||||
/// difference on the present tail — the video-plane-vs-compositor question itself.
|
||||
func start(
|
||||
connection: PunktfunkConnection,
|
||||
layer: AVSampleBufferDisplayLayer,
|
||||
endToEndMeter: LatencyMeter? = nil,
|
||||
onFrame: (@Sendable (AccessUnit) -> Void)?,
|
||||
onSessionEnd: (@Sendable () -> Void)?,
|
||||
onDecodedSize: (@Sendable (Int, Int) -> Void)? = nil
|
||||
@@ -158,7 +167,14 @@ final class StreamPump {
|
||||
// flagging it DoNotDisplay — the layer still decodes it (keeping the reference
|
||||
// chain fed) but shows the last GOOD picture until a clean re-anchor lifts the
|
||||
// gate. Folded from the AU's wire flags (stage-1 has no decode callback).
|
||||
if !gate.onDecoded(flags: au.flags) {
|
||||
if gate.onDecoded(flags: au.flags) {
|
||||
// Capture→enqueue (see start's doc). Only frames that will DISPLAY:
|
||||
// a withheld frame never reaches glass, so its enqueue instant would
|
||||
// dilute the population the Metal rungs are compared against. The
|
||||
// offset is read PER ENQUEUE — it is live (mid-stream re-synced) and
|
||||
// caching it rebuilds the stale-offset corruption (see clockOffsetNs).
|
||||
endToEndMeter?.record(ptsNs: au.ptsNs, offsetNs: connection.clockOffsetNs)
|
||||
} else {
|
||||
StreamPump.setDoNotDisplay(sample)
|
||||
}
|
||||
layer.enqueue(sample)
|
||||
|
||||
@@ -758,10 +758,18 @@ public final class StreamViewController: StreamViewControllerBase {
|
||||
/// the switch never lands, so an SDR-composited display can't show blown-out PQ either way.
|
||||
/// Applied once per session, as soon as the window and the negotiated mode both exist; the
|
||||
/// stop() teardown clears it.
|
||||
///
|
||||
/// ⚠️ Gated on the STREAM being HDR (`connection.isHDR`), not just on the user's HDR setting.
|
||||
/// The criteria below hardcode BT.2020 + ST.2084 PQ, so without that check an ordinary SDR
|
||||
/// session drove an HDR-capable TV into PQ output — which is a standard way to raise the black
|
||||
/// floor, since the Apple TV switches HDMI to limited-range levels in its HDR modes and a set
|
||||
/// configured for full-range then renders code 16 as grey. Layout re-runs this, so a session
|
||||
/// that flips to HDR mid-stream still picks the mode up on the next pass.
|
||||
private func applyDisplayCriteriaIfNeeded() {
|
||||
guard let manager = view.window?.avDisplayManager, let connection,
|
||||
manager.preferredDisplayCriteria == nil,
|
||||
SessionSettings.current.hdrEnabled
|
||||
SessionSettings.current.hdrEnabled,
|
||||
connection.isHDR
|
||||
else { return }
|
||||
let mode = connection.currentMode()
|
||||
guard mode.width > 0, mode.height > 0, mode.refreshHz > 0 else { return }
|
||||
|
||||
@@ -32,7 +32,7 @@ final class AudioDeviceWatcherTests: XCTestCase {
|
||||
let engine = AVAudioEngine()
|
||||
var reasons: [AudioDeviceWatcher.Reason] = []
|
||||
let watcher = AudioDeviceWatcher(
|
||||
isOurs: { $0 === engine }, onChange: { reasons.append($0) })
|
||||
isOurs: { $0 === engine }, onChange: { reason, _ in reasons.append(reason) })
|
||||
watcher.start()
|
||||
defer { watcher.stop() }
|
||||
|
||||
@@ -51,7 +51,7 @@ final class AudioDeviceWatcherTests: XCTestCase {
|
||||
let stranger = AVAudioEngine()
|
||||
var reasons: [AudioDeviceWatcher.Reason] = []
|
||||
let watcher = AudioDeviceWatcher(
|
||||
isOurs: { $0 === ours }, onChange: { reasons.append($0) })
|
||||
isOurs: { $0 === ours }, onChange: { reason, _ in reasons.append(reason) })
|
||||
watcher.start()
|
||||
defer { watcher.stop() }
|
||||
|
||||
@@ -66,7 +66,7 @@ final class AudioDeviceWatcherTests: XCTestCase {
|
||||
let engine = AVAudioEngine()
|
||||
var reasons: [AudioDeviceWatcher.Reason] = []
|
||||
let watcher = AudioDeviceWatcher(
|
||||
isOurs: { $0 === engine }, onChange: { reasons.append($0) })
|
||||
isOurs: { $0 === engine }, onChange: { reason, _ in reasons.append(reason) })
|
||||
watcher.start()
|
||||
watcher.stop()
|
||||
|
||||
@@ -93,7 +93,7 @@ final class AudioDeviceWatcherTests: XCTestCase {
|
||||
}
|
||||
|
||||
var reasons: [AudioDeviceWatcher.Reason] = []
|
||||
let watcher = AudioDeviceWatcher(isOurs: { _ in false }, onChange: { reasons.append($0) })
|
||||
let watcher = AudioDeviceWatcher(isOurs: { _ in false }, onChange: { reason, _ in reasons.append(reason) })
|
||||
watcher.start()
|
||||
defer {
|
||||
_ = Self.setDefaultOutput(original)
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
// The two decisions that ended the 2026-08-14 rebuild loop, driven with a synthetic clock.
|
||||
//
|
||||
// The loop's shape, for the plant-the-defect cases below: the voice-processing engine fails to
|
||||
// start (~1.9 s spent trying), the fallback comes up, and its own HAL fallout retriggers the
|
||||
// recovery ~0.6 s later — forever. Restore either defect (retry the failed topology, or keep the
|
||||
// flat 0.5 s floor) and the session pays an audio gap every ~2.5 s for as long as it lives.
|
||||
|
||||
import XCTest
|
||||
|
||||
@testable import PunktfunkKit
|
||||
|
||||
final class AudioRebuildPolicyTests: XCTestCase {
|
||||
// MARK: - RebuildBackoff
|
||||
|
||||
/// The first trigger of a session keeps the old behaviour: the burst-coalescing debounce.
|
||||
func testFirstTriggerWaitsOnlyTheDebounce() {
|
||||
var backoff = RebuildBackoff()
|
||||
XCTAssertEqual(backoff.delay(now: 1000), RebuildBackoff.debounce)
|
||||
}
|
||||
|
||||
/// One rebuild, then quiet: the next real device switch minutes later is answered at full
|
||||
/// responsiveness — the ladder must never make a HEALTHY recovery sluggish.
|
||||
func testAnIsolatedSwitchLongAfterTheLastRebuildResetsTheChain() {
|
||||
var backoff = RebuildBackoff()
|
||||
_ = backoff.delay(now: 1000)
|
||||
backoff.noteRebuild(at: 1000.2)
|
||||
// Chained once (a second switch soon after — legitimate, e.g. AirPods out then back in).
|
||||
_ = backoff.delay(now: 1001)
|
||||
backoff.noteRebuild(at: 1002)
|
||||
// Minutes of quiet, then a fresh switch: base debounce again, chain forgotten.
|
||||
XCTAssertEqual(backoff.delay(now: 1300), RebuildBackoff.debounce)
|
||||
XCTAssertEqual(backoff.chain, 0)
|
||||
}
|
||||
|
||||
/// THE FIELD LOOP, against the real constants: a trigger 0.6 s after every rebuild, ten
|
||||
/// minutes long. The flat 0.5 s floor produced a rebuild every ~2.5 s — ~240 audio gaps.
|
||||
/// The ladder must cut that by an order of magnitude and settle at the floor cap.
|
||||
func testAChainedLoopBacksOffToTheFloorCap() {
|
||||
var backoff = RebuildBackoff()
|
||||
var now: TimeInterval = 0
|
||||
var rebuilds = 0
|
||||
var lastDelay: TimeInterval = 0
|
||||
let end: TimeInterval = 600
|
||||
while now < end {
|
||||
lastDelay = backoff.delay(now: now)
|
||||
now += lastDelay // the scheduled rebuild fires...
|
||||
backoff.noteRebuild(at: now)
|
||||
rebuilds += 1
|
||||
now += 0.6 // ...and its fallout retriggers the recovery 0.6 s later.
|
||||
}
|
||||
XCTAssertEqual(
|
||||
lastDelay, RebuildBackoff.floorCap - 0.6, accuracy: 0.01,
|
||||
"a persistent loop should settle at one rebuild per floorCap")
|
||||
XCTAssertLessThanOrEqual(
|
||||
rebuilds, 30,
|
||||
"\(rebuilds) rebuilds in 10 min — the ladder is not escalating (the shipped flat "
|
||||
+ "floor produced ~240)")
|
||||
// And the loop's END must restore responsiveness: quiet, then a real switch.
|
||||
XCTAssertEqual(backoff.delay(now: now + 120), RebuildBackoff.debounce)
|
||||
}
|
||||
|
||||
/// The ladder's exponent is clamped — a loop that runs for hours must neither overflow nor
|
||||
/// push the interval past the cap.
|
||||
func testTheFloorNeverExceedsTheCap() {
|
||||
var backoff = RebuildBackoff()
|
||||
var now: TimeInterval = 0
|
||||
for _ in 0..<1000 {
|
||||
let delay = backoff.delay(now: now)
|
||||
XCTAssertLessThanOrEqual(delay, RebuildBackoff.floorCap)
|
||||
now += delay
|
||||
backoff.noteRebuild(at: now)
|
||||
now += 0.1
|
||||
}
|
||||
}
|
||||
|
||||
#if os(macOS)
|
||||
// MARK: - CombinedTopologyGate
|
||||
|
||||
/// The loop's fuel: re-attempting the voice-processing start that just failed. Same input
|
||||
/// device ⇒ never again.
|
||||
func testAFailureLatchesForTheDeviceItFailedOn() {
|
||||
var gate = CombinedTopologyGate()
|
||||
XCTAssertTrue(gate.shouldTry(input: 42), "an unfailed gate must allow the attempt")
|
||||
gate.noteFailure(input: 42)
|
||||
XCTAssertFalse(gate.shouldTry(input: 42))
|
||||
XCTAssertFalse(gate.shouldTry(input: 42), "the latch must hold across rebuilds")
|
||||
}
|
||||
|
||||
/// The failure is a property of the DEVICE: a different default input earns a fresh attempt,
|
||||
/// and its own failure latches again — one attempt per device change can never loop.
|
||||
func testADifferentInputDeviceEarnsOneFreshAttempt() {
|
||||
var gate = CombinedTopologyGate()
|
||||
gate.noteFailure(input: 42)
|
||||
XCTAssertTrue(gate.shouldTry(input: 7))
|
||||
gate.noteFailure(input: 7)
|
||||
XCTAssertFalse(gate.shouldTry(input: 7))
|
||||
// Back to the first device: the earlier failure may have been mid-transition — one fresh
|
||||
// attempt again, not a permanent ban.
|
||||
XCTAssertTrue(gate.shouldTry(input: 42))
|
||||
}
|
||||
|
||||
/// "No resolvable input device" is a real failure key too, distinct from "never failed".
|
||||
func testFailingWithNoInputDeviceLatchesForNoInputDevice() {
|
||||
var gate = CombinedTopologyGate()
|
||||
gate.noteFailure(input: nil)
|
||||
XCTAssertFalse(gate.shouldTry(input: nil))
|
||||
XCTAssertTrue(gate.shouldTry(input: 42), "a device appearing is a device change")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -106,6 +106,77 @@ final class AudioRingDriftTests: XCTestCase {
|
||||
"a single short read must not force a full re-prime")
|
||||
}
|
||||
|
||||
/// THE regression that made an iPad crackle where a Mac did not: the de-prime fuse must be the
|
||||
/// same SPAN OF TIME whatever the device's IO quantum. It used to be a callback COUNT (4), and
|
||||
/// a callback is not a unit of time — the same 4 was ~44 ms on a Mac's ~11 ms quantum and 20 ms
|
||||
/// on iOS, whose session asked for a 5 ms IO buffer. A Wi-Fi delivery stall therefore de-primed
|
||||
/// this ring on every bunching cycle where the identical policy rode it out elsewhere (measured
|
||||
/// on the shared Rust policy: 120 audible gaps per 10 min at a 5 ms quantum against 3 at 8 ms).
|
||||
/// Plant the defect by restoring a fixed count and the quanta below stop agreeing.
|
||||
///
|
||||
/// Mirrors `deprime_fuse_is_a_duration_not_a_callback_count` in `punktfunk_core::audio`.
|
||||
func testDeprimeFuseIsADurationNotACallbackCount() {
|
||||
let deprimeMS = 60 // AudioRing.deprimeMS / JitterTuning::COREAUDIO.deprime_ms
|
||||
let quanta = [5, 8, 10, 16, 21]
|
||||
var deprimedAt: [Int: Int] = [:]
|
||||
for quantumMS in quanta {
|
||||
let ring = AudioRing(capacity: 48_000 * channels, channels: channels)
|
||||
let want = quantumMS * perMS
|
||||
var scratch = [Float](repeating: 0, count: want)
|
||||
// Prime DEEP: the depth average is seeded with the refill, so `hollow` stays false for
|
||||
// the EWMA's whole settling second and the starvation fuse — not the hollow shortcut —
|
||||
// is what this measures.
|
||||
let big = [Float](repeating: 0.5, count: 80 * perMS)
|
||||
big.withUnsafeBufferPointer { ring.write($0.baseAddress!, count: big.count) }
|
||||
scratch.withUnsafeMutableBufferPointer { ring.read(into: $0.baseAddress!, count: want) }
|
||||
XCTAssertTrue(
|
||||
scratch.contains { $0 != 0 }, "q=\(quantumMS)ms: must play after priming")
|
||||
|
||||
// Starve on a trickle far under what the device takes: every read runs short but still
|
||||
// carries audio, so an all-zero read can only mean the ring gave up and re-primed.
|
||||
let trickle = [Float](repeating: 0.5, count: max(perMS, want / 4))
|
||||
var starvedMS = 0
|
||||
var deprimedAfterMS: Int?
|
||||
for _ in 0..<2_000 {
|
||||
trickle.withUnsafeBufferPointer {
|
||||
ring.write($0.baseAddress!, count: trickle.count)
|
||||
}
|
||||
let short = ring.bufferedSamples < want
|
||||
scratch.withUnsafeMutableBufferPointer {
|
||||
ring.read(into: $0.baseAddress!, count: want)
|
||||
}
|
||||
if scratch.allSatisfy({ $0 == 0 }) {
|
||||
deprimedAfterMS = starvedMS
|
||||
break
|
||||
}
|
||||
if short { starvedMS += quantumMS }
|
||||
}
|
||||
guard let deprimedAfterMS else {
|
||||
return XCTFail("q=\(quantumMS)ms: never de-primed at all")
|
||||
}
|
||||
deprimedAt[quantumMS] = deprimedAfterMS
|
||||
}
|
||||
|
||||
// Each quantum must give up somewhere around the fuse. The band is wide on purpose: at a
|
||||
// short quantum the HOLLOW shortcut legitimately fires a little before the fuse does (the
|
||||
// target has grown, the depth was never re-banked, so the click is taken early and spent
|
||||
// on a full refill — see `deprimeDebtMS`), and that is the policy working, not drift.
|
||||
for (q, ms) in deprimedAt.sorted(by: { $0.key < $1.key }) {
|
||||
XCTAssertTrue(
|
||||
(deprimeMS - 20...deprimeMS + 25).contains(ms),
|
||||
"q=\(q)ms de-primed after \(ms) ms, nowhere near the \(deprimeMS) ms fuse — "
|
||||
+ "\(deprimedAt.sorted { $0.key < $1.key })")
|
||||
}
|
||||
// ...and THE property: the fuse must not SCALE with the quantum. As a callback count these
|
||||
// same devices de-primed after 20/32/40/64/84 ms — a 4.2x spread, which is exactly why an
|
||||
// iPad crackled where a Mac did not. Measured in time the spread collapses to ~1.3x.
|
||||
let spread = Double(deprimedAt.values.max()!) / Double(deprimedAt.values.min()!)
|
||||
XCTAssertLessThan(
|
||||
spread, 1.6,
|
||||
"de-prime time still scales with the IO quantum (\(String(format: "%.2f", spread))x "
|
||||
+ "across \(deprimedAt.sorted { $0.key < $1.key })) — the fuse is a count again")
|
||||
}
|
||||
|
||||
/// Mirror of the Rust `target_grows_on_underruns_and_relaxes_when_quiet`, updated for
|
||||
/// near-miss growth: the drain's LAST full read (less than a frame left over) already grows
|
||||
/// the floor before anything was audible, clustered genuine underruns raise it further, and
|
||||
|
||||
@@ -3,8 +3,14 @@
|
||||
MSIX package manifest for the punktfunk Windows client (WinUI 3 via windows-reactor).
|
||||
|
||||
This is a TEMPLATE: packaging/pack-msix.ps1 substitutes {VERSION} (4-part numeric, e.g.
|
||||
0.2.137.0) and {PUBLISHER} (must EXACTLY equal the signing cert's subject DN — default
|
||||
`CN=unom` for the self-signed CI cert; a real code-signing cert just passes its own subject).
|
||||
0.2.137.0) and {PUBLISHER} (must EXACTLY equal the signing cert's subject DN — the default is
|
||||
the verified subject of the Azure `unom-io` certificate profile; the self-signed fallback mints
|
||||
a throwaway cert with that same subject so canary and release share a package identity).
|
||||
|
||||
Package identity is Name + Publisher, so changing {PUBLISHER} makes this a DIFFERENT package:
|
||||
installs of the older publisher cannot be upgraded in place and must be uninstalled first. That
|
||||
is a user-visible migration, not a packaging detail — mention it in the release notes. pack-msix.ps1
|
||||
reads the signature back off the packed .msix and fails the build if the two ever drift.
|
||||
|
||||
Why this packages cleanly even though the app was built "unpackaged": windows-reactor calls
|
||||
MddBootstrapInitialize2 with OnPackageIdentity_NOOP (crates/libs/reactor/src/app.rs), so under
|
||||
|
||||
@@ -56,34 +56,45 @@ MSIX requires a strictly 4-part numeric version. The workflow computes:
|
||||
|
||||
## Signing & install
|
||||
|
||||
CI signs every build with a **stable self-signed code-signing cert** (`CN=unom`, SHA-1
|
||||
`CD1EFDEEEC9743AFC38F56C5AF30C5A3009BE941`, valid to 2036). Its public half is checked in as
|
||||
[`punktfunk-codesign.cer`](punktfunk-codesign.cer); the private `.pfx` + password live in the
|
||||
`MSIX_CERT_PFX_B64` / `MSIX_CERT_PASSWORD` Actions secrets. Because it's the *same* cert every build,
|
||||
trusting it is **one-time, per machine** — once imported, every future build and in-place upgrade is
|
||||
trusted with no further prompt:
|
||||
CI signs every build with **Azure Artifact Signing** (formerly Trusted Signing) — account
|
||||
`unomsigning`, certificate profile `unom-io`, endpoint `https://neu.codesigning.azure.net/`. That
|
||||
chain is publicly trusted, so **there is nothing to import**:
|
||||
|
||||
```powershell
|
||||
# once per machine (elevated): trust the publisher
|
||||
Import-Certificate -FilePath .\punktfunk-codesign.cer -CertStoreLocation Cert:\LocalMachine\TrustedPeople
|
||||
# then install the package for your CPU (and re-run for each upgrade — no re-trust needed)
|
||||
# install the package for your CPU (and re-run for each upgrade)
|
||||
Add-AppxPackage -Path .\punktfunk-client-windows_<ver>_x64.msix # Intel/AMD
|
||||
Add-AppxPackage -Path .\punktfunk-client-windows_<ver>_arm64.msix # ARM64 (Snapdragon, etc.)
|
||||
```
|
||||
|
||||
The matching `.cer` is also published next to each `.msix` in the registry, so it's always at hand.
|
||||
|
||||
The MSIX declares a dependency on the Windows App SDK 2.x runtime; install
|
||||
[the App SDK runtime](https://aka.ms/windowsappsdk) if `Add-AppxPackage` reports a missing
|
||||
`Microsoft.WindowsAppRuntime.2` framework.
|
||||
|
||||
`pack-msix.ps1` signing precedence: it uses the **`MSIX_CERT_PFX_B64` / `MSIX_CERT_PASSWORD`** secrets
|
||||
when present (the stable cert above), else generates an *ephemeral* self-signed cert (forks / local
|
||||
builds without the secrets). Either way it exports the signing cert's public `.cer` for the import.
|
||||
**To move to a publicly-trusted (no-import) cert** — Azure Artifact Signing or a public OV cert —
|
||||
replace the two secrets with the new `.pfx`; the cert's subject DN must equal the manifest
|
||||
`Publisher`, so pass a matching `-Publisher` (it's stamped into the package `Identity`, and changing
|
||||
it changes the package identity → a one-time reinstall).
|
||||
### How signing resolves
|
||||
|
||||
`pack-msix.ps1` picks a backend in this order:
|
||||
|
||||
1. **Azure Artifact Signing** when `AZURE_CODESIGNING_ENDPOINT` / `_ACCOUNT` / `_PROFILE` are all
|
||||
set (the workflow sets them; they aren't secret). Credentials come from `AZURE_TENANT_ID` /
|
||||
`AZURE_CLIENT_ID` / `AZURE_CLIENT_SECRET` — the `punktfunk-ci-signing` service principal, which
|
||||
holds only the *Artifact Signing Certificate Profile Signer* role scoped to the `unom-io` profile.
|
||||
Keys are HSM-backed and never leave Azure, so there is no `.pfx` and no `.cer` is emitted.
|
||||
2. **`MSIX_CERT_PFX_B64` / `MSIX_CERT_PASSWORD`** — the older stable self-signed cert (`CN=unom`,
|
||||
public half checked in as [`punktfunk-codesign.cer`](punktfunk-codesign.cer)), kept as a fallback.
|
||||
3. An **ephemeral** self-signed cert (forks / local builds with no secrets at all).
|
||||
|
||||
Modes 2 and 3 still export a `.cer` to import into `Cert:\LocalMachine\TrustedPeople` first. On a
|
||||
`v*` tag, a build with no real signing backend **fails closed** rather than shipping a throwaway.
|
||||
|
||||
Two things about Azure mode that are easy to get wrong:
|
||||
|
||||
- **Timestamping is mandatory, not best-effort.** Azure mints a leaf cert per request that expires in
|
||||
about three days. An untimestamped signature therefore stops verifying within days of release, so
|
||||
the script refuses to retry without one (modes 2 and 3 keep the old best-effort retry).
|
||||
- **The manifest `Publisher` must equal the signer's subject exactly**, because MSIX package identity
|
||||
is Name + Publisher. The default `-Publisher` is the `unom-io` profile's verified subject; after
|
||||
signing, the script reads the signature back off the `.msix` and fails the build on any drift.
|
||||
Changing it makes a *different* package — existing installs must be uninstalled, not upgraded.
|
||||
|
||||
## Building locally
|
||||
|
||||
|
||||
@@ -13,15 +13,22 @@
|
||||
packaging/windows/pack-host-installer.ps1 still ships them for its amf-qsv encode path.
|
||||
|
||||
Signing cert precedence:
|
||||
0. Azure Artifact Signing (formerly Trusted Signing) when AZURE_CODESIGNING_ENDPOINT/_ACCOUNT/
|
||||
_PROFILE are all set. HSM-backed, so there is no .pfx and nothing to export: the chain is
|
||||
publicly trusted, so no .cer is produced and MSIX_CER_PATH stays unset.
|
||||
1. -PfxBase64 / -PfxPassword (a real or shared code-signing cert, e.g. from CI secrets) — the
|
||||
cert's subject DN MUST match -Publisher (which is stamped into the manifest Identity).
|
||||
2. otherwise an EPHEMERAL self-signed code-signing cert with subject = -Publisher is generated
|
||||
in-process. The package installs only where that cert is trusted, so the matching public
|
||||
.cer is exported next to the .msix for the user to import (Trusted People) before install.
|
||||
Swap in a real cert later with zero manifest changes — just pass -PfxBase64/-Publisher.
|
||||
This fallback is for canary/CI/dev ONLY: on a v* tag build a missing cert is a hard failure
|
||||
(-RequireSignedCert), never a silent downgrade to a throwaway cert.
|
||||
|
||||
WHICHEVER mode runs, the signed .msix is read back and its signer subject compared to -Publisher;
|
||||
a mismatch fails the build. MSIX package identity is Name + Publisher, so a publisher that does
|
||||
not match the signer is not a cosmetic problem — Add-AppxPackage rejects the package outright,
|
||||
and it would only be discovered by a user trying to install the release.
|
||||
|
||||
Run on the Windows runner (or the dev VM) with the MSVC/Windows SDK present.
|
||||
|
||||
.EXAMPLE
|
||||
@@ -36,9 +43,21 @@ param(
|
||||
[Parameter(Mandatory = $true)][string]$TargetDir, # cargo --release output dir (has the exe)
|
||||
[ValidateSet('x64', 'arm64')][string]$Arch = 'x64', # package ProcessorArchitecture + artifact suffix
|
||||
[string]$OutDir = (Join-Path $TargetDir 'msix'),
|
||||
[string]$Publisher = 'CN=unom', # MUST equal the signing cert subject DN
|
||||
# MUST equal the signing cert subject DN — this is the verified subject the Azure 'unom-io'
|
||||
# certificate profile issues. The 'ü' is written as an escape, not a literal: this file is UTF-8
|
||||
# with no BOM, and read by anything other than pwsh 7 a literal would silently mojibake into a
|
||||
# publisher that no longer matches the signer, which surfaces only as an Add-AppxPackage refusal
|
||||
# on a user's machine. Verified against the real signer after signing below.
|
||||
[string]$Publisher = "CN=unom - Enrico B$([char]0xFC)hler, O=unom - Enrico B$([char]0xFC)hler, L=Rottweil, S=Baden-W$([char]0xFC)rttemberg, C=DE",
|
||||
[string]$PfxBase64 = $env:MSIX_CERT_PFX_B64, # optional: base64 of a code-signing .pfx
|
||||
[string]$PfxPassword = $env:MSIX_CERT_PASSWORD,
|
||||
# Azure Artifact Signing. All three select it, ahead of any .pfx. Credentials arrive through the
|
||||
# environment via DefaultAzureCredential (AZURE_TENANT_ID / AZURE_CLIENT_ID / AZURE_CLIENT_SECRET)
|
||||
# rather than as arguments, so they cannot leak into a process listing or a transcript.
|
||||
[string]$AzureEndpoint = $env:AZURE_CODESIGNING_ENDPOINT, # e.g. https://neu.codesigning.azure.net/
|
||||
[string]$AzureAccount = $env:AZURE_CODESIGNING_ACCOUNT, # signing account name
|
||||
[string]$AzureProfile = $env:AZURE_CODESIGNING_PROFILE, # certificate profile name
|
||||
[string]$AzureDlib = $env:AZURE_CODESIGNING_DLIB, # path to Azure.CodeSigning.Dlib.dll
|
||||
# 'auto' (default) = required iff this is a v* tag build; 'true'/'false' to force. See below.
|
||||
[ValidateSet('auto', 'true', 'false')][string]$RequireSignedCert = 'auto'
|
||||
)
|
||||
@@ -64,6 +83,28 @@ function Find-SdkTool([string]$name) {
|
||||
if (-not $hit) { throw "$name not found under $root — install the Windows 10/11 SDK." }
|
||||
$hit.FullName
|
||||
}
|
||||
# Azure.CodeSigning.Dlib.dll ships in the Microsoft.Trusted.Signing.Client NuGet package, which has
|
||||
# no installer and no fixed location — hence an explicit override first, then the paths the runner
|
||||
# setup uses (packaging/windows/README.md). Newest wins, so a package update needs no edit here.
|
||||
function Find-AzureDlib([string]$Explicit) {
|
||||
if ($Explicit) {
|
||||
if (-not (Test-Path $Explicit)) { throw "AZURE_CODESIGNING_DLIB points at a missing file: $Explicit" }
|
||||
return (Resolve-Path $Explicit).Path
|
||||
}
|
||||
$roots = @(
|
||||
(Join-Path $env:USERPROFILE '.nuget\packages\microsoft.trusted.signing.client'),
|
||||
'C:\trusted-signing\microsoft.trusted.signing.client'
|
||||
) | Where-Object { $_ -and (Test-Path $_) }
|
||||
$hit = $roots | ForEach-Object { Get-ChildItem -Path $_ -Recurse -Filter 'Azure.CodeSigning.Dlib.dll' -ErrorAction SilentlyContinue } |
|
||||
Where-Object { $_.FullName -match '\\bin\\x64\\' } |
|
||||
Sort-Object LastWriteTime | Select-Object -Last 1
|
||||
if (-not $hit) {
|
||||
throw ("Azure.CodeSigning.Dlib.dll not found. Install the signing client on this box, e.g. " +
|
||||
"``nuget install Microsoft.Trusted.Signing.Client -OutputDirectory " +
|
||||
"`$env:USERPROFILE\.nuget\packages``, or set AZURE_CODESIGNING_DLIB to its full path.")
|
||||
}
|
||||
$hit.FullName
|
||||
}
|
||||
$makeappx = Find-SdkTool 'makeappx.exe'
|
||||
$signtool = Find-SdkTool 'signtool.exe'
|
||||
Write-Host "makeappx: $makeappx"
|
||||
@@ -159,13 +200,34 @@ $requireCert = if ($RequireSignedCert -eq 'auto') { $env:GITHUB_REF -like 'refs/
|
||||
else { [Convert]::ToBoolean($RequireSignedCert) }
|
||||
$pfxPath = Join-Path $OutDir 'signing.pfx'
|
||||
$cerPath = Join-Path $OutDir "punktfunk-client-windows_${Version}_${Arch}.cer"
|
||||
if ($PfxBase64) {
|
||||
$azureMetadata = Join-Path $OutDir 'azure-codesigning.json'
|
||||
$signMode = 'selfsigned'
|
||||
if ($AzureEndpoint -and $AzureAccount -and $AzureProfile) {
|
||||
$signMode = 'azure'
|
||||
$AzureDlib = Find-AzureDlib $AzureDlib
|
||||
# signtool takes the account/profile from this file (/dmdf), not the command line.
|
||||
@{
|
||||
Endpoint = $AzureEndpoint
|
||||
CodeSigningAccountName = $AzureAccount
|
||||
CertificateProfileName = $AzureProfile
|
||||
} | ConvertTo-Json | Set-Content -Path $azureMetadata -Encoding utf8
|
||||
Write-Host "signing via Azure Artifact Signing: $AzureAccount/$AzureProfile at $AzureEndpoint"
|
||||
Write-Host " dlib: $AzureDlib"
|
||||
foreach ($v in 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET') {
|
||||
if (-not [Environment]::GetEnvironmentVariable($v)) {
|
||||
throw ("Azure signing selected but $v is not set. The dlib authenticates with " +
|
||||
"DefaultAzureCredential; without the service-principal trio it falls through to an " +
|
||||
"interactive login that cannot complete on a runner and hangs the build.")
|
||||
}
|
||||
}
|
||||
} elseif ($PfxBase64) {
|
||||
$signMode = 'pfx'
|
||||
Write-Host "signing with supplied code-signing cert (MSIX_CERT_PFX_B64)"
|
||||
[IO.File]::WriteAllBytes($pfxPath, [Convert]::FromBase64String($PfxBase64))
|
||||
} elseif ($requireCert) {
|
||||
throw ("release build ($env:GITHUB_REF) with no MSIX_CERT_PFX_B64 — refusing to fall back to an " +
|
||||
"ephemeral self-signed cert. Restore the MSIX_CERT_PFX_B64 / MSIX_CERT_PASSWORD repo " +
|
||||
"secrets, or pass -RequireSignedCert false if this really is a test build.")
|
||||
throw ("release build ($env:GITHUB_REF) with neither AZURE_CODESIGNING_* nor MSIX_CERT_PFX_B64 — " +
|
||||
"refusing to fall back to an ephemeral self-signed cert. Restore the signing secrets " +
|
||||
"(packaging/windows/README.md), or pass -RequireSignedCert false if this really is a test build.")
|
||||
} else {
|
||||
Write-Host "no MSIX_CERT_PFX_B64 -> generating an ephemeral self-signed cert (subject $Publisher)"
|
||||
if (-not $PfxPassword) { $PfxPassword = 'punktfunk' }
|
||||
@@ -178,35 +240,80 @@ if ($PfxBase64) {
|
||||
Remove-Item "Cert:\CurrentUser\My\$($tmp.Thumbprint)" -Force
|
||||
}
|
||||
|
||||
# Always export the public .cer from the pfx. For a self-signed / private-trust cert it's the file
|
||||
# users import once (Trusted People) — a STABLE cert (same pfx every build via the secret) means that
|
||||
# import is a one-time, per-machine step that keeps working across upgrades. For a public-CA cert
|
||||
# it's just an unused extra (harmless). The manifest Publisher must equal the cert's subject DN.
|
||||
$pwsec = if ($PfxPassword) { ConvertTo-SecureString -String $PfxPassword -Force -AsPlainText } else { $null }
|
||||
$pubCert = if ($pwsec) { Get-PfxCertificate -FilePath $pfxPath -Password $pwsec } else { Get-PfxCertificate -FilePath $pfxPath }
|
||||
Export-Certificate -Cert $pubCert -FilePath $cerPath | Out-Null
|
||||
Write-Host "signing cert subject=$($pubCert.Subject) thumbprint=$($pubCert.Thumbprint)"
|
||||
if ($pubCert.Subject -ne $Publisher) {
|
||||
Write-Warning "cert subject '$($pubCert.Subject)' != manifest Publisher '$Publisher' — Add-AppxPackage will reject the mismatch. Pass -Publisher '$($pubCert.Subject)'."
|
||||
# Export the public .cer from the pfx. For a self-signed / private-trust cert it's the file users
|
||||
# import once (Trusted People) — a STABLE cert (same pfx every build via the secret) means that
|
||||
# import is a one-time, per-machine step that keeps working across upgrades. Azure signing is
|
||||
# HSM-backed: there is no pfx to read and its chain is publicly trusted, so no .cer is produced.
|
||||
if ($signMode -ne 'azure') {
|
||||
$pwsec = if ($PfxPassword) { ConvertTo-SecureString -String $PfxPassword -Force -AsPlainText } else { $null }
|
||||
$pubCert = if ($pwsec) { Get-PfxCertificate -FilePath $pfxPath -Password $pwsec } else { Get-PfxCertificate -FilePath $pfxPath }
|
||||
Export-Certificate -Cert $pubCert -FilePath $cerPath | Out-Null
|
||||
Write-Host "signing cert subject=$($pubCert.Subject) thumbprint=$($pubCert.Thumbprint)"
|
||||
}
|
||||
|
||||
# --- sign (timestamp best-effort) ---
|
||||
$signArgs = @('sign', '/fd', 'SHA256', '/f', $pfxPath)
|
||||
if ($PfxPassword) { $signArgs += @('/p', $PfxPassword) }
|
||||
& $signtool ($signArgs + @('/tr', 'http://timestamp.digicert.com', '/td', 'SHA256', $msix))
|
||||
# --- sign ---
|
||||
# The timestamp is best-effort for a .pfx whose cert outlives the release, but MANDATORY under Azure
|
||||
# signing: those leaf certs are minted per request and expire in ~3 days, so an untimestamped
|
||||
# signature stops verifying within days of shipping. Retrying without one there would produce a
|
||||
# package that installs on the runner and fails for every user that weekend — so the fallback is
|
||||
# gated on the mode rather than applied blindly.
|
||||
if ($signMode -eq 'azure') {
|
||||
$signArgs = @('sign', '/fd', 'SHA256', '/dlib', $AzureDlib, '/dmdf', $azureMetadata)
|
||||
$ts = 'http://timestamp.acs.microsoft.com'
|
||||
} else {
|
||||
$signArgs = @('sign', '/fd', 'SHA256', '/f', $pfxPath)
|
||||
if ($PfxPassword) { $signArgs += @('/p', $PfxPassword) }
|
||||
$ts = 'http://timestamp.digicert.com'
|
||||
}
|
||||
& $signtool ($signArgs + @('/tr', $ts, '/td', 'SHA256', $msix))
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
if ($signMode -eq 'azure') {
|
||||
throw ("timestamped sign failed ($LASTEXITCODE) — NOT retrying without a timestamp. An Azure " +
|
||||
"signing cert is valid for ~3 days; an untimestamped signature would go untrusted " +
|
||||
"within days of release.")
|
||||
}
|
||||
Write-Warning "timestamped sign failed — retrying without a timestamp"
|
||||
& $signtool ($signArgs + @($msix))
|
||||
if ($LASTEXITCODE -ne 0) { throw "signtool sign failed ($LASTEXITCODE)" }
|
||||
}
|
||||
Remove-Item $pfxPath -Force -ErrorAction SilentlyContinue
|
||||
Remove-Item $azureMetadata -Force -ErrorAction SilentlyContinue
|
||||
|
||||
# Read the signature back off the packed .msix and hold it against the manifest Publisher. MSIX
|
||||
# package identity is Name + Publisher, so a publisher that doesn't match the signer isn't cosmetic:
|
||||
# Add-AppxPackage refuses the package outright. Checking the ACTUAL signer (rather than a pfx we
|
||||
# happen to hold) is the only form of this check that works in every signing mode, and failing the
|
||||
# build here is the difference between a red pipeline and a release nobody can install.
|
||||
# Deliberately asymmetric: a subject we CAN read and that DISAGREES is a hard failure, but a subject
|
||||
# we cannot read at all is only a warning. Get-AuthenticodeSignature's support for the .msix/.appx
|
||||
# subject interface varies by Windows version, and signtool has already reported success by this
|
||||
# point — turning "the check could not run" into a build break would trade a real defect we catch for
|
||||
# an imaginary one we invent.
|
||||
$signerSubject = $null
|
||||
try { $signerSubject = (Get-AuthenticodeSignature $msix).SignerCertificate.Subject } catch { }
|
||||
if (-not $signerSubject) {
|
||||
Write-Warning ("could not read a signer subject back from $msix, so Publisher/signer agreement is " +
|
||||
"UNVERIFIED on this box. If the package is rejected at Add-AppxPackage time, compare " +
|
||||
"`signtool verify /pa /v` against the manifest Publisher '$Publisher' by hand.")
|
||||
} elseif ($signerSubject -ne $Publisher) {
|
||||
throw ("signer subject does not match the manifest Publisher, so this package cannot install:`n" +
|
||||
" signer : '$signerSubject'`n" +
|
||||
" Publisher : '$Publisher'`n" +
|
||||
"Pass -Publisher '$signerSubject' (or fix the certificate profile) and repack.")
|
||||
} else {
|
||||
Write-Host "verified signer subject matches manifest Publisher: $signerSubject"
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "==> MSIX: $msix"
|
||||
Write-Host "==> trust the cert once per machine (then it stays trusted across all future builds):"
|
||||
Write-Host " Import-Certificate -FilePath '$cerPath' -CertStoreLocation Cert:\LocalMachine\TrustedPeople"
|
||||
if ($signMode -eq 'azure') {
|
||||
Write-Host "==> signed by a publicly trusted CA — nothing for users to import."
|
||||
} else {
|
||||
Write-Host "==> trust the cert once per machine (then it stays trusted across all future builds):"
|
||||
Write-Host " Import-Certificate -FilePath '$cerPath' -CertStoreLocation Cert:\LocalMachine\TrustedPeople"
|
||||
}
|
||||
# emit paths for the workflow to publish (only under CI, where GITHUB_ENV is set)
|
||||
if ($env:GITHUB_ENV) {
|
||||
"MSIX_PATH=$msix" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8
|
||||
"MSIX_CER_PATH=$cerPath" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8
|
||||
if ($signMode -ne 'azure') { "MSIX_CER_PATH=$cerPath" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8 }
|
||||
}
|
||||
|
||||
@@ -180,6 +180,23 @@ pub struct Stats {
|
||||
/// decoder's submission returning in ~0.1 ms is not "decoded"); software measures
|
||||
/// the synchronous CPU decode.
|
||||
pub decode_ms: f32,
|
||||
/// Whether `decode_ms` OVERLAPS the presenter's `display` stage instead of tiling
|
||||
/// with it — true on the asynchronous native-Vulkan rung, false everywhere else.
|
||||
///
|
||||
/// The other stages are a per-frame partition of `e2e`: `pts →(host+net)→ received
|
||||
/// →(decode)→ decoded →(display)→ displayed`. That holds while `decoded` is a
|
||||
/// COMPLETION stamp, which it is on the synchronous rungs. On the native-Vulkan rung
|
||||
/// `receive_frame` returns at SUBMISSION (~0.1 ms) and the stamp shipped to the
|
||||
/// presenter is taken there, so the GPU decode happens INSIDE the `display` stage —
|
||||
/// `host+net` and `display` already tile `e2e` between them, and `decode` (measured
|
||||
/// received → fence-complete) re-counts the GPU work that `display` contains.
|
||||
///
|
||||
/// A 2026-08-13 field report read the row as a breakdown and asked why the parts did
|
||||
/// not add up: `host 5.4 · net 0.3 · decode 6.6 · display 1.4` against `e2e 8.1`. They
|
||||
/// do add up — without `decode` (5.4 + 0.3 + 1.4 ≈ 8.1). The figure is a true reading
|
||||
/// of a real quantity sitting in a row that reads like a partition, so the OSD renders
|
||||
/// it off that line rather than beside stages it does not tile with.
|
||||
pub decode_overlaps_display: bool,
|
||||
/// Unrecoverable network frame drops this window, and their share of
|
||||
/// received+lost (%). The OSD renders the counter line only when nonzero.
|
||||
pub lost: u32,
|
||||
@@ -770,6 +787,10 @@ fn pump(
|
||||
// corrected), `decode` = received→decoded (client-local). p50 per 1 s window.
|
||||
let mut hostnet_us: Vec<u64> = Vec::with_capacity(256);
|
||||
let mut decode_us: Vec<u64> = Vec::with_capacity(256);
|
||||
// Whether this window's decode samples came from the async (submission-stamped) rung, so
|
||||
// the OSD keeps them off the partition line. Latches per window alongside the samples,
|
||||
// rather than being read off the rung name — a demote mid-window changes both together.
|
||||
let mut decode_overlaps = false;
|
||||
// Adaptive bitrate: report the decode stage back to the core controller only when it's armed
|
||||
// (Automatic, non-PyroWave). Constant for the session — resolve once, gate the per-frame call.
|
||||
let wants_decode = connector.wants_decode_latency();
|
||||
@@ -1118,6 +1139,12 @@ fn pump(
|
||||
// `decode` stage: received→decode COMPLETE, single clock.
|
||||
match hw_fence {
|
||||
Some((sem, value)) => {
|
||||
// A fence means `decoded_ns` above was stamped at SUBMISSION, so
|
||||
// the GPU decode lands inside the presenter's `display` stage and
|
||||
// this figure re-counts it: it does NOT tile with the others.
|
||||
// Recorded so the OSD can render it off the partition line
|
||||
// (`Stats::decode_overlaps_display`).
|
||||
decode_overlaps = true;
|
||||
if decode_us.is_empty()
|
||||
&& decoder.wait_hw_decoded(sem, value, 50_000_000)
|
||||
{
|
||||
@@ -1433,6 +1460,7 @@ fn pump(
|
||||
host_pace_ms: pace_p50 as f32 / 1000.0,
|
||||
staged,
|
||||
decode_ms: dec_p50 as f32 / 1000.0,
|
||||
decode_overlaps_display: decode_overlaps,
|
||||
lost,
|
||||
lost_pct: if lost > 0 {
|
||||
lost as f32 * 100.0 / (frames_n + lost) as f32
|
||||
@@ -1461,6 +1489,7 @@ fn pump(
|
||||
bytes_n = 0;
|
||||
hostnet_us.clear();
|
||||
decode_us.clear();
|
||||
decode_overlaps = false;
|
||||
host_us_win.clear();
|
||||
net_us_win.clear();
|
||||
queue_us_win.clear();
|
||||
|
||||
@@ -245,11 +245,22 @@ impl Overlay for SkiaOverlay {
|
||||
shared.queue_family_index as usize,
|
||||
),
|
||||
&get_proc,
|
||||
// `None` leaves Skia's `fMaxAPIVersion` at its `0` sentinel, so it caps entry-point
|
||||
// validation at whatever `vkEnumerateInstanceVersion()` reports — byte-for-byte what
|
||||
// the (now removed) `BackendContext::new` did. The presenter owns the instance and its
|
||||
// `VkApplicationInfo`, so pinning a version here would just duplicate its choice.
|
||||
None,
|
||||
// 🛑 MUST be the presenter's declared version, never `None`.
|
||||
//
|
||||
// `None` leaves Skia's `fMaxAPIVersion` at its `0` sentinel, which makes Skia fall
|
||||
// back to `vkEnumerateInstanceVersion()` — the LOADER's ceiling, not ours. Those are
|
||||
// not the same number: the presenter asks for 1.3, while a current Mesa loader answers
|
||||
// 1.4 (1.4.321 on SteamOS 3.7). Skia then validates a 1.4 function table against an
|
||||
// instance that only ever promised 1.3, `vkGetDeviceProcAddr` returns null for the
|
||||
// entry points above 1.3, validation fails, and `make_vulkan` hands back `None` — so
|
||||
// the console UI refuses to start and `--browse` dies with it.
|
||||
//
|
||||
// ⚠ The `0` sentinel was harmless at skia-safe 0.87 (that Skia knew nothing of 1.4, so
|
||||
// clamping to the loader was a no-op) and the 0.99 migration preserved it as
|
||||
// "byte-for-byte what `BackendContext::new` did" — true of the VALUE, false of the
|
||||
// BEHAVIOUR. It shipped in 0.28.0 and took the Deck's launcher out. 0.99's own doc for
|
||||
// this parameter says it should match `VkApplicationInfo::apiVersion`; this is that.
|
||||
Some(skvk::Version::from(shared.api_version)),
|
||||
);
|
||||
// SAFETY: the instance/physical-device/device handles come from `shared`, which owns them
|
||||
// and outlives this backend context, and `get_proc` above resolves through those same
|
||||
|
||||
@@ -1016,11 +1016,27 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Ladder rung: the binary exists and runs but is not a worker. `/bin/false` exits at once, so
|
||||
/// the handshake reads EOF — the same rung a worker that dies during Vulkan bring-up takes.
|
||||
/// A binary that exists, execs, and exits at once. Resolved off `PATH` rather than hardcoded
|
||||
/// to `/bin/false`: NixOS ships only `/bin/sh` in `/bin`, and `PinnedExe::open` needs a real
|
||||
/// path (so a bare name cannot stand in for one — it would fail the OPEN and take the
|
||||
/// spawn-failure rung instead of the handshake rung this exercises).
|
||||
fn a_binary_that_exits_immediately() -> PathBuf {
|
||||
std::env::var_os("PATH")
|
||||
.as_deref()
|
||||
.map(std::env::split_paths)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|d| d.join("false"))
|
||||
.find(|p| p.is_file())
|
||||
.expect("a `false` binary on PATH")
|
||||
}
|
||||
|
||||
/// Ladder rung: the binary exists and runs but is not a worker. It exits at once, so the
|
||||
/// handshake reads EOF — the same rung a worker that dies during Vulkan bring-up takes.
|
||||
#[test]
|
||||
fn a_worker_that_exits_immediately_is_a_handshake_failure() {
|
||||
let err = spawn_link(Path::new("/bin/false"), ¶ms(), 40_000_000).unwrap_err();
|
||||
let err =
|
||||
spawn_link(&a_binary_that_exits_immediately(), ¶ms(), 40_000_000).unwrap_err();
|
||||
let text = format!("{err:#}");
|
||||
assert!(
|
||||
text.contains("handshake"),
|
||||
|
||||
@@ -214,6 +214,15 @@ pub struct HostConfig {
|
||||
/// showing the wrong monitor is worse than showing none). Linux-only today; see
|
||||
/// `design/per-monitor-portal-capture.md`.
|
||||
pub capture_monitor: Option<String>,
|
||||
/// `PUNKTFUNK_PORTAL_CURSOR_MODE` — `auto` (default) · `hidden` · `embedded` · `metadata`.
|
||||
/// Pin the ScreenCast cursor mode the Linux portal backends PREFER, instead of the one the
|
||||
/// session negotiates (`metadata` when the client draws the pointer itself, `embedded`
|
||||
/// otherwise). The pin is a preference, not a command: it still runs through
|
||||
/// `portal_cursor::pick`, so it can never ask a backend for a mode the backend does not
|
||||
/// advertise — that closes the session rather than degrading, which is the failure this knob
|
||||
/// sits next to. Exists for the backend that advertises a mode it implements badly, where
|
||||
/// negotiation has nothing to go on; `embedded` is the safe answer there.
|
||||
pub portal_cursor_mode: Option<String>,
|
||||
/// `PUNKTFUNK_COMPOSITOR` — explicit compositor override (operator/CI/test). NOT the runtime-detected
|
||||
/// session — this one is a constant operator knob; `apply_session_env` never writes it.
|
||||
pub compositor: Option<String>,
|
||||
@@ -262,10 +271,12 @@ pub struct HostConfig {
|
||||
/// spawn flags included.
|
||||
pub gamescope_hdr: bool,
|
||||
/// `PUNKTFUNK_GAMESCOPE_SDR_NITS` — the luminance SDR content is mapped to inside the PQ
|
||||
/// container of an HDR gamescope session (gamescope's `--hdr-sdr-content-nits`, default 400).
|
||||
/// container of an HDR gamescope session (gamescope's `--hdr-sdr-content-nits`).
|
||||
/// An HDR stream carries the desktop, the Steam overlay and any SDR game through the same PQ
|
||||
/// encode, so this is the knob that decides how bright "white" looks on the client's panel.
|
||||
/// `None` = leave gamescope's own default.
|
||||
/// `None` = 203 nits, BT.2408 reference white, which is what our clients decode against —
|
||||
/// NOT gamescope's own default of 400, which sits nearly a stop above it. See `pf-vdisplay`'s
|
||||
/// `SDR_REFERENCE_WHITE_NITS` for why the host pins this rather than letting it float.
|
||||
pub gamescope_sdr_nits: Option<u32>,
|
||||
/// `PUNKTFUNK_GAMESCOPE_BIND` — may the host bind the patched gamescope over
|
||||
/// `/usr/bin/gamescope` inside the session unit's mount namespace? That redirect is the ONLY
|
||||
@@ -399,6 +410,12 @@ impl HostConfig {
|
||||
capture_monitor: val("PUNKTFUNK_CAPTURE_MONITOR")
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty()),
|
||||
// Same emptied-to-None rule: a bare `PUNKTFUNK_PORTAL_CURSOR_MODE=` left in a host.env
|
||||
// means "not set", not an unrecognised value to warn about. The spellings are parsed
|
||||
// (and warned about) at the use site, `pf-vdisplay`'s `portal_cursor::want`.
|
||||
portal_cursor_mode: val("PUNKTFUNK_PORTAL_CURSOR_MODE")
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty()),
|
||||
compositor: val("PUNKTFUNK_COMPOSITOR"),
|
||||
gamepad: val("PUNKTFUNK_GAMEPAD"),
|
||||
vdisplay: val("PUNKTFUNK_VDISPLAY"),
|
||||
|
||||
@@ -26,6 +26,17 @@ pub struct SharedDevice {
|
||||
/// with [`pf_client_core::video::QueueLock::guard`], whose RAII form is what every
|
||||
/// Rust caller wants.
|
||||
pub queue_lock: std::sync::Arc<pf_client_core::video::QueueLock>,
|
||||
/// The Vulkan version an overlay renderer may size its function table to — the lower of
|
||||
/// [`crate::vk::INSTANCE_API_VERSION`] (what `VkApplicationInfo::apiVersion` declared for
|
||||
/// `instance`) and what the loader provides.
|
||||
///
|
||||
/// **Cap yourself here; do not ask the loader yourself.** Entry points above this version
|
||||
/// were never promised to us — `vkGetDeviceProcAddr` returns null for them — so a renderer
|
||||
/// that probes `vkEnumerateInstanceVersion` instead (a current Mesa answers 1.4 where we
|
||||
/// asked for 1.3) validates a function table it can never fill and refuses to start. That
|
||||
/// is exactly how the Skia console UI died in 0.28.0; see the note in `pf-console-ui`'s
|
||||
/// `SkiaOverlay::init`.
|
||||
pub api_version: u32,
|
||||
}
|
||||
|
||||
/// What the overlay may draw this frame — composed by the run loop from session state.
|
||||
|
||||
@@ -2847,10 +2847,21 @@ fn stats_text(
|
||||
} else {
|
||||
text.push_str(&format!(" · host+net {:.1}", s.host_net_ms));
|
||||
}
|
||||
text.push_str(&format!(
|
||||
" · decode {:.1} · display {:.1} ms",
|
||||
s.decode_ms, p.display_ms
|
||||
));
|
||||
// `decode` joins the partition line ONLY where it is one. The stages tile `e2e`
|
||||
// per frame — pts →(host+net)→ received →(decode)→ decoded →(display)→ displayed —
|
||||
// and that holds while `decoded` is a completion stamp. On the async native-Vulkan
|
||||
// rung it is a SUBMISSION stamp, so the GPU decode sits inside `display` and this
|
||||
// figure re-counts it; printing the two side by side invited exactly the reading a
|
||||
// 2026-08-13 field report made ("decode 6.6 next to display 1.4 and e2e 8.1 — the
|
||||
// parts don't add up"). They add up without it. See `Stats::decode_overlaps_display`.
|
||||
if s.decode_overlaps_display {
|
||||
text.push_str(&format!(" · display {:.1} ms", p.display_ms));
|
||||
} else {
|
||||
text.push_str(&format!(
|
||||
" · decode {:.1} · display {:.1} ms",
|
||||
s.decode_ms, p.display_ms
|
||||
));
|
||||
}
|
||||
// The display split (WP4). Only with true on-glass stamps — without them the
|
||||
// two halves are not separable and the unsplit figure stands alone rather than
|
||||
// implying a zero latch.
|
||||
@@ -2860,6 +2871,19 @@ fn stats_text(
|
||||
p.pace_ms, p.latch_ms
|
||||
));
|
||||
}
|
||||
// …and gets its own line there, qualified. Two things a reader has to know before
|
||||
// the number means anything: it is ONE frame per window on this rung (a per-frame
|
||||
// fence wait would serialise the decode pipeline — see the sampling comment in
|
||||
// `pf_client_core::session`), so it is a single sample rather than the p50 every
|
||||
// other figure here is; and it is already inside `display`, so adding it double-
|
||||
// counts. Suppressed at 0, which is the "every fence wait timed out" case rather
|
||||
// than a real zero.
|
||||
if s.decode_overlaps_display && s.decode_ms > 0.0 {
|
||||
text.push_str(&format!(
|
||||
"\ndecode {:.1} ms (1 sample, inside display — not additive)",
|
||||
s.decode_ms
|
||||
));
|
||||
}
|
||||
// Extended 0xCF host-stage split (T0.1): its own line so the per-stage attribution
|
||||
// (queue → encode → seal/xfer → pace) reads as the host pipeline in order.
|
||||
if s.staged {
|
||||
@@ -3275,6 +3299,10 @@ mod tests {
|
||||
host_pace_ms: 0.3,
|
||||
staged: true,
|
||||
decode_ms: 1.8,
|
||||
// The fixture is the SYNCHRONOUS shape, so `decode` stays on the partition
|
||||
// line and the existing assertions keep their meaning; the async rung's
|
||||
// split-out rendering is exercised separately below.
|
||||
decode_overlaps_display: false,
|
||||
lost: 3,
|
||||
lost_pct: 0.4,
|
||||
mic_sent: 0,
|
||||
@@ -3414,6 +3442,70 @@ mod tests {
|
||||
assert!(!normal.contains("present:") && !normal.contains("pace"));
|
||||
}
|
||||
|
||||
/// The stage line must stay a PARTITION of `e2e`. On the synchronous rungs `decode` is
|
||||
/// one of its terms; on the asynchronous native-Vulkan rung the shipped `decoded` stamp
|
||||
/// is taken at submission, so the GPU decode is inside `display` and `decode` re-counts
|
||||
/// it. A 2026-08-13 field report read `host 5.4 · net 0.3 · decode 6.6 · display 1.4`
|
||||
/// against `e2e 8.1` as a breakdown and asked why it did not add up — it adds up without
|
||||
/// `decode`. So the figure leaves that line and says what it is instead of sitting beside
|
||||
/// stages it does not tile with.
|
||||
#[test]
|
||||
fn an_overlapping_decode_figure_leaves_the_stage_line_and_says_so() {
|
||||
let (mut s, p) = sample();
|
||||
|
||||
// Synchronous: unchanged, and specifically still INLINE on the stage line.
|
||||
assert!(!s.decode_overlaps_display, "the fixture is the sync shape");
|
||||
let sync = stats_text(
|
||||
StatsVerbosity::Detailed,
|
||||
"m",
|
||||
&s,
|
||||
&p,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
None,
|
||||
);
|
||||
assert!(sync.contains("host 1.2 · net 0.9 · decode 1.8 · display 1.1 ms"));
|
||||
assert!(!sync.contains("not additive"));
|
||||
|
||||
// Asynchronous: off the stage line, which still reads as a partition…
|
||||
s.decode_overlaps_display = true;
|
||||
let async_ = stats_text(
|
||||
StatsVerbosity::Detailed,
|
||||
"m",
|
||||
&s,
|
||||
&p,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
None,
|
||||
);
|
||||
assert!(
|
||||
async_.contains("host 1.2 · net 0.9 · display 1.1 ms"),
|
||||
"the stage line keeps only terms that tile e2e: {async_}"
|
||||
);
|
||||
// …and the number survives, qualified by BOTH caveats a reader needs.
|
||||
assert!(async_.contains("\ndecode 1.8 ms (1 sample, inside display — not additive)"));
|
||||
|
||||
// A window whose every fence wait timed out reports 0, which is an absence of
|
||||
// measurement rather than an instant decode — it must not render as either.
|
||||
s.decode_ms = 0.0;
|
||||
let none = stats_text(
|
||||
StatsVerbosity::Detailed,
|
||||
"m",
|
||||
&s,
|
||||
&p,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
None,
|
||||
);
|
||||
assert!(
|
||||
!none.contains("decode"),
|
||||
"a 0 sample renders nothing: {none}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The decode-integrity line (M4) — the whole point of which is that it can tell
|
||||
/// three states apart that all look identical as "no complaints today":
|
||||
///
|
||||
|
||||
@@ -43,6 +43,24 @@ mod setup;
|
||||
|
||||
pub use setup::{list_adapters, probe_decode, AdapterDecode, PresentPref};
|
||||
|
||||
/// The Vulkan version every instance this crate creates declares in
|
||||
/// `VkApplicationInfo::apiVersion`.
|
||||
///
|
||||
/// 1.3 because Vulkan Video decode and PyroWave's compute kernels both need a 1.3 device.
|
||||
/// It is deliberately a CEILING as well as a floor: the loader is routinely newer (Mesa 26
|
||||
/// answers `vkEnumerateInstanceVersion` with 1.4), but we only ever promised 1.3, so the
|
||||
/// entry points above it are not ours to call. Anything that must know how far the device
|
||||
/// side reaches — notably an overlay renderer sizing its own function table — reads this
|
||||
/// through [`crate::overlay::SharedDevice::api_version`] rather than asking the loader.
|
||||
pub const INSTANCE_API_VERSION: u32 = vk::API_VERSION_1_3;
|
||||
|
||||
/// The clamp behind [`Presenter::overlay_api_version`], split out so the decision is provable
|
||||
/// without a device: the answer is the lower of what we declared and what the loader reports,
|
||||
/// and a loader too old to answer at all (`None`) can only be a 1.0 one.
|
||||
fn overlay_api_version_of(declared: u32, loader: Option<u32>) -> u32 {
|
||||
declared.min(loader.unwrap_or(vk::API_VERSION_1_0))
|
||||
}
|
||||
|
||||
/// The video-format probe behind [`AdapterDecode::formats`], re-exported so a caller
|
||||
/// that prints the report does not need its own `pf-vkdecode` dependency (and cannot
|
||||
/// end up printing a DIFFERENT crate version's idea of the flag names).
|
||||
@@ -387,8 +405,30 @@ impl Presenter {
|
||||
queue: self.queue,
|
||||
queue_family_index: self.qfi,
|
||||
queue_lock: self.queue_lock.clone(),
|
||||
api_version: self.overlay_api_version(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Vulkan version an overlay renderer may size its function table to: the LOWER of
|
||||
/// what our instance declared ([`INSTANCE_API_VERSION`]) and what the loader actually
|
||||
/// provides.
|
||||
///
|
||||
/// Both halves are load-bearing, in opposite directions. Taking only the loader's number
|
||||
/// is the bug that killed the console UI in 0.28.0 — Mesa answers 1.4 where we asked for
|
||||
/// 1.3, and the entry points in between resolve to null. Taking only ours would break the
|
||||
/// mirror case: a loader older than 1.3 still accepts our 1.3 instance (1.1+ loaders treat
|
||||
/// `apiVersion` as intent, not a contract), and claiming 1.3 to a renderer there promises
|
||||
/// functions the loader has never heard of. The minimum is the only number that is true on
|
||||
/// both sides.
|
||||
fn overlay_api_version(&self) -> u32 {
|
||||
// SAFETY: per the Vulkan contract above - `vkEnumerateInstanceVersion` is a global
|
||||
// command taking no handles, resolved through the loaded entry that owns it; it writes
|
||||
// one `u32` local. Absent (a 1.0 loader) it reports `None` rather than failing.
|
||||
let loader = unsafe { self.entry.try_enumerate_instance_version() }
|
||||
.ok()
|
||||
.flatten();
|
||||
overlay_api_version_of(INSTANCE_API_VERSION, loader)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Presenter {
|
||||
@@ -449,3 +489,42 @@ impl Drop for Presenter {
|
||||
let _ = &self.entry;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The 0.28.0 regression, as an assertion: a loader NEWER than the version we declared
|
||||
/// must not raise the cap. Skia sized its function table to the loader's 1.4 here, then
|
||||
/// could not resolve the entry points our 1.3 instance never exposed, and the console UI
|
||||
/// refused to start (Steam Deck, Mesa loader 1.4.321).
|
||||
#[test]
|
||||
fn a_newer_loader_never_raises_the_cap() {
|
||||
let loader = vk::make_api_version(0, 1, 4, 321);
|
||||
assert_eq!(
|
||||
overlay_api_version_of(INSTANCE_API_VERSION, Some(loader)),
|
||||
INSTANCE_API_VERSION
|
||||
);
|
||||
}
|
||||
|
||||
/// The mirror case, which is why this is a `min` and not "just use ours": a 1.1+ loader
|
||||
/// accepts our 1.3 `apiVersion` as intent even when it cannot deliver 1.3, so promising
|
||||
/// 1.3 to the overlay there would name functions the loader has never heard of.
|
||||
#[test]
|
||||
fn an_older_loader_lowers_the_cap() {
|
||||
let loader = vk::make_api_version(0, 1, 2, 198);
|
||||
assert_eq!(
|
||||
overlay_api_version_of(INSTANCE_API_VERSION, Some(loader)),
|
||||
loader
|
||||
);
|
||||
}
|
||||
|
||||
/// No `vkEnumerateInstanceVersion` at all is the one thing it can mean: a 1.0 loader.
|
||||
#[test]
|
||||
fn a_loader_that_cannot_answer_is_1_0() {
|
||||
assert_eq!(
|
||||
overlay_api_version_of(INSTANCE_API_VERSION, None),
|
||||
vk::API_VERSION_1_0
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,9 +155,11 @@ impl Presenter {
|
||||
// 1.3: Vulkan Video decode and PyroWave's compute kernels both need a 1.3
|
||||
// device, and the instance version caps what the device can report (any current
|
||||
// loader accepts 1.3 regardless of device support; device-level gating is below).
|
||||
// `SharedDevice::api_version` republishes this constant to the overlay — keep the
|
||||
// two the same by construction rather than by two spellings of `API_VERSION_1_3`.
|
||||
let app_info = vk::ApplicationInfo::default()
|
||||
.application_name(&app_name)
|
||||
.api_version(vk::API_VERSION_1_3);
|
||||
.api_version(super::INSTANCE_API_VERSION);
|
||||
// HDR10 presentation needs the extended colorspaces at the INSTANCE level.
|
||||
let mut instance_extensions: Vec<String> = instance_extensions.to_vec();
|
||||
let inst_available =
|
||||
@@ -749,7 +751,7 @@ pub fn probe_decode() -> Result<Vec<AdapterDecode>> {
|
||||
let app_name = CString::new("punktfunk-session").unwrap();
|
||||
let app_info = vk::ApplicationInfo::default()
|
||||
.application_name(&app_name)
|
||||
.api_version(vk::API_VERSION_1_3);
|
||||
.api_version(super::INSTANCE_API_VERSION);
|
||||
// SAFETY: per the Vulkan contract above - a create/allocate call on the live device, over
|
||||
// builder structs that are locals outliving the call; the handle it returns is owned by the
|
||||
// value being built here.
|
||||
@@ -902,7 +904,7 @@ pub fn list_adapters() -> Result<Vec<String>> {
|
||||
let app_name = CString::new("punktfunk-session").unwrap();
|
||||
let app_info = vk::ApplicationInfo::default()
|
||||
.application_name(&app_name)
|
||||
.api_version(vk::API_VERSION_1_3);
|
||||
.api_version(super::INSTANCE_API_VERSION);
|
||||
// SAFETY: per the Vulkan contract above - the Vulkan handles used here are owned by this type
|
||||
// and live for the call, and every builder struct is a local that outlives it.
|
||||
let instance = unsafe {
|
||||
|
||||
@@ -824,6 +824,15 @@ pub mod admission;
|
||||
#[path = "vdisplay/linux/portal_config.rs"]
|
||||
mod portal_config;
|
||||
|
||||
/// Which ScreenCast cursor mode to REQUEST — negotiated against `AvailableCursorModes` instead of
|
||||
/// hardcoded, because a mode the backend does not advertise closes the session outright.
|
||||
///
|
||||
/// Declared unconditionally for the same reason as `portal_config` above: the ladder is pure
|
||||
/// integer work whose tests are the only place its behaviour is observable without a compositor,
|
||||
/// so they should run on every platform's CI rather than only where the callers compile.
|
||||
#[path = "vdisplay/linux/portal_cursor.rs"]
|
||||
mod portal_cursor;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[path = "vdisplay/linux/hyprland.rs"]
|
||||
mod hyprland;
|
||||
|
||||
@@ -1237,7 +1237,7 @@ fn write_session_plus_dropin(
|
||||
wrapper: &std::path::Path,
|
||||
mode: Mode,
|
||||
hdr: bool,
|
||||
wsi_ok: bool,
|
||||
wsi: WsiPlan,
|
||||
) -> Result<bool> {
|
||||
let Some(bind) = arm_session_bind(wrapper) else {
|
||||
remove_session_plus_dropin();
|
||||
@@ -1260,11 +1260,7 @@ fn write_session_plus_dropin(
|
||||
.chain(cursor_args())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" "),
|
||||
wsi = if wsi_ok {
|
||||
String::new()
|
||||
} else {
|
||||
wsi_off_unit_lines()
|
||||
},
|
||||
wsi = wsi.unit_lines(),
|
||||
);
|
||||
std::fs::write(&path, body).with_context(|| format!("write drop-in {}", path.display()))?;
|
||||
Ok(true)
|
||||
@@ -1579,7 +1575,7 @@ fn ensure_box_gamescope_mode(mode: Mode, hdr: bool) -> Result<u32> {
|
||||
// Same two fixes the transient path gets, but this unit is the BOX's own — they have to arrive
|
||||
// as a drop-in, and `daemon-reload` before the restart or systemd runs the old unit.
|
||||
let mut bound = match write_gamescope_bin_wrapper()
|
||||
.and_then(|w| write_session_plus_dropin(&w, mode, hdr, wsi_layer_matches_our_gamescope()))
|
||||
.and_then(|w| write_session_plus_dropin(&w, mode, hdr, WsiPlan::resolve()))
|
||||
{
|
||||
Ok(true) => {
|
||||
// Record it BEFORE the restart, and persist it: from this instant the box's OWN
|
||||
@@ -4215,25 +4211,103 @@ const WSI_OFF_ENV: [(&str, &str); 2] = [
|
||||
("ENABLE_GAMESCOPE_WSI", "0"),
|
||||
];
|
||||
|
||||
/// [`WSI_OFF_ENV`] as `systemd-run` arguments, for the transient unit.
|
||||
fn wsi_off_setenv_args() -> Vec<String> {
|
||||
WSI_OFF_ENV
|
||||
.iter()
|
||||
.map(|(name, value)| format!("--setenv={name}={value}"))
|
||||
.collect()
|
||||
/// Our own WSI layer's implicit-layer manifest, laid down beside the compositor by
|
||||
/// `packaging/gamescope/build-punktfunk-gamescope.sh`.
|
||||
///
|
||||
/// It is built from the SAME source tree at the SAME rev as `punktfunk-gamescope`, so the layer and
|
||||
/// the compositor cannot disagree about `gamescope_swapchain` — which is what makes every "is the
|
||||
/// distro's layer close enough to ours?" guess unnecessary. It carries its own layer name and its
|
||||
/// own `enable_environment`, so it coexists with the distro's rather than replacing it.
|
||||
const OUR_WSI_LAYER_DIR_DEFAULT: &str = "/usr/lib/punktfunk/vulkan/implicit_layer.d";
|
||||
const OUR_WSI_LAYER_MANIFEST_NAME: &str = "punktfunk_gamescope_wsi.json";
|
||||
|
||||
/// Where our layer's manifest directory is. FHS by default, because that is where every distro
|
||||
/// package puts it; `PUNKTFUNK_GAMESCOPE_WSI_LAYER_DIR` overrides for a store with no `/usr` to
|
||||
/// speak of — on NixOS the layer lives inside the gamescope derivation and the module points this
|
||||
/// at it, the same posture as `PUNKTFUNK_GAMESCOPE_BIN`.
|
||||
fn our_wsi_layer_dir() -> String {
|
||||
std::env::var("PUNKTFUNK_GAMESCOPE_WSI_LAYER_DIR")
|
||||
.ok()
|
||||
.filter(|v| !v.trim().is_empty())
|
||||
.unwrap_or_else(|| OUR_WSI_LAYER_DIR_DEFAULT.to_string())
|
||||
}
|
||||
|
||||
/// [`WSI_OFF_ENV`] as unit-file lines, for the box-session drop-in. Trailing newline included, so
|
||||
/// whatever the body puts after it still parses — same contract as [`SessionBind::unit_lines`].
|
||||
fn wsi_off_unit_lines() -> String {
|
||||
WSI_OFF_ENV
|
||||
.iter()
|
||||
.map(|(name, value)| format!("Environment={name}={value}\n"))
|
||||
.collect()
|
||||
/// Which Vulkan WSI layer a session we spawn should run with. Three states, decided ONCE per
|
||||
/// launch because [`WsiPlan::resolve`] can spawn `--version` probes.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum WsiPlan {
|
||||
/// Our own matching layer is installed: enable it, suppress the distro's. Games get HDR.
|
||||
Ours,
|
||||
/// No layer of ours, and the distro's version triple matches the gamescope we run, so it is
|
||||
/// probably built against the same protocol. Leave the box exactly as it is.
|
||||
DistroKept,
|
||||
/// No layer of ours, and the distro's cannot be trusted. Disable it — a mismatched layer kills
|
||||
/// every Vulkan client — and accept that no game in this session can get an HDR10 swapchain.
|
||||
DistroDisabled,
|
||||
}
|
||||
|
||||
impl WsiPlan {
|
||||
/// ⚠️ Spawns up to two `gamescope --version` probes in the fallback arms, so resolve once and
|
||||
/// pass the result around rather than calling this per use site.
|
||||
fn resolve() -> Self {
|
||||
let manifest = std::path::Path::new(&our_wsi_layer_dir()).join(OUR_WSI_LAYER_MANIFEST_NAME);
|
||||
if manifest.is_file() {
|
||||
Self::Ours
|
||||
} else if wsi_layer_matches_our_gamescope() {
|
||||
Self::DistroKept
|
||||
} else {
|
||||
Self::DistroDisabled
|
||||
}
|
||||
}
|
||||
|
||||
/// The environment this plan needs, as `(name, value)` pairs.
|
||||
fn env(self) -> Vec<(&'static str, String)> {
|
||||
match self {
|
||||
// `VK_ADD_IMPLICIT_LAYER_PATH` ADDS to the loader's implicit-layer search (loader
|
||||
// 1.3.234+), so the box's own layer directories keep working; the distro's gamescope
|
||||
// layer is then switched off by name through its own variables, leaving exactly one
|
||||
// gamescope WSI layer live — ours.
|
||||
Self::Ours => vec![
|
||||
("VK_ADD_IMPLICIT_LAYER_PATH", our_wsi_layer_dir()),
|
||||
("PUNKTFUNK_GAMESCOPE_WSI", "1".to_string()),
|
||||
("DISABLE_GAMESCOPE_WSI", "1".to_string()),
|
||||
("ENABLE_GAMESCOPE_WSI", "0".to_string()),
|
||||
],
|
||||
Self::DistroKept => Vec::new(),
|
||||
Self::DistroDisabled => WSI_OFF_ENV
|
||||
.iter()
|
||||
.map(|(name, value)| (*name, (*value).to_string()))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// As `systemd-run` arguments, for the transient unit.
|
||||
fn setenv_args(self) -> Vec<String> {
|
||||
self.env()
|
||||
.iter()
|
||||
.map(|(name, value)| format!("--setenv={name}={value}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// As unit-file lines, for the box-session drop-in. Trailing newline included, so whatever the
|
||||
/// body puts after it still parses — same contract as [`SessionBind::unit_lines`].
|
||||
fn unit_lines(self) -> String {
|
||||
self.env()
|
||||
.iter()
|
||||
.map(|(name, value)| format!("Environment={name}={value}\n"))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the box's `VkLayer_FROG_gamescope_wsi` can be trusted against the gamescope we run.
|
||||
///
|
||||
/// ⚠️ **Fallback only** — reached from [`WsiPlan::resolve`] just when our own layer is absent (a
|
||||
/// `punktfunk-gamescope` package older than the one that started shipping it). It is a guess, and a
|
||||
/// guess in BOTH directions: a distro at the same upstream tag that patched the protocol compares
|
||||
/// EQUAL and keeps a layer that will kill every Vulkan client, while a distro at a different tag
|
||||
/// with a byte-identical protocol compares unequal and loses HDR for nothing. Do not build anything
|
||||
/// new on it; ship the layer instead, which is what [`WsiPlan::Ours`] does.
|
||||
///
|
||||
/// The layer ships with the DISTRO's gamescope and speaks its `gamescope_swapchain` protocol; we
|
||||
/// run our own build. When the two disagree the compositor rejects the client's
|
||||
/// `swapchain_feedback` ("message too short") and **kills every Vulkan client** — Steam never
|
||||
@@ -4244,8 +4318,13 @@ fn wsi_off_unit_lines() -> String {
|
||||
/// byte-identical between those commits, so this is the distro PATCHING gamescope, not a version
|
||||
/// bump — which is why the check is "do the version triples differ", not a floor.
|
||||
///
|
||||
/// Disabling it costs only the layer's extras (XWayland bypass, present-mode control, client HDR
|
||||
/// metadata) — far cheaper than a client that cannot start.
|
||||
/// Disabling it costs the layer's extras (XWayland bypass, present-mode control) and, on an HDR
|
||||
/// session, **HDR for games**. The layer is the ONLY route to an HDR10 swapchain under gamescope:
|
||||
/// gamescope advertises no runtime colour-management protocol for a Mesa/NVIDIA WSI to negotiate
|
||||
/// through, so with the layer inactive a client never gets a Surface-state block and lands on
|
||||
/// `hdr10_format=None` (measured on a Deck OLED — see the Gamescope WSI notes in the flatpak
|
||||
/// manifest). Still cheaper than a client that cannot start at all, but not free, which is why
|
||||
/// [`launch_session`] says so out loud when it fires on an HDR session.
|
||||
///
|
||||
/// ⚠️ **`ENABLE_GAMESCOPE_WSI=0` is NOT enough on its own**, which is what [`WSI_OFF_ENV`] is for.
|
||||
fn wsi_layer_matches_our_gamescope() -> bool {
|
||||
@@ -4304,16 +4383,30 @@ fn launch_session(client: &str, unit_name: &str, mode: Mode, hdr: bool) -> Resul
|
||||
// The distro's Vulkan WSI layer speaks the distro gamescope's protocol; ours may differ, and a
|
||||
// mismatch kills every Vulkan client with no error but a black screen. Steam Big Picture is not
|
||||
// one of them, so the casualty is the GAMES — see [`WSI_OFF_ENV`] for why both variables go.
|
||||
let wsi_ok = wsi_layer_matches_our_gamescope();
|
||||
if !wsi_ok {
|
||||
let wsi = WsiPlan::resolve();
|
||||
if wsi == WsiPlan::DistroDisabled {
|
||||
tracing::warn!(
|
||||
"gamescope: this box's VkLayer_FROG_gamescope_wsi was built for a different gamescope \
|
||||
than the one we run — disabling it for this session (DISABLE_GAMESCOPE_WSI=1, which \
|
||||
the session script cannot clobber the way it clobbers ENABLE_GAMESCOPE_WSI). Left \
|
||||
enabled it rejects the client's swapchain_feedback and every Vulkan client dies; \
|
||||
Steam's own UI is not one, so what you see is a game that runs with sound and input \
|
||||
on a black screen, with no other symptom."
|
||||
than the one we run, and no punktfunk layer is installed to use instead — disabling \
|
||||
it for this session (DISABLE_GAMESCOPE_WSI=1, which the session script cannot clobber \
|
||||
the way it clobbers ENABLE_GAMESCOPE_WSI). Left enabled it rejects the client's \
|
||||
swapchain_feedback and every Vulkan client dies; Steam's own UI is not one, so what \
|
||||
you see is a game that runs with sound and input on a black screen, with no other \
|
||||
symptom. Upgrading the punktfunk-gamescope package fixes this properly — it ships a \
|
||||
layer built from the same tree as the compositor."
|
||||
);
|
||||
// The HDR decisions are made independently — `hdr_args` never consults the layer plan — so
|
||||
// without this an HDR session launches advertising HDR while having made game HDR
|
||||
// unreachable in the same breath, and nothing anywhere says so.
|
||||
if hdr {
|
||||
tracing::warn!(
|
||||
"gamescope: this session negotiated HDR, but with the WSI layer disabled no game \
|
||||
in it can get an HDR10 swapchain — that layer is the only route to one. The \
|
||||
stream itself stays HDR (the capture really is PQ/BT.2020, and Steam's UI and the \
|
||||
desktop ride the same container), so what breaks is GAME HDR specifically: a \
|
||||
title told to render HDR renders it into an SDR swapchain and looks washed out."
|
||||
);
|
||||
}
|
||||
}
|
||||
let start_unit = |bind: Option<&SessionBind>| -> Result<()> {
|
||||
let mut cmd = Command::new("systemd-run");
|
||||
@@ -4321,10 +4414,8 @@ fn launch_session(client: &str, unit_name: &str, mode: Mode, hdr: bool) -> Resul
|
||||
for arg in bind.map(SessionBind::run_args).unwrap_or_default() {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
if !wsi_ok {
|
||||
for arg in wsi_off_setenv_args() {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
for arg in wsi.setenv_args() {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
// Same headless-must-not-attach rule as [`spawn`]: the transient unit inherits the
|
||||
// user manager env, which can carry a (possibly stale) desktop DISPLAY/WAYLAND_DISPLAY
|
||||
@@ -4559,23 +4650,38 @@ fn add_bare_gamescope_args(
|
||||
/// fine meanwhile.)
|
||||
/// * `--hdr-sdr-content-nits` maps SDR content into the PQ container. Everything that is not an
|
||||
/// HDR game — the desktop, the Steam overlay, an SDR title — rides through it, so it decides
|
||||
/// how bright "white" lands on the client's panel. Only passed when the operator set the knob;
|
||||
/// otherwise gamescope's own default (400) applies.
|
||||
/// how bright "white" lands on the client's panel. We always pass it, because the two ends have
|
||||
/// to agree on where diffuse white sits and gamescope's own default does not match ours — see
|
||||
/// [`SDR_REFERENCE_WHITE_NITS`].
|
||||
fn hdr_args(hdr: bool) -> Vec<String> {
|
||||
if !hdr {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut args = vec![
|
||||
let nits = pf_host_config::config()
|
||||
.gamescope_sdr_nits
|
||||
.unwrap_or(SDR_REFERENCE_WHITE_NITS);
|
||||
vec![
|
||||
"--hdr-enabled".to_string(),
|
||||
"--hdr-debug-force-support".to_string(),
|
||||
];
|
||||
if let Some(nits) = pf_host_config::config().gamescope_sdr_nits {
|
||||
args.push("--hdr-sdr-content-nits".to_string());
|
||||
args.push(nits.to_string());
|
||||
}
|
||||
args
|
||||
"--hdr-sdr-content-nits".to_string(),
|
||||
nits.to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
/// Where diffuse white sits, in nits, for SDR content carried inside an HDR session's PQ container.
|
||||
///
|
||||
/// 203 is BT.2408 "HDR Reference White", and it is the value every first-party client anchors to:
|
||||
/// the Apple presenter hands exactly 203 to `CAEDRMetadata.hdr10(opticalOutputScale:)`. gamescope's
|
||||
/// own default is 400, so leaving the flag off put the host nearly a stop (400/203 ≈ 1.97×) above
|
||||
/// what the client decodes against — the 2026-08-13 field report where Steam's Big Picture UI read
|
||||
/// as glaring and over-saturated on an iPad while HDR game content came out washed out. Both are
|
||||
/// the same error: the UI lands above SDR white, and the client's tone-mapper then works from a
|
||||
/// reference point the host never used, flattening the content around it.
|
||||
///
|
||||
/// This is the anchor, not a taste knob — `PUNKTFUNK_GAMESCOPE_SDR_NITS` is still there for an
|
||||
/// operator who wants a brighter or dimmer desktop, and moving it away from 203 re-opens the gap.
|
||||
const SDR_REFERENCE_WHITE_NITS: u32 = 203;
|
||||
|
||||
/// `--pipewire-composite-cursor` when the resolved gamescope has it (patch level 2+). Paired with
|
||||
/// [`crate::gamescope_composites_cursor`], which is what tells the host to STOP compositing the
|
||||
/// pointer itself — the two must agree, so both read the same probe.
|
||||
@@ -4778,12 +4884,12 @@ mod tests {
|
||||
any_output_size_is, cgroup_is_punktfunk_owned, cgroup_under_user_manager,
|
||||
classify_output_size, connected_connector_under, display_manager_unit_under, dm_plan,
|
||||
dm_survives_masked_unit, game_hz, gamescope_output_size, hdr_args, is_steam_launch,
|
||||
mask_unit, missing_flags, mode_mismatch, nested_wrapper_script, plan_bind,
|
||||
release_autologin_mask, script_hardcodes_gamescope, sentinel_advanced,
|
||||
mask_unit, missing_flags, mode_mismatch, nested_wrapper_script, our_wsi_layer_dir,
|
||||
plan_bind, release_autologin_mask, script_hardcodes_gamescope, sentinel_advanced,
|
||||
shape_dedicated_command, switch_ends_mask_window, takeover_state_is_live, unmask_unit,
|
||||
wsi_off_setenv_args, wsi_off_unit_lines, xwayland_refusal_marker, BindOff, BindPlan,
|
||||
BoxOutputSize, DmHelperError, SessionBind, TakeoverState, AUTOLOGIN_MASKED,
|
||||
DISTRO_GAMESCOPE_PATH, STOPPED_AUTOLOGIN, WSI_OFF_ENV, X11_SOCKET_DIR,
|
||||
xwayland_refusal_marker, BindOff, BindPlan, BoxOutputSize, DmHelperError, SessionBind,
|
||||
TakeoverState, WsiPlan, AUTOLOGIN_MASKED, DISTRO_GAMESCOPE_PATH, STOPPED_AUTOLOGIN,
|
||||
WSI_OFF_ENV, X11_SOCKET_DIR,
|
||||
};
|
||||
|
||||
fn argv(s: &str) -> Vec<String> {
|
||||
@@ -5611,8 +5717,8 @@ mod tests {
|
||||
);
|
||||
|
||||
// Both spellings reach both launch paths, and neither may lose the other.
|
||||
let args = wsi_off_setenv_args();
|
||||
let lines = wsi_off_unit_lines();
|
||||
let args = WsiPlan::DistroDisabled.setenv_args();
|
||||
let lines = WsiPlan::DistroDisabled.unit_lines();
|
||||
for (name, value) in WSI_OFF_ENV {
|
||||
assert!(args.contains(&format!("--setenv={name}={value}")), "{name}");
|
||||
assert!(
|
||||
@@ -5625,4 +5731,31 @@ mod tests {
|
||||
// lines above it rely on the same contract and the order has changed before.
|
||||
assert!(lines.ends_with('\n'));
|
||||
}
|
||||
|
||||
/// The whole point of shipping our own layer is that BOTH halves happen in one session: ours is
|
||||
/// switched on AND the distro's is forced off. Enabling ours while leaving theirs live would
|
||||
/// put two gamescope WSI layers in the loader's implicit set, and dropping ours while forcing
|
||||
/// theirs off is just the old no-game-HDR behaviour wearing a new name — so assert the pair,
|
||||
/// not either half.
|
||||
#[test]
|
||||
fn our_own_layer_is_enabled_and_the_distro_one_forced_off_together() {
|
||||
let env = WsiPlan::Ours.env();
|
||||
let get = |k: &str| {
|
||||
env.iter()
|
||||
.find(|(name, _)| *name == k)
|
||||
.map(|(_, v)| v.clone())
|
||||
.unwrap_or_else(|| panic!("{k} missing from the Ours plan"))
|
||||
};
|
||||
|
||||
assert_eq!(get("VK_ADD_IMPLICIT_LAYER_PATH"), our_wsi_layer_dir());
|
||||
assert_eq!(get("PUNKTFUNK_GAMESCOPE_WSI"), "1");
|
||||
// The clobber-proof one, for exactly the reason the test above states.
|
||||
assert_eq!(get("DISABLE_GAMESCOPE_WSI"), "1");
|
||||
assert_eq!(get("ENABLE_GAMESCOPE_WSI"), "0");
|
||||
|
||||
// `DistroKept` must stay genuinely inert: it is the arm that runs on a box we decided not
|
||||
// to touch, so a stray variable there would change behaviour we promised not to change.
|
||||
assert!(WsiPlan::DistroKept.env().is_empty());
|
||||
assert!(WsiPlan::DistroKept.unit_lines().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,12 +115,21 @@ fn output_owner_pid(name: &str) -> Option<u32> {
|
||||
/// The Hyprland virtual-display driver. Stateless — each [`create`](VirtualDisplay::create) adds one
|
||||
/// named headless output and spins up a portal thread owning the cast on it.
|
||||
pub struct HyprlandDisplay {
|
||||
/// Out-of-band cursor request (`set_hw_cursor`, the negotiated cursor channel): portal
|
||||
/// Out-of-band cursor request (`set_hw_cursor`, the negotiated cursor channel): PREFER portal
|
||||
/// `CursorMode::Metadata` — shapes/positions ride `SPA_META_Cursor` for the channel + the
|
||||
/// composite blend. Off (every non-channel session): `Embedded` — the compositor paints the
|
||||
/// pointer into frames, zero host-side cursor work (the pre-channel default this backend
|
||||
/// always had). ⚠️ Metadata is UNTESTED on-glass for this backend (Phase B wired it so the
|
||||
/// channel isn't silently dead here; KWin/Mutter are the validated legs).
|
||||
/// composite blend. Off (every non-channel session): prefer `Embedded` — the compositor paints
|
||||
/// the pointer into frames, zero host-side cursor work (the pre-channel default this backend
|
||||
/// always had).
|
||||
///
|
||||
/// Both are only a PREFERENCE: [`crate::portal_cursor`] settles it against what xdph actually
|
||||
/// advertises, because requesting an unadvertised mode makes xdg-desktop-portal fail the call.
|
||||
/// This used to be asserted instead, which is exactly how a cursor-forward session here became
|
||||
/// a black client.
|
||||
///
|
||||
/// ⚠️ On current xdph the metadata arm is UNREACHABLE, not merely untested: measured on .21
|
||||
/// 2026-08-14 (Hyprland 0.56.2, xdph 1.4.1) `AvailableCursorModes` = 3 — `Hidden|Embedded`
|
||||
/// only. Every session on this backend therefore resolves to `Embedded` today; KWin/Mutter
|
||||
/// remain the legs where the metadata channel is actually exercised.
|
||||
hw_cursor: bool,
|
||||
}
|
||||
|
||||
@@ -788,13 +797,7 @@ fn portal_thread(
|
||||
stop: Arc<AtomicBool>,
|
||||
hw_cursor: bool,
|
||||
) {
|
||||
// Portal cursor mode per the session's channel negotiation (see the struct doc).
|
||||
let cursor_mode = if hw_cursor {
|
||||
CursorMode::Metadata
|
||||
} else {
|
||||
CursorMode::Embedded
|
||||
};
|
||||
use ashpd::desktop::screencast::{CursorMode, Screencast, SelectSourcesOptions, SourceType};
|
||||
use ashpd::desktop::screencast::{Screencast, SelectSourcesOptions, SourceType};
|
||||
use ashpd::desktop::PersistMode;
|
||||
use ashpd::enumflags2::BitFlags;
|
||||
|
||||
@@ -818,6 +821,14 @@ fn portal_thread(
|
||||
let proxy = Screencast::new().await.context(
|
||||
"connect ScreenCast portal (is xdg-desktop-portal running with the hyprland backend/xdph?)",
|
||||
)?;
|
||||
// NEGOTIATED against what xdph advertises, never asserted from `hw_cursor` alone: a
|
||||
// cursor mode the backend does not offer does not degrade — xdg-desktop-portal's
|
||||
// FRONTEND fails the call ("Unavailable cursor mode %x") before xdph sees it.
|
||||
// MEASURED on .21 2026-08-14, Hyprland 0.56.2 + xdph 1.4.1 (both current):
|
||||
// `AvailableCursorModes` = 3 (Hidden|Embedded) — metadata is NOT offered. So the old
|
||||
// hardcode killed EVERY cursor-forward session here, on today's packages, not just on
|
||||
// old installs: `unavailable cursor mode 4`, "pipeline build failed", black client.
|
||||
let cursor_mode = crate::portal_cursor::negotiate(&proxy, hw_cursor, "xdph").await;
|
||||
let session = proxy
|
||||
.create_session(Default::default())
|
||||
.await
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
//! Which ScreenCast cursor mode to ASK the portal for — negotiated against what the backend
|
||||
//! advertises, rather than asserted.
|
||||
//!
|
||||
//! The portal spec is unforgiving here: `SelectSources` with a cursor mode that is absent from
|
||||
//! `AvailableCursorModes` does not quietly degrade — **xdg-desktop-portal itself rejects the call**
|
||||
//! (`"Unavailable cursor mode %x"`, an `INVALID_ARGUMENT` from the FRONTEND, which validates the
|
||||
//! request against the backend's advertised bitfield before the backend ever sees it). Both
|
||||
//! wlr-family backends used to hardcode `Metadata` whenever the session had negotiated the cursor
|
||||
//! channel, so every cursor-forward session died at `select_sources` — `unavailable cursor mode 4`
|
||||
//! (4 being `Metadata`'s bit) and a client left on a black screen behind "pipeline build failed".
|
||||
//! Field report 2026-08-14.
|
||||
//!
|
||||
//! ⚠️ This is NOT a stale-portal problem, and not Hyprland-specific. MEASURED on .21 2026-08-14 on
|
||||
//! fully current packages — Hyprland **0.56.2**, xdg-desktop-portal-hyprland **1.4.1**,
|
||||
//! xdg-desktop-portal **1.22.1** — with a live session and xdph attached (`[screencopy] init
|
||||
//! successful`): `AvailableCursorModes` reads **3** (`Hidden|Embedded`) on both the backend impl
|
||||
//! interface and the frontend. **Metadata is simply not offered by xdph today.** xdpw is the same
|
||||
//! story from the other end: its `screencast.c` refuses `METADATA` outright. So the hardcode broke
|
||||
//! every cursor-forward session on the entire wlr family, on current software — not only on old
|
||||
//! installs. (xdph 1.4.1 would itself fall back — its binary carries
|
||||
//! `"[screencopy] unsupported cursor_mode {}, fallback to {}"` — but it never gets the chance,
|
||||
//! because the frontend fails the call first.)
|
||||
//!
|
||||
//! `pf-capture`'s own portal path has always negotiated (`portal::choose_cursor_mode`) — this is
|
||||
//! that ladder, restated in the crate that owns the virtual-display backends. pf-vdisplay must not
|
||||
//! depend on pf-capture (see this crate's Cargo.toml: "never on capture/inject or the
|
||||
//! orchestrator"), so the two copies are deliberate; keep the ladders in step.
|
||||
//!
|
||||
//! Declared unconditionally although only the Linux backends call it: the ladder is pure integer
|
||||
//! work, and its tests are the whole point of the module — this is a decision that leaves no trace
|
||||
//! anyone can check without a compositor in front of them — so they run on every platform's CI
|
||||
//! rather than on the one leg that compiles `mod hyprland`.
|
||||
|
||||
/// A ScreenCast cursor mode, valued as the portal's own wire bits — which is what a backend prints
|
||||
/// when it rejects one, so `Metadata`'s `4` is literally the number in the field report.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Mode {
|
||||
/// No pointer in the cast at all.
|
||||
Hidden = 1,
|
||||
/// The compositor paints the pointer into the frames it hands us.
|
||||
Embedded = 2,
|
||||
/// The pointer rides `SPA_META_Cursor` metadata beside the frames: the compositor keeps its
|
||||
/// cheap hardware cursor plane, and the consumer either composites the shape itself or
|
||||
/// forwards it to a client that draws its own.
|
||||
Metadata = 4,
|
||||
}
|
||||
|
||||
impl Mode {
|
||||
/// The portal's bit for this mode.
|
||||
pub(crate) const fn bit(self) -> u32 {
|
||||
self as u32
|
||||
}
|
||||
|
||||
/// The spelling used in logs and in `PUNKTFUNK_PORTAL_CURSOR_MODE`.
|
||||
pub(crate) const fn name(self) -> &'static str {
|
||||
match self {
|
||||
Mode::Hidden => "hidden",
|
||||
Mode::Embedded => "embedded",
|
||||
Mode::Metadata => "metadata",
|
||||
}
|
||||
}
|
||||
|
||||
/// What to ask for instead, best first, when this mode is not advertised.
|
||||
const fn fallbacks(self) -> [Mode; 2] {
|
||||
match self {
|
||||
// The session wanted out-of-band shapes and cannot have them. `Embedded` still puts a
|
||||
// pointer on the client's screen (the compositor's, burnt in) — and because no
|
||||
// `SPA_META_Cursor` then arrives, the host feeds the cursor channel nothing and a
|
||||
// cursor-forward client draws nothing of its own, so this is one pointer, not two.
|
||||
// `Hidden` is last: it streams a desktop nobody can point at.
|
||||
Mode::Metadata => [Mode::Embedded, Mode::Hidden],
|
||||
// Embedded wanted but not offered. Metadata still beats Hidden: the CPU capture path
|
||||
// composites `SPA_META_Cursor` inline, so part of the matrix keeps a pointer.
|
||||
Mode::Embedded => [Mode::Metadata, Mode::Hidden],
|
||||
// A deliberate request for no pointer that the backend will not honour. Either
|
||||
// remaining mode shows one; prefer the cheap burnt-in pointer over metadata nothing on
|
||||
// this path is set up to draw.
|
||||
Mode::Hidden => [Mode::Embedded, Mode::Metadata],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The outcome of the ladder: what to request, and what the session actually wanted if those
|
||||
/// differ (the caller logs the gap — a silently downgraded cursor is how this class of bug hides).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Choice {
|
||||
/// The mode to put in `SelectSources`. Advertised, unless the backend advertised nothing.
|
||||
pub(crate) mode: Mode,
|
||||
/// Set only when `mode` is a downgrade: the mode the session asked for and could not have.
|
||||
pub(crate) wanted: Option<Mode>,
|
||||
}
|
||||
|
||||
/// Pick the cursor mode to request, given the backend's `AvailableCursorModes` bitfield.
|
||||
///
|
||||
/// Never returns a mode outside `advertised` unless `advertised` names none we know — see the tail
|
||||
/// comment, which is the one case with no right answer.
|
||||
pub(crate) fn pick(advertised: u32, want: Mode) -> Choice {
|
||||
if advertised & want.bit() != 0 {
|
||||
return Choice {
|
||||
mode: want,
|
||||
wanted: None,
|
||||
};
|
||||
}
|
||||
for alt in want.fallbacks() {
|
||||
if advertised & alt.bit() != 0 {
|
||||
return Choice {
|
||||
mode: alt,
|
||||
wanted: Some(want),
|
||||
};
|
||||
}
|
||||
}
|
||||
// The backend advertised no mode this build knows — 0, or only bits from a spec revision newer
|
||||
// than us. Every request is then a coin flip against a session-closing rejection; `Hidden` is
|
||||
// both the most universally implemented and the only one that cannot end up drawing two
|
||||
// pointers. The caller warns: whatever this backend is doing, we are guessing.
|
||||
Choice {
|
||||
mode: Mode::Hidden,
|
||||
wanted: Some(want),
|
||||
}
|
||||
}
|
||||
|
||||
/// A parsed `PUNKTFUNK_PORTAL_CURSOR_MODE`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Pin {
|
||||
/// Unset or `auto` — the session's own negotiation decides.
|
||||
Auto,
|
||||
/// Prefer this mode instead of what the session negotiated. Still runs the ladder, so a pin
|
||||
/// can never re-create the session-killing request this module exists to prevent.
|
||||
Mode(Mode),
|
||||
/// Set to something we do not recognise. Treated as `Auto`, but the caller says so out loud —
|
||||
/// a typo'd escape hatch that silently does nothing is worse than no escape hatch.
|
||||
Unrecognised,
|
||||
}
|
||||
|
||||
/// Parse the `PUNKTFUNK_PORTAL_CURSOR_MODE` value.
|
||||
pub(crate) fn parse_pin(raw: &str) -> Pin {
|
||||
match raw.trim().to_ascii_lowercase().as_str() {
|
||||
"" | "auto" => Pin::Auto,
|
||||
"hidden" | "none" => Pin::Mode(Mode::Hidden),
|
||||
"embedded" | "composited" => Pin::Mode(Mode::Embedded),
|
||||
"metadata" | "meta" => Pin::Mode(Mode::Metadata),
|
||||
_ => Pin::Unrecognised,
|
||||
}
|
||||
}
|
||||
|
||||
/// The mode this session wants before the backend gets a say: `Metadata` when the cursor channel
|
||||
/// was negotiated (`set_hw_cursor` — the client draws the pointer, so the compositor must not burn
|
||||
/// it in), `Embedded` otherwise. `PUNKTFUNK_PORTAL_CURSOR_MODE` overrides both.
|
||||
///
|
||||
/// `backend` names the portal implementation for the log line only (`xdph`, `xdpw`).
|
||||
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
pub(crate) fn want(hw_cursor: bool, backend: &str) -> Mode {
|
||||
let negotiated = if hw_cursor {
|
||||
Mode::Metadata
|
||||
} else {
|
||||
Mode::Embedded
|
||||
};
|
||||
let raw = match pf_host_config::config().portal_cursor_mode.as_deref() {
|
||||
Some(raw) => raw,
|
||||
None => return negotiated,
|
||||
};
|
||||
match parse_pin(raw) {
|
||||
Pin::Auto => negotiated,
|
||||
Pin::Mode(pinned) => {
|
||||
tracing::info!(
|
||||
backend,
|
||||
pinned = pinned.name(),
|
||||
negotiated = negotiated.name(),
|
||||
"ScreenCast: cursor mode pinned by PUNKTFUNK_PORTAL_CURSOR_MODE"
|
||||
);
|
||||
pinned
|
||||
}
|
||||
Pin::Unrecognised => {
|
||||
tracing::warn!(
|
||||
backend,
|
||||
value = raw,
|
||||
negotiated = negotiated.name(),
|
||||
"ScreenCast: unrecognised PUNKTFUNK_PORTAL_CURSOR_MODE (want auto|hidden|embedded|\
|
||||
metadata) — ignoring"
|
||||
);
|
||||
negotiated
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl Mode {
|
||||
fn to_ashpd(self) -> ashpd::desktop::screencast::CursorMode {
|
||||
use ashpd::desktop::screencast::CursorMode;
|
||||
match self {
|
||||
Mode::Hidden => CursorMode::Hidden,
|
||||
Mode::Embedded => CursorMode::Embedded,
|
||||
Mode::Metadata => CursorMode::Metadata,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask the portal what it supports, run the ladder, and hand back the mode to put in
|
||||
/// `SelectSources`. Infallible by construction: a backend we cannot interrogate gets `Embedded`,
|
||||
/// the mode that predates the property and that every implementation has always had.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) async fn negotiate(
|
||||
proxy: &ashpd::desktop::screencast::Screencast,
|
||||
hw_cursor: bool,
|
||||
backend: &str,
|
||||
) -> ashpd::desktop::screencast::CursorMode {
|
||||
let want = want(hw_cursor, backend);
|
||||
let advertised = match proxy.available_cursor_modes().await {
|
||||
Ok(avail) => avail.bits(),
|
||||
Err(e) => {
|
||||
// `AvailableCursorModes` is a versioned property (ScreenCast v2); a portal too old to
|
||||
// publish it is also too old to have metadata, and `Embedded` is what this backend
|
||||
// requested for its whole life before the cursor channel existed.
|
||||
tracing::warn!(
|
||||
backend,
|
||||
error = %e,
|
||||
"ScreenCast: AvailableCursorModes query failed — requesting Embedded cursor"
|
||||
);
|
||||
return Mode::Embedded.to_ashpd();
|
||||
}
|
||||
};
|
||||
let choice = pick(advertised, want);
|
||||
match choice.wanted {
|
||||
None => tracing::info!(
|
||||
backend,
|
||||
advertised = format_args!("{advertised:#05b}"),
|
||||
mode = choice.mode.name(),
|
||||
"ScreenCast: cursor mode negotiated"
|
||||
),
|
||||
// The downgrade path — and the one that used to be a dead session. Loud, because a stream
|
||||
// whose pointer quietly changed hands is exactly what nobody thinks to check.
|
||||
Some(wanted) => tracing::warn!(
|
||||
backend,
|
||||
advertised = format_args!("{advertised:#05b}"),
|
||||
wanted = wanted.name(),
|
||||
mode = choice.mode.name(),
|
||||
"ScreenCast: requested cursor mode is not advertised by this portal — downgrading \
|
||||
(requesting it anyway would close the session)"
|
||||
),
|
||||
}
|
||||
choice.mode.to_ashpd()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The portal's wire values. These are ABI — a backend rejecting our request prints the
|
||||
/// number, and `4` is the one in the field report that started this module.
|
||||
#[test]
|
||||
fn mode_bits_are_the_portal_wire_values() {
|
||||
assert_eq!(Mode::Hidden.bit(), 1);
|
||||
assert_eq!(Mode::Embedded.bit(), 2);
|
||||
assert_eq!(Mode::Metadata.bit(), 4);
|
||||
}
|
||||
|
||||
/// Our `Mode` is a restatement of ashpd's `CursorMode`, whose bits enumflags2 assigns from
|
||||
/// declaration order — so a reordering upstream would silently repoint every mode. Pin it
|
||||
/// where ashpd is actually compiled.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn mode_bits_match_ashpd() {
|
||||
use ashpd::desktop::screencast::CursorMode;
|
||||
use ashpd::enumflags2::BitFlags;
|
||||
for m in [Mode::Hidden, Mode::Embedded, Mode::Metadata] {
|
||||
assert_eq!(
|
||||
BitFlags::from_flag(m.to_ashpd()).bits(),
|
||||
m.bit(),
|
||||
"{} drifted from ashpd",
|
||||
m.name()
|
||||
);
|
||||
}
|
||||
assert_eq!(BitFlags::from_flag(CursorMode::Metadata).bits(), 4);
|
||||
}
|
||||
|
||||
/// THE REGRESSION, with the real number: `3` is what xdph actually advertises — measured on
|
||||
/// .21 2026-08-14 against a live Hyprland 0.56.2 + xdph 1.4.1, both current. A cursor-forward
|
||||
/// session wants metadata; asking for it made xdg-desktop-portal fail the call, and the client
|
||||
/// got a black screen behind "pipeline build failed" / "unavailable cursor mode 4".
|
||||
#[test]
|
||||
fn metadata_wanted_but_unadvertised_downgrades_to_embedded() {
|
||||
// Exactly the bitfield the portal reported on glass.
|
||||
assert_eq!(Mode::Hidden.bit() | Mode::Embedded.bit(), 3);
|
||||
let c = pick(3, Mode::Metadata);
|
||||
assert_eq!(c.mode, Mode::Embedded);
|
||||
assert_eq!(c.wanted, Some(Mode::Metadata));
|
||||
}
|
||||
|
||||
/// The same portal, a session with no cursor channel: already asking for what exists, so the
|
||||
/// fix must not perturb it.
|
||||
#[test]
|
||||
fn embedded_wanted_and_advertised_is_untouched() {
|
||||
let c = pick(Mode::Hidden.bit() | Mode::Embedded.bit(), Mode::Embedded);
|
||||
assert_eq!(c.mode, Mode::Embedded);
|
||||
assert_eq!(c.wanted, None);
|
||||
}
|
||||
|
||||
/// A portal that does support metadata (KWin, Mutter, xdph ≥ #366) still gets it — the point
|
||||
/// is to stop asserting, not to stop using it.
|
||||
#[test]
|
||||
fn metadata_is_used_where_advertised() {
|
||||
let all = Mode::Hidden.bit() | Mode::Embedded.bit() | Mode::Metadata.bit();
|
||||
let c = pick(all, Mode::Metadata);
|
||||
assert_eq!(c.mode, Mode::Metadata);
|
||||
assert_eq!(c.wanted, None);
|
||||
}
|
||||
|
||||
/// Embedded wanted, only metadata offered: the CPU capture path composites it, so a pointer
|
||||
/// survives. (Mirrors `pf-capture`'s ladder.)
|
||||
#[test]
|
||||
fn embedded_unadvertised_falls_to_metadata_not_hidden() {
|
||||
let c = pick(Mode::Hidden.bit() | Mode::Metadata.bit(), Mode::Embedded);
|
||||
assert_eq!(c.mode, Mode::Metadata);
|
||||
assert_eq!(c.wanted, Some(Mode::Embedded));
|
||||
}
|
||||
|
||||
/// A backend offering only `Hidden`: a cursorless stream beats a closed session.
|
||||
#[test]
|
||||
fn hidden_only_backend_yields_hidden() {
|
||||
let c = pick(Mode::Hidden.bit(), Mode::Metadata);
|
||||
assert_eq!(c.mode, Mode::Hidden);
|
||||
assert_eq!(c.wanted, Some(Mode::Metadata));
|
||||
}
|
||||
|
||||
/// Advertises nothing we know — no right answer, but it must still be a legal enum and flagged
|
||||
/// as a downgrade so the warn fires.
|
||||
#[test]
|
||||
fn unknown_advertisement_guesses_hidden_and_reports_a_downgrade() {
|
||||
for advertised in [0, 0b1000_0000] {
|
||||
let c = pick(advertised, Mode::Metadata);
|
||||
assert_eq!(c.mode, Mode::Hidden);
|
||||
assert_eq!(c.wanted, Some(Mode::Metadata));
|
||||
}
|
||||
}
|
||||
|
||||
/// Whatever the ladder returns must be a mode the backend named — the invariant the old
|
||||
/// hardcode broke. Exhaustive over every advertisement × every want.
|
||||
#[test]
|
||||
fn never_requests_an_unadvertised_mode() {
|
||||
let modes = [Mode::Hidden, Mode::Embedded, Mode::Metadata];
|
||||
for advertised in 1u32..=0b111 {
|
||||
for want in modes {
|
||||
let c = pick(advertised, want);
|
||||
assert!(
|
||||
advertised & c.mode.bit() != 0,
|
||||
"picked {} from advertised {advertised:#05b} (want {})",
|
||||
c.mode.name(),
|
||||
want.name()
|
||||
);
|
||||
// A downgrade is reported exactly when one happened.
|
||||
assert_eq!(c.wanted.is_some(), c.mode != want);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pin_parses_the_spellings_we_document() {
|
||||
assert_eq!(parse_pin(""), Pin::Auto);
|
||||
assert_eq!(parse_pin("auto"), Pin::Auto);
|
||||
assert_eq!(parse_pin(" AUTO "), Pin::Auto);
|
||||
assert_eq!(parse_pin("embedded"), Pin::Mode(Mode::Embedded));
|
||||
assert_eq!(parse_pin("Embedded"), Pin::Mode(Mode::Embedded));
|
||||
assert_eq!(parse_pin("metadata"), Pin::Mode(Mode::Metadata));
|
||||
assert_eq!(parse_pin("hidden"), Pin::Mode(Mode::Hidden));
|
||||
assert_eq!(parse_pin("2"), Pin::Unrecognised);
|
||||
assert_eq!(parse_pin("yes"), Pin::Unrecognised);
|
||||
}
|
||||
|
||||
/// The hatch pins a PREFERENCE, not the request: pinning metadata at a portal without it must
|
||||
/// still come out embedded rather than re-closing the session.
|
||||
#[test]
|
||||
fn a_pin_still_runs_the_ladder() {
|
||||
let c = pick(Mode::Hidden.bit() | Mode::Embedded.bit(), Mode::Metadata);
|
||||
assert_eq!(c.mode, Mode::Embedded);
|
||||
}
|
||||
}
|
||||
@@ -55,12 +55,17 @@ fn chooser_cmd() -> String {
|
||||
/// The wlroots/Sway virtual-display driver. Stateless — each [`create`](VirtualDisplay::create)
|
||||
/// adds one headless output and spins up a portal thread owning the cast on it.
|
||||
pub struct WlrootsDisplay {
|
||||
/// Out-of-band cursor request (`set_hw_cursor`, the negotiated cursor channel): portal
|
||||
/// Out-of-band cursor request (`set_hw_cursor`, the negotiated cursor channel): PREFER portal
|
||||
/// `CursorMode::Metadata` — shapes/positions ride `SPA_META_Cursor` for the channel + the
|
||||
/// composite blend. Off (every non-channel session): `Embedded` — the compositor paints the
|
||||
/// pointer into frames, zero host-side cursor work (the pre-channel default this backend
|
||||
/// always had). ⚠️ Metadata is UNTESTED on-glass for this backend (Phase B wired it so the
|
||||
/// channel isn't silently dead here; KWin/Mutter are the validated legs).
|
||||
/// composite blend. Off (every non-channel session): prefer `Embedded` — the compositor paints
|
||||
/// the pointer into frames, zero host-side cursor work (the pre-channel default this backend
|
||||
/// always had).
|
||||
///
|
||||
/// Both are only a PREFERENCE: [`crate::portal_cursor`] settles it against what xdpw actually
|
||||
/// advertises, because requesting an unadvertised mode closes the session outright. xdpw
|
||||
/// refuses metadata by construction (see the portal thread), so on this backend the channel can
|
||||
/// never be served out-of-band: it now degrades to `Embedded` and streams, where it used to
|
||||
/// cancel the cast and hand the client a black screen.
|
||||
hw_cursor: bool,
|
||||
}
|
||||
|
||||
@@ -512,13 +517,7 @@ fn portal_thread(
|
||||
stop: Arc<AtomicBool>,
|
||||
hw_cursor: bool,
|
||||
) {
|
||||
// Portal cursor mode per the session's channel negotiation (see the struct doc).
|
||||
let cursor_mode = if hw_cursor {
|
||||
CursorMode::Metadata
|
||||
} else {
|
||||
CursorMode::Embedded
|
||||
};
|
||||
use ashpd::desktop::screencast::{CursorMode, Screencast, SelectSourcesOptions, SourceType};
|
||||
use ashpd::desktop::screencast::{Screencast, SelectSourcesOptions, SourceType};
|
||||
use ashpd::desktop::PersistMode;
|
||||
use ashpd::enumflags2::BitFlags;
|
||||
|
||||
@@ -542,6 +541,14 @@ fn portal_thread(
|
||||
let proxy = Screencast::new().await.context(
|
||||
"connect ScreenCast portal (is xdg-desktop-portal running with the wlr backend?)",
|
||||
)?;
|
||||
// NEGOTIATED against what xdpw advertises, never asserted from `hw_cursor` alone — see
|
||||
// the xdph copy in `hyprland.rs` for the incident. xdpw is the sharper case: its
|
||||
// screencast.c refuses the mode outright —
|
||||
// if (sess->screencast_data.cursor_mode & METADATA) {
|
||||
// logprint(ERROR, "dbus: unsupported cursor mode requested, cancelling");
|
||||
// — so EVERY cursor-forward session on this backend asked for a mode that cancelled the
|
||||
// cast. Different wording from xdph's "unavailable cursor mode 4", same dead session.
|
||||
let cursor_mode = crate::portal_cursor::negotiate(&proxy, hw_cursor, "xdpw").await;
|
||||
let session = proxy
|
||||
.create_session(Default::default())
|
||||
.await
|
||||
|
||||
@@ -185,8 +185,12 @@ pub enum MaxLevelIdc {
|
||||
H265(hh::StdVideoH265LevelIdc),
|
||||
/// `VkVideoDecodeAV1CapabilitiesKHR::maxLevel`. Unlike the other two this code
|
||||
/// space is the BITSTREAM's own: `StdVideoAV1Level` is index-coded exactly like
|
||||
/// AV1's `seq_level_idx` (2.0 = 0, 2.1 = 1, … 7.3 = 23), so the decoder's gate
|
||||
/// compares the sequence header's value against it directly.
|
||||
/// AV1's `seq_level_idx` (2.0 = 0, 2.1 = 1, … 7.3 = 23).
|
||||
///
|
||||
/// ⚠ Only over 0…23. `seq_level_idx` is 5 bits, and 31 is Annex A's "maximum
|
||||
/// parameters" sentinel — no level constraint — which outranks even a device
|
||||
/// reporting the enum's top value. The AV1 gate therefore treats a stream above
|
||||
/// this ceiling as advisory instead of refusing it (`VkAv1Decoder::ensure_state`).
|
||||
Av1(hh::StdVideoAV1Level),
|
||||
}
|
||||
|
||||
|
||||
@@ -211,9 +211,16 @@ pub struct RawAv1Caps {
|
||||
pub max_coded_extent: vk::Extent2D,
|
||||
pub max_dpb_slots: u32,
|
||||
pub max_active_reference_pictures: u32,
|
||||
/// `VkVideoDecodeAV1CapabilitiesKHR::maxLevel` (index-coded Std level — the
|
||||
/// SAME numbering as the bitstream's `seq_level_idx`, which is what makes the
|
||||
/// decoder's level gate a plain comparison).
|
||||
/// `VkVideoDecodeAV1CapabilitiesKHR::maxLevel` (index-coded Std level — the same
|
||||
/// numbering as the bitstream's `seq_level_idx` OVER 0…23, which is the whole
|
||||
/// range `StdVideoAV1Level` enumerates).
|
||||
///
|
||||
/// ⚠ That correspondence does not extend to the rest of the bitstream field.
|
||||
/// `seq_level_idx` is 5 bits: 24…30 are reserved and 31 is Annex A's "maximum
|
||||
/// parameters" sentinel — "not constrained to a level" — which has no Std code
|
||||
/// point and is NOT an ordering above 7.3. The decoder's gate therefore treats
|
||||
/// a stream above this ceiling as advisory rather than comparing it as a level
|
||||
/// (`VkAv1Decoder::ensure_state`).
|
||||
pub max_level: hh::StdVideoAV1Level,
|
||||
/// `VkVideoCapabilitiesKHR::stdHeaderVersion` — session creation echoes it back.
|
||||
pub std_header_version: vk::ExtensionProperties,
|
||||
|
||||
@@ -100,6 +100,7 @@ use pf_bitstream::av1::NUM_REF_SLOTS;
|
||||
use pf_bitstream::h264::DisplayCrop;
|
||||
use tracing::debug;
|
||||
use tracing::trace;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::caps::DecodeCaps;
|
||||
use crate::caps::DecodeProfile;
|
||||
@@ -688,6 +689,10 @@ pub struct VkAv1Decoder {
|
||||
/// through a temporal unit, which is why the skip is per FRAME while the error
|
||||
/// is per ACCESS UNIT.
|
||||
awaiting_key: bool,
|
||||
/// One-shot latch for the over-declared-level warning, so a stream whose
|
||||
/// sequence header sits above the device ceiling says so once per decoder
|
||||
/// rather than once per access unit (`ensure_state` runs per AU).
|
||||
level_advisory_warned: bool,
|
||||
}
|
||||
|
||||
impl VkAv1Decoder {
|
||||
@@ -728,6 +733,7 @@ impl VkAv1Decoder {
|
||||
device_lost: false,
|
||||
recovery: RecoveryLatch::default(),
|
||||
awaiting_key: false,
|
||||
level_advisory_warned: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -745,8 +751,10 @@ impl VkAv1Decoder {
|
||||
///
|
||||
/// The negotiated facts are a HINT (the in-band sequence header is
|
||||
/// authoritative), so this is deliberately not a promise that decode will
|
||||
/// succeed: the level ceiling and a sequence header that disagrees with the
|
||||
/// Welcome still surface at the first AU.
|
||||
/// succeed: a coded extent outside the caps, a DPB deeper than the device
|
||||
/// allows, and a sequence header that disagrees with the Welcome all still
|
||||
/// surface at the first AU. The declared LEVEL is not among them — it is
|
||||
/// advisory, and `ensure_state` only warns on it.
|
||||
pub fn probe_stream_support(
|
||||
&self,
|
||||
chroma_format_idc: u8,
|
||||
@@ -1478,8 +1486,9 @@ impl VkAv1Decoder {
|
||||
self.flush();
|
||||
}
|
||||
|
||||
/// Session/caps for THIS plan exist and match its extent + profile, and the
|
||||
/// stream sits inside the device's level ceiling.
|
||||
/// Session/caps for THIS plan exist and match its extent + profile. A declared
|
||||
/// level above the device ceiling warns once and proceeds — see the gate below
|
||||
/// for why an AV1 `seq_level_idx` is advisory and 31 is not even a level.
|
||||
fn ensure_state(&mut self, plan: &AuPlan) -> Result<(), VkDecodeError> {
|
||||
let key = profile_key_for(plan)?;
|
||||
if self.caps.as_ref().map(|(k, _)| *k) != Some(key) {
|
||||
@@ -1491,17 +1500,39 @@ impl VkAv1Decoder {
|
||||
unsafe { query_av1_caps(&self.dev, key) }.map_err(|r| caps_query_error(r, key))?;
|
||||
self.caps = Some((key, derive_caps_av1(&raw, wanted)?));
|
||||
}
|
||||
// The level gate. AV1's `StdVideoAV1Level` is index-coded exactly like the
|
||||
// bitstream's `seq_level_idx` (2.0 = 0 … 7.3 = 23) and ascends with the
|
||||
// level, so this is a plain comparison — of AV1 code points against an AV1
|
||||
// ceiling, the pairing `MaxLevelIdc`'s tag exists to keep honest.
|
||||
// The declared level vs the device ceiling: a DECLARED level above `maxLevel`
|
||||
// is NOT a refusal, for the reason `VkH265Decoder::ensure_state` spells out —
|
||||
// the level is a CLAIM, and the stream's real demands are enforced where they
|
||||
// are physical facts (coded extent and DPB depth, checked in `rebuild_state`).
|
||||
//
|
||||
// AV1 makes the point sharper than H.265 did. `seq_level_idx` is a 5-bit
|
||||
// field; Annex A defines 0…23 (levels 2.0…7.3) and reserves 24…30, but **31 is
|
||||
// the "maximum parameters" level — the spec's own way of saying the bitstream
|
||||
// is not constrained to any level at all**. `StdVideoAV1Level` has no code
|
||||
// point for it (it stops at 7.3 = 23), so the index-coded comparison that
|
||||
// holds across 0…23 is meaningless against 31: the sentinel is not a level
|
||||
// and 31 > 23 is not "too demanding". Real-time encoders emit it as a matter
|
||||
// of course — a 2026-08-13 field report (RTX 5060 client, 4K120) had EVERY
|
||||
// AV1 session demote to D3D11VA on "stream level (seq_level_idx 31) above the
|
||||
// device's maxLevel (AV1 Std level 23)" while the same hardware decoded the
|
||||
// stream trivially. We never write an AV1 level on any host encode path, so
|
||||
// whatever the vendor defaults to is what the client must accept.
|
||||
//
|
||||
// Unlike H.265 there is nothing to clamp: `StdVideoAV1SequenceHeader` carries
|
||||
// no level field (see `params_av1`), so the declaration never reaches the
|
||||
// driver and cannot be invalid usage. Warn once, proceed.
|
||||
let caps_max_level = self.caps.as_ref().expect("queried above").1.max_level_idc;
|
||||
let stream_level = u32::from(stream_level_idx(plan));
|
||||
if stream_level > caps_max_level.code_point() {
|
||||
return Err(VkDecodeError::Unsupported(format!(
|
||||
"stream level (seq_level_idx {stream_level}) above the device's \
|
||||
maxLevel ({caps_max_level})"
|
||||
)));
|
||||
if stream_level > caps_max_level.code_point() && !self.level_advisory_warned {
|
||||
self.level_advisory_warned = true;
|
||||
warn!(
|
||||
stream_level,
|
||||
ceiling = %caps_max_level,
|
||||
"stream declares an AV1 level above the device ceiling — the declared \
|
||||
level is advisory (seq_level_idx 31 means \"maximum parameters\", and \
|
||||
encoders over-declare); proceeding, since the level never reaches the \
|
||||
driver"
|
||||
);
|
||||
}
|
||||
let coded = coded_extent(plan);
|
||||
match &self.state {
|
||||
@@ -2907,10 +2938,45 @@ mod tests {
|
||||
assert_eq!(key.output_format(), Some(crate::caps::NV12));
|
||||
assert!(!key.film_grain);
|
||||
|
||||
// The level gate reads operating point 0 and stays inside the Std range.
|
||||
// The level gate reads operating point 0. This vector declares a real level,
|
||||
// inside the Std range — the sentinel case is pinned separately below.
|
||||
assert!(stream_level_idx(&plan) <= 23);
|
||||
}
|
||||
|
||||
/// `seq_level_idx` 31 is Annex A's "maximum parameters" — "not constrained to a
|
||||
/// level" — not a level above 7.3, and `StdVideoAV1Level` has no code point for
|
||||
/// it. Comparing it as an ordinary level is what demoted every AV1 session on a
|
||||
/// 2026-08-13 field report (RTX 5060, 4K120): `maxLevel` came back 23 (7.3, the
|
||||
/// device's own maximum) and 31 > 23 refused a stream the hardware decodes fine.
|
||||
///
|
||||
/// This pins the ARITHMETIC that made the refusal look reasonable, so nobody
|
||||
/// restores the gate by reading `31 > 23` as "too demanding":
|
||||
#[test]
|
||||
fn the_av1_max_parameters_sentinel_is_not_a_level_above_the_ceiling() {
|
||||
// The ceiling as the gate reads it, on a device that decodes everything the
|
||||
// Std enum can name — 7.3, the top code point there is.
|
||||
let ceiling = crate::caps::MaxLevelIdc::Av1(hh::StdVideoAV1Level_STD_VIDEO_AV1_LEVEL_7_3);
|
||||
assert_eq!(ceiling.code_point(), 23, "the Std enum's top code point");
|
||||
|
||||
// Every `seq_level_idx` the Std enum names compares sanely against it…
|
||||
for idx in 0..=ceiling.code_point() {
|
||||
assert!(idx <= ceiling.code_point());
|
||||
}
|
||||
// …and everything above is OUTSIDE that code space, not above the ceiling:
|
||||
// 24…30 are reserved and 31 is "maximum parameters". A maxed-out device
|
||||
// cannot satisfy the comparison, which is why it is not a capability test.
|
||||
for idx in (ceiling.code_point() + 1)..=31 {
|
||||
assert!(
|
||||
idx > ceiling.code_point(),
|
||||
"seq_level_idx {idx} is outside the Std range, not a more demanding level"
|
||||
);
|
||||
}
|
||||
|
||||
// The field report's exact pairing, kept legible: 31 against a ceiling of 23.
|
||||
assert!(31 > ceiling.code_point());
|
||||
assert_eq!(format!("{ceiling}"), "AV1 Std level 23");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_decoded_key_frame_ends_the_wait_for_one() {
|
||||
let mut planner = Av1Planner::new();
|
||||
@@ -2951,7 +3017,7 @@ mod tests {
|
||||
/// `PlanError::AwaitingIdr`, and the reason [`VkAv1Decoder::awaiting_key`]'s
|
||||
/// docs carry: a clean `Ok(None)` resets the consumer's demotion streak once
|
||||
/// per frame, so a rung whose every key frame fails (film grain on a device
|
||||
/// without the grain profile; a level above `maxLevelIdc`; a sequence header
|
||||
/// without the grain profile; a coded extent outside the caps; a sequence header
|
||||
/// disagreeing with the negotiation) would never demote and the session would
|
||||
/// hold a frozen screen with a clean bill of health.
|
||||
///
|
||||
|
||||
@@ -407,10 +407,23 @@ pub struct JitterTuning {
|
||||
pub headroom_ms: u32,
|
||||
/// Absolute bound on buffered audio — the only hard guarantee on added latency.
|
||||
pub hard_cap_ms: u32,
|
||||
/// Consecutive short reads before the ring goes back to priming. `1` reproduces the old
|
||||
/// `if ring.is_empty() { primed = false }`, where a single transient drain manufactured a
|
||||
/// whole target's worth of fresh silence; every platform now uses hysteresis.
|
||||
pub deprime_after: u32,
|
||||
/// How long the ring may run short before it gives up and goes back to priming, in
|
||||
/// MILLISECONDS of starvation — not a count of callbacks.
|
||||
///
|
||||
/// It used to be a callback count, and that made the hysteresis mean something different on
|
||||
/// every platform, because a callback is not a unit of time: the same `4` was ~40 ms of slack
|
||||
/// on a 10 ms WASAPI quantum and **20 ms on iOS**, whose session asks for a 5 ms IO buffer —
|
||||
/// the shortest fuse of any client, on the one with the burstiest transport. A 100 ms Wi-Fi
|
||||
/// delivery stall then de-primed the Apple ring on every single bunching cycle (measured: 120
|
||||
/// audible gaps in 10 minutes at a 5 ms quantum, versus 3 at 8 ms and 1 at 16 ms, on an
|
||||
/// otherwise identical link) while the same policy rode it out everywhere else. Expressed in
|
||||
/// time, one number means one thing on all four clients and a device's buffer size stops
|
||||
/// silently re-tuning the de-prime behaviour.
|
||||
///
|
||||
/// A floor of `MIN_DEPRIME_CALLBACKS` callbacks still applies, so a large-quantum device
|
||||
/// keeps real hysteresis: `1` reproduces the old `if ring.is_empty() { primed = false }`, where
|
||||
/// a single transient drain manufactured a whole target's worth of fresh silence.
|
||||
pub deprime_ms: u32,
|
||||
}
|
||||
|
||||
impl JitterTuning {
|
||||
@@ -421,7 +434,7 @@ impl JitterTuning {
|
||||
max_target_ms: 60,
|
||||
headroom_ms: 25,
|
||||
hard_cap_ms: 80,
|
||||
deprime_after: 4,
|
||||
deprime_ms: 40,
|
||||
};
|
||||
/// WASAPI shared-mode event-driven render: the engine buffers for us, but nothing rate-matches.
|
||||
pub const WASAPI: JitterTuning = JitterTuning {
|
||||
@@ -429,15 +442,21 @@ impl JitterTuning {
|
||||
max_target_ms: 70,
|
||||
headroom_ms: 30,
|
||||
hard_cap_ms: 90,
|
||||
deprime_after: 4,
|
||||
deprime_ms: 50,
|
||||
};
|
||||
/// CoreAudio via AVAudioEngine — comparable to WASAPI; the iOS IO buffer is already 5 ms.
|
||||
/// CoreAudio via AVAudioEngine — comparable to WASAPI, but the transport is not: this is the
|
||||
/// preset an iPad on Wi-Fi runs, so it gets the longer fuse for the same reason [`AAUDIO`]
|
||||
/// does. (The old comment here read "the iOS IO buffer is already 5 ms" as grounds for using
|
||||
/// WASAPI's callback count unchanged; that quantum is precisely why a count was the wrong unit
|
||||
/// — see [`JitterTuning::deprime_ms`].)
|
||||
///
|
||||
/// [`AAUDIO`]: JitterTuning::AAUDIO
|
||||
pub const COREAUDIO: JitterTuning = JitterTuning {
|
||||
base_target_ms: 20,
|
||||
max_target_ms: 70,
|
||||
headroom_ms: 30,
|
||||
hard_cap_ms: 90,
|
||||
deprime_after: 4,
|
||||
deprime_ms: 60,
|
||||
};
|
||||
/// AAudio hands us a raw realtime callback and makes us own the buffer, and Wi-Fi power-save
|
||||
/// bunching lands as underruns = crackle. Android therefore starts DEEPER — but at 25 ms, not
|
||||
@@ -448,7 +467,7 @@ impl JitterTuning {
|
||||
max_target_ms: 90,
|
||||
headroom_ms: 40,
|
||||
hard_cap_ms: 120,
|
||||
deprime_after: 5,
|
||||
deprime_ms: 60,
|
||||
};
|
||||
|
||||
/// How far above the live target the depth average must sit before drift correction sheds:
|
||||
@@ -471,11 +490,21 @@ impl JitterTuning {
|
||||
pub struct JitterStep {
|
||||
/// Interleaved samples to discard from the FRONT of the ring before reading.
|
||||
pub drop_front: usize,
|
||||
/// When non-zero, `drop_front` is a smooth drift correction and this many interleaved samples
|
||||
/// of linear crossfade should be applied across the seam ([`crossfade_drop`] does it for a
|
||||
/// `VecDeque<f32>` ring). Zero means discard hard — either nothing is being dropped, or the
|
||||
/// ring blew the hard cap and is already a discontinuity.
|
||||
/// Interleaved samples of linear crossfade to apply across the seam left by `drop_front`
|
||||
/// ([`crossfade_drop`] does it for a `VecDeque<f32>` ring). Zero only when nothing is dropped.
|
||||
///
|
||||
/// BOTH kinds of drop are faded. The hard-cap trim used to splice raw, on the reasoning that a
|
||||
/// ring which blew its ceiling "is already a discontinuity" — but that is a statement about the
|
||||
/// ARRIVALS, not about the samples either side of the seam, which are ordinary continuous
|
||||
/// audio. It is also the drop that actually fires in the field: a bunching Wi-Fi link trimmed
|
||||
/// 120 times in 10 simulated minutes where the smooth shed fired for drift a handful of times.
|
||||
/// The gentle path that almost never runs was the one being faded.
|
||||
pub crossfade: usize,
|
||||
/// `drop_front` was the hard-cap backstop (a burst blew the ceiling) rather than the smooth
|
||||
/// drift shed. Both fade now, so the fade length no longer distinguishes them — and the two
|
||||
/// mean very different things to anyone reading logs or a test: sheds are the policy working,
|
||||
/// trims are the link outrunning the headroom.
|
||||
pub hard_trim: bool,
|
||||
/// Emit silence this callback: still priming, or re-priming after a sustained drain.
|
||||
pub silence: bool,
|
||||
}
|
||||
@@ -515,6 +544,19 @@ const SHRINK_PROBE_MS: u32 = 5_000;
|
||||
/// consecutive-empties hysteresis alone converges to. A full ring's underrun (one packet a few
|
||||
/// ms late) is nowhere near hollow and keeps the hysteresis.
|
||||
const DEPRIME_DEBT_MS: u32 = GROW_STEP_MS;
|
||||
/// Floor, in callbacks, under `JitterTuning::deprime_ms`: however short the starvation window works
|
||||
/// out to in time, a de-prime always needs at least this many consecutive short reads. A device
|
||||
/// with a quantum at or above `deprime_ms` would otherwise de-prime on the FIRST short read —
|
||||
/// exactly the "a single transient drain manufactures a whole target of fresh silence" defect the
|
||||
/// hysteresis exists to prevent, reintroduced at the other end of the quantum range.
|
||||
///
|
||||
/// Deliberately NOT `pub`: it is an internal detail of the policy, and cbindgen exports every
|
||||
/// public const into the C header, where this one would land unprefixed next to
|
||||
/// `PUNKTFUNK_AUDIO_*` and pollute every embedder's macro namespace.
|
||||
const MIN_DEPRIME_CALLBACKS: u32 = 2;
|
||||
// A de-prime on the FIRST short read is the defect the hysteresis exists to prevent, so hold the
|
||||
// floor at build time rather than in a test: tuning it to 1 should not compile.
|
||||
const _: () = assert!(MIN_DEPRIME_CALLBACKS >= 2);
|
||||
/// How long a failed probe keeps the sync loop from driving another shrink. Without this the
|
||||
/// loop pays an audible starvation event every [`SHRINK_QUIET_SYNC_MS`] on any link whose jitter
|
||||
/// genuinely needs the depth — sync asks for less, the ring shrinks, the link answers, the ring
|
||||
@@ -545,8 +587,12 @@ pub struct JitterPolicy {
|
||||
/// The live target, in interleaved samples — `base_target_ms` grown by underrun pressure.
|
||||
target: usize,
|
||||
primed: bool,
|
||||
/// Consecutive short reads (de-prime hysteresis).
|
||||
/// Consecutive short reads, and the audio they starved for in interleaved samples. BOTH gate
|
||||
/// the de-prime: the run must be at least [`JitterTuning::deprime_ms`] long AND at least
|
||||
/// [`MIN_DEPRIME_CALLBACKS`] callbacks, so the hysteresis means the same span of time whatever
|
||||
/// the device's quantum, without collapsing to a hair trigger on a large-quantum device.
|
||||
empties: u32,
|
||||
empties_run: usize,
|
||||
/// EWMA of ring depth, interleaved samples.
|
||||
depth_avg: f32,
|
||||
/// Consumed samples for which the EWMA has stayed above the shed threshold.
|
||||
@@ -594,6 +640,7 @@ impl JitterPolicy {
|
||||
target: tuning.base_target_ms as usize * per_ms,
|
||||
primed: false,
|
||||
empties: 0,
|
||||
empties_run: 0,
|
||||
depth_avg: 0.0,
|
||||
over_run: 0,
|
||||
underruns: 0,
|
||||
@@ -693,9 +740,14 @@ impl JitterPolicy {
|
||||
|
||||
let mut out = JitterStep::default();
|
||||
if depth > cap {
|
||||
// Blew the ceiling: a burst arrived, or we were wedged. Already a discontinuity —
|
||||
// discard hard, and reset the drift timer so the trim isn't double-counted as drift.
|
||||
// Blew the ceiling: a burst arrived, or we were wedged. Discard down to the cap and
|
||||
// reset the drift timer so the trim isn't double-counted as drift. Faded like any
|
||||
// other drop — see `JitterStep::crossfade` for why this used to splice raw and why
|
||||
// that was backwards.
|
||||
out.drop_front = depth - cap;
|
||||
out.hard_trim = true;
|
||||
out.crossfade = (SHED_CROSSFADE_MS as usize * self.per_ms)
|
||||
.min(depth.saturating_sub(out.drop_front));
|
||||
self.over_run = 0;
|
||||
} else if self.depth_avg
|
||||
> (target + self.tuning.shed_excess_ms() as usize * self.per_ms) as f32
|
||||
@@ -717,6 +769,7 @@ impl JitterPolicy {
|
||||
if !self.primed && depth.saturating_sub(out.drop_front) >= target {
|
||||
self.primed = true;
|
||||
self.empties = 0;
|
||||
self.empties_run = 0;
|
||||
// The refill just banked this much: seed the average with it rather than letting it
|
||||
// climb from wherever the drought left it — a freshly-primed ring would otherwise
|
||||
// read as hollow for the EWMA's whole settling time, and the FIRST late packet
|
||||
@@ -784,14 +837,22 @@ impl JitterPolicy {
|
||||
if ran_short {
|
||||
self.quiet_run = 0;
|
||||
self.empties += 1;
|
||||
if self.empties >= self.tuning.deprime_after || self.hollow {
|
||||
// The consecutive-empties hysteresis protects a FULL ring from one late packet.
|
||||
// A hollow ring is the opposite case: the target has been raised but the depth
|
||||
// never re-banked (growth is a promise; only a re-prime cashes it), and riding
|
||||
// that out is a click per bunching period, forever. The click just heard has
|
||||
// already paid for the refill — take it now.
|
||||
self.empties_run += want;
|
||||
// Starved for `deprime_ms` of audio, over at least MIN_DEPRIME_CALLBACKS callbacks.
|
||||
// Both, because either alone is wrong at one end of the quantum range: time alone is a
|
||||
// hair trigger on a device whose single quantum already exceeds the window, and a
|
||||
// callback count alone is the platform-dependent fuse this replaced.
|
||||
let starved = self.empties_run >= self.tuning.deprime_ms as usize * self.per_ms
|
||||
&& self.empties >= MIN_DEPRIME_CALLBACKS;
|
||||
if starved || self.hollow {
|
||||
// The starvation hysteresis protects a FULL ring from one late packet. A hollow
|
||||
// ring is the opposite case: the target has been raised but the depth never
|
||||
// re-banked (growth is a promise; only a re-prime cashes it), and riding that out
|
||||
// is a click per bunching period, forever. The click just heard has already paid
|
||||
// for the refill — take it now.
|
||||
self.primed = false;
|
||||
self.empties = 0;
|
||||
self.empties_run = 0;
|
||||
}
|
||||
if !restored {
|
||||
self.underruns += 1;
|
||||
@@ -814,6 +875,7 @@ impl JitterPolicy {
|
||||
// the path above takes over. A near-miss is pressure, not quiet.
|
||||
self.quiet_run = 0;
|
||||
self.empties = 0;
|
||||
self.empties_run = 0;
|
||||
if !self.near_miss_grown && !restored {
|
||||
self.near_miss_grown = true;
|
||||
let grown = self.target + GROW_STEP_MS as usize * self.per_ms;
|
||||
@@ -821,6 +883,7 @@ impl JitterPolicy {
|
||||
}
|
||||
} else {
|
||||
self.empties = 0;
|
||||
self.empties_run = 0;
|
||||
self.quiet_run += want;
|
||||
// A grown target normally relaxes only after a long quiet spell, because without other
|
||||
// evidence the only thing that can justify giving up hard-won slack is time. When the
|
||||
@@ -862,9 +925,10 @@ pub const SAMPLE_RATE_HZ: u32 = 48_000;
|
||||
/// `fade` samples so a drift correction is inaudible rather than a click.
|
||||
///
|
||||
/// The dropped region's tail fades out while the surviving head fades in, so the waveform is
|
||||
/// continuous across the splice. `fade == 0` discards hard (what a hard-cap trim wants — that
|
||||
/// backlog is already a discontinuity). Shared by the three `VecDeque<f32>` rings; the Apple ring
|
||||
/// is index-based and mirrors this in Swift.
|
||||
/// continuous across the splice. `fade == 0` discards hard; no caller in the policy asks for that
|
||||
/// any more (see [`JitterStep::crossfade`]), but it stays honoured for callers that splice at a
|
||||
/// point they know is already discontinuous. Shared by the three `VecDeque<f32>` rings; the Apple
|
||||
/// ring is index-based and mirrors this in Swift.
|
||||
pub fn crossfade_drop(ring: &mut std::collections::VecDeque<f32>, drop: usize, fade: usize) {
|
||||
if drop == 0 || ring.len() < drop {
|
||||
return;
|
||||
@@ -876,17 +940,19 @@ pub fn crossfade_drop(ring: &mut std::collections::VecDeque<f32>, drop: usize, f
|
||||
}
|
||||
// The last `fade` samples of what we are about to discard are the fade-OUT source; they blend
|
||||
// into the first `fade` samples of what survives.
|
||||
let mut faded = Vec::with_capacity(fade);
|
||||
//
|
||||
// Blended in place and BEFORE the drain, with no scratch buffer: a value written at `drop + i`
|
||||
// can never be read again as a fade-OUT source, because those sources are `drop - fade + j` for
|
||||
// `j < fade`, i.e. strictly below `drop`. One ascending pass is therefore safe — and this runs
|
||||
// inside realtime audio callbacks, where the `Vec` this used to allocate had no business being.
|
||||
// It now runs on every hard-cap trim too, which is the common case on a bunching link.
|
||||
for i in 0..fade {
|
||||
let old = ring[drop - fade + i];
|
||||
let new = ring[drop + i];
|
||||
let t = (i + 1) as f32 / (fade + 1) as f32;
|
||||
faded.push(old * (1.0 - t) + new * t);
|
||||
ring[drop + i] = old * (1.0 - t) + new * t;
|
||||
}
|
||||
ring.drain(..drop);
|
||||
for (i, v) in faded.into_iter().enumerate() {
|
||||
ring[i] = v;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- per-platform channel-layout helpers (pure data; no platform deps) --------------------
|
||||
@@ -1460,11 +1526,17 @@ mod tests {
|
||||
|
||||
let s = p.step(depth, want);
|
||||
if s.drop_front > 0 {
|
||||
if s.crossfade > 0 {
|
||||
out.soft_sheds += 1;
|
||||
} else {
|
||||
// Told apart by `hard_trim`, not by the fade length — both kinds fade now.
|
||||
if s.hard_trim {
|
||||
out.hard_trims += 1;
|
||||
} else {
|
||||
out.soft_sheds += 1;
|
||||
}
|
||||
assert!(
|
||||
s.crossfade > 0,
|
||||
"every drop must be faded: dropped {} with no crossfade",
|
||||
s.drop_front
|
||||
);
|
||||
depth -= s.drop_front.min(depth);
|
||||
}
|
||||
if s.silence {
|
||||
@@ -1508,7 +1580,22 @@ mod tests {
|
||||
"{name}: the headroom band is cut short by the hard cap"
|
||||
);
|
||||
assert!(t.max_target_ms >= t.base_target_ms, "{name}");
|
||||
assert!(t.deprime_after >= 2, "{name}: needs real hysteresis");
|
||||
// Real hysteresis, in time: a drought has to outlast several protocol frames before
|
||||
// the ring gives up, or one late packet manufactures a whole target of fresh silence.
|
||||
assert!(
|
||||
t.deprime_ms >= 4 * FRAME_MS,
|
||||
"{name}: de-primes after {} ms — a single late packet would trip it",
|
||||
t.deprime_ms
|
||||
);
|
||||
// ...and never longer than the deepest buffer this preset would ever hold: past that
|
||||
// point the drought has already cost more than the re-prime it is trying to avoid, and
|
||||
// every callback in between is dribbling partial reads at the listener.
|
||||
assert!(
|
||||
t.deprime_ms <= t.max_target_ms,
|
||||
"{name}: waits {} ms to de-prime but never buffers more than {} ms",
|
||||
t.deprime_ms,
|
||||
t.max_target_ms
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1619,7 +1706,20 @@ mod tests {
|
||||
s.drop_front > 0,
|
||||
"a 500 ms backlog must be trimmed on the spot"
|
||||
);
|
||||
assert_eq!(s.crossfade, 0, "a blown cap is already a discontinuity");
|
||||
assert!(s.hard_trim, "a cap trim must announce itself as one");
|
||||
// ...and it is FADED. This used to assert the opposite ("a blown cap is already a
|
||||
// discontinuity"), which confused the arrivals with the audio: the samples either side of
|
||||
// the splice are ordinary continuous sound, and a raw seam through them is a click. It is
|
||||
// also the drop that actually fires in the field — a bunching Wi-Fi link trims far more
|
||||
// often than drift sheds — so the one path that was left unfaded was the audible one.
|
||||
assert!(
|
||||
s.crossfade > 0,
|
||||
"a cap trim splices real audio and must be faded"
|
||||
);
|
||||
assert!(
|
||||
s.crossfade <= s.drop_front,
|
||||
"the fade cannot outrun what is being dropped"
|
||||
);
|
||||
let left = 500 * pm - s.drop_front;
|
||||
assert!(
|
||||
left <= JitterTuning::AAUDIO.hard_cap_ms as usize * pm,
|
||||
@@ -1647,12 +1747,46 @@ mod tests {
|
||||
assert!(p.is_primed());
|
||||
p.note_read(true); // one short read
|
||||
assert!(p.is_primed(), "a single short read must not de-prime");
|
||||
for _ in 1..JitterTuning::PIPEWIRE.deprime_after {
|
||||
let deprime = JitterTuning::PIPEWIRE.deprime_ms as usize;
|
||||
for _ in 1..(deprime / 5) {
|
||||
p.note_read(true);
|
||||
}
|
||||
assert!(!p.is_primed(), "a sustained drain must re-prime");
|
||||
}
|
||||
|
||||
/// THE regression this replaced a callback count for: the de-prime fuse must be the same
|
||||
/// SPAN OF TIME whatever the device's IO quantum. As a count it was not — the same `4` was
|
||||
/// ~40 ms on a 10 ms WASAPI quantum and 20 ms on iOS, whose session asks for a 5 ms IO buffer.
|
||||
/// A Wi-Fi delivery stall therefore de-primed the Apple ring on every bunching cycle while the
|
||||
/// identical policy rode it out everywhere else. Plant the defect by restoring a fixed count
|
||||
/// and the two quanta below stop agreeing.
|
||||
#[test]
|
||||
fn deprime_fuse_is_a_duration_not_a_callback_count() {
|
||||
for quantum_ms in [5usize, 8, 10, 16, 21] {
|
||||
let t = JitterTuning::COREAUDIO;
|
||||
let pm = per_ms(2);
|
||||
let want = quantum_ms * pm;
|
||||
let mut p = JitterPolicy::new(t, 2);
|
||||
// Prime well above target so the hysteresis path is what we measure, not `hollow`.
|
||||
assert!(!p.step(80 * pm, want).silence);
|
||||
assert!(p.is_primed());
|
||||
let mut starved_ms = 0;
|
||||
while p.is_primed() && starved_ms < 10 * t.deprime_ms as usize {
|
||||
p.note_read(true);
|
||||
starved_ms += quantum_ms;
|
||||
}
|
||||
assert!(!p.is_primed(), "q={quantum_ms}ms: never de-primed at all");
|
||||
// One quantum of granularity either side — the fuse can only be checked per callback.
|
||||
let floor = (t.deprime_ms as usize).min(quantum_ms * MIN_DEPRIME_CALLBACKS as usize);
|
||||
assert!(
|
||||
starved_ms >= floor && starved_ms < t.deprime_ms as usize + quantum_ms,
|
||||
"q={quantum_ms}ms de-primed after {starved_ms} ms, not ~{} ms — the fuse is still \
|
||||
scaling with the quantum",
|
||||
t.deprime_ms
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A device that pulls a big quantum cannot sustain a target below it: the effective target
|
||||
/// must lift, or the ring oscillates prime → dropout → re-prime forever.
|
||||
#[test]
|
||||
|
||||
@@ -47,7 +47,15 @@ pub(crate) const FLUSH_AFTER: Duration = Duration::from_millis(250);
|
||||
/// Minimum spacing between jump-to-live events, so a bottleneck that instantly rebuilds the queue (a
|
||||
/// link/consumer that can't sustain the bitrate at all) degrades into a periodic skip + a logged
|
||||
/// warning instead of a continuous flush/keyframe storm.
|
||||
pub(crate) const FLUSH_COOLDOWN: Duration = Duration::from_secs(2);
|
||||
///
|
||||
/// **Public because the HOST needs it to read its own logs.** Each jump-to-live sends a keyframe
|
||||
/// request, so a client that cannot sustain the rate asks for one at exactly this spacing,
|
||||
/// forever — and the host's recovery-cadence detector saw that perfect periodicity and blamed a
|
||||
/// periodic *display* disturbance (2026-08-13 field log: `period_s=2.0`, three subsystems named,
|
||||
/// none of them the cause). Perfect periodicity is the signature of a fixed software cooldown,
|
||||
/// not of a physical disturbance. The host compares against this constant rather than a copy of
|
||||
/// the number, so the two can never drift apart.
|
||||
pub const FLUSH_COOLDOWN: Duration = Duration::from_secs(2);
|
||||
|
||||
/// A clock-triggered jump-to-live that discarded fewer datagrams than this (and no queued AUs)
|
||||
/// found NO local backlog: the frames read as late, but nothing here was actually behind. Two
|
||||
|
||||
@@ -42,6 +42,7 @@ mod recovery;
|
||||
mod rumble;
|
||||
mod worker;
|
||||
|
||||
pub use self::frame_channel::FLUSH_COOLDOWN;
|
||||
pub use self::planes::AudioPacket;
|
||||
pub use self::probe::ProbeOutcome;
|
||||
pub use self::rumble::{ActuatorQuirks, RumbleCommand};
|
||||
|
||||
@@ -165,7 +165,18 @@ pub use stats::Stats;
|
||||
/// Additive and client-local: the v3 tail has been on the wire (and length-tolerant in both
|
||||
/// decoders) since it landed, and the host sends the same bytes either way, so [`WIRE_VERSION`] is
|
||||
/// unchanged.
|
||||
pub const ABI_VERSION: u32 = 18;
|
||||
/// v19: added `punktfunk_connection_note_frame_index_ex` and
|
||||
/// `punktfunk_reanchor_gate_arm_expecting_drops` — the width-carrying half of the reanchor gate.
|
||||
/// `note_frame_index_ex` reports how MANY frames an arrival revealed as missing where
|
||||
/// `punktfunk_connection_note_frame_index` reports only whether any were; passing that width to
|
||||
/// `arm_expecting_drops` pre-credits the reassembler's `frames_dropped` climb that the same loss
|
||||
/// produces up to ~120 ms later, so the gate does not read one loss as two and re-freeze a stream a
|
||||
/// fast LTR-RFI anchor has already healed. NEW symbols, not widened ones — the same rule v18 states:
|
||||
/// both originals keep their signatures and their behaviour, so an embedder that never adopts either
|
||||
/// is unchanged (it simply keeps the double-arm race the pair exists to close). Additive and
|
||||
/// client-local: nothing new goes on the wire — the width is computed from frame indices the client
|
||||
/// already receives — so [`WIRE_VERSION`] is unchanged.
|
||||
pub const ABI_VERSION: u32 = 19;
|
||||
|
||||
/// The punktfunk/1 **wire** version — what `Hello`/`Welcome` carry and hosts equality-check.
|
||||
/// Deliberately its own constant: [`ABI_VERSION`] tracks the embeddable **C surface**
|
||||
|
||||
@@ -219,10 +219,6 @@ pipewire = "0.9"
|
||||
# in the subsystem extraction, and each of those crates declares them itself — only the manifest
|
||||
# entries were left behind, along with comments describing code this crate no longer contains.
|
||||
# Verified unused before removal: zero `use`/path references across src/ + build.rs.
|
||||
# Read the Lutris library DB (`pga.db`) for the Lutris store provider. `bundled` vendors + compiles
|
||||
# SQLite (cc, already needed for ffmpeg/opus) so there's no system libsqlite3 runtime dependency —
|
||||
# clean for the deb/rpm/flatpak packaging. Opened read-only/immutable (Lutris may hold it open).
|
||||
rusqlite = { version = "0.40", features = ["bundled"] }
|
||||
# `libcuda.so.1` is dlopen'd at runtime (NOT link-time) so one Linux binary runs on NVIDIA
|
||||
# (zero-copy via CUDA) AND on AMD/Intel (VAAPI, no NVIDIA driver present) — see `zerocopy::cuda`.
|
||||
libloading = "0.9"
|
||||
@@ -319,12 +315,12 @@ windows = { version = "0.62", features = [
|
||||
# kept a fourth windows-sys major compiling. 0.8.1 moves to `windows-sys 0.61`, which the tree
|
||||
# already builds, and that duplicate is gone. (0.8.0 is NOT enough — it lands on 0.59.)
|
||||
windows-service = "0.8"
|
||||
# Read the GOG.com install registry (HKLM\SOFTWARE\WOW6432Node\GOG.com\Games) for the GOG store
|
||||
# provider — ergonomic + correct-by-construction vs. hand-rolled Reg* FFI for subkey enumeration.
|
||||
# Registry reads the host does on Windows — ergonomic + correct-by-construction vs. hand-rolled
|
||||
# Reg* FFI for subkey enumeration. Survived the removal of the built-in store scanners (which is
|
||||
# what first pulled it in): `library/launch.rs` resolves launcher install paths for the typed launch
|
||||
# kinds a plugin publishes, `procscan/windows.rs` maps processes, and the two `audio/windows/`
|
||||
# modules read and clean up device nodes.
|
||||
winreg = "0.56"
|
||||
# Parse each Xbox/Game-Pass game's MicrosoftGame.config (GDK manifest XML) for the Xbox store
|
||||
# provider — a small read-only DOM is all we need (Identity/Executable/ShellVisuals/StoreId).
|
||||
roxmltree = "0.21"
|
||||
# WASAPI loopback audio capture (default render endpoint -> 48 kHz stereo f32 for the Opus path).
|
||||
wasapi = "0.24"
|
||||
# Shared host<->driver wire contract for the pf-vdisplay IddCx virtual-display backend: the
|
||||
|
||||
@@ -62,6 +62,17 @@ pub struct PwAudioCapturer {
|
||||
/// active). Toggled by open/[`drain`](AudioCapturer::drain) (claim) and
|
||||
/// [`idle`](AudioCapturer::idle)/Drop (release).
|
||||
claimed: bool,
|
||||
/// Whether a session is currently CONSUMING this capturer, shared with the PipeWire
|
||||
/// thread so the drop counter can tell "the encode thread fell behind" from "nobody is
|
||||
/// reading". The capturer is host-lifetime and merely PARKED between sessions
|
||||
/// ([`idle`](AudioCapturer::idle)), so without this the producer keeps filling the bounded
|
||||
/// hand-off channel, every `try_send` fails once it is full, and the plane reports a 100 %
|
||||
/// drop rate — warning that "the stream will click" when there is no stream. A 2026-08-13
|
||||
/// field host log carried ten such warnings, up to `dropped_chunks=11251` (= 30 s × 375
|
||||
/// chunks/s, i.e. every single chunk), each one straddling a session boundary and each one
|
||||
/// meaningless. Distinct from `claimed`, which tracks the sink-routing claim and only
|
||||
/// exists when the stream sink is enabled at all.
|
||||
active: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl PwAudioCapturer {
|
||||
@@ -90,10 +101,21 @@ impl PwAudioCapturer {
|
||||
// mode the sink node must exist before we claim the default to its name.
|
||||
let (ready_tx, ready_rx) = sync_channel::<Result<()>>(1);
|
||||
let thread_sink_name = sink_name.clone();
|
||||
// Opens at session start (see the routing claim below), so the consumer is live from
|
||||
// the first chunk.
|
||||
let active = Arc::new(AtomicBool::new(true));
|
||||
let thread_active = Arc::clone(&active);
|
||||
thread::Builder::new()
|
||||
.name("punktfunk-pw-audio".into())
|
||||
.spawn(move || {
|
||||
if let Err(e) = pw_thread(tx, quit_rx, channels, thread_sink_name, ready_tx) {
|
||||
if let Err(e) = pw_thread(
|
||||
tx,
|
||||
quit_rx,
|
||||
channels,
|
||||
thread_sink_name,
|
||||
ready_tx,
|
||||
thread_active,
|
||||
) {
|
||||
tracing::error!(error = %format!("{e:#}"), "pipewire audio thread failed");
|
||||
}
|
||||
})
|
||||
@@ -118,12 +140,16 @@ impl PwAudioCapturer {
|
||||
quit: quit_tx,
|
||||
sink_name,
|
||||
claimed,
|
||||
active,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PwAudioCapturer {
|
||||
fn drop(&mut self) {
|
||||
// The receiver dies with us; anything the producer still pushes is unwanted by
|
||||
// definition, and it must not be reported as the encode thread falling behind.
|
||||
self.active.store(false, Ordering::Relaxed);
|
||||
if self.claimed {
|
||||
self.claimed = false;
|
||||
stream_sink::release();
|
||||
@@ -157,9 +183,15 @@ impl AudioCapturer for PwAudioCapturer {
|
||||
stream_sink::claim(name);
|
||||
self.claimed = true;
|
||||
}
|
||||
// Ordered AFTER the backlog drain, so the producer never counts a drop against a
|
||||
// channel this call is still emptying.
|
||||
self.active.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn idle(&mut self) {
|
||||
// Parked: from here the channel fills and stays full, and those drops are nobody's
|
||||
// fault. See `PwAudioCapturer::active`.
|
||||
self.active.store(false, Ordering::Relaxed);
|
||||
if self.claimed {
|
||||
self.claimed = false;
|
||||
stream_sink::release();
|
||||
@@ -644,6 +676,7 @@ fn pw_thread(
|
||||
channels: u32,
|
||||
sink_name: Option<String>,
|
||||
ready: std::sync::mpsc::SyncSender<Result<()>>,
|
||||
active: Arc<AtomicBool>,
|
||||
) -> Result<()> {
|
||||
use pipewire as pw;
|
||||
use pw::{properties::properties, spa};
|
||||
@@ -735,6 +768,9 @@ fn pw_thread(
|
||||
/// never again — the one number that identifies a clamped quantum, invisible on every
|
||||
/// subsequent open (including every reopen after a device change).
|
||||
reported_quantum: bool,
|
||||
/// Shared with the capturer — see [`PwAudioCapturer::active`]. Read on every
|
||||
/// failed hand-off to keep parked-capturer backpressure out of the drop count.
|
||||
active: Arc<AtomicBool>,
|
||||
}
|
||||
let ud = CapUd {
|
||||
tx,
|
||||
@@ -742,6 +778,7 @@ fn pw_thread(
|
||||
stats: Default::default(),
|
||||
last_stats: std::time::Instant::now(),
|
||||
reported_quantum: false,
|
||||
active,
|
||||
};
|
||||
let _listener = stream
|
||||
.add_local_listener_with_user_data(ud)
|
||||
@@ -844,11 +881,15 @@ fn pw_thread(
|
||||
samples.push(f32::from_le_bytes(b));
|
||||
}
|
||||
ud.stats.observe(&samples, ud.channels);
|
||||
// Non-blocking and lossy, as before — but COUNTED. A full channel means the
|
||||
// encode thread is not keeping up, and because the encoder simply
|
||||
// concatenates across the hole every dropped chunk is a click AND a
|
||||
// permanent shift of everything after it.
|
||||
if ud.tx.try_send(samples).is_err() {
|
||||
// Non-blocking and lossy, as before — but COUNTED, and only while a session
|
||||
// is actually reading. A full channel under a LIVE consumer means the encode
|
||||
// thread is not keeping up, and because the encoder simply concatenates
|
||||
// across the hole every dropped chunk is a click AND a permanent shift of
|
||||
// everything after it. A full channel under a PARKED capturer means nothing
|
||||
// at all: the capturer is host-lifetime, so between sessions the channel
|
||||
// fills once and then refuses everything, which counted as a 100 % drop rate
|
||||
// and warned about a stream that did not exist (`PwAudioCapturer::active`).
|
||||
if ud.tx.try_send(samples).is_err() && ud.active.load(Ordering::Relaxed) {
|
||||
ud.stats.dropped_chunks += 1;
|
||||
}
|
||||
if ud.last_stats.elapsed() >= crate::audio::capture_policy::STATS_EVERY {
|
||||
|
||||
@@ -26,13 +26,22 @@
|
||||
//! mixing mono or at 24 kHz) loses to real hardware; see [`super::wiring_plan`]. **Never** the
|
||||
//! Steam Streaming Speakers, whose loopback is silent — validated live;
|
||||
//! * default **RECORDING** → the mic target's capture endpoint (VB-Cable "CABLE Output") so host apps
|
||||
//! record the client's mic by default.
|
||||
//! record the client's mic by default — applied, like the playback default, ONLY while a
|
||||
//! desktop-audio capture is open. It used to be asserted on EVERY wiring pass, mic pump at boot
|
||||
//! included, which left an IDLE box's default recording/communication device parked on a virtual
|
||||
//! microphone nothing feeds — and games bind the default microphone at launch (`SetDefaultEndpoint`
|
||||
//! covers eCommunications, so in-game voice binds it too). The 2026-08 Helldivers 2 field reports
|
||||
//! measured that as 1% lows of 2–5 FPS in a LOCALLY played game while the host sat idle (HD2 is
|
||||
//! Wwise + always-on voice, exactly the "finicky with audio devices" case its own wiki warns
|
||||
//! about). An idle host must leave the box's audio defaults exactly as the operator set them.
|
||||
//!
|
||||
//! Because the playback default is *parked* on a silent sink during a stream, it is remembered
|
||||
//! ([`park_default_playback`], plus an on-disk crash marker) and put back when the capture closes
|
||||
//! ([`restore_default_playback`]) or, after a crash, on the next process's first wiring pass — an
|
||||
//! operator must never be stranded with silent speakers. A default the operator changed themselves
|
||||
//! mid-stream is respected (no restore over their choice).
|
||||
//! Because both defaults are *parked* during a stream — playback on a silent sink, recording on the
|
||||
//! virtual mic — the operator's devices are remembered ([`park_default_playback`] /
|
||||
//! [`park_default_recording`], plus on-disk crash markers) and put back when the capture closes
|
||||
//! ([`restore_default_playback`] / [`restore_default_recording`]) or, after a crash, on the next
|
||||
//! process's first wiring pass — an operator must never be stranded with silent speakers or a dead
|
||||
//! mic. A default the operator changed themselves mid-stream is respected (no restore over their
|
||||
//! choice).
|
||||
//!
|
||||
//! The assignment rules are the PURE [`wiring_plan`](super::wiring_plan) module (unit-tested on every
|
||||
//! platform); this module only enumerates endpoints, applies the plan, and logs. [`wire_now`] runs on
|
||||
@@ -142,8 +151,8 @@ pub(crate) fn endpoint_fingerprint() -> u64 {
|
||||
}
|
||||
|
||||
/// [`wire_now_full`] for callers that only need the assignment (the mic paths).
|
||||
pub(crate) fn wire_now(set_playback: bool) -> Wiring {
|
||||
wire_now_full(set_playback).wiring
|
||||
pub(crate) fn wire_now(park_defaults: bool) -> Wiring {
|
||||
wire_now_full(park_defaults).wiring
|
||||
}
|
||||
|
||||
/// The most recent wiring verdict, as the LAST wiring pass computed it (the mic pump wires
|
||||
@@ -170,13 +179,15 @@ fn pad_render_ids(renders: &[Endpoint]) -> Vec<String> {
|
||||
|
||||
/// Enumerate endpoints, compute the assignment, apply the default-device changes (unless
|
||||
/// `PUNKTFUNK_KEEP_DEFAULT`), and return the plan for the caller to act on (mic target / loopback
|
||||
/// echo guard). `set_playback` — true only from the desktop-audio capture open — additionally
|
||||
/// parks the default PLAYBACK device on the plan's loopback endpoint for the capture's lifetime
|
||||
/// (the mic pump passes false: it runs while the host is idle and must not silence the box).
|
||||
/// Must run on a COM-initialized thread (the WASAPI worker threads all `initialize_mta` first).
|
||||
/// Logged only when the assignment changes, so per-open recomputation stays quiet in the steady
|
||||
/// state.
|
||||
pub(crate) fn wire_now_full(set_playback: bool) -> WiredPlan {
|
||||
/// echo guard). `park_defaults` — true only from the desktop-audio capture open — additionally
|
||||
/// parks the default PLAYBACK device on the plan's loopback endpoint and the default RECORDING
|
||||
/// device on the virtual mic's capture side, both for the capture's lifetime (the mic pump passes
|
||||
/// false: it runs while the host is idle and must neither silence the box nor hold its default
|
||||
/// microphone — the idle-parked recording default is the 2026-08 Helldivers 2 tank, see the
|
||||
/// module docs). Must run on a COM-initialized thread (the WASAPI worker threads all
|
||||
/// `initialize_mta` first). Logged only when the assignment changes, so per-open recomputation
|
||||
/// stays quiet in the steady state.
|
||||
pub(crate) fn wire_now_full(park_defaults: bool) -> WiredPlan {
|
||||
recover_orphaned_default();
|
||||
let renders = list_endpoints(Direction::Render);
|
||||
let captures = list_endpoints(Direction::Capture);
|
||||
@@ -188,11 +199,11 @@ pub(crate) fn wire_now_full(set_playback: bool) -> WiredPlan {
|
||||
// them out of every role. Identity is platform data (stamped container / devnode marker),
|
||||
// so it is collected HERE and passed in, like the candidate lists themselves.
|
||||
let pad_ids = pad_render_ids(&renders);
|
||||
// Mix formats are read only when we are actually going to park the playback default (i.e. a
|
||||
// Mix formats are read only when we are actually going to park the defaults (i.e. a
|
||||
// desktop-audio capture is opening). The mic pump wires on every open while the host is idle
|
||||
// and does not care which loopback endpoint wins, so it must not pay an IAudioClient
|
||||
// activation per render endpoint on every pass.
|
||||
let probe: &dyn Fn(&Endpoint) -> Option<MixFormat> = if set_playback {
|
||||
let probe: &dyn Fn(&Endpoint) -> Option<MixFormat> = if park_defaults {
|
||||
&mix_format_of
|
||||
} else {
|
||||
&wiring_plan::no_formats
|
||||
@@ -311,30 +322,44 @@ pub(crate) fn wire_now_full(set_playback: bool) -> WiredPlan {
|
||||
}
|
||||
}
|
||||
}
|
||||
if set_playback {
|
||||
// Recording-default hygiene, IDLE passes only: builds before 2026-08-14 parked the default
|
||||
// recording on the virtual mic on EVERY wiring pass (boot included) and recorded nothing to
|
||||
// restore — so an upgraded box would otherwise sit wedged on a microphone nothing feeds
|
||||
// until the operator noticed (the Helldivers 2 idle tank; the session-scoped park below
|
||||
// can't heal it either: it remembers a previous default only when the default isn't already
|
||||
// ours). While nothing is parked, a default found sitting on the plan's mic capture moves to
|
||||
// the first real microphone. Session passes own the default and are exempt; a box with no
|
||||
// real microphone is left alone.
|
||||
if !park_defaults && PARKED_REC.lock().unwrap().is_none() {
|
||||
if let Some((mic_name, mic_id)) = &wiring.mic_capture {
|
||||
if default_capture_id().as_deref() == Some(mic_id.as_str()) {
|
||||
if let Some((name, id)) =
|
||||
wiring_plan::real_capture(&captures, Some(mic_id.as_str()))
|
||||
{
|
||||
match set_default_endpoint(id) {
|
||||
Ok(()) => tracing::info!(from = %mic_name, device = %name,
|
||||
"default recording was left on the virtual mic outside a stream — \
|
||||
moved it back to a real microphone"),
|
||||
Err(e) => tracing::warn!(device = %name, error = %format!("{e:#}"),
|
||||
"failed to move the default recording off the virtual mic"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if park_defaults {
|
||||
if let Some((name, id)) = &wiring.loopback_render {
|
||||
let mic_id = wiring.mic_render.as_ref().map(|(_, m)| m.as_str());
|
||||
park_default_playback(name, id, changed, mic_id);
|
||||
}
|
||||
}
|
||||
if let Some((name, id)) = &wiring.mic_capture {
|
||||
// `set_default_endpoint` is NOT a no-op on an unchanged default: it unconditionally
|
||||
// fires SetDefaultEndpoint for all three roles (an audio-policy write plus a
|
||||
// device-graph notification, each). Re-asserting on every wiring pass therefore both
|
||||
// churned the policy store AND silently stomped an operator's own recording-device
|
||||
// choice within one reopen cycle — write only when the plan changed or the default
|
||||
// actually drifted off the target.
|
||||
if changed || default_capture_id().as_deref() != Some(id.as_str()) {
|
||||
match set_default_endpoint(id) {
|
||||
Ok(()) => {
|
||||
if changed {
|
||||
tracing::info!(device = %name,
|
||||
"audio wiring: default recording = virtual mic (apps record the client's mic)");
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!(device = %name, error = %format!("{e:#}"),
|
||||
"audio wiring: failed to set the default recording device"),
|
||||
}
|
||||
// The recording default is SESSION-SCOPED like the playback default, and for the same
|
||||
// reason inverted: parking it while idle handed the box's default microphone (and, via
|
||||
// eCommunications, every game's voice input) to a virtual mic nothing feeds — the
|
||||
// 2026-08 Helldivers 2 idle tank (see the module docs). A game launched DURING the
|
||||
// stream still binds the client's mic (this runs before the session's game does);
|
||||
// one launched before the stream keeps the operator's mic, which is the honest answer.
|
||||
if let Some((name, id)) = &wiring.mic_capture {
|
||||
park_default_recording(name, id, changed);
|
||||
}
|
||||
}
|
||||
done(wiring)
|
||||
@@ -350,6 +375,26 @@ fn park_marker_path() -> std::path::PathBuf {
|
||||
pf_paths::config_dir().join("audio-default.prev")
|
||||
}
|
||||
|
||||
/// The operator's default recording endpoint while we have it parked on the virtual mic:
|
||||
/// `(previous_id, id_we_set)` — the recording-side twin of [`PARKED`].
|
||||
static PARKED_REC: Mutex<Option<(String, String)>> = Mutex::new(None);
|
||||
|
||||
/// On-disk crash marker mirroring [`PARKED_REC`] (two lines: previous id, set id).
|
||||
fn rec_marker_path() -> std::path::PathBuf {
|
||||
pf_paths::config_dir().join("audio-default-rec.prev")
|
||||
}
|
||||
|
||||
/// Consume a park marker file: returns the PREVIOUS default's id when the marker existed AND the
|
||||
/// current default still is the endpoint we set — a default the operator changed since wins, like
|
||||
/// on every other restore path. The file is removed either way (it describes a park that is over).
|
||||
fn take_marker(path: &std::path::Path, current_default: Option<String>) -> Option<String> {
|
||||
let s = std::fs::read_to_string(path).ok()?;
|
||||
let _ = std::fs::remove_file(path);
|
||||
let mut lines = s.lines();
|
||||
let (prev, set) = (lines.next()?, lines.next()?);
|
||||
(current_default.as_deref() == Some(set)).then(|| prev.to_string())
|
||||
}
|
||||
|
||||
/// The current default RENDER endpoint id, if any. pub(crate): the pad-endpoint provisioning
|
||||
/// uses it for its default-device guard (a freshly minted pad endpoint must never stay the
|
||||
/// default playback device).
|
||||
@@ -374,31 +419,28 @@ pub(crate) fn default_capture_id() -> Option<String> {
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Once per process: if a crash marker from a previous run exists, the host died while the
|
||||
/// playback default was parked — put the operator's device back, but only if the default still
|
||||
/// IS the endpoint we set (a manual change since the crash wins). Runs on the first wiring pass
|
||||
/// (the mic pump wires eagerly at host start, so this fires at boot, not at the first stream).
|
||||
/// Once per process: if a crash marker from a previous run exists, the host died while a default
|
||||
/// (playback and/or recording) was parked — put the operator's device back, but only if the
|
||||
/// default still IS the endpoint we set (a manual change since the crash wins). Runs on the first
|
||||
/// wiring pass (the mic pump wires eagerly at host start, so this fires at boot, not at the first
|
||||
/// stream).
|
||||
fn recover_orphaned_default() {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| {
|
||||
let path = park_marker_path();
|
||||
let Ok(s) = std::fs::read_to_string(&path) else {
|
||||
return;
|
||||
};
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let mut lines = s.lines();
|
||||
let (Some(prev), Some(set)) = (lines.next(), lines.next()) else {
|
||||
return;
|
||||
};
|
||||
if default_render_id().as_deref() != Some(set) {
|
||||
return;
|
||||
}
|
||||
match set_default_endpoint(prev) {
|
||||
Ok(()) => tracing::info!(
|
||||
"restored the default playback device a previous host run left parked"
|
||||
),
|
||||
Err(e) => tracing::warn!(error = %format!("{e:#}"),
|
||||
"failed to restore the default playback device left by a previous run"),
|
||||
for (path, current, what) in [
|
||||
(park_marker_path(), default_render_id(), "playback"),
|
||||
(rec_marker_path(), default_capture_id(), "recording"),
|
||||
] {
|
||||
let Some(prev) = take_marker(&path, current) else {
|
||||
continue;
|
||||
};
|
||||
match set_default_endpoint(&prev) {
|
||||
Ok(()) => tracing::info!(
|
||||
"restored the default {what} device a previous host run left parked"
|
||||
),
|
||||
Err(e) => tracing::warn!(error = %format!("{e:#}"),
|
||||
"failed to restore the default {what} device left by a previous run"),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -415,20 +457,18 @@ fn recover_orphaned_default() {
|
||||
///
|
||||
/// Returns whether a device was actually put back — the caller only logs it.
|
||||
pub(crate) fn unpark_default_for_uninstall() -> bool {
|
||||
let path = park_marker_path();
|
||||
let Ok(s) = std::fs::read_to_string(&path) else {
|
||||
return false;
|
||||
};
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let mut lines = s.lines();
|
||||
let (Some(prev), Some(set)) = (lines.next(), lines.next()) else {
|
||||
return false;
|
||||
};
|
||||
// A default the operator changed by hand since the park wins, exactly as on the recovery path.
|
||||
if default_render_id().as_deref() != Some(set) {
|
||||
return false;
|
||||
let mut restored = false;
|
||||
for (path, current) in [
|
||||
(park_marker_path(), default_render_id()),
|
||||
(rec_marker_path(), default_capture_id()),
|
||||
] {
|
||||
// A default the operator changed by hand since the park wins, exactly as on the
|
||||
// recovery path (`take_marker` answers None then).
|
||||
if let Some(prev) = take_marker(&path, current) {
|
||||
restored |= set_default_endpoint(&prev).is_ok();
|
||||
}
|
||||
}
|
||||
set_default_endpoint(prev).is_ok()
|
||||
restored
|
||||
}
|
||||
|
||||
/// Make `id` the default playback device for the duration of the desktop-audio capture,
|
||||
@@ -469,6 +509,48 @@ fn park_default_playback(name: &str, id: &str, changed: bool, mic_id: Option<&st
|
||||
}
|
||||
}
|
||||
|
||||
/// Make `id` the default recording device for the duration of the desktop-audio capture —
|
||||
/// [`park_default_playback`]'s recording twin, remembering the operator's current default (in
|
||||
/// memory + the crash marker) the FIRST time so [`restore_default_recording`] can put it back.
|
||||
/// Nothing is remembered when `id` already is the default — there is nothing to restore.
|
||||
fn park_default_recording(name: &str, id: &str, changed: bool) {
|
||||
let cur = default_capture_id();
|
||||
if cur.as_deref() != Some(id) {
|
||||
let mut parked = PARKED_REC.lock().unwrap();
|
||||
match parked.as_mut() {
|
||||
None => {
|
||||
if let Some(prev) = cur.clone() {
|
||||
let _ = std::fs::write(rec_marker_path(), format!("{prev}\n{id}"));
|
||||
*parked = Some((prev, id.to_string()));
|
||||
}
|
||||
}
|
||||
// Re-park onto a different endpoint mid-stream (plan changed): keep the ORIGINAL
|
||||
// previous default, update what we set.
|
||||
Some((prev, set)) if set != id => {
|
||||
let _ = std::fs::write(rec_marker_path(), format!("{prev}\n{id}"));
|
||||
*set = id.to_string();
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
// `set_default_endpoint` is NOT a no-op on an unchanged default: it unconditionally fires
|
||||
// SetDefaultEndpoint for all three roles (an audio-policy write plus a device-graph
|
||||
// notification, each) — write only when the plan changed or the default actually drifted
|
||||
// off the target, or the policy store churns on every reopen.
|
||||
if changed || cur.as_deref() != Some(id) {
|
||||
match set_default_endpoint(id) {
|
||||
Ok(()) => {
|
||||
if changed {
|
||||
tracing::info!(device = %name,
|
||||
"audio wiring: default recording = virtual mic (apps record the client's mic)");
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!(device = %name, error = %format!("{e:#}"),
|
||||
"audio wiring: failed to set the default recording device"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the default playback device back on the endpoint we are already capturing, WITHOUT a
|
||||
/// wiring pass (WP2.4).
|
||||
///
|
||||
@@ -507,6 +589,25 @@ pub(crate) fn restore_default_playback() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the operator's default recording device back after streaming — the inverse of
|
||||
/// [`park_default_recording`], with [`restore_default_playback`]'s exact rules: no-op if we never
|
||||
/// parked it, and a default the operator changed themselves mid-stream is left alone. Must run on
|
||||
/// a COM-initialized thread (called from the capture thread's exit path).
|
||||
pub(crate) fn restore_default_recording() {
|
||||
let Some((prev, set)) = PARKED_REC.lock().unwrap().take() else {
|
||||
return;
|
||||
};
|
||||
let _ = std::fs::remove_file(rec_marker_path());
|
||||
if default_capture_id().as_deref() != Some(set.as_str()) {
|
||||
return;
|
||||
}
|
||||
match set_default_endpoint(&prev) {
|
||||
Ok(()) => tracing::info!("default recording device restored after streaming"),
|
||||
Err(e) => tracing::warn!(error = %format!("{e:#}"),
|
||||
"failed to restore the default recording device after streaming"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a device by endpoint id, with a name for error context.
|
||||
///
|
||||
/// Resolves through [`super::pad_endpoint::open_wasapi_device`] rather than the `wasapi` crate's
|
||||
@@ -518,10 +619,11 @@ pub(crate) fn open_endpoint(ep: &Endpoint) -> Result<wasapi::Device> {
|
||||
.map_err(|e| anyhow!("open endpoint {:?}: {e:#}", ep.0))
|
||||
}
|
||||
|
||||
// --- IPolicyConfig (undocumented): set a default audio endpoint by id, for all three roles. ---
|
||||
// --- IPolicyConfig (undocumented): default-endpoint and endpoint-visibility writes. ---
|
||||
|
||||
/// The `IPolicyConfig` vtable. Only `SetDefaultEndpoint` is called; the 10 methods between `Release`
|
||||
/// and it (`GetMixFormat` … `SetPropertyValue`) are placeholders so the slot offset is correct.
|
||||
/// The `IPolicyConfig` vtable. Only `SetDefaultEndpoint` and `SetEndpointVisibility` are called;
|
||||
/// the 10 methods between `Release` and them (`GetMixFormat` … `SetPropertyValue`) are
|
||||
/// placeholders so the slot offsets are correct.
|
||||
#[repr(C)]
|
||||
struct IPolicyConfigVtbl {
|
||||
query_interface: unsafe extern "system" fn(
|
||||
@@ -537,7 +639,11 @@ struct IPolicyConfigVtbl {
|
||||
windows::core::PCWSTR,
|
||||
u32,
|
||||
) -> windows::core::HRESULT,
|
||||
// SetEndpointVisibility follows — unused.
|
||||
set_endpoint_visibility: unsafe extern "system" fn(
|
||||
*mut c_void,
|
||||
windows::core::PCWSTR,
|
||||
i32,
|
||||
) -> windows::core::HRESULT,
|
||||
}
|
||||
|
||||
// This mirrors the vtable of the UNDOCUMENTED `IPolicyConfig` COM interface, so there is no header
|
||||
@@ -546,18 +652,21 @@ struct IPolicyConfigVtbl {
|
||||
// table" — so a field added, removed or resized above it does not fail to compile: it silently calls
|
||||
// a DIFFERENT function through a mismatched signature, which is arbitrary-code territory rather
|
||||
// than a wrong answer. The `_reserved` gap is what makes that easy to get wrong, since its ten slots
|
||||
// carry no names to anchor a review. These assertions pin the two things the call actually depends
|
||||
// on: the slot index of `set_default_endpoint`, and the size of the table up to it.
|
||||
// carry no names to anchor a review. These assertions pin the things the calls actually depend
|
||||
// on: the slot indexes of `set_default_endpoint` and `set_endpoint_visibility`, and the size of
|
||||
// the table up to them.
|
||||
const _: () = {
|
||||
use std::mem::{offset_of, size_of};
|
||||
type P = *const c_void;
|
||||
// 3 IUnknown slots + 10 reserved = `set_default_endpoint` is slot 13 (0-based).
|
||||
// 3 IUnknown slots + 10 reserved = `set_default_endpoint` is slot 13 (0-based),
|
||||
// `set_endpoint_visibility` the slot after.
|
||||
assert!(offset_of!(IPolicyConfigVtbl, query_interface) == 0);
|
||||
assert!(offset_of!(IPolicyConfigVtbl, add_ref) == size_of::<P>());
|
||||
assert!(offset_of!(IPolicyConfigVtbl, release) == 2 * size_of::<P>());
|
||||
assert!(offset_of!(IPolicyConfigVtbl, _reserved) == 3 * size_of::<P>());
|
||||
assert!(offset_of!(IPolicyConfigVtbl, set_default_endpoint) == 13 * size_of::<P>());
|
||||
assert!(size_of::<IPolicyConfigVtbl>() == 14 * size_of::<P>());
|
||||
assert!(offset_of!(IPolicyConfigVtbl, set_endpoint_visibility) == 14 * size_of::<P>());
|
||||
assert!(size_of::<IPolicyConfigVtbl>() == 15 * size_of::<P>());
|
||||
};
|
||||
|
||||
/// Set `device_id` as the default audio endpoint for eConsole/eMultimedia/eCommunications via the
|
||||
@@ -603,3 +712,41 @@ pub(crate) fn set_default_endpoint(device_id: &str) -> Result<()> {
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// Show or hide an audio endpoint via the undocumented `IPolicyConfig::SetEndpointVisibility` —
|
||||
/// the exact call behind mmsys.cpl's "Disable"/"Enable" device menu. A hidden endpoint drops to
|
||||
/// `DEVICE_STATE_DISABLED`: it vanishes from every ACTIVE enumeration and cannot be opened, but
|
||||
/// its devnode, driver binding and stamped identity all stay put — showing it again is instant
|
||||
/// and raises no PnP traffic. pub(crate): the pad-endpoint provider parks its "Wireless
|
||||
/// Controller" speaker hidden while no client pad is attached (a visible idle pad speaker makes
|
||||
/// libScePad titles engage their DualSense-haptics path against an endpoint nothing services —
|
||||
/// the 2026-08-14 Helldivers 2 field confirmation).
|
||||
pub(crate) fn set_endpoint_visibility(device_id: &str, visible: bool) -> Result<()> {
|
||||
use windows::core::{IUnknown, Interface, GUID, PCWSTR};
|
||||
use windows::Win32::System::Com::{CoCreateInstance, CLSCTX_ALL};
|
||||
|
||||
const CLSID_POLICY_CONFIG: GUID = GUID::from_u128(0x870af99c_171d_4f9e_af0d_e63df40c2bc9);
|
||||
const IID_IPOLICY_CONFIG: GUID = GUID::from_u128(0xf8679f50_850a_41cf_9c72_430f290290c8);
|
||||
|
||||
let wide: Vec<u16> = device_id.encode_utf16().chain(std::iter::once(0)).collect();
|
||||
|
||||
// SAFETY: same contract as `set_default_endpoint` — owned IUnknown from CoCreateInstance,
|
||||
// QI'd pointer checked non-null, the call goes through the assertion-pinned vtable slot with
|
||||
// a NUL-terminated UTF-16 id and an INT bool, and the QI'd pointer is Released before return.
|
||||
unsafe {
|
||||
let unk: IUnknown = CoCreateInstance(&CLSID_POLICY_CONFIG, None, CLSCTX_ALL)
|
||||
.map_err(|e| anyhow!("CoCreateInstance(PolicyConfig): {e}"))?;
|
||||
let mut raw: *mut c_void = std::ptr::null_mut();
|
||||
unk.query(&IID_IPOLICY_CONFIG, &mut raw)
|
||||
.ok()
|
||||
.map_err(|e| anyhow!("QueryInterface(IPolicyConfig): {e}"))?;
|
||||
if raw.is_null() {
|
||||
bail!("IPolicyConfig QueryInterface returned null");
|
||||
}
|
||||
let vtbl = *(raw as *const *const IPolicyConfigVtbl);
|
||||
let hr = ((*vtbl).set_endpoint_visibility)(raw, PCWSTR(wide.as_ptr()), visible as i32);
|
||||
((*vtbl).release)(raw);
|
||||
hr.ok()
|
||||
.map_err(|e| anyhow!("SetEndpointVisibility({visible}): {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,8 +46,8 @@ pub(crate) struct Removed {
|
||||
pub endpoint_records: usize,
|
||||
}
|
||||
|
||||
/// Restore the default playback device if we left it parked, then remove every audio devnode
|
||||
/// this product minted, newest registry record and all.
|
||||
/// Restore the default playback/recording devices if we left them parked, then remove every
|
||||
/// audio devnode this product minted, newest registry record and all.
|
||||
///
|
||||
/// Best-effort throughout, like the rest of the (un)install path: a devnode that refuses to go
|
||||
/// is counted and reported, never fatal — a non-zero exit here would abort the whole uninstaller
|
||||
@@ -59,7 +59,7 @@ pub(crate) fn purge() -> Result<Removed> {
|
||||
// what the operator had. Putting it back is the difference between "the box works again"
|
||||
// and "the box works again, on the device it started with".
|
||||
if audio_control::unpark_default_for_uninstall() {
|
||||
println!("restored the default playback device this host had parked");
|
||||
println!("restored the default audio device(s) this host had parked");
|
||||
}
|
||||
|
||||
let mut out = Removed::default();
|
||||
|
||||
@@ -25,6 +25,12 @@
|
||||
//! behind the measured MMDevices ACL repair (see [`grant_system_full_control`]).
|
||||
//! 3. **Capture**: sessions loopback-capture the endpoint ([`PadLoopbackCapturer`], 4 ch f32
|
||||
//! interleaved) and ship the PCM to the client's pad speaker/haptics.
|
||||
//! 4. **Visibility** ([`set_visibility`]): the endpoint parks HIDDEN (`DEVICE_STATE_DISABLED`)
|
||||
//! whenever no client pad is attached — provisioning hides it at startup, the per-pad
|
||||
//! streamer shows it for exactly the pad's lifetime. The DualSense disguise that makes games
|
||||
//! route haptics at it during a session makes idle libScePad titles STALL on it otherwise
|
||||
//! (Helldivers 2, field-confirmed 2026-08-14: 2–5 FPS 1% lows with the host idle). The
|
||||
//! devnode, driver binding and stamps stay put, so flips raise no PnP traffic.
|
||||
//!
|
||||
//! The wiring plan must never route desktop audio or the virtual mic onto these endpoints —
|
||||
//! [`audio_control`](super::audio_control) collects the exclusion ids via
|
||||
@@ -1484,6 +1490,10 @@ static PROVISIONING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBo
|
||||
pub(crate) fn provision_at_startup() {
|
||||
if !pad_audio_enabled() {
|
||||
tracing::info!("pad audio disabled (PUNKTFUNK_PAD_AUDIO=0)");
|
||||
// Endpoints a previous run provisioned persist and stay VISIBLE — and a visible idle
|
||||
// pad speaker is exactly what libScePad titles stall on (see [`set_visibility`]).
|
||||
// Turning the feature off must also park the leftovers.
|
||||
hide_leftover_endpoints();
|
||||
return;
|
||||
}
|
||||
if PROVISIONED.get().is_some() {
|
||||
@@ -1531,6 +1541,17 @@ pub(crate) fn provision_at_startup() {
|
||||
stored-but-not-served until the next reboot"),
|
||||
}
|
||||
}
|
||||
// Park every provisioned endpoint HIDDEN until a client pad actually attaches. The
|
||||
// expensive work (devnode, driver bind, stamps, the AEB kick above) stays at boot —
|
||||
// the #185 lesson: no PnP traffic at session boundaries — but the ENDPOINT must not
|
||||
// sit visible on an idle box: libScePad titles (Helldivers 2, field-confirmed
|
||||
// 2026-08-14) find the "Wireless Controller" speaker BY IDENTITY, engage their
|
||||
// DualSense-haptics path against it, and stall on an endpoint nothing services —
|
||||
// 1% lows of 2–5 FPS with the host completely idle. The per-pad streamer shows it
|
||||
// for exactly the pad's lifetime, like a real DualSense arriving.
|
||||
for pe in &eps {
|
||||
set_visibility(&pe.endpoint_id, pe.pad_index, false);
|
||||
}
|
||||
// R5: latch the result ONLY if we actually provisioned something. This used to store
|
||||
// whatever `eps` held even when the loop broke on the first error — an empty vec —
|
||||
// and `OnceLock` made that permanent: one transient failure (a busy audio stack, a
|
||||
@@ -1570,6 +1591,54 @@ pub(crate) fn ensure_provisioned() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Show or hide a pad endpoint (best-effort, logged). Hidden = `DEVICE_STATE_DISABLED` via
|
||||
/// [`audio_control::set_endpoint_visibility`] — the endpoint keeps its devnode, driver binding
|
||||
/// and DualSense stamps, but vanishes from every ACTIVE enumeration and cannot be opened.
|
||||
///
|
||||
/// WHY pad endpoints park hidden: the stamp set exists so libScePad titles read the endpoint as
|
||||
/// a real DualSense speaker and route haptics audio at it — during a pad session that is the
|
||||
/// feature, on an idle box it is a trap. Helldivers 2 (field-confirmed 2026-08-14) finds the
|
||||
/// idle "Wireless Controller" speaker, engages its DualSense-haptics path against an endpoint
|
||||
/// nothing services, and drops to 2–5 FPS 1% lows with the host completely idle; the manual
|
||||
/// community remedy is disabling the device in mmsys.cpl — this is that remedy, automated and
|
||||
/// scoped to "no pad attached". Visibility flips raise no PnP traffic (the #185 lesson), only
|
||||
/// an endpoint state notification — the same event a real pad's arrival/departure raises.
|
||||
pub(crate) fn set_visibility(endpoint_id: &str, pad_index: u8, visible: bool) {
|
||||
match audio_control::set_endpoint_visibility(endpoint_id, visible) {
|
||||
Ok(()) => tracing::info!(pad = pad_index, endpoint = %endpoint_id,
|
||||
state = if visible { "shown (client pad attached)" } else { "hidden (no pad attached)" },
|
||||
"pad-audio endpoint visibility"),
|
||||
Err(e) => tracing::warn!(pad = pad_index, endpoint = %endpoint_id, visible,
|
||||
error = %format!("{e:#}"),
|
||||
"pad-audio endpoint visibility change failed — an idle visible pad speaker can \
|
||||
stall libScePad titles (disable it in mmsys.cpl as a manual fallback)"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Hide any pad endpoints a previous run left behind — the `PUNKTFUNK_PAD_AUDIO=0` path, where
|
||||
/// the provisioning worker never runs but persisted endpoints would otherwise stay visible (and
|
||||
/// stall idle libScePad titles) forever.
|
||||
fn hide_leftover_endpoints() {
|
||||
let spawned = thread::Builder::new()
|
||||
.name("punktfunk-pad-audio-hide".into())
|
||||
.spawn(|| {
|
||||
if wasapi::initialize_mta().ok().is_err() {
|
||||
return;
|
||||
}
|
||||
for idx in 0..4u8 {
|
||||
match find(idx) {
|
||||
Ok(Some(pe)) if !pe.endpoint_id.is_empty() => {
|
||||
set_visibility(&pe.endpoint_id, idx, false);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
tracing::warn!(error = %e, "could not spawn the pad-endpoint hide sweep");
|
||||
}
|
||||
}
|
||||
|
||||
/// The provisioned endpoint for one pad slot — what a session queries when a client pad with
|
||||
/// speaker support arrives, to attach a [`PadLoopbackCapturer`].
|
||||
#[allow(dead_code)]
|
||||
|
||||
@@ -24,8 +24,8 @@
|
||||
//! the set changes — the thread says why once, then parks on a cheap fingerprint poll and
|
||||
//! re-plans the instant the set moves (the 2026-08 field case hammered a full wiring pass —
|
||||
//! IPolicyConfig writes included — every 2 s for 8+ minutes without ever being able to
|
||||
//! succeed). On thread exit (capturer dropped at stream end) the parked default playback
|
||||
//! device is restored.
|
||||
//! succeed). On thread exit (capturer dropped at stream end) the parked default playback AND
|
||||
//! recording devices are restored — both defaults are strictly session-scoped.
|
||||
|
||||
use super::capture_policy::{CaptureStats, FightDamper, FIGHT_BACKOFF, STATS_EVERY};
|
||||
use super::{audio_control, wiring_plan, AudioCapturer, SAMPLE_RATE};
|
||||
@@ -43,6 +43,15 @@ pub struct WasapiLoopbackCapturer {
|
||||
channels: u32,
|
||||
stop: Arc<AtomicBool>,
|
||||
join: Option<JoinHandle<()>>,
|
||||
/// Whether a session is currently CONSUMING this capturer, shared with the capture thread
|
||||
/// so the drop counter can tell "the encode thread fell behind" from "nobody is reading".
|
||||
/// The native/gamestream planes park a capturer between sessions
|
||||
/// ([`idle`](AudioCapturer::idle)) instead of dropping it, and the hand-off channel is
|
||||
/// bounded — so without this the thread fills it once, then counts every subsequent chunk
|
||||
/// as a drop and warns that "the stream will click" with no stream to click. Proven on the
|
||||
/// Linux twin by a 2026-08-13 field log (100 % drop rate across session gaps); the parking
|
||||
/// call sites are platform-independent, so this half had the same defect.
|
||||
active: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl WasapiLoopbackCapturer {
|
||||
@@ -58,10 +67,13 @@ impl WasapiLoopbackCapturer {
|
||||
// rather than a silent dead thread.
|
||||
let (ready_tx, ready_rx) = sync_channel::<Result<()>>(1);
|
||||
let stop_t = stop.clone();
|
||||
// Opens at session start, so the consumer is live from the first chunk.
|
||||
let active = Arc::new(AtomicBool::new(true));
|
||||
let active_t = active.clone();
|
||||
let join = thread::Builder::new()
|
||||
.name("punktfunk-wasapi-audio".into())
|
||||
.spawn(move || {
|
||||
if let Err(e) = capture_thread(tx, stop_t, ready_tx, channels) {
|
||||
if let Err(e) = capture_thread(tx, stop_t, ready_tx, channels, active_t) {
|
||||
tracing::error!(error = %format!("{e:#}"), "wasapi loopback thread failed");
|
||||
}
|
||||
})
|
||||
@@ -76,6 +88,7 @@ impl WasapiLoopbackCapturer {
|
||||
channels,
|
||||
stop,
|
||||
join: Some(join),
|
||||
active,
|
||||
})
|
||||
}
|
||||
Ok(Err(e)) => Err(e),
|
||||
@@ -92,6 +105,9 @@ impl WasapiLoopbackCapturer {
|
||||
|
||||
impl Drop for WasapiLoopbackCapturer {
|
||||
fn drop(&mut self) {
|
||||
// The receiver dies with us; anything the thread still pushes is unwanted by
|
||||
// definition, and must not be reported as the encode thread falling behind.
|
||||
self.active.store(false, Ordering::Relaxed);
|
||||
self.stop.store(true, Ordering::SeqCst);
|
||||
if let Some(j) = self.join.take() {
|
||||
let _ = j.join();
|
||||
@@ -114,6 +130,14 @@ impl AudioCapturer for WasapiLoopbackCapturer {
|
||||
}
|
||||
fn drain(&mut self) {
|
||||
while self.chunks.try_recv().is_ok() {}
|
||||
// Ordered AFTER the backlog drain, so the capture thread never counts a drop against a
|
||||
// channel this call is still emptying.
|
||||
self.active.store(true, Ordering::Relaxed);
|
||||
}
|
||||
fn idle(&mut self) {
|
||||
// Parked: from here the channel fills and stays full, and those drops are nobody's
|
||||
// fault. See [`WasapiLoopbackCapturer::active`].
|
||||
self.active.store(false, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,6 +191,7 @@ fn capture_thread(
|
||||
stop: Arc<AtomicBool>,
|
||||
ready: SyncSender<Result<()>>,
|
||||
channels: u32,
|
||||
active: Arc<AtomicBool>,
|
||||
) -> Result<()> {
|
||||
// COM must be initialized on THIS thread (MTA), before any device call.
|
||||
if let Err(e) = wasapi::initialize_mta()
|
||||
@@ -192,7 +217,7 @@ fn capture_thread(
|
||||
// is said once per topology — the field log drowned in 256+ copies of the same line.
|
||||
let mut unsat_logged: Option<u64> = None;
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
match capture_once(&tx, &stop, &mut ready, channels, mode) {
|
||||
match capture_once(&tx, &stop, &mut ready, channels, mode, &active) {
|
||||
Ok(Next::Stopped) => break,
|
||||
Ok(Next::Reopen(m)) => {
|
||||
mode = m;
|
||||
@@ -265,9 +290,13 @@ fn capture_thread(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Hand the default playback device back to the operator (no-op if we never parked it, or if
|
||||
// they changed it themselves mid-stream). COM is initialized on this thread.
|
||||
// Hand the default playback AND recording devices back to the operator (no-ops if we never
|
||||
// parked them, or if they changed them themselves mid-stream). COM is initialized on this
|
||||
// thread. The recording restore is what keeps the parked default session-scoped — an idle
|
||||
// box holding the default microphone on a virtual mic nothing feeds is the 2026-08
|
||||
// Helldivers 2 tank (see `audio_control`'s module docs).
|
||||
audio_control::restore_default_playback();
|
||||
audio_control::restore_default_recording();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -357,6 +386,7 @@ fn capture_once(
|
||||
ready: &mut Option<SyncSender<Result<()>>>,
|
||||
channels: u32,
|
||||
mode: TargetMode,
|
||||
active: &AtomicBool,
|
||||
) -> Result<Next> {
|
||||
// Interleaved f32: channels * 4 bytes per frame.
|
||||
let block_align = channels as usize * 4;
|
||||
@@ -611,10 +641,14 @@ fn capture_once(
|
||||
samples.push(f32::from_le_bytes([c[0], c[1], c[2], c[3]]));
|
||||
}
|
||||
stats.observe(&samples, channels);
|
||||
// Non-blocking, lossy — same discipline as PipeWire. Now COUNTED: a full channel
|
||||
// means the encode thread is not keeping up, and every dropped chunk is a click plus
|
||||
// a permanent shift of everything after it.
|
||||
if tx.try_send(samples).is_err() {
|
||||
// Non-blocking, lossy — same discipline as PipeWire. COUNTED, and only while a
|
||||
// session is actually reading: a full channel under a LIVE consumer means the encode
|
||||
// thread is not keeping up, and every dropped chunk is a click plus a permanent
|
||||
// shift of everything after it. A full channel under a PARKED capturer means nothing
|
||||
// — the planes park capturers between sessions rather than dropping them, so the
|
||||
// channel fills once and then refuses everything
|
||||
// ([`WasapiLoopbackCapturer::active`]).
|
||||
if tx.try_send(samples).is_err() && active.load(Ordering::Relaxed) {
|
||||
stats.dropped_chunks += 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,8 +261,10 @@ fn resolve_target() -> Result<(wasapi::Device, String)> {
|
||||
// on the cable while later plans paired the default recording with the minted microphone
|
||||
// nothing wrote into (see `minted::ensure_blocking`). Instant once latched.
|
||||
super::minted::ensure_blocking();
|
||||
// set_playback=false: the mic pump runs while the host is idle — only the desktop-audio
|
||||
// capture may park the playback default (on the silent sink) for a stream's lifetime.
|
||||
// park_defaults=false: the mic pump runs while the host is idle — only the desktop-audio
|
||||
// capture may park the box's defaults (playback on the silent sink, recording on the virtual
|
||||
// mic) for a stream's lifetime. An idle box must keep the operator's own devices default —
|
||||
// an idle-parked recording default is the 2026-08 Helldivers 2 tank (`audio_control` docs).
|
||||
let mut wiring = audio_control::wire_now(false);
|
||||
if wiring.mic_render.is_none() && !wiring.mic_withheld {
|
||||
// A WITHHELD mic skips the install attempt: the Streaming Microphone exists — the plan
|
||||
|
||||
@@ -241,6 +241,30 @@ pub(crate) fn silent_sink(lname: &str) -> bool {
|
||||
lname.contains("steam streaming microphone")
|
||||
}
|
||||
|
||||
/// A capture endpoint that surfaces a VIRTUAL device's audio (cables, streaming mics, mixer
|
||||
/// strips, the host's own minted "Punktfunk" microphone) rather than a real microphone. The
|
||||
/// recording-default hygiene pass must never move the box's default onto one of these.
|
||||
pub(crate) fn virtual_capture(lname: &str) -> bool {
|
||||
lname.contains("cable output")
|
||||
|| lname.contains("steam streaming")
|
||||
|| lname.contains("voicemeeter")
|
||||
|| lname.contains("virtual")
|
||||
|| lname.contains("punktfunk")
|
||||
}
|
||||
|
||||
/// The first REAL capture endpoint (skipping `avoid_id` and every [`virtual_capture`]) — where
|
||||
/// the recording-default hygiene sends a default an earlier build left parked on the virtual mic
|
||||
/// while the host is idle. `None` on a box with no real microphone: nothing sane to move to, so
|
||||
/// the default is left alone.
|
||||
pub(crate) fn real_capture<'a>(
|
||||
captures: &'a [Endpoint],
|
||||
avoid_id: Option<&str>,
|
||||
) -> Option<&'a Endpoint> {
|
||||
captures
|
||||
.iter()
|
||||
.find(|(n, id)| Some(id.as_str()) != avoid_id && !virtual_capture(&n.to_lowercase()))
|
||||
}
|
||||
|
||||
/// A known-virtual device (cables/streaming endpoints). A render WITHOUT these markers is real
|
||||
/// hardware — the best loopback source (apps render there by default and the operator can also
|
||||
/// hear it).
|
||||
@@ -1137,6 +1161,29 @@ mod tests {
|
||||
assert!(both.contains("16000") && both.contains("channel"), "{both}");
|
||||
}
|
||||
|
||||
/// The recording-default hygiene picker: skips every virtual capture (cable, streaming mic,
|
||||
/// the minted "Punktfunk" pair, VoiceMeeter) and lands on the real microphone — the exact
|
||||
/// recording-tab zoo of the 2026-08-14 Helldivers 2 field box.
|
||||
#[test]
|
||||
fn recording_hygiene_picks_the_real_microphone() {
|
||||
let captures = [
|
||||
ep("Microphone (2- Punktfunk)"),
|
||||
ep("CABLE Output (VB-Audio Virtual Cable)"),
|
||||
ep("Microphone (Steam Streaming Microphone)"),
|
||||
ep("VoiceMeeter Output (VB-Audio VoiceMeeter VAIO)"),
|
||||
ep("Desktop Microphone (2- Microsoft LifeCam HD-3000)"),
|
||||
];
|
||||
assert_eq!(
|
||||
real_capture(&captures, None).unwrap().0,
|
||||
"Desktop Microphone (2- Microsoft LifeCam HD-3000)"
|
||||
);
|
||||
// `avoid_id` guards the plan's own mic capture even when its name would pass the
|
||||
// virtual test; with nothing else real, the answer is honestly None.
|
||||
let only = [ep("Desk Mic (USB)")];
|
||||
assert!(real_capture(&only, Some("id-desk mic (usb)")).is_none());
|
||||
assert!(real_capture(&[], None).is_none());
|
||||
}
|
||||
|
||||
/// Operator override beats the candidate order.
|
||||
#[test]
|
||||
fn env_override_wins() {
|
||||
|
||||
@@ -623,12 +623,15 @@ pub fn dualsense_windows_test(args: &[String]) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Windows: pad-audio endpoint provisioning — `pad-endpoint ensure|remove|status [--index N]`.
|
||||
/// Windows: pad-audio endpoint provisioning — `pad-endpoint
|
||||
/// ensure|remove|status|tone|capture|show|hide [--index N]`.
|
||||
/// `ensure` runs the idempotent startup path (reuse-or-create the devnode, bind the Steam
|
||||
/// Streaming Speakers driver, stamp the DualSense identity + 4ch/48k formats, report whether
|
||||
/// the stamps are SERVED); `status` prints the devnode/endpoint and per-stamp stored vs served
|
||||
/// state without changing anything; `remove` deletes the devnode via pnputil — the escape
|
||||
/// hatch only, endpoints are persistent by design. Stamping needs SYSTEM (the MMDevices ACL);
|
||||
/// hatch only, endpoints are persistent by design; `show`/`hide` flip the endpoint's
|
||||
/// visibility (the host parks it hidden while no client pad is attached — show it before
|
||||
/// `tone`/`capture`). Stamping needs SYSTEM (the MMDevices ACL);
|
||||
/// run `ensure` under the service account or PsExec when the property-store route is denied.
|
||||
/// Windows: the audio-substrate toolbox (`windows-audio-endpoints-and-vbcable.md`) —
|
||||
/// `audio-probe ssm|sink|sss-primary|mint|plan|cleanup [--keep]`. The S1–S3 spikes (`ssm` =
|
||||
@@ -744,7 +747,29 @@ pub fn pad_endpoint(args: &[String]) -> Result<()> {
|
||||
pe::capture_probe(&endpoint_id, secs)
|
||||
}
|
||||
Some("status") => pe::print_status(idx),
|
||||
_ => anyhow::bail!("usage: punktfunk-host pad-endpoint <ensure|remove|status> [--index N]"),
|
||||
// `show`/`hide` — flip the endpoint's visibility (DEVICE_STATE_DISABLED). The host parks
|
||||
// pad endpoints hidden while no client pad is attached (idle libScePad titles stall on a
|
||||
// visible one — the 2026-08-14 Helldivers 2 field case); `tone`/`capture` need the
|
||||
// endpoint SHOWN first, and `hide` puts the box back to the idle-safe state after.
|
||||
Some(verb @ ("show" | "hide")) => {
|
||||
let endpoint_id = match endpoint_override {
|
||||
Some(id) => id,
|
||||
None => match pe::find(idx)? {
|
||||
Some(ep) if !ep.endpoint_id.is_empty() => ep.endpoint_id,
|
||||
_ => {
|
||||
println!("pad-endpoint {verb}: pad {idx} has no endpoint — run `ensure`");
|
||||
return Ok(());
|
||||
}
|
||||
},
|
||||
};
|
||||
pe::set_visibility(&endpoint_id, idx, verb == "show");
|
||||
println!("pad-endpoint {verb}: {endpoint_id}");
|
||||
Ok(())
|
||||
}
|
||||
_ => anyhow::bail!(
|
||||
"usage: punktfunk-host pad-endpoint \
|
||||
<ensure|remove|status|tone|capture|show|hide> [--index N]"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1410,7 +1410,9 @@ mod tests {
|
||||
|
||||
static EXITS: AtomicUsize = AtomicUsize::new(0);
|
||||
EXITS.store(0, Ordering::SeqCst);
|
||||
let child = std::process::Command::new("/bin/true")
|
||||
// Resolved through PATH, not `/bin/true`: NixOS ships only `/bin/sh` in `/bin`, so the
|
||||
// absolute path made this test — and nothing else about the code under test — fail there.
|
||||
let child = std::process::Command::new("true")
|
||||
.spawn()
|
||||
.expect("spawn the fake launcher");
|
||||
let lease = open(
|
||||
|
||||
@@ -44,8 +44,8 @@ fn parse_compositor(s: &str) -> Option<crate::vdisplay::Compositor> {
|
||||
}
|
||||
|
||||
/// The GameStream catalog Moonlight sees in `/applist`: the operator base ([`base_catalog`] — Desktop +
|
||||
/// apps.json) with the host's auto-detected game library ([`append_library`]) layered on top, so a
|
||||
/// Moonlight client sees the same Steam/Epic/GOG/Xbox titles the native clients do instead of just Desktop.
|
||||
/// apps.json) with the host's game library ([`append_library`]) layered on top, so a Moonlight client
|
||||
/// sees the same titles the native clients do instead of just Desktop.
|
||||
pub fn catalog() -> Vec<AppEntry> {
|
||||
let mut apps = base_catalog();
|
||||
append_library(&mut apps);
|
||||
@@ -128,7 +128,7 @@ fn base_catalog() -> Vec<AppEntry> {
|
||||
/// the small Desktop/apps.json ids so the two never collide.
|
||||
const LIBRARY_ID_BASE: u32 = 0x4000_0000;
|
||||
|
||||
/// Append the host's installed game library ([`crate::library::all_games`] — Steam/Epic/GOG/Xbox/custom)
|
||||
/// Append the host's game library ([`crate::library::all_games`] — every enabled source's titles)
|
||||
/// to `apps`. Each title gets a STABLE GameStream `<ID>` derived from its store-qualified library id
|
||||
/// (Moonlight caches appids, so a title keeps its id across host restarts), carries that library id so
|
||||
/// the launch path resolves it against the host's own library, and is de-duplicated (by id) against the
|
||||
@@ -251,7 +251,7 @@ mod tests {
|
||||
/// pins that the claimed shape is that shape, and that an unclaimed one would NOT have been.
|
||||
#[test]
|
||||
fn a_claimed_plugin_entry_keeps_the_scanners_gamestream_id() {
|
||||
// What the built-in scanner produced, and what the steam plugin produces once it claims.
|
||||
// What the built-in scanner produced, and what the steam plugin produces now that it claims.
|
||||
assert_eq!(stable_app_id("steam:440"), stable_app_id("steam:440"));
|
||||
// The same title reconciled WITHOUT a claim gets an opaque `custom:` id — a different app
|
||||
// id, i.e. exactly the breakage the claim prevents.
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
//! History: ONE RSA-2048 identity (`gamestream::cert`) served every plane, because Moonlight
|
||||
//! mandates RSA and the planes grew out of the GameStream host. The native punktfunk/1 QUIC
|
||||
//! plane and the management API now share THIS identity instead: **ECDSA P-256** — generated by
|
||||
//! ring via rcgen (no `rsa` crate on the native path, so the accepted Marvin advisory
|
||||
//! RUSTSEC-2023-0071 stops applying to native-only hosts once WP19 gates the compat planes),
|
||||
//! browser-compatible (an operator opens `/api/docs` in one, and no mainstream browser accepts an
|
||||
//! Ed25519 server cert), and carrying real SANs (localhost, loopback, the machine hostname) —
|
||||
//! which the legacy cert never had. The GameStream plane keeps the RSA identity untouched:
|
||||
//! Moonlight pins it and its pairing hashes bind its X.509 signature bytes.
|
||||
//! rcgen on the workspace's aws-lc-rs backend (no `rsa` crate on the native path, so the accepted
|
||||
//! Marvin advisory RUSTSEC-2023-0071 stops applying to native-only hosts once WP19 gates the
|
||||
//! compat planes), browser-compatible (an operator opens `/api/docs` in one, and no mainstream
|
||||
//! browser accepts an Ed25519 server cert), and carrying real SANs (localhost, loopback, the
|
||||
//! machine hostname) — which the legacy cert never had. The GameStream plane keeps the RSA
|
||||
//! identity untouched: Moonlight pins it and its pairing hashes bind its X.509 signature bytes.
|
||||
//!
|
||||
//! ## Migration — the rule that keeps every pinned fingerprint valid
|
||||
//!
|
||||
@@ -73,9 +73,9 @@ pub fn load_or_adopt(np: &crate::native_pairing::NativePairing) -> Result<Native
|
||||
}
|
||||
// Live native pairings pinned the legacy RSA cert — switching identities now would strand
|
||||
// every one of them (the pin is the SHA-256 of the leaf DER). Keep serving what they pinned.
|
||||
// A pem-only read on purpose (WP19): rustls/ring can SERVE an existing RSA cert without the
|
||||
// `rsa` crate, so the native-only build never links it — the crate exists solely behind the
|
||||
// `gamestream` feature (generation + the pairing signer).
|
||||
// A pem-only read on purpose (WP19): rustls/aws-lc-rs can SERVE an existing RSA cert without
|
||||
// the `rsa` crate, so the native-only build never links it — the crate exists solely behind
|
||||
// the `gamestream` feature (generation + the pairing signer).
|
||||
if let (Ok(c), Ok(k)) = (
|
||||
fs::read_to_string(dir.join("cert.pem")),
|
||||
fs::read_to_string(dir.join("key.pem")),
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
//! Game library (plan: "surface the user's games"). A small adapter layer over the *stores*
|
||||
//! installed on the host — today **Steam** (read from local files, no API key) and a
|
||||
//! user-curated **custom** store (CRUD'd via the management API / web console). Every store
|
||||
//! produces the same [`GameEntry`], so a client renders one uniform grid and never has to know
|
||||
//! which launcher a title came from. Future stores (Heroic/Epic, GOG, Lutris, EmuDeck) are just
|
||||
//! more [`LibraryProvider`]s.
|
||||
//! Game library (plan: "surface the user's games"). One uniform [`GameEntry`] grid over every
|
||||
//! source of titles on this host, so a client never has to know which launcher a title came from.
|
||||
//!
|
||||
//! Artwork is keyed only by Steam appid against the public Steam CDN (no auth) — the client
|
||||
//! fetches the posters directly. Custom entries carry user-supplied art URLs.
|
||||
//! **Every source is a plugin.** The host itself scans nothing: library plugins (Steam, Lutris,
|
||||
//! Heroic, Epic, GOG, Xbox, Playnite, ROM managers, …) reconcile their titles into the stored
|
||||
//! catalog over the provider API, each claiming its store so its entries keep the stable
|
||||
//! `<store>:<external_id>` ids everything downstream already pins (`custom.rs`, design D2). The
|
||||
//! user-curated **custom** store — entries the operator typed in via the management API / web
|
||||
//! console — lives in the same catalog and is the one source that is not a plugin.
|
||||
//!
|
||||
//! Until v0.28.0 the host also carried six built-in scanners that read the launchers' local files
|
||||
//! directly. They were the bridge while the plugins were written; the plugins are the product now,
|
||||
//! and the scanners are gone. What survives them is deliberate: the entry model here, the whole of
|
||||
//! `launch.rs` (a plugin publishes a validated *value*, the host builds the command — design D1),
|
||||
//! and the source toggles in `scanners.rs`, whose ids match the claims by construction so an
|
||||
//! operator's disabled state carried across the extraction untouched.
|
||||
//!
|
||||
//! Artwork rides on the entries themselves — a plugin supplies URLs or local files, and the host's
|
||||
//! art proxy serves the local ones ([`art`]) so a client never receives an unreachable `C:\…` path.
|
||||
//!
|
||||
//! This module is read-mostly metadata; *launching* a chosen title (mapping [`LaunchSpec`] onto a
|
||||
//! gamescope session) is a later step — the launch hint is carried here so that wiring is trivial.
|
||||
//! gamescope session) is `launch.rs`.
|
||||
|
||||
// Shared vocabulary re-exported to the submodules (each is `use super::*`).
|
||||
pub(crate) use anyhow::{Context, Result};
|
||||
@@ -23,40 +33,18 @@ pub(crate) use utoipa::ToSchema;
|
||||
mod art;
|
||||
mod custom;
|
||||
mod detect;
|
||||
#[cfg(windows)]
|
||||
mod epic;
|
||||
#[cfg(windows)]
|
||||
mod gog;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod heroic;
|
||||
mod hidden;
|
||||
mod launch;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod lutris;
|
||||
mod plugin_launch;
|
||||
mod scanners;
|
||||
mod steam;
|
||||
#[cfg(windows)]
|
||||
mod xbox;
|
||||
|
||||
pub use art::*;
|
||||
pub use custom::*;
|
||||
pub use detect::*;
|
||||
#[cfg(windows)]
|
||||
pub use epic::*;
|
||||
#[cfg(windows)]
|
||||
pub use gog::*;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use heroic::*;
|
||||
pub use hidden::*;
|
||||
pub use launch::*;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use lutris::*;
|
||||
pub use plugin_launch::*;
|
||||
pub use scanners::*;
|
||||
pub use steam::*;
|
||||
#[cfg(windows)]
|
||||
pub use xbox::*;
|
||||
|
||||
/// Cover art for a title. All fields are URLs (the Steam CDN for Steam titles, user-supplied for
|
||||
/// custom). The client prefers `portrait` for a grid and falls back to `header` when a title has
|
||||
@@ -129,17 +117,6 @@ pub struct GameMeta {
|
||||
pub players: Option<u8>,
|
||||
}
|
||||
|
||||
impl GameMeta {
|
||||
/// The one field an installed-store scanner can assert about its own titles: they run on this
|
||||
/// host, i.e. on a PC. Everything else stays absent (the launchers' local files don't carry it).
|
||||
pub(crate) fn pc() -> Self {
|
||||
GameMeta {
|
||||
platform: Some("PC".into()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a library entry *is* — an ordinary title, or the launcher application itself (Steam Big
|
||||
/// Picture, Heroic, Playnite fullscreen). Purely a presentation hint: a launcher entry launches,
|
||||
/// leases and lists exactly like a game (design D4), and clients that don't know the field render it
|
||||
@@ -233,9 +210,9 @@ pub struct GameEntry {
|
||||
/// How the host would launch it, when known.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub launch: Option<LaunchSpec>,
|
||||
/// The external provider owning this entry (custom-store entries synced by a provider
|
||||
/// plugin, RFC §8) — `None` for installed-store titles and manual custom entries. The
|
||||
/// console uses it for attribution; `GET /library?provider=` filters on it.
|
||||
/// The external provider owning this entry (entries synced by a provider plugin, RFC §8) —
|
||||
/// `None` only for the manual entries the operator typed in. The console uses it for
|
||||
/// attribution; `GET /library?provider=` filters on it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub provider: Option<String>,
|
||||
/// How to recognize this title's process(es) once it is running ([`DetectSpec`]) — filled in by
|
||||
@@ -278,21 +255,8 @@ fn is_not_hidden(hidden: &bool) -> bool {
|
||||
!*hidden
|
||||
}
|
||||
|
||||
/// A store that contributes titles to the library. The trait is the extension point for future
|
||||
/// launchers; today only [`SteamProvider`] implements it.
|
||||
pub trait LibraryProvider {
|
||||
/// Stable store id (`"steam"`, …).
|
||||
fn store(&self) -> &'static str;
|
||||
/// Enumerate installed/owned titles. Best-effort: returns empty (not an error) when the store
|
||||
/// isn't present, so one missing launcher never fails the whole library.
|
||||
fn list(&self) -> Vec<GameEntry>;
|
||||
}
|
||||
|
||||
/// Steam art, keyed to one of the four [`Artwork`] fields. Newer/recently-updated titles serve
|
||||
/// their CDN assets from a per-asset-hash path the client can't predict (e.g.
|
||||
/// `.../apps/<id>/<hash>/header.jpg`), so the flat legacy URL [`steam_art`] guesses 404s for them —
|
||||
/// [`steam_art_bytes`] is the robust resolver: local Steam cache (exact, no guessing) first, the
|
||||
/// flat CDN URL as a fallback (still correct for the many titles that haven't been re-hashed).
|
||||
/// Which of the four [`Artwork`] fields an art request names — the `<kind>` in
|
||||
/// `GET /library/art/<id>/<kind>`, and the preference order the GameStream cover proxy walks.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ArtKind {
|
||||
Portrait,
|
||||
@@ -311,51 +275,26 @@ impl ArtKind {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Filenames Steam itself caches this kind under in `appcache/librarycache/<appid>/<hash>/`,
|
||||
/// tried in order (the 2x portrait, when present, is the sharper asset).
|
||||
fn local_filenames(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Self::Portrait => &["library_600x900_2x.jpg", "library_600x900.jpg"],
|
||||
Self::Hero => &["library_hero.jpg"],
|
||||
Self::Logo => &["logo.png"],
|
||||
// Steam's local cache names the header asset differently from the store CDN's
|
||||
// `header.jpg` (see `cdn_filename`).
|
||||
Self::Header => &["library_header.jpg"],
|
||||
}
|
||||
}
|
||||
|
||||
/// The legacy flat-URL filename on the public Steam CDN (works for any title the CDN hasn't
|
||||
/// migrated to a per-asset hash path).
|
||||
fn cdn_filename(self) -> &'static str {
|
||||
match self {
|
||||
Self::Portrait => "library_600x900.jpg",
|
||||
Self::Hero => "library_hero.jpg",
|
||||
Self::Logo => "logo.png",
|
||||
Self::Header => "header.jpg",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The full library: every *enabled* source's titles merged + the custom entries, sorted by title.
|
||||
/// The full library: every *enabled* source's titles, sorted by title.
|
||||
///
|
||||
/// Two independent gates run here, both at READ time so neither ever mutates stored state:
|
||||
/// Two gates run here, both at READ time so neither ever mutates stored state:
|
||||
///
|
||||
/// * **The operator's source toggles** (`scanners.rs`, persisted as a disabled-set in
|
||||
/// `library-scanners.json`) hide a source's titles from every surface — this grid, native clients,
|
||||
/// `/applist`, and launch resolution. They apply to built-in scanners *and* to plugin sources,
|
||||
/// which is what lets one toggle keep working verbatim across the whole migration: the ids match
|
||||
/// (provider id = claimed store id = old scanner id).
|
||||
/// * **Store claims** (D2): while a library plugin holds a store's claim, the matching built-in
|
||||
/// scanner is skipped so the two never double-list the same titles during the bridge releases.
|
||||
/// Removing the plugin releases the claim and the built-in comes straight back.
|
||||
/// `/applist`, and launch resolution. The plugin may keep reconciling while its source is off; the
|
||||
/// entries stay stored and simply aren't surfaced.
|
||||
/// * **The operator's per-entry hides** (`hidden.rs`), applied here rather than at each call site so
|
||||
/// a hidden title is gone from every surface by construction. [`all_games_for_operator`] is the
|
||||
/// single deliberate exception.
|
||||
///
|
||||
/// The user-curated custom store is not a source and always contributes.
|
||||
/// Manual custom entries — the ones the operator typed in — carry no source and always contribute.
|
||||
///
|
||||
/// A **third** gate rides on top of these two: the operator's per-entry hides (`hidden.rs`). It is
|
||||
/// applied here rather than at each call site so a hidden title is gone from every surface by
|
||||
/// construction — the grid, native clients, `/applist`, and launch resolution — exactly as a
|
||||
/// disabled source's titles are. [`all_games_for_operator`] is the single deliberate exception.
|
||||
/// There is no longer a third gate. Store claims used to suppress the built-in scanner a plugin had
|
||||
/// taken over; with the built-ins gone there is nothing left to suppress, so a claim now only fixes
|
||||
/// the ids a provider's entries surface under (`custom.rs::library_id_for`) and names its row in the
|
||||
/// sources list.
|
||||
pub fn all_games() -> Vec<GameEntry> {
|
||||
let hidden = hidden_ids();
|
||||
let mut games = collect_games();
|
||||
@@ -385,47 +324,12 @@ pub fn all_games_for_operator() -> Vec<OperatorGameEntry> {
|
||||
/// the hidden set, never in what they collect.
|
||||
fn collect_games() -> Vec<GameEntry> {
|
||||
let off = disabled_scanners();
|
||||
let claimed = claimed_stores();
|
||||
// A built-in scanner runs when the operator hasn't disabled it AND no plugin has claimed its
|
||||
// store out from under it.
|
||||
let on = |id: &str| !off.contains(id) && !claimed.contains_key(id);
|
||||
let mut games = Vec::new();
|
||||
if on("steam") {
|
||||
games.extend(SteamProvider.list());
|
||||
}
|
||||
// The Lutris + Heroic providers are Linux-only (their launchers are); on other hosts the library
|
||||
// is Steam + custom. Each provider is best-effort (empty when its store isn't present).
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
if on("lutris") {
|
||||
games.extend(LutrisProvider.list());
|
||||
}
|
||||
if on("heroic") {
|
||||
games.extend(HeroicProvider.list());
|
||||
}
|
||||
}
|
||||
// Windows store providers (their launchers are Windows-only): Epic + GOG + Xbox/Game Pass.
|
||||
#[cfg(windows)]
|
||||
{
|
||||
if on("epic") {
|
||||
games.extend(EpicProvider.list());
|
||||
}
|
||||
if on("gog") {
|
||||
games.extend(GogProvider.list());
|
||||
}
|
||||
if on("xbox") {
|
||||
games.extend(XboxProvider.list());
|
||||
}
|
||||
}
|
||||
// Stored entries: manual ones always contribute; a provider's are subject to the same source
|
||||
// toggle a built-in scanner is (WP2.6). The plugin may keep reconciling while it is off — the
|
||||
// entries stay stored and simply aren't surfaced, exactly like a disabled scanner's titles.
|
||||
games.extend(
|
||||
load_custom()
|
||||
.into_iter()
|
||||
.filter(|e| !source_id_for(e).is_some_and(|src| off.contains(src)))
|
||||
.map(GameEntry::from),
|
||||
);
|
||||
// Manual entries always contribute; a provider's are subject to the operator's source toggle.
|
||||
let mut games: Vec<GameEntry> = load_custom()
|
||||
.into_iter()
|
||||
.filter(|e| !source_id_for(e).is_some_and(|src| off.contains(src)))
|
||||
.map(GameEntry::from)
|
||||
.collect();
|
||||
games.sort_by_key(|g| g.title.to_lowercase());
|
||||
games
|
||||
}
|
||||
|
||||
@@ -1,109 +1,15 @@
|
||||
//! Artwork cache + background warmer: the on-disk poster cache, the per-store fetchers, and the
|
||||
//! Artwork serving: the local-file confinement rules, the art-proxy rewrite, and the
|
||||
//! `fetch_box_art` dispatch the management art proxy serves from. Split out of the `library` facade (plan §W5).
|
||||
//!
|
||||
//! There is no art *cache* or background *warmer* here any more. Both existed for the built-in GOG
|
||||
//! and Xbox scanners, the only two sources that had to reach a network catalog to learn what a
|
||||
//! title's cover was; every other source carried its own art. Those scanners were removed in
|
||||
//! v0.28.0, and the library plugins that replaced them resolve art while they scan and publish it on
|
||||
//! the entry — so the host now only ever *serves* art it was handed, and never fetches any on its
|
||||
//! own schedule. A stale `library-art-cache.json` left by an older host is simply ignored.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The persisted art cache: GameEntry id → resolved [`Artwork`]. An entry's PRESENCE means "already
|
||||
/// resolved" (even an empty Artwork = fetched, none found) so the warmer never re-fetches it.
|
||||
fn art_cache() -> &'static std::sync::Mutex<std::collections::HashMap<String, Artwork>> {
|
||||
static CACHE: std::sync::OnceLock<
|
||||
std::sync::Mutex<std::collections::HashMap<String, Artwork>>,
|
||||
> = std::sync::OnceLock::new();
|
||||
CACHE.get_or_init(|| {
|
||||
let loaded = std::fs::read_to_string(art_cache_path())
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str(&s).ok())
|
||||
.unwrap_or_default();
|
||||
std::sync::Mutex::new(loaded)
|
||||
})
|
||||
}
|
||||
|
||||
/// The art cache lives in the canonical HOST config dir (`%ProgramData%\punktfunk` on Windows /
|
||||
/// `~/.config/punktfunk` on Linux — `pf_paths::config_dir`, NOT the legacy XDG/HOME `config_dir`
|
||||
/// below that the custom store still uses).
|
||||
fn art_cache_path() -> PathBuf {
|
||||
pf_paths::config_dir().join("library-art-cache.json")
|
||||
}
|
||||
|
||||
/// The cached art for a library id, if it has been resolved (positive or negative). `None` = not yet
|
||||
/// warmed → the provider shows title-only until the warmer fills it in.
|
||||
pub(crate) fn cached_art(id: &str) -> Option<Artwork> {
|
||||
art_cache().lock().unwrap().get(id).cloned()
|
||||
}
|
||||
|
||||
/// Record resolved art for a library id + persist the cache (write-then-rename; best-effort).
|
||||
fn store_art(id: &str, art: Artwork) {
|
||||
let mut cache = art_cache().lock().unwrap();
|
||||
cache.insert(id.to_string(), art);
|
||||
if let Ok(json) = serde_json::to_string(&*cache) {
|
||||
let path = art_cache_path();
|
||||
if let Some(dir) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(dir);
|
||||
}
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
if std::fs::write(&tmp, json).is_ok() {
|
||||
let _ = std::fs::rename(&tmp, &path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the host-lifetime cover-art warmer: every few minutes, fetch + cache art for any library
|
||||
/// entry whose store needs a network lookup (GOG / Xbox) and isn't cached yet. Idempotent — once
|
||||
/// everything is cached a pass makes no network calls (and a host with only self-art stores never
|
||||
/// fetches at all). Call once from `serve()`; the returned handle can be dropped to detach it.
|
||||
pub fn start_art_warmer() -> std::thread::JoinHandle<()> {
|
||||
std::thread::Builder::new()
|
||||
.name("pf-art-warmer".into())
|
||||
.spawn(|| loop {
|
||||
warm_art_once();
|
||||
std::thread::sleep(std::time::Duration::from_secs(300));
|
||||
})
|
||||
.expect("spawn art warmer thread")
|
||||
}
|
||||
|
||||
/// One warming pass: resolve uncached GOG/Xbox art. Other stores carry their own art (Steam CDN
|
||||
/// template, Heroic CDN URLs, Lutris data: URLs, custom user URLs) and are skipped.
|
||||
fn warm_art_once() {
|
||||
for g in all_games() {
|
||||
if cached_art(&g.id).is_some() {
|
||||
continue;
|
||||
}
|
||||
let Some((store, localid)) = g.id.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
let art = match store {
|
||||
"gog" => fetch_gog_art(localid),
|
||||
// The xbox id is the StoreId when present, else the PFN (contains '_', no displaycatalog
|
||||
// entry) → cache empty for those so they aren't retried every pass.
|
||||
"xbox" if !localid.contains('_') => fetch_xbox_art(localid),
|
||||
"xbox" => Artwork::default(),
|
||||
_ => continue, // steam/heroic/lutris/custom resolve their own art
|
||||
};
|
||||
store_art(&g.id, art);
|
||||
}
|
||||
}
|
||||
|
||||
/// HTTP GET + parse JSON with a bounded timeout. `None` on any network/parse failure (best-effort —
|
||||
/// art is non-essential, so a failure just leaves the title-only card).
|
||||
fn fetch_json(url: &str) -> Option<serde_json::Value> {
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder()
|
||||
.timeout_global(Some(std::time::Duration::from_secs(10)))
|
||||
// Don't follow redirects — a redirect target (`3xx` → `http://169.254.169.254/…` or an
|
||||
// internal host) would be an SSRF pivot from the privileged host. Matches the webhook path
|
||||
// (security-review 2026-07-17). A rare legitimately-redirecting CDN just yields no art.
|
||||
.max_redirects(0)
|
||||
.build()
|
||||
.into();
|
||||
let body = agent
|
||||
.get(url)
|
||||
.call()
|
||||
.ok()?
|
||||
.body_mut()
|
||||
.read_to_string()
|
||||
.ok()?;
|
||||
serde_json::from_str(&body).ok()
|
||||
}
|
||||
|
||||
/// Fetch one image URL for the GameStream `/appasset` cover proxy, as `(bytes, content-type)`. Handles
|
||||
/// `data:` URLs (Lutris inlines art that way) by decoding inline, and `http(s)` URLs by a bounded GET
|
||||
/// (8 MiB cap so a hostile/huge art URL can't balloon host memory). `None` on any non-image scheme,
|
||||
@@ -169,11 +75,11 @@ pub(crate) fn fetch_image(url: &str) -> Option<(Vec<u8>, String)> {
|
||||
/// Playnite back-compat (it predates the `file://` contract).
|
||||
/// * POSIX absolute (`/home/u/covers/x.jpg`) — Lutris covers and Steam's `librarycache`.
|
||||
///
|
||||
/// The POSIX widening is why the two `/`-leading shapes the **host itself emits** must be excluded
|
||||
/// explicitly: its own art-proxy path (`/api/v1/library/art/…`, which [`proxy_local_art`] writes and
|
||||
/// which must survive a second pass unchanged) and a protocol-relative URL (`//cdn/…`, what GOG's and
|
||||
/// Microsoft's catalogs return — see [`abs_url`]). Mistaking either for a file would break the proxy
|
||||
/// round-trip or silently drop CDN art.
|
||||
/// The POSIX widening is why the two `/`-leading shapes must be excluded explicitly: the host's own
|
||||
/// art-proxy path (`/api/v1/library/art/…`, which [`proxy_local_art`] writes and which must survive a
|
||||
/// second pass unchanged) and a protocol-relative URL (`//cdn/…`, which GOG's and Microsoft's
|
||||
/// catalogs return and a plugin may pass straight through). Mistaking either for a file would break
|
||||
/// the proxy round-trip or silently drop CDN art.
|
||||
pub fn is_local_art_path(v: &str) -> bool {
|
||||
if v.starts_with("http://") || v.starts_with("https://") || v.starts_with("data:") {
|
||||
return false;
|
||||
@@ -244,12 +150,13 @@ fn percent_decode(s: &str) -> String {
|
||||
/// H-2): `mgmt-token`, `key.pem`, the SAM hive. So the value is confined here, at the one place
|
||||
/// bytes are read, rather than trusted because of where it was written.
|
||||
///
|
||||
/// Default: the users base (`C:\Users`), which is where every launcher keeps its art cache —
|
||||
/// Playnite, the only local-art provider, stores covers under `%APPDATA%\Playnite`. Derived from
|
||||
/// Default: the users base (`C:\Users`), where the launchers that install per-user keep their art —
|
||||
/// Playnite stores covers under `%APPDATA%\Playnite`, Heroic under `%APPDATA%\heroic`. Derived from
|
||||
/// `%PUBLIC%`'s parent because the host runs as SYSTEM, whose own `%USERPROFILE%` is
|
||||
/// `…\config\systemprofile` and tells us nothing about where the operator's launchers live.
|
||||
/// `PUNKTFUNK_LIBRARY_ART_ROOTS` (`;`-separated) replaces the default for an operator whose library
|
||||
/// is on another drive.
|
||||
/// `…\config\systemprofile` and tells us nothing about where the operator's launchers live. Plus
|
||||
/// the Steam install root ([`steam_art_roots`]), which is the one launcher that does NOT live under
|
||||
/// the users base. `PUNKTFUNK_LIBRARY_ART_ROOTS` (`;`-separated) replaces the whole default for an
|
||||
/// operator whose library is somewhere else again.
|
||||
fn art_roots() -> Vec<PathBuf> {
|
||||
if let Some(configured) = std::env::var_os("PUNKTFUNK_LIBRARY_ART_ROOTS") {
|
||||
return std::env::split_paths(&configured)
|
||||
@@ -268,6 +175,8 @@ fn art_roots() -> Vec<PathBuf> {
|
||||
roots.push(PathBuf::from(drive).join("Users"));
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
roots.extend(steam_art_roots());
|
||||
// POSIX: the user's home, which is the exact analogue of the Windows users base above — and
|
||||
// where every launcher this host reads art from actually keeps it. Steam's
|
||||
// `appcache/librarycache` and `userdata/<id>/config/grid`, Lutris's `coverart`/`banners` (both
|
||||
@@ -294,6 +203,54 @@ fn art_roots() -> Vec<PathBuf> {
|
||||
roots
|
||||
}
|
||||
|
||||
/// Windows: every Steam install root that exists on this box.
|
||||
///
|
||||
/// Steam is the one launcher whose art is NOT under the users base: it installs to
|
||||
/// `C:\Program Files (x86)\Steam`, and both places the `steam` library plugin publishes covers from
|
||||
/// — `appcache\librarycache\<appid>\…` and each account's `userdata\<id>\config\grid\` overrides —
|
||||
/// live under that root. Without this the users base rejected every one of them, and because an
|
||||
/// unservable path used to fail the WHOLE reconcile payload the plugin synced NO GAMES AT ALL, not
|
||||
/// merely no art. That is a v0.28.0 regression: the built-in scanner this plugin replaced served its
|
||||
/// covers through the legacy `steam:` art-proxy branch, which never passed through this confinement.
|
||||
/// (POSIX needs no equivalent — every Steam layout there, native and Flatpak, is already under
|
||||
/// `$HOME`.)
|
||||
///
|
||||
/// This does not widen what the host can be *tricked* into reading. The confinement exists to close
|
||||
/// one asymmetry: the host reads as SYSTEM, while the plugin lane that supplies the path is the far
|
||||
/// weaker LocalService (2026-08-05 review H-2). The Steam directory is readable by LocalService
|
||||
/// already, so nothing reachable through it is reachable *because* the host is privileged. The
|
||||
/// extension, regular-file, magic-byte and config-dir gates all still apply on top, so Steam's own
|
||||
/// `config.vdf` and `ssfn*` credential blobs are not servable from it either.
|
||||
#[cfg(windows)]
|
||||
fn steam_art_roots() -> Vec<PathBuf> {
|
||||
let mut out: Vec<PathBuf> = Vec::new();
|
||||
let mut push = |p: PathBuf| {
|
||||
// `is_dir` before dedup: `%ProgramFiles%` and `%ProgramW6432%` are the same directory on a
|
||||
// 64-bit host, and the registry commonly repeats whichever of the two Steam sits in.
|
||||
if p.is_dir() && !out.contains(&p) {
|
||||
out.push(p);
|
||||
}
|
||||
};
|
||||
for var in ["ProgramFiles(x86)", "ProgramFiles", "ProgramW6432"] {
|
||||
if let Some(pf) = std::env::var_os(var) {
|
||||
push(PathBuf::from(pf).join("Steam"));
|
||||
}
|
||||
}
|
||||
// A Steam installed off the default path — a second drive is common — is only discoverable from
|
||||
// the registry. HKLM and not HKCU, for the same reason the plugin reads HKLM: the host is
|
||||
// SYSTEM, whose own hive knows nothing about where the operator installed anything.
|
||||
for key in [r"SOFTWARE\WOW6432Node\Valve\Steam", r"SOFTWARE\Valve\Steam"] {
|
||||
if let Some(p) = winreg::RegKey::predef(winreg::enums::HKEY_LOCAL_MACHINE)
|
||||
.open_subkey(key)
|
||||
.ok()
|
||||
.and_then(|k| k.get_value::<String, _>("InstallPath").ok())
|
||||
{
|
||||
push(PathBuf::from(p));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `path` resolves inside one of [`art_roots`] and outside the host config dir.
|
||||
///
|
||||
/// Canonicalizes first, so a junction/symlink pointing out of the root is resolved before the
|
||||
@@ -411,6 +368,43 @@ pub fn validate_art_paths(art: &Artwork) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Strip every **local-file** art value the proxy would refuse to serve, returning the
|
||||
/// `(field, value)` pairs dropped. URLs and already-proxied paths are left alone.
|
||||
///
|
||||
/// The provider-reconcile counterpart to [`validate_art_paths`]. Both enforce the same invariant —
|
||||
/// an unservable path never reaches `library.json` — and differ only on what the REST of the payload
|
||||
/// is worth. An operator writing one custom entry typed that path by hand, so a hard 400 is the
|
||||
/// feedback they need. A plugin reconciling its whole entry set did not: it publishes hundreds of
|
||||
/// covers it resolved from disk, and refusing the payload over one of them costs the operator their
|
||||
/// entire library for that store.
|
||||
///
|
||||
/// That is not hypothetical. A default Windows Steam install put every cover outside the art roots,
|
||||
/// so `PUT /library/provider/steam` 400'd, the plugin could only report `HostRequestError`, and the
|
||||
/// grid stayed empty with no indication that the games themselves were fine. [`steam_art_roots`]
|
||||
/// fixes that specific mismatch; this makes the NEXT one cost a cover instead of a library.
|
||||
///
|
||||
/// Dropping rather than rewriting is deliberate: `None` is exactly what an entry with no art
|
||||
/// carries, and every client already renders that.
|
||||
pub fn sanitize_art_paths(art: &mut Artwork) -> Vec<(&'static str, String)> {
|
||||
let mut dropped = Vec::new();
|
||||
for (field, value) in [
|
||||
("portrait", &mut art.portrait),
|
||||
("hero", &mut art.hero),
|
||||
("logo", &mut art.logo),
|
||||
("header", &mut art.header),
|
||||
] {
|
||||
let unservable = value
|
||||
.as_deref()
|
||||
.is_some_and(|v| is_local_art_path(v) && !art_path_is_servable(v));
|
||||
if unservable {
|
||||
if let Some(v) = value.take() {
|
||||
dropped.push((field, v));
|
||||
}
|
||||
}
|
||||
}
|
||||
dropped
|
||||
}
|
||||
|
||||
/// Read a local image file into `(bytes, content-type)` for the art proxy. `None` if it isn't an
|
||||
/// existing regular file, is empty, exceeds 16 MiB (a cover never approaches that; the cap bounds
|
||||
/// host memory), resolves outside the allowed art roots ([`art_path_is_confined`]), or does not
|
||||
@@ -475,107 +469,20 @@ pub fn proxy_local_art(id: &str, art: &mut Artwork) {
|
||||
/// `(bytes, content-type)`. Resolves the id against the host's OWN library. Blocking — call off the
|
||||
/// async runtime (e.g. `spawn_blocking`).
|
||||
pub fn fetch_box_art(id: &str) -> Option<(Vec<u8>, String)> {
|
||||
// Same resolution order as the management art proxy (WP1.2): the stored catalog first, for ANY
|
||||
// id, so a library plugin's entries resolve without the warmer knowing its store.
|
||||
if let Some(entry) = entry_for_library_id(id) {
|
||||
return [
|
||||
ArtKind::Portrait,
|
||||
ArtKind::Header,
|
||||
ArtKind::Hero,
|
||||
ArtKind::Logo,
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|kind| art_field(&entry.art, kind))
|
||||
.find_map(|v| resolve_art_bytes(&v));
|
||||
}
|
||||
// Legacy in-host Steam scanner: its `Artwork` fields are relative proxy paths (see `steam_art`)
|
||||
// the *client* resolves against the host — meaningless to `fetch_image`, which expects an
|
||||
// absolute URL. Resolve those kinds directly instead of going through the URL fields.
|
||||
if let Some(appid) = id
|
||||
.strip_prefix("steam:")
|
||||
.and_then(|s| s.parse::<u32>().ok())
|
||||
{
|
||||
return [
|
||||
ArtKind::Portrait,
|
||||
ArtKind::Header,
|
||||
ArtKind::Hero,
|
||||
ArtKind::Logo,
|
||||
]
|
||||
.into_iter()
|
||||
.find_map(|kind| steam_art_bytes(appid, kind));
|
||||
}
|
||||
// The remaining in-host scanners (heroic/lutris/epic/gog/xbox) carry absolute CDN URLs.
|
||||
let g = all_games().into_iter().find(|g| g.id == id)?;
|
||||
[g.art.portrait, g.art.header, g.art.hero, g.art.logo]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find_map(|url| resolve_art_bytes(&url))
|
||||
}
|
||||
|
||||
/// Make a protocol-relative URL (`//host/...`, common in GOG + MS catalog responses) absolute https.
|
||||
fn abs_url(u: &str) -> String {
|
||||
u.strip_prefix("//")
|
||||
.map(|rest| format!("https://{rest}"))
|
||||
.unwrap_or_else(|| u.to_string())
|
||||
}
|
||||
|
||||
/// GOG cover art via the public (no-auth) product API. Field names / URL shapes are GOG-specific and
|
||||
/// best-effort (worth on-box confirmation); a wrong URL just degrades to the title card client-side.
|
||||
fn fetch_gog_art(product_id: &str) -> Artwork {
|
||||
let Some(v) = fetch_json(&format!(
|
||||
"https://api.gog.com/products/{product_id}?expand=images"
|
||||
)) else {
|
||||
return Artwork::default();
|
||||
};
|
||||
let img = |k: &str| {
|
||||
v.get("images")
|
||||
.and_then(|i| i.get(k))
|
||||
.and_then(|u| u.as_str())
|
||||
.map(abs_url)
|
||||
};
|
||||
Artwork {
|
||||
portrait: img("verticalCover"),
|
||||
hero: img("background"),
|
||||
logo: img("logo2x"),
|
||||
header: img("logo"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Xbox cover art via the (unofficial, no-auth) Microsoft display catalog, keyed by StoreId. Best-
|
||||
/// effort: the endpoint is internal/unstable, so on drift this just yields no art (title-only).
|
||||
fn fetch_xbox_art(store_id: &str) -> Artwork {
|
||||
let Some(v) = fetch_json(&format!(
|
||||
"https://displaycatalog.mp.microsoft.com/v7.0/products/{store_id}?market=US&languages=en-us&fieldsTemplate=Details"
|
||||
)) else {
|
||||
return Artwork::default();
|
||||
};
|
||||
let images = v
|
||||
.get("Products")
|
||||
.and_then(|p| p.as_array())
|
||||
.and_then(|a| a.first())
|
||||
.and_then(|p| p.get("LocalizedProperties"))
|
||||
.and_then(|l| l.as_array())
|
||||
.and_then(|a| a.first())
|
||||
.and_then(|lp| lp.get("Images"))
|
||||
.and_then(|i| i.as_array());
|
||||
let mut art = Artwork::default();
|
||||
for img in images.into_iter().flatten() {
|
||||
let (Some(purpose), Some(uri)) = (
|
||||
img.get("ImagePurpose").and_then(|v| v.as_str()),
|
||||
img.get("Uri").and_then(|v| v.as_str()),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
let url = abs_url(uri);
|
||||
match purpose {
|
||||
"Poster" => art.portrait = Some(url),
|
||||
"SuperHeroArt" | "Hero" => art.hero = Some(url),
|
||||
"Logo" => art.logo = Some(url),
|
||||
"BoxArt" => art.header = Some(url),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
art
|
||||
// Same resolution as the management art proxy (WP1.2): the stored catalog, for ANY id, so a
|
||||
// library plugin's entries resolve without this ever knowing which store they came from. That
|
||||
// used to be the first of three branches — the other two served the built-in scanners (a
|
||||
// `steam:` id whose art was a relative proxy path, and the CDN-URL scanners) and went with them.
|
||||
let entry = entry_for_library_id(id)?;
|
||||
[
|
||||
ArtKind::Portrait,
|
||||
ArtKind::Header,
|
||||
ArtKind::Hero,
|
||||
ArtKind::Logo,
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|kind| art_field(&entry.art, kind))
|
||||
.find_map(|v| resolve_art_bytes(&v))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -627,7 +534,7 @@ mod tests {
|
||||
"/api/v1/library/art/custom:abc/portrait"
|
||||
));
|
||||
assert!(!is_local_art_path("/api/v1/library/art/steam:570/hero"));
|
||||
// …nor a protocol-relative CDN URL (what GOG / the MS catalog return — see `abs_url`).
|
||||
// …nor a protocol-relative CDN URL (what GOG / the MS catalog return).
|
||||
assert!(!is_local_art_path("//images.gog.com/abc_vertical.jpg"));
|
||||
// A relative path is not absolute — nothing to serve.
|
||||
assert!(!is_local_art_path("covers/x.jpg"));
|
||||
@@ -723,15 +630,67 @@ mod tests {
|
||||
|
||||
const PNG: &[u8] = &[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 13];
|
||||
|
||||
/// `PUNKTFUNK_LIBRARY_ART_ROOTS` is process-global while cargo runs tests as threads, so the
|
||||
/// tests that repoint it must not overlap — one clearing the variable mid-flight makes the
|
||||
/// other's temp root stop being a root, which fails as a confinement bug that isn't there.
|
||||
/// The variables the art roots derive from are process-global while cargo runs tests as threads,
|
||||
/// so the tests that repoint them must not overlap — one clearing a variable mid-flight makes
|
||||
/// another's temp root stop being a root, which fails as a confinement bug that isn't there.
|
||||
/// Poisoning is recovered rather than propagated: a panic in one test should report ITS
|
||||
/// failure, not cascade into an unrelated `PoisonError`.
|
||||
static ART_ROOTS_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn lock_art_roots() -> std::sync::MutexGuard<'static, ()> {
|
||||
ART_ROOTS_LOCK.lock().unwrap_or_else(|e| e.into_inner())
|
||||
/// Holds `ART_ROOTS_LOCK` and the overrides one test needs, restoring the previous values on
|
||||
/// drop. **The only place these tests touch the process environment** — which is what keeps the
|
||||
/// unsafe-hygiene gate's count flat as tests are added, and what makes the restore run on an
|
||||
/// unwind (the hand-rolled set/restore this replaced leaked its override to every later test
|
||||
/// whenever an assertion fired between the two halves).
|
||||
struct ArtRootsEnv {
|
||||
_lock: std::sync::MutexGuard<'static, ()>,
|
||||
saved: Vec<(&'static str, Option<std::ffi::OsString>)>,
|
||||
}
|
||||
|
||||
impl ArtRootsEnv {
|
||||
/// `None` unsets the variable for the test's duration.
|
||||
fn set(vars: &[(&'static str, Option<&Path>)]) -> Self {
|
||||
let _lock = ART_ROOTS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut saved = Vec::new();
|
||||
for (key, value) in vars {
|
||||
saved.push((*key, std::env::var_os(key)));
|
||||
// SAFETY: `_lock` is held for this guard's whole lifetime, and this type is the
|
||||
// only writer of these variables in the binary — so no other thread is reading
|
||||
// them while they change.
|
||||
unsafe { write_env(key, value.map(|p| p.as_os_str())) };
|
||||
}
|
||||
Self { _lock, saved }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ArtRootsEnv {
|
||||
fn drop(&mut self) {
|
||||
for (key, value) in &self.saved {
|
||||
// SAFETY: still under `_lock`, which outlives this loop — same argument as `set`.
|
||||
unsafe { write_env(key, value.as_deref()) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The single write point, so the hygiene gate has exactly one pair of call sites to judge.
|
||||
///
|
||||
/// # Safety
|
||||
/// The caller must hold `ART_ROOTS_LOCK`; the process environment is global and unsound to
|
||||
/// mutate while another thread reads it.
|
||||
unsafe fn write_env(key: &str, value: Option<&std::ffi::OsStr>) {
|
||||
match value {
|
||||
// SAFETY: the caller holds `ART_ROOTS_LOCK` (this function's documented contract), and
|
||||
// `ArtRootsEnv` is the only writer in the binary — so no other thread is reading the
|
||||
// environment while it changes.
|
||||
Some(v) => unsafe { std::env::set_var(key, v) },
|
||||
// SAFETY: as above — the caller's lock is what makes this sound.
|
||||
None => unsafe { std::env::remove_var(key) },
|
||||
}
|
||||
}
|
||||
|
||||
/// `PUNKTFUNK_LIBRARY_ART_ROOTS` pointed at one directory — what most of these tests want.
|
||||
fn confine_art_to(dir: &Path) -> ArtRootsEnv {
|
||||
ArtRootsEnv::set(&[("PUNKTFUNK_LIBRARY_ART_ROOTS", Some(dir))])
|
||||
}
|
||||
|
||||
/// The art proxy reads bytes in the HOST process (LocalSystem on Windows) from a path the
|
||||
@@ -739,15 +698,12 @@ mod tests {
|
||||
/// (2026-08-05 review H-2). Confinement, extension, and content are all load-bearing.
|
||||
#[test]
|
||||
fn local_art_bytes_is_confined_and_image_only() {
|
||||
let _guard = lock_art_roots();
|
||||
let dir = std::env::temp_dir().join(format!("pf-art-test-{}", std::process::id()));
|
||||
let outside = std::env::temp_dir().join(format!("pf-art-out-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
// Confine the proxy to `dir` for the duration of this test.
|
||||
// SAFETY: `_guard` holds ART_ROOTS_LOCK (`lock_art_roots`), which serializes every test
|
||||
// that writes or reads this variable in the binary.
|
||||
unsafe { std::env::set_var("PUNKTFUNK_LIBRARY_ART_ROOTS", &dir) };
|
||||
let _env = confine_art_to(&dir);
|
||||
|
||||
// A real image inside the root: served, with the content type SNIFFED from the bytes.
|
||||
let cover = dir.join("cover.png");
|
||||
@@ -823,8 +779,6 @@ mod tests {
|
||||
// A UNC path is refused outright (outbound SMB auth coercion), before any filesystem hit.
|
||||
assert!(!art_path_is_servable(r"\\attacker\share\a.png"));
|
||||
|
||||
// SAFETY: still under `_guard` — the same ART_ROOTS_LOCK serialization as the set.
|
||||
unsafe { std::env::remove_var("PUNKTFUNK_LIBRARY_ART_ROOTS") };
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let _ = std::fs::remove_dir_all(&outside);
|
||||
}
|
||||
@@ -887,14 +841,11 @@ mod tests {
|
||||
/// readable together is the point: either alone passes with the bug present.
|
||||
#[test]
|
||||
fn file_url_art_is_accepted_at_write_time_exactly_as_at_read_time() {
|
||||
let _guard = lock_art_roots();
|
||||
let dir = std::env::temp_dir().join(format!("pf-art-wr-{}", std::process::id()));
|
||||
let outside = std::env::temp_dir().join(format!("pf-art-wr-out-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
// SAFETY: `_guard` holds ART_ROOTS_LOCK (`lock_art_roots`), which serializes every test
|
||||
// that writes or reads this variable in the binary.
|
||||
unsafe { std::env::set_var("PUNKTFUNK_LIBRARY_ART_ROOTS", &dir) };
|
||||
let _env = confine_art_to(&dir);
|
||||
|
||||
let cover = dir.join("cover.png");
|
||||
std::fs::write(&cover, PNG).unwrap();
|
||||
@@ -946,12 +897,149 @@ mod tests {
|
||||
"an out-of-root file:// cover is still refused"
|
||||
);
|
||||
|
||||
// SAFETY: still under `_guard` — the same ART_ROOTS_LOCK serialization as the set.
|
||||
unsafe { std::env::remove_var("PUNKTFUNK_LIBRARY_ART_ROOTS") };
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let _ = std::fs::remove_dir_all(&outside);
|
||||
}
|
||||
|
||||
/// A reconcile keeps its entries when a cover is unservable — it drops the cover.
|
||||
///
|
||||
/// Regression for the report that opened this: on a default Windows Steam install every
|
||||
/// `appcache\librarycache` path fell outside the users base, `validate_art_paths` refused the
|
||||
/// whole `PUT /library/provider/steam` payload, and the operator's grid stayed EMPTY. The games
|
||||
/// were never the problem. Asserting the survivors matters as much as the drop: a sanitizer that
|
||||
/// cleared the whole struct would also "pass" a drop-only test.
|
||||
#[test]
|
||||
fn sanitize_drops_only_the_unservable_local_art() {
|
||||
let dir = std::env::temp_dir().join(format!("pf-art-san-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let _env = confine_art_to(&dir);
|
||||
|
||||
let cover = dir.join("cover.png");
|
||||
std::fs::write(&cover, PNG).unwrap();
|
||||
let cover_url = file_url(&cover);
|
||||
let outside = if cfg!(windows) {
|
||||
r"C:\Program Files (x86)\Steam\appcache\librarycache\570\a\library_hero.jpg".to_string()
|
||||
} else {
|
||||
"/opt/steam/appcache/librarycache/570/a/library_hero.jpg".to_string()
|
||||
};
|
||||
|
||||
let mut art = Artwork {
|
||||
portrait: Some(cover_url.clone()),
|
||||
hero: Some(outside.clone()),
|
||||
logo: Some("https://cdn/l.png".into()),
|
||||
header: Some("/api/v1/library/art/steam:570/header".into()),
|
||||
};
|
||||
let dropped = sanitize_art_paths(&mut art);
|
||||
assert_eq!(
|
||||
dropped,
|
||||
vec![("hero", outside)],
|
||||
"only the out-of-root local path is dropped, and it is reported"
|
||||
);
|
||||
assert!(art.hero.is_none(), "the unservable value is gone, not kept");
|
||||
// A servable local cover, a remote URL and an already-proxied path all survive untouched —
|
||||
// the entry still renders everything it legitimately can.
|
||||
assert_eq!(art.portrait.as_deref(), Some(cover_url.as_str()));
|
||||
assert_eq!(art.logo.as_deref(), Some("https://cdn/l.png"));
|
||||
assert_eq!(
|
||||
art.header.as_deref(),
|
||||
Some("/api/v1/library/art/steam:570/header")
|
||||
);
|
||||
// Idempotent: what survived one pass survives the next, and nothing new is reported.
|
||||
assert!(sanitize_art_paths(&mut art).is_empty());
|
||||
|
||||
// The invariant the hard 400 used to hold is still held — nothing the write gate would
|
||||
// refuse comes out the other side.
|
||||
assert!(validate_art_paths(&art).is_ok());
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Windows only, and the actual bug report: a Steam cover under Program Files is servable with
|
||||
/// NO `PUNKTFUNK_LIBRARY_ART_ROOTS` set.
|
||||
///
|
||||
/// Drives the whole chain the `steam` plugin's payload traverses — Program Files probe →
|
||||
/// [`steam_art_roots`] → [`art_roots`] → confinement → [`art_path_is_servable`] →
|
||||
/// [`local_art_bytes`] — against a synthetic Steam tree, by repointing `%ProgramFiles(x86)%` at
|
||||
/// a temp dir. Hermetic on purpose: asserting over whatever Steam this box happens to have would
|
||||
/// pass vacuously on every CI runner, which is exactly the shape of test that let this ship.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn steam_librarycache_cover_is_servable_without_configuration() {
|
||||
let base = std::env::temp_dir().join(format!("pf-art-steam-{}", std::process::id()));
|
||||
// `appcache\librarycache\<appid>\<hash>\library_hero.jpg` — the exact shape the plugin
|
||||
// publishes, and the exact field the reported failure named.
|
||||
let hero = base
|
||||
.join("Steam")
|
||||
.join("appcache")
|
||||
.join("librarycache")
|
||||
.join("570")
|
||||
.join("abcdef")
|
||||
.join("library_hero.jpg");
|
||||
std::fs::create_dir_all(hero.parent().unwrap()).unwrap();
|
||||
std::fs::write(&hero, PNG).unwrap();
|
||||
|
||||
// No configured roots (that is the claim under test), and the Program Files probe pointed
|
||||
// at the synthetic tree. Both restored on drop — `%ProgramFiles(x86)%` is a real variable
|
||||
// on this box that later tests in the same process may legitimately read.
|
||||
let _env = ArtRootsEnv::set(&[
|
||||
("PUNKTFUNK_LIBRARY_ART_ROOTS", None),
|
||||
("ProgramFiles(x86)", Some(&base)),
|
||||
]);
|
||||
|
||||
let steam_root = base.join("Steam");
|
||||
assert!(
|
||||
steam_art_roots().contains(&steam_root),
|
||||
"the Program Files probe must find the Steam install"
|
||||
);
|
||||
assert!(
|
||||
art_roots().contains(&steam_root),
|
||||
"the DEFAULT art roots must include it — the whole point is that no env var is needed"
|
||||
);
|
||||
|
||||
// The plugin sends `file://`, so that is what has to be accepted; before the fix this was
|
||||
// false and `validate_art_paths` 400'd the entire reconcile.
|
||||
let url = file_url(&hero);
|
||||
assert!(art_path_is_servable(&url), "{url} must be servable");
|
||||
assert!(
|
||||
validate_art_paths(&Artwork {
|
||||
hero: Some(url.clone()),
|
||||
..Default::default()
|
||||
})
|
||||
.is_ok(),
|
||||
"a Steam-shaped payload must reconcile"
|
||||
);
|
||||
assert!(
|
||||
sanitize_art_paths(&mut Artwork {
|
||||
hero: Some(url.clone()),
|
||||
..Default::default()
|
||||
})
|
||||
.is_empty(),
|
||||
"and nothing about it is dropped"
|
||||
);
|
||||
assert_eq!(
|
||||
local_art_bytes(&url).expect("read time serves it too").0,
|
||||
PNG
|
||||
);
|
||||
|
||||
// The confinement did not go slack on the way: a secret next door is still not servable,
|
||||
// and neither is a non-image that merely wears the extension.
|
||||
let secret = base.join("Steam").join("config").join("config.vdf");
|
||||
std::fs::create_dir_all(secret.parent().unwrap()).unwrap();
|
||||
std::fs::write(&secret, b"\"Accounts\"\n{\n\"user\" \"token\"\n}\n").unwrap();
|
||||
assert!(
|
||||
local_art_bytes(secret.to_str().unwrap()).is_none(),
|
||||
"Steam's own credential blob must not be servable from an art root"
|
||||
);
|
||||
let disguised = base.join("Steam").join("config.png");
|
||||
std::fs::write(&disguised, b"\"Accounts\" { \"user\" \"token\" }").unwrap();
|
||||
assert!(
|
||||
local_art_bytes(disguised.to_str().unwrap()).is_none(),
|
||||
"an image extension is still not enough — the bytes must BE an image"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sniff_image_type_recognizes_containers_and_rejects_secrets() {
|
||||
assert_eq!(sniff_image_type(PNG), Some("image/png"));
|
||||
|
||||
@@ -166,7 +166,7 @@ pub struct Catalog {
|
||||
///
|
||||
/// The map — not the entries — is the authority for a claim, which is exactly why it survives an
|
||||
/// **empty reconcile**: a store the plugin legitimately owns can have zero installed titles, and
|
||||
/// the built-in scanner it suppresses must stay suppressed anyway. Releasing is explicit
|
||||
/// it must keep owning the store's id space regardless. Releasing is explicit
|
||||
/// (`DELETE /library/provider/{p}`, or the plugin claiming a different store).
|
||||
#[serde(default)]
|
||||
pub claims: BTreeMap<String, String>,
|
||||
@@ -442,6 +442,35 @@ pub fn validate_store_claim(store: &str) -> Result<(), String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop every `launcher_ui` entry naming a launcher this host cannot actually open, returning the
|
||||
/// `(title, value)` pairs removed.
|
||||
///
|
||||
/// The launch-side counterpart to [`sanitize_art_paths`], and it exists for the same reason: a
|
||||
/// plugin reconciles its **whole** entry set at once, so anything that fails the payload costs the
|
||||
/// operator every game in it. The Playnite plugin appends one launcher tile beside the games, so a
|
||||
/// host that could not resolve `Playnite.FullscreenApp.exe` refused the lot — the operator saw an
|
||||
/// empty grid and a `HostRequestError` naming `entries[9]`, with nothing to say the other entries
|
||||
/// were fine.
|
||||
///
|
||||
/// Only the *unresolvable* case is dropped. A value outside the platform's vocabulary is still a
|
||||
/// hard 400 in [`validate_provider_payload`]: that one is a bug in the plugin, and silently
|
||||
/// swallowing it would leave the author with a tile that never appears and no reason why.
|
||||
///
|
||||
/// Dropping the whole entry rather than clearing its `launch` is deliberate — a launcher tile with
|
||||
/// no launch is a dead tile, which is strictly worse than no tile.
|
||||
pub fn sanitize_launcher_entries(inputs: &mut Vec<ProviderEntryInput>) -> Vec<(String, String)> {
|
||||
let mut dropped = Vec::new();
|
||||
inputs.retain(|e| {
|
||||
let Some(launch) = &e.launch else { return true };
|
||||
if launch.kind != "launcher_ui" || resolvable_launcher_ui(&launch.value) {
|
||||
return true;
|
||||
}
|
||||
dropped.push((e.title.clone(), launch.value.clone()));
|
||||
false
|
||||
});
|
||||
dropped
|
||||
}
|
||||
|
||||
/// Validate a reconcile payload: non-empty titles and unique, non-empty external ids (the
|
||||
/// diff key — a duplicate would make ownership of the surviving entry ambiguous).
|
||||
pub fn validate_provider_payload(inputs: &[ProviderEntryInput]) -> Result<(), String> {
|
||||
@@ -467,12 +496,13 @@ pub fn validate_provider_payload(inputs: &[ProviderEntryInput]) -> Result<(), St
|
||||
"entries[{i}]: `launch.value` for kind `steam_ui` must be `bigpicture` or `desktop`"
|
||||
));
|
||||
}
|
||||
// Refused rather than silently accepted, because the failure is otherwise invisible
|
||||
// until a user clicks the tile: an unresolvable value yields no command at launch time.
|
||||
if launch.kind == "launcher_ui" && !valid_launcher_ui(&launch.value) {
|
||||
// Only the VOCABULARY is refused here. Whether the launcher is actually installed on
|
||||
// this box is not the payload's fault, and 400ing over it threw away every game in the
|
||||
// reconcile — see `sanitize_launcher_entries`, which drops just the tile instead.
|
||||
if launch.kind == "launcher_ui" && !known_launcher_ui(&launch.value) {
|
||||
return Err(format!(
|
||||
"entries[{i}]: `launch.value` for kind `launcher_ui` names a launcher this host \
|
||||
cannot open (`{}`)",
|
||||
"entries[{i}]: `launch.value` for kind `launcher_ui` is not a launcher this \
|
||||
host's platform supports (`{}`)",
|
||||
launch.value
|
||||
));
|
||||
}
|
||||
@@ -573,7 +603,7 @@ fn reconcile_entries(
|
||||
///
|
||||
/// Claiming is idempotent for the holder and refused for anyone else. A provider holds at most one
|
||||
/// store, so claiming a new one releases whatever it held before — otherwise an abandoned claim would
|
||||
/// go on suppressing a built-in scanner with nothing to replace it.
|
||||
/// go on holding a store id that no plugin is filling any more, locking out the next claimant.
|
||||
pub fn reconcile_provider(
|
||||
provider: &str,
|
||||
store: Option<&str>,
|
||||
@@ -712,8 +742,9 @@ mod tests {
|
||||
assert_eq!(g.meta.platform.as_deref(), Some("PS2"));
|
||||
}
|
||||
|
||||
/// D2's core promise: a **claimed** entry is indistinguishable from what the built-in scanner
|
||||
/// produced. Same id, same store badge — plus the provider attribution the scanner never had.
|
||||
/// D2's core promise, and the reason removing the built-in scanners was invisible downstream: a
|
||||
/// **claimed** entry is indistinguishable from what the scanner produced. Same id, same store
|
||||
/// badge — plus the provider attribution the scanner never had.
|
||||
#[test]
|
||||
fn a_claimed_entry_reproduces_the_scanner_identity() {
|
||||
let mut e = manual("host-assigned", "Portal 2");
|
||||
@@ -1064,6 +1095,14 @@ mod tests {
|
||||
// Other kinds are unconstrained here (the host validates them per-kind at launch).
|
||||
assert!(validate_provider_payload(&[with_launch("command", "anything")]).is_ok());
|
||||
|
||||
// `launcher_ui` is checked for VOCABULARY only. A launcher that is merely not installed
|
||||
// must pass here and be dropped later — see `an_unopenable_launcher_tile_costs_only_itself`.
|
||||
assert!(validate_provider_payload(&[with_launch("launcher_ui", "nonesuch")]).is_err());
|
||||
#[cfg(windows)]
|
||||
assert!(validate_provider_payload(&[with_launch("launcher_ui", "playnite")]).is_ok());
|
||||
#[cfg(target_os = "linux")]
|
||||
assert!(validate_provider_payload(&[with_launch("launcher_ui", "lutris")]).is_ok());
|
||||
|
||||
let with_env = |key: &str, value: Option<&str>| {
|
||||
let mut i = input("a", "A");
|
||||
i.detect.env_marker = Some(EnvMarker {
|
||||
@@ -1128,4 +1167,40 @@ mod tests {
|
||||
"duplicate external_id"
|
||||
);
|
||||
}
|
||||
|
||||
/// The regression `sanitize_launcher_entries` exists for: a launcher tile this host cannot open
|
||||
/// must cost that tile, not the games reconciled beside it.
|
||||
///
|
||||
/// Field shape — the Playnite plugin appends exactly one `launcher_ui` tile after its games, so
|
||||
/// `entries[N]` failing validation used to refuse the entire payload and leave the operator with
|
||||
/// an empty grid and a `HostRequestError` that named only the index.
|
||||
#[test]
|
||||
fn an_unopenable_launcher_tile_costs_only_itself() {
|
||||
let mut tile = input("launcher", "Playnite");
|
||||
tile.role = GameRole::Launcher;
|
||||
tile.launch = Some(LaunchSpec {
|
||||
kind: "launcher_ui".into(),
|
||||
value: "playnite".into(),
|
||||
});
|
||||
|
||||
let mut inputs = vec![input("a", "A"), tile, input("b", "B")];
|
||||
let dropped = sanitize_launcher_entries(&mut inputs);
|
||||
|
||||
if resolvable_launcher_ui("playnite") {
|
||||
// A Windows box with Playnite actually installed keeps all three.
|
||||
assert!(dropped.is_empty());
|
||||
assert_eq!(inputs.len(), 3);
|
||||
} else {
|
||||
// Everywhere else the tile goes and both games survive — the whole point of the split.
|
||||
assert_eq!(dropped.len(), 1);
|
||||
assert_eq!(dropped[0].1, "playnite");
|
||||
assert_eq!(inputs.len(), 2);
|
||||
assert!(inputs.iter().all(|e| e.external_id != "launcher"));
|
||||
}
|
||||
|
||||
// A payload of nothing but games is untouched on every OS.
|
||||
let mut only_games = vec![input("a", "A"), input("b", "B")];
|
||||
assert!(sanitize_launcher_entries(&mut only_games).is_empty());
|
||||
assert_eq!(only_games.len(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,224 +0,0 @@
|
||||
//! Epic Games Store provider: installed manifests + the catalog-cache art index + launch URIs. Split out of the `library` facade (plan §W5).
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Reads the Epic Games Launcher's local install manifests. Windows-only. Best-effort: empty when
|
||||
/// the launcher (or its manifest dir) isn't present.
|
||||
#[cfg(windows)]
|
||||
pub struct EpicProvider;
|
||||
|
||||
#[cfg(windows)]
|
||||
impl LibraryProvider for EpicProvider {
|
||||
fn store(&self) -> &'static str {
|
||||
"epic"
|
||||
}
|
||||
|
||||
fn list(&self) -> Vec<GameEntry> {
|
||||
let data = epic_data_dir();
|
||||
let Ok(rd) = std::fs::read_dir(data.join("Manifests")) else {
|
||||
return Vec::new();
|
||||
};
|
||||
// Parse the (best-effort) artwork cache ONCE: catalogItemId -> Artwork.
|
||||
let art = epic_art_index(&data.join("Catalog").join("catcache.bin"));
|
||||
let mut games = Vec::new();
|
||||
for entry in rd.flatten() {
|
||||
let p = entry.path();
|
||||
if p.extension().and_then(|e| e.to_str()) != Some("item") {
|
||||
continue;
|
||||
}
|
||||
// `.item` manifests are small JSON; cap the read so a planted giant can't OOM the host.
|
||||
let Some(bytes) = read_capped(&p, 1024 * 1024) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(v) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(g) = epic_entry(&v, &art) {
|
||||
games.push(g);
|
||||
}
|
||||
}
|
||||
games
|
||||
}
|
||||
}
|
||||
|
||||
/// `%ProgramData%\Epic\EpicGamesLauncher\Data` (machine-wide, SYSTEM-readable).
|
||||
#[cfg(windows)]
|
||||
fn epic_data_dir() -> PathBuf {
|
||||
std::env::var_os("ProgramData")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from("C:\\ProgramData"))
|
||||
.join("Epic")
|
||||
.join("EpicGamesLauncher")
|
||||
.join("Data")
|
||||
}
|
||||
|
||||
/// Map one `.item` manifest to a [`GameEntry`], or `None` if it isn't a launchable game. Uses
|
||||
/// Playnite's proven EXCLUSION filter (skip `UE_*` Unreal components; skip a DLC/addon unless it is
|
||||
/// `addons/launchable`) rather than a positive `games`-category match, which can drop legit titles.
|
||||
#[cfg(windows)]
|
||||
fn epic_entry(
|
||||
v: &serde_json::Value,
|
||||
art: &std::collections::HashMap<String, Artwork>,
|
||||
) -> Option<GameEntry> {
|
||||
let s = |k: &str| v.get(k).and_then(|x| x.as_str());
|
||||
let app_name = s("AppName")?.to_string();
|
||||
if app_name.starts_with("UE_") {
|
||||
return None; // Unreal Engine component, not a game
|
||||
}
|
||||
let cats: Vec<&str> = v
|
||||
.get("AppCategories")
|
||||
.and_then(|c| c.as_array())
|
||||
.map(|a| a.iter().filter_map(|x| x.as_str()).collect())
|
||||
.unwrap_or_default();
|
||||
if cats.contains(&"addons") && !cats.contains(&"addons/launchable") {
|
||||
return None; // non-launchable DLC/addon
|
||||
}
|
||||
// Drop stale records whose install dir is gone.
|
||||
let install = s("InstallLocation")?;
|
||||
if !Path::new(install).is_dir() {
|
||||
return None;
|
||||
}
|
||||
let title = s("DisplayName").unwrap_or(&app_name).to_string();
|
||||
let namespace = s("CatalogNamespace").unwrap_or("");
|
||||
let catalog = s("CatalogItemId").unwrap_or("");
|
||||
// The robust launch form is the namespace:catalogItemId:appName triple; fall back to the bare
|
||||
// appName when those ids are absent (some manifests lack them) — never drop the launch entirely.
|
||||
let value = if !namespace.is_empty() && !catalog.is_empty() {
|
||||
format!("{namespace}:{catalog}:{app_name}")
|
||||
} else {
|
||||
app_name.clone()
|
||||
};
|
||||
// Detect signals: the manifest's own `LaunchExecutable` (relative to the install dir) is exact
|
||||
// when present; the install dir covers the rest (Epic hands off to its launcher, so the host
|
||||
// never owns the game's process).
|
||||
let detect = match s("LaunchExecutable")
|
||||
.map(|rel| Path::new(install).join(rel))
|
||||
.filter(|p| p.is_file())
|
||||
{
|
||||
Some(exe) => DetectSpec::exe(exe).with_dir(install),
|
||||
None => DetectSpec::dir(install),
|
||||
};
|
||||
Some(GameEntry {
|
||||
provider: None,
|
||||
role: GameRole::Game,
|
||||
icon: None,
|
||||
meta: GameMeta::pc(),
|
||||
id: format!("epic:{app_name}"),
|
||||
store: "epic".into(),
|
||||
title,
|
||||
art: art.get(catalog).cloned().unwrap_or_default(),
|
||||
launch: Some(LaunchSpec {
|
||||
kind: "epic".into(),
|
||||
value,
|
||||
}),
|
||||
detect,
|
||||
})
|
||||
}
|
||||
|
||||
/// Read a launcher cache/manifest with a hard size cap, so a local unprivileged user can't plant a
|
||||
/// multi-GB file under the launcher's (Users-writable) data dir that OOMs the privileged host when
|
||||
/// it's loaded — then base64/JSON-decoded into further copies — during library enumeration
|
||||
/// (security-review 2026-06-28 S4). Returns `None` if missing, empty, or over `max`. Mirrors the
|
||||
/// Linux lutris-art reader's 1 MiB cap.
|
||||
#[cfg(windows)]
|
||||
fn read_capped(path: &Path, max: u64) -> Option<Vec<u8>> {
|
||||
let meta = std::fs::metadata(path).ok()?;
|
||||
if meta.len() == 0 || meta.len() > max {
|
||||
if meta.len() > max {
|
||||
tracing::warn!(path = %path.display(), len = meta.len(), max, "launcher cache exceeds size cap — skipping");
|
||||
}
|
||||
return None;
|
||||
}
|
||||
std::fs::read(path).ok()
|
||||
}
|
||||
|
||||
/// Best-effort parse of `catcache.bin` (base64-encoded JSON array of catalog items) into
|
||||
/// catalogItemId → [`Artwork`] from each item's `keyImages`. Empty map on any read/decode failure
|
||||
/// (the format is community-reverse-engineered + can lag a fresh install → titles just show no art).
|
||||
#[cfg(windows)]
|
||||
fn epic_art_index(catcache: &Path) -> std::collections::HashMap<String, Artwork> {
|
||||
use base64::Engine as _;
|
||||
let mut map = std::collections::HashMap::new();
|
||||
// 32 MiB cap: comfortably fits a real catalog cache, blocks a planted giant (S4).
|
||||
let Some(raw) = read_capped(catcache, 32 * 1024 * 1024) else {
|
||||
return map;
|
||||
};
|
||||
let Ok(decoded) = base64::engine::general_purpose::STANDARD.decode(raw) else {
|
||||
return map;
|
||||
};
|
||||
let Ok(items) = serde_json::from_slice::<serde_json::Value>(&decoded) else {
|
||||
return map;
|
||||
};
|
||||
let Some(arr) = items.as_array() else {
|
||||
return map;
|
||||
};
|
||||
for item in arr {
|
||||
let Some(cat) = item
|
||||
.get("id")
|
||||
.or_else(|| item.get("catalogItemId"))
|
||||
.and_then(|v| v.as_str())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(images) = item.get("keyImages").and_then(|v| v.as_array()) else {
|
||||
continue;
|
||||
};
|
||||
let mut art = Artwork::default();
|
||||
for img in images {
|
||||
let (Some(ty), Some(url)) = (
|
||||
img.get("type").and_then(|v| v.as_str()),
|
||||
img.get("url").and_then(|v| v.as_str()),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
if !(url.starts_with("http://") || url.starts_with("https://")) {
|
||||
continue;
|
||||
}
|
||||
match ty {
|
||||
"DieselGameBoxTall" => art.portrait = Some(url.to_string()),
|
||||
"DieselGameBox" => art.hero = Some(url.to_string()),
|
||||
"DieselGameBoxLogo" => art.logo = Some(url.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if art.portrait.is_some() || art.hero.is_some() || art.logo.is_some() {
|
||||
map.insert(cat.to_string(), art);
|
||||
}
|
||||
}
|
||||
map
|
||||
}
|
||||
|
||||
// The `epic` launch mapping (`epic_launch_uri`) lives in `launch.rs` (WP1.1) — this module
|
||||
// enumerates, it does not launch.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn epic_filters_and_builds_launch() {
|
||||
let dir = std::env::temp_dir().join(format!("pf-epic-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let inst = dir.to_string_lossy().into_owned();
|
||||
let empty = std::collections::HashMap::new();
|
||||
// Normal game with the full triple → kept, triple launch value.
|
||||
let game = serde_json::json!({
|
||||
"AppName": "Fortnite", "DisplayName": "Fortnite", "CatalogNamespace": "fn",
|
||||
"CatalogItemId": "abc123", "InstallLocation": inst.clone(),
|
||||
"AppCategories": ["public", "games", "applications"]
|
||||
});
|
||||
let e = epic_entry(&game, &empty).expect("game kept");
|
||||
assert_eq!(e.id, "epic:Fortnite");
|
||||
assert_eq!(e.launch.as_ref().unwrap().value, "fn:abc123:Fortnite");
|
||||
// UE component, non-launchable addon, and a missing install dir are all skipped.
|
||||
let ue = serde_json::json!({"AppName":"UE_5.3","InstallLocation":inst.clone(),"AppCategories":["engines"]});
|
||||
assert!(epic_entry(&ue, &empty).is_none());
|
||||
let dlc =
|
||||
serde_json::json!({"AppName":"DLC","InstallLocation":inst,"AppCategories":["addons"]});
|
||||
assert!(epic_entry(&dlc, &empty).is_none());
|
||||
let gone = serde_json::json!({"AppName":"Gone","InstallLocation":"C:\\nope-xyz","AppCategories":["games"]});
|
||||
assert!(epic_entry(&gone, &empty).is_none());
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
//! GOG Galaxy store provider: installed games from the Galaxy DB + play-task launch resolution. Split out of the `library` facade (plan §W5).
|
||||
|
||||
use super::art::cached_art;
|
||||
use super::*;
|
||||
|
||||
/// Reads the GOG.com install registry + per-game `.info` files. Windows-only. Best-effort: empty
|
||||
/// when GOG isn't installed.
|
||||
#[cfg(windows)]
|
||||
pub struct GogProvider;
|
||||
|
||||
#[cfg(windows)]
|
||||
impl LibraryProvider for GogProvider {
|
||||
fn store(&self) -> &'static str {
|
||||
"gog"
|
||||
}
|
||||
|
||||
fn list(&self) -> Vec<GameEntry> {
|
||||
gog_games()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn gog_games() -> Vec<GameEntry> {
|
||||
use winreg::enums::HKEY_LOCAL_MACHINE;
|
||||
use winreg::RegKey;
|
||||
// 32-bit GOG writes under WOW6432Node; a 64-bit process reads the explicit path directly.
|
||||
let Ok(games_key) =
|
||||
RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey("SOFTWARE\\WOW6432Node\\GOG.com\\Games")
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for sub in games_key.enum_keys().flatten() {
|
||||
// The subkey name IS the GOG product id.
|
||||
let Ok(k) = games_key.open_subkey(&sub) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(path) = k.get_value::<String, _>("PATH") else {
|
||||
continue;
|
||||
};
|
||||
if !Path::new(&path).is_dir() {
|
||||
continue;
|
||||
}
|
||||
let title = k
|
||||
.get_value::<String, _>("GAMENAME")
|
||||
.unwrap_or_else(|_| sub.clone());
|
||||
// Resolve the primary play task (exe + args + workdir) from goggame-<id>.info; skip if absent.
|
||||
let Some((exe, args, workdir)) = gog_play_task(&path, &sub) else {
|
||||
continue;
|
||||
};
|
||||
let id = format!("gog:{sub}");
|
||||
// Art (public api.gog.com) is resolved off the hot path by the background warmer; read
|
||||
// whatever it has cached (title-only until warmed).
|
||||
let art = cached_art(&id).unwrap_or_default();
|
||||
// GOG launches the game's exe directly (no Galaxy), so the host owns the process and the
|
||||
// spec is only the fallback for a stub launcher that hands off; both signals are exact here.
|
||||
let detect = DetectSpec::exe(&exe).with_dir(&path);
|
||||
out.push(GameEntry {
|
||||
provider: None,
|
||||
role: GameRole::Game,
|
||||
icon: None,
|
||||
meta: GameMeta::pc(),
|
||||
id,
|
||||
store: "gog".into(),
|
||||
title,
|
||||
art,
|
||||
launch: Some(LaunchSpec {
|
||||
kind: "gog".into(),
|
||||
value: format!("{exe}\t{args}\t{workdir}"),
|
||||
}),
|
||||
detect,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Join a manifest-supplied relative path onto `install`, rejecting anything that could escape (or
|
||||
/// replace) it: a drive prefix (`C:`), a root (`\`), or a `..` component — any of which `Path::join`
|
||||
/// lets REPLACE or climb out of `install` on Windows. Keeps a crafted `goggame-*.info` from pointing
|
||||
/// the play task's exe or working dir at an arbitrary program (security-review 2026-07-17). `None`
|
||||
/// ⇒ the path is out of bounds and the caller refuses it.
|
||||
#[cfg(windows)]
|
||||
fn confined_join(install: &str, rel: &str) -> Option<PathBuf> {
|
||||
use std::path::Component;
|
||||
let rp = Path::new(rel);
|
||||
if rp.components().any(|c| {
|
||||
matches!(
|
||||
c,
|
||||
Component::Prefix(_) | Component::RootDir | Component::ParentDir
|
||||
)
|
||||
}) {
|
||||
return None;
|
||||
}
|
||||
Some(Path::new(install).join(rp))
|
||||
}
|
||||
|
||||
/// The primary play task from `<install>\goggame-<id>.info`: `(absolute exe, args, working dir)`.
|
||||
/// Prefers `isPrimary` + `FileTask`, else the first `FileTask`. Paths are resolved against `install`
|
||||
/// and confined to it ([`confined_join`]).
|
||||
#[cfg(windows)]
|
||||
fn gog_play_task(install: &str, id: &str) -> Option<(String, String, String)> {
|
||||
let text =
|
||||
std::fs::read_to_string(Path::new(install).join(format!("goggame-{id}.info"))).ok()?;
|
||||
let v: serde_json::Value = serde_json::from_str(&text).ok()?;
|
||||
let tasks = v.get("playTasks")?.as_array()?;
|
||||
let is_file =
|
||||
|t: &serde_json::Value| t.get("type").and_then(|s| s.as_str()) == Some("FileTask");
|
||||
let pick = tasks
|
||||
.iter()
|
||||
.find(|t| {
|
||||
t.get("isPrimary")
|
||||
.and_then(|b| b.as_bool())
|
||||
.unwrap_or(false)
|
||||
&& is_file(t)
|
||||
})
|
||||
.or_else(|| tasks.iter().find(|t| is_file(t)))?;
|
||||
let rel = pick.get("path").and_then(|s| s.as_str())?;
|
||||
// Refuse the launch outright if the manifest's exe path escapes the install dir.
|
||||
let exe = confined_join(install, rel)?;
|
||||
let args = pick
|
||||
.get("arguments")
|
||||
.and_then(|s| s.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let workdir = pick
|
||||
.get("workingDir")
|
||||
.and_then(|s| s.as_str())
|
||||
// A working dir that escapes falls back to the install root (safe) rather than failing.
|
||||
.and_then(|w| confined_join(install, w))
|
||||
.unwrap_or_else(|| Path::new(install).to_path_buf());
|
||||
Some((
|
||||
exe.to_string_lossy().into_owned(),
|
||||
args,
|
||||
workdir.to_string_lossy().into_owned(),
|
||||
))
|
||||
}
|
||||
|
||||
// The `gog` launch mapping (`gog_spawn`) lives in `launch.rs` (WP1.1) — this module enumerates and
|
||||
// resolves the spawn triple off disk, but turning that triple into a command line is launch-side.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn gog_play_task_picks_primary_filetask() {
|
||||
let dir = std::env::temp_dir().join(format!("pf-gog-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let id = "1207658924";
|
||||
std::fs::write(
|
||||
dir.join(format!("goggame-{id}.info")),
|
||||
r#"{"playTasks":[
|
||||
{"isPrimary":false,"type":"FileTask","path":"other.exe"},
|
||||
{"isPrimary":true,"type":"FileTask","path":"bin\\game.exe","arguments":"-w","workingDir":"bin"}
|
||||
]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (exe, args, wd) = gog_play_task(&dir.to_string_lossy(), id).unwrap();
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
assert!(exe.ends_with("bin\\game.exe"), "exe={exe}");
|
||||
assert_eq!(args, "-w");
|
||||
assert!(wd.ends_with("bin"), "wd={wd}");
|
||||
}
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
//! Heroic (Epic/GOG) store provider: installed games from Heroic's JSON stores + CDN art. Split out of the `library` facade (plan §W5).
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Reads Heroic Games Launcher's local library cache. One provider surfaces all three of Heroic's
|
||||
/// backends (legendary=Epic, gog=GOG, nile=Amazon). Linux-only for now (Heroic on Windows uses a
|
||||
/// different config path and the launch path isn't wired there yet).
|
||||
#[cfg(target_os = "linux")]
|
||||
pub struct HeroicProvider;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl LibraryProvider for HeroicProvider {
|
||||
fn store(&self) -> &'static str {
|
||||
"heroic"
|
||||
}
|
||||
|
||||
fn list(&self) -> Vec<GameEntry> {
|
||||
let Some(root) = heroic_root() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut games = Vec::new();
|
||||
// (cache file, runner id, the electron-store data key holding the games array)
|
||||
for (file, runner, key) in [
|
||||
("legendary_library.json", "legendary", "library"),
|
||||
("gog_library.json", "gog", "games"),
|
||||
("nile_library.json", "nile", "library"),
|
||||
] {
|
||||
let path = root.join("store_cache").join(file);
|
||||
match heroic_games(&path, runner, key) {
|
||||
Ok(mut g) => games.append(&mut g),
|
||||
Err(e) => {
|
||||
tracing::debug!(error = %e, file, "heroic store_cache not read (store unused?)")
|
||||
}
|
||||
}
|
||||
}
|
||||
games
|
||||
}
|
||||
}
|
||||
|
||||
/// The first existing Heroic config root: `$XDG_CONFIG_HOME/heroic`, classic `~/.config/heroic`, or
|
||||
/// the Flatpak path.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn heroic_root() -> Option<PathBuf> {
|
||||
let mut candidates = Vec::new();
|
||||
if let Some(d) = std::env::var_os("XDG_CONFIG_HOME") {
|
||||
candidates.push(PathBuf::from(d).join("heroic"));
|
||||
}
|
||||
if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
|
||||
candidates.push(home.join(".config/heroic"));
|
||||
candidates.push(home.join(".var/app/com.heroicgameslauncher.hgl/config/heroic"));
|
||||
}
|
||||
candidates.into_iter().find(|p| p.is_dir())
|
||||
}
|
||||
|
||||
/// Parse one runner's `store_cache/*_library.json` (an electron-store object whose `key` holds the
|
||||
/// games array). Keeps only installed titles whose install dir still exists (the latter works around
|
||||
/// Heroic's gog `is_installed` bug, #2691). Art comes straight from the cached public CDN URLs.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn heroic_games(path: &Path, runner: &str, key: &str) -> anyhow::Result<Vec<GameEntry>> {
|
||||
let raw = std::fs::read_to_string(path)?;
|
||||
let root: serde_json::Value = serde_json::from_str(&raw)?;
|
||||
let arr = root
|
||||
.get(key)
|
||||
.and_then(|v| v.as_array())
|
||||
.ok_or_else(|| anyhow::anyhow!("no '{key}' array in {}", path.display()))?;
|
||||
let mut games = Vec::new();
|
||||
for g in arr {
|
||||
if !g
|
||||
.get("is_installed")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
continue; // the cache also lists owned-but-not-installed titles
|
||||
}
|
||||
// The install dir doubles as this title's detect signal (Heroic hands off to
|
||||
// legendary/gogdl/nile, so the host never sees the game's own process any other way).
|
||||
let install_path = g
|
||||
.get("install")
|
||||
.and_then(|i| i.get("install_path"))
|
||||
.and_then(|p| p.as_str())
|
||||
.filter(|p| Path::new(p).is_dir());
|
||||
let Some(install_path) = install_path else {
|
||||
continue;
|
||||
};
|
||||
let Some(app_name) = g
|
||||
.get("app_name")
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let title = g
|
||||
.get("title")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or(app_name)
|
||||
.to_string();
|
||||
// Only emit http(s) art (sideloaded titles can carry local file:// paths the client can't fetch).
|
||||
let http = |k: &str| {
|
||||
g.get(k)
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| s.starts_with("http://") || s.starts_with("https://"))
|
||||
.map(String::from)
|
||||
};
|
||||
let art = Artwork {
|
||||
portrait: http("art_square"),
|
||||
header: http("art_cover"),
|
||||
hero: http("art_background").or_else(|| http("art_cover")),
|
||||
logo: http("art_logo"),
|
||||
};
|
||||
games.push(GameEntry {
|
||||
provider: None,
|
||||
role: GameRole::Game,
|
||||
icon: None,
|
||||
meta: GameMeta::pc(),
|
||||
id: format!("heroic:{runner}:{app_name}"),
|
||||
store: "heroic".into(),
|
||||
title,
|
||||
art,
|
||||
launch: Some(LaunchSpec {
|
||||
kind: "heroic".into(),
|
||||
value: format!("{runner}:{app_name}"),
|
||||
}),
|
||||
// The install dir is the reliable signal. `HEROIC_APP_NAME` is also stamped on the game's
|
||||
// env by Heroic's launch path; it is carried as a second, cheap signal (a union — if a
|
||||
// Heroic version doesn't set it, the install dir still matches).
|
||||
detect: DetectSpec::dir(install_path)
|
||||
.with_env("HEROIC_APP_NAME", Some(app_name.to_string())),
|
||||
});
|
||||
}
|
||||
Ok(games)
|
||||
}
|
||||
|
||||
// The `heroic` launch mapping (`heroic_command` + its launcher-prefix probe) lives in `launch.rs`
|
||||
// (WP1.1) — this module enumerates, it does not launch.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn heroic_games_parses_installed_with_cdn_art() {
|
||||
let dir = std::env::temp_dir().join(format!("pf-heroic-test-{}", std::process::id()));
|
||||
let install = dir.join("game-install");
|
||||
std::fs::create_dir_all(&install).unwrap();
|
||||
let path = dir.join("legendary_library.json");
|
||||
let json = format!(
|
||||
r#"{{"library":[
|
||||
{{"app_name":"Quail","title":"Quail","is_installed":true,
|
||||
"install":{{"install_path":"{inst}"}},
|
||||
"art_square":"https://cdn/quail_tall.jpg","art_cover":"https://cdn/quail_wide.jpg",
|
||||
"art_logo":"file:///local/logo.png"}},
|
||||
{{"app_name":"Owned","title":"Owned Only","is_installed":false,
|
||||
"install":{{"install_path":"{inst}"}}}}
|
||||
]}}"#,
|
||||
inst = install.display()
|
||||
);
|
||||
std::fs::write(&path, json).unwrap();
|
||||
let games = heroic_games(&path, "legendary", "library").unwrap();
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
assert_eq!(games.len(), 1); // the uninstalled title is filtered out
|
||||
assert_eq!(games[0].id, "heroic:legendary:Quail");
|
||||
assert_eq!(games[0].title, "Quail");
|
||||
assert_eq!(
|
||||
games[0].art.portrait.as_deref(),
|
||||
Some("https://cdn/quail_tall.jpg")
|
||||
);
|
||||
assert_eq!(
|
||||
games[0].art.header.as_deref(),
|
||||
Some("https://cdn/quail_wide.jpg")
|
||||
);
|
||||
assert!(games[0].art.logo.is_none()); // file:// art is dropped (client can't fetch it)
|
||||
let l = games[0].launch.as_ref().unwrap();
|
||||
assert_eq!(
|
||||
(l.kind.as_str(), l.value.as_str()),
|
||||
("heroic", "legendary:Quail")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -325,7 +325,7 @@ fn windows_launch_for(spec: &LaunchSpec) -> Option<(String, Option<std::path::Pa
|
||||
|
||||
/// Windows: the default Steam install's `steam.exe`, if present. A non-default Steam install dir
|
||||
/// (registry `Valve\Steam\InstallPath`) isn't covered — the explorer.exe protocol fallback handles
|
||||
/// that case. Mirrors [`steam_roots`]' "default Program Files dirs" approach.
|
||||
/// that case. Probes the default Program Files dirs, in `ProgramFiles(x86)`-first order.
|
||||
#[cfg(windows)]
|
||||
fn steam_exe() -> Option<std::path::PathBuf> {
|
||||
for var in ["ProgramFiles(x86)", "ProgramFiles", "ProgramW6432"] {
|
||||
@@ -339,6 +339,47 @@ fn steam_exe() -> Option<std::path::PathBuf> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Resolve a package's PackageFamilyName by finding its
|
||||
/// `AppRepository\Packages\<PackageFullName>` dir (machine-wide, SYSTEM-readable) and reducing the
|
||||
/// full name to `Name_PublisherHash`. This READS the authoritative PFN — never compute the hash.
|
||||
///
|
||||
/// **Readable by the host, NOT by the plugin runner.** Measured on 2026-08-06: that directory is
|
||||
/// `UnauthorizedAccessException` for `NT AUTHORITY\LocalService` (which the runner is), while the
|
||||
/// host service runs as LocalSystem and enumerates all 348 entries. That asymmetry is the entire
|
||||
/// reason the `xbox` launch kind exists — a library plugin sends the package Identity it CAN read
|
||||
/// out of `MicrosoftGame.config`, and this resolves the rest at launch time.
|
||||
///
|
||||
/// It lives here rather than beside a scanner because it is **launch** vocabulary: the in-host Xbox
|
||||
/// scanner that used to share it was removed with the rest of the built-ins, and the plugin that
|
||||
/// replaced it depends on exactly this resolution step.
|
||||
#[cfg(windows)]
|
||||
fn xbox_pfn(identity: &str) -> Option<String> {
|
||||
let pkgs = std::path::PathBuf::from(std::env::var_os("ProgramData")?)
|
||||
.join("Microsoft")
|
||||
.join("Windows")
|
||||
.join("AppRepository")
|
||||
.join("Packages");
|
||||
let prefix = format!("{identity}_");
|
||||
for e in std::fs::read_dir(&pkgs).ok()?.flatten() {
|
||||
let dn = e.file_name().to_string_lossy().into_owned();
|
||||
if dn.starts_with(&prefix) {
|
||||
if let Some(pfn) = pfn_from_full(&dn, identity) {
|
||||
return Some(pfn);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// PackageFamilyName from a PackageFullName dir name
|
||||
/// (`Name_Version_Arch_ResourceId_PublisherHash`) → `Name_PublisherHash`. The hash is the last
|
||||
/// `_`-segment; `Name` is the caller's identity.
|
||||
#[cfg(windows)]
|
||||
fn pfn_from_full(dir_name: &str, identity: &str) -> Option<String> {
|
||||
let hash = dir_name.rsplit('_').next()?;
|
||||
(!hash.is_empty() && hash != dir_name).then(|| format!("{identity}_{hash}"))
|
||||
}
|
||||
|
||||
// ------------------------------------------------------- per-kind launch values (host-owned ABI)
|
||||
//
|
||||
// Each helper below turns a store's launch VALUE — the only part a scanner (or, after extraction, a
|
||||
@@ -437,13 +478,31 @@ fn launcher_ui_stores() -> &'static [&'static str] {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is this a `launcher_ui` value this host can resolve?
|
||||
/// Is `value` a launcher this host's platform knows about at all?
|
||||
///
|
||||
/// On Windows, Playnite is validated by *resolution* rather than by being on the list: a host
|
||||
/// without Playnite installed refuses the entry (a 400 the plugin author can act on) instead of
|
||||
/// publishing a tile that does nothing when a user clicks it.
|
||||
pub(crate) fn valid_launcher_ui(value: &str) -> bool {
|
||||
if !launcher_ui_stores().contains(&value) {
|
||||
/// The *vocabulary* half of the old `valid_launcher_ui`. A value outside this set is a plugin
|
||||
/// author's mistake — a typo, or a launcher this OS has no support for — and no amount of
|
||||
/// installing things on the box will make it resolve, so the reconcile refuses the payload.
|
||||
pub(crate) fn known_launcher_ui(value: &str) -> bool {
|
||||
launcher_ui_stores().contains(&value)
|
||||
}
|
||||
|
||||
/// Can this host open `value`'s launcher **right now**?
|
||||
///
|
||||
/// The *environment* half. Deliberately separate from [`known_launcher_ui`], because the two
|
||||
/// failures are not the same kind of thing and must not get the same answer:
|
||||
///
|
||||
/// - an unknown value is a bug in the plugin, and a 400 is the only way its author finds out;
|
||||
/// - a known value that will not resolve means the launcher simply is not installed here, which is
|
||||
/// an ordinary fact about the box, not a defect in the payload.
|
||||
///
|
||||
/// Conflating them cost a real library: the Playnite plugin publishes one launcher tile alongside
|
||||
/// every game, so a host that could not resolve Playnite 400'd the whole reconcile and the operator
|
||||
/// got **no games at all** — the same shape as the unservable-cover bug that
|
||||
/// [`super::sanitize_art_paths`] was introduced to fix. The tile is dropped now (see
|
||||
/// [`super::sanitize_launcher_entries`]) and the games sync.
|
||||
pub(crate) fn resolvable_launcher_ui(value: &str) -> bool {
|
||||
if !known_launcher_ui(value) {
|
||||
return false;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
@@ -461,36 +520,141 @@ pub(crate) fn valid_launcher_ui(value: &str) -> bool {
|
||||
/// directly, which is also why nothing here is interpolated from the entry: the whole value is the
|
||||
/// literal `"playnite"`.
|
||||
///
|
||||
/// Playnite installs per-user by default, so the install directory comes from its own uninstall
|
||||
/// entry (HKCU first, then HKLM for a machine-wide install), falling back to the default
|
||||
/// `%LOCALAPPDATA%\Playnite`. `None` when nothing resolves, which is what refuses the tile.
|
||||
/// `None` when nothing resolves, which is what drops the tile.
|
||||
#[cfg(windows)]
|
||||
fn playnite_fullscreen_exe() -> Option<std::path::PathBuf> {
|
||||
use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
|
||||
use winreg::RegKey;
|
||||
const KEY: &str = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Playnite";
|
||||
const EXE: &str = "Playnite.FullscreenApp.exe";
|
||||
|
||||
let from_registry = [HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE]
|
||||
playnite_install_dirs()
|
||||
.into_iter()
|
||||
.find_map(|root| {
|
||||
RegKey::predef(root)
|
||||
.open_subkey(KEY)
|
||||
.ok()?
|
||||
.get_value::<String, _>("InstallLocation")
|
||||
.ok()
|
||||
})
|
||||
.map(std::path::PathBuf::from);
|
||||
|
||||
from_registry
|
||||
.into_iter()
|
||||
.chain(
|
||||
std::env::var_os("LOCALAPPDATA").map(|l| std::path::PathBuf::from(l).join("Playnite")),
|
||||
)
|
||||
.map(|dir| dir.join(EXE))
|
||||
.find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// Windows: every directory that might hold a Playnite install, best candidates first.
|
||||
///
|
||||
/// **Playnite installs per-user by default, and this host is a LocalSystem service** — which
|
||||
/// invalidates all three of the obvious lookups, and is why this is not a two-liner:
|
||||
///
|
||||
/// - `HKEY_CURRENT_USER` is *SYSTEM's own* hive (`S-1-5-18`), never the person's, so a per-user
|
||||
/// install is invisible there. Every **loaded** hive under `HKEY_USERS` is read instead: only
|
||||
/// logged-on users' hives are loaded, which is exactly the set that can be streaming, and it
|
||||
/// avoids a `WTSQueryUserToken` dance for what is a best-effort probe. Same trade-off
|
||||
/// [`crate::procscan::steam_running_hint`] makes, for the same reason.
|
||||
/// - The uninstall subkey is matched by its **`DisplayName`**, not by key name. Playnite ships an
|
||||
/// Inno Setup installer and Inno registers `<AppId>_is1` — measured on a Windows box where Git
|
||||
/// and Inno itself appear as `Git_is1` and `Inno Setup 6_is1`. The hardcoded
|
||||
/// `…\Uninstall\Playnite` this replaced matched nothing on any box.
|
||||
/// - `%LOCALAPPDATA%` for a SYSTEM service is `C:\Windows\System32\config\systemprofile\AppData\
|
||||
/// Local`, so the default-install fallback cannot trust the variable — it enumerates the profiles
|
||||
/// under the users base instead, the same breadth [`super::art::art_roots`] already allows.
|
||||
///
|
||||
/// Order matters only as a preference: a registry `InstallLocation` is what the installer actually
|
||||
/// did, so it is consulted before the conventional path. Every candidate is probed for the exe, so
|
||||
/// a stale entry costs one `is_file` and nothing else.
|
||||
#[cfg(windows)]
|
||||
fn playnite_install_dirs() -> Vec<std::path::PathBuf> {
|
||||
use winreg::enums::{HKEY_LOCAL_MACHINE, HKEY_USERS, KEY_READ};
|
||||
use winreg::RegKey;
|
||||
|
||||
// 64-bit and 32-bit views. HKCU/HKU `Software` is not redirected (only `Software\Classes` is),
|
||||
// so the WOW view is a machine-hive concern only.
|
||||
const UNINSTALL: &str = r"Software\Microsoft\Windows\CurrentVersion\Uninstall";
|
||||
const UNINSTALL_WOW: &str = r"Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
|
||||
|
||||
let mut dirs: Vec<std::path::PathBuf> = Vec::new();
|
||||
|
||||
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
|
||||
playnite_dirs_from_uninstall(&hklm, UNINSTALL, &mut dirs);
|
||||
playnite_dirs_from_uninstall(&hklm, UNINSTALL_WOW, &mut dirs);
|
||||
|
||||
let users = RegKey::predef(HKEY_USERS);
|
||||
for sid in users.enum_keys().flatten() {
|
||||
// The `…_Classes` companion hives carry file associations, never uninstall entries.
|
||||
if sid.ends_with("_Classes") {
|
||||
continue;
|
||||
}
|
||||
if let Ok(hive) = users.open_subkey_with_flags(&sid, KEY_READ) {
|
||||
playnite_dirs_from_uninstall(&hive, UNINSTALL, &mut dirs);
|
||||
}
|
||||
}
|
||||
|
||||
// The conventional per-user location, for every profile on the box — this is where Playnite's
|
||||
// own default install lands, and it covers a user whose hive is not currently loaded.
|
||||
for profile in windows_user_profiles() {
|
||||
push_unique(&mut dirs, profile.join(r"AppData\Local\Playnite"));
|
||||
}
|
||||
dirs
|
||||
}
|
||||
|
||||
/// Collect `InstallLocation` from every Playnite-looking uninstall entry under `root\path`.
|
||||
///
|
||||
/// Matched on `DisplayName` because the key name is the installer's `AppId` (see
|
||||
/// [`playnite_install_dirs`]). `starts_with` rather than equality so a versioned or suffixed display
|
||||
/// name still counts; the value is only ever used as a directory to probe for the exe, so a false
|
||||
/// positive costs one failed `is_file`.
|
||||
#[cfg(windows)]
|
||||
fn playnite_dirs_from_uninstall(
|
||||
root: &winreg::RegKey,
|
||||
path: &str,
|
||||
out: &mut Vec<std::path::PathBuf>,
|
||||
) {
|
||||
use winreg::enums::KEY_READ;
|
||||
|
||||
let Ok(uninstall) = root.open_subkey_with_flags(path, KEY_READ) else {
|
||||
return;
|
||||
};
|
||||
for name in uninstall.enum_keys().flatten() {
|
||||
let Ok(entry) = uninstall.open_subkey_with_flags(&name, KEY_READ) else {
|
||||
continue;
|
||||
};
|
||||
let display: String = entry.get_value("DisplayName").unwrap_or_default();
|
||||
if !display.starts_with("Playnite") {
|
||||
continue;
|
||||
}
|
||||
if let Ok(location) = entry.get_value::<String, _>("InstallLocation") {
|
||||
let location = location.trim();
|
||||
if !location.is_empty() {
|
||||
push_unique(out, std::path::PathBuf::from(location));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every user profile directory on the box (`C:\Users\*`), minus the shared `Public` pseudo-profile.
|
||||
///
|
||||
/// `%PUBLIC%`'s parent is the users base on every supported Windows — the same derivation
|
||||
/// [`super::art::art_roots`] uses — with `%SystemDrive%\Users` as the fallback when the variable is
|
||||
/// missing from a service's environment.
|
||||
#[cfg(windows)]
|
||||
fn windows_user_profiles() -> Vec<std::path::PathBuf> {
|
||||
let base = std::env::var_os("PUBLIC")
|
||||
.map(std::path::PathBuf::from)
|
||||
.and_then(|p| p.parent().map(std::path::Path::to_path_buf))
|
||||
.or_else(|| {
|
||||
std::env::var_os("SystemDrive").map(|d| std::path::PathBuf::from(d).join("Users"))
|
||||
});
|
||||
let Some(base) = base else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Ok(entries) = std::fs::read_dir(&base) else {
|
||||
return Vec::new();
|
||||
};
|
||||
entries
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.is_dir() && !p.ends_with("Public"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Push `path` unless an equal one is already there — the candidate lists are a handful of entries,
|
||||
/// so a linear check beats carrying a set around.
|
||||
#[cfg(windows)]
|
||||
fn push_unique(out: &mut Vec<std::path::PathBuf>, path: std::path::PathBuf) {
|
||||
if !out.contains(&path) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a `heroic` LaunchSpec value (`<runner>:<appName>`) to the Heroic launch command, run nested in
|
||||
/// gamescope. The host owns this mapping; the client only ever sends the id. CAVEAT: Heroic is a
|
||||
/// single-instance Electron app — in a fresh per-session gamescope it boots, launches the game (which
|
||||
@@ -759,33 +923,38 @@ mod tests {
|
||||
fn launcher_ui_accepts_only_launchers_this_host_can_open() {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
assert!(valid_launcher_ui("heroic"));
|
||||
assert!(valid_launcher_ui("lutris"));
|
||||
// Not wired on this OS — refused inbound rather than becoming a tile that does nothing.
|
||||
assert!(!valid_launcher_ui("gog"));
|
||||
assert!(known_launcher_ui("heroic"));
|
||||
assert!(known_launcher_ui("lutris"));
|
||||
// Not wired on this OS — outside the vocabulary, so it is refused inbound rather than
|
||||
// becoming a tile that does nothing.
|
||||
assert!(!known_launcher_ui("gog"));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
// Playnite is accepted only when this host can actually FIND its Fullscreen app:
|
||||
// validation is resolution, so a box without Playnite refuses the entry rather than
|
||||
// publishing a tile that does nothing when clicked.
|
||||
// Playnite is in the vocabulary unconditionally — whether this particular box has it
|
||||
// installed is a separate question, answered by `resolvable_launcher_ui` below. Keeping
|
||||
// them separate is the fix for the reconcile that 400'd a whole library over one tile.
|
||||
assert!(known_launcher_ui("playnite"));
|
||||
assert_eq!(
|
||||
valid_launcher_ui("playnite"),
|
||||
resolvable_launcher_ui("playnite"),
|
||||
playnite_fullscreen_exe().is_some()
|
||||
);
|
||||
// The Linux launchers, and the Windows ones whose activation is still unverified
|
||||
// (Epic, GOG Galaxy, the Xbox app), stay refused.
|
||||
assert!(!valid_launcher_ui("heroic"));
|
||||
assert!(!valid_launcher_ui("gog"));
|
||||
assert!(!known_launcher_ui("heroic"));
|
||||
assert!(!known_launcher_ui("gog"));
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", windows)))]
|
||||
{
|
||||
// No launcher UIs are wired on this OS, so every value is refused.
|
||||
assert!(!valid_launcher_ui("heroic"));
|
||||
assert!(!valid_launcher_ui("gog"));
|
||||
assert!(!known_launcher_ui("heroic"));
|
||||
assert!(!known_launcher_ui("gog"));
|
||||
}
|
||||
assert!(!valid_launcher_ui(""));
|
||||
assert!(!valid_launcher_ui("lutris; rm -rf ~"));
|
||||
// Junk is outside the vocabulary on every OS, so it never reaches a resolver.
|
||||
assert!(!known_launcher_ui(""));
|
||||
assert!(!known_launcher_ui("lutris; rm -rf ~"));
|
||||
assert!(!resolvable_launcher_ui(""));
|
||||
assert!(!resolvable_launcher_ui("lutris; rm -rf ~"));
|
||||
}
|
||||
|
||||
/// The `xbox` kind is what a library PLUGIN can publish: the runner's principal cannot read
|
||||
@@ -941,6 +1110,24 @@ mod tests {
|
||||
assert!(gog_spawn("").is_none());
|
||||
}
|
||||
|
||||
/// Moved here with `xbox_pfn` when the built-in scanners were removed: reducing a
|
||||
/// PackageFullName to its family name is what the `xbox` launch kind does with the Identity a
|
||||
/// de-privileged plugin sends it, so the guard belongs to the launch path now.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn pfn_reduces_a_package_full_name_to_its_family() {
|
||||
assert_eq!(
|
||||
pfn_from_full(
|
||||
"Microsoft.624F8B84B80_1.0.0.0_x64__8wekyb3d8bbwe",
|
||||
"Microsoft.624F8B84B80"
|
||||
)
|
||||
.as_deref(),
|
||||
Some("Microsoft.624F8B84B80_8wekyb3d8bbwe")
|
||||
);
|
||||
// No `_` at all → nothing to reduce, and we must not invent a hash.
|
||||
assert!(pfn_from_full("NoUnderscore", "NoUnderscore").is_none());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_launch_for_maps_and_guards() {
|
||||
|
||||
@@ -1,194 +0,0 @@
|
||||
//! Lutris store provider: installed games from the Lutris SQLite DB + lutris.net CDN art. Split out of the `library` facade (plan §W5).
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Reads the **local** Lutris library DB (`pga.db`) — no network. Installed titles only; cover art
|
||||
/// from Lutris's on-disk cache, inlined as `data:` URLs. Linux-only (Lutris is Linux-only).
|
||||
#[cfg(target_os = "linux")]
|
||||
pub struct LutrisProvider;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl LibraryProvider for LutrisProvider {
|
||||
fn store(&self) -> &'static str {
|
||||
"lutris"
|
||||
}
|
||||
|
||||
fn list(&self) -> Vec<GameEntry> {
|
||||
let Some(db) = lutris_db() else {
|
||||
return Vec::new();
|
||||
};
|
||||
lutris_games(&db).unwrap_or_else(|e| {
|
||||
tracing::warn!(error = %e, db = %db.display(), "lutris pga.db read failed — skipping");
|
||||
Vec::new()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The first existing Lutris `pga.db`: XDG data dir, the classic `~/.local/share`, or Flatpak.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn lutris_db() -> Option<PathBuf> {
|
||||
let mut candidates = Vec::new();
|
||||
if let Some(d) = std::env::var_os("XDG_DATA_HOME") {
|
||||
candidates.push(PathBuf::from(d).join("lutris/pga.db"));
|
||||
}
|
||||
if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
|
||||
candidates.push(home.join(".local/share/lutris/pga.db"));
|
||||
candidates.push(home.join(".var/app/net.lutris.Lutris/data/lutris/pga.db"));
|
||||
}
|
||||
candidates.into_iter().find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// Installed games from a Lutris `pga.db`. Opened **read-only + immutable** (via a SQLite URI) so a
|
||||
/// running Lutris holding the file can't make us block or fail, and we never write to it.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn lutris_games(db: &Path) -> rusqlite::Result<Vec<GameEntry>> {
|
||||
use rusqlite::OpenFlags;
|
||||
// `immutable=1` treats the DB as read-only-and-unchanging → no locking against a live Lutris. The
|
||||
// path goes into the URI literally; a `?`/`#` in it (vanishingly rare on Linux) would mis-parse,
|
||||
// so fall back to a plain read-only open in that case.
|
||||
let path = db.to_string_lossy();
|
||||
let conn = if path.contains('?') || path.contains('#') {
|
||||
rusqlite::Connection::open_with_flags(db, OpenFlags::SQLITE_OPEN_READ_ONLY)?
|
||||
} else {
|
||||
rusqlite::Connection::open_with_flags(
|
||||
format!("file:{path}?immutable=1"),
|
||||
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_URI,
|
||||
)?
|
||||
};
|
||||
// `directory` (the game's install dir — our detect signal) is not load-bearing for the library, so
|
||||
// a pga.db schema without it must not cost the whole Lutris store: try the richer query first and
|
||||
// fall back to the historical one on any prepare error.
|
||||
const SELECT_WITH_DIR: &str = "SELECT id, slug, name, directory FROM games \
|
||||
WHERE installed = 1 AND name IS NOT NULL AND name <> '' \
|
||||
ORDER BY name COLLATE NOCASE";
|
||||
const SELECT_PLAIN: &str = "SELECT id, slug, name, NULL FROM games \
|
||||
WHERE installed = 1 AND name IS NOT NULL AND name <> '' \
|
||||
ORDER BY name COLLATE NOCASE";
|
||||
let mut stmt = match conn.prepare(SELECT_WITH_DIR) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "lutris pga.db has no `directory` column — listing without \
|
||||
install dirs (game-exit detection unavailable for Lutris titles)");
|
||||
conn.prepare(SELECT_PLAIN)?
|
||||
}
|
||||
};
|
||||
let rows = stmt.query_map([], |row| {
|
||||
Ok((
|
||||
row.get::<_, i64>(0)?,
|
||||
row.get::<_, Option<String>>(1)?,
|
||||
row.get::<_, String>(2)?,
|
||||
row.get::<_, Option<String>>(3)?,
|
||||
))
|
||||
})?;
|
||||
let mut games = Vec::new();
|
||||
for (id, slug, name, directory) in rows.flatten() {
|
||||
games.push(GameEntry {
|
||||
provider: None,
|
||||
role: GameRole::Game,
|
||||
icon: None,
|
||||
meta: GameMeta::pc(),
|
||||
id: format!("lutris:{id}"),
|
||||
store: "lutris".into(),
|
||||
title: name,
|
||||
art: slug.as_deref().map(lutris_art).unwrap_or_default(),
|
||||
launch: Some(LaunchSpec {
|
||||
kind: "lutris_id".into(),
|
||||
value: id.to_string(),
|
||||
}),
|
||||
// Lutris stamps no per-game env marker we can rely on, so the install dir is the whole
|
||||
// recipe; a game with none (an emulator entry pointing at a bare ROM) stays untracked.
|
||||
detect: directory
|
||||
.filter(|d| !d.trim().is_empty())
|
||||
.map(DetectSpec::dir)
|
||||
.unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
Ok(games)
|
||||
}
|
||||
|
||||
/// Lutris cover art (local files keyed by slug) inlined as `data:` URLs — Lutris has no public CDN
|
||||
/// keyed by a stable id (unlike Steam/Heroic), and `Artwork` fields are URLs the client fetches, so a
|
||||
/// self-contained `data:` URL needs no host-served endpoint. `coverart` → portrait, `banners` → header.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn lutris_art(slug: &str) -> Artwork {
|
||||
Artwork {
|
||||
portrait: lutris_image("coverart", slug),
|
||||
header: lutris_image("banners", slug),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Find `<kind>/<slug>.jpg` across the current (0.5.18+), legacy (`~/.cache`), and Flatpak Lutris
|
||||
/// dirs and inline it as `data:image/jpeg;base64,…`. Skips a missing or implausibly large file (a
|
||||
/// 1 MiB cap bounds the catalog JSON so a few big files can't bloat it).
|
||||
#[cfg(target_os = "linux")]
|
||||
fn lutris_image(kind: &str, slug: &str) -> Option<String> {
|
||||
use base64::Engine as _;
|
||||
// `slug` comes verbatim from Lutris's `pga.db` (untrusted at this layer). Reject any path
|
||||
// separator, parent ref, or NUL so a crafted slug can't escape the art roots and read an
|
||||
// arbitrary `<slug>.jpg` off disk — the bytes are base64-inlined into the `/api/v1/library`
|
||||
// JSON a paired client can GET, so an escape is an arbitrary-file-read exfil primitive
|
||||
// (security-review 2026-07-17). Real Lutris slugs are `[a-z0-9-]`.
|
||||
if slug.is_empty()
|
||||
|| slug.contains('/')
|
||||
|| slug.contains('\\')
|
||||
|| slug.contains("..")
|
||||
|| slug.contains('\0')
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let home = std::env::var_os("HOME").map(PathBuf::from)?;
|
||||
let roots = [
|
||||
home.join(".local/share/lutris"),
|
||||
home.join(".cache/lutris"),
|
||||
home.join(".var/app/net.lutris.Lutris/data/lutris"),
|
||||
home.join(".var/app/net.lutris.Lutris/cache/lutris"),
|
||||
];
|
||||
for root in roots {
|
||||
let p = root.join(kind).join(format!("{slug}.jpg"));
|
||||
let Ok(meta) = std::fs::metadata(&p) else {
|
||||
continue;
|
||||
};
|
||||
if meta.len() == 0 || meta.len() > 1024 * 1024 {
|
||||
continue;
|
||||
}
|
||||
if let Ok(bytes) = std::fs::read(&p) {
|
||||
let enc = base64::engine::general_purpose::STANDARD.encode(&bytes);
|
||||
return Some(format!("data:image/jpeg;base64,{enc}"));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn lutris_games_reads_installed_only() {
|
||||
use rusqlite::Connection;
|
||||
let dir = std::env::temp_dir().join(format!("pf-lutris-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let db = dir.join("pga.db");
|
||||
{
|
||||
let c = Connection::open(&db).unwrap();
|
||||
c.execute_batch(
|
||||
"CREATE TABLE games (id INTEGER PRIMARY KEY, slug TEXT, name TEXT, installed INTEGER);
|
||||
INSERT INTO games (id,slug,name,installed) VALUES (42,'elden-ring','ELDEN RING',1);
|
||||
INSERT INTO games (id,slug,name,installed) VALUES (7,'owned','Owned Only',0);
|
||||
INSERT INTO games (id,slug,name,installed) VALUES (9,'noname',NULL,1);",
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let games = lutris_games(&db).unwrap();
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
// Only the installed, named row; the uninstalled + NULL-name rows are filtered out.
|
||||
assert_eq!(games.len(), 1);
|
||||
assert_eq!(games[0].id, "lutris:42");
|
||||
assert_eq!(games[0].store, "lutris");
|
||||
assert_eq!(games[0].title, "ELDEN RING");
|
||||
let l = games[0].launch.as_ref().unwrap();
|
||||
assert_eq!((l.kind.as_str(), l.value.as_str()), ("lutris_id", "42"));
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
//! Library-scanner settings: which installed-store scanners run on this host. Every scanner is
|
||||
//! **on by default** (the shipped behavior before this existed); the operator can turn one off in
|
||||
//! the web console, which hides its titles from every library surface (console grid, native
|
||||
//! clients, the GameStream app list, launch resolution) from the next read. Only the *disabled*
|
||||
//! set is persisted, so a scanner added in a future build starts enabled without a migration.
|
||||
//! Game-source settings: which of this host's library sources contribute titles. Every source is
|
||||
//! **on by default**; the operator can turn one off in the web console, which hides its titles from
|
||||
//! every library surface (console grid, native clients, the GameStream app list, launch resolution)
|
||||
//! from the next read. Only the *disabled* set is persisted, so a source that appears later starts
|
||||
//! enabled without a migration.
|
||||
//!
|
||||
//! The user-curated **custom** store is not a scanner (nothing is scanned — the operator typed the
|
||||
//! entries in) and cannot be disabled here; provider plugins (RFC §8) likewise own their entries
|
||||
//! through the reconcile API. Down the road the scanners themselves are slated to become plugins —
|
||||
//! the stable per-scanner ids this module fixes (`steam`, `lutris`, …, matching each entry's
|
||||
//! `store` field) are the forward seam for that migration.
|
||||
//! **Every source here is a plugin now.** Through v0.27.x this module also enumerated the six
|
||||
//! scanners compiled into the host; that list is gone with the scanners themselves. The forward seam
|
||||
//! it was built for did its job exactly as designed — the ids never changed (provider id = claimed
|
||||
//! store id = old scanner id), so an operator who had `steam` switched off before the migration
|
||||
//! still has it switched off after, with nothing to carry over and no migration step. That property
|
||||
//! is the reason `library-scanners.json` keeps its name and its shape.
|
||||
//!
|
||||
//! The user-curated **custom** store is not a source (nothing is scanned — the operator typed the
|
||||
//! entries in) and cannot be disabled here.
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -27,8 +31,9 @@ pub struct ScannerInfo {
|
||||
pub label: String,
|
||||
/// Whether this host runs the source (default true).
|
||||
pub enabled: bool,
|
||||
/// Where the source comes from: `builtin` (a scanner in this host build) or `plugin`.
|
||||
#[schema(example = "builtin")]
|
||||
/// Where the source comes from. Always `plugin` from this host build onward — see
|
||||
/// [`SourceOrigin`].
|
||||
#[schema(example = "plugin")]
|
||||
pub origin: SourceOrigin,
|
||||
/// The provider id backing a `plugin` source — absent for a built-in scanner.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -43,30 +48,31 @@ pub struct ScannerInfo {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, ToSchema)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum SourceOrigin {
|
||||
/// A scanner compiled into this host build.
|
||||
/// A scanner compiled into the host build.
|
||||
///
|
||||
/// **No host build emits this any more** — the built-in scanners were removed in v0.28.0. The
|
||||
/// variant is kept deliberately, because it is still part of the API's vocabulary: the web
|
||||
/// console ships as its own package and is expected to drive an N-1 host, which does still
|
||||
/// report `builtin` sources. Deleting it here would drop `builtin` from the OpenAPI enum and
|
||||
/// narrow the console's generated union out from under that pairing.
|
||||
#[allow(dead_code)]
|
||||
Builtin,
|
||||
/// A plugin reconciling entries over the provider API.
|
||||
Plugin,
|
||||
}
|
||||
|
||||
/// The scanners compiled into THIS host build: (id, label). Steam is cross-platform; the rest are
|
||||
/// platform-gated exactly like their provider modules in `library.rs` — keep the two in sync when
|
||||
/// adding a store.
|
||||
fn scanner_defs() -> Vec<(&'static str, &'static str)> {
|
||||
let mut defs = vec![("steam", "Steam")];
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
defs.push(("lutris", "Lutris"));
|
||||
defs.push(("heroic", "Heroic (Epic / GOG / Amazon)"));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
defs.push(("epic", "Epic Games Launcher"));
|
||||
defs.push(("gog", "GOG Galaxy"));
|
||||
defs.push(("xbox", "Xbox / Game Pass"));
|
||||
}
|
||||
defs
|
||||
}
|
||||
/// Display names for the stores that used to have a built-in scanner, so a source keeps the label
|
||||
/// the operator has been toggling for releases instead of renaming itself to a bare id the day its
|
||||
/// plugin takes over. Anything not listed (rom-manager, playnite, a third-party provider) falls back
|
||||
/// to its own id, which is what those sources have always shown.
|
||||
const STORE_LABELS: &[(&str, &str)] = &[
|
||||
("steam", "Steam"),
|
||||
("lutris", "Lutris"),
|
||||
("heroic", "Heroic (Epic / GOG / Amazon)"),
|
||||
("epic", "Epic Games Launcher"),
|
||||
("gog", "GOG Galaxy"),
|
||||
("xbox", "Xbox / Game Pass"),
|
||||
];
|
||||
|
||||
/// Persisted shape (`library-scanners.json`): only the ids the operator turned OFF. Absent file =
|
||||
/// nothing disabled = the pre-existing all-scanners-on behavior.
|
||||
@@ -104,49 +110,26 @@ fn save_settings(settings: &ScannerSettings) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The disabled-scanner ids, loaded once per library read ([`all_games`] consults it per store).
|
||||
/// The disabled source ids, loaded once per library read ([`all_games`] filters each entry on it).
|
||||
pub(crate) fn disabled_scanners() -> HashSet<String> {
|
||||
load_settings().disabled.into_iter().collect()
|
||||
}
|
||||
|
||||
/// Every game source on this host with its current enable state (WP2.6):
|
||||
///
|
||||
/// 1. the built-in scanners this build compiled in, **minus** any whose store a plugin has claimed
|
||||
/// (the plugin replaces it, so showing both would offer two toggles for one thing);
|
||||
/// 2. the claimed stores themselves, as plugin sources;
|
||||
/// 3. any other provider that has entries — the *emergent* case (rom-manager, playnite), which has
|
||||
/// never had a toggle before and gets one for free here.
|
||||
/// 1. every **claimed store** — a library plugin that took a store's id, so its entries surface as
|
||||
/// `steam:570` rather than `custom:<opaque>`;
|
||||
/// 2. every other provider that has entries — the *emergent* case (rom-manager, playnite), which
|
||||
/// never claimed a store but still owns a set of titles the operator may want to switch off.
|
||||
///
|
||||
/// Built-ins keep their fixed definition order (stable for the console); plugin sources follow,
|
||||
/// sorted by id.
|
||||
/// Sorted by id, which is a stable order for the console. This used to lead with the built-in
|
||||
/// scanners compiled into the host, minus any store a plugin had claimed out from under them; with
|
||||
/// the scanners gone the subtraction has nothing left to subtract and the list is plugins only.
|
||||
pub fn list_scanners() -> Vec<ScannerInfo> {
|
||||
let off = disabled_scanners();
|
||||
let claims = crate::library::claimed_stores();
|
||||
let entries = crate::library::load_custom();
|
||||
|
||||
let mut out: Vec<ScannerInfo> = scanner_defs()
|
||||
.into_iter()
|
||||
.filter(|(id, _)| !claims.contains_key(*id))
|
||||
.map(|(id, label)| ScannerInfo {
|
||||
id: id.to_string(),
|
||||
label: label.to_string(),
|
||||
enabled: !off.contains(id),
|
||||
origin: SourceOrigin::Builtin,
|
||||
provider: None,
|
||||
entries: None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
// A claimed store shows under the SCANNER's label where we know one, so the row a user has been
|
||||
// toggling for releases doesn't rename itself out from under them mid-migration.
|
||||
let label_for = |id: &str| {
|
||||
scanner_defs()
|
||||
.into_iter()
|
||||
.find(|(sid, _)| *sid == id)
|
||||
.map(|(_, label)| label.to_string())
|
||||
.unwrap_or_else(|| id.to_string())
|
||||
};
|
||||
|
||||
let mut plugin_ids: Vec<(String, String)> = claims
|
||||
.iter()
|
||||
.map(|(store, provider)| (store.clone(), provider.clone()))
|
||||
@@ -163,27 +146,43 @@ pub fn list_scanners() -> Vec<ScannerInfo> {
|
||||
plugin_ids.sort();
|
||||
plugin_ids.dedup();
|
||||
|
||||
out.extend(plugin_ids.into_iter().map(|(id, provider)| {
|
||||
let count = entries
|
||||
.iter()
|
||||
.filter(|e| crate::library::source_id_for(e) == Some(id.as_str()))
|
||||
.count();
|
||||
ScannerInfo {
|
||||
label: label_for(&id),
|
||||
enabled: !off.contains(&id),
|
||||
origin: SourceOrigin::Plugin,
|
||||
provider: Some(provider),
|
||||
entries: Some(count),
|
||||
id,
|
||||
}
|
||||
}));
|
||||
out
|
||||
plugin_ids
|
||||
.into_iter()
|
||||
.map(|(id, provider)| {
|
||||
let count = entries
|
||||
.iter()
|
||||
.filter(|e| crate::library::source_id_for(e) == Some(id.as_str()))
|
||||
.count();
|
||||
ScannerInfo {
|
||||
label: store_label(&id),
|
||||
enabled: !off.contains(&id),
|
||||
origin: SourceOrigin::Plugin,
|
||||
provider: Some(provider),
|
||||
entries: Some(count),
|
||||
id,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `id` names a source that exists on this host right now — a compiled-in scanner, a claimed
|
||||
/// store, or a provider with entries. The toggle accepts exactly these (an unknown id still 404s).
|
||||
/// A source's display name — see [`STORE_LABELS`]; its own id when we know no nicer name.
|
||||
fn store_label(id: &str) -> String {
|
||||
STORE_LABELS
|
||||
.iter()
|
||||
.find(|(sid, _)| *sid == id)
|
||||
.map(|(_, label)| (*label).to_string())
|
||||
.unwrap_or_else(|| id.to_string())
|
||||
}
|
||||
|
||||
/// Whether `id` names a source that exists on this host right now — a claimed store or a provider
|
||||
/// with entries. The toggle accepts exactly these (an unknown id still 404s).
|
||||
///
|
||||
/// Note this is now strictly "a source that is really here". While the built-ins existed it also
|
||||
/// accepted any compiled-in scanner id, which was the same thing for them; a plugin that has never
|
||||
/// reconciled has no entries and no claim, so there is nothing to toggle and 404 is the honest
|
||||
/// answer.
|
||||
fn is_known_source(id: &str) -> bool {
|
||||
scanner_defs().iter().any(|(sid, _)| *sid == id) || list_scanners().iter().any(|s| s.id == id)
|
||||
list_scanners().iter().any(|s| s.id == id)
|
||||
}
|
||||
|
||||
/// Enable/disable one source. `None` when `id` names no source on this host (the mgmt layer maps
|
||||
@@ -221,14 +220,19 @@ pub fn set_scanner_enabled(id: &str, enabled: bool) -> Result<Option<Vec<Scanner
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The label table is what keeps a source row named "Steam" instead of "steam" now that the
|
||||
/// scanner which used to supply that name is gone. Pin both halves: the ids are unique, and an
|
||||
/// id we know nothing about degrades to itself rather than to an empty or panicking label.
|
||||
#[test]
|
||||
fn steam_is_always_a_scanner_and_ids_are_unique() {
|
||||
let defs = scanner_defs();
|
||||
assert!(defs.iter().any(|(id, _)| *id == "steam"));
|
||||
let ids: HashSet<_> = defs.iter().map(|(id, _)| *id).collect();
|
||||
assert_eq!(ids.len(), defs.len(), "scanner ids must be unique");
|
||||
// `custom` is a store but never a scanner — the toggle surface must not offer it.
|
||||
fn store_labels_are_unique_and_unknown_ids_degrade_to_themselves() {
|
||||
let ids: HashSet<_> = STORE_LABELS.iter().map(|(id, _)| *id).collect();
|
||||
assert_eq!(ids.len(), STORE_LABELS.len(), "source ids must be unique");
|
||||
// `custom` is a store but never a source — the toggle surface must not offer it.
|
||||
assert!(!ids.contains("custom"));
|
||||
|
||||
assert_eq!(store_label("steam"), "Steam");
|
||||
assert_eq!(store_label("rom-manager"), "rom-manager");
|
||||
assert_eq!(store_label(""), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,812 +0,0 @@
|
||||
//! Steam store provider: installed-title scan (local `libraryfolders.vdf` + app manifests, no
|
||||
//! API key) and Steam-CDN / local-`librarycache` artwork. Split out of the `library` facade (plan §W5).
|
||||
|
||||
use super::art::fetch_image;
|
||||
use super::*;
|
||||
|
||||
/// Reads the **local** Steam install — no Steam Web API key, no network. Installed titles come
|
||||
/// from `steamapps/appmanifest_<appid>.acf`; extra library folders from
|
||||
/// `steamapps/libraryfolders.vdf`; the user's own non-Steam shortcuts ("Add a Non-Steam Game to My
|
||||
/// Library") from each account's binary `userdata/<id>/config/shortcuts.vdf`; artwork from the
|
||||
/// public Steam CDN by appid, or the user's per-account `grid/` overrides (all a shortcut ever has).
|
||||
pub struct SteamProvider;
|
||||
|
||||
impl LibraryProvider for SteamProvider {
|
||||
fn store(&self) -> &'static str {
|
||||
"steam"
|
||||
}
|
||||
|
||||
fn list(&self) -> Vec<GameEntry> {
|
||||
let mut by_appid: std::collections::BTreeMap<u32, Installed> = Default::default();
|
||||
for steamapps in steam_library_dirs() {
|
||||
for app in scan_manifests(&steamapps) {
|
||||
// First library wins; dedups appids present in several libraries.
|
||||
by_appid.entry(app.appid).or_insert(app);
|
||||
}
|
||||
}
|
||||
let mut games: Vec<GameEntry> = by_appid
|
||||
.into_values()
|
||||
.filter(|app| !is_steam_tool(app.appid, &app.name))
|
||||
.map(|app| GameEntry {
|
||||
provider: None,
|
||||
role: GameRole::Game,
|
||||
icon: None,
|
||||
meta: GameMeta::pc(),
|
||||
id: format!("steam:{}", app.appid),
|
||||
store: "steam".into(),
|
||||
art: steam_art(app.appid),
|
||||
launch: Some(LaunchSpec {
|
||||
kind: "steam_appid".into(),
|
||||
value: app.appid.to_string(),
|
||||
}),
|
||||
// The appid alone is authoritative on Linux (Steam's launch reaper); the install dir
|
||||
// is what the Windows matcher — which has no reaper to watch — keys off instead.
|
||||
detect: match app.install_dir {
|
||||
Some(dir) => DetectSpec::steam(app.appid).with_dir(dir),
|
||||
None => DetectSpec::steam(app.appid),
|
||||
},
|
||||
title: app.name,
|
||||
})
|
||||
.collect();
|
||||
// Non-Steam shortcuts have no `appmanifest` — [`scan_manifests`] can't see them, so the
|
||||
// user's own custom entries are gathered separately from `shortcuts.vdf`.
|
||||
games.extend(steam_shortcuts());
|
||||
games
|
||||
}
|
||||
}
|
||||
|
||||
/// The Steam CDN poster/hero/logo/header for an appid — relative proxy paths the *client* resolves
|
||||
/// against the host it just talked to (so they work the same whichever interface/port the client
|
||||
/// reached the host on), backed by [`steam_art_bytes`] on the way out. Not every appid has a
|
||||
/// 600×900 capsule, but `header.jpg` is effectively universal — the client falls back to it.
|
||||
fn steam_art(appid: u32) -> Artwork {
|
||||
let url = |kind: &str| Some(format!("/api/v1/library/art/steam:{appid}/{kind}"));
|
||||
Artwork {
|
||||
portrait: url("portrait"),
|
||||
hero: url("hero"),
|
||||
logo: url("logo"),
|
||||
header: url("header"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve one Steam cover-art kind to bytes: the host's own local Steam cache first (exact — it's
|
||||
/// literally what the user's Steam client already shows for this title), then the user's per-account
|
||||
/// `grid/` overrides (the *only* art a non-Steam shortcut ever has), then the legacy flat CDN URL.
|
||||
/// `None` when none has it (the client then falls through to its next art candidate). Blocking
|
||||
/// (disk + network) — call off the async runtime.
|
||||
pub fn steam_art_bytes(appid: u32, kind: ArtKind) -> Option<(Vec<u8>, String)> {
|
||||
if let Some(local) =
|
||||
steam_local_art_bytes(appid, kind).or_else(|| steam_grid_art_bytes(appid, kind))
|
||||
{
|
||||
return Some(local);
|
||||
}
|
||||
// A non-Steam shortcut's appid has the high bit set (see [`shortcut_appid`]) and is never a real
|
||||
// store appid, so the CDN would only 404 — skip the wasted request and fall through cleanly.
|
||||
if appid & 0x8000_0000 != 0 {
|
||||
return None;
|
||||
}
|
||||
let url = format!(
|
||||
"https://cdn.cloudflare.steamstatic.com/steam/apps/{appid}/{}",
|
||||
kind.cdn_filename()
|
||||
);
|
||||
fetch_image(&url)
|
||||
}
|
||||
|
||||
/// Cap on a local librarycache file we'll read into memory — generous for a Steam-quality JPEG/PNG
|
||||
/// (these run well under 2 MiB in practice) while bounding a pathological file.
|
||||
const LOCAL_ART_MAX_BYTES: u64 = 8 * 1024 * 1024;
|
||||
|
||||
/// `appcache/librarycache/<appid>/<hash>/<filename>` across every Steam root, for whichever
|
||||
/// `<hash>` subdirectory actually has this kind's file (Steam reuses one hash dir per asset
|
||||
/// version, so there's normally exactly one candidate per kind).
|
||||
fn steam_local_art_bytes(appid: u32, kind: ArtKind) -> Option<(Vec<u8>, String)> {
|
||||
steam_roots()
|
||||
.into_iter()
|
||||
.find_map(|root| find_local_art_file(&root, appid, kind))
|
||||
.and_then(|path| {
|
||||
let bytes = std::fs::read(&path).ok()?;
|
||||
let ctype = if path.extension().is_some_and(|e| e == "png") {
|
||||
"image/png"
|
||||
} else {
|
||||
"image/jpeg"
|
||||
};
|
||||
Some((bytes, ctype.to_string()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Find this kind's cached file under one Steam root's `appcache/librarycache/<appid>/<hash>/`,
|
||||
/// trying each hash subdirectory (normally just one) and each candidate filename in priority
|
||||
/// order. Pure path lookup — no env/HOME dependency — so it's unit-testable against a plain
|
||||
/// directory fixture.
|
||||
fn find_local_art_file(root: &Path, appid: u32, kind: ArtKind) -> Option<PathBuf> {
|
||||
let cache_dir = root
|
||||
.join("appcache")
|
||||
.join("librarycache")
|
||||
.join(appid.to_string());
|
||||
let hash_dirs = std::fs::read_dir(&cache_dir).ok()?;
|
||||
for hash_dir in hash_dirs.flatten() {
|
||||
for name in kind.local_filenames() {
|
||||
let path = hash_dir.path().join(name);
|
||||
let Ok(meta) = std::fs::metadata(&path) else {
|
||||
continue;
|
||||
};
|
||||
if meta.len() > 0 && meta.len() <= LOCAL_ART_MAX_BYTES {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Artwork a user set in Steam itself for a **non-Steam shortcut** (or a `grid/` override for a real
|
||||
/// title), stored per-account under `userdata/<id>/config/grid/`, keyed by the same 32-bit appid the
|
||||
/// shortcut carries. Tried before the CDN — a shortcut has no CDN art at all, so this is where its
|
||||
/// poster lives.
|
||||
fn steam_grid_art_bytes(appid: u32, kind: ArtKind) -> Option<(Vec<u8>, String)> {
|
||||
for root in steam_roots() {
|
||||
let Ok(users) = std::fs::read_dir(root.join("userdata")) else {
|
||||
continue;
|
||||
};
|
||||
for user in users.flatten() {
|
||||
let grid = user.path().join("config").join("grid");
|
||||
if let Some(path) = find_grid_art_file(&grid, appid, kind) {
|
||||
if let Ok(bytes) = std::fs::read(&path) {
|
||||
let ctype = if path.extension().is_some_and(|e| e == "png") {
|
||||
"image/png"
|
||||
} else {
|
||||
"image/jpeg"
|
||||
};
|
||||
return Some((bytes, ctype.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The `grid/` filenames Steam stores this art kind under for appid `<A>`, tried in order (PNG then
|
||||
/// JPG — Steam accepts either). Pure path logic, so it's unit-testable against a directory fixture.
|
||||
fn find_grid_art_file(grid: &Path, appid: u32, kind: ArtKind) -> Option<PathBuf> {
|
||||
for name in grid_filenames(kind, appid) {
|
||||
let path = grid.join(&name);
|
||||
if let Ok(meta) = std::fs::metadata(&path) {
|
||||
if meta.len() > 0 && meta.len() <= LOCAL_ART_MAX_BYTES {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The `userdata/<id>/config/grid/` basenames Steam names each art kind under for appid `<A>`:
|
||||
/// portrait `<A>p`, hero `<A>_hero`, logo `<A>_logo`, and the wide capsule `<A>` — each as `.png`
|
||||
/// then `.jpg`.
|
||||
fn grid_filenames(kind: ArtKind, appid: u32) -> Vec<String> {
|
||||
let both = |base: String| vec![format!("{base}.png"), format!("{base}.jpg")];
|
||||
match kind {
|
||||
ArtKind::Portrait => both(format!("{appid}p")),
|
||||
ArtKind::Hero => both(format!("{appid}_hero")),
|
||||
ArtKind::Logo => both(format!("{appid}_logo")),
|
||||
ArtKind::Header => both(format!("{appid}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Candidate Steam roots (classic, Flatpak, Deck) that actually exist, canonicalized + deduped.
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn steam_roots() -> Vec<PathBuf> {
|
||||
let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let candidates = [
|
||||
home.join(".local/share/Steam"),
|
||||
home.join(".steam/steam"),
|
||||
home.join(".steam/root"),
|
||||
home.join(".var/app/com.valvesoftware.Steam/.local/share/Steam"), // Flatpak Steam
|
||||
];
|
||||
steam_roots_existing(candidates)
|
||||
}
|
||||
|
||||
/// Windows Steam roots: the default install dirs under Program Files. Games installed on other
|
||||
/// drives are still found via each root's `libraryfolders.vdf` (see [`steam_library_dirs`]). A
|
||||
/// non-default Steam install dir (registry `Valve\Steam\InstallPath`) isn't covered yet.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn steam_roots() -> Vec<PathBuf> {
|
||||
let mut candidates = Vec::new();
|
||||
for var in ["ProgramFiles(x86)", "ProgramFiles", "ProgramW6432"] {
|
||||
if let Some(pf) = std::env::var_os(var) {
|
||||
candidates.push(PathBuf::from(pf).join("Steam"));
|
||||
}
|
||||
}
|
||||
steam_roots_existing(candidates)
|
||||
}
|
||||
|
||||
/// Keep only the candidate roots that exist (have a `steamapps` dir), canonicalized + deduped.
|
||||
fn steam_roots_existing(candidates: impl IntoIterator<Item = PathBuf>) -> Vec<PathBuf> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut roots = Vec::new();
|
||||
for c in candidates {
|
||||
if let Ok(canon) = c.canonicalize() {
|
||||
if canon.join("steamapps").is_dir() && seen.insert(canon.clone()) {
|
||||
roots.push(canon);
|
||||
}
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
/// Every `steamapps` dir holding installed titles: each root's own, plus the extra library
|
||||
/// folders listed in `libraryfolders.vdf` (Steam lets you install games on other drives).
|
||||
fn steam_library_dirs() -> Vec<PathBuf> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut dirs = Vec::new();
|
||||
let mut push = |steamapps: PathBuf, dirs: &mut Vec<PathBuf>| {
|
||||
if let Ok(canon) = steamapps.canonicalize() {
|
||||
if canon.is_dir() && seen.insert(canon.clone()) {
|
||||
dirs.push(canon);
|
||||
}
|
||||
}
|
||||
};
|
||||
for root in steam_roots() {
|
||||
let steamapps = root.join("steamapps");
|
||||
if let Ok(text) = std::fs::read_to_string(steamapps.join("libraryfolders.vdf")) {
|
||||
for path in vdf_paths(&text) {
|
||||
push(PathBuf::from(path).join("steamapps"), &mut dirs);
|
||||
}
|
||||
}
|
||||
push(steamapps, &mut dirs);
|
||||
}
|
||||
dirs
|
||||
}
|
||||
|
||||
/// Pull every `"path" "<dir>"` value out of a `libraryfolders.vdf`. We don't need a full VDF
|
||||
/// parser for the two flat fields we read. On Windows the values are backslash-escaped
|
||||
/// (`D:\\SteamLibrary`), so unescape `\\` → `\`; Linux paths need no unescaping.
|
||||
fn vdf_paths(text: &str) -> Vec<String> {
|
||||
text.lines()
|
||||
.filter_map(|l| vdf_value(l.trim(), "path"))
|
||||
.map(|p| {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
p.replace("\\\\", "\\")
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
p.to_string()
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `"<key>" "<value>"` on a single line → `<value>`. Used for both VDF and ACF flat fields.
|
||||
fn vdf_value<'a>(line: &'a str, key: &str) -> Option<&'a str> {
|
||||
let rest = line.strip_prefix(&format!("\"{key}\""))?;
|
||||
let after = &rest[rest.find('"')? + 1..];
|
||||
Some(&after[..after.find('"')?])
|
||||
}
|
||||
|
||||
/// One installed Steam title, as read from its `appmanifest_<appid>.acf`.
|
||||
struct Installed {
|
||||
appid: u32,
|
||||
name: String,
|
||||
/// `<steamapps>/common/<installdir>`, when the manifest names one and it exists on disk — the
|
||||
/// game's own files, used to recognize its processes ([`DetectSpec::install_dir`]).
|
||||
install_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// Scan a `steamapps` dir for `appmanifest_*.acf` files → the installed titles it describes.
|
||||
fn scan_manifests(steamapps: &Path) -> Vec<Installed> {
|
||||
let Ok(rd) = std::fs::read_dir(steamapps) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for entry in rd.flatten() {
|
||||
let fname = entry.file_name();
|
||||
let fname = fname.to_string_lossy();
|
||||
if !(fname.starts_with("appmanifest_") && fname.ends_with(".acf")) {
|
||||
continue;
|
||||
}
|
||||
if let Ok(text) = std::fs::read_to_string(entry.path()) {
|
||||
let appid = text.lines().find_map(|l| vdf_value(l.trim(), "appid"));
|
||||
let name = text.lines().find_map(|l| vdf_value(l.trim(), "name"));
|
||||
if let (Some(Ok(appid)), Some(name)) = (appid.map(str::parse::<u32>), name) {
|
||||
// `installdir` is a bare folder name relative to this library's `common/`.
|
||||
let install_dir = text
|
||||
.lines()
|
||||
.find_map(|l| vdf_value(l.trim(), "installdir"))
|
||||
.map(|d| steamapps.join("common").join(d))
|
||||
.filter(|p| p.is_dir());
|
||||
out.push(Installed {
|
||||
appid,
|
||||
name: name.to_string(),
|
||||
install_dir,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Steam installs runtimes/redistributables as "apps" too — keep them out of a *game* library.
|
||||
fn is_steam_tool(appid: u32, name: &str) -> bool {
|
||||
// Steamworks Common Redistributables; Steam Linux Runtime 1.0/2.0/3.0 (Sniper/Soldier).
|
||||
const TOOL_IDS: &[u32] = &[228980, 1070560, 1391110, 1628350, 1493710];
|
||||
if TOOL_IDS.contains(&appid) {
|
||||
return true;
|
||||
}
|
||||
let n = name.to_ascii_lowercase();
|
||||
n.contains("proton")
|
||||
|| n.starts_with("steam linux runtime")
|
||||
|| n.contains("steamworks common")
|
||||
|| n.contains("steamvr")
|
||||
}
|
||||
|
||||
/// One non-Steam shortcut ("Add a Non-Steam Game to My Library"), as read from `shortcuts.vdf`.
|
||||
struct Shortcut {
|
||||
/// The 32-bit shortcut appid Steam assigns it (high bit set — see [`shortcut_appid`]). Keys the
|
||||
/// entry id and its `grid/` artwork; the 64-bit launch id derives from it ([`shortcut_gameid`]).
|
||||
appid: u32,
|
||||
/// Display name (`AppName`).
|
||||
name: String,
|
||||
/// The shortcut's target (`Exe`), as stored — Steam quotes it. This *is* the game (a shortcut
|
||||
/// points straight at it, with no launcher in between), so it doubles as the detect signal.
|
||||
exe: String,
|
||||
/// Whether Steam has this shortcut hidden from the library (`IsHidden`) — we honor that.
|
||||
hidden: bool,
|
||||
}
|
||||
|
||||
/// Every non-Steam shortcut across all Steam accounts on this host, as launchable [`GameEntry`]s.
|
||||
/// These carry no `appmanifest`, so [`scan_manifests`] never sees them — this is the only path that
|
||||
/// surfaces a user's custom Steam entries. Best-effort: an unreadable/absent `shortcuts.vdf`
|
||||
/// contributes nothing; hidden shortcuts and duplicate appids are dropped.
|
||||
fn steam_shortcuts() -> Vec<GameEntry> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut out = Vec::new();
|
||||
for path in shortcuts_files() {
|
||||
let Ok(bytes) = std::fs::read(&path) else {
|
||||
continue;
|
||||
};
|
||||
for sc in parse_shortcuts(&bytes) {
|
||||
if seen.insert(sc.appid) {
|
||||
if let Some(entry) = shortcut_entry(sc) {
|
||||
out.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Map one parsed [`Shortcut`] to a library entry, or `None` if Steam has it hidden. Launch reuses
|
||||
/// the `steam_appid` recipe (`steam steam://rungameid/<id>`) — the value is the 64-bit shortcut
|
||||
/// game id, not the 32-bit appid, because the plain appid won't launch a non-Steam shortcut.
|
||||
fn shortcut_entry(sc: Shortcut) -> Option<GameEntry> {
|
||||
if sc.hidden {
|
||||
return None;
|
||||
}
|
||||
Some(GameEntry {
|
||||
provider: None,
|
||||
role: GameRole::Game,
|
||||
icon: None,
|
||||
meta: GameMeta::pc(),
|
||||
id: format!("steam:{}", sc.appid),
|
||||
store: "steam".into(),
|
||||
title: sc.name,
|
||||
art: steam_art(sc.appid),
|
||||
launch: Some(LaunchSpec {
|
||||
kind: "steam_appid".into(),
|
||||
value: shortcut_gameid(sc.appid).to_string(),
|
||||
}),
|
||||
detect: shortcut_detect(&sc.exe),
|
||||
})
|
||||
}
|
||||
|
||||
/// Detect signals for a non-Steam shortcut: its `Exe` target is the game itself, so the executable
|
||||
/// (and its folder, which catches a launcher script that execs a sibling binary) identifies it. Steam
|
||||
/// stores the target quoted and may include trailing arguments; only an existing absolute path is
|
||||
/// asserted — a guess would be worse than no tracking at all.
|
||||
fn shortcut_detect(exe: &str) -> DetectSpec {
|
||||
let mut spec = crate::library::spec_from_command(exe);
|
||||
if let Some(dir) = spec.exe.as_deref().and_then(Path::parent) {
|
||||
spec.install_dir = Some(dir.to_path_buf());
|
||||
}
|
||||
spec
|
||||
}
|
||||
|
||||
/// Every `userdata/<id>/config/shortcuts.vdf` under each Steam root — one file per Steam account
|
||||
/// that has signed in on this host.
|
||||
fn shortcuts_files() -> Vec<PathBuf> {
|
||||
let mut files = Vec::new();
|
||||
for root in steam_roots() {
|
||||
let Ok(users) = std::fs::read_dir(root.join("userdata")) else {
|
||||
continue;
|
||||
};
|
||||
for user in users.flatten() {
|
||||
let path = user.path().join("config").join("shortcuts.vdf");
|
||||
if path.is_file() {
|
||||
files.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
files
|
||||
}
|
||||
|
||||
// `shortcut_gameid` (the 64-bit `rungameid` composition) moved to `launch.rs` (WP1.1) — it is launch
|
||||
// vocabulary; this module only reads the 32-bit appid out of `shortcuts.vdf`.
|
||||
|
||||
/// The 32-bit appid Steam derives for a shortcut from its target+name — `crc32(exe + name)` with the
|
||||
/// high bit set. Only used when `shortcuts.vdf` omits the stored `appid` (very old Steam); modern
|
||||
/// Steam writes it, and we prefer the stored value.
|
||||
fn shortcut_appid(exe: &str, name: &str) -> u32 {
|
||||
crc32(format!("{exe}{name}").as_bytes()) | 0x8000_0000
|
||||
}
|
||||
|
||||
/// Standard reflected (IEEE) CRC-32 — a few short strings' worth per scan, so a table-free bitwise
|
||||
/// loop is plenty. Matches what Steam uses to hash a shortcut's `exe + name`.
|
||||
fn crc32(data: &[u8]) -> u32 {
|
||||
let mut crc: u32 = 0xFFFF_FFFF;
|
||||
for &byte in data {
|
||||
crc ^= byte as u32;
|
||||
for _ in 0..8 {
|
||||
let mask = (crc & 1).wrapping_neg();
|
||||
crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
|
||||
}
|
||||
}
|
||||
!crc
|
||||
}
|
||||
|
||||
/// Parse a **binary** `shortcuts.vdf` into its shortcuts. The format is Steam's binary KeyValues: a
|
||||
/// 1-byte type tag (`0x00` nested map, `0x01` string, `0x02` int32), a NUL-terminated key, then a
|
||||
/// type-specific payload; `0x08` closes the current map. The whole file is one `shortcuts` map whose
|
||||
/// children (keyed `"0"`, `"1"`, …) are the individual shortcuts. Lenient and panic-free: a
|
||||
/// truncated file or an unrecognized tag stops the walk and returns whatever parsed so far.
|
||||
fn parse_shortcuts(buf: &[u8]) -> Vec<Shortcut> {
|
||||
let mut out = Vec::new();
|
||||
let mut pos = 0usize;
|
||||
// Enter the top-level map (`<0x00> "shortcuts" <NUL>`); tolerate any key name.
|
||||
if buf.first() != Some(&0x00) {
|
||||
return out;
|
||||
}
|
||||
pos += 1;
|
||||
if read_cstr(buf, &mut pos).is_none() {
|
||||
return out;
|
||||
}
|
||||
// Each child is a map describing one shortcut, until the map-closing `0x08`.
|
||||
while let Some(&tag) = buf.get(pos) {
|
||||
pos += 1;
|
||||
if tag != 0x00 {
|
||||
break; // `0x08` (end of shortcuts) or anything unexpected
|
||||
}
|
||||
if read_cstr(buf, &mut pos).is_none() {
|
||||
break; // the index key ("0", "1", …)
|
||||
}
|
||||
match parse_one_shortcut(buf, &mut pos) {
|
||||
Some(sc) => out.push(sc),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Parse one shortcut's fields (positioned just after its index key) up to the map-closing `0x08`,
|
||||
/// pulling the ones we surface. `None` on a truncated/garbled entry.
|
||||
fn parse_one_shortcut(buf: &[u8], pos: &mut usize) -> Option<Shortcut> {
|
||||
let mut appid: Option<u32> = None;
|
||||
let mut name = String::new();
|
||||
let mut exe = String::new();
|
||||
let mut hidden = false;
|
||||
loop {
|
||||
let tag = *buf.get(*pos)?;
|
||||
*pos += 1;
|
||||
if tag == 0x08 {
|
||||
break; // end of this shortcut
|
||||
}
|
||||
let key = read_cstr(buf, pos)?.to_ascii_lowercase();
|
||||
match tag {
|
||||
0x00 => skip_map(buf, pos)?, // nested map (e.g. `tags`) — not needed
|
||||
0x01 => {
|
||||
let val = read_cstr(buf, pos)?;
|
||||
match key.as_str() {
|
||||
"appname" => name = val,
|
||||
"exe" => exe = val,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
0x02 => {
|
||||
let val = read_i32(buf, pos)?;
|
||||
match key.as_str() {
|
||||
"appid" => appid = Some(val as u32),
|
||||
"ishidden" => hidden = val != 0,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
0x07 => *pos += 8, // uint64 — skip
|
||||
_ => return None, // unknown tag: payload size unknown, can't continue safely
|
||||
}
|
||||
}
|
||||
if name.trim().is_empty() {
|
||||
return None; // nothing worth showing
|
||||
}
|
||||
// Prefer the stored appid; fall back to Steam's derivation when it's absent (0 / missing).
|
||||
let appid = appid
|
||||
.filter(|a| *a != 0)
|
||||
.unwrap_or_else(|| shortcut_appid(&exe, &name));
|
||||
Some(Shortcut {
|
||||
appid,
|
||||
name,
|
||||
exe,
|
||||
hidden,
|
||||
})
|
||||
}
|
||||
|
||||
/// Skip a nested map's contents (positioned just after its key) up to and including its `0x08`.
|
||||
fn skip_map(buf: &[u8], pos: &mut usize) -> Option<()> {
|
||||
loop {
|
||||
let tag = *buf.get(*pos)?;
|
||||
*pos += 1;
|
||||
if tag == 0x08 {
|
||||
return Some(());
|
||||
}
|
||||
read_cstr(buf, pos)?; // key
|
||||
match tag {
|
||||
0x00 => skip_map(buf, pos)?,
|
||||
0x01 => {
|
||||
read_cstr(buf, pos)?;
|
||||
}
|
||||
0x02 => *pos += 4,
|
||||
0x07 => *pos += 8,
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a NUL-terminated UTF-8 string (lossy) starting at `pos`, advancing past the terminator.
|
||||
/// `None` if the buffer ends before a NUL.
|
||||
fn read_cstr(buf: &[u8], pos: &mut usize) -> Option<String> {
|
||||
let start = *pos;
|
||||
let end = buf.get(start..)?.iter().position(|&b| b == 0)? + start;
|
||||
let s = String::from_utf8_lossy(&buf[start..end]).into_owned();
|
||||
*pos = end + 1;
|
||||
Some(s)
|
||||
}
|
||||
|
||||
/// Read a little-endian int32 at `pos`, advancing 4 bytes. `None` if fewer than 4 bytes remain.
|
||||
fn read_i32(buf: &[u8], pos: &mut usize) -> Option<i32> {
|
||||
let bytes: [u8; 4] = buf.get(*pos..*pos + 4)?.try_into().ok()?;
|
||||
*pos += 4;
|
||||
Some(i32::from_le_bytes(bytes))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn vdf_value_extracts_quoted_field() {
|
||||
assert_eq!(
|
||||
vdf_value("\"path\"\t\t\"/mnt/games/SteamLibrary\"", "path"),
|
||||
Some("/mnt/games/SteamLibrary")
|
||||
);
|
||||
assert_eq!(vdf_value("\"appid\"\t\t\"570\"", "appid"), Some("570"));
|
||||
assert_eq!(vdf_value("\"name\"\t\t\"Dota 2\"", "name"), Some("Dota 2"));
|
||||
assert_eq!(vdf_value("\"installdir\"\t\t\"x\"", "appid"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vdf_paths_pulls_all_library_folders() {
|
||||
let vdf = r#"
|
||||
"libraryfolders"
|
||||
{
|
||||
"0"
|
||||
{
|
||||
"path" "/home/u/.local/share/Steam"
|
||||
"apps" { "570" "123" }
|
||||
}
|
||||
"1"
|
||||
{
|
||||
"path" "/mnt/ssd/SteamLibrary"
|
||||
}
|
||||
}
|
||||
"#;
|
||||
assert_eq!(
|
||||
vdf_paths(vdf),
|
||||
vec![
|
||||
"/home/u/.local/share/Steam".to_string(),
|
||||
"/mnt/ssd/SteamLibrary".to_string()
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tools_are_filtered_but_games_kept() {
|
||||
assert!(is_steam_tool(228980, "Steamworks Common Redistributables"));
|
||||
assert!(is_steam_tool(1493710, "Proton Experimental"));
|
||||
assert!(is_steam_tool(0, "Steam Linux Runtime 3.0 (sniper)"));
|
||||
assert!(!is_steam_tool(570, "Dota 2"));
|
||||
assert!(!is_steam_tool(1245620, "ELDEN RING"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steam_art_points_at_the_host_art_proxy() {
|
||||
let art = steam_art(570);
|
||||
assert_eq!(
|
||||
art.portrait.as_deref(),
|
||||
Some("/api/v1/library/art/steam:570/portrait")
|
||||
);
|
||||
assert_eq!(
|
||||
art.header.as_deref(),
|
||||
Some("/api/v1/library/art/steam:570/header")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_local_art_file_matches_the_hashed_librarycache_layout() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cache = dir
|
||||
.path()
|
||||
.join("appcache/librarycache/3527290/480bd879ac737921bfa2529a6fea15961267ad21");
|
||||
std::fs::create_dir_all(&cache).unwrap();
|
||||
std::fs::write(cache.join("library_600x900.jpg"), b"not really a jpeg").unwrap();
|
||||
|
||||
let found = find_local_art_file(dir.path(), 3527290, ArtKind::Portrait).unwrap();
|
||||
assert_eq!(found, cache.join("library_600x900.jpg"));
|
||||
// A kind with no cached file, and an appid with no cache dir at all, both miss cleanly.
|
||||
assert_eq!(
|
||||
find_local_art_file(dir.path(), 3527290, ArtKind::Hero),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
find_local_art_file(dir.path(), 570, ArtKind::Portrait),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_local_art_file_prefers_the_2x_portrait() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cache = dir.path().join("appcache/librarycache/570/somehash");
|
||||
std::fs::create_dir_all(&cache).unwrap();
|
||||
std::fs::write(cache.join("library_600x900.jpg"), b"1x").unwrap();
|
||||
std::fs::write(cache.join("library_600x900_2x.jpg"), b"2x").unwrap();
|
||||
|
||||
let found = find_local_art_file(dir.path(), 570, ArtKind::Portrait).unwrap();
|
||||
assert_eq!(found, cache.join("library_600x900_2x.jpg"));
|
||||
}
|
||||
|
||||
// --- Non-Steam shortcuts (custom Steam entries) ---
|
||||
|
||||
/// Build one binary-VDF field for a test `shortcuts.vdf`.
|
||||
fn field_str(key: &str, val: &str) -> Vec<u8> {
|
||||
let mut v = vec![0x01u8];
|
||||
v.extend_from_slice(key.as_bytes());
|
||||
v.push(0);
|
||||
v.extend_from_slice(val.as_bytes());
|
||||
v.push(0);
|
||||
v
|
||||
}
|
||||
fn field_i32(key: &str, val: i32) -> Vec<u8> {
|
||||
let mut v = vec![0x02u8];
|
||||
v.extend_from_slice(key.as_bytes());
|
||||
v.push(0);
|
||||
v.extend_from_slice(&val.to_le_bytes());
|
||||
v
|
||||
}
|
||||
fn map_open(key: &str) -> Vec<u8> {
|
||||
let mut v = vec![0x00u8];
|
||||
v.extend_from_slice(key.as_bytes());
|
||||
v.push(0);
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_shortcuts_reads_entries_honors_hidden_and_key_case() {
|
||||
let mut buf = Vec::new();
|
||||
buf.extend(map_open("shortcuts"));
|
||||
// Entry 0: a normal shortcut, with a nested `tags` map to exercise skip_map, and mixed-case
|
||||
// keys (Steam has shipped both `AppName` and `appname`). appid stored as a negative i32.
|
||||
buf.extend(map_open("0"));
|
||||
buf.extend(field_i32("appid", -1838178284)); // == 2456789012 as u32
|
||||
buf.extend(field_str("AppName", "My Emulator"));
|
||||
buf.extend(field_str("Exe", "\"/usr/bin/foo\""));
|
||||
buf.extend(field_i32("IsHidden", 0));
|
||||
buf.extend(map_open("tags"));
|
||||
buf.extend(field_str("0", "emulator"));
|
||||
buf.push(0x08); // end tags
|
||||
buf.push(0x08); // end entry 0
|
||||
// Entry 1: hidden, lowercase key variant.
|
||||
buf.extend(map_open("1"));
|
||||
buf.extend(field_str("appname", "Hidden Game"));
|
||||
buf.extend(field_i32("ishidden", 1));
|
||||
buf.push(0x08); // end entry 1
|
||||
buf.push(0x08); // end shortcuts
|
||||
|
||||
let scs = parse_shortcuts(&buf);
|
||||
assert_eq!(scs.len(), 2);
|
||||
assert_eq!(scs[0].appid, 2_456_789_012);
|
||||
assert_eq!(scs[0].name, "My Emulator");
|
||||
assert!(!scs[0].hidden);
|
||||
assert_eq!(scs[1].name, "Hidden Game");
|
||||
assert!(scs[1].hidden);
|
||||
|
||||
// A hidden shortcut is dropped from the surfaced library; a visible one launches via its
|
||||
// 64-bit game id (not the bare appid).
|
||||
assert!(shortcut_entry(scs.into_iter().nth(1).unwrap()).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_shortcuts_is_lenient() {
|
||||
assert!(parse_shortcuts(b"").is_empty()); // not even a top-level map
|
||||
assert!(parse_shortcuts(b"{not binary vdf}").is_empty());
|
||||
// A truncated entry (buffer ends mid-int) yields what parsed cleanly before it — here, none.
|
||||
let mut buf = Vec::new();
|
||||
buf.extend(map_open("shortcuts"));
|
||||
buf.extend(map_open("0"));
|
||||
buf.extend_from_slice(b"\x02appid\x00\x01\x02"); // 2 of 4 int bytes, then EOF
|
||||
assert!(parse_shortcuts(&buf).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shortcut_entry_launches_via_rungameid() {
|
||||
let sc = Shortcut {
|
||||
appid: 2_456_789_012,
|
||||
name: "My Emulator".into(),
|
||||
exe: "\"/opt/emu/run.sh\"".into(),
|
||||
hidden: false,
|
||||
};
|
||||
let entry = shortcut_entry(sc).unwrap();
|
||||
assert_eq!(entry.id, "steam:2456789012");
|
||||
assert_eq!(entry.store, "steam");
|
||||
let launch = entry.launch.unwrap();
|
||||
assert_eq!(launch.kind, "steam_appid");
|
||||
// Value is the 64-bit game id — digits only, so it passes the shared appid guard.
|
||||
assert_eq!(launch.value, shortcut_gameid(2_456_789_012).to_string());
|
||||
assert!(launch.value.bytes().all(|b| b.is_ascii_digit()));
|
||||
}
|
||||
|
||||
// `shortcut_gameid_composes_appid_and_marker` moved with the function to `launch.rs` (WP1.1).
|
||||
|
||||
#[test]
|
||||
fn crc32_matches_the_known_check_value_and_derives_a_high_bit_appid() {
|
||||
assert_eq!(crc32(b"123456789"), 0xCBF4_3926); // IEEE CRC-32 check value
|
||||
// A derived shortcut appid always has the high bit set (so it never collides with a real
|
||||
// store appid, and its CDN art fetch is skipped).
|
||||
assert_ne!(
|
||||
shortcut_appid("\"/usr/bin/foo\"", "My Emulator") & 0x8000_0000,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_filenames_follow_steams_naming() {
|
||||
assert_eq!(
|
||||
grid_filenames(ArtKind::Portrait, 42),
|
||||
vec!["42p.png", "42p.jpg"]
|
||||
);
|
||||
assert_eq!(
|
||||
grid_filenames(ArtKind::Hero, 42),
|
||||
vec!["42_hero.png", "42_hero.jpg"]
|
||||
);
|
||||
assert_eq!(
|
||||
grid_filenames(ArtKind::Logo, 42),
|
||||
vec!["42_logo.png", "42_logo.jpg"]
|
||||
);
|
||||
assert_eq!(
|
||||
grid_filenames(ArtKind::Header, 42),
|
||||
vec!["42.png", "42.jpg"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_grid_art_file_matches_the_userdata_grid_layout() {
|
||||
let grid = tempfile::tempdir().unwrap();
|
||||
std::fs::write(grid.path().join("2456789012p.jpg"), b"poster").unwrap();
|
||||
let found = find_grid_art_file(grid.path(), 2_456_789_012, ArtKind::Portrait).unwrap();
|
||||
assert_eq!(found, grid.path().join("2456789012p.jpg"));
|
||||
// Missing kinds and a zero-byte file both miss cleanly.
|
||||
assert_eq!(
|
||||
find_grid_art_file(grid.path(), 2_456_789_012, ArtKind::Hero),
|
||||
None
|
||||
);
|
||||
std::fs::write(grid.path().join("42p.png"), b"").unwrap();
|
||||
assert_eq!(find_grid_art_file(grid.path(), 42, ArtKind::Portrait), None);
|
||||
}
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
//! Xbox / Microsoft Store (UWP) provider: installed packages, PFN resolution, and store art. Split out of the `library` facade (plan §W5).
|
||||
|
||||
use super::art::cached_art;
|
||||
use super::*;
|
||||
|
||||
/// Reads installed Xbox / Game Pass / Store GDK games from the flat-file install dirs. Windows-only.
|
||||
/// Best-effort: empty when no `XboxGames` dir exists.
|
||||
#[cfg(windows)]
|
||||
pub struct XboxProvider;
|
||||
|
||||
#[cfg(windows)]
|
||||
impl LibraryProvider for XboxProvider {
|
||||
fn store(&self) -> &'static str {
|
||||
"xbox"
|
||||
}
|
||||
|
||||
fn list(&self) -> Vec<GameEntry> {
|
||||
xbox_games()
|
||||
}
|
||||
}
|
||||
|
||||
/// Scan each fixed drive's default `<drive>:\XboxGames` for GDK games — the presence of
|
||||
/// `Content\MicrosoftGame.config` is the game marker (so we list games, not ordinary UWP apps). A
|
||||
/// custom install folder (set via the undocumented `.GamingRoot`) isn't covered; the default folder
|
||||
/// is the common case. Non-GDK pure-UWP Store games (under the ACL-locked WindowsApps) are missed too.
|
||||
#[cfg(windows)]
|
||||
fn xbox_games() -> Vec<GameEntry> {
|
||||
let mut games = Vec::new();
|
||||
for letter in b'C'..=b'Z' {
|
||||
let root = PathBuf::from(format!("{}:\\XboxGames", letter as char));
|
||||
let Ok(rd) = std::fs::read_dir(&root) else {
|
||||
continue;
|
||||
};
|
||||
for entry in rd.flatten() {
|
||||
let title_dir = entry.path();
|
||||
let cfg = title_dir.join("Content").join("MicrosoftGame.config");
|
||||
if !cfg.is_file() {
|
||||
continue;
|
||||
}
|
||||
// Cap the read like the other untrusted on-disk manifests (Epic `read_capped`, Lutris
|
||||
// art) — a planted multi-GB MicrosoftGame.config under `<drive>:\XboxGames\…\Content\`
|
||||
// must not OOM the privileged host during enumeration (security-review 2026-07-17). A
|
||||
// real GDK manifest is a few KB.
|
||||
match cfg.metadata() {
|
||||
Ok(m) if m.len() <= 1024 * 1024 => {}
|
||||
_ => continue,
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(&cfg) else {
|
||||
continue;
|
||||
};
|
||||
let folder = title_dir
|
||||
.file_name()
|
||||
.map(|f| f.to_string_lossy().into_owned());
|
||||
let Some((name, app_id, title, store_id)) = xbox_parse_config(&text, folder.as_deref())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(pfn) = xbox_pfn(&name) else {
|
||||
tracing::debug!(package = %name, "xbox: no AppRepository entry → can't resolve PFN, skipping");
|
||||
continue;
|
||||
};
|
||||
let id_key = if store_id.is_empty() {
|
||||
pfn.clone()
|
||||
} else {
|
||||
store_id
|
||||
};
|
||||
let id = format!("xbox:{id_key}");
|
||||
// Art (unofficial displaycatalog, keyed by StoreId) is resolved off the hot path by the
|
||||
// background warmer; read whatever it has cached (title-only until warmed / if no StoreId).
|
||||
let art = cached_art(&id).unwrap_or_default();
|
||||
games.push(GameEntry {
|
||||
provider: None,
|
||||
role: GameRole::Game,
|
||||
icon: None,
|
||||
meta: GameMeta::pc(),
|
||||
id,
|
||||
store: "xbox".into(),
|
||||
title,
|
||||
art,
|
||||
launch: Some(LaunchSpec {
|
||||
kind: "aumid".into(),
|
||||
value: format!("{pfn}!{app_id}"),
|
||||
}),
|
||||
// AUMID activation goes through the shell, so the host never owns the process: the
|
||||
// title's `Content` dir (which holds the game's binaries) is the detect signal.
|
||||
detect: DetectSpec::dir(title_dir.join("Content")),
|
||||
});
|
||||
}
|
||||
}
|
||||
games.sort_by(|a, b| a.id.cmp(&b.id));
|
||||
games.dedup_by(|a, b| a.id == b.id); // same game on two drives → one entry
|
||||
games
|
||||
}
|
||||
|
||||
/// Parse the fields we need from a `MicrosoftGame.config`: `(Identity Name, AppId, title, StoreId)`.
|
||||
/// AppId is the `<Executable>`'s `Id` (the AUMID app id, typically "Game"). The title prefers
|
||||
/// `ShellVisuals@DefaultDisplayName`, but that can be an unresolved `ms-resource:` ref → fall back to
|
||||
/// the install folder name, then the package name.
|
||||
#[cfg(windows)]
|
||||
fn xbox_parse_config(text: &str, folder: Option<&str>) -> Option<(String, String, String, String)> {
|
||||
let doc = roxmltree::Document::parse(text).ok()?;
|
||||
let root = doc.root_element();
|
||||
let name = root
|
||||
.children()
|
||||
.find(|n| n.has_tag_name("Identity"))?
|
||||
.attribute("Name")?
|
||||
.to_string();
|
||||
let app_id = root
|
||||
.children()
|
||||
.find(|n| n.has_tag_name("ExecutableList"))
|
||||
.and_then(|el| {
|
||||
el.children()
|
||||
.filter(|n| n.has_tag_name("Executable"))
|
||||
.find_map(|e| e.attribute("Id"))
|
||||
})?
|
||||
.to_string();
|
||||
let ddn = root
|
||||
.children()
|
||||
.find(|n| n.has_tag_name("ShellVisuals"))
|
||||
.and_then(|sv| sv.attribute("DefaultDisplayName"))
|
||||
.filter(|s| !s.is_empty() && !s.starts_with("ms-resource"));
|
||||
let title = ddn
|
||||
.map(String::from)
|
||||
.or_else(|| folder.map(String::from))
|
||||
.unwrap_or_else(|| name.clone());
|
||||
let store_id = root
|
||||
.children()
|
||||
.find(|n| n.has_tag_name("StoreId"))
|
||||
.and_then(|n| n.text())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
Some((name, app_id, title, store_id))
|
||||
}
|
||||
|
||||
/// Resolve a package's PackageFamilyName by finding its
|
||||
/// `AppRepository\Packages\<PackageFullName>` dir (machine-wide, SYSTEM-readable) and reducing the
|
||||
/// full name to `Name_PublisherHash`. This READS the authoritative PFN — never compute the hash.
|
||||
///
|
||||
/// **Readable by the host, NOT by the plugin runner.** Measured on 2026-08-06: that directory is
|
||||
/// `UnauthorizedAccessException` for `NT AUTHORITY\LocalService` (which the runner is), while the
|
||||
/// host service runs as LocalSystem and enumerates all 348 entries. That asymmetry is why the
|
||||
/// `xbox` launch kind exists — a library plugin sends the package Identity it CAN read out of
|
||||
/// `MicrosoftGame.config`, and this resolves the rest at launch time (see `launch.rs`).
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn xbox_pfn(identity: &str) -> Option<String> {
|
||||
let pkgs = PathBuf::from(std::env::var_os("ProgramData")?)
|
||||
.join("Microsoft")
|
||||
.join("Windows")
|
||||
.join("AppRepository")
|
||||
.join("Packages");
|
||||
let prefix = format!("{identity}_");
|
||||
for e in std::fs::read_dir(&pkgs).ok()?.flatten() {
|
||||
let dn = e.file_name().to_string_lossy().into_owned();
|
||||
if dn.starts_with(&prefix) {
|
||||
if let Some(pfn) = pfn_from_full(&dn, identity) {
|
||||
return Some(pfn);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// PackageFamilyName from a PackageFullName dir name
|
||||
/// (`Name_Version_Arch_ResourceId_PublisherHash`) → `Name_PublisherHash`. The hash is the last
|
||||
/// `_`-segment; `Name` is the caller's identity.
|
||||
#[cfg(windows)]
|
||||
fn pfn_from_full(dir_name: &str, identity: &str) -> Option<String> {
|
||||
let hash = dir_name.rsplit('_').next()?;
|
||||
(!hash.is_empty() && hash != dir_name).then(|| format!("{identity}_{hash}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn xbox_parse_config_and_pfn() {
|
||||
let xml = r#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<Game configVersion="1">
|
||||
<Identity Name="Microsoft.624F8B84B80" Publisher="CN=Microsoft" Version="1.0.0.0" />
|
||||
<ExecutableList>
|
||||
<Executable Name="gamelaunchhelper.exe" Id="Game" />
|
||||
</ExecutableList>
|
||||
<StoreId>9NBLGGH4R315</StoreId>
|
||||
<ShellVisuals DefaultDisplayName="Halo Infinite" Square150x150Logo="x.png" />
|
||||
</Game>"#;
|
||||
let (name, app_id, title, store_id) = xbox_parse_config(xml, Some("HaloInfinite")).unwrap();
|
||||
assert_eq!(name, "Microsoft.624F8B84B80");
|
||||
assert_eq!(app_id, "Game");
|
||||
assert_eq!(title, "Halo Infinite");
|
||||
assert_eq!(store_id, "9NBLGGH4R315");
|
||||
// An ms-resource DefaultDisplayName is unresolvable → fall back to the install folder name.
|
||||
let xml2 = r#"<Game><Identity Name="Pkg.Name"/>
|
||||
<ExecutableList><Executable Id="App"/></ExecutableList>
|
||||
<ShellVisuals DefaultDisplayName="ms-resource:DisplayName"/></Game>"#;
|
||||
let (_, app2, title2, sid2) = xbox_parse_config(xml2, Some("MyGameFolder")).unwrap();
|
||||
assert_eq!(app2, "App");
|
||||
assert_eq!(title2, "MyGameFolder");
|
||||
assert_eq!(sid2, "");
|
||||
// PackageFamilyName reduced from a PackageFullName dir name (the hash is the last segment).
|
||||
assert_eq!(
|
||||
pfn_from_full(
|
||||
"Microsoft.624F8B84B80_1.0.0.0_x64__8wekyb3d8bbwe",
|
||||
"Microsoft.624F8B84B80"
|
||||
)
|
||||
.as_deref(),
|
||||
Some("Microsoft.624F8B84B80_8wekyb3d8bbwe")
|
||||
);
|
||||
assert!(pfn_from_full("NoUnderscore", "NoUnderscore").is_none());
|
||||
}
|
||||
}
|
||||
@@ -214,7 +214,12 @@ fn api_router_parts() -> (Router<Arc<MgmtState>>, utoipa::openapi::OpenApi) {
|
||||
))
|
||||
.routes(routes!(host::get_status))
|
||||
.routes(routes!(host::get_local_summary))
|
||||
.routes(routes!(clients::list_paired_clients))
|
||||
// GET and DELETE share the `/clients` path, so they must be ONE `routes!` — utoipa-axum
|
||||
// merges the methods of a single call into one route; two calls collide on the path.
|
||||
.routes(routes!(
|
||||
clients::list_paired_clients,
|
||||
clients::unpair_all_clients
|
||||
))
|
||||
.routes(routes!(clients::unpair_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.
|
||||
@@ -226,7 +231,11 @@ fn api_router_parts() -> (Router<Arc<MgmtState>>, utoipa::openapi::OpenApi) {
|
||||
.routes(routes!(native::get_native_pairing))
|
||||
.routes(routes!(native::arm_native_pairing))
|
||||
.routes(routes!(native::disarm_native_pairing))
|
||||
.routes(routes!(native::list_native_clients))
|
||||
// Same-path pair as `/clients` above — one `routes!` for both methods.
|
||||
.routes(routes!(
|
||||
native::list_native_clients,
|
||||
native::unpair_all_native_clients
|
||||
))
|
||||
.routes(routes!(native::unpair_native_client))
|
||||
.routes(routes!(native::list_pending_devices))
|
||||
.routes(routes!(native::approve_pending_device))
|
||||
@@ -314,7 +323,7 @@ pub fn openapi_json() -> String {
|
||||
(name = "pairing", description = "Pairing PIN delivery (the out-of-band half of the GameStream pairing handshake)"),
|
||||
(name = "native", description = "Native punktfunk/1 pairing: arm a window, display the host PIN, manage paired devices"),
|
||||
(name = "session", description = "Active streaming session control"),
|
||||
(name = "library", description = "Game library: installed-store titles (Steam) plus user-curated custom entries"),
|
||||
(name = "library", description = "Game library: the titles each installed library plugin syncs, plus user-curated custom entries"),
|
||||
(name = "stats", description = "Streaming performance-stats capture: arm/stop a recording, read the live + saved time-series for graphing"),
|
||||
(name = "logs", description = "Host log stream: the newest in-memory log entries, cursor-paged for live following"),
|
||||
(name = "events", description = "Host lifecycle events: an SSE stream (client/session/stream lifecycle, pairing, displays, library, host) with Last-Event-ID resume and server-side kind filters"),
|
||||
|
||||
@@ -153,6 +153,62 @@ pub(crate) async fn unpair_client(
|
||||
}
|
||||
}
|
||||
|
||||
/// Unpair every client
|
||||
///
|
||||
/// The collection form of [`unpair_client`]: empties the pairing store in ONE persisted write,
|
||||
/// carrying the same revocation guarantees across the whole set. A LIVE GameStream session is
|
||||
/// ended (its owning certificate is necessarily one of those just removed), and the ENet control
|
||||
/// port (UDP 47999) closes, because no pairing is left to hold it open.
|
||||
///
|
||||
/// Idempotent, and so a 200 rather than the single unpair's 204/404 pair: "unpair everything" is
|
||||
/// satisfied by an already-empty store, and the operator still wants to know whether that meant
|
||||
/// three devices or none.
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/clients",
|
||||
tag = "clients",
|
||||
operation_id = "unpairAllClients",
|
||||
responses(
|
||||
(status = OK, description = "Every client unpaired (possibly none)", body = UnpairAllResult),
|
||||
(status = UNAUTHORIZED, description = "Missing or invalid bearer token", body = ApiError),
|
||||
)
|
||||
)]
|
||||
pub(crate) async fn unpair_all_clients(State(st): State<Arc<MgmtState>>) -> Response {
|
||||
let mut paired = st.app.paired.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if paired.is_empty() {
|
||||
// Nothing to persist, no port to sync — an empty store is already the requested state.
|
||||
return Json(UnpairAllResult { unpaired: 0 }).into_response();
|
||||
}
|
||||
let removed: Vec<[u8; 32]> = paired
|
||||
.iter()
|
||||
.map(|der| Sha256::digest(der).into())
|
||||
.collect();
|
||||
paired.clear();
|
||||
// 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);
|
||||
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
|
||||
// launch — the cert was unreadable at /launch — cannot be attributed, and is left to the port
|
||||
// teardown below, which here always fires: no pairing remains.)
|
||||
let live_owner = st
|
||||
.app
|
||||
.launch
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.and_then(|l| l.owner_fp);
|
||||
if live_owner.is_some_and(|fp| removed.contains(&fp)) {
|
||||
st.app.quit_session("client unpaired");
|
||||
}
|
||||
if let Err(e) = crate::gamestream::sync_control(&st.app) {
|
||||
tracing::warn!(error = %format!("{e:#}"), "control port sync after unpair-all failed");
|
||||
}
|
||||
let unpaired = removed.len() as u32;
|
||||
tracing::info!(unpaired, "management API: all clients unpaired");
|
||||
Json(UnpairAllResult { unpaired }).into_response()
|
||||
}
|
||||
|
||||
/// Pairing-flow status
|
||||
///
|
||||
/// Poll this to know when to prompt the user for the PIN Moonlight displays.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Library-tagged management endpoints: installed-store + custom game entries and box art.
|
||||
//! Split out of the `mgmt` facade (plan §W5).
|
||||
//! Library-tagged management endpoints: the game catalog (plugin-synced + custom entries), the
|
||||
//! source toggles, the provider reconcile API and box art. Split out of the `mgmt` facade (plan §W5).
|
||||
|
||||
use super::auth::AuthLane;
|
||||
use super::shared::*;
|
||||
@@ -9,6 +9,10 @@ use axum::Extension;
|
||||
/// Refuse a write whose payload carries an operator-privileged field to a lane that may not set one
|
||||
/// (2026-08-05 review H-1), and refuse any local art path the proxy would not serve back (H-2).
|
||||
///
|
||||
/// The **single-entry writes** — the operator creating or editing one custom entry. The provider
|
||||
/// reconcile takes [`check_privileged_fields`] and sanitizes art instead; the split is the whole
|
||||
/// point, and [`crate::library::sanitize_art_paths`] carries the reasoning.
|
||||
///
|
||||
/// Both checks belong here rather than in the route gate: `PUT /library/provider/{p}` is a route a
|
||||
/// provider plugin must be able to call — reconciling its own entry set is the whole point of a
|
||||
/// scanner plugin — while `prep` / `launch.kind = "command"` inside that payload are the operator's
|
||||
@@ -22,14 +26,32 @@ use axum::Extension;
|
||||
/// `reason` is the caller's log line. It exists because these are TWO different refusals — an
|
||||
/// operator-privileged field (403) and an unservable art path (400) — and logging both as "carries
|
||||
/// a field this lane may not set" sent the Lutris/Steam `file://` art rejection looking like an
|
||||
/// auth problem. The plugin only ever sees `HostRequestError`, so this log line is the sole
|
||||
/// diagnosis surface for whoever has to explain why a scanner syncs nothing.
|
||||
/// auth problem.
|
||||
fn check_entry_fields(
|
||||
lane: AuthLane,
|
||||
art: &crate::library::Artwork,
|
||||
launch: Option<&crate::library::LaunchSpec>,
|
||||
prep: &[crate::hooks::PrepCmd],
|
||||
icon: Option<&str>,
|
||||
) -> Option<(String, Response)> {
|
||||
check_privileged_fields(lane, launch, prep, icon).or_else(|| {
|
||||
crate::library::validate_art_paths(art)
|
||||
.err()
|
||||
.map(|e| (e.clone(), api_error(StatusCode::BAD_REQUEST, &e)))
|
||||
})
|
||||
}
|
||||
|
||||
/// The half of [`check_entry_fields`] that is about *authority* rather than about art: an
|
||||
/// operator-privileged field this lane may not set (403), or an unrepresentable icon token (400).
|
||||
///
|
||||
/// Split out for the provider reconcile, which must apply exactly these two and NOT the art check —
|
||||
/// it sanitizes unservable covers instead of refusing the payload
|
||||
/// ([`crate::library::sanitize_art_paths`] explains why the two callers want different answers).
|
||||
fn check_privileged_fields(
|
||||
lane: AuthLane,
|
||||
launch: Option<&crate::library::LaunchSpec>,
|
||||
prep: &[crate::hooks::PrepCmd],
|
||||
icon: Option<&str>,
|
||||
) -> Option<(String, Response)> {
|
||||
if !lane.may_set_privileged_fields() {
|
||||
if let Some(field) = crate::library::privileged_field(launch, prep) {
|
||||
@@ -55,9 +77,7 @@ fn check_entry_fields(
|
||||
if let Err(e) = crate::library::validate_icon(icon) {
|
||||
return Some((e.clone(), api_error(StatusCode::BAD_REQUEST, &e)));
|
||||
}
|
||||
crate::library::validate_art_paths(art)
|
||||
.err()
|
||||
.map(|e| (e.clone(), api_error(StatusCode::BAD_REQUEST, &e)))
|
||||
None
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -70,11 +90,12 @@ pub(crate) struct LibraryQuery {
|
||||
|
||||
/// List the game library
|
||||
///
|
||||
/// Every installed-store title (Steam, read from the host's local files — no Steam API key)
|
||||
/// merged with the user's custom entries, sorted by title. Artwork fields are URLs the client
|
||||
/// fetches directly (the public Steam CDN for Steam titles). `?provider=` narrows to the
|
||||
/// entries a given external provider owns; `?platform=` to one platform (case-insensitive —
|
||||
/// installed-store titles are `PC`, custom/provider entries carry whatever was authored).
|
||||
/// Every title this host knows about, sorted by title: the entries each installed library plugin
|
||||
/// has synced (Steam, Lutris, Heroic, Epic, GOG, Xbox, Playnite, ROM managers, …) plus the user's
|
||||
/// own custom entries. Artwork fields are URLs the client fetches directly, except local files on
|
||||
/// the host, which are rewritten to this API's own art proxy. `?provider=` narrows to the entries a
|
||||
/// given external provider owns; `?platform=` to one platform (case-insensitive — whatever the
|
||||
/// source authored, conventionally `PC` for desktop stores).
|
||||
///
|
||||
/// **The operator's own lane additionally sees the titles they have HIDDEN**, each carrying
|
||||
/// `hidden: true`; every other lane gets them filtered out upstream and cannot tell they exist. The
|
||||
@@ -222,17 +243,20 @@ pub(crate) async fn set_library_entry_hidden(
|
||||
/// Request body for `setLibraryScanner`.
|
||||
#[derive(Deserialize, ToSchema)]
|
||||
pub(crate) struct ScannerToggle {
|
||||
/// Whether the scanner should run on this host.
|
||||
/// Whether this source should contribute titles on this host.
|
||||
enabled: bool,
|
||||
}
|
||||
|
||||
/// List the library scanners
|
||||
/// List the library sources
|
||||
///
|
||||
/// The installed-store scanners this host supports — the list is platform-dependent (Steam
|
||||
/// everywhere; Lutris + Heroic on Linux; Epic, GOG, and Xbox/Game Pass on Windows), so the console
|
||||
/// renders a toggle only for scanners that can do anything here. Scanners default to enabled;
|
||||
/// disabling one hides its titles from every library surface from the next read. The user-curated
|
||||
/// custom store is not a scanner and is always on.
|
||||
/// Every game source on this host with its enable state — one row per installed library plugin
|
||||
/// (Steam, Lutris, Heroic, Epic, GOG, Xbox, Playnite, ROM managers, …), so the list reflects what
|
||||
/// the operator has actually installed rather than what this build happens to support. Sources
|
||||
/// default to enabled; disabling one hides its titles from every library surface from the next
|
||||
/// read. The user-curated custom store is not a source and is always on.
|
||||
///
|
||||
/// Older hosts (≤ v0.27.x) also listed the six scanners built into the host binary, with
|
||||
/// `origin: "builtin"`. Those are gone; every row now reports `origin: "plugin"`.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/library/scanners",
|
||||
@@ -247,12 +271,13 @@ pub(crate) async fn list_library_scanners() -> Json<Vec<crate::library::ScannerI
|
||||
Json(crate::library::list_scanners())
|
||||
}
|
||||
|
||||
/// Enable or disable a library scanner
|
||||
/// Enable or disable a library source
|
||||
///
|
||||
/// Persists the toggle and applies it from the next library read (no restart). Disabling a scanner
|
||||
/// Persists the toggle and applies it from the next library read (no restart). Disabling a source
|
||||
/// hides its titles everywhere — the console grid, native clients, and the GameStream app list —
|
||||
/// and re-enabling brings them straight back (nothing is deleted; the scan just runs again). Emits
|
||||
/// `library.changed` with the scanner id as `source` when the state changed.
|
||||
/// and re-enabling brings them straight back. Nothing is deleted: the plugin may keep reconciling
|
||||
/// while its source is off, and those entries simply aren't surfaced. Emits `library.changed` with
|
||||
/// the source id as `source` when the state changed.
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/library/scanners/{id}",
|
||||
@@ -436,11 +461,11 @@ pub(crate) struct ReconcileQuery {
|
||||
///
|
||||
/// `?store=` additionally **claims** that store for the provider: its entries then surface with
|
||||
/// deterministic `<store>:<external_id>` ids and the store's own badge, instead of opaque
|
||||
/// `custom:<id>` ones — which is what lets a library plugin reproduce the entries an in-host scanner
|
||||
/// used to produce, right down to the GameStream app ids and client-side art caches. One provider
|
||||
/// per store; a second claimant gets 409. While a claim is held the matching built-in scanner is
|
||||
/// suppressed, so the two never double-list. The claim is released by `DELETE`, not by an empty
|
||||
/// reconcile (a store can legitimately have zero installed titles).
|
||||
/// `custom:<id>` ones — which is what let a library plugin reproduce the entries the in-host scanner
|
||||
/// used to produce, right down to the GameStream app ids and client-side art caches, and is why
|
||||
/// removing those scanners changed nothing downstream. One provider per store; a second claimant
|
||||
/// gets 409. The claim is released by `DELETE`, not by an empty reconcile (a store can legitimately
|
||||
/// have zero installed titles).
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/library/provider/{provider}",
|
||||
@@ -463,7 +488,7 @@ pub(crate) async fn reconcile_provider_entries(
|
||||
Extension(lane): Extension<AuthLane>,
|
||||
Path(provider): Path<String>,
|
||||
Query(q): Query<ReconcileQuery>,
|
||||
ApiJson(inputs): ApiJson<Vec<crate::library::ProviderEntryInput>>,
|
||||
ApiJson(mut inputs): ApiJson<Vec<crate::library::ProviderEntryInput>>,
|
||||
) -> Response {
|
||||
if let Err(e) = crate::library::validate_provider_name(&provider) {
|
||||
return api_error(StatusCode::BAD_REQUEST, &e);
|
||||
@@ -479,9 +504,15 @@ pub(crate) async fn reconcile_provider_entries(
|
||||
}
|
||||
// Every entry in the payload, not just the first — a reconcile replaces a whole entry set, so
|
||||
// one privileged field anywhere in it is one command execution.
|
||||
//
|
||||
// Art is deliberately NOT part of this refusal. A privileged field is the plugin overreaching
|
||||
// and must fail the write; an unservable cover is a path mismatch between where a launcher keeps
|
||||
// its art and where the host is allowed to read, and failing the payload over one of those threw
|
||||
// away a working library to save a thumbnail. Those covers are stripped below instead, which
|
||||
// holds the same "no unservable path is ever persisted" invariant.
|
||||
for (i, e) in inputs.iter().enumerate() {
|
||||
if let Some((reason, denied)) =
|
||||
check_entry_fields(lane, &e.art, e.launch.as_ref(), &e.prep, e.icon.as_deref())
|
||||
check_privileged_fields(lane, e.launch.as_ref(), &e.prep, e.icon.as_deref())
|
||||
{
|
||||
tracing::warn!(
|
||||
provider,
|
||||
@@ -493,6 +524,41 @@ pub(crate) async fn reconcile_provider_entries(
|
||||
return denied;
|
||||
}
|
||||
}
|
||||
// A launcher this box cannot open is a fact about the box, not a defect in the payload, so it
|
||||
// costs its own tile and nothing else. Before this, the Playnite plugin's single launcher entry
|
||||
// 400'd every game it shipped alongside.
|
||||
for (title, value) in crate::library::sanitize_launcher_entries(&mut inputs) {
|
||||
tracing::warn!(
|
||||
provider,
|
||||
launcher = %value,
|
||||
title = %title,
|
||||
"library reconcile: dropped a launcher tile this host cannot open — the rest of the \
|
||||
payload still syncs. Install the launcher, or turn the tile off in the plugin's config"
|
||||
);
|
||||
}
|
||||
// One aggregated line, not one per entry: a root mismatch misses EVERY cover in the payload, and
|
||||
// a per-entry warn would bury the rest of the log under a thousand copies of one fact.
|
||||
let mut dropped_art = 0usize;
|
||||
let mut first_dropped: Option<(String, &'static str, String)> = None;
|
||||
for e in inputs.iter_mut() {
|
||||
for (field, value) in crate::library::sanitize_art_paths(&mut e.art) {
|
||||
dropped_art += 1;
|
||||
first_dropped.get_or_insert_with(|| (e.title.clone(), field, value));
|
||||
}
|
||||
}
|
||||
if let Some((title, field, path)) = first_dropped {
|
||||
tracing::warn!(
|
||||
provider,
|
||||
dropped = dropped_art,
|
||||
example_title = %title,
|
||||
example_field = field,
|
||||
example_path = %path,
|
||||
"library reconcile: dropped local art the proxy may not serve — these entries still \
|
||||
sync, but their covers will be blank. The path must be an image file (jpg/png/webp/\
|
||||
gif/bmp/ico/tga) inside an allowed art root; set PUNKTFUNK_LIBRARY_ART_ROOTS if this \
|
||||
library's art lives outside the defaults"
|
||||
);
|
||||
}
|
||||
match crate::library::reconcile_provider(&provider, store.as_deref(), inputs) {
|
||||
Ok(crate::library::MutateOutcome::Done(entries)) => {
|
||||
tracing::info!(
|
||||
@@ -551,11 +617,12 @@ pub(crate) async fn delete_provider_entries(Path(provider): Path<String>) -> Res
|
||||
///
|
||||
/// Resolves `kind` (`portrait` | `hero` | `logo` | `header`) for the given library id and streams
|
||||
/// the image bytes. Any id stored in the host's catalog (manual entries, provider-synced entries,
|
||||
/// and a library plugin's claimed-store entries) serves its local art file. A Steam title falls back
|
||||
/// to the in-host scanner's resolver: the host's own local Steam cache first (exact — it's what the
|
||||
/// user's Steam client already shows for it), the public Steam CDN's flat URL convention second
|
||||
/// (newer titles' CDN assets can live at a per-asset-hash path the host can't predict, in which case
|
||||
/// this 404s and the client falls through to its next art candidate).
|
||||
/// and a library plugin's claimed-store entries) serves its local art file; anything else 404s and
|
||||
/// the client falls through to its next art candidate.
|
||||
///
|
||||
/// The host fetches nothing here. Art a plugin published as an `http(s)` URL is fetched by the
|
||||
/// client directly — this proxy exists for the *local* files a plugin finds on the host's own disk
|
||||
/// (a launcher's cover cache), which a client has no way to read.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/library/art/{id}/{kind}",
|
||||
@@ -575,10 +642,11 @@ pub(crate) async fn get_library_art(Path((id, kind)): Path<(String, String)>) ->
|
||||
let Some(kind) = crate::library::ArtKind::parse(&kind) else {
|
||||
return api_error(StatusCode::NOT_FOUND, "unknown art kind");
|
||||
};
|
||||
// `library.json` FIRST, for ANY id (WP1.2). Stored entries — manual, provider-synced, and (once
|
||||
// store claims land) a scanner plugin's `steam:570` — all serve their local art file from here,
|
||||
// so the proxy never has to know which store an id belongs to. Steam ids aren't stored today, so
|
||||
// this misses and the legacy branch below still answers them.
|
||||
// `library.json`, for ANY id (WP1.2): manual entries, provider-synced entries and a library
|
||||
// plugin's claimed-store `steam:570` all serve their local art file from here, so the proxy never
|
||||
// has to know which store an id belongs to. This was one of two branches — the second resolved a
|
||||
// `steam:` id through the in-host Steam scanner's own cache/CDN ladder, and was retired with that
|
||||
// scanner (M6). Steam ids now arrive here like every other claimed store's.
|
||||
let stored = {
|
||||
let id = id.clone();
|
||||
tokio::task::spawn_blocking(move || crate::library::library_local_art_bytes(&id, kind))
|
||||
@@ -587,20 +655,5 @@ pub(crate) async fn get_library_art(Path((id, kind)): Path<(String, String)>) ->
|
||||
if let Ok(Some((bytes, ctype))) = stored {
|
||||
return ([(header::CONTENT_TYPE, ctype)], bytes).into_response();
|
||||
}
|
||||
// Legacy in-host Steam scanner: local Steam cache, then the flat CDN URL. Retired with the
|
||||
// scanner itself once the steam plugin claims the store (M6).
|
||||
if let Some(appid) = id
|
||||
.strip_prefix("steam:")
|
||||
.and_then(|s| s.parse::<u32>().ok())
|
||||
{
|
||||
return match tokio::task::spawn_blocking(move || {
|
||||
crate::library::steam_art_bytes(appid, kind)
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(Some((bytes, ctype))) => ([(header::CONTENT_TYPE, ctype)], bytes).into_response(),
|
||||
_ => api_error(StatusCode::NOT_FOUND, "no art of that kind for this title"),
|
||||
};
|
||||
}
|
||||
api_error(StatusCode::NOT_FOUND, "no art of that kind for this title")
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user