/** * Playback buffer policy for the WebSocket compatibility path. * * Cloudflare Tunnel turns steady 20 ms frames into bursts. A mean/EWMA jitter * estimate hides those bursts behind a comfortably large average and then * still underruns on the tail, so the adaptive player uses a windowed p95 of * the audio-clock deviation instead. The target rises quickly when the tunnel * is late and decays slowly, which trades a little latency for far fewer * audible gaps. */ export const MIN_TARGET_AHEAD_MS = 80; export const MAX_TARGET_AHEAD_MS = 300; export const MAX_BUFFER_AHEAD_SETTING_MS = 500; const JITTER_WINDOW_SAMPLES = 100; const JITTER_WINDOW_MS = 2_000; const TARGET_JITTER_MS = 60; const MAX_OBSERVED_JITTER_MS = 500; const TARGET_RISE_PER_UPDATE_MS = 40; const TARGET_FALL_PER_STEP_MS = 2; const TARGET_FALL_INTERVAL_MS = 2_000; const SILENCE_RESET_MS = 200; /** Target play-ahead for a measured p95 jitter; 0 ms maps to the 80 ms floor. */ export function computeTargetAheadMs(jitterMs: number, maxMs = MAX_TARGET_AHEAD_MS): number { const boundedMax = Math.max( MIN_TARGET_AHEAD_MS, Math.min(MAX_BUFFER_AHEAD_SETTING_MS, Number.isFinite(maxMs) ? maxMs : MAX_TARGET_AHEAD_MS), ); const boundedJitter = Math.max(0, Math.min(MAX_OBSERVED_JITTER_MS, Number.isFinite(jitterMs) ? jitterMs : 0)); return Math.min(boundedMax, Math.max(MIN_TARGET_AHEAD_MS, TARGET_JITTER_MS + boundedJitter)); } /** * Tracks the difference between arrival spacing and audio-clock spacing. The * audio clock is carried in every v3 batch, so this needs no wall-clock sync * between the gateway and the browser. */ export class JitterEstimator { private samples: { at: number; value: number }[] = []; private lastAudioStartMs: number | null = null; private lastArrivalAt: number | null = null; private currentTargetMs = MIN_TARGET_AHEAD_MS; private lastDecreaseAt = 0; private p95 = 0; /** * Record one batch arrival. `audioStartMs` is the sender's audio clock; * `arrivalAt` defaults to `performance.now()`. */ observe(audioStartMs: number, arrivalAt = performance.now(), maxMs = MAX_TARGET_AHEAD_MS): number { if (!Number.isFinite(audioStartMs) || !Number.isFinite(arrivalAt)) return this.targetAheadMs(maxMs); if (this.lastAudioStartMs !== null && this.lastArrivalAt !== null) { const audioDelta = audioStartMs - this.lastAudioStartMs; if (audioDelta < -1_000 || audioDelta > 5_000) { // Sender restart or a huge clock jump: start a fresh window. this.resetWindow(); } else { const deviation = (arrivalAt - this.lastArrivalAt) - audioDelta; // Early delivery does not need a larger buffer; only late delivery does. this.push(Math.max(0, Math.min(MAX_OBSERVED_JITTER_MS, deviation)), arrivalAt); } } this.lastAudioStartMs = audioStartMs; this.lastArrivalAt = arrivalAt; this.recomputeTarget(maxMs, arrivalAt); return this.targetAheadMs(maxMs); } /** A long silence invalidates inter-arrival spacing; keep the target but reset the window. */ noteSilence(gapMs: number): void { if (gapMs >= SILENCE_RESET_MS) this.resetWindow(); } targetAheadMs(maxMs = MAX_TARGET_AHEAD_MS): number { const boundedMax = Math.max( MIN_TARGET_AHEAD_MS, Math.min(MAX_BUFFER_AHEAD_SETTING_MS, Number.isFinite(maxMs) ? maxMs : MAX_TARGET_AHEAD_MS), ); return Math.min(boundedMax, Math.max(MIN_TARGET_AHEAD_MS, Math.round(this.currentTargetMs))); } /** Current p95 deviation, useful for diagnostics. */ get jitter(): number { return this.p95; } reset(): void { this.resetWindow(); this.currentTargetMs = MIN_TARGET_AHEAD_MS; this.lastDecreaseAt = 0; this.p95 = 0; } private resetWindow(): void { this.samples = []; this.lastAudioStartMs = null; this.lastArrivalAt = null; } private push(value: number, at: number): void { this.samples.push({ at, value }); while (this.samples.length > JITTER_WINDOW_SAMPLES || (this.samples[0] && at - this.samples[0].at > JITTER_WINDOW_MS)) { this.samples.shift(); } } private recomputeTarget(maxMs: number, now: number): void { if (this.samples.length === 0) { this.p95 = 0; return; } const sorted = this.samples.map(sample => sample.value).sort((left, right) => left - right); this.p95 = sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * 0.95))] ?? 0; const desired = computeTargetAheadMs(this.p95, maxMs); if (desired > this.currentTargetMs) { this.currentTargetMs = Math.min(desired, this.currentTargetMs + TARGET_RISE_PER_UPDATE_MS); this.lastDecreaseAt = now; return; } if (now - this.lastDecreaseAt >= TARGET_FALL_INTERVAL_MS) { this.currentTargetMs = Math.max(desired, this.currentTargetMs - TARGET_FALL_PER_STEP_MS); this.lastDecreaseAt = now; } } } /** A large positive overrun: re-anchor only, never tear down the decoder. */ export function shouldResetSchedule(aheadMs: number, targetMs: number): boolean { return aheadMs > targetMs + 300; } /** The play head is close to real time; pull it back to the target. */ export function shouldRecover(aheadMs: number): boolean { return aheadMs < 20; }