Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
docs: simplify repository truth architecture (#295)
AAA3d960dc5bdc0
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.mdindex 2fec043c..362d1632 100644--- a/.github/pull_request_template.md+++ b/.github/pull_request_template.md@@ -8,13 +8,13 @@ List automated tests, manual checks, environments, and meaningful measurements.## Research And Decisions-Link the relevant requirement, research note, issue, and ADR, or explain why none is needed.+Link the relevant product owner, research note, issue, and ADR, or explain why none is needed.## Checklist- [ ] The branch contains one coherent change and no unrelated churn.- [ ] Required local tests and repository hygiene checks pass, and their exact evidence is listed above.- [ ] Security, privacy, compatibility, and licensing effects were considered.-- [ ] Requirements, operational docs, ADRs, project memory, and status were updated where their facts changed.+- [ ] Product owners, operational docs, ADRs, project memory, and status were updated only where their facts changed.- [ ] Stale or conflicting memory and documentation were removed rather than preserved as a diary.- [ ] No credentials, personal data, machine-specific paths, or required untracked artifacts are included.diff --git a/.github/workflows/repository-hygiene.yml b/.github/workflows/repository-hygiene.ymlindex 0dc0e331..8ea5660a 100644--- a/.github/workflows/repository-hygiene.yml+++ b/.github/workflows/repository-hygiene.yml@@ -1,6 +1,7 @@name: CIon:+ pull_request:push:branches:- main@@ -20,7 +21,7 @@ jobs:- name: Validate tracked project staterun: sh scripts/check-project-state.shenv:- SCREENER_BASE_SHA: ${{ github.event.before }}+ SCREENER_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }}- name: Set up Gouses: actions/setup-go@v6with:diff --git a/AGENTS.md b/AGENTS.mdindex d91fb71c..f6a69fb0 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,53 +1,84 @@# Project Instructions-## 1. Decision And Durable Truth--- Every task and action in this repository must follow the complete repo-tracked [`stop-that-shit` skill](./.agents/skills/stop-that-shit/SKILL.md). Read it before work; that file is the Screener authority for generic task boundaries, and any installed copy must stay synchronized with it rather than becoming a divergent variant.-- Core summary: within higher-priority instructions, the latest explicit user decision defines the task; take only requested actions and proven necessary consequences, and do not treat review/research/implementation as authority for implementation/deployment/cleanup beyond its task type. Broad words such as improve or optimize add no unnamed scope. Prefer standards and one owning invariant over example-specific mechanisms, while preserving unrelated work and necessary callers/tests/security. Reconstruct each deliverable from the accepted current result so it stands alone without rejected alternatives, process narration, or modification traces; inspect only the pending changes and report the result with completion evidence. The full skill governs when this summary is incomplete.-- Model recovery and failure handling from the smallest underlying authority and connection state. A concrete cause such as a graceful restart, crash, timeout, or network loss may improve diagnostics only when it changes a reachable decision; it must not create a parallel state, retry loop, fallback, or user-facing branch when the required recovery action is the same.-- Before a material product-contract, route-model, security, infrastructure, or irreversible change, settle the meaning against the whole product model and evidence, challenge contradictions or needless complexity, and update its single owning truth document. An ordinary scoped implementation or bug fix does not require a truth checkpoint unless it actually changes durable semantics or a current production/execution snapshot.-- Until the owner explicitly declares a public release, maintain only the current internal product contract. Do not preserve backward or forward compatibility, legacy wire/config aliases, dual parsers or writers, translators, deprecated APIs, migration shims, or tests whose only consumer is an older release. Upgrade the private deployment atomically, reject stale clients before authority, delete replaced surfaces, and use Git history for rollback. Reassess compatibility only when public release requirements are explicitly opened.-- Use the lean path by default for ordinary scoped work: inspect the affected code and owner, make the smallest change, run focused checks, inspect the diff, stage the requested files, and report. Do not automatically expand a small change into broad research, multiple truth-document edits, a full test suite, independent reviews, PR/merge, deployment, worktree cleanup, or a release postflight. Use the full integration/release path only when the owner explicitly asks for it or when closing a major phase or changing a public contract, route/security model, infrastructure, persistent/irreversible state, or release boundary.-- When durable semantics do change, update the single actual owner among requirement, design, ADR or research, and update `docs/project-memory.md` or `docs/status.md` only when its snapshot materially changes. Do not create parallel owners or mirror source details across documents. Ordinary UI details, self-evident code behavior, one-off fixes, routine validation, and completed history stay in code, tests, pull requests, and Git.-- If semantics remain disputed, record the hold in `docs/todo.md` and freeze only dependent work. Do not encode a guess as accepted truth.-- Queue new observations in their owner and continue the active milestone unless the user requests immediate investigation or the evidence reveals a P0 blocker.--## 2. Safety And Privacy--- Never commit credentials, TLS private keys, access tokens, or real user data. Commit only placeholder configuration and document local secret injection.-- Server-assisted media credentials are short-lived and narrowly authorized; rooms use authentication or unguessable expiring invitations. Do not log or persist private media-path identifiers beyond their accepted owner.-- Block the current phase on P0 security, privacy, authorization, irreversible-data, generation, bounded-resource, or rollback failures and on P1 failures of its core path.--## 3. Product Contract--- Build private, low-latency game screen sharing for one broadcaster and up to `20` authenticated Viewers, not a public or large-scale streaming service.-- A normal desktop or mobile browser is the initial Viewer target. A packaged sender or native capture helper is a later optimization.-- Keep media distributed and automatic. Central services own rooms, authentication, signaling, STUN, observability, and bounded fallback resources; do not silently make the product always-SFU.-- Ordinary peer ICE remains STUN-only and direct/peer UDP remains first; the only application fallback is the dedicated LiveKit SFU over UDP. Browser SFU publisher and subscriber PCs retain LiveKit-signaled UDP candidates but do not inherit external STUN/TURN ICE servers; deployment STUN remains available to ordinary peers and LiveKit server-side public-IP discovery. Screener configures no TURN, ICE/TCP, media TCP, or TLS-relayed media path. Every accepted path ends in bounded success or clear failure, and HTTPS/WSS transport is independent of media transport.-- Every non-server endpoint uses one server-authoritative steady outbound media-copy cap: default `2`, configurable as `1`, `2`, or `3`. A peer child or the Host's single SFU publication consumes one slot; upstream receive is free, and SFU subscriber egress is accounted at the server. Browser role, UA, visibility, and client advertisement do not create another tier.-- The accepted route model is one committed graph, one event-driven reconciliation loop, and at most one room-serial child operation. That operation owns one deterministic candidate list/cursor, one current candidate with its reservations, one route-demand owner, and one total deadline; its exact media child commits on the first newly decoded frame. Exact direct transport-connected progress may keep the current candidate until that total deadline but cannot commit or change the graph. Join/waiting, child reparent, relay ingress repair with subtree retention, confirmed departure, and effective-capacity reduction all use this operation. Initial acquisition gives direct candidates one bounded foreground window, then uses SFU for availability while any remaining direct candidates converge behind working media; a failed exact candidate is tried only for that operation and creates no persistent parent blacklist.-- WebRTC and LiveKit own ICE/DTLS/consent, congestion control, transient reconnect, and SFU stream state. Screener does not add all-pairs endpoint probing, parent-wide quality inference, a weighted route score, periodic rebalancing, or an independent depth cap. SFU is one Host publication with per-Viewer subscriptions, and endpoint overlap plus SFU resources remain independently admitted and bounded. Any future strict-firewall transport must be accepted as a LiveKit-internal capability from real evidence, not added as another application route candidate.-- WebRTC and LiveKit also own media-quality adaptation, bandwidth estimation, representation/layer selection, and recovery. Screener may express standard content intent, user-selected ceilings, codec choice, and documented component options, but it does not invent or maintain an application resolution/FPS/bitrate ladder, representation formula, quality score, hysteresis loop, periodic media controller, or manual SFU selector. Browser game-screen video uses the standard `contentHint = "motion"`; do not silently unset it or replace native adaptation unless the owner explicitly accepts a primary-source-supported mature alternative. Prefer pinned component defaults over hand-built SFU layers.--## 4. Canonical Repository And Integration--- Keep the canonical repository root on a clean, current `main` at audit and integration boundaries. Create branches and worktrees from that exact commit; an auxiliary worktree or old branch is never a truth source.-- Merge an accepted truth checkpoint before integrating dependent candidates. Rebase or rebuild each retained candidate from that exact `main` once, preserve main's owning truth on conflicts, and transplant only approved scoped code, tests, and new facts.-- Routine application-only releases verify a new immutable artifact, switch to it atomically, and guarantee the pre-cutover application release only through bounded health and postflight checks; it has no retention contract afterward and is not a maintained backup. A task that changes infrastructure, configuration, secrets, persistent state, or an irreversible surface must define recovery for only those touched surfaces before changing them.-- Cleanup is last. Preserve user work and verify integration, open references, branch equivalence, and link/reparse safety before removing a worktree or branch.-- Follow `CONTRIBUTING.md` for branch, research, validation, PR, merge, cleanup, and local-hook details.--## 5. Truth Map--- Start substantial work by reading `docs/project-memory.md`, `docs/status.md`, `docs/todo.md`, the relevant requirement/design, ADR, and research documents, then inspect the current branch and Git state.-- Current requirements and design live in `docs/需求理解.md` and `docs/方案设计.md`; decisions live in `docs/adr/`; evidence lives in `docs/research/`.-- `docs/project-memory.md` is the durable product snapshot, `docs/status.md` is the current execution/deployment index, and `docs/todo.md` is the only current work ledger. Git history owns the completed timeline.-- Give each durable fact one owner and replace stale text in place. Long-lived documents record product contracts, non-obvious invariants, algorithms/models, key tradeoffs, external evidence, and current execution boundaries; ordinary UI, self-evident implementation, routine validation process, and completed history stay in code, tests, pull requests, and Git. Keep status as an index rather than an archive, and update `docs/README.md` when documents move or change status.--## 6. Engineering Defaults--- Research non-trivial design, implementation, and bug fixes from current primary sources. Record durable findings and license boundaries under `docs/research/`.-- Add focused tests in proportion to the changed risk. Full-suite tests, independent review, expensive browser/network/endurance checks, and deployment validation belong at an explicitly requested or major acceptance boundary; use reproducible WebRTC measurements for performance claims.-- Keep scripts and hooks deterministic, fast, cross-platform, and CI-runnable.-- Support Windows, macOS, and Linux; avoid absolute paths and OS-specific separators. Text files use LF, and new filenames use ASCII unless an established user-facing convention requires otherwise.-- Before finishing material work, inspect Git status, report untracked project artifacts, and stage requested files unless told otherwise.+## Authority And Scope++- Read and follow the complete repo-tracked+ [`stop-that-shit` skill](./.agents/skills/stop-that-shit/SKILL.md) before work.+ It is the generic authority for scope, smallest-correct-result, and clean+ delivery; installed copies must remain synchronized with it.+- Within higher-priority instructions, the latest explicit user decision defines+ the task. Review, research, implementation, deployment, and cleanup grant only+ the authority inherent in that task type.+- Model recovery from the smallest underlying authority and connection state.+ Restart, crash, timeout, and network loss do not justify parallel states or+ case-specific fallbacks when their required action is the same.+- Ordinary scoped work uses the lean path: inspect the affected owner and code,+ make the smallest coherent change, run focused checks, inspect the diff, and+ stage the requested files. Use the full integration/release path only for an+ explicitly requested release or a material contract, route/security,+ infrastructure, persistence, or irreversible change.+- Until a public release is explicitly declared, keep one current internal+ contract. Delete replaced wire/config/API surfaces; do not add compatibility+ aliases, dual readers/writers, migrations, or tests for stale private clients.++## Product Contract++- Screener is private game screen sharing for one Host and up to 20 authenticated+ Viewers, with Web Host/Viewer/relay as the current product surface.+- Current product truth is split by owner:+ [rooms/access](./docs/product/rooms-access.md),+ [routing/transport](./docs/product/routing-transport.md),+ [media quality](./docs/product/media-quality.md), and+ [presentation/lifecycle](./docs/product/presentation-lifecycle.md).+- Media stays automatic and P2P-first; central services provide room authority,+ signaling, STUN, observability, and bounded LiveKit SFU/UDP fallback. Route+ changes must preserve the single-graph, single-operation model in+ [ADR-0005](./docs/adr/0005-automatic-hybrid-media-routing.md).+- WebRTC and LiveKit own network and media adaptation. Do not add custom quality+ scores, ladders, all-pairs probes, periodic rebalancing, or hand-built SFU+ representations without a new accepted decision backed by primary evidence.++## Durable Truth++- Start substantial work by reading [project memory](./docs/project-memory.md),+ [status](./docs/status.md), [TODO](./docs/todo.md), and only the relevant+ product module, ADR, research, or operations document. Then inspect branch,+ HEAD, status, staged diff, and worktrees.+- Product modules own current behavior; ADRs own non-obvious decisions and+ consequences; research owns evidence and license boundaries; deployment owns+ operational reference. Status is the current execution/deployment index, TODO+ is the only work ledger, and Git/PRs own completed history.+- Give every durable fact one owner. Update memory or status only when its compact+ snapshot materially changes. Ordinary UI detail, protocol field listings,+ self-evident code, test inventories, routine validation, and agent process do+ not belong in long-lived product truth.+- If semantics remain disputed, record the hold in TODO and freeze only dependent+ work. Never encode a guess as accepted truth.++## Safety++- Never commit credentials, TLS private keys, raw access tokens, or real user+ data. Commit placeholders and document local secret injection.+- Keep media credentials short-lived and narrowly authorized. Do not log or+ persist private media-path identifiers beyond their accepted owner.+- Block the current phase on P0 security, privacy, authorization, irreversible-+ data, generation, bounded-resource, or rollback failure, and on P1 failure of+ that phase's core path.++## Repository And Delivery++- Canonical root must be clean current `main` at audit/integration boundaries.+ Create branches/worktrees from that exact commit; old branches and worktrees+ are never truth sources.+- Preserve user work. Branch, truth-checkpoint, PR, release, recovery, and+ cleanup rules are owned by [CONTRIBUTING.md](./CONTRIBUTING.md); do not mirror+ that workflow here.++## Engineering Defaults++- Use primary sources for non-trivial design and bugs. Add focused tests in+ proportion to risk; batch full browser/network/endurance checks at acceptance.+- Keep scripts deterministic, fast, cross-platform, and CI-runnable. Support+ Windows, macOS, and Linux; use LF and ASCII filenames for new files.+- Before finishing material work, inspect status, report untracked artifacts,+ and stage requested files unless told otherwise.diff --git a/README.md b/README.mdindex 20c46753..3ad1da92 100644--- a/README.md+++ b/README.md@@ -1,12 +1,15 @@# Screener-Screener is a private, low-latency screen-sharing project for one game player and a small group of friends. Its accepted media target is WebRTC P2P-first, with a dedicated LiveKit SFU/UDP virtual parent feeding only the necessary roots when direct/STUN peer paths cannot serve them. Roots continue distributing to bounded peer descendants; this is not an always-SFU conferencing design. Viewers should be able to join from a desktop or mobile browser without installing the sender application.+Screener is a private, low-latency screen-sharing tool for one game player and+up to 20 authenticated friends. Web Viewers need no installation. Media is+automatic and P2P-first, with bounded Browser relay and one dedicated LiveKit+SFU/UDP fallback rather than an always-SFU conference topology.-The first measurable Web proof of concept is implemented. A host captures a screen, window, or browser tab and shares a random four-digit room code plus an independent fragment invitation. During a share, the host can change between three ceiling profiles without reopening the source picker, pause, and switch sources. Browser video is fixed VP8 and leaves the video content hint unset. Code-only entry defaults to `open` after site access; the only other state is `private`, which is invitation-only without a room password and also permits matching code-and-password entry when one is configured. A valid grant enters directly in either state. Rooms are process-memory state with a configurable dormant lease and disappear on restart. Lightweight deployments may keep independent direct WebRTC connections. The flagship deployment enables the all-room controller with bounded peer descendants and one LiveKit Host publication serving admitted Viewer subscriptions. Production admits 20 viewers; that admission limit is not a performance promise.+[Project memory](./docs/project-memory.md) is the compact product map.+[Current status](./docs/status.md) owns the exact source and production state;+this README intentionally does not mirror release details.-This is not yet a broadly validated product release; [Current status](./docs/status.md) owns the deployed revision and validation evidence. The deployed flagship boundary is the all-room bounded peer/SFU-UDP controller plus the memory-resident room/access model on `screener-v12`, with ordinary peer ICE kept STUN-only and no TURN or TCP media route. The optional Windows native sender remains source-only and is not a production runtime. Mobile devices are Web viewers only; ordinary Android and iOS browsers do not expose reliable screen capture for a Web Host. Real cross-network SFU media, game audio, a sustained public-network 1:20 session, mobile browser lifecycle behavior, and latency targets still require the documented manual test matrix.--## Run locally+## Local DevelopmentNode.js 24 and npm 11 are required.@@ -15,38 +18,29 @@ npm cinpm run dev```-Production requires an independent 8-128 byte visible-ASCII `SITE_ACCESS_PASSWORD`. It protects room creation, Host role, and code-only Viewer entry. A valid room-scoped fragment grant enters directly without it; otherwise code-only entry needs site access before the room's `open | private` policy is evaluated. Local development and tests may leave it empty.--Open `http://localhost:8787`. The server listens on `0.0.0.0` by default so a-phone on the same LAN can load `http://<computer-lan-ip>:8787`. To generate an-invite that the phone can open while the host keeps using secure-context-`localhost` capture, set `PUBLIC_BASE_URL` to that LAN URL and include both-origins in `ALLOWED_ORIGINS`. LAN viewers can join over HTTP; the sharing page-must remain on `localhost` or HTTPS because screen capture requires a secure-context. The local default has no STUN, so cross-network use still requires-HTTPS and the production ICE configuration documented separately.+Open `http://localhost:8787`. The development server listens on `0.0.0.0`, so a+phone on the same LAN may use `http://<computer-lan-ip>:8787`. Screen capture+must remain on `localhost` or HTTPS. Set `PUBLIC_BASE_URL` and+`ALLOWED_ORIGINS` when generated invitations need a different LAN origin.-`SITE_ACCESS_PASSWORD` supplies site access; valid room fragment grants bypass-that gate only for the exact Viewer role, while code-only entry requires site-access before code policy is evaluated. Ordinary ICE contains only self-hosted-STUN. LiveKit supplies bounded SFU/UDP subscriptions when direct/peer paths-cannot serve an edge; Screener configures no TURN or TCP media route. HTTPS/WSS-remains TLS/TCP independently.+Production requires an independent visible-ASCII `SITE_ACCESS_PASSWORD`; local+development and tests may leave it empty. Cross-network setup is documented in+[self-hosting](./docs/operations/self-hosting.md) and+[configuration reference](./docs/reference/configuration.md). Never commit real+credentials.-Run the complete automated validation with:+Run complete automated validation with:```shnpm run check```-Start here:--- [Requirements](./docs/需求理解.md)-- [WebRTC PoC design](./docs/方案设计.md)-- [Deployment and media transport](./docs/deployment.md)-- [Feasibility research](./docs/research/webrtc-p2p-screen-sharing.md)-- [Current project memory](./docs/project-memory.md)-- [Current status](./docs/status.md)-- [Architecture decision](./docs/adr/0001-p2p-first-media-topology.md)-- [Contributing and Git workflow](./CONTRIBUTING.md)-- [Documentation index](./docs/README.md)+## Documentation++- [Product and repository map](./docs/README.md)+- [Rooms and access](./docs/product/rooms-access.md)+- [Routing and transport](./docs/product/routing-transport.md)+- [Capture and media quality](./docs/product/media-quality.md)+- [Presentation and lifecycle](./docs/product/presentation-lifecycle.md)+- [Current work](./docs/todo.md)+- [Contributing workflow](./CONTRIBUTING.md)diff --git a/deploy/systemd/screener.service.example b/deploy/systemd/screener.service.exampleindex 5a4c5513..425ab614 100644--- a/deploy/systemd/screener.service.example+++ b/deploy/systemd/screener.service.example@@ -15,6 +15,8 @@ Restart=on-failureRestartSec=3sTimeoutStopSec=20sUMask=0077+StateDirectory=screener+StateDirectoryMode=0700NoNewPrivileges=truePrivateDevices=truediff --git a/docs/README.md b/docs/README.mdindex 2a83736a..a69c231b 100644--- a/docs/README.md+++ b/docs/README.md@@ -1,34 +1,72 @@-# Project Documentation--- [需求理解](./需求理解.md): current product scope, priorities, constraints, and acceptance criteria.-- [方案设计](./方案设计.md): accepted implementation design; unfinished release and validation work is tracked in the current TODO ledger.-- [Project memory](./project-memory.md): durable current product and source snapshot to read at the start of future work.-- [Current status](./status.md): bounded current/index snapshot of production, active milestones, decisions, blockers, and links to detail.-- [Verification status](./verification-status.md): exact integrated/deployed gates, current production evidence, open physical proof boundaries, and expensive-test applicability.-- [Session handoff](./session-handoff.md): temporary bootstrap prompt that points a new session back to the canonical truth owners.-- [Current TODO](./todo.md): unresolved work, active truth holds, and decisions that still require user confirmation.-- [Deployment](./deployment.md): exact current production, immutable release operations, scoped recovery rules, and transport evidence boundaries.-- [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, deterministic sticky topology, exact-route implementation evidence, and remaining physical gates.-- [Low-server-cost media routes](./research/low-server-media-routes.md): Host-publication/SFU distribution, route diagnostics, direct-to-SFU conclusion, hop-level accounting, privacy-safe ICE evidence, and bounded transport gates.-- [Built-in peer ICE TURN candidate](./research/built-in-peer-ice-turn.md): historical evidence for the rejected participant-wide and selected-edge TURN candidates.-- [Advanced peer distribution](./research/advanced-peer-distribution.md): generic local-reconcile evidence plus multi-tree/SVC, encoded-object relay, native RTP forwarding, FEC/network-coding, and MoQ gates.-- [Native shared-encode sender](./research/native-shared-encode-sender.md): consolidated Draft #16/#18/#22/#23/#25/#28 ladder, unclassified product-gate failure, staged revalidation, and stop line.-- [Native H.264 hardware decision](./research/native-h264-hardware-decision.md): bounded WebCodecs no-go, proved Media Foundation/NVIDIA hardware encode, the default-fmtp `42c01f` stop, and the retained interop boundary.-- [Native H.264 opt-in path](./research/native-h264-opt-in-path.md): explicit H.264 sender mode, exact Pion profile registration, and one bounded Host/Viewer loopback with hardware caveats.-- [Realtime quality adaptation](./research/realtime-quality-adaptation.md): Browser codec and `motion` evidence, manual quality ceilings, path-quality authority, and LiveKit-owned SFU representation adaptation.-- [Cross-restart room recovery](./research/cross-restart-room-recovery.md): room-authority lineage, optional SQLite stable mode, invitation continuity, and process-fresh media rebuild evidence.-- [Browser background capture diagnostics](./research/browser-background-capture.md): browser lifecycle evidence, a privacy-bounded capture/send/receive experiment, interpretation gates, and non-goal keepalive mechanisms.-- [Browser screen-audio quality](./research/browser-screen-audio-quality.md): capture/source compatibility, live sender-ceiling readback, Opus negotiation boundaries, and remaining audible/device evidence.-- [Display name and presence boundaries](./research/display-name-presence.md): browser-local storage failure behavior, Unicode normalization, control-character policy, and the Web-only presence capability boundary.-- [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): historical P2P-first baseline; later access and automatic-routing decisions supersede its stale current-state details.-- [ADR-0002](./adr/0002-memory-resident-protected-rooms.md): four-digit leased room authority with lightweight memory and optional SQLite stable modes, local Host defaults, scoped Viewer grants, and explicit room replacement.-- [ADR-0004](./adr/0004-peer-assisted-media-experiment.md): historical standard-WebRTC peer-assisted experiment and reusable evidence.-- [ADR-0005](./adr/0005-automatic-hybrid-media-routing.md): accepted P2P-first single-reconcile route model, including deployed Browser SFU ICE-server isolation; remaining real-network validation is tracked in verification status.-- [ADR-0006](./adr/0006-fixed-high-native-sender-canary.md): proposed fixed-`HIGH` native canary, current no-go result, and staged revalidation boundary.-- [ADR-0007](./adr/0007-path-isolated-representation-quality.md): accepted LiveKit-owned SFU representation adaptation, pinned evidence, and application-controller/SVC boundaries.-- [ADR-0008](./adr/0008-window-scoped-audio-capture.md): browser window-audio hint and the Windows WASAPI process-loopback boundary.--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.+# Documentation Map++Start with [project memory](./project-memory.md), [status](./status.md), and+[TODO](./todo.md). Read only the product, decision, evidence, or operations file+needed for the current task.++## Current Product++- [Rooms and access](./product/rooms-access.md)+- [Routing and transport](./product/routing-transport.md)+- [Capture, audio, and media quality](./product/media-quality.md)+- [Presentation and lifecycle](./product/presentation-lifecycle.md)++These four modules own current product behavior. Source code and tests own+ordinary implementation and UI detail.++## Current Indexes And Operations++- [Project memory](./project-memory.md): compact cross-domain map and invariants.+- [Status](./status.md): exact current source, production, milestone, and holds.+- [TODO](./todo.md): the only current work ledger.+- [Verification](./verification-status.md): open physical evidence and expensive+ gate applicability.+- [Deployment](./deployment.md): immutable application release and recovery.+- [Self-hosting](./operations/self-hosting.md): initial services, topology, and+ operational verification.+- [Configuration](./reference/configuration.md): environment, secrets, bounds,+ and ports.+- [Maintenance](./maintenance.md): truth ownership, context, and repository+ lifecycle.++## Decisions++- [ADR-0001](./adr/0001-p2p-first-media-topology.md): initial P2P-first+ baseline.+- [ADR-0002](./adr/0002-memory-resident-protected-rooms.md): room authority and+ optional SQLite stability.+- [ADR-0004](./adr/0004-peer-assisted-media-experiment.md): Browser relay+ experiment.+- [ADR-0005](./adr/0005-automatic-hybrid-media-routing.md): current automatic+ route and SFU resource model.+- [ADR-0006](./adr/0006-fixed-high-native-sender-canary.md): native sender+ canary stop line.+- [ADR-0007](./adr/0007-path-isolated-representation-quality.md): framework-+ owned media adaptation.+- [ADR-0008](./adr/0008-window-scoped-audio-capture.md): Browser/native window+ audio boundary.++## Evidence++Routing and transport:++- [WebRTC feasibility](./research/webrtc-p2p-screen-sharing.md)+- [Browser peer relay](./research/peer-assisted-media.md)+- [Low-server-cost routes](./research/low-server-media-routes.md)+- [Advanced distribution alternatives](./research/advanced-peer-distribution.md)++Media and platform:++- [Realtime quality and codecs](./research/realtime-quality-adaptation.md)+- [Browser background capture](./research/browser-background-capture.md)+- [Browser screen audio](./research/browser-screen-audio-quality.md)+- [Native sender and shared encode](./research/native-sender.md)++Rooms and repository practice:++- [Cross-restart room recovery](./research/cross-restart-room-recovery.md)+- [Agent context governance](./research/agent-context-governance.md)++Research records verified facts, measurements, assumptions, licenses, and+remaining evidence boundaries. It does not own current product behavior or work+priority.diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.mdindex 5a7cfbb4..b7ec3b7b 100644--- a/docs/adr/0005-automatic-hybrid-media-routing.md+++ b/docs/adr/0005-automatic-hybrid-media-routing.md@@ -1,535 +1,221 @@# ADR-0005: Automatic Hybrid Media Routing-- Status: Base routing and the evidence-only quality shadow are deployed on- strict v13. Exact current identity is owned by- [status](../status.md).+- Status: accepted; base route and evidence-only quality shadow deployed- Date: 2026-08-20- Last updated: 2026-08-27## Context-Screener serves one broadcaster and a small group of trusted viewers. Direct-browser WebRTC gives the desired latency and avoids central media cost, but a-single Host cannot safely fan out to every Viewer and some networks cannot-establish a usable peer path.+Direct Browser WebRTC gives Screener its desired latency and distributed cost,+but one Host cannot fan out to every Viewer and some endpoint pairs cannot+establish usable direct media. The product needs automatic peer distribution and+bounded server fallback without exposing topology choices to users or turning+every room into an SFU conference.-The product therefore needs one automatic route controller. Users do not choose-or understand the topology. The controller may use peers and bounded-server-assisted resources, but it must keep the ordinary media graph-distributed, deterministic, authorized, and recoverable.--This ADR records the accepted invariants and the complete assisted-route model.+This decision owns the route controller and resource model. The observable+product contract is [routing and transport](../product/routing-transport.md);+physical evidence is in the routing research documents.## Decision-### Endpoint capacity--Every non-server endpoint uses the same server-authoritative downstream media-capacity:--- the deployment default is `2`;-- the only accepted static values are `1`, `2`, and `3`;-- an upstream receive edge does not consume this downstream budget;-- role, browser, user agent, device class, and page visibility do not create a- different release tier;-- a connected endpoint's server-authoritative effective downstream capacity is- the deployment value clamped by its current `0..C` availability advertisement;- `0` means it currently accepts no downstream child and does not create another- release tier; and-- one named configuration value and one shared implementation boundary own the- policy. Route code must not repeat literal policy numbers.--The server returns the final deployment value as-`authenticated.endpointMediaCopyCapacity` on every successful signaling-authentication. Browser Host and Viewer clients validate `1..3` and use the-same value for authoritative child assignments and physical sender slots. Room-`maxViewers` is a separate participant-admission limit and never supplies a-sender budget. A missing or invalid capacity, old wire, or executable sender-fails before route authority is accepted.--Without the peer-assisted controller, signaling still admits at most that many-active Host children per room. Excess admitted Viewers wait without an-authorized media edge and are promoted in stable join order when a slot is-released; offer, answer, candidate, and restart routing is limited to the active-set.--Capacity counts active outbound media copies produced by a non-server endpoint:-an ordinary peer child consumes one slot and the Host's single SFU publication-consumes one Host slot. An upstream receive edge is free. A parallel-media-producing candidate requires a separately reserved transition slot. SFU-subscriptions consume server egress, not endpoint capacity.--### Active topology--The server owns one versioned route assignment per room. At every committed-revision:--- the Host has no upstream;-- each Viewer has exactly zero or one active upstream;-- the active media graph is acyclic;-- every non-server endpoint stays within its steady sender capacity or one- explicitly reserved transition-overlap slot;-- every active Viewer is source-reachable through peer edges or the current- authoritative Host publication;-- healthy unaffected branches remain sticky; and-- admission or recovery ends in a valid assignment, an explicit wait, or a- bounded failure.--Direct or peer UDP remains the first media choice. Ordinary peer-`RTCPeerConnection` instances receive STUN candidates only. The sole-application fallback is the dedicated LiveKit SFU over UDP; Screener configures-no TURN, ICE/TCP, media TCP, or TLS-relayed media. HTTPS and WSS continue to use-TLS/TCP independently of media transport.--Routing is event-driven. Join, capacity release or reduction, endpoint departure,-current-edge hard failure, and a non-paused decoded-frame stall wake the same-reconciliation loop. The controller otherwise leaves the room unchanged.--Parent selection is deterministic and local. The controller first filters on-current authority, source reachability, acyclicity, effective downstream-capacity, sender reservations, candidate tuples already tried by the current-operation, and server admission.-It then-orders eligible parents lexicographically by the shallowest resulting depth,-the greatest remaining steady sender capacity, a stable child-parent hash,-join order, and peer identity. The pairwise hash distributes otherwise equal-first choices without weakening capacity authority. It prepares one candidate at a time. The candidate's standard ICE-checklist proves transport connectivity; the exact candidate child's first new-decoded video frame is the application media-ready event. Raw addresses, a-claimed NAT class, geography, user agent, or a-weighted room-wide score never choose a parent. A failed candidate releases its-reservation before the next candidate is attempted. The first candidate that-reaches the media-usable floor commits; otherwise the loop reaches the next-candidate, an explicit wait, or bounded failure. A failed edge seeds its tuple-only into the operation opened by that fact version; a later external fact may-make the tuple eligible again. Exhaustion retires an edge that is hard-invalid,-attached to a confirmed-departed parent, or outside current effective capacity,-so blocked state never hides a physical copy or server resource. A healthy edge-used only for SFU bootstrap remains committed if bootstrap cannot start.--There is no independent maximum-depth policy. Acyclicity and room admission-bound the graph, while shallowest-first ordering minimizes depth. If a departed-Host root releases a Host slot, a new or orphaned child therefore prefers that-shallower Host result over another root's deeper slot. Healthy committed edges-remain sticky; the controller does not periodically rebalance the graph. Depth-remains an observed acceptance metric.--A candidate identity is one logical upstream path. An operation opened by a-failed edge seeds that exact current candidate as already tried, so the same-parent cannot immediately repeat. A new external fact may make the old-candidate eligible again; failure does not globally exclude that parent.--Foreground availability and direct convergence have separate priorities but-use the same controller and candidate transaction. Route acquisition gives the-best eligible direct parent one five-second head start before SFU. An exact hard-failure may advance another direct candidate inside that same window, but the-window never resets. If that exact direct candidate reports standard WebRTC-transport `connected`, the controller keeps it until the operation deadline;-this is progress only and cannot commit a route. Reaching the foreground-boundary without that progress defers the unresolved direct candidate rather-than declaring it failed, then starts SFU. A Viewer that-committed SFU retains that healthy route while the controller later tries its-remaining direct parents, one exact candidate at a time and round-robin across-SFU Viewers after each consumed candidate. Newly unrouted or repairing Viewers-always preempt this background direct work. The first direct-candidate that proves a decoded frame replaces SFU make-before-break; exhausting-the finite parent list simply keeps SFU. A candidate that would require a-bounded-gap cutover is skipped because background convergence may not interrupt-current media. This is event-driven route convergence, not periodic rebalancing-or quality-based switching.--If an SFU subscription is needed while the Host has no publication and all Host-slots are occupied, the controller retains one bounded bootstrap intent: the-original demand and session, plus the finite Host direct children already tried-as carriers. Each carrier uses the ordinary child-operation and must fit in the existing overlap allowance; a transition that-would first cut a healthy carrier is ineligible. Carrier failure leaves that-carrier's committed route intact and advances the intent. Exhausting all safe-carriers fails the waiting demands for that fact, never the healthy carriers.-On success, the original demand tries the new publication before its eligible-direct candidates; after its first decoded SFU frame those direct candidates-resume as background convergence. A new external fact may rebuild the finite carrier-list. This intent is part of the same controller and owns no second graph,-concurrent route operation, or independent timer.--### Authorization and transition--Every prepare, signal, recovery, commit, and rollback is bound to the-authenticated room and endpoint sessions, current share generation, base route-revision, and unique pending revision. Connection identity fences the candidate-PeerConnection, and publication generation remains owned by the SFU resource-lifecycle.-A single pending child-operation object aggregates these bindings, its exact-media child and route-demand owner, the deterministic candidate list and cursor,-its current candidate and reservations, and one deadline. Candidate failure-advances only that exact cursor entry.-Initial availability keeps one bounded direct window before SFU. Background-direct convergence uses the operation's full deadline for each remaining exact parent;-its finite tried set survives between attempts, rotates to the next SFU Viewer-after a consumed candidate, and a higher-priority route demand aborts the-current attempt without marking the parent failed. These-fields do not create another graph, concurrent pending route revision, periodic-timer, assignment generation, or all-pairs probe.-A `prepare` route update names that operation's exact child, route kind, and-server-issued candidate connection identity. Parent and child therefore-prepare the same connection; neither endpoint infers candidate authority from-an assignment-list difference. The candidate child may report one exact-transport-connected progress event fenced by the same revision and connection;-only its later decoded-frame ready event can commit.-The accepted Browser runtime contract uses the single `screener-v13` wire. On each WebSocket, the-server sends the exact prepare before its SFU configuration; the candidate child-is queued before a peer parent is allowed to start its offer. WebSocket ordering-is the companion-delivery contract, so clients keep no reordering inbox.-Duplicate current companions are idempotent and stale ones are ignored. Every-other wire and executable sender fails the protocol boundary before room-authority rather than receiving a compatibility path.-A stale or mismatched asynchronous result fails closed and cannot revive an old-edge.-Successful candidate `P` is broadcast as active revision `P`. Failure, timeout,-or authoritative abort keeps the previous committed graph content but advances-and broadcasts one active rollback revision `R > P` before any later prepare;-clients never infer rollback from silence or from an older revision.-One room-wide monotonic allocator owns active, prepare, rollback, retirement,-and prune revisions. A direct peer transport may adopt a fresh WebRTC connection-identity during its framework-owned rebuild only for the exact current-parent/child sessions; that identity update does not change topology.--A route replacement uses make-before-break only when the typed endpoint and-server-resource ledger atomically admits the required reservations. The old-route remains authoritative until the exact candidate child decodes its first-new video frame. ICE `connected` alone is insufficient. Commit promotes that-exact candidate-atomically; timeout, failure, stale identity, or revoked authority destroys it,-releases reservations idempotently, and keeps or restores the previous valid-route. The exact media-ready call synchronously commits typed admission before-graph promotion; a failed admission commit follows the ordinary candidate-failure path. Commit releases the resource-set difference plus the overlap-slot, and room stop/delete returns every current and committed resource through-one dispose operation. When a full sender has no overlap slot, server resources-are preflighted before one explicit bounded-gap cutover. Retirement keeps the-same total deadline, replans the untried tuple suffix against the new graph, and-appends one ordinary restore candidate when it cut a healthy logical edge.-There is no fourth endpoint copy and no separate restore state machine.--Recovery attempts are finite, generation-bound, and stop after success. The-controller must not turn a rare failure into an unbounded retry loop, unaccounted-server fanout, or an untracked parallel route.--## Accepted Assisted-Route Model--One room controller owns the committed graph, one pending child operation, and one-event-driven reconciliation loop. Allocate/distribute, child reparent, and relay-abdicate/drain are inputs to that loop rather than separate state machines.-Topology helpers retain participant metadata and choose candidates without a-second mutable graph.--- The loop first removes disconnected childless participants, then selects one- connected waiting Viewer or one child whose parent is disconnected,- lacks effective capacity for that child, or owns the exact failed edge. It- prepares one upstream change and wakes again after commit, abort, or another- room event.-- A relay whose ingress fails is itself the child being reparented; its subtree- remains attached. A disconnected endpoint, or one with effective downstream- capacity `0`, accepts no new children. Direct or deterministic overflow children- are reparented one at a time by the same loop, and disconnected leaves are- removed naturally.-- The Host is the only source publisher. There is at most one authoritative Host- publication per share generation, and every SFU-fed Viewer subscribes to it.- The Host page owns the canonical capture tracks. LiveKit publisher teardown,- remote room deletion, and transport recovery may release only their SFU- publication and must never stop those capture tracks.- Any source-reachable endpoint with effective capacity may be a parent- candidate; SFU-fed and peer-fed endpoints use the same provisional-child- transaction and each child edge commits independently. Viewer republishing- into a second SFU publication is outside the current product.-- The only server-assisted route is an SFU subscription backed by the Host's- one direct-ingress publication. Screener configures no TURN or media TCP- transport. An all-UDP-blocked network reaches a clear bounded failure; any- future strict-firewall transport requires its own evidence and belongs inside- LiveKit rather than becoming another application candidate.-- Browser SFU publisher and subscriber PCs explicitly use an empty ICE-server- list, retain LiveKit-signaled UDP candidates, and let standard ICE nominate a- non-relay pair. Candidate type, address family, count, and Browser socket- allocation are not application invariants. Ordinary peers still use- deployment STUN, and LiveKit server-side public-IP discovery may use that same- STUN service. This isolates SFU PCs from unnecessary external STUN/TURN- destinations without adding a route, transport, port, retry stage, or timeout.-- Browser ICE connectivity checks are the authority for direct UDP reachability.- Screener does not synthesize remote candidates, predict ports, classify NAT- behavior, or use TCP reachability as a media-path probe. Direct exhaustion- advances to the SFU stage inside the same operation deadline.-- Endpoint sender capacity is accounted independently from server ingress/egress, SFU- subscriptions, and one bounded transition-overlap slot.- Steady capacity is `1`, `2`, or `3` (default `2`); a transition may use- `min(steadyCap + 1, 3)` only for one fenced, deadline-bound handoff and must- return to steady bounds at commit. There is no fixed SFU-root count or- room-wide selected-lease count.-- Candidate-list creation, reserve, prepare, the child's first decoded frame,- atomic commit, abort, and idempotent release are one bounded child operation.- Its one total deadline cleans abandoned reservations and never revokes a- healthy committed edge. While that one exact candidate is pending, its- receive-transport owner runs one short-lived, generation-fenced- `framesDecoded` observer and stops it on proof, promotion, pause, replacement,- or teardown. A fresh peer connection or fresh SFU activation proves a- positive cumulative count; a paused prepared SFU route first records a- Resume-time baseline and requires later progress. This observer adds no- success/failure deadline and cannot select, reject, or reorder candidates.-- A child invalidates only its own exact edge after PeerConnection hard failure- or a named non-paused interval without a newly decoded frame. Bitrate, FPS,- resolution, blur, and sender statistics remain diagnostics or stock- WebRTC/LiveKit adaptation inputs; they do not change- parent eligibility. Multiple bad child edges recover independently through the- same loop and naturally empty an unusable relay.-- A currently decoding exact edge remains sticky. Current-path loss, RTT,- jitter, bitrate, resolution, FPS, freeze, and limitation evidence cannot prove- the counterfactual quality of another parent, so Screener creates no weighted- route score, alternative-parent probe, hysteresis loop, or periodic- quality-driven reparenting.-- Quality selection begins with one evidence-only shadow phase inside this same- controller. A Viewer reports standard freeze and pause deltas only for a- window with continuing decoded-frame progress. Presentation eligibility- separately requires that its exact current route is connected, the page is- visible and not suspended, the Host is not paused, the native video is- playing, and a current composited frame has already been proved. Current target Chromium does not- expose the W3C `framesRendered` member, so it is not a wire requirement; the- freeze/pause counters themselves remain renderer-derived. A strictly monotonic- presentation epoch fences every presentation-eligibility change; its first- new stats sample establishes a baseline and is not evidence. A zero-decoded- window neither enters the aggregate nor advances that epoch or freshness; a- later positive-progress window may carry the renderer's newly settled- freeze/pause delta. The server then revalidates the authenticated- Viewer session, exact committed upstream and connection before the controller- keeps one bounded current-epoch aggregate per child. Missing stats remain- unknown, recovered freeze/pause duration may exceed one report window, and a- stale aggregate disappears from the on-demand Host diagnostic snapshot.- Shadow observation never changes facts, capacity, graph, revision, candidate- order, SFU admission or reconciliation. Active trials remain unaccepted until- annotated production evidence establishes a usable trigger and disruption- boundary; any accepted trial must reuse this controller's single child- operation, reservations, first-frame commit and rollback rather than create a- second optimizer.-- Web clients derive active decoded progress from their existing periodic- WebRTC/LiveKit stats sampling. One route-keyed last-progress deadline reports- the exact edge once; it resets on route/connection change or decoded progress- and is suppressed while authoritatively paused. An active SFU route keeps that- same cadence when its video track is absent, its merged report is empty, or a- stats read fails; each such sample means no decoded progress, not a fabricated- metric or an immediate failure. Only route deactivation or teardown stops the- cadence, and stale asynchronous samples are generation-fenced. This steady-- state sampler is separate from the pending candidate's short-lived first-frame- observer and does not treat bitrate, FPS, track availability, or SFU layer- choice as route authority.-- Browser page resume/visibility recovery rebaselines this same deadline before- another no-progress sample can invalidate an edge. Frozen JavaScript wall time- is not media-failure proof. A newly composited current-generation frame clears- stale local recovery presentation but does not create route authority.-- Manual media reconnect remains on the current exact route. P2P directly- rebuilds the connection to the existing parent; SFU- disconnects and reconnects only the current LiveKit subscriber with fresh- scoped configuration. Neither action restarts Screener signaling, changes the- route revision, performs quality selection, or reparents. Only actual recovery- exhaustion reports route failure and enters normal reconciliation.-- Authoritative pause aborts the pending child operation, including its current- candidate and reservations, keeps the active graph, suppresses decoded-frame-- stall decisions, and leaves new participants waiting. Resume always wakes a- fresh reconciliation from the committed graph. Healthy unaffected edges remain- sticky.--SFU remains a bounded fallback resource with independent deployment-wide-admission. Resource exhaustion produces an explicit wait or failure; it never-creates unbounded central fanout.-Rooms that actually lose a candidate to deployment-wide admission register in-one waiter set. An actual SFU usage decrease drains that set once, advances-each waiting controller's external fact, and schedules normal reconciliation;-there is no periodic capacity poll or resource-specific route controller.--The accepted Viewer wire includes one strict, revision-fenced `route-status`-union only for states that the existing prepare/active `route-update` cannot-express: `{ state: "waiting", reason: "sfu-admission" }` while this Viewer is-waiting on central admission, or `{ state: "failed", reason:-"route-exhausted" }` after the controller reaches its bounded terminal. It is-sent only server-to-authenticated-Viewer and carries no text, identity,-candidate, retry hint, or other topology data. Access, Host presence, signaling,-media, and autoplay remain independent presentation inputs.--The room-serial operation does not divide its per-child deadline by Viewer-count, but simultaneous joins may form a linear queue. The current Browser-diagnostic owner observes existing route events without changing the controller:-for each current child it keeps only the latest route-demand, operation-start,-current-candidate-start, first-decoded-frame, and final-outcome timing. A new-demand overwrites that child's record; authoritative share stop/replacement,-confirmed departure, and room deletion remove it.--An authenticated Host acceptance harness may request one snapshot. The current-product UI exposes no diagnostic download button. The response-reads the current graph, current operation, and latest records; the server does-not push a periodic snapshot stream, start a timer, retain an event ring, log or-persist the result, or create a second graph. Snapshot-local ordinals express-parent/SFU relations but are not participant identities and must not be treated-as stable across snapshots. Queue wait is the interval from the same route-demand to operation start and remains `null` when either event is absent.--The response uses only `direct | sfu | waiting | failed` final-route values and-the closed rejection buckets `none`, `stale`, `endpoint-capacity`,-`sfu-admission`, `candidate-failed`, `first-frame-timeout`,-`operation-deadline`, and `aborted`. It never carries real peer, parent, session,-connection or generation identity, SDP, candidates, addresses, credentials, or-raw error text, and it has no route authority. A 20-Viewer burst reports the-sample count and nearest-rank p50/p95/max without a pass threshold before any-different concurrency model or deadline is accepted. Protocol tests reject-extra/private fields, deny the request to Viewers, and prove departure and-room-deletion cleanup.--For the single-process deployment, SFU admission is one injected authority with-deployment-wide ingress and egress counters. The fixed 9,000-room code space is-also the ingress ceiling because each room owns at most one Host publication;-egress is the same room capacity multiplied by per-room Viewer admission.-Neither has an independent setting. One exact room/share/publication entry owns-the Host publication ingress, while an exact Viewer subscription handle under-that entry owns one egress unit. The current publication is reused as-Viewers enter or leave the SFU path; each child candidate reserves and commits-only its own subscription handle. Reserved, committed, and draining handles,-concurrent publication generations, and generations still draining from-LiveKit all remain charged. A subscription that leaves the route remains-charged as draining until its publication room is deleted and proven absent;-reactivating that same Viewer handle does not charge it twice.--The accepted self-hosted deployment contract dedicates one LiveKit instance to Screener,-sets `room.auto_create: false`, and gives the application an explicit private-`LIVEKIT_API_URL`. The controller reserves the exact publication and first-subscription, creates that managed LiveKit room through `RoomService`, and only-then issues tokens. Later SFU-fed children reserve an exact subscription under-the same generation without republishing the Host. Publication replacement-moves the old generation and all of its subscription handles to `draining`;-abort, timeout, participant loss, share rollover, room stop, and room deletion-apply the same typed lifecycle to the resources they own.-`RoomService.DeleteRoom` must complete and a follow-up lookup must prove the-room absent before that generation's ingress or egress units are released.-Because joining cannot recreate a deleted room, a stale self-hosted token-cannot produce an off-ledger participant.--The single owner first binds the configured application listener exclusively;-a competing process that cannot bind makes no LiveKit control-plane call. While-bound but not initialized, HTTP returns `503` and no signaling upgrade handler-is installed. The owner then lists its dedicated LiveKit instance, rejects-foreign room names, deletes every stale Screener room, confirms the owned-namespace empty, and only then accepts application traffic. Graceful shutdown-drains the same namespace before forgetting counters. A Host signaling-disconnect keeps a committed generation charged while its exact LiveKit Host participant exists;-an interval-bounded control-plane check retires it after that participant-disappears. A multi-process application deployment requires a shared atomic-admission and lifecycle owner before it may claim these values are-deployment-wide.--## Current Source And Deployment Boundary--Canonical application/runtime source and production use the evidence-only-strict `screener-v13` quality shadow. Exact current source and deployment-identity is indexed by [status](../status.md).-Browser SFU PCs use empty external ICE-server lists. The controlled exact--candidate rollback/SFU commit and active-SFU cadence gates are closed. The-operation owner remains only `route`; broader heterogeneous-network and SFU-lifecycle validation remains open in the-[verification ledger](../verification-status.md).--## Acceptance Boundary--The deployed core's completed source and deployment evidence is indexed in-`docs/verification-status.md`. Any revised controller must re-pass these source-and deployment gates:--- property tests cover capacity `1`, `2`, and `3`, one active upstream,- acyclic and source-reachable assignments, stale generations, duplicate- signals, departure, rollback, and admission exhaustion;-- route changes preserve unaffected branches and never commit before the exact- candidate child's first decoded-frame ready;-- SFU lifecycle tests keep reserved, committed, and draining generations charged- until deletion plus absence proof, reject stale-token room recreation, prove a- competing listener owner makes no LiveKit call, fence startup against stale or- foreign rooms, reclaim an abandoned Host generation- without cutting a live Host participant, and keep two rooms under one global- capacity owner;-- candidate lists are deterministic under input permutation, preserve a healthy- current edge, prefer the shallowest least-loaded parent with capacity, and- advance one cursor after exact failure and idempotent cleanup without resetting- the total operation deadline;-- focused controller tests cover first-frame commit, candidate failure and stale- ready, relay-ingress reparent with its subtree intact, disconnected relay and- nested-disconnect convergence, effective capacity `0..C` and overflow drain,- SFU-fed first-child use and pause/resume;-- deployment preflight proves the LiveKit instance is dedicated, uses- `room.auto_create: false`, exposes `RoomService` only on its accepted private- control origin, and can drain its managed namespace before traffic or- rollback.--The following external acceptance remains open without changing the deployed-core's status:--- representative-network real-browser tests cover direct peer media, peer- relay, SFU media, bounded failure, and recovery beyond the completed- controlled direct-to-SFU transaction;-- measured endpoint upload and server ingress/egress prove the accepted- accounting under normal and migration overlap; and-- every exhausted path reaches a clear bounded wait or failure without leaking- credentials, candidates, addresses, or raw errors.--Loopback timing and synthetic signaling tests may validate invariants, but they-do not prove target-network latency, quality, capacity, or interoperability.--## Security and privacy--Route and signaling authority is room-, role-, session-, share-, revision-, and-connection-bound. LiveKit media credentials are short-lived and bound to the-room, role, share, and publication generation so healthy media may survive a-signaling reconnect. Server-assisted credentials remain memory-only and never-appear in application page URLs, browser persistence, or durable server storage. LiveKit places-its short-lived JWT in the WebSocket transport request target, which must not be-logged; no credential may enter application or proxy logs.-Ordinary SFU transport terminates DTLS-SRTP at the SFU; the product must not-claim application E2EE unless key distribution and real media evidence exist.-Authenticated Hosts and shipped clients are trusted media participants in the-current private-room threat model. Stale route-control sessions remain-unauthorized; a retired media generation remains charged during bounded drain-until deletion of its exact room prevents re-entry.+### One Capacity Rule++Every non-server endpoint uses one server-authoritative steady outbound media-+copy cap `C`: default `2`, configurable only as `1`, `2`, or `3`.++- one ordinary peer child consumes one copy;+- the Host's single SFU publication consumes one copy;+- upstream receive consumes none;+- role, Browser, UA, device, visibility, codec, and room Viewer limit do not+ create another tier;+- a client may advertise only `0..C` currently available copies, producing the+ controller's effective capacity.++One transition-overlap reservation may temporarily raise a producer to+`min(C + 1, 3)`. Commit or abort releases it. A fourth endpoint copy is never+authorized. SFU ingress and subscription egress are independent server resources+and are not inferred from endpoint child counts.++### One Graph And Reconcile Loop++One room controller owns:++- one committed, versioned, acyclic, source-reachable graph;+- one event-driven reconcile loop;+- at most one room-serial child operation; and+- participant sessions, effective capacity, current failure facts, and the+ Host's optional SFU publication.++The Host has no upstream. Each Viewer has zero or one active upstream. Healthy+unaffected edges remain sticky. Join/waiting, failed-edge repair, relay-ingress+repair with subtree retention, confirmed departure, and capacity reduction are+inputs to the same loop rather than separate routing systems.++Disconnected childless participants are removed naturally. A disconnected+relay or a relay with reduced capacity accepts no new children; only its+deterministic overflow children are reassigned. A relay whose ingress fails is+itself reparented while its descendants remain attached.++### Deterministic Candidates++Each child operation owns one candidate list and cursor, one current candidate+and reservations, one route-demand owner, one fact version, and one total+deadline. Candidate creation first rejects stale sessions, unreachable sources,+cycles, insufficient steady/overlap capacity, tuples already consumed by that+operation, and unavailable SFU resources.++Eligible Peer parents are ordered by:++1. shallowest resulting depth;+2. greatest remaining steady capacity;+3. a stable child-parent rank;+4. join order; and+5. peer identity.++There is no independent depth cap. Room admission and acyclicity bound the graph;+shallowest-first is a preference, not a periodic balancing mandate. IP address,+geography, NAT guess, UA, and scalar quality score do not select a parent.++A failed exact tuple is consumed only for its current operation. A later external+fact may make it eligible again; there is no persistent parent blacklist.++### Prepare, Commit, And Rollback++Every operation is fenced by room and endpoint sessions, share generation, base+and pending route revisions, and one candidate connection identity. SFU routes+also carry a publication generation. Duplicate current messages are idempotent;+stale asynchronous results fail closed.++The old committed route remains authoritative while the candidate prepares.+Parent and child prepare the same server-issued connection identity. Standard+ICE connected is progress only. The exact candidate child decoding its first new+video frame is the sole application commit proof.++The media-ready call commits typed endpoint/SFU admission before graph promotion.+Success broadcasts the candidate revision. Failure, timeout, pause, or stale+authority destroys the candidate, releases reservations idempotently, and+broadcasts a strictly newer rollback revision before another prepare. Clients+never infer rollback from silence or an older revision.++Make-before-break is used only when all required reservations exist. Availability+repair may use one explicitly planned bounded-gap retirement after server+resources are preflighted; it keeps the same deadline, replans the untried suffix,+and retains one restore tuple. Background convergence never interrupts healthy+media for a bounded-gap candidate.++### Availability Order++Initial acquisition gives direct Peer candidates one bounded foreground window.+Hard failure may advance a different direct candidate inside that same window,+but the window and total operation deadline never reset. Exact transport-+connected progress may retain the current direct candidate until the deadline;+it still cannot commit without decoded media.++When the direct foreground window ends, a usable SFU candidate may provide media+before unresolved direct candidates. After an SFU route commits, finite remaining+Peer candidates converge behind working media, one at a time and round-robin+across SFU Viewers. New join or repair work preempts this background convergence.+Exhausting direct candidates simply keeps the working SFU route.++If the Host is full and no publication exists, one bounded SFU-bootstrap intent+owns the original waiting demand and a finite cursor of eligible Host-direct+children. A carrier must create the publication through a normal overlap; it may+not cut a healthy branch first. Carrier failure keeps that branch and advances+the cursor. Success lets the original demand try the publication before its+remaining direct candidates. The intent owns no second graph, concurrent child+operation, or timer.++### SFU Resource Ownership++There is at most one Host publication per room/share generation. Every SFU+Viewer owns one subscription to it; Viewers never publish a second SFU stream.+The Host page owns capture tracks, so SFU teardown or recovery must not stop+capture.++The single-process server has one injected SFU admission owner. Its ingress+ceiling derives from the fixed room-code space, and egress derives from that+space times the per-room Viewer limit; neither has an independent tuning key.+Exact publication and subscription handles remain charged while reserved,+committed, or draining. Reactivating the same handle does not double-charge it.++The application explicitly creates a managed LiveKit room before issuing media+tokens. Replacement, abort, timeout, confirmed media-participant loss, share+rollover, stop, and room deletion transfer the resources they own into the same typed drain path.+Only successful room deletion plus an absence readback releases that generation,+so a stale token cannot recreate off-ledger media. The deployment must dedicate+the LiveKit namespace to Screener and complete startup ownership/cleanup before+accepting traffic; [self-hosting operations](../operations/self-hosting.md) owns+that procedure.++Only confirmed LiveKit media-participant absence retires an abandoned Host+publication. A Host signaling disconnect keeps the generation charged while the+exact LiveKit Host participant remains; one bounded control-plane check releases+it only after that participant disappears.++A room denied by deployment-wide SFU admission enters one bounded waiter set.+Actual SFU usage decrease drains that set once, advances each surviving room's+external fact, and schedules ordinary reconciliation. There is no periodic+capacity poll or second resource-specific controller.++Ordinary Peers use deployment STUN only. Browser SFU PeerConnections use an+empty external ICE-server list while retaining LiveKit-signaled UDP candidates.+Screener configures no TURN, ICE/TCP, media TCP, or TLS-relayed media. A future+strict-firewall transport must be accepted as a LiveKit-internal capability, not+as another application route candidate.++### Recovery, Pause, And Quality++WebRTC and LiveKit first own ICE/consent and transient reconnect on the current+route. Only framework recovery exhaustion, hard failure, a non-paused decoded-+frame stall, confirmed departure, or capacity invalidation enters route+reconciliation. Manual reconnect remains on the exact current route.++Authoritative Host pause aborts the pending operation and reservations, preserves+the committed graph, suppresses decoded-stall authority, and leaves new Viewers+waiting. Resume starts reconciliation from the current graph. Page-hidden wall+time is rebaselined before it can contribute to a stall decision.++Quality evidence is observation-only. Current low bitrate/FPS/resolution, loss,+RTT, jitter, freeze, or sender limitation does not change candidates, capacity,+SFU use, or graph authority. Screener has no weighted route score, parent-wide+quality inference, all-pairs probe, hysteresis controller, or periodic rebalance.+Open investigation remains in [TODO](../todo.md).## ConsequencesPositive:-- one capacity rule replaces role and browser policy forks;-- route safety is expressed through graph, identity, and media invariants;-- server-assisted paths remain bounded and explicit without turning the room- into an always-SFU topology.+- one capacity rule replaces role- and Browser-specific tiers;+- one graph and operation make route, identity, and resource ownership explicit;+- media stays distributed while SFU cost and stale-token behavior remain bounded;+- unrelated healthy branches survive local join, failure, and repair.Negative:-- one room-serial operation may create measurable queue-tail latency during a- burst;-- make-before-break consumes explicit endpoint and server reservations and may- require a bounded-gap cutover when no overlap slot exists; and-- real SFU and target-network evidence is still required; diagnostics remain- observational and do not grant route authority or close physical evidence.+- the serial operation can create queue-tail latency during bursts;+- Browser relay creates per-child decode/re-encode cost;+- make-before-break requires temporary reservations and some availability repair+ may require a bounded gap; and+- UDP-only media ends in explicit failure on fully blocked networks.-## Relationship to other ADRs+## Related Decisions And Evidence-- ADR-0001 owns the original browser P2P baseline.-- ADR-0004 is historical evidence about browser peer relay and re-encoding; it- does not set current capacity or server-assisted policy.-- ADR-0007 owns diagnostic path-quality evidence and representation behavior;- it does not create route eligibility.+- [ADR-0001](./0001-p2p-first-media-topology.md): initial P2P baseline.+- [ADR-0004](./0004-peer-assisted-media-experiment.md): Browser relay evidence.+- [ADR-0007](./0007-path-isolated-representation-quality.md): framework-owned+ representation adaptation.+- [Low-server-cost routes](../research/low-server-media-routes.md) and+ [peer-assisted media](../research/peer-assisted-media.md): measurements and+ rejected alternatives.+- [Verification status](../verification-status.md): current open physical gates.-## References+## Primary References- [WebRTC](https://w3c.github.io/webrtc-pc/)- [WebRTC statistics](https://www.w3.org/TR/webrtc-stats/)-- [WebRTC transports, RFC 8835](https://www.rfc-editor.org/rfc/rfc8835.html)+- [ICE, RFC 8445](https://www.rfc-editor.org/rfc/rfc8445.html)- [RTP topologies, RFC 7667](https://www.rfc-editor.org/rfc/rfc7667.html)-- [PIM-SM Join/Prune behavior, RFC 7761](https://www.rfc-editor.org/rfc/rfc7761.html)-- [ICE connectivity checks and candidate checklists, RFC 8445](https://www.rfc-editor.org/rfc/rfc8445.html)-- [NICE degree-bounded application-layer multicast](https://conferences.sigcomm.org/sigcomm/2002/papers/appmulti.pdf)-- [Overcast adaptive single-source distribution trees](https://www.usenix.org/conference/osdi-2000/overcast-reliable-multicasting-overlay-network)-- [Kubernetes cordon and drain](https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands)-- [LiveKit selective subscription](https://docs.livekit.io/transport/media/subscribe/#selective-subscription)-- [LiveKit track subscription permissions](https://docs.livekit.io/transport/media/publish/#track-permissions)-- [Kubernetes controllers](https://kubernetes.io/docs/concepts/architecture/controller/)-- [Consistent updates for software-defined networks](https://reitblatt.com/downloads/consistent-updates-hotnets11.pdf)+- [NICE degree-bounded multicast](https://conferences.sigcomm.org/sigcomm/2002/papers/appmulti.pdf)+- [Overcast](https://www.usenix.org/conference/osdi-2000/overcast-reliable-multicasting-overlay-network)+- [LiveKit selective subscription](https://docs.livekit.io/transport/media/subscribe/)+- [Consistent network updates](https://reitblatt.com/downloads/consistent-updates-hotnets11.pdf)diff --git a/docs/adr/0006-fixed-high-native-sender-canary.md b/docs/adr/0006-fixed-high-native-sender-canary.mdindex 9f6cdc28..36a815a5 100644--- a/docs/adr/0006-fixed-high-native-sender-canary.md+++ b/docs/adr/0006-fixed-high-native-sender-canary.md@@ -1,205 +1,60 @@# ADR-0006: Fixed-HIGH Native Sender Canary-- Status: Proposed - Product Gate No-Go+- Status: rejected product candidate; evidence retained for later revalidation- Date: 2026-08-19+- Last updated: 2026-08-27## Context-The Draft #16/#18/#22/#23/#25/#28 ladder proved isolated WebCodecs/Pion-properties, not integration with Screener's current rooms, signaling, ordinary-browser viewers, or per-edge ICE transport. A native sender remains a later-optimization and must not be presented as available product behavior.--## Retained Boundary--Any renewed product-wiring canary stays deliberately narrow:--- one fixed VP8 `HIGH` representation at 1280x720, 30 fps, and a 3 Mbps ceiling;-- one WebCodecs encoder object feeding at most two independent Pion WebRTC legs;-- the current strict ordinary-P2P signaling wire and unmodified browser viewers;-- independent STUN-backed ICE, RTP/RTCP, congestion, and lifecycle state per leg;-- read-only feedback, with PLI/FIR limited to requesting a shared keyframe; and-- bounded local queues, fail-closed critical errors, and sanitized local-only- diagnostics.--This canary excludes room-wide minimum feedback, automatic quality control,-`LOW`, viewer C reporting, peer-assisted/SFU routing, audio, packaging, and any-claim of one physical or hardware encoder. A third viewer must never create a-third host edge. The missing audio path remains a product-acceptance gap.--## 2026-08-19 Gate Result--The sole authorized run is `no-go-unclassified`; the retained evidence and-probe limitations are recorded in the native sender research. The earliest-missing checkpoint is viewer authentication, not a proven authentication-failure. No viewer-1 acceptance means there is no two-viewer, third-viewer-FIFO, or direct/SFU proof. The attempted native branch must not be opened or-merged as product code from this state.--## 2026-08-20 Historical Wire Checkpoint--This checkpoint targeted the then-current `screener-v2` wire and SQLite schema-v2. It is experiment provenance, not a current integration contract; current-source and production boundaries are owned by [status](../status.md), and-executable senders remain outside the current release.--A clean local delivery candidate now targets only `screener-v2`: it exchanges-`SITE_ACCESS_PASSWORD` for the bounded HttpOnly site-access cookie, uses-that cookie to create an explicit `private-link` room, carries it on the Host-WebSocket upgrade, and strictly decodes the current ordinary authenticated and-read-only Viewer-evidence shapes. There is no v1 parser, translator, raw-grant-persistence, or Bearer room-creation shortcut. Its fixed 300-second provisional-request always creates a random transient room in memory, even when SQLite is-configured. A connected current Host suppresses that reclaim deadline; only its-generation-matched disconnect resets the five-minute window, while the ordinary-transient `ROOM_TTL_SECONDS` cap always remains. A pre-auth connection or-authentication failure gets one retry with the same room/token/client generation-and never another room POST. Server restart drops the room; SQLite stays at v2-and ordinary Web rooms are unchanged. No claim-confirm message, durable native token, or recovery-subsystem is added. Focused Go/TypeScript tests and static checks pass. The unused-generic probe framework is deliberately not retained. A current command consumer-may keep only the minimum stage ledger needed by the next authorized run.--The first authorized current-wire run on 2026-08-20 remains-`no-go-unclassified`. It used Windows amd64, Chrome 151, one real animated Chrome-tab, and an isolated local Node server with an in-memory RoomStore and peer-assistance disabled. Safe Chrome history booleans prove that the source and-Sender pages loaded and that no Viewer page was created. The runner stopped-after a bounded 20-second Sender-start interval without observing the combined-Sender-ready and Go source-RTP condition.--The timeout path failed to preserve its final Sender DOM/counter sample. It-therefore cannot distinguish capture selection, site access/create, WSS-authentication, local bridge, first encoded output, or Go ingest as the first-runtime break. None is a proven product failure. No retry, timeout adjustment,-Viewer, second Viewer, or FIFO run followed. A separately authorized rerun must-first make the stage-1 ledger unconditional and prove that timeout retains the-last sanitized checkpoint; only a passed Sender/source-RTP stage may create the-single Viewer. The product gate remains no-go and this local branch is not a-product availability claim.--The retained current command consumer appends and flushes only monotonic,-sanitized Sender-start fields. Its static one-Viewer gate now freezes one-socket/auth/connection/PeerConnection/video-track generation and the matching-Pion slot/edge generation, then revalidates that identity during media progress;-raw connection IDs never leave the page probe. Every CDP RPC and sample shares-its enclosing absolute deadline. `passed` is impossible until bounded Chrome-and native process-tree exit, listener closure, and audited deletion of the-exact task profile under system Temp all succeed; a reparse point or deletion-failure is a fixed cleanup failure. Pure checks cover retained timeout evidence,-hung samples, cross-generation rejection, cleanup-before-pass, and profile-cleanup failure.--One separately authorized second run then used that frozen gate with the same-bounded local topology. Its retained ledger proves `getDisplayMedia` request and-resolution, site access and room creation, Host WSS authentication, local-bridge readiness and fixed-`HIGH` config acceptance, exactly one encoder object,-and entry into the first WebCodecs output callback. It serialized zero media-counters without retaining whether any diagnostics arrived, so those values do-not prove that Go reported zero. It stopped at `sender-start` and never created-a Viewer. No retry or threshold adjustment followed. Cleanup completed before-final failure: Chrome and Native exited, the-Node server and all three loopback ports closed, and the exact task Chrome-profile passed the non-reparse audit and was removed.--This remains `no-go-unclassified`. The frozen probe counted the first encoded-chunk before invoking the product output callback and did not record whether the-generation-bound local bridge attempted, returned from, or threw during its-binary send. Static inspection finds matching 17-byte big-endian frame contracts-on the Web and Go sides. A focused integration now configures the real `/media`-handler, sends one same-contract binary frame, and observes positive Go frame and-source-RTP accounting. That proves the current envelope can enter the current Go-fanout in a controlled test, not that the retained browser executed its send.--The handler no longer returns silently for every post-config bridge read error:-while the app context is active, any close other than normal or going-away emits-one `fatal` with the fixed sanitized message `local media bridge read failed`.-Focused tests prove the abnormal classification without its underlying close-reason and prove normal close and app shutdown do not misreport. This is a real-P1 bridge-read failure fix, but it does not classify the missing diagnostics-or prove a framing defect.--One authorized evidence-clarification revalidation then ran the corrected gate-exactly once with the same fixed VP8 `HIGH`, Chrome 151, one in-memory local room,-and peer assistance disabled. It retained the same start sequence through one-generation-1 binary send return, then observed no diagnostics or post-send-diagnostics, zero encoder errors, and at least one sanitized fatal marker. Its-media-counter zeros are initial ledger values, not Go reports. The first failed stage remained-`sender-start`, no Viewer was created, and cleanup passed 5/5. No retry,-threshold change, H.264, second Viewer, FIFO, or production run followed.--The result remains `no-go-unclassified`. It proves the first product binary-send returned, but the retained fatal marker and missing diagnostics do not prove-where or why the product path stopped. No raw cause may be inferred. There is-still no Viewer, two-viewer, FIFO, or physical or hardware-encoder proof.--A source follow-up identifies and removes one concrete fatal path without relabeling-that retained run. WebCodecs output duration is nullable; the local sender uses-33,333 microseconds when it is absent, while a valid next capture timestamp may-arrive slightly earlier. The prior RTP timeline rejected that strictly-increasing pair as `encoded frame timestamps overlap`. The candidate now derives-RTP cadence from adjacent strictly increasing source timestamps and uses duration-only to report positive source gaps. Focused tests retain dropped-frame timing,-non-increasing rejection, and sub-sample progress; the real `/media` handler also-accepts two frames at 1,000,000 and 1,033,000 microseconds when the first reports-33,333 microseconds. This proves the source path no longer raises that fatal, not-that it caused the retained browser failure.--## 2026-08-20 One-Viewer Loopback Revalidation--A bounded Chrome 151 run with fixed VP8 1280x720@30 and peer assistance disabled-closed the base sender-to-Viewer path once. Sender/Go recorded 30 written frames,-85 source RTP packets, and zero fatal or encoder errors. The Viewer authenticated,-completed offer/answer/ICE, received 877 packets, and advanced from 0 to 299-decoded and rendered frames at 1280x720. The probe was corrected to tolerate-pre-offer trickle candidates and a development-only pre-offer control-socket-replacement while retaining fail-closed checks after an active offer/PC.--The run still ended negative at the gate's Pion outbound assertion because the-two-second Go diagnostics snapshot did not refresh during the media sample-(`pionPacketDelta=0`). This is a residual observation-timing gap; inbound packet,-decode, render, source-RTP, and no-fatal evidence are retained. The result is-therefore a one-Viewer functional loopback proof, not a broad Native acceptance:-two edges, FIFO, hardware, endurance, public-network, audio, and packaged-native-boundaries remain no-go.--## Staged Revalidation--Any further run requires separate authorization and must stop at the first-failed stage while synchronously retaining a bounded final-negative snapshot:--1. Prove host room/auth, local config acknowledgement, one encoder object,- bridge ingress, frame decode, source RTP, and zero critical errors.-2. Prove viewer auth, `peer-joined`, exact offer/answer/candidate exchange, and- both PeerConnection state timelines.-3. Prove one viewer's inbound packets, `framesDecoded`, video readiness/current- time/dimensions, and rendered frames.-4. Add viewer 2 and prove two independent legs while encoder instances stay one- and host media edges stay at most two.-5. Add viewer 3, prove no third edge and a host-side waiting observation while- the viewer keeps its existing waiting state, then close viewer 1 and prove- FIFO promotion plus decoding/rendering.-6. Keep this candidate STUN-only. Direct failure remains inside ADR-0005's- dedicated Host-publication/SFU-subscription boundary; the Native canary does- not add another media transport or widen that route model.--A commit-bound, short-lived evaluation artifact may package the current source-to run these stages without a development toolchain. That artifact is not an-acceptance or release claim. Only after these stages pass may separate-performance, quality, loss, reconnect, browser, audio/A-V-sync, formal release,-and license gates begin. Do not expand the feature to make the diagnostic gate-pass.+A native sender could capture and encode once while serving bounded independent+WebRTC legs, reducing Browser capture/encode cost. Early WebCodecs/Pion and+Windows hardware fixtures proved isolated pieces but not compatibility with the+current room, signaling, routing, audio, packaging, and Browser Viewer contract.++## Decision++Do not integrate or ship the fixed-HIGH native sender. The current product+surface remains Web Host/Viewer/relay, and stale experimental wires receive no+compatibility reader.++The retained one-Viewer loopback proved that a fixed 1280x720@30 source could+authenticate, negotiate one independent Pion leg, and deliver decoded/rendered+Browser frames. Later Windows WGC/Media Foundation work proved one attributed+hardware H.264 path. Those are bounded functional facts, not evidence for two+Viewers, shared congestion behavior, audio/A-V sync, public networks, recovery,+endurance, packaging, licensing, or production.++## Reopen Boundary++A later native milestone must start from the then-current canonical contract and+stop at the first failed stage:++1. Prove current room creation, Host authorization, source/encoder identity,+ bounded queues, source RTP, and zero critical errors.+2. Prove one ordinary Browser Viewer through the current signaling and routing+ model, including exact offer/answer/ICE and decoded/rendered media.+3. Prove two independent transport legs while capture and encode remain shared+ and endpoint capacity remains authoritative.+4. Prove a third Viewer waits without creating a third edge, then is promoted+ when capacity releases.+5. Add application audio, PLI/FIR recovery, reconnect, source lifecycle,+ public-network/endurance, packaging, signature/update, and license gates.++The canary may not add a parallel room model, old wire, custom congestion+controller, room-wide minimum quality, another media transport, or claims of+hardware acceleration without process-and-adapter evidence. Direct/SFU behavior+must remain owned by ADR-0005.## Consequences-ADR-0006 records a bounded candidate and its failed first product gate, not an-accepted architecture or shipped sender. The deployed Web sender and ordinary-viewer remain unchanged. ADR-0007 continues to own path-isolated-representations; the current Browser SFU contract is one `HIGH`, and this canary-cannot advance or replace it.+- No native candidate constrains the current Browser product or route model.+- Existing native source and fixtures remain research/evaluation code, not a+ production runtime.+- Revalidation cost is explicit and cannot be hidden by preserving deprecated+ protocol or packaging surfaces.-## References+## Evidence-- `docs/research/native-shared-encode-sender.md`-- `docs/adr/0007-path-isolated-representation-quality.md`-- `docs/research/browser-screen-audio-quality.md`+- [Native sender and shared encode](../research/native-sender.md)+- [Browser screen audio](../research/browser-screen-audio-quality.md)+- [ADR-0005](./0005-automatic-hybrid-media-routing.md)diff --git a/docs/adr/0008-window-scoped-audio-capture.md b/docs/adr/0008-window-scoped-audio-capture.mdindex b1d3190a..f46e8446 100644--- a/docs/adr/0008-window-scoped-audio-capture.md+++ b/docs/adr/0008-window-scoped-audio-capture.md@@ -1,154 +1,60 @@-# ADR-0008: Window-Scoped Audio Capture+# ADR-0008: Browser Screen-Audio Scope-Date: 2026-08-21--Status: Accepted. The browser hint and opt-in Native Windows audio slice are-source-complete, including the bounded Windows x64 evaluation-package path.-The paired WGC/MF hardware-video source passed its one-Viewer acceptance smoke;-all Native sources remain default-off, formally unreleased, and undeployed.+- Status: accepted for Browser capture; Native process audio remains research+- Date: 2026-08-21+- Last updated: 2026-08-27## Context-The Web Host currently receives an optional audio track from-`getDisplayMedia({ audio: true })`. A browser may return no audio, and the Web-API does not expose a portable readback identifying whether that track is a-tab, window, monitor, or whole-system mix. Capturing a system mix while a voice-application is open can leak that conversation back to Viewers.+`getDisplayMedia({ audio: true })` may return tab, window, monitor, or system+audio depending on Browser, operating system, selected surface, and user choice.+The Web API exposes no portable proof that a returned track is isolated to one+application. Sharing a system mix can unintentionally include calls or+notifications.-Windows has a stricter primitive: WASAPI application loopback through-`ActivateAudioInterfaceAsync` with-`AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS.INCLUDE_TARGET_PROCESS_TREE`. It can be-paired with a selected window's PID and a WGC/DXGI video capture. Microsoft's-process-loopback contract starts at build 20348; this product slice gates on-Windows 11 desktop (build 22000 or newer) and is not a Windows 10 fallback.+Windows offers a narrower native primitive through WASAPI application loopback+for one selected process tree, but that capability belongs to the unreleased+native sender candidate rather than the current Web product.## Decision-1. The Web sender requests `windowAudio: "window"` for window surfaces and- `systemAudio: "include"` for monitor surfaces. The browser picker and user- consent decide whether audio is shared; older browsers may ignore either- hint, and track presence alone does not identify its source.-2. The default Web route remains unchanged in topology, codecs, and relay- behavior. Returned audio tracks use the standard `contentHint = "music"`;- this does not force a codec, bitrate, channel count, or processing mode. No- Web Audio mixer, SDP rewrite, or app-owned audio bitrate knob is introduced.-3. The native sender has an explicit Windows 11 local window target. Browser- VP8 may use that target only for `window-process-audio`; the separate- `native-window-h264` source uses the same bound HWND/PID/creation time for- WGC/DXGI video and WASAPI process-tree audio. Process IDs, HWNDs, creation- tokens, titles, paths, device identity, PCM, and local hardware status stay- local; they do not enter signaling, URLs, logs, or storage.-4. If the target process exits, produces no render stream, or the loopback- activation is denied, the sender reports `audio unavailable` or `audio- silent` and stops/asks the user. It never widens to whole-system audio.- Windows 10 remains explicitly unsupported until a separate API passes the- same isolation gate.--## Minimal Native Boundary--This is an interface boundary, not a new framework or a current wire change:--```text-NativeCaptureTarget { hwnd: uint64, pid: uint32, creationTime: uint64, includeProcessTree: true }-NativeCaptureSession.start(target)- -> VideoFrames(WGC/DXGI) + AudioPcm(WASAPI process loopback)- -> existing native sender timeline/encoder/fanout-NativeCaptureSession.stop()-```--The first fixture should prove only parent-game plus child-game audio, an-independent voice process, a notification, process restart, no render stream,-and A/V sync on one Viewer. It should use Microsoft's Application Loopback-sample and process-loopback parameter contract rather than a custom mixer.--## P1 First Slice: Audio Only--The first product-wiring slice is deliberately smaller than the complete-native capture boundary. It adds an explicit Windows 11-`window-process-audio` input while leaving the current Web video capture and-codec path unchanged. A small Windows helper resolves the selected target PID-and creation time locally, revalidates both immediately before activation, and-sends timestamped PCM through the authenticated loopback bridge.-The existing Chrome/Edge sender UI uses `AudioEncoder` with `codec: "opus"`,-48 kHz, two channels, and 20 ms frames, then returns the encoded Opus packets to-the existing Go sender. This reuses the current browser prerequisite and avoids-adding a native Opus library or a second package toolchain in this slice.+1. Browser capture asks for window audio on window surfaces and system audio on+ monitor surfaces where those hints exist. The Browser picker and consent+ remain authoritative; older Browsers may ignore the hints.+2. Missing audio never blocks video-only sharing and is reported explicitly.+ Track presence does not prove its source or isolation.+3. Returned screen-audio tracks use `contentHint = "music"`. Current bounded+ sender ceilings and narrow Opus stereo answer normalization are owned by+ [media quality](../product/media-quality.md). There is no Web Audio mixer,+ resampler, second representation, or independent audio clock.+4. Browser source switching replaces the current screen-audio track in the same+ persistent media stream. Local Viewer play, mute, and volume stay inside the+ native media element.+5. Do not describe generic Browser system audio as application-isolated. UI and+ documentation must leave source scope to the Browser's actual result.+6. Windows process-tree audio, WGC/MF video, helper protocols, and evaluation+ packaging remain Native research. Their product stop line is+ [ADR-0006](./0006-fixed-high-native-sender-canary.md); measurements are in+ [native sender evidence](../research/native-sender.md).-The bridge is one typed local media envelope (audio kind, flags, QPC-derived-timestamp, duration, bounded payload); it does not add a public signaling field.-The Go session owns one shared Opus `TrackLocalStaticRTP` and adds it before the-offer on every native PeerConnection. Audio packetization uses the 48 kHz RTP-clock and the source timestamp delta, so one encoded packet stream can feed the-existing two-edge cap. In this historical audio-only phase, the WGC/DXGI video-adapter was the next small slice; its retained `SystemRelativeTime` let the-completed native-video path share the same QPC origin.--Expected implementation size is about **500--800 new LOC**, excluding the-browser/Windows SDK and existing video/MF fixture code: Windows loopback-capture and local IPC (250--400), Go audio envelope/timeline/track (150--250),-and UI lifecycle/status plus focused tests (100--150). The landed slice keeps-that boundary and is not a deployment switch.--The two source clocks are both converted from 100-ns QPC: WGC-`SystemRelativeTime` and WASAPI `IAudioCaptureClient::GetBuffer`'s-`pu64QPCPosition`. Keep timestamps monotonic and derive audio duration from-the captured frame count (960 samples at 48 kHz for each 20 ms packet), not-from bridge arrival time. `TrackLocalStaticSample.Timestamp` is not the source-timeline control in the current Pion path; the audio fanout therefore uses the-same explicit RTP packetizer/timeline pattern as native video.--The slice fails closed. Windows 10, unsupported WGC, picker cancellation,-activation denial, an exited/inaccessible target, `AUDCLNT_E_DEVICE_INVALIDATED`-or `AUDCLNT_E_SERVICE_NOT_RUNNING`, protected-content silence, and a missing-render stream produce `audio unavailable` or `audio silent`. There is no retry-to whole-system loopback. No administrator privilege is required, but the-helper must run in the interactive user's session and honor Windows consent and-privacy settings. PID, creation token, title, path, device identity, and PCM-remain local.--The first smoke is one direct Viewer: a test window emits a known tone and-visual marker, while an independent voice process and notification emit-different markers. Require an Opus inbound track and rendered video/audio,-monotonic QPC timestamps, and a bounded A/V offset; verify the unrelated-markers are absent and that target exit/silence stops or asks without widening-capture. SFU/UDP, second Viewer, and endurance remain follow-up gates; paired-WGC video completion is recorded below. On 2026-08-21, 100 20-ms chunks isolated a 440 Hz target from-an independent 880 Hz process by 4017.8x. Chrome 151 then received one audio-track and 495 inbound Opus packets while video decoded/rendered 296 frames.--## P1 WGC/MF Completion+## Consequences-The paired native-video source reuses the proven hardware fixture rather than-adding a second encoder framework. WGC creates a capture item directly from the-bound HWND on the selected D3D11 device. The frame pool is free-threaded and is-recreated on content-size changes. D3D11 VideoProcessor performs aspect-fit-BGRA-to-NV12 conversion at fixed 1280x720/30, then the existing adapter-bound,-hardware-only asynchronous MF H.264 path emits Annex-B `42c01f` access units.-There is no software MFT, alternate codec, monitor, or browser-video fallback.+Positive:-The helper multiplexes process-tree PCM, H.264 access units, and bounded local-status. Go writes H.264 directly to the existing shared fanout; the browser UI-receives only a one-way local copy for `VideoDecoder` preview. PCM retains the-existing WebCodecs Opus bridge. PLI/FIR recovery is generation-bound and-coalesced into a helper key-frame command. The normal browser source uses its-independent Browser codec path; the native H.264 source remains an explicit mode-and is not an implicit runtime downgrade.+- Web capture stays on standard permission and track APIs;+- audio absence and privacy scope are represented honestly; and+- current audio quality controls do not require another media graph.-## Consequences+Negative:-- Current Web users get a useful Chromium hint and an honest status without a- privacy claim the platform cannot support.-- Strict per-window audio is a native Windows 11 feature, not a browser promise- or a silent system-audio fallback.-- The helper is packaged beside the sender in a commit-bound evaluation ZIP.- The ZIP carries internal and external SHA-256 manifests plus exact linked Go- dependency license files; it is neither an installer nor a release.+- Browser/system combinations remain inconsistent;+- Web cannot promise per-process isolation; and+- strict application-audio capture requires a later native product decision.-## Remaining Evidence Boundary+## Primary Sources-- A second Viewer, SFU/UDP, endurance, and real-game A/V sync remain unproven;- the one-Viewer H.264 and attributed `VideoEncode` gate passed.-- The short-lived Windows x64 evaluation artifact is retained evidence, not an- instruction to download or run it. Native release work remains at the bottom- of the single project TODO ledger and still requires license, signing, and its- own acceptance boundary.+- [Screen Capture](https://www.w3.org/TR/screen-capture/)+- [Media Capture and Streams](https://www.w3.org/TR/mediacapture-streams/)+- [Windows application loopback](https://learn.microsoft.com/en-us/samples/microsoft/windows-classic-samples/applicationloopbackaudio-sample/)+- [Windows Graphics Capture](https://learn.microsoft.com/en-us/windows/apps/develop/media-authoring-processing/screen-capture)+- [WASAPI process-loopback activation](https://learn.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ns-audioclientactivationparams-audioclient_process_loopback_params)diff --git a/docs/deployment.md b/docs/deployment.mdindex 4b923fe3..e85e7adc 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -1,572 +1,115 @@-# Minimal Deployment+# Application Release And Recovery-Last verified: 2026-08-27.+This file owns routine immutable application releases. Initial service setup is+in [self-hosting operations](./operations/self-hosting.md); environment and ports+are in [configuration reference](./reference/configuration.md); exact current+production identity is owned only by [status](./status.md).-This page records production running exact deployed application/runtime revision-`73ed920a229bfc64c89b97045c00d6cd75216f3a`, release `73ed920`, and the single-Browser `screener-v13` contract. Product direction and pending work are owned by-[project memory](./project-memory.md) and [the TODO ledger](./todo.md).+The tracked `release-app.sh` is the updater for the current bare-metal nginx,+LiveKit, coturn, nftables, and local-port-8787 deployment. It requires an+existing current release. Another proxy, optional-LiveKit shape, firewall owner,+application port, or first installation needs its own scoped bootstrap/updater;+do not call this wrapper generic.-This section documents the accepted UDP-only deployment contract: one Node.js-process provides the built Web client, room API, and WebSocket signaling behind-Caddy or nginx; ordinary peer ICE advertises only STUN, while Browser LiveKit-PCs configure no external ICE server and retain LiveKit-signaled UDP candidates.-LiveKit supplies bounded SFU capacity. Normal media remains distributed-through direct or peer edges whenever those paths work. Production includes-Browser SFU ICE isolation and leaves representation construction and selection-to pinned LiveKit with Dynacast and server send-side BWE.+## Release Boundary-A deployment may additionally provide one dedicated single-node LiveKit process-as the current controller's automatic final media fallback. This capacity is-dormant unless the complete public URL, private API URL, key, secret, and capacity-tuple is configured. It does not replace the P2P path,-the peer-assisted experiment, or required STUN discovery. LiveKit remains-ICE/UDP only. Ordinary peer ICE remains STUN-only and production coturn uses the-tracked STUN-only configuration with TCP/TLS disabled. The source and production-configure no TURN, ICE/TCP, media TCP, or TLS-relayed media.+A routine application release changes only the built Screener client/server and+its independent runtime dependency tree. It does not change infrastructure,+service units, proxy/firewall rules, secrets, LiveKit/coturn configuration, or+persistent room state.-Production runs exact `73ed920a229bfc64c89b97045c00d6cd75216f3a`, release-`73ed920`, from `/opt/screener/releases/73ed920`. The immutable runtime tar-SHA-256 is-`351053e497e8eee17956f4cec86305b05d805c80deb40b2cf4cd2668eaf08583`.-Its 41-file path/size/hash manifest SHA-256 is-`bb993950a30a0b99b9b6185aa13777edcccbdcdaebdfb1b05b3c3499a1e78479`.-Local and public `/healthz` return 200; Screener, LiveKit, coturn, and nginx are-active with `NRestarts=0`. The public main Browser asset is-`assets/index-CaM3Pn5_.js` with SHA-256-`3c64cd75a7d67716f7600465a1742b1c02f3b00e71a1039649604aaf6d08f816`.+Any task that touches one of those excluded surfaces must first record its exact+pre-change value and a recovery procedure for that surface. Do not complicate the+routine application wrapper with one-off infrastructure branches.-The release deploys the single Browser `screener-v13` wire and one internal,-content-independent H.264 sender gate with VP8 fallback across Browser direct,-browser-relay, and SFU video. It retains pinned LiveKit default screen-share-representations, Dynacast and server send-side BWE without an application layer-selector, video `contentHint = "motion"`, and a local share-locked-`VP8 | Auto | H264` Host selector without codec wire state. Random four-digit-rooms use a 24-hour dormant lease, one room-lived 22-character grant,-orthogonal `open | private` grant/code admission,-20-Viewer room admission, the uniform endpoint media-copy cap `2`, and the-one-controller exact-candidate route runtime. Production configures-`ROOM_DATABASE_PATH=/var/lib/screener/rooms.sqlite`; systemd owns that single-`0700` StateDirectory and the database is `0600`. Only room authority survives-an application restart; participants, routes and media rebuild from fresh-process state.-LiveKit is dedicated, has `room.auto_create: false` and-`max_participants: 21`, and the application derives deployment admission as-9,000 publication ingress plus `9000 * MAX_VIEWERS_PER_ROOM` subscription-egress handles. Coturn listens only on UDP 3478 for STUN;-LiveKit media listens on UDP 7882. The stable application firewall table-`inet bonfire_filter` has SHA-256-`afaf9d066e9f292d8bd19032b38c0978ccf60dd01c2fe7f210968ff751f90534`,-and `/etc/nftables.conf` has SHA-256-`d57cab70b455e6ddd5cd4688c354b9af5e1d4fb9e9b67c6b85ade0da347cb1d0`;-the whole live ruleset is not a stable identity because fail2ban owns a dynamic-address set.-These bounds are fail-safe admissions, not throughput or quality claims.-The retained local 20-Viewer Browser smoke and open real-network boundaries are-owned by [verification status](./verification-status.md).--## Topology and prerequisites--Use two DNS names, for example `share.example.com` and `stun.example.com`. They-may resolve to the same public IP: the Web ingress owns TCP 443 while the-self-hosted STUN listener owns UDP 3478.--```text-browser -- HTTPS/WSS --> Caddy or nginx :443 --> Node.js :8787-browser <------------ DTLS-SRTP P2P ------------> browser-browser -- ordinary-peer STUN/UDP --> coturn :3478-browser <---------- DTLS-SRTP/UDP ----------> LiveKit :7882-```+The pre-cutover application release is guaranteed only through bounded health+and postflight. It has no retention contract afterward and is not a maintained+backup; Git and immutable artifacts own history.-The minimum runtime is Node.js 24 LTS and coturn 4.17.2 or a newer patched-release. Provision a valid TLS certificate for the Web name. Enable operating system time-synchronization and keep the Node application port reachable only from its-reverse proxy. A single Node process is intentional. Participants, signaling,-routes and media remain in process memory; optional SQLite preserves only room-authority and does not restore live WebRTC connections.+## Build Host-Build and validate the exact revision on a build host before starting it:+Start from a clean exact revision with Node.js 24 and npm 11:```shnpm cinpm run check-npm start+npm run build+node scripts/package-app-release.mjs <output-directory-outside-repository>```-Do not run the repository full check, typecheck, or build on the current 960 MiB-no-swap production host. An inactive-release check before the `261e980c` cutover-temporarily starved HTTP and SSH; exact `691863e` remained current and all four-services stayed at `NRestarts=0`. The retained production path uses a locally-verified dist artifact plus one `npm ci --omit=dev --ignore-scripts --no-audit --no-fund`-in a transient unit bounded to 30% CPU, 160 MiB memory high, 256 MiB memory max,-no swap, and 120 seconds. It then runs only runtime imports and the-artifact/inode/permission gates.--Each immutable release must own an independent dependency tree. Never hard-link-`node_modules` or another file that deployment may `chown`, `chmod`, replace, or-remove: metadata changes would also mutate another immutable release. A copy or-copy-on-write reflink is acceptable only after an inode audit confirms that the-old and new regular-file sets have zero shared inodes. Do not recursively change-permissions until that check passes.--Routine application releases use the tracked-[`package-app-release.mjs`](../scripts/package-app-release.mjs) build-host entry-and [`release-app.sh`](../deploy/release-app.sh) server entry. The packager accepts-only a clean exact Git revision and already-built `dist`, emits one normalized-`tar.gz`, an exact path/size/hash manifest, and a non-secret release descriptor,-then extracts and verifies its own result. The archive also carries the full Git-revision. The server entry accepts only that descriptor, verifies the uploaded-hashes and revision, extracts into a new release directory, compares the exact-regular-file set with the manifest, installs an independent runtime dependency-tree under the existing resource bounds, and performs the atomic cutover and-bounded recovery checks. Release-specific scripts must not be copied and edited.--Infrastructure, configuration, secrets, and persistent state are outside this-application wrapper. A release that changes one of those surfaces uses a separate-scoped transaction with its own pre-change value and recovery path; it must not-make the routine application primitive conditional on that one-off change.--A routine application-only cutover leaves infrastructure, configuration, secrets,-and persistent state untouched. Verify a new immutable artifact, switch to it-atomically, and guarantee the pre-cutover application release only through-bounded health and postflight checks. It has no retention contract afterward and-is not a maintained backup. When a task actually changes infrastructure,-configuration, secrets, persistent state, or an irreversible surface, define and-verify recovery only for the touched surfaces before changing them.--In a strict-shell deployment, expected service states are data, not command-failures. Do not call `systemctl is-active` bare under `set -e`/`ERR`: an-intentionally stopped service returns a nonzero status and can trigger a false failure path. Read-`ActiveState` with `systemctl show`, compare the returned string explicitly, and-keep stop, symlink switch, start, health check, and any release restoration as-separate steps. Preflight every inspection dependency before changing a-service. After a start, poll health for a short bounded window instead of treating-one request during startup as a-failed release; retain the last failure while still enforcing the deadline.-After starting coturn, likewise wait boundedly for its UDP 3478 socket before-asserting STUN readiness; `ActiveState=active` can precede socket readiness.--Run `npm start` under a service supervisor that injects the environment, restarts-on failure, and applies bounded logs. For a simple untracked environment file,-the equivalent direct launch is-`node --env-file=.env.production dist/server/server/index.js`. Do not expose port-8787 to the Internet. The application default is `0.0.0.0` for LAN development-and container compatibility, while the bare-metal production baseline below-explicitly sets `LISTEN_HOST=127.0.0.1` because only the same-host reverse proxy-should connect. A container can instead use `0.0.0.0` and enforce the intended-boundary with port publishing rules or a host firewall.--The optional same-host LiveKit layout needs no additional public hostname:-`LIVEKIT_URL=wss://share.example.com` and nginx proxies only current `/rtc/v1*`-requests to LiveKit. Retired `/rtc` and `/rtc/validate` endpoints return 404-without request-target logging. LiveKit's HTTP/WebSocket listener on TCP 7880 is-private to nginx and the Screener process uses-`LIVEKIT_API_URL=http://127.0.0.1:7880` for `RoomService`; WebRTC media reaches-LiveKit directly on UDP 7882. No unrelated application may create rooms on this-instance, and its tracked configuration sets `room.auto_create: false`.-Install-[`screener-livekit-readiness.conf.example`](../deploy/systemd/screener-livekit-readiness.conf.example)-as a `screener.service.d` drop-in on this layout. `After=` orders the services,-while the bounded `ExecStartPre` waits for TCP 7880 readiness; ActiveState alone-does not prove the LiveKit control listener is accepting connections.--## Candidate boundary and recovery--The accepted target for `share.bonfire.icu` remains distributed and automatic:-direct/peer UDP first, with one Host publication available to authorized SFU-subscriptions when a logical edge cannot use peer transport. SFU-fed and-peer-fed endpoints use the same provisional-child transaction, and the exact-candidate child's first newly decoded frame commits that edge. Server-assisted-subscriptions and allocations use independent deployment admission rather than-an endpoint-cap or fixed-root rule.--The repository requires STUN and ordinary peer connections receive STUN-only-ICE. An existing logical edge prefers direct/peer UDP; the only application-suffix is the Host publication/SFU path. LiveKit participants receive only-revision-bound `sfu-config` URL/token messages and negotiate within LiveKit's-separate UDP-only ICE domain. The accepted Browser publisher and subscriber-connect contract provides an explicit empty ICE-server list, retains the UDP-candidates delivered through LiveKit signaling, and lets standard ICE select a-nominated non-relay pair. Candidate type, count, address family, and Browser-socket allocation remain implementation observations. This does not remove-ordinary-peer STUN or the deployment STUN used by LiveKit to discover its own-public address.+The packager refuses a dirty tree, records the full revision, emits a runtime+archive plus path/size/SHA-256 manifest and release descriptor, and+extracts its own artifact to verify it. Upload the archive, manifest, and+descriptor together to `/opt/screener/uploads`.-`PEER_ASSISTED_MEDIA=true` is the process-wide topology/SFU switch. Every normal-room gets its own bounded controller state and ordinary peer connections remain-STUN-only. Run route or infrastructure candidates on an isolated-instance/hostname and keep the current release unchanged. If the candidate fails,-stop it and restore only the recovery boundary defined for its changed surfaces;-do not add a permanent dual-transport branch.+Do not build or run the full repository check on a constrained production host.+The release wrapper installs only production dependencies in a transient,+CPU/memory/time-bounded unit.-A memory-room release starts with empty process authority. Starting the candidate-invalidates every current production room, Host token, invitation, password-verifier, and route; open pages must refresh or explicitly create a replacement-room. No room state crosses a release boundary in either direction. Guarantee the-pre-cutover immutable application release only through the bounded postflight; it-has no retention contract afterward and is not a maintained backup. An-application-only cutover leaves the environment, unit, LiveKit, coturn, firewall,-and reverse proxy unchanged; any task that changes one of those surfaces must-establish its scoped recovery before the change.+## Atomic Cutover-A shared-public-IP instance can test candidate behavior, but it cannot prove the-clean-port boundary or approve broad migration. The room-1 smoke uses this-shape: nginx owns 443, LiveKit 1.13.5 owns UDP 7882, and LiveKit is fail-closed under a 192 MiB-high/256 MiB hard cgroup limit with restart disabled. Prefer a separate VM/IP-for the full gate and verify representative external networks and devices.--Coturn provides STUN binding only and must reject allocation requests.-HTTPS/WSS always remains TLS/TCP independently of the UDP-only media ladder.--## Production application environment--Keep the real values in the process secret store or an untracked, access-restricted-environment file. Node.js 24 can load such a file with `--env-file`; the tracked-`.env.example` is only a schema. Generate independent secrets with a password-manager or a cross-platform Node command such as:+Run the tracked server entry with the uploaded descriptor:```sh-node -e "console.log(require('node:crypto').randomBytes(32).toString('base64url'))"-```--Use this production baseline template:--```dotenv-NODE_ENV=production-LISTEN_HOST=127.0.0.1-PORT=8787-PUBLIC_BASE_URL=https://share.example.com-ALLOWED_ORIGINS=https://share.example.com-SITE_ACCESS_PASSWORD=<INDEPENDENT_8_TO_128_BYTE_ACCESS_KEY>-ROOM_LEASE_SECONDS=86400-ROOM_DATABASE_PATH=/var/lib/screener/rooms.sqlite-MAX_VIEWERS_PER_ROOM=20-ENDPOINT_MEDIA_COPY_CAPACITY=2--STUN_URLS=stun:stun.example.com:3478-```--To make automatic SFU fallback capacity available, add the complete tuple:--```dotenv-PEER_ASSISTED_MEDIA=true-LIVEKIT_URL=wss://share.example.com-LIVEKIT_API_URL=http://127.0.0.1:7880-LIVEKIT_API_KEY=<GENERATED_LIVEKIT_API_KEY>-LIVEKIT_API_SECRET=<INDEPENDENT_SECRET_OF_AT_LEAST_32_BYTES>-```--Supplying any stale `PEER_ICE_TURN_*` or `SELECTED_EDGE_TURN_*` key, even blank,-fails startup. Production contains none of those keys, uses the tracked-STUN-only coturn configuration, and keeps TCP 3478/5349 plus every relay range-closed. An application-only release leaves the environment, coturn configuration,-and firewall unchanged; a task that changes any of them must define recovery for-that exact set before modification.--`PEER_ASSISTED_ROOM_IDS` is retired. Supplying it, even blank, fails startup so-that a stale room-1 deployment cannot silently retain the old scope. With-`PEER_ASSISTED_MEDIA=true`, every normal room receives peer-assisted routing,-optional LiveKit fallback, and the same deployment resource/fanout/failure guards.-Every ordinary peer connection remains STUN-only. There is no browser control,-percentage rollout, or second router.--`ALLOWED_ORIGINS` must list exact `http` or `https` origins, never `*`.-`SITE_ACCESS_PASSWORD` is required in production and must contain 8 through-128 visible ASCII bytes (`0x21` through `0x7e`). It must not be reused for-LiveKit, TLS, or another service. It authorizes room creation, Host role,-and code-only Viewer attempts; it does not replace a private room grant or-password. Local development and tests may omit it. Supplying a removed access-key, even blank, fails startup.-`ROOM_LEASE_SECONDS` defaults to 86,400 seconds and owns the dormant room-lifetime. An actively connected Host prevents expiry; explicit stop or Host-disconnect starts the lease, and only the exact Host token renews it before-expiry. Viewer activity never renews ownership. Optional `ROOM_DATABASE_PATH`-enables the exact-schema SQLite stable room-authority mode; unset keeps the-lightweight memory mode. `ROOM_TTL_SECONDS` remains invalid.-Production accepts 1 through 20 and explicitly selects 20. This is an-admission limit, not evidence that every publisher, network, or quality profile-can sustain that many streams.-`ENDPOINT_MEDIA_COPY_CAPACITY` defaults to 2 and accepts only 1, 2, or 3. It is-the single server-authoritative steady outbound media-copy cap for Host and-Viewer endpoints; role, browser, UA, and visibility do not create another tier.-A peer child or the Host's single SFU publication consumes one copy and upstream-receive is free. Transition work-may reach only `min(C + 1, 3)`. A Host already sending three copies at `C=3`-must fail or wait before a fourth endpoint copy is issued.-Supplying the removed `MAX_PEER_RELAY_DOWNSTREAM_EDGES`, even blank, fails-startup.--Production release `73ed920` runs the deployed server and Browser assets-atomically on `screener-v13`; every stale Browser or executable-sender wire fails-before room authority. Native senders and helpers are outside this release.--The four `LIVEKIT_*` values must either all be absent or all be present, and a-complete tuple requires `PEER_ASSISTED_MEDIA=true`. The four-digit code space-fixes ingress at 9,000 Host publications; egress is 9,000 multiplied by-`MAX_VIEWERS_PER_ROOM`. There is no separate SFU capacity configuration. An-empty tuple keeps the optional SDK and server path dormant. `LIVEKIT_URL` must be a-plain `ws:` or `wss:` origin with no `/rtc` suffix; production requires `wss:`.-`LIVEKIT_API_URL` must be a plain `http:` or `https:` origin with no path;-production permits plaintext only on loopback and otherwise requires `https:`.-`LIVEKIT_API_SECRET` must contain at least 32 bytes and must not reuse-`SITE_ACCESS_PASSWORD`. These credentials authorize short-lived LiveKit room-tokens and do not provide E2EE: the LiveKit operator can access ordinary SFU-media. The LiveKit instance is dedicated to this Screener process and has-`room.auto_create: false`. Screener first binds the configured application-listener exclusively; a competing process that cannot bind makes no LiveKit-call. While bound but not initialized it returns `503` and has no signaling-upgrade handler. It then rejects any foreign room name, deletes every stale-managed room, confirms the namespace empty, and begins serving. Each-exact-generation room is then created before its token is issued. Reserved,-committed, and draining generations remain charged until-`DeleteRoom` succeeds and a follow-up lookup proves absence. Run only one-application process until a shared atomic admission and lifecycle owner exists.--For the first candidate canary, use an isolated instance and one recorded room.-Restart the application, verify startup removes the now-stale managed LiveKit-room before serving traffic, and create a fresh application room after startup.-Hold the application port with another process and verify a competing-startup makes zero LiveKit calls. Verify that both the replacement room and a-second normal room contain-`mediaMode: "peer-assisted"`, with independent route revisions and no shared-room state or capacity bypass. Exercise join, offer and answer, stale-token-reconnect after abort, Host signaling loss with and without a live Host-participant, stop, restart, and room deletion in both rooms. Confirm each drain-keeps capacity charged until the room is absent. Ordinary Web clients remain-STUN-only. Roll back by stopping Screener, proving every managed LiveKit room-absent, and restoring the exact recorded application environment, application-release, LiveKit configuration, coturn configuration, and firewall snapshot as-one unit; or direct traffic to the unchanged old instance. During migration,-remove retired route configuration in the same coherent change; the process-flag explicitly enables the all-room controller.--Only `POST /api/site-access` accepts the site access secret in an-`Authorization: Bearer` header from an exact allowed Origin. Success returns a-12-hour stateless HMAC-SHA256 cookie with `HttpOnly`, `SameSite=Strict`,-`Path=/`, bounded `Max-Age`, and, under production HTTPS, `Secure` plus an-`__Host-` name. The cookie contains no account or server-side session ID. There-is no account database, JWT, session map, or logout endpoint.--Before an access-boundary release, set `CHROME_PATH` to a local Chrome or-Chromium executable and run `npm run gate:access-privacy`. The gate creates a-loopback in-memory room with an isolated browser profile, navigates the fragment-through CDP rather than a process argument, disposes that context, and emits only-fixed booleans and counts. It checks tracked request/nginx/application logs,-browser storage, fragment cleanup, absence of a persistent room file, and runs-the complete signaling suite containing the strong rotate/revoke teardown case.-It never connects to production or accepts a production credential; exact-production request/nginx/journal inspection remains separate.--nginx limits this exact endpoint per source at `5r/m` with `burst=5 nodelay` and-returns 429 when exhausted. The limiter uses nginx shared memory; do not add the-secret, Authorization header, request body, or a new source-address field to-logs. `POST /api/rooms` accepts only the site-access cookie and strict JSON-with an explicit code-entry policy and optional room password; a Bearer header-is not an alternate creation-path. `/signal` still admits a cookie-free browser after Origin and capacity-checks and records the cookie state at upgrade. Host requires it with the room-Host token. A Viewer may omit it only when presenting a valid, unexpired grant-for that exact room; otherwise the server rejects before evaluating code entry.--Every room receives an independent invitation-`/r/{code}#v={room-scoped-grant}`; the fragment does not enter HTTP or WebSocket-request targets. The page validates it, writes it only to that room's-`sessionStorage`, and immediately replaces the visible URL with `/r/{code}`.-The Host may update or revoke that grant without changing code-entry policy.--Room allocation and lifetime use one deliberately small model:--- random unallocated codes come only from `1000` through `9999`, never duplicate- an active code, use the fixed 9,000-room capacity, and return on room release;-- active Host sharing does not expire; stop, capture-track end, or Host- disconnect starts `ROOM_LEASE_SECONDS`;-- only the exact Host token resumes and renews before expiry, Viewer activity- cannot, and expiry invalidates the code, credentials, verifier, participants,- and routes; and-- lightweight-mode process restart has the same fail-closed effect; stable mode- restores only unexpired room authority and requires fresh sessions/routes.--The server keeps only digests/verifiers for Host tokens, Viewer grants, and-optional room passwords. In stable mode those room-authority values, policy,-authorization generation and lease use one exact SQLite schema; live members,-routes and SFU state remain memory-only. The same browser keeps its raw Host token,-creation profile and non-expiring preferred code locally. Production stable-mode-uses the service-owned `/var/lib/screener` StateDirectory. Any new activation or-path change requires a separately verified writable directory plus configuration-and database backup/restore boundaries before changing `ROOM_DATABASE_PATH`.--Production startup requires one to eight syntactically valid `stun:` URLs-before the server listens. This validates shape only; it does not prove DNS,-firewall, NAT mappings, or external STUN reachability. The current application-rejects `TURN_URLS`, `TURN_SHARED_SECRET`, or `TURN_CREDENTIAL_TTL_SECONDS` when-any key is present, including with an empty value. Remove those obsolete keys-from the candidate environment; startup fails instead of pretending they enable-compatibility.--The rejected `PEER_ICE_TURN_*` and `SELECTED_EDGE_TURN_*` candidate names must-remain absent from production and fail startup even when blank. Ordinary peer-edges remain STUN-only and the application has no TURN configuration surface.--## HTTPS and WSS ingress--Terminate public TLS at Caddy or nginx and proxy every application path to the-single Node process. `/signal` must preserve the WebSocket upgrade, `Host`, and-`Origin`, and its idle/read timeout must be longer than a normal sharing session.-Do not cache `/api/*` responses. Caddy's minimal same-host form is:--```caddyfile-share.example.com {- reverse_proxy 127.0.0.1:8787-}-```--An equivalent nginx location is:--```nginx-location / {- proxy_pass http://127.0.0.1:8787;- proxy_http_version 1.1;- proxy_set_header Host $host;- proxy_set_header Upgrade $http_upgrade;- proxy_set_header Connection "upgrade";- proxy_read_timeout 1h;-}+sudo env SCREENER_PUBLIC_ORIGIN=https://share.example.com \+ /path/to/repository/deploy/release-app.sh \+ /opt/screener/uploads/screener-<revision>.release.json```-The tracked-[`share.bonfire.icu.conf.example`](../deploy/nginx/share.bonfire.icu.conf.example)-follows this simple model and listens directly on public TCP 443. It does not-need an SNI transport router. Exact `/rtc` and pinned-v0 `/rtc/validate` requests-return 404 with access and request-line error logging disabled; only `/rtc/v1*`-is proxied. Current versioned requests carry a short-lived LiveKit JWT in the-query string, so no `/rtc*` target may fall through to the site's ordinary logs.--When Certbot manages the Web certificate, install the tracked-[`reload-nginx.sh`](../deploy/certbot/reload-nginx.sh) as an executable under-`/etc/letsencrypt/renewal-hooks/deploy/`. Run `certbot renew --dry-run` after-the first certificate is installed. This hook reloads only the Web ingress.--Keep the proxy's access-log retention bounded and access controlled. Requests to-`/r/{code}` put the room code in the path, so access logs can contain room codes-as well as network metadata. They must not be treated as public artifacts. For-a private room, the grant remains in the fragment and is not part of that-request target.--For a process-level liveness probe, send `GET /healthz`. A running process-returns HTTP 200 with `{"status":"ok"}` and `Cache-Control: no-store`; other-methods return 405 with `Allow: GET`. The endpoint does not inspect room state,-STUN/SFU reachability, or any external dependency, so use it only to decide whether-the Node process can accept HTTP requests. It is not a deployment-readiness or-end-to-end media check.--## Optional single-node LiveKit fallback--Use the tracked-[`livekit.yaml.example`](../deploy/livekit/livekit.yaml.example) and-[`livekit.service.example`](../deploy/systemd/livekit.service.example) as the-minimal single-node baseline. Install a reviewed, pinned LiveKit Server release-from its official release assets, generate an independent key pair with-`livekit-server generate-keys`, and place only the YAML key mapping in-`/etc/livekit/keys.yaml`. Keep that file owned by the `livekit` service account-with mode `0600`; put the same values in Screener's untracked process secrets.--The example deliberately omits Redis and every recording, ingress, egress,-webhook, external-TURN, and embedded-TURN service. It explicitly sets-`tcp_port: 0` and `allow_tcp_fallback: false`, and points `stun_servers` at the-deployment's self-hosted STUN listener for server-side public-IP discovery and-to prevent pinned LiveKit from substituting a public default in its join-response. Current Screener source gives Browser publisher/subscriber connects an-explicit empty list, so those SFU PCs do not use either response after the-pending application cutover. The tracked `rtc.congestion_control` enables-`use_send_side_bwe` for LiveKit-owned per-subscriber simulcast selection. Do not-add Redis for this one-node workload.-The service journal is the diagnostic log; keep its retention finite and access-restricted. Pinned LiveKit 1.13.5 includes raw PublisherOffer SDP in info-level-join records, so the tracked production baseline uses `logging.level: warn` and-`pion_level: error`. Raise either only in an isolated, short-lived canary and-remove its journal afterward. Never persist JWTs, SDP, ICE candidates, API-secrets, or full `/rtc` and `/rtc/*` request targets.--Configure both the host firewall and the provider firewall independently:--| Destination | Protocol | Exposure | Purpose |-| --- | --- | --- | --- |-| `127.0.0.1:7880` | TCP | Private | nginx to LiveKit signaling/API |-| public host `:7882` | UDP | Public | WebRTC ICE/UDP mux |--LiveKit may listen beyond loopback while it discovers and advertises public-media addresses, so the public-firewall denial of TCP 7880 is mandatory; nginx-must be its only ingress. UDP 7882 is a direct media listener and must not be-placed behind the HTTP reverse proxy. If the host is behind NAT, forward it-without port translation and verify the advertised candidate from an external-network. UDP-blocked networks are expected to fail clearly in this candidate;-do not set `rtc.tcp_port` above zero, enable TCP fallback, or add TURN to make a-canary pass silently.--## Self-hosted STUN--This subsection describes the accepted and deployed STUN-only boundary.-Production uses the tracked configuration and keeps TCP 3478/5349 plus every-relay range closed.--Copy [`deploy/coturn/turnserver.conf.example`](../deploy/coturn/turnserver.conf.example)-to an untracked service-owned location and use the tracked-[`coturn.service.example`](../deploy/systemd/coturn.service.example). The config-uses coturn's documented `stun-only` mode, ignores every TURN allocation request,-and disables TCP and TLS client listeners. It has no auth secret, user database,-relay port range, certificate, quota, or TURN REST credential. Pinned coturn-4.17.2 deprecates `no-dtls`, so the tracked config does not use that obsolete-switch or claim a separate DTLS listener gate.+The wrapper:++1. takes a deployment lock and validates the descriptor, revision, archive,+ manifest, current release, required services, and public origin;+2. rejects unexpected archive paths, links, file types, or duplicate inodes;+3. extracts to a new release directory and verifies every file hash and size;+4. installs an independent `node_modules` tree under resource limits and checks+ runtime imports plus production configuration;+5. proves the old and new releases share no regular-file inode;+6. atomically switches `/opt/screener/current`, starts the service, and polls+ bounded local/public health; and+7. restores the exact prior symlink and service when cutover or health fails.++Never hard-link dependency trees or recursively mutate permissions before the+inode audit: metadata changes would violate both releases. Expected service+states should be read as data (`systemctl show`), not used as bare commands under+strict-shell error traps.++## Persistent State++Stable mode stores only room authority at the configured SQLite path. The+systemd service owns its state directory and file permissions. Application+restart retains room ownership, invitations, policy, password verifier, and+lease; participants, signaling, routes, SFU state, and media reconnect from fresh+process state.-On a single-homed public host, automatic listener selection is sufficient. On a-multi-homed host, set `listening-ip` to the intended public interface. Open only-UDP 3478 and keep TCP 3478/5349 plus every old relay range closed. The same public-IP may serve HTTPS/WSS on TCP 443 and LiveKit media on UDP 7882.+Lightweight mode has no persistent room state and starts empty. A release does+not add a migration or compatibility reader for either mode; current exact+schema validation fails closed before signaling or LiveKit mutation.-The example writes informational logs to stdout. Apply finite supervisor-retention and restrict access because STUN sees client IP addresses. Do not-enable `verbose` or `log-binding` continuously. `stun-only` is a hard candidate-boundary, not a hidden unauthenticated TURN service.+## Postflight-Open only these public listeners:+Verify only the surfaces relevant to the release:-| Destination | Protocol | Purpose |-| --- | --- | --- |-| `share.example.com:80` | TCP | HTTP redirect and ACME challenge |-| `share.example.com:443` | TCP | HTTPS and WSS |-| `stun.example.com:3478` | UDP | STUN binding only |-| host public address `:7882` | UDP | LiveKit WebRTC ICE/UDP mux |+- local and public `/healthz` return `{"status":"ok"}`;+- the public HTML references the new immutable main asset;+- Screener, nginx, coturn, and LiveKit have expected active/restart+ state;+- the current symlink and served revision match the descriptor;+- room creation, Host authentication, one direct Viewer, and configured SFU+ fallback complete the scoped smoke; and+- infrastructure, config, secrets, ports, and persistent state not named by the+ task are unchanged.-## Verification+Representative network, mobile, audio, 20-Viewer, and endurance evidence belongs+to [verification status](./verification-status.md), not routine postflight.-Run these checks from real external networks before closing route acceptance:+## Recovery-1. Open the official [Trickle ICE sample](https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/)- and test the configured STUN URL. It must produce an `srflx` candidate over- UDP and no `relay` candidate. Confirm TCP 3478/5349 and the old relay range- are closed externally.-2. Create a normal Screener room on two different networks. Confirm media flows- and the selected-pair stats report a non-relay path when direct ICE succeeds.-3. On a normal room, exhaust a peer route and verify exactly one Host- publication serves only the admitted SFU subscriptions over LiveKit UDP 7882.- Peer descendants stay on ordinary direct UDP and every non-server endpoint- obeys the configured `ENDPOINT_MEDIA_COPY_CAPACITY`. On each Browser SFU PC,- verify no local external STUN/TURN server is configured, a nominated- non-relay UDP pair reaches an authorized LiveKit-signaled SFU candidate, and- the exact Viewer presents a decoded frame. Do not gate on candidate type or count.-4. Block all UDP and verify bounded recovery ends clearly without ICE/TCP,- TURN, or a long pseudo-connected path.-5. Exercise root departure, reconnect, SFU unavailable, route prepare rollback,- stop, and source/profile changes. Unaffected subtrees must not migrate.-6. Repeat at 1, 3, 5, and 20 viewers across representative consumer networks.- Record selected protocol, RTT, bitrate, frame rate, packet loss, publisher- upload/encode load, LiveKit ingress/egress, and final decoded quality. A real- public-network 1:20 session remains unverified; the passed local synthetic- 1:20 smoke does not replace this heterogeneous-network quality gate.+Before cutover, the wrapper keeps the exact prior release path. On failure after+the switch begins, it stops Screener, restores that path atomically, restarts the+service, and waits for health. A failed recovery exits distinctly and requires+operator intervention; it must not silently report the new release as active.-References: [coturn 4.17.2 release](https://github.com/coturn/coturn/releases/tag/4.17.2),-[pinned turnserver documentation](https://github.com/coturn/coturn/blob/4.17.2/README.turnserver),-the [pinned example configuration](https://github.com/coturn/coturn/blob/4.17.2/examples/etc/turnserver.conf),-[RFC6265bis](https://datatracker.ietf.org/doc/draft-ietf-httpbis-rfc6265bis/),-[LiveKit firewall guidance](https://docs.livekit.io/deploy/admin/firewall/), and-the [pinned LiveKit configuration sample](https://github.com/livekit/livekit/blob/v1.13.5/config-sample.yaml).+Infrastructure or persistent-state recovery is separate and limited to the+surfaces changed by that task. Do not restore an entire server, old firewall, or+old secret set for an application-only failure.diff --git a/docs/maintenance.md b/docs/maintenance.mdindex f52d2cd8..e9edd1ee 100644--- a/docs/maintenance.md+++ b/docs/maintenance.md@@ -12,34 +12,34 @@| --- | --- | --- || 每次都必须遵守的硬约束和导航 | `AGENTS.md` | 保持短、单义、稳定;不复制流程手册或临时状态 || 分支、研究、验证、PR、合并和清理流程 | `CONTRIBUTING.md` | 维护可执行的日常流程 |-| 当前产品事实和长期决定 | `docs/project-memory.md` | 就地更新,最多 200 行且不超过 16 KB |-| 当前生产、里程碑、阻塞项和明细索引 | `docs/status.md` | 只保留 current/index,最多 120 行且不超过 12 KB |+| 产品总览和领域导航 | `docs/project-memory.md` | 只保留每次 substantial task 都需要的摘要与链接 |+| 当前生产、里程碑、阻塞项和明细索引 | `docs/status.md` | 只保留 current/index;接近 120 行或 12 KB 时提示园艺审查 || 当前未决、已授权或待用户决策的工作 | `docs/todo.md` | 不是完成记录;不把 checkbox、实验或 agent 建议自动升级为 TODO |-| 当前需求与设计 | `docs/需求理解.md`、`docs/方案设计.md` | 维护一个现行版本,变更历史交给 Git |+| 当前产品合同 | `docs/product/` | 每个领域一个 owner;只写行为、边界和非显然不变量 || 架构取舍 | `docs/adr/` | 明确状态;新决定替代冲突旧决定 || 可复核证据和研究结论 | `docs/research/` | 标日期、来源、推断、适用边界和许可证 |-| 当前验证与部署边界 | `docs/verification-status.md`、`docs/deployment.md` | 按需读取,不保存发布流水账 |+| 当前验证与部署边界 | `docs/verification-status.md`、`docs/deployment.md`、`docs/operations/`、`docs/reference/` | 按需读取,不保存发布流水账 || 已完成工作的时间线 | commit、PR、issue | 不复制进常驻 memory 或 status |每个事实只有一个 owner。顶层文件提供链接和当前结论,不复制深层正文;`docs/README.md` 维护完整文档索引。## 顶级指令卫生-[官方调研](./research/agent-context-governance.md)的共同结论是:顶层指令应是短而稳定的地图,流程和专业细节按需加载,并定期删除冲突或陈旧规则。因此本仓库的 `AGENTS.md` 目标是约 50 行,而不是把任何公开上限当作填充目标。模块特有规则只有在对应代码存在且每次读取确有必要时,才放到最近目录的 `AGENTS.md`;流程说明进入 `CONTRIBUTING.md`,当前工作进入 `docs/todo.md`,证据与理由进入其 owner。+[官方调研](./research/agent-context-governance.md)的共同结论是:顶层指令应是短而稳定的地图,流程和专业细节按需加载,并定期删除冲突或陈旧规则。因此本仓库的 `AGENTS.md` 保持在 100 行内,而不是把公开上限当作填充目标。模块特有规则只有在对应代码存在且每次读取确有必要时,才放到最近目录的 `AGENTS.md`;流程说明进入 `CONTRIBUTING.md`,当前工作进入 `docs/todo.md`,证据与理由进入其 owner。## 真相更新顺序1. 按 [`stop-that-shit`](../.agents/skills/stop-that-shit/SKILL.md) 的 authority 和 scope 规则,对照完整产品模型、当前代码、测试和证据确定目标;语义未定时只冻结依赖项。-2. 就地更新受影响的 requirement、design、ADR 或 research owner;仅在快照确实变化时同步 memory/status,未决执行项进入 TODO。+2. 就地更新受影响的 product、ADR 或 research owner;仅在快照确实变化时同步 memory/status,未决执行项进入 TODO。3. 检查各 current owner 一致并形成 Git-tracked truth checkpoint,再开始依赖该结论的实现或派发。-语义仍未决定时,在 TODO 记录 hold,只冻结依赖项。接受的真相先进入 canonical `main`;保留候选再从该精确提交 rebase 或重建一次,只移植获批的 scoped code、tests 和 new facts。旧分支的 truth 文档不得覆盖当前 owner。具体 Git 和 worktree 操作遵循 `CONTRIBUTING.md`。+语义仍未决定时,在 TODO 记录 hold,只冻结依赖项。具体 Git、worktree、checkpoint 和 integration 流程由 `CONTRIBUTING.md` 拥有。## 机制减负审查机制减负遵循 [`stop-that-shit`](../.agents/skills/stop-that-shit/SKILL.md) 的 scope 和 smallest-correct-result 规则。本仓库的审查先只读清点机制服务的用户行为,量化移除后的真实退让,并与代码、配置、迁移、测试、运行时状态、部署和故障面的整体成本比较。文档也是需要同步和审查的机制:长期真相只保留产品合同、非显然不变量、算法/模型、关键取舍和外部证据,普通 UI 与实现细节由代码、测试和 PR 持有。若 owner 接受有界退让,先更新产品合同再删除失去必要性的完整表面;否则保留合同并寻找更小实现。审查不以行数为目标,也不授权无边界重构。-应用层 TURN 清理是 [ADR-0005](./adr/0005-automatic-hybrid-media-routing.md) 的机制减负实例;TURN 的完整成本证据由 [ICE/TURN 研究](./research/built-in-peer-ice-turn.md)维护。内存房间曾以有限恢复收益换取更小机制,但真实开发发布已证明旧邀请、撤销高水位和房间权威连续性构成一个内聚 SQLite 消费者,因此 [ADR-0002](./adr/0002-memory-resident-protected-rooms.md) 现在保留轻量与稳定两种模式。该变化说明减负结论必须随可达需求重审,而不是把一次删除推广为永不恢复该机制。+TURN 的减负证据由 [ADR-0005](./adr/0005-automatic-hybrid-media-routing.md) 和相关 transport research 持有;轻量/SQLite 房间取舍由 [ADR-0002](./adr/0002-memory-resident-protected-rooms.md) 持有。这些案例只证明应按当前消费者重审完整成本,不能被推广为永远删除或永远保留某类机制的规则。## 检查点与恢复@@ -47,19 +47,20 @@检查点按 [`stop-that-shit`](../.agents/skills/stop-that-shit/SKILL.md) 的 current-result 规则,只保存以后仍需要的结论、当前状态、下一步和真实阻塞;不保存原始对话或工具输出、完整日志、临时路径、可廉价重查的事实和过程性 TODO 流水账。-恢复上下文时依次读取 `AGENTS.md`、project memory、status、TODO、相关需求/设计/ADR/研究,然后检查当前分支、`git status`、近期 commit 和 PR。摘要与仓库冲突时,以当前代码、测试和权威文档为准。+恢复上下文时依次读取 `AGENTS.md`、project memory、status、TODO、相关 product/ADR/research,然后检查当前分支、`git status`、近期 commit 和 PR。摘要与仓库冲突时,以当前代码、测试和权威文档为准。## 清理规则- `project-memory.md` 和 `status.md` 接近预算时,先删除可从代码或 Git 恢复的完成/失效内容,再把仍需保留的细节迁到现有 owner;不要反复微压缩句子。- `todo.md` 只保留真实未完工作、明确 hold 和待用户决策,不保留完成清单或一次性审计过程。-- `verification-status.md` 只保留仍影响验收的跨模块证据;成熟结论迁回 requirement、ADR、research 或 deployment,过期结果删除。-- 需求和设计不在末尾追加确认流水;研究失效时更新正文及最后验证日期;只有仍有解释价值的历史取舍进入 ADR。+- `verification-status.md` 只保留仍影响验收的跨模块证据;成熟结论迁回 product、ADR、research 或 operations,过期结果删除。+- Product 合同不追加确认流水;研究失效时更新正文及最后验证日期;只有仍有解释价值的历史取舍进入 ADR。- 每个重要 PR 检查 current 文档是否互相矛盾、链接是否有效、memory/status/TODO 是否仍代表现在。## 验证与自动化- 迭代中运行覆盖当前改动的最小定向检查;完整套件、真实浏览器矩阵、网络整形、跨设备、长时稳定性和部署检查在相关候选的验收边界批量运行。-- 文档改动默认运行 Markdown、链接、whitespace、diff 和 repository-hygiene 检查;不因无关文档变化重跑媒体基准。+- 文档改动默认运行本地 Markdown 链接、whitespace、diff 和 repository-hygiene 检查;不因无关文档变化重跑媒体基准。+- 断链、缺失必需 owner 和格式损坏是 hard failure。每次注入的 `AGENTS.md`、repo STS skill 与只负责导入的 `CLAUDE.md` 也使用 hard context budget,避免规则稀释。Product、ADR、research、operations 等按需文档的行数/字节阈值只是 warning:它提示检查是否应拆分二级 owner、删除历史或移出过程信息,不要求为通过门禁压缩合理正文,也不是交付质量指标。- 昂贵证据记录 commit、环境、结果和适用边界。只有相关路径、协议、配置、依赖、环境或门槛改变,或旧证据失败/含糊时才重跑。- `.githooks/pre-commit`、`scripts/check-project-state.sh` 和 PowerShell 等价入口共享 `scripts/required-project-paths.txt`。Hook 只做快速、确定、可复现的检查;工程判断留给评审和测试。diff --git a/docs/operations/self-hosting.md b/docs/operations/self-hosting.mdnew file mode 100644index 00000000..be26cf2d--- /dev/null+++ b/docs/operations/self-hosting.md@@ -0,0 +1,89 @@+# Self-Hosting Operations++This runbook owns initial single-host service setup. Application releases use+[deployment](../deployment.md); accepted environment values and ports are in+[configuration reference](../reference/configuration.md).++## Topology++```text+Browser -- HTTPS/WSS --> nginx :443 --> Screener :8787+Browser -- /rtc/v1 WSS --> nginx :443 --> LiveKit :7880+Browser <---------- DTLS-SRTP P2P ----------> Browser+Browser -------- ordinary STUN/UDP --------> coturn :3478+Browser <--------- DTLS-SRTP/UDP ----------> LiveKit :7882+Screener -------- private RoomService -----> LiveKit :7880+```++The tracked public baseline uses Node.js 24, nginx, a valid Web TLS+certificate, time synchronization, and coturn 4.17.2 or a newer patched release.+LiveKit is required for the accepted SFU fallback and tracked release wrapper.+Web and STUN may use different DNS names on the same public IP. Another proxy or+P2P-only service shape needs its own matching updater and recovery checks.++Expose only the public listeners in+[configuration reference](../reference/configuration.md). Screener 8787 and+LiveKit 7880 stay private.++## Tracked Templates++- [Screener systemd unit](../../deploy/systemd/screener.service.example)+- [LiveKit systemd unit](../../deploy/systemd/livekit.service.example)+- [LiveKit readiness drop-in](../../deploy/systemd/screener-livekit-readiness.conf.example)+- [coturn systemd unit](../../deploy/systemd/coturn.service.example)+- [STUN-only coturn config](../../deploy/coturn/turnserver.conf.example)+- [LiveKit config](../../deploy/livekit/livekit.yaml.example)+- [nginx site](../../deploy/nginx/share.bonfire.icu.conf.example)++Copy templates outside the repository, inject independent secrets through an+access-restricted environment file or service manager, and adapt only addresses,+domains, certificates, users, and resource limits required by the host.++## Initial Setup++1. Configure DNS and TLS for the Web origin and STUN name.+2. Install Node.js, nginx, coturn, and pinned-compatible LiveKit.+3. Create an unprivileged `screener` service account, `/opt/screener/releases`,+ `/opt/screener/uploads`, and an access-restricted environment file.+4. Provision one verified initial immutable release and atomically point+ `/opt/screener/current` to it before enabling the unit. The tracked release+ wrapper is upgrade-only and deliberately refuses a missing prior release;+ this repository does not provide a generic first-install transaction.+5. When stable room authority is enabled, use the service-owned+ `/var/lib/screener` StateDirectory and include the SQLite file in the host's+ state backup/recovery policy.+6. Install the tracked service and proxy templates. Bind Screener to loopback on+ bare metal; containers may bind `0.0.0.0` only when publishing/firewall rules+ preserve the same boundary.+7. Apply the public-port allowlist and confirm every retired TURN/TCP port+ is closed.+8. Start coturn and LiveKit before Screener, then nginx. The LiveKit+ readiness drop-in waits for its private control listener before Screener.++LiveKit must be dedicated to this Screener application, set+`room.auto_create: false`, and expose its control listener only to the proxy and+application host. Screener binds its own listener before touching LiveKit,+rejects foreign room names, removes stale managed rooms, confirms the namespace+empty, and only then installs signaling. A competing application process must+make no LiveKit mutation.++Coturn runs `stun-only`, `no-tcp`, and `no-tls`. It must answer STUN binding and+reject TURN allocation. Avoid verbose STUN/ICE logging because infrastructure+necessarily observes client IP addresses.++## Operational Verification++- `/healthz` returns `{"status":"ok"}` locally and through the public origin.+- Screener, nginx, coturn, and LiveKit are active with expected restart+ counts and bounded logs/resources.+- The official Trickle ICE sample obtains an ordinary UDP `srflx` candidate from+ the configured STUN service and no relay candidate.+- A direct room presents media on two networks when Peer ICE succeeds.+- A constrained route creates one managed Host publication and only admitted+ subscriptions over LiveKit UDP; Peer descendants remain ordinary P2P.+- Blocking all UDP reaches a clear bounded failure.+- Restarting Screener in stable mode retains room authority while Browser+ sessions and media reconnect from fresh process state.++Representative network, mobile, audio, 20-Viewer, and long-running evidence is+tracked in [verification status](../verification-status.md), not in this runbook.diff --git a/docs/product/media-quality.md b/docs/product/media-quality.mdnew file mode 100644index 00000000..e79bacc4--- /dev/null+++ b/docs/product/media-quality.md@@ -0,0 +1,103 @@+# Capture, Audio, And Media Quality++This file owns the current Browser media contract. Detailed measurements and+platform limits live in [realtime quality research](../research/realtime-quality-adaptation.md)+and [screen-audio research](../research/browser-screen-audio-quality.md).+[ADR-0007](../adr/0007-path-isolated-representation-quality.md) owns the SFU+adaptation decision.++## Capture And Controls++- The Web Host may share a display, application window, or Browser tab and may+ stop, synchronously pause/resume audio and video, or switch source.+- Share and source-switch requests ask the Browser for available audio by+ default. Missing audio is reported clearly but does not block video-only+ sharing.+- Authoritative pause disables all current capture tracks while retaining the+ room and established routes. Black frames, track mute, or network failure are+ not interpreted as a user pause.+- The Host preview displays the capture stream directly and creates no Viewer or+ media route. Hiding the page may pause only that local video element; it must+ not intentionally stop capture, encoding, or upload.+- Live quality changes update the current capture constraints and sender+ ceilings without reopening source selection or replacing a healthy route.++## Video Profiles++The three recommended profiles are ceilings, not delivery guarantees:++| Profile | Target | Video bitrate ceiling |+| --- | --- | ---: |+| `720p30` | 1280x720 at 30 fps | 3 Mbps |+| `1080p30` | 1920x1080 at 30 fps | 5 Mbps |+| `1080p60` | 1920x1080 at 60 fps | 8 Mbps |++`1080p30` is the default. Advanced resolution includes 480p, 720p, 1080p, and+1440p; frame rate, bitrate, and `maintain-resolution | balanced |+maintain-framerate` remain independent controls. Display video uses the standard+`contentHint = "motion"` for game motion.++Current acceptance targets are:++- on a controlled P2P path with RTT at most 40 ms and loss at most 1%, glass-+ to-glass latency p50 at most 150 ms and p95 at most 250 ms;+- through a regional SFU/UDP root, glass-to-glass p95 at most 350 ms; and+- when the 60 fps profile is selected, no silent run of five seconds below 50+ decoded fps without an explicit adaptation or user-visible limitation.++These are targets pending the physical matrices in verification status, not+claims that every Browser, game, or network already meets them.++## Codec Decision++The pre-share Browser selector is `VP8 | Auto | H264`, defaults to Auto, and is+locked while sharing. It is local UI state and is not persisted or carried as a+room quality setting.++Auto uses one bounded actual-sender probe rather than a capability or device+allowlist. A proved sender prefers H.264 with VP8 fallback; unsupported, failed,+or inconclusive probes use VP8. Manual VP8 or H264 strictly selects that codec.+The result stays fixed for the current share and is reconsidered for a new share.+ADR-0007 owns probe and negotiation mechanics.++The Browser chooses the concrete encoder implementation. A reported H.264 codec+does not by itself prove hardware acceleration, and Web content cannot select a+specific MFT, NVENC, AMF, or QSV implementation.++## Framework-Owned Adaptation++Each direct or relay PeerConnection keeps its own stock WebRTC congestion and+quality adaptation. The Host's one SFU publication uses the share-generation+codec and selected ceiling but no application-defined simulcast ladder or backup+codec. Pinned LiveKit defaults construct representations; Dynacast aggregates+demand and server send-side BWE selects subscriber forwarding. AdaptiveStream+stays disabled because any Viewer may relay its received track.++Screener does not maintain an application bitrate/resolution ladder, scene+detector, periodic quality controller, manual SFU layer selector, or whole-room+lowest-common-denominator target.++## Screen Audio++Display audio uses `contentHint = "music"`. The live sender ceilings are 64,+128, and 192 kbps with 128 kbps default. Peer answers request Opus stereo and a+192 kbps receive ceiling. The SFU publication uses stereo, DTX disabled, and RED+disabled; this accepts less burst-loss resilience in exchange for bounded+publisher traffic. The Browser and source still decide whether an audio track+exists and what is actually delivered.++## Observable Truth++Requested resolution, frame rate, bitrate, content intent, codec, and audio+quality are inputs or ceilings. Sender parameter readback and current RTCStats+are the observable result. Connection detail may show actual path, codec,+resolution, FPS, bitrate, loss, jitter, RTT, and encode/decode behavior when the+Browser exposes them; missing or reset counters remain unknown.++The current quality shadow accepts only current foreground presentation evidence+and never changes routes or media settings. Quality-driven topology work is+parked in [TODO](../todo.md).++Web pages cannot guarantee Host background capture, mobile background playback,+or relay execution after Browser/OS suspension. Those remain physical lifecycle+boundaries, not keepalive features.diff --git a/docs/product/presentation-lifecycle.md b/docs/product/presentation-lifecycle.mdnew file mode 100644index 00000000..1224b3cb--- /dev/null+++ b/docs/product/presentation-lifecycle.md@@ -0,0 +1,86 @@+# Presentation And Lifecycle++This file owns user-visible workflow, presentation authority, presence, and+Browser lifecycle promises. Component structure, CSS, exact copy, and routine UI+tests belong in source code.++## Product Surface++The first screen is the working tool, not a marketing page. Once site access is+available, starting a share and joining a room are equally discoverable actions;+joining expands the four-digit room form in place, while `/join` remains a direct+entry route. Users never choose a media topology.++The Host workspace centers the capture preview, room code, invitation and common+share controls. The Viewer workspace centers one persistent 16:9 video stage,+room identity, current state, roster, and one manual media-reconnect action.+Controls and text must remain usable without overlap or horizontal overflow on+desktop and mobile viewports.++## Playback Ownership++One native `<video>` element owns Viewer play/pause, volume, mute, and fullscreen.+Those actions are local and never change Host capture, room state, routing, or+other Viewers. The Host preview has no media controls; explicit Host actions own+authoritative share pause and stop.++Autoplay rejection exposes the native play action. A connection, track object,+or `playing` event alone is not proof that the current route is visible. The+Viewer removes its blocking presentation only after a current-generation frame+is composited, using `requestVideoFrameCallback()` where available and a decoded-+progress fallback otherwise.++## State And Recovery++Access, Host presence and pause, route prepare/active, P2P/SFU connection, media+binding, frame proof, autoplay, and terminal failure are typed facts interpreted+by one presentation reducer. Older route or media generations cannot overwrite+the current result, and raw server errors are never rendered directly.++Excluding time spent in the Browser's capture/play authorization UI, a Viewer+request targets a first visible frame within three seconds. Until then, the page+must continuously show a truthful accessible connection stage rather than a+black screen, ICE-connected state, or unproved `playing` event.++- A proved current frame remains visible behind non-terminal recovery state.+- Host pause retains the current frame and waits for resume.+- Host signaling loss alone does not invalidate media that is still healthy.+- Exact media failure or terminal route failure invalidates current-frame proof+ before showing a retained frozen background and recovery or failure state.+- Room not found/expired is distinct from current-room access denial and does not+ prompt for a password.+- Manual reconnect rebuilds the same route. It does not select a new parent.+- An actionable overlay may appear while fullscreen remains active; application+ state never forces the user out of fullscreen.++Visibility, page freeze, and pagehide suppress application decoded-stall+authority. Returning to the page rebaselines time and proves a current frame+again before clearing recovery. LiveKit page-leave auto-disconnect is disabled,+but Browser or OS suspension and page reclamation remain outside Web guarantees.++## Presence And Diagnostics++Host and Viewer pages show the authoritative online Viewer count and roster,+independent of the media graph. A display name is Browser-local, NFC-normalized,+at most 24 Unicode code points, and rejects unsafe control or bidirectional+characters. It is a label, not an account, authorization identity, or routing+input. Duplicate names are allowed and receive a room-scoped peer suffix only+when disambiguation is needed.++Connection details are progressive and use one card shape for P2P, peer relay,+and SFU Viewers. Summary fields prioritize actual resolution, FPS, bitrate, and+loss; deeper fields appear only when meaningful. Topology is a separate view.+Locally exposed selected-candidate addresses may be shown only on the Browser+that owns that PeerConnection and are never uploaded, persisted, or used for+identity or route selection. The product does not offer a diagnostic-download+button or a raw stats dump.++Current Browser scope includes Web Host, Web Viewer, and Browser relay. Desktop+and mobile Browsers are Viewer targets; mobile Web capture, reliable background+relay, native sender, and packaged capture helpers remain later platform work.++## Primary References++- [WHATWG Web Storage](https://html.spec.whatwg.org/multipage/webstorage.html)+- [ECMAScript string normalization](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.normalize)+- [Unicode UAX #31](https://www.unicode.org/reports/tr31/)diff --git a/docs/product/rooms-access.md b/docs/product/rooms-access.mdnew file mode 100644index 00000000..76d052f0--- /dev/null+++ b/docs/product/rooms-access.md@@ -0,0 +1,79 @@+# Rooms And Access++This file owns the current room, admission, invitation, and persistence+contract. [ADR-0002](../adr/0002-memory-resident-protected-rooms.md) explains+the storage decision; implementation detail belongs in code and tests.++## Room Authority++- A room has one Host and at most 20 authenticated Viewers.+- Room codes are random free four-digit values from `1000..9999`. A code locates+ a room; it is not a secret or permanent identity.+- Every room has a 256-bit Host token. The server stores only its digest; the+ owning Browser keeps the raw token locally.+- Dormant rooms have a configurable lease, default 24 hours. An authenticated+ online Host clears the lease deadline whether or not it is currently sharing;+ Host absence starts the dormant lease. The exact Host token resumes an+ unexpired room; Viewer activity never renews it.+- The Host may replace its room code. Replacement atomically creates a different+ room and invalidates the old ownership, invitations, password, sessions,+ routes, and media resources. It ends an active share and stops its capture+ tracks; it does not migrate or automatically restart capture.+- A locally remembered preferred code is only a request. The server remains the+ authority and allocates another code when that code is unavailable or expired.++## Admission Paths++Three independent authorities exist:++1. **Site access.** Production requires an independent+ `SITE_ACCESS_PASSWORD`. Successful entry creates a 12-hour stateless,+ HttpOnly, `SameSite=Strict` cookie. It authorizes room creation, Host role,+ and code-only Viewer attempts; it is not a room credential.+2. **Host ownership.** The exact Host token authorizes that room's Host and+ access-management operations. It cannot authorize another room.+3. **Viewer invitation.** Every room creates a 128-bit, 22-character base64url+ Viewer grant. It authorizes only the Viewer role for that exact room+ incarnation and bypasses site access and code-entry policy.++The invitation grant is carried in the URL fragment, removed from the address+bar on first read, and retained only in room-scoped `sessionStorage`. Refreshing+the same tab preserves it. It is not intentionally persisted across independent+tabs or Browser sessions; tab duplication and opener initialization remain+Browser behavior. The grant has no independent TTL and ends with the room or+when the Host rotates or revokes it.++Code-only admission is independent of invitations:++- `open` admits a site-authorized Viewer by room code;+- `private` without a password is invitation-only;+- `private` with a password additionally admits a site-authorized matching+ code-and-password attempt.++An unknown, reclaimed, or expired code returns `ROOM_NOT_FOUND`. A current room+that refuses a code-only attempt returns the generic `ROOM_ACCESS_DENIED` result+without exposing its exact policy. Invalid grants and Host ownership failures+remain separate.++Rotating or revoking the Viewer grant is a strong authorization change. The new+generation is committed before old Viewers, signaling grace, routes, and sender+edges are closed. Changing code-entry policy or password affects later+code-only attempts and does not silently revoke invitations.++## Persistence Modes++- **Lightweight mode:** without `ROOM_DATABASE_PATH`, room authority is process+ memory and all rooms disappear on restart.+- **Stable mode:** with an explicit SQLite path, one exact-schema owner persists+ room authority across application restart.++Stable mode does not persist participants, signaling sessions, sharing state,+routes, codec decisions, quality evidence, or SFU state. After restart, clients+reauthenticate and rebuild media; a room that was active becomes dormant with a+fresh lease. [Status](../status.md) owns the selected deployment mode and+ADR-0002 owns storage validation.++The Host Browser may persist its creation preferences, including policy and an+optional room password. Raw Viewer grants never enter `localStorage`, cookies,+queries, server logs, or SQLite. Credentials, passwords, and invitation URLs are+never committed to the repository.diff --git a/docs/product/routing-transport.md b/docs/product/routing-transport.mdnew file mode 100644index 00000000..a660840a--- /dev/null+++ b/docs/product/routing-transport.md@@ -0,0 +1,86 @@+# Routing And Transport++This file owns the user-visible routing and transport contract.+[ADR-0005](../adr/0005-automatic-hybrid-media-routing.md) owns the controller+algorithm and resource invariants; [configuration](../reference/configuration.md)+owns ports and [self-hosting](../operations/self-hosting.md) owns service setup.++## Topology++- Media is automatic and P2P-first. Users do not select parents, route types, or+ network transports.+- The Host is the only source. Every Viewer has at most one active upstream, and+ the committed media graph is acyclic and source-reachable.+- A Viewer may relay its received Browser track to bounded peer children. This+ is standard WebRTC receive, decode, and per-child re-encode, not shared encode.+- SFU-fed and peer-fed Viewers may both serve as ordinary peer parents.+- A route ends in usable media, explicit bounded waiting, or clear failure.++The flagship deployment enables the all-room controller. A lightweight+deployment may disable peer assistance and keep only bounded direct Host edges;+it does not gain another transport or compatibility protocol.++## Endpoint And Server Capacity++Every non-server endpoint has one server-authoritative steady outbound media-+copy cap `C`, default `2` and configurable only as `1`, `2`, or `3`.++- one peer child consumes one copy;+- the Host's single SFU publication consumes one copy;+- upstream receive is free;+- role, Browser, UA, visibility, and codec do not create another tier.++A make-before-break transition may use the one admitted overlap slot and must+return to steady capacity at commit or abort. SFU publication ingress and+per-Viewer subscription egress use an independent server admission ledger;+ordinary endpoint child counts are not server capacity.++## Reconciliation++One room controller owns the committed graph and one bounded child transition.+Healthy current edges remain sticky. When admitted overlap exists, a usable old+route stays active until the exact candidate child decodes a first new frame;+ICE connected alone is not commit proof. Availability repair may instead use the+explicit bounded-gap plan defined by ADR-0005 when no overlap slot exists.+Failure or stale authority releases the candidate and preserves unaffected+branches.++Direct peers receive the first bounded opportunity, with SFU used for+availability when direct paths cannot provide media. Remaining direct paths may+converge behind a working SFU route. Relay-ingress failure reparents that relay+without discarding its subtree; departure and capacity changes move only affected+children. ADR-0005 owns filtering, ordering, cursor, revision, reservation, and+rollback mechanics.++Framework reconnect runs before route reassignment. Manual media reconnect also+rebuilds only the current P2P parent or current SFU subscription; it does not+perform quality selection or choose another route.++## SFU Fallback++The only application fallback is one dedicated LiveKit SFU publication from the+Host, with independently admitted Viewer subscriptions. The controller may+create it through the same bounded transition when Host capacity is occupied.+No Viewer creates a second publication.++Browser SFU PeerConnections use LiveKit-signaled UDP candidates and no external+ICE-server list. Ordinary peer connections use deployment STUN. Screener+configures no TURN, ICE/TCP, media TCP, or TLS-relayed media path. HTTPS/WSS is a+separate control transport and remains TLS/TCP.++SFU resources remain bounded throughout reservation, use, and cleanup; stale+credentials cannot recreate off-ledger media. ADR-0005 owns that lifecycle.++## Quality And Privacy Boundaries++WebRTC and LiveKit own ICE, consent, congestion control, bitrate, frame rate,+resolution, retransmission, reconnect, and SFU layer selection. Current route+quality is diagnostic: Screener has no weighted route score, parent-wide quality+inference, all-pairs probe, periodic rebalance, persistent parent blacklist, NAT+classification, or independent depth cap. Open quality work remains in the+[TODO ledger](../todo.md).++Direct P2P exposes endpoint network addresses to the trusted peer. SFU media is+encrypted hop-by-hop with DTLS-SRTP but terminates at the SFU; the product does+not claim operator-blind media without a separately accepted application E2EE+design. All-UDP-blocked networks currently end in bounded failure.diff --git a/docs/project-memory.md b/docs/project-memory.mdindex b94a4ad2..31230b11 100644--- a/docs/project-memory.md+++ b/docs/project-memory.md@@ -2,155 +2,59 @@Last updated: 2026-08-27-## Current Product Truth--- Screener is private, low-latency game screen sharing for one Host and up to- `20` authenticated Viewers, not a public broadcast service.-- Web Host, Viewer, and Browser relay are the current delivery surface. Native- capture, shared encoding, and distributable server/local packages remain- later work.-- Rooms use one bounded authority model: random free `1000..9999` code, default- 24-hour dormant lease, active sharing never expires, exact Host token resume,- and Viewer activity never renews. `ROOM_DATABASE_PATH` absent is the default- lightweight process-memory mode; configured is the optional SQLite stable- mode that persists only room authority across application restart. Production- enables stable mode; live participants, routes and media remain process-only.-- Every room has one 128-bit/22-character Viewer grant bound to that exact room- incarnation and independent `open | private` code entry. Private without a- password is invitation-only; adding a password also permits matching code- entry. Reclamation, explicit replacement, lightweight restart, rotate, or- revoke ends the grant; stable restart retains its digest and generation.- Missing codes return `ROOM_NOT_FOUND` without a password prompt.-- Host creation preferences, raw ownership token and one non-expiring preferred- code stay local to the Host browser. Server authority stores only- digests/verifiers, optionally in SQLite stable mode, and never uses IP, UA,- device, or browser fingerprint as identity.--## Media And Routing--- Media stays automatic and distributed. Ordinary peer ICE is STUN-only and- direct/peer UDP is preferred. The only application fallback is the dedicated- LiveKit SFU over UDP; Screener configures no TURN, ICE/TCP, media TCP, or- TLS-relayed media.-- Browser LiveKit publisher/subscriber PCs use no external ICE server and retain- LiveKit-signaled UDP candidates. Deployment STUN remains available to ordinary- peers and LiveKit server-side public-IP discovery.-- Every non-server endpoint uses one server-authoritative steady outbound copy- cap: default `2`, configurable only as `1`, `2`, or `3`. A peer child or the- Host publication consumes one slot; upstream receive is free; SFU subscriber- egress uses separate server admission.-- One room controller owns one committed acyclic source-reachable graph, one- event-driven reconciliation loop, and at most one room-serial child operation.- The operation owns one deterministic candidate list/cursor, one current- candidate and reservations, one fact version, and one total deadline.-- Candidate filtering enforces current authority, reachability, acyclicity,- capacity, transition slots, and server admission. Eligible P2P parents are- ordered by resulting depth, remaining capacity, a stable child-parent hash,- join order, and peer identity.-- A candidate commits only after the exact child decodes its first new video- frame. Exact direct transport-connected progress may retain the candidate- through the total deadline but cannot commit. Failure releases resources,- broadcasts a strictly newer rollback revision, advances the cursor without- resetting the deadline, and preserves unaffected healthy branches. SFU-backed- Viewers keep working media while finite direct candidates converge in- background round-robin. A relay with bad ingress reparents itself while- retaining its subtree.-- Healthy decoded routes remain sticky. There is no periodic rebalancing,- quality score, all-pairs probing, parent blacklist, NAT classification, port- prediction, or independent depth cap. Quality evidence cannot prove an- unconnected parent would be better.-- P2P and SFU first use their framework reconnect behavior. P2P recovery tries- the same parent, and SFU recovery rebuilds the same publication/subscription.- Manual media reconnect also stays on the current exact route. Only actual- recovery exhaustion, hard failure, non-paused decoded-frame stall, parent- departure, or capacity invalidation enters route reassignment.-- Active-path WebRTC/LiveKit sampling owns one exact-route decoded-progress- deadline. Route/connection change or new progress resets it; authoritative- pause suppresses it. Page resume rebaselines frozen wall-clock time before- another no-progress sample can fail a route.--## Media Quality--- Canonical source and production run one sender-scoped actual-sender preflight- with a deterministic moving probe track sized to the current share target, so- captured-content motion cannot decide encoder capability. Proved senders prefer- H.264 with native VP8 fallback, while failed/inconclusive senders remain- VP8-only. The Host UI provides a local pre-share `VP8 | Auto | H264` selector- with Auto default; it locks while sharing, is not persisted, and creates no- codec wire/state or active-edge switching. Viewer relays remain Auto.- Display video uses `contentHint = "motion"` and display audio uses- `contentHint = "music"`.-- Windows Chrome 151 uses software VP8 and exposes no Web control for selecting- NVENC, AMF, QSV, a GPU, or an MFT. Edge, non-Windows paths, and real-game CPU- contention remain evidence-specific.-- Recommended profiles remain exactly `720p30`, `1080p30`, and `1080p60`, with- `1080p30` default. `480p` is only an advanced `854x480` resolution choice;- advanced FPS and bitrate remain independent.-- WebRTC owns direct/peer media adaptation. The Host reapplies the selected video- profile after answer negotiation; no periodic application controller exists.-- The production SFU publisher uses the Host's H.264/VP8 decision and selected- ceiling but no backup codec or custom simulcast layers. Pinned LiveKit defaults own- representations, Dynacast owns aggregate- demand, and server send-side BWE owns subscriber forwarding. AdaptiveStream- stays disabled because any Viewer may relay its received track.-- Screen audio requests capture by default and offers live 64/128/192 kbps- sender ceilings with 128 default. Peer answers request Opus stereo with a- 192 kbps receive maximum. SFU publication uses stereo, DTX off, and RED off;- disabling RED accepts reduced burst-loss resilience in exchange for bounded- publisher traffic.-- Configured resolution, FPS, bitrate, preference, codec, and audio ceiling are- requests or ceilings. Sender readback and RTCStats are the observable truth.--## Presentation And Lifecycle--- Viewer presentation is revision/generation-fenced and keeps the stage stable- until a current-generation composited frame. A new current frame clears stale- media `connecting/reconnecting` presentation; old callbacks cannot prove a- new route.-- Viewer local play/pause, volume, mute, and fullscreen are owned by native video- controls on one persistent media element. Host preview is a muted, control-free- view of the capture stream; only explicit Host actions pause or stop sharing.-- Viewer hidden/freeze/pagehide suppress application decoded-stall authority;- visible/resume/pageshow rebaseline and rearm current-frame proof. SFU pagehide- does not make LiveKit actively disconnect, while SDK freeze behavior, playback,- background audio, page reclamation, and relay survival remain physical gates.-- Hiding or unfocusing the Host page pauses only the local preview element.- Browser/OS capture and background behavior remain platform capabilities; no- fake keepalive, silent media, Wake Lock, or timer loop is a product mechanism.--## Current Source And Production--- Canonical source and production use the same evidence-only strict- `screener-v13` quality shadow with adaptive H.264/VP8 selection, the local- Host codec override, and optional SQLite room authority. Exact identities are- indexed by [status](./status.md).-- Strict v13 rejects old Browser pages before room authority. Its bounded- current-edge aggregate adds no active route decision until annotated- production shadow evidence establishes an accepted policy.-- Production uses SQLite-backed random rooms, 20-Viewer admission, endpoint cap `2`,- fixed 9,000-publication ingress and `9000 * 20` subscription egress admission,- STUN UDP 3478, LiveKit media UDP 7882, and Web TCP 80/443. Node 8787 and- LiveKit 7880 remain private.-- Exact artifact and service state are owned by [deployment](./deployment.md)- and indexed by [status](./status.md). Physical evidence boundaries are owned- by [verification status](./verification-status.md).--## Current Priority--1. Collect annotated production samples from the evidence-only strict- `screener-v13` quality shadow.-2. Complete the mobile Viewer lifecycle matrix and representative real-network- route/media acceptance.--Quality-driven parent selection, Native sender work, distribution packages,-whole-product UI/bilingual polish, and repository-wide simplification remain-later decisions in [the TODO ledger](./todo.md).--## Working Rules--- Generic authority and scope follow the repo-tracked- [`stop-that-shit` skill](../.agents/skills/stop-that-shit/SKILL.md).-- Canonical `main` and the current truth owners override old branches,- worktrees, handoff text, and chat summaries.-- Preserve unique or dirty candidates until integration and reference/reparse- audits prove cleanup is safe.+Screener is private, low-latency game screen sharing for one Host and up to 20+authenticated friends. The current product surface is Web Host, Web Viewer, and+Browser relay; desktop and mobile Browsers are Viewer targets. It is not a+public broadcast service. Native capture, shared encoding, distributable+packages, and broader platform output remain later work.++## Product Map++- [Rooms and access](./product/rooms-access.md) owns room codes, leases,+ invitations, code entry, credentials, and lightweight/SQLite persistence.+- [Routing and transport](./product/routing-transport.md) owns P2P-first+ distribution, endpoint capacity, SFU fallback, recovery, and privacy limits.+- [Capture and media quality](./product/media-quality.md) owns Browser capture,+ profiles, codec selection, audio, and framework adaptation.+- [Presentation and lifecycle](./product/presentation-lifecycle.md) owns Host and+ Viewer workflows, playback authority, roster, state, and Browser lifecycle.++Non-obvious decisions live in [ADRs](./adr/); reproducible evidence and platform+limits live in [research](./research/). Source code and tests own self-evident+implementation and routine UI detail.++## Core Invariants++- Rooms use random four-digit codes, exact Host ownership, room-scoped Viewer+ invitations, independent `open | private` code entry, and a 24-hour dormant+ lease. Production enables optional SQLite stable room authority; live+ participants, routes, and media remain process-only.+- Media is automatic and distributed. Ordinary peers are STUN-only and prefer+ direct/peer UDP. The only application fallback is one bounded LiveKit SFU/UDP+ publication; Screener configures no TURN or TCP media route.+- Every endpoint shares one steady outbound-copy cap, default `2` and limited to+ `1..3`. One room controller owns one committed graph, one reconcile loop, and+ one serial child operation. First decoded frame is candidate commit proof.+- WebRTC and LiveKit own congestion control, media adaptation, reconnect, and SFU+ layers. Current route quality is diagnostic; no weighted score, all-pairs+ probe, parent-wide inference, or periodic rebalance is accepted.+- Browser video uses `motion`; each share chooses H.264 with VP8 fallback through+ an actual sender probe unless the Host explicitly selects VP8 or H264. Screen+ audio uses 64/128/192 kbps ceilings with 128 default.+- Viewer playback uses one native video element. Presentation and recovery are+ fenced by current route/media identity and current-frame proof; hidden-page+ time alone is not media-failure evidence or a keepalive guarantee.++## Current Snapshot++Canonical source and production use the strict `screener-v13` Browser/server+contract, optional SQLite room authority, the H.264/VP8 sender gate, and the+evidence-only quality shadow. [Status](./status.md) is the sole owner of exact+source, artifact, deployment, milestone, and blocker identity.++Current work is owned by the [TODO ledger](./todo.md). Open physical evidence is+owned by [verification status](./verification-status.md). Environment and initial+services are owned by [configuration](./reference/configuration.md) and+[self-hosting](./operations/self-hosting.md); application release is owned by+[deployment](./deployment.md).+Git history and pull requests own completed timelines.diff --git a/docs/reference/configuration.md b/docs/reference/configuration.mdnew file mode 100644index 00000000..d1cdbe96--- /dev/null+++ b/docs/reference/configuration.md@@ -0,0 +1,66 @@+# Configuration And Ports++The tracked [`.env.example`](../../.env.example) is the executable schema+companion; `src/server/config.ts` is validation truth. Keep real values in the+service secret store or an untracked access-restricted environment file.++## Application Environment++| Variable | Contract |+| --- | --- |+| `NODE_ENV` | `production` enables production-only validation. |+| `LISTEN_HOST` | Defaults to `0.0.0.0`; bare-metal production normally uses `127.0.0.1`. |+| `PORT` | Positive TCP port, default `8787`; the tracked release wrapper supports only that default. |+| `PUBLIC_BASE_URL` | Exact public HTTP(S) origin; production requires HTTPS. |+| `ALLOWED_ORIGINS` | Comma-separated exact HTTP(S) origins; wildcard is invalid. |+| `SITE_ACCESS_PASSWORD` | Production-required independent 8-128 visible-ASCII byte secret. |+| `ROOM_LEASE_SECONDS` | Positive dormant lease, default `86400`; active Host prevents expiry. |+| `ROOM_DATABASE_PATH` | Optional absolute SQLite file path; unset selects memory mode. |+| `MAX_VIEWERS_PER_ROOM` | `1..20`, default `8`. |+| `PEER_ASSISTED_MEDIA` | Enables the all-room bounded Peer/SFU controller. |+| `ENDPOINT_MEDIA_COPY_CAPACITY` | Shared endpoint steady-copy cap `1..3`, default `2`. |+| `STUN_URLS` | Comma-separated `stun:` URLs; at least one is required in production. |++Automatic SFU fallback is enabled only when `PEER_ASSISTED_MEDIA=true` and all+four values below are present:++| Variable | Contract |+| --- | --- |+| `LIVEKIT_URL` | Browser `ws:`/`wss:` origin with no path; production requires WSS. |+| `LIVEKIT_API_URL` | RoomService `http:`/`https:` origin with no path; production plaintext is loopback-only. |+| `LIVEKIT_API_KEY` | Independent LiveKit API key. |+| `LIVEKIT_API_SECRET` | Independent secret of at least 32 bytes. |++The site-access password, LiveKit API key, and LiveKit secret must not reuse one+another. LiveKit tokens are short-lived media credentials and do not provide+application E2EE.++Removed access, room TTL, endpoint-tier, room-rollout, and TURN variables fail+startup even when blank. The private deployment is upgraded atomically; there+are no compatibility aliases or dual configuration readers.++## Public And Private Ports++| Port | Scope | Owner |+| ---: | --- | --- |+| TCP 80/443 | public | HTTP redirect and HTTPS/WSS reverse proxy |+| UDP 3478 | public | STUN-only coturn |+| UDP 7882 | public when SFU enabled | LiveKit WebRTC media |+| TCP 8787 | private | Screener application |+| TCP 7880 | private when SFU enabled | LiveKit signaling/control |++TCP 3478, TCP/TLS 5349, TURN relay ranges, LiveKit media TCP, and other media+ports remain closed. HTTPS/WSS transport is independent of the UDP-only media+contract.++## Bounds++- Site-access requests are rate-limited at the reverse proxy and use constant-+ time secret comparison in the application.+- HTTP body, WebSocket payload, total/unauthed connections, room count, Viewer+ count, output buffers, endpoint copies, and SFU resources are bounded.+- The four-digit code space fixes the maximum managed Host publications at+ 9,000; maximum subscription admission is that capacity times the configured+ per-room Viewer limit. These are admission bounds, not throughput claims.+- One application process owns room authority and LiveKit admission. Multiple+ processes require a new shared atomic owner.diff --git a/docs/research/advanced-peer-distribution.md b/docs/research/advanced-peer-distribution.mdindex 95f8c11d..21d9eeca 100644--- a/docs/research/advanced-peer-distribution.md+++ b/docs/research/advanced-peer-distribution.md@@ -1,411 +1,180 @@# Advanced Peer Distribution-- Research date: 2026-08-26-- Scope: current route admission up to twenty trusted viewers, sub-second- interactive media, endpoint downstream cap `1..3`, and minimal central-server- media egress; retained advanced-media measurements may cover smaller cohorts-- Status: deterministic peer distribution and provisional make-before-break are- retained evidence. Exact Browser v10 source- `fdd5a4a529ff297f41c05ea3388bf484d76afe8f` implements ADR-0005's single- child-reparent reconciliation and exact first-frame transaction and remains- dated implementation evidence. Current source and production are indexed by- [status](../status.md) and follow ADR-0005. Advanced encoded-media routes remain- unimplemented candidates.--This document is research evidence, not current architecture or a backlog. See-[ADR-0005](../adr/0005-automatic-hybrid-media-routing.md) for accepted routing-invariants and [the TODO ledger](../todo.md) for pending work.--## Terms--- **Multiple trees:** split one media representation into two stripes and send- each stripe through a different peer tree. A viewer receives both trees; an- internal relay forwards only its assigned stripe. This balances endpoint- upload but requires two parents, assembly, loss recovery, and churn handling.-- **SVC:** one encoder produces a base layer plus dependent temporal or spatial- enhancement layers. It lets a forwarder drop enhancement data, but it does- not create a distribution topology or move layers between transports.-- **Network coding:** send repair symbols formed from several source symbols so- a receiver can recover loss after collecting enough independent symbols. It- adds bytes and CPU; it can reduce retransmission delay but cannot compress the- video or replace route migration after a complete path failure.--Complexity alone is not a rejection reason. A route is retained only when a-bounded experiment shows lower endpoint compute or bandwidth, keeps the user-experience automatic, and meets the latency and queue limits below.--## Cost Accounting--Let `B` be one complete stream bitrate, `N` the viewer count, and `r` repair-overhead. Protocol headers and retransmission overhead are additional.--| Route | Host upload | Central media traffic | Encode work |-| --- | ---: | ---: | --- |-| Current full-stream browser chains | at most `2B` | zero on direct peer edges; SFU legs are accounted separately | host up to two encoders; every relay encodes again |-| Native full-stream RTP relay | at most `2B` | zero on direct peer edges | relay zero encode; native host can share one encode |-| Two encoded-object stripe trees | about `(1+r)B` | zero on direct peer edges | host one encode; relay zero encode |-| Host publication with bounded SFU subscriptions | measured `B_pub` | per-subscriber egress; see low-server model | current Browser publication carries one representation; dual representation requires a new decision and physical evidence |-| Full central SFU/MoQ fanout | about `B` | ingress `B`, egress `N*B` | a possible bounded fallback result, never the default topology or mode |--Useful last-hop traffic remains approximately `N*B`; these routes only decide-which nodes emit the copies. Exact SFU publication/subscription and billing-accounting is owned by [Low-Server-Cost Media Routes](./low-server-media-routes.md).--## Candidate 1: Native RTP Relay--This is a retained Native research direction, not a current milestone. A-native helper can read-encoded RTP from one WebRTC receiver and write the payload to at most two-independent downstream browser PeerConnections without decoding and encoding-the video again. Each downstream edge keeps its own SSRC, pacing, RTCP,-DTLS-SRTP, and ICE behavior.--Draft PR [#16](https://github.com/TNTcraftHIM/Screener/pull/16) passes an earlier-in-process transport oracle: one Pion v4.2.18 `TrackLocalStaticRTP.WriteRTP`-call reaches two independent PeerConnections with preserved semantic payload,-sequence number, and timestamp plus binding-specific SSRCs. It contains no-encoder or browsers, so it is not evidence for one physical encode, end-to-end-compatibility, feedback arbitration, congestion control, or latency.--If an owning decision reopens it, the retained Go/Pion gate is video-only VP8 at-720p30 with one browser upstream and two unchanged browser children. It must-prove:+- Last reviewed: 2026-08-27+- Scope: advanced low-server distribution candidates for sub-second interactive media+- Status: research comparison and falsifiable gates, not an accepted product route++## Terms And Conservation++Let `B` be one complete stream bitrate, `N` the Viewer count, and `r` repair+overhead. Headers, audio and retransmission are additional. Every Viewer still+needs roughly `B` useful last-hop traffic, so a peer overlay redistributes about+`N*B`; it does not eliminate it.++- **Full-stream relay:** forwards a complete representation to each child.+- **Multiple trees:** split a representation into stripes carried by different+ interior-node-disjoint trees; every receiver reassembles the stripes.+- **SVC:** one encoder creates dependent temporal or spatial layers. It permits+ selective forwarding but does not create a topology or transport.+- **Network coding/FEC:** adds repair symbols so some loss can be recovered+ without retransmission; it neither compresses video nor repairs a failed path.++## Candidate Comparison++| Candidate | Host upload | Relay encode | Potential benefit | Decisive no-go |+| --- | ---: | ---: | --- | --- |+| Browser full-stream tree | up to `C*B` | one per child pipeline | deployable with standard WebRTC | relay CPU, generational loss or hop latency exceeds the small-room value |+| Native RTP relay | up to `C*B` | zero | removes relay re-encode | feedback, pacing or per-child congestion cannot remain isolated and bounded |+| Two encoded stripe trees | about `(1+r)B` | zero | lowers Host upload while retaining peer egress | endpoint upload remains near `2B`, two decoders/compositor are required, or churn breaks assembly |+| Browser encoded objects | about `C*B`, later stripeable | zero | pure-Web single encode and forwarding | application framing, jitter, A/V sync or queues recreate an unsafe media stack |+| FEC/network coding | unchanged plus repair | unchanged | faster repair for bounded loss | clean-path bytes/CPU exceed benefit or whole-path loss still dominates |+| Central SFU/MoQ | about `B` | central forwarding | mature low-latency availability | central egress remains `N*B` without a measured compensating gain |++`C` is an endpoint child bound, not a promise that the endpoint can encode or+upload `C` good streams. Native shared encode can reduce compute, while useful+network copies remain subject to conservation.++## Candidate Gates++### Native RTP Relay++A native relay may read encoded RTP from one receiver and write it to independent+downstream PeerConnections without decoding. Each child still needs its own+SSRC, pacing, RTCP feedback, DTLS-SRTP and ICE state.++Retain only if a 720p30, one-parent/two-child gate proves:- zero relay video-encoder calls and at least 40% lower relay CPU than browserremote-track forwarding;-- no more than 25 ms added p95 relay latency;+- no more than 25 ms added p95 relay latency and queue age below 100 ms;- per-child bytes no more than 110% of input payload bitrate;-- bounded queue age below 100 ms;-- PLI, NACK/RTX, and one direct edge under both clean and 1% loss conditions; and-- reparented first picture within one second after failure detection.--This lowers relay compute and generational quality loss. It does not lower host-or total upload until combined with a native shared sender or striped media.-Relay-capable participants need the helper; ordinary desktop/mobile browsers-remain valid leaves.--## Candidate 2: Two Stripe Trees With SVC--The target shape assigns every relay-capable endpoint at most two downstream-edges. The host sends stripe A to one seed and stripe B to another. An internal-node forwards its assigned roughly `B/2` stripe to at most two children, so its-total upload stays near `B`. Every viewer receives both stripes from two parents.-The host encodes once and sends about `B`, central egress stays near zero, and-relay nodes do not encode.--SVC may make one stripe a base temporal layer and the other enhancement data,-or duplicate selected base data for resilience. SVC alone cannot implement this-shape: the WebRTC SVC API keeps layers in one encoded RTP stream, and WebRTC-Encoded Transform does not permit moving encoded frames across streams. The-data plane therefore requires either native RTP/object nodes or WebCodecs plus-DataChannel.--Start with single-layer 50/50 frame/object striping, then test `L1T2` temporal-SVC only after transport works. Use two deterministic, interior-node-disjoint-trees; do not add a continuous optimizer.--Go gates:--- host and relay upload no more than `1.1B` without repair;-- unique host encode calls equal input frames and relay encode calls stay zero;-- whole-room useful bytes no more than `1.1*N*B` without repair;-- no more than 20 ms p95 overhead per hop and depth-four p95 no more than- 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-- 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-and application-side picture composition.--## Candidate 3: Browser Encoded Objects--WebCodecs can encode once and expose `EncodedVideoChunk` values. WebRTC-DataChannel can carry framed chunks over peer ICE paths. This is the-credible pure-browser route to encoded forwarding and later two-tree striping,-but it replaces the browser's RTP media receiver with application framing,-pacing, a jitter buffer, keyframe requests, a WebCodecs renderer, and eventually-A/V synchronization.--The first spike is only `host -> relay -> leaf`, 720p30 video, reliable control,-and unordered media with bounded retransmission. Use chunks no larger than-16 KiB and a hard `bufferedAmount` ceiling.--Go gates:--- one host encode and zero relay encode;-- at least 30% lower host encode CPU than two browser send pipelines and at- least 40% lower relay CPU than remote-track forwarding;-- framing bytes no more than 110% of the RTP baseline;-- two-hop glass-to-glass p95 no more than 250 ms;-- bounded queues and first picture below one second after reroute; and-- required mobile decoders pass, with later A/V drift no more than 50 ms.--## Candidate 4: FEC And Network Coding--FEC is useful only when repair bytes avoid slower RTX or visible freezes. It-does not reduce clean-path bandwidth or survive permanent loss of a full tree-unless redundancy approaches another complete stream.--Before media integration, replay captured RTP/object traces through a simulator:--- random loss at 0%, 1%, 3%, and 5%;-- 20, 50, and 100 ms bursts at 20, 40, and 80 ms RTT;-- baseline NACK/RTX versus XOR or Reed-Solomon `k=4/8` with one/two repair- symbols, then sliding-window RLC only if those results justify it.--Go gates:--- at least 50% lower residual loss/freeze at 1-3% loss or 20-50 ms bursts;-- repair p95 below 100 ms and at least 25% faster than RTX;-- total media plus repair and residual RTX bytes no more than 110% of baseline- media plus RTX bytes;-- no more than 16 ms generation buffering and 15% active repair overhead; and-- coding CPU below roughly 5% of one reference core.--Clean paths should keep repair disabled or below 3-5%. Whole-path failure still-belongs to the route controller.--## Candidate 5: MoQ--Browser WebTransport connects a browser to a server; it does not make a normal-browser an Internet-listening peer relay. A central MoQ deployment therefore-has the same server-egress class as an SFU. Benchmark it only as an optional-central fallback and keep it only if, at equal quality and egress, latency or-server CPU improves at least 20% over the SFU reference and draft-version churn+- isolated PLI, NACK/RTX and congestion behavior under clean and 1% loss; and+- a decodable first picture within one second after failure detection.++Reject if downstream feedback cannot be isolated, queue age is unbounded, or+ordinary browser leaves lose interoperability. This candidate lowers relay+compute, not total room upload.++### Two Stripe Trees++The Host sends complementary stripes through two deterministic,+interior-node-disjoint trees. An internal node forwards only its stripe; a Viewer+needs both parents and a bounded assembler. SVC alone cannot supply this shape:+its layers remain in one encoded RTP stream, and Encoded Transform does not move+encoded frames between transports.++Start with 50/50 single-layer frame/object striping. Retain only if:++- Host and relay upload stay at or below `1.1B` without repair;+- Host encodes once, relays encode zero times, and room useful bytes stay below+ `1.1*N*B`;+- per-hop overhead is at most 20 ms p95 and depth-four glass-to-glass p95 is at+ most 350 ms;+- path failure restores a decodable picture within one second; and+- repair still saves at least 30% Host upload relative to duplicating `2B`.++Reject if supported clients require unrelated decoders plus application-side+picture composition, or if bounded churn cannot preserve stripe identity.++### Browser Encoded Objects++WebCodecs exposes `EncodedVideoChunk`; DataChannel can carry framed objects over+peer ICE. This replaces the browser RTP receiver with application pacing,+framing, jitter buffering, keyframe requests, rendering and eventually A/V sync.++The first gate is only `Host -> relay -> leaf`, 720p30, chunks no larger than+16 KiB and a hard `bufferedAmount` ceiling. Retain only if:++- the Host encodes once and the relay does not encode;+- Host encode CPU falls at least 30% versus two browser send pipelines and relay+ CPU falls at least 40% versus remote-track forwarding;+- framing bytes are no more than 110% of the RTP baseline;+- two-hop glass-to-glass p95 is at most 250 ms, queues remain bounded, and first+ picture after reroute is below one second; and+- required mobile decoders pass and later A/V drift stays within 50 ms.++Reject rather than growing an application RTP replacement when those gates fail.++### FEC And Network Coding++First replay captured RTP/object traces through a simulator: random loss at+0/1/3/5%, 20/50/100 ms bursts, and 20/40/80 ms RTT. Compare NACK/RTX with small+XOR or Reed-Solomon blocks; consider sliding-window RLC only if simpler repair+passes.++Retain only if 1-3% loss or 20-50 ms bursts show at least 50% lower residual+loss/freeze, repair p95 below 100 ms and at least 25% faster than RTX, total media+plus repair and residual RTX no more than 110% of baseline, generation buffering+at most 16 ms, active repair overhead at most 15%, and coding CPU below about 5%+of one reference core. Clean paths should keep repair absent or minimal.++### MoQ++Browser WebTransport connects to a server; it does not turn a normal browser into+an Internet-listening peer relay. A central MoQ service therefore retains the+same egress class as an SFU. Keep it only if equal-quality measurements improve+latency or server CPU by at least 20% at the same egress, and draft-version churnis isolated behind a small adapter.-## Current Bounded Local Reconciliation Conclusion--This is the research basis for ADR-0005's bounded local reconciliation. Narada and Overcast-demonstrate measurement-driven overlay improvement, but neither supplies a-maintained WebRTC RTP/RTCP routing library. BitTorrent/WebTorrent and P2P Media-Loader use chunk-pull swarms and-playout buffers, while SplitStream requires striped multi-tree media.-Their exploration and hysteresis ideas are useful, but none is a drop-in route-controller for sub-second screen sharing. A mature SFU is the directly reusable-low-latency alternative, with central egress rather than audience forwarding.--This product has too few children per relay to infer parent-wide quality from a-small set of sibling samples. Mature outlier detection requires materially more-independent hosts and request volume before statistical ejection; route policy-therefore does not use sender/viewer correlation, sibling voting, relative FPS,-or a room score. Those metrics remain diagnostic.--The application consumes only an exact child edge's hard connection failure or-a non-paused interval with no newly decoded frame. That child enters ADR-0005's-single reconciliation loop. If the child is itself a relay, changing its ingress-retains its subtree. If several downstream edges fail, each child reparents-independently and the old relay naturally empties. WebRTC and LiveKit retain-transport connectivity, consent, congestion control, reconnection, and SFU-stream-state ownership.--Every upstream change uses one bounded transaction. The candidate is bound to-the authenticated endpoint sessions, share generation, base and pending route-revisions, and candidate connection. A usable old edge stays authoritative until-the candidate child decodes its first new video frame. That single event already-proves the candidate's ICE/DTLS/RTP/decode path; failure or deadline expiry-releases the candidate and wakes the same loop for the next choice.--For `N` Viewers a peer tree still has `N` media edges and approximately `N*B`-useful upload in aggregate. Local reparenting redistributes that traffic; it does-not eliminate it. The controller therefore keeps a healthy tree sticky and only-handles waiting or invalid edges.--Candidate inputs remain discrete: an active authenticated session,-effective capacity with a free downstream slot, acyclicity, source reachability,-and server admission. Standard ICE owns candidate-pair-priority, pruning, connectivity checks, peer-reflexive discovery, and nomination-inside one `RTCPeerConnection`; the application does not build another ping mesh.--The controller orders eligible parents by shallowest resulting tree, remaining-steady sender slots, stable join order, and peer identity. It keeps healthy-assignments sticky and changes only one child upstream per room transaction. A-provisional child reserves the required endpoint and server resources until-commit or abort. If an old edge is usable, make-before-break retains it until the-candidate child decodes; a hard-invalid edge uses the same transaction without-pretending the old media still works. No weighted score, UA/device model, IP-geography, claimed NAT type, cooldown optimizer, or role-specific rescue path is-part of selection.--## Staged Connection Recovery Evidence--Recovery should spend attempts on different layers, not repeat one opaque action-three times. The current WebRTC Recommendation advises an ICE restart when-`iceConnectionState` reaches `failed`; for `disconnected`, it recommends first-checking whether sent/received bytes progress over the next couple of seconds.-Pinned LiveKit client 2.22.0 uses reconnect delays of 0, 300, 1,200, 2,700,-4,800 and then 7,000 ms (with later jitter), a 15-second peer/WebSocket timeout,-and a four-second state reconciliation that requires three consecutive-mismatches before a full reconnect. Jitsi Videobridge similarly defaults to a-15-second first-transfer timeout and an eight-second inactivity limit. These are-reference boundaries, not universal prescriptions. Screener's separately owned-15-second ViewerPeer connection watchdog and the controller's 20-second route-deadline are implementation values, not accepted experience targets;-mobile-network evidence may justify revisiting them only through ADR-0005.--WebRTC/LiveKit first owns transient reconnect. A hard failure or non-paused-decoded-frame stall wakes ADR-0005 once and seeds the exact failed-`parent + transport` tuple as already tried. The same room operation tries other-direct parents, then different admitted transports and Host-publication SFU-under current capacity and server admission. There is no separate same-edge-repair ladder or persistent parent blacklist.-Every completion is guarded by the current authenticated sessions, share-generation, pending route revision, and candidate connection. Sustained bitrate,-FPS, resolution, and blur remain diagnostic.--The historical v8 room-1 production trace on 2026-08-20 observed two short Host-participants while two roots remained for roughly 4.6 seconds; all ended with-client-requested leave, no track publication survived, and neither service-restarted. This proves LiveKit participant entry. The timing is consistent with-the then-current one-shot grant refresh and recovery state machine, but logs do-not prove those transitions and cannot distinguish-connect, source, video publish, sender configuration, optional audio publish, or-transport failure. The production diagnostic exposes only a closed local-stage/outcome enum to an on-demand Host snapshot and deliberately keeps raw-errors, URLs, tokens, candidates, and addresses out of wire and logs.--## Automatic Route Controller Boundary--The 2026-08-26 production trace established a controller defect rather than a-missing relay topology: one SFU-fed Viewer was repeatedly tried as the first-direct parent, and its silent 10-second attempt caused every later direct parent-to be skipped before SFU reuse. Offer, answer, trickled candidates, relay-capacity, and the untried P2P-fed parent were all present. A room-wide serial-candidate therefore amplified one slow parent into queue delay for every later-Viewer.--The same trace contained four exact P2P first-frame successes at 0.488, 0.584,-0.593, and 2.901 seconds. The current five-second foreground head start covers-that observed maximum while halving the failed-candidate queue delay. It is a-measured product budget, not a browser or ICE standard; SFU-backed background-convergence preserves slower candidates for the full route deadline.-Standard `RTCPeerConnection.connectionState = connected` proves that the exact-ICE/DTLS transport is established but not that RTP video decoded. Screener may-therefore use it only to retain that candidate through the total route deadline;-the first newly decoded frame remains the sole graph-commit proof.--Browser ICE already races and paces address, interface, and NAT candidate pairs-inside one exact `RTCPeerConnection`. There is no mature Web API that races-multiple remote peers as one connection; each additional peer requires another-offer/answer, ICE/DTLS/RTP state, reservation, and potentially another media-encode. Jitsi provides the closest deployed model: it retains its JVB session,-attempts one exact P2P session, and stops using JVB only after P2P ICE succeeds.-Chunk swarms such as CoolStreaming, WebTorrent, PeerTube, and commercial eCDN-systems can contact several suppliers because buffered segments are-interchangeable; that model does not apply to one live RTP `MediaStream`.--The retained Browser design consequently keeps one current candidate and one-authoritative graph. Initial acquisition gives one best direct parent a bounded-head start before SFU and uses a stable pairwise hash to distribute otherwise-equal parent choices; once SFU has a current decoded frame, the remaining exact-direct parents are attempted one at a time behind that media. A new unrouted or-repairing Viewer preempts this low-priority convergence. Direct success commits-make-before-break on its first decoded frame; exhaustion leaves healthy SFU-unchanged. Literal multi-parent racing or concurrent child operations require a-new wire/revision/reservation model and remain outside the current result.--The accepted controller preserves healthy peer edges and chooses one route per-logical edge: direct/STUN first, then the dedicated SFU/UDP path when needed. A-server-fed ingress uses the room's single Host publication plus exact SFU-subscriptions; it is not a fixed rung inserted between every peer edge.-Every attempt ends in bounded success, wait, or failure.--Native full-stream relay and striped-object routes remain the bounded candidates-above; passing their own gates may change capability, but does not insert them-into the current route model.--The SFU uses one authoritative Host publication and exact per-Viewer-subscriptions. SFU-fed and peer-fed endpoints use the same provisional-child-first-frame transaction. Server ingress/egress uses deployment-wide admission-rather than a fixed root count or room-wide lease. The SFU/UDP accounting lives-in [Low-Server-Cost Media Routes](./low-server-media-routes.md). ADR-0005 owns-the accepted behavior.--The controller is automatic and invisible. It uses participant metadata, route-revisions, endpoint capacity, server admission, and discrete exact-edge failure;-it exposes no topology choices. One reconcile loop handles join, waiting,-disconnect, effective-capacity overflow, and failed edges. W3C-`framesDecoded` counts successfully decoded video frames, so the first new-candidate frame is the only application readiness event. LiveKit owns SFU-reconnection and stream state. The one pending candidate's receive-transport-owner therefore uses a short-lived exact-generation stats observer until a-fresh peer/SFU activation has a positive cumulative count; a prepared SFU route-that remained alive while paused instead takes a Resume-time baseline and waits-for later progress. It stops on proof, promotion, pause, replacement, or-teardown, creates no additional deadline, and is distinct from the existing-two-second active-path diagnostic/stall sampler. The application adds no-network-type poll or SFU-specific route timer.--The overlap edge is physical: an active Host SFU publication consumes one steady-sender slot, and a media-producing provisional peer candidate consumes another.-Every non-server parent uses deployment capacity `C in {1,2,3}` without a-Browser tier. A free steady slot permits ordinary make-before-break; otherwise a-single fenced `TransitionOverlapSlot` may raise the physical count only to-`min(C + 1, 3)`. A full `C=3` endpoint must wait, use a bounded-gap transition,-or fail before creating a fourth copy. Failed or stale probes restore the prior-controller revision and release their reservation before reconciliation-continues.+## Local Reconciliation Evidence++Narada, Overcast and NICE show that overlay measurements can improve tree shape;+SplitStream adds multi-tree striping. BitTorrent, WebTorrent, CoolStreaming and+P2P Media Loader can contact several suppliers because buffered chunks are+interchangeable. None is a maintained drop-in controller for a live+`MediaStream` with sub-second interaction.++ICE already races and paces address, interface and NAT candidate pairs inside+one exact `RTCPeerConnection`. Trying another parent requires another+offer/answer, ICE/DTLS/RTP state, reservation and potentially another encoder.+Application-level all-pairs probing therefore multiplies real media work rather+than extending ICE Happy Eyeballs.++For a small room, one to three child observations do not provide the independent+sample volume needed for statistical host ejection or a stable weighted score.+Current-edge stats can diagnose that edge; they cannot prove an unconnected+parent is better.++The smallest general reconciliation model supported by this evidence is:++1. one authoritative graph and one event-driven desired/current loop;+2. hard eligibility from authenticated presence, bounded capacity, acyclicity+ and source reachability;+3. at most one child transition at a time, fenced to exact sessions, source and+ connection identity;+4. make-before-break when the old path remains usable, with the first newly+ decoded frame as commit proof; and+5. release on failure or deadline, while transport libraries retain ICE,+ consent, congestion control and transient reconnect ownership.++Reparenting a relay can retain its subtree, and several bad child edges can move+independently. This changes traffic placement, not the `N*B` aggregate. Library+retry values are implementation references, not universal application timers;+any timeout must be measured against the target network and user-visible bound.## Sources And License Boundary-Sources checked on 2026-08-20 through 2026-08-24:--- [WebRTC SVC](https://www.w3.org/TR/webrtc-svc/),- [Encoded Transform](https://www.w3.org/TR/webrtc-encoded-transform/),- [WebCodecs](https://www.w3.org/TR/webcodecs/), and- [WebTransport](https://www.w3.org/TR/webtransport/) - W3C specifications.-- [WebRTC Data Channels, RFC 8831](https://www.rfc-editor.org/rfc/rfc8831.html)+- [WebRTC](https://www.w3.org/TR/webrtc/), [WebRTC Stats](https://www.w3.org/TR/webrtc-stats/),+ [WebRTC SVC](https://www.w3.org/TR/webrtc-svc/), [Encoded Transform](https://www.w3.org/TR/webrtc-encoded-transform/),+ [WebCodecs](https://www.w3.org/TR/webcodecs/), and [WebTransport](https://www.w3.org/TR/webtransport/).+- [ICE, RFC 8445](https://www.rfc-editor.org/rfc/rfc8445.html), [ICE Happy Eyeballs, RFC 8421](https://www.rfc-editor.org/rfc/rfc8421.html),+ [Trickle ICE, RFC 8838](https://www.rfc-editor.org/rfc/rfc8838.html), [Data Channels, RFC 8831](https://www.rfc-editor.org/rfc/rfc8831.html),and [Sliding-window RLC, RFC 8681](https://www.rfc-editor.org/rfc/rfc8681.html).-- [Pion WebRTC](https://github.com/pion/webrtc) and- [klauspost/reedsolomon](https://github.com/klauspost/reedsolomon) - MIT; no- source copied.-- [WebRTC Recommendation](https://www.w3.org/TR/webrtc/) - `failed` ICE restart- and `disconnected` bytes/stats guidance.-- [ICE, RFC 8445](https://www.rfc-editor.org/rfc/rfc8445.html),- [ICE Happy Eyeballs, RFC 8421](https://www.rfc-editor.org/rfc/rfc8421.html),- [Trickle ICE, RFC 8838](https://www.rfc-editor.org/rfc/rfc8838.html), and- [ICE PAC, RFC 8863](https://www.rfc-editor.org/rfc/rfc8863.html) - one exact- peer's native candidate checks and why application deadlines cannot infer an- untried parent.-- [JitsiConference P2P/JVB ownership](https://github.com/jitsi/lib-jitsi-meet/blob/master/JitsiConference.ts)- - mature server-media retention until one exact P2P session succeeds.-- [LiveKit client 2.22 reconnect policy](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/DefaultReconnectPolicy.ts),- [room defaults](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/defaults.ts),- and [state reconciliation](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/Room.ts)- - pinned implementation behavior, not a universal timeout prescription.-- [Kubernetes controllers](https://kubernetes.io/docs/concepts/architecture/controller/)- - event-driven desired/current reconciliation reference; no scheduler or- disruption framework is copied.-- [Envoy outlier detection](https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/cluster/v3/outlier_detection.proto)- - statistical host ejection defaults require at least five hosts and material- request volume, unlike Screener's one-to-three child sample.-- [LiveKit server 1.13.5 participant quality aggregation](https://github.com/livekit/livekit/blob/v1.13.5/pkg/rtc/participant.go)- and [connection scorer](https://github.com/livekit/livekit/blob/v1.13.5/pkg/sfu/connectionquality/scorer.go)- - Apache-2.0; studied only, with no source copied.-- [Jitsi Videobridge endpoint status defaults](https://github.com/jitsi/jitsi-videobridge/blob/master/jvb/src/main/resources/reference.conf)- - first-transfer and inactivity reference values.-- [SplitStream](https://www.microsoft.com/en-us/research/publication/splitstream-high-bandwidth-multicast-in-a-cooperative-environment/)- and [Network Coding for Large Scale Content Distribution](https://www.microsoft.com/en-us/research/publication/network-coding-for-large-scale-content-distribution/)- - research evidence, not reusable source licenses.-- [Narada](https://www.cs.cmu.edu/~srini/papers/papers/2002-Chu-jsac/2002-Chu-jsac.pdf),+- [SplitStream](https://www.microsoft.com/en-us/research/publication/splitstream-high-bandwidth-multicast-in-a-cooperative-environment/),+ [Narada](https://www.cs.cmu.edu/~srini/papers/papers/2002-Chu-jsac/2002-Chu-jsac.pdf),[Overcast](https://pdos.csail.mit.edu/~jj/jannotti.com/papers/overcast-osdi00/),[NICE](https://conferences.sigcomm.org/sigcomm/2002/papers/appmulti.pdf), and- [CoolStreaming/DONet](https://www.cs.sfu.ca/~jcliu/Papers/47_01.pdf) -- original application-layer multicast and live-streaming research.+ [CoolStreaming/DONet](https://www.cs.sfu.ca/~jcliu/Papers/47_01.pdf).- [BitTorrent BEP 3](https://www.bittorrent.org/beps/bep_0003.html),[WebTorrent](https://github.com/webtorrent/webtorrent), and- [P2P Media Loader](https://github.com/Novage/p2p-media-loader) - mature- chunk/segment swarms, not an RTP route implementation.-- [WebRTC statistics](https://www.w3.org/TR/webrtc-stats/) and- [LiveKit SFU](https://docs.livekit.io/reference/internals/livekit-sfu/) -- observable path boundaries and the centralized low-latency alternative.-- [LiveKit client 2.22 room events](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/Room.ts)- - pinned reconnect/reconnected behavior; no implementation source was copied.-- [MOQT draft](https://datatracker.ietf.org/doc/draft-ietf-moq-transport/) and- [moq-dev/moq](https://github.com/moq-dev/moq) - core MIT/Apache-2.0; its OBS- plugin is separately GPL-2.0-or-later and remains study-only.--No GPL/AGPL implementation code was copied.+ [P2P Media Loader](https://github.com/Novage/p2p-media-loader).+- [Pion WebRTC](https://github.com/pion/webrtc) and+ [klauspost/reedsolomon](https://github.com/klauspost/reedsolomon) are MIT;+ [LiveKit](https://github.com/livekit/livekit) is Apache-2.0.+- [Jitsi P2P/JVB ownership](https://github.com/jitsi/lib-jitsi-meet/blob/master/JitsiConference.ts)+ is implementation evidence, not copied code.+- [MOQT](https://datatracker.ietf.org/doc/draft-ietf-moq-transport/) and+ [moq-dev/moq](https://github.com/moq-dev/moq) are study references; the core+ uses MIT/Apache-2.0 while its OBS plugin is GPL-2.0-or-later.++No GPL/AGPL implementation code is copied or required by these candidates.diff --git a/docs/research/agent-context-governance.md b/docs/research/agent-context-governance.mdindex d01ffa6d..28243ee7 100644--- a/docs/research/agent-context-governance.md+++ b/docs/research/agent-context-governance.md@@ -1,66 +1,66 @@-# Agent Context And Repository Governance+# Agent Context And Documentation Governance-- Reviewed: 2026-08-22-- Scope: official Codex, Claude Code, Hermes Agent, and GitHub guidance-- Status: adopted repository-maintenance evidence+- Reviewed: 2026-08-27+- Scope: repository context, durable memory, documentation types, and decisions+- Status: evidence; repository policy is owned by+ [maintenance](../maintenance.md)## Findings-### Codex+### Repository Context-OpenAI recommends giving Codex a map rather than a large instruction manual.-Its own agent-first repository keeps a short root `AGENTS.md` that points to a-structured documentation tree. OpenAI reports that giant instruction files-crowd out task context, become hard to verify, and accumulate stale rules. Codex-works best when the repository also provides reliable tests, clear documentation,-and project-specific navigation and commands.+OpenAI's agent-first repository treats `AGENTS.md` as a map into a structured,+versioned knowledge base. Its reported failure mode for one large instruction+file is the same one observed in Screener: scarce context is crowded out, every+rule appears equally important, stale guidance accumulates, and ownership is+hard to verify. The recommended corrective structure is progressive disclosure,+cross-links, and mechanical freshness/structure checks.-Sources:--- [Harness engineering: leveraging Codex in an agent-first world](https://openai.com/index/harness-engineering/)-- [Introducing Codex](https://openai.com/index/introducing-codex/)--### Claude Code+Anthropic likewise recommends concise, specific project instructions and moves+multi-step procedures or path-specific rules to on-demand skills or scoped rule+files. A size ceiling is not a target.-Anthropic recommends specific, concise project instructions. Facts needed for-every session belong in the root memory file; multi-step procedures and-path-specific rules belong in skills or scoped rule files. The official guide-suggests keeping `CLAUDE.md` below 200 lines and periodically removing stale or-conflicting instructions. It also supports importing an existing `AGENTS.md`-instead of maintaining a second copy.+Hermes distinguishes project conventions (`AGENTS.md`) from user preference,+personality, and learned memory. Its persistent memory is deliberately bounded+and curated; full session history remains searchable on demand rather than being+injected into every prompt. Memory is a frozen session-start snapshot, so it+cannot replace current repository truth. Nested context is useful only when a+subtree has genuinely distinct rules.-Source: [Claude Code memory](https://code.claude.com/docs/en/memory)+Sources:-### Hermes Agent+- [OpenAI Harness engineering](https://openai.com/index/harness-engineering/)+- [Claude Code memory](https://code.claude.com/docs/en/memory)+- [Hermes file ownership](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/which-file-does-what.md)+- [Hermes persistent memory](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/memory.md)-Hermes separates project conventions in `AGENTS.md` from user memory,-personality, and other persistent state. Its project instructions are discovered-progressively, so nested files can own narrower rules without loading every-detail at repository startup.+### Documentation Shape-Source: [Which File Does What?](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/which-file-does-what.md)+Diataxis separates tutorial, how-to, reference, and explanation because mixing+reader goals makes each form harder to use. Screener's internal product modules+are compact reference; ADRs are explanation of a decision; deployment is a+how-to/reference boundary; research is evidence and explanation. The framework+does not require creating all four categories when there is no reader need.-### GitHub+An ADR should be a short record of one decision: context, decision, material+consequences, status, and links to supporting evidence. If a decision changes,+the old record is superseded instead of being expanded into a current manual.-Git history and pull requests are the durable record for completed work. Current-documents should not duplicate a release diary or preserve rejected alternatives-solely for history.+Git commits and pull requests own completed history. Current product and+operations documents should not preserve rejected alternatives, release diaries,+or agent process solely for chronology.-Source: [GitHub Flow](https://docs.github.com/en/get-started/using-github/github-flow)+Sources:-## Adopted Shape+- [Diataxis primer](https://diataxis.fr/start-here/)+- [Martin Fowler: Architecture Decision Record](https://martinfowler.com/bliki/ArchitectureDecisionRecord.html)+- [GitHub Flow](https://docs.github.com/en/get-started/using-github/github-flow)-- Root `AGENTS.md` targets roughly 50 lines and contains only cross-task hard- constraints, product contract, truth navigation, and essential safety rules.-- `CONTRIBUTING.md` owns branch, research, validation, PR, merge, and cleanup- procedures.-- Project memory and status are short current snapshots; `docs/todo.md` is the- only current work ledger; requirements, design, ADRs, and research own detail.-- Rejected alternatives and explanations of their removal leave current truth.- Git owns that history.-- Hooks verify required tracked files, links, size budgets, and deterministic- repository hygiene. They do not replace semantic review.+## Applicability-This structure is intentionally below the published size ceilings. A ceiling is-not a target: additional top-level text must be necessary on every task or move-to its closest owner.+Screener is small enough that a vector database, memory provider, generated code+map, parallel agent-context format, or separate RFC repository would add more+ownership than it removes. The useful practices are bounded always-on context,+one owner per fact, domain-shaped reference, evidence on demand, short ADRs,+link checks, and Git-backed history. Exact repository policy remains in+[maintenance](../maintenance.md), not in this research note.diff --git a/docs/research/browser-background-capture.md b/docs/research/browser-background-capture.mdindex 2572bf08..951c6cde 100644--- a/docs/research/browser-background-capture.md+++ b/docs/research/browser-background-capture.md@@ -1,395 +1,211 @@# Browser Background Capture Diagnostics- Research date: 2026-08-24-- Scope: desktop Chrome/Edge Web Host capture while the Host page is- unfocused, occluded, backgrounded, or minimized-- Status: Host capture report remains unconfirmed; Viewer resume/state lifecycle- correction is accepted pending integration and does not claim capture keepalive--## Current Conclusion--There is no evidence that Screener is missing a page-liveness signal. Chromium-already marks live `MediaStreamTrack` use as a scheduler opt-out from aggressive-throttling and wake-up alignment, feeds active capture into both renderer-priority policy paths, and holds an internal application-suspension wake lock-for active peer connections. Those mechanisms are intended to protect active-media from ordinary invisible-page background treatment; they do not guarantee-a requested capture rate, encoder throughput, or remote rendering rate, and no-Web API lets an application assert additional foreground scheduling priority.--A bounded Chrome 151 screening on the current Windows test machine also kept-real window capture, VP8 encoding, loopback receipt, and decode at about 29.4 to-29.6 fps while the Host document was focused, in a hidden tab, and in a-minimized browser window. No immediate Host-document background drop was-observed in those 15-second windows. The sample does not reproduce the reported-game workload, separate physical Viewer, production route, CPU/GPU contention,-or browser policies whose documented hidden-state threshold exceeds five-minutes.--The current report therefore remains open but diagnostic-only. It must-distinguish five different effects before any product change is considered:--1. Host preview or stats presentation is throttled while transmitted media is- unchanged.-2. The selected display surface becomes inaccessible, muted, unchanged, or- otherwise constrained by the browser, operating system, or capture backend.-3. Capture work or video encoding is CPU/GPU constrained.-4. WebRTC congestion control reduces outbound resolution, frame rate, or- bitrate.-5. The Viewer receives the normal stream but decodes, renders, or displays it- differently.--The Host page lifecycle and the captured source lifecycle are independent-variables. The Screen Capture specification permits a user agent to treat a-minimized captured surface as temporarily inaccessible and mute its track; it-does not say that minimizing the separate capturing page must reduce capture.-Capture constraints are post-selection preferences and allow frame decimation,-so requested `maxFramerate` is not proof of actual source or encoded frame rate.--Current production may select H.264 or VP8 through its bounded sender-gate. Every run still records the actual negotiated codec and encoder rather than-inferring either from configuration. Encoder implementation is a diagnostic-variable only after a stable baseline exists; neither codec nor encoder choice-is a page-keepalive mechanism.--The accepted Browser path uses `contentHint = "motion"`. A controlled-probe showed that this standard game-motion hint can spatially downscale to-preserve cadence; that quality tradeoff is independent from page lifecycle and-does not explain a state-dependent background report. The physical baseline-must start from current production rather than carrying an old report forward-as a current regression.--The Host investigation reopens only if the report reproduces on current-production with a continuously changing real game and synchronized capture,-send, receive, decode, CPU, and GPU evidence. Mobile Viewer background playback-and assigned-relay survival remain a separate browser/OS lifecycle gate and do-not inherit this desktop Host result.--## Current Source Boundary--Canonical source and production use the content-independent H.264 gate with VP8-fallback, video `contentHint = "motion"`, audio `contentHint = "music"`, and the-local share-locked Host codec selector without a codec wire field. Their exact-identity is owned by [status](../status.md).-The current path does not claim or implement a page-keepalive mechanism, and-deployment health supplies no physical background-capture evidence.--- Current `src/client/media/quality.ts` obtains one `getDisplayMedia()` stream,- applies ideal/max capture constraints, sets standard game-motion intent, and- applies sender bitrate, frame-rate, and degradation ceilings. Explicit- sharing pause and authoritative reconnect re-pause change capture tracks'- `enabled` state; neither manufactures foreground activity. Audio- `contentHint = "music"` remains unchanged.-- `src/client/pages/HostPage.tsx` pauses the existing local preview video when- the Host document is hidden or unfocused and resumes that preview when it is- visible and focused. This does not stop, mute, disable, or replace the capture- track or any sender.-- No `requestAnimationFrame()` loop drives source or production capture or sending.- WebRTC capture, encoding, congestion control, and transport remain- browser-owned.-- `src/client/webrtc/stats.ts` already distinguishes capture settings,- `media-source` encoder-input rate, outbound RTP rate and counters, encode- work, limitation reason, codec, encoder, and receiver metrics. Its interval- calculations use RTCStats timestamps, so delayed UI timer delivery must not- be inferred as an equal media-rate drop.-- The local connection-details UI shows only the latest bounded sample; it is a- cross-check rather than a historical trace and no longer exports a file.-- The short-lived pending-candidate decoded-frame observer reads cumulative RTP- progress only for the exact pending route. It neither drives capture nor proves- document activity, and it stops when that operation settles.-- Viewer resume/visibility recovery rebaselines the existing decoded-stall wall- clock and rearms current-frame presentation. It prevents frozen JavaScript- time from becoming an immediate route failure; it does not keep a page,- capture source, encoder, or network process alive.-- `scripts/peer-assisted-benchmark.ts` is not evidence for this issue: its- synthetic canvas source is timer-driven and its browser launch explicitly- disables background timer, occluded-window, and renderer backgrounding.--The first investigation uses these existing fields plus local browser-diagnostics. It does not authorize a server telemetry schema, persistent-history, background push, or another media lifecycle.--## Primary Evidence--All sources were checked on 2026-08-24.--- [W3C Screen Capture](https://www.w3.org/TR/screen-capture/) defines the- captured-surface mute/end lifecycle and permits post-selection downscaling- and frame decimation. It leaves the definition of temporary surface- inaccessibility to the user agent and operating system. This is a Working- Draft, so it is a diagnostic boundary rather than a cross-browser performance- guarantee.-- [W3C Media Capture and Streams](https://www.w3.org/TR/mediacapture-streams/)- keeps a `MediaStreamTrack` and its consumers distinct. A local media element- and an `RTCPeerConnection` consume the same track independently.-- [W3C WebRTC Statistics](https://w3c.github.io/webrtc-stats/) defines- `media-source` as media after track constraints and before encoding, while- outbound RTP describes encoded transmission. Cumulative counter deltas and- stats timestamps are the comparison basis. Optional absent fields remain- unknown. This is an Editor's Draft and does not require every browser to emit- every optional member.-- [WHATWG HTML Page Visibility](https://html.spec.whatwg.org/multipage/interaction.html#page-visibility)- defines observable document visibility; it does not define capture or encoder- priority.-- [Chromium capture accounting](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/content/browser/renderer_host/render_frame_host_impl.cc)- forwards the first `kCapturingMediaStream` to the renderer process, and the- [process-priority calculation](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/content/browser/child_process_launcher.cc)- treats a media stream as non-background when no priority override exists.- Chromium's- [Performance Manager voter registration](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/performance_manager/performance_manager_lifetime.cc)- separately installs `FrameCapturingMediaStreamVoter` to cast a- `USER_BLOCKING` vote for a capturing frame when that priority path is active.- These are implementation policies, not a priority measurement from the local- screening.-- [Chromium `MediaStreamTrack` scheduling](https://chromium.googlesource.com/chromium/src/+/0b9090f669ed390bbc61eadcd59a05ca98c6a0bc/third_party/blink/renderer/modules/mediastream/media_stream_track_impl.cc)- disables aggressive throttling and wake-up alignment while a live or muted- track exists. Ordinary hidden-page JavaScript timer batching remains- independent.-- [Chrome chained-timer throttling](https://developer.chrome.com/blog/timer-throttling-in-chrome-88)- says hidden-page timers may be batched and `requestAnimationFrame()` is not a- background clock. A live WebRTC media track avoids the intensive once-per-- minute timer tier, but ordinary background timer batching can still make a- UI sampler appear stale.-- [Chrome Energy Saver freezing](https://developer.chrome.com/blog/freezing-on-energy-saver)- excludes active screen/window/tab capture and a peer connection with a live- media track from the documented Chrome 133 freezing policy. That exclusion- is not an encoder or frame-rate guarantee.-- [Chromium `DesktopCaptureDevice`](https://chromium.googlesource.com/chromium/src/+/master/content/browser/media/capture/desktop_capture_device.cc)- schedules capture in the browser capture subsystem, requests an internal- display-sleep wake lock, and by default limits desktop capture to 50% of one- CPU core by lengthening the next capture period when capture work is slow. On- supported current Windows builds it also permits damage-driven WGC 0 Hz- behavior for unchanged content. This is direct evidence for measuring capture- work and actual content changes rather than manufacturing renderer activity- or treating intentionally absent duplicate frames as degradation.-- [WebRTC Windows WGC minimized-window tests](https://webrtc.googlesource.com/src/+/master/modules/desktop_capture/win/wgc_capturer_win_unittest.cc)- require temporary capture errors when the captured window itself is minimized- and recovery after it is restored. This is distinct from minimizing the- separate Host browser window and does not specify JavaScript event timing.-- [Chromium WebRTC internals owner](https://chromium.googlesource.com/chromium/src/+/master/content/browser/webrtc/webrtc_internals.cc)- requests an internal application-suspension wake lock for active peer- connections. This internal browser behavior is not equivalent to the Web- Screen Wake Lock API and is not an application control surface.-- [Chromium WebRTC internals dump UI](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/content/browser/webrtc/resources/webrtc_internals.html)- provides local API-event and getStats evidence. Its full dump is private lab- input, not a project artifact.-- [W3C Screen Wake Lock](https://www.w3.org/TR/screen-wake-lock/) only attempts- to prevent a visible document's screen from turning off; hidden documents- lose the lock. It does not promise capture, encoder, timer, or renderer- priority.-- [Chrome performance settings](https://support.google.com/chrome/answer/12929150)- and [Edge performance features](https://support.microsoft.com/en-us/edge/learn-about-performance-features-in-microsoft-edge)- provide user-side energy and sleeping controls. Edge explicitly excludes- active window/screen and user-media capture from Sleeping Tabs, while Energy- Saver can still affect video or gaming smoothness. Browser exclusions are- useful A/B controls, not Web application keepalive APIs.--## Bounded Current-Browser Screening--On 2026-08-24, before the current motion-hint decision, Chrome-`151.0.7922.174` on Windows 25H2 build `26200.9168`-captured a continuously changing native WPF window through real-`getDisplayMedia()`. The source remained visible and changing; capture returned-1186x712 at a 30 fps setting. One VP8/libvpx sender used no video hint, a 5 Mbps-ceiling, 30 fps ceiling, `scaleResolutionDownBy = 1`, and `balanced`, with one-same-machine loopback receiver. Each state had one 15-second RTCStats window.-The automation flag selected the named window in the picker only; no-background-timer, occlusion, renderer-priority, Energy Saver, or capture policy-was disabled.--| Host state | Capture fps | Encoded fps | Sent bitrate | Encode ms/frame | Decoded fps | Limitation |+- Scope: desktop Chrome/Edge screen capture when the capturing document or the+ selected surface changes foreground state+- Status: bounded platform evidence; the reported background degradation has+ not been reproduced++## Conclusion And Physical Boundary++The capturing document and the selected display surface have independent+lifecycles. Page Visibility exposes only the document's visibility. It does not+define capture, encoding, transport, decoding, or rendering priority. Conversely,+the Screen Capture specification permits a browser and operating system to treat+a selected surface as temporarily inaccessible. A minimized captured window may+therefore mute or interrupt its track even when the capturing document is active.++Capture constraints are post-selection preferences. The browser may downscale or+decimate frames, so a requested maximum frame rate is not proof of capture-source+or encoded progress. A local preview and an `RTCPeerConnection` are independent+consumers of the same `MediaStreamTrack`; a paused or throttled preview does not+by itself prove that transmission stopped.++Current Chromium evidence narrows, but does not remove, the platform boundary:++- active capture contributes to renderer/process priority policy;+- a live or muted `MediaStreamTrack` opts its frame out of aggressive throttling+ and wake-up alignment;+- an active peer connection holds Chromium's internal application-suspension+ wake lock;+- Chrome's documented Energy Saver freezing excludes active display capture and+ a peer connection with a live media track; and+- desktop capture runs in the browser capture subsystem, applies a CPU budget,+ and may intentionally produce no duplicate frames for unchanged content.++These are browser implementation policies, not Web API guarantees of capture+FPS, encoder throughput, or remote presentation. The Screen Wake Lock API only+tries to keep a visible document's screen awake and is not a capture-priority+control. Browser energy and sleeping controls are user-side experimental+variables, not application keepalive mechanisms.++The open report must distinguish: document/UI sampling delay, selected-surface+inaccessibility, capture or encode pressure, WebRTC congestion adaptation,+receiver decode pressure, and presentation lifecycle. No workaround follows+until aligned evidence identifies one of those owners.++## Controlled Screening Result++On 2026-08-24, Chrome `151.0.7922.174` on Windows 25H2 build `26200.9168`+captured a continuously changing native WPF window through `getDisplayMedia()`.+The selected surface remained visible and changing. Capture settings were+1186x712 and 30 fps. One unchanged peer connection, sender, and track used+VP8/libvpx, no video content hint, a 5 Mbps ceiling, a 30 fps ceiling,+`scaleResolutionDownBy = 1`, and `balanced`. A same-machine loopback receiver+provided one 15-second RTCStats window per state. Automation selected the named+window only; it did not disable timer, occlusion, renderer-priority, Energy+Saver, or capture policy.++| Capturing-document state | Capture fps | Encoded fps | Sent bitrate | Encode ms/frame | Decoded fps | Limitation || --- | ---: | ---: | ---: | ---: | ---: | --- || Focused | 29.58 | 29.58 | 1276 kbps | 1.50 | 29.51 | `none` || Hidden tab | 29.53 | 29.53 | 1206 kbps | 1.35 | 29.53 | `none` || Focused after hidden | 29.58 | 29.51 | 1231 kbps | 1.52 | 29.51 | `none` |-| Browser window minimized | 29.39 | 29.39 | 1316 kbps | 1.45 | 29.39 | `none` |+| Browser minimized | 29.39 | 29.39 | 1316 kbps | 1.45 | 29.39 | `none` || Focused after minimize | 29.39 | 29.39 | 1341 kbps | 1.46 | 29.39 | `none` |-At every boundary sample, the capture track was enabled, unmuted, and live at-1186x712; the local preview played at focused boundaries and was paused at-hidden and minimized boundaries. Outbound and inbound boundary samples were-also 1186x712, and every end sample reported `qualityLimitationReason=none`.-The probe kept one unchanged PC, sender, and track. Capture, encoded, and decoded-rates divided their monotonic counter deltas by the same outbound-RTP RTCStats-timestamp interval; bitrates used the corresponding byte deltas. Source and-inbound timestamps and raw stats identity were not independently retained, so-this is not an A/B/C interval-identity proof.--This is a screening result, not the product acceptance run. It has one short-same-machine loopback, no production Screener route, no separate physical-Viewer, no real game/render load, no audio, no CPU/GPU counter correlation, and-no repetition, randomized order, or hidden/minimized hold beyond five minutes.-It narrows the next test to the reported workload and environment; it does not-close the TODO or justify a Browser workaround.--## Minimal Reproduction--### Baseline--Use one desktop Host and one separate physical Viewer on a direct, wired path.-Do not include SFU, peer relay, multiple senders, Wi-Fi, or cellular behavior in-the first baseline. Use a supported stock Chrome/Edge build with a clean-profile and no background-throttling flags. Record browser and OS versions,-power source, Energy Saver state, display topology, and coarse CPU/GPU load.-Exact device, driver, and hardware identifiers remain local.--Use a deterministic, continuously changing game scene or built-in replay on a-real display surface. A JavaScript canvas animation is not suitable because-its own timer or animation-frame lifecycle would confound the capture result.-Keep the selected source foreground, visible, and changing throughout the-first matrix.--After Screener reproduces a stable baseline, the locally available NetEase UU-Remote client may be run against the same scene and network as a black-box-comparison for process CPU/GPU use, network traffic, latency, and visible-quality. User-observed low-latency behavior is a reason to measure it, not-evidence of its transport, codec, encoder, background policy, or applicability-to a browser Host; those properties remain unknown unless the comparison exposes-them directly.--Open `chrome://webrtc-internals` on Host and Viewer before sharing and keep its-overhead constant across every run. Leave audio-debug recording, event-log-recording, packet capture, and media recording disabled. The current Screener-connection-details view may be used as a latest-sample cross-check; it is not a-time series and has no diagnostic download. If a stable reproduction suggests-freezing or discard, inspect the Host tab from a pre-opened separate control-window in `chrome://discards` or `edge://discards` outside the timed measurement-window. That page may expose URLs and therefore remains local evidence.--### Host-State Matrix--Run these Host-page states while the captured source, Viewer, route, scene, and-quality setting remain unchanged:--| State | Host document | Browser window | Captured source |-| --- | --- | --- | --- |-| Focused | visible and focused | visible | visible and changing |-| Unfocused | visible, not focused | visible or occluded | visible and changing |-| Background tab | hidden | visible | visible and changing |-| Minimized | hidden | minimized | visible and changing on another display |--Use equal 60-second measurement windows, restore the focused baseline between-states, randomize state order, and repeat three fresh controlled runs. These-window and repeat counts define a small comparable sample; they are not product-timeouts, quality thresholds, or proof of statistical significance. Record the-actual initial negotiated codec and encoder; do not switch codec inside a-run.--For each exact overlapping window, correlate:--| Stage | Required evidence |+At every boundary sample the track was enabled, unmuted, and live. Capture,+outbound, and inbound resolution remained 1186x712. The local preview played at+focused boundaries and was paused at hidden/minimized boundaries, while outbound+and decoded progress stayed near 30 fps. Every end sample reported+`qualityLimitationReason = "none"`.++Rates used monotonic counter deltas over the same outbound-RTP RTCStats timestamp+interval. Source and inbound timestamps and raw stats identities were not+retained independently, so this was not a complete interval-aligned proof.++This screening did not reproduce an immediate background drop. It also did not+exercise a real game/load, a separate physical receiver, audio, CPU/GPU+correlation, repeated randomized order, or a hold beyond five minutes. It is a+negative screening result, not product acceptance and not evidence that all+machines, browsers, capture surfaces, or sustained background states behave the+same way.++## Reproducible Diagnostic Evidence++Use a continuously changing native game, replay, or equivalent real display+surface. A JavaScript canvas is unsuitable because its own timer and animation+lifecycle confound capture. Use a stock supported browser, a clean profile, no+background-policy-disabling flags, and a separate physical foreground receiver+on a stable baseline path. Keep the selected surface changing, and vary the+capturing document separately from the selected surface.++Every compared window needs one stable capture generation, sender, receiver,+track, SSRC/stats object identity, and negotiated codec. Form adjacent,+non-overlapping deltas from each object's own RTCStats timestamps, then compare+only overlapping capture/send/receive windows. An absent optional field remains+unknown. An identity change, counter reset, missing interval, or non-overlapping+window makes the comparison inconclusive.++| Stage | Required facts || --- | --- |-| A. Capture | track `enabled`/`muted`/`readyState`; `displaySurface`; `getSettings()` width, height, and requested-result frame rate; `RTCVideoSourceStats` frames and frame rate; Host visibility/focus and local preview `paused` state |-| B. Sender | outbound `framesEncoded`, frame rate, bytes, frame size, `totalEncodeTime` delta, `qualityLimitationReason`, target/available bitrate when present, actual codec/profile, encoder implementation, retransmission, loss, and RTT |-| C. Viewer | inbound bytes and frame rate, frames received/decoded/dropped, freeze count/duration deltas, loss, jitter, actual codec, and foreground render behavior |--Use RTCStats object identity, media generation, and timestamps to form adjacent,-non-overlapping deltas. A missing optional member, changed stats object, counter-reset, or non-overlapping interval remains unknown rather than zero. Record OS,-browser, game, and GPU/CPU observations over the same timestamps; do not infer a-media result from the Host UI refresh cadence.--### Follow-Up Only After Stable Reproduction--Change one variable per fresh run:--1. Compare entire-monitor and application-window capture, then vary the- captured source's own visible, occluded, and minimized state while the Host- page state stays fixed.-2. Compare local preview playing and paused while capture and sender identities- stay fixed.-3. When investigating the 2026-08-19 production report, compare exact release- `769de201f7cc` with the then-current exact `main` commit on the same machine,- browser, driver, game scene, and direct wired Viewer.-4. If the short state matrix does not reproduce a report that concerns sustained- background operation, run one fresh hold longer than Chrome's documented- five-minute hidden-policy window in only the reported hidden or minimized- state. Keep the source changing and compare the first and last minute with- focused baselines; do not multiply that hold across every state.--Do not run a full factorial matrix before the baseline reproduces. A follow-up-must have one stated hypothesis and one changed variable.--## Interpretation Gates--1. If Host preview or stats presentation slows while Viewer inbound and render- remain stable, classify it as local presentation or timer behavior; there is- no media defect to repair.-2. If JavaScript callback cadence slows while cumulative RTC counters divided by- RTCStats timestamp deltas remain stable, classify the observation as sampler- cadence, not capture or sender degradation.-3. If `RTCVideoSourceStats` frame progress falls, or the track becomes muted,- and outbound encoding follows it, localize the issue to the selected source,- operating system, or capture backend. A captured source that becomes- inaccessible is a platform lifecycle boundary, not evidence for Host-page- keepalive.-4. If source progress remains stable while outbound encoded progress falls and- encode work or `qualityLimitationReason=cpu` agrees, investigate encoder and- system load. `qualityLimitationReason` is corroborating evidence, not a sole- root-cause oracle.-5. If source progress remains stable while outbound rate falls with- `qualityLimitationReason=bandwidth`, target/available bitrate, loss, RTT, or- retransmission changes, investigate congestion control and the actual path.-6. If Host outbound remains stable while Viewer inbound or decode falls,- investigate transport or receiver behavior. If inbound/decode is stable but- only rendering changes, investigate Viewer presentation lifecycle.-7. If capture, outbound, inbound, and decoded progress remain stable but the- picture looks blurred, investigate actual codec/profile, bitrate,- quantization, and display scaling; do not classify it as background capture- throttling.-8. If required identities, overlapping windows, or optional metrics are- missing, the result is inconclusive. It does not authorize a workaround.+| A. Capture | Track `enabled`, `muted`, and `readyState`; `displaySurface`; actual `getSettings()` width, height, and frame rate; `RTCVideoSourceStats` frames and fps; capturing-document visibility/focus; selected-surface state; preview `paused` state |+| B. Sender | Outbound frames encoded, fps, bytes, frame size, encode-time delta, `qualityLimitationReason` and duration deltas, target/available bitrate when present, codec/profile, encoder category, retransmission, loss, and RTT |+| C. Receiver | Inbound bytes/fps, frames received/decoded/dropped, freeze count/duration deltas, loss, jitter, codec, and foreground render progress |+| D. System | Coarse Host/receiver CPU and GPU load, power source, browser energy/sleep setting, OS/browser versions, and selected-surface state |++Host state, selected-surface state, and system counters must share the same+relative timeline as A/B/C. Record the actual codec and encoder category rather+than inferring them from configuration. `qualityLimitationReason` is supporting+evidence, not a sole root-cause oracle.++### Interpretation++1. Preview or diagnostic UI cadence changes while source, outbound, inbound,+ decode, and render progress stay stable: presentation or sampler behavior,+ not a media-path defect.+2. JavaScript callbacks arrive late while rates calculated from RTCStats+ timestamps stay stable: sampler cadence, not capture degradation.+3. Source frame progress falls or the track mutes, and outbound encoding follows:+ selected surface, OS, or capture backend.+4. Source progress stays stable while encoded progress falls, with encode work or+ `qualityLimitationReason = "cpu"` agreeing: encoder or system pressure.+5. Source progress stays stable while outbound quality/progress falls with+ bandwidth limitation, target/available bitrate, loss, RTT, or retransmission+ changes: congestion or transport path.+6. Host outbound progress stays stable while receiver inbound or decode falls:+ transport or receiver. Decode stays stable while only displayed progress+ changes: receiver presentation lifecycle.+7. Capture, outbound, inbound, and decoded progress stay stable while visual+ detail falls: codec/profile, bitrate, quantization, adaptation, or display+ scaling rather than background capture throttling.+8. The required identity or temporal alignment is absent: inconclusive. Do not+ convert missing evidence to zero or infer a fix.++The first reproducible comparison should change only one lifecycle variable at a+time and restore a verified baseline between states. Window lengths, repetitions,+and state order are experiment design choices based on the reported onset and+browser policy under test; they are not product timeouts or quality thresholds.++## Mobile Boundary++Desktop Host capture evidence does not establish mobile Viewer background+playback or the survival of browser-owned work after OS suspension. Mobile+acceptance must separately observe:++- visible versus background document state;+- screen lock and unlock;+- OS suspension, page freezing, discard, or process reclamation;+- Wi-Fi/cellular transition and foreground recovery; and+- whether the exact pre-suspension media identity survived or was re-created.++A mobile browser cannot promise background execution beyond its browser/OS+lifecycle. Recovery must be judged from newly decoded and presented media after+foregrounding, not from delayed JavaScript timers or a desktop result.## Privacy And Evidence Handling-Raw `chrome://webrtc-internals` dumps stay on the controlled test machine and-must not be committed, uploaded, attached to a room, or sent through Screener.-They can include page URLs/origins, RTC configuration, candidate addresses,-network details, and other fingerprinting material. Do not enable packet,-audio-debug, event-log, or media recording for this experiment.--Only a manually reviewed derived table may become repository evidence. It must-replace room, user, session, connection, track, SSRC, and stats IDs with-run-local ordinals and omit URLs, origins, hostnames, IP addresses, candidate-addresses, device labels/IDs, exact hardware serials, and media content. The-allowed durable fields are test version/configuration, coarse environment,-surface category, document/source lifecycle state, route category, actual-codec/encoder category, bounded metric values, and relative timestamps.--No new diagnostic server upload, push, sampling timer, ring buffer,-persistence, raw stats/SDP/candidate collection, or general telemetry mechanism-is approved by this research. If the local tools cannot establish an A/B/C-overlap, document the exact missing field first; any new diagnostic consumer-requires its own bounded design and privacy review.--## Mechanisms Outside The Accepted Boundary--The diagnostic does not adopt:--- `requestAnimationFrame()`, chained timer, Worker, or synthetic activity loops;-- silent audio, `AudioContext` oscillators, hidden/looping media, Picture-in-- Picture tricks, focus stealing, or synthetic input;-- dummy `RTCDataChannel`, `RTCPeerConnection`, WebSocket, signaling ping, or- service-worker activity as a liveness proof;-- the Web Screen Wake Lock API as a capture-priority control;-- product launch flags that disable browser background policies;-- visibility-triggered codec switching, another Browser media codec, extra sender- generations, or automatic capture replacement;-- server-side media telemetry, raw diagnostic upload, periodic probes, routing- changes, quality-driven reparenting, or magic quality thresholds; or-- a Native/executable sender fallback for this browser diagnostic milestone.--The accepted response to a demonstrated standards/browser capability boundary-is a clear documented limitation. A workaround is considered only after the-same-machine A/B/C evidence identifies a controllable owner and a minimal-standard mechanism changes the remote result without creating another media-lifecycle.--## License Boundary+Raw `chrome://webrtc-internals` dumps stay on the controlled test machine. They+may contain URLs/origins, RTC configuration, candidate addresses, network data,+and fingerprinting material. Do not enable packet, audio-debug, event-log, or+media recording for this diagnostic.++Only a manually reviewed derived table may become durable evidence. Replace+room, user, session, connection, track, SSRC, and stats IDs with run-local+ordinals. Omit URLs, origins, hostnames, IP and candidate addresses, device+labels/IDs, hardware identifiers, and media content. Retain only versions and+configuration, coarse environment, lifecycle state, actual codec/encoder+category, bounded metrics, and relative timestamps.++## Primary Sources And License++Sources were checked on 2026-08-24.++- [W3C Screen Capture](https://www.w3.org/TR/screen-capture/) defines captured-+ surface lifecycle, temporary inaccessibility, constraints, downscaling, and+ frame decimation. It is a Working Draft, not a performance guarantee.+- [W3C Media Capture and Streams](https://www.w3.org/TR/mediacapture-streams/)+ defines tracks and their independent consumers.+- [W3C WebRTC Statistics](https://w3c.github.io/webrtc-stats/) distinguishes+ media-source, outbound RTP, inbound RTP, codec, and optional limitation facts;+ cumulative deltas and stats timestamps are the measurement basis.+- [WHATWG Page Visibility](https://html.spec.whatwg.org/multipage/interaction.html#page-visibility)+ defines document visibility, not media scheduling priority.+- Chromium's [capture accounting](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/content/browser/renderer_host/render_frame_host_impl.cc),+ [process-priority calculation](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/content/browser/child_process_launcher.cc),+ and [Performance Manager voter registration](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/performance_manager/performance_manager_lifetime.cc)+ show how active media capture influences current renderer priority policies.+- Chromium [`MediaStreamTrack` scheduling](https://chromium.googlesource.com/chromium/src/+/0b9090f669ed390bbc61eadcd59a05ca98c6a0bc/third_party/blink/renderer/modules/mediastream/media_stream_track_impl.cc)+ shows the live/muted-track scheduler opt-outs at a pinned revision.+- [Chrome timer throttling](https://developer.chrome.com/blog/timer-throttling-in-chrome-88)+ and [Chrome Energy Saver freezing](https://developer.chrome.com/blog/freezing-on-energy-saver)+ document hidden-timer behavior and active-media exclusions.+- Chromium [`DesktopCaptureDevice`](https://chromium.googlesource.com/chromium/src/+/master/content/browser/media/capture/desktop_capture_device.cc)+ shows browser-process capture scheduling, CPU budgeting, and supported+ damage-driven capture behavior.+- WebRTC's [Windows WGC minimized-window tests](https://webrtc.googlesource.com/src/+/master/modules/desktop_capture/win/wgc_capturer_win_unittest.cc)+ require temporary error on minimized selected windows and recovery on restore.+- Chromium's [WebRTC internals owner](https://chromium.googlesource.com/chromium/src/+/master/content/browser/webrtc/webrtc_internals.cc)+ shows the internal active-peer-connection application-suspension wake lock.+- [W3C Screen Wake Lock](https://www.w3.org/TR/screen-wake-lock/) bounds the Web+ API to visible-document screen wakefulness.+- [Chrome performance settings](https://support.google.com/chrome/answer/12929150)+ and [Edge performance features](https://support.microsoft.com/en-us/edge/learn-about-performance-features-in-microsoft-edge)+ document user-side energy and sleeping controls and media exclusions.This document summarizes public specifications and implementation evidence; it-copies no source code and adds no dependency. W3C material is covered by the-[W3C Document License](https://www.w3.org/copyright/document-license-2023/),-Chromium source files carry their BSD-style license, and Chrome for Developers-prose is CC BY 4.0 with samples under Apache 2.0. These sources are evidence-only; their implementation is not incorporated into Screener.+copies no source code and adds no dependency. W3C material uses the+[W3C Document License](https://www.w3.org/copyright/document-license-2023/).+Chromium and WebRTC source files carry BSD-style licenses. Chrome for Developers+prose is CC BY 4.0, with samples under Apache 2.0. These sources are evidence+only; their implementations are not incorporated into Screener.diff --git a/docs/research/browser-screen-audio-quality.md b/docs/research/browser-screen-audio-quality.mdindex 9e4cef21..3c59b474 100644--- a/docs/research/browser-screen-audio-quality.md+++ b/docs/research/browser-screen-audio-quality.md@@ -1,120 +1,58 @@-# Browser Screen-Audio Quality--- Research date: 2026-08-25-- Scope: Browser game/movie screen audio over P2P, relay, and LiveKit SFU-- Status: current Browser contract implemented and deployed; heterogeneous- devices and real-game A/V synchronization remain open--## Current Conclusion--Screener requests display audio by default on initial capture and source switch.-If the browser, selected source, operating system, or user returns no audio-track, video sharing continues with an explicit warning.--One screen-audio track uses `contentHint = "music"`. Capture requests ideal-stereo and disables echo cancellation, noise suppression, automatic gain, and-voice isolation where the browser supports those constraints. These are-preferences and readback fields, not portable fidelity guarantees.--The only user-facing audio-quality choices are sender ceilings of 96, 128, and-192 kbps, with 96 kbps as the default. They update live on current P2P,-Browser-relay, and SFU senders and apply to future senders. Actual RTP traffic-can remain below a ceiling because of content and congestion, and includes-transport behavior not represented by the selected number.--## Peer Contract--Direct and Browser-relay Viewer answers use one structured `sdp-transform`-operation on the single active Opus audio section. It idempotently requests-`stereo=1` and `maxaveragebitrate=192000`, preserving every unrelated codec,-format parameter, media section, and session attribute. Missing, ambiguous, or-malformed targets return the browser-generated answer unchanged.--The 192 kbps receive maximum permits every sender ceiling; it is not a current-target or minimum. Screener does not set `sprop-stereo`, rewrite FEC, force a-sample rate, or add broad string/regular-expression SDP mutation.--Each audio sender reads fresh parameters, applies the selected `maxBitrate`, and-reads the result back. A rejected update leaves the previous sender state and-media alive. Without a remote applied acknowledgement, the Host does not claim-room-wide atomic convergence.--## LiveKit Contract--The SFU publisher maps 96 and 128 kbps to pinned LiveKit music presets and uses-an explicit 192 kbps preset for the highest ceiling. Every SFU audio publication-uses:--- `forceStereo: true`;-- `dtx: false`; and-- `red: false`.--RTP RED sends redundant copies of prior audio data to improve recovery from-short packet-loss bursts. It also materially increases payload traffic; the-earlier 128 kbps selection produced about 256 kbps on the measured SFU path.-Screener disables RED so the selected audio ceiling remains a useful publisher-budget. This trades away RED-specific loss resilience. Opus in-band FEC and-other WebRTC recovery remain separately negotiated; disabling RED neither proves-nor disables them.--LiveKit reconnect reacquires the exact current publication and sender before-reapplying audio parameters. Unchanged publication/sender identity does not-reset stats or parameter state. Missing current ownership fails the SFU route-closed instead of mutating a stale sender.--## Relay And Presentation--A Browser relay keeps one persistent `MediaStream` and reconciles screen-audio-track addition, removal, and replacement into each current child sender. A-source switch does not create an independent audio clock or Web Audio graph.--Viewer playback uses the browser's native media controls on the one persistent-video element. Local volume, mute, play/pause, and fullscreen do not enter-signaling, sender configuration, room state, or another participant. Autoplay-rejection remains a typed presentation state until the browser receives a user-gesture.--Connection metrics select the exact current audio sender/receiver. When audio is-active, the UI reports actual interval traffic rather than a constant or-placeholder `1 kbps`. Track and sender replacement reset only the affected stats-identity, so stale asynchronous samples cannot overwrite the new route.--## Evidence Boundary--Chrome 151 production gates exercised direct Host children, a Browser-relay-child, and an SFU subscriber with generated screen audio. Under the preceding-64/128/256 kbps contract, video and decoded audio energy advanced at all three-ceilings and after source replacement. Direct and Browser-relay traffic tracked-the selected ceiling;-the then-enabled SFU RED path explained the approximately doubled SFU audio-payload.--The same evidence verified that the active-audio display no longer reports the-old constant `1 kbps`. It did not establish perceptual music quality, all-capture-source combinations, weak-network loss recovery after RED is disabled,-or real-game SFU A/V synchronization.--## Boundaries--- No microphone/voice processing policy is inferred from screen audio. A future- microphone is a separate source and track.-- No user control for codec, stereo, channel count, sample rate, DTX, RED, FEC,- or arbitrary bitrate.-- No Web Audio mixing, resampling, second representation, or independent audio- rate controller.-- `opus/48000/2`, capture channel count, and configured ceilings do not prove- encoded stereo or end-to-end fidelity.-- Browser/system capture scope may include calls or notifications; the page- cannot promise per-process isolation from generic system audio.--## Current Verification Gaps--- Chrome/Edge tab, window, and system-audio source combinations on supported- Windows versions.-- Real game/music subjective quality and A/V synchronization over direct,- relay, and SFU paths.-- Lossy Wi-Fi/cellular behavior with RED disabled, including concealment and- Opus FEC counters where exposed.+# Browser Screen-Audio Evidence++- Reviewed: 2026-08-27+- Scope: Browser display audio over direct, relay, and LiveKit paths+- Status: evidence; current controls are owned by+ [media quality](../product/media-quality.md)++## Findings++- `getDisplayMedia()` may return no audio track depending on Browser, operating+ system, selected surface, and user choice. Audio constraints are preferences,+ not a portable source or fidelity guarantee.+- Screen audio is distinct from microphone/voice processing. Echo cancellation,+ noise suppression, gain control, voice isolation, channel count, and content+ hint requests must be interpreted through actual capture and RTP evidence.+- One structured `sdp-transform` operation can request Opus stereo and a receive+ ceiling while preserving unrelated codecs, media sections, and attributes.+ Missing or ambiguous Opus targets should leave the Browser answer unchanged.+- Sender `maxBitrate` is a ceiling. Fresh parameter readback and interval RTP+ stats are required; content and congestion may produce lower traffic.+- Browser relay can keep screen audio in the same persistent `MediaStream` while+ source tracks are added, removed, or replaced. It does not need a Web Audio+ mix/resample graph or second clock.+- Viewer play, mute, volume, and autoplay recovery belong to the native media+ element and do not change sender or room state.++## RED Tradeoff++RTP RED carries redundant prior audio payload to improve short-loss recovery and+can materially increase traffic. Under an earlier 64/128/256 kbps experiment,+direct and Browser-relay payload tracked the selected sender ceiling, while the+then-enabled SFU RED path was approximately double its nominal audio payload.++That measurement justified treating RED and an audio ceiling as separate+decisions. Current values and LiveKit options are intentionally not mirrored+here; they are owned by the product module and code. Disabling RED does not prove+that Opus in-band FEC is enabled or disabled.++## Retained Functional Evidence++Chrome 151 controlled runs exercised a direct Host child, a Browser-relay child,+and one SFU subscriber with generated screen audio. Video, audio RTP, and decoded+audio energy advanced at all tested historical ceilings and after source+replacement. The active-audio display also stopped reporting the old constant+`1 kbps` placeholder.++These runs prove track/sender continuity and stats ownership. They do not prove+perceptual music quality, encoded stereo, all capture-source combinations,+weak-network behavior, real-game A/V synchronization, or mobile playback.++## Open Evidence++- Chrome/Edge tab, window, and system-audio combinations on supported Windows.+- Real game/music quality and A/V synchronization over direct, relay, and SFU.+- Lossy Wi-Fi/cellular concealment and Opus FEC behavior with current options.- macOS, Android, and iOS capture/playback behavior.## Primary Sources@@ -122,8 +60,8 @@ or real-game SFU A/V synchronization.- [Screen Capture](https://www.w3.org/TR/screen-capture/)- [Media Capture and Streams](https://www.w3.org/TR/mediacapture-streams/)- [WebRTC](https://www.w3.org/TR/webrtc/)-- [RFC 7587: Opus RTP payload](https://www.rfc-editor.org/rfc/rfc7587.html)-- [RFC 2198: RTP redundant audio](https://www.rfc-editor.org/rfc/rfc2198.html)-- [LiveKit audio RED and media options](https://docs.livekit.io/transport/media/advanced/)-- [LiveKit client 2.22.0 track options](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/track/options.ts)+- [Opus RTP, RFC 7587](https://www.rfc-editor.org/rfc/rfc7587.html)+- [RTP redundant audio, RFC 2198](https://www.rfc-editor.org/rfc/rfc2198.html)+- [LiveKit media options](https://docs.livekit.io/transport/media/advanced/)+- [LiveKit client options](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/track/options.ts)- [sdp-transform](https://github.com/clux/sdp-transform)diff --git a/docs/research/built-in-peer-ice-turn.md b/docs/research/built-in-peer-ice-turn.mddeleted file mode 100644index 8a866824..00000000--- a/docs/research/built-in-peer-ice-turn.md+++ /dev/null@@ -1,147 +0,0 @@-# Built-In Peer ICE TURN Candidate--- Research date: 2026-08-20; quota boundary rechecked 2026-08-21-- Scope: authenticated TURN on every ordinary peer `RTCPeerConnection` in an- exact-room canary-- Status: rejected after bounded production canary; historical evidence only--The remainder records the tested candidate and exact release behavior. Current-transport design is owned by [ADR-0005](../adr/0005-automatic-hybrid-media-routing.md).--## Decision--Do not deploy or continue either the participant-wide or selected-edge-application candidate. Ordinary peer connections remain STUN-only and the sole-application fallback is LiveKit SFU/UDP. Exact release `9461e20` used its dated-SFU-then-selected-TURN recovery slice; current route authority is ADR-0005.--This supersedes this document's former recommendation to place STUN plus TURN on-every capable exact-room Web peer connection. Git history retains that analysis;-the durable findings that still apply are summarized below.--The participant-wide and selected-edge implementation sections below are dated-evidence only. Their allocation, credential, authorization, rebuild, UI,-configuration, and deployment surfaces have no current product authority. An-isolated Host-SFU ingress canary proved historical selected TURN/UDP media, but-did not establish a unique product need beyond the accepted SFU fallback.--## Production Canary--The first exact-room canary used source `a11a73dfa79d`, immutable release-`a11a73dfa79d-r4`, and artifact SHA-256-`C954185869A3A15CCCE642AB72A4CF90770476C117D61182D7728280C30A036F`.-The candidate switch completed at 2026-08-20 14:59:33 +08. A local coturn REST-allocation passed without retaining or printing its credential, and the-application health, artifact, route, admission, SQLite, service, and local TURN-configuration gates passed.--The real direct Host plus Pion Viewer acceptance path did not establish its peer-connection. The stop line prevented the forced-relay test, so the run proved-neither direct-with-TURN behavior nor relayed media. It was fully rolled back.--Application issuance was disabled before coturn and its firewall rules returned-to the recorded pre-canary authenticated-relay baseline: TCP/UDP 3478 plus UDP-49152-49251. Exact production `7fea60ef6f2ad14a9ac1c23a89a523d91bbb97e4`-was restored and advertised no TURN credential. At the final lock-free check at-2026-08-20 15:12:40 +08, services were active, health/configuration/firewall/-SQLite matched baseline, and coturn reported zero allocations. The inactive-candidate release and `/opt/screener/backups/turn-a11-20260820T065933Z` remain-deployment evidence. Production later advanced independently to `31bee238`.--No candidate, credential, address, or raw signaling value is retained here.--## Why Built-In Issuance Was Rejected--RFC 8445 gives relay candidates a lower recommended type preference than host,-peer-reflexive, and server-reflexive candidates, so a healthy direct path is-normally preferred. That does not make participant-wide TURN free:--- gathering a relay candidate sends a TURN Allocate request and consumes an- allocation, relay port, memory, quota, and refresh traffic even when direct is- selected;-- coturn REST credentials authenticate an expiry-tagged bearer, not the room,- peer edge, route revision, parent, or connection generation;-- one participant credential can be reused by its holder until expiry;-- `setConfiguration()` affects future gathering and does not itself move an- existing connection, so refresh/recovery still needs lifecycle ownership; and-- placing TURN on every initial peer PC bypasses exact edge selection and spends- relay resources before the controller has observed a failed direct transport.--The candidate was smaller in code because it delegated selection to standard-ICE, but it widened credential scope and idle server cost. Its failed direct-acceptance supplied no compensating runtime evidence.--## Selected-Edge Boundary--The deployed selected-edge replacement was designed as one coherent-controller-owned change with a current consumer. ADR-0005 now owns path-selection and resource accounting; the transport boundary retained here is:--- a complete default-off deployment tuple with an independent secret, one- explicit TURN/UDP URI, bounded TTL, quota, bandwidth, and relay-port limits;-- issuance only after the exact logical edge's direct/STUN transport fails and- the controller selects TURN; SFU subscription is a separate ingress choice;-- one in-memory negotiating attempt bound to room/share generation, viewer and parent- sessions, route revision, the replaced connection, and a server-generated new- connection identity;-- one-use grants are bound to the logical edge, both endpoint sessions, route- revision, and connection generations; independent edges may have independent- grants under deployment-wide TURN admission. The exact release used one- `peer-selected` lease per room (excluding Host ingress), but that release- quota is historical rather than a current topology rule; negotiation remains- serialized only when route write sets conflict, while an answered exact lease- is active transport and may coexist with an unrelated migration under route- carry revalidation;-- coordinated parent and child rebuild for exactly that edge, using relay-only- ICE only on the new connection;-- revalidation at grant, rebuild, ready, failure, timeout, route change,- disconnect, and room stop/delete boundaries;-- one-use consumption and explicit terminal failure, with no refresh timer,- participant-wide credential, SQLite row, URL, log, browser persistence, raw- candidate, or second router; and-- Native and every ordinary Web peer connection remaining STUN-only.--Coturn still cannot enforce the application edge identity. The application-guards provide selected-edge authorization; short expiry and coturn quotas bound-bearer reuse and resource cost. Coturn's current `user-quota` and `total-quota`-bound allocations by credential user and server/realm, not by Screener room, so-they do not replace this application admission guard. Do not claim cryptographic-edge binding.--The source candidate uses the complete `SELECTED_EDGE_TURN_*` tuple only with-exact-room peer assistance and SFU configuration. `HostPeer`, relay parents, the-Viewer child, and `HybridMediaRouter` share one generation contract; a config-only-or issuer-only partial deployment remains forbidden.--## Retained Acceptance Boundary--Current acceptance must independently prove:--1. ordinary direct/peer PCs contain no TURN candidates;-2. one exact authorized parent/child edge can rebuild, select relay, and reach a- decoded/rendered frame after its direct transport fails;-3. Host-SFU publication ingress can independently select TURN when authorized,- without granting TURN to unrelated peer edges;-4. stale/replayed/wrong-session/wrong-revision/wrong-connection grants fail;-5. success stops further escalation, while expiry, coturn failure, disconnect,- and all-UDP-blocked cases terminate within the bounded window;-6. one and two selected relay edges stay within measured allocation, port, RSS,- CPU, RX/TX, loss, latency, and 1-GiB host limits; and-7. Android Chrome and iOS Safari complete the representative home, hotspot, and- carrier matrix before broader rollout.--The media ladder remains UDP-only. HTTPS/WSS remains TLS/TCP and does not-satisfy these media gates.--## Sources--Primary sources accessed 2026-08-20:--- [ICE, RFC 8445](https://www.rfc-editor.org/rfc/rfc8445.html)-- [TURN, RFC 8656](https://www.rfc-editor.org/rfc/rfc8656.html)-- [WebRTC configuration and ICE restart](https://www.w3.org/TR/webrtc/)-- [Coturn turnserver documentation](https://github.com/coturn/coturn/blob/master/README.turnserver)-- [Coturn TURN REST API implementation](https://github.com/coturn/coturn/wiki/turnserver)-- [TURN REST API draft](https://datatracker.ietf.org/doc/html/draft-uberti-behave-turn-rest-00)--No source code was copied.diff --git a/docs/research/display-name-presence.md b/docs/research/display-name-presence.mddeleted file mode 100644index 37e8667e..00000000--- a/docs/research/display-name-presence.md+++ /dev/null@@ -1,19 +0,0 @@-# Display name and presence boundaries--Accessed 2026-08-20. This note records only the browser and Unicode facts that constrain the local-name slice.--## Primary sources--- [WHATWG HTML: Web storage](https://html.spec.whatwg.org/multipage/webstorage.html#the-localstorage-attribute) defines `localStorage` as origin-scoped client storage. Access and writes may fail, so a display-name preference must remain optional and fall back without blocking room access.-- [ECMAScript: `String.prototype.normalize`](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.normalize) provides explicit Unicode normalization. Screener uses NFC before applying its code-point limit and before sending the value.-- [Unicode UAX #31](https://www.unicode.org/reports/tr31/) documents normalization and the security concerns around invisible/default-ignorable and bidirectional controls. Display names are not identifiers, but rejecting controls and bidi overrides avoids misleading roster text while allowing ordinary multilingual labels and emoji.--## Retained design--The browser is the only durable owner of a display-name preference. The signaling server retains the canonical value only on the authenticated socket state and derives an authoritative online snapshot from current connected sessions. Presence is display-only: it neither authorizes nor changes media routing. For Web display, an SFU Viewer entry carries `sfuMediaReady: true` only after first media is bound to its current session, active route revision, and publication generation; absence stays neutral, while track, route, or session loss removes the proof. Browser Hosts and Viewers explicitly opt in to the shared participant snapshot; executable senders are outside the current Browser contract. Host defaults may be derived from the room-scoped stable client ID, but the value is still local/socket-only.--## Current roster presentation--The live roster uses the display name alone when it is unique in the current room snapshot. When two or more participants use the same name, only those colliding entries append the shortest room-scoped `peerId` suffix that distinguishes them, starting at six characters and extending only for a suffix collision. A suffix collision between different names does not change either label. This is presentation-only; the suffix remains opaque and never participates in authorization, routing, or quality decisions.--Host and Viewer pages consume the same authoritative participant snapshot. The Viewer roster renders only Viewer entries, including the local Viewer, and replaces the whole list on each snapshot so joins, leaves, renames, and reconnections do not require a second client-side membership model.diff --git a/docs/research/low-server-media-routes.md b/docs/research/low-server-media-routes.mdindex f7861d59..a30c693e 100644--- a/docs/research/low-server-media-routes.md+++ b/docs/research/low-server-media-routes.md@@ -1,770 +1,260 @@# Low-Server-Cost Media Routes-- Research date: 2026-08-22; transport conclusion updated 2026-08-24-- Scope: one broadcaster, explicit admission up to twenty trusted viewers,- low latency, and bounded host media fanout-- Status: research and dated route evidence. Current invariants and assisted- transport roles are in [ADR-0005](../adr/0005-automatic-hybrid-media-routing.md).- Current source and production are indexed by [status](../status.md);- real-network validation remains in [verification status](../verification-status.md).--## Current Transport Conclusion--Screener's application route ladder is only direct/STUN peer followed by the-dedicated LiveKit SFU over UDP. One Host publication can serve multiple exact-Viewer subscriptions, so this remains a bounded central fallback rather than an-always-SFU topology. When all outbound UDP is blocked, both accepted paths end-in a clear bounded failure. Screener configures no TURN, ICE/TCP, media TCP, or-TLS-relayed media path.--Browser SFU publisher and subscriber PCs use no external ICE server, retain-LiveKit-signaled UDP candidates, and let standard ICE nominate a non-relay pair.-Candidate type, address family, count, and Browser socket allocation remain-observations rather than product invariants. Ordinary peer PCs remain STUN-only,-and the LiveKit server may still use deployment STUN to discover its own public-address. This is one application SFU route, not a new route class or a TURN-substitute.--WebRTC and LiveKit expose broader framework transport capabilities, but those-capabilities do not authorize another Screener route. Any future strict-firewall-coverage requires real target-network evidence and a new accepted decision, and-must remain inside LiveKit rather than become a third application route class.-The pinned LiveKit 1.13.5 configuration exposes `rtc.tcp_port`, external TURN,-and embedded TURN/TLS; none is enabled by the current product contract.--Primary sources checked 2026-08-24: [ICE, RFC-8445](https://www.rfc-editor.org/rfc/rfc8445.html), [NAT traversal and port-prediction, RFC 5128](https://www.rfc-editor.org/rfc/rfc5128.html#section-5.2),-[Experimental NAT behavior discovery, RFC-5780](https://www.rfc-editor.org/rfc/rfc5780.html), [WebRTC transports, RFC-8835](https://www.rfc-editor.org/rfc/rfc8835.html), [LiveKit connection-reliability](https://docs.livekit.io/intro/basics/connect/), [LiveKit self-hosted-deployment](https://docs.livekit.io/transport/self-hosting/deployment/), and the-[pinned LiveKit 1.13.5 configuration-sample](https://github.com/livekit/livekit/blob/v1.13.5/config-sample.yaml).--## Browser SFU ICE-Server Isolation--On 2026-08-24, exact repository dependency set `c7ec061`, Chrome 151 on Windows-11, pinned LiveKit Server 1.13.5, and pinned JS client 2.22.0 reproduced-intermittent initial LiveKit ICE failure while a Mihomo system-stack TUN owned-the public default route. The default arm and empty-ICE-server arm each used a-fresh Browser profile, then ran eight sequential attempts with a fresh page and-exact room per attempt under the same 12-second connection timeout and the same-640x360 at 30 fps canvas, VP8, single-layer publication. The default arm ran-first and the override was injected only through `Room.connect` as-`rtcConfig: { iceServers: [] }`. The temporary diagnostic harness was deleted;-this transcribed summary is bounded root-cause evidence, not a reproducible-regression artifact. No raw candidate, address, local port, token, or persistent-probe report was retained.--LiveKit supplied the deployment STUN endpoint and its public UDP candidate set-to the client. In this bounded environment Chrome used one local UDP socket for-the external STUN and SFU destinations, while Mihomo's documented-endpoint-independent NAT option was not enabled. Browser socket allocation is-an observation from this reproduction, not an application contract.--Eight isolated Host connections using that default configuration produced two-successful publications and six initial-ICE failures. A failed sampled attempt-showed 182 Browser connectivity requests with zero received responses; a-server-side pre-conntrack input counter observed 188 UDP packets and its output-counter observed 384 packets sourced by the SFU listener. The counters prove-server input and generated output-path traffic, not delivery beyond the host's-output hook. Together with the TUN association correlation and the controlled-A/B below, the best-supported cause for this reproduction is an-external-STUN/SFU association conflict after server output and before Browser-ICE receipt. The evidence does not generalize that cause to every TUN or VPN.--Pinned LiveKit Server adds configured STUN to each join response and falls back-to public default STUN when none is configured. Pinned JS client only adopts-those servers when its caller did not provide `rtcConfig.iceServers`. An-explicit empty array therefore keeps the remotely signaled SFU candidate while-preventing additional local STUN gathering; it does not disable ICE.-With `rtcConfig: { iceServers: [] }`, eight of eight isolated Host attempts-formed a nominated non-relay UDP pair; this environment observed-peer-reflexive-to-host candidate types. The first connected sample appeared-within 0.5 to 1.7 seconds and publication completed 75 to 89 ms later. The same-configuration belongs on Browser publisher and subscriber connects; ordinary-peer STUN remains unchanged. Candidate type and count are diagnostic only.-Product acceptance still requires an exact deployed Host-publication and-Viewer-first-frame canary under the reproducing TUN path plus a separate mobile-network.--Primary sources checked 2026-08-24: [Mihomo TUN configuration and-endpoint-independent NAT](https://wiki.metacubex.one/config/inbound/tun/),-[LiveKit Server 1.13.5 ICE-server response construction](https://github.com/livekit/livekit/blob/v1.13.5/pkg/service/roommanager.go),-[LiveKit JS client 2.22.0 connect-option assignment](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/Room.ts),-[LiveKit JS client 2.22.0 RTC configuration merging](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/RTCEngine.ts),-and [pinned LiveKit media-transport external-IP discovery](https://github.com/livekit/mediatransportutil/blob/a3417d38cda0/pkg/rtcconfig/ip.go).--## Historical Candidate Route Ladder--At this dated checkpoint, the candidate plan used direct Host P2P first, then a-bounded browser relay DAG. Browser relays decoded and re-encoded each stream,-while separate native shared-encode and encoded-RTP relay ideas remained-research candidates. A single-node SFU was tested as optional capacity after-peer recovery; its source checkpoint used one or two roots. These measurements-do not define the current topology, fallback order, or capacity policy.--At that checkpoint, any browser-spike failure other than isolated relay-re-encoding closed that browser-relay candidate. Native sender work remained a-separate research track. Closed-PR #12's explicit whole-room SFU mode is superseded. ADR-0005 and merged PR #17-own the automatic cross-mode controller. Production first enabled it only for-room `1` and later removed that rollout boundary. That first room-`1` release-observed participant entry but did not retain media. On 2026-08-21, a latest-source run-forced the first direct edge to fail and then passed one local SFU/UDP root with-Chrome 151, LiveKit 1.13.5, and pinned client 2.22.0. LiveKit produced two sender-RIDs in `q,h` order; Screener's former `q,f` guard caused the Host publisher to-fail closed at `sender-config`. After correcting that contract, Viewer inbound-packets and decoded/rendered frames increased, endpoint edges stayed bounded,-and both clients left cleanly. TURN did not participate in that first run. A-later exact-source canary against the then-production media tuple proved the-historical Host-ingress selected relay described below. A historical v8-production canary subsequently committed two SFU assignments and decoded-1920x1080 video. These are functional, not performance, evidence; heterogeneous-networks, mobile, resources, and endurance remain open.--## Token-Free SFU Standby Prewarm--The pinned Apache-2.0 `livekit-client` 2.22.0 source documents and implements-`Room.prepareConnection(url)` as DNS/TLS preparation. For a self-hosted URL and-no token, it converts `ws(s)` to `http(s)`, sends one `HEAD`, and catches errors.-It does not call `connect`; therefore it does not join a room, acquire a-participant identity, publish, subscribe, or create a media edge. A token is-only relevant to LiveKit Cloud region selection, which this self-hosted spike-does not use.--The smallest integration is to advertise the non-secret LiveKit origin only in-the authoritative peer-assisted authentication snapshot when the complete-fallback tuple exists. Each client dynamically imports the already-pinned SDK-once and attempts the URL once. Newer authentication invalidates a stale task-before the import completes; a failed HEAD is silent and is not retried. No JWT-is issued until the existing route controller actually selects SFU fallback.-With no fallback configuration, the field, import, HEAD, and behavior are all-absent.--A bounded Chrome 151/LiveKit 1.13.5 localhost/headless/video-only same-leaf A/B-reduced failure report to SFU active from 1.481 seconds to 200 ms and to a-rendered frame from 2.257 seconds to 319.7 ms. It retained the fixed direct ->-peer -> SFU order, two allowlisted roots, and host media-edge peak two. The-standby had already downloaded/parsed the SDK and made its token-free network-prewarm, without a participant or media edge, so the A/B does not isolate those-effects. Its roughly 86% result must not be extrapolated to a public network;-internet DNS/TLS reuse, RTT/loss, audio, transport fallback, and browser variance-still require measurement.--At that source checkpoint, the 2026-08-22 in-process-`gate:sfu-root-invariants` proved its fixed-root and Host-publication accounting,-token allowlist, zero-child reauthentication, and subscriber-retention behavior.-It used no LiveKit process, browser RTC stats, or packet counters, so it did not-measure `B_pub`, root egress, forwarding, or congestion behavior and does not-select the current resource model.--## Traffic Conservation And The Impossible Triangle--This is an engineering accounting identity, not a named theorem. Let `B` be-the measured useful media bitrate for one same-representation edge, `B_pub` the-actual SFU publication bitrate, `N` the Viewer count, `P` the number of Viewer-upstreams carried by peer edges, and `S` the number carried by SFU subscriptions.-Thus `N = P + S`. Split peer edges by sender: `H` are Host-to-Viewer and `V` are-Viewer-to-Viewer, so `P = H + V`. 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`--| Full-stream shape | Host upload | Viewer-relay upload | Central media traffic |+- Research date: 2026-08-22; last evidence review: 2026-08-24+- Scope: traffic conservation, SFU cost and ICE isolation, browser NAT limits,+ TURN screening, and bounded SFU admission for one Host and up to twenty authenticated Viewers+- Status: supporting evidence. Current truth is owned by+ [ADR-0005](../adr/0005-automatic-hybrid-media-routing.md), [status](../status.md),+ and [verification status](../verification-status.md).++## Research Conclusion++No topology removes the last-hop media copy delivered to each Viewer. Peer+distribution moves those copies to endpoints; an SFU moves them to a server.+Encoding once may reduce encode work, but it does not repeal network traffic+conservation.++TURN and an SFU solve different problems. TURN relays one ICE transport leg;+an SFU authenticates one publication and emits separately authorized+subscriptions. A relay candidate therefore says nothing about room topology or+whether central distribution is cheaper.++For ordinary browsers, ICE connectivity checks are the reachability authority.+NAT labels, STUN observations, TCP reachability, and guessed ports cannot prove+a usable peer UDP pair. A public SFU may remain reachable over outbound UDP+when peer UDP is not; if all outbound UDP is blocked, a UDP-only media design+must fail clearly unless a separately accepted framework transport exists.++## Traffic Conservation++This is an accounting identity, not a named theorem. Let:++- `N` be the Viewer count;+- `P` be Viewers whose current upstream is a peer edge;+- `S` be Viewers whose current upstream is an SFU subscription, so `N=P+S`;+- `H` be Host-to-Viewer peer edges and `V` Viewer-to-Viewer peer edges, so+ `P=H+V`;+- `B_e` be the measured useful bitrate of peer edge `e`;+- `B_pub` be the total Host-to-SFU publication bitrate across all active+ representations; and+- `B_s` be the selected bitrate of SFU subscription `s`.++Ignoring protocol overhead:++```text+Host upload = sum(B_e for Host peer edges) + (B_pub when published)+Viewer upload = sum(B_e for Viewer relay edges)+SFU media ingress = B_pub+SFU media egress = sum(B_s for subscriptions)+```++For equal-representation bitrate `B`:++| Shape | Host upload | Viewer upload | Central media traffic || --- | ---: | ---: | ---: |-| Peer-only, `S=0` | `H*B` | `V*B` | none |-| Mixed peer/SFU, `S>0` | `H*B + B_pub` | `V*B` | SFU ingress `B_pub` + egress `sum(B_s)` |-| Same-representation full-room SFU, `S=N` | `B` | `0` | SFU ingress `B` + egress `N*B` |--For mixed representations, replace `H*B` and `V*B` with the sums of their-actual peer-edge bitrates, and use each SFU subscription's selected `B_s`. SFU-host upload and ingress are `B_pub`, the sum of all actively published-representations; if simulcast `HIGH` and `LOW` both remain active, that may be-`B_HIGH+B_LOW`. Publisher-to-SFU and every SFU subscription are independent ICE-connections. Whether a subscribed endpoint also sends peer edges is represented-only by its actual committed children and those edges are already counted in-`V`. Ordinary peer edges are STUN-only. In a historical or external deployment-where a publisher leg separately uses TURN, retain host upload-`B_pub`, TURN ingress `B_pub`, TURN egress `B_pub`, and SFU ingress `B_pub` as-distinct interface/service traffic. Any separately TURN-relayed LiveKit-subscription or historical selected-edge peer leg adds TURN ingress and egress equal-to that leg's measured bitrate. These are one logical useful payload copy but-real physical hops, so NIC, service, and billing counters must never be folded.-SFU-subscriptions are never hidden inside endpoint child capacity. Their ingress-and egress are admitted explicitly; `S` is a measured route-result, not a fixed root limit.--RTP/RTCP/SRTP, DTLS, ICE and IP headers, retransmission, FEC, and redundant-paths only add traffic. W3C candidate-pair byte counters exclude some transport-overhead, and a provider may bill ingress and egress differently, so formulas-screen candidates but never replace host NIC, SFU, and billing counters-from the same run. Encoding once can reduce compute and memory bandwidth, but-it cannot remove the network copy delivered to each viewer.--## Transport And Topology Layers--TURN is an ICE transport and an SFU is a media service; neither fact alone-defines logical parentage or resource admission. Ordinary peer PCs gather only-STUN candidates. The current model binds each SFU subscription to route-authority while preserving sticky unaffected subtrees, the configured ordinary-endpoint cap, and bounded failure.--This distinction follows TURN's allocation/relay role in RFC 8656 and the media-topology boundary in RFC 7667. A relay candidate proves transport for one edge;-it is not evidence that an SFU topology would be cheaper or faster.--## Hard NAT And UDP-Blocked Boundary--"Symmetric NAT" is legacy shorthand. The actionable properties are endpoint--independent versus endpoint-dependent mapping and filtering, whether outbound-UDP reaches a public server, and whether a public IPv6 path exists. CGNAT names-an operator topology, not one mapping behavior: RFC 6888 inherits the UDP NAT-behavior requirements and recommends endpoint-independent filtering. Cellular-networks can add translation layers, short-lived state, strict filtering, and-network changes, but their selected ICE path must be measured.--| Network condition | Honest WebRTC boundary | Screener consequence |-| --- | --- | --- |-| Endpoint-independent mapping with UDP | Full ICE can check host, server-reflexive, and peer-reflexive paths | Keep direct/peer UDP first |-| One endpoint-dependent mapper | Coordinated checks can sometimes create a peer-reflexive path; success is not guaranteed | Exhaust the existing bounded restart/rebuild/alternate-parent steps |-| Both peer endpoints use endpoint-dependent mapping | A direct peer path is not reliable; RFC 8835 requires browser TURN capability for general WebRTC interoperability | Use the public SFU/UDP fallback when outbound UDP reaches it; otherwise fail clearly |-| All outbound UDP is blocked | The UDP media ladder has no reachable candidate | End with a clear bounded failure |-| Wi-Fi/cellular or address change | Old mappings and candidate pairs can become invalid | Use a new opaque generation and bounded ICE restart/rebuild, then re-run the same priority ladder |--Peer-reflexive discovery records an address only after a connectivity check-succeeds; it does not cross two incompatible mappings by itself. A restricted-endpoint may still reach SFU infrastructure over outbound UDP. The route model-must decide publication ownership, subscription placement, and resource-admission without changing this NAT boundary.--Do not infer endpoint-dependent mapping from a `cellular` or `CGNAT` label. A-2023 experiment reached three of four Dutch mobile carriers, but that cohort is-too small and unlike Screener's target networks. A 2026 native DCUtR study found-that 97.6% of its successful traversals completed on the first attempt; its-roughly 70% result is conditional on relay reservation and address discovery,-which had already failed for about 29% of collected attempts. ProbeLab also says-that its reported 39.7% "symmetric" success may include classification error or-a network change. These studies justify measurement and bounded retry, not a-browser success-rate claim or repeated-refresh roulette.--One field observation retained a working P2P route after a Wi-Fi-to-cellular-switch and still retained P2P when the user requested reconnect. That single-session cannot distinguish endpoint-independent cellular mapping, public IPv6,-an ICE-selected replacement pair, or operator mapping/filtering lifetime. It-supports one fresh, generation-bound P2P opportunity after a discrete network-change or explicit reconnect; it does not support periodic probing, a carrier-"kept channel" assumption, or a universal hard-NAT traversal claim.--### Real-Network Measurement Inputs--These are isolated measurement inputs for the accepted real-network ledger, not-authority to change production DNS, firewall, STUN count, or route behavior.--**1. Dual-stack Web, STUN, and SFU**--- Measurement setup: on an operator-owned isolated deployment, publish working- `AAAA` records, bind every public endpoint on IPv6, and open the same bounded- UDP paths. Browser ICE already gathers and- intermixes IPv4/IPv6 candidates; do not add application candidate ordering.- Product code can remain unchanged; any retained evidence is only a sanitized- selected-address-family enum tied to the existing opaque generation.-- Dependency: routed IPv6 at the provider, dual-stack STUN/SFU listeners,- correct firewall rules, and no IPv4-only hostname hidden in the media ladder.-- Acceptance: owned desktop, Wi-Fi, and cellular probes select an IPv6 P2P path- and an IPv6 SFU path where available; broken IPv6 still reaches- the IPv4 ladder within the current route deadline. Retain only an `ipv4|ipv6`- enum with the exact candidate first-frame transaction, never a raw address.-- Stop line: if any required public media endpoint has no routed IPv6, record the- deployment as incomplete and keep the IPv4 ladder. Do not build a custom IPv6- selector or claim NAT bypass from an `AAAA` record alone.--**2. Exactly two independent-destination STUN servers**--- Measurement setup: use an isolated `STUN_URLS` list with two independent- destinations. Current server code already accepts the list and sends both- URLs in one ICE server entry. Existing schema capacity for eight URLs is not a- product recommendation or production change.-- Dependency: each URL must resolve to a different public destination IP;- separate failure domains and dual-stack coverage are preferable. Current- libwebrtc tests show that equal observed mappings are deduplicated while two- different observed mappings from two STUN destinations can yield two `srflx`- candidates from the shared UDP port.-- Acceptance: each server alone gathers a usable `srflx` candidate on the exact- Chrome, Firefox, and Safari releases recorded in the matrix, the pair does not- regress time to first decoded frame, and gathering still succeeds with either- server unavailable. Confirm server identity only in locally retained browser- diagnostics; do not add URL or address retention to production telemetry.-- Stop line: two STUN destinations improve address-family/failure diversity and- can expose mapping differences in an owned canary; they do not reveal the- mapping that a peer destination will receive and do not solve two endpoint-- dependent mappers. Do not add a third server or a NAT classifier; neither is- part of the accepted Browser route model.--### Ordinary-Browser ICE Boundary--Browser ICE connectivity checks are the only accepted direct UDP reachability-authority. RFC 8445 already tests authenticated candidate pairs and produces an-actually usable nominated pair; a TCP connection, a claimed NAT label, or two-STUN observations cannot predict whether that UDP media pair is reachable.-RFC 5128 also limits port prediction to favorable mapping behavior and notes-that randomized or multi-level mappings defeat it. RFC 5780 is Experimental,-observes behavior only toward its STUN destinations, and explicitly does not-replace ICE.--Screener therefore does not synthesize remote candidates, guess adjacent ports,-classify NAT behavior, or probe TCP reachability. Direct ICE exhaustion advances-to SFU/UDP within the existing total operation deadline; when all UDP is blocked,-both accepted paths end in a clear bounded failure. This preserves one candidate-model and avoids adding mappings, ICE/DTLS work, abuse surface, or magic guess-budgets that ordinary browser APIs cannot make reliable.--### Ordinary-Browser Hard Boundaries--- Birthday-paradox traversal, broad multi-socket probing, source-port binding,- PCP/NAT-PMP/UPnP, and TCP simultaneous-open require socket or gateway control- that an ordinary page does not have. Many `RTCPeerConnection` objects are not- an acceptable substitute: the page still cannot bind ports and would create- unbounded ICE, DTLS, memory, and abuse risk.-- Peer-reflexive candidates remain useful, but browser ICE creates them only- after a connectivity check succeeds. RFC 8863's recommended 39.5-second PAC- timer is an ICE-agent failure boundary, not a JavaScript tuning API. Do not- extend Screener's current route deadline to 40 seconds; measure late recovery- behind a playing SFU route through an isolated measurement instead.-- The April 2026 ICE-renomination draft requires opt-in from both ICE agents and- the W3C `RTCConfiguration` exposes no renomination switch. Historical- libwebrtc native code has a disabled-by-default flag for an older renomination- proposal; it is neither this draft nor a browser API. Renomination can choose- among retained pairs inside one ICE session; it cannot turn an SFU connection- into a peer topology.-- Current QUIC traversal work also assumes an existing relay and candidate- discovery from the same application-controlled UDP socket. Browser- WebTransport is a client connection to a server, not a raw UDP socket or an- inbound peer listener. Native TCP/QUIC DCUtR results therefore do not reopen- Screener's accepted browser media transport boundary.-- `iceCandidatePoolSize` only pre-gathers implementation-managed candidates for- future ICE use. It does not expose ports, create birthday probes, or repair an- endpoint-dependent mapping. Repeated refreshes and a large STUN list likewise- add delay and mappings without a stable traversal mechanism.--The shared acceptance matrix remains EIM/EIM, one endpoint-dependent mapper,-two endpoint-dependent mappers including cellular-to-cellular, all UDP blocked,-and a Wi-Fi-to-cellular change. It measures ordinary ICE/STUN, SFU/UDP, and clear-failure without injecting candidates. Record only sanitized route kind, address-family, generation, queue/candidate/first-frame timing, loss, RTT, bitrate, and-SFU bytes. Keep credentials short-lived and generation-scoped and retain-ingress/egress caps.--## Privacy-Safe Route Diagnostic Boundary--Start with locally retained, redacted `webrtc-internals` as manual ground truth.-Production deploys the user-initiated local stats export and route-timing-snapshot. It may observe only existing-join, route-demand, operation-start, candidate-start, first-decoded-frame,-settle, share-stop, departure, and room-delete events. It keeps one latest-timing/outcome record per current child; a new demand overwrites that record,-and authoritative share stop/replacement, confirmed departure, or room deletion-removes it. It creates no timer, event ring, backend telemetry stream, or route-input.--Only an authenticated Host's explicit local-export action may request one-current snapshot. The response projects the current graph, current operation,-and latest records through snapshot-local ordinals that are not participant-identities. It includes relative queue/candidate/first-frame timing, operation-reason/stage/cursor, and final route `direct | sfu | waiting | failed`. A current-candidate may expose only the closed rejection bucket `none`, `stale`,-`endpoint-capacity`, `sfu-admission`, `candidate-failed`,-`first-frame-timeout`, `operation-deadline`, or `aborted`. Queue wait is measured-from route demand to operation start. Missing timing remains `null`; no consumer-reconstructs past events from the current graph.--Never retain or emit raw `errorText`, address, port, URL, candidate strings,-SDP, credentials, display name, or real peer/parent/session/connection/generation-identity. The server does not log, persist, or periodically push the snapshot,-and Viewers cannot request it. Current-path ICE/RTP stats remain local to the-page that owns the connection and have no route authority.--### Local Diagnostic Export Boundary--The local report is a projection of current sanitized metrics, not a serialized-stats object or signaling snapshot. It uses a fixed field allowlist and writes-unavailable values as `null`; selected addresses/ports, internal IDs, participant-identity, raw SDP/candidates, media-service URLs, and credentials never enter the-report input. The file is created only after a user click with a local JSON-`Blob`, is not uploaded or persisted, and its object URL is explicitly revoked.-The [W3C File API](https://www.w3.org/TR/FileAPI/) (accessed 2026-08-22) defines-Blob URLs for locally generated downloads and requires explicit revocation to-release their backing store.--## Historical SFU/UDP And Selected-Edge TURN Slice--Every ordinary bounded peer `RTCPeerConnection` used STUN-only ICE. The tested-source attempted bounded peer recovery, then its fixed-root SFU/UDP slice, then-one controller-selected authenticated TURN/UDP rebuild before failure. That-ordering and accounting are historical implementation evidence, not current-route authority.--The historical candidate relied on RFC 8656 TURN allocation carrying media-rather than acting as a handshake helper or topology. It kept ordinary PCs-STUN-only and used exact-room, complete-tuple, generation, and one-use gates to-contain its isolated rollout. Those gates describe the measured candidate only;-they do not authorize a current transport.--At that checkpoint, coturn validated bearer HMAC and expiry but not Screener's-room, edge, revision, parent, or connection identity. The application therefore-bound issuance and both endpoint rebuilds to the candidate's exact identity and-consumed the attempt on success, failure, expiry, or generation change. The-failed built-in alternative and retained standards evidence are in-[Built-In Peer ICE TURN Candidate](./built-in-peer-ice-turn.md).--Pinned LiveKit 1.13.5 and client 2.22.0 exposed TURN and per-connect `rtcConfig`-capabilities used to explain the historical Host-ingress experiment. That-separate ICE domain and its coturn credential were never authority for ordinary-peer PCs and are not part of the current product route.--Ordinary peer ICE remains STUN-only. Both the participant-wide and selected-edge-TURN candidates are rejected product paths; their canary evidence remains below-only to explain the measured tradeoff. Every ordinary Web peer remains STUN-only. The tracked coturn example is UDP-`stun-only`; the LiveKit example exposes only ICE/UDP mux 7882, explicitly sets-`tcp_port: 0` and `allow_tcp_fallback: false`, supplies the self-hosted STUN-endpoint, and configures no external or embedded TURN. Candidate validation and rollback use isolated-instances rather than a process-wide old-release compatibility branch. HTTPS/WSS remains TLS/TCP.--### Historical Host-Ingress Functional Evidence--On 2026-08-21 the tracked standalone gate reused the then-production selected-edge-tuple parser and credential issuer, supplied the short-lived credential only to-an isolated loopback Chrome page, and returned a sanitized result: one UDP relay-candidate and an otherwise non-blocking `701` error bucket. No URL, username,-credential, candidate address, or raw error text was emitted or persisted.--The canonical Chrome 151 product canary then used exact deployed Web source-`16f6eab27bdfb1c15cdbd814a35864f4f18be767` in a local Screener room while-connecting to the then-production LiveKit 1.13.5 and coturn tuple. After direct media-and active SFU media, a temporary DEV-only hook failed the refreshed publisher-once; the normal application failure path requested `host-sfu-ingress` and the-hook was removed after the run. The relay-policy publisher had only a TURN-server, reached connected/ICE-connected, and selected a succeeded/nominated UDP-pair with `relayProtocol=udp`. Pair counters reached 1,054,606 bytes sent and-4,934 received; outbound RTP reached 837,103 bytes and 101 frames. Viewer decode-and render counters both advanced during the selected stage. Ordinary peer PCs-kept policy `all` with STUN-only servers, Host active outbound edges stayed at-one, and explicit stop reduced them to zero. The production Screener app and-database were not used or modified.--Chrome reported the selected local candidate's `candidateType` as `prflx` while-also reporting `relayProtocol=udp`. That tuple is internally inconsistent with-the W3C model: `iceTransportPolicy="relay"` permits only media-relay candidates,-and `relayProtocol` is defined for a local relay candidate. The evidence is-therefore retained verbatim and classified from the relay-only configuration,-TURN-only server set, `relayProtocol`, and transmitted media together; the-`candidateType` field is not rewritten. This proves one active functional route,-not latency, quality, capacity, expiry, mobile, resource, or bandwidth behavior.-Coturn 4.17.2 documents `stun-only` as ignoring TURN requests and provides-`no-tcp` and `no-tls`; it marks `no-dtls` deprecated, so the tracked temporary-template did not use that switch. At that dated checkpoint, the shared host-still retained an authenticated-relay daemon and TCP/UDP 3478 plus UDP-49152-49251 rules. Current production instead runs coturn as STUN-only UDP 3478-and LiveKit media on UDP 7882, with coturn TCP/TLS and relay ranges disabled.-The historical participant-wide canary advertised no TURN credential and its-post-canary audit found zero allocations.--That historical candidate selected no new public port. LiveKit's optional-ICE/UDP mux, multi-port sample, and embedded TURN defaults are framework facts,-not current Screener deployment recommendations.--For `K` equal-representation first-level deliveries that cannot use direct media:--- `K` individual Host-to-Viewer selected-TURN edges: host upload `K*B`, server- ingress `K*B`, server egress `K*B`, total central traffic `2K*B`;-- one Host publication with `K` SFU subscriptions: host upload `B`, server- ingress `B`, server egress `K*B`, total central traffic `(K+1)*B`.--At `K=1` useful-payload traffic is equal, so the identity alone gives neither-route a preference; CPU and allocation cost require the same-host benchmark.-At `K=2`, the equal-representation SFU case halves host upload and-central ingress and reduces total central traffic from `4B` to `3B`, with the-same `2B` egress. Mixed representations replace `B` with measured `B_pub` and-`sum(B_s)`; a HIGH+LOW publication may erase that advantage. Public LiveKit-benchmarks and the Jitsi profiling breakdown establish capacity and component-categories only. Different machines and implementations cannot support a-universal relay/SFU CPU ratio or a claimed fixed percentage saving.--### Current Direct/SFU External Acceptance--One bounded exact-room gate owns the still-open direct/SFU evidence:--1. On the same host and NIC, measure LiveKit SFU UDP at 8 and 12 Mbps with one- publication and one, two, and twenty subscriptions. Record CPU seconds/GiB,- RX/TX bytes, packets/s, RSS, host upload, forwarding latency, loss/recovery,- and final decoded quality.-2. Cover representative consumer networks with independent STUN-only- direct/peer and SFU/UDP subscription gates. All ordinary peer connections- must remain STUN-only.-3. Block all UDP and show a bounded explicit failure; current media has no TCP- path.-4. Exercise assisted-route departure, reconnect, SFU unavailability, and- rollback. Non-server ordinary downstream edges stay within the configured- cap, SFU resources stay within accepted admission, and- unaffected peer subtrees do not migrate.-5. Correlate only route kind, candidate type/protocol, and opaque- generations; never upload raw SDP, candidate/address/IP, credentials, or- device identifiers.--Direct peer transport retains endpoint-to-endpoint DTLS-SRTP. Ordinary SFU-transport terminates DTLS-SRTP on both sides, so its operator can access media unless-Screener later implements application E2EE and key distribution. That accepted-tradeoff remains visible in deployment and UI claims.--A peer simultaneously re-publishing its received stream to the SFU and serving-peer children is outside the current product. A browser relay would decode and-re-encode, and publication ownership would add another failure domain; the-current model uses one authoritative Host publication. No global score,-continuous optimizer, geography, IP, UA, or self-reported capability chooses-routes.--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.--## Deployment-Wide SFU Admission--LiveKit's official benchmark guidance says each room must fit on one SFU node-and identifies published tracks, subscribers, and bytes forwarded per subscriber-as separate capacity drivers. Its room `maxParticipants` setting is a participant-count guard; it does not express Screener's Host-publication ingress or-per-subscription egress budget. The application therefore needs its own typed-admission boundary instead of treating a root count or the SDK room setting as-resource evidence.--Pinned LiveKit 1.13.5 treats `canPublishSources` as a source allowlist, not a-per-participant or per-source publication-count limit. `limit.num_tracks` gates-node-wide `NumTracksIn + NumTracksOut` admission, while-`subscription_limit_video/audio` caps each participant's concurrent subscribed-tracks by kind and leaves excess requests pending. Neither is an SFU bandwidth-budget or a replacement for Screener's ingress and egress admission.--For the current single application process, one O(1) ledger owns two explicitly-configured positive safe-integer capacities: each Host publication uses one-ingress unit and each authorized SFU subscription uses one egress unit. There is-no built-in default or fixed root count. A candidate reserves its full actual-ingress/egress demand under exact room/share/publication identity before any-token is issued; reserved, committed, and draining generations are all charged.-Capacity exhaustion leaves the current route unchanged and returns control to-the bounded fallback sequence. Screener sizes those capacities for its shipped-clients in private rooms where authenticated Hosts are trusted media-participants; the pinned upstream LiveKit release is sufficient for that-boundary.--Self-hosted `RemoveParticipant` closes the current participant but does not-invalidate a still-valid join token, and token expiry governs connection-admission rather than terminating an existing participant. A route commit or-client disconnect therefore cannot prove resource release. The dedicated-LiveKit instance disables automatic room creation. Screener explicitly creates-an exact-generation room containing an unguessable publication generation and-never reuses that name; `DeleteRoom` plus an absent-room readback is the drain-proof. With `room.auto_create: false`, an old token cannot recreate the absent-room. Reserved, committed, and draining generations remain charged until that-proof completes.--At process startup, the application first acquires its configured listener; a-competing process that cannot bind performs no LiveKit operation. The bound owner-returns `503` and installs no signaling upgrade handler while it rejects foreign-room names, drains all stale Screener rooms, and confirms the namespace empty-before admitting a new generation. Host signaling loss is checked against the-exact LiveKit Host participant on a bounded interval, so healthy media stays-charged while an abandoned generation is reclaimed after the participant-disappears.--These capacities are operator inputs derived from the actual instance, codec,-representation, bitrate, and accepted concurrency matrix. LiveKit's published-example benchmark cannot supply Screener defaults. A later multi-process-Screener deployment needs a shared atomic ledger; independent process-local-counters would not be deployment-wide admission.--## Route Screening--| Route | Where copies are emitted | Endpoint cost | Evidence status |-| --- | --- | --- | --- |-| Direct host P2P | Host emits one copy per Viewer | Host upload and sender pipelines grow with Viewers | Baseline evidence; current capacity is owned by the product contract |-| Bounded browser relay DAG | Host and each Web relay emit at most the configured endpoint cap | Ordinary browser, but every relay decodes and re-encodes and adds a hop | Current source and production admit up to 20; the exact v10 local direct loopback gate passed, while heterogeneous networks remain open |-| Native shared-encode host | Host targets one encode for standard WebRTC edges | libwebrtc public-API proxy risk spike, with Pion as fallback | Research evidence; 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 | Research only; no current product authorization |-| SFU service | SFU emits authorized subscription copies | Service pays bounded egress; an authoritative Host publisher supplies media | Production deploys the current topology/admission; local LiveKit functional evidence exists, while heterogeneous-network/resource validation remains open |-| SFU fallback | SFU emits authorized copies | Additional central ingress and egress cost | Deployed bounded path; real heterogeneous-network and resource acceptance remains open |-| SVC plus multiple trees | Peers emit striped layer copies across several trees | Layer scheduling, reassembly, redundancy, and more churn state | Separate conditional spike; target endpoint upload near `B` |-| Network coding | Peers or servers emit coded blocks | Generations, buffering, decoding, integrity, and a custom media plane | Trace/FEC spike only; optimize loss recovery, not clean bandwidth |-| MoQ | Publishers and MoQ relays emit object copies | New transport, packaging, player, relay, and auth stack | Optional central-fallback benchmark; still pays server egress |-| 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 |--## Native Sender And Encoded-RTP Relay Research--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.--Draft PR [#16](https://github.com/TNTcraftHIM/Screener/pull/16) has now passed-the narrower transport oracle: one Pion v4.2.18-`TrackLocalStaticRTP.WriteRTP` call fans a pre-packetized semantic payload to-two independent PeerConnections with binding-specific SSRCs. Because that-oracle contains no encoder, browsers, RTCP arbitration, or bandwidth-control-loop, it proves neither one physical encode nor a usable native relay. The-unresolved evidence boundary is browser-to-native-to-two-browser interoperability-with bounded RTCP/PLI, congestion, queues, throughput, and latency.--The native shared-encode sender and volunteer relay remain research candidates,-not current product work. Any later decision must keep deterministic assignment,-fanout, recovery, connectivity, mobile, and end-to-end latency concerns in their-proper owners.--## Outside The Current Browser-Track Spike--- **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. A separate encoded-object/native spike now owns its tree- maintenance, reassembly, scheduling, and redundancy gates; none belongs in- the fixed full-stream two-chain experiment.-- **Network coding:** published work improves block distribution in large- overlays. A trace-first FEC experiment must prove lower freeze/repair delay- within strict byte and buffering budgets before any media integration.-- **MoQ:** Media over QUIC provides promising relay-oriented publish/subscribe,- priorities, and partial reliability, but MOQT remains an active Internet-Draft.- Benchmark it only as a central fallback because a browser cannot act as an- inbound WebTransport peer and the relay still pays 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.--The measurable gates and exact staged experiments are in-[Advanced Peer Distribution](./advanced-peer-distribution.md).--## Sources And License Boundary--Primary sources accessed on 2026-08-19, 2026-08-21, 2026-08-22, and 2026-08-23:--- [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.+| Peer-only | `H*B` | `V*B` | `0` |+| Mixed peer/SFU | `H*B+B_pub` | `V*B` | `B_pub+sum(B_s)` |+| Full-room SFU | `B` | `0` | `(N+1)*B` |++For simulcast, `B_pub` is the sum of representations actually sent. A+`HIGH+LOW` publication can therefore cost more than one same-representation+peer edge. Dynacast or subscriber layer selection changes measured terms, not+the identity.++RTP/RTCP/SRTP, DTLS, ICE, IP headers, retransmission, FEC, and overlap only add+traffic. W3C candidate-pair byte counters omit some overhead, and provider+billing may count interfaces differently. Candidate formulas screen designs;+acceptance uses Host NIC, SFU interface, process, and billing counters from the+same run.++The unavoidable tradeoff is simple: if the server does not emit the copies,+endpoints must. If neither side emits them, the Viewers do not receive media.+Redundancy can improve recovery but adds copies and coordination.++## SFU Cost And Browser ICE Isolation++An SFU has at least four independent cost dimensions:++1. Host publication upload and server ingress (`B_pub`);+2. per-Viewer subscription egress (`sum(B_s)`);+3. packet forwarding, congestion-control, encryption, and room state; and+4. publication/subscription overlap and drain during recovery.++LiveKit's benchmark guidance treats published tracks, subscribers, and bytes+forwarded per subscriber as separate capacity drivers. Published example+numbers are not portable CPU, memory, or bandwidth defaults; instance type,+codec, representation set, bitrate, loss, and concurrency must be measured.++### Pinned Browser Isolation Evidence++One controlled Windows Chrome 151 reproduction used LiveKit Server 1.13.5 and+JS client 2.22.0 while a Mihomo system-stack TUN owned the public default route.+With server-supplied external STUN, two of eight isolated Host publications+connected. With the only changed input+`Room.connect(..., { rtcConfig: { iceServers: [] } })`, eight of eight formed a+nominated non-relay UDP pair. The explicit empty list retained LiveKit's+remotely signaled SFU candidate while suppressing additional Browser STUN+gathering; it did not disable ICE.++The result supports isolating Browser SFU PCs from external ICE servers in that+environment. It does not prove a universal TUN/VPN defect, a candidate-type+contract, fixed Browser socket allocation, mobile behavior, or public-network+success. Ordinary peer PCs and LiveKit server-side public-IP discovery are+separate ICE domains.++Relevant pinned sources are LiveKit's+[join-response construction](https://github.com/livekit/livekit/blob/v1.13.5/pkg/service/roommanager.go),+the client [connect options](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/Room.ts)+and [RTC configuration merge](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/RTCEngine.ts),+plus [media-transport public-IP discovery](https://github.com/livekit/mediatransportutil/blob/a3417d38cda0/pkg/rtcconfig/ip.go).++## Hard NAT And UDP Boundaries++"Symmetric NAT" is imprecise shorthand. Relevant facts are mapping and+filtering dependence, outbound UDP reachability, address-family support, state+lifetime, and network changes. CGNAT is an operator topology, not one behavior;+RFC 6888 inherits UDP NAT behavior requirements and recommends+endpoint-independent filtering.++| Condition | Standards boundary |+| --- | --- |+| Endpoint-independent mapping/filtering with UDP | Full ICE can test host, server-reflexive, and peer-reflexive pairs. |+| One endpoint-dependent mapper | Coordinated checks may work, but success is not guaranteed. |+| Two endpoint-dependent peer mappers | Direct peer UDP is not generally reliable; a public UDP service may still be reachable. |+| All outbound UDP blocked | No UDP candidate can carry media. |+| Wi-Fi/cellular/address change | Old mappings may be invalid; a fresh generation and bounded ICE rebuild must re-establish facts. |++Peer-reflexive candidates appear only after a connectivity check succeeds. RFC+5128 limits port prediction to favorable behavior; randomized or multi-level+mappings defeat it. RFC 5780 observes behavior toward its STUN destinations and+does not replace ICE. Carrier, CGNAT, UA, and candidate-type labels must not be+turned into success probabilities.++Ordinary browser JavaScript cannot bind raw UDP source ports, perform broad+multi-socket birthday probing, control PCP/NAT-PMP/UPnP gateways, or implement+TCP simultaneous-open. Creating many `RTCPeerConnection` instances would add+ICE/DTLS work, sockets, memory, and abuse surface without granting that control.+ICE renomination and QUIC traversal drafts do not expose a current browser API+that changes this boundary.++Native libp2p, Tailscale, and mobile studies are useful operational evidence,+but their relay reservation, raw-socket control, address discovery, native+coordination, and sampled networks differ from browser WebRTC. Their success+rates are not Screener coverage estimates.++## TURN Screening And No-Go++RFC 8656 TURN creates an allocation and relays packets for one client transport.+It does not authenticate or distribute a room publication. Gathering TURN+candidates participant-wide allocates server state even when the candidate is+never selected and widens credential scope beyond the exact route demand.++A later exact-edge TURN candidate narrows that scope but still adds a third+application candidate with separate credential issuance, allocation admission,+endpoint rebuild, recovery, expiry, and failure ownership. The functional+ability to relay one edge did not prove a need beyond the existing bounded SFU+fallback, so neither candidate is retained as a product route.++The useful-payload cost comparison explains the pressure. For `K` Host-to-+Viewer edges that all require TURN at bitrate `B`:++```text+TURN edges: Host K*B; TURN ingress K*B; TURN egress K*B+SFU: Host B; SFU ingress B; SFU egress K*B+```++At `K=1`, both central paths carry `2B`, so traffic alone chooses neither. At+`K=2`, TURN carries `4B` centrally while a same-representation SFU carries+`3B`; TURN also preserves two Host sender pipelines. Mixed representations use+measured `B_pub` and `sum(B_s)`, so the SFU advantage is not assumed.++This no-go is an application-scope decision, not a claim that TURN is broken.+Coturn remains a valid BSD-3-Clause STUN/TURN implementation, and LiveKit+supports TCP and embedded/external TURN options. Framework capability alone+does not require enabling every transport in Screener.++## SFU Admission Evidence++LiveKit controls do not directly express Screener's resource dimensions:++- room `maxParticipants` limits participant count;+- `canPublishSources` is an authorization allowlist;+- `limit.num_tracks` gates node-wide incoming plus outgoing tracks; and+- participant subscription limits cap subscribed track counts and may leave+ excess requests pending.++None is a Host-publication ingress budget, per-subscription egress budget, or+bandwidth/CPU guarantee. Application admission therefore needs distinct typed+publication and subscription demand, sized from the accepted codec,+representations, bitrate, instance, and concurrency evidence.++Admission must cover reservation, commitment, overlap, and drain. A token or+participant disconnect is not release proof: `RemoveParticipant` closes the+current participant but does not revoke an otherwise valid join token, and+token expiry controls new admission rather than terminating existing media.++For a dedicated self-hosted namespace, disabling `room.auto_create`, creating+an unguessable generation room explicitly, and retaining charges until+`DeleteRoom` succeeds and a follow-up lookup proves absence closes stale-token+re-entry. A single application process can own local counters; multiple+application processes require shared atomic admission before claiming a+deployment-wide bound.++The minimum capacity experiment measures one publication with 1, 2, and 20+subscriptions on the same SFU host and NIC. It records CPU time, RSS, ingress,+egress, packets, forwarding latency, loss/recovery, and decoded quality at the+actual representation/bitrate matrix. It also exercises reservation overlap,+failed creation, deletion-plus-absence, and process restart. Synthetic room or+track limits alone are not capacity evidence.++## Security And Privacy Boundary++TURN and SFU credentials must be short-lived, role- and generation-scoped, and+kept out of URLs, logs, diagnostics, and durable storage. Raw SDP, ICE+candidates, addresses, ports, tokens, and device identifiers are not needed for+route or capacity acceptance.++Direct peer media is endpoint-to-endpoint DTLS-SRTP. Ordinary SFU media+terminates DTLS-SRTP at the SFU, so the operator can access media unless an+application E2EE design and key-distribution mechanism is separately accepted.+This trust distinction is independent of traffic cost.++## Primary Sources And License Boundary++Sources were checked from 2026-08-19 through 2026-08-24:+- [RTP Topologies, RFC 7667](https://www.rfc-editor.org/rfc/rfc7667.html),- [ICE, RFC 8445](https://www.rfc-editor.org/rfc/rfc8445.html),- [dual-stack ICE guidance, RFC 8421](https://www.rfc-editor.org/rfc/rfc8421.html),- and [ICE PAC, RFC 8863](https://www.rfc-editor.org/rfc/rfc8863.html) - IETF- standards and BCP under IETF Trust terms.+ [ICE, RFC 8445](https://www.rfc-editor.org/rfc/rfc8445.html), and+ [WebRTC transports, RFC 8835](https://www.rfc-editor.org/rfc/rfc8835.html).- [UDP NAT behavior, RFC 4787](https://www.rfc-editor.org/rfc/rfc4787.html),[P2P across NATs, RFC 5128](https://www.rfc-editor.org/rfc/rfc5128.html),- [NAT behavior discovery, RFC 5780](https://www.rfc-editor.org/rfc/rfc5780.html),- [PCP, RFC 6887](https://www.rfc-editor.org/rfc/rfc6887.html), and- [CGN requirements, RFC 6888](https://www.rfc-editor.org/rfc/rfc6888.html) -- mapping, filtering, prediction, simultaneous-open, gateway-control, and CGN- resource boundaries.-- [TURN, RFC 8656](https://www.rfc-editor.org/rfc/rfc8656.html) - the relay is- transport for client/peer traffic, not a room distribution topology.-- [coturn 4.17.2 release](https://github.com/coturn/coturn/releases/tag/4.17.2)- and [pinned turnserver documentation](https://github.com/coturn/coturn/blob/4.17.2/README.turnserver)- - `stun-only` and UDP-only listener configuration; BSD-3-Clause, no code copied.-- [WebRTC transports, RFC 8835](https://www.rfc-editor.org/rfc/rfc8835.html) -- browser transport capability requirements do not require an application to- advertise every supported fallback on every connection.-- [WebRTC](https://www.w3.org/TR/webrtc/),- [WebRTC Statistics](https://w3c.github.io/webrtc-stats/),- [WebRTC Encoded Transform](https://w3c.github.io/webrtc-encoded-transform/#stream-processing),- [WebRTC SVC](https://www.w3.org/TR/webrtc-svc/), and- [WebTransport](https://www.w3.org/TR/webtransport/) - W3C specifications;- their JavaScript surfaces do not expose raw socket or gateway control.-- [Current libwebrtc STUN-port tests](https://chromium.googlesource.com/external/webrtc/+/refs/heads/main/p2p/base/stun_port_unittest.cc),- [native peer-connection configuration](https://chromium.googlesource.com/external/webrtc/+/refs/heads/main/api/peer_connection_interface.h),- and [native port allocator](https://chromium.googlesource.com/external/webrtc.git/+/master/p2p/base/port_allocator.h)- - `TestNoDuplicatedAddressWithTwoStunServers` and- `TestTwoCandidatesWithTwoStunServersAcrossNat` are current evidence for the- two-STUN behavior; the other controls are not exposed to browser JavaScript.- BSD-3-Clause, no code copied.-- [ICE Renomination, April 2026 Internet-Draft](https://datatracker.ietf.org/doc/draft-thatcher-tsvwg-renomination/)- and [n0 QUIC NAT Traversal, July 2026 Internet-Draft](https://datatracker.ietf.org/doc/draft-bruynooghe-n0-quic-nat-traversal/)- - active individual drafts, not browser APIs or final standards.-- [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 SFU- reference, with no code copied into this research change.-- [LiveKit 1.13.5 configuration sample](https://github.com/livekit/livekit/blob/v1.13.5/config-sample.yaml),- [pinned configuration source](https://github.com/livekit/livekit/blob/v1.13.5/pkg/config/config.go),- [node track-limit selection](https://github.com/livekit/livekit/blob/v1.13.5/pkg/routing/selector/utils.go),- [participant publication checks](https://github.com/livekit/livekit/blob/v1.13.5/pkg/rtc/participant.go),- [subscription-limit handling](https://github.com/livekit/livekit/blob/v1.13.5/pkg/rtc/subscriptionmanager.go),- [room allocation](https://github.com/livekit/livekit/blob/v1.13.5/pkg/service/roomallocator.go),- [room-service lifecycle](https://github.com/livekit/livekit/blob/v1.13.5/pkg/service/roomservice.go),- [access tokens and grants](https://docs.livekit.io/frontends/reference/tokens-grants/),+ [NAT discovery, RFC 5780](https://www.rfc-editor.org/rfc/rfc5780.html), and+ [CGN requirements, RFC 6888](https://www.rfc-editor.org/rfc/rfc6888.html).+- [TURN, RFC 8656](https://www.rfc-editor.org/rfc/rfc8656.html) and+ [coturn 4.17.2 documentation](https://github.com/coturn/coturn/blob/4.17.2/README.turnserver)+ (BSD-3-Clause; no code copied).+- [WebRTC](https://www.w3.org/TR/webrtc/) and+ [WebRTC Statistics](https://www.w3.org/TR/webrtc-stats/).+- [LiveKit Server 1.13.5 configuration](https://github.com/livekit/livekit/blob/v1.13.5/config-sample.yaml),+ [track-limit selection](https://github.com/livekit/livekit/blob/v1.13.5/pkg/routing/selector/utils.go),+ [publication checks](https://github.com/livekit/livekit/blob/v1.13.5/pkg/rtc/participant.go),+ [subscription limits](https://github.com/livekit/livekit/blob/v1.13.5/pkg/rtc/subscriptionmanager.go),+ and [RoomService lifecycle](https://github.com/livekit/livekit/blob/v1.13.5/pkg/service/roomservice.go).+- LiveKit official [tokens and grants](https://docs.livekit.io/frontends/reference/tokens-grants/),[RoomService API](https://docs.livekit.io/reference/other/roomservice-api/),- [server SDK 2.17.0 RoomServiceClient](https://github.com/livekit/node-sdks/blob/livekit-server-sdk%402.17.0/packages/livekit-server-sdk/src/RoomServiceClient.ts),- [ports/firewall](https://docs.livekit.io/transport/self-hosting/ports-firewall/),- [deployment/embedded TURN](https://docs.livekit.io/transport/self-hosting/deployment/),- and [benchmark guidance](https://docs.livekit.io/transport/self-hosting/benchmark/)- - transport, port, authentication, and capacity boundaries; no source copied.-- [LiveKit selective subscription](https://docs.livekit.io/transport/media/subscribe/)- and [end-to-end encryption](https://docs.livekit.io/transport/encryption/) -- official behavior and operator-boundary references.-- [LiveKit client 2.22.0 `Room.prepareConnection`](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/Room.ts),- [connection options](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/options.ts),- [RTC configuration construction](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/RTCEngine.ts),- [two-layer RID construction](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/participant/publishUtils.ts),- and [official usage](https://github.com/livekit/client-sdk-js#usage) -- Apache-2.0; API behavior and RID construction were inspected, with no source- copied.-- [libp2p hole-punching platform boundary](https://github.com/libp2p/specs/blob/master/connections/hole-punching.md),- [2026 large-scale DCUtR measurement](https://arxiv.org/html/2604.12484), and- [ProbeLab's 2026 final report](https://github.com/probe-lab/dcutr-project/blob/main/docs/dcutr-final-report.md)- - native relay-assisted evidence with conditional cohorts and explicit NAT-- classification caveats, not a browser-WebRTC success rate.-- [2023 CGNAT survey and four-carrier mobile experiment](https://arxiv.org/abs/2311.04658)- - small native mobile evidence, not a target-market coverage estimate.-- [Tailscale NAT traversal](https://tailscale.com/blog/how-nat-traversal-works) and- [2025 hard-NAT probing](https://tailscale.com/blog/nat-traversal-improvements-pt-1) - native operational references; no code copied.-- [Grozev, *Towards a Scalable Video Conferencing System*](https://publication-theses.unistra.fr/public/theses_doctorat/2019/Grozev_Boris_2019_ED269.pdf)- - one Jitsi profiling breakdown, not a coturn/LiveKit cross-system CPU ratio.--No GPL/AGPL code was copied. Published papers and specifications support design-analysis only; their presence here is not an implementation license.+ [ports and firewall](https://docs.livekit.io/transport/self-hosting/ports-firewall/),+ [deployment](https://docs.livekit.io/transport/self-hosting/deployment/),+ [benchmark guidance](https://docs.livekit.io/transport/self-hosting/benchmark/),+ [selective subscription](https://docs.livekit.io/transport/media/subscribe/),+ and [E2EE](https://docs.livekit.io/transport/encryption/).+- [LiveKit JS client 2.22.0](https://github.com/livekit/client-sdk-js/tree/v2.22.0)+ and [LiveKit Server](https://github.com/livekit/livekit) are Apache-2.0; their+ APIs and source behavior were inspected without copying code.+- [Mihomo TUN configuration](https://wiki.metacubex.one/config/inbound/tun/),+ [libp2p hole punching](https://github.com/libp2p/specs/blob/master/connections/hole-punching.md),+ [ProbeLab's DCUtR report](https://github.com/probe-lab/dcutr-project/blob/main/docs/dcutr-final-report.md),+ and the [2023 CGNAT/mobile study](https://arxiv.org/abs/2311.04658) bound the+ operational observations; none supplies a browser success-rate guarantee.++IETF and W3C specifications and published papers are design references, not+implementation licenses. No GPL/AGPL code was copied.diff --git a/docs/research/native-h264-hardware-decision.md b/docs/research/native-h264-hardware-decision.mddeleted file mode 100644index 85a3ece9..00000000--- a/docs/research/native-h264-hardware-decision.md+++ /dev/null@@ -1,405 +0,0 @@-# Native H.264 Hardware Decision Spike--Date: 2026-08-20--Status: Historical gate. Its `no-go-native-h264-hardware-pinned-fmtp`-stop resolved when the explicit opt-in Pion path registered exact `42c01f`;-the product WGC/MF path later passed its attributed one-Viewer smoke.--The later source-only functional slice in-[`native-h264-opt-in-path.md`](./native-h264-opt-in-path.md) registers the-fixture profile explicitly and proves one browser H.264 Host/Viewer loopback.-The native-window source now compiles this fixture's MF encoder source into the-product helper, retaining hardware-only enumeration and exact readback. That-path rendered 203 frames for one Chrome Viewer while the exact helper PID and-adapter LUID matched nonzero Windows `VideoEncode`; offline fixture telemetry-remains separate evidence.--This spike did not amend ADR-0006 or authorize another product, room, or-production run. It answered one narrow question: can a bounded Windows H.264-path satisfy the project's physical hardware-encode and existing default Pion-fmtp contracts before product integration?--The WebCodecs answer remains no: its bounded run did not prove hardware and its-emitted SPS differed from the requested codec string. A subsequent-hardware-only Media Foundation run did prove the selected NVIDIA encoder and-GPU engine, but emitted exact `profile-level-id=42c01f`, which is absent from-the default Pion mode-1 fmtp set. It therefore stopped before Pion, a Viewer,-rooms, or product wiring. The later opt-in source resolved that exact-registration mismatch without changing the browser VP8 default.--## Decision Summary--| Question | Result |-| --- | --- |-| Does Chrome 151 accept H.264 `avc1.42e01f`, Annex B, 720p30, realtime, 3 Mbps, `prefer-hardware`? | Yes. |-| Did the run prove an NVIDIA, AMD, or other hardware encoder? | No. Chrome-process Windows `VideoEncode` samples were all zero and no NVIDIA encode session was added. The sampling boundary cannot prove software because a later-created or non-child hardware process was not retained. |-| Did the requested codec string describe the emitted SPS exactly? | No. The requested `42e01f` produced SPS bytes `42 04 1f`. |-| Did forced key frames carry in-band recovery data? | Yes in this fixture: all six key chunks contained AUD, SPS, PPS, and IDR NAL units. |-| Can Pion v1.10.5 packetize the resulting Annex-B access units? | Yes statically: its `H264Payloader` splits 3/4-byte start codes, suppresses AUD/filler, emits SPS/PPS as STAP-A, and fragments slices as FU-A. |-| Did this isolated spike prove unmodified browser Viewer decode? | No. No PeerConnection, room, Viewer, or production service participated. A later opt-in loopback records that evidence separately. |-| Did this spike authorize the small WebCodecs/Pion codec diff? | No. The later exact-`42c01f` opt-in reopened and proved that boundary separately. |-| Did the Media Foundation fixture prove physical H.264 hardware encode? | Yes for one local RTX 4070 SUPER run: adapter-LUID-bound hardware enumeration, D3D11 awareness, the NVIDIA H.264 Encoder MFT, and process-plus-LUID `VideoEncode` activity agreed. |-| Did that hardware MFT emit an exact default Pion mode-1 fmtp string? | No. It emitted `42c01f`; the default set is `42001f`, `42e01f`, `4d001f`, and `64001f`. The fixture failed closed without changing the request or adding a fallback. This is not a standards-level profile incompatibility. |--## Standards And Platform Constraints--- WebCodecs defines `hardwareAcceleration: "prefer-hardware"` as a preference.- The user agent may ignore it, and `isConfigSupported()` is only a best-effort- capability answer. The answer can also change with resource availability.-- The AVC WebCodecs registration defines `avc.format: "annexb"`. Annex-B output- carries SPS/PPS in the bitstream instead of an AVC decoder configuration- description, which is the appropriate shape for live RTP packetization.-- WebRTC browsers must implement VP8 and H.264 Constrained Baseline. H.264- endpoints must support RFC 6184 and `packetization-mode=1`, include- `profile-level-id`, and send parameter sets in-band.-- RFC 6184 Table 5 identifies Constrained Baseline as `profile_idc=0x42` with- profile-iop matching `x1xx0000`. Both `42c01f` and `42e01f` match that same- Constrained Baseline sub-profile at level 3.1 even though their exact fmtp- strings differ.-- NVIDIA lists the local GeForce RTX 4070 SUPER as an Ada, eighth-generation- NVENC device with H.264 4:2:0 support. That proves the machine has suitable- hardware; it does not prove Chrome selected it.-- Media Foundation can enumerate hardware MFTs explicitly with- `MFT_ENUM_FLAG_HARDWARE`. A D3D11-aware transform can receive an- `IMFDXGIDeviceManager`, allowing capture and encode surfaces to remain on the- selected device. Hardware enumeration and D3D awareness are read-back gates,- not hints.--## WebCodecs Bounded Fixture--### Isolation--- Browser: Google Chrome `151.0.7922.138`.-- GPU cohort: NVIDIA GeForce RTX 4070 SUPER, NVIDIA driver `610.88`; an AMD- Radeon integrated adapter and virtual display adapters were also present.-- Source: local `127.0.0.1` page with a synthetic 1280x720 Canvas. No Screener- server, signaling endpoint, room, account, Viewer, Oopz process, or production- endpoint was started or contacted.-- Chrome used a unique temporary profile, D3D11 ANGLE, background throttling- disabled, and an off-screen window. The two temporary profiles contained no- reparse points. After the run, both exact temporary trees were audited again- without following links, deleted, and confirmed absent.-- Each codec was attempted at most once. H.264 performed one encode run. VP8- failed the exact `prefer-hardware` capability check and was not silently- retried with `no-preference`.--### Encoder Fixture--```text-width/height: 1280 x 720-framerate: 30-duration: 360 inputs / about 12 seconds-bitrate: 3,000,000 bits/s-latencyMode: realtime-bitrateMode: variable-hardwareAcceleration: prefer-hardware-H.264 codec/format: avc1.42e01f / annexb-key-frame request: frames 0, 60, 120, 180, 240, 300-source: moving synthetic Canvas, one VideoFrame per 33.333 ms-```--The output callback recorded each chunk's timestamp, size, callback latency,-and Annex-B NAL types. It parsed the SPS profile, constraint, and level bytes.-It did not save encoded frames.--The temporary fixture and sampling scripts were not retained. This is a single-bounded observation, not a repository-reproducible benchmark. The 15.984-second-CPU sampling window also extends beyond the 11.978-second encode loop, so its-CPU value describes the whole sampled Chrome process tree rather than active-encode cost.--### Physical Evidence Method--The hardware decision did not use `isConfigSupported()` as proof.--1. The launched Chrome process tree was resolved after the target attached and- before encoder configuration. It included the browser, GPU, utility, and- renderer processes.-2. Windows sampled- `\\GPU Engine(*)\\Utilization Percentage` once per second for 15 samples and- retained only `engtype_videoencode` instances owned by that process tree.-3. The same samples retained cumulative CPU seconds for the process tree.-4. `nvidia-smi` sampled global encoder session count, FPS, latency, and encoder- utilization. An unrelated `nvcontainer.exe` session already existed, so- global utilization was discarded as attribution evidence; only a new- session could have corroborated Chrome NVENC use.--This method has one explicit limitation: the process tree was not re-enumerated-after encoding began. A hardware service created later or outside Chrome's-parent/child tree would not have been attributed. The result is therefore-"hardware not proven", not a claim that a particular software encoder was-positively identified.--## Raw Bounded Evidence--### H.264--| Measure | Retained value |-| --- | --- |-| `isConfigSupported` | `true`; returned config retained `prefer-hardware`, `realtime`, `variable`, and `annexb` |-| Inputs / outputs | `360 / 360` |-| Encode-loop wall time | `11,977.6 ms` |-| Output bytes / observed VBR rate | `2,275,233 / 1,521,047 bit/s` |-| Encoder queue peak | `8` |-| Output callback latency | p50 `10.0 ms`; p95 `11.3 ms`; max `241.8 ms` |-| Scheduling delay | p50 `1.07 ms`; p95 `14.17 ms`; max `15.8 ms` |-| Pending outputs / fatal error | `0 / none` |-| Decoder config | codec `avc1.42e01f`, 1280x720, description `0` bytes |-| Chrome-tree `VideoEncode` | 15 samples: `[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]` |-| NVIDIA global sessions | 15 samples: `[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]` |-| Chrome-tree CPU | `3.21875 CPU-s / 15.984 wall-s`; `1.259%` of 16 logical processors, or about `20.1%` of one logical processor |--CPU includes Chrome, Canvas drawing, frame construction, and encode work; it is-not an isolated encoder CPU measurement.--All six requested key chunks had NAL types `[9, 7, 8, 5]`, meaning AUD, SPS,-PPS, and IDR. Their byte sizes were-`[6074, 8675, 6672, 9567, 8483, 10011]`. Each began with the same retained-prefix:--```text-000000010910000000016742041fe8a02802ddff-```--The parsed SPS bytes were `profile_idc=0x42`, constraints `0x04`, and-`level_idc=0x1f` (`42041f`). That is not the requested codec string's-`42e01f`. WebCodecs requires an encoder to produce a stream at least as-constrained as the requested string, but this spike does not attempt to prove-the H.264 semantic relationship between those two constraint bytes. The-product gate is simpler: do not advertise or request an fmtp value until the-emitted stream's constraint bytes are proven compatible, then prove an-unmodified Viewer negotiation and decode.--### VP8--The exact same 720p30 configuration with codec `vp8` and-`hardwareAcceleration: "prefer-hardware"` returned-`isConfigSupported().supported=false`. No VP8 frames were encoded and no-latency or CPU comparison is claimed. The current ADR-0006 candidate deletes-`hardwareAcceleration` and continues when that check fails; the existing-shared-encode research already classifies that behavior as an implementation-preference, not physical hardware evidence.--## Media Foundation Hardware Fixture--The follow-up fixture is retained at-`native/fixtures/mf-h264-hardware/`. Its build compiles the shared encoder-source from `native/window-capture-helper/` with fixture-only synthetic input-and telemetry. The generated fixture executable stays outside the repository-and has no room, capture, audio, signaling, Pion, or Viewer fallback.--### Fixed Contract--- Toolchain: MSVC 19.42 and Windows SDK 10.0.22621.0.-- Selected adapter: DXGI index 0, NVIDIA GeForce RTX 4070 SUPER, LUID- `0x00000000:0x0001a496`, driver 610.88.-- Selected transform: the sole adapter-bound candidate, NVIDIA H.264 Encoder- MFT, CLSID `{60F44560-5A20-4857-BFEF-D29773CB8040}`.-- Enumeration: `MFTEnum2` with the selected LUID, NV12 input, H.264 output, and- only `MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_SORTANDFILTER`.-- Device path: explicit D3D11 hardware device with video support, a reset DXGI- device manager, `MF_TRANSFORM_ASYNC=true`,- `MF_SA_D3D11_AWARE=true`, and accepted `MFT_MESSAGE_SET_D3D_MANAGER`.-- Media: NV12 GPU-surface inputs, 1280x720 at 30 fps, 3 Mbps H.264 Baseline- level 3.1, 360 paced inputs, and a maximum eight in flight.-- Required `ICodecAPI` readback: CBR, 3 Mbps mean bitrate, 12,500-byte- one-frame VBV, low-latency mode, and a 60-frame GOP. Every value required- `IsSupported=S_OK`, `SetValue=S_OK`, and exact `GetValue` readback.-- Recovery requests: `CODECAPI_AVEncVideoForceKeyFrame` immediately before- inputs 0, 60, 120, 180, 240, and 300.--The NVIDIA MFT returned `E_NOTIMPL` for at least the CBR `IsModifiable` query.-That advisory result was not treated as proof either way; an actual-`SetValue=S_OK` followed by exact `GetValue` was required. `S_FALSE`, a failed-set, missing readback, or a changed value still fails. Three redundant controls-were deliberately excluded:--- `AVEncCommonRealTime` was unsupported, while `AVLowLatencyMode` already- requires no reordering delay and one output per input;-- `AVEncCommonMaxBitRate` applies to peak-constrained VBR, not the selected- CBR mode; and-- the optional B-picture-count property was unsupported, while Baseline- excludes B slices and the run independently required ordered timestamps.--This keeps the contract on observable behavior rather than on optional aliases.--### Retained Run--One final instrumented run used the exact adapter and transform above. No-encoded sample was written to disk and no network or Screener process was-started.--| Measure | Retained value |-| --- | --- |-| Inputs / outputs | `360 / 360` |-| Recovery access units | `6 / 6`, each with Annex-B SPS, PPS, and IDR |-| Maximum in flight | `1` |-| Encoded bytes | `2,956,354` |-| Wall time | `12.106 s` |-| Input-to-output latency p95 | `11.575 ms` |-| Fixture process CPU | `2.094 CPU-s` over the run; includes synthetic NV12 generation and event handling |-| Process-and-adapter `VideoEncode` | 45 samples; mean `2.949%`, max `4.863%` |-| Output SPS `profile-level-id` | `42c01f` |-| Final result | `no-go-native-h264-hardware-pinned-fmtp` |--The physical evidence is correlated rather than inferred from low CPU: the-hardware-only activation was bound to the selected DXGI LUID, accepted that-device's D3D manager, and Windows observed `engtype_videoencode` activity for-both the fixture PID and that same LUID. The existing unrelated NVIDIA encoder-session cannot satisfy this PID-and-LUID filter.--The run failed its local gate because `42c01f` is not exactly one of Pion-v4.2.18's default mode-1 values (`42001f`, `42e01f`, `4d001f`, or `64001f`).-RFC 6184 Table 5 nevertheless classifies both `42c01f` and `42e01f` as the same-Constrained Baseline sub-profile. The result is therefore a default-capability-miss with unmodified Viewer interoperability unproven, not an incompatible-H.264 profile. The fixture did not change its request, register a new fmtp, try-the AMD adapter, activate another MFT, or add an NVENC/software fallback. Pion-and Viewer work did not begin, so the result proves a usable hardware-encode-primitive but not a transportable Screener stream.--## Static Product-Path Evaluation--The small bitstream path is plausible:--```text-one VideoEncoder- -> existing 17-byte Frame envelope- -> one Go Fanout queue and RTP packetizer- -> one TrackLocalStaticRTP- -> at most two PeerConnections / transport-local bindings-```--- `native/sender/internal/app/ui/app.js` owns one `VideoEncoder` object and- marks the next submitted frame as a key frame when any downstream request is- pending.-- `native/sender/internal/media/fanout.go` owns one queue, one timeline, and one- packetizer. Switching `VP8Payloader` to `H264Payloader` would not create a- per-Viewer encoder.-- `native/sender/internal/remote/peer.go` adds the same track to every bounded- PeerConnection. PLI or FIR on any leg emits the existing shared key-frame- request. A connected late Viewer also requests a key frame.-- Pion RTP v1.10.5 accepts Annex-B access units. Its H.264 payloader stores SPS- and PPS, emits them as STAP-A before the following NALU, fragments large NALUs- as FU-A, and discards AUD/filler. This requires negotiated- `packetization-mode=1`.--The fixture's repeated `[SPS, PPS, IDR]` key chunks make the shared feedback-shape credible: one merged PLI/FIR can generate one access unit for every-bound Viewer. This is static evidence plus an encoder-only fixture, not a-Viewer proof.--Two exact-string boundaries remain distinct. The earlier WebCodecs run emitted-`42041f`; the Media Foundation run emitted `42c01f`. Pion v4.2.18's default-H.264 mode-1 capabilities include `42001f`, `42e01f`, `4d001f`, and `64001f`,-so neither observed string is present by default. Unlike the earlier WebCodecs-value, the Media Foundation `42c01f` value matches RFC 6184's Constrained-Baseline pattern. Binding a track by MIME type alone can fall back to a partial-codec match and advertise a different format. The next gate must instead:--1. parse emitted SPS before publishing;-2. register and offer the exact emitted, standards-valid mode-1 capability;-3. retain the selected answer `profile-level-id` without raw SDP;-4. prove Chrome, Edge, Firefox, and Safari Viewer decode/render;-5. prove every join/PLI/FIR recovery unit carries usable in-band SPS/PPS and- IDR; and-6. retain one encoder invocation while two independent RTP bindings advance.--The obvious WebCodecs/Pion edit is roughly 40-80 core lines plus focused tests,-but it cannot supply either a portable hardware identity or this interop proof.-It therefore does not satisfy this spike's 200-300-core-line implementation-exception despite being textually small.--## WebCodecs Versus Native Hardware APIs--| Route | Advantage | Blocking cost / risk | Decision |-| --- | --- | --- | --- |-| WebCodecs H.264 Annex B + Pion | Smallest diff; observed SPS/PPS/IDR cadence; existing shared fanout remains intact | Hardware request is a hint; no encoder identity/readback; emitted constraint bytes differ and fmtp compatibility is unclassified; no Viewer proof | Freeze |-| Media Foundation hardware H.264 MFT | Proved one physical NVIDIA path with exact transform, D3D11 manager, codec readback, 360 outputs, and six recovery units | Emitted standards-valid Constrained Baseline `42c01f`, outside Pion's default exact fmtp set; no Pion or Viewer proof | Retain fixture; product no-go |-| Direct NVENC | Explicit NVIDIA encoder session and detailed low-latency controls | NVIDIA-only, SDK/API lifecycle and redistribution review, separate AMD/Intel future decisions | Hold unless the Media Foundation hardware contract fails |--Media Foundation remains the smallest proved physical-encode primitive because-it fails closed on an official hardware category without a vendor dispatch-layer. Its default-fmtp miss leaves product interoperability unproven. It is one-Windows H.264 fixture, not an abstraction for VP8/VP9/AV1/HEVC and not a-software fallback.--## Retained Stop Line--The hardware-only fixture is complete for this decision. Do not alter its-requested media type, local default-fmtp gate, or sender wiring merely to make-this fixture return zero. A separately bounded follow-up may register and offer-exact `42c01f`, then test Pion/two-binding and unmodified Viewer decode without-turning that experiment into product integration.--Direct NVENC is still a separately authorized candidate if tighter bitstream-control remains necessary after the bounded `42c01f` interop test. It is-NVIDIA-only and brings a Video Codec SDK license and distribution review, so it-is not an automatic fallback from this Media Foundation result. The existing-WebCodecs-to-Go bridge product gap also remains independent and should not be-hidden inside codec work.--## Go / No-Go Gates--The Media Foundation slice is `go-native-h264-hardware-fixture` only when all-of these are retained in one run. The current result is shown inline:--- pass: exact hardware MFT identity and D3D11-aware readback;-- pass: process-and-adapter-attributed `VideoEncode` activity and no software- fallback;-- pass: 360/360 bounded outputs with p95 input-to-output latency recorded;-- fail: exact SPS string membership in the default Pion mode-1 fmtp set; this- does not mean the emitted Constrained Baseline profile is incompatible;-- pass for encoder requests only: six SPS/PPS/IDR recovery access units;-- not run: the same encoded access unit packetized once and delivered over two- transport bindings; and-- not run: unmodified Viewer decode/render in the target browser matrix.--Any missing physical, fmtp, feedback, or Viewer evidence remains no-go. Do-not infer success from codec support, adapter model, transform enumeration,-low CPU, or a single browser decode.--## License Boundary--- Pion RTP/WebRTC is MIT and remains the packetization/transport candidate; no- Pion source was copied into this repository.-- Media Foundation and D3D11 are Windows platform APIs. The fixture should use- installed hardware MFTs and avoid redistributing vendor codec binaries.-- Direct NVENC would require a separate NVIDIA Video Codec SDK license and- redistribution review before product work.-- H.264 patent/licensing obligations remain unresolved regardless of whether- encoding is reached through WebCodecs, Media Foundation, or NVENC. The- project license and distribution model must be decided before distributing a- sender executable.--## Primary Sources--Accessed 2026-08-20:--- [W3C WebCodecs](https://www.w3.org/TR/webcodecs/)-- [W3C AVC WebCodecs registration](https://www.w3.org/TR/webcodecs-avc-codec-registration/)-- [RFC 7742: WebRTC video codec requirements](https://www.rfc-editor.org/rfc/rfc7742.html)-- [RFC 6184: H.264 RTP payload format](https://www.rfc-editor.org/rfc/rfc6184.html)-- [NVIDIA video encode/decode support matrix](https://developer.nvidia.com/video-encode-decode-support-matrix)-- [NVIDIA NVENC application note](https://docs.nvidia.com/video-technologies/video-codec-sdk/13.0/nvenc-application-note/index.html)-- [NVIDIA NVENC programming guide](https://docs.nvidia.com/video-technologies/video-codec-sdk/13.0/nvenc-video-encoder-api-prog-guide/index.html)-- [NVIDIA System Management Interface](https://docs.nvidia.com/deploy/nvidia-smi/index.html)-- [Microsoft `typeperf`](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/typeperf)-- [Microsoft `MFTEnumEx`](https://learn.microsoft.com/en-us/windows/win32/api/mfapi/nf-mfapi-mftenumex)-- [Microsoft `MFTEnum2`](https://learn.microsoft.com/en-us/windows/win32/api/mfapi/nf-mfapi-mftenum2)-- [Microsoft hardware MFTs](https://learn.microsoft.com/en-us/windows/win32/medfound/hardware-mfts)-- [Microsoft asynchronous MFTs](https://learn.microsoft.com/en-us/windows/win32/medfound/asynchronous-mfts)-- [Microsoft async MFT unlock](https://learn.microsoft.com/en-us/windows/win32/medfound/mf-transform-async-unlock)-- [Microsoft `MF_SA_D3D11_AWARE`](https://learn.microsoft.com/en-us/windows/win32/medfound/mf-sa-d3d11-aware)-- [Microsoft `MFCreateDXGIDeviceManager`](https://learn.microsoft.com/en-us/windows/win32/api/mfapi/nf-mfapi-mfcreatedxgidevicemanager)-- [Microsoft `MFCreateDXGISurfaceBuffer`](https://learn.microsoft.com/en-us/windows/win32/api/mfapi/nf-mfapi-mfcreatedxgisurfacebuffer)-- [Microsoft H.264 video encoder](https://learn.microsoft.com/en-us/windows/win32/medfound/h-264-video-encoder)-- [Microsoft low-latency codec property](https://learn.microsoft.com/en-us/windows/win32/medfound/codecapi-avlowlatencymode)-- [Microsoft force-key-frame property](https://learn.microsoft.com/en-us/windows/win32/medfound/codecapi-avencvideoforcekeyframe)-- [Microsoft `ICodecAPI::IsModifiable`](https://learn.microsoft.com/en-us/windows/win32/api/strmif/nf-strmif-icodecapi-ismodifiable)-- [Microsoft `ICodecAPI::SetValue`](https://learn.microsoft.com/en-us/windows/win32/api/strmif/nf-strmif-icodecapi-setvalue)-- [Microsoft D3D multithread protection](https://learn.microsoft.com/en-us/windows/win32/api/d3d10/nf-d3d10-id3d10multithread-setmultithreadprotected)-- [Microsoft H.264 profile enumeration](https://learn.microsoft.com/en-us/windows/win32/api/codecapi/ne-codecapi-eavench264vprofile)-- [Pion RTP v1.10.5 H.264 payloader](https://github.com/pion/rtp/blob/v1.10.5/codecs/h264_packet.go)-- [Pion WebRTC v4.2.18 media engine](https://github.com/pion/webrtc/blob/v4.2.18/mediaengine.go)diff --git a/docs/research/native-h264-opt-in-path.md b/docs/research/native-h264-opt-in-path.mddeleted file mode 100644index 080f4084..00000000--- a/docs/research/native-h264-opt-in-path.md+++ /dev/null@@ -1,123 +0,0 @@-# Native H.264 Opt-In Path--## 2026-08-21 Native Window Source--The Native sender has two explicit local video sources. The Web source uses the-independent Browser codec path; the separate `native-window-h264` source is Windows-11-only and requires-the user to select one local opaque window target. It never silently replaces a-browser source or falls back to software encode, another codec, monitor capture,-or system audio.--The native-window path is:--```text-opaque local target -> HWND + PID + process creation time- -> WGC BGRA surface on one selected D3D11 adapter- -> D3D11 VideoProcessor 1280x720 NV12- -> adapter-bound hardware-only MF H.264 42c01f Annex-B- -> generation-bound Go Session.WriteMedia- -> one Go queue and Pion H264Payloader- -> one TrackLocalStaticRTP- -> at most two independent PeerConnections-```--The helper revalidates HWND-to-PID and PID creation time immediately before WGC-activation. The same process identity feeds WASAPI application loopback with-`INCLUDE_TARGET_PROCESS_TREE`. One private stdout protocol multiplexes bounded-PCM, H.264 access units, and local hardware status. PID, HWND, creation time,-adapter/MFT identity, PCM, and status never enter signaling. Go sends H.264-directly to the existing fanout; a second local copy travels only to the sender-UI's `VideoDecoder` preview and never returns to Go. PCM retains the existing-local WebCodecs Opus bridge.--PLI/FIR and fanout recovery requests enter the generation-bound helper stdin as-one coalesced `K` command. The helper forces an in-band SPS/PPS/IDR recovery-unit, while the existing Pion `H264Payloader`, exact `42c01f` MediaEngine, one-shared track, and two-edge cap remain unchanged. The Browser source uses the existing-`getDisplayMedia` and `VideoEncoder` path.--Both the product helper and offline fixture compile the same MF encoder source.-The product build and the fixture build pass MSVC `/W4 /WX`; focused Go tests-cover bound target arguments, multiplexed protocol bounds, key-frame command-forwarding, generation/source validation, and the peer-assisted Host contract.--## Native Window Acceptance Evidence--One bounded Chrome 151 run used a real animated top-level window, process-tree-audio, the explicit Native source, and the peer-assisted direct-child wire. It-created no browser capture or `VideoEncoder`; the ordinary Viewer received-1,313 packets/1,431,696 bytes during the sample, decoded and rendered 203-1280x720 frames, and received 500 Opus packets without a fatal/encoder error.-The helper wrote 30 frames and 174 source RTP packets before the retained-sender-start snapshot.--The exact helper process was PID 15060. Its Windows GPU Engine instance-`pid_15060_luid_0x00000000_0x0001a496_phys_0_eng_6_engtype_videoencode`-reached 2.98028% utilization; the helper's independently validated adapter-status was `0x00000000:0x0001a496`. This is process-and-adapter-correlated-hardware evidence, not a throughput or performance claim. The independent-Viewer receive/decode/render and sender counters establish this functional-boundary; asynchronously sampled Pion deltas and elapsed time remain diagnostic.--Primary sources checked 2026-08-21:--- [Windows Graphics Capture](https://learn.microsoft.com/en-us/windows/uwp/audio-video-camera/screen-capture)-- [`IGraphicsCaptureItemInterop::CreateForWindow`](https://learn.microsoft.com/en-us/windows/win32/api/windows.graphics.capture.interop/nf-windows-graphics-capture-interop-igraphicscaptureiteminterop-createforwindow)-- [`Direct3D11CaptureFramePool::CreateFreeThreaded`](https://learn.microsoft.com/en-us/uwp/api/windows.graphics.capture.direct3d11captureframepool.createfreethreaded)-- [`CreateDirect3D11DeviceFromDXGIDevice`](https://learn.microsoft.com/en-us/windows/win32/api/windows.graphics.directx.direct3d11.interop/nf-windows-graphics-directx-direct3d11-interop-createdirect3d11devicefromdxgidevice)-- [Microsoft MIT HWND capture sample](https://github.com/microsoft/Windows.UI.Composition-Win32-Samples/tree/master/cpp/ScreenCaptureforHWND)-- [`ID3D11VideoDevice::CreateVideoProcessorInputView`](https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11videodevice-createvideoprocessorinputview)-- [`ID3D11VideoContext::VideoProcessorSetOutputBackgroundColor`](https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11videocontext-videoprocessorsetoutputbackgroundcolor)--## 2026-08-21 Browser-To-Native H.264 Evidence--The ordinary Browser WebRTC path is fixed VP8 and is independent of this Native-research. The browser-to-Native bridge loopback below uses Chrome WebCodecs-H.264 Annex-B -> the local envelope -> the same Go/Pion fanout only as bounded-Native-path evidence; it does not add a Browser codec option or fallback.--## Bounded Loopback Evidence--One short Chrome 151 one-viewer gate ran on 2026-08-20/21 with the in-memory-development server, no peer assistance, no TURN, and a synthetic animated-1280x720 source. The H.264 sender configuration was 720p30, 3 Mbps, one-encoder instance, Annex-B output, and `hardwareAcceleration: prefer-hardware`.--Retained evidence:--| Boundary | Result |-| --- | --- |-| Sender configuration / encoder | H.264 config accepted; one encoder; 18 frames written; 156 source RTP packets; 174,978 source RTP bytes; zero encoder/fatal errors |-| Signaling and ICE | Host authentication, room creation, offer/answer, trickle ICE, and both peer connections reached connected |-| Viewer media | 2,690 inbound packets, about 3.0 MiB, 299 decoded and 298 rendered frames, 1280x720 |-| Resource/lifecycle | One host edge; cleanup completed; no production endpoint or TURN allocation |--Independent Viewer receive/decode/render and sender checks passed. Sampling-latency and the asynchronously refreshed Pion delta are diagnostic only. This-is one functional loopback, not a public-network, multi-viewer, endurance, or-codec benchmark.--## Hardware Boundary--The Media Foundation/NVIDIA fixture established the physical hardware gate and-the exact `42c01f` in-band recovery contract. Browser H.264 cannot select a-specific adapter or Media Foundation encoder. The native-window source instead-enumerates only an adapter-LUID-bound hardware MFT, requires D3D11 awareness and-exact codec readback, and has no software retry. The Native acceptance run above adds the-required product-process `VideoEncode` attribution; fixture evidence remains a-separate encoder-contract measurement.--## Scope--- The Web source keeps the Browser codec decision independent; production rollout remains tracked separately- from this Native research path.-- No codec matrix, benchmark, second viewer, or endurance run is required for- this landing slice.-- `npm run probe:native-one-viewer` remains optional Native research and does- not enter Web acceptance.-- The Native source reuses existing controller compatibility and evaluation- packaging changes; it adds no topology.-- H.264 distribution still carries the existing patent/license review boundary.-----diff --git a/docs/research/native-sender.md b/docs/research/native-sender.mdnew file mode 100644index 00000000..7315f359--- /dev/null+++ b/docs/research/native-sender.md@@ -0,0 +1,161 @@+# Native Sender And Shared-Encode Evidence++- Reviewed: 2026-08-27+- Scope: Windows capture, one hardware H.264 encoder, bounded WebRTC fanout+- Status: later product candidate; one-Viewer functional/hardware evidence only++Current product scope is owned by [media quality](../product/media-quality.md).+[ADR-0006](../adr/0006-fixed-high-native-sender-canary.md) owns the stop line.++## Conclusion++A native sender can plausibly capture and encode once while serving bounded+independent WebRTC transports. Shared encoding can reduce capture/encode work;+it cannot remove each child's RTP, congestion, retransmission, encryption, and+network copy.++The retained evidence proves:++- Pion can fan one encoded source into two independent transport bindings;+- one WebCodecs encoder object fed two Browser sessions in a bounded fixture;+- one Windows Graphics Capture/Media Foundation H.264 path used an adapter-+ bound hardware MFT with matching process/LUID `VideoEncode` activity; and+- the product helper delivered H.264 video and process-tree audio to one Chrome+ Viewer.++It does not prove two-Viewer product fanout, heterogeneous congestion feedback,+loss/retransmission correctness, audio synchronization, reconnect isolation,+public networks, endurance, packaging, update/signing, cross-platform behavior,+or distribution licensing. Native remains outside the current release.++## Candidate Shape++The smallest retained Windows architecture is:++```text+opaque window target+ -> Windows Graphics Capture BGRA surface+ -> one D3D11 conversion to NV12+ -> one adapter-bound hardware Media Foundation H.264 encoder+ -> one generation-bound Go/Pion RTP source+ -> at most two independent PeerConnections+```++Each PeerConnection must keep independent ICE, DTLS-SRTP, SSRC/sequence/TWCC,+pacing, RTCP, congestion, and retransmission state. PLI/FIR from any child may be+coalesced into one shared SPS/PPS/IDR request, but a weak child's bitrate request+cannot silently become a room-wide minimum policy. A third Viewer must wait+under the same endpoint capacity as Web Hosts.++Local target identity, HWND/PID, process creation time, adapter/MFT identity,+PCM, and hardware diagnostics never enter signaling. The helper revalidates the+selected window/process before capture. There is no software, codec, monitor, or+audio fallback hidden behind a hardware-only source choice.++## Browser And Pion Fixtures++A stack of bounded fixtures established progressively narrower facts:++| Gate | Retained result | Missing proof |+| --- | --- | --- |+| One Pion RTP source, two bindings | Equivalent payload reached two transport-local SSRCs. | No encoder or Browser. |+| WebCodecs VP8, two Chrome receivers | One encoder object produced 120 outputs; both decoded. | Physical/hardware encoder identity. |+| 12-second live bridge | 360 inputs/outputs; both Viewers rendered 331 frames; queues remained bounded. | Product rooms/capture/audio. |+| Pion GCC plus negotiated RTX | Failed with unknown RTX SSRC. | Valid shared congestion/retransmission composition. |+| No-RTX replay | One leg recovered without disturbing the other. | Accurate retransmission-specific loss accounting. |+| Two-leg stock GCC | Both estimates happened to be 600 kbps; one shared reconfiguration and keyframe recovery succeeded. | Heterogeneous estimates and product policy. |++The stock-GCC/RTX composition remains no-go. Do not replace it with a custom+pacer, congestion controller, interceptor fork, SRTP, or private transport.+No-RTX replay remains research-only because it can distort RTP/RTCP loss+accounting.++## Hardware Encoder Evidence++### WebCodecs++Chrome accepted H.264 Annex-B 1280x720@30 with `prefer-hardware` and produced+360/360 frames, but Browser-process GPU samples showed no attributed+`VideoEncode` activity. The emitted SPS was `42041f`, not the requested codec+string. This proves usable chunks and in-band recovery units, not hardware+selection or exact WebRTC fmtp compatibility. VP8 `prefer-hardware` was rejected+on the same Windows system.++### Media Foundation Fixture++One MSVC/D3D11 fixture selected the NVIDIA H.264 Encoder MFT on an RTX 4070+SUPER by exact DXGI LUID, required hardware enumeration, D3D11 awareness,+low-latency mode, CBR readback, 3 Mbps, a 60-frame GOP, and forced keyframes.++| Measure | Retained result |+| --- | --- |+| Inputs / outputs | 360 / 360 |+| Recovery units | 6 / 6 with Annex-B SPS, PPS, and IDR |+| Maximum in flight | 1 |+| Wall time | 12.106 s |+| Input-to-output p95 | 11.575 ms |+| Process+adapter VideoEncode | 45 samples; mean 2.949%, max 4.863% |+| Emitted profile | `42c01f` |++The MFT was physically attributed by hardware-only activation, accepted device+manager, exact process/LUID GPU engine, and output progress. Its `42c01f`+Constrained Baseline profile was absent from Pion's default exact mode-1 list,+so the fixture correctly stopped before claiming transport interoperability.+The later opt-in fixture registered that exact profile and proved one Browser+loopback; it did not alter the wider stop line.++### Product Helper Smoke++The Windows helper reuses the same encoder source with WGC capture and+process-tree WASAPI loopback. One bounded run delivered 203 rendered 1280x720+frames and 500 Opus packets to a Chrome Viewer. The exact helper PID and adapter+LUID matched nonzero `VideoEncode`. This is a one-Viewer functional proof, not a+resource or product release claim.++## Remaining Gates++Before native product consideration, one current-wire candidate must prove:++1. current room/Host authorization and source-generation cleanup;+2. exact emitted H.264 profile negotiation and unmodified Chrome, Edge, Firefox,+ and Safari decode/render;+3. two independent transports with one physical encoder and compatible source,+ codec, cadence, and rate requests;+4. correct PLI/FIR, NACK/RTX, TWCC, burst/sustained loss, and reconnect isolation;+5. process audio, A/V synchronization, source switch, pause, and failure;+6. bounded CPU/GPU, memory, latency, quality, upload, queues, and thermals under+ real games and public networks;+7. evaluation packaging followed by installer, signing, update, and recovery;+ and+8. project, dependency, H.264 patent, and distribution license decisions.++No native experiment may preserve an obsolete Screener wire, create another+room/topology model, loosen endpoint capacity, or become production merely to+make a diagnostic gate pass.++## License Boundary++Pion is MIT and coder/websocket is ISC. The Windows APIs use installed hardware+MFTs; vendor codec binaries are not redistributed. Direct NVENC would require a+separate NVIDIA Video Codec SDK and redistribution review. H.264 patent and+project licensing remain unresolved before executable distribution. No+proprietary Oopz/Agora or GPL/AGPL code was copied.++## Primary Sources++- [Windows Graphics Capture](https://learn.microsoft.com/en-us/windows/apps/develop/media-authoring-processing/screen-capture)+- [Microsoft hardware MFTs](https://learn.microsoft.com/en-us/windows/win32/medfound/hardware-mfts)+- [Microsoft H.264 encoder](https://learn.microsoft.com/en-us/windows/win32/medfound/h-264-video-encoder)+- [Microsoft `MFTEnum2`](https://learn.microsoft.com/en-us/windows/win32/api/mfapi/nf-mfapi-mftenum2)+- [Microsoft low-latency mode](https://learn.microsoft.com/en-us/windows/win32/medfound/codecapi-avlowlatencymode)+- [Microsoft force keyframe](https://learn.microsoft.com/en-us/windows/win32/medfound/codecapi-avencvideoforcekeyframe)+- [WebCodecs](https://www.w3.org/TR/webcodecs/)+- [WebRTC codec requirements, RFC 7742](https://www.rfc-editor.org/rfc/rfc7742.html)+- [H.264 RTP payload, RFC 6184](https://www.rfc-editor.org/rfc/rfc6184.html)+- [WebRTC congestion control, RFC 8836](https://www.rfc-editor.org/rfc/rfc8836.html)+- [RTP feedback, RFC 4585](https://www.rfc-editor.org/rfc/rfc4585.html)+- [RTP retransmission, RFC 4588](https://www.rfc-editor.org/rfc/rfc4588.html)+- [Pion static track fanout](https://github.com/pion/webrtc/blob/v4.2.18/track_local_static.go)+- [Pion H.264 payloader](https://github.com/pion/rtp/blob/v1.10.5/codecs/h264_packet.go)+- [libwebrtc `VideoEncoderFactory`](https://webrtc.googlesource.com/src/+/refs/heads/main/api/video_codecs/video_encoder_factory.h)+- [NVIDIA NVENC guide](https://docs.nvidia.com/video-technologies/video-codec-sdk/13.0/nvenc-video-encoder-api-prog-guide/index.html)diff --git a/docs/research/native-shared-encode-sender.md b/docs/research/native-shared-encode-sender.mddeleted file mode 100644index 8290ceb2..00000000--- a/docs/research/native-shared-encode-sender.md+++ /dev/null@@ -1,392 +0,0 @@-# Native Shared-Encode Sender--- Research date: 2026-08-19-- Scope: one Windows game-capture sender, one encoded video stream, and at most- two independent standard WebRTC media edges-- Status: stacked Draft PRs #16/#18/#22/#23/#25/#28 pass one bounded live- two-leg WebCodecs/Pion candidate, and the later Native path has one Viewer- delivery proof. Two-leg product shared encoding and release remain unproven.--## Decision Input--TeamSpeak-style shared encoding is a required later sender phase. It can remove-duplicate host encoding work, but it cannot remove the upload copy, RTP state,-or congestion control required by each outgoing edge. The first implementation-must prove one narrow property before adding capture, audio, UI, or packaging:--> Two unmodified browser viewers receive two independent WebRTC sessions while-> one physical encoder invocation produces the compatible encoded access unit-> consumed by both sessions.--The completed Pion/WebCodecs research ladder proves a narrower property: one-JavaScript `VideoEncoder` object emitted the encoded chunks consumed by two-browser sessions. WebCodecs does not expose physical encoder-instance counts,-and Chrome used `hardwareAcceleration: "no-preference"` after rejecting the-single allowed `prefer-hardware` attempt. The result therefore must not be-described as one hardware or physical encode.--The preferred first experiment is a standalone Windows C++ sender using a fixed-libwebrtc revision. It keeps libwebrtc's mature PeerConnection, RTP/RTCP, pacing,-NACK/RTX, DTLS-SRTP, and ICE behavior on each edge. Electron is not part of-the media experiment; it can only wrap a proven helper later.--## Minimal Risk Spike--```text-existing Node signaling- |-Windows sender.exe-synthetic source -> shared encoder coordinator -> encoder proxy A -> PC A -> browser A- `--------> encoder proxy B -> PC B -> browser B-```--- Windows x64, C++, video-only, fixed 720p30, and exactly two outgoing edges.-- Inject a custom `VideoEncoderFactory` into libwebrtc. It returns two proxy- encoders, one for each normal send pipeline.-- Each proxy keeps its own `EncodedImageCallback`; one coordinator owns the- physical counting encoder.-- The coordinator deduplicates matching input-frame timestamps and publishes- the same reference-counted encoded buffer to both callbacks.-- Reject the second edge when codec, profile, dimensions, or layer configuration- differ. Never hide incompatibility by creating a second physical encoder.-- For this fixed single-layer spike only, aggregate the two `SetRates()`- requests by taking the minimum total target bitrate and frame rate, bounded by- the selected profile. This is an experiment safety policy, not a product- design: one weak edge can lower a healthy edge, so productization is- forbidden. Independent quality requires another representation, an accepted- scalable design, or transcoding.-- Coalesce PLI/keyframe requests so one physical keyframe is delivered to both- packetizers. RTP sequence numbers, SSRC, TWCC, pacing, retransmission caches,- RTCP, DTLS-SRTP, and ICE remain independent per edge.--libwebrtc officially permits an application to inject a `VideoEncoderFactory`-and defines `VideoEncoder::Encode`, `SetRates`, loss/RTT notifications, and the-encoded callback. It does **not** promise cross-PeerConnection shared encoding.-The proxy/coordinator design is therefore an inference that this spike must-validate, not a supported feature claim.--Stop the libwebrtc route if two send pipelines produce incompatible cadence,-timestamps, adaptation, or callback behavior and correctness would require a-fork of `VideoStreamEncoder`, `RtpVideoSender`, or another libwebrtc internal.-Do not carry a permanent media-engine fork for this feature.--## Capture And Hardware Encoding Come Later--Only after the synthetic two-edge property passes:--1. Capture a window or display with Windows Graphics Capture into a D3D11- surface.-2. Convert BGRA to NV12 once. Do not claim zero-copy until profiling proves the- actual texture path.-3. Enumerate hardware Media Foundation H.264 encoders with `MFTEnumEx` and- `MFT_ENUM_FLAG_HARDWARE`, then probe every required input/output type and- `ICodecAPI` control. Enumeration alone is not a capability guarantee.-4. Require proven support for low-latency operation, runtime bitrate control,- and explicit keyframe requests; reject that adapter instead of silently- weakening the contract when a property is unavailable or read-only.-5. Request one H.264 Constrained Baseline, packetization-mode 1 stream, then- inspect the emitted SPS and negotiated `profile-level-id` before accepting- the path. Browser baseline interoperability does not guarantee a particular- hardware MFT or 1080p60; test every target GPU/browser combination.--Audio, per-process WASAPI capture, WGC/DDA fallback, source selection, Electron,-installers, updating, and cross-platform abstractions stay outside the first-spike.--### 2026-08-20 Windows codec comparison--The target workstation exposes an NVIDIA GeForce RTX 4070 SUPER. NVIDIA's-published NVENC contract encodes H.264, HEVC, and AV1, but not VP8. The current-Native canary instead fixes VP8 and asks WebCodecs for `prefer-hardware`; its-code removes that preference when the capability check rejects it. The prior-bounded run did reject the preferred configuration and continued with-`no-preference`. One `VideoEncoder` and its first output callback therefore do-not establish hardware encoding, and VP8 cannot use this GPU's NVENC engine.--Discord and the read-only Oopz 0.87.425 package inspection both make H.264 the-smallest Windows hardware candidate. Discord publishes native OS/driver capture-and encoding with hardware preferred and WebRTC transport. Oopz's package-contains Agora screen-share integration, WGC/DXGI/D3D11 capture components, an-H.264 Web viewer configuration, NVENC/QSV/AMF plus software codec paths, and an-observable hardware-acceleration field. The inspection found one channel screen-publication and no evidence of an application-owned per-viewer PeerConnection-loop. That is consistent with a common publication, but static packaging cannot-prove one physical encoder, the codec/profile selected for a real host, or-actual GPU use.--The bounded WebCodecs H.264 run, its no-go result, and the hardware-only Media-Foundation successor are owned by-[Native H.264 hardware decision spike](./native-h264-hardware-decision.md).-Do not recreate a codec ladder here. AV1 waits for the same physical-encode-proof and the desktop/mobile Viewer decode matrix; compression efficiency alone-cannot advance it.--Reproducibility anchors for the proprietary-package inspection, without copied-code or user data:--- Oopz `data/app.so`: SHA-256- `462E081D03E49008AD8D64A032BD6396F0B97CDADBDF715F7C6810D081A714F8`.-- Oopz screen-viewer bundle `screenShare/page/assets/index-C6S4n49C.js`:- SHA-256- `1EAECD2C0DC332E5D2628047EE1BECB874C8130C2C383355EE313961EFC6E1CA`.-- Oopz `agora_rtc_sdk.dll`: SHA-256- `66B8B34A57BA0EE9DCC6C516E2CC20F5F1EB5D35ED7150FDF37201A46BC8D4A0`.--## Pion Validation Route--Pion is the released-public-API validation route while the larger libwebrtc-encoder-proxy experiment remains unbuilt. `TrackLocalStaticSample` owns one-packetizer and writes through a `TrackLocalStaticRTP` that can bind to multiple-PeerConnections, making encoded-payload fanout explicit.--This certainty moves more responsibility into the application. Pion's default-interceptors provide NACK, RTCP reports, statistics, and transport-wide feedback,-but an external encoder still needs explicit send-side bandwidth estimation,-aggregation of both edge targets, encoder bitrate control, PLI handling, and-bounded RTP/RTX queues. The already bounded #23/#28 ladder uses the same-minimum-edge safety rule and must not invent a custom SRTP, ICE, or congestion-protocol. A product route must follow ADR-0007 instead.--## Fixed-HIGH Product-Wiring Attempt--ADR-0006 retains one narrow candidate: fixed VP8 1280x720@30 with a 3 Mbps-ceiling, one WebCodecs encoder object, at most two independent Pion legs, the-strict ordinary signaling wire, unmodified viewers, read-only feedback, and no-audio or automatic `LOW`. This is a proposed test boundary, not current product-behavior or hardware-encoder evidence.--The 2026-08-20 local delivery checkpoint rebased that candidate onto the-then-current access contract, `screener-v2`, with site-access Cookie authentication,-explicit `private-link` creation, fragment-only Viewer grants returned to the-local Host, and STUN-only ordinary ICE. Native creation alone requests a fixed-300-second provisional room. It remains random and memory-only even with SQLite-configured: the current Host session suppresses the reclaim deadline, its-generation-matched disconnect resets the five-minute window, the ordinary-transient room TTL still caps the room, and restart drops it. A pre-auth-connection or authentication failure gets one same-room/token/client-generation-retry without a second room POST. SQLite remained v2 and ordinary Web creation-was unchanged. This paragraph records only the dated candidate boundary; current-source and production are owned by [status](../status.md), executable senders are-outside the current release, and no new work is authorized against v2.-Android stop/capture-failure cleanup keeps the established signaling socket until-its single-thread teardown sends `abandon-room` and then performs a normal close;-pending-work cancellation only blocks callbacks and cancels active HTTP. No ACK-is awaited. A provisional room whose WebSocket handshake never opened remains-bounded by the existing 300-second reclaim window.-HTTP statuses, Cookie attributes, create-room responses, Host authentication,-and ignored Viewer evidence are strict and bounded; errors retain only fixed categories.-Focused Go and TypeScript checks pass. The overbroad unused framework stays-deleted. `npm run probe:native-one-viewer` is the remaining local-only, optional-Native research runner; it is not part of Web acceptance, routine full checks,-or an automatic Actions workflow.--The probe requires an explicit Chrome executable and uses a task-local Go-executable or task-specific `PATH`; neither path is committed. It retains only-bounded booleans, capped counters, and ordinal/generation identities. One frozen-signaling socket, PeerConnection/video track, bridge generation, and Pion edge-must own all positive evidence. Cleanup is fail-closed and completes bounded-process-tree exit, closed-port checks, exact system-Temp profile validation,-reparse-point rejection, and deletion before a pass can be reported. Pure tests-cover deadline expiry, cross-connection evidence, bridge replacement,-cleanup-before-pass, profile bounds, and deletion failure.--The current correctness proof is one complete Chrome 151/Windows loopback with-an in-memory room, peer assistance off, and no production or SQLite access. The-Sender produced positive decoded/source-RTP evidence without a fatal or encoder-error; one Viewer authenticated, completed offer/answer/ICE, received media, and-advanced decoded and rendered frames at 1280x720. Sampled elapsed time and an-asynchronously refreshed Pion delta are diagnostics only and do not decide the-proof. This establishes one-Viewer functional delivery, not performance,-hardware use, public-network behavior, a second Viewer, FIFO promotion,-packaging, or release acceptance.--The retained implementation advances Pion time from positive adjacent source-timestamp deltas rather than assuming `EncodedVideoChunk.duration` is present or-authoritative. Equal or decreasing timestamps fail closed. Focused timeline and-real `/media` tests cover capture jitter, decode, fanout, positive source RTP,-and bounded fatal reporting for unexpected post-config bridge closure. The-probe treats candidates before the first offer and one development-only-pre-offer control-socket replacement as the same test generation; after an-active offer, connection or bridge replacement still fails closed. WebCodecs,-Chromium remote-debugging, Windows cleanup, and pinned Pion sources were-rechecked 2026-08-20.--ADR-0006 owns the remaining staged two-Viewer, third-Viewer waiting/FIFO,-network, package, and release stop lines; this research does not redefine them.--## Stacked Validation Ladder--These Draft PRs are deliberately stacked research, not six product features:--| PR / commit | Bounded gate | Result |-| --- | --- | --- |-| [#16](https://github.com/TNTcraftHIM/Screener/pull/16) / `5b09f0a` | One Pion RTP write across two independent transports | Equivalent payload reached two transport-local SSRCs. There was no encoder or browser. |-| [#18](https://github.com/TNTcraftHIM/Screener/pull/18) / `80f65d0` | Synthetic WebCodecs VP8 chunks through Pion to two Chrome receivers | One encoder object produced 120 inputs/outputs and both browsers decoded; this was an offline fixture, not physical-encode evidence. |-| [#22](https://github.com/TNTcraftHIM/Screener/pull/22) / `8121b69` | Continuous 320x180@30 live bridge for about 12 seconds | One encoder object sent 360 chunks; each viewer decoded and presented 331 frames, with encoder/native queue peaks of one. |-| [#23](https://github.com/TNTcraftHIM/Screener/pull/23) / `eb9aabe` | Merged PLI/FIR policy, min-of-two target policy, and independent 512-packet NACK/RTX state | Policy traces passed, but stock Pion GCC plus negotiated RTX failed with `unknown ssrc: 2001`. This composition is no-go. |-| [#25](https://github.com/TNTcraftHIM/Screener/pull/25) / `a6c3456` | No-RTX primary-SSRC replay under one controlled leg loss | Leg 1 emitted one NACK and one replay with fresh TWCC, then decoded another 278 frames; leg 2 stayed clean. This can distort RTCP loss accounting. |-| [#28](https://github.com/TNTcraftHIM/Screener/pull/28) / `aad560e` | Live two-leg stock-GCC target applied to the same encoder object, then one controlled loss | The bounded gate passed. Both estimates happened to be 600 kbps, so heterogeneous-estimate behavior remains unproven. |--### Final Live Gate Evidence--The sole authorized #28 browser run used Headless Chrome 151 and Pion WebRTC-v4.2.18 on Windows amd64. It ran 1280x720@30 for 12.972 seconds with 390-scheduled inputs and 390 outputs from one `VideoEncoder` object. The encoder-queue peaked at 1/4, the native queue at 1/8, and the WebSocket buffer at-12,467/524,288 bytes; no encoder or socket drop occurred.--Both legs returned real Transport-CC before target selection. Their final stock-GCC estimates were both 600 kbps. The coordinator took the minimum, published-one 600 kbps target, and the host serialized `flush()`, `configure()` on the-same encoder object, and a forced key frame to acknowledge the change from the-initial 1.2 Mbps ceiling.--After acknowledgment, the boundary dropped one leg-1 primary packet. Chrome-sent one NACK and Pion replayed the same primary RTP identity with a new TWCC-sequence; leg 2 recorded no drop, NACK, or replay. Both viewers decoded another-359 frames after the shared recovery marker. This is a go result only for the-bounded live target plus primary-SSRC recovery candidate.--## Product Quality Direction--PR #28 establishes only that one live `VideoEncoder` object accepted one-conservative feedback-derived reconfiguration while feeding two transports. It-does not establish heterogeneous feedback behavior and must not evolve into a-room-wide minimum controller.--ADR-0007 keeps stock WebRTC GCC per direct/peer path and accepts bounded Browser-SFU `HIGH+LOW` simulcast with Dynacast and LiveKit server send-side BWE. The-exact-production gate proved its dual-encode cost; the later pinned gate proved-native LOW selection for a constrained subscriber, so the product does not-remove LOW to protect Host capacity. Application evidence remains diagnostic-and does not select routes or layers.-The Host still follows the configured non-server outbound media-copy capacity;-the two-edge result in this experiment is a historical configuration, not a-fixed policy.--The app does not derive topology eligibility from representation state. Viewer-quality requests are authenticated, rate-limited, deduplicated diagnostic advice-and do not form a composite score. UA and device identity do not participate.--A native relay forwards the selected encoded packets and must not decode or-re-encode them. An ordinary non-scalable representation cannot be forwarded-into a second quality; doing so would require another encode, scalable layers,-or transcoding. ADR-0007 closes current Web P2P shared simulcast and Web/LiveKit-SVC, while accepting Browser SFU `HIGH+LOW` through LiveKit. A future native-decision may implement those representations only with an explicit hardware-contract, bounded layer count, one encoded output reused across accepted-transports, independent path selection, and the real game/power matrix. Media-Capabilities and RTCStats power-efficiency fields remain diagnostics, not-hardware proof.--Simulcast does not change this native proof boundary: one sender may negotiate-multiple representations, but separate direct PeerConnections have no portable-shared-encode contract and inactive API state is not physical resource proof.-ADR-0007 and-[Realtime Quality Adaptation](./realtime-quality-adaptation.md) own the-static standard-path results and any future native reopen gate. This path still-requires measured per-representation traffic/resources and cannot bypass #28's-stock-GCC/RTX stop line.--## 2026-08-21 Evaluation Packaging Boundary--The current source now has one Windows x64 evaluation-package path. It reuses-the existing Go build and MSVC helper build, places the two executables beside-each other, embeds the exact Git revision, adds an internal `SHA256SUMS.txt`,-and publishes the ZIP with an adjacent SHA-256 file.-`screener-sender.exe --version` is the non-interactive package smoke. This does not add an installer,-Electron, auto-update, signing, a bundled server, codec matrix, or release.--The manual-only workflow uses the official `windows-latest` image, whose current-manifest includes VSWhere, the x64 Visual C++ tools, and Windows 11 SDK, and the-official immutable `actions/upload-artifact@v7` path with missing-file failure,-zero second-stage compression for the precompressed ZIP, and seven-day-retention. It has no push or pull-request trigger and is dispatched only at an-explicitly authorized Native release-package boundary; it is not a Web-acceptance gate. GitHub requires authentication to download the resulting-artifact. Sources were checked 2026-08-21.--The linked-binary audit covers 23 modules: coder/websocket is ISC; the 16 Pion-modules are MIT; google/uuid, wlynxg/anet, and the four `golang.org/x` modules-are BSD-style. Every linked module exposes a recognized root license file. The-packager derives the list from `go list -deps`, copies those exact files plus-the Go toolchain license, and fails if a linked module has no license file. No-GPL/AGPL reference or proprietary Oopz code enters the package.--The project distribution license remains undecided. The Actions artifact is-therefore labeled evaluation-only and grants no project redistribution right;-GitHub Release publication remains blocked on the license decision. This-bounded trial artifact does not change ADR-0006's product No-Go status.--## Product Stop Line--The stock Pion GCC plus negotiated RFC 4588 RTX composition is-`no-go-stock-pion-gcc-rtx`; do not work around it with a custom pacer,-congestion controller, interceptor fork, or private transport. The no-RTX-primary-SSRC path stays research-only because it sacrifices retransmission--specific receiver statistics and can distort RTP/RTCP loss accounting.--No stacked PR is connected to Screener's product path, capture path, or-audio path. Before product consideration, a target native sender must still-prove one physical encoder invocation on representative hardware, live-PLI/FIR-to-encoder control, heterogeneous downstream estimates, bounded burst-and sustained loss, audio/A-V synchronization, reconnect isolation, browser-diversity, lifecycle, and sustained CPU/GPU,-memory, latency, quality, and upload measurements. A third host edge, custom-RTP/SRTP, or a custom congestion-control framework remains out of scope. The-#28 minimum-of-two policy is also out of scope for product code; retaining its-evidence does not retain its policy. Ordinary Web and Native peer ICE stays-STUN-only. The sole application fallback remains ADR-0005's Host publication-with exact SFU/UDP subscriptions; Native research adds no transport candidate.--## Primary Sources And License Boundary--- [libwebrtc PeerConnection factory injection](https://webrtc.googlesource.com/src/+/refs/heads/main/api/create_peerconnection_factory.h)-- [libwebrtc VideoEncoder API](https://webrtc.googlesource.com/src/+/refs/heads/main/api/video_codecs/video_encoder.h)-- [libwebrtc license](https://webrtc.googlesource.com/src/+/refs/heads/main/LICENSE)- and [PATENTS](https://webrtc.googlesource.com/src/+/refs/heads/main/PATENTS)-- [Windows Graphics Capture](https://learn.microsoft.com/en-us/windows/apps/develop/media-authoring-processing/screen-capture)-- [Media Foundation `MFTEnumEx`](https://learn.microsoft.com/en-us/windows/win32/api/mfapi/nf-mfapi-mftenumex)-- [Media Foundation `ICodecAPI::IsSupported`](https://learn.microsoft.com/en-us/windows/win32/api/icodecapi/nf-icodecapi-icodecapi-issupported)- and [`IsModifiable`](https://learn.microsoft.com/en-us/windows/win32/api/icodecapi/nf-icodecapi-icodecapi-ismodifiable)-- [Media Foundation H.264 encoder](https://learn.microsoft.com/en-us/windows/win32/medfound/h-264-video-encoder)-- [Media Foundation low-latency codec property](https://learn.microsoft.com/en-us/windows/win32/medfound/codecapi-avlowlatencymode)-- [Media Foundation force-keyframe property](https://learn.microsoft.com/en-us/windows/win32/medfound/codecapi-avencvideoforcekeyframe)-- [WebRTC video codec requirements, RFC 7742](https://www.rfc-editor.org/rfc/rfc7742.html)-- [WebRTC congestion control requirements, RFC 8836](https://www.rfc-editor.org/rfc/rfc8836.html)-- [Pion track fanout implementation](https://github.com/pion/webrtc/blob/main/track_local_static.go)-- [Pion v4.2.18 pinned track implementation](https://github.com/pion/webrtc/blob/v4.2.18/track_local_static.go)-- [Pion send-side bandwidth estimator](https://github.com/pion/interceptor/blob/main/pkg/gcc/send_side_bwe.go)-- [Pion WebRTC license](https://github.com/pion/webrtc/blob/main/LICENSE)-- [WebCodecs](https://www.w3.org/TR/webcodecs/)-- [NVIDIA NVENC application note](https://docs.nvidia.com/video-technologies/video-codec-sdk/13.1/nvenc-application-note/index.html)-- [Agora Windows screen sharing](https://doc.shengwang.cn/doc/rtc/windows/basic-features/screen-share)-- [Agora Windows encoding preference](https://doc.shengwang.cn/api-ref/rtc/windows/API/enum_encodingpreference)-- [Oopz help center](https://help.oopz.cn/)-- [W3C WebRTC Statistics](https://www.w3.org/TR/webrtc-stats/)-- [W3C WebRTC SVC](https://www.w3.org/TR/webrtc-svc/)-- [W3C Media Capabilities](https://www.w3.org/TR/media-capabilities/)-- [W3C WebRTC simulcast](https://www.w3.org/TR/webrtc/#simulcast-functionality)-- [Pion WebRTC v4.2.18](https://github.com/pion/webrtc/tree/v4.2.18)-- [Pion Interceptor v0.1.47](https://github.com/pion/interceptor/tree/v0.1.47)-- [Chromium Chrome test switches](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/chrome/common/chrome_switches.cc)-- [Chrome remote-debugging profile requirement](https://developer.chrome.com/blog/remote-debugging-port)-- [Microsoft `taskkill`](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/taskkill)-- [Microsoft `FileAttributes.ReparsePoint`](https://learn.microsoft.com/en-us/dotnet/api/system.io.fileattributes?view=net-10.0)-- [RFC 4585 RTP/AVPF feedback](https://www.rfc-editor.org/rfc/rfc4585.html)-- [RFC 4588 RTP retransmission](https://www.rfc-editor.org/rfc/rfc4588.html)-- [RFC 8888 congestion-control feedback](https://www.rfc-editor.org/rfc/rfc8888.html)-- [Electron desktop capture](https://www.electronjs.org/docs/latest/api/desktop-capturer/)-- [libwebrtc license](https://webrtc.googlesource.com/src/+/refs/heads/main/LICENSE)-- [GitHub Actions artifact upload](https://github.com/actions/upload-artifact)-- [GitHub Windows 2025 runner image](https://github.com/actions/runner-images/blob/main/images/windows/Windows2025-Readme.md)-- [PowerShell `Compress-Archive`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.archive/compress-archive)-- [Go license](https://go.dev/LICENSE)--The current Go candidate directly uses Pion (MIT) and coder/websocket (ISC).-The evaluation package generates and verifies notices for the Go runtime and-all linked direct/transitive dependencies. Choose the project license before a-formal release or redistribution grant.-libwebrtc/H.264 remains a separate future route requiring its own third-party-notice and patent/licensing review. No source code from these projects was-copied into Screener.diff --git a/docs/research/peer-assisted-media.md b/docs/research/peer-assisted-media.mdindex 4c97020a..dbc46912 100644--- a/docs/research/peer-assisted-media.md+++ b/docs/research/peer-assisted-media.md@@ -1,541 +1,183 @@-# Peer-Assisted Media Research+# Browser Peer Relay Evidence- Research date: 2026-08-22-- Scope: one game-screen broadcaster and an accepted admission target of twenty- trusted viewers; exact v10 direct-loopback evidence reaches twenty and the- earlier resource/quality gate remains eight-- Status: historical evidence plus the bounded controller. Exact Browser v10- source `fdd5a4a529ff297f41c05ea3388bf484d76afe8f` remains the dated local- direct-loopback implementation evidence. Current source and production are- indexed by [status](../status.md) and follow ADR-0005. A historical v8 canary- decoded SFU media. Heterogeneous-network, mobile, resource, and endurance- evidence remains open.--This document owns dated measurements and implementation evidence. Current-capacity and routing authority live in [ADR-0005](../adr/0005-automatic-hybrid-media-routing.md)-and [project memory](../project-memory.md).+- Status: retained Browser relay capability and measurement evidence-## Conclusion+Current product behavior is owned by+[Routing and transport](../product/routing-transport.md). Controller and+capacity decisions are owned by+[ADR-0005](../adr/0005-automatic-hybrid-media-routing.md). This document does+not define route selection, wire messages, UI, or current deployment state.-Peer-assisted forwarding can reduce broadcaster fanout without making an SFU-carry every viewer's traffic. The release measurements below are historical-evidence rather than current capacity policy. The accepted path uses standard-WebRTC media, one active upstream per Viewer, a bounded acyclic peer graph, and-one uniform non-server outbound capacity `C` configured as `1`, `2`, or `3`.-Host publication and peer children consume physical sender slots under-ADR-0005; SFU server resources use separate admission.--This path reuses WebRTC capture, codec negotiation, RTP, NACK/PLI/RTX, congestion-control, jitter buffering, ICE, STUN, DTLS-SRTP, and browser rendering. Ordinary-peer edges are STUN-only; direct exhaustion may instead select the dedicated-SFU/UDP path. The peer-relay 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 accepted controller preserves healthy direct/peer UDP edges. One Host-publication and per-Viewer SFU subscriptions provide server-fed ingress when selected by the-same bounded controller. Direct P2P remains the-simplest path while a healthy endpoint sender slot is available; later Viewers-may be assigned to peers automatically. ADR-0005 makes SFU capacity part of the flagship-target while retaining peer descendants. The historical v8 production rollout-used a room-`1` exact smoke and observed only participant entry, then removed-that room boundary. A controlled v8 canary subsequently committed two SFU-assignments and decoded 1920x1080 video. That does not close the real-network or-resource matrix.--## 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 two children has two independent outbound senders.--Sources:+## Conclusion-- [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)--### Server Authority And Ordinary Capacity--The WebRTC 1.0 sender model associates transmission with an individual-`RTCRtpSender`; it does not turn a client-declared fanout value into server-authority. Pion's maintained `TrackLocalStaticRTP` similarly maintains multiple-bindings and writes a packet per bound downstream context. These sources support-counting each physical downstream sender/edge, including an overlapping-provisional or selected replacement, rather than treating a logical route as one-upload. OWASP's server-side input-validation guidance treats client input as-untrusted and requires semantic validation in the trusted service.--The resulting Screener policy is an engineering inference: authenticate the-session first, then let the server apply one ordinary downstream capacity to-every non-server endpoint. The default is two and a deployment may choose one,-two, or three. Upstream receive is free; role, UA, visibility, and client-advertisement cannot raise or create another tier. A client-side clamp can limit-damage from a server regression, but does not replace authenticated server-authority. Assisted transport and temporary-overlap accounting are separate-routing questions and are not defined by this resource observation.--Sources, accessed 2026-08-22:--- [W3C WebRTC 1.0 Recommendation](https://www.w3.org/TR/webrtc/)-- [OWASP Input Validation Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html)-- [Pion `TrackLocalStaticRTP` bindings](https://github.com/pion/webrtc/blob/main/track_local_static.go)--### 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 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 browser-relay gate. The separate-native shared-encode sender described in `low-server-media-routes.md` is planned-independently and requires its own ADR and measurements.--Sources:+A normal Browser can receive a remote WebRTC video track and add it to another+`RTCPeerConnection`. This is the compatibility-first peer relay path and can+distribute Host upload across participating Viewers.++It is not encoded forwarding. The remote track exposes decoded frames, and+each downstream `RTCRtpSender` owns another WebRTC send stream and encoder.+The safe resource model is therefore:++- every relay hop decodes and re-encodes video;+- every child is another outbound media copy and network flow;+- repeated encoding can add CPU/GPU work, latency, and generational loss; and+- peer assistance distributes aggregate traffic but does not eliminate it.++Local Chrome controls proved that bounded Browser relays can forward media to+multiple descendants. They did not prove shared encoding, game readability,+public-network quality, mobile relay survival, or endurance.++## Standard Browser Relay++WebRTC permits one `MediaStreamTrack` to be sent by multiple+`RTCRtpSender` objects, but it does not promise a shared encoder. Current+libwebrtc constructs a `VideoSendStream` and `VideoStreamEncoder` for each send+stream. A product must assume one encoder pipeline per sender even if a Browser,+driver, or GPU happens to optimize a particular run.++A remote video track enters the receiver as decoded `VideoFrame` data. Adding+that track to a downstream connection feeds raw frames into a new sender and+encoder. A relay with two children therefore has two independent outbound+senders in addition to its upstream receiver.++Cloning the track or using `VideoTrackGenerator` may share capture or raw-frame+processing. Neither API shares the encoded bitstream or the downstream RTP,+congestion-control, keyframe, retransmission, and encryption state.++## Why Browser APIs Do Not Provide Shared Encode++### Encoded Transform++WebRTC Encoded Transform sits after a sender encoder or after a receiver+depacketizer. Its frame ownership rules do not permit moving an encoded frame+from one transform source into another sender's RTP pipeline. Replacing bytes+in dummy frames would still run the second encoder and would couple unrelated+codec metadata, cadence, dependency, and keyframe state. That is not a+supported encoded-frame tee.++### WebCodecs And DataChannel++WebCodecs can produce `EncodedVideoChunk` values but supplies neither a media+transport nor a bridge into `RTCRtpSender`. Sending chunks over DataChannel+would require an application media protocol for at least:++- stream and source generations;+- frame identity, timestamp, duration, type, and codec configuration;+- fragmentation, bounded reassembly, and queue limits;+- keyframe requests and decoder reset; and+- loss, late-frame, unsupported-codec, and reconnect behavior.++DataChannel retains ICE, DTLS, SCTP, and association congestion control, but it+does not provide WebRTC video RTP/RTCP behavior. RFC 8831 also warns that large+messages can monopolize an association when message interleaving is absent and+recommends limiting messages to 16 KB in that case. This is a custom media+plane, not a smaller form of standard Browser relay.++### Native Shared Encode++A native sender may provide an application `VideoEncoderFactory` and coordinate+multiple RTP senders around one hardware encoder. That possibility is outside+Browser JavaScript and is not a ready-made libwebrtc feature. It must reconcile+independent bitrate and keyframe requests, timestamps, codec/profile settings,+and downstream congestion state. It can reduce encode work, but it cannot+remove the network copy required for each child.++## Retained Measurements++All measurements below used synthetic local media and Chrome 151. They are+control and cost evidence, not current product policy or public-network+acceptance.++### Bounded Forwarding++- A 2026-08-21 capacity-two run used one Host and five Viewers at synthetic+ 720p30. Host and relay fanout peaked at two. One Viewer served two children;+ each child advanced by 80 decoded frames and about 1.1 MB. All five Viewers+ decoded and cleanup reported no fatal error.+- Exact Browser v10 source+ `fdd5a4a529ff297f41c05ea3388bf484d76afe8f` reached twenty Viewers in a local+ direct-loopback control. That run proves the bounded control and decoded-media+ path only; it does not close resource or quality acceptance.+- A three-Viewer rerun at source `b77f4eb58944` moved a descendant after its+ first-level relay closed and resumed decoded-frame progress in 5,380 ms. The+ Host remained within two outbound media edges.++### Quality And Resource Limits++- The three-Viewer rerun requested 1280x720 at 30 fps, but final samples were+ 320x180 at roughly 9-11 fps. Successful forwarding did not imply the requested+ quality.+- Two-second, sixteen-Viewer loopbacks completed without a fatal check for both+ historical cap-two and cap-three arms. Cap two reached depth four with a+ 1,167 ms maximum first-decode diagnostic; cap three reached depth three with+ 977 ms. Final samples were only 320x180 at 9-10 fps.+- Ten-second, sixteen-Viewer follow-ups observed 320x180 or 480x270. Cap two+ measured Host/relay bitrate 1,716/1,748 kbps, 11.17/11.20 fps, and+ 2.086/2.048 ms encode time per frame. Cap three measured 1,589/1,638 kbps,+ 10.83/10.87 fps, and 2.071/2.126 ms per frame. Every Host limitation sample+ was `bandwidth`; relay samples were `none`.+- Aggregate Chromium CPU was 221.4% for cap two and 209.8% for cap three, with+ peaks of 250.7% and 246.9%. The arms had different valid interval coverage,+ the runs were short, and CDP could not attribute the totals to an individual+ Host or relay page. These values cannot rank the two capacity settings or+ establish a resource ceiling.++The retained negative evidence is as important as successful decode: local+fanout worked, while requested resolution and frame rate were not sustained and+resource attribution remained incomplete. Real games, weaker devices,+heterogeneous networks, long runs, A/V behavior, and mobile lifecycle remain+unproved.++## Resource Consequences++For observed encoded bitrate `B`, `N` Viewers, and `C` ordinary children on one+parent:++- that parent sends approximately `C * B` plus transport overhead;+- aggregate delivery remains approximately `N * B` across all parents and any+ server-assisted paths; and+- every Browser relay also pays receive/decode plus per-child encode cost.++This is traffic conservation, not a capacity recommendation. Current endpoint+and server admission are defined only by the product contract and ADR-0005.-- [WebCodecs](https://www.w3.org/TR/webcodecs/)-- [WebRTC Data Channels, RFC 8831](https://www.rfc-editor.org/rfc/rfc8831.html)+## Compatibility Boundary-## Native TeamSpeak-Style Shared Encoding+The standard relay uses broadly implemented WebRTC track and sender APIs. It+does not require Encoded Transform, WebCodecs, or+`MediaStreamTrackProcessor`.-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.+The 2026-08-22 browser-compatibility snapshot showed why the custom encoded+alternative has a narrower surface: `RTCRtpScriptTransform` and `VideoDecoder`+availability varied by Browser/version, and `MediaStreamTrackProcessor` was+still missing or partial in important targets. API presence also does not prove+support for the exact codec, profile, resolution, or hardware path; runtime+configuration checks and media evidence would still be required.-A candidate native Screener sender could preserve standard browser receivers-without writing a new transport. libwebrtc accepts an application-supplied-`VideoEncoderFactory`, which creates a possible boundary for per-stream proxy-encoders backed by one shared hardware encoder. If the bounded spike proves the-callback and adaptation contract, libwebrtc could retain independent RTP-sequence numbers, packetization, SRTP, RTCP, NACK/RTX, ICE, and congestion state-for the two host edges.+## License Boundary-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. The separate bounded risk-spike must prove whether this route can guarantee one host encode while keeping-normal browser first-hop receivers; requiring a libwebrtc internal fork rejects-the route. Browser JavaScript cannot provide that guarantee.+This research uses W3C/IETF specifications, BSD-licensed libwebrtc source,+public browser-compatibility data, and an official TeamSpeak technical+statement. No GPL/AGPL implementation code was copied. GPL/AGPL projects remain+study-only until the repository license and distribution model are decided.-Sources:+## Primary Sources-- [TeamSpeak single-encoding explanation](https://community.teamspeak.com/t/ts6-beta-community-update-insights/58116/208)+- [WebRTC 1.0](https://www.w3.org/TR/webrtc/)+- [Media Capture and Streams](https://w3c.github.io/mediacapture-main/)+- [Media Capture Transform](https://w3c.github.io/mediacapture-transform/)+- [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 engine](https://webrtc.googlesource.com/src/+/refs/heads/main/media/engine/webrtc_video_engine.cc)+- [libwebrtc video send stream](https://webrtc.googlesource.com/src/+/refs/heads/main/video/video_send_stream_impl.cc)+- [libwebrtc video RTP receiver](https://webrtc.googlesource.com/src/+/refs/heads/main/pc/video_rtp_receiver.cc)- [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 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- framework connection rebuild does not change the logical edge count.--- the historical experiment gave the host and every ordinary Web viewer capacity- for at most two children;-- that experiment's endpoint child count was a hard invariant and never exceeded 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;-- 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, 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 the-direct stage is exhausted, the same controller may select the room's single Host-publication and an exact SFU/UDP subscription. Peer assistance therefore reduces-normal server media traffic but cannot promise zero server traffic in restrictive-networks.--## Implemented Bounded Quality Coordination--The implementation coordinates one strict `QualitySettings` object across the-peer-assisted tree without adaptation logic. Current source and production accept advanced-480p/720p/1080p/1440p resolution values, 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, and `480p` is only the advanced 854x480 resolution. The-server stores the latest complete object in a room-count-bounded in-memory map,-defaults to 1080p30 at 5 Mbps with balanced priority, includes it in-peer-assisted authenticated snapshots, and broadcasts Host changes to online-Viewers. Production uses the same 1080p30 default and advanced 480p boundary.-The value survives a stopped share, is removed with-the room, and is not persisted.-Ordinary P2P authentication remains unchanged and-setting-control messages are forbidden in that mode.--After peer-assisted authentication, the host reasserts its local selection-before reconciling assigned children. A viewer records the snapshot or update-before applying its assignment. `ViewerRelay` keeps a synchronously updated-desired setting and serializes setting changes with stream replacement, so both-an existing child and a later replacement start from the latest target. Inside-`HostPeer`, initial sender configuration, stream replacement, and setting-updates share one mutation queue; operations read the latest desired setting at-execution time, giving rapid changes last-wins behavior without versions or-acknowledgements.--If the host changes quality while signaling cannot accept the room update, its-current local senders still apply the setting but the UI reports that room sync-is waiting for reconnect. The next successful host authentication reasserts the-latest object; no acknowledgement state machine is added.--The configured SFU publisher follows the same boundary: first publication,-successful track replacement, and live setting changes all configure the real-`RTCRtpSender`, then retain requested/applied bitrate, frame rate, scale, and-preference. Configuration rejection uses the existing rollback/fail-closed-path rather than silently leaving the publication on unverified parameters.-After initial activation or source replacement settles, the host reads and-shows the route warning; a successful replacement rollback retains the original-failure instead of clearing it with the restored sender readback.--This only removes the previous fixed-1080p60 relay envelope. Browser constraints-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.--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;-and every viewer's decoded-frame and `requestVideoFrameCallback` counters grew-after each change. The harness brought each viewer page to the foreground for-its render check because Chrome throttles background frame callbacks. Host-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-22 release-checkpoint rerun at exact source `b77f4eb58944` used Chrome-151.0.7922.138, three Viewers, the Host2/ordinary Browser Viewer1 policy, an-eight-second sample window, and the existing hard-departure recovery gate. All-three Viewers decoded; Host media fanout peaked at two, Browser relay fanout at-one, and no SFU publication appeared. Closing the first-level relay page moved-its affected descendant and resumed advancing frames in 5,380 ms while the Host-remained within two media edges. The requested synthetic source was 1280x720 at-30 fps, but observed final samples remained 320x180 at roughly 9-11 fps. This is-real local `RTCPeerConnection` media and hard-participant-departure evidence. It-does not exercise decoded-frame-stall recovery or provisional MBB, a silent-socket partition, SFU, TURN, a public network, game capture, or resource quality.--A 2026-08-22 opt-in `BENCHMARK_CANARY=viewer-mbb` run on the same Chrome build-used one Host and three Viewers. It observed a real provisional-`RTCPeerConnection` retain the old edge, promote the candidate, preserve the-connection identity, and continue decoded-frame progress within the ordinary-edge cap. This is reusable make-before-break control evidence only; its-synthetic trigger is not route policy or heterogeneous-network 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.--The historical loopback runner used cap2 by default;-`BENCHMARK_EXPECTED_ENDPOINT_CAP=3` configured only its local server and gate.-That source checkpoint later rejected cap3 in its release-policy mode.-A 2026-08-22 Chrome 151 two-second-smoke passed with three Viewers at Host2/relay1 and six at Host3/relay3, with all-Viewers decoding. This was an experimental control-path result, not a-release-policy, production-default, SFU-capacity, or resource claim.--The following cap2/cap3 results are retained historical experiments and do not-select product policy. A 2026-08-22 Windows-Chrome 151.0.7922.138 headless loopback ran sixteen-Viewers for two seconds at 720p30 with cap2 and cap3. Both runs had all sixteen-Viewers decoding and no fatal/check failure. Cap2 peaked at Host2/relay2 with-depth four and a 1,167 ms maximum first-decode diagnostic; cap3 peaked at-Host3/relay3 with depth three and 977 ms. Final samples were only 320x180 at-9-10 fps. The 8-core/16-thread Ryzen 7 9700X runner had 47.1 GiB RAM and 13.7-GiB free after the runs, but no process CPU, GPU, NIC, or peak-memory totals were-captured. This proves the explicit admission, bounded topology, and decode paths-only; resource, visual quality, endurance, heterogeneous networks, and larger-room-acceptance remain open.--A same-machine 2026-08-22 Chrome 151 follow-up ran sixteen Viewers for ten seconds at 720p30 and introduced report schema v2; sender means are unweighted connected sender-sample means, while encode cost is weighted by guarded interval frame deltas.-Cap2 passed at Host2/relay2 with 2 Host and 14 relay senders: Host/relay bitrate was 1,716/1,748 kbps, FPS 11.17/11.20, available outgoing 5,393/5,704 kbps, and encode cost 2.086/2.048 ms per frame.-Cap3 passed at Host3/relay3 with 3 Host and 13 relay senders: the same fields were 1,589/1,638 kbps, 10.83/10.87 FPS, 5,474/5,956 kbps, and 2.071/2.126 ms per frame.-Both runs observed only 320x180 and 480x270; every Host limitation sample was `bandwidth`, every relay sample was `none`, and maximum first-decode diagnostics were 1,071/1,021 ms for cap2/cap3.-[CDP `SystemInfo.getProcessInfo`](https://chromedevtools.github.io/devtools-protocol/tot/SystemInfo/) exposes process type, PID, and cumulative CPU seconds, but no resident-set field; v2 therefore reports peak RSS as `null` and rejects intervals when the exact type/PID set changes or any counter retreats.-Cap2 measured 221.4% aggregate Chromium CPU (250.7% peak) over two valid and three rejected intervals; cap3 measured 209.8% (246.9% peak) over four valid and one rejected interval. Multicore totals may exceed 100%.-The different valid coverage and one short run per arm forbid a cap2/cap3 CPU ranking. CDP cannot attribute these all-process totals to an individual Host or relay page, and this ordinary-PC synthetic run does not close resource, game-quality, endurance, mobile, or larger-room acceptance.--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:-+- [libwebrtc `VideoEncoder`](https://webrtc.googlesource.com/src/+/refs/heads/main/api/video_codecs/video_encoder.h)+- [libwebrtc license](https://webrtc.googlesource.com/src/+/refs/heads/main/LICENSE)+- [TeamSpeak single-encoding explanation](https://community.teamspeak.com/t/ts6-beta-community-update-insights/58116/208)- [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, and configured ordinary-downstream capacity `C`:--- each non-server parent has at most approximately `C * B` ordinary downstream- upload, plus transport overhead;-- aggregate viewer delivery still requires approximately `N * B` across hosts,- relays, and SFU paths; and-- signaling/STUN carry negligible media traffic, while an SFU path incurs- bounded publication ingress and subscription egress.--Peer assistance distributes traffic; it does not eliminate it. The product-keeps topology automatic and invisible while the server enforces the configured-capacity. The standalone ADR-0004 spike relied on controlled join order; the-ADR-0005 controller starts each Viewer at zero and waits for an authenticated-capacity message. There is no mobile/iPad, UA, or visibility capacity branch.--## Selected-Pair Resolution--`RTCTransportStats.selectedCandidatePairId` identifies the current-`RTCIceCandidatePairStats` used for path, candidate, and round-trip metrics. When-that exact reference is absent, a fallback is valid only if exactly one-same-transport succeeded nominated or selected pair exists; an ambiguous or-broken relationship remains unknown.--`responsesReceived` is a cumulative connectivity-check response counter, not a-media-health signal. RFC 7675 consent checks normally occur less often than the-application stats sampler, so a zero interval does not prove a silent partition,-while growth does not prove media quality or future reachability. Screener does-not expose or route on this counter, and the accepted Browser contract does not-retain it or a derived sampling window.--Sources, accessed 2026-08-22:--- [W3C Identifiers for WebRTC's Statistics API](https://www.w3.org/TR/webrtc-stats/)-- [RFC 7675, Consent Freshness for WebRTC](https://www.rfc-editor.org/rfc/rfc7675.html)--## Bounded Spike And Gates--This historical gate assumed default-off configuration through-`PEER_ASSISTED_MEDIA=false`; current production enables the controller for all-rooms.-It uses the existing standard WebRTC screen stream, current Chrome/Edge as the-controlled relay cohort, Android Chrome and iOS Safari as compatibility-observations, and the configured downstream edge cap. The runner must accept the-shared room admission ceiling of twenty; the current retained run reaches-sixteen while the representative resource/quality gate remains at eight. 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-historical browser-relay gate.--Run 1, 3, 5, and 8 viewers for 30 minutes across the three recommended ceiling-combinations, plus any advanced combination proposed for production, 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.--The in-app per-frame encode/decode fields use adjacent `getStats()` counter-deltas and skip a tick while the same connection already has a sample in-flight. A first sample, zero-frame interval, changed stats object, or counter-reset reports unknown and rebases; a connection-lifetime average is not-accepted as relay-load evidence. Long-run percentiles and event timing still-come from a tracked run manifest plus browser WebRTC diagnostics, not a new-telemetry service.--All hard gates must pass:--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- encode time, CPU/GPU cost, and `qualityLimitationReason` are recorded rather- than mislabeled as shared encoding.-3. Under that dated gate, excluding its 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-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- 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 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-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. The separate planned native-shared-encode sender still requires its own ADR, lowers encode work rather than-per-edge upload, and cannot rescue other failed browser-relay gates. A rejected-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; historical v8-production first ran a room-`1` smoke and later removed that rollout boundary. A-controlled v8 canary decoded two SFU assignments; heterogeneous-network,-resource, 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.--## Browser Signaling Silent-Partition Detection--The recovery gate above does not cover a browser WebSocket that remains open-locally after its network path has silently failed. The server's default-30-second protocol heartbeat can take 30 to 60 seconds to observe that failure,-and browser script cannot observe WebSocket Ping or Pong control frames. The-[WHATWG WebSockets Living Standard](https://websockets.spec.whatwg.org/)-(accessed 2026-08-22) exposes messages, generic error/close events, and-`readyState`; it also specifies that constructing a WebSocket immediately-starts a new connection while `close()` starts a closing handshake whose close-event arrives later. The application therefore needs a small text-message-challenge rather than waiting for either protocol Ping/Pong or the old socket's-close event.--Production sends-`signaling-challenge { sequence }`, and the server sends the exact-`signaling-challenge-response { sequence }` only to that requesting socket.-Server and Browser assets deploy atomically; stale Browser and executable-sender-wires fail before room authority, with no compatibility parser or response seam.--The Web watchdog is eligible only while the current socket is authenticated,-the share is online, and the endpoint has an active authoritative route (the-Host itself, an ordinary Viewer with an online Host, or a peer-assisted Viewer-whose active upstream is not `none`). After five seconds it sends one-challenge. An exact two-second miss enters an internal suspect state and sends-one fresh confirm challenge; an exact second two-second miss logically retires-that socket generation and immediately constructs a replacement without-waiting for the old closing handshake. Responses from another sequence or-socket generation are ignored, and the server revalidates the current-authenticated session before replying. A hidden document, a visibility-restore, or an obviously late timer callback clears pending evidence and starts-a fresh five-second baseline instead of declaring failure.-This response-only watchdog is deployed in production and remains limited to-authenticated, visible sessions with an active authoritative route. Hidden or-background lifecycle is rebaselined rather than treated as failure; the watchdog-does not provide page or media keepalive. Mobile background behavior remains a-separate physical-device evidence boundary.--The response is socket-local, contains no room state, secret, candidate, or raw-statistics, is not logged, and is limited by the server to at most one response-per socket per second. The watchdog itself does not close or rebuild media,-emit `route-failed`, or change route authority. Ordinary P2P and a duplicate-same-revision SFU authority keep their healthy media while the new socket-reauthenticates. The watchdog does not create or carry media-transport-authority; route and SFU lifecycle remain owned by ADR-0005.--## 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.+- [CDP `SystemInfo.getProcessInfo`](https://chromedevtools.github.io/devtools-protocol/tot/SystemInfo/)diff --git a/docs/research/realtime-quality-adaptation.md b/docs/research/realtime-quality-adaptation.mdindex 29a8b4cd..1cc3d6f3 100644--- a/docs/research/realtime-quality-adaptation.md+++ b/docs/research/realtime-quality-adaptation.md@@ -1,593 +1,227 @@-# Realtime Screen-Share Quality Adaptation--- Research date: 2026-08-26-- Scope: Browser game-screen capture, encoding, P2P forwarding, and LiveKit SFU-- Status: strict-v13 evidence-only quality shadow deployed; production sampling- and active policy remain open--## Current Conclusion--Current production and canonical source use a content-independent H.264 sender-gate with VP8 fallback. The local pre-share Host `VP8 | Auto | H264` selector is-implemented and Viewer relays remain automatic.-Display video uses `contentHint = "motion"`, and display audio uses-`contentHint = "music"`. The three recommended profiles and advanced settings-are ceilings, not delivery guarantees. WebRTC owns direct and peer congestion-control; LiveKit owns SFU representations, Dynacast, subscriber bandwidth-estimation, and layer forwarding.--On current Windows Chrome, Browser WebRTC VP8 is a software path. Chromium 151's-Windows hardware encoder backends do not enumerate VP8, and the measured Edge-151 binary likewise showed no VideoEncode activity. The Web page cannot select a-GPU encoder or vendor API. This is a platform boundary, not a missing Screener-setting. Real-game contention remains open because software encoding competes-with the game for CPU even when encode time is below the frame budget.--Screener does not define a resolution/FPS/bitrate ladder, custom SFU lower-representation, scene detector, quality score, parent probe, periodic-rebalancing loop, or manual layer selector. It supplies standard content intent,-the selected sender ceiling, and readback of what the browser accepted.--The active topology remains availability-driven. A hard connection failure,-non-paused 15-second decoded-frame stall, parent departure, or capacity-invalidation may trigger the ADR-0005 recovery operation. Loss, RTT, jitter,-bitrate, resolution, FPS, freeze counters, codec, and limitation reason are-diagnostic and cannot prove that another parent would be better.--## Browser VP8 Evidence--Chrome 151 exact-production tests with real `getDisplayMedia()` showed that-direct and Browser-relay VP8 can sustain about 60 fps after the stock bandwidth-estimator warms up. The observed ramp took roughly 25 to 30 seconds; a configured-60 fps or bitrate remains a ceiling rather than a startup promise.--One controlled no-hint/motion comparison showed that Chromium may preserve-motion by spatially downscaling when `motion` is set. That is the standard-content-hint tradeoff for games, not a minimum-resolution contract. Leaving the-hint unset can preserve screen-classified resolution while shifting pressure to-quantization or frame delivery, so the earlier no-hint improvement was not free-adaptation. Current policy follows the standard game-motion intent and leaves-the resulting tradeoff to the browser.--### Windows Browser Hardware Boundary--Chromium `151.0.7922.174` constructs a hardware WebRTC encoder only when the-platform Video Encode Accelerator advertises the negotiated profile. Its-Windows Media Foundation backend enumerates H.264, VP9, AV1, and optional HEVC,-but not VP8; the Windows D3D12 backend likewise has no VP8 encoder. Libwebrtc's-VP8 implementation is `libvpx` and reports `is_hardware_accelerated = false`.-`setCodecPreferences()` can select VP8 but cannot choose NVENC, AMF, QSV, a GPU,-or an MFT. Media Capabilities is only a capability query and cannot prove the-encoder actually used by an exact PeerConnection.--Headful, isolated Chromium loopbacks on the current Ryzen 7 9700X / RTX 4070-SUPER machine used the accepted VP8 profiles and one deterministic 1080p canvas-source. Each 30-second measurement followed only a five-second settle window,-so the 1080p60 results include the known bandwidth-estimator ramp and are-screening data rather than steady-state game-cost baselines. Browser CPU covers-the entire isolated instance; `100%` means one logical core and includes source-rendering, local decode, and Browser services.--All runs used repository commit `74c959aa629f66db20439c98d0ea37bdfe8e2d63`,-benchmark schema 3, `BENCHMARK_HEADLESS=false`, `BENCHMARK_DURATION_SECONDS=30`,-`BENCHMARK_SETTLE_SECONDS=5`, endpoint cap `2`, and no canary or recovery arm.-`BENCHMARK_PROFILE` selected the table's profile, `BENCHMARK_VIEWERS` selected-one or two Viewers, and the sender count is the observed Host result under cap-`2`; `CHROME_PATH` selected the exact Browser version shown. The reproducible-entry point is `npx tsx scripts/peer-assisted-benchmark.ts`.--| Run | Browser | Profile | Senders | FPS mean (range) | Resolution(s) | Encode ms/frame | Limitation samples | Browser CPU (valid intervals) |-| --- | --- | --- | ---: | --- | --- | ---: | --- | --- |-| C30 | Chrome 151.0.7922.174 | 1080p30 | 1 | 30.0 (29-31) | 1920x1080 | 4.06 | `none` 16/16 | 96.6% (13/15) |-| C60-A | Chrome 151.0.7922.174 | 1080p60 | 1 | 55.2 (45-58) | 1920x1080, 1280x720 | 4.86 | `bandwidth` 10/16, `none` 6/16 | 136.4% (13/15) |-| C60-B | Chrome 151.0.7922.174 | 1080p60 | 1 | 55.6 (54-57) | 1920x1080, 1280x720 | 3.91 | `bandwidth` 10/16, `none` 6/16 | 122.6% (13/15) |-| C60-2 | Chrome 151.0.7922.174 | 1080p60 | 2 | 56.8 (55-59) | 1920x1080, 1280x720 | 5.03 | `bandwidth` 20/32, `none` 12/32 | 233.4% (13/15) |-| E60-A | Edge 151.0.4129.101 | 1080p60 | 1 | 48.6 (45-53) | 1920x1080, 1280x720 | 4.53 | `bandwidth` 12/16, `none` 4/16 | 137.9% (7/15) |-| E60-B | Edge 151.0.4129.101 | 1080p60 | 1 | 43.9 (28-53) | 1920x1080, 1280x720, 960x540 | 3.15 | `bandwidth` 12/16, `none` 4/16 | 104.2% (6/15) |--The 60 fps arms stayed below the configured ceiling and changed spatial-resolution while encode work remained well below 16.7 ms/frame. In these short-runs the local symptom coincided with stock bandwidth adaptation, not an encode-time overrun. The Chrome 1080p30 control held full resolution and cadence without-a quality limitation. Process-set changes made uncovered CPU intervals unknown;-the table does not fill them with zero.--Dynamic Windows GPU Engine sampling followed the isolated Browser descendant-PID sets in runs C60-B and E60-B. Ten valid samples in each run showed zero-`VideoEncode` and `VideoDecode` activity across the enumerated counters. Chrome-showed about 35.5% 3D and 1.6% Copy; Edge showed about 8.0% 3D and negligible-Copy. That activity is consistent with source rendering and texture movement but-does not prove per-engine attribution. The collector did not retain adapter-LUID-mapping, and the synthetic source exposed neither `encoderImplementation` nor-`powerEfficientEncoder`; these GPU counters are supporting observations only.-An existing fake `getDisplayMedia` Chrome sample did expose VP8 `libvpx` and-`powerEfficientEncoder = false`. The exact Chromium backend inventory, rather-than the GPU counters alone, closes Chrome's Windows VP8 hardware encode as-unavailable; E60-B provides no contrary Edge evidence.--### Chrome 151 Startup Matrix--On 2026-08-25, Chrome `151.0.7922.174` on Windows reproduced the production-symptom in a controlled local loopback with no external network. Every run used-the same fake `getDisplayMedia` monitor at 1920x1080@30, one P2P sender and-receiver, VP8 `libvpx` with `powerEfficientEncoder = false`, and sender ceilings-of 5 Mbps and 30 fps. Only the named startup input changed.--| Startup input | About 1 second | About 4 seconds | About 8 seconds | Limitation |-| --- | --- | --- | --- | --- |-| `motion + balanced` | 480x270, 13 fps | 480x270, 15 fps | 480x270, 14 fps | `bandwidth` |-| `motion + balanced + x-google-start-bitrate=4500` | 480x270, 14 fps | 480x270, 15 fps | 480x270, 14 fps | `bandwidth` |-| no hint + balanced | 1920x1080, 18 fps | 1920x1080, 19 fps | 1920x1080, 20 fps | `none` |-| `detail + balanced` | 1920x1080, 18 fps | 1920x1080, 19 fps | 1920x1080, 20 fps | `none` |-| `motion + maintain-resolution` | 1920x1080, 17 fps | 1920x1080, 20 fps | 1920x1080, 20 fps | `none` |--The transition matrix then started with `motion + maintain-resolution` and-changed only the sender degradation preference to balanced:--| Balanced transition | Observed result |-| --- | --- |-| At connection, about 11 ms | Fell to 480x270 and remained bandwidth-limited |-| After the first encoded frame, about 80 ms | Retained 1280x720 but remained bandwidth-limited |-| After five encoded frames, about 442 ms | Retained 1920x1080 with no limitation through 8 seconds |-| After one or two seconds | Retained 1920x1080 with no limitation through 8 seconds |--This isolates the failure from network, codec selection, hardware encoding,-capture constraints, sender readback, and the startup-bitrate SDP hint.-Chromium maps `motion` to non-screencast realtime video, where balanced permits-startup resolution restrictions; entering or leaving balanced clears those-restrictions. Five encoded frames is the first measured safe media fact and is-beyond libwebrtc's four-frame startup-drop bound, rather than an arbitrary wall-clock delay.--Screener keeps `motion` because its later multilevel resolution adaptation is-required. Each new peer sender and SFU publication therefore starts with the-selected ceilings but an effective `maintain-resolution` preference. After the-current sender has encoded at least five frames, the existing stats path applies-the user's desired preference once. Connected was too early, and one encoded-frame retained only 720p in the controlled matrix; five frames retained 1080p.-There is no added timer, periodic rewrite, or application quality controller.--## LiveKit SFU Evidence--Pinned LiveKit client `2.22.0`, server `1.13.5`, and Chrome 151 established that-the SDK's default VP8 screen-share simulcast can expose original and lower-representations, and that server send-side BWE can select a lower representation-for a constrained subscriber while an unconstrained subscriber receives the-highest available representation.--Pinned LiveKit retains its own codec and startup-bitrate behavior. Screener does-not add an SDP startup hint to raw peers; the controlled matrix showed that it-does not address this `motion + balanced` restriction.--An earlier exact-production A/B also showed that forcing an always-active lower-encoding can consume the same Host-to-SFU congestion budget and reduce the-highest encoding. That evidence rejects Screener mutation of active layers; it-does not justify single HIGH, which abandons constrained subscribers.--Current source therefore:--- creates one Host publication for all SFU subscribers;-- sets VP8, no backup codec, the selected HIGH ceiling, and degradation- preference;-- leaves `screenShareSimulcastLayers` unset so pinned LiveKit owns construction- and republish behavior;-- enables Dynacast and server send-side BWE;-- leaves AdaptiveStream disabled because a Viewer may relay the received track- to children; and-- requests no application-selected subscriber layer.--LiveKit documents automatic bandwidth-based layer selection. It does not expose-an automatic policy that observes delivered FPS and spatially downshifts solely-to satisfy Screener's `maintain-framerate` preference. Adding such a controller-or fork remains outside the current product.--## Codec Decision--VP8 is the only Browser media codec because it has the broadest current Browser-interoperability and produced stable software-encoding behavior in the measured-Chrome path. Windows Chrome uses software VP8, and the measured Edge binary gave-no contrary hardware evidence; the page has no hardware encoder selection-surface. Other operating systems remain evidence-specific and must not be-inferred from the Windows backend.--Chromium's `has_trusted_rate_controller` is a libwebrtc coordination fact, not-Windows trust or security classification. Media Foundation video encoding-initially reports it false. When Chromium's H.264 software bitrate controller-owns frame dropping, MFVEA reports it true so libwebrtc disables its independent-media-optimization frame dropper and avoids double-dropping.--A controlled Chrome 151 loopback isolated this interaction on one AMD Media-Foundation encoder with the same dynamic 1904x928@30 source. The ordinary 8 Mbps-path emitted 14.18 fps at 14.24 ms encode time per frame. Forcing Chromium's-desktop H.264 software BRC on the same MFT emitted 29.93 fps at 8.17 ms per frame-and about 3.65 Mbps. Disabling hardware encode selected OpenH264 and emitted-10.47 fps. Raising the ordinary MFT ceiling or changing degradation preference-did not restore cadence. This proves that the observed AMD result was an outer-rate-control/frame-drop interaction, not a fixed MFT throughput limit; it is no-physical result for Intel or another AMD driver cohort.--Chrome 151 and 152 leave `MediaFoundationUseSWBRCForH264Desktop` disabled by-default. Chromium commit `24e0453977d38` enables it by default, caps desktop-quality at QP 35, caps HRD fullness, and uses predictive buffer headroom for-delta-frame dropping; exact Chrome 153 beta source contains that change, and-Chrome 153 stable is scheduled for 2026-09-08. AMD remains separately covered-by the vendor-wide `disable_h264_accelerator_sw_brc` workaround for Chromium-issue `417752242`, while `MediaFoundationSWBRCForH264ForceAMDGPU` remains-disabled in Chrome 153 and 154. Current source therefore implies that a selected-Intel MFT can receive the new default controller, but does not establish that-physical result. The accepted `motion` hint also maps the WebRTC encoder to the-realtime/camera content type whose H.264 SW BRC was already default-enabled; it-does not bypass the AMD workaround.--A Browser page cannot enable these process features, override the GPU workaround,-set `has_trusted_rate_controller`, or select a particular MFT. The two feature-names can reproduce the AMD bypass only in an explicitly launched diagnostic-browser. They are not a product workaround. OpenH264 was not a superior fallback,-so Browser H.264 remains closed until a future decision accepts exact Chrome 153+-Intel-default and AMD-default/forced real-game evidence. The separately proved-Native hardware-MFT path does not alter the Browser decision.--Screego `v1.12.4` does not supply another encoder path. Its settings list the-browser's RTP codec/profile capabilities, map `Best Quality` to VP9 profile 2,-and reorder all capabilities before each per-Viewer offer. Other codecs remain-negotiation fallback; no actual encoder, power-efficiency, frame-rate, or-runtime fallback evidence participates. Screego changed its default back to the-browser order after VP9 materially reduced frame rate, and its maintained P2P-fanout still creates one PeerConnection per Viewer.--The Browser candidates therefore have narrower potential than their names imply:--| Candidate | Potential advantage over VP8 | Current Browser stop line |-| --- | --- | --- |-| H.264 | Hardware encode can reduce Host CPU while retaining broad decode support. | Chrome cannot select a specific MFT; AMD remains outside SW-BRC by default, and the exact Intel/Chrome 153 result is unmeasured. |-| VP9 | Profile 0 may use a Windows Media Foundation encoder and can improve rate-distortion efficiency. | Screego's profile-2 preset is not the Windows hardware profile; software VP9 can cost more CPU and already caused a visible frame-rate regression. |-| AV1 | Modern hardware can provide the strongest compression candidate. | Chrome 151 and 153 keep Windows WebRTC AV1 hardware encode disabled by default, so codec support does not provide a usable hardware contract. |-| H.265 | Supported hardware can provide efficient H.264-class low-CPU encode at lower bitrate. | It is an advanced codec not supported by every Browser client; LiveKit compatibility requires regression or a backup publication, and the current cross-Browser relay matrix is absent. |--No candidate yet provides a product-wide Browser improvement with VP8's-coverage, so Browser media remains VP8. A bounded preflight nevertheless proved-that an actual sender can distinguish the previously bad and a newly good H.264-path without naming a GPU or trusting capability advertisement. All samples used-one real tab `getDisplayMedia()` source at 1904x928@30, `contentHint = "motion"`,-a 5 Mbps ceiling, five seconds of settling, and a ten-second measurement window.--| Browser and path | Actual implementation | Source / encoded / decoded cadence | Result |+# Realtime Screen-Share Quality Evidence++- Reviewed: 2026-08-27+- Scope: Browser game capture, codecs, startup adaptation, relay, and LiveKit+- Status: current evidence; product behavior is owned by+ [media quality](../product/media-quality.md) and+ [ADR-0007](../adr/0007-path-isolated-representation-quality.md)++## Findings++- Browser settings are ceilings and content intent, not delivered floors.+ WebRTC owns each direct/relay edge's congestion adaptation; LiveKit owns SFU+ representations and subscriber forwarding.+- Windows Chromium WebRTC VP8 is a software `libvpx` path. Web content cannot+ select NVENC, AMF, QSV, a GPU, or a particular Media Foundation transform.+- H.264 can be substantially cheaper when Chromium selects a good hardware MFT,+ but capability or `powerEfficientEncoder` does not prove sender cadence. An+ actual bounded sender probe is required.+- `contentHint = "motion"` is the correct game-motion intent. Removing it may+ retain spatial resolution by changing another quality tradeoff; the observed+ improvement was not free.+- Chromium's `motion + balanced` startup can retain an early low-resolution+ restriction. Starting at `maintain-resolution` and applying the desired+ preference after five encoded frames clears that native restriction without a+ timer or periodic quality controller.+- LiveKit's default screen-share representations, Dynacast, and server send-side+ BWE support weak and strong subscribers. Forcing a permanent lower encoding or+ single HIGH both regress a valid cohort.+- Current route quality evidence is diagnostic. Receiver-only freeze/loss data+ cannot prove an unconnected parent is better or authorize parent-wide/SFU+ routing changes.++## VP8 Cost And Hardware Boundary++Chromium 151's Windows Media Foundation and D3D12 WebRTC encoder factories did+not enumerate VP8. Libwebrtc reports its VP8 implementation as software. Ten+valid GPU Engine samples in isolated Chrome and Edge runs showed zero+`VideoEncode`/`VideoDecode`; 3D activity reflected rendering/texture work and is+not encoder attribution.++Headful isolated loopbacks used a deterministic 1080p source, accepted profiles,+five seconds of settling, and 30 seconds of measurement. Browser CPU includes+source rendering, local decode, and Browser services; 100% is one logical core.++| Browser/profile | Senders | Delivered result | Encode cost | Browser CPU |+| --- | ---: | --- | ---: | ---: |+| Chrome 151, 1080p30 | 1 | 30 fps, 1920x1080, no limitation | 4.06 ms/frame | 96.6% |+| Chrome 151, 1080p60 | 1 | 55-56 fps, 1080p/720p, bandwidth-limited | 3.9-4.9 ms/frame | 123-136% |+| Chrome 151, 1080p60 | 2 | 56.8 fps, 1080p/720p, bandwidth-limited | 5.03 ms/frame | 233.4% |+| Edge 151, 1080p60 | 1 | 44-49 fps, 1080p/720p/540p | 3.2-4.5 ms/frame | 104-138% |++The 60 fps arms remained below the ceiling while encode time stayed well below+the 16.7 ms frame budget. In these short runs, stock bandwidth adaptation and+startup ramp, not a slow per-frame encoder call, coincided with the reduced+cadence/resolution. Web VP8 still competes materially with a game for CPU.++Reproduction uses `npx tsx scripts/peer-assisted-benchmark.ts`; retained commit+and environment details remain in Git history rather than this current evidence+summary.++## H.264 Root Cause And Gate++Chromium's `has_trusted_rate_controller` is encoder coordination, not a Windows+security classification. Some Media Foundation H.264 paths let both the MFT and+libwebrtc drop frames. A controlled Chrome 151 AMD loopback at roughly+1904x928@30 showed:++- ordinary hardware MFT: 14.18 fps at 14.24 ms encoded-frame cost;+- forced Chromium desktop software BRC on the same MFT: 29.93 fps at 8.17 ms;+- OpenH264 software fallback: 10.47 fps.++This isolates the observed AMD failure to outer bitrate-control/frame-drop+interaction, not a fixed MFT throughput ceiling. The page cannot enable the+process feature, override Chromium's AMD workaround, or select a different MFT.++Later exact Browser cohorts demonstrated why runtime evidence is useful:++| Path | Actual encoder | Source / encoded / decoded | Result || --- | --- | --- | --- |-| Chrome 151 direct H.264 | AMD Media Foundation hardware encoder; D3D11 decoder | 30.0 / 12.5 / 12.4 fps | Failed despite `powerEfficientEncoder = true`; encoded/source ratio 0.42. |-| Chrome 153 direct VP8 | `libvpx` software encoder and decoder | about 29.9 / 29.9 / 29.9 fps | Control sustained source cadence. |-| Chrome 153 direct H.264 | NVIDIA Media Foundation hardware encoder; D3D11 decoder | 29.9 / 29.9 / 30.0 fps | Full-cadence constrained baseline, ratio 1.00. |-| Chrome 153 LiveKit 1.13.5 H.264 | Simulcast adapter with two NVIDIA MFT encoders; D3D11 decoder | 29.5 / 29.1 / 29.1 fps | One `backupCodec: false` HIGH+LOW publication delivered the HIGH stream, ratio 0.99. |--Exact Chrome 153 also sustained about 30 fps on two simultaneous direct H.264-senders. A Host-to-Browser-relay-to-child chain sustained 29.6-29.7 fps at full-source resolution, and both encode stages remained NVIDIA MFT while both decode-stages remained D3D11. The dual-direct sample was still inside native bandwidth-ramp-up and therefore proves encoder cadence, not steady resolution quality.-Process identities changed during startup, so those whole-browser CPU deltas are-not retained as a codec cost claim.--`powerEfficientEncoder` alone cannot be the gate because the cadence-failing AMD-path also reported true. The portable evidence is the actual negotiated H.264-profile and implementation, plus identity-stable source-frame and encoded-frame-progress; the successful cohorts kept their encoded/source deficit bounded while-the bad path dropped frames continuously. The accepted gate uses a deterministic-moving Canvas track at the current share's effective target dimensions and frame-rate so static captured content cannot make encoder evidence inconclusive. It-warms the sender for 500 ms, measures for at least one second, and derives its-allowed frame lag from one 100 ms stats polling interval at the selected target-FPS; both source and encoded progress must reach that target. The four-second-deadline bounds local negotiation and evidence collection rather than defining-the performance threshold. With the real shared source held static through the-decision, exact Chrome 151 selected VP8 while exact Chrome 153 selected H.264;-the same moving-source runs selected VP8 and H.264 respectively. These two local-cohorts validate the mechanism but do not replace broader device and game-load-acceptance.--For direct peers, native SDP negotiation can order H.264 before VP8 in one offer-and choose the first codec supported by both endpoints; it does not require a-VP8 connection and a parallel H.264 connection. The accepted Browser design is-one share-scoped Host sender preflight and one received-source-scoped-Browser-relay preflight: a proved sender prefers H.264 for future edges,-otherwise it retains VP8, and already active edges are not churned. A single SFU-publication still cannot provide per-subscriber H.264 and VP8 without a second-encoded publication.-LiveKit backup codec is therefore not accepted. The Host source decision owns-that single publication: resolved H.264 or VP8 with no backup codec. No VP9,-AV1, H.265, codec wire/cache, parallel publication, or active-edge codec switch-is accepted by this evidence.--HEVC, AV1, custom WebCodecs pipelines, and application packetization do not-replace the browser WebRTC sender without a new capture, RTP/RTCP, feedback,-hardware, interoperability, and licensing design. No such path is accepted.--## Host Cost Boundary--One Chrome 151 VP8 sample on a Ryzen 7 9700X used about 0.79 logical core for one-1904x928@30 sender and about 1.34 logical cores for two independent senders. The-process totals included capture, WebRTC, source rendering, and local decode, so-they are not a weak-device or real-game capacity claim. Browser peers retain one-independent sender and congestion controller per `RTCPeerConnection`; shared-encoding is not guaranteed.--The current 1080p60 synthetic samples measured roughly 1.23 to 1.36 logical-cores for the whole isolated Browser with one sender and about 2.33 with two.-The second arm also added another Viewer, decode, render, and connection, so the-difference cannot be attributed to encoder count. The architectural boundary of-one ordinary sender per PeerConnection comes from WebRTC behavior, not this CPU-comparison; the measurement does not justify a shared Browser encoder.--The accepted way to handle a constrained Host is the existing explicit share-profile. Screener does not silently remove a representation needed by a weak-Viewer or invent a hidden host-performance tier.--## Page Lifecycle Boundary--Host document visibility, captured-source visibility, capture production,-encoder throughput, transport, Viewer decode, and local presentation are-different variables. Current code pauses only the Host's muted local preview-when its page is hidden or unfocused; it does not stop capture or senders.--Browser timers and frame callbacks may be delayed while hidden. A resumed Viewer-must rebaseline the existing decoded-stall wall clock before another no-progress-sample can invalidate the route, and a new current-generation composited frame-is authoritative evidence that stale `connecting` or `reconnecting`-presentation has ended. These rules make recovery lifecycle-safe; they are not-a keepalive mechanism.--The Screen Capture specification permits a user agent to mute a captured surface-that becomes inaccessible, including a minimized captured window. A page cannot-override that platform boundary. Mobile background audio, video recovery, page-reclamation, and relay survival remain physical-device acceptance work.--## Route Quality Authority--Current parent selection hard-filters authorization, source reachability,-acyclicity, capacity, and resource admission, then orders eligible P2P parents-by resulting depth, remaining sender capacity, a stable child-parent hash, join-order, and peer identity. Initial acquisition gives one direct candidate a-bounded foreground window, then uses SFU for availability while finite direct-candidates converge behind working media. It has no network-quality score.--A manual media reconnect stays on the current exact route: P2P rebuilds the-same parent connection, and SFU reconstructs the same subscription. Browser-page refresh also rebinds the same stable participant and committed graph.-Only actual recovery exhaustion enters the normal route-failure operation and-tries other eligible P2P parents before SFU.--Quality-driven relay abdication or active parent switching requires evidence-that current diagnostics do not yet provide. No active policy is implemented.--The reopened quality-selection research retains that information boundary.-Current-route WebRTC stats can prove user-visible degradation but cannot prove-that an unconnected parent is better. Mature overlay systems such as ALMI and-Overcast measure alternatives and require a meaningful improvement before-moving; their periodic all-neighbor probes and published example thresholds do-not fit Screener's Browser, capacity, or latency contract.--The smallest compatible model is one `QualityEpisode` owned by the existing-room controller. It creates no parent score, second graph, all-pairs probe, or-periodic rebalancer. Phase one uses only visible, locally playing, non-paused,-identity-stable freeze duration with continuing decoded progress. Loss, RTT,-jitter, bitrate, resolution, FPS, and decode time remain attribution; treating a-quality ceiling as a delivered floor requires a separate product SLO. Relay-ingress degradation reparents that relay while retaining its subtree; one-child's degradation moves only that child.--The implemented first stage is shadow evaluation only. Viewer evidence adds the-standard cumulative-renderer deltas `freezeCount`, `totalFreezesDuration`,-`pauseCount` and `totalPausesDuration` and requires continuing-`framesDecoded` progress. W3C already-defines a freeze relative to the last 30 rendered frames, so this phase invents-no FPS, bitrate, loss or latency threshold. A recovered freeze or pause updates-its duration only after a later frame is rendered, so a valid delta may exceed-the adjacent report window and must not be clipped. Current target Chromium-does not map W3C `framesRendered` into `RTCInboundRtpStreamStats`, so synthetic-fixtures must not make it a product dependency. A missing member is unknown;-only windows containing decoded progress and all four freeze/pause metrics enter-the aggregate.--Presentation eligibility binds visible/not-suspended page state, non-paused-Host authority, native video play state, current composited-frame proof and the-exact connected route. Every eligibility change advances a strictly monotonic-presentation epoch. The first completed stats sample in an epoch is only a-baseline; an async sample may be emitted only if the epoch is still current.-Rate limiting remains per Viewer connection across epoch changes.--After the signaling layer revalidates the authenticated Viewer, current upstream,-connection and room revision, the existing room controller independently checks-its exact committed edge. It retains no samples or event ring, only one safe--integer aggregate for the latest accepted epoch of each current child:-eligible windows/duration, recovered-freeze windows/count/duration, pause-count/duration, and the last accepted time used by the existing five-second-freshness rule. The Host-only on-demand route snapshot exposes that closed-aggregate under the child's temporary ordinal; it exposes no epoch, session,-connection, raw metric or timeline. Observation does not touch controller facts-or trigger route work.--### Strict-v13 Production Shadow Control--On 2026-08-27, production release `73ed920` and Chrome-`151.0.7922.174` ran isolated one-Host/one-Viewer direct-P2P controls with a-deterministic 1280x720@30 canvas source. Runner commit `802781878701` is retained-on `dev/retained-candidates`; it creates and abandons its own room and exports-only the anonymous Host diagnostic snapshot. A global CDP network rule was-installed at zero before the Viewer PeerConnection was created, then changed-for one bounded pulse and restored to zero. The rule returned a non-empty ID;-the final snapshot was comparable only when route revision, connection-generation, presentation epoch, Viewer session generation, parent and route all-remained unchanged.--| Packet loss | Pulse | Eligible windows / duration | Recovered freezes | Freeze duration | Result |-| ---: | ---: | ---: | ---: | ---: | --- |-| 0% | 2 s | 2 / 4,001 ms | 0 | 0 ms | comparable |-| 10% | 2 s | 3 / 6,000 ms | 0 | 0 ms | comparable |-| 10% | 6 s | 3 / 6,000 ms | 1 | 282 ms | comparable |-| 30% | 2 s | 2 / 4,000 ms | 2 | 701 ms | comparable |-| 30% | 6 s | 5 / 10,002 ms | 11 | 3,585 ms | comparable |-| 100% | 2 s | 4 / 8,000 ms | 1 | 2,011 ms | comparable |-| 100% | 6 s | n/a | n/a | n/a | route identity changed |--All comparable cells reported zero recovered pauses. The controls establish-that the strict-v13 collection path accepts renderer-settled freeze duration-across report windows and leaves the route unchanged. They also reject a loss-percentage, one freeze, or one pulse duration as a product trigger: the same-loss level produced different presentation results, and the longest all-drop-cell crossed into availability recovery instead of remaining a quality sample.-This synthetic direct cohort does not calibrate an active threshold or predict-another parent; real games, natural public-network sessions, relay subtrees,-SFU cohorts and mobile lifecycle evidence remain required.--Active migration follows only after annotated production samples establish an-acceptable false-positive and disruption boundary. An active episode would keep-the existing first-frame commit rule, allow one low-priority trial and at most-one restore, and yield immediately to join, hard recovery, departure, capacity,-pause, or SFU drain work. Post-commit probation measures the actual presented-path without holding two long-running media routes whose competing bandwidth-and non-rendered candidate metrics would distort comparison. The trigger,-probation, cooldown, inconclusive result and permission to create or prioritize-SFU resources remain the next product decision.--The possible active state machine remains `observe -> qualified -> queued ->-trial prepare -> first-frame commit -> probation -> keep | restore once ->-cooldown`. It uses the existing reservation and room-serial child operation,-permits no bounded-gap quality trial, and yields to availability work. Relay-ingress evidence may reparent that relay while retaining its subtree, but one or-several child reports cannot infer that the relay is globally bad. Phase one has-no quality-driven relay-wide abdication. Freeze entry/exit, probation evidence,-improvement margin, cooldown, and room disruption budget must be calibrated from-real annotated sessions; paper and library defaults are not Screener thresholds.--The candidate active model has one `QualityEpisode` inside the existing room-controller, not a second optimizer. It keeps only the exact subject, prior-route or capacity, trigger-evidence revision, trial revision, probation-baseline, one restore flag, and a cooldown `notBefore`. Cooldown expiry does not-wake the room; the next real room or evidence event may reconsider it. Join,-hard recovery, departure, pause, capacity, and SFU drain work always preempt and-clear lower-priority quality work.--One episode asks the existing deterministic filters and ordering for only the-first eligible candidate. It prepares that single route through the existing-capacity and server-resource reservations, retains the old route until first--frame commit, then measures the new presented path sequentially in probation.-Failure is inconclusive and enters cooldown; it does not enumerate more parents.-Probation may restore the old tuple once through the same child operation. A-quality-only trial is skipped when make-before-break overlap is unavailable;-bounded-gap cutover remains reserved for availability recovery.--The same episode model covers every transport without a P2P/SFU state matrix:--- one degraded child is the subject of an ordinary reparent operation;-- a relay with degraded ingress is itself the child, so its subtree remains;-- healthy ingress plus corroborated degradation across multiple exact child- sender/receiver pairs may reduce that parent's effective capacity by one,- letting existing overflow reconciliation move one child at a time;-- a Host-wide egress problem with a healthy source may trial the existing SFU- publication as one candidate, but only with normal Host overlap, publication,- subscription, and admission reservations; and-- an SFU-fed Viewer remains an ordinary peer parent candidate and never creates- a second publication.--Capacity recovery is event-driven half-open: after cooldown, a later real demand-may use one provisional slot, and that child supplies probation evidence. No-demand means no probe or rebalance. At `C=3`, a full Host has no fourth-copy-overlap; it must first move one child make-before-break through an already-eligible peer or skip the Host-to-SFU quality trial. SFU admission rejection-keeps the healthy route and ends the episode without joining the availability-resource-wait queue.--Current-path evidence cannot prove an unconnected path is better. FPS,-resolution, and bitrate require a same-window source baseline; configured-ceilings are not delivered floors. Loss, RTT, jitter, NACK/PLI, encode/decode-time, and `qualityLimitationReason` remain attribution unless corroborated by-presented-path evidence. Parent-wide abdication additionally needs evidence from-multiple distinct current children plus their exact sender constraints while-the parent ingress remains healthy; `C=1` therefore cannot infer parent-wide-quality from one child.--Production shadow data must determine every policy number: entry/exit floor,-minimum eligible windows and duration, aligned-window tolerance, probation,-meaningful improvement margin, cooldown, per-room disruption budget, `C=3`-quorum, Host-to-SFU gate, inconclusive rate, and browser/mobile missing-field-rate. Overcast's percentage, End System Multicast's hold-down/probe cadence,-QUIC path timers, circuit-breaker defaults, and paper test payloads are evidence-about structure only and are not accepted thresholds.--Overcast and ALMI support measured gain versus disruption before switching.-RFC 8326 supports drain-before-removal; RFC 9000 supports validating a new path-while the old path remains usable and not inheriting old congestion state. RFC-7196's documented damping false positives support shadow-first observation, but-its penalty score is not adopted. A half-open concept is useful without adding-a circuit-breaker dependency or sliding failure-rate controller. SplitStream,-CoolStreaming/DONet, and SAAR require multi-tree striping, mesh/block pull, or a-second active control overlay and remain explicit no-go references for this-single-graph product.--This research adds no dependency and copies no implementation. LiveKit is-Apache-2.0, libwebrtc uses its BSD-style license, and Resilience4j is-Apache-2.0; papers, RFCs, and W3C documents are referenced only for design-evidence. GPL/AGPL reference implementations remain study-only under the-repository license boundary.--## Current Verification Gaps--- Real games under competing CPU/GPU load at 720p30, 1080p30, and 1080p60.-- Real-game CPU contention on Windows and actual encoder paths on- macOS/Linux/weaker Hosts.-- Mixed P2P/SFU sessions on heterogeneous public networks, including recovery.-- Mobile foreground/background playback, page reclamation, and relay survival.-- Long-running encode/decode cost, thermals, A/V synchronization, and resource- admission at the 20-Viewer bound.--Measurements must correlate capture, outbound, and inbound stats over the same-interval. Missing counters and identity changes remain unknown, not zero.+| Chrome 151 direct H.264 | AMD Media Foundation | 30.0 / 12.5 / 12.4 fps | failed cadence despite efficient flag |+| Chrome 153 direct VP8 | `libvpx` software | 29.9 / 29.9 / 29.9 fps | full-cadence control |+| Chrome 153 direct H.264 | NVIDIA Media Foundation | 29.9 / 29.9 / 30.0 fps | full-cadence hardware path |+| Chrome 153 LiveKit H.264 | two NVIDIA MFT encoders | 29.5 / 29.1 / 29.1 fps | HIGH+LOW publication delivered HIGH |++Chrome 153 also sustained two direct H.264 senders and one Host-to-relay-to-child+chain near 30 fps with NVIDIA MFT encode and D3D11 decode at both stages. These+short runs prove cadence and negotiation, not steady game quality or whole-+Browser CPU cost.++The current Auto gate therefore uses a local H.264-only PeerConnection with a+deterministic moving Canvas track at the share target. It verifies negotiated+codec, source progress, and encoded progress rather than trusting capability,+GPU name, or `powerEfficientEncoder`. Unsupported, failed, slow, or inconclusive+evidence selects VP8. Manual VP8/H264 bypasses Auto and strictly applies the+choice.++The probe is share-generation scoped. Source switch, pause, profile changes, and+reparent do not rerun or change active edges. Viewer relays decide once before+their first child. The Host's one SFU publication uses the same resolved codec+and disables backup codec. A static real capture cannot make the decision+inconclusive because probe motion is independent.++VP9, AV1, and H.265 remain unsupported product candidates: Browser codec support+does not prove the desired hardware profile, cross-Browser relay compatibility,+or better real-time cadence. Screego's VP9 default was reverted after a frame-+rate regression and supplies no hidden encoder-selection workaround.++## Startup Quality Restriction++Chrome 151 reproduced the poor initial `motion + balanced` picture in a local+loopback with no external network, VP8 `libvpx`, 1920x1080@30 capture, and 5 Mbps+sender ceiling:++| Startup input | About 1 s | About 8 s | Limitation |+| --- | --- | --- | --- |+| `motion + balanced` | 480x270, 13 fps | 480x270, 14 fps | bandwidth |+| same plus SDP start-bitrate hint | 480x270, 14 fps | 480x270, 14 fps | bandwidth |+| no hint + balanced | 1920x1080, 18 fps | 1920x1080, 20 fps | none |+| `detail + balanced` | 1920x1080, 18 fps | 1920x1080, 20 fps | none |+| `motion + maintain-resolution` | 1920x1080, 17 fps | 1920x1080, 20 fps | none |++Changing only degradation preference at connection or after one encoded frame+retained 270p or 720p. Changing after five encoded frames retained 1080p and+cleared the limitation through the measured window. Five frames is the first+measured safe media fact and follows libwebrtc's four-frame startup-drop bound;+one/two-second timers are unnecessary.++Current senders therefore start with the requested ceiling and temporary+`maintain-resolution`, then the existing stats path applies the user's desired+preference once the exact sender has encoded five frames. The application does+not add an SDP bitrate hint, periodic rewrite, or custom adaptation ladder.++## LiveKit Representation Evidence++Pinned LiveKit client 2.22.0, server 1.13.5, and Chrome 151/153 showed that+default screen-share publication can expose original and lower representations,+and server BWE can forward a lower representation to a constrained subscriber+while another receives the highest available representation.++Forcing a lower encoding permanently consumed the same Host-to-SFU congestion+budget and reduced HIGH performance. Publishing only HIGH abandoned constrained+subscribers. Current ownership is therefore:++- one Host publication for all SFU subscribers;+- no custom `screenShareSimulcastLayers` and no backup codec;+- pinned LiveKit representation construction and republish behavior;+- Dynacast plus server send-side BWE; and+- AdaptiveStream disabled because every Viewer may relay its received track.++A LiveKit H.264 publication may use more than one hardware encoder for its+representations. Reducing Host network copies to one publication does not by+itself prove lower Host encode cost.++## Host And Page Cost Boundaries++Each ordinary Browser child is an independent PeerConnection and normally an+independent encode/network copy. A Browser relay decodes its upstream track and+re-encodes each child. Hardware codec success can reduce per-copy CPU but does+not change endpoint capacity or prove shared encode.++Host page visibility, captured-surface visibility, capture production, encode,+transport, Viewer decode, and local presentation are separate variables. Current+code pauses only the hidden/unfocused local preview. Browser/OS capture muting,+mobile suspension, page reclamation, and relay survival remain platform evidence+in [background capture research](./browser-background-capture.md), not Web+keepalive features.++## Quality Shadow++Strict v13 reports renderer-derived freeze/pause deltas only for exact current+foreground presentation with continuing decoded progress. Identity and+presentation changes establish a new baseline; missing fields remain unknown.+The controller retains one bounded fresh aggregate per child for the Host-only+acceptance snapshot. It does not change routes, capacity, SFU use, or media+settings.++A controlled production direct-P2P canvas run injected packet-loss pulses:++| Loss/pulse | Recovered freezes | Freeze duration | Outcome |+| --- | ---: | ---: | --- |+| 0% / 2 s | 0 | 0 ms | comparable |+| 10% / 2 s | 0 | 0 ms | comparable |+| 10% / 6 s | 1 | 282 ms | comparable |+| 30% / 2 s | 2 | 701 ms | comparable |+| 30% / 6 s | 11 | 3,585 ms | comparable |+| 100% / 2 s | 1 | 2,011 ms | comparable |+| 100% / 6 s | n/a | n/a | route identity changed |++All comparable arms had zero recovered pauses. The same loss rate produced+different presentation results, and the longest all-drop pulse crossed into+availability recovery. This proves the shadow path, not an active threshold or+counterfactual parent quality. Quality-driven routing is parked in TODO.++## Open Evidence++- Real games and sustained CPU/GPU contention across weaker Hosts and operating+ systems.+- Exact Chrome 153+ Intel and AMD default H.264 behavior without diagnostic+ feature overrides.+- Codec cost and quality after stock BWE reaches steady state.+- Mixed P2P/SFU public-network quality, long-running thermals, A/V sync, mobile+ lifecycle, and 20-Viewer resource admission.## Primary Sources-- [MediaStreamTrack Content Hints](https://www.w3.org/TR/mst-content-hint/)-- [Screen Capture](https://www.w3.org/TR/screen-capture/)-- [Media Capture from DOM Elements](https://www.w3.org/TR/mediacapture-fromelement/)- [WebRTC](https://www.w3.org/TR/webrtc/)- [WebRTC Statistics](https://www.w3.org/TR/webrtc-stats/)-- [libwebrtc adaptation overview](https://webrtc.googlesource.com/src/+/HEAD/video/g3doc/adaptation.md)-- [Chromium content-hint capture mapping](https://chromium.googlesource.com/chromium/src/+/3468eea378284a9cc42d05532cf3e1ee1f716fa9/content/renderer/media/webrtc/webrtc_video_capturer_adapter.cc)-- [libwebrtc content-hint sender mapping](https://webrtc.googlesource.com/src/+/98c256dadcab7c69e45de78091da9932d244f2e3/pc/rtp_sender.cc)-- [libwebrtc balanced restriction reset](https://webrtc.googlesource.com/src/+/f20ebb8adbf4fa781830e4384c61f732bd28a217/call/adaptation/video_stream_adapter.cc)+- [MediaStreamTrack Content Hints](https://www.w3.org/TR/mst-content-hint/)+- [Screen Capture](https://www.w3.org/TR/screen-capture/)+- [libwebrtc adaptation](https://webrtc.googlesource.com/src/+/HEAD/video/g3doc/adaptation.md)+- [libwebrtc VP8 encoder](https://webrtc.googlesource.com/src/+/refs/heads/main/modules/video_coding/codecs/vp8/libvpx_vp8_encoder.cc)- [libwebrtc startup frame dropper](https://webrtc.googlesource.com/src/+/f20ebb8adbf4fa781830e4384c61f732bd28a217/video/adaptation/video_stream_encoder_resource_manager.cc)-- [LiveKit initial-quality fix](https://github.com/livekit/client-sdk-js/pull/1987)-- [LiveKit initial-quality implementation](https://github.com/livekit/client-sdk-js/commit/5db17af)-- [LiveKit screen-share encoding construction](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/participant/publishUtils.ts)-- [LiveKit video simulcast and Dynacast](https://docs.livekit.io/transport/media/advanced/)-- [LiveKit selective subscription](https://docs.livekit.io/transport/media/subscribe/)-- [LiveKit server forwarding](https://github.com/livekit/livekit/blob/v1.13.5/pkg/sfu/forwarder.go)- [Chromium WebRTC encoder factory](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/platform/peerconnection/rtc_video_encoder_factory.cc)-- [Chromium 151 WebRTC video codec factory](https://chromium.googlesource.com/chromium/src/+/refs/tags/151.0.7922.174/third_party/blink/renderer/platform/peerconnection/video_codec_factory.cc)-- [Chromium 151 Windows Media Foundation encoder profiles](https://chromium.googlesource.com/chromium/src/+/refs/tags/151.0.7922.174/media/gpu/windows/mf_video_encoder_shared_state.cc)-- [Chromium D3D12 video encoder profiles](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/media/gpu/windows/d3d12_video_encode_accelerator.cc)-- [libwebrtc VP8 encoder](https://webrtc.googlesource.com/src/+/refs/heads/main/modules/video_coding/codecs/vp8/libvpx_vp8_encoder.cc)-- [libwebrtc trusted-rate-controller contract](https://webrtc.googlesource.com/src/+/refs/heads/main/api/video_codecs/video_encoder.h)-- [libwebrtc outer frame dropper](https://webrtc.googlesource.com/src/+/refs/heads/main/video/video_stream_encoder.cc)-- [Chromium Media Foundation encoder rate-control integration](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/media/gpu/windows/media_foundation_video_encode_accelerator_win.cc)-- [Chromium desktop H.264 SW BRC change](https://chromium.googlesource.com/chromium/src/media/+/24e0453977d38aada35c5e78fcec3d11d6cdea6e)-- [Chrome 153 H.264 MF feature defaults](https://chromium.googlesource.com/chromium/src/+/refs/tags/153.0.8010.5/media/gpu/windows/mf_video_encoder_switches.cc)-- [Chromium AMD H.264 SW BRC workaround](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/gpu/config/gpu_driver_bug_list.json)-- [Chromium AMD SW BRC issue 417752242](https://issues.chromium.org/issues/417752242)-- [Chrome 153 release schedule](https://developer.chrome.com/blog/chrome-two-week-release)-- [Screego codec preference implementation](https://github.com/screego/server/blob/v1.12.4/ui/src/useRoom.ts)-- [Screego VP9 quality experiment](https://github.com/screego/server/pull/132)-- [Screego per-Viewer encode cost](https://github.com/screego/server/issues/160)-- [Chromium Windows WebRTC hardware codec mapping](https://chromium.googlesource.com/chromium/src/+/refs/tags/153.0.8010.5/third_party/blink/renderer/platform/peerconnection/rtc_video_encoder_factory.cc)-- [Chromium WebRTC AV1 and H.265 feature gates](https://chromium.googlesource.com/chromium/src/+/refs/tags/153.0.8010.5/media/webrtc/webrtc_features.cc)-- [LiveKit advanced and backup codec contract](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/track/options.ts)-- [Overcast parent measurement and hysteresis](https://pdos.csail.mit.edu/~jj/jannotti.com/papers/overcast-osdi00/)-- [ALMI application-level multicast](https://www.usenix.org/legacy/event/usits01/full_papers/shi/shi_html/)-- [End System Multicast](https://static.usenix.org/events/usenix04/tech/general/full_papers/chu/chu_html/index.html)-- [RFC 8326 graceful routing shutdown](https://www.rfc-editor.org/rfc/rfc8326.html)-- [RFC 9000 path validation and migration](https://www.rfc-editor.org/rfc/rfc9000.html)-- [RFC 7196 route-flap damping](https://www.rfc-editor.org/rfc/rfc7196.html)-- [RFC 8836 WebRTC congestion-control interactions](https://www.rfc-editor.org/rfc/rfc8836.html)-- [Resilience4j circuit-breaker states](https://resilience4j.readme.io/docs/circuitbreaker)-- [SplitStream](https://www.microsoft.com/en-us/research/wp-content/uploads/2003/02/castro03splitstream.pdf)-- [CoolStreaming/DONet](https://researchportal.hkust.edu.hk/en/publications/coolstreamingdonet-a-data-driven-overlay-network-for-peer-to-peer/)-- [SAAR](https://static.usenix.org/event/nsdi07/tech/full_papers/nandi/nandi_html/index.html)+- [Chromium Media Foundation encoder](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/media/gpu/windows/media_foundation_video_encode_accelerator_win.cc)+- [Chromium H.264 software BRC](https://chromium.googlesource.com/chromium/src/media/+/24e0453977d38aada35c5e78fcec3d11d6cdea6e)+- [Chromium AMD H.264 workaround](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/gpu/config/gpu_driver_bug_list.json)+- [LiveKit publish options](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/track/options.ts)+- [LiveKit screen-share encodings](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/participant/publishUtils.ts)+- [LiveKit Dynacast and simulcast](https://docs.livekit.io/transport/media/advanced/)+- [LiveKit server forwarder](https://github.com/livekit/livekit/blob/v1.13.5/pkg/sfu/forwarder.go)+- [Screego codec ordering](https://github.com/screego/server/blob/v1.12.4/ui/src/useRoom.ts)+- [Screego VP9 regression](https://github.com/screego/server/pull/132)- [Media Capabilities](https://www.w3.org/TR/media-capabilities/)- [Chrome DevTools Protocol Network domain](https://chromedevtools.github.io/devtools-protocol/tot/Network/)++No implementation code was copied. LiveKit is Apache-2.0, libwebrtc uses its+BSD-style license, and Screego remains GPL research-only.diff --git a/docs/research/webrtc-p2p-screen-sharing.md b/docs/research/webrtc-p2p-screen-sharing.mdindex 66c15c3d..c952dc50 100644--- a/docs/research/webrtc-p2p-screen-sharing.md+++ b/docs/research/webrtc-p2p-screen-sharing.md@@ -1,404 +1,155 @@-# P2P 优先游戏屏幕共享调研与可行性评估+# WebRTC P2P 屏幕共享可行性-- 调研日期:2026-08-18-- 移动端采集与 Viewer 投屏能力复核:2026-08-21-- selected candidate 地址隐私语义复核:2026-08-22-- 目标场景:一名玩家向少量熟人私密分享,观看者可用手机/桌面浏览器加入,低延迟,尽量不消耗媒体服务器带宽-- 结论状态:本文保留早期 PoC 的可行性证据;当前 Browser source 与 production 只使用 direct/STUN peer 和 LiveKit SFU/UDP,Screener 不配置 TURN 或媒体 TCP。当前路由权威见 ADR-0005。--本文是可行性与历史证据,不定义当前路由策略;当前约束见-[ADR-0005](../adr/0005-automatic-hybrid-media-routing.md) 与 [TODO 台账](../todo.md)。+- 最后复核:2026-08-27+- 范围:浏览器采集与播放、WebRTC 可达性、一对多成本、移动端、+ codec 和安全边界+- 性质:通用研究证据,不定义任何产品的当前路由或部署状态## 结论-这个想法可行,而且非常适合先做 Web MVP。它的定位不是缩小版 Twitch,而是好友之间临时、私密、低延迟的实时窗口。正确的首版不是“完全没有服务器”,而是把系统拆为轻量控制面和 P2P 优先的数据面;分享者可以先用 Web/Electron,观看者应能直接打开手机或桌面浏览器链接:--```text- HTTPS / WSS-分享者 <------------ 房间、鉴权、信令 ------------> 观看者- | |- +---- ICE + STUN 尝试直接 UDP WebRTC ----------+- |- +---- logical edge: direct/STUN peer ----------------+- +---- fallback: one Host publication -> SFU subscriptions--当前自动模型由 ADR-0005 持有:健康 direct/peer 边保持 sticky;direct 阶段耗尽后,同一有界 operation 复用或建立一份 Host publication 并为 exact Viewer 建立 SFU subscription。每条路径受端点发送容量、独立 server admission、generation 和 bounded failure 共同约束。Browser source 与 production 已实现该模型;真实网络验收边界由 current status、TODO 和 verification ledger 持有。-系统必须无感完成拓扑分配、恢复和必要迁移;大规模公开分享仍直接使用现有直播服务。-```--“让画面跑起来”难度不高;“像 Discord/TeamSpeak 一样在不同 GPU、浏览器、NAT、运营商和弱网中都保持清晰、60 fps、低延迟”难度高。建议把产品分层:--- 当前 Browser 产品:Web、P2P/STUN 与专用 SFU/UDP,接入上限为 20;本地 20-Viewer Browser smoke 已证明控制面和容量边界,真实公网质量仍需验收。-- 可用边界:房间鉴权、自动路由、质量上限、ICE/LiveKit recovery、统计与明确的有界失败。-- 后续产品化:在当前功能和真实网络证据完成后交付公网服务器包与完全自包含的本地 Host-server 包;Native Host 是最低优先级增强。-- Discord 级:原生捕获/编码引擎、多个捕获后端、GPU 零复制、进程树音频、广泛兼容与持续遥测,属于长期工程。--## 竞品事实+浏览器可以用 `getDisplayMedia()`、`RTCPeerConnection` 和轻量信令完成+低延迟屏幕共享。P2P 能显著降低中央媒体带宽,适合少量互信观看者;它不等于+无服务器,也不能保证穿过所有 NAT、防火墙或移动网络。-| 产品 | 已公开的可靠事实 | 对本项目的含义 |-| --- | --- | --- |-| Discord Go Live | 使用 WebRTC,但媒体发往 Discord RTC Worker 后再转发给观看者;官方明确这是为了路由控制和隐藏用户 IP。桌面端有原生 C++ media engine、自研捕获/编码、多后端回退和硬件编码。 | Discord 的稳定性并不是纯 P2P 或纯浏览器免费获得的。它是未来质量上限参考,不是首版拓扑参考。 |-| TeamSpeak 6 | 官方技术回复说明用 WebRTC/ICE 做 P2P 屏幕分享;Windows 在 DX、Windows Game Capture 与传统捕获路径间选择。2026-04 官方称其 `turn.*` 主机实际仅启用 STUN,server-side SFU 仍在开发。 | 与当前目标接近,也解释了 direct-only/STUN-only 的部分可达风险;Screener 保持 direct/peer 优先,并用同一 controller 选择 direct 或 Host-publication/SFU subscription。 |-| KOOK / Oopz | 官方 SDK 清单只足以证明屏幕分享接入声网相关能力,没有公开具体媒体拓扑。 | 可以参考交互,不能把它们写成已经证实的 P2P 或 SFU 案例。 |+一份可用系统至少仍需要 HTTPS/WSS、房间鉴权、SDP/ICE candidate 交换、STUN、+容量保护和明确失败。无法直连时只能接受不可达,或使用 TURN/SFU 等服务器媒体+路径。浏览器 API 能快速验证需求,但不承诺固定捕获规格、跨连接共享编码、+手机后台执行或原生采集器级性能。-来源:+## Browser Capture And Playback-- [Discord Go Live 技术概览](https://discord.com/blog/how-it-all-goes-live-an-overview-of-discords-streaming-technology)-- [Discord WebRTC 架构](https://discord.com/blog/how-discord-handles-two-and-half-million-concurrent-voice-users-using-webrtc)-- [Discord GPU 编码优化](https://discord.com/blog/from-blocky-to-brilliant-improving-video-quality-on-discord-go-live-on-amd-gpus)-- [TeamSpeak 6 WebRTC 捕获与传输说明](https://community.teamspeak.com/t/what-dependencies-are-needed-for-screen-share/56852)-- [TeamSpeak 6 P2P 与未来 SFU 状态](https://community.teamspeak.com/t/where-is-screen-share-available-ts3-server-does-not-show-start-stream-button/58890)-- [TeamSpeak 6 P2P 技术讨论](https://community.teamspeak.com/t/how-does-share-screen-technically-work/56850)-- [TeamSpeak 6 当前 STUN/TURN 状态讨论](https://community.teamspeak.com/t/only-p2p-available-on-server-not-implemented-yet/55034?page=3)-- [KOOK SDK 清单](https://m.kookapp.cn/sdk_list.html)-- [Oopz 隐私与 SDK 说明](https://help.oopz.cn/agreement/privacy)+### 捕获合同-## ICE、STUN、TURN 与信令+- `getDisplayMedia()` 只在安全上下文中可用,并且每次调用都需要瞬态用户激活;+ 授权不能持久化,应用也不能用约束静默锁定指定窗口。+- 浏览器可以返回低于请求的尺寸或帧率,屏幕音频也可能缺失。成功后必须读取+ `MediaStreamTrack.getSettings()`,并把音频存在性视为结果而非保证。+- 受保护内容、系统安全桌面、独占全屏、最小化窗口和平台捕获后端会影响结果。+ 1080p60 是 best effort,不是 Web API 服务等级。+- `RTCRtpSender.replaceTrack()` 可在无需重新协商时换同类来源;若新轨超出已协商+ envelope 或改变不兼容的媒体属性,浏览器可以拒绝,调用方必须保留旧轨或重建+ 该连接。+- `contentHint = "motion"` 可表达高动态游戏内容;`setParameters()` 的码率、帧率+ 与 degradation preference 是上限或偏好,不能覆盖拥塞控制。-- 信令服务交换身份、房间状态、SDP 和 ICE candidates。WebRTC 不规定信令协议,WSS 是直接选择。-- STUN 让客户端发现公网映射并产生 server-reflexive candidate。它不承载媒体,也不能保证穿过所有 NAT。-- ICE 测试 host、server-reflexive、peer-reflexive 和 relay candidates,并选择可工作的候选对。Trickle ICE 可以减少建连等待。-- TURN 在无法直连时转发完整媒体流,是 NAT 组件中真正产生高带宽成本的部分。-- 当前 controller 保持健康 direct/peer UDP 边;ordinary peer 只接收 STUN。direct 阶段耗尽后,server-fed Viewer 使用唯一 Host publication 的精确 SFU subscription。每个尝试都受当前 generation、端点容量、server admission 和 bounded failure 约束。+### 发送与接收-不存在适用于所有用户的权威“P2P 直连率”。CGNAT、endpoint-dependent mapping、校园/企业防火墙、移动网络、IPv6 和地区运营商都会改变结果。真实网络验收必须分别记录 direct 的实际 `host/srflx/prflx` candidate type 与 SFU route kind,而不是引用未经验证的行业百分比。+把同一 track 加入多个 `RTCPeerConnection` 会产生独立的 sender、ICE/DTLS、+拥塞控制和反馈状态。标准不保证它们共享编码实例;CPU/GPU 和实际码控必须按目标+浏览器、GPU、分辨率和 fan-out 实测。-### 为什么会“有人能看,有人看不了”+Viewer 只需要接收一个 `MediaStream` 并绑定到带 `autoplay playsinline controls` 的+媒体元素。含声音的自动播放可能要求显式手势;应用不能用虚假“已播放”状态掩盖+autoplay rejection 或尚未解码的媒体。-ICE 是按分享者与每一名观看者的网络组合独立选路,而不是整个房间只做一次连接。一个家庭宽带观看者可能成功 UDP 打洞,另一个处于 CGNAT、对称 NAT、校园网、企业代理或蜂窝网络的观看者却没有可用直连候选。因此同一房间天然可能出现不同结果。+## ICE, NAT And Reachability-当前边界如下:+WebRTC 不规定信令协议。应用信令只交换会话描述、ICE candidates 和身份;媒体+可在协商后直接流经端点。-1. 将 direct UDP 设为最高优先级,成功者保持零媒体服务器路径。-2. Ordinary peer ICE 为 STUN-only;controller 在 direct 阶段耗尽后,按 server admission 授权当前 Host publication 的 SFU subscription,不能用固定全局梯级代替逐 edge 决策。-3. 通过统计确认 direct 的 selected candidate pair 或 SFU/UDP 媒体;不能从应用计时顺序推断路径。-4. 网络切换或候选对失效时执行 ICE restart,超时后重建该 peer connection。-5. 在 UI 和诊断中区分“直连”“SFU fallback”“正在恢复”和明确失败原因。+- STUN 发现公网映射并产生 server-reflexive candidate,不承载媒体,也不保证+ 穿过 endpoint-dependent mapping、CGNAT 或严格防火墙。+- ICE 在一个 exact peer connection 内检查 host、server-reflexive、peer-reflexive+ 和 relay candidates,并按优先级 nomination;Trickle ICE 允许候选生成时立即交换。+- TURN 提供 relay candidate 并转发完整媒体。它提高可达性,但不降低 Host 的每+ Viewer 媒体副本数,并给服务器增加每条边的入口与出口流量。+- 网络接口或映射变化可通过 ICE restart 重新收集和检查候选;应用层 timeout 不能+ 推断一个尚未尝试的远端节点是否可达。-这种混合房间里,一名观看者走 SFU/UDP 不会迫使其他观看者也进入 SFU;direct 与 SFU 路径分别保持自己的 WebRTC 安全边界。+同一房间中的每一对端点都有独立 NAT 组合,因此可能同时存在成功和失败的 P2P+连接。不存在可移植的“行业直连率”;家庭宽带、蜂窝网络、校园/企业网络、IPv4、+IPv6 和地区运营商必须分别取样。实际路径应由 selected candidate pair 与 transport+stats 确认,而不是从等待时长、IP 文本或客户端自报 NAT 类型推断。-来源:+## Bandwidth Conservation-- [WebRTC peer connection 与信令](https://webrtc.org/getting-started/peer-connections)-- [ICE RFC 8445](https://www.rfc-editor.org/rfc/rfc8445.html)-- [WebRTC transport 要求 RFC 8835](https://www.rfc-editor.org/rfc/rfc8835.html)-- [TURN RFC 8656](https://www.rfc-editor.org/rfc/rfc8656.html)-- [Trickle ICE RFC 8838](https://www.rfc-editor.org/rfc/rfc8838.html)+设完整媒体码率为 `B`,Viewer 数量为 `N`,单端点下游上限为 `C`。表中未计 RTP/IP+头、音频、RTX、FEC 和拥塞余量。-## 一对多带宽账--设单路编码码率为 `B`,观看者数量为 `N`。以下未计音频、RTP/IP 头、重传和 FEC;生产预算再预留约 10% 至 20%。--| 拓扑 | 分享者上行 | 服务器媒体 I/O | 适用性 |+| 拓扑 | Host 上行 | 中央媒体流量 | 关键代价 || --- | ---: | ---: | --- |-| P2P 星型 | `N * B` | 直连时接近 0 | 最符合成本目标;适合少量朋友 |-| P2P + TURN | 仍为 `N * B` | 每条中继约 `B` 入 + `B` 出 | 只解决不可达,不解决分享者上行 |-| Peer-assisted tree | 分享端最多约 `C * B` | 直连边接近 0;TURN 仍按边计费 | 每个 endpoint 最多发送 `C` 份;标准 browser relay 逐跳解码/重编码 |-| 整房 SFU(仅对照) | 约 `B` | `B` 入 + `N * B` 出 | 分享者轻松,但服务器承担全部观看流量;当前 root-shape 目标另按 `B_pub`、`B_i` 和 `B_exc,j` 计量 |-| MCU | 约 `B` | 另有解码、合成、重编码 | 本场景没有合成需求,不采用 |--以 `8 Mbps` 的 1080p60 目标流为例:--| 观看者 | 分享者上行 | 每小时分享者发送量 |-| ---: | ---: | ---: |-| 1 | 8 Mbps | 3.6 GB |-| 2 | 16 Mbps | 7.2 GB |-| 3 | 24 Mbps | 10.8 GB |-| 4 | 32 Mbps | 14.4 GB |-| 5 | 40 Mbps | 18.0 GB |-| 8 | 64 Mbps | 28.8 GB |--实际高动态 1080p60 可以把首版目标区间设为约 6 至 10 Mbps,因此四名观看者需要约 24 至 40 Mbps 持续上行,再加协议和重传余量。对光纤用户这并非不可行,但不能假设所有用户都具备该条件。--把同一 `MediaStreamTrack` 加到多个 `RTCPeerConnection` 会产生多个独立 `RTCRtpSender`、拥塞控制状态和码率目标。标准不保证跨连接只编码一次;浏览器可能优化,也可能创建多个编码上下文。因此分享端 CPU/GPU 容量必须实测。即使未来原生实现单次编码、多 peer packet fan-out,上行仍然是 `N * B`。--IETF 对 mesh/SFU 的拓扑说明见 [RFC 7667](https://www.rfc-editor.org/rfc/rfc7667.html)。--## 推荐的拓扑策略--当前 source 与 production 边界:--- 所有房间由 bounded peer-assisted/SFU controller 自动路由;ordinary peer 使用 STUN-only ICE。-- Current source 与 production 接受最多 20 名 Viewer。该数值只控制接入,不代表 1:20 已通过公网性能验收;真实矩阵仍需记录实际 sender、应用 CPU/内存与 SFU 用量。-- 每条 ordinary peer 链路独立使用 STUN-only ICE;direct 阶段耗尽后,同一 operation 可选择唯一 Host publication 的精确 SFU subscription。-- Current source 与 production 使用一份 Host publication 和精确 Viewer subscriptions,没有固定 SFU root 数或房间级 lease。-- 桌面和手机观看者使用同一个 Web 播放端;分享者不要求朋友安装完整客户端。--当前接受的非服务器 endpoint downstream 默认值为二,并允许部署静态配置为一、二或三;分享端及 Viewer 遵守同一规则。ADR-0004 的可删除实验验证第三名及后续 Viewer 可由客户端转发;ADR-0005 定义一份 Host publication、逐 Viewer SFU subscription 与独立 server admission,当前 Browser source 与 production 已收敛为一个自动 controller。真实 SFU、移动端和异构网络验收仍未完成;已关闭 PR #12 的显式整房 SFU 模式不再是当前方案。超过小房间上限时仍建议使用外部直播服务。观察项包括:--- 正常工作负载持续超过实测可承载的 P2P 人数。-- 当前 logical edge 的 direct/STUN transport 失败;controller 可在需要 server-fed source 时选择当前 Host publication 的 SFU subscription。-- 分享者上行安全余量不足。-- 分享者因 CPU/encoder 限制降质。-- 产品开始要求隐藏好友之间的 IP。--不要把观看者转发树直接加入 MVP。标准浏览器把收到的 WebRTC track 再发布会走解码后的 raw-frame sender,并创建新的编码 pipeline,增加负载、质量损失和逐跳延迟。ADR-0004 只允许用这条标准路径做确定性的两链 spike;若需要 Encoded Transform/DataChannel/WebCodecs 媒体、自定义拥塞控制、FEC/RTX、多树或综合评分,即放弃实验。详细证据见 `peer-assisted-media.md`。--## Web、Electron 与原生能力--### Web MVP--Web 版本能直接使用 `getDisplayMedia()` + WebRTC,最适合验证产品。但需要接受:--- 只能在 HTTPS 或 localhost 安全上下文使用。-- 每次捕获必须由用户手势触发并重新选择来源;授权不能持久保存。-- 网页不能通过 `deviceId` 强制指定某个游戏窗口。-- 即使请求 `audio: true`,浏览器规范也允许只返回视频;必须检查音轨是否存在。-- 1080p60 可以请求但不能保证。选择来源后用 `track.getSettings()` 验证实际分辨率和帧率。-- 最小化窗口、受保护内容、UAC secure desktop 和某些独占全屏路径可能黑屏或停止。游戏使用无边框窗口,或分享整个显示器,通常更稳。--直播中换源不需要先关房间。`RTCRtpSender.replaceTrack()` 可在同类媒体且协商 envelope 允许时替换 sender 的来源而不重新协商;分辨率、帧率块率、音频声道或编码约束不兼容时会拒绝,因此应用必须把失败限制在该 viewer 并重建其连接。为支持浏览器有时返回音频、有时不返回,初始 offer 可以预留 send-only audio transceiver,再将 audio sender 在 `null` 与真实 track 间替换。新的 `getDisplayMedia()` 仍必须由用户手势触发并重新选源,取消选择时旧流应继续工作。--游戏轨不覆盖 display-capture 的内容分类:--```js-const parameters = sender.getParameters();-parameters.encodings ??= [{}];-parameters.encodings[0].maxFramerate = 60;-parameters.encodings[0].maxBitrate = selectedProfileBitrate;-parameters.degradationPreference = "balanced";-await sender.setParameters(parameters);-```--这些参数是偏好或上限,不能绕过浏览器拥塞控制,也不能保证目标码率。`balanced` 允许浏览器在分辨率和帧率之间权衡,但不规定具体算法;视频 track 使用标准 `contentHint = "motion"` 表达游戏动态意图。当前源码链与测量要求见 [Realtime quality adaptation](./realtime-quality-adaptation.md)。静态画面通常能降低编码数据量,但规范不保证所有浏览器主动降低捕获频率或 GPU 开销。--因此首版不实现画面差分检测、周期性 `applyConstraints()` 或自定义动态 FPS 状态机。先对静态桌面和高动态游戏分别记录 `framesEncoded`、发送码率、`totalEncodeTime / framesEncoded`、`qualityLimitationReason` 及主机 CPU/GPU 占用;只有测量显示浏览器行为留下显著问题时,再设计最小的控制策略。这避免用额外竞态、计时器和画质跳变解决一个可能已由捕获器、编码器和 WebRTC 拥塞控制处理的问题。--来源:--- [W3C Screen Capture](https://www.w3.org/TR/screen-capture/)-- [W3C WebRTC](https://www.w3.org/TR/webrtc/)-- [W3C WebRTC Stats](https://www.w3.org/TR/webrtc-stats/)-- [W3C RTCRtpSender.replaceTrack](https://www.w3.org/TR/webrtc/#dom-rtcrtpsender-replacetrack)-- [MDN getDisplayMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia)-- [MediaStreamTrack content hints](https://www.w3.org/TR/mst-content-hint/)-- [RTCRtpSender 参数](https://developer.mozilla.org/en-US/docs/Web/API/RTCRtpSender/setParameters)-- [Chromium capture 架构](https://chromium.googlesource.com/chromium/src/+/HEAD/docs/media/capture/)--### 移动浏览器分享端边界--截至 2026-08-21,普通手机浏览器不能作为可靠的 Screener Host。当前-MDN Browser Compatibility Data 把 `getDisplayMedia()` 标为 Chrome Android、-Firefox Android 和 Safari iOS 均不支持;Chrome Android 72--88 与 Firefox-Android 66--79 曾暴露方法,但调用恒定以 `NotAllowedError` 失败。屏幕音频在-Chrome Android 也标为不支持。桌面模式、UA 或设备性能不能改变这个平台 API-边界。--Web UI 后续只做最小诚实处理:运行时检查-`navigator.mediaDevices?.getDisplayMedia`,缺失时在建房/发布前明确显示不支持;-方法存在也只表示可以尝试,真实调用失败仍区分 denied/cancelled/capture-failed,-不能按 UA 宣称兼容。移动 Viewer 不需要该 API,继续使用同一响应式 Web 播放端;-relay capacity 与其他普通 Web Viewer 相同。--来源:--- [MDN Browser Compatibility Data: `MediaDevices.getDisplayMedia`](https://github.com/mdn/browser-compat-data/blob/main/api/MediaDevices.json)-- [MDN `getDisplayMedia()`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia)-- [W3C Screen Capture](https://w3c.github.io/mediacapture-screen-share/)--### Viewer 后台播放边界--当前 Viewer 使用一个持续存在、可听的 `<video autoplay playsinline controls>`,播放被浏览器拦截时保留显式用户手势入口。Android Chrome 与 iOS Safari 对已经开始的可听 WebRTC 音频都有继续后台播放的现实能力,但音频焦点、OEM/系统策略、锁屏中断、页面 freeze/discard 和 WebContent 回收都不受网页保证。隐藏页面的视频帧交付、合成、JavaScript 路由控制与 relay 存活同样不是后台合同。--应用因此在 hidden、freeze 与 pagehide 期间暂停 decoded-stall 路由失败权威,在 visible、resume 与 pageshow 后先 rebaseline 并重建当前 frame proof;信令换代会释放未确认的 stall report 以允许 exact route 重试。SFU subscriber 使用 pinned LiveKit 的 `disconnectOnPageLeave=false`,避免 SDK 仅因 BFCache pagehide/beforeunload 主动拆除 Room;SDK 2.22.0 无条件注册的 `freeze -> disconnect` 保持未修改并进入真机 gate。应用不猜测系统 pause 与用户通过原生 controls 主动 pause 的区别,返回前台后的播放状态也由真机和既有显式播放入口验收。--一轮保留的 Chrome 151 双 Viewer 结果与该边界一致:后台标签页的 inbound、decoded 和 Opus RTP 计数继续增长,`requestVideoFrameCallback` 保持不变;前台 Viewer 的逐帧回调正常增长。这只证明该受控桌面样本的接收、解码和音频包连续性,不是可听性或手机生命周期证明。真机矩阵仍须分别覆盖 Android/iOS 的首次播放、切应用、锁屏、页面回收、后台期间换轨、Wi-Fi/蜂窝迁移、原生 controls 与被分配 relay child 后的生存/重分配。--来源(复核于 2026-08-26):[Page Visibility](https://www.w3.org/TR/page-visibility-2/)、[Chrome Page Lifecycle](https://developer.chrome.com/docs/web-platform/page-lifecycle-api)、[Chromium MediaStream hidden behavior](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/modules/mediastream/web_media_player_ms.cc)、[Android process lifecycle](https://developer.android.com/guide/components/activities/process-lifecycle)、[WebKit background WebRTC audio](https://bugs.webkit.org/show_bug.cgi?id=283297)、[LiveKit Safari background audio issue #1751](https://github.com/livekit/client-sdk-js/issues/1751)、[LiveKit page-freeze issue #1968](https://github.com/livekit/client-sdk-js/issues/1968)、[WHATWG media elements](https://html.spec.whatwg.org/multipage/media.html)。--### Viewer 向电视输出边界--截至 2026-08-21,Remote Playback API 仍不能作为 live WebRTC 的可移植输出契约。-W3C Candidate Recommendation 没有定义 `MediaStream`/`srcObject` 的远端播放行为,-把目标兼容性留给 UA;当实现只有 media flinging、媒体源又不是可交给目标的 URL 时,-规范明确允许 `prompt()` 返回 `NotSupportedError`。Chromium `f004e4a` 的实现只为非空、-有效且已判定兼容的 `KURL` 建立 availability URL;Screener 的进程内 `MediaStream`-没有该 URL。仅检测到 `HTMLMediaElement.remote` 因而不等于当前直播可投屏。--Safari 的边界更明确:WebKit `e88b92e` 的-`MediaPlayerPrivateMediaStreamAVFObjC::supportsType()` 对任何非本机 wireless playback-target 直接返回 `IsNotSupported`,而 Apple 的 AirPlay picker 示例使用 URL 型-`<video src="my-video.mp4">`,没有承诺 live WebRTC。当前 Safari AirPlay 媒体按钮和-Chrome Remote Playback 都不能为 Screener 显示一个诚实可用的站内入口;保留本机播放-以及系统级整屏/标签页镜像。--Google Cast `MediaInfo` 的 `contentUrl` 会被用作 media URL,缺失时 `contentId` 自身会-被当作 media URL;当前 P2P Viewer 持有的是进程内 `MediaStream`,没有可供电视 fetch-的 URL。为它新增转码、-HLS/Web Receiver 或私有协议会改变服务器媒体成本和安全边界,当前不做。投屏只属于-Viewer 本地播放输出;无论是否启用,现有 upstream PeerConnection、SFU/peer-route、Host fanout 和其他 Viewer 均不变。--未来只在浏览器发布说明或实现明确支持 live `MediaStream` wireless playback 后重开-这一切片。先用未合入产品的诊断页分别验证 Safari -> 实体 Apple TV 和 Chrome ->-实体 Chromecast/Google TV:现有 `srcObject` 的动态画面与音频连续播放至少 60 秒,-连接/断开后本机播放恢复,且 upstream PeerConnection identity、route 和 edge count-不变。某一平台单独通过时只支持该平台;通过后产品改动限于现有 `<video>` 的本地-availability 监听、一个用户手势图标按钮、状态/错误和监听清理,不增加媒体 URL、-receiver、信令或服务端路径。--许可证边界:这里只引用规范和官方实现行为,没有复制 Chromium/WebKit 代码或引入-依赖。当前不加载 Google Cast SDK,也不接受其 Additional Developer Terms;若未来改走-Cast sender/receiver,必须先单独完成条款、注册和分发审查。--来源(访问于 2026-08-21):--- [MDN Remote Playback API](https://developer.mozilla.org/en-US/docs/Web/API/Remote_Playback_API)-- [W3C Remote Playback API](https://www.w3.org/TR/remote-playback/)-- [Apple: Adding an AirPlay button to Safari media controls](https://developer.apple.com/documentation/webkitjs/adding_an_airplay_button_to_your_safari_media_controls)-- [Chromium `RemotePlayback` implementation at `f004e4a`](https://chromium.googlesource.com/chromium/src/+/f004e4a02b0ac1998398ed361d6aa133702b8c61/third_party/blink/renderer/modules/remoteplayback/remote_playback.cc)-- [WebKit live `MediaStream` AVFoundation player at `e88b92e`](https://github.com/WebKit/WebKit/blob/e88b92e29f0753e644abe33fdbc2b78c051ebf59/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaStreamAVFObjC.mm)-- [Google Cast Web Sender integration](https://developers.google.com/cast/docs/web_sender/integrate)-- [Google Cast `chrome.cast.media.MediaInfo`](https://developers.google.com/cast/docs/reference/web_sender/chrome.cast.media.MediaInfo)-- [Google Cast SDK Additional Developer Terms](https://developers.google.com/cast/docs/terms)--### Electron 分享端--Electron 可以固定 Chromium 版本,枚举屏幕/窗口,改善选源、热键和分享状态 UX,并使用 loopback 系统音频。它底层仍是 Chromium,单靠封装不会自动获得 Discord 级捕获质量。--推荐升级顺序:--1. Web 分享端和观看端。-2. Electron 分享端 + Web 观看端。-3. 若音频范围仍有问题,添加很小的 Windows WASAPI process-loopback native helper。-4. 只有实测证明捕获/编码是瓶颈时,才加入 WGC/DDA 纹理和原生 libwebrtc/硬件编码路径。--来源:--- [Electron desktopCapturer](https://www.electronjs.org/docs/latest/api/desktop-capturer/)-- [Windows.Graphics.Capture](https://learn.microsoft.com/en-us/windows/apps/develop/media-authoring-processing/screen-capture)-- [WASAPI loopback](https://learn.microsoft.com/en-us/windows/win32/coreaudio/loopback-recording)-- [Application loopback sample](https://github.com/microsoft/Windows-classic-samples/tree/main/Samples/ApplicationLoopback)-- [Desktop Duplication API](https://learn.microsoft.com/en-us/windows-hardware/drivers/display/desktop-duplication-api)--### Web 与移动观看端--观看端不需要屏幕捕获权限,做成响应式 Web 页面比绑定桌面客户端更符合本项目的便利性目标。首版至少要实测当前 Android Chrome 和 iOS Safari,并处理:--- Web Crypto Level 2 将 `crypto.randomUUID()` 限定在安全上下文,但没有这样限制 `crypto.getRandomValues()`。因此,通过 `http://<lan-ip>` 打开的局域网观看端不能在启动阶段依赖 `randomUUID()`,可改用 `getRandomValues()` 编码 128-bit 不透明标识。该例外只支持本地观看,并不放宽分享端或生产部署的 HTTPS 要求。([W3C Web Cryptography Level 2](https://www.w3.org/TR/WebCryptoAPI/),访问于 2026-08-18)-- 浏览器自动播放策略:先显示明确的“进入并播放”操作,再启动含声音的媒体。-- `playsinline`、横竖屏切换、全屏和安全区域,避免视频被强制弹出或裁切。-- 页面进入后台、锁屏后恢复,以及 Wi-Fi/蜂窝网络切换导致的 ICE restart。-- 手机解码温度与耗电;观看端只接收单路,不启用不必要的视频处理。-- H.264/VP8 能力协商和降档,不能假设桌面分享者选中的高级 codec 在每部手机上都有高效解码。--### 最小访问模型--接受的 access boundary 使用 production 必配的 `SITE_ACCESS_PASSWORD` 无状态 cookie 保护建房、Host role 和所有 code-only Viewer 入口;合法未过期的 exact-room fragment grant 可直接观看。没有 grant 时,服务端先要求 site access,再检查 ADR-0002 持有的 code-only policy;房间码只定位,cookie 也不替代房间密码。WebSocket upgrade 仍只做 Origin/容量检查并记录 cookie 状态,首条 `authenticate` 完成上述 role/room 授权。该边界不引入账号、JWT、服务端 session Map 或逐人 ACL。--RFC 3986 的规范事实是 fragment 在 URI dereference 前由 user agent 分离;WHATWG WebSockets 进一步规定含 fragment 的 constructor URL 必须抛 `SyntaxError`。因此把 128-bit room grant 放在 `/r/{code}#v=...`,再由页面在首个 WSS application message 发送,可以使它不进入 HTTP 或 WebSocket request-target。RFC 6750 对 OAuth bearer query 的警告并不直接规定本产品,但它提供了适用的安全类比:URI query 高概率被日志记录,不应承载此 grant。W3C Referrer Policy 的算法会从 referrer URL 移除 fragment,production 的 `no-referrer` header 再禁止整个 header;这是传输边界,不是“不会泄漏”的保证。--W3C TAG 的 capability URL 指南指出 URL 仍会出现在地址栏、历史、扩展、同步服务、截图和转发路径中,建议高熵、有限寿命与可撤销。目标使用 Node.js `randomBytes(16)` 的 128-bit 加密强随机量和完整 grant 的 SHA-256 摘要;grant 的有限寿命由 exact in-memory room incarnation 统一拥有,并在房间回收、进程重启、Host rotate 或 locked revoke 时结束,不增加第二个 expiry 时钟。浏览器首次严格解析后只写 room-scoped `sessionStorage`,立即 `history.replaceState` 到 canonical URL;刷新和页面内 WSS reconnect 可复用。HTML 标准明确新 auxiliary browsing context 可以复制同源 opener 的 session storage;这是已持有 bearer 的本地浏览器上下文转交边界,不是服务器扩大 room/role 权限,因此不增加导航状态机。raw grant 不进入 `localStorage`、cookie、query、Referrer、服务端持久存储、应用/代理日志或错误。OWASP 日志指南也明确把 access token、session identifier 和密码列为通常不应直接记录的数据。Fragment 降低服务端泄漏面,但 possession 仍等于该房间 Viewer 权限。--来源(访问于 2026-08-19):[RFC 3986 section 3.5](https://www.rfc-editor.org/rfc/rfc3986.html#section-3.5)、[WHATWG WebSockets](https://websockets.spec.whatwg.org/#the-websocket-interface)、[RFC 6455](https://www.rfc-editor.org/rfc/rfc6455.html)、[RFC 6750 section 2.3](https://www.rfc-editor.org/rfc/rfc6750.html#section-2.3)、[W3C Referrer Policy](https://www.w3.org/TR/referrer-policy/)、[W3C TAG Capability URLs](https://www.w3.org/TR/capability-urls/)、[HTML Web Storage](https://html.spec.whatwg.org/multipage/webstorage.html)、[Web Cryptography Level 2](https://www.w3.org/TR/WebCryptoAPI/)、[Node.js Crypto](https://nodejs.org/api/crypto.html) 与 [OWASP Logging Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html)。--WebRTC 媒体本身使用 DTLS-SRTP 加密,但 direct P2P 仍可能让这组可信好友看到彼此网络地址。若房间政策要求完全隐藏 endpoint IP,ordinary direct/peer 不能满足,应使用明确的中央媒体路径或拒绝该连接;当前产品不提供全房隐藏 endpoint IP 的独立策略开关。--## 编解码策略--- 当前 Browser 路径固定 VP8,因为它满足 WebRTC 基线互通,且无视频 hint 的受控证据恢复了接近 30 fps、完整分辨率和正常码控;direct、browser relay 与 SFU 不保留另一视频媒体 codec 作为 fallback。-- 不要仅凭 codec 名称判断性能。通过实际协商与统计确认 `encoderImplementation`、`powerEfficientEncoder`、`totalEncodeTime/framesEncoded` 和 `qualityLimitationReason`;VP8 hardware acceleration 仍需目标平台实测。-- 软件 VP9/AV1 可能抢占游戏 CPU;只有端点支持且实测硬件高效时才启用。-- Simulcast/SVC 主要帮助 SFU 按观看者网络选择层。它们不会消除 P2P fan-out 的 `N * B` 上行,还可能增加编码实例。--来源:--- [WebRTC codec requirements RFC 7742](https://www.rfc-editor.org/rfc/rfc7742.html)-- [WebRTC SVC](https://www.w3.org/TR/webrtc-svc/)-- [WebRTC Stats](https://www.w3.org/TR/webrtc-stats/)--## 可观测性与延迟验收--每个 peer connection 至少采集:--- selected candidate pair 和 `candidateType`-- current/available outgoing bitrate-- RTT、jitter、packets lost、NACK/PLI-- frameWidth、frameHeight、framesPerSecond、framesDropped-- `totalEncodeTime / framesEncoded`-- `encoderImplementation`、`powerEfficientEncoder`-- `qualityLimitationReason` 和各原因累计时长-- jitter buffer delay、decode time 和 total packet send delay--`RTCIceCandidateStats.protocol` 是内部候选传输字段;在通用 WebRTC 中,只有本地 relay candidate 的 `relayProtocol` 才能确认本端到 TURN 的实际传输,规范不向远端暴露该值。Screener 当前不配置 TURN,因此当前详情只以 `P2P`/`SFU fallback` 表示媒体方式,并显示浏览器对实际 current path 暴露的 `protocol` 与 candidate type;不合成 TURN 标签或补齐远端传输。W3C Stats 规定远端 candidate `address` 默认可为 `null`,浏览器也可按隐私策略过滤;诊断 UI 因此只读取当前本地 report 中由 media transport、`selectedCandidatePairId`、`localCandidateId`/`remoteCandidateId` 精确关联的地址与端口,缺失就保持未知,不解析 SDP 补值,也不上传、记录或持久化。--WebRTC 标准没有承诺固定毫秒延迟。工程目标必须带网络条件,并使用画面时间码或高速摄像机测量玻璃到玻璃延迟。60 fps 的单帧周期是 16.7 ms,端到端延迟还包含采集等待、编码、单程网络、jitter buffer、解码和显示。--建议目标:受控 direct/RTT <= 40 ms/丢包 <= 1% 时 p50 <= 150 ms、p95 <= 250 ms;区域 SFU/UDP root p95 <= 350 ms。先测量,再决定原生优化。--## 安全与成本防护--- WebRTC 使用 DTLS-SRTP;当前 SFU 在服务器上终止其两侧的 DTLS-SRTP,因此 operator 可接触媒体和流量元数据。-- P2P 会让房间内双方得知网络地址。熟人首版可以接受,陌生人房间不能默认接受。-- SFU credential 必须短期、精确绑定当前授权和代次,并受独立 ingress/egress admission 约束。-- site access password 控制建房/Host role 和 code-only 尝试,不能替代 room-scoped grant 或可选逐房间 Viewer 密码;`open` room code 明确不提供隐私。这些入口都不改变媒体 fanout/egress 上限。-- raw Viewer grant 与 Host token 等同访问凭据:服务器当前进程只保存摘要,禁止日志/遥测/错误/Referrer/持久存储明文。显示名、room-scoped peer 后缀和 IP 诊断均不参与授权。-- 如果未来要求 SFU operator 看不到内容,再评估 SFrame/WebRTC Encoded Transform 和群组密钥管理;当前不得宣称应用 E2EE。--## 参考代码优先级--| 项目 | 用途 | 许可证与判断 | 重点代码 |-| --- | --- | --- | --- |-| [MiroTalk BRO](https://github.com/miroslavpejic85/mirotalkbro) | 最贴近一人广播、多名观看;可用部署级开关选择 P2P 或 mediasoup SFU | AGPL-3.0。最快验证概念,闭源前只能研究或另购许可 | [broadcast.js](https://github.com/miroslavpejic85/mirotalkbro/blob/main/public/js/broadcast.js)、[server.js](https://github.com/miroslavpejic85/mirotalkbro/blob/main/app/server.js)、[mediasoup handler](https://github.com/miroslavpejic85/mirotalkbro/blob/main/app/mediasoup-handler.js) |-| [Screego](https://github.com/screego/server) | 极简屏幕分享、P2P fan-out、WebSocket 信令、内置 Pion TURN | GPL-3.0。最适合学习轻控制面和按需 TURN | [useRoom.ts](https://github.com/screego/server/blob/master/ui/src/useRoom.ts)、[ws](https://github.com/screego/server/tree/master/ws)、[turn/server.go](https://github.com/screego/server/blob/master/turn/server.go)、[NAT 文档](https://github.com/screego/server/blob/master/docs/nat-traversal.md) |-| [Tailchat Meeting](https://github.com/msgbyte/tailchat-meeting) | React 捕获生命周期与会议产品交互参考 | Apache-2.0,但媒体基于 mediasoup/SFU,不能作为当前 P2P 拓扑底座 | [ScreenShare.ts](https://github.com/msgbyte/tailchat-meeting/blob/master/app/src/features/ScreenShare.ts)、[media.ts](https://github.com/msgbyte/tailchat-meeting/blob/master/packages/sdk/src/client/media.ts) |-| [WebRTC samples](https://github.com/webrtc/samples) | 官方浏览器 API 最小示例 | BSD 风格。用于理解 API,不是产品框架 | [getDisplayMedia](https://github.com/webrtc/samples/tree/gh-pages/src/content/getusermedia/getdisplaymedia)、[peer connection examples](https://github.com/webrtc/samples/tree/gh-pages/src/content/peerconnection) |-| [PeerJS](https://github.com/peers/peerjs) | 快速 P2P 原型与简单信令抽象 | MIT。原型快,但产品最终可能需要直接控制 RTCPeerConnection 和统计 | [PeerJS server](https://github.com/peers/peerjs-server) |-| [coturn](https://github.com/coturn/coturn) | 当前 STUN-only 服务 | BSD-3-Clause。当前只启用 UDP STUN,不分配媒体 relay | [turnserver 文档](https://github.com/coturn/coturn/blob/master/README.turnserver)、[Docker](https://github.com/coturn/coturn/blob/master/docker/coturn/README.md) |-| [Peer Calls](https://github.com/peer-calls/peer-calls) | 同一应用中的 mesh/SFU 双模式 | Apache-2.0;维护速度较慢,适合参考而非首选底座 | [mesh.go](https://github.com/peer-calls/peer-calls/blob/master/server/mesh.go)、[sfu.go](https://github.com/peer-calls/peer-calls/blob/master/server/sfu.go)、[iceauth.go](https://github.com/peer-calls/peer-calls/blob/master/server/iceauth.go) |-| [Broadcast Box](https://github.com/Glimesh/broadcast-box) | 外部一对多 SFU、WHIP 推流/WHEP 播放参考 | MIT。只作单路广播研究对照,不替换当前 LiveKit route | [Broadcast.tsx](https://github.com/Glimesh/broadcast-box/blob/main/web/src/components/broadcast/Broadcast.tsx)、[simple watcher](https://github.com/Glimesh/broadcast-box/blob/main/examples/simple-watcher.html) |-| [LiveKit](https://github.com/livekit/livekit) | 当前专用 SFU、SDK 与鉴权底座 | Apache-2.0。Screener 当前只启用 LiveKit SFU/UDP;框架的其他 transport capability 不构成产品授权 | [屏幕共享](https://docs.livekit.io/transport/media/screenshare/)、[turn.go](https://github.com/livekit/livekit/blob/master/pkg/service/turn.go) |-| [mediasoup](https://github.com/versatica/mediasoup) | 强定制低层 SFU | ISC。自由度高,但房间、信令、鉴权、TURN 和 UI 都需自建 | [mediasoup demo](https://github.com/versatica/mediasoup-demo) |-| [Valve GameNetworkingSockets](https://github.com/ValveSoftware/GameNetworkingSockets) | Photon/Steam 式控制面与 P2P NAT 模型参考,不是媒体引擎 | BSD-3-Clause。其 P2P 文档同样要求信令、ICE/STUN 和 relay fallback | [README_P2P](https://github.com/ValveSoftware/GameNetworkingSockets/blob/master/README_P2P.md)、[test_p2p.cpp](https://github.com/ValveSoftware/GameNetworkingSockets/blob/master/tests/test_p2p.cpp) |--不建议新项目以休眠的 `ion-sfu` 为底座。Janus 和 Galene 均可用,但分别偏底层网关和完整会议系统,不如上述项目贴合当前边界。--## Historical 2026-08-18 Implementation Baseline--进入当时的 PoC 实现前曾核对以下官方版本和参考代码。TURN 条目只记录已放弃的 2026-08-18 baseline,不定义当前配置、实现或 roadmap:--- 本机原 Node 20 已结束维护;当前实现基线改为 Node 24 LTS。Vite 8 要求 Node `^20.19.0 || >=22.12.0`,仓库应通过 `engines`、`.node-version` 和 CI 固定受支持运行时。-- 使用 React + TypeScript 的官方 Vite SPA 模板,不引入 SSR 或全栈框架。生产环境不能使用 `vite preview`,由同一个 Node HTTP 服务提供静态构建、房间 API 与 WebSocket。-- `ws` 只用于服务端,浏览器使用原生 `WebSocket`。小信令禁用 `perMessageDeflate`、收紧 `maxPayload`,并采用官方 ping/pong heartbeat 模式。-- `ws.close()` 默认会等待关闭握手,不能用“升级成功后发送 close frame”实现公网连接硬上限。总连接和未鉴权连接容量应在 `handleUpgrade()` 前检查,超限直接返回 HTTP 503 并销毁底层 socket。-- Node 的 `IncomingMessage.url` 是未经应用路由解析的 request-target,而 WHATWG `URL` 构造器会拒绝部分输入。upgrade handler 必须捕获解析失败并关闭 socket,不能让未鉴权输入抛到 EventEmitter 顶层。-- coturn 使用 `use-auth-secret` 支持的 TURN REST 短期凭据:`base64(HMAC-SHA1(secret, expiry + ":" + subject))`。coturn 不提供 HTTP 凭据接口,必须由已鉴权的应用服务生成。-- WebRTC 会逐条验证 ICE URL,任一坏项都可能使整个 `RTCPeerConnection` 配置失败。启动预检按原始 URI 语法 fail closed,并要求 selected TURN URI 显式声明小写 `transport=udp`;配置形状验证不能替代公网 relay allocation 测试。-- Node `server.listen()` 省略 host 时可能监听未指定 IPv6 地址或 `0.0.0.0`。单机反向代理基线应显式绑定 loopback,容器或可信 LAN 才通过配置选择宽绑定;进程级 HTTP 健康检查不应同步探测 TURN 或其他外部网络。-- 截至本次复核,coturn 应使用 4.17.2 或更新补丁版本;4.17.2 修复了此前补丁版本的 UDP TTL 回归。-- MiroTalk BRO 当前 P2P 模式仍是 broadcaster 对每位 viewer 建独立连接;Screego 也采用独立 session 和 HMAC TURN 凭据。这验证了拓扑,但两者的静态/长时凭据与轻量恢复策略不直接照搬。-- Screego 的分享生命周期保持简单,当前客户端在分享停止时关闭 peers,未提供 `replaceTrack()` 换源路径,且为 GPL-3.0;本项目只借鉴其边界清晰的生命周期,不复制实现。Tailchat Meeting 使用 Apache-2.0,但其媒体生产者生命周期绑定 mediasoup/SFU;只参考捕获状态,不引入与 ADR-0001 冲突的拓扑。--新增来源,访问日期 2026-08-18:--- [Node.js release status](https://nodejs.org/en/about/previous-releases)-- [Vite Getting Started](https://vite.dev/guide/)-- [Vite static deployment](https://vite.dev/guide/static-deploy.html)-- [ws official README](https://github.com/websockets/ws/blob/master/README.md)-- [coturn 4.17.2 release](https://github.com/coturn/coturn/releases/tag/4.17.2)-- [coturn turnserver documentation](https://github.com/coturn/coturn/blob/master/README.turnserver)-- [coturn example configuration](https://github.com/coturn/coturn/blob/master/examples/etc/turnserver.conf)-- [Node.js 24 `server.listen`](https://nodejs.org/docs/latest-v24.x/api/net.html#serverlistenport-host-backlog-callback)--## 实施难度与预估--以下以一名熟悉 Web/TypeScript、具备基本网络经验的全职工程师为基准,只用于量级判断:--| 阶段 | 难度 | 预估 | 交付物 |-| --- | --- | --- | --- |-| 技术原型 | 低到中 | 3 至 7 个工作日 | Web 选源、逐观看者 P2P、基础信令、STUN、统计面板 |-| 可给朋友使用的 MVP | 中 | 4 至 8 周 | 私密房间、专用 SFU fallback、质量档位、断线恢复、音频提示、测试矩阵和部署 |-| 稳定产品化 | 高 | 2 至 4 个月以上 | 原生分享端、应用音频、硬编诊断、SFU 容量与真实网络验收、升级/安全/兼容处理 |-| Discord 级跨平台体验 | 很高 | 多人持续工程 | 原生 media engine、多捕获后端、GPU 零复制、广泛硬件与网络优化、SFU/E2EE |--最大的未知不是信令服务,而是浏览器是否在目标 GPU 上复用硬件编码、用户真实 P2P 直连率、香港/内地/海外路由和应用音频需求。第一里程碑应是一个带完整统计的原型和真实朋友网络测试,而不是先设计大规模后端。--## 最终建议--1. 首版坚持 P2P-first,但明确只服务一名 Host 加最多 20 名 Viewer;20-Viewer smoke 只验证 admission、控制面和资源上界,不把它写成任意公网画质或持续性能承诺。-2. Web 先行,目标 Windows Chrome/Edge;把 1080p60 写成 best effort,同时提供降档。-3. 保留 ordinary STUN-only 配置。Controller 对 exact logical edge 先验证 direct/STUN;需要 server-fed ingress 时复用唯一 Host publication 和精确 SFU subscription。Screener 不配置 TURN、ICE/TCP 或媒体 TCP。-4. 观看端优先做成免安装响应式 Web;分享端先 Web 验证,再按捕获/音频实测升级 Electron。-5. 产品代码优先直接使用浏览器 WebRTC API;借鉴 MiroTalk BRO 和 Screego,不在许可证未定前直接 fork GPL/AGPL 代码。-6. 每个非服务器端点使用部署权威 outbound capacity `C in {1,2,3}`,默认二;peer child 与 Host publication 消耗 sender slot,上游接收不计数。分配、恢复和 server admission 由 ADR-0005 统一约束,不从一次历史 fanout 测量推导产品上限。-7. SFU 保持一份 Host publication、逐 Viewer 精确 subscription、可逆且非整房默认;旗舰部署由 ADR-0005 控制器按 logical ingress 和 server admission 用作中央兜底。peer-assisted 若未通过逐跳重编码负载、延迟、兼容和换父门槛就整体放弃,不通过 encoded custom media、评分器、多树或自研 RTP 来挽救。+| P2P 星型 | `N * B` | 接近零 | Host sender/编码和上行随 Viewer 线性增长 |+| P2P + TURN | `N * B` | 每条 relay 约 `B` 入 + `B` 出 | 只改善可达性 |+| Peer tree | 最多约 `C * B` | direct edge 接近零 | 全房仍约 `N * B`,浏览器 relay 通常逐跳重编码 |+| SFU | 约 `B` | 约 `B` 入 + `N * B` 出 | Host 轻,服务器出口线性增长 |+| MCU | 约 `B` | 另有集中媒体流量 | 解码、合成和重编码成本最高 |++以 `8 Mbps` 为例,四个星型 Viewer 需要约 `32 Mbps` 持续 Host 上行,并在一小时内+发送约 `14.4 GB`,还未包含重传和协议开销。Peer tree 重新分配这些副本,不会消除+最后一跳的 `N * B` 守恒。原生 shared encoder 可以降低编码次数,但同样不能消除+网络副本。++标准浏览器把收到的远端 track 再发布时,通常从解码后的 raw frames 建立新的 sender+pipeline,增加 CPU、逐跳延迟和 generational loss。Encoded forwarding、striping 或+network coding 属于新的媒体数据面,不是普通 `RTCPeerConnection` 的免费能力。++## Mobile And Viewer Boundaries++- 普通移动浏览器不能被假定为可移植 Host。必须先 feature-detect+ `navigator.mediaDevices?.getDisplayMedia`,再以真实调用结果为准;桌面模式或 UA+ 不能创造平台未提供的 capture API。+- Android Chrome 和 iOS Safari 可作为普通 Viewer,但首次含声音播放、全屏、旋转、+ 安全区和原生 controls 必须真机验证。+- Page Visibility 只报告可见性。后台、锁屏、页面 freeze/discard、WebContent 回收和+ OS 内存压力可暂停视频合成、JavaScript、网络或整个页面,网页不能承诺后台转发。+- 页面恢复时应重新证明当前媒体进展;隐藏期间没有回调不等于网络或 route 已失败。+- Wi-Fi/蜂窝迁移可能改变 candidate pair,需要依赖 WebRTC reconnect/ICE restart,+ 不能按设备类型硬编码恢复路径。+- Remote Playback 规范没有给 `MediaStream/srcObject` 一个跨浏览器的电视输出合同;+ URL 型 flinging、系统镜像和 live stream 投放是不同能力。++## Codec And Quality++RFC 7742 要求 WebRTC 浏览器支持 VP8 和 H.264 Constrained Baseline 互通,但 codec 名称+不证明特定硬件 encoder/decoder、稳定帧率或低 CPU。VP9、AV1、HEVC 和硬件路径必须按+目标端点实际协商与统计验证。++可用证据包括实际 codec/profile、`framesEncoded/framesDecoded`、bitrate、resolution、+`totalEncodeTime`、`qualityLimitationReason`、implementation 和 power-efficiency 字段。+这些字段也可能缺失,缺失时保持 unknown。Simulcast/SVC 能让 SFU 选择 representation,+但不会消除 P2P 的多 sender 上行,并可能增加编码负载。++## Security Boundary++- WebRTC media 使用 DTLS-SRTP;信令仍需独立 HTTPS/WSS、Origin 校验、鉴权、消息与+ 资源上限。+- Direct P2P 会向对端网络栈暴露可达地址。mDNS candidate 或 stats filtering 不构成+ 完整的 endpoint-IP 隐藏合同;需要隐藏 IP 时必须使用中央 relay 或拒绝 direct。+- TURN/SFU 能看到流量元数据;普通 SFU 还终止两侧媒体安全会话。要防 media operator+ 读取内容,需要另行设计端到端加密、密钥分发、成员变更和丢包恢复。+- 房间 grant 与 Host token 是 bearer credentials:使用高熵随机值、有限授权、明确+ 撤销与过期,并避免出现在 query、日志、遥测、错误、Referrer 或持久明文存储。+- URL fragment 不进入 HTTP request-target,但仍会出现在地址栏、历史、扩展、截图和+ 用户转发中;它缩小服务端泄漏面,不改变 possession 即权限的事实。++## Evidence Gates++在宣称可用前,应在目标设备与真实网络上分别证明:capture settings、首帧时间、+selected pair、RTT/loss/jitter、发送与接收码率、编码/解码 cadence、CPU/GPU、后台恢复、+网络迁移和失败终态。Loopback 能验证状态机,不代表 NAT、移动生命周期或公网质量。++以下结论不能由浏览器 API 名称推出:所有网络可达、固定 1080p60、跨连接单次编码、+移动 Host、后台 relay、无线投屏、硬件 codec 或应用 E2EE。++## Primary Sources++- [Screen Capture](https://www.w3.org/TR/screen-capture/),+ [WebRTC](https://www.w3.org/TR/webrtc/),+ [WebRTC Stats](https://www.w3.org/TR/webrtc-stats/), and+ [MediaStreamTrack Content Hints](https://www.w3.org/TR/mst-content-hint/).+- [ICE, RFC 8445](https://www.rfc-editor.org/rfc/rfc8445.html),+ [Trickle ICE, RFC 8838](https://www.rfc-editor.org/rfc/rfc8838.html),+ [WebRTC transport, RFC 8835](https://www.rfc-editor.org/rfc/rfc8835.html), and+ [TURN, RFC 8656](https://www.rfc-editor.org/rfc/rfc8656.html).+- [RTP topologies, RFC 7667](https://www.rfc-editor.org/rfc/rfc7667.html) and+ [WebRTC video codecs, RFC 7742](https://www.rfc-editor.org/rfc/rfc7742.html).+- [Page Visibility](https://www.w3.org/TR/page-visibility-2/),+ [HTML media elements](https://html.spec.whatwg.org/multipage/media.html),+ [Remote Playback](https://www.w3.org/TR/remote-playback/), and+ [Web Cryptography](https://www.w3.org/TR/WebCryptoAPI/).+- [URI fragments, RFC 3986 section 3.5](https://www.rfc-editor.org/rfc/rfc3986.html#section-3.5),+ [WebSocket URL rules](https://websockets.spec.whatwg.org/), and+ [Capability URLs](https://www.w3.org/TR/capability-urls/).+- [Chromium capture architecture](https://chromium.googlesource.com/chromium/src/+/HEAD/docs/media/capture/),+ [Chrome Page Lifecycle](https://developer.chrome.com/docs/web-platform/page-lifecycle-api),+ and [Android process lifecycle](https://developer.android.com/guide/components/activities/process-lifecycle).diff --git a/docs/session-handoff.md b/docs/session-handoff.mddeleted file mode 100644index d81fbf86..00000000--- a/docs/session-handoff.md+++ /dev/null@@ -1,30 +0,0 @@-# Session Handoff--Last updated: 2026-08-25--This file is only a bootstrap pointer. Product truth lives in the linked owners.--## Resume Prompt--```text-Continue Screener from the canonical repository root:-C:\Users\TNTcraft\Documents\GitHub\Screener--Read AGENTS.md and the complete repo-tracked stop-that-shit skill first. Then-read CONTRIBUTING.md, docs/project-memory.md, docs/status.md, docs/todo.md, the-relevant requirement/design/ADR/research owner, and inspect branch/HEAD, status,-staged diff, and worktrees. Canonical main and repo truth override old branches,-worktrees, handoffs, agent memory, and chat summaries.--Current production and main identity is owned by docs/status.md. ADR-0002 owns-lightweight/stable room authority; ADR-0005 owns automatic direct/peer-to-LiveKit routing; ADR-0007-owns framework media adaptation. Current routes are sticky and quality evidence-is diagnostic only. Browser video uses the share-scoped H.264/VP8 decision with-contentHint=motion; LiveKit owns SFU representations; Screener configures no TURN-or media TCP.--Follow docs/todo.md in order. Do not run Native/executable work, broad repository-cleanup, quality-driven reparenting, or another transport unless its decision-boundary is explicitly opened. Preserve unique or dirty worktrees until merged--head, reference, and reparse audits prove cleanup safe.-```diff --git a/docs/status.md b/docs/status.mdindex a4ded5bb..070525ab 100644--- a/docs/status.md+++ b/docs/status.md@@ -69,12 +69,8 @@ This is the current execution index. Git history owns completed timelines;## Current Milestone-1. Collect annotated production freeze/pause samples from strict- `screener-v13` without active route changes.-2. Finish the Android Chrome and iOS Safari Viewer lifecycle matrix.-3. Finish representative public-network direct, peer-relay, SFU, recovery,- Pause/Resume, screen-audio, real-game A/V, and all-UDP-blocked acceptance- without adding another transport or quality controller.+The documentation truth architecture is at its acceptance boundary. Product and+source implementation remain parked pending owner direction.## Active Boundaries@@ -85,11 +81,12 @@ This is the current execution index. Git history owns completed timelines;- Current-path quality is diagnostic. High loss, RTT, jitter, low bitrate,resolution, FPS, or freeze counters do not trigger relay abdication or parentswitching.+- Repository simplification does not change or deploy product behavior beyond+ deleting proven dead private surfaces.- Native/executable senders, shared encode, distribution packages, broad UI- polish, bilingual support, and repository-wide simplification are outside the- current release.+ polish, and bilingual support remain outside the current release.## Current Hold-No source or deployment P0/P1 is open. Representative real-network and mobile-physical evidence remains required before route acceptance is complete.+No source or deployment P0/P1 is open. Product evidence work is parked in TODO+while the truth and mechanism ownership is simplified.diff --git a/docs/todo.md b/docs/todo.mdindex 5784428f..3c1c6f6f 100644--- a/docs/todo.md+++ b/docs/todo.md@@ -2,90 +2,55 @@Last reviewed: 2026-08-27-Only **Now** is executable. A branch, old experiment, observation, or accepted-later topic is not implementation authority by itself.+Only **Now** is executable. Observations, old branches, experiments, and parked+topics are not implementation authority.## Now-1. **Quality-route evidence and shadow calibration.** Collect annotated- production samples from the deployed strict `screener-v13` Browser/server- quality shadow before accepting an active trigger,- probation, restore or cooldown policy. Shadow evidence must not alter facts,- capacity, routes or SFU usage.-2. **Mobile Viewer lifecycle.** Run Android Chrome and iOS Safari matrices for- autoplay gesture, foreground/background audio, foreground video recovery,- lock/page reclamation, rotation, Wi-Fi/cellular migration, and assigned-relay- survival or controller recovery. Web does not promise background video or- relay execution after OS suspension.-3. **Finish real-network route and media acceptance.** Exercise direct peer,- Browser relay, SFU, relay-ingress recovery with subtree retention,- disconnect/capacity drain, Pause/Resume, source replacement, screen-audio- continuity, and real-game A/V sync across representative IPv4/IPv6,- Wi-Fi/cellular, and Host/Viewer TUN/VPN cases. Verify two simultaneous rooms- can own independent SFU publications. Include an all-UDP-blocked case and- weak-network audio after SFU RED was disabled. Every exhausted path must end- in bounded wait/failure without TURN, TCP probing, NAT classification,- guessed candidates, or another watchdog.--## Accepted Later Roadmap--1. **Platform output only when real.** Revisit AirPlay/Cast only when a target- browser and physical receiver prove the live `MediaStream` contract. System- mirroring remains external.-2. **Public-server one-click package.** After functional and real-network work,- package the exact application, STUN/SFU, reverse proxy, secrets, and health- checks for a user-owned public server. Do not call a partial installer ready.-3. **Fully local one-click package.** Package Windows/macOS/Linux Host capture,- application server, and local state without requiring source or Node. Report- public-origin, TLS, gateway, NAT, and firewall limits honestly.-4. **Native Host and shared encode, Windows first.** Productize only after real- capture, hardware-only encode, audio, identity, RTP/RTCP feedback, resource,- packaging, and licensing gates pass. Browser Host/relay keeps standard- per-`RTCPeerConnection` encoding.-5. **Whole-product UI and bilingual decision.** Once media and route behavior- stabilizes, review copy, responsive hierarchy, visual consistency, restrained- motion, bundle/rendering cost, and Chinese/English scope once as a whole.- Terminal and error views should retain the global header and an obvious way- back home. Ordinary screen-specific edits do not create parallel documentation.-6. **Client-input security review.** Inventory HTTP and WebSocket inputs once as- a whole: strict schemas, authentication, authorization, rate and body bounds,- resource effects, error disclosure, logging, and secret handling. Begin- read-only and add no parallel security framework without a proven gap.-7. **Repository simplification audit.** After the Browser, route, room, and- physical-media checkpoints settle, inventory components, configuration,- migrations, timers, compatibility paths, tests, and truth duplication using- the [maintenance review](./maintenance.md#机制减负审查). Begin read-only and do- not turn it into a broad refactor. The current read-only scan confirmed- coarse `mediaAssignment` wire residue, legacy SFU room-name acceptance,- and duplicated teardown/test/browser-gate owners as the bounded starting- set; it did not authorize unrelated cleanup.-8. **Per-share peer-only mode.** Add one default-off Host pre-share checkbox,- locked while sharing. Enabled rooms retain the automatic direct/peer graph- but exclude SFU candidates, configuration and resources, then end in the- existing bounded failure when no Peer route works. This does not claim- cryptographic protection from the operator serving the Web application;- application-layer E2EE remains a separate decision.+No product or source implementation is open after the documentation checkpoint.+Await owner direction.-## Product Decision Needed+## Parked Repository Work-| Item | Decision |-| --- | --- |-| Repository and distribution license | Decide before public release or package distribution. GPL/AGPL implementations remain research-only until then. |-| Active quality-route action | Shadow evidence is authorized, but active changes are not. Production samples must first settle the trigger, probation, one-restore and cooldown boundaries. Any accepted exact-child reparent, relay abdication/drain or Host convergence onto one SFU publication must reuse the existing single graph/operation and preserve SFU-fed Viewer relay; no second optimizer or periodic rebalancer is allowed. |+1. **Bounded mechanism simplification.** Remove only the proved zero-consumer or+ duplicate owners: coarse `mediaAssignment` wire residue, legacy SFU room-name+ acceptance, orphan `scripts/browser-codec-preflight.ts`, and the access gate's+ test-title scan. Keep the production+ `src/client/webrtc/video-codec-preflight.ts`, live internal media-assignment+ helpers, and destructive-path safety gates.-## Evidence Boundaries+## Parked Product Work-- Desktop Host background/minimized capture remains diagnostic until a current-- production real-game reproduction correlates capture, outbound, inbound,- decode, and CPU/GPU. Viewer resume correction is not a keepalive guarantee.-- Synthetic and loopback tests validate invariants, not target-network quality,- latency, capacity, mobile lifecycle, or endurance.-- Open Native and packaging branches are retained evidence/candidates, not- current releases.--## Candidate Handling--- Preserve dirty or unique worktrees and open stacks until reviewed. Never- import old truth wholesale.-- Sample worktree and branch state immediately before cleanup rather than- maintaining a permanent inventory here.+1. **Quality-driven route selection.** Strict v13 evidence remains diagnostic.+ Any future decision must use the existing graph/operation and must not add a+ score, all-pairs probe, periodic rebalancer, or ordinary SFU preference.+2. **Mobile Viewer lifecycle.** Run Android Chrome and iOS Safari matrices for+ autoplay, background audio, foreground recovery, lock/page reclamation,+ rotation, network migration, and relay survival.+3. **Representative network acceptance.** Complete public-network direct,+ Browser relay, SFU, recovery, Pause/Resume, screen-audio, real-game A/V,+ two-room SFU, 20-Viewer endurance, and all-UDP-blocked bounded failure.+4. **Per-share peer-only mode.** Add one default-off pre-share Host setting that+ excludes SFU for that share and ends in the existing bounded failure.+5. **Whole-product UI and bilingual decision.** Review copy, responsive+ hierarchy, visual consistency, restrained motion, rendering cost, terminal+ navigation, and Chinese/English scope once media behavior stabilizes.+6. **Client-input security review.** Audit HTTP/WebSocket schema, auth,+ authorization, rate/body/resource bounds, errors, logs, and secrets without+ adding a parallel security framework.+7. **Public-server package.** Package the exact Web/signaling, STUN/SFU, proxy,+ secrets, health, and recovery contract for a user-owned server.+8. **Fully local package.** Package Host capture, application server, and local+ state for Windows/macOS/Linux with honest TLS, gateway, NAT, and firewall+ limits.+9. **Native Host and shared encode.** Revisit Windows first only after capture,+ hardware encode, audio, RTP feedback, resources, packaging, licensing, and+ Browser interoperability are proved.+10. **Platform output.** Revisit AirPlay/Cast only when a target Browser and+ physical receiver prove the live `MediaStream` contract.++## Decision Needed++- Choose the repository and distribution license before public release or+ package distribution. GPL/AGPL implementations remain research-only until+ then.diff --git a/docs/verification-status.md b/docs/verification-status.mdindex 7cba63be..70ad5310 100644--- a/docs/verification-status.md+++ b/docs/verification-status.md@@ -2,132 +2,76 @@Last updated: 2026-08-27-This ledger records evidence that still changes how current source or production-may be interpreted. Git and pull requests own routine completed checks.--## Current Production Identity--- Production runs exact application/runtime revision- `73ed920a229bfc64c89b97045c00d6cd75216f3a`, release `73ed920`, wire- `screener-v13`, from `/opt/screener/releases/73ed920`.-- Runtime tar SHA-256:- `351053e497e8eee17956f4cec86305b05d805c80deb40b2cf4cd2668eaf08583`.- The 41-file manifest SHA-256 is- `bb993950a30a0b99b9b6185aa13777edcccbdcdaebdfb1b05b3c3499a1e78479`.-- Public Browser asset `assets/index-CaM3Pn5_.js` has SHA-256- `3c64cd75a7d67716f7600465a1742b1c02f3b00e71a1039649604aaf6d08f816`.- Public `/healthz` returns 200. Release postflight found Screener, LiveKit,- coturn, and nginx active with zero restarts.--## Completed Product Evidence--- Strict `screener-v13` rejects stale Browser/executable wires before room- authority. Lightweight and SQLite-stable rooms, 24-hour dormant leases,- room-lived Viewer grants, `open | private` code entry, invitation-only private- rooms, password entry, grant rotate/revoke, atomic room replacement and- `ROOM_NOT_FOUND` have passed source gates. Production stable mode retained an- exact Host authority across a controlled restart. A current-production- restart also preserved the Host-owned capture and restored Viewer media- without refreshing either page.-- Endpoint capacity `1/2/3`, default `2`, one active upstream, acyclicity,- source reachability, deterministic parent order, exact candidate identity,- transport-connected wake extension, first-decoded-frame commit, strictly newer- rollback, bounded resource accounting, SFU admission, and delete-plus-absence- release have focused unit and controller coverage.-- Controlled Chrome routing proved direct prepare failure, rollback, SFU- prepare, exact first-frame ready, SFU commit, and continuing UDP media without- external ICE servers on Browser LiveKit PCs. This does not replace public- heterogeneous-network recovery evidence.-- Chrome direct and Browser-relay VP8 measurements reached about 60 fps after- stock bandwidth-estimation warm-up. Pinned LiveKit client `2.22.0` and server- `1.13.5` separately proved native lower/higher screen-share representation- selection with Dynacast and server send-side BWE.-- Chromium 151's Windows backends and exact Chrome fake-monitor getDisplayMedia- evidence close the measured Chrome VP8 path as software. Short local controls- held 1080p30, while 1080p60 was primarily bandwidth-limited and spatially- adapted. Edge and real-game contention remain open in realtime-quality research.-- The content-independent sender gate selected VP8 on the measured Chrome 151- AMD path and H.264 on Chrome 153 NVIDIA with both moving and static shared- content. Static content therefore no longer prevents a codec decision; these- two local cohorts do not replace broader real-game/device acceptance.-- Direct, Browser-relay, and SFU paths advanced video plus screen audio at- 64/128/192 kbps ceilings and after source replacement. The old constant- active-audio `1 kbps` display is closed. Exact SFU weak-network behavior after- RED was disabled remains open.-- Browser SFU publisher/subscriber PCs use empty external ICE-server lists while- ordinary peers retain deployment STUN. The reported Host/Viewer TUN conflict- was closed by that isolation without adding TURN or TCP media.-- Password-KDF capacity now fails before room or SQLite mutation; route terminal- identity comes from the controller; Host child creation is assignment-fenced;- explicit SFU refresh has a typed failure path; Viewer access outcomes remain- exact; and Host quality intent survives signaling interruption.--## Current Source Evidence--- Canonical source and production use the strict-v13 application tree deployed- from `73ed920`. The adaptive H.264/VP8 sender- decision with `contentHint = "motion"` reapplies the- selected video profile after answer negotiation, leaves SFU representation- construction to pinned LiveKit, keeps Dynacast/send-side BWE, disables- AdaptiveStream, and disables SFU audio RED.-- The local `VP8 | Auto | H264` Host selector is locked to a share generation;- Viewer relays remain Auto and no codec wire state, cache, parallel media or- active-edge switching exists.-- Viewer page-resume decoded-stall rebaselining, current-frame presentation- authority, hidden-page stall suppression, retryable failure reporting, native- controls, and same-route manual reconnect are current source behavior. Mobile- physical evidence remains open.-- The evidence-only quality shadow accepts only exact foreground presentation- windows with decoded progress, keeps one bounded fresh aggregate per current- child, and exposes it through the Host-only anonymous route snapshot. It does- not change route facts, capacity, candidate order, SFU admission or reconcile.-- An isolated current-production direct-P2P control proved the strict-v13- aggregate across bounded CDP loss pulses. Freeze response was non-linear and- the longest all-drop cell crossed into route recovery, so the result validates- collection but supplies no active threshold; exact evidence is recorded in- [realtime quality research](./research/realtime-quality-adaptation.md#strict-v13-production-shadow-control).--## Open Physical Gates--### Route And Network--- Repeat direct, peer-relay, SFU, relay-ingress recovery with subtree retention,- disconnect/capacity drain, and Pause/Resume on representative IPv4/IPv6,- Wi-Fi/cellular, and Host/Viewer TUN/VPN networks.-- Verify all-UDP-blocked networks reach bounded explicit failure. No TURN,- ICE/TCP, media TCP, TLS relay, NAT classification, port prediction, or TCP- probe is authorized.-- Run the 20-Viewer public-network capacity/resource/endurance gate. Local or- synthetic 1:20 control evidence does not establish target-network quality.--### Media Quality--- Measure real games at 720p30, 1080p30, and 1080p60 across weaker Hosts and- actual Browser encoder implementations. Correlate capture, outbound, inbound,- decode, CPU/GPU, and A/V timing.-- Verify pinned LiveKit default representation behavior on exact production- under constrained and unconstrained subscribers without adding an application- layer selector.-- Verify weak-network screen audio and A/V synchronization after RED was- disabled, including concealment/FEC evidence where exposed.--### Lifecycle--- Desktop Host background/minimized capture remains unconfirmed. A short- current-Chrome window-capture screening did not reproduce an immediate drop;- a current-production real-game reproduction must separate Host page, captured- surface, capture, encoder, path, and Viewer behavior.-- Android Chrome and iOS Safari still need autoplay, background audio,- foreground video recovery, page reclamation, rotation, network migration, and- assigned-relay survival tests. Web does not promise background video or relay- execution after OS suspension.+This file owns only cross-module physical evidence that still changes how the+current product may be described. [Status](./status.md) owns exact source and+production identity; product modules and ADRs own accepted behavior; tests and+Git own completed implementation evidence.++## Route And Network++Still required on representative public networks:++- direct Host-to-Viewer P2P;+- Peer-fed and SFU-fed Browser relay, including a second-level child;+- Host and Viewer TUN/VPN cases;+- relay-ingress failure with subtree retention;+- disconnect and effective-capacity drain;+- two simultaneous rooms with independent SFU publications;+- measured endpoint upload and server ingress/egress during steady routing and+ make-before-break overlap;+- 20-Viewer queue tail, route depth, resource use, and endurance; and+- all-UDP-blocked bounded failure.++The route model, capacity `C=1..3`, first-frame commit, rollback, SFU admission,+and managed-room lifecycle have automated invariant coverage. That coverage does+not prove target-network quality, latency, or interoperability. See+[ADR-0005](./adr/0005-automatic-hybrid-media-routing.md) and the+[routing contract](./product/routing-transport.md).++## Media Quality++Still required:++- real games at 720p30, 1080p30, and 1080p60 on weaker Hosts;+- actual H.264/VP8 encoder paths and sustained CPU/GPU contention on Windows,+ macOS, and Linux;+- mixed P2P/SFU quality and recovery on heterogeneous public networks;+- screen-audio presence, stereo correctness, weak-network behavior, and A/V+ synchronization after SFU RED was disabled; and+- long-running encode/decode cost, thermals, frame delivery, and resource+ admission at the 20-Viewer bound.++Current controlled Browser evidence supports the H.264/VP8 gate, `motion`+content intent, startup-quality workaround, and LiveKit-owned SFU adaptation.+It does not establish a quality-driven topology trigger. See+[media quality](./product/media-quality.md) and+[realtime quality research](./research/realtime-quality-adaptation.md).++## Browser Lifecycle++Still required on physical Android Chrome and iOS Safari:++- autoplay and user-gesture recovery;+- foreground/background audio;+- foreground video recovery after background or lock;+- page reclamation and BFCache behavior;+- rotation and viewport changes;+- Wi-Fi/cellular migration; and+- survival or controller recovery when the mobile Viewer is a relay.++Desktop Host background/minimized capture also remains unconfirmed under a+current-production real game. Web code cannot promise OS background execution,+page retention, or capture keepalive. See+[presentation and lifecycle](./product/presentation-lifecycle.md) and+[background capture research](./research/browser-background-capture.md).## Interpretation Rules-- Configuration and loopback prove neither target-network quality nor hardware- acceleration.+- Configuration, unit tests, loopback, and synthetic signaling prove invariants,+ not target-network or device behavior.- Missing RTCStats fields are unknown, not zero.-- Current-path quality is diagnostic and cannot authorize active parent change.-- A Browser page lifecycle correction is recovery logic, not keepalive.-- Native, packaging, and broad UI work remain outside these gates until their- TODO decisions are opened.+- Requested quality values are ceilings; actual sender/receiver stats are truth.+- A page-lifecycle correction is recovery logic, not a keepalive guarantee.+- Expensive evidence remains applicable only while its protocol, component,+ configuration, environment, and acceptance boundary remain materially the+ same.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"deleted file mode 100644index f5e64e30..00000000--- "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"+++ /dev/null@@ -1,433 +0,0 @@-# 屏幕共享 WebRTC PoC 方案设计--## 2026-08-18 14:45--状态:canonical source 与 production 已部署唯一 strict `screener-v13` 的 evidence-only quality shadow;旧页面在 authority 前拒绝,不保留 v12 parser。当前已实现每分享代次的 H.264 sender gate 与 VP8 fallback、本地 pre-share `VP8 | 自动 | H264` selector、可选 SQLite stable room authority、无期限 preferred code 和换房控制;这些不新增 codec wire、自定义 SFU layer list或应用媒体质量 controller。Video 使用 `contentHint = "motion"`,audio 使用 `music`。SFU 由 pinned LiveKit 默认 representations、Dynacast、server send-side BWE 和 disabled AdaptiveStream 拥有质量适配;screen audio 使用 64/128/192 kbps ceiling、stereo、DTX off 与 RED off。精确执行状态由 `docs/status.md` 持有。--## 目标与边界--产品面向一名分享者和小范围可信朋友的低延迟游戏画面分享。观看端使用普通桌面或手机浏览器;每条普通媒体边独立 ICE 并优先 direct/peer UDP。所有非服务器端点共享一个服务端权威稳态 outbound media-copy capacity,由唯一部署项 `ENDPOINT_MEDIA_COPY_CAPACITY` 配置,默认 `2` 且只接受 `1`、`2` 或 `3`;peer child 或 Host publication 各消耗一份,upstream receive 免费,角色、浏览器、UA、设备和页面可见性不改变该值。活动媒体图无环,每名 Viewer 同时至多一个 active upstream。不兼容的 capacity 能力与单一 signaling wire 原子升级,旧客户端在取得房间 authority 前 fail closed。SFU subscriber egress、temporary overlap 和 direct-to-SFU fallback sequence 由 ADR-0005 的整体模型统一定义。--本阶段必须形成完整的最小纵向链路:--- 分享者主动选择屏幕、窗口或标签页,并请求可用音频;-- 创建四位随机数字房间;production site access 密码严格控制建房/发布和 code-only 观看,默认 room-scoped capability link 让受邀 Viewer 直接观看;轻量模式把房间权威留在当前进程,可选 SQLite stable 模式只持久化房间权威 aggregate;-- 每名观看者拥有独立的 `RTCPeerConnection`;-- 当前 production 要求 STUN,普通 peer ICE 只发 STUN servers;source 与 production 的 Browser SFU PC 使用空 ICE-server 列表、保留 LiveKit signaling 的 UDP candidates 并由标准 ICE 选择;-- 展示连接状态、direct/relay、RTT、实际码率、帧率和丢包等数据;-- 超过部署配置上限的观看者被明确拒绝,不静默超载;-- 在代码、测试和真实浏览器验证完成前,不宣称达到延迟或画质目标。--当前不实现账号数据库、通用业务数据库、Redis、语音聊天、Electron、原生捕获、PWA、录制、遥测平台或多地区调度。可选 SQLite 只保存 ADR-0002 定义的房间权威,不保存参与者、路由或媒体;peer-assisted/SFU candidate 只通过 ADR-0004/0005 的现有窄 owner 扩展,不引入第二套路由器或通用优化框架。--## 技术栈决策--| 层 | 选择 | 原因 |-| --- | --- | --- |-| Web 客户端 | React 19、TypeScript、Vite 8 | 同一套响应式界面覆盖分享者与桌面/移动观看者;官方模板成熟 |-| 媒体 | 浏览器原生 WebRTC 与 Screen Capture API | 不引入 PeerJS/simple-peer,保留对 ICE、sender 参数和 stats 的直接控制 |-| 应用服务 | Node.js 24 LTS、TypeScript、原生 HTTP、`ws` | 服务只负责小流量控制面;前后端可共享协议类型和校验 |-| 房间状态 | 进程内 `RoomStore` | 重启本已中断媒体;新增房间号和邀请的有界回退不值得持续承担数据库、迁移和恢复分支 |-| 运行时校验 | Zod | WebSocket 和 HTTP 输入不可信,需要与 TypeScript 类型一致的运行时边界 |-| 静态文件 | `sirv` | 生产环境由同一 Node 进程提供前端构建结果,避免引入完整 Web 框架 |-| 地址发现 | coturn 4.17.2 或更新补丁版本 | 只提供 STUN/UDP;tracked 配置使用 `stun-only`、`no-tcp` 与 `no-tls`,不分配媒体 relay |-| 测试 | Vitest | 覆盖纯逻辑和 Node 集成测试;真实媒体能力另做浏览器/网络矩阵 |-| TLS 入口 | Caddy 或 nginx,由部署者选择 | 统一 HTTPS/WSS;不把证书管理写进应用进程 |--不选 Go 的原因是 Node 不承载正常情况下的媒体流量,换语言不会减少分享者上行或 SFU 成本。不选 C++ 的原因是浏览器能力尚未被实测证明不足;只有捕获、应用音频或硬件编码出现明确瓶颈时才增加原生 helper。--最终分发有两个独立产物。公网服务器一键部署包面向用户自有服务器,编排同一版本的 Web/信令应用、易失房间状态、STUN/SFU 和反向代理,不建立第二套应用;域名、TLS、secret、端口、容量、健康检查和恢复继续 fail closed。普通 app-only 更新先验证新的不可变 artifact 再原子切换,切换前 application release 只保证保留到有限 health/postflight 完成;之后没有保留合同,也不作为维护中的备份。只有任务实际改动基础设施、配置、secret、持久或不可逆状态时,才为被触及表面定义恢复。它不提供托管基础设施,也不把占位配置写成可用服务。--本地自包含一键包在分享者电脑上同时承载 Host、当前 Web/信令应用服务器与本地状态,Viewer 仍使用普通浏览器。它不调用任何外部 Screener、STUN、SFU、隧道或 relay 服务,并复用唯一协议、房间、鉴权和路由实现;公网覆盖取决于本机入口、可信 origin、网关映射和 NAT 条件,direct P2P 可用时保留,受限时明确失败。具体 runtime、进程边界、签名、更新、证书、网关与 NAT 方案等当前功能和真实网络 TODO 完成后再由证据确定,不得先用某个打包器或自动映射技巧反向定义产品。--## 系统结构--```mermaid-flowchart LR- H[分享者 Web] -->|HTTPS: 建房| A[Node 应用服务]- H <-->|WSS: 鉴权与信令| A- V[观看者 Web 1..N] <-->|WSS: 鉴权与信令| A- H <-->|ordinary direct/peer DTLS-SRTP UDP| V- H -.经 controller 授权.-> S[有界 SFU 资源]- V -.经 controller 授权.-> S- H -.地址发现.-> T[coturn STUN-only]- V -.地址发现.-> T-```--每个观看者的候选检查和最终路径互不影响;健康 direct/peer 子树不会因另一条弱路径被全房迁移。Node 房间服务不复制、解码或转发媒体。SFU 只按 ADR-0005 的明确 owner、edge 与 deployment budget 参与,不能由图中的连线另行推导 fallback 顺序或 server fanout。--## 代码布局--```text-src/- client/ React 页面、捕获、PeerConnection、stats 和样式- server/ HTTP/WS 入口、配置、房间和静态 STUN ICE snapshot- shared/ 信令 schema 与跨端类型-tests/ RoomStore、ICE 配置、协议和 WebSocket 集成测试-```--保持单个 npm package。出现第二个可独立发布的程序前,不建立 monorepo 或 workspace。--## 房间与访问控制--`SITE_ACCESS_PASSWORD` 是简单的部署访问口令,不是 Viewer 密码或账号凭据。production 启动时必须配置;本地开发/测试可显式关闭。非空值必须包含 8 至 128 个可见 ASCII bytes(`0x21` 至 `0x7e`),并作为不复用 LiveKit、TLS 或其他凭据的独立 secret。`POST /api/site-access` 只在严格允许的 Origin 下接收 `Authorization: Bearer`,成功后签发 12 小时的无状态 site-access cookie:值只包含版本、到期时间和 HMAC-SHA256 签名,不创建账号、JWT 或服务端 session Map。cookie 使用 `HttpOnly`、`SameSite=Strict`、`Path=/`、有限 `Max-Age`;HTTPS 生产环境使用 `Secure` 和 `__Host-` 前缀。`POST /api/rooms` 只认该 cookie,不接受同一 Bearer 旁路。原子 deployment change 在 nginx 为该 admission endpoint 配置 per-source `limit_req`,初始边界为 `5r/m`、`burst=5 nodelay`;超限返回通用 429,允许到达 Node 的错误 secret 使用常量时间比较和统一 401。limiter 只使用 nginx shared memory,不新增 IP 持久化/日志字段;Node 不建立 IP key/LRU/session table,并保留现有全局/未鉴权连接上限。删除旧 `ACCESS_PASSWORD`、`/api/session` 与旧 cookie;旧环境变量出现时 fail-fast。--WebSocket upgrade 无法预知后续 role,因此仍允许没有 site-access cookie 的合法 grant Viewer 完成握手;握手前严格校验 `/signal` 无 query、Origin allowlist、总连接数和未鉴权连接数,并把当次 cookie 校验结果保存到 socket state。五秒内的第一条 `authenticate` 完成授权:Host 必须同时拥有 upgrade 时有效的 site-access 状态和当前房间 `hostToken`;Viewer 必须拥有目标房间当前 digest 对应的 grant,或者先通过 site access 再按 `open | private` code-only policy 校验。site-access cookie 只允许进行 code-only 尝试,不能替代 grant/房间密码;Viewer grant 也不能用于 HTTP 建房、Host role、其他房间或其他操作。--Viewer grant 与 code-only 入口是两个正交维度。每个房间用 `randomBytes(16).toString("base64url")` 生成 128-bit、22 字符 room-scoped opaque grant,服务端只在该 exact room incarnation 内保存完整 grant 的 SHA-256 摘要并用定长比较验证。grant 不编码版本、房间号或到期时间,也没有独立 expiry;它随房间存在,并在房间回收、进程重启、rotate 或 revoke 时失效。同号新房间生成新 digest,旧链接不能进入。Host 的主分享动作始终复制 token-bearing invitation;即时清退使用 rotate/revoke。--code-only policy 使用单一 `open | private` 状态:`open` 是无房间密码的默认值;`private` 在未配置密码时拒绝全部 code-only 请求,只允许有效 grant,配置密码后才接受已通过 site access 且密码匹配的 Viewer。两种状态都不改变有效 grant 的 exact-room Viewer authority,也不建立目录、账号、ACL 或额外媒体容量。Host 可独立改变 code-only policy、设置/替换/移除密码,以及 rotate/revoke grant;移除私密房间的密码会回到仅邀请可入,而不会切换为公开。--房间准入管理统一使用同源 `POST /api/rooms/{roomId}/access`:site-access cookie 与 `Authorization: Bearer {hostToken}` 共同授权一个受 schema 约束的 policy、password、rotate 或 revoke 动作。该控制面在分享活动和休眠期间语义相同,不建立 Host participant/WebSocket/media route,不改变 `sharingActive` 或 dormant lease;rotate/revoke 的现有强撤销副作用保持不变。--Host 的同源 `localStorage` creation profile 保存显示名、code-only policy 和可选房间密码,使 ownership 失效或租约过期后的下一次显式分享可原子应用同一偏好。建房响应仍返回实际 `roomLeaseSeconds` 并仅由 Host ownership/服务端房间生命周期使用;独立 preferred-room 记录只保存上次实际分配的四位号码,不保存时间、不运行续写 interval,也不证明或延长服务端租期。旧 ownership 过期/失效后始终请求该号码,服务端只在空闲时采用,否则随机分配并让客户端覆盖本地偏好。该密码只保存在 Host 浏览器;不进入 Viewer 浏览器、URL/query/fragment、cookie、日志或错误。建房/更新请求通过 HTTPS 把明文短暂交给服务端,服务端使用 Node 标准异步 `scrypt` 固定 `N=16384,r=8,p=1`、16-byte 随机 salt 和 32-byte verifier;稳定模式只持久化这 48-byte verifier material,轻量模式只保存在当前 RoomStore。进程级 gate 最多执行 2 个、等待 16 个派生,队满即有界失败;任务开始和提交前都复核当前 Host authority 与 room material。不存在、已回收或已过期房间使用 `ROOM_NOT_FOUND`;现存房间的未配置/错误密码和正确密码后的满房使用 `ROOM_ACCESS_DENIED`。--邀请使用 `/r/{roomId}#v={grant}`。RFC 3986 要求 fragment 在 dereference 前由 user agent 分离,因此 HTTP request-target 与反向代理 access log 看不到它;WHATWG WebSocket 还明确拒绝含 fragment 的 URL。客户端只从页面 URL 严格解析一次,把 grant 写入 `screener:viewer-grant:{roomId}` 的 `sessionStorage`,随即以 `history.replaceState` 把地址栏替换为 canonical `/r/{roomId}`;刷新和页面内 WSS 重连继续使用该页面会话的值。Host 建房/rotate 收到的 raw grant 同样只在内存和 room-scoped `sessionStorage` 中保留,用它临时构造复制链接;`localStorage` 的 room ownership 只包含 canonical URL、room ID、Host token 和期限。grant 不进入 cookie、query、WebSocket URL、Referrer、日志或错误。生产继续发送 `Referrer-Policy: no-referrer`;fragment 与该 header 降低传输泄漏,但不能防止原邀请消息、浏览器扩展、截图或用户转发,UI 必须把链接称为访问凭据。--房间只有一个权威模型和两种存储模式。进程启动时以 `1000..9999` 建立空闲码池,并先扣除稳定模式恢复的未过期房间;创建房间可携带一个严格四位 `preferredRoomId`,若它仍在空闲池则以同一个 swap-remove 取走,否则用加密随机索引分配,释放时放回。偏好请求不预占、不替换现存房间,也不改变新房凭据生成。固定 9000 个活动房间容量不需要碰撞重试、递增身份、独立房间上限或数据库序列。--`ROOM_LEASE_SECONDS` 默认 86400。RoomStore 对连接中的 Host 不执行到期;Host 明确停止或连接消失时将 `expiresAt` 设为 `now + lease`,同一 Host token 在期限内重新鉴权并分享时续租,Viewer 活动不修改期限。清理循环删除 dormant expired room、关闭其 session/route/resource 并把号码归还空闲池。`ROOM_DATABASE_PATH` 缺失时全部 authority 只在内存;配置绝对文件路径时,一个 exact-version `node:sqlite` owner 事务持久化 roomId、Host/grant digest、authorization generation、policy、可选 verifier 和 lease。启动删除过期行,保留 dormant absolute deadline,并把 crash-active 行转换为 `startup now + lease`;participant/session/share/pause/quality/codec/route/SFU/stats 一律不恢复。错误 application id、schema、row、路径或第二 owner 在 signaling/LiveKit 前 fail closed,不维护旧 schema reader 或 migration chain。所有房间继续生成 256-bit Host token,Host 浏览器保存 raw token,服务器只保存摘要;不使用 IP、UA、设备信息或浏览器指纹认领。--rotate/revoke 是 grant 路径的强撤销:服务端先在 RoomStore 中原子提交新 digest/authorization generation(稳定模式同一 SQLite transaction),再清除 Viewer grace、连接代次与路由状态,向 Viewer 发送通用访问已撤销终态使其立即关闭接收 `RTCPeerConnection`/媒体并停止重连,同时让每个 Host/relay/SFU upstream owner 关闭旧代次发送边,最后关闭 Viewer socket。不能只断 WSS,因为健康 P2P 可在信令断开后继续播放。rotate 生成并仅返回一次新 grant;revoke 写入没有对应 raw grant 的 fresh random locked digest。code-only policy 和密码保持独立;其变更只影响以后 code-only admission,除非 Host 明确执行强撤销。服务端永不返回现有 grant 明文;丢失 Host 标签页中的 grant 时只能 rotate。--房间号控件在复制按钮左侧提供换房 icon。它携带 exact Host token 与当前 creation profile 请求一个保证不同的新房间;服务端先完成新密码 material 与凭据生成,再以一个 RoomStore transaction 提交新 room 并删除旧 room,随后复用正常 abandon lifecycle 清除旧 session、route 与 SFU resource。提交前失败保持旧房不变;成功后活动分享结束、所有旧访问失效,客户端写入新 ownership、邀请和无期限 preferred code,不迁移旧媒体或自动重开 capture。--房间规则:--- 一名在线分享者、最多 `20` 名 authenticated Viewer;房间 admission 与 endpoint/SFU capacity 分离;-- 分享者明确停止或捕获轨结束时停止当前发布、通知观看者进入等待并开始 dormant lease,不立即删除房间;host 信令短断先交给既有恢复,在租期内仍可用同一 Host token 续租;-- 活动分享不因租期到达而删除;dormant 房间过期后拒绝新连接、通知现有参与者、清理 route/resource 并释放号码;-- 设置不超过四位号码池的全局房间上限;进程重启清空全部房间,不恢复任何 ownership、grant 或密码状态;-- 单个服务器内存控制面保存当前 room/participant/authorization/signaling 状态,但不记录 SDP、ICE candidate、IP 地址或媒体;媒体面继续按 P2P-first 图分布,不把媒体压力移到应用服务器。--客户端用 `sessionStorage` 保存随机的 128-bit `clientId`,作为当前标签页内稳定的参与者 key。同一 role/clientId 的新 WebSocket 会原子替换旧 socket;观看者断线后保留五秒 grace,期间不发送 `peer-left` 且 `peerId` 不变,重新鉴权时重发幂等的 `peer-joined`,超时才释放名额。host 鉴权或重连后,`authenticated` 携带包含 grace 成员的权威 viewer ID 列表供客户端删除已离开的 peer,服务端再重放当前在线观看者的 `peer-joined`,因此观看者可以先于 host 打开邀请,host 离线期间的离开也不会遗留幽灵连接。--显示名是独立的本地偏好:同源 `localStorage` 只保存浏览器输入,存储不可用时静默退回内存 fallback;服务端只把参与者的规范化名称挂在当前 authenticated socket state,断线即丢弃,不进入 RoomStore durable state 或日志。shared schema 先做 NFC、合并 Unicode space separators、去除边缘空格,再限制为 1 至 24 个 Unicode code points,并拒绝控制字符、行/段分隔符、BOM、双向控制符和孤立 surrogate;未设置时 Viewer 使用通用“访客”,Web Host 可由 room-scoped stable client ID 生成本地 fallback。普通多语言文本、组合字符和 emoji 仍可用。--Web Host 在 `authenticate` 中显式发送 `viewerPresence: true` capability,Viewer 也可显式订阅同一 participant snapshot;Native sender 不在 accepted Browser wire 内并在 authority 前拒绝。两端可在 `authenticate.displayName` 发送名称,并以 `set-display-name` 更新当前会话。服务端只向已订阅的 Web participant 发送完整 `viewer-presence` snapshot,列表严格来自当前带 sessionId 的在线参与者,不含五秒媒体恢复 grace 成员;条目用 `role` discriminator 区分 Host/Viewer。加入、离线、会话替换、改名和 active route 改变都会重发快照;该只读广播不调用 connect/reconcile,也不建立任何媒体边。Host 的“在线”Viewer 总数只取 Viewer 条目数;最多两条本机媒体快照只补充当前以 Host 为 active upstream 的连接指标。--每个 presence 条目包含 `role`、`peerId`、`displayName` 和服务端 active assignment 的精确 `upstream`:Host 为 `none`,Viewer 为 `none | peer(peerId) | sfu`。UI 默认只展示名称;房内出现同名时,仅为同名项追加 peerId 尾部至少六字符短后缀,并只在同名项后缀碰撞时逐字符有界延长至完整 peerId。卡片状态只依据本机连接或当前 Viewer 接收证据显示“已连接”,否则保持中性的“线路分配中”或具体连接状态;active assignment 本身不是连接成功证据。Host 对 direct、Peer 转发和 SFU Viewer 使用完全相同的卡片结构,不生成 SFU 分组或 Host publication 伪 Viewer。连接详情同样等待当前媒体证据,再显示绿色 `P2P` 或黄色 `SFU fallback`;每张卡优先使用该 Viewer 回报的实际接收指标,Host 直连发送快照只在尚无回报时提供同结构回退。一级固定为分辨率、帧率、码率和丢包,二级按方向只渲染当前有值的 RTT、实际 H264/VP8 codec、jitter、冻结/丢帧、解码耗时、音频播放质量,或捕获/编码输入、编码耗时、编码器与质量限制;超出 accepted codec contract 时另行提示。Host capture strip 在详情开启时追加 share-generation resolved codec,不冒充逐 edge 协商。候选地址、候选对 ID、STUN 计数、RID、fmtp、常规 sender 请求/读回和其他内部标识不渲染。Viewer 接收证据由服务端绑定当前 `viewer/upstream/connection/route revision`:Peer 子边只送达其直接父节点及 Host,SFU 接收只送达 Host;因此 SFU Viewer 继续带 Peer 子节点时,两名 Viewer 的证据仍各自归属,不逐层转发或互相冒充。Host 与 Viewer 都可通过独立拓扑按钮从 authoritative assignment snapshot 展示 Host、实际存在的 SFU 节点及精确上下游;Viewer 默认收起并放在视频下方,没有当前 Host presence 时不生成占位拓扑。拓扑不把计划线路当作连接成功,也不显示 IP 或唯一名称对应的 peerId。peerId 不因此成为授权身份或路由输入;名称、presence 与拓扑视图不改变授权、媒体或路由状态机。--## 信令协议--WebSocket 使用无 query/fragment 的同源 `/signal`。upgrade 只记录 site-access cookie 是否有效;连接后五秒内第一条消息必须是当前单一 wire 的房间级 `authenticate`。Host 消息携带 room、role、内部 Host token 与 clientId,并由 socket state 复核 site access。Viewer 消息携带 room、role、clientId,以及 exact-room Viewer grant 或当前 code-only password attempt。成功的 `authenticated` 快照始终携带部署最终值 `endpointMediaCopyCapacity: 1|2|3`;普通模式的服务端 admission 只向 Host 激活稳定加入顺序中的至多该数量 Viewer,并在离开后提升等待者,双方信令只允许 active child。Browser Host 与 Viewer 严格校验该值,房间 `maxViewers` 只约束观看者总 admission。Native/executable sender 停留在旧 wire 并在 authority 前拒绝。服务端设置 64 KiB `maxPayload`、关闭 `perMessageDeflate`,并以 ping/pong 清理失效连接。单进程固定限制 2048 条总连接和 256 条未鉴权连接,容量在 upgrade 前预留,超限直接返回 HTTP 503 并销毁 socket。--下表描述 accepted Browser 的单一 `screener-v13` wire;server 与 Browser assets 必须作为一个完整合同原子发布,其他 wire 在取得房间 authority 前拒绝,不存在旧 parser、writer、translator 或中间协议子集:--| 方向 | 消息 | 作用 |-| --- | --- | --- |-| client -> server | `authenticate` | Host 以 upgrade 时的 admission 状态加 room-scoped Host token 建立会话并可订阅 Web-only presence/settings;Viewer 以 exact-room Viewer grant,或 site access 加当前 `open/private` code-only policy 建立仅观看会话,并可附带规范化本地显示名 |-| server -> client | `authenticated` | 返回角色、peerId、可为空的房间期限、容量、host 状态、该 viewer 的历史 connectionId、host 的权威 viewer 列表和 ICE 配置;仅 Host 额外接收是否已配置房间密码的布尔状态,不回显密码 |-| viewer -> server | `set-display-name` | 只更新该 Viewer 当前 authenticated socket state 的规范化名称,不写房间或数据库状态 |-| server -> subscribed Web host | `viewer-presence` | 返回全部当前在线 Viewer 的权威 snapshot 与精确 active upstream;不触发媒体连接 |-| Host HTTPS -> server | room-access update | 以 site access 与精确 Host token 独立设置 `open/private`、设置/移除 password,或 rotate/revoke grant;不建立媒体会话或续租,raw grant 只在新建或 rotate 成功响应中出现一次,服务端不回显密码 |-| server -> host | `peer-joined` / `peer-left` | 建立或关闭该观看者的独立连接 |-| host -> viewer | `offer` / `candidate` | 带 `peerId` 与 `connectionId` 的定向信令 |-| viewer -> host | `answer` / `candidate` | 只能回给本房间分享者 |-| viewer -> host | `restart-request` | 以 `rebuild` 标志请求 ICE restart 或完整重建该 peer |-| host -> server | `stop-sharing` | 结束当前发布、清理本轮连接并让观看者等待;不删除房间或使邀请失效 |-| server -> viewer | `route-status` | strict union 只允许 `{ revision, state: "waiting", reason: "sfu-admission" }` 或 `{ revision, state: "failed", reason: "route-exhausted" }`;只补充现有 `route-update` 无法表达的 SFU admission waiting 与 bounded route exhaustion,不携带 raw text、identity、candidate 或 retry hint |-| host -> server -> host | `request-route-diagnostic` / `route-diagnostic-snapshot` | 仅供 authenticated Host 自动验收请求一份当前快照;产品 UI 不提供下载按钮,不连续推送、不参与 route authority |-| host -> server -> viewers | `set-sharing-paused` / `host-status` | 当前 Host session 与 `shareGeneration` 约束一个 paused boolean;Resume 使用同一状态更新,不建立第二次授权、source acknowledgement 或媒体 proof |--Zod 在服务边界拒绝未知类型、超长字符串、非法 SDP/candidate 结构和越权目标。服务端根据已认证会话决定路由:观看者不能给另一名观看者发信令,分享者也不能向本房间以外的 peerId 发送。--accepted 的唯一 wire 是 `screener-v13`,不做版本协商、旧 parser、双写或 translator。任何其他 Browser wire 及 executable sender 的首条消息在角色进入 room lookup 前得到同一个 fatal refresh 终态并停止自动重连。Client 与 server 共用 `SIGNAL_CLOSE_CODES` 定义会话替换、鉴权失败和 Viewer access revoke 的终态语义,避免双方对重连边界产生分叉;非法协议消息使用 WebSocket policy-violation close code。缺失、跨房、已 rotate 或 revoked 的当前 Viewer grant 使用同一个通用“邀请无效或已失效”结果。已通过 site access 的 well-formed code-only attempt 在没有 current room 时发 `ROOM_NOT_FOUND`;现存房间的 absent/wrong password、room full 与其他已知有界 admission refusal 继续发 `ROOM_ACCESS_DENIED`。两者都使用共享 authentication-failed close code。Grant 继续使用 `INVALID_TOKEN`,Host 鉴权保持独立,unexpected internal failure 使用不含 raw message 的 `SERVER_ERROR`。--## WebRTC 协商--分享者是唯一 offerer。每名观看者对应一个 `RTCPeerConnection`,以独立 `connectionId` 区分重建代次:--1. 分享者在开始按钮的同一用户手势内先成功调用 `getDisplayMedia()`。-2. 只有捕获 track 已存在时才请求创建或续租房间、连接 Host WebSocket 并显示邀请。新建请求携带本地 creation profile 和 preferred room,使 code-only policy、可选密码 verifier 与号码分配在房间可见前原子生效;偏好号码已占用时服务端直接随机分配并返回新的本地偏好。若用户在响应返回前取消,迟到结果不得覆盖后续分享会话,尚未认领的房间通过内部 `abandon-room` 立即释放号码。已经认领的房间在停止捕获后进入服务端 dormant lease,过期才释放;本地 preferred room 不参与该 lease。-3. 观看者认证后,服务端向在线分享者发送 `peer-joined`;host 晚上线或重连时收到完整观看者快照。-4. 分享者创建连接、加入当前视频 track,并以现有音轨或空 sender 预留 audio transceiver,设置 sender 参数,然后创建 offer。-5. 观看者收到 offer 后创建连接、设置 remote description、创建 answer。-6. 双方持续通过信令服务交换 trickle ICE candidates。-7. remote description 尚未设置时,客户端仅缓存有界数量的 candidates;旧 `connectionId` 消息直接丢弃。--这种单一 offerer 模式满足当前单向媒体需求,不引入 perfect-negotiation 状态机。同一页面中的不健康连接发送 `rebuild: false`,host 先尝试 `restartIce()`,非稳定信令状态或恢复失败时重建该 peer。新标签页没有旧 `RTCPeerConnection`,或页面 peer 与 `authenticated.connectionId` 代次不一致时,viewer 发送 `rebuild: true`,host 直接换代。健康且代次一致的媒体在单纯信令重连时保持不变;所有异步启动结果以 host 会话 generation 隔离,viewer 的异步 answer、candidate 和 stats 结果也必须同时匹配当前 connection 对象与 connectionId,旧代次不得改写新状态或发出信令。--信令 WebSocket 暂时中断时,不立即关闭仍健康的 P2P 媒体;客户端指数退避恢复控制通道。明确不可重连的会话替换会释放旧页面的 peer、统计定时器和媒体引用,host 也停止旧捕获。首版只保证同一页面生命周期内恢复,不承诺浏览器进程被系统挂起后的连续播放。--## 捕获、编码与质量--捕获只能由按钮产生的用户手势调用 `getDisplayMedia()`。三档目标为:--| 档位 | 约束目标 | 初始码率上限 |-| --- | --- | ---: |-| 720p30 | 1280x720、30 fps | 3 Mbps/peer |-| 1080p30 | 1920x1080、30 fps | 5 Mbps/peer |-| 1080p60 | 1920x1080、60 fps | 8 Mbps/peer |--浏览器可返回更低设置,界面以 `track.getSettings()` 显示实际捕获结果。推荐区始终只有表中的三档并默认选择中档 `1080p30`;高级分辨率额外提供 `480p`(854x480)、720p、1080p 与 1440p,FPS 继续独立接受 15 至 60 整数,码率继续独立接受 2 至 12 Mbps,因此不建立第四个推荐档或 `480p` preset ID。视频 track 使用标准 `contentHint = "motion"` 表达游戏动态意图;返回的音频 track 使用 `contentHint = "music"`。默认 `1080p30` 与折叠高级区初始值采用 `degradationPreference = "balanced"`,并允许显式选择清晰、均衡或流畅。高级设置在未分享时提供 `VP8 | 自动 | H264`,分享期间锁定;屏幕音频提供离散的 `64 kbps 普通 | 128 kbps 音乐默认 | 192 kbps 保真` sender ceiling。音频 ceiling 可在直播中串行更新。这些设置只是 ceiling 和浏览器偏好,不保证实际分辨率、帧率、码率或声道。--每次 `setParameters()` 都必须从当次 `getParameters()` 派生更新,然后读回 requested/applied `maxBitrate`、`maxFramerate`、`scaleResolutionDownBy` 和 degradation preference。浏览器负责具体降级,实际结果由 stats 观测;拒绝或浏览器改写必须进入可见状态,不能只写 `console.warn`。--Accepted `screener-v13` Web 视频使用页面内 share-generation-scoped H.264/VP8 决策。Host 高级设置在未分享时按从低到高显示 `VP8 | 自动 | H264`,默认自动,分享开始后锁定。自动模式在取得 room/route authority 前,以一对无 ICE server 的本地标准 `RTCPeerConnection` 运行一个有界 H.264-only sender probe;手动 VP8 或 H264 跳过 gate 并严格使用所选 primary codec。Probe 使用按当前分享 effective target dimensions/frame rate 生成的短时确定性运动 Canvas track,并以 `motion` 表达同一内容意图;真实 capture/upstream track 只提供目标规格,其当前内容是否变化不参与 encoder capability 判断。Gate 只用实际协商 codec、同一身份的 probe media-source/encoded progress 与 bounded completion 判断,不读取 UA/GPU/MFT allowlist,也不单独相信 capability 或 `powerEfficientEncoder`;标准 Canvas capture 不可用、失败或 inconclusive 时使用 VP8。自动成功让后续 offer 按浏览器原生 H.264 capability 顺序列出 H.264,再列 VP8 与 repair formats;自动失败或手动 VP8 只列 VP8,手动 H264 只列 H.264 mode 1。Viewer relay 始终自动,并在该分享代首次收到 upstream video 且没有 active/prepared child 时运行同一 gate;若 child prepare 先到,则等待已经在运行的 bounded gate 结束后只创建一份真实 child sender。质量设置、换源、换父和分享暂停/继续不重复决定;只有停止后开始新的分享代才按当前 selector 重新判断。Viewer 原生播放器暂停不改变 remote track 或 relay gate。无法应用 codec preferences 或缺少所选 codec 时明确失败。SFU publication 使用 Host share generation 的同一 resolved H.264/VP8 决定并关闭 backup codec。所有新 Web peer sender 与 SFU publication 保留 `motion` 和用户选择的分辨率、帧率及码率 ceiling;当 desired degradation preference 允许分辨率下降时,启动阶段的 effective preference 暂为 `maintain-resolution`,当前 sender 累计编码至少五帧后由既有 stats 路径一次性应用 desired preference。该切换使用标准 `setParameters()` 进入或离开 balanced 时的原生 restriction reset,不增加周期重写、质量评分或应用层调档器。Host selector 只在页面内存,resolved 结果也不持久化、不进入 quality state/wire、不改写已连接 edge;实际 outbound codec/profile、encoder implementation 与 stats 是只读结果真相。应用 SDP 变换边界仍只有 Viewer answer 的 Opus stereo receive preference。--Web display-audio 请求显式关闭 `echoCancellation`、`noiseSuppression`、`autoGainControl` 和 `voiceIsolation`,并以 `channelCount: { ideal: 2 }` 偏好双声道;这是当前 Chrome/Edge Host 基线的实现契约,用于避开网页 `getDisplayMedia()` 默认的语音处理和单声道 APM 候选,不宣称跨浏览器保证,也不固定采样率。所有值都是非强制 post-selection preference;不使用 `exact`、`min` 或 `advanced`。若 `getAudioTracks()` 为空,分享者界面必须显示“当前来源没有可共享音频”。Web 端同时传入 `windowAudio: "window"` 与 `systemAudio: "include"`:窗口选项请求该窗口/应用音频,整个屏幕选项允许用户勾选系统音频;标签页使用浏览器自身的标签页音频选择。浏览器可以忽略这些约束或 picker hints,且没有对应的标准来源类型读回,因此 UI 不额外推断或标注来源。系统音频由用户显式选择,可能包含语音或通知;video-only 始终可用。--当前 Windows Native sender 用本地 opaque ID 保存所选窗口的 HWND、PID 与进程创建时间;helper 在使用前重新验证三者绑定,并以 WASAPI process loopback 的 include-target-process-tree 捕获游戏及其子进程。目标进程无渲染流、退出或捕获失败时显示无声/未知,不回退为整机音频,也不上传 PID、路径、窗口标题、设备标识或原始音频。该路径只支持 Windows 11;Windows 10 game-only 音频保持明确不支持。--同一 helper 的显式 `native-window-h264` source 用 `CreateForWindow` 建立 WGC item,在所选 adapter 的 free-threaded D3D11 frame pool 接收 BGRA surface;D3D11 VideoProcessor 做固定 1280x720/30 aspect-fit NV12 转换,随后进入 adapter-LUID-bound、hardware-only asynchronous Media Foundation H.264 MFT。输出必须是 Annex-B `42c01f`,首次、周期和反馈恢复帧携带 SPS、PPS 与 IDR。PCM、H.264 access unit 和 local-only hardware status 通过一个有界 helper protocol 进入 generation-bound Go session;H.264 直接写现有 shared fanout,UI 只收一份单向预览副本,PCM 保持现有本地 WebCodecs Opus bridge。任一 Native capture/encode 失败都终止该 source,不静默改用软件 MFT、其他 codec、browser capture、monitor capture 或 system mix;普通 Web Host 使用独立的 Browser codec 路径。一名普通 Chrome Viewer 已 decoded/rendered 203 帧并收到 500 Opus packets;同一 helper PID/adapter 的 `VideoEncode` 与 LUID 匹配。--直播中切换来源仍由明确的按钮手势重新调用 `getDisplayMedia()`,不改变房间、host generation 或媒体拓扑。选源取消或失败时继续发送旧流;成功后为每个现有 sender 调用 `replaceTrack()`,健康连接不重新协商。初始 offer 预留 send-only audio transceiver,使音频可以在 `null -> track -> null` 间切换。若某个 peer 的替换或回滚失败,只重建该 peer;新流提交后才停止旧流,并以当前 stream 身份保护旧 track 的迟到 `ended` 事件。统计码率累加器在换源后重置,避免把不同 track 的计数器混算。--直播中切换质量不重新打开选源器:对当前视频 track 调用 `applyConstraints()`,再更新所有现有 sender 的参数;quality mutation 不重新运行 codec gate,新加入或重建的 Browser sender 使用当前分享代次的内存结果与最新其他权威设置。失败时保留当前分享并给出状态,不以重建整个房间补偿。临时暂停禁用当前 capture stream 的全部音视频 tracks;Host 通过当前 session 与 `shareGeneration` 发送一个 paused boolean,服务端同步 `host-status`、route pause 与 `authenticated` 快照,Viewer 在舞台显示“分享者已暂停”。Resume 使用同一状态更新并重新启用同一批 tracks,不另设 authorization、source acknowledgement 或 proof。晚加入和信令重连从快照恢复,恢复、停止、新分享或会话替换清除旧状态;不得把 track mute、黑帧或网络停顿推断成主动暂停。房间与连接保持不变。--Host 本地预览直接绑定现有 capture stream,不创建 viewer、`RTCPeerConnection` 或额外媒体边,也不产生 SFU/应用服务器出口。预览仍可能有本地合成、缩放和 GPU 显示成本;在同一动态场景对预览开/关采集 Host CPU、GPU、encode time 和实际 FPS。后台性能诊断必须把 Host 页面前台/遮挡/最小化、被捕获 source 前台/遮挡/最小化以及 preview 播放/暂停分成独立变量,并关联 document visibility/focus、track mute/readyState 与 capture/outbound/inbound stats。页面 timer、伪活跃和 Screen Wake Lock 都不构成屏幕捕获保活方案;若标准浏览器无法维持目标行为,应记录平台能力边界而不是制造第二套 lifecycle。只有稳定收益且捕获、编码和远端画面不变时,才把直播后的默认动态预览改为静止缩略图或隐藏并允许按需展开;隐藏预览绝不停止 capture track 或 sender encode。--codec 与 content-hint 依据由研究文档持有。`motion` 会改变 Chromium/libwebrtc 的适配取舍并可能空间降级以保留游戏动态;它是标准内容意图,不是分辨率或帧率保证。产品不再用 unset hint 固定 screen-classified 行为,也不围绕某次测量实现应用缩放器。Chrome 151 的普通 AMD H.264 MFT 即使报告 hardware efficiency 仍持续丢帧,而 Chrome 153 的 NVIDIA H.264 MFT、双 sender、Browser relay 与 LiveKit publication 均维持源 cadence,证明 capability、实现名称或单一硬件标志都不能替代实际 source/encoded progress。网页不启用浏览器进程开关或选择具体 GPU/MFT;gate 只选择 H.264-first 或 VP8-only 的标准协商输入,不控制实际 encoder。VP8 hardware acceleration 仍是证据特定事实;本设计不增加 VP9/AV1/H.265、自定义编码路径或转码。--`track.getSettings()` 中存在的 EC/NS/AGC/voice-isolation、`channelCount` 和 `sampleRate` 只能作为当前捕获观测;缺失字段保持未知,Opus 协商仍是独立事实。每个 Web Host 或浏览器 relay 的实际音频 sender 在首次绑定和换源后通过标准 `RTCRtpSender.setParameters()` 请求并读回当前 96/128/192 kbps ceiling;这只是上限,浏览器 WebRTC 拥塞控制仍可降低实际流量,不新增应用层音频降级器。96 kbps 普通是默认 ceiling;128 kbps 音乐和 192 kbps 保真由用户显式选择,均不是最低码率或质量保证。Peer answer 声明 `stereo=1;maxaveragebitrate=192000`,让同一接收协商覆盖所有三档,实际 sender ceiling 仍由所选档位约束;普通 PC synthetic 不用于标定参数、听感或性能。--Web peer 的最小 stereo 契约只改 Viewer 生成的 answer。实现把 MIT `sdp-transform` 2.15.0 与 `@types/sdp-transform` 声明为 root direct dependencies,不依赖 LiveKit 的 transitive install,也不用字符串或正则拼接 SDP。Helper 仅在解析出唯一非 rejected audio media、通过结构化 `rtp` entry 找到唯一 Opus payload 时,才在该 payload 的 fmtp 幂等 upsert `stereo=1` 与 `maxaveragebitrate=192000`;随后 `ViewerPeer` 把同一个结果交给 `setLocalDescription()` 和 signaling。首次连接、ICE restart、同 parent rebuild与浏览器 relay child 都走该边界。空 SDP、无或歧义 Opus、多个有效 audio、重复目标参数、畸形 fmtp、parse/write 异常都按对象 identity 返回浏览器原 answer,保住仍可继续的 mono/video edge,不发送半修改 SDP。RFC 7587 说明这两个值都是可选的单向 receiver parameters;`maxaveragebitrate` 是 maximum 而非最低保证,实际发送仍可随拥塞下降。当前 libwebrtc 把缺省 full-band stereo codec bitrate 配成 64 kbps,而 `RTCRtpSender.maxBitrate` 只限制上界;本接收上限允许三档,实际发送预算仍由 96/128/192 kbps sender ceiling 与拥塞共同决定。`sprop-stereo` 只是 sender likelihood hint,`usedtx` 缺省已是 0,本 slice 不增加二者,也不改浏览器协商的 `useinbandfec`。--SFU publisher 将 96 kbps 映射到 `AudioPresets.musicHighQuality`、128 kbps 映射到 `musicHighQualityStereo`,192 kbps 使用显式 `maxBitrate`;三者都使用 `forceStereo: true`、`dtx: false` 与 `red: false`。RED 与 Opus in-band FEC 是不同修复机制;关闭 RED 降低冗余流量并接受其弱网恢复退让,不声称禁用或替代 Opus FEC。直播中只改变档位时,不重新协商 Opus 或 republish;服务端沿现有 quality wire 保存 last-wins desired profile,各客户端 sender-mutation queue 从 fresh parameters 更新当前 P2P、relay 和 SFU audio sender并立即 readback,过期 completion 不覆盖新值,未来 sender 读取最新 desired profile。应用失败保留该 sender 的旧 applied 值和媒体并显示告警;无远端 applied 回执时 Host 不宣称全房原子收敛。Viewer 继续在同一个持久 `MediaStream`/媒体元素中增删 screen video/audio track;不新建 audio element、Web Audio mix/resample graph、第二 audio representation 或独立音频时钟。详细证据见 `docs/research/browser-screen-audio-quality.md`。--Viewer 本地连接详情只从当前 route 的唯一 inbound screen video/audio stats 读取同步证据:`audio estimatedPlayoutTimestamp - video estimatedPlayoutTimestamp` 表示当前发送端时间线差;音视频 jitter-buffer delay 取相邻窗口累计 delay/count 的比值;音频 concealment 取相邻窗口 concealed/total sample 与 event 增量。每个媒体种类用 stats id、SSRC 和 track identifier 共同守住区间身份,换流或累计计数回退时先重新基线,字段缺失或分母为零时保持未知。该证据不进入 signaling、质量上报或持久化,也不设置 `jitterBufferTarget`、Web Audio 或任何媒体控制参数;真实同步仍由同一持久 `MediaStream`/媒体元素和 WebRTC playout 负责。--`frameRate` 约束和 sender 的 `maxFramerate` 都是目标或上限;浏览器仍控制实际捕获、重复帧处理、编码和拥塞降级。静态画面可能由浏览器减少实际编码数据,但标准没有保证每个实现以同一种方式节省采集或 GPU 开销。本 PoC 不添加画面差分、定时改约束或自定义动态 FPS 状态机,先用 `framesEncoded`、实际发送码率、`totalEncodeTime`、质量受限原因和主机资源占用测量真实问题。--质量自适应采用 ADR-0007 的框架所有权,而不是全房间按最差链路降档。Direct/peer 保留每条 PeerConnection 的 stock WebRTC GCC。Browser Host 的唯一 SFU publication 不手写层列表,由锁定的 LiveKit client 默认行为拥有所选 H.264 或 VP8 的 screen-share representations、source replacement 与 republish。LiveKit Dynacast 和启用 send-side BWE 的 server stream allocator 独立处理聚合需求与每个 subscriber 的实际下行层,订阅端最高质量请求只是上限。Screener 不实现质量评分、带宽估计、周期调档或应用媒体层 selector。当前任一 Viewer 都可能承担 peer children,因此 subscriber 统一保持 `adaptiveStream: false`,relay ingress 不跟随本地 DOM 可见性。Pinned gate 证明了 LiveKit 原生空间选择和 Dynacast 能力,但具体 representation 参数仍属于 pinned component,而不是 Screener 产品常量。--质量证据只用于诊断,不形成全房分数或 parent authority。路由只消费 exact child edge 的 `failed/closed` 和非暂停 decoded-frame stall。prepare/commit/abort 绑定 authenticated sessions、share generation、base/pending revision 与 candidate connection;candidate child 的第一帧新 decoded video 是唯一应用层 media-ready,ICE connected 不能单独提交。--状态决策必须关联同一时间区间和媒体代次的三段证据:--| 阶段 | 必要证据 |-| --- | --- |-| A. Host capture | `track.getSettings()` 的实际宽、高、FPS |-| B. Host outbound | 实际宽高/FPS/码率、可用或目标码率、区间 encode time、`qualityLimitationReason`、RTT、丢包、重传、direct/SFU 路径,以及派生后的实际协商视频 codec/profile/parameters 和适用时的 `scalabilityMode` |-| C. Viewer inbound | 实际宽高/FPS/码率、丢包、jitter、区间 decoded/dropped frame 和 freeze,以及对应派生 codec/profile/parameters、适用时的 `scalabilityMode` 和实际解码表现 |--判断顺序固定为:Capture 低归为采集或约束;Capture 高而 outbound 低且 reason=`cpu` 归为编码资源;Capture 高而 outbound 低且 reason=`bandwidth` 归为 GCC、上行或当前路径;outbound 正常而 inbound 低归为传输或接收;inbound 指标正常但肉眼模糊归为码率/量化、协商 codec/profile/parameters、适用的 scalable layer 或显示缩放。B/C 必须关联同一派生协商结果与实际解码表现。累计统计只计算相邻、不重叠区间的 delta;缺字段、stats ID/媒体代次变化或计数器回退时重新建立基线,不能把未知当零。--探针按最小顺序落地:先在 host 同一个采样 tick 内关联 A+B,并携带明确 window、媒体/stats identity 和有效 delta;需要 Viewer 诊断时只增加受限、已鉴权 C 上报。不建设通用遥测 schema,只传派生后的协商字段,绝不上传 raw stats、raw SDP、candidate 地址或原始设备/网络标识;这些字段不产生路由 authority。--Viewer 的已鉴权质量证据只描述当前路径,不能命令 WebRTC/LiveKit 改层、改变 Host publication 或改变拓扑。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 设置最大空间/时间层请求,但实际选择依 codec、SDK 默认和 server selector 而异,且不延伸到 direct/peer descendants。未来只能由能明确锁定硬编、跨 direct/peer/SFU 复用合格输出且通过游戏性能/延迟门槛的 native sender 以新决策重开。普通非分层编码包不能只靠转发生成另一档画质,实现路径差异只能由届时接受的 scalable representation 或转码模型拥有。--质量控制不放宽稳态 outbound media-copy 预算:所有非服务器端点继续受统一静态 capacity 约束;native relay 只转发选定表示的编码包,不解码重编码。后续双树或条带化必须另行验收,不能绕过当前 graph、identity 和 capacity invariant。--路由状态只有 committed graph 和一个 pending child operation;该对象聚合 candidate list/cursor、一个 current candidate/预留和一个总 deadline。relay 自身 ingress 失效时,它作为 child 进入同一 reparent 并保留 subtree;disconnect 或 effective capacity 降低时让 direct/overflow children 逐个回到 reconcile。多个下游 edge 若各自失效,会独立迁移并自然排空 relay。权威 pause abort operation、保持 active graph、抑制 stall;resume 重新 reconcile。--标准表示能力排在任何自定义媒体实现之前。Web P2P simulcast 缺少 receiver 选 RID 与跨 PeerConnection shared-encode 契约;LiveKit SFU 则原生拥有 per-subscriber 层选择与 Dynacast。ADR-0007 的 pinned-stack 门禁已通过,Browser SFU 的接受目标是锁定 SDK 默认的两路 screen-share 表示、Dynacast 和 server send-side BWE,并完全委托框架启停和选择;不得把该能力扩散到 direct/peer,也不得绕过 stock WebRTC congestion control。--## 移动分享端能力边界与排期--普通移动浏览器当前只承担 Viewer。Chrome Android、Firefox Android 与 Safari-iOS 都没有可靠的 `getDisplayMedia()`;Web Host 入口必须检查运行时 API 并明确-区分 unsupported、用户拒绝/取消与 capture failure,不能用 UA、desktop mode-或设备型号放行。该边界不影响普通手机浏览器观看或统一 relay capacity;移动表现继续作为真机兼容观察。浏览器版本证据由-[WebRTC 调研](./research/webrtc-p2p-screen-sharing.md)持有。--移动端只承担响应式 Web Viewer;Web Host 支持矩阵保持桌面 Chrome/Edge。--Viewer 向电视投屏不进入媒体拓扑;系统级屏幕镜像现在由平台直接提供。Web 端后续只在运行时检测-`HTMLMediaElement.remote`,并在真实目标证明 live WebRTC `srcObject` 可远端播放后才-显示入口;Safari 官方只保证 `HTMLMediaElement` 的原生 AirPlay picker。Google Cast-`MediaInfo` 最终需要 `contentUrl` 或充当 URL 的 `contentId`,当前 P2P `MediaStream` 没有-该资源,因此不接-Cast sender/receiver SDK、不建转码或自有投屏协议。无论输出到本机还是电视,Viewer-都保留同一 upstream PeerConnection,SFU/peer route 与 Host fanout 完全不变。--## 媒体传输配置--Production `ServerConfig` 必须配置 `STUN_URLS`。所有 ordinary direct/peer-`RTCPeerConnection` 的 authenticated snapshot 只包含 STUN。HTTPS/WSS 始终使用-TLS/TCP,不属于媒体 transport 策略。--`PEER_ASSISTED_MEDIA` 启用同一个 process-wide route controller,但每个房间拥有-独立的 assignment、session、revision、generation、connection 和 capacity 状态。-所有非服务器端点读取同一个 deployment steady outbound media-copy capacity,默认-`2`,只接受 `1`、`2` 或 `3`;peer child 或 Host publication 各消耗一份,upstream-receive 免费。服务端是权威,客户端广告只能-收紧,不能按 Host/Viewer、浏览器、UA、设备或页面状态放宽或分叉。--每个 candidate 和异步结果都绑定 authenticated room/endpoint sessions、share-generation、base/pending route revision 与 candidate connection identity;SFU-publication generation 由 resource owner 单独持有。迁移保留可用旧 media;只有-candidate child 解码出第一帧新画面时才原子 commit。ICE `connected`、token-签发或 assignment 本身都不是 media-ready。失败、超时、stale identity 或授权-撤销销毁 candidate,保留或恢复最后一个有效 route。--SFU 是可选、有界的 server-assisted resource。一个 room controller-通过同一个 reconcile 处理 allocate/distribute、child reparent 和 relay drain。-Host 拥有唯一 authoritative publication,所有 SFU-fed Viewer 订阅它;SFU-fed-与 peer-fed endpoint 的新 child 都使用同一 provisional first-frame transaction。-现有 edge 优先保持 direct/STUN,唯一 suffix 是复用或建立 direct-ingress Host-publication 后的 SFU subscription。端点容量、SFU ingress/egress、临时 overlap、server admission-和 bounded failure 在同一 reserve/first-frame/commit-or-abort 事务中记账。--短期 SFU credential 必须严格绑定当前 route identity、只存内存、受 TTL 与 quota-限界,并且不进入 URL、日志、browser storage 或任何持久存储。普通 SFU 终止-DTLS-SRTP;没有应用层 E2EE 时 operator 可接触媒体,产品必须如实说明。-所有物理 hop 按[低服务器成本媒体路由](./research/low-server-media-routes.md)逐项计量。--精确 production behavior 只由 deployment 记录;新实现仅复用满足当前 identity、-media-proof 和 bounded-recovery 不变量的 scoped code 与 tests。--## 可观测性--每两秒在本地采集一次 `getStats()`。首版不上传原始统计。折叠详情可在产生该连接的本机显示 selected local/remote candidate 的 `address`/`port`,但浏览器未暴露时保持未知;地址不得进入信令、Viewer C、日志、诊断导出、持久化或路由/质量决策。在 peer 边中它只是当前连接端点,在 SFU 边中通常是 SFU 端点,不能标成参与者的权威公网 IP。--accepted `screener-v13` 的 Host/Viewer 产品 UI 不提供连接诊断文件下载。现有 periodic stats 只驱动当前页面的折叠连接详情、typed failure 与 accepted exact-edge stall;原始 stats、地址和身份不上传。authenticated Host 自动验收仍可按需请求一次 `route-diagnostic-snapshot`;服务端当场读取 current graph/operation 与 bounded latest timing records,不连续推送、不保留事件环、不建立第二张 graph。snapshot 使用临时 ordinal 和封闭 outcome bucket,不含 raw identity、address、candidate、credential 或 error,也不形成 route authority。--Host 与 relay Viewer 复用同一个纯 presentation reducer 保存远端 `ViewerQualityEvidence`。代际 identity 是 exact route identity(room/share、viewer/parent、assignment/connection、route revision 和当前可用的 media-binding generation,及适用时 publication generation);只有同 identity 且 sequence 严格递增才可承接每个字段最后一次真实非空观测,其他输入从新 evidence 重建。五秒 freshness 只控制 evidence 能否证明当前连接,采样缺字段或短暂超时不把展示字段归零。`new`/`connecting`/`disconnected` 保留同 identity shell 但立即标为非 fresh,`failed`/`closed` 或 route identity 变化清空。任何依赖当前状态的消费者只读取 fresh presentation;该层不新增 wire 字段或服务端 route authority。--质量诊断必须能按顺序区分:捕获源设置、sender 实际参数、CPU 或带宽 `qualityLimitationReason`、当前 peer/SFU 路径、outbound 与 inbound 差异,以及接收端 dropped/freeze。当前有界实现显示 sender 参数的 requested/applied 读回;同一个非 `none` 原生 `qualityLimitationReason` 连续出现三个采样周期后显示单条原因提示,原因变化、缺失或恢复为 `none` 即重新计数。这只是去抖后的观察,不组合评分、不触发调档或迁移。完整跨路径分类仍由后续真实矩阵验收;首轮使用浏览器 WebRTC internals 导出和一份脱敏 run manifest,不新增服务端遥测。--分享者逐观看者显示:--- `connectionState` / `iceConnectionState`;-- 选中候选对的 local/remote candidate type 与 ICE `protocol`;-- SFU/UDP 只按[低服务器成本媒体路由](./research/low-server-media-routes.md)的 generation-baselined、privacy-safe ICE manifest 记录;先以本地脱敏 `webrtc-internals` 建立 ground truth,不新增后台遥测;-- `currentRoundTripTime`、发送码率和 `availableOutgoingBitrate`;-- 实际帧率、分辨率和相邻有效采样窗的 RTP 丢包率;-- codec、编码实现、最近采样区间内的每帧编解码耗时和 `qualityLimitationReason`;同一连接不并发采样,首个样本、无新帧、统计对象换代或计数器重置时显示未知并重新建立基线,不用连接生命周期均值掩盖后续过载。-- 同一连接上实际存在且唯一的 audio RTP 对象所对应的区间码率、RTP 丢包率、jitter,以及由其 `codecId` 引用且绑定同一 transport 的 `RTCCodecStats` MIME、clock rate、channels 和最长 512 个可打印 ASCII 字符的 fmtp。clock/channels/fmtp 只标成 codec 协商事实,不推断捕获采样率、有效载荷立体声、DTX 或 FEC 当前行为。--观看者显示接收码率、帧率、分辨率、RTP 丢包率、jitter、解码/丢帧和当前路径;Host 对 outbound 使用其链接的 `remote-inbound-rtp` 计算接收侧丢包率。视频和音频丢包率都只在同一 RTP generation 的相邻样本中以 `lostDelta / (receivedDelta + lostDelta)` 计算;首样本、对象/计数器重置、负 delta、零分母或字段缺失时显示“未知”,不把累计 `packetsLost` 伪装成百分比。RTT 只标为网络往返时间,不能冒充玻璃到玻璃延迟。--## 界面结构--首屏就是工具,不做营销页。视觉采用中性深灰工作台,绿色表示 direct、琥珀色表示 relay/警告、红色表示失败,避免单一蓝紫色主题;浏览器 favicon 复用页头 `MonitorUp` 的深绿底、绿色显示器和上行箭头语言。--- 访问入口:未鉴权根路径、`/join` 和合法 code-only `/r/{code}` 显示“站点访问”与“站点口令”;malformed `/r/...` 直接显示房间号必须是 `1000..9999` 四位数字,其他未知路径只显示“无法访问”。有效 `/r/{code}#v={grant}` 直接进入;其余 Viewer 通过 site access 后以 code-only 方式进入。未分配、已回收或已过期的 well-formed code 显示“房间不存在或已过期”,不展开或提供密码输入;现存房间的 `ROOM_ACCESS_DENIED` 保留“输入房间密码”和使用 Host 邀请的动作。已有有效 site-access cookie 不重复显示整站验证;站点口令和房间密码不共享输入值或授权状态。-- 分享者根页面:顶部显示“{分享者显示名} 的屏幕”和房间状态,并在标题旁显示可单独复制的紧凑四位房间号;Viewer 同一位置显示权威 Host 名称,不再在标题下重复。主区域保持稳定的 16:9 舞台。未发布、已停止或可恢复错误状态时,舞台内以同等尺寸和权重显示“开始分享”和“加入房间”,中间只用“或”与分隔线表达发送/接收;固定 action row 只能包含这两个按钮及分隔,disclosure 是紧随其后的 sibling,不得参与 action-row track sizing。前者直接开始现有分享流程,后者在当前舞台内展开共享的房间码表单,提交后才导航到 `/r/{code}`。按钮同步 `aria-expanded`/`aria-controls`,展开后输入获得焦点,DOM 与焦点顺序保持触发器后接表单;窄屏允许 disclosure 自己换行,不改变两个 action 的矩形或产生横向滚动。不增加首页、向导或拓扑选择。直播时舞台只显示无媒体 controls 的本地预览,权威停止、同步暂停音视频、切换来源和质量档位保持为明确的页面动作。邀请控制使用紧凑 copy-first 布局:包含 22 字符 grant 的完整短 URL 保持可见,复制是主动作;更新和撤销使用有 tooltip/accessible name 的 familiar icons,房间号复制、`公开 | 私密` code-entry segmented control 与可选密码编辑保持职责分离。页面失焦仅暂停本地 video element,并在舞台提示“本地预览已暂停,分享仍在继续”;媒体暂停则禁用 capture stream 轨道,两者都保留现有连接。-- `/join`:保留为可直接访问的回退入口,并复用同一个四位房间码表单;一个纯 route parser 返回 `host | join | viewer | malformed-room | unknown`,只把精确 `/r/{1000..9999}` 当成 Viewer route。输入保留用户原文,`inputMode="numeric"` 只提示软键盘,提交时由共享 schema 拒绝而不是 `trim`、删除非数字或接受 Unicode 数字。通过 site access 后输入合法 code 并进入 `/r/{code}`,后续行为由 code-only admission 决定。-- `/r/{code}` 观看者:首次解析合法 fragment grant 后立即清理地址栏并直达;仅有 code 时先通过 site access,再按 `open/private` policy 进入。私密房间统一返回通用拒绝并允许尝试密码,不披露房间是否配置了密码。鉴权后主区域最大化远端视频,标题旁显示可复制的紧凑房间号,顶部保留连接状态;同一个 video element 使用浏览器原生 controls 处理本地播放、音量和全屏,页面只保留“重新连接媒体”。Host 主动暂停时复用视频舞台遮罩显示“分享者已暂停”,恢复后立即移除。视频舞台用单一派生 presentation reducer 合成 access、Host presence、route prepare/active、peer/SFU connection、remote track、首个 composited frame、autoplay rejection 和 bounded failure。支持时用 `requestVideoFrameCallback()` 确认第一帧已提交,旧浏览器回退到当前代 decoded-frame delta 与 video readiness;`playing`、track object 或 ICE `connected` 单独都不足以结束占位层。当前代 composited frame 清除同 revision 的旧 connecting/reconnecting 展示。Hidden/freeze/pagehide 暂停应用 decoded-stall authority;visible/resume/pageshow 先 rebaseline 并重建 frame proof。系统暂停后的播放恢复留给真机和既有原生 controls,不猜测用户播放意图。Exact failure 在同步发送失败或信令换代后释放已报告锁,允许同一权威 route 重试。手动重连只重建同一 P2P parent 或同一 SFU subscription,不主动重选线路。-- SFU subscriber 以 LiveKit `disconnectOnPageLeave=false` 避免 SDK 在 BFCache `pagehide`/`beforeunload` 主动拆线;Screener 的 generation invalidate、显式 `disconnect(false)` 和服务端 Viewer grace 仍拥有正常清理。Pinned SDK 无选项关闭的 `freeze -> disconnect` 不做 fork,只进入真机 gate。-- 首帧观察绑定当前 assignment/connection/media-binding generation 以及适用的 publication generation;`srcObject` 或 route identity 变化立即使旧回调和旧 decoded baseline 失效,迟到回调不能把新路线标成已播放。-- 移动端:视频保持稳定宽高比,控制与状态移到视频下方,任何文字和按钮不得溢出或遮挡。--两端默认显示紧凑在线 roster;Viewer 端复用同一权威 participant snapshot,只列出当前 Viewer(含本机)并在新 snapshot 到达时整体替换,停止分享仅移除已离线 Host,鉴权失效、房间关闭或页面卸载则清空。Host 与 Viewer 的本机显示名在界面中统一标为“昵称”,默认只读,铅笔按钮紧贴昵称并只切换当前控件的输入、保存和取消,唯一名称仅显示名称,重名时才追加 room-scoped `peerId` 短后缀。一个不持久化的“显示连接详情”复选框按页展开媒体方式、传输协议、候选路径、浏览器实际暴露的本地/远端候选地址、codec、RTT、RTP 丢包率、编解码耗时及逐边统计;地址与端口只从当前页面 `RTCPeerConnection.getStats()` 精确关联的 selected pair 读取,浏览器隐藏或缺失任一字段就不显示,且不进入质量证据、信令、服务端、日志或持久化。界面不提供诊断文件下载。真实连接失败、音频缺失、持续画质受限和需要用户动作的告警始终可见。显示名/roster 不进入 access credential 或服务器持久状态。--用户可见的非直播状态使用稳定、真实的阶段词:分享端使用“已停止分享”;观看端使用“等待开始分享”“正在分配线路”“正在建立 P2P”“正在连接 SFU”“正在接收画面”“播放已暂停”“正在恢复连接”或明确失败。阶段只描述当前用户可感知动作,不暴露房间寿命、媒体代次、parent identity 或内部迁移步骤。`room-closed` 显示“房间已关闭”或“房间已过期”,不得误写成“分享已结束”。服务端 raw `message` 永不直接渲染;单一纯 reducer 按下表优先级把 typed current-generation fact 派生为文案、遮罩、保留画面和动作,较旧 revision/generation 输入直接丢弃:--| 优先级 | 权威输入 | 展示与动作 |-| ---: | --- | --- |-| 1 | stale client、room closed/expired/lost、`ROOM_NOT_FOUND`、`ROOM_ACCESS_DENIED` | 阻塞终态;`ROOM_NOT_FOUND` 只显示房间不存在/已过期且不显示密码,其他状态显示对应刷新、可选密码或使用 Host 邀请的动作,不显示 route retry |-| 2 | Host authoritative pause | 保留仍属于 current binding 的最后画面并显示“分享者已暂停”;等待 Host,不显示 retry |-| 3 | 同一 current media identity 的 `play()` 仅因 `NotAllowedError` 被拒绝 | 不要求先有 frame proof,立即显示唯一主动作 `Play`;点击后播放成功只清除 autoplay block,仍须等 current-generation frame proof 才撤遮罩,其他播放异常使用 typed failure |-| 4 | current binding 已有 composited frame | 去掉阻塞层;若 signaling 恢复中但媒体仍健康,只显示非阻塞提示且不清空画面 |-| 5 | route terminal failure、Host stopped/offline | Host offline 本身保留仍健康的 current media;exact upstream 硬失败或 route terminal 先使 current frame proof 失效,已证明画面至多降为 retained background 并显示离线或失败。仅 route/controller 明确允许时显示 bounded retry |-| 6 | SFU capacity wait、peer/SFU prepare、已绑定但未证明首帧、尚无 assignment | 依次显示备用线路等待、建立线路、接收画面或分配线路;无 `Play`、无虚假百分比 |--Token-free SFU standby prewarm 保持可选且不创建 participant、publication、subscription 或 route authority。它只提前加载 pinned SDK 并调用官方 `prepareConnection()`;是否缩短公网首帧由阶段时间戳验证,失败时继续既有冷路径。--按钮使用 `lucide-react` 图标并提供可访问名称和 tooltip。动态状态区域固定最小尺寸,避免连接状态变化导致布局跳动。在 1440、1024、780、520、390、375 与 320 CSS px 下,closed/open/validation-error 三种 disclosure 状态的两个首屏 action 都须同排等宽、触控高度至少 44 px且前后 `getBoundingClientRect()` 尺寸不变;输入获得焦点,文字不溢出,详情不遮挡视频且 `scrollWidth <= clientWidth`。--观看端不维护第二套音量、静音、播放或全屏状态;浏览器原生 video controls 是这些本地动作的唯一 owner。它们不进入 WebRTC sender、信令、房间状态或应用持久化,也不作为音频码率、声道、采样率或来源隔离设置。--## 安全与故障边界--- 生产仅允许 HTTPS/WSS,并校验 WebSocket `Origin` allowlist。-- site access 密码以定长摘要配合常量时间比较;site-access cookie 由服务端 HMAC 签名且不含账号或可查询 session ID。Host token 与 Viewer grant 只保存 SHA-256 摘要并以定长比较验证;房间密码只保存带随机 salt 的 scrypt verifier material,并对派生结果做定长比较。site access 与建房 HTTP 响应设置 `Cache-Control: no-store`。-- Fragment 只避免其进入 HTTP/WebSocket request-target,不能把 capability 变成非敏感数据。客户端首次读取后立即清理地址栏,只在 room-scoped `sessionStorage` 留存;服务端和代理日志不得记录 WebSocket payload、Authorization、cookie、raw grant 或响应 body,异常只能记录安全路径、状态码和分类。-- HTTP body、WebSocket payload、总连接数、未鉴权连接数、输出缓冲、房间总数、观看人数和 candidate 缓存都有硬上限;无法解析的 upgrade request-target 在未鉴权边界返回 HTTP 400,不允许异常逃逸到进程顶层。-- 应用日志不得主动记录 IP;反向代理、STUN 和 LiveKit 为提供网络服务必然可见源地址,部署时需设置最短必要留存与访问控制。-- tracked coturn 的 `stun-only`、`no-tcp` 与 `no-tls` 加上 LiveKit 的 UDP-only 配置共同定义当前媒体边界。Coturn 不分配 relay,Screener 不配置 TURN、ICE/TCP、media TCP 或 TLS-relayed media。-- 分享者直连会向可信观看者暴露网络地址。受限网络只尝试当前 direct 与 SFU/UDP 路径并在有界窗口后明确失败。--## 验证计划--自动测试:--- SiteAccess 的 production 必配、8 至 128 visible-ASCII bytes/独立 secret、local-dev 显式关闭、12 小时签名 cookie、过期、篡改、cookie 属性、已移除 access key fail-fast 和无服务端 session 状态;-- RoomStore 的四位空闲码随机分配/释放、活动分享免过期、dormant lease/续租、Host token/Viewer grant 摘要验证、22 字符 128-bit grant 与 exact room incarnation 同寿、`open/private` 正交 policy、私密无密码仅邀请可入、跨房/同号重建拒绝、rotate/revoke 强撤销、Viewer 上限和超额拒绝;-- RoomStore 的轻量/SQLite 稳定双模式等价行为、exact schema/application identity/单 owner fail-fast、稳定重启只恢复 authority、crash-active 转 dormant、旧 revoked grant 仍拒绝,以及 `ROOM_LEASE_SECONDS` 默认/边界与固定 9000 房间码池;`ROOM_TTL_SECONDS` 继续 fail-fast;-- STUN UDP URL 严格校验、生产 STUN 必需、LiveKit tuple 完整性/TTL/secret 独立性、当前 route/session/revision/connection generation guard,以及 ordinary peer、未授权房间和 Native 的 STUN-only isolation;LiveKit `sfu-config` 保持独立边界;-- Accepted v13 contract 使用单一 `screener-v13` 信令 literal、严格 JSON schema、方向与房间授权校验、payload 上限和 client-mismatch 刷新终态;分享状态由 `shareGeneration`-fenced paused boolean 表达,missing room 使用 `ROOM_NOT_FOUND`,现存房间准入失败使用 `ROOM_ACCESS_DENIED`,Viewer route failure 为 typed terminal,Host-only bounded route snapshot 保留给自动验收但不进入产品 UI。`qualityProfileIdSchema` 保持三档,`qualityResolutionSchema` 包含 `480p`,`DEFAULT_QUALITY_SETTINGS` 为 1080p30,quality schema 严格拒绝 codec 字段;-- 质量协议的 host 授权、严格字段与数值范围、last-wins、当前/未来 relay、已配置 SFU 和普通 P2P wire 兼容;sender 的四字段 requested/applied 读回、拒绝与持续受限提示;screen audio SDP helper 覆盖 CRLF、existing/missing fmtp、unknown key preservation、幂等、payload number、rejected/non-audio,以及 empty/no-Opus/ambiguous/parser 异常原对象 fallback,`ViewerPeer` 覆盖 initial/restart/rebuild 时同一结果的 local/signaling 一致性,SFU publisher 精确断言 high-quality stereo/forceStereo/DTX/RED-off;-- HTTP/WS 集成:nginx per-source site-access `limit_req` 与错误不泄露 secret,应用不建立 IP limiter 状态;Viewer 可在 Origin/容量门下 upgrade;Host 首条鉴权同时要求 upgrade-captured site access 与 Host token,Viewer 要么持 exact-room grant,要么先有 site access 再按 `open/private`。覆盖原子创建 profile、同浏览器重建偏好、fragment/sessionStorage/replaceState、无 site access 的 code-only 拒绝、unknown/reclaimed/expired room 使用 `ROOM_NOT_FOUND` 且不显示密码、私密无密码与 wrong-or-absent-password/full code-only 使用 `ROOM_ACCESS_DENIED`、grant 与 Host 的独立错误、raw grant/密码不进入 URL/日志/服务端持久状态,以及 rotate/revoke 后 grace/route 清理、旧 Viewer/上游媒体边关闭和 reconnect 拒绝;-- 客户端策略与 stats 解析:会话替换不重连,ordinary ICE 与 LiveKit protocol 分离;-- SFU client isolation:`SfuPublisher` 与 `SfuSubscriber` 的 `Room.connect` mock 分别精确断言 `autoSubscribe: false` 与 `rtcConfig: { iceServers: [] }`,ordinary `HostPeer`/`ViewerPeer` 回归继续断言部署 STUN,防止空列表遗漏 Viewer 或扩散到 peer edge;-- route planner property tests:候选输入乱序仍产生相同 list,健康边 sticky,硬过滤拒绝 stale/cycle/effective-capacity/unadmitted parent,优先结果深度和剩余容量并稳定打破平局;失败候选清理后 cursor 前进且总 deadline 不重置;-- Viewer stage reducer:按上表覆盖 access/Host/queue、peer/SFU prepare、remote track 无首帧、首个 composited frame、autoplay rejection、健康媒体上的 signaling recovery、Host stop/offline 和 bounded failure;stale revision不能覆盖 current frame,raw server message不能进入 UI;-- route parser 覆盖 `/r/`、三位/五位、`0000`、ASCII 字母、Unicode 数字、额外 path segment、合法 query/hash 与 exact `1000..9999`,且 malformed 输入不发起鉴权;Host/Viewer UI 都不渲染诊断下载按钮,Host-only snapshot 继续拒绝 Viewer 与额外/raw/private 字段;-- TypeScript 类型检查、Vite production build 和仓库 hygiene。--人工矩阵:--- 同机双标签页与同 LAN direct;-- 真实跨网络、同房间 direct/peer UDP + SFU/UDP root;-- CGNAT、双 NAT、移动热点和普通家宽下按 accepted route model 验证 direct/peer、SFU/UDP、恢复和 bounded failure;记录 RSS/CPU/latency 与 RX/TX/loss。人为封锁全部 UDP 时仍必须有界明确失败。涉及路由或基础设施变更的候选保留独立实例和被触及表面的恢复边界,不在同进程保留旧 transport;-- Windows Chrome/Edge 的 tab/window/monitor 音轨有/无、同时语音通话和 video-only;一个可区分左右声道的 fixture 只验证 Web P2P 与 SFU 的 channel correctness、协商 fmtp 和 route switch 后持久 `MediaStream`,不做听感/性能标定;Windows 11 原生候选另测 game process tree、通知、无渲染流与进程重启,Windows 10 记录明确不支持/未解决;-- Android Chrome 与 iOS Safari 的播放手势、旋转、前后台和网络切换;-- 一名分享者、20 名观看者先运行 bounded smoke,记录路由深度、queue wait、candidate start、first decoded frame、final route、sender 数、应用 CPU/内存和 SFU 用量,并报告 current-child sample/pending count、原始排序时长与 nearest-rank p50/p95/max;端点 `C=1/2/3` 分开解释。未接受产品体验上限前不把观测值变成新的 magic timeout。30 分钟异构公网 endurance 仍是后续质量证据,不阻止已经有界失败的 20-Viewer admission。-- 真实桌面 Chrome 对 balanced 与 clarity 做控制传播和连接身份 smoke;该项只证明直播中应用与不重建,不代替清晰度、负载或公网矩阵。--真实矩阵未完成前,状态文档必须把这些列为待验证,而不是把设计目标写成产品能力。--## 当前交付边界--- Production 与 canonical source 当前使用严格单一 `screener-v13` wire。每分享代 actual-sender gate 在证据通过时让未来 direct/relay 和 Host 单一 SFU publication 使用 H.264,否则使用 VP8。本地 pre-share `VP8 | 自动 | H264` selector 已实现并在分享期间锁定;quality-state/wire、自定义 SFU layer list、backup publication与健康 edge codec 切换不存在。Browser SFU 使用 pinned LiveKit 默认 representations、Dynacast、server send-side BWE、disabled AdaptiveStream 与 RED off;精确执行状态由 `docs/status.md` 持有。-- Pause/Resume 由当前 Host session 和 `shareGeneration` 约束。Host 后台性能和 VP8 hardware acceleration 分别按受控根因证据诊断;标准 ICE/SFU 按真实异构网络验收。-- 当前发布面只包含 Web Host、Viewer 和 browser relay。Native sender、capture helper、shared-encode executable 与两个分发包仍由各自后续决策和物理证据驱动,不属于当前 Browser release。--任何一步只实现当前消费者需要的接口。不得为未来账号、第三种媒体拓扑或原生 sender 预建抽象层。--## 自动路由设计--启动 owner fence 复用配置的应用监听地址:进程必须先完成独占 bind,绑定失败时不得调用 LiveKit;bind 成功但 LiveKit 初始化未完成时,HTTP 只返回 `503` 且不安装 signaling upgrade handler。唯一 owner 完成 foreign-room 拒绝、遗留 managed-room 删除和 empty readback 后,才开放 HTTP 与 signaling。这个顺序使重启或竞争进程不能在失去应用 owner 身份时清理仍在使用的 LiveKit room。--服务端维护每个房间唯一的版本化 route owner,它独占 committed graph、一个 pending child operation 和 transition lifecycle。运行时只在该 owner 外保存一个串行 pump、一个 operation deadline timer 和资源生命周期任务;拓扑 helper 不持有第二份 graph。operation 内聚 tuple list/cursor、一个 current candidate/预留、当前 fact version 和一个总 deadline。committed media graph 必须无环且 source-reachable;Host 没有 upstream,每名 Viewer 同时只有零或一个 active upstream。加入、容量变化、节点离开、当前 edge `failed/closed`,以及非暂停时的 decoded-frame stall 都只唤醒同一个 `reconcileRoom(roomId)`;未受影响分支保持 sticky。--`reconcileRoom` 在没有 pending operation 时先处理 foreground route demand,再处理低优先级 direct convergence。Candidate planning 拒绝 stale session、不可 source-reachable、成环或没有稳态/overlap producer slot 的 candidate;排序依次使用结果深度、剩余 sender slots、稳定 child-parent hash、加入顺序与 peer identity。每次只 reserve/prepare 一个 exact candidate;WebRTC 负责 ICE/DTLS/consent,candidate child 解码出第一帧新画面后才同步提交资源和 graph。失败只消费该 exact tuple,健康旧边保持 sticky,不做周期性整树平衡或独立 depth hard cap。完整 cursor、bootstrap 与终态所有权由 ADR-0005 定义。--Pending candidate 的 receive-transport owner 只在当前 exact generation 下运行一个短生命周期 `framesDecoded` 观察器。全新 peer/SFU activation 以正累计值证明首帧;暂停期间仍保留的 prepared SFU 在 Resume 时先取 baseline,再要求后续增长。观察器在 proof、promotion、pause、换代或 teardown 时停止,不增加另一 success/failure deadline,也不参与 candidate 选择。Active route 仍由既有两秒 stats sampler维护诊断和 decoded stall,两者不得互相替代。SFU subscriber 的同一 sampler 从 active 开始持续到 deactivate/teardown;没有 video track、合并 report 为空或读取异常时只向 decoded-stall owner 交付一次 `null` progress sample,真实 metrics 仍只在有效 report 存在时交付。Track 换代同时换代 accumulator,旧异步结果不得驱动当前 route。--一个 operation 只有一个 timer 和一个总 deadline。Initial acquisition 给 direct 一个由生产首帧数据标定的固定 foreground window;显式硬失败可在该绝对窗口内推进其他 direct,silent candidate 到达边界后释放 reservation并转入SFU。Exact direct若在边界前报告标准WebRTC transport connected,就保留到总deadline继续等待第一解码帧;该进度不提交graph。SFU取得首帧后,剩余direct tuple才作为background逐Viewer轮转;没有SFU时仍使用完整deadline。不存在逐candidate timer或随人数切分的预算。--首次需要 SFU 但 Host 已满时,controller保存原始demand/session和本fact已试carrier集合,依稳定顺序让一个健康Host-direct child用普通SFU candidate建立publication。该candidate必须持有既有`TransitionOverlapSlot`;需要先切断健康carrier的bounded-gap计划不具资格。失败保持carrier及其subtree并尝试下一carrier;全部耗尽时终态归原始demand,同一fact不为后续demand重复整套carrier。成功后原demand下一次先尝试SFU,失败仍可继续direct suffix;carrier自身也进入低优先级direct convergence,待容量允许时恢复原Host直连。--所有非服务器端点共享一个 server-authoritative steady outbound media-copy cap `C`:唯一配置 `ENDPOINT_MEDIA_COPY_CAPACITY` 默认 `2`,只接受 `1`、`2` 或 `3`,不兼容旧键。服务端将 endpoint 当前广告的 `0..C` 可用值 clamp 为唯一 `effectiveDownstreamCapacity`;该值只表示当前可用 sender slots,不建立角色、浏览器、UA、设备或页面可见性 tier。peer child 或 Host publication 各占一份,upstream receive 免费;SFU subscriber egress 使用独立 server admission。Browser `screener-v13` 的 `authenticated.endpointMediaCopyCapacity` 把部署 `C` 交给 Host 与 Viewer;两端用该值校验稳态 assignment,并让 active+pending 的物理 copy 只在 controller 已授权 overlap 时达到 `min(C + 1, 3)`。代码通过一个 shared accounting guard 执行,不重复 magic number;其他 wire 与 Native executable 在 authority 前拒绝,不保留兼容路径。任何会产生第四份 endpoint media copy 的 token都不得签发;`C=3`满载bootstrap保持健康树并明确失败。--SFU admission 在应用单进程中只有一个注入实例。LiveKit credential tuple 完整时必须显式配置私有 `LIVEKIT_API_URL`;固定四位房号池给出 9000 个 publication ingress,上界 `9000 * MAX_VIEWERS_PER_ROOM` 给出 subscription egress,不存在独立 SFU 容量配置。专用 LiveKit 实例设置 `room.auto_create: false`。账本只保存全局已用计数,以及 exact room/share/publication generation 下的一份 publication handle 和按 Viewer identity 索引的 subscription handle。Publication 的 `reserved | committed | draining` 占 ingress `1`,每份 subscription 的同类状态占 egress `1`;离开 route 的 subscription 在该 generation 删除并确认 absent 前保持 draining,同一 Viewer handle 再次启用不重复计数。首个 SFU child 先 reserve publication 与自己的 subscription,再通过 `RoomService.CreateRoom` 创建 exact-generation room,成功后才 prepare 和签发 token;后续 child 只在同 generation reserve subscription 并复用 Host publication。exact candidate child 的 first decoded frame 后 commit 自己的资源;publication replacement 将旧 generation 及其全部 subscription 一起转入 draining,失败、超时、失联、分享换代、停止或删房按资源所有权进入同一生命周期。只有 `RoomService.DeleteRoom` 成功且 follow-up lookup 证明 room 不存在,账本才扣除该 generation 的 ingress/egress;auto-create 关闭后,旧 token 不能重建已删除 room。进程启动在接受流量前拒绝任何非 Screener room,删除全部遗留 Screener room并确认 namespace 为空;关闭时先 drain 再遗忘计数。Host 信令离线期间若 exact room 中的 Host participant 仍存在就继续计费并保留健康媒体,participant 消失后在一个有界轮询周期内回收。稳态 reserve/commit/drain bookkeeping 仍是 Map lookup 与整数加减;只有 generation 创建、删除、启动清场和 Host 离线检查访问 LiveKit control plane。多应用进程部署必须先增加共享原子 admission/lifecycle owner。--只有实际因 deployment-wide SFU admission 失败的房间进入一个 `resourceWaiterRoomIds` Set。LiveKit delete-plus-absent 使真实 usage 下降时,owner 一次 drain 该 Set,对每个仍存在的 controller 调用 `touchExternalFacts()` 并排入普通 reconcile。它不轮询、不按资源类型复制 route state,也不唤醒未等待资源的房间。--普通 Web relay 把收到的 remote track 加入独立 downstream `RTCPeerConnection`,因此可能逐跳解码和重编码;浏览器不保证跨连接 shared encode。每条 ordinary child 是独立网络副本,实际 encode time、CPU/GPU、bitrate、loss、frame rate、depth 和 recovery 必须测量。--迁移使用 authenticated room/endpoint sessions、share generation、base/pending route revision 与 candidate connection identity。`route-update/prepare` 显式携带当前 operation 的 exact child peer ID、route kind 与服务端生成的 candidate connection ID;parent 与 child 直接使用该 candidate。服务端在每个 WebSocket 上先发 prepare,再发其 SFU config,并在允许 parent offer前先排入 child 的 companion;客户端依赖 WebSocket顺序而不维护消息重排 inbox。可用旧 route 保持 active,candidate 在 active map 外准备;candidate child 的第一帧新 decoded video 触发 `settleReady(commitAdmissionSync)`,成功 candidate `P` 下发 active `P`。失败、超时、代次变化或授权撤销销毁 candidate,保持仍有效的 committed graph 内容并先下发单调递增的 active rollback revision `R > P`,再准备后续 candidate;一个 monotonic allocator同时拥有 prepare/commit/rollback/retirement/prune revision。Direct edge 的 stock WebRTC rebuild可在 exact current sessions内原子采用新 connection ID而不改变 topology。Make-before-break 的 overlap 由统一端点容量、单个有界 `TransitionOverlapSlot` 和 typed server-resource admission 同时决定;stop/delete通过controller `dispose()`一次返回所有current与committed资源。--SFU 的 publisher、subscriber、central admission、resource accounting、temporary overlap 和 fallback sequence 由 ADR-0005 统一定义。普通端点 child count 不能成为 server cap,兜底也不能形成无界 whole-room fanout。一个 Host publication 服务所有 SFU subscriptions;SFU-fed 与 peer-fed endpoint 使用相同的 provisional-child first-frame transaction。--Browser SFU publisher 与 subscriber 在 `Room.connect` 时都传入同一个显式 `rtcConfig: { iceServers: [] }`。LiveKit signaling SDP 继续交付专用 SFU 的授权 UDP candidates,并由标准 ICE 选择 nominated non-relay pair;candidate type、地址族、数量和浏览器 socket 分配都不是应用不变量。该配置只阻止 pinned SDK 合并 join response 或默认公共 STUN,不删除 remote candidate、不改变 ordinary peer 的 STUN 配置,也不改变 LiveKit server 使用部署 STUN 发现自身公网地址。它移除 SFU PC 不需要的外部 STUN/TURN 目的地,避免本次 TUN reproduction 中的 external-STUN/SFU association 冲突。连接失败仍由现有 operation deadline 和 typed failure处理,不增加 TURN、端口、重试层或专用超时。--relay 自身 ingress 失效时,reconcile 把它作为 child 换父并保留 subtree。endpoint disconnect 或 effective capacity 降低时,只保留稳定顺序内可容纳的 children,并把 overflow children 逐个送回同一 reconcile;offline childless participant 自然删除。Browser child复用现有 WebRTC/LiveKit stats sampling保存 exact active route的 `lastDecodedAt`;采样出现新 decoded frame就更新,route/connection变化就重置,超过统一 deadline只报告一次 exact edge。权威 pause abort pending operation、保留 active graph、让新参与者 waiting,并抑制/重置 decoded stall;resume重新从当前采样建立基线。Track availability、A/B/C、码率、FPS、模糊、sender stats和SFU layer只用于框架恢复或诊断。--实现迁移以当前 ADR-0005 invariants 为准;代码迁移只保留仍满足当前 identity、first-frame commit 和 bounded-recovery 约束的部分。-## 官方与参考资料--访问日期为 2026-08-18 至 2026-08-21:--- [Vite Getting Started](https://vite.dev/guide/)-- [React: Build a React app from Scratch](https://react.dev/learn/build-a-react-app-from-scratch)-- [Node.js release status](https://nodejs.org/en/about/previous-releases)-- [ws official README](https://github.com/websockets/ws/blob/master/README.md)-- [Screen Capture specification](https://www.w3.org/TR/screen-capture/)-- [WebRTC specification](https://www.w3.org/TR/webrtc/)-- [Media Capture Content Hints](https://www.w3.org/TR/mst-content-hint/)-- [RTCRtpSender.replaceTrack](https://www.w3.org/TR/webrtc/#dom-rtcrtpsender-replacetrack)-- [WebRTC Stats](https://www.w3.org/TR/webrtc-stats/)-- [WebRTC SVC](https://www.w3.org/TR/webrtc-svc/)-- [Media Capabilities](https://www.w3.org/TR/media-capabilities/)-- [WebCodecs](https://www.w3.org/TR/webcodecs/)-- [WebRTC official samples](https://webrtc.github.io/samples/)-- [coturn server documentation](https://github.com/coturn/coturn/blob/master/README.turnserver)-- [coturn example configuration](https://github.com/coturn/coturn/blob/master/examples/etc/turnserver.conf)-- [Cookies: HTTP State Management Mechanism draft (RFC6265bis)](https://datatracker.ietf.org/doc/draft-ietf-httpbis-rfc6265bis/)-- [Node.js `crypto.createHmac()` and `crypto.timingSafeEqual()`](https://nodejs.org/api/crypto.html)-- [W3C WAI: Labeling Controls](https://www.w3.org/WAI/tutorials/forms/labels/)-- [W3C WAI-ARIA APG: Disclosure Pattern](https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/)-- [W3C WCAG 2.2: Focus Order](https://www.w3.org/WAI/WCAG22/Understanding/focus-order.html)-- [W3C WCAG 2.2: Target Size (Enhanced)](https://www.w3.org/WAI/WCAG22/Understanding/target-size-enhanced)--MiroTalk BRO(AGPL-3.0)和 Screego(GPL-3.0)仅用于结构研究。Tailchat Meeting(Apache-2.0)用于捕获生命周期对照,但它采用 mediasoup/SFU,不作为本项目拓扑或依赖底座。项目许可证确定前不复制 GPL/AGPL 代码。-----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"deleted file mode 100644index d19108e6..00000000--- "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"+++ /dev/null@@ -1,195 +0,0 @@-# 屏幕共享项目需求理解--## 2026-08-18 13:31--## 需求概述--### 当前路由不变量--`PEER_ASSISTED_MEDIA=true` 是旗舰部署的单一总开关;每个房间独立保存 route revision、会话代次、失败状态和容量预算。系统优先使用 direct/peer UDP,普通 peer 连接保持 STUN-only,唯一应用兜底是专用 LiveKit SFU/UDP。所有非服务器端点使用同一个服务端权威稳态 outbound media-copy capacity:默认 `2`,只允许静态配置 `1`、`2` 或 `3`;peer child 或 Host 的唯一 SFU publication 各消耗一份,上游接收不消耗该预算,角色、浏览器、UA、设备或页面可见性不产生特例。--构建一个面向熟人游戏场景的低延迟屏幕共享工具。分享者可以在私密房间内分享游戏、应用窗口或显示器画面及声音,多名朋友可以即时观看。中心服务负责房间、身份、确定性路由和建立连接;每名 Viewer 同时至多一个 active upstream,活动媒体图保持无环且可达源。切换绑定当前鉴权会话、分享代次和唯一 pending revision;可用旧边保留到 exact candidate child 解码出第一帧新画面,所有路线最终进入有效媒体、明确等待或有界失败。系统自动完成分配和恢复,用户不手动选择拓扑。当前发布面只包含 Web Host、Viewer 和 browser relay;Electron/原生 sender、capture helper 与 shared-encode executable 属于最低优先级的后续增强。观看端使用普通桌面或手机浏览器。--SFU 的 publication、subscription、server-resource accounting、临时 overlap 和 direct-to-SFU fallback 序列由 ADR-0005 的整体模型统一定义,不能从普通端点 child 数量推导。SFU 只能是有界兜底资源,不能把产品改成无界或 always-SFU 的整房转发。当前 PoC 的观看人数限制是实现事实,不是性能声明;任何扩容目标必须以真实资源、质量、深度和恢复矩阵另行验收。产品不承担公开直播或大规模观看。--## 功能需求--### P0 - 必须实现--- 首屏双入口:分享入口通过站点访问后,主工作区必须同等突出“开始分享”和“加入房间”两个主要动作,并用清楚的视觉分隔表达发送与接收;持合法房间 grant 的观看者不需要知道站点访问密码。“加入房间”在当前舞台内就地展开房间码输入并提交,不先跳转到独立页面;直接访问 `/join` 仍提供同一输入能力。不增加营销首页、模式向导或拓扑选择。浏览器标签页使用与现有 `MonitorUp` 品牌语言一致的 favicon。-- 简单房间:分享者从当前空闲池随机获得一个 `1000` 至 `9999` 的四位房间码,房间码只负责定位,不是秘密或永久身份。Host 与 Viewer 标题附近都紧凑、显眼地显示房间号并提供只复制房间号的动作;Host 的复制按钮左侧保留一个申请新房间号的刷新图标动作。该动作销毁旧房间并走同一回收流程,使旧 Host token、密码 verifier、Viewer grant、授权代次和媒体路由全部失效,再按普通建房流程取得新号码。每个新房默认生成含独立 Viewer grant 的完整邀请链接,Host 的主分享动作复制该链接。房间号入口只有公开和私密两种状态;新房默认公开,允许已通过站点访问的 Viewer 直接用房间号加入且不设房间密码。私密且未设置密码时只有有效邀请可加入;设置密码后才额外允许房间号加密码加入。邀请链接与房间号准入相互独立。所有入口只授予该房间 Viewer,不能建房、发布、冒充 Host 或跨房。-- 免安装观看:桌面和手机观看者可直接通过浏览器链接进入、授权并播放,不依赖与分享端相同的桌面客户端。-- 屏幕采集:分享者可主动选择显示器或应用窗口,开始、停止、临时同步暂停音视频和切换分享来源;暂停保留现有连接并禁用当前 capture stream 的全部媒体轨道。服务端按当前分享代次同步这一主动暂停状态,观看端在视频舞台显示“分享者已暂停”,不得从黑帧、track mute 或网络状态推断暂停;晚加入和信令重连使用权威快照,恢复、停止、新分享或会话替换清除旧提示。Host 本地预览必须直接使用 capture stream;页面失焦或隐藏时只暂停本地 video element,并明确提示“本地预览已暂停,分享仍在继续”,恢复焦点后继续预览,不得停止 capture、编码或上行。预览不得建立 viewer/媒体边或消耗 SFU、应用服务器 media egress;预览仍可能产生本地合成、缩放和 GPU 显示成本,不能把隐藏预览称为停止采集或编码。-- 游戏声音:Windows Chrome/Edge 的初次分享和切换来源都默认请求可用的标签页、窗口或系统音频;浏览器、系统、所选来源或用户没有返回音轨时必须明确提示,而不是静默无声或阻止 video-only 分享。-- 观看端本地播放:Viewer 使用同一个带浏览器原生 controls 的 video element 承载播放/暂停、音量、静音和全屏;这些动作只影响当前浏览器,不修改 Host 音轨、编码、房间状态、路由或其他观看者。Host 本地预览不提供媒体 controls,权威暂停仍由明确的“暂停分享”动作拥有。-- 本地昵称与房间成员:用户可设置一个只保存在当前浏览器同源 `localStorage` 的显示名,界面统一称为“昵称”;默认以只读文本显示,铅笔编辑按钮紧贴昵称,点击后才进入编辑。Viewer 顶部标题直接显示“{Host 名称} 的屏幕”,不得在下方重复一行 Host 名称。信令只在当前在线 socket 会话内保存和广播 NFC 规范化、最多 24 个 Unicode code points、拒绝控制/换行/双向覆盖符与孤立 surrogate 的纯文本标签,不写服务端持久存储或日志。空值使用通用角色 fallback。Web Host 与 Viewer 都必须看到全部当前在线 Viewer 的权威总数与 roster,不能拿最多两条 Host 媒体直连数冒充在线人数;presence 更新也不得创建媒体连接。展示身份默认只显示名称;仅当房内出现同名时追加当前房间 `peerId` 的至少六字符短后缀,并只在同名项后缀碰撞时有界延长。显示名、后缀和 `clientId` 都不是账号、授权身份或全局 UUID,重复名称允许且不得参与授权、路由或质量决策。Web Host 与 Viewer 通过同一 opt-in participant roster 看到 Host 名称;Native/executable sender 不在当前发布面,也不接收 Web roster。-- 一对多观看:每个房间允许一名 Host 和最多 `20` 名 authenticated Viewer;房间 admission 与端点下游容量、SFU admission 分别配置,超额加入必须明确拒绝。观看人数不从 endpoint cap 推导,20-Viewer smoke 只证明控制面与资源上界,不是任意网络质量声明。-- 端点发送容量:所有非服务器端点使用同一个服务端权威稳态 outbound media-copy capacity,由唯一部署项 `ENDPOINT_MEDIA_COPY_CAPACITY` 配置,默认 `2` 且只接受 `1`、`2` 或 `3`;不读取旧键或保留第二套 tier。peer child 或 Host 的唯一 SFU publication 各消耗一份,上游接收不消耗该预算。客户端只能声明不高于部署值的可用容量,角色、浏览器、UA、设备类型和页面可见性不产生不同上限。服务端在每次 `authenticated` 权威快照中返回最终 `endpointMediaCopyCapacity`;普通非 peer-assisted 模式也只授权稳定加入顺序中的至多 `C` 个 Host child,超额 Viewer 保持入房等待并在槽位释放后提升,信令不能绕过该集合。Browser Host 与 Viewer 严格校验该值并用它约束稳态 assignment;并行产生媒体的 candidate 必须持有唯一 `TransitionOverlapSlot`,active+pending 物理 copy 只可达到 `min(C + 1, 3)` 并在 commit/abort 后释放。`C=3` 满载时必须先收到 active bounded-gap retirement 再 prepare,绝不产生第四份 copy。SFU subscriber egress 由独立 server admission 记账。当前不兼容房间合同以单一 release 原子升级;缺失/非法 cap、旧 wire 与 executable sender都在取得room/route authority前fail closed。-- P2P 优先:每条普通逻辑媒体边先尝试 direct/peer UDP,服务器不得默认中转可直连媒体。更多观看者优先沿满足统一端点容量的无环 peer 图分布;每名 Viewer 同时至多一个 active upstream,失败时只影响需要重选的 child。任何 source-reachable endpoint 在 effective capacity 有空位时都可作为 parent candidate;Peer-fed 与 SFU-fed endpoint 使用同一个 provisional-child transaction,并在 candidate child 解码出第一帧新画面后独立提交该 edge。Host 已满且首次需要 SFU 时,同一 controller 用有限 carrier cursor 建立唯一 publication;carrier 必须能在既有 overlap 上限内完成,不能先切断健康分支。终态归原始等待需求,publication 成功后该需求先取得 SFU 画面,剩余 direct candidate 再在后台收敛;完整事务由 ADR-0005 定义。-- NAT 与传输边界:STUN 必须可用,所有 ordinary peer `RTCPeerConnection` 只接收 STUN ICE servers。Browser LiveKit publisher/subscriber PC 必须显式使用空 `iceServers`,保留 LiveKit signaling 交付的授权 SFU UDP candidates,并由标准 ICE 选择 nominated non-relay pair;不得把 ordinary-peer STUN、LiveKit join response 中的 STUN 或默认公共 STUN混入该 PC,也不得把某一种 candidate type 或数量写成成功条件。部署 STUN 仍供 ordinary peers 和 LiveKit server-side 公网地址发现使用。浏览器 ICE connectivity checks 是 direct UDP 可达性的权威;Screener 不合成 remote candidate、不预测端口、不分类 NAT,也不使用 TCP 探测推断 UDP 媒体可达性。所有恢复和候选授权必须绑定 authenticated room/endpoint session、share generation、base/pending route revision 与 candidate connection identity;成功即停止,失败、超时或绑定失效即撤销,direct 阶段耗尽后在同一 operation deadline 内进入 SFU/UDP,全部可用路径耗尽后明确等待或失败。已接受的完整顺序只有保持或尝试 direct/STUN peers,再复用或建立 direct-ingress Host publication/SFU subscription。Screener 不配置 TURN、ICE/TCP、media TCP 或 TLS-relayed media;当前 LiveKit 也保持 UDP-only。未来若真实严格防火墙矩阵证明需要另一种传输,必须把它作为 LiveKit 内部能力重新决策,不能增加第三种应用 route candidate。LiveKit join JWT 仅按协议进入不得记录的 WebSocket request target;HTTPS/WSS 继续独立使用 TLS/TCP。-- 质量控制:推荐档位始终只有 720p30(3 Mbps)、1080p30(5 Mbps)、1080p60(8 Mbps)三档,默认选择中档 `1080p30`。高级设置的分辨率选项增加 `480p`(854x480),其 FPS 与码率仍由高级控件独立选择;不增加 `480p` 推荐档、preset ID 或固定的 480p FPS/码率组合。三档与高级设置初始值统一采用中档 `balanced`(均衡),`maintain-resolution`(清晰)、`maintain-framerate`(流畅)保留为显式选择。Browser Host 在未分享时提供本地 `VP8 | 自动 | H264` 选择并在分享期间锁定;自动模式每个新分享代次运行一次有界实际 sender 预检,Relay 在该代首次取得 upstream source 且尚无 child 时运行同一预检。H.264 源帧与编码帧进度通过时,未来 direct/relay offer 原生排序 H.264 后接 VP8,Host 的唯一 SFU publication 也使用 H.264;不支持、证据不足、超时或表现不达标时只使用 VP8。Resolved codec 不进入质量状态或 wire、不持久化,也不因质量设置、换源或换父重复探测或切换已连接线路。分享期间可直接换视频档位和 64/128/192 kbps 音频 sender ceiling,音频默认选择中档 128 kbps,不重新选择来源或重建健康连接。Peer-assisted relay 与已配置的 SFU 必须接收同一个严格校验的房间级权威设置,覆盖当前和以后建立的 sender;普通 P2P 信令结构保持不变。任何设置都只是浏览器上限和偏好,具体降级由 WebRTC/LiveKit 决定;必须读回实际 sender 参数并通过 stats 观测结果、显示参数拒绝、改写和持续受限原因。Host 资源不足时由 Host 主动选择较低的现有档位。Screener 不设置自定义 SFU layer list、动态 FPS、综合评分或周期性全房间调档。-- 路径隔离表示:direct/peer 继续使用每条 PeerConnection 独立的 stock WebRTC GCC,不把 Viewer 反馈合成全房目标。Browser Host 的唯一 SFU publication 不设置 `screenShareSimulcastLayers`,由锁定的 LiveKit client 默认行为拥有当前 H.264 或 VP8 source decision 对应的 screen-share representations、source replacement 与 republish;LiveKit Dynacast 和启用 send-side BWE 的 server stream allocator 负责需求聚合与每个 subscriber 的实际下行层。Screener 不实现质量评分、带宽估计、周期调档或应用媒体层 selector。所有当前 Viewer 都可能承担 peer children,因此 subscriber 保持 `adaptiveStream: false`,不得让本地元素尺寸或可见性控制 relay ingress。表示选择不改变拓扑、端点容量或路由失效权威。-- 路由失效输入:应用不推断 parent-wide 质量,也不计算综合分数。当前 authenticated child 只在 PeerConnection `failed/closed`,或非权威暂停时现有 periodic stats 在统一 deadline 内没有新 decoded frame 时,使自己的 exact edge 失效并唤醒同一个 reconcile。decoded progress 只保存 route-keyed `lastDecodedAt`,route/connection变化或新帧重置、暂停抑制,同一 edge只报告一次,不增加轮询器。Active SFU route 暂时没有 video track、stats report 为空或 stats 读取失败时,现有采样 cadence 仍把该次作为无 decoded progress 推进 deadline;它不得停表、伪造连接指标或立即判定 edge 失效,只有 route 停用或 teardown 才停止该 cadence。该 operation 把失败的 exact direct parent 在当前 fact version 视为已尝试;foreground direct window结束后用SFU取得可用画面,剩余direct candidate只在画面后方收敛,新的外部事实才允许本轮失败tuple重新进入。Track availability、低码率、低 FPS、模糊、sender/viewer stats 与 SFU layer只用于stock WebRTC/LiveKit恢复和诊断。relay自身ingress失效时,它作为child换父并保留subtree;disconnect或effective downstream capacity降低只让direct/overflow children逐个走同一事务。-- 断线恢复:临时网络变化先交给 WebRTC/LiveKit 的 ICE、consent、重连和流状态。Direct edge 可在 exact current parent/child sessions 内采用 framework rebuild 的新 connection ID而不改变topology。应用只在上述exact edge失效后运行一次有界reconcile;任一步成功即停止。候选耗尽时hard-invalid、confirmed-departed或overflow edge被退休并进入明确waiting,healthy bootstrap edge保留。所有异步结果受authenticated session、share generation、base/pending route revision与candidate connection identity约束,未受影响分支保持sticky。权威暂停abort未提交candidate、保留active graph、抑制stall,并在resume后重新reconcile。-- 每名 child 只有一个有界 operation deadline;foreground direct 预算、SFU 可用性优先和后台 direct 收敛由 ADR-0005 的同一 cursor 模型定义,不配置逐 candidate timeout。Exact direct 的标准WebRTC transport-connected只把当前wake延长到该总deadline,不提交graph;第一解码帧仍是唯一commit证据。20 名 Viewer 同时加入时,单一 room-serial operation 仍可能形成线性排队尾延迟;在接受另一种并发模型前,只测量 queue wait、candidate start、first decoded frame 与 final route 的 p50/p95/max,不用 NAT 猜测、TCP probe 或 magic timeout 绕过排队。-- 可观测性:按目标 RTP transport 与不透明连接/ICE 代次关联 selected path、`iceGatheringState`/ICE/connection state、事件推导的建立时长、generation-baselined pair-change delta,以及 RTT、RTP 丢包率、抖动、码率、帧率、编码耗时和受限原因。候选、route decision、队列时序与错误的 wire 和日志使用封闭 schema 和 code bucket,禁止 raw SDP、candidate、地址、URL、`errorText`、真实 peer/parent/session/connection identity 或网络标识。Host 与 Viewer 产品 UI 不提供连接诊断文件下载;本地折叠详情只显示当前页面直接观测到的连接事实。现有 Host-only bounded route snapshot 保留给自动验收,不连续推送、不进入产品 UI、也不形成 route authority。只有创建该 `RTCPeerConnection` 的本机可显示浏览器对 selected local/remote candidate 实际暴露的地址与端口;该值不上传、不持久化、不用于地理/NAT 推断,缺失或被隐私保护时显示未知。-- 渐进式诊断:分享者和观看者默认只看到房间、画面、核心状态和常用控制;Host 对每名 Viewer 使用同一种卡片,不按 direct、Peer 转发或 SFU 分组。卡片只把本机连接或当前 Viewer 接收证据称为“已连接”,其余状态保持中性的“线路分配中”或具体连接状态,不把 active assignment 当作连接成功。展开连接详情也只在当前媒体证据成立后显示绿色 `P2P` 或黄色 `SFU fallback`;一级只保留分辨率、帧率、码率和丢包等一眼可读的实际画面结果,二级只显示当前确有值且能解释网络、编解码或播放质量的指标,并显示实际 H264/VP8 codec。Host capture strip 在详情开启时显示本分享代 resolved codec;这不是每条 edge 的协商替代品。实际 codec 超出 accepted H264/VP8 contract 时继续提示;候选地址、候选对 ID、STUN 计数、RID、fmtp 和其他浏览器内部标识不进入产品 UI。Host/Peer/SFU 的精确上下游与分支结构只由独立权威拓扑视图表达,不在卡片内重复。远端 Viewer evidence 的详情 shell 在同一 viewer/upstream/connection/route identity 内保持稳定并保留每个字段最后一次真实非空观测;五秒 freshness 只决定 evidence 能否继续证明“已连接”,`connecting`/`disconnected` 立即降为非 fresh,`failed`/`closed`、identity/session/share/route 变化或非单调 sequence 则清空/换代。隐藏诊断不能隐藏失败原因、音频缺失、持续画质受限、编码合同偏离或需要用户操作的告警。-- 站点访问:生产部署必须配置独立的 `SITE_ACCESS_PASSWORD` 控制建房、Host 信令角色和所有 code-only Viewer 入口;只有本地开发/测试可显式关闭。非空值接受 8 至 128 个可见 ASCII bytes,不能复用 LiveKit、TLS 或其他部署 secret。`POST /api/site-access` 验证成功签发 12 小时、无服务端会话状态的 HttpOnly、`SameSite=Strict` site-access cookie。有效 room-scoped fragment grant 可绕过站点 gate 直接进入对应房间;其余 `/r/{code}` 和 `/join` 必须先持有效 site-access cookie,之后才检查房间是否存在与 `open | private` code-only policy。未分配、已回收或已过期的 code 返回 `ROOM_NOT_FOUND`;现存私密房间的无密码、缺失或错误密码及容量拒绝继续使用 `ROOM_ACCESS_DENIED`。建房 HTTP 只认该 cookie。已移除的旧环境变量、endpoint 和 cookie 不保留兼容。不引入账号、JWT、服务端 session Map 或通用 logout。-- 房间级观看授权:新房间总是生成一个 128-bit 随机、22 字符 base64url、可 rotate/revoke 的 room-scoped Viewer grant;服务端只在该 exact room incarnation 保存完整 grant 的 SHA-256 摘要,稳定模式可持久化该摘要与 authorization generation。grant 没有独立到期时间或内嵌 room/expiry 字段,与房间同寿,并在房间回收、显式换房、轻量模式重启、rotate 或 revoke 时失效;同号新房间使用新摘要,旧链接不能进入。浏览器从 URL fragment 严格读取 grant 后,只写该房间的 `sessionStorage` 并立即用 `history.replaceState` 清除 fragment;刷新和页面内重连可继续。code-only 入口独立采用 `open | private`,默认 `open` 且无房间密码;`private` 可不设密码并拒绝全部 code-only 尝试,设置密码后只接受匹配值。所有 code-only 尝试先通过站点访问。raw grant 不得进入 `localStorage`、cookie、query、WebSocket URL、Referrer、SQLite、日志或错误。Host 可独立 rotate/revoke grant、改变 code-only policy 或设置/移除密码;授权变化必须先提交新的权威代次,再清除 Viewer grace/路由、终止旧代次信令和媒体并断开受影响 Viewer。-- 房间权威状态:服务器只在一个有界 RoomStore 中保存房间码、租期、Host token/Viewer grant 摘要、authorization generation、code-only policy、可选 48-byte 房间密码校验材料、参与者和控制状态。`ROOM_LEASE_SECONDS` 默认 `86400`;Host 正在分享时不回收,停止分享或 Host 断开后开始 dormant lease,同一 Host token 在期限内重新分享即续租,Viewer 活动不续租,过期后释放号码。`ROOM_DATABASE_PATH` 未配置时全部状态随进程退出;配置时 SQLite 只保存房间权威 aggregate,参与者和媒体控制仍随进程退出。不存在账号、用户表、持久服务器 session、旧 schema reader 或 migration chain。-- 本地 Host 偏好:房间所有权继续使用随机 Host token,不使用 IP、UA、硬件信息或浏览器指纹。Host 浏览器在同源 `localStorage` 保存 raw Host token,以及昵称、code-only policy 和可选房间密码组成的创建偏好;另以无秘密记录只保存上次实际分配的四位号码。该 preferred room 没有本地租期、倒计时或续写 timer,也不证明或延长服务端 `ROOM_LEASE_SECONDS`。服务器保存 token 摘要和密码 verifier,稳定模式可将其持久化。旧 ownership 过期/失效后的下一次显式分享始终请求原号码;服务端只在号码空闲时分配,否则随机分配并返回新的本地偏好。两种结果都创建全新 room incarnation、Host token 和 Viewer grant,不恢复旧成员或路由。换设备、换浏览器或清理站点数据即没有该偏好。-### P1 - 重要功能--- 公网服务器一键部署包:在用户自有的公网服务器上一键部署当前 Web/信令应用、易失房间状态和所需 STUN/SFU/反向代理组件,复用唯一配置、secret、路由、健康检查和恢复合同。普通 app-only 更新先验证新的不可变 artifact 再原子切换,切换前 application release 只保证保留到有限 health/postflight 完成;之后没有保留合同,也不作为维护中的备份。只有实际改动基础设施、配置、secret、持久或不可逆状态时,才为被触及表面定义恢复并预检。它不是托管服务,不能内置真实凭据或跳过域名、TLS、防火墙、端口、容量和适用的恢复预检。-- 本地自包含一键包:提供 Windows、macOS 和 Linux 可分发的桌面包,在分享者电脑上同时运行 Host、当前 Web/信令应用服务器和本地状态,朋友继续通过普通浏览器邀请观看。安装后启动不要求源码 checkout、Node 或任何外部 Screener、STUN、SFU、隧道或 relay 服务;它尽力使用本机可达入口和 direct P2P,但必须明确报告公网入口、可信 HTTPS/WSS、网关映射或 NAT 路径缺失,不能承诺任意 CGNAT/严格防火墙必通。两种分发包都排在当前功能、路由、NAT 和真实网络 TODO 完成之后。-- 独立房间入口:合法 `/r/{code}#v={grant}` 邀请直接进入对应房间;没有 grant 的 `/join` 或 `/r/{code}` 先显示明确标为“站点访问”的整站验证,再提交 code-only 尝试。`open` 且可准入时直接进入;未分配、已回收或已过期的 code 明确显示“房间不存在或已过期”且不提供密码输入;现存房间的其他预期拒绝使用 `ROOM_ACCESS_DENIED`,不披露具体 policy。有效 site-access cookie 只跳过第一步,两类密码不得复用或互相替代。Host 可设置、轮换或移除房间观看密码;密码接受 1 至 64 个可见 ASCII 字符,异步 scrypt 全局最多执行 2 个、等待 16 个派生。Host 可把房间密码保存在同源本地创建偏好中;它不得进入 URL、cookie、日志或服务端持久存储。--- 统一自动路由:旗舰部署开启 `PEER_ASSISTED_MEDIA` 后,每个房间只有一个服务端 route controller、一个 committed graph、一个 pending child operation、一个串行 pump 和一个 operation deadline timer。Graph 必须无环、source-reachable,且每名 Viewer 同时至多一个 active upstream;加入、容量变化、离开、exact edge 失败与非暂停 decoded-frame stall 都只唤醒同一个 reconcile,其余健康分支保持 sticky。候选先按身份、source reachability、无环、effective capacity 与 sender transition 过滤,再按深度、剩余容量、稳定 child-parent hash 和稳定身份排序;server admission、exact transport progress、首帧 commit、Host-full bootstrap、后台 round-robin 与终态所有权统一由 ADR-0005 定义。普通 peer 始终 STUN-only,SFU 使用独立 admission;不建立第二 graph、周期性重平衡、质量评分或独立 depth cap。-- 观看端连接反馈:Viewer 舞台从鉴权到首帧使用一个由现有权威状态推导的稳定阶段反馈,至少区分等待分享、分配线路、建立 P2P、连接 SFU、等待首帧、浏览器阻止自动播放、恢复连接和有界失败。阶段不是进度百分比,也不产生 route authority;只有当前 video element 实际提交首帧后才显示正在播放。Autoplay rejection 通过原生媒体 controls 恢复;连接中不显示虚假的播放动作。手动“重新连接媒体”只恢复当前 exact route:P2P 直接重建到同一 parent 的连接,SFU 只断开并重连当前 publication 的 subscriber;两者都保留 Screener WebSocket、房间会话和 route revision,不触发主动换父、质量选优或 P2P/SFU 重选。真实恢复耗尽后才进入既有 route-failure operation。仍有已证明旧帧时保留为背景并显示恢复状态,不为显示反馈主动清空健康 media element。页面从冻结/隐藏恢复时先重置 decoded-stall wall-clock baseline 并重新证明当前代画面,冻结时间本身不得成为立即换路依据。Host 离线本身不使仍健康的媒体失效;exact upstream 硬失败或 route terminal failure 必须使 current frame proof 失效,已证明画面至多降为 retained background,不能遮蔽离线或有界失败。已接受的 `screener-v13` 补充消息只有 strict、current-candidate-fenced 的 transport-connected 进度,以及仅允许 `waiting/sfu-admission` 与 `failed/route-exhausted` 两种配对的 `route-status` union;两者都不携带 raw text、额外身份或 retry hint,且都不产生 route authority。-- 质量控制扩展:推荐档位仍是默认入口且只保留 720p30/1080p30/1080p60 三档,当前页面初始 desired state 选择均衡的 1080p30 且不写 `localStorage`;“分享高级设置”允许 480p(854x480)/720p/1080p/1440p 分辨率 ceiling、15 至 60 的整数 FPS ceiling、2 至 12 Mbps 视频码率 ceiling、清晰/均衡/流畅三种偏好,以及离散的 `64 kbps 普通 | 128 kbps 音乐默认 | 192 kbps 保真` 屏幕音频 sender ceiling;480p 不形成推荐档或固定 FPS/码率组合,音频初始值为 128 kbps。视频档位和音频档位可在直播中显式应用。所有当前及以后建立的 Web Host、Browser relay 与 SFU sender 都读取最新 desired 档位,并各自在 fresh sender parameters 上应用和读回 endpoint-local applied 值;实际码率仍由浏览器拥塞控制和 stats 决定。Peer 只在唯一明确的 active Opus audio 上做结构化、幂等的 Viewer answer `stereo=1;maxaveragebitrate=192000` 变换,使同一接收上限覆盖三档;非目标形态或 parser/writer 异常必须原样保留浏览器 answer,不得阻断可继续的 mono/video edge。不得用宽泛字符串/正则改 SDP,也不得改写浏览器协商的 FEC。SFU 将 64/128 kbps 映射到 pinned SDK stereo music preset,192 kbps 使用显式 ceiling,统一设置 `forceStereo = true`、`dtx = false` 与 `red = false`。不得暴露任意码率、声道、采样率、audio codec、stereo、DTX、RED 或 FEC 控件;192 kbps 只是显式较高上限,不是无损、高保真或最低码率保证。实际质量持续低于所选上限时必须显示可解释的限制原因;在真实拥塞、编码器和接收端证据完成前,不把任一组合称为“完美平衡”。未来 microphone voice 若进入范围,必须是独立 track/处理链,不能把 AEC/降噪/DTX 套到电影或游戏音频。-- SFU 质量设置生命周期:直播中修改档位时,浏览器 sender 的 applied readback、LiveKit `LocalVideoTrack` 保存的 degradation preference、track restart options 与 `LocalTrackPublication` 的 republish options 必须作为同一次串行操作更新;任一步失败恢复旧 sender 与旧 SDK 保存态,旧 publication generation 不得回写当前状态。LiveKit full reconnect/republish 不得恢复初次发布的旧偏好。该修复不改变 codec、码率上限、层数或路由,也不能单独解释即时低帧。-- 本地预览性能候选:在相同动态场景中 A/B 测量 Host 动态预览开/关的 CPU、GPU、encode time 和实际 FPS。只有稳定收益且捕获、编码和远端画面不受影响时,才允许直播开始后默认显示静止缩略图或隐藏动态预览并提供按需展开;未测前不宣称收益。-- Peer-assisted 媒体路径:所有非服务器 endpoint 都受同一个服务端权威稳态 outbound media-copy capacity 约束,默认 `2` 且可静态配置为 `1`、`2` 或 `3`;peer child 与 Host publication 都按实际发送副本计数。每名 Viewer 任一时刻只有一个 active upstream,活动媒体图保持无环;只在离散事件中做有界分配或换父。浏览器把收到的标准 remote track 加入独立下游 `RTCPeerConnection` 时会逐跳解码并分别重编码,必须测量而不能称为 shared encode。服务端只在有界房间内存中保存严格校验的质量设置,不写入持久存储。-- 原生 shared encode 分享端:后续独立的 Electron/原生分享端若获新决策,必须让每个 active representation 只产生一份兼容编码结果,并在获准的 direct、peer 与 SFU transport 间复用。Native 如何满足届时锁定的 SFU representation contract 仍须通过明确硬件路径和真实游戏、编码、上传门槛。每条连接仍保留独立 WebRTC packetization、SSRC、pacing、加密和反馈,且各自消耗上传带宽。浏览器不保证跨 `RTCPeerConnection` 复用编码器,因此当前 Web spike 不能宣称满足该保证。-- 原生 shared encode relay:具备原生 relay 能力的非服务器端点同样受统一服务端权威下游容量约束,并应复用兼容编码输出而不再次编码。当前普通浏览器 relay 使用逐边重编码的标准 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`,违反当前 Browser 无 SVC、单表示合同。只有未来 native sender 能明确选择硬件编码器、最多发布两层、将同一编码输出复用于 direct/peer/SFU、保持每条路径独立选择并通过真实游戏和亚秒延迟门槛时,才可用新的 capability decision 重开 SVC;不能把浏览器 API 支持或 UA 推断当成采用理由。-- 分包/分层多树实验:把编码包、对象或可独立解码层拆到多个 peer 路径以分散上传,只能在独立 spike 中验证。必须保持亚秒级,处理多父重组、排序、丢包恢复、关键帧、同步和节点退出;未通过门槛前不进入产品路由控制器。-- SFU 中央兜底:产品部署提供有界 SFU 资源,但不要求用户选模式,也不得默认变成整房 always-SFU。只有 Host 拥有一个 authoritative publication;SFU-fed 与 peer-fed endpoint 使用同一个 provisional-child first-frame transaction,严格受限 endpoint 在没有成功 child candidate 时自然保持 leaf。启用 LiveKit fallback 时必须使用专用且关闭 `room.auto_create` 的实例,并显式提供私有 `LIVEKIT_API_URL`。固定四位房号池同时给出 9000 个 publication ingress 上界,subscription egress 上界为 `9000 * MAX_VIEWERS_PER_ROOM`,不另设 SFU 容量参数。单进程全局账本按 exact room/share/publication 保存一份 Host publication ingress,并在该 generation 下按 exact Viewer 保存 subscription egress;当前 publication 被后续 SFU Viewer 复用,每个 child candidate 只 reserve/commit 自己的 subscription。一份 publication 占一个 ingress,每份 reserved、committed 或 draining subscription 占一个 egress;离开 route 的 subscription 在整个 publication room 删除并确认 absent 前仍作为 draining 计费,同一 Viewer handle 再次启用不重复计数。新 generation 在发 token 前 reserve publication 与首个 subscription,并先通过 RoomService 创建对应 room;first-frame ready同步commit admission后才promote graph。publication replacement、abort、timeout、disconnect、share rollover、room stop/delete按资源差集或controller `dispose()`进入draining,只有DeleteRoom成功和absent readback才释放该generation的ingress/egress。启动时必须先拒绝外来room、清除全部遗留Screener room并确认namespace为空;Host信令离线但LiveKit participant仍存在时继续保留和计费,participant消失后有界回收。实际因deployment-wide admission失败的房间只进入一个waiter Set;LiveKit drain完成时一次性touch这些controller的external fact并走普通reconcile,不轮询。固定root数和普通endpoint child数不能代替准入;资源耗尽进入明确waiting或failure。多应用进程部署必须先引入共享原子owner。-- 分享端桌面封装:用 Electron 固定 Chromium 版本、改善选源/热键/系统音频体验,同时保留 Web 观看端。-- Windows 应用音频:Windows 11 Native sender 使用本地 opaque window target 绑定 HWND、PID 与进程创建时间,只捕获所选游戏及其子进程的音频,避免把语音聊天或通知声一并分享;“全部系统声音”只能由分享者显式选择。普通 Windows 10 不具备当前 process-loopback API 门槛,必须明确标为未解决/不支持而不是伪兼容。浏览器无法证明或隔离任意进程音频时必须如实提示,原生捕获失败、无声或进程退出不得静默扩大为整机捕获。-- 受限网络边界:当前媒体只使用 ordinary direct/STUN UDP 与 LiveKit SFU/UDP;全 UDP 封锁、只允许标准 HTTPS 出站等网络在有界窗口后明确失败。不得用 TCP 探测、客户端声称的 NAT 类型或另一套应用 route candidate 猜测可达性。若真实矩阵证明该失败边界需要扩展,先比较 LiveKit 内建 ICE/TCP 或其内部安全 relay transport,并另行接受安全、端口、延迟和部署合同。-- Web 编码:视频 track 使用标准 `contentHint = "motion"` 表达游戏/动态画面意图,音频 track 使用 `contentHint = "music"`;两者都不承诺实际 codec、分辨率、帧率、码率或硬件实现。Browser direct、browser relay 与 SFU publication 的唯一视频媒体 codec 是 VP8,不提供 Automatic/H.264/其他 codec 选择、fallback 或运行时切换。实际 codec/profile、encoder implementation 与 stats 继续作为只读诊断事实,不产生自动切换或路由 authority;依据由 [realtime quality research](./research/realtime-quality-adaptation.md) 持有。--### P2 - 可选功能--- 运行时有效容量:部署的 steady cap `C` 仍只接受 `1`、`2` 或 `3` 且默认 `2`,不按角色、设备或 UA 分类。服务端把 authenticated endpoint 当前广告的 `0..C` 可用值 clamp 成唯一 `effectiveDownstreamCapacity`;`0` 表示当前不承担下游,不是另一套 release tier。controller 通过同一个 reconcile 迁移 deterministic overflow children。H.264、hardware encode 或 shared encode 可以降低编码成本或同观感码率,但每个 ordinary child 仍消耗一份网络副本。-- 原生 Windows 捕获辅助程序:显式 `native-window-h264` 模式使用同一 bound window target 的 WGC/D3D11 画面与 WASAPI process-tree PCM,并用 adapter-bound、hardware-only Media Foundation H.264 `42c01f` 直接进入现有 Go fanout;普通 Web Host 保持独立的 Browser codec 路径,不允许运行时静默改用软件编码、显示器画面或系统混音。一名普通 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、SFU/peer route、Host fanout 或服务端媒体分发;Google Cast receiver 需要可获取的媒体 URL,当前 P2P `MediaStream` 不满足该输入,因此不加入 Cast SDK/receiver。-- 多地区 server-assisted ingress/egress 调度及 SFU 的按地区、运营商可达率。--## 非功能需求--- 性能:在 RTT 不高于 40 ms、丢包不高于 1% 的受控 P2P 路径中,玻璃到玻璃延迟目标为 p50 不高于 150 ms、p95 不高于 250 ms;区域 SFU/UDP root 路径的 p95 目标不高于 350 ms。-- 启播:观看者请求观看后,除用户授权耗时外,3 秒内出现首帧;从请求开始到首帧期间持续显示真实、稳定且可访问的连接阶段,不用黑屏、`playing` 事件或 ICE `connected` 冒充已播放。-- 流畅性:选择 60 fps 档位时,不能在没有降档或提示的情况下连续 5 秒低于 50 个解码帧每秒。-- 成本:direct/peer UDP 不经过应用服务器。SFU 的 ingress、egress 和并发上限由整体路由模型明确配置;验收逐 hop 记录 Host、peer、SFU 和供应商计费的真实 bytes,不得用普通端点 child 数或有效载荷近似代替中央资源准入。-- 安全:应用控制面全程 HTTPS/WSS;site access、Host token 与 room-scoped Viewer grant 权限正交,任何一个 Viewer grant 只授予一个房间的观看角色。P2P 边在 WebRTC 端点间使用 DTLS-SRTP,普通 SFU 是逐跳 DTLS-SRTP;只有另行实现并验收应用层 E2EE 才能对 SFU operator 保持媒体端到端机密。仓库、服务端持久存储、日志和错误不得包含明文密码或 grant。已鉴权 Host 与 shipped clients 是当前私密房间中的可信媒体参与者;越权房间、角色和未授权 subscription 必须拒绝。旧 generation 不得重新取得 route authority,并在有界 drain 后由 exact-room 删除阻止再次加入。-- 隐私:P2P 会向房间内好友暴露网络地址,首版威胁模型仅覆盖可信熟人;若要求隐藏 IP,必须切换为服务器转发。-- 可维护性:代码、需求、调研、项目记忆、`AGENTS.md` 和 `.codex/` 均在 Git 中跟踪;开发配置不得依赖单一操作系统的绝对路径。-- 迁移完整性:项目拥有者明确宣布公开发布前,只维护当前内部产品合同,不承担 backward/forward compatibility。Browser 客户端、服务端和部署配置使用单一 `screener-v13` wire 原子发布,旧客户端在 authority 前拒绝;Host codec selector 只属于页面本地 pre-share 设置,不进入 quality-state/wire。旧 parser/writer、双写、translator、deprecated alias、migration shim 与仅服务旧版本的测试均不存在;SQLite 只接受 exact current schema。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,并实测自动播放限制、横竖屏、锁屏恢复与移动网络切换。所有 Web Viewer 使用统一的 server-authoritative endpoint capacity;移动真机表现是兼容观察,不建立单独 route class。--## 边界与约束--- 首版不包含远程键鼠控制、公开/大规模直播、录制、社区系统或完整语音聊天;大规模分享直接使用现有直播服务。-- `open` code-only 入口只省略房间密码,不省略站点访问;`private` 在没有房间密码时只允许 grant 邀请,在设置密码后才允许匹配的 code-only 请求。四位房间码只定位,不提供隐私保证、目录或防转发承诺。现有每房 Viewer 上限、全局/未鉴权连接上限、房间上限和中央 egress/admission cap 仍适用,任何访问方式都不能创建无界服务器 fanout。-- 房间控制面保持单进程、单实例和一个 RoomStore 合同。`ROOM_DATABASE_PATH` 未配置时使用默认轻量模式,进程重启清空房间;配置时使用 SQLite 稳定模式,只持久化房间号、租约、Host/Viewer credential digest、Viewer authorization generation、`open | private` policy 和可选密码 verifier。成员、`clientId`、`peerId`、session/share generation、暂停、质量、codec、route、SFU、SDP、ICE candidate、IP、stats 与媒体始终不持久化,重启后必须重新鉴权、建图并以新首帧提交。-- 20-Viewer admission 是产品边界,不承诺任意机器、档位、网络或跨洲路径都达到相同画质;endpoint cap、SFU admission 和明确 wait/failure 继续保护资源。-- 浏览器规范要求每次由用户主动选择分享源,权限不能永久保存;纯网页不能保证指定游戏窗口或始终获得系统音频。-- 1080p60 是能力目标,实际分辨率、帧率和硬件编码由浏览器、GPU、驱动、画面复杂度及网络共同决定。-- 旗舰 release 的正常房间都可使用同一自动 controller;部署未启用总开关的轻量实例才保持标准 WebRTC P2P。Peer relay 只复用标准 remote-track WebRTC,不加入 Encoded Transform/DataChannel/WebCodecs 媒体协议,也不自研 UDP、编解码器、拥塞控制、FEC/RTX、多树、转码、codec ladder 或综合评分器。独立 native shared encode sender 不在本实验内;跨模式迁移受 ADR-0005 的 exact attempt、candidate-child first frame 和 typed resource admission 共同约束。-- GPL/AGPL 项目在许可证策略确认前仅用于研究,不能直接复制到计划闭源的产品中。--## 验收标准--### 房间模式与生命周期--- Given 当前空闲房间码池,When 连续创建房间,Then 每间房从 `1000..9999` 的未占用集合随机取得一个四位码,不重复活动号码,活动房间容量固定为 9000;释放房间后号码返回同一空闲池。-- Given Host 正在分享,When `ROOM_LEASE_SECONDS` 到达,Then 活动房间不被回收。Given 分享者明确停止、捕获轨结束或 Host 断开,When 同一 Host token 在默认 86400 秒内重新分享,Then 恢复原房间并重新续租;轻量模式限当前进程,稳定模式可跨应用重启。超过期限则关闭房间、释放号码并拒绝旧 Host token、grant 和房间密码。-- Given 分享期间只有 host 信令短暂断开,When 现有 P2P 媒体仍健康,Then 客户端继续播放媒体并恢复信令,而不是错误显示“已停止分享”。-- Given 应用以 production 模式启动但 `SITE_ACCESS_PASSWORD` 缺失,或配置仍提供已删除的 `ACCESS_PASSWORD`、`ROOM_TTL_SECONDS`,When 应用启动,Then 配置校验明确失败。Given 配置 `ROOM_DATABASE_PATH`,When 路径、应用标识、schema、行数据或独占 owner 任一无效,Then 在 signaling 与 LiveKit mutation 前 fail closed;未配置时不创建数据库或写目录。-- Given production site access secret 短于 8 bytes、长于 128 bytes 或含非可见 ASCII,When 新 release 启动,Then 必须 fail-fast。Given 同一来源连续提交错误 secret,When 超过 deployment `limit_req` 的 `5r/m`、`burst=5 nodelay` 边界,Then nginx 返回不含凭据的通用限频结果;允许请求的错误值仍使用常量时间比较和统一鉴权失败,limiter 只使用 nginx 内存且不新增 IP 持久化/日志字段。-- Given 新建房间,When 服务端返回邀请并由 Host/Viewer 客户端读取,Then grant 是 128-bit 随机量的 22 字符 base64url,只授权该 exact room incarnation 的 Viewer,并只在该页面会话的 room-scoped `sessionStorage` 留存且在首次读取后从地址栏移除;HTTP request-target、WebSocket URL、Referrer、cookie、`localStorage`、服务端持久存储、日志和错误均不包含 raw grant。Given 房间仍存在且未 rotate/revoke,Then grant 保持有效;稳定模式应用重启只恢复 digest 和 authorization generation,存活页面可用原 grant 重新鉴权。Given 房间回收、显式换房、轻量模式重启、rotate/revoke 或同号新房间,Then 旧 grant 失效。-- Given 本地输入不是 `1000..9999` 的四位房间码,When 用户提交或直接访问 malformed `/r/...`,Then 客户端保留原输入并直接提示“四位数字”,不发起房间鉴权、不静默删除字符。Given 默认新房,When 已通过站点访问的 Viewer 只输入合法房间码,Then 无房间密码即可在现有 Viewer/连接/egress 上限内加入,同时 Host 的主分享动作仍复制独立的 token-bearing link。-- Given 已通过 site access 的 well-formed code-only 尝试对应未分配、已回收或已过期房间,When `screener-v13` 首条信令鉴权到达,Then 服务端返回 `ROOM_NOT_FOUND`,UI 显示“房间不存在或已过期”且不提供密码重试。Given code 属于现存房间但缺失/错误密码、满房或其他已知有界 admission refusal,Then 服务端继续返回 `ROOM_ACCESS_DENIED` 并使用共享 authentication-failed close code,UI 可提供现有可选密码重试和 Host 邀请提示。Given grant 无效,Then 继续使用通用 `INVALID_TOKEN`;Host 鉴权保持独立错误,unexpected internal failure 使用不含 raw message 的 `SERVER_ERROR`。Given Viewer 持另一个房间的 grant、缺失 grant 或自行把 role 改为 Host,Then 不能建房、发布、跨房或绕过 Host token。-- Given Host rotate/revoke Viewer grant,When 新内存摘要和 authorization generation 提交,Then 服务端清除 Viewer grace/路由,命令 Viewer 关闭接收 PC/媒体并让每个 Host/relay/SFU upstream owner 关闭对应旧代次媒体边,最后关闭旧 Viewer socket;rotate 返回一次新 grant,revoke 锁定 grant 路径,code-only policy 保持独立。-- Given Host 浏览器仍持有现存房间的 ownership,When 分享活动或休眠期间更新邀请、code-only policy 或房间密码,Then 同源 HTTP 管理只接受有效 site access 与该房间精确 Host token;操作不建立 Host 媒体会话、不把房间标为分享中、不申请 route/resource,也不续租 dormant lease。rotate/revoke 继续执行同一强撤销,服务端只在 rotate 成功时返回新的 raw grant。-- Given Host 同源本地偏好保存了 `open | private`、可选房间密码和上次实际分配的房间号,When 服务器报告旧 ownership 已过期/失效或重启后该 Host 下一次显式开始分享,Then 客户端清除失效 ownership、始终请求该 preferred room 并原子重放创建偏好;号码空闲时分配给新的 room incarnation,已占用时随机分配并替换本地偏好。两者都生成新的 Host token 和 Viewer grant。该本地号码没有租期、倒计时或续租 authority;换浏览器、换设备或清理站点数据时没有该偏好。-- Given 应用进程重启,When 运行轻量模式,Then 所有旧房间、租约、摘要、密码 verifier 和参与者均已丢弃并 fail closed。Given 运行稳定模式,Then 未过期房间的号码、credential digest、authorization generation、policy/password verifier 和 dormant deadline 从 exact current schema 恢复;crash 时 active 的房间从启动时刻进入一个配置租期,所有 participant/session/share/route/SFU 状态仍为空,旧页面必须重新鉴权并重新提交媒体。-- Given Host 点击房间号旁的换房按钮,When exact Host token 仍有效,Then 服务端以一个原子操作分配保证不同的新号码并正常销毁旧 room incarnation;成功后旧 Host token、grant、密码、authorization、session、route 与 SFU 资源全部失效,活动分享结束,客户端保存新房间和无期限 preferred code。Given 新号码或凭据无法在提交前生成,Then 旧房间保持不变。-- Given 部署切换了不兼容的当前协议,When 仍打开的旧页面连接新服务端,Then 单一 release/protocol mismatch 边界终止该 session、停止自动重连并明确提示刷新;不得通过旧 parser、双写或双协议继续假连接。--### P2P 与 SFU 兜底--- Given 一个应用进程已经持有配置的监听地址,When 另一个进程以相同地址启动,Then 竞争进程必须在任何 LiveKit list/delete/create 前因 bind 失败退出。Given owner 已 bind 但 LiveKit startup reconciliation 尚未完成,Then HTTP 只返回 `503` 且 signaling 不接受连接;只有 foreign-room 检查、managed-room 清场和 empty readback 全部成功后才开放服务。--- Given 两端网络允许 UDP 打洞,When 观看者加入,Then `getStats()` 显示选中的候选对不是 `relay`,且服务器没有承载媒体流量。-- Given ordinary peer edge 被创建或重建,When 检查其 ICE 配置,Then 只包含部署 STUN。-- Given Browser Host publisher 或 Viewer subscriber 进入 LiveKit SFU candidate,When 检查 pinned `Room.connect` 参数与实际 ICE,Then 两端都使用 `autoSubscribe: false` 和精确 `rtcConfig: { iceServers: [] }`,继续接收 LiveKit signaling 的 remote UDP candidates,并可由任意合法 candidate type 形成 nominated non-relay pair;该空列表不得扩散到 ordinary Host/Viewer peer PC。-- Given route candidate、signal、recovery 或 commit 的 authenticated room/endpoint session、share generation、base/pending revision 或 candidate connection identity 任一不匹配,When 旧消息或异步结果到达,Then 该操作 fail closed 且不能替换当前媒体;SFU publication generation 继续由 resource owner 单独验证。-- Given 新路线正在准备,When exact candidate child 尚未解码出第一帧新画面,Then 可用旧路线保持权威;首帧后只原子提交该 candidate,失败或统一 deadline 到期销毁候选并保留或恢复旧路线。-- Given 所有 direct 与 SFU 媒体路径耗尽,When 有界连接窗口结束,Then 界面显示通用等待或连接失败,不静默黑屏、不长时间假连接,也不尝试未授权路径。SFU 的精确 path order 和 resource accounting 按 ADR-0005 验证。-- Given 同一 committed graph 和候选集合以不同枚举顺序输入 controller,When 新 Viewer 加入或 exact failed edge 触发换父,Then 硬过滤结果相同,选择稳定落到最浅且分配后剩余容量最多的合格 parent,并以加入顺序和 peer identity 打破平局;健康 current edge 不因出现更优候选而迁移。Given 第一候选 ICE 或首帧失败,Then controller 先幂等清理该候选再尝试下一候选,且不会启动 all-pairs probe;若候选创建了受管 SFU room,其 server capacity 在删除并证明 room 不存在前仍计费。-- Given 任意 ordinary Browser direct edge,When 浏览器 ICE checks 成功或 direct 阶段耗尽,Then 应用分别采用该实际可达 peer path 或在同一总 deadline 内进入 SFU/UDP;不得合成 remote candidate、预测端口、上报 NAT 类型或用 TCP 可达性替代 UDP ICE 结果。Given 所有 UDP 均被阻止,Then direct 与 SFU 都在有界窗口内结束并显示明确失败。--### 浏览器与移动端观看--- Given 观看者只有受支持的手机浏览器,When 打开有效邀请链接并执行浏览器要求的播放手势,Then 无需安装应用即可进入房间、看到首帧并听到可用音频。-- Given 用户在普通手机浏览器尝试成为 Host,When `navigator.mediaDevices.getDisplayMedia` 缺失,Then 页面在创建发布路径前明确显示该浏览器不支持移动端屏幕分享,并保留加入房间入口。Given API 存在但真实调用失败,When 失败原因是拒绝/取消或其他 capture error,Then 分别显示对应状态而不是一律重标为不支持;判断使用运行时能力/结果而不是 UA、平台或设备型号,也不能把移动 Viewer 支持宣传成移动 Web Host 支持。-- Given 观看者操作浏览器原生媒体 controls,When 播放、暂停、调节音量、静音或进入全屏,Then 只改变当前 video element,其他观看者、发送端、房间与路由不受影响,不产生信令、应用持久化或媒体重协商。-- Given Viewer 已通过浏览器要求的用户手势开始可听播放,When 页面切到后台且浏览器仍保留该页面,Then 同一个媒体元素、信令和 WebRTC 连接尽力继续承载音频,返回前台后沿当前直播恢复画面而无需重新加入;后台视频合成、JavaScript、逐帧回调或 relay 存活不作承诺。Hidden、freeze 与 pagehide 期间应用 decoded-stall 没有路由失败权威;visible、resume 或 pageshow 先 rebaseline 并重建当前 frame proof。系统是否暂停现有 video 及返回后能否无手势恢复由真机验收,应用不得猜测并覆盖用户通过原生 controls 的主动暂停。Given exact route failure 通知暂时无法写入信令或随后发生信令换代,Then 后续采样仍可重试,不得永久吞掉该故障。Given iOS 锁屏、系统回收页面或后台期间产生新的媒体连接,Then 以当前真机行为为准,恢复时继续使用已有重连和显式播放入口。-- Given 用户查看本机身份,When 尚未进入编辑状态,Then 界面显示“昵称”、当前昵称和紧贴其后的铅笔按钮,不显示默认可编辑输入框。Given 用户修改昵称后以 Host 或 Viewer 加入房间,Then 所有在线参与者看到同一份服务端权威 roster、对应房间标题;唯一名称只显示名称,重名项追加当前房间 `peerId` 短后缀。刷新后本机名称仍在,清除站点数据后恢复未命名默认值,服务器不存在显示名或成员的持久记录,展示身份不参与授权或路由。-- Given 手机从 Wi-Fi 切换到蜂窝网络或页面从后台恢复,When 原候选对失效,Then 客户端执行 ICE restart 或重建连接,并显示恢复进度而不是永久黑屏。-- Given SFU Viewer 页面进入 pagehide 或 beforeunload,When 当前应用仍可能通过 BFCache/页面恢复继续使用,Then LiveKit 不得仅因该页面事件主动拆除 Room;Screener 正常换路/卸载仍显式 disconnect,SDK 无法关闭的 freeze 行为继续由真机矩阵验收。-- Given Viewer 已鉴权但尚未提交首帧,When route 从 peer prepare 进入 SFU 或等待媒体,Then 固定舞台依次显示当前真实阶段且不跳动、不显示虚假百分比;只有当前代 video frame 被 compositor 接收后才显示正在播放。Given `video.play()` 仅因 autoplay policy 被拒绝,Then 保留原生媒体 controls 并显示非阻塞播放暂停状态;连接尚未完成时不显示自制播放按钮。Given 旧媒体仍可见且正在 MBB 恢复,Then 保留旧画面并叠加恢复状态。-- Given Viewer 尝试把直播输出到电视,When 浏览器/系统提供已验证的 Remote Playback、AirPlay 或屏幕镜像能力,Then 该动作只改变本机输出设备,现有 upstream PeerConnection、SFU/peer route 和其他参与者保持不变。Given live `srcObject` 未经目标设备证明或 API 缺失,Then 产品不显示伪可用 Cast/AirPlay 按钮,也不创建自有 receiver 或转码服务器。--### 一对多与带宽保护--- Given `ENDPOINT_MEDIA_COPY_CAPACITY=C`,其中 `C` 只能是 `1`、`2` 或 `3` 且默认 `2`,When Browser Host 或任一 Browser Viewer 建立、恢复、重鉴权或迁移媒体路径,Then peer child 与 Host publication 的稳态实际发送副本总数不超过 `C`,upstream receive 不计数,角色、浏览器和 UA 不改变 `C`;每个 `authenticated` 快照都携带同一个 `C`,并行候选只有持有 `TransitionOverlapSlot` 时才可达到 `min(C + 1, 3)`,并在 commit/abort 后释放。Given 已接受的 `screener-v13` 房间合同,When Host 或 Viewer 取得房间 authority,Then server 与 Browser assets 属于同一 release,缺失或越界的 `C`、其他 wire 与 executable sender 得到明确 mismatch,且 `C=3` 满载 Host 在取得会产生第四份 endpoint media copy 的 publication/token 前明确等待或失败。-- Given peer-assisted 路径分别运行 1、5、10、20 名观看者,When 用户加入、容量释放、节点离开、重鉴权或当前 edge 失效,Then 服务端只为新 Viewer、等待 Viewer 或失去 parent 的 subtree root 选择一个 active parent;每名 Viewer 同时至多一个 active upstream,活动图无环,其余健康边保持 sticky。没有可用 parent 时明确等待或拒绝,不主动重平衡或引入常驻多源媒体。-- Given 一个 Host root 退出并释放 Host sender slot,When 新 Viewer 加入或一个失父 child 进入同一 reconcile,Then 候选按结果深度优先,选择 Host 而不是另一 root 的更深空槽;已健康挂在另一 root 下的旧 child 不被周期性搬动。连接详情只显示当前页面本地观测值;Host 与 Viewer 页面均不提供诊断文件下载。Given authenticated Host test harness 请求 bounded route snapshot,Then 服务端只返回现有 privacy-safe current snapshot;Viewer 请求仍拒绝,snapshot 不参与 route authority。-- Given 一名分享者和 20 名观看者,When 运行 bounded browser smoke,Then 全部 Viewer 取得明确媒体或 bounded wait/failure,非服务器端点不超过 `C`,并记录 route depth、首帧时间、实际 sender 数、应用服务器 CPU/内存以及 SFU 用量。诊断汇总报告 20 个 current-child 样本数、pending 数、每项原始排序时长和 nearest-rank p50/p95/max,不设通过阈值;confirmed departure 和 room delete 后对应 timing 必须消失。该 smoke 验证 admission、控制面效能和资源上界,不单独证明任意公网画质或 30 分钟 endurance。-- Given candidate 改变房间 admission 默认值或上限,When 在目标数量与代表性路径上运行规定时长并注入 relay departure、重连和一个弱路径,Then 每名观看者持续解码、每个非服务器端点不超过配置容量、深度与故障半径有界、未受影响 subtree 不迁移,并记录端点与中央服务的 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 或放宽 endpoint capacity 后才能满足,When 结束 bounded spike,Then 放弃并删除该浏览器 relay 实验路径,保留标准 P2P 与整体路由模型已接受的 fallback;后续 native shared encode sender 仍按独立 ADR 推进,但不能据此把失败的 relay 拓扑判为通过。-- Given 新观看者会使预计总上行超过安全预算,When 其请求加入,Then 系统只选择整体路由模型已授权且满足配置容量与资源准入的路径;没有合格路线时明确等待或拒绝,而不是创建超过配置容量的 ordinary edge 或持续堆积发送队列。各 transport 的拥塞控制适应该路径,诊断证据不改变拓扑或合成全房降档。-- Given SFU 参与路线,When 计算准入、迁移 overlap 或失败恢复,Then 同时检查统一端点容量和独立的 server ingress/egress、SFU 资源预算;不得把普通端点 child 数当作 server cap,也不得借兜底形成无界整房 fanout。-- Given 配置完整 LiveKit credential tuple,When `LIVEKIT_API_URL` 缺失或不是允许的 control-plane origin,Then 服务必须在启动时 fail closed。Given 配置有效,When startup listing 出现非 Screener room、遗留 room 无法删除、删除后仍存在,或 exact candidate room 无法显式创建,Then 应用不得签发 token 或接受可能重复计算的 SFU generation。Given 当前 reserved、committed 与 draining 的 ingress 或 egress 会越过房号池及每房 Viewer 准入推导出的容量,Then controller 必须在签发任何新 SFU token 前拒绝该 candidate,并保持旧 route 和计数不变。Given generation 被 commit、abort、timeout、stop、delete 或 Host participant 离线回收,When DeleteRoom 尚未成功或 absent readback 尚未完成,Then 它必须继续占用账本资源且旧 token 不能创建 room。-- Given Host、relay parent 或 leaf 处于受限网络,When direct/peer 路径不足,Then 只执行 ADR-0005 授权的 SFU publisher/subscriber fallback;不得靠未授权的固定数量、静态 lease、TCP probe 或 claimed NAT type 猜测实现。--### 质量和恢复--- Given 用户选择任一推荐档位或高级质量参数,When 接收端实际分辨率、帧率或码率持续显著低于该目标,Then 诊断数据能区分采集约束、发送编码、带宽/拥塞、当前 peer/SFU 路径和接收端限制;产品不得只改变档位标签却继续隐藏实际降级。-- Given Browser Host 建立 SFU publication,When publish options、sender 参数和 RTCStats 可读,Then Screener 不设置自定义 simulcast layer list,实际 VP8 encodings 来自 pinned LiveKit 默认行为且不随 Viewer 数线性创建;LiveKit Dynacast 与启用 send-side BWE 的 server stream allocator 负责聚合需求和每个 SFU subscriber 的实际下行层,弱下行不能改变健康路径、拓扑或 direct/peer 各自的 stock WebRTC GCC。-- Given 当前 Viewer 的 exact edge 进入 `failed/closed`,或在非权威暂停时超过统一 deadline 没有新 decoded frame,When 服务端确认 authenticated child、share generation、active revision 与 connection identity 仍匹配,Then 只把该 child 送入同一个 reserve/prepare/first-frame/commit-or-abort 事务;低码率、低 FPS、模糊和 SFU layer 只进入诊断。-- Given 当前 edge 仍在解码但分辨率、FPS、码率、freeze ratio、RTT、jitter、loss 或 limitation evidence 持续影响观感,When 评估是否自动换父,Then 当前产品只诊断而不迁移:现有路径证据不能证明未连接 parent 的反事实质量,WebRTC/LiveKit 继续拥有拥塞适应,应用不建立 alternative-parent probe、hysteresis/cooldown、加权分数或周期性重排。-- Given 同一 Viewer 同时是某人的 child 和其他人的 parent,When 自身 ingress 失效,Then 它作为 child 换父、在新 ingress 首帧提交前保留可用旧 edge,并保持 subtree。Given endpoint disconnect 或 `effectiveDownstreamCapacity` 降低,Then controller 只保留稳定顺序内可容纳的 children,并将 deterministic overflow children 逐个送入同一事务;childless 后删除 disconnected relay。-- Given 当前分享权威 paused,When 新 Viewer 加入、edge 失效或已有 child operation 尚未提交,Then abort 整个 pending route operation 及其 current candidate/预留、保留 active graph、让新 Viewer waiting,并且不因没有 decoded frame 触发恢复。普通 Pause/Resume 只通过当前 Host session 与 `shareGeneration` 约束的一次 paused-state 更新同步本地 capture tracks、服务端快照、`host-status` 和 route pause;Resume 重新启用同一批 tracks并从当前 graph 唤醒 fresh reconciliation,不建立第二次授权、source acknowledgement、媒体 proof 或回滚状态。较早 share generation、已替换 Host session、stop 或新分享的迟到更新不得改变当前状态。-- Given 当前 Browser SFU publication,When 进行质量验收,Then 受限与非受限 subscriber 的实际 representation 由 pinned LiveKit 原生选择并以 sender/server/receiver stats 证明;不得把一次 layer 数量或参数写成 Screener 产品常量,不得退回全房间最低目标、启用 AdaptiveStream 控制潜在 relay ingress,或增加应用媒体层 controller。-- Given 同一时刻采集、host outbound 与 viewer inbound 证据,When 进行根因分类,Then 关联派生后的实际协商视频 codec/profile/parameters、适用时的 `scalabilityMode` 与真实解码表现,依次区分 Capture 低、Capture 高但 outbound 因 CPU 低、Capture 高但 outbound 因 bandwidth 低、outbound 正常但 inbound 低、以及 inbound 正常但肉眼模糊五类;不用 UA 或设备型号代替运行时证据,也不上传 raw SDP。-- Given Viewer 上报当前路径质量证据,When 报告未鉴权、过频、重复、过期或没有匹配的 sender/viewer 统计,Then 报告被丢弃;有效报告也只能用于诊断,不能改变 Host 表示或路径状态。-- Given 受控 RTT/丢包测试条件,When 连续分享高动态游戏画面 30 分钟,Then 延迟、帧率与丢帧达到上述目标,且没有不可恢复的冻结。-- Given Windows Chrome/Edge Browser Host 开始分享,When 浏览器返回 display video track,Then 应用设置 `contentHint = "motion"`,并按浏览器 stats 如实显示实际 RTP codec 与实现字段。Host 高级设置在未分享时按从低到高显示 `VP8 | 自动 | H264` 且默认自动,分享开始后锁定;自动模式以有界 H.264 sender preflight 决定 H.264-first 或 VP8-only,手动 H264 只允许 H.264 mode 1,手动 VP8 只允许 VP8。Viewer relay 始终自动。换源、换父、质量更新与暂停/继续沿用当前分享代决定;停止后开始新分享才按当前 selector 重新决定。缺少所选 codec、`setCodecPreferences()` 或应用失败在创建 offer 前明确失败。Given 建立 SFU publication,Then 使用 Host share generation 的同一 resolved H.264/VP8 决定、禁用 backup codec,且 Screener 不设置自定义 simulcast layer list。-- Given 分享过程中切换 Wi-Fi/有线网络,When ICE 连接失败,Then 客户端触发 ICE restart,并在成功或超时后给出明确状态。-- Given 当前路径仍可播放且控制器准备迁移 logical parent 或替换 transport,When 候选路径拥有模型授权的 overlap 资源,Then 旧路径保持权威,直到 exact candidate child 解码出第一帧新画面后才原子提交;ICE `connected` 单独不能触发切换。-- Given 候选没有准入资源,或 provisional 路径失败、超时、代次过期、参与者变化、房间停止、权限撤销或 session 被替换,When 本次机会结束,Then 原路径和未受影响 branches 继续工作,临时资源被销毁,重试遵守模型定义的有界策略。-- Given 浏览器未返回系统音轨,When 分享开始,Then 分享者在启播前看到“当前来源没有可共享音频”的提示。-- Given 分享者选择标签页或窗口,When 浏览器支持对应音频捕获,Then picker 提供该来源音频而不扩大为系统混音。Given 分享者选择整个屏幕,When 浏览器支持系统音频,Then picker 提供由用户决定的系统音频开关。应用同时请求 `windowAudio: "window"` 和 `systemAudio: "include"`,不根据 track 存在性伪造来源标签。-- Given 浏览器返回分享音轨,When 开始发布,Then 应用设置标准 `contentHint = "music"` 作为内容意图元数据;该值可读回,但不作为 Opus、码率、声道、采样率、FEC、DTX 或立体声的质量证据。-- Given Web Host 或浏览器 relay 建立或替换分享音轨,When 对实际音频 sender 应用发送参数,Then 从当次 `getParameters()` 派生所选 `encodings[0].maxBitrate = 64000 | 128000 | 192000`、调用 `setParameters()` 并立即读回,档位缺失时按 128000 处理;Given Web Viewer 为含唯一有效 audio/Opus payload 的 offer 生成 answer,Then 用结构化 SDP parser 只 upsert 该 payload 的 `stereo=1` 与 `maxaveragebitrate=192000`,并把同一个结果用于 `setLocalDescription()` 和 signaling。首次连接、ICE restart、同 parent rebuild 和 relay child 都适用;空 SDP、无/歧义 Opus、多个有效 audio、重复目标参数、畸形 fmtp 或 parse/write 异常必须按对象 identity 返回浏览器原 answer 并继续,不能发送部分修改或静默冒充 stereo/实际码率。只有实际 `setLocalDescription()` 失败才进入既有连接错误路径。`sprop-stereo` 与 `usedtx` 不新增,其他 fmtp/FEC/session/media 字段逐项保留。-- Given 通过 SFU 发布分享音轨,When 构建 LiveKit 2.22.0 publish options,Then 64 kbps 使用 `AudioPresets.musicStereo`、128 kbps 使用 `AudioPresets.musicHighQualityStereo`、192 kbps 使用同等结构的显式 sender ceiling,三档都设置 `forceStereo = true`、`dtx = false` 与 `red = false`;验收同时核对 SDK 选项、applied ceiling、当前 RTP codec/fmtp 与 stats 实际码率,不能从 preset 名称或 `opus/48000/2` 单独推断实际声道内容。-- Given 分享正在直播或暂停且 Host 选择新的 64/128/192 kbps 音频档位,When 当前 profile mutation 串行执行,Then 服务端以 last-wins 保存并广播最新 desired profile,每个当前 Host、relay 与 SFU audio sender 从 fresh `getParameters()` 派生 `setParameters()` 并立即 readback,过期 completion 不得覆盖新值;以后创建的 sender 使用最新 desired profile。单个端点应用失败时保留媒体与其旧 applied 值、显示可见告警并允许后续更新或重建重试,不得谎称全房已收敛。当前 applied readback 保持 endpoint-local;没有显式回执 wire 就不宣称跨端点原子提交。该操作不改变 Opus、route revision、media-binding generation 或 publication generation,也不创建第二个音频控制环。当前 screen-audio Host 基线是 Chrome/Edge;其他浏览器只有实际 sender readback 成功时才算支持。-- Given Host 打开分享高级设置,When 尚未开始分享,Then 本地三段 codec selector 可编辑且默认自动;Given 分享已开始或暂停,Then selector 锁定且不触发重协商。该选择和 share-generation-scoped 自动结果均不持久化、不进入 quality state/wire、不改写健康 edge;实际协商 codec 与 encoder 只作为连接详情中的只读诊断。-- Given 浏览器返回屏幕音轨,When 产品展示音频状态或未来连接详情,Then 只能把存在性、浏览器实际返回的 track settings、实际协商 codec/fmtp 和实际流量分别标为捕获、协商或观测事实;字段缺失必须显示为未知,且不得从 Opus 的 `48000/2` RTP 声明推断源采样率或实际 stereo。-- Given Web 或后续 native sender 分享电影/视频音频,When 进行产品验收,Then 必须用独立 A/B/C 证据关联 capture audio track/settings、实际 negotiated codec/fmtp、outbound/inbound 实际码率、loss、jitter、concealment、jitter-buffer 与 A/V sync;P2P、浏览器 relay 与 SFU route switch 保持同一持久 Viewer `MediaStream`/媒体元素和 stereo 协商,不新增独立 audio element 或 Web Audio 时钟边界。native sender 必须通过该音质和同步矩阵,且不得把 audio `maxBitrate` ceiling 当作提质证明。-- Given 分享者同时运行语音软件,When 选择仅分享游戏声音,Then supported Windows 11 native sender 只保留目标游戏及其子进程的渲染音频,观众、通知和其他应用声音不得进入分享;浏览器 system audio 无法满足时必须允许 video-only 或明确告知其可能包含语音/通知,不能用 AEC、降噪或来源标签伪称已隔离。-- Given 分享者显式选择 Native window H.264 与一个本地窗口,When 分享开始,Then helper 必须在再次验证 HWND/PID/creation-time 后以 WGC/D3D11 和 hardware-only MF H.264 产生一份 `42c01f` Annex-B 输出并直接复用现有 Go/Pion fanout;Viewer 仍使用普通浏览器。硬件 MFT、WGC、音频或目标身份任一失败都明确停止该模式,不得静默改用软件编码、浏览器画面、显示器画面或系统混音。--### 仓库可移植性--- Given 在新的 Windows、macOS 或 Linux 工作副本中克隆仓库,When 打开项目,Then 需求、调研、项目记忆、`AGENTS.md` 与 `.codex/` 均存在且处于 Git 跟踪状态,不依赖原开发机器的绝对路径或密钥。-- Given 用户在自有公网服务器运行一键部署包,When 域名、TLS、端口、secret、容量、存储和适用的恢复预检通过,Then 同一版本的应用、STUN/SFU 与反向代理可重复启动并输出精确健康结果;普通 app-only 更新必须先验证新的不可变 application artifact,再原子切换,切换前 release 只保证保留到有限 health/postflight 完成且之后没有保留合同。实际触及基础设施、配置、secret、持久或不可逆状态的任务必须先为这些表面建立恢复。任一必需条件失败时不得显示 ready、写入占位凭据或留下半配置服务。-- Given 用户安装本地自包含一键包,When 在 Windows、macOS 或 Linux 启动分享,Then 包内 Host、当前应用服务器和受限本地状态使用同一协议与配置合同启动,用户无需源码、Node 或任何外部服务,Viewer 邀请仍由普通浏览器打开。Given 公网 HTTPS/WSS、信令入口、媒体 UDP、网关映射或 NAT 路径任一不可用,Then 预检必须如实显示受限或不可达,不得把 loopback/LAN 成功写成公网成功;可工作的 direct P2P 保留,失败进入明确终态。--## 决策与证据归属--- 项目许可证及闭源商用边界由发布和分发前的 license decision 持有;决定前 GPL/AGPL 实现保持研究用途,不进入产品源码。-- SFU 部署区域不由假定的用户地域决定;真实公网、跨地区、CGNAT、双 NAT、移动热点与普通家宽结果归入 real-network acceptance,测量后再决定部署位置和容量。-- iOS Safari、Android Chrome 的最低版本与平板适配范围归入 mobile Viewer lifecycle acceptance;物理设备矩阵完成前不宣称后台播放、锁屏、网络迁移或 relay 延续保证。--基础 WebRTC 证据与难度评估见 `docs/research/webrtc-p2p-screen-sharing.md`;peer-assisted、shared encode 和浏览器限制见 `docs/research/peer-assisted-media.md`。-----diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjsnew file mode 100644index 00000000..6a5848ec--- /dev/null+++ b/scripts/check-docs.mjs@@ -0,0 +1,272 @@+#!/usr/bin/env node++import { execFileSync } from "node:child_process";+import { existsSync, readFileSync, statSync } from "node:fs";+import { dirname, extname, relative, resolve, sep } from "node:path";+import { fileURLToPath } from "node:url";++const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const repositoryFiles = execFileSync(+ "git",+ ["ls-files", "--cached", "--others", "--exclude-standard"],+ { cwd: root, encoding: "utf8" },+)+ .trim()+ .split(/\r?\n/u)+ .filter((file) => file && existsSync(resolve(root, file)));+const markdownFiles = repositoryFiles.filter((file) => file.endsWith(".md"));+const failures = [];+const warnings = [];+const anchorCache = new Map();++const exactHardBudgets = new Map([+ ["AGENTS.md", [100, 8_000]],+ ["CLAUDE.md", [10, 1_000]],+ [".agents/skills/stop-that-shit/SKILL.md", [140, 8_000]],+]);+const exactWarningBudgets = new Map([+ ["docs/README.md", [180, 16_000]],+ ["docs/deployment.md", [250, 20_000]],+ ["docs/project-memory.md", [120, 12_000]],+ ["docs/status.md", [120, 12_000]],+ ["docs/todo.md", [160, 16_000]],+]);+const prefixWarningBudgets = [+ ["docs/product/", 180, 16_000],+ ["docs/adr/", 350, 30_000],+ ["docs/research/", 650, 50_000],+ ["docs/operations/", 250, 20_000],+ ["docs/reference/", 250, 20_000],+];++for (const file of markdownFiles) {+ const absolute = resolve(root, file);+ const text = readFileSync(absolute, "utf8");+ checkFormat(file, text);+ checkBudget(file, text);++ const scannable = withoutFencedCode(text).replace(/`[^`\n]*`/gu, "");+ const targets = [+ ...inlineLinkTargets(scannable),+ ...matches(scannable, /^\s*\[[^\]]+\]:\s+(\S+)/gmu),+ ...matches(scannable, /<a\s+[^>]*href=["']([^"']+)["'][^>]*>/giu),+ ];+ for (const raw of targets) checkLink(file, absolute, raw);+}++if (warnings.length > 0) {+ process.stderr.write(`${warnings.map((warning) => `warning: ${warning}`).join("\n")}\n`);+}+if (failures.length > 0) {+ process.stderr.write(`${failures.join("\n")}\n`);+ process.exit(1);+}++process.stdout.write(`Documentation checks passed (${markdownFiles.length} Markdown files).\n`);++function checkFormat(file, text) {+ if (text.length > 0 && !text.endsWith("\n")) {+ failures.push(`${file}: missing final newline`);+ }+ if (text.endsWith("\n\n")) {+ failures.push(`${file}: extra blank line at end of file`);+ }+}++function checkBudget(file, text) {+ const hardBudget = exactHardBudgets.get(file);+ const warningBudget =+ exactWarningBudgets.get(file) ??+ prefixWarningBudgets+ .filter(([prefix]) => file.startsWith(prefix))+ .map(([, maxLines, maxBytes]) => [maxLines, maxBytes])[0];+ const lines = logicalLines(text);+ const bytes = Buffer.byteLength(text);+ if (hardBudget) {+ const [maxLines, maxBytes] = hardBudget;+ if (lines > maxLines || bytes > maxBytes) {+ failures.push(+ `${file}: exceeds required ${maxLines}-line/${maxBytes}-byte ` ++ `top-level context budget (${lines} lines, ${bytes} bytes)`,+ );+ }+ }+ if (warningBudget) {+ const [maxLines, maxBytes] = warningBudget;+ if (lines <= maxLines && bytes <= maxBytes) return;+ warnings.push(+ `${file}: exceeds ${maxLines}-line/${maxBytes}-byte gardening threshold ` ++ `(${lines} lines, ${bytes} bytes)`,+ );+ }+}++function checkLink(file, sourcePath, raw) {+ const target = linkTarget(raw);+ if (!target || isExternal(target)) return;++ const [pathAndQuery, rawFragment = ""] = target.split("#", 2);+ const rawPath = pathAndQuery.split("?", 1)[0];+ let pathText;+ let fragment;+ try {+ pathText = decodeURIComponent(rawPath);+ fragment = decodeURIComponent(rawFragment).toLowerCase();+ } catch {+ failures.push(`${file}: invalid URL encoding: ${target}`);+ return;+ }++ const targetPath = pathText+ ? pathText.startsWith("/")+ ? resolve(root, `.${pathText}`)+ : resolve(dirname(sourcePath), pathText)+ : sourcePath;+ const repoRelative = relative(root, targetPath);+ if (repoRelative === ".." || repoRelative.startsWith(`..${sep}`)) {+ failures.push(`${file}: link leaves repository: ${target}`);+ return;+ }+ if (!existsSync(targetPath)) {+ failures.push(`${file}: missing link target: ${target}`);+ return;+ }+ if (+ fragment &&+ statSync(targetPath).isFile() &&+ extname(targetPath).toLowerCase() === ".md" &&+ !anchorsFor(targetPath).has(fragment)+ ) {+ failures.push(`${file}: missing anchor in ${repoRelative}: #${rawFragment}`);+ }+}++function logicalLines(text) {+ if (!text) return 0;+ const lines = text.split(/\r?\n/u).length;+ return text.endsWith("\n") ? lines - 1 : lines;+}++function matches(text, pattern) {+ return [...text.matchAll(pattern)].map((match) => match[1]);+}++function inlineLinkTargets(text) {+ const targets = [];+ for (let index = 0; index < text.length - 1; index += 1) {+ if (text[index] !== "]" || text[index + 1] !== "(") continue;+ let depth = 1;+ let cursor = index + 2;+ const start = cursor;+ for (; cursor < text.length && depth > 0; cursor += 1) {+ if (text[cursor] === "\\") {+ cursor += 1;+ } else if (text[cursor] === "(") {+ depth += 1;+ } else if (text[cursor] === ")") {+ depth -= 1;+ }+ }+ if (depth === 0) {+ targets.push(text.slice(start, cursor - 1));+ index = cursor - 1;+ }+ }+ return targets;+}++function linkTarget(raw) {+ const value = raw.trim();+ if (value.startsWith("<")) {+ const end = value.indexOf(">");+ return end > 0 ? value.slice(1, end) : null;+ }+ return value.split(/\s+["']/u, 1)[0];+}++function isExternal(target) {+ if (/^[a-z][a-z0-9+.-]*:/iu.test(target) || target.startsWith("//")) {+ return true;+ }+ return target.startsWith("/") && !/\.md(?:[?#]|$)/iu.test(target);+}++function withoutFencedCode(text) {+ let fence = null;+ return text+ .split(/\r?\n/u)+ .map((line) => {+ const marker = /^\s*(`{3,}|~{3,})/u.exec(line)?.[1] ?? null;+ if (fence) {+ if (marker && marker[0] === fence[0] && marker.length >= fence.length) {+ fence = null;+ }+ return "";+ }+ if (marker) {+ fence = marker;+ return "";+ }+ return line;+ })+ .join("\n");+}++function anchorsFor(path) {+ const cached = anchorCache.get(path);+ if (cached) return cached;++ const lines = withoutFencedCode(readFileSync(path, "utf8")).split(/\r?\n/u);+ const headings = [];+ for (let index = 0; index < lines.length; index += 1) {+ const atx = /^(#{1,6})\s+(.+?)\s*#*\s*$/u.exec(lines[index]);+ if (atx) {+ headings.push(atx[2]);+ continue;+ }+ if (+ lines[index].trim() &&+ index + 1 < lines.length &&+ /^\s*(?:=+|-+)\s*$/u.test(lines[index + 1])+ ) {+ headings.push(lines[index].trim());+ index += 1;+ }+ }++ const anchors = new Set();+ const counts = new Map();+ for (const heading of headings) {+ const base = githubSlug(heading);+ if (!base) continue;+ const count = counts.get(base) ?? 0;+ counts.set(base, count + 1);+ anchors.add(count === 0 ? base : `${base}-${count}`);+ }+ anchorCache.set(path, anchors);+ return anchors;+}++function githubSlug(heading) {+ return decodeHtmlEntities(heading)+ .toLowerCase()+ .replace(/<[^>]+>/gu, "")+ .replace(/!?\[([^\]]+)\]\([^)]+\)/gu, "$1")+ .replace(/[`*_~]/gu, "")+ .replace(/[^\p{L}\p{M}\p{N}\s_-]/gu, "")+ .trim()+ .replace(/\s+/gu, "-");+}++function decodeHtmlEntities(value) {+ const named = { amp: "&", apos: "'", gt: ">", lt: "<", quot: '"' };+ return value.replace(/&(#x[0-9a-f]+|#\d+|amp|apos|gt|lt|quot);/giu, (match, entity) => {+ if (entity[0] !== "#") return named[entity.toLowerCase()];+ const radix = entity[1]?.toLowerCase() === "x" ? 16 : 10;+ const digits = radix === 16 ? entity.slice(2) : entity.slice(1);+ const codePoint = Number.parseInt(digits, radix);+ return Number.isInteger(codePoint) && codePoint >= 0 && codePoint <= 0x10ffff+ ? String.fromCodePoint(codePoint)+ : match;+ });+}diff --git a/scripts/check-project-state.ps1 b/scripts/check-project-state.ps1index c19f7ec2..fade1b5c 100644--- a/scripts/check-project-state.ps1+++ b/scripts/check-project-state.ps1@@ -6,9 +6,7 @@ if ($LASTEXITCODE -ne 0) {}Set-Location $repoRoot-$requiredPaths = Get-Content -Encoding UTF8 scripts/required-project-paths.txt--foreach ($path in $requiredPaths) {+foreach ($path in Get-Content -Encoding UTF8 scripts/required-project-paths.txt) {if ([string]::IsNullOrWhiteSpace($path)) { continue }git ls-files --error-unmatch -- $path 2>$null | Out-Nullif ($LASTEXITCODE -ne 0) {@@ -16,22 +14,6 @@ foreach ($path in $requiredPaths) {}}-$agentLines = @(Get-Content -Encoding UTF8 AGENTS.md).Count-$memoryLines = @(Get-Content -Encoding UTF8 docs/project-memory.md).Count-$memoryBytes = (Get-Item docs/project-memory.md).Length-$statusLines = @(Get-Content -Encoding UTF8 docs/status.md).Count-$statusBytes = (Get-Item docs/status.md).Length--if ($agentLines -gt 200) {- throw "AGENTS.md exceeds the 200-line context budget: $agentLines lines"-}-if ($memoryLines -gt 200 -or $memoryBytes -gt 16000) {- throw "docs/project-memory.md exceeds its budget: $memoryLines lines, $memoryBytes bytes"-}-if ($statusLines -gt 120 -or $statusBytes -gt 12000) {- throw "docs/status.md exceeds its 120-line/12000-byte current-index budget: $statusLines lines, $statusBytes bytes. Remove completed history or move retained detail to its owning document; do not micro-compress prose."-}-git diff --checkif ($LASTEXITCODE -ne 0) { throw "Working-tree whitespace check failed." }git diff --cached --check@@ -42,4 +24,7 @@ if ($env:SCREENER_BASE_SHA) {if ($LASTEXITCODE -ne 0) { throw "Commit-range whitespace check failed." }}+node scripts/check-docs.mjs+if ($LASTEXITCODE -ne 0) { throw "Documentation check failed." }+Write-Host "Repository hygiene checks passed."diff --git a/scripts/check-project-state.sh b/scripts/check-project-state.shindex 54833f9e..87272b3b 100755--- a/scripts/check-project-state.sh+++ b/scripts/check-project-state.sh@@ -12,27 +12,6 @@ while IFS= read -r path || [ -n "$path" ]; dofidone < scripts/required-project-paths.txt-agent_lines=$(wc -l < AGENTS.md | tr -d '[:space:]')-memory_lines=$(wc -l < docs/project-memory.md | tr -d '[:space:]')-memory_bytes=$(wc -c < docs/project-memory.md | tr -d '[:space:]')-status_lines=$(wc -l < docs/status.md | tr -d '[:space:]')-status_bytes=$(wc -c < docs/status.md | tr -d '[:space:]')--if [ "$agent_lines" -gt 200 ]; then- echo "AGENTS.md exceeds the 200-line context budget: $agent_lines lines" >&2- exit 1-fi--if [ "$memory_lines" -gt 200 ] || [ "$memory_bytes" -gt 16000 ]; then- echo "docs/project-memory.md exceeds its budget: $memory_lines lines, $memory_bytes bytes" >&2- exit 1-fi--if [ "$status_lines" -gt 120 ] || [ "$status_bytes" -gt 12000 ]; then- echo "docs/status.md exceeds its 120-line/12000-byte current-index budget: $status_lines lines, $status_bytes bytes. Remove completed history or move retained detail to its owning document; do not micro-compress prose." >&2- exit 1-fi-git diff --checkgit diff --cached --check@@ -40,4 +19,6 @@ if [ -n "${SCREENER_BASE_SHA:-}" ]; thengit diff --check "$SCREENER_BASE_SHA"...HEADfi+node scripts/check-docs.mjs+echo "Repository hygiene checks passed."diff --git a/scripts/required-project-paths.txt b/scripts/required-project-paths.txtindex 05ea60a9..4fb35fa3 100644--- a/scripts/required-project-paths.txt+++ b/scripts/required-project-paths.txt@@ -22,9 +22,13 @@ docs/status.mddocs/todo.mddocs/verification-status.mddocs/maintenance.md-docs/需求理解.md-docs/方案设计.md+docs/product/rooms-access.md+docs/product/routing-transport.md+docs/product/media-quality.md+docs/product/presentation-lifecycle.mddocs/deployment.md+docs/operations/self-hosting.md+docs/reference/configuration.mdscripts/package-app-release.mjsdeploy/release-app.shdocs/adr/0001-p2p-first-media-topology.md@@ -39,6 +43,7 @@ native/window-capture-helper/process_audio.hscripts/required-project-paths.txtscripts/check-project-state.shscripts/check-project-state.ps1+scripts/check-docs.mjsscripts/package-native-sender.ps1scripts/install-hooks.shscripts/install-hooks.ps1