Skip to content

armgit / Piik

Public Imported from GitHub
0

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

docs(route): advance routing work to waves C-D

AAA7725f18ac454
diff --git a/docs/project-memory.md b/docs/project-memory.md
index a2300ac0..90565fb9 100644
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@ -21,7 +21,7 @@ Last updated: 2026-08-23
## Current Source And Production
- Canonical source is the clean `main` branch. New branches and worktrees start from its exact current commit after accepted truth is merged.
-- Current source implements the uniform `1/2/3` endpoint cap through one shared accounting guard, advances Web/server/Native to `screener-v6`, rejects v5 before room authority, and carries the exact deployment cap in every authenticated snapshot so ordinary Host authorization, Native admission, peer-assisted assignments, and sender slots use the same authority. SFU-fed Viewers remain leaves without outbound proof, and the fixed SFU-root and room-wide selected-lease guards remain pending later server admission waves.
+- Current source implements the uniform `1/2/3` endpoint cap through one shared accounting guard, advances Web/server/Native to `screener-v6`, rejects v5 before room authority, and carries the exact deployment cap in every authenticated snapshot so ordinary Host authorization, Native admission, peer-assisted assignments, and sender slots use the same authority. SFU-fed Viewers remain leaves without outbound proof. SFU admission uses explicit no-default ingress/egress capacities, exact `reserved | committed | draining` lifecycle accounting, and a listener-fenced dedicated LiveKit owner; the room-wide selected-lease guard remains for its independent TURN-admission wave.
- Production runs exact `9461e207af62b4f38f6b7a8aa16f8beb49e0e4ee`, release `9461e20`, wire `screener-v5`; `21d5cd9f7139` is the rollback release.
- Production still enforces Host downstream `2`, ordinary Browser downstream `1`, deployment values `1/2`, a fixed SFU-root limit of `2`, and legacy publication/selected accounting. This is a dated implementation divergence, not current product policy.
- Production has automatic routing, bad-relay corroboration, peer-quality make-before-break with Viewer and Host provisional parents, selected-edge transport, stable route/connection details, 64/128/256 audio choices, access controls, self-check, diagnostic export, and signaling watchdog behavior.
@@ -31,7 +31,7 @@ Last updated: 2026-08-23
## Current Priority
1. Keep this truth set and [the TODO ledger](./todo.md) concise and internally consistent.
-2. Complete and release the remaining route waves B-D first. Then release live audio and paused video-codec switching, follow with evidence-led H.264 diagnosis, the strict-NAT emulator gate, connection feedback, and the remaining functional roadmap. Distribution packaging starts only after those TODOs are complete. Parallel branches may finish earlier but do not change this merge/deployment order.
+2. Complete and release route waves C-D first. Then release live audio and paused video-codec switching, follow with evidence-led H.264 diagnosis, the strict-NAT emulator gate, connection feedback, and the remaining functional roadmap. Distribution packaging starts only after those TODOs are complete. Parallel branches may finish earlier but do not change this merge/deployment order.
## Working Rules
diff --git a/docs/status.md b/docs/status.md
index 1cf34b3e..b4088c5b 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -15,15 +15,16 @@ This is the current execution index. Git history owns completed timelines; [veri
- Canonical source is the clean `main` branch; auxiliary branches and worktrees do not own current truth.
- Current source implements one steady outbound media-copy cap for every non-server endpoint: default `2`, static `1/2/3`, a peer child or Host publication consumes one slot, upstream receive is free, a committed selected TURN transport replaces the same copy while hidden carry consumes another, and no Browser/UA/visibility tier exists. One shared guard owns the accounting and transition work is bounded by `min(C + 1, 3)`.
-- The v6 release boundary rejects v5 before room authority and carries the exact deployment cap in every authenticated snapshot so ordinary Host authorization, Native admission, peer-assisted child assignments, and sender slots share the server authority. It leaves an SFU-fed Viewer childless without independent outbound proof and keeps quality events child-scoped without a fixed two-child parent drain. Fixed SFU-root and room-wide selected-lease guards remain until their independent server admission owners land.
+- The v6 release boundary rejects v5 before room authority and carries the exact deployment cap in every authenticated snapshot so ordinary Host authorization, Native admission, peer-assisted child assignments, and sender slots share the server authority. It leaves an SFU-fed Viewer childless without independent outbound proof and keeps quality events child-scoped without a fixed two-child parent drain.
+- Current source also implements explicit no-default SFU ingress/egress capacities and exact `reserved | committed | draining` accounting. The listener owner reconciles its dedicated non-auto-create LiveKit namespace before serving, creates each generation before token issuance, releases only after delete-plus-absence proof, and reclaims Host-offline generations through bounded exact-participant checks. The room-wide selected-lease guard remains until its separate TURN-admission wave.
- Automatic P2P-first routing, one active upstream, an acyclic graph, exact identity/generation authority, media-proven make-before-break, and bounded failure remain accepted.
-- The holistic assisted-route model is accepted: one controller performs allocation, child reparenting, and relay abdication/drain. One Host publication serves SFU subscriptions; TURN is an exact edge transport, not a topology node. Wave A supplies endpoint accounting and the wire boundary without pretending that later controller convergence, media-binding generations, or independent SFU/TURN admission already exist.
+- The holistic assisted-route model is accepted: one controller performs allocation, child reparenting, and relay abdication/drain. One Host publication serves SFU subscriptions; TURN is an exact edge transport, not a topology node. Endpoint accounting, the wire boundary, and SFU admission/lifecycle are implemented; independent TURN admission and controller convergence remain pending.
- Parent selection is deterministic rather than random or score-based: hard eligibility filters, then shallowest result, remaining sender capacity, stable join order, and peer identity; one provisional edge uses standard ICE and media proof at a time. Viewer connection feedback and the strict-NAT emulator gate are accepted follow-up work, not deployed behavior.
- Live 64/128/256 audio-ceiling mutation and paused-share video codec switching are accepted but not yet implemented on canonical `main`. H.264 startup blur/low-FPS reports remain an evidence-led diagnosis, not a presumed codec defect. Public-server and fully local distribution packages are later work after the functional, NAT, and real-network ledger is complete.
## Current Milestone
-1. Complete and release route waves B-D from exact canonical `main` on the merged Wave A cap/wire boundary, including bounded server admission, deterministic local parent selection, quality ownership, and one controller.
+1. Complete and release route waves C-D with independent TURN admission, deterministic local parent selection, quality ownership, and one controller.
2. Release live audio-ceiling mutation and paused-share codec switching on the resulting generation/transition boundary.
3. Reproduce the H.264 startup report before any codec-specific repair, and build the strict-NAT emulator gate before any manually approved canary in an operator-owned test room.
4. Add first-frame-driven Viewer connection stages and finish the remaining accepted functional and real-network work.
@@ -38,5 +39,7 @@ This is the current execution index. Git history owns completed timelines; [veri
## Next Stop
-Reconcile each retained route candidate once onto this clean `main`; remaining
-TODOs stay scoped to their owner and do not revive superseded branches.
+Implement the independent TURN-admission and controller-convergence waves from
+this source. The route release still requires measured SFU capacities, a
+dedicated LiveKit instance with the documented private control-plane contract,
+and the focused real-network and Native `C=1/2/3` acceptance matrix.
diff --git a/docs/todo.md b/docs/todo.md
index 8f8bd4d3..c253c5b8 100644
--- a/docs/todo.md
+++ b/docs/todo.md
@@ -6,7 +6,7 @@ Only items in **Now** are executable after their stated decision gate. A branch
## Now
-1. **Route waves B-D: bounded fallback, selection, and controller convergence.** Replace the temporary fixed SFU subscriber guard with explicit deployment-wide SFU ingress/egress admission; then replace the temporary room-wide selected-lease guard with per-edge TURN allocation admission and exact accounting. Converge allocation, child reparent, and relay drain on one committed graph/controller. A signaling-connected relay that stops current-generation RTP cannot require its own report: after the bounded parent-proof deadline, persistent child-side silence reparents only the affected child whether the parent proved sending or not; cordon or drain the relay only after parent/session hard failure, explicit sender/resource failure, failed ingress repair, or independent downstream evidence. Parent candidates use hard eligibility filters followed by deterministic shallowest, remaining-capacity, join-order, and peer-identity ordering; standard ICE plus exact media proof tests one candidate at a time. Do not add raw-IP/NAT ranking, all-pairs probes, a weighted score, UA/visibility tiers, or periodic rebalancing. The temporary guards are safety boundaries, not accepted product limits, and must not be removed early.
+1. **Route Waves C-D: TURN admission, selection, and controller convergence.** Replace the remaining room-wide selected-lease guard with per-edge TURN allocation admission and exact accounting. Converge allocation, child reparent, and relay drain on one committed graph/controller. A signaling-connected relay that stops current-generation RTP cannot require its own report: after the bounded parent-proof deadline, persistent child-side silence reparents only the affected child whether the parent proved sending or not; cordon or drain the relay only after parent/session hard failure, explicit sender/resource failure, failed ingress repair, or independent downstream evidence. Parent candidates use hard eligibility filters followed by deterministic shallowest, remaining-capacity, join-order, and peer-identity ordering; standard ICE plus exact media proof tests one candidate at a time. Do not add raw-IP/NAT ranking, all-pairs probes, a weighted score, UA/visibility tiers, or periodic rebalancing. The remaining temporary guard is a safety boundary, not accepted product policy, and must not be removed early.
2. **Switch screen-audio ceilings live.** Keep Opus fixed and serialize 64/128/256 kbps desired profile updates across every current Host, relay, and SFU audio sender. Each endpoint uses fresh `getParameters()`/`setParameters()` readback, ignores stale completions, retains media plus its prior applied value on failure, and applies the latest desired value to future edges. Do not add a remote applied-ack protocol or claim room-wide atomic convergence in this slice.
3. **Switch video codec while paused.** After the route/media-generation boundary is available, serialize the change with route mutation, freeze exact current route/media bindings, hold new joins, renegotiate P2P/relay and republish SFU while paused, then verify actual codec plus decoded frames on resume. A binding invalidated by leave or hard route failure exits this proof set and waits for routing to rebuild from the final committed preference after the bounded codec transaction settles. On failure pause again and perform bounded rollback; rollback proves the prior preference was reapplied plus a newly negotiated actual codec and decoded progress, not literal equality with the old actual codec. Zero targets update only the future-edge preference. Reset `automatic` with empty codec preferences. This is a paused bounded-gap transaction; unpaused make-before-break is a later extension.
4. **Diagnose the production H.264/blur report.** Reproduce exact release `769de201f7cc` against current `main` on the same Host/browser/driver/game and one wired direct Viewer, changing one variable at a time. Implement a codec-specific repair only if codec/encoder evidence identifies it; otherwise fix the proven capture, sender, BWE, or lifecycle cause.
diff --git a/docs/verification-status.md b/docs/verification-status.md
index 77e08d8e..11128497 100644
--- a/docs/verification-status.md
+++ b/docs/verification-status.md
@@ -21,6 +21,7 @@ Capacity and routing entries below describe the exact tested source or release o
## Retained Functional Evidence
- Exact source `31e323e2754fcfde15f7b4d69e925ec71e2795cb` passed repository hygiene, TypeScript typecheck, client/server builds, all 660 Web tests, all Native Go packages, `go vet`, and two independent P0/P1 reviews. The tests cover strict v6 endpoint-cap authentication, ordinary active/waiting authorization and grace promotion, Native cap propagation and admission, and peer-assisted cap rejection. This is local state-machine/build evidence, not a complete Native physical-slot matrix or production, browser-quality, or heterogeneous-network acceptance.
+- Exact Wave B implementation source `815c6174d411c55648daf5cd6ac4c42f64effff9`, based on `d1ba2e52919225e67ad0c8dd2b660f333fbc88fd`, passed its 372-test SFU-admission gate, all 690 Web tests, TypeScript typecheck, and client/server builds. Focused tests cover reserved/committed/draining accounting, reserve-before-token enforcement, explicit room lifecycle, listener-owner startup fencing, restart cleanup, stale-token replay boundaries, Host-offline reclamation, shutdown races, and two-room global admission. This is fake-control-plane and local state-machine evidence, not a real LiveKit process/JWT replay, packet-flow, multi-process, deployment-capacity, or production proof.
- Chrome 151 synthetic `1/3/5/8` and 720p30 runs preserved bounded fanout and decoding. A `9461e20`-era three-Viewer rerun kept Host2/Browser Viewer1, decoded every Viewer, and recovered a hard first-level relay departure in 5,380 ms; it did not exercise quality-triggered MBB. Sixteen-Viewer cap2/cap3 loopbacks decoded all Viewers and a ten-second follow-up recorded guarded sender and aggregate Chromium CPU evidence, but resolution/FPS remained low and the ordinary-PC data cannot rank caps, select product policy, or prove sustainable heterogeneous-network quality. See [peer-assisted media](./research/peer-assisted-media.md).
- Chrome 151 with local LiveKit 1.13.5/client 2.22.0 proved one SFU/UDP root after `q,f` -> `q,h`: decoded frames advanced 3 -> 23, rendered frames reached 26, Host used one edge, leaves were clean, and TURN was absent. This is functional evidence only. See [low-server media routes](./research/low-server-media-routes.md).
- Host A+B and authenticated P2P Viewer C evidence is sanitized, generation-bound, read-only, and closed for stale, ambiguous, or SFU-fed reports. Production can expose a Host-local current SFU `h` snapshot and clears it on publisher identity changes; raw media metadata is not retained. See [realtime quality adaptation](./research/realtime-quality-adaptation.md).
@@ -34,7 +35,7 @@ Capacity and routing entries below describe the exact tested source or release o
- Routing: verify current-release initial ingress, `peer-selected` expiry/failure, corroborated bad-relay reassignment, one-root healthy SFU reselection, silent control partitions, signaling-connected current-generation RTP silence, and bounded failure on real browser/media paths. Silent control partitions may wait 30 to 60 seconds for heartbeat detection before the default five-second grace; RTP-silence acceptance must prove child-scoped recovery without granting one uncorroborated child authority to drain its parent.
- Quality: production startup blur remains unclassified. One same-`balanced` local A/B retained route/PC/SSRC/track while 720p rose to 1080p, but natural ramp prevents causal, production, or SFU conclusions. Correlate Host capture/encode/send with Viewer receive/decode before changing policy.
- Relay resources: current source has the authenticated `1/2/3` endpoint-cap boundary, while production `9461e20` remains Host2/ordinary Browser Viewer1 and rejects Viewer child2 regardless of advertised capacity. Before release, explicitly exercise Native `C=1/2/3` admission, waiting promotion, peer-assisted assignment, and physical sender slots; CPU/GPU/upload and heterogeneous-network measurements remain evidence, not authority to change the contract.
-- SFU: production `9461e20` deploys ordered `q,h`, roots <=2, and Dynacast off. Those are release facts; the accepted model has no fixed root-count or room-wide lease rule and still needs real shaped packet flow, BWE downshift/recovery, resource, and root-with-children validation. Use Linux `tc` or an authorized public canary for per-leaf shaping, never CDP throttling.
+- SFU: production `9461e20` deploys ordered `q,h`, roots <=2, and Dynacast off. Those are release facts; the accepted model has no fixed root-count or room-wide lease rule. Current source still needs real LiveKit lifecycle/JWT replay and shaped packet-flow, BWE downshift/recovery, resource, and root-with-children validation. Use Linux `tc` or an authorized public canary for per-leaf shaping, never CDP throttling.
- Audio: verify the 64/128/256 kbps Share settings, negotiated/observed bitrate, audible music quality, route changes, and game A/V synchronization. Bitrate settings are ceilings, not quality proof.
- Observability: the UI and local stats plumbing are deployed, including identity-bound relayed-detail retention and export freshness guards, but target-browser availability and actual values remain unverified for Host SFU sender evidence, codec/fmtp and encoder implementation/power efficiency, media-source and encoded FPS, A/V playout/jitter/concealment, selected candidate endpoints, and bounded same-pair STUN-response observation. These fields diagnose and have no recovery authority; they do not by themselves prove hardware encode, synchronization quality, or route quality.
- Mobile: Android/iOS remain Viewer-only. Autoplay, rotation, iOS lock-screen/page reclamation, background reconnection, and network changes need device evidence. AirPlay/system mirroring is Viewer-local output, not a portable in-app WebRTC output contract.
diff --git "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md" "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
index e4241186..5f9ddf65 100644
--- "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
+++ "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
@@ -358,13 +358,13 @@ Token-free SFU standby prewarm 保持可选且不创建 participant、publicatio
2. 完成 RoomStore、建房 API、WebSocket 鉴权和定向信令。
3. 完成屏幕捕获、逐观看者 PeerConnection、观看播放和手动质量档。
4. 完成连接恢复和 stats 面板;随后以 STUN-only snapshot 替换旧全房 TURN credential/refresh wire。
-5. 在已合入的 endpoint cap/accounting 与 `screener-v6` wire 边界上,从 canonical `main` 按 ADR-0005 完成 route waves B-D:建立 SFU/TURN resource admission,并把 deterministic allocation、child reparent 和 parent drain 收到一个 controller;每个 wave 独立可回滚。
+5. 在已合入的 endpoint cap/accounting、`screener-v6` wire 与 SFU admission/lifecycle 边界上,按 ADR-0005 完成 route waves C-D:建立 TURN allocation admission,并把 deterministic allocation、child reparent 和 parent drain 收到一个 controller;每个 wave 独立可回滚。
6. 路由边界合入后依次落 live screen-audio ceiling 和 paused video-codec transaction;随后做 H.264 根因诊断与 strict-NAT emulator gate,门禁通过才允许 allowlisted canary。
7. 加入 first-frame-driven Viewer connection stages。Site access、room-scoped Viewer grant、路由与 SQLite v3 合同保持唯一。
8. Windows Native fixed-`HIGH` 保持可选且不改变 Web 默认;shared encode、移动 lifecycle 和平台输出按 TODO roadmap 后续推进。
9. 当前功能、NAT 与真实网络 TODO 完成后,再分别设计和交付公网服务器一键部署包与完全不依赖外部服务的本地 Host-server 包。
-生产仍运行 `screener-v5`;当前 source 的 Wave A capacity slice 使用 `screener-v6`。不兼容 wire/schema 迁移须原子切换并保留迁移前备份。
+生产仍运行 `screener-v5`;当前 source 使用 `screener-v6`。不兼容 wire/schema 迁移须原子切换并保留迁移前备份。
任何一步只实现当前消费者需要的接口。不得为未来账号、第三种媒体拓扑或原生 sender 预建抽象层。
@@ -376,7 +376,7 @@ Token-free SFU standby prewarm 保持可选且不创建 participant、publicatio
Parent selection 使用硬过滤加字典序,不建立综合质量评分器。先拒绝 stale session、不可 source-reachable、成环、超深、无 sender/overlap slot、relay-ineligible、位于 failed-edge cooldown 或 server resource 未准入的候选;对剩余候选依次比较结果深度、分配后剩余稳态 sender slots、稳定加入顺序与 peer identity。controller 每次只 reserve/prepare 一个候选,使用该 `RTCPeerConnection` 自带的 ICE checklist/connectivity checks,再以 current-generation RTP、live track 与 decoded frame 验证;初次加入或 hard failure 采用达到 media-usable floor 的首个候选,soft-quality reparent 还需 quality owner 证明候选达到 recovery threshold 且优于仍健康旧 edge。失败先幂等清理候选再取下一个;受管 SFU room 完成删除证明前仍占 server capacity。应用不做 all-pairs ping、raw-IP/NAT/地理排名、周期探测或全房重平衡。一个 exact edge 的近期失败只进入该 edge 的有界 exclusion/cooldown,不污染其他路径。
-所有非服务器端点共享一个 server-authoritative steady outbound media-copy capacity:唯一配置 `ENDPOINT_MEDIA_COPY_CAPACITY` 默认 `2`,只接受 `1`、`2` 或 `3`,不兼容旧键。peer child 或 Host publication 各占一份,upstream receive 免费,committed selected TURN 只替换同一份 edge transport;SFU subscriber egress 与 TURN allocation 使用独立 server admission。客户端 capability 只能收紧该值,不能按角色、浏览器、UA、设备或页面可见性建立另一套 policy。服务端通过 v6 `authenticated.endpointMediaCopyCapacity` 把最终值交给 Web 与 Native;Native 不从 `maxViewers` 推导发送预算,普通 admission、peer-assisted child assignment 和槽位分配共用该值。代码通过一个 shared accounting guard 执行,不在 Host、Viewer、active、recovery 或 migration 分支重复 magic number;client/server/native wire 随该能力原子升级。首个迁移波次在独立 server admission 就绪前保留现有 SFU subscriber 与 room-wide selected-lease 安全护栏,但不把其固定值当作产品 policy;`C=3` 满载时必须在发出会产生第四份 Host media copy 的 token/grant 前明确等待或失败。
+所有非服务器端点共享一个 server-authoritative steady outbound media-copy capacity:唯一配置 `ENDPOINT_MEDIA_COPY_CAPACITY` 默认 `2`,只接受 `1`、`2` 或 `3`,不兼容旧键。peer child 或 Host publication 各占一份,upstream receive 免费,committed selected TURN 只替换同一份 edge transport;SFU subscriber egress 与 TURN allocation 使用独立 server admission。客户端 capability 只能收紧该值,不能按角色、浏览器、UA、设备或页面可见性建立另一套 policy。服务端通过 v6 `authenticated.endpointMediaCopyCapacity` 把最终值交给 Web 与 Native;Native 不从 `maxViewers` 推导发送预算,普通 admission、peer-assisted child assignment 和槽位分配共用该值。代码通过一个 shared accounting guard 执行,不在 Host、Viewer、active、recovery 或 migration 分支重复 magic number;client/server/native wire 随该能力原子升级。room-wide selected-lease 安全护栏在独立 TURN admission 就绪前继续保留,但不把其固定值当作产品 policy;`C=3` 满载时必须在发出会产生第四份 Host media copy 的 token/grant 前明确等待或失败。
SFU admission 在应用单进程中只有一个注入实例。LiveKit credential tuple 完整时,必须同时显式配置私有 `LIVEKIT_API_URL`、正 safe integer `SFU_INGRESS_CAPACITY` 与 `SFU_EGRESS_CAPACITY`;容量没有产品默认值,也不从 Viewer 数、endpoint cap 或历史 root 数推导。专用 LiveKit 实例设置 `room.auto_create: false`。账本只保存全局已用计数和按 exact room/share/publication generation 索引的 `reserved | committed | draining` 条目:Host publication 计 ingress `1`,每个订阅计 egress `1`,candidate、committed 和未完成 drain 的旧 generation 同时计数。route controller 先 reserve,再通过 `RoomService.CreateRoom` 创建 exact-generation room,成功后才 prepare 和签发 token;media proof 后 commit candidate 并把旧 generation 转入 draining,失败、超时、失联、分享换代、停止或删房也只转入同一状态。只有 `RoomService.DeleteRoom` 成功且 follow-up lookup 证明 room 不存在,账本才扣除对应资源;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。当前切片不实现 TURN allocation admission,不改 parent selection,也不预建多进程协调;多应用进程部署必须先增加共享原子 admission/lifecycle owner。