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

fix(web): keep viewer media state truthful [skip ci]

AAA9a76cc717747
diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.md
index 3d32941a..39ccf9ab 100644
--- a/docs/adr/0005-automatic-hybrid-media-routing.md
+++ b/docs/adr/0005-automatic-hybrid-media-routing.md
@@ -52,6 +52,13 @@ Treat the SFU as a virtual parent for selected fallback roots, not as an
all-room replacement. Keep the existing peer-assisted topology as the active
baseline and add one in-memory `MediaRouteController` per room.
+Eligible parent relationships form a mesh-like candidate graph, but active
+media remains a loop-free graph with one upstream per Viewer. Join, capacity,
+disconnect, and current-edge failure are bounded reselection triggers. A
+transition may overlap old and prepared edges only within the existing edge
+budgets and must commit from current-generation media proof; steady multi-source
+striping is not part of the media path.
+
```text
normal: host -> root A -> ...
host -> root B -> ...
diff --git a/docs/project-memory.md b/docs/project-memory.md
index f69f37ed..623afc0d 100644
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@ -32,7 +32,7 @@ Last updated: 2026-08-21
- Flagship media is UDP; HTTPS/WSS stays TLS/TCP; the old release remains rollback-only.
- Treat settings as ceilings and degradation as unclassified. Use correlated Host A+B/Viewer C and one-variable evidence; never force AV1, infer by UA, or create a composite score.
- Web window/system-audio requests are browser hints; tracks use `music`. P2P/relay/SFU senders request 128,000 bit/s and SFU disables DTX; this is a ceiling, not a quality/stereo guarantee. Native Win11 process audio stays source-only; one Viewer got 495 Opus packets.
-- Presence reports exact active upstream and feeds the on-demand Host topology; it never creates media. Details label P2P/SFU and show TURN only for an actual relay. Web Host names stay socket/localStorage-only; Native remains outside the boundary.
+- Presence reports exact active upstream and feeds Host topology; it does not prove media. Details may label assigned P2P/SFU before media proof and show TURN only for an actual relay; status stays pending without local/current evidence. Web Host names stay socket/localStorage-only; Native remains outside the boundary.
- Do not add scene detection, dynamic-FPS control, or forced AV1 without negotiation, encode, game, CPU/GPU, and sender evidence.
- ADR-0002 grant/public access, the v3 room-password migration, and Web Host display names are deployed. Names/presence remain session-only without account or roster tables.
diff --git a/docs/status.md b/docs/status.md
index 179e6fd4..80ac460d 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -17,7 +17,7 @@ Flagship; parallel; min run/smoke/rollback; benchmark later. Active UI/config/lo
- Capture precedes room creation; source/quality changes and AV pause preserve peers. Recommended profiles and advanced defaults use `balanced`; clarity/fluid remain explicit. The browser chooses degradation; readback/stats report actual behavior.
- Production access is `screener-v2`: a valid private fragment grant enters directly; every code-only Viewer must first hold site access, after which public-watch accepts the code and private rooms still require their room password. `SITE_ACCESS_PASSWORD`, `/api/site-access`, and the site-access cookie are deployed atomically; raw credentials are never stored.
-- Source UI uses adjacent nickname editing, distinct site/room prompts, and a shared inline/`/join` room-code form; production still has the prior UI. Deployed presence exposes exact active upstream/topology and remains control-plane-only.
+- Source UI uses adjacent nickname editing, distinct site/room prompts, and a shared room-code form; production still has the prior UI. Exact upstream may label green P2P/yellow `SFU fallback` before media proof; connected status still needs evidence and TURN stays actual-only.
- Native v2 is source-only (memory rooms, 300s reclaim); it follows authenticated direct-child assignments up to two and fails unsupported SFU/selected ingress boundedly.
- PR #44's STUN-only/SFU-UDP router and token-free fallback prewarm are process-enabled for all normal rooms: roots <=2, browser relay <=1, bounded failure. Room `1` is historical smoke; mobile/iPad viewers are leaves, healthy edges sticky, and HTTPS/WSS stays TLS/TCP.
- After an answer, a generation-bound 15s initial-connect deadline enters ICE restart; success/replacement/disposal cancels it. It is deployed but not mobile-verified.
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 9d8bd043..cfc63ab1 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"
@@ -100,7 +100,7 @@ rotate、revoke 或从 public-watch 切回 private-link 都是当前 Viewer 的
Web Host 在 `authenticate` 中显式发送 `viewerPresence: true` capability,Viewer 也可显式订阅同一 participant snapshot;Native sender 不发送,因此继续只收到原有 exact server wire。两端可在 `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 接收证据显示“已连接”,否则区分“线路已分配”和“连接中”;连接详情只显示 `P2P` 或 `SFU`,且仅在本机真实 selected relay 时附加 `TURN`。独立拓扑按钮从同一 snapshot 展示 Host、实际存在的 SFU 节点及精确上下游,不从客户端媒体快照推断。peerId 不因此成为授权身份或路由输入;名称、presence 与拓扑视图不改变授权、媒体或路由状态机。
+每个 presence 条目包含 `role`、`peerId`、`displayName` 和服务端 active assignment 的精确 `upstream`:Host 为 `none`,Viewer 为 `none | peer(peerId) | sfu`。UI 始终展示名称加 peerId 尾部至少六字符短后缀;碰撞时逐字符有界延长至完整 peerId。卡片状态只依据本机连接或当前 Viewer 接收证据显示“已连接”,否则保持中性的“线路分配中”或具体连接状态;active assignment 本身不是连接成功证据。连接详情按 authoritative assignment/controller route 显示媒体徽标,即使媒体仍在连接:`P2P` 为绿色图标,`SFU fallback` 为黄色图标,且仅在本机真实 selected relay 时另附 `TURN`。独立拓扑按钮从同一 snapshot 展示 Host、实际存在的 SFU 节点及精确上下游,不从客户端媒体快照推断。peerId 不因此成为授权身份或路由输入;名称、presence 与拓扑视图不改变授权、媒体或路由状态机。
## 信令协议
@@ -309,7 +309,7 @@ hop 按[低服务器成本媒体路由](./research/low-server-media-routes.md)
首屏就是工具,不做营销页。视觉采用中性深灰工作台,绿色表示 direct、琥珀色表示 relay/警告、红色表示失败,避免单一蓝紫色主题;浏览器 favicon 复用页头 `MonitorUp` 的深绿底、绿色显示器和上行箭头语言。
- 访问入口:未鉴权根路径、`/join` 和 code-only `/r/{code}` 显示“站点访问”与“站点口令”,未知路径只显示“无法访问”。有效 `/r/{code}#v={grant}` 直接进入;其余 Viewer 通过 site access 后,public-watch 进入房间,private room 显示“加入房间”与“房间密码”。已有有效 site-access cookie 不重复显示整站验证;站点口令和房间密码不共享输入值或授权状态。无效、过期、错误密码或满员只显示通用拒绝,不泄露房间存在性或 policy。
-- 分享者根页面:顶部显示“{分享者显示名} 的屏幕”和房间状态,并在标题旁显示可单独复制的紧凑房间号;Viewer 同一位置显示权威 Host 名称,不再在标题下重复。主区域保持稳定的 16:9 舞台。未发布、已停止或可恢复错误状态时,舞台内以同等尺寸和权重显示“开始分享”和“加入房间”,中间只用“或”与分隔线表达发送/接收;前者直接开始现有分享流程,后者作为 disclosure 在当前舞台内、紧邻触发按钮就地展开共享的房间码表单,提交后才导航到 `/r/{code}`。按钮同步 `aria-expanded`/`aria-controls`,展开后输入获得焦点,DOM 与焦点顺序保持触发器后接表单;窄屏允许表单换到动作行下方,不产生横向滚动。不增加首页、向导或拓扑选择。直播时舞台显示本地预览及独立全屏图标,底部保留停止、同步暂停音视频、质量档位和复制完整邀请链接;页面失焦仅暂停本地 video element,媒体暂停则禁用 capture stream 轨道,两者都保留现有连接。
+- 分享者根页面:顶部显示“{分享者显示名} 的屏幕”和房间状态,并在标题旁显示可单独复制的紧凑房间号;Viewer 同一位置显示权威 Host 名称,不再在标题下重复。主区域保持稳定的 16:9 舞台。未发布、已停止或可恢复错误状态时,舞台内以同等尺寸和权重显示“开始分享”和“加入房间”,中间只用“或”与分隔线表达发送/接收;前者直接开始现有分享流程,后者作为 disclosure 在当前舞台内、紧邻触发按钮就地展开共享的房间码表单,提交后才导航到 `/r/{code}`。按钮同步 `aria-expanded`/`aria-controls`,展开后输入获得焦点,DOM 与焦点顺序保持触发器后接表单;窄屏允许表单换到动作行下方,不产生横向滚动。不增加首页、向导或拓扑选择。直播时舞台显示本地预览及独立全屏图标,底部保留停止、同步暂停音视频、质量档位和复制完整邀请链接;页面失焦仅暂停本地 video element,并在舞台提示“本地预览已暂停,分享仍在继续”;媒体暂停则禁用 capture stream 轨道,两者都保留现有连接。
- `/join`:保留为可直接访问的回退入口,并复用同一个房间码表单;通过 site access 后只输入正整数房间码并进入 `/r/{code}`。public-watch 直接通过,private room 缺失 grant 时显示当前房间的密码表单。
- `/r/{code}` 观看者:private room 首次解析合法 fragment grant 后立即清理地址栏并直达;仅有 code 时先通过 site access,再按 public/private policy 进入。鉴权后主区域最大化远端视频,标题旁显示可复制的紧凑房间号,顶部保留连接状态,并提供本地音量、静音、全屏和重试控制。
- 移动端:视频保持稳定宽高比,控制与状态移到视频下方,任何文字和按钮不得溢出或遮挡。
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 697a90d7..ccce72c9 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"
@@ -19,7 +19,7 @@
- [ ] 首屏双入口:分享入口通过站点访问后,主工作区必须同等突出“开始分享”和“加入房间”两个主要动作,并用清楚的视觉分隔表达发送与接收;持合法房间 grant 的观看者不需要知道站点访问密码。“加入房间”在当前舞台内就地展开房间码输入并提交,不先跳转到独立页面;直接访问 `/join` 仍提供同一输入能力。不增加营销首页、模式向导或拓扑选择。浏览器标签页使用与现有 `MonitorUp` 品牌语言一致的 favicon。
- [ ] 简单房间:分享者获得纯数字房间码,但房间码只负责定位。现有 `/r/{code}#v={grant}` 合法未过期邀请继续直接进入;仅有 `/r/{code}` 或 `/join` 房间码的 Viewer 必须先通过站点访问验证,再按房间 policy 进入:public-watch 接受房间码,private room 还需正确观看密码。所有入口只授予该房间 Viewer,不能建房、发布、冒充 Host 或跨房。Host 与 Viewer 标题附近都紧凑、显眼地显示房间号并提供只复制房间号的动作,Host 保留复制完整邀请链接;持久房间码从 `1` 开始自增,其他模式继续使用随机临时房间码。
- [ ] 免安装观看:桌面和手机观看者可直接通过浏览器链接进入、授权并播放,不依赖与分享端相同的桌面客户端。
-- [ ] 屏幕采集:分享者可主动选择显示器或应用窗口,开始、停止、临时同步暂停音视频和切换分享来源;暂停保留现有连接并禁用当前 capture stream 的全部媒体轨道。Host 本地预览必须直接使用 capture stream,支持独立全屏;页面失焦或隐藏时只暂停本地 video element,恢复焦点后继续预览,不得停止 capture、编码或上行。预览不得建立 viewer/媒体边或消耗 TURN、SFU、应用服务器 media egress;预览仍可能产生本地合成、缩放和 GPU 显示成本,不能把隐藏预览称为停止采集或编码。
+- [ ] 屏幕采集:分享者可主动选择显示器或应用窗口,开始、停止、临时同步暂停音视频和切换分享来源;暂停保留现有连接并禁用当前 capture stream 的全部媒体轨道。Host 本地预览必须直接使用 capture stream,支持独立全屏;页面失焦或隐藏时只暂停本地 video element,并明确提示“本地预览已暂停,分享仍在继续”,恢复焦点后继续预览,不得停止 capture、编码或上行。预览不得建立 viewer/媒体边或消耗 TURN、SFU、应用服务器 media egress;预览仍可能产生本地合成、缩放和 GPU 显示成本,不能把隐藏预览称为停止采集或编码。
- [ ] 游戏声音:Windows Chrome/Edge 目标环境可请求系统音频;没有返回音轨时必须明确提示,而不是静默无声。
- [ ] 观看端本地音量:播放控制栏提供 `0%` 至 `100%` 音量条和静音按钮,只改变当前浏览器的媒体元素,不修改 Host 音轨、编码、房间状态或其他观看者。切流、换父和 ICE 恢复保留当前页面内的值;刷新后不持久化。静音保留上次非零音量,拖动到非零值自动取消静音。
- [ ] 本地昵称与房间成员:用户可设置一个只保存在当前浏览器同源 `localStorage` 的显示名,界面统一称为“昵称”;默认以只读文本显示,铅笔编辑按钮紧贴昵称,点击后才进入编辑。Viewer 顶部标题直接显示“{Host 名称} 的屏幕”,不得在下方重复一行 Host 名称。信令只在当前在线 socket 会话内保存和广播 NFC 规范化、最多 24 个 Unicode code points、拒绝控制/换行/双向覆盖符与孤立 surrogate 的纯文本标签,不写 SQLite 或日志。空值使用通用角色 fallback。Host 必须看到全部当前在线 Viewer 的权威总数与 roster,不能拿最多两条 Host 媒体直连数冒充在线人数;presence 更新也不得创建媒体连接。展示身份使用“名称 + 当前房间 `peerId` 的至少六字符短后缀”,房内碰撞时有界延长。显示名、后缀和 `clientId` 都不是账号、授权身份或全局 UUID,重复名称允许且不得参与授权、路由或质量决策。Web Host 与 Viewer 通过同一 opt-in participant roster 看到 Host 名称;Native 不发送 capability,wire 保持不变。
@@ -32,7 +32,7 @@
- [ ] 路径级质量状态:应用的 `HIGH`/`FALLBACK` 非对称窗口只决定拓扑资格和诊断,不命令正常的媒体层切换,也不计算综合分数。SFU BWE downshift 先进入 `suspect`;多个连续窗口的 sender/viewer 关联证据确认 `FALLBACK` 后,应用不得稳定保留该 parent,并把 downstream capacity 降为 0。计划或显式质量 fallback 仅是内建路径失败后的候选:已有 children 时先在 connection/assignment generation guard 下全部迁走,失败或代次过期则保持原 assignment/quality。Autonomous downshift 无法 packet-level 预先迁移,default-on 前必须验收 descendants 的短暂影响。只有更长的稳定恢复窗口和 cooldown 后才能重新声明 relay capacity。Viewer 请求必须鉴权、限频、去重,并由 sender 的 GCC/Transport-CC、实际码率、RTT、丢包、重传、编码限制、协商 codec/profile/parameters 与 viewer 解码、丢帧、冻结证据交叉验证;不能仅凭自报生效,也不得上传 raw SDP、candidate 地址或原始设备/网络标识。
- [ ] 断线恢复:临时网络变化时按不同层级做一次性恢复,而不是把同一动作机械重复三次。`failed` 边先做一次 ICE restart,再重建一次同 parent 的 `RTCPeerConnection`,随后尝试一个不同的合格 peer parent;只有 peer 路径耗尽才进入 SFU。`connecting`/`checking` 先显示不改变拓扑的慢连接状态,硬超时必须由真实移动网络证据确定,不能为了更快使用服务器而过早放弃最终可成功的 P2P。任一步恢复即停止后续动作;所有异步结果受 session、route revision、assignment/connection generation 约束。active SFU 只允许一次 fresh-token 重试,再失败即有界回到 peer baseline 或明确失败,并向 Host 显示不含 URL、地址、token 或原始错误的失败阶段。
- [ ] 可观测性:按目标 RTP transport 与不透明连接/ICE 代次关联 selected path、`iceGatheringState`/ICE/connection state、事件推导的建立时长、generation-baselined pair-change delta,以及 RTT、RTP 丢包率、抖动、码率、帧率、编码耗时和受限原因。候选与错误的 wire、日志和导出只使用[低服务器成本媒体路由](./research/low-server-media-routes.md)的脱敏字段和 code bucket,禁止 raw SDP、candidate、地址、URL、`errorText` 或网络标识。只有创建该 `RTCPeerConnection` 的本机可在折叠详情中显示浏览器对 selected local/remote candidate 实际暴露的地址与端口;该值不上传、不持久化、不用于地理/NAT 推断,缺失或被隐私保护时显示未知。
-- [ ] 渐进式诊断:分享者和观看者默认只看到房间、画面、核心状态和常用控制;Host 的 Viewer 卡片只把本机连接或当前接收证据称为“已连接”,其余 active assignment 显示“线路已分配”,未分配显示“连接中”。展开连接详情只把媒体方式归为 `P2P` 或 `SFU`,实际 selected relay 时才另标 `TURN`;Host/Peer 上下游只在独立的权威拓扑视图中展示。候选路径、RTT、视频/音频 RTP 区间丢包率、实际编解码器、音频区间码率/jitter 和视频编码耗时等技术详情由一个明确的“显示连接详情”开关展开。音频 codec MIME、RTP clock、channels 与 fmtp 只能来自当前 RTP 对象引用的 `RTCCodecStats`,缺失即未知;`opus/48000/2` 不得写成 48 kHz 音源或实际立体声。隐藏诊断不能隐藏失败原因、音频缺失、持续画质受限或需要用户操作的告警。
+- [ ] 渐进式诊断:分享者和观看者默认只看到房间、画面、核心状态和常用控制;Host 的 Viewer 卡片只把本机连接或当前接收证据称为“已连接”,其余状态保持中性的“线路分配中”或具体连接状态,不把 active assignment 当作连接成功。展开连接详情可按 authoritative assignment/controller route 显示媒体方式,即使媒体仍在连接:`P2P` 使用绿色与直观图标,`SFU` 使用黄色的 `SFU fallback`;实际 selected relay 时才另标 `TURN`。Host/Peer 上下游仍只在独立的权威拓扑视图中展示。候选路径、RTT、视频/音频 RTP 区间丢包率、实际编解码器、音频区间码率/jitter 和视频编码耗时等技术详情由一个明确的“显示连接详情”开关展开。音频 codec MIME、RTP clock、channels 与 fmtp 只能来自当前 RTP 对象引用的 `RTCCodecStats`,缺失即未知;`opus/48000/2` 不得写成 48 kHz 音源或实际立体声。隐藏诊断不能隐藏失败原因、音频缺失、持续画质受限或需要用户操作的告警。
- [ ] 站点访问:生产部署必须配置独立的 `SITE_ACCESS_PASSWORD` 控制建房、Host 信令角色和所有 code-only Viewer 入口;只有本地开发/测试可显式关闭。非空值接受 8 至 128 个可见 ASCII bytes,不能复用 TURN、LiveKit、TLS 或其他部署 secret。`POST /api/site-access` 验证成功签发 12 小时、无服务端会话状态的 HttpOnly、`SameSite=Strict` site-access cookie。有效 room-scoped fragment grant 可绕过站点 gate 直接进入对应房间;其余 `/r/{code}`、`/join` 和 public-watch 必须先持有效站点 cookie,之后才检查房间 public/private policy 和房间密码。失败统一且不得泄露房间是否存在或 policy;建房 HTTP 只认该 cookie。已移除的旧环境变量、endpoint 和 cookie 不保留兼容。不引入账号、JWT、服务端 session Map 或通用 logout。
- [ ] 房间级观看授权:新房间默认生成含 256-bit 随机量、限时且可撤销的 room-scoped Viewer grant;服务端只保存完整 grant 的 SHA-256 摘要。到期阻止以后鉴权/重连,但不为已鉴权 Viewer 设置踢出定时器;即时清退使用 rotate/revoke。浏览器从 URL fragment 严格读取 grant 后,只写该房间的 `sessionStorage` 并立即用 `history.replaceState` 清除 fragment;刷新和页面内重连可继续。私密房间缺失 grant 时必须先通过站点访问,再提供正确房间观看密码;任一缺失都 fail closed。grant 不得进入 `localStorage`、cookie、query、WebSocket URL、Referrer、日志或错误。Host 可 rotate 或 revoke;revoke 只锁定 grant 路径,已配置的房间密码仍是独立的后续进入方式。新 grant 摘要成功提交后必须清除 Viewer grace/路由、终止旧授权代次的信令和媒体并断开全部旧 Viewer,数据库写失败则不得改变连接。public-watch 是显式、可逆的 room policy,只放宽房间级观看,不绕过站点访问。
- [ ] 最小持久化:`ROOM_DATABASE_PATH` 可选且必须与 `SITE_ACCESS_PASSWORD` 同时配置。两者都存在时,SQLite 只持久保存从 `1` 开始自增的房间 ID、Host token 摘要、nullable Viewer grant 摘要,以及 nullable 48-byte Viewer-password material(16-byte salt + 32-byte scrypt verifier);数据库 `CHECK` 约束非空 BLOB 长度,不新增用户、成员或 session 表。明文房间密码只短暂存在于当前页面和鉴权/派生调用内存,不进入 URL、cookie、浏览器持久存储、日志或 SQLite。持久房间停止后仍显示等待状态;私密邀请按期限或 Host rotate 更新。旧 schema 行在原子迁移时必须 fail-closed 为没有可用明文 grant 的锁定私密状态,Host rotate 后才能生成新邀请。
@@ -41,7 +41,7 @@
- [ ] 私密房间双入口:private room 接受现有 `/r/{code}#v={grant}` 合法邀请直接进入,或“站点访问 + 房间号 + 该房间观看密码”。没有 grant 的 `/join` 或 `/r/{code}` 先显示明确标为“站点访问”的整站验证,通过后才显示明确标为“加入房间”的当前房间密码输入;有效 site-access cookie 直接跳过第一步,但两类密码不得复用、代填或互相替代。Host 可设置、轮换或移除房间观看密码。密码接受 1 至 64 个可见 ASCII 字符;异步 scrypt 全局最多执行 2 个、等待 16 个派生。站点口令和房间密码都不得进入 URL/query/storage/log/SQLite;不存在、错误密码、队满和正确密码后的满房都返回通用结果。
-- [ ] 统一自动路由:旗舰部署开启 `PEER_ASSISTED_MEDIA` 后,所有正常房间都进入同一个 direct/peer -> SFU -> selected-edge controller;每个房间独立保存 assignment/session/revision/connection generation 和容量状态。`PEER_ASSISTED_ROOM_IDS` 已退役,room `1` 只作为历史 smoke fixture,不能作为功能开关。未启用总开关的开发/轻量部署仍可保留 ordinary P2P;普通 peer 始终 STUN-only。selected-edge TURN 只能复用当前 controller 选中的异常 edge,不能向普通 peer edge 预发 candidates。该能力不增加 UI、用户选择、百分比发布或第二套路由器。
+- [ ] 统一自动路由:旗舰部署开启 `PEER_ASSISTED_MEDIA` 后,所有正常房间都进入同一个 direct/peer -> SFU -> selected-edge controller;每个房间独立保存 assignment/session/revision/connection generation 和容量状态。合格父节点构成网状候选关系,但实际媒体保持无环且每个 Viewer 只有一个 active upstream;加入、容量变化、掉线和当前边失败触发有界重选,切换重叠必须受现有边预算与当前代媒体证据约束,不做常驻多源分片。`PEER_ASSISTED_ROOM_IDS` 已退役,room `1` 只作为历史 smoke fixture,不能作为功能开关。未启用总开关的开发/轻量部署仍可保留 ordinary P2P;普通 peer 始终 STUN-only。selected-edge TURN 只能复用当前 controller 选中的异常 edge,不能向普通 peer edge 预发 candidates。该能力不增加 UI、用户选择、百分比发布或第二套路由器。
- [ ] 质量控制扩展:推荐档位仍是默认入口;折叠高级区只允许 720p/1080p/1440p 分辨率 ceiling、15 至 60 的整数 FPS ceiling、2 至 12 Mbps 视频码率 ceiling,以及清晰/平衡/流畅三种偏好。直播中显式应用后才生效,避免滑杆产生连续控制流量。Web 不提供音频声道、采样率、Opus 码率、stereo、DTX 或 FEC 控件;每个实际浏览器音频 sender 固定请求并读回 128 kbps ceiling,SFU 音频发布使用同值 preset 且关闭 DTX。该值只是标准 API/SDK 支持的发送上限,实际码率仍以 stats 为准。display capture 未把声道和采样率定义为可移植控制,其他项依赖 codec/fmtp 协商而没有可移植 sender setter。不得为这些控件新增应用层 SDP munging 或用默认值制造伪控制。实际质量持续低于所选上限时必须显示可解释的限制原因;在真实拥塞、编码器和接收端证据完成前,不把任一组合称为“完美平衡”。
- [ ] 本地预览性能候选:在相同动态场景中 A/B 测量 Host 动态预览开/关的 CPU、GPU、encode time 和实际 FPS。只有稳定收益且捕获、编码和远端画面不受影响时,才允许直播开始后默认显示静止缩略图或隐藏动态预览并提供按需展开;未测前不宣称收益。
- [ ] Peer-assisted 媒体实验:分享端最多两个 child、每名 viewer 最多一个 child;信令服务只按深度和服务端加入序号确定性地形成两条 sticky 平衡链,不加入综合评分或主动重平衡。每个 viewer 将收到的标准 remote track 通过新的 `RTCPeerConnection` 转发,因此会逐跳解码和重编码;必须测量而不能称为 shared encode。服务端只在受房间数限制的内存状态中保存当前严格校验的质量设置,不写入 SQLite;host 鉴权后先重报设置,在线 viewers 接收更新,后加入者从鉴权快照取得当前值。该功能在 ADR-0004 的实验门槛通过并由后续 ADR 正式接受前不得成为产品路径。
diff --git a/src/client/components/StatusBadge.tsx b/src/client/components/StatusBadge.tsx
index 3a1f7328..72748288 100644
--- a/src/client/components/StatusBadge.tsx
+++ b/src/client/components/StatusBadge.tsx
@@ -1,8 +1,9 @@
-import { CircleAlert, Radio, Wifi, WifiOff } from "lucide-react";
+import { CircleAlert, Network, Radio, Server, Wifi, WifiOff } from "lucide-react";
import type {
MediaPath,
SignalConnectionState,
} from "../types";
+import { MEDIA_ROUTE_PRESENTATION, ROUTING_STATUS_PRESENTATION } from "./status-badge-model";
interface BadgeProps {
tone: "good" | "warning" | "danger" | "neutral";
@@ -36,15 +37,15 @@ export function SignalStatusBadge({
export function PeerStatusBadge({
state,
}: {
- state: RTCPeerConnectionState | "reconnecting" | "waiting" | "assigned";
+ state: RTCPeerConnectionState | "reconnecting" | "waiting" | "routing";
}) {
const labels: Record<
- RTCPeerConnectionState | "reconnecting" | "waiting" | "assigned",
+ RTCPeerConnectionState | "reconnecting" | "waiting" | "routing",
BadgeProps
> = {
waiting: { tone: "neutral", label: "等待开始分享" },
reconnecting: { tone: "warning", label: "正在恢复" },
- assigned: { tone: "neutral", label: "线路已分配" },
+ routing: ROUTING_STATUS_PRESENTATION,
new: { tone: "neutral", label: "准备中" },
connecting: { tone: "neutral", label: "正在连接" },
connected: { tone: "good", label: "已连接" },
@@ -81,12 +82,16 @@ export function PathBadge({ path }: { path: MediaPath }) {
}
export function MediaRouteBadge({ route }: { route: "p2p" | "sfu" }) {
+ const presentation = MEDIA_ROUTE_PRESENTATION[route];
+ const Icon = presentation.icon === "network" ? Network : Server;
return (
- <Badge
- tone={route === "p2p" ? "good" : "neutral"}
- label={route === "p2p" ? "P2P" : "SFU"}
+ <span
+ className={`status-badge status-${presentation.tone}`}
title="当前媒体路径"
- />
+ >
+ <Icon size={14} aria-hidden="true" />
+ {presentation.label}
+ </span>
);
}
export function WarningBanner({ children }: { children: React.ReactNode }) {
diff --git a/src/client/components/status-badge-model.ts b/src/client/components/status-badge-model.ts
new file mode 100644
index 00000000..25748b4d
--- /dev/null
+++ b/src/client/components/status-badge-model.ts
@@ -0,0 +1,43 @@
+import type { ParticipantRouteAssignment } from "../../shared/protocol";
+import type { ConnectionMetrics, PeerSnapshot } from "../types";
+
+export const MEDIA_ROUTE_PRESENTATION = {
+ p2p: { tone: "good", label: "P2P", icon: "network" },
+ sfu: { tone: "warning", label: "SFU fallback", icon: "server" },
+} as const;
+export const ROUTING_STATUS_PRESENTATION = { tone: "neutral", label: "线路分配中" } as const;
+
+export type PresentedMediaRoute = keyof typeof MEDIA_ROUTE_PRESENTATION;
+
+export function viewerRouteEvidence(
+ upstream: ParticipantRouteAssignment["upstream"] | null,
+ peer: PeerSnapshot | null,
+ sfu: {
+ connectionState: "connected" | "reconnecting";
+ metrics: ConnectionMetrics | null;
+ } | null,
+): {
+ route: PresentedMediaRoute | null;
+ evidence: {
+ connectionState: PeerSnapshot["connectionState"] | "reconnecting";
+ metrics: ConnectionMetrics | null;
+ } | null;
+} {
+ if (!upstream) {
+ return sfu
+ ? { route: "sfu", evidence: sfu }
+ : peer
+ ? { route: "p2p", evidence: peer }
+ : { route: null, evidence: null };
+ }
+ if (upstream.kind === "sfu") {
+ return { route: "sfu", evidence: sfu };
+ }
+ if (upstream.kind === "peer") {
+ return {
+ route: "p2p",
+ evidence: peer?.peerId === upstream.peerId ? peer : null,
+ };
+ }
+ return { route: null, evidence: null };
+}
diff --git a/src/client/media/viewer-sfu-route.ts b/src/client/media/viewer-sfu-route.ts
index 1b7eb3de..d2322117 100644
--- a/src/client/media/viewer-sfu-route.ts
+++ b/src/client/media/viewer-sfu-route.ts
@@ -43,12 +43,14 @@ interface ViewerSfuRouteEvents {
assignment: ParticipantRouteAssignment,
initialVideoStream: boolean,
) => void;
+ onSfuVideoAvailability?: (available: boolean) => void;
onSfuUpdate?: (metrics: ConnectionMetrics | null) => void;
onSfuState?: (state: "connected" | "reconnecting") => void;
send: (message: ClientMessage) => boolean;
createSubscriber?: (
events: {
onStream: (stream: MediaStream | null) => void;
+ onVideoAvailability: (available: boolean) => void;
onStats: (metrics: ConnectionMetrics) => void;
onState: (state: "connected" | "reconnecting") => void;
onDisconnected: () => void;
@@ -189,6 +191,9 @@ export class ViewerSfuRoute {
this.handleStream(slot, stream);
}
},
+ onVideoAvailability: (available: boolean) => {
+ this.handleVideoAvailability(slot, available);
+ },
onStats: (metrics: ConnectionMetrics) => {
if (this.active === slot && !slot.failed) {
this.events.onSfuUpdate?.(metrics);
@@ -409,6 +414,22 @@ export class ViewerSfuRoute {
this.ready(token.revision, "active");
}
+ private handleVideoAvailability(
+ slot: ViewerSubscriberSlot,
+ available: boolean,
+ ): void {
+ if (
+ this.closed ||
+ this.active !== slot ||
+ slot.failed ||
+ !slot.activated ||
+ this.route.getMediaAssignment()?.upstream.kind !== "sfu"
+ ) {
+ return;
+ }
+ this.events.onSfuVideoAvailability?.(available);
+ }
+
private commitMedia(token: RouteOperationToken, acknowledge: boolean): void {
if (!this.route.markMediaActive(token)) {
return;
diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx
index 266470ba..6364336f 100644
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@ -95,7 +95,10 @@ import {
MAX_HOST_MEDIA_CHILDREN,
reconcileBoundedMediaChildren,
} from "../webrtc/media-assignment";
-import { sourceSwitchNotice } from "./host-page-notices";
+import {
+ shouldPauseLocalPreview,
+ sourceSwitchNotice,
+} from "./host-page-notices";
type HostPhase = "idle" | "starting" | "live" | "ended" | "error";
@@ -227,6 +230,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
const [switchingSource, setSwitchingSource] = useState(false);
const [changingQuality, setChangingQuality] = useState(false);
const [sharingPaused, setSharingPaused] = useState(false);
+ const [localPreviewPaused, setLocalPreviewPaused] = useState(false);
const [showConnectionDetails, setShowConnectionDetails] = useState(false);
const [showTopology, setShowTopology] = useState(false);
const [joiningRoom, setJoiningRoom] = useState(false);
@@ -309,7 +313,12 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
if (!video) {
return;
}
- if (document.visibilityState !== "visible" || !document.hasFocus()) {
+ const shouldPause = shouldPauseLocalPreview(
+ document.visibilityState,
+ document.hasFocus(),
+ );
+ setLocalPreviewPaused(shouldPause);
+ if (shouldPause) {
video.pause();
return;
}
@@ -1718,13 +1727,18 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
<MonitorUp size={36} strokeWidth={1.5} aria-hidden="true" />
</div>
)}
- {(phase === "starting" || switchingSource || sharingPaused) && (
+ {(phase === "starting" ||
+ switchingSource ||
+ sharingPaused ||
+ (stream !== null && localPreviewPaused)) && (
<div className="stage-overlay" role="status">
{switchingSource
? "正在切换来源"
: sharingPaused
? "音视频分享已暂停"
- : "正在连接"}
+ : phase === "starting"
+ ? "正在连接"
+ : "本地预览已暂停,分享仍在继续"}
</div>
)}
</div>
@@ -2081,13 +2095,14 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
? peerSnapshots.get(viewer.peerId)
: undefined;
const qualityEvidence = viewerQualityEvidence.get(viewer.peerId);
+ const hasCurrentMediaEvidence =
+ snapshot?.connectionState === "connected" ||
+ (viewer.upstream.kind === "peer" &&
+ qualityEvidence?.parentPeerId === viewer.upstream.peerId);
const viewerState =
- snapshot?.connectionState === "connected" || qualityEvidence
+ hasCurrentMediaEvidence
? "connected"
- : snapshot?.connectionState ??
- (viewer.upstream.kind === "none"
- ? "connecting"
- : "assigned");
+ : (snapshot?.connectionState ?? "routing");
return (
<article className="viewer-item" key={viewer.peerId}>
<div className="viewer-item-heading">
diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsx
index 331b40b5..ee3d3149 100644
--- a/src/client/pages/ViewerPage.tsx
+++ b/src/client/pages/ViewerPage.tsx
@@ -20,6 +20,7 @@ import {
type IceConfig,
type MediaAssignment,
type ParticipantPresenceEntry,
+ type ParticipantRouteAssignment,
type ServerMessage,
} from "../../shared/protocol";
import { AppHeader } from "../components/AppHeader";
@@ -34,6 +35,7 @@ import {
WarningBanner,
} from "../components/StatusBadge";
import { StatsGrid } from "../components/StatsGrid";
+import { viewerRouteEvidence } from "../components/status-badge-model";
import { readDisplayName, saveDisplayName } from "../lib/display-name";
import { clearViewerGrant, getStableClientId } from "../lib/session";
import { SignalingClient } from "../lib/signaling";
@@ -99,6 +101,10 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
const [remoteStream, setRemoteStream] = useState<MediaStream | null>(null);
const [peerSnapshot, setPeerSnapshot] = useState<PeerSnapshot | null>(null);
const [sfuUpstream, setSfuUpstream] = useState<SfuUpstreamState | null>(null);
+ const [assignedRoute, setAssignedRoute] = useState<{
+ revision: number;
+ upstream: ParticipantRouteAssignment["upstream"];
+ } | null>(null);
const [relaySnapshot, setRelaySnapshot] = useState<PeerSnapshot | null>(null);
const [relayChildEvidence, setRelayChildEvidence] =
useState<ViewerQualityEvidence | null>(null);
@@ -139,6 +145,26 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
const signalRef = useRef<SignalingClient | null>(null);
const displayNameRef = useRef(displayName);
const { muted, volumePercent } = playbackVolume;
+ const routePresentation = viewerRouteEvidence(
+ assignedRoute?.upstream ?? null,
+ peerSnapshot,
+ sfuUpstream,
+ );
+ const routeConnectionState =
+ routePresentation.evidence?.connectionState ??
+ (hostOnline ? "routing" : "waiting");
+ const routeMetrics = routePresentation.evidence?.metrics ?? null;
+
+ function acceptAssignedRoute(
+ revision: number,
+ upstream: ParticipantRouteAssignment["upstream"],
+ ): void {
+ setAssignedRoute((current) =>
+ current && revision < current.revision
+ ? current
+ : { revision, upstream },
+ );
+ }
useEffect(() => {
let active = true;
@@ -203,6 +229,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
}
messageAuthority.invalidate();
setSfuStandbyUrl(null);
+ setAssignedRoute(null);
clearViewerSfuRoute();
clearPeerState();
setHostPresence(null);
@@ -215,6 +242,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
if (active) {
messageAuthority.invalidate();
setSfuStandbyUrl(null);
+ setAssignedRoute(null);
clearViewerSfuRoute();
clearPeerState();
setHostPresence(null);
@@ -390,6 +418,16 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
);
}
},
+ onSfuVideoAvailability: (available) => {
+ if (!active || viewerSfuRoute !== route || available) {
+ return;
+ }
+ setSfuUpstream(null);
+ viewerRelay?.stop();
+ setStatusText(
+ currentHostOnline ? "正在恢复连接" : "等待开始分享",
+ );
+ },
onSfuStream: (nextStream, assignment, initialVideoStream) => {
if (!active || viewerSfuRoute !== route) {
return;
@@ -409,9 +447,10 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
relay?.setChild(currentAssignment.childPeerIds[0] ?? null);
relay?.setStream(nextStream);
setRemoteStream(nextStream);
- if (initialVideoStream) {
- setSfuUpstream({ connectionState: "connected", metrics: null });
- }
+ setSfuUpstream(
+ (current) =>
+ current ?? { connectionState: "connected", metrics: null },
+ );
setStatusText("正在播放");
if (initialVideoStream) {
peerRef.current?.dispose();
@@ -621,6 +660,14 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
clearRelayChildEvidence();
}
currentRouteRevision = nextRouteRevision;
+ setAssignedRoute(
+ nextPeerAssisted && "routeAssignment" in message
+ ? {
+ revision: message.routeRevision,
+ upstream: message.routeAssignment.upstream,
+ }
+ : null,
+ );
const relayCapacity = relayCapacityMessageForBrowser(nextPeerAssisted);
if (relayCapacity) {
signal.send(relayCapacity);
@@ -704,6 +751,10 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
selectedEdgeTurn = message;
clearViewerSfuRoute();
clearUpstreamState();
+ acceptAssignedRoute(message.revision, {
+ kind: "peer",
+ peerId: message.parentPeerId,
+ });
currentAssignment = {
parentPeerId: message.parentPeerId,
childPeerIds: currentAssignment.childPeerIds,
@@ -722,7 +773,10 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
}
currentRouteRevision = message.revision;
}
- ensureViewerSfuRoute().accept(message);
+ const result = ensureViewerSfuRoute().accept(message);
+ if (result !== "stale") {
+ acceptAssignedRoute(message.revision, message.assignment.upstream);
+ }
}
return;
}
@@ -814,6 +868,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
}
if (message.type === "sharing-stopped") {
setSfuStandbyUrl(null);
+ setAssignedRoute(null);
currentHostOnline = false;
clearViewerSfuRoute();
clearPeerState();
@@ -834,6 +889,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
setAccessState("denied");
clearViewerGrant(roomId);
setSfuStandbyUrl(null);
+ setAssignedRoute(null);
clearViewerSfuRoute();
clearPeerState();
setHostPresence(null);
@@ -845,6 +901,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
viewerAuthenticated = false;
setAccessState("denied");
setSfuStandbyUrl(null);
+ setAssignedRoute(null);
clearViewerSfuRoute();
clearPeerState();
setHostPresence(null);
@@ -868,6 +925,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
].includes(message.code)
) {
setSfuStandbyUrl(null);
+ setAssignedRoute(null);
clearViewerSfuRoute();
clearPeerState();
setHostPresence(null);
@@ -1099,16 +1157,14 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
</div>
<div className="viewer-badges">
<PeerStatusBadge
- state={
- sfuUpstream
- ? sfuUpstream.connectionState
- : (peerSnapshot?.connectionState ?? "waiting")
- }
+ state={routeConnectionState}
/>
- {showConnectionDetails && (sfuUpstream || peerSnapshot) && (
+ {showConnectionDetails && routePresentation.route && (
<>
- <MediaRouteBadge route={sfuUpstream ? "sfu" : "p2p"} />
- {(sfuUpstream?.metrics ?? peerSnapshot?.metrics)?.path === "relay" && <PathBadge path="relay" />}
+ <MediaRouteBadge route={routePresentation.route} />
+ {routeMetrics?.path === "relay" && (
+ <PathBadge path="relay" />
+ )}
</>
)}
</div>
@@ -1274,7 +1330,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
onChange={setShowConnectionDetails}
/>
- {peerSnapshot?.error && (
+ {routePresentation.evidence === peerSnapshot && peerSnapshot?.error && (
<div className="notice notice-error" role="status">
{peerSnapshot.error}
</div>
@@ -1287,25 +1343,20 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
{qualityLimitation && (
<WarningBanner>{qualityLimitation}</WarningBanner>
)}
- {showConnectionDetails && peerSnapshot && (
+ {showConnectionDetails && routePresentation.route && (
<section className="viewer-stats" aria-labelledby="stats-heading">
<h2 id="stats-heading">连接数据</h2>
<div className="viewer-transport-heading">
- <MediaRouteBadge route="p2p" />
- {peerSnapshot.metrics.path === "relay" && <PathBadge path="relay" />}
- </div>
- <StatsGrid metrics={peerSnapshot.metrics} direction="receive" />
- </section>
- )}
- {showConnectionDetails && sfuUpstream && (
- <section className="viewer-stats" aria-labelledby="sfu-stats-heading">
- <h2 id="sfu-stats-heading">连接数据</h2>
- <div className="viewer-transport-heading">
- <MediaRouteBadge route="sfu" />
- {sfuUpstream.metrics?.path === "relay" && <PathBadge path="relay" />}
+ <MediaRouteBadge route={routePresentation.route} />
+ {routeMetrics?.path === "relay" && (
+ <PathBadge path="relay" />
+ )}
</div>
- {sfuUpstream.metrics && (
- <StatsGrid metrics={sfuUpstream.metrics} direction="receive" />
+ {routeMetrics && (
+ <StatsGrid
+ metrics={routeMetrics}
+ direction="receive"
+ />
)}
</section>
)}
diff --git a/src/client/pages/host-page-notices.ts b/src/client/pages/host-page-notices.ts
index 7cbf5df1..5113dcbb 100644
--- a/src/client/pages/host-page-notices.ts
+++ b/src/client/pages/host-page-notices.ts
@@ -26,3 +26,10 @@ export function sourceSwitchNotice({
? `分享来源已切换,但${peerWarning}`
: "分享来源已切换";
}
+
+export function shouldPauseLocalPreview(
+ visibilityState: DocumentVisibilityState,
+ hasFocus: boolean,
+): boolean {
+ return visibilityState !== "visible" || !hasFocus;
+}
diff --git a/src/client/sfu/subscriber.ts b/src/client/sfu/subscriber.ts
index cb586a72..30bca000 100644
--- a/src/client/sfu/subscriber.ts
+++ b/src/client/sfu/subscriber.ts
@@ -17,6 +17,7 @@ import {
interface SubscriberEvents {
onStream: (stream: MediaStream | null) => void;
+ onVideoAvailability?: (available: boolean) => void;
onStats?: (metrics: ConnectionMetrics) => void;
onState?: (state: "connected" | "reconnecting") => void;
onDisconnected?: () => void;
@@ -25,6 +26,8 @@ interface SubscriberEvents {
interface SubscribedTrack {
sid: string;
track: RemoteTrack;
+ mediaStreamTrack: MediaStreamTrack;
+ onEnded: () => void;
}
type SubscriberState =
@@ -44,6 +47,8 @@ export class SfuSubscriber {
private sdk: LiveKit | null = null;
private video: SubscribedTrack | null = null;
private audio: SubscribedTrack | null = null;
+ private readonly stream = new MediaStream();
+ private streamEmitted = false;
private readonly desiredTrackSids = new Set<string>();
private state: SubscriberState = "idle";
private statsAccumulator: StatsAccumulator = createStatsAccumulator();
@@ -190,6 +195,8 @@ export class SfuSubscriber {
return;
}
this.addTrack(
+ room,
+ generation,
publication.trackSid,
publication.source,
track,
@@ -200,12 +207,12 @@ export class SfuSubscriber {
room.on(
sdk.RoomEvent.TrackUnsubscribed,
(
- _track: RemoteTrack,
+ track: RemoteTrack,
publication: RemoteTrackPublication,
participant: RemoteParticipant,
) => {
if (this.owns(room, generation) && participant.identity === HOST_IDENTITY) {
- this.removeTrack(publication.trackSid);
+ this.removeTrack(publication.trackSid, track.mediaStreamTrack);
}
},
);
@@ -280,34 +287,73 @@ export class SfuSubscriber {
}
private addTrack(
+ room: Room,
+ generation: number,
sid: string,
source: Track.Source,
track: RemoteTrack,
trackType: typeof Track,
): void {
+ let previous: SubscribedTrack | null;
if (source === trackType.Source.ScreenShare) {
- this.video = { sid, track };
+ previous = this.video;
} else if (source === trackType.Source.ScreenShareAudio) {
- this.audio = { sid, track };
+ previous = this.audio;
} else {
return;
}
+ const mediaStreamTrack = track.mediaStreamTrack;
+ if (previous?.sid === sid && previous.mediaStreamTrack === mediaStreamTrack) {
+ return;
+ }
+ const hadVideo = this.video !== null;
+ if (previous) this.detachTrack(previous);
+ const subscribed = {
+ sid,
+ track,
+ mediaStreamTrack,
+ onEnded: () => {
+ if (this.state === "active" && this.owns(room, generation)) {
+ this.removeTrack(sid, mediaStreamTrack);
+ }
+ },
+ };
+ mediaStreamTrack.addEventListener("ended", subscribed.onEnded, { once: true });
+ this.stream.addTrack(mediaStreamTrack);
+ if (source === trackType.Source.ScreenShare) {
+ this.video = subscribed;
+ } else {
+ this.audio = subscribed;
+ }
this.emitStream();
+ if (!hadVideo && this.video) {
+ this.events.onVideoAvailability?.(true);
+ }
if (this.video) {
this.startStats();
}
}
- private removeTrack(sid: string): void {
- if (this.video?.sid === sid) {
+ private removeTrack(sid: string, track?: MediaStreamTrack): void {
+ const previousVideo = this.video;
+ const previousAudio = this.audio;
+ if (this.video?.sid === sid && (!track || this.video.mediaStreamTrack === track)) {
+ this.detachTrack(this.video);
this.video = null;
}
- if (this.audio?.sid === sid) {
+ if (this.audio?.sid === sid && (!track || this.audio.mediaStreamTrack === track)) {
+ this.detachTrack(this.audio);
this.audio = null;
}
+ if (this.video === previousVideo && this.audio === previousAudio) {
+ return;
+ }
this.emitStream();
if (!this.video) {
this.stopStats();
+ if (previousVideo) {
+ this.events.onVideoAvailability?.(false);
+ }
}
}
@@ -315,11 +361,13 @@ export class SfuSubscriber {
if (!this.video) {
return;
}
- const tracks = [this.video.track.mediaStreamTrack];
- if (this.audio) {
- tracks.push(this.audio.track.mediaStreamTrack);
- }
- this.events.onStream(new MediaStream(tracks));
+ this.streamEmitted = true;
+ this.events.onStream(this.stream);
+ }
+
+ private detachTrack(track: SubscribedTrack): void {
+ track.mediaStreamTrack.removeEventListener("ended", track.onEnded);
+ this.stream.removeTrack(track.mediaStreamTrack);
}
private startStats(): void {
@@ -388,11 +436,22 @@ export class SfuSubscriber {
}
private clearMedia(notify: boolean): void {
+ const hadStream = this.streamEmitted;
const hadVideo = this.video !== null;
this.stopStats();
+ if (this.video) {
+ this.detachTrack(this.video);
+ }
+ if (this.audio) {
+ this.detachTrack(this.audio);
+ }
this.video = null;
this.audio = null;
- if (notify && hadVideo) {
+ this.streamEmitted = false;
+ if (hadVideo) {
+ this.events.onVideoAvailability?.(false);
+ }
+ if (notify && hadStream) {
this.events.onStream(null);
}
}
diff --git a/src/server/signaling.ts b/src/server/signaling.ts
index 40a4d30b..8c4c6748 100644
--- a/src/server/signaling.ts
+++ b/src/server/signaling.ts
@@ -1138,12 +1138,6 @@ export class SignalingServer {
);
return;
}
- const target = this.connectedPeer(source.roomId, targetPeerId);
- if (!target) {
- this.sendError(sourceSocket, "PEER_NOT_FOUND", "Target peer is not connected");
- return;
- }
-
const parentToChild = this.hybridMediaRouter!.isActivePeerParentOf(
source.roomId,
source.peerId,
@@ -1154,6 +1148,15 @@ export class SignalingServer {
targetPeerId,
source.peerId,
);
+ const target = this.connectedPeer(source.roomId, targetPeerId);
+ if (!target) {
+ if (parentToChild || childToParent) {
+ return;
+ }
+ this.sendError(sourceSocket, "PEER_NOT_FOUND", "Target peer is not connected");
+ return;
+ }
+
const description =
message.payload.kind === "description"
? message.payload.description
diff --git a/tests/host-page-notice.test.ts b/tests/host-page-notice.test.ts
index a5538f27..7ac6eaf3 100644
--- a/tests/host-page-notice.test.ts
+++ b/tests/host-page-notice.test.ts
@@ -1,6 +1,17 @@
import { describe, expect, it } from "vitest";
-import { sourceSwitchNotice } from "../src/client/pages/host-page-notices.ts";
+import {
+ shouldPauseLocalPreview,
+ sourceSwitchNotice,
+} from "../src/client/pages/host-page-notices.ts";
+
+describe("shouldPauseLocalPreview", () => {
+ it("distinguishes local preview suspension from active focus", () => {
+ expect(shouldPauseLocalPreview("hidden", true)).toBe(true);
+ expect(shouldPauseLocalPreview("visible", false)).toBe(true);
+ expect(shouldPauseLocalPreview("visible", true)).toBe(false);
+ });
+});
describe("sourceSwitchNotice", () => {
it("does not report success when the SFU source replacement failed", () => {
diff --git a/tests/route-transition.test.ts b/tests/route-transition.test.ts
index a12d02a7..082cd456 100644
--- a/tests/route-transition.test.ts
+++ b/tests/route-transition.test.ts
@@ -88,6 +88,7 @@ function createFakePublisher(log: string[], label: string) {
interface FakeSubscriberEvents {
onStream: (stream: MediaStream | null) => void;
+ onVideoAvailability?: (available: boolean) => void;
onStats?: (metrics: ConnectionMetrics) => void;
onState?: (state: "connected" | "reconnecting") => void;
onDisconnected: () => void;
@@ -158,6 +159,9 @@ describe("MediaRouteTransition", () => {
route.accept({ revision: 5, phase: "active", assignment: direct });
+ expect(
+ route.accept({ revision: 4, phase: "active", assignment: sfu }),
+ ).toBe("stale");
expect(route.acceptsConfig(4)).toBe(false);
expect(route.owns(staleToken)).toBe(false);
expect(route.markMediaActive(staleToken)).toBe(false);
@@ -941,7 +945,7 @@ describe("ViewerSfuRoute", () => {
expect(deliveredSignals).toEqual(["early-offer"]);
});
- it("keeps peer media through prepare and switches on the first video stream callback", async () => {
+ it("switches on first SFU video and forwards loss across SFU revision reuse", async () => {
const log: string[] = [];
const messages: ClientMessage[] = [];
const peerAssignments: ParticipantRouteAssignment[] = [];
@@ -952,6 +956,7 @@ describe("ViewerSfuRoute", () => {
}> = [];
const sfuUpdates: Array<ConnectionMetrics | null> = [];
const sfuStates: string[] = [];
+ const videoAvailability: boolean[] = [];
const metrics = {} as ConnectionMetrics;
const subscribers: ReturnType<typeof createFakeSubscriber>[] = [];
const route = new ViewerSfuRoute({
@@ -964,6 +969,8 @@ describe("ViewerSfuRoute", () => {
},
onSfuUpdate: (update) => sfuUpdates.push(update),
onSfuState: (state) => sfuStates.push(state),
+ onSfuVideoAvailability: (available) =>
+ videoAvailability.push(available),
send: (message) => {
messages.push(message);
return true;
@@ -1008,6 +1015,10 @@ describe("ViewerSfuRoute", () => {
revision: 2,
phase: "active",
});
+
+ subscribers[0]?.events.onVideoAvailability?.(false);
+ subscribers[0]?.events.onVideoAvailability?.(true);
+ expect(videoAvailability).toEqual([]);
subscribers[0]?.events.onStats?.(metrics);
subscribers[0]?.events.onState?.("reconnecting");
expect(sfuUpdates).toEqual([]);
@@ -1028,6 +1039,10 @@ describe("ViewerSfuRoute", () => {
phase: "active",
});
+ subscribers[0]?.events.onVideoAvailability?.(false);
+ subscribers[0]?.events.onVideoAvailability?.(true);
+ expect(videoAvailability).toEqual([false, true]);
+
route.accept({
revision: 3,
phase: "active",
@@ -1035,6 +1050,8 @@ describe("ViewerSfuRoute", () => {
});
expect(subscribers).toHaveLength(1);
expect(subscribers[0]?.deactivate).not.toHaveBeenCalled();
+ subscribers[0]?.events.onVideoAvailability?.(false);
+ expect(videoAvailability).toEqual([false, true, false]);
route.accept({
revision: 4,
@@ -1055,8 +1072,10 @@ describe("ViewerSfuRoute", () => {
expect(sfuUpdates).toEqual([metrics, null]);
subscribers[0]?.events.onStats?.(metrics);
subscribers[0]?.events.onState?.("connected");
+ subscribers[0]?.events.onVideoAvailability?.(false);
expect(sfuUpdates).toEqual([metrics, null]);
expect(sfuStates).toEqual(["reconnecting"]);
+ expect(videoAvailability).toEqual([false, true, false]);
});
it("disconnects a subscriber whose connect completes after rollback", async () => {
diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.ts
index c88850ba..05c1b6fc 100644
--- a/tests/server-signal.test.ts
+++ b/tests/server-signal.test.ts
@@ -5503,7 +5503,7 @@ describe("WebSocket signaling", () => {
},
}),
);
- expect((await host.inbox.next("error")).code).toBe("PEER_NOT_FOUND");
+ await host.inbox.expectNone(30);
const reconnectedFirstViewer = await openClient(harness.webSocketUrl);
const reconnectedFirstAuth = peerAssisted(
diff --git a/tests/sfu-client.test.ts b/tests/sfu-client.test.ts
index f8fe4d92..2a108689 100644
--- a/tests/sfu-client.test.ts
+++ b/tests/sfu-client.test.ts
@@ -244,6 +244,15 @@ vi.mock("livekit-client", () => ({
class FakeMediaStream {
constructor(private readonly tracks: MediaStreamTrack[] = []) {}
+ addTrack(track: MediaStreamTrack): void {
+ if (!this.tracks.includes(track)) this.tracks.push(track);
+ }
+
+ removeTrack(track: MediaStreamTrack): void {
+ const index = this.tracks.indexOf(track);
+ if (index >= 0) this.tracks.splice(index, 1);
+ }
+
getTracks(): MediaStreamTrack[] {
return [...this.tracks];
}
@@ -270,7 +279,7 @@ const qualityProfile = {
} as const;
function track(kind: "video" | "audio", id: string): MediaStreamTrack {
- return { id, kind } as MediaStreamTrack;
+ return Object.assign(new EventTarget(), { id, kind }) as MediaStreamTrack;
}
function remoteTrack(
@@ -845,7 +854,8 @@ describe("SfuSubscriber", () => {
hostVideo,
host,
);
- expect(streams.at(-1)?.getTracks()).toEqual([video, audio]);
+ expect(streams.at(-1)?.getVideoTracks()).toEqual([video]);
+ expect(streams.at(-1)?.getAudioTracks()).toEqual([audio]);
expect(subscriber.deactivate()).toBe(true);
expect(hostVideo.setSubscribed).toHaveBeenLastCalledWith(false);
@@ -854,6 +864,92 @@ describe("SfuSubscriber", () => {
expect(room.disconnect).not.toHaveBeenCalled();
});
+ it("keeps one stream while video-first tracks change", async () => {
+ const streams: Array<MediaStream | null> = [];
+ const availability: boolean[] = [];
+ const subscriber = new SfuSubscriber({
+ onStream: (nextStream) => streams.push(nextStream),
+ onVideoAvailability: (available) => availability.push(available),
+ });
+ await subscriber.connect(connection);
+ const room = livekit.state.rooms[0];
+ const host = new livekit.FakeRemoteParticipant("host");
+ const hostVideo = new livekit.FakeRemotePublication(
+ "host-video",
+ Track.Source.ScreenShare,
+ );
+ const hostAudio = new livekit.FakeRemotePublication(
+ "host-audio",
+ Track.Source.ScreenShareAudio,
+ );
+ host.add(hostVideo).add(hostAudio);
+ room.remoteParticipants.set("host", host);
+ expect(subscriber.activate()).toBe(true);
+ const video = track("video", "video-1");
+ room.emit(RoomEvent.TrackSubscribed, remoteTrack(video), hostVideo, host);
+ const stableStream = streams.at(-1);
+ expect(stableStream?.getTracks()).toEqual([video]);
+ expect(availability).toEqual([true]);
+ const audio = track("audio", "audio-1");
+ room.emit(RoomEvent.TrackSubscribed, remoteTrack(audio), hostAudio, host);
+ expect(streams.at(-1)).toBe(stableStream);
+ expect(stableStream?.getAudioTracks()).toEqual([audio]);
+ const callbacksBeforeReplacement = streams.length;
+ const replacement = track("video", "video-2");
+ room.emit(RoomEvent.TrackSubscribed, remoteTrack(replacement), hostVideo, host);
+ expect(streams).toHaveLength(callbacksBeforeReplacement + 1);
+ expect(streams.at(-1)).toBe(stableStream);
+ expect(stableStream?.getVideoTracks()).toEqual([replacement]);
+ video.dispatchEvent(new Event("ended"));
+ expect(stableStream?.getVideoTracks()).toEqual([replacement]);
+ expect(availability).toEqual([true]);
+ replacement.dispatchEvent(new Event("ended"));
+ expect(stableStream?.getVideoTracks()).toEqual([]);
+ expect(streams).toHaveLength(callbacksBeforeReplacement + 1);
+ expect(availability).toEqual([true, false]);
+
+ const recovered = track("video", "video-3");
+ room.emit(RoomEvent.TrackSubscribed, remoteTrack(recovered), hostVideo, host);
+ expect(streams.at(-1)).toBe(stableStream);
+ expect(stableStream?.getVideoTracks()).toEqual([recovered]);
+ expect(availability).toEqual([true, false, true]);
+ });
+
+ it.each(["unsubscribed", "unpublished", "host-disconnected"] as const)(
+ "reports the last video unavailable when it is %s",
+ async (loss) => {
+ const availability: boolean[] = [];
+ const subscriber = new SfuSubscriber({
+ onStream: vi.fn(),
+ onVideoAvailability: (available) => availability.push(available),
+ });
+ await subscriber.connect(connection);
+ const room = livekit.state.rooms[0];
+ const host = new livekit.FakeRemoteParticipant("host");
+ const publication = new livekit.FakeRemotePublication(
+ "host-video",
+ Track.Source.ScreenShare,
+ );
+ host.add(publication);
+ room.remoteParticipants.set("host", host);
+ subscriber.activate();
+ const video = track("video", "video-1");
+ const remoteVideo = remoteTrack(video);
+ room.emit(RoomEvent.TrackSubscribed, remoteVideo, publication, host);
+ availability.length = 0;
+
+ if (loss === "unsubscribed") {
+ room.emit(RoomEvent.TrackUnsubscribed, remoteVideo, publication, host);
+ } else if (loss === "unpublished") {
+ room.emit(RoomEvent.TrackUnpublished, publication, host);
+ } else {
+ room.emit(RoomEvent.ParticipantDisconnected, host);
+ }
+
+ expect(availability).toEqual([false]);
+ },
+ );
+
it("reports merged receiver stats and drops a stale sample", async () => {
const updates: ConnectionMetrics[] = [];
const states: string[] = [];
diff --git a/tests/status-badge.test.ts b/tests/status-badge.test.ts
new file mode 100644
index 00000000..e00e9dd5
--- /dev/null
+++ b/tests/status-badge.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ MEDIA_ROUTE_PRESENTATION,
+ ROUTING_STATUS_PRESENTATION,
+ viewerRouteEvidence,
+} from "../src/client/components/status-badge-model.ts";
+import { EMPTY_METRICS, type PeerSnapshot } from "../src/client/types.ts";
+
+const peerSnapshot: PeerSnapshot = {
+ peerId: "host-peer",
+ connectionId: "connection-1",
+ connectionState: "connected",
+ iceConnectionState: "connected",
+ metrics: { ...EMPTY_METRICS, path: "direct" },
+ error: null,
+};
+
+describe("route status badges", () => {
+ it("uses distinct icon and color language for active P2P and SFU routes", () => {
+ expect(MEDIA_ROUTE_PRESENTATION.p2p).toEqual({
+ tone: "good", label: "P2P", icon: "network",
+ });
+ expect(MEDIA_ROUTE_PRESENTATION.sfu).toEqual({
+ tone: "warning", label: "SFU fallback", icon: "server",
+ });
+ });
+
+ it("shows an assigned route before current media evidence", () => {
+ expect(ROUTING_STATUS_PRESENTATION).toEqual({
+ tone: "neutral", label: "线路分配中",
+ });
+ expect(viewerRouteEvidence({ kind: "sfu" }, null, null)).toEqual({
+ route: "sfu",
+ evidence: null,
+ });
+ });
+
+ it("uses evidence only when it matches the authoritative upstream", () => {
+ expect(viewerRouteEvidence({ kind: "sfu" }, peerSnapshot, null)).toEqual({
+ route: "sfu",
+ evidence: null,
+ });
+ expect(
+ viewerRouteEvidence(
+ { kind: "peer", peerId: "new-parent" },
+ peerSnapshot,
+ null,
+ ),
+ ).toEqual({ route: "p2p", evidence: null });
+ });
+
+ it("exposes TURN only from current assigned-edge evidence", () => {
+ const relayPeer = {
+ ...peerSnapshot,
+ metrics: { ...EMPTY_METRICS, path: "relay" as const },
+ };
+ expect(
+ viewerRouteEvidence(
+ { kind: "peer", peerId: "host-peer" },
+ relayPeer,
+ null,
+ ).evidence?.metrics?.path,
+ ).toBe("relay");
+ });
+});