File size: 24,503 Bytes
4a58e48
 
 
daa9f5e
4a58e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1876f7
 
4a58e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
daa9f5e
 
4a58e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1876f7
4a58e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
daa9f5e
4a58e48
daa9f5e
 
 
 
 
4a58e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1876f7
 
 
 
4a58e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1876f7
 
 
 
 
 
 
 
 
 
 
4a58e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1876f7
 
 
 
 
 
4a58e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1876f7
 
4a58e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1876f7
4a58e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1876f7
4a58e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1876f7
 
4a58e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
// 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<number, { key: string; resolve: (b: Blob) => void; reject: (e: Error) => void }>();
  private clips = new Map<string, Promise<Blob>>(); // 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<Blob> | 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<Blob> {
    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<Blob>((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<number | null> {
    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;
  }
}