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

docs: define peer-assisted media experiment

AAA92078c129807
diff --git a/docs/README.md b/docs/README.md
index de3c431b..91932e23 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -7,8 +7,11 @@
- [Deployment](./deployment.md): minimal Node, HTTPS/WSS, coturn, firewall, secret, optional TURN/TLS, and network-verification procedure.
- [Maintenance guide](./maintenance.md): Git workflow, context hygiene, document lifecycle, research policy, and automation.
- [P2P WebRTC research](./research/webrtc-p2p-screen-sharing.md): evidence, bandwidth model, browser constraints, reference implementations, and feasibility assessment.
+- [Peer-assisted media research](./research/peer-assisted-media.md): browser shared-encode limits, standard relay re-encoding, rejected custom encoded transport, deterministic sticky topology, and abandon gates.
+- [Low-server-cost media routes](./research/low-server-media-routes.md): traffic accounting, route screening, conditional native encoded-RTP relay, and explicit SFU fallbacks.
- [Agent context governance research](./research/agent-context-governance.md): official Codex, Claude Code, Hermes Agent, and GitHub practices adopted by this repository.
- [ADR-0001](./adr/0001-p2p-first-media-topology.md): accepted P2P-first media topology and its consequences.
- [ADR-0002](./adr/0002-persistent-protected-rooms.md): optional SQLite persistence, protected sequential room IDs, and room lifecycle.
+- [ADR-0004](./adr/0004-peer-assisted-media-experiment.md): proposed, experiment-only standard-WebRTC peer-assisted spike with hard fanout and failure gates.
Documentation and project memory are part of the product source of truth. Update them in the same change that alters the corresponding requirement or architecture.
diff --git a/docs/adr/0001-p2p-first-media-topology.md b/docs/adr/0001-p2p-first-media-topology.md
index d2102575..23bd0b0d 100644
--- a/docs/adr/0001-p2p-first-media-topology.md
+++ b/docs/adr/0001-p2p-first-media-topology.md
@@ -3,6 +3,11 @@
- Status: Accepted for the MVP
- Date: 2026-08-18
+Draft ADR-0003 and Proposed ADR-0004 do not supersede this production baseline.
+They isolate an optional SFU implementation and a bounded peer-assisted
+experiment respectively. A later Accepted ADR is required before either changes
+the default topology.
+
## Context
The product targets one game broadcaster and a small group of trusted friends. Low glass-to-glass latency, private access, no-install browser viewing, and low server bandwidth cost matter more than large-room scalability. Public broadcasting is deliberately delegated to existing OBS/Twitch-class services. NATs, CGNAT, restrictive firewalls, variable publisher upload, and browser capture limitations prevent a direct-only design from being reliable for every user; partial room reachability is not acceptable behavior.
@@ -13,11 +18,11 @@ Use separate control and media planes:
- A small HTTPS/WSS service owns identity, rooms, invitations, presence, and WebRTC signaling.
- A viewer can join through a numeric room code on desktop or mobile without installing the sharing client. The viewer link has no separate token or fragment; the host publication token remains internal. A deployment may place one site-wide password gate in front of both hosting and viewing; access policy remains control-plane state and does not change the media topology. ADR-0002 owns the current room-ID and lifetime policy.
-- ICE attempts a direct UDP path for every broadcaster-viewer pair, using STUN to discover candidates.
+- ICE attempts a direct UDP path for every current broadcaster-viewer edge, using STUN to discover candidates. A later accepted peer-assisted topology must apply the same rule independently to each assigned parent-child edge.
- Only pairs that cannot connect directly use authenticated TURN. Production requires STUN plus TURN over UDP and TCP; TURN/TLS is an optional restrictive-network enhancement, using its standard TCP port 5349 by default. Port 443 is optional and requires a dedicated public IP or a validated layer-4/SNI route when HTTPS already owns that address and port.
- Candidate selection is independent per pair. A room may simultaneously contain direct and relayed viewers without moving working peers onto the server.
-- The broadcaster creates one peer connection per viewer. Rooms default to eight viewers and deployments may configure a limit from 1 through 16. Eight is an admission default, not a validated media-performance promise; the sustainable envelope is decided from publisher upload, encoder, latency, and stability measurements.
-- No SFU is planned for the normal product envelope. It is only a future reconsideration point if the small-room scope changes or measured relay/upload/encoder pressure makes the chosen envelope unworkable.
+- The deployed MVP broadcaster creates one peer connection per viewer. Rooms default to eight viewers and deployments may configure a limit from 1 through 16. Eight is an admission default, not a validated media-performance promise. A newer product target caps host media fanout at two; the current implementation does not satisfy that target above two viewers, and Proposed ADR-0004 owns the isolated experiment rather than silently changing this accepted baseline.
+- No SFU is the automatic or default path for the normal product envelope. Severe user-observed multi-viewer degradation triggered Draft ADR-0003/PR #12 as an explicit optional experiment, but it is not merged, deployed, or accepted while that PR remains Draft.
## Consequences
@@ -43,7 +48,7 @@ Negative:
- Always-SFU: operationally stable but makes the server carry all viewer egress, contrary to the main cost constraint.
- Public-broadcast scaling: Twitch/OBS-class services already solve this separate workload and it would distort the private-room design.
- MCU/transcoding: unnecessary CPU/GPU work and added latency for a single screen stream.
-- Peer-assisted relay tree: adds churn handling, extra latency, trust problems, and browser re-encoding or a custom packet-forwarding protocol.
+- Peer-assisted relay tree for the MVP: adds churn handling, extra latency, trust problems, and browser re-encoding or a custom packet-forwarding protocol. Proposed ADR-0004 permits only a bounded, removable experiment; production use remains rejected until a later ADR passes measured gates.
- Custom Parsec-like transport: duplicates capture, codec, congestion-control, NAT, and security work already provided by WebRTC.
## Revisit Triggers
diff --git a/docs/adr/0004-peer-assisted-media-experiment.md b/docs/adr/0004-peer-assisted-media-experiment.md
new file mode 100644
index 00000000..39c5d62f
--- /dev/null
+++ b/docs/adr/0004-peer-assisted-media-experiment.md
@@ -0,0 +1,175 @@
+# ADR-0004: Peer-Assisted Media Experiment
+
+- Status: Proposed - Experiment Only
+- Date: 2026-08-19
+
+## Context
+
+ADR-0001 accepted standard browser WebRTC P2P for the MVP and rejected a viewer
+relay tree because it adds churn, latency, and either browser re-encoding or a
+custom packet-forwarding protocol. Real multi-viewer use later degraded severely.
+The product now also has a hard target that a broadcaster must never carry more
+than two outgoing media edges.
+
+Draft PR #12 proposes an independently reversible deployment-level SFU under
+ADR-0003, but it is not merged or accepted. Making an SFU the normal path would
+move every viewer's egress cost to the server. TeamSpeak-style shared encoding
+reduces host encode work but still sends one network copy to every viewer, so it
+cannot meet the new fanout target alone.
+
+The research in `docs/research/peer-assisted-media.md` finds no browser API that
+can move one encoded frame between `RTCRtpSender` pipelines. Standard browser
+track relay decodes and re-encodes at each hop. The first experiment accepts
+that measurable cost because avoiding it requires a custom encoded-frame media
+plane.
+
+This ADR does not accept peer-assisted media for production. It proposes one
+bounded experiment that must either meet explicit gates or be removed.
+
+## Proposed Experiment
+
+Preserve the product priority in this order:
+
+1. direct P2P for one or two viewers;
+2. peer-assisted forwarding for later viewers when this experiment is active
+ and every required capability is present; and
+3. the optional SFU as an explicit deployment alternative, not a silent
+ in-room migration.
+
+The experiment is gated by `PEER_ASSISTED_MEDIA`, which defaults to `false`.
+Enabling it requires `MAX_VIEWERS_PER_ROOM` at or below eight; larger configured
+rooms fail configuration rather than silently running a different topology.
+
+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. 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,
+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,
+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.
+Each logical edge still uses its own ICE process and authenticated TURN fallback
+when direct connectivity is unavailable.
+
+Every edge uses the existing standard WebRTC media path. A viewer receives the
+remote `MediaStream`, renders it, and sends those remote tracks through one new
+downstream `RTCPeerConnection`. The browser therefore decodes and re-encodes at
+every relay hop. Existing audio follows the same stream when capture provides
+it; the experiment does not invent a separate audio protocol.
+
+Encoded Transform, DataChannel media, WebCodecs rendering, dummy-sender byte
+replacement, custom congestion control, codec ladders, multiple trees, mobile
+background relay, and automatic SFU migration are excluded. They are not rescue
+work if standard track relay fails.
+
+## Shared Encoding Boundary
+
+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.
+
+A production peer-assisted design must eventually use a packaged/native sender
+whose custom libwebrtc encoder proxies share one encoded output while retaining
+independent standard WebRTC packetizers for the host's edges. That native work
+requires a separate ADR and measurements. It is not implemented or abstracted
+in advance by this spike. Standard browser viewing remains required.
+
+## Acceptance Gate
+
+Test 1, 3, 5, and 8 viewers for 30 minutes at 720p60 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. The protocol has no relay-capability bit, so controlled join order is
+the only enforcement and this spike is not safe for arbitrary-user deployment.
+
+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;
+- 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,
+ CPU/GPU load, and `qualityLimitationReason`; no result calls this shared or
+ zero-copy forwarding;
+- excluding explicit TURN paths, the application server carries no media;
+- host and relay upload remain within 20% of `childCount * observedBitrate`;
+- 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
+ 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;
+- loss of either first-level relay that the server observes immediately first
+ 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 about-8-second gate covers a controlled page close that the server observes
+immediately. A silent network partition depends on the default 30-second
+heartbeat and can take 30 to 60 seconds to detect before the same 5-second
+grace; that path is a separate, currently unverified measurement.
+
+Fixing an ordinary implementation bug inside the bounded spike is allowed. If
+meeting a gate requires Encoded Transform/DataChannel/WebCodecs media, custom
+congestion control, FEC/RTX changes, multiple trees, relay scoring, transcoding,
+a codec ladder, relaxed host fanout, or a browser-specific RTP injection hack,
+stop. Change this ADR to Rejected and delete the experimental runtime path and
+dependencies. Only when every non-encoding gate passes and relay re-encoding is
+the sole failure may a separate ADR propose a native shared-encode host with
+opt-in native volunteer encoded-RTP relays. Any other failure closes peer
+assistance and keeps standard P2P plus explicit user-operated or central SFU
+fallbacks.
+
+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, privacy disclosure, and the native shared-encode sender.
+
+## Consequences If The Spike Proceeds
+
+Positive:
+
+- The host upload and connection count become bounded without assigning normal
+ viewer egress to an SFU.
+- ICE, TURN, DTLS-SRTP, RTP recovery, congestion control, codec negotiation,
+ jitter buffering, and browser rendering remain provided by WebRTC.
+- Deterministic assignment is small enough to inspect and reproduce.
+
+Negative:
+
+- Every relay decodes and re-encodes, adding CPU/GPU load, latency, and
+ generational quality loss.
+- Every relay adds a network hop and becomes an availability dependency for its
+ 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.
+
+## Relationship To Existing ADRs
+
+- ADR-0001 remains the accepted production baseline. This proposal narrows its
+ peer-tree rejection only enough to run an isolated experiment.
+- Draft ADR-0003 in PR #12 remains the separate explicit optional-SFU proposal.
+ This proposal neither accepts/removes it nor adds automatic P2P/SFU switching.
+- If a later ADR accepts peer-assisted media, it must state exactly which parts
+ of ADR-0001 and ADR-0003 it supersedes.
+
+## References
+
+Sources were checked on 2026-08-19:
+
+- [WebRTC](https://w3c.github.io/webrtc-pc/)
+- [WebRTC Encoded Transform](https://w3c.github.io/webrtc-encoded-transform/)
+- [WebCodecs](https://www.w3.org/TR/webcodecs/)
+- [WebRTC Data Channels, RFC 8831](https://www.rfc-editor.org/rfc/rfc8831.html)
+- [libwebrtc video send stream](https://webrtc.googlesource.com/src/+/refs/heads/main/video/video_send_stream_impl.cc)
+- [libwebrtc video encoder factory](https://webrtc.googlesource.com/src/+/refs/heads/main/api/video_codecs/video_encoder_factory.h)
+- [TeamSpeak single-encoding explanation](https://community.teamspeak.com/t/ts6-beta-community-update-insights/58116/208)
+- [SplitStream, SOSP 2003](https://www.microsoft.com/en-us/research/publication/splitstream-high-bandwidth-multicast-in-a-cooperative-environment/)
diff --git a/docs/project-memory.md b/docs/project-memory.md
index bbaaf75c..d48f40be 100644
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@ -1,72 +1,68 @@
# Project Memory
-Last updated: 2026-08-18
+Last updated: 2026-08-19
## Confirmed Intent
-- The product is a Discord/KOOK/Oopz/TeamSpeak-like screen-sharing tool for gaming with friends.
-- One user broadcasts a game, application, or display; several friends watch with very low latency.
-- The normal use case is a small, trusted friend group. Public or large-scale streaming is explicitly out of scope and can be handled by OBS/Twitch-class services.
-- Viewers should be able to open an invite link in a desktop or mobile browser without installing a dedicated client.
-- The system should resemble a Photon-style developer experience: a central room/rendezvous service establishes sessions while realtime traffic is carried by clients whenever possible.
-- Server bandwidth cost is a primary constraint. The default media path remains P2P-first, with servers used for signaling, STUN, TURN fallback, and observability. A deployment-level SFU mode is acceptable when measured multi-viewer P2P behavior is unusable; it must remain explicit and independently reversible.
-- Avoiding TeamSpeak-like partial reachability is a primary requirement: every broadcaster-viewer pair must independently have TURN/UDP and TURN/TCP candidates available when direct ICE cannot connect. TURN/TLS is an optional compatibility enhancement, not a production prerequisite.
-- A web experience is preferred for convenience, but using a desktop sender is acceptable when it materially improves game capture, audio capture, or hardware encoding.
-- All project documentation, memory, code, `AGENTS.md`, and `.codex/` configuration must live in this Git repository and remain tracked for cross-device development.
-- Normal maintenance uses short-lived branches, focused commits, remote backup, pull requests, checks, merge, and branch deletion.
-- Long conversations require explicit repository checkpoints. Current memory is curated and rewritten when facts change; it must not grow as a transcript or duplicate Git history.
-- Material designs, fixes, and implementations begin with current online research of official docs and established projects, supplemented by community reports or papers where useful.
-- Engineering follows Occam's razor: use the simplest complete solution for verified needs and reject speculative scale, abstractions, services, and compatibility work until evidence justifies them.
+- Build Discord/KOOK/Oopz/TeamSpeak-like low-latency game screen sharing for one broadcaster and a small trusted friend group. Public or large broadcasts belong on OBS/Twitch-class services.
+- Viewers should join from a normal desktop or mobile browser. A packaged sender is acceptable later when measurements justify native capture, audio, or shared encoding.
+- Use a Photon-style central rendezvous service for access, rooms, signaling, deterministic topology, STUN, TURN fallback, and observability while clients carry media whenever practical.
+- Server bandwidth cost is a primary constraint. The media priority is direct P2P, then measured peer assistance, then an explicit user-operated or central SFU fallback. Never migrate topology silently.
+- The broadcaster has a hard target of at most two downstream media edges. Every assigned edge independently uses ICE and authenticated TURN/UDP or TURN/TCP when direct connectivity fails; P2P-first never means direct-only.
+- Browser-only convenience does not override reachability, measurable performance, or honest resource accounting. Shared encoding reduces compute, not the network copy required by each viewer.
+- Durable decisions, current snapshots, research, code, `AGENTS.md`, and `.codex/` belong in Git. Memory and status are rewritten in place rather than kept as transcripts.
+- Research current official sources and established implementations before material work. Apply Occam's razor and reject speculative protocols, services, scoring, and scale.
## Current Recommendation
-- Start with a Windows Chrome/Edge sharing MVP and a responsive Web viewer using one `RTCPeerConnection` per viewer. Validate current Android Chrome and iOS Safari as viewing endpoints.
-- Rooms default to one broadcaster and at most eight viewers, with a deployment range of 1 through 16. Treat eight as an admission default rather than a validated performance claim; measure publisher upload, encoder load, latency, and stability before describing a supported 1:8 envelope.
-- Use HTTPS/WSS signaling, trickle ICE, STUN, and authenticated coturn candidates. Prefer direct UDP, then relay UDP, with TURN/TCP as the required non-UDP fallback. Optional TURN/TLS uses standard TCP 5349 by default; TCP 443 is reserved for deployments with a dedicated public IP or validated L4/SNI routing.
-- Allow mixed connectivity in one room: direct viewers stay direct while only incompatible network pairs consume TURN bandwidth.
-- Treat 1080p60 as a best-effort quality profile, not a universal guarantee. Provide 720p60 and 720p30 fallbacks.
-- Do not add custom scene detection or dynamic-FPS control until WebRTC statistics and host resource measurements show that browser capture, encoding, and congestion behavior leave a material problem.
-- Leave codec order at the browser default in the first PoC and record the negotiated codec, encoder implementation, and power efficiency. Prefer H.264 only after target-machine measurements show that it is the hardware-efficient path; retain VP8 compatibility.
-- Add an Electron or native Windows sender only after browser measurements identify capture, application-audio, or encode bottlenecks.
-- Keep P2P as the default and add only an explicit deployment-level `p2p|sfu` choice. Multi-viewer use has already shown severe user-observed P2P degradation, consistent with one sender and encoder per viewer. The first SFU experiment should use a single node, one published layer, and no automatic switching, hybrid path, Redis, or peer forwarding tree.
-- Keep room policy deployment-driven and small. Public and password-only deployments use random temporary rooms. A deployment that configures both the whole-site password and a SQLite path gets sequential, non-expiring protected rooms; stopping a share leaves viewers waiting and does not destroy the room.
+- Keep the deployed Windows Chrome/Edge broadcaster and responsive Web viewer as the measurement baseline. Validate current Android Chrome and iOS Safari as leaves.
+- Use direct host P2P for one or two viewers. ADR-0004 owns the default-off experiment for later viewers: two sticky deterministic chains, host capacity two, viewer capacity one, no proactive rebalance or composite score, and no more than eight viewers when `PEER_ASSISTED_MEDIA=true`.
+- Standard browser relays resend remote `MediaStreamTrack` values and therefore decode and re-encode at every hop. Browser WebRTC does not guarantee one shared encoder across peer connections; measure this cost rather than hiding it.
+- Every ADR-0004 gate is mandatory. Reject the browser experiment if it needs Encoded Transform/DataChannel/WebCodecs media, custom congestion or RTP recovery, multiple trees, relay scoring, transcoding, codec ladders, browser RTP injection, or more than two host edges.
+- Only if topology, churn, connectivity, compatibility, and latency pass and re-encoding is the sole failure may a separate ADR propose a native shared-encode host plus opt-in native volunteer encoded-RTP relays. Any other failure closes peer assistance.
+- Keep user-operated mini-SFU deployment and central single-node SFU Draft PR #12 as explicit fallbacks. They transfer fanout egress to their operator and do not justify automatic switching, Redis, or multi-node infrastructure.
+- Prefer direct UDP, then TURN/UDP, with TURN/TCP as the required non-UDP fallback. Optional TURN/TLS uses TCP 5349 by default; TCP 443 needs a dedicated address or validated L4/SNI routing.
+- Treat 1080p60 as best effort and retain 720p60 and 720p30 fallbacks. Keep browser codec order until target hardware proves a more efficient common codec; do not add custom dynamic-FPS logic without stats showing a real gap.
+- Keep room policy deployment-driven. Public and password-only deployments use random temporary rooms. A site password plus SQLite path enables sequential persistent rooms; stopping sharing leaves the room and viewer link available.
## Current Implementation
-- The repository contains a single npm package using Node.js 24, React, TypeScript, Vite, native WebRTC, `ws`, Zod, Vitest, and a separate coturn deployment. The server defaults to an all-interface listener for LAN development and containers; the bare-metal reverse-proxy baseline explicitly binds loopback. It provides a process-only `/healthz` endpoint and requires STUN plus explicit TURN/UDP and TURN/TCP URLs before production startup. TURN/TLS is accepted but optional; configuration checks do not establish public-network reachability.
-- The Web PoC implements capture-before-room creation, live source replacement without renegotiating healthy peers, one independent peer connection per viewer, stable signaling reconnect identities that also work for LAN viewers on HTTP, explicit ICE restart or peer rebuild, host session generation isolation, viewer connection-generation guards for asynchronous signaling and stats, short-lived TURN credentials, three manual quality profiles, and local WebRTC statistics.
-- Access is deliberately small: `ACCESS_PASSWORD` is optional, site-wide, and accepts 1 through 128 visible ASCII characters when non-empty. When configured, host and viewer routes first establish a 12-hour stateless HMAC HttpOnly `SameSite=Strict` cookie; room creation and WebSocket upgrade accept that cookie and no direct room-creation Bearer bypass. There are no accounts, JWTs, server-side access-session maps, or logout flow.
-- ADR-0002 accepts an optional `ROOM_DATABASE_PATH` only alongside `ACCESS_PASSWORD`. In that mode, built-in `node:sqlite` stores only an auto-incremented room ID and host-token digest; links do not expire and stopping sharing leaves the room waiting. Without the path, rooms remain random and temporary. Public mode can never use sequential persistent rooms. Commit `2f66770f8e90` is deployed with `/var/lib/screener/rooms.sqlite`; the state directory and database permissions are verified, and the empty database preserves ID `1` for the first real browser room.
-- `/r/{code}` carries no viewer token or fragment, `/join` accepts only the numeric code, and the 256-bit host token stays internal to host authentication. In public mode the random code is the sole viewing capability and is not a strong privacy guarantee, so private Internet deployments should configure `ACCESS_PASSWORD`.
-- The Web control plane is deployed at `https://share.bonfire.icu` behind nginx with Node.js 24.19.0, and `turn.bonfire.icu` runs authenticated coturn 4.17.2 on standard UDP/TCP 3478. HTTPS, WSS, room authentication, certificate renewal, public STUN, authenticated TURN/UDP and TURN/TCP allocations, and relay-only bidirectional data paths are verified. TURN/TLS is intentionally not enabled.
-- Automated checks pass on current `main` with 102 Vitest tests and both production builds. Same-machine synthetic-media Chromium recovery and public relay-only DataChannel evidence remains from the earlier baseline. Production storage startup and permissions are verified; a real persistent-room stop/reuse/restart cycle, real screen/game audio, heterogeneous media sessions, mobile lifecycle handling, and latency or quality targets remain unverified.
-- No infrastructure blocker remains for the current staging deployment. The immediate control-plane milestone and the separate real-device/media matrix are bounded in `docs/status.md`; neither justifies a native sender yet.
+- The repository is one npm package using Node.js 24, React, TypeScript, Vite, native WebRTC, `ws`, Zod, Vitest, and separate coturn. LAN/container listening defaults to all interfaces; bare-metal reverse proxy deployment binds loopback and exposes `/healthz`.
+- The deployed media path still creates one independent host `RTCPeerConnection` per viewer. It supports capture-before-room creation, live source replacement, stable signaling identities, reconnect/ICE recovery, generation guards, short-lived TURN credentials, three manual quality profiles, and local WebRTC stats. It violates the new fanout target above two viewers.
+- The spike branch contains deterministic server/client peer-assisted assignment and standard remote-track relay. It defaults off, is capped at eight viewers, re-encodes at every relay, and is neither merged nor deployed. Native shared encoding and custom encoded browser transport are not implemented.
+- Access remains deliberately small: optional site-wide `ACCESS_PASSWORD`, a 12-hour stateless HMAC HttpOnly `SameSite=Strict` cookie, internal host token, role-bound signaling, Origin/payload checks, and no accounts, JWTs, session map, or logout flow.
+- With `ROOM_DATABASE_PATH` and the site password, built-in SQLite stores only auto-incremented room ID and host-token digest. Links persist and stopping sharing leaves viewers waiting. Without the path, rooms remain random and temporary; public mode cannot use sequential rooms.
+- Commit `2f66770f8e90` is deployed at `https://share.bonfire.icu` behind nginx. Authenticated coturn at `turn.bonfire.icu:3478` has verified public STUN, TURN/UDP, TURN/TCP, and relay-only traffic. TURN/TLS is intentionally disabled.
+- Chromium 151 has now demonstrated the intended three-viewer peer-assisted shape: exactly two connected host outbound peers; viewer 1 with one inbound plus one outbound forwarding to viewer 3; viewer 2 direct from the host; and decoded frames at all three viewers. Closing the first-level relay reattached its branch and resumed decoding in about 5.3 seconds while host active connected outbound edges peaked at two.
+- A Chromium 151 one-to-eight synthetic functional smoke formed two depth-four chains: two connected host outbound peers, one inbound plus one outbound at viewers 1 through 6, inbound-only viewers 7 and 8, and decoded frames everywhere. This is short functional evidence, not proof of 720p60 quality, performance, latency, or endurance.
+- That recovery covers only a page close immediately observed by the server. A silent partition waits for the 30-second heartbeat, so detection can take 30 to 60 seconds before the default 5-second viewer grace; it is unverified. The controlled server-observed recovery gate remains 5 seconds of grace plus at most 3 seconds to a decodable picture.
+- Relay outbound stats are observable, but relay senders still use a fixed `1080p60`/8 Mbps envelope rather than the host-selected profile; profile propagation blocks valid comparative measurements. Real persistent-room reuse/restart, screen and game audio, heterogeneous networks, relay resource and generational-quality cost, depth-four latency, endurance, silent partition recovery, and mobile leaves remain unverified.
+- On the current spike branch, `npm run check` passes type checking, 11 Vitest files with 129 tests, and both client and server production builds.
+- Draft SFU PR #12 and ADR-0003 remain unmerged, undeployed, and independently reversible. There is no infrastructure blocker for the current Web deployment or bounded spike.
## Provisional Quality Targets
-- Under a controlled direct path with RTT at or below 40 ms and packet loss at or below 1%: glass-to-glass latency p50 at or below 150 ms and p95 at or below 250 ms.
-- Under a regional TURN/UDP path with the same endpoint conditions: glass-to-glass latency p95 at or below 350 ms.
-- First picture within 3 seconds after a viewer requests to watch, excluding explicit user permission time.
-- A stable 60 fps profile should not silently fall below 50 decoded fps for more than 5 consecutive seconds; it must visibly downgrade or report the limiting reason.
-- These are engineering targets to validate with timestamp/high-speed-camera tests, not claims about untested networks.
+- Controlled direct path at RTT no more than 40 ms and loss no more than 1%: glass-to-glass p50 no more than 150 ms and p95 no more than 250 ms.
+- Regional TURN/UDP under the same endpoint conditions: glass-to-glass p95 no more than 350 ms.
+- First picture within 3 seconds after a watch request, excluding explicit permission time.
+- A 60 fps profile must not remain below 50 decoded fps for more than 5 seconds without a visible downgrade or limiting reason.
+
+These are measurement gates, not performance claims.
## Open Decisions
-- The sustainable viewer count for each publisher hardware, quality profile, network class, and media mode. Current P2P use degraded severely as viewers increased; that observation needs instrumented 1/3/5/8 comparison rather than a 1:8 support claim.
-- Exact mobile browser support matrix and the required behavior around autoplay, backgrounding, orientation changes, and network handoff.
-- Whether the first release is open source, source-available, or proprietary; this affects whether GPL/AGPL projects can be reused rather than only studied.
-- Initial deployment regions and expected mainland China/Hong Kong/overseas network mix.
-- Whether Windows per-application audio is P0 or whether whole-system loopback is acceptable initially.
-- Whether voice chat is ever in scope or the product remains complementary to an existing voice application.
+- Sustainable viewer count by broadcaster hardware, quality profile, network class, and media route; use instrumented 1/3/5/8 comparisons rather than a 1:8 claim.
+- Whether ADR-0004 passes fanout, re-encoding, depth-four latency, reparenting, silent-partition, and mobile-leaf gates.
+- Exact mobile lifecycle behavior and whether Windows per-application audio is required for the first release.
+- Project license and distribution model, which determines whether GPL/AGPL sources can move beyond study-only use.
+- Initial deployment regions and expected mainland China, Hong Kong, and overseas network mix.
+- Whether voice chat ever enters scope or Screener stays complementary to an existing voice application.
## Source Of Truth
-- Requirements: `docs/需求理解.md`
-- First PoC technical design: `docs/方案设计.md`
-- Minimal production-shaped deployment: `docs/deployment.md`
-- Research and feasibility: `docs/research/webrtc-p2p-screen-sharing.md`
-- Topology decision: `docs/adr/0001-p2p-first-media-topology.md`
-- Persistent protected-room decision: `docs/adr/0002-persistent-protected-rooms.md`
-- Current phase and next step: `docs/status.md`
-- Maintenance and context lifecycle: `docs/maintenance.md`
-- Agent workflow: `AGENTS.md` and `.codex/`
+- Documentation index: `docs/README.md`
+- Current phase: `docs/status.md`
+- Requirements and first PoC design: linked from the documentation index
+- Media research: `docs/research/webrtc-p2p-screen-sharing.md`, `docs/research/peer-assisted-media.md`, and `docs/research/low-server-media-routes.md`
+- Architecture: ADR-0001, ADR-0002, proposed experiment ADR-0004, and Draft PR #12's unaccepted ADR-0003
+- Deployment and maintenance: `docs/deployment.md`, `docs/maintenance.md`, `AGENTS.md`, and `.codex/`
diff --git a/docs/research/low-server-media-routes.md b/docs/research/low-server-media-routes.md
new file mode 100644
index 00000000..64bb0141
--- /dev/null
+++ b/docs/research/low-server-media-routes.md
@@ -0,0 +1,149 @@
+# Low-Server-Cost Media Routes
+
+- Research date: 2026-08-19
+- Scope: one broadcaster, at most eight trusted viewers, low latency, and host
+ media fanout at most two
+- Status: route screening for ADR-0004; only the standard browser relay is in
+ the current spike
+
+## Current Route Ladder
+
+The smallest current plan is:
+
+1. Use direct host P2P for one or two viewers.
+2. For later viewers, test the fixed two-chain browser relay in ADR-0004. It is
+ disabled by default with `PEER_ASSISTED_MEDIA=false`, is limited to at most
+ eight viewers, and decodes and re-encodes at every relay.
+3. Only if that spike passes every topology, churn, connectivity, compatibility,
+ and latency gate but fails solely because of relay re-encoding may a separate
+ experiment combine a native shared-encode host with opt-in native volunteer
+ encoded-RTP relays.
+4. Keep a user-operated mini-SFU and a centrally operated single-node SFU as
+ explicit fallbacks. They transfer fanout bandwidth to their operator; they do
+ not make it disappear.
+
+Any browser-spike failure other than the isolated re-encoding cost closes the
+peer-assisted route. Draft SFU PR #12 remains unmerged and undeployed. There is
+no automatic topology migration in this plan.
+
+## Traffic Conservation And The Impossible Triangle
+
+This is an engineering accounting identity, not a named theorem. For `N`
+viewers receiving bitrate `B`, useful last-hop delivery is approximately
+`N * B`. Ignoring protocol overhead:
+
+`host last-hop copies + peer last-hop copies + server last-hop copies = N * B`
+
+TURN, RTP/QUIC headers, retransmission, FEC, and redundant paths only add traffic.
+Encoding once can reduce compute and memory bandwidth, but it cannot remove the
+network copy delivered to each viewer.
+
+On today's unicast Internet, a design cannot maximize all three of these for
+more than one viewer:
+
+1. near-zero central-server media egress;
+2. near-zero host and viewer upload, compute, and installation burden; and
+3. ultra-low-latency, robust recovery across churn, NAT, and restrictive networks.
+
+If the server does not emit the copies, endpoints must. If endpoints do not,
+the server must. Redundancy can improve recovery but costs traffic and
+coordination; removing redundancy leaves a recovery interval after a relay is
+lost.
+
+## Route Screening
+
+| 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 |
+| Native shared host plus native volunteer encoded-RTP relay | Host encodes once for up to two edges; each volunteer forwards one encoded copy | Native install, RTP/RTCP forwarding, packaging, and opt-in relay policy | Conditional next experiment only if re-encoding is the sole browser-spike failure |
+| User-operated mini-SFU | User's SFU emits viewer copies | Separate deployment and its egress bill; running it on the host does not reduce that host's uplink | Explicit fallback |
+| Central single-node SFU | Service SFU emits viewer copies | Lowest endpoint relay burden; service pays approximately `N * B` egress | Explicit fallback; Draft PR #12 only |
+| SVC plus multiple trees | Peers emit striped layer copies across several trees | Layer scheduling, reassembly, redundancy, and more churn state | Reject for the current product |
+| Network coding | Peers or servers emit coded blocks | Generations, buffering, decoding, integrity, and a custom media plane | Reject for the current product |
+| MoQ | Publishers and MoQ relays emit object copies | New transport, packaging, player, relay, and auth stack | Reject for the current WebRTC product |
+| Peer-assisted CDN | Peers cache or upload segments/objects | Discovery, locality, scheduling, incentives, abuse, and privacy systems | Reject for this trusted group |
+| IP multicast | Multicast routers replicate packets | Requires multicast-enabled hosts and routed networks unavailable to ordinary Internet browsers | Reject outside managed networks |
+
+## Conditional Native Encoded-RTP Route
+
+Pion exposes the necessary native building blocks: `TrackRemote.ReadRTP()` reads
+encoded RTP, `TrackLocalStaticRTP.WriteRTP()` writes pre-packetized RTP into
+standard downstream WebRTC connections, and `RTPSender.ReadRTCP()` exposes
+receiver feedback. A native volunteer could therefore terminate an upstream
+WebRTC connection and forward encoded RTP to one downstream connection without
+decoding or re-encoding. The downstream leaf can remain a normal browser.
+
+This is feasibility evidence, not a ready relay. A real implementation still
+has to prove codec/profile agreement, SSRC and sequence/timestamp handling,
+RTCP feedback translation, NACK/RTX behavior, congestion control, keyframe
+requests, generation changes, security, packaging, and voluntary use. The host
+also needs a separate native shared encoder so its two WebRTC packetizers consume
+one encoded result. Pion's broadcast example demonstrates server-side RTP
+fanout, but it does not supply this end-user topology or product behavior.
+
+This route is permitted only after measurements isolate re-encoding as the sole
+failure. It must not rescue failures in deterministic assignment, host fanout,
+relay loss recovery, ICE/TURN connectivity, mobile leaves, or end-to-end latency.
+
+## Rejected For The Current Implementation
+
+- **SVC and multiple trees:** WebRTC SVC controls layered encoding; it does not
+ distribute replicas. SplitStream shows how striping across multiple trees can
+ spread peer load, but the required tree maintenance, reassembly, scheduling,
+ and redundancy contradict the fixed two-chain experiment.
+- **Network coding:** published work improves block distribution in large
+ overlays. Generations, coding/decoding, pollution protection, and buffering
+ create a custom transport and add latency; it is not a small extension to live
+ browser WebRTC.
+- **MoQ:** Media over QUIC provides promising relay-oriented publish/subscribe,
+ priorities, and partial reliability, but MOQT and its streaming format remain
+ active Internet-Drafts. Adopting it would replace the media plane and still
+ leave relay operators paying fanout egress.
+- **Peer-assisted CDN:** PCDN research addresses large file or segmented VoD
+ distribution and ISP/provider cost. Its discovery, caching, locality,
+ scheduling, incentives, and abuse controls are disproportionate for at most
+ eight trusted viewers and do not guarantee sub-second live latency.
+- **IP multicast:** Internet Group Management and Source-Specific Multicast
+ require participating hosts and multicast routers. ICE establishes unicast
+ candidate-pair transports; normal browser WebRTC across NAT and mobile networks
+ exposes no Internet multicast delivery path.
+
+## Sources And License Boundary
+
+Primary sources checked on 2026-08-19:
+
+- [Pion WebRTC](https://github.com/pion/webrtc) - MIT; no code copied.
+- [Pion WebRTC v4 API](https://pkg.go.dev/github.com/pion/webrtc/v4) - API
+ evidence for RTP and RTCP access.
+- [Pion broadcast example](https://github.com/pion/webrtc/tree/main/examples/broadcast)
+ and [examples index](https://github.com/pion/webrtc/blob/main/examples/README.md)
+ - MIT; reference behavior only.
+- [RTP Topologies, RFC 7667](https://www.rfc-editor.org/rfc/rfc7667.html) and
+ [ICE, RFC 8445](https://www.rfc-editor.org/rfc/rfc8445.html) - IETF standards
+ under IETF Trust terms.
+- [WebRTC](https://www.w3.org/TR/webrtc/),
+ [WebRTC Encoded Transform](https://w3c.github.io/webrtc-encoded-transform/#stream-processing),
+ and [WebRTC SVC](https://www.w3.org/TR/webrtc-svc/) - W3C specifications; SVC
+ is an encoding control, not a distribution topology.
+- [MoQ Transport](https://datatracker.ietf.org/doc/draft-ietf-moq-transport/),
+ [MoQ Streaming Format](https://datatracker.ietf.org/doc/draft-ietf-moq-msf/),
+ and the [MoQ working group](https://datatracker.ietf.org/wg/moq/) - active IETF
+ work, not final RFCs.
+- [moq-dev/moq](https://github.com/moq-dev/moq) - core crates are dual
+ MIT/Apache-2.0; its separately distributed `cpp/obs` plugin is
+ GPL-2.0-or-later. No code was copied.
+- [SplitStream, SOSP 2003](https://www.microsoft.com/en-us/research/publication/splitstream-high-bandwidth-multicast-in-a-cooperative-environment/)
+ - published research, no implementation license granted here.
+- [Network Coding for Large Scale Content Distribution, INFOCOM 2005](https://www.microsoft.com/en-us/research/publication/network-coding-for-large-scale-content-distribution/)
+ - published research, no implementation license granted here.
+- [Should Internet Service Providers Fear Peer-Assisted Content Distribution?](https://www.usenix.org/conference/imc-05/should-internet-service-providers-fear-peer-assisted-content-distribution)
+ - published research, no implementation license granted here.
+- [IP multicast, RFC 1112](https://www.rfc-editor.org/rfc/rfc1112.html) and
+ [Source-Specific Multicast, RFC 4607](https://www.rfc-editor.org/rfc/rfc4607.html)
+ - IETF standards under IETF Trust terms.
+- [LiveKit](https://github.com/livekit/livekit) - Apache-2.0; the optional SFU
+ reference, with no code copied into this research change.
+
+No GPL/AGPL code was copied. Published papers and specifications support design
+analysis only; their presence here is not an implementation license.
diff --git a/docs/research/peer-assisted-media.md b/docs/research/peer-assisted-media.md
new file mode 100644
index 00000000..0f5061e7
--- /dev/null
+++ b/docs/research/peer-assisted-media.md
@@ -0,0 +1,299 @@
+# Peer-Assisted Media Research
+
+- Research date: 2026-08-19
+- Scope: one game-screen broadcaster, at most eight trusted viewers, host media fanout at most two
+- Status: evidence for a bounded experiment; not a production topology decision
+
+## Conclusion
+
+Peer-assisted forwarding can cap the broadcaster at one or two outgoing media
+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.
+
+This path reuses WebRTC capture, codec negotiation, RTP, NACK/PLI/RTX, congestion
+control, jitter buffering, ICE, STUN, TURN, DTLS-SRTP, and browser rendering. Its
+cost is unavoidable in ordinary browsers: every relay decodes and re-encodes
+the screen stream. The first spike measures whether that cost is acceptable; it
+does not hide it or claim shared encoding.
+
+The product preference is `direct P2P -> peer-assisted -> optional SFU`. This is
+an engineering priority, not permission for silent in-room migration. Direct
+P2P remains the simplest path for one or two viewers. The experiment assigns the
+third and later viewers to peers automatically. The optional SFU remains an
+explicit, independently reversible deployment choice.
+
+## What Browsers Can Share
+
+The WebRTC specification permits the same `MediaStreamTrack` to be sent more
+than once, but each send is represented by a separate `RTCRtpSender`. It does
+not promise that these senders share an encoder. Current libwebrtc constructs a
+separate `VideoSendStream` and `VideoStreamEncoder` with its own encoder queue
+for each send stream. The product must therefore assume one encoder pipeline
+per browser send stream even if a particular GPU driver happens to optimize it.
+
+Cloning a track or using `VideoTrackGenerator` can share a capture source or
+raw-frame preprocessing. The values entering each `RTCRtpSender` are still raw
+`VideoFrame` objects, so this does not share the encoded result.
+
+Sources:
+
+- [WebRTC sender/receiver relationship](https://w3c.github.io/webrtc-pc/#rtp-media-api)
+- [Media Capture shared sources](https://w3c.github.io/mediacapture-main/)
+- [Media Capture Transform raw `VideoFrame` model](https://w3c.github.io/mediacapture-transform/)
+- [libwebrtc creates a send stream per sender](https://webrtc.googlesource.com/src/+/refs/heads/main/media/engine/webrtc_video_engine.cc)
+- [libwebrtc creates a `VideoStreamEncoder` per send stream](https://webrtc.googlesource.com/src/+/refs/heads/main/video/video_send_stream_impl.cc)
+
+## Why Encoded Transform Is Not Shared Encoding
+
+WebRTC Encoded Transform runs after a sender encoder and before its packetizer,
+or after a receiver depacketizer and before its decoder. Its normative write
+algorithm rejects a frame whose owner differs from the transform's frame
+source, stating that a processor cannot create frames or move frames between
+streams. It therefore cannot tee sender A's encoded frame into sender B's RTP
+pipeline.
+
+Replacing the bytes of dummy frames produced by sender B would still run sender
+B's encoder and would couple unrelated keyframe, dependency, cadence, and codec
+metadata. It is a browser-specific hack rather than a supported pre-encoded RTP
+injection point and is outside this experiment.
+
+Encoded Transform could expose the already depacketized frame before decode,
+but using that data outside the receiver leads to the custom transport described
+below. It is not part of the first spike.
+
+Source: [WebRTC Encoded Transform stream processing](https://w3c.github.io/webrtc-encoded-transform/#stream-processing)
+
+## Standard Browser Relay Versus Encoded Relay
+
+### Standard WebRTC Track Relay
+
+A browser can receive a remote `MediaStreamTrack` and add it to another
+`RTCPeerConnection`. This is the compatibility-first route, but the public
+track carries decoded frames. Current libwebrtc connects a receiver to a
+`VideoSinkInterface<VideoFrame>` and a sender accepts a
+`VideoSourceInterface<VideoFrame>` before creating its own encoder pipeline.
+
+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.
+
+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)
+
+### Encoded DataChannel Relay, Rejected For The First Spike
+
+WebCodecs accepts and emits `EncodedVideoChunk` values but defines no network
+transport and no bridge into `RTCRtpSender`. Sending those chunks through a
+DataChannel avoids relay re-encoding, but the application must define:
+
+- protocol and stream-generation versions;
+- frame ID, timestamp, duration, key/delta type, and codec configuration;
+- fragments and reassembly bounds;
+- queue limits and late-frame dropping;
+- keyframe requests after join, loss, or reparenting;
+- decoder reset and generation changes; and
+- explicit failure when the codec or feature set is unsupported.
+
+DataChannel still provides ICE/TURN traversal, DTLS protection, SCTP
+fragmentation, partial reliability, and association-level congestion control.
+RFC 8831 warns that a large message can monopolize an SCTP association when
+message interleaving is unavailable and recommends limiting messages to 16 KB
+in that case. Even a minimal custom alternative would need a reliable ordered
+control channel plus an unordered, zero-retransmission video channel, with
+application messages no larger than 16 KB when interleaving is unavailable.
+
+This is a custom media plane over a proven transport, not a custom UDP stack.
+It remains materially more complex than standard WebRTC media and is rejected
+for the first spike. It cannot rescue a failed gate; only when re-encoding is
+the sole failure may the separate native encoded-RTP route described in
+`low-server-media-routes.md` be proposed.
+
+Sources:
+
+- [WebCodecs](https://www.w3.org/TR/webcodecs/)
+- [WebRTC Data Channels, RFC 8831](https://www.rfc-editor.org/rfc/rfc8831.html)
+
+## Native TeamSpeak-Style Shared Encoding
+
+TeamSpeak describes its current single-encoding design as encoding once and
+sending the result directly to viewers. This removes repeated encoding and
+memory cost, but it does not remove one network copy per viewer. It therefore
+does not satisfy a hard host fanout of two by itself.
+
+A future native Screener sender can preserve standard browser receivers without
+writing a new transport. libwebrtc accepts an application-supplied
+`VideoEncoderFactory`; a factory can return per-send-stream proxy encoders
+backed by one shared hardware encoder and fan the resulting `EncodedImage` into
+each stream's `EncodedImageCallback`. libwebrtc can then retain independent RTP
+sequence numbers, packetization, SRTP, RTCP, NACK/RTX, ICE, and congestion state
+for the two host edges.
+
+This is an engineering inference from the native interfaces, not a ready-made
+libwebrtc feature. The coordinator must deduplicate input frames, reconcile
+independent rate requests, combine keyframe requests, preserve timestamps, and
+require one common codec/profile/resolution/layer. It is high-complexity native
+work, but it is the viable long-term way to **guarantee** one host encode while
+keeping normal browser first-hop receivers. Browser JavaScript cannot provide
+that guarantee.
+
+Sources:
+
+- [TeamSpeak single-encoding explanation](https://community.teamspeak.com/t/ts6-beta-community-update-insights/58116/208)
+- [libwebrtc `VideoEncoderFactory`](https://webrtc.googlesource.com/src/+/refs/heads/main/api/video_codecs/video_encoder_factory.h)
+- [libwebrtc `VideoEncoder` and encoded callback](https://webrtc.googlesource.com/src/+/refs/heads/main/api/video_codecs/video_encoder.h)
+
+## 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
+means one downstream `RTCPeerConnection` carrying the shared stream; selecting
+TURN for that connection 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;
+- 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
+- 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.
+
+Per-edge ICE remains independent. An edge may be direct or may use authenticated
+TURN, so peer assistance reduces normal server media traffic but cannot promise
+zero server traffic in restrictive networks.
+
+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
+to abandon this small-product experiment, not to expand it.
+
+Source: [SplitStream, SOSP 2003](https://www.microsoft.com/en-us/research/publication/splitstream-high-bandwidth-multicast-in-a-cooperative-environment/)
+
+## Compatibility Boundary
+
+The standard remote-track relay in the first spike uses broadly deployed WebRTC
+media APIs and does not depend on Encoded Transform or WebCodecs. Current MDN
+browser-compatibility data records `RTCRtpScriptTransform` in
+Chrome 141, Firefox 117, and Safari 15.4. `VideoDecoder` is recorded in Chrome
+94, Firefox desktop 130, and Safari/iOS 16.4, but not Firefox Android.
+`MediaStreamTrackProcessor` remains less portable: Chrome's implementation is
+partial, Firefox has no implementation, and Safari added it in version 18.
+
+These compatibility figures explain why the custom encoded alternative is not
+the first spike. Even when an API exists, an application must call
+`VideoDecoder.isConfigSupported()` for the exact codec configuration. API
+presence is not proof that a particular codec, profile, resolution, or hardware
+path works.
+
+Sources:
+
+- [Encoded Transform compatibility data](https://raw.githubusercontent.com/mdn/browser-compat-data/main/api/RTCRtpScriptTransform.json)
+- [WebCodecs `VideoDecoder` compatibility data](https://raw.githubusercontent.com/mdn/browser-compat-data/main/api/VideoDecoder.json)
+- [`MediaStreamTrackProcessor` compatibility data](https://raw.githubusercontent.com/mdn/browser-compat-data/main/api/MediaStreamTrackProcessor.json)
+
+## Resource Model
+
+For observed encoded bitrate `B`, `N` viewers, two host slots, and one viewer
+slot:
+
+- host upload is at most approximately `2 * B`, plus transport overhead;
+- each relay upload is at most approximately `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.
+This spike has no runtime capability flag: its desktop relay/mobile leaf matrix
+is enforced only by controlled join order, so it must not be enabled for
+arbitrary users.
+
+## Bounded Spike And Gates
+
+The experiment is disabled by default through `PEER_ASSISTED_MEDIA=false` and
+cannot be enabled above eight viewers. It 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
+existing screen-audio track when the browser provides one. SVC/simulcast,
+custom encoded transport, FEC changes, multi-tree striping, transcoding,
+background mobile relay, and automatic SFU migration are excluded.
+
+Run 1, 3, 5, and 8 viewers for 30 minutes at 720p60 under controlled per-edge
+RTT at or below 40 ms and loss at or below 1%. Record topology generation and
+depth, selected candidate type, host and relay upload, packets lost, jitter,
+frames encoded/decoded/dropped, total encode/decode time, decoded FPS,
+`qualityLimitationReason`, first picture, reparent time, CPU, GPU, and
+glass-to-glass latency.
+
+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,
+ 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
+ encode time, CPU/GPU cost, and `qualityLimitationReason` are recorded rather
+ than mislabeled as shared encoding.
+3. Excluding explicitly selected TURN edges, application-server media ingress
+ 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
+ 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
+ grace, deterministic reassignment produces a new decodable picture within the
+ following 3 seconds without violating host fanout, about 8 seconds total.
+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.
+
+An ordinary implementation defect may be corrected inside the spike. If a gate
+requires an encoded DataChannel/WebCodecs media plane, custom congestion
+control, FEC/RTX changes, multiple distribution trees, relay scoring,
+transcoding, a codec ladder, or relaxed host fanout, abandon this browser
+architecture. Mark ADR-0004 rejected, remove its experimental runtime code and
+dependencies, and retain this research. Only if relay re-encoding is the sole
+failed gate may a separate ADR propose the native shared-encode/encoded-RTP
+route; every other failure keeps standard P2P plus explicit user-operated or
+central SFU fallbacks.
+
+Passing these gates proves only that a second design phase is justified. It
+does not accept peer-assisted media for production. Production adoption would
+need a new ADR, voluntary relay policy, broader audio/A-V verification, and the
+native host shared-encode design.
+
+The recovery gate above does not cover silent network partitions. With the
+default 30-second heartbeat, server detection can take 30 to 60 seconds before
+the same 5-second grace begins; that case remains unverified and must be reported
+separately.
+
+## License Boundary
+
+This research uses W3C/IETF specifications, BSD-licensed libwebrtc source,
+official TeamSpeak statements, browser-compatibility data, and a published
+systems paper. No GPL/AGPL implementation code was copied. GPL/AGPL projects
+remain study-only until the project license and distribution model are decided.
diff --git a/docs/research/webrtc-p2p-screen-sharing.md b/docs/research/webrtc-p2p-screen-sharing.md
index 906dbd3e..aa98d2ce 100644
--- a/docs/research/webrtc-p2p-screen-sharing.md
+++ b/docs/research/webrtc-p2p-screen-sharing.md
@@ -2,7 +2,7 @@
- 调研日期:2026-08-18
- 目标场景:一名玩家向少量熟人私密分享,观看者可用手机/桌面浏览器加入,低延迟,尽量不消耗媒体服务器带宽
-- 结论状态:可用于原型立项;人数、音频范围和部署地区仍需实测确认
+- 结论状态:标准 P2P 原型基线已采用;多人退化已触发独立的 peer-assisted 调研与 Draft SFU 对照,二者都未成为默认路径
## 结论
@@ -16,7 +16,8 @@
|
+---- 仅直连失败的观看者 ---- TURN relay -------+
-若未来产品范围超出小房间边界,再单独评估区域 SFU;大规模公开分享直接使用现有直播服务。
+首选顺序:一至两名观看者直接 P2P -> 通过门槛后的 peer-assisted -> 部署者显式选择的可选 SFU。
+该顺序不允许静默拓扑迁移;大规模公开分享仍直接使用现有直播服务。
```
“让画面跑起来”难度不高;“像 Discord/TeamSpeak 一样在不同 GPU、浏览器、NAT、运营商和弱网中都保持清晰、60 fps、低延迟”难度高。建议把产品分层:
@@ -88,6 +89,7 @@ ICE 是按分享者与每一名观看者的网络组合独立选路,而不是
| --- | ---: | ---: | --- |
| P2P 星型 | `N * B` | 直连时接近 0 | 最符合成本目标;适合少量朋友 |
| P2P + TURN | 仍为 `N * B` | 每条中继约 `B` 入 + `B` 出 | 只解决不可达,不解决分享者上行 |
+| Peer-assisted 两链 | 分享端最多约 `2 * B` | 直连边接近 0;TURN 仍按边计费 | 每名 viewer 最多转发一份;标准 browser relay 逐跳解码/重编码 |
| SFU | 约 `B` | `B` 入 + `N * B` 出 | 分享者轻松,但服务器承担全部观看流量 |
| MCU | 约 `B` | 另有解码、合成、重编码 | 本场景没有合成需求,不采用 |
@@ -110,7 +112,7 @@ IETF 对 mesh/SFU 的拓扑说明见 [RFC 7667](https://www.rfc-editor.org/rfc/r
## 推荐的拓扑策略
-MVP(也是预期的正常产品形态):
+已部署 MVP 基线:
- 小范围观看者默认 P2P,每人一条独立连接。
- 当前 PoC 默认允许八名观看者,部署者可配置 1 至 16,超额连接会被明确拒绝。该数值只控制接入,不代表 1:8 已通过性能验收;必须收集可用上行、实际发送码率、`qualityLimitationReason`、编码耗时和发送队列来确定真实可持续人数。
@@ -118,7 +120,7 @@ MVP(也是预期的正常产品形态):
- 若一开始就有多条 `relay`,应提示服务器带宽正在增加。
- 桌面和手机观看者使用同一个 Web 播放端;分享者不要求朋友安装完整客户端。
-本项目不以 SFU 作为正常扩容路径;超过小房间上限时直接建议使用外部直播服务。只有以后改变产品范围时,才根据遥测重新评估房间级 SFU,观察项包括:
+新的产品目标要求分享端 fanout 永远不超过二。Proposed ADR-0004 用一个可整体删除的实验验证第三名及后续 viewer 能否由客户端转发;Draft PR #12 则保留显式单节点 SFU 作为独立对照。两者都不允许在房间内静默切换,超过小房间上限时仍建议使用外部直播服务。观察项包括:
- 正常工作负载持续超过实测可承载的 P2P 人数。
- 第一名或多名观看者已使用 TURN,继续 P2P 会重复占用服务器上行。
@@ -126,7 +128,7 @@ MVP(也是预期的正常产品形态):
- 分享者因 CPU/encoder 限制降质。
- 产品开始要求隐藏好友之间的 IP。
-不要在 MVP 做观看者转发树。浏览器对收到的 WebRTC track 再发布可能发生解码/重编码,增加负载、质量损失和一跳延迟;真正的数据包级转发还需要自定义密钥、拥塞、故障切换和原生网络层。
+不要把观看者转发树直接加入 MVP。标准浏览器把收到的 WebRTC track 再发布会走解码后的 raw-frame sender,并创建新的编码 pipeline,增加负载、质量损失和逐跳延迟。ADR-0004 只允许用这条标准路径做确定性的两链 spike;若需要 Encoded Transform/DataChannel/WebCodecs 媒体、自定义拥塞控制、FEC/RTX、多树或综合评分,即放弃实验。详细证据见 `peer-assisted-media.md`。
## Web、Electron 与原生能力
@@ -321,5 +323,5 @@ WebRTC 标准没有承诺固定毫秒延迟。工程目标必须带网络条件
3. 从第一天部署 coturn,并验证 direct、TURN/UDP、TURN/TCP 以及移动网络切换;这是避免“部分好友永远看不了”的必要条件。TURN/TLS 按部署需要选配,默认 5349,443 只作为受限网络增强。
4. 观看端优先做成免安装响应式 Web;分享端先 Web 验证,再按捕获/音频实测升级 Electron。
5. 产品代码优先直接使用浏览器 WebRTC API;借鉴 MiroTalk BRO 和 Screego,不在许可证未定前直接 fork GPL/AGPL 代码。
-6. 正常人数超过产品上限时引导使用现有直播服务,不为了假设规模提前搭 SFU;若范围以后改变,首选 Broadcast Box 或 LiveKit,不从零写 SFU。
-7. 不做客户端转发树和自定义视频协议;它们会把项目从中等难度推到接近自研 Parsec 的高难度。
+6. 分享端 hard fanout 为二;一至两名 viewer 走直接 P2P,第三名及以后只通过 ADR-0004 的 bounded peer-assisted spike 验证,不得隐藏回退为更多 host 连接。
+7. 可选 SFU 保持显式、可逆且非默认。peer-assisted 若未通过逐跳重编码负载、延迟、兼容和换父门槛就整体放弃,不通过 encoded custom media、评分器、多树或自研 RTP 来挽救。
diff --git a/docs/status.md b/docs/status.md
index 84cf1cf9..bca2551c 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -1,73 +1,79 @@
# Current Status
-Last updated: 2026-08-18
+Last updated: 2026-08-19
## Phase
-The WebRTC proof of concept is deployed at `https://share.bonfire.icu`. Commit
-`2f66770f8e90` adds protected SQLite persistence, sequential room IDs, reusable
-links, and a waiting state after sharing stops. The production database is
-initialized and empty, so the first real persistent room can receive ID `1`.
-Real capture, game audio, mobile lifecycle, and performance targets remain
-unverified. Increasing the P2P viewer count has already caused severe user-
-observed degradation, so an explicitly configured SFU mode is the next media
-experiment; P2P remains the default topology.
-
-## Established Baseline
-
-- Runtime: Node.js 24, React, TypeScript, Vite, native browser WebRTC, `ws`, Zod, and a separate coturn deployment.
-- Product scope: private game sharing for one broadcaster and a small friend group. Rooms default to eight viewers and accept a configured limit from 1 through 16; this is an admission limit, not a verified performance envelope.
-- Client behavior: screen capture precedes room creation; live source changes preserve healthy peer connections; `/r/{code}` invitations and `/join` use a numeric room code with no viewer token or URL fragment; every viewer has an independent `RTCPeerConnection`.
-- Control plane contract: optional whole-site `ACCESS_PASSWORD` with 1 through 128 visible ASCII characters, a 12-hour stateless HMAC HttpOnly `SameSite=Strict` cookie, an internal host token, role-bound signaling, stable reconnect identities, short-lived coturn credentials, and Origin/payload checks. There are no accounts, JWTs, server-side access-session maps, or logout flow.
-- Room policies: no `ROOM_DATABASE_PATH` means random temporary rooms governed by `ROOM_TTL_SECONDS`; configuring it together with `ACCESS_PASSWORD` enables protected rooms whose numeric IDs increment from `1` and whose links do not expire. A database path without the whole-site password is invalid. Stopping sharing leaves the room available and viewers waiting. SQLite stores only room ID and host-token digest.
-- Media topology: direct ICE is preferred per viewer, with authenticated TURN/UDP and TURN/TCP required in production. TURN/TLS is an optional deployment capability, using standard TCP 5349 by default; mixed direct and relay paths are supported by design.
-- Diagnostics: per-peer path, candidate types, ICE protocol, local TURN protocol, RTT, bitrate, frame rate, dimensions, loss, jitter, codec, and quality-limitation fields are read locally from WebRTC stats.
-- Large public broadcasts are out of scope and should use OBS/Twitch-class services.
-
-## Verification
-
-- On current `main`, `npm run check` passes type checking,
- 102 Vitest tests, the client production build, and the server production build.
-
-The remaining browser and network evidence predates the persistent-room rollout;
-it does not verify a real browser stop-and-republish cycle with room ID `1`.
-
-- Headless Chromium 151 created real local peer connections from animated canvas streams. The viewer reached `connected`, received a live video track, and reported a direct UDP path.
-- Browser fault injection recovered after dropping the first offer, dropping the first answer, and failing the first `createOffer`. A viewer-only signaling reconnect preserved the existing healthy media peer; replacing that viewer tab rebuilt media, released the old peer, and did not enter a reconnect loop.
-- Delayed ViewerPeer answer, candidate flush, ICE event, and stats results are discarded after a connection generation is replaced, so an old peer cannot signal through or overwrite the new peer snapshot.
-- Injecting a live picker-cancellation result preserved the old stream. Replacing synthetic video, adding synthetic audio, and removing it all kept the same connected host/viewer peer objects and did not create another offer; retired capture tracks stopped after each successful change.
-- Chrome 151 at 390 px completed the protected-site gate, login, host, and manual room-code join flow without horizontal overflow. The unauthenticated gate shows no application header or sharing controls.
-- Production configuration fails closed when required HTTPS, STUN, TURN, or TURN-secret constraints are missing.
-- Production startup rejects malformed ICE URLs and requires STUN plus explicit TURN/UDP and TURN/TCP entries. Optional TURN/TLS entries may use standard TCP 5349 or, when separately routed, TCP 443. Configuration validation remains distinct from the runtime relay checks below.
-- The application defaults to `LISTEN_HOST=0.0.0.0` for LAN development and containers, while the bare-metal reverse-proxy deployment explicitly uses loopback. It exposes a process-only `GET /healthz` liveness response.
-- Viewer session identities use `crypto.getRandomValues()` rather than the secure-context-only `crypto.randomUUID()`, so a phone can initialize the viewer over trusted LAN HTTP while the host keeps screen capture on `localhost`.
-- The staging host runs Debian 12, nginx, Node.js 24.19.0, and source-built coturn 4.17.2. Screener binds loopback behind nginx; authenticated STUN and TURN/UDP+TCP bind `turn.bonfire.icu:3478`. TURN/TLS remains intentionally disabled.
-- Commit `2f66770f8e90` is deployed. Production verification covered rejection of the previous password, login with the current password, the `Secure`/`HttpOnly`/`SameSite=Strict` cookie, the initialized empty SQLite schema, service state directory mode `0700`, database mode `0600`, and a clean service restart with zero automatic restarts. The prior room and WebSocket authentication checks remain applicable. The existing blog continued returning HTTP 200.
-- Public STUN Binding succeeds over both UDP and TCP 3478. Chromium 151 obtained authenticated relay candidates through TURN/UDP and TURN/TCP, then two relay-only peer connections completed a bidirectional DataChannel ping/pong over each transport. Simultaneous guest conntrack samples observed both 3478 control traffic and relay-range UDP traffic, independently confirming the public TURN path through the cloud and host firewalls.
-- The existing TeamSpeak files, services, timers, and ports were not changed.
+The standard one-`RTCPeerConnection`-per-viewer WebRTC PoC is deployed at
+`https://share.bonfire.icu`. Commit `2f66770f8e90` is the deployed baseline for
+protected SQLite rooms, sequential reusable IDs, and waiting after sharing
+stops. This path still exceeds the new host-fanout target above two viewers.
+
+The spike branch contains a default-off, standard-WebRTC peer-assisted
+experiment for later viewers. It assigns two sticky chains with host capacity
+two and viewer capacity one, then relays remote tracks with a decode/re-encode
+at every browser hop. `PEER_ASSISTED_MEDIA=false` remains the default and the
+mode cannot be enabled above eight viewers. Limited Chromium evidence now proves
+the intended three-viewer shape, a synthetic eight-viewer functional topology,
+and one controlled page-close recovery, but the mode is not merged, deployed,
+or production-validated. Draft SFU PR #12 is also unmerged and undeployed.
+
+## Current Snapshot
+
+- Product scope is private game sharing for one broadcaster and a small trusted friend group; public broadcasting remains out of scope.
+- Runtime is Node.js 24, React, TypeScript, Vite, native browser WebRTC, `ws`, Zod, Vitest, and a separate coturn deployment.
+- Capture precedes room creation. Healthy peers survive source replacement, and local stats report path, candidate, RTT, bitrate, frame, loss, jitter, codec, and quality-limitation data.
+- Whole-site `ACCESS_PASSWORD` is optional. Protected sessions use a stateless 12-hour HMAC HttpOnly `SameSite=Strict` cookie; host authentication remains internal and signaling is role-bound.
+- Without `ROOM_DATABASE_PATH`, rooms are random and temporary. With both the database path and site password, room IDs start at `1`, links persist, and stopping a share leaves viewers waiting. SQLite stores only room ID and host-token digest.
+- Direct ICE is preferred independently per media edge. Authenticated TURN/UDP and TURN/TCP are required production fallbacks; TURN/TLS is optional.
+- The experimental media priority remains direct P2P for one or two viewers, peer-assisted only after its gates pass, then user-operated or central single-node SFU as an explicit fallback. There is no automatic migration.
+
+## Verified Evidence
+
+- On the current spike branch, `npm run check` passes type checking, 11 Vitest files with 129 tests, and both client and server production builds.
+- The production site runs behind nginx on Debian 12 with Node.js 24.19.0. Authenticated coturn 4.17.2 serves public STUN and TURN/UDP+TCP on `turn.bonfire.icu:3478`; TURN/TLS is intentionally disabled.
+- HTTPS/WSS, the site gate and cookie, room/WebSocket authorization, certificate renewal, SQLite permissions and clean service restart are verified. Public Chromium relay-only connections passed bidirectional traffic over TURN/UDP and TURN/TCP.
+- Earlier Chromium 151 synthetic-media checks covered direct UDP media, offer/answer/create-offer recovery, signaling reconnect generation isolation, live video/audio source replacement, and the protected 390 px viewer flow.
+- In a real Chromium 151 one-to-three-viewer run, the host held exactly two connected outbound media peers. Viewer 1 held one inbound and one outbound peer and forwarded media to viewer 3; viewer 2 remained directly attached to the host. All three viewers decoded frames.
+- A Chromium 151 one-to-eight synthetic functional smoke formed two depth-four chains. The host held two connected outbound peers; viewers 1 through 6 each held one inbound and one outbound peer; viewers 7 and 8 were inbound-only leaves; all viewers decoded frames. This short smoke proves functional topology only, not 720p60 quality, resource cost, latency, or endurance.
+- Closing that first-level relay page caused its branch to reattach and decode again after about 5.3 seconds. The host's peak active connected outbound media-edge count remained two.
+- That recovery proves only the path where the server observes a page close immediately. A silent network partition depends on the 30-second heartbeat, so detection can take 30 to 60 seconds before the 5-second viewer grace begins; that path is unverified.
+
+## Unverified Boundaries
+
+- The peer-assisted mode has not completed 1/3/5/8-viewer 30-minute runs, relay CPU/GPU and generational-quality measurements, controlled loss/RTT tests, or depth-four latency gates.
+- Android Chrome and iOS Safari remain required leaves but are not verified for this topology. The protocol has no relay-capability bit; controlled join order is the only mobile-leaf enforcement, so arbitrary-user deployment is excluded.
+- Real screen/game audio, heterogeneous machines and networks, browser lifecycle behavior, and sustained 1080p60 or 720p60 performance remain unverified.
+- The first real protected room still needs room ID `1`, stop-and-republish, link reuse, and service-restart verification.
+- Shared browser encoding is not available. Encoded Transform, DataChannel/WebCodecs media, custom congestion control, multiple trees, relay scoring, and automatic SFU switching remain outside the spike.
+- Relay outbound diagnostics are visible, but relays still use a fixed `1080p60`/8 Mbps sender envelope instead of the host's selected profile. Profile propagation must be unified before quality or resource comparisons are valid.
## Next Milestone
-Preserve the first real room for the normal browser workflow, then verify room ID
-`1`, stop-and-republish waiting behavior, link reuse, and recovery after a service
-restart. In a separate PR and ADR, add a deployment-level `p2p|sfu` media mode
-using a single-node SFU; do not add automatic switching, hybrid sending, Redis,
-or multi-node infrastructure before measurements justify them.
+Complete only the bounded ADR-0004 experiment:
-Execute and record the manual browser/network matrix for both applicable modes:
+- preserve host fanout at two and viewer fanout at one across joins, reconnects, grace expiry, and reparenting;
+- propagate one room quality profile to host and relay senders before comparative media measurements;
+- run reproducible 1/3/5/8-viewer 720p60 measurements for topology depth, selected ICE path, host/relay upload, encode/decode work, first picture, decoded FPS, quality limitation, and glass-to-glass latency;
+- repeat first-level relay loss with server-observed close and separately measure silent heartbeat-detected partition recovery; and
+- verify current Chrome/Edge relays plus Android Chrome and iOS Safari leaves.
-- real screen/window capture and available game or system audio on Windows Chrome and Edge;
-- one broadcaster with 1, 3, 5, and 8 heterogeneous viewers, recording publisher upload and encode load plus server ingress and egress to locate each sustainable envelope;
-- same-LAN direct, cross-network direct, a forced-relay Screener media session, mixed direct/relay, and a UDP-blocked TURN/TCP path; test TURN/TLS separately only when deployed;
-- Android Chrome and iOS Safari playback, orientation, backgrounding, and network handoff;
-- actual codec implementation, encode load, publisher upload, bitrate, frame rate, first picture, and glass-to-glass latency. Custom dynamic-FPS logic remains intentionally unimplemented until these measurements show a gap in browser capture, encoding, and congestion behavior.
+For a disconnect immediately observed by the server, the recovery gate retains
+the default 5-second grace followed by at most 3 seconds to restore a decodable
+picture, about 8 seconds total. Silent partitions must be reported separately
+with their heartbeat-detection delay.
-## Current Blocker
+All gates fail closed. If success requires a custom browser media plane, changed
+RTP recovery, multiple trees, scoring, transcoding, a codec ladder, or more than
+two host edges, remove this experiment. Only an isolated re-encoding failure may
+advance to a separate native shared-encode and volunteer encoded-RTP proposal.
-- No infrastructure blocker remains for the current deployment. Persistent storage and systemd filesystem permissions are active; the first real browser room lifecycle and the separate P2P/SFU media matrix remain unverified.
+## Blockers And Decisions
-## Blocking Decisions
+No infrastructure blocker remains. Production adoption is blocked on the
+measurement matrix above, not implementation claims.
- Whole-system versus selected-game audio for the first release.
-- Initial deployment region and network test cohort.
-- Project license and intended distribution model.
+- Initial deployment region and network cohort.
+- Project license and distribution model.
+- Whether peer assistance passes every non-encoding gate; any other failure closes that route.
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 45242e22..a1d16a06 100644
--- "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
+++ "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
@@ -2,7 +2,7 @@
## 2026-08-18 14:45
-状态:已接受,可进入实现。本文约束首个可测 PoC,不代表全部 P0 已完成。
+状态:已接受的首个 PoC 基线。本文不接受后续媒体拓扑;peer-assisted 仅由 ADR-0004 提议为独立实验。
## 目标与边界
@@ -18,7 +18,7 @@
- 超过部署配置上限的观看者被明确拒绝,不静默超载;
- 在代码、测试和真实浏览器验证完成前,不宣称达到延迟或画质目标。
-本阶段不实现账号数据库、通用业务数据库、Redis、SFU、simulcast/SVC、观看者转发树、语音聊天、Electron、原生捕获、PWA、录制、遥测平台或多地区调度。唯一持久化例外是可选的 `node:sqlite` 房间身份表。
+本基线不实现账号数据库、通用业务数据库、Redis、SFU、simulcast/SVC、观看者转发树、语音聊天、Electron、原生捕获、PWA、录制、遥测平台或多地区调度。唯一持久化例外是可选的 `node:sqlite` 房间身份表。后续 SFU 与 peer-assisted 工作必须留在各自分支和 ADR 中,不能反向把实验复杂度预埋进该基线。
## 技术栈决策
@@ -188,6 +188,8 @@ TURN/TLS 是可选能力,不是生产启动门槛。启用时默认使用 RFC
- `/r/{code}` 观看者:主区域最大化远端视频;顶部显示房间与连接状态;提供声音、全屏和重试控制,不要求额外邀请码或 viewer token。
- 移动端:视频保持稳定宽高比,控制与状态移到视频下方,任何文字和按钮不得溢出或遮挡。
+用户可见的非直播状态只使用“已停止分享”(分享端已结束当前发布)和“等待开始分享”(观看端等待发布)。房间寿命、媒体代次、换父和恢复等内部状态不得作为额外产品文案暴露。
+
按钮使用 `lucide-react` 图标并提供可访问名称和 tooltip。动态状态区域固定最小尺寸,避免连接状态变化导致布局跳动。
## 安全与故障边界
@@ -231,7 +233,23 @@ TURN/TLS 是可选能力,不是生产启动门槛。启用时默认使用 RFC
4. 完成 TURN 短期凭据、ICE 配置刷新、连接恢复和 stats 面板。
5. 完成自动测试、真实浏览器烟测、部署说明、状态与记忆更新。
-任何一步只实现当前消费者需要的接口。不得为未来账号、SFU 或原生 sender 预建抽象层。
+任何一步只实现当前消费者需要的接口。不得为未来账号、第三种媒体拓扑或原生 sender 预建抽象层。
+
+## 2026-08-19 Peer-Assisted 实验边界
+
+状态:Proposed / Experiment Only。该扩展不改变上面的已部署 PoC,也不表示正式采用。
+
+新的产品硬目标是分享端任何时刻最多两条下游媒体边。首选顺序为一个或两个观看者直接 P2P,更多观看者尝试 peer-assisted,部署者仍可显式选择可选 SFU;这不是静默的房间内 P2P/SFU 迁移。
+
+实验只实现一个由服务端确定的广度优先拓扑:host 最多两个 child,每名 viewer 最多一个 child,因此形成两条按加入顺序平衡的 sticky 链。父节点只按深度和 `serverJoinSequence` 选择第一个空 slot。新 viewer 加入时不搬动已有节点;parent 离开时只把失去 parent 的 subtree root 重新分配到第一个空 slot,其 descendants 保持连接。该规则不采集或组合 RTT、带宽、CPU、地理位置与质量评分,也不主动重平衡。没有 parent 时明确等待或拒绝,不能创建分享端第三条边。
+
+所有边都继续使用标准 WebRTC。每名 viewer 播放收到的 remote `MediaStream`,并把其中的 remote tracks 加入给唯一 child 的新 `RTCPeerConnection`。该路径会逐跳解码和重编码;实验必须记录每层 encode time、CPU/GPU、`qualityLimitationReason`、帧率、分辨率和延迟,不能称为 zero-copy 或 shared encode。
+
+spike 复用现有 screen stream 和浏览器 codec 协商,覆盖当前桌面 Chrome/Edge relay、按测试顺序位于链尾的当前 Android Chrome 与 iOS Safari leaf、最多八名 viewer;捕获存在时沿同一标准 WebRTC 路径带上音频。Encoded Transform/DataChannel/WebCodecs 媒体、SVC/simulcast、多树、转码、codec ladder、综合评分、移动端后台 relay 和自动 SFU 迁移均不实现。验收与失败即放弃条件以 ADR-0004 为准;成功也只能触发新的生产 ADR。
+
+浏览器不保证多个 `RTCPeerConnection` 共享一次编码。实验允许 host 对一至两个 seed 各自编码;若未来正式采用,原生分享端必须用 shared encoder 将一份编码结果交给最多两套标准 WebRTC packetizer。该长期实现不在本 spike 中提前抽象。
+
+详细证据见 `docs/research/peer-assisted-media.md`,提案见 `docs/adr/0004-peer-assisted-media-experiment.md`。
## 官方与参考资料
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 8e4f2f3d..b05894c0 100644
--- "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"
+++ "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"
@@ -4,7 +4,7 @@
## 需求概述
-构建一个面向熟人游戏场景的低延迟屏幕共享工具。分享者可以在私密房间内分享游戏、应用窗口或显示器画面及声音,多名朋友可以即时观看。系统采用类似 Photon Host Mode 的产品抽象:中心服务负责房间、身份和建立连接,媒体默认通过 WebRTC 在客户端间 P2P 传输;STUN 协助打洞,直连失败的单条链路才使用 TURN。分享端 Web 优先并允许后续 Electron/原生增强;观看端必须可通过桌面或手机浏览器打开邀请链接,不绑定专用客户端。
+构建一个面向熟人游戏场景的低延迟屏幕共享工具。分享者可以在私密房间内分享游戏、应用窗口或显示器画面及声音,多名朋友可以即时观看。系统采用类似 Photon Host Mode 的产品抽象:中心服务负责房间、身份、确定性拓扑和建立连接,媒体偏好依次为小规模直接 P2P、实验性的 peer-assisted 转发、部署者显式选择的可选 SFU;STUN 协助打洞,直连失败的单条边才使用 TURN。该顺序不是静默运行时迁移许可。分享端 Web 优先并允许后续 Electron/原生增强;观看端必须可通过桌面或手机浏览器打开邀请链接,不绑定专用客户端。
当前 PoC 默认允许一名分享者和最多八名观看者,部署者可在 1 至 16 之间配置上限,超额观看者会被明确拒绝。八人只是当前容量默认值,不是已验证的性能承诺;真实 1:8 上行、编码和稳定性仍须测量。产品不承担公开直播或大规模观看,相关需求交给 OBS/Twitch 等成熟直播服务。
@@ -16,17 +16,21 @@
- [ ] 免安装观看:桌面和手机观看者可直接通过浏览器链接进入、授权并播放,不依赖与分享端相同的桌面客户端。
- [ ] 屏幕采集:分享者可主动选择显示器或应用窗口,开始、停止和切换分享状态。
- [ ] 游戏声音:Windows Chrome/Edge 目标环境可请求系统音频;没有返回音轨时必须明确提示,而不是静默无声。
-- [ ] 一对多观看:一名分享者可向配置允许的多名观看者发送画面,每名观看者拥有独立的 WebRTC 连接与状态;默认上限为 8,可配置范围为 1 至 16。
-- [ ] P2P 优先:ICE 必须先尝试直接 UDP 路径,服务器不得默认中转可直连的媒体。
-- [ ] NAT 兜底:每名观看者独立进行 ICE;生产环境必须提供 STUN、TURN/UDP 与 TURN/TCP candidates,通过优先级偏好直连和 UDP,同时允许无法使用 UDP 的网络选择 TCP,不能因为其网络与其他观看者不同而静默失败。
+- [ ] 一对多观看:一名分享者可向配置允许的多名观看者发送画面;默认上限为 8,可配置范围为 1 至 16。当前 PoC 的逐观看者连接是测量基线,不再是超过两名观看者时的目标拓扑。
+- [ ] 分享端 fanout 硬上限:分享端任何时刻最多维护两条下游媒体边,包括加入、断线、换父和恢复过程。第三名及后续观看者只能由通过验收的 peer-assisted 拓扑、部署者显式选择的可选 SFU 承载,或被明确拒绝;不能隐藏地回退为分享端第三条连接。
+- [ ] P2P 优先:每条逻辑媒体边的 ICE 必须先尝试直接 UDP 路径,服务器不得默认中转可直连的媒体。一个或两个观看者优先直接连接分享端;更多观看者的 peer-assisted 行为须先通过 ADR-0004 的实验门槛。
+- [ ] NAT 兜底:每条 parent-child 边独立进行 ICE;生产环境必须提供 STUN、TURN/UDP 与 TURN/TCP candidates,通过优先级偏好直连和 UDP,同时允许无法使用 UDP 的网络选择 TCP,不能因为某条边的网络与其他边不同而静默失败。
- [ ] 质量档位:至少提供 1080p60、720p60、720p30 三档目标,并依赖 WebRTC 拥塞控制及明确的手动档位避免持续排队;自定义动态 FPS 策略必须在统计证明有必要后再实现。
- [ ] 断线恢复:临时网络变化时尝试 ICE restart 和重连,并向用户显示当前连接状态。
- [ ] 可观测性:采集候选类型、RTT、丢包、抖动、实际码率、帧率、编码耗时和质量受限原因。
- [ ] 访问控制:部署者可配置一个全站 `ACCESS_PASSWORD`;为空时网站公开,非空值必须为 1 至 128 个可见 ASCII 字符。配置时分享者和观看者都必须先登录。登录成功签发 12 小时、无服务端会话状态的 HttpOnly、`SameSite=Strict` cookie,建房 HTTP 和 WebSocket 都只使用该 cookie,不提供建房 Bearer 旁路;不引入账号、JWT、服务端 session Map 或 logout。
-- [ ] 持久受保护房间:`ROOM_DATABASE_PATH` 可选且必须与 `ACCESS_PASSWORD` 同时配置。两者都存在时,SQLite 只持久保存从 `1` 开始自增的房间 ID 与 host token 摘要;房间及链接不设过期时间,停止分享只让观看页进入等待状态。密码模式不配置数据库时仍使用临时房间;公开模式始终使用随机临时房间。
+- [ ] 持久受保护房间:`ROOM_DATABASE_PATH` 可选且必须与 `ACCESS_PASSWORD` 同时配置。两者都存在时,SQLite 只持久保存从 `1` 开始自增的房间 ID 与 host token 摘要;房间及链接不设过期时间,停止后分享端显示“已停止分享”,观看页显示“等待开始分享”。密码模式不配置数据库时仍使用临时房间;公开模式始终使用随机临时房间。
### P1 - 重要功能
+- [ ] Peer-assisted 媒体实验:分享端最多两个 child、每名 viewer 最多一个 child;信令服务只按深度和服务端加入序号确定性地形成两条 sticky 平衡链,不加入综合评分或主动重平衡。每个 viewer 将收到的标准 remote track 通过新的 `RTCPeerConnection` 转发,因此会逐跳解码和重编码;必须测量而不能称为 shared encode。该功能在 ADR-0004 的实验门槛通过并由后续 ADR 正式接受前不得成为产品路径。
+- [ ] 原生 shared encode 分享端:长期产品若采用 peer-assisted,Electron/原生分享端必须保证一份兼容编码输出扇出到最多两套独立 WebRTC packetizer;浏览器不保证跨 `RTCPeerConnection` 复用编码器,因此纯 Web 分享端只能作为实验或便利回退,不能宣称满足 shared encode 保证。
+- [ ] 可选 SFU:部署者可显式选择单节点 SFU 来降低分享端上传;它保持非默认、可逆,并承担每名观看者的服务器出口成本。Draft PR #12 仍在评审,不能视为已合并、已部署或推荐路径。
- [ ] 分享端桌面封装:用 Electron 固定 Chromium 版本、改善选源/热键/系统音频体验,同时保留 Web 观看端。
- [ ] Windows 应用音频:仅捕获所选游戏及其子进程的音频,避免把语音聊天或通知声一并分享。
- [ ] 连接自检:在开始分享前验证信令、STUN、TURN/UDP、TURN/TCP 及部署实际配置的可选 TURN/TLS 可达性,并给出不暴露凭据的诊断结果。
@@ -44,11 +48,11 @@
- 性能:在 RTT 不高于 40 ms、丢包不高于 1% 的受控 P2P 路径中,玻璃到玻璃延迟目标为 p50 不高于 150 ms、p95 不高于 250 ms;区域 TURN/UDP 路径的 p95 目标不高于 350 ms。
- 启播:观看者请求观看后,除用户授权耗时外,3 秒内出现首帧。
- 流畅性:选择 60 fps 档位时,不能在没有降档或提示的情况下连续 5 秒低于 50 个解码帧每秒。
-- 成本:直连媒体不经过服务器;STUN 与信令仅承担小流量;TURN 的实际流量必须可计量、限额和告警。
+- 成本:除按边选择的 TURN 中继外,直连和 peer-assisted 媒体不经过应用服务器;STUN 与信令仅承担小流量;TURN 的实际流量必须可计量、限额和告警。Peer-assisted 只把约 `N * B` 的总观看流量分散到参与节点,不能宣称消除流量;SFU 则把该出口成本转移到服务器。
- 安全:应用控制面全程 HTTPS/WSS,媒体端到端链路使用 WebRTC DTLS-SRTP;普通 `turn:` over TCP 不额外套 TLS,但不移除媒体层加密。TURN 使用短期凭据、配额和速率限制;仓库不得包含真实密钥。
- 隐私:P2P 会向房间内好友暴露网络地址,首版威胁模型仅覆盖可信熟人;若要求隐藏 IP,必须切换为服务器转发。
- 可维护性:代码、需求、调研、项目记忆、`AGENTS.md` 和 `.codex/` 均在 Git 中跟踪;开发配置不得依赖单一操作系统的绝对路径。
-- 兼容性:分享端首个目标矩阵为 Windows 10/11 的当前 Chrome/Edge;观看端还必须覆盖当前 Android Chrome 和 iOS Safari,并实测自动播放限制、横竖屏、锁屏恢复与移动网络切换。
+- 兼容性:分享端首个目标矩阵为 Windows 10/11 的当前 Chrome/Edge;观看端还必须覆盖当前 Android Chrome 和 iOS Safari,并实测自动播放限制、横竖屏、锁屏恢复与移动网络切换。Peer-assisted 实验只允许能力完整的前台桌面 Chrome/Edge 作为 relay,手机必须保持 leaf。
## 边界与约束
@@ -58,7 +62,7 @@
- 默认八名观看者和可配置的 1 至 16 范围是接入容量边界,不承诺任意机器、档位或网络都能稳定承载该人数,也不承诺跨洲网络下的固定低延迟。
- 浏览器规范要求每次由用户主动选择分享源,权限不能永久保存;纯网页不能保证指定游戏窗口或始终获得系统音频。
- 1080p60 是能力目标,实际分辨率、帧率和硬件编码由浏览器、GPU、驱动、画面复杂度及网络共同决定。
-- 首版不实现 SFU,不从零实现编解码器或自定义 UDP 视频协议;产品范围以后改变时重新立项,而不是预留复杂框架。
+- 已部署首版仍是标准 WebRTC P2P。Peer-assisted spike 只复用标准 remote-track WebRTC,不加入 Encoded Transform/DataChannel/WebCodecs 媒体协议,也不自研 UDP、编解码器、拥塞控制、FEC/RTX、多树、转码、codec ladder 或综合评分器;需要其中任一项即放弃实验。SFU 只允许作为单独评审、显式配置的可选模式,不自动切换或双发。
- GPL/AGPL 项目在许可证策略确认前仅用于研究,不能直接复制到计划闭源的产品中。
## 验收标准
@@ -66,8 +70,8 @@
### 房间模式与生命周期
- Given `ACCESS_PASSWORD` 和 `ROOM_DATABASE_PATH` 都已配置,When 连续创建房间并重启应用,Then 房间码从 `1` 开始单调递增,已创建链接仍可加入,且 SQLite 的应用数据只包含房间 ID 与 host token 摘要。
-- Given 持久房间正在分享,When 分享者明确停止或捕获轨结束,Then 房间和链接保持有效,观看者进入等待状态;分享者重新发布后可继续在同一房间观看。
-- Given 分享期间只有 host 信令短暂断开,When 现有 P2P 媒体仍健康,Then 客户端继续播放媒体并恢复信令,而不是提前进入停止分享状态。
+- Given 持久房间正在分享,When 分享者明确停止或捕获轨结束,Then 房间和链接保持有效,分享端显示“已停止分享”,观看者显示“等待开始分享”;分享者重新发布后可继续在同一房间观看。
+- Given 分享期间只有 host 信令短暂断开,When 现有 P2P 媒体仍健康,Then 客户端继续播放媒体并恢复信令,而不是错误显示“已停止分享”。
- Given `ROOM_DATABASE_PATH` 已配置但 `ACCESS_PASSWORD` 为空,When 应用启动,Then 配置校验明确失败,不能在公开网站暴露可枚举的持久房间。
- Given `ROOM_DATABASE_PATH` 为空,When 创建房间,Then 无论是否启用全站密码都使用随机临时房间码并遵守 `ROOM_TTL_SECONDS`;停止分享本身不立即销毁房间。
@@ -86,7 +90,11 @@
### 一对多与带宽保护
-- Given 一名分享者和八名观看者,When 在受控网络中运行已记录的质量档位,Then 八名观看者可独立加入和离开,任一观看者离开不会中断其他连接,并记录每路码率、候选类型、编码负载和分享者总上行;该条在真实矩阵完成前保持未验收。
+- Given 一名分享者和一至两名观看者,When 运行直接 P2P,Then 分享端为每人建立独立媒体边且总 fanout 不超过二。
+- Given peer-assisted spike 分别运行 1、3、5、8 名观看者,When 用户加入、离开或 relay 失效,Then 服务端使用同一个确定性广度优先规则形成两条 sticky 链,只为新 viewer 或失去 parent 的 subtree root 分配 parent,不主动搬动其他节点;分享端在任何瞬间都不超过两个 child 且每名 viewer 不超过一个,没有可用 parent 时明确等待或拒绝,而不是增加分享端 fanout。
+- Given 一名分享者和八名观看者,When 在受控网络中运行已记录的质量档位,Then 记录每条边的拓扑深度、候选类型、码率、编码/解码负载、分享端与 relay 上行、首帧和玻璃到玻璃延迟;该条在真实矩阵完成前保持未验收。
+- 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 放弃并删除实验运行时代码,保留标准 P2P 和可选 SFU。
- Given 新观看者会使预计总上行超过安全预算,When 其请求加入,Then 系统自动降低档位、拒绝该档位或建议改用外部直播服务,而不是持续堆积发送队列。
### 质量和恢复
@@ -107,6 +115,6 @@
- 首批用户主要位于香港、内地还是跨地区;该信息决定 TURN 部署位置和测试矩阵。
- iOS Safari 与 Android Chrome 的最低版本及是否要求平板适配。
-详细技术证据、参考代码和难度评估见 `docs/research/webrtc-p2p-screen-sharing.md`。
+基础 WebRTC 证据与难度评估见 `docs/research/webrtc-p2p-screen-sharing.md`;peer-assisted、shared encode 和浏览器限制见 `docs/research/peer-assisted-media.md`。
---