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(media): compare relay FPS with parent input

AAAe24719db3beb
diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.md
index d2e076aa..1c2c6e8d 100644
--- a/docs/adr/0005-automatic-hybrid-media-routing.md
+++ b/docs/adr/0005-automatic-hybrid-media-routing.md
@@ -168,8 +168,13 @@ 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
+only when B independently reports one of the two hard sender predicates and C
+is either severe or relatively degraded. Severe remains freeze, zero decode,
+or high loss. Relative degradation applies only below a Viewer relay parent:
+the parent's own most recent C must already be correlated, current for its
+session, route and connection, no older than five seconds, and the child's FPS
+must be below two-thirds of that actual inbound FPS. It never compares C with
+the room's configured FPS ceiling. 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,
@@ -377,19 +382,23 @@ The first controller reacts only to discrete events:
- 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%.
+ which B reports `cpu`/`bandwidth` sender limitation or at least 100 sent
+ packets with RTCP-reported remote loss divided by sent packets at least 30%,
+ and C either has the existing severe freeze/zero-decode/high-loss predicate
+ or, below a Viewer relay parent, receives less than two-thirds of that
+ parent's fresh correlated inbound FPS.
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,
+alone is diagnostic-only. C may be stored before B arrives, but only one
+unchanged severe or relative pair advances its own 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
+an evidence gap over five seconds. Severe evidence retains the existing bounded
+peer/SFU/TURN ladder. Relative-FPS evidence tries only another peer; if none is
+eligible, the old active edge stays and no route, SFU, TURN, or room cooldown is
+created. A successful peer reassignment or started severe 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,
@@ -397,13 +406,16 @@ 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
+intent as the ordinary failure owner. A successful relative-FPS move holds its
+old parent for 30 seconds, or until that parent session changes, to avoid a soft
+bounce. A real `route-failed` is stronger evidence: it releases that soft hold,
+hard-excludes the current failed parent and may immediately reuse the old
+playable parent. Other successful quality moves release their temporary
+exclusion. 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
+prescribe Screener's route policy. Therefore 50%, two-thirds FPS, 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
diff --git a/docs/project-memory.md b/docs/project-memory.md
index 186c8b41..438f3b3d 100644
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@ -1,6 +1,6 @@
# Project Memory
-Last updated: 2026-08-21
+Last updated: 2026-08-22
## Confirmed Intent
@@ -28,7 +28,7 @@ Last updated: 2026-08-21
- Mobile endpoints are Web Viewer-only. Current Android/iOS browsers do not expose Web Host capture; AirPlay/system mirroring is Viewer-local output.
- ADR-0005: direct/peer UDP -> bounded SFU roots -> selected-edge TURN. The deployed controller caps pending/answered `peer-selected` at one per room; Host ingress is independent. A pre-`ecc794d` exact-source/production-media canary proves active Host ingress only. Ordinary peers stay STUN-only.
- `PEER_ASSISTED_MEDIA=true` enables isolated all-room controllers; room `1` is historical. Keep sticky P2P and one recovery attempt per layer. Deployed healthy-SFU MBB covers one root and retained parent after reauth/recovery, gated by media proof, Host2/browser1 overlap and cooldown. It excludes `peer-selected`; active-SFU loss aborts into normal recovery. Capacity `0 -> 1`, multi-root and browser gates remain open.
-- C+B quality reparenting is edge-local and cooldown-bound; no score, timer, or global parent penalty.
+- C+B reparenting stays edge-local: severe uses fallback; relative relay FPS uses fresh parent evidence and peers only. No scoring or global 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.
- Screen audio: Web capture requests speech processing off and ideal stereo; peer answers use `stereo=1;maxaveragebitrate=128000`; SFU uses 128 kbps stereo/`forceStereo`, DTX off, RED retained. Proof open; no audio UI; voice and Native stay separate.
@@ -43,7 +43,7 @@ Last updated: 2026-08-21
## Current Implementation
- The repository is one npm package using Node.js 24, React, TypeScript, Vite, native WebRTC, `ws`, Zod, Vitest, and separate coturn.
-- Production: exact `4ee2f27f3f3e0882ae6f9d970fef1cf3b6fb1f7b`, release `4ee2f27f3f3e`, Web wire `screener-v4`; rollback `3d75e7b88635`.
+- Production: exact `25b725fdfcccc181a22ef020d77f5668470ba636`, release `25b725fdfccc`, Web wire `screener-v4`.
- Web keeps one SFU stream, clears unavailable video, exposes evidence-backed routes/transports and paused preview, and drops signals to a grace-retained offline current-edge target. Routing is automatic; entry/nickname UI is live; Native remains source-only.
- Web relay is cap2 with one upstream; child3 rejects and no UA/visibility split exists.
- Deployed relay evidence reaches opted-in Host rosters; direct proof stays local-edge-only.
diff --git a/docs/research/advanced-peer-distribution.md b/docs/research/advanced-peer-distribution.md
index 36bfa09f..1654c73b 100644
--- a/docs/research/advanced-peer-distribution.md
+++ b/docs/research/advanced-peer-distribution.md
@@ -193,10 +193,13 @@ 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.
+may retain C while awaiting B, but advances only when B is hard and C is either
+severe or relatively degraded. The relative case exists only below a Viewer
+relay: the relay's own latest correlated C must still match its session, active
+route and connection and be at most five seconds old; the child must receive
+less than two-thirds of that actual inbound FPS. The configured FPS ceiling is
+not evidence. `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.
@@ -205,21 +208,25 @@ 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
+at least 30%. Three consecutive windows of the same severe or relative kind 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. Severe evidence retains the existing fallback ladder. Relative FPS
+tries another peer only; no candidate keeps the old edge without SFU, TURN, an
+error, or room cooldown. A successful peer move or started severe 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
+An SFU preparation created by severe 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.
+that same intent without losing its exclusion. A successful relative move holds
+the old parent for 30 seconds or until its session changes. A real active-route
+failure overrides that soft hold, hard-excludes the current failed parent, and
+allows the old playable peer to take over immediately.
W3C defines outbound `packetsSent` as the local cumulative RTP packet count.
`remote-inbound-rtp.packetsLost` is remote receiver data delivered by RTCP and
@@ -233,7 +240,8 @@ 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
+freeze share, two-thirds FPS ratio, 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.
@@ -244,8 +252,9 @@ bad: the remote-loss value is that child's RTCP report and
server implementation deliberately reduces published-track and subscribed-
downtrack quality to a participant-wide minimum; that aggregate is useful for
conferencing UI but is not a directional P2P parent score. Screener consequently
-excludes only the failed parent for the affected Viewer-rooted subtree and
-releases the quality-owned exclusion after a successful move.
+excludes only the affected edge parent. Alternate-parent selection remains
+deterministic breadth-first; preferring recent healthy candidates over unknown
+candidates is a later make-before-break slice, not a score in this correction.
With host and current browser-relay degree two, deterministic breadth-first
assignment keeps eight viewers to depth three. A tree for `N` viewers
diff --git a/docs/status.md b/docs/status.md
index c70ea3c1..9f2277e4 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -1,10 +1,10 @@
# Current Status
-Last updated: 2026-08-21
+Last updated: 2026-08-22
## Phase
-Production is exact `4ee2f27f3f3e0882ae6f9d970fef1cf3b6fb1f7b` at `https://share.bonfire.icu`, release `4ee2f27f3f3e`, wire `screener-v4`; rollback is release `3d75e7b88635`. SQLite v3/five rooms keeps SHA-256 `aef724ae52c4107be8ec8791e72f8dcaa11b0ec849fb432d022e2cfb9cfe0974`, owner/mode `screener:screener`/0600. Four services and local/public health are green.
+Production is exact `25b725fdfcccc181a22ef020d77f5668470ba636` at `https://share.bonfire.icu`, release `25b725fdfccc`, wire `screener-v4`. SQLite v3/five rooms keeps SHA-256 `aef724ae52c4107be8ec8791e72f8dcaa11b0ec849fb432d022e2cfb9cfe0974`, owner/mode `screener:screener`/0600. Four services and local/public health are green.
Ordinary ICE is STUN-only; limits are SFU roots <=2, one `peer-selected` attempt excluding Host ingress, and selected UDP TTL 120. No browser/media/SFU/TURN/performance canary ran; exact-`16f6eab` Host-ingress proof is separate.
Stable SFU, route/transport truth, preview notice, entry/nickname UI and Web relay cap2 are live. Native is source-only. The controlled production A/B uses browser/LiveKit codec defaults; explicit codec controls are source-complete.
@@ -20,7 +20,7 @@ Parallel flagship work; use minimum relevant checks and rollback proof. Target-d
- Native v4 is source-only (memory rooms, 300s reclaim); it does not subscribe to Web presence, follows authenticated direct-child assignments up to two, and fails unsupported SFU/selected ingress boundedly.
- Production is roots/Web relay <=2; every Viewer has one upstream and rejects child3. One-root healthy-SFU MBB is deployed but media-unverified; capacity `0 -> 1`, multi-root and browser gates remain open. Room `1` is historical; HTTPS/WSS is TLS/TCP.
- After an answer, a generation-bound 15s initial-connect deadline enters ICE restart; success/replacement/disposal cancels it. It is deployed but not mobile-verified.
-- Room `1` C+B reparenting remains uncalibrated. Deployed admission rescue promotes an unassigned relay over the oldest childless zero-capacity Host leaf, with no scores or periodic optimization.
+- C+B reparenting remains uncalibrated. Source compares relay-child FPS with fresh parent input and tries peers only; no candidate keeps the old edge. This correction is not deployed. Admission rescue stays deterministic.
## Verified Evidence
diff --git a/src/server/hybrid-media-router.ts b/src/server/hybrid-media-router.ts
index 23195668..9be96162 100644
--- a/src/server/hybrid-media-router.ts
+++ b/src/server/hybrid-media-router.ts
@@ -33,6 +33,7 @@ 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_RELAY_FPS_RATIO = 2 / 3;
const VIEWER_QUALITY_MIN_LOSS_PACKETS = 100;
const VIEWER_QUALITY_HIGH_LOSS_RATIO = 0.3;
interface PendingRoutePreparation {
@@ -104,6 +105,7 @@ interface HealthySfuReselectionProbe {
}
interface QualityRouteIntentGuard {
+ kind: ViewerQualityBadWindowKind;
viewerSessionId: string;
connectionId: string;
routeRevision: number;
@@ -112,6 +114,8 @@ interface QualityRouteIntentGuard {
exclusionOwnedByQuality: boolean;
}
+type ViewerQualityBadWindowKind = "severe" | "relative-fps";
+
interface ViewerQualityEvidenceState {
viewerSessionId: string;
parentPeerId: string;
@@ -120,6 +124,11 @@ interface ViewerQualityEvidenceState {
routeRevision: number;
lastCorrelatedAtMs: number | null;
badWindowCount: number;
+ badWindowKind: ViewerQualityBadWindowKind | null;
+ lastCorrelatedFps: {
+ correlatedAtMs: number;
+ framesPerSecond: number | null;
+ } | null;
pendingViewerEvidence: {
acceptedAtMs: number;
evidence: Extract<ServerMessage, { type: "viewer-quality-evidence" }>;
@@ -227,6 +236,10 @@ export class HybridMediaRouter {
string,
ViewerQualityEvidenceState
>();
+ private readonly heldQualityParentExclusionsByViewer = new Map<
+ string,
+ { parentPeerId: string; parentSessionId: string; expiresAtMs: number }
+ >();
private readonly roomQualityMigrationCooldownUntilMs = new Map<
string,
number
@@ -274,11 +287,13 @@ export class HybridMediaRouter {
this.relayCapacitySessionsByRoom.clear();
this.sfuDisabledRoomIds.clear();
this.viewerQualityEvidenceStates.clear();
+ this.heldQualityParentExclusionsByViewer.clear();
this.roomQualityMigrationCooldownUntilMs.clear();
}
connectParticipant(input: AuthenticatedRouteParticipant): HybridAuthenticationState {
this.clearRoomViewerQualityEvidenceStates(input.roomId);
+ this.clearHeldQualityParentExclusion(input.roomId, input.peerId);
this.clearSfuRefreshesForPeer(input.roomId, input.peerId);
if (input.role === "viewer") {
const connectionKey = viewerConnectionKey(input.roomId, input.peerId);
@@ -552,6 +567,10 @@ export class HybridMediaRouter {
? previous.lastCorrelatedAtMs
: null,
badWindowCount: canContinueStreak ? previous.badWindowCount : 0,
+ badWindowKind: canContinueStreak ? previous.badWindowKind : null,
+ lastCorrelatedFps: sameIdentity
+ ? previous?.lastCorrelatedFps ?? null
+ : null,
pendingViewerEvidence: { acceptedAtMs: now, evidence },
});
}
@@ -603,12 +622,18 @@ export class HybridMediaRouter {
now - pending.acceptedAtMs > VIEWER_QUALITY_EVIDENCE_GAP_MS
) {
state.badWindowCount = 0;
+ state.badWindowKind = null;
state.lastCorrelatedAtMs = null;
return;
}
+ state.lastCorrelatedFps = {
+ correlatedAtMs: now,
+ framesPerSecond: pending.evidence.metrics.framesPerSecond,
+ };
const cooldownUntil = this.roomQualityMigrationCooldownUntilMs.get(roomId);
if (cooldownUntil !== undefined && now < cooldownUntil) {
state.badWindowCount = 0;
+ state.badWindowKind = null;
state.lastCorrelatedAtMs = now;
return;
}
@@ -618,22 +643,37 @@ export class HybridMediaRouter {
const existingIntent = this.viewerRouteIntentsByRoom
.get(roomId)
?.get(viewerPeerId);
+ this.pruneHeldQualityParentExclusion(roomId, viewerPeerId, now);
const failedParents = this.failedParentPeerIdsByViewer.get(connectionKey);
if (existingIntent || failedParents?.has(edge.parentPeerId)) {
state.badWindowCount = 0;
+ state.badWindowKind = null;
state.lastCorrelatedAtMs = now;
return;
}
- const hardBad =
- isHardBadViewerQualityWindow(pending.evidence) &&
- isHardBadParentEdgeQualityProof(evidence.proof);
- state.badWindowCount = hardBad
- ? state.lastCorrelatedAtMs !== null &&
+ const hardParentProof = isHardBadParentEdgeQualityProof(evidence.proof);
+ const badWindowKind = !hardParentProof
+ ? null
+ : isHardBadViewerQualityWindow(pending.evidence)
+ ? "severe"
+ : this.isHardBadRelativeRelayFpsWindow(
+ roomId,
+ edge.parentPeerId,
+ parentSessionId,
+ pending.evidence,
+ now,
+ )
+ ? "relative-fps"
+ : null;
+ state.badWindowCount = badWindowKind
+ ? state.badWindowKind === badWindowKind &&
+ state.lastCorrelatedAtMs !== null &&
now - state.lastCorrelatedAtMs <= VIEWER_QUALITY_EVIDENCE_GAP_MS
? state.badWindowCount + 1
: 1
: 0;
+ state.badWindowKind = badWindowKind;
state.lastCorrelatedAtMs = now;
if (state.badWindowCount < VIEWER_QUALITY_BAD_WINDOWS_TO_REASSIGN) {
return;
@@ -656,6 +696,7 @@ export class HybridMediaRouter {
sfuAttempts: 0,
unavailableReported: false,
qualityGuard: {
+ kind: badWindowKind!,
viewerSessionId,
connectionId: evidence.guard.connectionId,
routeRevision: evidence.guard.routeRevision,
@@ -668,6 +709,46 @@ export class HybridMediaRouter {
this.drainViewerRouteIntents(roomId);
}
+ private isHardBadRelativeRelayFpsWindow(
+ roomId: string,
+ parentPeerId: string,
+ parentSessionId: string,
+ childEvidence: Extract<
+ ServerMessage,
+ { type: "viewer-quality-evidence" }
+ >,
+ now: number,
+ ): boolean {
+ const parentState = this.viewerQualityEvidenceStates.get(
+ viewerConnectionKey(roomId, parentPeerId),
+ );
+ const correlated = parentState?.lastCorrelatedFps;
+ const parentEdge = this.resolveActivePeerEdge(roomId, parentPeerId);
+ if (
+ this.options.roomStore.getConnectedViewer(roomId, parentPeerId)
+ ?.sessionId !== parentSessionId ||
+ !parentState ||
+ !correlated ||
+ parentState.viewerSessionId !== parentSessionId ||
+ parentEdge?.parentPeerId !== parentState.parentPeerId ||
+ parentEdge.revision !== parentState.routeRevision ||
+ this.options.getConnectionId(roomId, parentPeerId) !==
+ parentState.connectionId ||
+ now < correlated.correlatedAtMs ||
+ now - correlated.correlatedAtMs > VIEWER_QUALITY_EVIDENCE_GAP_MS
+ ) {
+ return false;
+ }
+ const childFps = childEvidence.metrics.framesPerSecond;
+ const parentInboundFps = correlated.framesPerSecond;
+ return (
+ childFps !== null &&
+ parentInboundFps !== null &&
+ parentInboundFps > 0 &&
+ childFps < parentInboundFps * VIEWER_QUALITY_RELAY_FPS_RATIO
+ );
+ }
+
setViewerRelayCapacity(
participant: AuthenticatedRouteParticipant,
downstreamEdges: RelayDownstreamEdges,
@@ -1128,13 +1209,34 @@ export class HybridMediaRouter {
) {
return;
}
+ const now = this.options.now?.() ?? Date.now();
+ this.pruneHeldQualityParentExclusion(
+ participant.roomId,
+ participant.peerId,
+ now,
+ );
+ const heldQualityParent =
+ this.heldQualityParentExclusionsByViewer.get(connectionKey);
+ const heldQualityFailure =
+ heldQualityParent?.parentPeerId === assignment.upstream.peerId;
+ if (heldQualityFailure) {
+ this.heldQualityParentExclusionsByViewer.delete(connectionKey);
+ } else if (heldQualityParent) {
+ this.clearHeldQualityParentExclusion(
+ participant.roomId,
+ participant.peerId,
+ );
+ }
let failedParents = this.failedParentPeerIdsByViewer.get(connectionKey);
if (!failedParents) {
failedParents = new Set();
this.failedParentPeerIdsByViewer.set(connectionKey, failedParents);
}
- if (failedParents.has(assignment.upstream.peerId)) {
+ if (
+ failedParents.has(assignment.upstream.peerId) &&
+ !heldQualityFailure
+ ) {
const existingIntent = this.viewerRouteIntentsByRoom
.get(participant.roomId)
?.get(participant.peerId);
@@ -1796,6 +1898,11 @@ export class HybridMediaRouter {
roomId,
viewerPeerId,
);
+ this.pruneHeldQualityParentExclusion(
+ roomId,
+ viewerPeerId,
+ this.options.now?.() ?? Date.now(),
+ );
const controller = this.mediaRouteControllers.get(roomId);
const assignment = controller
?.getActiveRoute()
@@ -1899,12 +2006,26 @@ export class HybridMediaRouter {
if (changes) {
if (intent.qualityGuard) {
this.startRoomQualityMigrationCooldown(roomId);
- this.releaseQualityOwnedParentExclusion(
- roomId,
- viewerPeerId,
- intent,
- intent.qualityGuard,
- );
+ if (intent.qualityGuard.kind === "relative-fps") {
+ this.heldQualityParentExclusionsByViewer.set(
+ viewerConnectionKey(roomId, viewerPeerId),
+ {
+ parentPeerId: intent.qualityGuard.parentPeerId,
+ parentSessionId: intent.qualityGuard.parentSessionId,
+ expiresAtMs:
+ (this.options.now?.() ?? Date.now()) +
+ VIEWER_QUALITY_REASSIGN_COOLDOWN_MS,
+ },
+ );
+ intent.qualityGuard.exclusionOwnedByQuality = false;
+ } else {
+ this.releaseQualityOwnedParentExclusion(
+ roomId,
+ viewerPeerId,
+ intent,
+ intent.qualityGuard,
+ );
+ }
}
intents.delete(viewerPeerId);
this.clearChangedConnectionIds(roomId, changes);
@@ -1914,6 +2035,11 @@ export class HybridMediaRouter {
}
}
+ if (intent.qualityGuard?.kind === "relative-fps") {
+ this.discardQualityIntent(roomId, viewerPeerId, intent);
+ continue;
+ }
+
if (
intent.sfuAttempts === 0 &&
this.options.sfuFallback &&
@@ -2038,6 +2164,44 @@ export class HybridMediaRouter {
}
}
+ private pruneHeldQualityParentExclusion(
+ roomId: string,
+ viewerPeerId: string,
+ now: number,
+ ): void {
+ if (!Number.isFinite(now)) {
+ return;
+ }
+ const connectionKey = viewerConnectionKey(roomId, viewerPeerId);
+ const held = this.heldQualityParentExclusionsByViewer.get(connectionKey);
+ if (
+ !held ||
+ (now < held.expiresAtMs &&
+ this.connectedPeer(roomId, held.parentPeerId)?.sessionId ===
+ held.parentSessionId)
+ ) {
+ return;
+ }
+ this.clearHeldQualityParentExclusion(roomId, viewerPeerId);
+ }
+
+ private clearHeldQualityParentExclusion(
+ roomId: string,
+ viewerPeerId: string,
+ ): void {
+ const connectionKey = viewerConnectionKey(roomId, viewerPeerId);
+ const held = this.heldQualityParentExclusionsByViewer.get(connectionKey);
+ if (!held) {
+ return;
+ }
+ this.heldQualityParentExclusionsByViewer.delete(connectionKey);
+ const failedParents = this.failedParentPeerIdsByViewer.get(connectionKey);
+ failedParents?.delete(held.parentPeerId);
+ if (failedParents?.size === 0) {
+ this.failedParentPeerIdsByViewer.delete(connectionKey);
+ }
+ }
+
private prepareSfuFallback(
roomId: string,
failedPeerId: string,
@@ -2857,6 +3021,11 @@ export class HybridMediaRouter {
this.failedParentPeerIdsByViewer.delete(key);
}
}
+ for (const key of this.heldQualityParentExclusionsByViewer.keys()) {
+ if (key.startsWith(prefix)) {
+ this.heldQualityParentExclusionsByViewer.delete(key);
+ }
+ }
}
private clearRoomMediaRouteState(roomId: string): void {
@@ -2940,6 +3109,7 @@ export class HybridMediaRouter {
roomId: string,
peerId: string,
): void {
+ this.clearHeldQualityParentExclusion(roomId, peerId);
const intents = this.viewerRouteIntentsByRoom.get(roomId);
for (const [viewerPeerId, intent] of [...(intents ?? [])]) {
if (
@@ -3016,6 +3186,7 @@ function sameQualityRouteIntentGuard(
right: QualityRouteIntentGuard,
): boolean {
return (
+ left.kind === right.kind &&
left.viewerSessionId === right.viewerSessionId &&
left.connectionId === right.connectionId &&
left.routeRevision === right.routeRevision &&
diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.ts
index 7881e09f..2eb095e1 100644
--- a/tests/server-signal.test.ts
+++ b/tests/server-signal.test.ts
@@ -282,6 +282,161 @@ async function correlateParentEdgeQualityEvidence(
return viewerEvidence;
}
+async function startRelayRelativeFpsFixture(
+ prefix: string,
+ now: () => number,
+ options: {
+ alternateRelayCapacity?: 0 | 1;
+ onSfuTokenIssue?: () => void;
+ sfu?: boolean;
+ } = {},
+) {
+ const harness = options.sfu
+ ? await startSfuHarness({
+ now,
+ tokenIssuer: {
+ issueToken: async ({ peerId }) => {
+ options.onSfuTokenIssue?.();
+ return `token-${peerId}`;
+ },
+ },
+ })
+ : await startHarness({ peerAssistedMedia: true, now });
+ const host = await openClient(harness.webSocketUrl);
+ const hostAuth = peerAssisted(
+ await authenticate(host, harness.room, "host", `${prefix}-host`),
+ );
+ const parent = await openClient(harness.webSocketUrl);
+ const parentAuth = peerAssisted(
+ await authenticate(parent, harness.room, "viewer", `${prefix}-parent`, 1),
+ );
+ const alternate = await openClient(harness.webSocketUrl);
+ const alternateAuth = peerAssisted(
+ await authenticate(
+ alternate,
+ harness.room,
+ "viewer",
+ `${prefix}-alternate`,
+ options.alternateRelayCapacity ?? 1,
+ ),
+ );
+ const child = await openClient(harness.webSocketUrl);
+ const childAuth = peerAssisted(
+ await authenticate(child, harness.room, "viewer", `${prefix}-child`, 0),
+ );
+ expect(parentAuth.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: hostAuth.peerId,
+ });
+ expect(alternateAuth.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: hostAuth.peerId,
+ });
+ expect(childAuth.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: parentAuth.peerId,
+ });
+
+ const parentConnectionId = `${prefix}_parent_connection`;
+ host.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: parentAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: parentConnectionId,
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
+ );
+ await parent.inbox.next("signal");
+
+ const childConnectionId = `${prefix}_child_connection`;
+ parent.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: childAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: childConnectionId,
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
+ );
+ await child.inbox.next("signal");
+
+ return {
+ alternate,
+ alternateAuth,
+ child,
+ childAuth,
+ childConnectionId,
+ harness,
+ host,
+ hostAuth,
+ parent,
+ parentAuth,
+ parentConnectionId,
+ routeRevision: childAuth.routeRevision,
+ };
+}
+
+async function correlateRelayParentInboundFps(
+ fixture: Awaited<ReturnType<typeof startRelayRelativeFpsFixture>>,
+ framesPerSecond: number,
+) {
+ fixture.parent.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ fixture.parentConnectionId,
+ fixture.routeRevision,
+ 0,
+ { framesPerSecond },
+ ),
+ ),
+ );
+ while (true) {
+ const evidence = await fixture.host.inbox.next("viewer-quality-evidence");
+ if (evidence.viewerPeerId !== fixture.parentAuth.peerId) {
+ continue;
+ }
+ fixture.host.socket.send(
+ JSON.stringify({
+ type: "parent-edge-quality-evidence",
+ viewerPeerId: evidence.viewerPeerId,
+ guard: evidence.guard,
+ viewerSequence: evidence.sequence,
+ proof: { kind: "sending", packetsSentDelta: 1_500 },
+ }),
+ );
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ return;
+ }
+}
+
+async function correlateRelayChildFps(
+ fixture: Awaited<ReturnType<typeof startRelayRelativeFpsFixture>>,
+ sequence: number,
+ framesPerSecond: number,
+) {
+ fixture.child.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ fixture.childConnectionId,
+ fixture.routeRevision,
+ sequence,
+ { framesPerSecond },
+ ),
+ ),
+ );
+ await correlateParentEdgeQualityEvidence(fixture.parent, {
+ kind: "sender-limited",
+ packetsSentDelta: 1_500,
+ reason: "bandwidth",
+ });
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+}
+
async function startSfuHarness(options: {
tokenIssuer: SfuTokenIssuer;
selectedEdgeTurn?: boolean;
@@ -3005,6 +3160,354 @@ describe("WebSocket signaling", () => {
acceptedParentEvidence.mockRestore();
});
+ it("does not treat a 30 FPS relay child as bad against a 60 FPS setting", async () => {
+ let now = 90_000;
+ const fixture = await startRelayRelativeFpsFixture(
+ "relative_same_fps",
+ () => now,
+ );
+ await correlateRelayParentInboundFps(fixture, 30);
+ for (let sequence = 0; sequence < 3; sequence += 1) {
+ await correlateRelayChildFps(fixture, sequence, 30);
+ now += 2_000;
+ }
+ await expect(
+ fixture.child.inbox.next("route-update", 40),
+ ).rejects.toThrow("Timed out");
+ });
+
+ it("moves a relay child after three corroborated relative-FPS windows", async () => {
+ let now = 110_000;
+ const fixture = await startRelayRelativeFpsFixture(
+ "relative_peer_move",
+ () => now,
+ );
+ await correlateRelayParentInboundFps(fixture, 30);
+ for (let sequence = 0; sequence < 3; sequence += 1) {
+ await correlateRelayChildFps(fixture, sequence, 10);
+ now += 2_000;
+ }
+ const moved = await nextActiveRouteAfter(
+ fixture.child,
+ fixture.routeRevision,
+ );
+ expect(moved.assignment.upstream).toEqual({
+ kind: "peer",
+ peerId: fixture.alternateAuth.peerId,
+ });
+
+ const failedAlternateConnection = "relative_peer_move_failed_alternate";
+ fixture.alternate.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: fixture.childAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: failedAlternateConnection,
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
+ );
+ await fixture.child.inbox.next("signal");
+ fixture.child.socket.send(
+ JSON.stringify({
+ type: "route-failed",
+ revision: moved.revision,
+ phase: "active",
+ connectionId: failedAlternateConnection,
+ }),
+ );
+ const recovered = await nextActiveRouteAfter(fixture.child, moved.revision);
+ expect(recovered.assignment.upstream).toEqual({
+ kind: "peer",
+ peerId: fixture.parentAuth.peerId,
+ });
+ });
+
+ it("keeps the old relay edge when relative FPS has no alternate peer", async () => {
+ let now = 130_000;
+ let issuedSfuTokens = 0;
+ const fixture = await startRelayRelativeFpsFixture(
+ "relative_no_alternate",
+ () => now,
+ {
+ alternateRelayCapacity: 0,
+ onSfuTokenIssue: () => {
+ issuedSfuTokens += 1;
+ },
+ sfu: true,
+ },
+ );
+ await correlateRelayParentInboundFps(fixture, 30);
+ for (let sequence = 0; sequence < 3; sequence += 1) {
+ await correlateRelayChildFps(fixture, sequence, 10);
+ now += 2_000;
+ }
+ await expect(
+ fixture.child.inbox.next("route-update", 40),
+ ).rejects.toThrow("Timed out");
+ await expect(
+ fixture.child.inbox.next("sfu-config", 40),
+ ).rejects.toThrow("Timed out");
+ await expect(fixture.child.inbox.next("error", 40)).rejects.toThrow(
+ "Timed out",
+ );
+ expect(issuedSfuTokens).toBe(0);
+
+ const activeConnectionId = "relative_no_alternate_still_active";
+ fixture.parent.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: fixture.childAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: activeConnectionId,
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
+ );
+ expect(await fixture.child.inbox.next("signal")).toMatchObject({
+ fromPeerId: fixture.parentAuth.peerId,
+ });
+
+ for (let sequence = 0; sequence < 3; sequence += 1) {
+ fixture.child.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ activeConnectionId,
+ fixture.routeRevision,
+ sequence,
+ { framesDecodedDelta: 0 },
+ ),
+ ),
+ );
+ await correlateParentEdgeQualityEvidence(fixture.parent);
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ now += 2_000;
+ }
+ const prepare = await nextPreparedRoute(fixture.child);
+ expect(prepare.assignment.upstream).toEqual({ kind: "sfu" });
+ expect(await fixture.child.inbox.next("sfu-config")).toMatchObject({
+ revision: prepare.revision,
+ });
+ expect(issuedSfuTokens).toBeGreaterThan(0);
+ });
+
+ it("does not apply relative-FPS reparenting to a Host-direct edge", async () => {
+ let now = 150_000;
+ const harness = await startHarness({
+ peerAssistedMedia: true,
+ now: () => now,
+ });
+ const host = await openClient(harness.webSocketUrl);
+ const hostAuth = peerAssisted(
+ await authenticate(host, harness.room, "host", "relative_host_direct_host"),
+ );
+ const viewer = await openClient(harness.webSocketUrl);
+ const viewerAuth = peerAssisted(
+ await authenticate(
+ viewer,
+ harness.room,
+ "viewer",
+ "relative_host_direct_viewer",
+ 0,
+ ),
+ );
+ const alternate = await openClient(harness.webSocketUrl);
+ const alternateAuth = peerAssisted(
+ await authenticate(
+ alternate,
+ harness.room,
+ "viewer",
+ "relative_host_direct_alternate",
+ 1,
+ ),
+ );
+ await nextActiveRouteRevision(viewer, alternateAuth.routeRevision);
+ expect(viewerAuth.routeAssignment.upstream).toEqual({
+ kind: "peer",
+ peerId: hostAuth.peerId,
+ });
+ host.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: viewerAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: "relative_host_direct_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(
+ "relative_host_direct_connection",
+ alternateAuth.routeRevision,
+ sequence,
+ { framesPerSecond: 10 },
+ ),
+ ),
+ );
+ await correlateParentEdgeQualityEvidence(host);
+ now += 2_000;
+ }
+ await expect(viewer.inbox.next("route-update", 40)).rejects.toThrow(
+ "Timed out",
+ );
+ });
+
+ it("requires fresh correlated inbound FPS from the relay parent", async () => {
+ let now = 170_000;
+ const fixture = await startRelayRelativeFpsFixture(
+ "relative_parent_freshness",
+ () => now,
+ );
+ for (let sequence = 0; sequence < 3; sequence += 1) {
+ await correlateRelayChildFps(fixture, sequence, 10);
+ now += 2_000;
+ }
+ await expect(
+ fixture.child.inbox.next("route-update", 40),
+ ).rejects.toThrow("Timed out");
+
+ await correlateRelayParentInboundFps(fixture, 30);
+ now += 5_001;
+ for (let sequence = 3; sequence < 6; sequence += 1) {
+ await correlateRelayChildFps(fixture, sequence, 10);
+ now += 2_000;
+ }
+ await expect(
+ fixture.child.inbox.next("route-update", 40),
+ ).rejects.toThrow("Timed out");
+ });
+
+ it.each(["connection", "revision", "session"] as const)(
+ "rejects relative FPS after the relay parent's %s identity changes",
+ async (changedIdentity) => {
+ let now = 180_000;
+ const prefix = `relative_parent_${changedIdentity}`;
+ const fixture = await startRelayRelativeFpsFixture(prefix, () => now);
+ await correlateRelayParentInboundFps(fixture, 30);
+ let routeRevision = fixture.routeRevision;
+
+ if (changedIdentity === "connection") {
+ fixture.host.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: fixture.parentAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: `${prefix}_replacement_connection`,
+ description: { type: "offer", sdp: "v=0\r\n" },
+ },
+ }),
+ );
+ await fixture.parent.inbox.next("signal");
+ } else if (changedIdentity === "revision") {
+ const extra = await openClient(fixture.harness.webSocketUrl);
+ const extraAuth = peerAssisted(
+ await authenticate(
+ extra,
+ fixture.harness.room,
+ "viewer",
+ `${prefix}-extra`,
+ 0,
+ ),
+ );
+ routeRevision = extraAuth.routeRevision;
+ await nextActiveRouteRevision(fixture.child, routeRevision);
+ } else {
+ const replacement = await openClient(fixture.harness.webSocketUrl);
+ const replacementAuth = peerAssisted(
+ await authenticate(
+ replacement,
+ fixture.harness.room,
+ "viewer",
+ `${prefix}-parent`,
+ 1,
+ ),
+ );
+ expect(replacementAuth.peerId).toBe(fixture.parentAuth.peerId);
+ routeRevision = replacementAuth.routeRevision;
+ fixture.parent = replacement;
+ }
+
+ for (let sequence = 0; sequence < 3; sequence += 1) {
+ fixture.child.socket.send(
+ JSON.stringify(
+ viewerQualityEvidenceWithMetrics(
+ fixture.childConnectionId,
+ routeRevision,
+ sequence,
+ { framesPerSecond: 10 },
+ ),
+ ),
+ );
+ await correlateParentEdgeQualityEvidence(fixture.parent, {
+ kind: "sender-limited",
+ packetsSentDelta: 1_500,
+ reason: "bandwidth",
+ });
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ now += 2_000;
+ }
+ await expect(
+ fixture.child.inbox.next("route-update", 40),
+ ).rejects.toThrow("Timed out");
+ },
+ );
+
+ it("keeps severe zero-decode quality fallback eligible for SFU", async () => {
+ let now = 190_000;
+ const harness = await startSfuHarness({
+ now: () => now,
+ tokenIssuer: { issueToken: async ({ peerId }) => `token-${peerId}` },
+ });
+ const host = await openClient(harness.webSocketUrl);
+ const hostAuth = peerAssisted(
+ await authenticate(host, harness.room, "host", "severe_sfu_host"),
+ );
+ const viewer = await openClient(harness.webSocketUrl);
+ const viewerAuth = peerAssisted(
+ await authenticate(viewer, harness.room, "viewer", "severe_sfu_viewer", 0),
+ );
+ host.socket.send(
+ JSON.stringify({
+ type: "signal",
+ targetPeerId: viewerAuth.peerId,
+ payload: {
+ kind: "description",
+ connectionId: "severe_sfu_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(
+ "severe_sfu_connection",
+ viewerAuth.routeRevision,
+ sequence,
+ { framesDecodedDelta: 0 },
+ ),
+ ),
+ );
+ await correlateParentEdgeQualityEvidence(host);
+ now += 2_000;
+ }
+ const prepare = await nextPreparedRoute(viewer);
+ expect(prepare.assignment.upstream).toEqual({ kind: "sfu" });
+ expect(await viewer.inbox.next("sfu-config")).toMatchObject({
+ revision: prepare.revision,
+ });
+ expect(hostAuth.routeAssignment.upstream).toEqual({ kind: "none" });
+ });
+
it("reparents only a viewer subtree after three hard quality windows", async () => {
let now = 100_000;
const harness = await startHarness({