diff --git a/public/assets/worklets/pcm-playback.worklet.js b/public/assets/worklets/pcm-playback.worklet.js index b4ee8c7..560e2cc 100644 --- a/public/assets/worklets/pcm-playback.worklet.js +++ b/public/assets/worklets/pcm-playback.worklet.js @@ -95,6 +95,16 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor { clear() { 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.queuedSource = 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. const playedMs = Math.floor((playedOut * 1000) / sampleRate); if (playedMs <= 0) return; - this.port.postMessage({ type: 'progress', audioRef: ref, playedMs }); + this.port.postMessage({ type: 'progress', audioRef: ref, playedMs, consumedSamples: playedOut, contextRate: sampleRate }); } } diff --git a/src/app/services/voice-stream/pcm-playback.worklet.spec.ts b/src/app/services/voice-stream/pcm-playback.worklet.spec.ts index 457ef0c..aede489 100644 --- a/src/app/services/voice-stream/pcm-playback.worklet.spec.ts +++ b/src/app/services/voice-stream/pcm-playback.worklet.spec.ts @@ -9,7 +9,7 @@ import { describe, it, expect, vi } from 'vitest'; * (the class reads `sampleRate` at call time, not at module-eval time). */ 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 }; count: number; capacity: number; @@ -20,10 +20,10 @@ interface Proc { } 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: { 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() { this.port = { onmessage: null, postMessage: (m) => this.out.push(m) }; @@ -150,6 +150,22 @@ describe('pcm-playback.worklet', () => { 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', () => { it('plays the 364800-byte incident fully before generation ends at 24 kHz', async () => { 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', () => { it('clears the queue and reports only the source actually consumed', async () => { const proc = await loadPlaybackProcessor(24000); diff --git a/src/app/services/voice-stream/voice-audio-engine.service.ts b/src/app/services/voice-stream/voice-audio-engine.service.ts index 673a488..c602461 100644 --- a/src/app/services/voice-stream/voice-audio-engine.service.ts +++ b/src/app/services/voice-stream/voice-audio-engine.service.ts @@ -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 { VOICE_STREAM_CONFIG } from './voice-stream.types'; @@ -87,6 +87,16 @@ export class VoiceAudioEngine { // differs. Never assume the requested rate (SKILLS.md ยง3.2). const ctx = new AudioContext({ latencyHint: 'interactive', sampleRate: cfg.outputSampleRate }); 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 // 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 }>) => { + 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; handlers.onFrame(event.data.pcm, event.data.rms); }; @@ -127,22 +147,32 @@ export class VoiceAudioEngine { outputChannelCount: [1], }); 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) { case 'idle': handlers.onPlaybackIdle(event.data.audioRef); break; 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) { handlers.onPlaybackProgress(event.data.audioRef, event.data.playedMs ?? 0); } 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': handlers.onPlaybackOverflow(); 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.fftSize = 1024; this.analyser.smoothingTimeConstant = 0.6; @@ -215,8 +245,14 @@ export class VoiceAudioEngine { // ---- cleanup --------------------------------------------------------------- stop(): void { - if (this.capture) this.capture.port.onmessage = null; - if (this.playback) this.playback.port.onmessage = null; + if (this.capture) { + 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.capture?.disconnect(); diff --git a/src/app/services/voice-stream/voice-stream.service.ts b/src/app/services/voice-stream/voice-stream.service.ts index 5e9c635..ea59e30 100644 --- a/src/app/services/voice-stream/voice-stream.service.ts +++ b/src/app/services/voice-stream/voice-stream.service.ts @@ -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 { MicrophoneError } from '../microphone/microphone.service'; import { uuid } from '../../shared/utils/uuid'; @@ -147,6 +147,8 @@ export class VoiceStreamService { private cleanupPromise: Promise | null = null; private session = 0; private streaming = false; + private traceStarted = performance.now(); + private underrunStarted: number | null = null; private audioGenerationDone = false; // server finished sending this audio_ref's frames private interruptTimer: ReturnType | null = null; private settleTimer: ReturnType | null = null; @@ -191,6 +193,8 @@ export class VoiceStreamService { if (!this.isSupported) return this.failure('unsupported', MESSAGES.unsupported); const session = ++this.session; + this.traceStarted = performance.now(); + this.underrunStarted = null; const stale = (): boolean => session !== this.session; this.messages.set([]); @@ -431,8 +435,15 @@ export class VoiceStreamService { private onServerAudio(chunk: ArrayBuffer, session: number): void { 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.audioTrace('audio_enqueued', { chunkBytes }); this.clearSettleTimer(); if (this.state() !== 'SPEAKING') { @@ -452,6 +463,7 @@ export class VoiceStreamService { if (playedMs <= 0) return; // Keep the latest cumulative value per ref; the final report is sent from here too. this.playedMsByRef.set(audioRef, playedMs); + if (audioRef === this.currentAudioRef) this.audioTrace('playback_progress', { playedMs }); this.sendPlaybackProgress(audioRef, playedMs); this.resolveProgressWaiters(); } @@ -475,6 +487,7 @@ export class VoiceStreamService { const transport = this.transport; if (!ref || !transport || this.connection() !== 'connected') return Promise.resolve(); + this.audioTrace('clear_session_end'); this.engine.clearPlayback(); // worklet answers with its final cumulative report return new Promise((resolve) => { const done = (): void => { @@ -560,6 +573,7 @@ export class VoiceStreamService { receivedBytes: this.currentAudioReceivedBytes, }); } + this.audioTrace('flush_audio_ended'); this.engine.flushPlayback(this.currentAudioRef); break; @@ -642,6 +656,8 @@ export class VoiceStreamService { this.markInterrupted(turnRef); return; } + this.audioTrace('clear_interruption'); + this.underrunStarted = null; this.engine.clearPlayback(); // the worklet posts the final progress for the active ref if (!this.currentAudioTurnRef || this.currentAudioTurnRef === turnRef) { 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. + this.audioTrace('clear_retryable_error'); + this.underrunStarted = null; this.engine.clearPlayback(); this.clearSettleTimer(); this.finalizeAssistant(); @@ -695,9 +713,28 @@ export class VoiceStreamService { // ---- end of an assistant turn ---------------------------------------------- + /** Numeric browser timeline; backend timestamps use a different clock. */ + private audioTrace(stage: string, counters: Record = {}): 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 { if (audioRef && audioRef !== this.currentAudioRef) 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. if (this.audioGenerationDone && this.currentAudioRef) { const sent = this.currentAudioSentBytes; @@ -706,11 +743,13 @@ export class VoiceStreamService { if (sent !== null && Math.abs(sent - playedMs * 48) >= 48) { console.warn('Voice audio playback mismatch', { sentBytes: sent, playedMs }); } + this.audioTrace('audio_drained', { playedMs }); this.finishTurn(); } } private finishTurn(): void { + this.underrunStarted = null; this.audioGenerationDone = false; this.currentAudioRef = null; this.currentAudioTurnRef = null;