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): allow two Web relay children [skip ci]

AAAae153c05bd9b
diff --git a/AGENTS.md b/AGENTS.md
index 1ad19c1d..16500b4b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -7,7 +7,7 @@
- Keep media distributed and automatic. Use centralized services for rooms, authentication, signaling, STUN, observability, and bounded SFU-root capacity. TURN is an optional authenticated selected-edge compatibility transport, disabled unless explicitly configured; it is not a media topology.
- Let viewers join from a normal desktop or mobile browser without installing the sender application.
- STUN is required. The target ladder is direct/peer UDP, then an SFU/UDP virtual parent feeding at most two roots, then optional authenticated selected-edge TURN, followed by a clear bounded failure. Ordinary peer edges must not receive TURN candidates by default. HTTPS/WSS remains TLS/TCP and is independent of this media-transport policy.
-- Every non-server endpoint has at most two active downstream media edges; an upstream receive edge does not consume this upload budget. Browser relays remain stricter at one downstream edge until their re-encode/resource gates pass. Central media normally serves at most two roots; extra server-fed exceptional viewers require an explicit deployment egress/admission cap and must never create unbounded fanout.
+- Every non-server endpoint stays within its advertised relay capacity and the deployment hard ceiling; an upstream receive edge does not consume this upload budget. The current ordinary Web release tier is uniformly two without UA- or visibility-based policy, and actual edge failure returns to the bounded route-reselection path. A later accepted tier may use evidence-driven discrete `0/1/2/3` capacity under a server ceiling and cooldown; it must not infer capacity from device identity. Central media normally serves at most two roots; extra server-fed exceptional viewers require an explicit deployment egress/admission cap and must never create unbounded fanout.
- Treat a web client as the initial delivery target. A packaged desktop sender or native capture helper is a later optimization, not an assumed requirement.
- Do not silently change the product into an always-SFU conferencing system. An SFU is a virtual parent for one or two necessary roots whose peer descendants remain distributed; record any broader topology change as an ADR with measured justification.
diff --git a/docs/adr/0004-peer-assisted-media-experiment.md b/docs/adr/0004-peer-assisted-media-experiment.md
index c02e1a99..a7256fb7 100644
--- a/docs/adr/0004-peer-assisted-media-experiment.md
+++ b/docs/adr/0004-peer-assisted-media-experiment.md
@@ -52,11 +52,11 @@ or duplicate values fail startup when the experiment is enabled; there is no
all-room fail-open. This exact-room gate is temporary validation scope and adds
no UI, percentage rollout, or routing score.
-The signaling server assigns two sticky, balanced chains with a deterministic
-breadth-first walk. The host has capacity for at most two children and each
-viewer for at most one. Candidate parents are ordered by depth and server-issued
-join sequence. Joining a viewer does not move existing assignments except for
-ADR-0005's bounded admission rescue: an unassigned one-slot relay may replace
+The signaling server assigns a sticky, bounded DAG with a deterministic
+breadth-first walk. The host and each ordinary Web viewer currently have
+capacity for at most two children. Candidate parents are ordered by depth and
+server-issued join sequence. Joining a viewer does not move existing assignments except for
+ADR-0005's bounded admission rescue: an unassigned relay may replace
the oldest childless zero-capacity Host leaf when both Host slots are full. If a
parent leaves, only its orphaned subtree root is assigned to the first available
slot; the root's descendants stay attached. No RTT, bandwidth, CPU, geography,
@@ -64,7 +64,7 @@ capability, or quality scoring is added.
For this ADR, one media edge is one downstream `RTCPeerConnection` carrying the
shared stream. Using TURN for that connection does not alter the edge count. The
-host's two-child limit is a hard invariant across join, reconnect,
+current two-child endpoint limit is a hard invariant across join, reconnect,
reparent, and recovery paths. If the deterministic topology has no connected
eligible parent, the viewer remains admitted but waits without media until a
slot becomes reachable; it must not create a third host connection.
@@ -107,8 +107,8 @@ route-controller ADR owns cross-mode fallback.
The browser spike may encode once for each of the host's one or two seed
connections because browsers do not guarantee cross-connection encoder reuse.
-Each viewer relay also performs one downstream encode. This is tolerated only
-for the experiment and must be measured honestly.
+Each viewer relay also performs one downstream encode per child, currently up
+to two. This is tolerated only for the experiment and must be measured honestly.
A separate planned packaged/native sender must use custom libwebrtc encoder
proxies that share one encoded output while retaining independent standard
@@ -123,19 +123,18 @@ viewing remains required.
Test 1, 3, 5, and 8 viewers for 30 minutes across the three recommended ceiling
combinations, plus any advanced combination proposed for production, with
controlled per-edge RTT at or below 40 ms and loss at or below 1%. Current
-desktop Chrome and Edge form the relay cohort; current Android Chrome and iOS
-Safari join last as leaf checks. ADR-0005 now adds a per-session binary relay
-capacity: detected mobile/iPad clients report zero and desktop-class browsers
-report one. That heuristic, background lifecycle, and voluntary relay policy
-remain unverified, so the spike is still unsafe for arbitrary-user deployment.
-This one-child, depth-four gate remains an eight-viewer experiment; it cannot
+Chrome and Edge form the controlled relay cohort; Android Chrome and iOS Safari
+remain compatibility observations. ADR-0005 now gives every ordinary Web
+Viewer the same two-edge capacity without UA or visibility detection. Mobile
+resource behavior remains unverified, but does not define a separate route
+class. This depth-three gate remains an eight-viewer experiment; it cannot
authorize the accepted 20-viewer default. That later release requires a separate
-20-viewer matrix and proven capacity-two relay or bounded central exceptions.
+20-viewer matrix or bounded central exceptions.
The proposal advances only if every condition holds:
-- host media fanout is never greater than two and viewer fanout is never greater
- than one, including relay loss and reparenting;
+- host and viewer media fanout are never greater than two, including relay loss
+ and reparenting, and a third child is never admitted;
- assignments are reproducible from depth and server join order, without a
composite score, live optimization loop, or proactive rebalancing;
- every relay's expected outbound RTP encoder is measured through encode time,
@@ -146,7 +145,7 @@ The proposal advances only if every condition holds:
- authentication and live setting changes leave every current and future child
sender targeting the same latest room setting without altering the P2P wire;
- first picture is at most 3 seconds, a 60 fps run does not remain below 50
- decoded fps for more than 5 seconds, and depth-four p95 glass-to-glass
+ decoded fps for more than 5 seconds, and depth-three p95 glass-to-glass
latency is at most 350 ms;
- relay delta encode time per frame stays at or below 16.7 ms on the reference
cohort and CPU limitation does not persist for more than 5 seconds;
@@ -154,7 +153,10 @@ The proposal advances only if every condition holds:
receives the default 5-second disconnect grace; if it does not reconnect,
the same deterministic assignment rule produces a new decodable picture
within the following 3 seconds (about 8 seconds total under defaults); and
-- the common codec path works on the required desktop relays and mobile leaves.
+- the common codec path works on the controlled Web relay cohort.
+
+Android Chrome and iOS Safari remain non-blocking compatibility observations;
+their behavior does not introduce a device-specific relay-capacity policy.
The about-8-second gate covers a controlled page close that the server observes
immediately. A silent network partition depends on the default 30-second
@@ -174,7 +176,7 @@ failed browser-relay topology as passing.
Passing the gate does not change this ADR to Accepted. It permits a separate ADR
to propose a production design, including broader game-audio/A-V verification,
-voluntary relay policy, and privacy disclosure. The native shared-encode sender
+automatic bounded relay policy, and privacy disclosure. The native shared-encode sender
is the independent planned work described above, not a reward for passing this
gate.
@@ -196,8 +198,8 @@ Negative:
descendants.
- Relay upload, battery, background suspension, and peer IP exposure affect
viewers, not just the broadcaster.
-- Two one-child chains need depth four for eight viewers, so the latency target
- is uncertain by design.
+- The capacity-two DAG still adds repeated encode and up to three hops for eight
+ viewers, so the latency target remains uncertain until measured.
## Relationship To Existing ADRs
diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.md
index 39ccf9ab..357a4bac 100644
--- a/docs/adr/0005-automatic-hybrid-media-routing.md
+++ b/docs/adr/0005-automatic-hybrid-media-routing.md
@@ -27,8 +27,9 @@ credentials are not participant-wide ICE configuration and are never added to
ordinary peer connections by default. HTTPS/WSS remains TLS/TCP and is outside
this media policy. Every non-server endpoint has at most two active
downstream media edges; its upstream receive edge does not consume that upload
-budget. The current browser relay remains stricter at one child until its
-re-encode and resource gates pass.
+budget. The current source candidate gives every ordinary Web relay that same
+two-child hard limit without a UA or visibility policy; production remains at
+one until this candidate ships.
TURN and SFU occupy different layers. A selected TURN candidate continuously
relays media for its authorized ICE edge; it is not a handshake helper or a
@@ -134,19 +135,18 @@ one-use state, fanout, and quotas bound the bearer. LiveKit publisher/subscriber
ICE remains a separate participant-wide domain.
Every viewer starts with zero relay capacity for each authenticated session. A
-peer-assisted Web client explicitly advertises either zero or one downstream
-edge; conservative UA-CH/user-agent detection reports mobile and iPad clients as
-leaves and desktop-class browsers as one-child relays. The controller uses this
-binary capability only for future admission and recovery. Withdrawing capacity
-does not proactively migrate an otherwise healthy existing edge.
+peer-assisted Web client then explicitly advertises two downstream edges; there
+is no UA-, device-, or visibility-based branch. The controller accepts bounded
+capacity values from zero through two for admission and recovery. Withdrawing
+capacity does not proactively migrate an otherwise healthy existing edge.
The source now implements one narrow admission exception to sticky assignment.
On an active peer-only route with no SFU publication or pending prepare, a
connected, childless Viewer that has no upstream or failed-parent history and
-advertises one relay slot may replace the oldest connected, childless,
-zero-capacity Host child when both Host slots are full. That leaf becomes the
-new relay's only child. The synchronous change preserves Host fanout two,
-browser fanout one and the depth bound, advances one route revision, and clears
+advertises relay capacity may replace the oldest connected, childless,
+zero-capacity Host child when both Host slots are full. That leaf becomes one
+child of the new relay. The synchronous change preserves Host and browser
+fanout at two, advances one route revision, and clears
both changed upstream connection generations. Host-side reconciliation closes
the stale child edge before starting the replacement. No healthy routed
candidate, quality score, timer, global parent penalty, or periodic rebalance is
@@ -225,7 +225,7 @@ Minimal protocol additions:
- optional `sfuStandbyUrl` in a peer-assisted authenticated snapshot, only when
the server has complete LiveKit fallback configuration;
-- `relay-capacity { downstreamEdges: 0 | 1 }` from an authenticated
+- `relay-capacity { downstreamEdges: 0 | 1 | 2 }` from an authenticated
peer-assisted viewer;
- `route-update { revision, phase: "prepare" | "active", assignment }`;
- `sfu-config { revision, url, token }`;
@@ -535,7 +535,8 @@ boundary is actually configured and the UI must not claim E2EE.
- Every non-server endpoint stays at or below two active downstream media edges
across prepare, commit, rollback, reconnect, and stale-message sequences;
- current browser relays stay at one child until separately accepted.
+ the current Web candidate uses the same two-child bound and never admits a
+ third edge.
- Only necessary roots or explicitly admitted exceptional viewers receive SFU
media and the configured central egress budget is never exceeded.
- A reliable SFU root continues to serve bounded peer descendants. Normal
diff --git a/docs/adr/0007-demand-driven-dual-representation-quality.md b/docs/adr/0007-demand-driven-dual-representation-quality.md
index 509b6e66..1491c49d 100644
--- a/docs/adr/0007-demand-driven-dual-representation-quality.md
+++ b/docs/adr/0007-demand-driven-dual-representation-quality.md
@@ -120,9 +120,8 @@ derived negotiated codec/profile/parameters (including applicable
`scalabilityMode`) agree with sender transport/GCC and encode evidence. A
request alone cannot lower quality or start a representation.
-UA, platform, and device-model detection does not participate in quality
-selection. The existing mobile/iPad heuristic remains limited to conservative
-relay-capacity admission. Browser capability queries can guide a bounded probe,
+UA, platform, and device-model detection does not participate in quality or
+relay-capacity selection. Browser capability queries can guide a bounded probe,
but runtime encode/decode behavior is authoritative.
## Standard Capability Short-Circuits
diff --git a/docs/project-memory.md b/docs/project-memory.md
index 623afc0d..43d68d6f 100644
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@ -8,7 +8,7 @@ Last updated: 2026-08-21
- Browser first. Viewers use desktop/mobile Web; an optional sender requires a proven browser capability gap.
- Use a small central service for access, rooms, signaling, deterministic topology, STUN, observability, and bounded SFU-root capacity.
- Minimize server bandwidth. Ordinary peer ICE is STUN-only. Failure tries restart, rebuild, alternate peer and bounded SFU/UDP roots; only then may the controller authorize short-lived TURN for one selected exceptional edge before clear failure. TURN is transport, not topology.
-- Non-server nodes have at most two downstream edges; browser relays stay at one until resource gates pass. SFU normally feeds one or two roots that retain peer descendants; separately capped server edges may serve exceptional viewers that cannot attach behind a healthy root.
+- The current release budget is two downstream edges per non-server node, including ordinary Web relays; upstream receive is free and UA/visibility do not change it. SFU normally feeds one or two roots that retain peer descendants; separately capped server edges may serve exceptional viewers that cannot attach behind a healthy root. A future evidence-driven tier may change the ceiling only through the owning requirement and design.
- Two-tree packet/layer striping may reduce endpoint upload toward one stream bitrate, but needs a bounded multi-parent, loss, sync, churn, and latency experiment; it is not in the current full-stream chains.
- Direct/peer keeps per-PC stock GCC. SFU paths start at a `HIGH` ceiling and share at most one `LOW`; next test LiveKit exactly-two built-in BWE on zero-descendant leaves. If it passes, no app media selector is built. Explicit quality, manual activation, then custom/native are later fallbacks; always-on `LOW` needs resource gates.
- A later explicit quality fallback evacuates children under a generation guard first. Autonomous BWE enters `suspect`; confirmation evacuates children, and no confirmed `FALLBACK` parent remains. Root-with-children impact is a default-on gate; capacity returns after longer recovery plus cooldown. Self-report alone never triggers it.
@@ -19,7 +19,7 @@ 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.
+- Keep desktop Chrome/Edge and the responsive Web viewer as the baseline. Observe Android Chrome and iOS Safari compatibility without assigning a separate relay-capacity class.
- Keep Viewer playback on one persistent, user-started audible media element while hidden. Continuity evidence uses media/connection counters; hidden video composition is presentation-only, and iOS lock-screen, reclamation and background reconnection remain device gates.
- 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.
@@ -27,7 +27,7 @@ Last updated: 2026-08-21
- ADR-0006's historical browser-bridge canary remains no-go; VP8 stays default. Browser H.264 rendered 298/299; Native WGC/MF rendered 203 with PID/LUID-correlated `VideoEncode`. Downloaded use, multi-viewer/endurance/public proof remain open.
- Mobile endpoints are Web Viewer-only. Current Android/iOS browsers do not expose Web Host capture; AirPlay/system mirroring is Viewer-local output.
- ADR-0005: direct/peer UDP -> bounded SFU roots -> selected-edge TURN. The deployed controller caps pending/answered `peer-selected` at one per room; Host ingress is independent. A pre-`ecc794d` exact-source/production-media canary proves active Host ingress only. Ordinary peers stay 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.
+- 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, one active upstream 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.
@@ -52,6 +52,7 @@ Last updated: 2026-08-21
- ADR-0005 rejects `PEER_ASSISTED_ROOM_IDS`; `PEER_ASSISTED_MEDIA=true` enables every room and ordinary peers stay STUN-only. Initial or active Host ingress may consume one bound relay-only grant; ready/abort clears it and failure restores peer baseline. Stale room-ID config fails startup; `screener-v2` is the only deployed wire.
- 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.
- Deployed Web uses LiveKit 2.22.0 `q,h`. Chrome 151 proves local SFU/UDP and, separately, active selected TURN/UDP Host ingress against production media services with Viewer frame progress and clean stop. Initial/peer-selected relay, BWE, and C+B remain open.
+- The current local source candidate gives every ordinary Web Viewer two relay slots. A Chrome 151 synthetic 720p30 run with five Viewers kept Host/relay fanout at two, advanced both children of one relay by 80 decoded frames and about 1.1 MB each, decoded at every Viewer, and stopped without fatal error. This is bounded functional evidence only; production remains one-slot until the candidate ships.
## Provisional Quality Targets
@@ -65,7 +66,7 @@ These are measurement gates, not performance claims.
## Open Decisions
- Sustainable count by hardware, quality, network, and route: finish instrumented `1/3/5/8`, then pass a 20-viewer matrix before changing the accepted target default to 20.
-- Whether ADR-0004 passes fanout, re-encoding, depth-four latency, reparenting, silent-partition, and mobile-leaf gates.
+- Whether ADR-0004 passes re-encoding, depth-three/eight-viewer latency, reparenting, silent-partition, and representative resource gates.
- Selected-edge: active Host-ingress function passes; initial ingress, `peer-selected`, expiry/failure, mobile, resource and bandwidth gates remain. The bearer is non-revocable until expiry; performance follows later and Media TCP is out.
- Exact mobile Viewer lifecycle behavior across autoplay, rotation, iOS lock-screen/page reclamation, background reconnection and network changes.
- Project license and distribution model, which determines whether GPL/AGPL sources can move beyond study-only use.
diff --git a/docs/research/advanced-peer-distribution.md b/docs/research/advanced-peer-distribution.md
index 6520b091..6e4ef844 100644
--- a/docs/research/advanced-peer-distribution.md
+++ b/docs/research/advanced-peer-distribution.md
@@ -103,7 +103,8 @@ Go gates:
350 ms;
- a path failure returns a decodable picture within one second after detection;
- protection still saves at least 30% host upload relative to `2B`; and
-- target desktop relays and mobile leaves pass runtime codec capability probes.
+- the controlled Web relay cohort passes runtime codec capability probes;
+ mobile browsers remain compatibility observations, not a capacity class.
Reject that spike if endpoint upload remains near `2B`, relay encoding returns,
queues cannot be bounded, or supported clients require two unrelated decoders
@@ -245,8 +246,8 @@ conferencing UI but is not a directional P2P parent score. Screener consequently
excludes only the failed parent for the affected Viewer-rooted subtree and
releases the quality-owned exclusion after a successful move.
-With host degree two and the current browser-relay degree one, two balanced
-chains already minimize maximum depth at `ceil(N/2)`. A tree for `N` viewers
+With host and current browser-relay degree two, deterministic breadth-first
+assignment keeps eight viewers to depth three. A tree for `N` viewers
still has `N` media edges, approximately `N*B` useful upload in aggregate, and
approximately `2B` host upload once both roots are used. Local reparenting does
not reduce either bandwidth quantity. Reordering an already balanced healthy
@@ -254,8 +255,8 @@ tree also cannot reduce depth; a move needs a discrete admission, path, TURN,
relay-resource, recovery, or future native-capacity benefit.
The source admission-rescue slice is limited to its discrete capacity case. If
-a relay-capable viewer is unassigned because two zero-capacity roots,
-especially mobile leaves, occupy both host slots, it inserts that viewer above
+a relay-capable viewer is unassigned because two zero-capacity roots occupy
+both host slots, it inserts that viewer above
one deterministic childless root:
```text
@@ -263,10 +264,10 @@ host -> new relay -> existing leaf
host -> other root
```
-This admits the waiting viewer while keeping host fanout two and browser relay
-fanout one. The router permits it only on an active peer-only route with no SFU
+This admits the waiting viewer while keeping host and browser-relay fanout at
+two. The router permits it only on an active peer-only route with no SFU
publication or pending prepare, when the connected candidate currently has no
-upstream or children, newly offers one relay slot, and has no failed-parent
+upstream or children, offers relay capacity, and has no failed-parent
history. The host must have exactly two children and the chosen child must be a
connected, childless, zero-capacity leaf. Existing server join order chooses the
oldest eligible leaf. One synchronous topology snapshot changes the host,
@@ -291,8 +292,8 @@ move only one affected subtree, use separate enter and recovery thresholds plus
a cooldown, and disable proactive moves for the share after repeated rollback.
Use make-before-break only when the new parent has a free downstream media slot
-and every affected endpoint remains within its limit: host at most two, current
-browser relay one, and any future native relay at most two. Admission rescue
+and every affected endpoint remains within its current limit: host, Web relay,
+and native relay at most two. Admission rescue
starts with both host slots occupied, so it is break-before-make: retire the
chosen host-to-leaf media edge before activating host-to-new-relay media. A
control-only `RTCPeerConnection` may prewarm ICE but cannot prove media uplink:
diff --git a/docs/research/low-server-media-routes.md b/docs/research/low-server-media-routes.md
index 2f76658d..343a17bd 100644
--- a/docs/research/low-server-media-routes.md
+++ b/docs/research/low-server-media-routes.md
@@ -140,8 +140,8 @@ only STUN candidates. The controller may authorize one failed edge to rebuild
relay-only after SFU/UDP; LiveKit participant transport remains separate. An SFU is a topology node.
Screener uses it as a virtual
parent for one or two roots, not as an automatic all-viewer fanout service.
-After media reaches a root, the deterministic sticky subtree, host/root fanout
-at most two, browser fanout one, maximum depth, and bounded failure radius still
+After media reaches a root, the deterministic sticky subtree, current host/root
+and browser fanout at most two, maximum depth, and bounded failure radius still
apply. Only the absence of any reliable relay root permits a necessary viewer
to consume one of the same one or two root slots with zero descendants.
@@ -393,7 +393,7 @@ lost.
| Route | Where copies are emitted | Endpoint cost | Current disposition |
| --- | --- | --- | --- |
| Direct host P2P | Host emits one copy per viewer | Host upload and sender pipelines grow with viewers | Keep for one or two viewers |
-| Fixed two-chain browser relay | Host emits at most two copies; each relay emits at most one | Ordinary browser, but every relay decodes and re-encodes and adds a hop | Current default-off, maximum-eight-viewer spike |
+| Bounded browser relay DAG | Host and each Web relay emit at most two copies | Ordinary browser, but every relay decodes and re-encodes and adds a hop | Current capacity-two source candidate, maximum-eight-viewer gate |
| Native shared-encode host | Host targets one encode for at most two standard WebRTC edges | libwebrtc public-API proxy risk spike, with Pion as fallback | Planned separate sender phase; still pays per-edge upload |
| Native volunteer encoded-RTP relay | Each volunteer forwards one encoded copy | Native install, RTP/RTCP forwarding, packaging, and opt-in relay policy | Conditional experiment only if relay re-encoding is the sole browser-spike failure |
| SFU virtual parent | SFU normally emits one or two root copies; roots keep peer descendants | Service pays measured root egress; host sends one publication | Accepted primary central fallback after direct/peer UDP; local SFU/UDP and active Host-ingress relay function pass, while public-room/performance evidence remains open |
diff --git a/docs/research/peer-assisted-media.md b/docs/research/peer-assisted-media.md
index b24ae739..a336303b 100644
--- a/docs/research/peer-assisted-media.md
+++ b/docs/research/peer-assisted-media.md
@@ -1,10 +1,10 @@
# Peer-Assisted Media Research
-- Research date: 2026-08-19
+- Research date: 2026-08-21
- Scope: one game-screen broadcaster, at most eight trusted viewers, host media fanout at most two
-- Status: historical evidence for the bounded ADR-0004 experiment; accepted
- ADR-0005 now owns automatic peer/SFU routing. Production later removed the
- room-`1` rollout boundary; retained SFU media remains unverified.
+- Status: historical evidence plus the current capacity-two source candidate;
+ accepted ADR-0005 owns automatic peer/SFU routing. Production later removed
+ the room-`1` rollout boundary; retained SFU media remains unverified.
## Conclusion
@@ -13,9 +13,10 @@ edges without making an SFU carry every viewer's traffic. The smallest credible
experiment uses only standard WebRTC media:
1. the browser host sends its screen stream to at most two first-level viewers;
-2. each viewer may add the received remote `MediaStreamTrack` values to one
- downstream `RTCPeerConnection`; and
-3. the signaling server assigns two balanced chains deterministically.
+2. each viewer may add the received remote `MediaStreamTrack` values to at most
+ two downstream `RTCPeerConnection` instances; and
+3. the signaling server assigns one active upstream per viewer in a bounded,
+ deterministic breadth-first DAG.
This path reuses WebRTC capture, codec negotiation, RTP, NACK/PLI/RTX, congestion
control, jitter buffering, ICE, STUN, DTLS-SRTP, and browser rendering. A later
@@ -87,12 +88,14 @@ It follows from those source interfaces that a normal browser relay decodes and
re-encodes at every hop. It is functional but adds relay CPU/GPU load, encode
delay, and generational quality loss. Each outbound WebRTC send stream creates
an independent sender encoder: the experimental host can therefore encode
-twice, while a viewer with one child encodes once.
+twice, while a viewer with two children has two independent outbound senders.
Sources:
- [libwebrtc video RTP receiver](https://webrtc.googlesource.com/src/+/refs/heads/main/pc/video_rtp_receiver.cc)
- [libwebrtc raw-frame sender source](https://webrtc.googlesource.com/src/+/refs/heads/main/media/engine/webrtc_video_engine.cc)
+- [W3C WebRTC `addTrack` and sender model](https://www.w3.org/TR/webrtc/) (accessed 2026-08-21)
+- [WebRTC remote-stream forwarding primitives](https://webrtc.org/getting-started/remote-streams) (accessed 2026-08-21)
### Encoded DataChannel Relay, Rejected For The First Spike
@@ -158,29 +161,32 @@ Sources:
## Deterministic Experimental Topology
-The signaling server remains the topology authority. The experiment uses two
-sticky, balanced chains selected by one breadth-first walk. Here, one media edge
+The signaling server remains the topology authority. The source candidate uses
+a sticky, bounded DAG selected by one breadth-first walk. Here, one media edge
means one downstream `RTCPeerConnection` carrying the shared stream; a later
controller-selected TURN rebuild does not change the edge count.
-- the host has capacity for at most two children and every viewer for at most
- one;
-- the host's child count is a hard invariant and never exceeds two, including
- joins, reconnects, and reparenting;
+- the host and every ordinary Web viewer currently have capacity for at most two
+ children;
+- each endpoint's child count is a hard invariant and never exceeds two,
+ including joins, reconnects, and reparenting;
- candidate parents are ordered by depth and server join sequence, and the
first connected node with a free slot is selected;
-- joining a viewer never moves an existing assignment; on parent loss, only the
- orphaned subtree root is reassigned and its descendants remain attached; and
+- every viewer has exactly one active upstream even though several candidate
+ parents may be eligible;
+- join/capacity admission never moves a healthy edge; on disconnect or current
+ edge failure, only each orphaned direct subtree root is reassigned while its
+ descendants remain attached; and
- if no assigned parent is available, media waits or admission fails explicitly.
The host never opens a third edge.
There is no RTT, bandwidth, CPU, geography, candidate-type, or historical
-quality score. There is no optimization loop or live topology rebalancing. With
-two host slots and one slot per viewer, eight viewers require a maximum depth of
-four; that latency and repeated-encode cost is part of the experiment rather
-than something hidden by a scheduler. The controlled relay cohort uses
-foreground desktop Chrome/Edge; mobile leaf checks join after their intended
-parent so the spike does not pretend to solve background mobile relay policy.
+quality score. There is no optimization loop, multi-source media, or live
+topology rebalancing. With two host and two viewer slots, eight viewers require
+a maximum depth of three; that latency and repeated-encode cost is part of the
+experiment rather than something hidden by a scheduler. Ordinary Web clients
+use the same capacity without UA or visibility classification; mobile devices
+remain non-blocking compatibility observations.
Per-edge ICE remains independent. Ordinary peer edges are STUN-only; after
direct/peer UDP and SFU/UDP fail, a controller-selected exceptional edge may use
@@ -195,7 +201,7 @@ integer 15-60 fps, integer 2-12 Mbps, and the three standard degradation
preferences; missing, extra, or out-of-range fields fail schema validation.
The three visible presets are recommendations rather than wire IDs. The server
stores the latest complete object in a room-count-bounded in-memory map,
-defaults to 1080p60 at 8 Mbps with clarity priority, includes it in
+defaults to 1080p60 at 8 Mbps with balanced priority, includes it in
peer-assisted authenticated snapshots, and broadcasts host changes to online
viewers. The value survives a stopped share, is removed with the room, and is
not written to SQLite. Ordinary P2P authentication remains unchanged and
@@ -230,7 +236,7 @@ and RTP sender parameters remain targets, so achieved bitrate, frame rate,
resolution, encode work, and cross-hop quality still require the measurement
matrix below. It does not add or imply shared encoding.
-A controlled Chrome 151 loopback smoke used one host, three viewers, and a
+An earlier controlled Chrome 151 loopback smoke used one host, three viewers, and a
synthetic 720p30 source. Balanced and clarity settings reached every
participant; every baseline active outbound video sender displayed the matching
requested/applied preference; peer-connection fingerprints stayed unchanged;
@@ -241,6 +247,14 @@ fanout stayed at two and relay fanout at one. This is control and continuity
evidence only, not visual-quality, full-resolution, load, TURN, public-network,
or endurance evidence.
+A 2026-08-21 local Chrome 151 capacity-two run used one Host and five Viewers
+with a synthetic 720p30 stream. Host and relay fanout peaked at two; one Viewer
+simultaneously served two children, whose inbound counters each advanced by 80
+decoded frames and about 1.1 MB. All five Viewers decoded and cleanup reported
+no fatal error. The run proves the two-child control path and bound on local
+Chrome only. It does not prove shared encoding, CPU/GPU cost, visual quality,
+games, mobile resources, public networking, or endurance.
+
Peer multicast research such as SplitStream demonstrates why load-balanced,
failure-tolerant overlays normally introduce multiple trees and content
striping. Those mechanisms are intentionally excluded: needing them is a reason
@@ -272,26 +286,24 @@ Sources:
## Resource Model
-For observed encoded bitrate `B`, `N` viewers, two host slots, and one viewer
-slot:
+For observed encoded bitrate `B`, `N` viewers, and the current two host/viewer
+slots:
- host upload is at most approximately `2 * B`, plus transport overhead;
-- each relay upload is at most approximately `B`;
+- each relay upload is at most approximately `2 * B`;
- aggregate viewer delivery still requires approximately `N * B` across hosts,
relays, and any TURN paths; and
- signaling/STUN carry negligible media traffic, while a TURN path still incurs
relay ingress and egress for that edge.
-Peer assistance distributes traffic; it does not eliminate it. Relay
-eligibility must therefore be visible and voluntary in any production design.
+Peer assistance distributes traffic; it does not eliminate it. The product
+keeps topology automatic and invisible while enforcing advertised capacity and
+the deployment ceiling.
The standalone ADR-0004 spike has no runtime capability flag and relies on
-controlled join order. The accepted ADR-0005 controller starts every viewer as
-a leaf, then accepts an explicit per-session capacity of zero or one. The first
-production smoke scoped it to room `1`; current production no longer has that
-room boundary. Its Web client
-reports detected mobile/iPad clients as leaves and desktop-class browsers as
-one-child relays. That conservative heuristic is still unverified on the real
-mobile matrix and is not a substitute for a future voluntary relay policy.
+controlled join order. The accepted ADR-0005 controller starts every viewer at
+zero, then the current Web client advertises an explicit per-session capacity
+of two. The first production smoke scoped it to room `1`; current production no
+longer has that room boundary. There is no mobile/iPad, UA, or visibility branch.
## Bounded Spike And Gates
@@ -299,9 +311,9 @@ This historical gate assumed default-off configuration through
`PEER_ASSISTED_MEDIA=false`; current production enables the controller for all
rooms.
It cannot be enabled above eight viewers and uses the existing standard WebRTC
-screen stream, current desktop Chrome/Edge as relay nodes, current Android
-Chrome and iOS Safari as required
-leaf checks, one child per viewer, and at most eight viewers. It may carry the
+screen stream, current Chrome/Edge as the controlled relay cohort, Android
+Chrome and iOS Safari as compatibility observations, at most two children per
+viewer, and at most eight viewers. It may carry the
existing screen-audio track when the browser provides one. SVC/simulcast,
custom encoded transport, FEC changes, multi-tree striping, transcoding,
background mobile relay, and the later ADR-0005 SFU controller are outside this
@@ -325,8 +337,8 @@ telemetry service.
All hard gates must pass:
-1. The host has no more than two outgoing media edges and every viewer has no
- more than one child at every sampled instant,
+1. The host and every viewer have no more than two outgoing media edges at every
+ sampled instant, and a third child is rejected,
including churn; no hidden direct-host fallback is allowed.
2. Assignment is reproducible from depth and server join order. Standard relay
statistics are expected to show a new outbound RTP encoder at every hop; its
@@ -336,7 +348,7 @@ All hard gates must pass:
and egress remains zero. Host and relay upload stay within 20% of
`childCount * B`.
4. First picture is at most 3 seconds, decoded 60 fps does not remain below 50
- for more than 5 seconds without an explicit failure, and depth-four p95
+ for more than 5 seconds without an explicit failure, and depth-three p95
glass-to-glass latency is at most 350 ms.
5. Closing either first-level relay so the server observes it immediately starts
the default 5-second disconnect grace. If it does not reconnect during that
@@ -345,8 +357,9 @@ All hard gates must pass:
6. At each relay, delta encode time per encoded frame stays at or below one
60 fps frame interval on the reference cohort and CPU limitation does not
persist for more than 5 seconds.
-7. The standard WebRTC stream works on current Chrome and Edge relay nodes and
- on current Android Chrome and iOS Safari leaves.
+7. The standard WebRTC stream works on the controlled Chrome and Edge relay
+ cohort. Android Chrome and iOS Safari remain non-blocking compatibility
+ observations rather than a separate capacity policy.
An ordinary implementation defect may be corrected inside the spike. If a gate
requires an encoded DataChannel/WebCodecs media plane, custom congestion
@@ -360,10 +373,9 @@ relay experiment keeps standard P2P plus explicit user-operated or central SFU
fallbacks.
Passing these historical gates proved only that a second design phase was
-justified. ADR-0005 subsequently accepted the bounded controller and production
-first ran a room-`1` smoke and later removed that rollout boundary, but retained
-SFU media, voluntary relay policy, and broader audio/A-V verification remain
-open. The
+justified. ADR-0005 subsequently accepted the bounded controller; production
+first ran a room-`1` smoke and later removed that rollout boundary. Retained SFU
+media and broader audio/A-V verification remain open. The
native host shared-encode sender is a separate planned phase regardless of this
experiment's result and is not implemented here.
diff --git a/docs/research/realtime-quality-adaptation.md b/docs/research/realtime-quality-adaptation.md
index 8bd6e4cd..5059194d 100644
--- a/docs/research/realtime-quality-adaptation.md
+++ b/docs/research/realtime-quality-adaptation.md
@@ -285,9 +285,8 @@ remains protected in either case.
A viewer's `LOW` request is advisory and must be authenticated, session-bound,
rate-limited, deduplicated, and corroborated by sender transport/encode and
-viewer receive/decode stats. UA or device-model detection is not quality
-evidence; the current mobile/iPad heuristic remains restricted to relay
-capacity. A valid report may affect confirmed topology eligibility; it does not
+viewer receive/decode stats. UA or device-model detection is not quality or
+relay-capacity evidence. A valid report may affect confirmed topology eligibility; it does not
command built-in WebRTC/LiveKit media adaptation.
The application must not stably retain a confirmed `FALLBACK` parent. For a
diff --git a/docs/research/webrtc-p2p-screen-sharing.md b/docs/research/webrtc-p2p-screen-sharing.md
index e67966c9..d66de8c6 100644
--- a/docs/research/webrtc-p2p-screen-sharing.md
+++ b/docs/research/webrtc-p2p-screen-sharing.md
@@ -186,8 +186,8 @@ Chrome Android 也标为不支持。桌面模式、UA 或设备性能不能改
Web UI 后续只做最小诚实处理:运行时检查
`navigator.mediaDevices?.getDisplayMedia`,缺失时在建房/发布前明确显示不支持;
方法存在也只表示可以尝试,真实调用失败仍区分 denied/cancelled/capture-failed,
-不能按 UA 宣称兼容。移动 Viewer 不需要该 API,继续使用同一响应式 Web 播放端并保持
-leaf-only。
+不能按 UA 宣称兼容。移动 Viewer 不需要该 API,继续使用同一响应式 Web 播放端;
+relay capacity 与其他普通 Web Viewer 相同。
来源:
diff --git a/docs/status.md b/docs/status.md
index 80ac460d..5eedc86d 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -19,13 +19,13 @@ Flagship; parallel; min run/smoke/rollback; benchmark later. Active UI/config/lo
- Production access is `screener-v2`: a valid private fragment grant enters directly; every code-only Viewer must first hold site access, after which public-watch accepts the code and private rooms still require their room password. `SITE_ACCESS_PASSWORD`, `/api/site-access`, and the site-access cookie are deployed atomically; raw credentials are never stored.
- Source UI uses adjacent nickname editing, distinct site/room prompts, and a shared room-code form; production still has the prior UI. Exact upstream may label green P2P/yellow `SFU fallback` before media proof; connected status still needs evidence and TURN stays actual-only.
- Native v2 is source-only (memory rooms, 300s reclaim); it follows authenticated direct-child assignments up to two and fails unsupported SFU/selected ingress boundedly.
-- 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.
+- Production is roots <=2/Web relay <=1; source gives every Web Viewer cap2, one upstream and bounded sticky recovery. Room `1` is historical; HTTPS/WSS is 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` 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.
## Verified Evidence
-- Chrome 151 synthetic `1/3/5/8` and 720p30 quality-change runs kept 2/1 fanout and decoding; slowest first frame was 1.05 seconds and one relay close recovered in 5.32 seconds. This is control evidence only.
+- Chrome 151 synthetic `1/3/5/8` and 720p30 runs kept bounded fanout/decoding. A five-Viewer cap2 run had one relay serve two children (+80 decoded frames/~1.1 MB each), all decoded and no fatal; local typecheck, 31 files/458 tests and both builds pass. Functional only.
- Chrome 151 + local LiveKit 1.13.5/client 2.22.0 SFU/UDP passed after `q,f` -> `q,h`: one root, decoded 3 -> 23, rendered 26, Host edge one, clean leaves, no TURN. Functional only.
- 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.
- 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.
@@ -44,7 +44,7 @@ Flagship; parallel; min run/smoke/rollback; benchmark later. Active UI/config/lo
- Silent partitions can wait 30 to 60 seconds for heartbeat detection before the default 5-second grace; this remains unverified.
- 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, hardware, endurance, public/downloaded-package, and browser-diversity proof remain open.
-- Browser fanout is host two/viewer one; any accepted endpoint relay stays capped at two downstream edges.
+- Production fanout is Host2/Viewer1; source is Host2/Viewer2 and rejects child3. Resource behavior remains open.
- PR #49/#50 BWE is unverified/default-off: test zero-child leaves, then root impact. No local per-leaf UDP shaper; resume with Linux `tc` or public canary, never CDP. Web P2P/SVC shortcuts remain no-go.
- Headful fragment-to-sessionStorage consumption, invitation rotation after migration, and request/log leak inspection remain production UX gates. Accounts stay out.
- Structure debt: split `HybridMediaRouter`, `HostPage`, `SignalingServer`, and `ViewerPage` only at proven consumer boundaries, never by file length.
@@ -55,7 +55,7 @@ Next: representative production-room UDP/frame/cap/stop canary; room `1` is hist
Recovery uses one ICE restart, one same-parent rebuild, one alternate peer, then SFU. Next gate exactly-two/Dynacast-off BWE on a zero-child SFU leaf, then root evacuation.
Native WGC/MF passed one-Viewer hardware; package download, Viewer2/FIFO and game A/V remain. Benchmark later.
Ordinary peers stay STUN-only; initial ingress and `peer-selected` still need forced-relay proof.
-ADR-0004 still needs the 30-minute `1/3/5/8` matrix; a separate 20-viewer gate must pass before changing the default eight.
+ADR-0004 still needs its resource/quality matrix; the 20-viewer gate precedes a default change. Mobile uses the same capacity and is a compatibility observation.
## Blockers And Decisions
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 1020666a..8aa170ec 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"
@@ -194,7 +194,7 @@ Host 本地预览直接绑定现有 capture stream,不创建 viewer、`RTCPeer
探针按最小顺序落地:先在 host 同一个采样 tick 内关联 A+B,并携带明确 window、媒体/stats identity 和有效 delta;验证可靠后才增加只包含拓扑判定所需字段的受限、已鉴权 C 上报。不建设通用遥测 schema,只传派生后的协商字段,绝不上传 raw stats、raw SDP、candidate 地址或原始设备/网络标识;鉴权与关联只使用服务端签发的不透明 path/connection generation ID。
-Viewer 可通过已鉴权、绑定当前房间/路径代次的控制面报告需要 `LOW`,但它只是一条拓扑观测输入,不能命令内建 WebRTC/LiveKit 媒体层。报告必须限频、去重,并与 sender 的 Transport-CC/GCC、实际码率、RTT、丢包、重传及编码限制、派生协商 codec/profile/parameters(适用时含 `scalabilityMode`)和 viewer 的实际解码/丢帧/冻结表现交叉验证。UA、平台和设备型号不参与质量决策;现有 mobile/iPad 检测只用于保守设置 relay capacity。
+Viewer 可通过已鉴权、绑定当前房间/路径代次的控制面报告需要 `LOW`,但它只是一条拓扑观测输入,不能命令内建 WebRTC/LiveKit 媒体层。报告必须限频、去重,并与 sender 的 Transport-CC/GCC、实际码率、RTT、丢包、重传及编码限制、派生协商 codec/profile/parameters(适用时含 `scalabilityMode`)和 viewer 的实际解码/丢帧/冻结表现交叉验证。UA、平台和设备型号不参与质量或 relay capacity 决策。
SVC 的标准能力门禁已经静态关闭为 `no-go-web-svc-cross-path-hardware-contract`。WebRTC-SVC 只配置单个 outgoing sender,direct/peer receiver 没有对应的按层选择 API,独立 PeerConnection 之间也没有 shared-encode 契约;requested/applied codec/`scalabilityMode`、Media Capabilities `powerEfficient` 与 RTCStats encoder 字段不能证明编码器一定是硬件。Pinned LiveKit 虽能在 SFU 内为每个 subscriber 设置最大空间/时间层,但 client 2.22.0 会把 screen-share SVC 强制成三层 temporal-only `L1T3`,既没有低分辨率 base,也超过最多两层的门槛;这种 SFU 选层也不延伸到 direct/peer descendants。当前静态结论不运行 browser harness。未来只能由能明确锁定硬编、最多两层、跨 direct/peer/SFU 复用同一输出且通过游戏性能/延迟门槛的 native sender 以新决策重开。普通非分层编码包不能只靠转发生成另一档画质,实现路径差异只能用第二表示、合格的 scalable layers 或 relay/SFU 转码。
@@ -209,10 +209,10 @@ SVC 的标准能力门禁已经静态关闭为 `no-go-web-svc-cross-path-hardwar
普通移动浏览器当前只承担 Viewer。Chrome Android、Firefox Android 与 Safari
iOS 都没有可靠的 `getDisplayMedia()`;Web Host 入口必须检查运行时 API 并明确
区分 unsupported、用户拒绝/取消与 capture failure,不能用 UA、desktop mode
-或设备型号放行。该边界不影响普通手机浏览器观看;手机仍是 leaf-only,并继续通过真机矩阵。浏览器版本证据由
+或设备型号放行。该边界不影响普通手机浏览器观看或统一 relay capacity;移动表现继续作为真机兼容观察。浏览器版本证据由
[WebRTC 调研](./research/webrtc-p2p-screen-sharing.md)持有。
-移动端只承担响应式 Web Viewer 和 leaf 角色;Web Host 支持矩阵保持桌面 Chrome/Edge。
+移动端只承担响应式 Web Viewer;Web Host 支持矩阵保持桌面 Chrome/Edge。
Viewer 向电视投屏不进入媒体拓扑;系统级屏幕镜像现在由平台直接提供。Web 端后续只在运行时检测
`HTMLMediaElement.remote`,并在真实目标证明 live WebRTC `srcObject` 可远端播放后才
@@ -247,8 +247,8 @@ storage、room row 或 SQLite。
该临时 edge 不改写 active SFU assignment 或另建 route owner;attempt 存续期间
presence 的 active upstream 仍为 `sfu`,本地 ICE path 才报告 TURN transport。签发前按当前 assignment
-重新计算 parent 下游预算,Host 的 SFU publication 也占一边;Host 两边或 ViewerRelay
-一边已满且 target 不是现有 child 时 fail closed,不替换无关 child。
+重新计算 parent 下游预算,Host 的 SFU publication 也占一边;Host 或 ViewerRelay
+两边已满且 target 不是现有 child 时 fail closed,不替换无关 child。
普通 peer、LiveKit participant 与 selected-edge coturn 是三个明确 ICE 域。SFU
publisher/subscriber 只消费 revision-bound `sfu-config {url, token}`,再由 LiveKit
@@ -281,8 +281,7 @@ Coturn bearer 在 TTL 内不可撤销,HMAC 只证明 expiry 与 secret;应
收到和使用 rebuild,但不能宣称 coturn 对 room/edge 做了密码学绑定。
SFU 正常只作为 virtual parent 向一至两个必要 roots 发布;可靠 root 收到
-媒体后继续服务 sticky descendants。host/native root 最多两条下游媒体边,
-browser root/relay 最多一个 child。无法挂到健康 root 的极端 viewers 只能
+媒体后继续服务 sticky descendants。当前 host/native/Web root 或 relay 最多两条下游媒体边。无法挂到健康 root 的极端 viewers 只能
通过独立 `E`/central-egress cap 准入。普通 SFU 终止两侧 DTLS-SRTP;没有
应用层 E2EE 时 operator 可接触媒体,这一产品取舍必须保持可见。所有物理
hop 按[低服务器成本媒体路由](./research/low-server-media-routes.md)逐项计量。
@@ -369,7 +368,7 @@ hop 按[低服务器成本媒体路由](./research/low-server-media-routes.md)
5. 完成 automatic peer/SFU controller,并让 room `1` 仅作为历史 smoke fixture。
6. 可选 selected-edge TURN tuple、revision-bound one-use grant 与 parent/child rebuild 已在 source 和 production 配置闭环;下一功能验收只需一条 forced relay 媒体 smoke,完整网络/资源 benchmark 后置。ordinary STUN-only、SFU/UDP、coturn rollout 仍保持独立边界。
7. 在媒体主线阶段验收后,用一个原子 PR 迁移 site access、`screener-v2`、room-scoped Viewer grant 和 SQLite v2;同一部署切换客户端/服务端/环境和数据库备份,随后删除 v1 配置、wire 与测试。用户名/roster 保持独立。
-8. Windows Native fixed-`HIGH` 保持可选且不改变 Web 默认;移动端保持 Viewer leaf。Viewer-to-TV 只采用已验证的平台本地输出,不改变媒体路由。
+8. Windows Native fixed-`HIGH` 保持可选且不改变 Web 默认;移动端保持 Viewer-only 且不单独分配 relay capacity。Viewer-to-TV 只采用已验证的平台本地输出,不改变媒体路由。
任何一步只实现当前消费者需要的接口。不得为未来账号、第三种媒体拓扑或原生 sender 预建抽象层。
@@ -390,17 +389,19 @@ STUN-only;只有 controller-selected edge 可接收一次短期 grant。该边
恢复目标按证据和成本逐级升级:短暂 `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 或地址。
-实验只实现一个由服务端确定的广度优先拓扑:host 最多两个 child,每名 viewer 最多一个 child,因此形成两条按加入顺序平衡的 sticky 链。父节点只按深度和 `serverJoinSequence` 选择第一个空 slot。新 viewer 加入通常不搬动已有节点;唯一例外是纯 peer active route 没有 pending/SFU 时,无上游、无 child、无失败 parent 历史且刚声明一槽容量的 viewer,可在 Host 两槽已满时按加入序替换一个 childless、零容量 Host leaf,并把该 leaf 作为自己的唯一 child。Host 客户端先关闭旧 leaf edge 再启动新 relay edge,同一同步拓扑变更只推进一个 route revision。Parent 离开时仍只把失去 parent 的 subtree root 重新分配到第一个空 slot,其 descendants 保持连接。该规则不采集或组合 RTT、带宽、CPU、地理位置与质量评分,也不主动重平衡。没有 parent 时明确等待或拒绝,不能创建分享端第三条边。
+当前 source candidate 实现一个由服务端确定的广度优先活动拓扑:host 与普通 Web viewer 都最多两个 child。服务器可在多个合格 parent 中选择,但每名 viewer 同时只有一个 active upstream,活动媒体图保持无环。新 viewer 加入或容量释放时只接纳等待节点;节点断开或当前 edge 失败时只重新分配失去 parent 的直接 subtree root,其 descendants 保持连接。移除有两个 child 的 relay 时两个直接 roots 分别重新分配。客户端先关闭不再分配的旧 edge,再建立替代 edge;每次变更推进 route revision,stale signal/recovery 不得复活旧边。该规则不采集或组合 RTT、带宽、CPU、地理位置与质量评分,也不主动重平衡、多源接收或持续优化。没有 parent 时明确等待或拒绝,任一 endpoint 不能创建第三条边。
-该 one-child 浏览器实验在深度四时只能覆盖八名观看者,不能证明 20 人能力。目标 20 人需要资源门禁通过的 relay `downstreamCapacity=2`(两棵深度四二叉树理论可容纳 30 人,但这只是可达性)或受独立中央 egress cap 约束的 SFU 例外;必须实测逐跳重编码、上行、延迟和故障半径。未通过时保持当前默认八人,不增加深度或 Host fanout 来凑容量。
+当前固定 `downstreamCapacity=2` 让八名观看者的确定性广度优先 DAG 最大深度降到三;两棵深度四二叉子树理论可容纳 30 人,但这只是可达性,不能证明 20 人能力。目标 20 人仍必须实测逐跳重编码、上行、延迟和故障半径,或使用受独立中央 egress cap 约束的 SFU 例外。未通过时保持当前默认八人,不增加深度或 Host fanout 来凑容量。
-所有边都继续使用标准 WebRTC。每名 viewer 播放收到的 remote `MediaStream`,并把其中的 remote tracks 加入给唯一 child 的新 `RTCPeerConnection`。该路径会逐跳解码和重编码;实验必须记录每层 encode time、CPU/GPU、`qualityLimitationReason`、帧率、分辨率和延迟,不能称为 zero-copy 或 shared encode。
+所有边都继续使用标准 WebRTC。每名 viewer 播放收到的 remote `MediaStream`,并把同一组 remote tracks 加入最多两个 child 各自独立的 `RTCPeerConnection`。该路径会逐跳解码并为每个 outbound sender 重编码;实验必须记录每层 encode time、CPU/GPU、`qualityLimitationReason`、帧率、分辨率和延迟,不能称为 zero-copy 或 shared encode。
+
+固定 `2` 是当前上线档而非永久产品上限;后续统一 evidence-driven controller 可在独立验收后使用离散 `0/1/2/3`,不按 device/UA 分支,并由持续 sender bitrate、`availableOutgoingBitrate`、区间 encode time、`qualityLimitationReason`、loss/RTT 健康窗、server deployment hard ceiling 与 cooldown 共同限界。本次 slice 不实现该动态控制。H.264、hardware encode 或 shared encode 可降低编码成本或同观感码率,但每个 child 的网络副本仍独立存在。
Peer-assisted 信令只接受一个严格对象:`resolution` 为 `720p | 1080p | 1440p`,`maxFramerate` 为 15 至 60 的整数,`maxBitrate` 为 2,000,000 至 12,000,000 的整数,`degradationPreference` 为 `maintain-resolution | balanced | maintain-framerate`,缺字段、多余字段和越界值都拒绝。服务端用受房间容量限制的内存 Map 保存完整设置,默认 1080p60、8 Mbps、`balanced`,不写入 SQLite;停止分享时保留,房间被放弃或过期时删除。只有 peer-assisted host 可更新,鉴权快照和在线广播携带同一完整设置;普通 P2P 的严格鉴权 wire 保持原样,host 或 viewer 在该模式发送同步消息都会被拒绝。启用 SFU 时 publisher 也使用这一设置,不另建一套质量协议。
Viewer 在处理 peer-assisted 鉴权快照时先更新 `ViewerRelay` 的 desired settings,再应用拓扑分配;同一个串行队列协调 remote stream、当前 child 更新和以后重建的 child,因此它们读取同一最新目标。每个 `HostPeer` 也把初始 sender 配置、`replaceStream()` 和 `updateProfile()` 放进同一 sender-mutation queue;desired settings 在入队前同步更新,已排队操作执行时读取最新值,使快速连续修改保持 last-wins,而不增加版本号或确认协议。这里同步的是浏览器 sender 的目标上限,不是实际分辨率、帧率、码率或 shared encoding 的性能保证。
-spike 复用现有 screen stream 和浏览器 codec 协商,覆盖当前桌面 Chrome/Edge relay、按测试顺序位于链尾的当前 Android Chrome 与 iOS Safari leaf、最多八名 viewer;捕获存在时沿同一标准 WebRTC 路径带上音频。Encoded Transform/DataChannel/WebCodecs 媒体、SVC/simulcast、多树、转码、codec ladder、综合评分、移动端后台 relay 和跨模式 SFU 迁移不在本次 spike 内实现。该范围限制不能解释为拒绝产品所需的自动兜底;验收与失败即放弃条件以 ADR-0004 为准,自动路由由后续独立 ADR 定义。
+spike 复用现有 screen stream 和浏览器 codec 协商,当前普通 Web relay 不按桌面、Android 或 iOS UA 拆分 capacity,最多八名 viewer;捕获存在时沿同一标准 WebRTC 路径带上音频。移动真机表现作为非阻断兼容观察;Encoded Transform/DataChannel/WebCodecs 媒体、SVC/simulcast、多树、转码、codec ladder、综合评分、移动端后台 relay 和跨模式 SFU 迁移不在本次 spike 内实现。该范围限制不能解释为拒绝产品所需的自动兜底;验收与失败即放弃条件以 ADR-0004 为准,自动路由由后续独立 ADR 定义。
浏览器不保证多个 `RTCPeerConnection` 共享一次编码。实验允许 host 对一至两个 seed 各自编码。后续 native sender 必须让每个 active representation 只编码一次并跨 direct、peer 与 SFU transport 复用;每条连接仍拥有独立 packetizer、SSRC、pacing、加密、反馈和上传。健康路径选择共享 `HIGH`,最多另有一份弱路径共用的 `LOW`,是否常驻由硬件、游戏和上传门槛决定。该计划不依赖本次浏览器 relay 实验成败,也不在本 spike 中提前抽象或实现。
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 c1fd7210..8a763e72 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"
@@ -24,7 +24,7 @@
- [ ] 观看端本地音量:播放控制栏提供 `0%` 至 `100%` 音量条和静音按钮,只改变当前浏览器的媒体元素,不修改 Host 音轨、编码、房间状态或其他观看者。切流、换父和 ICE 恢复保留当前页面内的值;刷新后不持久化。静音保留上次非零音量,拖动到非零值自动取消静音。
- [ ] 本地昵称与房间成员:用户可设置一个只保存在当前浏览器同源 `localStorage` 的显示名,界面统一称为“昵称”;默认以只读文本显示,铅笔编辑按钮紧贴昵称,点击后才进入编辑。Viewer 顶部标题直接显示“{Host 名称} 的屏幕”,不得在下方重复一行 Host 名称。信令只在当前在线 socket 会话内保存和广播 NFC 规范化、最多 24 个 Unicode code points、拒绝控制/换行/双向覆盖符与孤立 surrogate 的纯文本标签,不写 SQLite 或日志。空值使用通用角色 fallback。Host 必须看到全部当前在线 Viewer 的权威总数与 roster,不能拿最多两条 Host 媒体直连数冒充在线人数;presence 更新也不得创建媒体连接。展示身份使用“名称 + 当前房间 `peerId` 的至少六字符短后缀”,房内碰撞时有界延长。显示名、后缀和 `clientId` 都不是账号、授权身份或全局 UUID,重复名称允许且不得参与授权、路由或质量决策。Web Host 与 Viewer 通过同一 opt-in participant roster 看到 Host 名称;Native 不发送 capability,wire 保持不变。
- [ ] 一对多观看:当前安全默认上限为 8、可配置范围为 1 至 16;自动分布式拓扑验收后,同一 release 将默认值和上限改为 20。当前 PoC 的逐观看者连接是测量基线,不再是超过两名观看者时的目标拓扑;未通过 20 人门禁时继续明确拒绝超额加入。
-- [ ] 端点 fanout 硬上限:任一非服务器端点任何时刻最多维护两条 active downstream media edges,包括加入、断线、换父和恢复过程;上游接收不计入这项上传预算。当前 browser relay 因逐跳重编码仍保守限制为一个 child,只有资源矩阵通过后才可升到二。第三名及后续观看者由系统自动分配给通过验收的 peer-assisted 拓扑,不能隐藏地回退为 Host 第三条连接。没有可行 peer path 时,SFU 作为主要中央兜底 virtual parent 正常向一至两个必要 roots 送流;媒体到达 root 后其余可行观看者仍优先沿受限 peer descendants 扩散。多个无法挂到健康 root 的极端 viewer 可成为额外 server-fed 例外,但必须受显式中央 egress/admission 上限约束,不能无界整房 fanout。TURN 只作为可选的极端网络 transport 兼容层,不定义房间拓扑。
+- [ ] 端点 fanout 硬上限:任一非服务器端点任何时刻最多维护两条 active downstream media edges,包括加入、断线、换父和恢复过程;上游接收不计入这项上传预算。普通 Web relay 统一声明最多两个 child,不按 UA、设备类型或页面可见性另建容量策略;实际 edge 失败进入同一有界换父路径。第三名及后续观看者由系统自动分配给通过验收的 peer-assisted 拓扑,不能隐藏地回退为 Host 第三条连接。没有可行 peer path 时,SFU 作为主要中央兜底 virtual parent 正常向一至两个必要 roots 送流;媒体到达 root 后其余可行观看者仍优先沿受限 peer descendants 扩散。多个无法挂到健康 root 的极端 viewer 可成为额外 server-fed 例外,但必须受显式中央 egress/admission 上限约束,不能无界整房 fanout。TURN 只作为可选的极端网络 transport 兼容层,不定义房间拓扑。
- [ ] P2P 优先:每条逻辑媒体边的 ICE 必须先尝试直接 UDP 路径,服务器不得默认中转可直连的媒体。一个或两个观看者优先直接连接分享端;更多观看者的 peer-assisted 行为须先通过 ADR-0004 的实验门槛。
- [ ] NAT 与传输兜底:STUN 必须可用,所有 ordinary peer `RTCPeerConnection` 只接收 STUN ICE servers。PC 失败后按一次 ICE restart、一次同 parent rebuild、一个 alternate peer、再 SFU/UDP virtual parent 的顺序恢复,任一步成功即停止;只有该 edge 的 SFU/UDP 也失败后,controller 才可授权一次短期 authenticated selected-edge TURN/UDP rebuild。授权必须绑定当前 room/share generation、viewer/parent session、route revision 与 old/new connection identity,成功、失败、超时或代次变化即消费;同一房间同时 pending 或 active 的 `peer-selected` attempt 总数最多为一,`host-sfu-ingress` 使用独立状态且不占该 last-mile 名额。不得按 participant、房间或普通 peer PC 下发,Native v2 保持 STUN-only。凭据不进入 URL、日志、浏览器持久化或 SQLite。Coturn 只验证 HMAC 与 expiry,应用必须重验 edge 代次并用短 TTL、one-use state 与 quota 限界。媒体 ICE/TCP、TURN/TCP 或 TURN/TLS 另行验收;HTTPS/WSS 仍使用 TLS/TCP。
- [ ] 质量控制:保留 1080p60(8 Mbps)、1080p30(5 Mbps)、720p30(3 Mbps)三档推荐上限,三档与高级设置初始值统一采用 `balanced`;分享期间可直接换档或应用有界高级设置,不重新选择来源或重建健康连接。Peer-assisted relay 与已配置的 SFU 必须接收同一个严格校验的房间级权威设置,覆盖当前和以后建立的 sender;普通 P2P 信令结构保持不变。任何设置都只是浏览器上限和偏好,具体降级由浏览器决定;必须读回实际 sender 参数并通过 stats 观测结果、显示参数拒绝、改写和持续受限原因。不做自定义动态 FPS、综合评分或周期性全房间调档。
@@ -45,9 +45,9 @@
- [ ] 纯 P2P 调试会话:Host 可在高级设置中为下一次分享临时选择“仅测试 P2P”。该选择只允许 Host 在新 share generation 的首次鉴权中请求,服务端权威阻止本次分享的 SFU prepare/config/publication、standby 和 selected-edge TURN,同时保留 STUN-only direct、ICE restart/rebuild 与一个 alternate peer;耗尽后明确失败。同 generation 信令重连保持且不能中途切换;停止分享、新 share generation、room 删除或服务端进程重启才清除。新进程可从 Host 不可变认证 identity 重新接受请求,并在 `authenticated` 中回显实际状态。设置不持久化,Viewer 不能设置。它只用于收集真实连接结果,不得宣称能稳定穿透 endpoint-dependent NAT。
- [ ] 质量控制扩展:推荐档位仍是默认入口;折叠高级区只允许 720p/1080p/1440p 分辨率 ceiling、15 至 60 的整数 FPS ceiling、2 至 12 Mbps 视频码率 ceiling,以及清晰/平衡/流畅三种偏好。直播中显式应用后才生效,避免滑杆产生连续控制流量。Web 不提供音频声道、采样率、Opus 码率、stereo、DTX 或 FEC 控件;每个实际浏览器音频 sender 固定请求并读回 128 kbps ceiling,SFU 音频发布使用同值 preset 且关闭 DTX。该值只是标准 API/SDK 支持的发送上限,实际码率仍以 stats 为准。display capture 未把声道和采样率定义为可移植控制,其他项依赖 codec/fmtp 协商而没有可移植 sender setter。不得为这些控件新增应用层 SDP munging 或用默认值制造伪控制。实际质量持续低于所选上限时必须显示可解释的限制原因;在真实拥塞、编码器和接收端证据完成前,不把任一组合称为“完美平衡”。
- [ ] 本地预览性能候选:在相同动态场景中 A/B 测量 Host 动态预览开/关的 CPU、GPU、encode time 和实际 FPS。只有稳定收益且捕获、编码和远端画面不受影响时,才允许直播开始后默认显示静止缩略图或隐藏动态预览并提供按需展开;未测前不宣称收益。
-- [ ] Peer-assisted 媒体实验:分享端最多两个 child、每名 viewer 最多一个 child;信令服务只按深度和服务端加入序号确定性地形成两条 sticky 平衡链,不加入综合评分或主动重平衡。每个 viewer 将收到的标准 remote track 通过新的 `RTCPeerConnection` 转发,因此会逐跳解码和重编码;必须测量而不能称为 shared encode。服务端只在受房间数限制的内存状态中保存当前严格校验的质量设置,不写入 SQLite;host 鉴权后先重报设置,在线 viewers 接收更新,后加入者从鉴权快照取得当前值。该功能在 ADR-0004 的实验门槛通过并由后续 ADR 正式接受前不得成为产品路径。
+- [ ] Peer-assisted 媒体路径:分享端与每名普通 Web viewer 都最多两个 child。信令服务维护可从多个合格节点选择 parent 的候选图,但每名 viewer 任一时刻只有一个 active upstream,活动媒体图保持无环;只在新加入、容量释放、节点断开或当前 edge 失败时按深度和服务端加入序号做有界分配或换父,不加入综合评分、主动重平衡、多源媒体或持续优化。每个 viewer 将收到的标准 remote track 通过最多两个新的 `RTCPeerConnection` 转发,因此会逐跳解码和分别重编码;必须测量而不能称为 shared encode。服务端只在受房间数限制的内存状态中保存当前严格校验的质量设置,不写入 SQLite;host 鉴权后先重报设置,在线 viewers 接收更新,后加入者从鉴权快照取得当前值。
- [ ] 原生 shared encode 分享端:后续独立的 Electron/原生分享端必须让每个 active representation 只产生一份兼容编码结果,并在 direct、peer 与 SFU transport 间复用;健康路径选择共享 `HIGH`,最多另有一份弱路径共用的 `LOW`,是否常驻由硬件、游戏和上传门槛决定。每条连接仍保留独立 WebRTC packetization、SSRC、pacing、加密和反馈,且各自消耗上传带宽。浏览器不保证跨 `RTCPeerConnection` 复用编码器,因此当前 Web spike 不能宣称满足该保证。
-- [ ] 原生 shared encode relay:具备原生 relay 能力的 audience 同样最多维护两条下游媒体边,并应复用兼容编码输出而不再次编码。普通浏览器 audience 继续作为 leaf 或使用当前会逐跳重编码的实验路径,不伪称 shared encode。
+- [ ] 原生 shared encode relay:具备原生 relay 能力的 audience 同样最多维护两条下游媒体边,并应复用兼容编码输出而不再次编码。普通浏览器 audience 使用当前最多两条下游、逐边重编码的标准 WebRTC 路径,不伪称 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 模式已被取代。room `1` 的历史 smoke 没有 retained SFU media;公网媒体、资源和恢复门禁仍适用于全站路由。
@@ -60,6 +60,7 @@
### P2 - 可选功能
+- [ ] 证据驱动的统一 relay capacity:当前上线档固定为 `2`,不是永久产品上限。后续只在独立验收后允许所有 Web relay 使用同一套离散 `0/1/2/3` 容量状态,不按设备或 UA 分类;持续 sender bitrate、`availableOutgoingBitrate`、区间 encode time、`qualityLimitationReason`、loss 与 RTT 健康窗共同决定升降,服务端 deployment hard ceiling 与 cooldown 继续限界。H.264、hardware encode 或 shared encode 可以降低编码成本或同观感码率,但每个 child 仍消耗一份网络副本。本次 slice 不实现动态控制。
- [x] 原生 Windows 捕获辅助程序:显式 `native-window-h264` 模式使用同一 bound window target 的 WGC/D3D11 画面与 WASAPI process-tree PCM,并用 adapter-bound、hardware-only Media Foundation H.264 `42c01f` 直接进入现有 Go fanout;浏览器 VP8/H.264 是显式替代选项,VP8 默认,不允许运行时静默改用软件编码、显示器画面或系统混音。一名普通 Chrome Viewer 已 decoded/rendered 203 帧并收到 500 Opus packets,同一 helper PID/adapter 的 `VideoEncode` 与 LUID 匹配。
- [ ] Viewer 向电视输出:系统级屏幕镜像现在可直接使用;产品只复用平台 AirPlay/Cast,不自造投屏协议。截至 2026-08-21,Chromium 的 Remote Playback URL 路径和 WebKit 明确拒绝 wireless target 的 live `MediaStream` player 均未给当前 WebRTC `srcObject` 提供可用契约,因此不显示伪可用入口。只在浏览器实现明确支持并由实体 Apple TV 或 Chromecast/Google TV 证明当前 live 画面与音频后,才按通过的平台加入 Viewer 本地图标按钮。投屏不能改变 room、TURN/SFU/peer route、Host fanout 或服务端媒体分发;Google Cast receiver 需要可获取的媒体 URL,当前 P2P `MediaStream` 不满足该输入,因此不加入 Cast SDK/receiver。
- [ ] 多地区 SFU-root 调度,以及可选 TURN 兼容层的按地区、运营商可达率。
@@ -75,7 +76,7 @@
- 可维护性:代码、需求、调研、项目记忆、`AGENTS.md` 和 `.codex/` 均在 Git 中跟踪;开发配置不得依赖单一操作系统的绝对路径。
- 迁移完整性:同一 release 的客户端、服务端和部署配置原子迁移;canary 结束后删除被替代的配置、wire、parser、双写与测试,不为无当前消费者的旧版本保留兼容层或第二套架构。Git 历史承担旧实现追溯。
- Web 优先:每项用户能力先使用普通浏览器的标准 API 和正常权限流程;只有当前目标浏览器存在已证实的能力缺口且该功能仍属当前范围时,才允许独立、可选的 Sender。不得为假设中的未来能力预建客户端、兼容层或第二套会话架构。
-- 兼容性:分享端首个目标矩阵为 Windows 10/11 的当前 Chrome/Edge;普通移动浏览器当前只属于 Viewer 矩阵。截止 2026-08-21,MDN Browser Compatibility Data 仍将 Chrome Android、Firefox Android 和 Safari iOS 的 `getDisplayMedia()` 标为不支持;Web Host 必须用运行时能力检测,API 缺失时明确显示不支持,API 存在但调用拒绝时区分用户拒绝/取消与 capture failure,不能用 UA/设备型号伪造兼容。观看端仍必须覆盖当前 Android Chrome 和 iOS Safari,并实测自动播放限制、横竖屏、锁屏恢复与移动网络切换。Peer-assisted 实验只允许能力完整的前台桌面 Chrome/Edge 作为 relay,手机必须保持 leaf。
+- 兼容性:分享端首个目标矩阵为 Windows 10/11 的当前 Chrome/Edge;普通移动浏览器当前只属于 Viewer 矩阵。截止 2026-08-21,MDN Browser Compatibility Data 仍将 Chrome Android、Firefox Android 和 Safari iOS 的 `getDisplayMedia()` 标为不支持;Web Host 必须用运行时能力检测,API 缺失时明确显示不支持,API 存在但调用拒绝时区分用户拒绝/取消与 capture failure,不能用 UA/设备型号伪造兼容。观看端仍必须覆盖当前 Android Chrome 和 iOS Safari,并实测自动播放限制、横竖屏、锁屏恢复与移动网络切换。普通 Web Viewer 统一使用当前 relay capacity `2`;移动真机表现是兼容观察,不建立单独 route class。
## 边界与约束
@@ -130,14 +131,14 @@
### 一对多与带宽保护
- 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 peer-assisted 路径分别运行 1、3、5、8 名观看者,When 用户加入、容量释放、节点离开或当前 edge 失效,Then 服务端使用同一个确定性广度优先规则,只为新 viewer、等待 viewer 或失去 parent 的 subtree root 选择一个 active parent;其余健康边保持 sticky。分享端与每名 viewer 在每个瞬时采样都不超过两个 child,移除有两个 child 的 relay 会分别重新分配两个直接 subtree roots,第三个 child 不建立媒体边;除此之外没有可用 parent 时明确等待或拒绝,不主动重平衡、引入多源媒体或增加分享端 fanout。
- Given 一名分享者和八名观看者,When 在受控网络中运行已记录的质量档位,Then 记录每条边的拓扑深度、候选类型、码率、编码/解码负载、分享端与 relay 上行、首帧和玻璃到玻璃延迟;该条在真实矩阵完成前保持未验收。
- 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 拓扑判为通过。
- Given 新观看者会使预计总上行超过安全预算,When 其请求加入,Then 系统先遵守两边 fanout 预算选择 peer-assisted 或已配置的 SFU;没有合格路线时明确等待或拒绝,而不是创建第三条 host 边或持续堆积发送队列。Direct/peer GCC 与 SFU BWE 各自适应该路径,应用证据只改变拓扑资格,不能合成全房降档。
-- Given TURN 或 SFU 被某条路线使用,When 媒体已抵达一至两个可靠 root,Then 其余可行 viewers 仍由 sticky、受深度与故障半径限制的 peer descendants 服务;host/root fanout 不超过二,当前 browser relay 不超过一个 child,中央服务和任一 endpoint 都不得无界集中 fanout。
+- Given TURN 或 SFU 被某条路线使用,When 媒体已抵达一至两个可靠 root,Then 其余可行 viewers 仍由 sticky、受深度与故障半径限制的 peer descendants 服务;host/root 和当前 browser relay fanout 均不超过二,中央服务和任一 endpoint 都不得无界集中 fanout。
- Given 没有任何满足能力、深度、路径和恢复门槛的可靠 relay root,When 控制器穷尽 peer recovery,Then SFU 可把必要 viewers 作为零-descendant roots;正常仍限一至二 roots,多个异常 viewers 只能使用另行配置的中央 egress cap,否则明确等待或失败,不得变成无界整房 SFU。
### 质量和恢复
diff --git a/scripts/peer-assisted-benchmark.ts b/scripts/peer-assisted-benchmark.ts
index a570a735..37b192a9 100644
--- a/scripts/peer-assisted-benchmark.ts
+++ b/scripts/peer-assisted-benchmark.ts
@@ -708,9 +708,9 @@ export function buildRunChecks(
},
{
name: "relay-active-media-edges",
- passed: summary.maxRelayActiveMediaEdges <= 1,
+ passed: summary.maxRelayActiveMediaEdges <= 2,
actual: summary.maxRelayActiveMediaEdges,
- expected: "<= 1",
+ expected: "<= 2",
},
{
name: "all-viewers-decoded",
diff --git a/src/client/media/relay-capability.ts b/src/client/media/relay-capability.ts
index 7140c09a..557589bd 100644
--- a/src/client/media/relay-capability.ts
+++ b/src/client/media/relay-capability.ts
@@ -1,51 +1,18 @@
import type { ClientMessage } from "../../shared/protocol";
-export interface BrowserRelayEnvironment {
- userAgent: string;
- userAgentDataMobile?: boolean;
- maxTouchPoints: number;
-}
-
type RelayCapacityMessage = Extract<
ClientMessage,
{ type: "relay-capacity" }
>;
-export function detectBrowserRelayCapacity(
- environment: BrowserRelayEnvironment,
-): 0 | 1 {
- if (
- environment.userAgentDataMobile === true ||
- /Android|iPhone|iPad|iPod|Mobile/i.test(environment.userAgent) ||
- (/Macintosh/i.test(environment.userAgent) &&
- environment.maxTouchPoints > 1)
- ) {
- return 0;
- }
- return 1;
-}
-
export function relayCapacityMessageForBrowser(
peerAssisted: boolean,
- environment?: BrowserRelayEnvironment,
): RelayCapacityMessage | null {
if (!peerAssisted) {
return null;
}
- const browser = environment ?? currentBrowserEnvironment();
return {
type: "relay-capacity",
- downstreamEdges: detectBrowserRelayCapacity(browser),
- };
-}
-
-function currentBrowserEnvironment(): BrowserRelayEnvironment {
- const browserNavigator = navigator as Navigator & {
- userAgentData?: { mobile?: boolean };
- };
- return {
- userAgent: browserNavigator.userAgent,
- userAgentDataMobile: browserNavigator.userAgentData?.mobile,
- maxTouchPoints: browserNavigator.maxTouchPoints,
+ downstreamEdges: 2,
};
}
diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsx
index ee3d3149..689f1328 100644
--- a/src/client/pages/ViewerPage.tsx
+++ b/src/client/pages/ViewerPage.tsx
@@ -276,7 +276,8 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
}
function acceptRelayChildEvidence(evidence: ViewerQualityEvidence): void {
- const relaySnapshot = viewerRelay?.getSnapshot() ?? null;
+ const relaySnapshot =
+ viewerRelay?.getSnapshot(evidence.viewerPeerId) ?? null;
if (
!peerAssisted ||
evidence.parentPeerId !== currentPeerId ||
@@ -328,7 +329,9 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
relayChildEvidenceCurrent &&
!qualityEvidenceMatchesSnapshot(
relayChildEvidenceCurrent,
- snapshot,
+ viewerRelay?.getSnapshot(
+ relayChildEvidenceCurrent.viewerPeerId,
+ ) ?? null,
)
) {
clearRelayChildEvidence();
@@ -337,10 +340,30 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
},
},
);
- viewerRelay.setChild(currentAssignment.childPeerIds[0] ?? null);
+ viewerRelay.setChildren(currentAssignment.childPeerIds);
return viewerRelay;
}
+ function reconcileRelayChildren(
+ previousChildPeerIds: readonly string[],
+ ): void {
+ const nextChildPeerIds = currentAssignment.childPeerIds;
+ const changed =
+ previousChildPeerIds.length !== nextChildPeerIds.length ||
+ previousChildPeerIds.some(
+ (peerId, index) => peerId !== nextChildPeerIds[index],
+ );
+ for (const peerId of previousChildPeerIds) {
+ if (!nextChildPeerIds.includes(peerId)) {
+ parentEdgeQualityEvidenceReporter.forget(peerId);
+ }
+ }
+ if (changed) {
+ clearRelayChildEvidence();
+ }
+ ensureViewerRelay()?.setChildren(nextChildPeerIds);
+ }
+
function ensureViewerSfuRoute(): ViewerSfuRoute {
if (viewerSfuRoute) {
return viewerSfuRoute;
@@ -380,13 +403,13 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
parentEdgeQualityEvidenceReporter.reset();
setSfuUpstream(null);
clearPeerState();
- viewerRelay?.setChild(null);
+ viewerRelay?.setChildren([]);
},
reconcileSfuChildren: (childPeerIds) => {
if (!active || viewerSfuRoute !== route) {
return;
}
- const previousChildId = currentAssignment.childPeerIds[0] ?? null;
+ const previousChildPeerIds = currentAssignment.childPeerIds;
currentAssignment = limitMediaAssignment(
{
parentPeerId: currentAssignment.parentPeerId,
@@ -394,15 +417,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
},
MAX_VIEWER_MEDIA_CHILDREN,
);
- if (
- previousChildId &&
- previousChildId !== (currentAssignment.childPeerIds[0] ?? null)
- ) {
- parentEdgeQualityEvidenceReporter.forget(previousChildId);
- }
- ensureViewerRelay()?.setChild(
- currentAssignment.childPeerIds[0] ?? null,
- );
+ reconcileRelayChildren(previousChildPeerIds);
},
onSfuUpdate: (metrics) => {
if (active && viewerSfuRoute === route) {
@@ -432,19 +447,13 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
if (!active || viewerSfuRoute !== route) {
return;
}
- const previousChildId = currentAssignment.childPeerIds[0] ?? null;
+ const previousChildPeerIds = currentAssignment.childPeerIds;
currentAssignment = limitMediaAssignment(
{ parentPeerId: null, childPeerIds: assignment.childPeerIds },
MAX_VIEWER_MEDIA_CHILDREN,
);
- if (
- previousChildId &&
- previousChildId !== (currentAssignment.childPeerIds[0] ?? null)
- ) {
- parentEdgeQualityEvidenceReporter.forget(previousChildId);
- }
+ reconcileRelayChildren(previousChildPeerIds);
const relay = ensureViewerRelay();
- relay?.setChild(currentAssignment.childPeerIds[0] ?? null);
relay?.setStream(nextStream);
setRemoteStream(nextStream);
setSfuUpstream(
@@ -524,20 +533,14 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
MAX_VIEWER_MEDIA_CHILDREN,
);
const previousParentId = currentAssignment.parentPeerId;
- const previousChildId = currentAssignment.childPeerIds[0] ?? null;
+ const previousChildPeerIds = currentAssignment.childPeerIds;
currentAssignment = nextAssignment;
if (previousParentId !== nextAssignment.parentPeerId) {
clearUpstreamState();
setStatusText("正在恢复连接");
}
- if (previousChildId !== (nextAssignment.childPeerIds[0] ?? null)) {
- if (previousChildId) {
- parentEdgeQualityEvidenceReporter.forget(previousChildId);
- }
- clearRelayChildEvidence();
- }
- ensureViewerRelay()?.setChild(nextAssignment.childPeerIds[0] ?? null);
+ reconcileRelayChildren(previousChildPeerIds);
}
function ensurePeer(): ViewerPeer | null {
@@ -657,6 +660,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
? message.routeRevision
: 0;
if (nextRouteRevision !== currentRouteRevision) {
+ viewerRelay?.clearSelectedEdgeTurn();
clearRelayChildEvidence();
}
currentRouteRevision = nextRouteRevision;
@@ -728,17 +732,23 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
if (message.edgeKind !== "peer-selected") {
return;
}
+ if (!peerAssisted) {
+ return;
+ }
+ if (message.parentPeerId === currentPeerId) {
+ ensureViewerRelay()?.startSelectedEdgeTurn(
+ message,
+ currentPeerId,
+ currentRouteRevision,
+ );
+ return;
+ }
if (
- !peerAssisted ||
message.revision !== currentRouteRevision ||
Date.parse(message.expiresAt) <= Date.now()
) {
return;
}
- if (message.parentPeerId === currentPeerId) {
- ensureViewerRelay()?.startSelectedEdgeTurn(message);
- return;
- }
const currentIdentity =
peerRef.current?.getConnectionIdentity() ?? retiredUpstream;
if (
@@ -765,6 +775,9 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
if (message.type === "route-update") {
if (peerAssisted) {
if (message.phase === "active") {
+ if (message.revision !== currentRouteRevision) {
+ viewerRelay?.clearSelectedEdgeTurn();
+ }
if (selectedEdgeTurn?.revision !== message.revision) {
selectedEdgeTurn = null;
}
@@ -813,12 +826,12 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
}
if (
peerAssisted &&
- currentAssignment.childPeerIds[0] === message.fromPeerId
- ) {
- await viewerRelay?.acceptSignal(
+ (await viewerRelay?.acceptSignal(
message.fromPeerId,
message.payload,
- );
+ currentRouteRevision,
+ ))
+ ) {
return;
}
if (
diff --git a/src/client/webrtc/media-assignment.ts b/src/client/webrtc/media-assignment.ts
index 120f76cf..b50b4977 100644
--- a/src/client/webrtc/media-assignment.ts
+++ b/src/client/webrtc/media-assignment.ts
@@ -5,7 +5,7 @@ import type {
} from "../../shared/protocol";
export const MAX_HOST_MEDIA_CHILDREN = 2;
-export const MAX_VIEWER_MEDIA_CHILDREN = 1;
+export const MAX_VIEWER_MEDIA_CHILDREN = 2;
export function limitMediaAssignment(
assignment: MediaAssignment,
diff --git a/src/client/webrtc/viewer-relay.ts b/src/client/webrtc/viewer-relay.ts
index e29b2ddb..f66376ab 100644
--- a/src/client/webrtc/viewer-relay.ts
+++ b/src/client/webrtc/viewer-relay.ts
@@ -6,6 +6,7 @@ import type {
import type { QualityProfile } from "../media/quality";
import type { PeerSnapshot } from "../types";
import { HostPeer } from "./host-peer";
+import { MAX_VIEWER_MEDIA_CHILDREN } from "./media-assignment";
interface ViewerRelayEvents {
sendSignal: (peerId: string, payload: SignalPayload) => boolean;
@@ -15,14 +16,19 @@ type SelectedEdgeTurn = Extract<
ServerMessage,
{ type: "selected-edge-turn"; edgeKind: "peer-selected" }
>;
+interface SelectedChildConnection {
+ peerId: string;
+ connectionId: string;
+ revision: number;
+}
export class ViewerRelay {
- private childPeerId: string | null = null;
+ private childPeerIds: string[] = [];
private stream: MediaStream | null = null;
- private peer: HostPeer | null = null;
- private snapshot: PeerSnapshot | null = null;
- private retiredConnection: { peerId: string; connectionId: string } | null =
- null;
+ private readonly peers = new Map<string, HostPeer>();
+ private readonly snapshots = new Map<string, PeerSnapshot>();
+ private readonly retiredConnections = new Map<string, string>();
+ private selectedChildConnection: SelectedChildConnection | null = null;
private syncQueue = Promise.resolve();
private disposed = false;
@@ -32,52 +38,101 @@ export class ViewerRelay {
private readonly events: ViewerRelayEvents,
) {}
- getSnapshot(): PeerSnapshot | null {
- return this.snapshot
- ? { ...this.snapshot, metrics: { ...this.snapshot.metrics } }
+ getSnapshot(childPeerId?: string): PeerSnapshot | null {
+ const peerId =
+ childPeerId ??
+ this.childPeerIds.find((candidate) => this.snapshots.has(candidate));
+ const snapshot = peerId ? this.snapshots.get(peerId) : undefined;
+ return snapshot
+ ? { ...snapshot, metrics: { ...snapshot.metrics } }
: null;
}
startSelectedEdgeTurn(
message: SelectedEdgeTurn,
+ parentPeerId: string,
+ routeRevision: number,
+ now = Date.now(),
): boolean {
const stream = this.stream;
- const connection = this.peer
- ? { peerId: this.peer.peerId, connectionId: this.peer.connectionId }
- : this.retiredConnection;
+ const currentPeer = this.peers.get(message.viewerPeerId);
+ const connectionId =
+ currentPeer?.connectionId ??
+ this.retiredConnections.get(message.viewerPeerId);
+ const selected = this.selectedChildConnection;
+ const retainedChildPeerIds = selected
+ ? this.childPeerIds.filter((peerId) => peerId !== selected.peerId)
+ : this.childPeerIds;
if (
this.disposed ||
!stream ||
- connection?.peerId !== message.viewerPeerId ||
- connection.connectionId !== message.oldConnectionId
+ message.parentPeerId !== parentPeerId ||
+ message.revision !== routeRevision ||
+ Date.parse(message.expiresAt) <= now ||
+ connectionId !== message.oldConnectionId ||
+ (!retainedChildPeerIds.includes(message.viewerPeerId) &&
+ retainedChildPeerIds.length >= MAX_VIEWER_MEDIA_CHILDREN)
) {
return false;
}
- this.disposePeer();
- this.childPeerId = message.viewerPeerId;
+ if (selected) {
+ this.clearSelectedEdgeTurn();
+ }
+ if (!this.childPeerIds.includes(message.viewerPeerId)) {
+ this.childPeerIds.push(message.viewerPeerId);
+ }
+ this.disposePeer(message.viewerPeerId);
+ this.selectedChildConnection = {
+ peerId: message.viewerPeerId,
+ connectionId: message.newConnectionId,
+ revision: message.revision,
+ };
this.startPeer(message.viewerPeerId, stream, 0, message);
return true;
}
- setChild(childPeerId: string | null): void {
+ clearSelectedEdgeTurn(): void {
+ const selected = this.selectedChildConnection;
+ if (!selected) {
+ return;
+ }
+ this.selectedChildConnection = null;
+ this.childPeerIds = this.childPeerIds.filter(
+ (peerId) => peerId !== selected.peerId,
+ );
+ this.disposePeer(selected.peerId);
+ }
+
+ setChildren(childPeerIds: readonly string[]): void {
if (this.disposed) {
return;
}
- if (this.childPeerId === childPeerId) {
- if (
- childPeerId &&
- this.stream &&
- (!this.peer || !this.peer.isConnected())
- ) {
- this.disposePeer();
- this.startPeer(childPeerId, this.stream);
+ const nextChildPeerIds = [...new Set(childPeerIds)].slice(
+ 0,
+ MAX_VIEWER_MEDIA_CHILDREN,
+ );
+ const selectedPeerId = this.selectedChildConnection?.peerId ?? null;
+ if (selectedPeerId && !nextChildPeerIds.includes(selectedPeerId)) {
+ if (nextChildPeerIds.length >= MAX_VIEWER_MEDIA_CHILDREN) {
+ nextChildPeerIds.pop();
+ }
+ nextChildPeerIds.push(selectedPeerId);
+ }
+ for (const childPeerId of this.childPeerIds) {
+ if (!nextChildPeerIds.includes(childPeerId)) {
+ this.disposePeer(childPeerId);
}
- return;
}
- this.disposePeer();
- this.childPeerId = childPeerId;
- if (childPeerId && this.stream) {
- this.startPeer(childPeerId, this.stream);
+ this.childPeerIds = nextChildPeerIds;
+ for (const childPeerId of this.childPeerIds) {
+ const peer = this.peers.get(childPeerId);
+ if (childPeerId === selectedPeerId) {
+ continue;
+ }
+ if (this.stream && (!peer || !peer.isConnected())) {
+ this.disposePeer(childPeerId);
+ this.startPeer(childPeerId, this.stream);
+ }
}
}
@@ -107,11 +162,22 @@ export class ViewerRelay {
async acceptSignal(
fromPeerId: string,
payload: SignalPayload,
- ): Promise<void> {
- if (fromPeerId !== this.childPeerId) {
- return;
+ routeRevision: number,
+ ): Promise<boolean> {
+ const peer = this.peers.get(fromPeerId);
+ const selected = this.selectedChildConnection;
+ if (
+ !this.childPeerIds.includes(fromPeerId) ||
+ !peer ||
+ peer.connectionId !== payload.connectionId ||
+ (selected?.peerId === fromPeerId &&
+ (selected.connectionId !== payload.connectionId ||
+ selected.revision !== routeRevision))
+ ) {
+ return false;
}
- await this.peer?.acceptSignal(payload);
+ await peer.acceptSignal(payload);
+ return true;
}
async recover(
@@ -120,15 +186,15 @@ export class ViewerRelay {
rebuild: boolean,
): Promise<void> {
const stream = this.stream;
- const peer = this.peer;
- if (this.disposed || !stream || fromPeerId !== this.childPeerId) {
+ const peer = this.peers.get(fromPeerId);
+ if (this.disposed || !stream || !this.childPeerIds.includes(fromPeerId)) {
return;
}
if (rebuild) {
if (peer && peer.connectionId !== connectionId) {
return;
}
- this.disposePeer();
+ this.disposePeer(fromPeerId);
this.startPeer(fromPeerId, stream);
return;
}
@@ -138,20 +204,23 @@ export class ViewerRelay {
if (await peer.restartIce()) {
return;
}
- if (this.peer === peer) {
- this.disposePeer();
+ if (this.peers.get(fromPeerId) === peer) {
+ this.disposePeer(fromPeerId);
this.startPeer(fromPeerId, stream);
}
}
updateIceConfig(iceConfig: IceConfig): void {
this.iceConfig = iceConfig;
- this.peer?.updateIceConfig(iceConfig);
+ for (const peer of this.peers.values()) {
+ peer.updateIceConfig(iceConfig);
+ }
}
stop(): void {
this.stream = null;
- this.disposePeer();
+ this.clearSelectedEdgeTurn();
+ this.disposePeers();
}
dispose(): void {
@@ -160,16 +229,27 @@ export class ViewerRelay {
}
this.disposed = true;
this.stream = null;
- this.childPeerId = null;
- this.disposePeer();
+ this.selectedChildConnection = null;
+ this.childPeerIds = [];
+ this.disposePeers();
}
private async syncStream(stream: MediaStream): Promise<void> {
- const childPeerId = this.childPeerId;
- if (this.disposed || this.stream !== stream || !childPeerId) {
+ if (this.disposed || this.stream !== stream) {
return;
}
- const peer = this.peer;
+ await Promise.all(
+ this.childPeerIds.map((childPeerId) =>
+ this.syncPeerStream(childPeerId, stream),
+ ),
+ );
+ }
+
+ private async syncPeerStream(
+ childPeerId: string,
+ stream: MediaStream,
+ ): Promise<void> {
+ const peer = this.peers.get(childPeerId);
if (!peer) {
this.startPeer(childPeerId, stream);
return;
@@ -184,13 +264,13 @@ export class ViewerRelay {
if (
replaced ||
this.disposed ||
- this.peer !== peer ||
+ this.peers.get(childPeerId) !== peer ||
this.stream !== stream ||
- this.childPeerId !== childPeerId
+ !this.childPeerIds.includes(childPeerId)
) {
return;
}
- this.disposePeer();
+ this.disposePeer(childPeerId);
this.startPeer(childPeerId, stream);
}
@@ -198,11 +278,17 @@ export class ViewerRelay {
if (this.disposed || this.desiredProfile !== profile) {
return false;
}
- const peer = this.peer;
- if (!peer) {
+ const peers = [...this.peers.entries()];
+ if (peers.length === 0) {
return true;
}
- return peer.updateProfile(this.desiredProfile);
+ const results = await Promise.all(
+ peers.map(async ([childPeerId, peer]) =>
+ this.peers.get(childPeerId) !== peer ||
+ (await peer.updateProfile(this.desiredProfile)),
+ ),
+ );
+ return this.desiredProfile === profile && results.every(Boolean);
}
private startPeer(
@@ -213,9 +299,9 @@ export class ViewerRelay {
): void {
if (
this.disposed ||
- this.peer ||
+ this.peers.has(childPeerId) ||
this.stream !== stream ||
- this.childPeerId !== childPeerId
+ !this.childPeerIds.includes(childPeerId)
) {
return;
}
@@ -231,26 +317,26 @@ export class ViewerRelay {
{
sendSignal: (targetPeerId, payload) =>
!this.disposed &&
- this.peer === peer &&
- this.childPeerId === targetPeerId
+ this.peers.get(childPeerId) === peer &&
+ childPeerId === targetPeerId
? this.events.sendSignal(targetPeerId, payload)
: false,
onUpdate: (snapshot) => {
if (
!this.disposed &&
- this.peer === peer &&
- this.childPeerId === childPeerId &&
+ this.peers.get(childPeerId) === peer &&
+ this.childPeerIds.includes(childPeerId) &&
snapshot.peerId === childPeerId &&
snapshot.connectionId === peer.connectionId
) {
if (selectedTurn && snapshot.connectionState === "failed") {
- this.disposePeer();
+ this.disposePeer(childPeerId);
return;
}
- this.snapshot = {
+ this.snapshots.set(childPeerId, {
...snapshot,
metrics: { ...snapshot.metrics },
- };
+ });
this.events.onUpdate?.(this.getSnapshot());
}
},
@@ -258,21 +344,21 @@ export class ViewerRelay {
selectedTurn !== undefined,
selectedTurn?.newConnectionId,
);
- this.peer = peer;
+ this.peers.set(childPeerId, peer);
void peer
.start()
.catch(() => false)
.then((started) => {
- if (started || this.peer !== peer) {
+ if (started || this.peers.get(childPeerId) !== peer) {
return;
}
- this.disposePeer();
+ this.disposePeer(childPeerId);
if (
!selectedTurn &&
attempt < 1 &&
!this.disposed &&
this.stream === stream &&
- this.childPeerId === childPeerId
+ this.childPeerIds.includes(childPeerId)
) {
window.setTimeout(() => {
this.startPeer(childPeerId, stream, attempt + 1);
@@ -281,17 +367,37 @@ export class ViewerRelay {
});
}
- private disposePeer(): void {
- const peer = this.peer;
+ private disposePeers(): void {
+ for (const childPeerId of [...this.peers.keys()]) {
+ this.disposePeer(childPeerId);
+ }
+ }
+
+ private disposePeer(childPeerId: string): void {
+ const peer = this.peers.get(childPeerId);
+ if (
+ peer &&
+ this.selectedChildConnection?.peerId === childPeerId &&
+ this.selectedChildConnection.connectionId === peer.connectionId
+ ) {
+ this.selectedChildConnection = null;
+ this.childPeerIds = this.childPeerIds.filter(
+ (peerId) => peerId !== childPeerId,
+ );
+ }
if (peer) {
- this.retiredConnection = {
- peerId: peer.peerId,
- connectionId: peer.connectionId,
- };
+ this.retiredConnections.delete(childPeerId);
+ this.retiredConnections.set(childPeerId, peer.connectionId);
+ while (this.retiredConnections.size > MAX_VIEWER_MEDIA_CHILDREN) {
+ const oldestPeerId = this.retiredConnections.keys().next().value;
+ if (typeof oldestPeerId === "string") {
+ this.retiredConnections.delete(oldestPeerId);
+ }
+ }
}
- this.peer = null;
- this.snapshot = null;
- this.events.onUpdate?.(null);
+ this.peers.delete(childPeerId);
+ this.snapshots.delete(childPeerId);
+ this.events.onUpdate?.(this.getSnapshot());
peer?.dispose();
}
}
diff --git a/src/server/hybrid-media-router.ts b/src/server/hybrid-media-router.ts
index 37ae479a..588ce545 100644
--- a/src/server/hybrid-media-router.ts
+++ b/src/server/hybrid-media-router.ts
@@ -647,7 +647,7 @@ export class HybridMediaRouter {
.get(participant.roomId)
?.get(participant.peerId);
const allowAdmissionRescue =
- downstreamEdges === 1 &&
+ downstreamEdges > 0 &&
active?.sfu.publicationGeneration === null &&
active.assignments.get(participant.peerId)?.upstream.kind === "none" &&
controller?.getPendingRoute() === undefined &&
@@ -1055,11 +1055,10 @@ export class HybridMediaRouter {
const parent = this.connectedPeer(roomId, intent.failedParentPeerId);
const shareGeneration = this.options.getShareGeneration(roomId);
const parentAssignment = active.assignments.get(intent.failedParentPeerId);
- const parentChildLimit =
- intent.failedParentPeerId ===
- this.peerRelayTopology.getHostPeerId(roomId)
- ? 2
- : 1;
+ const parentChildLimit = this.peerRelayTopology.getDownstreamCapacity(
+ roomId,
+ intent.failedParentPeerId,
+ );
if (
viewer?.sessionId !== intent.sessionId ||
parent?.sessionId !== intent.failedParentSessionId ||
diff --git a/src/server/peer-relay-topology.ts b/src/server/peer-relay-topology.ts
index fb693023..fb129de6 100644
--- a/src/server/peer-relay-topology.ts
+++ b/src/server/peer-relay-topology.ts
@@ -110,10 +110,15 @@ export class PeerRelayTopology {
if (
options.rescueUnassignedRelay &&
previousDownstreamEdges === 0 &&
- downstreamEdges === 1
+ downstreamEdges > 0
) {
this.rescueUnassignedRelay(room, peerId, connectedPeerIds);
}
+ for (const [candidatePeerId, candidate] of orderedViewers(room)) {
+ if (candidate.parentPeerId === null) {
+ this.assignViewer(room, candidatePeerId, connectedPeerIds);
+ }
+ }
return changedAssignments(before, snapshot(room));
}
@@ -130,8 +135,8 @@ export class PeerRelayTopology {
const before = snapshot(room);
this.detach(room, peerId, removed.parentPeerId);
- const subtreeRootPeerId = removed.childPeerIds[0];
- if (subtreeRootPeerId) {
+ const subtreeRootPeerIds = [...removed.childPeerIds];
+ for (const subtreeRootPeerId of subtreeRootPeerIds) {
const subtreeRoot = room.viewers.get(subtreeRootPeerId);
if (subtreeRoot) {
subtreeRoot.parentPeerId = null;
@@ -139,7 +144,7 @@ export class PeerRelayTopology {
}
room.viewers.delete(peerId);
- if (subtreeRootPeerId) {
+ for (const subtreeRootPeerId of subtreeRootPeerIds) {
this.assignViewer(room, subtreeRootPeerId, connectedPeerIds);
}
for (const [candidatePeerId, viewer] of orderedViewers(room)) {
@@ -178,6 +183,14 @@ export class PeerRelayTopology {
return room ? snapshot(room) : new Map();
}
+ getDownstreamCapacity(
+ roomId: string,
+ peerId: string,
+ ): RelayDownstreamEdges {
+ const room = this.rooms.get(roomId);
+ return room ? downstreamCapacity(room, peerId) : 0;
+ }
+
getHostPeerId(roomId: string): string | undefined {
return this.rooms.get(roomId)?.hostPeerId;
}
@@ -312,7 +325,7 @@ export class PeerRelayTopology {
!connectedPeerIds.has(peerId) ||
candidate.parentPeerId !== null ||
candidate.childPeerIds.length !== 0 ||
- candidate.downstreamEdges !== 1 ||
+ candidate.downstreamEdges === 0 ||
room.hostChildPeerIds.length !== downstreamCapacity(room, hostPeerId)
) {
return;
@@ -410,7 +423,10 @@ function findReassignmentParent(
return undefined;
}
-function downstreamCapacity(room: RelayRoom, peerId: string): number {
+function downstreamCapacity(
+ room: RelayRoom,
+ peerId: string,
+): RelayDownstreamEdges {
return room.hostPeerId === peerId
? 2
: (room.viewers.get(peerId)?.downstreamEdges ?? 0);
diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts
index 6eaf0dd1..0ee0afbd 100644
--- a/src/shared/protocol.ts
+++ b/src/shared/protocol.ts
@@ -185,6 +185,7 @@ export const DEFAULT_QUALITY_SETTINGS = {
export const relayDownstreamEdgesSchema = z.union([
z.literal(0),
z.literal(1),
+ z.literal(2),
]);
export type RelayDownstreamEdges = z.infer<typeof relayDownstreamEdgesSchema>;
diff --git a/tests/host-peer-tracks.test.ts b/tests/host-peer-tracks.test.ts
index 9ae7d71c..6ec90fd2 100644
--- a/tests/host-peer-tracks.test.ts
+++ b/tests/host-peer-tracks.test.ts
@@ -68,6 +68,9 @@ class FakeSender {
class FakePeerConnection {
static latest: FakePeerConnection | null = null;
+ static instances: FakePeerConnection[] = [];
+ static activeCount = 0;
+ static peakActiveCount = 0;
static offersFailing = 0;
readonly configurations: RTCConfiguration[] = [];
@@ -81,10 +84,17 @@ class FakePeerConnection {
signalingState: RTCSignalingState = "stable";
localDescription: RTCSessionDescription | null = null;
remoteDescription: RTCSessionDescription | null = null;
+ readonly addedIceCandidates: Array<RTCIceCandidateInit | null> = [];
readonly statsReports: Array<RTCStatsReport | Promise<RTCStatsReport>> = [];
constructor(configuration?: RTCConfiguration) {
FakePeerConnection.latest = this;
+ FakePeerConnection.instances.push(this);
+ FakePeerConnection.activeCount += 1;
+ FakePeerConnection.peakActiveCount = Math.max(
+ FakePeerConnection.peakActiveCount,
+ FakePeerConnection.activeCount,
+ );
if (configuration) {
this.configurations.push(configuration);
}
@@ -122,11 +132,24 @@ class FakePeerConnection {
this.localDescription = description as RTCSessionDescription;
}
+ async setRemoteDescription(
+ description: RTCSessionDescriptionInit,
+ ): Promise<void> {
+ this.remoteDescription = description as RTCSessionDescription;
+ }
+
+ async addIceCandidate(candidate: RTCIceCandidateInit | null): Promise<void> {
+ this.addedIceCandidates.push(candidate);
+ }
+
readonly getStats = vi.fn(async (): Promise<RTCStatsReport> =>
await (this.statsReports.shift() ?? emptyStatsReport())
);
close(): void {
+ if (this.connectionState !== "closed") {
+ FakePeerConnection.activeCount -= 1;
+ }
this.connectionState = "closed";
}
}
@@ -267,6 +290,30 @@ function createStream(
} as unknown as MediaStream;
}
+const selectedTurnIceServer = {
+ urls: ["turn:turn.example.test:3478?transport=udp"],
+ username: "1787230000:opaque_identity_12345678",
+ credential: "short-lived-credential",
+};
+
+function selectedEdgeTurn(
+ viewerPeerId: string,
+ oldConnectionId: string,
+ newConnectionId: string,
+) {
+ return {
+ type: "selected-edge-turn" as const,
+ edgeKind: "peer-selected" as const,
+ revision: 7,
+ parentPeerId: "selected-parent",
+ viewerPeerId,
+ oldConnectionId,
+ newConnectionId,
+ expiresAt: "2099-08-20T12:00:00.000Z",
+ iceServer: selectedTurnIceServer,
+ };
+}
+
function createPeer(
stream: MediaStream,
onUpdate: (snapshot: PeerSnapshot) => void = () => undefined,
@@ -286,6 +333,9 @@ function createPeer(
beforeEach(() => {
FakePeerConnection.latest = null;
+ FakePeerConnection.instances = [];
+ FakePeerConnection.activeCount = 0;
+ FakePeerConnection.peakActiveCount = 0;
FakePeerConnection.offersFailing = 0;
statsCallbacks.length = 0;
vi.stubGlobal("RTCPeerConnection", FakePeerConnection);
@@ -826,6 +876,86 @@ describe("HostPeer source replacement", () => {
});
describe("ViewerRelay downstream ownership", () => {
+ it("reconciles two children without ever opening a third edge", async () => {
+ const targets: string[] = [];
+ const relay = new ViewerRelay(
+ { iceServers: [] },
+ QUALITY_PROFILES["1080p60"],
+ {
+ sendSignal: (peerId) => {
+ targets.push(peerId);
+ return true;
+ },
+ },
+ );
+ const firstVideo = createTrack("video", "first-video");
+ const firstAudio = createTrack("audio", "first-audio");
+ relay.setChildren(["child-a", "child-b", "ignored-third"]);
+ relay.setStream(createStream(firstVideo, firstAudio));
+
+ await vi.waitFor(() =>
+ expect(new Set(targets)).toEqual(new Set(["child-a", "child-b"])),
+ );
+ const [childAConnection, childBConnection] =
+ FakePeerConnection.instances;
+ expect(childAConnection).toBeDefined();
+ expect(childBConnection).toBeDefined();
+ childAConnection!.connectionState = "connected";
+ childBConnection!.connectionState = "connected";
+ const retiredConnectionId = relay.getSnapshot("child-a")!.connectionId;
+
+ const nextVideo = createTrack("video", "next-video");
+ const nextAudio = createTrack("audio", "next-audio");
+ relay.setStream(createStream(nextVideo, nextAudio));
+ await vi.waitFor(() => {
+ expect(childAConnection!.senders[0]?.track).toBe(nextVideo);
+ expect(childBConnection!.senders[0]?.track).toBe(nextVideo);
+ expect(childAConnection!.senders[1]?.track).toBe(nextAudio);
+ expect(childBConnection!.senders[1]?.track).toBe(nextAudio);
+ });
+
+ relay.setChildren(["child-b", "child-c"]);
+ await vi.waitFor(() => expect(targets).toContain("child-c"));
+ expect(childAConnection!.connectionState).toBe("closed");
+ expect(childBConnection!.connectionState).toBe("connected");
+ expect(FakePeerConnection.activeCount).toBe(2);
+ expect(FakePeerConnection.peakActiveCount).toBe(2);
+ expect(targets).not.toContain("ignored-third");
+
+ await relay.acceptSignal("stale-child", {
+ kind: "description",
+ connectionId: "stale-connection",
+ description: { type: "answer", sdp: "stale-answer" },
+ }, 7);
+ await relay.recover("stale-child", "stale-connection", true);
+ await relay.recover("child-c", "wrong-connection", true);
+ expect(FakePeerConnection.activeCount).toBe(2);
+ const childCConnection = FakePeerConnection.latest!;
+ const childCConnectionId = relay.getSnapshot("child-c")!.connectionId;
+ await relay.recover("child-c", childCConnectionId, true);
+ await vi.waitFor(() =>
+ expect(FakePeerConnection.latest).not.toBe(childCConnection),
+ );
+ expect(childBConnection!.connectionState).toBe("connected");
+ expect(FakePeerConnection.activeCount).toBe(2);
+ expect(FakePeerConnection.peakActiveCount).toBe(2);
+
+ expect(
+ relay.startSelectedEdgeTurn(
+ selectedEdgeTurn(
+ "child-a",
+ retiredConnectionId,
+ "selected-connection-overflow",
+ ),
+ "selected-parent",
+ 7,
+ ),
+ ).toBe(false);
+ expect(FakePeerConnection.activeCount).toBe(2);
+ expect(FakePeerConnection.peakActiveCount).toBe(2);
+ relay.dispose();
+ });
+
it("rebuilds a retired child as one relay-only selected edge", async () => {
const sendSignal = vi.fn(() => true);
const relay = new ViewerRelay(
@@ -833,29 +963,43 @@ describe("ViewerRelay downstream ownership", () => {
QUALITY_PROFILES["720p30"],
{ sendSignal },
);
- relay.setChild("selected-child");
+ relay.setChildren(["selected-child"]);
relay.setStream(createStream(createTrack("video", "selected-video"), null));
await vi.waitFor(() => expect(sendSignal).toHaveBeenCalledOnce());
const oldConnectionId = relay.getSnapshot()!.connectionId;
- relay.setChild(null);
+ FakePeerConnection.latest!.connectionState = "connected";
+ relay.setChildren(["selected-child", "sibling-child"]);
+ await vi.waitFor(() => expect(sendSignal).toHaveBeenCalledTimes(2));
+ const siblingConnection = FakePeerConnection.latest!;
+ siblingConnection.connectionState = "connected";
+ relay.setChildren(["sibling-child"]);
sendSignal.mockClear();
- const iceServer = {
- urls: ["turn:turn.example.test:3478?transport=udp"],
- username: "1787230000:opaque_identity_12345678",
- credential: "short-lived-credential",
- };
-
- expect(relay.startSelectedEdgeTurn({
- type: "selected-edge-turn",
- edgeKind: "peer-selected",
- revision: 7,
- parentPeerId: "selected-parent",
- viewerPeerId: "selected-child",
+ const selectedGrant = selectedEdgeTurn(
+ "selected-child",
oldConnectionId,
- newConnectionId: "selected-connection-new",
- expiresAt: "2026-08-20T12:00:00.000Z",
- iceServer,
- })).toBe(true);
+ "selected-connection-new",
+ );
+ expect(
+ relay.startSelectedEdgeTurn(selectedGrant, "wrong-parent", 7),
+ ).toBe(false);
+ expect(
+ relay.startSelectedEdgeTurn(selectedGrant, "selected-parent", 6),
+ ).toBe(false);
+ expect(
+ relay.startSelectedEdgeTurn(
+ selectedGrant,
+ "selected-parent",
+ 7,
+ Date.parse(selectedGrant.expiresAt),
+ ),
+ ).toBe(false);
+ expect(
+ relay.startSelectedEdgeTurn(
+ selectedGrant,
+ "selected-parent",
+ 7,
+ ),
+ ).toBe(true);
await vi.waitFor(() => expect(sendSignal).toHaveBeenCalledOnce());
expect(sendSignal).toHaveBeenCalledWith(
"selected-child",
@@ -866,9 +1010,90 @@ describe("ViewerRelay downstream ownership", () => {
}),
);
expect(FakePeerConnection.latest?.configurations).toEqual([{
- iceServers: [iceServer],
+ iceServers: [selectedTurnIceServer],
iceTransportPolicy: "relay",
}]);
+ const selectedConnection = FakePeerConnection.latest!;
+ relay.setChildren(["sibling-child"]);
+ expect(selectedConnection.connectionState).not.toBe("closed");
+ expect(siblingConnection.connectionState).toBe("connected");
+ expect(relay.getSnapshot("selected-child")?.connectionId).toBe(
+ "selected-connection-new",
+ );
+ expect(FakePeerConnection.activeCount).toBe(2);
+ expect(FakePeerConnection.peakActiveCount).toBe(2);
+ const pendingCandidate = { candidate: "candidate-before-answer" };
+ await expect(
+ relay.acceptSignal("selected-child", {
+ kind: "candidate",
+ connectionId: "selected-connection-new",
+ candidate: pendingCandidate,
+ }, 7),
+ ).resolves.toBe(true);
+ expect(selectedConnection.addedIceCandidates).toEqual([]);
+ await expect(
+ relay.acceptSignal("selected-child", {
+ kind: "description",
+ connectionId: "selected-connection-new",
+ description: { type: "answer", sdp: "selected-answer" },
+ }, 7),
+ ).resolves.toBe(true);
+ expect(selectedConnection.remoteDescription?.type).toBe("answer");
+ expect(selectedConnection.addedIceCandidates).toEqual([pendingCandidate]);
+ await expect(
+ relay.acceptSignal("selected-child", {
+ kind: "candidate",
+ connectionId: "selected-connection-new",
+ candidate: null,
+ }, 7),
+ ).resolves.toBe(true);
+ expect(selectedConnection.addedIceCandidates).toEqual([
+ pendingCandidate,
+ null,
+ ]);
+ await expect(
+ relay.acceptSignal("selected-child", {
+ kind: "candidate",
+ connectionId: "selected-connection-new",
+ candidate: null,
+ }, 6),
+ ).resolves.toBe(false);
+ await expect(
+ relay.acceptSignal("selected-child", {
+ kind: "candidate",
+ connectionId: oldConnectionId,
+ candidate: null,
+ }, 7),
+ ).resolves.toBe(false);
+ expect(
+ relay.startSelectedEdgeTurn(
+ selectedEdgeTurn(
+ "selected-child",
+ "selected-connection-new",
+ "selected-connection-replacement",
+ ),
+ "selected-parent",
+ 7,
+ ),
+ ).toBe(true);
+ await vi.waitFor(() => expect(sendSignal).toHaveBeenCalledTimes(2));
+ expect(selectedConnection.connectionState).toBe("closed");
+ const replacementConnection = FakePeerConnection.latest!;
+ expect(replacementConnection.connectionState).not.toBe("closed");
+ expect(FakePeerConnection.activeCount).toBe(2);
+ expect(FakePeerConnection.peakActiveCount).toBe(2);
+ relay.clearSelectedEdgeTurn();
+ expect(replacementConnection.connectionState).toBe("closed");
+ await expect(
+ relay.acceptSignal("selected-child", {
+ kind: "candidate",
+ connectionId: "selected-connection-replacement",
+ candidate: null,
+ }, 7),
+ ).resolves.toBe(false);
+ expect(FakePeerConnection.activeCount).toBe(1);
+ expect(FakePeerConnection.peakActiveCount).toBe(2);
+ relay.dispose();
});
it("exposes a defensive snapshot of current downstream send metrics", async () => {
@@ -877,7 +1102,7 @@ describe("ViewerRelay downstream ownership", () => {
QUALITY_PROFILES["720p30"],
{ sendSignal: () => true },
);
- relay.setChild("metrics-child");
+ relay.setChildren(["metrics-child"]);
relay.setStream(
createStream(createTrack("video", "metrics-video"), null),
);
@@ -935,13 +1160,13 @@ describe("ViewerRelay downstream ownership", () => {
{ sendSignal: () => true },
);
const stream = createStream(createTrack("video", "relay-video"), null);
- relay.setChild("first-child");
+ relay.setChildren(["first-child"]);
relay.setStream(stream);
await vi.waitFor(() =>
expect(relay.getSnapshot()?.peerId).toBe("first-child"),
);
- relay.setChild("second-child");
+ relay.setChildren(["second-child"]);
expect(relay.getSnapshot()).toBeNull();
await vi.waitFor(() =>
expect(relay.getSnapshot()?.peerId).toBe("second-child"),
@@ -970,7 +1195,7 @@ describe("ViewerRelay downstream ownership", () => {
QUALITY_PROFILES["720p30"],
{ sendSignal: () => true },
);
- relay.setChild("old-child");
+ relay.setChildren(["old-child"]);
relay.setStream(
createStream(createTrack("video", "relay-video"), null),
);
@@ -980,7 +1205,7 @@ describe("ViewerRelay downstream ownership", () => {
FakePeerConnection.latest!.statsReports.push(pendingOldStats);
statsCallbacks[0]!();
- relay.setChild("current-child");
+ relay.setChildren(["current-child"]);
await vi.waitFor(() =>
expect(relay.getSnapshot()?.peerId).toBe("current-child"),
);
@@ -1020,7 +1245,7 @@ describe("ViewerRelay downstream ownership", () => {
},
);
- relay.setChild("lan-child-peer");
+ relay.setChildren(["lan-child-peer"]);
relay.setStream(
createStream(createTrack("video", "lan-video"), null),
);
@@ -1045,14 +1270,14 @@ describe("ViewerRelay downstream ownership", () => {
},
);
const stream = createStream(createTrack("video", "relay-video"), null);
- relay.setChild("same-child-peer");
+ relay.setChildren(["same-child-peer"]);
relay.setStream(stream);
await vi.runAllTimersAsync();
const failedPeer = FakePeerConnection.latest;
expect(targets).toEqual([]);
- relay.setChild("same-child-peer");
+ relay.setChildren(["same-child-peer"]);
await vi.runAllTimersAsync();
expect(FakePeerConnection.latest).not.toBe(failedPeer);
@@ -1074,14 +1299,14 @@ describe("ViewerRelay downstream ownership", () => {
},
},
);
- relay.setChild("reconciled-child");
+ relay.setChildren(["reconciled-child"]);
relay.setStream(
createStream(createTrack("video", "reconciled-video"), null),
);
await vi.waitFor(() => expect(targets).toEqual(["reconciled-child"]));
const stalledConnection = FakePeerConnection.latest!;
- relay.setChild("reconciled-child");
+ relay.setChildren(["reconciled-child"]);
await vi.waitFor(() =>
expect(FakePeerConnection.latest).not.toBe(stalledConnection),
);
@@ -1089,7 +1314,7 @@ describe("ViewerRelay downstream ownership", () => {
await vi.waitFor(() => expect(targets).toHaveLength(2));
connectedConnection.connectionState = "connected";
- relay.setChild("reconciled-child");
+ relay.setChildren(["reconciled-child"]);
expect(FakePeerConnection.latest).toBe(connectedConnection);
expect(targets).toHaveLength(2);
});
@@ -1111,7 +1336,7 @@ describe("ViewerRelay downstream ownership", () => {
createTrack("audio", "first-audio"),
);
- relay.setChild("child-peer-one");
+ relay.setChildren(["child-peer-one"]);
relay.setStream(firstStream);
await vi.waitFor(() => expect(FakePeerConnection.latest).not.toBeNull());
const connection = FakePeerConnection.latest!;
@@ -1126,7 +1351,7 @@ describe("ViewerRelay downstream ownership", () => {
expect(connection.senders[1]?.track).toBe(nextAudio);
expect(connection.transceiverInputs).toHaveLength(2);
- relay.setChild("child-peer-two");
+ relay.setChildren(["child-peer-two"]);
await vi.waitFor(() => expect(FakePeerConnection.latest).not.toBe(connection));
expect(connection.connectionState).toBe("closed");
await vi.waitFor(() => expect(targets.at(-1)).toBe("child-peer-two"));
@@ -1144,7 +1369,7 @@ describe("ViewerRelay downstream ownership", () => {
QUALITY_PROFILES["1080p60"],
{ sendSignal: () => true },
);
- relay.setChild("first-profile-child");
+ relay.setChildren(["first-profile-child"]);
relay.setStream(createStream(createTrack("video", "profile-video"), null));
await vi.waitFor(() =>
expect(
@@ -1163,7 +1388,7 @@ describe("ViewerRelay downstream ownership", () => {
encodings: [{ maxBitrate: 10_500_000, maxFramerate: 45 }],
});
- relay.setChild("second-profile-child");
+ relay.setChildren(["second-profile-child"]);
await vi.waitFor(() =>
expect(FakePeerConnection.latest).not.toBe(firstConnection),
);
diff --git a/tests/media-assignment.test.ts b/tests/media-assignment.test.ts
index ea2df928..3da2a0fe 100644
--- a/tests/media-assignment.test.ts
+++ b/tests/media-assignment.test.ts
@@ -37,7 +37,7 @@ describe("peer-assisted client assignment", () => {
limitMediaAssignment(assignment, MAX_VIEWER_MEDIA_CHILDREN),
).toEqual({
parentPeerId: "parent_12345678",
- childPeerIds: ["child_12345678"],
+ childPeerIds: ["child_12345678", "child_abcdefgh"],
});
});
diff --git a/tests/peer-relay-topology.test.ts b/tests/peer-relay-topology.test.ts
index e69c8af9..f51b9f94 100644
--- a/tests/peer-relay-topology.test.ts
+++ b/tests/peer-relay-topology.test.ts
@@ -11,6 +11,7 @@ function addRelayViewer(
roomId: string,
peerId: string,
connectedPeerIds: ReadonlySet<string>,
+ downstreamEdges: 1 | 2 = 1,
) {
const changes = topology.addViewer(roomId, peerId, connectedPeerIds);
return [
@@ -18,7 +19,7 @@ function addRelayViewer(
...topology.setViewerRelayCapacity(
roomId,
peerId,
- 1,
+ downstreamEdges,
connectedPeerIds,
),
];
@@ -29,6 +30,7 @@ function expectValidTree(
roomId: string,
hostPeerId: string,
viewerPeerIds: readonly string[],
+ maxViewerChildren = 1,
): number {
const hostAssignment = topology.getAssignment(roomId, hostPeerId)!;
expect(hostAssignment.parentPeerId).toBeNull();
@@ -38,7 +40,9 @@ function expectValidTree(
let maximumDepth = 0;
for (const peerId of viewerPeerIds) {
const assignment = topology.getAssignment(roomId, peerId)!;
- expect(assignment.childPeerIds.length).toBeLessThanOrEqual(1);
+ expect(assignment.childPeerIds.length).toBeLessThanOrEqual(
+ maxViewerChildren,
+ );
for (const childPeerId of assignment.childPeerIds) {
expect(allChildren.has(childPeerId)).toBe(false);
allChildren.add(childPeerId);
@@ -283,6 +287,83 @@ describe("PeerRelayTopology", () => {
expect(expectValidTree(topology, roomId, hostPeerId, viewerPeerIds)).toBe(4);
});
+ it("forms a bounded depth-three DAG for eight capacity-two viewers", () => {
+ const topology = new PeerRelayTopology();
+ const roomId = "room";
+ const hostPeerId = "host";
+ const viewerPeerIds = Array.from(
+ { length: 8 },
+ (_, index) => `viewer-${index + 1}`,
+ );
+ const peers = connected(hostPeerId, ...viewerPeerIds);
+ topology.setHost(roomId, hostPeerId, peers);
+
+ for (let index = 0; index < viewerPeerIds.length; index += 1) {
+ addRelayViewer(
+ topology,
+ roomId,
+ viewerPeerIds[index]!,
+ peers,
+ 2,
+ );
+ expectValidTree(
+ topology,
+ roomId,
+ hostPeerId,
+ viewerPeerIds.slice(0, index + 1),
+ 2,
+ );
+ }
+
+ expect(topology.getAssignment(roomId, "viewer-1")?.childPeerIds).toEqual([
+ "viewer-3",
+ "viewer-4",
+ ]);
+ expect(topology.getDownstreamCapacity(roomId, "viewer-1")).toBe(2);
+ expect(topology.getAssignment(roomId, "viewer-5")?.parentPeerId).toBe(
+ "viewer-2",
+ );
+ expect(
+ expectValidTree(topology, roomId, hostPeerId, viewerPeerIds, 2),
+ ).toBe(3);
+ });
+
+ it("reattaches both child subtrees when a capacity-two relay leaves", () => {
+ const topology = new PeerRelayTopology();
+ const peers = connected("host", "relay", "sibling", "child-a", "child-b");
+ topology.setHost("room", "host", peers);
+ addRelayViewer(topology, "room", "relay", peers, 2);
+ addRelayViewer(topology, "room", "sibling", peers, 2);
+ addRelayViewer(topology, "room", "child-a", peers, 2);
+ addRelayViewer(topology, "room", "child-b", peers, 2);
+ expect(topology.getAssignment("room", "relay")?.childPeerIds).toEqual([
+ "child-a",
+ "child-b",
+ ]);
+
+ topology.removeViewer(
+ "room",
+ "relay",
+ connected("host", "sibling", "child-a", "child-b"),
+ );
+
+ expect(topology.getAssignment("room", "child-a")?.parentPeerId).toBe(
+ "host",
+ );
+ expect(topology.getAssignment("room", "child-b")?.parentPeerId).toBe(
+ "sibling",
+ );
+ expect(
+ expectValidTree(
+ topology,
+ "room",
+ "host",
+ ["sibling", "child-a", "child-b"],
+ 2,
+ ),
+ ).toBe(2);
+ });
+
it("uses the same depth-four bound for initial admission", () => {
const topology = new PeerRelayTopology();
const roomId = "room";
diff --git a/tests/protocol.test.ts b/tests/protocol.test.ts
index 42760ed0..7f20e44c 100644
--- a/tests/protocol.test.ts
+++ b/tests/protocol.test.ts
@@ -449,7 +449,7 @@ describe("client signaling protocol", () => {
).toBe(false);
});
- it("accepts only a binary browser relay capacity", () => {
+ it("accepts only a bounded browser relay capacity", () => {
expect(
clientMessageSchema.safeParse({
type: "relay-capacity",
@@ -467,6 +467,12 @@ describe("client signaling protocol", () => {
type: "relay-capacity",
downstreamEdges: 2,
}).success,
+ ).toBe(true);
+ expect(
+ clientMessageSchema.safeParse({
+ type: "relay-capacity",
+ downstreamEdges: 3,
+ }).success,
).toBe(false);
expect(
clientMessageSchema.safeParse({
diff --git a/tests/relay-capability.test.ts b/tests/relay-capability.test.ts
index 64cf4105..14ec2d53 100644
--- a/tests/relay-capability.test.ts
+++ b/tests/relay-capability.test.ts
@@ -1,50 +1,17 @@
import { describe, expect, it } from "vitest";
import {
- detectBrowserRelayCapacity,
relayCapacityMessageForBrowser,
} from "../src/client/media/relay-capability.ts";
-const desktop = {
- userAgent:
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/140 Safari/537.36",
- userAgentDataMobile: false,
- maxTouchPoints: 0,
-};
-
describe("browser relay capability", () => {
- it("allows one downstream edge on a desktop browser", () => {
- expect(detectBrowserRelayCapacity(desktop)).toBe(1);
- expect(relayCapacityMessageForBrowser(true, desktop)).toEqual({
+ it("allows two downstream edges on a peer-assisted Web viewer", () => {
+ expect(relayCapacityMessageForBrowser(true)).toEqual({
type: "relay-capacity",
- downstreamEdges: 1,
+ downstreamEdges: 2,
});
});
- it.each([
- {
- userAgent: desktop.userAgent,
- userAgentDataMobile: true,
- maxTouchPoints: 0,
- },
- {
- userAgent: "Mozilla/5.0 (Linux; Android 16; Mobile)",
- userAgentDataMobile: false,
- maxTouchPoints: 5,
- },
- {
- userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 19_0 like Mac OS X)",
- maxTouchPoints: 5,
- },
- {
- userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15)",
- userAgentDataMobile: false,
- maxTouchPoints: 5,
- },
- ])("keeps mobile and touch iPadOS browsers as leaves", (environment) => {
- expect(detectBrowserRelayCapacity(environment)).toBe(0);
- });
-
it("does not create a relay message for ordinary P2P", () => {
expect(relayCapacityMessageForBrowser(false)).toBeNull();
});
diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.ts
index 21cc5cc4..a6d978a5 100644
--- a/tests/server-signal.test.ts
+++ b/tests/server-signal.test.ts
@@ -437,7 +437,7 @@ async function authenticate(
room: CreatedRoom,
role: Role,
clientId: string,
- relayCapacity: 0 | 1 | null = 1,
+ relayCapacity: 0 | 1 | 2 | null = 1,
shareGeneration?: string,
presence: {
displayName?: string;
@@ -572,6 +572,7 @@ async function prepareFallbackForTwoViewers(
room: CreatedRoom,
prefix: string,
shareGeneration?: string,
+ options: { viewerParentSibling?: boolean } = {},
) {
const host = await openClient(webSocketUrl);
const hostAuth = peerAssisted(
@@ -591,6 +592,7 @@ async function prepareFallbackForTwoViewers(
room,
"viewer",
`${prefix}-failed-client`,
+ options.viewerParentSibling ? 0 : 1,
),
);
const rootViewer = await openClient(webSocketUrl);
@@ -600,12 +602,35 @@ async function prepareFallbackForTwoViewers(
room,
"viewer",
`${prefix}-root-client`,
+ options.viewerParentSibling ? 2 : 1,
),
);
- const directRoute = await nextActiveRouteAfter(
- failedViewer,
- failedAuth.routeRevision,
- );
+ let rootSibling: TestClient | undefined;
+ let rootSiblingAuth:
+ | ReturnType<typeof peerAssisted>
+ | undefined;
+ if (options.viewerParentSibling) {
+ rootSibling = await openClient(webSocketUrl);
+ rootSiblingAuth = peerAssisted(
+ await authenticate(
+ rootSibling,
+ room,
+ "viewer",
+ `${prefix}-root-sibling-client`,
+ 0,
+ ),
+ );
+ expect(rootSiblingAuth.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: rootAuth.peerId,
+ });
+ }
+ const directRoute = rootSiblingAuth
+ ? await nextActiveRouteRevision(
+ failedViewer,
+ rootSiblingAuth.routeRevision,
+ )
+ : await nextActiveRouteAfter(failedViewer, failedAuth.routeRevision);
host.socket.send(
JSON.stringify({
type: "signal",
@@ -661,6 +686,8 @@ async function prepareFallbackForTwoViewers(
failedAuth,
rootViewer,
rootAuth,
+ rootSibling,
+ rootSiblingAuth,
hostPrepare,
rootPrepare,
};
@@ -4690,6 +4717,7 @@ describe("WebSocket signaling", () => {
harness.room,
"selected-viewer-parent",
"selected-viewer-parent-share",
+ { viewerParentSibling: true },
);
for (const client of [prepared.host, prepared.failedViewer]) {
client.socket.send(JSON.stringify({
@@ -4698,9 +4726,13 @@ describe("WebSocket signaling", () => {
phase: "prepare",
}));
}
- await Promise.all([
+ const [, , parentActive] = await Promise.all([
nextActiveRouteRevision(prepared.host, prepared.hostPrepare.revision),
nextActiveRouteRevision(prepared.failedViewer, prepared.rootPrepare.revision),
+ nextActiveRouteRevision(prepared.rootViewer, prepared.rootPrepare.revision),
+ ]);
+ expect(parentActive.assignment.childPeerIds).toEqual([
+ prepared.rootSiblingAuth!.peerId,
]);
prepared.failedViewer.socket.send(JSON.stringify({
type: "refresh-sfu",
@@ -4732,6 +4764,16 @@ describe("WebSocket signaling", () => {
},
}));
await prepared.failedViewer.inbox.next("signal");
+ prepared.rootViewer.socket.send(JSON.stringify({
+ type: "signal",
+ targetPeerId: prepared.failedAuth.peerId,
+ payload: {
+ kind: "candidate",
+ connectionId: childGrant.newConnectionId,
+ candidate: { candidate: "parent-candidate" },
+ },
+ }));
+ await prepared.failedViewer.inbox.next("signal");
prepared.failedViewer.socket.send(JSON.stringify({
type: "signal",
targetPeerId: prepared.rootAuth.peerId,
@@ -4742,6 +4784,52 @@ describe("WebSocket signaling", () => {
},
}));
await prepared.rootViewer.inbox.next("signal");
+ prepared.failedViewer.socket.send(JSON.stringify({
+ type: "signal",
+ targetPeerId: prepared.rootAuth.peerId,
+ payload: {
+ kind: "candidate",
+ connectionId: childGrant.newConnectionId,
+ candidate: null,
+ },
+ }));
+ await prepared.rootViewer.inbox.next("signal");
+ const reconnectedSibling = await openClient(harness.webSocketUrl);
+ const reconnectedSiblingAuth = peerAssisted(
+ await authenticate(
+ reconnectedSibling,
+ harness.room,
+ "viewer",
+ "selected-viewer-parent-root-sibling-client",
+ 0,
+ ),
+ );
+ expect(reconnectedSiblingAuth.routeRevision).toBe(childGrant.revision);
+ expect(
+ await nextActiveRouteRevision(
+ prepared.rootViewer,
+ childGrant.revision,
+ ),
+ ).toMatchObject({
+ assignment: { childPeerIds: [reconnectedSiblingAuth.peerId] },
+ });
+ prepared.rootViewer.socket.send(JSON.stringify({
+ type: "signal",
+ targetPeerId: prepared.failedAuth.peerId,
+ payload: {
+ kind: "candidate",
+ connectionId: childGrant.newConnectionId,
+ candidate: { candidate: "candidate-after-sibling-reconnect" },
+ },
+ }));
+ expect(await prepared.failedViewer.inbox.next("signal")).toMatchObject({
+ fromPeerId: prepared.rootAuth.peerId,
+ payload: {
+ kind: "candidate",
+ connectionId: childGrant.newConnectionId,
+ candidate: { candidate: "candidate-after-sibling-reconnect" },
+ },
+ });
prepared.host.socket.send(JSON.stringify({
type: "stop-sharing",
shareGeneration: "selected-viewer-parent-share",