@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,79 @@
1
+ /**
2
+ * Offline render: a whole text to one buffer of samples, with word and
3
+ * phoneme times kept as offsets in the caller's text, so "save wav" and
4
+ * the lipsync export do not depend on capturing live playback. Every PCM
5
+ * engine can do this, since its synth yields samples. A native engine
6
+ * (the system voice) plays itself and hands back no audio, so it cannot:
7
+ * `canRender` says so, and asking for it throws an OfflineRenderError
8
+ * whose message is the copy to show.
9
+ */
10
+ import type { BufferLike } from "./player.js";
11
+ import { type CutterOptions, type SpeakableOptions } from "./text.js";
12
+ import type { Engine, PcmEngine, VoiceConfig } from "./types.js";
13
+ /** A word or phoneme in a render: offsets in the input text, times in seconds from the start of the buffer. */
14
+ export interface RenderedTimed {
15
+ start: number;
16
+ end: number;
17
+ t0: number;
18
+ t1: number;
19
+ phoneme?: string;
20
+ /** Guessed from text length because the engine reported no word times. */
21
+ estimated: boolean;
22
+ }
23
+ export interface RenderedSpeech {
24
+ /** Mono samples at `sampleRate`. */
25
+ samples: Float32Array;
26
+ sampleRate: number;
27
+ /** Seconds, computed from the sample count. */
28
+ duration: number;
29
+ /** The engine that rendered it. */
30
+ engine: string;
31
+ words: RenderedTimed[];
32
+ phonemes: RenderedTimed[];
33
+ }
34
+ export interface RenderOptions {
35
+ voice?: VoiceConfig;
36
+ /** Per voice settings by engine id, merged over `voice`. */
37
+ voices?: Record<string, VoiceConfig>;
38
+ speakable?: SpeakableOptions;
39
+ cutter?: CutterOptions;
40
+ /** Silence between segments, seconds. Default 0.08. */
41
+ gap?: number;
42
+ signal?: AbortSignal;
43
+ /** Called with each engine that is skipped and why, for a status line. */
44
+ onSkip?(engine: string, reason: string): void;
45
+ }
46
+ /** The system voice plays through the platform and hands back no samples. */
47
+ export declare const OFFLINE_RENDER_REFUSAL = "the system voice plays live and gives no audio to save. pick bellows or pocket to save a wav.";
48
+ /** 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. */
49
+ export declare class OfflineRenderError extends Error {
50
+ readonly name = "OfflineRenderError";
51
+ readonly code: "native" | "failed";
52
+ constructor(code: "native" | "failed", message: string);
53
+ }
54
+ /** Whether an engine can render to a buffer: PCM engines can unless they say otherwise, native ones cannot. */
55
+ export declare function canRender(e: Engine): e is PcmEngine;
56
+ /**
57
+ * Render `text` on the first engine in `engines` that can render and does
58
+ * not fail. Each engine must already be loaded, or loads here with no
59
+ * status hooks. Native engines are skipped with OFFLINE_RENDER_REFUSAL.
60
+ */
61
+ export declare function renderSpeech(engines: Engine | readonly Engine[], text: string, o?: RenderOptions): Promise<RenderedSpeech>;
62
+ /** The render as 16 bit wav bytes. */
63
+ export declare function renderedWavBytes(r: RenderedSpeech): Uint8Array;
64
+ /** The render as a wav Blob for "save wav". */
65
+ export declare function renderedWav(r: RenderedSpeech): Blob;
66
+ /** The render as an AudioBuffer (or the context's buffer type) at the render's rate. */
67
+ export declare function renderedBuffer<B extends BufferLike>(ctx: {
68
+ createBuffer(channels: number, length: number, rate: number): B;
69
+ }, r: RenderedSpeech): B;
70
+ /** Word and phoneme times as json for the lipsync tool and "export word timing". */
71
+ export declare function renderedTiming(r: RenderedSpeech, text: string): {
72
+ engine: string;
73
+ sampleRate: number;
74
+ duration: number;
75
+ words: (RenderedTimed & {
76
+ text: string;
77
+ })[];
78
+ phonemes: RenderedTimed[];
79
+ };
package/dist/render.js ADDED
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Offline render: a whole text to one buffer of samples, with word and
3
+ * phoneme times kept as offsets in the caller's text, so "save wav" and
4
+ * the lipsync export do not depend on capturing live playback. Every PCM
5
+ * engine can do this, since its synth yields samples. A native engine
6
+ * (the system voice) plays itself and hands back no audio, so it cannot:
7
+ * `canRender` says so, and asking for it throws an OfflineRenderError
8
+ * whose message is the copy to show.
9
+ */
10
+ import { encodeWav } from "@hackbuild/audio-dsp";
11
+ import { estimateWordTimes, SegmentCutter, speakable } from "./text.js";
12
+ /** The system voice plays through the platform and hands back no samples. */
13
+ export const OFFLINE_RENDER_REFUSAL = "the system voice plays live and gives no audio to save. pick bellows or pocket to save a wav.";
14
+ /** 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. */
15
+ export class OfflineRenderError extends Error {
16
+ name = "OfflineRenderError";
17
+ code;
18
+ constructor(code, message) {
19
+ super(message);
20
+ this.code = code;
21
+ }
22
+ }
23
+ /** Whether an engine can render to a buffer: PCM engines can unless they say otherwise, native ones cannot. */
24
+ export function canRender(e) {
25
+ return e.kind === "pcm" && e.offline !== false;
26
+ }
27
+ /**
28
+ * Render `text` on the first engine in `engines` that can render and does
29
+ * not fail. Each engine must already be loaded, or loads here with no
30
+ * status hooks. Native engines are skipped with OFFLINE_RENDER_REFUSAL.
31
+ */
32
+ export async function renderSpeech(engines, text, o = {}) {
33
+ const list = Array.isArray(engines) ? engines : [engines];
34
+ const errors = [];
35
+ for (const e of list) {
36
+ if (o.signal?.aborted)
37
+ break;
38
+ if (!canRender(e)) {
39
+ o.onSkip?.(e.id, OFFLINE_RENDER_REFUSAL);
40
+ continue;
41
+ }
42
+ try {
43
+ await e.load(o.signal ? { signal: o.signal } : {});
44
+ return await renderOn(e, text, o);
45
+ }
46
+ catch (err) {
47
+ if (o.signal?.aborted)
48
+ break;
49
+ const m = err instanceof Error ? err.message : String(err);
50
+ errors.push(`${e.id}: ${m}`);
51
+ o.onSkip?.(e.id, m);
52
+ }
53
+ }
54
+ if (o.signal?.aborted)
55
+ throw new DOMException("render stopped", "AbortError");
56
+ if (!errors.length)
57
+ throw new OfflineRenderError("native", OFFLINE_RENDER_REFUSAL);
58
+ throw new OfflineRenderError("failed", `no voice could render this text. ${errors.join("; ")}.`);
59
+ }
60
+ async function renderOn(e, text, o) {
61
+ const cfg = { ...(o.voice ?? {}), ...(o.voices?.[e.id] ?? {}) };
62
+ const signal = o.signal ?? new AbortController().signal;
63
+ const segs = new SegmentCutter(o.cutter).take(text, true);
64
+ const parts = [];
65
+ const words = [];
66
+ const phonemes = [];
67
+ let rate = 0;
68
+ let n = 0;
69
+ const gap = o.gap ?? 0.08;
70
+ for (const seg of segs) {
71
+ const sp = speakable(seg.text, o.speakable);
72
+ if (!sp.text)
73
+ continue;
74
+ const at = (i) => seg.start + sp.map[Math.min(i, sp.map.length - 1)];
75
+ // an end offset is exclusive: one past its last spoken character, so markup after a word stays out
76
+ const endAt = (i) => (i > 0 ? at(i - 1) + 1 : at(0));
77
+ if (n > 0 && rate > 0) {
78
+ const g = new Float32Array(Math.round(gap * rate));
79
+ parts.push(g);
80
+ n += g.length;
81
+ }
82
+ const segStart = n;
83
+ let reported = false;
84
+ for await (const c of e.synth(sp.text, cfg, signal)) {
85
+ if (signal.aborted)
86
+ throw new DOMException("render stopped", "AbortError");
87
+ if (!rate)
88
+ rate = c.sampleRate;
89
+ const s = c.sampleRate === rate ? c.samples : resample(c.samples, c.sampleRate, rate);
90
+ const base = n / rate;
91
+ const put = (list, w) => {
92
+ const r = { start: at(w.start), end: endAt(w.end), t0: base + w.t0, t1: base + w.t1, estimated: false };
93
+ if (w.phoneme !== undefined)
94
+ r.phoneme = w.phoneme;
95
+ list.push(r);
96
+ };
97
+ for (const w of c.words ?? []) {
98
+ reported = true;
99
+ put(words, w);
100
+ }
101
+ for (const p of c.phonemes ?? [])
102
+ put(phonemes, p);
103
+ parts.push(s);
104
+ n += s.length;
105
+ }
106
+ if (!reported && rate) {
107
+ const t0 = segStart / rate;
108
+ for (const w of estimateWordTimes(sp.text, (n - segStart) / rate))
109
+ words.push({ start: at(w.start), end: endAt(w.end), t0: t0 + w.t0, t1: t0 + w.t1, estimated: true });
110
+ }
111
+ }
112
+ if (!rate)
113
+ throw new Error("the engine returned no audio");
114
+ const samples = new Float32Array(n);
115
+ let off = 0;
116
+ for (const p of parts) {
117
+ samples.set(p, off);
118
+ off += p.length;
119
+ }
120
+ return { samples, sampleRate: rate, duration: n / rate, engine: e.id, words, phonemes };
121
+ }
122
+ /** Linear resample for an engine whose chunks change rate mid render. */
123
+ function resample(x, from, to) {
124
+ const n = Math.max(1, Math.round((x.length * to) / from));
125
+ const y = new Float32Array(n);
126
+ const k = from / to;
127
+ for (let i = 0; i < n; i++) {
128
+ const p = i * k;
129
+ const a = Math.floor(p);
130
+ const f = p - a;
131
+ y[i] = (x[a] ?? 0) * (1 - f) + (x[Math.min(a + 1, x.length - 1)] ?? 0) * f;
132
+ }
133
+ return y;
134
+ }
135
+ /** The render as 16 bit wav bytes. */
136
+ export function renderedWavBytes(r) {
137
+ return encodeWav([r.samples], r.sampleRate, "pcm16");
138
+ }
139
+ /** The render as a wav Blob for "save wav". */
140
+ export function renderedWav(r) {
141
+ return new Blob([renderedWavBytes(r)], { type: "audio/wav" });
142
+ }
143
+ /** The render as an AudioBuffer (or the context's buffer type) at the render's rate. */
144
+ export function renderedBuffer(ctx, r) {
145
+ const b = ctx.createBuffer(1, r.samples.length, r.sampleRate);
146
+ b.getChannelData(0).set(r.samples);
147
+ return b;
148
+ }
149
+ /** Word and phoneme times as json for the lipsync tool and "export word timing". */
150
+ export function renderedTiming(r, text) {
151
+ return {
152
+ engine: r.engine,
153
+ sampleRate: r.sampleRate,
154
+ duration: r.duration,
155
+ words: r.words.map((w) => ({ ...w, text: text.slice(w.start, w.end) })),
156
+ phonemes: r.phonemes,
157
+ };
158
+ }