/** * Streaming PCM16 playback (contract: 24 kHz mono PCM16LE output, no WAV header). * * Bounded playout queue. The cap is on OUTSTANDING SOURCE PCM — BOUND_BYTES (96,000 bytes * = 48,000 source samples ≈ 2 s at 24 kHz mono PCM16) — and each stage uses ONE unit * consistently: * admission + progress are booked in SOURCE samples (the contract/wire unit); * the ring stores the RESAMPLED OUTPUT samples the AudioContext actually consumes. * The output ring is sized to hold the source bound at the worst-case ratio * (source bound ÷ ratio), so the SAME 2 s source cap holds at any real context rate * (24k / 44.1k / 48k …) without widening the source limit, suppressing overflow or * silently dropping PCM. If the queue fills anyway the processor posts `overflow` and the * call fails safely. * * Real playback progress: played_ms for a server audio_ref is the cumulative SOURCE * samples of THAT ref actually consumed by process(), never a timer. Queued audio keeps * its own audio_ref when a different ref arrives (a FIFO of per-ref source spans), so * progress is never credited to the wrong turn. Reported ~4×/s, on ref completion, and on * clear/flush/idle, so the main thread can send the contract's playback_progress message. * * Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate, audioRef } * { type: 'clear' } barge-in: drop everything immediately * { type: 'flush' } end of turn: play what is left, then report 'idle' * Messages out: { type: 'progress', audioRef, playedMs } * { type: 'idle' } buffer ran dry after playing * { type: 'overflow' } bounded queue filled — caller fails the session safely */ const BOUND_BYTES = 96000; // contract cap on outstanding SOURCE PCM16 const RESAMPLE_MARGIN = 64; // slack for fractional-boundary rounding (never widens the source bound) const REPORT_INTERVAL_MS = 250; class PcmPlaybackProcessor extends AudioWorkletProcessor { constructor() { super(); this.sourceCapacity = Math.floor(BOUND_BYTES / 2); // 48,000 SOURCE samples (the admission bound) this.ratio = 1; // SOURCE samples per OUTPUT sample (resolved on first push) this.sized = false; // true once the output ring matches the real context rate this.capacity = this.sourceCapacity; // OUTPUT slots currently allocated (grows for upsampling) this.buf = new Float32Array(this.capacity); this.r = 0; this.w = 0; this.count = 0; // OUTPUT samples currently queued this.queuedSource = 0; // SOURCE samples currently queued (the admission bound unit) this.prebuffer = Math.floor(sampleRate * 0.08); // jitter buffer before (re)starting this.started = false; this.prev = 0; this.pos = 1; // Per-audio_ref attribution. `refQueue` keeps the still-queued SOURCE span of each ref // (merged per ref so it stays ≤ the number of turns); `refPlayedSamples` keeps each // ref's cumulative consumed source. Together they tie queued audio to its own ref and // keep progress cumulative and correct across ref changes. this.refQueue = []; // [{ ref, src }] src = remaining SOURCE samples of that ref this.refPlayedSamples = new Map(); this.playingRef = null; // ref currently being consumed / reported this.unreportedSamples = 0; this.overflowPosted = false; this.port.onmessage = (e) => { const m = e.data; if (!m) return; if (m.type === 'push') this.push(new Int16Array(m.pcm), m.sampleRate, m.audioRef || null); else if (m.type === 'clear') this.clear(); else if (m.type === 'flush') this.flush(); }; } /** Resolve the source→output ratio and size the output ring to hold the source bound. */ configure(ratio) { if (this.sized && ratio === this.ratio) return; this.ratio = ratio > 0 ? ratio : 1; const need = Math.ceil(this.sourceCapacity / this.ratio) + RESAMPLE_MARGIN; // Only grow while the ring is empty (first push): never drop queued audio. if (need > this.capacity && this.count === 0) { this.capacity = need; this.buf = new Float32Array(this.capacity); this.r = 0; this.w = 0; } this.sized = true; } clear() { this.reportFinal(); // final cumulative report for the interrupted ref this.r = this.w = this.count = 0; this.queuedSource = 0; this.refQueue.length = 0; this.started = false; this.prev = 0; this.pos = 1; this.playingRef = null; } flush() { if (this.count === 0) { this.started = false; this.reportFinal(); this.port.postMessage({ type: 'idle' }); } else { this.started = true; // short tail: do not wait for the prebuffer } } push(int16, srcRate, audioRef) { const n = int16.length; if (!n) return; const ratio = srcRate / sampleRate; // SOURCE samples per OUTPUT sample this.configure(ratio); // OUTPUT samples this chunk will add — the exact count the resample loop performs. const produced = this.pos < n ? Math.ceil((n - this.pos) / this.ratio) : 0; // Bounded queue — two consistent guards, each in its own unit: // 1) SOURCE bound: the contract 96,000-byte cap, invariant across context rates. if (this.queuedSource + n > this.sourceCapacity) return this.overflow(); // 2) OUTPUT storage: never let the ring overrun because a chunk resampled larger. if (this.count + produced > this.capacity) return this.overflow(); this.queuedSource += n; // Keep the audio_ref of the queued source span so consumption is credited correctly // even when the next ref arrives while this one is still playing. const last = this.refQueue[this.refQueue.length - 1]; if (last && last.ref === audioRef) last.src += n; else this.refQueue.push({ ref: audioRef, src: n }); const src = new Float32Array(n + 1); src[0] = this.prev; for (let i = 0; i < n; i++) src[i + 1] = int16[i] / 32768; let pos = this.pos; while (pos < n) { const i = Math.floor(pos); const frac = pos - i; this.write(src[i] * (1 - frac) + src[i + 1] * frac); pos += this.ratio; } this.prev = src[n]; this.pos = pos - n; } overflow() { if (!this.overflowPosted) { this.overflowPosted = true; this.port.postMessage({ type: 'overflow' }); } } write(v) { // Defense in depth: admission already reserves the room, so this never discards in // normal flow — but it guarantees the ring is never overwritten nor exceeds capacity. if (this.count >= this.capacity) return; this.buf[this.w] = v; this.w = (this.w + 1) % this.capacity; this.count++; } process(inputs, outputs) { const out = outputs[0]; const ch0 = out[0]; if (!this.started && this.count >= this.prebuffer) this.started = true; if (this.started) { let played = 0; for (let i = 0; i < ch0.length; i++) { if (this.count > 0) { ch0[i] = this.buf[this.r]; this.r = (this.r + 1) % this.capacity; this.count--; played++; } else { ch0[i] = 0; } } if (played > 0) { const consumedSource = played * this.ratio; // OUTPUT played → SOURCE consumed this.queuedSource = Math.max(0, this.queuedSource - consumedSource); this.consumeSpans(consumedSource); this.reportCadence(); } if (this.count === 0) { this.started = false; this.reportFinal(); this.port.postMessage({ type: 'idle' }); } } else { ch0.fill(0); } for (let c = 1; c < out.length; c++) out[c].set(ch0); return true; } /** Draw `amount` SOURCE samples off the front of the ref FIFO, crediting each ref. */ consumeSpans(amount) { while (amount > 1e-6 && this.refQueue.length) { const span = this.refQueue[0]; const take = amount < span.src ? amount : span.src; span.src -= take; amount -= take; this.creditRef(span.ref, take); if (span.src <= 1e-6) { this.refQueue.shift(); this.postProgress(span.ref); // ref finished: post its final cumulative before the next ref } } } creditRef(ref, sourceSamples) { this.refPlayedSamples.set(ref, (this.refPlayedSamples.get(ref) ?? 0) + sourceSamples); this.playingRef = ref; this.unreportedSamples += sourceSamples; } /** Final cumulative report for the ref currently playing (interruption / drain / clear). */ reportFinal() { this.unreportedSamples = 0; if (!this.playingRef) return; this.postProgress(this.playingRef); } /** Cadence report for the ref currently playing (~REPORT_INTERVAL_MS of consumed source). */ reportCadence() { if (!this.playingRef) return; const srcRate = this.ratio * sampleRate; if ((this.unreportedSamples / srcRate) * 1000 >= REPORT_INTERVAL_MS) { this.reportFinal(); } } postProgress(ref) { const playedSamples = this.refPlayedSamples.get(ref) ?? 0; const srcRate = this.ratio * sampleRate; // floor: never claims an unheard millisecond; monotonic because it is cumulative. const playedMs = Math.floor((playedSamples / srcRate) * 1000); if (playedMs <= 0) return; this.port.postMessage({ type: 'progress', audioRef: ref, playedMs }); } } registerProcessor('pcm-playback', PcmPlaybackProcessor);