@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Moheeb Zara
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,199 @@
1
- # Temporary Holding Version
1
+ # @hackbuild/speak
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Speech out for a character in a tab. A speaker takes the reply while it
4
+ streams, cuts it into segments, runs them through the first engine in a
5
+ chain that works (Kokoro, Pocket TTS, the system voice), plays PCM back to
6
+ back on one AudioContext through one analyser, and reports progress as
7
+ offsets in the caller's text when the voice reaches them. Code MIT; this
8
+ README CC-BY-4.0 with the code samples also MIT. No weights and no voice
9
+ references ship here.
10
+
11
+ # not on npm yet: the @hackbuild scope is unpublished; build from this repository
12
+ npm install @hackbuild/speak
13
+
14
+ ## Use
15
+
16
+ import { createSpeaker, kokoroEngine, pocketEngine, webSpeechEngine } from "@hackbuild/speak";
17
+ import { runtimeLoader } from "@hackbuild/devices";
18
+
19
+ const ctx = new AudioContext();
20
+ const speaker = createSpeaker({
21
+ ctx,
22
+ engines: [
23
+ pocketEngine(), // Pocket TTS, weights CC-BY-4.0, pinned build
24
+ // Kokoro 82M, weights Apache-2.0; opt in, its phonemizer is GPL (below)
25
+ kokoroEngine({ runtime: runtimeLoader(["https://cdn.jsdelivr.net/npm/kokoro-js@1.2.1/+esm"]), allowGplPhonemizer: true }),
26
+ webSpeechEngine(), // system voice
27
+ ],
28
+ onProgress: (p) => director.reached(p.offset), // action cues, same offsets as the tag parser
29
+ onTimed: (t) => lips.push(t), // words or phonemes on the audio clock
30
+ onSpeaking: (b) => listener.setTalking(b), // barge in threshold swap
31
+ onStatus: (s) => show(s),
32
+ });
33
+
34
+ for await (const ev of chat.stream(messages)) if (ev.type === "text") speaker.feed(visible += tags.feed(ev.text).text);
35
+ speaker.feed(visible, true);
36
+ speaker.analyser; // the one output node for a level or viseme driver
37
+ speaker.stop(); // barge in
38
+
39
+ ## Behaviour
40
+
41
+ - Offsets: `feed(text)` takes the visible reply (action tags already
42
+ removed by @hackbuild/structured's tag parser). Every `Progress` and
43
+ `TimedEvent` offset is in that text. `speakable()` strips think blocks
44
+ (also unclosed ones), code fences, markdown marks, link targets, emoji
45
+ and variation selectors, reads bare URLs as "link", applies a caller
46
+ lexicon, collapses whitespace, and keeps a map from each spoken
47
+ character back to the input.
48
+ - Segments: the first ends at a clause (`,` `;` `:`) once 24 characters
49
+ long, so speech starts early; later ones end at a sentence, or at the
50
+ last clause or space before 160 characters. Abbreviations (Dr., e.g.)
51
+ and decimals do not end a sentence; an open word at the stream's edge
52
+ waits.
53
+ - Pipelining: one loop synthesizes segment N+1 while N plays. Chunks are
54
+ scheduled at max(now + 40 ms, end of the last chunk) with a 96 sample
55
+ fade at the start and end of each segment.
56
+ - Chain: engines load on first use; a load error, a synth error or the
57
+ watchdog (no audio for 45 s by default) marks the engine failed and the
58
+ same segment goes to the next one. `resetEngines()` clears the marks. A
59
+ native engine waits for queued PCM to finish.
60
+ - Timing: engine word or phoneme times are placed on the audio clock.
61
+ Kokoro through kokoro-js reports none, so word times are estimated from
62
+ word length over the segment's duration and marked `estimated`. Web
63
+ Speech reports word boundaries as they happen; its level is a pulse per
64
+ boundary (estimated). A native engine counts as speaking from the
65
+ platform's start event, or its first word boundary when there is none;
66
+ with neither, `onSpeaking` never fires and time to first audio is
67
+ unknown rather than 0.
68
+ - Cache: recent clips by engine, voice, rate and text, bounded at 3
69
+ minutes of 24 kHz samples (computed), so a replay does no synthesis.
70
+ - `tick()` fires due cues; it runs every 25 ms while speaking, or pass
71
+ `tickMs: 0` and call it per frame.
72
+
73
+ ## Offline render and save wav
74
+
75
+ `renderSpeech(engines, text, opts)` renders a whole text on the first
76
+ engine that can, to one mono buffer, with word and phoneme times kept as
77
+ offsets in the input text and seconds from the buffer start. Segments are
78
+ cut as the speaker cuts them and joined with 80 ms of silence (default).
79
+ `speaker.render(text)` does the same on the speaker's chain and voice
80
+ settings. `renderedWav(r)` gives a 16 bit wav Blob, `renderedBuffer(ctx,
81
+ r)` an AudioBuffer, `renderedTiming(r, text)` the word timing json for
82
+ lipsync.
83
+
84
+ - Every PCM engine renders (stub, bellows, pocket, kokoro behind its opt
85
+ in). `canRender(engine)` reads the `offline` flag; the system voice sets
86
+ it false, since it plays through the platform and hands back no samples.
87
+ - Native engines are skipped. When nothing else is left, an
88
+ `OfflineRenderError` (code `native`) is thrown whose message is the
89
+ copy, and `humanError` from `@hackbuild/devices` returns it as is:
90
+ "the system voice plays live and gives no audio to save. pick bellows or
91
+ pocket to save a wav."
92
+ - An engine with no word times gets estimated ones, marked `estimated`.
93
+
94
+ ## Kokoro and the GPL phonemizer
95
+
96
+ kokoro-js turns text into phonemes with the `phonemizer` package, whose
97
+ npm metadata says Apache-2.0 but whose code is eSpeak NG compiled to
98
+ wasm, which is GPL-3.0-or-later. This package stays MIT because it never
99
+ bundles kokoro-js: the caller passes a loader for it. Kokoro is opt in:
100
+ `kokoroEngine` refuses to load unless `allowGplPhonemizer: true` is
101
+ passed, and `KOKORO_GPL_NOTICE` holds the text to show. No non-GPL
102
+ phonemizer for kokoro-js was found on 2026-11-23, so there is no non-GPL
103
+ Kokoro path; the MIT defaults are the bellows voice and the system voice.
104
+ An app that ships kokoro-js takes on the GPL terms.
105
+
106
+ ## Pocket TTS
107
+
108
+ The browser build is a community Space pinned to commit `d0c0c79`
109
+ (`POCKET_SPACE_COMMIT`); its weights load from that commit too.
110
+ `inference-worker.js` and `sentencepiece.js` are checked against SHA-256
111
+ values measured at that commit (`POCKET_SHA256`) before they run, since
112
+ they run with the page's origin. Another `base` takes its own `sha256`;
113
+ without one its scripts run unchecked and the load says so. A load that
114
+ times out or errors terminates its worker. `cloneVoice` waits for a
115
+ running generate. The Space card names cc-by-4.0 for the build.
116
+
117
+ The community browser build's `inference-worker.js` is fetched as text and
118
+ four rewrites run through @hackbuild/ai-env: sentencepiece loaded from a
119
+ Blob URL with a data: URL fallback, `CHUNK_GAP_SEC` 0.25 to 0.1, one wasm
120
+ thread with the proxy off before `wasmPaths`, and relative paths made
121
+ absolute against the base. A rewrite that matches nothing is reported as
122
+ `patch-missed` and, unless `strictPatches: false`, fails the load so the
123
+ chain moves on. The worker spawns classic from a Blob first (file://
124
+ refuses module workers). `cloneVoice(samples, rate)` takes a reference
125
+ the caller supplies, makes it mono 24 kHz, 15 s at most, peak 0.9, and
126
+ encodes it as voice "custom"; nothing is stored or bundled.
127
+
128
+ ## Bellows voice
129
+
130
+ `bellowsEngine({ runtime, rng })` speaks through bellows-voice, the
131
+ owner's articulatory voice for the bellowsjs engine (MIT): a physical
132
+ model of a vocal tract, so it has no weights and no weight licence; its
133
+ code is MIT and is loaded by the caller, never bundled. `runtime` returns
134
+ `bellows-voice/engine` from bellows-voice 0.8.0 on npm (the optional
135
+ peer), which imports bellowsjs 0.5.x. `renderSpeechFrom({ bellows,
136
+ voice, engine })` is legacy glue for bellows-voice 0.7.3, which has no
137
+ `renderSpeech`: the same call built from its public API as bellows' own
138
+ `speak()` lays a line out. Each segment goes through its
139
+ offline `renderSpeech`, and the chunk carries the exact phoneme spans the
140
+ engine sang (no word times; the speaker estimates those).
141
+
142
+ - Seed: one draw from the injected `rng` when the engine is made, plus the
143
+ segment count, so the same Rng gives the same audio.
144
+ - The render runs on the calling thread; pass `render(text, opts, signal)`
145
+ to call `renderSpeech` in a worker instead.
146
+ - Voices are the 14 bellows-voice starter voices (`BELLOWS_VOICES`); its
147
+ naturalness is below the neural engines (inferred), so it fits a robot,
148
+ creature or singing voice, or a fallback that needs no download.
149
+
150
+ ## What is verified, and what is not
151
+
152
+ ### Verified on this machine
153
+
154
+ - 2026-11-22: `npx vitest run packages/speak` passes, 17 tests (28 on 2026-11-23, bellows included), in Node
155
+ 22.18.0 with a fake AudioContext, a fake Web Speech API, a fake
156
+ kokoro-js module and a fake Pocket worker: speakable text and its
157
+ offset map, segment cuts, gapless scheduling and fades, progress order
158
+ against the audio clock, the engine chain with a load failure and a
159
+ watchdog trip, the cache, stop, Pocket patching, missed patch refusal,
160
+ chunk streaming and clone preparation.
161
+
162
+ - 2026-11-23: `test/bellows.test.ts`, 5 tests on a fake module: one
163
+ draw from the rng for the seed, the seed per segment, phoneme times from
164
+ the spans, a refusal without `renderSpeech`, a caller render. Then in
165
+ Node 22.18.0 against a local build of bellows-voice at ac30dc2: a 2.30 s
166
+ line rendered in 873 ms cold and 516 ms warm, byte identical for the
167
+ same rng seed and different for another, 25 phonemes (measured). The
168
+ 0.7.3 path through `renderSpeechFrom` gave the same 2.30 s line in 916
169
+ ms cold and 489 ms warm, byte identical for one seed (measured), and a
170
+ unit test checks the score it posts.
171
+ - 2026-11-23, later: a test renders "hello there." through the npm
172
+ bellows-voice 0.8.0 `/engine` (a dev dependency at the root): byte
173
+ identical for one rng seed, different for another.
174
+
175
+ - 2026-11-24: `test/render.test.ts`, 6 tests on the stub engine and fakes:
176
+ word offsets through markdown, estimated times, the skip order, the
177
+ refusal copy through `humanError`, wav bytes decoded back, and
178
+ `speaker.render` with the chain's rate.
179
+
180
+ ### Not verified by anything
181
+
182
+ - Any real engine: Kokoro 82M on webgpu fp32 or wasm q8, the Pocket
183
+ worker (its message names are taken from earlier builds, not from
184
+ upstream documentation), system voices in Chrome, Safari and Firefox.
185
+ - Audible gaps or clicks at chunk joins; looked at by nobody.
186
+ - Time to first audio (no measurement).
187
+ - Offline render on a real engine; only the stub has rendered.
188
+ - Pocket's patches against the current upstream worker source.
189
+
190
+ ## Size budget
191
+
192
+ | file | gzip (measured) | ceiling |
193
+ |---|---|---|
194
+ | `dist/index.js` (main entry, imports external) | 16,112 bytes | 16,917 bytes |
195
+ | `dist/single/index.iife.js` (single file build) | 19,747 bytes | 20,734 bytes |
196
+
197
+ Measured 2026-11-24 by `node tools/lint-packages.mjs` (gzip level 9) from the packed
198
+ tarball. Generated from `tools/size-budget.json`; CI fails when a file moves more than
199
+ 5 percent from its row.
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Bellows: the articulatory voice of bellows-voice (the owner's physical
3
+ * model of a vocal tract for the bellowsjs engine, MIT) as a PcmEngine. It
4
+ * has no weights, so there is no weight licence to state; the code it runs
5
+ * is MIT. Each segment is rendered offline with `renderSpeech` from
6
+ * `bellows-voice/engine` (bellows-voice 0.8.0 on npm),
7
+ * which returns the samples and the exact phoneme spans the engine sang.
8
+ *
9
+ * Randomness: the engine draws its jitter and noise from a string seed.
10
+ * The seed is drawn once from the injected Rng when the engine is made,
11
+ * and each segment adds its count, so the same Rng gives the same audio
12
+ * and no draw here goes to the platform random source.
13
+ *
14
+ * The render runs on the calling thread (bellows reports 8 s of speech in
15
+ * 1.1 to 1.8 s in Node, vendor), so pass `render` to move it to a worker.
16
+ */
17
+ import type { PcmEngine, Timed } from "./types.js";
18
+ export type Rng = () => number;
19
+ /** One timed sound, as bellows-voice's SungSpan, seconds from the segment start. */
20
+ export interface BellowsSpan {
21
+ ipa: string;
22
+ start: number;
23
+ end: number;
24
+ }
25
+ export interface BellowsRenderOptions {
26
+ voice?: string;
27
+ seed: string;
28
+ sampleRate?: number;
29
+ rate?: number;
30
+ hz?: number;
31
+ accent?: string;
32
+ tail?: number;
33
+ }
34
+ export interface BellowsRender {
35
+ samples: Float32Array;
36
+ sampleRate: number;
37
+ spans: BellowsSpan[];
38
+ }
39
+ /** The part of `bellows-voice/engine` this adapter calls. */
40
+ export interface BellowsVoiceModule {
41
+ renderSpeech(text: string, opts: BellowsRenderOptions): BellowsRender;
42
+ }
43
+ /** The parts of bellowsjs 0.5 and bellows-voice 0.7 (index and /engine) `renderSpeechFrom` calls. */
44
+ export interface BellowsParts {
45
+ bellows: {
46
+ internParam(name: string): number;
47
+ registerBuiltins(): void;
48
+ registerEngine(e: unknown): void;
49
+ renderOffline(setup: unknown[], o: {
50
+ seconds: number;
51
+ sampleRate?: number;
52
+ }): {
53
+ left: Float32Array;
54
+ right: Float32Array;
55
+ sampleRate: number;
56
+ };
57
+ };
58
+ voice: {
59
+ lyricsToSyllables(text: string, o?: Record<string, unknown>): unknown[];
60
+ speechPlan(syllables: readonly unknown[], o?: Record<string, unknown>, questions?: readonly boolean[]): {
61
+ syllables: unknown[];
62
+ notes: {
63
+ hz: number;
64
+ dur: number;
65
+ rest?: boolean;
66
+ }[];
67
+ };
68
+ planSung(notes: readonly {
69
+ time: number;
70
+ dur: number;
71
+ hz: number;
72
+ }[], syllables: readonly unknown[], o?: Record<string, unknown>): {
73
+ phrases: {
74
+ start: number;
75
+ end: number;
76
+ spans: BellowsSpan[];
77
+ }[];
78
+ };
79
+ sungEvents(plan: unknown, o: Record<string, unknown>): {
80
+ events: unknown[];
81
+ leadIn: number;
82
+ };
83
+ resolveAccent(a?: unknown): {
84
+ prosody?: unknown;
85
+ };
86
+ spellOut(text: string): string;
87
+ voicePreset(id: string): {
88
+ params: Record<string, number>;
89
+ speechHz: number;
90
+ } | undefined;
91
+ VOCAL_PLAN_LEAD: number;
92
+ vocalGlideLead(): number;
93
+ };
94
+ engine: {
95
+ vocalEngine: unknown;
96
+ };
97
+ }
98
+ /**
99
+ * Legacy: a renderSpeech for bellows-voice 0.7.3, which has none, built from its
100
+ * public API as its own Singer.speak lays a line out: phrases at their
101
+ * marks, speechPlan timing, planSung spans, sungEvents for the kernel and
102
+ * renderOffline on this thread. Spoken consonants at full length, as in
103
+ * bellows-voice (SPOKEN_CONSONANT_SCALE 1).
104
+ */
105
+ export declare function renderSpeechFrom(p: BellowsParts): BellowsVoiceModule;
106
+ export interface BellowsOptions {
107
+ /** Loads bellows-voice/engine (it imports bellowsjs 0.5.x itself), e.g. through runtimeLoader. */
108
+ runtime: () => Promise<BellowsVoiceModule>;
109
+ /** The injected random source; drawn once, for the seed. */
110
+ rng: Rng;
111
+ /** A bellows-voice starter voice id. Default "narrator-female". */
112
+ voice?: string;
113
+ /** One of its accents by id. Default the engine's General American. */
114
+ accent?: string;
115
+ /** Default 48000. */
116
+ sampleRate?: number;
117
+ /** Replaces the in-thread render, e.g. with a call into a worker that runs renderSpeech. */
118
+ render?: (text: string, opts: BellowsRenderOptions, signal: AbortSignal) => Promise<BellowsRender>;
119
+ }
120
+ /** The starter voices of bellows-voice 0.8.0 (VOICE_PRESETS ids). */
121
+ export declare const BELLOWS_VOICES: readonly ["narrator-female", "narrator-male", "child", "bass", "baritone", "tenor", "contralto", "mezzo", "soprano", "pop-female", "pop-male", "rock", "elder", "beatboxer"];
122
+ /** A seed string from an Rng: one draw, 32 bits. */
123
+ export declare const seedFrom: (rng: Rng) => string;
124
+ /** Spans to phoneme timings. The engine reports no words, so each phoneme covers the whole segment text. */
125
+ export declare function spansToPhonemes(spans: readonly BellowsSpan[], textLength: number): Timed[];
126
+ export declare function bellowsEngine(o: BellowsOptions): PcmEngine;
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Bellows: the articulatory voice of bellows-voice (the owner's physical
3
+ * model of a vocal tract for the bellowsjs engine, MIT) as a PcmEngine. It
4
+ * has no weights, so there is no weight licence to state; the code it runs
5
+ * is MIT. Each segment is rendered offline with `renderSpeech` from
6
+ * `bellows-voice/engine` (bellows-voice 0.8.0 on npm),
7
+ * which returns the samples and the exact phoneme spans the engine sang.
8
+ *
9
+ * Randomness: the engine draws its jitter and noise from a string seed.
10
+ * The seed is drawn once from the injected Rng when the engine is made,
11
+ * and each segment adds its count, so the same Rng gives the same audio
12
+ * and no draw here goes to the platform random source.
13
+ *
14
+ * The render runs on the calling thread (bellows reports 8 s of speech in
15
+ * 1.1 to 1.8 s in Node, vendor), so pass `render` to move it to a worker.
16
+ */
17
+ /**
18
+ * Legacy: a renderSpeech for bellows-voice 0.7.3, which has none, built from its
19
+ * public API as its own Singer.speak lays a line out: phrases at their
20
+ * marks, speechPlan timing, planSung spans, sungEvents for the kernel and
21
+ * renderOffline on this thread. Spoken consonants at full length, as in
22
+ * bellows-voice (SPOKEN_CONSONANT_SCALE 1).
23
+ */
24
+ export function renderSpeechFrom(p) {
25
+ let registered = false;
26
+ return {
27
+ renderSpeech(text, o) {
28
+ const { bellows: b, voice: v } = p;
29
+ if (!registered) {
30
+ b.registerBuiltins();
31
+ b.registerEngine(p.engine.vocalEngine);
32
+ registered = true;
33
+ }
34
+ const preset = v.voicePreset(o.voice ?? "narrator-female");
35
+ if (!preset)
36
+ throw new Error(`bellows-voice: no starter voice "${o.voice}"`);
37
+ const accent = v.resolveAccent(o.accent);
38
+ const syllables = [];
39
+ const questions = [];
40
+ for (const m of v.spellOut(text).matchAll(/[^.!?;:,\n]+[.!?;:,\n]*/gu)) {
41
+ const part = v.lyricsToSyllables(m[0], { numbers: false, accent, reduce: true });
42
+ if (!part.length)
43
+ continue;
44
+ part[part.length - 1].phraseEnd = true;
45
+ syllables.push(...part);
46
+ questions.push(m[0].includes("?"));
47
+ }
48
+ const line = v.speechPlan(syllables, { hz: o.hz ?? preset.speechHz, rate: o.rate, prosody: accent.prosody }, questions);
49
+ const lay = (at) => {
50
+ const out = [];
51
+ let t = at;
52
+ for (const n of line.notes) {
53
+ const dur = Number.isFinite(n.dur) && n.dur > 0 ? n.dur : 0;
54
+ if (!n.rest)
55
+ out.push({ time: t, dur, hz: n.hz });
56
+ t += dur;
57
+ }
58
+ return out;
59
+ };
60
+ const ids = { phonemeParam: b.internParam("phoneme"), bendParam: b.internParam("bend"), nextPhonemeParam: b.internParam("nextPhoneme"), nextInParam: b.internParam("nextIn") };
61
+ const plan1 = (at) => {
62
+ const plan = v.planSung(lay(at), line.syllables, { consonantScale: 1 });
63
+ const posted = v.sungEvents(plan, { channel: 0, ...ids, planLead: v.VOCAL_PLAN_LEAD, bendLead: v.vocalGlideLead(), firstNoteId: 1, busy: [], notBefore: 0 });
64
+ return { plan, posted };
65
+ };
66
+ let { plan, posted } = plan1(0);
67
+ if (posted.leadIn > 0)
68
+ ({ plan, posted } = plan1(posted.leadIn));
69
+ const end = plan.phrases.reduce((e, ph) => Math.max(e, ph.end), 0);
70
+ const sampleRate = o.sampleRate ?? 48000;
71
+ const setup = [
72
+ ...Object.entries({ phoneme: ids.phonemeParam, bend: ids.bendParam, nextPhoneme: ids.nextPhonemeParam, nextIn: ids.nextInParam }).map(([name, index]) => ({ type: "internParam", name, index })),
73
+ { type: "createChannel", id: 0, engineId: "vocal", params: preset.params, seed: `${o.seed}::ch0` },
74
+ { type: "events", events: posted.events },
75
+ ];
76
+ const a = b.renderOffline(setup, { seconds: end + (o.tail ?? 0.4), sampleRate });
77
+ const samples = new Float32Array(a.left.length);
78
+ for (let i = 0; i < samples.length; i++)
79
+ samples[i] = 0.5 * (a.left[i] + a.right[i]);
80
+ return { samples, sampleRate: a.sampleRate, spans: plan.phrases.flatMap((ph) => ph.spans) };
81
+ },
82
+ };
83
+ }
84
+ /** The starter voices of bellows-voice 0.8.0 (VOICE_PRESETS ids). */
85
+ export const BELLOWS_VOICES = [
86
+ "narrator-female", "narrator-male", "child", "bass", "baritone", "tenor", "contralto", "mezzo", "soprano", "pop-female", "pop-male", "rock", "elder", "beatboxer",
87
+ ];
88
+ /** A seed string from an Rng: one draw, 32 bits. */
89
+ export const seedFrom = (rng) => String((rng() * 2 ** 32) >>> 0);
90
+ /** Spans to phoneme timings. The engine reports no words, so each phoneme covers the whole segment text. */
91
+ export function spansToPhonemes(spans, textLength) {
92
+ const out = [];
93
+ for (const s of spans) {
94
+ if (s.ipa === "_" || !(s.end > s.start))
95
+ continue;
96
+ out.push({ start: 0, end: textLength, t0: Math.max(0, s.start), t1: s.end, phoneme: s.ipa });
97
+ }
98
+ return out;
99
+ }
100
+ export function bellowsEngine(o) {
101
+ let mod = null;
102
+ const seed = seedFrom(o.rng);
103
+ let count = 0;
104
+ return {
105
+ kind: "pcm",
106
+ id: "bellows",
107
+ licence: "none, no weights (bellows-voice and bellowsjs code MIT)",
108
+ async load(ctx) {
109
+ if (mod || o.render)
110
+ return;
111
+ ctx.onStatus?.({ engine: "bellows", kind: "licence", text: "bellows voice: no weights, code mit" });
112
+ ctx.onStatus?.({ engine: "bellows", kind: "loading", text: "loading bellows-voice" });
113
+ mod = await o.runtime();
114
+ if (typeof mod.renderSpeech !== "function") {
115
+ mod = null;
116
+ throw new Error("bellows-voice has no renderSpeech; pass bellows-voice 0.8.0 /engine, or renderSpeechFrom(parts) for 0.7.3");
117
+ }
118
+ ctx.onStatus?.({ engine: "bellows", kind: "ready", text: "bellows voice ready, renders on this thread" });
119
+ },
120
+ async *synth(text, cfg, signal) {
121
+ const opts = {
122
+ voice: cfg.voice ?? o.voice ?? "narrator-female",
123
+ seed: `${seed}:${count++}`,
124
+ sampleRate: o.sampleRate ?? 48000,
125
+ tail: 0.15,
126
+ ...(cfg.rate !== undefined ? { rate: cfg.rate } : {}),
127
+ ...(o.accent !== undefined ? { accent: o.accent } : {}),
128
+ };
129
+ let r;
130
+ if (o.render)
131
+ r = await o.render(text, opts, signal);
132
+ else {
133
+ if (!mod)
134
+ throw new Error("bellows is not loaded");
135
+ await Promise.resolve();
136
+ r = mod.renderSpeech(text, opts);
137
+ }
138
+ if (signal.aborted)
139
+ return;
140
+ yield { samples: r.samples, sampleRate: r.sampleRate, phonemes: spansToPhonemes(r.spans, text.length) };
141
+ },
142
+ voices: () => [...BELLOWS_VOICES],
143
+ };
144
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Voice clone reference preparation: mono in, linear resample to 24 kHz,
3
+ * cut to 15 s, peak normalized to 0.9 (earlier builds' settings). The
4
+ * reference audio is always the caller's; this package ships none.
5
+ */
6
+ export interface CloneOptions {
7
+ rate?: number;
8
+ seconds?: number;
9
+ peak?: number;
10
+ }
11
+ /** Average channels to mono. */
12
+ export declare function toMono(channels: readonly Float32Array[]): Float32Array;
13
+ export declare function prepareClone(samples: Float32Array, rate: number, o?: CloneOptions): Float32Array;
package/dist/clone.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Voice clone reference preparation: mono in, linear resample to 24 kHz,
3
+ * cut to 15 s, peak normalized to 0.9 (earlier builds' settings). The
4
+ * reference audio is always the caller's; this package ships none.
5
+ */
6
+ /** Average channels to mono. */
7
+ export function toMono(channels) {
8
+ if (channels.length === 1)
9
+ return channels[0];
10
+ const n = Math.min(...channels.map((c) => c.length));
11
+ const out = new Float32Array(n);
12
+ for (const c of channels)
13
+ for (let i = 0; i < n; i++)
14
+ out[i] += c[i] / channels.length;
15
+ return out;
16
+ }
17
+ export function prepareClone(samples, rate, o = {}) {
18
+ const dst = o.rate ?? 24000;
19
+ const maxN = Math.round((o.seconds ?? 15) * dst);
20
+ const n = Math.min(maxN, Math.floor((samples.length * dst) / rate));
21
+ const out = new Float32Array(n);
22
+ const step = rate / dst;
23
+ for (let i = 0; i < n; i++) {
24
+ const x = i * step;
25
+ const a = Math.floor(x);
26
+ const f = x - a;
27
+ out[i] = (samples[a] ?? 0) * (1 - f) + (samples[Math.min(a + 1, samples.length - 1)] ?? 0) * f;
28
+ }
29
+ let peak = 0;
30
+ for (const v of out)
31
+ peak = Math.max(peak, Math.abs(v));
32
+ if (peak > 0) {
33
+ const g = (o.peak ?? 0.9) / peak;
34
+ for (let i = 0; i < n; i++)
35
+ out[i] *= g;
36
+ }
37
+ return out;
38
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Engines: Kokoro through kokoro-js (or a transformers.js style module the
3
+ * caller passes), Web Speech, and a stub that needs no weights. Pocket TTS
4
+ * lives in pocket.ts.
5
+ */
6
+ import type { NativeEngine, PcmEngine } from "./types.js";
7
+ /** A tone engine for `?stub` pages and tests: 60 ms per character at a low level, with exact word times. */
8
+ export declare function stubEngine(o?: {
9
+ id?: string;
10
+ rate?: number;
11
+ secPerChar?: number;
12
+ chunkSec?: number;
13
+ fail?: "load" | "synth" | "hang";
14
+ }): PcmEngine;
15
+ /** The parts of kokoro-js this adapter calls (kokoro-js 1.2.1). */
16
+ export interface KokoroModule {
17
+ KokoroTTS: {
18
+ from_pretrained(id: string, o: Record<string, unknown>): Promise<{
19
+ generate(text: string, o: {
20
+ voice?: string;
21
+ speed?: number;
22
+ }): Promise<{
23
+ audio: Float32Array;
24
+ sampling_rate: number;
25
+ }>;
26
+ list_voices?(): unknown;
27
+ voices?: Record<string, unknown>;
28
+ }>;
29
+ };
30
+ }
31
+ export interface KokoroOptions {
32
+ /** Loads kokoro-js, e.g. runtimeLoader(["https://cdn.jsdelivr.net/npm/kokoro-js@1.2.1/+esm"]) from @hackbuild/devices. */
33
+ runtime: () => Promise<KokoroModule>;
34
+ /** onnx-community/Kokoro-82M-v1.0-ONNX, weights Apache-2.0. */
35
+ model?: string;
36
+ /** "webgpu" runs fp32, "wasm" runs q8 (webgpu with q8 gave garbled audio in an earlier build). Default wasm. */
37
+ device?: "webgpu" | "wasm";
38
+ voice?: string;
39
+ /**
40
+ * kokoro-js phonemizes through eSpeak NG, which is GPL-3.0-or-later. The
41
+ * engine refuses to load until the caller sets this, after reading
42
+ * KOKORO_GPL_NOTICE. No non-GPL phonemizer for kokoro-js is known on
43
+ * 2026-11-23.
44
+ */
45
+ allowGplPhonemizer?: boolean;
46
+ }
47
+ /** What loading kokoro-js brings in, stated before it loads. */
48
+ export declare 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.";
49
+ /**
50
+ * Kokoro 82M, opt in: see KOKORO_GPL_NOTICE. Whole segments are generated at once; word times are
51
+ * estimated from the segment length by the speaker, since kokoro-js
52
+ * reports none.
53
+ */
54
+ export declare function kokoroEngine(o: KokoroOptions): PcmEngine;
55
+ /** The parts of the Web Speech synthesis API used here. */
56
+ export interface SynthLike {
57
+ speak(u: UtteranceLike): void;
58
+ cancel(): void;
59
+ getVoices(): {
60
+ name: string;
61
+ lang: string;
62
+ }[];
63
+ }
64
+ export interface UtteranceLike {
65
+ text: string;
66
+ rate: number;
67
+ pitch: number;
68
+ voice: {
69
+ name: string;
70
+ lang: string;
71
+ } | null;
72
+ onboundary: ((ev: {
73
+ charIndex: number;
74
+ charLength?: number;
75
+ name?: string;
76
+ }) => void) | null;
77
+ onstart?: (() => void) | null;
78
+ onend: (() => void) | null;
79
+ onerror: ((ev: {
80
+ error?: string;
81
+ }) => void) | null;
82
+ }
83
+ /** The system voice. Plays itself; word boundaries come from the browser. */
84
+ export declare function webSpeechEngine(o?: {
85
+ synth?: SynthLike;
86
+ Utterance?: new (text: string) => UtteranceLike;
87
+ }): NativeEngine;