feat(voice): enhance streaming engine and improve system reliability
Improve the PCM playback worklet with robust resampling and buffer management. Refactor the voice-stream service for better session teardown and error handling. Fix authentication issues by enabling credentials in HttpService and using relative URLs. Add Jalali date support and an AI model configuration tab in settings. Enhance diagnostics for voice transport and the audio engine.
This commit is contained in:
@@ -1,40 +1,57 @@
|
||||
/**
|
||||
* Streaming PCM16 playback (contract: 24 kHz mono PCM16LE output, no WAV header).
|
||||
*
|
||||
* Bounded playout queue: at most BOUND_SAMPLES (96,000 bytes) of source audio is admitted.
|
||||
* When it fills, the processor reports `overflow` and the call must fail safely — PCM is
|
||||
* never silently dropped to keep the same context alive.
|
||||
* 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` is computed from the source samples actually
|
||||
* consumed by `process()` per audio_ref (never an elapsed timer), kept cumulative per ref
|
||||
* and reported roughly 4×/s, on ref changes, and on clear/flush/idle — so the main thread
|
||||
* can send the contract's `playback_progress` control message.
|
||||
* 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: 'idle' } buffer ran dry after playing
|
||||
* { type: 'overflow' } bounded queue filled — caller fails the session safely
|
||||
*/
|
||||
const BOUND_BYTES = 96000; // contract cap for the playback queue
|
||||
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.capacity = Math.floor(BOUND_BYTES / 2); // source samples (PCM16)
|
||||
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;
|
||||
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;
|
||||
this.ratio = 1; // source samples per output sample, set per push
|
||||
this.currentRef = null;
|
||||
this.refPlayedSamples = new Map(); // cumulative consumed source samples per audio_ref
|
||||
// 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) => {
|
||||
@@ -46,18 +63,36 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
};
|
||||
}
|
||||
|
||||
/** 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.reportProgress(true); // final report for the interrupted ref
|
||||
this.playingRef = null;
|
||||
}
|
||||
|
||||
flush() {
|
||||
if (this.count === 0) {
|
||||
this.started = false;
|
||||
this.reportProgress(true);
|
||||
this.reportFinal();
|
||||
this.port.postMessage({ type: 'idle' });
|
||||
} else {
|
||||
this.started = true; // short tail: do not wait for the prebuffer
|
||||
@@ -68,16 +103,26 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
const n = int16.length;
|
||||
if (!n) return;
|
||||
|
||||
// Bounded queue: admitting this chunk past the cap is a safe failure, not a silent drop.
|
||||
if (this.count + n > this.capacity) {
|
||||
if (!this.overflowPosted) {
|
||||
this.overflowPosted = true;
|
||||
this.port.postMessage({ type: 'overflow' });
|
||||
}
|
||||
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 });
|
||||
|
||||
this.ratio = srcRate / sampleRate; // source samples per output sample
|
||||
const src = new Float32Array(n + 1);
|
||||
src[0] = this.prev;
|
||||
for (let i = 0; i < n; i++) src[i + 1] = int16[i] / 32768;
|
||||
@@ -91,15 +136,19 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
}
|
||||
this.prev = src[n];
|
||||
this.pos = pos - n;
|
||||
}
|
||||
|
||||
if (audioRef !== this.currentRef) {
|
||||
this.reportProgress(true); // final report for the ref that just ended
|
||||
this.currentRef = audioRef;
|
||||
this.reportProgress(true);
|
||||
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++;
|
||||
@@ -123,20 +172,15 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
ch0[i] = 0;
|
||||
}
|
||||
}
|
||||
if (this.currentRef && played > 0) {
|
||||
// Convert consumed output samples back to contract (source) samples.
|
||||
const consumed = played * this.ratio;
|
||||
const ref = this.currentRef;
|
||||
this.refPlayedSamples.set(ref, (this.refPlayedSamples.get(ref) ?? 0) + consumed);
|
||||
this.unreportedSamples += consumed;
|
||||
const srcRate = this.ratio * sampleRate;
|
||||
if ((this.unreportedSamples / srcRate) * 1000 >= REPORT_INTERVAL_MS) {
|
||||
this.reportProgress(false);
|
||||
}
|
||||
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.reportProgress(true);
|
||||
this.reportFinal();
|
||||
this.port.postMessage({ type: 'idle' });
|
||||
}
|
||||
} else {
|
||||
@@ -147,14 +191,49 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
return true;
|
||||
}
|
||||
|
||||
reportProgress(force) {
|
||||
/** 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;
|
||||
const ref = this.currentRef;
|
||||
if (!ref) return;
|
||||
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 playedMs = Math.max(0, Math.round((playedSamples / srcRate) * 1000));
|
||||
if (playedMs <= 0) return; // nothing has actually been heard for this ref yet
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user