@hackbuild/speak 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1899 @@
1
+ var HackbuildSpeak = (function(exports) {
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ // packages/speak/src/text.ts
4
+ const cp = (n) => `\\u{${n.toString(16)}}`;
5
+ const PICTO = new RegExp(`[\\p{Extended_Pictographic}${cp(127995)}-${cp(127999)}${cp(65038)}${cp(65039)}${cp(8205)}${cp(8419)}]+`, "gu");
6
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7
+ /**
8
+ * Strip what should not be read aloud: think blocks (closed or still
9
+ * open), code fences, markdown marks, link targets, emoji and variation
10
+ * selectors; read bare URLs as one word; apply the lexicon; collapse
11
+ * whitespace. Returns the text and an offset map back into the input.
12
+ */
13
+ function speakable(input, o = {}) {
14
+ const edits = [];
15
+ const claimed = [];
16
+ const free = (a, b) => claimed.every(([x, y]) => b <= x || a >= y);
17
+ const add = (start, end, repl) => {
18
+ if (end <= start || !free(start, end)) return;
19
+ claimed.push([start, end]);
20
+ edits.push({
21
+ start,
22
+ end,
23
+ repl
24
+ });
25
+ };
26
+ const each = (re, fn) => {
27
+ for (const m of input.matchAll(re)) fn(m);
28
+ };
29
+ each(/<(think|thinking|thought)>[\s\S]*?(<\/\1>|$)/gi, (m) => add(m.index, m.index + m[0].length, " "));
30
+ each(/```[\s\S]*?(```|$)/g, (m) => add(m.index, m.index + m[0].length, " "));
31
+ each(/\[([^\]\n]+)\]\((\S+?)\)/g, (m) => {
32
+ add(m.index, m.index + 1, "");
33
+ add(m.index + 1 + m[1].length, m.index + m[0].length, "");
34
+ });
35
+ each(/\bhttps?:\/\/\S+|\bwww\.\S+\.\S+/g, (m) => {
36
+ const t = m[0].replace(/[.,;:?)]+$/, "");
37
+ add(m.index, m.index + t.length, o.url ?? "link");
38
+ });
39
+ for (const [k, v] of Object.entries(o.lexicon ?? {})) each(new RegExp(`(?<![\\p{L}\\p{N}])${esc(k)}(?![\\p{L}\\p{N}])`, "gu"), (m) => add(m.index, m.index + m[0].length, v));
40
+ each(/^[ \t]*(#{1,6}|>|[-*+]|\d+[.)])[ \t]+/gm, (m) => add(m.index, m.index + m[0].length, ""));
41
+ each(/[*_~`]+/g, (m) => add(m.index, m.index + m[0].length, ""));
42
+ each(PICTO, (m) => add(m.index, m.index + m[0].length, " "));
43
+ edits.sort((a, b) => a.start - b.start);
44
+ let text = "";
45
+ const map = [];
46
+ const push = (ch, at) => {
47
+ if (/\s/.test(ch)) {
48
+ if (!text.length || /\s$/.test(text)) return;
49
+ ch = " ";
50
+ }
51
+ text += ch;
52
+ map.push(at);
53
+ };
54
+ let i = 0;
55
+ for (const e of edits) {
56
+ for (; i < e.start; i++) push(input[i], i);
57
+ for (const ch of e.repl) push(ch, e.start);
58
+ i = e.end;
59
+ }
60
+ for (; i < input.length; i++) push(input[i], i);
61
+ while (text.endsWith(" ")) {
62
+ text = text.slice(0, -1);
63
+ map.pop();
64
+ }
65
+ map.push(input.length);
66
+ return {
67
+ text,
68
+ map: Int32Array.from(map)
69
+ };
70
+ }
71
+ const ABBREV = /(?:\b(?:mr|mrs|ms|dr|st|vs|etc|e\.g|i\.e|no|approx))\.$/i;
72
+ /**
73
+ * Cuts a growing reply into segments for a voice. The first segment ends
74
+ * at a clause once it is 24 characters long so speech starts early; later
75
+ * segments end at sentences, or at the last clause or space before 160
76
+ * characters. `take(full, final)` returns the segments completed since the
77
+ * last call.
78
+ */
79
+ var SegmentCutter = class {
80
+ pos = 0;
81
+ n = 0;
82
+ first;
83
+ max;
84
+ constructor(o = {}) {
85
+ this.first = o.firstClause ?? 24;
86
+ this.max = o.maxChars ?? 160;
87
+ }
88
+ reset() {
89
+ this.pos = 0;
90
+ this.n = 0;
91
+ }
92
+ take(full, final) {
93
+ const out = [];
94
+ for (;;) {
95
+ const cut = this.findCut(full, final);
96
+ if (cut < 0) break;
97
+ const raw = full.slice(this.pos, cut);
98
+ const lead = raw.length - raw.trimStart().length;
99
+ const t = raw.trim();
100
+ if (t) out.push({
101
+ index: this.n++,
102
+ text: t,
103
+ start: this.pos + lead,
104
+ end: this.pos + lead + t.length
105
+ });
106
+ this.pos = cut;
107
+ }
108
+ return out;
109
+ }
110
+ findCut(full, final) {
111
+ const rest = full.slice(this.pos);
112
+ if (!rest.trim()) return final && rest.length ? full.length : -1;
113
+ const sentence = /[.?!]+["')\]]*(\s|$)|\n/g;
114
+ let m;
115
+ let sent = -1;
116
+ while (m = sentence.exec(rest)) {
117
+ const endsAt = m.index + m[0].length;
118
+ if (m[1] === "" && !final && endsAt === rest.length) break;
119
+ if (m[0] !== "\n" && ABBREV.test(rest.slice(0, m.index + 1))) continue;
120
+ if (rest.slice(0, m.index).trim().length === 0) continue;
121
+ sent = endsAt;
122
+ break;
123
+ }
124
+ if (this.n === 0) {
125
+ const c = /[,;:]\s/g;
126
+ while (m = c.exec(rest)) {
127
+ if (sent >= 0 && m.index >= sent) break;
128
+ if (m.index >= this.first - 1) return this.pos + m.index + 1;
129
+ }
130
+ }
131
+ if (sent >= 0) return this.pos + sent;
132
+ if (rest.length > this.max) {
133
+ const head = rest.slice(0, this.max);
134
+ const clause = Math.max(head.lastIndexOf(", "), head.lastIndexOf("; "), head.lastIndexOf(": "));
135
+ const at = clause > 0 ? clause + 1 : head.lastIndexOf(" ");
136
+ return this.pos + (at > 0 ? at : this.max);
137
+ }
138
+ return final ? full.length : -1;
139
+ }
140
+ };
141
+ /** Word spans in a text: [start, end) character offsets. */
142
+ function wordSpans(text) {
143
+ return [...text.matchAll(/[\p{L}\p{N}'’]+/gu)].map((m) => ({
144
+ start: m.index,
145
+ end: m.index + m[0].length
146
+ }));
147
+ }
148
+ /**
149
+ * Estimated word times for an engine that gives none: each word gets a
150
+ * share of the duration by its character count plus one for the gap.
151
+ * Marked estimated wherever it is reported.
152
+ */
153
+ function estimateWordTimes(text, duration) {
154
+ const w = wordSpans(text);
155
+ const weight = w.map((x) => x.end - x.start + 1);
156
+ const total = weight.reduce((a, b) => a + b, 0) || 1;
157
+ let t = 0;
158
+ return w.map((x, i) => {
159
+ const d = weight[i] / total * duration;
160
+ const r = {
161
+ ...x,
162
+ t0: t,
163
+ t1: t + d
164
+ };
165
+ t += d;
166
+ return r;
167
+ });
168
+ }
169
+ // packages/speak/src/player.ts
170
+ var GaplessPlayer = class {
171
+ ctx;
172
+ analyser;
173
+ gain;
174
+ nextT = 0;
175
+ live = /* @__PURE__ */ new Set();
176
+ buf;
177
+ lead;
178
+ fadeN;
179
+ constructor(ctx, o = {}) {
180
+ this.ctx = ctx;
181
+ this.lead = o.lead ?? .04;
182
+ this.fadeN = o.fade ?? 96;
183
+ this.gain = ctx.createGain();
184
+ this.analyser = ctx.createAnalyser();
185
+ this.analyser.fftSize = 1024;
186
+ this.gain.connect(this.analyser);
187
+ this.analyser.connect(ctx.destination);
188
+ this.buf = /* @__PURE__ */ new Float32Array(1024);
189
+ }
190
+ /** Context time when the last scheduled chunk ends. */
191
+ get endTime() {
192
+ return this.nextT;
193
+ }
194
+ get playing() {
195
+ return this.ctx.currentTime < this.nextT && this.live.size > 0;
196
+ }
197
+ /** Schedule one chunk. Fades are applied to a copy. Returns its context time span. */
198
+ schedule(samples, rate, fade = {}) {
199
+ const x = Float32Array.from(samples);
200
+ const n = Math.min(this.fadeN, Math.floor(x.length / 2));
201
+ for (let i = 0; i < n; i++) {
202
+ const g = i / n;
203
+ if (fade.in) x[i] *= g;
204
+ if (fade.out) x[x.length - 1 - i] *= g;
205
+ }
206
+ const b = this.ctx.createBuffer(1, Math.max(1, x.length), rate);
207
+ b.getChannelData(0).set(x);
208
+ const s = this.ctx.createBufferSource();
209
+ s.buffer = b;
210
+ s.connect(this.gain);
211
+ const start = Math.max(this.ctx.currentTime + this.lead, this.nextT);
212
+ const end = start + x.length / rate;
213
+ s.onended = () => this.live.delete(s);
214
+ this.live.add(s);
215
+ s.start(start);
216
+ this.nextT = end;
217
+ return {
218
+ start,
219
+ end
220
+ };
221
+ }
222
+ stop() {
223
+ for (const s of this.live) try {
224
+ s.stop();
225
+ } catch {}
226
+ this.live.clear();
227
+ this.nextT = 0;
228
+ }
229
+ /** RMS of the analyser's last window (computed), 0 when silent. */
230
+ level() {
231
+ this.analyser.getFloatTimeDomainData(this.buf);
232
+ let s = 0;
233
+ for (const v of this.buf) s += v * v;
234
+ return Math.sqrt(s / this.buf.length);
235
+ }
236
+ };
237
+ // packages/speak/src/engines.ts
238
+ /** A tone engine for `?stub` pages and tests: 60 ms per character at a low level, with exact word times. */
239
+ function stubEngine(o = {}) {
240
+ const sr = o.rate ?? 24e3;
241
+ const spc = o.secPerChar ?? .06;
242
+ const chunkSec = o.chunkSec ?? .25;
243
+ return {
244
+ kind: "pcm",
245
+ id: o.id ?? "stub",
246
+ licence: "none, no weights",
247
+ async load() {
248
+ if (o.fail === "load") throw new Error("stub engine refused to load");
249
+ },
250
+ async *synth(text, cfg, signal) {
251
+ if (o.fail === "synth") throw new Error("stub engine failed to synthesize");
252
+ if (o.fail === "hang") {
253
+ await new Promise((res) => signal.addEventListener("abort", () => res(), { once: true }));
254
+ return;
255
+ }
256
+ const dur = text.length * spc / (cfg.rate ?? 1);
257
+ const total = Math.max(1, Math.round(dur * sr));
258
+ const words = wordSpans(text).map((w) => ({
259
+ ...w,
260
+ t0: w.start * spc / (cfg.rate ?? 1),
261
+ t1: w.end * spc / (cfg.rate ?? 1)
262
+ }));
263
+ const step = Math.round(chunkSec * sr);
264
+ for (let off = 0; off < total; off += step) {
265
+ if (signal.aborted) return;
266
+ await Promise.resolve();
267
+ const n = Math.min(step, total - off);
268
+ const samples = new Float32Array(n);
269
+ for (let i = 0; i < n; i++) samples[i] = .05 * Math.sin(2 * Math.PI * 220 * (off + i) / sr);
270
+ const t0 = off / sr;
271
+ const t1 = (off + n) / sr;
272
+ const inChunk = words.filter((w) => w.t0 >= t0 && w.t0 < t1).map((w) => ({
273
+ ...w,
274
+ t0: w.t0 - t0,
275
+ t1: w.t1 - t0
276
+ }));
277
+ yield {
278
+ samples,
279
+ sampleRate: sr,
280
+ words: inChunk
281
+ };
282
+ }
283
+ },
284
+ voices: () => ["stub"]
285
+ };
286
+ }
287
+ /** What loading kokoro-js brings in, stated before it loads. */
288
+ const KOKORO_GPL_NOTICE = "kokoro-js phonemizes with the phonemizer package, which is eSpeak NG compiled to wasm under GPL-3.0-or-later. it loads from your url at run time and is never bundled into this MIT package; an app that ships kokoro-js takes on the GPL terms.";
289
+ /**
290
+ * Kokoro 82M, opt in: see KOKORO_GPL_NOTICE. Whole segments are generated at once; word times are
291
+ * estimated from the segment length by the speaker, since kokoro-js
292
+ * reports none.
293
+ */
294
+ function kokoroEngine(o) {
295
+ let tts = null;
296
+ const device = o.device ?? "wasm";
297
+ return {
298
+ kind: "pcm",
299
+ id: "kokoro",
300
+ licence: "Kokoro-82M weights Apache-2.0; kokoro-js phonemizer (eSpeak NG) GPL-3.0-or-later",
301
+ async load(ctx) {
302
+ if (tts) return;
303
+ if (!o.allowGplPhonemizer) throw new Error(`${KOKORO_GPL_NOTICE} pass allowGplPhonemizer: true to load it.`);
304
+ ctx.onStatus?.({
305
+ engine: "kokoro",
306
+ kind: "licence",
307
+ text: "kokoro 82m weights apache-2.0; its phonemizer, espeak ng, is gpl-3.0-or-later"
308
+ });
309
+ tts = await (await o.runtime()).KokoroTTS.from_pretrained(o.model ?? "onnx-community/Kokoro-82M-v1.0-ONNX", {
310
+ dtype: device === "webgpu" ? "fp32" : "q8",
311
+ device,
312
+ progress_callback: (p) => ctx.onStatus?.({
313
+ engine: "kokoro",
314
+ kind: "loading",
315
+ text: p.status ?? "loading",
316
+ ...p.progress !== void 0 ? { progress: p.progress } : {}
317
+ })
318
+ });
319
+ ctx.onStatus?.({
320
+ engine: "kokoro",
321
+ kind: "ready",
322
+ text: `kokoro ready on ${device}`
323
+ });
324
+ },
325
+ async *synth(text, cfg, signal) {
326
+ if (!tts) throw new Error("kokoro is not loaded");
327
+ const a = await tts.generate(text, {
328
+ voice: cfg.voice ?? o.voice ?? "af_heart",
329
+ speed: cfg.rate ?? 1
330
+ });
331
+ if (signal.aborted) return;
332
+ yield {
333
+ samples: a.audio,
334
+ sampleRate: a.sampling_rate
335
+ };
336
+ },
337
+ voices: () => tts?.voices ? Object.keys(tts.voices) : ["af_heart"]
338
+ };
339
+ }
340
+ /** The system voice. Plays itself; word boundaries come from the browser. */
341
+ function webSpeechEngine(o = {}) {
342
+ const g = globalThis;
343
+ const synth = o.synth ?? g.speechSynthesis;
344
+ const U = o.Utterance ?? g.SpeechSynthesisUtterance;
345
+ return {
346
+ kind: "native",
347
+ id: "webspeech",
348
+ offline: false,
349
+ licence: "system voices, the browser's and platform's terms",
350
+ async load() {
351
+ if (!synth || !U) throw new Error("no speechSynthesis in this browser");
352
+ },
353
+ speak(text, cfg, hooks, signal) {
354
+ return new Promise((resolve, reject) => {
355
+ if (!synth || !U) return reject(/* @__PURE__ */ new Error("no speechSynthesis in this browser"));
356
+ const u = new U(text);
357
+ u.rate = cfg.rate ?? 1;
358
+ u.pitch = cfg.pitch ?? 1;
359
+ u.voice = synth.getVoices().find((v) => v.name === cfg.voice) ?? null;
360
+ u.onboundary = (ev) => {
361
+ if (ev.name === void 0 || ev.name === "word") hooks.onBoundary(ev.charIndex, ev.charLength);
362
+ };
363
+ u.onstart = () => hooks.onStart?.();
364
+ u.onend = () => resolve();
365
+ u.onerror = (ev) => ev.error === "interrupted" || ev.error === "canceled" ? resolve() : reject(/* @__PURE__ */ new Error(`speech synthesis: ${ev.error ?? "error"}`));
366
+ signal.addEventListener("abort", () => synth.cancel(), { once: true });
367
+ synth.speak(u);
368
+ });
369
+ },
370
+ stop() {
371
+ synth?.cancel();
372
+ },
373
+ voices: () => synth?.getVoices().map((v) => v.name) ?? []
374
+ };
375
+ }
376
+ // packages/speak/src/bellows.ts
377
+ /**
378
+ * Legacy: a renderSpeech for bellows-voice 0.7.3, which has none, built from its
379
+ * public API as its own Singer.speak lays a line out: phrases at their
380
+ * marks, speechPlan timing, planSung spans, sungEvents for the kernel and
381
+ * renderOffline on this thread. Spoken consonants at full length, as in
382
+ * bellows-voice (SPOKEN_CONSONANT_SCALE 1).
383
+ */
384
+ function renderSpeechFrom(p) {
385
+ let registered = false;
386
+ return { renderSpeech(text, o) {
387
+ const { bellows: b, voice: v } = p;
388
+ if (!registered) {
389
+ b.registerBuiltins();
390
+ b.registerEngine(p.engine.vocalEngine);
391
+ registered = true;
392
+ }
393
+ const preset = v.voicePreset(o.voice ?? "narrator-female");
394
+ if (!preset) throw new Error(`bellows-voice: no starter voice "${o.voice}"`);
395
+ const accent = v.resolveAccent(o.accent);
396
+ const syllables = [];
397
+ const questions = [];
398
+ for (const m of v.spellOut(text).matchAll(/[^.!?;:,\n]+[.!?;:,\n]*/gu)) {
399
+ const part = v.lyricsToSyllables(m[0], {
400
+ numbers: false,
401
+ accent,
402
+ reduce: true
403
+ });
404
+ if (!part.length) continue;
405
+ part[part.length - 1].phraseEnd = true;
406
+ syllables.push(...part);
407
+ questions.push(m[0].includes("?"));
408
+ }
409
+ const line = v.speechPlan(syllables, {
410
+ hz: o.hz ?? preset.speechHz,
411
+ rate: o.rate,
412
+ prosody: accent.prosody
413
+ }, questions);
414
+ const lay = (at) => {
415
+ const out = [];
416
+ let t = at;
417
+ for (const n of line.notes) {
418
+ const dur = Number.isFinite(n.dur) && n.dur > 0 ? n.dur : 0;
419
+ if (!n.rest) out.push({
420
+ time: t,
421
+ dur,
422
+ hz: n.hz
423
+ });
424
+ t += dur;
425
+ }
426
+ return out;
427
+ };
428
+ const ids = {
429
+ phonemeParam: b.internParam("phoneme"),
430
+ bendParam: b.internParam("bend"),
431
+ nextPhonemeParam: b.internParam("nextPhoneme"),
432
+ nextInParam: b.internParam("nextIn")
433
+ };
434
+ const plan1 = (at) => {
435
+ const plan = v.planSung(lay(at), line.syllables, { consonantScale: 1 });
436
+ return {
437
+ plan,
438
+ posted: v.sungEvents(plan, {
439
+ channel: 0,
440
+ ...ids,
441
+ planLead: v.VOCAL_PLAN_LEAD,
442
+ bendLead: v.vocalGlideLead(),
443
+ firstNoteId: 1,
444
+ busy: [],
445
+ notBefore: 0
446
+ })
447
+ };
448
+ };
449
+ let { plan, posted } = plan1(0);
450
+ if (posted.leadIn > 0) ({plan, posted} = plan1(posted.leadIn));
451
+ const end = plan.phrases.reduce((e, ph) => Math.max(e, ph.end), 0);
452
+ const sampleRate = o.sampleRate ?? 48e3;
453
+ const setup = [
454
+ ...Object.entries({
455
+ phoneme: ids.phonemeParam,
456
+ bend: ids.bendParam,
457
+ nextPhoneme: ids.nextPhonemeParam,
458
+ nextIn: ids.nextInParam
459
+ }).map(([name, index]) => ({
460
+ type: "internParam",
461
+ name,
462
+ index
463
+ })),
464
+ {
465
+ type: "createChannel",
466
+ id: 0,
467
+ engineId: "vocal",
468
+ params: preset.params,
469
+ seed: `${o.seed}::ch0`
470
+ },
471
+ {
472
+ type: "events",
473
+ events: posted.events
474
+ }
475
+ ];
476
+ const a = b.renderOffline(setup, {
477
+ seconds: end + (o.tail ?? .4),
478
+ sampleRate
479
+ });
480
+ const samples = new Float32Array(a.left.length);
481
+ for (let i = 0; i < samples.length; i++) samples[i] = .5 * (a.left[i] + a.right[i]);
482
+ return {
483
+ samples,
484
+ sampleRate: a.sampleRate,
485
+ spans: plan.phrases.flatMap((ph) => ph.spans)
486
+ };
487
+ } };
488
+ }
489
+ /** The starter voices of bellows-voice 0.8.0 (VOICE_PRESETS ids). */
490
+ const BELLOWS_VOICES = [
491
+ "narrator-female",
492
+ "narrator-male",
493
+ "child",
494
+ "bass",
495
+ "baritone",
496
+ "tenor",
497
+ "contralto",
498
+ "mezzo",
499
+ "soprano",
500
+ "pop-female",
501
+ "pop-male",
502
+ "rock",
503
+ "elder",
504
+ "beatboxer"
505
+ ];
506
+ /** A seed string from an Rng: one draw, 32 bits. */
507
+ const seedFrom = (rng) => String(rng() * 2 ** 32 >>> 0);
508
+ /** Spans to phoneme timings. The engine reports no words, so each phoneme covers the whole segment text. */
509
+ function spansToPhonemes(spans, textLength) {
510
+ const out = [];
511
+ for (const s of spans) {
512
+ if (s.ipa === "_" || !(s.end > s.start)) continue;
513
+ out.push({
514
+ start: 0,
515
+ end: textLength,
516
+ t0: Math.max(0, s.start),
517
+ t1: s.end,
518
+ phoneme: s.ipa
519
+ });
520
+ }
521
+ return out;
522
+ }
523
+ function bellowsEngine(o) {
524
+ let mod = null;
525
+ const seed = seedFrom(o.rng);
526
+ let count = 0;
527
+ return {
528
+ kind: "pcm",
529
+ id: "bellows",
530
+ licence: "none, no weights (bellows-voice and bellowsjs code MIT)",
531
+ async load(ctx) {
532
+ if (mod || o.render) return;
533
+ ctx.onStatus?.({
534
+ engine: "bellows",
535
+ kind: "licence",
536
+ text: "bellows voice: no weights, code mit"
537
+ });
538
+ ctx.onStatus?.({
539
+ engine: "bellows",
540
+ kind: "loading",
541
+ text: "loading bellows-voice"
542
+ });
543
+ mod = await o.runtime();
544
+ if (typeof mod.renderSpeech !== "function") {
545
+ mod = null;
546
+ throw new Error("bellows-voice has no renderSpeech; pass bellows-voice 0.8.0 /engine, or renderSpeechFrom(parts) for 0.7.3");
547
+ }
548
+ ctx.onStatus?.({
549
+ engine: "bellows",
550
+ kind: "ready",
551
+ text: "bellows voice ready, renders on this thread"
552
+ });
553
+ },
554
+ async *synth(text, cfg, signal) {
555
+ const opts = {
556
+ voice: cfg.voice ?? o.voice ?? "narrator-female",
557
+ seed: `${seed}:${count++}`,
558
+ sampleRate: o.sampleRate ?? 48e3,
559
+ tail: .15,
560
+ ...cfg.rate !== void 0 ? { rate: cfg.rate } : {},
561
+ ...o.accent !== void 0 ? { accent: o.accent } : {}
562
+ };
563
+ let r;
564
+ if (o.render) r = await o.render(text, opts, signal);
565
+ else {
566
+ if (!mod) throw new Error("bellows is not loaded");
567
+ await Promise.resolve();
568
+ r = mod.renderSpeech(text, opts);
569
+ }
570
+ if (signal.aborted) return;
571
+ yield {
572
+ samples: r.samples,
573
+ sampleRate: r.sampleRate,
574
+ phonemes: spansToPhonemes(r.spans, text.length)
575
+ };
576
+ },
577
+ voices: () => [...BELLOWS_VOICES]
578
+ };
579
+ }
580
+ // packages/ai-env/src/source.ts
581
+ function rewriteSource(src, rewrites) {
582
+ let text = src;
583
+ const missed = [];
584
+ rewrites.forEach(([pattern, replacement], index) => {
585
+ if (typeof pattern === "string") {
586
+ if (!text.includes(pattern)) missed.push({
587
+ index,
588
+ pattern
589
+ });
590
+ else text = text.split(pattern).join(replacement);
591
+ } else {
592
+ const re = pattern.global ? pattern : new RegExp(pattern.source, pattern.flags + "g");
593
+ re.lastIndex = 0;
594
+ if (!re.test(text)) missed.push({
595
+ index,
596
+ pattern: String(pattern)
597
+ });
598
+ re.lastIndex = 0;
599
+ text = text.replace(re, replacement);
600
+ }
601
+ });
602
+ return {
603
+ text,
604
+ missed
605
+ };
606
+ }
607
+ const MODULE_WORKER = /new\s+Worker\(\s*([^,()]+(?:\([^()]*\))?[^,()]*)\s*,\s*\{([^{}]*)\}\s*\)/g;
608
+ /**
609
+ * Turn module workers into classic workers: Chrome refuses module workers
610
+ * from a file:// page (as earlier builds did). Other option keys
611
+ * are kept. Returns the text and how many constructors changed.
612
+ */
613
+ function toClassicWorker(src) {
614
+ let count = 0;
615
+ return {
616
+ text: src.replace(MODULE_WORKER, (whole, target, opts) => {
617
+ if (!/\btype\s*:\s*["'`]module["'`]/.test(opts)) return whole;
618
+ count++;
619
+ const rest = opts.split(",").map((s) => s.trim()).filter((s) => s && !/^type\s*:/.test(s));
620
+ return rest.length ? `new Worker(${target.trim()}, { ${rest.join(", ")} })` : `new Worker(${target.trim()})`;
621
+ }),
622
+ count
623
+ };
624
+ }
625
+ /**
626
+ * Make relative import specifiers absolute against `base`, so a module
627
+ * imported from a Blob or data: URL can still reach its siblings.
628
+ * Covers static `from "./x"`, bare `import "./x"` and dynamic `import("./x")`.
629
+ */
630
+ function absolutizeImports(src, base) {
631
+ const abs = (spec) => new URL(spec, base).href;
632
+ return src.replace(/(\bfrom\s*)(["'])(\.{1,2}\/[^"']*)\2/g, (_m, pre, q, spec) => `${pre}${q}${abs(spec)}${q}`).replace(/(\bimport\s*)(["'])(\.{1,2}\/[^"']*)\2/g, (_m, pre, q, spec) => `${pre}${q}${abs(spec)}${q}`).replace(/(\bimport\s*\(\s*)(["'])(\.{1,2}\/[^"']*)\2/g, (_m, pre, q, spec) => `${pre}${q}${abs(spec)}${q}`);
633
+ }
634
+ const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
635
+ /** Base64 of bytes, built in 32 KB steps so no call takes a huge argument list. */
636
+ function bytesToBase64(bytes) {
637
+ const parts = [];
638
+ const STEP = 32766;
639
+ for (let off = 0; off < bytes.length; off += STEP) {
640
+ const end = Math.min(bytes.length, off + STEP);
641
+ let s = "";
642
+ for (let i = off; i < end; i += 3) {
643
+ const a = bytes[i];
644
+ const b = i + 1 < end ? bytes[i + 1] : 0;
645
+ const c = i + 2 < end ? bytes[i + 2] : 0;
646
+ const n = a << 16 | b << 8 | c;
647
+ s += B64[n >> 18 & 63] + B64[n >> 12 & 63];
648
+ s += i + 1 < end ? B64[n >> 6 & 63] : "=";
649
+ s += i + 2 < end ? B64[n & 63] : "=";
650
+ }
651
+ parts.push(s);
652
+ }
653
+ return parts.join("");
654
+ }
655
+ function textToDataUrl(text, mime = "text/javascript") {
656
+ return `data:${mime};base64,${bytesToBase64(new TextEncoder().encode(text))}`;
657
+ }
658
+ // packages/ai-env/src/load.ts
659
+ /**
660
+ * File:// safe loading of ES modules and workers.
661
+ *
662
+ * importEsm: plain import() first when nothing needs patching and the page
663
+ * is served over http(s); else fetch the text, patch it, import it from a
664
+ * Blob URL, then from a base64 data: URL (as earlier builds did). Each URL in
665
+ * `urls` is tried in order, so a CDN fallback list is one call.
666
+ *
667
+ * spawnWorker: the worker ladder, written once. Rungs are module-blob,
668
+ * classic-blob and, opt in only, inline (the source runs on the page with
669
+ * a worker shaped shim). A rung counts once the worker posts the ready
670
+ * handshake appended after the source, so a worker whose top level code
671
+ * throws moves to the next rung instead of hanging.
672
+ *
673
+ * Integrity: importEsm takes a SHA-256 per URL and spawnWorker one for a
674
+ * URL source; fetched text whose hash differs is refused.
675
+ */
676
+ /** Lowercase hex SHA-256 of a string's UTF-8 bytes, through Web Crypto. */
677
+ async function sha256Text(text) {
678
+ const subtle = globalThis.crypto?.subtle;
679
+ if (!subtle) throw new Error("no web crypto in this context, so a sha256 cannot be checked");
680
+ const d = new Uint8Array(await subtle.digest("SHA-256", new TextEncoder().encode(text)));
681
+ return Array.from(d, (b) => b.toString(16).padStart(2, "0")).join("");
682
+ }
683
+ var LoadError = class extends Error {
684
+ attempts;
685
+ constructor(message, attempts) {
686
+ super(message);
687
+ this.name = "LoadError";
688
+ this.attempts = attempts;
689
+ }
690
+ };
691
+ function errText(e) {
692
+ return e instanceof Error ? `${e.name}: ${e.message}` : String(e);
693
+ }
694
+ const READY = "__aiEnvReady";
695
+ function handshake() {
696
+ return `try{self.postMessage({${READY}:1})}catch(e){}\n`;
697
+ }
698
+ /**
699
+ * Import module text: a Blob URL first, then a base64 data: URL (file://
700
+ * pages and runtimes without Blob URL imports). No eval.
701
+ */
702
+ async function importText(text) {
703
+ let u = null;
704
+ try {
705
+ u = URL.createObjectURL(new Blob([text], { type: "text/javascript" }));
706
+ return await import(
707
+ /* @vite-ignore */
708
+ u
709
+ );
710
+ } catch {
711
+ return await import(
712
+ /* @vite-ignore */
713
+ textToDataUrl(text)
714
+ );
715
+ } finally {
716
+ if (u) URL.revokeObjectURL(u);
717
+ }
718
+ }
719
+ /**
720
+ * A worker shaped object that runs the source on the page. The source is
721
+ * wrapped in a function in a module and imported from a Blob or data: URL,
722
+ * so no eval or Function constructor is used, and it runs in strict mode.
723
+ * Messages are delivered on a later task so ordering matches a real
724
+ * worker. It shares the page realm, so `globalThis`, the DOM and storage
725
+ * are in reach: spawnWorker uses it only when the caller lists "inline",
726
+ * and never for a URL source without a SHA-256.
727
+ */
728
+ var InlineWorker = class {
729
+ pageListeners = /* @__PURE__ */ new Map();
730
+ innerListeners = /* @__PURE__ */ new Set();
731
+ innerOnMessage = null;
732
+ dead = false;
733
+ /** Settles once the source has run; page messages wait for it, as a real worker queues them. */
734
+ started;
735
+ constructor(src) {
736
+ const self = {
737
+ postMessage: (data) => this.emit("message", { data }),
738
+ addEventListener: (type, fn) => {
739
+ if (type === "message") this.innerListeners.add(fn);
740
+ },
741
+ removeEventListener: (type, fn) => {
742
+ if (type === "message") this.innerListeners.delete(fn);
743
+ },
744
+ set onmessage(fn) {
745
+ inner.innerOnMessage = fn;
746
+ },
747
+ get onmessage() {
748
+ return inner.innerOnMessage;
749
+ },
750
+ close: () => this.terminate(),
751
+ importScripts: () => {
752
+ throw new Error("importScripts is not available in an inline worker");
753
+ }
754
+ };
755
+ const inner = this;
756
+ this.started = (async () => {
757
+ let run;
758
+ try {
759
+ run = (await importText(`export default function (self, postMessage, importScripts) {\n${src}\n}\n`)).default;
760
+ } catch (e) {
761
+ this.emit("error", { message: errText(e) });
762
+ return;
763
+ }
764
+ try {
765
+ run(self, self.postMessage, self.importScripts);
766
+ } catch (e) {
767
+ this.emit("error", { message: errText(e) });
768
+ }
769
+ })();
770
+ }
771
+ emit(type, ev) {
772
+ if (this.dead) return;
773
+ setTimeout(() => {
774
+ if (this.dead) return;
775
+ for (const fn of this.pageListeners.get(type) ?? []) fn(ev);
776
+ }, 0);
777
+ }
778
+ postMessage(data) {
779
+ if (this.dead) return;
780
+ this.started.then(() => setTimeout(() => {
781
+ if (this.dead) return;
782
+ const ev = { data };
783
+ this.innerOnMessage?.(ev);
784
+ for (const fn of this.innerListeners) fn(ev);
785
+ }, 0));
786
+ }
787
+ terminate() {
788
+ this.dead = true;
789
+ }
790
+ addEventListener(type, fn) {
791
+ let s = this.pageListeners.get(type);
792
+ if (!s) this.pageListeners.set(type, s = /* @__PURE__ */ new Set());
793
+ s.add(fn);
794
+ }
795
+ removeEventListener(type, fn) {
796
+ this.pageListeners.get(type)?.delete(fn);
797
+ }
798
+ };
799
+ function waitReady(w, ms) {
800
+ return new Promise((resolve, reject) => {
801
+ const done = (err) => {
802
+ clearTimeout(t);
803
+ w.removeEventListener("message", onMsg);
804
+ w.removeEventListener("error", onErr);
805
+ if (err === void 0) resolve();
806
+ else reject(new Error(err));
807
+ };
808
+ const onMsg = (ev) => {
809
+ const d = ev.data;
810
+ if (d && typeof d === "object" && d[READY] === 1) done();
811
+ };
812
+ const onErr = (ev) => done(ev.message || "worker error event");
813
+ const t = setTimeout(() => done(`no ready handshake in ${ms} ms`), ms);
814
+ w.addEventListener("message", onMsg);
815
+ w.addEventListener("error", onErr);
816
+ });
817
+ }
818
+ /**
819
+ * Spawn a worker from source text or a URL to source text, walking the
820
+ * rungs in `prefer` (default module-blob, classic-blob). The inline rung
821
+ * runs on the page and is used only when listed; for a URL source it also
822
+ * needs `sha256`. The ready handshake message is swallowed; the caller
823
+ * sees only its own messages.
824
+ */
825
+ async function spawnWorker(source, opts = {}) {
826
+ let src;
827
+ const want = typeof source === "string" ? void 0 : source.sha256?.toLowerCase();
828
+ if (typeof source === "string") src = source;
829
+ else {
830
+ const res = await (opts.fetch ?? globalThis.fetch.bind(globalThis))(source.url);
831
+ if (!res.ok) throw new LoadError(`worker source http ${res.status}`, [{
832
+ url: source.url,
833
+ via: "fetch",
834
+ error: `http ${res.status}`
835
+ }]);
836
+ src = await res.text();
837
+ if (want) {
838
+ const got = await sha256Text(src);
839
+ if (got !== want) throw new LoadError(`worker source sha256 ${got}, expected ${want}`, [{
840
+ url: source.url,
841
+ via: "fetch",
842
+ error: "sha256 mismatch"
843
+ }]);
844
+ }
845
+ }
846
+ if (opts.rewrites?.length) {
847
+ const r = rewriteSource(src, opts.rewrites);
848
+ if (r.missed.length) opts.onMissed?.(r.missed);
849
+ src = r.text;
850
+ }
851
+ const base = opts.base ?? (typeof source === "string" ? void 0 : source.url);
852
+ const prefer = opts.prefer ?? ["module-blob", "classic-blob"];
853
+ const readyMs = opts.readyMs ?? 4e3;
854
+ const W = opts.Worker ?? globalThis.Worker;
855
+ const mkUrl = opts.createObjectURL ?? ((b) => URL.createObjectURL(b));
856
+ const revoke = opts.revokeObjectURL ?? ((u) => URL.revokeObjectURL?.(u));
857
+ const failures = [];
858
+ const prelude = opts.prelude ? opts.prelude + "\n" : "";
859
+ for (const rung of prefer) {
860
+ let w;
861
+ let url = null;
862
+ try {
863
+ if (rung === "inline" && typeof source !== "string" && !want) throw new Error("inline runs on the page, so a url source needs a sha256 for it");
864
+ if (rung === "inline") w = new InlineWorker(prelude + src + "\n" + handshake());
865
+ else {
866
+ if (!W) throw new Error("Worker is not defined");
867
+ let body = src;
868
+ if (rung === "classic-blob") body = toClassicWorker(body).text;
869
+ else if (base) body = absolutizeImports(body, base);
870
+ url = mkUrl(new Blob([prelude + body + "\n" + handshake()], { type: "text/javascript" }));
871
+ const o = { type: rung === "module-blob" ? "module" : "classic" };
872
+ if (opts.name) o.name = opts.name;
873
+ w = new W(url, o);
874
+ }
875
+ await waitReady(w, readyMs);
876
+ return {
877
+ worker: w,
878
+ rung,
879
+ failures
880
+ };
881
+ } catch (e) {
882
+ w?.terminate();
883
+ failures.push({
884
+ rung,
885
+ error: errText(e)
886
+ });
887
+ } finally {
888
+ if (url) revoke(url);
889
+ }
890
+ }
891
+ throw new LoadError(`no worker rung started: ${failures.map((f) => `${f.rung} (${f.error})`).join("; ")}`, failures.map((f) => ({
892
+ url: "",
893
+ via: f.rung,
894
+ error: f.error
895
+ })));
896
+ }
897
+ // packages/speak/src/clone.ts
898
+ /** Average channels to mono. */
899
+ function toMono(channels) {
900
+ if (channels.length === 1) return channels[0];
901
+ const n = Math.min(...channels.map((c) => c.length));
902
+ const out = new Float32Array(n);
903
+ for (const c of channels) for (let i = 0; i < n; i++) out[i] += c[i] / channels.length;
904
+ return out;
905
+ }
906
+ function prepareClone(samples, rate, o = {}) {
907
+ const dst = o.rate ?? 24e3;
908
+ const maxN = Math.round((o.seconds ?? 15) * dst);
909
+ const n = Math.min(maxN, Math.floor(samples.length * dst / rate));
910
+ const out = new Float32Array(n);
911
+ const step = rate / dst;
912
+ for (let i = 0; i < n; i++) {
913
+ const x = i * step;
914
+ const a = Math.floor(x);
915
+ const f = x - a;
916
+ out[i] = (samples[a] ?? 0) * (1 - f) + (samples[Math.min(a + 1, samples.length - 1)] ?? 0) * f;
917
+ }
918
+ let peak = 0;
919
+ for (const v of out) peak = Math.max(peak, Math.abs(v));
920
+ if (peak > 0) {
921
+ const g = (o.peak ?? .9) / peak;
922
+ for (let i = 0; i < n; i++) out[i] *= g;
923
+ }
924
+ return out;
925
+ }
926
+ /** The community build at that commit. A caller may pass another base, with its own hashes. */
927
+ const POCKET_SPACE_BASE = `https://huggingface.co/spaces/KevinAHM/pocket-tts-web/resolve/d0c0c79b7712256a32d691c67f20b8ae2e020d00/`;
928
+ /** SHA-256 of the build's scripts at POCKET_SPACE_COMMIT (measured 2026-11-23: 33984 and 4020131 bytes). */
929
+ const POCKET_SHA256 = {
930
+ worker: "dace0a022e17dffcf60fdb7b86e49facf093f709b352fb306c1d6641ae0f5366",
931
+ sentencepiece: "fc802c6945931e685d82d0f601cda185bb43990870d712119caf5ea74e6e9c56"
932
+ };
933
+ /** Prelude that imports the checked sentencepiece.js text from a Blob URL, falling back to a data: URL. */
934
+ function pocketPrelude(sentencepieceSource) {
935
+ return [
936
+ "self.__hbSentencepiece = async () => {",
937
+ ` const t = ${JSON.stringify(sentencepieceSource)};`,
938
+ " try { return await import(URL.createObjectURL(new Blob([t], { type: 'text/javascript' }))); }",
939
+ " catch (e) { const u = new TextEncoder().encode(t); let s = ''; for (let i = 0; i < u.length; i += 32768) s += String.fromCharCode.apply(null, u.subarray(i, i + 32768));",
940
+ " return await import('data:text/javascript;base64,' + btoa(s)); }",
941
+ "};"
942
+ ].join("\n");
943
+ }
944
+ /** The four rewrites, in order: sentencepiece import, chunk gap, one wasm thread with no proxy, absolute relative paths. */
945
+ function pocketRewrites(base, chunkGapSec = .1) {
946
+ return [
947
+ [/import\(\s*(["'`])\.\/sentencepiece\.js(?:\?[^"'`]*)?\1\s*\)/, "self.__hbSentencepiece()"],
948
+ [/CHUNK_GAP_SEC\s*=\s*[\d.]+/, `CHUNK_GAP_SEC = ${chunkGapSec}`],
949
+ [/(\w+)\.env\.wasm\.wasmPaths\s*=/, "$1.env.wasm.numThreads = 1; $1.env.wasm.proxy = false; $1.env.wasm.wasmPaths ="],
950
+ [/(["'`])\.\/(?!\.)/, `$1${base}`]
951
+ ];
952
+ }
953
+ function pocketEngine(o = {}) {
954
+ const base = o.base ?? "https://huggingface.co/spaces/KevinAHM/pocket-tts-web/resolve/d0c0c79b7712256a32d691c67f20b8ae2e020d00/";
955
+ const st = o.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
956
+ const ct = o.clearTimeout ?? ((h) => clearTimeout(h));
957
+ let w = null;
958
+ let voices = [];
959
+ let voice = o.voice ?? "";
960
+ let sr = 24e3;
961
+ let sink = null;
962
+ let busy = Promise.resolve();
963
+ return {
964
+ kind: "pcm",
965
+ id: "pocket",
966
+ licence: "Pocket TTS weights CC-BY-4.0 (Kyutai); the browser build's scripts per its Space card, cc-by-4.0",
967
+ get sampleRate() {
968
+ return sr;
969
+ },
970
+ async load(ctx) {
971
+ if (w) return;
972
+ const say = (kind, text, progress) => ctx.onStatus?.({
973
+ engine: "pocket",
974
+ kind,
975
+ text,
976
+ ...progress !== void 0 ? { progress } : {}
977
+ });
978
+ say("licence", "pocket tts weights, cc-by-4.0, kyutai");
979
+ const sums = o.sha256 ?? (base === "https://huggingface.co/spaces/KevinAHM/pocket-tts-web/resolve/d0c0c79b7712256a32d691c67f20b8ae2e020d00/" ? POCKET_SHA256 : null);
980
+ if (!sums) say("loading", "pocket scripts from a custom base run unchecked; pass sha256 to pin them");
981
+ const f = o.spawn?.fetch ?? globalThis.fetch.bind(globalThis);
982
+ const spUrl = new URL("sentencepiece.js", base).href;
983
+ const spRes = await f(spUrl);
984
+ if (!spRes.ok) throw new Error(`sentencepiece.js http ${spRes.status}`);
985
+ const sp = await spRes.text();
986
+ if (sums) {
987
+ const got = await sha256Text(sp);
988
+ if (got !== sums.sentencepiece) throw new Error(`sentencepiece.js sha256 ${got}, expected ${sums.sentencepiece}`);
989
+ }
990
+ let missed = [];
991
+ const spawned = await spawnWorker({
992
+ url: new URL("inference-worker.js", base).href,
993
+ ...sums ? { sha256: sums.worker } : {}
994
+ }, {
995
+ prefer: ["classic-blob", "module-blob"],
996
+ ...o.spawn,
997
+ prelude: pocketPrelude(sp),
998
+ rewrites: pocketRewrites(base, o.chunkGapSec),
999
+ onMissed: (m) => missed = m
1000
+ });
1001
+ if (missed.length) {
1002
+ say("patch-missed", `worker patches matched nothing: ${missed.map((m) => m.pattern).join(", ")}`);
1003
+ if (o.strictPatches !== false) {
1004
+ spawned.worker.terminate();
1005
+ throw new Error("pocket worker changed upstream; patches did not match");
1006
+ }
1007
+ }
1008
+ const worker = spawned.worker;
1009
+ const fail = (err, reject) => {
1010
+ worker.removeEventListener("message", on);
1011
+ worker.terminate();
1012
+ reject(err);
1013
+ };
1014
+ let on = () => {};
1015
+ await new Promise((resolve, reject) => {
1016
+ const to = st(() => fail(/* @__PURE__ */ new Error(`pocket did not load in ${(o.loadTimeoutMs ?? 42e4) / 1e3} s`), reject), o.loadTimeoutMs ?? 42e4);
1017
+ on = (ev) => {
1018
+ const m = ev.data ?? {};
1019
+ if (m.type === "model_status" || m.type === "status") say("loading", String(m.text ?? m.status ?? "loading").slice(0, 40));
1020
+ else if (m.type === "voices_loaded") {
1021
+ voices = (m.voices ?? []).map((v) => typeof v === "string" ? v : String(v.name ?? v.id));
1022
+ voice ||= m.defaultVoice ?? voices[0] ?? "";
1023
+ } else if (m.type === "bundle_loaded" && m.sampleRate) sr = m.sampleRate;
1024
+ else if (m.type === "loaded") {
1025
+ ct(to);
1026
+ worker.removeEventListener("message", on);
1027
+ resolve();
1028
+ } else if (m.type === "error") {
1029
+ ct(to);
1030
+ fail(new Error(m.error ?? "pocket worker error"), reject);
1031
+ }
1032
+ };
1033
+ worker.addEventListener("message", on);
1034
+ worker.postMessage({ type: "load" });
1035
+ });
1036
+ worker.addEventListener("message", (ev) => sink?.(ev.data ?? {}));
1037
+ w = worker;
1038
+ if (voice) worker.postMessage({
1039
+ type: "set_voice",
1040
+ data: { voiceName: voice }
1041
+ });
1042
+ say("ready", `pocket ready on ${spawned.rung}`);
1043
+ },
1044
+ synth(text, cfg, signal) {
1045
+ const worker = w;
1046
+ if (!worker) throw new Error("pocket is not loaded");
1047
+ return { [Symbol.asyncIterator]: async function* () {
1048
+ let release;
1049
+ const prev = busy;
1050
+ busy = new Promise((r) => release = r);
1051
+ await prev;
1052
+ const queue = [];
1053
+ let wake = null;
1054
+ sink = (m) => {
1055
+ queue.push(m);
1056
+ wake?.();
1057
+ };
1058
+ const onAbort = () => {
1059
+ worker.postMessage({ type: "stop" });
1060
+ wake?.();
1061
+ };
1062
+ signal.addEventListener("abort", onAbort, { once: true });
1063
+ try {
1064
+ const v = cfg.voice ?? voice;
1065
+ worker.postMessage({
1066
+ type: "generate",
1067
+ data: {
1068
+ text,
1069
+ voice: v
1070
+ }
1071
+ });
1072
+ for (;;) {
1073
+ if (signal.aborted) return;
1074
+ const m = queue.shift();
1075
+ if (!m) {
1076
+ await new Promise((r) => wake = r);
1077
+ wake = null;
1078
+ continue;
1079
+ }
1080
+ if (m.type === "audio_chunk" && m.data instanceof Float32Array) yield {
1081
+ samples: m.data,
1082
+ sampleRate: sr
1083
+ };
1084
+ else if (m.type === "stream_ended") return;
1085
+ else if (m.type === "error") throw new Error(m.error ?? "pocket generate error");
1086
+ }
1087
+ } finally {
1088
+ signal.removeEventListener("abort", onAbort);
1089
+ sink = null;
1090
+ release();
1091
+ }
1092
+ } };
1093
+ },
1094
+ async cloneVoice(samples, rate) {
1095
+ const worker = w;
1096
+ if (!worker) throw new Error("pocket is not loaded");
1097
+ const audio = prepareClone(samples, rate, { rate: 24e3 });
1098
+ let release;
1099
+ const prev = busy;
1100
+ busy = new Promise((r) => release = r);
1101
+ await prev;
1102
+ try {
1103
+ await new Promise((resolve, reject) => {
1104
+ sink = (m) => {
1105
+ if (m.type === "voice_encoded") resolve();
1106
+ else if (m.type === "error") reject(new Error(m.error ?? "voice encode error"));
1107
+ };
1108
+ worker.postMessage({
1109
+ type: "encode_voice",
1110
+ data: { audio }
1111
+ });
1112
+ });
1113
+ } finally {
1114
+ sink = null;
1115
+ release();
1116
+ }
1117
+ voice = "custom";
1118
+ worker.postMessage({
1119
+ type: "set_voice",
1120
+ data: { voiceName: "custom" }
1121
+ });
1122
+ },
1123
+ voices: () => voices,
1124
+ dispose() {
1125
+ w?.terminate();
1126
+ w = null;
1127
+ }
1128
+ };
1129
+ }
1130
+ // packages/audio-dsp/src/writers.ts
1131
+ /** WAV bytes, interleaved. 16 bit PCM by default, or 32 bit float. */
1132
+ function encodeWav(channels, sampleRate, format = "pcm16") {
1133
+ const n = channels[0]?.length ?? 0;
1134
+ const nc = channels.length;
1135
+ const bps = format === "pcm16" ? 2 : 4;
1136
+ const bytes = n * nc * bps;
1137
+ const buf = new ArrayBuffer(44 + bytes);
1138
+ const dv = new DataView(buf);
1139
+ const str = (o, s) => {
1140
+ for (let i = 0; i < s.length; i++) dv.setUint8(o + i, s.charCodeAt(i));
1141
+ };
1142
+ str(0, "RIFF");
1143
+ dv.setUint32(4, 36 + bytes, true);
1144
+ str(8, "WAVE");
1145
+ str(12, "fmt ");
1146
+ dv.setUint32(16, 16, true);
1147
+ dv.setUint16(20, format === "pcm16" ? 1 : 3, true);
1148
+ dv.setUint16(22, nc, true);
1149
+ dv.setUint32(24, sampleRate, true);
1150
+ dv.setUint32(28, sampleRate * nc * bps, true);
1151
+ dv.setUint16(32, nc * bps, true);
1152
+ dv.setUint16(34, bps * 8, true);
1153
+ str(36, "data");
1154
+ dv.setUint32(40, bytes, true);
1155
+ let o = 44;
1156
+ for (let i = 0; i < n; i++) for (let c = 0; c < nc; c++) {
1157
+ const v = channels[c][i];
1158
+ if (format === "float32") dv.setFloat32(o, v, true);
1159
+ else {
1160
+ const x = Math.max(-1, Math.min(1, v));
1161
+ dv.setInt16(o, x < 0 ? x * 32768 : x * 32767, true);
1162
+ }
1163
+ o += bps;
1164
+ }
1165
+ return new Uint8Array(buf);
1166
+ }
1167
+ (() => {
1168
+ const t = /* @__PURE__ */ new Uint32Array(256);
1169
+ for (let i = 0; i < 256; i++) {
1170
+ let c = i;
1171
+ for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
1172
+ t[i] = c >>> 0;
1173
+ }
1174
+ return t;
1175
+ })();
1176
+ // packages/speak/src/render.ts
1177
+ /**
1178
+ * Offline render: a whole text to one buffer of samples, with word and
1179
+ * phoneme times kept as offsets in the caller's text, so "save wav" and
1180
+ * the lipsync export do not depend on capturing live playback. Every PCM
1181
+ * engine can do this, since its synth yields samples. A native engine
1182
+ * (the system voice) plays itself and hands back no audio, so it cannot:
1183
+ * `canRender` says so, and asking for it throws an OfflineRenderError
1184
+ * whose message is the copy to show.
1185
+ */
1186
+ /** The system voice plays through the platform and hands back no samples. */
1187
+ const OFFLINE_RENDER_REFUSAL = "the system voice plays live and gives no audio to save. pick bellows or pocket to save a wav.";
1188
+ /** Thrown when no engine in the chain can render offline. Its message is the copy to show; humanError in @hackbuild/devices returns it as is. */
1189
+ var OfflineRenderError = class extends Error {
1190
+ name = "OfflineRenderError";
1191
+ code;
1192
+ constructor(code, message) {
1193
+ super(message);
1194
+ this.code = code;
1195
+ }
1196
+ };
1197
+ /** Whether an engine can render to a buffer: PCM engines can unless they say otherwise, native ones cannot. */
1198
+ function canRender(e) {
1199
+ return e.kind === "pcm" && e.offline !== false;
1200
+ }
1201
+ /**
1202
+ * Render `text` on the first engine in `engines` that can render and does
1203
+ * not fail. Each engine must already be loaded, or loads here with no
1204
+ * status hooks. Native engines are skipped with OFFLINE_RENDER_REFUSAL.
1205
+ */
1206
+ async function renderSpeech(engines, text, o = {}) {
1207
+ const list = Array.isArray(engines) ? engines : [engines];
1208
+ const errors = [];
1209
+ for (const e of list) {
1210
+ if (o.signal?.aborted) break;
1211
+ if (!canRender(e)) {
1212
+ o.onSkip?.(e.id, OFFLINE_RENDER_REFUSAL);
1213
+ continue;
1214
+ }
1215
+ try {
1216
+ await e.load(o.signal ? { signal: o.signal } : {});
1217
+ return await renderOn(e, text, o);
1218
+ } catch (err) {
1219
+ if (o.signal?.aborted) break;
1220
+ const m = err instanceof Error ? err.message : String(err);
1221
+ errors.push(`${e.id}: ${m}`);
1222
+ o.onSkip?.(e.id, m);
1223
+ }
1224
+ }
1225
+ if (o.signal?.aborted) throw new DOMException("render stopped", "AbortError");
1226
+ if (!errors.length) throw new OfflineRenderError("native", OFFLINE_RENDER_REFUSAL);
1227
+ throw new OfflineRenderError("failed", `no voice could render this text. ${errors.join("; ")}.`);
1228
+ }
1229
+ async function renderOn(e, text, o) {
1230
+ const cfg = {
1231
+ ...o.voice ?? {},
1232
+ ...o.voices?.[e.id] ?? {}
1233
+ };
1234
+ const signal = o.signal ?? new AbortController().signal;
1235
+ const segs = new SegmentCutter(o.cutter).take(text, true);
1236
+ const parts = [];
1237
+ const words = [];
1238
+ const phonemes = [];
1239
+ let rate = 0;
1240
+ let n = 0;
1241
+ const gap = o.gap ?? .08;
1242
+ for (const seg of segs) {
1243
+ const sp = speakable(seg.text, o.speakable);
1244
+ if (!sp.text) continue;
1245
+ const at = (i) => seg.start + sp.map[Math.min(i, sp.map.length - 1)];
1246
+ const endAt = (i) => i > 0 ? at(i - 1) + 1 : at(0);
1247
+ if (n > 0 && rate > 0) {
1248
+ const g = new Float32Array(Math.round(gap * rate));
1249
+ parts.push(g);
1250
+ n += g.length;
1251
+ }
1252
+ const segStart = n;
1253
+ let reported = false;
1254
+ for await (const c of e.synth(sp.text, cfg, signal)) {
1255
+ if (signal.aborted) throw new DOMException("render stopped", "AbortError");
1256
+ if (!rate) rate = c.sampleRate;
1257
+ const s = c.sampleRate === rate ? c.samples : resample(c.samples, c.sampleRate, rate);
1258
+ const base = n / rate;
1259
+ const put = (list, w) => {
1260
+ const r = {
1261
+ start: at(w.start),
1262
+ end: endAt(w.end),
1263
+ t0: base + w.t0,
1264
+ t1: base + w.t1,
1265
+ estimated: false
1266
+ };
1267
+ if (w.phoneme !== void 0) r.phoneme = w.phoneme;
1268
+ list.push(r);
1269
+ };
1270
+ for (const w of c.words ?? []) {
1271
+ reported = true;
1272
+ put(words, w);
1273
+ }
1274
+ for (const p of c.phonemes ?? []) put(phonemes, p);
1275
+ parts.push(s);
1276
+ n += s.length;
1277
+ }
1278
+ if (!reported && rate) {
1279
+ const t0 = segStart / rate;
1280
+ for (const w of estimateWordTimes(sp.text, (n - segStart) / rate)) words.push({
1281
+ start: at(w.start),
1282
+ end: endAt(w.end),
1283
+ t0: t0 + w.t0,
1284
+ t1: t0 + w.t1,
1285
+ estimated: true
1286
+ });
1287
+ }
1288
+ }
1289
+ if (!rate) throw new Error("the engine returned no audio");
1290
+ const samples = new Float32Array(n);
1291
+ let off = 0;
1292
+ for (const p of parts) {
1293
+ samples.set(p, off);
1294
+ off += p.length;
1295
+ }
1296
+ return {
1297
+ samples,
1298
+ sampleRate: rate,
1299
+ duration: n / rate,
1300
+ engine: e.id,
1301
+ words,
1302
+ phonemes
1303
+ };
1304
+ }
1305
+ /** Linear resample for an engine whose chunks change rate mid render. */
1306
+ function resample(x, from, to) {
1307
+ const n = Math.max(1, Math.round(x.length * to / from));
1308
+ const y = new Float32Array(n);
1309
+ const k = from / to;
1310
+ for (let i = 0; i < n; i++) {
1311
+ const p = i * k;
1312
+ const a = Math.floor(p);
1313
+ const f = p - a;
1314
+ y[i] = (x[a] ?? 0) * (1 - f) + (x[Math.min(a + 1, x.length - 1)] ?? 0) * f;
1315
+ }
1316
+ return y;
1317
+ }
1318
+ /** The render as 16 bit wav bytes. */
1319
+ function renderedWavBytes(r) {
1320
+ return encodeWav([r.samples], r.sampleRate, "pcm16");
1321
+ }
1322
+ /** The render as a wav Blob for "save wav". */
1323
+ function renderedWav(r) {
1324
+ return new Blob([renderedWavBytes(r)], { type: "audio/wav" });
1325
+ }
1326
+ /** The render as an AudioBuffer (or the context's buffer type) at the render's rate. */
1327
+ function renderedBuffer(ctx, r) {
1328
+ const b = ctx.createBuffer(1, r.samples.length, r.sampleRate);
1329
+ b.getChannelData(0).set(r.samples);
1330
+ return b;
1331
+ }
1332
+ /** Word and phoneme times as json for the lipsync tool and "export word timing". */
1333
+ function renderedTiming(r, text) {
1334
+ return {
1335
+ engine: r.engine,
1336
+ sampleRate: r.sampleRate,
1337
+ duration: r.duration,
1338
+ words: r.words.map((w) => ({
1339
+ ...w,
1340
+ text: text.slice(w.start, w.end)
1341
+ })),
1342
+ phonemes: r.phonemes
1343
+ };
1344
+ }
1345
+ // packages/speak/src/speaker.ts
1346
+ /**
1347
+ * The speaker: takes a reply as it streams, cuts it into segments, runs
1348
+ * them through the first engine that works, plays PCM gapless on one
1349
+ * player, and reports progress as offsets in the caller's text when the
1350
+ * voice reaches them. Segment N+1 is synthesized while N plays. A
1351
+ * watchdog moves to the next engine when one goes quiet. A bounded cache
1352
+ * of recent clips makes a replay instant.
1353
+ */
1354
+ const defaultTimers = {
1355
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
1356
+ clearTimeout: (h) => clearTimeout(h)
1357
+ };
1358
+ var Watchdog = class extends Error {};
1359
+ var Speaker = class {
1360
+ player;
1361
+ o;
1362
+ timers;
1363
+ cutter;
1364
+ failed = /* @__PURE__ */ new Set();
1365
+ loaded = /* @__PURE__ */ new Set();
1366
+ queue = [];
1367
+ cues = [];
1368
+ utt = 0;
1369
+ uttText = "";
1370
+ uttFinal = true;
1371
+ abort = new AbortController();
1372
+ pumping = false;
1373
+ nativeBusy = false;
1374
+ speakingNow = false;
1375
+ waiters = [];
1376
+ nativeLevelUntil = 0;
1377
+ interval = null;
1378
+ cache = /* @__PURE__ */ new Map();
1379
+ cacheN = 0;
1380
+ current = null;
1381
+ constructor(o) {
1382
+ this.o = o;
1383
+ this.timers = o.timers ?? defaultTimers;
1384
+ this.player = new GaplessPlayer(o.ctx, o.player);
1385
+ this.cutter = new SegmentCutter(o.cutter);
1386
+ }
1387
+ /** The single analyser every PCM engine plays through. */
1388
+ get analyser() {
1389
+ return this.player.analyser;
1390
+ }
1391
+ get speaking() {
1392
+ return this.speakingNow;
1393
+ }
1394
+ /** The engine that spoke last. */
1395
+ get engine() {
1396
+ return this.current;
1397
+ }
1398
+ get utterance() {
1399
+ return this.utt;
1400
+ }
1401
+ /** Feed the visible reply so far. After `final`, the next feed starts a new utterance. */
1402
+ feed(textSoFar, final = false) {
1403
+ if (this.uttFinal) {
1404
+ this.utt++;
1405
+ this.cutter.reset();
1406
+ this.uttFinal = false;
1407
+ }
1408
+ this.uttText = textSoFar;
1409
+ for (const seg of this.cutter.take(textSoFar, final)) this.queue.push({
1410
+ seg,
1411
+ utt: this.utt,
1412
+ input: textSoFar
1413
+ });
1414
+ if (final) this.uttFinal = true;
1415
+ this.pump();
1416
+ return this.utt;
1417
+ }
1418
+ /** Speak a whole text; resolves when its audio has played or it was stopped. */
1419
+ say(text) {
1420
+ if (!this.uttFinal) this.feed(this.uttText, true);
1421
+ this.feed(text, true);
1422
+ return this.done();
1423
+ }
1424
+ /** Resolves when nothing is queued, synthesizing or playing. */
1425
+ done() {
1426
+ if (!this.busy()) return Promise.resolve();
1427
+ return new Promise((r) => this.waiters.push(r));
1428
+ }
1429
+ stop() {
1430
+ this.abort.abort();
1431
+ this.abort = new AbortController();
1432
+ this.queue = [];
1433
+ this.cues = [];
1434
+ this.player.stop();
1435
+ for (const e of this.o.engines) if (e.kind === "native") e.stop();
1436
+ this.uttFinal = true;
1437
+ this.setSpeaking(false);
1438
+ this.flushWaiters();
1439
+ }
1440
+ /**
1441
+ * Render a whole text offline on the speaker's engine chain, with its
1442
+ * voice settings, for "save wav". Engines marked failed are skipped;
1443
+ * native engines are skipped since they give no samples.
1444
+ */
1445
+ render(text, signal) {
1446
+ const o = this.o;
1447
+ return renderSpeech(o.engines.filter((e) => !this.failed.has(e.id)), text, {
1448
+ ...o.voice ? { voice: o.voice } : {},
1449
+ ...o.voices ? { voices: o.voices } : {},
1450
+ ...o.speakable ? { speakable: o.speakable } : {},
1451
+ ...o.cutter ? { cutter: o.cutter } : {},
1452
+ ...signal ? { signal } : {},
1453
+ onSkip: (engine, reason) => o.onStatus?.({
1454
+ engine,
1455
+ kind: "failed",
1456
+ text: `${engine}: ${reason}`
1457
+ })
1458
+ });
1459
+ }
1460
+ /** Clear failure marks so every engine is tried again. */
1461
+ resetEngines() {
1462
+ this.failed.clear();
1463
+ }
1464
+ /** Output level for lip sync: analyser RMS for PCM engines, a boundary pulse for a native one (estimated). */
1465
+ level() {
1466
+ if (this.nativeBusy) return this.o.ctx.currentTime < this.nativeLevelUntil ? .3 : .05;
1467
+ return this.player.level();
1468
+ }
1469
+ /** Fire cues whose time has come and settle the speaking state. Runs on a timer unless tickMs is 0. */
1470
+ tick() {
1471
+ const now = this.o.ctx.currentTime;
1472
+ if (this.cues.length) {
1473
+ const due = this.cues.filter((c) => c.time <= now);
1474
+ if (due.length) {
1475
+ this.cues = this.cues.filter((c) => c.time > now);
1476
+ for (const c of due) c.fire();
1477
+ }
1478
+ }
1479
+ if (this.speakingNow && !this.busy()) {
1480
+ this.setSpeaking(false);
1481
+ this.flushWaiters();
1482
+ } else if (!this.busy()) this.flushWaiters();
1483
+ }
1484
+ dispose() {
1485
+ this.stop();
1486
+ if (this.interval !== null) this.timers.clearTimeout(this.interval);
1487
+ this.interval = null;
1488
+ }
1489
+ busy() {
1490
+ return this.pumping || this.nativeBusy || this.queue.length > 0 || this.cues.length > 0 || this.o.ctx.currentTime < this.player.endTime;
1491
+ }
1492
+ flushWaiters() {
1493
+ const w = this.waiters;
1494
+ this.waiters = [];
1495
+ for (const r of w) r();
1496
+ }
1497
+ setSpeaking(b) {
1498
+ if (b === this.speakingNow) return;
1499
+ this.speakingNow = b;
1500
+ this.o.onSpeaking?.(b);
1501
+ if (b) this.startTicker();
1502
+ }
1503
+ startTicker() {
1504
+ const ms = this.o.tickMs ?? 25;
1505
+ if (ms <= 0 || this.interval !== null) return;
1506
+ const loop = () => {
1507
+ this.interval = null;
1508
+ this.tick();
1509
+ if (this.busy()) this.interval = this.timers.setTimeout(loop, ms);
1510
+ };
1511
+ this.interval = this.timers.setTimeout(loop, ms);
1512
+ }
1513
+ cfg(id) {
1514
+ return {
1515
+ ...this.o.voice ?? {},
1516
+ ...this.o.voices?.[id] ?? {}
1517
+ };
1518
+ }
1519
+ async ensure(e) {
1520
+ if (this.failed.has(e.id)) return false;
1521
+ if (this.loaded.has(e.id)) return true;
1522
+ try {
1523
+ this.o.onStatus?.({
1524
+ engine: e.id,
1525
+ kind: "loading",
1526
+ text: `loading ${e.id}`
1527
+ });
1528
+ await e.load({
1529
+ signal: this.abort.signal,
1530
+ onStatus: (s) => this.o.onStatus?.(s)
1531
+ });
1532
+ this.loaded.add(e.id);
1533
+ return true;
1534
+ } catch (err) {
1535
+ this.fail(e, err);
1536
+ return false;
1537
+ }
1538
+ }
1539
+ fail(e, err) {
1540
+ this.failed.add(e.id);
1541
+ const kind = err instanceof Watchdog ? "watchdog" : "failed";
1542
+ this.o.onStatus?.({
1543
+ engine: e.id,
1544
+ kind,
1545
+ text: `${e.id}: ${err instanceof Error ? err.message : String(err)}`
1546
+ });
1547
+ }
1548
+ async pump() {
1549
+ if (this.pumping) return;
1550
+ this.pumping = true;
1551
+ try {
1552
+ while (this.queue.length) {
1553
+ const job = this.queue.shift();
1554
+ const signal = this.abort.signal;
1555
+ let spoken = false;
1556
+ for (const e of this.o.engines) {
1557
+ if (signal.aborted) break;
1558
+ if (!await this.ensure(e)) continue;
1559
+ try {
1560
+ if (e.kind === "pcm") await this.runPcm(e, job.seg, job.utt, signal);
1561
+ else await this.runNative(e, job.seg, job.utt, signal);
1562
+ spoken = true;
1563
+ break;
1564
+ } catch (err) {
1565
+ if (signal.aborted) break;
1566
+ this.fail(e, err);
1567
+ }
1568
+ }
1569
+ if (!spoken && !signal.aborted) this.o.onStatus?.({
1570
+ engine: "none",
1571
+ kind: "failed",
1572
+ text: "no voice engine could speak this segment"
1573
+ });
1574
+ }
1575
+ } finally {
1576
+ this.pumping = false;
1577
+ if (this.o.tickMs === 0 || this.interval === null) this.tick();
1578
+ }
1579
+ }
1580
+ progress(p) {
1581
+ this.o.onProgress?.(p);
1582
+ }
1583
+ async *chunksOf(e, text, cfg, signal, info) {
1584
+ const key = `${e.id}|${cfg.voice ?? ""}|${cfg.rate ?? 1}|${text}`;
1585
+ const hit = this.cache.get(key);
1586
+ info.cached = !!hit;
1587
+ if (hit) {
1588
+ this.cache.delete(key);
1589
+ this.cache.set(key, hit);
1590
+ yield* hit.chunks;
1591
+ return;
1592
+ }
1593
+ const engineAbort = new AbortController();
1594
+ const onAbort = () => engineAbort.abort();
1595
+ if (signal.aborted) engineAbort.abort();
1596
+ else signal.addEventListener("abort", onAbort, { once: true });
1597
+ const it = e.synth(text, cfg, engineAbort.signal)[Symbol.asyncIterator]();
1598
+ const got = [];
1599
+ let n = 0;
1600
+ const ms = this.o.watchdogMs ?? 45e3;
1601
+ try {
1602
+ for (;;) {
1603
+ let h;
1604
+ const timeout = new Promise((_, rej) => {
1605
+ h = this.timers.setTimeout(() => rej(new Watchdog(`no audio for ${ms / 1e3} s`)), ms);
1606
+ });
1607
+ let r;
1608
+ try {
1609
+ r = await Promise.race([it.next(), timeout]);
1610
+ } catch (err) {
1611
+ engineAbort.abort();
1612
+ throw err;
1613
+ } finally {
1614
+ this.timers.clearTimeout(h);
1615
+ }
1616
+ if (r.done) break;
1617
+ got.push(r.value);
1618
+ n += r.value.samples.length;
1619
+ yield r.value;
1620
+ }
1621
+ } finally {
1622
+ signal.removeEventListener("abort", onAbort);
1623
+ }
1624
+ const cap = this.o.cacheSamples ?? 432e4;
1625
+ if (cap > 0 && n <= cap && !signal.aborted) {
1626
+ this.cache.set(key, {
1627
+ chunks: got,
1628
+ n
1629
+ });
1630
+ this.cacheN += n;
1631
+ for (const [k, v] of this.cache) {
1632
+ if (this.cacheN <= cap) break;
1633
+ this.cache.delete(k);
1634
+ this.cacheN -= v.n;
1635
+ }
1636
+ }
1637
+ }
1638
+ async runPcm(e, seg, utt, signal) {
1639
+ const sp = speakable(seg.text, this.o.speakable);
1640
+ if (!sp.text) return;
1641
+ const at = (i) => seg.start + sp.map[Math.min(i, sp.map.length - 1)];
1642
+ const cfg = this.cfg(e.id);
1643
+ let segStart = -1;
1644
+ let segEnd = -1;
1645
+ let reported = false;
1646
+ let first = true;
1647
+ let pending = null;
1648
+ const info = { cached: false };
1649
+ const place = (c, last) => {
1650
+ const span = this.player.schedule(c.samples, c.sampleRate, {
1651
+ in: first,
1652
+ out: last
1653
+ });
1654
+ if (first) {
1655
+ segStart = span.start;
1656
+ this.current = e.id;
1657
+ this.o.onSegment?.({
1658
+ ...seg,
1659
+ utterance: utt,
1660
+ engine: e.id,
1661
+ cached: info.cached
1662
+ });
1663
+ this.cue(span.start, () => {
1664
+ this.progress({
1665
+ utterance: utt,
1666
+ offset: seg.start,
1667
+ kind: "segment",
1668
+ estimated: false
1669
+ });
1670
+ this.setSpeaking(true);
1671
+ });
1672
+ this.startTicker();
1673
+ }
1674
+ first = false;
1675
+ segEnd = span.end;
1676
+ for (const [kind, list] of [["word", c.words], ["phoneme", c.phonemes]]) for (const w of list ?? []) {
1677
+ reported ||= kind === "word";
1678
+ this.placeTimed(utt, kind, w, span.start, at, false);
1679
+ }
1680
+ };
1681
+ for await (const c of this.chunksOf(e, sp.text, cfg, signal, info)) {
1682
+ if (signal.aborted) return;
1683
+ if (pending) place(pending, false);
1684
+ pending = c;
1685
+ }
1686
+ if (signal.aborted) return;
1687
+ if (pending) place(pending, true);
1688
+ if (segStart < 0) return;
1689
+ if (!reported) for (const w of estimateWordTimes(sp.text, segEnd - segStart)) this.placeTimed(utt, "word", w, segStart, at, true);
1690
+ this.cue(segEnd, () => this.progress({
1691
+ utterance: utt,
1692
+ offset: seg.end,
1693
+ kind: "end",
1694
+ estimated: false
1695
+ }));
1696
+ }
1697
+ placeTimed(utt, kind, w, base, at, estimated) {
1698
+ const ev = {
1699
+ utterance: utt,
1700
+ kind,
1701
+ start: at(w.start),
1702
+ end: at(w.end),
1703
+ t0: base + w.t0,
1704
+ t1: base + w.t1,
1705
+ estimated
1706
+ };
1707
+ if (w.phoneme !== void 0) ev.phoneme = w.phoneme;
1708
+ this.o.onTimed?.(ev);
1709
+ if (kind === "word") this.cue(ev.t0, () => this.progress({
1710
+ utterance: utt,
1711
+ offset: ev.start,
1712
+ kind: "word",
1713
+ estimated
1714
+ }));
1715
+ }
1716
+ cue(time, fire) {
1717
+ this.cues.push({
1718
+ time,
1719
+ fire
1720
+ });
1721
+ this.cues.sort((a, b) => a.time - b.time);
1722
+ }
1723
+ async runNative(e, seg, utt, signal) {
1724
+ while (!signal.aborted && this.o.ctx.currentTime < this.player.endTime) {
1725
+ await new Promise((r) => this.timers.setTimeout(r, Math.max(10, (this.player.endTime - this.o.ctx.currentTime) * 1e3)));
1726
+ this.tick();
1727
+ }
1728
+ if (signal.aborted) return;
1729
+ const sp = speakable(seg.text, this.o.speakable);
1730
+ if (!sp.text) return;
1731
+ const at = (i) => seg.start + sp.map[Math.min(i, sp.map.length - 1)];
1732
+ this.nativeBusy = true;
1733
+ this.current = e.id;
1734
+ this.o.onSegment?.({
1735
+ ...seg,
1736
+ utterance: utt,
1737
+ engine: e.id,
1738
+ cached: false
1739
+ });
1740
+ let started = false;
1741
+ const start = () => {
1742
+ if (started) return;
1743
+ started = true;
1744
+ this.setSpeaking(true);
1745
+ };
1746
+ this.progress({
1747
+ utterance: utt,
1748
+ offset: seg.start,
1749
+ kind: "segment",
1750
+ estimated: false
1751
+ });
1752
+ try {
1753
+ await e.speak(sp.text, this.cfg(e.id), {
1754
+ onStart: start,
1755
+ onBoundary: (ci, len) => {
1756
+ start();
1757
+ const t = this.o.ctx.currentTime;
1758
+ this.nativeLevelUntil = t + .15;
1759
+ const end = len !== void 0 ? ci + len : (/[\p{L}\p{N}'’]+/u.exec(sp.text.slice(ci))?.[0].length ?? 0) + ci;
1760
+ this.o.onTimed?.({
1761
+ utterance: utt,
1762
+ kind: "word",
1763
+ start: at(ci),
1764
+ end: at(end),
1765
+ t0: t,
1766
+ t1: t,
1767
+ estimated: false
1768
+ });
1769
+ this.progress({
1770
+ utterance: utt,
1771
+ offset: at(ci),
1772
+ kind: "word",
1773
+ estimated: false
1774
+ });
1775
+ }
1776
+ }, signal);
1777
+ if (!signal.aborted) this.progress({
1778
+ utterance: utt,
1779
+ offset: seg.end,
1780
+ kind: "end",
1781
+ estimated: false
1782
+ });
1783
+ } finally {
1784
+ this.nativeBusy = false;
1785
+ }
1786
+ }
1787
+ };
1788
+ function createSpeaker(o) {
1789
+ return new Speaker(o);
1790
+ }
1791
+ // packages/speak/src/records.ts
1792
+ const SPEAK_RECORDS = [
1793
+ {
1794
+ id: "kokoro-82m",
1795
+ label: "kokoro 82m",
1796
+ provides: ["speak"],
1797
+ provider: "kokoro-js",
1798
+ source: { modelId: "onnx-community/Kokoro-82M-v1.0-ONNX" },
1799
+ sizeMB: 330,
1800
+ sizeSource: "inferred",
1801
+ ladder: [{
1802
+ device: "webgpu",
1803
+ dtype: "fp32",
1804
+ needs: ["http"]
1805
+ }, {
1806
+ device: "wasm",
1807
+ dtype: "q8"
1808
+ }],
1809
+ licence: "Apache-2.0 (weights); the kokoro-js runtime phonemizes with eSpeak NG, GPL-3.0-or-later, loaded at run time and opt in",
1810
+ commercial: true,
1811
+ place: "cpu-worker",
1812
+ runtime: "kokoro-js@1.2.1",
1813
+ notes: ["webgpu with q8 gave garbled audio in an earlier build", "fp32 weights (about 330 MB, inferred) do not cache on file://, so webgpu needs http"]
1814
+ },
1815
+ {
1816
+ id: "pocket-tts",
1817
+ label: "pocket tts",
1818
+ provides: ["speak"],
1819
+ provider: "pocket-worker",
1820
+ source: {
1821
+ url: "https://huggingface.co/spaces/KevinAHM/pocket-tts-web/resolve/d0c0c79b7712256a32d691c67f20b8ae2e020d00/",
1822
+ repo: "kyutai/pocket-tts",
1823
+ revision: "d0c0c79b7712256a32d691c67f20b8ae2e020d00"
1824
+ },
1825
+ sizeMB: null,
1826
+ sizeSource: "unknown",
1827
+ ladder: [{ device: "wasm" }],
1828
+ licence: "CC-BY-4.0 (weights), MIT (code)",
1829
+ commercial: true,
1830
+ place: "cpu-worker",
1831
+ notes: ["zero shot clone from a caller supplied reference", "community browser build; its worker is patched at load and patches are reported when they stop matching"]
1832
+ },
1833
+ {
1834
+ id: "bellows-voice",
1835
+ label: "bellows voice",
1836
+ provides: ["speak"],
1837
+ provider: "bellows-voice",
1838
+ source: { repo: "virgilvox/bellows-voice" },
1839
+ sizeMB: 0,
1840
+ sizeSource: "vendor",
1841
+ ladder: [{ device: "wasm" }],
1842
+ licence: "none, no weights (code MIT)",
1843
+ commercial: true,
1844
+ place: "cpu-worker",
1845
+ runtime: "bellows-voice@0.8.0 on bellowsjs@0.5.0",
1846
+ notes: [
1847
+ "a physical model of the vocal tract, no download beyond its code (about 65 KB gzipped, vendor)",
1848
+ "deterministic per seed; the seed is drawn once from the injected rng",
1849
+ "exact phoneme times; no word times"
1850
+ ]
1851
+ },
1852
+ {
1853
+ id: "web-speech",
1854
+ label: "system voice",
1855
+ provides: ["speak"],
1856
+ provider: "system",
1857
+ source: {},
1858
+ sizeMB: 0,
1859
+ sizeSource: "vendor",
1860
+ ladder: [{ device: "browser" }],
1861
+ licence: "system voices, the platform's terms",
1862
+ commercial: "unknown",
1863
+ place: "main",
1864
+ notes: ["some browsers send text to a server for system voices"]
1865
+ }
1866
+ ];
1867
+ exports.BELLOWS_VOICES = BELLOWS_VOICES;
1868
+ exports.GaplessPlayer = GaplessPlayer;
1869
+ exports.KOKORO_GPL_NOTICE = KOKORO_GPL_NOTICE;
1870
+ exports.OFFLINE_RENDER_REFUSAL = OFFLINE_RENDER_REFUSAL;
1871
+ exports.OfflineRenderError = OfflineRenderError;
1872
+ exports.POCKET_SPACE_BASE = POCKET_SPACE_BASE;
1873
+ exports.SPEAK_RECORDS = SPEAK_RECORDS;
1874
+ exports.SegmentCutter = SegmentCutter;
1875
+ exports.Speaker = Speaker;
1876
+ exports.bellowsEngine = bellowsEngine;
1877
+ exports.canRender = canRender;
1878
+ exports.createSpeaker = createSpeaker;
1879
+ exports.estimateWordTimes = estimateWordTimes;
1880
+ exports.kokoroEngine = kokoroEngine;
1881
+ exports.pocketEngine = pocketEngine;
1882
+ exports.pocketPrelude = pocketPrelude;
1883
+ exports.pocketRewrites = pocketRewrites;
1884
+ exports.prepareClone = prepareClone;
1885
+ exports.renderSpeech = renderSpeech;
1886
+ exports.renderSpeechFrom = renderSpeechFrom;
1887
+ exports.renderedBuffer = renderedBuffer;
1888
+ exports.renderedTiming = renderedTiming;
1889
+ exports.renderedWav = renderedWav;
1890
+ exports.renderedWavBytes = renderedWavBytes;
1891
+ exports.seedFrom = seedFrom;
1892
+ exports.spansToPhonemes = spansToPhonemes;
1893
+ exports.speakable = speakable;
1894
+ exports.stubEngine = stubEngine;
1895
+ exports.toMono = toMono;
1896
+ exports.webSpeechEngine = webSpeechEngine;
1897
+ exports.wordSpans = wordSpans;
1898
+ return exports;
1899
+ })({});