Skip to content

armgit / Piik

Public Imported from GitHub
0

Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。

chore: merge main into spike/hybrid-warm-fallback

AAAa75c755d7ca5
diff --cc docs/README.md
index a4051d6f,87055c58..f3fb6f2c
--- a/docs/README.md
+++ b/docs/README.md
@@@ -16,6 -16,6 +16,6 @@@
- [ADR-0001](./adr/0001-p2p-first-media-topology.md): accepted P2P-first media topology and its consequences.
- [ADR-0002](./adr/0002-persistent-protected-rooms.md): optional SQLite persistence, protected sequential room IDs, and room lifecycle.
- [ADR-0004](./adr/0004-peer-assisted-media-experiment.md): proposed, experiment-only standard-WebRTC peer-assisted spike with hard fanout and failure gates.
- - [ADR-0005](./adr/0005-automatic-hybrid-media-routing.md): proposed automatic P2P/peer/SFU routing, token-free standby prewarm, transitions, and hard host-edge budget.
-- [ADR-0005](./adr/0005-automatic-hybrid-media-routing.md): proposed, default-off automatic P2P/peer/SFU preparation, commit, failback, and rollback with a hard host-edge budget.
++- [ADR-0005](./adr/0005-automatic-hybrid-media-routing.md): proposed, default-off automatic P2P/peer/SFU preparation, token-free standby prewarm, commit, failback, and rollback with a hard host-edge budget.
Documentation and project memory are part of the product source of truth. Update them in the same change that alters the corresponding requirement or architecture.
diff --cc docs/project-memory.md
index a235bceb,c5630664..b132677d
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@@ -6,45 -6,46 +6,47 @@@ Last updated: 2026-08-1
- Build Discord/KOOK/Oopz/TeamSpeak-like low-latency game screen sharing for one broadcaster and a small trusted friend group. Public or large broadcasts belong on OBS/Twitch-class services.
- Viewers should join from a normal desktop or mobile browser. A packaged/native sender is a planned later stage for shared encoding and may also improve capture and audio without changing the Web viewer requirement.
--- Use a Photon-style central rendezvous service for access, rooms, signaling, deterministic topology, STUN, TURN fallback, and observability while clients carry media whenever practical.
++- Use a small central service for access, rooms, signaling, deterministic topology, STUN/TURN, and observability while clients carry media whenever practical.
- Server bandwidth cost is a primary constraint. The ordered media ladder is direct P2P, then measured peer assistance, then an enabled user-operated or central SFU fallback. Route selection and failure recovery must be automatic and viewer-transparent, while remaining deterministic, budget-driven, and small enough to reason about. This has always been the product intent; earlier text prohibiting silent migration was an incorrect interpretation and is superseded.
- Host and relay-capable endpoints each have a target budget of at most two downstream media edges. Every P2P edge independently uses direct ICE or authenticated TURN fallback. With two edges, the long-term native/encoded-object path should reuse one compatible encoded output; the current browser experiment is stricter at one viewer child and re-encodes.
- Packet or layer striping across two peer trees is a recorded candidate for reducing endpoint upload toward one full-stream bitrate. It requires a separate bounded experiment for multi-parent assembly, loss recovery, synchronization, churn, and sub-second latency; it is not part of the current full-stream two-chain implementation.
--- Browser convenience does not override reachability or honest resource accounting. Shared encoding reduces compute, not each viewer's last-hop copy.
++- Shared encoding reduces compute, not each viewer's last-hop copy.
- Durable decisions, current snapshots, research, code, `AGENTS.md`, and `.codex/` belong in Git. Memory and status are rewritten in place rather than kept as transcripts.
- Research current official sources and established implementations before material work. Apply Occam's razor and reject speculative protocols, services, scoring, and scale.
## Current Recommendation
--- Keep the deployed Windows Chrome/Edge broadcaster and responsive Web viewer as the measurement baseline. Validate current Android Chrome and iOS Safari as leaves.
- - Use direct host P2P for one or two viewers. Draft ADR-0004 and Draft PR #13 own the default-off experiment for later viewers: two sticky deterministic chains, host capacity two, viewer capacity one, no proactive rebalance or composite score, and no more than eight viewers when `PEER_ASSISTED_MEDIA=true`.
++- Keep desktop Chrome/Edge and the responsive Web viewer as the baseline. Validate Android Chrome and iOS Safari as leaves.
+ - Use direct host P2P for one or two viewers. `main` carries ADR-0004's default-off experiment for later viewers: two sticky deterministic chains, host capacity two, viewer capacity one, no proactive rebalance or composite score, and no more than eight viewers when `PEER_ASSISTED_MEDIA=true`.
- Standard browser relays resend remote `MediaStreamTrack` values and therefore decode and re-encode at every hop. Browser WebRTC does not guarantee one shared encoder across peer connections; measure this cost rather than hiding it.
--- Keep the full-stream browser experiment bounded. If it needs a different media plane, mark that experiment failed and evaluate native RTP relay, encoded-object striping, SVC, or FEC in separate measured spikes rather than hiding the change inside ADR-0004.
++- Keep the browser experiment bounded. Evaluate native RTP relay, encoded-object striping, SVC, or FEC only in separate measured spikes.
- Plan a separate native-sender ADR for TeamSpeak-style shared encoding regardless of the browser relay result. One compatible encoded output may feed at most two standard WebRTC packetizers to reduce host encode work, but each edge still consumes upload bandwidth. This work is not part of the current Draft and cannot rescue another failed browser-relay gate.
- - Keep user-operated mini-SFU deployment and central single-node SFU Draft PR #12 as optional infrastructure. When configured, the route controller may select them automatically as the last fallback; their fanout egress belongs to their operator and does not justify Redis or multi-node infrastructure.
- - Keep automatic routing behind ADR-0005: discrete failures drive peer recovery and optional SFU fallback, host media uses break-before-make and never exceeds two active edges, and a binary per-session relay capability keeps detected mobile/iPad clients as leaves. Token-free authenticated standby prewarm now passes the local sub-second gate; public transport and load gates remain.
+ - Keep user-operated or central single-node SFU capacity optional. When configured, `main`'s #17 route controller may select it only as the final fallback; its fanout egress belongs to its operator and does not justify Redis or multi-node infrastructure. Closed PR #12's explicit whole-room SFU mode is superseded, not a current option.
-- Keep `main`'s automatic routing default-off behind ADR-0005: discrete failures drive peer recovery and optional SFU fallback, host media uses break-before-make and never exceeds two active edges, and a binary per-session relay capability keeps detected mobile/iPad clients as leaves. Corrected local recovery works but misses the sub-second gate.
++- Keep `main`'s automatic routing default-off behind ADR-0005: discrete failures drive peer recovery and optional SFU fallback, host media uses break-before-make and never exceeds two active edges, and a binary per-session relay capability keeps detected mobile/iPad clients as leaves. Draft PR #20's token-free standby prewarm passes the local sub-second gate; public transport and load gates remain.
- Prefer direct UDP, then TURN/UDP, with TURN/TCP as the required non-UDP fallback. Optional TURN/TLS uses TCP 5349 by default; TCP 443 needs a dedicated address or validated L4/SNI routing.
- - Treat 3/5/8 Mbps profiles as ceilings. Production users report severe degradation across all three; run one controlled 1/2/3-viewer capture before changing constants, then A/B clarity-first against `balanced`. Do not hide actual limits or add an automatic score/controller without evidence.
+ - Treat every quality setting as a ceiling. The current Draft defaults to clarity-first and adds bounded manual controls plus sender readback; production remains `balanced`, and its reported degradation is still unclassified. Run the 1/2/3-viewer plus TURN matrix before changing ceilings or adding any automatic controller.
- Do not add custom scene detection or dynamic-FPS control until WebRTC statistics and host resource measurements prove a material gap. Keep browser codec order until target hardware proves a more efficient common codec.
- Keep room policy deployment-driven. Public and password-only deployments use random temporary rooms. A site password plus SQLite path enables sequential persistent rooms; stopping sharing leaves the room and viewer link available.
## Current Implementation
--- The repository is one npm package using Node.js 24, React, TypeScript, Vite, native WebRTC, `ws`, Zod, Vitest, and separate coturn. LAN/container listening defaults to all interfaces; bare-metal reverse-proxy deployment binds loopback and exposes `/healthz`.
++- The repository is one npm package using Node.js 24, React, TypeScript, Vite, native WebRTC, `ws`, Zod, Vitest, and separate coturn.
- Production commit `5b2fb005f6f7` is deployed at `https://share.bonfire.icu`. It provides live source and quality changes without rebuilding healthy peers, video-only pause, clearer connection states, and the standard one-host-`RTCPeerConnection`-per-viewer path. Production therefore still exceeds the two-edge host target above two viewers.
- Production supports the three profiles with `contentHint = "motion"` and `degradationPreference = "balanced"`; its real live quality/pause cycle remains unverified.
-- `main` includes PR #19's equal idle-stage share/join actions and default-closed technical details. Draft PR #21 keeps advanced quality in the common control area and SFU initial/update/replacement warnings visible. Neither change is deployed.
++- `main` includes PR #19's equal idle-stage share/join actions and default-closed technical details plus PR #21's bounded advanced quality settings and visible SFU sender warnings. These changes are not deployed.
- Access stays small: optional `ACCESS_PASSWORD`, a 12-hour stateless HMAC HttpOnly `SameSite=Strict` cookie, internal host token, role-bound signaling, Origin/payload checks, and no accounts, JWTs, or session map.
- With `ROOM_DATABASE_PATH` and the site password, built-in SQLite stores only auto-incremented room ID and host-token digest. Links persist and stopping sharing leaves viewers waiting. Production room ID `1` survived the `5b2fb005f6f7` deployment restart. Without the path, rooms remain random and temporary; public mode cannot use sequential rooms.
- Production runs behind nginx with Node.js 24.19.0. Authenticated coturn 4.17.2 at `turn.bonfire.icu:3478` has verified public STUN, TURN/UDP, TURN/TCP, and relay-only traffic. TURN/TLS is intentionally disabled.
- - Draft PR #13 contains deterministic server/client peer-assisted assignment, standard remote-track relay, and synchronized 1080p60/1080p30/720p30 room profiles. It defaults off, is capped at eight viewers, re-encodes at every relay, and is neither merged nor deployed. Native shared encoding and custom encoded browser transport are not implemented.
- - Draft PR #17 stacks on PR #13: peer recovery precedes an allowlisted SFU root; revisioned prepare/commit/abort is session-bound; active SFU failure gets one token refresh, then fails back and disables SFU for that share. Draft PR #20 advertises a non-secret standby URL only when configured and performs one token-free SDK import plus DNS/TLS/HTTP warmup per client; it creates no participant/media edge, and LiveKit remains dormant when unconfigured.
+ - `main` contains deterministic peer-assisted assignment and standard remote-track relay. It defaults off, is capped at eight viewers, re-encodes at every relay, and is not deployed. Native shared encoding and custom encoded browser transport are not implemented.
+ - `main` also contains ADR-0005's default-off route controller: peer recovery precedes an allowlisted SFU root; revisioned prepare/commit/abort is session-bound; active SFU failure gets one token refresh, then fails back for that share. LiveKit is dormant when unconfigured.
-- Corrected Chrome 151/LiveKit 1.13.5 smoke physically failed one leaf through peer recovery/reparent and two-root SFU. Frames resumed; 472 hook-assisted 25 ms samples saw host edge peak two. Failure-to-render took 2.257 seconds. It is localhost, headless, synthetic 720p30 video only.
++- Draft PR #20 advertises a non-secret standby URL only when fallback is configured and performs one token-free SDK import plus DNS/TLS/HTTP warmup per client; it creates no participant or media edge and changes nothing when unconfigured.
+- Corrected Chrome 151/LiveKit 1.13.5 same-leaf/two-root cold/standby A/B reduced failure-to-active from 1.481 seconds to 200 ms and failure-to-render from 2.257 seconds to 319.7 ms. The leaf decoded/rendered 31 new frames and 25 ms sampling kept host edge peak two. It is localhost, headless, synthetic 720p30 video only; the roughly 86% result combines SDK download/parse and network prewarm and must not be extrapolated to public networks.
- Draft PR #16 (`5b09f0a`) proves one Pion RTP write fans equivalent data to two transports with independent SSRCs. It has no encoder and proves neither physical shared encode nor browser readiness.
- Chrome 151 short synthetic `1/3/5/8` runs kept host edges at two, relay edges at one, and all viewers decoding; a three-viewer relay close recovered in 5.32 seconds. This proves topology/control only, not quality, load, endurance, or silent partitions.
- - The peer-assisted authenticated snapshot and host-only update synchronize one bounded, non-persistent room profile. Online viewers receive changes; `ViewerRelay` uses the latest desired profile for current and future children, while `HostPeer` serializes sender setup, stream replacement, and last-wins profile updates. The ordinary P2P wire is unchanged. Real 1/3/5/8 quality, resource, and latency measurements remain pending.
- - Chromium 151 kept relay/sender/signaling generations through 8 Mbps/60, 5 Mbps/30, and 3 Mbps/30 ceilings while the leaf decoded. Synthetic 640x360/30 proves control propagation, not full-resolution load.
+ - The current quality stack uses one strict, non-persistent `QualitySettings` value: 720p/1080p/1440p, integer 15-60 fps, 2-12 Mbps, and clarity/balanced/fluid preference. Host-only updates are last-wins for current/future relays and optional SFU; ordinary P2P wire stays unchanged. Initial, replaced, and updated senders share serialized configure/readback; rejection, rewriting, or three identical native limitation samples produce one visible warning without automatic action. Successful replacement rollback retains the original failure warning.
+ - Chrome 151 with one host, three viewers, and synthetic 720p30 passed balanced and clarity propagation to every participant. Every baseline active video sender showed matching preference readback, peer fingerprints stayed stable, and every viewer decoded and rendered new frames after each change; host fanout was two and relay fanout one. This is control evidence, not a quality, load, public-network, or endurance claim.
- Per-frame encode/decode diagnostics use adjacent non-overlapping `getStats()` deltas rather than connection-lifetime averages; first, empty, changed-stream, and reset intervals remain unknown and rebase.
- - Draft PR #17 passes CI. Draft PR #20 passes CI, type checking, 20 Vitest files/259 tests, both builds, dependency audit, and repository hygiene. Production separately passed 108 tests and deployment checks.
-- The review revision passes repository hygiene, type checking, 21 Vitest files/268 tests, both builds, and the Chrome control smoke. Production separately passed 108 tests and deployment checks.
++- The integrated PR #20 revision passes repository hygiene, type checking, 22 Vitest files/274 tests, both builds, and the existing Chrome evidence. Production separately passed 108 tests and deployment checks.
## Provisional Quality Targets
diff --cc docs/research/low-server-media-routes.md
index 3104ee58,52778377..adaa12e2
--- a/docs/research/low-server-media-routes.md
+++ b/docs/research/low-server-media-routes.md
@@@ -29,40 -29,10 +29,40 @@@ The smallest current plan is
disappear.
Any browser-spike failure other than isolated relay re-encoding closes that
- browser-relay route. It does not cancel the separate native sender plan. Draft
- SFU PR #12 remains unmerged and undeployed. ADR-0005 now owns a separate Draft
- implementation of the automatic cross-mode controller; it is also undeployed
- and has passed a corrected localhost Chrome/LiveKit functional smoke. Public
+ browser-relay route. It does not cancel the separate native sender plan. Closed
+ PR #12's explicit whole-room SFU mode is superseded. ADR-0005 and merged PR #17
-own the default-off automatic cross-mode controller; it remains undeployed and
-has not passed real LiveKit/browser network validation.
++own the default-off automatic cross-mode controller; it remains undeployed.
++Corrected localhost Chrome/LiveKit functional recovery passed, while public
+transport, quality, load, and browser validation remain open.
+
+## Token-Free SFU Standby Prewarm
+
+The pinned Apache-2.0 `livekit-client` 2.22.0 source documents and implements
+`Room.prepareConnection(url)` as DNS/TLS preparation. For a self-hosted URL and
+no token, it converts `ws(s)` to `http(s)`, sends one `HEAD`, and catches errors.
+It does not call `connect`; therefore it does not join a room, acquire a
+participant identity, publish, subscribe, or create a media edge. A token is
+only relevant to LiveKit Cloud region selection, which this self-hosted spike
+does not use.
+
+The smallest integration is to advertise the non-secret LiveKit origin only in
+the authoritative peer-assisted authentication snapshot when the complete
+fallback tuple exists. Each client dynamically imports the already-pinned SDK
+once and attempts the URL once. Newer authentication invalidates a stale task
+before the import completes; a failed HEAD is silent and is not retried. No JWT
+is issued until the existing route controller actually selects SFU fallback.
+With no fallback configuration, the field, import, HEAD, and behavior are all
+absent.
+
+A bounded Chrome 151/LiveKit 1.13.5 localhost/headless/video-only same-leaf A/B
+reduced failure report to SFU active from 1.481 seconds to 200 ms and to a
+rendered frame from 2.257 seconds to 319.7 ms. It retained the fixed direct ->
+peer -> SFU order, two allowlisted roots, and host media-edge peak two. The
+standby had already downloaded/parsed the SDK and made its token-free network
+prewarm, without a participant or media edge, so the A/B does not isolate those
+effects. Its roughly 86% result must not be extrapolated to a public network;
+internet DNS/TLS reuse, RTT/loss, audio, transport fallback, and browser variance
+still require measurement.
## Traffic Conservation And The Impossible Triangle
diff --cc docs/status.md
index 782bbc78,1f5d07bc..54bde926
--- a/docs/status.md
+++ b/docs/status.md
@@@ -8,11 -8,10 +8,11 @@@ The WebRTC proof of concept at `https:/
`5b2fb005f6f7` with live quality/source changes, video pause, protected SQLite
rooms, sequential IDs, and reusable links.
- Production still creates one host peer connection per viewer. Draft PR #13 adds
- default-off two-chain peer assistance with per-hop re-encoding; ADR-0005 adds
- optional automatic SFU fallback in Draft PR #17. Corrected recovery passes the
- local sub-second gate with token-free standby prewarm in Draft PR #20; neither
- PR is merged or deployed.
+ Production still creates one host peer connection per viewer. `main` now
+ contains the default-off two-chain peer assistance, optional automatic SFU
-fallback, and simplified entry/diagnostics from merged PRs #13, #17, and #19;
-none is deployed. Corrected route recovery works but misses its sub-second gate.
++fallback, simplified entry/diagnostics, and bounded quality settings from merged
++PRs #13, #17, #19, and #21; none is deployed. Draft PR #20's token-free standby
++prewarm passes the local sub-second recovery gate.
## Current Snapshot
@@@ -21,37 -20,39 +21,38 @@@
- Without `ROOM_DATABASE_PATH`, rooms are random and temporary. With both the database path and site password, room IDs start at `1`, links persist, and stopping a share leaves viewers waiting. SQLite stores only room ID and host-token digest.
- Direct ICE is preferred independently per media edge. Authenticated TURN/UDP and TURN/TCP are required production fallbacks; TURN/TLS is optional.
- Hidden routing is `direct P2P -> peer-assisted -> optional SFU`. After bounded ICE recovery it tries peer reparenting before an allowlisted SFU root. Session-bound revisions prepare, commit break-before-make under two host edges, or abort. Active SFU gets one token refresh, then fails back for that share.
+- Complete fallback configuration adds a non-secret standby URL to peer-assisted authentication. Host and viewers import the SDK and make one token-free DNS/TLS warmup; no configuration means no field, import, request, participant, or media edge.
- A viewer starts as a leaf each session and explicitly advertises relay capacity zero or one; the Web client reports detected mobile/iPad clients as zero and desktop-class browsers as one. Withdrawal stops future assignment without moving a healthy edge. Browser relays remain one-child; the host remains two-child.
- - Peer-assisted profile state is bounded, memory-only, absent from ordinary P2P wire, and applied to current and future relay children.
-- Draft PR #21 uses one strict, memory-only quality setting for current/future relays and optional SFU; ordinary P2P wire stays unchanged. It defaults clarity-first and exposes bounded manual ceilings.
-- It builds on `main`'s equal idle-stage share/join actions and default-closed technical details; SFU initial/update/replacement warnings remain visible. It is not deployed.
++- `main` uses one strict, memory-only quality setting for current/future relays and optional SFU; ordinary P2P wire stays unchanged. It defaults clarity-first, exposes bounded manual ceilings, and keeps SFU initial/update/replacement warnings visible.
++- `main` also carries equal idle-stage share/join actions and default-closed technical details. These changes are not deployed.
## Verified Evidence
- Production passed 108 tests, both builds, public HTTPS/access/TURN checks, clean activation, and a database restart retaining room `1`.
- - Draft PR #13 now provides `npm run benchmark:peer-assisted`; the full check passes type checking, 13 Vitest files with 152 tests, and both production builds.
-- PR #13 introduced `npm run benchmark:peer-assisted`; its 152-test baseline and both builds passed.
- A short Chrome 151 synthetic `1/3/5/8` benchmark passed every topology check: host active edges peaked at two, relay edges at one, every viewer kept increasing decoded frames through the measurement window, and the slowest first decoded frame was about 1.05 seconds. Closing a first-level relay in the three-viewer run recovered in about 5.32 seconds without exceeding host fanout two.
- - A separate live-profile smoke kept the same relay peer, sender, and signaling generations through 8 Mbps/60, 5 Mbps/30, and 3 Mbps/30 ceilings while its leaf kept decoding.
-- Chrome 151 with one host, three viewers, and synthetic 720p30 passed balanced and clarity propagation to every participant. Every baseline active video sender showed matching preference readback, peer-connection fingerprints stayed stable, and every viewer decoded and rendered new frames after each change; host fanout was two and relay fanout one.
-- That quality smoke was localhost, headless, and video-only. It proves control propagation and continuity, not visual quality, full-resolution performance, CPU/GPU load, TURN, public networks, or endurance.
-- Corrected Chrome 151/LiveKit 1.13.5 synthetic 720p30 smoke physically failed the same leaf through peer recovery/reparent and a two-root SFU route. Its frames resumed; 472 hook-assisted 25 ms samples saw host edge peak two. Failure report to active took 1.481 seconds and to new render 2.257 seconds.
-- The review revision passes repository hygiene, type checking, 21 Vitest files/268 tests, both production builds, and the Chrome control smoke above.
++- A localhost/headless Chrome 151 run with one host, three viewers, and synthetic 720p30 propagated balanced and clarity settings to every participant. Every active sender matched preference readback, peer fingerprints stayed stable, all viewers decoded/rendered new frames, and fanout stayed host two/relay one. This proves control continuity, not visual quality or performance.
+- Corrected Chrome 151/LiveKit 1.13.5 localhost/headless/video-only same-leaf A/B measured the cold path at 1.481 seconds to active and 2.257 seconds to render. Standby prepare arrived in 5 ms, active in 200 ms, and the same leaf rendered in 319.7 ms with 31 new decoded/frame-callback frames; 25 ms sampling kept host edge peak two. The roughly 86% result combines early SDK download/parse with token-free DNS/TLS/HTTP prewarm, creates no participant/media edge, and does not predict public-network performance.
- - Draft PR #17 passes CI. Draft PR [#20](https://github.com/TNTcraftHIM/Screener/pull/20) passes CI, type checking, 20 Vitest files/259 tests, both production builds, dependency audit, and repository hygiene.
- - Draft PR [#16](https://github.com/TNTcraftHIM/Screener/pull/16) passes CI for one Pion RTP write fanned to two transports. It has no encoder and proves neither physical encode nor browser E2E.
++- The integrated PR #20 revision passes repository hygiene, type checking, 22 Vitest files/274 tests, both production builds, and the existing Chrome evidence above.
+ - Chrome 151 CDP checks at 320/375/390 CSS px keep the two idle-stage actions equal, on one row, 44 px high, and free of horizontal overflow. The Viewer waiting page also has no overflow; its details checkbox starts false, changes locally, and resets after navigation. These checks cover idle/waiting states, not live media.
-- Draft PR [#16](https://github.com/TNTcraftHIM/Screener/pull/16) passes CI for one Pion RTP write fanned to two transports. It has no encoder and proves neither physical encode nor browser E2E.
- Local diagnostics use adjacent non-overlapping `getStats()` deltas; empty, changed-stream, and reset intervals rebase instead of publishing lifetime averages.
- Production HTTPS/WSS, access cookie, room/WebSocket authorization, certificate renewal, public STUN, and authenticated TURN/UDP and TURN/TCP relay-only bidirectional paths are verified. TURN/TLS is intentionally disabled.
## Unverified Boundaries
--- The short harness uses synthetic headless capture and proves topology, controls, stats collection, and recovery only. Full-resolution 30-minute runs, relay CPU/GPU, generational quality, controlled loss/RTT, depth latency, and actual game-capture behavior remain unverified.
++- Full-resolution 30-minute runs, relay CPU/GPU, generational quality, controlled loss/RTT, depth latency, and actual game capture remain unverified.
- Android Chrome and iOS Safari remain unverified leaves. Runtime capability conservatively marks detected mobile/iPad clients as leaves; real UA/lifecycle behavior remains open.
--- The observed recovery starts from a page close immediately seen by the server. A silent partition can wait 30 to 60 seconds for heartbeat detection before the default 5-second grace; it remains unverified.
++- Silent partitions can wait 30 to 60 seconds for heartbeat detection before the default 5-second grace; this remains unverified.
- Real screen/game audio, heterogeneous machines and networks, mobile lifecycle behavior, the production live quality/pause cycle, room `1` stop-and-republish/link reuse, and sustained profile performance remain unverified.
- - Production users report severe resolution/bitrate/FPS degradation across all profiles. A controlled 1/2/3-viewer and TURN sample must distinguish capture, per-edge CPU, bandwidth/path, and receiver limits before changing ceilings or codecs; clarity-first versus `balanced` is the first bounded A/B.
+ - Production users report severe resolution/bitrate/FPS degradation across all profiles. The Draft now permits bounded clarity/balanced comparison, but a controlled 1/2/3-viewer and TURN sample must still distinguish capture, per-edge CPU, path, and receiver limits before any quality claim or automatic controller.
- Browser relays do not share encoding. Encoded objects, custom congestion control, multiple trees, and network coding remain separate measured candidates.
--- The long-term endpoint budget is at most two downstream edges for both the host and relay-capable viewers, with one compatible encoded output reused across both edges where a native media engine can prove it. The current browser spike remains host capacity two/viewer capacity one and performs a new encode at each relay. Packet/layer striping and multi-parent assembly are recorded, not implemented.
++- The endpoint budget is host/relay at most two downstream edges; a native engine must prove shared encoding. The browser path remains host two/viewer one and re-encodes per relay. Striping and multi-parent assembly are only recorded.
+- The corrected standby smoke is localhost/headless/video-only; public DNS/TLS reuse, transport, audio, shaping, load, mobile, endurance, and sub-25 ms overlap remain open.
## Next Milestone
- Finish ADR-0005 before UI polish: validate standby gains across public
- transports, rollback, reconnect, controls, edge counts, egress, and load.
-Before enabling `main`'s experimental routes, address the 2.257-second fallback
-and validate public transports, rollback, reconnect, controls, edge counts,
-egress, and load. The quality stack remains undeployed until those gates pass.
++Before enabling `main`'s experimental routes, validate standby gains across
++public transports, rollback, reconnect, controls, edge counts, egress, and load.
++The quality and routing stacks remain undeployed until those gates pass.
ADR-0004 still requires a full-resolution 30-minute `1/3/5/8` network,
resource, quality, latency, recovery, and browser/mobile-leaf matrix.
diff --cc src/client/pages/HostPage.tsx
index 2cd38292,0574cb4b..ad8e9a77
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@@ -37,12 -39,18 +39,19 @@@ import { SignalingClient } from "../lib
import {
applyCaptureProfile,
captureDisplay,
+ DEGRADATION_PREFERENCE_LABELS,
+ matchingQualityProfileId,
QUALITY_PROFILES,
+ QUALITY_PROFILE_LABELS,
+ QUALITY_RESOLUTIONS,
+ qualitySettingsLabel,
setVideoPaused,
+ type DegradationPreference,
type QualityProfileId,
+ type QualitySettings,
} from "../media/quality";
import { HostSfuRoute } from "../media/host-sfu-route";
+import { SfuStandbyPrewarmer } from "../media/sfu-standby-prewarmer";
import type {
PeerSnapshot,
SignalConnectionState,
@@@ -222,15 -240,21 +244,30 @@@ export function HostPage({ onAuthorizat
void route?.disconnect();
}
+ function setSfuStandbyUrl(url: string | null | undefined): void {
+ if (!url) {
+ sfuStandbyPrewarmerRef.current?.setUrl(null);
+ return;
+ }
+ sfuStandbyPrewarmerRef.current ??= new SfuStandbyPrewarmer();
+ sfuStandbyPrewarmerRef.current.setUrl(url);
+ }
+
+ function showHostSfuQualityWarning(
+ route: HostSfuRoute,
+ generation: number,
+ ): void {
+ if (
+ isCurrentGeneration(generation) &&
+ hostSfuRouteRef.current === route
+ ) {
+ const warning = route.getQualityWarning();
+ if (warning) {
+ setNotice(warning);
+ }
+ }
+ }
+
function disposeResources(notifyServer: boolean): void {
sourceSwitchRef.current = null;
qualityChangeRef.current = null;
diff --cc src/client/pages/ViewerPage.tsx
index e7555ce0,121f139e..7b9f1d4d
--- a/src/client/pages/ViewerPage.tsx
+++ b/src/client/pages/ViewerPage.tsx
@@@ -23,12 -25,8 +25,9 @@@ import
import { StatsGrid } from "../components/StatsGrid";
import { getStableClientId } from "../lib/session";
import { SignalingClient } from "../lib/signaling";
- import {
- QUALITY_PROFILES,
- type QualityProfileId,
- } from "../media/quality";
+ import type { QualitySettings } from "../media/quality";
import { relayCapacityMessageForBrowser } from "../media/relay-capability";
+import { SfuStandbyPrewarmer } from "../media/sfu-standby-prewarmer";
import { ViewerMessageAuthority } from "../media/viewer-message-authority";
import { ViewerSfuRoute } from "../media/viewer-sfu-route";
import type {
@@@ -559,10 -541,9 +559,10 @@@ export function ViewerPage({ roomId, on
return;
}
if (message.type === "room-closed") {
+ setSfuStandbyUrl(null);
clearViewerSfuRoute();
clearPeerState();
- setStatusText(message.reason === "expired" ? "房间已过期" : "分享已结束");
+ setStatusText(message.reason === "expired" ? "房间已过期" : "房间已关闭");
signal.stop();
return;
}
diff --cc src/server/signaling.ts
index 05eeb77d,1fcdf0b1..7887e082
--- a/src/server/signaling.ts
+++ b/src/server/signaling.ts
@@@ -385,12 -382,9 +382,12 @@@ export class SignalingServer
mediaAssignment: hybridState.mediaAssignment,
routeRevision: hybridState.routeRevision,
routeAssignment: hybridState.routeAssignment,
- qualityProfileId:
- this.qualityProfileIdsByRoom.get(participant.roomId) ??
- DEFAULT_QUALITY_PROFILE_ID,
+ qualitySettings:
+ this.qualitySettingsByRoom.get(participant.roomId) ??
+ DEFAULT_QUALITY_SETTINGS,
+ ...(this.options.sfuFallback
+ ? { sfuStandbyUrl: this.options.sfuFallback.url }
+ : {}),
});
} else {
this.send(socket, authenticatedMessage);
diff --cc src/shared/protocol.ts
index 7d4d53e7,cfcbd0e1..1c9db32a
--- a/src/shared/protocol.ts
+++ b/src/shared/protocol.ts
@@@ -270,8 -285,7 +298,8 @@@ const authenticatedMessageSchema = z.un
mediaAssignment: mediaAssignmentSchema,
routeRevision: mediaRouteRevisionSchema,
routeAssignment: participantRouteAssignmentSchema,
- qualityProfileId: qualityProfileIdSchema,
+ qualitySettings: qualitySettingsSchema,
+ sfuStandbyUrl: liveKitWebSocketUrlSchema.optional(),
})
.strict(),
]);
diff --cc tests/protocol.test.ts
index 57cc9d43,1fa0e6b5..15845e79
--- a/tests/protocol.test.ts
+++ b/tests/protocol.test.ts
@@@ -363,25 -375,18 +381,30 @@@ describe("server signaling protocol", (
expect(
serverMessageSchema.safeParse({
...authenticatedMessage(8),
- qualityProfileId: "1080p60",
+ qualitySettings,
}).success,
).toBe(false);
+ expect(
+ serverMessageSchema.safeParse({
+ ...authenticatedMessage(8),
+ sfuStandbyUrl: "wss://sfu.example.com",
+ }).success,
+ ).toBe(false);
+ expect(
+ serverMessageSchema.safeParse({
+ ...peerAssisted,
+ sfuStandbyUrl: "https://sfu.example.com",
+ }).success,
+ ).toBe(false);
expect(
serverMessageSchema.safeParse({
- type: "quality-profile",
- qualityProfileId: "720p30",
+ type: "quality-settings",
+ qualitySettings: {
+ resolution: "720p",
+ maxFramerate: 30,
+ maxBitrate: 3_000_000,
+ degradationPreference: "balanced",
+ },
}).success,
).toBe(true);
expect(
diff --cc tests/server-signal.test.ts
index 7eb7e778,24f1c8bf..bfc808f0
--- a/tests/server-signal.test.ts
+++ b/tests/server-signal.test.ts
@@@ -806,8 -833,7 +834,8 @@@ describe("WebSocket signaling", () =>
"p2p-quality-host",
);
expect("mediaMode" in hostAuth).toBe(false);
- expect("qualityProfileId" in hostAuth).toBe(false);
+ expect("qualitySettings" in hostAuth).toBe(false);
+ expect("sfuStandbyUrl" in hostAuth).toBe(false);
const viewer = await openClient(harness.webSocketUrl);
const viewerAuth = await authenticate(
@@@ -817,8 -843,7 +845,8 @@@
"p2p-quality-viewer",
);
expect("mediaMode" in viewerAuth).toBe(false);
- expect("qualityProfileId" in viewerAuth).toBe(false);
+ expect("qualitySettings" in viewerAuth).toBe(false);
+ expect("sfuStandbyUrl" in viewerAuth).toBe(false);
await host.inbox.next("peer-joined");
host.socket.send(