Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
import type {
ClientMessage,
MediaRoutePhase,
ParticipantRouteAssignment,
PreparedRouteCandidate,
ServerMessage,
SfuSignalMessage,
} from "../../shared/protocol";
import { SfuSubscriber } from "../sfu/subscriber";
import type { ConnectionMetrics } from "../types";
import type { SfuConnectionConfig } from "../sfu/publisher";
import {
SfuQualityProbe,
type CandidateQualityProbeResult,
} from "./candidate-quality-probe";
import {
MediaRouteTransition,
reportActivePeerRouteFailure,
type RouteOperationToken,
type RouteUpdateInput,
type RouteUpdateResult,
} from "./route-transition";
interface ViewerSubscriberTransport {
getRemoteInput?(): RTCDataChannel | null;
connect(config: SfuConnectionConfig): Promise<boolean>;
updateConfig(config: SfuConnectionConfig): void;
isConnected(): boolean;
acceptSignal(message: SfuSignalMessage): Promise<void>;
reconnect(): boolean;
resync(): void;
activate(): boolean;
deactivate(): boolean;
armDecodedFrameProof(requireProgress?: boolean): void;
stopDecodedFrameProof(): void;
disconnect(): Promise<void>;
}
interface ViewerSubscriberSlot {
connectionId: string;
revision: number;
publicationGeneration: string;
subscriber: ViewerSubscriberTransport;
connected: boolean;
activated: boolean;
stream: MediaStream | null;
decodedFrame: boolean;
readySent: boolean;
qualityProbe: SfuQualityProbe | null;
qualityResult: CandidateQualityProbeResult;
failed: boolean;
activationToken: RouteOperationToken | null;
}
interface ViewerSfuRouteEvents {
onInputChanged?: () => void;
activatePeer: (
assignment: ParticipantRouteAssignment,
revision?: number,
) => boolean | "waiting" | void | Promise<boolean | "waiting" | void>;
preparePeer?: (
assignment: ParticipantRouteAssignment | null,
revision?: number,
candidate?: PreparedRouteCandidate,
) => void;
prepareChild?: (
candidate: PreparedRouteCandidate | null,
childPeerIds?: readonly string[],
revision?: number,
) => void;
activateChildren?: (
childPeerIds: readonly string[],
revision: number,
) => void;
resetMedia?: () => void;
reconcileSfuChildren?: (childPeerIds: string[]) => void;
onSfuStream: (
stream: MediaStream,
assignment: ParticipantRouteAssignment,
initialVideoStream: boolean,
revision: number,
) => void;
onSfuVideoAvailability?: (available: boolean, revision: number) => void;
onSfuUpdate?: (metrics: ConnectionMetrics | null, revision: number) => void;
currentPeerMetrics?: () => ConnectionMetrics | null;
qualityProbeEligible?: () => boolean;
onSfuState?: (
state: "connected" | "reconnecting",
revision: number,
) => void;
onSfuFailure?: (failure: "VIDEO_REJECTED" | null, revision: number) => void;
send: (message: ClientMessage) => boolean;
createSubscriber?: (
events: {
onStream: (stream: MediaStream | null) => void;
onVideoAvailability: (available: boolean) => void;
onStats: (metrics: ConnectionMetrics) => void;
onFirstDecodedFrame: () => boolean;
onState: (state: "connected" | "reconnecting") => void;
onDisconnected: (failure?: "VIDEO_REJECTED") => void;
},
) => ViewerSubscriberTransport;
}
export class ViewerSfuRoute {
getRemoteInput(): RTCDataChannel | null { return this.active?.subscriber.getRemoteInput?.() ?? null; }
private readonly route = new MediaRouteTransition();
private pending: ViewerSubscriberSlot | null = null;
private active: ViewerSubscriberSlot | null = null;
private pendingPeer: {
revision: number;
connectionId: string;
activationToken: RouteOperationToken | null;
} | null = null;
private transitionTail: Promise<void> = Promise.resolve();
private resyncGeneration = 0;
private resyncing = false;
private paused = false;
private closed = false;
constructor(
private viewerPeerId: string,
private readonly events: ViewerSfuRouteEvents,
) {}
accept(update: RouteUpdateInput, acknowledge = true): RouteUpdateResult {
if (this.closed) {
return "stale";
}
const previousActiveAssignment = this.route.getActiveAssignment();
const result = this.route.accept(update);
if (result === "stale") {
return result;
}
if (this.active) {
this.active.subscriber.updateConfig({ ...this.active, revision: update.revision });
}
const pausedActiveReconciliation =
this.paused && update.phase === "active" && result !== "duplicate";
const retiredActive = pausedActiveReconciliation
? this.detachUnreferencedActive(update.assignment)
: null;
// Committed child permissions cannot wait for unrelated upstream SDP.
if (update.phase === "active" && result !== "duplicate") {
this.activateChildren(update.assignment.childPeerIds, update.revision);
}
if (this.paused && update.phase === "prepare") {
this.discardPending();
return result;
}
if (result === "duplicate") {
return result;
}
if (retiredActive) {
void this.queueTransition(() =>
this.disconnectRetiredSubscriber(retiredActive),
);
}
if (update.phase === "active") {
const token = this.route.getActiveToken()!;
if (this.pendingPeer) {
if (update.assignment.upstream.kind === "peer" &&
(this.pendingPeer.revision === update.revision ||
(this.pendingPeer.activationToken && sameUpstream(previousActiveAssignment, update.assignment)))) {
this.pendingPeer.activationToken = token;
} else {
this.pendingPeer = null;
this.events.preparePeer?.(null);
}
}
if (this.pending) {
if (update.assignment.upstream.kind === "sfu" &&
this.pending.publicationGeneration === update.assignment.sfuPublicationGeneration &&
(this.pending.revision === update.revision || this.pending.activationToken)) {
this.pending.activationToken = token;
this.pending.revision = update.revision;
this.pending.subscriber.updateConfig(this.pending);
} else {
this.clearPending();
}
}
}
if (update.phase === "prepare") {
const candidate = update.candidate;
const ownsUpstreamCandidate = candidate.childPeerId === this.viewerPeerId;
const ownsChildCandidate =
candidate.transport !== "sfu" &&
update.assignment.childPeerIds.includes(candidate.childPeerId);
this.events.prepareChild?.(
ownsChildCandidate ? candidate : null,
ownsChildCandidate ? update.assignment.childPeerIds : undefined,
ownsChildCandidate ? update.revision : undefined,
);
if (!ownsUpstreamCandidate) {
// A child operation cannot retire an incoming resource already committed
// by the server, even while its local activation is still queued.
if (this.pendingPeer && !this.pendingPeer.activationToken) {
this.pendingPeer = null;
this.events.preparePeer?.(null);
}
if (this.pending && !this.pending.activationToken) this.clearPending();
return result;
}
const replacedPeerCandidate = this.pendingPeer !== null;
if (replacedPeerCandidate) {
this.events.preparePeer?.(null);
this.pendingPeer = null;
}
const needsPeerCandidate =
candidate.transport !== "sfu" &&
update.assignment.upstream.kind === "peer" &&
candidate.connectionId.length > 0;
if (needsPeerCandidate && update.assignment.upstream.kind === "peer") {
this.pendingPeer = {
revision: update.revision,
connectionId: candidate.connectionId,
activationToken: null,
};
this.events.preparePeer?.(update.assignment, update.revision, candidate);
} else if (update.assignment.upstream.kind !== "peer" && !replacedPeerCandidate) {
this.events.preparePeer?.(null);
}
if (this.pending?.revision !== update.revision) {
this.clearPending();
}
if (
candidate.transport !== "sfu" ||
update.assignment.upstream.kind !== "sfu"
) {
this.clearPending();
}
return result;
}
const token = this.route.getActiveToken();
if (!token) {
return result;
}
if (!this.pendingPeer) {
this.preparePeer(update.assignment);
}
if (this.resyncing) {
return result;
}
void this.queueActiveRoute(token, acknowledge, this.paused);
return result;
}
setPaused(paused: boolean): void {
this.paused = paused;
if (paused) {
this.pending?.qualityProbe?.reset();
if (this.pending) {
this.pending.qualityResult = "pending";
}
}
if (paused) {
this.discardPending();
return;
}
for (const slot of new Set([this.active, this.pending])) {
if (slot?.activated && !slot.failed) {
slot.subscriber.armDecodedFrameProof();
}
}
}
resetQualityProbe(): void {
this.pending?.qualityProbe?.reset();
if (this.pending) {
this.pending.qualityResult = "pending";
}
}
reconnectActive(): boolean {
const revision = this.route.getRevision();
const assignment = this.route.getActiveAssignment();
const active = this.active;
if (
this.closed ||
this.resyncing ||
this.pending !== null ||
this.paused ||
revision === null ||
this.route.getPhase() !== "active" ||
assignment?.upstream.kind !== "sfu" ||
!active ||
active.failed ||
!active.activated ||
active.revision !== revision ||
active.publicationGeneration !== assignment.sfuPublicationGeneration
) {
return false;
}
return active.subscriber.reconnect();
}
private discardPending(): void {
this.pendingPeer = null;
this.events.preparePeer?.(null);
this.events.prepareChild?.(null);
this.clearPending();
}
async resyncAuthoritative(
update: RouteUpdateInput,
viewerPeerId: string,
): Promise<RouteUpdateResult> {
if (this.closed) {
return "stale";
}
const identityChanged = viewerPeerId !== this.viewerPeerId;
if (identityChanged) {
this.viewerPeerId = viewerPeerId;
}
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.publicationGeneration ===
update.assignment.sfuPublicationGeneration)),
);
if (
!identityChanged &&
((!this.active && !this.pending) || preservesActiveMedia)
) {
const result = this.accept(update, false);
if (result !== "stale") {
const active = this.active;
const token = this.route.token();
await this.transitionTail;
if (!this.closed && token && this.route.owns(token) &&
preservesActiveMedia && active && this.active === active) {
if (active.failed) {
this.routeFailed(update.revision, "active", active.connectionId);
} else {
active.subscriber.resync();
}
}
return result;
}
}
const resyncGeneration = ++this.resyncGeneration;
this.resyncing = true;
this.pendingPeer = null;
this.route.reset();
this.events.prepareChild?.(null);
const pending = this.pending;
const active = this.active;
this.pending = null;
this.active = null;
if (pending) {
pending.failed = true;
}
if (active) {
active.failed = true;
}
const accepted = this.route.accept(update);
this.preparePeer(update.assignment);
this.events.resetMedia?.();
if (update.phase === "active") {
this.activateChildren(update.assignment.childPeerIds, update.revision);
}
await this.queueTransition(async () => {
if (active?.activated) {
try {
active.subscriber.deactivate();
} catch {
// Disconnect remains the fail-closed cleanup path.
}
}
if (active) {
await disconnectSubscriber(active.subscriber);
}
if (pending && pending !== active) {
await disconnectSubscriber(pending.subscriber);
}
});
if (this.closed || this.resyncGeneration !== resyncGeneration) {
return "stale";
}
this.resyncing = false;
const token = this.route.getActiveToken();
if (token) {
await this.queueActiveRoute(token, false);
}
return accepted;
}
async acceptConfig(
message: Extract<ServerMessage, { type: "sfu-config" }>,
): Promise<void> {
if (
this.closed ||
!this.route.acceptsConfig(message.revision)
) {
return;
}
const token = this.route.token();
const assignment = this.route.getPlannedAssignment();
const phase = this.route.getPhase();
const candidate = this.route.getPreparedCandidate();
const publicationGeneration = assignment?.sfuPublicationGeneration;
if (
!token ||
!phase ||
assignment?.upstream.kind !== "sfu" ||
!publicationGeneration ||
message.publicationGeneration !== publicationGeneration ||
(phase === "prepare" &&
(candidate?.childPeerId !== this.viewerPeerId ||
candidate.transport !== "sfu"))
) {
return;
}
if (
phase === "active" &&
this.active?.publicationGeneration === publicationGeneration &&
this.active.activated &&
this.active.connectionId === message.connectionId
) {
if (this.active.failed) {
this.routeFailed(message.revision, "active", message.connectionId);
return;
}
this.active.subscriber.updateConfig(message);
await this.queueActiveRoute(token, true, this.paused);
return;
}
if (
this.pending?.revision === message.revision &&
this.pending.publicationGeneration === publicationGeneration &&
this.pending.connectionId === message.connectionId &&
!this.pending.failed
) {
this.pending.subscriber.updateConfig(message);
return;
}
// Active config only describes an existing server-side connection. A new
// local peer would have no offer; ask the graph owner to replace that edge.
if (phase === "active") {
this.routeFailed(message.revision, "active", message.connectionId);
return;
}
this.clearPending();
let slot: ViewerSubscriberSlot;
const subscriberEvents = {
send: this.events.send,
onInputChanged: () => { if (this.active === slot) this.events.onInputChanged?.(); },
onStream: (stream: MediaStream | null) => {
if (stream) {
this.handleStream(slot, stream);
}
},
onVideoAvailability: (available: boolean) => {
this.handleVideoAvailability(slot, available);
},
onStats: (metrics: ConnectionMetrics) => {
if (this.active === slot && !slot.failed) {
this.events.onSfuUpdate?.(metrics, slot.revision);
} else if (
this.pending === slot &&
!slot.failed &&
!slot.readySent &&
this.route.getPhase() === "prepare" &&
slot.qualityProbe
) {
if (this.events.qualityProbeEligible?.() === false) {
slot.qualityProbe.reset();
slot.qualityResult = "pending";
} else {
slot.qualityResult = slot.qualityProbe.observe(
this.events.currentPeerMetrics?.() ?? null,
metrics,
);
if (slot.qualityResult === "approved") {
this.sendPendingReady(slot);
}
}
}
},
onFirstDecodedFrame: () => this.handlePendingDecodedFrame(slot),
onState: (state: "connected" | "reconnecting") => {
if (this.active === slot && !slot.failed) {
this.events.onSfuState?.(state, slot.revision);
} else if (this.pending === slot && !slot.failed && state === "connected") {
this.sendPendingReady(slot);
void this.queueTransition(() => this.promotePendingSfu(slot));
}
},
onDisconnected: (failure?: "VIDEO_REJECTED") => this.failSubscriberSlot(slot, failure),
};
const subscriber =
this.events.createSubscriber?.(subscriberEvents) ??
new SfuSubscriber(subscriberEvents);
const preparedCandidate = this.route.getPreparedCandidate();
slot = {
connectionId: message.connectionId,
revision: message.revision,
publicationGeneration,
subscriber,
connected: false,
activated: false,
stream: null,
decodedFrame: false,
readySent: false,
qualityProbe:
preparedCandidate?.transport === "sfu" &&
preparedCandidate.qualityProbe
? new SfuQualityProbe()
: null,
qualityResult: "pending",
failed: false,
activationToken: null,
};
this.pending = slot;
this.events.onSfuFailure?.(null, slot.revision);
try {
const connected = await subscriber.connect(message);
if (!connected) {
const currentToken = (this.route.owns(token) ? token : null);
if (this.pending === slot && currentToken) {
slot.revision = currentToken.revision;
this.handleFailure(slot);
} else {
if (this.pending === slot) {
this.pending = null;
}
slot.failed = true;
}
await disconnectSubscriber(subscriber);
return;
}
const currentToken = (this.route.owns(token) ? token : null);
if (this.pending !== slot || !currentToken) {
if (this.pending === slot) {
this.pending = null;
}
slot.failed = true;
await disconnectSubscriber(subscriber);
return;
}
slot.revision = currentToken.revision;
slot.connected = true;
if (!subscriber.activate()) {
this.failSubscriberSlot(slot);
await disconnectSubscriber(subscriber);
return;
}
slot.activated = true;
if (!this.paused) {
subscriber.armDecodedFrameProof();
}
} catch {
this.failSubscriberSlot(slot);
await disconnectSubscriber(subscriber);
}
}
reportPeerFailure(parentPeerId: string, connectionId: string): boolean {
return reportActivePeerRouteFailure(
this.route,
parentPeerId,
connectionId,
this.events.send,
);
}
retryPeerActivation(connectionId: string): boolean {
const token = this.pendingPeer?.activationToken;
if (this.closed || this.resyncing || !token || !this.route.ownsActive(token) ||
this.pendingPeer?.connectionId !== connectionId) return false;
void this.queueActiveRoute(token, false);
return true;
}
async acceptSignal(message: SfuSignalMessage): Promise<void> {
const slot = [this.pending, this.active].find((slot) =>
slot && !slot.failed && slot.connectionId === message.connectionId &&
slot.publicationGeneration === message.publicationGeneration,
);
if (slot === this.pending && !slot?.activationToken && slot?.revision !== message.revision) return;
await slot?.subscriber.acceptSignal(message);
}
async disconnect(): Promise<void> {
if (this.closed) {
return;
}
this.closed = true;
this.resyncGeneration += 1;
this.resyncing = false;
this.route.reset();
this.pendingPeer = null;
this.events.preparePeer?.(null);
this.events.prepareChild?.(null);
await this.queueTransition(async () => {
const pending = this.pending;
const active = this.active;
this.pending = null;
this.active = null;
if (pending) {
pending.failed = true;
}
if (active) {
active.failed = true;
}
this.events.onSfuUpdate?.(
null,
active?.revision ?? pending?.revision ?? this.route.getRevision() ?? 0,
);
if (active?.activated) {
try {
active.subscriber.deactivate();
} catch {
// Disconnect remains the fail-closed cleanup path.
}
}
await Promise.all([
pending ? disconnectSubscriber(pending.subscriber) : undefined,
active && active !== pending
? disconnectSubscriber(active.subscriber)
: undefined,
]);
});
}
private preparePeer(assignment: ParticipantRouteAssignment): void {
this.events.preparePeer?.(
assignment.upstream.kind === "peer" ? assignment : null,
);
}
private queueActiveRoute(
token: RouteOperationToken,
acknowledge: boolean,
retireUnreferenced = false,
): Promise<void> {
const pendingPeer = this.pendingPeer;
const pendingSfu = this.pending;
return this.queueTransition(async () => {
if (this.closed || this.resyncing || !this.route.ownsActive(token) ||
(pendingPeer?.activationToken && this.pendingPeer !== pendingPeer) ||
(pendingSfu?.activationToken && this.pending !== pendingSfu && this.active !== pendingSfu)) {
return;
}
const assignment = this.route.getActiveAssignment();
if (!assignment) {
return;
}
const assignedPublicationGeneration =
assignment.upstream.kind === "sfu"
? assignment.sfuPublicationGeneration
: null;
if (
retireUnreferenced &&
this.active?.publicationGeneration !== assignedPublicationGeneration
) {
await this.retireActive();
if (!this.route.ownsActive(token)) {
return;
}
}
if (assignment.upstream.kind === "sfu") {
const mediaAssignment = this.route.getMediaAssignment();
if (
mediaAssignment?.upstream.kind === "sfu" &&
this.active?.publicationGeneration ===
assignment.sfuPublicationGeneration &&
this.active?.activated &&
!this.active.failed &&
this.pending?.publicationGeneration !== assignment.sfuPublicationGeneration
) {
if (this.pending === pendingSfu) this.clearPending();
this.active.revision = token.revision;
this.active.subscriber.updateConfig(this.active);
this.commitMedia(token);
return;
}
await this.activateSfu(token, acknowledge);
return;
}
const promoted =
pendingPeer?.activationToken && this.route.ownsActive(pendingPeer.activationToken)
? await this.events.activatePeer(assignment, pendingPeer.revision)
: false;
if (pendingPeer) {
if (this.pendingPeer !== pendingPeer) return;
if (pendingPeer.activationToken) token = pendingPeer.activationToken;
}
if (!this.route.ownsActive(token)) {
return;
}
if (promoted === "waiting") return;
if (pendingPeer?.activationToken && promoted !== true) {
// Readiness may reach the server before a candidate's local failure.
// Once committed, report against the exact active connection for recovery.
this.routeFailed(token.revision, "active", pendingPeer.connectionId);
return;
}
if (this.pendingPeer === pendingPeer) this.pendingPeer = null;
if (this.pending === pendingSfu) this.clearPending();
if (this.active) {
await this.retireActive();
}
if (!this.route.ownsActive(token)) {
return;
}
if (!promoted) {
await this.events.activatePeer(assignment);
}
if (!this.route.ownsActive(token)) {
return;
}
this.commitMedia(token);
});
}
private queueTransition(work: () => Promise<void>): Promise<void> {
const next = this.transitionTail.then(work, work);
this.transitionTail = next.catch(() => undefined);
return this.transitionTail;
}
private activateChildren(childPeerIds: readonly string[], revision: number): void {
if (this.events.activateChildren) {
this.events.activateChildren(childPeerIds, revision);
} else {
this.events.reconcileSfuChildren?.([...childPeerIds]);
}
}
private async activateSfu(
token: RouteOperationToken,
acknowledge: boolean,
): Promise<void> {
const assignment = this.route.getActiveAssignment();
const publicationGeneration = assignment?.sfuPublicationGeneration;
if (this.active?.failed && this.active.publicationGeneration === publicationGeneration && !this.pending) {
this.routeFailed(token.revision, "active", this.active.connectionId);
return;
}
if (
this.active?.revision === token.revision &&
this.active.publicationGeneration === publicationGeneration &&
this.active.activated && this.pending === null
) {
return;
}
const pending = this.pending;
if (
!pending ||
pending.revision !== token.revision ||
pending.publicationGeneration !== publicationGeneration ||
!pending.connected
) {
if (
acknowledge &&
this.route.ownsActive(token) &&
pending === null
) {
this.events.send({ type: "refresh-sfu", revision: token.revision });
}
return;
}
await this.promotePendingSfu(pending);
}
private handleStream(slot: ViewerSubscriberSlot, stream: MediaStream): void {
if (this.closed || slot.failed || !slot.activated) {
return;
}
slot.stream = stream;
if (this.active === slot) {
const assignment = this.route.getMediaAssignment();
if (assignment?.upstream.kind === "sfu") {
this.events.onSfuStream(stream, assignment, false, slot.revision);
}
return;
}
void this.queueTransition(() => this.promotePendingSfu(slot));
}
private handlePendingDecodedFrame(slot: ViewerSubscriberSlot): boolean {
if (this.closed || slot.failed || this.pending !== slot) {
return true;
}
if (this.paused || !slot.activated) {
return false;
}
const committed = slot.activationToken && this.route.ownsActive(slot.activationToken);
const assignment = committed ? this.route.getActiveAssignment() : this.route.getPlannedAssignment();
const phase = committed ? "active" : this.route.getPhase();
const revision = committed ? this.route.getActiveRevision() : this.route.getRevision();
if (
revision !== slot.revision ||
assignment?.upstream.kind !== "sfu" ||
assignment.sfuPublicationGeneration !== slot.publicationGeneration ||
phase === null
) {
return true;
}
slot.decodedFrame = true;
if (phase === "prepare") {
this.sendPendingReady(slot);
return slot.qualityProbe !== null || slot.readySent;
}
void this.queueTransition(() => this.promotePendingSfu(slot));
return true;
}
private sendPendingReady(slot: ViewerSubscriberSlot): void {
if (
this.pending !== slot ||
slot.failed ||
slot.readySent ||
!slot.subscriber.isConnected() ||
!slot.decodedFrame ||
(slot.qualityProbe !== null && slot.qualityResult !== "approved") ||
(slot.qualityProbe !== null &&
this.events.qualityProbeEligible?.() === false) ||
this.route.getPhase() !== "prepare" ||
this.route.getRevision() !== slot.revision
) {
return;
}
slot.readySent = this.events.send({
type: "route-ready",
revision: slot.revision,
phase: "prepare",
});
}
private async promotePendingSfu(slot: ViewerSubscriberSlot): Promise<void> {
const token = slot.activationToken;
const assignment = this.route.getActiveAssignment();
if (
this.pending !== slot ||
!slot.subscriber.isConnected() ||
!slot.stream ||
!slot.decodedFrame ||
!token ||
!this.route.ownsActive(token) ||
assignment?.upstream.kind !== "sfu"
) {
return;
}
slot.subscriber.stopDecodedFrameProof();
this.pending = null;
const previous = this.active;
this.active = slot;
if (!this.route.markMediaActive(token)) {
this.active = previous;
slot.failed = true;
await disconnectSubscriber(slot.subscriber);
return;
}
this.events.onSfuStream(slot.stream, assignment, true, slot.revision);
if (previous && previous !== slot) {
previous.failed = true;
try {
previous.subscriber.deactivate();
} catch {
// Disconnect remains the fail-closed cleanup path.
}
await disconnectSubscriber(previous.subscriber);
}
}
private handleVideoAvailability(
slot: ViewerSubscriberSlot,
available: boolean,
): void {
if (
this.closed ||
this.active !== slot ||
slot.failed ||
!slot.activated ||
this.route.getMediaAssignment()?.upstream.kind !== "sfu"
) {
return;
}
this.events.onSfuVideoAvailability?.(available, slot.revision);
}
private commitMedia(token: RouteOperationToken): void {
if (!this.route.markMediaActive(token)) {
return;
}
}
private clearPending(): void {
if (!this.pending) {
return;
}
const pending = this.pending;
this.pending = null;
pending.failed = true;
void disconnectSubscriber(pending.subscriber);
}
private async retireActive(): Promise<void> {
if (!this.active) {
return;
}
const active = this.active;
this.active = null;
active.failed = true;
this.events.onSfuUpdate?.(null, active.revision);
await this.disconnectRetiredSubscriber(active);
}
private detachUnreferencedActive(
assignment: ParticipantRouteAssignment,
): ViewerSubscriberSlot | null {
const publicationGeneration =
assignment.upstream.kind === "sfu"
? assignment.sfuPublicationGeneration
: null;
if (
!this.active ||
this.active.publicationGeneration === publicationGeneration
) {
return null;
}
const active = this.active;
this.active = null;
active.failed = true;
this.events.onSfuUpdate?.(null, active.revision);
return active;
}
private async disconnectRetiredSubscriber(
active: ViewerSubscriberSlot,
): Promise<void> {
if (active.activated) {
try {
active.subscriber.deactivate();
} catch {
// Disconnect remains the fail-closed cleanup path.
}
}
await disconnectSubscriber(active.subscriber);
}
private handleFailure(slot: ViewerSubscriberSlot, failure?: "VIDEO_REJECTED"): void {
if (this.closed || slot.failed) {
return;
}
const wasActive = this.active === slot;
const wasPending = this.pending === slot;
if (!wasActive && !wasPending) {
slot.failed = true;
return;
}
this.events.onSfuFailure?.(failure ?? null, slot.revision);
slot.failed = true;
slot.subscriber.stopDecodedFrameProof();
if (this.pending === slot) {
this.pending = null;
}
if (wasActive) {
this.events.onSfuUpdate?.(null, slot.revision);
}
const assignment = this.route.getPlannedAssignment();
const revision = this.route.getRevision();
const phase = this.route.getPhase();
const matchesPlannedRoute =
revision === slot.revision &&
assignment?.upstream.kind === "sfu" &&
assignment.sfuPublicationGeneration === slot.publicationGeneration;
if (revision === null || phase === null) {
return;
}
if (wasActive || (slot.activationToken && this.route.ownsActive(slot.activationToken))) {
const activeRevision = this.route.getActiveRevision();
const activeAssignment = this.route.getActiveAssignment();
if (
activeRevision !== null &&
activeAssignment?.upstream.kind === "sfu" &&
activeAssignment.sfuPublicationGeneration === slot.publicationGeneration
) {
this.routeFailed(activeRevision, "active", slot.connectionId);
}
} else if (matchesPlannedRoute) {
this.routeFailed(revision, phase, phase === "active" ? slot.connectionId : null);
}
}
private failSubscriberSlot(slot: ViewerSubscriberSlot, failure?: "VIDEO_REJECTED"): void {
if (this.pending !== slot && this.active !== slot) {
slot.failed = true;
return;
}
this.handleFailure(slot, failure);
}
private routeFailed(
revision: number,
phase: MediaRoutePhase,
connectionId: string | null = null,
): boolean {
return this.events.send({
type: "route-failed",
revision,
phase,
connectionId,
});
}
}
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> {
subscriber.stopDecodedFrameProof();
await subscriber.disconnect().catch(() => undefined);
}