Skip to content

armgit / Piik

Public Imported from GitHub
0

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

feat(route): implement native-edge topology convergence (#299)

AAA71de09403336
diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.md
index b6c737c9..4916eb4d 100644
--- a/docs/adr/0005-automatic-hybrid-media-routing.md
+++ b/docs/adr/0005-automatic-hybrid-media-routing.md
@@ -1,6 +1,6 @@
# ADR-0005: Automatic Hybrid Media Routing
-- Status: accepted; base route and quality shadow deployed; native-edge convergence not implemented
+- Status: accepted; native-edge convergence implemented in source, not yet deployed
- Date: 2026-08-20
- Last updated: 2026-08-27
@@ -177,11 +177,11 @@ the committed graph, suppresses decoded-stall authority, and leaves new Viewers
waiting. Resume starts reconciliation from the current graph. Page-hidden wall
time is rebaselined before it can contribute to a stall decision.
-Deployed quality evidence remains observation-only. The accepted next slice is
-continuous local convergence inside the same graph, reconcile loop, and
-room-serial child operation. Availability first gets every Viewer usable media;
-quality work runs only while no join, failure, pause, identity, departure,
-capacity, or SFU-resource work needs that operation.
+Native-edge convergence runs inside the same graph, reconcile loop, and
+room-serial child operation when its per-share gate is enabled. Availability
+first gets every Viewer usable media; quality work runs only while no join,
+failure, pause, identity, departure, capacity, or SFU-resource work needs that
+operation. With the gate disabled, quality evidence remains observation-only.
Each exact current or pending edge has one native state: `unknown`, `healthy`, or
`degraded`. For ordinary P2P, the parent reports the exact outbound sender's
diff --git a/docs/product/routing-transport.md b/docs/product/routing-transport.md
index c79064cf..827316bf 100644
--- a/docs/product/routing-transport.md
+++ b/docs/product/routing-transport.md
@@ -89,11 +89,13 @@ credentials cannot recreate off-ledger media. ADR-0005 owns that lifecycle.
## Quality And Privacy Boundaries
WebRTC and LiveKit own ICE, consent, congestion control, bitrate, frame rate,
-resolution, retransmission, reconnect, and SFU layer selection. Current route
-quality is diagnostic: Screener has no weighted route score, parent-wide quality
-inference, all-pairs probe, periodic rebalance, persistent parent blacklist, NAT
-classification, or independent depth cap. Open quality work remains in the
-[TODO ledger](../todo.md).
+resolution, retransmission, reconnect, and SFU layer selection. When the
+per-share convergence gate is enabled, Screener uses their exact categorical
+edge state only to move one degraded local edge through the existing serial
+operation; disabling the gate leaves that state diagnostic. Screener has no
+weighted route score, parent-wide quality inference, all-pairs probe, periodic
+rebalance, persistent parent blacklist, NAT classification, or independent
+depth cap.
Direct P2P exposes endpoint network addresses to the trusted peer. SFU media is
encrypted hop-by-hop with DTLS-SRTP but terminates at the SFU; the product does
diff --git a/docs/project-memory.md b/docs/project-memory.md
index 991d68c6..c48ac9f7 100644
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@ -38,11 +38,10 @@ implementation and routine UI detail.
one serial child operation. First decoded frame commits availability work;
accepted quality work adds native edge proof before commit in that operation.
- WebRTC and LiveKit own congestion control, media adaptation, reconnect, and SFU
- layers. Current source keeps route quality diagnostic. The accepted next slice
- is event-driven local topology convergence from their native edge state, with
- bounded SFU only after healthy Peer escape fails. Its initial per-share gate is
- opt-in; no weighted score, all-pairs probe, parent-wide prediction, or periodic
- rebalance is accepted.
+ layers. Current source implements opt-in, event-driven local topology
+ convergence from their native edge state, with bounded SFU only after healthy
+ Peer escape fails. No weighted score, all-pairs probe, parent-wide prediction,
+ or periodic rebalance is accepted.
- Browser video uses `motion`; each share chooses H.264 with VP8 fallback through
an actual sender probe unless the Host explicitly selects VP8 or H264. Screen
audio uses 64/128/192 kbps ceilings with 128 default.
@@ -52,10 +51,12 @@ implementation and routine UI detail.
## Current Snapshot
-Canonical source and production use the strict `screener-v13` Browser/server
-contract, optional SQLite room authority, the H.264/VP8 sender gate, and the
-evidence-only quality shadow. [Status](./status.md) is the sole owner of exact
-source, artifact, deployment, milestone, and blocker identity.
+Canonical source uses the strict `screener-v14` Browser/server contract with the
+opt-in native-edge convergence controller. Production remains on
+`screener-v13` until the current application release completes. Both retain
+optional SQLite room authority and the H.264/VP8 sender gate. [Status](./status.md)
+is the sole owner of exact source, artifact, deployment, milestone, and blocker
+identity.
Current work is owned by the [TODO ledger](./todo.md). Open physical evidence is
owned by [verification status](./verification-status.md). Environment and initial
diff --git a/docs/status.md b/docs/status.md
index 5c6ebb73..c67e949f 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -42,10 +42,9 @@ This is the current execution index. Git history owns completed timelines;
## Current Source
-- Canonical `main` and production use the same evidence-only strict
- `screener-v13` quality-shadow application tree deployed from `73ed920`.
+- Canonical source uses the strict `screener-v14` Browser/server contract.
Optional SQLite stable authority, non-expiring local preferred code, atomic
- room replacement and the Host codec selector are implemented; production
+ room replacement and the Host codec selector remain implemented; production
selects stable storage. Graceful restart, crash, timeout and network loss use
one reconnect state. LiveKit room teardown cannot stop Host-owned capture.
- One event-driven controller owns the committed graph and one room-serial child
@@ -54,14 +53,15 @@ This is the current execution index. Git history owns completed timelines;
total deadline, while first decoded frame remains the only commit proof. SFU
provides working media before finite background direct convergence. Healthy
decoded edges remain sticky.
-- WebRTC/LiveKit own media adaptation. Screener has no custom SFU layer list,
- quality score, layer selector, periodic rebalancing, or quality-driven parent
- change. P2P and SFU recover their current route before actual failure enters
- normal reassignment.
-- Current Viewer freeze/pause evidence requires decoded progress and exact
- foreground presentation authority. The controller retains one bounded,
- fresh current-edge aggregate per child for the Host-only on-demand snapshot;
- it does not change route facts, capacity, candidates, SFU usage or reconcile.
+- WebRTC/LiveKit own media adaptation. With the per-share convergence gate
+ enabled, one fresh degraded native edge may enter the existing serial route
+ operation after availability work. A candidate commits only after first-frame
+ readiness and fresh healthy native proof while the old edge remains degraded.
+ Peer candidates stay first and bounded SFU is only the suffix after healthy
+ Peer escape fails. The gate defaults off.
+- Screener has no custom SFU layer list, quality score, layer selector,
+ all-pairs probe, parent-wide prediction or periodic rebalancing. P2P and SFU
+ still recover their current route before actual failure enters reassignment.
- Viewer hidden/freeze/pagehide suppress decoded-stall routing authority;
visible/resume/pageshow rebaseline and rearm current-frame proof. SFU
pagehide no longer triggers LiveKit's automatic disconnect. Native Viewer
@@ -69,9 +69,9 @@ This is the current execution index. Git history owns completed timelines;
## Current Milestone
-The native-edge local-convergence design is accepted at its truth boundary.
-Current source and production remain on the evidence-only shadow;
-implementation has not started.
+Native-edge local convergence is implemented and locally accepted in source.
+Production remains on the evidence-only `screener-v13` release until the current
+application release and scoped postflight complete.
## Active Boundaries
@@ -79,8 +79,8 @@ implementation has not started.
screening did not reproduce a Host-page drop; accepted Viewer lifecycle work
prevents frozen JavaScript wall time from becoming an immediate route failure
but is not capture keepalive.
-- Current-path quality is diagnostic in source and production. The accepted next
- slice is ADR-0005 native-edge local convergence; weighted/global optimization
+- Current-path quality can drive opt-in local convergence in source and remains
+ diagnostic in production until deployment. Weighted/global optimization
remains parked.
- Repository simplification does not change or deploy product behavior beyond
deleting proven dead private surfaces.
@@ -89,5 +89,5 @@ implementation has not started.
## Current Hold
-No source or deployment P0/P1 is open. Native-edge convergence is the next
-source task in TODO; broader product evidence remains parked.
+No source or deployment P0/P1 is open. Native-edge convergence release and
+postflight are the current task; broader product evidence remains parked.
diff --git a/docs/todo.md b/docs/todo.md
index 92a7b499..d78719e8 100644
--- a/docs/todo.md
+++ b/docs/todo.md
@@ -7,11 +7,10 @@ topics are not implementation authority.
## Now
-1. **Native-edge topology convergence.** Implement ADR-0005's categorical
- `unknown | healthy | degraded` evidence, availability-first local moves, one
- serial candidate, bounded Host-to-SFU suffix, default-off pre-share rollout
- gate, and default-off peer-only policy. Current production remains
- observation-only until focused route and Browser gates pass.
+1. **Release native-edge topology convergence.** Integrate the accepted
+ `screener-v14` implementation, deploy the immutable application artifact, and
+ complete scoped direct/SFU postflight. Production remains observation-only
+ until cutover succeeds.
## Parked Repository Work
diff --git a/docs/verification-status.md b/docs/verification-status.md
index 70ad5310..7d0f6473 100644
--- a/docs/verification-status.md
+++ b/docs/verification-status.md
@@ -42,10 +42,10 @@ Still required:
admission at the 20-Viewer bound.
Current controlled Browser evidence supports the H.264/VP8 gate, `motion`
-content intent, startup-quality workaround, and LiveKit-owned SFU adaptation.
-It does not establish a quality-driven topology trigger. See
-[media quality](./product/media-quality.md) and
-[realtime quality research](./research/realtime-quality-adaptation.md).
+content intent, startup-quality workaround, LiveKit-owned SFU adaptation, and
+the native-edge convergence invariants. It does not establish their quality or
+resource benefit on heterogeneous public networks. See [media quality](./product/media-quality.md)
+and [realtime quality research](./research/realtime-quality-adaptation.md).
## Browser Lifecycle
diff --git a/src/client/media/host-provisional-child.ts b/src/client/media/host-provisional-child.ts
index f126b986..036d3702 100644
--- a/src/client/media/host-provisional-child.ts
+++ b/src/client/media/host-provisional-child.ts
@@ -29,6 +29,11 @@ interface HostProvisionalChildEvents {
sendSignal: (peerId: string, payload: SignalPayload) => boolean;
activeConnectionId?: (peerId: string) => string | null;
onPromotedStreamFailure?: (peer: HostPeer) => void;
+ onPreparedUpdate?: (
+ peer: HostPeer,
+ snapshot: PeerSnapshot,
+ revision: number,
+ ) => void;
onPromotedUpdate?: (peer: HostPeer, snapshot: PeerSnapshot) => void;
}
@@ -111,6 +116,7 @@ export class HostProvisionalChild {
if (snapshot.connectionState === "failed") {
this.fail(peer);
}
+ this.events.onPreparedUpdate?.(peer, snapshot, revision);
return;
}
if (this.promotedPeer === peer) {
diff --git a/src/client/media/host-sfu-route.ts b/src/client/media/host-sfu-route.ts
index d6583803..1e397a3f 100644
--- a/src/client/media/host-sfu-route.ts
+++ b/src/client/media/host-sfu-route.ts
@@ -62,6 +62,11 @@ interface HostSfuRouteEvents {
getVideoCodec: () => BrowserVideoCodec;
reconcileChildren: (childPeerIds: string[]) => void;
send: (message: ClientMessage) => boolean;
+ onSenderUpdate?: (
+ metrics: ConnectionMetrics,
+ revision: number,
+ publicationGeneration: string,
+ ) => void;
onPublisherUpdate?: (snapshot: HostSfuPublisherSnapshot | null) => void;
createPublisher?: (
onDisconnected: () => void,
@@ -675,6 +680,20 @@ export class HostSfuRoute {
slot: HostPublisherSlot,
metrics: ConnectionMetrics | null,
): void {
+ if (
+ metrics !== null &&
+ !this.closed &&
+ !slot.failed &&
+ slot.active &&
+ (this.pending === slot || this.active === slot) &&
+ this.ownsPublisherSlot(slot)
+ ) {
+ this.events.onSenderUpdate?.(
+ metrics,
+ slot.revision,
+ slot.publicationGeneration,
+ );
+ }
if (
metrics === null ||
this.closed ||
diff --git a/src/client/media/sender-quality-evidence.ts b/src/client/media/sender-quality-evidence.ts
new file mode 100644
index 00000000..b51c4d86
--- /dev/null
+++ b/src/client/media/sender-quality-evidence.ts
@@ -0,0 +1,128 @@
+import {
+ senderQualityEvidenceMessageSchema,
+ sfuPublisherQualityEvidenceMessageSchema,
+ type ClientMessage,
+} from "../../shared/protocol";
+import type { PeerSnapshot } from "../types";
+import type { ConnectionMetrics } from "../types";
+
+let senderEvidenceGeneration = 0;
+const connectionGenerations = new Map<string, number>();
+const publicationGenerations = new Map<string, number>();
+const unknownConnections = new Set<string>();
+const unknownPublications = new Set<string>();
+
+export function invalidateSenderQualityEvidence(): void {
+ senderEvidenceGeneration += 1;
+ connectionGenerations.clear();
+ publicationGenerations.clear();
+ unknownConnections.clear();
+ unknownPublications.clear();
+}
+
+function ownsCurrentEvidenceGeneration(
+ identities: Map<string, number>,
+ identity: string,
+): boolean {
+ if (identities.get(identity) === senderEvidenceGeneration) {
+ return true;
+ }
+ identities.set(identity, senderEvidenceGeneration);
+ return false;
+}
+
+function emitUnknownOnce(identities: Set<string>, identity: string): boolean {
+ if (identities.has(identity)) {
+ return false;
+ }
+ identities.add(identity);
+ return true;
+}
+
+function nativeQualityState(
+ metrics: ConnectionMetrics,
+): "unknown" | "healthy" | "degraded" {
+ if (
+ (metrics.nativeEdgeQualityState !== "healthy" &&
+ metrics.nativeEdgeQualityState !== "degraded") ||
+ metrics.sampleWindowMs === null ||
+ metrics.intervalFramesEncoded === null ||
+ metrics.intervalFramesEncoded <= 0
+ ) {
+ return "unknown";
+ }
+ const reason = metrics.qualityLimitationReason;
+ if (reason !== "none" && reason !== "bandwidth" && reason !== "cpu") {
+ return "unknown";
+ }
+ return metrics.nativeEdgeQualityState;
+}
+
+export function senderQualityEvidenceFromSnapshot(
+ snapshot: PeerSnapshot,
+ routeRevision: number,
+): Extract<ClientMessage, { type: "sender-quality-evidence" }> | null {
+ const evidence = nativeQualityState(snapshot.metrics);
+ const hasIdentity =
+ snapshot.metrics.rtpStatsId !== null &&
+ snapshot.metrics.trackIdentifier !== null;
+ const state =
+ ownsCurrentEvidenceGeneration(
+ connectionGenerations,
+ snapshot.connectionId,
+ ) && hasIdentity
+ ? evidence
+ : "unknown";
+ const parsed = senderQualityEvidenceMessageSchema.safeParse({
+ type: "sender-quality-evidence",
+ childPeerId: snapshot.peerId,
+ connectionId: snapshot.connectionId,
+ rtpStatsId:
+ state === "unknown" ? null : snapshot.metrics.rtpStatsId,
+ trackIdentifier:
+ state === "unknown"
+ ? null
+ : snapshot.metrics.trackIdentifier,
+ routeRevision,
+ state,
+ });
+ if (state === "unknown") {
+ if (!emitUnknownOnce(unknownConnections, snapshot.connectionId)) {
+ return null;
+ }
+ } else {
+ unknownConnections.delete(snapshot.connectionId);
+ }
+ return parsed.success ? parsed.data : null;
+}
+
+export function sfuPublisherQualityEvidenceFromMetrics(
+ metrics: ConnectionMetrics,
+ routeRevision: number,
+ publicationGeneration: string,
+): Extract<
+ ClientMessage,
+ { type: "sfu-publisher-quality-evidence" }
+> | null {
+ const evidence = nativeQualityState(metrics);
+ const state = ownsCurrentEvidenceGeneration(
+ publicationGenerations,
+ publicationGeneration,
+ )
+ ? evidence
+ : "unknown";
+ const parsed = sfuPublisherQualityEvidenceMessageSchema.safeParse({
+ type: "sfu-publisher-quality-evidence",
+ routeRevision,
+ publicationGeneration,
+ state,
+ });
+ if (state === "unknown") {
+ if (!emitUnknownOnce(unknownPublications, publicationGeneration)) {
+ return null;
+ }
+ } else {
+ unknownPublications.delete(publicationGeneration);
+ }
+ return parsed.success ? parsed.data : null;
+}
diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx
index 83ac9ba9..47be8737 100644
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@ -23,6 +23,7 @@ import { useEffect, useMemo, useRef, useState } from "react";
import {
DEFAULT_HOST_DISPLAY_NAME_PREFIX,
DEFAULT_QUALITY_SETTINGS,
+ DEFAULT_ROUTE_POLICY,
MAX_VIEWER_PASSWORD_LENGTH,
viewerPasswordSchema,
type CreateRoomResponse,
@@ -31,6 +32,7 @@ import {
type PreparedRouteCandidate,
type ServerMessage,
type CodeEntryPolicy,
+ type RoutePolicy,
} from "../../shared/protocol";
import { AppHeader } from "../components/AppHeader";
import { ConnectionDetailsToggle } from "../components/ConnectionDetailsToggle";
@@ -107,6 +109,11 @@ import {
HostProvisionalChild,
} from "../media/host-provisional-child";
import { SfuStandbyPrewarmer } from "../media/sfu-standby-prewarmer";
+import {
+ invalidateSenderQualityEvidence,
+ senderQualityEvidenceFromSnapshot,
+ sfuPublisherQualityEvidenceFromMetrics,
+} from "../media/sender-quality-evidence";
import {
classifyHostViewerQualityEvidence,
metricsFromQualityEvidence,
@@ -187,6 +194,7 @@ function closeAbandonedRoom(room: HostRoomIdentity): void {
token: room.hostToken,
clientId: getStableClientId("host", room.roomId),
shareGeneration: createOpaqueId(),
+ routePolicy: DEFAULT_ROUTE_POLICY,
},
{
onMessage: () => undefined,
@@ -256,6 +264,9 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
const [advancedQuality, setAdvancedQuality] = useState<QualitySettings>(
DEFAULT_QUALITY_SETTINGS,
);
+ const [routePolicy, setRoutePolicy] = useState<RoutePolicy>(
+ DEFAULT_ROUTE_POLICY,
+ );
const [videoCodecMode, setVideoCodecMode] =
useState<BrowserVideoCodecMode>("auto");
const [resolvedVideoCodec, setResolvedVideoCodec] =
@@ -340,6 +351,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
const qualityChangeRef = useRef<object | null>(null);
const pendingQualityChangeRef = useRef<QualitySettings | null>(null);
const qualitySettingsRef = useRef<QualitySettings>(DEFAULT_QUALITY_SETTINGS);
+ const routePolicyRef = useRef<RoutePolicy>(DEFAULT_ROUTE_POLICY);
const advancedQualityRef = useRef<QualitySettings>(advancedQuality);
const videoCodecModeRef = useRef<BrowserVideoCodecMode>(videoCodecMode);
const roomMutationRef = useRef<object | null>(null);
@@ -386,6 +398,17 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
}, [stream]);
useEffect(() => {
+ let senderQualitySuspended = false;
+ const resetSenderQualityAuthority = () => {
+ if (senderQualitySuspended) {
+ return;
+ }
+ senderQualitySuspended = true;
+ invalidateSenderQualityEvidence();
+ if (routePolicyRef.current.topologyOptimization) {
+ signalRef.current?.send({ type: "reset-sender-quality" });
+ }
+ };
const syncPreviewPlayback = () => {
const video = videoRef.current;
if (!video) {
@@ -395,6 +418,11 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
document.visibilityState,
document.hasFocus(),
);
+ if (document.visibilityState !== "visible") {
+ resetSenderQualityAuthority();
+ } else {
+ senderQualitySuspended = false;
+ }
setLocalPreviewPaused(shouldPause);
if (shouldPause) {
video.pause();
@@ -408,11 +436,13 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
document.addEventListener("visibilitychange", syncPreviewPlayback);
window.addEventListener("blur", syncPreviewPlayback);
window.addEventListener("focus", syncPreviewPlayback);
+ window.addEventListener("pagehide", resetSenderQualityAuthority);
syncPreviewPlayback();
return () => {
document.removeEventListener("visibilitychange", syncPreviewPlayback);
window.removeEventListener("blur", syncPreviewPlayback);
window.removeEventListener("focus", syncPreviewPlayback);
+ window.removeEventListener("pagehide", resetSenderQualityAuthority);
};
}, [stream]);
@@ -508,6 +538,23 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
isCurrentGeneration(generation) && hostSfuRouteRef.current === route
? signalRef.current?.send(message) === true
: false,
+ onSenderUpdate: (metrics, revision, publicationGeneration) => {
+ if (
+ !isCurrentGeneration(generation) ||
+ !routePolicyRef.current.topologyOptimization ||
+ document.visibilityState !== "visible"
+ ) {
+ return;
+ }
+ const evidence = sfuPublisherQualityEvidenceFromMetrics(
+ metrics,
+ revision,
+ publicationGeneration,
+ );
+ if (evidence) {
+ signalRef.current?.send(evidence);
+ }
+ },
});
hostSfuRouteRef.current = route;
return route;
@@ -860,6 +907,15 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
setResolvedVideoCodec(null);
}
+ function changeRoutePolicy(patch: Partial<RoutePolicy>): void {
+ if (phase === "starting" || phase === "live") {
+ return;
+ }
+ const next = { ...routePolicyRef.current, ...patch };
+ routePolicyRef.current = next;
+ setRoutePolicy(next);
+ }
+
function changeAdvancedQuality(
patch: Partial<QualitySettings>,
): void {
@@ -1061,6 +1117,22 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
provisional?.discard();
}
+ function reportSenderQuality(
+ snapshot: PeerSnapshot,
+ revision: number,
+ ): void {
+ if (
+ !routePolicyRef.current.topologyOptimization ||
+ document.visibilityState !== "visible"
+ ) {
+ return;
+ }
+ const evidence = senderQualityEvidenceFromSnapshot(snapshot, revision);
+ if (evidence) {
+ signalRef.current?.send(evidence);
+ }
+ }
+
function prepareHostChild(
revision: number,
assignment: HostRouteAssignment,
@@ -1100,6 +1172,12 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
peersRef.current.get(peer.peerId) === peer
) {
updatePeerSnapshot(snapshot);
+ reportSenderQuality(snapshot, activeRouteRevisionRef.current);
+ }
+ },
+ onPreparedUpdate: (_peer, snapshot, revision) => {
+ if (isCurrentGeneration(generation)) {
+ reportSenderQuality(snapshot, revision);
}
},
});
@@ -1184,6 +1262,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
peersRef.current.get(peerId) === peer
) {
updatePeerSnapshot(snapshot);
+ reportSenderQuality(snapshot, activeRouteRevisionRef.current);
}
},
},
@@ -1333,6 +1412,8 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
"mediaMode" in message &&
message.mediaMode === "peer-assisted"
) {
+ routePolicyRef.current = { ...message.routePolicy };
+ setRoutePolicy({ ...message.routePolicy });
const currentQualitySettings =
pendingQualitySettings ?? message.qualitySettings;
activeRouteRevisionRef.current = message.routeRevision;
@@ -1625,6 +1706,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
shareGeneration,
sharingPaused: false,
qualitySettings: qualitySettingsRef.current,
+ routePolicy: routePolicyRef.current,
viewerPresence: true,
displayName: initialDisplayName,
},
@@ -1818,6 +1900,10 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
}
retiringStreamRef.current = previousStream;
+ invalidateSenderQualityEvidence();
+ if (routePolicyRef.current.topologyOptimization) {
+ signalRef.current?.send({ type: "reset-sender-quality" });
+ }
setMediaPaused(captured, sharingPausedRef.current);
streamRef.current = captured;
setStream(captured);
@@ -2494,34 +2580,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
</output>
</div>
</label>
- <fieldset className="control-group quality-priority">
- <legend>视频编码</legend>
- <div className="segmented-control">
- {(["vp8", "auto", "h264"] as const).map((mode) => (
- <button
- key={mode}
- type="button"
- className={
- videoCodecMode === mode ? "is-selected" : undefined
- }
- aria-pressed={videoCodecMode === mode}
- disabled={phase === "starting" || phase === "live"}
- onClick={() => changeVideoCodecMode(mode)}
- >
- <span>{mode === "auto" ? "自动" : mode.toUpperCase()}</span>
- <small>
- {mode === "vp8"
- ? "兼容优先"
- : mode === "h264"
- ? "硬件优先"
- : resolvedVideoCodec
- ? resolvedVideoCodec.toUpperCase()
- : "自动选择"}
- </small>
- </button>
- ))}
- </div>
- </fieldset>
<fieldset className="control-group quality-priority">
<legend>画面偏好</legend>
<div className="segmented-control">
@@ -2600,6 +2658,67 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
))}
</div>
</fieldset>
+ <fieldset className="control-group route-policy-controls">
+ <legend>路由策略</legend>
+ <label>
+ <input
+ type="checkbox"
+ checked={routePolicy.topologyOptimization}
+ disabled={phase === "starting" || phase === "live"}
+ onChange={(event) =>
+ changeRoutePolicy({
+ topologyOptimization: event.target.checked,
+ })
+ }
+ />
+ <span>
+ 自动优化拓扑
+ <small>观看中逐步选择更健康的连接</small>
+ </span>
+ </label>
+ <label>
+ <input
+ type="checkbox"
+ checked={routePolicy.peerOnly}
+ disabled={phase === "starting" || phase === "live"}
+ onChange={(event) =>
+ changeRoutePolicy({ peerOnly: event.target.checked })
+ }
+ />
+ <span>
+ 纯 P2P
+ <small>不使用媒体服务器,无法直连时停止尝试</small>
+ </span>
+ </label>
+ </fieldset>
+ <fieldset className="control-group quality-priority">
+ <legend>视频编码</legend>
+ <div className="segmented-control">
+ {(["vp8", "auto", "h264"] as const).map((mode) => (
+ <button
+ key={mode}
+ type="button"
+ className={
+ videoCodecMode === mode ? "is-selected" : undefined
+ }
+ aria-pressed={videoCodecMode === mode}
+ disabled={phase === "starting" || phase === "live"}
+ onClick={() => changeVideoCodecMode(mode)}
+ >
+ <span>{mode === "auto" ? "自动" : mode.toUpperCase()}</span>
+ <small>
+ {mode === "vp8"
+ ? "兼容优先"
+ : mode === "h264"
+ ? "硬件优先"
+ : resolvedVideoCodec
+ ? resolvedVideoCodec.toUpperCase()
+ : "自动选择"}
+ </small>
+ </button>
+ ))}
+ </div>
+ </fieldset>
</div>
</details>
</div>
diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsx
index 0b9fd051..7d9f3c11 100644
--- a/src/client/pages/ViewerPage.tsx
+++ b/src/client/pages/ViewerPage.tsx
@@ -15,6 +15,7 @@ import {
import { useEffect, useMemo, useReducer, useRef, useState } from "react";
import {
DEFAULT_QUALITY_SETTINGS,
+ DEFAULT_ROUTE_POLICY,
MAX_VIEWER_PASSWORD_LENGTH,
viewerPasswordSchema,
type IceConfig,
@@ -22,6 +23,7 @@ import {
type ParticipantPresenceEntry,
type ParticipantRouteAssignment,
type ServerMessage,
+ type RoutePolicy,
} from "../../shared/protocol";
import { AppHeader } from "../components/AppHeader";
import { ConnectionDetailsToggle } from "../components/ConnectionDetailsToggle";
@@ -47,6 +49,10 @@ import { DecodedFrameStallDetector } from "../media/decoded-frame-stall";
import type { QualitySettings } from "../media/quality";
import { relayCapacityMessageForBrowser } from "../media/relay-capability";
import { SfuStandbyPrewarmer } from "../media/sfu-standby-prewarmer";
+import {
+ invalidateSenderQualityEvidence,
+ senderQualityEvidenceFromSnapshot,
+} from "../media/sender-quality-evidence";
import {
metricsFromQualityEvidence,
nextViewerQualityEvidencePresentationExpiryAt,
@@ -421,6 +427,8 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
let endpointMediaCopyCapacity = MAX_ENDPOINT_MEDIA_CHILDREN;
let viewerAuthorizationGeneration: string | null = null;
let currentQualitySettings: QualitySettings = DEFAULT_QUALITY_SETTINGS;
+ let currentRoutePolicy: RoutePolicy = DEFAULT_ROUTE_POLICY;
+ let currentShareGeneration: string | null = null;
let currentAssignment: MediaAssignment = {
parentPeerId: null,
childPeerIds: [],
@@ -446,8 +454,15 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
};
const suspendForPageLifecycle = (): void => {
invalidatePresentedMedia();
+ const newlySuspended = !pageSuspended;
pageSuspended = true;
syncDecodedFrameStallPause();
+ if (newlySuspended) {
+ invalidateSenderQualityEvidence();
+ if (currentRoutePolicy.topologyOptimization) {
+ signal.send({ type: "reset-sender-quality" });
+ }
+ }
};
const recoverFromPageLifecycle = (): void => {
invalidatePresentedMedia();
@@ -693,6 +708,22 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
}
}
},
+ onSenderUpdate: (snapshot, preparedRevision) => {
+ if (
+ !active ||
+ pageSuspended ||
+ !currentRoutePolicy.topologyOptimization
+ ) {
+ return;
+ }
+ const evidence = senderQualityEvidenceFromSnapshot(
+ snapshot,
+ preparedRevision ?? currentRouteRevision,
+ );
+ if (evidence) {
+ signal.send(evidence);
+ }
+ },
},
endpointMediaCopyCapacity,
);
@@ -1340,6 +1371,8 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
});
if (nextPeerAssisted && "qualitySettings" in message) {
currentQualitySettings = message.qualitySettings;
+ currentRoutePolicy = message.routePolicy;
+ currentShareGeneration = message.shareGeneration;
void viewerRelay?.updateProfile(currentQualitySettings);
const route = ensureViewerSfuRoute();
route.setPaused(sharingPaused);
@@ -1494,6 +1527,18 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
}
return;
}
+ if (message.type === "route-policy") {
+ if (
+ peerAssisted &&
+ (currentShareGeneration === null ||
+ currentShareGeneration === message.shareGeneration)
+ ) {
+ currentShareGeneration = message.shareGeneration;
+ currentRoutePolicy = message.routePolicy;
+ setSfuStandbyUrl(message.sfuStandbyUrl ?? null);
+ }
+ return;
+ }
if (message.type === "signal") {
if (peerAssisted && pendingPeer?.parentPeerId === message.fromPeerId) {
if (currentAssignment.parentPeerId !== message.fromPeerId) {
@@ -1597,6 +1642,8 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
currentRouteAssignment = null;
currentRouteConnectionId = null;
pendingRouteConnection = null;
+ currentShareGeneration = null;
+ currentRoutePolicy = DEFAULT_ROUTE_POLICY;
setSfuStandbyUrl(null);
setAssignedRoute(null);
currentHostOnline = false;
diff --git a/src/client/sfu/publisher.ts b/src/client/sfu/publisher.ts
index f9419a61..635d3544 100644
--- a/src/client/sfu/publisher.ts
+++ b/src/client/sfu/publisher.ts
@@ -27,10 +27,13 @@ import type { BrowserVideoCodec } from "../webrtc/video-codec";
import {
captureMetrics,
collectConnectionMetricsFromReport,
+ collectNativeSenderQualityFromReport,
+ createNativeSenderQualityAccumulator,
createStatsAccumulator,
maxEncodedVideoFrames,
mergeStatsReports,
type StatsAccumulator,
+ type NativeSenderQualityAccumulator,
} from "../webrtc/stats";
import { sfuRoomConnectOptions } from "./connection-options";
@@ -76,6 +79,7 @@ interface PublisherStatsIdentity {
audioSender: RTCRtpSender | null;
audioTrack: MediaStreamTrack | null;
accumulator: StatsAccumulator;
+ nativeQualityAccumulator: NativeSenderQualityAccumulator;
}
type LiveKit = typeof import("livekit-client");
@@ -1027,6 +1031,7 @@ export class SfuPublisher {
audioSender,
audioTrack,
accumulator: createStatsAccumulator(),
+ nativeQualityAccumulator: createNativeSenderQualityAccumulator(),
};
this.statsIdentity = identity;
}
@@ -1058,16 +1063,31 @@ export class SfuPublisher {
) {
return;
}
+ const nativeQuality = collectNativeSenderQualityFromReport(
+ report,
+ identity.videoTrack.id,
+ identity.nativeQualityAccumulator,
+ );
+ const connectionMetrics = collectConnectionMetricsFromReport(
+ report,
+ "send",
+ identity.accumulator,
+ {
+ trackIdentifier: identity.videoTrack.id,
+ audioTrackIdentifier: identity.audioTrack?.id ?? null,
+ },
+ );
const metrics = {
- ...collectConnectionMetricsFromReport(
- report,
- "send",
- identity.accumulator,
- {
- trackIdentifier: identity.videoTrack.id,
- audioTrackIdentifier: identity.audioTrack?.id ?? null,
- },
- ),
+ ...connectionMetrics,
+ nativeEdgeQualityState: nativeQuality.nativeEdgeQualityState,
+ ...(nativeQuality.nativeEdgeQualityState === "unknown"
+ ? {}
+ : {
+ qualityLimitationReason:
+ nativeQuality.qualityLimitationReason,
+ sampleWindowMs: nativeQuality.sampleWindowMs,
+ intervalFramesEncoded: nativeQuality.intervalFramesEncoded,
+ }),
...captureMetrics(identity.videoTrack),
};
if (
diff --git a/src/client/styles.css b/src/client/styles.css
index 64e37c26..b1f6bfb7 100644
--- a/src/client/styles.css
+++ b/src/client/styles.css
@@ -588,6 +588,48 @@ h3 {
color: #a9cdb7;
}
+.route-policy-controls {
+ display: grid;
+ grid-column: 1 / -1;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px;
+}
+
+.route-policy-controls legend {
+ grid-column: 1 / -1;
+}
+
+.route-policy-controls label {
+ display: flex;
+ min-width: 0;
+ gap: 9px;
+ align-items: flex-start;
+ padding: 10px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ cursor: pointer;
+}
+
+.route-policy-controls input {
+ flex: 0 0 auto;
+ margin: 2px 0 0;
+ accent-color: var(--green-strong);
+}
+
+.route-policy-controls span {
+ display: grid;
+ min-width: 0;
+ gap: 3px;
+ font-size: 12px;
+ font-weight: 600;
+}
+
+.route-policy-controls small {
+ color: var(--faint);
+ font-size: 10px;
+ font-weight: 500;
+}
+
.control-note {
margin: 8px 0 0;
color: var(--muted);
@@ -1435,6 +1477,11 @@ h3 {
.quality-priority {
grid-column: auto;
}
+
+ .route-policy-controls {
+ grid-column: auto;
+ grid-template-columns: 1fr;
+ }
.viewer-stats .stats-grid {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
diff --git a/src/client/types.ts b/src/client/types.ts
index e5e521cc..33909ed5 100644
--- a/src/client/types.ts
+++ b/src/client/types.ts
@@ -5,6 +5,7 @@ export type SignalConnectionState =
| "offline";
export type MediaPath = "direct" | "unknown";
+export type NativeEdgeQualityState = "unknown" | "healthy" | "degraded";
export interface ConnectionMetrics {
sampleTimestampMs: number | null;
@@ -72,6 +73,7 @@ export interface ConnectionMetrics {
intervalEncodeMs: number | null;
intervalDecodeMs: number | null;
qualityLimitationReason: string | null;
+ nativeEdgeQualityState: NativeEdgeQualityState;
}
export interface PeerSnapshot {
@@ -154,4 +156,5 @@ export const EMPTY_METRICS: ConnectionMetrics = {
intervalEncodeMs: null,
intervalDecodeMs: null,
qualityLimitationReason: null,
+ nativeEdgeQualityState: "unknown",
};
diff --git a/src/client/webrtc/stats.ts b/src/client/webrtc/stats.ts
index 41342163..34df3598 100644
--- a/src/client/webrtc/stats.ts
+++ b/src/client/webrtc/stats.ts
@@ -10,6 +10,11 @@ type StatsRecord = Record<string, unknown> & {
timestamp: number;
};
+type QualityLimitationDurations = Record<
+ "none" | "bandwidth" | "cpu" | "other",
+ number
+>;
+
export interface StatsAccumulator {
mediaId: string | null;
ssrc: number | null;
@@ -32,6 +37,7 @@ export interface StatsAccumulator {
previousRetransmittedBytes: number | null;
previousVideoJitterBufferDelay: number | null;
previousVideoJitterBufferEmittedCount: number | null;
+ previousQualityLimitationDurations: QualityLimitationDurations | null;
audioMediaId: string | null;
audioSsrc: number | null;
audioTrackIdentifier: string | null;
@@ -53,6 +59,114 @@ export interface StatsMediaSelector {
audioTrackIdentifier?: string | null;
}
+interface NativeSenderQualityPrevious {
+ timestamp: number;
+ durations: QualityLimitationDurations;
+ framesEncoded: number;
+}
+
+export interface NativeSenderQualityAccumulator {
+ previousByStatsId: Map<string, NativeSenderQualityPrevious>;
+}
+
+export function createNativeSenderQualityAccumulator(): NativeSenderQualityAccumulator {
+ return { previousByStatsId: new Map() };
+}
+
+export function collectNativeSenderQualityFromReport(
+ report: RTCStatsReport,
+ trackIdentifier: string,
+ accumulator: NativeSenderQualityAccumulator,
+): Pick<
+ ConnectionMetrics,
+ | "nativeEdgeQualityState"
+ | "qualityLimitationReason"
+ | "sampleWindowMs"
+ | "intervalFramesEncoded"
+> {
+ const records: StatsRecord[] = [];
+ report.forEach((raw) => {
+ const record = raw as StatsRecord;
+ if (
+ record.type === "outbound-rtp" &&
+ record.kind === "video" &&
+ record.isRemote !== true &&
+ record.active !== false &&
+ mediaTrackIdentifier(report, record, "send") === trackIdentifier
+ ) {
+ records.push(record);
+ }
+ });
+ const activeIds = new Set(records.map((record) => record.id));
+ for (const id of accumulator.previousByStatsId.keys()) {
+ if (!activeIds.has(id)) accumulator.previousByStatsId.delete(id);
+ }
+ const samples = records.map((record) => {
+ const timestamp = numberValue(record, "timestamp");
+ const durations = qualityLimitationDurationsValue(record);
+ const reason = stringValue(record, "qualityLimitationReason");
+ const framesEncoded = numberValue(record, "framesEncoded");
+ const previous = accumulator.previousByStatsId.get(record.id);
+ const windowMs =
+ timestamp !== null && previous && timestamp > previous.timestamp
+ ? timestamp - previous.timestamp
+ : null;
+ const state = nativeEdgeQualityState(
+ reason,
+ durations,
+ previous?.durations ?? null,
+ windowMs !== null,
+ );
+ const intervalFramesEncoded =
+ previous &&
+ framesEncoded !== null &&
+ framesEncoded >= previous.framesEncoded
+ ? framesEncoded - previous.framesEncoded
+ : null;
+ if (timestamp !== null && durations && framesEncoded !== null) {
+ accumulator.previousByStatsId.set(record.id, {
+ timestamp,
+ durations,
+ framesEncoded,
+ });
+ } else {
+ accumulator.previousByStatsId.delete(record.id);
+ }
+ return { state, reason, windowMs, intervalFramesEncoded };
+ });
+ if (
+ samples.length === 0 ||
+ samples.some(
+ (sample) =>
+ sample.state === "unknown" ||
+ sample.windowMs === null ||
+ sample.intervalFramesEncoded === null,
+ )
+ ) {
+ return {
+ nativeEdgeQualityState: "unknown",
+ qualityLimitationReason: null,
+ sampleWindowMs: null,
+ intervalFramesEncoded: null,
+ };
+ }
+ const degraded = samples.filter((sample) => sample.state === "degraded");
+ return {
+ nativeEdgeQualityState: degraded.length > 0 ? "degraded" : "healthy",
+ qualityLimitationReason:
+ degraded.some((sample) => sample.reason === "bandwidth")
+ ? "bandwidth"
+ : degraded.length > 0
+ ? "cpu"
+ : "none",
+ sampleWindowMs: Math.min(...samples.map((sample) => sample.windowMs!)),
+ intervalFramesEncoded: samples.reduce(
+ (total, sample) => total + sample.intervalFramesEncoded!,
+ 0,
+ ),
+ };
+}
+
export function captureMetrics(
track: MediaStreamTrack,
): Pick<
@@ -100,6 +214,7 @@ export function createStatsAccumulator(): StatsAccumulator {
previousRetransmittedBytes: null,
previousVideoJitterBufferDelay: null,
previousVideoJitterBufferEmittedCount: null,
+ previousQualityLimitationDurations: null,
audioMediaId: null,
audioSsrc: null,
audioTrackIdentifier: null,
@@ -210,6 +325,62 @@ function stringValue(record: StatsRecord | null, key: string): string | null {
return typeof value === "string" && value.length > 0 ? value : null;
}
+function qualityLimitationDurationsValue(
+ record: StatsRecord | null,
+): QualityLimitationDurations | null {
+ const value = record?.qualityLimitationDurations;
+ if (!value || typeof value !== "object") {
+ return null;
+ }
+ const durations = value as Record<string, unknown>;
+ const result = {} as QualityLimitationDurations;
+ for (const reason of ["none", "bandwidth", "cpu", "other"] as const) {
+ const duration = durations[reason];
+ if (typeof duration !== "number" || !Number.isFinite(duration) || duration < 0) {
+ return null;
+ }
+ result[reason] = duration;
+ }
+ return result;
+}
+
+function nativeEdgeQualityState(
+ reason: string | null,
+ current: QualityLimitationDurations | null,
+ previous: QualityLimitationDurations | null,
+ hasInterval: boolean,
+): ConnectionMetrics["nativeEdgeQualityState"] {
+ if (!hasInterval || !current || !previous) {
+ return "unknown";
+ }
+ const deltas = {} as QualityLimitationDurations;
+ for (const key of ["none", "bandwidth", "cpu", "other"] as const) {
+ if (current[key] < previous[key]) {
+ return "unknown";
+ }
+ deltas[key] = current[key] - previous[key];
+ }
+ if (
+ reason === "none" &&
+ deltas.none > 0 &&
+ deltas.bandwidth === 0 &&
+ deltas.cpu === 0 &&
+ deltas.other === 0
+ ) {
+ return "healthy";
+ }
+ if (
+ (reason === "bandwidth" || reason === "cpu") &&
+ deltas[reason] > 0 &&
+ deltas.none === 0 &&
+ deltas.other === 0 &&
+ deltas[reason === "bandwidth" ? "cpu" : "bandwidth"] === 0
+ ) {
+ return "degraded";
+ }
+ return "unknown";
+}
+
function booleanValue(record: StatsRecord | null, key: string): boolean | null {
const value = record?.[key];
return typeof value === "boolean" ? value : null;
@@ -516,6 +687,11 @@ export function collectConnectionMetricsFromReport(
media,
"jitterBufferEmittedCount",
);
+ const qualityLimitationReason = stringValue(
+ media,
+ "qualityLimitationReason",
+ );
+ const qualityLimitationDurations = qualityLimitationDurationsValue(media);
let bitrateKbps: number | null = null;
let derivedFps: number | null = null;
const sampleWindowMs =
@@ -650,6 +826,12 @@ export function collectConnectionMetricsFromReport(
previous.previousVideoJitterBufferEmittedCount,
)
: null;
+ const currentNativeEdgeQualityState = nativeEdgeQualityState(
+ qualityLimitationReason,
+ qualityLimitationDurations,
+ previous.previousQualityLimitationDurations,
+ sampleWindowMs !== null,
+ );
previous.mediaId = mediaId;
previous.ssrc = ssrc;
previous.trackIdentifier = trackIdentifier;
@@ -672,6 +854,7 @@ export function collectConnectionMetricsFromReport(
previous.previousVideoJitterBufferDelay = videoJitterBufferDelay;
previous.previousVideoJitterBufferEmittedCount =
videoJitterBufferEmittedCount;
+ previous.previousQualityLimitationDurations = qualityLimitationDurations;
const linkedCodec = linkedMediaCodec(report, media, transport, "video");
const codecEvidence = deriveCodecEvidence(linkedCodec);
@@ -902,6 +1085,7 @@ export function collectConnectionMetricsFromReport(
encodeTimeDelta === null ? null : encodeTimeDelta * 1_000,
intervalEncodeMs,
intervalDecodeMs,
- qualityLimitationReason: stringValue(media, "qualityLimitationReason"),
+ qualityLimitationReason,
+ nativeEdgeQualityState: currentNativeEdgeQualityState,
};
}
diff --git a/src/client/webrtc/viewer-relay.ts b/src/client/webrtc/viewer-relay.ts
index 5b3db2f1..bebef755 100644
--- a/src/client/webrtc/viewer-relay.ts
+++ b/src/client/webrtc/viewer-relay.ts
@@ -17,6 +17,7 @@ import { preferredVideoCodecForTrack } from "./video-codec-preflight";
interface ViewerRelayEvents {
sendSignal: (peerId: string, payload: SignalPayload) => boolean;
onUpdate?: (snapshot: PeerSnapshot | null) => void;
+ onSenderUpdate?: (snapshot: PeerSnapshot, revision: number | null) => void;
}
interface PreparedChild {
revision: number;
@@ -513,6 +514,10 @@ export class ViewerRelay {
if (snapshot.connectionState === "failed") {
this.failPreparedChild(peer);
}
+ this.events.onSenderUpdate?.(
+ snapshot,
+ this.preparedChild?.revision ?? null,
+ );
return;
}
if (
@@ -526,6 +531,7 @@ export class ViewerRelay {
...snapshot,
metrics: { ...snapshot.metrics },
});
+ this.events.onSenderUpdate?.(snapshot, null);
this.events.onUpdate?.(this.getSnapshot());
}
},
diff --git a/src/server/hybrid-media-router.ts b/src/server/hybrid-media-router.ts
index f8fa1e9e..5acc4dd7 100644
--- a/src/server/hybrid-media-router.ts
+++ b/src/server/hybrid-media-router.ts
@@ -7,6 +7,7 @@ import type {
MediaRouteUpstream,
ParticipantRouteAssignment,
PreparedRouteCandidate,
+ RoutePolicy,
Role,
ServerMessage,
} from "../shared/protocol.js";
@@ -21,6 +22,8 @@ import {
type OperationSnapshot,
type RouteQualityEvidenceInput,
type RouteQualityEvidenceResult,
+ type SenderQualityEvidenceInput,
+ type SfuPublisherQualityEvidenceInput,
type RouteSnapshot,
} from "./room-route-controller.js";
import type { RoomStore } from "./room-store.js";
@@ -158,6 +161,7 @@ export interface AuthenticatedRouteParticipant {
role: Role;
peerId: string;
sessionId: string;
+ routePolicy?: RoutePolicy;
}
export class HybridMediaRouter {
@@ -275,6 +279,131 @@ export class HybridMediaRouter {
);
}
+ observeSenderQualityEvidence(
+ participant: AuthenticatedRouteParticipant,
+ message: Extract<ClientMessage, { type: "sender-quality-evidence" }>,
+ ): boolean {
+ const room = this.rooms.get(participant.roomId);
+ const controller = room?.controller;
+ if (!room || !controller) {
+ return false;
+ }
+ const before = controller.snapshot().revision;
+ const input: SenderQualityEvidenceInput = {
+ parentPeerId: participant.peerId,
+ parentSessionId: participant.sessionId,
+ childPeerId: message.childPeerId,
+ routeRevision: message.routeRevision,
+ connectionId: message.connectionId,
+ senderIdentity:
+ message.rtpStatsId && message.trackIdentifier
+ ? `${message.rtpStatsId}\u0000${message.trackIdentifier}`
+ : null,
+ state: message.state,
+ acceptedAtMs: this.now(),
+ };
+ const result = controller.observeSenderQualityEvidence(
+ input,
+ (reservation) => this.commitReservation(reservation),
+ );
+ this.releaseResources(result.released);
+ if (result.committed) {
+ this.resourceWaiters.delete(participant.roomId);
+ this.options.setConnectionId(
+ participant.roomId,
+ message.childPeerId,
+ message.connectionId,
+ );
+ }
+ if (controller.snapshot().revision !== before) {
+ this.broadcastActive(participant.roomId, room);
+ }
+ this.sendRouteFailures(
+ participant.roomId,
+ result.failedPeerIds,
+ controller.snapshot().revision,
+ );
+ if (result.accepted) {
+ this.requestPump(participant.roomId);
+ }
+ return result.accepted;
+ }
+
+ observeSfuPublisherQualityEvidence(
+ participant: AuthenticatedRouteParticipant,
+ message: Extract<
+ ClientMessage,
+ { type: "sfu-publisher-quality-evidence" }
+ >,
+ ): boolean {
+ const room = this.rooms.get(participant.roomId);
+ const controller = room?.controller;
+ if (!room || !controller || participant.role !== "host") {
+ return false;
+ }
+ const operation = controller.snapshot().operation;
+ const candidateChildPeerId = operation?.childPeerId;
+ const candidateConnectionId = operation?.current?.connectionId;
+ const before = controller.snapshot().revision;
+ const input: SfuPublisherQualityEvidenceInput = {
+ hostPeerId: participant.peerId,
+ hostSessionId: participant.sessionId,
+ publicationGeneration: message.publicationGeneration,
+ routeRevision: message.routeRevision,
+ state: message.state,
+ acceptedAtMs: this.now(),
+ };
+ const result = controller.observeSfuPublisherQualityEvidence(
+ input,
+ (reservation) => this.commitReservation(reservation),
+ );
+ this.releaseResources(result.released);
+ if (
+ result.committed &&
+ candidateChildPeerId &&
+ candidateConnectionId
+ ) {
+ this.resourceWaiters.delete(participant.roomId);
+ this.options.setConnectionId(
+ participant.roomId,
+ candidateChildPeerId,
+ candidateConnectionId,
+ );
+ }
+ if (controller.snapshot().revision !== before) {
+ this.broadcastActive(participant.roomId, room);
+ }
+ this.sendRouteFailures(
+ participant.roomId,
+ result.failedPeerIds,
+ controller.snapshot().revision,
+ );
+ if (result.accepted) {
+ this.requestPump(participant.roomId);
+ }
+ return result.accepted;
+ }
+
+ resetSenderQuality(participant: AuthenticatedRouteParticipant): void {
+ const room = this.rooms.get(participant.roomId);
+ const controller = room?.controller;
+ if (!room || !controller) {
+ return;
+ }
+ const before = controller.snapshot().revision;
+ this.releaseResources(
+ controller.resetSenderQuality(
+ participant.peerId,
+ participant.sessionId,
+ this.now(),
+ ),
+ );
+ if (controller.snapshot().revision !== before) {
+ this.broadcastActive(participant.roomId, room);
+ }
+ this.requestPump(participant.roomId);
+ }
+
isActivePeerParentOf(
roomId: string,
parentPeerId: string,
@@ -503,7 +632,7 @@ export class HybridMediaRouter {
exhausted: settled.failedPeerIds.length > 0,
});
this.releaseResources(settled.released);
- if (settled.accepted) {
+ if (settled.committed !== false && settled.accepted) {
this.resourceWaiters.delete(participant.roomId);
this.options.setConnectionId(
participant.roomId,
@@ -785,13 +914,16 @@ export class HybridMediaRouter {
room: RoomRuntime,
host: AuthenticatedRouteParticipant,
): void {
+ const routePolicy = host.routePolicy;
room.controller = new RoomRouteController<RouteResource>({
hostPeerId: host.peerId,
debugRoomId: roomId,
endpointMediaCopyCapacity: this.options.endpointMediaCopyCapacity,
operationTimeoutMs:
this.options.sfuFallback?.prepareTimeoutMs ?? DEFAULT_ROUTE_OPERATION_TIMEOUT_MS,
- sfuEnabled: Boolean(this.options.sfuFallback),
+ sfuEnabled: Boolean(this.options.sfuFallback) && routePolicy?.peerOnly !== true,
+ qualityConvergenceEnabled:
+ routePolicy?.topologyOptimization === true,
});
room.controller.upsertParticipant({
peerId: host.peerId,
@@ -877,6 +1009,15 @@ export class HybridMediaRouter {
rejectionBucket: preparation.rejectionBucket,
cursor: operation.cursor,
});
+ if (operation.reason === "quality-convergence") {
+ const skipped = controller.skipCurrentCandidate(
+ guard,
+ this.now(),
+ preparation.rejectionBucket,
+ );
+ this.releaseResources(skipped.released);
+ continue;
+ }
if (preparation.rejectionBucket !== "sfu-admission") {
this.resourceWaiters.delete(roomId);
}
diff --git a/src/server/room-route-controller.ts b/src/server/room-route-controller.ts
index 537d44bd..6ac55d85 100644
--- a/src/server/room-route-controller.ts
+++ b/src/server/room-route-controller.ts
@@ -93,6 +93,7 @@ export interface ControllerOptions {
endpointMediaCopyCapacity: number;
operationTimeoutMs: number;
sfuEnabled?: boolean;
+ qualityConvergenceEnabled?: boolean;
}
const routeDebug = debuglog("screener-route");
@@ -122,6 +123,9 @@ interface Attempt<Resource> {
publicationConnectionId?: string;
reservation: CandidateReservation<Resource>;
transportConnected: boolean;
+ mediaReady: boolean;
+ senderQualityState?: "healthy" | "degraded";
+ senderQualityAcceptedAtMs?: number;
}
interface ChildOperation<Resource> {
@@ -191,6 +195,7 @@ export interface ReconcileResult<Resource> {
export interface SettleResult<Resource> {
accepted: boolean;
+ committed?: boolean;
failedPeerIds: readonly string[];
activeRevision: number;
released: readonly Resource[];
@@ -237,6 +242,53 @@ interface RouteQualityObservation {
pauseCount: number;
pauseDurationMs: number;
lastAcceptedAtMs: number;
+ lastDecodedProgressAtMs: number | null;
+}
+
+interface SenderQualityObservation {
+ childSessionId: string;
+ parentPeerId: string;
+ parentSessionId: string;
+ connectionId: string;
+ senderIdentity: string;
+ state: "healthy" | "degraded";
+ lastAcceptedAtMs: number;
+ consumedAtFactVersion?: number;
+}
+
+export interface SenderQualityEvidenceInput {
+ parentPeerId: string;
+ parentSessionId: string;
+ childPeerId: string;
+ routeRevision: number;
+ connectionId: string;
+ senderIdentity: string | null;
+ state: "unknown" | "healthy" | "degraded";
+ acceptedAtMs: number;
+}
+
+export interface SenderQualityEvidenceResult<Resource> {
+ accepted: boolean;
+ committed: boolean;
+ failedPeerIds: readonly string[];
+ activeRevision: number;
+ released: readonly Resource[];
+}
+
+interface SfuPublisherQualityObservation {
+ hostSessionId: string;
+ publicationGeneration: string;
+ state: "healthy" | "degraded";
+ lastAcceptedAtMs: number;
+}
+
+export interface SfuPublisherQualityEvidenceInput {
+ hostPeerId: string;
+ hostSessionId: string;
+ publicationGeneration: string;
+ routeRevision: number;
+ state: "unknown" | "healthy" | "degraded";
+ acceptedAtMs: number;
}
export interface RouteQualityEvidenceInput {
@@ -278,6 +330,12 @@ export class RoomRouteController<Resource = unknown> {
string,
RouteQualityObservation
>();
+ private readonly senderQualityObservations = new Map<
+ string,
+ SenderQualityObservation
+ >();
+ private readonly senderQualityBaselines = new Map<string, boolean>();
+ private sfuPublisherQualityObservation?: SfuPublisherQualityObservation;
private readonly qualityBaselinesPending = new Set<string>();
private readonly directContinuations = new Map<string, DirectContinuation>();
private sfuBootstrapIntent?: SfuBootstrapIntent;
@@ -292,6 +350,7 @@ export class RoomRouteController<Resource = unknown> {
endpointCapacity: options.endpointMediaCopyCapacity,
operationTimeoutMs: options.operationTimeoutMs,
sfuEnabled: options.sfuEnabled === true,
+ qualityConvergenceEnabled: options.qualityConvergenceEnabled === true,
});
}
@@ -373,7 +432,11 @@ export class RoomRouteController<Resource = unknown> {
? {
childOrdinal,
reason: operation.reason,
- stage: operation.current ? "first-frame" : "admission",
+ stage: operation.current?.mediaReady
+ ? "quality-proof"
+ : operation.current
+ ? "first-frame"
+ : "admission",
cursor: operation.cursor,
candidateCount: operation.candidates.length,
}
@@ -540,6 +603,7 @@ export class RoomRouteController<Resource = unknown> {
parentSessionId:
this.participants.get(edge.parentPeerId)?.sessionId ?? "",
} : { ...edge, childSessionId });
+ this.requireSenderQualityBaseline(childPeerId);
this.assertGraph();
}
@@ -692,6 +756,9 @@ export class RoomRouteController<Resource = unknown> {
if (paused) {
this.qualityObservations.clear();
this.qualityBaselinesPending.clear();
+ this.senderQualityObservations.clear();
+ this.senderQualityBaselines.clear();
+ this.sfuPublisherQualityObservation = undefined;
}
this.touchFacts();
return paused ? this.abortOperation(nowMs, "aborted") : [];
@@ -762,6 +829,7 @@ export class RoomRouteController<Resource = unknown> {
pauseCount: 0,
pauseDurationMs: 0,
lastAcceptedAtMs: input.acceptedAtMs,
+ lastDecodedProgressAtMs: null,
};
this.qualityObservations.set(input.childPeerId, observation);
}
@@ -769,7 +837,20 @@ export class RoomRouteController<Resource = unknown> {
const metrics = input.metrics;
if (
metrics.framesDecodedDelta === null ||
- metrics.framesDecodedDelta <= 0 ||
+ metrics.framesDecodedDelta <= 0
+ ) {
+ return "accepted";
+ }
+ const hadFreshDecodedProgress =
+ observation.lastDecodedProgressAtMs !== null &&
+ input.acceptedAtMs <
+ observation.lastDecodedProgressAtMs +
+ VIEWER_QUALITY_EVIDENCE_EXPIRY_MS;
+ observation.lastDecodedProgressAtMs = input.acceptedAtMs;
+ if (!hadFreshDecodedProgress && edge.kind === "sfu") {
+ this.touchFacts();
+ }
+ if (
metrics.freezeCountDelta === null ||
metrics.freezeDurationMsDelta === null ||
metrics.pauseCountDelta === null ||
@@ -809,6 +890,339 @@ export class RoomRouteController<Resource = unknown> {
return "observed";
}
+ observeSenderQualityEvidence(
+ input: SenderQualityEvidenceInput,
+ commitReservation: (
+ reservation: CandidateReservation<Resource>,
+ ) => boolean = () => true,
+ ): SenderQualityEvidenceResult<Resource> {
+ const rejected = (): SenderQualityEvidenceResult<Resource> => ({
+ accepted: false,
+ committed: false,
+ failedPeerIds: [],
+ activeRevision: this.revision,
+ released: [],
+ });
+ if (
+ this.options.qualityConvergenceEnabled !== true ||
+ this.paused ||
+ !Number.isSafeInteger(input.acceptedAtMs) ||
+ input.acceptedAtMs < 0
+ ) {
+ return rejected();
+ }
+ const parent = this.participants.get(input.parentPeerId);
+ const child = this.participants.get(input.childPeerId);
+ if (
+ !parent?.sessionId ||
+ parent.sessionId !== input.parentSessionId ||
+ !child?.sessionId ||
+ child.departureConfirmed ||
+ parent.departureConfirmed
+ ) {
+ return rejected();
+ }
+
+ const operation = this.operation;
+ const attempt = operation?.current;
+ if (
+ operation?.reason === "quality-convergence" &&
+ attempt?.tuple.kind === "peer" &&
+ operation.childPeerId === input.childPeerId &&
+ operation.childSessionId === child.sessionId &&
+ attempt.tuple.parentPeerId === input.parentPeerId &&
+ attempt.parentSessionId === input.parentSessionId &&
+ attempt.connectionId === input.connectionId &&
+ attempt.revision === input.routeRevision
+ ) {
+ return this.settleCandidateQuality(
+ operation,
+ attempt,
+ input.state,
+ input.acceptedAtMs,
+ input.senderIdentity,
+ commitReservation,
+ );
+ }
+
+ const edge = this.upstreamByViewer.get(input.childPeerId);
+ if (
+ input.routeRevision !== this.revision ||
+ edge?.kind !== "peer" ||
+ !edge.usable ||
+ !edge.physicalActive ||
+ edge.parentPeerId !== input.parentPeerId ||
+ edge.parentSessionId !== input.parentSessionId ||
+ edge.childSessionId !== child.sessionId ||
+ edge.connectionId !== input.connectionId
+ ) {
+ return rejected();
+ }
+ if (input.state === "unknown") {
+ this.senderQualityObservations.delete(input.childPeerId);
+ this.senderQualityBaselines.set(
+ input.childPeerId,
+ this.senderQualityBaselines.get(input.childPeerId) ?? true,
+ );
+ const released =
+ operation?.reason === "quality-convergence" &&
+ operation.childPeerId === input.childPeerId
+ ? this.abortOperation(input.acceptedAtMs, "aborted")
+ : [];
+ return {
+ accepted: true,
+ committed: false,
+ failedPeerIds: [],
+ activeRevision: this.revision,
+ released,
+ };
+ }
+ if (!input.senderIdentity) {
+ return rejected();
+ }
+ const previous = this.senderQualityObservations.get(input.childPeerId);
+ const sameIdentity =
+ previous?.childSessionId === child.sessionId &&
+ previous.parentPeerId === input.parentPeerId &&
+ previous.parentSessionId === input.parentSessionId &&
+ previous.connectionId === input.connectionId;
+ const sameSenderIdentity =
+ sameIdentity && previous?.senderIdentity === input.senderIdentity;
+ const senderIdentityChanged =
+ sameIdentity && previous?.senderIdentity !== input.senderIdentity;
+ const wasFreshHealthy =
+ sameSenderIdentity &&
+ previous?.state === "healthy" &&
+ input.acceptedAtMs <
+ previous.lastAcceptedAtMs + VIEWER_QUALITY_EVIDENCE_EXPIRY_MS;
+ const baselineRequired = this.senderQualityBaselines.has(
+ input.childPeerId,
+ );
+ const baselineSuppressesFact =
+ this.senderQualityBaselines.get(input.childPeerId) === true;
+ if (input.state === "healthy") {
+ this.senderQualityBaselines.delete(input.childPeerId);
+ }
+ this.senderQualityObservations.set(input.childPeerId, {
+ childSessionId: child.sessionId,
+ parentPeerId: input.parentPeerId,
+ parentSessionId: input.parentSessionId,
+ connectionId: input.connectionId,
+ senderIdentity: input.senderIdentity,
+ state: input.state,
+ lastAcceptedAtMs: input.acceptedAtMs,
+ consumedAtFactVersion:
+ (baselineRequired || senderIdentityChanged) &&
+ input.state === "degraded"
+ ? this.factVersion
+ : sameSenderIdentity &&
+ previous?.state === "degraded" &&
+ input.state === "degraded"
+ ? previous.consumedAtFactVersion
+ : undefined,
+ });
+ if (
+ input.state === "healthy" &&
+ !wasFreshHealthy &&
+ !baselineSuppressesFact
+ ) {
+ this.touchFacts();
+ }
+ if (
+ input.state === "healthy" &&
+ operation?.reason === "quality-convergence" &&
+ operation.childPeerId === input.childPeerId
+ ) {
+ const released = this.abortOperation(input.acceptedAtMs, "aborted");
+ return {
+ accepted: true,
+ committed: false,
+ failedPeerIds: [],
+ activeRevision: this.revision,
+ released,
+ };
+ }
+ return {
+ accepted: true,
+ committed: false,
+ failedPeerIds: [],
+ activeRevision: this.revision,
+ released: [],
+ };
+ }
+
+ observeSfuPublisherQualityEvidence(
+ input: SfuPublisherQualityEvidenceInput,
+ commitReservation: (
+ reservation: CandidateReservation<Resource>,
+ ) => boolean = () => true,
+ ): SenderQualityEvidenceResult<Resource> {
+ const rejected = (): SenderQualityEvidenceResult<Resource> => ({
+ accepted: false,
+ committed: false,
+ failedPeerIds: [],
+ activeRevision: this.revision,
+ released: [],
+ });
+ const host = this.participants.get(this.options.hostPeerId);
+ if (
+ this.options.qualityConvergenceEnabled !== true ||
+ this.paused ||
+ input.hostPeerId !== this.options.hostPeerId ||
+ !host?.sessionId ||
+ host.sessionId !== input.hostSessionId
+ ) {
+ return rejected();
+ }
+ const operation = this.operation;
+ const attempt = operation?.current;
+ if (
+ operation?.reason === "quality-convergence" &&
+ attempt?.tuple.kind === "sfu" &&
+ attempt.hostSessionId === input.hostSessionId &&
+ attempt.publicationGeneration === input.publicationGeneration &&
+ attempt.revision === input.routeRevision
+ ) {
+ return this.settleCandidateQuality(
+ operation,
+ attempt,
+ input.state,
+ input.acceptedAtMs,
+ input.publicationGeneration,
+ commitReservation,
+ );
+ }
+ if (
+ input.routeRevision !== this.revision ||
+ !this.hostPublication?.usable ||
+ !this.hostPublication.physicalActive ||
+ this.hostPublication.hostSessionId !== input.hostSessionId ||
+ this.hostPublication.generation !== input.publicationGeneration
+ ) {
+ return rejected();
+ }
+ if (input.state === "unknown") {
+ this.sfuPublisherQualityObservation = undefined;
+ return {
+ accepted: true,
+ committed: false,
+ failedPeerIds: [],
+ activeRevision: this.revision,
+ released: [],
+ };
+ }
+ const previous = this.sfuPublisherQualityObservation;
+ const wasFreshHealthy =
+ previous?.hostSessionId === input.hostSessionId &&
+ previous.publicationGeneration === input.publicationGeneration &&
+ previous.state === "healthy" &&
+ input.acceptedAtMs <
+ previous.lastAcceptedAtMs + VIEWER_QUALITY_EVIDENCE_EXPIRY_MS;
+ this.sfuPublisherQualityObservation = {
+ hostSessionId: input.hostSessionId,
+ publicationGeneration: input.publicationGeneration,
+ state: input.state,
+ lastAcceptedAtMs: input.acceptedAtMs,
+ };
+ if (input.state === "healthy" && !wasFreshHealthy) {
+ this.touchFacts();
+ }
+ return {
+ accepted: true,
+ committed: false,
+ failedPeerIds: [],
+ activeRevision: this.revision,
+ released: [],
+ };
+ }
+
+ private settleCandidateQuality(
+ operation: ChildOperation<Resource>,
+ attempt: Attempt<Resource>,
+ state: "unknown" | "healthy" | "degraded",
+ acceptedAtMs: number,
+ senderIdentity: string | null,
+ commitReservation: (
+ reservation: CandidateReservation<Resource>,
+ ) => boolean,
+ ): SenderQualityEvidenceResult<Resource> {
+ if (state === "unknown") {
+ attempt.senderQualityState = undefined;
+ attempt.senderQualityAcceptedAtMs = undefined;
+ return {
+ accepted: true,
+ committed: false,
+ failedPeerIds: [],
+ activeRevision: this.revision,
+ released: [],
+ };
+ }
+ if (!senderIdentity) {
+ return {
+ accepted: false,
+ committed: false,
+ failedPeerIds: [],
+ activeRevision: this.revision,
+ released: [],
+ };
+ }
+ attempt.senderQualityState = state;
+ attempt.senderQualityAcceptedAtMs = acceptedAtMs;
+ const guard = {
+ childPeerId: operation.childPeerId,
+ childSessionId: operation.childSessionId,
+ revision: attempt.revision,
+ connectionId: attempt.connectionId,
+ };
+ const settled =
+ state === "degraded"
+ ? this.candidateFailed(guard, acceptedAtMs)
+ : attempt.mediaReady
+ ? this.candidateReady(guard, acceptedAtMs, commitReservation)
+ : null;
+ return {
+ accepted: true,
+ committed: settled?.committed === true,
+ failedPeerIds: settled?.failedPeerIds ?? [],
+ activeRevision: settled?.activeRevision ?? this.revision,
+ released: settled?.released ?? [],
+ };
+ }
+
+ resetSenderQuality(
+ parentPeerId: string,
+ parentSessionId: string,
+ nowMs: number,
+ ): readonly Resource[] {
+ const parent = this.participants.get(parentPeerId);
+ if (parent?.sessionId !== parentSessionId) {
+ return [];
+ }
+ for (const [childPeerId, observation] of this.senderQualityObservations) {
+ if (
+ observation.parentPeerId === parentPeerId &&
+ observation.parentSessionId === parentSessionId
+ ) {
+ this.senderQualityObservations.delete(childPeerId);
+ this.senderQualityBaselines.set(childPeerId, true);
+ }
+ }
+ if (parentPeerId === this.options.hostPeerId) {
+ this.sfuPublisherQualityObservation = undefined;
+ }
+ const operation = this.operation;
+ const attempt = operation?.current;
+ const ownsCandidate =
+ operation?.reason === "quality-convergence" &&
+ attempt &&
+ (attempt.tuple.kind === "peer"
+ ? attempt.tuple.parentPeerId === parentPeerId &&
+ attempt.parentSessionId === parentSessionId
+ : parentPeerId === this.options.hostPeerId &&
+ attempt.hostSessionId === parentSessionId);
+ return ownsCandidate ? this.abortOperation(nowMs, "aborted") : [];
+ }
+
reconcile(nowMs: number): ReconcileResult<Resource> {
const released: Resource[] = [];
const validation = this.validateOrAdvance(nowMs);
@@ -823,6 +1237,15 @@ export class RoomRouteController<Resource = unknown> {
});
released.push(...this.abortOperation(nowMs, "aborted"));
}
+ if (
+ this.operation?.reason === "quality-convergence" &&
+ (this.hasSfuBootstrapWork() || this.selectNextChild())
+ ) {
+ this.debug("quality-convergence-preempted", {
+ child: this.debugPeer(this.operation.childPeerId),
+ });
+ released.push(...this.abortOperation(nowMs, "aborted"));
+ }
if (this.paused || this.operation) {
return {
operation: this.operationSnapshot(),
@@ -841,14 +1264,23 @@ export class RoomRouteController<Resource = unknown> {
: bootstrap
? undefined
: this.selectDirectContinuation();
+ const qualityChildPeerId =
+ routeChildPeerId || bootstrap || continuation
+ ? undefined
+ : this.selectQualityChild(nowMs);
const childPeerId =
- routeChildPeerId ?? bootstrap?.carrierPeerId ?? continuation?.childPeerId;
+ routeChildPeerId ??
+ bootstrap?.carrierPeerId ??
+ continuation?.childPeerId ??
+ qualityChildPeerId;
if (!childPeerId) return { removedPeerIds, failedPeerIds, released };
const child = this.participants.get(childPeerId)!;
const reason: RouteDemandReason = continuation
? "direct-convergence"
: bootstrap
? "sfu-bootstrap"
+ : qualityChildPeerId
+ ? "quality-convergence"
: (this.routeTimings.get(childPeerId)?.reason ??
this.routeDemandReason(childPeerId));
const demandPeerId = bootstrap?.demandPeerId ?? childPeerId;
@@ -856,7 +1288,9 @@ export class RoomRouteController<Resource = unknown> {
this.ensureDemand(demandPeerId, nowMs, reason);
let candidates = continuation
? [continuation.plan]
- : this.buildCandidates(childPeerId, bootstrap !== undefined);
+ : qualityChildPeerId
+ ? this.buildQualityCandidates(childPeerId, nowMs)
+ : this.buildCandidates(childPeerId, bootstrap !== undefined);
if (!bootstrap && !continuation && demand.sfuFirstAtNextRoute) {
const sfuIndex = candidates.findIndex(
(candidate) => candidate.tuple.kind === "sfu",
@@ -880,6 +1314,19 @@ export class RoomRouteController<Resource = unknown> {
this.directContinuations.delete(childPeerId);
continue;
}
+ if (reason === "quality-convergence") {
+ const observation = this.senderQualityObservations.get(childPeerId);
+ if (observation) {
+ observation.consumedAtFactVersion = this.factVersion;
+ }
+ this.finishTiming(
+ childPeerId,
+ nowMs,
+ this.currentFinalRoute(childPeerId),
+ "candidate-failed",
+ );
+ continue;
+ }
if (reason === "sfu-bootstrap") {
const failedDemandPeerId = this.completeSfuBootstrapCarrier(
childPeerId,
@@ -968,6 +1415,26 @@ export class RoomRouteController<Resource = unknown> {
failedPeerIds: failedPeerIdsFrom(validation),
};
}
+ if (
+ operation.reason === "quality-convergence" &&
+ plan.tuple.kind === "peer" &&
+ !this.qualitySourcePathHealthy(plan.tuple.parentPeerId, input.nowMs)
+ ) {
+ this.noteRejection(operation.demandPeerId, "stale");
+ operation.cursor += 1;
+ this.clearCandidateTiming(operation.demandPeerId);
+ const advanced = this.validateOrAdvance(input.nowMs);
+ return {
+ accepted: true,
+ operation: this.operationSnapshot(),
+ released: [
+ ...validation.released,
+ ...reservationResources(input.reservation),
+ ...advanced.released,
+ ],
+ failedPeerIds: failedPeerIdsFrom(validation, advanced),
+ };
+ }
if (plan.endpointTransition.kind === "bounded-gap") {
return {
accepted: false,
@@ -1003,6 +1470,16 @@ export class RoomRouteController<Resource = unknown> {
if (tuple.kind === "sfu" && tuple.publication !== "reuse" && !input.publicationConnectionId) {
throw new Error("SFU publication candidate needs an ingress connection identity");
}
+ const initialSfuQuality =
+ publicationGeneration &&
+ this.sfuPublisherQualityObservation?.publicationGeneration ===
+ publicationGeneration &&
+ this.sfuPublisherQualityObservation.hostSessionId === hostSessionId &&
+ input.nowMs <
+ this.sfuPublisherQualityObservation.lastAcceptedAtMs +
+ VIEWER_QUALITY_EVIDENCE_EXPIRY_MS
+ ? this.sfuPublisherQualityObservation
+ : undefined;
operation.current = {
tuple,
revision: this.allocateRevision(),
@@ -1017,6 +1494,13 @@ export class RoomRouteController<Resource = unknown> {
publicationConnectionId: input.publicationConnectionId,
reservation: input.reservation,
transportConnected: false,
+ mediaReady: false,
+ ...(tuple.kind === "sfu" && initialSfuQuality
+ ? {
+ senderQualityState: initialSfuQuality.state,
+ senderQualityAcceptedAtMs: initialSfuQuality.lastAcceptedAtMs,
+ }
+ : {}),
};
this.debug("candidate-started", {
child: this.debugPeer(operation.childPeerId),
@@ -1188,6 +1672,54 @@ export class RoomRouteController<Resource = unknown> {
released: validation.released,
};
}
+ if (operation.reason === "quality-convergence") {
+ attempt.mediaReady = true;
+ const currentEdge = this.upstreamByViewer.get(operation.childPeerId);
+ if (
+ !currentEdge ||
+ this.senderQualityState(
+ operation.childPeerId,
+ currentEdge,
+ nowMs,
+ ) !== "degraded"
+ ) {
+ return {
+ accepted: true,
+ committed: false,
+ failedPeerIds: failedPeerIdsFrom(validation),
+ activeRevision: this.revision,
+ released: [
+ ...validation.released,
+ ...this.abortOperation(nowMs, "aborted"),
+ ],
+ };
+ }
+ if (attempt.senderQualityState === undefined) {
+ return {
+ accepted: true,
+ committed: false,
+ failedPeerIds: failedPeerIdsFrom(validation),
+ activeRevision: this.revision,
+ released: validation.released,
+ };
+ }
+ if (
+ attempt.senderQualityAcceptedAtMs === undefined ||
+ nowMs >=
+ attempt.senderQualityAcceptedAtMs +
+ VIEWER_QUALITY_EVIDENCE_EXPIRY_MS ||
+ (attempt.tuple.kind === "peer" &&
+ !this.qualitySourcePathHealthy(
+ attempt.tuple.parentPeerId,
+ nowMs,
+ ))
+ ) {
+ return this.candidateFailed(guard, nowMs);
+ }
+ if (attempt.senderQualityState === "degraded") {
+ return this.candidateFailed(guard, nowMs);
+ }
+ }
if (!commitReservation(attempt.reservation)) {
this.debug("candidate-commit-rejected", {
child: this.debugPeer(operation.childPeerId),
@@ -1233,6 +1765,7 @@ export class RoomRouteController<Resource = unknown> {
}
return {
accepted: true,
+ committed: true,
failedPeerIds: failedPeerIdsFrom(validation),
activeRevision: this.revision,
released,
@@ -1338,6 +1871,9 @@ export class RoomRouteController<Resource = unknown> {
this.upstreamByViewer.clear();
this.qualityObservations.clear();
this.qualityBaselinesPending.clear();
+ this.senderQualityObservations.clear();
+ this.senderQualityBaselines.clear();
+ this.sfuPublisherQualityObservation = undefined;
this.hostPublication = null;
this.participants.clear();
this.routeTimings.clear();
@@ -1383,6 +1919,7 @@ export class RoomRouteController<Resource = unknown> {
if (nowMs >= operation.deadlineAtMs) {
const directConvergence = operation.reason === "direct-convergence";
const sfuBootstrap = operation.reason === "sfu-bootstrap";
+ const qualityConvergence = operation.reason === "quality-convergence";
if (directConvergence) {
this.consumeDirectContinuationCandidate(operation);
}
@@ -1400,17 +1937,21 @@ export class RoomRouteController<Resource = unknown> {
const bootstrapAvailable =
!directConvergence &&
!sfuBootstrap &&
+ !qualityConvergence &&
!factsChanged &&
this.bootstrapCandidateAvailable(operation.demandPeerId);
const exhausted = sfuBootstrap
? failedBootstrapDemand !== undefined
- : !directConvergence && !factsChanged && !bootstrapAvailable;
+ : !directConvergence &&
+ !qualityConvergence &&
+ !factsChanged &&
+ !bootstrapAvailable;
if (bootstrapAvailable) this.stageSfuBootstrap(operation);
if (!sfuBootstrap) {
this.finishTiming(
operation.demandPeerId,
nowMs,
- directConvergence
+ directConvergence || qualityConvergence
? this.currentFinalRoute(operation.demandPeerId)
: exhausted
? "failed"
@@ -1418,9 +1959,20 @@ export class RoomRouteController<Resource = unknown> {
factsChanged ? "stale" : "operation-deadline",
);
}
+ if (qualityConvergence) {
+ const observation = this.senderQualityObservations.get(
+ operation.childPeerId,
+ );
+ if (observation) {
+ observation.consumedAtFactVersion = this.factVersion;
+ }
+ }
this.blockAndClear(
operation,
- !directConvergence && !sfuBootstrap && !factsChanged,
+ !directConvergence &&
+ !sfuBootstrap &&
+ !qualityConvergence &&
+ !factsChanged,
released,
revisionAdvanced,
);
@@ -1429,7 +1981,8 @@ export class RoomRouteController<Resource = unknown> {
}
return {
...result,
- exhausted: directConvergence ? undefined : exhausted,
+ exhausted:
+ directConvergence || qualityConvergence ? undefined : exhausted,
exhaustedChildPeerId: failedBootstrapDemand ??
(exhausted ? operation.demandPeerId : undefined),
expired: true,
@@ -1491,6 +2044,7 @@ export class RoomRouteController<Resource = unknown> {
if (operation.cursor < operation.candidates.length) return result;
const directConvergence = operation.reason === "direct-convergence";
const sfuBootstrap = operation.reason === "sfu-bootstrap";
+ const qualityConvergence = operation.reason === "quality-convergence";
const factsChanged = operation.builtAtFactVersion !== this.factVersion;
const rejectionBucket = factsChanged
? "stale"
@@ -1509,17 +2063,21 @@ export class RoomRouteController<Resource = unknown> {
const bootstrapAvailable =
!directConvergence &&
!sfuBootstrap &&
+ !qualityConvergence &&
!factsChanged &&
this.bootstrapCandidateAvailable(operation.demandPeerId);
const exhausted = sfuBootstrap
? failedBootstrapDemand !== undefined
- : !directConvergence && !factsChanged && !bootstrapAvailable;
+ : !directConvergence &&
+ !qualityConvergence &&
+ !factsChanged &&
+ !bootstrapAvailable;
if (bootstrapAvailable) this.stageSfuBootstrap(operation);
if (!sfuBootstrap) {
this.finishTiming(
operation.demandPeerId,
nowMs,
- directConvergence
+ directConvergence || qualityConvergence
? this.currentFinalRoute(operation.demandPeerId)
: exhausted
? "failed"
@@ -1527,13 +2085,25 @@ export class RoomRouteController<Resource = unknown> {
rejectionBucket,
);
}
+ if (qualityConvergence) {
+ const observation = this.senderQualityObservations.get(
+ operation.childPeerId,
+ );
+ if (observation) {
+ observation.consumedAtFactVersion = this.factVersion;
+ }
+ }
this.blockAndClear(
operation,
- !directConvergence && !sfuBootstrap && !factsChanged,
+ !directConvergence &&
+ !sfuBootstrap &&
+ !qualityConvergence &&
+ !factsChanged,
released,
this.revision !== activeRevisionAtStart,
);
- result.exhausted = directConvergence ? undefined : exhausted;
+ result.exhausted =
+ directConvergence || qualityConvergence ? undefined : exhausted;
if (failedBootstrapDemand) {
result.exhaustedChildPeerId = failedBootstrapDemand;
} else if (exhausted) {
@@ -1617,6 +2187,23 @@ export class RoomRouteController<Resource = unknown> {
this.directContinuations.delete(operation.childPeerId);
}
}
+ const producerPeerIds = new Set<string>();
+ if (old?.kind === "peer") {
+ producerPeerIds.add(old.parentPeerId);
+ }
+ producerPeerIds.add(
+ attempt.tuple.kind === "peer"
+ ? attempt.tuple.parentPeerId
+ : this.options.hostPeerId,
+ );
+ for (const producerPeerId of producerPeerIds) {
+ for (const childPeerId of this.childrenOf(producerPeerId)) {
+ this.senderQualityObservations.delete(childPeerId);
+ this.senderQualityBaselines.set(childPeerId, true);
+ }
+ }
+ this.requireSenderQualityBaseline(operation.childPeerId, true);
+ this.senderQualityBaselines.set(operation.childPeerId, false);
this.revision = attempt.revision;
this.operation = undefined;
this.touchFacts();
@@ -1701,6 +2288,149 @@ export class RoomRouteController<Resource = unknown> {
this.candidateValid(childPeerId, candidate));
}
+ private senderQualityState(
+ childPeerId: string,
+ edge: CommittedEdge<Resource>,
+ nowMs: number,
+ ): "unknown" | "healthy" | "degraded" {
+ if (edge.kind !== "peer") {
+ return this.sourceUsableForQuality(edge) ? "healthy" : "unknown";
+ }
+ const observation = this.senderQualityObservations.get(childPeerId);
+ const child = this.participants.get(childPeerId);
+ return observation &&
+ nowMs < observation.lastAcceptedAtMs + VIEWER_QUALITY_EVIDENCE_EXPIRY_MS &&
+ child?.sessionId === observation.childSessionId &&
+ edge.childSessionId === observation.childSessionId &&
+ edge.parentPeerId === observation.parentPeerId &&
+ edge.parentSessionId === observation.parentSessionId &&
+ edge.connectionId === observation.connectionId &&
+ this.sourceUsableForQuality(edge)
+ ? observation.state
+ : "unknown";
+ }
+
+ private sfuPublisherQualityState(
+ publicationGeneration: string,
+ nowMs: number,
+ ): "unknown" | "healthy" | "degraded" {
+ const observation = this.sfuPublisherQualityObservation;
+ return observation &&
+ observation.publicationGeneration === publicationGeneration &&
+ observation.hostSessionId === this.hostPublication?.hostSessionId &&
+ nowMs < observation.lastAcceptedAtMs + VIEWER_QUALITY_EVIDENCE_EXPIRY_MS
+ ? observation.state
+ : "unknown";
+ }
+
+ private qualitySourcePathHealthy(peerId: string, nowMs: number): boolean {
+ if (peerId === this.options.hostPeerId) {
+ return true;
+ }
+ const seen = new Set<string>();
+ while (!seen.has(peerId)) {
+ seen.add(peerId);
+ const edge = this.upstreamByViewer.get(peerId);
+ if (!edge?.usable || !edge.physicalActive) {
+ return false;
+ }
+ if (edge.kind === "sfu") {
+ return (
+ this.sourceUsableForQuality(edge) &&
+ this.decodedProgressFresh(peerId, edge, nowMs) &&
+ this.sfuPublisherQualityState(
+ edge.publicationGeneration,
+ nowMs,
+ ) === "healthy"
+ );
+ }
+ if (this.senderQualityState(peerId, edge, nowMs) !== "healthy") {
+ return false;
+ }
+ if (edge.parentPeerId === this.options.hostPeerId) {
+ return true;
+ }
+ peerId = edge.parentPeerId;
+ }
+ return false;
+ }
+
+ private decodedProgressFresh(
+ childPeerId: string,
+ edge: CommittedEdge<Resource>,
+ nowMs: number,
+ ): boolean {
+ const observation = this.qualityObservations.get(childPeerId);
+ const participant = this.participants.get(childPeerId);
+ return Boolean(
+ observation &&
+ observation.lastDecodedProgressAtMs !== null &&
+ nowMs <
+ observation.lastDecodedProgressAtMs +
+ VIEWER_QUALITY_EVIDENCE_EXPIRY_MS &&
+ participant?.sessionId === observation.childSessionId &&
+ edge.childSessionId === observation.childSessionId &&
+ edge.connectionId === observation.connectionId &&
+ this.qualityObservationMatchesEdge(observation, edge) &&
+ this.sourceUsableForQuality(edge),
+ );
+ }
+
+ private buildQualityCandidates(
+ childPeerId: string,
+ nowMs: number,
+ ): CandidatePlan[] {
+ const current = this.upstreamByViewer.get(childPeerId);
+ if (current?.kind !== "peer") {
+ return [];
+ }
+ const currentKey = edgeTupleKey(current);
+ const candidates = this.buildCandidates(childPeerId, false).filter(
+ (candidate) =>
+ candidate.endpointTransition.kind !== "bounded-gap" &&
+ tupleKey(candidate.tuple) !== currentKey &&
+ (candidate.tuple.kind === "peer"
+ ? this.qualitySourcePathHealthy(candidate.tuple.parentPeerId, nowMs)
+ : candidate.tuple.publication !== "reuse" ||
+ Boolean(
+ this.hostPublication &&
+ this.sfuPublisherQualityState(
+ this.hostPublication.generation,
+ nowMs,
+ ) === "healthy",
+ )),
+ );
+ const peers = candidates.filter(
+ (candidate) => candidate.tuple.kind === "peer",
+ );
+ const sfu =
+ current.parentPeerId === this.options.hostPeerId
+ ? candidates.filter((candidate) => candidate.tuple.kind === "sfu")
+ : [];
+ return [...peers, ...sfu];
+ }
+
+ private selectQualityChild(nowMs: number): string | undefined {
+ if (this.options.qualityConvergenceEnabled !== true) {
+ return undefined;
+ }
+ return this.availableViewers()
+ .filter(({ peerId }) => {
+ const edge = this.upstreamByViewer.get(peerId);
+ const observation = this.senderQualityObservations.get(peerId);
+ return Boolean(
+ edge?.kind === "peer" &&
+ observation?.consumedAtFactVersion !== this.factVersion &&
+ this.senderQualityState(peerId, edge, nowMs) === "degraded",
+ );
+ })
+ .sort(
+ (left, right) =>
+ this.depth(left.peerId) - this.depth(right.peerId) ||
+ compareParticipant(left, right),
+ )[0]?.peerId;
+ }
+
private selectNextChild(): string | undefined {
const viewers = this.availableViewers();
const departedParent = viewers.find(({ peerId }) => {
@@ -2252,6 +2982,16 @@ export class RoomRouteController<Resource = unknown> {
}
private advanceActiveRevision(operation: ChildOperation<Resource>): void {
+ if (operation.reason === "quality-convergence" && operation.current) {
+ const producerPeerId =
+ operation.current.tuple.kind === "peer"
+ ? operation.current.tuple.parentPeerId
+ : this.options.hostPeerId;
+ for (const childPeerId of this.childrenOf(producerPeerId)) {
+ this.senderQualityObservations.delete(childPeerId);
+ this.senderQualityBaselines.set(childPeerId, true);
+ }
+ }
this.revision = this.allocateRevision();
operation.baseRevision = this.revision;
}
@@ -2411,7 +3151,12 @@ export class RoomRouteController<Resource = unknown> {
}
private foregroundSfuIndex(operation: ChildOperation<Resource>): number {
- if (operation.reason === "direct-convergence") return -1;
+ if (
+ operation.reason === "direct-convergence" ||
+ operation.reason === "quality-convergence"
+ ) {
+ return -1;
+ }
const index = operation.candidates.findIndex(
(candidate, candidateIndex) =>
candidateIndex >= operation.cursor && candidate.tuple.kind === "sfu",
@@ -2662,15 +3407,35 @@ export class RoomRouteController<Resource = unknown> {
: this.descendantsOf(peerId).add(peerId);
affected.forEach((childPeerId) => {
this.qualityObservations.delete(childPeerId);
+ this.senderQualityObservations.delete(childPeerId);
+ this.senderQualityBaselines.delete(childPeerId);
if (this.upstreamByViewer.has(childPeerId)) {
this.qualityBaselinesPending.add(childPeerId);
+ this.senderQualityBaselines.set(childPeerId, true);
} else {
this.qualityBaselinesPending.delete(childPeerId);
+ this.senderQualityBaselines.delete(childPeerId);
}
});
}
+ private requireSenderQualityBaseline(
+ peerId: string,
+ suppressFact = false,
+ ): void {
+ for (const childPeerId of this.descendantsOf(peerId).add(peerId)) {
+ if (this.upstreamByViewer.has(childPeerId)) {
+ this.senderQualityObservations.delete(childPeerId);
+ this.senderQualityBaselines.set(
+ childPeerId,
+ suppressFact || this.senderQualityBaselines.get(childPeerId) === true,
+ );
+ }
+ }
+ }
+
private clearSfuQuality(): void {
+ this.sfuPublisherQualityObservation = undefined;
for (const [childPeerId, edge] of this.upstreamByViewer) {
if (edge.kind === "sfu") {
this.clearQualityForParticipant(childPeerId);
diff --git a/src/server/signaling.ts b/src/server/signaling.ts
index b9506520..25a1291c 100644
--- a/src/server/signaling.ts
+++ b/src/server/signaling.ts
@@ -8,6 +8,7 @@ import {
DEFAULT_HOST_DISPLAY_NAME_PREFIX,
DEFAULT_VIEWER_DISPLAY_NAME,
DEFAULT_QUALITY_SETTINGS,
+ DEFAULT_ROUTE_POLICY,
MAX_SIGNAL_BYTES,
MAX_VIEWER_QUALITY_EVIDENCE_BYTES,
SIGNAL_CLOSE_CODES,
@@ -17,6 +18,7 @@ import {
type CodeEntryPolicy,
type ClientMessage,
type QualitySettings,
+ type RoutePolicy,
type RoomAccessUpdateRequest,
type RoomAccessUpdateResponse,
type Role,
@@ -83,6 +85,11 @@ interface ViewerMediaReadyState {
sfuPublicationGeneration: string;
}
+interface SenderQualityRateWindow {
+ startedAtMs: number;
+ count: number;
+}
+
export interface SignalingOptions {
server: HttpServer;
roomStore: RoomStore;
@@ -118,11 +125,16 @@ export class SignalingServer {
ViewerQualityEvidenceGate
>();
private readonly viewerQualityEvidenceAttemptAtMs = new Map<string, number>();
+ private readonly senderQualityRateBySession = new Map<
+ string,
+ SenderQualityRateWindow
+ >();
private readonly viewerMediaReadyByRoom = new Map<
string,
Map<string, ViewerMediaReadyState>
>();
private readonly qualitySettingsByRoom = new Map<string, QualitySettings>();
+ private readonly routePolicyByRoom = new Map<string, RoutePolicy>();
private readonly shareGenerationsByRoom = new Map<string, string>();
private readonly pausedShareGenerationsByRoom = new Map<string, string>();
private readonly deferredViewerPresenceRooms = new Set<string>();
@@ -252,7 +264,9 @@ export class SignalingServer {
}
this.viewerQualityEvidenceGates.clear();
this.viewerQualityEvidenceAttemptAtMs.clear();
+ this.senderQualityRateBySession.clear();
this.viewerMediaReadyByRoom.clear();
+ this.routePolicyByRoom.clear();
this.shareGenerationsByRoom.clear();
this.pausedShareGenerationsByRoom.clear();
this.ordinaryActiveHostChildrenByRoom.clear();
@@ -577,6 +591,27 @@ export class SignalingServer {
});
}
}
+ if (
+ currentGeneration !== shareGeneration ||
+ !this.routePolicyByRoom.has(participant.roomId)
+ ) {
+ const routePolicy = {
+ ...(message.routePolicy ?? DEFAULT_ROUTE_POLICY),
+ };
+ this.routePolicyByRoom.set(participant.roomId, routePolicy);
+ for (const viewer of this.options.roomStore.getConnectedViewers(
+ participant.roomId,
+ )) {
+ this.sendToSession(viewer.sessionId, {
+ type: "route-policy",
+ shareGeneration,
+ routePolicy,
+ ...(this.options.sfuFallback && !routePolicy.peerOnly
+ ? { sfuStandbyUrl: this.options.sfuFallback.url }
+ : {}),
+ });
+ }
+ }
this.shareGenerationsByRoom.set(participant.roomId, shareGeneration);
if (
message.sharingPaused === true ||
@@ -621,6 +656,13 @@ export class SignalingServer {
role: participant.role,
peerId: participant.peerId,
sessionId: state.sessionId,
+ ...(participant.role === "host"
+ ? {
+ routePolicy:
+ this.routePolicyByRoom.get(participant.roomId) ??
+ DEFAULT_ROUTE_POLICY,
+ }
+ : {}),
};
let hybridState;
try {
@@ -687,17 +729,23 @@ export class SignalingServer {
...authenticatedMessageBase,
role: "viewer" as const,
};
+ const routePolicy =
+ this.routePolicyByRoom.get(participant.roomId) ?? DEFAULT_ROUTE_POLICY;
+ const hasRoutePolicy = this.routePolicyByRoom.has(participant.roomId);
if (hybridState) {
this.send(socket, {
...authenticatedMessage,
mediaMode: "peer-assisted",
+ shareGeneration:
+ this.shareGenerationsByRoom.get(participant.roomId) ?? null,
mediaAssignment: hybridState.mediaAssignment,
routeRevision: hybridState.routeRevision,
routeAssignment: hybridState.routeAssignment,
qualitySettings:
this.qualitySettingsByRoom.get(participant.roomId) ??
DEFAULT_QUALITY_SETTINGS,
- ...(this.options.sfuFallback
+ routePolicy,
+ ...(this.options.sfuFallback && hasRoutePolicy && !routePolicy.peerOnly
? { sfuStandbyUrl: this.options.sfuFallback.url }
: {}),
});
@@ -974,6 +1022,25 @@ export class SignalingServer {
case "viewer-quality-evidence":
this.handleViewerQualityEvidence(socket, authenticated, message);
return;
+ case "sender-quality-evidence":
+ this.handleSenderQualityEvidence(socket, authenticated, message);
+ return;
+ case "sfu-publisher-quality-evidence":
+ this.handleSfuPublisherQualityEvidence(socket, authenticated, message);
+ return;
+ case "reset-sender-quality":
+ if (this.isHybridMediaEnabled()) {
+ const state = this.socketStates.get(socket);
+ if (state?.authenticated === authenticated) {
+ this.hybridMediaRouter!.resetSenderQuality({
+ roomId: authenticated.roomId,
+ role: authenticated.role,
+ peerId: authenticated.peerId,
+ sessionId: state.sessionId,
+ });
+ }
+ }
+ return;
case "set-display-name":
if (
authenticated.role === "host" &&
@@ -1272,6 +1339,87 @@ export class SignalingServer {
}
}
+ private handleSenderQualityEvidence(
+ socket: WebSocket,
+ source: AuthenticatedSession,
+ message: Extract<ClientMessage, { type: "sender-quality-evidence" }>,
+ ): void {
+ if (!this.isHybridMediaEnabled() || source.peerId === message.childPeerId) {
+ return;
+ }
+ const state = this.socketStates.get(socket);
+ if (!state || state.authenticated !== source) {
+ return;
+ }
+ const now = this.now();
+ if (!this.consumeSenderQualityBudget(state.sessionId, now)) {
+ return;
+ }
+ this.hybridMediaRouter!.observeSenderQualityEvidence(
+ {
+ roomId: source.roomId,
+ role: source.role,
+ peerId: source.peerId,
+ sessionId: state.sessionId,
+ },
+ message,
+ );
+ }
+
+ private handleSfuPublisherQualityEvidence(
+ socket: WebSocket,
+ source: AuthenticatedSession,
+ message: Extract<
+ ClientMessage,
+ { type: "sfu-publisher-quality-evidence" }
+ >,
+ ): void {
+ if (!this.isHybridMediaEnabled() || source.role !== "host") {
+ return;
+ }
+ const state = this.socketStates.get(socket);
+ if (!state || state.authenticated !== source) {
+ return;
+ }
+ const now = this.now();
+ if (!this.consumeSenderQualityBudget(state.sessionId, now)) {
+ return;
+ }
+ this.hybridMediaRouter!.observeSfuPublisherQualityEvidence(
+ {
+ roomId: source.roomId,
+ role: source.role,
+ peerId: source.peerId,
+ sessionId: state.sessionId,
+ },
+ message,
+ );
+ }
+
+ private consumeSenderQualityBudget(
+ sessionId: string,
+ nowMs: number,
+ ): boolean {
+ const maximumReports =
+ Math.min(this.options.endpointMediaCopyCapacity + 1, 3) * 2;
+ const current = this.senderQualityRateBySession.get(sessionId);
+ if (
+ !current ||
+ nowMs - current.startedAtMs >= VIEWER_QUALITY_EVIDENCE_INTERVAL_MS
+ ) {
+ this.senderQualityRateBySession.set(sessionId, {
+ startedAtMs: nowMs,
+ count: 1,
+ });
+ return true;
+ }
+ if (current.count >= maximumReports) {
+ return false;
+ }
+ current.count += 1;
+ return true;
+ }
+
private routeSignal(
sourceSocket: WebSocket,
source: AuthenticatedSession,
@@ -1473,6 +1621,7 @@ export class SignalingServer {
return;
}
clearTimeout(state.authenticationTimer);
+ this.senderQualityRateBySession.delete(state.sessionId);
this.socketStates.delete(socket);
if (this.socketsBySessionId.get(state.sessionId) === socket) {
this.socketsBySessionId.delete(state.sessionId);
@@ -1559,6 +1708,7 @@ export class SignalingServer {
private stopSharing(roomId: string): void {
this.qualitySettingsByRoom.delete(roomId);
+ this.routePolicyByRoom.delete(roomId);
this.pausedShareGenerationsByRoom.delete(roomId);
this.clearRoomConnectionIds(roomId);
if (this.isHybridMediaEnabled()) {
@@ -1590,6 +1740,7 @@ export class SignalingServer {
this.hybridMediaRouter!.deleteRoom(closed.roomId);
}
this.qualitySettingsByRoom.delete(closed.roomId);
+ this.routePolicyByRoom.delete(closed.roomId);
this.shareGenerationsByRoom.delete(closed.roomId);
this.pausedShareGenerationsByRoom.delete(closed.roomId);
for (const sessionId of closed.sessionIds) {
@@ -1611,6 +1762,7 @@ export class SignalingServer {
this.hybridMediaRouter!.deleteRoom(expired.roomId);
}
this.qualitySettingsByRoom.delete(expired.roomId);
+ this.routePolicyByRoom.delete(expired.roomId);
this.shareGenerationsByRoom.delete(expired.roomId);
this.pausedShareGenerationsByRoom.delete(expired.roomId);
for (const sessionId of expired.sessionIds) {
diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts
index e52d02c2..f19bc85c 100644
--- a/src/shared/protocol.ts
+++ b/src/shared/protocol.ts
@@ -6,7 +6,7 @@ import { isCanonicalVideoCodecEvidence } from "./video-codec-evidence.js";
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-v13";
+export const SIGNALING_PROTOCOL = "screener-v14";
export const SIGNAL_CLOSE_CODES = {
serviceRestart: 1012,
sessionReplaced: 4001,
@@ -213,6 +213,18 @@ export const DEFAULT_QUALITY_SETTINGS = {
screenAudioQuality: "music",
} as const satisfies QualitySettings;
+export const routePolicySchema = z
+ .object({
+ peerOnly: z.boolean(),
+ topologyOptimization: z.boolean(),
+ })
+ .strict();
+export type RoutePolicy = z.infer<typeof routePolicySchema>;
+export const DEFAULT_ROUTE_POLICY = {
+ peerOnly: false,
+ topologyOptimization: false,
+} as const satisfies RoutePolicy;
+
export const relayDownstreamEdgesSchema = z
.number()
.int()
@@ -348,6 +360,7 @@ export const routeDemandReasonSchema = z.enum([
"capacity-reduction",
"sfu-bootstrap",
"direct-convergence",
+ "quality-convergence",
]);
export type RouteDemandReason = z.infer<typeof routeDemandReasonSchema>;
@@ -441,7 +454,7 @@ const routeDiagnosticOperationSchema = z
.object({
childOrdinal: routeDiagnosticOrdinalSchema,
reason: routeDemandReasonSchema,
- stage: z.enum(["admission", "first-frame"]),
+ stage: z.enum(["admission", "first-frame", "quality-proof"]),
cursor: z.number().int().min(0).max(MAX_VIEWERS_PER_ROOM_LIMIT),
candidateCount: z.number().int().min(1).max(MAX_VIEWERS_PER_ROOM_LIMIT + 1),
})
@@ -642,6 +655,40 @@ export const viewerQualityEvidenceMessageSchema = z
})
.strict();
+export const senderQualityEvidenceMessageSchema = z
+ .object({
+ type: z.literal("sender-quality-evidence"),
+ childPeerId: opaqueIdSchema,
+ connectionId: opaqueIdSchema,
+ rtpStatsId: z.string().min(1).max(256).nullable(),
+ trackIdentifier: z.string().min(1).max(256).nullable(),
+ routeRevision: mediaRouteRevisionSchema,
+ state: z.enum(["unknown", "healthy", "degraded"]),
+ })
+ .strict()
+ .superRefine((message, context) => {
+ if (
+ (message.state !== "unknown" &&
+ (message.rtpStatsId === null ||
+ message.trackIdentifier === null))
+ ) {
+ context.addIssue({
+ code: "custom",
+ message: "Known sender quality needs exact RTP identity",
+ path: ["rtpStatsId"],
+ });
+ }
+ });
+
+export const sfuPublisherQualityEvidenceMessageSchema = z
+ .object({
+ type: z.literal("sfu-publisher-quality-evidence"),
+ publicationGeneration: opaqueIdSchema,
+ routeRevision: mediaRouteRevisionSchema,
+ state: z.enum(["unknown", "healthy", "degraded"]),
+ })
+ .strict();
+
const authenticateMessageSchema = z.discriminatedUnion("role", [
z
.object({
@@ -654,6 +701,7 @@ const authenticateMessageSchema = z.discriminatedUnion("role", [
shareGeneration: opaqueIdSchema.optional(),
sharingPaused: z.boolean().optional(),
qualitySettings: qualitySettingsSchema.optional(),
+ routePolicy: routePolicySchema.default(DEFAULT_ROUTE_POLICY),
viewerPresence: z.literal(true).optional(),
displayName: displayNameSchema.optional(),
})
@@ -750,6 +798,9 @@ export const clientMessageSchema = z.union([
.strict(),
z.object({ type: z.literal("request-route-diagnostic") }).strict(),
viewerQualityEvidenceMessageSchema,
+ senderQualityEvidenceMessageSchema,
+ sfuPublisherQualityEvidenceMessageSchema,
+ z.object({ type: z.literal("reset-sender-quality") }).strict(),
z
.object({
type: z.literal("set-display-name"),
@@ -820,10 +871,12 @@ const authenticatedViewerMessageShape = {
const peerAssistedAuthenticatedShape = {
mediaMode: z.literal("peer-assisted"),
+ shareGeneration: opaqueIdSchema.nullable(),
mediaAssignment: mediaAssignmentSchema,
routeRevision: mediaRouteRevisionSchema,
routeAssignment: participantRouteAssignmentSchema,
qualitySettings: qualitySettingsSchema,
+ routePolicy: routePolicySchema,
sfuStandbyUrl: liveKitWebSocketUrlSchema.optional(),
};
@@ -948,6 +1001,14 @@ export const serverMessageSchema = z.union([
qualitySettings: qualitySettingsSchema,
})
.strict(),
+ z
+ .object({
+ type: z.literal("route-policy"),
+ shareGeneration: opaqueIdSchema,
+ routePolicy: routePolicySchema,
+ sfuStandbyUrl: liveKitWebSocketUrlSchema.optional(),
+ })
+ .strict(),
z
.object({
type: z.literal("pause-sharing-source"),
diff --git a/tests/client-state.test.ts b/tests/client-state.test.ts
index efcd2048..e5fa516e 100644
--- a/tests/client-state.test.ts
+++ b/tests/client-state.test.ts
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
+ DEFAULT_ROUTE_POLICY,
SIGNALING_PROTOCOL,
type QualitySettings,
} from "../src/shared/protocol.ts";
@@ -872,6 +873,7 @@ describe("client signaling recovery policy", () => {
role: "host",
token: "h".repeat(43),
clientId: "host-client",
+ routePolicy: DEFAULT_ROUTE_POLICY,
shareGeneration: "share_generation_12345678",
sharingPaused: true,
},
@@ -891,7 +893,7 @@ describe("client signaling recovery policy", () => {
socket.dispatchEvent(new Event("open"));
receive(socket, {
type: "authenticated",
- protocol: "screener-v13",
+ protocol: SIGNALING_PROTOCOL,
role: "host",
peerId: "host_12345678",
roomExpiresAt: null,
@@ -927,7 +929,7 @@ describe("client signaling recovery policy", () => {
});
receive(sockets[1]!, {
type: "authenticated",
- protocol: "screener-v13",
+ protocol: SIGNALING_PROTOCOL,
role: "host",
peerId: "host_12345678",
roomExpiresAt: null,
@@ -1010,6 +1012,7 @@ describe("client signaling recovery policy", () => {
role: "host",
token: "h".repeat(43),
clientId: "host-client",
+ routePolicy: DEFAULT_ROUTE_POLICY,
shareGeneration,
qualitySettings: initialQuality,
},
@@ -1054,6 +1057,7 @@ describe("client signaling recovery policy", () => {
viewerPasswordEnabled: false,
viewerAuthorizationGeneration: "viewer_generation_12345678",
mediaMode: "peer-assisted",
+ shareGeneration,
mediaAssignment: { parentPeerId: null, childPeerIds: [] },
routeRevision: 1,
routeAssignment: {
@@ -1062,6 +1066,7 @@ describe("client signaling recovery policy", () => {
sfuPublicationGeneration: null,
},
qualitySettings,
+ routePolicy: DEFAULT_ROUTE_POLICY,
}),
});
socket.dispatchEvent(event);
@@ -1148,6 +1153,7 @@ describe("client signaling recovery policy", () => {
role: "host",
token: "h".repeat(43),
clientId: "host-client",
+ routePolicy: DEFAULT_ROUTE_POLICY,
},
{
onMessage,
@@ -1166,7 +1172,7 @@ describe("client signaling recovery policy", () => {
socket.dispatchEvent(new Event("open"));
receive(socket, {
type: "authenticated",
- protocol: "screener-v13",
+ protocol: SIGNALING_PROTOCOL,
role: "host",
peerId: "host_12345678",
roomExpiresAt: null,
@@ -1292,7 +1298,7 @@ describe("client signaling recovery policy", () => {
sockets[0]!.dispatchEvent(new Event("open"));
receive({
type: "authenticated",
- protocol: "screener-v13",
+ protocol: SIGNALING_PROTOCOL,
role: "viewer",
peerId: "viewer_12345678",
roomExpiresAt: null,
@@ -1305,6 +1311,7 @@ describe("client signaling recovery policy", () => {
codeEntryPolicy: "open",
viewerAuthorizationGeneration: "viewer_generation_12345678",
mediaMode: "peer-assisted",
+ shareGeneration: "share_generation_12345678",
mediaAssignment: { parentPeerId: null, childPeerIds: [] },
routeRevision: 1,
routeAssignment: {
@@ -1319,6 +1326,7 @@ describe("client signaling recovery policy", () => {
degradationPreference: "balanced",
screenAudioQuality: "music",
},
+ routePolicy: DEFAULT_ROUTE_POLICY,
});
advance(5_000);
expect(sockets[0]!.send).toHaveBeenCalledTimes(1);
@@ -1419,7 +1427,7 @@ describe("client signaling recovery policy", () => {
JSON.parse(String(sockets[0]!.send.mock.calls[0]![0])),
).toMatchObject({
type: "authenticate",
- protocol: "screener-v13",
+ protocol: SIGNALING_PROTOCOL,
});
const message = new Event("message");
Object.defineProperty(message, "data", { value: payload });
@@ -1466,6 +1474,7 @@ describe("client signaling recovery policy", () => {
role: "host",
token: "h".repeat(43),
clientId: "host-client",
+ routePolicy: DEFAULT_ROUTE_POLICY,
},
{
onMessage,
diff --git a/tests/hybrid-media-router.test.ts b/tests/hybrid-media-router.test.ts
index d235d17f..1823a3d6 100644
--- a/tests/hybrid-media-router.test.ts
+++ b/tests/hybrid-media-router.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
-import type { ServerMessage } from "../src/shared/protocol.ts";
+import type { RoutePolicy, ServerMessage } from "../src/shared/protocol.ts";
import {
HybridMediaRouter,
type AuthenticatedRouteParticipant,
@@ -20,7 +20,11 @@ function createStore(maxViewersPerRoom = 20) {
});
}
-function connectHost(store: RoomStore, room: CreatedRoom) {
+function connectHost(
+ store: RoomStore,
+ room: CreatedRoom,
+ routePolicy?: RoutePolicy,
+) {
const connected = store.connectParticipant({
roomId: room.roomId,
role: "host",
@@ -33,6 +37,7 @@ function connectHost(store: RoomStore, room: CreatedRoom) {
role: "host" as const,
peerId: connected.peerId,
sessionId: "host_session_12345678",
+ ...(routePolicy ? { routePolicy } : {}),
};
}
@@ -204,6 +209,213 @@ async function establishSfuRoom(
}
describe("HybridMediaRouter v9 runtime", () => {
+ it("commits topology convergence only after candidate media and native health", async () => {
+ const { store, sent, router } = harness(2);
+ try {
+ const room = await store.createRoom();
+ const host = connectHost(store, room, {
+ peerOnly: false,
+ topologyOptimization: true,
+ });
+ complete(router, host);
+ const first = connectViewer(store, room, "quality-first");
+ complete(router, first);
+ await vi.waitFor(() => expect(preparedFor(sent, first.sessionId)).toBeDefined());
+ const firstPrepare = preparedFor(sent, first.sessionId)!;
+ router.handleRouteReady(first, {
+ type: "route-ready",
+ revision: firstPrepare.revision,
+ phase: "prepare",
+ });
+ const second = connectViewer(store, room, "quality-second");
+ complete(router, second);
+ await vi.waitFor(() => expect(preparedFor(sent, second.sessionId)).toBeDefined());
+ const secondPrepare = preparedFor(sent, second.sessionId)!;
+ router.handleRouteReady(second, {
+ type: "route-ready",
+ revision: secondPrepare.revision,
+ phase: "prepare",
+ });
+ router.setViewerRelayCapacity(second, 2);
+
+ const firstEdge = router.resolveActiveViewerMediaEdge(room.roomId, first.peerId)!;
+ const secondEdge = router.resolveActiveViewerMediaEdge(room.roomId, second.peerId)!;
+ expect(firstEdge.upstream).toEqual({ kind: "peer", peerId: host.peerId });
+ expect(secondEdge.upstream).toEqual({ kind: "peer", peerId: host.peerId });
+ expect(
+ router.observeSenderQualityEvidence(host, {
+ type: "sender-quality-evidence",
+ childPeerId: second.peerId,
+ connectionId: secondEdge.connectionId,
+ rtpStatsId: "second-rtp",
+ trackIdentifier: "track",
+ routeRevision: secondEdge.revision,
+ state: "healthy",
+ }),
+ ).toBe(true);
+ expect(
+ router.observeSenderQualityEvidence(host, {
+ type: "sender-quality-evidence",
+ childPeerId: first.peerId,
+ connectionId: firstEdge.connectionId,
+ rtpStatsId: "first-rtp",
+ trackIdentifier: "track",
+ routeRevision: firstEdge.revision,
+ state: "healthy",
+ }),
+ ).toBe(true);
+ expect(
+ router.observeSenderQualityEvidence(host, {
+ type: "sender-quality-evidence",
+ childPeerId: first.peerId,
+ connectionId: firstEdge.connectionId,
+ rtpStatsId: "first-rtp",
+ trackIdentifier: "track",
+ routeRevision: firstEdge.revision,
+ state: "degraded",
+ }),
+ ).toBe(true);
+
+ await vi.waitFor(() =>
+ expect(preparedFor(sent, first.sessionId)?.revision).toBeGreaterThan(
+ firstEdge.revision,
+ ),
+ );
+ const qualityPrepare = preparedFor(sent, first.sessionId)!;
+ router.handleRouteReady(first, {
+ type: "route-ready",
+ revision: qualityPrepare.revision,
+ phase: "prepare",
+ });
+ expect(
+ router.resolveActiveViewerMediaEdge(room.roomId, first.peerId)?.upstream,
+ ).toEqual({ kind: "peer", peerId: host.peerId });
+
+ expect(
+ router.observeSenderQualityEvidence(second, {
+ type: "sender-quality-evidence",
+ childPeerId: first.peerId,
+ connectionId: qualityPrepare.candidate.connectionId,
+ rtpStatsId: "candidate-rtp",
+ trackIdentifier: "track",
+ routeRevision: qualityPrepare.revision,
+ state: "healthy",
+ }),
+ ).toBe(true);
+ await vi.waitFor(() =>
+ expect(
+ router.resolveActiveViewerMediaEdge(room.roomId, first.peerId)?.upstream,
+ ).toEqual({ kind: "peer", peerId: second.peerId }),
+ );
+ } finally {
+ await router.close();
+ }
+ });
+
+ it("keeps peer-only shares out of configured SFU fallback", async () => {
+ const { store, sent, router } = harness(1, true);
+ try {
+ const room = await store.createRoom();
+ const host = connectHost(store, room, {
+ peerOnly: true,
+ topologyOptimization: false,
+ });
+ complete(router, host);
+ const first = connectViewer(store, room, "peer-only-first");
+ complete(router, first);
+ await vi.waitFor(() =>
+ expect(preparedFor(sent, first.sessionId)?.candidate.transport).toBe(
+ "direct",
+ ),
+ );
+ const direct = preparedFor(sent, first.sessionId)!;
+ router.handleRouteReady(first, {
+ type: "route-ready",
+ revision: direct.revision,
+ phase: "prepare",
+ });
+
+ const blocked = connectViewer(store, room, "peer-only-blocked");
+ complete(router, blocked);
+ await vi.waitFor(() =>
+ expect(
+ sent
+ .get(blocked.sessionId)
+ ?.findLast((message) => message.type === "route-status"),
+ ).toMatchObject({ state: "failed", reason: "route-exhausted" }),
+ );
+ expect(
+ [...sent.values()]
+ .flat()
+ .some((message) => message.type === "sfu-config"),
+ ).toBe(false);
+ } finally {
+ await router.close();
+ }
+ });
+
+ it("silently keeps working media when quality-only SFU admission is denied", async () => {
+ const { store, sent, admission, router } = harness(1, true, undefined, 1);
+ const occupied = {
+ roomId: "9001",
+ shareGeneration: "occupied_share_12345678",
+ publicationGeneration: "occupied_publication_12345678",
+ };
+ try {
+ expect(admission?.reservePublication(occupied)).toBe(true);
+ const room = await store.createRoom();
+ const host = connectHost(store, room, {
+ peerOnly: false,
+ topologyOptimization: true,
+ });
+ complete(router, host);
+ const viewer = connectViewer(store, room, "quality-sfu-denied");
+ 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",
+ });
+ const active = router.resolveActiveViewerMediaEdge(room.roomId, viewer.peerId)!;
+ for (const state of ["healthy", "degraded"] as const) {
+ expect(
+ router.observeSenderQualityEvidence(host, {
+ type: "sender-quality-evidence",
+ childPeerId: viewer.peerId,
+ connectionId: active.connectionId,
+ rtpStatsId: "viewer-rtp",
+ trackIdentifier: "track",
+ routeRevision: active.revision,
+ state,
+ }),
+ ).toBe(true);
+ }
+ await vi.waitFor(() =>
+ expect(router.routeDiagnosticSnapshot(room.roomId).operation).toBeNull(),
+ );
+ expect(
+ sent
+ .get(viewer.sessionId)
+ ?.some((message) => message.type === "route-status"),
+ ).toBe(false);
+ expect(
+ router.resolveActiveViewerMediaEdge(room.roomId, viewer.peerId),
+ ).toMatchObject({
+ connectionId: active.connectionId,
+ upstream: { kind: "peer", peerId: host.peerId },
+ });
+ } finally {
+ if (admission) {
+ admission.beginDrain(occupied);
+ admission.completeDrain(occupied);
+ }
+ await router.close();
+ }
+ });
+
+
it("reports active SFU viewers as one authoritative snapshot", async () => {
const { store, sent, router, onViewerMediaSnapshot } = harness(1, true);
try {
diff --git a/tests/protocol.test.ts b/tests/protocol.test.ts
index 3efdfc33..6ae3b7a3 100644
--- a/tests/protocol.test.ts
+++ b/tests/protocol.test.ts
@@ -5,6 +5,7 @@ import { describe, expect, it } from "vitest";
import {
DEFAULT_QUALITY_SETTINGS,
+ DEFAULT_ROUTE_POLICY,
DEFAULT_VIEWER_DISPLAY_NAME,
MAX_DISPLAY_NAME_CODE_POINTS,
MAX_MEDIA_ROUTE_REVISION,
@@ -96,7 +97,7 @@ describe("client signaling protocol", () => {
"utf8",
);
- expect(SIGNALING_PROTOCOL).toBe("screener-v13");
+ expect(SIGNALING_PROTOCOL).toBe("screener-v14");
expect(nativeWire).toMatch(/signalingProtocol\s*=\s*"screener-v6"/);
});
@@ -861,6 +862,34 @@ describe("client signaling protocol", () => {
}
});
+ it("accepts only native sender quality state with exact known identity", () => {
+ const sender = {
+ type: "sender-quality-evidence",
+ childPeerId: "viewer_12345678",
+ connectionId: "connection_12345678",
+ rtpStatsId: "rtp-stats-1",
+ trackIdentifier: "track-1",
+ routeRevision: 3,
+ state: "degraded",
+ } as const;
+ expect(clientMessageSchema.safeParse(sender).success).toBe(true);
+ expect(
+ clientMessageSchema.safeParse({
+ ...sender,
+ state: "healthy",
+ rtpStatsId: null,
+ }).success,
+ ).toBe(false);
+ expect(
+ clientMessageSchema.safeParse({
+ type: "sfu-publisher-quality-evidence",
+ publicationGeneration: "publication_generation_12345678",
+ routeRevision: 4,
+ state: "healthy",
+ }).success,
+ ).toBe(true);
+ });
+
it.each([
["video/VP8", null, "max-fr=60; max-fs=8160"],
["video/VP9", "profile-id=2", "max-fs=8160"],
@@ -1331,6 +1360,7 @@ describe("server signaling protocol", () => {
const peerAssisted = {
...authenticatedMessage(8),
mediaMode: "peer-assisted",
+ shareGeneration: "share_generation_12345678",
mediaAssignment: {
parentPeerId: null,
childPeerIds: ["viewer_12345678", "viewer_87654321"],
@@ -1342,6 +1372,7 @@ describe("server signaling protocol", () => {
sfuPublicationGeneration: null,
},
qualitySettings,
+ routePolicy: DEFAULT_ROUTE_POLICY,
};
expect(serverMessageSchema.safeParse(peerAssisted).success).toBe(true);
diff --git a/tests/room-route-controller.test.ts b/tests/room-route-controller.test.ts
index 432a4982..8b294982 100644
--- a/tests/room-route-controller.test.ts
+++ b/tests/room-route-controller.test.ts
@@ -21,7 +21,10 @@ const F = "viewer_f_12345678";
function controller(
capacity: 1 | 2 | 3 = 2,
- options: { sfuEnabled?: boolean } = {},
+ options: {
+ sfuEnabled?: boolean;
+ qualityConvergenceEnabled?: boolean;
+ } = {},
) {
const routes = new RoomRouteController<string>({
hostPeerId: HOST,
@@ -149,6 +152,119 @@ function qualityMetrics(
}
describe("RoomRouteController", () => {
+ it("keeps the old edge until one native-healthy quality candidate commits", () => {
+ const routes = controller(2, { qualityConvergenceEnabled: true });
+ addViewer(routes, A, 2);
+ addViewer(routes, B, 2);
+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));
+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));
+ const activeRevision = routes.snapshot().revision;
+
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: HOST,
+ parentSessionId: "host_session",
+ childPeerId: B,
+ routeRevision: activeRevision,
+ connectionId: "b_from_host",
+ senderIdentity: "b-rtp\u0000b-track",
+ state: "healthy",
+ acceptedAtMs: 100,
+ }).accepted,
+ ).toBe(true);
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: HOST,
+ parentSessionId: "host_session",
+ childPeerId: A,
+ routeRevision: activeRevision,
+ connectionId: "a_from_host",
+ senderIdentity: "a-rtp\u0000a-track",
+ state: "healthy",
+ acceptedAtMs: 99,
+ }).accepted,
+ ).toBe(true);
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: HOST,
+ parentSessionId: "host_session",
+ childPeerId: A,
+ routeRevision: activeRevision,
+ connectionId: "a_from_host",
+ senderIdentity: "a-rtp\u0000a-track",
+ state: "degraded",
+ acceptedAtMs: 100,
+ }).accepted,
+ ).toBe(true);
+
+ const operation = routes.reconcile(101).operation!;
+ expect(operation.reason).toBe("quality-convergence");
+ expect(operation.candidates[0]?.tuple).toEqual({
+ kind: "peer",
+ parentPeerId: B,
+ transport: "direct",
+ });
+ const begin = beginCandidate(routes, {
+ nowMs: 102,
+ connectionId: "a_from_b",
+ reservation: { kind: "direct" },
+ });
+ const current = begin.operation!.current!;
+ const guard: CandidateGuard = {
+ childPeerId: A,
+ childSessionId: `${A}_session`,
+ revision: current.revision,
+ connectionId: "a_from_b",
+ };
+ expect(routes.candidateReady(guard, 103)).toMatchObject({
+ accepted: true,
+ committed: false,
+ });
+ expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
+ kind: "peer",
+ parentPeerId: HOST,
+ connectionId: "a_from_host",
+ });
+
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: B,
+ parentSessionId: `${B}_session`,
+ childPeerId: A,
+ routeRevision: current.revision,
+ connectionId: "a_from_b",
+ senderIdentity: "a-from-b-rtp\u0000a-track",
+ state: "healthy",
+ acceptedAtMs: 104,
+ }).committed,
+ ).toBe(true);
+ expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
+ kind: "peer",
+ parentPeerId: B,
+ connectionId: "a_from_b",
+ });
+
+ const migratedRevision = routes.snapshot().revision;
+ const observeMigrated = (state: "healthy" | "degraded", at: number) =>
+ routes.observeSenderQualityEvidence({
+ parentPeerId: B,
+ parentSessionId: `${B}_session`,
+ childPeerId: A,
+ routeRevision: migratedRevision,
+ connectionId: "a_from_b",
+ senderIdentity: "a-from-b-rtp\u0000a-track",
+ state,
+ acceptedAtMs: at,
+ });
+ expect(observeMigrated("degraded", 105).accepted).toBe(true);
+ expect(routes.reconcile(106).operation).toBeUndefined();
+ expect(observeMigrated("healthy", 107).accepted).toBe(true);
+ expect(observeMigrated("degraded", 108).accepted).toBe(true);
+ expect(routes.reconcile(109).operation?.reason).toBe(
+ "quality-convergence",
+ );
+ });
+
it("keeps only fresh exact-edge quality shadow aggregates", () => {
const routes = controller(2);
addViewer(routes, A, 1, 0);
@@ -234,6 +350,504 @@ describe("RoomRouteController", () => {
expect(routes.routeDiagnosticSnapshot(7_301).children[0]?.quality).toBeNull();
});
+ it("commits when native health arrives before candidate media", () => {
+ const routes = controller(2, { qualityConvergenceEnabled: true });
+ addViewer(routes, A, 2);
+ addViewer(routes, B, 2);
+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));
+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));
+ const revision = routes.snapshot().revision;
+ for (const [childPeerId, connectionId, state, acceptedAtMs] of [
+ [B, "b_from_host", "healthy", 100],
+ [A, "a_from_host", "healthy", 99],
+ [A, "a_from_host", "degraded", 100],
+ ] as const) {
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: HOST,
+ parentSessionId: "host_session",
+ childPeerId,
+ routeRevision: revision,
+ connectionId,
+ senderIdentity: `${connectionId}-rtp\u0000track`,
+ state,
+ acceptedAtMs,
+ }).accepted,
+ ).toBe(true);
+ }
+ routes.reconcile(101);
+ const begin = beginCandidate(routes, {
+ nowMs: 102,
+ connectionId: "a_from_b",
+ reservation: { kind: "direct" },
+ });
+ const current = begin.operation!.current!;
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: B,
+ parentSessionId: `${B}_session`,
+ childPeerId: A,
+ routeRevision: current.revision,
+ connectionId: "a_from_b",
+ senderIdentity: "a-from-b-rtp\u0000track",
+ state: "healthy",
+ acceptedAtMs: 103,
+ }).committed,
+ ).toBe(false);
+ expect(
+ routes.candidateReady(
+ {
+ childPeerId: A,
+ childSessionId: `${A}_session`,
+ revision: current.revision,
+ connectionId: "a_from_b",
+ },
+ 104,
+ ).committed,
+ ).toBe(true);
+ });
+
+ it("preempts quality work for a Viewer without media", () => {
+ const routes = controller(2, { qualityConvergenceEnabled: true });
+ addViewer(routes, A, 2);
+ addViewer(routes, B, 2);
+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));
+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));
+ const revision = routes.snapshot().revision;
+ for (const [childPeerId, connectionId, state, acceptedAtMs] of [
+ [B, "b_from_host", "healthy", 100],
+ [A, "a_from_host", "healthy", 99],
+ [A, "a_from_host", "degraded", 100],
+ ] as const) {
+ routes.observeSenderQualityEvidence({
+ parentPeerId: HOST,
+ parentSessionId: "host_session",
+ childPeerId,
+ routeRevision: revision,
+ connectionId,
+ senderIdentity: `${connectionId}-rtp\u0000track`,
+ state,
+ acceptedAtMs,
+ });
+ }
+ expect(routes.reconcile(101).operation?.reason).toBe(
+ "quality-convergence",
+ );
+ addViewer(routes, C, 0, 102);
+ expect(routes.reconcile(103).operation).toMatchObject({
+ childPeerId: C,
+ reason: "join",
+ });
+ commitCurrent(routes, 104, "c_join_connection");
+ const resumedRevision = routes.snapshot().revision;
+ for (const [childPeerId, connectionId, state, acceptedAtMs] of [
+ [B, "b_from_host", "healthy", 105],
+ [A, "a_from_host", "healthy", 105],
+ [A, "a_from_host", "degraded", 106],
+ ] as const) {
+ routes.observeSenderQualityEvidence({
+ parentPeerId: HOST,
+ parentSessionId: "host_session",
+ childPeerId,
+ routeRevision: resumedRevision,
+ connectionId,
+ senderIdentity: `${connectionId}-rtp\u0000track`,
+ state,
+ acceptedAtMs,
+ });
+ }
+ expect(routes.reconcile(107).operation?.reason).toBe(
+ "quality-convergence",
+ );
+ expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
+ parentPeerId: HOST,
+ connectionId: "a_from_host",
+ });
+ });
+
+ it("reconsiders an exhausted edge when an existing parent becomes healthy", () => {
+ const routes = controller(2, { qualityConvergenceEnabled: true });
+ addViewer(routes, A, 2);
+ addViewer(routes, B, 2);
+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));
+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));
+ const revision = routes.snapshot().revision;
+ for (const [state, acceptedAtMs] of [
+ ["healthy", 99],
+ ["degraded", 100],
+ ] as const) {
+ routes.observeSenderQualityEvidence({
+ parentPeerId: HOST,
+ parentSessionId: "host_session",
+ childPeerId: A,
+ routeRevision: revision,
+ connectionId: "a_from_host",
+ senderIdentity: "a-rtp\u0000track",
+ state,
+ acceptedAtMs,
+ });
+ }
+ expect(routes.reconcile(101).operation).toBeUndefined();
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: HOST,
+ parentSessionId: "host_session",
+ childPeerId: B,
+ routeRevision: revision,
+ connectionId: "b_from_host",
+ senderIdentity: "b-rtp\u0000track",
+ state: "healthy",
+ acceptedAtMs: 102,
+ }).accepted,
+ ).toBe(true);
+ expect(routes.reconcile(103).operation).toMatchObject({
+ childPeerId: A,
+ reason: "quality-convergence",
+ });
+ });
+
+ it("rejects stale candidate proof and a parent whose source degrades", () => {
+ const routes = controller(2, { qualityConvergenceEnabled: true });
+ addViewer(routes, A, 2);
+ addViewer(routes, B, 2);
+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));
+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));
+ const observeCurrent = (
+ childPeerId: string,
+ connectionId: string,
+ state: "healthy" | "degraded",
+ acceptedAtMs: number,
+ ) =>
+ routes.observeSenderQualityEvidence({
+ parentPeerId: HOST,
+ parentSessionId: "host_session",
+ childPeerId,
+ routeRevision: routes.snapshot().revision,
+ connectionId,
+ senderIdentity: `${connectionId}-rtp\u0000track`,
+ state,
+ acceptedAtMs,
+ });
+ expect(observeCurrent(B, "b_from_host", "healthy", 100).accepted).toBe(
+ true,
+ );
+ expect(observeCurrent(A, "a_from_host", "healthy", 99).accepted).toBe(
+ true,
+ );
+ expect(observeCurrent(A, "a_from_host", "degraded", 100).accepted).toBe(
+ true,
+ );
+ routes.reconcile(101);
+ let begin = beginCandidate(routes, {
+ nowMs: 102,
+ connectionId: "a_from_b_stale",
+ reservation: { kind: "direct" },
+ });
+ let current = begin.operation!.current!;
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: B,
+ parentSessionId: `${B}_session`,
+ childPeerId: A,
+ routeRevision: current.revision,
+ connectionId: "a_from_b_stale",
+ senderIdentity: "a-stale-rtp\u0000a-track",
+ state: "healthy",
+ acceptedAtMs: 104,
+ }).accepted,
+ ).toBe(true);
+ expect(observeCurrent(A, "a_from_host", "degraded", 5_103).accepted).toBe(
+ true,
+ );
+ expect(
+ routes.candidateReady(
+ {
+ childPeerId: A,
+ childSessionId: `${A}_session`,
+ revision: current.revision,
+ connectionId: "a_from_b_stale",
+ },
+ 5_104,
+ ).committed,
+ ).not.toBe(true);
+ expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
+ parentPeerId: HOST,
+ });
+
+ expect(observeCurrent(A, "a_from_host", "healthy", 5_200).accepted).toBe(
+ true,
+ );
+ expect(observeCurrent(A, "a_from_host", "degraded", 5_201).accepted).toBe(
+ true,
+ );
+ expect(observeCurrent(B, "b_from_host", "healthy", 5_201).accepted).toBe(
+ true,
+ );
+ routes.reconcile(5_202);
+ begin = beginCandidate(routes, {
+ nowMs: 5_203,
+ connectionId: "a_from_b_bad_source",
+ reservation: { kind: "direct" },
+ });
+ current = begin.operation!.current!;
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: B,
+ parentSessionId: `${B}_session`,
+ childPeerId: A,
+ routeRevision: current.revision,
+ connectionId: "a_from_b_bad_source",
+ senderIdentity: "a-bad-source-rtp\u0000a-track",
+ state: "healthy",
+ acceptedAtMs: 5_204,
+ }).accepted,
+ ).toBe(true);
+ expect(observeCurrent(B, "b_from_host", "degraded", 5_205).accepted).toBe(
+ true,
+ );
+ expect(
+ routes.candidateReady(
+ {
+ childPeerId: A,
+ childSessionId: `${A}_session`,
+ revision: current.revision,
+ connectionId: "a_from_b_bad_source",
+ },
+ 5_206,
+ ).committed,
+ ).not.toBe(true);
+ expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
+ parentPeerId: HOST,
+ });
+ });
+
+ it("consumes a candidate whose source expires before begin", () => {
+ const routes = controller(2, { qualityConvergenceEnabled: true });
+ addViewer(routes, A, 2);
+ addViewer(routes, B, 2);
+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));
+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));
+ const revision = routes.snapshot().revision;
+ for (const [childPeerId, connectionId, state, acceptedAtMs] of [
+ [B, "b_from_host", "healthy", 0],
+ [A, "a_from_host", "healthy", 0],
+ [A, "a_from_host", "degraded", 1],
+ ] as const) {
+ routes.observeSenderQualityEvidence({
+ parentPeerId: HOST,
+ parentSessionId: "host_session",
+ childPeerId,
+ routeRevision: revision,
+ connectionId,
+ senderIdentity: `${connectionId}-rtp\u0000track`,
+ state,
+ acceptedAtMs,
+ });
+ }
+ expect(routes.reconcile(2).operation?.reason).toBe("quality-convergence");
+ const begin = beginCandidate(routes, {
+ nowMs: 5_001,
+ connectionId: "expired_candidate",
+ reservation: { kind: "direct" },
+ });
+ expect(begin.accepted).toBe(true);
+ expect(begin.operation).toBeUndefined();
+ expect(routes.snapshot().operation).toBeUndefined();
+ });
+
+ it("uses bounded SFU only after a degraded Host edge has no Peer escape", () => {
+ const routes = controller(1, {
+ sfuEnabled: true,
+ qualityConvergenceEnabled: true,
+ });
+ addViewer(routes, A, 1);
+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));
+ const activeRevision = routes.snapshot().revision;
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: HOST,
+ parentSessionId: "host_session",
+ childPeerId: A,
+ routeRevision: activeRevision,
+ connectionId: "a_from_host",
+ senderIdentity: "a-rtp\u0000a-track",
+ state: "healthy",
+ acceptedAtMs: 99,
+ }).accepted,
+ ).toBe(true);
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: HOST,
+ parentSessionId: "host_session",
+ childPeerId: A,
+ routeRevision: activeRevision,
+ connectionId: "a_from_host",
+ senderIdentity: "a-rtp\u0000a-track",
+ state: "degraded",
+ acceptedAtMs: 100,
+ }).accepted,
+ ).toBe(true);
+ const operation = routes.reconcile(101).operation!;
+ expect(operation.candidates.map((candidate) => candidate.tuple)).toEqual([
+ { kind: "sfu", publication: "create" },
+ ]);
+ const begin = beginCandidate(routes, {
+ nowMs: 102,
+ connectionId: "a_from_sfu",
+ reservation: {
+ kind: "sfu-create",
+ edge: "sfu-edge",
+ publication: "sfu-publication",
+ overlap: "host-overlap",
+ },
+ publicationGeneration: "publication_generation_12345678",
+ publicationConnectionId: "publication_connection_12345678",
+ hostSessionId: "host_session",
+ });
+ const current = begin.operation!.current!;
+ expect(
+ routes.candidateReady(
+ {
+ childPeerId: A,
+ childSessionId: `${A}_session`,
+ revision: current.revision,
+ connectionId: "a_from_sfu",
+ },
+ 103,
+ ),
+ ).toMatchObject({ accepted: true, committed: false });
+ expect(
+ routes.observeSfuPublisherQualityEvidence({
+ hostPeerId: HOST,
+ hostSessionId: "host_session",
+ publicationGeneration: "publication_generation_12345678",
+ routeRevision: current.revision,
+ state: "healthy",
+ acceptedAtMs: 104,
+ }).committed,
+ ).toBe(true);
+ expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
+ kind: "sfu",
+ connectionId: "a_from_sfu",
+ });
+ });
+
+ it("uses SFU reuse only after its active publication becomes healthy", () => {
+ const routes = controller(2, {
+ sfuEnabled: true,
+ qualityConvergenceEnabled: true,
+ });
+ addViewer(routes, A, 1);
+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));
+ routes.hydrateHostPublication(
+ "publication_generation_12345678",
+ "publication_resource",
+ );
+ const revision = routes.snapshot().revision;
+ for (const [state, acceptedAtMs] of [
+ ["healthy", 99],
+ ["degraded", 100],
+ ] as const) {
+ routes.observeSenderQualityEvidence({
+ parentPeerId: HOST,
+ parentSessionId: "host_session",
+ childPeerId: A,
+ routeRevision: revision,
+ connectionId: "a_from_host",
+ senderIdentity: "a-rtp\u0000track",
+ state,
+ acceptedAtMs,
+ });
+ }
+ expect(routes.reconcile(101).operation).toBeUndefined();
+ expect(
+ routes.observeSfuPublisherQualityEvidence({
+ hostPeerId: HOST,
+ hostSessionId: "host_session",
+ publicationGeneration: "publication_generation_12345678",
+ routeRevision: revision,
+ state: "healthy",
+ acceptedAtMs: 102,
+ }).accepted,
+ ).toBe(true);
+ expect(routes.reconcile(103).operation?.candidates[0]?.tuple).toEqual({
+ kind: "sfu",
+ publication: "reuse",
+ });
+ });
+
+ it("accepts an SFU-fed Peer parent from decoded progress without freeze stats", () => {
+ const routes = controller(2, {
+ sfuEnabled: true,
+ qualityConvergenceEnabled: true,
+ });
+ addViewer(routes, A, 1);
+ addViewer(routes, B, 2);
+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));
+ routes.hydrateHostPublication(
+ "publication_generation_12345678",
+ "publication_resource",
+ );
+ routes.hydrateEdge(B, {
+ kind: "sfu",
+ publicationGeneration: "publication_generation_12345678",
+ transport: "sfu",
+ connectionId: "b_from_sfu",
+ usable: true,
+ physicalActive: true,
+ resource: "b_subscription",
+ });
+ const revision = routes.snapshot().revision;
+ expect(
+ routes.observeSfuPublisherQualityEvidence({
+ hostPeerId: HOST,
+ hostSessionId: "host_session",
+ publicationGeneration: "publication_generation_12345678",
+ routeRevision: revision,
+ state: "healthy",
+ acceptedAtMs: 100,
+ }).accepted,
+ ).toBe(true);
+ expect(
+ routes.observeQualityEvidence({
+ childPeerId: B,
+ childSessionId: `${B}_session`,
+ routeRevision: revision,
+ connectionId: "b_from_sfu",
+ upstream: { kind: "sfu" },
+ presentationEpoch: 1,
+ windowMs: 2_000,
+ metrics: qualityMetrics({
+ freezeCountDelta: null,
+ freezeDurationMsDelta: null,
+ pauseCountDelta: null,
+ pauseDurationMsDelta: null,
+ }),
+ acceptedAtMs: 100,
+ }),
+ ).toBe("accepted");
+ for (const [state, acceptedAtMs] of [
+ ["healthy", 99],
+ ["degraded", 100],
+ ] as const) {
+ routes.observeSenderQualityEvidence({
+ parentPeerId: HOST,
+ parentSessionId: "host_session",
+ childPeerId: A,
+ routeRevision: revision,
+ connectionId: "a_from_host",
+ senderIdentity: "a-rtp\u0000track",
+ state,
+ acceptedAtMs,
+ });
+ }
+ expect(routes.reconcile(101).operation?.candidates[0]?.tuple).toEqual({
+ kind: "peer",
+ parentPeerId: B,
+ transport: "direct",
+ });
+ });
+
it("clears quality shadow for a relay subtree when its source changes", () => {
const routes = controller(2);
addViewer(routes, A, 2);
diff --git a/tests/sender-quality-evidence.test.ts b/tests/sender-quality-evidence.test.ts
new file mode 100644
index 00000000..8428fd29
--- /dev/null
+++ b/tests/sender-quality-evidence.test.ts
@@ -0,0 +1,181 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ invalidateSenderQualityEvidence,
+ senderQualityEvidenceFromSnapshot,
+} from "../src/client/media/sender-quality-evidence.ts";
+import type { PeerSnapshot } from "../src/client/types.ts";
+import {
+ collectConnectionMetricsFromReport,
+ collectNativeSenderQualityFromReport,
+ createNativeSenderQualityAccumulator,
+ createStatsAccumulator,
+} from "../src/client/webrtc/stats.ts";
+
+function report(
+ timestamp: number,
+ reason: "none" | "bandwidth" | "cpu",
+ durations: Record<"none" | "bandwidth" | "cpu" | "other", number>,
+): RTCStatsReport {
+ return new Map([
+ [
+ "video",
+ {
+ id: "video",
+ type: "outbound-rtp",
+ kind: "video",
+ timestamp,
+ ssrc: 1,
+ bytesSent: timestamp * 100,
+ framesEncoded: timestamp / 20,
+ qualityLimitationReason: reason,
+ qualityLimitationDurations: durations,
+ },
+ ],
+ ]) as unknown as RTCStatsReport;
+}
+
+describe("native sender quality evidence", () => {
+ it("conservatively combines every active SFU publication encoding", () => {
+ const accumulator = createNativeSenderQualityAccumulator();
+ const multi = (
+ timestamp: number,
+ reasons: readonly ["none" | "bandwidth", "none" | "bandwidth"],
+ ) => {
+ const entries: Array<[string, Record<string, unknown>]> = [
+ [
+ "source",
+ {
+ id: "source",
+ type: "media-source",
+ timestamp,
+ trackIdentifier: "track",
+ },
+ ],
+ ];
+ reasons.forEach((reason, index) =>
+ entries.push([
+ `video-${index}`,
+ {
+ id: `video-${index}`,
+ type: "outbound-rtp",
+ kind: "video",
+ timestamp,
+ framesEncoded: timestamp / 20 + index,
+ mediaSourceId: "source",
+ qualityLimitationReason: reason,
+ qualityLimitationDurations: {
+ none: reason === "none" ? timestamp / 1_000 : 3,
+ bandwidth:
+ reason === "bandwidth" ? timestamp / 1_000 - 3 : 0,
+ cpu: 0,
+ other: 0,
+ },
+ },
+ ]),
+ );
+ return new Map(entries) as unknown as RTCStatsReport;
+ };
+
+ expect(
+ collectNativeSenderQualityFromReport(
+ multi(1_000, ["none", "none"]),
+ "track",
+ accumulator,
+ ).nativeEdgeQualityState,
+ ).toBe("unknown");
+ expect(
+ collectNativeSenderQualityFromReport(
+ multi(3_000, ["none", "none"]),
+ "track",
+ accumulator,
+ ).nativeEdgeQualityState,
+ ).toBe("healthy");
+ expect(
+ collectNativeSenderQualityFromReport(
+ multi(5_000, ["bandwidth", "none"]),
+ "track",
+ accumulator,
+ ).nativeEdgeQualityState,
+ ).toBe("degraded");
+ });
+
+ it("derives categorical state only from one complete native duration delta", () => {
+ const accumulator = createStatsAccumulator();
+ const first = collectConnectionMetricsFromReport(
+ report(1_000, "none", { none: 1, bandwidth: 0, cpu: 0, other: 0 }),
+ "send",
+ accumulator,
+ );
+ expect(first.nativeEdgeQualityState).toBe("unknown");
+
+ const healthy = collectConnectionMetricsFromReport(
+ report(3_000, "none", { none: 3, bandwidth: 0, cpu: 0, other: 0 }),
+ "send",
+ accumulator,
+ );
+ expect(healthy.nativeEdgeQualityState).toBe("healthy");
+
+ const degraded = collectConnectionMetricsFromReport(
+ report(5_000, "bandwidth", {
+ none: 3,
+ bandwidth: 2,
+ cpu: 0,
+ other: 0,
+ }),
+ "send",
+ accumulator,
+ );
+ expect(degraded.nativeEdgeQualityState).toBe("degraded");
+
+ const mixed = collectConnectionMetricsFromReport(
+ report(7_000, "none", {
+ none: 4,
+ bandwidth: 3,
+ cpu: 0,
+ other: 0,
+ }),
+ "send",
+ accumulator,
+ );
+ expect(mixed.nativeEdgeQualityState).toBe("unknown");
+ });
+
+ it("serializes only exact healthy or degraded sender snapshots", () => {
+ const metrics = collectConnectionMetricsFromReport(
+ report(1_000, "none", { none: 1, bandwidth: 0, cpu: 0, other: 0 }),
+ "send",
+ createStatsAccumulator(),
+ );
+ const snapshot: PeerSnapshot = {
+ peerId: "viewer_12345678",
+ connectionId: "connection_12345678",
+ connectionState: "connected",
+ iceConnectionState: "connected",
+ metrics: {
+ ...metrics,
+ rtpStatsId: "rtp-stats-1",
+ trackIdentifier: "track-1",
+ sampleWindowMs: 2_000,
+ intervalFramesEncoded: 100,
+ qualityLimitationReason: "none",
+ nativeEdgeQualityState: "healthy",
+ },
+ error: null,
+ };
+ expect(senderQualityEvidenceFromSnapshot(snapshot, 7)).toMatchObject({
+ state: "unknown",
+ });
+ expect(senderQualityEvidenceFromSnapshot(snapshot, 7)).toMatchObject({
+ type: "sender-quality-evidence",
+ childPeerId: snapshot.peerId,
+ connectionId: snapshot.connectionId,
+ routeRevision: 7,
+ state: "healthy",
+ });
+ invalidateSenderQualityEvidence();
+ expect(senderQualityEvidenceFromSnapshot(snapshot, 7)).toMatchObject({
+ state: "unknown",
+ });
+ });
+});
diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.ts
index 93046e2b..675be265 100644
--- a/tests/server-signal.test.ts
+++ b/tests/server-signal.test.ts
@@ -11,6 +11,7 @@ import {
SIGNALING_PROTOCOL,
decodeServerMessage,
type QualitySettings,
+ type RoutePolicy,
type RoomAccessUpdateRequest,
type Role,
type ServerMessage,
@@ -290,6 +291,7 @@ async function authenticate(
codeOnly?: true;
sharingPaused?: boolean;
qualitySettings?: QualitySettings;
+ routePolicy?: RoutePolicy;
} = {},
) {
client.socket.send(
@@ -309,6 +311,9 @@ async function authenticate(
...(presence.qualitySettings
? { qualitySettings: presence.qualitySettings }
: {}),
+ ...(presence.routePolicy
+ ? { routePolicy: presence.routePolicy }
+ : {}),
...(presence.viewerPresence ? { viewerPresence: true } : {}),
...(presence.displayName
? { displayName: presence.displayName }
@@ -455,6 +460,44 @@ async function closeClient(client: TestClient): Promise<void> {
}
describe("WebSocket signaling", () => {
+ it("echoes the exact per-share route policy authority", async () => {
+ const harness = await startHarness({ peerAssistedMedia: true });
+ const viewer = await openClient(harness.webSocketUrl);
+ const waiting = peerAssisted(
+ await authenticate(
+ viewer,
+ harness.room,
+ "viewer",
+ "route-policy-viewer",
+ 1,
+ ),
+ );
+ expect(waiting.shareGeneration).toBeNull();
+ const host = await openClient(harness.webSocketUrl);
+ const routePolicy = {
+ peerOnly: true,
+ topologyOptimization: true,
+ } as const;
+ const authenticated = peerAssisted(
+ await authenticate(
+ host,
+ harness.room,
+ "host",
+ "route-policy-host",
+ 1,
+ "route_policy_share_generation_12345678",
+ { routePolicy },
+ ),
+ );
+ expect(authenticated.routePolicy).toEqual(routePolicy);
+ expect("sfuStandbyUrl" in authenticated).toBe(false);
+ expect(await viewer.inbox.next("route-policy")).toEqual({
+ type: "route-policy",
+ shareGeneration: "route_policy_share_generation_12345678",
+ routePolicy,
+ });
+ });
+
it("rebuilds a route when a Viewer reconnects before the Host after restart", async () => {
const directory = mkdtempSync(join(tmpdir(), "screener-route-restart-"));
const path = join(directory, "rooms.sqlite");
diff --git a/tests/sfu-client.test.ts b/tests/sfu-client.test.ts
index 98cf1b21..6f378e58 100644
--- a/tests/sfu-client.test.ts
+++ b/tests/sfu-client.test.ts
@@ -550,6 +550,7 @@ describe("SfuPublisher", () => {
encoderImplementation: "ExternalEncoder",
powerEfficientEncoder: true,
qualityLimitationReason: "bandwidth",
+ nativeEdgeQualityState: "unknown",
});
sender.getStats.mockResolvedValueOnce(