@adea-ai/voice 0.0.0-stage → 0.4.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/README.md +136 -2
- package/dist/cli/helpers-cli.d.ts +2 -0
- package/dist/cli/helpers-cli.js +117 -0
- package/dist/contract/contract.d.ts +157 -0
- package/dist/contract/errors.d.ts +26 -0
- package/dist/contract/index.d.ts +10 -0
- package/dist/contract/index.js +64 -0
- package/dist/contract/session.d.ts +71 -0
- package/dist/contract/turns.d.ts +91 -0
- package/dist/contract/wire.d.ts +279 -0
- package/dist/desktop/conversation.d.ts +86 -0
- package/dist/desktop/desktop-voice.d.ts +212 -0
- package/dist/desktop/helper-lock.d.ts +121 -0
- package/dist/desktop/helper-process.d.ts +96 -0
- package/dist/desktop/index.d.ts +9 -0
- package/dist/desktop/index.js +1454 -0
- package/dist/desktop/macho-digest.d.ts +9 -0
- package/dist/index-7n7epq1a.js +47 -0
- package/dist/index-a7d617zr.js +295 -0
- package/dist/index-ght8wwpd.js +156 -0
- package/dist/index-m4g2tpeq.js +522 -0
- package/dist/index-r4hz8gk0.js +10 -0
- package/dist/index-tvz9s9nz.js +77 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +96 -0
- package/dist/settings/index.d.ts +5 -0
- package/dist/settings/index.js +34 -0
- package/dist/settings/settings.d.ts +163 -0
- package/dist/web/index.d.ts +16 -0
- package/dist/web/index.js +1697 -0
- package/dist/web/stt/speech-recognition.d.ts +226 -0
- package/dist/web/tts/locale-match.d.ts +40 -0
- package/dist/web/tts/phonon.d.ts +139 -0
- package/dist/web/tts/player.d.ts +115 -0
- package/dist/web/tts/system-voices.d.ts +162 -0
- package/dist/web/turns.d.ts +91 -0
- package/package.json +68 -4
- package/src/cli/helpers-cli.ts +135 -0
- package/src/contract/contract.ts +393 -0
- package/src/contract/errors.ts +98 -0
- package/src/contract/index.ts +10 -0
- package/src/contract/session.ts +77 -0
- package/src/contract/turns.ts +48 -0
- package/src/contract/wire.ts +384 -0
- package/src/desktop/conversation.ts +347 -0
- package/src/desktop/desktop-voice.ts +1129 -0
- package/src/desktop/helper-lock.ts +550 -0
- package/src/desktop/helper-process.ts +408 -0
- package/src/desktop/index.ts +18 -0
- package/src/desktop/macho-digest.ts +135 -0
- package/src/index.ts +7 -0
- package/src/settings/index.ts +5 -0
- package/src/settings/settings.ts +478 -0
- package/src/web/index.ts +16 -0
- package/src/web/stt/speech-recognition.ts +1013 -0
- package/src/web/tts/locale-match.ts +131 -0
- package/src/web/tts/phonon.ts +386 -0
- package/src/web/tts/player.ts +271 -0
- package/src/web/tts/system-voices.ts +510 -0
- package/src/web/turns.ts +235 -0
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Region-aware locale matching for platform voices (#36).
|
|
3
|
+
*
|
|
4
|
+
* Matching only the language subtag picks `es-ES` for an `es-419` request whenever the browser lists
|
|
5
|
+
* Spain first, which is what the 2026-11-19 acceptance run recorded in Firefox and Safari. The rule
|
|
6
|
+
* here is: **exact tag > same region group > same language**, with an explicit preference order
|
|
7
|
+
* inside a group. For Latin-American Spanish that order is `es-419`, `es-MX`, `es-US`, `es-AR`, then
|
|
8
|
+
* the other Latin-American regions, and `es-ES` only last.
|
|
9
|
+
*
|
|
10
|
+
* Pure functions over tags: no browser, no voices list.
|
|
11
|
+
*/
|
|
12
|
+
import type { VoiceLocaleMatch } from "../../contract/contract";
|
|
13
|
+
|
|
14
|
+
/** A parsed BCP-47 tag: language, optional script, optional region (upper case or 3 digits). */
|
|
15
|
+
export interface ParsedLocale {
|
|
16
|
+
readonly language: string;
|
|
17
|
+
readonly script?: string;
|
|
18
|
+
readonly region?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function parseLocale(tag: string): ParsedLocale {
|
|
22
|
+
const parts = tag.trim().replace(/_/g, "-").split("-").filter((part) => part.length > 0);
|
|
23
|
+
const language = (parts[0] ?? "").toLowerCase();
|
|
24
|
+
let script: string | undefined;
|
|
25
|
+
let region: string | undefined;
|
|
26
|
+
for (const part of parts.slice(1)) {
|
|
27
|
+
if (script === undefined && region === undefined && /^[a-z]{4}$/i.test(part)) {
|
|
28
|
+
script = part[0]!.toUpperCase() + part.slice(1).toLowerCase();
|
|
29
|
+
} else if (region === undefined && (/^[a-z]{2}$/i.test(part) || /^\d{3}$/.test(part))) {
|
|
30
|
+
region = part.toUpperCase();
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return { language, ...(script ? { script } : {}), ...(region ? { region } : {}) };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Region groups per language, each in preference order. A region's group is the first group that
|
|
38
|
+
* lists it; the first group of a language is not privileged. Chinese groups by script as well, so
|
|
39
|
+
* `zh-Hant` finds `zh-TW` and never `zh-CN`.
|
|
40
|
+
*/
|
|
41
|
+
export const REGION_GROUPS: Readonly<Record<string, readonly (readonly string[])[]>> = {
|
|
42
|
+
es: [
|
|
43
|
+
// Latin America and the US: `es-419` first, then the largest audiences, then the rest.
|
|
44
|
+
["419", "MX", "US", "AR", "CO", "CL", "PE", "VE", "EC", "GT", "CU", "BO", "DO", "HN", "PY", "SV", "NI", "CR", "PA", "UY", "PR"],
|
|
45
|
+
["ES", "GQ", "150"],
|
|
46
|
+
],
|
|
47
|
+
pt: [
|
|
48
|
+
["BR"],
|
|
49
|
+
["PT", "AO", "MZ", "CV", "GW", "ST", "TL", "MO", "150"],
|
|
50
|
+
],
|
|
51
|
+
en: [
|
|
52
|
+
["US", "CA", "PH"],
|
|
53
|
+
["GB", "IE", "AU", "NZ", "ZA", "IN", "SG", "HK", "150"],
|
|
54
|
+
],
|
|
55
|
+
fr: [
|
|
56
|
+
["FR", "BE", "CH", "LU", "MC", "150"],
|
|
57
|
+
["CA"],
|
|
58
|
+
],
|
|
59
|
+
zh: [
|
|
60
|
+
["HANS", "CN", "SG", "MY"],
|
|
61
|
+
["HANT", "TW", "HK", "MO"],
|
|
62
|
+
],
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** The region-group key of a parsed tag: Chinese groups by script first, everything else by region. */
|
|
66
|
+
function groupKey(locale: ParsedLocale): string | undefined {
|
|
67
|
+
if (locale.language === "zh" && locale.script) return locale.script.toUpperCase();
|
|
68
|
+
return locale.region;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function groupOf(locale: ParsedLocale): { group: readonly string[] } | undefined {
|
|
72
|
+
const key = groupKey(locale);
|
|
73
|
+
if (key === undefined) return undefined;
|
|
74
|
+
const group = REGION_GROUPS[locale.language]?.find((candidate) => candidate.includes(key));
|
|
75
|
+
return group ? { group } : undefined;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface LocaleMatch {
|
|
79
|
+
readonly match: VoiceLocaleMatch;
|
|
80
|
+
/** Lower is better. Stable across calls, so it can sort a list of voices. */
|
|
81
|
+
readonly rank: number;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* How well a voice's language tag serves a requested locale, or undefined for another language.
|
|
86
|
+
*
|
|
87
|
+
* - exact tag (case and `_`/`-` insensitive) is `exact`, rank 0;
|
|
88
|
+
* - a voice in the requested region's group is `region`, ranked by the group's preference order;
|
|
89
|
+
* - a request without a region accepts every voice of the language as `region`;
|
|
90
|
+
* - anything else of the same language is `language`: a region-less voice (`es`) before an
|
|
91
|
+
* off-region one (`es-ES` for `es-419`).
|
|
92
|
+
*/
|
|
93
|
+
export function matchLocale(requested: string, voiceLang: string): LocaleMatch | undefined {
|
|
94
|
+
const want = parseLocale(requested);
|
|
95
|
+
const have = parseLocale(voiceLang);
|
|
96
|
+
if (want.language.length === 0 || want.language !== have.language) return undefined;
|
|
97
|
+
if (normalize(requested) === normalize(voiceLang)) return { match: "exact", rank: 0 };
|
|
98
|
+
const wantKey = groupKey(want);
|
|
99
|
+
const haveKey = groupKey(have);
|
|
100
|
+
if (wantKey === undefined) {
|
|
101
|
+
// The request names no region: every voice of the language serves it. Region-less voices first.
|
|
102
|
+
return { match: "region", rank: haveKey === undefined ? 100 : 200 + preferenceIndex(have) };
|
|
103
|
+
}
|
|
104
|
+
if (haveKey === wantKey && (want.region === have.region || want.region === undefined || have.region === undefined)) {
|
|
105
|
+
return { match: "exact", rank: 1 };
|
|
106
|
+
}
|
|
107
|
+
const wanted = groupOf(want);
|
|
108
|
+
if (wanted && haveKey !== undefined && wanted.group.includes(haveKey)) {
|
|
109
|
+
return { match: "region", rank: 100 + wanted.group.indexOf(haveKey) };
|
|
110
|
+
}
|
|
111
|
+
if (have.region === undefined && haveKey === undefined) return { match: "language", rank: 1_000 };
|
|
112
|
+
return { match: "language", rank: 1_100 + preferenceIndex(have) };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** A voice's position in its language's preference lists, for a deterministic tie-break. */
|
|
116
|
+
function preferenceIndex(locale: ParsedLocale): number {
|
|
117
|
+
const key = groupKey(locale);
|
|
118
|
+
const groups = REGION_GROUPS[locale.language];
|
|
119
|
+
if (key === undefined || groups === undefined) return 99;
|
|
120
|
+
let offset = 0;
|
|
121
|
+
for (const group of groups) {
|
|
122
|
+
const index = group.indexOf(key);
|
|
123
|
+
if (index >= 0) return offset + index;
|
|
124
|
+
offset += group.length;
|
|
125
|
+
}
|
|
126
|
+
return 99;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function normalize(tag: string): string {
|
|
130
|
+
return tag.trim().replace(/_/g, "-").toLowerCase();
|
|
131
|
+
}
|
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Phonon 31M as the browser's local English voice (issue #27).
|
|
3
|
+
*
|
|
4
|
+
* Three rules shape this adapter:
|
|
5
|
+
*
|
|
6
|
+
* 1. **Nothing downloads by itself.** `availability` is `modelNotInstalled` until the host has the
|
|
7
|
+
* person's consent and calls `load()`; routing reports `modelDownloadDisabled` unless the host
|
|
8
|
+
* opted into the install, so a page that never uses voice never fetches a model.
|
|
9
|
+
* 2. **Only the cleared family.** Phonon 31M English is Apache-2.0 and is the only family this
|
|
10
|
+
* adapter accepts. Phonon 40M (Spanish/multilingual) is CC BY-NC 4.0 and reports
|
|
11
|
+
* `licenseNotAccepted` rather than loading; the ES-419 path belongs to platform voices (#36).
|
|
12
|
+
* 3. **Cancellation is a request cancel, not a mute.** The engine's `AbortSignal` stops generation
|
|
13
|
+
* in the worker; the player flushes what this utterance scheduled (and only that). Both happen in
|
|
14
|
+
* `cancel()`, and `done` settles when playback drained, not when generation finished.
|
|
15
|
+
*
|
|
16
|
+
* The runtime, the player and the clock are injected so the policies and the pump are testable
|
|
17
|
+
* without a browser.
|
|
18
|
+
*/
|
|
19
|
+
import type { LoadProgress, ModelSpec } from "phonon-tts";
|
|
20
|
+
|
|
21
|
+
import {
|
|
22
|
+
AVAILABLE,
|
|
23
|
+
VOICE_CONTRACT,
|
|
24
|
+
unavailable,
|
|
25
|
+
type VoiceProvider,
|
|
26
|
+
type VoiceProviderAvailability,
|
|
27
|
+
type VoiceProviderDescriptor,
|
|
28
|
+
} from "../../contract/contract";
|
|
29
|
+
import { VoiceError } from "../../contract/errors";
|
|
30
|
+
import { StreamingPcmPlayer, type AudioContextFactory } from "./player";
|
|
31
|
+
|
|
32
|
+
export type PhononFamily = "phonon-31m-en" | "phonon-40m";
|
|
33
|
+
|
|
34
|
+
/** Where the checkpoint comes from. Both forms are explicit; there is no implicit default. */
|
|
35
|
+
export type PhononModelSource =
|
|
36
|
+
| { readonly kind: "pinned" }
|
|
37
|
+
| { readonly kind: "urls"; readonly spec: ModelSpec };
|
|
38
|
+
|
|
39
|
+
export interface PhononSpeechStats {
|
|
40
|
+
readonly frames?: number;
|
|
41
|
+
readonly samples?: number;
|
|
42
|
+
readonly firstAudioMs?: number | null;
|
|
43
|
+
readonly totalMs?: number;
|
|
44
|
+
readonly cancelled: boolean;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface PhononSpeechStream extends AsyncIterable<Float32Array> {
|
|
48
|
+
readonly sampleRate: number;
|
|
49
|
+
readonly done: Promise<PhononSpeechStats>;
|
|
50
|
+
cancel(): void;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The subset of `phonon-tts`'s `PhononTTS` this adapter uses. */
|
|
54
|
+
export interface PhononEngine {
|
|
55
|
+
readonly sampleRate: number;
|
|
56
|
+
readonly voices: string[];
|
|
57
|
+
readonly languages: string[];
|
|
58
|
+
readonly device?: string;
|
|
59
|
+
readonly threads?: number;
|
|
60
|
+
stream(
|
|
61
|
+
text: string,
|
|
62
|
+
options?: { voice?: string; temperature?: number; seed?: number | bigint; signal?: AbortSignal },
|
|
63
|
+
): PhononSpeechStream;
|
|
64
|
+
dispose(): void;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface PhononLoadRequest {
|
|
68
|
+
readonly lang: string;
|
|
69
|
+
readonly model?: ModelSpec | string;
|
|
70
|
+
readonly quant?: "q8" | "f32";
|
|
71
|
+
readonly cache?: boolean;
|
|
72
|
+
readonly onProgress?: (progress: LoadProgress) => void;
|
|
73
|
+
readonly device?: "cpu" | "auto" | "webgpu";
|
|
74
|
+
readonly threads?: number | "auto";
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface PhononRuntime {
|
|
78
|
+
load(request: PhononLoadRequest): Promise<PhononEngine>;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The shipped runtime: `phonon-tts@0.7.1`, loaded on demand so nothing loads it eagerly. */
|
|
82
|
+
export const defaultPhononRuntime: PhononRuntime = {
|
|
83
|
+
async load(request) {
|
|
84
|
+
const module = await import("phonon-tts");
|
|
85
|
+
const engine = await module.PhononTTS.load(request as never);
|
|
86
|
+
return engine as unknown as PhononEngine;
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/** Deletes every model file the package cached. Exposed so settings can offer it. */
|
|
91
|
+
export async function clearPhononCache(): Promise<boolean> {
|
|
92
|
+
const module = await import("phonon-tts");
|
|
93
|
+
return module.clearCache();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface PhononProviderOptions {
|
|
97
|
+
/** Only `en` locales are served. Default `en`. */
|
|
98
|
+
readonly locale?: string;
|
|
99
|
+
/** Which family this build carries. Default `phonon-31m-en`. */
|
|
100
|
+
readonly family?: PhononFamily;
|
|
101
|
+
/** Required for `family: "phonon-31m-en"`: pinned Hub revision or explicit asset URLs. */
|
|
102
|
+
readonly model?: PhononModelSource;
|
|
103
|
+
readonly runtime?: PhononRuntime;
|
|
104
|
+
readonly device?: "cpu" | "auto" | "webgpu";
|
|
105
|
+
readonly threads?: number | "auto";
|
|
106
|
+
readonly cache?: boolean;
|
|
107
|
+
/** WebAssembly SIMD probe; injected in tests. */
|
|
108
|
+
readonly supportsSimd?: () => boolean;
|
|
109
|
+
readonly audioContextFactory?: AudioContextFactory;
|
|
110
|
+
readonly now?: () => number;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface SpeakOptions {
|
|
114
|
+
readonly voice?: string;
|
|
115
|
+
readonly temperature?: number;
|
|
116
|
+
readonly seed?: number | bigint;
|
|
117
|
+
/** Called with the first scheduled PCM chunk's latency, in milliseconds. */
|
|
118
|
+
readonly onFirstAudio?: (milliseconds: number) => void;
|
|
119
|
+
readonly onChunk?: (samples: number) => void;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface SpeechHandle {
|
|
123
|
+
/** Resolves when playback drained or cancellation finished; rejects with a `VoiceError`. */
|
|
124
|
+
readonly done: Promise<PhononSpeechStats>;
|
|
125
|
+
/** Request cancel: stops the worker's generation and flushes playback. Idempotent. */
|
|
126
|
+
cancel(): void;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export const PHONON_PROVIDER_ID = "web.phonon";
|
|
130
|
+
export const PHONON_EN_FAMILY = "phonon-31m-en";
|
|
131
|
+
|
|
132
|
+
export class PhononProvider implements VoiceProvider {
|
|
133
|
+
readonly descriptor: VoiceProviderDescriptor;
|
|
134
|
+
private readonly options: Required<Pick<PhononProviderOptions, "locale" | "family">> & PhononProviderOptions;
|
|
135
|
+
private engine: PhononEngine | undefined;
|
|
136
|
+
private player: StreamingPcmPlayer | undefined;
|
|
137
|
+
private loading: Promise<PhononEngine> | undefined;
|
|
138
|
+
/** Callers still waiting on `loading` (not aborted). Zero when it lands means nobody wants it. */
|
|
139
|
+
private loadWaiters = 0;
|
|
140
|
+
private readonly progressListeners = new Set<(progress: LoadProgress) => void>();
|
|
141
|
+
|
|
142
|
+
constructor(options: PhononProviderOptions = {}) {
|
|
143
|
+
this.options = { locale: options.locale ?? "en", family: options.family ?? PHONON_EN_FAMILY, ...options };
|
|
144
|
+
this.descriptor = {
|
|
145
|
+
id: PHONON_PROVIDER_ID,
|
|
146
|
+
displayName: "Phonon 31M (on-device)",
|
|
147
|
+
kind: "textToSpeech",
|
|
148
|
+
platforms: ["web"],
|
|
149
|
+
execution: "onDevice",
|
|
150
|
+
contract: VOICE_CONTRACT,
|
|
151
|
+
requiresModelDownload: true,
|
|
152
|
+
modelFamilies: [PHONON_EN_FAMILY],
|
|
153
|
+
licenses: [{ spdxIdentifier: "Apache-2.0", commercialUse: true }],
|
|
154
|
+
capabilities: {
|
|
155
|
+
trueCancellation: true,
|
|
156
|
+
voiceSelection: true,
|
|
157
|
+
utteranceQueueing: true,
|
|
158
|
+
localeSelection: false,
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Whether the checkpoint is loaded in this page. */
|
|
164
|
+
get isLoaded(): boolean {
|
|
165
|
+
return this.engine !== undefined;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Voices the loaded checkpoint offers. Empty before `load()`. */
|
|
169
|
+
get voices(): readonly string[] {
|
|
170
|
+
return this.engine?.voices ?? [];
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async availability(locale: string): Promise<VoiceProviderAvailability> {
|
|
174
|
+
if (this.options.family !== PHONON_EN_FAMILY) {
|
|
175
|
+
return unavailable(
|
|
176
|
+
"licenseNotAccepted",
|
|
177
|
+
"Phonon 40M weights are CC BY-NC 4.0 and are not approved for commercial distribution",
|
|
178
|
+
{ kind: "switchLocale", detail: "use platform voices for non-English speech" },
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
const language = locale.toLowerCase().split(/[-_]/)[0] ?? "";
|
|
182
|
+
if (language !== "en") {
|
|
183
|
+
if (language === "es") {
|
|
184
|
+
return unavailable(
|
|
185
|
+
"licenseNotAccepted",
|
|
186
|
+
"Spanish needs the Phonon 40M weights, which are CC BY-NC 4.0 and not approved for commercial use",
|
|
187
|
+
{ kind: "chooseAnotherProvider", detail: "use the platform voice for ES-419" },
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
return unavailable("unsupportedLocale", `${locale} is not supported by Phonon 31M`, {
|
|
191
|
+
kind: "chooseAnotherProvider",
|
|
192
|
+
detail: "use a platform voice for this language",
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
const supportsSimd = this.options.supportsSimd ?? defaultSupportsSimd;
|
|
196
|
+
if (!supportsSimd()) {
|
|
197
|
+
return unavailable("unsupportedDevice", "this browser has no WebAssembly SIMD, so Phonon cannot run", {
|
|
198
|
+
kind: "chooseAnotherProvider",
|
|
199
|
+
detail: "use a platform voice in this browser",
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
if (this.isLoaded) return AVAILABLE;
|
|
203
|
+
return unavailable("modelNotInstalled", "the Phonon 31M checkpoint is not installed in this browser", {
|
|
204
|
+
kind: "installModel",
|
|
205
|
+
detail: "download Phonon 31M (about 85 MB) for on-device speech",
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Downloads the checkpoint (explicitly, with progress) and loads it in a worker. Idempotent:
|
|
211
|
+
* concurrent callers share one download, and each gets its own progress callbacks.
|
|
212
|
+
*
|
|
213
|
+
* `signal` is per caller: aborting it rejects *that* caller with `cancelled` right away and
|
|
214
|
+
* detaches its progress listener, without affecting other callers. `phonon-tts@0.7.1`'s
|
|
215
|
+
* `PhononTTS.load` takes no `AbortSignal`, so the download itself cannot be interrupted; when it
|
|
216
|
+
* lands and every caller has aborted, the engine is disposed instead of kept.
|
|
217
|
+
*/
|
|
218
|
+
async load(options: { onProgress?: (progress: LoadProgress) => void; signal?: AbortSignal } = {}): Promise<PhononEngine> {
|
|
219
|
+
const signal = options.signal;
|
|
220
|
+
if (signal?.aborted) throw new VoiceError("cancelled");
|
|
221
|
+
if (this.engine) return this.engine;
|
|
222
|
+
const shared = this.loading ?? this.startLoading();
|
|
223
|
+
|
|
224
|
+
const listener = options.onProgress;
|
|
225
|
+
if (listener) this.progressListeners.add(listener);
|
|
226
|
+
this.loadWaiters += 1;
|
|
227
|
+
let waiting = true;
|
|
228
|
+
const release = () => {
|
|
229
|
+
if (!waiting) return;
|
|
230
|
+
waiting = false;
|
|
231
|
+
this.loadWaiters -= 1;
|
|
232
|
+
if (listener) this.progressListeners.delete(listener);
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
let detach = () => {};
|
|
236
|
+
const aborted = new Promise<never>((_, reject) => {
|
|
237
|
+
if (signal === undefined) return;
|
|
238
|
+
const onAbort = () => {
|
|
239
|
+
release();
|
|
240
|
+
reject(new VoiceError("cancelled"));
|
|
241
|
+
};
|
|
242
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
243
|
+
detach = () => signal.removeEventListener("abort", onAbort);
|
|
244
|
+
});
|
|
245
|
+
try {
|
|
246
|
+
return await Promise.race([shared, aborted]);
|
|
247
|
+
} finally {
|
|
248
|
+
release();
|
|
249
|
+
detach();
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
private startLoading(): Promise<PhononEngine> {
|
|
254
|
+
if (this.options.model === undefined) {
|
|
255
|
+
return Promise.reject(
|
|
256
|
+
new VoiceError(
|
|
257
|
+
"assets_missing",
|
|
258
|
+
"no Phonon model source is configured; the host must pin a revision or serve the assets",
|
|
259
|
+
),
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
const runtime = this.options.runtime ?? defaultPhononRuntime;
|
|
263
|
+
const request: PhononLoadRequest = {
|
|
264
|
+
lang: "en",
|
|
265
|
+
model: this.options.model.kind === "pinned" ? undefined : this.options.model.spec,
|
|
266
|
+
quant: "q8",
|
|
267
|
+
cache: this.options.cache ?? true,
|
|
268
|
+
device: this.options.device ?? "cpu",
|
|
269
|
+
threads: this.options.threads ?? "auto",
|
|
270
|
+
onProgress: (progress) => {
|
|
271
|
+
for (const listener of [...this.progressListeners]) listener(progress);
|
|
272
|
+
},
|
|
273
|
+
};
|
|
274
|
+
const loading = (async () => {
|
|
275
|
+
try {
|
|
276
|
+
const engine = await runtime.load(request);
|
|
277
|
+
if (this.loadWaiters === 0) {
|
|
278
|
+
// Every caller aborted while the download ran: do not keep a model nobody asked for.
|
|
279
|
+
engine.dispose();
|
|
280
|
+
throw new VoiceError("cancelled");
|
|
281
|
+
}
|
|
282
|
+
this.engine = engine;
|
|
283
|
+
return engine;
|
|
284
|
+
} catch (error) {
|
|
285
|
+
throw VoiceError.wrapping(error);
|
|
286
|
+
} finally {
|
|
287
|
+
this.loading = undefined;
|
|
288
|
+
}
|
|
289
|
+
})();
|
|
290
|
+
this.loading = loading;
|
|
291
|
+
return loading;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Speaks one request: streams PCM into the player, cancellable at any point. */
|
|
295
|
+
speak(text: string, options: SpeakOptions = {}): SpeechHandle {
|
|
296
|
+
const engine = this.engine;
|
|
297
|
+
if (engine === undefined) {
|
|
298
|
+
return {
|
|
299
|
+
done: Promise.reject(new VoiceError("assets_missing", "call load() after the person consents to the download")),
|
|
300
|
+
cancel: () => {},
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
const controller = new AbortController();
|
|
304
|
+
const player = this.playerFor(engine.sampleRate);
|
|
305
|
+
const startedAt = (this.options.now ?? defaultNow)();
|
|
306
|
+
const stream = engine.stream(text, {
|
|
307
|
+
voice: options.voice,
|
|
308
|
+
temperature: options.temperature,
|
|
309
|
+
seed: options.seed,
|
|
310
|
+
signal: controller.signal,
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
const clock = this.options.now ?? defaultNow;
|
|
314
|
+
// This request's own slice of the schedule: cancelling it never flushes another utterance.
|
|
315
|
+
const playback = player.beginUtterance();
|
|
316
|
+
const signal = controller.signal;
|
|
317
|
+
const done = (async (): Promise<PhononSpeechStats> => {
|
|
318
|
+
let firstChunk = true;
|
|
319
|
+
try {
|
|
320
|
+
for await (const pcm of stream) {
|
|
321
|
+
// Chunks already buffered in the stream must not reach the speakers after cancel().
|
|
322
|
+
if (signal.aborted) break;
|
|
323
|
+
if (firstChunk) {
|
|
324
|
+
firstChunk = false;
|
|
325
|
+
options.onFirstAudio?.(clock() - startedAt);
|
|
326
|
+
}
|
|
327
|
+
playback.enqueue(pcm);
|
|
328
|
+
options.onChunk?.(pcm.length);
|
|
329
|
+
}
|
|
330
|
+
if (signal.aborted) throw new VoiceError("cancelled");
|
|
331
|
+
const stats = await stream.done;
|
|
332
|
+
// Generation is over; the request is done when the person has heard it.
|
|
333
|
+
await playback.finish();
|
|
334
|
+
if (signal.aborted || playback.stopped) throw new VoiceError("cancelled");
|
|
335
|
+
return stats;
|
|
336
|
+
} catch (error) {
|
|
337
|
+
playback.stop();
|
|
338
|
+
throw VoiceError.wrapping(error);
|
|
339
|
+
}
|
|
340
|
+
})();
|
|
341
|
+
|
|
342
|
+
return {
|
|
343
|
+
done,
|
|
344
|
+
cancel: () => {
|
|
345
|
+
if (signal.aborted) return;
|
|
346
|
+
controller.abort();
|
|
347
|
+
stream.cancel();
|
|
348
|
+
playback.stop();
|
|
349
|
+
},
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** Stops generation and playback and frees the worker. */
|
|
354
|
+
dispose(): void {
|
|
355
|
+
this.engine?.dispose();
|
|
356
|
+
this.engine = undefined;
|
|
357
|
+
void this.player?.dispose();
|
|
358
|
+
this.player = undefined;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
private playerFor(sampleRate: number): StreamingPcmPlayer {
|
|
362
|
+
if (this.player === undefined) {
|
|
363
|
+
this.player = new StreamingPcmPlayer({
|
|
364
|
+
sampleRate,
|
|
365
|
+
factory: this.options.audioContextFactory,
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
return this.player;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const defaultNow = (): number => (typeof performance === "undefined" ? Date.now() : performance.now());
|
|
373
|
+
|
|
374
|
+
function defaultSupportsSimd(): boolean {
|
|
375
|
+
const wasm = (globalThis as { WebAssembly?: { validate?: (bytes: Uint8Array) => boolean } }).WebAssembly;
|
|
376
|
+
if (wasm?.validate === undefined) return false;
|
|
377
|
+
// The smallest module the engine needs is SIMD: 16-byte v128 lanes.
|
|
378
|
+
const probe = new Uint8Array([
|
|
379
|
+
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7b,
|
|
380
|
+
]);
|
|
381
|
+
try {
|
|
382
|
+
return wasm.validate(probe);
|
|
383
|
+
} catch {
|
|
384
|
+
return false;
|
|
385
|
+
}
|
|
386
|
+
}
|