Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
import { retireSfuPublisherQualityEvidence } from "./sender-quality-evidence";
import type { CopyKey } from "../ui/copy";
import type { MediaFailure } from "../ui/media-failure";
import type {
ClientMessage,
MediaRoutePhase,
ParticipantRouteAssignment,
ServerMessage,
SfuSignalMessage,
} from "../../shared/protocol";
import {
SfuPublisher,
type SfuConnectionConfig,
type SfuPublisherFailureStage,
} from "../sfu/publisher";
import type { ConnectionMetrics } from "../types";
import type { BrowserVideoCodec } from "../webrtc/video-codec";
import type { QualityProfile } from "./quality";
import { qualitySettingsEqual } from "./quality";
import {
MediaRouteTransition,
type RouteOperationToken,
type RouteUpdateInput,
type RouteUpdateResult,
} from "./route-transition";
export interface HostPublisherTransport {
connect(config: SfuConnectionConfig): Promise<boolean>;
updateConfig(config: SfuConnectionConfig): void;
acceptSignal(message: SfuSignalMessage): Promise<void>;
activate(
stream: MediaStream,
profile: QualityProfile,
videoCodec?: BrowserVideoCodec,
): Promise<boolean>;
deactivate(): Promise<boolean>;
replaceStream(stream: MediaStream): Promise<boolean>;
updateProfile(profile: QualityProfile): Promise<boolean>;
setPaused(paused: boolean): void;
getQualityWarning?(): MediaFailure[] | null;
getFailureStage?(): SfuPublisherFailureStage | null;
disconnect(): Promise<void>;
}
interface HostPublisherSlot {
revision: number;
activationToken: RouteOperationToken | null;
connectionId: string;
publicationGeneration: string;
publisher: HostPublisherTransport;
connected: boolean;
active: boolean;
failed: boolean;
}
interface HostSfuRouteEvents {
getStream: () => MediaStream | null;
getProfile: () => QualityProfile;
getVideoCodec: () => BrowserVideoCodec;
reconcileChildren: (assignment: ParticipantRouteAssignment, revision: number) => void;
send: (message: ClientMessage) => boolean;
onSenderUpdate?: (
metrics: ConnectionMetrics,
revision: number,
publicationGeneration: string,
) => void;
createPublisher?: (
onDisconnected: () => void,
onStats: (metrics: ConnectionMetrics | null) => void,
) => HostPublisherTransport;
}
export class HostSfuRoute {
private readonly route = new MediaRouteTransition();
private pending: HostPublisherSlot | null = null;
private active: HostPublisherSlot | null = null;
private recovery: { revision: number; refreshed: boolean } | null = null;
private lastFailureStage: SfuPublisherFailureStage | null = null;
private transitionTail: Promise<void> = Promise.resolve();
private resyncGeneration = 0;
private resyncing = false;
private paused = false;
private closed = false;
constructor(private readonly events: HostSfuRouteEvents) {}
accept(update: RouteUpdateInput): RouteUpdateResult {
if (this.closed) {
return "stale";
}
const previousRevision = this.route.getRevision();
const result = this.route.accept(update);
if (result === "stale") {
return result;
}
if (this.active) {
this.active.publisher.updateConfig({ ...this.active, revision: update.revision });
}
const pausedActiveReconciliation =
this.paused && update.phase === "active" && result !== "duplicate";
const retiredActive = pausedActiveReconciliation
? this.detachUnreferencedActive(
update.assignment.sfuPublicationGeneration,
)
: null;
if (update.phase === "active" && result !== "duplicate") {
this.events.reconcileChildren(update.assignment, update.revision);
}
if (this.paused && update.phase === "prepare") {
this.clearPending();
return result;
}
if (previousRevision !== update.revision) {
this.recovery = null;
this.lastFailureStage = null;
}
if (
update.phase === "active" && this.pending &&
this.pending.publicationGeneration === update.assignment.sfuPublicationGeneration &&
(this.pending.revision === update.revision || this.pending.activationToken)
) {
this.pending.activationToken = this.route.getActiveToken();
this.pending.revision = update.revision;
this.pending.publisher.updateConfig(this.pending);
}
if (update.phase === "prepare") {
if (
this.pending &&
((!this.pending.activationToken && this.pending.revision !== update.revision) ||
this.pending.publicationGeneration !==
update.assignment.sfuPublicationGeneration)
) {
this.clearPending();
}
if (update.assignment.sfuPublicationGeneration === null) {
this.clearPending();
}
return result;
}
const token = this.route.getActiveToken();
if (retiredActive) {
void this.queueTransition(() =>
this.disconnectRetiredPublisher(retiredActive),
);
}
if (token && !this.resyncing) {
void this.queueActivation(token, this.paused);
}
return result;
}
async acceptAndWait(
update: RouteUpdateInput,
): Promise<RouteUpdateResult> {
const result = this.accept(update);
await this.transitionTail;
return result;
}
async resyncAuthoritative(
update: RouteUpdateInput,
): Promise<RouteUpdateResult> {
this.lastFailureStage = null;
const result = this.accept(update);
if (result !== "stale" || this.closed) {
await this.transitionTail;
return result;
}
const resyncGeneration = ++this.resyncGeneration;
this.resyncing = true;
this.route.reset();
this.recovery = null;
const closing = this.retirePublishers();
this.events.reconcileChildren({
upstream: { kind: "none" },
childPeerIds: [],
sfuPublicationGeneration: null,
}, update.revision);
const accepted = this.accept(update);
await this.queueTransition(() => closing);
if (this.closed || this.resyncGeneration !== resyncGeneration) {
return "stale";
}
this.resyncing = false;
const token = this.route.getActiveToken();
if (token) {
await this.queueActivation(token);
}
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 ||
!publicationGeneration ||
message.publicationGeneration !== publicationGeneration ||
(phase === "prepare" && candidate?.transport !== "sfu")
) {
return;
}
if (
this.active?.publicationGeneration === publicationGeneration &&
this.active.connectionId === message.connectionId
) {
this.active.revision = message.revision;
this.active.publisher.updateConfig(message);
if (phase === "active" && this.active.active) {
await this.queueActivation(token);
}
return;
}
if (
this.pending &&
(this.pending.revision === message.revision || this.pending.activationToken) &&
this.pending.publicationGeneration === publicationGeneration &&
this.pending.connectionId === message.connectionId &&
!this.pending.failed
) {
this.pending.publisher.updateConfig(message);
return;
}
this.clearPending();
let slot: HostPublisherSlot;
const publisher =
this.events.createPublisher?.(
() => this.failPublisherSlot(slot),
(metrics) => this.handlePublisherStats(slot, metrics),
) ??
new SfuPublisher({
send: this.events.send,
onDisconnected: () => this.failPublisherSlot(slot),
onStats: (metrics) => this.handlePublisherStats(slot, metrics),
});
slot = {
revision: message.revision,
activationToken: phase === "active" ? this.route.getActiveToken() : null,
connectionId: message.connectionId,
publicationGeneration,
publisher,
connected: false,
active: false,
failed: false,
};
this.pending = slot;
try {
const connected = await publisher.connect(message);
if (!connected) {
if (this.pending === slot && this.ownsPublisherSlot(slot)) {
this.handleFailure(slot);
} else {
if (this.pending === slot) {
this.pending = null;
}
slot.failed = true;
}
await this.disconnectPublisher(slot);
return;
}
if (this.pending !== slot || !this.ownsPublisherSlot(slot)) {
if (this.pending === slot) {
this.pending = null;
}
slot.failed = true;
await this.disconnectPublisher(slot);
return;
}
slot.connected = true;
let prepared = false;
await this.queueTransition(async () => {
if (this.pending !== slot || !this.ownsPublisherSlot(slot)) {
if (this.pending === slot) {
this.pending = null;
}
slot.failed = true;
await this.disconnectPublisher(slot);
return;
}
prepared = await this.preparePublisher(slot);
});
if (!prepared) {
return;
}
if (slot.activationToken && !this.resyncing) {
await this.queueActivation(slot.activationToken);
}
} catch {
this.failPublisherSlot(slot);
await this.disconnectPublisher(slot);
}
}
setPaused(paused: boolean): void {
this.paused = paused;
for (const slot of this.publishingSlots()) {
slot.publisher.setPaused(paused);
}
if (paused) {
this.clearPending();
}
}
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?.publisher.acceptSignal(message);
}
updateProfile(profile: QualityProfile): Promise<boolean> {
const slots = this.publishingSlots();
return slots.length === 0
? Promise.resolve(true)
: Promise.all(
slots.map((slot) =>
slot.publisher
.updateProfile(profile)
.catch(() => false),
),
).then((results) => results.every(Boolean));
}
getQualityWarning(): MediaFailure[] | null {
if (this.active?.active) {
return this.active.publisher.getQualityWarning?.() ?? null;
}
return this.lastFailureStage
? [sfuFailureWarning(this.lastFailureStage)]
: null;
}
async replaceStream(stream: MediaStream, rebuildTransport = false): Promise<boolean> {
if (rebuildTransport) {
const slots = [...new Set([this.active, this.pending])].filter(
(slot): slot is HostPublisherSlot => slot !== null && !slot.failed,
);
for (const slot of slots) this.handleFailure(slot, false);
const closing = Promise.all(slots.map(slot => this.disconnectPublisher(slot))).then(() => undefined);
await this.queueTransition(() => closing);
return slots.length === 0;
}
const slots = this.publishingSlots();
const initialActive = this.active;
if (slots.length === 0) {
return true;
}
const results = await Promise.all(
slots.map((slot) => slot.publisher.replaceStream(stream).catch(() => false)),
);
let replaced = true;
await this.queueTransition(async () => {
const currentActive = this.active;
if (currentActive) {
const activeIndex = slots.indexOf(currentActive);
replaced = activeIndex < 0 || results[activeIndex] === true;
} else if (initialActive) {
const activeIndex = slots.indexOf(initialActive);
const stillPlanned =
this.route.getPlannedAssignment()?.sfuPublicationGeneration ===
initialActive.publicationGeneration;
replaced =
activeIndex < 0 || results[activeIndex] === true || !stillPlanned;
}
for (const [index, slot] of slots.entries()) {
if (results[index] === false) {
this.failPublisherSlot(slot);
await this.disconnectPublisher(slot);
}
}
});
return replaced;
}
private publishingSlots(): HostPublisherSlot[] {
return [...new Set([this.active, this.pending])].filter(
(slot): slot is HostPublisherSlot =>
slot !== null && slot.active && !slot.failed,
);
}
async disconnect(): Promise<void> {
if (this.closed) {
return;
}
this.closed = true;
this.resyncGeneration += 1;
this.resyncing = false;
this.route.reset();
this.recovery = null;
const closing = this.retirePublishers();
await this.queueTransition(() => closing);
}
private async retirePublishers(): Promise<void> {
const pending = this.pending;
const active = this.active;
this.pending = null;
this.active = null;
if (pending) pending.failed = true;
if (active) active.failed = true;
// Cancel before joining the transition queue: its current operation may
// itself be waiting for one of these publishers to finish preparation.
await Promise.all([
pending ? this.disconnectPublisher(pending) : undefined,
active && active !== pending ? this.disconnectRetiredPublisher(active) : undefined,
]);
}
private queueActivation(
token: RouteOperationToken,
retireUnreferenced = false,
): Promise<void> {
const pending = this.pending;
return this.queueTransition(async () => {
if (
this.closed || this.resyncing || !this.route.ownsActive(token) ||
(pending?.activationToken && this.pending !== pending && this.active !== pending)
) {
return;
}
const assignment = this.route.getActiveAssignment();
if (assignment) {
if (
retireUnreferenced &&
this.active?.publicationGeneration !==
assignment.sfuPublicationGeneration
) {
await this.retireActive();
if (!this.route.ownsActive(token)) {
return;
}
}
await this.activate(assignment, token, pending);
}
});
}
private queueTransition(work: () => Promise<void>): Promise<void> {
const next = this.transitionTail.then(work, work);
this.transitionTail = next.catch(() => undefined);
return this.transitionTail;
}
private async activate(
assignment: ParticipantRouteAssignment,
token: RouteOperationToken,
pendingAtQueue: HostPublisherSlot | null,
): Promise<void> {
const publicationGeneration = assignment.sfuPublicationGeneration;
if (publicationGeneration === null) {
if (this.pending === pendingAtQueue) this.clearPending();
await this.retireActive();
if (!this.route.ownsActive(token)) {
return;
}
this.commitMedia(token);
return;
}
if (
this.active &&
!this.active.failed &&
this.active.publicationGeneration === publicationGeneration &&
this.pending?.publicationGeneration !== publicationGeneration
) {
this.active.revision = token.revision;
this.active.activationToken = token;
this.active.publisher.updateConfig(this.active);
if (this.pending === pendingAtQueue) this.clearPending();
if (this.active.active) {
this.commitMedia(token);
}
return;
}
const pending = this.pending;
if (
!pending ||
pending.revision !== token.revision ||
pending.publicationGeneration !== publicationGeneration ||
!pending.connected ||
!pending.active
) {
if (this.route.ownsActive(token)) {
this.requestRecovery(token.revision);
}
return;
}
this.pending = null;
const previous = this.active;
this.active = pending;
if (!this.route.markMediaActive(token)) {
this.active = previous;
pending.failed = true;
await this.disconnectPublisher(pending);
return;
}
this.lastFailureStage = null;
this.recovery = null;
if (previous && previous !== pending) {
previous.failed = true;
if (previous.active) {
await previous.publisher.deactivate().catch(() => false);
}
await this.disconnectPublisher(previous);
}
}
private async preparePublisher(slot: HostPublisherSlot): Promise<boolean> {
const stream = this.events.getStream();
const profile = this.events.getProfile();
const videoCodec = this.events.getVideoCodec();
if (!stream) {
this.failPublisherSlot(slot);
return false;
}
try {
if (!(await slot.publisher.activate(stream, profile, videoCodec))) {
this.failPublisherSlot(slot);
await this.disconnectPublisher(slot);
return false;
}
slot.publisher.setPaused(this.paused);
if (this.pending !== slot || !this.ownsPublisherSlot(slot)) {
await this.disconnectPublisher(slot);
return false;
}
slot.active = true;
const latestStream = this.events.getStream();
if (
latestStream &&
latestStream !== stream &&
!(await slot.publisher.replaceStream(latestStream))
) {
this.failPublisherSlot(slot);
await this.disconnectPublisher(slot);
return false;
}
const latestProfile = this.events.getProfile();
if (
!qualitySettingsEqual(latestProfile, profile) &&
!(await slot.publisher.updateProfile(latestProfile))
) {
this.failPublisherSlot(slot);
await this.disconnectPublisher(slot);
return false;
}
return this.pending === slot && this.ownsPublisherSlot(slot);
} catch {
this.failPublisherSlot(slot);
await this.disconnectPublisher(slot);
return false;
}
}
private ownsPublisherSlot(slot: HostPublisherSlot): boolean {
if (slot.activationToken) return this.route.ownsActive(slot.activationToken);
return (
this.route.getRevision() === slot.revision &&
this.route.getPlannedAssignment()?.sfuPublicationGeneration ===
slot.publicationGeneration
);
}
private commitMedia(token: RouteOperationToken): void {
if (!this.route.markMediaActive(token)) {
return;
}
this.lastFailureStage = null;
this.recovery = null;
}
private clearPending(expected?: HostPublisherSlot): void {
if (!this.pending || (expected && this.pending !== expected)) {
return;
}
const pending = this.pending;
this.pending = null;
pending.failed = true;
const closing = this.disconnectPublisher(pending);
void this.queueTransition(() => closing);
}
private async retireActive(except?: HostPublisherSlot): Promise<void> {
if (!this.active || this.active === except) {
return;
}
const active = this.active;
this.active = null;
active.failed = true;
await this.disconnectRetiredPublisher(active);
}
private detachUnreferencedActive(
publicationGeneration: string | null,
): HostPublisherSlot | null {
if (
!this.active ||
this.active.publicationGeneration === publicationGeneration
) {
return null;
}
const active = this.active;
this.active = null;
active.failed = true;
return active;
}
private async disconnectRetiredPublisher(
active: HostPublisherSlot,
): Promise<void> {
if (active.active) {
await active.publisher.deactivate().catch(() => false);
}
await this.disconnectPublisher(active);
}
private handleFailure(slot: HostPublisherSlot, refreshConnection = true): void {
if (this.closed || slot.failed) {
return;
}
const wasActive = this.active === slot;
const wasPending = this.pending === slot;
const wasCommitted = slot.activationToken !== null &&
this.route.ownsActive(slot.activationToken);
if (!wasActive && !wasPending) {
slot.failed = true;
return;
}
const assignment = this.route.getPlannedAssignment();
const revision = this.route.getRevision();
const phase = this.route.getPhase();
const matchesPlannedRoute =
revision === slot.revision &&
assignment?.sfuPublicationGeneration === slot.publicationGeneration;
this.lastFailureStage = slot.publisher.getFailureStage?.() ?? "transport";
slot.failed = true;
if (wasPending) {
this.pending = null;
}
if (wasActive) {
this.active = null;
}
this.retirePublisherEvidence(slot);
if (revision === null || phase === null) {
return;
}
if (phase === "prepare") {
const activeRevision = this.route.getActiveRevision();
if (wasActive || wasCommitted) {
if (
activeRevision !== null &&
this.route.getActiveAssignment()?.sfuPublicationGeneration ===
slot.publicationGeneration
) {
this.routeFailed(activeRevision, "active", slot.connectionId);
}
} else if (matchesPlannedRoute) {
this.routeFailed(revision, "prepare", null);
}
return;
}
if (!matchesPlannedRoute) {
return;
}
if (refreshConnection) this.requestRecovery(revision, slot.connectionId);
// A different source backend needs its own encoder/transport. Refresh only
// describes the old physical connection; authority must replace that slot.
else this.routeFailed(revision, "active", slot.connectionId);
}
private failPublisherSlot(slot: HostPublisherSlot): void {
if (this.pending !== slot && this.active !== slot) {
slot.failed = true;
return;
}
this.handleFailure(slot);
}
private requestRecovery(
revision: number,
connectionId: string | null = null,
): void {
if (!this.recovery || this.recovery.revision !== revision) {
this.recovery = { revision, refreshed: false };
}
if (!this.recovery.refreshed) {
this.recovery.refreshed = true;
if (this.events.send({ type: "refresh-sfu", revision })) {
return;
}
}
this.routeFailed(revision, "active", connectionId);
}
private routeFailed(
revision: number,
phase: MediaRoutePhase,
connectionId: string | null,
): void {
this.events.send({
type: "route-failed",
revision,
phase,
connectionId,
});
}
private async disconnectPublisher(slot: HostPublisherSlot): Promise<void> {
this.retirePublisherEvidence(slot);
await slot.publisher.disconnect().catch(() => undefined);
}
private retirePublisherEvidence(slot: HostPublisherSlot): void {
const generation = slot.publicationGeneration;
if (![this.active, this.pending].some((current) =>
current && current !== slot && !current.failed &&
current.publicationGeneration === generation,
)) {
retireSfuPublisherQualityEvidence(generation);
}
}
private handlePublisherStats(
slot: HostPublisherSlot,
metrics: ConnectionMetrics | null,
): void {
if (
metrics !== null &&
!this.closed &&
!slot.failed &&
slot.active &&
(this.pending === slot || this.active === slot) &&
this.ownsPublisherSlot(slot)
) {
this.events.onSenderUpdate?.(
metrics,
slot.revision,
slot.publicationGeneration,
);
}
}
}
function sfuFailureWarning(stage: SfuPublisherFailureStage): MediaFailure {
const stageKey: Record<SfuPublisherFailureStage, CopyKey> = {
connect: "host.warn.sfuStage.connect",
source: "host.warn.sfuStage.source",
"video-publish": "host.warn.sfuStage.videoPublish",
"sender-config": "host.warn.sfuStage.senderConfig",
"audio-publish": "host.warn.sfuStage.audioPublish",
transport: "host.warn.sfuStage.transport",
};
return { key: "host.warn.sfuRecover", paramKeys: [stageKey[stage]] };
}