import { currentCandidateGeneration, linearCandidateTuple } from "../webrtc/linear-ice-candidate"; import type { NatTraversalPath } from "../../shared/nat-candidate"; import { browserDebugEnabled, debugError, debugEvent, registerDebugCollector } from "./debug"; import { isPredictedCandidateFoundation } from "../../shared/nat-candidate"; const connections = new WeakMap(); const linearCandidates = new WeakMap(); export function recordLinearCandidate(connection: RTCPeerConnection, candidate: RTCIceCandidateInit): void { const known = linearCandidates.get(connection) ?? []; if (known.length < 16) { known.push(candidate); linearCandidates.set(connection, known); } } /** Match actual selected stats to admitted hypotheses, never rewrite ICE foundations. */ export function remoteCandidateTraversalPath(connection: RTCPeerConnection | undefined, remote: Record | null | undefined): NatTraversalPath { const known = connection && linearCandidates.get(connection); if (known?.length) { const address = remote?.address ?? remote?.ip; if (typeof address !== "string" || typeof remote?.port !== "number" || typeof remote.protocol !== "string") return "unknown"; const tuple = JSON.stringify([remote.protocol.toLowerCase(), address, remote.port]); const matching = known.filter(candidate => linearCandidateTuple(candidate) === tuple); if (matching.length) return matching.some(candidate => currentCandidateGeneration(connection!, candidate) && (remote.usernameFragment == null || remote.usernameFragment === candidate.usernameFragment)) ? "predicted" : "unknown"; } return typeof remote?.foundation !== "string" ? "unknown" : isPredictedCandidateFoundation(remote.foundation) ? "predicted" : "ordinary"; } const statsTypes = new Set([ "codec", "inbound-rtp", "outbound-rtp", "remote-inbound-rtp", "remote-outbound-rtp", "media-source", "transport", "candidate-pair", "local-candidate", "remote-candidate", ]); // Observe existing connection owners and their existing statistics samples. // These listeners add no polling or transport actions. export function observeDebugConnection(connection: RTCPeerConnection, identity: object): () => void { if (!browserDebugEnabled) return () => { linearCandidates.delete(connection); }; connections.set(connection, identity); const live = () => connection.connectionState !== "closed"; const release = registerDebugCollector("webrtc", async () => { if (!live()) return; const report = await connection.getStats(); if (live()) debugRtcStats(connection, report); }); const transports = new Set(); const snapshot = (event: string) => { try { debugEvent("webrtc", event, { ...identity, connectionState: connection.connectionState, iceConnectionState: connection.iceConnectionState, iceGatheringState: connection.iceGatheringState, signalingState: connection.signalingState }); for (const endpoint of [...connection.getSenders(), ...connection.getReceivers()]) { const transport = endpoint.transport; if (!transport || transports.has(transport)) continue; transports.add(transport); const state = () => debugEvent("webrtc", "dtls-state", { ...identity, state: transport.state }); transport.addEventListener("statechange", state); state(); } } catch (error) { debugError("webrtc", "collector-failed", error, { ...identity, collector: "connection-state" }); } }; for (const event of ["connectionstatechange", "iceconnectionstatechange", "icegatheringstatechange", "signalingstatechange", "track"]) { connection.addEventListener(event, () => snapshot(event)); } connection.addEventListener("icecandidateerror", (event) => { debugEvent("webrtc", "ice-candidate-error", { ...identity, errorCode: event.errorCode, errorText: event.errorText, address: event.address, port: event.port, url: event.url }); }); snapshot("created"); return () => { linearCandidates.delete(connection); connections.delete(connection); release(); }; } const PLAYBACK_FRAME_SAMPLE_WAIT_MS = 250; export function observeDebugPlayback(video: HTMLVideoElement, context: () => { source: "screen" | "watch"; flowId?: string; selected: boolean; presentedFrame: boolean }): () => void { if (!browserDebugEnabled) return () => {}; const lifetime = new AbortController(); const unregister = registerDebugCollector("playback", async () => { if (lifetime.signal.aborted) return; const stream = video.srcObject, url = video.currentSrc; let presentedFrames: number | null = null; if (video.requestVideoFrameCallback && video.ownerDocument.visibilityState === "visible") { presentedFrames = await new Promise(resolve => { const handle = video.requestVideoFrameCallback((_now, metadata) => { lifetime.signal.removeEventListener("abort", cancel); clearTimeout(timer); resolve(metadata.presentedFrames ?? null); }); function cancel() { lifetime.signal.removeEventListener("abort", cancel); clearTimeout(timer); video.cancelVideoFrameCallback(handle); resolve(null); } const timer = setTimeout(cancel, PLAYBACK_FRAME_SAMPLE_WAIT_MS); lifetime.signal.addEventListener("abort", cancel); }); } if (lifetime.signal.aborted || video.srcObject !== stream || video.currentSrc !== url) return; const box = video.getBoundingClientRect(); const quality = video.getVideoPlaybackQuality?.(); const decoded = (video as HTMLVideoElement & { webkitDecodedFrameCount?: number }).webkitDecodedFrameCount; debugEvent("playback", "snapshot", { ...context(), displayWidth: box.width, displayHeight: box.height, presentedFrames, width: video.videoWidth, height: video.videoHeight, readyState: video.readyState, paused: video.paused, ended: video.ended, visibility: video.ownerDocument.visibilityState, decodedVideoFrames: decoded ?? null, totalVideoFrames: quality?.totalVideoFrames ?? null, droppedVideoFrames: quality?.droppedVideoFrames ?? null, }); }); return () => { lifetime.abort(); unregister(); }; } export function debugRtcStats(connection: RTCPeerConnection, report: RTCStatsReport): void { if (!browserDebugEnabled) return; const identity = connections.get(connection); if (!identity) return; const stats: object[] = []; report.forEach((record) => { if (statsTypes.has(record.type)) stats.push(record); }); // Preserve a small connectivity summary before the bounded raw array. With // many interfaces, raw pairs can otherwise push the selected path past it. const pairs = { total: 0, waiting: 0, "in-progress": 0, succeeded: 0, failed: 0, frozen: 0, unknown: 0 }; const selected: object[] = []; report.forEach((record) => { if (record.type === "candidate-pair") { pairs.total++; const state = record.state as keyof typeof pairs; pairs[Object.hasOwn(pairs, state) && state !== "total" ? state : "unknown"]++; } if (record.type !== "transport" || typeof record.selectedCandidatePairId !== "string") return; const pair = report.get(record.selectedCandidatePairId); if (pair?.type !== "candidate-pair") return; const local = report.get(pair.localCandidateId), remote = report.get(pair.remoteCandidateId); selected.push({ state: pair.state ?? null, dtlsState: record.dtlsState ?? null, localType: local?.candidateType ?? null, remoteType: remote?.candidateType ?? null, protocol: local?.protocol ?? null, natTraversalPath: remoteCandidateTraversalPath(connection, remote), requestsSent: pair.requestsSent ?? null, responsesReceived: pair.responsesReceived ?? null, currentRoundTripTime: pair.currentRoundTripTime ?? null, }); }); debugEvent("webrtc", "stats", { ...identity, ice: { pairs, selected }, stats }); } export function debugRtcFailure(connection: RTCPeerConnection, error: unknown): void { if (browserDebugEnabled) debugError("webrtc", "collector-failed", error, { ...connections.get(connection), collector: "getStats" }); } export function debugTrack(track: MediaStreamTrack, details: object = {}): void { if (!browserDebugEnabled) return; try { const stats = track.kind === "video" ? (track as MediaStreamTrack & { stats?: { deliveredFrames: number; discardedFrames: number; totalFrames: number } | null; }).stats : null; debugEvent("capture", "track", { ...details, trackId: track.id, kind: track.kind, state: track.readyState, enabled: track.enabled, muted: track.muted, contentHint: track.contentHint, settings: track.getSettings(), constraints: track.getConstraints(), ...(stats ? { videoFrameStats: { deliveredFrames: stats.deliveredFrames, discardedFrames: stats.discardedFrames, totalFrames: stats.totalFrames } } : {}) }); } catch (error) { debugError("capture", "collector-failed", error, { collector: "track", trackId: track.id }); } }