/* Authenticated, incremental PCM playback for Athena's call-mode TTS. */ (() => { let context, active; const pending = new Set(); const audioContext = () => context ??= new (window.AudioContext || window.webkitAudioContext)(); // Create/resume inside a real user gesture, before the asynchronous reply. document.addEventListener('pointerdown', () => { try { audioContext().resume().catch(() => {}); } catch (_) {} }, {capture: true}); async function getAudio(token, voice, text) { const controller = new AbortController(); const response = await fetch('/api/v1/audio/speech/pcm-stream', { method: 'POST', signal: controller.signal, headers: {Authorization: `Bearer ${token}`, 'Content-Type': 'application/json'}, body: JSON.stringify({input: text, voice}) }); if (!response.ok) { const error = await response.json().catch(() => ({})); throw new Error(error.detail || `Audio streaming: HTTP ${response.status}`); } if (response.headers.get('X-Audio-Sample-Rate') !== '24000' || response.headers.get('X-Audio-Format') !== 's16le') { controller.abort(); throw new Error('Unsupported PCM stream'); } const item = {athenaPCM: true, reader: response.body.getReader(), controller, chunks: [], complete: false, cancelled: false, sources: new Set(), restart: () => getAudio(token, voice, text)}; pending.add(item); return item; } async function play(item, rate = 1) { if (item.cancelled) Object.assign(item, await item.restart()); const ctx = audioContext(); await ctx.resume(); active = item; let next = ctx.currentTime + 0.06, leftover = null, total = 0; const enqueue = bytes => { const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); const buffer = ctx.createBuffer(1, bytes.byteLength / 2, 24000); const samples = buffer.getChannelData(0); for (let i = 0; i < samples.length; i++) samples[i] = view.getInt16(i * 2, true) / 32768; const source = ctx.createBufferSource(); source.buffer = buffer; source.playbackRate.value = Math.max(.25, Math.min(4, Number(rate) || 1)); source.connect(ctx.destination); item.sources.add(source); source.onended = () => item.sources.delete(source); next = Math.max(next, ctx.currentTime + .02); source.start(next); next += buffer.duration / source.playbackRate.value; }; try { if (item.complete) for (const bytes of item.chunks) enqueue(bytes); else { for (;;) { if (item.cancelled) return; // Bound scheduled audio; maintain ordered playback without gaps. while (next - ctx.currentTime > 2 && !item.cancelled) await new Promise(resolve => setTimeout(resolve, 30)); if (item.cancelled) return; const {value, done} = await item.reader.read(); if (done) break; let bytes = value; if (leftover !== null) { bytes = new Uint8Array(value.length + 1); bytes[0] = leftover; bytes.set(value, 1); leftover = null; } if (bytes.length % 2) {leftover = bytes[bytes.length - 1]; bytes = bytes.subarray(0, -1);} if (bytes.length) { total += bytes.length; if (total > 32 * 1024 * 1024) throw new Error('PCM stream exceeds audio limit'); const copy = bytes.slice(); item.chunks.push(copy); enqueue(copy); } } if (leftover !== null || !item.chunks.length) throw new Error('Incomplete PCM stream'); item.complete = true; } while (item.sources.size && !item.cancelled) await new Promise(resolve => setTimeout(resolve, 30)); } catch (error) { item.cancelled = true; item.controller.abort(); for (const source of item.sources) try {source.stop();} catch (_) {} throw error; } finally {pending.delete(item); if (active === item) active = null;} } function stop() { for (const item of new Set([...pending, ...(active ? [active] : [])])) { item.cancelled = true; item.controller.abort(); item.reader.cancel().catch(() => {}); for (const source of item.sources) try {source.stop();} catch (_) {} item.sources.clear(); } pending.clear(); active = null; } window.athenaPCM = {getAudio, play, stop}; })();