Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
feat(browser): complete v9 runtime
AAA3536671016ab
diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.mdindex c5c82aa6..f463d091 100644--- a/docs/adr/0005-automatic-hybrid-media-routing.md+++ b/docs/adr/0005-automatic-hybrid-media-routing.md@@ -233,7 +233,13 @@ second mutable graph.- Candidate-list creation, reserve, prepare, the child's first decoded frame,atomic commit, abort, and idempotent release are one bounded child operation.Its one total deadline cleans abandoned reservations and never revokes a- healthy committed edge.+ healthy committed edge. While that one exact candidate is pending, its+ receive-transport owner runs one short-lived, generation-fenced+ `framesDecoded` observer and stops it on proof, promotion, pause, replacement,+ or teardown. A fresh peer connection or fresh SFU activation proves a+ positive cumulative count; a paused prepared SFU route first records a+ Resume-time baseline and requires later progress. This observer adds no+ success/failure deadline and cannot select, reject, or reorder candidates.- A child invalidates only its own exact edge after PeerConnection hard failureor a named non-paused interval without a newly decoded frame. Bitrate, FPS,resolution, blur, and sender statistics remain diagnostics or stock@@ -248,7 +254,8 @@ second mutable graph.- Web clients derive active decoded progress from their existing periodicWebRTC/LiveKit stats sampling. One route-keyed last-progress deadline reportsthe exact edge once; it resets on route/connection change or decoded progress- and is suppressed while authoritatively paused. It adds no polling loop and+ and is suppressed while authoritatively paused. This steady-state sampler is+ separate from the pending candidate's short-lived first-frame observer anddoes not treat bitrate, FPS, track availability, or SFU layer choice as routeauthority.- Authoritative pause aborts the pending child operation, including its currentdiff --git a/docs/research/advanced-peer-distribution.md b/docs/research/advanced-peer-distribution.mdindex ffbc199f..c20d1adc 100644--- a/docs/research/advanced-peer-distribution.md+++ b/docs/research/advanced-peer-distribution.md@@ -1,6 +1,6 @@# Advanced Peer Distribution-- Research date: 2026-08-23+- Research date: 2026-08-24- Scope: current route admission up to twenty trusted viewers, sub-secondinteractive media, endpoint downstream cap `1..3`, and minimal central-servermedia egress; retained advanced-media measurements may cover smaller cohorts@@ -290,8 +290,14 @@ it exposes no topology choices. One reconcile loop handles join, waiting,disconnect, effective-capacity overflow, and failed edges. W3C`framesDecoded` counts successfully decoded video frames, so the first newcandidate frame is the only application readiness event. LiveKit owns SFU-reconnection and stream state; the application adds no network-type poll or-SFU-specific timer.+reconnection and stream state. The one pending candidate's receive-transport+owner therefore uses a short-lived exact-generation stats observer until a+fresh peer/SFU activation has a positive cumulative count; a prepared SFU route+that remained alive while paused instead takes a Resume-time baseline and waits+for later progress. It stops on proof, promotion, pause, replacement, or+teardown, creates no additional deadline, and is distinct from the existing+two-second active-path diagnostic/stall sampler. The application adds no+network-type poll or SFU-specific route timer.The overlap edge is physical: an active Host SFU publication consumes one steadysender slot, and a media-producing provisional peer candidate consumes another.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 002fabe0..42a25573 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"@@ -309,7 +309,7 @@ Host 与 relay Viewer 复用同一个纯 presentation reducer 保存远端 `View| 2 | Host authoritative pause | 保留仍属于 current binding 的最后画面并显示“分享者已暂停”;等待 Host,不显示 retry || 3 | 同一 current media identity 的 `play()` 仅因 `NotAllowedError` 被拒绝 | 不要求先有 frame proof,立即显示唯一主动作 `Play`;点击后播放成功只清除 autoplay block,仍须等 current-generation frame proof 才撤遮罩,其他播放异常使用 typed failure || 4 | current binding 已有 composited frame | 去掉阻塞层;若 signaling 恢复中但媒体仍健康,只显示非阻塞提示且不清空画面 |-| 5 | route terminal failure、Host stopped/offline | 只有仍 current 且已证明的旧画面可保留;否则阻塞。仅 route/controller 明确允许时显示 bounded retry |+| 5 | route terminal failure、Host stopped/offline | Host offline 本身保留仍健康的 current media;exact upstream 硬失败或 route terminal 先使 current frame proof 失效,已证明画面至多降为 retained background 并显示离线或失败。仅 route/controller 明确允许时显示 bounded retry || 6 | SFU capacity wait、peer/SFU prepare、已绑定但未证明首帧、尚无 assignment | 依次显示备用线路等待、建立线路、接收画面或分配线路;无 `Play`、无虚假百分比 |Token-free SFU standby prewarm 保持可选且不创建 participant、publication、subscription 或 route authority。它只提前加载 pinned SDK 并调用官方 `prepareConnection()`;是否缩短公网首帧由阶段时间戳验证,失败时继续既有冷路径。@@ -382,6 +382,8 @@ Token-free SFU standby prewarm 保持可选且不创建 participant、publicatio`reconcileRoom` 在没有 pending operation 时先删除 disconnected childless participant,再找一个 waiting Viewer,或 parent offline/effective-capacity 不足、exact edge 已失效的 child。Candidate planning 拒绝 stale session、不可 source-reachable、成环或没有稳态/overlap/bounded-gap producer slot 的 candidate;server resource admission 在执行当前 cursor 时单独检查。由 failed edge 启动时只为当前 fact version 把 exact candidate 记为已尝试;新的外部事实允许重新评估。对剩余 upstream 依次比较结果深度、剩余 sender slots、稳定加入顺序与 peer identity,先建立其他 direct/STUN,再复用或建立 SFU。Host root退出后新释放的Host槽位因此优先于另一root的更深槽位;健康旧边保持sticky,不做周期性整树平衡。每次只 reserve/prepare cursor 指向的 candidate。WebRTC 负责 ICE/DTLS/consent;exact candidate child 解码出第一帧新画面后发送一次 ready,controller 先同步 commit typed admission,再原子提交 graph。失败释放 candidate、广播严格更新的 rollback revision 并推进 cursor,operation 总 deadline 不重置。耗尽时 hard-invalid、confirmed-departed 或 deterministic overflow edge 被退休并进入明确 waiting;healthy bootstrap edge 保留。无环和房间 admission 已约束最大深度,不增加独立 depth hard cap。+Pending candidate 的 receive-transport owner 只在当前 exact generation 下运行一个短生命周期 `framesDecoded` 观察器。全新 peer/SFU activation 以正累计值证明首帧;暂停期间仍保留的 prepared SFU 在 Resume 时先取 baseline,再要求后续增长。观察器在 proof、promotion、pause、换代或 teardown 时停止,不增加另一 success/failure deadline,也不参与 candidate 选择。Active route 仍由既有两秒 stats sampler维护诊断和 decoded stall,两者不得互相替代。+一个 operation 仍只有一个 timer 和一个总 deadline,但 timer 的下一次 wake 从当前 candidate list 派生。Controller 提取实际存在的 direct 与 SFU 阶段并等分总窗口;显式失败可以在阶段内继续尝试其他 candidate,silent candidate 到达 direct wake boundary 后释放 reservation、广播 rollback 并跳到 SFU。只有 direct 时仍使用完整 deadline;direct+SFU 时各用一半。这样不引入每-candidate magic milliseconds,也不允许一条 silent direct 把 SFU suffix 饿死。首次需要 SFU 但 Host 已满时不建立另一条 rescue 流程。若 affected child 已是 Host direct child,就用它;否则用稳定加入顺序中最新的 connected Host direct child。`reconcileRoom` 为该 child 建立普通 SFU candidate,创建唯一 publication,保持其 subtree,并在该 child 首帧后提交。Host publication 取代释放的 peer slot,随后同一 fixed-point scan 再处理原 waiting/failed child。若旧 Host peer sender 在首帧前仍保留,candidate 必须持有同一 `TransitionOverlapSlot`。没有 overlap 时先 preflight server resource,再退休 exact producer;operation 保持原总 deadline、按新 graph 重算未尝试 suffix,并为被切断的 healthy direct edge追加一个最后 restore tuple。Forward candidate 与 restore 都失败才进入 waiting,不得产生第四份 endpoint copy或另一套恢复状态。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 8bdf775f..e3e59cb8 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"@@ -45,7 +45,7 @@ SFU 的 publication、subscription、server-resource accounting、临时 overlap- 独立房间入口:合法 `/r/{code}#v={grant}` 邀请直接进入对应房间;没有 grant 的 `/join` 或 `/r/{code}` 先显示明确标为“站点访问”的整站验证,再提交 code-only 尝试。`open` 且可准入时直接进入;其余预期拒绝统一为 `ROOM_ACCESS_DENIED`,不得先披露 `password | disabled` policy。有效 site-access cookie 只跳过第一步,两类密码不得复用或互相替代。Host 可设置、轮换或移除房间观看密码;密码接受 1 至 64 个可见 ASCII 字符,异步 scrypt 全局最多执行 2 个、等待 16 个派生。Host 可把房间密码保存在同源本地创建偏好中;它不得进入 URL、cookie、日志或服务端持久存储。未知或过期房间、disabled policy、缺失/错误密码、队满和其他已知有界 admission refusal 都返回相同 code、公开文案和 close 行为。- 统一自动路由:旗舰部署开启 `PEER_ASSISTED_MEDIA` 后,每个房间使用一个服务端 route controller,独占 committed graph、一个 pending child operation 和 event-driven reconcile。运行时只增加一个串行pump、一个operation deadline timer与typed resource lifecycle task,不维护另一份graph。operation持有candidate list/cursor、一个current candidate/资源预留、fact version和一个总deadline。committed graph必须无环、source-reachable,且每名Viewer同时至多一个active upstream。加入、容量变化、节点离开、exact edge `failed/closed`,以及非暂停decoded-frame stall都只唤醒同一个reconcile;其余健康分支保持sticky。候选按当前身份、source reachability、无环、effective capacity与sender transition硬过滤,再按结果深度、剩余sender slots、稳定加入顺序和peer identity排序;因此 Host root退出后新释放的Host槽位比已有root的更深槽位优先,但健康旧边不因周期性平衡而迁移。server admission在执行当前cursor时独立reserve。candidate child首帧ready触发`settleReady(commitAdmissionSync)`,成功prepare `P`提交active `P`;失败释放资源并用同一monotonic allocator广播`R>P` rollback,cursor推进但总deadline不重置。bounded-gap先preflight server resource,再retire producer、按新graph重算未尝试suffix,并在切断healthy edge时追加一个普通restore candidate。relay自身ingress失效时作为child换父并保留subtree;relay disconnect/cap降低让overflow children逐个走同一事务,childless后删除。房间admission和无环约束最大深度,不设独立hard cap。普通peer始终STUN-only,SFU使用独立admission。-- 观看端连接反馈:Viewer 舞台从鉴权到首帧使用一个由现有权威状态推导的稳定阶段反馈,至少区分等待分享、分配线路、建立 P2P、连接备用线路、等待首帧、浏览器阻止自动播放、恢复连接和有界失败。阶段不是进度百分比,也不产生 route authority;只有当前 video element 实际提交首帧后才显示正在播放。播放按钮只在 `play()` 因自动播放策略被拒绝时稳定出现,连接中不得忽隐忽现;明确失败后才提供一次受现有 controller 约束的重试入口。make-before-break 或仍有可见旧帧时保留画面并叠加恢复状态,不为显示反馈主动清空健康 media element。Accepted v9 的服务端补充消息是 strict、current-revision-fenced `route-status` union,且只允许 `waiting/sfu-admission` 与 `failed/route-exhausted` 两种配对;它不携带 raw text、身份、candidate 或 retry hint,prepare/active、access、Host、signal、media 与 autoplay 继续由各自权威输入派生。+- 观看端连接反馈:Viewer 舞台从鉴权到首帧使用一个由现有权威状态推导的稳定阶段反馈,至少区分等待分享、分配线路、建立 P2P、连接备用线路、等待首帧、浏览器阻止自动播放、恢复连接和有界失败。阶段不是进度百分比,也不产生 route authority;只有当前 video element 实际提交首帧后才显示正在播放。播放按钮只在 `play()` 因自动播放策略被拒绝时稳定出现,连接中不得忽隐忽现;明确失败后才提供一次受现有 controller 约束的重试入口。make-before-break 或仍有可见旧帧时保留画面并叠加恢复状态,不为显示反馈主动清空健康 media element。Host 离线本身不使仍健康的媒体失效;exact upstream 硬失败或 route terminal failure 必须使 current frame proof 失效,已证明画面至多降为 retained background,不能遮蔽离线或有界失败。Accepted v9 的服务端补充消息是 strict、current-revision-fenced `route-status` union,且只允许 `waiting/sfu-admission` 与 `failed/route-exhausted` 两种配对;它不携带 raw text、身份、candidate 或 retry hint,prepare/active、access、Host、signal、media 与 autoplay 继续由各自权威输入派生。- 质量控制扩展:推荐档位仍是默认入口且只保留 1080p60/1080p30/720p30 三档,当前页面初始 desired state 选择 1080p30 且不写 `localStorage`;“分享高级设置”允许 480p(854x480)/720p/1080p/1440p 分辨率 ceiling、15 至 60 的整数 FPS ceiling、2 至 12 Mbps 视频码率 ceiling、清晰/平衡/流畅三种偏好、`自动 | H.264 | VP8` 编码选择,以及离散的 `64 kbps 省流 | 128 kbps 音乐默认 | 256 kbps 极高音质` 屏幕音频 sender ceiling;480p 不形成推荐档或固定 FPS/码率组合,初始值采用 `balanced`、`automatic` 与 128 kbps。视频档位和音频档位在直播中显式应用;音频变更只更新固定 Opus 路径的 sender ceiling,不是 codec 切换。所有当前及以后建立的 Web Host、Browser relay 与 SFU sender 都读取最新 desired 档位,并各自在 fresh sender parameters 上应用和读回 endpoint-local applied 值;实际码率仍由浏览器拥塞控制和 stats 决定。Peer 只在唯一明确的 active Opus audio 上做结构化、幂等的 Viewer answer `stereo=1;maxaveragebitrate=256000` 变换,使同一接收上限覆盖三档;非目标形态或 parser/writer 异常必须原样保留浏览器 answer,不得阻断可继续的 mono/video edge。不得用宽泛字符串/正则改 SDP,也不得改写浏览器协商的 FEC。SFU 将三档映射到 pinned SDK 的 music stereo preset 或显式 256 kbps ceiling,统一保留 `forceStereo = true`、`dtx = false` 与 pinned room default `red = true`。不得暴露任意码率、声道、采样率、audio codec、stereo、DTX、RED 或 FEC 控件;256 kbps 只是显式较高上限,不是无损、高保真或最低码率保证。实际质量持续低于所选上限时必须显示可解释的限制原因;在真实拥塞、编码器和接收端证据完成前,不把任一组合称为“完美平衡”。未来 microphone voice 若进入范围,必须是独立 track/处理链,不能把 AEC/降噪/DTX 套到电影或游戏音频。- SFU 质量设置生命周期:直播中修改档位时,浏览器 sender 的 applied readback、LiveKit `LocalVideoTrack` 保存的 degradation preference、track restart options 与 `LocalTrackPublication` 的 republish options 必须作为同一次串行操作更新;任一步失败恢复旧 sender 与旧 SDK 保存态,旧 publication generation 不得回写当前状态。LiveKit full reconnect/republish 不得恢复初次发布的旧偏好。该修复不改变 codec、码率上限、层数或路由,也不能单独解释即时低帧。- 本地预览性能候选:在相同动态场景中 A/B 测量 Host 动态预览开/关的 CPU、GPU、encode time 和实际 FPS。只有稳定收益且捕获、编码和远端画面不受影响时,才允许直播开始后默认显示静止缩略图或隐藏动态预览并提供按需展开;未测前不宣称收益。diff --git a/scripts/peer-assisted-benchmark.ts b/scripts/peer-assisted-benchmark.tsindex 69a63ff8..d1ca4615 100644--- a/scripts/peer-assisted-benchmark.ts+++ b/scripts/peer-assisted-benchmark.ts@@ -9,6 +9,7 @@ import WebSocket from "ws";import {MAX_VIEWERS_PER_ROOM_LIMIT,type ParticipantRouteAssignment,+ type RouteDiagnosticSnapshot,} from "../src/shared/protocol";import {DEFAULT_ENDPOINT_MEDIA_COPY_CAPACITY,@@ -29,12 +30,33 @@ import {type QualityProfileId,type QualitySettings,} from "../src/client/media/quality";+import {+ summarizeRouteTiming,+ type RouteTimingDistribution,+} from "../src/client/lib/diagnostic-export";const PROFILE_SETTINGS = QUALITY_PROFILES;type ProfileId = QualityProfileId;type PageRole = "host" | "viewer";export type BenchmarkCanaryMode = "none" | "viewer-mbb";+const ROUTE_TIMING_KEYS = [+ "queueWaitMs",+ "candidateStartMs",+ "firstDecodedFrameMs",+ "finalMs",+] as const satisfies readonly (keyof RouteDiagnosticSnapshot["children"][number])[];+type RouteTimingKey = (typeof ROUTE_TIMING_KEYS)[number];+export type BenchmarkRouteTimingSamples = {+ [Key in RouteTimingKey]: Array<+ RouteDiagnosticSnapshot["children"][number][Key]+ >;+};+export type BenchmarkRouteTimingSummary = Record<+ RouteTimingKey,+ RouteTimingDistribution+>;+interface ViewerMbbCanaryResult {kind: "viewer-mbb";status: "passed" | "failed";@@ -83,12 +105,6 @@ interface ConnectionObservation {error?: string;}-interface ActiveRouteReadyObservation {- revision: number;- upstreamKind: ParticipantRouteAssignment["upstream"]["kind"];- sfuPublicationGeneration: string | null;-}-interface PageObservation {label: string;role: PageRole;@@ -101,7 +117,6 @@ interface PageObservation {qualitySettings: QualitySettings | null;routeRevision: number | null;routeAssignment: ParticipantRouteAssignment | null;- activeRouteReady: ActiveRouteReadyObservation[];maxActiveOutboundMediaEdges: number;maxAssignedChildren: number;firstDecodedAtEpochMs: number | null;@@ -110,6 +125,33 @@ interface PageObservation {connections: ConnectionObservation[];}+interface FailurePageEvidence {+ label: string;+ role: PageRole;+ authenticated: boolean;+ signalingConnected: boolean;+ routeRevision: number | null;+ upstreamKind: ParticipantRouteAssignment["upstream"]["kind"] | null;+ assignedChildCount: number;+ firstDecoded: boolean;+ firstRendered: boolean;+ connectionCount: number;+ connections: Array<{+ connectionState: string;+ iceConnectionState: string;+ identity: "peer" | "unidentified";+ hasOutboundVideo: boolean;+ hasInboundVideo: boolean;+ decoded: boolean;+ }>;+}++interface BenchmarkFailureEvidence {+ expectedPageCount: number;+ observedPageCount: number;+ pages: FailurePageEvidence[];+}+interface TimedSample {atEpochMs: number;elapsedMs: number;@@ -162,13 +204,16 @@ interface BenchmarkRun {status: "passed" | "failed";checks: RunCheck[];summary: ReturnType<typeof summarizeSamples> | null;+ routeTimingSummary: BenchmarkRouteTimingSummary | null;+ routeTimingStatus: "not-requested" | "captured" | "unavailable";samples: TimedSample[];recovery: RecoveryResult;+ failureEvidence?: BenchmarkFailureEvidence;error?: string;}interface BenchmarkReport {- schemaVersion: 2;+ schemaVersion: 3;startedAt: string;completedAt: string | null;gitCommit: string | null;@@ -217,8 +262,10 @@ interface ManagedProcess {log: BoundedLog;}-const DEFAULT_VIEWER_COUNTS = [1, 3, 5, 8];const MAX_VIEWERS = MAX_VIEWERS_PER_ROOM_LIMIT;+const MAX_FAILURE_CONNECTIONS_PER_PAGE =+ MAX_ENDPOINT_MEDIA_COPY_CAPACITY * 2;+const DEFAULT_VIEWER_COUNTS = [MAX_VIEWERS];const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");class BoundedLog {@@ -327,6 +374,73 @@ class CdpConnection {}}+export function summarizeBenchmarkRouteTiming(+ samples: BenchmarkRouteTimingSamples,+): BenchmarkRouteTimingSummary {+ return Object.fromEntries(+ ROUTE_TIMING_KEYS.map((key) => [+ key,+ summarizeRouteTiming(samples[key]),+ ]),+ ) as BenchmarkRouteTimingSummary;+}++export function buildRouteTimingCheck(+ status: BenchmarkRun["routeTimingStatus"],+ summary: BenchmarkRouteTimingSummary | null,+ expectedChildCount = MAX_VIEWERS,+): RunCheck {+ const completeDistributionCount =+ status === "captured" && summary+ ? ROUTE_TIMING_KEYS.filter((key) => {+ const distribution = summary[key];+ return (+ distribution.sampleCount + distribution.pendingCount ===+ expectedChildCount+ );+ }).length+ : 0;+ return {+ name: "route-timing-current-children",+ passed: completeDistributionCount === ROUTE_TIMING_KEYS.length,+ actual: completeDistributionCount,+ expected:+ `${ROUTE_TIMING_KEYS.length} captured timing distributions with ` ++ `${expectedChildCount} current-child sample or pending values each`,+ };+}++export async function joinViewerBurst<T>(+ viewerCount: number,+ createViewer: (viewerIndex: number) => Promise<T>,+ waitForMedia: (viewer: T, viewerIndex: number) => Promise<unknown>,+): Promise<T[]> {+ const creations = await Promise.allSettled(+ Array.from({ length: viewerCount }, (_, index) =>+ createViewer(index + 1),+ ),+ );+ const creationFailure = creations.find(+ (result): result is PromiseRejectedResult => result.status === "rejected",+ );+ if (creationFailure) {+ throw creationFailure.reason;+ }+ const viewers = creations.map(+ (result) => (result as PromiseFulfilledResult<T>).value,+ );+ const media = await Promise.allSettled(+ viewers.map((viewer, index) => waitForMedia(viewer, index + 1)),+ );+ const mediaFailure = media.find(+ (result): result is PromiseRejectedResult => result.status === "rejected",+ );+ if (mediaFailure) {+ throw mediaFailure.reason;+ }+ return viewers;+}+export function parseViewerCounts(value: string | undefined): number[] {if (!value?.trim()) {return [...DEFAULT_VIEWER_COUNTS];@@ -424,6 +538,11 @@ export function parseBenchmarkConfig();}const canaryMode = parseBenchmarkCanaryMode(environment.BENCHMARK_CANARY);+ if (canaryMode === "viewer-mbb" && !viewerCounts.includes(3)) {+ throw new Error(+ "BENCHMARK_CANARY=viewer-mbb requires a selected viewer count of 3",+ );+ }const recoveryText = environment.BENCHMARK_RECOVERY_VIEWERS?.trim();const recoveryViewerCount = recoveryText ? Number(recoveryText) : null;if (@@ -516,6 +635,59 @@ export function activeVideoEdgeCount(}).length;}+export function sanitizeFailurePageEvidence(+ page: PageObservation,+): FailurePageEvidence {+ const connectionStates = new Set([+ "new",+ "connecting",+ "connected",+ "disconnected",+ "failed",+ "closed",+ ]);+ const iceConnectionStates = new Set([+ "new",+ "checking",+ "connected",+ "completed",+ "disconnected",+ "failed",+ "closed",+ ]);+ return {+ label: page.label,+ role: page.role,+ authenticated: page.peerId !== null,+ signalingConnected: page.signalingConnected,+ routeRevision: page.routeRevision,+ upstreamKind: page.routeAssignment?.upstream.kind ?? null,+ assignedChildCount: page.routeAssignment?.childPeerIds.length ?? 0,+ firstDecoded: page.firstDecodedAtEpochMs !== null,+ firstRendered: page.firstRenderedAtEpochMs !== null,+ connectionCount: page.connections.length,+ connections: page.connections+ .slice(-MAX_FAILURE_CONNECTIONS_PER_PAGE)+ .map((connection) => ({+ connectionState: connectionStates.has(connection.connectionState)+ ? connection.connectionState+ : "unknown",+ iceConnectionState: iceConnectionStates.has(+ connection.iceConnectionState,+ )+ ? connection.iceConnectionState+ : "unknown",+ identity:+ connection.connectionId !== null || connection.remotePeerId !== null+ ? "peer"+ : "unidentified",+ hasOutboundVideo: connection.hasOutboundVideo,+ hasInboundVideo: connection.hasInboundVideo,+ decoded: (connection.receiveTotals?.framesTotal ?? 0) > 0,+ })),+ };+}+function hasAuthoritativeMediaUpstream(page: PageObservation): boolean {return (page.routeRevision !== null &&@@ -541,6 +713,7 @@ function inspectSfuPublication(pages: readonly PageObservation[]) {);const publicationOwners = pages.filter((page) =>+ page.role === "host" &&typeof page.routeAssignment?.sfuPublicationGeneration === "string",);if (sfuViewers.length === 0) {@@ -557,24 +730,36 @@ function inspectSfuPublication(pages: readonly PageObservation[]) {const host = publicationOwners[0]!;const hostRevision = host.routeRevision;const hostGeneration = host.routeAssignment?.sfuPublicationGeneration ?? null;- const hasMatchingActiveReady = (page: PageObservation): boolean =>- page.activeRouteReady.some(- (ready) =>- ready.revision === page.routeRevision &&- ready.upstreamKind === page.routeAssignment?.upstream.kind &&- ready.sfuPublicationGeneration ===- page.routeAssignment?.sfuPublicationGeneration,- );+ const hasExactSfuMedia = (+ page: PageObservation,+ direction: "send" | "receive",+ ): boolean =>+ page.connections.some((connection) => {+ const totals =+ direction === "send"+ ? connection.sendTotals+ : connection.receiveTotals;+ return (+ connection.connectionId === null &&+ connection.remotePeerId === null &&+ connection.connectionState === "connected" &&+ (direction === "send"+ ? connection.hasOutboundVideo+ : connection.hasInboundVideo) &&+ totals !== null &&+ typeof totals.framesTotal === "number" &&+ totals.framesTotal > 0+ );+ });const coherent =- host.role === "host" &&hostRevision !== null &&hostGeneration !== null &&pages.every((page) => page.routeRevision === hostRevision) &&- hasMatchingActiveReady(host) &&+ hasExactSfuMedia(host, "send") &&sfuViewers.every((viewer) =>- viewer.routeAssignment?.sfuPublicationGeneration === null &&- hasMatchingActiveReady(viewer),+ viewer.routeAssignment?.sfuPublicationGeneration === hostGeneration &&+ hasExactSfuMedia(viewer, "receive"),);return { observed: true, rootCount: sfuViewers.length, coherent };}@@ -973,7 +1158,6 @@ export function buildBenchmarkInitScript(options: {qualitySettings: null,routeRevision: null,routeAssignment: null,- activeRouteReady: [],maxActiveOutboundMediaEdges: 0,maxAssignedChildren: 0,firstDecodedAtEpochMs: null,@@ -991,6 +1175,9 @@ export function buildBenchmarkInitScript(options: {let plannedRouteAssignment = null;const canary = { prepareUpdates: 0, activeUpdates: 0, routeFailed: 0 };const nativeSends = new WeakMap();+ const routeTimingKeys = ${JSON.stringify(ROUTE_TIMING_KEYS)};+ let routeDiagnosticRequested = false;+ let routeTimingSamples = null;function isOpaqueId(value) {return typeof value === "string" &&@@ -1017,7 +1204,11 @@ export function buildBenchmarkInitScript(options: {!value.childPeerIds.every(isOpaqueId) ||new Set(value.childPeerIds).size !== value.childPeerIds.length ||(value.sfuPublicationGeneration !== null &&- !isOpaqueId(value.sfuPublicationGeneration))+ !isOpaqueId(value.sfuPublicationGeneration)) ||+ (clonedUpstream.kind === "sfu" &&+ value.sfuPublicationGeneration === null) ||+ (clonedUpstream.kind === "peer" &&+ value.sfuPublicationGeneration !== null)) {return null;}@@ -1103,6 +1294,33 @@ export function buildBenchmarkInitScript(options: {if (descriptions.length > 128) descriptions.shift();}+ function sanitizeRouteTimingSamples(value) {+ const children = value && typeof value === "object" &&+ !Array.isArray(value) && Array.isArray(value.children)+ ? value.children+ : null;+ if (!children || children.length > ${MAX_VIEWERS}) return null;+ const samples = Object.fromEntries(+ routeTimingKeys.map((key) => [key, []]),+ );+ for (const child of children) {+ if (!child || typeof child !== "object" || Array.isArray(child)) {+ return null;+ }+ for (const key of routeTimingKeys) {+ const duration = child[key];+ if (+ duration !== null &&+ (!Number.isSafeInteger(duration) || duration < 0)+ ) {+ return null;+ }+ samples[key].push(duration);+ }+ }+ return samples;+ }+function handleSignalMessage(value, direction, socket) {if (typeof value !== "string") return;let message;@@ -1111,7 +1329,6 @@ export function buildBenchmarkInitScript(options: {if (direction === "out" && message.type === "authenticate") {signalingSocket = socket;peerAssisted = false;- state.activeRouteReady = [];state.role = message.role;state.roomId = message.roomId;state.authenticateSentAtEpochMs = Date.now();@@ -1120,22 +1337,6 @@ export function buildBenchmarkInitScript(options: {return;} else if (direction === "out" && message.type === "set-quality-settings") {state.qualitySettings = message.qualitySettings;- } else if (- direction === "out" &&- message.type === "route-ready" &&- message.phase === "active" &&- peerAssisted &&- Number.isSafeInteger(message.revision) &&- message.revision === state.routeRevision &&- state.routeAssignment- ) {- state.activeRouteReady.push({- revision: message.revision,- upstreamKind: state.routeAssignment.upstream.kind,- sfuPublicationGeneration:- state.routeAssignment.sfuPublicationGeneration,- });- if (state.activeRouteReady.length > 32) state.activeRouteReady.shift();} else if (direction === "out" && message.type === "route-failed") {canary.routeFailed += 1;}@@ -1161,6 +1362,14 @@ export function buildBenchmarkInitScript(options: {acceptRouteUpdate(message.revision, message.phase, message.assignment);} else if (direction === "in" && message.type === "quality-settings") {state.qualitySettings = message.qualitySettings;+ } else if (+ direction === "in" &&+ message.type === "route-diagnostic-snapshot" &&+ state.role === "host" &&+ routeDiagnosticRequested &&+ routeTimingSamples === null+ ) {+ routeTimingSamples = sanitizeRouteTimingSamples(message.snapshot);}if (message.type === "signal") recordDescription(message, direction);}@@ -1198,6 +1407,30 @@ export function buildBenchmarkInitScript(options: {} catch { return false; }}+ function requestRouteDiagnosticSnapshot() {+ if (+ state.role !== "host" ||+ !state.signalingConnected ||+ routeDiagnosticRequested+ ) {+ return false;+ }+ routeDiagnosticRequested = true;+ if (sendCanaryMessage({ type: "request-route-diagnostic" })) {+ return true;+ }+ routeDiagnosticRequested = false;+ return false;+ }++ function routeDiagnosticTimingSamples() {+ return routeTimingSamples+ ? Object.fromEntries(+ routeTimingKeys.map((key) => [key, [...routeTimingSamples[key]]]),+ )+ : null;+ }+const NativePeerConnection = globalThis.RTCPeerConnection;function recordActiveOutboundEdges() {const active = connections.filter(({ connection }) =>@@ -1384,7 +1617,6 @@ export function buildBenchmarkInitScript(options: {return {...state,routeAssignment: cloneRouteAssignment(state.routeAssignment),- activeRouteReady: state.activeRouteReady.map((ready) => ({ ...ready })),};}@@ -1441,7 +1673,7 @@ export function buildBenchmarkInitScript(options: {}Object.defineProperty(globalThis, "__SCREENER_BENCHMARK__", {configurable: false,- value: { sample, progress, snapshot, canarySnapshot, sendViewerQualityEvidence, stop: () => clearInterval(videoObserver) },+ value: { sample, progress, snapshot, canarySnapshot, sendViewerQualityEvidence, requestRouteDiagnosticSnapshot, routeDiagnosticTimingSamples, stop: () => clearInterval(videoObserver) },});})();`;}@@ -1564,7 +1796,7 @@ async function evaluate<T>(return evaluation.result.value as T;}-async function createPage(+export async function createPage(cdp: CdpConnection,url: string,options: Parameters<typeof buildBenchmarkInitScript>[0],@@ -1574,51 +1806,60 @@ async function createPage(url: "about:blank",background: false,});- const attached = await cdp.call<{ sessionId: string }>("Target.attachToTarget", {- targetId: created.targetId,- flatten: true,- });- const page: PageHandle = {- targetId: created.targetId,- sessionId: attached.sessionId,- label: options.label,- };- await Promise.all([- cdp.call("Page.enable", {}, page.sessionId),- cdp.call("Runtime.enable", {}, page.sessionId),- ]);- await cdp.call(- "Page.addScriptToEvaluateOnNewDocument",- { source: buildBenchmarkInitScript(options) },- page.sessionId,- );- const navigation = await cdp.call<{ errorText?: string }>(- "Page.navigate",- { url },- page.sessionId,- );- if (navigation.errorText) {- throw new Error(`Navigation failed: ${navigation.errorText}`);+ try {+ const attached = await cdp.call<{ sessionId: string }>(+ "Target.attachToTarget",+ { targetId: created.targetId, flatten: true },+ );+ const page: PageHandle = {+ targetId: created.targetId,+ sessionId: attached.sessionId,+ label: options.label,+ };+ await Promise.all([+ cdp.call("Page.enable", {}, page.sessionId),+ cdp.call("Runtime.enable", {}, page.sessionId),+ ]);+ await cdp.call(+ "Page.addScriptToEvaluateOnNewDocument",+ { source: buildBenchmarkInitScript(options) },+ page.sessionId,+ );+ const navigation = await cdp.call<{ errorText?: string }>(+ "Page.navigate",+ { url },+ page.sessionId,+ );+ if (navigation.errorText) {+ throw new Error(`Navigation failed: ${navigation.errorText}`);+ }+ await waitForPage(+ cdp,+ page,+ "document.readyState === 'complete' && Boolean(globalThis.__SCREENER_BENCHMARK__)",+ 15_000,+ "page initialization",+ signal,+ );+ return page;+ } catch (error) {+ await closeTarget(cdp, created.targetId);+ throw error;}- await waitForPage(- cdp,- page,- "document.readyState === 'complete' && Boolean(globalThis.__SCREENER_BENCHMARK__)",- 15_000,- "page initialization",- signal,- );- return page;}-async function closePage(cdp: CdpConnection, page: PageHandle): Promise<void> {+async function closeTarget(cdp: CdpConnection, targetId: string): Promise<void> {try {- await cdp.call("Target.closeTarget", { targetId: page.targetId });+ await cdp.call("Target.closeTarget", { targetId });} catch {// Browser shutdown and a prior recovery close make target cleanup idempotent.}}+async function closePage(cdp: CdpConnection, page: PageHandle): Promise<void> {+ await closeTarget(cdp, page.targetId);+}+async function waitForPage(cdp: CdpConnection,page: PageHandle,@@ -1674,6 +1915,35 @@ async function progressSample();}+export function buildBenchmarkFailureEvidence(+ pages: readonly PageObservation[],+ expectedPageCount: number,+): BenchmarkFailureEvidence {+ return {+ expectedPageCount,+ observedPageCount: pages.length,+ pages: pages.map(sanitizeFailurePageEvidence),+ };+}++async function captureFailureEvidence(+ cdp: CdpConnection,+ pages: readonly PageHandle[],+ expectedPageCount: number,+): Promise<BenchmarkFailureEvidence> {+ const observations = await Promise.allSettled(+ pages+ .slice(0, MAX_VIEWERS + 1)+ .map((page) => progressSample(cdp, page)),+ );+ return buildBenchmarkFailureEvidence(+ observations.flatMap((result) =>+ result.status === "fulfilled" ? [result.value] : [],+ ),+ expectedPageCount,+ );+}+async function startHost(cdp: CdpConnection,page: PageHandle,@@ -1745,6 +2015,36 @@ async function waitForViewerMedia(throw new Error(`Timed out waiting for decoded media in ${page.label}`);}+async function requestRouteTimingSummary(+ cdp: CdpConnection,+ hostPage: PageHandle,+ timeoutMs: number,+ signal: AbortSignal,+): Promise<BenchmarkRouteTimingSummary> {+ const requested = await evaluate<boolean>(+ cdp,+ hostPage,+ "globalThis.__SCREENER_BENCHMARK__.requestRouteDiagnosticSnapshot()",+ );+ if (!requested) {+ throw new Error("Host route diagnostic request was unavailable");+ }+ await waitForPage(+ cdp,+ hostPage,+ "globalThis.__SCREENER_BENCHMARK__.routeDiagnosticTimingSamples() !== null",+ timeoutMs,+ "Host route diagnostic snapshot",+ signal,+ );+ const samples = await evaluate<BenchmarkRouteTimingSamples>(+ cdp,+ hostPage,+ "globalThis.__SCREENER_BENCHMARK__.routeDiagnosticTimingSamples()",+ );+ return summarizeBenchmarkRouteTiming(samples);+}+async function samplePages(cdp: CdpConnection,pages: PageHandle[],@@ -2366,6 +2666,8 @@ async function runCase(const pages: PageHandle[] = [];const samples: TimedSample[] = [];let recovery: RecoveryResult = { triggered: false };+ let routeTimingSummary: BenchmarkRouteTimingSummary | null = null;+ let routeTimingStatus: BenchmarkRun["routeTimingStatus"] = "not-requested";try {const capture = PROFILE_SETTINGS[config.profileId];const captureResolution = QUALITY_RESOLUTIONS[capture.resolution];@@ -2399,21 +2701,41 @@ async function runCase(if (!viewerUrl.startsWith(`${baseUrl}/r/${roomId}#v=`)) {throw new Error("Host private Viewer invite was unavailable");}- for (let viewerIndex = 1; viewerIndex <= viewerCount; viewerIndex += 1) {- const viewerPage = await createPage(cdp, viewerUrl, {- ...commonInit,- label: `viewer-${viewerIndex}`,- role: "viewer",- viewerIndex,- clearHostRoom: false,- }, signal);- pages.push(viewerPage);- await waitForViewerMedia(- cdp,- viewerPage,- config.connectionTimeoutMs,- signal,- );+ const viewerPages = await joinViewerBurst(+ viewerCount,+ async (viewerIndex) => {+ const viewerPage = await createPage(cdp, viewerUrl, {+ ...commonInit,+ label: `viewer-${viewerIndex}`,+ role: "viewer",+ viewerIndex,+ clearHostRoom: false,+ }, signal);+ pages.push(viewerPage);+ return viewerPage;+ },+ (viewerPage) =>+ waitForViewerMedia(+ cdp,+ viewerPage,+ config.connectionTimeoutMs,+ signal,+ ),+ );+ pages.splice(1, pages.length - 1, ...viewerPages);+ if (viewerCount === MAX_VIEWERS) {+ routeTimingStatus = "unavailable";+ try {+ routeTimingSummary = await requestRouteTimingSummary(+ cdp,+ hostPage,+ config.connectionTimeoutMs,+ signal,+ );+ routeTimingStatus = "captured";+ } catch {+ routeTimingSummary = null;+ }}if (config.settleMs > 0) {await delay(config.settleMs, signal);@@ -2427,6 +2749,8 @@ async function runCase(status: canaryResult.status,checks: canaryChecks(canaryResult),summary: null,+ routeTimingSummary,+ routeTimingStatus,samples: [],recovery: { triggered: false },};@@ -2451,6 +2775,11 @@ async function runCase(config.profileId,config.expectedEndpointCap,);+ if (viewerCount === MAX_VIEWERS) {+ checks.push(+ buildRouteTimingCheck(routeTimingStatus, routeTimingSummary, viewerCount),+ );+ }if (config.qualityControlSmoke && viewerCount >= 3) {const qualityControl = await runQualityControlSmoke(cdp,@@ -2500,19 +2829,60 @@ async function runCase(status: checks.every((check) => check.passed) ? "passed" : "failed",checks,summary,+ routeTimingSummary,+ routeTimingStatus,samples,recovery,};} catch (error) {+ if (+ viewerCount === MAX_VIEWERS &&+ routeTimingStatus !== "captured" &&+ pages[0]+ ) {+ routeTimingStatus = "unavailable";+ try {+ routeTimingSummary = await requestRouteTimingSummary(+ cdp,+ pages[0],+ config.sampleIntervalMs,+ signal,+ );+ routeTimingStatus = "captured";+ } catch {+ routeTimingSummary = null;+ }+ }+ const failureEvidence = await captureFailureEvidence(+ cdp,+ pages,+ viewerCount + 1,+ ).catch(() => ({+ expectedPageCount: viewerCount + 1,+ observedPageCount: 0,+ pages: [],+ }));return {viewerCount,startedAt: new Date(startedAtMs).toISOString(),completedAt: new Date().toISOString(),status: "failed",- checks: [],+ checks:+ viewerCount === MAX_VIEWERS+ ? [+ buildRouteTimingCheck(+ routeTimingStatus,+ routeTimingSummary,+ viewerCount,+ ),+ ]+ : [],summary: samples.length > 0 ? summarizeSamples(samples, viewerCount) : null,+ routeTimingSummary,+ routeTimingStatus,samples,recovery,+ failureEvidence,error: errorMessage(error),};} finally {@@ -2560,7 +2930,7 @@ export async function main(): Promise<number> {const profile = PROFILE_SETTINGS[config.profileId];const profileResolution = QUALITY_RESOLUTIONS[profile.resolution];const report: BenchmarkReport = {- schemaVersion: 2,+ schemaVersion: 3,startedAt: new Date().toISOString(),completedAt: null,gitCommit: await gitCommit(),@@ -2598,7 +2968,7 @@ export async function main(): Promise<number> {limitations: ["Synthetic canvas motion exercises real Chromium WebRTC but is not a game-capture quality claim.","Headless runs are topology and transport evidence, not representative GPU or power evidence.",- "First-frame and recovery timing fields are diagnostics and never determine this loopback gate's status.",+ "Timing values never determine this loopback gate's status; the exact 20-Viewer route snapshot and four complete current-child distributions are required without a duration threshold.","CDP process CPU covers the isolated Chromium instance, not a specific Host or relay page; identity changes or counter resets make that interval unknown, and multicore utilization may exceed 100%.","CDP SystemInfo exposes no resident-set field, so peakResidentSetBytes is null; GPU, NIC, glass-to-glass latency, generational visual quality, mobile browsers, and SFU require other measurement.","The local runner does not start LiveKit; SFU consistency is reported only when an SFU route is actually observed.",diff --git a/src/client/App.tsx b/src/client/App.tsxindex 755855a2..43fd2f51 100644--- a/src/client/App.tsx+++ b/src/client/App.tsx@@ -27,7 +27,7 @@ function stateFromStatus(status: SiteAccessStatus): AccessState {}function readableError(error: unknown): string {- return error instanceof Error && error.message+ return error instanceof ApiError? error.message: "无法连接站点访问服务,请重试";}@@ -206,7 +206,7 @@ function MalformedRoomRoute() {<main className="access-workspace access-workspace-full"><section className="access-panel"><h1>房间号格式不正确</h1>- <p className="section-meta">房间号必须是 1000..9999 的四位数字</p>+ <p className="section-meta">请输入 1000 至 9999 的四位房间号</p></section></main></div>diff --git a/src/client/components/RoomCodeEntry.tsx b/src/client/components/RoomCodeEntry.tsxindex 42c64936..58b5582c 100644--- a/src/client/components/RoomCodeEntry.tsx+++ b/src/client/components/RoomCodeEntry.tsx@@ -17,7 +17,7 @@ export function RoomCodeEntry({ id, autoFocus = false, inline = false }: RoomCodevent.preventDefault();const route = roomRouteFromInput(roomId);if (!route) {- setError("房间号必须是 1000..9999 的四位数字");+ setError("请输入 1000 至 9999 的四位房间号");return;}window.location.assign(route);@@ -32,12 +32,12 @@ export function RoomCodeEntry({ id, autoFocus = false, inline = false }: RoomCod{!inline && (<div><h1>加入房间</h1>- <p className="section-meta">输入分享者提供的房间码</p>+ <p className="section-meta">输入分享者提供的房间号</p></div>)}<div className="token-field"><label className={inline ? "visually-hidden" : "field-label"} htmlFor={inputId}>- 房间码+ 房间号</label><span className="input-with-icon"><Hash size={16} aria-hidden="true" />@@ -47,7 +47,7 @@ export function RoomCodeEntry({ id, autoFocus = false, inline = false }: RoomCodinputMode="numeric"autoComplete="off"autoFocus={autoFocus}- placeholder={inline ? "房间码" : undefined}+ placeholder={inline ? "房间号" : undefined}aria-invalid={error ? "true" : undefined}onChange={(event) => {setRoomId(event.target.value);diff --git a/src/client/components/StageEntryActions.tsx b/src/client/components/StageEntryActions.tsxindex da1efd7e..a1c58b41 100644--- a/src/client/components/StageEntryActions.tsx+++ b/src/client/components/StageEntryActions.tsx@@ -31,7 +31,7 @@ export function StageEntryActions({<buttonclassName="entry-action"type="button"- title="输入房间码加入观看"+ title="输入房间号加入观看"aria-expanded={joiningRoom}aria-controls="host-room-code-entry"onClick={onJoinToggle}diff --git a/src/client/components/StatsGrid.tsx b/src/client/components/StatsGrid.tsxindex 2bd8c533..43a89b11 100644--- a/src/client/components/StatsGrid.tsx+++ b/src/client/components/StatsGrid.tsx@@ -19,7 +19,7 @@ function qualityReason(value: string | null): string {cpu: "编码受限",other: "其他限制",};- return value ? (labels[value] ?? value) : "未知";+ return value ? (labels[value] ?? "未分类限制") : "未知";}function requestedApplied(diff --git a/src/client/lib/api.ts b/src/client/lib/api.tsindex 9b5e34c8..d46a1ecf 100644--- a/src/client/lib/api.ts+++ b/src/client/lib/api.ts@@ -19,25 +19,6 @@ export class ApiError extends Error {}}-function errorMessage(value: unknown): string | null {- if (!value || typeof value !== "object") {- return null;- }-- const record = value as Record<string, unknown>;- if (typeof record.message === "string") {- return record.message;- }- if (typeof record.error === "string") {- return record.error;- }- if (record.error && typeof record.error === "object") {- const nested = record.error as Record<string, unknown>;- return typeof nested.message === "string" ? nested.message : null;- }- return null;-}-async function responseBody(response: Response): Promise<unknown> {try {return await response.json();@@ -72,7 +53,7 @@ export async function getSiteAccess(): Promise<SiteAccessStatus> {throw new ApiError(response.status === 401? "站点访问已失效,请重新验证"- : (errorMessage(body) ?? `验证失败 (${response.status})`),+ : `站点验证服务暂时不可用 (${response.status})`,response.status,);}@@ -94,7 +75,7 @@ export async function authenticateSiteAccess(throw new ApiError(response.status === 401? "站点口令不正确,请重试"- : (errorMessage(body) ?? `验证失败 (${response.status})`),+ : `站点验证服务暂时不可用 (${response.status})`,response.status,);}@@ -123,7 +104,7 @@ export async function createRoom(throw new ApiError(response.status === 401? "站点访问已失效,请重新验证"- : (errorMessage(body) ?? `建房失败 (${response.status})`),+ : `当前无法创建房间 (${response.status})`,response.status,);}diff --git a/src/client/lib/signaling.ts b/src/client/lib/signaling.tsindex 6218e442..328f5487 100644--- a/src/client/lib/signaling.ts+++ b/src/client/lib/signaling.ts@@ -1,5 +1,6 @@import {decodeServerMessage,+ SIGNAL_CLOSE_CODES,SIGNALING_PROTOCOL,type ClientMessage,type DisplayName,@@ -20,10 +21,15 @@ type SignalingIdentity = WithoutProtocolEnvelope<interface SignalingEvents {onMessage: (message: ServerMessage) => void;onStatus: (status: SignalConnectionState) => void;- onTerminated: (message: string) => void;+ onTerminated: (reason: SignalingTerminationReason) => void;onAccessRequired: () => void;}+export type SignalingTerminationReason =+ | "STALE_CLIENT"+ | "SESSION_REPLACED"+ | "SIGNAL_TERMINATED";+const FATAL_SIGNAL_ERRORS = new Set(["AUTH_REQUIRED","INVALID_TOKEN",@@ -32,11 +38,7 @@ const FATAL_SIGNAL_ERRORS = new Set(["ROOM_FULL","HOST_ALREADY_CONNECTED",]);-const SESSION_REPLACED_CLOSE_CODE = 4001;-const CLIENT_RECONNECT_CLOSE_CODE = 4002;const INVALID_MESSAGE_CLOSE_CODE = 1008;-const VIEWER_ACCESS_REVOKED_CLOSE_CODE = 4004;-const PROTOCOL_REFRESH_MESSAGE = "页面版本已更新,请刷新后重试";const TERMINAL_SEND_TIMEOUT_MS = 15_000;const SIGNALING_CHALLENGE_INTERVAL_MS = 5_000;const SIGNALING_CHALLENGE_TIMEOUT_MS = 2_000;@@ -50,9 +52,10 @@ interface PendingSignalingChallenge {export function shouldReconnectSignaling(code: number): boolean {return (- code !== SESSION_REPLACED_CLOSE_CODE &&+ code !== SIGNAL_CLOSE_CODES.sessionReplaced &&+ code !== SIGNAL_CLOSE_CODES.authenticationFailed &&code !== INVALID_MESSAGE_CLOSE_CODE &&- code !== VIEWER_ACCESS_REVOKED_CLOSE_CODE+ code !== SIGNAL_CLOSE_CODES.viewerAccessRevoked);}@@ -120,7 +123,7 @@ export class SignalingClient {return false;}this.clearSignalingWatchdog();- socket.close(CLIENT_RECONNECT_CLOSE_CODE, "client reconnect");+ socket.close(SIGNAL_CLOSE_CODES.clientReconnect, "client reconnect");return true;}@@ -151,19 +154,70 @@ export class SignalingClient {return this.setDisplayName(displayName);}- setSharingPaused(paused: boolean): boolean {+ pauseSharing(): boolean {if (this.identity.role !== "host") {return false;}- this.identity.sharingPaused = paused;+ this.identity.sharingPaused = true;if (!this.identity.shareGeneration) {return false;}- return this.send({- type: "set-sharing-paused",- shareGeneration: this.identity.shareGeneration,- paused,- });+ try {+ return this.send({+ type: "set-sharing-paused",+ shareGeneration: this.identity.shareGeneration,+ paused: true,+ });+ } catch {+ return false;+ }+ }++ confirmSharingPaused(): void {+ if (this.identity.role === "host") {+ this.identity.sharingPaused = true;+ }+ }++ requestSharingResume(): boolean {+ if (this.identity.role !== "host" || !this.identity.shareGeneration) {+ return false;+ }+ try {+ return this.send({+ type: "request-sharing-resume",+ shareGeneration: this.identity.shareGeneration,+ });+ } catch {+ return false;+ }+ }++ confirmSharingResumed(+ authorization: Extract<+ ServerMessage,+ { type: "sharing-resume-authorized" }+ >,+ ): boolean {+ if (+ this.identity.role !== "host" ||+ !this.identity.shareGeneration ||+ authorization.shareGeneration !== this.identity.shareGeneration+ ) {+ return false;+ }+ let sent = false;+ try {+ sent = this.send({+ type: "sharing-source-enabled",+ shareGeneration: authorization.shareGeneration,+ codecGeneration: authorization.codecGeneration,+ resumeAttempt: authorization.resumeAttempt,+ });+ } catch {+ sent = false;+ }+ return sent;}sendThenStop(message: ClientMessage): void {@@ -291,11 +345,11 @@ export class SignalingClient {this.clearTimers();this.events.onStatus("offline");this.events.onTerminated(- event.reason === "Session replaced"- ? "此页面的会话已被另一个标签页接管"+ event.code === SIGNAL_CLOSE_CODES.sessionReplaced+ ? "SESSION_REPLACED": event.code === INVALID_MESSAGE_CLOSE_CODE- ? PROTOCOL_REFRESH_MESSAGE- : "信令会话已终止,请刷新后重试",+ ? "STALE_CLIENT"+ : "SIGNAL_TERMINATED",);}});@@ -318,7 +372,7 @@ export class SignalingClient {private terminateForProtocolMismatch(): void {this.stop();- this.events.onTerminated(PROTOCOL_REFRESH_MESSAGE);+ this.events.onTerminated("STALE_CLIENT");}private clearAuthenticationTimer(): void {@@ -350,6 +404,13 @@ export class SignalingClient {message.routeAssignment.upstream.kind !== "none";} else if (message.type === "host-status") {this.hostOnline = message.online;+ if (+ this.identity.role === "host" &&+ message.online &&+ !message.paused+ ) {+ this.identity.sharingPaused = false;+ }} else if (message.type === "route-update" &&message.phase === "active" &&@@ -454,7 +515,7 @@ export class SignalingClient {this.clearSignalingWatchdog();this.events.onStatus("reconnecting");if (socket.readyState < WebSocket.CLOSING) {- socket.close(CLIENT_RECONNECT_CLOSE_CODE, "signaling timeout");+ socket.close(SIGNAL_CLOSE_CODES.clientReconnect, "signaling timeout");}this.connect();}diff --git a/src/client/media/codec-proof.ts b/src/client/media/codec-proof.tsnew file mode 100644index 00000000..bcb15166--- /dev/null+++ b/src/client/media/codec-proof.ts@@ -0,0 +1,187 @@+import {+ codecProofEvidenceSchema,+ type ClientMessage,+ type CodecProofBinding,+ type ServerMessage,+} from "../../shared/protocol";+import type { ConnectionMetrics } from "../types";++type ProofRequest = Extract<+ ServerMessage,+ { type: "video-codec-proof-request" }+>;++export interface CodecProofRouteSample {+ routeRevision: number;+ binding: CodecProofBinding;+ metrics: ConnectionMetrics | null;+}++interface DecodedBaseline {+ sampleTimestampMs: number;+ rtpStatsId: string;+ rtpSsrc: number | null;+ rtpMid: string | null;+ rtpRid: string | null;+ trackIdentifier: string | null;+}++interface PendingProof {+ request: ProofRequest;+ baseline: DecodedBaseline | null;+}++export class CodecProofReporter {+ private pending: PendingProof | null = null;++ constructor(+ private readonly send: (message: ClientMessage) => boolean,+ ) {}++ request(request: ProofRequest): boolean {+ this.pending = {+ request,+ baseline: null,+ };+ return true;+ }++ offer(sample: CodecProofRouteSample): void {+ const pending = this.pending;+ if (!pending) return;+ if (!sameRequestRoute(pending.request, sample)) {+ return;+ }+ const current = decodedBaseline(sample.metrics);+ if (!current) return;+ if (!pending.baseline) {+ pending.baseline = current;+ return;+ }+ if (current.sampleTimestampMs <= pending.baseline.sampleTimestampMs) {+ return;+ }+ if (!sameRtpIdentity(pending.baseline, current)) {+ pending.baseline = current;+ return;+ }+ const framesDecodedDelta = sample.metrics?.intervalFramesDecoded;+ if (+ framesDecodedDelta === null ||+ framesDecodedDelta === undefined ||+ !Number.isSafeInteger(framesDecodedDelta) ||+ framesDecodedDelta <= 0+ ) {+ return;+ }+ const evidence = codecProofEvidenceSchema.safeParse({+ baselineSampleTimestampMs: pending.baseline.sampleTimestampMs,+ sampleTimestampMs: current.sampleTimestampMs,+ rtpStatsId: current.rtpStatsId,+ rtpSsrc: current.rtpSsrc,+ rtpMid: current.rtpMid,+ rtpRid: current.rtpRid,+ trackIdentifier: current.trackIdentifier,+ framesDecodedDelta,+ actualCodec: actualVideoCodec(sample.metrics?.codec ?? null),+ });+ if (!evidence.success) return;+ if (+ this.send({+ type: "video-codec-proof",+ shareGeneration: pending.request.shareGeneration,+ generation: pending.request.generation,+ resumeAttempt: pending.request.resumeAttempt,+ routeRevision: pending.request.routeRevision,+ binding: pending.request.binding,+ evidence: evidence.data,+ })+ ) {+ this.pending = null;+ }+ }++ clear(): void {+ this.pending = null;+ }+}++function sameRequestRoute(+ request: ProofRequest,+ sample: CodecProofRouteSample,+): boolean {+ return (+ request.routeRevision === sample.routeRevision &&+ sameProofBinding(request.binding, sample.binding)+ );+}++function sameProofBinding(+ left: CodecProofBinding,+ right: CodecProofBinding,+): boolean {+ return (+ left.kind === right.kind &&+ left.connectionId === right.connectionId &&+ (left.kind === "peer" ||+ (right.kind === "sfu" &&+ left.publicationGeneration === right.publicationGeneration))+ );+}++function decodedBaseline(+ metrics: ConnectionMetrics | null,+): DecodedBaseline | null {+ if (+ !metrics ||+ !Number.isFinite(metrics.sampleTimestampMs) ||+ metrics.sampleTimestampMs === null ||+ metrics.sampleTimestampMs < 0 ||+ !validIdentityString(metrics.rtpStatsId) ||+ !validOptionalIdentityString(metrics.rtpMid) ||+ !validOptionalIdentityString(metrics.rtpRid) ||+ !validOptionalIdentityString(metrics.trackIdentifier) ||+ (metrics.rtpSsrc !== null &&+ (!Number.isSafeInteger(metrics.rtpSsrc) ||+ metrics.rtpSsrc < 0 ||+ metrics.rtpSsrc > 0xffff_ffff))+ ) {+ return null;+ }+ return {+ sampleTimestampMs: metrics.sampleTimestampMs,+ rtpStatsId: metrics.rtpStatsId,+ rtpSsrc: metrics.rtpSsrc,+ rtpMid: metrics.rtpMid,+ rtpRid: metrics.rtpRid,+ trackIdentifier: metrics.trackIdentifier,+ };+}++function validIdentityString(value: string | null): value is string {+ return value !== null && value.length >= 1 && value.length <= 512;+}++function validOptionalIdentityString(value: string | null): boolean {+ return value === null || validIdentityString(value);+}++function sameRtpIdentity(+ left: DecodedBaseline,+ right: DecodedBaseline,+): boolean {+ return (+ left.rtpStatsId === right.rtpStatsId &&+ left.rtpSsrc === right.rtpSsrc &&+ left.rtpMid === right.rtpMid &&+ left.rtpRid === right.rtpRid &&+ left.trackIdentifier === right.trackIdentifier+ );+}++function actualVideoCodec(codec: string | null): "h264" | "vp8" | "other" {+ const normalized = codec?.toLowerCase() ?? "";+ if (normalized.includes("h264")) return "h264";+ if (normalized.includes("vp8")) return "vp8";+ return "other";+}diff --git a/src/client/media/decoded-frame-proof.ts b/src/client/media/decoded-frame-proof.tsnew file mode 100644index 00000000..82a3d5e7--- /dev/null+++ b/src/client/media/decoded-frame-proof.ts@@ -0,0 +1,73 @@+const DECODED_FRAME_PROOF_INTERVAL_MS = 100;++export interface DecodedFrameProofOptions {+ readFramesDecoded: () => Promise<number | null>;+ owns: () => boolean;+ requireProgress?: boolean;+ onProof: () => boolean;+}++export function observeDecodedFrameProof(+ options: DecodedFrameProofOptions,+): () => void {+ let stopped = false;+ let timer: ReturnType<typeof setTimeout> | null = null;+ let baseline: number | null = null;++ const stop = (): void => {+ stopped = true;+ if (timer !== null) {+ globalThis.clearTimeout(timer);+ timer = null;+ }+ };+ const schedule = (): void => {+ if (stopped || !options.owns()) {+ stop();+ return;+ }+ timer = globalThis.setTimeout(() => {+ timer = null;+ void poll();+ }, DECODED_FRAME_PROOF_INTERVAL_MS);+ };+ const poll = async (): Promise<void> => {+ if (stopped || !options.owns()) {+ stop();+ return;+ }+ try {+ const framesDecoded = await options.readFramesDecoded();+ if (stopped || !options.owns()) {+ stop();+ return;+ }+ if (+ framesDecoded !== null &&+ Number.isFinite(framesDecoded) &&+ framesDecoded >= 0+ ) {+ let proved = false;+ if (options.requireProgress) {+ if (baseline === null || framesDecoded < baseline) {+ baseline = framesDecoded;+ } else {+ proved = framesDecoded > baseline;+ }+ } else {+ proved = framesDecoded > 0;+ }+ if (proved && options.onProof()) {+ stop();+ return;+ }+ }+ } catch {+ // Proof sampling is observational; the route owner retains its deadline.+ }+ schedule();+ };++ void poll();+ return stop;+}diff --git a/src/client/media/host-sfu-route.ts b/src/client/media/host-sfu-route.tsindex 235eae09..32235726 100644--- a/src/client/media/host-sfu-route.ts+++ b/src/client/media/host-sfu-route.ts@@ -1,8 +1,12 @@import type {ClientMessage,+ CodecPreparationBinding,+ CodecTransitionGeneration,MediaRoutePhase,ParticipantRouteAssignment,+ PreparedRouteCandidate,ServerMessage,+ VideoCodecPreference,} from "../../shared/protocol";import {SfuPublisher,@@ -15,6 +19,7 @@ import type {QualityProfile,VideoSenderParameterReadback,} from "./quality";+import { qualitySettingsEqual } from "./quality";import {MediaRouteTransition,type RouteOperationToken,@@ -42,6 +47,8 @@ interface HostPublisherSlot {connected: boolean;active: boolean;failed: boolean;+ codecTransition: PreparedRouteCandidate["codecTransition"];+ codecPreparationReported: boolean;}export interface HostSfuPublisherSnapshot {@@ -50,12 +57,22 @@ export interface HostSfuPublisherSnapshot {audioSenderParameters: AudioSenderParameterReadback | null;}+export interface HostSfuCodecPreparationResult {+ generation: CodecTransitionGeneration;+ videoCodec: VideoCodecPreference;+ binding: Extract<CodecPreparationBinding, { kind: "sfu" }>;+ accepted: boolean;+}+interface HostSfuRouteEvents {getStream: () => MediaStream | null;getProfile: () => QualityProfile;reconcileChildren: (childPeerIds: string[]) => void;send: (message: ClientMessage) => boolean;onPublisherUpdate?: (snapshot: HostSfuPublisherSnapshot | null) => void;+ onCodecPublisherPrepared?: (+ result: HostSfuCodecPreparationResult,+ ) => void;createPublisher?: (onDisconnected: () => void,onStats: (metrics: ConnectionMetrics | null) => void,@@ -85,7 +102,21 @@ export class HostSfuRoute {if (result === "stale") {return result;}- if (this.paused) {+ const pausedActiveReconciliation =+ this.paused && update.phase === "active" && result !== "duplicate";+ const retiredActive = pausedActiveReconciliation+ ? this.detachUnreferencedActive(+ update.assignment.sfuPublicationGeneration,+ )+ : null;+ if (pausedActiveReconciliation) {+ this.events.reconcileChildren(update.assignment.childPeerIds);+ }+ if (+ this.paused &&+ update.phase === "prepare" &&+ !isPausedCodecSfuCandidate(update)+ ) {this.clearPending();return result;}@@ -112,8 +143,13 @@ export class HostSfuRoute {}const token = this.route.token();+ if (retiredActive) {+ void this.queueTransition(() =>+ this.disconnectRetiredPublisher(retiredActive),+ );+ }if (token && !this.resyncing) {- void this.queueActivation(token);+ void this.queueActivation(token, this.paused);}return result;}@@ -180,7 +216,11 @@ export class HostSfuRoute {async acceptConfig(message: Extract<ServerMessage, { type: "sfu-config" }>,): Promise<void> {- if (this.closed || this.paused || !this.route.acceptsConfig(message.revision)) {+ if (+ this.closed ||+ !this.route.acceptsConfig(message.revision) ||+ (this.paused && !this.hasPausedCodecSfuCandidate())+ ) {return;}const token = this.route.token();@@ -188,6 +228,8 @@ export class HostSfuRoute {const phase = this.route.getPhase();const candidate = this.route.getPreparedCandidate();const publicationGeneration = assignment?.sfuPublicationGeneration;+ const codecTransition =+ phase === "prepare" ? candidate?.codecTransition ?? null : null;if (!token ||!phase ||@@ -197,6 +239,18 @@ export class HostSfuRoute {) {return;}+ if (+ codecTransition !== null &&+ this.active?.publicationGeneration === publicationGeneration+ ) {+ this.events.onCodecPublisherPrepared?.({+ ...codecTransition,+ binding: { kind: "sfu", publicationGeneration },+ accepted: false,+ });+ this.routeFailed(message.revision, "prepare", null);+ return;+ }if (this.active?.publicationGeneration === publicationGeneration) {this.active.revision = message.revision;if (phase === "active" && this.active.active) {@@ -230,6 +284,8 @@ export class HostSfuRoute {connected: false,active: false,failed: false,+ codecTransition: codecTransition ? { ...codecTransition } : null,+ codecPreparationReported: false,};this.pending = slot;try {@@ -249,7 +305,18 @@ export class HostSfuRoute {return;}slot.connected = true;- if (!(await this.preparePublisher(slot))) {+ let prepared = false;+ await this.queueTransition(async () => {+ if (this.pending !== slot || !this.route.owns(token)) {+ if (this.pending === slot) {+ this.pending = null;+ }+ await disconnectPublisher(publisher);+ return;+ }+ prepared = await this.preparePublisher(slot);+ });+ if (!prepared) {return;}if (phase === "active" && !this.resyncing) {@@ -263,7 +330,7 @@ export class HostSfuRoute {setPaused(paused: boolean): void {this.paused = paused;- if (paused) {+ if (paused && !this.hasPausedCodecSfuCandidate()) {this.clearPending();}}@@ -274,7 +341,9 @@ export class HostSfuRoute {? Promise.resolve(true): Promise.all(slots.map((slot) =>- slot.publisher.updateProfile(profile).catch(() => false),+ slot.publisher+ .updateProfile(this.profileForSlot(slot, profile))+ .catch(() => false),),).then((results) => results.every(Boolean));}@@ -352,13 +421,26 @@ export class HostSfuRoute {});}- private queueActivation(token: RouteOperationToken): Promise<void> {+ private queueActivation(+ token: RouteOperationToken,+ retireUnreferenced = false,+ ): Promise<void> {return this.queueTransition(async () => {if (this.closed || this.resyncing || !this.route.owns(token, "active")) {return;}const assignment = this.route.getActiveAssignment();if (assignment) {+ if (+ retireUnreferenced &&+ this.active?.publicationGeneration !==+ assignment.sfuPublicationGeneration+ ) {+ await this.retireActive();+ if (!this.route.owns(token, "active")) {+ return;+ }+ }await this.activate(assignment, token);}});@@ -434,7 +516,7 @@ export class HostSfuRoute {private async preparePublisher(slot: HostPublisherSlot): Promise<boolean> {const stream = this.events.getStream();- const profile = this.events.getProfile();+ const profile = this.profileForSlot(slot, this.events.getProfile());if (!stream) {this.handleFailure(slot);return false;@@ -460,16 +542,20 @@ export class HostSfuRoute {await disconnectPublisher(slot.publisher);return false;}- const latestProfile = this.events.getProfile();+ const latestProfile = this.profileForSlot(slot, this.events.getProfile());if (- latestProfile !== profile &&+ !qualitySettingsEqual(latestProfile, profile) &&!(await slot.publisher.updateProfile(latestProfile))) {this.handleFailure(slot);await disconnectPublisher(slot.publisher);return false;}- return this.pending === slot && this.ownsPublisherSlot(slot);+ const prepared = this.pending === slot && this.ownsPublisherSlot(slot);+ if (prepared) {+ this.reportCodecPreparation(slot, true);+ }+ return prepared;} catch {this.handleFailure(slot);await disconnectPublisher(slot.publisher);@@ -485,6 +571,42 @@ export class HostSfuRoute {);}+ private hasPausedCodecSfuCandidate(): boolean {+ const candidate = this.route.getPreparedCandidate();+ return (+ this.route.getPhase() === "prepare" &&+ candidate?.transport === "sfu" &&+ candidate.codecTransition !== null+ );+ }++ private profileForSlot(+ slot: HostPublisherSlot,+ profile: QualityProfile,+ ): QualityProfile {+ return slot.codecTransition+ ? { ...profile, videoCodec: slot.codecTransition.videoCodec }+ : profile;+ }++ private reportCodecPreparation(+ slot: HostPublisherSlot,+ accepted: boolean,+ ): void {+ if (!slot.codecTransition || slot.codecPreparationReported) {+ return;+ }+ slot.codecPreparationReported = true;+ this.events.onCodecPublisherPrepared?.({+ ...slot.codecTransition,+ binding: {+ kind: "sfu",+ publicationGeneration: slot.publicationGeneration,+ },+ accepted,+ });+ }+private currentActiveToken(slot: HostPublisherSlot,): RouteOperationToken | null {@@ -525,6 +647,27 @@ export class HostSfuRoute {const active = this.active;this.events.onPublisherUpdate?.(null);this.active = null;+ await this.disconnectRetiredPublisher(active);+ }++ private detachUnreferencedActive(+ publicationGeneration: string | null,+ ): HostPublisherSlot | null {+ if (+ !this.active ||+ this.active.publicationGeneration === publicationGeneration+ ) {+ return null;+ }+ const active = this.active;+ this.active = null;+ this.events.onPublisherUpdate?.(null);+ return active;+ }++ private async disconnectRetiredPublisher(+ active: HostPublisherSlot,+ ): Promise<void> {if (active.active) {await active.publisher.deactivate().catch(() => false);}@@ -536,9 +679,19 @@ export class HostSfuRoute {return;}const wasActive = this.active === slot;+ const wasPending = this.pending === slot;+ const assignment = this.route.getPlannedAssignment();+ const revision = this.route.getRevision();+ const phase = this.route.getPhase();+ const matchesPlannedRoute =+ revision === slot.revision &&+ assignment?.sfuPublicationGeneration === slot.publicationGeneration;+ if (!wasActive && !wasPending && !matchesPlannedRoute) {+ return;+ }this.lastFailureStage = slot.publisher.getFailureStage?.() ?? "transport";slot.failed = true;- if (this.pending === slot) {+ if (wasPending) {this.pending = null;}if (wasActive) {@@ -546,12 +699,9 @@ export class HostSfuRoute {this.active = null;}- const assignment = this.route.getPlannedAssignment();- const revision = this.route.getRevision();- const phase = this.route.getPhase();- const matchesPlannedRoute =- revision === slot.revision &&- assignment?.sfuPublicationGeneration === slot.publicationGeneration;+ if (matchesPlannedRoute) {+ this.reportCodecPreparation(slot, false);+ }if (revision === null || phase === null) {return;}@@ -619,6 +769,14 @@ export class HostSfuRoute {}}+function isPausedCodecSfuCandidate(update: RouteUpdateInput): boolean {+ return (+ update.phase === "prepare" &&+ update.candidate.transport === "sfu" &&+ update.candidate.codecTransition !== null+ );+}+async function disconnectPublisher(publisher: HostPublisherTransport,): Promise<void> {diff --git a/src/client/media/host-source-authority.ts b/src/client/media/host-source-authority.tsnew file mode 100644index 00000000..76acc494--- /dev/null+++ b/src/client/media/host-source-authority.ts@@ -0,0 +1,53 @@+import type {+ CodecTransitionGeneration,+ ResumeAttempt,+ ServerMessage,+} from "../../shared/protocol";+import { setMediaPaused } from "./quality";++type PauseSharingSourceMessage = Extract<+ ServerMessage,+ { type: "pause-sharing-source" }+>;++interface AuthoritativeHostPauseInput {+ message: PauseSharingSourceMessage;+ currentShareGeneration: string | null;+ activeResumeAttempt: ResumeAttempt | null;+ activeCodecGeneration: CodecTransitionGeneration | null;+ stream: MediaStream | null;+ pauseSfuRoute: () => void;+ markHostPaused: () => void;+}++export interface AuthoritativeHostPauseResult {+ localCodecContextMatches: boolean;+}++export function applyAuthoritativeHostPause({+ message,+ currentShareGeneration,+ activeResumeAttempt,+ activeCodecGeneration,+ stream,+ pauseSfuRoute,+ markHostPaused,+}: AuthoritativeHostPauseInput): AuthoritativeHostPauseResult | null {+ if (message.shareGeneration !== currentShareGeneration) {+ return null;+ }++ if (stream) {+ setMediaPaused(stream, true);+ }+ pauseSfuRoute();+ markHostPaused();++ return {+ localCodecContextMatches:+ (message.resumeAttempt === null ||+ message.resumeAttempt === activeResumeAttempt) &&+ (message.codecGeneration === null ||+ message.codecGeneration === activeCodecGeneration),+ };+}diff --git a/src/client/media/route-transition.ts b/src/client/media/route-transition.tsindex 27e33180..d45aa38d 100644--- a/src/client/media/route-transition.ts+++ b/src/client/media/route-transition.ts@@ -70,7 +70,7 @@ export class MediaRouteTransition {this.phase = update.phase;this.plannedAssignment = cloneAssignment(update.assignment);this.preparedCandidate =- update.phase === "prepare" ? { ...update.candidate } : null;+ update.phase === "prepare" ? cloneCandidate(update.candidate) : null;if (update.phase === "active") {this.activeAssignment = cloneAssignment(update.assignment);}@@ -128,7 +128,9 @@ export class MediaRouteTransition {}getPreparedCandidate(): PreparedRouteCandidate | null {- return this.preparedCandidate ? { ...this.preparedCandidate } : null;+ return this.preparedCandidate+ ? cloneCandidate(this.preparedCandidate)+ : null;}reset(): void {@@ -149,10 +151,36 @@ function sameCandidate(return (left?.childPeerId === right.childPeerId &&left.connectionId === right.connectionId &&- left.transport === right.transport+ left.transport === right.transport &&+ sameCodecTransition(left.codecTransition, right.codecTransition)+ );+}++function sameCodecTransition(+ left: PreparedRouteCandidate["codecTransition"] | undefined,+ right: PreparedRouteCandidate["codecTransition"],+): boolean {+ return (+ left === right ||+ (left !== null &&+ left !== undefined &&+ right !== null &&+ left.generation === right.generation &&+ left.videoCodec === right.videoCodec));}+function cloneCandidate(+ candidate: PreparedRouteCandidate,+): PreparedRouteCandidate {+ return {+ ...candidate,+ codecTransition: candidate.codecTransition+ ? { ...candidate.codecTransition }+ : null,+ };+}+export function reportActivePeerRouteFailure(route: MediaRouteTransition,parentPeerId: string,diff --git a/src/client/media/viewer-presentation.ts b/src/client/media/viewer-presentation.tsindex 86bbce5a..b38dee54 100644--- a/src/client/media/viewer-presentation.ts+++ b/src/client/media/viewer-presentation.ts@@ -118,6 +118,7 @@ export type ViewerPresentationAction =| { type: "autoplay-blocked"; generation: number; revision: number }| { type: "autoplay-cleared"; generation: number }| { type: "playback-failed"; generation: number; revision: number }+ | { type: "media-invalidated"; revision: number }| { type: "media-cleared" }| {type: "failure";@@ -211,11 +212,15 @@ export function reduceViewerPresentation(state.routeStatus.state === "waiting"? state.routeStatus: null,+ autoplayBlockedGeneration: revisionChanged+ ? null+ : state.autoplayBlockedGeneration,retainedFrame:state.retainedFrame || (revisionChanged && currentFrame),failure:revisionChanged &&(state.failure === "ROUTE_EXHAUSTED" ||+ state.failure === "AUTOPLAY_BLOCKED" ||state.failure === "PLAYBACK_FAILED")? null: state.failure,@@ -226,6 +231,8 @@ export function reduceViewerPresentation(return state;}const revisionChanged = state.revision !== action.revision;+ const terminal = action.state === "failed";+ const currentFrame = hasCurrentFrame(state);return {...state,revision: action.revision,@@ -233,12 +240,20 @@ export function reduceViewerPresentation(revision: action.revision,state: action.state,},+ media: terminal ? null : state.media,+ autoplayBlockedGeneration: revisionChanged || terminal+ ? null+ : state.autoplayBlockedGeneration,retainedFrame:- state.retainedFrame || (revisionChanged && hasCurrentFrame(state)),+ state.retainedFrame ||+ ((revisionChanged || terminal) && currentFrame),failure:action.state === "failed"? "ROUTE_EXHAUSTED"- : state.failure === "ROUTE_EXHAUSTED"+ : revisionChanged &&+ (state.failure === "ROUTE_EXHAUSTED" ||+ state.failure === "AUTOPLAY_BLOCKED" ||+ state.failure === "PLAYBACK_FAILED")? null: state.failure,};@@ -297,7 +312,8 @@ export function reduceViewerPresentation(if (!state.media ||state.media.generation !== action.generation ||- state.media.revision !== action.revision+ state.media.revision !== action.revision ||+ state.revision !== action.revision) {return state;}@@ -320,11 +336,22 @@ export function reduceViewerPresentation(if (!state.media ||state.media.generation !== action.generation ||- state.media.revision !== action.revision+ state.media.revision !== action.revision ||+ state.revision !== action.revision) {return state;}return { ...state, failure: "PLAYBACK_FAILED" };+ case "media-invalidated":+ if (state.revision !== action.revision) {+ return state;+ }+ return {+ ...state,+ media: null,+ retainedFrame: state.retainedFrame || hasCurrentFrame(state),+ autoplayBlockedGeneration: null,+ };case "media-cleared":return {...state,@@ -340,12 +367,19 @@ export function reduceViewerPresentation() {return state;}+ const terminalRoute = action.failure === "ROUTE_EXHAUSTED";return {...state,revision:action.revision === undefined? state.revision: Math.max(state.revision ?? 0, action.revision),+ media: terminalRoute ? null : state.media,+ retainedFrame:+ state.retainedFrame || (terminalRoute && hasCurrentFrame(state)),+ autoplayBlockedGeneration: terminalRoute+ ? null+ : state.autoplayBlockedGeneration,failure: action.failure,};case "retry-available":@@ -434,6 +468,7 @@ export function deriveViewerPresentation(if (state.media &&+ state.media.revision === state.revision &&state.autoplayBlockedGeneration === state.media.generation) {return {diff --git a/src/client/media/viewer-sfu-route.ts b/src/client/media/viewer-sfu-route.tsindex 18581711..f82762c1 100644--- a/src/client/media/viewer-sfu-route.ts+++ b/src/client/media/viewer-sfu-route.ts@@ -20,11 +20,14 @@ interface ViewerSubscriberTransport {connect(config: SfuConnectionConfig): Promise<boolean>;activate(): boolean;deactivate(): boolean;+ armDecodedFrameProof(requireProgress?: boolean): void;+ stopDecodedFrameProof(): void;disconnect(): Promise<void>;}interface ViewerSubscriberSlot {revision: number;+ publicationGeneration: string;subscriber: ViewerSubscriberTransport;connected: boolean;activated: boolean;@@ -75,6 +78,7 @@ interface ViewerSfuRouteEvents {onStream: (stream: MediaStream | null) => void;onVideoAvailability: (available: boolean) => void;onStats: (metrics: ConnectionMetrics) => void;+ onFirstDecodedFrame: () => boolean;onState: (state: "connected" | "reconnecting") => void;onDisconnected: () => void;},@@ -107,13 +111,30 @@ export class ViewerSfuRoute {if (result === "stale") {return result;}- if (this.paused) {+ const pausedActiveReconciliation =+ this.paused && update.phase === "active" && result !== "duplicate";+ const retiredActive = pausedActiveReconciliation+ ? this.detachUnreferencedActive(update.assignment)+ : null;+ if (pausedActiveReconciliation) {+ this.activateChildren(update.assignment.childPeerIds, update.revision);+ }+ if (+ this.paused &&+ update.phase === "prepare" &&+ !isPausedCodecSfuCandidate(update)+ ) {this.discardPending();return result;}if (result === "duplicate") {return result;}+ if (retiredActive) {+ void this.queueTransition(() =>+ this.disconnectRetiredSubscriber(retiredActive),+ );+ }if (previousRevision !== update.revision) {this.recovery = null;if (@@ -177,14 +198,26 @@ export class ViewerSfuRoute {if (this.resyncing) {return result;}- void this.queueActiveRoute(token, acknowledge);+ void this.queueActiveRoute(token, acknowledge, this.paused);return result;}setPaused(paused: boolean): void {+ const wasPaused = this.paused;this.paused = paused;- if (paused) {+ if (paused && !this.hasPausedCodecSfuCandidate()) {this.discardPending();+ } else if (paused && this.pending) {+ this.pending.decodedFrame = false;+ this.pending.readySent = false;+ this.pending.subscriber.stopDecodedFrameProof();+ } else if (+ wasPaused &&+ !paused &&+ this.pending &&+ this.hasPausedCodecSfuCandidate()+ ) {+ this.pending.subscriber.armDecodedFrameProof(true);}}@@ -258,17 +291,23 @@ export class ViewerSfuRoute {async acceptConfig(message: Extract<ServerMessage, { type: "sfu-config" }>,): Promise<void> {- if (this.closed || this.paused || !this.route.acceptsConfig(message.revision)) {+ if (+ this.closed ||+ !this.route.acceptsConfig(message.revision) ||+ (this.paused && !this.hasPausedCodecSfuCandidate())+ ) {return;}const token = this.route.token();const assignment = this.route.getPlannedAssignment();const phase = this.route.getPhase();const candidate = this.route.getPreparedCandidate();+ const publicationGeneration = assignment?.sfuPublicationGeneration;if (!token ||!phase ||assignment?.upstream.kind !== "sfu" ||+ !publicationGeneration ||(phase === "prepare" &&(candidate?.childPeerId !== this.viewerPeerId ||candidate.transport !== "sfu"))@@ -276,10 +315,21 @@ export class ViewerSfuRoute {return;}- if (this.active?.revision === message.revision && this.active.activated) {+ if (+ phase === "active" &&+ this.active?.publicationGeneration === publicationGeneration &&+ this.active.activated+ ) {+ if (phase === "active") {+ await this.queueActiveRoute(token, true, this.paused);+ }return;}- if (this.pending?.revision === message.revision && !this.pending.failed) {+ if (+ this.pending?.revision === message.revision &&+ this.pending.publicationGeneration === publicationGeneration &&+ !this.pending.failed+ ) {return;}@@ -295,27 +345,11 @@ export class ViewerSfuRoute {this.handleVideoAvailability(slot, available);},onStats: (metrics: ConnectionMetrics) => {- if (this.pending === slot && !slot.failed) {- if ((metrics.intervalFramesDecoded ?? 0) > 0) {- slot.decodedFrame = true;- if (- phase === "prepare" &&- this.route.getRevision() === slot.revision &&- this.route.getPhase() === "prepare" &&- !slot.readySent- ) {- slot.readySent = this.events.send({- type: "route-ready",- revision: slot.revision,- phase: "prepare",- });- }- void this.queueTransition(() => this.promotePendingSfu(slot));- }- } else if (this.active === slot && !slot.failed) {+ if (this.active === slot && !slot.failed) {this.events.onSfuUpdate?.(metrics, slot.revision);}},+ onFirstDecodedFrame: () => this.handlePendingDecodedFrame(slot),onState: (state: "connected" | "reconnecting") => {if (this.active === slot && !slot.failed) {this.events.onSfuState?.(state, slot.revision);@@ -328,6 +362,7 @@ export class ViewerSfuRoute {new SfuSubscriber(subscriberEvents);slot = {revision: message.revision,+ publicationGeneration,subscriber,connected: false,activated: false,@@ -362,6 +397,9 @@ export class ViewerSfuRoute {return;}slot.activated = true;+ if (!this.paused) {+ subscriber.armDecodedFrameProof();+ }if (phase === "active" && !this.resyncing) {await this.queueActiveRoute(token, true);}@@ -423,9 +461,20 @@ export class ViewerSfuRoute {);}+ private hasPausedCodecSfuCandidate(): boolean {+ const candidate = this.route.getPreparedCandidate();+ return (+ this.route.getPhase() === "prepare" &&+ candidate?.childPeerId === this.viewerPeerId &&+ candidate.transport === "sfu" &&+ candidate.codecTransition !== null+ );+ }+private queueActiveRoute(token: RouteOperationToken,acknowledge: boolean,+ retireUnreferenced = false,): Promise<void> {return this.queueTransition(async () => {if (this.closed || this.resyncing || !this.route.owns(token, "active")) {@@ -435,11 +484,26 @@ export class ViewerSfuRoute {if (!assignment) {return;}+ const assignedPublicationGeneration =+ assignment.upstream.kind === "sfu"+ ? assignment.sfuPublicationGeneration+ : null;+ if (+ retireUnreferenced &&+ this.active?.publicationGeneration !== assignedPublicationGeneration+ ) {+ await this.retireActive();+ if (!this.route.owns(token, "active")) {+ return;+ }+ }if (assignment.upstream.kind === "sfu") {this.activateChildren(assignment.childPeerIds, token.revision);const mediaAssignment = this.route.getMediaAssignment();if (mediaAssignment?.upstream.kind === "sfu" &&+ this.active?.publicationGeneration ===+ assignment.sfuPublicationGeneration &&this.active?.activated &&this.pending?.revision !== token.revision) {@@ -497,11 +561,22 @@ export class ViewerSfuRoute {token: RouteOperationToken,acknowledge: boolean,): Promise<void> {- if (this.active?.revision === token.revision && this.active.activated) {+ const assignment = this.route.getActiveAssignment();+ const publicationGeneration = assignment?.sfuPublicationGeneration;+ if (+ this.active?.revision === token.revision &&+ this.active.publicationGeneration === publicationGeneration &&+ this.active.activated+ ) {return;}const pending = this.pending;- if (!pending || pending.revision !== token.revision || !pending.connected) {+ if (+ !pending ||+ pending.revision !== token.revision ||+ pending.publicationGeneration !== publicationGeneration ||+ !pending.connected+ ) {if (acknowledge && this.route.owns(token, "active")) {this.requestRecovery(token.revision);}@@ -527,6 +602,35 @@ export class ViewerSfuRoute {void this.queueTransition(() => this.promotePendingSfu(slot));}+ private handlePendingDecodedFrame(slot: ViewerSubscriberSlot): boolean {+ if (this.closed || slot.failed || this.pending !== slot) {+ return true;+ }+ if (this.paused || !slot.activated) {+ return false;+ }+ const assignment = this.route.getPlannedAssignment();+ const phase = this.route.getPhase();+ if (+ this.route.getRevision() !== slot.revision ||+ assignment?.upstream.kind !== "sfu" ||+ assignment.sfuPublicationGeneration !== slot.publicationGeneration ||+ phase === null+ ) {+ return true;+ }+ slot.decodedFrame = true;+ if (phase === "prepare" && !slot.readySent) {+ slot.readySent = this.events.send({+ type: "route-ready",+ revision: slot.revision,+ phase: "prepare",+ });+ }+ void this.queueTransition(() => this.promotePendingSfu(slot));+ return phase !== "prepare" || slot.readySent;+ }+private async promotePendingSfu(slot: ViewerSubscriberSlot): Promise<void> {const token = slot.activationToken;const assignment = this.route.getActiveAssignment();@@ -540,6 +644,7 @@ export class ViewerSfuRoute {) {return;}+ slot.subscriber.stopDecodedFrameProof();this.pending = null;const previous = this.active;this.active = slot;@@ -603,6 +708,31 @@ export class ViewerSfuRoute {const active = this.active;this.active = null;this.events.onSfuUpdate?.(null, active.revision);+ await this.disconnectRetiredSubscriber(active);+ }++ private detachUnreferencedActive(+ assignment: ParticipantRouteAssignment,+ ): ViewerSubscriberSlot | null {+ const publicationGeneration =+ assignment.upstream.kind === "sfu"+ ? assignment.sfuPublicationGeneration+ : null;+ if (+ !this.active ||+ this.active.publicationGeneration === publicationGeneration+ ) {+ return null;+ }+ const active = this.active;+ this.active = null;+ this.events.onSfuUpdate?.(null, active.revision);+ return active;+ }++ private async disconnectRetiredSubscriber(+ active: ViewerSubscriberSlot,+ ): Promise<void> {if (active.activated) {try {active.subscriber.deactivate();@@ -619,6 +749,7 @@ export class ViewerSfuRoute {}const wasActive = this.active === slot;slot.failed = true;+ slot.subscriber.stopDecodedFrameProof();if (this.pending === slot) {this.pending = null;}@@ -631,7 +762,9 @@ export class ViewerSfuRoute {const revision = this.route.getRevision();const phase = this.route.getPhase();const matchesPlannedRoute =- revision === slot.revision && assignment?.upstream.kind === "sfu";+ revision === slot.revision &&+ assignment?.upstream.kind === "sfu" &&+ assignment.sfuPublicationGeneration === slot.publicationGeneration;if (revision === null || phase === null) {return;}@@ -671,8 +804,17 @@ export class ViewerSfuRoute {}+function isPausedCodecSfuCandidate(update: RouteUpdateInput): boolean {+ return (+ update.phase === "prepare" &&+ update.candidate.transport === "sfu" &&+ update.candidate.codecTransition !== null+ );+}+async function disconnectSubscriber(subscriber: ViewerSubscriberTransport,): Promise<void> {+ subscriber.stopDecodedFrameProof();await subscriber.disconnect().catch(() => undefined);}diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsxindex f3d48f89..ae8f46d3 100644--- a/src/client/pages/HostPage.tsx+++ b/src/client/pages/HostPage.tsx@@ -28,6 +28,8 @@ import {type PreparedRouteCandidate,type ServerMessage,type CodeEntryPolicy,+ type CodecTransitionGeneration,+ type ResumeAttempt,} from "../../shared/protocol";import { AppHeader } from "../components/AppHeader";import { ConnectionSelfCheck } from "../components/ConnectionSelfCheck";@@ -67,7 +69,10 @@ import {replaceViewerInvite,writeHostRoom,} from "../lib/session";-import { SignalingClient } from "../lib/signaling";+import {+ SignalingClient,+ type SignalingTerminationReason,+} from "../lib/signaling";import { labelParticipantSnapshot } from "../lib/viewer-presence";import {applyCaptureProfile,@@ -93,6 +98,7 @@ import {HostSfuRoute,type HostSfuPublisherSnapshot,} from "../media/host-sfu-route";+import { applyAuthoritativeHostPause } from "../media/host-source-authority";import {HostProvisionalChild,} from "../media/host-provisional-child";@@ -117,12 +123,29 @@ import {reconcileBoundedMediaChildren,} from "../webrtc/media-assignment";import {+ hostActionErrorNotice,+ hostServerErrorNotice,shouldPauseLocalPreview,sourceSwitchNotice,+ type HostAction,+ VIDEO_CODEC_TRANSITION_FAILED_NOTICE,videoCodecLockNotice,} from "./host-page-notices";type HostPhase = "idle" | "starting" | "live" | "ended" | "error";+type CodecTransitionPhase =+ | "preparing"+ | "prepared"+ | "proving"+ | "rollback-preparing"+ | "rollback-prepared"+ | "failed";++interface CodecTransitionState {+ generation: CodecTransitionGeneration | null;+ requested: VideoCodecPreference;+ rollback: boolean;+}type ViewerQualityEvidence = Extract<ServerMessage,@@ -151,11 +174,10 @@ function captureDetails(stream: MediaStream): CaptureDetails {};}-function readableError(error: unknown): string {- if (error instanceof DOMException && error.name === "NotAllowedError") {- return "屏幕选择已取消或没有共享权限";- }- return error instanceof Error && error.message ? error.message : "启动分享失败";+function readableError(error: unknown, action: HostAction): string {+ return error instanceof ApiError+ ? error.message+ : hostActionErrorNotice(error, action);}function closeAbandonedRoom(room: HostRoomIdentity): void {@@ -207,6 +229,17 @@ function hostRoomFromCreated(room: CreateRoomResponse): HostRoomState {};}+function hostTerminationMessage(reason: SignalingTerminationReason): string {+ switch (reason) {+ case "STALE_CLIENT":+ return "页面版本已更新,请刷新后重试";+ case "SESSION_REPLACED":+ return "此页面的会话已被另一个标签页接管";+ case "SIGNAL_TERMINATED":+ return "信令会话已终止,请刷新后重试";+ }+}+interface HostPageProps {onAuthorizationRequired?: () => void;}@@ -258,6 +291,9 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {const [switchingSource, setSwitchingSource] = useState(false);const [changingQuality, setChangingQuality] = useState(false);const [sharingPaused, setSharingPaused] = useState(false);+ const [resumePending, setResumePending] = useState(false);+ const [codecTransitionPhase, setCodecTransitionPhase] =+ useState<CodecTransitionPhase | null>(null);const [localPreviewPaused, setLocalPreviewPaused] = useState(false);const [showConnectionDetails, setShowConnectionDetails] = useState(false);const [showTopology, setShowTopology] = useState(false);@@ -293,6 +329,10 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {const qualityChangeRef = useRef<object | null>(null);const qualitySettingsRef = useRef<QualitySettings>(DEFAULT_QUALITY_SETTINGS);const sharingPausedRef = useRef(false);+ const resumePendingRef = useRef(false);+ const activeResumeAttemptRef = useRef<ResumeAttempt | null>(null);+ const codecTransitionRef = useRef<CodecTransitionState | null>(null);+ const codecTransitionPhaseRef = useRef<CodecTransitionPhase | null>(null);const retiringStreamRef = useRef<MediaStream | null>(null);const hostSfuRouteRef = useRef<HostSfuRoute | null>(null);const sfuStandbyPrewarmerRef = useRef<SfuStandbyPrewarmer | null>(null);@@ -470,6 +510,31 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {setSfuPublisherSnapshot(snapshot);}},+ onCodecPublisherPrepared: (result) => {+ const shareGeneration = shareGenerationRef.current;+ if (+ !shareGeneration ||+ !isCurrentGeneration(generation) ||+ hostSfuRouteRef.current !== route+ ) {+ return;+ }+ const rollback =+ codecTransitionRef.current?.rollback === true ||+ codecTransitionPhaseRef.current === "rollback-preparing";+ codecTransitionRef.current = {+ generation: result.generation,+ requested: result.videoCodec,+ rollback,+ };+ signalRef.current?.send({+ type: "video-codec-prepared",+ shareGeneration,+ generation: result.generation,+ binding: result.binding,+ accepted: result.accepted,+ });+ },});hostSfuRouteRef.current = route;return route;@@ -560,6 +625,12 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {setChangingQuality(false);sharingPausedRef.current = false;setSharingPaused(false);+ resumePendingRef.current = false;+ setResumePending(false);+ activeResumeAttemptRef.current = null;+ codecTransitionRef.current = null;+ codecTransitionPhaseRef.current = null;+ setCodecTransitionPhase(null);}function forgetRoom(): void {@@ -723,7 +794,45 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {}function changeVideoCodec(videoCodec: VideoCodecPreference): void {- if (phase === "starting" || phase === "live") {+ if (phase === "starting") {+ return;+ }+ if (phase === "live") {+ const shareGeneration = shareGenerationRef.current;+ if (+ !sharingPausedRef.current ||+ !peerAssistedRef.current ||+ !shareGeneration ||+ changingQuality ||+ switchingSource ||+ codecTransitionRef.current+ ) {+ return;+ }+ if (+ (qualitySettingsRef.current.videoCodec ?? "automatic") === videoCodec+ ) {+ return;+ }+ if (+ signalRef.current?.send({+ type: "request-video-codec-transition",+ shareGeneration,+ videoCodec,+ }) !== true+ ) {+ setNotice("信令正在恢复,暂时无法切换视频编码");+ return;+ }+ codecTransitionRef.current = {+ generation: null,+ requested: videoCodec,+ rollback: false,+ };+ codecTransitionPhaseRef.current = "preparing";+ setCodecTransitionPhase("preparing");+ setAdvancedQuality((current) => ({ ...current, videoCodec }));+ setNotice("正在准备视频编码");return;}const next = { ...qualitySettingsRef.current, videoCodec };@@ -747,6 +856,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {preserveAdvancedDraft = false,): Promise<void> {const previousProfile = qualitySettingsRef.current;+ const codecTransition = codecTransitionRef.current;if (phase === "live" &&(nextProfile.videoCodec ?? "automatic") !==@@ -754,6 +864,19 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {) {return;}+ if (+ phase === "live" &&+ codecTransition &&+ !videoQualitySettingsEqual(previousProfile, nextProfile)+ ) {+ return;+ }+ if (+ phase === "live" &&+ codecTransitionPhaseRef.current === "failed"+ ) {+ return;+ }if (phase !== "live") {commitQuality(nextProfile, preserveAdvancedDraft);return;@@ -782,6 +905,9 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {const audioChanged =resolveScreenAudioQuality(previousProfile.screenAudioQuality) !==resolveScreenAudioQuality(nextProfile.screenAudioQuality);+ const endpointProfile = codecTransition+ ? { ...nextProfile, videoCodec: codecTransition.requested }+ : nextProfile;try {if (videoChanged) {@@ -810,14 +936,14 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {Promise.all([...[...peersRef.current.values()].map((peer) =>- peer.updateProfile(nextProfile),+ peer.updateProfile(endpointProfile),),...(hostProvisionalChildRef.current- ? [hostProvisionalChildRef.current.updateProfile(nextProfile)]+ ? [hostProvisionalChildRef.current.updateProfile(endpointProfile)]: []),],),- activeSfuRoute?.updateProfile(nextProfile) ??+ activeSfuRoute?.updateProfile(endpointProfile) ??Promise.resolve(true),]);if (@@ -852,7 +978,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {isCurrentGeneration(generation) &&qualityChangeRef.current === token) {- setNotice(readableError(error));+ setNotice(readableError(error, "quality"));}} finally {if (qualityChangeRef.current === token) {@@ -867,19 +993,38 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {if (phase !== "live" || !activeStream) {return;}- const nextPaused = !sharingPausedRef.current;- if (!setMediaPaused(activeStream, nextPaused)) {- setNotice("当前分享没有可暂停的媒体轨道");+ if (sharingPausedRef.current) {+ if (resumePendingRef.current) {+ return;+ }+ if (signalRef.current?.requestSharingResume() !== true) {+ setNotice("信令正在恢复,分享仍保持暂停");+ return;+ }+ resumePendingRef.current = true;+ setResumePending(true);+ setNotice("正在恢复分享");return;}- sharingPausedRef.current = nextPaused;- setSharingPaused(nextPaused);- hostSfuRouteRef.current?.setPaused(nextPaused);- if (nextPaused) {- discardPreparedHostChild();+ if (!setMediaPaused(activeStream, true)) {+ setNotice("当前分享没有可暂停的媒体轨道");+ return;}- signalRef.current?.setSharingPaused(nextPaused);- setNotice(nextPaused ? "音视频分享已暂停" : "音视频分享已恢复");+ sharingPausedRef.current = true;+ setSharingPaused(true);+ hostSfuRouteRef.current?.setPaused(true);+ discardPreparedHostChild();+ signalRef.current?.pauseSharing();+ activeResumeAttemptRef.current = null;+ const codecState = codecTransitionRef.current;+ if (codecState && codecTransitionPhaseRef.current === "proving") {+ const nextPhase = codecState.rollback+ ? "rollback-prepared"+ : "prepared";+ codecTransitionPhaseRef.current = nextPhase;+ setCodecTransitionPhase(nextPhase);+ }+ setNotice("音视频分享已暂停");}async function enterPreviewFullscreen(): Promise<void> {@@ -1071,7 +1216,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {void startPeer(peerId, generation, attempt + 1).catch((error: unknown) => {if (isCurrentGeneration(generation)) {- setNotice(readableError(error));+ setNotice(readableError(error, "connection"));}},);@@ -1128,22 +1273,81 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {(peerId) => {void startPeer(peerId, generation).catch((error: unknown) => {if (isCurrentGeneration(generation)) {- setNotice(readableError(error));+ setNotice(readableError(error, "connection"));}});},);}+ async function prepareVideoCodec(+ message: Extract<ServerMessage, { type: "video-codec-prepare" }>,+ generation: number,+ ): Promise<void> {+ const shareGeneration = shareGenerationRef.current;+ if (+ !shareGeneration ||+ message.shareGeneration !== shareGeneration ||+ !isCurrentGeneration(generation)+ ) {+ return;+ }++ const rollback =+ codecTransitionRef.current?.rollback === true ||+ codecTransitionPhaseRef.current === "rollback-preparing";+ codecTransitionRef.current = {+ generation: message.generation,+ requested: message.videoCodec,+ rollback,+ };++ let accepted = false;+ if (message.binding.kind === "peer") {+ const peer = peersRef.current.get(message.binding.childPeerId);+ if (peer?.connectionId === message.binding.connectionId) {+ peer.cancelVideoCodecPreparation();+ accepted = await peer.prepareVideoCodec(+ message.generation,+ message.videoCodec,+ );+ }+ }++ if (+ !isCurrentGeneration(generation) ||+ shareGenerationRef.current !== shareGeneration+ ) {+ return;+ }+ signalRef.current?.send({+ type: "video-codec-prepared",+ shareGeneration,+ generation: message.generation,+ binding: message.binding,+ accepted,+ });+ }+function handleSignalMessage(message: ServerMessage,generation: number,activeRoomId: string,+ reauthenticated: boolean,): void {if (!isCurrentGeneration(generation)) {return;}if (message.type === "authenticated" && message.role === "host") {+ peersRef.current.forEach((peer) =>+ peer.cancelVideoCodecPreparation(),+ );+ codecTransitionRef.current = null;+ codecTransitionPhaseRef.current = null;+ setCodecTransitionPhase(null);+ resumePendingRef.current = false;+ setResumePending(false);+ activeResumeAttemptRef.current = null;discardPreparedHostChild();hostPeerIdRef.current = message.peerId;endpointMediaCopyCapacityRef.current = message.endpointMediaCopyCapacity;@@ -1170,10 +1374,33 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {...message.routeAssignment.childPeerIds,];peerAssistedRef.current = true;- signalRef.current?.send({- type: "set-quality-settings",- qualitySettings: qualitySettingsRef.current,- });+ const activeCodecTransition = codecTransitionRef.current;+ if (reauthenticated) {+ commitQuality(+ message.qualitySettings,+ activeCodecTransition !== null,+ );+ if (activeCodecTransition === null) {+ const endpointUpdates = [+ ...[...peersRef.current.values()].map((peer) =>+ peer.updateProfile(message.qualitySettings),+ ),+ ...(hostProvisionalChildRef.current+ ? [+ hostProvisionalChildRef.current.updateProfile(+ message.qualitySettings,+ ),+ ]+ : []),+ ];+ void Promise.allSettled(endpointUpdates);+ }+ } else {+ signalRef.current?.send({+ type: "set-quality-settings",+ qualitySettings: qualitySettingsRef.current,+ });+ }const route = ensureHostSfuRoute(generation);void route.resyncAuthoritative({@@ -1181,7 +1408,16 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {phase: "active",assignment: message.routeAssignment,})- .then(() => showHostSfuQualityWarning(route, generation));+ .then(async () => {+ if (+ reauthenticated &&+ codecTransitionRef.current === null &&+ hostSfuRouteRef.current === route+ ) {+ await route.updateProfile(message.qualitySettings);+ }+ showHostSfuQualityWarning(route, generation);+ });return;}activeRouteRevisionRef.current = 0;@@ -1267,6 +1503,168 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {downloadDiagnosticReport("host", connections, message.snapshot);return;}+ if (message.type === "video-codec-prepare") {+ void prepareVideoCodec(message, generation);+ return;+ }+ if (message.type === "video-codec-result") {+ let transition = codecTransitionRef.current;+ if (+ !transition &&+ message.status === "failed" &&+ message.failure === "stale-binding"+ ) {+ transition = {+ generation: message.generation,+ requested: message.videoCodec,+ rollback: true,+ };+ codecTransitionRef.current = transition;+ }+ if (+ !transition ||+ (transition.generation !== null &&+ transition.generation !== message.generation)+ ) {+ return;+ }+ transition.generation = message.generation;+ if (message.status === "prepared") {+ codecTransitionPhaseRef.current = "prepared";+ setCodecTransitionPhase("prepared");+ setNotice("视频编码已准备,恢复分享后完成验证");+ return;+ }+ if (message.status === "rollback-prepared") {+ transition.rollback = true;+ transition.requested = message.videoCodec;+ codecTransitionPhaseRef.current = "rollback-prepared";+ setCodecTransitionPhase("rollback-prepared");+ setAdvancedQuality((current) => ({+ ...current,+ videoCodec: message.videoCodec,+ }));+ setNotice("新编码未通过验证;原编码已准备,恢复分享后完成恢复");+ return;+ }+ if (message.status === "committed") {+ activeResumeAttemptRef.current = null;+ codecTransitionRef.current = null;+ codecTransitionPhaseRef.current = null;+ setCodecTransitionPhase(null);+ commitQuality(+ { ...qualitySettingsRef.current, videoCodec: message.videoCodec },+ true,+ );+ setAdvancedQuality((current) => ({+ ...current,+ videoCodec: message.videoCodec,+ }));+ setNotice(+ message.failure+ ? "已恢复原视频编码"+ : `视频编码已切换为 ${VIDEO_CODEC_PREFERENCE_LABELS[message.videoCodec]}`,+ );+ } else {+ transition.requested = message.videoCodec;+ transition.rollback = true;+ codecTransitionPhaseRef.current = "failed";+ setCodecTransitionPhase("failed");+ resumePendingRef.current = false;+ setResumePending(false);+ activeResumeAttemptRef.current = null;+ setAdvancedQuality((current) => ({+ ...current,+ videoCodec: message.videoCodec,+ }));+ setNotice(VIDEO_CODEC_TRANSITION_FAILED_NOTICE);+ }+ return;+ }+ if (message.type === "sharing-resume-authorized") {+ if (message.shareGeneration !== shareGenerationRef.current) {+ return;+ }+ const transition = codecTransitionRef.current;+ if (+ (message.codecGeneration === null && transition !== null) ||+ (message.codecGeneration !== null &&+ (transition?.generation !== message.codecGeneration ||+ (codecTransitionPhaseRef.current !== "prepared" &&+ codecTransitionPhaseRef.current !== "rollback-prepared")))+ ) {+ activeResumeAttemptRef.current = null;+ signalRef.current?.pauseSharing();+ resumePendingRef.current = false;+ setResumePending(false);+ setNotice("恢复授权已失效,分享仍保持暂停");+ return;+ }+ activeResumeAttemptRef.current = message.resumeAttempt;+ const activeStream = streamRef.current;+ if (!activeStream || !setMediaPaused(activeStream, false)) {+ activeResumeAttemptRef.current = null;+ signalRef.current?.pauseSharing();+ resumePendingRef.current = false;+ setResumePending(false);+ setNotice("当前分享没有可恢复的媒体轨道");+ return;+ }+ hostSfuRouteRef.current?.setPaused(false);+ if (signalRef.current?.confirmSharingResumed(message) !== true) {+ setMediaPaused(activeStream, true);+ hostSfuRouteRef.current?.setPaused(true);+ signalRef.current?.pauseSharing();+ activeResumeAttemptRef.current = null;+ resumePendingRef.current = false;+ setResumePending(false);+ setNotice("信令正在恢复,分享仍保持暂停");+ return;+ }+ sharingPausedRef.current = false;+ setSharingPaused(false);+ resumePendingRef.current = false;+ setResumePending(false);+ if (message.codecGeneration !== null) {+ codecTransitionPhaseRef.current = "proving";+ setCodecTransitionPhase("proving");+ setNotice("正在验证视频编码");+ } else {+ setNotice("音视频分享已恢复");+ }+ return;+ }+ if (message.type === "pause-sharing-source") {+ const transition = codecTransitionRef.current;+ const pause = applyAuthoritativeHostPause({+ message,+ currentShareGeneration: shareGenerationRef.current,+ activeResumeAttempt: activeResumeAttemptRef.current,+ activeCodecGeneration: transition?.generation ?? null,+ stream: streamRef.current,+ pauseSfuRoute: () => hostSfuRouteRef.current?.setPaused(true),+ markHostPaused: () => {+ sharingPausedRef.current = true;+ setSharingPaused(true);+ signalRef.current?.confirmSharingPaused();+ resumePendingRef.current = false;+ setResumePending(false);+ activeResumeAttemptRef.current = null;+ },+ });+ if (!pause) {+ return;+ }+ if (transition && pause.localCodecContextMatches) {+ transition.rollback = true;+ codecTransitionPhaseRef.current = "rollback-preparing";+ setCodecTransitionPhase("rollback-preparing");+ setNotice("新编码未通过验证,正在恢复原编码");+ } else {+ setNotice("分享仍保持暂停");+ }+ return;+ }if (message.type === "route-update") {if (peerAssistedRef.current) {const route = ensureHostSfuRoute(generation);@@ -1329,7 +1727,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {}void startPeer(message.peerId, generation).catch((error: unknown) => {if (isCurrentGeneration(generation)) {- setNotice(readableError(error));+ setNotice(readableError(error, "connection"));}});return;@@ -1367,7 +1765,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {generation,).catch((error: unknown) => {if (isCurrentGeneration(generation)) {- setNotice(readableError(error));+ setNotice(readableError(error, "connection"));}});return;@@ -1381,6 +1779,20 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {return;}if (message.type === "error") {+ if (+ codecTransitionRef.current?.generation === null &&+ codecTransitionPhaseRef.current === "preparing"+ ) {+ codecTransitionRef.current = null;+ codecTransitionPhaseRef.current = null;+ setCodecTransitionPhase(null);+ setAdvancedQuality((current) => ({+ ...current,+ videoCodec: qualitySettingsRef.current.videoCodec ?? "automatic",+ }));+ }+ resumePendingRef.current = false;+ setResumePending(false);setViewerGrantUpdating(false);setViewerPasswordUpdating(false);viewerPasswordActionRef.current = null;@@ -1389,16 +1801,14 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {endSharing("房间已失效,再次点击将创建新房", false);return;}- if (- [- "AUTH_REQUIRED",- "HOST_ALREADY_CONNECTED",- ].includes(message.code)- ) {- endSharing(message.message, false);+ if (message.code === "AUTH_REQUIRED") {+ return;+ }+ if (message.code === "HOST_ALREADY_CONNECTED") {+ endSharing(hostServerErrorNotice(message.code), false);return;}- setNotice(message.message);+ setNotice(hostServerErrorNotice(message.code));}}@@ -1429,7 +1839,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {}activeGenerationRef.current = null;shareGenerationRef.current = null;- setNotice(readableError(error));+ setNotice(readableError(error, "capture"));setPhase("error");return;}@@ -1502,12 +1912,12 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {setSignalStatus(status);}},- onTerminated: (message) => {+ onTerminated: (reason) => {if (isCurrentGeneration(generation) &&signalRef.current === signal) {- endSharing(message, false);+ endSharing(hostTerminationMessage(reason), false);}},onAccessRequired: () => {@@ -1542,6 +1952,10 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {void createReplacementRoom();return;}+ const reauthenticated =+ authenticated &&+ message.type === "authenticated" &&+ message.role === "host";if (message.type === "authenticated" && message.role === "host") {authenticated = true;iceConfigRef.current = message.iceConfig;@@ -1554,7 +1968,12 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {});setPhase("live");}- handleSignalMessage(message, generation, activeRoom.roomId);+ handleSignalMessage(+ message,+ generation,+ activeRoom.roomId,+ reauthenticated,+ );},},);@@ -1591,7 +2010,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {onAuthorizationRequired();return;}- setNotice(readableError(error));+ setNotice(readableError(error, "room"));setPhase("error");}};@@ -1616,7 +2035,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {onAuthorizationRequired();return;}- setNotice(readableError(error));+ setNotice(readableError(error, "room"));setPhase("error");}}@@ -1647,7 +2066,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {isCurrentGeneration(generation) &&sourceSwitchRef.current === token) {- setNotice(readableError(error));+ setNotice(readableError(error, "source"));}finishSourceSwitch(token);return;@@ -1745,7 +2164,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {isCurrentGeneration(generation) &&sourceSwitchRef.current === token) {- setNotice(readableError(error));+ setNotice(readableError(error, "connection"));}}}),@@ -1879,7 +2298,14 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {: null;const activeCodeEntryPolicy =room?.codeEntryPolicy ?? creationProfile.codeEntryPolicy;- const codecLockNotice = videoCodecLockNotice(phase);+ const codecLockNotice = videoCodecLockNotice(+ phase,+ sharingPaused,+ codecTransitionPhase,+ );+ const codecResumeReady =+ codecTransitionPhase === "prepared" ||+ codecTransitionPhase === "rollback-prepared";return (<div className="app-shell">@@ -1919,7 +2345,14 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {<buttonclassName="button button-secondary"type="button"- disabled={switchingSource || changingQuality}+ disabled={+ switchingSource ||+ changingQuality ||+ resumePending ||+ (sharingPaused &&+ codecTransitionPhase !== null &&+ !codecResumeReady)+ }onClick={toggleSharingPause}>{sharingPaused ? (@@ -1927,14 +2360,22 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {) : (<Pause size={16} fill="currentColor" aria-hidden="true" />)}- {sharingPaused ? "恢复分享" : "暂停分享"}+ {resumePending+ ? "正在恢复"+ : sharingPaused+ ? "恢复分享"+ : "暂停分享"}</button>)}{phase === "live" && (<buttonclassName="button button-secondary"type="button"- disabled={switchingSource || changingQuality}+ disabled={+ switchingSource ||+ changingQuality ||+ codecTransitionPhase !== null+ }onClick={() => void switchSource()}><RefreshCw size={16} aria-hidden="true" />@@ -2165,7 +2606,8 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {disabled={phase === "starting" ||switchingSource ||- changingQuality+ changingQuality ||+ codecTransitionPhase !== null}onClick={() =>void changeQuality({@@ -2310,8 +2752,9 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {}disabled={phase === "starting" ||- phase === "live" ||- changingQuality+ (phase === "live" && !sharingPaused) ||+ changingQuality ||+ codecTransitionPhase !== null}onClick={() =>changeVideoCodec(codec)@@ -2353,7 +2796,8 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {disabled={phase === "starting" ||switchingSource ||- changingQuality+ changingQuality ||+ codecTransitionPhase === "failed"}onClick={() =>changeScreenAudioQuality(audioQuality)@@ -2370,7 +2814,8 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {disabled={phase === "starting" ||switchingSource ||- changingQuality+ changingQuality ||+ codecTransitionPhase !== null}onClick={() => void changeQuality(advancedQuality)}>diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsxindex 3b6dfe8a..15ddc054 100644--- a/src/client/pages/ViewerPage.tsx+++ b/src/client/pages/ViewerPage.tsx@@ -73,6 +73,10 @@ import {isAutoplayPolicyRejection,observeCompositedVideoFrame,} from "../media/video-frame-proof";+import {+ CodecProofReporter,+ type CodecProofRouteSample,+} from "../media/codec-proof";import { exactPeerSignalOwner } from "../media/route-transition";import { ViewerSfuRoute } from "../media/viewer-sfu-route";import {@@ -111,6 +115,7 @@ interface PendingPeerRoute {revision: number;parentPeerId: string;peer: ViewerPeer | null;+ decodedFrame: boolean;readySent: boolean;candidateConnectionId: string;stream: MediaStream | null;@@ -336,6 +341,14 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {let peerAssisted = false;let currentPeerId: string | null = null;let currentRouteRevision = 0;+ let currentRouteAssignment: ParticipantRouteAssignment | null = null;+ let currentRouteConnectionId: string | null = null;+ let pendingRouteConnection: {+ revision: number;+ connectionId: string;+ } | null = null;+ let activePeerProofSnapshot: PeerSnapshot | null = null;+ let activeSfuProofMetrics: ConnectionMetrics | null = null;let endpointMediaCopyCapacity = MAX_ENDPOINT_MEDIA_CHILDREN;let viewerAuthorizationGeneration: string | null = null;let currentQualitySettings: QualitySettings = DEFAULT_QUALITY_SETTINGS;@@ -384,7 +397,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {dispatchPresentation({ type: "signal", signal: status });}},- onTerminated: (message) => {+ onTerminated: (reason) => {if (!active) {return;}@@ -397,7 +410,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {dispatchPresentation({type: "access",access: "denied",- failure: viewerTerminationFailure(message),+ failure: reason,});},onAccessRequired: () => {@@ -427,6 +440,69 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {const qualityEvidenceReporter = new ViewerQualityEvidenceReporter((message) => active && signal.send(message),);+ const codecProofReporter = new CodecProofReporter(+ (message) => active && signal.send(message),+ );++ function currentCodecProofSample(): CodecProofRouteSample | null {+ const assignment = currentRouteAssignment;+ const connectionId = currentRouteConnectionId;+ if (!assignment || !connectionId) {+ return null;+ }+ if (assignment.upstream.kind === "peer") {+ const snapshot = activePeerProofSnapshot;+ if (+ !snapshot ||+ snapshot.peerId !== assignment.upstream.peerId ||+ snapshot.connectionId !== connectionId+ ) {+ return null;+ }+ return {+ routeRevision: currentRouteRevision,+ binding: { kind: "peer", connectionId },+ metrics: snapshot.metrics,+ };+ }+ if (+ assignment.upstream.kind !== "sfu" ||+ assignment.sfuPublicationGeneration === null+ ) {+ return null;+ }+ return {+ routeRevision: currentRouteRevision,+ binding: {+ kind: "sfu",+ connectionId,+ publicationGeneration: assignment.sfuPublicationGeneration,+ },+ metrics: activeSfuProofMetrics,+ };+ }++ function offerCodecProof(): void {+ const sample = currentCodecProofSample();+ if (sample) {+ codecProofReporter.offer(sample);+ }+ }++ function activateProofRoute(+ revision: number,+ assignment: ParticipantRouteAssignment,+ connectionId: string | null,+ ): void {+ codecProofReporter.clear();+ currentRouteRevision = revision;+ currentRouteAssignment = assignment;+ currentRouteConnectionId =+ assignment.upstream.kind === "none" ? null : connectionId;+ activePeerProofSnapshot = null;+ activeSfuProofMetrics = null;+ pendingRouteConnection = null;+ }function commitRelayChildEvidence(presentation: ViewerQualityEvidencePresentation | null,@@ -596,20 +672,24 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {snapshot !== null &&snapshot.peerId === probe.parentPeerId &&probe.peer?.hasConnectionId(snapshot.connectionId) === true &&- (snapshot.metrics.intervalFramesDecoded ?? 0) > 0+ probe.decodedFrame);}- function provePendingPeer(): void {+ function provePendingPeer(): boolean {const probe = pendingPeer;- if (!probe || probe.readySent || !pendingPeerHasDecodedFrame(probe)) {- return;+ if (!probe || probe.readySent) {+ return true;+ }+ if (!pendingPeerHasDecodedFrame(probe)) {+ return false;}probe.readySent = signal.send({type: "route-ready",revision: probe.revision,phase: "prepare",});+ return probe.readySent;}function ensureViewerSfuRoute(): ViewerSfuRoute {@@ -638,6 +718,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {return false;}const previousPeer = peerRef.current;+ probe.peer.stopDecodedFrameProof();pendingPeer = null;prepareParent(null);peerRef.current = probe.peer;@@ -651,6 +732,8 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {);ensureViewerRelay()?.setStream(probe.stream);bindRemoteStream(probe.stream, revision);+ activePeerProofSnapshot = probe.snapshot;+ offerCodecProof();setPeerSnapshot(probe.snapshot);setSfuUpstream(null);return true;@@ -682,6 +765,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {revision,parentPeerId: assignment.upstream.peerId,peer: null,+ decodedFrame: false,readySent: false,candidateConnectionId: candidate.connectionId,stream: null,@@ -729,6 +813,10 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {},onSfuUpdate: (metrics, revision) => {if (active && viewerSfuRoute === route) {+ if (revision === currentRouteRevision) {+ activeSfuProofMetrics = metrics;+ offerCodecProof();+ }if (metrics) {observeActiveDecodedFrames("sfu",@@ -807,6 +895,8 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {const route = viewerSfuRoute;discardPendingPeer();viewerSfuRoute = null;+ activeSfuProofMetrics = null;+ codecProofReporter.clear();setSfuUpstream(null);void route?.disconnect();}@@ -842,6 +932,8 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {function clearUpstreamState(clearMedia = false): void {qualityEvidenceReporter.reset();+ codecProofReporter.clear();+ activePeerProofSnapshot = null;const peer = peerRef.current;peer?.dispose();peerRef.current = null;@@ -903,6 +995,8 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {probe.snapshot = snapshot;provePendingPeer();} else if (active && peerRef.current === peer) {+ activePeerProofSnapshot = snapshot;+ offerCodecProof();observeActiveDecodedFrames("peer",`${probe.parentPeerId}:${snapshot.connectionId}`,@@ -918,6 +1012,17 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {});}},+ onFirstDecodedFrame: (connectionId): boolean => {+ if (+ pendingPeer !== probe ||+ !peer.hasConnectionId(connectionId) ||+ connectionId !== probe.candidateConnectionId+ ) {+ return true;+ }+ probe.decodedFrame = true;+ return provePendingPeer();+ },onRecoveryExhausted: (parentPeerId, connectionId): boolean => {if (pendingPeer === probe && peer.hasConnectionId(connectionId)) {signal.send({@@ -929,6 +1034,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {probe.peer = null;probe.stream = null;probe.snapshot = null;+ probe.decodedFrame = false;probe.readySent = false;peer.dispose();return true;@@ -976,6 +1082,8 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {},onUpdate: (snapshot) => {if (active) {+ activePeerProofSnapshot = snapshot;+ offerCodecProof();observeActiveDecodedFrames("peer",`${snapshot.peerId}:${snapshot.connectionId}`,@@ -985,9 +1093,14 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {qualityEvidenceReporter.offer(snapshot, currentRouteRevision);if (!currentHostOnline &&- snapshot.connectionState === "failed"+ (snapshot.connectionState === "failed" ||+ snapshot.connectionState === "closed")) {clearPeerState();+ dispatchPresentation({+ type: "media-invalidated",+ revision: currentRouteRevision,+ });return;}setPeerSnapshot(snapshot);@@ -1051,11 +1164,22 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {}currentRouteRevision = nextRouteRevision;if (nextPeerAssisted && "routeAssignment" in message) {+ activateProofRoute(+ message.routeRevision,+ message.routeAssignment,+ message.connectionId,+ );acceptAssignedRoute(message.routeRevision,message.routeAssignment.upstream,);} else {+ codecProofReporter.clear();+ currentRouteAssignment = null;+ currentRouteConnectionId = null;+ pendingRouteConnection = null;+ activePeerProofSnapshot = null;+ activeSfuProofMetrics = null;setAssignedRoute(null);dispatchPresentation({type: "route",@@ -1134,17 +1258,44 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {}if (message.type === "route-update") {if (peerAssisted) {- if (- message.phase === "active" &&- message.revision >= currentRouteRevision- ) {- if (message.revision !== currentRouteRevision) {- clearRelayChildEvidence();- }- currentRouteRevision = message.revision;- }const result = ensureViewerSfuRoute().accept(message);if (result !== "stale") {+ if (+ result === "accepted" &&+ message.phase === "prepare" &&+ message.candidate.childPeerId === currentPeerId+ ) {+ pendingRouteConnection = {+ revision: message.revision,+ connectionId: message.candidate.connectionId,+ };+ }+ if (result === "accepted" && message.phase === "active") {+ if (message.revision !== currentRouteRevision) {+ clearRelayChildEvidence();+ }+ const samePeerUpstream =+ currentRouteAssignment?.upstream.kind === "peer" &&+ message.assignment.upstream.kind === "peer" &&+ currentRouteAssignment.upstream.peerId ===+ message.assignment.upstream.peerId;+ const sameSfuUpstream =+ currentRouteAssignment?.upstream.kind === "sfu" &&+ message.assignment.upstream.kind === "sfu" &&+ currentRouteAssignment.sfuPublicationGeneration ===+ message.assignment.sfuPublicationGeneration;+ const connectionId =+ pendingRouteConnection?.revision === message.revision+ ? pendingRouteConnection.connectionId+ : samePeerUpstream || sameSfuUpstream+ ? currentRouteConnectionId+ : null;+ activateProofRoute(+ message.revision,+ message.assignment,+ connectionId,+ );+ }acceptAssignedRoute(message.revision,message.assignment.upstream,@@ -1154,6 +1305,32 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {}return;}+ if (message.type === "video-codec-prepare") {+ const accepted =+ peerAssisted &&+ currentHostPaused &&+ message.binding.kind === "peer" &&+ (await ensureViewerRelay()?.prepareVideoCodec(+ message.binding.childPeerId,+ message.binding.connectionId,+ message.generation,+ message.videoCodec,+ )) === true;+ if (active && messageAuthority.owns(authorityToken)) {+ signal.send({+ type: "video-codec-prepared",+ shareGeneration: message.shareGeneration,+ generation: message.generation,+ binding: message.binding,+ accepted,+ });+ }+ return;+ }+ if (message.type === "video-codec-proof-request") {+ codecProofReporter.request(message);+ return;+ }if (message.type === "route-status") {dispatchPresentation({type: "route-status",@@ -1281,6 +1458,10 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {return;}if (message.type === "sharing-stopped") {+ codecProofReporter.clear();+ currentRouteAssignment = null;+ currentRouteConnectionId = null;+ pendingRouteConnection = null;setSfuStandbyUrl(null);setAssignedRoute(null);currentHostOnline = false;@@ -1391,6 +1572,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {active = false;currentPeerId = null;qualityEvidenceReporter.reset();+ codecProofReporter.clear();clearRelayChildEvidence();sfuStandbyPrewarmer?.dispose();signal.stop();@@ -2058,13 +2240,3 @@ function viewerFailureFromServerCode(return null;}}--function viewerTerminationFailure(message: string): ViewerFailureCode {- if (message === "页面版本已更新,请刷新后重试") {- return "STALE_CLIENT";- }- if (message === "此页面的会话已被另一个标签页接管") {- return "SESSION_REPLACED";- }- return "SIGNAL_TERMINATED";-}diff --git a/src/client/pages/host-page-notices.ts b/src/client/pages/host-page-notices.tsindex 463f60bb..0a261025 100644--- a/src/client/pages/host-page-notices.ts+++ b/src/client/pages/host-page-notices.ts@@ -1,3 +1,64 @@+import type { ServerMessage } from "../../shared/protocol";++export type HostAction =+ | "capture"+ | "source"+ | "quality"+ | "connection"+ | "room";++const HOST_ACTION_FALLBACK: Record<HostAction, string> = {+ capture: "启动分享失败",+ source: "切换分享来源失败",+ quality: "应用画质设置失败",+ connection: "观看连接处理失败",+ room: "房间操作失败",+};++type ServerErrorCode = Extract<+ ServerMessage,+ { type: "error" }+>["code"];++const HOST_SERVER_ERROR_NOTICE: Record<ServerErrorCode, string> = {+ AUTH_REQUIRED: "站点访问已失效,请重新验证",+ INVALID_MESSAGE: "页面版本已更新,请刷新后重试",+ INVALID_TOKEN: "分享凭证已失效,请重新创建房间",+ ROOM_ACCESS_DENIED: "当前操作没有权限",+ ROOM_EXPIRED: "房间已过期,请重新创建",+ ROOM_FULL: "房间已满",+ HOST_ALREADY_CONNECTED: "此房间已在另一个页面中分享",+ PEER_NOT_FOUND: "对应的观看连接已经离开",+ FORBIDDEN: "当前操作不可用",+ SERVER_ERROR: "服务暂时不可用,请稍后重试",+};++export function hostActionErrorNotice(+ error: unknown,+ action: HostAction,+): string {+ if (+ error instanceof DOMException &&+ (action === "capture" || action === "source")+ ) {+ switch (error.name) {+ case "NotAllowedError":+ return "屏幕选择已取消或没有共享权限";+ case "NotFoundError":+ return "没有可用的屏幕分享来源";+ case "NotReadableError":+ return "浏览器暂时无法读取所选分享来源";+ case "SecurityError":+ return "当前页面无法启动屏幕分享";+ }+ }+ return HOST_ACTION_FALLBACK[action];+}++export function hostServerErrorNotice(code: ServerErrorCode): string {+ return HOST_SERVER_ERROR_NOTICE[code];+}+export function sourceSwitchNotice({failedPeerCount,sfuReplaced,@@ -34,8 +95,21 @@ export function shouldPauseLocalPreview(return visibilityState !== "visible" || !hasFocus;}-export function videoCodecLockNotice(phase: string): string | null {- return phase === "starting" || phase === "live"- ? "本次分享的编码已锁定,停止分享后可修改"+export const VIDEO_CODEC_TRANSITION_FAILED_NOTICE =+ "视频编码切换已失效,请停止分享后重试";++export function videoCodecLockNotice(+ phase: string,+ sharingPaused: boolean,+ codecTransitionPhase: string | null = null,+): string | null {+ if (codecTransitionPhase === "failed") {+ return VIDEO_CODEC_TRANSITION_FAILED_NOTICE;+ }+ if (phase === "starting") {+ return "分享开始后,暂停分享即可切换视频编码";+ }+ return phase === "live" && !sharingPaused+ ? "暂停分享后可切换视频编码": null;}diff --git a/src/client/sfu/publisher.ts b/src/client/sfu/publisher.tsindex 2ac0e724..52114cf8 100644--- a/src/client/sfu/publisher.ts+++ b/src/client/sfu/publisher.ts@@ -420,10 +420,7 @@ export class SfuPublisher {if (!this.owns(room, generation)) {return false;}- const failureWarning =- error instanceof Error && error.message- ? `切换 SFU 分享来源失败:${error.message}`- : "切换 SFU 分享来源失败";+ const failureWarning = "切换 SFU 分享来源失败";// A rejected publish/unpublish may have changed server state without// returning enough ownership information to undo it safely.@@ -552,7 +549,7 @@ export class SfuPublisher {senderParameters = configured.readback;videoWarning = configured.warning;appliedVideoProfile = profile;- } catch (error) {+ } catch {if (!this.owns(room, generation) ||requestedRevision !== this.profileRevision ||@@ -564,10 +561,7 @@ export class SfuPublisher {return false;}videoSucceeded = false;- const failureWarning =- error instanceof Error && error.message- ? `应用 SFU 发送参数失败:${error.message}`- : "应用 SFU 发送参数失败";+ const failureWarning = "应用 SFU 发送参数失败";try {const rolledBack = await configurePublishedVideo(video,@@ -1091,10 +1085,8 @@ function retainPublishedAudioOptions(};}-function audioSenderFailureWarning(error: unknown): string {- return error instanceof Error && error.message- ? `应用 SFU 音频发送参数失败:${error.message}`- : "应用 SFU 音频发送参数失败";+function audioSenderFailureWarning(_error: unknown): string {+ return "应用 SFU 音频发送参数失败";}function mergeQualityWarnings(...warnings: Array<string | null>): string | null {diff --git a/src/client/sfu/subscriber.ts b/src/client/sfu/subscriber.tsindex 8350d35e..7ef6b9db 100644--- a/src/client/sfu/subscriber.ts+++ b/src/client/sfu/subscriber.ts@@ -11,14 +11,17 @@ import type { ConnectionMetrics } from "../types";import {collectConnectionMetricsFromReport,createStatsAccumulator,+ decodedVideoFrames,mergeStatsReports,type StatsAccumulator,} from "../webrtc/stats";+import { observeDecodedFrameProof } from "../media/decoded-frame-proof";interface SubscriberEvents {onStream: (stream: MediaStream | null) => void;onVideoAvailability?: (available: boolean) => void;onStats?: (metrics: ConnectionMetrics) => void;+ onFirstDecodedFrame?: () => boolean;onState?: (state: "connected" | "reconnecting") => void;onDisconnected?: () => void;}@@ -63,6 +66,8 @@ export class SfuSubscriber {private statsAccumulator: StatsAccumulator = createStatsAccumulator();private statsTimer: ReturnType<typeof setInterval> | null = null;private statsInFlight: StatsAccumulator | null = null;+ private decodedFrameProofMode: "fresh" | "progress" | null = null;+ private stopDecodedFrameObserver: (() => void) | null = null;private generation = 0;private terminalNotified = false;@@ -158,6 +163,17 @@ export class SfuSubscriber {return true;}+ armDecodedFrameProof(requireProgress = false): void {+ this.cancelDecodedFrameObserver();+ this.decodedFrameProofMode = requireProgress ? "progress" : "fresh";+ this.startDecodedFrameProof();+ }++ stopDecodedFrameProof(): void {+ this.decodedFrameProofMode = null;+ this.cancelDecodedFrameObserver();+ }+async disconnect(): Promise<void> {const room = this.invalidate(true);if (room) {@@ -370,8 +386,9 @@ export class SfuSubscriber {track: RemoteTrack,trackType: typeof Track,): void {+ const isVideo = source === trackType.Source.ScreenShare;let previous: SubscribedTrack | null;- if (source === trackType.Source.ScreenShare) {+ if (isVideo) {previous = this.video;} else if (source === trackType.Source.ScreenShareAudio) {previous = this.audio;@@ -383,6 +400,9 @@ export class SfuSubscriber {return;}const hadVideo = this.video !== null;+ if (isVideo) {+ this.cancelDecodedFrameObserver();+ }if (previous) this.detachTrack(previous);const subscribed = {sid,@@ -396,7 +416,7 @@ export class SfuSubscriber {};mediaStreamTrack.addEventListener("ended", subscribed.onEnded, { once: true });this.stream.addTrack(mediaStreamTrack);- if (source === trackType.Source.ScreenShare) {+ if (isVideo) {this.video = subscribed;} else {this.audio = subscribed;@@ -408,12 +428,16 @@ export class SfuSubscriber {if (this.video) {this.startStats();}+ if (isVideo) {+ this.startDecodedFrameProof();+ }}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.cancelDecodedFrameObserver();this.detachTrack(this.video);this.video = null;}@@ -455,6 +479,44 @@ export class SfuSubscriber {void this.updateStats();}+ private startDecodedFrameProof(): void {+ const room = this.room;+ const video = this.video;+ const generation = this.generation;+ const mode = this.decodedFrameProofMode;+ if (!room || !video || !mode || this.state !== "active") {+ return;+ }+ this.cancelDecodedFrameObserver();+ this.stopDecodedFrameObserver = observeDecodedFrameProof({+ readFramesDecoded: async () => {+ const report = mergeStatsReports([+ await video.track.getRTCStatsReport(),+ ]);+ return report ? decodedVideoFrames(report) : null;+ },+ owns: () =>+ this.owns(room, generation) &&+ this.state === "active" &&+ this.video === video &&+ this.decodedFrameProofMode === mode,+ requireProgress: mode === "progress",+ onProof: () => {+ const accepted = this.events.onFirstDecodedFrame?.() ?? true;+ if (accepted) {+ this.decodedFrameProofMode = null;+ this.stopDecodedFrameObserver = null;+ }+ return accepted;+ },+ });+ }++ private cancelDecodedFrameObserver(): void {+ this.stopDecodedFrameObserver?.();+ this.stopDecodedFrameObserver = null;+ }+private async updateStats(): Promise<void> {const room = this.room;const video = this.video;@@ -514,6 +576,7 @@ export class SfuSubscriber {private clearMedia(notify: boolean): void {const hadStream = this.streamEmitted;const hadVideo = this.video !== null;+ this.stopDecodedFrameProof();this.stopStats();if (this.video) {this.detachTrack(this.video);diff --git a/src/client/styles.css b/src/client/styles.cssindex 28bc8be5..2f3f4cca 100644--- a/src/client/styles.css+++ b/src/client/styles.css@@ -340,16 +340,24 @@ h3 {}.stage-entry {- gap: 13px;+ grid-template-columns: minmax(0, 1fr);+ grid-template-rows: minmax(0, 1fr) 44px minmax(0, 1fr);+ gap: 0;width: 100%;}+.stage-entry .stage-status {+ align-self: end;+ margin-bottom: 13px;+}+.stage-status {color: var(--muted);}.entry-actions {display: grid;+ grid-row: 2;grid-template-columns: minmax(0, 1fr) 24px minmax(0, 1fr);width: min(520px, calc(100% - 20px));gap: 8px;@@ -359,6 +367,7 @@ h3 {.entry-action {display: inline-flex;min-width: 0;+ height: 44px;min-height: 44px;gap: 7px;align-items: center;@@ -446,10 +455,13 @@ h3 {.room-code-entry.is-inline {display: grid;+ grid-row: 3;min-width: 0;width: min(520px, calc(100% - 20px));grid-template-columns: minmax(0, 1fr) 44px;gap: 8px;+ align-self: start;+ margin-top: 13px;}.room-code-entry.is-inline .access-error {@@ -781,6 +793,9 @@ h3 {.invite-primary,.room-entry-policy {min-width: 0;+}++.room-entry-policy {padding-left: 12px;border-left: 1px solid var(--border);}diff --git a/src/client/webrtc/host-peer.ts b/src/client/webrtc/host-peer.tsindex d508f468..b863c848 100644--- a/src/client/webrtc/host-peer.ts+++ b/src/client/webrtc/host-peer.ts@@ -1,4 +1,8 @@-import type { IceConfig, SignalPayload } from "../../shared/protocol";+import type {+ CodecTransitionGeneration,+ IceConfig,+ SignalPayload,+} from "../../shared/protocol";import { createOpaqueId } from "../lib/opaque-id";import {audioSenderParameterWarning,@@ -35,12 +39,39 @@ interface HostPeerEvents {onUpdate: (snapshot: PeerSnapshot) => void;}+interface CodecPreparationRequest {+ generation: CodecTransitionGeneration;+ videoCodec: QualityProfile["videoCodec"];+ negotiationEpoch: number;+ promise: Promise<boolean>;+ resolve: (accepted: boolean) => void;+ settled: boolean;+}++interface CodecAnswerWaiter {+ request: CodecPreparationRequest;+ epoch: number;+ resolve: (accepted: boolean) => void;+}++type NegotiationAnswerOwner =+ | {+ kind: "ordinary";+ epoch: number;+ }+ | {+ kind: "codec";+ epoch: number;+ waiter: CodecAnswerWaiter;+ };+export class HostPeer {readonly connectionId: string;private readonly connection: RTCPeerConnection;private readonly pendingCandidates: SignalCandidate[] = [];private statsAccumulator = createStatsAccumulator();+ private videoTransceiver: RTCRtpTransceiver | null = null;private videoSender: RTCRtpSender | null = null;private audioSender: RTCRtpSender | null = null;private statsTimer: number | null = null;@@ -56,9 +87,13 @@ export class HostPeer {private limitationReason: string | null = null;private limitationSamples = 0;private disposed = false;- private negotiating = false;private profileRevision = 0;+ private negotiationEpoch = 0;+ private ordinaryAnswerEpoch: number | null = null;+ private codecPreparation: CodecPreparationRequest | null = null;+ private codecAnswerWaiter: CodecAnswerWaiter | null = null;private senderMutationTail: Promise<void> = Promise.resolve();+ private negotiationTail: Promise<void> = Promise.resolve();private snapshot: PeerSnapshot;constructor(@@ -98,10 +133,13 @@ export class HostPeer {direction: "sendonly",streams: [this.stream],});- applyVideoCodecPreference(- videoTransceiver,- this.desiredProfile.videoCodec,- );+ if (this.desiredProfile.videoCodec !== "automatic") {+ applyVideoCodecPreference(+ videoTransceiver,+ this.desiredProfile.videoCodec,+ );+ }+ this.videoTransceiver = videoTransceiver;this.videoSender = videoTransceiver.sender;this.audioSender = this.connection.addTransceiver(audioTrack ?? "audio", {direction: "sendonly",@@ -233,6 +271,65 @@ export class HostPeer {});}+ prepareVideoCodec(+ generation: CodecTransitionGeneration,+ videoCodec: QualityProfile["videoCodec"],+ ): Promise<boolean> {+ const current = this.codecPreparation;+ if (+ current?.generation === generation &&+ current.videoCodec === videoCodec+ ) {+ return current.promise;+ }+ if (current) {+ this.finishCodecPreparation(current, false);+ }++ let resolve!: (accepted: boolean) => void;+ const promise = new Promise<boolean>((resolvePromise) => {+ resolve = resolvePromise;+ });+ const request: CodecPreparationRequest = {+ generation,+ videoCodec,+ negotiationEpoch: this.nextNegotiationEpoch(),+ promise,+ resolve,+ settled: false,+ };+ this.codecPreparation = request;+ void this.enqueueSenderMutation(() =>+ this.runCodecPreparation(request),+ ).then(+ (accepted) => this.finishCodecPreparation(request, accepted),+ () => this.finishCodecPreparation(request, false),+ );+ return promise;+ }++ cancelVideoCodecPreparation(): void {+ const request = this.codecPreparation;+ if (!request) {+ return;+ }+ this.finishCodecPreparation(request, false);+ if (this.disposed) {+ return;+ }+ const epoch = this.nextNegotiationEpoch();+ void this.enqueueNegotiation(async () => {+ if (+ this.disposed ||+ epoch !== this.negotiationEpoch ||+ this.codecPreparation+ ) {+ return;+ }+ await this.rollbackPendingLocalOffer();+ });+ }+async acceptSignal(payload: SignalPayload): Promise<void> {if (this.disposed || payload.connectionId !== this.connectionId) {return;@@ -243,8 +340,7 @@ export class HostPeer {if (payload.description.type !== "answer") {return;}- await this.connection.setRemoteDescription(payload.description);- await this.flushCandidates();+ await this.enqueueNegotiation(() => this.acceptAnswer(payload));} else if (this.connection.remoteDescription) {await this.connection.addIceCandidate(payload.candidate);} else if (this.pendingCandidates.length < MAX_PENDING_CANDIDATES) {@@ -256,16 +352,34 @@ export class HostPeer {}async restartIce(): Promise<boolean> {- if (this.disposed) {- return false;- }- if (this.negotiating) {- return true;- }- if (this.connection.signalingState !== "stable") {- return false;+ while (!this.disposed) {+ const codecPreparation = this.codecPreparation;+ if (codecPreparation) {+ await codecPreparation.promise;+ continue;+ }+ const restarted = await this.enqueueNegotiation(async () => {+ if (this.disposed) {+ return false;+ }+ if (this.codecPreparation) {+ return null;+ }+ if (this.connection.signalingState !== "stable") {+ return false;+ }+ const accepted = await this.createOwnedOffer(+ true,+ this.nextNegotiationEpoch(),+ null,+ );+ return !accepted && this.codecPreparation ? null : accepted;+ });+ if (restarted !== null) {+ return restarted;+ }}- return this.createOffer(true);+ return false;}isConnected(): boolean {@@ -294,10 +408,13 @@ export class HostPeer {return;}this.disposed = true;+ this.nextNegotiationEpoch();+ this.ordinaryAnswerEpoch = null;if (this.statsTimer !== null) {window.clearInterval(this.statsTimer);this.statsTimer = null;}+ this.cancelVideoCodecPreparation();this.connection.close();}@@ -329,27 +446,60 @@ export class HostPeer {return result;}- private async createOffer(restart: boolean): Promise<boolean> {- if (this.disposed) {+ private enqueueNegotiation<T>(operation: () => Promise<T>): Promise<T> {+ const result = this.negotiationTail.then(operation, operation);+ this.negotiationTail = result.then(+ () => undefined,+ () => undefined,+ );+ return result;+ }++ private createOffer(restart: boolean): Promise<boolean> {+ return this.enqueueNegotiation(async () => {+ if (this.disposed || this.codecPreparation) {+ return false;+ }+ return this.createOwnedOffer(+ restart,+ this.nextNegotiationEpoch(),+ null,+ );+ });+ }++ private async createOwnedOffer(+ restart: boolean,+ epoch: number,+ negotiationGeneration: CodecTransitionGeneration | null,+ request: CodecPreparationRequest | null = null,+ ): Promise<boolean> {+ if (!this.ownsLocalOffer(epoch, request)) {return false;}- this.negotiating = true;try {if (restart) {this.connection.restartIce();}const offer = await this.connection.createOffer();- if (this.disposed) {+ if (!this.ownsLocalOffer(epoch, request)) {return false;}await this.connection.setLocalDescription(offer);- if (this.disposed || !this.connection.localDescription) {+ if (+ !this.ownsLocalOffer(epoch, request) ||+ !this.connection.localDescription+ ) {return false;}+ if (negotiationGeneration === null) {+ this.ordinaryAnswerEpoch = epoch;+ }if (!this.events.sendSignal(this.peerId, {kind: "description",connectionId: this.connectionId,+ negotiationGeneration,description: {type: "offer",sdp: this.connection.localDescription.sdp,@@ -362,10 +512,17 @@ export class HostPeer {this.emit();return true;} catch (error) {+ if (!this.ownsLocalOffer(epoch, request)) {+ return false;+ }+ if (+ negotiationGeneration === null &&+ this.ordinaryAnswerEpoch === epoch+ ) {+ this.ordinaryAnswerEpoch = null;+ }this.setError(error, restart ? "恢复连接失败" : "创建连接失败");return false;- } finally {- this.negotiating = false;}}@@ -376,6 +533,209 @@ export class HostPeer {}}+ private async acceptAnswer(+ payload: Extract<SignalPayload, { kind: "description" }>,+ ): Promise<void> {+ const owner = this.currentAnswerOwner(payload.negotiationGeneration);+ if (!owner) {+ return;+ }+ try {+ await this.connection.setRemoteDescription(payload.description);+ if (!this.ownsAnswer(owner)) {+ return;+ }+ await this.flushCandidates();+ if (this.ownsAnswer(owner)) {+ this.completeAnswer(owner, true);+ }+ } catch (error) {+ if (!this.ownsAnswer(owner)) {+ return;+ }+ this.completeAnswer(owner, false);+ throw error;+ }+ }++ private currentAnswerOwner(+ generation: CodecTransitionGeneration | null,+ ): NegotiationAnswerOwner | null {+ if (generation === null) {+ const epoch = this.ordinaryAnswerEpoch;+ return epoch !== null && epoch === this.negotiationEpoch+ ? { kind: "ordinary", epoch }+ : null;+ }+ const waiter = this.codecAnswerWaiter;+ return waiter &&+ waiter.epoch === this.negotiationEpoch &&+ waiter.request.generation === generation &&+ this.ownsCodecPreparation(waiter.request)+ ? { kind: "codec", epoch: waiter.epoch, waiter }+ : null;+ }++ private ownsAnswer(owner: NegotiationAnswerOwner): boolean {+ if (this.disposed || owner.epoch !== this.negotiationEpoch) {+ return false;+ }+ return owner.kind === "ordinary"+ ? this.ordinaryAnswerEpoch === owner.epoch+ : this.codecAnswerWaiter === owner.waiter &&+ this.ownsCodecPreparation(owner.waiter.request);+ }++ private completeAnswer(+ owner: NegotiationAnswerOwner,+ accepted: boolean,+ ): void {+ if (!this.ownsAnswer(owner)) {+ return;+ }+ if (owner.kind === "ordinary") {+ this.ordinaryAnswerEpoch = null;+ return;+ }+ this.codecAnswerWaiter = null;+ owner.waiter.resolve(accepted);+ }++ private settleCodecAnswer(+ accepted: boolean,+ generation?: CodecTransitionGeneration,+ epoch?: number,+ ): void {+ const waiter = this.codecAnswerWaiter;+ if (+ (generation !== undefined &&+ waiter?.request.generation !== generation) ||+ (epoch !== undefined && waiter?.epoch !== epoch)+ ) {+ return;+ }+ this.codecAnswerWaiter = null;+ waiter?.resolve(accepted);+ }++ private async runCodecPreparation(+ request: CodecPreparationRequest,+ ): Promise<boolean> {+ const negotiation = await this.enqueueNegotiation(async () => {+ const transceiver = this.videoTransceiver;+ if (+ !this.ownsCodecPreparation(request) ||+ request.negotiationEpoch !== this.negotiationEpoch ||+ !transceiver ||+ !(await this.rollbackPendingLocalOffer()) ||+ !this.ownsCodecPreparation(request) ||+ request.negotiationEpoch !== this.negotiationEpoch ||+ !applyVideoCodecPreference(transceiver, request.videoCodec)+ ) {+ return null;+ }+ const answer = new Promise<boolean>((resolve) => {+ this.codecAnswerWaiter = {+ request,+ epoch: request.negotiationEpoch,+ resolve,+ };+ });+ if (+ !(await this.createOwnedOffer(+ false,+ request.negotiationEpoch,+ request.generation,+ request,+ ))+ ) {+ this.settleCodecAnswer(+ false,+ request.generation,+ request.negotiationEpoch,+ );+ return null;+ }+ return { answer };+ });+ if (!negotiation) {+ return false;+ }+ const accepted = await negotiation.answer;+ if (!accepted || !this.ownsCodecPreparation(request)) {+ return false;+ }+ this.desiredProfile = {+ ...this.desiredProfile,+ videoCodec: request.videoCodec,+ };+ this.appliedVideoProfile = this.appliedVideoProfile+ ? { ...this.appliedVideoProfile, videoCodec: request.videoCodec }+ : { ...this.desiredProfile };+ return true;+ }++ private ownsLocalOffer(+ epoch: number,+ request: CodecPreparationRequest | null,+ ): boolean {+ return (+ !this.disposed &&+ epoch === this.negotiationEpoch &&+ (request === null ||+ (request.negotiationEpoch === epoch &&+ this.ownsCodecPreparation(request)))+ );+ }++ private nextNegotiationEpoch(): number {+ this.ordinaryAnswerEpoch = null;+ this.negotiationEpoch += 1;+ return this.negotiationEpoch;+ }++ private ownsCodecPreparation(request: CodecPreparationRequest): boolean {+ return (+ !this.disposed &&+ !request.settled &&+ this.codecPreparation === request+ );+ }++ private finishCodecPreparation(+ request: CodecPreparationRequest,+ accepted: boolean,+ ): void {+ if (request.settled) {+ return;+ }+ request.settled = true;+ if (this.codecAnswerWaiter?.request === request) {+ const waiter = this.codecAnswerWaiter;+ this.codecAnswerWaiter = null;+ waiter.resolve(false);+ }+ if (this.codecPreparation === request) {+ this.codecPreparation = null;+ }+ request.resolve(accepted);+ }++ private async rollbackPendingLocalOffer(): Promise<boolean> {+ if (this.connection.signalingState === "stable") {+ return true;+ }+ if (this.connection.signalingState !== "have-local-offer") {+ return false;+ }+ try {+ await this.connection.setLocalDescription({ type: "rollback" });+ return (this.connection.signalingState as RTCSignalingState) === "stable";+ } catch {+ return false;+ }+ }+private async updateStats(): Promise<void> {if (this.disposed ||@@ -426,9 +786,8 @@ export class HostPeer {}}- private setError(error: unknown, fallback: string): void {- const message = error instanceof Error ? error.message : fallback;- this.snapshot = { ...this.snapshot, error: message || fallback };+ private setError(_error: unknown, fallback: string): void {+ this.snapshot = { ...this.snapshot, error: fallback };this.emit();}@@ -459,12 +818,9 @@ export class HostPeer {try {senderParameters = await configureVideoSender(sender, profile);videoWarning = senderParameterWarning(senderParameters);- } catch (error) {+ } catch {videoSucceeded = false;- videoWarning =- error instanceof Error && error.message- ? `应用发送参数失败:${error.message}`- : "应用发送参数失败";+ videoWarning = "应用发送参数失败";}}@@ -484,12 +840,9 @@ export class HostPeer {profile.screenAudioQuality,);audioWarning = audioSenderParameterWarning(audioSenderParameters);- } catch (error) {+ } catch {audioSucceeded = false;- audioWarning =- error instanceof Error && error.message- ? `应用音频发送参数失败:${error.message}`- : "应用音频发送参数失败";+ audioWarning = "应用音频发送参数失败";}} else {audioSenderParameters = null;@@ -562,7 +915,7 @@ export class HostPeer {return "浏览器持续报告其他画质限制";default:return this.limitationReason- ? `浏览器持续报告画质限制:${this.limitationReason}`+ ? "浏览器持续报告未分类的画质限制": null;}}diff --git a/src/client/webrtc/stats.ts b/src/client/webrtc/stats.tsindex 679fb362..3ecaff4c 100644--- a/src/client/webrtc/stats.ts+++ b/src/client/webrtc/stats.ts@@ -278,6 +278,13 @@ function mediaRecord(return narrowed.length === 1 ? narrowed[0]! : null;}+export function decodedVideoFrames(+ report: RTCStatsReport,+ selector: StatsMediaSelector | null = null,+): number | null {+ return numberValue(mediaRecord(report, "receive", selector), "framesDecoded");+}+function transportRecord(report: RTCStatsReport,media: StatsRecord | null,diff --git a/src/client/webrtc/video-codec-preference.ts b/src/client/webrtc/video-codec-preference.tsindex 1b038593..d2125edb 100644--- a/src/client/webrtc/video-codec-preference.ts+++ b/src/client/webrtc/video-codec-preference.ts@@ -12,11 +12,16 @@ export function applyVideoCodecPreference(preference: VideoCodecPreference | undefined,): boolean {const resolvedPreference = preference ?? "automatic";- if (- resolvedPreference === "automatic" ||- typeof transceiver.setCodecPreferences !== "function"- ) {- return resolvedPreference === "automatic";+ if (typeof transceiver.setCodecPreferences !== "function") {+ return false;+ }+ if (resolvedPreference === "automatic") {+ try {+ transceiver.setCodecPreferences([]);+ return true;+ } catch {+ return false;+ }}const codecs = videoCodecs();const mimeType = `video/${resolvedPreference}`;diff --git a/src/client/webrtc/viewer-peer.ts b/src/client/webrtc/viewer-peer.tsindex 27d060ac..c1b07645 100644--- a/src/client/webrtc/viewer-peer.ts+++ b/src/client/webrtc/viewer-peer.ts@@ -1,4 +1,8 @@-import type { IceConfig, SignalPayload } from "../../shared/protocol";+import type {+ CodecTransitionGeneration,+ IceConfig,+ SignalPayload,+} from "../../shared/protocol";import {EMPTY_METRICS,type PeerSnapshot,@@ -6,9 +10,11 @@ import {import {collectConnectionMetrics,createStatsAccumulator,+ decodedVideoFrames,type StatsAccumulator,} from "./stats";import { preferScreenAudioStereo } from "./screen-audio-sdp";+import { observeDecodedFrameProof } from "../media/decoded-frame-proof";const MAX_PENDING_CANDIDATES = 64;const MAX_AUTOMATIC_RECOVERY_REQUESTS = 2;@@ -29,6 +35,7 @@ interface ViewerPeerEvents {) => boolean;onStream: (stream: MediaStream) => void;onUpdate: (snapshot: PeerSnapshot) => void;+ onFirstDecodedFrame?: (connectionId: string) => boolean;onRecoveryExhausted?: (parentPeerId: string,connectionId: string,@@ -47,6 +54,7 @@ export class ViewerPeer {private statsAccumulator: StatsAccumulator = createStatsAccumulator();private statsTimer: number | null = null;private statsInFlightConnection: RTCPeerConnection | null = null;+ private stopDecodedFrameObserver: (() => void) | null = null;private disconnectTimer: number | null = null;private initialConnectionTimer: number | null = null;private recoveryTimer: number | null = null;@@ -56,6 +64,10 @@ export class ViewerPeer {private disposed = false;private currentIceConfig: PeerIceConfig;private snapshot: PeerSnapshot | null = null;+ private descriptionTail: Promise<void> = Promise.resolve();+ private latestCodecNegotiationGeneration:+ | CodecTransitionGeneration+ | null = null;constructor(iceConfig: PeerIceConfig,@@ -71,101 +83,34 @@ export class ViewerPeer {if (this.disposed) {return;}- let operationConnection: RTCPeerConnection | null = null;- let operationConnectionId: string | null = null;-- try {- if (payload.kind === "description") {- if (payload.description.type !== "offer") {- return;- }- if (- !this.connection ||- this.connectionId !== payload.connectionId ||- this.parentPeerId !== parentPeerId- ) {- this.replaceConnection(parentPeerId, payload.connectionId);- }- const connection = this.connection;- if (!connection) {- return;- }- const connectionId = payload.connectionId;- operationConnection = connection;- operationConnectionId = connectionId;- await connection.setRemoteDescription(payload.description);- if (!this.isCurrentConnection(connection, connectionId)) {- return;- }- await this.flushCandidates(connection, connectionId);- if (!this.isCurrentConnection(connection, connectionId)) {- return;- }- const answer = preferScreenAudioStereo(await connection.createAnswer());- if (!this.isCurrentConnection(connection, connectionId)) {- return;- }- await connection.setLocalDescription(answer);- if (!this.isCurrentConnection(connection, connectionId)) {- return;- }- if (!connection.localDescription) {- throw new Error("Local description was not created");- }- if (!this.events.sendSignal(parentPeerId, {- kind: "description",- connectionId,- description: {- type: "answer",- sdp: connection.localDescription.sdp,- },- })) {- throw new Error("Signaling is unavailable while sending the answer");- }- this.offerRecoveryAttempts = 0;- this.scheduleInitialConnectionDeadline(connection, connectionId);- } else if (- this.connection &&- this.parentPeerId === parentPeerId &&- this.connectionId === payload.connectionId &&- this.connection.remoteDescription- ) {- const connection = this.connection;- const connectionId = payload.connectionId;- operationConnection = connection;- operationConnectionId = connectionId;- await connection.addIceCandidate(payload.candidate);- if (!this.isCurrentConnection(connection, connectionId)) {- return;- }- } else {- this.queueCandidate(payload.connectionId, payload.candidate);+ if (payload.kind === "description") {+ if (payload.description.type !== "offer") {+ return;}- } catch (error) {if (- !operationConnection ||- operationConnectionId === null ||- !this.isCurrentConnection(operationConnection, operationConnectionId)+ !this.connection ||+ this.connectionId !== payload.connectionId ||+ this.parentPeerId !== parentPeerId) {+ this.replaceConnection(parentPeerId, payload.connectionId);+ }+ const connection = this.connection;+ if (!connection) {return;}- this.setError(error, "处理分享端信令失败");- if (- payload.kind === "description" &&- this.offerRecoveryAttempts < 1 &&- this.events.sendRestartRequest(- parentPeerId,- operationConnectionId,- true,- )- ) {- this.offerRecoveryAttempts += 1;- this.automaticRecoveryRequests = MAX_AUTOMATIC_RECOVERY_REQUESTS;- this.scheduleRecoveryDeadline();- } else if (payload.kind === "description") {- this.reportRecoveryExhausted();+ const generation = payload.negotiationGeneration;+ if (generation !== null) {+ const latest = this.latestCodecNegotiationGeneration;+ if (latest !== null && generation <= latest) {+ return;+ }+ this.latestCodecNegotiationGeneration = generation;}+ return this.enqueueDescription(() =>+ this.acceptDescription(parentPeerId, connection, payload),+ );}+ await this.acceptCandidate(parentPeerId, payload);}updateIceConfig(iceConfig: IceConfig): void {@@ -223,6 +168,11 @@ export class ViewerPeer {return this.connection?.connectionState === "connected";}+ stopDecodedFrameProof(): void {+ this.stopDecodedFrameObserver?.();+ this.stopDecodedFrameObserver = null;+ }+dispose(): void {if (this.disposed) {return;@@ -243,6 +193,8 @@ export class ViewerPeer {}this.parentPeerId = parentPeerId;this.connectionId = connectionId;+ this.descriptionTail = Promise.resolve();+ this.latestCodecNegotiationGeneration = null;this.remoteStream = new MediaStream();this.statsAccumulator = createStatsAccumulator();@@ -304,9 +256,123 @@ export class ViewerPeer {this.statsTimer = window.setInterval(() => {void this.updateStats(connection, connectionId);}, 2_000);+ if (this.events.onFirstDecodedFrame) {+ this.stopDecodedFrameObserver = observeDecodedFrameProof({+ readFramesDecoded: async () => {+ const track = this.remoteStream.getVideoTracks()[0];+ return decodedVideoFrames(+ await connection.getStats(),+ track ? { trackIdentifier: track.id } : null,+ );+ },+ owns: () => this.isCurrentConnection(connection, connectionId),+ onProof: () =>+ this.events.onFirstDecodedFrame?.(connectionId) ?? true,+ });+ }this.emit();}+ private enqueueDescription(work: () => Promise<void>): Promise<void> {+ const result = this.descriptionTail.then(work, work);+ this.descriptionTail = result.catch(() => undefined);+ return result;+ }++ private async acceptDescription(+ parentPeerId: string,+ connection: RTCPeerConnection,+ payload: Extract<SignalPayload, { kind: "description" }>,+ ): Promise<void> {+ const connectionId = payload.connectionId;+ const generation = payload.negotiationGeneration;+ try {+ await connection.setRemoteDescription(payload.description);+ if (!this.ownsDescription(connection, connectionId, generation)) {+ return;+ }+ await this.flushCandidates(connection, connectionId);+ if (!this.ownsDescription(connection, connectionId, generation)) {+ return;+ }+ const answer = preferScreenAudioStereo(await connection.createAnswer());+ if (!this.ownsDescription(connection, connectionId, generation)) {+ return;+ }+ await connection.setLocalDescription(answer);+ if (!this.ownsDescription(connection, connectionId, generation)) {+ return;+ }+ if (!connection.localDescription) {+ throw new Error("Local description was not created");+ }+ if (!this.events.sendSignal(parentPeerId, {+ kind: "description",+ connectionId,+ negotiationGeneration: generation,+ description: {+ type: "answer",+ sdp: connection.localDescription.sdp,+ },+ })) {+ throw new Error("Signaling is unavailable while sending the answer");+ }+ this.offerRecoveryAttempts = 0;+ this.scheduleInitialConnectionDeadline(connection, connectionId);+ } catch (error) {+ if (!this.ownsDescription(connection, connectionId, generation)) {+ return;+ }+ this.setError(error, "处理分享端信令失败");+ if (+ this.offerRecoveryAttempts < 1 &&+ this.events.sendRestartRequest(parentPeerId, connectionId, true)+ ) {+ this.offerRecoveryAttempts += 1;+ this.automaticRecoveryRequests = MAX_AUTOMATIC_RECOVERY_REQUESTS;+ this.scheduleRecoveryDeadline();+ } else {+ this.reportRecoveryExhausted();+ }+ }+ }++ private async acceptCandidate(+ parentPeerId: string,+ payload: Extract<SignalPayload, { kind: "candidate" }>,+ ): Promise<void> {+ if (+ !this.connection ||+ this.parentPeerId !== parentPeerId ||+ this.connectionId !== payload.connectionId ||+ !this.connection.remoteDescription+ ) {+ this.queueCandidate(payload.connectionId, payload.candidate);+ return;+ }+ const connection = this.connection;+ const connectionId = payload.connectionId;+ try {+ await connection.addIceCandidate(payload.candidate);+ } catch (error) {+ if (this.isCurrentConnection(connection, connectionId)) {+ this.setError(error, "处理分享端信令失败");+ }+ }+ }++ private ownsDescription(+ connection: RTCPeerConnection,+ connectionId: string,+ generation: CodecTransitionGeneration | null,+ ): boolean {+ return (+ this.isCurrentConnection(connection, connectionId) &&+ (generation === null ||+ this.latestCodecNegotiationGeneration === generation)+ );+ }+private handleConnectionState(state: RTCPeerConnectionState): void {if (state === "connected") {this.clearDisconnectTimer();@@ -555,6 +621,7 @@ export class ViewerPeer {private disposeConnection(): void {this.clearDisconnectTimer();this.clearInitialConnectionTimer();+ this.stopDecodedFrameProof();if (this.statsTimer !== null) {window.clearInterval(this.statsTimer);this.statsTimer = null;diff --git a/src/client/webrtc/viewer-relay.ts b/src/client/webrtc/viewer-relay.tsindex b156df94..60c936f9 100644--- a/src/client/webrtc/viewer-relay.ts+++ b/src/client/webrtc/viewer-relay.ts@@ -1,4 +1,5 @@import type {+ CodecTransitionGeneration,IceConfig,PreparedRouteCandidate,SignalPayload,@@ -192,6 +193,24 @@ export class ViewerRelay {return result.catch(() => false);}+ prepareVideoCodec(+ childPeerId: string,+ connectionId: string,+ generation: CodecTransitionGeneration,+ videoCodec: QualityProfile["videoCodec"],+ ): Promise<boolean> {+ const peer = this.peers.get(childPeerId);+ if (+ this.disposed ||+ !peer ||+ peer.connectionId !== connectionId ||+ !this.childPeerIds.includes(childPeerId)+ ) {+ return Promise.resolve(false);+ }+ return peer.prepareVideoCodec(generation, videoCodec);+ }+getSignalRouteRevision(fromPeerId: string,connectionId: string,diff --git a/src/server/codec-transition.ts b/src/server/codec-transition.tsnew file mode 100644index 00000000..d2ff57e9--- /dev/null+++ b/src/server/codec-transition.ts@@ -0,0 +1,1247 @@+import type {+ ClientMessage,+ CodecPreparationBinding,+ CodecProofBinding,+ CodecTransitionGeneration,+ ResumeAttempt,+ ServerMessage,+ VideoCodecPreference,+} from "../shared/protocol.js";+import type {+ CodecRouteSnapshot,+ CodecRouteTarget,+} from "./hybrid-media-router.js";++const DEFAULT_CODEC_TRANSITION_TIMEOUT_MS = 20_000;++type PreparedMessage = Extract<+ ClientMessage,+ { type: "video-codec-prepared" }+>;+type ProofMessage = Extract<ClientMessage, { type: "video-codec-proof" }>;+type ResultMessage = Extract<ServerMessage, { type: "video-codec-result" }>;+type TransitionFailure = NonNullable<ResultMessage["failure"]>;+type FrozenTarget = CodecRouteTarget;++interface Preparation {+ ownerSessionId: string;+ binding: CodecPreparationBinding;+}++interface Transaction {+ hostSessionId: string;+ shareGeneration: string;+ generation: CodecTransitionGeneration;+ requested: VideoCodecPreference;+ previous: VideoCodecPreference;+ rollback: boolean;+ requiresSfuReplacement: boolean;+ sfuOperationPending: boolean;+ phase:+ | "initializing"+ | "preparing"+ | "prepared"+ | "awaiting-source"+ | "proving"+ | "rollback-prepared"+ | "failed";+ failure: TransitionFailure | null;+ targets: Map<string, FrozenTarget>;+ pendingPreparations: Map<string, Preparation>;+ pendingProofs: Set<string>;+ proofRevision: number | null;+ timer?: NodeJS.Timeout;+}++interface PendingResume {+ hostSessionId: string;+ shareGeneration: string;+ codecGeneration: CodecTransitionGeneration | null;+ resumeAttempt: ResumeAttempt;+ deadlineAtMs: number;+ timer: NodeJS.Timeout;+}++export interface CodecTransitionCoordinatorOptions {+ snapshot: (roomId: string) => CodecRouteSnapshot | null;+ sendToSession: (sessionId: string, message: ServerMessage) => void;+ commitCodec: (roomId: string, videoCodec: VideoCodecPreference) => void;+ authorizeResume: (+ roomId: string,+ hostSessionId: string,+ shareGeneration: string,+ codecGeneration: CodecTransitionGeneration | null,+ resumeAttempt: ResumeAttempt,+ ) => void;+ confirmSourceEnabled: (+ roomId: string,+ hostSessionId: string,+ shareGeneration: string,+ codecGeneration: CodecTransitionGeneration | null,+ resumeAttempt: ResumeAttempt,+ ) => boolean;+ restoreAuthoritativePause: (+ roomId: string,+ hostSessionId: string,+ shareGeneration: string,+ codecGeneration: CodecTransitionGeneration | null,+ resumeAttempt: ResumeAttempt | null,+ ) => void;+ returnTargetsToRouteWait: (+ roomId: string,+ viewerPeerIds: readonly string[],+ ) => void;+ beginSfuReplacement: (input: {+ roomId: string;+ hostSessionId: string;+ generation: CodecTransitionGeneration;+ videoCodec: VideoCodecPreference;+ timeoutMs: number;+ }) => Promise<CodecRouteSnapshot | null>;+ parkSfuReplacement: (+ roomId: string,+ generation: CodecTransitionGeneration,+ ) => boolean;+ beginSfuProof: (+ roomId: string,+ generation: CodecTransitionGeneration,+ timeoutMs: number,+ ) => boolean;+ abortSfuReplacement: (+ roomId: string,+ generation: CodecTransitionGeneration,+ ) => void;+ releaseRoutePause: (roomId: string) => void;+ timeoutMs?: number;+ createGeneration?: () => CodecTransitionGeneration;+ createResumeAttempt?: () => ResumeAttempt;+ now?: () => number;+}++export class CodecTransitionCoordinator {+ private readonly rooms = new Map<string, Transaction>();+ private readonly timeoutMs: number;+ private readonly createGeneration: () => CodecTransitionGeneration;+ private readonly createResumeAttempt: () => ResumeAttempt;+ private readonly now: () => number;+ private latestGeneration = 0;+ private latestResumeAttempt = 0;+ private readonly pendingResumes = new Map<string, PendingResume>();+ private readonly revalidatingRoomIds = new Set<string>();+ private readonly deferredRevalidationRoomIds = new Set<string>();++ constructor(private readonly options: CodecTransitionCoordinatorOptions) {+ this.timeoutMs = options.timeoutMs ?? DEFAULT_CODEC_TRANSITION_TIMEOUT_MS;+ if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0) {+ throw new Error("Codec transition timeout must be a positive integer");+ }+ this.createGeneration =+ options.createGeneration ?? (() => this.latestGeneration + 1);+ this.createResumeAttempt =+ options.createResumeAttempt ?? (() => this.latestResumeAttempt + 1);+ this.now = options.now ?? Date.now;+ }++ start(input: {+ roomId: string;+ hostSessionId: string;+ shareGeneration: string;+ requested: VideoCodecPreference;+ previous: VideoCodecPreference;+ }): "started" | "committed" | "busy" | "unavailable" {+ if (this.rooms.has(input.roomId)) {+ return "busy";+ }+ const snapshot = this.options.snapshot(input.roomId);+ if (!snapshot) {+ return "unavailable";+ }+ if (snapshot.targets.length === 0) {+ this.options.commitCodec(input.roomId, input.requested);+ this.sendResult(input.hostSessionId, {+ generation: this.allocateGeneration(),+ videoCodec: input.requested,+ status: "committed",+ failure: null,+ });+ return "committed";+ }+ const transaction: Transaction = {+ hostSessionId: input.hostSessionId,+ shareGeneration: input.shareGeneration,+ generation: this.allocateGeneration(),+ requested: input.requested,+ previous: input.previous,+ rollback: false,+ requiresSfuReplacement: snapshot.targets.some(isSfuTarget),+ sfuOperationPending: false,+ phase: "initializing",+ failure: null,+ targets: new Map(),+ pendingPreparations: new Map(),+ pendingProofs: new Set(),+ proofRevision: null,+ };+ this.rooms.set(input.roomId, transaction);+ this.beginTransactionPreparation(input.roomId, transaction, snapshot);+ return "started";+ }++ prepared(+ roomId: string,+ senderSessionId: string,+ message: PreparedMessage,+ ): void {+ let transaction = this.rooms.get(roomId);+ if (!this.messageOwns(transaction, message)) {+ return;+ }+ this.revalidate(roomId, transaction);+ transaction = this.rooms.get(roomId);+ if (!this.messageOwns(transaction, message)) {+ return;+ }+ const key = preparationKey(message.binding);+ const expected = transaction.pendingPreparations.get(key);+ if (+ transaction.phase !== "preparing" ||+ !expected ||+ expected.ownerSessionId !== senderSessionId ||+ !samePreparationBinding(expected.binding, message.binding)+ ) {+ return;+ }+ if (!message.accepted) {+ this.preparationFailed(roomId, transaction);+ return;+ }+ transaction.pendingPreparations.delete(key);+ if (transaction.pendingPreparations.size === 0) {+ this.finishPreparation(roomId, transaction);+ }+ }++ requestResume(input: {+ roomId: string;+ hostSessionId: string;+ shareGeneration: string;+ }): "normal" | "started-proof" | "busy" {+ if (this.pendingResumes.has(input.roomId)) {+ return "busy";+ }+ let transaction = this.rooms.get(input.roomId);+ if (!transaction) {+ this.beginResumeAttempt(input, null);+ return "normal";+ }+ if (+ transaction.hostSessionId !== input.hostSessionId ||+ transaction.shareGeneration !== input.shareGeneration ||+ (transaction.phase !== "prepared" &&+ transaction.phase !== "rollback-prepared")+ ) {+ return "busy";+ }+ this.revalidate(input.roomId, transaction);+ transaction = this.rooms.get(input.roomId);+ if (+ !transaction ||+ transaction.hostSessionId !== input.hostSessionId ||+ transaction.shareGeneration !== input.shareGeneration ||+ (transaction.phase !== "prepared" &&+ transaction.phase !== "rollback-prepared")+ ) {+ return "busy";+ }+ if (transaction.targets.size === 0) {+ this.finishProof(input.roomId, transaction, false);+ this.beginResumeAttempt(input, null);+ return "started-proof";+ }+ transaction.phase = "awaiting-source";+ transaction.proofRevision = null;+ transaction.pendingProofs = new Set(transaction.targets.keys());+ this.beginResumeAttempt(input, transaction.generation);+ return "started-proof";+ }++ sourceEnabled(input: {+ roomId: string;+ hostSessionId: string;+ shareGeneration: string;+ codecGeneration: CodecTransitionGeneration | null;+ resumeAttempt: ResumeAttempt;+ }): boolean {+ const pending = this.pendingResumes.get(input.roomId);+ if (!sameResumeAttempt(pending, input)) {+ return false;+ }+ if (pending.deadlineAtMs <= this.now()) {+ this.resumeAttemptExpired(input.roomId, pending);+ return false;+ }++ if (input.codecGeneration === null) {+ if (+ !this.options.confirmSourceEnabled(+ input.roomId,+ input.hostSessionId,+ input.shareGeneration,+ null,+ input.resumeAttempt,+ )+ ) {+ return false;+ }+ this.clearPendingResume(input.roomId, pending);+ this.options.releaseRoutePause(input.roomId);+ return true;+ }++ let transaction = this.rooms.get(input.roomId);+ if (+ !transaction ||+ transaction.phase !== "awaiting-source" ||+ transaction.generation !== input.codecGeneration+ ) {+ return false;+ }+ this.revalidate(input.roomId, transaction);+ transaction = this.rooms.get(input.roomId);+ const currentPending = this.pendingResumes.get(input.roomId);+ if (+ !transaction ||+ transaction.phase !== "awaiting-source" ||+ transaction.generation !== input.codecGeneration ||+ !sameResumeAttempt(currentPending, input)+ ) {+ return false;+ }+ const remainingMs = currentPending.deadlineAtMs - this.now();+ if (remainingMs <= 0) {+ this.resumeAttemptExpired(input.roomId, currentPending);+ return false;+ }+ if (+ !this.options.confirmSourceEnabled(+ input.roomId,+ input.hostSessionId,+ input.shareGeneration,+ input.codecGeneration,+ input.resumeAttempt,+ )+ ) {+ return false;+ }+ if (transaction.targets.size === 0) {+ this.finishProof(input.roomId, transaction);+ return true;+ }+ if (+ transaction.sfuOperationPending &&+ !this.options.beginSfuProof(+ input.roomId,+ transaction.generation,+ Math.max(1, Math.ceil(remainingMs)),+ )+ ) {+ this.proofFailed(input.roomId, transaction);+ return false;+ }+ transaction.phase = "proving";+ transaction.proofRevision = null;+ transaction.pendingProofs = new Set(transaction.targets.keys());+ this.revalidate(input.roomId, transaction);+ const proving = this.rooms.get(input.roomId);+ if (proving === transaction && proving.phase === "proving") {+ if (proving.targets.size === 0) {+ this.finishProof(input.roomId, proving);+ } else {+ this.issueProofBatch(input.roomId, proving);+ }+ }+ return true;+ }++ pause(input: {+ roomId: string;+ hostSessionId: string;+ shareGeneration: string;+ }): void {+ const pending = this.pendingResumes.get(input.roomId);+ if (+ pending &&+ (pending.hostSessionId !== input.hostSessionId ||+ pending.shareGeneration !== input.shareGeneration)+ ) {+ return;+ }+ if (pending) {+ this.clearPendingResume(input.roomId, pending);+ }+ const transaction = this.rooms.get(input.roomId);+ if (+ !transaction ||+ transaction.hostSessionId !== input.hostSessionId ||+ transaction.shareGeneration !== input.shareGeneration ||+ (transaction.phase !== "awaiting-source" &&+ transaction.phase !== "proving")+ ) {+ return;+ }+ transaction.pendingProofs.clear();+ transaction.proofRevision = null;+ if (transaction.sfuOperationPending) {+ this.options.parkSfuReplacement(input.roomId, transaction.generation);+ }+ transaction.phase = transaction.rollback+ ? "rollback-prepared"+ : "prepared";+ }++ proof(roomId: string, senderSessionId: string, message: ProofMessage): void {+ let transaction = this.rooms.get(roomId);+ let pendingResume = this.pendingResumes.get(roomId);+ if (+ !this.messageOwns(transaction, message) ||+ !pendingResume ||+ pendingResume.codecGeneration !== message.generation ||+ pendingResume.resumeAttempt !== message.resumeAttempt ||+ transaction.phase !== "proving"+ ) {+ return;+ }+ this.revalidate(roomId, transaction);+ transaction = this.rooms.get(roomId);+ pendingResume = this.pendingResumes.get(roomId);+ if (+ !this.messageOwns(transaction, message) ||+ !pendingResume ||+ pendingResume.codecGeneration !== message.generation ||+ pendingResume.resumeAttempt !== message.resumeAttempt ||+ transaction.phase !== "proving" ||+ transaction.proofRevision !== message.routeRevision+ ) {+ return;+ }+ const target = [...transaction.targets.values()].find(+ (candidate) => candidate.viewerSessionId === senderSessionId,+ );+ if (+ !target ||+ !transaction.pendingProofs.has(target.viewerPeerId) ||+ !target.proofReady ||+ target.routeRevision !== message.routeRevision ||+ !sameProofBinding(target.proofBinding, message.binding)+ ) {+ return;+ }+ const expected = expectedActualCodec(transaction);+ if (expected && message.evidence.actualCodec !== expected) {+ this.proofFailed(roomId, transaction);+ return;+ }+ transaction.pendingProofs.delete(target.viewerPeerId);+ if (transaction.pendingProofs.size === 0) {+ this.finishProof(roomId, transaction);+ }+ }++ participantChanged(roomId: string): void {+ if (this.revalidatingRoomIds.has(roomId)) {+ this.deferredRevalidationRoomIds.add(roomId);+ return;+ }+ const transaction = this.rooms.get(roomId);+ if (!transaction || transaction.phase === "failed") {+ return;+ }+ this.revalidate(roomId, transaction);+ const current = this.rooms.get(roomId);+ if (current !== transaction) {+ return;+ }+ if (+ transaction.targets.size === 0 &&+ transaction.phase !== "initializing" &&+ transaction.phase !== "awaiting-source"+ ) {+ this.finishProof(+ roomId,+ transaction,+ transaction.phase === "proving",+ );+ return;+ }+ if (+ transaction.phase === "preparing" &&+ transaction.pendingPreparations.size === 0+ ) {+ this.finishPreparation(roomId, transaction);+ } else if (transaction.phase === "proving") {+ this.issueProofBatch(roomId, transaction);+ if (transaction.pendingProofs.size === 0) {+ this.finishProof(roomId, transaction);+ }+ }+ }++ clearRoom(roomId: string): void {+ this.deferredRevalidationRoomIds.delete(roomId);+ this.clearPendingResume(roomId);+ const transaction = this.rooms.get(roomId);+ if (!transaction) {+ return;+ }+ this.clearDeadline(transaction);+ this.abortPendingSfuOperation(roomId, transaction);+ this.rooms.delete(roomId);+ }++ blocksResume(roomId: string): boolean {+ return this.rooms.has(roomId) || this.pendingResumes.has(roomId);+ }++ invalidateHostSession(roomId: string, nextHostSessionId?: string): void {+ const pendingResume = this.pendingResumes.get(roomId);+ this.clearPendingResume(roomId, pendingResume);+ const transaction = this.rooms.get(roomId);+ if (!transaction) {+ if (pendingResume && nextHostSessionId) {+ this.options.restoreAuthoritativePause(+ roomId,+ nextHostSessionId,+ pendingResume.shareGeneration,+ null,+ null,+ );+ }+ return;+ }+ this.clearDeadline(transaction);+ this.abortPendingSfuOperation(roomId, transaction);+ transaction.pendingPreparations.clear();+ transaction.pendingProofs.clear();+ transaction.proofRevision = null;+ transaction.phase = "failed";+ transaction.failure = "stale-binding";+ if (nextHostSessionId) {+ transaction.hostSessionId = nextHostSessionId;+ }+ this.options.restoreAuthoritativePause(+ roomId,+ transaction.hostSessionId,+ transaction.shareGeneration,+ transaction.generation,+ null,+ );+ this.sendResult(transaction.hostSessionId, {+ generation: transaction.generation,+ videoCodec: transaction.previous,+ status: "failed",+ failure: "stale-binding",+ });+ }++ close(): void {+ for (const [roomId, transaction] of this.rooms) {+ this.clearDeadline(transaction);+ this.abortPendingSfuOperation(roomId, transaction);+ }+ for (const pending of this.pendingResumes.values()) {+ clearTimeout(pending.timer);+ }+ this.pendingResumes.clear();+ this.rooms.clear();+ this.revalidatingRoomIds.clear();+ this.deferredRevalidationRoomIds.clear();+ }++ private beginTransactionPreparation(+ roomId: string,+ transaction: Transaction,+ snapshot: CodecRouteSnapshot,+ ): void {+ transaction.requiresSfuReplacement = snapshot.targets.some(isSfuTarget);+ transaction.sfuOperationPending = false;+ transaction.phase = transaction.requiresSfuReplacement+ ? "initializing"+ : "preparing";+ transaction.pendingPreparations.clear();+ transaction.pendingProofs.clear();+ transaction.proofRevision = null;+ this.armDeadline(roomId, transaction, () =>+ this.preparationFailed(roomId, transaction),+ );+ if (!transaction.requiresSfuReplacement) {+ transaction.targets = freezeTargets(snapshot);+ this.sendPreparationRequests(roomId, transaction);+ return;+ }+ const generation = transaction.generation;+ transaction.sfuOperationPending = true;+ const videoCodec = transaction.rollback+ ? transaction.previous+ : transaction.requested;+ void this.options+ .beginSfuReplacement({+ roomId,+ hostSessionId: transaction.hostSessionId,+ generation,+ videoCodec,+ timeoutMs: this.timeoutMs,+ })+ .then((preparedSnapshot) => {+ const current = this.rooms.get(roomId);+ if (+ current !== transaction ||+ transaction.generation !== generation ||+ transaction.phase !== "initializing"+ ) {+ this.options.abortSfuReplacement(roomId, generation);+ return;+ }+ if (!preparedSnapshot || !preparedSnapshot.targets.some(isSfuTarget)) {+ this.abortPendingSfuOperation(roomId, transaction);+ const currentSnapshot = this.options.snapshot(roomId);+ if (+ !currentSnapshot ||+ currentSnapshot.targets.some(isSfuTarget)+ ) {+ this.preparationFailed(roomId, transaction);+ return;+ }+ transaction.requiresSfuReplacement = false;+ transaction.targets = freezeTargets(currentSnapshot);+ transaction.phase = "preparing";+ this.sendPreparationRequests(roomId, transaction);+ return;+ }+ transaction.targets = freezeTargets(preparedSnapshot);+ transaction.phase = "preparing";+ this.sendPreparationRequests(roomId, transaction);+ })+ .catch(() => {+ const current = this.rooms.get(roomId);+ if (+ current === transaction &&+ transaction.generation === generation &&+ transaction.phase === "initializing"+ ) {+ this.preparationFailed(roomId, transaction);+ } else {+ this.options.abortSfuReplacement(roomId, generation);+ }+ });+ }++ private sendPreparationRequests(+ roomId: string,+ transaction: Transaction,+ ): void {+ transaction.pendingPreparations = preparationsFor(transaction.targets);+ if (transaction.pendingPreparations.size === 0) {+ if (transaction.targets.size === 0) {+ this.finishProof(roomId, transaction, false);+ } else {+ this.finishPreparation(roomId, transaction);+ }+ return;+ }+ const videoCodec = transaction.rollback+ ? transaction.previous+ : transaction.requested;+ for (const preparation of transaction.pendingPreparations.values()) {+ if (preparation.binding.kind === "sfu") {+ continue;+ }+ this.options.sendToSession(preparation.ownerSessionId, {+ type: "video-codec-prepare",+ shareGeneration: transaction.shareGeneration,+ generation: transaction.generation,+ videoCodec,+ binding: preparation.binding,+ });+ }+ }++ private finishPreparation(roomId: string, transaction: Transaction): void {+ if (+ this.rooms.get(roomId) !== transaction ||+ transaction.phase !== "preparing"+ ) {+ return;+ }+ if (+ transaction.sfuOperationPending &&+ !this.options.parkSfuReplacement(roomId, transaction.generation)+ ) {+ this.preparationFailed(roomId, transaction);+ return;+ }+ this.clearDeadline(transaction);+ transaction.phase = transaction.rollback ? "rollback-prepared" : "prepared";+ this.sendResult(transaction.hostSessionId, {+ generation: transaction.generation,+ videoCodec: transaction.rollback+ ? transaction.previous+ : transaction.requested,+ status: transaction.rollback ? "rollback-prepared" : "prepared",+ failure: transaction.rollback ? transaction.failure : null,+ });+ }++ private preparationFailed(roomId: string, transaction: Transaction): void {+ if (this.rooms.get(roomId) !== transaction) {+ return;+ }+ this.clearDeadline(transaction);+ this.clearPendingResume(roomId);+ this.abortPendingSfuOperation(roomId, transaction);+ if (transaction.rollback) {+ this.failClosed(roomId, transaction, "rollback-failed");+ return;+ }+ transaction.failure = "preparation-failed";+ transaction.rollback = true;+ transaction.generation = this.allocateGeneration();+ transaction.targets.clear();+ this.beginTransactionPreparation(+ roomId,+ transaction,+ this.options.snapshot(roomId) ?? { revision: 0, targets: [] },+ );+ }++ private proofFailed(roomId: string, transaction: Transaction): void {+ if (this.rooms.get(roomId) !== transaction) {+ return;+ }+ this.clearDeadline(transaction);+ const pendingResume = this.pendingResumes.get(roomId);+ this.options.restoreAuthoritativePause(+ roomId,+ transaction.hostSessionId,+ transaction.shareGeneration,+ transaction.generation,+ pendingResume?.resumeAttempt ?? null,+ );+ this.clearPendingResume(roomId, pendingResume);+ this.abortPendingSfuOperation(roomId, transaction);+ if (transaction.rollback) {+ this.failClosed(roomId, transaction, "rollback-failed");+ return;+ }+ transaction.failure = "proof-failed";+ transaction.rollback = true;+ transaction.generation = this.allocateGeneration();+ transaction.targets.clear();+ this.beginTransactionPreparation(+ roomId,+ transaction,+ this.options.snapshot(roomId) ?? { revision: 0, targets: [] },+ );+ }++ private finishProof(+ roomId: string,+ transaction: Transaction,+ releaseRoutePause = true,+ ): void {+ if (this.rooms.get(roomId) !== transaction) {+ return;+ }+ this.clearDeadline(transaction);+ this.clearPendingResume(roomId);+ const committed = transaction.rollback+ ? transaction.previous+ : transaction.requested;+ this.options.commitCodec(roomId, committed);+ this.rooms.delete(roomId);+ this.sendResult(transaction.hostSessionId, {+ generation: transaction.generation,+ videoCodec: committed,+ status: "committed",+ failure: transaction.rollback ? transaction.failure : null,+ });+ if (releaseRoutePause) {+ this.options.releaseRoutePause(roomId);+ }+ }++ private failClosed(+ roomId: string,+ transaction: Transaction,+ failure: TransitionFailure,+ ): void {+ if (this.rooms.get(roomId) !== transaction) {+ return;+ }+ this.clearDeadline(transaction);+ this.clearPendingResume(roomId);+ this.abortPendingSfuOperation(roomId, transaction);+ transaction.phase = "failed";+ transaction.failure = failure;+ transaction.pendingPreparations.clear();+ transaction.pendingProofs.clear();+ transaction.proofRevision = null;+ this.sendResult(transaction.hostSessionId, {+ generation: transaction.generation,+ videoCodec: transaction.previous,+ status: "failed",+ failure,+ });+ }++ private revalidate(roomId: string, transaction: Transaction): void {+ if (this.revalidatingRoomIds.has(roomId)) {+ this.deferredRevalidationRoomIds.add(roomId);+ return;+ }+ this.revalidatingRoomIds.add(roomId);+ try {+ this.revalidateCurrentSnapshot(roomId, transaction);+ } finally {+ this.revalidatingRoomIds.delete(roomId);+ }+ if (this.deferredRevalidationRoomIds.delete(roomId)) {+ this.participantChanged(roomId);+ }+ }++ private revalidateCurrentSnapshot(+ roomId: string,+ transaction: Transaction,+ ): void {+ if (+ transaction.phase === "initializing" ||+ transaction.phase === "failed"+ ) {+ return;+ }+ const current = this.options.snapshot(roomId);+ if (!current) {+ this.invalidateAllTargets(roomId, transaction);+ return;+ }+ let changed = false;+ let lostSfuTarget = false;+ const currentByViewer = new Map(+ current.targets.map((target) => [target.viewerPeerId, target]),+ );+ const invalidatedViewerPeerIds: string[] = [];+ for (const [viewerPeerId, frozen] of transaction.targets) {+ const candidate = currentByViewer.get(viewerPeerId);+ if (!candidate || !sameTarget(frozen, candidate)) {+ transaction.targets.delete(viewerPeerId);+ transaction.pendingProofs.delete(viewerPeerId);+ invalidatedViewerPeerIds.push(viewerPeerId);+ lostSfuTarget ||= isSfuTarget(frozen);+ changed = true;+ continue;+ }+ if (+ frozen.routeRevision !== candidate.routeRevision ||+ frozen.proofReady !== candidate.proofReady+ ) {+ frozen.routeRevision = candidate.routeRevision;+ frozen.proofReady = candidate.proofReady;+ changed = true;+ }+ }+ if (+ transaction.sfuOperationPending &&+ [...transaction.targets.values()].some(+ (target) => isSfuTarget(target) && target.proofReady,+ )+ ) {+ transaction.sfuOperationPending = false;+ }+ if (lostSfuTarget && transaction.sfuOperationPending) {+ this.abortPendingSfuOperation(roomId, transaction);+ transaction.requiresSfuReplacement = false;+ }+ const pendingSfuSubtree = transaction.sfuOperationPending+ ? pendingSfuSubtreeViewerPeerIds(transaction.targets)+ : new Set<string>();+ if (transaction.phase === "proving") {+ for (const [viewerPeerId, target] of transaction.targets) {+ if (target.proofReady || pendingSfuSubtree.has(viewerPeerId)) continue;+ transaction.targets.delete(viewerPeerId);+ transaction.pendingProofs.delete(viewerPeerId);+ invalidatedViewerPeerIds.push(viewerPeerId);+ changed = true;+ }+ }+ if (transaction.phase === "preparing") {+ const stillRequired = preparationsFor(transaction.targets);+ for (const [key, preparation] of transaction.pendingPreparations) {+ const currentPreparation = stillRequired.get(key);+ if (+ !currentPreparation ||+ currentPreparation.ownerSessionId !== preparation.ownerSessionId+ ) {+ transaction.pendingPreparations.delete(key);+ }+ }+ }+ if (invalidatedViewerPeerIds.length > 0) {+ this.options.returnTargetsToRouteWait(roomId, invalidatedViewerPeerIds);+ this.refreshRetainedTargets(roomId, transaction);+ }+ if (transaction.phase === "proving" && changed) {+ transaction.proofRevision = null;+ transaction.pendingProofs = new Set(transaction.targets.keys());+ this.issueProofBatch(roomId, transaction);+ }+ }++ private invalidateAllTargets(+ roomId: string,+ transaction: Transaction,+ ): void {+ const invalidated = [...transaction.targets.keys()];+ const hadSfu = [...transaction.targets.values()].some(isSfuTarget);+ transaction.targets.clear();+ transaction.pendingPreparations.clear();+ transaction.pendingProofs.clear();+ transaction.proofRevision = null;+ if (invalidated.length > 0) {+ this.options.returnTargetsToRouteWait(roomId, invalidated);+ }+ if (hadSfu && transaction.sfuOperationPending) {+ this.abortPendingSfuOperation(roomId, transaction);+ transaction.requiresSfuReplacement = false;+ }+ }++ private refreshRetainedTargets(+ roomId: string,+ transaction: Transaction,+ ): void {+ const current = this.options.snapshot(roomId);+ if (!current) {+ return;+ }+ const currentByViewer = new Map(+ current.targets.map((target) => [target.viewerPeerId, target]),+ );+ for (const [viewerPeerId, frozen] of transaction.targets) {+ const candidate = currentByViewer.get(viewerPeerId);+ if (candidate && sameTarget(frozen, candidate)) {+ frozen.routeRevision = candidate.routeRevision;+ frozen.proofReady = candidate.proofReady;+ }+ }+ }++ private issueProofBatch(roomId: string, transaction: Transaction): void {+ const pendingResume = this.pendingResumes.get(roomId);+ if (+ transaction.phase !== "proving" ||+ !pendingResume ||+ pendingResume.hostSessionId !== transaction.hostSessionId ||+ pendingResume.shareGeneration !== transaction.shareGeneration ||+ pendingResume.codecGeneration !== transaction.generation ||+ transaction.targets.size === 0 ||+ [...transaction.targets.values()].some((target) => !target.proofReady)+ ) {+ return;+ }+ const revisions = new Set(+ [...transaction.targets.values()].map((target) => target.routeRevision),+ );+ if (revisions.size !== 1) {+ return;+ }+ const revision = revisions.values().next().value;+ if (revision === undefined || transaction.proofRevision === revision) {+ return;+ }+ transaction.proofRevision = revision;+ transaction.pendingProofs = new Set(transaction.targets.keys());+ const expectedCodec = expectedActualCodec(transaction);+ for (const target of transaction.targets.values()) {+ this.options.sendToSession(target.viewerSessionId, {+ type: "video-codec-proof-request",+ shareGeneration: transaction.shareGeneration,+ generation: transaction.generation,+ resumeAttempt: pendingResume.resumeAttempt,+ routeRevision: target.routeRevision,+ expectedCodec,+ binding: target.proofBinding,+ });+ }+ }++ private abortPendingSfuOperation(+ roomId: string,+ transaction: Transaction,+ ): void {+ if (!transaction.sfuOperationPending) return;+ transaction.sfuOperationPending = false;+ this.options.abortSfuReplacement(roomId, transaction.generation);+ }++ private beginResumeAttempt(+ input: {+ roomId: string;+ hostSessionId: string;+ shareGeneration: string;+ },+ codecGeneration: CodecTransitionGeneration | null,+ ): void {+ const resumeAttempt = this.allocateResumeAttempt();+ let pending!: PendingResume;+ const timer = setTimeout(+ () => this.resumeAttemptExpired(input.roomId, pending),+ this.timeoutMs,+ );+ pending = {+ hostSessionId: input.hostSessionId,+ shareGeneration: input.shareGeneration,+ codecGeneration,+ resumeAttempt,+ deadlineAtMs: this.now() + this.timeoutMs,+ timer,+ };+ this.pendingResumes.set(input.roomId, pending);+ this.options.authorizeResume(+ input.roomId,+ input.hostSessionId,+ input.shareGeneration,+ codecGeneration,+ resumeAttempt,+ );+ }++ private resumeAttemptExpired(roomId: string, pending: PendingResume): void {+ if (this.pendingResumes.get(roomId) !== pending) {+ return;+ }+ const transaction = this.rooms.get(roomId);+ if (+ transaction &&+ pending.codecGeneration === transaction.generation &&+ transaction.phase === "proving"+ ) {+ this.proofFailed(roomId, transaction);+ return;+ }+ this.options.restoreAuthoritativePause(+ roomId,+ pending.hostSessionId,+ pending.shareGeneration,+ pending.codecGeneration,+ pending.resumeAttempt,+ );+ this.clearPendingResume(roomId, pending);+ if (+ transaction &&+ pending.codecGeneration === transaction.generation &&+ transaction.phase === "awaiting-source"+ ) {+ transaction.pendingProofs.clear();+ transaction.proofRevision = null;+ transaction.phase = transaction.rollback+ ? "rollback-prepared"+ : "prepared";+ }+ }++ private clearPendingResume(+ roomId: string,+ expected?: PendingResume,+ ): void {+ const pending = this.pendingResumes.get(roomId);+ if (!pending || (expected && pending !== expected)) {+ return;+ }+ clearTimeout(pending.timer);+ this.pendingResumes.delete(roomId);+ }++ private allocateGeneration(): CodecTransitionGeneration {+ const generation = this.createGeneration();+ if (+ !Number.isSafeInteger(generation) ||+ generation <= this.latestGeneration+ ) {+ throw new Error("Codec transition generation must increase monotonically");+ }+ this.latestGeneration = generation;+ return generation;+ }++ private allocateResumeAttempt(): ResumeAttempt {+ const resumeAttempt = this.createResumeAttempt();+ if (+ !Number.isSafeInteger(resumeAttempt) ||+ resumeAttempt <= this.latestResumeAttempt+ ) {+ throw new Error("Resume attempt must increase monotonically");+ }+ this.latestResumeAttempt = resumeAttempt;+ return resumeAttempt;+ }++ private armDeadline(+ roomId: string,+ transaction: Transaction,+ expire: () => void,+ ): void {+ this.clearDeadline(transaction);+ transaction.timer = setTimeout(() => {+ if (this.rooms.get(roomId) === transaction) {+ transaction.timer = undefined;+ expire();+ }+ }, this.timeoutMs);+ }++ private clearDeadline(transaction: Transaction): void {+ if (transaction.timer) {+ clearTimeout(transaction.timer);+ transaction.timer = undefined;+ }+ }++ private messageOwns(+ transaction: Transaction | undefined,+ message: {+ shareGeneration: string;+ generation: CodecTransitionGeneration;+ },+ ): transaction is Transaction {+ return Boolean(+ transaction &&+ transaction.shareGeneration === message.shareGeneration &&+ transaction.generation === message.generation,+ );+ }++ private sendResult(+ hostSessionId: string,+ result: Omit<ResultMessage, "type">,+ ): void {+ this.options.sendToSession(hostSessionId, {+ type: "video-codec-result",+ ...result,+ });+ }+}++function freezeTargets(snapshot: CodecRouteSnapshot): Map<string, FrozenTarget> {+ return new Map(+ snapshot.targets.map((target) => [target.viewerPeerId, { ...target }]),+ );+}++function preparationsFor(+ targets: ReadonlyMap<string, FrozenTarget>,+): Map<string, Preparation> {+ const preparations = new Map<string, Preparation>();+ for (const target of targets.values()) {+ const key = preparationKey(target.preparationBinding);+ preparations.set(key, {+ ownerSessionId: target.preparationOwnerSessionId,+ binding: target.preparationBinding,+ });+ }+ return preparations;+}++function preparationKey(binding: CodecPreparationBinding): string {+ return binding.kind === "peer"+ ? `peer:${binding.childPeerId}:${binding.connectionId}`+ : `sfu:${binding.publicationGeneration}`;+}++function samePreparationBinding(+ left: CodecPreparationBinding,+ right: CodecPreparationBinding,+): boolean {+ return preparationKey(left) === preparationKey(right);+}++function sameProofBinding(+ left: CodecProofBinding,+ right: CodecProofBinding,+): boolean {+ return left.kind === right.kind &&+ left.connectionId === right.connectionId &&+ (left.kind === "peer" ||+ (right.kind === "sfu" &&+ left.publicationGeneration === right.publicationGeneration));+}++function sameTarget(left: FrozenTarget, right: CodecRouteTarget): boolean {+ return left.viewerSessionId === right.viewerSessionId &&+ left.preparationOwnerSessionId === right.preparationOwnerSessionId &&+ samePreparationBinding(left.preparationBinding, right.preparationBinding) &&+ sameProofBinding(left.proofBinding, right.proofBinding);+}++function isSfuTarget(target: CodecRouteTarget): boolean {+ return target.preparationBinding.kind === "sfu";+}++function pendingSfuSubtreeViewerPeerIds(+ targets: ReadonlyMap<string, FrozenTarget>,+): Set<string> {+ const subtreeViewerPeerIds = new Set<string>();+ const subtreeParentSessionIds = new Set<string>();+ for (const target of targets.values()) {+ if (!target.proofReady && isSfuTarget(target)) {+ subtreeViewerPeerIds.add(target.viewerPeerId);+ subtreeParentSessionIds.add(target.viewerSessionId);+ }+ }++ let previousSize = -1;+ while (subtreeViewerPeerIds.size !== previousSize) {+ previousSize = subtreeViewerPeerIds.size;+ for (const target of targets.values()) {+ if (+ target.preparationBinding.kind !== "peer" ||+ subtreeViewerPeerIds.has(target.viewerPeerId) ||+ !subtreeParentSessionIds.has(target.preparationOwnerSessionId)+ ) {+ continue;+ }+ subtreeViewerPeerIds.add(target.viewerPeerId);+ subtreeParentSessionIds.add(target.viewerSessionId);+ }+ }+ return subtreeViewerPeerIds;+}++function explicitCodec(+ preference: VideoCodecPreference,+): "h264" | "vp8" | null {+ return preference === "automatic" ? null : preference;+}++function expectedActualCodec(+ transaction: Pick<Transaction, "requested" | "rollback">,+): "h264" | "vp8" | null {+ return transaction.rollback ? null : explicitCodec(transaction.requested);+}++function sameResumeAttempt(+ pending: PendingResume | undefined,+ candidate: {+ hostSessionId: string;+ shareGeneration: string;+ codecGeneration: CodecTransitionGeneration | null;+ resumeAttempt: ResumeAttempt;+ },+): pending is PendingResume {+ return Boolean(+ pending &&+ pending.hostSessionId === candidate.hostSessionId &&+ pending.shareGeneration === candidate.shareGeneration &&+ pending.codecGeneration === candidate.codecGeneration &&+ pending.resumeAttempt === candidate.resumeAttempt,+ );+}diff --git a/src/server/hybrid-media-router.ts b/src/server/hybrid-media-router.tsindex 275eb99a..ed621e86 100644--- a/src/server/hybrid-media-router.ts+++ b/src/server/hybrid-media-router.ts@@ -2,12 +2,16 @@ import { randomBytes } from "node:crypto";import type {ClientMessage,+ CodecPreparationBinding,+ CodecProofBinding,+ CodecTransitionGeneration,MediaAssignment,MediaRouteUpstream,ParticipantRouteAssignment,PreparedRouteCandidate,Role,ServerMessage,+ VideoCodecPreference,} from "../shared/protocol.js";import { assertEndpointMediaCopyCapacity } from "../shared/media-copy-accounting.js";import type { SfuTokenIssuer } from "./livekit-token.js";@@ -17,6 +21,8 @@ import {type CandidatePlan,type CandidateReservation,type CandidateTuple,+ type CodecOperationGuard,+ type EdgeGuard,type OperationSnapshot,type RouteSnapshot,} from "./room-route-controller.js";@@ -79,6 +85,15 @@ interface RoomRuntime {pump?: Promise<void>;deadlineTimer?: NodeJS.Timeout;refreshKeys: Set<string>;+ codecOperation?: CodecOperationRuntime;+ codecDrainBarrierKey?: string;+}++interface CodecOperationRuntime {+ generation: CodecTransitionGeneration;+ guard: CodecOperationGuard;+ drainBeforePreparationKey?: string;+ resolvePreparation?: (snapshot: CodecRouteSnapshot | null) => void;}interface PreparedCandidate {@@ -86,10 +101,15 @@ interface PreparedCandidate {connectionId: string;publicationGeneration?: string;publicationConnectionId?: string;+ hostSessionId?: string;hostSfuConfig?: Extract<ServerMessage, { type: "sfu-config" }>;viewerSfuConfig?: Extract<ServerMessage, { type: "sfu-config" }>;}+type ResourceWaiter =+ | { kind: "admission" }+ | { kind: "drain"; drainKey: string };+type PrepareResult =| {kind: "denied";@@ -141,9 +161,24 @@ export interface AuthenticatedRouteParticipant {sessionId: string;}+export interface CodecRouteTarget {+ viewerPeerId: string;+ viewerSessionId: string;+ preparationOwnerSessionId: string;+ preparationBinding: CodecPreparationBinding;+ proofBinding: CodecProofBinding;+ routeRevision: number;+ proofReady: boolean;+}++export interface CodecRouteSnapshot {+ revision: number;+ targets: readonly CodecRouteTarget[];+}+export class HybridMediaRouter {private readonly rooms = new Map<string, RoomRuntime>();- private readonly resourceWaiterRoomIds = new Set<string>();+ private readonly resourceWaiters = new Map<string, ResourceWaiter>();private readonly sfuDrainTasks = new Map<string, SfuDrainTask>();private readonly hostOfflineChecks = new Map<string, HostOfflineCheck>();private readonly now: () => number;@@ -158,7 +193,7 @@ export class HybridMediaRouter {async close(): Promise<void> {this.closing = true;for (const roomId of [...this.rooms.keys()]) this.clearRoom(roomId);- this.resourceWaiterRoomIds.clear();+ this.resourceWaiters.clear();for (const check of this.hostOfflineChecks.values()) clearTimeout(check.timer);this.hostOfflineChecks.clear();const fallback = this.options.sfuFallback;@@ -277,6 +312,311 @@ export class HybridMediaRouter {: { kind: "none" };}+ codecRouteSnapshot(roomId: string): CodecRouteSnapshot | null {+ const room = this.rooms.get(roomId);+ const snapshot = room?.controller?.snapshot();+ if (!room || !snapshot) {+ return null;+ }+ const targets: CodecRouteTarget[] = [];+ for (const [viewerPeerId, edge] of snapshot.upstreamByViewer) {+ if (!edge.usable || !edge.physicalActive) {+ continue;+ }+ const viewer = this.options.roomStore.getConnectedViewer(+ roomId,+ viewerPeerId,+ );+ if (viewer?.sessionId !== edge.childSessionId) {+ continue;+ }+ const pathIsPhysical = this.pathIsPhysical(+ roomId,+ snapshot,+ viewerPeerId,+ );+ if (edge.kind === "peer") {+ const parent = this.connectedPeer(roomId, edge.parentPeerId);+ if (parent?.sessionId !== edge.parentSessionId) {+ continue;+ }+ targets.push({+ viewerPeerId,+ viewerSessionId: edge.childSessionId,+ preparationOwnerSessionId: edge.parentSessionId,+ preparationBinding: {+ kind: "peer",+ childPeerId: viewerPeerId,+ connectionId: edge.connectionId,+ },+ proofBinding: {+ kind: "peer",+ connectionId: edge.connectionId,+ },+ routeRevision: snapshot.revision,+ proofReady: pathIsPhysical,+ });+ continue;+ }+ const publication = snapshot.hostPublication;+ const host = this.options.roomStore.getConnectedHost(roomId);+ if (+ pathIsPhysical &&+ publication?.usable &&+ publication.physicalActive &&+ publication.generation === edge.publicationGeneration &&+ host?.sessionId === publication.hostSessionId+ ) {+ targets.push({+ viewerPeerId,+ viewerSessionId: edge.childSessionId,+ preparationOwnerSessionId: publication.hostSessionId,+ preparationBinding: {+ kind: "sfu",+ publicationGeneration: edge.publicationGeneration,+ },+ proofBinding: {+ kind: "sfu",+ connectionId: edge.connectionId,+ publicationGeneration: edge.publicationGeneration,+ },+ routeRevision: snapshot.revision,+ proofReady: true,+ });+ }+ }+ const operation = snapshot.operation;+ const current = operation?.current;+ if (+ operation?.owner.kind === "codec" &&+ current?.tuple.kind === "sfu"+ ) {+ const host = this.options.roomStore.getConnectedHost(roomId);+ const viewer = this.options.roomStore.getConnectedViewer(+ roomId,+ operation.childPeerId,+ );+ if (+ host?.sessionId === operation.owner.hostSessionId &&+ viewer?.sessionId === operation.childSessionId+ ) {+ const target: CodecRouteTarget = {+ viewerPeerId: operation.childPeerId,+ viewerSessionId: operation.childSessionId,+ preparationOwnerSessionId: host.sessionId,+ preparationBinding: {+ kind: "sfu",+ publicationGeneration: operation.owner.publicationGeneration,+ },+ proofBinding: {+ kind: "sfu",+ connectionId: operation.owner.connectionId,+ publicationGeneration: operation.owner.publicationGeneration,+ },+ routeRevision: current.revision,+ proofReady: false,+ };+ const existingIndex = targets.findIndex(+ (candidate) => candidate.viewerPeerId === operation.childPeerId,+ );+ if (existingIndex === -1) targets.push(target);+ else targets[existingIndex] = target;+ }+ }+ return { revision: snapshot.revision, targets };+ }++ beginCodecSfuReplacement(input: {+ roomId: string;+ hostSessionId: string;+ generation: CodecTransitionGeneration;+ videoCodec: VideoCodecPreference;+ timeoutMs: number;+ }): Promise<CodecRouteSnapshot | null> {+ const room = this.rooms.get(input.roomId);+ const controller = room?.controller;+ const snapshot = controller?.snapshot();+ if (+ !room ||+ !controller ||+ !snapshot ||+ room.codecOperation ||+ !this.options.sfuFallback+ ) {+ return Promise.resolve(null);+ }+ const nowMs = this.now();+ const publicationGeneration = opaqueId();+ const connectionId = opaqueId();+ const publicationConnectionId = opaqueId();+ const begun = controller.beginCodecSfuPublication({+ routeRevision: snapshot.revision,+ hostSessionId: input.hostSessionId,+ codecGeneration: input.generation,+ videoCodec: input.videoCodec,+ publicationGeneration,+ connectionId,+ publicationConnectionId,+ nowMs,+ deadlineAtMs: nowMs + input.timeoutMs,+ });+ if (!begun.accepted || !begun.guard) {+ this.releaseResources(begun.released);+ return Promise.resolve(null);+ }+ let resolvePreparation!: (snapshot: CodecRouteSnapshot | null) => void;+ const preparation = new Promise<CodecRouteSnapshot | null>((resolve) => {+ resolvePreparation = resolve;+ });+ const carriedDrainBarrierKey = room.codecDrainBarrierKey;+ const drainBeforePreparationKey =+ carriedDrainBarrierKey ??+ (snapshot.hostPublication?.resource.kind === "sfu-publication"+ ? managedSfuRoomName(snapshot.hostPublication.resource.fence)+ : undefined);+ room.codecDrainBarrierKey = undefined;+ room.codecOperation = {+ generation: input.generation,+ guard: begun.guard,+ ...(drainBeforePreparationKey ? { drainBeforePreparationKey } : {}),+ resolvePreparation,+ };+ this.releaseResources(begun.released);+ if (controller.snapshot().revision !== snapshot.revision) {+ this.broadcastActive(input.roomId, room);+ }+ this.requestPump(input.roomId);+ return preparation;+ }++ parkCodecSfuReplacement(+ roomId: string,+ generation: CodecTransitionGeneration,+ ): boolean {+ const room = this.rooms.get(roomId);+ const runtime = room?.codecOperation;+ const controller = room?.controller;+ const operation = controller?.snapshot().operation;+ if (+ !room ||+ !runtime ||+ runtime.generation !== generation ||+ !controller ||+ operation?.owner.kind !== "codec"+ ) {+ return false;+ }+ const expectedPhase = operation.owner.phase;+ if (expectedPhase !== "preparing" && expectedPhase !== "proving") {+ return expectedPhase === "prepared";+ }+ const parked = controller.transitionCodecOperation({+ guard: runtime.guard,+ expectedPhase,+ phase: "prepared",+ });+ this.releaseResources(parked.released);+ this.clearDeadline(room);+ return parked.accepted;+ }++ beginCodecSfuProof(+ roomId: string,+ generation: CodecTransitionGeneration,+ timeoutMs: number,+ ): boolean {+ const room = this.rooms.get(roomId);+ const runtime = room?.codecOperation;+ const controller = room?.controller;+ if (!room || !runtime || runtime.generation !== generation || !controller) {+ return false;+ }+ const nowMs = this.now();+ const proving = controller.transitionCodecOperation({+ guard: runtime.guard,+ expectedPhase: "prepared",+ phase: "proving",+ nowMs,+ deadlineAtMs: nowMs + timeoutMs,+ });+ this.releaseResources(proving.released);+ this.clearDeadline(room);+ return proving.accepted;+ }++ abortCodecSfuReplacement(+ roomId: string,+ generation: CodecTransitionGeneration,+ ): void {+ const room = this.rooms.get(roomId);+ const runtime = room?.codecOperation;+ const controller = room?.controller;+ if (!room || !runtime || runtime.generation !== generation || !controller) {+ return;+ }+ const before = controller.snapshot().revision;+ const aborted = controller.abortCodecOperation(runtime.guard, this.now());+ this.releaseResources(aborted.released);+ this.carryCodecDrainBarrier(room);+ this.resourceWaiters.delete(roomId);+ this.settleCodecPreparation(room, null);+ room.codecOperation = undefined;+ this.clearDeadline(room);+ if (controller.snapshot().revision !== before) {+ this.broadcastActive(roomId, room);+ }+ }++ routeWaitInvalidCodecTargets(+ roomId: string,+ viewerPeerIds: readonly string[],+ ): number | null {+ const room = this.rooms.get(roomId);+ const controller = room?.controller;+ const snapshot = controller?.snapshot();+ if (!room || !controller || !snapshot) return null;++ const guards: EdgeGuard[] = [];+ for (const viewerPeerId of new Set(viewerPeerIds)) {+ const viewer = this.options.roomStore.getConnectedViewer(+ roomId,+ viewerPeerId,+ );+ const edge = snapshot.upstreamByViewer.get(viewerPeerId);+ if (+ !viewer ||+ !edge?.physicalActive ||+ edge.childSessionId !== viewer.sessionId+ ) {+ continue;+ }+ guards.push({+ childPeerId: viewerPeerId,+ childSessionId: viewer.sessionId,+ routeRevision: snapshot.revision,+ connectionId: edge.connectionId,+ ...(edge.kind === "peer"+ ? { parentSessionId: edge.parentSessionId }+ : {}),+ });+ }+ if (guards.length === 0) return snapshot.revision;++ const retired = controller.retireCommittedTransportsForRouteWait(+ guards,+ this.now(),+ );+ if (!retired.accepted) {+ throw new Error("Codec route targets could not enter route-wait");+ }+ this.releaseResources(retired.released);+ if (retired.activeRevision !== snapshot.revision) {+ this.broadcastActive(roomId, room);+ }+ this.requestPump(roomId);+ return retired.activeRevision;+ }+viewerSfuMediaStateIsCurrent(roomId: string,viewerPeerId: string,@@ -408,6 +748,10 @@ export class HybridMediaRouter {return;}const before = controller.snapshot().revision;+ const codecGeneration =+ operation.owner.kind === "codec"+ ? operation.owner.codecGeneration+ : undefined;const settled = controller.candidateReady({childPeerId: participant.peerId,@@ -420,12 +764,19 @@ export class HybridMediaRouter {);this.releaseResources(settled.released);if (settled.accepted) {- this.resourceWaiterRoomIds.delete(participant.roomId);+ this.resourceWaiters.delete(participant.roomId);this.options.setConnectionId(participant.roomId,participant.peerId,current.connectionId,);+ if (+ codecGeneration !== undefined &&+ room.codecOperation?.generation === codecGeneration+ ) {+ this.settleCodecPreparation(room, null);+ room.codecOperation = undefined;+ }}if (controller.snapshot().revision !== before) this.broadcastActive(participant.roomId, room);if (settled.exhausted) {@@ -492,7 +843,11 @@ export class HybridMediaRouter {const ownsPublication =current.tuple.kind === "sfu" &&participant.role === "host" &&- participant.peerId === room.hostPeerId;+ participant.peerId === room.hostPeerId &&+ this.options.roomStore.getConnectedHost(participant.roomId)+ ?.sessionId === participant.sessionId &&+ (operation.owner.kind !== "codec" ||+ operation.owner.hostSessionId === participant.sessionId);if (!ownsChild && !ownsParent && !ownsPublication) return;if (message.connectionId && message.connectionId !== current.connectionId) return;const before = snapshot.revision;@@ -561,13 +916,16 @@ export class HybridMediaRouter {) {return;}- controller.invalidateEdge({+ const invalidated = controller.invalidateEdge({childPeerId: participant.peerId,childSessionId: participant.sessionId,routeRevision: snapshot.revision,connectionId: edge.connectionId,...(edge.kind === "peer" ? { parentSessionId: edge.parentSessionId } : {}),}, this.now());+ if (invalidated && edge.usable && snapshot.paused) {+ this.options.onActiveRouteChanged?.(participant.roomId);+ }this.requestPump(participant.roomId);}@@ -663,6 +1021,10 @@ export class HybridMediaRouter {if (room.requested && !this.closing) this.requestPump(roomId);}})().catch(() => {+ const generation = room.codecOperation?.generation;+ if (generation !== undefined) {+ this.abortCodecSfuReplacement(roomId, generation);+ }console.error("Media route reconciliation failed");this.sendRoomError(roomId, "SERVER_ERROR", "Media routing failed");});@@ -687,15 +1049,48 @@ export class HybridMediaRouter {const operation = reconciled.operation ?? controller.snapshot().operation;if (!operation) {this.clearDeadline(room);+ this.resourceWaiters.delete(roomId);+ if (room.codecOperation) {+ this.settleCodecPreparation(room, null);+ this.carryCodecDrainBarrier(room);+ room.codecOperation = undefined;+ }return;}if (operation.current) {- this.scheduleDeadline(roomId, room, operation);+ this.resourceWaiters.delete(roomId);+ if (operation.owner.kind === "route") {+ this.scheduleDeadline(roomId, room, operation);+ } else {+ this.clearDeadline(room);+ }return;}const plan = operation.candidates[operation.cursor];- if (!plan) return;+ if (!plan) {+ this.resourceWaiters.delete(roomId);+ return;+ }+ if (operation.owner.kind === "codec") {+ const runtime = room.codecOperation;+ const drainKey = runtime?.drainBeforePreparationKey;+ if (+ runtime?.generation === operation.owner.codecGeneration &&+ drainKey &&+ this.sfuDrainTasks.has(drainKey)+ ) {+ this.resourceWaiters.set(roomId, { kind: "drain", drainKey });+ this.clearDeadline(room);+ return;+ }+ if (runtime) runtime.drainBeforePreparationKey = undefined;+ }const guard = cursorGuard(operation, plan);+ if (plan.tuple.kind === "sfu") {+ this.resourceWaiters.set(roomId, { kind: "admission" });+ } else {+ this.resourceWaiters.delete(roomId);+ }const preparation = await this.prepareCandidate(roomId,room,@@ -705,6 +1100,21 @@ export class HybridMediaRouter {(plan.endpointTransition.kind === "bounded-gap" ? 2 : 1),);if (preparation.kind === "denied") {+ if (preparation.rejectionBucket !== "sfu-admission") {+ this.resourceWaiters.delete(roomId);+ }+ if (operation.owner.kind === "codec") {+ if (preparation.rejectionBucket === "sfu-admission") {+ this.resourceWaiters.set(roomId, { kind: "admission" });+ this.clearDeadline(room);+ return;+ }+ this.abortCodecSfuReplacement(+ roomId,+ operation.owner.codecGeneration,+ );+ return;+ }if (preparation.rejectionBucket === "sfu-admission") {if (!controller.noteCurrentCandidateRejection(@@ -714,7 +1124,7 @@ export class HybridMediaRouter {) {continue;}- this.resourceWaiterRoomIds.add(roomId);+ this.resourceWaiters.set(roomId, { kind: "admission" });this.sendViewerRouteStatus(roomId, operation.childPeerId, {type: "route-status",revision: operation.baseRevision,@@ -740,8 +1150,12 @@ export class HybridMediaRouter {}continue;}+ this.resourceWaiters.delete(roomId);let currentOperation = controller.snapshot().operation;- if (plan.endpointTransition.kind === "bounded-gap") {+ if (+ operation.owner.kind === "route" &&+ plan.endpointTransition.kind === "bounded-gap"+ ) {const beforeGap = controller.snapshot().revision;const gap = controller.retireCurrentCandidateProducer(guard, this.now());this.releaseResources(gap.released);@@ -772,9 +1186,17 @@ export class HybridMediaRouter {reservation: preparation.prepared.reservation,publicationGeneration: preparation.prepared.publicationGeneration,publicationConnectionId: preparation.prepared.publicationConnectionId,+ hostSessionId: preparation.prepared.hostSessionId,});this.releaseResources(begun.released);if (!begun.accepted || !begun.operation?.current) {+ if (operation.owner.kind === "codec") {+ this.abortCodecSfuReplacement(+ roomId,+ operation.owner.codecGeneration,+ );+ return;+ }if (begun.exhausted) {this.sendViewerRouteStatus(roomId, operation.childPeerId, {type: "route-status",@@ -791,7 +1213,15 @@ export class HybridMediaRouter {begun.operation,preparation.prepared,);- this.scheduleDeadline(roomId, room, begun.operation);+ if (begun.operation.owner.kind === "codec") {+ this.clearDeadline(room);+ this.settleCodecPreparation(+ room,+ this.codecRouteSnapshot(roomId),+ );+ } else {+ this.scheduleDeadline(roomId, room, begun.operation);+ }return;}}@@ -809,7 +1239,10 @@ export class HybridMediaRouter {if (!child || child.sessionId !== operation.childSessionId || !shareGeneration) {return { kind: "denied", rejectionBucket: "stale" };}- const connectionId = opaqueId();+ const connectionId =+ operation.owner.kind === "codec"+ ? operation.owner.connectionId+ : opaqueId();const overlap =plan.endpointTransition.kind === "overlap"? overlapResource(plan.endpointTransition.producerPeerId)@@ -826,7 +1259,13 @@ export class HybridMediaRouter {const fallback = this.options.sfuFallback;const host = this.options.roomStore.getConnectedHost(roomId);- if (!fallback || !host || host.peerId !== room.hostPeerId) {+ if (+ !fallback ||+ !host ||+ host.peerId !== room.hostPeerId ||+ (operation.owner.kind === "codec" &&+ host.sessionId !== operation.owner.hostSessionId)+ ) {return { kind: "denied", rejectionBucket: "stale" };}if (plan.tuple.publication === "reuse") {@@ -865,6 +1304,7 @@ export class HybridMediaRouter {kind: "ready",prepared: {connectionId,+ hostSessionId: host.sessionId,reservation: {kind: "sfu-reuse",edge,@@ -880,7 +1320,7 @@ export class HybridMediaRouter {},};} catch {- fallback.admission.releaseSubscription(fence);+ this.releaseSubscription(fence);return { kind: "denied", rejectionBucket: "candidate-failed" };}}@@ -893,6 +1333,13 @@ export class HybridMediaRouter {shareGeneration,host,overlap,+ operation.owner.kind === "codec"+ ? {+ publicationGeneration: operation.owner.publicationGeneration,+ publicationConnectionId:+ operation.owner.publicationConnectionId,+ }+ : undefined,);}@@ -902,11 +1349,16 @@ export class HybridMediaRouter {revision: number,connectionId: string,shareGeneration: string,- host: { peerId: string },+ host: { peerId: string; sessionId: string },overlap?: OverlapRouteResource,+ codecIdentity?: {+ publicationGeneration: string;+ publicationConnectionId: string;+ },): Promise<PrepareResult> {const fallback = this.options.sfuFallback!;- const publicationGeneration = opaqueId();+ const publicationGeneration =+ codecIdentity?.publicationGeneration ?? opaqueId();const publicationFence: SfuResourceFence = {roomId,shareGeneration,@@ -925,7 +1377,8 @@ export class HybridMediaRouter {return { kind: "denied", rejectionBucket: "sfu-admission" };}const subscription = subscriptionResource(subscriptionFence);- const publicationConnectionId = publicationGeneration;+ const publicationConnectionId =+ codecIdentity?.publicationConnectionId ?? publicationGeneration;const publication = publicationResource(publicationFence);try {await fallback.roomControl.createRoom(publicationFence);@@ -951,6 +1404,7 @@ export class HybridMediaRouter {kind: "ready",prepared: {connectionId,+ hostSessionId: host.sessionId,publicationGeneration,publicationConnectionId,reservation: {@@ -1018,7 +1472,13 @@ export class HybridMediaRouter {return;}const host = this.options.roomStore.getConnectedHost(roomId);- if (prepared.hostSfuConfig && host) {+ if (+ prepared.hostSfuConfig &&+ host &&+ host.sessionId === prepared.hostSessionId &&+ (operation.owner.kind !== "codec" ||+ host.sessionId === operation.owner.hostSessionId)+ ) {this.options.sendToSession(host.sessionId, {type: "route-update",revision: current.revision,@@ -1106,20 +1566,25 @@ export class HybridMediaRouter {const childPeerIds = [...edges].filter(([, candidate]) =>candidate.kind === "peer" &&- candidate.parentPeerId === peerId &&- sourceReachable(candidate.parentPeerId),+ candidate.parentPeerId === peerId,).map(([childPeerId]) => childPeerId);assignments.set(peerId, {upstream:- peerId === hostPeerId || !reachable || !edge+ peerId === hostPeerId || !edge? { kind: "none" }: edge.kind === "peer"? { kind: "peer", peerId: edge.parentPeerId }- : { kind: "sfu" },+ : reachable+ ? { kind: "sfu" }+ : { kind: "none" },childPeerIds,sfuPublicationGeneration:- peerId === hostPeerId ? publicationGeneration : null,+ peerId === hostPeerId+ ? publicationGeneration+ : reachable && edge?.kind === "sfu"+ ? edge.publicationGeneration+ : null,});}return assignments;@@ -1183,7 +1648,7 @@ export class HybridMediaRouter {if (seen.has(current)) return false;seen.add(current);const edge = snapshot.upstreamByViewer.get(current);- if (!edge?.physicalActive) return false;+ if (!edge?.physicalActive || !edge.usable) return false;if (edge.kind === "sfu") {return Boolean(snapshot.hostPublication?.physicalActive &&@@ -1240,7 +1705,13 @@ export class HybridMediaRouter {}private releaseResources(resources: readonly RouteResource[]): void {- for (const resource of resources) this.releaseResource(resource);+ // Generation drain owns physical release; its child handles stay charged until absence.+ for (const resource of resources) {+ if (resource.kind === "sfu-publication") this.releaseResource(resource);+ }+ for (const resource of resources) {+ if (resource.kind !== "sfu-publication") this.releaseResource(resource);+ }}private releaseResource(resource: RouteResource): void {@@ -1248,17 +1719,43 @@ export class HybridMediaRouter {resource.released = true;if (resource.kind === "overlap") return;if (resource.kind === "sfu-subscription") {- this.options.sfuFallback?.admission.releaseSubscription(resource.fence);+ this.releaseSubscription(resource.fence);return;}if (this.options.sfuFallback?.admission.beginDrain(resource.fence)) {+ const room = this.rooms.get(resource.fence.roomId);+ if (room?.codecOperation) {+ room.codecOperation.drainBeforePreparationKey = managedSfuRoomName(+ resource.fence,+ );+ }this.scheduleSfuDrain(resource.fence);}}- private wakeResourceWaiters(): void {- const roomIds = [...this.resourceWaiterRoomIds];- this.resourceWaiterRoomIds.clear();+ private releaseSubscription(fence: SfuSubscriptionFence): boolean {+ const admission = this.options.sfuFallback?.admission;+ if (!admission) return false;+ const beforeEgress = admission.usage().egress;+ const accepted = admission.releaseSubscription(fence);+ if (accepted && admission.usage().egress < beforeEgress) {+ this.wakeResourceWaiters();+ }+ return accepted;+ }++ private wakeResourceWaiters(completedDrainKey?: string): void {+ const roomIds: string[] = [];+ for (const [roomId, waiter] of this.resourceWaiters) {+ if (+ waiter.kind === "drain" &&+ waiter.drainKey !== completedDrainKey+ ) {+ continue;+ }+ this.resourceWaiters.delete(roomId);+ roomIds.push(roomId);+ }for (const roomId of roomIds) {const controller = this.rooms.get(roomId)?.controller;if (!controller) continue;@@ -1439,7 +1936,11 @@ export class HybridMediaRouter {throw new Error("LiveKit drain has no matching resource generation");}this.sfuDrainTasks.delete(key);- this.wakeResourceWaiters();+ const room = this.rooms.get(task.fence.roomId);+ if (room?.codecDrainBarrierKey === key) {+ room.codecDrainBarrierKey = undefined;+ }+ this.wakeResourceWaiters(key);} catch (error) {if (this.sfuDrainTasks.get(key) !== task) return;if (this.closing) throw error;@@ -1456,21 +1957,39 @@ export class HybridMediaRouter {return tracked;}+ private settleCodecPreparation(+ room: RoomRuntime,+ snapshot: CodecRouteSnapshot | null,+ ): void {+ const resolve = room.codecOperation?.resolvePreparation;+ if (!resolve) return;+ room.codecOperation!.resolvePreparation = undefined;+ resolve(snapshot);+ }++ private carryCodecDrainBarrier(room: RoomRuntime): void {+ const key = room.codecOperation?.drainBeforePreparationKey;+ if (key && this.sfuDrainTasks.has(key)) {+ room.codecDrainBarrierKey = key;+ }+ }+private clearRoom(roomId: string): void {const room = this.rooms.get(roomId);if (!room) return;this.clearDeadline(room);this.cancelHostOfflineCheck(roomId);+ this.settleCodecPreparation(room, null);+ room.codecOperation = undefined;const controller = room.controller;room.controller = undefined;room.requested = false;if (controller) this.releaseResources(controller.dispose());this.rooms.delete(roomId);- this.resourceWaiterRoomIds.delete(roomId);+ this.resourceWaiters.delete(roomId);for (const fence of this.options.sfuFallback?.admission.beginDrainRoom(roomId) ?? []) {this.scheduleSfuDrain(fence);}- this.wakeResourceWaiters();}private sendRoomError(roomId: string, code: ErrorCode, message: string): void {@@ -1493,6 +2012,7 @@ function cursorGuard(plan: CandidatePlan,): CandidateCursorGuard {return {+ owner: { ...operation.owner },childPeerId: operation.childPeerId,childSessionId: operation.childSessionId,baseRevision: operation.baseRevision,@@ -1527,6 +2047,13 @@ function preparedRouteCandidate(childPeerId: operation.childPeerId,connectionId,transport: tuple.kind === "peer" ? tuple.transport : "sfu",+ codecTransition:+ operation.owner.kind === "codec"+ ? {+ generation: operation.owner.codecGeneration,+ videoCodec: operation.owner.videoCodec,+ }+ : null,};}diff --git a/src/server/room-route-controller.ts b/src/server/room-route-controller.tsindex 65fc58bb..6327c9a1 100644--- a/src/server/room-route-controller.ts+++ b/src/server/room-route-controller.ts@@ -1,9 +1,11 @@import {MAX_MEDIA_ROUTE_REVISION,+ type CodecTransitionGeneration,type RouteDemandReason,type RouteDiagnosticFinalRoute,type RouteDiagnosticRejectionBucket,type RouteDiagnosticSnapshot,+ type VideoCodecPreference,} from "../shared/protocol.js";import { assertEndpointMediaCopyCapacity } from "../shared/media-copy-accounting.js";@@ -74,6 +76,7 @@ export interface CandidateGuard {}export interface CandidateCursorGuard {+ owner: OperationOwner;childPeerId: string;childSessionId: string;baseRevision: number;@@ -106,12 +109,29 @@ interface Attempt<Resource> {connectionId: string;childSessionId: string;parentSessionId?: string;+ hostSessionId?: string;publicationGeneration?: string;publicationConnectionId?: string;reservation: CandidateReservation<Resource>;}+export type CodecOperationPhase = "preparing" | "prepared" | "proving";++export type OperationOwner =+ | { kind: "route" }+ | {+ kind: "codec";+ codecGeneration: CodecTransitionGeneration;+ phase: CodecOperationPhase;+ videoCodec: VideoCodecPreference;+ hostSessionId: string;+ publicationGeneration: string;+ connectionId: string;+ publicationConnectionId: string;+ };+interface ChildOperation<Resource> {+ owner: OperationOwner;childPeerId: string;childSessionId: string;reason: RouteDemandReason;@@ -120,10 +140,12 @@ interface ChildOperation<Resource> {cursor: number;deadlineAtMs: number;builtAtFactVersion: number;+ deferredRetirements: EdgeGuard[];current?: Attempt<Resource>;}export interface OperationSnapshot {+ owner: OperationOwner;childPeerId: string;childSessionId: string;reason: RouteDemandReason;@@ -166,6 +188,64 @@ export interface BeginResult<Resource> {released: readonly Resource[];}+export interface RetireTransportsResult<Resource> {+ accepted: boolean;+ activeRevision: number;+ retiredPeerIds: readonly string[];+ released: readonly Resource[];+}++export interface CodecOperationGuard {+ codecGeneration: CodecTransitionGeneration;+ hostSessionId: string;+ childPeerId: string;+ childSessionId: string;+ publicationGeneration: string;+ connectionId: string;+ publicationConnectionId: string;+}++export interface BeginCodecSfuPublicationInput {+ routeRevision: number;+ hostSessionId: string;+ codecGeneration: CodecTransitionGeneration;+ videoCodec: VideoCodecPreference;+ publicationGeneration: string;+ connectionId: string;+ publicationConnectionId: string;+ nowMs: number;+ deadlineAtMs: number;+ retainedAnchor?: {+ childPeerId: string;+ childSessionId: string;+ };+}++export interface BeginCodecSfuPublicationResult<Resource> {+ accepted: boolean;+ activeRevision: number;+ anchorPeerId?: string;+ guard?: CodecOperationGuard;+ retiredPeerIds: readonly string[];+ operation?: OperationSnapshot;+ released: readonly Resource[];+}++export interface CodecOperationMutationResult<Resource> {+ accepted: boolean;+ activeRevision: number;+ operation?: OperationSnapshot;+ released: readonly Resource[];+}++export interface TransitionCodecOperationInput {+ guard: CodecOperationGuard;+ expectedPhase: CodecOperationPhase;+ phase: CodecOperationPhase;+ nowMs?: number;+ deadlineAtMs?: number;+}+interface HostPublication<Resource> {generation: string;hostSessionId: string;@@ -438,6 +518,242 @@ export class RoomRouteController<Resource = unknown> {this.assertGraph();}+ beginCodecSfuPublication(+ input: BeginCodecSfuPublicationInput,+ ): BeginCodecSfuPublicationResult<Resource> {+ assertCodecOperationInput(input);+ const rejected = (): BeginCodecSfuPublicationResult<Resource> => ({+ accepted: false,+ activeRevision: this.revision,+ retiredPeerIds: [],+ released: [],+ });+ const host = this.participants.get(this.options.hostPeerId);+ if (+ !this.options.sfuEnabled ||+ !this.paused ||+ this.operation ||+ this.revision !== input.routeRevision ||+ host?.sessionId !== input.hostSessionId ||+ host.departureConfirmed+ ) {+ return rejected();+ }++ const publication = this.hostPublication;+ if (+ publication &&+ (publication.hostSessionId !== input.hostSessionId ||+ publication.generation === input.publicationGeneration ||+ publication.connectionId === input.publicationConnectionId)+ ) {+ return rejected();+ }+ const publicationViewers = publication+ ? [...this.upstreamByViewer]+ .filter(+ ([, edge]) =>+ edge.kind === "sfu" &&+ edge.publicationGeneration === publication.generation,+ )+ .map(([peerId]) => this.participants.get(peerId))+ .filter((participant): participant is Participant =>+ Boolean(participant?.sessionId && !participant.departureConfirmed),+ )+ .sort(compareParticipant)+ : [];+ let anchor: Participant | undefined;+ if (input.retainedAnchor) {+ const retained = this.participants.get(input.retainedAnchor.childPeerId);+ const retainedEdge = this.upstreamByViewer.get(+ input.retainedAnchor.childPeerId,+ );+ if (+ retained?.role !== "viewer" ||+ retained.sessionId !== input.retainedAnchor.childSessionId ||+ retained.departureConfirmed ||+ (publication &&+ (retainedEdge?.kind !== "sfu" ||+ retainedEdge.publicationGeneration !== publication.generation ||+ (publication.physicalActive &&+ (!retainedEdge.physicalActive || !retainedEdge.usable)))) ||+ (!publication && retainedEdge)+ ) {+ return rejected();+ }+ anchor = retained;+ } else {+ anchor = publication?.physicalActive+ ? publicationViewers.find((participant) => {+ const edge = this.upstreamByViewer.get(participant.peerId);+ return edge?.physicalActive && edge.usable;+ })+ : publicationViewers[0];+ }+ if (!anchor?.sessionId) return rejected();+ const anchorEdge = this.upstreamByViewer.get(anchor.peerId);+ if (anchorEdge?.connectionId === input.connectionId) return rejected();+ const copiesAfterRetirement =+ this.physicalCopies(this.options.hostPeerId) -+ (publication?.physicalActive ? 1 : 0);+ if (copiesAfterRetirement + 1 > host.effectiveDownstreamCapacity) {+ return rejected();+ }++ const released = new Set<Resource>();+ const retiredPeerIds: string[] = [];+ if (publication) {+ for (const [viewerPeerId, edge] of this.upstreamByViewer) {+ if (+ edge.kind !== "sfu" ||+ edge.publicationGeneration !== publication.generation+ ) {+ continue;+ }+ if (edge.physicalActive) {+ released.add(edge.resource);+ retiredPeerIds.push(viewerPeerId);+ }+ edge.physicalActive = false;+ edge.usable = false;+ const participant = this.participants.get(viewerPeerId);+ if (participant) {+ participant.blockedAtFactVersion = undefined;+ participant.failedTuple = undefined;+ }+ this.recordDemand(viewerPeerId, input.nowMs, "edge-unavailable");+ }+ if (publication.physicalActive) released.add(publication.resource);+ publication.physicalActive = false;+ publication.usable = false;+ this.revision = this.allocateRevision();+ this.touchFacts();+ }++ const tuple: CandidateTuple = {+ kind: "sfu",+ publication: publication ? "replace" : "create",+ };+ const plan = this.planCandidate(anchor.peerId, tuple);+ if (!plan) {+ throw new Error("Codec SFU publication candidate is not admissible");+ }+ this.ensureDemand(anchor.peerId, input.nowMs, "edge-unavailable");+ this.startOperationTiming(anchor.peerId, input.nowMs);+ this.operation = {+ owner: {+ kind: "codec",+ codecGeneration: input.codecGeneration,+ phase: "preparing",+ videoCodec: input.videoCodec,+ hostSessionId: input.hostSessionId,+ publicationGeneration: input.publicationGeneration,+ connectionId: input.connectionId,+ publicationConnectionId: input.publicationConnectionId,+ },+ childPeerId: anchor.peerId,+ childSessionId: anchor.sessionId,+ reason: "edge-unavailable",+ baseRevision: this.revision,+ candidates: [plan],+ cursor: 0,+ deadlineAtMs: input.deadlineAtMs,+ builtAtFactVersion: this.factVersion,+ deferredRetirements: [],+ };+ this.assertGraph();+ const guard = codecOperationGuard(this.operation);+ return {+ accepted: true,+ activeRevision: this.revision,+ anchorPeerId: anchor.peerId,+ guard,+ retiredPeerIds,+ operation: this.operationSnapshot(),+ released: [...released],+ };+ }++ transitionCodecOperation(+ input: TransitionCodecOperationInput,+ ): CodecOperationMutationResult<Resource> {+ const operation = this.operation;+ if (+ !operation ||+ !codecOperationGuardMatches(input.guard, operation) ||+ operation.owner.kind !== "codec" ||+ !operation.current ||+ operation.owner.phase !== input.expectedPhase ||+ !codecPhaseTransitionAllowed(input.expectedPhase, input.phase)+ ) {+ return {+ accepted: false,+ activeRevision: this.revision,+ operation: this.operationSnapshot(),+ released: [],+ };+ }+ if (input.phase === "proving") {+ if (+ input.nowMs === undefined ||+ input.deadlineAtMs === undefined ||+ !Number.isSafeInteger(input.deadlineAtMs) ||+ input.deadlineAtMs <= input.nowMs+ ) {+ throw new Error("Codec proof deadline must be in the future");+ }+ operation.deadlineAtMs = input.deadlineAtMs;+ }+ operation.owner.phase = input.phase;+ return {+ accepted: true,+ activeRevision: this.revision,+ operation: this.operationSnapshot(),+ released: [],+ };+ }++ abortCodecOperation(+ guard: CodecOperationGuard,+ nowMs?: number,+ ): CodecOperationMutationResult<Resource> {+ const operation = this.operation;+ if (!operation || !codecOperationGuardMatches(guard, operation)) {+ return {+ accepted: false,+ activeRevision: this.revision,+ operation: this.operationSnapshot(),+ released: [],+ };+ }+ const released = operation.current+ ? [...reservationResources(operation.current.reservation)]+ : [];+ if (nowMs !== undefined) {+ this.finishTiming(+ operation.childPeerId,+ nowMs,+ this.currentFinalRoute(operation.childPeerId),+ "aborted",+ );+ }+ let revisionAdvanced = Boolean(operation.current);+ if (operation.current) this.advanceActiveRevision(operation);+ if (this.retireDeferredCodecEdges(operation, released)) {+ if (!revisionAdvanced) {+ this.advanceActiveRevision(operation);+ revisionAdvanced = true;+ }+ this.touchFacts();+ }+ this.operation = undefined;+ return {+ accepted: true,+ activeRevision: this.revision,+ released,+ };+ }+invalidateEdge(guard: EdgeGuard, nowMs?: number): boolean {const child = this.participants.get(guard.childPeerId);const edge = this.upstreamByViewer.get(guard.childPeerId);@@ -533,6 +849,92 @@ export class RoomRouteController<Resource = unknown> {return edge.transport === "direct" ? [] : [edge.resource];}+ retireCommittedTransportsForRouteWait(+ guards: readonly EdgeGuard[],+ nowMs: number,+ ): RetireTransportsResult<Resource> {+ const childPeerIds = new Set<string>();+ const owned: Array<{+ childPeerId: string;+ child: Participant;+ edge: CommittedEdge<Resource>;+ }> = [];+ const codecOperation =+ this.operation?.owner.kind === "codec" ? this.operation : undefined;+ if (+ !this.paused ||+ (this.operation && !codecOperation) ||+ guards.length === 0+ ) {+ return {+ accepted: false,+ activeRevision: this.revision,+ retiredPeerIds: [],+ released: [],+ };+ }+ for (const guard of guards) {+ const child = this.participants.get(guard.childPeerId);+ const edge = this.upstreamByViewer.get(guard.childPeerId);+ if (+ childPeerIds.has(guard.childPeerId) ||+ guard.routeRevision !== this.revision ||+ !child ||+ child.sessionId !== guard.childSessionId ||+ !edge ||+ !edge.physicalActive ||+ edge.childSessionId !== guard.childSessionId ||+ edge.connectionId !== guard.connectionId ||+ (edge.kind === "peer" &&+ edge.parentSessionId !== guard.parentSessionId)+ ) {+ return {+ accepted: false,+ activeRevision: this.revision,+ retiredPeerIds: [],+ released: [],+ };+ }+ childPeerIds.add(guard.childPeerId);+ owned.push({ childPeerId: guard.childPeerId, child, edge });+ }++ const released: Resource[] = [];+ let invalidated = false;+ for (const { childPeerId, child, edge } of owned) {+ if (edge.usable) {+ edge.usable = false;+ this.recordDemand(childPeerId, nowMs, "edge-unavailable");+ invalidated = true;+ }+ child.blockedAtFactVersion = undefined;+ child.failedTuple = undefined;+ }+ if (codecOperation) {+ const deferred = guards.filter(+ (guard) =>+ !codecOperation.deferredRetirements.some((candidate) =>+ edgeGuardEquals(candidate, guard),+ ),+ );+ codecOperation.deferredRetirements.push(+ ...deferred.map((guard) => ({ ...guard })),+ );+ if (invalidated) this.touchFacts();+ codecOperation.builtAtFactVersion = this.factVersion;+ } else if (invalidated) {+ this.revision = this.allocateRevision();+ this.touchFacts();+ }+ this.assertGraph();+ return {+ accepted: true,+ activeRevision: this.revision,+ retiredPeerIds: [...childPeerIds],+ released,+ };+ }+retireHostPublication(guard: {hostSessionId: string;routeRevision: number;@@ -607,6 +1009,7 @@ export class RoomRouteController<Resource = unknown> {}this.startOperationTiming(childPeerId, nowMs);this.operation = {+ owner: { kind: "route" },childPeerId,childSessionId: child.sessionId!,reason,@@ -615,6 +1018,7 @@ export class RoomRouteController<Resource = unknown> {cursor: 0,deadlineAtMs: nowMs + this.options.operationTimeoutMs,builtAtFactVersion: this.factVersion,+ deferredRetirements: [],};return {operation: this.operationSnapshot(),@@ -633,6 +1037,7 @@ export class RoomRouteController<Resource = unknown> {reservation: CandidateReservation<Resource>;publicationGeneration?: string;publicationConnectionId?: string;+ hostSessionId?: string;}): BeginResult<Resource> {const validation = this.validateOrAdvance(input.nowMs);const operation = this.operation;@@ -652,6 +1057,27 @@ export class RoomRouteController<Resource = unknown> {exhausted: validation.exhausted,};}+ if (+ operation.owner.kind === "codec" &&+ (operation.owner.phase !== "preparing" ||+ plan.tuple.kind !== "sfu" ||+ this.participants.get(this.options.hostPeerId)?.sessionId !==+ operation.owner.hostSessionId ||+ input.connectionId !== operation.owner.connectionId ||+ input.publicationGeneration !==+ operation.owner.publicationGeneration ||+ input.publicationConnectionId !==+ operation.owner.publicationConnectionId)+ ) {+ return {+ accepted: false,+ operation: this.operationSnapshot(),+ released: [+ ...validation.released,+ ...reservationResources(input.reservation),+ ],+ };+ }if (plan.endpointTransition.kind === "bounded-gap") {return {accepted: false,@@ -660,6 +1086,23 @@ export class RoomRouteController<Resource = unknown> {};}const tuple = plan.tuple;+ const hostSessionId =+ tuple.kind === "sfu"+ ? this.participants.get(this.options.hostPeerId)?.sessionId+ : undefined;+ if (+ tuple.kind === "sfu" &&+ (!input.hostSessionId || input.hostSessionId !== hostSessionId)+ ) {+ return {+ accepted: false,+ operation: this.operationSnapshot(),+ released: [+ ...validation.released,+ ...reservationResources(input.reservation),+ ],+ };+ }this.assertReservation(tuple, input.reservation, plan.endpointTransition.kind === "overlap");const publicationGeneration = tuple.kind === "sfu"? tuple.publication === "reuse" ? this.hostPublication?.generation : input.publicationGeneration@@ -674,6 +1117,10 @@ export class RoomRouteController<Resource = unknown> {connectionId: input.connectionId,childSessionId: operation.childSessionId,parentSessionId: tuple.kind === "peer" ? this.participants.get(tuple.parentPeerId)?.sessionId ?? undefined : undefined,+ hostSessionId:+ tuple.kind === "sfu"+ ? input.hostSessionId+ : undefined,publicationGeneration,publicationConnectionId: input.publicationConnectionId,reservation: input.reservation,@@ -791,6 +1238,16 @@ export class RoomRouteController<Resource = unknown> {const validation = this.validateOrAdvance(nowMs);const operation = this.operation;const attempt = operation?.current;+ if (+ operation?.owner.kind === "codec" &&+ operation.owner.phase !== "proving"+ ) {+ return {+ accepted: false,+ activeRevision: this.revision,+ released: validation.released,+ };+ }if (!operation || !attempt || !this.guardMatches(guard, operation, attempt)) {return { accepted: false, exhausted: validation.exhausted, activeRevision: this.revision, released: validation.released };}@@ -871,6 +1328,7 @@ export class RoomRouteController<Resource = unknown> {expired: boolean;consumedGuard: boolean;} {+ const activeRevisionAtStart = this.revision;const released: Resource[] = [];const result: {released: Resource[];@@ -881,8 +1339,15 @@ export class RoomRouteController<Resource = unknown> {} = { released, expired: false, consumedGuard: false };let operation = this.operation;if (!operation) return result;- if (nowMs >= operation.deadlineAtMs) {+ if (+ !(+ operation.owner.kind === "codec" &&+ operation.owner.phase === "prepared"+ ) &&+ nowMs >= operation.deadlineAtMs+ ) {if (operation.current) released.push(...reservationResources(operation.current.reservation));+ const revisionAdvanced = Boolean(operation.current);if (operation.current) this.advanceActiveRevision(operation);const factsChanged = operation.builtAtFactVersion !== this.factVersion;this.finishTiming(@@ -891,7 +1356,12 @@ export class RoomRouteController<Resource = unknown> {factsChanged ? "waiting" : "failed",factsChanged ? "stale" : "operation-deadline",);- this.blockAndClear(operation, !factsChanged, released);+ this.blockAndClear(+ operation,+ !factsChanged,+ released,+ revisionAdvanced,+ );return {...result,exhausted: !factsChanged,@@ -906,7 +1376,12 @@ export class RoomRouteController<Resource = unknown> {}if (this.participants.get(operation.childPeerId)?.sessionId !== operation.childSessionId) {if (operation.current) released.push(...reservationResources(operation.current.reservation));+ const revisionAdvanced = Boolean(operation.current);if (operation.current) this.advanceActiveRevision(operation);+ if (this.retireDeferredCodecEdges(operation, released)) {+ if (!revisionAdvanced) this.advanceActiveRevision(operation);+ this.touchFacts();+ }this.finishTiming(operation.childPeerId,nowMs,@@ -956,7 +1431,12 @@ export class RoomRouteController<Resource = unknown> {? "candidate-failed": this.routeTimings.get(operation.childPeerId)!.rejectionBucket,);- this.blockAndClear(operation, !factsChanged, released);+ this.blockAndClear(+ operation,+ !factsChanged,+ released,+ this.revision !== activeRevisionAtStart,+ );result.exhausted = !factsChanged && !this.bootstrapForBlockedDemand();if (result.exhausted) {result.exhaustedChildPeerId = operation.childPeerId;@@ -968,9 +1448,17 @@ export class RoomRouteController<Resource = unknown> {private commitAttempt(operation: ChildOperation<Resource>, attempt: Attempt<Resource>): Resource[] {const beforeResources = new Set(this.committedResources());const old = this.upstreamByViewer.get(operation.childPeerId);+ const codecReplacementGeneration =+ operation.owner.kind === "codec" &&+ attempt.tuple.kind === "sfu" &&+ attempt.tuple.publication === "replace"+ ? this.hostPublication?.generation+ : undefined;if (attempt.tuple.kind === "sfu" && attempt.tuple.publication === "replace") {- this.removePublicationGeneration(this.hostPublication!.generation);+ if (operation.owner.kind === "route") {+ this.removePublicationGeneration(this.hostPublication!.generation);+ }}if (attempt.tuple.kind === "peer") {@@ -989,6 +1477,9 @@ export class RoomRouteController<Resource = unknown> {if (!hostSessionId || !attempt.publicationConnectionId) {throw new Error("SFU publication identity is unavailable");}+ if (attempt.hostSessionId !== hostSessionId) {+ throw new Error("SFU publication Host session is stale");+ }this.hostPublication = {generation,hostSessionId,@@ -998,6 +1489,20 @@ export class RoomRouteController<Resource = unknown> {resource: reservation.publication,};}+ if (codecReplacementGeneration) {+ for (const [viewerPeerId, existing] of this.upstreamByViewer) {+ if (+ viewerPeerId === operation.childPeerId ||+ existing.kind !== "sfu" ||+ existing.publicationGeneration !== codecReplacementGeneration+ ) {+ continue;+ }+ existing.publicationGeneration = generation;+ existing.usable = false;+ existing.physicalActive = false;+ }+ }const edge = (attempt.reservation as Extract<CandidateReservation<Resource>, { kind: "sfu-reuse" | "sfu-create" }>).edge;this.upstreamByViewer.set(operation.childPeerId, {kind: "sfu", childSessionId: operation.childSessionId,@@ -1006,6 +1511,7 @@ export class RoomRouteController<Resource = unknown> {});}this.revision = attempt.revision;+ this.retireDeferredCodecEdges(operation);this.operation = undefined;this.touchFacts();const participant = this.participants.get(operation.childPeerId);@@ -1132,6 +1638,13 @@ export class RoomRouteController<Resource = unknown> {!this.targetFits(parent.peerId, childPeerId)) return false;} else {if (!this.options.sfuEnabled) return false;+ if (+ attempt?.hostSessionId &&+ attempt.hostSessionId !==+ this.participants.get(this.options.hostPeerId)?.sessionId+ ) {+ return false;+ }if (tuple.publication === "reuse") {if (!this.hostPublication?.usable || !this.hostPublication.physicalActive ||(attempt && attempt.publicationGeneration !== this.hostPublication.generation)) return false;@@ -1250,8 +1763,16 @@ export class RoomRouteController<Resource = unknown> {bucket,);}- const released = this.operation.current ? reservationResources(this.operation.current.reservation) : [];- if (this.operation.current) this.advanceActiveRevision(this.operation);+ const operation = this.operation;+ const released = operation.current+ ? [...reservationResources(operation.current.reservation)]+ : [];+ const revisionAdvanced = Boolean(operation.current);+ if (operation.current) this.advanceActiveRevision(operation);+ if (this.retireDeferredCodecEdges(operation, released)) {+ if (!revisionAdvanced) this.advanceActiveRevision(operation);+ this.touchFacts();+ }this.operation = undefined;return released;}@@ -1265,17 +1786,56 @@ export class RoomRouteController<Resource = unknown> {operation: ChildOperation<Resource>,block = true,released: Resource[] = [],+ revisionAdvanced = false,): void {const child = this.participants.get(operation.childPeerId);+ const retiredDeferred = this.retireDeferredCodecEdges(operation, released);this.operation = undefined;- if (!block || !child) return;- if (this.retireInvalidOperationEdge(operation.childPeerId, released)) {+ const retiredInvalid = block && child+ ? this.retireInvalidOperationEdge(operation.childPeerId, released)+ : false;+ if ((retiredDeferred || retiredInvalid) && !revisionAdvanced) {this.revision = this.allocateRevision();+ }+ if (retiredDeferred || retiredInvalid) {this.touchFacts();}+ if (!block || !child) return;child.blockedAtFactVersion = this.factVersion;}+ private retireDeferredCodecEdges(+ operation: ChildOperation<Resource>,+ released: Resource[] = [],+ ): boolean {+ if (+ operation.owner.kind !== "codec" ||+ operation.deferredRetirements.length === 0+ ) {+ return false;+ }+ let retired = false;+ for (const guard of operation.deferredRetirements) {+ const edge = this.upstreamByViewer.get(guard.childPeerId);+ if (+ !edge ||+ !edge.physicalActive ||+ edge.childSessionId !== guard.childSessionId ||+ edge.connectionId !== guard.connectionId ||+ (edge.kind === "peer" &&+ edge.parentSessionId !== guard.parentSessionId)+ ) {+ continue;+ }+ edge.physicalActive = false;+ edge.usable = false;+ if (edge.kind === "sfu") released.push(edge.resource);+ retired = true;+ }+ operation.deferredRetirements = [];+ return retired;+ }+private retireInvalidOperationEdge(childPeerId: string, released: Resource[]): boolean {const edge = this.upstreamByViewer.get(childPeerId);if (!edge || !this.edgeRequiresMove(childPeerId, edge)) return false;@@ -1327,7 +1887,8 @@ export class RoomRouteController<Resource = unknown> {private operationSnapshot(): OperationSnapshot | undefined {const operation = this.operation;if (!operation) return undefined;- return { childPeerId: operation.childPeerId, childSessionId: operation.childSessionId,+ return { owner: { ...operation.owner },+ childPeerId: operation.childPeerId, childSessionId: operation.childSessionId,reason: operation.reason,baseRevision: operation.baseRevision, factVersion: operation.builtAtFactVersion,candidates: operation.candidates.map(cloneCandidatePlan),@@ -1342,6 +1903,12 @@ export class RoomRouteController<Resource = unknown> {nowMs: number,released: Resource[],): boolean {+ if (+ operation.owner.kind === "codec" &&+ operation.owner.phase === "prepared"+ ) {+ return false;+ }const plan = operation.current? { tuple: operation.current.tuple }: operation.candidates[operation.cursor];@@ -1441,7 +2008,8 @@ export class RoomRouteController<Resource = unknown> {private cursorGuardMatches(guard: CandidateCursorGuard, operation: ChildOperation<Resource>): boolean {const plan = operation.candidates[operation.cursor];- return Boolean(plan && guard.childPeerId === operation.childPeerId &&+ return Boolean(plan && operationOwnerEquals(guard.owner, operation.owner) &&+ guard.childPeerId === operation.childPeerId &&guard.childSessionId === operation.childSessionId && guard.baseRevision === operation.baseRevision &&guard.factVersion === operation.builtAtFactVersion && guard.cursor === operation.cursor &&candidatePlanEquals(guard.plan, plan));@@ -1758,6 +2326,102 @@ export class RoomRouteController<Resource = unknown> {}}+function codecOperationGuard<Resource>(+ operation: ChildOperation<Resource>,+): CodecOperationGuard {+ if (operation.owner.kind !== "codec") {+ throw new Error("Route operation is not codec-owned");+ }+ return {+ codecGeneration: operation.owner.codecGeneration,+ hostSessionId: operation.owner.hostSessionId,+ childPeerId: operation.childPeerId,+ childSessionId: operation.childSessionId,+ publicationGeneration: operation.owner.publicationGeneration,+ connectionId: operation.owner.connectionId,+ publicationConnectionId: operation.owner.publicationConnectionId,+ };+}++function codecOperationGuardMatches<Resource>(+ guard: CodecOperationGuard,+ operation: ChildOperation<Resource>,+): boolean {+ return (+ operation.owner.kind === "codec" &&+ operation.owner.codecGeneration === guard.codecGeneration &&+ operation.owner.hostSessionId === guard.hostSessionId &&+ operation.childPeerId === guard.childPeerId &&+ operation.childSessionId === guard.childSessionId &&+ operation.owner.publicationGeneration ===+ guard.publicationGeneration &&+ operation.owner.connectionId === guard.connectionId &&+ operation.owner.publicationConnectionId ===+ guard.publicationConnectionId+ );+}++function operationOwnerEquals(left: OperationOwner, right: OperationOwner): boolean {+ if (left.kind !== right.kind) return false;+ if (left.kind === "route" || right.kind === "route") return true;+ return (+ left.codecGeneration === right.codecGeneration &&+ left.phase === right.phase &&+ left.videoCodec === right.videoCodec &&+ left.hostSessionId === right.hostSessionId &&+ left.publicationGeneration === right.publicationGeneration &&+ left.connectionId === right.connectionId &&+ left.publicationConnectionId === right.publicationConnectionId+ );+}++function edgeGuardEquals(left: EdgeGuard, right: EdgeGuard): boolean {+ return (+ left.childPeerId === right.childPeerId &&+ left.childSessionId === right.childSessionId &&+ left.parentSessionId === right.parentSessionId &&+ left.routeRevision === right.routeRevision &&+ left.connectionId === right.connectionId+ );+}++function codecPhaseTransitionAllowed(+ from: CodecOperationPhase,+ to: CodecOperationPhase,+): boolean {+ return (+ (from === "preparing" && to === "prepared") ||+ (from === "prepared" && to === "proving") ||+ (from === "proving" && to === "prepared")+ );+}++function assertCodecOperationInput(input: BeginCodecSfuPublicationInput): void {+ if (!Number.isSafeInteger(input.codecGeneration) || input.codecGeneration <= 0) {+ throw new Error("Codec generation must be a positive safe integer");+ }+ if (+ !Number.isFinite(input.nowMs) ||+ !Number.isSafeInteger(input.deadlineAtMs) ||+ input.deadlineAtMs <= input.nowMs+ ) {+ throw new Error("Codec preparation deadline must be in the future");+ }+ if (+ ![input.publicationGeneration, input.connectionId, input.publicationConnectionId]+ .every((value) => value.length > 0)+ ) {+ throw new Error("Codec SFU identity is invalid");+ }+ if (+ input.retainedAnchor &&+ (!input.retainedAnchor.childPeerId ||+ !input.retainedAnchor.childSessionId)+ ) {+ throw new Error("Codec SFU retained anchor is invalid");+ }+}+function compareParticipant(left: Participant, right: Participant): number {return left.joinOrder - right.joinOrder || left.peerId.localeCompare(right.peerId);}diff --git a/src/server/sfu-resource-admission.ts b/src/server/sfu-resource-admission.tsindex 342c1969..c77bf1d7 100644--- a/src/server/sfu-resource-admission.ts+++ b/src/server/sfu-resource-admission.ts@@ -23,7 +23,6 @@ type ResourceState = "reserved" | "committed" | "draining";interface SubscriptionEntry {fence: SfuSubscriptionFence;state: ResourceState;- reservedFromDraining: boolean;}interface PublicationEntry {@@ -91,7 +90,6 @@ export class SfuResourceAdmission {}if (publication.state !== "committed") return false;existing.state = "reserved";- existing.reservedFromDraining = true;return true;}if (this.egressInUse >= this.egressCapacity) return false;@@ -99,7 +97,6 @@ export class SfuResourceAdmission {publication.subscriptions.set(fence.viewerPeerId, {fence: cloneSubscriptionFence(fence),state: "reserved",- reservedFromDraining: false,});this.egressInUse += 1;return true;@@ -128,7 +125,6 @@ export class SfuResourceAdmission {for (const subscription of publication.subscriptions.values()) {if (subscription.state === "reserved") {subscription.state = "committed";- subscription.reservedFromDraining = false;}}return draining;@@ -148,7 +144,6 @@ export class SfuResourceAdmission {if (subscription.state === "committed") return true;if (subscription.state !== "reserved") return false;subscription.state = "committed";- subscription.reservedFromDraining = false;return true;}@@ -164,13 +159,7 @@ export class SfuResourceAdmission {return false;}if (subscription.state === "reserved") {- if (subscription.reservedFromDraining) {- subscription.state = "draining";- subscription.reservedFromDraining = false;- } else {- publication.subscriptions.delete(fence.viewerPeerId);- this.subtractEgress(1);- }+ subscription.state = "draining";return true;}if (subscription.state === "committed") {@@ -246,7 +235,6 @@ export class SfuResourceAdmission {publication.state = "draining";for (const subscription of publication.subscriptions.values()) {subscription.state = "draining";- subscription.reservedFromDraining = false;}}diff --git a/src/server/signaling.ts b/src/server/signaling.tsindex cc70a76f..674810b3 100644--- a/src/server/signaling.ts+++ b/src/server/signaling.ts@@ -10,15 +10,19 @@ import {DEFAULT_QUALITY_SETTINGS,MAX_SIGNAL_BYTES,MAX_VIEWER_QUALITY_EVIDENCE_BYTES,+ SIGNAL_CLOSE_CODES,SIGNALING_PROTOCOL,VIEWER_QUALITY_EVIDENCE_INTERVAL_MS,decodeClientMessage,type ClientMessage,+ type CodecTransitionGeneration,type CodeEntryPolicy,type QualitySettings,+ type ResumeAttempt,type Role,type ServerMessage,type ParticipantPresenceEntry,+ type VideoCodecPreference,} from "../shared/protocol.js";import { assertEndpointMediaCopyCapacity } from "../shared/media-copy-accounting.js";import {@@ -30,6 +34,7 @@ import {HybridMediaRouter,type SfuFallbackOptions,} from "./hybrid-media-router.js";+import { CodecTransitionCoordinator } from "./codec-transition.js";import { createIceConfig, type IceConfigOptions } from "./ice.js";type ErrorCode = Extract<ServerMessage, { type: "error" }>["code"];@@ -125,6 +130,7 @@ export class SignalingServer {Set<string>>();private readonly hybridMediaRouter?: HybridMediaRouter;+ private readonly codecTransitions?: CodecTransitionCoordinator;private readonly now: () => number;private readonly authenticationTimeoutMs: number;private readonly viewerDisconnectGraceMs: number;@@ -175,6 +181,7 @@ export class SignalingServer {getShareGeneration: (roomId) => this.shareGenerationsByRoom.get(roomId),onActiveRouteChanged: (roomId) => {this.viewerMediaReadyByRoom.delete(roomId);+ this.codecTransitions?.participantChanged(roomId);this.sendViewerPresence(roomId);},onViewerMediaState: (@@ -196,6 +203,81 @@ export class SignalingServer {now: this.now,});}+ this.codecTransitions = new CodecTransitionCoordinator({+ snapshot: (roomId) =>+ this.hybridMediaRouter?.codecRouteSnapshot(roomId) ?? {+ revision: 0,+ targets: [],+ },+ sendToSession: (sessionId, message) =>+ this.sendToSession(sessionId, message),+ commitCodec: (roomId, videoCodec) =>+ this.commitRoomVideoCodec(roomId, videoCodec),+ authorizeResume: (+ roomId,+ hostSessionId,+ shareGeneration,+ codecGeneration,+ resumeAttempt,+ ) =>+ this.authorizeSharingResume(+ roomId,+ hostSessionId,+ shareGeneration,+ codecGeneration,+ resumeAttempt,+ ),+ confirmSourceEnabled: (+ roomId,+ hostSessionId,+ shareGeneration,+ codecGeneration,+ resumeAttempt,+ ) =>+ this.confirmSharingSourceEnabled(+ roomId,+ hostSessionId,+ shareGeneration,+ codecGeneration,+ resumeAttempt,+ ),+ restoreAuthoritativePause: (+ roomId,+ hostSessionId,+ shareGeneration,+ codecGeneration,+ resumeAttempt,+ ) =>+ this.restoreAuthoritativePause(+ roomId,+ hostSessionId,+ shareGeneration,+ codecGeneration,+ resumeAttempt,+ ),+ returnTargetsToRouteWait: (roomId, viewerPeerIds) =>+ this.hybridMediaRouter?.routeWaitInvalidCodecTargets(+ roomId,+ viewerPeerIds,+ ),+ beginSfuReplacement: (input) =>+ this.hybridMediaRouter?.beginCodecSfuReplacement(input) ??+ Promise.resolve(null),+ parkSfuReplacement: (roomId, generation) =>+ this.hybridMediaRouter?.parkCodecSfuReplacement(roomId, generation) ??+ false,+ beginSfuProof: (roomId, generation, timeoutMs) =>+ this.hybridMediaRouter?.beginCodecSfuProof(+ roomId,+ generation,+ timeoutMs,+ ) ?? false,+ abortSfuReplacement: (roomId, generation) =>+ this.hybridMediaRouter?.abortCodecSfuReplacement(roomId, generation),+ releaseRoutePause: (roomId) =>+ this.hybridMediaRouter?.setPaused(roomId, false),+ now: this.now,+ });this.upgradeHandler = (request, socket, head) => {let requestUrl: URL;@@ -256,6 +338,7 @@ export class SignalingServer {clearTimeout(timer);}this.viewerGraceTimers.clear();+ this.codecTransitions?.close();let routeCloseError: unknown;try {await this.hybridMediaRouter?.close();@@ -287,7 +370,7 @@ export class SignalingServer {const sessionId = randomBytes(16).toString("base64url");const authenticationTimer = setTimeout(() => {this.sendError(socket, "AUTH_REQUIRED", "Authentication timed out");- socket.close(4001, "Authentication required");+ socket.close(SIGNAL_CLOSE_CODES.authenticationFailed, "Authentication required");}, this.authenticationTimeoutMs);authenticationTimer.unref();@@ -345,7 +428,7 @@ export class SignalingServer {if (!state.authenticated) {if (message.type !== "authenticate") {this.sendError(socket, "AUTH_REQUIRED", "Authenticate before sending messages");- socket.close(4001, "Authentication required");+ socket.close(SIGNAL_CLOSE_CODES.authenticationFailed, "Authentication required");return;}if (state.authenticating) {@@ -373,7 +456,7 @@ export class SignalingServer {return;}if (!this.isCurrentSession(state)) {- socket.close(4001, "Session replaced");+ socket.close(SIGNAL_CLOSE_CODES.sessionReplaced, "Session replaced");return;}@@ -387,7 +470,7 @@ export class SignalingServer {): Promise<void> {if (message.role === "host" && !state.siteAccessAuthenticated) {this.sendError(socket, "AUTH_REQUIRED", "Site access is required");- socket.close(4003, "Authentication failed");+ socket.close(SIGNAL_CLOSE_CODES.authenticationFailed, "Authentication failed");return;}if (@@ -404,7 +487,7 @@ export class SignalingServer {"INVALID_TOKEN",authenticationErrorMessage("INVALID_TOKEN"),);- socket.close(4003, "Authentication failed");+ socket.close(SIGNAL_CLOSE_CODES.authenticationFailed, "Authentication failed");return;}@@ -459,7 +542,7 @@ export class SignalingServer {}const code = authenticationErrorCode(message, error);this.sendError(socket, code, authenticationErrorMessage(code));- socket.close(4003, "Authentication failed");+ socket.close(SIGNAL_CLOSE_CODES.authenticationFailed, "Authentication failed");return;}@@ -486,6 +569,10 @@ export class SignalingServer {);shareGeneration =message.shareGeneration ?? currentGeneration ?? state.sessionId;+ const sameShareWasAuthoritativelyPaused =+ currentGeneration === shareGeneration &&+ this.pausedShareGenerationsByRoom.get(participant.roomId) ===+ shareGeneration;if (currentGeneration !== undefined &¤tGeneration !== shareGeneration@@ -493,7 +580,11 @@ export class SignalingServer {this.stopSharing(participant.roomId);}this.shareGenerationsByRoom.set(participant.roomId, shareGeneration);- if (message.sharingPaused === true) {+ if (+ message.sharingPaused === true ||+ this.codecTransitions?.blocksResume(participant.roomId) ||+ sameShareWasAuthoritativelyPaused+ ) {this.pausedShareGenerationsByRoom.set(participant.roomId,shareGeneration,@@ -613,7 +704,7 @@ export class SignalingServer {if (participant.replacedSessionId) {const replaced = this.socketsBySessionId.get(participant.replacedSessionId);if (replaced && replaced !== socket) {- replaced.close(4001, "Session replaced");+ replaced.close(SIGNAL_CLOSE_CODES.sessionReplaced, "Session replaced");}}@@ -631,6 +722,26 @@ export class SignalingServer {);}+ if (participant.role === "host") {+ if (this.codecTransitions?.blocksResume(participant.roomId)) {+ this.codecTransitions.invalidateHostSession(+ participant.roomId,+ state.sessionId,+ );+ } else if (+ shareGeneration !== null &&+ this.pausedShareGenerationsByRoom.get(participant.roomId) ===+ shareGeneration+ ) {+ this.sendToSession(state.sessionId, {+ type: "pause-sharing-source",+ shareGeneration,+ codecGeneration: null,+ resumeAttempt: null,+ });+ }+ }+this.sendViewerPresence(participant.roomId);if (participant.role === "host") {@@ -748,10 +859,23 @@ export class SignalingServer {);return;}- this.qualitySettingsByRoom.set(+ const currentQuality = this.qualitySettingsByRoom.get(authenticated.roomId,- { ...message.qualitySettings },);+ if (+ currentQuality &&+ videoCodec(currentQuality) !== videoCodec(message.qualitySettings)+ ) {+ this.sendError(+ socket,+ "FORBIDDEN",+ "视频编码只能在分享暂停后切换",+ );+ return;+ }+ this.qualitySettingsByRoom.set(authenticated.roomId, {+ ...message.qualitySettings,+ });for (const viewer of this.options.roomStore.getConnectedViewers(authenticated.roomId,)) {@@ -930,7 +1054,7 @@ export class SignalingServer {}case "set-sharing-paused":if (authenticated.role !== "host") {- this.sendError(socket, "FORBIDDEN", "Only the host may pause sharing");+ this.sendError(socket, "FORBIDDEN", "只有当前分享者可以暂停分享");return;}const pauseSocketState = this.socketStates.get(socket);@@ -945,33 +1069,181 @@ export class SignalingServer {authenticated.shareGeneration ||message.shareGeneration !== authenticated.shareGeneration) {- socket.close(4001, "Sharing generation replaced");+ socket.close(SIGNAL_CLOSE_CODES.sessionReplaced, "Sharing generation replaced");+ return;+ }+ this.pausedShareGenerationsByRoom.set(+ authenticated.roomId,+ authenticated.shareGeneration,+ );+ this.codecTransitions?.pause({+ roomId: authenticated.roomId,+ hostSessionId: pauseSocketState.sessionId,+ shareGeneration: authenticated.shareGeneration,+ });+ if (this.isHybridMediaEnabled()) {+ this.hybridMediaRouter!.setPaused(authenticated.roomId, true);+ }+ this.broadcastHostStatus(authenticated.roomId, true, true);+ return;+ case "request-sharing-resume": {+ if (authenticated.role !== "host") {+ this.sendError(socket, "FORBIDDEN", "只有当前分享者可以恢复分享");return;}- if (message.paused) {- this.pausedShareGenerationsByRoom.set(+ const resumeState = this.socketStates.get(socket);+ const currentHost = this.options.roomStore.getConnectedHost(+ authenticated.roomId,+ );+ if (+ !resumeState ||+ currentHost?.sessionId !== resumeState.sessionId ||+ authenticated.shareGeneration === null ||+ this.shareGenerationsByRoom.get(authenticated.roomId) !==+ authenticated.shareGeneration ||+ this.pausedShareGenerationsByRoom.get(authenticated.roomId) !==+ authenticated.shareGeneration ||+ message.shareGeneration !== authenticated.shareGeneration+ ) {+ socket.close(SIGNAL_CLOSE_CODES.sessionReplaced, "Sharing generation replaced");+ return;+ }+ const result = this.codecTransitions!.requestResume({+ roomId: authenticated.roomId,+ hostSessionId: resumeState.sessionId,+ shareGeneration: authenticated.shareGeneration,+ });+ if (result === "busy") {+ this.sendError(+ socket,+ "FORBIDDEN",+ "视频编码尚未准备完成",+ );+ }+ return;+ }+ case "sharing-source-enabled": {+ if (authenticated.role !== "host") {+ this.sendError(socket, "FORBIDDEN", "只有当前分享者可以确认恢复分享");+ return;+ }+ const sourceState = this.socketStates.get(socket);+ const currentHost = this.options.roomStore.getConnectedHost(+ authenticated.roomId,+ );+ if (+ !sourceState ||+ currentHost?.sessionId !== sourceState.sessionId ||+ authenticated.shareGeneration === null ||+ this.shareGenerationsByRoom.get(authenticated.roomId) !==+ authenticated.shareGeneration ||+ message.shareGeneration !== authenticated.shareGeneration+ ) {+ socket.close(SIGNAL_CLOSE_CODES.sessionReplaced, "Sharing generation replaced");+ return;+ }+ if (+ !this.codecTransitions!.sourceEnabled({+ roomId: authenticated.roomId,+ hostSessionId: sourceState.sessionId,+ shareGeneration: authenticated.shareGeneration,+ codecGeneration: message.codecGeneration,+ resumeAttempt: message.resumeAttempt,+ })+ ) {+ this.rejectSharingSourceAcknowledgement(authenticated.roomId,+ sourceState.sessionId,authenticated.shareGeneration,+ message.codecGeneration,+ message.resumeAttempt,);- } else {- this.pausedShareGenerationsByRoom.delete(authenticated.roomId);}- if (this.isHybridMediaEnabled()) {- this.hybridMediaRouter!.setPaused(authenticated.roomId, message.paused);+ return;+ }+ case "request-video-codec-transition": {+ if (+ authenticated.role !== "host" ||+ !this.isHybridMediaEnabled()+ ) {+ this.sendError(socket, "FORBIDDEN", "只有当前分享者可以切换视频编码");+ return;}- for (const viewer of this.options.roomStore.getConnectedViewers(+ const transitionState = this.socketStates.get(socket);+ const currentHost = this.options.roomStore.getConnectedHost(authenticated.roomId,- )) {- this.sendToSession(viewer.sessionId, {- type: "host-status",- online: true,- paused: message.paused,- });+ );+ if (+ !transitionState ||+ currentHost?.sessionId !== transitionState.sessionId ||+ authenticated.shareGeneration === null ||+ this.shareGenerationsByRoom.get(authenticated.roomId) !==+ authenticated.shareGeneration ||+ this.pausedShareGenerationsByRoom.get(authenticated.roomId) !==+ authenticated.shareGeneration ||+ message.shareGeneration !== authenticated.shareGeneration+ ) {+ socket.close(SIGNAL_CLOSE_CODES.sessionReplaced, "Sharing generation replaced");+ return;+ }+ const previous = videoCodec(+ this.qualitySettingsByRoom.get(authenticated.roomId) ??+ DEFAULT_QUALITY_SETTINGS,+ );+ if (previous === message.videoCodec) {+ return;+ }+ const result = this.codecTransitions!.start({+ roomId: authenticated.roomId,+ hostSessionId: transitionState.sessionId,+ shareGeneration: authenticated.shareGeneration,+ requested: message.videoCodec,+ previous,+ });+ if (result === "busy" || result === "unavailable") {+ this.sendError(+ socket,+ result === "busy" ? "FORBIDDEN" : "SERVER_ERROR",+ result === "busy"+ ? "已有视频编码切换正在进行"+ : "当前媒体线路不可用",+ );+ }+ return;+ }+ case "video-codec-prepared": {+ if (!this.isHybridMediaEnabled()) {+ this.sendError(socket, "FORBIDDEN", "当前未启用媒体线路");+ return;+ }+ const state = this.socketStates.get(socket);+ if (state?.authenticated === authenticated) {+ this.codecTransitions!.prepared(+ authenticated.roomId,+ state.sessionId,+ message,+ );+ }+ return;+ }+ case "video-codec-proof": {+ if (!this.isHybridMediaEnabled() || authenticated.role !== "viewer") {+ this.sendError(socket, "FORBIDDEN", "只有当前观看者可以确认已解码画面");+ return;+ }+ const state = this.socketStates.get(socket);+ if (state?.authenticated === authenticated) {+ this.codecTransitions!.proof(+ authenticated.roomId,+ state.sessionId,+ message,+ );}return;+ }case "stop-sharing":if (authenticated.role !== "host") {- this.sendError(socket, "FORBIDDEN", "Only the host may stop sharing");+ this.sendError(socket, "FORBIDDEN", "只有当前分享者可以停止分享");return;}if (@@ -981,7 +1253,7 @@ export class SignalingServer {(message.shareGeneration !== undefined &&message.shareGeneration !== authenticated.shareGeneration)) {- socket.close(4001, "Sharing generation replaced");+ socket.close(SIGNAL_CLOSE_CODES.sessionReplaced, "Sharing generation replaced");return;}const state = this.socketStates.get(socket);@@ -1492,19 +1764,14 @@ export class SignalingServer {);}if (disconnected.role === "host") {- for (const viewer of this.options.roomStore.getConnectedViewers(- disconnected.roomId,- )) {- this.sendToSession(viewer.sessionId, {- type: "host-status",- online: false,- paused: false,- });- }+ this.codecTransitions?.invalidateHostSession(disconnected.roomId);+ this.broadcastHostStatus(disconnected.roomId, false, false);this.sendViewerPresence(disconnected.roomId);return;}+ this.codecTransitions?.participantChanged(disconnected.roomId);+this.sendViewerPresence(disconnected.roomId);const key = viewerGraceKey(disconnected.roomId, disconnected.peerId);@@ -1554,6 +1821,7 @@ export class SignalingServer {}private stopSharing(roomId: string): void {+ this.codecTransitions?.clearRoom(roomId);this.pausedShareGenerationsByRoom.delete(roomId);this.clearRoomConnectionIds(roomId);if (this.isHybridMediaEnabled()) {@@ -1577,6 +1845,7 @@ export class SignalingServer {this.clearRoomGraceTimers(roomId);this.clearRoomConnectionIds(roomId);this.ordinaryActiveHostChildrenByRoom.delete(roomId);+ this.codecTransitions?.clearRoom(roomId);if (this.isHybridMediaEnabled()) {this.hybridMediaRouter!.deleteRoom(roomId);}@@ -1598,6 +1867,7 @@ export class SignalingServer {this.clearRoomGraceTimers(expired.roomId);this.clearRoomConnectionIds(expired.roomId);this.ordinaryActiveHostChildrenByRoom.delete(expired.roomId);+ this.codecTransitions?.clearRoom(expired.roomId);if (this.isHybridMediaEnabled()) {this.hybridMediaRouter!.deleteRoom(expired.roomId);}@@ -1894,6 +2164,132 @@ export class SignalingServer {}}+ private commitRoomVideoCodec(+ roomId: string,+ nextVideoCodec: VideoCodecPreference,+ ): void {+ const qualitySettings = {+ ...(this.qualitySettingsByRoom.get(roomId) ?? DEFAULT_QUALITY_SETTINGS),+ videoCodec: nextVideoCodec,+ };+ this.qualitySettingsByRoom.set(roomId, qualitySettings);+ for (const viewer of this.options.roomStore.getConnectedViewers(roomId)) {+ this.sendToSession(viewer.sessionId, {+ type: "quality-settings",+ qualitySettings,+ });+ }+ }++ private authorizeSharingResume(+ roomId: string,+ hostSessionId: string,+ shareGeneration: string,+ codecGeneration: CodecTransitionGeneration | null,+ resumeAttempt: ResumeAttempt,+ ): void {+ const host = this.options.roomStore.getConnectedHost(roomId);+ if (+ host?.sessionId !== hostSessionId ||+ this.shareGenerationsByRoom.get(roomId) !== shareGeneration ||+ this.pausedShareGenerationsByRoom.get(roomId) !== shareGeneration+ ) {+ return;+ }+ this.sendToSession(hostSessionId, {+ type: "sharing-resume-authorized",+ shareGeneration,+ codecGeneration,+ resumeAttempt,+ });+ }++ private confirmSharingSourceEnabled(+ roomId: string,+ hostSessionId: string,+ shareGeneration: string,+ _codecGeneration: CodecTransitionGeneration | null,+ _resumeAttempt: ResumeAttempt,+ ): boolean {+ const host = this.options.roomStore.getConnectedHost(roomId);+ if (+ host?.sessionId !== hostSessionId ||+ this.shareGenerationsByRoom.get(roomId) !== shareGeneration ||+ this.pausedShareGenerationsByRoom.get(roomId) !== shareGeneration+ ) {+ return false;+ }+ this.pausedShareGenerationsByRoom.delete(roomId);+ this.sendToSession(hostSessionId, {+ type: "host-status",+ online: true,+ paused: false,+ });+ this.broadcastHostStatus(roomId, true, false);+ return true;+ }++ private restoreAuthoritativePause(+ roomId: string,+ hostSessionId: string,+ shareGeneration: string,+ codecGeneration: CodecTransitionGeneration | null,+ resumeAttempt: ResumeAttempt | null,+ ): void {+ if (this.shareGenerationsByRoom.get(roomId) !== shareGeneration) {+ return;+ }+ this.pausedShareGenerationsByRoom.set(roomId, shareGeneration);+ this.hybridMediaRouter?.setPaused(roomId, true);+ const host = this.options.roomStore.getConnectedHost(roomId);+ if (host?.sessionId === hostSessionId) {+ this.sendToSession(hostSessionId, {+ type: "pause-sharing-source",+ shareGeneration,+ codecGeneration,+ resumeAttempt,+ });+ this.broadcastHostStatus(roomId, true, true);+ }+ }++ private rejectSharingSourceAcknowledgement(+ roomId: string,+ hostSessionId: string,+ shareGeneration: string,+ codecGeneration: CodecTransitionGeneration | null,+ resumeAttempt: ResumeAttempt,+ ): void {+ if (+ this.shareGenerationsByRoom.get(roomId) !== shareGeneration ||+ this.pausedShareGenerationsByRoom.get(roomId) !== shareGeneration ||+ this.options.roomStore.getConnectedHost(roomId)?.sessionId !==+ hostSessionId+ ) {+ return;+ }+ this.sendToSession(hostSessionId, {+ type: "pause-sharing-source",+ shareGeneration,+ codecGeneration,+ resumeAttempt,+ });+ }++ private broadcastHostStatus(+ roomId: string,+ online: boolean,+ paused: boolean,+ ): void {+ for (const viewer of this.options.roomStore.getConnectedViewers(roomId)) {+ this.sendToSession(viewer.sessionId, {+ type: "host-status",+ online,+ paused,+ });+ }+ }+private closeRevokedViewerSession(sessionId: string): void {const socket = this.socketsBySessionId.get(sessionId);if (!socket) {@@ -1909,7 +2305,7 @@ export class SignalingServer {}// Deauthorize before close so queued callbacks from the old generation// cannot route signaling after the persistent authorization commit.- socket.close(4004, "Viewer access revoked");+ socket.close(SIGNAL_CLOSE_CODES.viewerAccessRevoked, "Viewer access revoked");}private sendEncodedToSession(sessionId: string, encoded: string): boolean {@@ -2026,6 +2422,10 @@ function viewerConnectionKey(roomId: string, peerId: string): string {return `${roomId}:${peerId}`;}+function videoCodec(settings: QualitySettings): VideoCodecPreference {+ return settings.videoCodec ?? "automatic";+}+function authenticationErrorMessage(code: ErrorCode): string {switch (code) {case "ROOM_ACCESS_DENIED":diff --git a/src/shared/protocol.ts b/src/shared/protocol.tsindex c699a45d..3dc6e90b 100644--- a/src/shared/protocol.ts+++ b/src/shared/protocol.ts@@ -7,6 +7,12 @@ export const MAX_VIEWERS_PER_ROOM_LIMIT = 20;export const MAX_PARTICIPANTS_PER_ROOM_LIMIT = MAX_VIEWERS_PER_ROOM_LIMIT + 1;export const MAX_SIGNAL_BYTES = 64 * 1024;export const SIGNALING_PROTOCOL = "screener-v9";+export const SIGNAL_CLOSE_CODES = {+ sessionReplaced: 4001,+ clientReconnect: 4002,+ authenticationFailed: 4003,+ viewerAccessRevoked: 4004,+} as const;export const ROOM_CODE_LENGTH = 4;export const MAX_MEDIA_ROUTE_REVISION = Number.MAX_SAFE_INTEGER;export const MAX_SFU_TOKEN_LENGTH = 8 * 1024;@@ -182,6 +188,85 @@ export type VideoCodecPreference = z.infer<typeof videoCodecPreferenceSchema>;+export const codecTransitionGenerationSchema = z+ .number()+ .int()+ .min(1)+ .max(Number.MAX_SAFE_INTEGER);+export type CodecTransitionGeneration = z.infer<+ typeof codecTransitionGenerationSchema+>;+export const resumeAttemptSchema = z+ .number()+ .int()+ .min(1)+ .max(Number.MAX_SAFE_INTEGER);+export type ResumeAttempt = z.infer<typeof resumeAttemptSchema>;+export const codecPreparationBindingSchema = z.discriminatedUnion("kind", [+ z+ .object({+ kind: z.literal("peer"),+ childPeerId: opaqueIdSchema,+ connectionId: opaqueIdSchema,+ })+ .strict(),+ z+ .object({+ kind: z.literal("sfu"),+ publicationGeneration: opaqueIdSchema,+ })+ .strict(),+]);+export type CodecPreparationBinding = z.infer<+ typeof codecPreparationBindingSchema+>;++export const codecProofBindingSchema = z.discriminatedUnion("kind", [+ z+ .object({+ kind: z.literal("peer"),+ connectionId: opaqueIdSchema,+ })+ .strict(),+ z+ .object({+ kind: z.literal("sfu"),+ connectionId: opaqueIdSchema,+ publicationGeneration: opaqueIdSchema,+ })+ .strict(),+]);+export type CodecProofBinding = z.infer<typeof codecProofBindingSchema>;++const codecProofTimestampSchema = z+ .number()+ .finite()+ .min(0)+ .max(Number.MAX_SAFE_INTEGER);+const codecProofIdentityStringSchema = z.string().min(1).max(512);+export const codecProofEvidenceSchema = z+ .object({+ baselineSampleTimestampMs: codecProofTimestampSchema,+ sampleTimestampMs: codecProofTimestampSchema,+ rtpStatsId: codecProofIdentityStringSchema,+ rtpSsrc: z.number().int().min(0).max(0xffff_ffff).nullable(),+ rtpMid: codecProofIdentityStringSchema.nullable(),+ rtpRid: codecProofIdentityStringSchema.nullable(),+ trackIdentifier: codecProofIdentityStringSchema.nullable(),+ framesDecodedDelta: z.number().int().min(1).max(10_000),+ actualCodec: z.enum(["h264", "vp8", "other"]),+ })+ .strict()+ .refine(+ (evidence) =>+ evidence.sampleTimestampMs > evidence.baselineSampleTimestampMs,+ {+ message: "Codec proof sample must follow its decoded-frame baseline",+ path: ["sampleTimestampMs"],+ },+ );+export type CodecProofEvidence = z.infer<typeof codecProofEvidenceSchema>;+export const screenAudioQualitySchema = z.enum(["saver","music",@@ -294,6 +379,7 @@ export const signalPayloadSchema = z.discriminatedUnion("kind", [.object({kind: z.literal("description"),connectionId: opaqueIdSchema,+ negotiationGeneration: codecTransitionGenerationSchema.nullable(),description: sessionDescriptionSchema,}).strict(),@@ -312,6 +398,13 @@ export const preparedRouteCandidateSchema = zchildPeerId: opaqueIdSchema,connectionId: opaqueIdSchema,transport: z.enum(["direct", "sfu"]),+ codecTransition: z+ .object({+ generation: codecTransitionGenerationSchema,+ videoCodec: videoCodecPreferenceSchema,+ })+ .strict()+ .nullable(),}).strict();export type PreparedRouteCandidate = z.infer<@@ -483,7 +576,29 @@ export const participantRouteAssignmentSchema = z.refine((peerIds) => new Set(peerIds).size === peerIds.length),sfuPublicationGeneration: sfuPublicationGenerationSchema.nullable(),})- .strict();+ .strict()+ .superRefine((assignment, context) => {+ if (+ assignment.upstream.kind === "sfu" &&+ assignment.sfuPublicationGeneration === null+ ) {+ context.addIssue({+ code: "custom",+ message: "An SFU upstream requires its publication generation",+ path: ["sfuPublicationGeneration"],+ });+ }+ if (+ assignment.upstream.kind === "peer" &&+ assignment.sfuPublicationGeneration !== null+ ) {+ context.addIssue({+ code: "custom",+ message: "A peer upstream cannot own an SFU publication generation",+ path: ["sfuPublicationGeneration"],+ });+ }+ });export type ParticipantRouteAssignment = z.infer<typeof participantRouteAssignmentSchema>;@@ -706,7 +821,48 @@ export const clientMessageSchema = z.union([.object({type: z.literal("set-sharing-paused"),shareGeneration: opaqueIdSchema,- paused: z.boolean(),+ paused: z.literal(true),+ })+ .strict(),+ z+ .object({+ type: z.literal("request-sharing-resume"),+ shareGeneration: opaqueIdSchema,+ })+ .strict(),+ z+ .object({+ type: z.literal("sharing-source-enabled"),+ shareGeneration: opaqueIdSchema,+ codecGeneration: codecTransitionGenerationSchema.nullable(),+ resumeAttempt: resumeAttemptSchema,+ })+ .strict(),+ z+ .object({+ type: z.literal("request-video-codec-transition"),+ shareGeneration: opaqueIdSchema,+ videoCodec: videoCodecPreferenceSchema,+ })+ .strict(),+ z+ .object({+ type: z.literal("video-codec-prepared"),+ shareGeneration: opaqueIdSchema,+ generation: codecTransitionGenerationSchema,+ binding: codecPreparationBindingSchema,+ accepted: z.boolean(),+ })+ .strict(),+ z+ .object({+ type: z.literal("video-codec-proof"),+ shareGeneration: opaqueIdSchema,+ generation: codecTransitionGenerationSchema,+ resumeAttempt: resumeAttemptSchema,+ routeRevision: mediaRouteRevisionSchema,+ binding: codecProofBindingSchema,+ evidence: codecProofEvidenceSchema,}).strict(),z@@ -872,6 +1028,63 @@ export const serverMessageSchema = z.union([qualitySettings: qualitySettingsSchema,}).strict(),+ z+ .object({+ type: z.literal("video-codec-prepare"),+ shareGeneration: opaqueIdSchema,+ generation: codecTransitionGenerationSchema,+ videoCodec: videoCodecPreferenceSchema,+ binding: codecPreparationBindingSchema,+ })+ .strict(),+ z+ .object({+ type: z.literal("video-codec-proof-request"),+ shareGeneration: opaqueIdSchema,+ generation: codecTransitionGenerationSchema,+ resumeAttempt: resumeAttemptSchema,+ routeRevision: mediaRouteRevisionSchema,+ expectedCodec: z.enum(["h264", "vp8"]).nullable(),+ binding: codecProofBindingSchema,+ })+ .strict(),+ z+ .object({+ type: z.literal("video-codec-result"),+ generation: codecTransitionGenerationSchema,+ videoCodec: videoCodecPreferenceSchema,+ status: z.enum([+ "prepared",+ "committed",+ "rollback-prepared",+ "failed",+ ]),+ failure: z+ .enum([+ "preparation-failed",+ "proof-failed",+ "rollback-failed",+ "stale-binding",+ ])+ .nullable(),+ })+ .strict(),+ z+ .object({+ type: z.literal("sharing-resume-authorized"),+ shareGeneration: opaqueIdSchema,+ codecGeneration: codecTransitionGenerationSchema.nullable(),+ resumeAttempt: resumeAttemptSchema,+ })+ .strict(),+ z+ .object({+ type: z.literal("pause-sharing-source"),+ shareGeneration: opaqueIdSchema,+ codecGeneration: codecTransitionGenerationSchema.nullable(),+ resumeAttempt: resumeAttemptSchema.nullable(),+ })+ .strict(),z.object({type: z.literal("viewer-quality-evidence"),diff --git a/tests/client-state.test.ts b/tests/client-state.test.tsindex 3f7017c8..05aec1c9 100644--- a/tests/client-state.test.ts+++ b/tests/client-state.test.ts@@ -542,6 +542,23 @@ describe("site access API", () => {});});+ it("does not expose an English server error body to the access page", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn<typeof fetch>().mockResolvedValue(+ new Response(JSON.stringify({ error: "Internal Server Error" }), {+ status: 503,+ headers: { "Content-Type": "application/json" },+ }),+ ),+ );++ await expect(getSiteAccess()).rejects.toMatchObject({+ status: 503,+ message: "站点验证服务暂时不可用 (503)",+ });+ });+it("does not send a raw bearer token when creating a room by default", async () => {const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify({ error: "test response" }), {@@ -629,12 +646,62 @@ describe("room codes", () => {describe("client signaling recovery policy", () => {it("does not reconnect a session that another tab replaced", () => {expect(shouldReconnectSignaling(4001)).toBe(false);+ expect(shouldReconnectSignaling(4003)).toBe(false);expect(shouldReconnectSignaling(4004)).toBe(false);expect(shouldReconnectSignaling(1008)).toBe(false);expect(shouldReconnectSignaling(4002)).toBe(true);expect(shouldReconnectSignaling(1006)).toBe(true);});+ it("classifies a close-only authentication failure without claiming replacement", () => {+ const sockets: FakeWebSocket[] = [];+ class FakeWebSocket extends EventTarget {+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ readyState = FakeWebSocket.OPEN;+ readonly send = vi.fn();+ readonly close = vi.fn();++ constructor(readonly url: string) {+ super();+ sockets.push(this);+ }+ }+ vi.stubGlobal("WebSocket", FakeWebSocket);+ vi.stubGlobal("window", {+ location: new URL("https://share.test/r/1234"),+ setTimeout,+ clearTimeout,+ });+ const onTerminated = vi.fn();+ const signal = new SignalingClient(+ {+ roomId: "1234",+ role: "viewer",+ clientId: "viewer-client",+ },+ {+ onMessage: () => undefined,+ onStatus: () => undefined,+ onTerminated,+ onAccessRequired: () => undefined,+ },+ );++ signal.start();+ sockets[0]!.dispatchEvent(new Event("open"));+ const closed = new Event("close");+ Object.defineProperties(closed, {+ code: { value: 4003 },+ reason: { value: "Authentication required" },+ });+ sockets[0]!.dispatchEvent(closed);++ expect(onTerminated).toHaveBeenCalledOnce();+ expect(onTerminated).toHaveBeenCalledWith("SIGNAL_TERMINATED");+ expect(sockets).toHaveLength(1);+ });+it("restarts only an authenticated active signaling session on request", () => {const sockets: FakeWebSocket[] = [];class FakeWebSocket extends EventTarget {@@ -700,6 +767,134 @@ describe("client signaling recovery policy", () => {expect(signal.reconnect()).toBe(false);});+ it("keeps a Host paused across reconnect until the server confirms Resume", () => {+ vi.useFakeTimers();+ const sockets: FakeWebSocket[] = [];+ class FakeWebSocket extends EventTarget {+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ readyState = FakeWebSocket.OPEN;+ readonly send = vi.fn();+ readonly close = vi.fn(() => {+ this.readyState = FakeWebSocket.CLOSING;+ });++ constructor(readonly url: string) {+ super();+ sockets.push(this);+ }+ }+ vi.stubGlobal("WebSocket", FakeWebSocket);+ vi.stubGlobal("window", {+ location: new URL("https://share.test/r/1234"),+ setTimeout: globalThis.setTimeout,+ clearTimeout: globalThis.clearTimeout,+ });+ const signal = new SignalingClient(+ {+ roomId: "1234",+ role: "host",+ token: "h".repeat(43),+ clientId: "host-client",+ shareGeneration: "share_generation_12345678",+ sharingPaused: true,+ },+ {+ onMessage: () => undefined,+ onStatus: () => undefined,+ onTerminated: () => undefined,+ onAccessRequired: () => undefined,+ },+ );+ const receive = (socket: FakeWebSocket, value: object) => {+ const event = new Event("message");+ Object.defineProperty(event, "data", { value: JSON.stringify(value) });+ socket.dispatchEvent(event);+ };+ const authenticate = (socket: FakeWebSocket) => {+ socket.dispatchEvent(new Event("open"));+ receive(socket, {+ type: "authenticated",+ protocol: "screener-v9",+ role: "host",+ peerId: "host_12345678",+ roomExpiresAt: null,+ maxViewers: 8,+ endpointMediaCopyCapacity: 2,+ hostOnline: true,+ hostPaused: true,+ connectionId: null,+ viewerPeerIds: [],+ iceConfig: { iceServers: [] },+ codeEntryPolicy: "open",+ viewerAuthorizationGeneration: "viewer_generation_12345678",+ });+ };+ const reconnect = (socket: FakeWebSocket) => {+ expect(signal.reconnect()).toBe(true);+ const close = new Event("close");+ Object.defineProperties(close, {+ code: { value: 4002 },+ reason: { value: "client reconnect" },+ });+ socket.dispatchEvent(close);+ vi.advanceTimersByTime(750);+ };++ signal.start();+ authenticate(sockets[0]!);+ expect(+ signal.confirmSharingResumed({+ type: "sharing-resume-authorized",+ shareGeneration: "share_generation_12345678",+ codecGeneration: null,+ resumeAttempt: 1,+ }),+ ).toBe(true);+ expect(+ JSON.parse(String(sockets[0]!.send.mock.calls.at(-1)![0])),+ ).toMatchObject({+ type: "sharing-source-enabled",+ resumeAttempt: 1,+ });++ reconnect(sockets[0]!);+ sockets[1]!.dispatchEvent(new Event("open"));+ expect(JSON.parse(String(sockets[1]!.send.mock.calls[0]![0]))).toMatchObject({+ type: "authenticate",+ sharingPaused: true,+ });+ receive(sockets[1]!, {+ type: "authenticated",+ protocol: "screener-v9",+ role: "host",+ peerId: "host_12345678",+ roomExpiresAt: null,+ maxViewers: 8,+ endpointMediaCopyCapacity: 2,+ hostOnline: true,+ hostPaused: true,+ connectionId: null,+ viewerPeerIds: [],+ iceConfig: { iceServers: [] },+ codeEntryPolicy: "open",+ viewerAuthorizationGeneration: "viewer_generation_12345678",+ });+ receive(sockets[1]!, {+ type: "host-status",+ online: true,+ paused: false,+ });++ reconnect(sockets[1]!);+ sockets[2]!.dispatchEvent(new Event("open"));+ expect(JSON.parse(String(sockets[2]!.send.mock.calls[0]![0]))).toMatchObject({+ type: "authenticate",+ sharingPaused: false,+ });+ signal.stop();+ });+it("confirms an exact silent partition before replacing the socket immediately", () => {vi.useFakeTimers();let now = 0;@@ -1019,9 +1214,7 @@ describe("client signaling recovery policy", () => {sockets[0]!.dispatchEvent(close);expect(onTerminated).toHaveBeenCalledOnce();- expect(onTerminated).toHaveBeenCalledWith(- "页面版本已更新,请刷新后重试",- );+ expect(onTerminated).toHaveBeenCalledWith("STALE_CLIENT");expect(sockets[0]!.close).toHaveBeenCalledOnce();expect(sockets).toHaveLength(1);},diff --git a/tests/codec-proof.test.ts b/tests/codec-proof.test.tsnew file mode 100644index 00000000..0dec6aff--- /dev/null+++ b/tests/codec-proof.test.ts@@ -0,0 +1,134 @@+import { describe, expect, it, vi } from "vitest";++import {+ CodecProofReporter,+ type CodecProofRouteSample,+} from "../src/client/media/codec-proof.ts";+import { EMPTY_METRICS } from "../src/client/types.ts";+import type { ClientMessage, ServerMessage } from "../src/shared/protocol.ts";++const request = {+ type: "video-codec-proof-request",+ shareGeneration: "share_generation_12345678",+ generation: 1,+ resumeAttempt: 3,+ routeRevision: 7,+ expectedCodec: "vp8",+ binding: { kind: "peer", connectionId: "connection_12345678" },+} satisfies Extract<ServerMessage, { type: "video-codec-proof-request" }>;++function sample(+ timestamp: number,+ framesDecodedDelta: number | null,+ rtpStatsId = "inbound_video_12345678",+): CodecProofRouteSample {+ return {+ routeRevision: 7,+ binding: { kind: "peer", connectionId: "connection_12345678" },+ metrics: {+ ...EMPTY_METRICS,+ sampleTimestampMs: timestamp,+ rtpStatsId,+ rtpSsrc: 42,+ rtpMid: "0",+ trackIdentifier: "track_12345678",+ intervalFramesDecoded: framesDecodedDelta,+ codec: "video/VP8",+ },+ };+}++describe("CodecProofReporter", () => {+ it("proves only a later decoded sample on the exact frozen binding", () => {+ const sent: ClientMessage[] = [];+ const reporter = new CodecProofReporter((message) => {+ sent.push(message);+ return true;+ });++ expect(reporter.request(request)).toBe(true);+ reporter.offer(sample(100, 1));+ reporter.offer(sample(200, 0));+ expect(sent).toEqual([]);+ reporter.offer(sample(300, 5));++ expect(sent).toEqual([+ expect.objectContaining({+ type: "video-codec-proof",+ generation: 1,+ resumeAttempt: 3,+ routeRevision: 7,+ evidence: expect.objectContaining({+ baselineSampleTimestampMs: 100,+ sampleTimestampMs: 300,+ framesDecodedDelta: 5,+ actualCodec: "vp8",+ }),+ }),+ ]);+ });++ it("re-baselines when the inbound RTP stats object changes", () => {+ const send = vi.fn((_message: ClientMessage) => true);+ const reporter = new CodecProofReporter(send);+ reporter.request(request);++ reporter.offer(sample(100, 0, "old_inbound_12345678"));+ reporter.offer(sample(200, 1, "new_inbound_12345678"));+ expect(send).not.toHaveBeenCalled();+ reporter.offer(sample(300, 2, "new_inbound_12345678"));+ expect(send).toHaveBeenCalledOnce();+ });++ it("retains a request until an exact-route baseline becomes available", () => {+ const send = vi.fn(() => true);+ const reporter = new CodecProofReporter(send);+ expect(reporter.request(request)).toBe(true);+ reporter.offer({ ...sample(150, 1), routeRevision: 8 });+ expect(send).not.toHaveBeenCalled();+ reporter.offer(sample(200, 0));+ reporter.offer(sample(300, 2));+ expect(send).toHaveBeenCalledOnce();+ });++ it("ignores out-of-order samples without replacing the current baseline", () => {+ const send = vi.fn((_message: ClientMessage) => true);+ const reporter = new CodecProofReporter(send);+ reporter.request(request);++ reporter.offer(sample(200, 0));+ reporter.offer(sample(100, 1, "older_inbound_12345678"));+ reporter.offer(sample(300, 2));++ expect(send).toHaveBeenCalledOnce();+ expect(send.mock.calls[0]?.[0]).toMatchObject({+ type: "video-codec-proof",+ evidence: {+ baselineSampleTimestampMs: 200,+ sampleTimestampMs: 300,+ },+ });+ });++ it("uses the first exact sample after the proof request only as a baseline", () => {+ const send = vi.fn((_message: ClientMessage) => true);+ const reporter = new CodecProofReporter(send);++ reporter.request(request);+ reporter.offer(sample(200, 1));+ reporter.offer(sample(300, 0));+ expect(send).not.toHaveBeenCalled();++ reporter.offer(sample(400, 2));+ expect(send).toHaveBeenCalledOnce();+ expect(send.mock.calls[0]?.[0]).toMatchObject({+ type: "video-codec-proof",+ resumeAttempt: 3,+ evidence: {+ baselineSampleTimestampMs: 200,+ sampleTimestampMs: 400,+ framesDecodedDelta: 2,+ },+ });+ });+});diff --git a/tests/codec-transition.test.ts b/tests/codec-transition.test.tsnew file mode 100644index 00000000..0e866943--- /dev/null+++ b/tests/codec-transition.test.ts@@ -0,0 +1,1423 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import {+ CodecTransitionCoordinator,+ type CodecTransitionCoordinatorOptions,+} from "../src/server/codec-transition.ts";+import type {+ CodecRouteSnapshot,+ CodecRouteTarget,+} from "../src/server/hybrid-media-router.ts";+import {+ clientMessageSchema,+ type CodecProofEvidence,+ type CodecTransitionGeneration,+ type ResumeAttempt,+ type ServerMessage,+} from "../src/shared/protocol.ts";++interface ResumeAuthorization {+ codecGeneration: CodecTransitionGeneration | null;+ resumeAttempt: ResumeAttempt;+}++const resumeAuthorizations = new WeakMap<+ CodecTransitionCoordinator,+ ResumeAuthorization[]+>();++const peerTarget = (+ viewerPeerId = "viewer_12345678",+ viewerSessionId = "viewer_session_12345678",+ parentSessionId = "host_session_12345678",+ connectionId = "connection_12345678",+): CodecRouteTarget => ({+ viewerPeerId,+ viewerSessionId,+ preparationOwnerSessionId: parentSessionId,+ preparationBinding: {+ kind: "peer",+ childPeerId: viewerPeerId,+ connectionId,+ },+ proofBinding: { kind: "peer", connectionId },+ routeRevision: 7,+ proofReady: true,+});++const sfuTarget = (+ publicationGeneration = "publication_generation_12345678",+ connectionId = "sfu_connection_12345678",+ routeRevision = 7,+ proofReady = true,+ viewerPeerId = "viewer_sfu_12345678",+ viewerSessionId = "viewer_session_sfu_12345678",+): CodecRouteTarget => ({+ viewerPeerId,+ viewerSessionId,+ preparationOwnerSessionId: "host_session_12345678",+ preparationBinding: {+ kind: "sfu",+ publicationGeneration,+ },+ proofBinding: {+ kind: "sfu",+ connectionId,+ publicationGeneration,+ },+ routeRevision,+ proofReady,+});++function deferred<T>() {+ let resolve!: (value: T | PromiseLike<T>) => void;+ const promise = new Promise<T>((resolvePromise) => {+ resolve = resolvePromise;+ });+ return { promise, resolve };+}++const flushPromises = async () => {+ await Promise.resolve();+ await Promise.resolve();+};++function createHarness(+ initialTargets: CodecRouteTarget[] = [peerTarget()],+ options: {+ createGeneration?: () => CodecTransitionGeneration;+ createResumeAttempt?: () => ResumeAttempt;+ routeWaitRevision?: number | null;+ beginSfuReplacement?: CodecTransitionCoordinatorOptions["beginSfuReplacement"];+ parkSfuReplacement?: CodecTransitionCoordinatorOptions["parkSfuReplacement"];+ beginSfuProof?: CodecTransitionCoordinatorOptions["beginSfuProof"];+ abortSfuReplacement?: CodecTransitionCoordinatorOptions["abortSfuReplacement"];+ } = {},+) {+ let snapshot: CodecRouteSnapshot | null = {+ revision: 7,+ targets: initialTargets,+ };+ let nextGeneration = 1;+ let nextResumeAttempt = 1;+ const routeWaitRevision: number | null =+ options.routeWaitRevision === undefined ? 9 : options.routeWaitRevision;+ let routeWaitHandler: (() => void) | null = null;+ const sent: Array<{ sessionId: string; message: ServerMessage }> = [];+ const committed: string[] = [];+ const resumes: ResumeAuthorization[] = [];+ const confirmations: ResumeAuthorization[] = [];+ const pauses: Array<CodecTransitionGeneration | null> = [];+ const pauseAttempts: Array<ResumeAttempt | null> = [];+ const releases: string[] = [];+ const routeWaitCalls: Array<{+ roomId: string;+ viewerPeerIds: string[];+ }> = [];+ const sfuReplacementCalls: Array<+ Parameters<CodecTransitionCoordinatorOptions["beginSfuReplacement"]>[0]+ > = [];+ const parkedSfuReplacements: Array<{+ roomId: string;+ generation: CodecTransitionGeneration;+ }> = [];+ const sfuProofCalls: Array<{+ roomId: string;+ generation: CodecTransitionGeneration;+ timeoutMs: number;+ }> = [];+ const abortedSfuReplacements: Array<{+ roomId: string;+ generation: CodecTransitionGeneration;+ }> = [];+ const coordinator = new CodecTransitionCoordinator({+ snapshot: () => snapshot,+ sendToSession: (sessionId, message) => sent.push({ sessionId, message }),+ commitCodec: (_roomId, codec) => committed.push(codec),+ authorizeResume: (+ _roomId,+ _hostSessionId,+ _shareGeneration,+ codecGeneration,+ resumeAttempt,+ ) => resumes.push({ codecGeneration, resumeAttempt }),+ confirmSourceEnabled: (+ _roomId,+ _hostSessionId,+ _shareGeneration,+ codecGeneration,+ resumeAttempt,+ ) => {+ confirmations.push({ codecGeneration, resumeAttempt });+ return true;+ },+ restoreAuthoritativePause: (+ _roomId,+ _hostSessionId,+ _shareGeneration,+ codecGeneration,+ resumeAttempt,+ ) => {+ pauses.push(codecGeneration);+ pauseAttempts.push(resumeAttempt);+ },+ returnTargetsToRouteWait: (roomId, viewerPeerIds) => {+ routeWaitCalls.push({ roomId, viewerPeerIds: [...viewerPeerIds] });+ routeWaitHandler?.();+ return routeWaitRevision;+ },+ beginSfuReplacement: (input) => {+ sfuReplacementCalls.push({ ...input });+ return options.beginSfuReplacement?.(input) ?? Promise.resolve(null);+ },+ parkSfuReplacement: (roomId, generation) => {+ parkedSfuReplacements.push({ roomId, generation });+ return options.parkSfuReplacement?.(roomId, generation) ?? false;+ },+ beginSfuProof: (roomId, generation, timeoutMs) => {+ sfuProofCalls.push({ roomId, generation, timeoutMs });+ return options.beginSfuProof?.(roomId, generation, timeoutMs) ?? false;+ },+ abortSfuReplacement: (roomId, generation) => {+ abortedSfuReplacements.push({ roomId, generation });+ options.abortSfuReplacement?.(roomId, generation);+ },+ releaseRoutePause: (roomId) => releases.push(roomId),+ timeoutMs: 100,+ createGeneration: options.createGeneration ?? (() => nextGeneration++),+ createResumeAttempt:+ options.createResumeAttempt ?? (() => nextResumeAttempt++),+ });+ resumeAuthorizations.set(coordinator, resumes);+ return {+ coordinator,+ sent,+ committed,+ resumes,+ confirmations,+ pauses,+ pauseAttempts,+ releases,+ routeWaitCalls,+ sfuReplacementCalls,+ parkedSfuReplacements,+ sfuProofCalls,+ abortedSfuReplacements,+ setSnapshot(next: CodecRouteSnapshot | null) {+ snapshot = next;+ },+ setRouteWaitHandler(next: (() => void) | null) {+ routeWaitHandler = next;+ },+ };+}++const start = (coordinator: CodecTransitionCoordinator) =>+ coordinator.start({+ roomId: "1234",+ hostSessionId: "host_session_12345678",+ shareGeneration: "share_generation_12345678",+ requested: "h264",+ previous: "vp8",+ });++const prepared = (+ coordinator: CodecTransitionCoordinator,+ accepted = true,+ generation: CodecTransitionGeneration = 1,+) =>+ coordinator.prepared("1234", "host_session_12345678", {+ type: "video-codec-prepared",+ shareGeneration: "share_generation_12345678",+ generation,+ binding: {+ kind: "peer",+ childPeerId: "viewer_12345678",+ connectionId: "connection_12345678",+ },+ accepted,+ });++const sfuPrepared = (+ coordinator: CodecTransitionCoordinator,+ publicationGeneration: string,+ accepted = true,+ generation: CodecTransitionGeneration = 1,+) =>+ coordinator.prepared("1234", "host_session_12345678", {+ type: "video-codec-prepared",+ shareGeneration: "share_generation_12345678",+ generation,+ binding: {+ kind: "sfu",+ publicationGeneration,+ },+ accepted,+ });++const requestResume = (coordinator: CodecTransitionCoordinator) =>+ coordinator.requestResume({+ roomId: "1234",+ hostSessionId: "host_session_12345678",+ shareGeneration: "share_generation_12345678",+ });++const acknowledgeLatestResume = (coordinator: CodecTransitionCoordinator) => {+ const authorization = resumeAuthorizations.get(coordinator)?.at(-1);+ if (!authorization) return false;+ return coordinator.sourceEnabled({+ roomId: "1234",+ hostSessionId: "host_session_12345678",+ shareGeneration: "share_generation_12345678",+ ...authorization,+ });+};++const resume = (coordinator: CodecTransitionCoordinator) => {+ const result = requestResume(coordinator);+ if (result !== "busy") {+ acknowledgeLatestResume(coordinator);+ }+ return result;+};++const latestResumeAttempt = (coordinator: CodecTransitionCoordinator) =>+ resumeAuthorizations.get(coordinator)?.at(-1)?.resumeAttempt ?? 1;++const proofEvidence = (+ actualCodec: CodecProofEvidence["actualCodec"],+ overrides: Partial<CodecProofEvidence> = {},+): CodecProofEvidence => ({+ baselineSampleTimestampMs: 100,+ sampleTimestampMs: 200,+ rtpStatsId: "inbound_rtp_1",+ rtpSsrc: 1_234,+ rtpMid: "0",+ rtpRid: null,+ trackIdentifier: "remote_video_track_1",+ framesDecodedDelta: 1,+ actualCodec,+ ...overrides,+});++const proof = (+ coordinator: CodecTransitionCoordinator,+ actualCodec: CodecProofEvidence["actualCodec"],+ options: {+ generation?: CodecTransitionGeneration;+ resumeAttempt?: ResumeAttempt;+ routeRevision?: number;+ evidence?: Partial<CodecProofEvidence>;+ } = {},+) =>+ coordinator.proof("1234", "viewer_session_12345678", {+ type: "video-codec-proof",+ shareGeneration: "share_generation_12345678",+ generation: options.generation ?? 1,+ resumeAttempt:+ options.resumeAttempt ?? latestResumeAttempt(coordinator),+ routeRevision: options.routeRevision ?? 7,+ binding: { kind: "peer", connectionId: "connection_12345678" },+ evidence: proofEvidence(actualCodec, options.evidence),+ });++const sfuProof = (+ coordinator: CodecTransitionCoordinator,+ actualCodec: CodecProofEvidence["actualCodec"],+ publicationGeneration: string,+ connectionId: string,+ options: {+ generation?: CodecTransitionGeneration;+ resumeAttempt?: ResumeAttempt;+ routeRevision?: number;+ evidence?: Partial<CodecProofEvidence>;+ } = {},+) =>+ coordinator.proof("1234", "viewer_session_sfu_12345678", {+ type: "video-codec-proof",+ shareGeneration: "share_generation_12345678",+ generation: options.generation ?? 1,+ resumeAttempt:+ options.resumeAttempt ?? latestResumeAttempt(coordinator),+ routeRevision: options.routeRevision ?? 7,+ binding: {+ kind: "sfu",+ connectionId,+ publicationGeneration,+ },+ evidence: proofEvidence(actualCodec, options.evidence),+ });++describe("CodecTransitionCoordinator", () => {+ beforeEach(() => vi.useFakeTimers());++ afterEach(() => {+ vi.clearAllTimers();+ vi.useRealTimers();+ });++ it("waits without a timer after preparation and commits only after decoded proof", () => {+ const harness = createHarness();++ expect(start(harness.coordinator)).toBe("started");+ expect(harness.sent.at(-1)?.message.type).toBe("video-codec-prepare");+ prepared(harness.coordinator);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-result",+ status: "prepared",+ videoCodec: "h264",+ });++ vi.advanceTimersByTime(10_000);+ expect(harness.committed).toEqual([]);+ expect(harness.pauses).toEqual([]);++ expect(resume(harness.coordinator)).toBe("started-proof");+ expect(harness.resumes).toEqual([+ { codecGeneration: 1, resumeAttempt: 1 },+ ]);+ expect(harness.releases).toEqual([]);+ proof(harness.coordinator, "h264");++ expect(harness.committed).toEqual(["h264"]);+ expect(harness.releases).toEqual(["1234"]);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-result",+ status: "committed",+ failure: null,+ });+ });++ it("keeps the room paused and withholds proof until the exact source ack", () => {+ const harness = createHarness();+ start(harness.coordinator);+ prepared(harness.coordinator);++ expect(requestResume(harness.coordinator)).toBe("started-proof");+ expect(harness.confirmations).toEqual([]);+ expect(+ harness.sent.filter(+ ({ message }) => message.type === "video-codec-proof-request",+ ),+ ).toEqual([]);+ expect(+ harness.coordinator.sourceEnabled({+ roomId: "1234",+ hostSessionId: "host_session_12345678",+ shareGeneration: "share_generation_12345678",+ codecGeneration: 1,+ resumeAttempt: 2,+ }),+ ).toBe(false);++ expect(acknowledgeLatestResume(harness.coordinator)).toBe(true);+ expect(harness.confirmations).toEqual([+ { codecGeneration: 1, resumeAttempt: 1 },+ ]);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-proof-request",+ generation: 1,+ resumeAttempt: 1,+ });++ proof(harness.coordinator, "h264", { resumeAttempt: 2 });+ expect(harness.committed).toEqual([]);+ proof(harness.coordinator, "h264");+ expect(harness.committed).toEqual(["h264"]);+ });++ it("invalidates an old source ack and proof when Pause opens a new attempt", () => {+ const harness = createHarness();+ start(harness.coordinator);+ prepared(harness.coordinator);+ requestResume(harness.coordinator);+ const first = harness.resumes.at(-1)!;++ harness.coordinator.pause({+ roomId: "1234",+ hostSessionId: "host_session_12345678",+ shareGeneration: "share_generation_12345678",+ });+ expect(+ harness.coordinator.sourceEnabled({+ roomId: "1234",+ hostSessionId: "host_session_12345678",+ shareGeneration: "share_generation_12345678",+ ...first,+ }),+ ).toBe(false);++ requestResume(harness.coordinator);+ const second = harness.resumes.at(-1)!;+ expect(second.resumeAttempt).toBeGreaterThan(first.resumeAttempt);+ expect(acknowledgeLatestResume(harness.coordinator)).toBe(true);+ proof(harness.coordinator, "h264", {+ resumeAttempt: first.resumeAttempt,+ });+ expect(harness.committed).toEqual([]);+ proof(harness.coordinator, "h264");+ expect(harness.committed).toEqual(["h264"]);+ });++ it("bounds an ordinary Resume ack and permits a later retry", () => {+ const harness = createHarness([]);++ expect(requestResume(harness.coordinator)).toBe("normal");+ expect(harness.releases).toEqual([]);+ vi.advanceTimersByTime(100);+ expect(harness.pauses).toEqual([null]);+ expect(harness.pauseAttempts).toEqual([1]);+ expect(harness.releases).toEqual([]);++ expect(requestResume(harness.coordinator)).toBe("normal");+ expect(harness.resumes.at(-1)).toEqual({+ codecGeneration: null,+ resumeAttempt: 2,+ });+ expect(acknowledgeLatestResume(harness.coordinator)).toBe(true);+ expect(harness.releases).toEqual(["1234"]);+ });++ it("invalidates an ordinary Resume across a Host session replacement", () => {+ const harness = createHarness([]);+ requestResume(harness.coordinator);++ harness.coordinator.invalidateHostSession(+ "1234",+ "host_session_reconnected_12345678",+ );++ expect(harness.pauses).toEqual([null]);+ expect(harness.pauseAttempts).toEqual([null]);+ expect(acknowledgeLatestResume(harness.coordinator)).toBe(false);+ expect(harness.releases).toEqual([]);+ });++ it("uses one Resume deadline across source ack and proof", () => {+ const harness = createHarness();+ start(harness.coordinator);+ prepared(harness.coordinator);+ requestResume(harness.coordinator);++ vi.advanceTimersByTime(90);+ expect(acknowledgeLatestResume(harness.coordinator)).toBe(true);+ vi.advanceTimersByTime(10);++ expect(harness.pauses).toEqual([1]);+ expect(harness.pauseAttempts).toEqual([1]);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-prepare",+ generation: 2,+ videoCodec: "vp8",+ });+ });++ it("continues the same generation when a pending SFU target has left", async () => {+ const replacement = deferred<CodecRouteSnapshot | null>();+ const direct = peerTarget();+ const harness = createHarness(+ [direct, sfuTarget("publication_generation_old_12345678")],+ { beginSfuReplacement: () => replacement.promise },+ );+ start(harness.coordinator);++ harness.setSnapshot({+ revision: 8,+ targets: [{ ...direct, routeRevision: 8 }],+ });+ replacement.resolve(null);+ await flushPromises();++ expect(harness.abortedSfuReplacements).toEqual([+ { roomId: "1234", generation: 1 },+ ]);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-prepare",+ generation: 1,+ videoCodec: "h264",+ });+ expect(harness.sfuReplacementCalls).toHaveLength(1);+ });++ it("recomputes SFU need from the current snapshot for rollback", () => {+ const never = () => new Promise<CodecRouteSnapshot | null>(() => undefined);+ const direct = peerTarget();+ const harness = createHarness(+ [sfuTarget("publication_generation_old_12345678")],+ { beginSfuReplacement: never },+ );+ start(harness.coordinator);+ harness.setSnapshot({ revision: 8, targets: [direct] });++ vi.advanceTimersByTime(100);++ expect(harness.sfuReplacementCalls).toHaveLength(1);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-prepare",+ generation: 2,+ videoCodec: "vp8",+ });+ });++ it("parks a fresh SFU publication and gates proof until its route is ready", async () => {+ const oldPublication = "publication_generation_old_12345678";+ const freshPublication = "publication_generation_h264_12345678";+ const freshConnection = "sfu_connection_h264_12345678";+ const replacement = deferred<CodecRouteSnapshot | null>();+ const harness = createHarness([sfuTarget(oldPublication)], {+ beginSfuReplacement: () => replacement.promise,+ parkSfuReplacement: () => true,+ beginSfuProof: () => true,+ });++ expect(start(harness.coordinator)).toBe("started");+ expect(harness.sfuReplacementCalls).toEqual([+ {+ roomId: "1234",+ hostSessionId: "host_session_12345678",+ generation: 1,+ videoCodec: "h264",+ timeoutMs: 100,+ },+ ]);+ expect(harness.sent).toEqual([]);++ const freshPending = sfuTarget(+ freshPublication,+ freshConnection,+ 8,+ false,+ );+ const freshSnapshot = { revision: 8, targets: [freshPending] };+ harness.setSnapshot(freshSnapshot);+ replacement.resolve(freshSnapshot);+ await flushPromises();++ expect(+ harness.sent.filter(+ ({ message }) => message.type === "video-codec-prepare",+ ),+ ).toEqual([]);+ sfuPrepared(harness.coordinator, freshPublication);+ expect(harness.parkedSfuReplacements).toEqual([+ { roomId: "1234", generation: 1 },+ ]);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-result",+ generation: 1,+ status: "prepared",+ });++ vi.advanceTimersByTime(10_000);+ expect(harness.sfuReplacementCalls).toHaveLength(1);+ expect(harness.abortedSfuReplacements).toEqual([]);+ expect(harness.committed).toEqual([]);++ expect(resume(harness.coordinator)).toBe("started-proof");+ expect(harness.sfuProofCalls).toEqual([+ { roomId: "1234", generation: 1, timeoutMs: 100 },+ ]);+ expect(+ harness.sent.filter(+ ({ message }) => message.type === "video-codec-proof-request",+ ),+ ).toEqual([]);++ harness.setSnapshot({+ revision: 9,+ targets: [{ ...freshPending, routeRevision: 9, proofReady: true }],+ });+ harness.coordinator.participantChanged("1234");+ expect(harness.sent.at(-1)).toMatchObject({+ sessionId: "viewer_session_sfu_12345678",+ message: {+ type: "video-codec-proof-request",+ generation: 1,+ routeRevision: 9,+ binding: {+ kind: "sfu",+ connectionId: freshConnection,+ publicationGeneration: freshPublication,+ },+ },+ });++ sfuProof(+ harness.coordinator,+ "h264",+ freshPublication,+ freshConnection,+ { routeRevision: 9 },+ );+ expect(harness.committed).toEqual(["h264"]);+ expect(harness.releases).toEqual(["1234"]);+ });++ it("starts rollback with another fresh SFU generation after proof failure", async () => {+ const replacements = [+ deferred<CodecRouteSnapshot | null>(),+ deferred<CodecRouteSnapshot | null>(),+ ];+ let replacementIndex = 0;+ const harness = createHarness(+ [sfuTarget("publication_generation_old_12345678")],+ {+ beginSfuReplacement: () =>+ replacements[replacementIndex++]!.promise,+ parkSfuReplacement: () => true,+ beginSfuProof: () => true,+ },+ );++ start(harness.coordinator);+ const requestedPending = sfuTarget(+ "publication_generation_h264_12345678",+ "sfu_connection_h264_12345678",+ 8,+ false,+ );+ const requestedSnapshot = { revision: 8, targets: [requestedPending] };+ harness.setSnapshot(requestedSnapshot);+ replacements[0]!.resolve(requestedSnapshot);+ await flushPromises();+ sfuPrepared(+ harness.coordinator,+ "publication_generation_h264_12345678",+ );+ resume(harness.coordinator);+ harness.setSnapshot({+ revision: 9,+ targets: [{ ...requestedPending, routeRevision: 9, proofReady: true }],+ });+ harness.coordinator.participantChanged("1234");++ sfuProof(+ harness.coordinator,+ "vp8",+ "publication_generation_h264_12345678",+ "sfu_connection_h264_12345678",+ { routeRevision: 9 },+ );+ expect(harness.pauses).toEqual([1]);+ expect(harness.sfuReplacementCalls.map((call) => call.generation)).toEqual([+ 1, 2,+ ]);+ expect(harness.sfuReplacementCalls.at(-1)).toMatchObject({+ generation: 2,+ videoCodec: "vp8",+ });+ expect(harness.resumes).toHaveLength(1);++ const rollbackPending = sfuTarget(+ "publication_generation_rollback_12345678",+ "sfu_connection_rollback_12345678",+ 10,+ false,+ );+ const rollbackSnapshot = { revision: 10, targets: [rollbackPending] };+ harness.setSnapshot(rollbackSnapshot);+ replacements[1]!.resolve(rollbackSnapshot);+ await flushPromises();+ sfuPrepared(+ harness.coordinator,+ "publication_generation_rollback_12345678",+ true,+ 2,+ );+ expect(harness.parkedSfuReplacements).toEqual([+ { roomId: "1234", generation: 1 },+ { roomId: "1234", generation: 2 },+ ]);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-result",+ generation: 2,+ status: "rollback-prepared",+ failure: "proof-failed",+ });+ expect(harness.resumes).toHaveLength(1);++ expect(resume(harness.coordinator)).toBe("started-proof");+ harness.setSnapshot({+ revision: 11,+ targets: [{ ...rollbackPending, routeRevision: 11, proofReady: true }],+ });+ harness.coordinator.participantChanged("1234");+ sfuProof(+ harness.coordinator,+ "vp8",+ "publication_generation_rollback_12345678",+ "sfu_connection_rollback_12345678",+ { generation: 2, routeRevision: 11 },+ );++ expect(harness.committed).toEqual(["vp8"]);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-result",+ generation: 2,+ status: "committed",+ failure: "proof-failed",+ });+ });++ it("bounds SFU initialization while leaving a parked preparation timerless", async () => {+ const parkedReplacement = deferred<CodecRouteSnapshot | null>();+ const parkedHarness = createHarness(+ [sfuTarget("publication_generation_old_12345678")],+ {+ beginSfuReplacement: () => parkedReplacement.promise,+ parkSfuReplacement: () => true,+ },+ );+ start(parkedHarness.coordinator);+ const freshPending = sfuTarget(+ "publication_generation_parked_12345678",+ "sfu_connection_parked_12345678",+ 8,+ false,+ );+ const freshSnapshot = { revision: 8, targets: [freshPending] };+ parkedHarness.setSnapshot(freshSnapshot);+ parkedReplacement.resolve(freshSnapshot);+ await flushPromises();+ sfuPrepared(+ parkedHarness.coordinator,+ "publication_generation_parked_12345678",+ );+ vi.advanceTimersByTime(10_000);+ expect(parkedHarness.sfuReplacementCalls).toHaveLength(1);+ expect(parkedHarness.abortedSfuReplacements).toEqual([]);+ expect(parkedHarness.coordinator.blocksResume("1234")).toBe(true);++ const never = () => new Promise<CodecRouteSnapshot | null>(() => undefined);+ const boundedHarness = createHarness(+ [sfuTarget("publication_generation_old_12345678")],+ { beginSfuReplacement: never },+ );+ start(boundedHarness.coordinator);+ vi.advanceTimersByTime(100);+ expect(+ boundedHarness.sfuReplacementCalls.map((call) => ({+ generation: call.generation,+ videoCodec: call.videoCodec,+ })),+ ).toEqual([+ { generation: 1, videoCodec: "h264" },+ { generation: 2, videoCodec: "vp8" },+ ]);+ expect(boundedHarness.abortedSfuReplacements).toEqual([+ { roomId: "1234", generation: 1 },+ ]);++ vi.advanceTimersByTime(100);+ expect(boundedHarness.abortedSfuReplacements).toEqual([+ { roomId: "1234", generation: 1 },+ { roomId: "1234", generation: 2 },+ ]);+ expect(boundedHarness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-result",+ generation: 2,+ status: "failed",+ failure: "rollback-failed",+ });+ });++ it("retires a target that is no longer proof-ready before issuing proof", () => {+ const target = peerTarget();+ const harness = createHarness([target]);++ start(harness.coordinator);+ prepared(harness.coordinator);+ expect(requestResume(harness.coordinator)).toBe("started-proof");++ harness.setSnapshot({+ revision: 8,+ targets: [{ ...target, routeRevision: 8, proofReady: false }],+ });+ harness.coordinator.participantChanged("1234");+ expect(acknowledgeLatestResume(harness.coordinator)).toBe(true);++ expect(harness.routeWaitCalls).toEqual([+ { roomId: "1234", viewerPeerIds: ["viewer_12345678"] },+ ]);+ expect(+ harness.sent.filter(+ ({ message }) => message.type === "video-codec-proof-request",+ ),+ ).toEqual([]);+ expect(harness.committed).toEqual(["h264"]);+ expect(harness.releases).toEqual(["1234"]);++ vi.advanceTimersByTime(10_000);+ expect(harness.pauses).toEqual([]);+ });++ it("removes an invalid SFU anchor from proof without starting rollback", async () => {+ const replacement = deferred<CodecRouteSnapshot | null>();+ const direct = peerTarget();+ const harness = createHarness(+ [direct, sfuTarget("publication_generation_old_12345678")],+ {+ beginSfuReplacement: () => replacement.promise,+ parkSfuReplacement: () => true,+ beginSfuProof: () => true,+ },+ );++ start(harness.coordinator);+ const retainedDirect = { ...direct, routeRevision: 8 };+ const pendingAnchor = sfuTarget(+ "publication_generation_h264_12345678",+ "sfu_connection_h264_12345678",+ 8,+ false,+ );+ const freshSnapshot = {+ revision: 8,+ targets: [retainedDirect, pendingAnchor],+ };+ harness.setSnapshot(freshSnapshot);+ replacement.resolve(freshSnapshot);+ await flushPromises();+ prepared(harness.coordinator);+ sfuPrepared(+ harness.coordinator,+ "publication_generation_h264_12345678",+ );+ expect(resume(harness.coordinator)).toBe("started-proof");+ expect(+ harness.sent.filter(+ ({ message }) => message.type === "video-codec-proof-request",+ ),+ ).toEqual([]);++ harness.setSnapshot({+ revision: 9,+ targets: [{ ...retainedDirect, routeRevision: 9 }],+ });+ harness.coordinator.participantChanged("1234");+ expect(harness.routeWaitCalls).toEqual([+ { roomId: "1234", viewerPeerIds: ["viewer_sfu_12345678"] },+ ]);+ expect(harness.abortedSfuReplacements).toEqual([+ { roomId: "1234", generation: 1 },+ ]);+ expect(+ harness.sent.filter(+ ({ message }) => message.type === "video-codec-proof-request",+ ),+ ).toEqual([+ expect.objectContaining({+ sessionId: "viewer_session_12345678",+ message: expect.objectContaining({+ generation: 1,+ routeRevision: 9,+ binding: {+ kind: "peer",+ connectionId: "connection_12345678",+ },+ }),+ }),+ ]);++ proof(harness.coordinator, "h264", { routeRevision: 9 });+ expect(harness.committed).toEqual(["h264"]);+ expect(harness.pauses).toEqual([]);+ expect(harness.sfuReplacementCalls).toHaveLength(1);+ expect(+ harness.sent.some(+ ({ message }) =>+ message.type === "video-codec-result" &&+ (message.status === "rollback-prepared" ||+ message.status === "failed"),+ ),+ ).toBe(false);+ });++ it("routes non-ready targets outside the pending SFU subtree to wait immediately", async () => {+ const replacement = deferred<CodecRouteSnapshot | null>();+ const retainedAnchorChild = peerTarget(+ "viewer_anchor_child_12345678",+ "viewer_session_anchor_child_12345678",+ "viewer_session_sfu_anchor_12345678",+ "connection_anchor_child_12345678",+ );+ const retainedAnchorGrandchild = peerTarget(+ "viewer_anchor_grandchild_12345678",+ "viewer_session_anchor_grandchild_12345678",+ "viewer_session_anchor_child_12345678",+ "connection_anchor_grandchild_12345678",+ );+ const unreachableOtherRootChild = {+ ...peerTarget(+ "viewer_other_child_12345678",+ "viewer_session_other_child_12345678",+ "viewer_session_sfu_other_12345678",+ "connection_other_child_12345678",+ ),+ proofReady: false,+ };+ const harness = createHarness(+ [+ sfuTarget(+ "publication_generation_old_12345678",+ "sfu_connection_anchor_old_12345678",+ 7,+ true,+ "viewer_sfu_anchor_12345678",+ "viewer_session_sfu_anchor_12345678",+ ),+ sfuTarget(+ "publication_generation_old_12345678",+ "sfu_connection_other_old_12345678",+ 7,+ true,+ "viewer_sfu_other_12345678",+ "viewer_session_sfu_other_12345678",+ ),+ retainedAnchorChild,+ retainedAnchorGrandchild,+ { ...unreachableOtherRootChild, proofReady: true },+ ],+ {+ beginSfuReplacement: () => replacement.promise,+ parkSfuReplacement: () => true,+ beginSfuProof: () => true,+ },+ );++ start(harness.coordinator);+ const freshAnchor = sfuTarget(+ "publication_generation_h264_12345678",+ "sfu_connection_anchor_h264_12345678",+ 8,+ false,+ "viewer_sfu_anchor_12345678",+ "viewer_session_sfu_anchor_12345678",+ );+ const preparedSnapshot = {+ revision: 8,+ targets: [+ freshAnchor,+ { ...retainedAnchorChild, routeRevision: 8, proofReady: false },+ {+ ...retainedAnchorGrandchild,+ routeRevision: 8,+ proofReady: false,+ },+ { ...unreachableOtherRootChild, routeRevision: 8 },+ ],+ };+ harness.setSnapshot(preparedSnapshot);+ replacement.resolve(preparedSnapshot);+ await flushPromises();+ for (const target of preparedSnapshot.targets) {+ if (target.preparationBinding.kind !== "peer") continue;+ harness.coordinator.prepared("1234", target.preparationOwnerSessionId, {+ type: "video-codec-prepared",+ shareGeneration: "share_generation_12345678",+ generation: 1,+ binding: target.preparationBinding,+ accepted: true,+ });+ }+ sfuPrepared(+ harness.coordinator,+ "publication_generation_h264_12345678",+ );+ expect(resume(harness.coordinator)).toBe("started-proof");+ expect(harness.routeWaitCalls).toEqual([+ {+ roomId: "1234",+ viewerPeerIds: ["viewer_other_child_12345678"],+ },+ ]);+ expect(+ harness.sent.filter(+ ({ message }) => message.type === "video-codec-proof-request",+ ),+ ).toEqual([]);++ harness.setSnapshot({+ revision: 9,+ targets: [+ { ...freshAnchor, routeRevision: 9, proofReady: true },+ { ...retainedAnchorChild, routeRevision: 9, proofReady: true },+ {+ ...retainedAnchorGrandchild,+ routeRevision: 9,+ proofReady: true,+ },+ { ...unreachableOtherRootChild, routeRevision: 9 },+ ],+ });+ harness.coordinator.participantChanged("1234");++ expect(harness.routeWaitCalls).toEqual([+ {+ roomId: "1234",+ viewerPeerIds: ["viewer_other_child_12345678"],+ },+ ]);+ expect(+ harness.sent+ .filter(({ message }) => message.type === "video-codec-proof-request")+ .map(({ sessionId }) => sessionId),+ ).toEqual([+ "viewer_session_sfu_anchor_12345678",+ "viewer_session_anchor_child_12345678",+ "viewer_session_anchor_grandchild_12345678",+ ]);+ expect(harness.pauses).toEqual([]);+ });++ it("rolls back an actual-codec mismatch and waits for another user resume", () => {+ const harness = createHarness();+ start(harness.coordinator);+ prepared(harness.coordinator);+ resume(harness.coordinator);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-proof-request",+ generation: 1,+ expectedCodec: "h264",+ });++ proof(harness.coordinator, "vp8");+ expect(harness.pauses).toEqual([1]);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-prepare",+ generation: 2,+ videoCodec: "vp8",+ });+ expect(harness.resumes).toHaveLength(1);++ prepared(harness.coordinator, true, 2);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-result",+ status: "rollback-prepared",+ failure: "proof-failed",+ });+ vi.advanceTimersByTime(10_000);+ expect(harness.resumes).toHaveLength(1);+ expect(harness.committed).toEqual([]);++ resume(harness.coordinator);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-proof-request",+ generation: 2,+ expectedCodec: null,+ });+ proof(harness.coordinator, "vp8", { generation: 2 });+ expect(harness.committed).toEqual(["vp8"]);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-result",+ status: "committed",+ videoCodec: "vp8",+ failure: "proof-failed",+ });+ });++ it("accepts a different actual codec after exact rollback preparation", () => {+ const harness = createHarness();+ expect(+ harness.coordinator.start({+ roomId: "1234",+ hostSessionId: "host_session_12345678",+ shareGeneration: "share_generation_12345678",+ requested: "vp8",+ previous: "h264",+ }),+ ).toBe("started");+ prepared(harness.coordinator);+ resume(harness.coordinator);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-proof-request",+ generation: 1,+ expectedCodec: "vp8",+ });++ proof(harness.coordinator, "h264");+ expect(harness.pauses).toEqual([1]);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-prepare",+ generation: 2,+ videoCodec: "h264",+ });+ prepared(harness.coordinator, true, 2);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-result",+ status: "rollback-prepared",+ failure: "proof-failed",+ });++ resume(harness.coordinator);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-proof-request",+ generation: 2,+ expectedCodec: null,+ });+ proof(harness.coordinator, "vp8", { generation: 2 });++ expect(harness.committed).toEqual(["h264"]);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-result",+ generation: 2,+ status: "committed",+ videoCodec: "h264",+ failure: "proof-failed",+ });+ });++ it("returns a user-paused proof to the prepared state", () => {+ const harness = createHarness();+ start(harness.coordinator);+ prepared(harness.coordinator);+ resume(harness.coordinator);++ harness.coordinator.pause({+ roomId: "1234",+ hostSessionId: "host_session_12345678",+ shareGeneration: "share_generation_12345678",+ });+ vi.advanceTimersByTime(10_000);+ expect(harness.pauses).toEqual([]);+ expect(harness.committed).toEqual([]);++ expect(resume(harness.coordinator)).toBe("started-proof");+ proof(harness.coordinator, "h264");+ expect(harness.committed).toEqual(["h264"]);+ });++ it("removes invalidated bindings and leaves routing to rebuild after commit", () => {+ const harness = createHarness();+ start(harness.coordinator);+ harness.setSnapshot({ revision: 8, targets: [] });+ harness.coordinator.participantChanged("1234");++ expect(harness.routeWaitCalls).toEqual([+ { roomId: "1234", viewerPeerIds: ["viewer_12345678"] },+ ]);+ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-result",+ status: "committed",+ });+ expect(harness.committed).toEqual(["h264"]);+ expect(resume(harness.coordinator)).toBe("normal");+ expect(harness.resumes).toEqual([+ { codecGeneration: null, resumeAttempt: 1 },+ ]);+ expect(harness.releases).toEqual(["1234"]);+ });++ it("batch-retires invalid bindings, rebases proof, and defers synchronous reentry", () => {+ const retained = peerTarget();+ const removedA = peerTarget(+ "viewer_removed_a_12345678",+ "viewer_session_removed_a_12345678",+ "host_session_12345678",+ "connection_removed_a_12345678",+ );+ const removedB = peerTarget(+ "viewer_removed_b_12345678",+ "viewer_session_removed_b_12345678",+ "host_session_12345678",+ "connection_removed_b_12345678",+ );+ const harness = createHarness([retained, removedA, removedB]);+ start(harness.coordinator);+ harness.setSnapshot({+ revision: 8,+ targets: [{ ...retained, routeRevision: 8 }],+ });+ harness.setRouteWaitHandler(() => {+ harness.setSnapshot({+ revision: 9,+ targets: [{ ...retained, routeRevision: 9 }],+ });+ harness.coordinator.participantChanged("1234");+ });++ harness.coordinator.participantChanged("1234");++ expect(harness.routeWaitCalls).toEqual([+ {+ roomId: "1234",+ viewerPeerIds: [+ "viewer_removed_a_12345678",+ "viewer_removed_b_12345678",+ ],+ },+ ]);+ prepared(harness.coordinator);+ expect(resume(harness.coordinator)).toBe("started-proof");+ expect(+ harness.sent.filter(+ ({ message }) => message.type === "video-codec-proof-request",+ ),+ ).toEqual([+ expect.objectContaining({+ sessionId: "viewer_session_12345678",+ message: expect.objectContaining({+ routeRevision: 9,+ generation: 1,+ }),+ }),+ ]);++ proof(harness.coordinator, "h264", { routeRevision: 9 });+ expect(harness.committed).toEqual(["h264"]);+ });++ it("allocates increasing generations and rejects a duplicate allocator value", () => {+ const harness = createHarness([]);++ expect(start(harness.coordinator)).toBe("committed");+ expect(+ harness.coordinator.start({+ roomId: "5678",+ hostSessionId: "host_session_12345678",+ shareGeneration: "share_generation_12345678",+ requested: "h264",+ previous: "vp8",+ }),+ ).toBe("committed");+ expect(+ harness.sent+ .map(({ message }) => message)+ .filter((message) => message.type === "video-codec-result")+ .map((message) => message.generation),+ ).toEqual([1, 2]);++ const duplicate = createHarness([], { createGeneration: () => 1 });+ expect(start(duplicate.coordinator)).toBe("committed");+ expect(() =>+ duplicate.coordinator.start({+ roomId: "5678",+ hostSessionId: "host_session_12345678",+ shareGeneration: "share_generation_12345678",+ requested: "h264",+ previous: "vp8",+ }),+ ).toThrow("Codec transition generation must increase monotonically");+ });++ it("rejects a non-increasing Resume attempt across rooms", () => {+ const harness = createHarness([], { createResumeAttempt: () => 1 });+ expect(requestResume(harness.coordinator)).toBe("normal");++ expect(() =>+ harness.coordinator.requestResume({+ roomId: "5678",+ hostSessionId: "host_session_other_12345678",+ shareGeneration: "share_generation_other_12345678",+ }),+ ).toThrow("Resume attempt must increase monotonically");+ });++ it("accepts only proof evidence sampled after a positive decoded-frame delta", () => {+ const message = {+ type: "video-codec-proof" as const,+ shareGeneration: "share_generation_12345678",+ generation: 1,+ resumeAttempt: 1,+ routeRevision: 7,+ binding: { kind: "peer" as const, connectionId: "connection_12345678" },+ evidence: proofEvidence("h264"),+ };++ expect(clientMessageSchema.safeParse(message).success).toBe(true);+ expect(+ clientMessageSchema.safeParse({+ ...message,+ evidence: proofEvidence("h264", {+ baselineSampleTimestampMs: 200,+ sampleTimestampMs: 200,+ }),+ }).success,+ ).toBe(false);+ expect(+ clientMessageSchema.safeParse({+ ...message,+ evidence: proofEvidence("h264", { framesDecodedDelta: 0 }),+ }).success,+ ).toBe(false);+ });++ it("updates only the future preference when no route target exists", () => {+ const harness = createHarness([]);++ expect(start(harness.coordinator)).toBe("committed");+ expect(harness.committed).toEqual(["h264"]);+ expect(harness.resumes).toEqual([]);+ expect(harness.releases).toEqual([]);+ });++ it("keeps a failed rollback as a timerless resume blocker", () => {+ const harness = createHarness();+ start(harness.coordinator);+ prepared(harness.coordinator);+ resume(harness.coordinator);+ proof(harness.coordinator, "vp8");+ prepared(harness.coordinator, false, 2);++ expect(harness.sent.at(-1)?.message).toMatchObject({+ type: "video-codec-result",+ status: "failed",+ failure: "rollback-failed",+ });+ vi.advanceTimersByTime(10_000);+ expect(resume(harness.coordinator)).toBe("busy");+ expect(harness.releases).toEqual([]);+ expect(harness.coordinator.blocksResume("1234")).toBe(true);+ });++ it("invalidates a transaction across a host session boundary", () => {+ const harness = createHarness();+ start(harness.coordinator);++ harness.coordinator.invalidateHostSession(+ "1234",+ "host_session_reconnected_12345678",+ );++ expect(harness.pauses).toEqual([1]);+ expect(harness.sent.at(-1)).toMatchObject({+ sessionId: "host_session_reconnected_12345678",+ message: {+ type: "video-codec-result",+ status: "failed",+ failure: "stale-binding",+ },+ });+ expect(+ harness.coordinator.requestResume({+ roomId: "1234",+ hostSessionId: "host_session_reconnected_12345678",+ shareGeneration: "share_generation_12345678",+ }),+ ).toBe("busy");+ expect(harness.releases).toEqual([]);+ });++ it("repauses a proving transaction on reconnect and ignores its delayed proof", () => {+ const harness = createHarness();+ start(harness.coordinator);+ prepared(harness.coordinator);+ expect(requestResume(harness.coordinator)).toBe("started-proof");+ expect(acknowledgeLatestResume(harness.coordinator)).toBe(true);+ const staleResumeAttempt = latestResumeAttempt(harness.coordinator);++ harness.coordinator.invalidateHostSession(+ "1234",+ "host_session_reconnected_12345678",+ );++ expect(harness.pauses).toEqual([1]);+ expect(harness.pauseAttempts).toEqual([null]);+ proof(harness.coordinator, "h264", {+ resumeAttempt: staleResumeAttempt,+ });+ expect(harness.committed).toEqual([]);+ expect(harness.releases).toEqual([]);+ expect(harness.coordinator.blocksResume("1234")).toBe(true);+ });+});diff --git a/tests/decoded-frame-proof.test.ts b/tests/decoded-frame-proof.test.tsnew file mode 100644index 00000000..dc947291--- /dev/null+++ b/tests/decoded-frame-proof.test.ts@@ -0,0 +1,89 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { observeDecodedFrameProof } from "../src/client/media/decoded-frame-proof";++interface Deferred<T> {+ promise: Promise<T>;+ resolve: (value: T) => void;+}++function deferred<T>(): Deferred<T> {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((next) => {+ resolve = next;+ });+ return { promise, resolve };+}++beforeEach(() => {+ vi.useFakeTimers();+ vi.stubGlobal("window", {+ setTimeout,+ clearTimeout,+ });+});++afterEach(() => {+ vi.clearAllTimers();+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe("decoded frame proof observer", () => {+ it("accepts the first cumulative frame on a fresh exact transport", async () => {+ const readFramesDecoded = vi+ .fn<() => Promise<number | null>>()+ .mockResolvedValueOnce(0)+ .mockResolvedValueOnce(1);+ const onProof = vi.fn(() => true);++ observeDecodedFrameProof({+ readFramesDecoded,+ owns: () => true,+ onProof,+ });+ await vi.advanceTimersByTimeAsync(100);++ expect(readFramesDecoded).toHaveBeenCalledTimes(2);+ expect(onProof).toHaveBeenCalledOnce();+ });++ it("requires growth beyond a post-resume baseline", async () => {+ const values = [7, 7, 8];+ const onProof = vi.fn(() => true);++ observeDecodedFrameProof({+ readFramesDecoded: async () => values.shift() ?? 8,+ owns: () => true,+ requireProgress: true,+ onProof,+ });+ await vi.advanceTimersByTimeAsync(100);+ expect(onProof).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(100);+ expect(onProof).toHaveBeenCalledOnce();+ });++ it("serializes reads and ignores an in-flight result after ownership ends", async () => {+ const first = deferred<number | null>();+ let owned = true;+ const readFramesDecoded = vi.fn(() => first.promise);+ const onProof = vi.fn(() => true);+ const stop = observeDecodedFrameProof({+ readFramesDecoded,+ owns: () => owned,+ onProof,+ });++ await vi.advanceTimersByTimeAsync(1_000);+ expect(readFramesDecoded).toHaveBeenCalledOnce();+ owned = false;+ stop();+ first.resolve(3);+ await Promise.resolve();+ await vi.runAllTimersAsync();++ expect(onProof).not.toHaveBeenCalled();+ expect(readFramesDecoded).toHaveBeenCalledOnce();+ });+});diff --git a/tests/host-page-notice.test.ts b/tests/host-page-notice.test.tsindex fbaa9477..a3514a85 100644--- a/tests/host-page-notice.test.ts+++ b/tests/host-page-notice.test.ts@@ -1,11 +1,61 @@import { describe, expect, it } from "vitest";import {+ hostActionErrorNotice,+ hostServerErrorNotice,shouldPauseLocalPreview,sourceSwitchNotice,+ VIDEO_CODEC_TRANSITION_FAILED_NOTICE,videoCodecLockNotice,} from "../src/client/pages/host-page-notices.ts";+describe("host error notices", () => {+ it("maps every server error code without exposing server text", () => {+ const notices = {+ AUTH_REQUIRED: "站点访问已失效,请重新验证",+ INVALID_MESSAGE: "页面版本已更新,请刷新后重试",+ INVALID_TOKEN: "分享凭证已失效,请重新创建房间",+ ROOM_ACCESS_DENIED: "当前操作没有权限",+ ROOM_EXPIRED: "房间已过期,请重新创建",+ ROOM_FULL: "房间已满",+ HOST_ALREADY_CONNECTED: "此房间已在另一个页面中分享",+ PEER_NOT_FOUND: "对应的观看连接已经离开",+ FORBIDDEN: "当前操作不可用",+ SERVER_ERROR: "服务暂时不可用,请稍后重试",+ } as const;++ for (const [code, notice] of Object.entries(notices)) {+ expect(+ hostServerErrorNotice(code as keyof typeof notices),+ ).toBe(notice);+ expect(notice).not.toContain("server-internal-sentinel");+ }+ });++ it("uses stable action messages instead of arbitrary exception text", () => {+ const sentinel = new Error("browser-internal-sentinel");+ expect(hostActionErrorNotice(sentinel, "quality")).toBe(+ "应用画质设置失败",+ );+ expect(hostActionErrorNotice(sentinel, "connection")).toBe(+ "观看连接处理失败",+ );+ expect(hostActionErrorNotice(sentinel, "room")).toBe("房间操作失败");+ expect(hostActionErrorNotice(sentinel, "source")).toBe("切换分享来源失败");+ });++ it.each([+ ["NotAllowedError", "屏幕选择已取消或没有共享权限"],+ ["NotFoundError", "没有可用的屏幕分享来源"],+ ["NotReadableError", "浏览器暂时无法读取所选分享来源"],+ ["SecurityError", "当前页面无法启动屏幕分享"],+ ])("maps capture DOMException %s", (name, notice) => {+ expect(+ hostActionErrorNotice(new DOMException("raw-browser-text", name), "capture"),+ ).toBe(notice);+ });+});+describe("shouldPauseLocalPreview", () => {it("distinguishes local preview suspension from active focus", () => {expect(shouldPauseLocalPreview("hidden", true)).toBe(true);@@ -47,15 +97,22 @@ describe("sourceSwitchNotice", () => {});describe("videoCodecLockNotice", () => {- it("explains why codec controls are locked during a share", () => {- expect(videoCodecLockNotice("starting")).toBe(- "本次分享的编码已锁定,停止分享后可修改",+ it("exposes codec switching only after the active share is paused", () => {+ expect(videoCodecLockNotice("starting", false)).toBe(+ "分享开始后,暂停分享即可切换视频编码",);- expect(videoCodecLockNotice("live")).toBe(- "本次分享的编码已锁定,停止分享后可修改",+ expect(videoCodecLockNotice("live", false)).toBe(+ "暂停分享后可切换视频编码",);+ expect(videoCodecLockNotice("live", true)).toBeNull();for (const phase of ["idle", "ended", "error"]) {- expect(videoCodecLockNotice(phase)).toBeNull();+ expect(videoCodecLockNotice(phase, false)).toBeNull();}});++ it("keeps a failed codec transaction visible until sharing stops", () => {+ expect(videoCodecLockNotice("live", true, "failed")).toBe(+ VIDEO_CODEC_TRANSITION_FAILED_NOTICE,+ );+ });});diff --git a/tests/host-peer-tracks.test.ts b/tests/host-peer-tracks.test.tsindex 6a41642f..8b19f3d5 100644--- a/tests/host-peer-tracks.test.ts+++ b/tests/host-peer-tracks.test.ts@@ -11,6 +11,7 @@ import { ViewerRelay } from "../src/client/webrtc/viewer-relay.ts";import type {IceConfig,ParticipantRouteAssignment,+ SignalPayload,} from "../src/shared/protocol.ts";const statsCallbacks: Array<() => void> = [];@@ -87,6 +88,9 @@ class FakePeerConnection {init?: RTCRtpTransceiverInit;}> = [];readonly codecPreferenceCalls: RTCRtpCodec[][] = [];+ remoteDescriptionCallCount = 0;+ deferRemoteDescriptionCall: number | null = null;+ private releaseRemoteDescription: (() => void) | null = null;connectionState: RTCPeerConnectionState = "new";iceConnectionState: RTCIceConnectionState = "new";signalingState: RTCSignalingState = "stable";@@ -144,15 +148,32 @@ class FakePeerConnection {async setLocalDescription(description: RTCSessionDescriptionInit,): Promise<void> {+ if (description.type === "rollback") {+ this.localDescription = null;+ this.signalingState = "stable";+ return;+ }this.localDescription = description as RTCSessionDescription;}async setRemoteDescription(description: RTCSessionDescriptionInit,): Promise<void> {+ this.remoteDescriptionCallCount += 1;+ if (this.deferRemoteDescriptionCall === this.remoteDescriptionCallCount) {+ this.deferRemoteDescriptionCall = null;+ await new Promise<void>((resolve) => {+ this.releaseRemoteDescription = resolve;+ });+ }this.remoteDescription = description as RTCSessionDescription;}+ releaseDeferredRemoteDescription(): void {+ this.releaseRemoteDescription?.();+ this.releaseRemoteDescription = null;+ }+async addIceCandidate(candidate: RTCIceCandidateInit | null): Promise<void> {this.addedIceCandidates.push(candidate);}@@ -358,6 +379,20 @@ afterEach(() => {});describe("HostPeer source replacement", () => {+ it("does not expose WebRTC exception text in connection errors", async () => {+ const updates: PeerSnapshot[] = [];+ FakePeerConnection.offersFailing = 1;+ const peer = createPeer(+ createStream(createTrack("video", "video"), null),+ (snapshot) => updates.push(snapshot),+ );++ await expect(peer.start()).resolves.toBe(false);++ expect(updates.at(-1)?.error).toBe("创建连接失败");+ expect(updates.at(-1)?.error).not.toContain("createOffer failed");+ });+it("leaves browser codec ordering unchanged", async () => {const peer = createPeer(createStream(createTrack("video", "video"), null));@@ -401,6 +436,309 @@ describe("HostPeer source replacement", () => {},);+ it("supersedes an unanswered codec offer with the next exact generation", async () => {+ const signals: SignalPayload[] = [];+ const peer = new HostPeer(+ "viewer-peer",+ { iceServers: [] },+ createStream(createTrack("video", "video"), null),+ QUALITY_PROFILES["720p30"],+ {+ sendSignal: (_peerId, payload) => {+ signals.push(payload);+ return true;+ },+ onUpdate: () => undefined,+ },+ );+ await expect(peer.start()).resolves.toBe(true);+ await peer.acceptSignal({+ kind: "description",+ connectionId: peer.connectionId,+ negotiationGeneration: null,+ description: { type: "answer", sdp: "initial-answer" },+ });++ const first = peer.prepareVideoCodec(1, "h264");+ await vi.waitFor(() =>+ expect(+ signals.filter(+ (signal) =>+ signal.kind === "description" &&+ signal.negotiationGeneration === 1,+ ),+ ).toHaveLength(1),+ );+ const connection = FakePeerConnection.latest!;+ connection.signalingState = "have-local-offer";++ const rollback = peer.prepareVideoCodec(2, "vp8");+ await expect(first).resolves.toBe(false);+ await vi.waitFor(() =>+ expect(+ signals.filter(+ (signal) =>+ signal.kind === "description" &&+ signal.negotiationGeneration === 2,+ ),+ ).toHaveLength(1),+ );+ expect(connection.localDescription?.type).toBe("offer");++ await peer.acceptSignal({+ kind: "description",+ connectionId: peer.connectionId,+ negotiationGeneration: 1,+ description: { type: "answer", sdp: "stale-answer" },+ });+ let rollbackSettled = false;+ void rollback.then(() => {+ rollbackSettled = true;+ });+ await Promise.resolve();+ expect(rollbackSettled).toBe(false);++ connection.signalingState = "stable";+ await peer.acceptSignal({+ kind: "description",+ connectionId: peer.connectionId,+ negotiationGeneration: 2,+ description: { type: "answer", sdp: "rollback-answer" },+ });+ await expect(rollback).resolves.toBe(true);+ expect(connection.remoteDescription?.sdp).toBe("rollback-answer");+ expect(connection.codecPreferenceCalls).toHaveLength(2);+ });++ it("serializes an in-flight codec answer before offering a newer generation", async () => {+ const signals: SignalPayload[] = [];+ const peer = new HostPeer(+ "viewer-peer",+ { iceServers: [] },+ createStream(createTrack("video", "video"), null),+ QUALITY_PROFILES["720p30"],+ {+ sendSignal: (_peerId, payload) => {+ signals.push(payload);+ return true;+ },+ onUpdate: () => undefined,+ },+ );+ await expect(peer.start()).resolves.toBe(true);+ await peer.acceptSignal({+ kind: "description",+ connectionId: peer.connectionId,+ negotiationGeneration: null,+ description: { type: "answer", sdp: "initial-answer" },+ });+ signals.length = 0;++ const first = peer.prepareVideoCodec(21, "h264");+ await vi.waitFor(() =>+ expect(+ signals.filter(+ (signal) =>+ signal.kind === "description" &&+ signal.negotiationGeneration === 21,+ ),+ ).toHaveLength(1),+ );+ const connection = FakePeerConnection.latest!;+ connection.deferRemoteDescriptionCall = 2;+ const staleAnswer = peer.acceptSignal({+ kind: "description",+ connectionId: peer.connectionId,+ negotiationGeneration: 21,+ description: { type: "answer", sdp: "generation-21-answer" },+ });+ await vi.waitFor(() =>+ expect(connection.remoteDescriptionCallCount).toBe(2),+ );++ const second = peer.prepareVideoCodec(22, "vp8");+ await expect(first).resolves.toBe(false);+ await Promise.resolve();+ expect(+ signals.filter(+ (signal) =>+ signal.kind === "description" &&+ signal.negotiationGeneration === 22,+ ),+ ).toEqual([]);++ connection.releaseDeferredRemoteDescription();+ await staleAnswer;+ await vi.waitFor(() =>+ expect(+ signals.filter(+ (signal) =>+ signal.kind === "description" &&+ signal.negotiationGeneration === 22,+ ),+ ).toHaveLength(1),+ );+ await peer.acceptSignal({+ kind: "description",+ connectionId: peer.connectionId,+ negotiationGeneration: 22,+ description: { type: "answer", sdp: "generation-22-answer" },+ });+ await expect(second).resolves.toBe(true);+ expect(connection.remoteDescription?.sdp).toBe("generation-22-answer");+ });++ it("waits for the codec negotiation owner before sending an ICE restart offer", async () => {+ const signals: SignalPayload[] = [];+ const peer = new HostPeer(+ "viewer-peer",+ { iceServers: [] },+ createStream(createTrack("video", "video"), null),+ QUALITY_PROFILES["720p30"],+ {+ sendSignal: (_peerId, payload) => {+ signals.push(payload);+ return true;+ },+ onUpdate: () => undefined,+ },+ );+ await expect(peer.start()).resolves.toBe(true);+ await peer.acceptSignal({+ kind: "description",+ connectionId: peer.connectionId,+ negotiationGeneration: null,+ description: { type: "answer", sdp: "initial-answer" },+ });+ signals.length = 0;++ const codec = peer.prepareVideoCodec(31, "h264");+ await vi.waitFor(() =>+ expect(+ signals.filter(+ (signal) =>+ signal.kind === "description" &&+ signal.negotiationGeneration === 31,+ ),+ ).toHaveLength(1),+ );+ const connection = FakePeerConnection.latest!;+ const restart = peer.restartIce();+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(connection.restartIce).not.toHaveBeenCalled();+ expect(+ signals.filter(+ (signal) =>+ signal.kind === "description" &&+ signal.negotiationGeneration === null,+ ),+ ).toEqual([]);++ await peer.acceptSignal({+ kind: "description",+ connectionId: peer.connectionId,+ negotiationGeneration: 31,+ description: { type: "answer", sdp: "codec-answer" },+ });+ await expect(codec).resolves.toBe(true);+ await expect(restart).resolves.toBe(true);+ expect(connection.restartIce).toHaveBeenCalledOnce();+ expect(+ signals+ .filter((signal) => signal.kind === "description")+ .map((signal) => signal.negotiationGeneration),+ ).toEqual([31, null]);+ });++ it("rolls back a cancelled codec offer before an ordinary ICE restart", async () => {+ const signals: SignalPayload[] = [];+ const peer = new HostPeer(+ "viewer-peer",+ { iceServers: [] },+ createStream(createTrack("video", "video"), null),+ QUALITY_PROFILES["720p30"],+ {+ sendSignal: (_peerId, payload) => {+ signals.push(payload);+ return true;+ },+ onUpdate: () => undefined,+ },+ );+ await expect(peer.start()).resolves.toBe(true);+ await peer.acceptSignal({+ kind: "description",+ connectionId: peer.connectionId,+ negotiationGeneration: null,+ description: { type: "answer", sdp: "initial-answer" },+ });+ signals.length = 0;++ const codec = peer.prepareVideoCodec(41, "h264");+ await vi.waitFor(() =>+ expect(+ signals.filter(+ (signal) =>+ signal.kind === "description" &&+ signal.negotiationGeneration === 41,+ ),+ ).toHaveLength(1),+ );+ const connection = FakePeerConnection.latest!;+ connection.signalingState = "have-local-offer";+ peer.cancelVideoCodecPreparation();+ const restart = peer.restartIce();++ await expect(codec).resolves.toBe(false);+ await expect(restart).resolves.toBe(true);+ expect(connection.signalingState).toBe("stable");+ expect(connection.restartIce).toHaveBeenCalledOnce();+ expect(+ signals+ .filter((signal) => signal.kind === "description")+ .map((signal) => signal.negotiationGeneration),+ ).toEqual([41, null]);+ });++ it("coalesces an exact duplicate codec preparation", async () => {+ const signals: SignalPayload[] = [];+ const peer = new HostPeer(+ "viewer-peer",+ { iceServers: [] },+ createStream(createTrack("video", "video"), null),+ QUALITY_PROFILES["720p30"],+ {+ sendSignal: (_peerId, payload) => {+ signals.push(payload);+ return true;+ },+ onUpdate: () => undefined,+ },+ );+ await expect(peer.start()).resolves.toBe(true);+ const first = peer.prepareVideoCodec(4, "h264");+ const duplicate = peer.prepareVideoCodec(4, "h264");++ expect(duplicate).toBe(first);+ await vi.waitFor(() =>+ expect(+ signals.filter(+ (signal) =>+ signal.kind === "description" &&+ signal.negotiationGeneration === 4,+ ),+ ).toHaveLength(1),+ );+ await peer.acceptSignal({+ kind: "description",+ connectionId: peer.connectionId,+ negotiationGeneration: 4,+ description: { type: "answer", sdp: "codec-answer" },+ });+ await expect(first).resolves.toBe(true);+ await expect(duplicate).resolves.toBe(true);+ });+it("applies STUN-only ICE configuration at creation and update", () => {const peer = createPeer(createStream(createTrack("video", "video"), null),@@ -636,6 +974,7 @@ describe("HostPeer source replacement", () => {await peer.acceptSignal({kind: "description",connectionId: peer.connectionId,+ negotiationGeneration: null,description: { type: "answer", sdp: "test-answer" },});@@ -687,11 +1026,11 @@ describe("HostPeer source replacement", () => {const updating = peer.updateProfile(QUALITY_PROFILES["1080p60"]);await expect(starting).resolves.toBe(true);- expect(- updates.some((snapshot) =>- snapshot.qualityWarning?.startsWith("应用发送参数失败"),- ),- ).toBe(true);+ const failureWarning = updates.find((snapshot) =>+ snapshot.qualityWarning?.startsWith("应用发送参数失败"),+ )?.qualityWarning;+ expect(failureWarning).toBe("应用发送参数失败");+ expect(failureWarning).not.toContain("setParameters failed");await expect(updating).resolves.toBe(true);expect(videoSender.setParameters).toHaveBeenCalledTimes(2);expect(videoSender.appliedMaxBitrates).toEqual([8_000_000]);@@ -1016,6 +1355,36 @@ describe("HostPeer source replacement", () => {expect(sender.setParameters).toHaveBeenCalledOnce();});+ it("does not expose an unknown browser quality-limitation value", async () => {+ const updates: PeerSnapshot[] = [];+ const peer = createPeer(+ createStream(createTrack("video", "video"), null),+ (snapshot) => updates.push(snapshot),+ );+ await expect(peer.start()).resolves.toBe(true);+ const connection = FakePeerConnection.latest!;+ for (const timestamp of [1_000, 2_000, 3_000]) {+ connection.statsReports.push(+ sendStatsReport({+ bytesSent: timestamp * 1_000,+ framesEncoded: timestamp / 10,+ timestamp,+ qualityLimitationReason: "browser-internal-sentinel",+ }),+ );+ }++ for (let index = 0; index < 3; index += 1) {+ const updateCount = updates.length;+ statsCallbacks[0]!();+ await vi.waitFor(() => expect(updates.length).toBeGreaterThan(updateCount));+ }++ expect(updates.at(-1)?.qualityWarning).toBe(+ "浏览器持续报告未分类的画质限制",+ );+ });+it("rolls the first sender back when the second replacement fails", async () => {const oldVideo = createTrack("video", "old-video");const oldAudio = createTrack("audio", "old-audio");@@ -1067,6 +1436,7 @@ function hostProvisionalInput(childPeerId: childPeerIds.at(-1) ?? "candidate-child",connectionId: `candidate-connection-${revision}`,transport: "direct" as const,+ codecTransition: null,},assignment: hostAssignment(childPeerIds,@@ -1103,11 +1473,13 @@ describe("Host provisional child runtime ownership", () => {expect(owner.acceptSignal("wrong-child", {kind: "description",connectionId: preparedConnectionId,+ negotiationGeneration: null,description: { type: "answer", sdp: "wrong-peer" },})).toBe(false);expect(owner.acceptSignal("probe-child", {kind: "description",connectionId: "wrong-connection",+ negotiationGeneration: null,description: { type: "answer", sdp: "wrong-connection" },})).toBe(false);expect(owner.acceptSignal("probe-child", {@@ -1118,6 +1490,7 @@ describe("Host provisional child runtime ownership", () => {expect(owner.acceptSignal("probe-child", {kind: "description",connectionId: preparedConnectionId,+ negotiationGeneration: null,description: { type: "answer", sdp: "right-answer" },})).toBe(true);await vi.waitFor(() =>@@ -1207,6 +1580,7 @@ describe("ViewerRelay downstream ownership", () => {childPeerId,connectionId: `relay-candidate-${revision}`,transport: "direct" as const,+ codecTransition: null,});it("promotes the exact prepared child connection within the current Viewer cap", async () => {@@ -1233,6 +1607,7 @@ describe("ViewerRelay downstream ownership", () => {relay.acceptSignal("prepared-child", {kind: "description",connectionId: "wrong-connection",+ negotiationGeneration: null,description: { type: "answer", sdp: "wrong-answer" },}, 7),).resolves.toBe(false);@@ -1240,6 +1615,7 @@ describe("ViewerRelay downstream ownership", () => {relay.acceptSignal("prepared-child", {kind: "description",connectionId: preparedConnectionId,+ negotiationGeneration: null,description: { type: "answer", sdp: "right-answer" },}, 6),).resolves.toBe(false);@@ -1262,6 +1638,7 @@ describe("ViewerRelay downstream ownership", () => {relay.acceptSignal("prepared-child", {kind: "description",connectionId: preparedConnectionId,+ negotiationGeneration: null,description: { type: "answer", sdp: "right-answer" },}, preparedRevision),).resolves.toBe(true);diff --git a/tests/host-source-authority.test.ts b/tests/host-source-authority.test.tsnew file mode 100644index 00000000..6468f50a--- /dev/null+++ b/tests/host-source-authority.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it, vi } from "vitest";++import { applyAuthoritativeHostPause } from "../src/client/media/host-source-authority.ts";++function createStream() {+ const videoTrack = { enabled: true } as MediaStreamTrack;+ const audioTrack = { enabled: true } as MediaStreamTrack;+ const stream = {+ getTracks: () => [videoTrack, audioTrack],+ getVideoTracks: () => [videoTrack],+ } as unknown as MediaStream;+ return { stream, videoTrack, audioTrack };+}++describe("Host source authority", () => {+ it("repause disables the current share after reconnect cleared local codec state", () => {+ const { stream, videoTrack, audioTrack } = createStream();+ const pauseSfuRoute = vi.fn();+ let hostPaused = false;++ const result = applyAuthoritativeHostPause({+ message: {+ type: "pause-sharing-source",+ shareGeneration: "share_generation_12345678",+ codecGeneration: 7,+ resumeAttempt: null,+ },+ currentShareGeneration: "share_generation_12345678",+ activeResumeAttempt: null,+ activeCodecGeneration: null,+ stream,+ pauseSfuRoute,+ markHostPaused: () => {+ hostPaused = true;+ },+ });++ expect(result).toEqual({ localCodecContextMatches: false });+ expect(videoTrack.enabled).toBe(false);+ expect(audioTrack.enabled).toBe(false);+ expect(pauseSfuRoute).toHaveBeenCalledOnce();+ expect(hostPaused).toBe(true);+ });++ it("rejects a stale share before touching its source or route", () => {+ const { stream, videoTrack, audioTrack } = createStream();+ const pauseSfuRoute = vi.fn();+ const markHostPaused = vi.fn();++ const result = applyAuthoritativeHostPause({+ message: {+ type: "pause-sharing-source",+ shareGeneration: "stale_share_generation_12345678",+ codecGeneration: 7,+ resumeAttempt: 3,+ },+ currentShareGeneration: "current_share_generation_12345678",+ activeResumeAttempt: 3,+ activeCodecGeneration: 7,+ stream,+ pauseSfuRoute,+ markHostPaused,+ });++ expect(result).toBeNull();+ expect(videoTrack.enabled).toBe(true);+ expect(audioTrack.enabled).toBe(true);+ expect(pauseSfuRoute).not.toHaveBeenCalled();+ expect(markHostPaused).not.toHaveBeenCalled();+ });+});diff --git a/tests/hybrid-media-router.test.ts b/tests/hybrid-media-router.test.tsindex 8577c579..f2e92ecb 100644--- a/tests/hybrid-media-router.test.ts+++ b/tests/hybrid-media-router.test.ts@@ -65,6 +65,34 @@ function complete(return state;}+function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>((settle) => {+ resolve = settle;+ });+ return { promise, resolve };+}++function reconnectHost(+ store: RoomStore,+ room: CreatedRoom,+ sessionId: string,+): AuthenticatedRouteParticipant {+ const connected = store.connectParticipant({+ roomId: room.roomId,+ role: "host",+ token: room.hostToken,+ clientId: "host_client_12345678",+ sessionId,+ });+ return {+ roomId: room.roomId,+ role: "host",+ peerId: connected.peerId,+ sessionId,+ };+}+function preparedFor(sent: Map<string, ServerMessage[]>,sessionId: string,@@ -96,14 +124,19 @@ function harness(endpointMediaCopyCapacity: 1 | 2 | 3,withSfu = false,prepareTimeoutMs?: number,+ sfuIngressCapacity = 2,) {const store = createStore();const sent = new Map<string, ServerMessage[]>();const connections = new Map<string, string>();const admission = withSfu- ? new SfuResourceAdmission({ ingressCapacity: 2, egressCapacity: 20 })+ ? new SfuResourceAdmission({+ ingressCapacity: sfuIngressCapacity,+ egressCapacity: 20,+ }): undefined;const roomControl = withSfu ? new FakeSfuRoomControl() : undefined;+ const onActiveRouteChanged = vi.fn();const router = new HybridMediaRouter({roomStore: store,endpointMediaCopyCapacity,@@ -137,8 +170,56 @@ function harness(connections.delete(`${roomId}:${viewerPeerId}`);},getShareGeneration: () => SHARE_GENERATION,+ onActiveRouteChanged,});- return { store, sent, admission, router };+ return {+ store,+ sent,+ admission,+ roomControl,+ onActiveRouteChanged,+ router,+ };+}++async function establishSfuRoom(+ store: RoomStore,+ sent: Map<string, ServerMessage[]>,+ router: HybridMediaRouter,+ room: CreatedRoom,+) {+ const host = connectHost(store, room);+ complete(router, host);+ const first = connectViewer(store, room, `sfu-root-${room.roomId}`);+ complete(router, first);+ await vi.waitFor(() => expect(preparedFor(sent, first.sessionId)).toBeDefined());+ const firstDirect = preparedFor(sent, first.sessionId)!;+ router.handleRouteReady(first, {+ type: "route-ready",+ revision: firstDirect.revision,+ phase: "prepare",+ });+ const second = connectViewer(store, room, `sfu-leaf-${room.roomId}`);+ complete(router, second);+ await vi.waitFor(() =>+ expect(preparedFor(sent, first.sessionId)?.candidate.transport).toBe("sfu"),+ );+ const firstSfu = preparedFor(sent, first.sessionId)!;+ router.handleRouteReady(first, {+ type: "route-ready",+ revision: firstSfu.revision,+ phase: "prepare",+ });+ await vi.waitFor(() =>+ expect(preparedFor(sent, second.sessionId)?.candidate.transport).toBe("sfu"),+ );+ const secondSfu = preparedFor(sent, second.sessionId)!;+ router.handleRouteReady(second, {+ type: "route-ready",+ revision: secondSfu.revision,+ phase: "prepare",+ });+ return { host, first, second };}describe("HybridMediaRouter v9 runtime", () => {@@ -417,6 +498,75 @@ describe("HybridMediaRouter v9 runtime", () => {}});+ it("does not wake admission waiters when a subscription remains charged for drain", async () => {+ const { store, sent, admission, router } = harness(1, true, undefined, 2);+ try {+ const activeRoom = await store.createRoom();+ const active = await establishSfuRoom(+ store,+ sent,+ router,+ activeRoom,+ );+ await vi.waitFor(() =>+ expect(admission?.usage()).toEqual({ ingress: 1, egress: 2 }),+ );+ expect(+ admission?.reservePublication({+ roomId: "9001",+ shareGeneration: "waiter_share_12345678",+ publicationGeneration: "waiter_publication_12345678",+ }),+ ).toBe(true);+ const reservePublication = vi.spyOn(admission!, "reservePublication");++ const waitingRoom = await store.createRoom();+ const waitingHost = connectHost(store, waitingRoom);+ complete(router, waitingHost);+ const waitingViewer = connectViewer(store, waitingRoom, "waiter");+ complete(router, waitingViewer);+ await vi.waitFor(() =>+ expect(preparedFor(sent, waitingViewer.sessionId)).toBeDefined(),+ );+ const direct = preparedFor(sent, waitingViewer.sessionId)!;+ router.handleRouteFailed(waitingViewer, {+ type: "route-failed",+ revision: direct.revision,+ phase: "prepare",+ connectionId: direct.candidate.connectionId,+ });+ await vi.waitFor(() =>+ expect(+ sent+ .get(waitingViewer.sessionId)+ ?.findLast((message) => message.type === "route-status"),+ ).toMatchObject({ state: "waiting", reason: "sfu-admission" }),+ );+ const attemptsBeforeRelease = reservePublication.mock.calls.length;++ store.disconnectParticipant(+ activeRoom.roomId,+ active.first.peerId,+ active.first.sessionId,+ );+ router.disconnectParticipant(+ activeRoom.roomId,+ active.first.peerId,+ active.first.sessionId,+ );+ router.removeViewer(activeRoom.roomId, active.first.peerId);+ await vi.waitFor(() =>+ expect(router.routeDiagnosticSnapshot(activeRoom.roomId).children).toHaveLength(1),+ );+ await Promise.resolve();++ expect(admission?.usage()).toEqual({ ingress: 2, egress: 2 });+ expect(reservePublication).toHaveBeenCalledTimes(attemptsBeforeRelease);+ } finally {+ await router.close();+ }+ });+it("orders exact prepare, commits only child proof, and rolls back above P", async () => {const { store, sent, router } = harness(2);const room = await store.createRoom();@@ -529,6 +679,331 @@ describe("HybridMediaRouter v9 runtime", () => {await router.close();});+ it("replaces an SFU publication through the codec-owned paused operation", async () => {+ const { store, sent, admission, roomControl, router } = harness(+ 1,+ true,+ undefined,+ 1,+ );+ try {+ const room = await store.createRoom();+ const host = connectHost(store, room);+ complete(router, host);+ const first = connectViewer(store, room, "codec_sfu_first");+ complete(router, first);+ await vi.waitFor(() => expect(preparedFor(sent, first.sessionId)).toBeDefined());+ const firstDirect = preparedFor(sent, first.sessionId)!;+ expect(firstDirect.candidate.codecTransition).toBeNull();+ router.handleRouteReady(first, {+ type: "route-ready",+ revision: firstDirect.revision,+ phase: "prepare",+ });++ const second = connectViewer(store, room, "codec_sfu_second");+ complete(router, second);+ await vi.waitFor(() =>+ expect(preparedFor(sent, first.sessionId)?.candidate.transport).toBe("sfu"),+ );+ const firstSfu = preparedFor(sent, first.sessionId)!;+ router.handleRouteReady(first, {+ type: "route-ready",+ revision: firstSfu.revision,+ phase: "prepare",+ });+ await vi.waitFor(() =>+ expect(preparedFor(sent, second.sessionId)?.candidate.transport).toBe("sfu"),+ );+ const secondSfu = preparedFor(sent, second.sessionId)!;+ router.handleRouteReady(second, {+ type: "route-ready",+ revision: secondSfu.revision,+ phase: "prepare",+ });+ await vi.waitFor(() =>+ expect(admission?.usage()).toEqual({ ingress: 1, egress: 2 }),+ );++ const previous = router.codecRouteSnapshot(room.roomId)!;+ const previousPublication = (+ previous.targets[0]!.proofBinding as Extract<+ (typeof previous.targets)[number]["proofBinding"],+ { kind: "sfu" }+ >+ ).publicationGeneration;+ router.setPaused(room.roomId, true);+ const preparedSnapshot = await router.beginCodecSfuReplacement({+ roomId: room.roomId,+ hostSessionId: host.sessionId,+ generation: 1,+ videoCodec: "h264",+ timeoutMs: 1_000,+ });+ expect(preparedSnapshot).not.toBeNull();+ const freshTarget = preparedSnapshot!.targets.find(+ (target) => target.preparationBinding.kind === "sfu",+ )!;+ expect(freshTarget).toMatchObject({ proofReady: false });+ expect(freshTarget.preparationBinding).not.toMatchObject({+ publicationGeneration: previousPublication,+ });+ const codecPrepare = preparedFor(sent, freshTarget.viewerSessionId)!;+ expect(codecPrepare.candidate).toMatchObject({+ transport: "sfu",+ codecTransition: { generation: 1, videoCodec: "h264" },+ });+ expect(roomControl?.deleted).toContainEqual(+ expect.objectContaining({ publicationGeneration: previousPublication }),+ );+ expect(roomControl?.created).toHaveLength(2);++ expect(router.parkCodecSfuReplacement(room.roomId, 1)).toBe(true);+ const anchor =+ freshTarget.viewerPeerId === first.peerId ? first : second;+ router.handleRouteReady(anchor, {+ type: "route-ready",+ revision: codecPrepare.revision,+ phase: "prepare",+ });+ expect(+ router.codecRouteSnapshot(room.roomId)?.targets.find(+ (target) => target.viewerPeerId === anchor.peerId,+ )?.proofReady,+ ).toBe(false);++ expect(router.beginCodecSfuProof(room.roomId, 1, 1_000)).toBe(true);+ router.handleRouteReady(anchor, {+ type: "route-ready",+ revision: codecPrepare.revision,+ phase: "prepare",+ });+ await vi.waitFor(() =>+ expect(+ router.codecRouteSnapshot(room.roomId)?.targets.find(+ (target) => target.viewerPeerId === anchor.peerId,+ ),+ ).toMatchObject({ proofReady: true }),+ );+ expect(admission?.usage()).toEqual({ ingress: 1, egress: 1 });+ } finally {+ await router.close();+ }+ });++ it("waits for exact old-generation drain before codec creation even with spare ingress", async () => {+ const { store, sent, admission, roomControl, router } = harness(+ 1,+ true,+ undefined,+ 2,+ );+ const drain = deferred();+ try {+ const room = await store.createRoom();+ const { host } = await establishSfuRoom(store, sent, router, room);+ await vi.waitFor(() =>+ expect(admission?.usage()).toEqual({ ingress: 1, egress: 2 }),+ );+ roomControl!.deleteBarrier = drain.promise;+ router.setPaused(room.roomId, true);+ let settled = false;+ const preparation = router+ .beginCodecSfuReplacement({+ roomId: room.roomId,+ hostSessionId: host.sessionId,+ generation: 1,+ videoCodec: "h264",+ timeoutMs: 1_000,+ })+ .finally(() => {+ settled = true;+ });++ await vi.waitFor(() =>+ expect(+ (+ Reflect.get(router, "resourceWaiters") as Map<string, unknown>+ ).has(room.roomId),+ ).toBe(true),+ );+ expect(roomControl?.created).toHaveLength(1);+ expect(settled).toBe(false);++ drain.resolve();+ const snapshot = await preparation;+ expect(snapshot).not.toBeNull();+ expect(roomControl?.deleted).toHaveLength(1);+ expect(roomControl?.created).toHaveLength(2);+ } finally {+ drain.resolve();+ await router.close();+ }+ });++ it("waits for an aborted fresh codec generation to drain before rollback at ingress two", async () => {+ const { store, sent, admission, roomControl, router } = harness(+ 1,+ true,+ undefined,+ 2,+ );+ const forwardDrain = deferred();+ try {+ const room = await store.createRoom();+ const { host } = await establishSfuRoom(store, sent, router, room);+ router.setPaused(room.roomId, true);+ const forward = await router.beginCodecSfuReplacement({+ roomId: room.roomId,+ hostSessionId: host.sessionId,+ generation: 1,+ videoCodec: "h264",+ timeoutMs: 1_000,+ });+ expect(forward).not.toBeNull();+ expect(roomControl?.created).toHaveLength(2);++ roomControl!.deleteBarrier = forwardDrain.promise;+ router.abortCodecSfuReplacement(room.roomId, 1);+ let rollbackSettled = false;+ const rollback = router+ .beginCodecSfuReplacement({+ roomId: room.roomId,+ hostSessionId: host.sessionId,+ generation: 2,+ videoCodec: "automatic",+ timeoutMs: 1_000,+ })+ .finally(() => {+ rollbackSettled = true;+ });++ await vi.waitFor(() =>+ expect(+ (+ Reflect.get(router, "resourceWaiters") as Map<string, unknown>+ ).has(room.roomId),+ ).toBe(true),+ );+ expect(admission?.usage()).toEqual({ ingress: 1, egress: 1 });+ expect(roomControl?.created).toHaveLength(2);+ expect(rollbackSettled).toBe(false);++ forwardDrain.resolve();+ await expect(rollback).resolves.not.toBeNull();+ expect(roomControl?.created).toHaveLength(3);+ } finally {+ forwardDrain.resolve();+ await router.close();+ }+ });++ it("ignores a stale Host session failure for the current codec publication candidate", async () => {+ const { store, sent, router } = harness(1, true);+ try {+ const room = await store.createRoom();+ const { host: staleHost } = await establishSfuRoom(+ store,+ sent,+ router,+ room,+ );+ const currentHost = reconnectHost(+ store,+ room,+ "host_session_reconnected_12345678",+ );+ complete(router, currentHost);+ router.setPaused(room.roomId, true);+ const snapshot = await router.beginCodecSfuReplacement({+ roomId: room.roomId,+ hostSessionId: currentHost.sessionId,+ generation: 1,+ videoCodec: "h264",+ timeoutMs: 1_000,+ });+ expect(snapshot).not.toBeNull();+ const target = snapshot!.targets.find(+ (candidate) => candidate.preparationBinding.kind === "sfu",+ )!;+ const prepared = preparedFor(sent, target.viewerSessionId)!;++ router.handleRouteFailed(staleHost, {+ type: "route-failed",+ revision: prepared.revision,+ phase: "prepare",+ connectionId: null,+ });++ expect(router.parkCodecSfuReplacement(room.roomId, 1)).toBe(true);+ router.abortCodecSfuReplacement(room.roomId, 1);+ } finally {+ await router.close();+ }+ });++ it("wakes codec revalidation when a paused active edge fails", async () => {+ const { store, sent, onActiveRouteChanged, router } = harness(1);+ const room = await store.createRoom();+ const host = connectHost(store, room);+ complete(router, host);+ const viewer = connectViewer(store, room, "paused_hard_failure");+ complete(router, viewer);+ await vi.waitFor(() =>+ expect(preparedFor(sent, viewer.sessionId)).toBeDefined(),+ );+ const prepared = preparedFor(sent, viewer.sessionId)!;+ router.handleRouteReady(viewer, {+ type: "route-ready",+ revision: prepared.revision,+ phase: "prepare",+ });+ router.setPaused(room.roomId, true);+ onActiveRouteChanged.mockClear();++ router.handleRouteFailed(viewer, {+ type: "route-failed",+ revision: prepared.revision,+ phase: "active",+ connectionId: prepared.candidate.connectionId,+ });++ expect(onActiveRouteChanged).toHaveBeenCalledTimes(1);+ expect(onActiveRouteChanged).toHaveBeenCalledWith(room.roomId);+ expect(router.codecRouteSnapshot(room.roomId)?.targets).toEqual([]);+ await router.close();+ });++ it("clears an exact drain waiter on codec abort", async () => {+ const { store, sent, roomControl, router } = harness(1, true, undefined, 2);+ const drain = deferred();+ try {+ const room = await store.createRoom();+ const { host } = await establishSfuRoom(store, sent, router, room);+ roomControl!.deleteBarrier = drain.promise;+ router.setPaused(room.roomId, true);+ const preparation = router.beginCodecSfuReplacement({+ roomId: room.roomId,+ hostSessionId: host.sessionId,+ generation: 1,+ videoCodec: "h264",+ timeoutMs: 1_000,+ });+ const waiters = Reflect.get(router, "resourceWaiters") as Map<+ string,+ unknown+ >;+ await vi.waitFor(() => expect(waiters.has(room.roomId)).toBe(true));++ router.abortCodecSfuReplacement(room.roomId, 1);+ await expect(preparation).resolves.toBeNull();+ expect(waiters.has(room.roomId)).toBe(false);+ } finally {+ drain.resolve();+ await router.close();+ }+ });+it("emits typed exhaustion and clears diagnostics on departure and room deletion", async () => {const { store, sent, router } = harness(1);const room = await store.createRoom();diff --git a/tests/media-assignment.test.ts b/tests/media-assignment.test.tsindex 139bf63b..ec8b149b 100644--- a/tests/media-assignment.test.ts+++ b/tests/media-assignment.test.ts@@ -13,6 +13,7 @@ import {const offer: SignalPayload = {kind: "description",connectionId: "connection_12345678",+ negotiationGeneration: null,description: { type: "offer", sdp: "test-offer" },};diff --git a/tests/peer-assisted-benchmark.test.ts b/tests/peer-assisted-benchmark.test.tsindex ff89ff1e..40f122bd 100644--- a/tests/peer-assisted-benchmark.test.ts+++ b/tests/peer-assisted-benchmark.test.ts@@ -1,19 +1,25 @@import { runInNewContext } from "node:vm";-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import {activeVideoEdgeCount,+ buildBenchmarkFailureEvidence,buildBenchmarkInitScript,buildRecoveryCheck,+ buildRouteTimingCheck,buildRunChecks,captureRecoveryViewerBaselines,+ createPage,everyViewerAdvanced,everyViewerRecoveredMedia,+ joinViewerBurst,mergeRecoveryHostPeaks,parseBenchmarkCanaryMode,parseBenchmarkConfig,parseExpectedEndpointCap,parseViewerCounts,+ sanitizeFailurePageEvidence,+ summarizeBenchmarkRouteTiming,summarizeSamples,} from "../scripts/peer-assisted-benchmark";import { MAX_VIEWERS_PER_ROOM_LIMIT } from "../src/shared/protocol";@@ -29,6 +35,19 @@ const lowQualitySettings = {degradationPreference: "maintain-resolution",} as const;+interface Deferred<T> {+ promise: Promise<T>;+ resolve: (value: T) => void;+}++function createDeferred<T>(): Deferred<T> {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((resolvePromise) => {+ resolve = resolvePromise;+ });+ return { promise, resolve };+}+function page(role: "host" | "viewer",label: string,@@ -59,11 +78,6 @@ function page(),sfuPublicationGeneration: null as string | null,},- activeRouteReady: [] as Array<{- revision: number;- upstreamKind: ParticipantRouteAssignment["upstream"]["kind"];- sfuPublicationGeneration: string | null;- }>,firstDecodedAtEpochMs: role === "viewer" ? 1_500 : null,firstRenderedAtEpochMs: role === "viewer" ? 1_550 : null,renderedFrames: role === "viewer" ? 10 : 0,@@ -71,8 +85,8 @@ function page(...Array.from({ length: sendEdges }, (_, index) => ({index,createdAtEpochMs: 1_000,- connectionId: `send-${index}`,- remotePeerId: `child-${index}`,+ connectionId: `send-${index}` as string | null,+ remotePeerId: `child-${index}` as string | null,connectionState: "connected",iceConnectionState: "connected",hasOutboundVideo: true,@@ -103,12 +117,15 @@ function page(}class FakeWebSocket {+ readonly sent: string[] = [];private readonly listeners = new Map<string,Array<(event: { data?: string }) => void>>();- send(_data: string): void {}+ send(data: string): void {+ this.sent.push(data);+ }addEventListener(type: string,@@ -137,15 +154,13 @@ interface ObserverSnapshot {signalingConnected: boolean;routeRevision: number | null;routeAssignment: ParticipantRouteAssignment | null;- activeRouteReady: Array<{- revision: number;- upstreamKind: ParticipantRouteAssignment["upstream"]["kind"];- sfuPublicationGeneration: string | null;- }>;maxAssignedChildren: number;}-function createObserverHarness(expectedEndpointCap = 2) {+function createObserverHarness(+ expectedEndpointCap = 2,+ role: "host" | "viewer" = "host",+) {const context: Record<string, unknown> = {WebSocket: FakeWebSocket,RTCPeerConnection: class FakePeerConnection {},@@ -158,9 +173,9 @@ function createObserverHarness(expectedEndpointCap = 2) {queueMicrotask,};const source = buildBenchmarkInitScript({- label: "host-1",- role: "host",- viewerIndex: null,+ label: role === "host" ? "host-1" : "viewer-1",+ role,+ viewerIndex: role === "viewer" ? 1 : null,clearHostRoom: false,width: 1280,height: 720,@@ -175,20 +190,32 @@ function createObserverHarness(expectedEndpointCap = 2) {const api = context.__SCREENER_BENCHMARK__ as {snapshot: () => ObserverSnapshot;canarySnapshot: () => Record<string, unknown>;+ requestRouteDiagnosticSnapshot: () => boolean;+ routeDiagnosticTimingSamples: () => Record<+ string,+ Array<number | null>+ > | null;};return {socket: () => new WebSocketConstructor(),snapshot: () => structuredClone(api.snapshot()),canarySnapshot: () => structuredClone(api.canarySnapshot()),+ requestRouteDiagnosticSnapshot: () =>+ api.requestRouteDiagnosticSnapshot(),+ routeDiagnosticTimingSamples: () =>+ structuredClone(api.routeDiagnosticTimingSamples()),};}-function authenticate(socket: FakeWebSocket): void {+function authenticate(+ socket: FakeWebSocket,+ role: "host" | "viewer" = "host",+): void {socket.send(JSON.stringify({type: "authenticate",roomId: "1",- role: "host",+ role,}),);}@@ -204,28 +231,39 @@ function routeAssignment(};}-function markActiveRouteReady(observation: ReturnType<typeof page>): void {- if (observation.routeRevision === null) {- throw new Error("An active route revision is required");+function markSfuMedia(observation: ReturnType<typeof page>): void {+ const connection = observation.connections.find((candidate) =>+ observation.role === "host"+ ? candidate.hasOutboundVideo+ : candidate.hasInboundVideo,+ );+ if (!connection) {+ throw new Error("An SFU media connection is required");}- observation.activeRouteReady.push({- revision: observation.routeRevision,- upstreamKind: observation.routeAssignment.upstream.kind,- sfuPublicationGeneration:- observation.routeAssignment.sfuPublicationGeneration,- });+ connection.connectionId = null;+ connection.remotePeerId = null;}describe("peer topology loopback configuration", () => {it("keeps the real-relay canary opt-in", () => {expect(parseBenchmarkCanaryMode(undefined)).toBe("none");expect(parseBenchmarkCanaryMode("viewer-mbb")).toBe("viewer-mbb");- expect(parseBenchmarkConfig({ CHROME_PATH: "chrome", BENCHMARK_CANARY: "viewer-mbb" }).canaryMode).toBe("viewer-mbb");+ expect(parseBenchmarkConfig({+ CHROME_PATH: "chrome",+ BENCHMARK_CANARY: "viewer-mbb",+ BENCHMARK_VIEWERS: "3",+ }).canaryMode).toBe("viewer-mbb");+ expect(() => parseBenchmarkConfig({+ CHROME_PATH: "chrome",+ BENCHMARK_CANARY: "viewer-mbb",+ })).toThrow(/selected viewer count of 3/);expect(() => parseBenchmarkCanaryMode("signaling")).toThrow(/BENCHMARK_CANARY/);});- it("uses the bounded 1/3/5/8 matrix by default", () => {- expect(parseViewerCounts(undefined)).toEqual([1, 3, 5, 8]);+ it("runs the exact 20-Viewer acceptance case by default", () => {+ expect(parseViewerCounts(undefined)).toEqual([+ MAX_VIEWERS_PER_ROOM_LIMIT,+ ]);});it("deduplicates configured viewer counts without changing their order", () => {@@ -243,6 +281,124 @@ describe("peer topology loopback configuration", () => {);});+ it("starts every Viewer join before waiting for burst media", async () => {+ const creations = Array.from({ length: 3 }, () =>+ createDeferred<string>(),+ );+ const media = Array.from({ length: 3 }, () => createDeferred<void>());+ const creationStarts: number[] = [];+ const mediaStarts: number[] = [];++ const burst = joinViewerBurst(+ 3,+ (viewerIndex) => {+ creationStarts.push(viewerIndex);+ return creations[viewerIndex - 1]!.promise;+ },+ (_viewer, viewerIndex) => {+ mediaStarts.push(viewerIndex);+ return media[viewerIndex - 1]!.promise;+ },+ );+ expect(creationStarts).toEqual([1, 2, 3]);+ expect(mediaStarts).toEqual([]);++ creations[0]!.resolve("viewer-1");+ creations[1]!.resolve("viewer-2");+ await Promise.resolve();+ expect(mediaStarts).toEqual([]);+ creations[2]!.resolve("viewer-3");+ await vi.waitFor(() => expect(mediaStarts).toEqual([1, 2, 3]));++ media[2]!.resolve();+ media[0]!.resolve();+ media[1]!.resolve();+ await expect(burst).resolves.toEqual([+ "viewer-1",+ "viewer-2",+ "viewer-3",+ ]);+ });++ it("summarizes all four route timing keys without a pass threshold", () => {+ const values = Array.from({ length: 20 }, (_, index) =>+ index % 5 === 0 ? null : (20 - index) * 10,+ );+ const summary = summarizeBenchmarkRouteTiming({+ queueWaitMs: values,+ candidateStartMs: values,+ firstDecodedFrameMs: values,+ finalMs: values,+ });++ for (const timing of Object.values(summary)) {+ expect(timing).toEqual({+ sampleCount: 16,+ pendingCount: 4,+ rawMs: [+ 10, 20, 30, 40, 60, 70, 80, 90, 110, 120, 130, 140, 160,+ 170, 180, 190,+ ],+ p50Ms: 90,+ p95Ms: 190,+ maxMs: 190,+ });+ expect(Object.keys(timing)).not.toContain("passed");+ }+ expect(buildRouteTimingCheck("captured", summary)).toMatchObject({+ passed: true,+ actual: 4,+ });+ expect(buildRouteTimingCheck("unavailable", summary).passed).toBe(false);++ const incomplete = {+ ...summary,+ finalMs: { ...summary.finalMs, pendingCount: 3 },+ };+ expect(buildRouteTimingCheck("captured", incomplete)).toMatchObject({+ passed: false,+ actual: 3,+ });+ });++ it("closes the exact CDP target when page initialization fails", async () => {+ const call = vi.fn(+ async (method: string): Promise<Record<string, unknown>> => {+ if (method === "Target.createTarget") {+ return { targetId: "target-viewer-17" };+ }+ if (method === "Target.attachToTarget") {+ return { sessionId: "session-viewer-17" };+ }+ if (method === "Page.navigate") {+ return { errorText: "navigation rejected" };+ }+ return {};+ },+ );++ await expect(+ createPage(+ { call } as unknown as Parameters<typeof createPage>[0],+ "http://127.0.0.1:3000/r/1234",+ {+ label: "viewer-17",+ role: "viewer",+ viewerIndex: 17,+ clearHostRoom: false,+ width: 1280,+ height: 720,+ frameRate: 30,+ expectedEndpointCap: 2,+ },+ new AbortController().signal,+ ),+ ).rejects.toThrow("Navigation failed: navigation rejected");+ expect(call).toHaveBeenCalledWith("Target.closeTarget", {+ targetId: "target-viewer-17",+ });+ });+it("requires recovery to target one selected case", () => {expect(() =>parseBenchmarkConfig({@@ -291,6 +447,204 @@ describe("peer topology loopback configuration", () => {});describe("peer topology loopback observations", () => {+ it("bounds failure evidence and removes media-path identifiers and raw errors", () => {+ const unsafe = page("viewer", "viewer-11", 0, 1);+ unsafe.roomId = "room-secret";+ unsafe.peerId = "peer-secret";+ unsafe.routeAssignment.upstream = {+ kind: "peer",+ peerId: "parent-secret",+ };+ unsafe.connections = Array.from({ length: 9 }, (_, index) => ({+ ...structuredClone(unsafe.connections[0]!),+ index,+ connectionId: `connection-secret-${index}`,+ remotePeerId: `remote-secret-${index}`,+ error: `private-error-${index}`,+ }));++ const failure = buildBenchmarkFailureEvidence([unsafe], 21);+ expect(failure).toMatchObject({+ expectedPageCount: 21,+ observedPageCount: 1,+ pages: [+ {+ label: "viewer-11",+ authenticated: true,+ upstreamKind: "peer",+ connectionCount: 9,+ },+ ],+ });+ expect(failure.pages[0]?.connections).toHaveLength(6);+ expect(sanitizeFailurePageEvidence(unsafe)).toEqual(failure.pages[0]);+ const serialized = JSON.stringify(failure);+ for (const secret of [+ "room-secret",+ "peer-secret",+ "parent-secret",+ "connection-secret",+ "remote-secret",+ "private-error",+ ]) {+ expect(serialized).not.toContain(secret);+ }+ });++ it("requests one Host-only route snapshot and retains only timing samples", () => {+ const observer = createObserverHarness();+ const socket = observer.socket();+ authenticate(socket);+ socket.emitMessage({+ type: "authenticated",+ role: "host",+ peerId: "host_peer_0001",+ mediaMode: "peer-assisted",+ routeRevision: 1,+ routeAssignment: routeAssignment([]),+ qualitySettings: lowQualitySettings,+ });++ expect(observer.requestRouteDiagnosticSnapshot()).toBe(true);+ expect(observer.requestRouteDiagnosticSnapshot()).toBe(false);+ expect(+ socket.sent+ .map((value) => JSON.parse(value) as { type?: string })+ .filter((message) => message.type === "request-route-diagnostic"),+ ).toHaveLength(1);++ const children = Array.from(+ { length: MAX_VIEWERS_PER_ROOM_LIMIT },+ (_, index) => ({+ ordinal: index + 1,+ ...(index === 0+ ? {+ peerId: "must_not_escape",+ connectionId: "must_not_escape",+ }+ : {}),+ queueWaitMs: index === 0 ? 30 : null,+ candidateStartMs: index === 0 ? 50 : index === 1 ? 20 : null,+ firstDecodedFrameMs: index === 0 ? 80 : null,+ finalMs: index === 0 ? 90 : null,+ }),+ );+ socket.emitMessage({+ type: "route-diagnostic-snapshot",+ snapshot: { children },+ });++ const timing = observer.routeDiagnosticTimingSamples();+ expect(timing?.queueWaitMs).toHaveLength(MAX_VIEWERS_PER_ROOM_LIMIT);+ expect(timing?.queueWaitMs.slice(0, 2)).toEqual([30, null]);+ expect(timing?.candidateStartMs.slice(0, 2)).toEqual([50, 20]);+ expect(timing?.firstDecodedFrameMs.slice(0, 2)).toEqual([80, null]);+ expect(timing?.finalMs.slice(0, 2)).toEqual([90, null]);+ expect(+ JSON.stringify(observer.routeDiagnosticTimingSamples()),+ ).not.toContain("must_not_escape");+ });++ it("captures a partial failure snapshot without satisfying exact 20", () => {+ const observer = createObserverHarness();+ const socket = observer.socket();+ authenticate(socket);+ socket.emitMessage({+ type: "authenticated",+ role: "host",+ peerId: "host_peer_0001",+ mediaMode: "peer-assisted",+ routeRevision: 1,+ routeAssignment: routeAssignment([]),+ qualitySettings: lowQualitySettings,+ });+ expect(observer.requestRouteDiagnosticSnapshot()).toBe(true);+ socket.emitMessage({+ type: "route-diagnostic-snapshot",+ snapshot: {+ children: Array.from(+ { length: MAX_VIEWERS_PER_ROOM_LIMIT - 1 },+ (_, index) => ({+ ordinal: index + 1,+ queueWaitMs: null,+ candidateStartMs: null,+ firstDecodedFrameMs: null,+ finalMs: null,+ }),+ ),+ },+ });+ const timing = observer.routeDiagnosticTimingSamples();+ expect(timing?.queueWaitMs).toHaveLength(+ MAX_VIEWERS_PER_ROOM_LIMIT - 1,+ );+ expect(+ buildRouteTimingCheck(+ "captured",+ summarizeBenchmarkRouteTiming(+ timing as Parameters<typeof summarizeBenchmarkRouteTiming>[0],+ ),+ ).passed,+ ).toBe(false);+ });++ it("does not expose the route diagnostic request on a Viewer page", () => {+ const observer = createObserverHarness(2, "viewer");+ const socket = observer.socket();+ authenticate(socket, "viewer");+ socket.emitMessage({+ type: "authenticated",+ role: "viewer",+ peerId: "viewer_peer_0001",+ mediaMode: "peer-assisted",+ routeRevision: 1,+ routeAssignment: {+ upstream: { kind: "peer", peerId: "host_peer_0001" },+ childPeerIds: [],+ sfuPublicationGeneration: null,+ },+ qualitySettings: lowQualitySettings,+ });++ expect(observer.requestRouteDiagnosticSnapshot()).toBe(false);+ expect(+ socket.sent+ .map((value) => JSON.parse(value) as { type?: string })+ .some((message) => message.type === "request-route-diagnostic"),+ ).toBe(false);+ });++ it.each([+ ["an SFU upstream without a generation", { kind: "sfu" }, null],+ [+ "a peer upstream with a generation",+ { kind: "peer", peerId: "host_peer_0001" },+ "publication_generation_12345678",+ ],+ ])("rejects %s in the v9 route observer", (_label, upstream, generation) => {+ const observer = createObserverHarness(2, "viewer");+ const socket = observer.socket();+ authenticate(socket, "viewer");+ socket.emitMessage({+ type: "authenticated",+ role: "viewer",+ peerId: "viewer_peer_0001",+ mediaMode: "peer-assisted",+ routeRevision: 1,+ routeAssignment: {+ upstream,+ childPeerIds: [],+ sfuPublicationGeneration: generation,+ },+ qualitySettings: lowQualitySettings,+ });++ expect(observer.snapshot()).toMatchObject({+ routeRevision: null,+ routeAssignment: null,+ });+ });+it("counts only active media connections in the requested direction", () => {const host = page("host", "host", 2, 0);host.connections[0]!.connectionState = "closed";@@ -457,8 +811,10 @@ describe("peer topology loopback observations", () => {"publication_generation_12345678";initial[1]!.routeRevision = 7;initial[1]!.routeAssignment.upstream = { kind: "sfu" };- markActiveRouteReady(initial[0]!);- markActiveRouteReady(initial[1]!);+ initial[1]!.routeAssignment.sfuPublicationGeneration =+ "publication_generation_12345678";+ markSfuMedia(initial[0]!);+ markSfuMedia(initial[1]!);const final = structuredClone(initial);final[1]!.connections[0]!.receiveTotals!.framesTotal = 20;@@ -512,9 +868,10 @@ describe("peer topology loopback observations", () => {for (const root of [firstRoot, secondRoot]) {root.routeRevision = 7;root.routeAssignment.upstream = { kind: "sfu" };+ root.routeAssignment.sfuPublicationGeneration = generation;}for (const participant of [host, firstRoot, secondRoot]) {- markActiveRouteReady(participant);+ markSfuMedia(participant);}const initial = [host, direct, firstRoot, secondRoot];@@ -548,7 +905,8 @@ describe("peer topology loopback observations", () => {const thirdRoot = page("viewer", "viewer-4", 0, 1);thirdRoot.routeRevision = 7;thirdRoot.routeAssignment.upstream = { kind: "sfu" };- markActiveRouteReady(thirdRoot);+ thirdRoot.routeAssignment.sfuPublicationGeneration = generation;+ markSfuMedia(thirdRoot);const threeRootInitial = [...structuredClone(initial), thirdRoot];const threeRootFinal = structuredClone(threeRootInitial);for (const viewer of threeRootFinal.slice(1)) {@@ -602,8 +960,8 @@ describe("peer topology loopback observations", () => {initial[1]!.routeRevision = viewerRevision;initial[1]!.routeAssignment.upstream = { kind: "sfu" };initial[1]!.routeAssignment.sfuPublicationGeneration = viewerGeneration;- markActiveRouteReady(initial[0]!);- markActiveRouteReady(initial[1]!);+ markSfuMedia(initial[0]!);+ markSfuMedia(initial[1]!);const final = structuredClone(initial);final[1]!.connections[0]!.receiveTotals!.framesTotal = 20;return summarizeSamples(@@ -648,13 +1006,15 @@ describe("peer topology loopback observations", () => {"publication_generation_12345678";initial[1]!.routeRevision = 7;initial[1]!.routeAssignment.upstream = { kind: "sfu" };+ initial[1]!.routeAssignment.sfuPublicationGeneration =+ "publication_generation_12345678";initial[2]!.routeRevision = 6;initial[2]!.routeAssignment.upstream = {kind: "peer",peerId: initial[1]!.peerId,};- markActiveRouteReady(initial[0]!);- markActiveRouteReady(initial[1]!);+ markSfuMedia(initial[0]!);+ markSfuMedia(initial[1]!);const final = structuredClone(initial);final[1]!.connections.at(-1)!.receiveTotals!.framesTotal = 20;@@ -682,7 +1042,9 @@ describe("peer topology loopback observations", () => {"publication_generation_12345678";initial[1]!.routeRevision = 7;initial[1]!.routeAssignment.upstream = { kind: "sfu" };- markActiveRouteReady(initial[0]!);+ initial[1]!.routeAssignment.sfuPublicationGeneration =+ "publication_generation_12345678";+ markSfuMedia(initial[0]!);const final = structuredClone(initial);final[1]!.connections[0]!.receiveTotals!.framesTotal = 20;@@ -1001,20 +1363,6 @@ describe("peer topology loopback observations", () => {maxAssignedChildren: 2,});- owner.send(- JSON.stringify({ type: "route-ready", revision: 5, phase: "active" }),- );- outsider.send(- JSON.stringify({ type: "route-ready", revision: 5, phase: "active" }),- );- expect(observer.snapshot().activeRouteReady).toEqual([- {- revision: 5,- upstreamKind: "none",- sfuPublicationGeneration: "publication_generation_12345678",- },- ]);-owner.emitMessage({type: "route-update",revision: 5,@@ -1081,7 +1429,6 @@ describe("peer topology loopback observations", () => {signalingConnected: false,routeRevision: 4,routeAssignment: assignment,- activeRouteReady: [],});current.emitMessage({type: "authenticated",diff --git a/tests/protocol.test.ts b/tests/protocol.test.tsindex ba991f2e..1b6a44b6 100644--- a/tests/protocol.test.ts+++ b/tests/protocol.test.ts@@ -565,6 +565,76 @@ describe("client signaling protocol", () => {).toBe(false);});+ it("requires one exact Resume attempt across authorization, ack, and proof", () => {+ const sourceAck = {+ type: "sharing-source-enabled",+ shareGeneration: "share_generation_12345678",+ codecGeneration: 4,+ resumeAttempt: 9,+ };+ expect(clientMessageSchema.safeParse(sourceAck).success).toBe(true);+ expect(+ clientMessageSchema.safeParse({ ...sourceAck, resumeAttempt: undefined })+ .success,+ ).toBe(false);++ const proof = {+ type: "video-codec-proof",+ shareGeneration: "share_generation_12345678",+ generation: 4,+ resumeAttempt: 9,+ routeRevision: 7,+ binding: { kind: "peer", connectionId: "connection_12345678" },+ evidence: {+ baselineSampleTimestampMs: 100,+ sampleTimestampMs: 200,+ rtpStatsId: "inbound_video_12345678",+ rtpSsrc: 42,+ rtpMid: "0",+ rtpRid: null,+ trackIdentifier: "track_12345678",+ framesDecodedDelta: 1,+ actualCodec: "h264",+ },+ };+ expect(clientMessageSchema.safeParse(proof).success).toBe(true);+ expect(+ clientMessageSchema.safeParse({ ...proof, resumeAttempt: undefined })+ .success,+ ).toBe(false);++ const authorization = {+ type: "sharing-resume-authorized",+ shareGeneration: "share_generation_12345678",+ codecGeneration: 4,+ resumeAttempt: 9,+ };+ expect(serverMessageSchema.safeParse(authorization).success).toBe(true);+ expect(+ serverMessageSchema.safeParse({+ ...authorization,+ resumeAttempt: undefined,+ }).success,+ ).toBe(false);++ const proofRequest = {+ type: "video-codec-proof-request",+ shareGeneration: "share_generation_12345678",+ generation: 4,+ resumeAttempt: 9,+ routeRevision: 7,+ expectedCodec: "h264",+ binding: { kind: "peer", connectionId: "connection_12345678" },+ };+ expect(serverMessageSchema.safeParse(proofRequest).success).toBe(true);+ expect(+ serverMessageSchema.safeParse({+ ...proofRequest,+ resumeAttempt: undefined,+ }).success,+ ).toBe(false);+ });+it("accepts only strict, bounded quality settings", () => {expect(clientMessageSchema.safeParse({@@ -1244,9 +1314,37 @@ describe("server signaling protocol", () => {childPeerId: "child_12345678",connectionId: "connection_12345678",transport: "direct",+ codecTransition: null,},}).success,).toBe(true);+ expect(+ serverMessageSchema.safeParse({+ type: "route-update",+ revision: 10,+ phase: "prepare",+ assignment,+ candidate: {+ childPeerId: "child_12345678",+ connectionId: "connection_12345678",+ transport: "sfu",+ codecTransition: { generation: 4, videoCodec: "h264" },+ },+ }).success,+ ).toBe(true);+ expect(+ serverMessageSchema.safeParse({+ type: "route-update",+ revision: 10,+ phase: "prepare",+ assignment,+ candidate: {+ childPeerId: "child_12345678",+ connectionId: "connection_12345678",+ transport: "direct",+ },+ }).success,+ ).toBe(false);expect(serverMessageSchema.safeParse({type: "sfu-config",@@ -1309,10 +1407,17 @@ describe("server signaling protocol", () => {upstream,childPeerIds: [],sfuPublicationGeneration:- upstream.kind === "none" ? "generation_12345678" : null,+ upstream.kind === "peer" ? null : "generation_12345678",}).success,).toBe(true);}+ expect(+ participantRouteAssignmentSchema.safeParse({+ upstream: { kind: "sfu" },+ childPeerIds: [],+ sfuPublicationGeneration: null,+ }).success,+ ).toBe(false);});it("accepts only canonical server-derived viewer evidence envelopes", () => {diff --git a/tests/room-route-controller.test.ts b/tests/room-route-controller.test.tsindex 66457b07..55b4c06a 100644--- a/tests/room-route-controller.test.ts+++ b/tests/room-route-controller.test.ts@@ -6,6 +6,7 @@ import {type CandidateCursorGuard,type CandidateReservation,type CommittedEdgeSeed,+ type EdgeGuard,type OperationSnapshot,} from "../src/server/room-route-controller.ts";@@ -52,6 +53,7 @@ function addViewer(function cursorGuard(operation: OperationSnapshot): CandidateCursorGuard {return {+ owner: { ...operation.owner },childPeerId: operation.childPeerId,childSessionId: operation.childSessionId,baseRevision: operation.baseRevision,@@ -69,11 +71,15 @@ function beginCandidate(reservation: CandidateReservation<string>;publicationGeneration?: string;publicationConnectionId?: string;+ hostSessionId?: string;},) {const operation = routes.snapshot().operation!;return routes.beginCurrentCandidate({guard: cursorGuard(operation),+ ...(input.reservation.kind === "direct"+ ? {}+ : { hostSessionId: input.hostSessionId ?? "host_session" }),...input,});}@@ -120,6 +126,26 @@ function peerEdge(};}+function beginCodecSfu(+ routes: RoomRouteController<string>,+ overrides: Partial<+ Parameters<typeof routes.beginCodecSfuPublication>[0]+ > = {},+) {+ return routes.beginCodecSfuPublication({+ routeRevision: routes.snapshot().revision,+ hostSessionId: "host_session",+ codecGeneration: 1,+ videoCodec: "h264",+ publicationGeneration: "publication_fresh",+ connectionId: "subscription_fresh",+ publicationConnectionId: "publication_connection_fresh",+ nowMs: 10,+ deadlineAtMs: 110,+ ...overrides,+ });+}+describe("RoomRouteController", () => {it("retains one latest timing sample for a 20-Viewer burst", () => {const routes = controller(2);@@ -1113,6 +1139,622 @@ describe("RoomRouteController", () => {});});+ it("starts one codec-owned SFU gap with a deterministic anchor and retained subtrees", () => {+ const routes = controller(1, { sfuEnabled: true });+ addViewer(routes, B, 1);+ addViewer(routes, A, 0);+ addViewer(routes, C, 0);+ routes.hydrateHostPublication(+ "publication_old",+ "publication_resource_old",+ "publication_connection_old",+ );+ for (const peerId of [B, A]) {+ routes.hydrateEdge(peerId, {+ kind: "sfu",+ publicationGeneration: "publication_old",+ transport: "sfu",+ connectionId: `${peerId}_sfu_old`,+ usable: true,+ physicalActive: true,+ resource: `${peerId}_subscription_old`,+ });+ }+ routes.hydrateEdge(C, peerEdge(B, "c_from_b"));+ routes.setPaused(true);++ const begun = beginCodecSfu(routes);+ expect(begun).toMatchObject({+ accepted: true,+ activeRevision: 1,+ anchorPeerId: B,+ retiredPeerIds: [B, A],+ operation: {+ owner: {+ kind: "codec",+ codecGeneration: 1,+ phase: "preparing",+ videoCodec: "h264",+ publicationGeneration: "publication_fresh",+ connectionId: "subscription_fresh",+ publicationConnectionId: "publication_connection_fresh",+ },+ childPeerId: B,+ candidates: [{ tuple: { kind: "sfu", publication: "replace" } }],+ },+ });+ expect(begun.released).toEqual(expect.arrayContaining([+ "publication_resource_old",+ `${B}_subscription_old`,+ `${A}_subscription_old`,+ ]));+ expect(begun.released).toHaveLength(3);+ expect(routes.snapshot().hostPublication).toMatchObject({+ generation: "publication_old",+ usable: false,+ physicalActive: false,+ });+ for (const peerId of [B, A]) {+ expect(routes.snapshot().upstreamByViewer.get(peerId)).toMatchObject({+ kind: "sfu",+ publicationGeneration: "publication_old",+ usable: false,+ physicalActive: false,+ });+ }+ expect(routes.snapshot().upstreamByViewer.get(C)).toMatchObject({+ kind: "peer",+ parentPeerId: B,+ usable: true,+ physicalActive: true,+ });+ expect(beginCodecSfu(routes, { codecGeneration: 2 }).accepted).toBe(false);+ });++ it("parks an exact codec SFU attempt until proving and rebinds logical subscribers on commit", () => {+ const routes = controller(1, { sfuEnabled: true });+ addViewer(routes, A, 0);+ addViewer(routes, B, 0);+ routes.hydrateHostPublication(+ "publication_old",+ "publication_resource_old",+ "publication_connection_old",+ );+ for (const peerId of [A, B]) {+ routes.hydrateEdge(peerId, {+ kind: "sfu",+ publicationGeneration: "publication_old",+ transport: "sfu",+ connectionId: `${peerId}_sfu_old`,+ usable: true,+ physicalActive: true,+ resource: `${peerId}_subscription_old`,+ });+ }+ routes.setPaused(true);+ const begun = beginCodecSfu(routes);+ const guard = begun.guard!;++ const wrongIdentity = beginCandidate(routes, {+ nowMs: 11,+ connectionId: "wrong_subscription",+ publicationGeneration: "publication_fresh",+ publicationConnectionId: "publication_connection_fresh",+ reservation: {+ kind: "sfu-create",+ edge: "wrong_edge_reservation",+ publication: "wrong_publication_reservation",+ },+ });+ expect(wrongIdentity.accepted).toBe(false);+ expect(wrongIdentity.released).toEqual([+ "wrong_edge_reservation",+ "wrong_publication_reservation",+ ]);++ const pending = beginCandidate(routes, {+ nowMs: 12,+ connectionId: guard.connectionId,+ publicationGeneration: guard.publicationGeneration,+ publicationConnectionId: guard.publicationConnectionId,+ reservation: {+ kind: "sfu-create",+ edge: "subscription_resource_fresh",+ publication: "publication_resource_fresh",+ },+ }).operation!;+ const readyGuard: CandidateGuard = {+ childPeerId: pending.childPeerId,+ childSessionId: pending.childSessionId,+ revision: pending.current!.revision,+ connectionId: guard.connectionId,+ };+ expect(routes.candidateReady(readyGuard, 13).accepted).toBe(false);+ expect(routes.transitionCodecOperation({+ guard,+ expectedPhase: "preparing",+ phase: "prepared",+ }).accepted).toBe(true);+ expect(routes.operationExpired(10_000).accepted).toBe(false);+ expect(routes.snapshot().operation?.owner).toMatchObject({+ kind: "codec",+ phase: "prepared",+ });+ expect(routes.candidateReady(readyGuard, 10_001).accepted).toBe(false);+ expect(routes.transitionCodecOperation({+ guard: { ...guard, connectionId: "stale_connection" },+ expectedPhase: "prepared",+ phase: "proving",+ nowMs: 20,+ deadlineAtMs: 30,+ }).accepted).toBe(false);+ expect(routes.transitionCodecOperation({+ guard,+ expectedPhase: "prepared",+ phase: "proving",+ nowMs: 20,+ deadlineAtMs: 30,+ }).accepted).toBe(true);+ expect(routes.transitionCodecOperation({+ guard,+ expectedPhase: "proving",+ phase: "prepared",+ }).accepted).toBe(true);+ expect(routes.operationExpired(1_000).accepted).toBe(false);+ expect(routes.candidateReady(readyGuard, 1_001).accepted).toBe(false);+ expect(routes.transitionCodecOperation({+ guard,+ expectedPhase: "prepared",+ phase: "proving",+ nowMs: 22,+ deadlineAtMs: 40,+ }).accepted).toBe(true);++ expect(routes.candidateReady(readyGuard, 23).accepted).toBe(true);+ const committed = routes.snapshot();+ expect(committed.operation).toBeUndefined();+ expect(committed.hostPublication).toMatchObject({+ generation: "publication_fresh",+ connectionId: "publication_connection_fresh",+ usable: true,+ physicalActive: true,+ resource: "publication_resource_fresh",+ });+ expect(committed.upstreamByViewer.get(A)).toMatchObject({+ publicationGeneration: "publication_fresh",+ connectionId: "subscription_fresh",+ usable: true,+ physicalActive: true,+ resource: "subscription_resource_fresh",+ });+ expect(committed.upstreamByViewer.get(B)).toMatchObject({+ publicationGeneration: "publication_fresh",+ usable: false,+ physicalActive: false,+ resource: `${B}_subscription_old`,+ });+ });++ it("folds an invalid direct binding into the pending codec revision", () => {+ const routes = controller(1, { sfuEnabled: true });+ addViewer(routes, A, 1);+ addViewer(routes, B, 0);+ routes.hydrateHostPublication(+ "publication_old",+ "publication_resource_old",+ "publication_connection_old",+ );+ routes.hydrateEdge(A, {+ kind: "sfu",+ publicationGeneration: "publication_old",+ transport: "sfu",+ connectionId: "a_sfu_old",+ usable: true,+ physicalActive: true,+ resource: "a_subscription_old",+ });+ routes.hydrateEdge(B, peerEdge(A, "b_from_a"));+ routes.setPaused(true);+ const begun = beginCodecSfu(routes);+ const guard = begun.guard!;+ const pending = beginCandidate(routes, {+ nowMs: 11,+ connectionId: guard.connectionId,+ publicationGeneration: guard.publicationGeneration,+ publicationConnectionId: guard.publicationConnectionId,+ reservation: {+ kind: "sfu-create",+ edge: "subscription_resource_fresh",+ publication: "publication_resource_fresh",+ },+ }).operation!;+ const pendingRevision = pending.current!.revision;+ const activeRevision = routes.snapshot().revision;++ expect(+ routes.retireCommittedTransportsForRouteWait(+ [+ {+ childPeerId: B,+ childSessionId: `${B}_session`,+ parentSessionId: `${A}_session`,+ routeRevision: activeRevision,+ connectionId: "b_from_a",+ },+ ],+ 12,+ ),+ ).toMatchObject({+ accepted: true,+ activeRevision,+ retiredPeerIds: [B],+ });+ expect(routes.snapshot().revision).toBe(activeRevision);+ expect(routes.snapshot().upstreamByViewer.get(B)).toMatchObject({+ usable: false,+ physicalActive: true,+ });+ expect(routes.snapshot().operation?.current?.revision).toBe(pendingRevision);++ expect(+ routes.transitionCodecOperation({+ guard,+ expectedPhase: "preparing",+ phase: "prepared",+ }).accepted,+ ).toBe(true);+ expect(+ routes.transitionCodecOperation({+ guard,+ expectedPhase: "prepared",+ phase: "proving",+ nowMs: 13,+ deadlineAtMs: 30,+ }).accepted,+ ).toBe(true);+ expect(+ routes.candidateReady(+ {+ childPeerId: A,+ childSessionId: `${A}_session`,+ revision: pendingRevision,+ connectionId: guard.connectionId,+ },+ 14,+ ).accepted,+ ).toBe(true);+ expect(routes.snapshot().revision).toBe(pendingRevision);+ expect(routes.snapshot().upstreamByViewer.get(B)).toMatchObject({+ usable: false,+ physicalActive: false,+ });+ });++ it.each([+ ["before-candidate", "commit"],+ ["before-candidate", "abort"],+ ["after-candidate", "commit"],+ ["after-candidate", "abort"],+ ] as const)(+ "retires a C=2 invalid exact edge folded %s through codec %s",+ (foldAt, outcome) => {+ const routes = controller(2, { sfuEnabled: true });+ addViewer(routes, A, 0);+ addViewer(routes, B, 0);+ routes.hydrateHostPublication(+ "publication_old",+ "publication_resource_old",+ "publication_connection_old",+ );+ routes.hydrateEdge(A, {+ kind: "sfu",+ publicationGeneration: "publication_old",+ transport: "sfu",+ connectionId: "a_sfu_old",+ usable: true,+ physicalActive: true,+ resource: "a_subscription_old",+ });+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));+ routes.setPaused(true);+ const begun = beginCodecSfu(routes);+ const guard = begun.guard!;+ const activeRevision = routes.snapshot().revision;+ const directGuard: EdgeGuard = {+ childPeerId: B,+ childSessionId: `${B}_session`,+ parentSessionId: "host_session",+ routeRevision: activeRevision,+ connectionId: "b_from_host",+ };+ const invalidateAndFold = (nowMs: number) => {+ expect(routes.invalidateEdge(directGuard, nowMs)).toBe(true);+ expect(routes.snapshot().upstreamByViewer.get(B)).toMatchObject({+ usable: false,+ physicalActive: true,+ });+ const invalidatedFactVersion = routes.snapshot().factVersion;+ expect(+ routes.retireCommittedTransportsForRouteWait(+ [directGuard],+ nowMs + 1,+ ),+ ).toMatchObject({+ accepted: true,+ activeRevision,+ released: [],+ });+ expect(routes.snapshot().factVersion).toBe(invalidatedFactVersion);+ expect(routes.invalidateEdge(directGuard, nowMs + 2)).toBe(true);+ expect(+ routes.retireCommittedTransportsForRouteWait(+ [directGuard],+ nowMs + 3,+ ),+ ).toMatchObject({+ accepted: true,+ activeRevision,+ released: [],+ });+ expect(routes.snapshot().factVersion).toBe(invalidatedFactVersion);+ expect(routes.snapshot().upstreamByViewer.get(B)).toMatchObject({+ usable: false,+ physicalActive: true,+ });+ };++ if (foldAt === "before-candidate") invalidateAndFold(11);+ const pending = beginCandidate(routes, {+ nowMs: 20,+ connectionId: guard.connectionId,+ publicationGeneration: guard.publicationGeneration,+ publicationConnectionId: guard.publicationConnectionId,+ reservation: {+ kind: "sfu-create",+ edge: "subscription_resource_fresh",+ publication: "publication_resource_fresh",+ },+ }).operation!;+ if (foldAt === "after-candidate") invalidateAndFold(21);+ expect(+ routes.transitionCodecOperation({+ guard,+ expectedPhase: "preparing",+ phase: "prepared",+ }).accepted,+ ).toBe(true);+ expect(routes.operationExpired(1_000_000).accepted).toBe(false);++ if (outcome === "commit") {+ expect(+ routes.transitionCodecOperation({+ guard,+ expectedPhase: "prepared",+ phase: "proving",+ nowMs: 30,+ deadlineAtMs: 40,+ }).accepted,+ ).toBe(true);+ const settled = routes.candidateReady(+ {+ childPeerId: A,+ childSessionId: `${A}_session`,+ revision: pending.current!.revision,+ connectionId: guard.connectionId,+ },+ 31,+ );+ expect(settled.accepted).toBe(true);+ expect(settled.activeRevision).toBe(pending.current!.revision);+ } else {+ const aborted = routes.abortCodecOperation(guard, 31);+ expect(aborted.accepted).toBe(true);+ expect(aborted.activeRevision).toBeGreaterThan(+ pending.current!.revision,+ );+ expect(aborted.released).toEqual([+ "subscription_resource_fresh",+ "publication_resource_fresh",+ ]);+ }+ expect(routes.snapshot().upstreamByViewer.get(B)).toMatchObject({+ usable: false,+ physicalActive: false,+ });+ expect(+ routes.retireCommittedTransportsForRouteWait([directGuard], 32),+ ).toMatchObject({ accepted: false, released: [] });+ },+ );++ it("aborts an exact pending codec publication and starts a fresh retained-anchor rollback", () => {+ const routes = controller(1, { sfuEnabled: true });+ addViewer(routes, A, 0);+ routes.hydrateHostPublication(+ "publication_old",+ "publication_resource_old",+ "publication_connection_old",+ );+ routes.hydrateEdge(A, {+ kind: "sfu",+ publicationGeneration: "publication_old",+ transport: "sfu",+ connectionId: "subscription_old",+ usable: true,+ physicalActive: true,+ resource: "subscription_resource_old",+ });+ routes.setPaused(true);+ const forward = beginCodecSfu(routes);+ const forwardGuard = forward.guard!;+ const pending = beginCandidate(routes, {+ nowMs: 11,+ connectionId: forwardGuard.connectionId,+ publicationGeneration: forwardGuard.publicationGeneration,+ publicationConnectionId: forwardGuard.publicationConnectionId,+ reservation: {+ kind: "sfu-create",+ edge: "forward_subscription_resource",+ publication: "forward_publication_resource",+ },+ }).operation!;+ const pendingRevision = pending.current!.revision;++ expect(routes.abortCodecOperation({+ ...forwardGuard,+ codecGeneration: 2,+ }, 12).accepted).toBe(false);+ const aborted = routes.abortCodecOperation(forwardGuard, 12);+ expect(aborted.accepted).toBe(true);+ expect(aborted.activeRevision).toBeGreaterThan(pendingRevision);+ expect(aborted.released).toEqual([+ "forward_subscription_resource",+ "forward_publication_resource",+ ]);+ expect(routes.snapshot().operation).toBeUndefined();+ expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({+ publicationGeneration: "publication_old",+ usable: false,+ physicalActive: false,+ });++ const rollback = beginCodecSfu(routes, {+ routeRevision: routes.snapshot().revision,+ codecGeneration: 2,+ videoCodec: "automatic",+ publicationGeneration: "publication_rollback",+ connectionId: "subscription_rollback",+ publicationConnectionId: "publication_connection_rollback",+ nowMs: 20,+ deadlineAtMs: 120,+ retainedAnchor: {+ childPeerId: A,+ childSessionId: `${A}_session`,+ },+ });+ expect(rollback).toMatchObject({+ accepted: true,+ anchorPeerId: A,+ retiredPeerIds: [],+ released: [],+ operation: {+ owner: {+ kind: "codec",+ codecGeneration: 2,+ phase: "preparing",+ videoCodec: "automatic",+ publicationGeneration: "publication_rollback",+ },+ candidates: [{ tuple: { kind: "sfu", publication: "replace" } }],+ },+ });+ });++ it.each(["preparing", "proving"] as const)(+ "reselects a connected logical SFU placeholder when the %s anchor leaves",+ (phase) => {+ const routes = controller(1, { sfuEnabled: true });+ addViewer(routes, A, 0);+ addViewer(routes, B, 0);+ routes.hydrateHostPublication(+ "publication_old",+ "publication_resource_old",+ "publication_connection_old",+ );+ for (const peerId of [A, B]) {+ routes.hydrateEdge(peerId, {+ kind: "sfu",+ publicationGeneration: "publication_old",+ transport: "sfu",+ connectionId: `${peerId}_sfu_old`,+ usable: true,+ physicalActive: true,+ resource: `${peerId}_subscription_old`,+ });+ }+ routes.setPaused(true);+ const forward = beginCodecSfu(routes);+ const guard = forward.guard!;+ beginCandidate(routes, {+ nowMs: 11,+ connectionId: guard.connectionId,+ publicationGeneration: guard.publicationGeneration,+ publicationConnectionId: guard.publicationConnectionId,+ reservation: {+ kind: "sfu-create",+ edge: "forward_subscription_resource",+ publication: "forward_publication_resource",+ },+ });+ if (phase === "proving") {+ expect(routes.transitionCodecOperation({+ guard,+ expectedPhase: "preparing",+ phase: "prepared",+ }).accepted).toBe(true);+ expect(routes.transitionCodecOperation({+ guard,+ expectedPhase: "prepared",+ phase: "proving",+ nowMs: 12,+ deadlineAtMs: 112,+ }).accepted).toBe(true);+ }++ expect(routes.disconnectSession(A, `${A}_session`)).toBe(true);+ expect(routes.confirmDeparture(A, 13)).toBe(true);+ expect(routes.abortCodecOperation(guard, 14).accepted).toBe(true);+ const rollback = beginCodecSfu(routes, {+ routeRevision: routes.snapshot().revision,+ codecGeneration: 2,+ videoCodec: "automatic",+ publicationGeneration: `publication_rollback_${phase}`,+ connectionId: `subscription_rollback_${phase}`,+ publicationConnectionId: `publication_connection_rollback_${phase}`,+ nowMs: 20,+ deadlineAtMs: 120,+ });+ expect(rollback).toMatchObject({+ accepted: true,+ anchorPeerId: B,+ operation: {+ owner: {+ kind: "codec",+ codecGeneration: 2,+ phase: "preparing",+ },+ childPeerId: B,+ candidates: [+ { tuple: { kind: "sfu", publication: "replace" } },+ ],+ },+ });+ },+ );++ it("creates a codec SFU publication for an exact retained waiting anchor", () => {+ const routes = controller(1, { sfuEnabled: true });+ addViewer(routes, A, 0);+ routes.setPaused(true);+ const begun = beginCodecSfu(routes, {+ retainedAnchor: {+ childPeerId: A,+ childSessionId: `${A}_session`,+ },+ });+ expect(begun).toMatchObject({+ accepted: true,+ anchorPeerId: A,+ activeRevision: 0,+ retiredPeerIds: [],+ released: [],+ operation: {+ owner: { kind: "codec", phase: "preparing" },+ candidates: [{ tuple: { kind: "sfu", publication: "create" } }],+ },+ });+ });+it("replaces one publication and makes every old subscriber waiting", () => {const routes = controller(1, { sfuEnabled: true });addViewer(routes, A, 0);diff --git a/tests/route-transition.test.ts b/tests/route-transition.test.tsindex 2b57d057..50e05924 100644--- a/tests/route-transition.test.ts+++ b/tests/route-transition.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest";import type {ClientMessage,ParticipantRouteAssignment,+ PreparedRouteCandidate,} from "../src/shared/protocol.ts";import { HostSfuRoute } from "../src/client/media/host-sfu-route.ts";import { QUALITY_PROFILES } from "../src/client/media/quality.ts";@@ -25,10 +26,11 @@ const peerAssignment = (const viewerSfuAssignment = (childPeerIds: string[] = [],+ publicationGeneration = "publication_generation_12345678",): ParticipantRouteAssignment => ({upstream: { kind: "sfu" },childPeerIds,- sfuPublicationGeneration: null,+ sfuPublicationGeneration: publicationGeneration,});const hostAssignment = (@@ -80,7 +82,13 @@ const candidate = (childPeerId = "viewer_12345678",transport: "direct" | "sfu" = "direct",connectionId = `candidate_${revision}_12345678`,-) => ({ childPeerId, connectionId, transport });+ codecTransition: PreparedRouteCandidate["codecTransition"] = null,+): PreparedRouteCandidate => ({+ childPeerId,+ connectionId,+ transport,+ codecTransition,+});function createFakeSubscriber(events: SubscriberEvents, log: string[], label: string) {return {@@ -97,6 +105,12 @@ function createFakeSubscriber(events: SubscriberEvents, log: string[], label: stlog.push(`${label}:deactivate`);return true;}),+ armDecodedFrameProof: vi.fn((requireProgress = false) => {+ log.push(`${label}:proof:${requireProgress ? "progress" : "fresh"}`);+ }),+ stopDecodedFrameProof: vi.fn(() => {+ log.push(`${label}:proof:stop`);+ }),disconnect: vi.fn(async () => {log.push(`${label}:disconnect`);}),@@ -130,6 +144,38 @@ describe("minimal route transition contracts", () => {).toBe("stale");});+ it("treats the codec transaction tag as part of exact candidate identity", () => {+ const route = new MediaRouteTransition();+ const assignment = viewerSfuAssignment();+ const tagged = candidate(+ 2,+ "viewer_12345678",+ "sfu",+ "candidate_2_12345678",+ { generation: 7, videoCodec: "h264" },+ );++ expect(+ route.accept({+ revision: 2,+ phase: "prepare",+ assignment,+ candidate: tagged,+ }),+ ).toBe("accepted");+ expect(+ route.accept({+ revision: 2,+ phase: "prepare",+ assignment,+ candidate: {+ ...tagged,+ codecTransition: { generation: 8, videoCodec: "h264" },+ },+ }),+ ).toBe("stale");+ });+it("keeps duplicate peer prepare idempotent and releases it before takeover", async () => {const prepared: Array<{ parentPeerId: string | null; revision?: number }> = [];const activatePeer = vi.fn(() => true);@@ -290,6 +336,346 @@ describe("minimal route transition contracts", () => {expect(publishers[1]?.disconnect).not.toHaveBeenCalled();});+ it("prepares a fresh tagged SFU publisher while paused with the tagged codec", async () => {+ const messages: ClientMessage[] = [];+ const prepared: unknown[] = [];+ const publishers: ReturnType<typeof createFakePublisher>[] = [];+ const route = new HostSfuRoute({+ getStream: () => ({}) as MediaStream,+ getProfile: () => QUALITY_PROFILES["720p30"],+ reconcileChildren: () => undefined,+ send: (message) => {+ messages.push(message);+ return true;+ },+ onCodecPublisherPrepared: (result) => prepared.push(result),+ createPublisher: () => {+ const publisher = createFakePublisher([], "codec-publisher");+ publishers.push(publisher);+ return publisher;+ },+ });++ route.setPaused(true);+ route.accept({+ revision: 2,+ phase: "prepare",+ assignment: hostAssignment("ordinary-publication"),+ candidate: candidate(2, "viewer_12345678", "sfu"),+ });+ await route.acceptConfig(sfuConfig(2));+ expect(publishers).toEqual([]);++ route.accept({+ revision: 3,+ phase: "prepare",+ assignment: hostAssignment("fresh-publication"),+ candidate: candidate(+ 3,+ "viewer_12345678",+ "sfu",+ "candidate_3_12345678",+ { generation: 11, videoCodec: "h264" },+ ),+ });+ await route.acceptConfig(sfuConfig(3));++ expect(publishers).toHaveLength(1);+ expect(publishers[0]?.activate).toHaveBeenCalledWith(+ expect.anything(),+ { ...QUALITY_PROFILES["720p30"], videoCodec: "h264" },+ );+ expect(prepared).toEqual([+ {+ generation: 11,+ videoCodec: "h264",+ binding: {+ kind: "sfu",+ publicationGeneration: "fresh-publication",+ },+ accepted: true,+ },+ ]);+ expect(messages.filter((message) => message.type === "route-ready")).toEqual([]);+ });++ it("reports an exact rejected binding when fresh codec publication fails", async () => {+ const prepared: unknown[] = [];+ const route = new HostSfuRoute({+ getStream: () => ({}) as MediaStream,+ getProfile: () => QUALITY_PROFILES["720p30"],+ reconcileChildren: () => undefined,+ send: () => true,+ onCodecPublisherPrepared: (result) => prepared.push(result),+ createPublisher: () => ({+ ...createFakePublisher([], "failed-codec-publisher"),+ activate: vi.fn(async () => false),+ }),+ });++ route.setPaused(true);+ route.accept({+ revision: 5,+ phase: "prepare",+ assignment: hostAssignment("failed-publication"),+ candidate: candidate(+ 5,+ "viewer_12345678",+ "sfu",+ "candidate_5_12345678",+ { generation: 13, videoCodec: "vp8" },+ ),+ });+ await route.acceptConfig(sfuConfig(5));++ expect(prepared).toEqual([+ {+ generation: 13,+ videoCodec: "vp8",+ binding: {+ kind: "sfu",+ publicationGeneration: "failed-publication",+ },+ accepted: false,+ },+ ]);+ });++ it("reconciles paused Host active truth by exact SFU publication", async () => {+ let releaseOldPublisher!: () => void;+ const oldPublisherRetired = new Promise<void>((resolve) => {+ releaseOldPublisher = resolve;+ });+ const reconciledChildren: string[][] = [];+ const disconnectedCallbacks: Array<() => void> = [];+ const messages: ClientMessage[] = [];+ const publishers: ReturnType<typeof createFakePublisher>[] = [];+ const route = new HostSfuRoute({+ getStream: () => ({}) as MediaStream,+ getProfile: () => QUALITY_PROFILES["720p30"],+ reconcileChildren: (children) => reconciledChildren.push(children),+ send: (message) => {+ messages.push(message);+ return true;+ },+ createPublisher: (onDisconnected) => {+ disconnectedCallbacks.push(onDisconnected);+ const publisher = createFakePublisher(+ [],+ `publisher-${publishers.length + 1}`,+ );+ if (publishers.length === 0) {+ publisher.deactivate.mockImplementation(async () => {+ await oldPublisherRetired;+ return true;+ });+ publisher.disconnect.mockImplementation(async () => {+ onDisconnected();+ });+ }+ publishers.push(publisher);+ return publisher;+ },+ });++ await route.acceptAndWait({+ revision: 1,+ phase: "active",+ assignment: hostAssignment("publication-old"),+ });+ await route.acceptConfig(sfuConfig(1));+ route.setPaused(true);++ await route.acceptAndWait({+ revision: 2,+ phase: "active",+ assignment: hostAssignment("publication-old", ["retained-child"]),+ });+ expect(publishers[0]?.disconnect).not.toHaveBeenCalled();+ expect(reconciledChildren.at(-1)).toEqual(["retained-child"]);+ expect(+ route.accept({+ revision: 2,+ phase: "active",+ assignment: hostAssignment("publication-old", ["retained-child"]),+ }),+ ).toBe("duplicate");+ expect(publishers[0]?.disconnect).not.toHaveBeenCalled();++ const retiringOldPublication = route.acceptAndWait({+ revision: 3,+ phase: "active",+ assignment: hostAssignment(null, ["retained-child"]),+ });+ disconnectedCallbacks[0]?.();++ route.accept({+ revision: 4,+ phase: "prepare",+ assignment: hostAssignment("publication-fresh", ["retained-child"]),+ candidate: candidate(+ 4,+ "viewer_12345678",+ "sfu",+ "candidate_4_12345678",+ { generation: 15, videoCodec: "vp8" },+ ),+ });+ const freshPublication = route.acceptConfig(sfuConfig(4));+ await vi.waitFor(() => expect(publishers).toHaveLength(2));+ expect(publishers[1]?.connect).toHaveBeenCalledOnce();+ expect(publishers[1]?.activate).not.toHaveBeenCalled();+ releaseOldPublisher();+ await Promise.all([retiringOldPublication, freshPublication]);+ expect(publishers[0]?.disconnect).toHaveBeenCalledOnce();+ expect(publishers[1]?.activate).toHaveBeenCalledOnce();+ disconnectedCallbacks[0]?.();+ expect(+ messages.filter((message) => message.type === "route-failed"),+ ).toEqual([]);++ route.setPaused(false);+ await route.acceptAndWait({+ revision: 4,+ phase: "active",+ assignment: hostAssignment("publication-fresh", ["retained-child"]),+ });+ expect(publishers[1]?.disconnect).not.toHaveBeenCalled();+ });++ it("does not activate a fresh SFU publisher after its exact route becomes stale", async () => {+ let releaseOldPublisher!: () => void;+ const oldPublisherRetired = new Promise<void>((resolve) => {+ releaseOldPublisher = resolve;+ });+ const publishers: ReturnType<typeof createFakePublisher>[] = [];+ const route = new HostSfuRoute({+ getStream: () => ({}) as MediaStream,+ getProfile: () => QUALITY_PROFILES["720p30"],+ reconcileChildren: () => undefined,+ send: () => true,+ createPublisher: () => {+ const publisher = createFakePublisher(+ [],+ `publisher-${publishers.length + 1}`,+ );+ if (publishers.length === 0) {+ publisher.deactivate.mockImplementation(async () => {+ await oldPublisherRetired;+ return true;+ });+ }+ publishers.push(publisher);+ return publisher;+ },+ });++ await route.acceptAndWait({+ revision: 1,+ phase: "active",+ assignment: hostAssignment("publication-old"),+ });+ await route.acceptConfig(sfuConfig(1));+ route.setPaused(true);+ const retiringOldPublication = route.acceptAndWait({+ revision: 2,+ phase: "active",+ assignment: hostAssignment(null),+ });+ await vi.waitFor(() =>+ expect(publishers[0]?.deactivate).toHaveBeenCalledOnce(),+ );++ route.accept({+ revision: 3,+ phase: "prepare",+ assignment: hostAssignment("publication-fresh"),+ candidate: candidate(+ 3,+ "viewer_12345678",+ "sfu",+ "candidate_3_12345678",+ { generation: 17, videoCodec: "h264" },+ ),+ });+ const freshPublication = route.acceptConfig(sfuConfig(3));+ await vi.waitFor(() => expect(publishers).toHaveLength(2));+ expect(publishers[1]?.activate).not.toHaveBeenCalled();++ const stalePublication = route.acceptAndWait({+ revision: 4,+ phase: "active",+ assignment: hostAssignment(null),+ });+ releaseOldPublisher();+ await Promise.all([+ retiringOldPublication,+ freshPublication,+ stalePublication,+ ]);++ expect(publishers[1]?.activate).not.toHaveBeenCalled();+ expect(publishers[1]?.disconnect).toHaveBeenCalledOnce();+ });++ it("rejects a tagged codec candidate that reuses the active SFU publication", async () => {+ const messages: ClientMessage[] = [];+ const prepared: unknown[] = [];+ const publishers: ReturnType<typeof createFakePublisher>[] = [];+ const route = new HostSfuRoute({+ getStream: () => ({}) as MediaStream,+ getProfile: () => QUALITY_PROFILES["720p30"],+ reconcileChildren: () => undefined,+ send: (message) => {+ messages.push(message);+ return true;+ },+ onCodecPublisherPrepared: (result) => prepared.push(result),+ createPublisher: () => {+ const publisher = createFakePublisher([], "publisher");+ publishers.push(publisher);+ return publisher;+ },+ });++ await route.acceptAndWait({+ revision: 1,+ phase: "active",+ assignment: hostAssignment("publication-a"),+ });+ await route.acceptConfig(sfuConfig(1));+ route.setPaused(true);+ route.accept({+ revision: 2,+ phase: "prepare",+ assignment: hostAssignment("publication-a"),+ candidate: candidate(+ 2,+ "viewer_12345678",+ "sfu",+ "candidate_2_12345678",+ { generation: 14, videoCodec: "h264" },+ ),+ });+ await route.acceptConfig(sfuConfig(2));++ expect(publishers).toHaveLength(1);+ expect(prepared).toEqual([+ {+ generation: 14,+ videoCodec: "h264",+ binding: { kind: "sfu", publicationGeneration: "publication-a" },+ accepted: false,+ },+ ]);+ expect(messages.at(-1)).toEqual({+ type: "route-failed",+ revision: 2,+ phase: "prepare",+ connectionId: null,+ });+ });+it("uses the subscriber first decoded frame as the only SFU prepare ready", async () => {const log: string[] = [];const messages: ClientMessage[] = [];@@ -322,31 +708,25 @@ describe("minimal route transition contracts", () => {await route.acceptConfig(sfuConfig(1));const firstStream = {} as MediaStream;subscribers[0]?.events.onStream(firstStream);- subscribers[0]?.events.onStats?.({- intervalFramesDecoded: 1,- } as ConnectionMetrics);+ subscribers[0]?.events.onFirstDecodedFrame();await vi.waitFor(() => expect(streams).toEqual([firstStream]));route.accept({revision: 2,phase: "prepare",- assignment: viewerSfuAssignment(),+ assignment: viewerSfuAssignment([], "publication-generation-2"),candidate: candidate(2, "viewer_12345678", "sfu"),});await route.acceptConfig(sfuConfig(2));const pendingStream = {} as MediaStream;subscribers[1]?.events.onStream(pendingStream);subscribers[1]?.events.onStats?.({- intervalFramesDecoded: 0,+ intervalFramesDecoded: 2,} as ConnectionMetrics);expect(messages.filter((message) => message.type === "route-ready")).toEqual([]);- subscribers[1]?.events.onStats?.({- intervalFramesDecoded: 2,- } as ConnectionMetrics);- subscribers[1]?.events.onStats?.({- intervalFramesDecoded: 3,- } as ConnectionMetrics);+ subscribers[1]?.events.onFirstDecodedFrame();+ subscribers[1]?.events.onFirstDecodedFrame();expect(messages.filter((message) => message.type === "route-ready")).toEqual([{ type: "route-ready", revision: 2, phase: "prepare" },]);@@ -355,7 +735,7 @@ describe("minimal route transition contracts", () => {route.accept({revision: 2,phase: "active",- assignment: viewerSfuAssignment(),+ assignment: viewerSfuAssignment([], "publication-generation-2"),});await vi.waitFor(() => expect(streams).toEqual([firstStream, pendingStream]));expect(subscribers[0]?.deactivate).toHaveBeenCalledOnce();@@ -390,9 +770,177 @@ describe("minimal route transition contracts", () => {expect(subscriber.disconnect).toHaveBeenCalledOnce();subscriber.events.onStream({} as MediaStream);- subscriber.events.onStats?.({- intervalFramesDecoded: 4,- } as ConnectionMetrics);+ subscriber.events.onFirstDecodedFrame();expect(messages.filter((message) => message.type === "route-ready")).toEqual([]);});++ it("keeps a tagged SFU subscriber while paused and waits for a post-resume frame", async () => {+ const messages: ClientMessage[] = [];+ let subscriber!: ReturnType<typeof createFakeSubscriber>;+ const route = new ViewerSfuRoute("viewer_12345678", {+ activatePeer: () => true,+ reconcileSfuChildren: () => undefined,+ onSfuStream: () => undefined,+ send: (message) => {+ messages.push(message);+ return true;+ },+ createSubscriber: (events) => {+ subscriber = createFakeSubscriber(events, [], "codec-subscriber");+ return subscriber;+ },+ });++ route.setPaused(true);+ route.accept({+ revision: 4,+ phase: "prepare",+ assignment: viewerSfuAssignment([], "fresh-publication"),+ candidate: candidate(+ 4,+ "viewer_12345678",+ "sfu",+ "candidate_4_12345678",+ { generation: 12, videoCodec: "vp8" },+ ),+ });+ await route.acceptConfig(sfuConfig(4));+ expect(subscriber.connect).toHaveBeenCalledOnce();+ expect(subscriber.activate).toHaveBeenCalledOnce();+ expect(subscriber.armDecodedFrameProof).not.toHaveBeenCalled();++ subscriber.events.onStream({} as MediaStream);+ subscriber.events.onFirstDecodedFrame();+ expect(messages.filter((message) => message.type === "route-ready")).toEqual([]);++ route.setPaused(false);+ expect(subscriber.armDecodedFrameProof).toHaveBeenLastCalledWith(true);+ subscriber.events.onFirstDecodedFrame();+ expect(messages.filter((message) => message.type === "route-ready")).toEqual([+ { type: "route-ready", revision: 4, phase: "prepare" },+ ]);++ route.setPaused(true);+ expect(subscriber.stopDecodedFrameProof).toHaveBeenCalled();+ subscriber.events.onFirstDecodedFrame();+ route.setPaused(false);+ expect(subscriber.armDecodedFrameProof).toHaveBeenLastCalledWith(true);+ expect(messages.filter((message) => message.type === "route-ready")).toEqual([+ { type: "route-ready", revision: 4, phase: "prepare" },+ ]);+ subscriber.events.onFirstDecodedFrame();+ expect(messages.filter((message) => message.type === "route-ready")).toEqual([+ { type: "route-ready", revision: 4, phase: "prepare" },+ { type: "route-ready", revision: 4, phase: "prepare" },+ ]);+ });++ it("retires only an unreferenced paused Viewer SFU slot", async () => {+ const messages: ClientMessage[] = [];+ const activatedPeers: ParticipantRouteAssignment[] = [];+ const activatedChildren: string[][] = [];+ const streams: MediaStream[] = [];+ const subscribers: ReturnType<typeof createFakeSubscriber>[] = [];+ const route = new ViewerSfuRoute("viewer_12345678", {+ activatePeer: (assignment) => {+ activatedPeers.push(assignment);+ return true;+ },+ activateChildren: (children) => activatedChildren.push([...children]),+ onSfuStream: (stream) => streams.push(stream),+ send: (message) => {+ messages.push(message);+ return true;+ },+ createSubscriber: (events) => {+ const subscriber = createFakeSubscriber(+ events,+ [],+ `subscriber-${subscribers.length + 1}`,+ );+ subscribers.push(subscriber);+ return subscriber;+ },+ });++ route.accept({+ revision: 1,+ phase: "active",+ assignment: viewerSfuAssignment([], "publication-old"),+ });+ await route.acceptConfig(sfuConfig(1));+ const oldStream = {} as MediaStream;+ subscribers[0]?.events.onStream(oldStream);+ subscribers[0]?.events.onFirstDecodedFrame();+ await vi.waitFor(() => expect(streams).toEqual([oldStream]));+ route.setPaused(true);++ route.accept({+ revision: 2,+ phase: "active",+ assignment: viewerSfuAssignment(+ ["retained-child"],+ "publication-old",+ ),+ });+ await vi.waitFor(() =>+ expect(activatedChildren.at(-1)).toEqual(["retained-child"]),+ );+ expect(subscribers[0]?.disconnect).not.toHaveBeenCalled();+ expect(+ route.accept({+ revision: 2,+ phase: "active",+ assignment: viewerSfuAssignment(+ ["retained-child"],+ "publication-old",+ ),+ }),+ ).toBe("duplicate");+ expect(subscribers[0]?.disconnect).not.toHaveBeenCalled();++ route.accept({+ revision: 3,+ phase: "active",+ assignment: peerAssignment("retained-parent", ["retained-child"]),+ });+ await vi.waitFor(() =>+ expect(subscribers[0]?.disconnect).toHaveBeenCalledOnce(),+ );+ expect(activatedPeers.at(-1)).toEqual(+ peerAssignment("retained-parent", ["retained-child"]),+ );++ route.accept({+ revision: 4,+ phase: "prepare",+ assignment: viewerSfuAssignment(+ ["retained-child"],+ "publication-fresh",+ ),+ candidate: candidate(+ 4,+ "viewer_12345678",+ "sfu",+ "candidate_4_12345678",+ { generation: 16, videoCodec: "h264" },+ ),+ });+ await route.acceptConfig(sfuConfig(4));+ subscribers[0]?.events.onDisconnected();+ subscribers[1]?.events.onStream({} as MediaStream);+ subscribers[1]?.events.onFirstDecodedFrame();+ expect(messages.filter((message) => message.type === "route-ready")).toEqual([]);+ expect(+ messages.filter((message) => message.type === "route-failed"),+ ).toEqual([]);++ route.setPaused(false);+ expect(subscribers[1]?.armDecodedFrameProof).toHaveBeenLastCalledWith(true);+ subscribers[1]?.events.onFirstDecodedFrame();+ expect(messages.filter((message) => message.type === "route-ready")).toEqual([+ { type: "route-ready", revision: 4, phase: "prepare" },+ ]);+ expect(subscribers[1]?.disconnect).not.toHaveBeenCalled();+ });});diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.tsindex 8ee0c76c..3818853f 100644--- a/tests/server-signal.test.ts+++ b/tests/server-signal.test.ts@@ -1355,6 +1355,7 @@ describe("WebSocket signaling", () => {payload: {kind: "description",connectionId: "persistence-failure-edge",+ negotiationGeneration: null,description: { type: "offer", sdp: "v=0\r\n" },},}),@@ -1494,11 +1495,31 @@ describe("WebSocket signaling", () => {activeHost.socket.send(JSON.stringify({- type: "set-sharing-paused",+ type: "request-sharing-resume",+ shareGeneration,+ }),+ );+ const resumeAuthorization = await activeHost.inbox.next(+ "sharing-resume-authorized",+ );+ expect(resumeAuthorization).toMatchObject({+ shareGeneration,+ codecGeneration: null,+ resumeAttempt: expect.any(Number),+ });+ await replacement.inbox.expectNone(20);+ activeHost.socket.send(+ JSON.stringify({+ type: "sharing-source-enabled",shareGeneration,- paused: false,+ codecGeneration: null,+ resumeAttempt: resumeAuthorization.resumeAttempt,}),);+ expect(await activeHost.inbox.next("host-status")).toMatchObject({+ online: true,+ paused: false,+ });expect(await replacement.inbox.next("host-status")).toMatchObject({online: true,paused: false,@@ -1543,6 +1564,192 @@ describe("WebSocket signaling", () => {});});+ it("keeps ordinary P2P Resume paused until the exact source ack", async () => {+ const harness = await startHarness({ peerAssistedMedia: false });+ const shareGeneration = "ordinary_resume_share_generation_12345678";+ const host = await openClient(harness.webSocketUrl);+ await authenticate(+ host,+ harness.room,+ "host",+ "ordinary-resume-host-client",+ 1,+ shareGeneration,+ );+ const viewer = await openClient(harness.webSocketUrl);+ await authenticate(+ viewer,+ harness.room,+ "viewer",+ "ordinary-resume-viewer-client",+ );+ await host.inbox.next("peer-joined");++ const pause = {+ type: "set-sharing-paused",+ shareGeneration,+ paused: true,+ };+ host.socket.send(JSON.stringify(pause));+ expect(await viewer.inbox.next("host-status")).toMatchObject({+ paused: true,+ });+ host.socket.send(+ JSON.stringify({ type: "request-sharing-resume", shareGeneration }),+ );+ const first = await host.inbox.next("sharing-resume-authorized");+ await viewer.inbox.expectNone(20);++ host.socket.send(JSON.stringify(pause));+ expect(await viewer.inbox.next("host-status")).toMatchObject({+ paused: true,+ });+ host.socket.send(+ JSON.stringify({ type: "request-sharing-resume", shareGeneration }),+ );+ const second = await host.inbox.next("sharing-resume-authorized");+ expect(second.resumeAttempt).toBeGreaterThan(first.resumeAttempt);++ host.socket.send(+ JSON.stringify({+ type: "sharing-source-enabled",+ shareGeneration,+ codecGeneration: null,+ resumeAttempt: first.resumeAttempt,+ }),+ );+ expect(await host.inbox.next("pause-sharing-source")).toMatchObject({+ shareGeneration,+ codecGeneration: null,+ resumeAttempt: first.resumeAttempt,+ });+ await viewer.inbox.expectNone(20);++ host.socket.send(+ JSON.stringify({+ type: "sharing-source-enabled",+ shareGeneration,+ codecGeneration: null,+ resumeAttempt: second.resumeAttempt,+ }),+ );+ expect(await host.inbox.next("host-status")).toMatchObject({+ online: true,+ paused: false,+ });+ expect(await viewer.inbox.next("host-status")).toMatchObject({+ online: true,+ paused: false,+ });+ host.socket.send(+ JSON.stringify({+ type: "sharing-source-enabled",+ shareGeneration,+ codecGeneration: null,+ resumeAttempt: first.resumeAttempt,+ }),+ );+ await Promise.all([+ host.inbox.expectNone(20),+ viewer.inbox.expectNone(20),+ ]);+ });++ it("retains authoritative pause when a Resume ack is lost across Host reconnect", async () => {+ const harness = await startHarness({ peerAssistedMedia: false });+ const shareGeneration = "reconnect_resume_share_generation_12345678";+ const hostClientId = "reconnect-resume-host-client";+ const host = await openClient(harness.webSocketUrl);+ await authenticate(+ host,+ harness.room,+ "host",+ hostClientId,+ 1,+ shareGeneration,+ );+ const viewer = await openClient(harness.webSocketUrl);+ await authenticate(+ viewer,+ harness.room,+ "viewer",+ "reconnect-resume-viewer-client",+ );+ await host.inbox.next("peer-joined");++ host.socket.send(+ JSON.stringify({+ type: "set-sharing-paused",+ shareGeneration,+ paused: true,+ }),+ );+ expect(await viewer.inbox.next("host-status")).toMatchObject({+ online: true,+ paused: true,+ });+ host.socket.send(+ JSON.stringify({ type: "request-sharing-resume", shareGeneration }),+ );+ const lostAuthorization = await host.inbox.next(+ "sharing-resume-authorized",+ );++ await closeClient(host);+ expect(await viewer.inbox.next("host-status")).toMatchObject({+ online: false,+ paused: false,+ });++ const reconnectedHost = await openClient(harness.webSocketUrl);+ await authenticate(+ reconnectedHost,+ harness.room,+ "host",+ hostClientId,+ 1,+ shareGeneration,+ { sharingPaused: false },+ );+ expect(+ await reconnectedHost.inbox.next("pause-sharing-source"),+ ).toMatchObject({+ shareGeneration,+ codecGeneration: null,+ resumeAttempt: null,+ });+ expect(await viewer.inbox.next("host-status")).toMatchObject({+ online: true,+ paused: true,+ });++ reconnectedHost.socket.send(+ JSON.stringify({ type: "request-sharing-resume", shareGeneration }),+ );+ const retryAuthorization = await reconnectedHost.inbox.next(+ "sharing-resume-authorized",+ );+ expect(retryAuthorization.resumeAttempt).toBeGreaterThan(+ lostAuthorization.resumeAttempt,+ );+ reconnectedHost.socket.send(+ JSON.stringify({+ type: "sharing-source-enabled",+ shareGeneration,+ codecGeneration: null,+ resumeAttempt: retryAuthorization.resumeAttempt,+ }),+ );+ expect(await reconnectedHost.inbox.next("host-status")).toMatchObject({+ online: true,+ paused: false,+ });+ expect(await viewer.inbox.next("host-status")).toMatchObject({+ online: true,+ paused: false,+ });+ });+it("keeps a viewer peer stable when it reconnects inside the grace period", async () => {const harness = await startHarness({ viewerDisconnectGraceMs: 80 });const host = await openClient(harness.webSocketUrl);@@ -1562,6 +1769,7 @@ describe("WebSocket signaling", () => {payload: {kind: "description",connectionId: "stable-connection",+ negotiationGeneration: null,description: { type: "offer", sdp: "v=0\r\n" },},}),@@ -1675,6 +1883,7 @@ describe("WebSocket signaling", () => {payload: {kind: "description",connectionId: "waiting-host-offer",+ negotiationGeneration: null,description: { type: "offer", sdp: "v=0\r\n" },},}),@@ -1701,6 +1910,7 @@ describe("WebSocket signaling", () => {payload: {kind: "description",connectionId: "waiting-viewer-answer",+ negotiationGeneration: null,description: { type: "answer", sdp: "v=0\r\n" },},}),@@ -1735,6 +1945,7 @@ describe("WebSocket signaling", () => {payload: {kind: "description",connectionId: "active-host-offer",+ negotiationGeneration: null,description: { type: "offer", sdp: "v=0\r\n" },},}),@@ -1838,6 +2049,7 @@ describe("WebSocket signaling", () => {payload: {kind: "description",connectionId: "promoted-host-offer",+ negotiationGeneration: null,description: { type: "offer", sdp: "v=0\r\n" },},}),@@ -1869,6 +2081,7 @@ describe("WebSocket signaling", () => {payload: {kind: "description",connectionId: "connection-before-stop",+ negotiationGeneration: null,description: { type: "offer", sdp: "v=0\r\n" },},}),@@ -2012,6 +2225,7 @@ describe("WebSocket signaling", () => {payload: {kind: "description",connectionId: "connection-before-control-outage",+ negotiationGeneration: null,description: { type: "offer", sdp: "v=0\r\n" },},}),@@ -2121,6 +2335,7 @@ describe("WebSocket signaling", () => {payload: {kind: "description",connectionId: "connection-during-grace",+ negotiationGeneration: null,description: { type: "offer", sdp: "v=0\r\n" },},}),@@ -2283,9 +2498,13 @@ describe("WebSocket signaling", () => {expect(status).toBe(403);const unauthenticated = await openClient(harness.webSocketUrl);+ const unauthenticatedClosed = new Promise<number>((resolve) =>+ unauthenticated.socket.once("close", (code) => resolve(code)),+ );expect((await unauthenticated.inbox.next("error", 300)).code).toBe("AUTH_REQUIRED",);+ expect(await unauthenticatedClosed).toBe(4003);const oversized = await openClient(harness.webSocketUrl);const closeCode = new Promise<number>((resolve) =>diff --git a/tests/sfu-client.test.ts b/tests/sfu-client.test.tsindex b59f6bd5..a8ddec3e 100644--- a/tests/sfu-client.test.ts+++ b/tests/sfu-client.test.ts@@ -1046,7 +1046,8 @@ describe("SfuPublisher", () => {maxFramerate: 60,degradationPreference: "maintain-resolution",});- expect(publisher.getQualityWarning()).toContain("preference save failed");+ expect(publisher.getQualityWarning()).toContain("应用 SFU 发送参数失败");+ expect(publisher.getQualityWarning()).not.toContain("preference save failed");});it("does not retain an update from a disconnected publisher generation", async () => {@@ -1196,9 +1197,8 @@ describe("SfuPublisher", () => {}),],});- expect(publisher.getQualityWarning()).toBe(- "应用 SFU 发送参数失败:unsupported",- );+ expect(publisher.getQualityWarning()).toBe("应用 SFU 发送参数失败");+ expect(publisher.getQualityWarning()).not.toContain("unsupported");});it("retains a LOW rewrite warning after rolling back sender parameters", async () => {@@ -1234,9 +1234,8 @@ describe("SfuPublisher", () => {applied: { maxBitrate: 8_000_000 },mismatches: [],});- expect(publisher.getQualityWarning()).toContain(- "应用 SFU 发送参数失败:unsupported",- );+ expect(publisher.getQualityWarning()).toContain("应用 SFU 发送参数失败");+ expect(publisher.getQualityWarning()).not.toContain("unsupported");expect(publisher.getQualityWarning()).toContain("低档表示");expect(publisher.getQualityWarning()).toContain("码率上限");});@@ -1318,8 +1317,9 @@ describe("SfuPublisher", () => {expect(localTrack.currentTrack).toBe(previousVideo);expect(localTrack.sender.setParameters).toHaveBeenCalledTimes(3);expect(publisher.getSenderParameters()?.applied.maxBitrate).toBe(8_000_000);- expect(publisher.getQualityWarning()).toBe(- "切换 SFU 分享来源失败:replacement parameters rejected",+ expect(publisher.getQualityWarning()).toBe("切换 SFU 分享来源失败");+ expect(publisher.getQualityWarning()).not.toContain(+ "replacement parameters rejected",);});@@ -1360,6 +1360,63 @@ describe("SfuPublisher", () => {});describe("SfuSubscriber", () => {+ it("uses cumulative frames for a fresh exact subscriber and growth after rearm", async () => {+ vi.useFakeTimers();+ let framesDecoded = 1;+ const proofs: number[] = [];+ const subscriber = new SfuSubscriber({+ onStream: vi.fn(),+ onFirstDecodedFrame: () => {+ proofs.push(framesDecoded);+ return true;+ },+ });+ 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);+ expect(subscriber.activate()).toBe(true);+ subscriber.armDecodedFrameProof();+ const video = track("video", "video-1");+ room.emit(+ RoomEvent.TrackSubscribed,+ remoteTrack(video, () =>+ statsReport([+ {+ id: "video-in",+ type: "inbound-rtp",+ timestamp: 1_000,+ kind: "video",+ framesDecoded,+ },+ ]),+ ),+ publication,+ host,+ );+ await vi.waitFor(() => expect(proofs).toEqual([1]));++ proofs.length = 0;+ framesDecoded = 7;+ subscriber.armDecodedFrameProof(true);+ await Promise.resolve();+ await vi.advanceTimersByTimeAsync(100);+ expect(proofs).toEqual([]);+ framesDecoded = 8;+ await vi.advanceTimersByTimeAsync(300);+ expect(proofs).toEqual([8]);++ subscriber.deactivate();+ framesDecoded = 9;+ await vi.advanceTimersByTimeAsync(500);+ expect(proofs).toEqual([8]);+ });+it("reconciles a Host publication announced while connect is pending", async () => {const gate = deferred();livekit.state.connectGate = gate.promise;diff --git a/tests/sfu-resource-admission.test.ts b/tests/sfu-resource-admission.test.tsindex f367ef47..6cff73b6 100644--- a/tests/sfu-resource-admission.test.ts+++ b/tests/sfu-resource-admission.test.ts@@ -131,7 +131,7 @@ describe("SfuResourceAdmission", () => {expect(admission.usage()).toEqual({ ingress: 1, egress: 2 });});- it("refunds a new reserved subscription when its candidate aborts", () => {+ it("keeps a released reserved subscription charged until publication absence", () => {const admission = new SfuResourceAdmission({ingressCapacity: 1,egressCapacity: 2,@@ -146,9 +146,15 @@ describe("SfuResourceAdmission", () => {expect(admission.reserveSubscription(candidate)).toBe(true);expect(admission.usage()).toEqual({ ingress: 1, egress: 2 });expect(admission.releaseSubscription(candidate)).toBe(true);- expect(admission.releaseSubscription(candidate)).toBe(false);+ expect(admission.releaseSubscription(candidate)).toBe(true);expect(admission.commitSubscription(candidate)).toBe(false);- expect(admission.usage()).toEqual({ ingress: 1, egress: 1 });+ expect(admission.usage()).toEqual({ ingress: 1, egress: 2 });+ expect(+ admission.reserveSubscription(subscription(active, "viewer_c")),+ ).toBe(false);+ expect(admission.beginDrain(active)).toBe(true);+ expect(admission.completeDrain(active)).toBe(true);+ expect(admission.usage()).toEqual({ ingress: 0, egress: 0 });});it("reactivates a draining subscription in the current generation without double charging", () => {diff --git a/tests/stage-entry-actions.test.ts b/tests/stage-entry-actions.test.tsindex 3744fbdf..5e64fa6e 100644--- a/tests/stage-entry-actions.test.ts+++ b/tests/stage-entry-actions.test.ts@@ -32,6 +32,7 @@ describe("Host stage entry layout", () => {const row = open.match(/<div class="entry-actions">([\s\S]*?)<\/div>/)?.[1];expect(row).toContain("开始分享");expect(row).toContain("加入房间");+ expect(open).toContain('title="输入房间号加入观看"');expect(row).not.toContain('class="room-code-entry');expect(row).not.toContain("<form");expect(open).toContain('aria-expanded="true"');@@ -47,7 +48,10 @@ describe("Host stage entry layout", () => {/\.entry-actions\s*\{[\s\S]*?grid-template-columns:\s*minmax\(0, 1fr\) 24px minmax\(0, 1fr\);[\s\S]*?width:\s*min\(520px, calc\(100% - 20px\)\);/,);expect(css).toMatch(- /\.entry-action\s*\{[\s\S]*?min-height:\s*44px;/,+ /\.stage-entry\s*\{[\s\S]*?grid-template-columns:\s*minmax\(0, 1fr\);[\s\S]*?grid-template-rows:\s*minmax\(0, 1fr\) 44px minmax\(0, 1fr\);/,+ );+ expect(css).toMatch(+ /\.entry-action\s*\{[\s\S]*?height:\s*44px;[\s\S]*?min-height:\s*44px;/,);expect(css).toMatch(/\.room-code-entry\.is-inline\s*\{[\s\S]*?width:\s*min\(520px, calc\(100% - 20px\)\);[\s\S]*?grid-template-columns:\s*minmax\(0, 1fr\) 44px;/,diff --git a/tests/stats-grid.test.ts b/tests/stats-grid.test.tsindex fe7395cd..e700049b 100644--- a/tests/stats-grid.test.ts+++ b/tests/stats-grid.test.ts@@ -104,6 +104,21 @@ describe("StatsGrid progressive disclosure", () => {expect(html).not.toContain("aria-expanded");});+ it("does not expose an unknown browser quality-limitation value", () => {+ const html = renderToStaticMarkup(+ createElement(StatsGrid, {+ metrics: {+ ...metrics,+ qualityLimitationReason: "browser-internal-sentinel",+ },+ direction: "send",+ }),+ );++ expect(html).toContain("未分类限制");+ expect(html).not.toContain("browser-internal-sentinel");+ });+it("shows local inbound playout and repair evidence only for receivers", () => {const receiverMetrics = {...metrics,diff --git a/tests/viewer-peer-generation.test.ts b/tests/viewer-peer-generation.test.tsindex e3d4001b..67628573 100644--- a/tests/viewer-peer-generation.test.ts+++ b/tests/viewer-peer-generation.test.ts@@ -34,6 +34,7 @@ interface ConnectionPlan {answerError?: Error;candidateGates?: Promise<void>[];localDescriptionGate?: Promise<void>;+ statsGate?: Promise<RTCStatsReport>;}class FakeMediaStream {@@ -46,6 +47,10 @@ class FakeMediaStream {addTrack(track: MediaStreamTrack): void {this.tracks.push(track);}++ getVideoTracks(): MediaStreamTrack[] {+ return this.tracks.filter((track) => track.kind === "video");+ }}class FakePeerConnection extends EventTarget {@@ -93,14 +98,15 @@ class FakePeerConnection extends EventTarget {this.candidateGates = [...(plan.candidateGates ?? [])];this.localDescriptionGate = plan.localDescriptionGate ?? null;this.answerError = plan.answerError ?? null;+ this.statsGate = plan.statsGate ?? null;FakePeerConnection.instances.push(this);}- async setRemoteDescription(- description: RTCSessionDescriptionInit,- ): Promise<void> {- this.remoteDescription = description as RTCSessionDescription;- }+ readonly setRemoteDescription = vi.fn(+ async (description: RTCSessionDescriptionInit): Promise<void> => {+ this.remoteDescription = description as RTCSessionDescription;+ },+ );async createAnswer(): Promise<RTCSessionDescriptionInit> {if (this.answerError) {@@ -127,10 +133,14 @@ const timeoutCallbacks = new Map<number, () => void>();const timeoutDelays = new Map<number, number>();let nextTimeoutId = 1;-function offer(connectionId: string): SignalPayload {+function offer(+ connectionId: string,+ negotiationGeneration: number | null = null,+): SignalPayload {return {kind: "description",connectionId,+ negotiationGeneration,description: { type: "offer", sdp: `offer-${connectionId}` },};}@@ -147,6 +157,21 @@ function candidate(connectionId: string, value: string): SignalPayload {};}+function decodedReport(framesDecoded: number): RTCStatsReport {+ return new Map([+ [+ "video-in",+ {+ id: "video-in",+ type: "inbound-rtp",+ timestamp: 1_000,+ kind: "video",+ framesDecoded,+ },+ ],+ ]) as unknown as RTCStatsReport;+}+function createPeer(signals: SignalPayload[],snapshots: PeerSnapshot[],@@ -207,6 +232,57 @@ afterEach(() => {});describe("ViewerPeer connection generations", () => {+ it("proves a fresh exact connection from its first cumulative decoded frame", async () => {+ FakePeerConnection.plans.push({+ statsGate: Promise.resolve(decodedReport(1)),+ });+ const decoded = vi.fn(() => true);+ const peer = new ViewerPeer(+ { iceServers: [] },+ {+ sendSignal: () => true,+ sendRestartRequest: () => true,+ onStream: () => undefined,+ onUpdate: () => undefined,+ onFirstDecodedFrame: decoded,+ },+ );++ await peer.acceptSignal("host", offer("fresh-exact"));+ await flushAsyncWork();++ expect(decoded).toHaveBeenCalledOnce();+ expect(decoded).toHaveBeenCalledWith("fresh-exact");+ peer.dispose();+ });++ it("does not publish an in-flight decoded proof from a replaced connection", async () => {+ const oldStats = createDeferred<RTCStatsReport>();+ FakePeerConnection.plans.push(+ { statsGate: oldStats.promise },+ { statsGate: Promise.resolve(new Map() as unknown as RTCStatsReport) },+ );+ const decoded = vi.fn(() => true);+ const peer = new ViewerPeer(+ { iceServers: [] },+ {+ sendSignal: () => true,+ sendRestartRequest: () => true,+ onStream: () => undefined,+ onUpdate: () => undefined,+ onFirstDecodedFrame: decoded,+ },+ );++ await peer.acceptSignal("host-a", offer("old-exact"));+ await peer.acceptSignal("host-b", offer("new-exact"));+ oldStats.resolve(decodedReport(3));+ await flushAsyncWork();++ expect(decoded).not.toHaveBeenCalled();+ peer.dispose();+ });+it("sets and signals stereo audio bitrate for every answer", async () => {const signals: SignalPayload[] = [];const peer = createPeer(signals, []);@@ -590,6 +666,50 @@ describe("ViewerPeer connection generations", () => {});});+ it("serializes same-connection codec offers and fences stale generations", async () => {+ const firstLocalDescription = createDeferred<void>();+ FakePeerConnection.plans.push({+ localDescriptionGate: firstLocalDescription.promise,+ });+ const signals: SignalPayload[] = [];+ const peer = createPeer(signals, []);++ const first = peer.acceptSignal("host", offer("codec-connection", 5));+ await vi.waitFor(() =>+ expect(+ FakePeerConnection.instances[0]?.setLocalDescription,+ ).toHaveBeenCalledOnce(),+ );+ const connection = FakePeerConnection.instances[0]!;+ const replacement = peer.acceptSignal(+ "host",+ offer("codec-connection", 6),+ );+ await peer.acceptSignal("host", offer("codec-connection", 6));+ await Promise.resolve();+ expect(connection.setRemoteDescription).toHaveBeenCalledOnce();++ firstLocalDescription.resolve();+ await Promise.all([first, replacement]);+ expect(+ signals+ .filter((signal) => signal.kind === "description")+ .map((signal) => signal.negotiationGeneration),+ ).toEqual([6]);+ expect(connection.setRemoteDescription).toHaveBeenCalledTimes(2);++ await peer.acceptSignal("host", offer("codec-connection"));+ expect(+ signals+ .filter((signal) => signal.kind === "description")+ .map((signal) => signal.negotiationGeneration),+ ).toEqual([6, null]);+ expect(connection.setRemoteDescription).toHaveBeenCalledTimes(3);++ await peer.acceptSignal("host", offer("codec-connection", 5));+ expect(connection.setRemoteDescription).toHaveBeenCalledTimes(3);+ });+it("stops flushing old candidates when the connection is replaced", async () => {const firstCandidate = createDeferred<void>();FakePeerConnection.plans.push({diff --git a/tests/viewer-presentation.test.ts b/tests/viewer-presentation.test.tsindex 52253d35..520b8cb7 100644--- a/tests/viewer-presentation.test.ts+++ b/tests/viewer-presentation.test.ts@@ -98,6 +98,64 @@ describe("Viewer presentation reducer", () => {expect(deriveViewerPresentation(staleFailure).stage).toBe("receiving");});+ it("ignores late playback results from a retained older route revision", () => {+ const oldMedia = apply(+ { type: "access", access: "ready" },+ { type: "host", host: "online" },+ { type: "route", revision: 5, phase: "active", kind: "p2p" },+ { type: "media-bound", generation: 5, revision: 5 },+ { type: "frame-presented", generation: 5, revision: 5 },+ );+ const preparing = reduceViewerPresentation(oldMedia, {+ type: "route",+ revision: 6,+ phase: "prepare",+ kind: "sfu",+ });++ const staleAutoplay = reduceViewerPresentation(preparing, {+ type: "autoplay-blocked",+ generation: 5,+ revision: 5,+ });+ const staleFailure = reduceViewerPresentation(preparing, {+ type: "playback-failed",+ generation: 5,+ revision: 5,+ });++ expect(staleAutoplay).toBe(preparing);+ expect(staleFailure).toBe(preparing);+ expect(deriveViewerPresentation(preparing)).toMatchObject({+ stage: "preparing-sfu",+ overlay: "status",+ showPlay: false,+ });+ });++ it("clears autoplay authority when the route revision advances", () => {+ const blocked = apply(+ { type: "access", access: "ready" },+ { type: "host", host: "online" },+ { type: "route", revision: 5, phase: "active", kind: "p2p" },+ { type: "media-bound", generation: 5, revision: 5 },+ { type: "autoplay-blocked", generation: 5, revision: 5 },+ );+ const preparing = reduceViewerPresentation(blocked, {+ type: "route",+ revision: 6,+ phase: "prepare",+ kind: "sfu",+ });++ expect(preparing.autoplayBlockedGeneration).toBeNull();+ expect(preparing.failure).toBeNull();+ expect(deriveViewerPresentation(preparing)).toMatchObject({+ stage: "preparing-sfu",+ showPlay: false,+ });+ });+it("keeps a proven old frame through recovery without accepting stale proof", () => {const oldFrame = apply({ type: "access", access: "ready" },@@ -160,6 +218,67 @@ describe("Viewer presentation reducer", () => {});});+ it("keeps a healthy Host-offline frame but invalidates it on upstream failure", () => {+ const offlineWithMedia = apply(+ { type: "access", access: "ready" },+ { type: "signal", signal: "connected" },+ { type: "host", host: "online" },+ { type: "route", revision: 3, phase: "active", kind: "p2p" },+ { type: "media-bound", generation: 2, revision: 3 },+ { type: "frame-presented", generation: 2, revision: 3 },+ { type: "host", host: "offline" },+ );+ expect(deriveViewerPresentation(offlineWithMedia)).toMatchObject({+ stage: "playing",+ overlay: "none",+ hasCurrentFrame: true,+ notice: "分享者连接已中断,画面仍然可用",+ });+ expect(+ reduceViewerPresentation(offlineWithMedia, {+ type: "media-invalidated",+ revision: 2,+ }),+ ).toBe(offlineWithMedia);++ const failed = reduceViewerPresentation(offlineWithMedia, {+ type: "media-invalidated",+ revision: 3,+ });+ expect(deriveViewerPresentation(failed)).toMatchObject({+ stage: "host-offline",+ overlay: "status",+ hasCurrentFrame: false,+ hasRetainedFrame: true,+ failureCode: "HOST_OFFLINE",+ });+ });++ it("demotes the current frame when an exact route terminally fails", () => {+ const playing = apply(+ { type: "access", access: "ready" },+ { type: "signal", signal: "connected" },+ { type: "host", host: "online" },+ { type: "route", revision: 4, phase: "active", kind: "sfu" },+ { type: "media-bound", generation: 3, revision: 4 },+ { type: "frame-presented", generation: 3, revision: 4 },+ );+ const failed = reduceViewerPresentation(playing, {+ type: "route-status",+ revision: 4,+ state: "failed",+ });++ expect(deriveViewerPresentation(failed)).toMatchObject({+ stage: "route-failed",+ message: "没有可用的媒体线路",+ overlay: "status",+ hasCurrentFrame: false,+ hasRetainedFrame: true,+ failureCode: "ROUTE_EXHAUSTED",+ });+ });+it("honors terminal access, Host pause, and typed route status priority", () => {const paused = apply({ type: "access", access: "ready" },