Compare commits

..
Author SHA1 Message Date
enricobuehler 80061fbf6b fix(ci): an unset HOST_CER_PATH is $null, and a null hash key is fatal — not an empty key
ci / rust-arm64 (pull_request) Failing after 1m42s
ci / bun-nix (pull_request) Successful in 16s
ci / web (pull_request) Successful in 1m4s
windows-client / client (arm64, --no-default-features, aarch64-pc-windows-msvc, C:\t-a64) (pull_request) Successful in 2m43s
ci / docs-site (pull_request) Successful in 8m29s
windows-client / client (x64, , x86_64-pc-windows-msvc, C:\t) (pull_request) Successful in 6m18s
ci / rust (pull_request) Failing after 21m4s
Azure signing produces no .cer, so HOST_CER_PATH is deliberately unset. The publish step then built
its alias map as a single hash literal containing $env:HOST_CER_PATH as a KEY, and an unset $env:
var is $null — "A null key is not allowed in a hash literal", which failed the whole step. Canary
run 18256: the installer signed fine and published to its versioned path, then this line killed the
alias refresh, so `canary/punktfunk-host-setup.exe` went stale.

I reasoned about this line while making the .cer optional and concluded an unset variable would give
an empty-string key, which is legal. It does not — that only happens through string interpolation.
The $files guard just above filters the missing .cer correctly; the hash literal ran before anything
could use it.

Build the map incrementally instead, adding the .cer entry only when there is one, so the legacy
.pfx modes still alias it.

windows-client.yml survived the same change only by accident: it writes "$($env:MSIX_CER_PATH)",
and interpolating $null yields an empty string, which IS a legal key. Made that explicit too rather
than leaving correctness resting on quotes someone could reasonably tidy away.

