feat(voice): enhance audio stream lifecycle with sent_bytes validation and ref-attributed idle tracking

This commit is contained in:
amirhosein mazaheri
2026-10-12 18:51:05 +03:30
parent 89c6bc6d44
commit 58c3c20933
8 changed files with 344 additions and 102 deletions
@@ -27,9 +27,9 @@
*
* Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate, audioRef }
* { type: 'clear' } barge-in: drop everything immediately
* { type: 'flush' } end of turn: emit the tail, play what is left, then idle
* { type: 'flush', audioRef } end of turn: emit the tail, play what is left, then idle
* Messages out: { type: 'progress', audioRef, playedMs }
* { type: 'idle' } buffer ran dry after playing
* { 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
@@ -74,7 +74,7 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
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();
else if (m.type === 'flush') this.flush(m.audioRef);
};
}
@@ -110,12 +110,12 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
this.playingRef = null;
}
flush() {
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' });
this.port.postMessage({ type: 'idle', audioRef: audioRef || this.pendingRef });
} else {
this.started = true; // play the remaining audio + tail without waiting for the prebuffer
}
@@ -260,7 +260,7 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
this.queuedSource = 0;
this.started = false;
this.reportFinal();
this.port.postMessage({ type: 'idle' });
this.port.postMessage({ type: 'idle', audioRef: this.pendingRef });
}
} else {
ch0.fill(0);