Skip to content

armgit / Piik

Public Imported from GitHub
0

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

fix(routing): reparent persistently degraded viewer edges (#62)

AAA08aee2558239
diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.md
index b356a3f7..c9bb7591 100644
--- a/docs/adr/0005-automatic-hybrid-media-routing.md
+++ b/docs/adr/0005-automatic-hybrid-media-routing.md
@@ -117,6 +117,32 @@ leaves and desktop-class browsers as one-child relays. The controller uses this
binary capability only for future admission and recovery. Withdrawing capacity
does not proactively migrate an otherwise healthy existing edge.
+The repository quality-reparent candidate adds one bounded parent-to-server
+evidence message and no second route owner. Signaling authenticates and
+forwards Viewer C under its existing session, connection, revision, parent,
+sequence, two-second rate and 2 KiB guards. The current parent then answers only
+from its current outbound `HostPeer` sample: a positive `packetsSent` delta is
+required. Its existing proof union carries `sending` for current liveness,
+`sender-limited` only for an exact `qualityLimitationReason` of `cpu` or
+`bandwidth`, or `remote-loss` only when the same interval has at least 100 sent
+packets and RTCP-reported remote loss divided by sent packets is at least 30%.
+`sending` is diagnostic and cannot advance a bad streak. The 2 KiB answer
+echoes the exact C sequence; signaling
+accepts it once, within five seconds, from the current parent session and same
+child generation. A parent consumes a stats sample only once per child and
+current connection, using the existing finite monotonic stats timestamp; its
+DOMHighResTimeStamp-derived window is rounded before the one-to-five-second
+bound is checked. Viewer C may wait pending, but the router advances the streak
+only when that C has a hard receive predicate and B independently reports one
+of the two hard sender predicates. Both inputs are WebRTC stats gathered by
+stock browsers at separate endpoints; parent remote loss originates in RTCP.
+This is cross-endpoint corroboration, not cryptographic independence or defense
+against colluding authenticated participants. Raw stats, addresses, candidates,
+SDP, URLs and a composite score remain out of wire.
+The router may create the existing Viewer route intent;
+`PeerRelayTopology.reassignViewer` and `MediaRouteController` continue to own
+the subtree change, revision, generation, prepare, commit and rollback.
+
Targeted tests cover the revision controller, protocol authorization, relay
capacity, ordered client transitions, stale asynchronous work, server-restart
resynchronization, one-shot credential recovery, peer failback, and optional
@@ -259,8 +285,10 @@ it never uploads the raw error, endpoint, token, candidate, or address.
An activated SFU-root route is sticky until a discrete route event requires a
change or the current share stops. A new sharing generation starts from the
-cheapest available UDP route. The first target does not continuously rebalance
-healthy media, avoiding oscillation without adding a score or optimizer.
+cheapest available UDP route. The controller does not continuously rebalance
+healthy media. The bounded quality candidate changes only the Viewer-rooted
+subtree whose current parent-to-child edge produced three consecutive hard-bad
+windows; it does not withdraw that parent's global relay capacity.
The authenticated standby is not a transport: it has no grant and never joins a
room. During route prepare the current implementation warms only an unpublishing/unsubscribed
@@ -307,11 +335,38 @@ The first controller reacts only to discrete events:
- no eligible peer slot or the accepted maximum depth;
- exhausted ICE/rebuild for an assigned edge;
- relay participant departure;
-- unsupported route capability; or
-- a hard bounded-send-queue overflow on a future encoded-object route.
-
-It does not combine RTT, CPU, bitrate, geography, or a synthetic health score.
-Measurements may add a new explicit trigger only through a reviewed change.
+- unsupported route capability;
+- a hard bounded-send-queue overflow on a future encoded-object route; or
+- three consecutive, current-identity correlated Viewer C/parent B windows in
+ which C has a hard receive predicate (freeze duration at least 50% of the
+ sample window, positive received RTP with zero decoded frames, or at least
+ 100 received-plus-lost packets with loss at least 30%) and B independently
+ reports `cpu`/`bandwidth` sender limitation or at least 100 sent packets with
+ RTCP-reported remote loss divided by sent packets at least 30%.
+
+It does not combine RTT, bitrate, geography, or a synthetic health score; the
+exact sender-limitation enum is a predicate, not an encoder score. Either side
+alone is diagnostic-only. C may be stored before B arrives, but only the hard
+pair advances the streak. Healthy or ambiguous correlated windows clear it. A Viewer or parent session,
+connection ID, route revision or parent identity change also resets it, as does
+an evidence gap over five seconds. A successful peer reassignment or started
+SFU prepare creates one 30-second room migration budget. Viewer/session churn
+cannot bypass that budget; removal, disconnect, authorization or generation
+change clears per-edge evidence and intent state, while room stop/delete clears
+the room budget. A quality-created intent retains its Viewer/parent sessions,
+connection, revision and parent guard through every drain, peer change, SFU
+prepare and commit boundary. Pending SFU work also retains the exact originating
+intent identity: missing, replaced or changed guards abort before grants or
+commit, while a genuine `route-failed` may explicitly take over that same
+intent as the ordinary failure owner. Stale work and successful peer migration
+release only the quality-owned temporary parent exclusion; a real
+`route-failed` exclusion remains owned by the failure path. The W3C stats
+definitions establish the counter meanings and their WebRTC 1.0 example uses
+30% loss as a likely culprit; they do not
+prescribe Screener's route policy. Therefore 50%, 100 packets, three windows,
+five seconds and 30 seconds are conservative candidate constants pending
+production calibration, not claimed optimums. Measurements may change them
+only through a reviewed change.
ADR-0007's `HIGH`/`FALLBACK` quality state is separate and does not become a
topology trigger or a room-wide health score.
diff --git a/docs/project-memory.md b/docs/project-memory.md
index d8d90005..381c9489 100644
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@ -27,7 +27,7 @@ Last updated: 2026-08-20
- Mobile Web Host is unsupported; feature-detect and fail clearly. Mobile Viewer stays leaf-only. After Windows native, gate Android 14+; iOS waits for stable iOS 27 ScreenCaptureKit.
- ADR-0005 accepts SFU roots as the primary central fallback after direct/peer UDP. The candidate has no TURN consumer or credential wire; any future exceptional-edge grant is a complete separate change. PR #12 is superseded.
- Keep the controller exact-room only: room `1` is the STUN/SFU smoke. Preserve sticky progressing P2P, mobile leaves and break-before-make. Recovery spends one attempt per layer (ICE restart, same-parent rebuild, alternate peer, then SFU), never three identical retries; active SFU gets one fresh grant before Peer failback.
-- Local reparenting is a later candidate: start with unassigned relay admission rescue; do not block current work.
+- Quality reparenting needs three correlated C+B hard-bad windows and reuses the local-subtree peer/SFU/failure intent. Single-sided reports are diagnostic; one room cooldown blocks churn. No score, timer, or global parent penalty.
- Flagship media is UDP; HTTPS/WSS stays TLS/TCP; the old release remains rollback-only.
- Treat settings as ceilings and degradation as unclassified. Use correlated Host A+B/Viewer C and one-variable evidence; never force AV1, infer by UA, or create a composite score.
- Production reports poor film audio and self-echo when system capture includes voice software. Diagnose audio A/B/C and sync; Web cannot isolate arbitrary processes and `maxBitrate` is not quality-up. A Windows 11 native candidate defaults to game-process-tree audio and never widens silently; Windows 10 remains unresolved/unsupported. See `docs/research/browser-screen-audio-quality.md`.
@@ -51,7 +51,7 @@ Last updated: 2026-08-20
- Native drafts remain experiments: one WebCodecs object is not hardware proof; stock GCC+RTX is no-go.
- Chrome 151 synthetic topology/quality-control runs kept fanout 2/1 and all viewers decoding; one relay close recovered in 5.32 seconds. This is control evidence only.
- Room 1 publishes `HIGH+LOW` with Dynacast off and subscriber `HIGH` ceilings. It is unverified; test zero-child leaves, then root evacuation before broad rollout.
-- Local Host A+B aligns one capture/outbound/transport generation; authenticated Viewer C adds a sanitized, read-only P2P window and fails closed for stale, ambiguous, or SFU-fed evidence. It retains no raw fmtp/SDP/stats and performs no media action. Topology classification remains absent.
+- Generation-bound C+B needs three hard-bad windows; parent samples are one-use per connection. Pending SFU binds intent/guard. Stale/successful peer work releases quality exclusion; real failure may take it over. No metadata/topology classification.
## Provisional Quality Targets
@@ -71,7 +71,7 @@ These are measurement gates, not performance claims.
- Project license and distribution model, which determines whether GPL/AGPL sources can move beyond study-only use.
- Initial deployment regions and expected mainland China, Hong Kong, and overseas network mix.
- Whether voice chat ever enters scope or Screener stays complementary to an existing voice application.
-- Exact evidence thresholds/windows and the native hardware matrix for ADR-0007; #28's minimum-of-two rule is not a candidate.
+- Production calibration of local-reparent thresholds and the ADR-0007 native matrix; #28's minimum-of-two rule is not a candidate.
## Source Of Truth
diff --git a/docs/research/advanced-peer-distribution.md b/docs/research/advanced-peer-distribution.md
index 603d8207..fbb83aab 100644
--- a/docs/research/advanced-peer-distribution.md
+++ b/docs/research/advanced-peer-distribution.md
@@ -168,15 +168,73 @@ is isolated behind a small adapter.
## Candidate 6: Bounded Capability-Aware Local Reparenting
-This is a later topology candidate, not part of ADR-0004 or the current
-implementation milestone. Narada and Overcast demonstrate measurement-driven
-overlay improvement, but neither supplies a maintained WebRTC RTP/RTCP routing
-library. BitTorrent/WebTorrent and P2P Media Loader use chunk-pull swarms and
+This remains a bounded topology candidate outside ADR-0004. Narada and Overcast
+demonstrate measurement-driven overlay improvement, but neither supplies a
+maintained WebRTC RTP/RTCP routing library. BitTorrent/WebTorrent and P2P Media
+Loader use chunk-pull swarms and
playout buffers, while SplitStream requires striped multi-tree media.
Their exploration and hysteresis ideas are useful, but none is a drop-in route
controller for sub-second screen sharing. A mature SFU is the directly reusable
low-latency alternative, with central egress rather than audience forwarding.
+The first quality-driven slice reuses the authenticated Viewer C window and
+existing route intent, plus one strict parent-to-server B message. Signaling
+binds C to room, Viewer session, connection ID, active revision, parent
+peer/session, sequence, two-second rate and 2 KiB size, then forwards the same
+sanitized object. The current parent answers that exact sequence within five
+seconds only when its current outbound sample has a positive `packetsSent`
+delta. The existing discriminated proof is `sending` for diagnostic liveness,
+`sender-limited` only for an exact `qualityLimitationReason` of `cpu` or
+`bandwidth`, or `remote-loss` when that interval has at least 100 sent packets
+and RTCP-reported remote loss divided by sent packets is at least 30%; it never
+carries a null placeholder. One current connection cannot reuse the same
+`sampleTimestampMs` for multiple C sequences; fractional stats windows are
+rounded before applying the protocol bounds. The
+server accepts one B from the bound parent session and generation. The router
+may retain C while awaiting B, but advances only when the correlated pair has a
+hard C receive predicate and a hard B sender predicate. `sending`, either
+report alone, and healthy or ambiguous pairs reset or do not advance the
+streak.
+It holds at most one pending/streak state per connected Viewer and one room
+cooldown, with no timer, weighted score or global parent-capacity decision.
+
+The conservative Viewer C hard predicates are: freeze duration at least half
+of the one-to-five-second window; positive received-packet delta with zero
+decoded frames; or at least 100 received-plus-lost packets with loss at least
+30%. Parent B must independently report the exact `cpu`/`bandwidth` sender
+limitation or at least 100 sent packets with remote loss divided by sent packets
+at least 30%. Three consecutive dual-hard-bad windows are required. A healthy
+or incomplete correlated window, any Viewer/parent session, connection, route
+revision or parent change, or a gap over five seconds clears the streak. A
+successful peer move or started SFU prepare spends a 30-second room migration
+budget, so a new public Viewer identity cannot bypass it. Per-edge state clears
+on authentication/generation change, disconnect/removal and route replacement;
+room stop/delete also clears the cooldown.
+
+An SFU preparation created by quality retains the exact originating intent and
+its full Viewer/parent session, connection and revision guard until grants and
+commit finish. Missing, replaced or changed intent state aborts and releases
+only its quality-owned parent exclusion. A real `route-failed` can take over
+that same intent without losing its exclusion; a successful peer move releases
+the quality-only exclusion so a later real failure after reattachment remains
+actionable.
+
+W3C defines outbound `packetsSent` as the local cumulative RTP packet count.
+`remote-inbound-rtp.packetsLost` is remote receiver data delivered by RTCP and
+the corresponding stats object does not exist until that RTCP first arrives;
+absence is therefore not zero. W3C's video-only `qualityLimitationReason` stays
+an exact local sender predicate rather than an encoder score. Parent B and
+Viewer C are gathered by stock browsers at separate endpoints, but RTCP remote
+loss is receiver-originated and neither report is cryptographically independent
+or resistant to colluding authenticated participants. W3C also defines
+Viewer-side
+`packetsReceived`, `packetsLost`, `framesDecoded`, `freezeCount` and
+`totalFreezesDuration`; its WebRTC 1.0 diagnostic example treats loss over 30%
+as a likely culprit. It does not define route-migration thresholds. The 50%
+freeze share, 100-packet floor, three windows, five-second gap and 30-second
+cooldown are falsifiable candidate constants for production calibration, not
+standards-derived or claimed optimum values.
+
With host degree two and the current browser-relay degree one, two balanced
chains already minimize maximum depth at `ceil(N/2)`. A tree for `N` viewers
still has `N` media edges, approximately `N*B` useful upload in aggregate, and
@@ -185,9 +243,10 @@ not reduce either bandwidth quantity. Reordering an already balanced healthy
tree also cannot reduce depth; a move needs a discrete admission, path, TURN,
relay-resource, recovery, or future native-capacity benefit.
-The initial spike is limited to admission rescue. If a relay-capable viewer is
-unassigned because two zero-capacity roots, especially mobile leaves, occupy
-both host slots, insert that viewer above one deterministic childless root:
+The admission-rescue slice is limited to its discrete capacity case. If a
+relay-capable viewer is unassigned because two zero-capacity roots, especially
+mobile leaves, occupy both host slots, insert that viewer above one
+deterministic childless root:
```text
host -> new relay -> existing leaf
@@ -230,9 +289,11 @@ reference runs must not migrate; each move must record one discrete benefit,
avoid reversal during cooldown, and restore the prior deterministic route on
rollback. Reject this candidate if it needs all-pairs probing, a continuous
optimizer, temporary fanout above budget, self-reported geography or device
-quality, or cannot beat the unchanged route. Start and stop the initial spike
-at admission rescue. Later measured work owns quality-driven moves and
-healthy TURN-to-direct optimization.
+quality, or cannot beat the unchanged route. The earlier admission-rescue case
+remains valid, while this quality slice moves only the affected Viewer-rooted
+subtree and excludes only its current failed parent through the existing
+peer-first, then SFU, then explicit-failure path. Healthy TURN-to-direct
+optimization remains future work.
## Staged Connection Recovery Evidence
diff --git a/docs/status.md b/docs/status.md
index 4bae8136..177a4419 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -21,7 +21,7 @@ The v1 DB/old env pair is only for the deeper pre-access `9610032` rollback.
- Fallback prewarm is token-free and limited to room `1`; mobile/iPad viewers are leaves and healthy edges stay sticky.
- After an answer, a generation-bound 15s initial-connect deadline enters ICE restart; success/replacement/disposal cancels it. It is deployed but not mobile-verified.
- Room `1` can publish exactly `HIGH+LOW` with Dynacast/backup codec off and subscriber `HIGH` ceilings; it has no retained real media frame.
-- A+B/P2P C remains read-only. Autonomous BWE is only `suspect`; confirmed fallback evacuates children and loses parent capacity. Root impact remains a default-on gate.
+- Exact-room quality reparenting is candidate-only: three C+B hard-bad pairs reuse peer/SFU/failure and one room cooldown; single-side reports do nothing. Thresholds need game/mobile calibration.
## Verified Evidence
diff --git a/src/client/media/parent-edge-quality-evidence.ts b/src/client/media/parent-edge-quality-evidence.ts
new file mode 100644
index 00000000..48e4eacd
--- /dev/null
+++ b/src/client/media/parent-edge-quality-evidence.ts
@@ -0,0 +1,133 @@
+import {
+ MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES,
+ parentEdgeQualityEvidenceMessageSchema,
+ type ClientMessage,
+ type ServerMessage,
+} from "../../shared/protocol";
+import type { PeerSnapshot } from "../types";
+
+type ViewerQualityEvidence = Extract<
+ ServerMessage,
+ { type: "viewer-quality-evidence" }
+>;
+
+const PARENT_EDGE_QUALITY_MIN_LOSS_PACKETS = 100;
+const PARENT_EDGE_QUALITY_HIGH_LOSS_RATIO = 0.3;
+
+export function parentEdgeQualityEvidenceFromSnapshot(
+ evidence: ViewerQualityEvidence,
+ snapshot: PeerSnapshot | null,
+): Extract<ClientMessage, { type: "parent-edge-quality-evidence" }> | null {
+ if (
+ snapshot === null ||
+ snapshot.peerId !== evidence.viewerPeerId ||
+ snapshot.connectionId !== evidence.guard.connectionId ||
+ snapshot.connectionState !== "connected"
+ ) {
+ return null;
+ }
+ const { metrics } = snapshot;
+ const packetsSentDelta = metrics.intervalPacketsSent;
+ const sampleWindowMs = metrics.sampleWindowMs;
+ const windowMs =
+ sampleWindowMs !== null && Number.isFinite(sampleWindowMs)
+ ? Math.round(sampleWindowMs)
+ : null;
+ if (
+ !Number.isSafeInteger(packetsSentDelta) ||
+ packetsSentDelta === null ||
+ packetsSentDelta <= 0 ||
+ windowMs === null ||
+ !Number.isSafeInteger(windowMs) ||
+ windowMs < 1_000 ||
+ windowMs > 5_000
+ ) {
+ return null;
+ }
+
+ const remotePacketsLostDelta = metrics.intervalPacketsLost;
+ const senderLimitation =
+ metrics.qualityLimitationReason === "cpu" ||
+ metrics.qualityLimitationReason === "bandwidth"
+ ? metrics.qualityLimitationReason
+ : null;
+ const hasHighRemoteLoss =
+ Number.isSafeInteger(remotePacketsLostDelta) &&
+ remotePacketsLostDelta !== null &&
+ remotePacketsLostDelta > 0 &&
+ packetsSentDelta >= PARENT_EDGE_QUALITY_MIN_LOSS_PACKETS &&
+ remotePacketsLostDelta / packetsSentDelta >=
+ PARENT_EDGE_QUALITY_HIGH_LOSS_RATIO;
+ const proof = senderLimitation
+ ? {
+ kind: "sender-limited" as const,
+ packetsSentDelta,
+ reason: senderLimitation,
+ }
+ : hasHighRemoteLoss
+ ? {
+ kind: "remote-loss" as const,
+ packetsSentDelta,
+ remotePacketsLostDelta,
+ }
+ : { kind: "sending" as const, packetsSentDelta };
+ const parsed = parentEdgeQualityEvidenceMessageSchema.safeParse({
+ type: "parent-edge-quality-evidence",
+ viewerPeerId: evidence.viewerPeerId,
+ guard: evidence.guard,
+ viewerSequence: evidence.sequence,
+ proof,
+ });
+ if (!parsed.success) {
+ return null;
+ }
+ return JSON.stringify(parsed.data).length <=
+ MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES
+ ? parsed.data
+ : null;
+}
+
+export class ParentEdgeQualityEvidenceReporter {
+ private readonly samplesByViewer = new Map<
+ string,
+ { connectionId: string; sampleTimestampMs: number }
+ >();
+
+ offer(
+ evidence: ViewerQualityEvidence,
+ snapshot: PeerSnapshot | null,
+ ): Extract<ClientMessage, { type: "parent-edge-quality-evidence" }> | null {
+ const sampleTimestampMs = snapshot?.metrics.sampleTimestampMs;
+ if (
+ snapshot === null ||
+ typeof sampleTimestampMs !== "number" ||
+ !Number.isFinite(sampleTimestampMs)
+ ) {
+ return null;
+ }
+ const previous = this.samplesByViewer.get(evidence.viewerPeerId);
+ if (
+ previous?.connectionId === evidence.guard.connectionId &&
+ sampleTimestampMs <= previous.sampleTimestampMs
+ ) {
+ return null;
+ }
+ const message = parentEdgeQualityEvidenceFromSnapshot(evidence, snapshot);
+ if (!message) {
+ return null;
+ }
+ this.samplesByViewer.set(evidence.viewerPeerId, {
+ connectionId: evidence.guard.connectionId,
+ sampleTimestampMs,
+ });
+ return message;
+ }
+
+ forget(viewerPeerId: string): void {
+ this.samplesByViewer.delete(viewerPeerId);
+ }
+
+ reset(): void {
+ this.samplesByViewer.clear();
+ }
+}
diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx
index a21b9151..b034820b 100644
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@ -61,6 +61,9 @@ import {
type QualitySettings,
} from "../media/quality";
import { HostSfuRoute } from "../media/host-sfu-route";
+import {
+ ParentEdgeQualityEvidenceReporter,
+} from "../media/parent-edge-quality-evidence";
import { SfuStandbyPrewarmer } from "../media/sfu-standby-prewarmer";
import { metricsFromQualityEvidence } from "../media/viewer-quality-evidence";
import type {
@@ -203,6 +206,9 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
const viewerQualityEvidenceTimersRef = useRef(
new Map<string, number>(),
);
+ const parentEdgeQualityEvidenceReporterRef = useRef(
+ new ParentEdgeQualityEvidenceReporter(),
+ );
const peerAssistedRef = useRef(false);
const activeRouteRevisionRef = useRef(0);
const generationRef = useRef(0);
@@ -248,6 +254,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
);
viewerQualityEvidenceTimersRef.current.clear();
viewerQualityEvidenceRef.current.clear();
+ parentEdgeQualityEvidenceReporterRef.current.reset();
activeRouteRevisionRef.current = 0;
void hostSfuRouteRef.current?.disconnect();
hostSfuRouteRef.current = null;
@@ -361,6 +368,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
);
viewerQualityEvidenceTimersRef.current.clear();
viewerQualityEvidenceRef.current = new Map();
+ parentEdgeQualityEvidenceReporterRef.current.reset();
setViewerQualityEvidence(new Map());
activeRouteRevisionRef.current = 0;
setSignalStatus("offline");
@@ -436,6 +444,13 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
) {
return;
}
+ const parentEvidence = parentEdgeQualityEvidenceReporterRef.current.offer(
+ evidence,
+ peer.getSnapshot(),
+ );
+ if (peerAssistedRef.current && parentEvidence) {
+ signalRef.current?.send(parentEvidence);
+ }
const next = new Map(viewerQualityEvidenceRef.current);
next.set(evidence.viewerPeerId, evidence);
viewerQualityEvidenceRef.current = next;
@@ -594,6 +609,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
function removePeer(peerId: string): void {
clearViewerQualityEvidence(peerId);
+ parentEdgeQualityEvidenceReporterRef.current.forget(peerId);
peersRef.current.get(peerId)?.dispose();
peersRef.current.delete(peerId);
setPeerSnapshots((current) => {
diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsx
index a95c4475..fd404180 100644
--- a/src/client/pages/ViewerPage.tsx
+++ b/src/client/pages/ViewerPage.tsx
@@ -29,6 +29,9 @@ import { StatsGrid } from "../components/StatsGrid";
import { clearViewerGrant, getStableClientId } from "../lib/session";
import { SignalingClient } from "../lib/signaling";
import type { QualitySettings } from "../media/quality";
+import {
+ ParentEdgeQualityEvidenceReporter,
+} from "../media/parent-edge-quality-evidence";
import { relayCapacityMessageForBrowser } from "../media/relay-capability";
import { SfuStandbyPrewarmer } from "../media/sfu-standby-prewarmer";
import {
@@ -182,6 +185,8 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
const qualityEvidenceReporter = new ViewerQualityEvidenceReporter(
(message) => active && signal.send(message),
);
+ const parentEdgeQualityEvidenceReporter =
+ new ParentEdgeQualityEvidenceReporter();
function clearRelayChildEvidence(): void {
relayChildEvidenceCurrent = null;
@@ -193,14 +198,22 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
}
function acceptRelayChildEvidence(evidence: ViewerQualityEvidence): void {
+ const relaySnapshot = viewerRelay?.getSnapshot() ?? null;
if (
!peerAssisted ||
evidence.parentPeerId !== currentPeerId ||
evidence.guard.routeRevision !== currentRouteRevision ||
- !qualityEvidenceMatchesSnapshot(evidence, viewerRelay?.getSnapshot() ?? null)
+ !qualityEvidenceMatchesSnapshot(evidence, relaySnapshot)
) {
return;
}
+ const parentEvidence = parentEdgeQualityEvidenceReporter.offer(
+ evidence,
+ relaySnapshot,
+ );
+ if (parentEvidence) {
+ signal.send(parentEvidence);
+ }
clearRelayChildEvidence();
relayChildEvidenceCurrent = evidence;
setRelayChildEvidence(evidence);
@@ -288,6 +301,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
return;
}
currentAssignment = { parentPeerId: null, childPeerIds: [] };
+ parentEdgeQualityEvidenceReporter.reset();
clearPeerState();
viewerRelay?.setChild(null);
},
@@ -295,6 +309,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
if (!active || viewerSfuRoute !== route) {
return;
}
+ const previousChildId = currentAssignment.childPeerIds[0] ?? null;
currentAssignment = limitMediaAssignment(
{
parentPeerId: currentAssignment.parentPeerId,
@@ -302,6 +317,12 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
},
MAX_VIEWER_MEDIA_CHILDREN,
);
+ if (
+ previousChildId &&
+ previousChildId !== (currentAssignment.childPeerIds[0] ?? null)
+ ) {
+ parentEdgeQualityEvidenceReporter.forget(previousChildId);
+ }
ensureViewerRelay()?.setChild(
currentAssignment.childPeerIds[0] ?? null,
);
@@ -310,10 +331,17 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
if (!active || viewerSfuRoute !== route) {
return;
}
+ const previousChildId = currentAssignment.childPeerIds[0] ?? null;
currentAssignment = limitMediaAssignment(
{ parentPeerId: null, childPeerIds: assignment.childPeerIds },
MAX_VIEWER_MEDIA_CHILDREN,
);
+ if (
+ previousChildId &&
+ previousChildId !== (currentAssignment.childPeerIds[0] ?? null)
+ ) {
+ parentEdgeQualityEvidenceReporter.forget(previousChildId);
+ }
const relay = ensureViewerRelay();
relay?.setChild(currentAssignment.childPeerIds[0] ?? null);
relay?.setStream(nextStream);
@@ -396,6 +424,9 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
setStatusText("正在恢复连接");
}
if (previousChildId !== (nextAssignment.childPeerIds[0] ?? null)) {
+ if (previousChildId) {
+ parentEdgeQualityEvidenceReporter.forget(previousChildId);
+ }
clearRelayChildEvidence();
}
ensureViewerRelay()?.setChild(nextAssignment.childPeerIds[0] ?? null);
@@ -714,6 +745,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
active = false;
currentPeerId = null;
qualityEvidenceReporter.reset();
+ parentEdgeQualityEvidenceReporter.reset();
relayChildEvidenceCurrent = null;
if (relayChildEvidenceTimer !== null) {
window.clearTimeout(relayChildEvidenceTimer);
diff --git a/src/client/types.ts b/src/client/types.ts
index 2e726780..ad29facb 100644
--- a/src/client/types.ts
+++ b/src/client/types.ts
@@ -30,6 +30,7 @@ export interface ConnectionMetrics {
frameHeight: number | null;
resolution: string | null;
packetsLost: number | null;
+ intervalPacketsSent: number | null;
intervalPacketsReceived: number | null;
intervalPacketsLost: number | null;
jitterMs: number | null;
@@ -86,6 +87,7 @@ export const EMPTY_METRICS: ConnectionMetrics = {
frameHeight: null,
resolution: null,
packetsLost: null,
+ intervalPacketsSent: null,
intervalPacketsReceived: null,
intervalPacketsLost: null,
jitterMs: null,
diff --git a/src/client/webrtc/host-peer.ts b/src/client/webrtc/host-peer.ts
index c6a75f6e..9c04ac3e 100644
--- a/src/client/webrtc/host-peer.ts
+++ b/src/client/webrtc/host-peer.ts
@@ -245,6 +245,10 @@ export class HostPeer {
return this.connection.connectionState === "connected";
}
+ getSnapshot(): PeerSnapshot {
+ return { ...this.snapshot, metrics: { ...this.snapshot.metrics } };
+ }
+
updateIceConfig(iceConfig: IceConfig): void {
if (this.disposed) {
return;
diff --git a/src/client/webrtc/stats.ts b/src/client/webrtc/stats.ts
index 95d38c67..dab2a05b 100644
--- a/src/client/webrtc/stats.ts
+++ b/src/client/webrtc/stats.ts
@@ -19,6 +19,7 @@ export interface StatsAccumulator {
timestamp: number | null;
previousTotalEncodeTime: number | null;
previousTotalDecodeTime: number | null;
+ previousPacketsSent: number | null;
previousPacketsReceived: number | null;
previousPacketsLost: number | null;
previousFramesDropped: number | null;
@@ -42,6 +43,7 @@ export function createStatsAccumulator(): StatsAccumulator {
timestamp: null,
previousTotalEncodeTime: null,
previousTotalDecodeTime: null,
+ previousPacketsSent: null,
previousPacketsReceived: null,
previousPacketsLost: null,
previousFramesDropped: null,
@@ -288,6 +290,7 @@ export async function collectConnectionMetrics(
const timestamp = numberValue(media, "timestamp");
const framesEncoded = numberValue(media, "framesEncoded");
const framesDecoded = numberValue(media, "framesDecoded");
+ const packetsSent = numberValue(media, "packetsSent");
const packetsReceived = numberValue(media, "packetsReceived");
const packetsLost = numberValue(
direction === "send" ? remoteInbound : media,
@@ -359,8 +362,16 @@ export async function collectConnectionMetrics(
sampleWindowMs !== null,
)
: null;
+ const intervalPacketsSent =
+ direction === "send"
+ ? intervalDelta(
+ packetsSent,
+ previous.previousPacketsSent,
+ sampleWindowMs !== null,
+ )
+ : null;
const intervalPacketsLost =
- direction === "receive"
+ direction === "receive" || direction === "send"
? intervalDelta(
packetsLost,
previous.previousPacketsLost,
@@ -408,6 +419,7 @@ export async function collectConnectionMetrics(
previous.timestamp = timestamp;
previous.previousTotalEncodeTime = totalEncodeTime;
previous.previousTotalDecodeTime = totalDecodeTime;
+ previous.previousPacketsSent = packetsSent;
previous.previousPacketsReceived = packetsReceived;
previous.previousPacketsLost = packetsLost;
previous.previousFramesDropped = framesDropped;
@@ -456,6 +468,7 @@ export async function collectConnectionMetrics(
frameHeight: height,
resolution: width !== null && height !== null ? `${width}x${height}` : null,
packetsLost,
+ intervalPacketsSent,
intervalPacketsReceived,
intervalPacketsLost,
jitterMs:
diff --git a/src/server/hybrid-media-router.ts b/src/server/hybrid-media-router.ts
index 941c4bf6..a8f98303 100644
--- a/src/server/hybrid-media-router.ts
+++ b/src/server/hybrid-media-router.ts
@@ -4,6 +4,7 @@ import {
MAX_MEDIA_ROUTE_REVISION,
type ClientMessage,
type MediaAssignment,
+ type ParentEdgeQualityProof,
type ParticipantRouteAssignment,
type RelayDownstreamEdges,
type Role,
@@ -24,9 +25,20 @@ import type { RoomStore } from "./room-store.js";
type ErrorCode = Extract<ServerMessage, { type: "error" }>["code"];
const DEFAULT_SFU_PREPARE_TIMEOUT_MS = 5_000;
+const VIEWER_QUALITY_BAD_WINDOWS_TO_REASSIGN = 3;
+const VIEWER_QUALITY_EVIDENCE_GAP_MS = 5_000;
+const VIEWER_QUALITY_REASSIGN_COOLDOWN_MS = 30_000;
+const VIEWER_QUALITY_FREEZE_RATIO = 0.5;
+const VIEWER_QUALITY_MIN_LOSS_PACKETS = 100;
+const VIEWER_QUALITY_HIGH_LOSS_RATIO = 0.3;
interface PendingRoutePreparation {
revision: number;
intentPeerId: string;
+ routeIntent: ViewerRouteIntent;
+ qualityIntent: {
+ guard: QualityRouteIntentGuard;
+ takenOverByRouteFailure: boolean;
+ } | null;
expectedSessionIds: ReadonlyMap<string, string>;
grantsIssued: boolean;
timer: NodeJS.Timeout;
@@ -37,6 +49,47 @@ interface ViewerRouteIntent {
sessionId: string;
sfuAttempts: number;
unavailableReported: boolean;
+ qualityGuard?: QualityRouteIntentGuard;
+}
+
+interface QualityRouteIntentGuard {
+ viewerSessionId: string;
+ connectionId: string;
+ routeRevision: number;
+ parentPeerId: string;
+ parentSessionId: string;
+ exclusionOwnedByQuality: boolean;
+}
+
+interface ViewerQualityEvidenceState {
+ viewerSessionId: string;
+ parentPeerId: string;
+ parentSessionId: string;
+ connectionId: string;
+ routeRevision: number;
+ lastCorrelatedAtMs: number | null;
+ badWindowCount: number;
+ pendingViewerEvidence: {
+ acceptedAtMs: number;
+ evidence: Extract<ServerMessage, { type: "viewer-quality-evidence" }>;
+ } | null;
+}
+
+interface ForwardedViewerQualityEvidence {
+ roomId: string;
+ viewerSessionId: string;
+ parentSessionId: string;
+ evidence: Extract<ServerMessage, { type: "viewer-quality-evidence" }>;
+}
+
+interface ForwardedParentEdgeQualityEvidence {
+ roomId: string;
+ viewerSessionId: string;
+ parentSessionId: string;
+ evidence: Extract<
+ ClientMessage,
+ { type: "parent-edge-quality-evidence" }
+ >;
}
type SfuPrepareResult = "started" | "busy" | "unavailable";
@@ -54,6 +107,7 @@ export interface HybridMediaRouterOptions {
sendToSession: (sessionId: string, message: ServerMessage) => void;
getConnectionId: (roomId: string, viewerPeerId: string) => string | undefined;
deleteConnectionId: (roomId: string, viewerPeerId: string) => void;
+ now?: () => number;
}
export interface HybridAuthenticationState {
@@ -95,6 +149,14 @@ export class HybridMediaRouter {
Map<string, string>
>();
private readonly sfuDisabledRoomIds = new Set<string>();
+ private readonly viewerQualityEvidenceStates = new Map<
+ string,
+ ViewerQualityEvidenceState
+ >();
+ private readonly roomQualityMigrationCooldownUntilMs = new Map<
+ string,
+ number
+ >();
constructor(private readonly options: HybridMediaRouterOptions) {
const fallback = options.sfuFallback;
@@ -125,13 +187,17 @@ export class HybridMediaRouter {
this.consumedSfuRefreshesByRoom.clear();
this.relayCapacitySessionsByRoom.clear();
this.sfuDisabledRoomIds.clear();
+ this.viewerQualityEvidenceStates.clear();
+ this.roomQualityMigrationCooldownUntilMs.clear();
}
connectParticipant(input: AuthenticatedRouteParticipant): HybridAuthenticationState {
+ this.clearRoomViewerQualityEvidenceStates(input.roomId);
this.clearSfuRefreshesForPeer(input.roomId, input.peerId);
if (input.role === "viewer") {
+ const connectionKey = viewerConnectionKey(input.roomId, input.peerId);
this.failedParentPeerIdsByViewer.delete(
- viewerConnectionKey(input.roomId, input.peerId),
+ connectionKey,
);
this.viewerRouteIntentsByRoom.get(input.roomId)?.delete(input.peerId);
this.relayCapacitySessionsByRoom.get(input.roomId)?.delete(input.peerId);
@@ -238,6 +304,179 @@ export class HybridMediaRouter {
};
}
+ handleViewerQualityEvidence(input: ForwardedViewerQualityEvidence): void {
+ const { evidence, roomId, viewerSessionId, parentSessionId } = input;
+ const { viewerPeerId, parentPeerId } = evidence;
+ const viewer = this.options.roomStore.getConnectedViewer(
+ roomId,
+ viewerPeerId,
+ );
+ const parent = this.connectedPeer(roomId, parentPeerId);
+ const edge = this.resolveActivePeerEdge(roomId, viewerPeerId);
+ if (
+ viewer?.sessionId !== viewerSessionId ||
+ parent?.sessionId !== parentSessionId ||
+ edge?.parentPeerId !== parentPeerId ||
+ edge.revision !== evidence.guard.routeRevision ||
+ this.options.getConnectionId(roomId, viewerPeerId) !==
+ evidence.guard.connectionId
+ ) {
+ return;
+ }
+
+ const connectionKey = viewerConnectionKey(roomId, viewerPeerId);
+ const existingIntent = this.viewerRouteIntentsByRoom
+ .get(roomId)
+ ?.get(viewerPeerId);
+ if (
+ existingIntent?.qualityGuard &&
+ !this.qualityIntentIsCurrent(roomId, viewerPeerId, existingIntent)
+ ) {
+ this.discardQualityIntent(roomId, viewerPeerId, existingIntent);
+ }
+ const now = this.options.now?.() ?? Date.now();
+ if (!Number.isFinite(now)) {
+ return;
+ }
+ const previous = this.viewerQualityEvidenceStates.get(connectionKey);
+ const sameIdentity =
+ previous?.viewerSessionId === viewerSessionId &&
+ previous.parentPeerId === parentPeerId &&
+ previous.parentSessionId === parentSessionId &&
+ previous.connectionId === evidence.guard.connectionId &&
+ previous.routeRevision === evidence.guard.routeRevision;
+ const canContinueStreak =
+ sameIdentity &&
+ previous !== undefined &&
+ previous.pendingViewerEvidence === null &&
+ previous.lastCorrelatedAtMs !== null &&
+ now - previous.lastCorrelatedAtMs <= VIEWER_QUALITY_EVIDENCE_GAP_MS;
+ this.viewerQualityEvidenceStates.set(connectionKey, {
+ viewerSessionId,
+ parentPeerId,
+ parentSessionId,
+ connectionId: evidence.guard.connectionId,
+ routeRevision: evidence.guard.routeRevision,
+ lastCorrelatedAtMs: canContinueStreak
+ ? previous.lastCorrelatedAtMs
+ : null,
+ badWindowCount: canContinueStreak ? previous.badWindowCount : 0,
+ pendingViewerEvidence: { acceptedAtMs: now, evidence },
+ });
+ }
+
+ handleParentEdgeQualityEvidence(
+ input: ForwardedParentEdgeQualityEvidence,
+ ): void {
+ const { evidence, roomId, viewerSessionId, parentSessionId } = input;
+ const viewerPeerId = evidence.viewerPeerId;
+ const viewer = this.options.roomStore.getConnectedViewer(
+ roomId,
+ viewerPeerId,
+ );
+ const edge = this.resolveActivePeerEdge(roomId, viewerPeerId);
+ const parent = edge
+ ? this.connectedPeer(roomId, edge.parentPeerId)
+ : undefined;
+ if (
+ viewer?.sessionId !== viewerSessionId ||
+ parent?.sessionId !== parentSessionId ||
+ edge?.revision !== evidence.guard.routeRevision ||
+ this.options.getConnectionId(roomId, viewerPeerId) !==
+ evidence.guard.connectionId
+ ) {
+ return;
+ }
+
+ const connectionKey = viewerConnectionKey(roomId, viewerPeerId);
+ const state = this.viewerQualityEvidenceStates.get(connectionKey);
+ const pending = state?.pendingViewerEvidence;
+ if (
+ !state ||
+ !pending ||
+ state.viewerSessionId !== viewerSessionId ||
+ state.parentPeerId !== edge.parentPeerId ||
+ state.parentSessionId !== parentSessionId ||
+ state.connectionId !== evidence.guard.connectionId ||
+ state.routeRevision !== evidence.guard.routeRevision ||
+ pending.evidence.sequence !== evidence.viewerSequence
+ ) {
+ return;
+ }
+ state.pendingViewerEvidence = null;
+
+ const now = this.options.now?.() ?? Date.now();
+ if (
+ !Number.isFinite(now) ||
+ now < pending.acceptedAtMs ||
+ now - pending.acceptedAtMs > VIEWER_QUALITY_EVIDENCE_GAP_MS
+ ) {
+ state.badWindowCount = 0;
+ state.lastCorrelatedAtMs = null;
+ return;
+ }
+ const cooldownUntil = this.roomQualityMigrationCooldownUntilMs.get(roomId);
+ if (cooldownUntil !== undefined && now < cooldownUntil) {
+ state.badWindowCount = 0;
+ state.lastCorrelatedAtMs = now;
+ return;
+ }
+ if (cooldownUntil !== undefined) {
+ this.roomQualityMigrationCooldownUntilMs.delete(roomId);
+ }
+ const existingIntent = this.viewerRouteIntentsByRoom
+ .get(roomId)
+ ?.get(viewerPeerId);
+ const failedParents = this.failedParentPeerIdsByViewer.get(connectionKey);
+ if (existingIntent || failedParents?.has(edge.parentPeerId)) {
+ state.badWindowCount = 0;
+ state.lastCorrelatedAtMs = now;
+ return;
+ }
+
+ const hardBad =
+ isHardBadViewerQualityWindow(pending.evidence) &&
+ isHardBadParentEdgeQualityProof(evidence.proof);
+ state.badWindowCount = hardBad
+ ? state.lastCorrelatedAtMs !== null &&
+ now - state.lastCorrelatedAtMs <= VIEWER_QUALITY_EVIDENCE_GAP_MS
+ ? state.badWindowCount + 1
+ : 1
+ : 0;
+ state.lastCorrelatedAtMs = now;
+ if (state.badWindowCount < VIEWER_QUALITY_BAD_WINDOWS_TO_REASSIGN) {
+ return;
+ }
+
+ let roomIntents = this.viewerRouteIntentsByRoom.get(roomId);
+ if (!roomIntents) {
+ roomIntents = new Map();
+ this.viewerRouteIntentsByRoom.set(roomId, roomIntents);
+ }
+ let excludedParents = this.failedParentPeerIdsByViewer.get(connectionKey);
+ if (!excludedParents) {
+ excludedParents = new Set();
+ this.failedParentPeerIdsByViewer.set(connectionKey, excludedParents);
+ }
+ excludedParents.add(edge.parentPeerId);
+ roomIntents.set(viewerPeerId, {
+ failedParentPeerId: edge.parentPeerId,
+ sessionId: viewerSessionId,
+ sfuAttempts: 0,
+ unavailableReported: false,
+ qualityGuard: {
+ viewerSessionId,
+ connectionId: evidence.guard.connectionId,
+ routeRevision: evidence.guard.routeRevision,
+ parentPeerId: edge.parentPeerId,
+ parentSessionId,
+ exclusionOwnedByQuality: true,
+ },
+ });
+ this.viewerQualityEvidenceStates.delete(connectionKey);
+ this.drainViewerRouteIntents(roomId);
+ }
+
setViewerRelayCapacity(
participant: AuthenticatedRouteParticipant,
downstreamEdges: RelayDownstreamEdges,
@@ -410,6 +649,24 @@ export class HybridMediaRouter {
this.failedParentPeerIdsByViewer.set(connectionKey, failedParents);
}
if (failedParents.has(assignment.upstream.peerId)) {
+ const existingIntent = this.viewerRouteIntentsByRoom
+ .get(participant.roomId)
+ ?.get(participant.peerId);
+ if (
+ existingIntent?.qualityGuard?.parentPeerId ===
+ assignment.upstream.peerId
+ ) {
+ const pending = this.pendingRoutePreparations.get(participant.roomId);
+ if (
+ pending?.intentPeerId === participant.peerId &&
+ pending.routeIntent === existingIntent &&
+ pending.qualityIntent
+ ) {
+ pending.qualityIntent.takenOverByRouteFailure = true;
+ }
+ existingIntent.qualityGuard.exclusionOwnedByQuality = false;
+ existingIntent.qualityGuard = undefined;
+ }
return;
}
failedParents.add(assignment.upstream.peerId);
@@ -441,7 +698,8 @@ export class HybridMediaRouter {
);
}
- disconnectParticipant(roomId: string): void {
+ disconnectParticipant(roomId: string, peerId: string): void {
+ this.clearViewerQualityStateForParticipant(roomId, peerId);
const pending = this.pendingRoutePreparations.get(roomId);
if (!pending || this.pendingSessionsAreCurrent(roomId, pending)) {
return;
@@ -450,6 +708,7 @@ export class HybridMediaRouter {
}
removeViewer(roomId: string, peerId: string): void {
+ this.clearViewerQualityStateForParticipant(roomId, peerId);
this.abortPendingRouteForTopologyChange(roomId);
const changes = this.peerRelayTopology.removeViewer(
roomId,
@@ -618,6 +877,13 @@ export class HybridMediaRouter {
private drainViewerRouteIntents(roomId: string): void {
this.enqueueUnassignedViewerIntents(roomId);
+ const pending = this.pendingRoutePreparations.get(roomId);
+ if (pending) {
+ if (this.abortStalePendingQualityIntent(roomId, pending)) {
+ return;
+ }
+ return;
+ }
if (this.pendingRoutePreparations.has(roomId)) {
return;
}
@@ -627,6 +893,13 @@ export class HybridMediaRouter {
}
for (const [viewerPeerId, intent] of [...intents]) {
+ if (
+ intent.qualityGuard &&
+ !this.qualityIntentIsCurrent(roomId, viewerPeerId, intent)
+ ) {
+ this.discardQualityIntent(roomId, viewerPeerId, intent);
+ continue;
+ }
const viewer = this.options.roomStore.getConnectedViewer(
roomId,
viewerPeerId,
@@ -636,7 +909,11 @@ export class HybridMediaRouter {
?.getActiveRoute()
.assignments.get(viewerPeerId);
if (viewer?.sessionId !== intent.sessionId || !assignment) {
- intents.delete(viewerPeerId);
+ if (intent.qualityGuard) {
+ this.discardQualityIntent(roomId, viewerPeerId, intent);
+ } else {
+ intents.delete(viewerPeerId);
+ }
continue;
}
if (intent.failedParentPeerId === null) {
@@ -661,6 +938,13 @@ export class HybridMediaRouter {
) {
excludedParents.add(hostPeerId);
}
+ if (
+ intent.qualityGuard &&
+ !this.qualityIntentIsCurrent(roomId, viewerPeerId, intent)
+ ) {
+ this.discardQualityIntent(roomId, viewerPeerId, intent);
+ continue;
+ }
const changes = this.peerRelayTopology.reassignViewer(
roomId,
viewerPeerId,
@@ -669,6 +953,15 @@ export class HybridMediaRouter {
MAX_PEER_RELAY_DEPTH,
);
if (changes) {
+ if (intent.qualityGuard) {
+ this.startRoomQualityMigrationCooldown(roomId);
+ this.releaseQualityOwnedParentExclusion(
+ roomId,
+ viewerPeerId,
+ intent,
+ intent.qualityGuard,
+ );
+ }
intents.delete(viewerPeerId);
this.clearChangedConnectionIds(roomId, changes);
this.reconcileMediaRoute(roomId);
@@ -687,7 +980,18 @@ export class HybridMediaRouter {
viewerConnectionKey(roomId, viewerPeerId),
);
if (!failedParents?.has(intent.failedParentPeerId)) {
- intents.delete(viewerPeerId);
+ if (intent.qualityGuard) {
+ this.discardQualityIntent(roomId, viewerPeerId, intent);
+ } else {
+ intents.delete(viewerPeerId);
+ }
+ continue;
+ }
+ if (
+ intent.qualityGuard &&
+ !this.qualityIntentIsCurrent(roomId, viewerPeerId, intent)
+ ) {
+ this.discardQualityIntent(roomId, viewerPeerId, intent);
continue;
}
const changes = this.peerRelayTopology.reassignViewer(
@@ -698,6 +1002,15 @@ export class HybridMediaRouter {
MAX_PEER_RELAY_DEPTH,
);
if (changes) {
+ if (intent.qualityGuard) {
+ this.startRoomQualityMigrationCooldown(roomId);
+ this.releaseQualityOwnedParentExclusion(
+ roomId,
+ viewerPeerId,
+ intent,
+ intent.qualityGuard,
+ );
+ }
intents.delete(viewerPeerId);
this.clearChangedConnectionIds(roomId, changes);
this.reconcileMediaRoute(roomId);
@@ -711,12 +1024,23 @@ export class HybridMediaRouter {
this.options.sfuFallback &&
!this.sfuDisabledRoomIds.has(roomId)
) {
+ if (
+ intent.qualityGuard &&
+ !this.qualityIntentIsCurrent(roomId, viewerPeerId, intent)
+ ) {
+ this.discardQualityIntent(roomId, viewerPeerId, intent);
+ continue;
+ }
const result = this.prepareSfuFallback(
roomId,
viewerPeerId,
intent.sessionId,
+ intent,
);
if (result === "started") {
+ if (intent.qualityGuard) {
+ this.startRoomQualityMigrationCooldown(roomId);
+ }
intent.sfuAttempts += 1;
return;
}
@@ -740,10 +1064,83 @@ export class HybridMediaRouter {
}
}
+ private qualityIntentIsCurrent(
+ roomId: string,
+ viewerPeerId: string,
+ intent: ViewerRouteIntent,
+ ): boolean {
+ const guard = intent.qualityGuard;
+ if (!guard) {
+ return true;
+ }
+ const edge = this.resolveActivePeerEdge(roomId, viewerPeerId);
+ return (
+ this.options.roomStore.getConnectedViewer(roomId, viewerPeerId)
+ ?.sessionId === guard.viewerSessionId &&
+ this.connectedPeer(roomId, guard.parentPeerId)?.sessionId ===
+ guard.parentSessionId &&
+ edge?.parentPeerId === guard.parentPeerId &&
+ edge.revision === guard.routeRevision &&
+ this.options.getConnectionId(roomId, viewerPeerId) === guard.connectionId
+ );
+ }
+
+ private discardQualityIntent(
+ roomId: string,
+ viewerPeerId: string,
+ intent: ViewerRouteIntent,
+ ): void {
+ const guard = intent.qualityGuard;
+ const intents = this.viewerRouteIntentsByRoom.get(roomId);
+ if (!guard || intents?.get(viewerPeerId) !== intent) {
+ return;
+ }
+ intents.delete(viewerPeerId);
+ if (intents.size === 0) {
+ this.viewerRouteIntentsByRoom.delete(roomId);
+ }
+ this.releaseQualityOwnedParentExclusion(
+ roomId,
+ viewerPeerId,
+ intent,
+ guard,
+ );
+ this.viewerQualityEvidenceStates.delete(
+ viewerConnectionKey(roomId, viewerPeerId),
+ );
+ }
+
+ private releaseQualityOwnedParentExclusion(
+ roomId: string,
+ viewerPeerId: string,
+ excludedIntent: ViewerRouteIntent,
+ guard: QualityRouteIntentGuard,
+ ): void {
+ if (!guard.exclusionOwnedByQuality) {
+ return;
+ }
+ const currentIntent = this.viewerRouteIntentsByRoom
+ .get(roomId)
+ ?.get(viewerPeerId);
+ if (
+ currentIntent !== excludedIntent &&
+ currentIntent?.failedParentPeerId === guard.parentPeerId
+ ) {
+ return;
+ }
+ const connectionKey = viewerConnectionKey(roomId, viewerPeerId);
+ const failedParents = this.failedParentPeerIdsByViewer.get(connectionKey);
+ failedParents?.delete(guard.parentPeerId);
+ if (failedParents?.size === 0) {
+ this.failedParentPeerIdsByViewer.delete(connectionKey);
+ }
+ }
+
private prepareSfuFallback(
roomId: string,
failedPeerId: string,
sourceSessionId: string,
+ routeIntent: ViewerRouteIntent,
): SfuPrepareResult {
const fallback = this.options.sfuFallback;
const controller = this.mediaRouteControllers.get(roomId);
@@ -896,6 +1293,13 @@ export class HybridMediaRouter {
this.pendingRoutePreparations.set(roomId, {
revision,
intentPeerId: failedPeerId,
+ routeIntent,
+ qualityIntent: routeIntent.qualityGuard
+ ? {
+ guard: { ...routeIntent.qualityGuard },
+ takenOverByRouteFailure: false,
+ }
+ : null,
expectedSessionIds,
grantsIssued: false,
timer,
@@ -953,6 +1357,9 @@ export class HybridMediaRouter {
this.abortPendingRoute(roomId);
return;
}
+ if (this.abortStalePendingQualityIntent(roomId, pending)) {
+ return;
+ }
for (const { peerId, sessionId, token } of grants) {
const assignment = pendingRoute.route.assignments.get(peerId);
if (!assignment) {
@@ -999,6 +1406,9 @@ export class HybridMediaRouter {
}
return;
}
+ if (this.abortStalePendingQualityIntent(roomId, pending)) {
+ return;
+ }
const before = controller.getActiveRoute();
if (!controller.commit(revision)) {
return;
@@ -1040,14 +1450,14 @@ export class HybridMediaRouter {
excludedPeerId?: string,
): void {
const pending = this.pendingRoutePreparations.get(roomId);
- const intent = pending
+ const currentIntent = pending
? this.viewerRouteIntentsByRoom
.get(roomId)
?.get(pending.intentPeerId)
: undefined;
- if (intent) {
- intent.sfuAttempts = 0;
- intent.unavailableReported = false;
+ if (pending && currentIntent === pending.routeIntent) {
+ pending.routeIntent.sfuAttempts = 0;
+ pending.routeIntent.unavailableReported = false;
}
this.abortPendingRoute(roomId, excludedPeerId, false);
}
@@ -1064,6 +1474,69 @@ export class HybridMediaRouter {
return true;
}
+ private abortStalePendingQualityIntent(
+ roomId: string,
+ pending: PendingRoutePreparation,
+ ): boolean {
+ if (this.pendingQualityIntentIsCurrent(roomId, pending)) {
+ return false;
+ }
+ this.abortPendingRoute(roomId, undefined, false);
+ const qualityIntent = pending.qualityIntent;
+ if (qualityIntent && !qualityIntent.takenOverByRouteFailure) {
+ const currentIntent = this.viewerRouteIntentsByRoom
+ .get(roomId)
+ ?.get(pending.intentPeerId);
+ if (
+ currentIntent === pending.routeIntent &&
+ currentIntent.qualityGuard
+ ) {
+ this.discardQualityIntent(
+ roomId,
+ pending.intentPeerId,
+ currentIntent,
+ );
+ } else {
+ this.releaseQualityOwnedParentExclusion(
+ roomId,
+ pending.intentPeerId,
+ pending.routeIntent,
+ qualityIntent.guard,
+ );
+ }
+ }
+ this.drainViewerRouteIntents(roomId);
+ return true;
+ }
+
+ private pendingQualityIntentIsCurrent(
+ roomId: string,
+ pending: PendingRoutePreparation,
+ ): boolean {
+ const qualityIntent = pending.qualityIntent;
+ if (!qualityIntent) {
+ return true;
+ }
+ const currentIntent = this.viewerRouteIntentsByRoom
+ .get(roomId)
+ ?.get(pending.intentPeerId);
+ if (currentIntent !== pending.routeIntent) {
+ return false;
+ }
+ if (qualityIntent.takenOverByRouteFailure) {
+ return (
+ currentIntent.qualityGuard === undefined &&
+ currentIntent.failedParentPeerId === qualityIntent.guard.parentPeerId
+ );
+ }
+ const currentGuard = currentIntent.qualityGuard;
+ return (
+ currentGuard !== undefined &&
+ sameQualityRouteIntentGuard(currentGuard, qualityIntent.guard) &&
+ this.qualityIntentIsCurrent(roomId, pending.intentPeerId, currentIntent)
+ );
+ }
+
private async sendFreshSfuConfig(
roomId: string,
peerId: string,
@@ -1247,6 +1720,7 @@ export class HybridMediaRouter {
route: RoomMediaRoute,
excludedPeerId?: string,
): void {
+ this.clearRoomViewerQualityEvidenceStates(roomId);
for (const [peerId, assignment] of route.assignments) {
if (peerId === excludedPeerId) {
continue;
@@ -1382,6 +1856,8 @@ export class HybridMediaRouter {
this.viewerRouteIntentsByRoom.delete(roomId);
this.consumedSfuRefreshesByRoom.delete(roomId);
this.sfuDisabledRoomIds.delete(roomId);
+ this.clearRoomViewerQualityEvidenceStates(roomId);
+ this.roomQualityMigrationCooldownUntilMs.delete(roomId);
}
private clearSfuRefreshesForPeer(roomId: string, peerId: string): void {
@@ -1400,6 +1876,48 @@ export class HybridMediaRouter {
}
}
+ private startRoomQualityMigrationCooldown(roomId: string): void {
+ const now = this.options.now?.() ?? Date.now();
+ if (!Number.isFinite(now)) {
+ return;
+ }
+ this.roomQualityMigrationCooldownUntilMs.set(
+ roomId,
+ now + VIEWER_QUALITY_REASSIGN_COOLDOWN_MS,
+ );
+ }
+
+ private clearViewerQualityStateForParticipant(
+ roomId: string,
+ peerId: string,
+ ): void {
+ const intents = this.viewerRouteIntentsByRoom.get(roomId);
+ for (const [viewerPeerId, intent] of [...(intents ?? [])]) {
+ if (
+ intent.qualityGuard &&
+ (viewerPeerId === peerId || intent.qualityGuard.parentPeerId === peerId)
+ ) {
+ this.discardQualityIntent(roomId, viewerPeerId, intent);
+ }
+ }
+ const connectionKey = viewerConnectionKey(roomId, peerId);
+ this.viewerQualityEvidenceStates.delete(connectionKey);
+ for (const [key, state] of this.viewerQualityEvidenceStates) {
+ if (key.startsWith(`${roomId}:`) && state.parentPeerId === peerId) {
+ this.viewerQualityEvidenceStates.delete(key);
+ }
+ }
+ }
+
+ private clearRoomViewerQualityEvidenceStates(roomId: string): void {
+ const prefix = `${roomId}:`;
+ for (const key of this.viewerQualityEvidenceStates.keys()) {
+ if (key.startsWith(prefix)) {
+ this.viewerQualityEvidenceStates.delete(key);
+ }
+ }
+ }
+
private enqueueUnassignedViewerIntents(roomId: string): void {
const advertised = this.relayCapacitySessionsByRoom.get(roomId);
const assignments = this.mediaRouteControllers
@@ -1444,6 +1962,20 @@ function viewerConnectionKey(roomId: string, peerId: string): string {
return `${roomId}:${peerId}`;
}
+function sameQualityRouteIntentGuard(
+ left: QualityRouteIntentGuard,
+ right: QualityRouteIntentGuard,
+): boolean {
+ return (
+ left.viewerSessionId === right.viewerSessionId &&
+ left.connectionId === right.connectionId &&
+ left.routeRevision === right.routeRevision &&
+ left.parentPeerId === right.parentPeerId &&
+ left.parentSessionId === right.parentSessionId &&
+ left.exclusionOwnedByQuality === right.exclusionOwnedByQuality
+ );
+}
+
function sfuRefreshKey(
publicationGeneration: string,
peerId: string,
@@ -1621,3 +2153,51 @@ function sameUpstream(
left.upstream.peerId === right.upstream.peerId))
);
}
+
+function isHardBadViewerQualityWindow(
+ evidence: Extract<ServerMessage, { type: "viewer-quality-evidence" }>,
+): boolean {
+ const metrics = evidence.metrics;
+ const freezeRatio =
+ metrics.freezeDurationMsDelta === null
+ ? null
+ : metrics.freezeDurationMsDelta / evidence.windowMs;
+ if (freezeRatio !== null && freezeRatio >= VIEWER_QUALITY_FREEZE_RATIO) {
+ return true;
+ }
+ if (
+ metrics.packetsReceivedDelta !== null &&
+ metrics.packetsReceivedDelta > 0 &&
+ metrics.framesDecodedDelta === 0
+ ) {
+ return true;
+ }
+ if (
+ metrics.packetsReceivedDelta === null ||
+ metrics.packetsLostDelta === null
+ ) {
+ return false;
+ }
+ const totalPackets =
+ metrics.packetsReceivedDelta + metrics.packetsLostDelta;
+ return (
+ totalPackets >= VIEWER_QUALITY_MIN_LOSS_PACKETS &&
+ metrics.packetsLostDelta / totalPackets >= VIEWER_QUALITY_HIGH_LOSS_RATIO
+ );
+}
+
+function isHardBadParentEdgeQualityProof(
+ proof: ParentEdgeQualityProof,
+): boolean {
+ if (proof.kind === "sender-limited") {
+ return true;
+ }
+ if (proof.kind !== "remote-loss") {
+ return false;
+ }
+ return (
+ proof.packetsSentDelta >= VIEWER_QUALITY_MIN_LOSS_PACKETS &&
+ proof.remotePacketsLostDelta / proof.packetsSentDelta >=
+ VIEWER_QUALITY_HIGH_LOSS_RATIO
+ );
+}
diff --git a/src/server/signaling.ts b/src/server/signaling.ts
index 4fa784f8..8512ef22 100644
--- a/src/server/signaling.ts
+++ b/src/server/signaling.ts
@@ -6,10 +6,12 @@ import WebSocket, { WebSocketServer } from "ws";
import {
DEFAULT_QUALITY_SETTINGS,
+ MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES,
MAX_SIGNAL_BYTES,
MAX_VIEWER_QUALITY_EVIDENCE_BYTES,
SIGNALING_PROTOCOL,
VIEWER_QUALITY_EVIDENCE_INTERVAL_MS,
+ VIEWER_QUALITY_EVIDENCE_EXPIRY_MS,
decodeClientMessage,
type ClientMessage,
type QualitySettings,
@@ -58,6 +60,7 @@ interface ViewerQualityEvidenceGate {
routeRevision: number;
sequence: number;
acceptedAtMs: number;
+ parentEvidenceAccepted: boolean;
}
export interface SignalingOptions {
@@ -149,6 +152,7 @@ export class SignalingServer {
),
deleteConnectionId: (roomId, viewerPeerId) =>
this.deleteViewerConnectionId(roomId, viewerPeerId),
+ now: this.now,
});
}
@@ -284,8 +288,12 @@ export class SignalingServer {
return;
}
if (
- message.type === "viewer-quality-evidence" &&
- Buffer.byteLength(encoded, "utf8") > MAX_VIEWER_QUALITY_EVIDENCE_BYTES
+ ((message.type === "viewer-quality-evidence" &&
+ Buffer.byteLength(encoded, "utf8") >
+ MAX_VIEWER_QUALITY_EVIDENCE_BYTES) ||
+ (message.type === "parent-edge-quality-evidence" &&
+ Buffer.byteLength(encoded, "utf8") >
+ MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES))
) {
this.rejectInvalidMessage(socket);
return;
@@ -619,6 +627,9 @@ export class SignalingServer {
case "viewer-quality-evidence":
this.handleViewerQualityEvidence(socket, authenticated, message);
return;
+ case "parent-edge-quality-evidence":
+ this.handleParentEdgeQualityEvidence(socket, authenticated, message);
+ return;
case "set-viewer-access":
if (authenticated.role !== "host") {
this.sendError(
@@ -832,6 +843,73 @@ export class SignalingServer {
routeRevision,
sequence: message.sequence,
acceptedAtMs: now,
+ parentEvidenceAccepted: false,
+ });
+ if (this.isPeerAssistedRoom(source.roomId)) {
+ this.hybridMediaRouter!.handleViewerQualityEvidence({
+ roomId: source.roomId,
+ viewerSessionId: viewerState.sessionId,
+ parentSessionId: parent.sessionId,
+ evidence: forwarded,
+ });
+ }
+ }
+
+ private handleParentEdgeQualityEvidence(
+ socket: WebSocket,
+ source: AuthenticatedSession,
+ message: Extract<
+ ClientMessage,
+ { type: "parent-edge-quality-evidence" }
+ >,
+ ): void {
+ if (!this.isPeerAssistedRoom(source.roomId)) {
+ return;
+ }
+ const sourceState = this.socketStates.get(socket);
+ if (!sourceState || sourceState.authenticated !== source) {
+ return;
+ }
+ const viewer = this.options.roomStore.getConnectedViewer(
+ source.roomId,
+ message.viewerPeerId,
+ );
+ const gate = this.viewerQualityEvidenceGates.get(
+ viewerConnectionKey(source.roomId, message.viewerPeerId),
+ );
+ const edge = this.hybridMediaRouter?.resolveActivePeerEdge(
+ source.roomId,
+ message.viewerPeerId,
+ );
+ const connectionId = this.connectionIdsByViewer.get(
+ viewerConnectionKey(source.roomId, message.viewerPeerId),
+ );
+ const now = this.now();
+ if (
+ !viewer ||
+ !gate ||
+ gate.parentEvidenceAccepted ||
+ source.peerId !== gate.parentPeerId ||
+ sourceState.sessionId !== gate.parentSessionId ||
+ viewer.sessionId !== gate.viewerSessionId ||
+ connectionId !== gate.connectionId ||
+ edge?.parentPeerId !== source.peerId ||
+ edge.revision !== gate.routeRevision ||
+ message.guard.connectionId !== gate.connectionId ||
+ message.guard.routeRevision !== gate.routeRevision ||
+ message.viewerSequence !== gate.sequence ||
+ now < gate.acceptedAtMs ||
+ now - gate.acceptedAtMs > VIEWER_QUALITY_EVIDENCE_EXPIRY_MS
+ ) {
+ return;
+ }
+
+ gate.parentEvidenceAccepted = true;
+ this.hybridMediaRouter!.handleParentEdgeQualityEvidence({
+ roomId: source.roomId,
+ viewerSessionId: viewer.sessionId,
+ parentSessionId: sourceState.sessionId,
+ evidence: message,
});
}
@@ -1026,7 +1104,10 @@ export class SignalingServer {
return;
}
if (this.isPeerAssistedRoom(disconnected.roomId)) {
- this.hybridMediaRouter!.disconnectParticipant(disconnected.roomId);
+ this.hybridMediaRouter!.disconnectParticipant(
+ disconnected.roomId,
+ disconnected.peerId,
+ );
}
if (disconnected.role === "host") {
for (const viewer of this.options.roomStore.getConnectedViewers(
diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts
index c0f5d0ba..028fd888 100644
--- a/src/shared/protocol.ts
+++ b/src/shared/protocol.ts
@@ -10,6 +10,7 @@ export const MAX_MEDIA_ROUTE_REVISION = Number.MAX_SAFE_INTEGER;
export const MAX_SFU_TOKEN_LENGTH = 8 * 1024;
export const MAX_ICE_SERVER_URLS = 8;
export const MAX_VIEWER_QUALITY_EVIDENCE_BYTES = 2 * 1024;
+export const MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES = 2 * 1024;
export const VIEWER_QUALITY_EVIDENCE_INTERVAL_MS = 2_000;
export const VIEWER_QUALITY_EVIDENCE_EXPIRY_MS = 5_000;
@@ -325,6 +326,45 @@ export type ViewerQualityEvidenceMessage = z.infer<
typeof viewerQualityEvidenceMessageSchema
>;
+const parentEdgeQualityProofSchema = z.discriminatedUnion("kind", [
+ z
+ .object({
+ kind: z.literal("sending"),
+ packetsSentDelta: z.number().int().min(1).max(1_000_000),
+ })
+ .strict(),
+ z
+ .object({
+ kind: z.literal("sender-limited"),
+ packetsSentDelta: z.number().int().min(1).max(1_000_000),
+ reason: z.enum(["cpu", "bandwidth"]),
+ })
+ .strict(),
+ z
+ .object({
+ kind: z.literal("remote-loss"),
+ packetsSentDelta: z.number().int().min(1).max(1_000_000),
+ remotePacketsLostDelta: z.number().int().min(1).max(1_000_000),
+ })
+ .strict(),
+]);
+export type ParentEdgeQualityProof = z.infer<
+ typeof parentEdgeQualityProofSchema
+>;
+
+export const parentEdgeQualityEvidenceMessageSchema = z
+ .object({
+ type: z.literal("parent-edge-quality-evidence"),
+ viewerPeerId: opaqueIdSchema,
+ guard: viewerQualityEvidenceGuardSchema,
+ viewerSequence: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
+ proof: parentEdgeQualityProofSchema,
+ })
+ .strict();
+export type ParentEdgeQualityEvidenceMessage = z.infer<
+ typeof parentEdgeQualityEvidenceMessageSchema
+>;
+
const authenticateMessageSchema = z.discriminatedUnion("role", [
z
.object({
@@ -400,6 +440,7 @@ export const clientMessageSchema = z.union([
})
.strict(),
viewerQualityEvidenceMessageSchema,
+ parentEdgeQualityEvidenceMessageSchema,
z
.object({
type: z.literal("set-viewer-access"),
diff --git a/tests/client-state.test.ts b/tests/client-state.test.ts
index de8e568d..bdbf7f76 100644
--- a/tests/client-state.test.ts
+++ b/tests/client-state.test.ts
@@ -867,6 +867,8 @@ describe("WebRTC stats parsing", () => {
timestamp: number,
retransmittedPacketsSent: number,
retransmittedBytesSent: number,
+ packetsSent: number,
+ packetsLost: number,
) =>
new Map<string, unknown>([
[
@@ -877,18 +879,30 @@ describe("WebRTC stats parsing", () => {
timestamp,
kind: "video",
ssrc: 101,
+ remoteId: "remote-inbound",
bytesSent: timestamp * 10,
framesEncoded: timestamp / 10,
+ packetsSent,
retransmittedPacketsSent,
retransmittedBytesSent,
},
],
+ [
+ "remote-inbound",
+ {
+ id: "remote-inbound",
+ type: "remote-inbound-rtp",
+ timestamp,
+ kind: "video",
+ packetsLost,
+ },
+ ],
]) as unknown as RTCStatsReport;
const reports = [
- outbound(1_000, 2, 200),
- outbound(2_000, 5, 800),
- outbound(3_000, 1, 100),
- outbound(4_000, 4, 700),
+ outbound(1_000, 2, 200, 100, 1),
+ outbound(2_000, 5, 800, 400, 3),
+ outbound(3_000, 1, 100, 50, 1),
+ outbound(4_000, 4, 700, 350, 4),
];
const connection = {
getStats: async () => reports.shift()!,
@@ -903,14 +917,20 @@ describe("WebRTC stats parsing", () => {
expect(first.intervalRetransmittedPackets).toBeNull();
expect(stable).toMatchObject({
+ intervalPacketsSent: 300,
+ intervalPacketsLost: 2,
intervalRetransmittedPackets: 3,
intervalRetransmittedBytes: 600,
});
expect(reset).toMatchObject({
+ intervalPacketsSent: null,
+ intervalPacketsLost: null,
intervalRetransmittedPackets: null,
intervalRetransmittedBytes: null,
});
expect(afterReset).toMatchObject({
+ intervalPacketsSent: 300,
+ intervalPacketsLost: 3,
intervalRetransmittedPackets: 3,
intervalRetransmittedBytes: 600,
});
diff --git a/tests/protocol.test.ts b/tests/protocol.test.ts
index 75f17cdd..62a9cec0 100644
--- a/tests/protocol.test.ts
+++ b/tests/protocol.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
MAX_MEDIA_ROUTE_REVISION,
+ MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES,
MAX_SFU_TOKEN_LENGTH,
MAX_VIEWER_QUALITY_EVIDENCE_BYTES,
MAX_VIEWERS_PER_ROOM_LIMIT,
@@ -50,6 +51,14 @@ const qualityEvidence = {
},
} as const;
+const parentEdgeQualityEvidence = {
+ type: "parent-edge-quality-evidence",
+ viewerPeerId: "viewer_12345678",
+ guard: qualityEvidence.guard,
+ viewerSequence: qualityEvidence.sequence,
+ proof: { kind: "sending", packetsSentDelta: 1_500 },
+} as const;
+
describe("client signaling protocol", () => {
it("rejects the removed all-room ICE refresh request", () => {
expect(clientMessageSchema.safeParse({ type: "refresh-ice" }).success).toBe(
@@ -384,6 +393,63 @@ describe("client signaling protocol", () => {
}
});
+ it("accepts only strict, bounded parent edge quality proof", () => {
+ expect(
+ clientMessageSchema.safeParse(parentEdgeQualityEvidence).success,
+ ).toBe(true);
+ expect(
+ Buffer.byteLength(JSON.stringify(parentEdgeQualityEvidence), "utf8"),
+ ).toBeLessThanOrEqual(MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES);
+ for (const reason of ["cpu", "bandwidth"] as const) {
+ expect(
+ clientMessageSchema.safeParse({
+ ...parentEdgeQualityEvidence,
+ proof: {
+ kind: "sender-limited",
+ packetsSentDelta: 1_500,
+ reason,
+ },
+ }).success,
+ ).toBe(true);
+ }
+
+ for (const invalid of [
+ { ...parentEdgeQualityEvidence, roomId },
+ { ...parentEdgeQualityEvidence, viewerSequence: -1 },
+ {
+ ...parentEdgeQualityEvidence,
+ proof: { kind: "sending", packetsSentDelta: 0 },
+ },
+ {
+ ...parentEdgeQualityEvidence,
+ proof: {
+ kind: "remote-loss",
+ packetsSentDelta: 1_500,
+ remotePacketsLostDelta: null,
+ },
+ },
+ {
+ ...parentEdgeQualityEvidence,
+ proof: {
+ kind: "sender-limited",
+ packetsSentDelta: 1_500,
+ reason: "other",
+ },
+ },
+ {
+ ...parentEdgeQualityEvidence,
+ proof: {
+ kind: "sender-limited",
+ packetsSentDelta: 1_500,
+ reason: "cpu",
+ score: 1,
+ },
+ },
+ ]) {
+ expect(clientMessageSchema.safeParse(invalid).success).toBe(false);
+ }
+ });
+
it.each([
["video/VP8", null, "max-fr=60; max-fs=8160"],
["video/VP9", "profile-id=2", "max-fs=8160"],
diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.ts
index d78730cd..95360265 100644
--- a/tests/server-signal.test.ts
+++ b/tests/server-signal.test.ts
@@ -5,12 +5,15 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import WebSocket from "ws";
import {
+ MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES,
MAX_SIGNAL_BYTES,
MAX_VIEWER_QUALITY_EVIDENCE_BYTES,
SIGNALING_PROTOCOL,
decodeServerMessage,
+ type ParentEdgeQualityProof,
type Role,
type ServerMessage,
+ type ViewerQualityEvidenceMetrics,
} from "../src/shared/protocol.ts";
import {
createScreenerServer,
@@ -21,6 +24,7 @@ import { RoomDatabase } from "../src/server/room-database.ts";
import { RoomStore, type CreatedRoom } from "../src/server/room-store.ts";
import { SignalingServer } from "../src/server/signaling.ts";
import type { SfuTokenIssuer } from "../src/server/livekit-token.ts";
+import { HybridMediaRouter } from "../src/server/hybrid-media-router.ts";
const allowedOrigin = "http://allowed.test";
const defaultQualitySettings = {
@@ -237,12 +241,51 @@ function viewerQualityEvidence(
} as const;
}
+function viewerQualityEvidenceWithMetrics(
+ connectionId: string,
+ routeRevision: number,
+ sequence: number,
+ metrics: Partial<ViewerQualityEvidenceMetrics>,
+) {
+ const evidence = viewerQualityEvidence(
+ connectionId,
+ routeRevision,
+ sequence,
+ );
+ return {
+ ...evidence,
+ metrics: { ...evidence.metrics, ...metrics },
+ };
+}
+
+async function correlateParentEdgeQualityEvidence(
+ parent: TestClient,
+ proof: ParentEdgeQualityProof = {
+ kind: "remote-loss",
+ packetsSentDelta: 100,
+ remotePacketsLostDelta: 30,
+ },
+) {
+ const viewerEvidence = await parent.inbox.next("viewer-quality-evidence");
+ parent.socket.send(
+ JSON.stringify({
+ type: "parent-edge-quality-evidence",
+ viewerPeerId: viewerEvidence.viewerPeerId,
+ guard: viewerEvidence.guard,
+ viewerSequence: viewerEvidence.sequence,
+ proof,
+ }),
+ );
+ return viewerEvidence;
+}
+
async function startSfuHarness(options: {
tokenIssuer: SfuTokenIssuer;
prepareTimeoutMs?: number;
maxRoots?: number;
viewerDisconnectGraceMs?: number;
stunUrls?: readonly string[];
+ now?: () => number;
}): Promise<SignalHarness> {
const roomStore = new RoomStore({
ttlMs: 14_400_000,
@@ -272,6 +315,7 @@ async function startSfuHarness(options: {
allowedOrigins: new Set([allowedOrigin]),
hostAdmissionAtUpgrade: () => true,
publicBaseUrl: new URL("https://share.example.test"),
+ now: options.now,
authenticationTimeoutMs: 500,
viewerDisconnectGraceMs: options.viewerDisconnectGraceMs ?? 50,
heartbeatIntervalMs: 60_000,
@@ -1715,6 +1759,825 @@ describe("WebSocket signaling", () => {
await host.inbox.expectNone(30);
});
+ it("correlates B only from the current parent session and C generation", async () => {
+ const acceptedParentEvidence = vi.spyOn(
+ HybridMediaRouter.prototype,
+ "handleParentEdgeQualityEvidence",
+ );
+ let now = 80_000;
+ const harness = await startHarness({
+ peerAssistedMedia: true,
+ now: () => now,
+ });
+ const host = await openClient(harness.webSocketUrl);
+ const hostAuth = peerAssisted(
+ await authenticate(host, harness.room, "host", "quality-guard-host"),
+ );
+ const viewer = await openClient(harness.webSocketUrl);
+ const viewerAuth = peerAssisted(
+ await authenticate(viewer, harness.room, "viewer", "quality-guard-viewer"),
+ );
+ const unrelatedParent = await openClient(harness.webSocketUrl);
+ const unrelatedParentAuth = peerAssisted(
+ await authenticate(
+ unrelatedParent,
+ harness.room,
+ "viewer",
+ "quality-guard-unrelated",
+ ),
+ );
+ const active = await nextActiveRouteAfter(
+ viewer,
+ viewerAuth.routeRevision,
+ );
+ expect(active.assignment.upstream).toEqual({
+ kind: "peer",
+ peerId: hostAuth.peerId,
+ });
+ host.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: viewerAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: "quality_guard_connection",
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
+ );
+ await viewer.inbox.next("signal");
+
+ let sequence = 0;
+ const sendBadC = async (parent: TestClient = host) => {
+ viewer.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ "quality_guard_connection",
+ active.revision,
+ sequence,
+ { packetsReceivedDelta: 70, packetsLostDelta: 30 },
+ ),
+ ),
+ );
+ sequence += 1;
+ return parent.inbox.next("viewer-quality-evidence");
+ };
+ const parentProof = (
+ evidence: Extract<ServerMessage, { type: "viewer-quality-evidence" }>,
+ ) => ({
+ type: "parent-edge-quality-evidence" as const,
+ viewerPeerId: evidence.viewerPeerId,
+ guard: evidence.guard,
+ viewerSequence: evidence.sequence,
+ proof: {
+ kind: "remote-loss" as const,
+ packetsSentDelta: 100,
+ remotePacketsLostDelta: 30,
+ },
+ });
+
+ let evidence = await sendBadC();
+ unrelatedParent.socket.send(JSON.stringify(parentProof(evidence)));
+ now += 2_000;
+
+ for (const mutate of [
+ (proof: ReturnType<typeof parentProof>) => ({
+ ...proof,
+ guard: { ...proof.guard, connectionId: "quality_guard_wrong" },
+ }),
+ (proof: ReturnType<typeof parentProof>) => ({
+ ...proof,
+ guard: { ...proof.guard, routeRevision: proof.guard.routeRevision + 1 },
+ }),
+ (proof: ReturnType<typeof parentProof>) => ({
+ ...proof,
+ viewerSequence: proof.viewerSequence + 1,
+ }),
+ ]) {
+ evidence = await sendBadC();
+ host.socket.send(JSON.stringify(mutate(parentProof(evidence))));
+ now += 2_000;
+ }
+
+ evidence = await sendBadC();
+ now += 5_001;
+ host.socket.send(JSON.stringify(parentProof(evidence)));
+
+ now += 2_000;
+ evidence = await sendBadC();
+ const replacementHost = await openClient(harness.webSocketUrl);
+ const replacementHostAuth = peerAssisted(
+ await authenticate(
+ replacementHost,
+ harness.room,
+ "host",
+ "quality-guard-host",
+ ),
+ );
+ expect(replacementHostAuth.peerId).toBe(hostAuth.peerId);
+ replacementHost.socket.send(JSON.stringify(parentProof(evidence)));
+
+ expect(acceptedParentEvidence).not.toHaveBeenCalled();
+ await expect(viewer.inbox.next("route-update", 40)).rejects.toThrow(
+ "Timed out",
+ );
+
+ now += 2_000;
+ for (let index = 0; index < 3; index += 1) {
+ evidence = await sendBadC(replacementHost);
+ const proof = parentProof(evidence);
+ replacementHost.socket.send(JSON.stringify(proof));
+ if (index === 0) {
+ replacementHost.socket.send(JSON.stringify(proof));
+ }
+ now += 2_000;
+ }
+ const moved = await nextActiveRouteAfter(viewer, active.revision);
+ expect(acceptedParentEvidence).toHaveBeenCalledTimes(3);
+ expect(moved.assignment.upstream).toEqual({
+ kind: "peer",
+ peerId: unrelatedParentAuth.peerId,
+ });
+ acceptedParentEvidence.mockRestore();
+ });
+
+ it("reparents only a viewer subtree after three hard quality windows", async () => {
+ let now = 100_000;
+ const harness = await startHarness({
+ peerAssistedMedia: true,
+ now: () => now,
+ });
+ const host = await openClient(harness.webSocketUrl);
+ const hostAuth = peerAssisted(
+ await authenticate(host, harness.room, "host", "quality-route-host"),
+ );
+ host.inbox.ignore("route-update");
+ host.inbox.ignore("media-assignment");
+
+ const parentA = await openClient(harness.webSocketUrl);
+ const parentAAuth = peerAssisted(
+ await authenticate(
+ parentA,
+ harness.room,
+ "viewer",
+ "quality-route-parent-a",
+ ),
+ );
+ expect(parentAAuth.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: hostAuth.peerId,
+ });
+ const parentB = await openClient(harness.webSocketUrl);
+ const parentBAuth = peerAssisted(
+ await authenticate(
+ parentB,
+ harness.room,
+ "viewer",
+ "quality-route-parent-b",
+ ),
+ );
+ expect(parentBAuth.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: hostAuth.peerId,
+ });
+ const subtreeRoot = await openClient(harness.webSocketUrl);
+ const subtreeRootAuth = peerAssisted(
+ await authenticate(
+ subtreeRoot,
+ harness.room,
+ "viewer",
+ "quality-route-subtree-root",
+ ),
+ );
+ expect(subtreeRootAuth.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: parentAAuth.peerId,
+ });
+ const alternateParent = await openClient(harness.webSocketUrl);
+ const alternateParentAuth = peerAssisted(
+ await authenticate(
+ alternateParent,
+ harness.room,
+ "viewer",
+ "quality-route-alternate-parent",
+ ),
+ );
+ expect(alternateParentAuth.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: parentBAuth.peerId,
+ });
+ const subtreeLeaf = await openClient(harness.webSocketUrl);
+ const subtreeLeafAuth = peerAssisted(
+ await authenticate(
+ subtreeLeaf,
+ harness.room,
+ "viewer",
+ "quality-route-subtree-leaf",
+ 0,
+ ),
+ );
+ expect(subtreeLeafAuth.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: subtreeRootAuth.peerId,
+ });
+ await nextActiveRouteRevision(
+ subtreeRoot,
+ subtreeLeafAuth.routeRevision,
+ );
+
+ parentA.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: subtreeRootAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: "quality_route_parent_a",
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
+ );
+ await subtreeRoot.inbox.next("signal");
+
+ for (let sequence = 0; sequence < 3; sequence += 1) {
+ subtreeRoot.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ "quality_route_stale",
+ subtreeLeafAuth.routeRevision,
+ sequence,
+ { framesDecodedDelta: 0 },
+ ),
+ ),
+ );
+ }
+ await expect(
+ subtreeRoot.inbox.next("route-update", 40),
+ ).rejects.toThrow("Timed out");
+
+ for (let sequence = 0; sequence < 3; sequence += 1) {
+ subtreeRoot.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ "quality_route_parent_a",
+ subtreeLeafAuth.routeRevision,
+ sequence,
+ { framesDecodedDelta: 0 },
+ ),
+ ),
+ );
+ await parentA.inbox.next("viewer-quality-evidence");
+ now += 2_000;
+ }
+ await expect(
+ subtreeRoot.inbox.next("route-update", 40),
+ ).rejects.toThrow("Timed out");
+
+ for (let sequence = 3; sequence < 6; sequence += 1) {
+ subtreeRoot.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ "quality_route_parent_a",
+ subtreeLeafAuth.routeRevision,
+ sequence,
+ { framesDecodedDelta: 0 },
+ ),
+ ),
+ );
+ await correlateParentEdgeQualityEvidence(parentA, {
+ kind: "sending",
+ packetsSentDelta: 1_500,
+ });
+ now += 2_000;
+ }
+ await expect(
+ subtreeRoot.inbox.next("route-update", 40),
+ ).rejects.toThrow("Timed out");
+
+ subtreeRoot.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ "quality_route_parent_a",
+ subtreeLeafAuth.routeRevision,
+ 6,
+ { packetsReceivedDelta: 70, packetsLostDelta: 30 },
+ ),
+ ),
+ );
+ await correlateParentEdgeQualityEvidence(parentA);
+ now += 2_000;
+ subtreeRoot.socket.send(
+ JSON.stringify(
+ viewerQualityEvidence(
+ "quality_route_parent_a",
+ subtreeLeafAuth.routeRevision,
+ 7,
+ ),
+ ),
+ );
+ await correlateParentEdgeQualityEvidence(parentA);
+ now += 2_000;
+ subtreeRoot.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ "quality_route_parent_a",
+ subtreeLeafAuth.routeRevision,
+ 8,
+ { freezeDurationMsDelta: 1_000 },
+ ),
+ ),
+ );
+ await correlateParentEdgeQualityEvidence(parentA, {
+ kind: "sender-limited",
+ packetsSentDelta: 1_500,
+ reason: "cpu",
+ });
+ now += 2_000;
+ subtreeRoot.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ "quality_route_parent_a",
+ subtreeLeafAuth.routeRevision,
+ 9,
+ { freezeDurationMsDelta: 1_000 },
+ ),
+ ),
+ );
+ await correlateParentEdgeQualityEvidence(parentA, {
+ kind: "sender-limited",
+ packetsSentDelta: 1_500,
+ reason: "bandwidth",
+ });
+ await expect(
+ subtreeRoot.inbox.next("route-update", 40),
+ ).rejects.toThrow("Timed out");
+
+ now += 2_000;
+ subtreeRoot.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ "quality_route_parent_a",
+ subtreeLeafAuth.routeRevision,
+ 10,
+ { freezeDurationMsDelta: 1_000 },
+ ),
+ ),
+ );
+ await correlateParentEdgeQualityEvidence(parentA, {
+ kind: "sender-limited",
+ packetsSentDelta: 1_500,
+ reason: "cpu",
+ });
+ const movedRoot = await nextActiveRouteAfter(
+ subtreeRoot,
+ subtreeLeafAuth.routeRevision,
+ );
+ expect(movedRoot.assignment.upstream).toEqual({
+ kind: "peer",
+ peerId: alternateParentAuth.peerId,
+ });
+ const movedLeaf = await nextActiveRouteAfter(
+ subtreeLeaf,
+ subtreeLeafAuth.routeRevision,
+ );
+ expect(movedLeaf).toMatchObject({
+ revision: movedRoot.revision,
+ assignment: {
+ upstream: { kind: "peer", peerId: subtreeRootAuth.peerId },
+ },
+ });
+ const unchangedBranch = await nextActiveRouteAfter(
+ alternateParent,
+ subtreeLeafAuth.routeRevision,
+ );
+ expect(unchangedBranch).toMatchObject({
+ revision: movedRoot.revision,
+ assignment: {
+ upstream: { kind: "peer", peerId: parentBAuth.peerId },
+ childPeerIds: [subtreeRootAuth.peerId],
+ },
+ });
+ const unchangedBranchRoot = await nextActiveRouteAfter(
+ parentB,
+ subtreeLeafAuth.routeRevision,
+ );
+ expect(unchangedBranchRoot).toMatchObject({
+ revision: movedRoot.revision,
+ assignment: {
+ upstream: { kind: "peer", peerId: hostAuth.peerId },
+ childPeerIds: [alternateParentAuth.peerId],
+ },
+ });
+
+ subtreeRoot.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: subtreeLeafAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: "quality_route_leaf",
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
+ );
+ await subtreeLeaf.inbox.next("signal");
+ for (let sequence = 0; sequence < 3; sequence += 1) {
+ now += 2_000;
+ subtreeLeaf.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ "quality_route_leaf",
+ movedRoot.revision,
+ sequence,
+ { framesDecodedDelta: 0 },
+ ),
+ ),
+ );
+ await correlateParentEdgeQualityEvidence(subtreeRoot);
+ }
+ await expect(
+ subtreeLeaf.inbox.next("route-update", 40),
+ ).rejects.toThrow("Timed out");
+ await expect(
+ subtreeLeaf.inbox.next("error", 40),
+ ).rejects.toThrow("Timed out");
+
+ alternateParent.socket.close();
+ const reattachedRoot = await nextActiveRouteAfter(
+ subtreeRoot,
+ movedRoot.revision,
+ );
+ expect(reattachedRoot.assignment.upstream).toEqual({
+ kind: "peer",
+ peerId: parentAAuth.peerId,
+ });
+
+ parentA.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: subtreeRootAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: "quality_route_reattached",
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
+ );
+ await subtreeRoot.inbox.next("signal");
+ subtreeRoot.socket.send(
+ JSON.stringify({
+ type: "route-failed",
+ revision: reattachedRoot.revision,
+ phase: "active",
+ connectionId: "quality_route_reattached",
+ }),
+ );
+ const recoveredRoot = await nextActiveRouteAfter(
+ subtreeRoot,
+ reattachedRoot.revision,
+ );
+ expect(recoveredRoot.assignment.upstream).toEqual({
+ kind: "peer",
+ peerId: parentBAuth.peerId,
+ });
+ });
+
+ it("resets a hard-quality streak after a five-second evidence gap", async () => {
+ let now = 200_000;
+ const harness = await startHarness({
+ peerAssistedMedia: true,
+ now: () => now,
+ });
+ const host = await openClient(harness.webSocketUrl);
+ const hostAuth = peerAssisted(
+ await authenticate(host, harness.room, "host", "quality-gap-host"),
+ );
+ const viewer = await openClient(harness.webSocketUrl);
+ const viewerAuth = peerAssisted(
+ await authenticate(viewer, harness.room, "viewer", "quality-gap-viewer"),
+ );
+ host.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: viewerAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: "quality_gap_connection",
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
+ );
+ await viewer.inbox.next("signal");
+
+ const sendBadWindow = async (sequence: number) => {
+ viewer.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ "quality_gap_connection",
+ viewerAuth.routeRevision,
+ sequence,
+ { framesDecodedDelta: 0 },
+ ),
+ ),
+ );
+ await correlateParentEdgeQualityEvidence(host);
+ };
+ await sendBadWindow(0);
+ now += 2_000;
+ await sendBadWindow(1);
+ now += 5_001;
+ await sendBadWindow(2);
+ await expect(viewer.inbox.next("error", 40)).rejects.toThrow("Timed out");
+ now += 2_000;
+ await sendBadWindow(3);
+ await expect(viewer.inbox.next("error", 40)).rejects.toThrow("Timed out");
+ now += 2_000;
+ await sendBadWindow(4);
+ expect(await viewer.inbox.next("error")).toMatchObject({
+ code: "PEER_NOT_FOUND",
+ message: "No media fallback route is available",
+ });
+ expect(viewerAuth.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: hostAuth.peerId,
+ });
+ });
+
+ it("breaks a hard-quality streak when newer C replaces an unmatched window", async () => {
+ let now = 225_000;
+ const harness = await startHarness({
+ peerAssistedMedia: true,
+ now: () => now,
+ });
+ const host = await openClient(harness.webSocketUrl);
+ const hostAuth = peerAssisted(
+ await authenticate(host, harness.room, "host", "quality-pending-host"),
+ );
+ const viewer = await openClient(harness.webSocketUrl);
+ const viewerAuth = peerAssisted(
+ await authenticate(
+ viewer,
+ harness.room,
+ "viewer",
+ "quality-pending-viewer",
+ ),
+ );
+ host.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: viewerAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: "quality_pending_connection",
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
+ );
+ await viewer.inbox.next("signal");
+
+ const sendBadC = (sequence: number) => {
+ viewer.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ "quality_pending_connection",
+ viewerAuth.routeRevision,
+ sequence,
+ { framesDecodedDelta: 0 },
+ ),
+ ),
+ );
+ };
+
+ sendBadC(0);
+ await correlateParentEdgeQualityEvidence(host);
+ now += 2_000;
+
+ sendBadC(1);
+ await host.inbox.next("viewer-quality-evidence");
+ now += 2_000;
+
+ sendBadC(2);
+ await correlateParentEdgeQualityEvidence(host);
+ now += 2_000;
+ sendBadC(3);
+ await correlateParentEdgeQualityEvidence(host);
+ await expect(viewer.inbox.next("error", 40)).rejects.toThrow("Timed out");
+
+ now += 2_000;
+ sendBadC(4);
+ await correlateParentEdgeQualityEvidence(host);
+ expect(await viewer.inbox.next("error")).toMatchObject({
+ code: "PEER_NOT_FOUND",
+ message: "No media fallback route is available",
+ });
+ expect(viewerAuth.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: hostAuth.peerId,
+ });
+ });
+
+ it("keeps a pending quality SFU prepare after the same intent becomes a real failure", async () => {
+ let now = 250_000;
+ let releaseTokens!: () => void;
+ let markTokenStarted!: () => void;
+ const tokenBarrier = new Promise<void>((resolve) => {
+ releaseTokens = resolve;
+ });
+ const tokenStarted = new Promise<void>((resolve) => {
+ markTokenStarted = resolve;
+ });
+ const harness = await startSfuHarness({
+ now: () => now,
+ tokenIssuer: {
+ async issueToken(request) {
+ markTokenStarted();
+ await tokenBarrier;
+ return `token-${request.peerId}`;
+ },
+ },
+ });
+ const host = await openClient(harness.webSocketUrl);
+ peerAssisted(
+ await authenticate(host, harness.room, "host", "quality-takeover-host"),
+ );
+ const viewer = await openClient(harness.webSocketUrl);
+ const viewerAuth = peerAssisted(
+ await authenticate(
+ viewer,
+ harness.room,
+ "viewer",
+ "quality-takeover-viewer",
+ ),
+ );
+ await nextActiveRouteRevision(host, viewerAuth.routeRevision);
+ host.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: viewerAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: "quality_takeover_connection",
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
+ );
+ await viewer.inbox.next("signal");
+ for (let sequence = 0; sequence < 3; sequence += 1) {
+ viewer.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ "quality_takeover_connection",
+ viewerAuth.routeRevision,
+ sequence,
+ { framesDecodedDelta: 0 },
+ ),
+ ),
+ );
+ await correlateParentEdgeQualityEvidence(host);
+ now += 2_000;
+ }
+ await tokenStarted;
+
+ viewer.socket.send(
+ JSON.stringify({
+ type: "route-failed",
+ revision: viewerAuth.routeRevision,
+ phase: "active",
+ connectionId: "quality_takeover_connection",
+ }),
+ );
+ viewer.socket.send(
+ JSON.stringify({
+ type: "set-quality-settings",
+ qualitySettings: defaultQualitySettings,
+ }),
+ );
+ expect(await viewer.inbox.next("error")).toMatchObject({
+ code: "FORBIDDEN",
+ });
+ releaseTokens();
+
+ const prepare = await nextPreparedRoute(viewer);
+ expect(prepare.assignment.upstream).toEqual({ kind: "sfu" });
+ expect(await viewer.inbox.next("sfu-config")).toMatchObject({
+ revision: prepare.revision,
+ });
+ });
+
+ it("aborts a quality SFU prepare after next-generation C removes its intent", async () => {
+ let now = 300_000;
+ let releaseTokens!: () => void;
+ let holdTokens = true;
+ const tokenBarrier = new Promise<void>((resolve) => {
+ releaseTokens = resolve;
+ });
+ const harness = await startSfuHarness({
+ now: () => now,
+ tokenIssuer: {
+ async issueToken(request) {
+ if (holdTokens) {
+ await tokenBarrier;
+ }
+ return `token-${request.peerId}`;
+ },
+ },
+ });
+ const host = await openClient(harness.webSocketUrl);
+ const hostAuth = peerAssisted(
+ await authenticate(host, harness.room, "host", "quality-guard-host"),
+ );
+ const viewer = await openClient(harness.webSocketUrl);
+ const viewerAuth = peerAssisted(
+ await authenticate(
+ viewer,
+ harness.room,
+ "viewer",
+ "quality-guard-viewer",
+ ),
+ );
+ await nextActiveRouteRevision(host, viewerAuth.routeRevision);
+
+ host.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: viewerAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: "quality_guard_original",
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
+ );
+ await viewer.inbox.next("signal");
+ for (let sequence = 0; sequence < 3; sequence += 1) {
+ viewer.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ "quality_guard_original",
+ viewerAuth.routeRevision,
+ sequence,
+ { framesDecodedDelta: 0 },
+ ),
+ ),
+ );
+ await correlateParentEdgeQualityEvidence(host);
+ now += 2_000;
+ }
+
+ host.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: viewerAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: "quality_guard_replaced",
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
+ );
+ await viewer.inbox.next("signal");
+ viewer.socket.send(
+ JSON.stringify(
+ viewerQualityEvidence(
+ "quality_guard_replaced",
+ viewerAuth.routeRevision,
+ 0,
+ ),
+ ),
+ );
+ expect(await host.inbox.next("viewer-quality-evidence")).toMatchObject({
+ guard: { connectionId: "quality_guard_replaced" },
+ sequence: 0,
+ });
+ holdTokens = false;
+ releaseTokens();
+
+ const rollback = await nextActiveRouteAfter(
+ viewer,
+ viewerAuth.routeRevision,
+ );
+ expect(rollback.assignment).toMatchObject({
+ upstream: { kind: "peer", peerId: hostAuth.peerId },
+ sfuPublicationGeneration: null,
+ });
+ await expect(viewer.inbox.next("sfu-config", 40)).rejects.toThrow(
+ "Timed out",
+ );
+
+ viewer.socket.send(
+ JSON.stringify({
+ type: "route-failed",
+ revision: rollback.revision,
+ phase: "active",
+ connectionId: "quality_guard_replaced",
+ }),
+ );
+ const prepare = await nextPreparedRoute(viewer);
+ expect(prepare.assignment.upstream).toEqual({ kind: "sfu" });
+ expect(await viewer.inbox.next("sfu-config")).toMatchObject({
+ revision: prepare.revision,
+ });
+ });
+
it("rejects viewer C evidence above the byte cap", async () => {
const harness = await startHarness();
const viewer = await openClient(harness.webSocketUrl);
@@ -1741,6 +2604,33 @@ describe("WebSocket signaling", () => {
expect(await closed).toBe(1008);
});
+ it("rejects parent B evidence above the byte cap", async () => {
+ const harness = await startHarness();
+ const host = await openClient(harness.webSocketUrl);
+ await authenticate(host, harness.room, "host", "oversized-parent-host");
+ const closed = new Promise<number>((resolve) =>
+ host.socket.once("close", (code) => resolve(code)),
+ );
+ const valid = JSON.stringify({
+ type: "parent-edge-quality-evidence",
+ viewerPeerId: "oversized_parent_viewer",
+ guard: {
+ connectionId: "oversized_parent_connection",
+ routeRevision: 0,
+ },
+ viewerSequence: 0,
+ proof: { kind: "sending", packetsSentDelta: 1 },
+ });
+
+ host.socket.send(
+ `${valid}${" ".repeat(MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES + 1)}`,
+ );
+ expect(await host.inbox.next("error")).toMatchObject({
+ code: "INVALID_MESSAGE",
+ });
+ expect(await closed).toBe(1008);
+ });
+
it("routes offer and answer only between the host and the targeted viewer", async () => {
const harness = await startHarness();
const secondRoom = harness.roomStore.createRoom();
diff --git a/tests/viewer-quality-evidence.test.ts b/tests/viewer-quality-evidence.test.ts
index ad42da51..dd56ff85 100644
--- a/tests/viewer-quality-evidence.test.ts
+++ b/tests/viewer-quality-evidence.test.ts
@@ -7,6 +7,10 @@ import {
qualityEvidenceWindowFromMetrics,
ViewerQualityEvidenceReporter,
} from "../src/client/media/viewer-quality-evidence.ts";
+import {
+ ParentEdgeQualityEvidenceReporter,
+ parentEdgeQualityEvidenceFromSnapshot,
+} from "../src/client/media/parent-edge-quality-evidence.ts";
import {
EMPTY_METRICS,
type ConnectionMetrics,
@@ -244,4 +248,97 @@ describe("viewer quality evidence", () => {
codec: "video/H264",
});
});
+
+ it("builds parent proof only from a current connected send interval", () => {
+ const evidence = {
+ type: "viewer-quality-evidence",
+ viewerPeerId: "viewer_12345678",
+ parentPeerId: "host_12345678",
+ guard: {
+ connectionId: "connection_12345678",
+ routeRevision: 4,
+ },
+ sequence: 7,
+ ...qualityEvidenceWindowFromMetrics(receiveMetrics())!,
+ } as Extract<ServerMessage, { type: "viewer-quality-evidence" }>;
+ const current = {
+ ...snapshot(
+ evidence.guard.connectionId,
+ receiveMetrics({
+ sampleWindowMs: 2_000.25,
+ intervalPacketsSent: 1_200,
+ intervalPacketsLost: 12,
+ }),
+ ),
+ peerId: evidence.viewerPeerId,
+ };
+ const reporter = new ParentEdgeQualityEvidenceReporter();
+
+ expect(reporter.offer(evidence, current)).toEqual({
+ type: "parent-edge-quality-evidence",
+ viewerPeerId: evidence.viewerPeerId,
+ guard: evidence.guard,
+ viewerSequence: evidence.sequence,
+ proof: {
+ kind: "sending",
+ packetsSentDelta: 1_200,
+ },
+ });
+ expect(
+ reporter.offer({ ...evidence, sequence: evidence.sequence + 1 }, current),
+ ).toBeNull();
+ expect(
+ reporter.offer(
+ { ...evidence, sequence: evidence.sequence + 1 },
+ {
+ ...current,
+ metrics: {
+ ...current.metrics,
+ sampleTimestampMs: current.metrics.sampleTimestampMs! + 0.25,
+ },
+ },
+ ),
+ ).toMatchObject({ viewerSequence: evidence.sequence + 1 });
+ expect(
+ parentEdgeQualityEvidenceFromSnapshot(evidence, {
+ ...current,
+ metrics: {
+ ...current.metrics,
+ intervalPacketsSent: 100,
+ intervalPacketsLost: 30,
+ },
+ }),
+ ).toMatchObject({
+ proof: {
+ kind: "remote-loss",
+ packetsSentDelta: 100,
+ remotePacketsLostDelta: 30,
+ },
+ });
+ for (const reason of ["cpu", "bandwidth"] as const) {
+ expect(
+ parentEdgeQualityEvidenceFromSnapshot(evidence, {
+ ...current,
+ metrics: {
+ ...current.metrics,
+ qualityLimitationReason: reason,
+ },
+ }),
+ ).toMatchObject({
+ proof: { kind: "sender-limited", packetsSentDelta: 1_200, reason },
+ });
+ }
+ expect(
+ parentEdgeQualityEvidenceFromSnapshot(evidence, {
+ ...current,
+ connectionId: "connection_replaced_12345678",
+ }),
+ ).toBeNull();
+ expect(
+ parentEdgeQualityEvidenceFromSnapshot(evidence, {
+ ...current,
+ metrics: { ...current.metrics, intervalPacketsSent: null },
+ }),
+ ).toBeNull();
+ });
});