Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
fix(web): show SFU viewer connection truth (#127)
AAA766aaf4f6ee2
diff --git a/src/client/components/StatusBadge.tsx b/src/client/components/StatusBadge.tsxindex 4618d854..9d1f09a7 100644--- a/src/client/components/StatusBadge.tsx+++ b/src/client/components/StatusBadge.tsx@@ -37,10 +37,14 @@ export function SignalStatusBadge({export function PeerStatusBadge({state,}: {- state: RTCPeerConnectionState | "waiting";+ state: RTCPeerConnectionState | "reconnecting" | "waiting";}) {- const labels: Record<RTCPeerConnectionState | "waiting", BadgeProps> = {+ const labels: Record<+ RTCPeerConnectionState | "reconnecting" | "waiting",+ BadgeProps+ > = {waiting: { tone: "neutral", label: "等待开始分享" },+ reconnecting: { tone: "warning", label: "正在恢复" },new: { tone: "neutral", label: "准备中" },connecting: { tone: "neutral", label: "正在连接" },connected: { tone: "good", label: "已连接" },@@ -76,6 +80,16 @@ export function PathBadge({ path }: { path: MediaPath }) {);}+export function MediaRouteBadge({ route }: { route: "p2p" | "sfu" }) {+ return (+ <Badge+ tone={route === "p2p" ? "good" : "neutral"}+ label={route === "p2p" ? "P2P" : "SFU"}+ title="当前媒体路径"+ />+ );+}+export function TopologyBadge({topology,}: {diff --git a/src/client/media/viewer-sfu-route.ts b/src/client/media/viewer-sfu-route.tsindex b5e21c9d..1b7eb3de 100644--- a/src/client/media/viewer-sfu-route.ts+++ b/src/client/media/viewer-sfu-route.ts@@ -5,6 +5,7 @@ import type {ServerMessage,} from "../../shared/protocol";import { SfuSubscriber } from "../sfu/subscriber";+import type { ConnectionMetrics } from "../types";import type { SfuConnectionConfig } from "../sfu/publisher";import {MediaRouteTransition,@@ -42,10 +43,14 @@ interface ViewerSfuRouteEvents {assignment: ParticipantRouteAssignment,initialVideoStream: boolean,) => void;+ onSfuUpdate?: (metrics: ConnectionMetrics | null) => void;+ onSfuState?: (state: "connected" | "reconnecting") => void;send: (message: ClientMessage) => boolean;createSubscriber?: (events: {onStream: (stream: MediaStream | null) => void;+ onStats: (metrics: ConnectionMetrics) => void;+ onState: (state: "connected" | "reconnecting") => void;onDisconnected: () => void;},) => ViewerSubscriberTransport;@@ -184,6 +189,16 @@ export class ViewerSfuRoute {this.handleStream(slot, stream);}},+ onStats: (metrics: ConnectionMetrics) => {+ if (this.active === slot && !slot.failed) {+ this.events.onSfuUpdate?.(metrics);+ }+ },+ onState: (state: "connected" | "reconnecting") => {+ if (this.active === slot && !slot.failed) {+ this.events.onSfuState?.(state);+ }+ },onDisconnected: () => this.handleFailure(slot),};const subscriber =@@ -250,6 +265,7 @@ export class ViewerSfuRoute {const active = this.active;this.pending = null;this.active = null;+ this.events.onSfuUpdate?.(null);if (active?.activated) {try {active.subscriber.deactivate();@@ -418,6 +434,7 @@ export class ViewerSfuRoute {}const active = this.active;this.active = null;+ this.events.onSfuUpdate?.(null);if (active.activated) {try {active.subscriber.deactivate();@@ -439,6 +456,7 @@ export class ViewerSfuRoute {}if (wasActive) {this.active = null;+ this.events.onSfuUpdate?.(null);}const assignment = this.route.getPlannedAssignment();diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsxindex eb5d43d3..73b8fb92 100644--- a/src/client/pages/ViewerPage.tsx+++ b/src/client/pages/ViewerPage.tsx@@ -27,6 +27,7 @@ import { ConnectionDetailsToggle } from "../components/ConnectionDetailsToggle";import { RoomCode } from "../components/RoomCode";import { qualityLimitationSummary } from "../components/connection-details";import {+ MediaRouteBadge,PathBadge,PeerStatusBadge,SignalStatusBadge,@@ -56,6 +57,7 @@ import {toggleViewerMuted,} from "../media/viewer-volume";import type {+ ConnectionMetrics,PeerSnapshot,SignalConnectionState,} from "../types";@@ -81,6 +83,10 @@ type SelectedEdgeTurn = Extract<ServerMessage,{ type: "selected-edge-turn"; edgeKind: "peer-selected" }>;+interface SfuUpstreamState {+ connectionState: "connected" | "reconnecting";+ metrics: ConnectionMetrics | null;+}export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {const [accessState, setAccessState] = useState<@@ -92,6 +98,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {const [hostOnline, setHostOnline] = useState(false);const [remoteStream, setRemoteStream] = useState<MediaStream | null>(null);const [peerSnapshot, setPeerSnapshot] = useState<PeerSnapshot | null>(null);+ const [sfuUpstream, setSfuUpstream] = useState<SfuUpstreamState | null>(null);const [relaySnapshot, setRelaySnapshot] = useState<PeerSnapshot | null>(null);const [relayChildEvidence, setRelayChildEvidence] =useState<ViewerQualityEvidence | null>(null);@@ -343,6 +350,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {}currentAssignment = { parentPeerId: null, childPeerIds: [] };parentEdgeQualityEvidenceReporter.reset();+ setSfuUpstream(null);clearPeerState();viewerRelay?.setChild(null);},@@ -368,6 +376,20 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {currentAssignment.childPeerIds[0] ?? null,);},+ onSfuUpdate: (metrics) => {+ if (active && viewerSfuRoute === route) {+ setSfuUpstream((current) =>+ metrics && current ? { ...current, metrics } : null,+ );+ }+ },+ onSfuState: (state) => {+ if (active && viewerSfuRoute === route) {+ setSfuUpstream((current) =>+ current ? { ...current, connectionState: state } : null,+ );+ }+ },onSfuStream: (nextStream, assignment, initialVideoStream) => {if (!active || viewerSfuRoute !== route) {return;@@ -387,6 +409,9 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {relay?.setChild(currentAssignment.childPeerIds[0] ?? null);relay?.setStream(nextStream);setRemoteStream(nextStream);+ if (initialVideoStream) {+ setSfuUpstream({ connectionState: "connected", metrics: null });+ }setStatusText("正在播放");if (initialVideoStream) {peerRef.current?.dispose();@@ -404,6 +429,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {function clearViewerSfuRoute(): void {const route = viewerSfuRoute;viewerSfuRoute = null;+ setSfuUpstream(null);prepareParent(null);void route?.disconnect();}@@ -1072,10 +1098,20 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {</div></div><div className="viewer-badges">- <PeerStatusBadge state={peerSnapshot?.connectionState ?? "waiting"} />- {showConnectionDetails && (- <PathBadge path={peerSnapshot?.metrics.path ?? "unknown"} />- )}+ <PeerStatusBadge+ state={+ sfuUpstream+ ? sfuUpstream.connectionState+ : (peerSnapshot?.connectionState ?? "waiting")+ }+ />+ {sfuUpstream ? (+ <MediaRouteBadge route="sfu" />+ ) : showConnectionDetails &&+ peerSnapshot &&+ peerSnapshot.metrics.path !== "unknown" ? (+ <PathBadge path={peerSnapshot.metrics.path} />+ ) : null}</div></div>@@ -1255,9 +1291,30 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {{showConnectionDetails && peerSnapshot && (<section className="viewer-stats" aria-labelledby="stats-heading"><h2 id="stats-heading">连接数据</h2>+ <div className="viewer-transport-heading">+ <MediaRouteBadge route="p2p" />+ {peerSnapshot.metrics.path !== "unknown" && (+ <PathBadge path={peerSnapshot.metrics.path} />+ )}+ </div><StatsGrid metrics={peerSnapshot.metrics} direction="receive" /></section>)}+ {showConnectionDetails && sfuUpstream && (+ <section className="viewer-stats" aria-labelledby="sfu-stats-heading">+ <h2 id="sfu-stats-heading">连接数据</h2>+ <div className="viewer-transport-heading">+ <MediaRouteBadge route="sfu" />+ {sfuUpstream.metrics &&+ sfuUpstream.metrics.path !== "unknown" && (+ <PathBadge path={sfuUpstream.metrics.path} />+ )}+ </div>+ {sfuUpstream.metrics && (+ <StatsGrid metrics={sfuUpstream.metrics} direction="receive" />+ )}+ </section>+ )}{showConnectionDetails && relaySnapshot && (<section className="viewer-stats" aria-labelledby="relay-stats-heading"><h2 id="relay-stats-heading">转发数据</h2>diff --git a/src/client/sfu/subscriber.ts b/src/client/sfu/subscriber.tsindex 88e7db55..cb586a72 100644--- a/src/client/sfu/subscriber.ts+++ b/src/client/sfu/subscriber.ts@@ -7,15 +7,24 @@ import type {} from "livekit-client";import type { SfuConnectionConfig } from "./publisher";+import type { ConnectionMetrics } from "../types";+import {+ collectConnectionMetricsFromReport,+ createStatsAccumulator,+ mergeStatsReports,+ type StatsAccumulator,+} from "../webrtc/stats";interface SubscriberEvents {onStream: (stream: MediaStream | null) => void;+ onStats?: (metrics: ConnectionMetrics) => void;+ onState?: (state: "connected" | "reconnecting") => void;onDisconnected?: () => void;}interface SubscribedTrack {sid: string;- track: MediaStreamTrack;+ track: RemoteTrack;}type SubscriberState =@@ -27,6 +36,7 @@ type SubscriberState =type LiveKit = typeof import("livekit-client");const HOST_IDENTITY = "host";+const STATS_INTERVAL_MS = 2_000;const roomDisconnects = new WeakMap<Room, Promise<void>>();export class SfuSubscriber {@@ -36,6 +46,9 @@ export class SfuSubscriber {private audio: SubscribedTrack | null = null;private readonly desiredTrackSids = new Set<string>();private state: SubscriberState = "idle";+ private statsAccumulator: StatsAccumulator = createStatsAccumulator();+ private statsTimer: ReturnType<typeof setInterval> | null = null;+ private statsInFlight: StatsAccumulator | null = null;private generation = 0;private terminalNotified = false;@@ -179,7 +192,7 @@ export class SfuSubscriber {this.addTrack(publication.trackSid,publication.source,- track.mediaStreamTrack,+ track,sdk.Track,);},@@ -214,6 +227,17 @@ export class SfuSubscriber {}},);+ room.on(sdk.RoomEvent.Reconnecting, () => {+ if (this.owns(room, generation) && this.state === "active") {+ this.events.onState?.("reconnecting");+ }+ });+ room.on(sdk.RoomEvent.Reconnected, () => {+ if (this.owns(room, generation) && this.state === "active") {+ this.events.onState?.("connected");+ void this.updateStats();+ }+ });room.on(sdk.RoomEvent.Disconnected, () => {if (this.owns(room, generation)) {const notify = this.state !== "connecting";@@ -258,7 +282,7 @@ export class SfuSubscriber {private addTrack(sid: string,source: Track.Source,- track: MediaStreamTrack,+ track: RemoteTrack,trackType: typeof Track,): void {if (source === trackType.Source.ScreenShare) {@@ -269,6 +293,9 @@ export class SfuSubscriber {return;}this.emitStream();+ if (this.video) {+ this.startStats();+ }}private removeTrack(sid: string): void {@@ -279,21 +306,90 @@ export class SfuSubscriber {this.audio = null;}this.emitStream();+ if (!this.video) {+ this.stopStats();+ }}private emitStream(): void {if (!this.video) {return;}- const tracks = [this.video.track];+ const tracks = [this.video.track.mediaStreamTrack];if (this.audio) {- tracks.push(this.audio.track);+ tracks.push(this.audio.track.mediaStreamTrack);}this.events.onStream(new MediaStream(tracks));}+ private startStats(): void {+ if (this.statsTimer === null) {+ this.statsTimer = setInterval(() => {+ void this.updateStats();+ }, STATS_INTERVAL_MS);+ }+ void this.updateStats();+ }++ private async updateStats(): Promise<void> {+ const room = this.room;+ const video = this.video;+ const generation = this.generation;+ const accumulator = this.statsAccumulator;+ if (+ !room ||+ !video ||+ this.state !== "active" ||+ this.statsInFlight === accumulator+ ) {+ return;+ }+ this.statsInFlight = accumulator;+ try {+ const reports = await Promise.all([+ video.track.getRTCStatsReport(),+ this.audio?.track.getRTCStatsReport(),+ ]);+ if (+ !this.owns(room, generation) ||+ this.state !== "active" ||+ this.video !== video ||+ this.statsAccumulator !== accumulator+ ) {+ return;+ }+ const report = mergeStatsReports(reports);+ if (!report) {+ return;+ }+ this.events.onStats?.(+ collectConnectionMetricsFromReport(+ report,+ "receive",+ accumulator,+ ),+ );+ } catch {+ // Stats are observational and must never disrupt active SFU media.+ } finally {+ if (this.statsInFlight === accumulator) {+ this.statsInFlight = null;+ }+ }+ }++ private stopStats(): void {+ if (this.statsTimer !== null) {+ clearInterval(this.statsTimer);+ this.statsTimer = null;+ }+ this.statsInFlight = null;+ this.statsAccumulator = createStatsAccumulator();+ }+private clearMedia(notify: boolean): void {const hadVideo = this.video !== null;+ this.stopStats();this.video = null;this.audio = null;if (notify && hadVideo) {diff --git a/src/client/webrtc/stats.ts b/src/client/webrtc/stats.tsindex f0c3e413..556a3d6c 100644--- a/src/client/webrtc/stats.ts+++ b/src/client/webrtc/stats.ts@@ -72,6 +72,16 @@ export function createStatsAccumulator(): StatsAccumulator {};}+export function mergeStatsReports(+ reports: readonly (RTCStatsReport | undefined)[],+): RTCStatsReport | null {+ const merged = new Map<string, unknown>();+ for (const report of reports) {+ report?.forEach((record, id) => merged.set(id, record));+ }+ return merged.size > 0 ? (merged as unknown as RTCStatsReport) : null;+}+function intervalDelta(current: number | null,previous: number | null,@@ -296,7 +306,20 @@ export async function collectConnectionMetrics(previous: StatsAccumulator,selector: StatsMediaSelector | null = null,): Promise<ConnectionMetrics> {- const report = await connection.getStats();+ return collectConnectionMetricsFromReport(+ await connection.getStats(),+ direction,+ previous,+ selector,+ );+}++export function collectConnectionMetricsFromReport(+ report: RTCStatsReport,+ direction: "send" | "receive",+ previous: StatsAccumulator,+ selector: StatsMediaSelector | null = null,+): ConnectionMetrics {const media = mediaRecord(report, direction, selector);const transport = transportRecord(report, media);let pair = selectedCandidatePair(report, transport);diff --git a/tests/route-transition.test.ts b/tests/route-transition.test.tsindex 4aaff3a8..a12d02a7 100644--- a/tests/route-transition.test.ts+++ b/tests/route-transition.test.ts@@ -11,6 +11,7 @@ import {import { HostSfuRoute } from "../src/client/media/host-sfu-route.ts";import { ViewerSfuRoute } from "../src/client/media/viewer-sfu-route.ts";import { QUALITY_PROFILES } from "../src/client/media/quality.ts";+import type { ConnectionMetrics } from "../src/client/types.ts";const peerAssignment = (parentPeerId: string,@@ -87,6 +88,8 @@ function createFakePublisher(log: string[], label: string) {interface FakeSubscriberEvents {onStream: (stream: MediaStream | null) => void;+ onStats?: (metrics: ConnectionMetrics) => void;+ onState?: (state: "connected" | "reconnecting") => void;onDisconnected: () => void;}@@ -947,6 +950,9 @@ describe("ViewerSfuRoute", () => {initialVideoStream: boolean;assignment: ParticipantRouteAssignment;}> = [];+ const sfuUpdates: Array<ConnectionMetrics | null> = [];+ const sfuStates: string[] = [];+ const metrics = {} as ConnectionMetrics;const subscribers: ReturnType<typeof createFakeSubscriber>[] = [];const route = new ViewerSfuRoute({activatePeer: (assignment) => {@@ -956,6 +962,8 @@ describe("ViewerSfuRoute", () => {onSfuStream: (stream, assignment, initialVideoStream) => {streams.push({ stream, assignment, initialVideoStream });},+ onSfuUpdate: (update) => sfuUpdates.push(update),+ onSfuState: (state) => sfuStates.push(state),send: (message) => {messages.push(message);return true;@@ -1000,9 +1008,17 @@ describe("ViewerSfuRoute", () => {revision: 2,phase: "active",});+ subscribers[0]?.events.onStats?.(metrics);+ subscribers[0]?.events.onState?.("reconnecting");+ expect(sfuUpdates).toEqual([]);+ expect(sfuStates).toEqual([]);const stream = {} as MediaStream;subscribers[0]?.events.onStream(stream);+ subscribers[0]?.events.onStats?.(metrics);+ subscribers[0]?.events.onState?.("reconnecting");+ expect(sfuUpdates).toEqual([metrics]);+ expect(sfuStates).toEqual(["reconnecting"]);expect(streams).toEqual([{ stream, assignment: nextAssignment, initialVideoStream: true },]);@@ -1034,6 +1050,13 @@ describe("ViewerSfuRoute", () => {await vi.waitFor(() => expect(subscribers[1]?.disconnect).toHaveBeenCalled());expect(subscribers[0]?.deactivate).not.toHaveBeenCalled();expect(streams).toHaveLength(1);++ await route.disconnect();+ expect(sfuUpdates).toEqual([metrics, null]);+ subscribers[0]?.events.onStats?.(metrics);+ subscribers[0]?.events.onState?.("connected");+ expect(sfuUpdates).toEqual([metrics, null]);+ expect(sfuStates).toEqual(["reconnecting"]);});it("disconnects a subscriber whose connect completes after rollback", async () => {diff --git a/tests/sfu-client.test.ts b/tests/sfu-client.test.tsindex cca9b05f..0d0d7aaf 100644--- a/tests/sfu-client.test.ts+++ b/tests/sfu-client.test.ts@@ -2,6 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { SfuPublisher } from "../src/client/sfu/publisher.ts";import { SfuSubscriber } from "../src/client/sfu/subscriber.ts";+import type { ConnectionMetrics } from "../src/client/types.ts";+import { mergeStatsReports } from "../src/client/webrtc/stats.ts";type EventHandler = (...args: unknown[]) => void;@@ -211,6 +213,8 @@ const livekit = vi.hoisted(() => {const RoomEvent = {Disconnected: "disconnected",ParticipantDisconnected: "participant-disconnected",+ Reconnected: "reconnected",+ Reconnecting: "reconnecting",TrackPublished: "track-published",TrackSubscribed: "track-subscribed",TrackUnpublished: "track-unpublished",@@ -269,6 +273,37 @@ function track(kind: "video" | "audio", id: string): MediaStreamTrack {return { id, kind } as MediaStreamTrack;}+function remoteTrack(+ mediaStreamTrack: MediaStreamTrack,+ getStats: () => RTCStatsReport | Promise<RTCStatsReport> = () =>+ new Map() as unknown as RTCStatsReport,+) {+ return {+ mediaStreamTrack,+ getRTCStatsReport: vi.fn(async () => getStats()),+ };+}++function statsReport(+ records: Array<Record<string, unknown> & { id: string }>,+): RTCStatsReport {+ return new Map(+ records.map((record) => [record.id, record]),+ ) as unknown as RTCStatsReport;+}++function receiverReport(kind: "video" | "audio"): RTCStatsReport {+ return statsReport([+ {+ id: `${kind}-in`,+ type: "inbound-rtp",+ timestamp: 1_000,+ kind,+ trackIdentifier: `${kind}-1`,+ },+ ]);+}+function stream(...tracks: MediaStreamTrack[]): MediaStream {return new FakeMediaStream(tracks) as unknown as MediaStream;}@@ -778,7 +813,7 @@ describe("SfuSubscriber", () => {const audio = track("audio", "audio-1");room.emit(RoomEvent.TrackSubscribed,- { mediaStreamTrack: audio },+ remoteTrack(audio),hostAudio,host,);@@ -787,7 +822,7 @@ describe("SfuSubscriber", () => {const video = track("video", "video-1");room.emit(RoomEvent.TrackSubscribed,- { mediaStreamTrack: video },+ remoteTrack(video),hostVideo,host,);@@ -800,6 +835,77 @@ describe("SfuSubscriber", () => {expect(room.disconnect).not.toHaveBeenCalled();});+ it("reports merged receiver stats and drops a stale sample", async () => {+ const updates: ConnectionMetrics[] = [];+ const states: string[] = [];+ const subscriber = new SfuSubscriber({+ onStream: vi.fn(),+ onStats: (metrics) => updates.push(metrics),+ onState: (state) => states.push(state),+ });+ await subscriber.connect(connection);+ const room = livekit.state.rooms[0];+ const host = new livekit.FakeRemoteParticipant("host");+ const hostVideo = new livekit.FakeRemotePublication(+ "host-video",+ Track.Source.ScreenShare,+ );+ const hostAudio = new livekit.FakeRemotePublication(+ "host-audio",+ Track.Source.ScreenShareAudio,+ );+ host.add(hostVideo).add(hostAudio);+ room.remoteParticipants.set("host", host);+ expect(subscriber.activate()).toBe(true);++ const reports = {+ video: receiverReport("video"),+ audio: receiverReport("audio"),+ };+ expect(+ Array.from(mergeStatsReports([reports.video, reports.audio])!.keys()),+ ).toEqual(["video-in", "audio-in"]);+ const video = track("video", "video-1");+ const audio = track("audio", "audio-1");+ let videoStats: RTCStatsReport | Promise<RTCStatsReport> = reports.video;+ const remoteVideo = remoteTrack(video, () => videoStats);+ room.emit(+ RoomEvent.TrackSubscribed,+ remoteTrack(audio, () => reports.audio),+ hostAudio,+ host,+ );+ room.emit(+ RoomEvent.TrackSubscribed,+ remoteVideo,+ hostVideo,+ host,+ );+ await vi.waitFor(() => expect(updates).toHaveLength(1));++ expect(updates.at(-1)).toMatchObject({+ rtpStatsId: "video-in",+ trackIdentifier: "video-1",+ });++ let releaseStats = (): void => undefined;+ videoStats = new Promise<RTCStatsReport>((resolve) => {+ releaseStats = () => resolve(reports.video);+ });+ room.emit(RoomEvent.Reconnecting);+ room.emit(RoomEvent.Reconnected);+ expect(states).toEqual(["reconnecting", "connected"]);+ await vi.waitFor(() =>+ expect(remoteVideo.getRTCStatsReport).toHaveBeenCalledTimes(2),+ );++ expect(subscriber.deactivate()).toBe(true);+ releaseStats();+ await Promise.resolve();+ await Promise.resolve();+ expect(updates).toHaveLength(1);+ });+it("notifies the controller after a terminal room disconnect", async () => {const disconnected = vi.fn();const subscriber = new SfuSubscriber({