Verified under pwsh 7: the old literal reproduces the exact CI message with the var unset; the new
form yields one entry unset and two entries set, with the .cer alias intact.
2026-08-14 20:07:57 +02:00
enricobuehler 4676d20dc1 Host capture gain works on punktfunk/1, and boosting no longer hard-clips (#229)
arch / build-publish (push) Failing after 7m4s
apple / distribute (push) Successful in 11m50s
ci / docs-site (push) Successful in 9m13s
android / android (push) Successful in 8m2s
apple / screenshots (push) Successful in 8m39s
deb / build-publish-gamescope (push) Successful in 28s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 8s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 12s
docker / builders-arm64cross (push) Failing after 8s
flatpak / build-publish (push) Successful in 11m42s
deb / build-publish-host (push) Successful in 5m14s
docker / deploy-docs (push) Failing after 4s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 27s
deb / build-publish (push) Successful in 12m23s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 13s
apple / swift (push) Successful in 1m56s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 10s
deb / smoke-install (push) Failing after 5s
deb / build-publish-client-arm64 (push) Successful in 1m23s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 11s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 11s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 24s
windows-client / client (x64, , x86_64-pc-windows-msvc, C:\t) (push) Successful in 6m50s
windows-host / package (push) Failing after 12m55s
windows-host / canary-manifest (push) Skipped
windows-host / winget-source (push) Skipped
ci / web (push) Successful in 1m10s
ci / rust-arm64 (push) Failing after 2m16s
windows-client / client (arm64, --no-default-features, aarch64-pc-windows-msvc, C:\t-a64) (push) Successful in 3m2s
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Successful in 19m1s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 1m19s
ci / rust (push) Successful in 28m39s
ci / bun-nix (push) Successful in 18s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Successful in 18m58s
2026-08-14 17:20:50 +00:00
enricobuehler be0030f953 Merge pull request #228 from worktree-azure-trusted-signing
android / android (push) Canceled after 0s
windows-client / client (arm64, --no-default-features, aarch64-pc-windows-msvc, C:\t-a64) (push) Canceled after 0s
windows-client / client (x64, , x86_64-pc-windows-msvc, C:\t) (push) Canceled after 0s
apple / swift (push) Canceled after 0s
apple / distribute (push) Canceled after 0s
windows-host / package (push) Canceled after 0s
windows-host / canary-manifest (push) Canceled after 0s
windows-host / winget-source (push) Canceled after 0s
apple / screenshots (push) Canceled after 0s
arch / build-publish (push) Canceled after 0s
ci / rust (push) Canceled after 0s
ci / rust-arm64 (push) Canceled after 0s
ci / web (push) Canceled after 0s
ci / docs-site (push) Canceled after 0s
ci / bun-nix (push) Canceled after 0s
deb / build-publish (push) Canceled after 0s
deb / build-publish-host (push) Canceled after 0s
deb / build-publish-gamescope (push) Canceled after 0s
decky / build-publish (push) Successful in 1m0s
deb / build-publish-client-arm64 (push) Canceled after 0s
deb / smoke-install (push) Canceled after 0s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Canceled after 0s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Canceled after 0s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Canceled after 0s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Canceled after 0s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Canceled after 0s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Canceled after 0s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Canceled after 0s
docker / builders-arm64cross (push) Canceled after 0s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Canceled after 0s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Canceled after 0s
docker / deploy-docs (push) Canceled after 0s
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Canceled after 0s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Canceled after 0s
Sign Windows releases with Azure Artifact Signing — a 3-day leaf makes timestamping mandatory
2026-08-14 17:20:10 +00:00
enricobuehler 8ee963b2b0 Merge pull request 'Exclusive topology left the KDE panel lit under a gamescope spawn — DPMS it dark' (#227) from worktree-gamescope-exclusive-dpms into main
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Failing after 2s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Failing after 1s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Failing after 2s
ci / rust-arm64 (push) Failing after 3s
docker / builders-arm64cross (push) Skipped
ci / rust (push) Canceled after 5m33s
ci / bun-nix (push) Successful in 1m29s
ci / web (push) Successful in 3m32s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Failing after 2s
deb / build-publish-host (push) Failing after 2m10s
ci / docs-site (push) Successful in 4m13s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Failing after 8s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Failing after 2s
docker / deploy-docs (push) Skipped
deb / build-publish (push) Canceled after 5m32s
deb / smoke-install (push) Canceled after 0s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Failing after 24s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Failing after 22s
android / android (push) Canceled after 5m25s
deb / build-publish-gamescope (push) Failing after 1m50s
deb / build-publish-client-arm64 (push) Failing after 1m40s
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Canceled after 15s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Canceled after 12s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Failing after 6s
windows-host / package (push) Canceled after 5m46s
windows-host / canary-manifest (push) Canceled after 0s
windows-host / winget-source (push) Canceled after 0s
arch / build-publish (push) Canceled after 5m30s
2026-08-14 17:14:42 +00:00
enricobuehler 2d15548e38 ci(windows): provision the signing toolchain — no .NET runtime meant signtool exited 3 in silence
windows-client / client (x64, , x86_64-pc-windows-msvc, C:\t) (pull_request) Successful in 7m59s
android / android (pull_request) Failing after 2m16s
ci / web (pull_request) Successful in 2m29s
ci / rust-arm64 (pull_request) Successful in 2m35s
windows-client / client (arm64, --no-default-features, aarch64-pc-windows-msvc, C:\t-a64) (pull_request) Successful in 4m24s
apple / swift (pull_request) Successful in 2m7s
apple / distribute (pull_request) Skipped
apple / screenshots (pull_request) Skipped
ci / bun-nix (pull_request) Successful in 5m25s
ci / rust (pull_request) Successful in 7m16s
ci / docs-site (pull_request) Successful in 7m48s
Verified the whole Azure signing path on the runner (.133) today and it failed twice, for two
reasons that neither error message named. Both are now provisioned here so a rebuild from the
unom/infra Packer template cannot silently un-fix them.

Azure.CodeSigning.Dlib.dll is a mixed-mode C++/CLI assembly: it ships Ijwhost.dll and a
runtimeconfig.json pinning Microsoft.NETCore.App 8.0.0. The runner had NO .NET runtime at all —
pwsh 7 is a self-contained install and brings no shared runtime — so signtool exited 3 having
printed absolutely nothing. Installing the .NET 8 runtime turned that into a clean sign.

The client itself installs machine-wide under C:\trusted-signing rather than a user's .nuget,
because act_runner runs as SYSTEM, whose USERPROFILE is C:\Windows\System32\config\systemprofile.
A per-user install under Administrator is invisible to every job that actually builds. Confirmed by
resolving Find-AzureDlib from a SYSTEM scheduled task, which is also how the earlier SSH-only
attempts misled: over a network logon New-SelfSignedCertificate hits NTE_PERM, so a control test
that "fails" there proves nothing about how CI will behave.

Both downloads are SHA-256 pinned against version-immutable URLs (nuget.org flat-container and the
dotnet builds CDN), so they fail closed on tampering rather than on every Microsoft patch release —
unlike the BtbN `latest` pin above, which re-rolls. The .NET install uses Start-Process -Wait
because the bundle is a GUI PE that returns instantly under `&`, leaving $LASTEXITCODE unset and
racing the completion check (cost one false failure here).

End-to-end result on .133, as SYSTEM: sign rc=0, verify rc=0, chain Microsoft Identity Verification
Root CA 2020 -> ID Verified CS EOC CA 04 -> "unom - Enrico Buhler", leaf thumbprint
DD6A610F242CB5B2078C2A5D628699B6AB0CAC07 (matches the profile Azure reports), timestamped, leaf
expires in 3 days as expected. Signing an unsigned binary and reading the subject back reproduces
pack-msix.ps1's Publisher assertion exactly (match=True) — checked against a NON-catalog-signed
binary on purpose, because Get-AuthenticodeSignature on a catalog-signed system exe returns the
catalog signer and would have read as a false mismatch.
2026-08-14 19:05:21 +02:00
enricobuehler 6eb5edaff4 feat(audio): capture gain on punktfunk/1, and a soft knee instead of the clamp that made boosting a trap
android / android (pull_request) Failing after 1m5s
apple / swift (pull_request) Successful in 1m57s
apple / distribute (pull_request) Skipped
apple / screenshots (pull_request) Skipped
ci / docs-site (pull_request) Successful in 1m37s
ci / web (pull_request) Successful in 1m58s
ci / bun-nix (pull_request) Successful in 41s
windows-client / client (x64, , x86_64-pc-windows-msvc, C:\t) (pull_request) Successful in 6m41s
ci / rust (pull_request) Successful in 21m14s
ci / rust-arm64 (pull_request) Failing after 3m56s
windows-client / client (arm64, --no-default-features, aarch64-pc-windows-msvc, C:\t-a64) (pull_request) Successful in 2m50s
`PUNKTFUNK_AUDIO_GAIN` had two defects that compounded.

It existed only on the GameStream plane, so on native `punktfunk/1` it silently did
nothing — and since WASAPI loopback is tapped UPSTREAM of the endpoint's master volume,
turning the host's speaker slider up does not change the level a client receives either.
Between the two there was no host-side way at all to lift a quiet desktop mix on the
protocol that matters.

And where it did apply it was `(s * gain).clamp(-1.0, 1.0)` — a hard clip. Flat-topping a
waveform is a first-derivative discontinuity, which radiates harsh high-order harmonics, so
any operator who pushed past roughly 1.5x heard gross distortion long before reaching the
level they were chasing. A field report of "+18 dB and everything warbles" is the expected
output of that line, not a fault anywhere downstream of it.

`punktfunk_core::audio::apply_gain` replaces the clamp with a tanh soft knee above 0.7
(~-3.1 dBFS), chosen for three properties: C1-continuous where the branches meet (slope 1
on both sides, so the onset of limiting is not itself an audible event), bounded by
construction (asymptotic to 1.0, and +-inf maps to +-1.0, so nothing leaves out of range),
and odd-symmetric (benign harmonics, no DC). It is a memoryless waveshaper, so it costs
zero latency in the realtime encode path.

Unity is a no-op inside `apply_gain` itself, not merely at the call sites, so the default
wire stays byte-for-byte identical and a future caller that forgets to gate cannot quietly
bend every peak. `capture_gain` is now shared by both planes and rejects the two values
that are always typos: non-positive (would invert or mute) and above 8.0/+18 dB (capped,
and said out loud).

This buys headroom, NOT loudness. It cannot close a peak-to-loudness gap against
already-limited broadcast content; that needs a compressor with a real time constant, which
this deliberately is not, and the docs say so.

`SOFT_LIMIT_KNEE` is excluded from cbindgen: it is host-side capture processing that no C
embedder can act on, and exporting it would add a bare `#define` against the config's own
R21 rule. Verified by regenerating `include/punktfunk_core.h` — byte-identical, ABI 19
untouched.
2026-08-14 18:49:29 +02:00
enricobuehler 9dde564835 Merge pull request 'CRA Phase 1 closeout — vendor-CVE watch doc, retention verified, docs-site deps current' (#226) from worktree-cra-phase1-closeout into main
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 8s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 14s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 14s
ci / docs-site (push) Successful in 1m9s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 10s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 10s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 15s
docker / builders-arm64cross (push) Successful in 17s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 1m10s
docker / deploy-docs (push) Successful in 35s
ci / web (push) Successful in 5m55s
audit / c-abi-asan (push) Successful in 9m42s
audit / bun-audit (plugin-kit) (push) Successful in 2m7s
audit / bun-audit (sdk) (push) Successful in 14s
audit / bun-audit (web) (push) Successful in 15s
audit / docs-site-audit (push) Successful in 16s
audit / pnpm-audit (push) Successful in 9s
nix / flake (push) Successful in 13m53s
audit / cargo-audit (push) Successful in 5m42s
ci / rust (push) Successful in 20m6s
ci / rust-arm64 (push) Successful in 1m17s
audit / license-gate (push) Successful in 4m29s
audit / miri (push) Successful in 4m36s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 11s
ci / bun-nix (push) Successful in 22s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 8s
2026-08-14 16:37:35 +00:00
enricobuehler b79ff45bd1 feat(windows): sign via Azure Artifact Signing — a 3-day leaf makes timestamping mandatory
Releases move from the self-signed CN=unom cert to Azure Artifact Signing (formerly Trusted
Signing): account `unomsigning`, profile `unom-io`, signed by the `punktfunk-ci-signing` service
principal, which holds only the Artifact Signing Certificate Profile Signer role scoped to that one
profile. Both pack scripts gain the backend ahead of the existing .pfx and ephemeral fallbacks, so
canary and fork builds are unaffected.

Three things that are easy to get wrong, and are handled here rather than discovered in the field:

Azure mints a leaf certificate per signing request that expires in about three days. Both scripts
previously retried WITHOUT a timestamp when a timestamped sign failed — under Azure that ships an
artifact which verifies on the runner and goes untrusted days later, on every user's machine at
once. The retry is now gated on the mode: still lenient for a .pfx whose cert outlives the release,
a hard failure for Azure.

The MSIX manifest Publisher must equal the signer subject byte-for-byte, because package identity is
Name + Publisher. The default is now the profile's verified subject, written with `[char]0xFC`
escapes rather than literal umlauts so this UTF-8-without-BOM file cannot silently mojibake the DN
into one that no longer matches. pack-msix.ps1 now also reads the signature back off the packed
.msix and fails on drift — asymmetric on purpose: a subject that disagrees is fatal, a subject that
cannot be read is only a warning, since Get-AuthenticodeSignature's .msix support varies by Windows
version and signtool has already reported success by then. NOTE this changes package identity, so
existing installs need an uninstall, not an upgrade.

The updater's leaf-pinning note was wrong and is corrected: update/windows.rs claimed the
AUTHENTICODE_SHA256 field made Trusted Signing "a manifest edit", but a per-request leaf is exactly
what a leaf pin cannot track — a pin would go stale within days and reject every release after it.

Drivers are deliberately untouched: their catalogs keep the DRIVER_CERT_* cert and the installer
still plants it as a machine root. The two signatures were always independent (SmartScreen/UAC vs
PnP), which is why the installer could move without them. Whether a publicly-trusted catalog would
let us drop that root plant is recorded as an unverified follow-up, not assumed.

Verified: both scripts parse under the PowerShell 7 AST parser, both workflows are valid YAML, the
evaluated Publisher default matches the subject Azure reports for the profile (86 chars, ordinal),
rustfmt clean. NOT verified on Windows — the sign path itself needs an on-glass run on .133.
2026-08-14 18:24:27 +02:00
enricobuehler 42848c56b7 docs(compliance): the vendor-CVE watch the technical file will cite — and the SBOM learns we ship Bun
ci / rust-arm64 (pull_request) Successful in 1m33s
ci / bun-nix (pull_request) Successful in 1m33s
ci / web (pull_request) Successful in 2m5s
ci / docs-site (pull_request) Successful in 2m20s
ci / rust (pull_request) Successful in 5m58s
nix / flake (pull_request) Successful in 14m59s
compliance/vendored-components.md records, per vendored/bundled component,
where the pin lives, how it updates, and which feed to watch — the CRA
Art. 13(5) due-diligence evidence (S4 in the roadmap). Retention verified
while writing it: Gitea serves the full release history v0.17.x -> current,
stable sysext feeds publish KEEP=0, flatpak rsyncs without --delete.

The manual SBOM fragment gains the bundled Bun 1.3.14 runtime (portable
bun.exe in the Windows installer for the console + plugin runner — it was
in no lockfile and no SBOM) and stops hardcoding the gamescope patch count
at 3 when the series is at 9. SECURITY.md gets the one sentence Annex I
Part II asks for: security fixes are free, prompt, and ride patch releases
— which the stable channel already did, unwritten.
2026-08-14 18:14:32 +02:00
enricobuehler 39b9e9e276 chore(docs-site): current deps all around — the 67 leftover advisories all live inside @unom/ui's payload chain
bun update (fumadocs 16.14, tanstack ~1.170, react 19.2) plus @unom/ui 0.8.16
-> 0.9.2 and @unom/app-ui 0.1 -> 0.2.1. Build, tsc --noEmit and a served
smoke test all pass. The audit stays non-blocking: every remaining advisory
is pinned inside @unom/ui's own dependency tree (@payloadcms/* -> fast-uri/
image-size/sharp, next 16.x, sass -> immutable) — nothing bumpable from this
lockfile, and overrides would fork what the CMS actually ships. The comment
in audit.yml now names that blocker instead of the stale dompurify/node-tar
list.
2026-08-14 18:14:29 +02:00
enricobuehler 79114891df fix(vdisplay): exclusive topology left the KDE panel lit under a gamescope spawn — DPMS it dark
ci / bun-nix (pull_request) Successful in 1m42s
ci / web (pull_request) Successful in 3m41s
ci / rust (pull_request) Successful in 23m56s
ci / rust-arm64 (pull_request) Successful in 6m2s
android / android (pull_request) Successful in 7m12s
ci / docs-site (pull_request) Successful in 7m45s
A bare-spawn gamescope session is its own headless compositor, so it was the one
Linux route that never consulted effective_topology(): on a KDE desktop box the
physical panel kept showing the idle desktop for the whole stream while the
policy said exclusive. The KWin route's mechanism (disable the physicals) is
closed on this route — KWin refuses a configuration with zero enabled outputs
and no output on that desktop is ours to leave enabled — so the honest
translation is DPMS: the desktop stays exactly where it is, the panels go dark,
local input wakes them, and stream input never does (it enters gamescope's own
EIS socket, not KWin's libinput).

New kwin_dpms module drives the vendored org_kde_kwin_dpms protocol in-process
over the desktop's own Wayland (the kwin_output_mgmt stack and rationale), with
a kscreen-doctor --dpms fallback on kwin.rs's shared verdict/budget. The darken
is refcounted host-wide rather than floated through the registry's per-group
restore, because every gamescope spawn is its own group — the float alone would
re-light the panel when the first of two concurrent spawns ends. Each exclusive
spawn registers the release as its per-display topology restore, so the
registry still times every release (§6.1) and the last one out re-lights only
what the first darken actually turned off. Crash-safe by construction: DPMS is
non-persistent, so a dead host leaves nothing to journal — the panel re-lights
on the next local input.

Managed and Attach are deliberately untouched: managed's takeover already
stopped the desktop, and attach may be mirroring a gamescope that is itself
driving the physical panel.
2026-08-14 18:11:50 +02:00
enricobuehler d0a3eca7b8 Merge pull request 'A per-user Playnite install is invisible to a SYSTEM host, and one tile killed the whole library' (#225) from fix/playnite-launcher-resolve into main
arch / build-publish (push) Successful in 9m22s
deb / build-publish-host (push) Successful in 5m46s
ci / docs-site (push) Successful in 3m54s
deb / build-publish-gamescope (push) Successful in 33s
ci / rust-arm64 (push) Successful in 4m33s
ci / rust (push) Successful in 5m19s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 11s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 8s
docker / deploy-docs (push) Successful in 52s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 8s
windows-host / package (push) Successful in 16m20s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 13s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 1m34s
windows-host / winget-source (push) Skipped
deb / build-publish (push) Successful in 4m0s
windows-host / canary-manifest (push) Successful in 38s
deb / smoke-install (push) Successful in 6m25s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 11s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 25s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Successful in 17m28s
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Successful in 20m3s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 1m5s
android / android (push) Successful in 7m28s
deb / build-publish-client-arm64 (push) Successful in 3m31s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 2m2s
ci / web (push) Successful in 1m4s
ci / bun-nix (push) Successful in 1m30s
docker / builders-arm64cross (push) Successful in 50s
2026-08-14 16:07:37 +00:00
enricobuehler bf741f8693 fix(library): a per-user Playnite install is invisible to a SYSTEM host, and one tile killed the library
ci / web (pull_request) Successful in 1m13s
ci / bun-nix (pull_request) Successful in 1m25s
ci / rust (pull_request) Successful in 4m18s
ci / docs-site (pull_request) Successful in 4m27s
ci / rust-arm64 (pull_request) Successful in 4m39s
android / android (pull_request) Successful in 7m42s
Syncing the Playnite plugin failed outright:

  PUT /library/provider/playnite failed: entries[9]: launch.value for kind
  launcher_ui names a launcher this host cannot open (playnite)

Two defects, and the second is why it cost every game rather than one tile.

1. The host looked for Playnite in the wrong registry hive and the wrong
   profile. `playnite_fullscreen_exe()` read HKEY_CURRENT_USER, then fell back
   to %LOCALAPPDATA% — but the Windows host is a LocalSystem service, so its
   HKCU is the SYSTEM hive (S-1-5-18) and its %LOCALAPPDATA% is
   C:\Windows\System32\config\systemprofile\AppData\Local. Playnite installs
   per-user by default, so both lookups miss on a default install. The doc
   comment reasoned correctly that Playnite is per-user and then read the one
   HKCU that cannot see it.

   It also hardcoded `…\Uninstall\Playnite`. 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` — so
   that key matched nothing anywhere.

   Now: every loaded hive under HKEY_USERS plus both HKLM views, matched on
   DisplayName rather than key name, then `C:\Users\*\AppData\Local\Playnite`
   for the conventional install (and for a user whose hive is not loaded).

2. One unopenable tile 400'd the whole reconcile. The Playnite plugin appends
   a single launcher tile beside its games, so refusing the payload cost the
   operator the entire library — the same shape as the unservable-cover bug
   that sanitize_art_paths was introduced to fix, on the launch side this time.

   `valid_launcher_ui` conflated two different failures. Split into
   `known_launcher_ui` (vocabulary — a plugin bug, still a hard 400, because
   the author has no other way to find out) and `resolvable_launcher_ui`
   (environment — the launcher just is not installed here, which is a fact
   about the box). `sanitize_launcher_entries` drops only the latter, with one
   warn, and the games sync.
2026-08-14 15:28:41 +02:00
enricobuehler ea5afbaa8c Merge pull request '0.28.1 notes — the Mac microphone loop is a headline fix the notes had never heard of' (#224) from worktree-release-0281-notes into main
decky / build-publish (push) Successful in 43s
arch / build-publish (push) Successful in 7m39s
ci / rust-arm64 (push) Successful in 6m17s
windows-host / package (push) Successful in 13m46s
windows-host / canary-manifest (push) Skipped
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Successful in 23m15s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Successful in 23m25s
windows-host / winget-source (push) Successful in 20s
windows-client / client (arm64, --no-default-features, aarch64-pc-windows-msvc, C:\t-a64) (push) Successful in 3m31s
android / android (push) Successful in 6m39s
ci / web (push) Successful in 1m9s
ci / docs-site (push) Successful in 1m31s
linux-client-screenshots / screenshots (push) Successful in 3m50s
sbom / sbom (push) Successful in 22s
deb / build-publish-host (push) Successful in 6m58s
deb / build-publish (push) Successful in 7m11s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 21s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 23s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 14s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 13s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 13s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 22s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 18s
docker / builders-arm64cross (push) Successful in 13s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 24s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 23s
deb / build-publish-client-arm64 (push) Successful in 1m24s
deb / build-publish-gamescope (push) Successful in 1m30s
docker / deploy-docs (push) Successful in 20s
android-screenshots / screenshots (push) Successful in 2m2s
windows-client / client (x64, , x86_64-pc-windows-msvc, C:\t) (push) Successful in 6m58s
ci / rust (push) Successful in 5m30s
apple / swift (push) Successful in 2m4s
web-screenshots / screenshots (push) Successful in 4m45s
flatpak / build-publish (push) Successful in 8m47s
apple / distribute (push) Successful in 12m34s
deb / smoke-install (push) Successful in 10m14s
ci / bun-nix (push) Successful in 5m52s
apple / screenshots (push) Successful in 8m59s
2026-08-14 11:26:53 +00:00
enricobuehler 832a5ffd8d docs(release): the Mac microphone loop is a headline fix, and the notes had never heard of it
ci / rust-arm64 (pull_request) Successful in 3m5s
ci / web (pull_request) Successful in 2m50s
ci / bun-nix (pull_request) Successful in 38s
ci / docs-site (pull_request) Successful in 2m19s
ci / rust (pull_request) Successful in 6m56s
Ten more commits landed after the 0.28.1 release commit — the deb image fix, the
two macOS audio ones (#221 + #223) and the TV screenshot automation — so the
release paperwork no longer described the release.

CHANGELOG: 50 -> 60 commits since v0.28.0. Nothing else moves; the version table
is unchanged on every row, re-verified against the tag (`include/`,
`crates/pf-driver-proto`, `plugin-kit/package.json` and `sdk/` are all still
byte-identical to v0.28.0, so the C ABI stays 19). #221 brought its own CHANGELOG
section, so the technical half already covered it.

NOTES: the user-facing file had no mention of the macOS fault at all, and it is
headline-grade — streaming from a Mac with the mic on cut audio AND froze input
on a ~2.5 s metronome, with turning the microphone off as the only workaround. It
now leads the summary paragraph, has a TL;DR line and a full Fixed entry
explaining the loop in plain terms (a mic that cannot run echo cancellation, each
failed attempt knocking out the working path and thereby triggering the next).

The TL;DR was also trimmed from nine multi-line bullets to seven one-liners.
`docs/releases/README.md` asks for 3-6, and this release has an unusual number of
genuinely severe entries — seven is the honest floor without hiding one, and the
long-form detail was already duplicated below in Fixed, which is where it belongs.
The Apple stats-overlay and Apple TV colour bullets lost their TL;DR slots and
keep their Fixed entries.

`SessionAudio.start()` being asynchronous on macOS is added to the notes' `For
developers` paragraph — it is the one embedder-visible edge in #223, and an
embedder who only reads the notes would otherwise meet it at runtime.

Play notes are untouched and still accurate: the only commit to touch
clients/android since is `b6b3c10c`, which is screenshot CI, not app behaviour.

Gates on this tree: fmt clean, `cargo metadata --locked` consistent,
`cargo test -p punktfunk-core` 210 passed, C ABI harness abi_version=19,
`api/openapi.json` and the docs-site copy still byte-identical.
2026-08-14 13:15:08 +02:00
enricobuehler 76c677a8f8 Merge pull request 'The TV storefronts were the only ones with no automated screenshot captures' (#222) from worktree-store-shots-tv-automation into main
apple / screenshots (push) Successful in 8m26s
ci / rust-arm64 (push) Successful in 6m15s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 24s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 17s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 18s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 10s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 9s
docker / builders-arm64cross (push) Successful in 17s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 57s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 8s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 11s
ci / docs-site (push) Successful in 8m18s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 1m49s
docker / deploy-docs (push) Successful in 14s
ci / web (push) Successful in 9m5s
android / android (push) Successful in 12m53s
apple / distribute (push) Successful in 10m48s
ci / rust (push) Canceled after 14m52s
apple / swift (push) Successful in 1m57s
ci / bun-nix (push) Successful in 43s
Reviewed-on: #222
2026-08-14 11:11:46 +00:00
enricobuehler 7cb70bf6ea Merge pull request 'Apple audio engine starts leave the main thread — input never waits on the audio server' (#223) from worktree-macos-mic-rebuild-loop into main
apple / swift (push) Canceled after 18s
apple / screenshots (push) Canceled after 0s
apple / distribute (push) Canceled after 0s
ci / rust (push) Canceled after 38s
ci / rust-arm64 (push) Canceled after 14s
ci / web (push) Canceled after 0s
ci / docs-site (push) Canceled after 0s
ci / bun-nix (push) Canceled after 0s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Canceled after 5s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Canceled after 0s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Canceled after 0s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Canceled after 0s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Canceled after 0s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Canceled after 0s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Canceled after 0s
docker / builders-arm64cross (push) Canceled after 0s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Canceled after 0s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Canceled after 0s
docker / deploy-docs (push) Canceled after 0s
2026-08-14 11:05:55 +00:00
enricobuehler b6b3c10cb5 ci(screenshots): the TV storefronts were the only ones with no automated captures
ci / bun-nix (pull_request) Successful in 1m49s
ci / rust-arm64 (pull_request) Successful in 4m41s
apple / distribute (pull_request) Skipped
apple / screenshots (pull_request) Skipped
ci / web (pull_request) Successful in 3m53s
apple / swift (pull_request) Successful in 2m3s
ci / docs-site (pull_request) Successful in 5m11s
android / android (pull_request) Successful in 11m24s
ci / rust (pull_request) Failing after 10m14s
Google Play's Android TV slot needs 16:9 1920x1080 shots and the App Store
needs Apple TV 1920x1080 — neither existed as automation output:

- apple.yml screenshots job now runs the tvos leg. The harness supported it
  all along (tools/screenshots.sh tvos); what the job was missing is the
  Tier-3 tvOS xcframework slices (nightly + -Zbuild-std, same recipe the
  distribute job uses on this runner) and an explicit scene list — the
  gamepad-console scenes are compiled out on tvOS, and an UNKNOWN scene
  name falls back to a normal app launch, which would silently capture the
  real empty app. Still best-effort: a tvOS hiccup warns, never reds.
- TvScreenshotTest renders the console scenes + the stream HUD at Android
  TV geometry (w960dp-h540dp-television-xhdpi = native 1920x1080, no
  resampling), prefixed tv- so the artifact separates the form factors.
  Verified locally: 6 scenes, all 1920x1080.

android-screenshots.yml needs no change — it runs the whole unit-test task
and uploads the whole roborazzi output dir.
2026-08-14 12:55:03 +02:00
enricobuehler 1a8fa2282f fix(apple): engine starts leave the main thread — input never waits on the audio server
ci / rust (pull_request) Successful in 5m26s
apple / swift (pull_request) Successful in 1m57s
apple / screenshots (pull_request) Skipped
apple / distribute (pull_request) Skipped
ci / rust-arm64 (pull_request) Successful in 5m7s
ci / bun-nix (pull_request) Successful in 2m11s
ci / web (pull_request) Successful in 3m32s
ci / docs-site (pull_request) Successful in 3m32s
An AVAudioEngine start can block on the audio server for seconds (~1.9 s
per attempt in the 2026-08-14 field case), and macOS captures and sends the
stream's input from the main thread — so every device-change rebuild, loop
or no loop, froze the stream's input for the length of the rebuild, and a
mic-on session start stalled the UI at connect.

All engine lifecycle work (start/startEngines and below, teardown, rebuild)
now runs on a per-session serial engineQueue; the main queue keeps only the
trigger bookkeeping — debounce, backoff, and the retry ladder — which is
cheap by construction. The rebuild path splits accordingly: rebuildFire
(main: bookkeeping, reads the config) → performRebuild (engineQueue: the
actual teardown + start) → rebuildFailed (main: ladder scheduling; a fresh
trigger already queued wins over a retry).

Confinement moves with the work: ring, startConfig and enginesAttempted go
under the existing stateLock (start paths write on engineQueue, stats and
the revive gate read elsewhere); combinedGate is engineQueue-confined; the
permission-grant continuation lands on engineQueue instead of main. The
engines were already lock-guarded and stopped cross-thread by stop(), and
every start path already re-checks the stop flag after publishing, so the
in-flight-start-vs-stop race keeps its existing resolution.

Embedder-visible edge: SessionAudio.start() is now asynchronous on macOS
too (it always was on iOS/tvOS) — playback is live shortly after the call,
not on return; stats is safe from any thread.

Gates: swift build + 295 tests 0 failures (macOS), full-package
arm64-apple-ios17.0 typecheck.
2026-08-14 12:49:48 +02:00
enricobuehler d669064dc0 Merge pull request 'The macOS device-change recovery answered itself — mic-on streams cut audio and input every ~2.5 s' (#221) from worktree-macos-mic-rebuild-loop into main
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 2m43s
ci / web (push) Successful in 3m20s
docker / deploy-docs (push) Successful in 37s
apple / screenshots (push) Canceled after 3m35s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 9m4s
ci / docs-site (push) Successful in 3m38s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 7m25s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 7m12s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 4m36s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 7m26s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 5m46s
apple / distribute (push) Successful in 10m35s
ci / bun-nix (push) Successful in 17s
ci / rust (push) Successful in 6m11s
docker / builders-arm64cross (push) Successful in 2m57s
apple / swift (push) Successful in 2m4s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 48s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 1m12s
ci / rust-arm64 (push) Successful in 3m5s
Reviewed-on: #221
2026-08-14 10:49:37 +00:00
enricobuehler d4ad8be6bf Merge pull request 'The gamescope deb image never needed x11-xcb until we started building the WSI layer' (#220) from worktree-gamescope-deb-x11xcb into main
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Canceled after 0s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Canceled after 0s
docker / builders-arm64cross (push) Canceled after 0s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Canceled after 0s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Canceled after 0s
docker / deploy-docs (push) Canceled after 0s
ci / rust (push) Canceled after 16s
ci / web (push) Canceled after 18s
ci / bun-nix (push) Canceled after 19s
ci / rust-arm64 (push) Canceled after 16s
ci / docs-site (push) Canceled after 19s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Canceled after 27s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Canceled after 0s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Canceled after 0s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Canceled after 0s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Canceled after 0s
Reviewed-on: #220
2026-08-14 10:49:24 +00:00
enricobuehler e0c10bad85 fix(apple): the macOS device-change recovery answered itself — mic-on streams cut audio and input every ~2.5 s
ci / bun-nix (pull_request) Successful in 22s
ci / docs-site (pull_request) Successful in 1m15s
ci / rust-arm64 (pull_request) Successful in 1m17s
ci / web (pull_request) Successful in 1m25s
apple / swift (pull_request) Successful in 2m6s
apple / distribute (pull_request) Skipped
apple / screenshots (pull_request) Skipped
ci / rust (pull_request) Successful in 4m33s
The voice-processing engine cannot start on some input devices (field case:
a 6-channel interface — 'combined engine failed to start', every time). The
device-change recovery re-tried it on every rebuild, and the failed attempt's
HAL churn (VPIO builds and tears down an aggregate device) stopped the healthy
fallback engines, which posted the AVAudioEngineConfigurationChange that
scheduled the next rebuild: a self-sustaining ~2.5 s loop for the session's
whole life. Each ~1.9 s rebuild runs on the main thread — where macOS input
capture and sending live — so the stream's INPUT cut out on the same beat,
while video (own socket, own threads) ran untouched; the wire signature
matched network loss and the host's METRONOMIC heuristic pointed at the
display stack, which is what made the field report so misleading.

Three defenses, layered because no single one covers every feedback shape:
a VPIO start failure latches per input device (CombinedTopologyGate — a
rebuild goes straight to the split topology; a different default input earns
exactly one fresh attempt); a configuration change posted by an engine that
is RUNNING is the rebuild's own echo and is ignored (an engine stops itself
before posting, so a live poster was already restarted); and rebuilds that
chain anyway back off exponentially (RebuildBackoff, 0.5 s floor doubling to
a 30 s cap, reset by 10 s of quiet) with a WARN that names the condition.

Both policies extracted to AudioRebuildPolicy.swift where a unit test can
reach them: 7 new tests, the loop test plant-the-defect verified (the shipped
flat floor produces 800 rebuilds in the 10-minute sim; the ladder ≤ 25, and
responsiveness after quiet is asserted). iOS/tvOS semantics untouched.

Gates: swift build + 295 tests 0 failures (macOS), full-package
arm64-apple-ios17.0 typecheck.
2026-08-14 12:40:51 +02:00
enricobuehler 1b28a7f7f1 fix(ci): the gamescope deb image never needed x11-xcb until we started building the WSI layer
ci / docs-site (pull_request) Successful in 1m28s
ci / bun-nix (pull_request) Successful in 2m57s
ci / web (pull_request) Successful in 3m9s
ci / rust-arm64 (pull_request) Successful in 5m17s
ci / rust (pull_request) Successful in 8m33s
The v0.28.1 deb leg failed for real, and the package it costs is the whole
punktfunk-gamescope .deb:

    gamescope/layer/meson.build:3:14: ERROR: Dependency "x11-xcb" not found, tried pkgconfig

Not a flake and not the pin. v0.28.1 flipped
`-Denable_gamescope_wsi_layer=true` in build-punktfunk-gamescope.sh (it was off
before, on the recorded and false premise that the layer is version-independent
of the compositor). The layer is a separate meson subdir with its own dependency
set, and it wants x11-xcb — which the compositor never did. So an image that had
been sufficient for every previous release stopped being sufficient the moment
the layer started building, and nothing named the new dep anywhere.

Debian is the only channel that has to name it: Arch's libx11 and Fedora's
libX11-devel both ship x11-xcb.pc themselves, which is why arch.yml and rpm.yml
build the same tree fine and only the trixie image came up short.

Asserted as well as installed. The image already asserts the wayland-server
floor at build time, on the argument that the one version deciding whether the
image can do its job should fail loudly HERE rather than inside a deb.yml run —
and this is the same class, only worse: a missing x11-xcb does not fail the
compositor build, it fails the layer's, and the layer is the only route to an
HDR10 swapchain for a nested game. Losing it silently produces a package that
looks completely healthy and denies every game HDR, which is precisely the
failure v0.28.1 exists to end. The assertion means the next dependency the layer
grows fails at image build instead of mid-release.

ORDERING, for whoever lands this: docker.yml rebuilds the image on a push to
main (its key hashes the ci/ tree, so this change busts it), and deb.yml's
gamescope job consumes `:latest`. Let the image publish before the deb job that
needs it runs — on a release cut that means merging this, letting docker.yml
finish, and only then pushing the tag. The failed job saved no cache, so the tag
run rebuilds against the new image rather than restoring the broken state.

NOT verified locally: no Docker on this machine, so the image was not built and
the layer was not compiled here. The package name is confirmed against Debian's
own package index (libx11-xcb-dev ships x11-xcb.pc, and exists in trixie), and
the assertion added here is what proves it in CI — if the name were wrong the
image build fails loudly instead of the deb leg failing quietly.
2026-08-14 12:03:55 +02:00
enricobuehler ceb081f045 Merge pull request '0.28.1' (#219) from worktree-release-0281 into main
audit / bun-audit (web) (push) Successful in 48s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 33s
audit / c-abi-asan (push) Successful in 7m51s
docker / deploy-docs (push) Successful in 33s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 46s
apple / distribute (push) Successful in 11m17s
audit / pnpm-audit (push) Successful in 1m49s
deb / build-publish (push) Successful in 4m36s
deb / build-publish-host (push) Successful in 5m11s
deb / build-publish-client-arm64 (push) Successful in 3m22s
apple / screenshots (push) Successful in 6m51s
docker / builders-arm64cross (push) Successful in 19s
arch / build-publish (push) Successful in 8m11s
deb / build-publish-gamescope (push) Failing after 1m41s
ci / rust-arm64 (push) Successful in 1m50s
audit / miri (push) Successful in 5m53s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 8s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 8s
deb / smoke-install (push) Successful in 2m16s
windows-client / client (x64, , x86_64-pc-windows-msvc, C:\t) (push) Successful in 6m47s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 10s
ci / web (push) Successful in 1m6s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 15s
windows-client / client (arm64, --no-default-features, aarch64-pc-windows-msvc, C:\t-a64) (push) Successful in 3m6s
ci / bun-nix (push) Successful in 35s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 1m20s
windows-host / package (push) Successful in 13m7s
windows-host / winget-source (push) Skipped
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 1m23s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Successful in 18m23s
audit / cargo-audit (push) Successful in 1m37s
android / android (push) Successful in 11m50s
windows-host / canary-manifest (push) Successful in 28s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 1m21s
ci / docs-site (push) Successful in 1m22s
flatpak / build-publish (push) Successful in 10m34s
apple / swift (push) Successful in 1m56s
audit / bun-audit (plugin-kit) (push) Successful in 1m12s
audit / license-gate (push) Successful in 7m31s
ci / rust (push) Successful in 20m19s
audit / bun-audit (sdk) (push) Successful in 1m9s
nix / flake (push) Failing after 16m12s
audit / docs-site-audit (push) Successful in 20s
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Successful in 20m27s
Reviewed-on: #219
2026-08-14 09:24:20 +00:00
enricobuehler 0870f81148 release: 0.28.1 — version bump, notes, CHANGELOG, Play notes
ci / bun-nix (pull_request) Successful in 58s
ci / web (pull_request) Successful in 6m9s
ci / docs-site (pull_request) Successful in 6m22s
ci / rust (pull_request) Successful in 14m57s
windows-client / client (x64, , x86_64-pc-windows-msvc, C:\t) (pull_request) Successful in 6m39s
nix / flake (pull_request) Successful in 15m55s
ci / rust-arm64 (pull_request) Successful in 9m42s
apple / swift (pull_request) Successful in 2m0s
apple / screenshots (pull_request) Skipped
apple / distribute (pull_request) Skipped
windows-client / client (arm64, --no-default-features, aarch64-pc-windows-msvc, C:\t-a64) (pull_request) Successful in 3m6s
android / android (pull_request) Successful in 5m48s
50 commits since v0.28.0 (32 non-merge). Cut from origin/main f8361f3e.

THE NUMBER: 0.28.1 is defensible but not free. Three `feat(...)` commits landed
since the tag — the "unpair all" button and its two endpoints, the Apple
gamepad-UI host menu, and the tvOS present-floor levers. That is not the shape
of v0.28.0's cut (17 feats, a packager-visible default flip, an MSRV rise and a
deletion that empties the library grid), and none of the three changes a
contract: every one is additive, and the version table is unchanged on every row
an embedder, packager or driver author reads. `scripts/ci/pf-version.sh` derives
the canary base as latest-stable + one minor, so 0.28.1 and 0.29.0 both leave
canary on 0.29.x and neither collides.

NOTHING BREAKS, and this was measured rather than assumed, twice — before and
after the four late PRs. `include/` is byte-identical to the v0.28.0 tag, so the
C ABI stays 19; `crates/pf-driver-proto`, `plugin-kit/package.json` and `sdk/`
show no diff against the tag at all. The one Rust-visible change is an addition:
`punktfunk_core::client::FLUSH_COOLDOWN` went `pub(crate)` -> `pub`, so the host
can compare against the constant instead of a copy of the number.

ONE DEFECT FOUND AND FIXED WHILE PREPARING:

`docs-site/public/openapi.json` had drifted for the THIRD time in two release
cycles. It was still stamped 0.27.0 and missing both new collection deletes,
while `api/openapi.json` sits at 0.28.0. v0.28.0 fixed this once (it was five
releases stale at 0.21.0) and it drifted again inside that same cycle. Re-synced;
the two files are byte-identical again, and re-checked after the rebase. The copy
is a documented manual step (CONTRIBUTING.md) that nothing in CI enforces — three
drifts is the argument for gating it, and that gate is not in this commit.

CHANGELOG: the in-development section carried four topics and the late PRs
brought four more of their own; the remaining twenty-one commits had none. Added
the version table (every row measured, not copied forward), an explicit empty
breaking-changes verdict, and sections for the management API's two collection
deletes, the Hyprland/Sway cursor-mode negotiation, the gamescope WSI layer we
now ship ourselves, the 203-nit SDR anchor, the Apple stats/colour faults, the
Skia loader-version regression, the AV1 level sentinel, the stats stage-line
partition, the two host warnings that named the wrong subsystem, and the
docs-site openapi drift.

NOTES: `docs/releases/v0.28.1.md` follows the post-v0.25.0 split — user-facing
only, TL;DR first, internals left to the CHANGELOG link, which points at the
v0.28.1 TAG rather than main. The two Windows headliners lead it: the Steam
add-on publishing nothing (a 0.28.0 regression that emptied the grid) and an idle
host wrecking a locally played game. `Before you update` carries the two
Sound-settings changes an operator will see and could read as defects, plus the
0.27-and-older pointer at v0.28.0's action items.

luxus is credited three times: in the lead-in the Discord embed shows, inline on
the fix itself, and in a new `## Thanks` section — the linger crash was his find,
his patch and his on-glass proof, and it ships as he wrote it. The CHANGELOG
keeps its own credit with the overlay#9 link.

Play notes are 436 characters against the 500 cap and cover only what changed in
the Android app, which this release is still one commit of.

GATES, all green on this tree after the rebase: `cargo fmt --all --check` clean;
`cargo metadata --locked` consistent; Cargo.lock diff is versions-only, 36/36
lines, zero non-version lines against the new base; `cargo test -p punktfunk-core`
210 passed; the C ABI harness passes printing abi_version=19 (needs
`LIBRARY_PATH=/opt/homebrew/opt/opus/lib` on macOS — a link path, not a defect);
the repo pre-push hook exits 0.
2026-08-14 11:22:08 +02:00
enricobuehler f8361f3e6f Merge pull request 'The NixOS module started a second host in root's systemd, which stole the ports from the real one' (#218) from worktree-nixos-module-user-scoping into main
docker / deploy-docs (push) Canceled after 3m33s
ci / web (push) Successful in 1m10s
docker / builders-arm64cross (push) Successful in 9s
ci / rust-arm64 (push) Successful in 1m25s
nix / flake (push) Canceled after 4m8s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 7s
ci / bun-nix (push) Successful in 15s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 6s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 7s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 8s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 8s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 8s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 9s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 15s
ci / rust (push) Canceled after 6m29s
ci / docs-site (push) Canceled after 5m54s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 15s
Reviewed-on: #218
2026-08-14 09:17:54 +00:00
enricobuehler e8bc10bf0c Merge remote-tracking branch 'origin/main' into worktree-nixos-module-user-scoping
ci / rust-arm64 (pull_request) Successful in 3m45s
ci / docs-site (pull_request) Successful in 3m49s
ci / bun-nix (pull_request) Successful in 24s
ci / rust (pull_request) Successful in 18m12s
nix / flake (pull_request) Successful in 15m35s
ci / web (pull_request) Successful in 1m1s
# Conflicts:
#	CHANGELOG.md
2026-08-14 11:16:49 +02:00
enricobuehler 4499313749 fix(nix): the module started a second host in root's systemd, stealing the ports from the real one
ci / docs-site (pull_request) Successful in 1m17s
ci / bun-nix (pull_request) Successful in 1m33s
nix / flake (pull_request) Failing after 1m23s
ci / rust (pull_request) Canceled after 1m54s
ci / rust-arm64 (pull_request) Canceled after 2m3s
ci / web (pull_request) Successful in 1m8s
`systemd.user.*` has no per-user form in NixOS — it installs units into every
user's manager. With `host.autoStart` adding them to `default.target`, that
included root, whose `user@0.service` exists the moment anybody SSHes in as
root. Root's host won the race for the fixed ports and the desktop user's copy
crash-looped forever on `bind RTSP 48010: Address already in use`.

Every other listener binds first and logs success, so the log reads like a
clash with an unrelated program; a second copy of itself running as root is the
last thing you look for. `host.users` did not help — it only granted
input/punktfunk group membership and never scoped the units.

Render `ConditionUser=` on all four user units from `host.users`. Entries are
written `|user`: the pipe makes each a triggering condition, which systemd ORs,
where plain repeated `ConditionUser=` lines are ANDed and would match nobody.
With `host.users` empty, fall back to `!@system` — still keeps root out while
leaving the manual `systemctl --user enable --now` route working for a login.

module-check.nix gains three assertions covering both branches and web-init
keeping its non-triggering ConditionPathExists alongside the new condition.
They run in nix.yml's eval leg, and were confirmed to fail against the unfixed
module (2 of 23) before being committed. Verified on the box that found this:
root force-starting the host now yields ConditionResult=no.
2026-08-14 11:00:43 +02:00
enricobuehler 784f880fbf Merge pull request 'Helldivers 2 tanked on an IDLE host: the pad DualSense speaker stayed visible and the recording default was parked forever' (#217) from worktree-hd2-idle-recording-default into main
deb / smoke-install (push) Successful in 9m33s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 8s
ci / rust (push) Successful in 18m45s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Successful in 17m52s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 47s
deb / build-publish (push) Successful in 4m49s
ci / rust-arm64 (push) Successful in 1m28s
deb / build-publish-host (push) Successful in 5m18s
ci / bun-nix (push) Successful in 27s
ci / web (push) Successful in 1m45s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 2m3s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 1m11s
arch / build-publish (push) Failing after 2m47s
ci / docs-site (push) Successful in 1m55s
deb / build-publish-client-arm64 (push) Successful in 5m23s
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Failing after 1m39s
deb / build-publish-gamescope (push) Failing after 1m48s
docker / builders-arm64cross (push) Successful in 33s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 10s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 10s
windows-host / package (push) Successful in 13m9s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 8s
windows-host / winget-source (push) Skipped
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 11s
windows-host / canary-manifest (push) Successful in 20s
android / android (push) Successful in 13m47s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 10s
docker / deploy-docs (push) Failing after 6m58s
2026-08-14 08:41:12 +00:00
enricobuehler 8ca4c6eb0e Merge pull request 'Hyprland/Sway black client — the wlr-family backends asserted a cursor mode instead of negotiating it' (#216) from worktree-hyprland-cursor-mode-negotiation into main
deb / build-publish (push) Canceled after 1m17s
docker / deploy-docs (push) Canceled after 0s
deb / build-publish-host (push) Canceled after 37s
deb / build-publish-gamescope (push) Canceled after 19s
deb / build-publish-client-arm64 (push) Canceled after 0s
deb / smoke-install (push) Canceled after 0s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Canceled after 11s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Canceled after 1s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Canceled after 0s
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Canceled after 0s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Canceled after 12s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Canceled after 0s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Canceled after 0s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Canceled after 0s
windows-host / package (push) Canceled after 1m53s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Canceled after 0s
docker / builders-arm64cross (push) Canceled after 0s
windows-host / canary-manifest (push) Canceled after 0s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Canceled after 0s
windows-host / winget-source (push) Canceled after 0s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Canceled after 0s
arch / build-publish (push) Failing after 33s
ci / web (push) Successful in 1m11s
ci / rust-arm64 (push) Successful in 1m21s
android / android (push) Canceled after 1m50s
ci / rust (push) Canceled after 1m37s
ci / docs-site (push) Canceled after 1m42s
ci / bun-nix (push) Canceled after 1m42s
2026-08-14 08:39:18 +00:00
enricobuehler 13aa59c575 fix(vdisplay): the wlr-family backends asserted a cursor mode instead of negotiating it, so the portal refused the call
ci / bun-nix (pull_request) Successful in 24s
ci / docs-site (pull_request) Successful in 1m13s
ci / web (pull_request) Successful in 3m27s
android / android (pull_request) Successful in 4m2s
ci / rust-arm64 (pull_request) Successful in 4m40s
ci / rust (pull_request) Successful in 10m47s
Hyprland and wlroots both hardcoded portal `CursorMode::Metadata` whenever the
session had negotiated the cursor channel, and never asked the backend what it
supports. That is not a soft failure: xdg-desktop-portal's FRONTEND validates the
requested mode against the backend's `AvailableCursorModes` and fails the call
with `"Unavailable cursor mode %x"` before the backend ever sees it.

So a cursor-forward session (desktop mouse mode) died at `select_sources`,
surfacing as "pipeline build failed" and a black client, with
`unavailable cursor mode 4` in the portal log. Field report 2026-08-14.

MEASURED on .21 the same day, and it is worse than the report suggested: against
a LIVE Hyprland 0.56.2 with xdg-desktop-portal-hyprland 1.4.1 and
xdg-desktop-portal 1.22.1 — all current — `AvailableCursorModes` reads **3**
(Hidden|Embedded) on both the backend impl interface and the frontend. xdph does
not offer the metadata cursor at all, so this broke EVERY cursor-forward session
on current Hyprland, not merely on old installs. Updating the portal would not
have helped. xdpw is the same from the other end: its screencast.c refuses
METADATA outright.

pf-capture's own portal path has always negotiated (`choose_cursor_mode`); this
restates that ladder in pf-vdisplay, which may not depend on pf-capture. The
downgrade is graceful rather than merely survivable: with the portal on Embedded
no `SPA_META_Cursor` arrives, so the host feeds the cursor channel nothing and a
cursor-forward client draws nothing of its own — one pointer, not two.

`PUNKTFUNK_PORTAL_CURSOR_MODE=auto|hidden|embedded|metadata` pins the preference
for a backend that advertises a mode it implements badly, which negotiation
cannot detect. It is a preference only: pins run the same ladder, so no value can
re-create the refused request.

The module is declared unconditionally so its ladder tests run on every CI leg
rather than only the one that compiles `mod hyprland` — including a Linux-only
test pinning our bit values against ashpd's enum, verified non-vacuous by
planting a wrong discriminant (ashpd answers 4 for Metadata, the number in the
report). The regression test uses 3, the bitfield measured on glass. Linux: 225
tests pass, clippy --all-targets -D warnings clean.
2026-08-14 10:27:14 +02:00
enricobuehler 652de8b5e0 docs(changelog): the pad-audio DualSense speaker hides while no client pad is attached
ci / bun-nix (pull_request) Successful in 33s
ci / rust-arm64 (pull_request) Successful in 1m21s
ci / docs-site (pull_request) Successful in 1m14s
android / android (pull_request) Successful in 4m21s
ci / rust (pull_request) Successful in 8m45s
ci / web (pull_request) Successful in 6m32s
2026-08-14 10:26:16 +02:00
enricobuehler ec36597058 fix(audio/windows): the pad-audio DualSense speaker hides while no client pad is attached — idle libScePad titles stalled on it
The per-pad endpoint is stamped to be indistinguishable from a real
DualSense speaker — that is the feature during a pad session (libScePad
titles route haptics audio at it) and a trap the rest of the time: the
endpoint is pre-provisioned at EVERY host start and stayed visible
forever, so an idle Helldivers 2 found it by identity, engaged its
DualSense-haptics path against a device nothing services, and dropped to
2–5 FPS 1% lows — host idle, no controller plugged in, no session ever
run (field-confirmed 2026-08-14: the reporter isolated the 'DualSense
speaker' and disabling it in mmsys.cpl restored full performance).

That manual remedy is now automatic: the endpoint parks HIDDEN
(DEVICE_STATE_DISABLED, IPolicyConfig::SetEndpointVisibility — the call
behind mmsys.cpl's own Disable, vtable slot pinned next to the
SetDefaultEndpoint we already bind) whenever no client pad is attached.
Provisioning hides it at startup, a PUNKTFUNK_PAD_AUDIO=0 host hides
leftovers from earlier runs, and the per-pad streamer shows it for
exactly the pad's lifetime — to a game, a DualSense arriving and
leaving. The devnode, driver binding and stamps stay put (registry-based
resolution finds a disabled endpoint at the next boot), so the flips
raise no PnP traffic and the expensive provisioning still happens once
at boot — the #185 lesson holds.

Devtest: pad-endpoint grew show/hide verbs; tone/capture need a show
first on a parked box.
2026-08-14 10:26:13 +02:00
enricobuehler e5c0d6b4eb docs(changelog): an idle Windows host no longer owns the box's default microphone 2026-08-14 10:12:00 +02:00
enricobuehler 0bba8d7f8c fix(audio/windows): the default recording device is session-scoped now — an idle host parked every game's voice input on a dead virtual mic
The wiring pass asserted 'default recording = virtual mic capture' on EVERY
pass — including the mic pump's eager boot pass — so an idle box permanently
held the Windows default recording device (and, since SetDefaultEndpoint
covers eCommunications, every game's voice input) on a virtual microphone
whose render feeder is idle-stopped, with no restore path at all: not at
session end, not at service stop. Field-measured 2026-08-14: Helldivers 2
(Wwise + always-on voice) played LOCALLY on an idle host tanks to 2–5 FPS 1%
lows, and mmsys.cpl's own Recording tab goes unresponsive polling the same
endpoint; the reporter's Sound settings showed 'Punktfunk Microphone —
Dispositivo predefinito' with the host idle.

The recording default now follows the exact discipline the playback default
has always had — parked only while a desktop-audio capture is open, with the
operator's device remembered (in memory + an on-disk crash marker,
audio-default-rec.prev), restored on capture close, recovered after a crash
on the next boot's first wiring pass, and unparked by the uninstaller. A
game launched during a stream still binds the client's mic (the park runs
before the session's game does); one launched before the stream keeps the
operator's own microphone — the honest answer.

Because earlier builds recorded nothing to restore, an upgraded box would
have stayed wedged on the virtual mic forever: an idle-pass hygiene now
moves a default found sitting on the plan's mic capture back to the first
REAL microphone (pure picker wiring_plan::real_capture, unit-tested against
the field box's exact recording-tab inventory). Session passes are exempt,
and a box with no real microphone is left alone.

Also folded in: the mid-idle drift re-assert is gone with the gating, so a
mic-pump reopen no longer stomps a recording device the operator chose
themselves.
2026-08-14 10:11:58 +02:00
enricobuehler 0ead084838 Merge pull request 'Steam's art lives in Program Files, which was never an allowed art root' (#215) from worktree-steam-art-root-windows into main
arch / build-publish (push) Failing after 32s
ci / web (push) Successful in 1m20s
ci / rust-arm64 (push) Successful in 1m43s
ci / bun-nix (push) Successful in 1m48s
apple / swift (push) Successful in 2m2s
decky / build-publish (push) Failing after 41s
deb / build-publish-host (push) Failing after 2m13s
deb / build-publish-gamescope (push) Failing after 1m46s
deb / build-publish-client-arm64 (push) Successful in 1m26s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 27s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 15s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 12s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 9s
ci / docs-site (push) Successful in 3m26s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 10s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 21s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 21s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 22s
docker / builders-arm64cross (push) Successful in 46s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 2m11s
ci / rust (push) Successful in 8m11s
android / android (push) Successful in 9m34s
docker / deploy-docs (push) Failing after 6m25s
windows-host / package (push) Successful in 13m53s
windows-host / winget-source (push) Skipped
apple / distribute (push) Successful in 12m19s
deb / build-publish (push) Failing after 14m16s
windows-host / canary-manifest (push) Successful in 28s
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Successful in 16m40s
apple / screenshots (push) Successful in 6m48s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Successful in 19m21s
deb / smoke-install (push) Failing after 9m33s
2026-08-14 07:51:30 +00:00
enricobuehler 0f9ccfa8b6 fix(ci): funnel the art tests' env overrides through one RAII guard
ci / bun-nix (pull_request) Successful in 24s
apple / swift (pull_request) Successful in 2m8s
apple / distribute (pull_request) Skipped
apple / screenshots (pull_request) Skipped
android / android (pull_request) Successful in 3m59s
ci / web (pull_request) Successful in 5m47s
ci / docs-site (pull_request) Successful in 5m51s
ci / rust-arm64 (pull_request) Successful in 5m54s
ci / rust (pull_request) Successful in 18m16s
CI gate C (unsafe hygiene) failed on the previous commit: `library/art.rs`
went from 4 process-global-API mentions to 10, because the two new tests each
hand-rolled a set/restore pair the way the two existing ones already did.

The gate says fix the call sites rather than raise the baseline, and it is
right to here — the hand-rolled pattern was also leaking. Each test set
`PUNKTFUNK_LIBRARY_ART_ROOTS` and unset it at the end, so any assertion
firing between the two halves left the override installed for every later
test in the process, turning one real failure into a cascade.

`ArtRootsEnv` now holds the lock and the saved values and restores them on
drop, which runs on an unwind too. `write_env` is the single write point, so
the gate has exactly one pair of call sites to judge: the count drops to 2,
below the old baseline of 4, and stays flat however many tests are added.
Baseline lowered to 2 in the same commit, as the ratchet's policy requires.

⚠ The gate greps for the API names in COMMENTS as well as code, so the SAFETY
comments here deliberately describe the calls instead of naming them.

Re-verified after the refactor: .25 493/493 + clippy clean, .133 12/12 art
tests + clippy clean, `check-unsafe-hygiene.sh` clean locally.
2026-08-14 09:32:43 +02:00
enricobuehler 8d60f1cec0 Merge remote-tracking branch 'origin/main' into worktree-steam-art-root-windows
ci / web (pull_request) Successful in 1m10s
ci / rust-arm64 (pull_request) Successful in 1m34s
ci / bun-nix (pull_request) Successful in 1m51s
android / android (pull_request) Successful in 3m57s
ci / docs-site (pull_request) Successful in 3m8s
ci / rust (pull_request) Failing after 6m35s
# Conflicts:
#	CHANGELOG.md
2026-08-14 09:12:39 +02:00
enricobuehler 6dd4add11b fix(library): Steam's art lives in Program Files, which was never an allowed art root
ci / bun-nix (pull_request) Successful in 20s
android / android (pull_request) Canceled after 1m22s
ci / rust-arm64 (pull_request) Successful in 1m17s
ci / rust (pull_request) Canceled after 1m22s
ci / web (pull_request) Canceled after 1m18s
ci / docs-site (pull_request) Canceled after 1m18s
A field report: the Steam plugin installed, the grid stayed empty, and the
only clue was one warn per sync — `art.hero: local art must be an image file
… inside an allowed art root`.

Two defects, both here.

The art roots defaulted to the users base (`C:\Users`, from `%PUBLIC%`'s
parent). That covers the launchers that install per-user, but not Steam,
which installs to `C:\Program Files (x86)\Steam` and keeps both the things
the plugin publishes there — `appcache\librarycache\<appid>\<hash>\` and each
account's `userdata\<id>\config\grid\`. So every cover was out of root. It is
a v0.28.0 regression: the built-in scanner the plugin replaced served covers
through the legacy `steam:` art-proxy branch, which never passed through the
H-2 confinement, so deleting the scanner routed that art through a gate it
had never been measured against. `art_roots()` now also carries every Steam
install it can find, from the three Program Files vars and from HKLM
`Valve\Steam\InstallPath` so a Steam on another drive counts too. POSIX needs
no equivalent — native and Flatpak Steam are both already under `$HOME`.

The confinement is not weakened. It exists to stop the host (SYSTEM) reading
what the plugin lane (LocalService) cannot reach itself; the Steam directory
is readable by LocalService already, so nothing there is reachable *because*
the host is privileged, and the extension, regular-file, magic-byte and
config-dir gates still apply on top. Tested: `config.vdf` is not servable
from an art root, nor is a non-image wearing `.png`.

Second, and the reason this cost a whole library rather than a thumbnail: the
provider reconcile validated art per entry and 400'd the WHOLE payload on the
first bad value. A path mismatch therefore deleted every game from that
store, and the plugin — which only ever sees `HostRequestError` — could not
say which. A reconcile now strips unservable local art and syncs the rest,
logging one aggregated warn with the count, an example path and the env var.
The invariant the 400 held is unchanged: no unservable path is persisted. The
operator's own single-entry writes keep the hard 400, because there the path
was typed by hand and silence would be the wrong answer.

Verified on Linux (.25: 493/493, clippy clean) and Windows (.133: 12/12 art
tests, clippy clean). The new Windows test is hermetic — it repoints
`%ProgramFiles(x86)%` at a synthetic Steam tree rather than asserting over
whatever Steam the box happens to have, since the vacuous version of that
test is what would have let this ship. Confirmed non-vacuous by disabling the
fix: it fails on "the DEFAULT art roots must include it".
2026-08-14 08:38:43 +02:00
enricobuehler b6cc76c472 Merge pull request 'The Android audio plane trusted AAudio, so a TV that opened a dead stream was silent all session' (#214) from worktree-android-aaudio-shield-silence into main
ci / bun-nix (push) Successful in 1m10s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 23s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 10s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 11s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 11s
ci / docs-site (push) Successful in 2m3s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 12s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 55s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 8s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 1m21s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 3m23s
ci / web (push) Successful in 3m52s
docker / builders-arm64cross (push) Successful in 9s
docker / deploy-docs (push) Successful in 37s
ci / rust-arm64 (push) Successful in 4m25s
ci / rust (push) Successful in 4m8s
android / android (push) Successful in 12m7s
2026-08-14 06:22:33 +00:00
enricobuehler e2239fd964 Merge remote-tracking branch 'origin/main' into worktree-android-aaudio-shield-silence
ci / web (pull_request) Successful in 1m6s
ci / rust-arm64 (pull_request) Successful in 2m17s
ci / bun-nix (pull_request) Successful in 1m16s
ci / docs-site (pull_request) Successful in 1m56s
ci / rust (pull_request) Successful in 5m29s
android / android (pull_request) Successful in 7m31s
# Conflicts:
#	CHANGELOG.md
2026-08-14 08:07:00 +02:00
enricobuehler f17fe1fc2b Merge pull request 'Unpair every device from one button, over a collection DELETE per plane' (#213) from worktree-unpair-all-button into main
arch / build-publish (push) Failing after 1m7s
ci / docs-site (push) Successful in 1m21s
ci / bun-nix (push) Successful in 4m16s
ci / rust-arm64 (push) Successful in 4m43s
ci / rust (push) Successful in 5m49s
ci / web (push) Successful in 5m48s
deb / build-publish-gamescope (push) Failing after 1m33s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 10s
deb / build-publish-host (push) Successful in 4m42s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 9s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 37s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 16s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 30s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 11s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 36s
android / android (push) Successful in 8m2s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 1m29s
docker / builders-arm64cross (push) Successful in 16s
deb / build-publish-client-arm64 (push) Successful in 4m25s
deb / build-publish (push) Failing after 8m38s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 4m57s
deb / smoke-install (push) Successful in 2m36s
windows-host / package (push) Successful in 16m54s
windows-host / winget-source (push) Skipped
windows-host / canary-manifest (push) Successful in 20s
docker / deploy-docs (push) Successful in 6m42s
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Successful in 18m23s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Successful in 20m28s
2026-08-13 22:53:06 +00:00
enricobuehler a3a6444e6e feat(host,web): unpair every device from one button, over a collection DELETE per plane
ci / bun-nix (pull_request) Successful in 23s
ci / docs-site (pull_request) Successful in 1m10s
ci / rust-arm64 (pull_request) Successful in 5m59s
ci / web (pull_request) Successful in 6m25s
android / android (pull_request) Successful in 4m20s
ci / rust (pull_request) Successful in 16m23s
Clearing a host's trust store meant clicking the row trash icon once per
device and confirming each time — tedious with a handful of clients, and
easy to leave half-done.

The "Paired devices" card header now carries an "Unpair all" action behind
a single confirmation. It is backed by two new endpoints rather than a loop
over the per-fingerprint deletes:

    DELETE /api/v1/clients          -> {"unpaired": N}
    DELETE /api/v1/native/clients   -> {"unpaired": N}

one per pairing plane, because the two planes own separate trust stores
with separate persistence and separate revocation duties. Each empties its
store in ONE persisted write. Doing it as N deletes would rewrite (and
atomically rename) the store once per client, and a failure partway would
leave the operator with a half-emptied store and no way to tell which half.

They are collection deletes, so they carry the single delete's revocation
guarantees across the whole set: a live session owned by any removed
certificate is ended, and on the Moonlight side the ENet control port
closes, because no pairing is left to hold it open.

200 with a count rather than the single delete's 204/404: "unpair
everything" is idempotent, an already-empty store satisfies it, and the
count still tells the operator whether that meant three devices or none.

Both gates match on (method, path), so the roster's plugin-readable GET
does not carry over to emptying it — both new routes are admin-token only,
like every other pairing-administration route, with explicit rows in the
route-classification table.

The console calls only the planes that actually have a row: the native
endpoint answers 503 on a host built without that plane, which would
otherwise report a failure for devices that were never there.
2026-08-14 00:35:33 +02:00
enricobuehler 38631d43df fix(client/android): the audio plane trusted AAudio, so a TV that opened a dead stream was silent all session
ci / bun-nix (pull_request) Successful in 19s
ci / web (pull_request) Successful in 1m13s
android / android (pull_request) Canceled after 1m41s
ci / rust (pull_request) Canceled after 1m39s
ci / docs-site (pull_request) Canceled after 1m41s
ci / rust-arm64 (pull_request) Canceled after 1m43s
Field report: no audio at all on an NVIDIA Shield Android TV, stereo, same
host and settings that play fine on an Apple TV. Video unaffected. Turning
off low-latency mode — which gates the forced HDMI mode switch and the
usage=Game tagging, the two things that toggle controls — changed nothing.

This client opens AAudio directly, where the Apple one goes through
AVAudioEngine and gets route-change handling for free; that is why this was
Android-only. Opening AAudio is a negotiation with a vendor HAL and this
plane treated it as a formality: one Exclusive attempt, one Shared retry,
everything after the open taken on trust. Three separate failures all came
out as "the app has no sound" behind a perfectly ordinary log line:

  - a configuration that opens but routes nowhere — nothing ever checked
    that the device pulled a single sample, so the decode thread fed Opus
    into a dead stream indefinitely;
  - request_start failing — we gave up on the spot rather than trying
    anything else, so one unhappy config disabled audio for the session;
  - a disconnect — by AAudio's contract the stream is then DEAD and the
    only recovery is close + open a new one, but the error callback logged
    a warning and did nothing. On a TV that is not rare: this client drives
    an HDMI mode switch on the video plane, and the platform's own
    match-content-frame-rate setting drives more.

The open now walks a ladder, every rung must prove the device is pulling
before it is accepted, and a supervisor owns the plane for the session and
reopens it when the device goes away — with bounded retries across the
settling time of a route change, so a reopen landing mid-switch cannot
permanently disable audio. Granted rate/channels/format are checked rather
than assumed: the realtime callback casts AAudio's buffer to f32 and writes
num_frames * channels of them, so a HAL that disagreed was an out-of-bounds
write on the audio thread, not just a mistuning.

TV boxes now start at Shared. Exclusive is MMAP, the lowest-latency path
AAudio has and the one rung whose routing cannot be verified from inside
the process; the latency it buys was never banked, since the ring depths
are unchanged from the Shared-only era (AAUDIO still primes at 25 ms). On a
mains-powered HDMI box that trade is not worth betting the audio plane on.
Phones keep Exclusive first. If no rung proves itself the first one that
opened and started is used anyway — a watchdog must never be able to turn
working audio into no audio.

nativeStartAudio takes isTv (FEATURE_LEANBACK, the source the video plane
already used) because ro.build.characteristics is not answered by every TV.

debug.punktfunk.audio_sharing / audio_perf / audio_reopen bisect all of it
with setprop, for the device that reports silence and cannot be handed a
custom build. A stream that stops taking samples after it started now says
so at error level instead of looking exactly like an app with no sound.

Not verified on a Shield — no such device here.
2026-08-14 00:15:48 +02:00
enricobuehler 4caf2b76e8 Merge pull request 'gamescope +pfhdr7 — linger no longer dies of its own capture teardown (luxus's fix, overlay#9)' (#212) from worktree-gamescope-linger-pw-destroy-race into main
ci / web (push) Successful in 1m15s
ci / docs-site (push) Successful in 1m29s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 6s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 7s
ci / rust (push) Successful in 7m33s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 9s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 8s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 13s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 12s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 1m34s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 55s
ci / rust-arm64 (push) Successful in 4m37s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 1m23s
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Failing after 1m29s
ci / bun-nix (push) Successful in 4m9s
docker / deploy-docs (push) Successful in 33s
arch / build-publish (push) Successful in 10m38s
docker / builders-arm64cross (push) Successful in 1m45s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Successful in 16m28s
Reviewed-on: #212
2026-08-13 22:15:40 +00:00
enricobuehler 0f64551c56 fix(packaging/gamescope): +pfhdr7 — linger no longer dies of its own capture teardown
ci / rust-arm64 (pull_request) Successful in 2m5s
ci / bun-nix (pull_request) Successful in 5m28s
ci / web (pull_request) Successful in 7m2s
ci / docs-site (pull_request) Successful in 8m0s
ci / rust (pull_request) Successful in 16m28s
Patch 0009, reported, written and proven live by luxus (punktfunk-overlay#9): when the capture
consumer leaves, stream_handle_remove_buffer — and the stale-push path in dispatch_nudge —
destroyed idle buffers on the PipeWire thread. Dropping the last CVulkanTexture reference there
calls into the Vulkan driver (vkDestroyImage / FreeMemory / dmabuf fds) while steamcompmgr can
still be inside vulkan_screenshot on another buffer of the same 4-buffer pool; on NVIDIA the race
lands as a SIGSEGV in CVulkanCmdBuffer::insertBarrier. The timing is what made it selectively
lethal: it fires at stream END — exactly the window where the host keeps the headless display
lingering for a reconnect. So the kept display was already dead (journal: linger line → coredump →
"kept display was dead — recreating") and the "resumed" session was a fresh compositor with the
game lost.

The fix queues the corpses (bury_buffer, mutex-guarded) and steamcompmgr reaps them on every
vblank, including while the stream is only paused — the linger state itself. Field-proven on the
reporter's NVIDIA host: 4 coredumps in one evening of BG3 at 4K60 HDR with --pipewire-composite-
cursor (the heaviest paint path we ship), zero after; disconnect/reconnect confirmed live to reuse
the lingered session (2026-08-13). Three of the four stacks are this race; the fourth
(~CVulkanDevice during exit) is patch 0006's already-fixed static-destruction bug — do not
re-diagnose it as part of this.

Ours differs from the overlay's original only by the meson.build banner hunk: +pfhdr6 → +pfhdr7,
PKGBUILD 3.16.25.pfhdr7-1. No new capability — same rule as pfhdr5/6: "reconnect lost my game"
triage has to read a box's exposure off its banner, and every probe is >=. Known residual,
deliberately untouched: add_buffer's error path still deletes on the PW thread. By the later
`goto error`s a texture may be attached, so the race is reachable there in theory — but only when
an add FAILS mid-renegotiation, which no field coredump shows; the patch stays byte-identical with
what was proven on-glass.

Verified: the full 0001..0009 series applies onto the bare 5fb8dce4 pin with plain `git am` (the
build script's own invocation, no -3, no fuzz) and with `git am -3`; the fc44 CI image
(punktfunk-fedora44-rpm) builds the result with rpm.yml's exact dep recipe to a binary whose
banner reads `3.16.25-20-g40fe8b5+pfhdr7 (gcc 16.1.1)`. After 0009, destroy_buffer has exactly
two callers left —
pipewire_reap_dead_buffers (steamcompmgr vblank) and pipewire_destroy_buffer (steamcompmgr's
copy-completion path) — both on the compositor thread. Nix, deb, sysext and rpm all glob
patches/*.patch and read the level off the banner, so no other packaging file moves.
2026-08-14 00:03:17 +02:00
enricobuehler 8fe5acf7f2 Merge pull request 'The OSD stage line stays a partition — an async decode figure is not one of its terms' (#211) from worktree-decode-stat-overlap into main
android / android (push) Failing after 1m54s
ci / docs-site (push) Successful in 1m32s
deb / build-publish (push) Successful in 3m38s
ci / rust-arm64 (push) Successful in 7m6s
ci / web (push) Successful in 6m49s
deb / build-publish-gamescope (push) Failing after 1m33s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 14s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 9s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 52s
ci / bun-nix (push) Successful in 6m10s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 10s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 8s
arch / build-publish (push) Successful in 10m47s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 14s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 13s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 1m57s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 1m57s
deb / build-publish-client-arm64 (push) Successful in 3m27s
deb / build-publish-host (push) Successful in 8m5s
docker / builders-arm64cross (push) Successful in 47s
ci / rust (push) Canceled after 15m18s
docker / deploy-docs (push) Canceled after 3m24s
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Canceled after 4m53s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Canceled after 3m46s
windows-client / client (arm64, --no-default-features, aarch64-pc-windows-msvc, C:\t-a64) (push) Successful in 3m9s
deb / smoke-install (push) Successful in 4m34s
flatpak / build-publish (push) Successful in 11m50s
windows-client / client (x64, , x86_64-pc-windows-msvc, C:\t) (push) Successful in 11m16s
Reviewed-on: #211
2026-08-13 21:56:44 +00:00
enricobuehler fb33555059 Merge pull request 'HDR was a stop bright, in-game HDR was unreachable on every distro, and SDR shipped untagged' (#210) from worktree-hdr-colour-anchor-fixes into main
arch / build-publish (push) Failing after 6s
ci / bun-nix (push) Successful in 30s
ci / web (push) Successful in 1m1s
deb / build-publish-gamescope (push) Failing after 1m48s
deb / build-publish-client-arm64 (push) Successful in 1m16s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 7s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 8s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 7s
apple / swift (push) Successful in 2m5s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 8s
deb / build-publish-host (push) Successful in 4m29s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 9s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 9s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 8s
ci / rust-arm64 (push) Successful in 5m37s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 17s
android / android (push) Canceled after 6m33s
ci / rust (push) Canceled after 6m33s
ci / docs-site (push) Canceled after 6m29s
deb / build-publish (push) Canceled after 6m29s
deb / smoke-install (push) Canceled after 0s
docker / builders-arm64cross (push) Canceled after 0s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Canceled after 1m16s
docker / deploy-docs (push) Canceled after 0s
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Canceled after 1m11s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Canceled after 16s
nix / flake (push) Failing after 2m20s
windows-host / package (push) Successful in 12m56s
windows-host / winget-source (push) Skipped
apple / distribute (push) Successful in 11m11s
windows-host / canary-manifest (push) Successful in 41s
apple / screenshots (push) Successful in 6m56s
Reviewed-on: #210
2026-08-13 21:50:11 +00:00
enricobuehler 81022bcc80 fix(client/stats): keep the stage line a partition — an async decode figure is not one of its terms
ci / web (pull_request) Successful in 2m11s
ci / bun-nix (pull_request) Successful in 3m25s
ci / rust-arm64 (pull_request) Successful in 4m39s
android / android (pull_request) Successful in 6m20s
ci / docs-site (pull_request) Successful in 5m37s
ci / rust (pull_request) Successful in 6m40s
windows-client / client (arm64, --no-default-features, aarch64-pc-windows-msvc, C:\t-a64) (pull_request) Successful in 2m49s
windows-client / client (x64, , x86_64-pc-windows-msvc, C:\t) (pull_request) Successful in 6m34s
A 2026-08-13 field report read the OSD's stage line as a breakdown of e2e 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/9.1`. Fair question, and the numbers are all
individually true. They add up without `decode`: 5.4 + 0.3 + 1.4 ≈ 8.1.

The stages ARE a per-frame partition of e2e — pts →(host+net)→ received
→(decode)→ decoded →(display)→ displayed — and that holds for as long as the
`decoded` stamp is a COMPLETION stamp. On the synchronous rungs it is. On the
native-Vulkan rung `receive_frame` returns at SUBMISSION (~0.1 ms) and the
stamp shipped to the presenter is taken there, so `display` is measured from
submit and the GPU decode happens INSIDE it. `host+net` and `display` already
tile e2e between them; the `decode` figure, measured received → fence-complete,
re-counts the GPU work `display` contains. Two figures, one overlap, printed
side by side as though they tiled.

So on that rung `decode` leaves the stage line and gets its own, carrying the
two caveats a reader needs before the number means anything: it is ONE sample
per window there, not the p50 every other figure on that line is, and it is
already inside `display` so adding it double-counts. The synchronous rungs are
untouched — `decode` is a real term there and stays inline.

Deliberately NOT changed: the one-sample-per-window design. `pf_client_core::
session` argues it at length — a per-frame fence wait serialises the decode
pipeline (an APU's 19 ms decode capping a 5120×1440 stream at ~51 fps), and M4
already re-examined and rejected polling, which quantises every sample up by a
frame interval (8.3 ms at 120 Hz against decodes of ~0.1-2 ms). That reasoning
still holds; the reporting around it was the defect. Making `decode` a genuine
per-frame term would need a completion stamp off the hot path — a waiter thread
on the timeline, which that comment already names as the remaining option — and
is a bigger change than this one.

Also not answered here: why the sampled frame read 6.6 ms when the sampling
comment expects 0.1-2 ms. It is a tail frame by construction (a frame that took
6.6 ms to decode also took ≥ 6.6 ms to display, against a 1.4 ms display p50),
but whether the first frame of a window is SYSTEMATICALLY a tail frame needs
instrumenting rather than guessing.

Verified in the linux/amd64 container: pf-presenter 47/47 (incl. the new case,
which pins both shapes and the timed-out-window zero), pf-client-core 188/188,
`clippy --all-targets -D warnings` clean on both, fmt clean. The pf-client-core
leg was proven non-vacuous with a planted compile_error! first.
2026-08-13 23:49:41 +02:00
enricobuehler 1b167f8e35 Merge pull request 'The host tile gets a menu, and the start-of-stream banner becomes an About tab' (#209) from worktree-gamepad-ui-host-mgmt-about into main
ci / bun-nix (push) Successful in 24s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 19s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 9s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 9s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 26s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 23s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 11s
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 1m16s
apple / swift (push) Successful in 2m2s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 58s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 1m16s
ci / web (push) Successful in 3m13s
docker / builders-arm64cross (push) Successful in 1m48s
docker / deploy-docs (push) Successful in 31s
ci / docs-site (push) Successful in 3m24s
apple / distribute (push) Canceled after 1m47s
apple / screenshots (push) Canceled after 0s
ci / rust (push) Canceled after 3m50s
ci / rust-arm64 (push) Canceled after 3m49s
2026-08-13 21:46:19 +00:00
enricobuehler 082c65755f fix(packaging): every channel ships the WSI layer, so in-game HDR works off a stock install
ci / web (pull_request) Successful in 1m0s
ci / bun-nix (pull_request) Successful in 2m6s
ci / rust-arm64 (pull_request) Successful in 3m29s
ci / docs-site (pull_request) Successful in 3m53s
android / android (pull_request) Successful in 5m4s
ci / rust (pull_request) Successful in 5m9s
apple / swift (pull_request) Successful in 2m0s
apple / distribute (pull_request) Skipped
apple / screenshots (pull_request) Skipped
nix / flake (pull_request) Failing after 6m17s
The previous commit built the layer and taught the host to use it, but only the
Arch PKGBUILD carried the files, so every other channel still landed on the
no-game-HDR fallback. This finishes the job.

The packaging scripts now take `--stage`, the DESTDIR the gamescope build script
wrote, instead of a path to one binary. That is the part worth keeping: the next
file this package needs will not require a new flag in four scripts and two
workflows. CI caches the whole staged tree for the same reason. The gs-cache key
already hashes packaging/gamescope/**, which this commit changes, so stale caches
in the old single-file shape cannot be restored into the new layout.

Channels, all of them:
  rpm     spec gains Source1/Source2 and %files entries
  deb     build-gamescope-deb.sh copies the layer into the package root
  Arch    PKGBUILD (previous commit); the sysext extracts the whole usr tree
  sysext  bazzite takes --gamescope-stage; arch asserts the layer arrived
  nix     the derivation keeps, renames and rewrites the layer rather than
          deleting it with everything else

A missing layer is fatal in every one of them, not best-effort. A package that
carries the compositor without it looks completely healthy and then silently
denies every game an HDR10 swapchain -- the exact failure this whole change
exists to end, so it must not be possible to ship it again by accident.

Two things needed care:

The layer manifest carries an ABSOLUTE library_path baked in at build time, so
every channel has to install the .so at exactly that path. That means literal
/usr/lib/punktfunk, not %{_libdir} (which is /usr/lib64 on Fedora) and not a
Debian multiarch triplet. Nothing links the .so by soname -- the loader dlopens
it by that path -- so multilib has no claim here. The rpm and nix install checks
now read the path back out of the manifest and fail if it names a file the
package does not install, because a manifest pointing at nothing is the silent
shape of this bug.

NixOS has no /usr, so the layer lives inside the gamescope derivation and the
host's path is overridable via PUNKTFUNK_GAMESCOPE_WSI_LAYER_DIR, which the
module sets -- the same posture as PUNKTFUNK_GAMESCOPE_BIN, and documented.

The manifest rewrite moved out of a heredoc into
packaging/gamescope/rewrite-wsi-layer-manifest.py because the FHS builds and the
Nix store both need it and must rename the layer identically; two copies would
drift into a host looking for a name only one of them produces.

Verified: 214 pf-vdisplay tests pass in a linux container, clippy -D warnings and
rustfmt clean, bash -n on all five changed shell scripts, both workflow YAMLs
parse, and the rewrite script was run against a synthetic FROG manifest to
confirm it renames/repoints/regates while preserving the `functions` block --
which is the field that decides whether the layer loads at all.
NOT verified: no nix on this machine, so gamescope.nix, flake.nix and the module
are unevaluated; no gamescope build, no package build of any kind, and no game
has taken an HDR swapchain on glass.
2026-08-13 23:37:48 +02:00
enricobuehler 9c2c8d1643 fix(apple/about): drop the identity card for a version line under the rows
ci / bun-nix (pull_request) Successful in 42s
ci / web (pull_request) Successful in 1m9s
ci / docs-site (pull_request) Successful in 1m13s
ci / rust-arm64 (pull_request) Successful in 1m20s
ci / rust (pull_request) Successful in 13m50s
apple / swift (pull_request) Successful in 2m0s
apple / distribute (pull_request) Skipped
apple / screenshots (pull_request) Skipped
The card led the About tab with the app icon, and on tvOS that icon is a 400x240
rectangle meeting a layout built for square art. Three passes at framing it —
aspect-correct frame, then dropping the zero-radius clip that was cropping it,
then a max frame so it could shrink instead of overflow — and it was still cut
off on real hardware.

So the card goes. A version string answers the only question anyone opens About
to ask, it has no aspect ratio to get wrong, and it belongs under the rows rather
than over them: quiet and centred, reading as a footer instead of a row you
failed to press. `Row.Kind.footer` draws it.

swift build clean on macOS, arm64-apple-ios17.0 and arm64-apple-tvos17.0;
on glass on an Apple TV as 0.29.0 (100004).
2026-08-13 23:28:04 +02:00
enricobuehler c591b7b4af Merge pull request 'The Apple HUD froze its clock offset at connect, so every host-anchored number lied — and the tvOS present floor is closed on sound evidence now' (#208) from worktree-appletv-present-depth into main
docker / builders (ci/android-ci.Dockerfile, punktfunk-android-ci) (push) Successful in 47s
docker / builders (ci/arch-ci.Dockerfile, punktfunk-arch-ci) (push) Successful in 46s
ci / bun-nix (push) Successful in 56s
docker / builders (ci/gamescope-trixie.Dockerfile, punktfunk-gamescope-trixie) (push) Successful in 12s
docker / builders (ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 14s
docker / builders (ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Successful in 11s
ci / web (push) Successful in 1m30s
docker / builders (ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 14s
ci / docs-site (push) Successful in 1m38s
ci / rust-arm64 (push) Successful in 1m39s
apple / swift (push) Successful in 2m3s
docker / builders (--build-arg FEDORA_VERSION=44, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm, -f44) (push) Successful in 35s
docker / apps (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 40s
docker / builders-arm64cross (push) Successful in 12s
docker / apps (., web/Dockerfile, punktfunk-web) (push) Successful in 1m16s
ci / rust (push) Successful in 4m49s
docker / deploy-docs (push) Failing after 6m59s
apple / distribute (push) Successful in 10m26s
apple / screenshots (push) Successful in 6m45s
2026-08-13 21:21:40 +00:00
enricobuehler 3ac4548cf8 fix(gamescope): ship the WSI layer built beside our compositor, instead of guessing at the distro's
A game nested under gamescope gets an HDR10 swapchain from the FROG WSI layer and
from nothing else -- gamescope advertises no runtime colour-management protocol a
Mesa/NVIDIA WSI could negotiate through. That layer talks `gamescope_swapchain`
to the compositor, and when the two disagree the compositor rejects the client's
swapchain_feedback and every Vulkan client dies on a black screen with sound and
input and no error anywhere.

We ship our own compositor and did NOT ship a layer, on the recorded grounds that
the layer is "version-independent of the compositor binary". It is not, and
wsi_layer_matches_our_gamescope() exists because it is not. So the host was left
guessing from version triples, and that guess is wrong in both directions: a
distro at the same upstream tag that patched the protocol compares EQUAL and
keeps a layer that will kill every game, while a distro at a different tag with a
byte-identical protocol compares unequal and loses HDR for nothing. Since we pin
a rev, the second case is the normal one -- on essentially every box with a
distro gamescope, the layer was disabled and no game could render HDR.

Ship the layer instead. It is built from the same tree at the same rev as the
compositor, so the two cannot drift, and the guess stops being load-bearing. It
is installed under our own name (VK_LAYER_PUNKTFUNK_gamescope_wsi) at our own
path with our own enable/disable variables, so it coexists with the distro's
rather than colliding -- the Vulkan loader keys implicit layers on that name --
and the host switches the two independently in one session.

WsiPlan makes the three states explicit and resolves them once per launch, since
the fallback spawns `--version` probes:
  Ours            our layer is installed: enable it, force the distro's off
  DistroKept      no layer of ours, distro's looks compatible: touch nothing
  DistroDisabled  no layer of ours, distro's untrusted: today's behaviour

That last arm is the fail-safe. A host newer than its gamescope package behaves
exactly as it does today rather than enabling a layer that is not there, so this
can roll out one packaging surface at a time without a flag day.

Only the Arch PKGBUILD carries the new files so far. The rpm path takes a
CI-cached binary rather than the build script's stage dir, so it needs the cache,
build-gamescope-rpm.sh and the spec moved together; the deb, both sysexts and
gamescope.nix need the same two files added. Until each lands, those boxes take
the DistroDisabled arm and are no worse off than before.

Verified: 214 pf-vdisplay tests pass in a linux container (including a new one
pinning that the Ours arm enables ours AND forces the distro's off together --
either half alone is a bug), clippy -D warnings and rustfmt clean, both shell
files pass bash -n, and the manifest rewrite was run against a synthetic FROG
manifest to confirm it renames/repoints/regates while preserving the `functions`
block. NOT verified: an actual gamescope build, any package build, or a game
taking an HDR swapchain on glass.
2026-08-13 23:18:02 +02:00
enricobuehler 6fd5769b3b fix(apple/about): a zero-radius clip is still a clip, and it cropped the TV's wide icon
`cornerRadius: 0` reads as "no rounding", but a RoundedRectangle clip is not a
no-op at zero — it still clips to the layout frame, so any art whose aspect ratio
isn't the frame's loses its ends. The TV's 400x240 icon did exactly that as soon
as there was a real icon to draw instead of the square monogram. The mask now
applies only where it is wanted: iOS, whose icon ships unmasked because the
springboard rounds it at draw time.

The frame goes from fixed to MAX for the same failure one step further out: at a
fixed width the image cannot shrink when its row is tight, so it overflows and is
cropped by whatever is above it. `.fit` inside a max frame gives the whole icon
back, just smaller. And the icon takes layout priority in the identity card — the
tagline beside it is happy to wrap, and a 5:3 icon is what suffers first if the
text is given the width it asks for.

swift build clean on macOS, arm64-apple-ios17.0 and arm64-apple-tvos17.0.
2026-08-13 23:10:34 +02:00
enricobuehler ed8c080603 fix(apple/about): the identity card ignored the row column, and the TV had no icon to show
Both found on glass on an Apple TV.

The card was laid out against the SCREEN while everything under it is laid out
against a centred column of `rowMaxWidth` — 920pt against a 1920-wide TV. So it
began a few hundred points to the left of every row it introduced and read as a
separate banner rather than the head of the list. It now takes the same column
and the same inner inset as a row's contents, so the icon sits directly above
the row icons.

And it was drawing the "P" monogram, never the app's mark. That fallback exists
because tvOS ships its icon as a parallax image STACK (Back/Circle1/Circle2/
Front) with no single image to load, so `AppIconView.bundleIcon` returned nil
there and always had. `AboutAppIcon` is those four layers flattened into one
asset, generated from the SAME art the stack uses so the two cannot drift into
being subtly different icons. A TV icon is a 400x240 rectangle rather than a
squircle, so `side` means HEIGHT on tvOS and the width follows the real 5:3 art
— framed square it would have sat in a box two thirds empty.

Verified the asset actually survives compilation (`assetutil` finds AboutAppIcon
in the built Assets.car at both scales) — a missing imageset would silently fall
back to the monogram again, which is exactly the bug being fixed.

swift build clean on macOS, arm64-apple-ios17.0 and arm64-apple-tvos17.0.
2026-08-13 23:04:29 +02:00
enricobuehler a190fdb1ae fix(apple/tvos): an SDR stream forced the TV into HDR10 output
applyDisplayCriteriaIfNeeded builds a synthetic format description hardcoding
BT.2020 primaries, ST.2084 PQ and the BT.2020 matrix, then hands it to
AVDisplayManager to pick a display mode. Its guard checked only that no criteria
had been set yet and that the user's HDR setting was on -- never that the stream
itself was HDR. Since that setting defaults to true, an ordinary SDR session
drove an HDR-capable TV into PQ output.

That is a standard way to raise the black floor: 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 rather than black.

Now gated on connection.isHDR as well. Layout re-runs this, so a session that
flips to HDR mid-stream still picks the mode up on the next pass.

This was NOT the cause of the 2026-08-13 grey-blacks report -- that one had the
client's HDR setting off, so this path never ran (see the SDR layer tagging in
the previous commit for the mechanism that did apply). It is a real bug on its
own, found while investigating it.

Verified: full tvOS compile clean against the AppleTVOS SDK. Not yet verified on
glass.
2026-08-13 22:59:38 +02:00
enricobuehler 94f049ba70 fix(apple): the SDR layer shipped untagged, because an SDR session never configured colour
configure(hdr:) guards on hdr != hdrActive, and hdrActive starts false. A
session that is SDR from its first frame therefore matched the initial state and
fell straight through the guard, so configureColor never ran even once and the
layer kept make()'s bare configuration -- which never assigns a colour space.

An untagged CAMetalLayer gets no colour matching: the BT.709-encoded stream is
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.
It matches a field report of greys where blacks should be, which arrived with
the client's own HDR switch already OFF -- so nothing else in the pipeline had
tagged those pixels either.

It also meant PUNKTFUNK_SDR_COLORSPACE was dead code on exactly the sessions it
existed to fix: an operator A/B-ing it in the field would have seen no change at
all, because the assignment it feeds was never executed.

So: configureColor now runs once regardless (same-state calls after the first
are still no-ops), and tagging is the default rather than opt-in, since drawing
a BT.709 stream in the panel's native space is not a rendering anyone asked for.
PUNKTFUNK_SDR_COLORSPACE=none restores the untagged look as the A/B lever.

The tvOS HDR tone-map branch gets the same tag -- pf_frag_hdr_tv outputs BT.709,
so it is an SDR layer by the time it is presented.

Verified: full tvOS compile of every PunktfunkKit source clean against the
AppleTVOS SDK. (The build's link step fails on three ABI symbols missing from
the checked-in PunktfunkCore.xcframework, which predates them -- pre-existing,
main fails identically, unrelated to these files.) Not yet verified on glass.
2026-08-13 22:59:36 +02:00
enricobuehler c29e720324 fix(gamescope): HDR sessions anchored SDR white a stop bright, and never said game HDR was unreachable
Field report 2026-08-13, Bazzite host in gaming mode to an iPad: Steam's Big
Picture UI looked glaring and over-saturated while HDR game content looked
washed out, both on the same stream.

Those are one error. gamescope maps everything that is not an HDR game -- the
desktop, the Steam overlay, an SDR title -- into the session's PQ container at
--hdr-sdr-content-nits, and we only passed that flag when an operator had set
PUNKTFUNK_GAMESCOPE_SDR_NITS. Unset, gamescope used its own default of 400,
while every first-party client anchors diffuse white at 203 (BT.2408 reference
white; the Apple presenter hands exactly that to CAEDRMetadata.hdr10's
opticalOutputScale). The two ends were nearly a stop apart, so the UI landed
above SDR white and the client's tone-mapper worked from a reference point the
host had never used, flattening the content around it.

The flag is now always passed, defaulting to 203. The knob still overrides it
for anyone who wants a brighter or dimmer desktop.

Separately, and visible in the same log: the two HDR decisions in a gamescope
session are made independently. hdr_args() never consults
wsi_layer_matches_our_gamescope(), so when the WSI-layer version check fires --
which it does on essentially every Bazzite box, since we pin our own gamescope
rev and the check compares version triples -- the session launches advertising
HDR while having made an HDR10 swapchain unreachable for every game in it. That
layer is the only route to one, so a title told to render HDR renders it into an
SDR swapchain and looks washed out, with nothing anywhere saying why. It now
warns. The behaviour of the check itself is deliberately left alone: re-enabling
a genuinely mismatched layer black-screens every Vulkan client, which is worse
than losing HDR, and that trade needs a real box to retest.

Verified: scripts/xcheck.sh linux clippy clean on pf-vdisplay (-D warnings),
rustfmt clean. Not yet verified on glass.
2026-08-13 22:59:30 +02:00
enricobuehler e057bd60f4 refactor(apple/gamepad-ui): About is its own section, not the last row of Interface
Reachable, but wrong: About sat at the bottom of the Interface tab, under the
palette and the overlay position — a page about the app filed among the settings
that change how it looks, found only by scrolling past them.

It is a tab now, trailing the strip beside 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.

The standalone GamepadAboutView goes away with it. Its content is the tab's rows,
its two reading surfaces (shortcuts, licences) are in-place layers like the pin
picker, and the identity card — icon, name, version, tagline — rides in the
header under the tab strip. In the header rather than as a first row so the list
holds no focus stop that does nothing when pressed; laid out sideways rather than
centred like the touch page, because this header already carries a title and a
strip and a centred icon-name-version-tagline stack would leave no room for the
rows under it.

Row grows a `kind`, so the About tab can draw a heading and a block of prose
without every other tab's rows pretending to be one.

swift build clean on macOS, arm64-apple-ios17.0 and arm64-apple-tvos17.0;
288 tests pass.
2026-08-13 22:57:17 +02:00
enricobuehler 96278eebb5 feat(apple/gamepad-ui): the host tile gets a menu, and the start-of-stream banner becomes a page you can open
The gamepad UI could add a host and connect to one, and that was all: a renamed
machine or a fat-fingered address stayed wrong forever, because the only surface
that could edit or remove one was the touch UI. The desktop console and the
Android console have both had a host menu on UP for a while — this is the Apple
port of it, so the three consoles are learned once.

UP on a saved tile opens Wake / Copy link / Edit… / Forget pairing / Remove.
Wiring UP takes the whole vertical axis away from scrolling (down goes inert): a
horizontal carousel has no vertical travel to spend, and one meaning per
direction is what makes the gesture learnable. Remove arms on the first press
and only fires on the second, and disarms if focus wanders off the row — the
touch grid gets a system confirmation dialog, and a thumbstick from across a
room is a good reason to be at least as strict. A pinned profile card offers
only Unpin: it is a shortcut, not a second host.

Edit reuses GamepadAddHostView, seeded from the record and writing a COPY back
through HostStore.update, so the fingerprint, MACs, pins and binding the form
never shows survive a rename. It REPLACES the menu rather than stacking on it,
which keeps the shell's "depth <= 1 by construction" true.

This also retires the start-of-stream shortcut banner. Telling someone the
controls for six seconds, over the stream they have just connected to, answers
the question at the one moment nobody is asking it — and it put a composited
overlay above the stream to do it. The words are now ShortcutsCatalog, rendered
by an About page on BOTH surfaces: the new gamepad one (icon, version, licenses,
shortcuts) and the touch AboutView. The touch half is not a bonus — the banner
fired in touch mode on a Mac too, so deleting it without that would have cost
those users the only place the keys were written down.

Verified: swift build clean on macOS, arm64-apple-ios17.0 and arm64-apple-tvos17.0
(the iOS pass is what typechecks the shell-layer code, which is #if os(iOS));
288 tests pass. NOT verified on glass — screen capture is unavailable in this
environment, so the new screens have been compiled and reasoned about but not
seen.
2026-08-13 22:34:46 +02:00
114 changed files with 8040 additions and 1082 deletions
+21 -10
View File
@@ -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 0609 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)
+7 -5
View File
@@ -9,11 +9,13 @@
# login gate, session sealing, mgmt bearer token), sdk (@punktfunk/host),
# plugin-kit (@punktfunk/plugin-kit).
# * pnpm audit → clients/decky (the Steam Deck plugin).
# * docs-site → scanned NON-blocking (continue-on-error): known transitive advisories ride in
# via the CMS/UI chain (@unom/ui → payload → dompurify/monaco) and the nitropack
# build chain (node-tar, brace-expansion); clearing them needs coordinated bumps
# verified against the LIVE site (the docs don't build standalone) — tracked in
# punktfunk-planning design/cra-readiness.md. Flip to blocking once clean.
# * docs-site → scanned NON-blocking (continue-on-error). 2026-08-14: docs-site's own deps
# are current (fumadocs/tanstack/react bumped; build + tsc + serve verified),
# but every remaining advisory is pinned INSIDE @unom/ui 0.9.2's dependency
# tree (@payloadcms/* → fast-uri/image-size/sharp, next 16.x, sass→immutable) —
# nothing bumpable from this lockfile, and overrides would fork what the CMS
# actually ships. The fix belongs in the @unom/ui package repo; flip this to
# blocking after a ui release with a clean payload chain lands here.
# * cargo-about → license-allowlist gate over the host + driver workspaces (about.toml `accepted`);
# fails if any crate carries a license outside the allowlist — the regression
# guard about.toml always promised. (The Android Gradle tree has no lockfile, so
+5 -3
View File
@@ -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:
+10 -6
View File
@@ -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
+20 -4
View File
@@ -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: |
@@ -275,10 +288,13 @@ jobs:
# stable release -> `latest/` alias; canary main build -> `canary/` alias.
$alias = if ($env:GITHUB_REF -like 'refs/tags/v*') { 'latest' } else { 'canary' }
# version-less, arch-suffixed alias names so each channel keeps one predictable URL.
$aliasNames = @{
"$($env:MSIX_PATH)" = "$($env:PKG)_${{ matrix.arch }}.msix"
"$($env:MSIX_CER_PATH)" = "$($env:PKG)_${{ matrix.arch }}.cer"
}
# Under Azure signing there is no .cer, so MSIX_CER_PATH is unset. The quotes below are
# load-bearing: "$($env:UNSET)" interpolates to an empty string (a legal key), whereas a
# BARE $env:UNSET is $null and a null key is a hard error in a hash literal — which is
# exactly how windows-host.yml's publish step broke. Added explicitly rather than relying
# on that accident, so removing the quotes can't silently reintroduce it.
$aliasNames = @{ "$($env:MSIX_PATH)" = "$($env:PKG)_${{ matrix.arch }}.msix" }
if ($env:MSIX_CER_PATH) { $aliasNames[$env:MSIX_CER_PATH] = "$($env:PKG)_${{ matrix.arch }}.cer" }
$files = @($env:MSIX_PATH, $env:MSIX_CER_PATH) | Where-Object { $_ -and (Test-Path $_) }
if (-not $files) { throw "pack produced no artifacts to publish" }
function Put($f, $url) {
+30 -4
View File
@@ -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: |
@@ -452,7 +472,13 @@ jobs:
# Refresh the channel alias (delete-then-reupload, like flatpak.yml/decky.yml) for a
# predictable download URL: stable release -> `latest/`, canary main build -> `canary/`.
$alias = if ($env:GITHUB_REF -like 'refs/tags/v*') { 'latest' } else { 'canary' }
$aliasNames = @{ $env:HOST_SETUP_PATH = 'punktfunk-host-setup.exe'; $env:HOST_CER_PATH = 'punktfunk-host-windows.cer' }
# Build this incrementally, NOT as one literal: under Azure signing there is no .cer, so
# HOST_CER_PATH is unset — and an unset $env: var is $null, which is a HARD ERROR as a hash
# literal key ("A null key is not allowed in a hash literal"), not the empty-string key it
# looks like it should be. The $files guard above filters the missing .cer out just fine;
# this line ran before anything could use it and failed the whole publish step.
$aliasNames = @{ $env:HOST_SETUP_PATH = 'punktfunk-host-setup.exe' }
if ($env:HOST_CER_PATH) { $aliasNames[$env:HOST_CER_PATH] = 'punktfunk-host-windows.cer' }
foreach ($f in $files) {
$an = $aliasNames[$f]; if (-not $an) { continue }
curl.exe -fsS -o NUL --user "enricobuehler:$($env:REGISTRY_TOKEN)" -X DELETE "$base/$alias/$an" 2>$null
+591 -1
View File
@@ -12,7 +12,584 @@ with the version table of the release you are moving to, then read **Breaking ch
---
## v0.28.1 — in development
## v0.28.1
60 commits since v0.28.0.
A patch release in the strict sense: **nothing on the wire, in the C ABI, in the driver protocol or
in the plugin contract moves.** Every host, client, driver and plugin built against v0.28.0 keeps
working against v0.28.1 and vice versa, in both directions and with no re-pairing.
### Versions
| | v0.28.0 | v0.28.1 | Notes |
|---|---|---|---|
| Wire protocol | 2 | **2** | unchanged |
| C ABI | 19 | **19** | unchanged — `include/punktfunk_core.h` is byte-identical to the v0.28.0 tag |
| Rust edition | 2024 | **2024** | unchanged |
| MSRV (`rust-version`) | 1.85 | **1.85** | unchanged |
| Workspace crate dirs | 27 | **27** | unchanged |
| Virtual-display driver protocol | 6 | **6** | unchanged (minimum accepted still 3) |
| Windows virtual-gamepad channel | 3 | **3** | unchanged |
| Plugin index schema | 1 | **1** | unchanged |
| `api/openapi.json` | 0.27.0 | **0.28.0** | the management API **did** change (two collection deletes, below); the file carries the stamp it was regenerated under, not `0.28.1` |
| gamescope patch level (`+pfhdrN`) | 6 | **7** | 8 patches → 9 (the linger crash); no new capability |
| `@punktfunk/host` (SDK) | 0.1.4 | **0.1.4** | unchanged |
| `@punktfunk/plugin-kit` | 0.4.1 | **0.4.1** | unchanged |
**The `api/openapi.json` stamp is not a per-release counter** and should not be read as one. The
drift test (`openapi_document_is_complete_and_checked_in`) normalizes `info.version` on both sides,
so only the *surface* is gated and a version bump alone never invalidates the snapshot. The table
row says what the file actually says. Regenerating it needs a Linux or Windows host build —
`punktfunk-host` does not compile on macOS.
### ⚠ Breaking changes
**None.** No wire change, no C ABI change, no driver-protocol change, no plugin-contract change.
Three things are worth an embedder's or packager's attention anyway, none of which break a build:
- **The Rust crate gained one public constant.** `punktfunk_core::client::FLUSH_COOLDOWN` was
`pub(crate)`; the host now compares against it rather than against a copy of the number (see the
keyframe-cadence fix below). Addition only.
- **`NativeBridge.nativeStartAudio` takes a third argument** on Android — `isTv`. Detail in the
Android section; this is a JNI signature change, so an out-of-tree caller must pass it.
- **Every Linux packaging channel now ships a second gamescope artifact**, the Vulkan WSI layer,
and a package that carries the compositor without it is *fatal* rather than degraded. If you
repackage `punktfunk-gamescope` downstream, read the gamescope section before rebuilding.
### The management API gains two collection deletes — "unpair all"
Clearing a host's trust store meant one row-level delete per device, each with its own
confirmation. Two new endpoints, one per pairing plane:
```
DELETE /api/v1/clients -> {"unpaired": N}
DELETE /api/v1/native/clients -> {"unpaired": N}
```
They are **not** a loop over the per-fingerprint deletes. Each empties its store in ONE persisted
write, because N deletes would rewrite and atomically rename the store N times and a failure
partway leaves a half-emptied store with nothing saying which half. The two planes are separate
endpoints because they own separate trust stores with separate persistence and separate revocation
duties.
Being collection deletes, they carry the single delete's revocation guarantees across the whole
set: a live session owned by any removed certificate is ended, and on the GameStream side the ENet
control port (UDP 47999) closes, because no pairing is left to hold it open.
**200 with a count, not the single delete's 204/404.** "Unpair everything" is idempotent — an
already-empty store satisfies it — and the count still distinguishes three devices from none.
**Both are admin-token only.** The route-classification gates match on (method, path), so the
roster's plugin-readable `GET` does not carry over to emptying it; both new routes have explicit
rows in the table, like every other pairing-administration route. The native endpoint answers
**503** on a host built without that plane, which is why the console calls only the planes that
actually have a row.
`UnpairAllResult` is the one new schema. `api/openapi.json` is regenerated;
`docs-site/public/openapi.json` is re-synced from it (see **Documentation** at the end).
### The pad-audio "Wireless Controller" speaker hides while no client pad is attached
Field-confirmed (2026-08-14, the same Helldivers 2 reports as below): the per-pad audio endpoint
the Windows host mints — a Steam-Streaming-Speakers instance stamped with a DualSense's name,
container and 4 ch/48 kHz formats, **pre-provisioned at every host start** — is deliberately
indistinguishable from a real DualSense speaker. That disguise is the feature during a pad
session (libScePad titles route haptics audio at it) and a trap the rest of the time: an idle
Helldivers 2 finds the endpoint by identity, engages its DualSense-haptics path against a device
nothing services, and drops to 25 FPS 1% lows — with the host completely idle, no controller
plugged in, and no session ever run. The reporter isolating "the DualSense speaker" and disabling
it in mmsys.cpl restored full performance; that manual remedy is now automatic.
The endpoint now parks **hidden** (`DEVICE_STATE_DISABLED`, via `IPolicyConfig::
SetEndpointVisibility` — the exact call behind mmsys.cpl's Disable) whenever no client pad is
attached: provisioning hides it at startup (and a `PUNKTFUNK_PAD_AUDIO=0` host hides leftovers
from earlier runs), the per-pad streamer shows it for exactly the pad's lifetime — to a game,
indistinguishable from a DualSense arriving and leaving. The devnode, driver binding and stamps
stay put, so the flips raise no PnP traffic and the expensive provisioning still happens once at
boot.
**Operator-visible:** "Speakers (Wireless Controller)" now shows as *disabled* in the Sound
control panel while no client pad is connected — that is the parked state, not a defect. The
`pad-endpoint` devtest grew `show`/`hide` verbs; `tone`/`capture` need a `show` first.
### An idle Windows host no longer owns the box's default microphone
Field report (the second Helldivers 2 one — the first led to v0.28.0's mint-retry fix): with the
host **idle**, a locally played Helldivers 2 tanks to 25 FPS 1% lows, and Windows' own Sound
settings Recording tab goes unresponsive. Root cause: the audio wiring pass asserted *default
recording = the virtual mic's capture side* on **every** pass, including the mic pump's eager
boot pass — and `SetDefaultEndpoint` covers eCommunications, so every game's voice input bound a
virtual microphone whose feeder only runs during a stream. Nothing ever restored it: not session
end, not service stop. Games that hold an always-open voice capture (Helldivers 2 is Wwise +
in-game voice — its own wiki calls the game "finicky with audio devices") stall on that dead
endpoint.
The recording default is now **session-scoped**, exactly like the playback default has always
been: parked on the virtual mic only while a desktop-audio capture is open, the operator's device
remembered (plus an on-disk crash marker, `audio-default-rec.prev`), restored when the capture
closes, recovered at next boot after a crash, and unparked by the uninstaller. A game launched
*during* a stream still records the client's mic; one launched before the stream keeps the
operator's own microphone.
Boxes wedged by earlier builds (which recorded nothing to restore) heal themselves: an idle
wiring pass that finds the default recording sitting on the plan's mic capture moves it back to
the first real microphone.
**Operator-visible:** outside a stream, the default recording device is now whatever you set —
Punktfunk only takes it for the duration of a stream. If you *want* apps to record the client mic
while idle, select "Punktfunk Microphone" manually; the host no longer re-asserts it (idle
re-assertion used to stomp a manual choice within one mic-pump reopen).
### The NixOS module started a second host in root's systemd, which stole the ports from the real one
Found on the first real deployment of `packaging/nix/nixos-module.nix` (NixOS 26.05, punktfunk
0.28.0-nix). The host crash-looped forever on one line:
```
ERROR punktfunk_host: start RTSP server: bind RTSP 48010: Address already in use (os error 98)
```
`systemd.user.*` has no per-user form in NixOS: it installs units into **every** user's systemd
manager. `host.autoStart` then adds them to `default.target` — for every user, including **root**,
whose `user@0.service` springs into existence the moment anybody so much as SSHes in as root. Root's
copy of the host won the race for the fixed ports, and the desktop user's copy could never bind.
The failure is nastier than it sounds because every *other* listener binds first and logs success —
the version banner, mDNS on 47989, the GameStream warning all print normally — so the log reads like
a conflict with some unrelated program. A second copy of *itself*, running as root, is the last
thing anyone looks for. `host.users` did not help: that option only granted `input`/`punktfunk`
group membership and never scoped the units.
Fixed by rendering `ConditionUser=` on all four user units (`punktfunk-host`, `punktfunk-web`,
`punktfunk-web-init`, `punktfunk-scripting`) from `host.users`. Each entry is written `|user` — the
pipe makes it a *triggering* condition, which systemd ORs; plain repeated `ConditionUser=` lines are
ANDed and would have matched nobody. With `host.users` empty the units fall back to
`ConditionUser=!@system`, which still keeps root out while leaving a normal login free to run the
host by hand, as the module header documents.
`packaging/nix/module-check.nix` gained three assertions covering both branches and the fact that
`punktfunk-web-init` keeps its pre-existing (non-triggering) `ConditionPathExists` alongside the new
condition. They run in the `eval` leg of `nix.yml`, and were verified to fail against the unfixed
module before being committed.
### The Steam plugin synced nothing on Windows: its art is in Program Files, the art roots were not
Field report — the plugin installed, the grid stayed empty, and the only clue was one host warn per
sync:
```
plugin:steam sync (fs-change) failed: HostRequestError: PUT /library/provider/steam?store=steam
failed: art.hero: local art must be an image file (…) inside an allowed art root
```
Two independent defects, both fixed here.
**1. Steam's art was never inside an allowed root on Windows.** `art_roots()` defaulted to the users
base (`C:\Users`, from `%PUBLIC%`'s parent), which covers the launchers that install per-user —
Playnite under `%APPDATA%`, Heroic under `%APPDATA%` — but *not* Steam, which installs to
`C:\Program Files (x86)\Steam` and keeps both the art the plugin publishes there:
`appcache\librarycache\<appid>\<hash>\` and each account's `userdata\<id>\config\grid\` overrides.
Every cover the plugin emitted was out of root. This is a v0.28.0 regression: the built-in scanner
the plugin replaced served its covers through the legacy `steam:` art-proxy branch, which never
passed through the H-2 confinement — deleting the scanner routed that art through a gate it had
never been measured against. `art_roots()` now also includes every Steam install root it can find,
from `%ProgramFiles(x86)%` / `%ProgramFiles%` / `%ProgramW6432%` and from HKLM
`Valve\Steam\InstallPath` (so a Steam on another drive is covered too). POSIX needed no equivalent —
every Steam layout there, native and Flatpak, is already under `$HOME`.
This does not weaken the confinement. It exists to stop the host (SYSTEM) reading files the plugin
lane (LocalService) cannot reach itself; the Steam directory is readable by LocalService already, so
nothing there is reachable *because* the host is privileged. The extension, regular-file, magic-byte
and config-dir gates all still apply, so Steam's own `config.vdf` and `ssfn*` credential blobs are
not servable from it — there is a test.
**2. One unservable cover threw away the entire library.** `PUT /library/provider/{p}` validated art
per entry and returned 400 for the whole payload on the first bad value, so a path mismatch cost the
operator *every game from that store*, not a thumbnail — and the plugin, which only ever sees
`HostRequestError`, could not say which. A provider reconcile now **strips** unservable local art and
syncs the rest (`sanitize_art_paths`), logging one aggregated warn naming the count, an example path
and the env var. The invariant the 400 held is unchanged: no unservable path is ever persisted. The
operator's own single-entry custom writes keep the hard 400 — there the path was typed by hand, and
silence would be the wrong answer.
**Operator-visible:** an art-root mismatch no longer fails a sync. If covers are blank where you
expect art, the cue is the host log's `dropped local art the proxy may not serve` line, and the knob
is `PUNKTFUNK_LIBRARY_ART_ROOTS` (which **replaces** the defaults — list every root you need).
### Hyprland/Sway — the wlr-family backends asserted a cursor mode instead of negotiating it
🛑 **Every cursor-forward session on current Hyprland died at `select_sources`** — "pipeline build
failed" and a black client, with `unavailable cursor mode 4` in the portal log.
Hyprland and wlroots both hardcoded portal `CursorMode::Metadata` whenever the session had
negotiated the cursor channel, and never asked the backend what it supports. That is **not** a soft
failure: xdg-desktop-portal's **frontend** validates the requested mode against the backend's
`AvailableCursorModes` and fails the call with `"Unavailable cursor mode %x"` before the backend
ever sees it.
**Measured on glass 2026-08-14, and worse than the report suggested.** Against a live Hyprland
0.56.2 with xdg-desktop-portal-hyprland 1.4.1 and xdg-desktop-portal 1.22.1 — all current —
`AvailableCursorModes` reads **3** (`Hidden|Embedded`) on both the backend impl interface and the
frontend. **xdph does not offer the metadata cursor at all**, so this broke every cursor-forward
session on current Hyprland, not merely on old installs, and **updating the portal would not have
helped.** xdpw is the same from the other end: its `screencast.c` refuses `METADATA` outright.
`pf-capture`'s own portal path has always negotiated (`choose_cursor_mode`); this restates that
ladder in `pf-vdisplay`, which may not depend on `pf-capture`. The downgrade is graceful rather than
merely survivable: with the portal on `Embedded` no `SPA_META_Cursor` arrives, so the host feeds the
cursor channel nothing and a cursor-forward client draws nothing of its own — **one pointer, not
two.**
**`PUNKTFUNK_PORTAL_CURSOR_MODE=auto|hidden|embedded|metadata`** pins the preference for a backend
that advertises a mode it implements badly, which negotiation cannot detect. It is a preference
only: a pin runs the same ladder, so no value can re-create the refused request.
⚠ The module is declared **unconditionally**, so its ladder tests run on every CI leg rather than
only the one that compiles `mod hyprland` — including a Linux-only test pinning our bit values
against ashpd's enum (ashpd answers 4 for `Metadata`, the number in the report), verified
non-vacuous by planting a wrong discriminant.
### Android — the audio plane trusted AAudio, and a TV box that opened a stream it never played was silent for the session
🛑 **Reported from the field: no audio at all on an NVIDIA Shield Android TV, stereo, with the same
host and settings that play fine on an Apple TV.** Video unaffected. Turning off the client's
low-latency mode — which is what gates the forced HDMI mode switch and the `usage=Game` tagging —
changed nothing.
The Android client opens AAudio directly (the Apple client goes through AVAudioEngine, which
reconfigures itself on a route change; that difference is why this was Android-only). Opening
AAudio is a negotiation with a vendor HAL, and this plane treated it as a formality: one Exclusive
attempt, one Shared retry, and everything after the open taken on trust. **Three distinct failures
all presented as "the app has no sound" behind a healthy-looking log**, and none of them was
detected:
- **A configuration that opens but routes nowhere.** Nothing ever checked that the device actually
pulled a sample, so the decode thread would happily decode Opus into a dead stream forever.
- **`request_start` failing.** The old code gave up on the spot instead of trying anything else, so
one unhappy configuration disabled audio for the whole session.
- **A disconnect.** By AAudio's contract a disconnected stream is dead and the only recovery is
close + open a new one. The error callback logged a warning and did nothing else — so an HDMI
mode switch, an AVR re-handshake or any route change meant silence for the rest of the session.
On a TV that is not a rare event: the client itself drives an HDMI mode switch on the video
plane, and the platform's own match-content-frame-rate setting drives more.
The open now walks a **ladder**, every rung has to **prove the device is pulling** before it is
accepted, and a **supervisor** owns the plane for the session and reopens it when the device goes
away (bounded retries across the settling time of a route change, so a reopen landing mid-switch
does not permanently disable audio). The granted rate/channel-count/format are checked against what
was asked for rather than assumed — the realtime callback casts AAudio's buffer to `f32` and writes
`num_frames × channels` of them, so a HAL that disagreed was an out-of-bounds write on the audio
thread, not merely a mistuning.
**Behaviour change on TV boxes: they now start at Shared instead of Exclusive.** Exclusive is
MMAP, the lowest-latency path AAudio has, and the one rung whose routing cannot be verified from
inside the process. The latency it buys here was never actually banked — the jitter-ring depths are
unchanged from the Shared-only era (`JitterTuning::AAUDIO` still primes at 25 ms) — so on a
mains-powered HDMI box the few ms are worth less than not betting the audio plane on it. Phones,
tablets and handhelds are unchanged and still try Exclusive first. If no rung proves itself, the
first one that opened and started is used anyway: the watchdog must never be able to turn working
audio into no audio.
**Embedder-visible:** `NativeBridge.nativeStartAudio` takes a third argument, `isTv`
(`FEATURE_LEANBACK`, the same source the video plane already used).
Three new sysprops bisect all of it on a device that cannot be handed a custom build, alongside the
existing `debug.punktfunk.no_av_sync`: `debug.punktfunk.audio_sharing` (`exclusive`|`shared`),
`debug.punktfunk.audio_perf` (`lowlatency`|`none`) and `debug.punktfunk.audio_reopen` (`0` pins the
old give-up-on-disconnect behaviour). A stream that stops taking samples after it started now says
so at `error` level instead of looking exactly like an app with no sound.
### gamescope — we ship our own Vulkan WSI layer, so a game can reach an HDR10 swapchain (⚠ packager-visible)
🛑 **On essentially every box running a distro gamescope, no game could render HDR at all** — and
nothing said so.
A game nested under gamescope gets an HDR10 swapchain from the FROG WSI layer and from nothing
else: gamescope advertises no runtime colour-management protocol a Mesa/NVIDIA WSI could negotiate
through. That layer speaks `gamescope_swapchain` to the compositor, and when the two disagree the
compositor rejects the client's `swapchain_feedback` and **every Vulkan client dies on a black
screen** with sound and input intact and no error anywhere.
We shipped our own compositor and *not* a layer, on the recorded grounds that the layer is
"version-independent of the compositor binary". It is not — `wsi_layer_matches_our_gamescope()`
exists precisely because it is not — so the host was left guessing from version triples, and that
guess is wrong in both directions. A distro at the same upstream tag that patched the protocol
compares EQUAL and keeps a layer that will black-screen every game; a distro at a different tag
with a byte-identical protocol compares unequal and loses HDR for nothing. **Since we pin a rev,
the second case is the normal one.**
We now build the layer from the same tree at the same rev as the compositor and ship it, so the two
cannot drift and the guess stops being load-bearing. It installs under **our own** name
(`VK_LAYER_PUNKTFUNK_gamescope_wsi`), at our own path, with our own enable/disable variables, so it
coexists with the distro's rather than colliding — the Vulkan loader keys implicit layers on that
name — and the host switches the two independently within one session.
`WsiPlan` resolves three states once per launch (the fallback spawns `--version` probes):
| state | condition | action |
|---|---|---|
| `Ours` | our layer is installed | enable ours, force the distro's off — **both halves, or it is a bug** |
| `DistroKept` | no layer of ours, distro's looks compatible | touch nothing |
| `DistroDisabled` | no layer of ours, distro's untrusted | v0.28.0's behaviour |
That last arm is the fail-safe: a host newer than its gamescope package behaves exactly as it did,
rather than enabling a layer that is not there.
**What packagers must know.** The layer manifest carries an **absolute** `library_path` baked in
at build time, so every channel installs the `.so` at exactly that path: literal
`/usr/lib/punktfunk`**not** `%{_libdir}` (which is `/usr/lib64` on Fedora) and not a Debian
multiarch triplet. Nothing links it by soname (the loader `dlopen`s it by that path), so multilib
has no claim. rpm and nix read the path back **out of the manifest** and fail if it names a file the
package does not install, because a manifest pointing at nothing is the silent shape of this bug.
A missing layer is **fatal in every channel**, not best-effort: a package carrying the compositor
without it looks completely healthy and then silently denies every game an HDR10 swapchain.
The packaging scripts now take `--stage` (the DESTDIR the gamescope build script wrote) instead of
a path to one binary, and CI caches the whole staged tree; the `gs-cache` key already hashes
`packaging/gamescope/**`, so stale caches in the old single-file shape cannot be restored into the
new layout. The manifest rewrite lives in `packaging/gamescope/rewrite-wsi-layer-manifest.py`
rather than a heredoc, because the FHS builds and the Nix store both need it and must rename the
layer identically. **NixOS has no `/usr`**, so the layer lives inside the gamescope derivation and
the host's path is overridable with **`PUNKTFUNK_GAMESCOPE_WSI_LAYER_DIR`**, which the module sets
— the same posture as `PUNKTFUNK_GAMESCOPE_BIN`.
### gamescope — HDR sessions anchored SDR white a stop bright, and never said game HDR was unreachable
🛑 **Field report: Steam's Big Picture UI glaring and over-saturated while HDR game content looked
washed out, on the same stream.** Those are one error.
gamescope maps everything that is not an HDR game — the desktop, the Steam overlay, an SDR title —
into the session's PQ container at `--hdr-sdr-content-nits`, and we passed that flag **only** when
an operator had set `PUNKTFUNK_GAMESCOPE_SDR_NITS`. Unset, gamescope used its own default of
**400**, while every first-party client anchors diffuse white at **203** (BT.2408 reference white;
the Apple presenter hands exactly that to `CAEDRMetadata.hdr10`'s `opticalOutputScale`). The two
ends sat nearly a stop apart, so the UI landed above SDR white and the client's tone-mapper worked
from a reference point the host had never used, flattening the content around it.
**The flag is now always passed, defaulting to 203.** `PUNKTFUNK_GAMESCOPE_SDR_NITS` still
overrides it for anyone who wants a brighter or dimmer desktop — it is the anchor, not a taste
knob. ⭐ Because it is an env var, a field A/B needs **no rebuild**.
Separately, and visible in the same log: the two HDR decisions in a gamescope session were made
independently. `hdr_args()` never consulted `wsi_layer_matches_our_gamescope()`, so when the layer
check fired the session launched **advertising HDR while having made an HDR10 swapchain
unreachable for every game in it** — a title told to render HDR rendered it into an SDR swapchain
and looked washed out, with nothing anywhere saying why. It now warns. The behaviour of the check
itself is deliberately unchanged; the section above is the real fix.
### punktfunk-gamescope `+pfhdr7` — a lingered session no longer dies of its own capture teardown
🛑 **On client disconnect the host keeps the headless gamescope alive so a reconnect resumes the
same session — and gamescope could SIGSEGV in exactly that window, so the kept display was dead and
reconnect silently got a fresh compositor with the game lost.** When the capture consumer leaves,
PipeWire's `remove_buffer` (and the stale-push path in `dispatch_nudge`) destroyed idle buffers on
the **PipeWire thread**; dropping the last `CVulkanTexture` reference there calls into the Vulkan
driver (`vkDestroyImage`/`FreeMemory`/dmabuf fds) while steamcompmgr can still be inside
`vulkan_screenshot` on another buffer of the same 4-buffer pool. On NVIDIA that races to a SIGSEGV
in `CVulkanCmdBuffer::insertBarrier` — timed at stream end, which is why it selectively killed
linger. The journal signature: linger line → coredump → `kept display was dead — recreating`.
Patch 0009 queues those corpses on the PipeWire thread and has steamcompmgr reap them on every
vblank — including while the stream is paused, which is precisely the linger state. Found, fixed
and proven live by **luxus** ([punktfunk-overlay#9](https://github.com/luxus/punktfunk-overlay/issues/9)):
four coredumps on 4K60 HDR + composited cursor, zero after; disconnect/reconnect now reuses the
lingered session. Banner `+pfhdr6``+pfhdr7` (no new capability — but "reconnect lost my game"
triage must be able to read a box's exposure off its banner, the same rule as `+pfhdr5`/`6`).
### Apple — the stats overlay lied three ways, and every host-anchored number with it
🛑 **Two sessions minutes apart on the same wire read `hostnet_p50` 1721 ms, then a physically
impossible 4.4 ms** — host-side encode alone is ~4.7. Three independent defects, all of which
corrupt any measurement taken against a host clock:
- **A frozen clock-offset.** The client consumed the **connect-time** skew offset and cached it —
in a `Stage2Pipeline` field, in a `StreamPump` `let`, and in a `ContentView` closure **capture
list** feeding the hostnet meter and the host/network splitter. The core keeps a *live* estimate
(`punktfunk_connection_clock_offset_now_ns`, ABI v10, re-synced every 60 s and on suspected
wall-clock steps) whose own doc says the connect-time value "silently corrupts every
capture-clock comparison" after an NTP step — **and a VM host steps.**
`PunktfunkConnection.clockOffsetNs` is now the live read (an atomic load behind the FFI), read at
use: per record, per AU, per enqueue. The Swift audio plane's AvSync observation takes the same
live value.
- **Silently trimmed impossible samples.** `LatencyMeter`'s guard (≤ 0 after offset correction)
dropped samples without counting them, so a wrong offset did not invalidate a window — it trimmed
the impossible half of the shifted distribution and presented the surviving tail as a plausible
small number. That is the origin of the historical "0 ms network / 0 ms e2e" readings. Refusals
are now counted and drained **separately from `Stats`** — deliberately, because a fully-poisoned
window drains to `nil` and a count inside `Stats` would vanish with it. The HUD shows an orange
**`clock offset suspect`** line and the stats line grew **`skew_trim=N`**; nonzero means
disregard `e2e`/`hostnet` for that window.
- **`-1` fallbacks printing as `NaN`.** In a `CVarArg` context `cond ? someDouble : -1` does **not**
unify to `Double` — the literal goes in as `Int`, and `%f` reads `Int64(-1)`'s all-ones bit
pattern, which is a quiet NaN. Latent since the 1 Hz stats line existed. All fallbacks are now
typed `-1.0`.
**Any client-side e2e or hostnet figure recorded before this release is suspect** and worth
re-measuring rather than trusted as a baseline.
Two new levers ship with the tvOS present-floor investigation, both env-only:
**`PUNKTFUNK_FRAME_LATENCY`** (float 0…4, default 1) makes the `preferredFrameLatency` ask
adjustable, so an on-device ladder can establish whether the property does anything on tvOS — the
previous "immovable two-refresh floor" verdict rested on a **readback** of a plain read-write
float, which is not a grant. **`PUNKTFUNK_PRESENTER=stage1` now resolves on Release builds** (the
persisted picker stays DEBUG-gated; an env var takes a `devicectl`/Xcode launch to exist, so it is
never a leftover). Stage-1 presents on the hardware video plane rather than through the GPU
compositor — the one rung that can dodge the two-refresh regime — and the field A/B that concluded
otherwise had silently run stage-4, because the gate keyed on build config.
### Apple — two colour faults: an SDR stream shipped untagged, and it forced the TV into HDR10
- **The SDR layer was never tagged.** `configure(hdr:)` guards on `hdr != hdrActive` and
`hdrActive` starts `false`, so a session that is SDR from its first frame matched the initial
state, fell through the guard, and `configureColor` never ran once — the layer kept `make()`'s
bare configuration, which assigns no colour space. An untagged `CAMetalLayer` gets no colour
matching: a BT.709 stream is drawn in the display's native space. Mild oversaturation on a P3 Mac
or iPad; on a tvOS display composited for HDR it also lifts the black floor. ⚠ It also made
`PUNKTFUNK_SDR_COLORSPACE` **dead code on exactly the sessions it exists to fix**, so a field A/B
of that knob would have shown no change.
- **An SDR stream drove an HDR-capable TV into PQ output.** `applyDisplayCriteriaIfNeeded` builds a
synthetic format description hardcoding BT.2020 primaries, ST.2084 and the BT.2020 matrix, then
hands it to `AVDisplayManager` — and its guard checked only that no criteria had been set and that
the user's HDR *setting* was on, never that **the stream** was HDR. That setting defaults to true.
The Apple TV switches HDMI to limited range in its HDR modes, so a set configured for full range
renders code 16 as grey rather than black. Now gated on `connection.isHDR` as well; layout re-runs
it, so a session that flips to HDR mid-stream still picks the mode up.
### Apple — the macOS device-change recovery could answer itself forever (mic on)
**Streaming from a Mac with the microphone enabled cut audio AND input on a ~2.5 s metronome
while video ran untouched** (field, 2026-08-14: a Mac Studio whose default input is a 6-channel
device). The chain: the voice-processing engine cannot start on that mic, every rebuild re-tried
it, and the failed attempt's HAL churn (VPIO builds and tears down an aggregate device) stopped
the healthy fallback engines — which posted the `AVAudioEngineConfigurationChange` that scheduled
the next rebuild. Each ~1.9 s rebuild runs on the main thread, where macOS input capture and
sending live, so input froze on the same beat — and since audio, input and mic share the QUIC
datagram plane while video rides its own socket, the wire signature read as a network fault and
the host's METRONOMIC heuristic pointed at the display stack. Three defenses, layered because no
single one covers every feedback shape:
- **A voice-processing start failure latches per input device** (`CombinedTopologyGate`): a
rebuild goes straight to the split topology instead of re-running a failure that is a property
of the device. A different default input earns exactly one fresh attempt.
- **A configuration change posted by an engine that is RUNNING is the rebuild's own echo, and is
ignored**: an engine stops itself before posting, so a live poster was already restarted.
- **Rebuilds that chain anyway back off exponentially** (`RebuildBackoff`: 0.5 s floor doubling
to a 30 s cap, reset by 10 s of quiet) — an unforeseen loop costs one blip per half-minute
instead of a metronome, and the chaining itself logs a WARN that names the condition.
iOS/tvOS behaviour is untouched (routes are session-managed there; nothing is latched). Until a
client carries this, the field workaround is turning the client microphone off.
**And the engines no longer start on the main thread at all.** An engine start can block on the
audio server for seconds (~1.9 s per attempt in the field case) and macOS captures and sends the
stream's input from the main thread — so even a single legitimate device switch froze input for
the length of the rebuild, loop or no loop. All engine build/start/teardown now runs on a
per-session serial `engineQueue`; the main queue keeps only the trigger bookkeeping (debounce,
backoff, retry ladder), which is cheap by construction. ⚠ Embedder-visible edge:
`SessionAudio.start()` is now asynchronous on macOS too (it always was on iOS/tvOS) — playback is
live shortly after the call, not on return, and `stats` is safe from any thread.
### Apple gamepad UI — a host menu, and About becomes a page
**UP on a saved tile opens Wake / Copy link / Edit… / Forget pairing / Remove.** The desktop and
Android consoles have had this for a while; this is the Apple port, so the three consoles are
learned once. Wiring UP takes the whole vertical axis away from scrolling (down goes inert) — a
horizontal carousel has no vertical travel to spend, and one meaning per direction is what makes
the gesture learnable. **Remove arms on the first press and fires on the second**, disarming if
focus wanders off the row: the touch grid gets a system confirmation dialog, and a thumbstick from
across a room deserves at least as much. Edit reuses `GamepadAddHostView` seeded from the record and
writes a **copy** back through `HostStore.update`, so the fingerprint, MACs, pins and binding the
form never shows survive a rename; it **replaces** the menu rather than stacking on it, keeping the
shell's "depth ≤ 1 by construction" true. A pinned profile card offers only Unpin — it is a
shortcut, not a second host.
**The start-of-stream shortcut banner is retired.** Telling someone the controls for six seconds,
over the stream they just connected to, answers the question at the one moment nobody is asking it
— and it put a composited overlay above the stream to do it. The words are now a catalogue rendered
in an About page you can open, which is also its own section rather than the last row of Interface.
Its remaining fixes: the identity card became a version line under the rows, a zero-radius clip is
still a clip (it cropped the TV's wide icon), and the card ignored the row column.
**Apple console screens read the ink they publish.** A SwiftUI screen cannot read the environment
value it publishes in the same view — so a pale palette stayed white-on-white on Apple TV. Fixed
across every console screen.
### Console UI — Skia sized its function table to the loader, not to what we promised
🛑 **On a Steam Deck the console home died on update**, and in a stream the same failure quietly
cost the stats OSD and capture HUD.
The skia-safe 0.87 → 0.99 move swapped `BackendContext::new` for `new_builder(…, None)` and
recorded the `None` as "byte-for-byte what the removed constructor did". True of the **value**,
false of the **behaviour**: `None` leaves Skia's `fMaxAPIVersion` at its `0` sentinel, and the newer
Skia acts on that sentinel by falling back to **`vkEnumerateInstanceVersion()` — the loader's
ceiling, not ours.** The presenter declares 1.3; a current Mesa answers 1.4 (1.4.321 on SteamOS
3.7, host and inside the flatpak sandbox alike). Skia then validates a 1.4 function table against an
instance that only promised 1.3, `vkGetDeviceProcAddr` returns null for the entry points in
between, and `make_vulkan` hands back `None`. At 0.87 the sentinel was inert because that Skia knew
nothing of Vulkan 1.4 — **which is why this surfaced the moment v0.28.0 landed.**
`run.rs` makes an overlay that cannot init fatal for `--browse`, so the Decky panel's button and the
gamepad-UI library shortcut both failed to open. The presenter now publishes
`SharedDevice::api_version``min(what we declared, what the loader reports)` — and
`SkiaOverlay::init` passes it instead of `None`. ⚠ `pf-presenter`'s `vk` module is
`cfg(any(linux, windows))`, so this was never Deck-specific.
### pf-vkdecode — AV1's "maximum parameters" level is not a level above the ceiling
🛑 **Every AV1 session demoted to D3D11VA** with `stream level (seq_level_idx 31) above the device's
maxLevel (AV1 Std level 23)` — on hardware decoding the stream trivially on the rung it fell
through to.
`seq_level_idx` is a 5-bit field: Annex A defines 0…23 (levels 2.0…7.3), reserves 24…30, and makes
**31 the "maximum parameters" level — the spec's own way of saying the bitstream is not constrained
to a level.** `StdVideoAV1Level` stops at 7.3 = 23, so 31 has no Std code point and the index-coded
comparison that holds across 0…23 says nothing: `31 > 23` is true even of a device that decodes
everything AV1 can name, which is what makes it useless as a capability test. We write no AV1 level
on any host encode path, so whichever sentinel the vendor's encoder defaults to is what the client
must accept. This is the AV1 half of the same defect fixed for H.264/H.265 in v0.28.0, which was
left alone on the premise that no over-declaration had been seen in the field — the reporter's log
from that same day already showed otherwise.
### Client stats — the stage line is a partition again
A field reader added up `host 5.4 · net 0.3 · decode 6.6 · display 1.4` against `e2e 8.1` and asked
why the parts did not sum. Fair question: they sum **without** `decode`.
The stages *are* a per-frame partition of e2e — pts →(host+net)→ received →(decode)→ decoded
→(display)→ displayed — for as long as the `decoded` stamp is a **completion** stamp. On the
synchronous rungs it is. On the **native-Vulkan** rung `receive_frame` returns at *submission*
(~0.1 ms) and the stamp is taken there, so `display` is measured from submit and the GPU decode
happens **inside** it. `host+net` and `display` already tile e2e; the `decode` figure (received →
fence-complete) re-counts the GPU work `display` contains — two figures with one overlap, printed
as though they tiled.
On that rung `decode` now leaves the stage line and gets its own, carrying the two caveats a reader
needs: it is **one sample per window** there, not the p50 every other figure on that line is, and it
is already inside `display`, so adding it double-counts. The synchronous rungs are untouched.
**Deliberately not changed:** the one-sample-per-window design. A per-frame fence wait serialises
the decode pipeline (an APU's 19 ms decode capping a 5120×1440 stream at ~51 fps) and polling
quantises every sample up by a frame interval. The reporting was the defect, not the sampling.
### Host — two warnings that named the wrong subsystem
Both fired in the same 2026-08-13 field log, and both sent an investigation somewhere innocent:
- **"Client keyframe recoveries are METRONOMIC — a periodic host/display disturbance … is the
likely cause"**, at `period_s=2.0`, naming three host subsystems. **2.0 s is the *client's*
`FLUSH_COOLDOWN`.** The receive-backlog guard sheds a standing queue with a flush plus a keyframe
request, rate-limited to one per cooldown, so a client that cannot sustain the stream asks for a
keyframe at exactly that spacing for as long as it stays behind. **Perfect periodicity is the
signature of a fixed software cooldown, not of a physical disturbance.** The host now compares
against `punktfunk_core::client::FLUSH_COOLDOWN` itself rather than a copy of the number, so the
two cannot drift.
- **"The audio encode thread could not keep up — captured audio was DROPPED"**, worst case
`dropped_chunks=11251`. Not one sample anybody wanted was lost. PipeWire negotiated a 128-frame
quantum, so the plane produces 48000/128 = 375 chunks/s and a 30 s window holds exactly 11250 —
a 100 % drop rate at `peak_db=-120.0`, digital silence. Every one of the ten warnings straddled a
**session boundary**, and `dropped_chunks/375` matches the seconds with *no live session* in that
window to within a fraction of a second. The warning no longer fires for idle seconds.
### NixOS — the plugin runner was installed, running, and reported missing
@@ -52,6 +629,19 @@ NixOS ships only `sh` in `/bin`, so `gamelease`'s hand-off test and `pyrowave_re
handshake-rung test failed there for reasons unrelated to the code under test. Both now resolve a
real binary rather than assuming an FHS path.
### Documentation
**`docs-site/public/openapi.json` was stale again, and by the same mechanism as last release.**
v0.28.0 fixed it once (it was five releases behind at `0.21.0`); the scanner-removal regen then
updated `api/openapi.json` alone and it drifted a second time inside that same cycle. It has now
drifted a third time, across the unpair-all endpoints — the docs-site copy was still stamped
`0.27.0` and missing both collection deletes. Re-synced; the two files are byte-identical again.
⚠ **The copy is a documented manual step (`cp api/openapi.json docs-site/public/openapi.json`,
CONTRIBUTING.md) and nothing in CI enforces it.** Three drifts in two release cycles is the
argument for gating it; until something does, **treat the copy as part of regenerating, not as a
follow-up.**
---
## v0.28.0
Generated
+36 -36
View File
@@ -1090,7 +1090,7 @@ dependencies = [
[[package]]
name = "cursor-probe"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"anyhow",
"pf-capture",
@@ -1222,7 +1222,7 @@ dependencies = [
[[package]]
name = "display-disturb"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"pf-win-display",
"windows 0.62.2 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -2343,7 +2343,7 @@ dependencies = [
[[package]]
name = "latency-probe"
version = "0.28.0"
version = "0.28.1"
[[package]]
name = "lazy_static"
@@ -2446,7 +2446,7 @@ dependencies = [
[[package]]
name = "libvpl-sys"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"bindgen",
"cmake",
@@ -2475,7 +2475,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "loss-harness"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"punktfunk-core",
]
@@ -2967,7 +2967,7 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pf-bitstream"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"cros-codecs",
"tracing",
@@ -2975,7 +2975,7 @@ dependencies = [
[[package]]
name = "pf-capture"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"anyhow",
"ashpd",
@@ -2996,7 +2996,7 @@ dependencies = [
[[package]]
name = "pf-client-core"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"anyhow",
"ash",
@@ -3031,7 +3031,7 @@ dependencies = [
[[package]]
name = "pf-clipboard"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"anyhow",
"ashpd",
@@ -3049,7 +3049,7 @@ dependencies = [
[[package]]
name = "pf-console-ui"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"anyhow",
"ash",
@@ -3071,7 +3071,7 @@ dependencies = [
[[package]]
name = "pf-dxvadec"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"cros-codecs",
"pf-bitstream",
@@ -3081,7 +3081,7 @@ dependencies = [
[[package]]
name = "pf-encode"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"anyhow",
"ash",
@@ -3107,7 +3107,7 @@ dependencies = [
[[package]]
name = "pf-frame"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"anyhow",
"libc",
@@ -3119,7 +3119,7 @@ dependencies = [
[[package]]
name = "pf-gpu"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"anyhow",
"pf-host-config",
@@ -3133,11 +3133,11 @@ dependencies = [
[[package]]
name = "pf-host-config"
version = "0.28.0"
version = "0.28.1"
[[package]]
name = "pf-inject"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"anyhow",
"ashpd",
@@ -3166,14 +3166,14 @@ dependencies = [
[[package]]
name = "pf-paths"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"tracing",
]
[[package]]
name = "pf-presenter"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"anyhow",
"ash",
@@ -3188,7 +3188,7 @@ dependencies = [
[[package]]
name = "pf-update"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"serde",
"serde_json",
@@ -3196,7 +3196,7 @@ dependencies = [
[[package]]
name = "pf-update-check"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"anyhow",
"aws-lc-rs",
@@ -3208,7 +3208,7 @@ dependencies = [
[[package]]
name = "pf-vaadec"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"cros-codecs",
"pf-bitstream",
@@ -3217,7 +3217,7 @@ dependencies = [
[[package]]
name = "pf-vdisplay"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"anyhow",
"ashpd",
@@ -3250,7 +3250,7 @@ dependencies = [
[[package]]
name = "pf-vkdecode"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"ash",
"cros-codecs",
@@ -3261,7 +3261,7 @@ dependencies = [
[[package]]
name = "pf-win-display"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"pf-paths",
"punktfunk-core",
@@ -3272,7 +3272,7 @@ dependencies = [
[[package]]
name = "pf-zerocopy"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"anyhow",
"ash",
@@ -3484,7 +3484,7 @@ dependencies = [
[[package]]
name = "punktfunk-cli"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"pf-client-core",
"punktfunk-core",
@@ -3494,7 +3494,7 @@ dependencies = [
[[package]]
name = "punktfunk-client-android"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"android_logger",
"jni",
@@ -3512,7 +3512,7 @@ dependencies = [
[[package]]
name = "punktfunk-client-linux"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"anyhow",
"async-channel",
@@ -3529,7 +3529,7 @@ dependencies = [
[[package]]
name = "punktfunk-client-session"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"pf-client-core",
"pf-console-ui",
@@ -3543,7 +3543,7 @@ dependencies = [
[[package]]
name = "punktfunk-client-windows"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"async-channel",
"mdns-sd",
@@ -3561,7 +3561,7 @@ dependencies = [
[[package]]
name = "punktfunk-core"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"aes-gcm",
"cbindgen",
@@ -3593,7 +3593,7 @@ dependencies = [
[[package]]
name = "punktfunk-encode-worker"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"pf-encode",
"tracing",
@@ -3602,7 +3602,7 @@ dependencies = [
[[package]]
name = "punktfunk-host"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"aes",
"aes-gcm",
@@ -3672,7 +3672,7 @@ dependencies = [
[[package]]
name = "punktfunk-probe"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"anyhow",
"mdns-sd",
@@ -3686,7 +3686,7 @@ dependencies = [
[[package]]
name = "punktfunk-tray"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"anyhow",
"ksni",
@@ -3709,7 +3709,7 @@ checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "pyrowave-sys"
version = "0.28.0"
version = "0.28.1"
dependencies = [
"bindgen",
"cmake",
+1 -1
View File
@@ -65,7 +65,7 @@ exclude = [
ndk = { path = "clients/android/native/vendor/ndk" }
[workspace.package]
version = "0.28.0"
version = "0.28.1"
edition = "2024"
rust-version = "1.85"
license = "MIT OR Apache-2.0"
+5 -1
View File
@@ -5,13 +5,17 @@ machine, so we take security reports seriously and appreciate responsible disclo
## Supported versions
Punktfunk ships on two tracks — **stable** (a `vX.Y.Z` tag; the current line is **0.22.x**) and
Punktfunk ships on two tracks — **stable** (a `vX.Y.Z` tag) and
**canary** (built from `main`). Fixes ship as a new release on those tracks; in practice
we don't backport to older minor versions, so the supported versions are the latest stable release
and the current canary build. If you're on an older build, please check that the issue still
reproduces on the latest stable before reporting it. See
[Release Channels](https://docs.punktfunk.unom.io/docs/channels).
Security fixes are **free of charge**, ship **without undue delay**, and are **separated from
feature updates where feasible**: on the stable track they arrive as patch releases (`vX.Y.Z+1`)
that carry the fix rather than waiting on the next feature release.
## Reporting a vulnerability
**Please report security issues privately by email to security@punktfunk.com.**
+97 -1
View File
@@ -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}": {
@@ -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}": {
@@ -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).",
+15
View File
@@ -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"
@@ -816,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)
@@ -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 hostclient audio: Opus decode jitter ring AAudio (LowLatency), all in Rust.
* Start hostclient 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)
File diff suppressed because it is too large Load Diff
+6 -5
View File
@@ -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
@@ -826,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(
@@ -845,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
@@ -1075,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)
@@ -1166,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
@@ -28,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.
@@ -60,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)
@@ -101,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.
@@ -205,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),
]
}
@@ -264,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)
}
@@ -94,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
@@ -122,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
@@ -204,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
}
@@ -264,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) }
@@ -280,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,
@@ -417,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)
@@ -472,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 }))
@@ -546,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 })
@@ -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
@@ -88,6 +88,11 @@ struct GamepadInk: Equatable, Sendable {
/// 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 {
@@ -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
}
}
@@ -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()
}
@@ -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,6 +42,9 @@ 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 {
@@ -53,6 +56,8 @@ struct GamepadSettingsView: View {
@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).
@@ -64,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
@@ -135,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(
@@ -160,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))
@@ -329,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`).
@@ -386,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()
}
@@ -393,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.
@@ -505,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
@@ -530,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
}
@@ -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
}
}
@@ -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 (captureon-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 (captureon-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,
@@ -342,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)
@@ -356,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 {
@@ -374,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()
@@ -513,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) {
@@ -523,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()
@@ -549,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)
@@ -572,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)")
}
@@ -594,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
@@ -610,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,
@@ -626,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("""
@@ -637,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)
}
}
@@ -786,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)
}
@@ -813,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)?
{
@@ -823,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
@@ -983,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
@@ -1001,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
@@ -1054,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
@@ -1064,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)
@@ -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`.
@@ -597,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)
}
@@ -633,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
@@ -646,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
@@ -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
}
+8 -2
View File
@@ -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
+29 -18
View File
@@ -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
+130 -23
View File
@@ -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 }
}
+9 -1
View File
@@ -62,10 +62,18 @@
{
"type": "application",
"name": "punktfunk-gamescope",
"version": "upstream gamescope pinned by packaging/nix/gamescope.nix (nixpkgs) or built by packaging/gamescope/build-punktfunk-gamescope.sh, plus 3 local patches from packaging/gamescope/patches/",
"version": "upstream gamescope pinned by packaging/nix/gamescope.nix (nixpkgs) or built by packaging/gamescope/build-punktfunk-gamescope.sh, plus the local patch series from packaging/gamescope/patches/",
"description": "Patched gamescope compositor distributed via sysext/Arch/nix channels alongside the host",
"licenses": [{ "license": { "id": "BSD-2-Clause" } }],
"externalReferences": [{ "type": "vcs", "url": "https://github.com/ValveSoftware/gamescope" }]
},
{
"type": "application",
"name": "Bun",
"version": "1.3.14 (pinned in .gitea/workflows/windows-host.yml)",
"description": "Portable JavaScript runtime bundled in the Windows host installer to run the web console (.output) and the plugin/script runner. Embeds JavaScriptCore (LGPL-2.1).",
"licenses": [{ "license": { "id": "MIT" } }],
"externalReferences": [{ "type": "vcs", "url": "https://github.com/oven-sh/bun" }]
}
]
}
+51
View File
@@ -0,0 +1,51 @@
# Vendored & bundled components — CVE watch and update cadence
Due-diligence record for every third-party component that ships with Punktfunk but is
**not** tracked by a package manager's advisory feed (CRA Art. 13(5); Annex I Part II §1).
Everything resolved through Cargo/bun/pnpm lockfiles is already scanned weekly by
`.gitea/workflows/audit.yml` (cargo-audit against RustSec, bun/pnpm audit) — this file
covers what those scanners cannot see: vendored source trees, git-rev pins, and binaries
staged into installers. The component inventory itself lives in
`compliance/sbom/manual-components.cdx.json` and is merged into every release SBOM;
keep the two files in sync when a component is added, removed, or re-pinned.
Owner for all of it: Enrico (sole maintainer). Standing cadence: **walk this table once
per quarter and before every stable release**; act immediately on any advisory from the
watch feeds below.
| Component | Where / pin | How to update | Watch |
|---|---|---|---|
| **pyrowave** (+ Granite, volk, Vulkan-Headers subtree) | `crates/pyrowave-sys/vendor/pyrowave`, pin = `PYROWAVE_COMMIT` in `scripts/vendor-pyrowave.sh`; exact commits recorded in `vendor/pyrowave/PUNKTFUNK-VENDOR.txt` | Bump the commit in the script, re-run it (network required; never from CI), re-apply `crates/pyrowave-sys/patches/`. ⚠️ **Bitstream changes are protocol-affecting** — the wire bit means "PyroWave as of this pin"; a bitstream-changing bump must bump the protocol version and re-diff the Apple Metal hand-port (see the script header). | GitHub releases/commits of Themaister/pyrowave + Themaister/Granite (niche projects, no CVE feed — repo watch is the feed) |
| **libvpl** 2.17.0 | `crates/libvpl-sys/vendor/libvpl` (dispatcher statically linked; needs cmake + libclang) | Manual re-vendor from intel/libvpl at the new tag; rebuild `libvpl-sys` | Intel Security Center (INTEL-SA advisories for oneVPL/media) + intel/libvpl releases |
| **windows-rs** git pin | `rev = acb5a1a7…` on microsoft/windows-rs (workspace `[patch]`/git deps: `windows`, `windows-reactor`, …) | Move the rev / return to crates.io once the needed fixes are released. Note: cargo-audit matches these by name+version from Cargo.lock, but a pre-release rev may not map cleanly onto RustSec advisories — treat the pin itself as the thing to retire. | RustSec (already weekly) + microsoft/windows-rs releases |
| **usbfs-iso / uac-host** git pin | `rev = f3de1fd…` on unom-io/usbfs-iso | First-party fork — we are upstream; fix in the fork, move the rev | Own repo (issues land in our tracker) |
| **FFmpeg** (host encode only) | Linux: system `libav*` (distro-updated, not ours to patch — but Arch soname majors can break us, see ffmpeg9 note). Windows: AMF/QSV shared DLLs staged from `FFMPEG_DIR` by `pack-host-installer.ps1`; LGPL notice bundled | Windows: rebuild/refresh the staged DLL set, ship in the next installer. Linux: nothing to ship; verify against new distro majors | ffmpeg-security announcements (ffmpeg.org security page) — a libav* CVE in decode/parse paths we use ⇒ refresh the Windows DLLs without undue delay |
| **SDL3** | Desktop clients, dynamically linked; system-provided or bundled per platform package | Bump the bundled copy in the affected package; system copies are distro-updated | libsdl-org/SDL GitHub security advisories + releases |
| **gamescope** + patch series | Pin in `packaging/nix/gamescope.nix` / built by `packaging/gamescope/build-punktfunk-gamescope.sh`; local patches in `packaging/gamescope/patches/` | Bump the pin, re-rebase the patch series, rebuild sysext/Arch/nix + .deb channels. ⚠️ the gamescope CI legs are best-effort: a broken patch shows up as a *missing package*, not a red build | ValveSoftware/gamescope releases + security advisories |
| **Bun runtime** 1.3.14 | Pinned in `.gitea/workflows/windows-host.yml` (`bun-v1.3.14`); bundled portable in the Windows host installer to run the web console + plugin runner. Embeds JavaScriptCore | Bump the version string in the workflow; next installer build picks it up | oven-sh/bun releases (security notes ride in release notes) |
Not on this list on purpose:
- **VB-CABLE** — no longer bundled (audio-substrate program, 2026-08; the host mints its
own virtual audio devices). If it ever returns, it returns to this table first.
- **openh264 / rav1d CPU decode floor** — crates.io dependencies with vendored C/asm
inside the `-sys` crates; cargo-audit tracks the crate advisories, and the upstream
(Cisco openh264, memorysafety/rav1d) security feeds surface through RustSec. No
separate manual watch needed unless we pin them to git.
## Security-update availability (CRA: ≥10 years)
Where users fetch fixes, and why old artifacts don't vanish (verified 2026-08-14):
- **Gitea releases + package registries** (git.unom.io): no cleanup rules configured,
and Gitea does not expire releases or packages on its own — the full release history
(v0.17.x through current) is still served with assets. Blobs live in the `unom-git`
S3 bucket with an R2 mirror, and the box is restic-backed every 6 h. Old release
assets (and their `.sha256` sidecars) therefore stay downloadable.
- **Bazzite sysext feeds**: stable channels publish with `KEEP=0` (keep everything);
only canary channels prune (`KEEP=6`) — see `rpm.yml` + `publish-sysext-feed.sh`.
- **Flatpak repo** (flatpak.unom.io): published by rsync *without* `--delete`; old
OSTree commits accumulate, both channels stay in the signed summary.
- **Policy**: never add cleanup that deletes *security* releases; if storage pressure
ever forces pruning, prune canary builds, never tagged stable releases. SBOMs are
release assets, so the ≥10-year SBOM retention rides on the same guarantee.
+29
View File
@@ -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();
+19 -2
View File
@@ -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"),
+96 -4
View File
@@ -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":
///
+87
View File
@@ -0,0 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="dpms">
<copyright><![CDATA[
SPDX-FileCopyrightText: 2015 Martin Gräßlin
SPDX-License-Identifier: LGPL-2.1-or-later
]]></copyright>
<interface name="org_kde_kwin_dpms_manager" version="1">
<description summary="Output dpms manager">
The Dpms manager allows to get a org_kde_kwin_dpms for a given wl_output.
The org_kde_kwin_dpms provides the currently used VESA Display Power Management
Signaling state (see https://en.wikipedia.org/wiki/VESA_Display_Power_Management_Signaling ).
In addition it allows to request a state change. A compositor is not obliged to honor it
and will normally automatically switch back to on state.
Warning! The protocol described in this file is a desktop environment
implementation detail. Regular clients must not use this protocol.
Backward incompatible changes may be added without bumping the major
version of the extension.
</description>
<request name="get">
<description summary="Get org_kde_kwin_dpms for wl_output">
Factory request to get the org_kde_kwin_dpms for a given wl_output.
</description>
<arg name="id" type="new_id" interface="org_kde_kwin_dpms"/>
<arg name="output" type="object" interface="wl_output"/>
</request>
</interface>
<interface name="org_kde_kwin_dpms" version="1">
<description summary="Dpms for a wl_output">
This interface provides information about the VESA DPMS state for a wl_output.
It gets created through the request get on the org_kde_kwin_dpms_manager interface.
On creating the resource the server will push whether DPSM is supported for the output,
the currently used DPMS state and notifies the client through the done event once all
states are pushed. Whenever a state changes the set of changes is committed with the
done event.
</description>
<event name="supported">
<description summary="Event indicating whether DPMS is supported on the wl_output">
This event gets pushed on binding the resource and indicates whether the wl_output
supports DPMS. There are operation modes of a Wayland server where DPMS might not
make sense (e.g. nested compositors).
</description>
<arg name="supported" type="uint" summary="Boolean value whether DPMS is supported (1) for the wl_output or not (0)"/>
</event>
<enum name="mode">
<entry name="On" value="0"/>
<entry name="Standby" value="1"/>
<entry name="Suspend" value="2"/>
<entry name="Off" value="3"/>
</enum>
<event name="mode">
<description summary="Event indicating used DPMS mode">
This mode gets pushed on binding the resource and provides the currently used
DPMS mode. It also gets pushed if DPMS is not supported for the wl_output, in that
case the value will be On.
The event is also pushed whenever the state changes.
</description>
<arg name="mode" type="uint" summary="The new currently used mode"/>
</event>
<event name="done">
<description summary="All changes are pushed">
This event gets pushed on binding the resource once all other states are pushed.
In addition it gets pushed whenever a state changes to tell the client that all
state changes have been pushed.
</description>
</event>
<request name="set">
<description summary="Request DPMS state change for the wl_output">
Requests that the compositor puts the wl_output into the passed mode. The compositor
is not obliged to change the state. In addition the compositor might leave the mode
whenever it seems suitable. E.g. the compositor might return to On state on user input.
The client should not assume that the mode changed after requesting a new mode.
Instead the client should listen for the mode event.
</description>
<arg name="mode" type="uint" summary="Requested mode"/>
</request>
<request name="release" type="destructor">
<description summary="release the dpms object"/>
</request>
</interface>
</protocol>
+18
View File
@@ -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;
@@ -839,6 +848,15 @@ mod kwin;
#[path = "vdisplay/linux/kwin_output_mgmt.rs"]
mod kwin_output_mgmt;
// DPMS control of the box's live KDE desktop (org_kde_kwin_dpms) — how a bare-spawn gamescope
// session honors `Topology::Exclusive`: the spawn is its own headless compositor, so the desktop's
// physical outputs can't be *disabled* (KWin refuses zero enabled outputs and no output there is
// ours) — they are put to DPMS-off for the stream instead, refcounted across concurrent spawns.
// Consumed by `gamescope` (best-effort, with kscreen fallback).
#[cfg(target_os = "linux")]
#[path = "vdisplay/linux/kwin_dpms.rs"]
mod kwin_dpms;
#[cfg(target_os = "windows")]
#[path = "vdisplay/windows/manager.rs"]
pub mod manager;
@@ -69,6 +69,11 @@ pub struct GamescopeDisplay {
/// the decision and this session's `create`. `None` = nothing resolved it (a caller that never
/// ran `apply_input_env`); `create` then falls through to the bare spawn, the safe default.
route: Option<crate::GamescopeRoute>,
/// The topology-restore action the bare-spawn `create` prepared under `Topology::Exclusive` —
/// the release of this display's [`crate::kwin_dpms`] darken hold — pending pickup by the
/// registry via [`VirtualDisplay::take_topology_restore`], so it runs at the display's
/// teardown (§6.1) and never before.
pending_restore: Option<Box<dyn FnOnce() + Send>>,
}
/// A running host-managed session (its transient systemd --user unit) + the mode it was launched at.
@@ -441,6 +446,14 @@ impl VirtualDisplay for GamescopeDisplay {
self.route = route;
}
fn take_topology_restore(&mut self) -> Option<Box<dyn FnOnce() + Send>> {
// The DPMS darken-hold release the bare-spawn `create` registered (Exclusive topology
// only). The registry stores it on this display's entry and runs it at teardown — which,
// for gamescope, is the display's OWN teardown: every spawn is its own group, and the
// cross-session ordering lives in `kwin_dpms`'s refcount, not in the group float.
self.pending_restore.take()
}
fn poolable_now(&self) -> bool {
// Only a bare SPAWN is registry-poolable (its `create` reports `Owned`); Managed and
// Attach report `SessionManaged`/`External`, so the registry must not reuse a kept spawn
@@ -576,6 +589,23 @@ impl VirtualDisplay for GamescopeDisplay {
hz = mode.refresh_hz,
"gamescope virtual output ready"
);
// `Topology::Exclusive`, bare-spawn edition: this spawn is its OWN headless compositor —
// nothing above touched the box's live desktop (KWin), which would otherwise keep driving
// the physical panel with the idle desktop for the whole stream. The KWin route disables
// the physicals outright, but that door is closed here (KWin refuses zero enabled outputs,
// and no output on that desktop is ours to leave enabled) — so the desktop's panels go to
// DPMS-off instead, best-effort and self-gating (a box with no KDE desktop declines
// quietly inside `kwin_dpms`). Placed AFTER the spawn succeeded, so a failed create never
// blanks the user's screen. The hold is refcounted in `kwin_dpms` rather than floated
// through the registry's group restore, because every gamescope spawn is its own group
// (`registry::group_key`) — the float alone would re-light the panel when the FIRST of two
// concurrent spawns ends, under the second's still-live stream. Skipped for Managed (its
// takeover already stopped the desktop) and Attach (it mirrors a gamescope that may itself
// be driving the physical panel) — both returned earlier in this function.
if crate::effective_topology() == crate::policy::Topology::Exclusive {
crate::kwin_dpms::acquire_stream_darken();
self.pending_restore = Some(Box::new(crate::kwin_dpms::release_stream_darken));
}
// Bare SPAWN: we own the nested gamescope process → registry-poolable (keep-alive-able).
Ok(VirtualOutput::owned(
node_id,
@@ -1237,7 +1267,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 +1290,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 +1605,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 +4241,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 +4348,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 +4413,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 +4444,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 +4680,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 +4914,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 +5747,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 +5761,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
@@ -704,7 +704,7 @@ fn kscreen_ok(args: &[String]) -> bool {
/// before exiting, so a slow-but-working KWin gives us a kill on a request that already landed;
/// any caller that treats `None` as "it failed" is asserting something it does not know, and for
/// the restore path that assertion costs a monitor its refresh rate.
fn kscreen_verdict(args: &[String]) -> Option<bool> {
pub(crate) fn kscreen_verdict(args: &[String]) -> Option<bool> {
match crate::proc::status_within(
std::process::Command::new("kscreen-doctor").args(args),
KSCREEN_BUDGET,
@@ -0,0 +1,675 @@
//! DPMS control of the box's live KDE desktop (`org_kde_kwin_dpms`) — how a bare-spawn gamescope
//! session honors [`Topology::Exclusive`](crate::policy::Topology::Exclusive).
//!
//! A bare spawn is its OWN headless compositor: nothing on that route touches the desktop the box
//! is showing, so on a KDE machine the physical panel keeps displaying the (idle) desktop for the
//! whole stream — while the same `exclusive` policy on the KWin route turns the physicals off
//! outright. The KWin route's mechanism is closed to us here: KWin refuses an output configuration
//! with ZERO enabled outputs, and a gamescope session has no KWin output of its own to leave
//! enabled. DPMS is the honest translation of `exclusive` for this route — the desktop stays
//! exactly where it is (no topology churn, no window re-homing), the panels go dark, and any
//! LOCAL input wakes them, which is the right answer for a desktop someone can walk up to.
//! Stream input never wakes them: it is injected into the nested gamescope's own EIS socket and
//! does not pass through KWin.
//!
//! Driven in-process over the compositor's own Wayland (`Connection::connect_to_env`, the same
//! stack as [`crate::kwin_output_mgmt`] and for the same reason: `kscreen-doctor` rides a separate
//! libkscreen/KDED layer that can be wedged while KWin itself answers fine), with a
//! `kscreen-doctor --dpms` shell-out fallback. Best-effort everywhere — a box with no Wayland
//! session, or a non-KDE desktop, declines quietly and the stream proceeds with the panel lit,
//! exactly as before this module existed.
//!
//! **The hold is refcounted here, NOT floated through the registry's per-group restore.** Every
//! gamescope spawn is its own display group (`registry::group_key` — deliberately, they are
//! independent nested sessions), so the §6.1 group machinery alone would run the FIRST session's
//! restore at that session's teardown and re-light the panel under a second, still-streaming
//! session. Instead each exclusive spawn takes one [`acquire_stream_darken`] hold (the 0→1 edge
//! darkens) and registers [`release_stream_darken`] as its per-display topology restore (the 1→0
//! edge re-lights) — the same shape as `sleep_inhibit`'s refcount, riding the registry only for
//! the *timing* of each release.
//!
//! Crash safety comes free: DPMS is non-persistent, so a host that dies holding the panel dark
//! leaves nothing to journal — the screen re-lights on the next local input or compositor
//! restart. (Contrast the Windows `pnp_disable_monitors` path, which needs a recovery journal
//! precisely because its disable survives everything.)
use std::collections::HashMap;
use std::os::fd::{AsFd, AsRawFd};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use wayland_client::protocol::wl_callback::{self, WlCallback};
use wayland_client::protocol::wl_output::{self, WlOutput};
use wayland_client::protocol::wl_registry::{self, WlRegistry};
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle};
// Client bindings for the vendored KDE dpms protocol (`protocols/dpms.xml`), generated inline like
// the two in `kwin_output_mgmt`. Self-contained: its only foreign object type is the core
// `wl_output`, which `wayland_client::protocol` already provides.
#[allow(clippy::all, dead_code, non_camel_case_types, non_snake_case, unused)]
pub mod protocol {
use wayland_client;
use wayland_client::protocol::*;
pub mod __interfaces {
use wayland_client::protocol::__interfaces::*;
wayland_scanner::generate_interfaces!("protocols/dpms.xml");
}
use self::__interfaces::*;
wayland_scanner::generate_client_code!("protocols/dpms.xml");
}
use protocol::org_kde_kwin_dpms::{Event as DpmsEvent, OrgKdeKwinDpms as Dpms};
use protocol::org_kde_kwin_dpms_manager::OrgKdeKwinDpmsManager as DpmsManager;
// The wire enum `org_kde_kwin_dpms.mode`. The XML types the `mode` request/event args as plain
// `uint` (no `enum=` attribute), so the generated signatures take/deliver `u32` — these constants
// are the protocol's values, kept in sync with the vendored `dpms.xml`.
const DPMS_MODE_ON: u32 = 0;
const DPMS_MODE_OFF: u32 = 3;
/// `org_kde_kwin_dpms_manager` is a frozen v1 protocol (its own header warns it may change
/// without a version bump, but no v2 has appeared since 2015); bind `min(advertised, 1)`.
const MANAGER_MAX: u32 = 1;
/// `wl_output.name` — the connector name used for logging — arrived in v4. Everything else we do
/// works at v1, so a lower advert just costs the log its names.
const WL_OUTPUT_MAX: u32 = 4;
/// Overall budget for one darken/re-light operation (mirrors `kwin_output_mgmt::OP_BUDGET`):
/// generous next to a healthy roundtrip, and only there so a wedged compositor can't pin the
/// session-create (or group-teardown) thread.
const OP_BUDGET: Duration = Duration::from_secs(3);
/// Poll slice while waiting on the Wayland fd (matches `kwin_output_mgmt`).
const POLL_MS: i32 = 100;
/// One output's accumulated state on this connection, keyed by its `wl_output` global name.
#[derive(Default)]
struct OutputState {
proxy: Option<WlOutput>,
/// Connector name (`DP-1`) from `wl_output.name` (v4) — logging only; the global number is
/// the address everything operates on.
connector: Option<String>,
dpms: Option<Dpms>,
/// `org_kde_kwin_dpms.supported` — `None` until the bind burst arrives.
supported: Option<bool>,
/// The last `org_kde_kwin_dpms.mode` seen — kept current, so the post-`set` wait can watch it
/// flip.
mode: Option<u32>,
}
/// Everything one connection's queue accumulates.
#[derive(Default)]
struct State {
manager: Option<DpmsManager>,
/// Keyed by the `wl_output` GLOBAL NAME — a stable address for the compositor's lifetime, and
/// the identity the darken records so the re-light (a separate, later connection) can find the
/// same outputs again.
outputs: HashMap<u32, OutputState>,
/// Highest `wl_callback` serial whose `done` has arrived — the barrier the pump waits on.
sync_done: u32,
}
impl Dispatch<WlRegistry, ()> for State {
fn event(
state: &mut Self,
registry: &WlRegistry,
event: wl_registry::Event,
_: &(),
_: &Connection,
qh: &QueueHandle<Self>,
) {
match event {
wl_registry::Event::Global {
name,
interface,
version,
} => {
if interface == DpmsManager::interface().name {
let v = version.min(MANAGER_MAX);
state.manager = Some(registry.bind::<DpmsManager, _, _>(name, v, qh, ()));
} else if interface == WlOutput::interface().name {
let v = version.min(WL_OUTPUT_MAX);
// The global name rides in the UserData so the output's own events (and the
// dpms object's, which gets the same stamp) can find this entry.
let out = registry.bind::<WlOutput, _, _>(name, v, qh, name);
state.outputs.entry(name).or_default().proxy = Some(out);
}
}
// An output unplugged mid-operation: drop the entry so we never `set` on its corpse.
wl_registry::Event::GlobalRemove { name } => {
state.outputs.remove(&name);
}
_ => {}
}
}
}
impl Dispatch<WlOutput, u32> for State {
fn event(
state: &mut Self,
_: &WlOutput,
event: wl_output::Event,
global: &u32,
_: &Connection,
_: &QueueHandle<Self>,
) {
if let wl_output::Event::Name { name } = event {
if let Some(o) = state.outputs.get_mut(global) {
o.connector = Some(name);
}
}
}
}
impl Dispatch<Dpms, u32> for State {
fn event(
state: &mut Self,
_: &Dpms,
event: DpmsEvent,
global: &u32,
_: &Connection,
_: &QueueHandle<Self>,
) {
let Some(o) = state.outputs.get_mut(global) else {
return;
};
match event {
DpmsEvent::Supported { supported } => o.supported = Some(supported != 0),
DpmsEvent::Mode { mode } => o.mode = Some(mode),
DpmsEvent::Done => {}
}
}
}
// The manager has no events; the impl exists because `WlRegistry::bind` demands one.
impl Dispatch<DpmsManager, ()> for State {
fn event(
_: &mut Self,
_: &DpmsManager,
_: protocol::org_kde_kwin_dpms_manager::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
}
}
impl Dispatch<WlCallback, u32> for State {
fn event(
state: &mut Self,
_: &WlCallback,
event: wl_callback::Event,
serial: &u32,
_: &Connection,
_: &QueueHandle<Self>,
) {
if let wl_callback::Event::Done { .. } = event {
state.sync_done = state.sync_done.max(*serial);
}
}
}
/// Why [`Session::open`] declined — the same honest-decline discipline as
/// `kwin_output_mgmt::OpenFailure`: which rung said no decides both the log level and whether the
/// `kscreen-doctor` fallback is worth attempting.
enum OpenFailure {
/// No Wayland connection at all (`WAYLAND_DISPLAY` unset/stale). The common case for the bare
/// spawn's natural habitat — a headless plain-distro box with no desktop to darken.
Connect(String),
/// The compositor accepted the connection but did not answer the registry barrier in budget:
/// a live but wedged session — the case the shell-out fallback exists for.
RegistryBarrier,
/// Connected and answering, but `org_kde_kwin_dpms_manager` is not advertised — not KWin. A
/// definitive answer: no fallback can succeed here either (`kscreen-doctor` drives the same
/// KDE-only machinery), so this rung declines without one.
NoDpmsGlobal,
/// The manager is there but the per-output DPMS state bursts never completed in budget.
StateBarrier,
}
impl std::fmt::Display for OpenFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
OpenFailure::Connect(e) => write!(f, "no Wayland connection ({e})"),
OpenFailure::RegistryBarrier => {
write!(
f,
"the compositor did not answer the registry roundtrip in budget"
)
}
OpenFailure::NoDpmsGlobal => {
write!(f, "org_kde_kwin_dpms_manager is not advertised (not KWin)")
}
OpenFailure::StateBarrier => {
write!(
f,
"the outputs' DPMS state never finished announcing in budget"
)
}
}
}
}
/// A connected session with the manager bound and every output's DPMS state read.
struct Session {
conn: Connection,
queue: wayland_client::EventQueue<State>,
state: State,
next_sync: u32,
}
impl Session {
/// [`Session::connect`] for the operation named by `op`, logging the decline at a level that
/// matches what it means: `Connect`/`NoDpmsGlobal` are the everyday non-KDE answers (most
/// bare-spawn boxes have no desktop at all) and log at debug; the two barrier failures mean a
/// LIVE session stopped answering — on a KDE box that is a panel left lit, so they warn.
fn open(op: &'static str) -> Result<Session, OpenFailure> {
let opened = Session::connect();
if let Err(reason) = &opened {
match reason {
OpenFailure::Connect(_) | OpenFailure::NoDpmsGlobal => {
tracing::debug!(op, %reason, "KWin DPMS unavailable");
}
OpenFailure::RegistryBarrier | OpenFailure::StateBarrier => {
tracing::warn!(
op,
%reason,
"KWin DPMS: in-process path unavailable — falling back to kscreen-doctor"
);
}
}
}
opened
}
/// Connect to the desktop's Wayland socket, bind the dpms manager + every `wl_output`, create
/// a dpms status object per output and drain their state bursts — all bounded by [`OP_BUDGET`].
fn connect() -> Result<Session, OpenFailure> {
let conn = Connection::connect_to_env().map_err(|e| OpenFailure::Connect(e.to_string()))?;
let queue = conn.new_event_queue();
let qh = queue.handle();
let _registry = conn.display().get_registry(&qh, ());
let mut s = Session {
conn,
queue,
state: State::default(),
next_sync: 0,
};
let deadline = Instant::now() + OP_BUDGET;
// Phase 1: process the registry globals (binds the manager + every wl_output).
if !s.sync_barrier(deadline) {
return Err(OpenFailure::RegistryBarrier);
}
let Some(mgr) = s.state.manager.clone() else {
return Err(OpenFailure::NoDpmsGlobal);
};
// Phase 2: one dpms status object per output (stamped with the output's global name so its
// events land on the right entry), then a barrier that drains both the outputs' `name`
// events and the dpms objects' supported/mode/done bursts.
let qh = s.queue.handle();
let bound: Vec<(u32, WlOutput)> = s
.state
.outputs
.iter()
.filter_map(|(g, o)| o.proxy.clone().map(|p| (*g, p)))
.collect();
for (global, out) in bound {
let d = mgr.get(&out, &qh, global);
if let Some(o) = s.state.outputs.get_mut(&global) {
o.dpms = Some(d);
}
}
if !s.sync_barrier(deadline) {
return Err(OpenFailure::StateBarrier);
}
Ok(s)
}
/// Send a `wl_display.sync` and pump the queue until its `done` arrives or `deadline` passes.
fn sync_barrier(&mut self, deadline: Instant) -> bool {
self.next_sync += 1;
let serial = self.next_sync;
let qh = self.queue.handle();
let _cb = self.conn.display().sync(&qh, serial);
self.pump_until(deadline, |st| st.sync_done >= serial)
}
/// Bounded manual event loop — flush, dispatch, poll the fd. Mirrors
/// `kwin_output_mgmt::Session::pump_until` (same rationale: `blocking_dispatch` can't be
/// interrupted, so the fd is polled in [`POLL_MS`] slices against `deadline`).
fn pump_until(&mut self, deadline: Instant, done: impl Fn(&State) -> bool) -> bool {
loop {
if done(&self.state) {
return true;
}
if self.queue.dispatch_pending(&mut self.state).is_err() {
return false;
}
if done(&self.state) {
return true;
}
if Instant::now() >= deadline {
return false;
}
if self.conn.flush().is_err() {
return false;
}
let Some(guard) = self.conn.prepare_read() else {
continue; // events already queued — loop dispatches them
};
let mut pfd = libc::pollfd {
fd: self.conn.as_fd().as_raw_fd(),
events: libc::POLLIN,
revents: 0,
};
let remaining = deadline.saturating_duration_since(Instant::now());
let timeout = (remaining.as_millis() as i32).clamp(0, POLL_MS);
// SAFETY: `&mut pfd` points at one live, fully-initialized `libc::pollfd` on the stack
// and the count `1` matches that single element, so `poll` reads `fd`/`events` and
// writes `revents` strictly within `pfd`. `pfd.fd` is the Wayland connection's fd,
// valid because `self.conn` (and the `prepare_read` guard) outlive the call. `poll`
// blocks up to `timeout` ms and writes only `revents`; `pfd` is a fresh local that
// aliases nothing.
let r = unsafe { libc::poll(&mut pfd, 1, timeout) };
if r > 0 && (pfd.revents & libc::POLLIN) != 0 {
let _ = guard.read();
} // else: timeout/signal — drop the guard, re-check the deadline
}
}
/// Request `target` on every DPMS-supporting output not already there — restricted to the
/// globals in `only` when given (the re-light path, which must touch ONLY what the darken
/// touched: a panel the USER had put to sleep before the stream is theirs to keep dark).
/// Returns the outputs actually asked to change, `(global, connector)`, then waits (within
/// budget) for each one's `mode` event to confirm — the protocol is explicit that `set` is a
/// request the compositor may decline, so the confirmation is watched and its absence logged
/// rather than assumed.
fn set_mode(&mut self, target: u32, only: Option<&[u32]>) -> Vec<(u32, Option<String>)> {
let deadline = Instant::now() + OP_BUDGET;
let mut touched: Vec<(u32, Option<String>)> = Vec::new();
for (global, o) in &self.state.outputs {
if only.is_some_and(|list| !list.contains(global)) {
continue;
}
if o.supported != Some(true) || o.mode == Some(target) {
continue;
}
if let Some(dpms) = &o.dpms {
dpms.set(target);
touched.push((*global, o.connector.clone()));
}
}
if touched.is_empty() {
return touched;
}
let want: Vec<u32> = touched.iter().map(|(g, _)| *g).collect();
// An output that vanished mid-wait (GlobalRemove pruned it) counts as settled — there is
// nothing left to flip.
let confirmed = self.pump_until(deadline, |st| {
want.iter()
.all(|g| st.outputs.get(g).is_none_or(|o| o.mode == Some(target)))
});
if !confirmed {
tracing::warn!(
outputs = ?touched,
target,
"KWin DPMS: the compositor did not confirm the mode change in budget (the \
requests are flushed; it may still land, or KWin may have declined)"
);
}
touched
}
}
/// What the 0→1 darken actually achieved — the record the 1→0 re-light undoes. Which arm did the
/// work matters: the two are undone through different doors.
enum Darkened {
/// The in-process path turned these outputs off — `(wl_output global, connector)`. Global
/// names are stable for the compositor's lifetime, so a later connection re-lights exactly
/// these. If KWin restarted in between the names match nothing — and that is the CORRECT
/// no-op, because a fresh KWin brings its outputs up lit anyway.
Wayland(Vec<(u32, Option<String>)>),
/// The `kscreen-doctor --dpms off` fallback ran (it takes no per-output address, so the
/// re-light is the symmetric `--dpms on`).
Kscreen,
}
/// The host-wide darken hold — refcounted like `sleep_inhibit`: the 0→1 edge darkens, the 1→0
/// edge re-lights, and everything between is bookkeeping. See the module docs for why the
/// registry's per-group restore float can't provide this (every gamescope spawn is its own group).
struct Holds {
count: u32,
/// What the 0→1 darken achieved, held until the 1→0 release undoes it. `None` while count > 0
/// means the darken found nothing to do (no KDE, panels already dark) — the release then has
/// nothing to undo, which is exactly right.
darkened: Option<Darkened>,
}
impl Holds {
/// Take a hold; `true` on the 0→1 edge — the caller darkens and [`record`](Self::record)s.
fn acquire_edge(&mut self) -> bool {
self.count += 1;
self.count == 1
}
/// Store the 0→1 darken's outcome.
fn record(&mut self, d: Option<Darkened>) {
self.darkened = d;
}
/// Drop a hold; `Some` on the 1→0 edge hands the caller the record to undo. A release with no
/// hold outstanding is a caller bug (an unbalanced restore) — logged, never underflowed.
fn release_edge(&mut self) -> Option<Darkened> {
if self.count == 0 {
tracing::warn!("KWin DPMS: release without a matching acquire (unbalanced restore)");
return None;
}
self.count -= 1;
if self.count == 0 {
self.darkened.take()
} else {
None
}
}
}
static HOLDS: Mutex<Holds> = Mutex::new(Holds {
count: 0,
darkened: None,
});
/// Take one darken hold for an exclusive-topology stream. The first hold turns the live KDE
/// desktop's panels off (best-effort, bounded); later holds just count. Callers MUST balance each
/// call with [`release_stream_darken`] — the gamescope backend does it by registering the release
/// as the display's topology restore, so the registry runs it exactly once per display at
/// teardown (§6.1).
///
/// The lock is deliberately held across the darken itself: a racing second acquire must queue
/// behind it (and then see the recorded outcome), not observe a count of 2 with nothing darkened.
/// Same discipline on the release side, which keeps a teardown-overlapping-connect sequence
/// strictly ordered: re-light completes, then the new stream's darken runs.
pub fn acquire_stream_darken() {
let mut h = HOLDS.lock().unwrap_or_else(|e| e.into_inner());
if h.acquire_edge() {
let d = darken();
h.record(d);
}
}
/// Drop one darken hold; the last one out re-lights whatever the first hold's darken achieved.
pub fn release_stream_darken() {
let mut h = HOLDS.lock().unwrap_or_else(|e| e.into_inner());
if let Some(d) = h.release_edge() {
relight(d);
}
}
/// The 0→1 darken: in-process over `org_kde_kwin_dpms` first, `kscreen-doctor --dpms off` as the
/// wedged-compositor fallback. `None` = nothing was darkened (no desktop, not KDE, panels already
/// off, or every arm declined) — and therefore nothing to restore.
fn darken() -> Option<Darkened> {
match Session::open("darken") {
Ok(mut s) => {
let touched = s.set_mode(DPMS_MODE_OFF, None);
if touched.is_empty() {
tracing::debug!(
"KWin DPMS: no output to darken (none supported, or all already off)"
);
None
} else {
tracing::info!(
outputs = ?touched,
"KWin DPMS: desktop outputs off for the exclusive gamescope stream"
);
Some(Darkened::Wayland(touched))
}
}
// Definitive "not KDE" / "no desktop": no fallback can do better (kscreen-doctor drives
// the same KDE-only machinery), so decline quietly — already logged by `open`.
Err(OpenFailure::NoDpmsGlobal) | Err(OpenFailure::Connect(_)) => None,
// A live session that stopped answering: the standalone tool rides a different stack
// (libkscreen/KDED) and may still get through — the same rationale as `kwin.rs`'s
// kscreen fallbacks, honest-verdict discipline included.
Err(_) => match kscreen_dpms("off") {
Some(true) => {
tracing::info!(
"KWin DPMS: desktop outputs off for the exclusive gamescope stream \
(kscreen-doctor fallback)"
);
Some(Darkened::Kscreen)
}
// Killed at its budget — NOT a refusal: kscreen-doctor applies first and then waits
// on the compositor, so a loaded KWin routinely lands the change and still gets
// killed. Record the darken so the teardown re-light runs either way; a `--dpms on`
// against a lit panel is a no-op.
None => Some(Darkened::Kscreen),
Some(false) => {
tracing::warn!(
"KWin DPMS: could not darken the desktop outputs for the exclusive topology \
(in-process path and kscreen-doctor both declined) the panel stays lit"
);
None
}
},
}
}
/// The 1→0 re-light. **This is the last line of defence for a dark monitor**, so every arm that
/// gives up says so loudly (the same discipline as `kwin.rs::reenable_outputs_kscreen`) — a dark
/// panel with no line in the log is the failure mode this chain exists to prevent. The worst case
/// stays self-healing regardless: DPMS is non-persistent, and any local input wakes the panel.
fn relight(d: Darkened) {
match d {
Darkened::Wayland(outputs) => {
let globals: Vec<u32> = outputs.iter().map(|(g, _)| *g).collect();
match Session::open("re-light") {
Ok(mut s) => {
s.set_mode(DPMS_MODE_ON, Some(&globals));
tracing::info!(outputs = ?outputs, "KWin DPMS: desktop outputs back on");
}
Err(_) => match kscreen_dpms("on") {
Some(true) | None => {
tracing::info!(
"KWin DPMS: desktop outputs back on (kscreen-doctor fallback)"
);
}
Some(false) => {
tracing::error!(
outputs = ?outputs,
"KWin DPMS: could NOT re-light the desktop outputs (in-process \
restore and kscreen-doctor both declined) the panel stays dark \
until local input wakes it"
);
}
},
}
}
Darkened::Kscreen => {
if kscreen_dpms("on") == Some(false) {
tracing::error!(
"KWin DPMS: could NOT re-light the desktop outputs (kscreen-doctor refused \
the --dpms on it earlier accepted the off for) the panel stays dark until \
local input wakes it"
);
}
}
}
}
/// `kscreen-doctor --dpms <on|off>` for its verdict, on `kwin.rs`'s shared budget and three-state
/// convention (`Some(true)` ran and succeeded, `Some(false)` refused or unrunnable, `None` killed
/// at the budget — which, for a tool that applies first and waits after, usually means it landed).
fn kscreen_dpms(mode: &'static str) -> Option<bool> {
crate::kwin::kscreen_verdict(&["--dpms".to_string(), mode.to_string()])
}
#[cfg(test)]
mod tests {
use super::{Darkened, Holds};
fn fresh() -> Holds {
Holds {
count: 0,
darkened: None,
}
}
#[test]
fn first_acquire_darkens_later_ones_count() {
let mut h = fresh();
assert!(h.acquire_edge(), "0→1 must darken");
h.record(Some(Darkened::Kscreen));
assert!(
!h.acquire_edge(),
"a second concurrent stream must not re-darken"
);
assert!(!h.acquire_edge());
}
#[test]
fn only_the_last_release_relights() {
let mut h = fresh();
assert!(h.acquire_edge());
h.record(Some(Darkened::Wayland(vec![(7, Some("DP-1".into()))])));
assert!(!h.acquire_edge());
// First release: a sibling still streams — the panel must stay dark.
assert!(h.release_edge().is_none());
// Last release hands back the record to undo.
let d = h.release_edge();
assert!(matches!(d, Some(Darkened::Wayland(v)) if v == vec![(7, Some("DP-1".into()))]));
}
#[test]
fn a_darken_that_did_nothing_restores_nothing() {
let mut h = fresh();
assert!(h.acquire_edge());
h.record(None); // no KDE / already dark: nothing was changed
assert!(h.release_edge().is_none(), "nothing to undo");
assert_eq!(h.count, 0);
}
#[test]
fn unbalanced_release_never_underflows() {
let mut h = fresh();
assert!(h.release_edge().is_none());
assert_eq!(h.count, 0, "count must not wrap");
// And the state machine still works afterwards.
assert!(h.acquire_edge());
h.record(Some(Darkened::Kscreen));
assert!(matches!(h.release_edge(), Some(Darkened::Kscreen)));
}
#[test]
fn a_full_cycle_rearms_the_darken() {
let mut h = fresh();
assert!(h.acquire_edge());
h.record(Some(Darkened::Kscreen));
assert!(h.release_edge().is_some());
// A later stream on the same host lifetime darkens again.
assert!(
h.acquire_edge(),
"the 0→1 edge must re-arm after a full cycle"
);
}
}
@@ -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
+13 -1
View File
@@ -17,7 +17,19 @@ parse_deps = false
# imports and their #[repr(C)] structs into the header, where socklen_t/ssize_t/iovec/msghdr are
# undefined and the C harness fails to compile: the Apple batched recv (transport/udp.rs
# `recvmsg_x` + `MsghdrX`) and the Android bionic mmsg bindings (`android_mmsg` module).
exclude = ["MsghdrX", "recvmsg_x", "mmsghdr", "sendmmsg", "recvmmsg"]
#
# `SOFT_LIMIT_KNEE` is host-side CAPTURE processing (the operator gain's soft knee, applied before
# the encoder). No C embedder can act on it — they receive already-gained audio — so exporting it
# would add a bare `#define` to the ABI surface, against R21 below, for a constant with no meaning
# on that side of the boundary. Excluded rather than renamed: the header stays byte-identical.
exclude = [
"MsghdrX",
"recvmsg_x",
"mmsghdr",
"sendmmsg",
"recvmmsg",
"SOFT_LIMIT_KNEE",
]
# Reached by no exported SIGNATURE, so cbindgen's sweep misses it — but a C embedder needs the
# vocabulary: `punktfunk_connection_end_reason` writes one of these as a bare byte (deliberately,
# so the JNI/Swift sides can marshal a `u8` rather than an enum), which without this would leave
+135
View File
@@ -955,6 +955,68 @@ pub fn crossfade_drop(ring: &mut std::collections::VecDeque<f32>, drop: usize, f
ring.drain(..drop);
}
/// Where [`apply_gain`]'s soft knee begins, in linear amplitude (≈ 3.1 dBFS). Below this the
/// gained signal is passed through EXACTLY — a boost whose peaks never reach the knee is plain
/// multiplication, sample for sample, so the limiter costs nothing on material that does not need
/// it.
pub const SOFT_LIMIT_KNEE: f32 = 0.7;
/// Multiply `samples` by `gain`, bending anything that would overshoot full scale into a soft knee
/// instead of slicing it flat.
///
/// **Why this is not a `clamp`.** The GameStream plane's gain was `(s * gain).clamp(-1.0, 1.0)`,
/// which is a hard clip: the waveform's peaks are replaced by literal flat tops, and a flat top is
/// a discontinuity in the first derivative. That radiates high-order harmonics — the harsher and
/// more aliasing-prone the higher they go — which is why a field report of "+18 dB and everything
/// warbles" is the expected outcome of that code and not a bug in anything downstream. Any operator
/// who set `PUNKTFUNK_AUDIO_GAIN` much above ~1.5 was hearing this.
///
/// The curve here is `tanh`-based and chosen for three properties, in this order:
///
/// 1. **C¹-continuous at the knee.** The shaped branch's slope at `m == KNEE` is
/// `(1-K) · sech²(0) · 1/(1-K) == 1`, exactly the slope of the linear branch it meets. There is
/// no corner in the transfer curve, so the onset of limiting is not itself an audible event —
/// the failure mode of a naïve piecewise limiter, which trades one discontinuity for another.
/// 2. **Bounded by construction.** `tanh` is asymptotic to 1, so the output approaches but never
/// exceeds full scale for any finite input, and `±inf` maps to `±1.0`. No sample can leave here
/// out of range, which is what the encoder downstream assumes.
/// 3. **Odd-symmetric.** `f(-x) == -f(x)`, so the distortion it does introduce is odd-harmonic and
/// adds no DC offset — the benign, "saturating" flavour rather than the rectifying one.
///
/// Callers gate on `gain != 1.0`, so the default path is untouched and the wire stays byte-for-byte
/// identical to a build without this. Note this is a WAVESHAPER, not a lookahead limiter: it is
/// memoryless and therefore costs zero latency, which is the trade that makes it acceptable in the
/// realtime encode path. It raises headroom; it does not raise *loudness* the way a compressor
/// with a real time constant would, and it should not be sold as one.
pub fn apply_gain(samples: &mut [f32], gain: f32) {
// Unity is a no-op, not "multiply by one and shape": the shaper is only correct to apply to a
// signal somebody asked to boost. Without this, calling at unity would bend every peak above
// the knee — a silent quality change for anyone who forgot to gate the call, and the reason
// the callers' `gain != 1.0` guards are a convenience rather than a load-bearing contract.
if gain == 1.0 {
return;
}
for s in samples {
*s = soft_limit(*s * gain);
}
}
/// The waveshaper behind [`apply_gain`]: identity below [`SOFT_LIMIT_KNEE`], asymptotic to ±1.0
/// above it. Exposed so the clients can mirror the curve if they ever grow a gain of their own.
pub fn soft_limit(x: f32) -> f32 {
let m = x.abs();
if m <= SOFT_LIMIT_KNEE {
return x;
}
let head = 1.0 - SOFT_LIMIT_KNEE;
let shaped = SOFT_LIMIT_KNEE + head * ((m - SOFT_LIMIT_KNEE) / head).tanh();
if x < 0.0 {
-shaped
} else {
shaped
}
}
// ---- per-platform channel-layout helpers (pure data; no platform deps) --------------------
/// Windows `WAVEFORMATEXTENSIBLE.dwChannelMask` for the wire layout.
@@ -2432,4 +2494,77 @@ mod tests {
assert!(s.audible_tail <= 4, "{s:?}");
assert!(s.audible <= 12, "{s:?}");
}
/// Unity must be bit-exact. The callers gate on `gain != 1.0` anyway, but if this ever stopped
/// holding, every default session's wire would shift and the "byte-for-byte identical" claim
/// the tier machinery rests on would quietly become false.
#[test]
fn unity_gain_is_bit_exact() {
let src: Vec<f32> = (0..512).map(|i| (i as f32 / 512.0) * 2.0 - 1.0).collect();
let mut got = src.clone();
apply_gain(&mut got, 1.0);
assert_eq!(got, src, "unity gain must not touch a single sample");
}
/// Below the knee the limiter is not in circuit at all: a boost whose peaks stay under
/// `SOFT_LIMIT_KNEE` must be plain multiplication, or quiet material pays for a limiter it
/// never needed.
#[test]
fn below_the_knee_is_plain_multiplication() {
let mut got = vec![0.0, 0.1, -0.2, 0.34, -0.05];
apply_gain(&mut got, 2.0);
for (i, (g, s)) in got.iter().zip([0.0f32, 0.1, -0.2, 0.34, -0.05]).enumerate() {
assert_eq!(*g, s * 2.0, "sample {i} must be untouched below the knee");
}
}
/// The property the hard `clamp` violated and this exists to restore: no input, however
/// absurdly gained, may leave the shaper out of range — and non-finite input must not escape
/// as something the encoder would choke on.
#[test]
fn nothing_escapes_full_scale() {
for gain in [1.5f32, 4.0, 8.0, 64.0, 1000.0] {
let mut got: Vec<f32> = (0..401).map(|i| (i as f32 - 200.0) / 200.0).collect();
apply_gain(&mut got, gain);
for s in &got {
assert!(s.abs() <= 1.0, "gain {gain} produced {s}");
}
}
assert_eq!(soft_limit(f32::INFINITY), 1.0);
assert_eq!(soft_limit(f32::NEG_INFINITY), -1.0);
}
/// Monotonic and odd-symmetric. Monotonicity is what keeps the shaper a limiter rather than a
/// fold-back distortion; odd symmetry is what keeps its harmonics benign and its DC at zero.
#[test]
fn the_curve_is_monotonic_and_odd() {
let mut prev = f32::NEG_INFINITY;
for i in 0..=4000 {
let x = (i as f32 - 2000.0) / 500.0; // -4.0 ..= 4.0
let y = soft_limit(x);
assert!(y >= prev, "not monotonic at {x}: {y} < {prev}");
prev = y;
assert!(
(soft_limit(-x) + y).abs() < 1e-6,
"not odd-symmetric at {x}"
);
}
}
/// The knee must not itself be an audible event. Both branches meet at the same value AND the
/// same slope, so the transfer curve has no corner — a piecewise limiter that gets this wrong
/// just swaps the clip's discontinuity for a softer one.
#[test]
fn the_knee_has_no_corner() {
let k = SOFT_LIMIT_KNEE;
assert!((soft_limit(k) - k).abs() < 1e-6, "value jumps at the knee");
let h = 1e-4;
let below = (soft_limit(k) - soft_limit(k - h)) / h;
let above = (soft_limit(k + h) - soft_limit(k)) / h;
assert!((below - 1.0).abs() < 1e-2, "linear side slope {below}");
assert!(
(above - below).abs() < 1e-2,
"slope jumps at the knee: {below} -> {above}"
);
}
}
+48
View File
@@ -13,6 +13,54 @@ pub const SAMPLE_RATE: u32 = 48_000;
/// Stereo channel count — the default and the punktfunk/1 audio plane's fixed layout.
pub const CHANNELS: usize = 2;
/// Highest boost `PUNKTFUNK_AUDIO_GAIN` will honour (+18 dB). Past this the soft knee is doing
/// essentially all the work and the result is a squashed signal, not a louder one — so a runaway
/// value (a stray `180` for `1.8`) is capped and said out loud rather than silently shipped.
const MAX_CAPTURE_GAIN: f32 = 8.0;
/// The operator's capture gain, shared by BOTH audio planes (`PUNKTFUNK_AUDIO_GAIN`, default
/// `1.0` = untouched).
///
/// **Why the host needs one at all.** WASAPI loopback is tapped UPSTREAM of the endpoint's master
/// volume, so turning the host's speaker slider up does nothing whatsoever to the level a client
/// receives. Before this, the native `punktfunk/1` plane had no gain of any kind, which left no
/// host-side way to raise a quiet desktop mix — the GameStream plane's knob was the only one, and
/// it applied to the wrong protocol.
///
/// Applied through [`punktfunk_core::audio::apply_gain`], whose soft knee replaces the hard
/// `clamp(-1.0, 1.0)` this used to be. That clamp is why boosting was a trap: it flat-tops peaks,
/// and flat tops are audible as harsh distortion long before the operator reaches the level they
/// were chasing.
///
/// ⚠ This is headroom, not loudness. It cannot close a peak-to-loudness gap against
/// already-limited broadcast content — that needs a real compressor with a time constant, which is
/// deliberately NOT what this is.
pub fn capture_gain() -> f32 {
let raw: f32 = std::env::var("PUNKTFUNK_AUDIO_GAIN")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(1.0);
// A negative or non-finite gain is a typo, never an intent: it would invert or poison every
// sample. Fall back to unity rather than shipping it.
if !raw.is_finite() || raw <= 0.0 {
if std::env::var("PUNKTFUNK_AUDIO_GAIN").is_ok() {
tracing::warn!(
"PUNKTFUNK_AUDIO_GAIN must be a positive number (1.0 = unchanged) — ignoring"
);
}
return 1.0;
}
if raw > MAX_CAPTURE_GAIN {
tracing::warn!(
requested = raw,
capped = MAX_CAPTURE_GAIN,
"PUNKTFUNK_AUDIO_GAIN is above the +18 dB ceiling — capping"
);
return MAX_CAPTURE_GAIN;
}
raw
}
/// Produces interleaved `f32` PCM at [`SAMPLE_RATE`] in the channel count it was opened
/// with. Lives on its own thread; never blocks the capture loop (drops if the consumer
/// falls behind).
@@ -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 25 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: 25 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 25 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 25 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};
@@ -290,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(())
}
@@ -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() {
+28 -3
View File
@@ -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 S1S3 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]"
),
}
}
@@ -397,11 +397,9 @@ fn audio_body(
// stays small.
let start = Instant::now();
let mut frame_no: u64 = 0;
// Optional linear gain for quiet capture sources (PUNKTFUNK_AUDIO_GAIN, default 1.0).
let gain: f32 = std::env::var("PUNKTFUNK_AUDIO_GAIN")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(1.0);
// Optional gain for quiet capture sources (PUNKTFUNK_AUDIO_GAIN, default 1.0). Soft-limited
// rather than clamped — see `crate::audio::capture_gain`.
let gain = crate::audio::capture_gain();
tracing::info!(
channels = layout.channels,
streams = layout.streams,
@@ -418,9 +416,7 @@ fn audio_body(
while acc.len() >= frame_len {
let mut frame: Vec<f32> = acc.drain(..frame_len).collect();
if gain != 1.0 {
for s in &mut frame {
*s = (*s * gain).clamp(-1.0, 1.0);
}
punktfunk_core::audio::apply_gain(&mut frame, gain);
}
let n = enc.encode_float(&frame, &mut out)?;
// AES-128-CBC the Opus payload (RTP header stays plaintext). Per-packet IV =
+291 -22
View File
@@ -150,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)
@@ -174,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
@@ -200,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
@@ -317,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
@@ -542,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
@@ -558,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");
@@ -642,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);
}
@@ -706,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();
@@ -765,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"));
+79 -5
View File
@@ -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
));
}
@@ -1065,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 {
@@ -1129,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);
}
}
+170 -42
View File
@@ -478,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)]
@@ -502,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
@@ -800,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
+11 -2
View File
@@ -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))
+56
View File
@@ -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.
+68 -7
View File
@@ -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)]
@@ -468,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);
@@ -484,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,
@@ -498,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!(
+46
View File
@@ -256,6 +256,52 @@ pub(crate) async fn unpair_native_client(
}
}
/// Unpair every native client
///
/// The collection form of [`unpair_native_client`]: empties the punktfunk/1 trust store in ONE
/// persisted write (not a loop of them — a failure partway would leave a half-emptied store), and
/// ends every live native session the removed clients own.
///
/// Idempotent, hence a 200 rather than the single unpair's 204/404: an already-empty store
/// satisfies the request, and the count still tells the operator what it meant.
#[utoipa::path(
delete,
path = "/native/clients",
tag = "native",
operation_id = "unpairAllNativeClients",
responses(
(status = OK, description = "Every native client unpaired (possibly none)", body = UnpairAllResult),
(status = SERVICE_UNAVAILABLE, description = "Native host not enabled", body = ApiError),
(status = UNAUTHORIZED, description = "Missing or invalid bearer token", body = ApiError),
(status = INTERNAL_SERVER_ERROR, description = "Could not persist the trust store", body = ApiError),
)
)]
pub(crate) async fn unpair_all_native_clients(State(st): State<Arc<MgmtState>>) -> Response {
let Some(np) = &st.native else {
return api_error(StatusCode::SERVICE_UNAVAILABLE, "native host not enabled");
};
match np.remove_all() {
Ok(removed) => {
// Revocation reaches LIVE sessions too — the same guarantee the single unpair gives,
// applied across the set.
let stopped: usize = removed
.iter()
.map(|fp| crate::session_status::stop_by_fingerprint(&fp.to_ascii_lowercase()))
.sum();
if stopped > 0 {
tracing::info!(stopped, "unpair-all: live native session(s) stopped");
}
let unpaired = removed.len() as u32;
tracing::info!(unpaired, "management API: all native clients unpaired");
Json(UnpairAllResult { unpaired }).into_response()
}
Err(e) => api_error(
StatusCode::INTERNAL_SERVER_ERROR,
&format!("could not persist trust store: {e}"),
),
}
}
/// List devices awaiting pairing approval
///
/// Unpaired devices that tried to connect while the host requires pairing. Approve one to pair
+12
View File
@@ -21,6 +21,18 @@ pub(crate) struct ApiError {
error: String,
}
/// What a bulk unpair removed. Shared by the two collection DELETEs (`/clients` and
/// `/native/clients`) so the console sees one schema across both pairing planes.
///
/// A count rather than 204: "unpair everything" is idempotent, so an empty store is a success, and
/// the operator still wants to be told whether that meant three devices or none.
#[derive(Serialize, ToSchema)]
pub(crate) struct UnpairAllResult {
/// Clients removed from the trust store — 0 when nothing was paired.
#[schema(example = 3)]
pub(crate) unpaired: u32,
}
pub(crate) fn api_error(status: StatusCode, message: &str) -> Response {
(
status,
+122 -1
View File
@@ -819,7 +819,8 @@ async fn paired_clients_list_and_unpair() {
{
let mut p = state.paired.lock().unwrap();
p.clear();
p.push(der);
// Cloned, not moved: the unpair-all section at the end of this test re-seeds it.
p.push(der.clone());
}
let (status, body) = send(&app, get_req("/api/v1/clients")).await;
@@ -888,6 +889,71 @@ async fn paired_clients_list_and_unpair() {
serde_json::from_slice::<Vec<Vec<u8>>>(&disk).unwrap(),
Vec::<Vec<u8>>::new()
);
// ---- the COLLECTION delete: unpair everything at once -----------------------------------
//
// Re-seed two clients (the store was just emptied) and clear the teardown flags, so what the
// bulk delete does to a live session is attributable to IT and not left over from above.
let second = crate::identity::ephemeral().unwrap();
let (_, second_pem) = x509_parser::pem::parse_x509_pem(second.cert_pem.as_bytes()).unwrap();
let second_der = second_pem.contents.clone();
let second_fp = hex::encode(Sha256::digest(&second_der));
{
use std::sync::atomic::Ordering;
let mut p = state.paired.lock().unwrap();
p.clear();
p.push(der.clone());
p.push(second_der);
state.quit.store(false, Ordering::SeqCst);
state.streaming.store(true, Ordering::SeqCst);
// A live session owned by the SECOND client — the bulk delete must end whichever of the
// removed certs owns it, not just the first one it happens to walk past.
let mut owner = [0u8; 32];
owner.copy_from_slice(&hex::decode(&second_fp).unwrap());
*state.launch.lock().unwrap() = Some(LaunchSession {
gcm_key: [0; 16],
rikeyid: 0,
width: 1920,
height: 1080,
fps: 60,
appid: 1,
peer_ip: None,
owner_fp: Some(owner),
});
}
let del_all = || {
axum::http::Request::delete("/api/v1/clients")
.body(Body::empty())
.unwrap()
};
let (status, body) = send(&app, del_all()).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body["unpaired"], 2, "both clients must be reported removed");
let (_, body) = send(&app, get_req("/api/v1/clients")).await;
assert_eq!(body, serde_json::json!([]));
{
use std::sync::atomic::Ordering;
assert!(
state.launch.lock().unwrap().is_none(),
"unpair-all must end the live session of any client it revokes"
);
assert!(state.quit.load(Ordering::SeqCst));
}
// Persisted, for the same reason the single unpair is: a resurrected pairing would re-open
// the control port on the next boot.
let disk = std::fs::read(tmp.path().join("paired.json")).unwrap();
assert_eq!(
serde_json::from_slice::<Vec<Vec<u8>>>(&disk).unwrap(),
Vec::<Vec<u8>>::new()
);
// Idempotent: emptying an empty store is a 200 with a zero count, NOT the single delete's 404.
// ("unpair everything" is already satisfied — there is no missing resource to report.)
let (status, body) = send(&app, del_all()).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body["unpaired"], 0);
}
#[cfg(feature = "gamestream")]
@@ -1248,8 +1314,13 @@ fn every_route_is_classified_for_the_plugin_and_cert_lanes() {
// ---- paired-device rosters: readable by a plugin, never by another paired client, and
// removal is pairing administration in both lanes.
("GET", "/api/v1/clients", true, false),
// The bulk form is the same authority as the single one — and, sharing its path with a
// plugin-readable GET, worth an explicit row: both gates match on (method, path), so the
// roster's read permission must never carry over to emptying it.
("DELETE", "/api/v1/clients", false, false),
("DELETE", "/api/v1/clients/{fingerprint}", false, false),
("GET", "/api/v1/native/clients", true, false),
("DELETE", "/api/v1/native/clients", false, false),
(
"DELETE",
"/api/v1/native/clients/{fingerprint}",
@@ -1667,6 +1738,56 @@ async fn native_pairing_arm_show_and_unpair() {
assert_eq!(b["armed"], false);
}
/// The collection delete on the native plane: one call empties the trust store, and repeating it
/// is a zero-count success rather than an error.
#[tokio::test]
async fn native_unpair_all_empties_the_trust_store() {
let np = Arc::new(
crate::native_pairing::NativePairing::load_with(
Some(std::env::temp_dir().join(format!("pf-mgmt-np-all-{}.json", std::process::id()))),
None,
false,
)
.unwrap(),
);
let app = test_app_native(test_state(), np.clone());
np.add("Living room TV", "aa11").unwrap();
np.add("Studio Deck", "bb22").unwrap();
assert_eq!(np.list().len(), 2);
let del_all = || {
axum::http::Request::delete("/api/v1/native/clients")
.body(Body::empty())
.unwrap()
};
let (status, body) = send(&app, del_all()).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body["unpaired"], 2);
// Gone from both the API and the store behind it (one persisted write, not two).
let (_, body) = send(&app, get_req("/api/v1/native/clients")).await;
assert_eq!(body, serde_json::json!([]));
assert!(np.list().is_empty());
assert!(!np.is_paired("aa11") && !np.is_paired("bb22"));
// Idempotent — unlike the single delete, which 404s on a fingerprint it cannot find.
let (status, body) = send(&app, del_all()).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body["unpaired"], 0);
}
/// Without a native plane there is no trust store to empty — 503, matching every other
/// `/native/*` route (and NOT a silent 200 that would tell the console it had unpaired something).
#[tokio::test]
async fn native_unpair_all_without_a_native_host_is_unavailable() {
let app = test_app(test_state(), None);
let req = axum::http::Request::delete("/api/v1/native/clients")
.body(Body::empty())
.unwrap();
assert_eq!(send(&app, req).await.0, StatusCode::SERVICE_UNAVAILABLE);
}
#[tokio::test]
async fn pending_devices_approve_and_deny() {
let np = Arc::new(
+18 -1
View File
@@ -142,6 +142,20 @@ pub(super) fn audio_thread(
};
let frame_len = SAMPLES_PER_FRAME * want as usize;
// Operator capture gain, soft-limited (`PUNKTFUNK_AUDIO_GAIN`, default 1.0 = untouched). This
// plane had NO gain at all until now, so `PUNKTFUNK_AUDIO_GAIN` silently did nothing on
// punktfunk/1 while working on GameStream — and since WASAPI loopback taps upstream of the
// endpoint's master volume, there was no other host-side way to lift a quiet desktop mix.
// Read once per session rather than per frame: this is an operator setting, not a live control.
let gain = crate::audio::capture_gain();
if gain != 1.0 {
tracing::info!(
gain,
"audio: applying operator capture gain (soft-limited above \
{}; headroom, not loudness)",
punktfunk_core::audio::SOFT_LIMIT_KNEE
);
}
let mut acc: Vec<f32> = Vec::with_capacity(frame_len * 4);
// Sized for the largest surround frame (7.1 HQ ≈ 1.3 KB at 5 ms); ample for normal quality.
let mut opus_buf = vec![0u8; 4096];
@@ -253,7 +267,10 @@ pub(super) fn audio_thread(
}
pace_due = Some(pace_due.unwrap_or_else(std::time::Instant::now) + FRAME_INTERVAL);
let frame: Vec<f32> = acc.drain(..frame_len).collect();
let mut frame: Vec<f32> = acc.drain(..frame_len).collect();
if gain != 1.0 {
punktfunk_core::audio::apply_gain(&mut frame, gain);
}
let pts_ns = next_pts_ns;
next_pts_ns += FRAME_MS as u64 * 1_000_000;
match enc.encode_float(&frame, &mut opus_buf) {
+11 -1
View File
@@ -321,16 +321,26 @@ pub(super) fn spawn(
}
let stop_t = stop.clone();
let endpoint_id = ep.endpoint_id;
let vis_id = endpoint_id.clone();
match std::thread::Builder::new()
.name(format!("punktfunk1-pad{pad}"))
.spawn(move || {
// COM for the visibility flips (the capturer's opens run on their own thread).
let _ = wasapi::initialize_mta();
// The endpoint parks HIDDEN while no pad is attached — an idle visible "Wireless
// Controller" speaker makes libScePad titles engage their DualSense-haptics path
// against an endpoint nothing services (the 2026-08-14 Helldivers 2 field tank).
// Show it for exactly this pad's lifetime, like a real DualSense arriving; the
// capturer's open/backoff loop absorbs the moment audiosrv takes to re-activate.
crate::audio::pad_endpoint::set_visibility(&vis_id, pad, true);
pad_audio_thread(
conn,
pad,
kinds,
move || crate::audio::pad_endpoint::PadLoopbackCapturer::open(&endpoint_id),
stop_t,
)
);
crate::audio::pad_endpoint::set_visibility(&vis_id, pad, false);
}) {
Ok(join) => Some(PadAudioHandle {
stop,
@@ -159,6 +159,12 @@ impl NativePairing {
self.store.remove(fp_hex)
}
/// Remove EVERY paired client in one persisted write. Returns the fingerprints removed, so the
/// caller can end the sessions they own. On a persist failure nothing is removed.
pub fn remove_all(&self) -> Result<Vec<String>> {
self.store.remove_all()
}
// -- Delegated approval (roadmap §8b-1) ---------------------------------
/// Record an unpaired device's knock for delegated approval. Re-knocks from the same fingerprint
@@ -130,6 +130,28 @@ impl TrustStore {
Ok(removed)
}
/// Remove EVERY paired client, in ONE persisted write. Returns the fingerprints removed, so
/// the caller can tear down the live sessions they own. On a persist failure the in-memory
/// store is rolled back (it never diverges from disk), exactly like [`Self::remove`].
///
/// Not a loop over [`Self::remove`]: that would rewrite (and fsync-rename) the store once per
/// client, and a failure partway would leave the operator with a half-emptied trust store and
/// no way to tell which half.
pub(super) fn remove_all(&self) -> Result<Vec<String>> {
let mut p = self.paired.lock().unwrap();
if p.clients.clients.is_empty() {
return Ok(Vec::new());
}
// `take` leaves the empty list in place to be persisted, and hands us the snapshot that
// doubles as both the rollback value and the removed-fingerprint report.
let snapshot = std::mem::take(&mut p.clients.clients);
if let Err(e) = save(&p) {
p.clients.clients = snapshot;
return Err(e);
}
Ok(snapshot.into_iter().map(|c| c.fingerprint).collect())
}
/// The number of paired clients (for the status snapshot).
pub(super) fn count(&self) -> u32 {
self.paired.lock().unwrap().clients.clients.len() as u32
+15 -5
View File
@@ -7,12 +7,20 @@
//! 1. **SHA-256 == the signed manifest's** — the primary integrity gate (the manifest is the
//! Ed25519-verified document; this check makes the downloaded bytes those exact bytes).
//! 2. **Authenticode**: the embedded signature must be cryptographically valid, tolerating
//! `CERT_E_UNTRUSTEDROOT` while the shipping cert is self-signed (`CN=unom`); when the
//! `CERT_E_UNTRUSTEDROOT` (canary and local builds still sign with a self-signed cert, and
//! releases moved to Azure Artifact Signing without needing this to tighten); when the
//! manifest carries leaf pins, the signing leaf's SHA-256 must match one. The leaf is taken
//! from the SAME `WinVerifyTrust` state (`WTHelperGetProvSignerFromChain`), never a second
//! parse — no verify-vs-inspect gap. An empty pin list skips only the pin comparison (the
//! manifest hash already binds content; pins arrive via `AUTHENTICODE_SHA256` in CI once
//! the cert story settles — the field exists so Trusted Signing is a manifest edit).
//! manifest hash already binds content).
//!
//! **Leaf pinning cannot be used with Azure Artifact Signing.** That service mints a fresh leaf
//! per signing request, valid ~3 days, so an `AUTHENTICODE_SHA256` pin would go stale within days
//! of publishing and reject every subsequent release. (An earlier note here assumed the opposite —
//! that the pin field made Trusted Signing "a manifest edit". It does not.) If pinning is wanted
//! against the Azure-signed artifacts, pin something stable instead: the issuing intermediate, or
//! the certificate subject. Leave the list empty until then; the Ed25519-signed manifest hash is
//! what actually binds the downloaded bytes.
//!
//! The spawn uses `CREATE_BREAKAWAY_FROM_JOB`: the service worker's job object is kill-on-close
//! (a stopping service would otherwise take the installer down with it) and was created
@@ -284,8 +292,10 @@ fn preflight_disk(at: &Path, needed: u64) -> Result<(), String> {
Ok(())
}
/// Authenticode: valid embedded signature (untrusted root tolerated — self-signed `CN=unom`),
/// signing-leaf SHA-256 ∈ `pins` when pins are present. The leaf comes out of the same
/// Authenticode: valid embedded signature (untrusted root tolerated — canary/local builds are still
/// self-signed), signing-leaf SHA-256 ∈ `pins` when pins are present — but see the module docs: a
/// leaf pin is unusable against Azure-signed releases, whose leaf rotates every few days. The leaf
/// comes out of the same
/// `WinVerifyTrust` state via `WTHelperGetProvSignerFromChain`. (`pub(crate)`: the service
/// supervisor's boot-loop rollback re-checks the cached previous installer with it.)
pub(crate) fn verify_authenticode(path: &Path, pins: &[String]) -> Result<(), String> {
+537 -191
View File
File diff suppressed because it is too large Load Diff
+5 -3
View File
@@ -93,8 +93,9 @@ the full picture (and [Bazzite](/docs/bazzite) for that distro's specifics).
| `PUNKTFUNK_GAMESCOPE_NODE` | `auto` · node id | Discover + capture a **running** gamescope's PipeWire node at a fixed mode. Do **not** combine with `SESSION`. |
| `PUNKTFUNK_GAMESCOPE_APP` | command | For an ad-hoc bare-gamescope session, the nested command to run (e.g. `vkcube`). |
| `PUNKTFUNK_GAMESCOPE_HDR` | `1` · `0` *(default on)* | Allow HDR (10-bit BT.2020 PQ) sessions on the gamescope backend. Needs the `punktfunk-gamescope` build — see [HDR on gamescope](/docs/gamescope#hdr-on-gamescope); without the build, sessions stream SDR. Set `0` to force SDR. |
| `PUNKTFUNK_GAMESCOPE_SDR_NITS` | e.g. `400` | On an HDR gamescope session, the luminance SDR content (desktop, Steam overlay, SDR games) is mapped to inside the PQ container. Unset = gamescope's own default of 400. |
| `PUNKTFUNK_GAMESCOPE_SDR_NITS` | e.g. `400` | On an HDR gamescope session, the luminance SDR content (desktop, Steam overlay, SDR games) is mapped to inside the PQ container. Unset = 203, BT.2408 reference white, which is what our clients decode against (gamescope's own default of 400 sits nearly a stop above it). |
| `PUNKTFUNK_GAMESCOPE_BIN` | path | Force a specific gamescope binary for the sessions the host spawns. Unset = prefer `punktfunk-gamescope` on `PATH`, then `gamescope`. |
| `PUNKTFUNK_GAMESCOPE_WSI_LAYER_DIR` | path | Directory holding our Vulkan WSI layer's manifest — the layer that lets a game nested under gamescope get an HDR10 swapchain. Unset = `/usr/lib/punktfunk/vulkan/implicit_layer.d`, where every distro package installs it. The NixOS module sets this for you, since the layer lives inside the gamescope derivation there. If no manifest is found the host leaves the system's own layer alone and games stay SDR. |
| `PUNKTFUNK_SESSION_WATCH` | `1` · `0` | Follow a Gaming ↔ Desktop switch **mid-stream** (rebuild the backend in place, no reconnect). **On by default** on Bazzite/SteamOS; set `0` to disable. |
| `PUNKTFUNK_GAMESCOPE_GRAB_CURSOR` | `1` | Add `--force-grab-cursor` to a bare gamescope session the host spawns **to run an app or game** (never the empty keep-alive session), forcing relative-mouse capture so FPS mouselook works over the injected pointer. **Off by default** — relative mode breaks absolute-pointer titles and menus, so turn it on per host. |
| `PUNKTFUNK_GAMESCOPE_SPLASH` | `1` · `0` *(default on)* | Run the built-in splash client inside each bare gamescope session the host spawns. **Leave it on**: gamescope only produces capture buffers once something paints, and a Steam launch paints nothing for its whole bootstrap — without the splash a fresh session starves and times out. `0` is a debugging escape hatch. |
@@ -114,6 +115,7 @@ See your desktop page ([KDE](/docs/kde), [GNOME](/docs/gnome)) for when to set t
|---|---|---|
| `PUNKTFUNK_KWIN_VIRTUAL_PRIMARY` | `1` | Make the streamed per-session output the sole desktop so plasmashell + windows render on it (not on the headless bootstrap output). Set by the KDE appliance `host.env`. Superseded by the console's **Topology** setting. |
| `PUNKTFUNK_MUTTER_VIRTUAL_PRIMARY` | `1` | GNOME/Mutter equivalent of the above. |
| `PUNKTFUNK_PORTAL_CURSOR_MODE` | `auto` *(default)* · `embedded` · `metadata` · `hidden` | **Hyprland / wlroots only, and a troubleshooting knob** — which ScreenCast cursor mode the host asks the portal for. Unset, the host asks for `metadata` when the client draws the pointer itself and `embedded` otherwise, then settles that against the modes your portal advertises; it never requests one your portal lacks. Set `embedded` if the pointer misbehaves on a portal that *claims* metadata support but implements it poorly — that is the one case the automatic negotiation cannot detect. A pin is still only a preference: it is checked against the advertised modes like any other. |
## Session recovery (Linux)
@@ -154,7 +156,7 @@ See your desktop page ([KDE](/docs/kde), [GNOME](/docs/gnome)) for when to set t
|---|---|---|
| `PUNKTFUNK_AUDIO_QUALITY` | `low` · `standard` · `high` *(default `high`)* | Desktop-audio encode quality. `high` (stereo 256 kbps Opus, effectively transparent) costs about 1 % of a normal video bitrate, so there's rarely a reason to go lower. `standard` is exactly the pre-0.25 encoder (stereo 128 kbps) — handy for an A/B comparison; `low` is for genuinely constrained links (noticeably lossy on music, still fine for game audio and voice). A typo warns in the log and keeps `high` rather than silently downgrading. Host-side only — clients play whatever arrives, no client setting involved. |
| `PUNKTFUNK_AUDIO_REDUNDANCY` | `1` · `0` *(default: automatic)* | Send audio packets redundantly so a lossy link doesn't crackle. Leave it unset: the host turns redundancy on by itself, only toward clients that support it and only while the link is actually losing packets. `1` forces it on for the whole session, `0` never sends it. |
| `PUNKTFUNK_AUDIO_GAIN` | float (default `1.0`) | **(Moonlight/GameStream sessions only)** Linear gain applied to captured desktop audio — bump it for a quiet source. The native `punktfunk/1` path ignores it; adjust the source's own volume there instead. |
| `PUNKTFUNK_AUDIO_GAIN` | float (default `1.0`) | Gain applied to captured desktop audio — bump it for a quiet source. Applies to **both** the native `punktfunk/1` and Moonlight/GameStream paths. Peaks are rounded off by a soft limiter rather than clipped, so a boost distorts gracefully instead of abruptly; values above `8.0` (+18 dB) are capped, and a non-positive value is ignored. Note this buys **headroom, not loudness** — it cannot make a desktop mix as loud as already-limited streaming-app audio, and pushing it hard to try will audibly squash the signal. On Windows this is the only host-side control that works at all: loopback capture is tapped upstream of the endpoint's master volume, so the speaker slider does not affect what a client receives. |
| `PUNKTFUNK_MIC_DEVICE` | name substring | **(Windows)** Target mic-uplink device by friendly-name substring (first match wins). |
| `PUNKTFUNK_MIC_LEGACY_BUFFER` | `1` | Restore the fixed pre-adaptive mic buffering (a ~48 ms prime and ~120 ms cap on Windows; a buffer scaled to the recording app's audio quantum on Linux) instead of the adaptive per-client jitter target. One-release escape hatch: if the microphone coming out of the host only sounds right *with* this set, that's a bug — please report it. |
| `PUNKTFUNK_NO_MIC_INSTALL` | set | **(Windows)** Skip installing the virtual-mic driver (e.g. when the host runs as SYSTEM). |
@@ -217,7 +219,7 @@ it — leave it or delete it, it makes no difference.
| `PUNKTFUNK_PLUGIN_TOKEN` | token | The scoped token the [plugin/scripting runner](/docs/plugins) uses — a narrower credential than `PUNKTFUNK_MGMT_TOKEN`, never full admin. Same precedence: if unset it's generated and persisted to `~/.config/punktfunk/plugin-token`. Set only to pin a specific token. |
| `PUNKTFUNK_CONFIG_DIR` | path | Override the config directory (default `~/.config/punktfunk`) — pairing state, certs, apps.json, captures. |
| `PUNKTFUNK_UI_PLUGIN_PORT` | port *(default: console port + 1)* | The separate port [plugin](/docs/plugins) UIs are served from. They get their own origin on purpose — a plugin page can never act as *you* on the console. If the console log says this port couldn't be opened (plugin UIs then stay disabled rather than sharing the console's origin), point it at a free port and restart. |
| `PUNKTFUNK_LIBRARY_ART_ROOTS` | directories, `;`-separated | Where the host is allowed to read game artwork from when serving your library. Defaults to sensible platform roots (your home directory on Linux/macOS); set it when box art lives elsewhere — a second drive, a network mount. The host log's "not under an allowed art root" line is this knob's cue. |
| `PUNKTFUNK_LIBRARY_ART_ROOTS` | directories, separated like `PATH` (`;` on Windows, `:` on Linux/macOS) | Where the host is allowed to read game artwork from when serving your library. Defaults to sensible platform roots: your home directory on Linux/macOS, and on Windows the users base (`C:\Users`) plus your Steam install, wherever it is. Set it when box art lives somewhere else again — a second drive, a network mount, or a launcher installed outside all of those. Setting it **replaces** the defaults, so list every root you need. The host log's "dropped local art the proxy may not serve" line is this knob's cue: those entries still appear in your library, but their covers stay blank until the root is allowed. |
## Updates
+5 -2
View File
@@ -85,8 +85,11 @@ happens. Staying on attach also leaves the stream with no cursor;
[HDR on gamescope](/docs/gamescope#hdr-on-gamescope) has the fix for that half.
SDR content rides the same PQ container — the desktop, the Steam overlay, an SDR game — mapped in at
`PUNKTFUNK_GAMESCOPE_SDR_NITS` (gamescope's own default is 400). That is the knob when white looks
too bright or too dim on your TV.
`PUNKTFUNK_GAMESCOPE_SDR_NITS`, which defaults to **203 nits**. That is BT.2408 reference white, and
it is the level our clients decode against, so the two ends agree out of the box. gamescope's own
default is 400, nearly a stop brighter; hosts that let it float showed a glaring, over-saturated
Steam UI and washed-out HDR game content on the same stream. Move the knob if you want a brighter or
dimmer desktop, but be aware that moving it re-opens that gap.
### Linux + GNOME
+25
View File
@@ -84,6 +84,31 @@ and fails the session with a clear error rather than streaming a blank surface.
capture the Hyprland log (`hyprctl` instance dir → `hyprland.log`) and check your GPU's GBM support;
running Hyprland as a real session (not nested) is the supported configuration.
## Troubleshooting: black client + "unavailable cursor mode 4"
A black client, `pipeline build failed` in the host log, and **`unavailable cursor mode 4`** from
xdph are one failure, not three.
`4` is the ScreenCast portal's *metadata* cursor mode, which the host prefers when the client draws
the pointer locally (desktop mouse mode). xdg-desktop-portal-hyprland **does not offer that mode**
on a current stack (Hyprland 0.56.2, xdph 1.4.1) its `AvailableCursorModes` is `3`, meaning hidden
and embedded only. Asking for a mode the backend does not advertise is not a soft failure:
`xdg-desktop-portal` rejects the call outright, so the cast died during setup and the client had
nothing to show.
Updating xdph does **not** fix this — the mode is absent on current versions, not just old ones.
Hosts from this release check what your portal advertises and use an embedded cursor instead, so the
session streams. If you are on an older host, switch the client to **game mouse mode**: that stops
it asking for the metadata cursor at all.
If the pointer misbehaves on an xdph that *does* advertise metadata support, pin the mode:
```sh
PUNKTFUNK_PORTAL_CURSOR_MODE=embedded
```
See [Configuration](/docs/configuration#compositor-specific-linux).
## Permission system
Hyprland's permission system (`ecosystem.enforce_permissions`, 0.49+, **off by default**) can deny
+14
View File
@@ -82,6 +82,20 @@ For how long the virtual output lives, and extend-vs-exclusive topology, see
Then `systemctl --user restart xdg-desktop-portal`. On a box with only xdpw installed there is
nothing to choose between, so you can skip this.
## Troubleshooting: black client + "unsupported cursor mode requested"
A black client with `pipeline build failed` in the host log and **`dbus: unsupported cursor mode
requested, cancelling`** from xdpw is one failure, not two.
xdpw refuses the ScreenCast *metadata* cursor mode and cancels the cast, and the portal spec makes
that fatal rather than a fallback. Hosts before this release asked for it whenever the client drew
the pointer itself (desktop mouse mode), so those sessions never produced a frame. Hosts from this
release check what xdpw advertises first and use an embedded cursor instead, so the session streams.
On an older host, switch the client to **game mouse mode** — it stops asking for the metadata cursor
and the stream comes up. The same failure on Hyprland reads `unavailable cursor mode 4`; see
[Hyprland](/docs/hyprland).
## Start the host
With the backend selected, start the host from **inside your Sway session**:
+20 -20
View File
@@ -10,30 +10,30 @@
"lint": "tsc --noEmit"
},
"dependencies": {
"@fontsource-variable/geist": "^5.2.9",
"@scalar/api-reference-react": "^0.9.47",
"@tanstack/react-router": "^1.121.0",
"@tanstack/react-start": "^1.121.0",
"@unom/app-ui": "^0.1.0",
"@fontsource-variable/geist": "^5.3.0",
"@scalar/api-reference-react": "^0.9.63",
"@tanstack/react-router": "^1.170.28",
"@tanstack/react-start": "^1.168.45",
"@unom/app-ui": "^0.2.1",
"@unom/style": "^0.4.4",
"@unom/ui": "^0.8.16",
"fumadocs-core": "^16.10.5",
"fumadocs-ui": "^16.10.5",
"react": "^19.0.0",
"react-dom": "^19.0.0"
"@unom/ui": "^0.9.2",
"fumadocs-core": "^16.14.4",
"fumadocs-ui": "^16.14.4",
"react": "^19.2.8",
"react-dom": "^19.2.8"
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"@tailwindcss/vite": "^4.3.3",
"@tanstack/nitro-v2-vite-plugin": "^1.155.0",
"@types/mdx": "^2.0.14",
"@types/node": "^22.10.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^5",
"fumadocs-mdx": "^15.0.12",
"tailwindcss": "^4.0.0",
"typescript": "^5.7.0",
"vite": "^7.3.5",
"vite-tsconfig-paths": "^5.1.0"
"@types/node": "^22.20.1",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.4",
"@vitejs/plugin-react": "^5.2.0",
"fumadocs-mdx": "^15.2.3",
"tailwindcss": "^4.3.3",
"typescript": "^5.9.3",
"vite": "^7.3.6",
"vite-tsconfig-paths": "^5.1.4"
}
}
+97 -1
View File
@@ -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}": {
@@ -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}": {
@@ -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).",
+63
View File
@@ -0,0 +1,63 @@
Wire-compatible with 0.28.0 — everything you have already paired keeps working, and you can update one side at a time. Nothing here changes how a host and a client agree on what to send each other, so an old client on a new host, or the other way round, streams exactly as it does today.
This is a fix release, and most of it is about things that were wrong in ways nothing announced. On Windows, your Steam library could stay completely empty after the last update, and a Punktfunk host sitting idle — nothing connected, nothing streaming — could wreck the frame rate of a game you were playing on that same machine. Streaming from a Mac with the microphone on cut the sound and froze the controls every couple of seconds. An Android TV box could be silent for a whole session; a Steam Deck's Punktfunk home would not open; games could not reach high dynamic range (HDR) at all on Linux machines running our own compositor, while the Steam interface in front of them glared; and an Apple TV was being pushed into HDR mode by streams that were not HDR at all, lifting blacks to grey.
Several of these came from people who reported them carefully enough to be found. One of them, the crash that lost your game on reconnect, was tracked down, fixed and proven on his own hardware by **luxus** — that fix is in this release as he wrote it.
## TL;DR
- **On Windows, your Steam games went missing after 0.28.0** — the add-on could publish nothing, because Steam keeps its artwork somewhere the host was not allowed to read.
- **An idle host could ruin a game running on that same Windows machine**, down to 25 frames per second, with nothing connected and no stream running.
- **Streaming from a Mac with your microphone on cut the sound and froze your controls every couple of seconds** — and turning the mic off was the only way round it.
- **No sound at all on some Android TV boxes**, an NVIDIA Shield in particular — and sound now returns by itself when your TV changes mode mid-stream.
- **The Punktfunk home would not open on a Steam Deck after 0.28.0**, and streams elsewhere lost their statistics overlay to the same fault.
- **Streaming your desktop with the pointer forwarded gave a black picture on Hyprland and Sway** — every current install, not just old ones.
- **High dynamic range was broken in both directions on Linux hosts:** games could not reach it at all, and everything else was mapped a stop too bright. Both fixed.
## Before you update
- **On Windows, two things in your Sound settings will look different, and both are deliberate.** "Speakers (Wireless Controller)" now shows as *disabled* whenever no controller is connected through Punktfunk — that is it parked out of the way of your local games, not a fault, and it comes back on its own. And Punktfunk no longer keeps your default microphone: it borrows it for the length of a stream and gives it back. If you actually want apps to record the client's microphone while nothing is streaming, select "Punktfunk Microphone" yourself — your choice will now be left alone.
- **Only if you are coming from 0.27 or older:** read [the 0.28.0 notes](https://git.unom.io/unom/punktfunk/releases/tag/v0.28.0) first. That release has two things that need you to act — your game library now comes from add-ons you install per store (with none installed, your library is empty), and Moonlight-compatible connections became something you switch on. Neither applies if you are already on 0.28.0.
## New
- **Your saved hosts have a menu when you use a controller on Apple devices.** Press up on a host tile for Wake, Copy link, Edit, Forget pairing and Remove — the same menu the desktop and Android consoles already had, so all three work the same way. A renamed machine or a mistyped address used to stay wrong forever unless you switched to touch. Removing asks twice, deliberately, because a thumbstick from across the room deserves at least as much care as a dialog.
- **The shortcut list is now a page you can open.** It used to appear as a banner over the stream for six seconds right after connecting — which is the one moment nobody is asking what the controls are. It lives in an About section you can visit whenever you want it.
- **Unpair every device at once.** Clearing a host's paired devices meant deleting them one at a time, confirming each. There is now a single action for it on the Paired devices card, and it ends any live session belonging to a device it removes.
## Improved
- **High dynamic range brightness matches between host and client.** Anything that is not an HDR game — your desktop, the Steam overlay, an ordinary title — was being mapped nearly a stop brighter by the host than every Punktfunk client expects. That is what made the Steam interface look glaring and over-saturated while actual HDR game content looked flat and washed out on the same stream. Both come from the same mistake and both are fixed.
- **Your host tells you when high dynamic range cannot work.** A session could start advertising HDR while having made it unreachable for every game inside it, with nothing anywhere explaining the washed-out result. It now says so.
- **The on-screen statistics no longer double-count decoding.** On machines using the fastest decoding path, the stage breakdown listed a figure that was already included in another one, so the parts did not add up to the total and a reader who checked was right to be confused. It is now reported separately, labelled as the single sample it is.
## Fixed
- **On Windows, the Steam add-on synced nothing and your grid stayed empty.** Steam installs to Program Files and keeps its artwork there, and the host's list of places it is allowed to read art from covered the launchers that install per-user — but not Steam. Every cover the add-on offered was rejected, and because one bad cover failed the whole submission, that meant every Steam game rather than one thumbnail. Both halves are fixed: Steam's own install locations are now allowed (including on a second drive), and a cover that cannot be served is dropped so the rest of your library still arrives. This only affected Windows — every Steam layout on Linux was already covered — and it arrived with 0.28.0, when the built-in Steam scanner was replaced by the add-on.
- **A Punktfunk host that was doing nothing at all could wreck a game running on the same Windows machine** — 25 frames per second at worst, with no client connected and no stream ever started. Two independent causes, both from the same set of reports: the host presents a controller speaker that looks exactly like a real DualSense's, and a game that finds it engages its DualSense audio path against a device nothing is feeding; and the host was claiming your default microphone permanently, so any game holding an open voice input stalled on a virtual mic that only runs during a stream. The controller speaker is now hidden except while a controller is actually attached, and your microphone is only borrowed for the length of a stream. Machines already stuck repair themselves on the next start.
- **Streaming your desktop with the pointer forwarded gave a black picture on Hyprland and Sway.** Punktfunk asked the desktop's screen-sharing service for the pointer in a form neither compositor offers, and the request was refused before it ever reached them — so the whole capture failed rather than losing just the pointer. It now asks what is actually available and takes the best on offer. Measured against fully up-to-date Hyprland and portal versions: this was every current install, and updating them would not have helped. You will now see a single pointer drawn by the host instead of your client drawing its own.
- **Streaming from a Mac with the microphone on cut the audio and froze the controls on a two-and-a-half second beat**, while the picture carried on untouched. Some microphones — a multi-channel audio interface set as your Mac's input, for instance — cannot run the echo-cancelling mode Punktfunk asks for. Each failed attempt knocked out the working audio path, and the knock-out was itself the signal that triggered the next attempt, so it went round forever. Your controls froze on the same beat because that rebuild happened on the part of the app that also sends your keyboard and mouse. All three links in that loop are broken now, and audio setup no longer happens where your input lives — so even a genuine change of sound device no longer costs you control of the stream. Until now the only workaround was turning the client's microphone off.
- **An Android TV box could have no audio for an entire session.** Reported on an NVIDIA Shield with a host and settings that played fine everywhere else, and video unaffected. The app asked Android for an audio device and then trusted the answer: a device that accepted the request but played nothing was never noticed, a device that refused to start disabled sound for the rest of the session, and — most common on a television — a device that went away during an HDMI mode change was never reopened. It now proves that sound is actually being taken before it accepts a device, and reopens automatically when your TV or receiver changes mode. TV boxes now use the ordinary shared audio path rather than the exclusive low-latency one, which was never buying them the latency it cost.
- **The Punktfunk home would not open on a Steam Deck after updating to 0.28.0.** Both the Decky button and the library shortcut failed. The same fault silently removed the statistics and capture overlays inside streams on other machines. It came from a graphics library sizing itself to what the machine's graphics driver supported rather than to what Punktfunk had asked for, which only became a problem once drivers moved ahead of us.
- **Games could not use high dynamic range on Linux hosts running Punktfunk's compositor** — on essentially every machine, not a rare configuration. Reaching HDR requires a small graphics component that has to match the compositor exactly, and we shipped the compositor without it, leaving the host guessing whether the one your distribution provided was compatible. Because we build our own compositor, that guess was almost always wrong in the direction of switching HDR off. We now ship the matching component ourselves, on every Linux packaging channel.
- **Reconnecting after a disconnect could lose your game** on Linux hosts with an NVIDIA card. The host keeps your session alive when a client leaves so reconnecting resumes it, and the compositor could crash in exactly that window — so the session you came back to was a brand-new one with your game gone. Found, fixed and proven in the field by **luxus**, over an evening of Baldur's Gate 3 at 4K60 HDR that had produced four crashes before the fix and none after.
- **A stream that was not HDR pushed an Apple TV into HDR mode anyway**, which switches the HDMI output to limited range — so on a television set for full range, black came out grey. The switch was triggered by your HDR *setting* being on rather than by the stream actually being HDR, and that setting is on by default.
- **Ordinary streams on Apple devices were drawn with no colour information at all**, leaving them mildly over-saturated on a Mac or iPad with a wide-colour screen, and lifting blacks on an Apple TV. A stream that was not HDR from its very first frame skipped colour setup entirely.
- **The statistics overlay on Apple devices reported numbers that could not be true** — a network figure lower than the host's own encoding time, and historically readings of zero. Three faults: the clock difference with the host was measured once at connect and never updated (it drifts, and on a virtual-machine host it jumps), impossible samples were being discarded silently rather than invalidating the reading, and several unavailable values printed as "NaN". The overlay now warns you when a reading is suspect instead of showing a plausible wrong number.
- **AV1 streams fell back to slower decoding** on hardware that decodes them perfectly well. Some encoders mark a stream as "not restricted to any quality level", and that marker was being read as a level so high that no device could claim to support it.
- **On Apple TV, console text could be white on a pale background**, making screens unreadable with the light appearance.
- **Punktfunk add-ons could not be installed on NixOS**, where the component that manages them was reported missing on machines where it was installed, enabled and running.
- **On NixOS the host could crash-loop forever, unable to claim its own ports.** A second copy was being started under the root account — which springs into life the moment anyone signs in as root — and it won the race for the ports the real one needed. The log blamed some other program, because a second copy of itself is the last thing anyone looks for. The service is now scoped to the accounts you list.
- **Two host warnings blamed the wrong thing.** One announced a "metronomic" disturbance from your display hardware when the regular timing was in fact a client's own recovery interval; the other reported catastrophic audio loss between sessions, when what it had counted was silence during the seconds no one was connected. Neither ever indicated a real fault.
## Thanks
**luxus** found the crash that lost your game on reconnect, wrote the fix, and proved it on his own machine — an evening of Baldur's Gate 3 at 4K60 HDR that had produced four crashes before it and none after. It ships here as he wrote it.
Most of the rest of this release exists because people took the trouble to report a fault precisely: the silent Android TV box, the empty Steam library, the game stuttering next to an idle host, the washed-out HDR, the black picture on Hyprland. Thank you — that detail is what makes a fault findable.
## For developers
Protocol, ABI, driver and embedder detail — including the version table and the (empty) breaking-changes list — is in [CHANGELOG.md](https://git.unom.io/unom/punktfunk/src/tag/v0.28.1/CHANGELOG.md).
Nothing breaks: the wire protocol, the C ABI, the virtual-display driver protocol and the plugin contract are all unchanged from v0.28.0. Three things are worth reading if they apply to you: every Linux packaging channel now ships a second gamescope artifact and a package without it fails to build rather than degrading quietly, Android's `nativeStartAudio` takes one more argument, and `SessionAudio.start()` is now asynchronous on macOS as it already was on iOS and tvOS — playback is live shortly after the call rather than on return.
+3
View File
@@ -0,0 +1,3 @@
• Fixes having no sound at all on some Android TV boxes, the NVIDIA Shield among them. The app now checks that your TV or receiver is really taking the audio, instead of trusting that it will.
• Sound returns on its own when your TV or receiver changes mode during a stream. Before, it could stay silent for the rest of the session.
• A stream that loses audio now says so, rather than looking exactly like an app with nothing to play.
+4
View File
@@ -69,6 +69,10 @@
# from source and would make `nix flake check` an hour long.
punktfunk-gamescope = pkgs.callPackage ./packaging/nix/gamescope.nix {
patchDir = ./packaging/gamescope/patches;
# Shared verbatim with build-punktfunk-gamescope.sh, which is the whole reason it is a
# file: the FHS packages and the Nix store must rename the WSI layer identically, or
# the host looks for a layer name that only one of them produces.
manifestRewriter = ./packaging/gamescope/rewrite-wsi-layer-manifest.py;
};
};
in
+9 -1
View File
@@ -77,7 +77,15 @@ if [ -n "$GAMESCOPE" ]; then
[ -x "$GS_BIN" ] || { echo "$GAMESCOPE did not provide usr/bin/punktfunk-gamescope" >&2; exit 1; }
"$GS_BIN" --version 2>&1 | grep -q '+pfhdr' || {
echo "$GAMESCOPE's binary has no +pfhdr marker — it is not a punktfunk HDR build" >&2; exit 1; }
echo "folded in $("$GS_BIN" --version 2>&1 | head -1)"
# The package carries the Vulkan WSI layer alongside the compositor and the extraction above takes
# the whole `usr`, so this is an assertion rather than a step — but a silent one is exactly how
# this went wrong before: an image with the compositor and no layer streams HDR while every game
# inside it renders SDR, and nothing anywhere says why.
for f in usr/lib/punktfunk/libVkLayer_PUNKTFUNK_gamescope_wsi.so \
usr/lib/punktfunk/vulkan/implicit_layer.d/punktfunk_gamescope_wsi.json; do
[ -f "$STAGE/$f" ] || { echo "$GAMESCOPE has no $f — no game HDR without it" >&2; exit 1; }
done
echo "folded in $("$GS_BIN" --version 2>&1 | head -1) + its WSI layer"
fi
# The marker systemd-sysext requires to merge the image. ID=_any merges onto ANY host os-release
+27 -10
View File
@@ -24,15 +24,20 @@
#
# Usage:
# bash build-sysext.sh --version-id 43 --out dist/punktfunk-0.7.1-1-x86-64.raw \
# [--gamescope path/to/punktfunk-gamescope] \
# [--gamescope-stage path/to/gamescope-destdir] \
# dist/punktfunk-0.7.1-1.fc43.x86_64.rpm dist/punktfunk-web-0.7.1-1.fc43.noarch.rpm
#
# --gamescope folds in a prebuilt HDR-capable gamescope (packaging/gamescope) as
# --gamescope-stage folds in a prebuilt HDR-capable gamescope (packaging/gamescope) as
# /usr/bin/punktfunk-gamescope, which is what lets the gamescope backend stream 10-bit BT.2020 PQ.
# It is NOT built here: it is a C++ meson build with gamescope's whole dependency set, so CI builds
# it in the same Fedora container beforehand (`bash packaging/gamescope/build-punktfunk-gamescope.sh
# --destdir stage --prefix /usr`) and passes the resulting binary in. Omit it and the image is
# exactly what it was — the host then stays SDR on that backend, by design.
# --destdir stage --prefix /usr`) and passes that DESTDIR in. Omit it and the image is exactly what
# it was — the host then stays SDR on that backend, by design.
#
# A directory rather than the binary, because the tree also carries the Vulkan WSI layer built beside
# the compositor. That layer is the only route to an HDR10 swapchain for a game nested under
# gamescope, so an image with the compositor and without it would stream HDR while every game in it
# rendered SDR.
#
# The installed image MUST be named punktfunk.raw (the embedded extension-release marker is
# extension-release.punktfunk; systemd-sysext requires marker == image name) — the feed carries
@@ -44,7 +49,7 @@ while [ $# -gt 0 ]; do
case "$1" in
--version-id) VERSION_ID="${2:?}"; shift 2 ;;
--out) OUT="${2:?}"; shift 2 ;;
--gamescope) GAMESCOPE="${2:?}"; shift 2 ;;
--gamescope-stage) GAMESCOPE="${2:?}"; shift 2 ;;
*) RPMS+=("$1"); shift ;;
esac
done
@@ -87,15 +92,27 @@ if [ -d "$STAGE/etc" ]; then
fi
rm -rf "${STAGE:?}/var" # rpm ghosts etc. — nothing outside /usr may remain
# The HDR-capable gamescope, when one was built (see --gamescope in the header). Verified by its
# The HDR-capable gamescope, when one was built (see --gamescope-stage in the header). Verified by its
# banner marker rather than trusted by filename: an unpatched gamescope shipped under this name
# would make the host promise HDR it cannot deliver, and the punktfunk/1 Welcome cannot take that
# back mid-session.
if [ -n "$GAMESCOPE" ]; then
[ -x "$GAMESCOPE" ] || { echo "no such executable: $GAMESCOPE" >&2; exit 1; }
"$GAMESCOPE" --version 2>&1 | grep -q '+pfhdr' || {
echo "$GAMESCOPE has no +pfhdr marker — it is not a punktfunk HDR build" >&2; exit 1; }
install -Dm0755 "$GAMESCOPE" "$STAGE/usr/bin/punktfunk-gamescope"
GS_BIN="$GAMESCOPE/usr/bin/punktfunk-gamescope"
GS_LAYER_SO="$GAMESCOPE/usr/lib/punktfunk/libVkLayer_PUNKTFUNK_gamescope_wsi.so"
GS_LAYER_JSON="$GAMESCOPE/usr/lib/punktfunk/vulkan/implicit_layer.d/punktfunk_gamescope_wsi.json"
[ -x "$GS_BIN" ] || { echo "no such executable: $GS_BIN" >&2; exit 1; }
"$GS_BIN" --version 2>&1 | grep -q '+pfhdr' || {
echo "$GS_BIN has no +pfhdr marker — it is not a punktfunk HDR build" >&2; exit 1; }
# Fatal for the same reason the marker check is: an image carrying the compositor without its
# layer streams HDR while every game inside it renders SDR, and says nothing about why.
for f in "$GS_LAYER_SO" "$GS_LAYER_JSON"; do
[ -f "$f" ] || { echo "$f missing — the gamescope stage has no WSI layer" >&2; exit 1; }
done
install -Dm0755 "$GS_BIN" "$STAGE/usr/bin/punktfunk-gamescope"
install -Dm0755 "$GS_LAYER_SO" \
"$STAGE/usr/lib/punktfunk/libVkLayer_PUNKTFUNK_gamescope_wsi.so"
install -Dm0644 "$GS_LAYER_JSON" \
"$STAGE/usr/lib/punktfunk/vulkan/implicit_layer.d/punktfunk_gamescope_wsi.json"
fi
# Enable the plugin/script runner for every user, by baking its `[Install] WantedBy=default.target`
+28 -5
View File
@@ -10,24 +10,38 @@
# not Provide/Conflict with it. Only the sessions punktfunk-host starts itself resolve this binary
# (PUNKTFUNK_GAMESCOPE_BIN > punktfunk-gamescope > gamescope).
#
# `--stage` is the DESTDIR build-punktfunk-gamescope.sh wrote, not a single binary: that tree carries
# the compositor AND the Vulkan WSI layer built beside it, and a game nested under gamescope gets its
# HDR10 swapchain from that layer or from nowhere. Taking the whole tree is what stops the next file
# in the package needing a new flag in every packaging script.
#
# Usage:
# VERSION=3.16.25.pfhdr4~ci42.gdeadbee bash packaging/debian/build-gamescope-deb.sh \
# --binary gs-cache/punktfunk-gamescope [--arch amd64]
# --stage gs-cache [--arch amd64]
# Output: dist/punktfunk-gamescope_<version>_<arch>.deb
set -euo pipefail
BINARY=""
SRC_STAGE=""
DEB_ARCH=""
while [ $# -gt 0 ]; do
case "$1" in
--binary) BINARY="${2:?--binary needs a path}"; shift 2 ;;
--stage) SRC_STAGE="${2:?--stage needs a path}"; shift 2 ;;
--arch) DEB_ARCH="${2:?--arch needs a value}"; shift 2 ;;
*) echo "unknown argument: $1" >&2; exit 2 ;;
esac
done
[ -n "$BINARY" ] || { echo "ERROR: --binary is required" >&2; exit 2; }
[ -n "$SRC_STAGE" ] || { echo "ERROR: --stage is required" >&2; exit 2; }
# The layout build-punktfunk-gamescope.sh writes under its --destdir/--prefix.
BINARY="$SRC_STAGE/usr/bin/punktfunk-gamescope"
LAYER_SO="$SRC_STAGE/usr/lib/punktfunk/libVkLayer_PUNKTFUNK_gamescope_wsi.so"
LAYER_JSON="$SRC_STAGE/usr/lib/punktfunk/vulkan/implicit_layer.d/punktfunk_gamescope_wsi.json"
[ -x "$BINARY" ] || { echo "ERROR: $BINARY is not an executable file" >&2; exit 1; }
# Hard, not best-effort: a package carrying the compositor without its layer looks perfectly healthy
# and then silently denies every game an HDR10 swapchain.
for f in "$LAYER_SO" "$LAYER_JSON"; do
[ -f "$f" ] || { echo "ERROR: $f missing from the stage — no game HDR without it" >&2; exit 1; }
done
PKG="punktfunk-gamescope"
ROOTDIR="$(cd "$(dirname "$0")/../.." && pwd)"
@@ -60,6 +74,12 @@ trap 'rm -rf "$STAGE"' EXIT
# root-only and some tooling refuses it.
chmod 0755 "$STAGE"
install -Dm0755 "$BINARY" "$STAGE/usr/bin/punktfunk-gamescope"
# /usr/lib/punktfunk, not a multiarch triplet dir: the layer manifest carries that absolute path
# baked in at build time, so the two have to agree. Nothing links the .so by soname — the Vulkan
# loader dlopens it by exactly that path — so multiarch has no say here.
install -Dm0755 "$LAYER_SO" "$STAGE/usr/lib/punktfunk/libVkLayer_PUNKTFUNK_gamescope_wsi.so"
install -Dm0644 "$LAYER_JSON" \
"$STAGE/usr/lib/punktfunk/vulkan/implicit_layer.d/punktfunk_gamescope_wsi.json"
mkdir -p "$STAGE/DEBIAN"
# Shared-library dependencies straight from the binary's own ELF NEEDED entries. That is what makes
@@ -103,7 +123,10 @@ fi
echo " * --pipewire-composite-external-overlay: the mangoapp performance overlay is painted"
echo " into the capture stream, so the fps/stats readout is visible remotely."
echo " ."
echo " Installed as /usr/bin/punktfunk-gamescope; your system gamescope is untouched."
echo " Installed as /usr/bin/punktfunk-gamescope, with its matching Vulkan WSI layer under"
echo " /usr/lib/punktfunk. The layer has its own name and its own enable variable, so it sits"
echo " beside your gamescope package's rather than replacing it; your system gamescope is"
echo " untouched."
} > "$STAGE/DEBIAN/control"
mkdir -p dist
+20 -4
View File
@@ -19,7 +19,7 @@ pkgname=punktfunk-gamescope
# bump it with the marker so pacman sees a new version when only our patches moved.
_gsver=3.16.25
_gsrev=5fb8dce4a09d0a68d097b9faf9513782106bc843
pkgver="${_gsver}.pfhdr6"
pkgver="${_gsver}.pfhdr7"
# 2: patch 0006 (never destroy the Vulkan device/output at exit). No capability moved, so the
# `.pfhdrN` level deliberately stays put — see README.md.
# 3: pin moved 8c676c39 -> 5fb8dce4 (3.16.25-1 -> 3.16.25-11), which brings upstream's own
@@ -39,6 +39,12 @@ pkgver="${_gsver}.pfhdr6"
# the composite (and the stream) black while every health signal stayed green. No capability the
# host probes for, but a field box's banner has to distinguish a build that can lose its composite
# this way from one that cannot.
#
# pfhdr7 / rel 1: patch 0009 (reported + written by luxus, punktfunk-overlay#9) moves capture-buffer
# destruction off the PipeWire thread: remove_buffer used to drop the last CVulkanTexture ref there,
# racing steamcompmgr's vulkan_screenshot on the same device — a SIGSEGV precisely in the linger
# window, so a kept display was dead and reconnect lost the game session. No capability the host
# probes for, but "reconnect lost my game" triage has to read the difference off the banner.
pkgrel=1
pkgdesc="gamescope with 10-bit BT.2020/PQ PipeWire capture, for punktfunk HDR streaming"
arch=('x86_64' 'aarch64')
@@ -98,10 +104,20 @@ build() {
}
package() {
# ONLY the compositor, under our own name: a full `meson install` would also lay down
# gamescopectl / gamescopereaper / gamescopestream and the WSI layer, colliding file-for-file
# with the distro's `gamescope` package. The host only ever execs the compositor.
# The compositor, under our own name: a full `meson install` would also lay down
# gamescopectl / gamescopereaper / gamescopestream, colliding file-for-file with the distro's
# `gamescope` package. The host only ever execs the compositor.
install -Dm755 "${srcdir}/stage/usr/bin/punktfunk-gamescope" \
"${pkgdir}/usr/bin/punktfunk-gamescope"
# ...and the WSI layer built beside it. NOT a collision: the build script renamed the layer and
# rehomed it under /usr/lib/punktfunk, so it sits alongside the distro's rather than over it, and
# the host enables whichever it means to per session. Without this file no game in a punktfunk
# gamescope session can get an HDR10 swapchain at all — that layer is the only route to one.
install -Dm755 "${srcdir}/stage/usr/lib/punktfunk/libVkLayer_PUNKTFUNK_gamescope_wsi.so" \
"${pkgdir}/usr/lib/punktfunk/libVkLayer_PUNKTFUNK_gamescope_wsi.so"
install -Dm644 "${srcdir}/stage/usr/lib/punktfunk/vulkan/implicit_layer.d/punktfunk_gamescope_wsi.json" \
"${pkgdir}/usr/lib/punktfunk/vulkan/implicit_layer.d/punktfunk_gamescope_wsi.json"
install -Dm644 gamescope/LICENSE "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
}
+16
View File
@@ -19,6 +19,7 @@ The patches here add the missing half, and nothing else. See
| `0006-punktfunk-never-destroy-the-Vulkan-device-or-output-.patch` | Give `g_device` and `g_output` storage that is never destroyed, so their destructors cannot call a Vulkan driver glibc has already unloaded at `exit()` | **Yes** — a plain static-destruction-order bug, not punktfunk-specific |
| `0007-pipewire-never-leave-pw_buffer-user_data-pointing-at.patch` | Associate `pw_buffer->user_data` with its `pipewire_buffer` for every path out of `add_buffer`, clear it in `remove_buffer` (the last point both halves are known), and null-check the consumers — killing the use-after-free that aborted the session on every capture renegotiation | **Yes** — a plain use-after-free in the PipeWire buffer lifecycle |
| `0008-steamcompmgr-honor-GAMESCOPE_NO_FOCUS-never-a-focus-.patch` | Honor `GAMESCOPE_NO_FOCUS` (set by hhd-ui and MangoHud, consumed by nobody): such windows are skipped by both focus-candidate collectors, so a mapped-but-unpainted overlay app can no longer win focus and turn the composite black. Compositing is untouched — only focus SELECTION is barred | **Yes** — the atom's setters already exist in the wild; some compositor has to keep the promise |
| `0009-pipewire-destroy-capture-textures-on-the-compositor-.patch` | Move capture-buffer destruction off the PipeWire thread: `remove_buffer`/stale-push queue the corpse (`bury_buffer`), steamcompmgr reaps on every vblank — including while the stream is paused, which is exactly the linger window. Without it, dropping the last `CVulkanTexture` ref on the PW thread races `vulkan_screenshot` on the same device and SIGSEGVs (NVIDIA `insertBarrier`), so a lingered display is dead and reconnect loses the session. Reported + written by luxus (punktfunk-overlay#9) | **Yes** — the race is upstream's `paint_pipewire` vs `destroy_buffer`; our patches only make the paint path heavier |
### Why the headless patch matters
@@ -68,6 +69,20 @@ variant of the same fault instead. Two traps when triaging it:
lands in a working-looking game mode at the wrong resolution and without any of these patches.
Read the banner in `~/.gamescope-stdout.log`, not the fact that a session exists.
### Why the teardown patch is what makes linger real
Patch 0007 keeps a session alive across renegotiations; patch 0009 keeps it alive across
*disconnects*. When the capture consumer leaves, `stream_handle_remove_buffer` used to destroy
idle buffers on the PipeWire thread — and `~CVulkanTexture` talks to the Vulkan device
(`vkDestroyImage`/`FreeMemory`/dmabuf fds) while steamcompmgr can still be inside
`vulkan_screenshot` on another buffer of the same 4-buffer pool. On NVIDIA that races to a SIGSEGV
in `CVulkanCmdBuffer::insertBarrier`, timed precisely at stream end — so the display the host
keeps lingering for a reconnect is already dead, and the "resumed" session silently becomes a
fresh compositor with the game lost. The journal signature: a linger line, then a coredump, then
`kept display was dead — recreating`. Found, fixed and proven live by luxus
([punktfunk-overlay#9](https://github.com/luxus/punktfunk-overlay/issues/9)) on 4K60 HDR + composited
cursor, the heaviest paint path we ship.
## Why the marker exists
punktfunk decides a session's shape **before** the virtual display exists: the bit depth at
@@ -87,6 +102,7 @@ The number is a **monotonic patch-set revision**, so one probe answers every cap
| `+pfhdr4` | …and `--pipewire-composite-external-overlay` |
| `+pfhdr5` | …and the PipeWire buffer use-after-free is fixed (no new capability) |
| `+pfhdr6` | …and `GAMESCOPE_NO_FOCUS` windows are never focus candidates (no new capability) |
| `+pfhdr7` | …and PipeWire teardown cannot SIGSEGV a lingering compositor (no new capability) |
Bump it whenever a patch adds or changes something the host must know about before it spawns.
+22 -5
View File
@@ -7,19 +7,24 @@
# had no packaged route at all, which is how a field report ended up on a stock gamescope streaming
# a session that told every game the display was 60 Hz.
#
# The binary is NOT built here; CI builds it once per Fedora major and caches it
# Nothing is BUILT here; CI builds once per Fedora major and caches the staged tree
# (.gitea/workflows/rpm.yml). See punktfunk-gamescope.spec's header for why repacking beats
# rebuilding.
#
# `--stage` is the DESTDIR that build-punktfunk-gamescope.sh wrote, not a single binary: that tree
# carries the compositor AND the WSI layer built beside it, and a game gets an HDR10 swapchain from
# that layer or from nowhere. Taking the whole tree rather than a file per artifact is deliberate —
# it is what stops the next file added to the package needing a new flag in four packaging scripts.
#
# Usage:
# bash packaging/gamescope/build-gamescope-rpm.sh \
# --binary gs-cache/punktfunk-gamescope \
# --stage gs-cache \
# [--version 3.16.25] [--release 1] [--outdir dist]
#
# Output: <outdir>/punktfunk-gamescope-<version>-<release>.<arch>.rpm
set -euo pipefail
BINARY=""
STAGE=""
# Default the version to the upstream gamescope the pinned revision describes as, suffixed with the
# patch-set revision — same shape as the Arch package's `pkgver`, so the two channels read alike.
VERSION=""
@@ -28,7 +33,7 @@ OUTDIR="dist"
while [ $# -gt 0 ]; do
case "$1" in
--binary) BINARY="${2:?--binary needs a path}"; shift 2 ;;
--stage) STAGE="${2:?--stage needs a path}"; shift 2 ;;
--version) VERSION="${2:?--version needs a value}"; shift 2 ;;
--release) RELEASE="${2:?--release needs a value}"; shift 2 ;;
--outdir) OUTDIR="${2:?--outdir needs a value}"; shift 2 ;;
@@ -36,8 +41,18 @@ while [ $# -gt 0 ]; do
esac
done
[ -n "$BINARY" ] || { echo "ERROR: --binary is required" >&2; exit 2; }
[ -n "$STAGE" ] || { echo "ERROR: --stage is required" >&2; exit 2; }
# The layout build-punktfunk-gamescope.sh writes under its --destdir/--prefix.
BINARY="$STAGE/usr/bin/punktfunk-gamescope"
LAYER_SO="$STAGE/usr/lib/punktfunk/libVkLayer_PUNKTFUNK_gamescope_wsi.so"
LAYER_JSON="$STAGE/usr/lib/punktfunk/vulkan/implicit_layer.d/punktfunk_gamescope_wsi.json"
[ -x "$BINARY" ] || { echo "ERROR: $BINARY is not an executable file" >&2; exit 1; }
# Hard, not best-effort. A package that carries the compositor without its layer looks completely
# healthy and then silently denies every game an HDR10 swapchain — the failure this whole change
# exists to end. Better to fail the packaging step than to ship that quietly again.
for f in "$LAYER_SO" "$LAYER_JSON"; do
[ -f "$f" ] || { echo "ERROR: $f missing from the stage — no game HDR without it" >&2; exit 1; }
done
ROOTDIR="$(cd "$(dirname "$0")/../.." && pwd)"
cd "$ROOTDIR"
@@ -66,6 +81,8 @@ TOP="$(mktemp -d)"
trap 'rm -rf "$TOP"' EXIT
mkdir -p "$TOP"/{SOURCES,SPECS,BUILD,BUILDROOT,RPMS,SRPMS}
install -m0755 "$BINARY" "$TOP/SOURCES/punktfunk-gamescope"
install -m0755 "$LAYER_SO" "$TOP/SOURCES/libVkLayer_PUNKTFUNK_gamescope_wsi.so"
install -m0644 "$LAYER_JSON" "$TOP/SOURCES/punktfunk_gamescope_wsi.json"
mkdir -p "$OUTDIR"
rpmbuild \
@@ -90,10 +90,14 @@ echo "==> configuring"
# test suite is not our job either way.
# -Denable_openvr_support the VR integration pulls the openvr submodule + its build for a
# code path a headless capture session never enters.
# -Denable_gamescope_wsi_layer the WSI layer is a SEPARATE artifact the distro's gamescope
# package already installs; ours must not collide with it.
# (The layer the nested games load is that one — it is version-
# independent of the compositor binary.)
# -Denable_gamescope_wsi_layer ON, and installed under our own name below. This used to be off,
# on the grounds that the distro's gamescope package already ships a
# layer and that the layer is "version-independent of the compositor
# binary". That second half is FALSE: the layer and the compositor
# speak `gamescope_swapchain` to each other, and when they disagree
# the compositor rejects the client's `swapchain_feedback` and every
# Vulkan client dies on a black screen. A compositor we ship needs
# the layer we built beside it.
#
# `force_fallback_for` includes **wlroots** on purpose, and it is load-bearing for a binary we
# SHIP: gamescope vendors a wlroots submodule, but meson prefers a system one when the build host
@@ -124,7 +128,7 @@ meson setup "$BUILD" "$SRCDIR" \
-Dpipewire=enabled \
-Denable_tests=false \
-Denable_openvr_support=false \
-Denable_gamescope_wsi_layer=false
-Denable_gamescope_wsi_layer=true
echo "==> building"
ninja -C "$BUILD" ${JOBS:+-j "$JOBS"}
@@ -149,6 +153,36 @@ DEST="${DESTDIR}${PREFIX}/bin/punktfunk-gamescope"
echo "==> installing $DEST"
install -Dm755 "$BIN" "$DEST"
# The WSI layer, under OUR name, at OUR path.
#
# A game nested under gamescope gets an HDR10 swapchain from this layer and from nothing else —
# gamescope advertises no runtime colour-management protocol a Mesa/NVIDIA WSI could negotiate
# through — so a compositor shipped WITHOUT a matching layer simply cannot do HDR for games. Built
# from this same tree at this same rev, so the two can never drift apart; that is the whole point,
# and it is what makes the host's old "compare version triples and hope" check unnecessary.
#
# It must not collide with the distro's layer and must be switchable independently of it, so the
# generated manifest is rewritten to carry our layer name, our library path and our own
# enable/disable variables. The Vulkan loader keys implicit layers on that NAME, so with a distinct
# one both layers can sit installed side by side and the host picks per session.
#
# python3 rather than sed because meson is itself a Python program — it is guaranteed present on any
# host that got this far — and a JSON edit belongs in a JSON parser.
LAYER_SO=$(find "$BUILD" -type f -name 'libVkLayer_*gamescope_wsi*.so' | head -1)
LAYER_SRC_JSON=$(find "$BUILD" -type f -name '*gamescope_wsi*.json' | head -1)
[ -n "$LAYER_SO" ] && [ -n "$LAYER_SRC_JSON" ] || {
echo "the WSI layer did not build (.so=${LAYER_SO:-none} .json=${LAYER_SRC_JSON:-none}) — without" >&2
echo "it no game in a punktfunk gamescope session can get an HDR10 swapchain" >&2
exit 1
}
LAYER_LIB_PATH="${PREFIX}/lib/punktfunk/libVkLayer_PUNKTFUNK_gamescope_wsi.so"
LAYER_DEST_JSON="${DESTDIR}${PREFIX}/lib/punktfunk/vulkan/implicit_layer.d/punktfunk_gamescope_wsi.json"
echo "==> installing ${DESTDIR}${LAYER_LIB_PATH}"
install -Dm755 "$LAYER_SO" "${DESTDIR}${LAYER_LIB_PATH}"
install -d "$(dirname "$LAYER_DEST_JSON")"
python3 "$(dirname "$0")/rewrite-wsi-layer-manifest.py" \
"$LAYER_SRC_JSON" "$LAYER_DEST_JSON" "$LAYER_LIB_PATH"
if [ "$SETCAP" = 1 ] && command -v setcap >/dev/null; then
# gamescope raises its own scheduling priority; without CAP_SYS_NICE it still runs, just noisier
# and with worse frame pacing. Best-effort — needs root, and a package sets it declaratively.
@@ -0,0 +1,159 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: luxus <luxus@users.noreply.github.com>
Date: Thu, 13 Aug 2026 23:15:48 +0200
Subject: [PATCH] pipewire: destroy capture textures on the compositor thread
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
When the capture consumer leaves, PipeWire remove_buffer destroys idle
buffers on the PW thread. CVulkanTexture's destructor talks to the Vulkan
device (DestroyImage / FreeMemory / close dmabuf fds). steamcompmgr may
still be inside vulkan_screenshot on another buffer of the same device.
That race SIGSEGVs in CVulkanCmdBuffer::insertBarrier / libnvidia-eglcore
and kills the compositor. A lingering gamescope session then cannot be
reused — the host has to spawn a new one.
Queue those corpses and delete them on the steamcompmgr vblank, including
when the stream is only paused (linger: no consumer, compositor stays up).
The same race exists on the stale-push path (dispatch_nudge destroying a
buffer whose pw_buffer vanished while it was copying), so that call is
buried too. Corpses queued when the compositor exits are reclaimed by the
kernel, same as patch 0006's deliberate leak.
Reported, written and proven live by luxus (punktfunk-overlay#9): four
coredumps on an NVIDIA host, all at stream end / linger, three in
paint_pipewire → vulkan_screenshot → insertBarrier with a concurrent
destroy_buffer → ~CVulkanTexture on the PipeWire thread; after this patch
a disconnect/reconnect reuses the lingered session.
Not addressed here: stream_handle_add_buffer's `error:` path still deletes
on the PW thread. By the later `goto error`s a texture may be attached, so
the same race is reachable in theory — but only when an add FAILS mid-
renegotiation, which none of the field coredumps show. Left as-is to stay
byte-identical with the change that was proven on-glass.
punktfunk: the banner moves to +pfhdr7. No new capability — but a build
whose linger can die of its own capture teardown is indistinguishable from
one that cannot except by this marker, and "reconnect lost my game" is
exactly the field report that needs that read (same rule as pfhdr5/6).
Upstream: yes — the race is upstream's paint_pipewire vs destroy_buffer;
our HDR/cursor patches only make the paint path heavier.
---
src/meson.build | 3 ++-
src/pipewire.cpp | 28 ++++++++++++++++++++++++++--
src/pipewire.hpp | 3 +++
src/steamcompmgr.cpp | 10 ++++++++--
4 files changed, 39 insertions(+), 5 deletions(-)
diff --git a/src/meson.build b/src/meson.build
index acfcaea..fe854af 100644
--- a/src/meson.build
+++ b/src/meson.build
@@ -186,7 +186,8 @@ vcs_tag = run_command(vcs_tag_cmd, check: false).stdout().strip()
# +pfhdr4 — …and `--pipewire-composite-external-overlay`
# +pfhdr5 — …and the PipeWire buffer use-after-free is fixed (no new capability)
# +pfhdr6 — …and GAMESCOPE_NO_FOCUS windows are never focus candidates (no new capability)
-version_tag = vcs_tag + '+pfhdr6' + ' (' + compiler_name + ' ' + compiler_version + ')'
+# +pfhdr7 — …and PipeWire teardown cannot SIGSEGV a lingering compositor (no new capability)
+version_tag = vcs_tag + '+pfhdr7' + ' (' + compiler_name + ' ' + compiler_version + ')'
gamescope_version_conf = configuration_data()
gamescope_version_conf.set('VCS_TAG', version_tag)
diff --git a/src/pipewire.cpp b/src/pipewire.cpp
index c683b3a..3c727e9 100644
--- a/src/pipewire.cpp
+++ b/src/pipewire.cpp
@@ -7,6 +7,7 @@
#include <unistd.h>
#include <atomic>
+#include <mutex>
#include <thread>
#include <vector>
@@ -103,6 +104,29 @@ static void destroy_buffer(struct pipewire_buffer *buffer) {
delete buffer;
}
+// The PipeWire thread must not destroy CVulkanTextures: steamcompmgr may be
+// inside vulkan_screenshot on another buffer of the same device. Queue the
+// corpse and let steamcompmgr delete it on the next vblank.
+static std::mutex s_deadBuffersMutex;
+static std::vector<struct pipewire_buffer *> s_deadBuffers;
+
+static void bury_buffer(struct pipewire_buffer *buffer)
+{
+ std::lock_guard<std::mutex> lock(s_deadBuffersMutex);
+ s_deadBuffers.push_back(buffer);
+}
+
+void pipewire_reap_dead_buffers(void)
+{
+ std::vector<struct pipewire_buffer *> dead;
+ {
+ std::lock_guard<std::mutex> lock(s_deadBuffersMutex);
+ dead.swap(s_deadBuffers);
+ }
+ for (struct pipewire_buffer *buffer : dead)
+ destroy_buffer(buffer);
+}
+
void pipewire_destroy_buffer(struct pipewire_buffer *buffer)
{
destroy_buffer(buffer);
@@ -384,7 +408,7 @@ static void dispatch_nudge(struct pipewire_state *state, int fd)
pwr_log.errorf("pw_stream_queue_buffer failed");
}
} else {
- destroy_buffer(buffer);
+ bury_buffer(buffer);
}
}
}
@@ -694,7 +718,7 @@ static void stream_handle_remove_buffer(void *data, struct pw_buffer *pw_buffer)
buffer->buffer = nullptr;
if (!buffer->copying) {
- destroy_buffer(buffer);
+ bury_buffer(buffer);
}
}
diff --git a/src/pipewire.hpp b/src/pipewire.hpp
index b4d7e29..d0b510c 100644
--- a/src/pipewire.hpp
+++ b/src/pipewire.hpp
@@ -60,5 +60,8 @@ uint32_t get_pipewire_stream_node_id(void);
struct pipewire_buffer *dequeue_pipewire_buffer(void);
bool pipewire_is_streaming();
void pipewire_destroy_buffer(struct pipewire_buffer *buffer);
+// Destroy textures queued by the PipeWire thread. Must run on steamcompmgr —
+// CVulkanTexture's dtor talks to the Vulkan device.
+void pipewire_reap_dead_buffers(void);
void push_pipewire_buffer(struct pipewire_buffer *buffer);
void nudge_pipewire(void);
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index 14596ae..932316f 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -9321,8 +9321,14 @@ steamcompmgr_main(int argc, char **argv)
#if HAVE_PIPEWIRE
// Drive on vblank, not the timer: under VRR the timer starves (page flips re-arm it).
- if ( vblank && pipewire_is_streaming() )
- paint_pipewire();
+ // Reap even when the consumer is gone: linger keeps us alive, and textures
+ // queued by remove_buffer must die on this thread, not PipeWire's.
+ if ( vblank )
+ {
+ pipewire_reap_dead_buffers();
+ if ( pipewire_is_streaming() )
+ paint_pipewire();
+ }
#endif
update_vrr_atoms(root_ctx, false, &flush_root);
+33 -2
View File
@@ -9,7 +9,7 @@
# The counterpart for Arch is packaging/gamescope/PKGBUILD, which DOES build from source, because
# makepkg fetches sources by design and the AUR-style recipe is what an Arch user expects.
#
# Usage: bash packaging/gamescope/build-gamescope-rpm.sh --binary <path-to-punktfunk-gamescope>
# Usage: bash packaging/gamescope/build-gamescope-rpm.sh --stage <destdir-the-build-script-wrote>
Name: punktfunk-gamescope
Version: %{pf_version}
Release: %{pf_release}%{?dist}
@@ -19,6 +19,12 @@ Summary: gamescope with punktfunk's PipeWire capture patches (HDR, cursor
License: BSD-2-Clause
URL: https://git.unom.io/unom/punktfunk
Source0: punktfunk-gamescope
# The Vulkan WSI layer built from the same tree at the same rev as the compositor above. A game
# nested under gamescope gets its HDR10 swapchain from this layer and from nothing else, and a layer
# built for a DIFFERENT gamescope kills every Vulkan client — so the two ship together or the
# package is a trap.
Source1: libVkLayer_PUNKTFUNK_gamescope_wsi.so
Source2: punktfunk_gamescope_wsi.json
# Not `Provides: gamescope` and not `Conflicts:` either — this ships a differently-named binary and
# is designed to coexist. A box's Game Mode session keeps running the distro's gamescope; only the
@@ -49,7 +55,10 @@ packaging/gamescope/patches:
* --pipewire-composite-external-overlay: paint the mangoapp performance overlay into the capture
stream, so the fps/stats readout is visible to someone watching remotely.
Installed as /usr/bin/punktfunk-gamescope. Your system gamescope is untouched.
Installed as /usr/bin/punktfunk-gamescope, with its matching Vulkan WSI layer under
/usr/lib/punktfunk. The layer carries its own name and its own enable variable, so it sits beside
the one your gamescope package installs rather than replacing it, and only sessions punktfunk-host
starts switch to it. Your system gamescope is untouched.
%prep
# Nothing to unpack: Source0 IS the binary.
@@ -60,6 +69,14 @@ Installed as /usr/bin/punktfunk-gamescope. Your system gamescope is untouched.
%install
install -Dm0755 %{SOURCE0} %{buildroot}%{_bindir}/punktfunk-gamescope
# /usr/lib, spelled literally rather than %{_libdir}, which is /usr/lib64 here. The layer's manifest
# carries an ABSOLUTE library_path baked in at build time (/usr/lib/punktfunk/...), so this path and
# that string have to agree or the loader finds a manifest pointing at nothing. Nothing links this
# .so by soname — the Vulkan loader dlopens it by that absolute path — so there is no multilib
# question to answer, and a private vendor directory is where it belongs.
install -Dm0755 %{SOURCE1} %{buildroot}/usr/lib/punktfunk/libVkLayer_PUNKTFUNK_gamescope_wsi.so
install -Dm0644 %{SOURCE2} %{buildroot}/usr/lib/punktfunk/vulkan/implicit_layer.d/punktfunk_gamescope_wsi.json
%check
# The marker is the host's entire capability probe (`gamescope_patch_level()`): a binary that lost
# the patches would install fine and then silently stream SDR with no cursor. Refuse to package it.
@@ -71,8 +88,22 @@ install -Dm0755 %{SOURCE0} %{buildroot}%{_bindir}/punktfunk-gamescope
exit 1
}
# The manifest's absolute library_path must name the file we actually installed. Getting this wrong
# (%{_libdir} on a multilib box, a renamed .so) produces a package that installs cleanly and then
# does nothing at all — the loader reads a manifest, finds no library, and moves on in silence.
LAYER_LIB="$(grep -o '"library_path"[[:space:]]*:[[:space:]]*"[^"]*"' \
%{buildroot}/usr/lib/punktfunk/vulkan/implicit_layer.d/punktfunk_gamescope_wsi.json \
| sed 's/.*"\(\/[^"]*\)".*/\1/')"
[ -f "%{buildroot}${LAYER_LIB}" ] || {
echo "punktfunk-gamescope: the layer manifest points at ${LAYER_LIB}, which this package does" >&2
echo " not install games would silently get no HDR swapchain" >&2
exit 1
}
%files
%{_bindir}/punktfunk-gamescope
/usr/lib/punktfunk/libVkLayer_PUNKTFUNK_gamescope_wsi.so
/usr/lib/punktfunk/vulkan/implicit_layer.d/punktfunk_gamescope_wsi.json
%changelog
# Generated per build; see the git history for the patch set's own changes.
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""Rewrite gamescope's generated Vulkan layer manifest so OUR copy of the layer can be installed
beside the distro's instead of colliding with it.
A game nested under gamescope gets its HDR10 swapchain from the FROG WSI layer and from nothing
else, and that layer speaks `gamescope_swapchain` to the compositor: a layer built for a DIFFERENT
gamescope makes the compositor reject the client's swapchain_feedback, and every Vulkan client dies
on a black screen with sound and input and no error. So a compositor we ship needs the layer we
built beside it which means two gamescope WSI layers on one box.
Three fields make that safe, and the loader is why:
* `name` the Vulkan loader deduplicates implicit layers by name, and with both called
VK_LAYER_FROG_gamescope_wsi which one wins is unspecified. A distinct name is what lets both sit
installed at once.
* `library_path` made absolute, so resolution never depends on where the loader found the
manifest.
* `enable_environment` / `disable_environment` our own gates, so the host can switch ours ON and
the distro's OFF in the same session. Sharing ENABLE_GAMESCOPE_WSI would make that impossible.
Everything else is passed through untouched, `functions` above all: it names the layer's entry
points, and a manifest with the wrong ones is a layer that silently never loads.
Used by build-punktfunk-gamescope.sh (FHS packaging) and packaging/nix/gamescope.nix (the Nix store),
which is the point of it being a file rather than a heredoc the two must not drift.
Usage: rewrite-wsi-layer-manifest.py <src.json> <dst.json> <installed-library-path>
"""
import json
import sys
LAYER_NAME = "VK_LAYER_PUNKTFUNK_gamescope_wsi"
ENABLE_VAR = "PUNKTFUNK_GAMESCOPE_WSI"
DISABLE_VAR = "PUNKTFUNK_GAMESCOPE_WSI_DISABLE"
def main(argv):
if len(argv) != 4:
print(__doc__, file=sys.stderr)
return 2
src, dst, lib = argv[1:4]
with open(src) as f:
manifest = json.load(f)
layer = manifest.get("layer")
if not isinstance(layer, dict):
print(f"{src}: no 'layer' object — not a Vulkan layer manifest", file=sys.stderr)
return 1
# A manifest that never named the entry points would produce a layer that loads and does
# nothing, which is indistinguishable on a running box from "this GPU has no HDR".
if not layer.get("functions") and not layer.get("library_path"):
print(f"{src}: neither 'functions' nor 'library_path' — refusing to rewrite", file=sys.stderr)
return 1
layer["name"] = LAYER_NAME
layer["library_path"] = lib
layer["enable_environment"] = {ENABLE_VAR: "1"}
layer["disable_environment"] = {DISABLE_VAR: "1"}
with open(dst, "w") as f:
json.dump(manifest, f, indent=2)
f.write("\n")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))

Some files were not shown because too many files have changed in this diff Show More