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. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。

feat(media): enable hybrid routing for all rooms

AAA93c6763198d7
diff --git a/.env.example b/.env.example
index 79038de3..3d5df7e3 100644
--- a/.env.example
+++ b/.env.example
@@ -16,11 +16,9 @@ ROOM_DATABASE_PATH=
ROOM_TTL_SECONDS=14400
MAX_ROOMS=1000
MAX_VIEWERS_PER_ROOM=8
-# Experimental standard-WebRTC relay chains. Keep false outside measured tests.
+# Bounded standard-WebRTC relay/SFU controller for every room when true.
+# Keep false outside measured tests.
PEER_ASSISTED_MEDIA=false
-# Required exact-room canary when peer assistance is true. Use a non-empty,
-# comma-separated list of positive numeric room IDs; missing or blank fails startup.
-PEER_ASSISTED_ROOM_IDS=
# Optional automatic SFU fallback capacity. Set PEER_ASSISTED_MEDIA=true and
# supply all three values together; leaving them empty keeps LiveKit completely
@@ -47,7 +45,6 @@ STUN_URLS=
# STUN_URLS=stun:stun.example.com:3478
# Automatic SFU fallback (requires PEER_ASSISTED_MEDIA=true and does not
# replace STUN above):
-# PEER_ASSISTED_ROOM_IDS=1
# LIVEKIT_URL=wss://share.example.com
# LIVEKIT_API_KEY=replace-with-a-livekit-api-key
# LIVEKIT_API_SECRET=replace-with-at-least-32-independent-random-bytes
diff --git a/docs/adr/0001-p2p-first-media-topology.md b/docs/adr/0001-p2p-first-media-topology.md
index a7d69926..13ddc0c8 100644
--- a/docs/adr/0001-p2p-first-media-topology.md
+++ b/docs/adr/0001-p2p-first-media-topology.md
@@ -10,8 +10,9 @@ peer-assisted media, and an enabled SFU fallback is a standing requirement and
is governed by ADR-0005.
Historical ADR-0003's explicit whole-room SFU mode is rejected/superseded.
-ADR-0004's bounded peer topology and ADR-0005's default-off automatic controller
-now run only in the exact-room production smoke. ADR-0005 accepts the target
+ADR-0004's bounded peer topology and ADR-0005's automatic controller are
+process-enabled for all normal rooms when configured; room `1` is only the
+historical production smoke. ADR-0005 accepts the target
direct/peer UDP -> SFU-root UDP -> optional authenticated selected-edge TURN
ladder. Ordinary peer ICE remains STUN-only; the selected-edge config/wire is
not implemented or deployed and still requires isolated acceptance gates.
diff --git a/docs/adr/0004-peer-assisted-media-experiment.md b/docs/adr/0004-peer-assisted-media-experiment.md
index 65f2e9f9..c02e1a99 100644
--- a/docs/adr/0004-peer-assisted-media-experiment.md
+++ b/docs/adr/0004-peer-assisted-media-experiment.md
@@ -1,6 +1,6 @@
# ADR-0004: Peer-Assisted Media Experiment
-- Status: Proposed - Experiment Only
+- Status: Proposed - Historical Experiment (rollout superseded by ADR-0005)
- Date: 2026-08-19
## Context
diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.md
index 687cf48a..bdccbb15 100644
--- a/docs/adr/0005-automatic-hybrid-media-routing.md
+++ b/docs/adr/0005-automatic-hybrid-media-routing.md
@@ -1,6 +1,6 @@
# ADR-0005: Automatic Hybrid Media Routing
-- Status: Accepted Direction - Default-Off Migration Unverified
+- Status: Accepted Direction - All-Room Controller, Media Evidence Unverified
- Date: 2026-08-19
## Context
@@ -76,16 +76,17 @@ tuple and remains a controller-owned transport attempt, never a topology choice.
## Implementation Status
Merged PR #17 implements this controller on top of merged PR #13, and PR #20
-adds the bounded standby prewarm below. Production enables them only for
-persistent room `1`; other rooms stay ordinary P2P, and production remains
+adds the bounded standby prewarm below. The process flag enables the controller
+for every normal room; room `1` is retained only as a historical smoke fixture,
+and production remains
STUN-only. The current source no longer contains the rejected participant-wide
TURN config, issuer, capability, refresh wire, or client propagation. Stale
`PEER_ICE_TURN_*` keys fail startup even when blank. The source candidate now
implements a complete default-off selected-edge tuple and one post-SFU
relay-only rebuild; it remains undeployed and lacks real TURN/media evidence.
The wire has two explicit edge kinds: `peer-selected` for the last-mile failed
-peer edge and `host-sfu-ingress` for an exact-room-`1` restricted Host-to-SFU
-retry. Ordinary Peer ICE remains STUN-only.
+peer edge and `host-sfu-ingress` for a restricted Host-to-SFU retry. Ordinary
+Peer ICE remains STUN-only.
The current runtime removes the old all-room coturn contract. Production
requires STUN and authenticated ICE snapshots contain only STUN servers in
@@ -97,19 +98,17 @@ been observed, but retained media and route admission remain unverified. The old
`769de201f7cc` release and coturn relay are isolated rollback resources, not a
permanent compatibility branch or advertised current transport.
-The repository also requires a strict, non-empty `PEER_ASSISTED_ROOM_IDS`
-deployment allowlist whenever `PEER_ASSISTED_MEDIA=true`. Only exact listed room
-IDs enter the controller or receive optional LiveKit standby, grants, or a
-selected-edge TURN attempt. All other rooms retain the current ordinary P2P
-authentication shape, STUN-only ICE, and signaling/quality/lifecycle behavior. Missing, blank, malformed, or duplicate
-entries fail startup; there is no configuration state that enables all rooms. The boundary is a
-temporary deployment-only validation gate with no browser selector, percentage
-framework, or second router.
+`PEER_ASSISTED_MEDIA=true` is now the only rollout switch. It enables the
+controller, LiveKit standby, grants, and selected-edge attempts for every normal
+room, while each room keeps independent route state and the existing root/fanout
+limits. `PEER_ASSISTED_ROOM_IDS` is retired and fails startup if supplied during
+migration; room `1` is a historical smoke fixture, not a feature gate. A process
+with the flag disabled remains ordinary P2P.
The implementation keeps the LiveKit dependency dormant unless the complete URL, API key,
and API secret tuple is present together with `PEER_ASSISTED_MEDIA=true`. It
issues short-lived room-, role-, peer-, and publication-generation-bound grants,
-and only allowlisted branch roots may subscribe. A necessary viewer with no
+and only selected branch roots may subscribe. A necessary viewer with no
descendants is still a root under the same authorization and total cap. The
server currently retries a failed edge through the deterministic peer topology;
only an exhausted peer route can request an SFU branch root. The target keeps
@@ -245,9 +244,10 @@ connection generation and assigned-edge authorization. The server
derives the failed edge from the authenticated session, active revision, and
connection ID instead of accepting a client-supplied parent or arbitrary reason.
Late, duplicate, or stale revision messages have no effect.
-Non-allowlisted rooms receive the ordinary P2P snapshot with none of the hybrid
-fields above, even when the same process serves an allowlisted room and has a
-complete LiveKit tuple.
+When the process flag is enabled, every normal room receives the hybrid snapshot
+and its own controller state. A process with the flag disabled receives the
+ordinary P2P snapshot. The distinction is process configuration, never a room
+ID allowlist.
## Transition
@@ -284,7 +284,7 @@ complete LiveKit tuple.
publish until the replaced direct edge and any old SFU generation are
inactive.
-6. Allowlisted fallback roots explicitly subscribe. On their first new video
+6. Selected fallback roots explicitly subscribe. On their first new video
track, they atomically replace their upstream stream, acknowledge active,
and feed the existing downstream relay without rebuilding descendants.
7. A prepare timeout increments the revision and restores the unchanged active
@@ -295,8 +295,8 @@ complete LiveKit tuple.
failure, or the initial SFU prepare, is exhausted, the router grants at most
one relay-only rebuild of that Viewer's original failed peer edge. An active
Host-to-SFU route may instead receive one `host-sfu-ingress` relay-only grant
- when the explicit restricted-source decision applies to exact room `1`; the
- grant is bound to the host session and publication generation. Failure is
+ when the explicit restricted-source decision applies; the grant is bound to
+ the host session and publication generation. Failure is
terminal for that attempt; stop, session replacement, topology revision or a
new sharing generation clears it, then the existing bounded peer failback
remains available.
@@ -338,7 +338,7 @@ One bounded cold/standby A/B comparison used Chrome 151, LiveKit 1.13.5,
headless synthetic 1280x720/30 video, three viewers, and localhost. The harness
physically closed the same leaf's inbound peer edge, observed it resume under a
second peer, then physically closed that new edge and reported its real
-connection ID and active revision. The resulting plan had two allowlisted SFU
+connection ID and active revision. The resulting plan had two selected SFU
roots.
| Failure report to | Cold route controller | Authenticated standby |
@@ -420,13 +420,13 @@ participant-wide TURN path: the rejected candidate is removed and its stale
environment keys fail startup. The default-off selected-edge source candidate uses
a short coturn REST bearer and one server-generated connection identity per explicit
edge kind. `peer-selected` binds the failed parent/Viewer pair; `host-sfu-ingress`
-binds exact room `1`, the host session, the SFU publication generation, and the
+binds the room, host session, SFU publication generation, and the
old/new connection identities. The Host client applies that grant only to a
relay-only LiveKit publisher `RTCConfiguration`. It is undeployed and has no real
relay-media evidence.
LiveKit participant-wide embedded/external TURN remains a separate ICE domain.
-The bounded cost model, privacy-safe ICE fields, and exact-room A/B sequence
+The bounded cost model and privacy-safe ICE fields
live in [Low-Server-Cost Media Routes](../research/low-server-media-routes.md).
For one SFU publisher at bitrate `B_pub` and `R` roots at measured bitrates
`B_i`, host upload is `B_pub` and central ingress plus egress is
@@ -437,15 +437,15 @@ peer PCs. Every host NIC, TURN ingress/egress, SFU ingress/egress, root NIC, and
exception NIC hop remains real traffic.
Migration is gated, not optional design debate. Production has entered a
-shared-IP exact-room smoke while the old release remains a separate rollback
-instance. Room `1` must still verify direct/peer UDP, SFU/UDP, one explicitly
-selected relay edge, and bounded failure with all transports exhausted; the
-current process never restores the old all-room TURN wire. The matrix covers CGNAT, double NAT, mobile hotspot,
+historical shared-IP room-`1` smoke while the old release remains a separate
+rollback instance. The same direct/peer UDP, SFU/UDP, selected relay edge, and
+bounded failure gates apply to every room in the flagship process; the current
+process never restores the old all-room TURN wire. The matrix covers CGNAT, double NAT, mobile hotspot,
ordinary home networks, root departure, reconnect, SFU unavailable, and rollback. It records
CPU seconds/GiB, NIC bytes/pps, RSS, host upload, p95/p99 forwarding latency,
loss/recovery, final quality, host edges at most two, SFU roots at most two, and
-unchanged healthy subtrees. Every ordinary connection stays STUN-only; only
-after that gate may the controller broaden beyond room `1`.
+unchanged healthy subtrees. Every ordinary connection stays STUN-only; room
+scope does not change that rule.
A peer root re-publishing its received stream to the SFU while also feeding
peer descendants remains a separate bounded candidate. The current browser
@@ -462,8 +462,8 @@ the current fallback-root identities, including any zero-descendant roots.
Ordinary SFU WebRTC transport encryption terminates at the SFU, so its operator
can access media. LiveKit supports application E2EE in which its server cannot
access media content, but signaling/API data remains visible and Screener has
-not implemented the required key distribution. The exact-room comparison must
-record which boundary is actually configured and the UI must not claim E2EE.
+not implemented the required key distribution. The comparison must record which
+boundary is actually configured and the UI must not claim E2EE.
## Implementation Order
@@ -500,10 +500,11 @@ record which boundary is actually configured and the UI must not claim E2EE.
persistent-room stop/restart semantics survive the transition.
- No LiveKit configuration preserves the existing P2P/peer behavior and wire,
but is not the final flagship deployment target.
-- In one process, non-allowlisted rooms preserve ordinary P2P route fields,
- directed signaling, quality rejection, stop/reconnect/delete semantics, and
- remain isolated from allowlisted peer/SFU state and receive STUN-only ICE.
- Native v2 and every ordinary peer PC also remain STUN-only. Only a current
+- In a process with the controller flag disabled, ordinary rooms preserve the
+ ordinary P2P route fields, directed signaling, quality rejection,
+ stop/reconnect/delete semantics, and STUN-only ICE. With the flag enabled,
+ every room gets isolated per-room peer/SFU state under the same limits. Native
+ v2 and every ordinary peer PC remain STUN-only; only a current
controller-selected exceptional edge may receive a short-lived TURN grant.
- LiveKit/SFU UDP must pass CGNAT, double-NAT, hotspot, home-network, loss,
rollback, and SFU-unavailable gates. Blocked UDP fails clearly within a
@@ -540,7 +541,8 @@ Negative:
## Relationship To Existing ADRs
- This decision corrects the automatic-migration interpretation in ADR-0001;
- production now runs its exact-room smoke while broad rollout remains gated.
+ room `1` is historical smoke evidence, while the source controller is
+ process-enabled for all normal rooms.
- ADR-0004 remains the bounded full-stream browser-relay experiment.
- This decision and merged PR #17 supersede ADR-0003/closed PR #12's
process-wide explicit media mode with default-off automatic hybrid fallback.
diff --git a/docs/deployment.md b/docs/deployment.md
index 1c0df47a..5a89796d 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -112,10 +112,11 @@ exceptional edge. LiveKit participants receive only revision-bound `sfu-config`
URL/token messages and negotiate within LiveKit's separate ICE domain. The
selected-edge TURN config/wire is source-only and not yet deployed.
-`PEER_ASSISTED_ROOM_IDS` remains the topology/SFU canary boundary. Listed and
-unlisted ordinary peer connections both get STUN-only ICE; only the selected-edge
-source path may grant TURN to the controller's then-current
-edge. Run candidate rooms on an isolated instance/hostname and keep
+`PEER_ASSISTED_MEDIA=true` is the process-wide topology/SFU switch. Every normal
+room gets its own bounded controller state; ordinary peer connections remain
+STUN-only and only the selected-edge source path may grant TURN to the
+controller's then-current edge. Run candidate releases on an isolated
+instance/hostname and keep
the old release unchanged for rollback. If the candidate fails, roll back the
release or instance; do not add a permanent dual-transport branch.
@@ -185,7 +186,6 @@ To make automatic SFU fallback capacity available, add the complete tuple:
```dotenv
PEER_ASSISTED_MEDIA=true
-PEER_ASSISTED_ROOM_IDS=1
LIVEKIT_URL=wss://share.example.com
LIVEKIT_API_KEY=<GENERATED_LIVEKIT_API_KEY>
LIVEKIT_API_SECRET=<INDEPENDENT_SECRET_OF_AT_LEAST_32_BYTES>
@@ -197,22 +197,17 @@ stale key, even blank, fails startup. The source candidate uses the complete
`SELECTED_EDGE_TURN_URLS`, `SELECTED_EDGE_TURN_SHARED_SECRET`, and
`SELECTED_EDGE_TURN_CREDENTIAL_TTL_SECONDS` default-off tuple with one explicit
TURN/UDP URI, an independent secret and bounded TTL. Enable it only after the
-exact-room peer/SFU tuple and bounded coturn service are ready; roll back by
+all-room peer/SFU tuple and bounded coturn service are ready; roll back by
removing the application tuple before changing coturn or firewall state. Credentials
never enter URLs, logs, browser persistence, room rows, or SQLite.
-`PEER_ASSISTED_ROOM_IDS` is the required deployment canary boundary whenever
-`PEER_ASSISTED_MEDIA=true`. Its non-empty value
-is a comma-separated set of exact positive numeric room IDs, using the same
-1-to-12-digit syntax as room authentication. Duplicate IDs, empty entries,
-leading zeroes, and malformed IDs fail startup. A non-empty allowlist requires
-`PEER_ASSISTED_MEDIA=true`. Only listed rooms receive peer-assisted
-authentication, routing, room quality state, or optional LiveKit fallback;
-every other room keeps ordinary P2P route fields and signaling behavior. The
-selected-edge TURN attempt is confined to a current controller edge in a
-listed room; every ordinary peer connection remains STUN-only. Omitting or blanking the variable fails startup rather
-than enabling every room. There is no browser control, percentage rollout, or
-all-room fail-open.
+`PEER_ASSISTED_ROOM_IDS` is retired. Supplying it, even blank, fails startup so
+that a stale room-1 deployment cannot silently retain the old scope. With
+`PEER_ASSISTED_MEDIA=true`, every normal room receives peer-assisted routing,
+optional LiveKit fallback, and the same per-room root/fanout/failure guards.
+Every ordinary peer connection remains STUN-only; selected-edge TURN is still
+issued only to a current controller-selected edge. There is no browser control,
+percentage rollout, or second router.
`ALLOWED_ORIGINS` must list exact `http` or `https` origins, never `*`.
`HOST_ADMISSION_PASSWORD` is required in production and must contain 8 through
@@ -237,12 +232,11 @@ credentials authorize short-lived LiveKit room tokens and do not provide E2EE:
the LiveKit operator can access ordinary SFU media.
For the first candidate canary, use an isolated instance and a protected
-persistent room whose ID is stable across restarts. Set only that ID, restart
-the application, and verify
-that its authenticated message contains `mediaMode: "peer-assisted"` while a
-second non-allowlisted room contains none of `mediaMode`, `qualitySettings`,
-`routeRevision`, `routeAssignment`, or `sfuStandbyUrl`. Exercise join, offer and
-answer, stop, reconnect, and room deletion in both rooms. Ordinary Web and
+persistent room whose ID is stable across restarts. Restart the application and
+verify that both that room and a second normal room contain
+`mediaMode: "peer-assisted"`, with independent route revisions and no shared
+room state. Exercise join, offer and answer, stop, reconnect, and room deletion
+in both rooms. Ordinary Web and
Native-shaped clients remain STUN-only. With the selected-edge tuple, only
the current controller-selected edge may receive a one-use grant; all other
sessions and connections remain STUN-only. Roll back by disabling application
@@ -250,9 +244,9 @@ issuance before restoring the exact recorded pre-canary coturn/firewall baseline
traffic to the unchanged old release. Do not treat disabling
`PEER_ASSISTED_MEDIA` alone as TURN rollback: disable the selected-edge tuple
independently, and no removed old
-TURN wire is restored. After acceptance, retire or replace the
-temporary exact-room gate in a separate coherent change; never clear the value
-to trigger an implicit all-room rollout.
+TURN wire is restored. During migration, remove the retired room-ID variable in
+the same coherent change; the process flag explicitly enables the all-room
+controller.
Only `POST /api/host-admission` accepts the Host admission secret in an
`Authorization: Bearer` header from an exact allowed Origin. Success returns a
@@ -572,7 +566,7 @@ Run these checks from real external networks before calling the deployment usabl
are closed externally.
2. Create a normal Screener room on two different networks. Confirm media flows
and the selected-pair stats report a non-relay path when direct ICE succeeds.
-3. On an exact allowlisted room, exhaust a peer route and verify the host plus at
+3. On a normal room, exhaust a peer route and verify the host plus at
most two necessary roots select LiveKit UDP 7882. Peer descendants stay on
ordinary direct UDP and host/relay downstream caps remain two/one.
4. Block all UDP on one test client. Verify bounded ICE recovery ends in a clear
diff --git a/docs/maintenance.md b/docs/maintenance.md
index b1f4b0c6..bd4c7f01 100644
--- a/docs/maintenance.md
+++ b/docs/maintenance.md
@@ -90,7 +90,7 @@
- host 下游活跃媒体边不超过两个;
- 普通桌面或移动浏览器 Viewer 无需安装应用;
- break-before-make、安全授权、重连、回滚和陈旧消息隔离语义;
-- 功能默认关闭,并保留 exact-room allowlist 灰度边界。
+- 轻量实例可关闭 controller;旗舰部署以 `PEER_ASSISTED_MEDIA=true` 对所有正常房间启用,room `1` 仅是历史 smoke,已不再保留 exact-room allowlist 灰度边界。
实现期间只运行覆盖当前改动的窄测;完整候选形成后统一运行一次 full check。除非媒体行为或证据采集逻辑改变,不重跑昂贵浏览器/网络矩阵。实现 PR 必须原位同步 status、project memory 和相关 ADR,删除失效描述,不新增过程流水账文档。
diff --git a/docs/project-memory.md b/docs/project-memory.md
index b4fcea01..4f553771 100644
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@ -20,33 +20,37 @@ Last updated: 2026-08-21
## Current Recommendation
- 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. Keep ADR-0004 off broadly; use an isolated exact-room candidate until resource, quality, recovery, SFU/UDP, bounded-failure, and browser/mobile gates pass.
+- Use direct host P2P for one or two viewers, then the bounded controller for every room when `PEER_ASSISTED_MEDIA=true`. Room `1` is historical smoke, not a runtime gate; resource, quality, recovery, SFU/UDP, bounded-failure, and browser/mobile evidence remain separate.
- Browser relays resend remote `MediaStreamTrack` values and re-encode at each hop; WebRTC does not guarantee a shared encoder across peer connections, so measure the cost.
- Keep experiments bounded: the standard representation sequence is below; native RTP relay, encoded-object striping, and FEC remain separate.
-- ADR-0006 remains no-go. Native has explicit H.264 opt-in beside default VP8: Chrome 151 loopback reached 299 decoded/298 rendered frames (18 sender, 156 source RTP, 2,690 inbound) at 1280x720 with zero encoder/fatal errors. The gate retains a Pion snapshot-timing residual. `prefer-hardware` is only a request; physical attribution, multi-viewer, endurance, public-network, and packaged-native proof remain open.
+- ADR-0006 remains no-go. Native H.264 opt-in loopback (Chrome 151, 1280x720) rendered 298/299 with zero fatal/encoder errors; VP8 remains default. Pion timing, hardware attribution, multi-viewer/endurance/public/packaged proof remain open.
- Mobile Web Host is unsupported; feature-detect and fail clearly. Mobile Viewer stays leaf-only. After Windows native, gate Android 14+; iOS waits for stable iOS 27 ScreenCaptureKit.
-- ADR-0005 accepts direct/peer UDP, bounded SFU roots, then optional selected-edge TURN. Source has a default-off, undeployed one-shot rebuild after SFU; participant-wide TURN remains rejected and production stays STUN-only.
-- Keep the controller exact-room only: room `1` is the STUN/SFU smoke. Preserve sticky progressing P2P, mobile leaves and break-before-make. Recovery spends one attempt per layer (ICE restart, same-parent rebuild, alternate peer, then SFU), never three identical retries; active SFU gets one fresh grant before Peer failback.
+- ADR-0005 accepts direct/peer UDP, bounded SFU roots, then optional selected-edge TURN. Source has a default-off, undeployed one-shot rebuild after SFU; participant-wide TURN remains rejected and ordinary peer ICE stays STUN-only.
+- The controller is process-enabled, not room-allowlisted: `PEER_ASSISTED_MEDIA=true` gives every normal room the same direct/peer -> SFU -> selected-edge path with per-room state. Room `1` is historical smoke. Preserve sticky P2P, mobile leaves and break-before-make; recovery gets one attempt per layer (ICE restart, same-parent rebuild, alternate peer, then SFU), never three identical retries.
- C+B quality reparenting is edge-local and cooldown-bound; no score, timer, or global parent penalty.
- Flagship media is UDP; HTTPS/WSS stays TLS/TCP; the old release remains rollback-only.
- Treat settings as ceilings and degradation as unclassified. Use correlated Host A+B/Viewer C and one-variable evidence; never force AV1, infer by UA, or create a composite score.
-- Production reports poor film audio and self-echo when system capture includes voice software. Diagnose audio A/B/C and sync; Web cannot isolate arbitrary processes and `maxBitrate` is not quality-up. A Windows 11 native candidate defaults to game-process-tree audio and never widens silently; Windows 10 remains unresolved/unsupported. See `docs/research/browser-screen-audio-quality.md`.
+- System capture can cause film-audio loss/self-echo; Web cannot isolate processes. Diagnose A/B/C and sync; Windows 11 native game-tree audio is a candidate, Windows 10 unresolved. See `docs/research/browser-screen-audio-quality.md`.
- Viewer-local names and the opt-in Web participant roster remain control-plane-only. The Web Host name change is source-only after its failed activation; names stay socket/localStorage-only, and Native remains outside the capability boundary.
- Do not add scene detection, dynamic-FPS control, or forced AV1 without negotiation, encode, game, CPU/GPU, and sender evidence.
- ADR-0002 grant/public access and the v3 room-password migration are deployed; Host display-name remains source-only. Names/presence remain session-only without account or roster tables.
- Deferred architecture audit: `docs/maintenance.md`.
+## Current Execution Principle
+
+- Prioritize flagship/mainline; parallelize design, research, implementation, tests, and audit. Land the smallest runnable change with one smoke and rollback; avoid duplicate matrices. Room `1` is not a feature boundary; reuse mature designs without overstating hardware; benchmark after functional landing.
+
## Current Implementation
- The repository is one npm package using Node.js 24, React, TypeScript, Vite, native WebRTC, `ws`, Zod, Vitest, and separate coturn.
-- Production currently serves `fdd14ba0d9b5ea4c43aa0f6a3a29e0eacf182612` at `https://share.bonfire.icu` after the single Host display-name cutover attempt at `2026-08-20T16:09Z` was automatically rolled back. The prepare-to-release switch and health gate passed; a post-cutover assertion used stale `NRestarts=31` data and triggered the rollback. Health is 200 and SQLite v3 retains four rooms including room `1`. Room `1` alone enables peer/SFU routing, C+B local reparenting, and admission rescue; unlisted rooms remain ordinary P2P. The preceding `31bee238` release remains historical rollback evidence.
+- Production serves `fdd14ba0d9b5ea4c43aa0f6a3a29e0eacf182612` at `https://share.bonfire.icu` after the `2026-08-20T16:09Z` Host display-name cutover rolled back on stale `NRestarts=31` data. Health is 200; SQLite v3 retains four rooms including room `1`. That rollback still has the historical room-1 gate; source removes it for the next release. `31bee238` is historical rollback evidence.
- The current Screener, LiveKit, coturn, and nginx services each report `NRestarts=0`. The Host display-name artifact was not retained as an active release, so Host names remain source-only/not deployed; selected-edge TURN remains disabled.
- Production ICE is STUN-only; stale `PEER_ICE_TURN_*` keys fail startup even blank. Source has a default-off coturn REST rebuild for the original failed Host/ViewerRelay edge after Viewer-root SFU exhaustion; it is undeployed/unverified and production advertises no TURN credential.
- Production requires an independent `HOST_ADMISSION_PASSWORD` only for creation/Host role. Default private fragment grants, room passwords, and explicit public-watch authorize Viewers; four anonymous Chrome routes stayed neutral until authorization. There are no accounts/JWT/session rows; SQLite v3 still contains all four rooms, including room `1`.
-- Production uses nginx, Node.js 24.19.0, coturn 4.17.2, and pinned LiveKit 1.13.5 on UDP 7882 with TCP fallback disabled. The application TURN tuple is absent; coturn retains the old authenticated-relay config and TCP/UDP 3478 plus UDP 49152-49251 rules but receives no advertised credential. Current service state is health 200 with all four service restart counts at 0.
-- ADR-0005 is configured with exact `PEER_ASSISTED_ROOM_IDS=1`; unlisted rooms use ordinary P2P. `screener-v2` is the only deployed signaling literal; there is no v1 parser or translator.
+- Production uses nginx, Node.js 24.19.0, coturn 4.17.2, and LiveKit 1.13.5 on UDP 7882 (TCP fallback off). No application TURN tuple is advertised; coturn retains the old authenticated-relay ports. Services are healthy with zero restarts.
+- ADR-0005 source rejects `PEER_ASSISTED_ROOM_IDS`; `PEER_ASSISTED_MEDIA=true` enables every room, while ordinary peer ICE stays STUN-only. A stale room-ID variable fails startup. `screener-v2` is the only deployed signaling literal; there is no v1 parser or translator.
- Chrome 151/LiveKit localhost A/B cut failure-to-active/render from 1.481/2.257 seconds to 0.200/0.320; 31 new frames and 25 ms sampling kept host edges at two. It is headless synthetic 720p30 and includes SDK/network prewarm, not public-network evidence.
-- Chrome 151 synthetic topology/quality-control runs kept fanout 2/1 and all viewers decoding; one relay close recovered in 5.32 seconds. This is control evidence only.
+- Chrome 151 synthetic topology/quality runs kept fanout 2/1 and decoding; one relay close recovered in 5.32 seconds. Control evidence only.
- Room `1` publishes `HIGH+LOW` with Dynacast off and subscriber `HIGH` ceilings, and now has bounded local quality reparenting. Both remain unverified on real media; test zero-child leaves and calibrated C+B loss before broad rollout.
- C+B uses three hard-bad pairs, one-use samples and guarded intent/cooldown. Deployed admission rescue moves the oldest childless zero-capacity Host leaf below an unassigned one-slot relay in one revision; no score/timer/global rebalance. Deployment passed, but no real room triggered it.
- Source-only Web Host name/presence leaves Native wire/media unchanged and separates Viewer roster from Host diagnostics; the Host-name artifact was not activated.
diff --git a/docs/status.md b/docs/status.md
index 687a6c25..499c9a71 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -11,19 +11,23 @@ automatic rollback. SQLite v3 has four rooms including room `1`; the
application/database stayed healthy, and current Screener, LiveKit, coturn, and
nginx services each report `NRestarts=0`. Host display names remain
source-only/not deployed.
-Ordinary ICE is STUN-only process-wide; persistent room `1` alone enables the
-automatic peer/SFU-UDP controller with at most two SFU roots. The old
+Ordinary ICE is STUN-only; source flag `PEER_ASSISTED_MEDIA=true` enables the
+bounded peer/SFU-UDP controller for every room (at most two roots). Room `1` is
+historical smoke only. The old
`fdd14ba0d9b5` is the healthy v3 rollback target; older schema details are in
`docs/deployment.md`. Native is no-go and not in production.
+## Execution Principle
+
+Flagship first; parallelize design/research/code/tests/audit. Ship minimum runnable + smoke + rollback; avoid duplicate matrices. Room `1` is historical; benchmark later; no hardware overclaim.
+
## Current Snapshot
- Capture precedes room creation; source/quality changes preserve peers and pause keeps audio/connections. Quality defaults to `maintain-resolution` with balanced/fluid options.
- Production access is `screener-v2`: Host admission, private grants/passwords, and public codes authorize Viewers. SQLite v3 retains four rooms and checked material; raw credentials are never stored.
- The Host display-name change is source-only after the failed `61a87ae` activation; it did not alter the deployed wire or UI.
- Source-only Native v2 uses memory-only rooms, 300s reclaim and `ROOM_TTL`; production does not run it.
-- PR #44's exact-room STUN-only/SFU-UDP router is enabled only for production room `1`: host/SFU roots <=2, browser relay <=1, bounded failure. HTTPS/WSS stays TLS/TCP.
-- Fallback prewarm is token-free and limited to room `1`; mobile/iPad viewers are leaves and healthy edges stay sticky.
+- PR #44's STUN-only/SFU-UDP router and token-free fallback prewarm are process-enabled for all normal rooms: roots <=2, browser relay <=1, bounded failure. Room `1` is historical smoke; mobile/iPad viewers are leaves, healthy edges sticky, and HTTPS/WSS stays TLS/TCP.
- After an answer, a generation-bound 15s initial-connect deadline enters ICE restart; success/replacement/disposal cancels it. It is deployed but not mobile-verified.
- Room `1` can publish exactly `HIGH+LOW` with Dynacast/backup codec off and subscriber `HIGH` ceilings; it has no retained real media frame.
- Room `1` C+B reparenting remains uncalibrated. Deployed admission rescue promotes an unassigned one-slot relay over the oldest childless zero-capacity Host leaf, with no scores or periodic optimization.
@@ -36,17 +40,17 @@ automatic peer/SFU-UDP controller with at most two SFU roots. The old
- Host A+B and authenticated P2P Viewer C are sanitized, generation-bound, read-only, and fail closed for stale, ambiguous, or SFU-fed evidence; no raw media metadata is retained.
- SVC is `no-go-web-svc-cross-path-hardware-contract`: no direct/peer selection, cross-PC shared encode, or portable hardware proof; pinned screen share is `L1T3`. No browser run was warranted.
- The `a11a73d` built-in TURN canary is rejected: local allocation passed, but direct Host/Pion Viewer failed before forced relay. Full rollback restored STUN-only client ICE and zero allocations.
-- Native loopbacks (Chrome 151) reached 1280x720 Viewers: VP8 30 sender/85 source RTP/877 inbound/299 decoded; H.264 opt-in 18/156/2,690/299 decoded/298 rendered, with no fatal/encoder errors. H.264 uses `42c01f` Annex-B; `prefer-hardware` is not hardware proof. Pion outbound snapshot timing remains; multi-viewer/FIFO/endurance/public/native proof is open, production stays VP8.
+- Native loopbacks (Chrome 151): VP8 299 decoded; H.264 opt-in 299 decoded/298 rendered at 1280x720, with no fatal/encoder errors. H.264 Annex-B; hardware preference is not proof. Pion timing and multi-viewer/FIFO/endurance/public/native proof remain open; production stays VP8.
- Access protocol/config/HTTP/storage/SQLite/signaling focused tests pass, including commit-first teardown and v1 rollback.
-- Source adds room-1 Host ingress + peer last-mile; Peer ICE STUN-only; 160 tests pass.
+- Source adds selected Host ingress + peer last-mile for every enabled room; Peer ICE STUN-only; focused routing/config tests pass.
- The `61a87ae` Host-name artifact was rolled back after a stale restart-count assertion; `fdd14ba` is healthy and Host display-name remains source-only. Selected-edge TURN is disabled.
## Unverified Boundaries
-- Room 1 proved LiveKit participant entry but not a retained SFU Viewer frame, exact retry/failback transition, selected UDP pair, admission-rescue transition, edge cap, quality or resource deltas. Former game-share load/blur remains unclassified.
+- Room 1 proved LiveKit participant entry but not a retained SFU frame, retry/failback, selected UDP pair, admission rescue, edge cap, quality, or resource deltas. Former game-share load/blur remains unclassified.
- Android Chrome/iOS Safari Viewer leaves remain unverified and conservatively leaf-only. Mobile Web Host is unsupported; native senders are planned only.
- Silent partitions can wait 30 to 60 seconds for heartbeat detection before the default 5-second grace; this remains unverified.
-- Real audio and heterogeneous clients remain unverified. Production reports poor film audio and voice-call self-echo under system capture; there is no app audio ceiling or Web process isolation. Diagnose A/B/C and sync, then gate Windows 11 game-process audio; Windows 10 stays unresolved without system fallback.
+- Real audio and heterogeneous clients remain unverified. System capture can lose film audio or echo voice calls; Web has no process isolation. Diagnose A/B/C and sync; gate Windows 11 game audio; Windows 10 unresolved.
- The former release reportedly sustained bandwidth-limited blur on a capable LAN; Host refresh recovered while Viewer refresh did not. The new deployment has not yet reproduced or cleared it.
- ADR-0006 has one Viewer proof; two-edge/FIFO, physical hardware, endurance, public, packaged-native, and browser-diversity proof remain open.
- Browser fanout is host two/viewer one; any accepted endpoint relay stays capped at two downstream edges.
diff --git "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md" "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
index c43c4779..01504ff9 100644
--- "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
+++ "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
@@ -2,7 +2,7 @@
## 2026-08-18 14:45
-状态:首个 PoC 基线及其已接受扩展的当前设计。Production 仍使用 STUN-only ordinary ICE,并只为 room `1` 启用 exact-room peer-assisted 与 LiveKit SFU/UDP。默认关闭的 built-in Peer ICE TURN canary 已失败并回滚,不再是产品方向;下一候选只能在 SFU/UDP 后由 controller 选择单条异常 edge。旧 release 与 coturn relay 仅保留为隔离回滚路径,不是同进程兼容分支。
+状态:首个 PoC 基线及其已接受扩展的当前设计。Production 仍使用 STUN-only ordinary ICE;旗舰进程以 `PEER_ASSISTED_MEDIA=true` 对所有正常房间启用 peer-assisted 与 LiveKit SFU/UDP,room `1` 仅是历史 smoke。默认关闭的 built-in Peer ICE TURN canary 已失败并回滚,不再是产品方向;下一候选只能在 SFU/UDP 后由 controller 选择单条异常 edge。旧 release 与 coturn relay 仅保留为隔离回滚路径,不是同进程兼容分支。
## 目标与边界
@@ -275,9 +275,10 @@ reparent,再在 root budget 内准备 SFU,最终没有可行 route 时返回
旧 release 需要 coturn TURN/UDP+TCP,目前仅作为独立回滚实例保留;current
production 不根据 room allowlist 保留旧 release TURN 兼容分支。
-`PEER_ASSISTED_ROOM_IDS` 灰度 topology/SFU route;未命中房间始终 STUN-only,且
-普通 peer edge 即使命中也不能默认收到 TURN candidates。因此验证与回滚必须使用
-隔离 candidate/旧实例,不能假设同进程未命中房间仍有旧 transport。
+`PEER_ASSISTED_MEDIA` 是 process-wide topology/SFU route 开关;启用后每个房间
+拥有独立 controller 状态,普通 peer edge 仍不能默认收到 TURN candidates。
+`PEER_ASSISTED_ROOM_IDS` 已退役,旧变量必须在迁移时删除。因此验证与回滚必须使用
+隔离 candidate/旧实例,不能假设旧 release 与新 transport 共存。
Selected-edge TURN 复用 `HybridMediaRouter` 的 assignment/revision owner,不新增
第二个路由器或周期优化器。Coturn 只能验证 HMAC 与 expiry,不能自行验证 room、
@@ -374,7 +375,7 @@ hop 按[低服务器成本媒体路由](./research/low-server-media-routes.md)
2. 完成 RoomStore、建房 API、WebSocket 鉴权和定向信令。
3. 完成屏幕捕获、逐观看者 PeerConnection、观看播放和手动质量档。
4. 完成连接恢复和 stats 面板;随后以 STUN-only snapshot 替换旧全房 TURN credential/refresh wire。
-5. 完成 automatic peer/SFU controller 与 exact-room canary 边界。
+5. 完成 automatic peer/SFU controller,并让 room `1` 仅作为历史 smoke fixture。
6. 默认关闭的 selected-edge TURN tuple、revision-bound one-use grant 与 parent/child rebuild 已在 source candidate 闭环;其后再用有界网络矩阵验收 ordinary STUN-only、SFU/UDP、单条 forced relay、资源成本和明确失败,coturn/production rollout 保持独立验收边界。保留现有 benchmark,但统一性能对比不是功能落地前置。
7. 在媒体主线阶段验收后,用一个原子 PR 迁移 Host admission、`screener-v2`、room-scoped Viewer grant 和 SQLite v2;同一部署切换客户端/服务端/环境和数据库备份,随后删除 v1 配置、wire 与测试。用户名/roster 保持独立。
8. P1 继续完成 Windows native fixed-`HIGH` staged gate 与 deployment;移动 Host 不阻断或先于它。
@@ -386,19 +387,17 @@ hop 按[低服务器成本媒体路由](./research/low-server-media-routes.md)
## 2026-08-19 Peer-Assisted 实验边界
历史状态(2026-08-19):Proposed / Experiment Only。后续 ADR-0005 已接受
-bounded controller,且 production 已启用 room `1` exact smoke;下列内容保留为
+bounded controller,且 room `1` 曾作为 exact smoke;下列内容保留为
最初实验门槛,不代表当前 rollout 状态。
-部署设置 `PEER_ASSISTED_MEDIA=true` 时必须同时提供非空的
-`PEER_ASSISTED_ROOM_IDS` 精确限制实验房间。该值只接受逗号分隔、符合现有
-room code 规则且不重复的 ID;缺失、空值或非法配置都启动失败,不存在全房间
-fail-open。未命中房间不得进入
-`HybridMediaRouter`、房间质量同步或 LiveKit 兜底,route 字段、定向信令、停止、
-重连和删除保持普通 P2P 行为;未命中房间的 ordinary ICE 始终 STUN-only,
-不接收 TURN config。命中房间的 ordinary peer PC 与 Native v2 同样保持 STUN-only;
-只有 controller-selected edge 可接收一次短期 grant。该边界不增加 UI、用户选择或百分比框架。
+当前部署设置 `PEER_ASSISTED_MEDIA=true` 后,所有正常房间进入
+`HybridMediaRouter`、房间质量同步和 LiveKit 兜底;每个房间的 route 字段、定向
+信令、停止、重连和删除状态仍独立。`PEER_ASSISTED_ROOM_IDS` 已退役并在启动时拒绝,
+不能以旧变量隐式限制到 room `1`。所有 ordinary peer PC 与 Native v2 仍保持
+STUN-only;只有 controller-selected edge 可接收一次短期 grant。该边界不增加 UI、
+用户选择或百分比框架。
-产品硬目标是任一非服务器节点任何时刻最多两条下游媒体边。系统按一个或两个观看者直接 P2P、更多观看者 peer-assisted、部署 SFU 中央兜底、最后 selected-edge TURN 的顺序自动分配和恢复,分享者与观看者不选择拓扑。默认媒体 transport 只使用 UDP;SFU 作为 virtual parent 正常只送一至两个 roots,roots 之后仍优先沿受限 peer descendants 扩散;多个无法挂到健康 root 的极端 viewers 只可使用另设上限的中央 edge。Production 已把普通 ICE 收敛为 STUN-only、删除旧全房 TURN wire并只为 room `1` 开启 failure-only controller;source 也已删除失败的 participant-wide built-in code/wire,旧 `PEER_ICE_TURN_*` 配置启动失败,replacement selected-edge 已完成 source candidate 但尚未部署。exact-room 公网 SFU media、selected relay 与资源仍未验收,旧 release/coturn 仅作回滚。ADR-0004/0005 的 broad-rollout 验收尚未完成。
+产品硬目标是任一非服务器节点任何时刻最多两条下游媒体边。系统按一个或两个观看者直接 P2P、更多观看者 peer-assisted、部署 SFU 中央兜底、最后 selected-edge TURN 的顺序自动分配和恢复,分享者与观看者不选择拓扑。默认媒体 transport 只使用 UDP;SFU 作为 virtual parent 正常只送一至两个 roots,roots 之后仍优先沿受限 peer descendants 扩散;多个无法挂到健康 root 的极端 viewers 只可使用另设上限的中央 edge。Production 已把普通 ICE 收敛为 STUN-only、删除旧全房 TURN wire;source 对所有启用的房间使用同一 failure-only controller,旧 `PEER_ICE_TURN_*` 配置启动失败,replacement selected-edge 已完成 source candidate 但尚未部署。公网 SFU media、selected relay 与资源仍未验收,旧 release/coturn 仅作回滚。ADR-0004/0005 的媒体验收尚未完成。
恢复目标按证据和成本逐级升级:短暂 `disconnected` 先观察同代 bytes/stats,`failed` 才执行一次 ICE restart;仍失败时重建一次相同 parent,再尝试不同的合格 peer parent,peer 候选耗尽后才申请 SFU。每个动作最多一次且成功即停,不实现“三次相同重试”。初始 `connecting`/`checking` 的软提示和硬窗口尚未实现;硬窗口必须先用移动网络实测确定,不能直接复用现有 3 秒恢复常量。Viewer SFU root 只刷新一次短期 grant,随后至多重建一次原 failed parent selected edge;Host publisher/global SFU failure 维持 bounded peer failback。Host 只保留当前 route revision 的 `connect | source | video-publish | sender-config | audio-publish | transport` 枚举阶段作为本地事件提示,不上传原始错误、URL、token、candidate 或地址。
diff --git "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md" "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"
index 8d4915e9..5b44aaee 100644
--- "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"
+++ "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"
@@ -4,6 +4,10 @@
## 需求概述
+### 2026-08-21 路由范围修订
+
+`PEER_ASSISTED_MEDIA=true` 是旗舰部署的单一总开关,启用后所有正常房间都使用同一个 direct/peer UDP -> SFU/UDP -> selected-edge TURN 决策控制器;每个房间仍独立保存 route revision、会话代次、失败状态和容量预算。`PEER_ASSISTED_ROOM_IDS` 已退役,旧变量必须在迁移时删除,不能再把 room `1` 当作功能开关。room `1` 只保留为历史 smoke fixture。普通 peer 连接继续 STUN-only,TURN 仍只向 controller 选中的受限 edge 短期发放。
+
构建一个面向熟人游戏场景的低延迟屏幕共享工具。分享者可以在私密房间内分享游戏、应用窗口或显示器画面及声音,多名朋友可以即时观看。系统采用类似 Photon Host Mode 的产品抽象:中心服务负责房间、身份、确定性拓扑和建立连接,媒体优先级依次为小规模 direct/peer UDP、部署提供的 SFU/UDP virtual parent、可选的 authenticated selected-edge TURN,最后明确失败;SFU 只向一至两个必要 roots 送流,roots 继续分布式服务其 peer descendants。TURN 是默认关闭的异常边 transport,不是拓扑,也不得默认加入普通 peer edge 的 candidates。系统必须自动、无感地完成分配、故障恢复和必要的路线迁移,分享者与观看者不手动选择拓扑。分享端 Web 优先并允许后续 Electron/原生增强;观看端必须可通过桌面或手机浏览器打开邀请链接,不绑定专用客户端。
当前 PoC 默认允许一名分享者和最多八名观看者,部署者可在 1 至 16 之间配置上限,超额观看者会被明确拒绝。已接受的自动分布式拓扑目标把默认值和可配置上限提高到 20,但只能与通过 20 人资源、质量、深度和恢复门禁的路由 release 原子启用;在此之前不得只改常量,让普通逐观看者 P2P 建立 20 条 Host 边。产品仍不承担公开直播或大规模观看,相关需求交给 OBS/Twitch 等成熟直播服务。
@@ -37,7 +41,7 @@
- [ ] 私密房间双入口:在不引入账号、密码找回或通用服务端 session 的前提下,private room 同时接受“房间号 + 该房间观看密码”和现有 `/r/{code}#v={grant}` 私密邀请;有效 grant 直接进入目标房间,没有 grant 的 `/join` 或 `/r/{code}` 只显示中性的房间密码输入。Host 可设置、轮换或移除房间观看密码。密码接受 1 至 64 个可见 ASCII 字符,不要求字符组合复杂度;服务端先以固定保守参数的 Node 异步 scrypt 落地,全局最多执行 2 个、等待 16 个派生,取槽后跳过 stale session,目标 1 GiB 部署机的参数 benchmark 与优化在功能部署后进行。房间密码、grant 与 verifier 的权限都只能是该房间 Viewer;明文密码不得进入 URL/query/cookie、`localStorage`、`sessionStorage`、日志或 SQLite,也不能取得 Host admission、建房、发布或跨房权限。不存在、错误密码、队满和正确密码后的满房都返回通用结果。当前源码候选已实现该最小闭环,线上仍未部署。
-- [ ] 实验路由按房间灰度:部署开启 `PEER_ASSISTED_MEDIA` 时必须同时提供非空、严格的房间 ID allowlist,只有指定房间进入 peer-assisted 与已配置的 SFU 路径;缺失、空值、非法或重复配置启动即失败,绝不 fail-open 为全房。未命中房间继续使用当前 ordinary P2P 拓扑及其质量拒绝、停止、重连和删除语义,并保持 STUN-only。未来 selected-edge TURN 只能复用同一 controller 的当前 assignment/session/revision/connection generation,不得借 allowlist 向普通 peer edge 预发 TURN candidates。旧 production release 与新 candidate 必须用隔离实例验证和回滚,不能在产品代码建立长期双 transport 分支。exact-room 只服务本阶段验证;验收后以独立 coherent change 退役灰度边界,不能靠清空变量暗中放量。该能力不增加 UI、用户选择、百分比发布或第二套路由器。
+- [ ] 统一自动路由:旗舰部署开启 `PEER_ASSISTED_MEDIA` 后,所有正常房间都进入同一个 direct/peer -> SFU -> selected-edge controller;每个房间独立保存 assignment/session/revision/connection generation 和容量状态。`PEER_ASSISTED_ROOM_IDS` 已退役,room `1` 只作为历史 smoke fixture,不能作为功能开关。未启用总开关的开发/轻量部署仍可保留 ordinary P2P;普通 peer 始终 STUN-only。selected-edge TURN 只能复用当前 controller 选中的异常 edge,不能向普通 peer edge 预发 candidates。该能力不增加 UI、用户选择、百分比发布或第二套路由器。
- [ ] 质量控制扩展:推荐档位仍是默认入口;折叠高级区只允许 720p/1080p/1440p 分辨率 ceiling、15 至 60 的整数 FPS ceiling、2 至 12 Mbps 视频码率 ceiling,以及清晰/平衡/流畅三种偏好。直播中显式应用后才生效,避免滑杆产生连续控制流量。当前 Web 发送端不提供音频声道、采样率、Opus 码率、stereo、DTX 或 FEC 控件:display capture 未把声道和采样率定义为可移植控制,标准音频 `maxBitrate` 只是可能导致更低质量或停播的发送上限,其他项依赖 codec/fmtp 协商而没有可移植 sender setter。除非真实音频矩阵证明用户问题、标准 API 能应用并读回且实际结果可独立观测,否则不得为这些控件新增应用层 SDP munging 或用默认值制造伪控制。实际质量持续低于所选上限时必须显示可解释的限制原因;在真实拥塞、编码器和接收端证据完成前,不把任一组合称为“完美平衡”。
- [ ] 本地预览性能候选:在相同动态场景中 A/B 测量 Host 动态预览开/关的 CPU、GPU、encode time 和实际 FPS。只有稳定收益且捕获、编码和远端画面不受影响时,才允许直播开始后默认显示静止缩略图或隐藏动态预览并提供按需展开;未测前不宣称收益。
@@ -46,11 +50,11 @@
- [ ] 原生 shared encode relay:具备原生 relay 能力的 audience 同样最多维护两条下游媒体边,并应复用兼容编码输出而不再次编码。普通浏览器 audience 继续作为 leaf 或使用当前会逐跳重编码的实验路径,不伪称 shared encode。
- [ ] SVC 重开条件:当前标准 Web/LiveKit SVC 已静态拒绝为 `no-go-web-svc-cross-path-hardware-contract`。sender `scalabilityMode` 没有 direct/peer receiver 对应的按层选择或跨 PeerConnection shared-encode 契约;requested/applied mode、Media Capabilities `powerEfficient` 和 RTCStats encoder 字段也不能证明没有静默软件 fallback。Pinned client 2.22.0 还会把 screen-share SVC 覆盖为三层 temporal-only `L1T3`,不满足低分辨率 base 与最多两层。只有未来 native sender 能明确选择硬件编码器、最多发布两层、将同一编码输出复用于 direct/peer/SFU、保持每条路径独立选择并通过真实游戏和亚秒延迟门槛时,才可用新的 capability decision 重开 SVC;不能把浏览器 API 支持或 UA 推断当成采用理由。
- [ ] 分包/分层多树实验:把编码包、对象或可独立解码层拆到多个 peer 路径以分散上传,只能在独立 spike 中验证。必须保持亚秒级,处理多父重组、排序、丢包恢复、关键帧、同步和节点退出;未通过门槛前不进入产品路由控制器。
-- [ ] SFU-root 中央兜底:产品部署目标必须提供经 canary 验收的单节点 SFU 资源;系统在 direct/peer UDP 不可用或明确拓扑预算无法接纳时自动把它作为主要中央兜底,不要求用户选模式。它只向总计一至两个必要 roots 出口;root 优先承担受限 peer descendants,没有可靠 relay root 时必要 viewer 只作为同一总上限内的零 descendants root。已关闭 PR #12 的显式整房 SFU 模式已被取代。Production room `1` 已开启 failure-only exact-room smoke,但尚无 retained SFU media;通过 ADR-0005 的公网媒体、资源和恢复门禁后才能扩大到默认梯级。
+- [ ] SFU-root 中央兜底:产品部署目标必须提供经 canary 验收的单节点 SFU 资源;系统在 direct/peer UDP 不可用或明确拓扑预算无法接纳时自动把它作为主要中央兜底,不要求用户选模式。它只向总计一至两个必要 roots 出口;root 优先承担受限 peer descendants,没有可靠 relay root 时必要 viewer 只作为同一总上限内的零 descendants root。已关闭 PR #12 的显式整房 SFU 模式已被取代。room `1` 的历史 smoke 没有 retained SFU media;公网媒体、资源和恢复门禁仍适用于全站路由。
- [ ] 分享端桌面封装:用 Electron 固定 Chromium 版本、改善选源/热键/系统音频体验,同时保留 Web 观看端。
- [ ] Windows 应用音频:Windows 11 原生候选默认仅捕获所选游戏及其子进程的音频,避免把语音聊天或通知声一并分享;“全部系统声音”只能由分享者显式选择。普通 Windows 10 不具备当前 process-loopback API 门槛,必须明确标为未解决/不支持而不是伪兼容。浏览器无法证明或隔离任意进程音频时必须如实提示,原生捕获失败、无声或进程退出不得静默扩大为整机捕获。
- [ ] 连接自检:在开始分享前验证信令、STUN 和 SFU ICE/UDP 可达性,并给出不暴露地址或凭据的诊断结果。启用 selected-edge TURN canary 时只报告脱敏的授权阶段与 selected candidate type,不输出 URL、username、credential、地址或原始 candidate;媒体 TCP 不在当前配置面。
-- [ ] 受限网络增强:短期鉴权 TURN 只能由完整、默认关闭的部署 tuple 与 exact-room controller 启用,并且只能在 direct/peer UDP 与 SFU/UDP 均已按有界梯级失败后,向 controller 选中的当前异常 edge 一次性授权。普通 peer PC 从创建起保持 STUN-only;不得向整个 participant、房间或所有 peer connections 预发 TURN candidates。凭据必须绑定当前授权 session 与 route/connection generation、短期有效、内存态、一次性消费且不进入 URL、日志、浏览器持久化或 SQLite。媒体 TCP 仍需独立 canary;两者都不能被描述为更高清的传输方式。
+- [ ] 受限网络增强:短期鉴权 TURN 只能由完整、默认关闭的部署 tuple 与当前 room controller 启用,并且只能在 direct/peer UDP 与 SFU/UDP 均已按有界梯级失败后,向 controller 选中的当前异常 edge 一次性授权。普通 peer PC 从创建起保持 STUN-only;不得向整个 participant、房间或所有 peer connections 预发 TURN candidates。凭据必须绑定当前授权 session 与 route/connection generation、短期有效、内存态、一次性消费且不进入 URL、日志、浏览器持久化或 SQLite。媒体 TCP 仍需独立 canary;两者都不能被描述为更高清的传输方式。
- [ ] 运行时编解码选择:先保留浏览器默认协商;只有端点能力相交、Media Capabilities 对目标分辨率/FPS/码率报告 supported/smooth/power-efficient,且实际 outbound codec、区间 encode time、游戏 FPS、CPU/GPU 与 sender 数量共同通过时,才调整 H.264、VP8、VP9 或 AV1 优先级。AV1 不得因压缩率推断而默认启用,任何候选都不得静默落入高负载软件编码。
- [ ] 诊断页面:用户可导出不含敏感地址和凭据的连接诊断信息。
@@ -81,7 +85,7 @@
- 当前八名观看者和 1 至 16 配置范围是接入边界;目标默认 20 也只是通过指定矩阵后的接入边界,不承诺任意机器、档位、网络或跨洲路径都稳定承载。
- 浏览器规范要求每次由用户主动选择分享源,权限不能永久保存;纯网页不能保证指定游戏窗口或始终获得系统音频。
- 1080p60 是能力目标,实际分辨率、帧率和硬件编码由浏览器、GPU、驱动、画面复杂度及网络共同决定。
-- 当前 production 的未命中房间仍是标准 WebRTC P2P,room `1` 已部署 peer-assisted/SFU 跨模式 controller。Peer relay 只复用标准 remote-track WebRTC,不加入 Encoded Transform/DataChannel/WebCodecs 媒体协议,也不自研 UDP、编解码器、拥塞控制、FEC/RTX、多树、转码、codec ladder 或综合评分器。独立 native shared encode sender 不在本实验内,也不能挽救拓扑门槛失败;跨模式迁移继续由 ADR-0005 的 generation 与 edge budget 约束,不使用短时双发。
+- 旗舰 release 的正常房间都可使用 peer-assisted/SFU 跨模式 controller;部署未启用总开关的轻量实例才保持标准 WebRTC P2P。Peer relay 只复用标准 remote-track WebRTC,不加入 Encoded Transform/DataChannel/WebCodecs 媒体协议,也不自研 UDP、编解码器、拥塞控制、FEC/RTX、多树、转码、codec ladder 或综合评分器。独立 native shared encode sender 不在本实验内,也不能挽救拓扑门槛失败;跨模式迁移继续由 ADR-0005 的 generation 与 edge budget 约束,不使用短时双发。
- GPL/AGPL 项目在许可证策略确认前仅用于研究,不能直接复制到计划闭源的产品中。
## 验收标准
@@ -107,7 +111,7 @@
- Given 两端网络允许 UDP 打洞,When 观看者加入,Then `getStats()` 显示选中的候选对不是 `relay`,且服务器没有承载媒体流量。
- Given direct/peer UDP 无法建立但 LiveKit SFU/UDP 可达,When 观看者加入或现有 edge 恢复耗尽,Then 系统只把必要 root 切到 SFU,保留可行 peer descendants 和未受影响路径,无需用户选择模式。
- Given 未配置 TURN 且所有媒体 UDP 路径均不可用,When 有界连接窗口耗尽,Then 界面快速显示通用连接失败,不静默黑屏、不长时间假连接,也不自动尝试媒体 TCP。
-- Given 未配置完整 selected-edge TURN tuple、房间未命中 exact allowlist、当前 route/connection generation 不匹配或该 edge 未经过 controller 选择,When 会话鉴权、peer PC 创建或旧消息重放,Then authenticated snapshot 与 ordinary peer PC 必须保持 STUN-only,服务端不得签发或接受该 TURN grant;不得把 credential 发给 Native v2、普通房间或未鉴权会话。
+- Given 未配置完整 selected-edge TURN tuple、当前 route/connection generation 不匹配或该 edge 未经过 controller 选择,When 会话鉴权、peer PC 创建或旧消息重放,Then authenticated snapshot 与 ordinary peer PC 必须保持 STUN-only,服务端不得签发或接受该 TURN grant;不得把 credential 发给 Native v2、普通房间或未鉴权会话。
- Given 当前异常 edge 已耗尽 direct/peer UDP 与 SFU/UDP 且 controller 授权一次 selected-edge TURN attempt,When parent 与 child 以同一 session/revision/old-and-new connection generation 重建,Then 只有该新 PC 使用 relay-only 短期 credential;成功即停止,失败或过期即消费并明确失败,不得把 bearer 复用于其他 edge、后续 PC 或整个 participant。
- Given 部署者为 LiveKit 启用了 embedded/external TURN,When publisher 或 subscriber 的 SFU/UDP 路径耗尽,Then 只把它作为 LiveKit participant-to-SFU 兼容 transport 单独验收;它不是 Screener selected peer-edge grant,也不得改变 controller 的默认梯级。
- Given 部署者另行启用并验收媒体 TCP/TLS 兼容模式,When UDP 被封锁,Then 对应路径建立或返回可诊断失败;未启用该能力不阻塞面向消费网络的旗舰验收,HTTPS/WSS 仍正常使用 TLS/TCP。
@@ -126,7 +130,7 @@
- Given 一名分享者和一至两名观看者,When 运行直接 P2P,Then 分享端为每人建立独立媒体边且总 fanout 不超过二。
- Given peer-assisted spike 分别运行 1、3、5、8 名观看者,When 用户加入、离开或 relay 失效,Then 服务端使用同一个确定性广度优先规则形成两条 sticky 链,只为新 viewer 或失去 parent 的 subtree root 分配 parent;唯一的健康边搬动例外是:无上游的一槽 relay 在纯 peer active route、无 pending/SFU、Host 两槽已满时,按加入序把一个 childless、零容量 Host leaf 放到自己下游。分享端在任何瞬间都不超过两个 child 且每名 viewer 不超过一个;除此之外没有可用 parent 时明确等待或拒绝,不主动重平衡或增加分享端 fanout。
- Given 一名分享者和八名观看者,When 在受控网络中运行已记录的质量档位,Then 记录每条边的拓扑深度、候选类型、码率、编码/解码负载、分享端与 relay 上行、首帧和玻璃到玻璃延迟;该条在真实矩阵完成前保持未验收。
-- Given candidate 将房间默认上限改为 20,When 在 exact-room 中连续运行 20 名观看者 30 分钟并注入 relay departure、重连和一个弱路径,Then 每名观看者持续解码、Host 下游边不超过二、每个 relay 不超过已验收能力、深度与故障半径有界、未受影响 subtree 不迁移,并记录端点/SFU 的 CPU、GPU、内存、上行、出口、帧率、丢包率、冻结和恢复;任一门槛失败时不得切换默认值。
+- Given candidate 将房间默认上限改为 20,When 在历史 room-1 smoke fixture 或其他正常房间中连续运行 20 名观看者 30 分钟并注入 relay departure、重连和一个弱路径,Then 每名观看者持续解码、Host 下游边不超过二、每个 relay 不超过已验收能力、深度与故障半径有界、未受影响 subtree 不迁移,并记录端点/SFU 的 CPU、GPU、内存、上行、出口、帧率、丢包率、冻结和恢复;任一门槛失败时不得切换默认值。
- Given peer-assisted host 鉴权或直播中连续修改质量设置,When 服务端校验其分辨率、FPS、码率和偏好,Then 只有 host 的完整有界设置被接受,last-wins 地应用到当前和以后建立的 relay child sender 以及启用的 SFU publisher;越界、缺字段和多余字段被拒绝,普通 P2P 的鉴权 wire 不新增该字段且不接受同步消息。
- Given 标准浏览器把收到的 remote track 直接加入下游 `RTCPeerConnection`,When 检查 relay 统计和 libwebrtc 路径,Then 明确记录新的 outbound encoder、编码耗时和 CPU/GPU 限制,不把它当作 encoded forwarding 或 shared encode 成果。
- Given ADR-0004 的任一硬门槛只有在引入 Encoded Transform/DataChannel/WebCodecs 媒体、自定义拥塞控制、FEC/RTX、多树、综合评分、转码、codec ladder、浏览器 RTP 注入 hack 或放宽 host fanout 后才能满足,When 结束 bounded spike,Then 放弃并删除浏览器 relay 实验运行时代码,保留标准 P2P 和 SFU-root fallback;后续 native shared encode sender 仍按独立 ADR 推进,但不能据此把失败的 relay 拓扑判为通过。
diff --git a/scripts/native-one-viewer-gate.ts b/scripts/native-one-viewer-gate.ts
index 5a3b4d2a..56f613b7 100644
--- a/scripts/native-one-viewer-gate.ts
+++ b/scripts/native-one-viewer-gate.ts
@@ -318,7 +318,6 @@ async function main(): Promise<void> {
HOST_ADMISSION_PASSWORD: accessKey,
ROOM_DATABASE_PATH: "",
PEER_ASSISTED_MEDIA: "false",
- PEER_ASSISTED_ROOM_IDS: "",
STUN_URLS: "",
});
const roomStore = new ObservedRoomStore({
diff --git a/scripts/peer-assisted-benchmark.ts b/scripts/peer-assisted-benchmark.ts
index 44ea5b9e..3ac4d6b8 100644
--- a/scripts/peer-assisted-benchmark.ts
+++ b/scripts/peer-assisted-benchmark.ts
@@ -14,7 +14,6 @@ import {
import { loadConfig } from "../src/server/config";
import {
RoomStore,
- type RoomStoreOptions,
} from "../src/server/room-store";
import {
QUALITY_PROFILES,
@@ -28,21 +27,6 @@ const PROFILE_SETTINGS = QUALITY_PROFILES;
type ProfileId = QualityProfileId;
type PageRole = "host" | "viewer";
-class BenchmarkRoomStore extends RoomStore {
- constructor(
- options: RoomStoreOptions,
- private readonly exactPeerRooms: Set<string>,
- ) {
- super(options);
- }
-
- override createRoom() {
- const room = super.createRoom();
- this.exactPeerRooms.add(room.roomId);
- return room;
- }
-}
-
export interface BenchmarkConfig {
chromePath: string;
viewerCounts: number[];
@@ -2162,7 +2146,6 @@ export async function main(): Promise<number> {
const debugPort = await reservePort();
const baseUrl = `http://127.0.0.1:${appPort}`;
profileDirectory = await mkdtemp(join(tmpdir(), "screener-peer-benchmark-"));
- const exactPeerRooms = new Set(["1"]);
const serverConfig = loadConfig({
NODE_ENV: "development",
PORT: String(appPort),
@@ -2171,21 +2154,16 @@ export async function main(): Promise<number> {
ALLOWED_ORIGINS: baseUrl,
ROOM_DATABASE_PATH: "",
PEER_ASSISTED_MEDIA: "true",
- PEER_ASSISTED_ROOM_IDS: "1",
MAX_VIEWERS_PER_ROOM: String(Math.max(...config.viewerCounts)),
STUN_URLS: "",
});
- serverConfig.peerAssistedRoomIds = exactPeerRooms;
server = await createScreenerServer({
config: serverConfig,
- roomStore: new BenchmarkRoomStore(
- {
- ttlMs: serverConfig.roomTtlMs,
- maxRooms: serverConfig.maxRooms,
- maxViewersPerRoom: serverConfig.maxViewersPerRoom,
- },
- exactPeerRooms,
- ),
+ roomStore: new RoomStore({
+ ttlMs: serverConfig.roomTtlMs,
+ maxRooms: serverConfig.maxRooms,
+ maxViewersPerRoom: serverConfig.maxViewersPerRoom,
+ }),
});
await server.listen(appPort, "127.0.0.1");
diff --git a/src/server/app.ts b/src/server/app.ts
index c4483641..918da282 100644
--- a/src/server/app.ts
+++ b/src/server/app.ts
@@ -111,7 +111,6 @@ export async function createScreenerServer(
server: httpServer,
roomStore,
peerAssistedMedia: config.peerAssistedMedia,
- peerAssistedRoomIds: config.peerAssistedRoomIds,
...(sfuFallback ? { sfuFallback } : {}),
...(config.selectedEdgeTurn ? { selectedEdgeTurn: config.selectedEdgeTurn } : {}),
ice: iceOptions,
diff --git a/src/server/config.ts b/src/server/config.ts
index 78db1643..88867b5f 100644
--- a/src/server/config.ts
+++ b/src/server/config.ts
@@ -1,7 +1,6 @@
import {
MAX_ICE_SERVER_URLS,
MAX_VIEWERS_PER_ROOM_LIMIT,
- roomCodeSchema,
stunUrlSchema,
turnUrlSchema,
} from "../shared/protocol.js";
@@ -20,13 +19,14 @@ const DEFAULT_MAX_VIEWERS_PER_ROOM = 8;
const DEFAULT_MAX_SFU_ROOTS_PER_ROOM = 2;
const MAX_SFU_ROOTS_PER_ROOM = 2;
const VISIBLE_ASCII_PATTERN = /^[\x21-\x7e]+$/;
-const REMOVED_TURN_ENVIRONMENT_VARIABLES = [
+const REMOVED_ENVIRONMENT_VARIABLES = [
"TURN_URLS",
"TURN_SHARED_SECRET",
"TURN_CREDENTIAL_TTL_SECONDS",
"PEER_ICE_TURN_URLS",
"PEER_ICE_TURN_SHARED_SECRET",
"PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS",
+ "PEER_ASSISTED_ROOM_IDS",
] as const;
export interface LiveKitFallbackConfig {
@@ -54,7 +54,6 @@ export interface ServerConfig {
maxRooms: number;
maxViewersPerRoom: number;
peerAssistedMedia: boolean;
- peerAssistedRoomIds?: ReadonlySet<string>;
livekitFallback?: LiveKitFallbackConfig;
selectedEdgeTurn?: SelectedEdgeTurnConfig;
stunUrls: readonly string[];
@@ -256,32 +255,6 @@ function parseOrigins(value: string | undefined, fallback: string): Set<string>
return new Set((origins.length > 0 ? origins : [fallback]).map(toOrigin));
}
-function parsePeerAssistedRoomIds(
- value: string | undefined,
-): ReadonlySet<string> | undefined {
- if (value === undefined || value.trim() === "") {
- return undefined;
- }
-
- const roomIds = new Set<string>();
- for (const entry of value.split(",")) {
- const roomId = entry.trim();
- if (!roomId) {
- throw new Error("PEER_ASSISTED_ROOM_IDS contains an empty room ID");
- }
- if (!roomCodeSchema.safeParse(roomId).success) {
- throw new Error(
- "PEER_ASSISTED_ROOM_IDS must contain comma-separated valid room IDs",
- );
- }
- if (roomIds.has(roomId)) {
- throw new Error(`PEER_ASSISTED_ROOM_IDS contains duplicate room ID ${roomId}`);
- }
- roomIds.add(roomId);
- }
- return roomIds;
-}
-
function toOrigin(value: string): string {
const url = new URL(value);
if (url.protocol !== "http:" && url.protocol !== "https:") {
@@ -293,10 +266,12 @@ function toOrigin(value: string): string {
export function loadConfig(
environment: NodeJS.ProcessEnv = process.env,
): ServerConfig {
- for (const name of REMOVED_TURN_ENVIRONMENT_VARIABLES) {
+ for (const name of REMOVED_ENVIRONMENT_VARIABLES) {
if (Object.prototype.hasOwnProperty.call(environment, name)) {
throw new Error(
- `${name} is no longer supported; ordinary ICE accepts STUN_URLS only`,
+ name === "PEER_ASSISTED_ROOM_IDS"
+ ? `${name} is no longer supported; peer-assisted media applies to every room when enabled`
+ : `${name} is no longer supported; ordinary ICE accepts STUN_URLS only`,
);
}
}
@@ -356,22 +331,9 @@ export function loadConfig(
false,
"PEER_ASSISTED_MEDIA",
);
- const peerAssistedRoomIds = parsePeerAssistedRoomIds(
- environment.PEER_ASSISTED_ROOM_IDS,
- );
const livekitFallback = parseLiveKitFallback(environment, nodeEnv);
const selectedEdgeTurn = parseSelectedEdgeTurn(environment);
- if (peerAssistedRoomIds && !peerAssistedMedia) {
- throw new Error(
- "PEER_ASSISTED_ROOM_IDS requires PEER_ASSISTED_MEDIA=true",
- );
- }
- if (peerAssistedMedia && !peerAssistedRoomIds) {
- throw new Error(
- "PEER_ASSISTED_MEDIA=true requires non-empty PEER_ASSISTED_ROOM_IDS",
- );
- }
if (livekitFallback && !peerAssistedMedia) {
throw new Error("LiveKit fallback requires PEER_ASSISTED_MEDIA=true");
}
@@ -438,7 +400,6 @@ export function loadConfig(
maxRooms: parsePositiveInteger(environment.MAX_ROOMS, 1_000, "MAX_ROOMS"),
maxViewersPerRoom,
peerAssistedMedia,
- peerAssistedRoomIds,
livekitFallback,
selectedEdgeTurn,
stunUrls,
diff --git a/src/server/signaling.ts b/src/server/signaling.ts
index 98f33e1f..5b6781fc 100644
--- a/src/server/signaling.ts
+++ b/src/server/signaling.ts
@@ -76,7 +76,6 @@ export interface SignalingOptions {
server: HttpServer;
roomStore: RoomStore;
peerAssistedMedia: boolean;
- peerAssistedRoomIds?: ReadonlySet<string>;
sfuFallback?: SfuFallbackOptions;
selectedEdgeTurn?: SelectedEdgeTurnConfig;
ice: IceConfigOptions;
@@ -142,15 +141,6 @@ export class SignalingServer {
if (options.sfuFallback && !options.peerAssistedMedia) {
throw new Error("SFU fallback requires peer-assisted media");
}
- if (options.peerAssistedRoomIds && !options.peerAssistedMedia) {
- throw new Error("Peer-assisted room IDs require peer-assisted media");
- }
- if (
- options.peerAssistedMedia &&
- (!options.peerAssistedRoomIds || options.peerAssistedRoomIds.size === 0)
- ) {
- throw new Error("Peer-assisted media requires exact room IDs");
- }
if (options.peerAssistedMedia) {
this.hybridMediaRouter = new HybridMediaRouter({
roomStore: options.roomStore,
@@ -1417,10 +1407,10 @@ export class SignalingServer {
}
private isPeerAssistedRoom(roomId: string): boolean {
- if (!this.hybridMediaRouter) {
- return false;
- }
- return this.options.peerAssistedRoomIds?.has(roomId) ?? false;
+ // The controller owns independent per-room state; the process flag is the
+ // only rollout switch. Keep the room argument at call sites for clarity.
+ void roomId;
+ return this.hybridMediaRouter !== undefined;
}
private hasConnectionCapacity(): boolean {
diff --git a/tests/server-config.test.ts b/tests/server-config.test.ts
index dc012f72..9cc55cc6 100644
--- a/tests/server-config.test.ts
+++ b/tests/server-config.test.ts
@@ -12,7 +12,6 @@ describe("server configuration", () => {
expect(config.stunUrls).toEqual([]);
expect(config.maxViewersPerRoom).toBe(8);
expect(config.peerAssistedMedia).toBe(false);
- expect(config.peerAssistedRoomIds).toBeUndefined();
expect(config.livekitFallback).toBeUndefined();
expect(config.selectedEdgeTurn).toBeUndefined();
});
@@ -20,7 +19,6 @@ describe("server configuration", () => {
it("enables selected-edge TURN only from its complete post-SFU tuple", () => {
const base = {
PEER_ASSISTED_MEDIA: "true",
- PEER_ASSISTED_ROOM_IDS: "1",
LIVEKIT_URL: "wss://livekit.test",
LIVEKIT_API_KEY: "test-key",
LIVEKIT_API_SECRET: "s".repeat(32),
@@ -52,7 +50,6 @@ describe("server configuration", () => {
expect(() =>
loadConfig({
PEER_ASSISTED_MEDIA: "true",
- PEER_ASSISTED_ROOM_IDS: "1",
LIVEKIT_URL: "wss://livekit.test",
LIVEKIT_API_KEY: "test-key",
LIVEKIT_API_SECRET: "s".repeat(32),
@@ -66,7 +63,6 @@ describe("server configuration", () => {
it("enables LiveKit fallback only for a complete credential tuple", () => {
const config = loadConfig({
PEER_ASSISTED_MEDIA: "true",
- PEER_ASSISTED_ROOM_IDS: "1",
LIVEKIT_URL: " ws://livekit.test:7880 ",
LIVEKIT_API_KEY: " test-key ",
LIVEKIT_API_SECRET: ` ${"s".repeat(32)} `,
@@ -85,7 +81,6 @@ describe("server configuration", () => {
(maxSfuRootsPerRoom) => {
const config = loadConfig({
PEER_ASSISTED_MEDIA: "true",
- PEER_ASSISTED_ROOM_IDS: "1",
LIVEKIT_URL: "wss://livekit.test",
LIVEKIT_API_KEY: "test-key",
LIVEKIT_API_SECRET: "s".repeat(32),
@@ -152,7 +147,6 @@ describe("server configuration", () => {
PUBLIC_BASE_URL: "https://share.test",
STUN_URLS: "stun:stun.test:3478",
PEER_ASSISTED_MEDIA: "true",
- PEER_ASSISTED_ROOM_IDS: "1",
LIVEKIT_URL: "ws://livekit.test:7880",
LIVEKIT_API_KEY: "test-key",
LIVEKIT_API_SECRET: "s".repeat(32),
@@ -184,14 +178,12 @@ describe("server configuration", () => {
{
HOST_ADMISSION_PASSWORD: "x".repeat(32),
PEER_ASSISTED_MEDIA: "true",
- PEER_ASSISTED_ROOM_IDS: "1",
LIVEKIT_URL: "wss://livekit.test",
LIVEKIT_API_KEY: "test-key",
LIVEKIT_API_SECRET: "x".repeat(32),
},
{
PEER_ASSISTED_MEDIA: "true",
- PEER_ASSISTED_ROOM_IDS: "1",
LIVEKIT_URL: "wss://livekit.test",
LIVEKIT_API_KEY: "x".repeat(32),
LIVEKIT_API_SECRET: "x".repeat(32),
@@ -206,7 +198,6 @@ describe("server configuration", () => {
expect(
loadConfig({
PEER_ASSISTED_MEDIA: "true",
- PEER_ASSISTED_ROOM_IDS: "1",
}).peerAssistedMedia,
).toBe(true);
expect(loadConfig({ PEER_ASSISTED_MEDIA: "false" }).peerAssistedMedia).toBe(
@@ -218,7 +209,6 @@ describe("server configuration", () => {
expect(() =>
loadConfig({
PEER_ASSISTED_MEDIA: "true",
- PEER_ASSISTED_ROOM_IDS: "1",
MAX_VIEWERS_PER_ROOM: "9",
}),
).toThrow(
@@ -226,48 +216,15 @@ describe("server configuration", () => {
);
});
- it("requires and parses a strict peer-assisted room allowlist", () => {
- expect(
- loadConfig({
- PEER_ASSISTED_MEDIA: "true",
- PEER_ASSISTED_ROOM_IDS: " 1,123456789012 ",
- }).peerAssistedRoomIds,
- ).toEqual(new Set(["1", "123456789012"]));
- for (const peerAssistedRoomIds of [undefined, " "]) {
- expect(() =>
- loadConfig({
- PEER_ASSISTED_MEDIA: "true",
- ...(peerAssistedRoomIds === undefined
- ? {}
- : { PEER_ASSISTED_ROOM_IDS: peerAssistedRoomIds }),
- }),
- ).toThrow(
- "PEER_ASSISTED_MEDIA=true requires non-empty PEER_ASSISTED_ROOM_IDS",
- );
- }
- });
-
- it("requires peer-assisted media for a non-empty room allowlist", () => {
+ it("enables the hybrid controller for every room when selected", () => {
+ expect(loadConfig({ PEER_ASSISTED_MEDIA: "true" }).peerAssistedMedia).toBe(
+ true,
+ );
expect(() =>
- loadConfig({
- PEER_ASSISTED_MEDIA: "false",
- PEER_ASSISTED_ROOM_IDS: "1",
- }),
- ).toThrow("PEER_ASSISTED_ROOM_IDS requires PEER_ASSISTED_MEDIA=true");
+ loadConfig({ PEER_ASSISTED_ROOM_IDS: "1" }),
+ ).toThrow("PEER_ASSISTED_ROOM_IDS is no longer supported");
});
- it.each(["0", "01", "1234567890123", "room-1", "1,,2", "1,1"])(
- "rejects an invalid peer-assisted room allowlist: %s",
- (roomIds) => {
- expect(() =>
- loadConfig({
- PEER_ASSISTED_MEDIA: "true",
- PEER_ASSISTED_ROOM_IDS: roomIds,
- }),
- ).toThrow("PEER_ASSISTED_ROOM_IDS");
- },
- );
-
it("allows an explicit loopback listen host", () => {
expect(loadConfig({ LISTEN_HOST: " 127.0.0.1 " }).listenHost).toBe(
"127.0.0.1",
@@ -310,7 +267,6 @@ describe("server configuration", () => {
HOST_ADMISSION_PASSWORD: "host-password-12",
STUN_URLS: "stun:stun.test:3478",
PEER_ASSISTED_MEDIA: "true",
- PEER_ASSISTED_ROOM_IDS: "1",
LIVEKIT_URL: "wss://livekit.test",
LIVEKIT_API_KEY: "test-key",
LIVEKIT_API_SECRET: "s".repeat(32),
diff --git a/tests/server-http.test.ts b/tests/server-http.test.ts
index c4951049..ce9daef5 100644
--- a/tests/server-http.test.ts
+++ b/tests/server-http.test.ts
@@ -380,7 +380,6 @@ describe("server HTTP listener and health", () => {
const baseUrl = await start(
testConfig({
peerAssistedMedia: true,
- peerAssistedRoomIds: new Set(["1"]),
livekitFallback: {
url: "ws://livekit.test:7880",
apiKey: "test-key",
diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.ts
index 96ed034c..ea290347 100644
--- a/tests/server-signal.test.ts
+++ b/tests/server-signal.test.ts
@@ -138,7 +138,6 @@ interface SignalHarness {
roomStore: RoomStore;
room: CreatedRoom;
database?: RoomDatabase;
- peerAssistedRoomIds?: Set<string>;
}
function testConfig(): ServerConfig {
@@ -189,10 +188,6 @@ async function startHarness(
"private-link",
overrides.provisionalHostClaimSeconds,
);
- const peerAssistedRoomIds = config.peerAssistedMedia
- ? new Set([room.roomId])
- : undefined;
- config.peerAssistedRoomIds = peerAssistedRoomIds;
runningServer = await createScreenerServer({
config,
roomStore,
@@ -213,7 +208,6 @@ async function startHarness(
roomStore,
room,
database,
- peerAssistedRoomIds,
};
}
@@ -302,7 +296,6 @@ async function startSfuHarness(options: {
maxViewersPerRoom: 8,
});
const room = roomStore.createRoom();
- const peerAssistedRoomIds = new Set([room.roomId]);
const httpServer = createServer((_request, response) => {
response.statusCode = 404;
response.end();
@@ -311,7 +304,6 @@ async function startSfuHarness(options: {
server: httpServer,
roomStore,
peerAssistedMedia: true,
- peerAssistedRoomIds,
sfuFallback: {
url: "wss://sfu.example.test",
tokenIssuer: options.tokenIssuer,
@@ -369,7 +361,6 @@ async function startSfuHarness(options: {
webSocketUrl: `ws://127.0.0.1:${port}/signal`,
roomStore,
room,
- peerAssistedRoomIds,
};
}
@@ -1909,7 +1900,7 @@ describe("WebSocket signaling", () => {
await viewer.inbox.expectNone(30);
});
- it("isolates the routing allowlist while ordinary ICE stays STUN-only", async () => {
+ it("enables hybrid routing for every room while ordinary ICE stays STUN-only", async () => {
const harness = await startSfuHarness({
tokenIssuer: { issueToken: async () => "unused-test-token" },
stunUrls: ["stun:stun.example.test:3478"],
@@ -1931,28 +1922,16 @@ describe("WebSocket signaling", () => {
});
const ordinaryHost = await openClient(harness.webSocketUrl);
- const ordinaryHostAuth = await authenticate(
- ordinaryHost,
- ordinaryRoom,
- "host",
- "ordinary-host",
- );
- expect(Object.keys(ordinaryHostAuth).sort()).toEqual(
- [
- "connectionId",
- "hostOnline",
- "iceConfig",
- "maxViewers",
- "peerId",
- "protocol",
- "role",
- "roomExpiresAt",
- "type",
- "viewerAuthorizationGeneration",
- "viewerPeerIds",
- "viewerPolicy",
- ].sort(),
+ const ordinaryHostAuth = peerAssisted(
+ await authenticate(
+ ordinaryHost,
+ ordinaryRoom,
+ "host",
+ "ordinary-host",
+ ),
);
+ expect(ordinaryHostAuth.mediaMode).toBe("peer-assisted");
+ expect(ordinaryHostAuth.sfuStandbyUrl).toBe("wss://sfu.example.test");
expect(ordinaryHostAuth.iceConfig).toEqual(hybridHostAuth.iceConfig);
expect(
ordinaryHostAuth.iceConfig.iceServers.every(
@@ -1961,74 +1940,24 @@ describe("WebSocket signaling", () => {
).toBe(true);
const ordinaryViewer = await openClient(harness.webSocketUrl);
- const ordinaryViewerAuth = await authenticate(
- ordinaryViewer,
- ordinaryRoom,
- "viewer",
- "ordinary-viewer",
- );
- expect(Object.keys(ordinaryViewerAuth).sort()).toEqual(
- Object.keys(ordinaryHostAuth).sort(),
- );
- expect(await ordinaryHost.inbox.next("peer-joined")).toEqual({
- type: "peer-joined",
- peerId: ordinaryViewerAuth.peerId,
- });
-
- ordinaryHost.socket.send(
- JSON.stringify({
- type: "signal",
- targetPeerId: ordinaryViewerAuth.peerId,
- payload: {
- kind: "description",
- connectionId: "ordinary-room-connection",
- description: { type: "offer", sdp: "v=0\r\n" },
- },
- }),
- );
- expect(await ordinaryViewer.inbox.next("signal")).toMatchObject({
- fromPeerId: ordinaryHostAuth.peerId,
- payload: { connectionId: "ordinary-room-connection" },
- });
- ordinaryViewer.socket.send(
- JSON.stringify({
- type: "signal",
- payload: {
- kind: "description",
- connectionId: "ordinary-room-connection",
- description: { type: "answer", sdp: "v=0\r\n" },
- },
- }),
- );
- expect(await ordinaryHost.inbox.next("signal")).toMatchObject({
- fromPeerId: ordinaryViewerAuth.peerId,
- payload: { connectionId: "ordinary-room-connection" },
- });
-
- ordinaryHost.socket.send(
- JSON.stringify({
- type: "set-quality-settings",
- qualitySettings: balancedQualitySettings,
- }),
- );
- expect((await ordinaryHost.inbox.next("error")).code).toBe("FORBIDDEN");
- ordinaryViewer.socket.send(
- JSON.stringify({ type: "relay-capacity", downstreamEdges: 1 }),
- );
- expect((await ordinaryViewer.inbox.next("error")).code).toBe("FORBIDDEN");
- ordinaryViewer.socket.send(
- JSON.stringify({ type: "refresh-sfu", revision: 0 }),
+ const ordinaryViewerAuth = peerAssisted(
+ await authenticate(
+ ordinaryViewer,
+ ordinaryRoom,
+ "viewer",
+ "ordinary-viewer",
+ ),
);
- expect((await ordinaryViewer.inbox.next("error")).code).toBe("FORBIDDEN");
+ expect(ordinaryViewerAuth.mediaMode).toBe("peer-assisted");
+ expect(ordinaryViewerAuth.sfuStandbyUrl).toBe("wss://sfu.example.test");
+ expect(ordinaryViewerAuth.iceConfig).toEqual(hybridHostAuth.iceConfig);
+ await closeClient(hybridHost);
+ await closeClient(ordinaryHost);
await closeClient(ordinaryViewer);
- expect(await ordinaryHost.inbox.next("peer-left", 500)).toEqual({
- type: "peer-left",
- peerId: ordinaryViewerAuth.peerId,
- });
});
- it("keeps allowlisted and ordinary room lifecycles independent", async () => {
+ it("keeps all-room hybrid lifecycles independent", async () => {
const harness = await startHarness({
peerAssistedMedia: true,
viewerDisconnectGraceMs: 500,
@@ -2058,15 +1987,22 @@ describe("WebSocket signaling", () => {
await hybridViewer.inbox.next("quality-settings");
const ordinaryHost = await openClient(harness.webSocketUrl);
- await authenticate(ordinaryHost, ordinaryRoom, "host", "lifecycle-ordinary-host");
- const ordinaryViewer = await openClient(harness.webSocketUrl);
- const ordinaryViewerAuth = await authenticate(
- ordinaryViewer,
+ await authenticate(
+ ordinaryHost,
ordinaryRoom,
- "viewer",
- "lifecycle-ordinary-viewer",
+ "host",
+ "lifecycle-ordinary-host",
);
- await ordinaryHost.inbox.next("peer-joined");
+ const ordinaryViewer = await openClient(harness.webSocketUrl);
+ const ordinaryViewerAuth = peerAssisted(
+ await authenticate(
+ ordinaryViewer,
+ ordinaryRoom,
+ "viewer",
+ "lifecycle-ordinary-viewer",
+ ),
+ );
+ await ordinaryHost.inbox.next("media-assignment");
const hybridHostClosed = new Promise<number>((resolve) =>
hybridHost.socket.once("close", (code) => resolve(code)),
@@ -2100,16 +2036,20 @@ describe("WebSocket signaling", () => {
qualitySettings: lowQualitySettings,
});
const resumedOrdinaryViewer = await openClient(harness.webSocketUrl);
- const resumedOrdinaryViewerAuth = await authenticate(
- resumedOrdinaryViewer,
- ordinaryRoom,
- "viewer",
- "lifecycle-ordinary-viewer",
+ const resumedOrdinaryViewerAuth = peerAssisted(
+ await authenticate(
+ resumedOrdinaryViewer,
+ ordinaryRoom,
+ "viewer",
+ "lifecycle-ordinary-viewer",
+ ),
);
expect(resumedOrdinaryViewerAuth.peerId).toBe(ordinaryViewerAuth.peerId);
expect(resumedOrdinaryViewerAuth.connectionId).toBeNull();
- expect("mediaMode" in resumedOrdinaryViewerAuth).toBe(false);
- expect("qualitySettings" in resumedOrdinaryViewerAuth).toBe(false);
+ expect(resumedOrdinaryViewerAuth.mediaMode).toBe("peer-assisted");
+ expect(resumedOrdinaryViewerAuth.qualitySettings).toEqual(
+ defaultQualitySettings,
+ );
const resumedHybridHost = await openClient(harness.webSocketUrl);
const resumedHybridHostAuth = peerAssisted(
@@ -2125,36 +2065,17 @@ describe("WebSocket signaling", () => {
qualitySettings: lowQualitySettings,
});
const resumedOrdinaryHost = await openClient(harness.webSocketUrl);
- const resumedOrdinaryHostAuth = await authenticate(
+ await authenticate(
resumedOrdinaryHost,
ordinaryRoom,
"host",
"lifecycle-ordinary-host",
);
- expect(await resumedOrdinaryHost.inbox.next("peer-joined")).toMatchObject({
- peerId: resumedOrdinaryViewerAuth.peerId,
- });
-
resumedHybridHost.socket.send(JSON.stringify({ type: "abandon-room" }));
await resumedHybridHost.inbox.next("room-closed");
await resumedHybridViewer.inbox.next("room-closed");
expect(harness.roomStore.size).toBe(1);
- resumedOrdinaryHost.socket.send(
- JSON.stringify({
- type: "signal",
- targetPeerId: resumedOrdinaryViewerAuth.peerId,
- payload: {
- kind: "description",
- connectionId: "ordinary-after-hybrid-delete",
- description: { type: "offer", sdp: "v=0\r\n" },
- },
- }),
- );
- expect(await resumedOrdinaryViewer.inbox.next("signal")).toMatchObject({
- fromPeerId: resumedOrdinaryHostAuth.peerId,
- payload: { connectionId: "ordinary-after-hybrid-delete" },
- });
resumedOrdinaryHost.socket.send(JSON.stringify({ type: "abandon-room" }));
await resumedOrdinaryHost.inbox.next("room-closed");
await resumedOrdinaryViewer.inbox.next("room-closed");
@@ -3392,7 +3313,6 @@ describe("WebSocket signaling", () => {
it("assigns a bounded peer relay tree and authorizes only direct media edges", async () => {
const harness = await startHarness({ peerAssistedMedia: true });
const secondRoom = harness.roomStore.createRoom();
- harness.peerAssistedRoomIds!.add(secondRoom.roomId);
const host = await openClient(harness.webSocketUrl);
const hostAuth = peerAssisted(
await authenticate(host, harness.room, "host", "relay-host"),
@@ -4662,7 +4582,6 @@ describe("WebSocket signaling", () => {
});
const replacementRoom = harness.roomStore.createRoom();
- harness.peerAssistedRoomIds!.add(replacementRoom.roomId);
const replacing = await prepareFallbackForTwoViewers(
harness.webSocketUrl,
replacementRoom,
@@ -4733,7 +4652,6 @@ describe("WebSocket signaling", () => {
expect(replacementRoot.socket.readyState).toBe(WebSocket.OPEN);
const prepareFailureRoom = harness.roomStore.createRoom();
- harness.peerAssistedRoomIds!.add(prepareFailureRoom.roomId);
const prepareFailure = await prepareFallbackForTwoViewers(
harness.webSocketUrl,
prepareFailureRoom,