Add live voice playback diagnostics and sample accounting

This commit is contained in:
11linear11
2026-10-12 17:52:20 -04:00
parent 58c3c20933
commit 52202c2a35
4 changed files with 124 additions and 10 deletions
+11 -1
View File
@@ -95,6 +95,16 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
clear() { clear() {
this.reportFinal(); // final cumulative report for the interrupted ref this.reportFinal(); // final cumulative report for the interrupted ref
// Attribute queued output and the deferred tail to their real references.
const discarded = new Map();
for (const span of this.refQueue) {
discarded.set(span.ref, (discarded.get(span.ref) ?? 0) + span.out);
}
const tail = Math.max(0, Math.round(this.admittedSrc / this.ratio) - this.emittedOut);
if (tail > 0) discarded.set(this.pendingRef, (discarded.get(this.pendingRef) ?? 0) + tail);
for (const [audioRef, discardedSamples] of discarded) {
this.port.postMessage({ type: 'discarded', audioRef, discardedSamples, contextRate: sampleRate });
}
this.r = this.w = this.count = 0; this.r = this.w = this.count = 0;
this.queuedSource = 0; this.queuedSource = 0;
this.refQueue.length = 0; this.refQueue.length = 0;
@@ -310,7 +320,7 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
// Multiply integer counts first to avoid rounding an exact whole millisecond down. // Multiply integer counts first to avoid rounding an exact whole millisecond down.
const playedMs = Math.floor((playedOut * 1000) / sampleRate); 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, consumedSamples: playedOut, contextRate: sampleRate });
} }
} }
@@ -9,7 +9,7 @@ import { describe, it, expect, vi } from 'vitest';
* (the class reads `sampleRate` at call time, not at module-eval time). * (the class reads `sampleRate` at call time, not at module-eval time).
*/ */
interface Proc { interface Proc {
out: Array<{ type: string; audioRef?: string; playedMs?: number }>; out: Array<{ type: string; audioRef?: string; playedMs?: number; consumedSamples?: number; discardedSamples?: number; contextRate?: number }>;
port: { onmessage: (e: { data: unknown }) => void }; port: { onmessage: (e: { data: unknown }) => void };
count: number; count: number;
capacity: number; capacity: number;
@@ -20,10 +20,10 @@ interface Proc {
} }
class FakeAudioWorkletProcessor { class FakeAudioWorkletProcessor {
out: Array<{ type: string; audioRef?: string; playedMs?: number }> = []; out: Array<{ type: string; audioRef?: string; playedMs?: number; consumedSamples?: number; discardedSamples?: number; contextRate?: number }> = [];
port: { port: {
onmessage: ((e: { data: unknown }) => void) | null; onmessage: ((e: { data: unknown }) => void) | null;
postMessage: (m: { type: string; audioRef?: string; playedMs?: number }) => void; postMessage: (m: { type: string; audioRef?: string; playedMs?: number; consumedSamples?: number; discardedSamples?: number; contextRate?: number }) => void;
}; };
constructor() { constructor() {
this.port = { onmessage: null, postMessage: (m) => this.out.push(m) }; this.port = { onmessage: null, postMessage: (m) => this.out.push(m) };
@@ -150,6 +150,22 @@ describe('pcm-playback.worklet', () => {
expect(peakSource).toBeLessThan(proc.sourceCapacity); expect(peakSource).toBeLessThan(proc.sourceCapacity);
}); });
it.each([24000, 44100, 48000])('reports actual consumed samples at %i Hz without crediting a discarded tail', async (rate) => {
const proc = await loadPlaybackProcessor(rate);
push(proc, frame(0, 4800), 'aud-counted');
render(proc, 128);
clear(proc);
const reports = proc.out.filter((m) => m.type === 'progress');
expect(reports.length).toBeGreaterThan(0);
const final = reports.at(-1)!;
expect(final.contextRate).toBe(rate);
expect(final.consumedSamples).toBe(128);
expect(final.playedMs).toBe(Math.floor(128 * 1000 / rate));
expect(final.consumedSamples!).toBeLessThan(4800 * rate / 24000);
const discarded = proc.out.find((m) => m.type === 'discarded')!;
expect(discarded.discardedSamples! + final.consumedSamples!).toBe(Math.round(4800 * rate / 24000));
});
describe('exact consumed-sample progress', () => { describe('exact consumed-sample progress', () => {
it('plays the 364800-byte incident fully before generation ends at 24 kHz', async () => { it('plays the 364800-byte incident fully before generation ends at 24 kHz', async () => {
const proc = await loadPlaybackProcessor(24000); const proc = await loadPlaybackProcessor(24000);
@@ -327,6 +343,19 @@ describe('pcm-playback.worklet', () => {
}); });
}); });
it('attributes discarded samples separately when two references share the queue', async () => {
const proc = await loadPlaybackProcessor(24000);
push(proc, frame(0, 3000), 'aud-a');
push(proc, frame(3000, 3000), 'aud-b');
render(proc, 128);
clear(proc);
const discarded = proc.out.filter((m) => m.type === 'discarded');
expect(discarded.find((m) => m.audioRef === 'aud-a')?.discardedSamples).toBe(2872);
expect(discarded.find((m) => m.audioRef === 'aud-b')?.discardedSamples).toBe(3000);
expect(proc.refPlayedOut.get('aud-a')).toBe(128);
expect(proc.refPlayedOut.get('aud-b') ?? 0).toBe(0);
});
describe('interruption and clear', () => { describe('interruption and clear', () => {
it('clears the queue and reports only the source actually consumed', async () => { it('clears the queue and reports only the source actually consumed', async () => {
const proc = await loadPlaybackProcessor(24000); const proc = await loadPlaybackProcessor(24000);
@@ -1,4 +1,4 @@
import { Injectable, NgZone, inject } from '@angular/core'; import { Injectable, NgZone, inject, isDevMode } from '@angular/core';
import { MicrophoneError, MicrophoneService } from '../microphone/microphone.service'; import { MicrophoneError, MicrophoneService } from '../microphone/microphone.service';
import { VOICE_STREAM_CONFIG } from './voice-stream.types'; import { VOICE_STREAM_CONFIG } from './voice-stream.types';
@@ -87,6 +87,16 @@ export class VoiceAudioEngine {
// differs. Never assume the requested rate (SKILLS.md §3.2). // differs. Never assume the requested rate (SKILLS.md §3.2).
const ctx = new AudioContext({ latencyHint: 'interactive', sampleRate: cfg.outputSampleRate }); const ctx = new AudioContext({ latencyHint: 'interactive', sampleRate: cfg.outputSampleRate });
this.ctx = ctx; this.ctx = ctx;
const startedAt = performance.now();
let captureFrames = 0;
let lastCaptureTrace = startedAt;
ctx.onstatechange = () => {
if (isDevMode()) console.info('Voice audio context state', {
state: ctx.state, contextRate: ctx.sampleRate,
elapsedMs: Math.floor(performance.now() - startedAt),
contextMs: Math.floor(ctx.currentTime * 1000),
});
};
// Explicitly reject an unusable context rate: a 0/NaN/non-finite rate cannot resample // Explicitly reject an unusable context rate: a 0/NaN/non-finite rate cannot resample
// and must fail safely instead of silently producing no playback. // and must fail safely instead of silently producing no playback.
@@ -111,6 +121,16 @@ export class VoiceAudioEngine {
}, },
}); });
this.capture.port.onmessage = (event: MessageEvent<{ pcm: ArrayBuffer; rms: number }>) => { this.capture.port.onmessage = (event: MessageEvent<{ pcm: ArrayBuffer; rms: number }>) => {
captureFrames++;
const now = performance.now();
if (isDevMode() && now - lastCaptureTrace >= 1000) {
lastCaptureTrace = now;
console.info('Voice capture clock', {
captureFrames, state: ctx.state,
elapsedMs: Math.floor(now - startedAt),
contextMs: Math.floor(ctx.currentTime * 1000),
});
}
this.inputRms = event.data.rms; this.inputRms = event.data.rms;
handlers.onFrame(event.data.pcm, event.data.rms); handlers.onFrame(event.data.pcm, event.data.rms);
}; };
@@ -127,22 +147,32 @@ export class VoiceAudioEngine {
outputChannelCount: [1], outputChannelCount: [1],
}); });
this.playback.port.onmessage = ( this.playback.port.onmessage = (
event: MessageEvent<{ type: string; audioRef?: string; playedMs?: number }>, event: MessageEvent<{ type: string; audioRef?: string; playedMs?: number; consumedSamples?: number; discardedSamples?: number; contextRate?: number }>,
) => { ) => {
switch (event.data?.type) { switch (event.data?.type) {
case 'idle': case 'idle':
handlers.onPlaybackIdle(event.data.audioRef); handlers.onPlaybackIdle(event.data.audioRef);
break; break;
case 'progress': case 'progress':
if (isDevMode()) console.info('Voice worklet consumption', { audioRef: event.data.audioRef, consumedSamples: event.data.consumedSamples, contextRate: event.data.contextRate });
if (event.data.audioRef) { if (event.data.audioRef) {
handlers.onPlaybackProgress(event.data.audioRef, event.data.playedMs ?? 0); handlers.onPlaybackProgress(event.data.audioRef, event.data.playedMs ?? 0);
} }
break; break;
case 'discarded':
if (isDevMode()) console.info('Voice worklet discarded samples', { audioRef: event.data.audioRef, discardedSamples: event.data.discardedSamples, contextRate: event.data.contextRate });
break;
case 'overflow': case 'overflow':
handlers.onPlaybackOverflow(); handlers.onPlaybackOverflow();
break; break;
} }
}; };
this.playback.onprocessorerror = () => {
console.error('Voice playback processor failed', { state: ctx.state });
};
this.capture.onprocessorerror = () => {
console.error('Voice capture processor failed', { state: ctx.state });
};
this.analyser = ctx.createAnalyser(); this.analyser = ctx.createAnalyser();
this.analyser.fftSize = 1024; this.analyser.fftSize = 1024;
this.analyser.smoothingTimeConstant = 0.6; this.analyser.smoothingTimeConstant = 0.6;
@@ -215,8 +245,14 @@ export class VoiceAudioEngine {
// ---- cleanup --------------------------------------------------------------- // ---- cleanup ---------------------------------------------------------------
stop(): void { stop(): void {
if (this.capture) this.capture.port.onmessage = null; if (this.capture) {
if (this.playback) this.playback.port.onmessage = null; this.capture.port.onmessage = null;
this.capture.onprocessorerror = null;
}
if (this.playback) {
this.playback.port.onmessage = null;
this.playback.onprocessorerror = null;
}
this.source?.disconnect(); this.source?.disconnect();
this.capture?.disconnect(); this.capture?.disconnect();
@@ -1,4 +1,4 @@
import { Injectable, NgZone, computed, inject, signal } from '@angular/core'; import { Injectable, NgZone, computed, inject, isDevMode, signal } from '@angular/core';
import { Subject } from 'rxjs'; import { Subject } from 'rxjs';
import { MicrophoneError } from '../microphone/microphone.service'; import { MicrophoneError } from '../microphone/microphone.service';
import { uuid } from '../../shared/utils/uuid'; import { uuid } from '../../shared/utils/uuid';
@@ -147,6 +147,8 @@ export class VoiceStreamService {
private cleanupPromise: Promise<void> | null = null; private cleanupPromise: Promise<void> | null = null;
private session = 0; private session = 0;
private streaming = false; private streaming = false;
private traceStarted = performance.now();
private underrunStarted: number | null = null;
private audioGenerationDone = false; // server finished sending this audio_ref's frames private audioGenerationDone = false; // server finished sending this audio_ref's frames
private interruptTimer: ReturnType<typeof setTimeout> | null = null; private interruptTimer: ReturnType<typeof setTimeout> | null = null;
private settleTimer: ReturnType<typeof setTimeout> | null = null; private settleTimer: ReturnType<typeof setTimeout> | null = null;
@@ -191,6 +193,8 @@ export class VoiceStreamService {
if (!this.isSupported) return this.failure('unsupported', MESSAGES.unsupported); if (!this.isSupported) return this.failure('unsupported', MESSAGES.unsupported);
const session = ++this.session; const session = ++this.session;
this.traceStarted = performance.now();
this.underrunStarted = null;
const stale = (): boolean => session !== this.session; const stale = (): boolean => session !== this.session;
this.messages.set([]); this.messages.set([]);
@@ -431,8 +435,15 @@ export class VoiceStreamService {
private onServerAudio(chunk: ArrayBuffer, session: number): void { private onServerAudio(chunk: ArrayBuffer, session: number): void {
if (session !== this.session || !this.streaming) return; if (session !== this.session || !this.streaming) return;
this.currentAudioReceivedBytes += chunk.byteLength; if (this.underrunStarted !== null) {
this.audioTrace('underrun_resumed', { gapMs: Math.floor(performance.now() - this.underrunStarted) });
this.underrunStarted = null;
}
const chunkBytes = chunk.byteLength; // transfer to the worklet detaches this buffer
this.currentAudioReceivedBytes += chunkBytes;
this.audioTrace('audio_received', { chunkBytes });
this.engine.enqueuePlayback(chunk, this.currentAudioRef); this.engine.enqueuePlayback(chunk, this.currentAudioRef);
this.audioTrace('audio_enqueued', { chunkBytes });
this.clearSettleTimer(); this.clearSettleTimer();
if (this.state() !== 'SPEAKING') { if (this.state() !== 'SPEAKING') {
@@ -452,6 +463,7 @@ export class VoiceStreamService {
if (playedMs <= 0) return; if (playedMs <= 0) return;
// Keep the latest cumulative value per ref; the final report is sent from here too. // Keep the latest cumulative value per ref; the final report is sent from here too.
this.playedMsByRef.set(audioRef, playedMs); this.playedMsByRef.set(audioRef, playedMs);
if (audioRef === this.currentAudioRef) this.audioTrace('playback_progress', { playedMs });
this.sendPlaybackProgress(audioRef, playedMs); this.sendPlaybackProgress(audioRef, playedMs);
this.resolveProgressWaiters(); this.resolveProgressWaiters();
} }
@@ -475,6 +487,7 @@ export class VoiceStreamService {
const transport = this.transport; const transport = this.transport;
if (!ref || !transport || this.connection() !== 'connected') return Promise.resolve(); if (!ref || !transport || this.connection() !== 'connected') return Promise.resolve();
this.audioTrace('clear_session_end');
this.engine.clearPlayback(); // worklet answers with its final cumulative report this.engine.clearPlayback(); // worklet answers with its final cumulative report
return new Promise<void>((resolve) => { return new Promise<void>((resolve) => {
const done = (): void => { const done = (): void => {
@@ -560,6 +573,7 @@ export class VoiceStreamService {
receivedBytes: this.currentAudioReceivedBytes, receivedBytes: this.currentAudioReceivedBytes,
}); });
} }
this.audioTrace('flush_audio_ended');
this.engine.flushPlayback(this.currentAudioRef); this.engine.flushPlayback(this.currentAudioRef);
break; break;
@@ -642,6 +656,8 @@ export class VoiceStreamService {
this.markInterrupted(turnRef); this.markInterrupted(turnRef);
return; return;
} }
this.audioTrace('clear_interruption');
this.underrunStarted = null;
this.engine.clearPlayback(); // the worklet posts the final progress for the active ref this.engine.clearPlayback(); // the worklet posts the final progress for the active ref
if (!this.currentAudioTurnRef || this.currentAudioTurnRef === turnRef) { if (!this.currentAudioTurnRef || this.currentAudioTurnRef === turnRef) {
this.currentAudioRef = null; this.currentAudioRef = null;
@@ -686,6 +702,8 @@ export class VoiceStreamService {
} }
// The session survives a retryable failure (e.g. SEARCH_TIMEOUT): drop the failed turn and keep listening. // The session survives a retryable failure (e.g. SEARCH_TIMEOUT): drop the failed turn and keep listening.
this.audioTrace('clear_retryable_error');
this.underrunStarted = null;
this.engine.clearPlayback(); this.engine.clearPlayback();
this.clearSettleTimer(); this.clearSettleTimer();
this.finalizeAssistant(); this.finalizeAssistant();
@@ -695,9 +713,28 @@ export class VoiceStreamService {
// ---- end of an assistant turn ---------------------------------------------- // ---- end of an assistant turn ----------------------------------------------
/** Numeric browser timeline; backend timestamps use a different clock. */
private audioTrace(stage: string, counters: Record<string, number> = {}): void {
if (!isDevMode()) return;
console.info('Voice audio trace', {
stage,
sessionId: this.remote?.sessionId,
turnRef: this.currentAudioTurnRef,
audioRef: this.currentAudioRef,
elapsedMs: Math.floor(performance.now() - this.traceStarted),
receivedBytes: this.currentAudioReceivedBytes,
sentBytes: this.currentAudioSentBytes,
...counters,
});
}
private onPlaybackIdle(audioRef?: string | null): void { private onPlaybackIdle(audioRef?: string | null): void {
if (audioRef && audioRef !== this.currentAudioRef) return; if (audioRef && audioRef !== this.currentAudioRef) return;
if (this.state() !== 'SPEAKING' && this.state() !== 'PROCESSING') return; if (this.state() !== 'SPEAKING' && this.state() !== 'PROCESSING') return;
if (!this.audioGenerationDone && this.currentAudioRef && this.underrunStarted === null) {
this.underrunStarted = performance.now();
this.audioTrace('underrun_started');
}
// A dry queue while generation is open is an underrun, not the end of a turn. // A dry queue while generation is open is an underrun, not the end of a turn.
if (this.audioGenerationDone && this.currentAudioRef) { if (this.audioGenerationDone && this.currentAudioRef) {
const sent = this.currentAudioSentBytes; const sent = this.currentAudioSentBytes;
@@ -706,11 +743,13 @@ export class VoiceStreamService {
if (sent !== null && Math.abs(sent - playedMs * 48) >= 48) { if (sent !== null && Math.abs(sent - playedMs * 48) >= 48) {
console.warn('Voice audio playback mismatch', { sentBytes: sent, playedMs }); console.warn('Voice audio playback mismatch', { sentBytes: sent, playedMs });
} }
this.audioTrace('audio_drained', { playedMs });
this.finishTurn(); this.finishTurn();
} }
} }
private finishTurn(): void { private finishTurn(): void {
this.underrunStarted = null;
this.audioGenerationDone = false; this.audioGenerationDone = false;
this.currentAudioRef = null; this.currentAudioRef = null;
this.currentAudioTurnRef = null; this.currentAudioTurnRef = null;