Files
faq_chatbot_frontend/public/assets/worklets/pcm-playback.worklet.js
T

318 lines
13 KiB
JavaScript

/**
* 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 is booked in SOURCE samples (the contract/wire unit);
* the ring stores the RESAMPLED OUTPUT samples the AudioContext actually consumes;
* PROGRESS is booked in OUTPUT samples (an integer the resampler fully controls), and
* rendered as milliseconds at the context rate. Because resampling preserves duration,
* output-time equals source-time, so this reports the same ms as source/srcRate — but it
* is exact (no float drift over thousands of iterations).
* 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.
*
* End-of-turn tail: the resample loop keeps the window's last sample as `prev` (for
* cross-chunk continuity) and only emits it at the start of the NEXT chunk. At the final
* chunk there is no next chunk, so without an explicit flush the last source sample is never
* emitted — queued source never reaches zero and played_ms under-reports by ~1 ms, which the
* backend reads as perpetual outstanding playback (a stall/overflow signature). `flush()`
* (raised on audio_ended) emits that deferred tail so every admitted source sample becomes
* output and fully played audio drains to exactly its real duration. `clear()` (barge-in)
* discards the tail instead, so interrupted audio is never credited as played.
*
* Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate, audioRef }
* { type: 'clear' } barge-in: drop everything immediately
* { type: 'flush', audioRef } end of turn: emit the tail, play what is left, then idle
* Messages out: { type: 'progress', audioRef, playedMs }
* { type: 'idle', audioRef } 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 (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;
// End-of-turn tail accounting (per turn, reset on flush/clear). `admittedSrc` +
// `emittedOut` let flush() emit the exact OUTPUT count for all admitted source; the last
// chunk window is retained so the tail can be interpolated correctly.
this.admittedSrc = 0; // SOURCE samples admitted this turn
this.emittedOut = 0; // OUTPUT samples emitted for them so far
this.windowSrc = null; // last chunk's src window (for tail interpolation)
this.windowN = 0;
// Per-audio_ref attribution. `refQueue` keeps the still-queued OUTPUT span of each ref
// (merged per ref so it stays ≤ the number of turns); `refPlayedOut` keeps each ref's
// cumulative OUTPUT samples consumed. Together they tie queued audio to its own ref and
// keep progress cumulative and correct across ref changes.
this.refQueue = []; // [{ ref, out }] out = remaining OUTPUT samples of that ref
this.refPlayedOut = new Map();
this.playingRef = null; // ref currently being consumed / reported
this.pendingRef = null; // audio_ref of the most recent push (the one flush() tail belongs to)
this.unreportedOut = 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(m.audioRef);
};
}
/** 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;
// Discard the deferred tail too: interrupted audio is NOT played, so it must not be
// credited or emitted.
this.admittedSrc = 0;
this.emittedOut = 0;
this.windowSrc = null;
this.windowN = 0;
this.playingRef = null;
}
flush(audioRef = this.pendingRef) {
this.finalizeTail(); // emit the deferred tail so every admitted sample becomes output
if (this.count === 0) {
this.started = false;
this.reportFinal();
this.port.postMessage({ type: 'idle', audioRef: audioRef || this.pendingRef });
} else {
this.started = true; // play the remaining audio + tail without waiting for the prebuffer
}
}
/**
* End-of-turn tail: emit the OUTPUT samples for every admitted SOURCE sample that the push
* loop deferred (it keeps the window's last sample as `prev` for cross-chunk continuity and
* only emits it at the start of the next chunk). Continuing the interpolation past the last
* sample — holding its value — produces real output so fully played audio leaves queued
* source at zero and played_ms reflects the true duration (never fabricated upward).
*/
finalizeTail() {
const src = this.windowSrc;
const n = this.windowN;
if (src && n > 0) {
const target = Math.round(this.admittedSrc / this.ratio); // exact OUTPUT count for the turn
let pos = n + this.pos; // continue from where the push loop stopped (abs. in this window)
while (this.emittedOut < target) {
const base = Math.min(Math.floor(pos), n);
const frac = Math.min(1, Math.max(0, pos - base));
const a = src[base];
const b = src[Math.min(base + 1, n)]; // clamp: hold the last sample past the boundary
this.write(a * (1 - frac) + b * frac);
this.creditQueue(1); // the emitted tail belongs to the current (last) ref
this.emittedOut++;
pos += this.ratio;
}
}
// Each turn is an independent signal: reset the resampler for the next one.
this.admittedSrc = 0;
this.emittedOut = 0;
this.windowSrc = null;
this.windowN = 0;
this.pos = 1;
this.prev = 0;
}
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's main loop will add — an upper bound on the exact count.
const produced =
this.ratio === 1 ? n : 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;
this.admittedSrc += n; // every admitted source sample must eventually become output
// Matching rates need no interpolation or deferred tail. Render every admitted
// sample even while generation is still open; progress reflects only consumed PCM.
if (this.ratio === 1) {
this.pendingRef = audioRef;
for (let i = 0; i < n; i++) this.write(int16[i] / 32768);
this.creditQueue(n);
this.emittedOut += n;
return;
}
const src = new Float32Array(n + 1);
src[0] = this.prev;
for (let i = 0; i < n; i++) src[i + 1] = int16[i] / 32768;
// Retain this window so flush() can emit the deferred tail correctly.
this.windowSrc = src;
this.windowN = n;
let pos = this.pos;
let mainOut = 0;
while (pos < n) {
const i = Math.floor(pos);
const frac = pos - i;
this.write(src[i] * (1 - frac) + src[i + 1] * frac);
mainOut++;
pos += this.ratio;
}
this.prev = src[n];
this.pos = pos - n;
this.emittedOut += mainOut;
this.pendingRef = audioRef;
this.creditQueue(mainOut); // attribute this chunk's OUTPUT to its audio_ref
}
/** Adds `out` OUTPUT samples to the current ref's span (merging consecutive same-ref pushes). */
creditQueue(out) {
const ref = this.pendingRef;
const last = this.refQueue[this.refQueue.length - 1];
if (last && last.ref === ref) last.out += out;
else this.refQueue.push({ ref, out });
}
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) {
this.queuedSource = Math.max(0, this.queuedSource - played * this.ratio); // OUTPUT→SOURCE
this.consumeSpans(played);
this.reportCadence();
}
if (this.count === 0) {
// Ring drained: nothing is outstanding, so no phantom source remains for this turn.
this.queuedSource = 0;
this.started = false;
this.reportFinal();
this.port.postMessage({ type: 'idle', audioRef: this.pendingRef });
}
} else {
ch0.fill(0);
}
for (let c = 1; c < out.length; c++) out[c].set(ch0);
return true;
}
/** Draw `played` OUTPUT samples off the front of the ref FIFO, crediting each ref. */
consumeSpans(played) {
while (played > 0 && this.refQueue.length) {
const span = this.refQueue[0];
const take = played < span.out ? played : span.out;
span.out -= take;
played -= take;
this.refPlayedOut.set(span.ref, (this.refPlayedOut.get(span.ref) ?? 0) + take);
this.playingRef = span.ref;
this.unreportedOut += take;
if (span.out <= 0) {
this.refQueue.shift();
this.postProgress(span.ref); // ref finished: post its final cumulative before the next ref
}
}
}
/** Final cumulative report for the ref currently playing (interruption / drain / clear). */
reportFinal() {
this.unreportedOut = 0;
if (!this.playingRef) return;
this.postProgress(this.playingRef);
}
/** Cadence report for the ref currently playing (~REPORT_INTERVAL_MS of consumed output). */
reportCadence() {
if (!this.playingRef) return;
if ((this.unreportedOut / sampleRate) * 1000 >= REPORT_INTERVAL_MS) {
this.reportFinal();
}
}
postProgress(ref) {
const playedOut = this.refPlayedOut.get(ref) ?? 0;
// OUTPUT samples at the context rate → milliseconds; floor never claims an unheard ms and
// stays monotonic because it is cumulative. Output-time equals source-time (SRC preserves
// duration), so this equals the contract's played source / srcRate.
// Multiply integer counts first to avoid rounding an exact whole millisecond down.
const playedMs = Math.floor((playedOut * 1000) / sampleRate);
if (playedMs <= 0) return;
this.port.postMessage({ type: 'progress', audioRef: ref, playedMs });
}
}
registerProcessor('pcm-playback', PcmPlaybackProcessor);