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(route): make route convergence measured and presentation-stable (#305)

AAA8f7fbe5bfe00
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 85ad25eb..b0394067 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -27,6 +27,12 @@ Direct commits to `main` are reserved for an explicit user-approved exception. N
For deployment work, a routine application-only release verifies a new immutable artifact, switches to it atomically, and guarantees the pre-cutover application release only through bounded health and postflight checks; it has no retention contract afterward and is not a maintained backup. Define recovery only for the infrastructure, configuration, secrets, persistent state, or irreversible surfaces the task actually touches, before changing them.
+Do not change `SIGNALING_PROTOCOL` for compatible internal, UI, routing, or
+release work. A wire change makes existing pages stale and forces an active
+Browser Host to reload, which ends its capture. Bump it only for an actually
+incompatible message contract whose atomic cutover and capture interruption are
+explicitly accepted.
+
Clean up worktrees and branches only after semantic review and integration are complete and the normal merged-head, open-reference, clean-tree, and non-following link checks pass. Never merge an old branch wholesale after a newer truth checkpoint.
## Research Standard
diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.md
index a7a2a1f2..f2de750f 100644
--- a/docs/adr/0005-automatic-hybrid-media-routing.md
+++ b/docs/adr/0005-automatic-hybrid-media-routing.md
@@ -195,11 +195,12 @@ first gets every Viewer usable media; quality work runs only while no join,
failure, pause, identity, departure, capacity, or SFU-resource work needs that
operation. With the gate disabled, quality evidence remains observation-only.
-Each exact current or pending edge has one native state: `unknown`, `healthy`, or
-`degraded`. For ordinary P2P, the parent reports the exact outbound sender's
-WebRTC `qualityLimitationReason` and cumulative durations. One complete
-same-identity delta in `none` is healthy; one in `bandwidth` or `cpu` is
-degraded; `other`, missing, reset, hidden, or stale evidence is unknown. SFU
+Each exact sender has one native observation: `unknown`, `clear`, or `limited`.
+The wire retains `healthy` and `degraded` as the internal categorical names, but
+they mean only one complete same-identity `qualityLimitationReason` delta in
+`none`, or one in `bandwidth`/`cpu`. This observation can trigger one bounded
+experiment; it does not locate the physical bottleneck or prove end-to-end
+quality. `other`, missing, reset, hidden, or stale evidence is unknown. SFU
publication and subscription state remains owned by LiveKit plus the exact
Viewer's continuing decoded progress. Screener does not combine loss, RTT,
jitter, bitrate, FPS, resolution, or freezes into a weighted route score.
@@ -209,17 +210,20 @@ same sender identity. Healthy, unknown, stale, reset, source change, or identity
change clears that run. This is the same persistence semantic used by the Host
quality warning; a single native limitation interval remains diagnostic.
-When the current source path remains persistently degraded, the controller
+When the current sender remains persistently limited, the controller
considers the shallowest affected child first and uses the existing
deterministic candidate filters, ordering, cursor, reservations, and total
-deadline. Candidate Peer parents must have a healthy source path and available
-steady capacity. Only one candidate runs at a time; the old route keeps playing.
-First decoded frame proves candidate usability, and a complete healthy native
-edge delta proves the new path has escaped the old limitation. If the old edge
-recovers, the candidate is degraded or unknown, authority changes, or the
-deadline expires, the candidate is aborted and the graph stays unchanged. A
-successful commit clears and rebaselines quality state for that edge and its
-affected subtree.
+deadline. Candidate Peer parents need a usable source path and available steady
+capacity; clear native paths are tried before the remaining deterministic Peer
+candidates but are not a hard eligibility tier. Only one candidate runs at a
+time and the old route keeps playing. The same Viewer compares fresh old and
+candidate receive windows. A P2P candidate commits only after first decoded
+frame and three consecutive windows with no freeze/pause, no lower pixel area or
+rounded FPS, and a strict improvement in at least one of those dimensions.
+Bitrate does not rank P2P candidates because codec and content phase make it
+non-monotonic. Old-edge recovery, missing/incomparable evidence, authority
+change, or deadline aborts the experiment. A successful commit clears and
+rebaselines the affected subtree.
The same rule supplies both active parent change and relay abdication. A bad
relay ingress reparents that relay while retaining its subtree. A bad exact
@@ -229,7 +233,7 @@ again; relief can cancel the remaining work without a parent score or explicit
capacity penalty.
The Host capture/source is a separate fact. A stalled source cannot be repaired
-by topology. One degraded Host-origin edge may move only to a healthy Peer. SFU
+by topology. One limited Host-origin edge may try the same measured Peer move. SFU
becomes a quality suffix only when every current Host-origin Peer edge, with a
minimum of two, independently remains persistently degraded. This bounded
condition identifies possible Host fanout pressure without making SFU an
diff --git a/docs/product/presentation-lifecycle.md b/docs/product/presentation-lifecycle.md
index 0c19e1ab..c808e3c0 100644
--- a/docs/product/presentation-lifecycle.md
+++ b/docs/product/presentation-lifecycle.md
@@ -37,6 +37,14 @@ binding, frame proof, autoplay, and terminal failure are typed facts interpreted
by one presentation reducer. Older route or media generations cannot overwrite
the current result, and raw server errors are never rendered directly.
+The room route revision orders control messages; it is not a Viewer media
+identity. A Viewer frame belongs to its local media generation and remains
+current across unrelated graph revisions until that exact binding is replaced,
+invalidated, or terminally failed. Pending candidates never own the primary
+badge, status line, or overlay while committed media remains proved. Those
+surfaces share the presentation reducer; raw transport snapshots provide route
+labels, reconnect authority, and diagnostics only.
+
Excluding time spent in the Browser's capture/play authorization UI, a Viewer
request targets a first visible frame within three seconds. Until then, the page
must continuously show a truthful accessible connection stage rather than a
@@ -73,6 +81,9 @@ when disambiguation is needed.
Connection details are progressive and use one card shape for P2P, peer relay,
and SFU Viewers. Summary fields prioritize actual resolution, FPS, bitrate, and
loss; deeper fields appear only when meaningful. Topology is a separate view.
+Native bandwidth or CPU limitation warnings describe the exact outbound sender
+that reported adaptation; they do not by themselves locate the physical
+bottleneck or describe the Viewer's receive path.
Locally exposed selected-candidate addresses may be shown only on the Browser
that owns that PeerConnection and are never uploaded, persisted, or used for
identity or route selection. The product does not offer a diagnostic-download
diff --git a/docs/product/routing-transport.md b/docs/product/routing-transport.md
index 90d5a8a1..2acf1aa2 100644
--- a/docs/product/routing-transport.md
+++ b/docs/product/routing-transport.md
@@ -102,9 +102,12 @@ credentials cannot recreate off-ledger media. ADR-0005 owns that lifecycle.
WebRTC and LiveKit own ICE, consent, congestion control, bitrate, frame rate,
resolution, retransmission, reconnect, and SFU layer selection. When the
-per-share convergence gate is enabled, Screener uses their exact categorical
-edge state only to move one persistently degraded local edge through the
-existing serial operation. Ordinary quality moves remain Peer-to-Peer. SFU may
+per-share convergence gate is enabled, Screener uses an exact persistent native
+sender limitation only to trigger one measured experiment through the existing
+serial operation. The same Viewer must then prove a P2P candidate strictly
+improves delivered pixel area or rounded FPS without regressing either dimension
+or producing a freeze/pause across three fresh paired windows. Ordinary quality
+moves remain Peer-to-Peer. SFU may
join quality work only as Host fanout relief when every current Host-origin Peer
edge, with at least two such edges, is persistently degraded; one Viewer moves
before the controller observes the new topology again. During that overlap, the
diff --git a/src/client/media/sfu-quality-probe.ts b/src/client/media/candidate-quality-probe.ts
similarity index 60%
rename from src/client/media/sfu-quality-probe.ts
rename to src/client/media/candidate-quality-probe.ts
index 05f4e3d3..3a7f9611 100644
--- a/src/client/media/sfu-quality-probe.ts
+++ b/src/client/media/candidate-quality-probe.ts
@@ -8,7 +8,7 @@ interface DeliveredVideoSample {
timestampMs: number;
pixels: number;
framesPerSecond: number;
- bitrateKbps: number;
+ bitrateKbps: number | null;
}
function deliveredVideoSample(
@@ -29,20 +29,17 @@ function deliveredVideoSample(
frameWidth === null ||
frameHeight === null ||
framesPerSecond === null ||
- bitrateKbps === null ||
intervalFramesDecoded === null ||
!Number.isFinite(sampleTimestampMs) ||
!Number.isFinite(sampleWindowMs) ||
!Number.isFinite(frameWidth) ||
!Number.isFinite(frameHeight) ||
!Number.isFinite(framesPerSecond) ||
- !Number.isFinite(bitrateKbps) ||
frameWidth <= 0 ||
frameHeight <= 0 ||
sampleWindowMs < 1_000 ||
sampleWindowMs > 5_000 ||
framesPerSecond <= 0 ||
- bitrateKbps <= 0 ||
intervalFramesDecoded <= 0
) {
return null;
@@ -51,14 +48,19 @@ function deliveredVideoSample(
timestampMs: sampleTimestampMs,
pixels: frameWidth * frameHeight,
framesPerSecond: Math.round(framesPerSecond),
- bitrateKbps,
+ bitrateKbps:
+ typeof bitrateKbps === "number" &&
+ Number.isFinite(bitrateKbps) &&
+ bitrateKbps > 0
+ ? bitrateKbps
+ : null,
};
}
-export function sfuCandidateDoesNotRegress(
+function comparableSamples(
current: ConnectionMetrics,
candidate: ConnectionMetrics,
-): boolean | null {
+): [DeliveredVideoSample, DeliveredVideoSample] | null {
const currentVideo = deliveredVideoSample(current);
const candidateVideo = deliveredVideoSample(candidate);
if (
@@ -73,6 +75,22 @@ export function sfuCandidateDoesNotRegress(
) {
return null;
}
+ return [currentVideo, candidateVideo];
+}
+
+export function sfuCandidateDoesNotRegress(
+ current: ConnectionMetrics,
+ candidate: ConnectionMetrics,
+): boolean | null {
+ const samples = comparableSamples(current, candidate);
+ if (!samples) return null;
+ const [currentVideo, candidateVideo] = samples;
+ if (
+ currentVideo.bitrateKbps === null ||
+ candidateVideo.bitrateKbps === null
+ ) {
+ return null;
+ }
return (
candidate.intervalFreezeCount === 0 &&
candidate.intervalFreezeDurationMs === 0 &&
@@ -84,10 +102,36 @@ export function sfuCandidateDoesNotRegress(
);
}
-export class SfuQualityProbe {
+export function p2pCandidateStrictlyImproves(
+ current: ConnectionMetrics,
+ candidate: ConnectionMetrics,
+): boolean | null {
+ const samples = comparableSamples(current, candidate);
+ if (!samples) return null;
+ const [currentVideo, candidateVideo] = samples;
+ return (
+ candidate.intervalFreezeCount === 0 &&
+ candidate.intervalFreezeDurationMs === 0 &&
+ candidate.intervalPauseCount === 0 &&
+ candidate.intervalPauseDurationMs === 0 &&
+ candidateVideo.pixels >= currentVideo.pixels &&
+ candidateVideo.framesPerSecond >= currentVideo.framesPerSecond &&
+ (candidateVideo.pixels > currentVideo.pixels ||
+ candidateVideo.framesPerSecond > currentVideo.framesPerSecond)
+ );
+}
+
+class ConsecutiveCandidateQualityProbe {
private lastCandidateTimestampMs: number | null = null;
private lastCurrentTimestampMs: number | null = null;
- private consecutiveNonRegressingWindows = 0;
+ private consecutiveApprovedWindows = 0;
+
+ constructor(
+ private readonly compare: (
+ current: ConnectionMetrics,
+ candidate: ConnectionMetrics,
+ ) => boolean | null,
+ ) {}
observe(
current: ConnectionMetrics | null,
@@ -106,20 +150,16 @@ export class SfuQualityProbe {
(this.lastCurrentTimestampMs !== null &&
current.sampleTimestampMs <= this.lastCurrentTimestampMs)
) {
- this.consecutiveNonRegressingWindows = 0;
+ this.consecutiveApprovedWindows = 0;
return false;
}
this.lastCurrentTimestampMs = current.sampleTimestampMs;
- const nonRegressing = sfuCandidateDoesNotRegress(current, candidate);
- if (nonRegressing === null) {
- this.consecutiveNonRegressingWindows = 0;
- return false;
- }
- this.consecutiveNonRegressingWindows = nonRegressing
- ? this.consecutiveNonRegressingWindows + 1
+ const approved = this.compare(current, candidate);
+ this.consecutiveApprovedWindows = approved
+ ? this.consecutiveApprovedWindows + 1
: 0;
return (
- this.consecutiveNonRegressingWindows >=
+ this.consecutiveApprovedWindows >=
PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS
);
}
@@ -127,6 +167,18 @@ export class SfuQualityProbe {
reset(): void {
this.lastCandidateTimestampMs = null;
this.lastCurrentTimestampMs = null;
- this.consecutiveNonRegressingWindows = 0;
+ this.consecutiveApprovedWindows = 0;
+ }
+}
+
+export class SfuQualityProbe extends ConsecutiveCandidateQualityProbe {
+ constructor() {
+ super(sfuCandidateDoesNotRegress);
+ }
+}
+
+export class P2pQualityProbe extends ConsecutiveCandidateQualityProbe {
+ constructor() {
+ super(p2pCandidateStrictlyImproves);
}
}
diff --git a/src/client/media/sender-quality-evidence.ts b/src/client/media/sender-quality-evidence.ts
index 8cdd541a..fa79741f 100644
--- a/src/client/media/sender-quality-evidence.ts
+++ b/src/client/media/sender-quality-evidence.ts
@@ -105,6 +105,13 @@ export function senderQualityEvidenceFromSnapshot(
reason: state === "unknown" ? null : snapshot.metrics.qualityLimitationReason,
framesPerSecond: snapshot.metrics.framesPerSecond,
bitrateKbps: snapshot.metrics.bitrateKbps,
+ captureFramesPerSecond: snapshot.metrics.captureFramesPerSecond,
+ mediaSourceFramesPerSecond: snapshot.metrics.mediaSourceFramesPerSecond,
+ width: snapshot.metrics.frameWidth,
+ height: snapshot.metrics.frameHeight,
+ availableOutgoingKbps: snapshot.metrics.availableOutgoingKbps,
+ rttMs: snapshot.metrics.rttMs,
+ packetLossPercent: snapshot.metrics.packetLossPercent,
},
});
if (!parsed.success) {
@@ -162,6 +169,13 @@ export function sfuPublisherQualityEvidenceFromMetrics(
reason: state === "unknown" ? null : metrics.qualityLimitationReason,
framesPerSecond: metrics.framesPerSecond,
bitrateKbps: metrics.bitrateKbps,
+ captureFramesPerSecond: metrics.captureFramesPerSecond,
+ mediaSourceFramesPerSecond: metrics.mediaSourceFramesPerSecond,
+ width: metrics.frameWidth,
+ height: metrics.frameHeight,
+ availableOutgoingKbps: metrics.availableOutgoingKbps,
+ rttMs: metrics.rttMs,
+ packetLossPercent: metrics.packetLossPercent,
},
});
if (!parsed.success) {
diff --git a/src/client/media/viewer-presentation.ts b/src/client/media/viewer-presentation.ts
index 7b8d222e..29692259 100644
--- a/src/client/media/viewer-presentation.ts
+++ b/src/client/media/viewer-presentation.ts
@@ -66,7 +66,7 @@ interface ViewerRouteStatusFact {
interface ViewerMediaFact {
generation: number;
- revision: number;
+ boundAtRevision: number;
framePresented: boolean;
}
@@ -102,7 +102,6 @@ export type ViewerPresentationAction =
revision: number;
phase: "prepare" | "active";
kind: ViewerRouteKind;
- preserveMedia?: boolean;
}
| {
type: "route-status";
@@ -137,6 +136,10 @@ export interface ViewerPresentation {
hasCurrentFrame: boolean;
hasRetainedFrame: boolean;
failureCode: ViewerFailureCode | null;
+ connectionState:
+ | "routing"
+ | "waiting"
+ | Exclude<ViewerPresentationState["connection"], "idle">;
}
export const INITIAL_VIEWER_PRESENTATION_STATE: ViewerPresentationState = {
@@ -197,11 +200,11 @@ export function reduceViewerPresentation(
return state;
}
const revisionChanged = state.revision !== action.revision;
- const currentFrame = hasCurrentFrame(state);
- const preserveMedia =
- revisionChanged &&
- action.preserveMedia === true &&
- state.media?.revision === state.revision;
+ const committedRoute = action.phase === "active" && action.kind !== "none";
+ const reactivatingTerminalRoute =
+ committedRoute &&
+ (state.routeStatus?.state === "failed" ||
+ state.failure === "ROUTE_EXHAUSTED");
return {
...state,
revision: action.revision,
@@ -211,29 +214,20 @@ export function reduceViewerPresentation(
kind: action.kind,
},
routeStatus:
- state.routeStatus?.revision === action.revision
+ !committedRoute && state.routeStatus?.revision === action.revision
? state.routeStatus
: null,
- media: preserveMedia
- ? { ...state.media!, revision: action.revision }
- : state.media,
- autoplayBlockedGeneration: revisionChanged && !preserveMedia
- ? null
- : state.autoplayBlockedGeneration,
- retainedFrame:
- preserveMedia
- ? state.retainedFrame
- : state.retainedFrame || (revisionChanged && currentFrame),
- connection: revisionChanged && !preserveMedia
- ? action.kind === "none"
- ? "idle"
+ connection: reactivatingTerminalRoute
+ ? state.media
+ ? "reconnecting"
: "connecting"
- : state.connection,
+ : revisionChanged && state.media === null
+ ? action.kind === "none"
+ ? "idle"
+ : "connecting"
+ : state.connection,
failure:
- revisionChanged &&
- (state.failure === "ROUTE_EXHAUSTED" ||
- state.failure === "AUTOPLAY_BLOCKED" ||
- state.failure === "PLAYBACK_FAILED")
+ committedRoute && state.failure === "ROUTE_EXHAUSTED"
? null
: state.failure,
};
@@ -246,11 +240,9 @@ export function reduceViewerPresentation(
const terminal = action.state === "failed";
const currentFrame = hasCurrentFrame(state);
const currentMedia =
- terminal && state.media?.revision === action.revision
+ terminal && state.media
? { ...state.media, framePresented: false }
- : terminal
- ? null
- : state.media;
+ : state.media;
return {
...state,
revision: action.revision,
@@ -258,6 +250,11 @@ export function reduceViewerPresentation(
revision: action.revision,
state: action.state,
},
+ connection: terminal
+ ? "failed"
+ : state.media
+ ? state.connection
+ : "connecting",
media: currentMedia,
autoplayBlockedGeneration: revisionChanged || terminal
? null
@@ -287,7 +284,6 @@ export function reduceViewerPresentation(
};
case "media-bound": {
if (
- (state.revision !== null && action.revision < state.revision) ||
(state.media && action.generation <= state.media.generation) ||
(state.routeStatus?.revision === action.revision &&
state.routeStatus.state === "failed") ||
@@ -298,10 +294,9 @@ export function reduceViewerPresentation(
}
return {
...state,
- revision: Math.max(state.revision ?? 0, action.revision),
media: {
generation: action.generation,
- revision: action.revision,
+ boundAtRevision: action.revision,
framePresented: false,
},
retainedFrame: state.retainedFrame || hasCurrentFrame(state),
@@ -318,8 +313,6 @@ export function reduceViewerPresentation(
if (
!state.media ||
state.media.generation !== action.generation ||
- state.media.revision !== action.revision ||
- state.revision !== action.revision ||
state.routeStatus?.state === "failed" ||
state.failure === "ROUTE_EXHAUSTED"
) {
@@ -338,8 +331,6 @@ export function reduceViewerPresentation(
if (
!state.media ||
state.media.generation !== action.generation ||
- state.media.revision !== action.revision ||
- state.revision !== action.revision ||
!state.media.framePresented
) {
return state;
@@ -352,9 +343,7 @@ export function reduceViewerPresentation(
case "autoplay-blocked":
if (
!state.media ||
- state.media.generation !== action.generation ||
- state.media.revision !== action.revision ||
- state.revision !== action.revision
+ state.media.generation !== action.generation
) {
return state;
}
@@ -376,9 +365,7 @@ export function reduceViewerPresentation(
case "playback-failed":
if (
!state.media ||
- state.media.generation !== action.generation ||
- state.media.revision !== action.revision ||
- state.revision !== action.revision
+ state.media.generation !== action.generation
) {
return state;
}
@@ -423,13 +410,9 @@ export function reduceViewerPresentation(
}
const terminalRoute = action.failure === "ROUTE_EXHAUSTED";
const terminalMedia =
- terminalRoute &&
- action.revision !== undefined &&
- state.media?.revision === action.revision
+ terminalRoute && state.media
? { ...state.media, framePresented: false }
- : terminalRoute
- ? null
- : state.media;
+ : state.media;
return {
...state,
revision:
@@ -437,6 +420,7 @@ export function reduceViewerPresentation(
? state.revision
: Math.max(state.revision ?? 0, action.revision),
media: terminalMedia,
+ connection: terminalRoute ? "failed" : state.connection,
retainedFrame:
state.retainedFrame || (terminalRoute && hasCurrentFrame(state)),
autoplayBlockedGeneration: terminalRoute
@@ -528,7 +512,6 @@ export function deriveViewerPresentation(
if (
state.media &&
- state.media.revision === state.revision &&
state.autoplayBlockedGeneration === state.media.generation &&
state.connection === "connected"
) {
@@ -646,7 +629,7 @@ export function deriveViewerPresentation(
state,
);
}
- if (state.media && state.media.revision === state.revision) {
+ if (state.media) {
return presentation(
"receiving",
"正在接收画面",
@@ -725,9 +708,7 @@ export function viewerFailureFromServerCode(
}
function hasCurrentFrame(state: ViewerPresentationState): boolean {
- return Boolean(
- state.media?.framePresented && state.media.revision === state.revision,
- );
+ return state.media?.framePresented === true;
}
function presentation(
@@ -744,5 +725,11 @@ function presentation(
hasCurrentFrame: hasCurrentFrame(state),
hasRetainedFrame: state.retainedFrame,
failureCode: state.failure,
+ connectionState:
+ state.connection === "idle"
+ ? state.host === "online" || state.host === "paused"
+ ? "routing"
+ : "waiting"
+ : state.connection,
};
}
diff --git a/src/client/media/viewer-sfu-route.ts b/src/client/media/viewer-sfu-route.ts
index bc45d4c5..d1578fd2 100644
--- a/src/client/media/viewer-sfu-route.ts
+++ b/src/client/media/viewer-sfu-route.ts
@@ -8,7 +8,7 @@ import type {
import { SfuSubscriber } from "../sfu/subscriber";
import type { ConnectionMetrics } from "../types";
import type { SfuConnectionConfig } from "../sfu/publisher";
-import { SfuQualityProbe } from "./sfu-quality-probe";
+import { SfuQualityProbe } from "./candidate-quality-probe";
import {
MediaRouteTransition,
reportActivePeerRouteFailure,
@@ -28,6 +28,7 @@ interface ViewerSubscriberTransport {
interface ViewerSubscriberSlot {
revision: number;
+ phase: MediaRoutePhase;
publicationGeneration: string;
subscriber: ViewerSubscriberTransport;
connected: boolean;
@@ -118,10 +119,39 @@ export class ViewerSfuRoute {
return "stale";
}
const previousRevision = this.route.getRevision();
+ const previousMediaAssignment = this.route.getMediaAssignment();
+ const sameCommittedMedia =
+ update.phase === "active" &&
+ sameUpstream(previousMediaAssignment, update.assignment);
+ const continuingRecovery =
+ previousRevision !== update.revision && sameCommittedMedia
+ ? this.manualReconnectRevision !== null
+ ? "manual"
+ : this.recovery !== null
+ ? "automatic"
+ : null
+ : null;
const result = this.route.accept(update);
if (result === "stale") {
return result;
}
+ if (continuingRecovery) {
+ if (this.active) {
+ this.active.revision = update.revision;
+ }
+ if (this.pending?.phase === "active") {
+ this.pending.revision = update.revision;
+ }
+ if (this.manualReconnectRevision !== null) {
+ this.manualReconnectRevision = update.revision;
+ }
+ if (this.recovery) {
+ this.recovery.revision = update.revision;
+ if (this.pending === null) {
+ this.recovery.refreshed = false;
+ }
+ }
+ }
const pausedActiveReconciliation =
this.paused && update.phase === "active" && result !== "duplicate";
const retiredActive = pausedActiveReconciliation
@@ -142,7 +172,7 @@ export class ViewerSfuRoute {
this.disconnectRetiredSubscriber(retiredActive),
);
}
- if (previousRevision !== update.revision) {
+ if (previousRevision !== update.revision && !sameCommittedMedia) {
this.recovery = null;
this.manualReconnectRevision = null;
if (
@@ -206,7 +236,22 @@ export class ViewerSfuRoute {
if (this.resyncing) {
return result;
}
- void this.queueActiveRoute(token, acknowledge, this.paused);
+ const transition = this.queueActiveRoute(token, acknowledge, this.paused);
+ if (continuingRecovery === "manual" && this.pending === null) {
+ void transition.then(() => {
+ if (
+ this.closed ||
+ this.paused ||
+ this.route.getRevision() !== update.revision ||
+ this.route.getPhase() !== "active"
+ ) {
+ return;
+ }
+ if (this.manualReconnectRevision === update.revision) {
+ this.events.send({ type: "refresh-sfu", revision: update.revision });
+ }
+ });
+ }
return result;
}
@@ -281,9 +326,24 @@ export class ViewerSfuRoute {
this.viewerPeerId = viewerPeerId;
}
this.pendingPeerRevision = null;
- if (!identityChanged && !this.active && !this.pending) {
+ const currentMediaAssignment = this.route.getMediaAssignment();
+ const preservesActiveMedia = Boolean(
+ !identityChanged &&
+ update.phase === "active" &&
+ sameUpstream(currentMediaAssignment, update.assignment) &&
+ (update.assignment.upstream.kind !== "sfu" ||
+ (this.active?.activated &&
+ !this.active.failed &&
+ this.active.publicationGeneration ===
+ update.assignment.sfuPublicationGeneration)),
+ );
+ if (
+ !identityChanged &&
+ ((!this.active && !this.pending) || preservesActiveMedia)
+ ) {
const result = this.accept(update, false);
if (result !== "stale") {
+ await this.transitionTail;
return result;
}
}
@@ -438,6 +498,7 @@ export class ViewerSfuRoute {
const preparedCandidate = this.route.getPreparedCandidate();
slot = {
revision: message.revision,
+ phase,
publicationGeneration,
subscriber,
connected: false,
@@ -462,16 +523,20 @@ export class ViewerSfuRoute {
token: message.token,
});
if (!connected) {
- if (this.pending === slot && this.route.owns(token)) {
+ const currentToken = this.currentPendingToken(slot, token);
+ if (this.pending === slot && currentToken) {
+ slot.revision = currentToken.revision;
this.handleFailure(slot);
}
await disconnectSubscriber(subscriber);
return;
}
- if (this.pending !== slot || !this.route.owns(token)) {
+ const currentToken = this.currentPendingToken(slot, token);
+ if (this.pending !== slot || !currentToken) {
await disconnectSubscriber(subscriber);
return;
}
+ slot.revision = currentToken.revision;
slot.connected = true;
if (!subscriber.activate()) {
this.handleFailure(slot);
@@ -482,8 +547,8 @@ export class ViewerSfuRoute {
if (!this.paused) {
subscriber.armDecodedFrameProof();
}
- if (phase === "active" && !this.resyncing) {
- await this.queueActiveRoute(token, true);
+ if (slot.phase === "active" && !this.resyncing) {
+ await this.queueActiveRoute(currentToken, true);
}
} catch {
await disconnectSubscriber(subscriber);
@@ -652,7 +717,11 @@ export class ViewerSfuRoute {
pending.publicationGeneration !== publicationGeneration ||
!pending.connected
) {
- if (acknowledge && this.route.owns(token, "active")) {
+ if (
+ acknowledge &&
+ this.route.owns(token, "active") &&
+ pending === null
+ ) {
this.requestRecovery(token.revision);
}
return;
@@ -888,6 +957,13 @@ export class ViewerSfuRoute {
if (!matchesPlannedRoute) {
return;
}
+ if (
+ this.recovery?.revision === revision &&
+ this.recovery.refreshed
+ ) {
+ this.routeFailed(revision, "active");
+ return;
+ }
this.requestRecovery(revision);
}
@@ -901,7 +977,26 @@ export class ViewerSfuRoute {
return;
}
}
- this.routeFailed(revision, "active");
+ }
+
+ private currentPendingToken(
+ slot: ViewerSubscriberSlot,
+ original: RouteOperationToken,
+ ): RouteOperationToken | null {
+ if (this.route.owns(original)) {
+ return original;
+ }
+ if (slot.phase !== "active") {
+ return null;
+ }
+ const current = this.route.token();
+ const assignment = this.route.getActiveAssignment();
+ return current &&
+ this.route.owns(current, "active") &&
+ assignment?.upstream.kind === "sfu" &&
+ assignment.sfuPublicationGeneration === slot.publicationGeneration
+ ? current
+ : null;
}
private routeFailed(revision: number, phase: MediaRoutePhase): void {
@@ -915,6 +1010,24 @@ export class ViewerSfuRoute {
}
+function sameUpstream(
+ current: ParticipantRouteAssignment | null,
+ next: ParticipantRouteAssignment,
+): boolean {
+ if (!current || current.upstream.kind !== next.upstream.kind) {
+ return false;
+ }
+ if (current.upstream.kind === "peer" && next.upstream.kind === "peer") {
+ return current.upstream.peerId === next.upstream.peerId;
+ }
+ if (current.upstream.kind === "sfu" && next.upstream.kind === "sfu") {
+ return (
+ current.sfuPublicationGeneration === next.sfuPublicationGeneration
+ );
+ }
+ return current.upstream.kind === "none";
+}
+
async function disconnectSubscriber(
subscriber: ViewerSubscriberTransport,
): Promise<void> {
diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsx
index de94097c..27408b87 100644
--- a/src/client/pages/ViewerPage.tsx
+++ b/src/client/pages/ViewerPage.tsx
@@ -45,6 +45,7 @@ import { readDisplayName, saveDisplayName } from "../lib/display-name";
import { clearViewerGrant, getStableClientId } from "../lib/session";
import { SignalingClient } from "../lib/signaling";
import { labelParticipantSnapshot } from "../lib/viewer-presence";
+import { P2pQualityProbe } from "../media/candidate-quality-probe";
import { DecodedFrameStallDetector } from "../media/decoded-frame-stall";
import type { QualitySettings } from "../media/quality";
import { relayCapacityMessageForBrowser } from "../media/relay-capability";
@@ -115,12 +116,14 @@ interface PendingPeerRoute {
candidateConnectionId: string;
stream: MediaStream | null;
snapshot: PeerSnapshot | null;
+ qualityProbe: P2pQualityProbe | null;
+ qualityApproved: boolean;
}
interface RemoteMediaBinding {
stream: MediaStream;
generation: number;
- revision: number;
+ boundAtRevision: number;
videoTrackKey: string;
}
@@ -169,7 +172,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
const presentation = deriveViewerPresentation(presentationState);
const accessState = presentationState.access;
const signalStatus = presentationState.signal;
- const [hostOnline, setHostOnline] = useState(false);
const [remoteMedia, setRemoteMedia] = useState<RemoteMediaBinding | null>(
null,
);
@@ -273,9 +275,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
signalStatus === "connected" &&
reconnectRoute !== null &&
presentationState.connection !== "reconnecting";
- const routeConnectionState =
- routePresentation.evidence?.connectionState ??
- (hostOnline ? "routing" : "waiting");
+ const routeConnectionState = presentation.connectionState;
const routeMetrics = routePresentation.evidence?.metrics ?? null;
function bindRemoteStream(stream: MediaStream, revision: number): void {
@@ -287,14 +287,13 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
const current = remoteMediaRef.current;
if (
current?.stream === stream &&
- current.revision === revision &&
current.videoTrackKey === videoTrackKey
) {
return;
}
const next: RemoteMediaBinding = {
stream,
- revision,
+ boundAtRevision: revision,
videoTrackKey,
generation: ++mediaGenerationRef.current,
};
@@ -304,7 +303,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
dispatchPresentation({
type: "media-bound",
generation: next.generation,
- revision: next.revision,
+ revision: next.boundAtRevision,
});
}
@@ -323,7 +322,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
dispatchPresentation({
type: "frame-proof-reset",
generation: binding.generation,
- revision: binding.revision,
+ revision: binding.boundAtRevision,
});
}
@@ -341,7 +340,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
const current = remoteMediaRef.current;
return (
current?.generation === binding.generation &&
- current.revision === binding.revision &&
current.stream === binding.stream
);
}
@@ -369,13 +367,13 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
dispatchPresentation({
type: "autoplay-blocked",
generation: binding.generation,
- revision: binding.revision,
+ revision: binding.boundAtRevision,
});
} else {
dispatchPresentation({
type: "playback-failed",
generation: binding.generation,
- revision: binding.revision,
+ revision: binding.boundAtRevision,
});
}
},
@@ -386,16 +384,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
revision: number,
upstream: ParticipantRouteAssignment["upstream"],
phase: "prepare" | "active" = "active",
- preserveMedia = false,
): void {
- if (preserveMedia) {
- const current = remoteMediaRef.current;
- if (current && current.revision !== revision) {
- const rebased = { ...current, revision };
- remoteMediaRef.current = rebased;
- setRemoteMedia(rebased);
- }
- }
setAssignedRoute((current) =>
current && revision < current.revision
? current
@@ -406,7 +395,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
revision,
phase,
kind: routeKindFromAssignment(upstream),
- preserveMedia,
});
}
@@ -458,6 +446,8 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
const newlySuspended = !pageSuspended;
pageSuspended = true;
viewerSfuRoute?.resetQualityProbe();
+ pendingPeer?.qualityProbe?.reset();
+ if (pendingPeer) pendingPeer.qualityApproved = false;
syncDecodedFrameStallPause();
if (newlySuspended) {
invalidateSenderQualityEvidence();
@@ -575,7 +565,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
currentRouteAssignment.upstream.kind !== "none" &&
currentRouteConnectionId !== null &&
binding &&
- binding.revision === currentRouteRevision &&
qualityFrameProofGenerationRef.current === binding.generation &&
state.routeStatus?.state !== "failed" &&
state.failure !== "ROUTE_EXHAUSTED" &&
@@ -828,10 +817,14 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
if (!pendingPeerHasDecodedFrame(probe)) {
return false;
}
+ if (probe.qualityProbe && !probe.qualityApproved) {
+ return false;
+ }
probe.readySent = signal.send({
type: "route-ready",
revision: probe.revision,
phase: "prepare",
+ ...(probe.qualityProbe ? { qualityApproved: true as const } : {}),
});
return probe.readySent;
}
@@ -913,6 +906,10 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
candidateConnectionId: candidate.connectionId,
stream: null,
snapshot: null,
+ qualityProbe: candidate.qualityProbe
+ ? new P2pQualityProbe()
+ : null,
+ qualityApproved: false,
};
}
prepareParent(
@@ -1165,6 +1162,22 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
if (pendingPeer === probe) {
if (snapshot.connectionId !== probe.candidateConnectionId) return;
probe.snapshot = snapshot;
+ if (probe.qualityProbe) {
+ if (
+ pageSuspended ||
+ currentHostPaused ||
+ !qualityPresentationEligible(
+ peerRef.current?.isConnected() === true,
+ )
+ ) {
+ probe.qualityProbe.reset();
+ probe.qualityApproved = false;
+ } else if (
+ probe.qualityProbe.observe(activePeerMetrics, snapshot.metrics)
+ ) {
+ probe.qualityApproved = true;
+ }
+ }
provePendingPeer();
} else if (active && peerRef.current === peer) {
activePeerMetrics = snapshot.metrics;
@@ -1364,7 +1377,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
}
currentIceConfig = message.iceConfig;
currentHostOnline = message.hostOnline;
- setHostOnline(message.hostOnline);
const sharingPaused = message.hostPaused ?? false;
if (currentHostPaused !== sharingPaused && sharingPaused) {
invalidatePresentedMedia();
@@ -1464,18 +1476,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
message.assignment.upstream.kind === "sfu" &&
currentRouteAssignment.sfuPublicationGeneration ===
message.assignment.sfuPublicationGeneration;
- const peerIdentity = peerRef.current?.getConnectionIdentity();
- const exactPeerUpstream =
- samePeerUpstream &&
- currentRouteAssignment?.upstream.kind === "peer" &&
- currentRouteConnectionId !== null &&
- peerIdentity != null &&
- peerIdentity.parentPeerId ===
- currentRouteAssignment.upstream.peerId &&
- peerIdentity.connectionId === currentRouteConnectionId;
- const preserveMedia =
- remoteMediaRef.current !== null &&
- (sameSfuUpstream || exactPeerUpstream);
const connectionId =
pendingRouteConnection?.revision === message.revision
? pendingRouteConnection.connectionId
@@ -1496,7 +1496,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
message.revision,
message.assignment.upstream,
"active",
- preserveMedia,
);
}
}
@@ -1631,7 +1630,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
}
currentHostPaused = message.paused;
syncDecodedFrameStallPause();
- setHostOnline(message.online);
dispatchPresentation({
type: "host",
host: message.paused
@@ -1663,7 +1661,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
clearViewerSfuRoute();
clearPeerState(true);
clearHostPresence();
- setHostOnline(false);
dispatchPresentation({ type: "sharing-stopped" });
return;
}
@@ -1848,7 +1845,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
dispatchPresentation({
type: "frame-presented",
generation: binding.generation,
- revision: binding.revision,
+ revision: binding.boundAtRevision,
});
});
}, [frameProofEpoch, presentationState.connection, remoteMedia]);
diff --git a/src/client/webrtc/host-peer.ts b/src/client/webrtc/host-peer.ts
index 5f963337..a33d824f 100644
--- a/src/client/webrtc/host-peer.ts
+++ b/src/client/webrtc/host-peer.ts
@@ -682,9 +682,9 @@ export class HostPeer {
}
switch (this.limitationReason) {
case "bandwidth":
- return "持续受带宽限制,浏览器正在降低画面质量";
+ return "此发送连接持续按带宽估计降低分辨率或帧率";
case "cpu":
- return "持续受编码性能限制,浏览器正在降低画面质量";
+ return "此发送连接持续因编码性能降低分辨率或帧率";
case "other":
return "浏览器持续报告其他画质限制";
default:
diff --git a/src/server/hybrid-media-router.ts b/src/server/hybrid-media-router.ts
index 0a968c48..5d8d2b8c 100644
--- a/src/server/hybrid-media-router.ts
+++ b/src/server/hybrid-media-router.ts
@@ -324,6 +324,16 @@ export class HybridMediaRouter {
reason: message.diagnostics.reason,
framesPerSecond: message.diagnostics.framesPerSecond,
bitrateKbps: message.diagnostics.bitrateKbps,
+ captureFramesPerSecond:
+ message.diagnostics.captureFramesPerSecond ?? null,
+ mediaSourceFramesPerSecond:
+ message.diagnostics.mediaSourceFramesPerSecond ?? null,
+ width: message.diagnostics.width ?? null,
+ height: message.diagnostics.height ?? null,
+ availableOutgoingKbps:
+ message.diagnostics.availableOutgoingKbps ?? null,
+ rttMs: message.diagnostics.rttMs ?? null,
+ packetLossPercent: message.diagnostics.packetLossPercent ?? null,
});
}
this.releaseResources(result.released);
@@ -384,6 +394,16 @@ export class HybridMediaRouter {
reason: message.diagnostics.reason,
framesPerSecond: message.diagnostics.framesPerSecond,
bitrateKbps: message.diagnostics.bitrateKbps,
+ captureFramesPerSecond:
+ message.diagnostics.captureFramesPerSecond ?? null,
+ mediaSourceFramesPerSecond:
+ message.diagnostics.mediaSourceFramesPerSecond ?? null,
+ width: message.diagnostics.width ?? null,
+ height: message.diagnostics.height ?? null,
+ availableOutgoingKbps:
+ message.diagnostics.availableOutgoingKbps ?? null,
+ rttMs: message.diagnostics.rttMs ?? null,
+ packetLossPercent: message.diagnostics.packetLossPercent ?? null,
});
}
this.releaseResources(result.released);
@@ -635,6 +655,7 @@ export class HybridMediaRouter {
},
this.now(),
(reservation) => this.commitReservation(reservation),
+ { relativeQualityApproved: message.qualityApproved === true },
);
this.debug(participant.roomId, "route-ready-settled", {
participant: this.debugPeer(participant.roomId, participant.peerId),
@@ -851,12 +872,13 @@ export class HybridMediaRouter {
refreshSfu(participant: AuthenticatedRouteParticipant, revision: number): void {
const room = this.rooms.get(participant.roomId);
const snapshot = room?.controller?.snapshot();
- if (!room || !snapshot || snapshot.revision !== revision) return;
- const key = `${revision}\u0000${participant.peerId}\u0000${participant.sessionId}`;
+ if (!room || !snapshot || revision > snapshot.revision) return;
+ const currentRevision = snapshot.revision;
+ const key = `${currentRevision}\u0000${participant.peerId}\u0000${participant.sessionId}`;
if (room.sfuRefreshesInFlight.has(key)) return;
room.sfuRefreshesInFlight.add(key);
void this.sendFreshSfuConfig(participant)
- .catch(() => this.failCurrentSfuRoute(participant, revision))
+ .catch(() => this.failCurrentSfuRoute(participant, currentRevision))
.finally(() => room.sfuRefreshesInFlight.delete(key));
}
@@ -915,7 +937,7 @@ export class HybridMediaRouter {
requested: false,
sfuRefreshesInFlight: new Set(),
debugOrdinalByPeerId: new Map(),
- nextDebugOrdinal: 0,
+ nextDebugOrdinal: 1,
};
this.rooms.set(roomId, room);
}
@@ -1949,9 +1971,7 @@ function preparedRouteCandidate(
childPeerId: operation.childPeerId,
connectionId,
transport: tuple.kind === "peer" ? tuple.transport : "sfu",
- qualityProbe:
- operation.reason === "quality-convergence" ||
- operation.reason === "root-convergence",
+ qualityProbe: operation.reason === "quality-convergence",
};
}
diff --git a/src/server/room-route-controller.ts b/src/server/room-route-controller.ts
index 693cfb54..3ab08107 100644
--- a/src/server/room-route-controller.ts
+++ b/src/server/room-route-controller.ts
@@ -944,7 +944,7 @@ export class RoomRouteController<Resource = unknown> {
const operation = this.operation;
const attempt = operation?.current;
if (
- this.operationRequiresHealthyCandidate(operation) &&
+ operation?.reason === "root-convergence" &&
attempt?.tuple.kind === "peer" &&
operation.childPeerId === input.childPeerId &&
operation.childSessionId === child.sessionId &&
@@ -1033,16 +1033,9 @@ export class RoomRouteController<Resource = unknown> {
previous.lastAcceptedAtMs + VIEWER_QUALITY_EVIDENCE_EXPIRY_MS;
const senderIdentityChanged =
sameIdentity && previous?.senderIdentity !== input.senderIdentity;
- const wasFreshHealthy =
- sameSenderIdentity &&
- previous?.state === "healthy" &&
- input.acceptedAtMs <
- previous.lastAcceptedAtMs + VIEWER_QUALITY_EVIDENCE_EXPIRY_MS;
const baselineRequired = this.senderQualityBaselines.has(
input.childPeerId,
);
- const baselineSuppressesFact =
- this.senderQualityBaselines.get(input.childPeerId) === true;
if (input.state === "healthy") {
this.senderQualityBaselines.delete(input.childPeerId);
}
@@ -1085,13 +1078,6 @@ export class RoomRouteController<Resource = unknown> {
consecutiveDegradedWindows,
});
}
- if (
- input.state === "healthy" &&
- !wasFreshHealthy &&
- !baselineSuppressesFact
- ) {
- this.touchFacts();
- }
if (
input.state === "healthy" &&
operation?.reason === "quality-convergence" &&
@@ -1426,7 +1412,7 @@ export class RoomRouteController<Resource = unknown> {
const operation = this.operation;
const attempt = operation?.current;
const ownsCandidate =
- this.operationRequiresHealthyCandidate(operation) &&
+ this.operationRequiresNativeCandidateProof(operation) &&
attempt &&
(attempt.tuple.kind === "peer"
? attempt.tuple.parentPeerId === parentPeerId &&
@@ -1630,27 +1616,6 @@ export class RoomRouteController<Resource = unknown> {
failedPeerIds: failedPeerIdsFrom(validation),
};
}
- if (
- this.operationRequiresHealthyCandidate(operation) &&
- plan.tuple.kind === "peer" &&
- operation.reason === "quality-convergence" &&
- !this.qualitySourcePathHealthy(plan.tuple.parentPeerId, input.nowMs)
- ) {
- this.noteRejection(operation.demandPeerId, "stale");
- operation.cursor += 1;
- this.clearCandidateTiming(operation.demandPeerId);
- const advanced = this.validateOrAdvance(input.nowMs);
- return {
- accepted: true,
- operation: this.operationSnapshot(),
- released: [
- ...validation.released,
- ...reservationResources(input.reservation),
- ...advanced.released,
- ],
- failedPeerIds: failedPeerIdsFrom(validation, advanced),
- };
- }
if (plan.endpointTransition.kind === "bounded-gap") {
return {
accepted: false,
@@ -1861,6 +1826,7 @@ export class RoomRouteController<Resource = unknown> {
guard: CandidateGuard,
nowMs: number,
commitReservation: (reservation: CandidateReservation<Resource>) => boolean = () => true,
+ proof: { relativeQualityApproved?: boolean } = {},
): SettleResult<Resource> {
const validation = this.validateOrAdvance(nowMs);
const operation = this.operation;
@@ -1873,7 +1839,17 @@ export class RoomRouteController<Resource = unknown> {
released: validation.released,
};
}
- if (this.operationRequiresHealthyCandidate(operation)) {
+ const relativeP2pApproved =
+ operation.reason === "quality-convergence" &&
+ attempt.tuple.kind === "peer" &&
+ proof.relativeQualityApproved === true;
+ const relativeP2pPending =
+ operation.reason === "quality-convergence" &&
+ attempt.tuple.kind === "peer" &&
+ !relativeP2pApproved;
+ const nativeCandidateProof =
+ this.operationRequiresNativeCandidateProof(operation);
+ if (relativeP2pApproved || relativeP2pPending || nativeCandidateProof) {
attempt.mediaReady = true;
const currentEdge = this.upstreamByViewer.get(operation.childPeerId);
if (
@@ -1898,6 +1874,17 @@ export class RoomRouteController<Resource = unknown> {
],
};
}
+ }
+ if (relativeP2pPending) {
+ return {
+ accepted: true,
+ committed: false,
+ failedPeerIds: failedPeerIdsFrom(validation),
+ activeRevision: this.revision,
+ released: validation.released,
+ };
+ }
+ if (nativeCandidateProof) {
const candidateQualityState =
attempt.tuple.kind === "sfu" && attempt.tuple.publication === "reuse"
? this.sfuPublisherQualityState(
@@ -1921,18 +1908,12 @@ export class RoomRouteController<Resource = unknown> {
};
}
if (
- ((attempt.tuple.kind !== "sfu" ||
- attempt.tuple.publication !== "reuse") &&
- (attempt.senderQualityAcceptedAtMs === undefined ||
- nowMs >=
- attempt.senderQualityAcceptedAtMs +
- VIEWER_QUALITY_EVIDENCE_EXPIRY_MS)) ||
- (operation.reason === "quality-convergence" &&
- attempt.tuple.kind === "peer" &&
- !this.qualitySourcePathHealthy(
- attempt.tuple.parentPeerId,
- nowMs,
- ))
+ (attempt.tuple.kind !== "sfu" ||
+ attempt.tuple.publication !== "reuse") &&
+ (attempt.senderQualityAcceptedAtMs === undefined ||
+ nowMs >=
+ attempt.senderQualityAcceptedAtMs +
+ VIEWER_QUALITY_EVIDENCE_EXPIRY_MS)
) {
return this.candidateFailed(guard, nowMs);
}
@@ -2262,14 +2243,9 @@ export class RoomRouteController<Resource = unknown> {
attempt.tuple.kind === "peer" &&
!attempt.transportConnected &&
nowMs >= attempt.startedAtMs + this.directHeadStartMs();
- const qualityPeerSourceInvalid =
- operation.reason === "quality-convergence" &&
- attempt.tuple.kind === "peer" &&
- !this.qualitySourcePathHealthy(attempt.tuple.parentPeerId, nowMs);
if (
!guardFailed &&
!peerNoProgressExpired &&
- !qualityPeerSourceInvalid &&
plan &&
this.candidateValid(operation.childPeerId, plan, attempt)
) {
@@ -2662,26 +2638,33 @@ export class RoomRouteController<Resource = unknown> {
(candidate) =>
candidate.endpointTransition.kind !== "bounded-gap" &&
tupleKey(candidate.tuple) !== currentKey &&
- (candidate.tuple.kind === "peer"
- ? this.qualitySourcePathHealthy(candidate.tuple.parentPeerId, nowMs)
- : candidate.tuple.publication !== "reuse" ||
- Boolean(
- this.hostPublication &&
- this.sfuPublisherQualityState(
- this.hostPublication.generation,
- nowMs,
- ) === "healthy",
- )),
+ (candidate.tuple.kind === "peer" ||
+ candidate.tuple.publication !== "reuse" ||
+ Boolean(
+ this.hostPublication &&
+ this.sfuPublisherQualityState(
+ this.hostPublication.generation,
+ nowMs,
+ ) === "healthy",
+ )),
);
const peers = candidates.filter(
(candidate) => candidate.tuple.kind === "peer",
);
+ const clearPeers = peers.filter(
+ (candidate) =>
+ candidate.tuple.kind === "peer" &&
+ this.qualitySourcePathHealthy(candidate.tuple.parentPeerId, nowMs),
+ );
+ const remainingPeers = peers.filter(
+ (candidate) => !clearPeers.includes(candidate),
+ );
const sfu =
current.parentPeerId === this.options.hostPeerId &&
this.hostFanoutNeedsSfuRelief(nowMs)
? candidates.filter((candidate) => candidate.tuple.kind === "sfu")
: [];
- return [...peers, ...sfu];
+ return [...clearPeers, ...remainingPeers, ...sfu];
}
private selectQualityChild(nowMs: number): string | undefined {
@@ -2960,12 +2943,13 @@ export class RoomRouteController<Resource = unknown> {
);
}
- private operationRequiresHealthyCandidate(
+ private operationRequiresNativeCandidateProof(
operation: ChildOperation<Resource> | undefined,
): operation is ChildOperation<Resource> {
return (
- operation?.reason === "quality-convergence" ||
- operation?.reason === "root-convergence"
+ operation?.reason === "root-convergence" ||
+ (operation?.reason === "quality-convergence" &&
+ operation.current?.tuple.kind === "sfu")
);
}
diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts
index 185ea189..982f00a0 100644
--- a/src/shared/protocol.ts
+++ b/src/shared/protocol.ts
@@ -655,6 +655,13 @@ const senderQualityDiagnosticsSchema = z
reason: z.enum(["none", "bandwidth", "cpu"]).nullable(),
framesPerSecond: nullableEvidenceNumber(240),
bitrateKbps: nullableEvidenceNumber(100_000),
+ captureFramesPerSecond: nullableEvidenceNumber(240).optional(),
+ mediaSourceFramesPerSecond: nullableEvidenceNumber(240).optional(),
+ width: nullableEvidenceInteger(16_384).optional(),
+ height: nullableEvidenceInteger(16_384).optional(),
+ availableOutgoingKbps: nullableEvidenceNumber(100_000).optional(),
+ rttMs: nullableEvidenceNumber(60_000).optional(),
+ packetLossPercent: nullableEvidenceNumber(100).optional(),
})
.strict();
@@ -830,6 +837,7 @@ export const clientMessageSchema = z.union([
type: z.literal("route-ready"),
revision: mediaRouteRevisionSchema,
phase: mediaRoutePhaseSchema,
+ qualityApproved: z.literal(true).optional(),
})
.strict(),
z
diff --git a/tests/sfu-quality-probe.test.ts b/tests/candidate-quality-probe.test.ts
similarity index 56%
rename from tests/sfu-quality-probe.test.ts
rename to tests/candidate-quality-probe.test.ts
index 3d31aca3..f7b8d47b 100644
--- a/tests/sfu-quality-probe.test.ts
+++ b/tests/candidate-quality-probe.test.ts
@@ -1,9 +1,11 @@
import { describe, expect, it } from "vitest";
import {
+ P2pQualityProbe,
SfuQualityProbe,
+ p2pCandidateStrictlyImproves,
sfuCandidateDoesNotRegress,
-} from "../src/client/media/sfu-quality-probe.ts";
+} from "../src/client/media/candidate-quality-probe.ts";
import {
EMPTY_METRICS,
type ConnectionMetrics,
@@ -58,6 +60,81 @@ describe("SFU quality probe", () => {
metrics(8_000),
),
).toBeNull();
+ expect(
+ sfuCandidateDoesNotRegress(
+ current,
+ metrics(2_100, { bitrateKbps: null }),
+ ),
+ ).toBeNull();
+ });
+
+ it("requires a strict P2P receive improvement without a tradeoff", () => {
+ const current = metrics(2_000, {
+ frameWidth: 320,
+ frameHeight: 180,
+ framesPerSecond: 10,
+ bitrateKbps: 200,
+ });
+ expect(
+ p2pCandidateStrictlyImproves(
+ current,
+ metrics(2_100, {
+ frameWidth: 1_280,
+ frameHeight: 720,
+ framesPerSecond: 30,
+ bitrateKbps: 150,
+ }),
+ ),
+ ).toBe(true);
+ expect(
+ p2pCandidateStrictlyImproves(
+ { ...current, bitrateKbps: null },
+ metrics(2_100, {
+ frameWidth: 1_280,
+ frameHeight: 720,
+ framesPerSecond: 30,
+ bitrateKbps: null,
+ }),
+ ),
+ ).toBe(true);
+ expect(p2pCandidateStrictlyImproves(current, { ...current })).toBe(false);
+ expect(
+ p2pCandidateStrictlyImproves(
+ current,
+ metrics(2_100, {
+ frameWidth: 1_280,
+ frameHeight: 720,
+ framesPerSecond: 5,
+ }),
+ ),
+ ).toBe(false);
+ expect(
+ p2pCandidateStrictlyImproves(
+ current,
+ metrics(2_100, { intervalFreezeCount: 1 }),
+ ),
+ ).toBe(false);
+ });
+
+ it("requires three consecutive strict P2P improvements", () => {
+ const probe = new P2pQualityProbe();
+ const current = (timestampMs: number) =>
+ metrics(timestampMs, {
+ frameWidth: 320,
+ frameHeight: 180,
+ framesPerSecond: 10,
+ });
+ const candidate = (timestampMs: number) =>
+ metrics(timestampMs, {
+ frameWidth: 1_280,
+ frameHeight: 720,
+ framesPerSecond: 30,
+ });
+ expect(probe.observe(current(1_000), candidate(1_100))).toBe(false);
+ expect(probe.observe(current(3_000), candidate(3_100))).toBe(false);
+ expect(probe.observe(current(5_000), candidate(5_100))).toBe(true);
+ probe.reset();
+ expect(probe.observe(current(7_000), candidate(7_100))).toBe(false);
});
it("requires three consecutive windows and resets after a regression", () => {
diff --git a/tests/connection-details.test.ts b/tests/connection-details.test.ts
index 53d48910..5f0ddccf 100644
--- a/tests/connection-details.test.ts
+++ b/tests/connection-details.test.ts
@@ -23,10 +23,10 @@ describe("progressive connection details", () => {
expect(
qualityLimitationSummary([
snapshot(null),
- snapshot("持续受带宽限制,浏览器正在降低画面质量"),
- snapshot("持续受编码性能限制,浏览器正在降低画面质量"),
+ snapshot("此发送连接持续按带宽估计降低分辨率或帧率"),
+ snapshot("此发送连接持续因编码性能降低分辨率或帧率"),
]),
- ).toBe("持续受带宽限制,浏览器正在降低画面质量");
+ ).toBe("此发送连接持续按带宽估计降低分辨率或帧率");
expect(qualityLimitationSummary([snapshot(null)])).toBeNull();
});
diff --git a/tests/host-peer-tracks.test.ts b/tests/host-peer-tracks.test.ts
index d9032a2a..8743afc5 100644
--- a/tests/host-peer-tracks.test.ts
+++ b/tests/host-peer-tracks.test.ts
@@ -1379,7 +1379,7 @@ describe("HostPeer source replacement", () => {
await sample();
expect(updates.at(-1)?.qualityWarning).toBeNull();
await sample();
- expect(updates.at(-1)?.qualityWarning).toContain("持续受带宽限制");
+ expect(updates.at(-1)?.qualityWarning).toContain("按带宽估计");
expect(sender.setParameters).toHaveBeenCalledTimes(2);
await sample();
diff --git a/tests/hybrid-media-router.test.ts b/tests/hybrid-media-router.test.ts
index 9241b916..31f8d0d6 100644
--- a/tests/hybrid-media-router.test.ts
+++ b/tests/hybrid-media-router.test.ts
@@ -218,7 +218,7 @@ async function establishSfuRoom(
}
describe("HybridMediaRouter v9 runtime", () => {
- it("commits topology convergence only after candidate media and native health", async () => {
+ it("commits P2P quality convergence after client relative approval", async () => {
const { store, sent, router } = harness(2);
try {
const room = await store.createRoom();
@@ -309,25 +309,15 @@ describe("HybridMediaRouter v9 runtime", () => {
expect(
router.resolveActiveViewerMediaEdge(room.roomId, first.peerId)?.upstream,
).toEqual({ kind: "peer", peerId: host.peerId });
-
+ router.handleRouteReady(first, {
+ type: "route-ready",
+ revision: qualityPrepare.revision,
+ phase: "prepare",
+ qualityApproved: true,
+ });
expect(
- router.observeSenderQualityEvidence(second, {
- type: "sender-quality-evidence",
- childPeerId: first.peerId,
- connectionId: qualityPrepare.candidate.connectionId,
- rtpStatsId: "candidate-rtp",
- trackIdentifier: "track",
- sampleTimestampMs: 200,
- routeRevision: qualityPrepare.revision,
- state: "healthy",
- diagnostics: senderDiagnostics("healthy"),
- }),
- ).toBe(true);
- await vi.waitFor(() =>
- expect(
- router.resolveActiveViewerMediaEdge(room.roomId, first.peerId)?.upstream,
- ).toEqual({ kind: "peer", peerId: second.peerId }),
- );
+ router.resolveActiveViewerMediaEdge(room.roomId, first.peerId)?.upstream,
+ ).toEqual({ kind: "peer", peerId: second.peerId });
} finally {
await router.close();
}
@@ -1240,7 +1230,7 @@ describe("HybridMediaRouter v9 runtime", () => {
?.filter((message) => message.type === "sfu-config").length ?? 0;
const initialCount = configCount();
- router.refreshSfu(first, active!.revision);
+ router.refreshSfu(first, 0);
await vi.waitFor(() => expect(configCount()).toBe(initialCount + 1));
router.refreshSfu(first, active!.revision);
await vi.waitFor(() => expect(configCount()).toBe(initialCount + 2));
diff --git a/tests/protocol.test.ts b/tests/protocol.test.ts
index 896619bd..19581863 100644
--- a/tests/protocol.test.ts
+++ b/tests/protocol.test.ts
@@ -939,6 +939,22 @@ describe("client signaling protocol", () => {
phase: "prepare",
}).success,
).toBe(true);
+ expect(
+ clientMessageSchema.safeParse({
+ type: "route-ready",
+ revision: 7,
+ phase: "prepare",
+ qualityApproved: true,
+ }).success,
+ ).toBe(true);
+ expect(
+ clientMessageSchema.safeParse({
+ type: "route-ready",
+ revision: 7,
+ phase: "prepare",
+ qualityApproved: false,
+ }).success,
+ ).toBe(false);
expect(
clientMessageSchema.safeParse({
type: "route-transport-connected",
diff --git a/tests/room-route-controller.test.ts b/tests/room-route-controller.test.ts
index 5c4a53ca..3c5a1385 100644
--- a/tests/room-route-controller.test.ts
+++ b/tests/room-route-controller.test.ts
@@ -323,7 +323,7 @@ describe("RoomRouteController", () => {
});
});
- it("keeps the old edge until one native-healthy quality candidate commits", () => {
+ it("commits only after the Viewer approves a P2P receive improvement", () => {
const routes = controller(2, { qualityConvergenceEnabled: true });
addViewer(routes, A, 2);
addViewer(routes, B, 2);
@@ -358,29 +358,19 @@ describe("RoomRouteController", () => {
revision: current.revision,
connectionId: "a_from_b",
};
- expect(routes.candidateReady(guard, 105)).toMatchObject({
- accepted: true,
- committed: false,
- });
expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
kind: "peer",
parentPeerId: HOST,
connectionId: "a_from_host",
});
-
expect(
- routes.observeSenderQualityEvidence({
- parentPeerId: B,
- parentSessionId: `${B}_session`,
- childPeerId: A,
- routeRevision: current.revision,
- connectionId: "a_from_b",
- senderIdentity: "a-from-b-rtp\u0000a-track",
- sampleTimestampMs: 106,
- state: "healthy",
- acceptedAtMs: 106,
- }).committed,
- ).toBe(true);
+ routes.candidateReady(guard, 105, undefined, {
+ relativeQualityApproved: true,
+ }),
+ ).toMatchObject({
+ accepted: true,
+ committed: true,
+ });
expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
kind: "peer",
parentPeerId: B,
@@ -591,7 +581,7 @@ describe("RoomRouteController", () => {
expect(routes.routeDiagnosticSnapshot(7_301).children[0]?.quality).toBeNull();
});
- it("commits when native health arrives before candidate media", () => {
+ it("does not require a P2P candidate sender category after client approval", () => {
const routes = controller(2, { qualityConvergenceEnabled: true });
addViewer(routes, A, 2);
addViewer(routes, B, 2);
@@ -613,6 +603,17 @@ describe("RoomRouteController", () => {
reservation: { kind: "direct" },
});
const current = begin.operation!.current!;
+ expect(
+ routes.candidateTransportConnected(
+ {
+ childPeerId: A,
+ childSessionId: `${A}_session`,
+ revision: current.revision,
+ connectionId: "a_from_b",
+ },
+ 105,
+ ).accepted,
+ ).toBe(true);
expect(
routes.observeSenderQualityEvidence({
parentPeerId: B,
@@ -622,9 +623,9 @@ describe("RoomRouteController", () => {
connectionId: "a_from_b",
senderIdentity: "a-from-b-rtp\u0000track",
sampleTimestampMs: 105,
- state: "healthy",
+ state: "degraded",
acceptedAtMs: 105,
- }).committed,
+ }).accepted,
).toBe(false);
expect(
routes.candidateReady(
@@ -635,11 +636,13 @@ describe("RoomRouteController", () => {
connectionId: "a_from_b",
},
106,
+ undefined,
+ { relativeQualityApproved: true },
).committed,
).toBe(true);
});
- it("rejects a candidate whose sender identity changes during proof", () => {
+ it("leaves P2P candidate sender identity out of relative approval", () => {
const routes = controller(2, { qualityConvergenceEnabled: true });
addViewer(routes, A, 2);
addViewer(routes, B, 2);
@@ -672,15 +675,28 @@ describe("RoomRouteController", () => {
acceptedAtMs: sampleTimestampMs,
});
expect(candidateEvidence("candidate-rtp-1\u0000track", 105).accepted).toBe(
- true,
+ false,
);
- expect(candidateEvidence("candidate-rtp-2\u0000track", 106).committed).toBe(
+ expect(candidateEvidence("candidate-rtp-2\u0000track", 106).accepted).toBe(
false,
);
+ expect(
+ routes.candidateReady(
+ {
+ childPeerId: A,
+ childSessionId: `${A}_session`,
+ revision: current.revision,
+ connectionId: "a_from_b",
+ },
+ 107,
+ undefined,
+ { relativeQualityApproved: true },
+ ).committed,
+ ).toBe(true);
expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
kind: "peer",
- parentPeerId: HOST,
- connectionId: "a_from_host",
+ parentPeerId: B,
+ connectionId: "a_from_b",
});
});
@@ -722,34 +738,25 @@ describe("RoomRouteController", () => {
});
});
- it("reconsiders an exhausted edge when an existing parent becomes healthy", () => {
+ it("keeps a usable parent eligible before native state becomes clear", () => {
const routes = controller(2, { qualityConvergenceEnabled: true });
addViewer(routes, A, 2);
addViewer(routes, B, 2);
routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));
routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));
observePersistentDegraded(routes, A, "a_from_host", 99);
- expect(routes.reconcile(103).operation).toBeUndefined();
- expect(
- routes.observeSenderQualityEvidence({
- parentPeerId: HOST,
- parentSessionId: "host_session",
- childPeerId: B,
- routeRevision: routes.snapshot().revision,
- connectionId: "b_from_host",
- senderIdentity: "b-rtp\u0000track",
- sampleTimestampMs: 104,
- state: "healthy",
- acceptedAtMs: 104,
- }).accepted,
- ).toBe(true);
- expect(routes.reconcile(105).operation).toMatchObject({
+ expect(routes.reconcile(103).operation).toMatchObject({
childPeerId: A,
reason: "quality-convergence",
+ candidates: [
+ {
+ tuple: { kind: "peer", parentPeerId: B, transport: "direct" },
+ },
+ ],
});
});
- it("rejects stale candidate proof and a parent whose source degrades", () => {
+ it("uses client relative proof even when candidate native state is limited", () => {
const routes = controller(2, { qualityConvergenceEnabled: true });
addViewer(routes, A, 2);
addViewer(routes, B, 2);
@@ -788,98 +795,61 @@ describe("RoomRouteController", () => {
true,
);
routes.reconcile(103);
- let begin = beginCandidate(routes, {
+ const begin = beginCandidate(routes, {
nowMs: 104,
connectionId: "a_from_b_stale",
reservation: { kind: "direct" },
});
- let current = begin.operation!.current!;
- expect(
- routes.observeSenderQualityEvidence({
- parentPeerId: B,
- parentSessionId: `${B}_session`,
- childPeerId: A,
- routeRevision: current.revision,
- connectionId: "a_from_b_stale",
- senderIdentity: "a-stale-rtp\u0000a-track",
- sampleTimestampMs: 104,
- state: "healthy",
- acceptedAtMs: 104,
- }).accepted,
- ).toBe(true);
- expect(observeCurrent(A, "a_from_host", "degraded", 5_103).accepted).toBe(
- true,
- );
+ const current = begin.operation!.current!;
expect(
- routes.candidateReady(
+ routes.candidateTransportConnected(
{
childPeerId: A,
childSessionId: `${A}_session`,
revision: current.revision,
connectionId: "a_from_b_stale",
},
- 5_104,
- ).committed,
- ).not.toBe(true);
- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
- parentPeerId: HOST,
- });
-
- expect(observeCurrent(A, "a_from_host", "healthy", 5_200).accepted).toBe(
- true,
- );
- expect(observeCurrent(A, "a_from_host", "degraded", 5_201).accepted).toBe(
- true,
- );
- expect(observeCurrent(A, "a_from_host", "degraded", 5_202).accepted).toBe(
- true,
- );
- expect(observeCurrent(A, "a_from_host", "degraded", 5_203).accepted).toBe(
- true,
- );
- expect(observeCurrent(B, "b_from_host", "healthy", 5_203).accepted).toBe(
- true,
- );
- routes.reconcile(5_204);
- begin = beginCandidate(routes, {
- nowMs: 5_205,
- connectionId: "a_from_b_bad_source",
- reservation: { kind: "direct" },
- });
- current = begin.operation!.current!;
+ 105,
+ ).accepted,
+ ).toBe(true);
expect(
routes.observeSenderQualityEvidence({
parentPeerId: B,
parentSessionId: `${B}_session`,
childPeerId: A,
routeRevision: current.revision,
- connectionId: "a_from_b_bad_source",
- senderIdentity: "a-bad-source-rtp\u0000a-track",
- sampleTimestampMs: 5_206,
+ connectionId: "a_from_b_stale",
+ senderIdentity: "a-stale-rtp\u0000a-track",
+ sampleTimestampMs: 104,
state: "healthy",
- acceptedAtMs: 5_206,
+ acceptedAtMs: 104,
}).accepted,
- ).toBe(true);
- expect(observeCurrent(B, "b_from_host", "degraded", 5_207).accepted).toBe(
- true,
- );
+ ).toBe(false);
+ for (const acceptedAtMs of [5_101, 5_102, 5_103]) {
+ expect(
+ observeCurrent(A, "a_from_host", "degraded", acceptedAtMs).accepted,
+ ).toBe(true);
+ }
expect(
routes.candidateReady(
{
childPeerId: A,
childSessionId: `${A}_session`,
revision: current.revision,
- connectionId: "a_from_b_bad_source",
+ connectionId: "a_from_b_stale",
},
- 5_208,
+ 5_104,
+ undefined,
+ { relativeQualityApproved: true },
).committed,
- ).not.toBe(true);
+ ).toBe(true);
expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
- parentPeerId: HOST,
+ parentPeerId: B,
+ connectionId: "a_from_b_stale",
});
});
- it("consumes a candidate whose source expires before begin", () => {
+ it("keeps a usable candidate when its native source category expires", () => {
const routes = controller(2, { qualityConvergenceEnabled: true });
addViewer(routes, A, 2);
addViewer(routes, B, 2);
@@ -899,29 +869,47 @@ describe("RoomRouteController", () => {
reservation: { kind: "direct" },
});
expect(begin.accepted).toBe(true);
- expect(begin.operation).toBeUndefined();
- expect(routes.snapshot().operation).toBeUndefined();
+ expect(begin.operation?.current?.connectionId).toBe("expired_candidate");
});
- it("uses bounded SFU only when every Host root is persistently degraded", () => {
+ it("keeps bounded SFU after direct candidates when every Host root is degraded", () => {
const routes = controller(2, {
sfuEnabled: true,
qualityConvergenceEnabled: true,
});
addViewer(routes, A, 1);
- addViewer(routes, B, 1);
+ addViewer(routes, B, 0);
routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));
routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));
observePersistentDegraded(routes, A, "a_from_host", 99);
expect(routes.reconcile(103).operation).toBeUndefined();
observePersistentDegraded(routes, B, "b_from_host", 104);
const operation = routes.reconcile(108).operation!;
+ const childPeerId = operation.childPeerId;
expect(operation.candidates.map((candidate) => candidate.tuple)).toEqual([
+ { kind: "peer", parentPeerId: A, transport: "direct" },
{ kind: "sfu", publication: "create" },
]);
- const begin = beginCandidate(routes, {
+ const direct = beginCandidate(routes, {
nowMs: 109,
- connectionId: "a_from_sfu",
+ connectionId: "quality_peer_candidate",
+ reservation: { kind: "direct" },
+ }).operation!;
+ expect(
+ routes.candidateFailed(
+ {
+ childPeerId,
+ childSessionId: `${childPeerId}_session`,
+ revision: direct.current!.revision,
+ connectionId: "quality_peer_candidate",
+ },
+ 110,
+ ),
+ ).toMatchObject({ accepted: true, failedPeerIds: [] });
+
+ const begin = beginCandidate(routes, {
+ nowMs: 111,
+ connectionId: "quality_sfu_candidate",
reservation: {
kind: "sfu-create",
edge: "sfu-edge",
@@ -936,12 +924,12 @@ describe("RoomRouteController", () => {
expect(
routes.candidateReady(
{
- childPeerId: A,
- childSessionId: `${A}_session`,
+ childPeerId,
+ childSessionId: `${childPeerId}_session`,
revision: current.revision,
- connectionId: "a_from_sfu",
+ connectionId: "quality_sfu_candidate",
},
- 110,
+ 112,
),
).toMatchObject({ accepted: true, committed: false });
expect(
@@ -949,12 +937,12 @@ describe("RoomRouteController", () => {
routes,
"publication_generation_12345678",
current.revision,
- 111,
+ 113,
).committed,
).toBe(true);
- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
+ expect(routes.snapshot().upstreamByViewer.get(childPeerId)).toMatchObject({
kind: "sfu",
- connectionId: "a_from_sfu",
+ connectionId: "quality_sfu_candidate",
});
});
@@ -964,7 +952,7 @@ describe("RoomRouteController", () => {
qualityConvergenceEnabled: true,
});
addViewer(routes, A, 1);
- addViewer(routes, B, 1);
+ addViewer(routes, B, 0);
routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));
routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));
observePersistentDegraded(routes, A, "a_from_host", 99);
@@ -1016,8 +1004,8 @@ describe("RoomRouteController", () => {
sfuEnabled: true,
qualityConvergenceEnabled: true,
});
- addViewer(routes, A, 1);
- addViewer(routes, B, 1);
+ addViewer(routes, A, 0);
+ addViewer(routes, B, 0);
routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));
routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));
routes.hydrateHostPublication(
diff --git a/tests/route-transition.test.ts b/tests/route-transition.test.ts
index 056c9eae..50fe5adf 100644
--- a/tests/route-transition.test.ts
+++ b/tests/route-transition.test.ts
@@ -724,6 +724,135 @@ describe("minimal route transition contracts", () => {
await route.disconnect();
});
+ it("keeps an active SFU subscriber across same-publication resync", async () => {
+ const subscribers: ReturnType<typeof createFakeSubscriber>[] = [];
+ const streams: MediaStream[] = [];
+ const resetMedia = vi.fn();
+ const route = new ViewerSfuRoute("viewer_12345678", {
+ activatePeer: () => true,
+ resetMedia,
+ reconcileSfuChildren: () => undefined,
+ onSfuStream: (stream) => streams.push(stream),
+ send: () => true,
+ createSubscriber: (events) => {
+ const subscriber = createFakeSubscriber(events, [], "active");
+ subscribers.push(subscriber);
+ return subscriber;
+ },
+ });
+ const assignment = viewerSfuAssignment();
+ route.accept({ revision: 7, phase: "active", assignment });
+ await route.acceptConfig(sfuConfig(7));
+ const initialStream = {} as MediaStream;
+ subscribers[0]?.events.onStream(initialStream);
+ subscribers[0]?.events.onFirstDecodedFrame();
+ await vi.waitFor(() => expect(streams).toEqual([initialStream]));
+
+ await expect(
+ route.resyncAuthoritative(
+ { revision: 8, phase: "active", assignment },
+ "viewer_12345678",
+ ),
+ ).resolves.toBe("accepted");
+ expect(subscribers).toHaveLength(1);
+ expect(subscribers[0]?.deactivate).not.toHaveBeenCalled();
+ expect(subscribers[0]?.disconnect).not.toHaveBeenCalled();
+ expect(resetMedia).not.toHaveBeenCalled();
+ await route.disconnect();
+ });
+
+ it("retargets manual SFU recovery after an unrelated room revision", async () => {
+ const messages: ClientMessage[] = [];
+ const subscribers: ReturnType<typeof createFakeSubscriber>[] = [];
+ const streams: MediaStream[] = [];
+ const route = new ViewerSfuRoute("viewer_12345678", {
+ activatePeer: () => true,
+ reconcileSfuChildren: () => undefined,
+ onSfuStream: (stream) => streams.push(stream),
+ send: (message) => {
+ messages.push(message);
+ return true;
+ },
+ createSubscriber: (events) => {
+ const subscriber = createFakeSubscriber(events, [], "active");
+ subscribers.push(subscriber);
+ return subscriber;
+ },
+ });
+ const assignment = viewerSfuAssignment();
+ route.accept({ revision: 7, phase: "active", assignment });
+ await route.acceptConfig(sfuConfig(7));
+ const initialStream = {} as MediaStream;
+ subscribers[0]?.events.onStream(initialStream);
+ subscribers[0]?.events.onFirstDecodedFrame();
+ await vi.waitFor(() => expect(streams).toEqual([initialStream]));
+ messages.length = 0;
+ expect(route.reconnectActive()).toBe(true);
+
+ route.accept({ revision: 8, phase: "active", assignment });
+ await vi.waitFor(() =>
+ expect(
+ messages.filter((message) => message.type === "refresh-sfu"),
+ ).toEqual([
+ { type: "refresh-sfu", revision: 7 },
+ { type: "refresh-sfu", revision: 8 },
+ ]),
+ );
+ expect(subscribers[0]?.disconnect).not.toHaveBeenCalled();
+ await route.disconnect();
+ });
+
+ it("keeps an in-flight SFU recovery across an unrelated room revision", async () => {
+ let releaseRecovery!: (connected: boolean) => void;
+ const recoveryConnected = new Promise<boolean>((resolve) => {
+ releaseRecovery = resolve;
+ });
+ const subscribers: ReturnType<typeof createFakeSubscriber>[] = [];
+ const streams: MediaStream[] = [];
+ const route = new ViewerSfuRoute("viewer_12345678", {
+ activatePeer: () => true,
+ reconcileSfuChildren: () => undefined,
+ onSfuStream: (stream) => streams.push(stream),
+ send: () => true,
+ createSubscriber: (events) => {
+ const subscriber = createFakeSubscriber(events, [], "subscriber");
+ if (subscribers.length === 1) {
+ subscriber.connect.mockImplementation(() => recoveryConnected);
+ }
+ subscribers.push(subscriber);
+ return subscriber;
+ },
+ });
+ const assignment = viewerSfuAssignment();
+ route.accept({ revision: 7, phase: "active", assignment });
+ await route.acceptConfig(sfuConfig(7));
+ const initialStream = {} as MediaStream;
+ subscribers[0]?.events.onStream(initialStream);
+ subscribers[0]?.events.onFirstDecodedFrame();
+ await vi.waitFor(() => expect(streams).toEqual([initialStream]));
+
+ expect(route.reconnectActive()).toBe(true);
+ const recovery = route.acceptConfig({
+ ...sfuConfig(7),
+ token: "recovery-token",
+ });
+ await vi.waitFor(() => expect(subscribers).toHaveLength(2));
+ route.accept({ revision: 8, phase: "active", assignment });
+ expect(subscribers).toHaveLength(2);
+ expect(subscribers[1]?.disconnect).not.toHaveBeenCalled();
+
+ releaseRecovery(true);
+ await recovery;
+ const recoveredStream = {} as MediaStream;
+ subscribers[1]?.events.onStream(recoveredStream);
+ subscribers[1]?.events.onFirstDecodedFrame();
+ await vi.waitFor(() =>
+ expect(streams).toEqual([initialStream, recoveredStream]),
+ );
+ expect(subscribers[0]?.disconnect).toHaveBeenCalledOnce();
+ await route.disconnect();
+ });
+
it("discards a paused pending subscriber and ignores its later evidence", async () => {
const messages: ClientMessage[] = [];
let subscriber!: ReturnType<typeof createFakeSubscriber>;
diff --git a/tests/viewer-presentation.test.ts b/tests/viewer-presentation.test.ts
index c9005e1d..ae0a2245 100644
--- a/tests/viewer-presentation.test.ts
+++ b/tests/viewer-presentation.test.ts
@@ -52,6 +52,7 @@ describe("Viewer presentation reducer", () => {
stage: "playing",
overlay: "none",
hasCurrentFrame: true,
+ connectionState: "connected",
});
});
@@ -125,7 +126,7 @@ describe("Viewer presentation reducer", () => {
expect(nextRoute.connection).toBe("connecting");
});
- it("rebases proven media when only the room graph revision changes", () => {
+ it("keeps proven media independent of room graph revision changes", () => {
const playing = apply(
{ type: "access", access: "ready" },
{ type: "signal", signal: "connected" },
@@ -140,12 +141,11 @@ describe("Viewer presentation reducer", () => {
revision: 3,
phase: "active",
kind: "p2p",
- preserveMedia: true,
});
expect(rebased.media).toEqual({
generation: 4,
- revision: 3,
+ boundAtRevision: 2,
framePresented: true,
});
expect(rebased.connection).toBe("connected");
@@ -174,7 +174,7 @@ describe("Viewer presentation reducer", () => {
expect(deriveViewerPresentation(staleFailure).stage).toBe("receiving");
});
- it("ignores late playback results from a retained older route revision", () => {
+ it("keeps playback authority with the bound media generation", () => {
const oldMedia = apply(
{ type: "access", access: "ready" },
{ type: "host", host: "online" },
@@ -200,15 +200,18 @@ describe("Viewer presentation reducer", () => {
revision: 5,
});
- expect(staleAutoplay).toBe(preparing);
- expect(staleFailure).toBe(preparing);
+ expect(staleAutoplay).toMatchObject({
+ autoplayBlockedGeneration: 5,
+ failure: "AUTOPLAY_BLOCKED",
+ });
+ expect(staleFailure).toMatchObject({ failure: "PLAYBACK_FAILED" });
expect(deriveViewerPresentation(preparing)).toMatchObject({
- stage: "preparing-sfu",
- overlay: "status",
+ stage: "playing",
+ overlay: "none",
});
});
- it("clears autoplay authority when the route revision advances", () => {
+ it("retains autoplay authority until the media generation changes", () => {
const blocked = apply(
{ type: "access", access: "ready" },
{ type: "host", host: "online" },
@@ -223,14 +226,14 @@ describe("Viewer presentation reducer", () => {
kind: "sfu",
});
- expect(preparing.autoplayBlockedGeneration).toBeNull();
- expect(preparing.failure).toBeNull();
+ expect(preparing.autoplayBlockedGeneration).toBe(5);
+ expect(preparing.failure).toBe("AUTOPLAY_BLOCKED");
expect(deriveViewerPresentation(preparing)).toMatchObject({
- stage: "preparing-sfu",
+ stage: "receiving",
});
});
- it("keeps a proven old frame through recovery without accepting stale proof", () => {
+ it("keeps a proven frame until a replacement media generation binds", () => {
const oldFrame = apply(
{ type: "access", access: "ready" },
{ type: "host", host: "online" },
@@ -245,18 +248,20 @@ describe("Viewer presentation reducer", () => {
kind: "sfu",
});
expect(deriveViewerPresentation(recovering)).toMatchObject({
- stage: "preparing-sfu",
- overlay: "status",
- hasCurrentFrame: false,
- hasRetainedFrame: true,
+ stage: "playing",
+ overlay: "none",
+ hasCurrentFrame: true,
+ hasRetainedFrame: false,
});
- const staleProof = reduceViewerPresentation(recovering, {
+ const continuingProof = reduceViewerPresentation(recovering, {
type: "frame-presented",
generation: 5,
revision: 5,
});
- expect(staleProof).toBe(recovering);
+ expect(continuingProof).toMatchObject({
+ media: { generation: 5, framePresented: true },
+ });
const rebound = reduceViewerPresentation(recovering, {
type: "media-bound",
@@ -315,6 +320,60 @@ describe("Viewer presentation reducer", () => {
});
});
+ it("re-arms current media when active authority returns after route failure", () => {
+ const failed = apply(
+ { type: "access", access: "ready" },
+ { type: "signal", signal: "connected" },
+ { type: "host", host: "online" },
+ { type: "route", revision: 3, phase: "active", kind: "sfu" },
+ { type: "media-bound", generation: 2, revision: 3 },
+ { type: "frame-presented", generation: 2, revision: 3 },
+ { type: "route-status", revision: 3, state: "failed" },
+ );
+ const recovering = reduceViewerPresentation(failed, {
+ type: "route",
+ revision: 4,
+ phase: "active",
+ kind: "sfu",
+ });
+ expect(recovering).toMatchObject({
+ connection: "reconnecting",
+ routeStatus: null,
+ failure: null,
+ media: { generation: 2, framePresented: false },
+ });
+
+ const resumed = reduceViewerPresentation(recovering, {
+ type: "frame-presented",
+ generation: 2,
+ revision: 3,
+ });
+ expect(resumed.connection).toBe("connected");
+ expect(deriveViewerPresentation(resumed)).toMatchObject({
+ stage: "playing",
+ overlay: "none",
+ });
+ });
+
+ it("keeps a browser playback failure across unrelated active authority", () => {
+ const failed = apply(
+ { type: "access", access: "ready" },
+ { type: "host", host: "online" },
+ { type: "route", revision: 3, phase: "active", kind: "sfu" },
+ { type: "media-bound", generation: 2, revision: 3 },
+ { type: "playback-failed", generation: 2, revision: 3 },
+ );
+ const rebased = reduceViewerPresentation(failed, {
+ type: "route",
+ revision: 4,
+ phase: "active",
+ kind: "sfu",
+ });
+
+ expect(rebased.failure).toBe("PLAYBACK_FAILED");
+ expect(deriveViewerPresentation(rebased).stage).toBe("playback-failed");
+ });
+
it("keeps a healthy Host-offline frame but invalidates it on upstream failure", () => {
const offlineWithMedia = apply(
{ type: "access", access: "ready" },
@@ -436,6 +495,7 @@ describe("Viewer presentation reducer", () => {
hasCurrentFrame: false,
hasRetainedFrame: true,
failureCode: "ROUTE_EXHAUSTED",
+ connectionState: "failed",
});
const lateFrame = reduceViewerPresentation(failed, {
@@ -451,14 +511,21 @@ describe("Viewer presentation reducer", () => {
revision: 4,
}),
).toBe(failed);
+ const restored = reduceViewerPresentation(failed, {
+ type: "route",
+ revision: 4,
+ phase: "active",
+ kind: "sfu",
+ });
+ expect(restored.routeStatus).toBeNull();
+ expect(restored.failure).toBeNull();
expect(
- reduceViewerPresentation(failed, {
- type: "route",
+ reduceViewerPresentation(restored, {
+ type: "frame-presented",
+ generation: 3,
revision: 4,
- phase: "active",
- kind: "sfu",
- }).routeStatus,
- ).toEqual({ revision: 4, state: "failed" });
+ }).media?.framePresented,
+ ).toBe(true);
const localFailure = reduceViewerPresentation(playing, {
type: "failure",