fix(voice): handle exact consumed-sample progress and direct native-rate playback

This commit is contained in:
amirhosein mazaheri
2026-10-12 17:51:52 +03:30
parent b3eb4a6de5
commit 97427a1581
2 changed files with 63 additions and 12 deletions
+24 -12
View File
@@ -32,22 +32,22 @@
* { type: 'idle' } buffer ran dry after playing * { type: 'idle' } buffer ran dry after playing
* { type: 'overflow' } bounded queue filled — caller fails the session safely * { type: 'overflow' } bounded queue filled — caller fails the session safely
*/ */
const BOUND_BYTES = 96000; // contract cap on outstanding SOURCE PCM16 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 RESAMPLE_MARGIN = 64; // slack for fractional-boundary rounding (never widens the source bound)
const REPORT_INTERVAL_MS = 250; const REPORT_INTERVAL_MS = 250;
class PcmPlaybackProcessor extends AudioWorkletProcessor { class PcmPlaybackProcessor extends AudioWorkletProcessor {
constructor() { constructor() {
super(); super();
this.sourceCapacity = Math.floor(BOUND_BYTES / 2); // 48,000 SOURCE samples (admission bound) 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.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.sized = false; // true once the output ring matches the real context rate
this.capacity = this.sourceCapacity; // OUTPUT slots currently allocated (grows for upsampling) this.capacity = this.sourceCapacity; // OUTPUT slots currently allocated (grows for upsampling)
this.buf = new Float32Array(this.capacity); this.buf = new Float32Array(this.capacity);
this.r = 0; this.r = 0;
this.w = 0; this.w = 0;
this.count = 0; // OUTPUT samples currently queued this.count = 0; // OUTPUT samples currently queued
this.queuedSource = 0; // SOURCE samples currently queued (the admission bound unit) this.queuedSource = 0; // SOURCE samples currently queued (the admission bound unit)
this.prebuffer = Math.floor(sampleRate * 0.08); // jitter buffer before (re)starting this.prebuffer = Math.floor(sampleRate * 0.08); // jitter buffer before (re)starting
this.started = false; this.started = false;
this.prev = 0; this.prev = 0;
@@ -56,17 +56,17 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
// `emittedOut` let flush() emit the exact OUTPUT count for all admitted source; the last // `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. // chunk window is retained so the tail can be interpolated correctly.
this.admittedSrc = 0; // SOURCE samples admitted this turn this.admittedSrc = 0; // SOURCE samples admitted this turn
this.emittedOut = 0; // OUTPUT samples emitted for them so far this.emittedOut = 0; // OUTPUT samples emitted for them so far
this.windowSrc = null; // last chunk's src window (for tail interpolation) this.windowSrc = null; // last chunk's src window (for tail interpolation)
this.windowN = 0; this.windowN = 0;
// Per-audio_ref attribution. `refQueue` keeps the still-queued OUTPUT span of each ref // 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 // (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 // cumulative OUTPUT samples consumed. Together they tie queued audio to its own ref and
// keep progress cumulative and correct across ref changes. // keep progress cumulative and correct across ref changes.
this.refQueue = []; // [{ ref, out }] out = remaining OUTPUT samples of that ref this.refQueue = []; // [{ ref, out }] out = remaining OUTPUT samples of that ref
this.refPlayedOut = new Map(); this.refPlayedOut = new Map();
this.playingRef = null; // ref currently being consumed / reported 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.pendingRef = null; // audio_ref of the most recent push (the one flush() tail belongs to)
this.unreportedOut = 0; this.unreportedOut = 0;
this.overflowPosted = false; this.overflowPosted = false;
this.port.onmessage = (e) => { this.port.onmessage = (e) => {
@@ -162,7 +162,8 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
this.configure(ratio); this.configure(ratio);
// OUTPUT samples this chunk's main loop will add — an upper bound on the exact count. // OUTPUT samples this chunk's main loop will add — an upper bound on the exact count.
const produced = this.pos < n ? Math.ceil((n - this.pos) / this.ratio) : 0; 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: // Bounded queue — two consistent guards, each in its own unit:
// 1) SOURCE bound: the contract 96,000-byte cap, invariant across context rates. // 1) SOURCE bound: the contract 96,000-byte cap, invariant across context rates.
@@ -173,6 +174,16 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
this.queuedSource += n; this.queuedSource += n;
this.admittedSrc += n; // every admitted source sample must eventually become output 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); const src = new Float32Array(n + 1);
src[0] = this.prev; src[0] = this.prev;
for (let i = 0; i < n; i++) src[i + 1] = int16[i] / 32768; for (let i = 0; i < n; i++) src[i + 1] = int16[i] / 32768;
@@ -296,7 +307,8 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
// OUTPUT samples at the context rate → milliseconds; floor never claims an unheard ms and // 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 // stays monotonic because it is cumulative. Output-time equals source-time (SRC preserves
// duration), so this equals the contract's played source / srcRate. // duration), so this equals the contract's played source / srcRate.
const playedMs = Math.floor((playedOut / sampleRate) * 1000); // Multiply integer counts first to avoid rounding an exact whole millisecond down.
const playedMs = Math.floor((playedOut * 1000) / sampleRate);
if (playedMs <= 0) return; if (playedMs <= 0) return;
this.port.postMessage({ type: 'progress', audioRef: ref, playedMs }); this.port.postMessage({ type: 'progress', audioRef: ref, playedMs });
} }
@@ -150,6 +150,45 @@ describe('pcm-playback.worklet', () => {
expect(peakSource).toBeLessThan(proc.sourceCapacity); expect(peakSource).toBeLessThan(proc.sourceCapacity);
}); });
describe('exact consumed-sample progress', () => {
it('plays the 364800-byte incident fully before generation ends at 24 kHz', async () => {
const proc = await loadPlaybackProcessor(24000);
for (let chunk = 0; chunk < 38; chunk++) {
push(proc, frame(chunk * 4800, 4800), 'aud-incident');
drain(proc, 128);
}
// No audio_ended/flush: every native-rate sample can already be rendered.
expect(proc.refPlayedOut.get('aud-incident')).toBe(182400);
expect(playedFor(proc, 'aud-incident')).toBe(7600);
expect(proc.count).toBe(0);
expect(overflowCount(proc)).toBe(0);
});
it('renders native-rate PCM directly without an inserted leading sample', async () => {
const proc = await loadPlaybackProcessor(24000);
const pcm = frame(200, 4800);
push(proc, pcm, 'aud-1');
const output = new Float32Array(128);
proc.process([[]], [[output]]);
expect(Array.from(output)).toEqual(Array.from(pcm.slice(0, 128), (v) => v / 32768));
expect(proc.refPlayedOut.get('aud-1')).toBe(128);
});
for (const rate of [24000, 48000]) {
it(`reports 1001 ms after rendering every sample at ${rate} Hz`, async () => {
const proc = await loadPlaybackProcessor(rate);
push(proc, frame(0, 24024), 'aud-1');
flush(proc);
drain(proc);
expect(proc.refPlayedOut.get('aud-1')).toBe((rate * 1001) / 1000);
expect(playedFor(proc, 'aud-1')).toBe(1001);
const values = proc.out.filter((m) => m.audioRef === 'aud-1').map((m) => m.playedMs ?? 0);
expect(values).toEqual([...values].sort((a, b) => a - b));
expect(values.every((ms) => ms <= 1001)).toBe(true);
});
}
});
describe('fractional resampling across chunk boundaries', () => { describe('fractional resampling across chunk boundaries', () => {
// 6,000 source samples = 250 ms at 24 kHz. A linear resampler carries ~1 sample of latency // 6,000 source samples = 250 ms at 24 kHz. A linear resampler carries ~1 sample of latency
// across a boundary, so reported progress is within 1 ms of 250 — but it must never // across a boundary, so reported progress is within 1 ms of 250 — but it must never