// Playback engine: walks a chapter sentence by sentence, using either the on-device // Kokoro model (generated ahead, cached in IndexedDB) or the system speech voice. import { audioKeys, getAudio, putAudio } from './db'; import { isSilentWav } from './text'; import { splitSentences } from './text'; import type { Book } from './db'; export const NATURAL_VOICES = [ { id: 'af_heart', label: 'Heart · US · female' }, { id: 'af_bella', label: 'Bella · US · female' }, { id: 'am_michael', label: 'Michael · US · male' }, { id: 'am_fenrir', label: 'Fenrir · US · male' }, { id: 'bf_emma', label: 'Emma · UK · female' }, { id: 'bm_george', label: 'George · UK · male' }, ]; export type Voice = { kind: 'natural'; id: string } | { kind: 'device'; id: string }; export type ModelState = | { s: 'idle' } | { s: 'loading'; loaded: number; total: number } | { s: 'ready'; device: string } | { s: 'error'; message: string }; export interface EngineEvents { onSentence(chapter: number, index: number): void; onPlaying(playing: boolean): void; onBuffering(b: boolean): void; onModel(m: ModelState): void; onChapterEnd(nextChapter: number | null): void; onError(msg: string, code?: 'device-unavailable'): void; onPrepare?(done: number, total: number): void; onSleep?(): void; /** heard: the natural voice just finished the previous (free) chapter. */ onGate?(heard: boolean): void; /** The free listening time is used up: playback stopped (or did not start) at a sentence boundary. */ onLimit?(stoppedMidway: boolean): void; } /** The browser speech API, or null where it does not exist (Android WebView / in-app browsers). */ export const synth: SpeechSynthesis | null = typeof window !== 'undefined' && 'speechSynthesis' in window ? window.speechSynthesis : null; const AHEAD = 6; // sentences generated ahead of the one playing export function wavBlob(pcm: Float32Array, rate: number): Blob { const buf = new ArrayBuffer(44 + pcm.length * 2); const v = new DataView(buf); const w = (o: number, s: string) => [...s].forEach((c, i) => v.setUint8(o + i, c.charCodeAt(0))); w(0, 'RIFF'); v.setUint32(4, 36 + pcm.length * 2, true); w(8, 'WAVE'); w(12, 'fmt '); v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true); v.setUint32(24, rate, true); v.setUint32(28, rate * 2, true); v.setUint16(32, 2, true); v.setUint16(34, 16, true); w(36, 'data'); v.setUint32(40, pcm.length * 2, true); for (let i = 0; i < pcm.length; i++) { const s = Math.max(-1, Math.min(1, pcm[i])); v.setInt16(44 + i * 2, s < 0 ? s * 0x8000 : s * 0x7fff, true); } return new Blob([buf], { type: 'audio/wav' }); } // 0.05 s of silence, used to unlock audio playback inside the first tap (iOS/Android autoplay rules) const SILENCE = URL.createObjectURL(wavBlob(new Float32Array(1200), 24000)); export class Engine { book: Book | null = null; chapter = 0; sentences: string[] = []; index = 0; playing = false; speed = 1; voice: Voice = { kind: 'natural', id: 'af_heart' }; model: ModelState = { s: 'idle' }; /** generation time vs audio length, for diagnostics and tests */ stats: { genMs: number; audioMs: number }[] = []; private audio = new Audio(); private worker: Worker | null = null; private nextId = 1; private pending = new Map void; reject: (e: Error) => void }>(); private clips = new Map>(); // in-flight / recent generations private url: string | null = null; private token = 0; // invalidates stale async continuations private unlocked = false; private selfPause = false; private queuedVoice: Voice | null = null; naturalId = 'af_heart'; /** Ready-made audio for a sentence (the built-in sample ships its clips), consulted before the model. */ preclip?: (key: string, chapter: number, i: number, text: string) => Promise | undefined; /** generate the whole chapter in the background (for devices slower than real time) */ preparing = false; /** reached the end of the last chapter */ finished = false; constructor(private ev: EngineEvents) { this.audio.preload = 'auto'; (this.audio as any).preservesPitch = true; this.audio.addEventListener('ended', () => { if (this.audio.src === SILENCE) return; // the unlock blip, not a sentence if (this.playing && this.voice.kind === 'natural') this.advance(); }); this.audio.addEventListener('pause', () => { // paused from the OS (headphones unplugged, lock-screen control) if (this.selfPause) { this.selfPause = false; return; } if (this.playing && this.voice.kind === 'natural' && !this.audio.ended && this.audio.src !== SILENCE && this.audio.currentTime > 0) { this.playing = false; this.ev.onPlaying(false); } }); this.setupMediaSession(); } /* ---------- model ---------- */ ensureModel() { if (this.worker) return; this.worker = new Worker(new URL('./tts-worker.ts', import.meta.url), { type: 'module' }); this.worker.onmessage = (e) => this.onWorker(e.data); this.worker.onerror = (e) => (console.warn('voice worker:', e.message), this.killWorker('The natural voice stopped working.')); this.setModel({ s: 'loading', loaded: 0, total: 0 }); void pickDevice().then((device) => { const ortBase = new URL('ort/', document.baseURI).href; this.worker!.postMessage({ type: 'load', device, ortBase, modelBase: new URL('models/kokoro/', document.baseURI).href, threads: threadCount(), dtype: lsGet('earshelf.dtype') || undefined }); }); } private killWorker(message: string) { for (const p of this.pending.values()) p.reject(new Error(message)); this.pending.clear(); this.clips.clear(); this.worker?.terminate(); this.worker = null; this.setModel({ s: 'error', message }); } private setModel(m: ModelState) { this.model = m; this.ev.onModel(m); } private onWorker(m: any) { if (m.type === 'progress') this.setModel({ s: 'loading', loaded: m.loaded, total: m.total }); else if (m.type === 'ready') this.setModel({ s: 'ready', device: m.device }); else if (m.type === 'loadError') this.killWorker(m.message); else if (m.type === 'audio' || m.type === 'error') { const p = this.pending.get(m.id); if (!p) return; this.pending.delete(m.id); if (m.type === 'error') { this.clips.delete(p.key); p.reject(new Error(m.message)); return; } this.stats.push({ genMs: m.ms, audioMs: Math.round((m.pcm.length / m.rate) * 1000) }); if (this.stats.length > 50) this.stats.shift(); const blob = wavBlob(m.pcm, m.rate); const key = p.key; // stored under the book that asked for it; dropped from memory once it is safely in IndexedDB void putAudio(key, key.split('|')[0], blob) .then(() => { if (Number(key.split('|')[2]) < this.index || this.clips.size > AHEAD + 4) this.clips.delete(key); }) .catch(() => {}); p.resolve(blob); if (this.preparing) this.reportPrepare(); } } private key(chapter: number, i: number, vid = this.naturalVoiceId()) { return `${this.book!.id}|${chapter}|${i}|${vid}`; } /** The natural voice in use, or the one to prepare while the device voice reads. */ naturalVoiceId() { return this.voice.kind === 'natural' ? this.voice.id : this.naturalId; } private clip(i: number): Promise { const text = this.sentences[i]; const vid = this.naturalVoiceId(); const key = this.key(this.chapter, i, vid); let p = this.clips.get(key); if (p) return p; const chapter = this.chapter; p = (async () => { const ready = await this.preclip?.(key, chapter, i, text)?.catch(() => undefined); if (ready) return ready; let cached = await getAudio(key).catch(() => undefined); // saved before the silent-output retry existed: generate it again if (cached && cached.type === 'audio/wav' && isSilentWav(await cached.arrayBuffer())) cached = undefined; if (cached) { queueMicrotask(() => this.clips.delete(key)); // already on disk: no need to hold it in memory return cached; } this.ensureModel(); return new Promise((resolve, reject) => { const id = this.nextId++; this.pending.set(id, { key, resolve, reject }); this.worker!.postMessage({ type: 'gen', id, text, voice: vid, priority: i === this.index }); }); })(); this.clips.set(key, p); p.catch(() => this.clips.delete(key)); return p; } private prefetch(from: number) { if (!this.natOk()) return; // locked chapter: never spend the device's time on audio it cannot play const keep: number[] = []; const span = this.preparing ? this.sentences.length : AHEAD; for (let i = from; i < Math.min(this.sentences.length, from + span + 1); i++) { void this.clip(i).catch(() => {}); } // drop queued jobs for sentences we skipped past const prefix = `${this.book!.id}|${this.chapter}|`; const vid = this.naturalVoiceId(); for (const [id, p] of this.pending) { const parts = p.key.split('|'); const idx = Number(parts[2]); if (p.key.startsWith(prefix) && parts[3] === vid && idx >= from && idx <= from + span) keep.push(id); else { this.pending.delete(id); this.clips.delete(p.key); p.reject(new Error('skipped')); } } this.worker?.postMessage({ type: 'cancel', keep }); } /** Start generating the rest of this chapter (and the next ones) in the background. */ prepare() { if (!this.book) return; this.preparing = true; this.ensureModel(); this.prefetch(this.voice.kind === 'device' ? this.index + 1 : this.index); this.reportPrepare(); } private prepTimer: number | undefined; private reportPrepare() { clearTimeout(this.prepTimer); this.prepTimer = window.setTimeout(() => void this.countPrepared(), 300); } private async countPrepared() { if (!this.book || !this.preparing) return; const prefix = `${this.book.id}|${this.chapter}|`; const vid = this.naturalVoiceId(); const from = this.index; const keys = await audioKeys(prefix).catch(() => [] as string[]); const have = new Set(keys.filter((k) => k.endsWith('|' + vid)).map((k) => Number(k.split('|')[2]))); let done = 0; for (let i = from; i < this.sentences.length; i++) if (have.has(i)) done++; this.ev.onPrepare?.(done, this.sentences.length - from); } /** Real-time factor of the natural voice on this device (generation time / audio time). */ rtf(): number | null { const s = this.stats.slice(-4); if (!s.length) return null; return s.reduce((a, x) => a + x.genMs, 0) / Math.max(1, s.reduce((a, x) => a + x.audioMs, 0)); } /** Generate the next sentence with the natural voice (kept for later) and return the measured speed. */ async probe(): Promise { if (!this.book || !this.natOk()) return null; const i = Math.min(this.index + 1, this.sentences.length - 1); const before = this.stats.length; try { await this.clip(i); } catch { return null; } return this.stats.length > before ? this.rtf() : 0; // 0 = it was already saved } /* ---------- navigation ---------- */ open(book: Book, chapter: number, sentence: number) { this.stopOutput(); this.queuedVoice = null; this.preparing = false; this.lastNaturalChapter = -1; this.book = book; this.loadChapter(chapter, sentence); // warm the cache so pressing play is instant if (this.voice.kind === 'natural') this.prefetch(this.index); } private loadChapter(chapter: number, sentence: number) { this.finished = false; this.chapter = chapter; this.sentences = splitSentences(this.book!.chapters[chapter].text); this.index = Math.max(0, Math.min(sentence, this.sentences.length - 1)); this.ev.onSentence(this.chapter, this.index); this.updateMediaMeta(); if (this.preparing && !this.natOk()) { this.preparing = false; this.ev.onPrepare?.(0, 0); // clear the "Preparing…" banner } if (this.preparing) { this.prefetch(this.index); void this.reportPrepare(); } } /** Must be called from a user gesture the first time (unlocks audio on mobile). */ play() { if (!this.book) return; if (this.mayContinue && !this.mayContinue()) { this.ev.onLimit?.(false); return; } if (this.finished) { // a finished book starts over (button, Space key or lock-screen play) this.loadChapter(0, 0); } if (!this.unlocked) { this.audio.src = SILENCE; void this.audio.play().catch(() => {}); this.unlocked = true; } if (this.voice.kind === 'device') synth?.cancel(); this.playing = true; this.ev.onPlaying(true); void this.speakCurrent(); } pause() { if (this.queuedVoice) { // apply a pending voice switch now instead of losing it this.voice = this.queuedVoice; if (this.voice.kind === 'natural') this.naturalId = this.voice.id; this.queuedVoice = null; } this.playing = false; this.token++; this.stopOutput(); this.ev.onPlaying(false); this.ev.onBuffering(false); } toggle() { this.playing ? this.pause() : this.play(); } jump(index: number) { if (!this.book) return; this.finished = false; this.index = Math.max(0, Math.min(index, this.sentences.length - 1)); this.ev.onSentence(this.chapter, this.index); if (this.playing) { this.stopOutput(); void this.speakCurrent(); } } next() { if (this.index + 1 < this.sentences.length) this.jump(this.index + 1); else if (this.book && this.chapter + 1 < this.book.chapters.length) this.gotoChapter(this.chapter + 1); // on the very last sentence Next does nothing: the book is finished only after it is heard } prev() { if (this.index > 0) this.jump(this.index - 1); else if (this.chapter > 0) this.gotoChapter(this.chapter - 1, true); } /** * Skip by listening time (≈15 characters a second at 1×), landing on a sentence start. * Crosses into the next or previous chapter at the edges. */ skip(seconds: number) { if (!this.book) return; let chars = Math.abs(seconds) * CHARS_PER_SEC * this.speed; if (seconds > 0) { let i = this.index; const last = this.sentences.length - 1; while (chars > 0 && i < last) chars -= this.sentences[i++].length + 1; // past the last sentence's length too: the next chapter; otherwise land on the last sentence if (i === last && chars > this.sentences[last].length && this.chapter + 1 < this.book.chapters.length) return this.gotoChapter(this.chapter + 1); if (i === this.index) return; // already on the book's last sentence: nothing ahead this.jump(i); } else { let i = this.index; while (chars > 0 && i > 0) chars -= this.sentences[--i].length + 1; if (chars > 0 && i === 0 && this.index === 0 && this.chapter > 0) return this.gotoChapter(this.chapter - 1, true); this.jump(i); } } gotoChapter(c: number, atEnd = false) { if (!this.book) return; if (c >= this.book.chapters.length) { this.finished = true; this.pause(); this.clearChapterSleep(); this.ev.onChapterEnd(null); return; } if (c < 0) return; const wasPlaying = this.playing; this.stopOutput(); this.loadChapter(c, 0); if (atEnd) { this.index = this.sentences.length - 1; this.ev.onSentence(this.chapter, this.index); } if (wasPlaying) void this.speakCurrent(); } setSpeed(s: number) { this.speed = s; this.audio.playbackRate = s; if (this.voice.kind === 'device' && this.playing) { this.stopOutput(); void this.speakCurrent(); } } setVoice(v: Voice) { this.queuedVoice = null; const wasPlaying = this.playing; if (wasPlaying) this.pause(); this.voice = v; if (v.kind === 'natural') { this.naturalId = v.id; this.ensureModel(); } else this.preparing = false; if (wasPlaying) this.play(); } /** Switch voice at the next sentence boundary (no repeat, no gap). */ queueVoice(v: Voice) { if (!this.playing) return this.setVoice(v); this.queuedVoice = v; } private advance() { const atEnd = this.index + 1 >= this.sentences.length; const bookEnds = atEnd && !!this.book && this.chapter + 1 >= this.book.chapters.length; if (!bookEnds && this.mayContinue && !this.mayContinue()) { // free time is up: stop cleanly at the end of the sentence just heard, the next one stays the position if (!atEnd) this.index++; else this.loadChapter(this.chapter + 1, 0); if (!atEnd) this.ev.onSentence(this.chapter, this.index); this.pause(); this.ev.onLimit?.(true); return; } if (this.queuedVoice) { this.voice = this.queuedVoice; this.queuedVoice = null; if (this.voice.kind === 'natural') this.naturalId = this.voice.id; if (this.voice.kind === 'natural' && !this.unlocked) this.unlocked = true; } if (this.index + 1 < this.sentences.length) { this.index++; this.ev.onSentence(this.chapter, this.index); void this.speakCurrent(); } else { const nextC = this.chapter + 1; if (this.book && nextC < this.book.chapters.length) { this.ev.onChapterEnd(nextC); this.loadChapter(nextC, 0); if (this.stopAtChapterEnd) { // sleep timer "end of chapter": stop at the start of the next one this.stopAtChapterEnd = false; this.pause(); this.ev.onSleep?.(); return; } void this.speakCurrent(); } else { this.finished = true; this.pause(); this.clearChapterSleep(); this.ev.onChapterEnd(null); } } } private stopOutput() { this.token++; if (this.voice.kind === 'device' || synth?.speaking) synth?.cancel(); if (!this.audio.paused) { this.selfPause = true; this.audio.pause(); } } private async speakCurrent() { if (this.mayContinue && !this.mayContinue()) { // free time is up: jumps, seeks, chapter changes and speed changes stop here too this.pause(); this.ev.onLimit?.(false); return; } if (this.voice.kind === 'natural' && this.gate && !this.gate(this.chapter)) { // natural voice not unlocked for this chapter: keep reading with the device voice this.voice = this.gateFallback?.() || { kind: 'device', id: '' }; this.queuedVoice = null; this.preparing = false; this.ev.onGate?.(this.lastNaturalChapter >= 0 && this.lastNaturalChapter === this.chapter - 1); } const my = ++this.token; const i = this.index; if (this.voice.kind === 'device') return this.speakDevice(i, my); this.prefetch(i); let blob: Blob; const ready = this.clips.get(this.key(this.chapter, i)); let buffering = false; const t = setTimeout(() => { if (my === this.token) { buffering = true; this.ev.onBuffering(true); } }, 120); try { blob = await (ready || this.clip(i)); } catch (e) { clearTimeout(t); if (my !== this.token) return; if ((e as Error).message === 'skipped') return; this.ev.onBuffering(false); console.warn('sentence failed:', (e as Error).message); this.ev.onError("Couldn't read this sentence. Tap play to try again."); this.pause(); return; } clearTimeout(t); if (my !== this.token || !this.playing) return; if (buffering) this.ev.onBuffering(false); this.lastNaturalChapter = this.chapter; if (this.url) URL.revokeObjectURL(this.url); this.url = URL.createObjectURL(blob); this.audio.src = this.url; this.audio.playbackRate = this.speed; try { await this.audio.play(); } catch (e) { if (my !== this.token) return; this.pause(); this.ev.onError('Tap play to start listening.'); } } private speakDevice(i: number, my: number) { if (!synth) { this.pause(); this.ev.onError('This browser has no built-in voice.', 'device-unavailable'); return; } const u = new SpeechSynthesisUtterance(this.sentences[i]); const v = synth.getVoices().find((x) => x.voiceURI === this.voice.id); if (v) { u.voice = v; u.lang = v.lang; } else if (this.book) u.lang = this.book.lang; u.rate = this.speed; u.onend = () => { if (my === this.token && this.playing) this.advance(); }; u.onerror = (e) => { if (my !== this.token) return; if (e.error === 'interrupted' || e.error === 'canceled') return; this.pause(); if (e.error === 'synthesis-failed' || e.error === 'synthesis-unavailable' || e.error === 'language-unavailable' || e.error === 'voice-unavailable' || !synth.getVoices().length) { this.ev.onError('This browser has no built-in voice.', 'device-unavailable'); } else (console.warn('speech error:', e.error), this.ev.onError('The voice stopped. Tap play to try again.')); }; synth.speak(u); } /* ---------- lock screen / headset controls ---------- */ private setupMediaSession() { if (!('mediaSession' in navigator)) return; const ms = navigator.mediaSession; const h = (a: MediaSessionAction, f: () => void) => { try { ms.setActionHandler(a, f); } catch { /* unsupported action */ } }; h('play', () => this.play()); h('pause', () => this.pause()); h('nexttrack', () => this.next()); h('previoustrack', () => this.prev()); h('seekforward', () => this.skip(30)); h('seekbackward', () => this.skip(-15)); } /** May the natural voice read (or generate for) this chapter? */ natOk(chapter = this.chapter) { return !this.gate || this.gate(chapter); } /** Chapter in which the natural voice was last heard (this book open), for the paywall moment. */ private lastNaturalChapter = -1; /** Paywall hook: may playback go on to the next sentence? (unset = always) */ mayContinue?: () => boolean; /** Paywall hook: may the natural voice read this chapter? (unset = always) */ gate?: (chapter: number) => boolean; /** Voice to use when the gate says no. */ gateFallback?: () => Voice; /** Sleep timer: pause when the current chapter ends. */ stopAtChapterEnd = false; private clearChapterSleep() { if (!this.stopAtChapterEnd) return; this.stopAtChapterEnd = false; // the book ended first: the timer is done this.ev.onSleep?.(); } /** Cover image URL for the lock screen (set by the UI). */ artwork = ''; private updateMediaMeta() { if (!('mediaSession' in navigator) || !this.book) return; try { navigator.mediaSession.metadata = new MediaMetadata({ title: this.book.chapters[this.chapter]?.title || this.book.title, artist: this.book.author || 'EarShelf', album: this.book.title, artwork: this.artwork ? [{ src: this.artwork, sizes: '512x512' }] : [], }); } catch { /* ignore */ } } } /** ≈155 words a minute at 1× (900 characters a minute). */ export const CHARS_PER_SEC = 15; async function pickDevice(): Promise<'webgpu' | 'wasm'> { // Measured 2026-11-18 (Ryzen 5 7500F, Chrome): WASM fp16 (163 MB) RTF 0.52, q8 (92 MB) 0.94, q4f16 0.52, fp32 0.52. // WebGPU needs fp32 (326 MB), failed to cache and stalled headless; available only when forced. try { if (localStorage.getItem('earshelf.device') === 'webgpu' && (navigator as any).gpu) return 'webgpu'; } catch { /* storage blocked */ } return 'wasm'; } function threadCount(): number { try { const forced = Number(localStorage.getItem('earshelf.threads')); if (forced > 0) return forced; } catch { /* ignore */ } if (!crossOriginIsolated) return 1; // measured: phones (big.LITTLE) are fastest with 2 threads, desktops gain nothing past 4 const mobile = /Android|iPhone|iPad|Mobile/i.test(navigator.userAgent); return Math.min(mobile ? 2 : 4, navigator.hardwareConcurrency || 2); } function lsGet(k: string): string | null { try { return localStorage.getItem(k); } catch { return null; } }