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): define reusable SFU subscriptions

AAAe2f6a0b7b82b
diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.md
index 0c34f96e..62a26732 100644
--- a/docs/adr/0005-automatic-hybrid-media-routing.md
+++ b/docs/adr/0005-automatic-hybrid-media-routing.md
@@ -227,21 +227,29 @@ For the single-process deployment, SFU admission is one injected authority with
deployment-wide ingress and egress counters. Enabling LiveKit requires explicit
positive safe-integer `SFU_INGRESS_CAPACITY` and `SFU_EGRESS_CAPACITY` values;
neither has a product default and neither is derived from endpoint capacity,
-Viewer admission, or a fixed root count. One Host publication consumes one
-ingress unit and every SFU subscription consumes one egress unit. A concurrent
-candidate and every generation still draining from LiveKit remain charged in
-addition to the committed generation.
+Viewer admission, or a fixed root count. 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 room, share, and publication
-generation, creates that managed LiveKit room through `RoomService`, and only
-then issues tokens. Commit moves the old generation to `draining`; abort,
-timeout, participant loss, share rollover, room stop, and room deletion move
-their generation to the same state. `RoomService.DeleteRoom` must complete and a
-follow-up lookup must prove the room absent before its ingress or egress units
-are released. Because joining cannot recreate a deleted room, a stale
-self-hosted token cannot produce an off-ledger participant.
+`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
diff --git a/docs/project-memory.md b/docs/project-memory.md
index a0f0d922..d6754acd 100644
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@ -12,7 +12,7 @@ Last updated: 2026-08-23
- Every non-server endpoint uses one server-authoritative steady outbound media-copy capacity: default `2`, statically configurable as `1`, `2`, or `3`. A peer child or the Host publication consumes one slot; upstream receive is free, selected TURN replaces the same copy's transport, and SFU subscriber egress is accounted at the server. Browser role/UA/visibility does not create a separate tier, and clients cannot raise the deployment value.
- The stable routing invariants are one authoritative upstream per Viewer, an acyclic source-reachable active graph, exact authenticated route attempts, endpoint and server admission, one room-serial child operation, and bounded success, wait, or failure.
- One room controller reconciles allocation, child reparenting, and relay drain through the same operation. It finds one waiting Viewer or invalid edge and builds one deterministic candidate list. The operation owns its cursor, current candidate and reservations, plus one total deadline; only its current candidate may produce media. A usable old edge remains until the exact candidate child decodes its first new video frame. That event commits; failure advances the cursor, while total deadline or exhaustion ends in wait or failure. A relay with a bad ingress reparents itself as a child and retains its subtree. A disconnected endpoint, or one whose effective downstream capacity falls below its current child count, accepts no excess children; its direct or overflow children enter the same operation and a disconnected endpoint is removed when childless. Authoritative pause aborts the operation, suppresses stall decisions, and resumes from a fresh reconciliation.
-- One Host publication may serve all SFU subscriptions. SFU-fed and peer-fed endpoints use the same provisional-child transaction, and selected TURN changes only the transport of an authorized logical edge. Parent choice hard-filters authority, reachability, cycles, effective capacity, and server admission, then orders by shallowest result, remaining steady sender capacity, stable join order, and peer identity. Acyclicity and room admission bound maximum depth; depth is observed but has no separate hard cap. Raw IP, claimed NAT type, UA, geography, all-pairs probes, weighted scores, and periodic room rebalancing are not route inputs.
+- One Host publication may serve all SFU subscriptions. Its exact generation owns one ingress handle and exact Viewer subscription handles own egress; later SFU children reuse the publication, while reserved, committed, and draining handles remain charged until the managed room is deleted and proven absent. SFU-fed and peer-fed endpoints use the same provisional-child transaction, and selected TURN changes only the transport of an authorized logical edge. Parent choice hard-filters authority, reachability, cycles, effective capacity, and server admission, then orders by shallowest result, remaining steady sender capacity, stable join order, and peer identity. Acyclicity and room admission bound maximum depth; depth is observed but has no separate hard cap. Raw IP, claimed NAT type, UA, geography, all-pairs probes, weighted scores, and periodic room rebalancing are not route inputs.
- Ordinary peer ICE is STUN-only. Credentials, room secrets, candidate details, and diagnostic data remain private and narrowly scoped.
- Screen audio offers live-switchable 64/128/256 kbps sender ceilings and defaults to 128. The existing last-wins quality wire owns desired state; each endpoint serially applies and reads back current Host/relay/SFU audio senders, exposes local failures, and gives future senders the latest desired value. Opus remains fixed, and without an applied-ack wire the Host does not claim room-wide atomic convergence. These are configuration ceilings, not fidelity claims.
- Video codec selection remains `automatic | H.264 | VP8`. The accepted first switching boundary is a generation-fenced renegotiation/republish transaction while sharing is explicitly paused; unpaused hot switching is later reuse of that transaction, not an independent mechanism.
diff --git a/docs/status.md b/docs/status.md
index 4bbcfab0..588de0ee 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -19,7 +19,7 @@ This is the current execution index. Git history owns completed timelines; [veri
- 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. Current `main` still carries the legacy childless-SFU-fed and route-quality slices that the pending generic reconciliation replaces.
- 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. Selected TURN has an independent explicit no-default deployment capacity; one process-local ledger charges every exact peer-selected edge and Host-SFU ingress through reserve, commit, drain, and release.
- Automatic P2P-first routing, one active upstream, an acyclic source-reachable graph, exact attempt authority, first-decoded-frame make-before-break, and bounded failure remain accepted.
-- The accepted controller has one event-driven reconciliation loop and at most one room-serial child operation. That object owns one deterministic candidate list/cursor, one current media candidate, its reservations, and one total deadline. Join, exact-edge failure, relay disconnect, and effective-capacity reduction all enqueue that operation. A relay repairs its own ingress as a child while retaining its subtree; excess direct children use the same operation before a disconnected childless relay is removed. One Host publication serves SFU subscriptions, SFU-fed endpoints use the ordinary provisional-child path, and TURN changes edge transport rather than topology. Endpoint accounting, the wire boundary, SFU lifecycle, and TURN admission are implemented; this controller convergence remains pending.
+- The accepted controller has one event-driven reconciliation loop and at most one room-serial child operation. That object owns one deterministic candidate list/cursor, one current media candidate, its reservations, and one total deadline. Join, exact-edge failure, relay disconnect, and effective-capacity reduction all enqueue that operation. A relay repairs its own ingress as a child while retaining its subtree; excess direct children use the same operation before a disconnected childless relay is removed. One Host publication serves exact Viewer subscription handles under the same SFU generation, SFU-fed endpoints use the ordinary provisional-child path, and TURN changes edge transport rather than topology. Endpoint accounting, the wire boundary, aggregate generation lifecycle, and TURN admission are implemented; exact subscription 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. The exact candidate child's first new decoded frame is the only application media-ready event. Moderate bitrate, FPS, or visual degradation remains with stock WebRTC/LiveKit adaptation and diagnostics; only hard connection failure or a non-paused decoded-frame stall invalidates a route edge. 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.
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 3b0a198f..df534995 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"
@@ -379,7 +379,7 @@ Token-free SFU standby prewarm 保持可选且不创建 participant、publicatio
所有非服务器端点共享一个 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 免费,committed selected TURN 只替换同一份 edge transport;SFU subscriber egress 与 TURN allocation 使用独立 server admission。服务端通过 v6 `authenticated.endpointMediaCopyCapacity` 把部署 `C` 交给 Web 与 Native;Native 不从 `maxViewers` 推导发送预算。代码通过一个 shared accounting guard 执行,不重复 magic number;client/server/native wire 随该能力原子升级。Selected TURN 使用显式无默认值的正 safe-integer deployment capacity;同一个进程内 ledger 对每条 exact peer-selected edge 和 Host-SFU ingress 在 credential 签发前 reserve `1`,并让 reserved、committed、draining authorization 持续计费至 exact logical release。`C=3` 满载时只阻止会产生第四份 endpoint media copy 的 token/grant;同一 edge 改用 TURN 不增加 endpoint copy,但仍需独立 TURN admission。
-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;exact candidate child 的 first decoded frame 后 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 使用独立的进程内 logical ledger;多应用进程部署必须先增加共享原子 admission/lifecycle owner。
+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 下的一份 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。TURN allocation 使用独立的进程内 logical ledger;多应用进程部署必须先增加共享原子 admission/lifecycle owner。
普通 Web relay 把收到的 remote track 加入独立 downstream `RTCPeerConnection`,因此可能逐跳解码和重编码;浏览器不保证跨连接 shared encode。每条 ordinary child 是独立网络副本,实际 encode time、CPU/GPU、bitrate、loss、frame rate、depth 和 recovery 必须测量。
diff --git "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md" "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"
index 5c7348bb..7808c419 100644
--- "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"
+++ "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"
@@ -52,7 +52,7 @@ SFU/TURN 的 publication、subscription、transport、server-resource accounting
- 原生 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`,不满足低分辨率 base 与最多两层。只有未来 native sender 能明确选择硬件编码器、最多发布两层、将同一编码输出复用于 direct/peer/SFU、保持每条路径独立选择并通过真实游戏和亚秒延迟门槛时,才可用新的 capability decision 重开 SVC;不能把浏览器 API 支持或 UA 推断当成采用理由。
- 分包/分层多树实验:把编码包、对象或可独立解码层拆到多个 peer 路径以分散上传,只能在独立 spike 中验证。必须保持亚秒级,处理多父重组、排序、丢包恢复、关键帧、同步和节点退出;未通过门槛前不进入产品路由控制器。
-- SFU/TURN 中央兜底:产品部署可以提供有界 SFU 与可选 TURN 资源,但不要求用户选模式,也不得默认变成整房 always-SFU。只有 Host 拥有一个 authoritative publication;SFU-fed 与 peer-fed endpoint 使用同一个 provisional-child first-frame transaction,严格受限 endpoint 在没有成功 child candidate 时自然保持 leaf。TURN 是某条授权 logical edge 或 Host-SFU ingress 的 selected transport,不是拓扑节点。启用 LiveKit fallback 时必须使用专用且关闭 `room.auto_create` 的实例,并显式提供私有 `LIVEKIT_API_URL`、无默认值的正整数 `SFU_INGRESS_CAPACITY` 与 `SFU_EGRESS_CAPACITY`;一份 Host publication 占一个 ingress,每份 SFU subscription 占一个 egress,reserved、committed 和 draining generation 都计入容量。单进程全局账本在发 token 前按 exact room/share/publication fence reserve,并先通过 RoomService 创建对应 room;commit、abort、timeout、disconnect、share rollover、room stop/delete 只把 generation 转入 draining,只有 DeleteRoom 成功和 absent readback 才释放计数。启动时必须先拒绝外来 room、清除全部遗留 Screener room 并确认 namespace 为空;Host 信令离线但 LiveKit participant 仍存在时继续保留和计费,participant 消失后有界回收。固定 root 数和普通端点 child 数都不能代替该准入;资源耗尽进入下一条有界候选、明确等待或失败。多应用进程部署必须先引入共享原子 admission/lifecycle owner,不能把各进程本地计数相加冒充全局准入。
+- SFU/TURN 中央兜底:产品部署可以提供有界 SFU 与可选 TURN 资源,但不要求用户选模式,也不得默认变成整房 always-SFU。只有 Host 拥有一个 authoritative publication;SFU-fed 与 peer-fed endpoint 使用同一个 provisional-child first-frame transaction,严格受限 endpoint 在没有成功 child candidate 时自然保持 leaf。TURN 是某条授权 logical edge 或 Host-SFU ingress 的 selected transport,不是拓扑节点。启用 LiveKit fallback 时必须使用专用且关闭 `room.auto_create` 的实例,并显式提供私有 `LIVEKIT_API_URL`、无默认值的正整数 `SFU_INGRESS_CAPACITY` 与 `SFU_EGRESS_CAPACITY`。单进程全局账本按 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;publication replacement、abort、timeout、disconnect、share rollover、room stop/delete 按资源所有权进入 draining,只有 DeleteRoom 成功和 absent readback 才释放该 generation 的 ingress/egress。启动时必须先拒绝外来 room、清除全部遗留 Screener room 并确认 namespace 为空;Host 信令离线但 LiveKit participant 仍存在时继续保留和计费,participant 消失后有界回收。固定 root 数和普通端点 child 数都不能代替该准入;资源耗尽进入下一条有界候选、明确等待或失败。多应用进程部署必须先引入共享原子 admission/lifecycle owner,不能把各进程本地计数相加冒充全局准入。
- 分享端桌面封装:用 Electron 固定 Chromium 版本、改善选源/热键/系统音频体验,同时保留 Web 观看端。
- Windows 应用音频:Windows 11 Native sender 使用本地 opaque window target 绑定 HWND、PID 与进程创建时间,只捕获所选游戏及其子进程的音频,避免把语音聊天或通知声一并分享;“全部系统声音”只能由分享者显式选择。普通 Windows 10 不具备当前 process-loopback API 门槛,必须明确标为未解决/不支持而不是伪兼容。浏览器无法证明或隔离任意进程音频时必须如实提示,原生捕获失败、无声或进程退出不得静默扩大为整机捕获。
- 受限网络增强:短期鉴权 TURN 只有在完整、默认关闭的部署配置和当前 route controller 明确授权时可用;普通 peer PC 从创建起保持 STUN-only,不得向整个 participant、房间或所有 peer connections 预发 TURN candidates。凭据必须绑定 exact room/share/session/route/connection generation,短期有效、内存态、受配额约束且不进入 URL、日志、浏览器持久化或 SQLite。TURN 只替换授权 edge 的 transport;Host 无 direct first-level path 时可作为单条 Host-SFU ingress 的 transport。TURN 不得被描述为更高清的传输方式。