@adea-ai/voice 0.0.0-stage → 0.2.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 +51 -2
- package/dist/cli/helpers-cli.d.ts +2 -0
- package/dist/cli/helpers-cli.js +102 -0
- package/dist/contract/contract.d.ts +138 -0
- package/dist/contract/errors.d.ts +26 -0
- package/dist/contract/index.d.ts +9 -0
- package/dist/contract/index.js +54 -0
- package/dist/contract/session.d.ts +58 -0
- package/dist/contract/wire.d.ts +188 -0
- package/dist/desktop/desktop-voice.d.ts +152 -0
- package/dist/desktop/helper-lock.d.ts +83 -0
- package/dist/desktop/helper-process.d.ts +92 -0
- package/dist/desktop/index.d.ts +7 -0
- package/dist/desktop/index.js +1042 -0
- package/dist/index-9kerqn9r.js +150 -0
- package/dist/index-acm1yvvv.js +290 -0
- package/dist/index-r4hz8gk0.js +10 -0
- package/dist/index-rehs788p.js +42 -0
- package/dist/index-s270cw30.js +295 -0
- package/dist/index-tvz9s9nz.js +77 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +86 -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 +15 -0
- package/dist/web/index.js +1287 -0
- package/dist/web/stt/speech-recognition.d.ts +105 -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 +122 -0
- package/dist/web/turns.d.ts +101 -0
- package/package.json +68 -4
- package/src/cli/helpers-cli.ts +119 -0
- package/src/contract/contract.ts +365 -0
- package/src/contract/errors.ts +98 -0
- package/src/contract/index.ts +9 -0
- package/src/contract/session.ts +65 -0
- package/src/contract/wire.ts +263 -0
- package/src/desktop/desktop-voice.ts +933 -0
- package/src/desktop/helper-lock.ts +375 -0
- package/src/desktop/helper-process.ts +401 -0
- package/src/desktop/index.ts +16 -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 +15 -0
- package/src/web/stt/speech-recognition.ts +583 -0
- package/src/web/tts/phonon.ts +386 -0
- package/src/web/tts/player.ts +271 -0
- package/src/web/tts/system-voices.ts +401 -0
- package/src/web/turns.ts +224 -0
|
@@ -0,0 +1,1287 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_ENDPOINTING2
|
|
3
|
+
} from "../index-r4hz8gk0.js";
|
|
4
|
+
import {
|
|
5
|
+
VOICE_CONTRACT2,
|
|
6
|
+
AVAILABLE2,
|
|
7
|
+
unavailable2,
|
|
8
|
+
isAvailable2
|
|
9
|
+
} from "../index-9kerqn9r.js";
|
|
10
|
+
import {
|
|
11
|
+
VoiceError2
|
|
12
|
+
} from "../index-tvz9s9nz.js";
|
|
13
|
+
// src/web/stt/speech-recognition.ts
|
|
14
|
+
function recognitionConstructor(environment) {
|
|
15
|
+
return environment.SpeechRecognition ?? environment.webkitSpeechRecognition;
|
|
16
|
+
}
|
|
17
|
+
var WEB = ["web"];
|
|
18
|
+
var LOCAL_RECOGNITION_ID = "web.speech-recognition-local";
|
|
19
|
+
var SERVICE_RECOGNITION_ID = "web.speech-recognition-service";
|
|
20
|
+
function browserRecognitionLocal(environment = globalThis) {
|
|
21
|
+
return new BrowserRecognitionProvider("local", environment);
|
|
22
|
+
}
|
|
23
|
+
function browserRecognitionService(environment = globalThis) {
|
|
24
|
+
return new BrowserRecognitionProvider("service", environment);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
class BrowserRecognitionProvider {
|
|
28
|
+
descriptor;
|
|
29
|
+
environment;
|
|
30
|
+
mode;
|
|
31
|
+
constructor(mode, environment) {
|
|
32
|
+
this.mode = mode;
|
|
33
|
+
this.environment = environment;
|
|
34
|
+
this.descriptor = {
|
|
35
|
+
id: mode === "local" ? LOCAL_RECOGNITION_ID : SERVICE_RECOGNITION_ID,
|
|
36
|
+
displayName: mode === "local" ? "Browser dictation (on-device)" : "Browser dictation (browser service)",
|
|
37
|
+
kind: "speechToText",
|
|
38
|
+
platforms: WEB,
|
|
39
|
+
execution: mode === "local" ? "onDevice" : "network",
|
|
40
|
+
contract: VOICE_CONTRACT2,
|
|
41
|
+
requiresModelDownload: mode === "local",
|
|
42
|
+
modelFamilies: mode === "local" ? ["browser.on-device-recognition"] : [],
|
|
43
|
+
licenses: [
|
|
44
|
+
{ spdxIdentifier: mode === "local" ? "Browser-On-Device-Recognition" : "Browser-Speech-Service", commercialUse: true }
|
|
45
|
+
],
|
|
46
|
+
capabilities: {
|
|
47
|
+
streamingPartials: true,
|
|
48
|
+
trueCancellation: true,
|
|
49
|
+
modelInstallation: mode === "local",
|
|
50
|
+
localeSelection: true
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
async availability(locale) {
|
|
55
|
+
const constructor = recognitionConstructor(this.environment);
|
|
56
|
+
if (constructor === undefined) {
|
|
57
|
+
return unavailable2("unsupportedPlatform", "this browser has no Web Speech API", {
|
|
58
|
+
kind: "chooseAnotherProvider",
|
|
59
|
+
detail: "use a browser with speech recognition, or the native app"
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
if (this.mode === "service") {
|
|
63
|
+
return AVAILABLE2;
|
|
64
|
+
}
|
|
65
|
+
if (constructor.available === undefined) {
|
|
66
|
+
return unavailable2("unsupportedDevice", "this browser cannot run recognition on-device, so offline dictation is not offered here", { kind: "chooseAnotherProvider", detail: "use a browser with on-device recognition, or dictation with network consent" });
|
|
67
|
+
}
|
|
68
|
+
const state = await probeOnDevice(constructor, locale);
|
|
69
|
+
switch (state) {
|
|
70
|
+
case "available":
|
|
71
|
+
return AVAILABLE2;
|
|
72
|
+
case "downloadable":
|
|
73
|
+
case "downloading":
|
|
74
|
+
return unavailable2("modelNotInstalled", `the ${locale} recognition model is not installed on this device`, {
|
|
75
|
+
kind: "installModel",
|
|
76
|
+
detail: `install the ${locale} browser recognition model`
|
|
77
|
+
});
|
|
78
|
+
case "unavailable":
|
|
79
|
+
return unavailable2("unsupportedLocale", `${locale} has no on-device recognition model in this browser`, {
|
|
80
|
+
kind: "switchLocale",
|
|
81
|
+
detail: "choose a language this browser supports on-device"
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
async installModel(locale, options) {
|
|
86
|
+
if (options?.allowDownload !== true) {
|
|
87
|
+
throw new VoiceError2("denied", "installing a recognition model needs the person's explicit download consent");
|
|
88
|
+
}
|
|
89
|
+
const install = recognitionConstructor(this.environment)?.install;
|
|
90
|
+
if (install === undefined) {
|
|
91
|
+
throw new VoiceError2("assets_missing", "this browser has no on-device recognition install path");
|
|
92
|
+
}
|
|
93
|
+
return install({ langs: [locale] });
|
|
94
|
+
}
|
|
95
|
+
async createSession(options) {
|
|
96
|
+
const availability = await this.availability(options.locale);
|
|
97
|
+
if (!isAvailable2(availability)) {
|
|
98
|
+
const reason = availability.unavailable;
|
|
99
|
+
throw new VoiceError2(codeFor(reason.reason), reason.message);
|
|
100
|
+
}
|
|
101
|
+
if (this.mode === "service" && !options.allowNetwork) {
|
|
102
|
+
throw new VoiceError2("denied", "browser service recognition sends audio to the browser vendor; it needs explicit consent");
|
|
103
|
+
}
|
|
104
|
+
const constructor = recognitionConstructor(this.environment);
|
|
105
|
+
if (constructor === undefined)
|
|
106
|
+
throw new VoiceError2("unavailable");
|
|
107
|
+
const recognition = new constructor;
|
|
108
|
+
recognition.lang = options.locale;
|
|
109
|
+
recognition.continuous = true;
|
|
110
|
+
recognition.interimResults = true;
|
|
111
|
+
recognition.maxAlternatives = 1;
|
|
112
|
+
if (this.mode === "local")
|
|
113
|
+
recognition.processLocally = true;
|
|
114
|
+
return new WebRecognitionSession(recognition, this.mode === "local" ? "onDevice" : "network", {
|
|
115
|
+
endpointing: options.endpointing ?? DEFAULT_ENDPOINTING2,
|
|
116
|
+
now: this.environment.now ?? (() => performance.now()),
|
|
117
|
+
sleep: this.environment.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
async function probeOnDevice(constructor, locale) {
|
|
122
|
+
try {
|
|
123
|
+
return await constructor.available({ langs: [locale], processLocally: true }) ?? "unavailable";
|
|
124
|
+
} catch {
|
|
125
|
+
return "unavailable";
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function codeFor(reason) {
|
|
129
|
+
switch (reason) {
|
|
130
|
+
case "unsupportedLocale":
|
|
131
|
+
return "language_unsupported";
|
|
132
|
+
case "modelNotInstalled":
|
|
133
|
+
case "modelDownloadDisabled":
|
|
134
|
+
return "assets_missing";
|
|
135
|
+
case "permissionDenied":
|
|
136
|
+
return "denied";
|
|
137
|
+
case "unsupportedDevice":
|
|
138
|
+
case "unsupportedOperatingSystem":
|
|
139
|
+
case "unsupportedPlatform":
|
|
140
|
+
return "unavailable";
|
|
141
|
+
default:
|
|
142
|
+
return "unavailable";
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
class WebRecognitionSession {
|
|
147
|
+
execution;
|
|
148
|
+
recognition;
|
|
149
|
+
endpointing;
|
|
150
|
+
now;
|
|
151
|
+
sleep;
|
|
152
|
+
queue = [];
|
|
153
|
+
resolved;
|
|
154
|
+
finished = false;
|
|
155
|
+
terminal;
|
|
156
|
+
started = false;
|
|
157
|
+
iterated = false;
|
|
158
|
+
resolveTerminal = undefined;
|
|
159
|
+
terminalSignal = new Promise((resolve) => {
|
|
160
|
+
this.resolveTerminal = resolve;
|
|
161
|
+
});
|
|
162
|
+
finalizedText = "";
|
|
163
|
+
volatileText = "";
|
|
164
|
+
sequence = 0;
|
|
165
|
+
lastWordAt = 0;
|
|
166
|
+
words = false;
|
|
167
|
+
stopRequested = false;
|
|
168
|
+
endPromise;
|
|
169
|
+
constructor(recognition, execution, timing) {
|
|
170
|
+
this.recognition = recognition;
|
|
171
|
+
this.execution = execution;
|
|
172
|
+
this.endpointing = timing.endpointing;
|
|
173
|
+
this.now = timing.now;
|
|
174
|
+
this.sleep = timing.sleep;
|
|
175
|
+
recognition.onstart = () => {
|
|
176
|
+
this.started = true;
|
|
177
|
+
this.lastWordAt = this.now();
|
|
178
|
+
};
|
|
179
|
+
recognition.onresult = (event) => this.onResult(event);
|
|
180
|
+
recognition.onerror = (event) => this.onError(event);
|
|
181
|
+
recognition.onend = () => this.onEnd();
|
|
182
|
+
}
|
|
183
|
+
events() {
|
|
184
|
+
if (this.iterated) {
|
|
185
|
+
throw new VoiceError2("bad_request", "a transcription session's events() can be consumed only once");
|
|
186
|
+
}
|
|
187
|
+
this.iterated = true;
|
|
188
|
+
if (!this.started && !this.terminal) {
|
|
189
|
+
this.started = true;
|
|
190
|
+
this.lastWordAt = this.now();
|
|
191
|
+
this.startWatching();
|
|
192
|
+
try {
|
|
193
|
+
this.recognition.start();
|
|
194
|
+
} catch (error) {
|
|
195
|
+
this.fail(VoiceError2.wrapping(error));
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
let handedOut = false;
|
|
199
|
+
return {
|
|
200
|
+
[Symbol.asyncIterator]: () => {
|
|
201
|
+
if (handedOut)
|
|
202
|
+
throw new VoiceError2("bad_request", "a transcription session's events can be iterated only once");
|
|
203
|
+
handedOut = true;
|
|
204
|
+
return { next: () => this.next() };
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
async end() {
|
|
209
|
+
if (this.endPromise)
|
|
210
|
+
return this.endPromise;
|
|
211
|
+
this.stopRequested = true;
|
|
212
|
+
if (!this.started) {
|
|
213
|
+
this.started = true;
|
|
214
|
+
this.fail(new VoiceError2("no_speech"));
|
|
215
|
+
this.endPromise = Promise.resolve();
|
|
216
|
+
return this.endPromise;
|
|
217
|
+
}
|
|
218
|
+
this.endPromise = this.finishByRequest();
|
|
219
|
+
return this.endPromise;
|
|
220
|
+
}
|
|
221
|
+
async cancel() {
|
|
222
|
+
this.started = true;
|
|
223
|
+
if (this.terminal)
|
|
224
|
+
return;
|
|
225
|
+
this.emitTerminal({ type: "cancelled" });
|
|
226
|
+
}
|
|
227
|
+
async finishByRequest() {
|
|
228
|
+
try {
|
|
229
|
+
this.recognition.stop();
|
|
230
|
+
} catch (error) {
|
|
231
|
+
this.fail(VoiceError2.wrapping(error));
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
await Promise.race([
|
|
235
|
+
this.terminalSignal,
|
|
236
|
+
(async () => {
|
|
237
|
+
await this.sleep(this.endpointing.finalizationDeadlineSeconds * 1000);
|
|
238
|
+
if (!this.terminal)
|
|
239
|
+
this.finishWithCollected();
|
|
240
|
+
})()
|
|
241
|
+
]);
|
|
242
|
+
}
|
|
243
|
+
onResult(event) {
|
|
244
|
+
if (this.terminal)
|
|
245
|
+
return;
|
|
246
|
+
let changed = false;
|
|
247
|
+
const volatile = [];
|
|
248
|
+
for (let index = event.resultIndex;index < event.results.length; index += 1) {
|
|
249
|
+
const result = event.results[index];
|
|
250
|
+
if (!result)
|
|
251
|
+
continue;
|
|
252
|
+
const alternative = result[0];
|
|
253
|
+
const transcript = alternative?.transcript ?? "";
|
|
254
|
+
if (result.isFinal) {
|
|
255
|
+
const trimmed = transcript.trim();
|
|
256
|
+
if (trimmed.length > 0) {
|
|
257
|
+
this.finalizedText = joinText(this.finalizedText, trimmed);
|
|
258
|
+
changed = true;
|
|
259
|
+
this.words = true;
|
|
260
|
+
this.lastWordAt = this.now();
|
|
261
|
+
}
|
|
262
|
+
} else {
|
|
263
|
+
volatile.push(transcript);
|
|
264
|
+
if (transcript.trim().length > 0) {
|
|
265
|
+
this.words = true;
|
|
266
|
+
this.lastWordAt = this.now();
|
|
267
|
+
}
|
|
268
|
+
changed = true;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const volatileText = volatile.reduce(joinText, "");
|
|
272
|
+
if (volatileText !== this.volatileText)
|
|
273
|
+
changed = true;
|
|
274
|
+
this.volatileText = volatileText;
|
|
275
|
+
if (changed) {
|
|
276
|
+
this.queue.push({
|
|
277
|
+
type: "partial",
|
|
278
|
+
partial: { finalizedText: this.finalizedText, volatileText: this.volatileText, sequence: this.sequence++ }
|
|
279
|
+
});
|
|
280
|
+
this.drain();
|
|
281
|
+
}
|
|
282
|
+
if (this.stopRequested && this.volatileText.length === 0) {
|
|
283
|
+
this.finishWithCollected();
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
onError(event) {
|
|
287
|
+
if (this.terminal)
|
|
288
|
+
return;
|
|
289
|
+
const error = mapRecognitionError(event);
|
|
290
|
+
if (error.code === "cancelled") {
|
|
291
|
+
this.emitTerminal({ type: "cancelled" });
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
this.fail(error);
|
|
295
|
+
}
|
|
296
|
+
onEnd() {
|
|
297
|
+
if (this.terminal)
|
|
298
|
+
return;
|
|
299
|
+
this.finishWithCollected(true);
|
|
300
|
+
}
|
|
301
|
+
finishWithCollected(fromEnd = false) {
|
|
302
|
+
this.emitTerminal(this.words ? { type: "final", text: this.text } : { type: "failed", error: new VoiceError2("no_speech") }, fromEnd);
|
|
303
|
+
}
|
|
304
|
+
startWatching() {
|
|
305
|
+
this.watch();
|
|
306
|
+
}
|
|
307
|
+
async watch() {
|
|
308
|
+
if (this.watchTask)
|
|
309
|
+
return;
|
|
310
|
+
this.watchTask = (async () => {
|
|
311
|
+
const startedAt = this.now();
|
|
312
|
+
for (;; ) {
|
|
313
|
+
if (this.terminal)
|
|
314
|
+
return;
|
|
315
|
+
await this.sleep(this.endpointing.tickIntervalSeconds * 1000);
|
|
316
|
+
if (this.terminal)
|
|
317
|
+
return;
|
|
318
|
+
const now = this.now();
|
|
319
|
+
if (this.endpointing.maxDurationSeconds !== null && now - startedAt >= this.endpointing.maxDurationSeconds * 1000) {
|
|
320
|
+
await this.end();
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
if (!this.words && now - startedAt >= this.endpointing.noSpeechTimeoutSeconds * 1000) {
|
|
324
|
+
this.fail(new VoiceError2("no_speech"));
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
if (this.words && now - this.lastWordAt >= this.endpointing.silenceLimitSeconds * 1000) {
|
|
328
|
+
await this.end();
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
})();
|
|
333
|
+
}
|
|
334
|
+
watchTask;
|
|
335
|
+
get text() {
|
|
336
|
+
return joinText(this.finalizedText, this.volatileText);
|
|
337
|
+
}
|
|
338
|
+
fail(error) {
|
|
339
|
+
this.emitTerminal({ type: "failed", error });
|
|
340
|
+
}
|
|
341
|
+
emitTerminal(event, fromEnd = false) {
|
|
342
|
+
if (this.terminal)
|
|
343
|
+
return;
|
|
344
|
+
this.terminal = event.type === "final" ? "final" : event.type === "failed" ? "failed" : "cancelled";
|
|
345
|
+
this.release(fromEnd);
|
|
346
|
+
this.queue.push(event);
|
|
347
|
+
this.finished = true;
|
|
348
|
+
this.drain();
|
|
349
|
+
this.resolveTerminal?.();
|
|
350
|
+
}
|
|
351
|
+
release(fromEnd) {
|
|
352
|
+
const recognition = this.recognition;
|
|
353
|
+
recognition.onstart = null;
|
|
354
|
+
recognition.onresult = null;
|
|
355
|
+
recognition.onerror = null;
|
|
356
|
+
recognition.onend = null;
|
|
357
|
+
if (fromEnd)
|
|
358
|
+
return;
|
|
359
|
+
try {
|
|
360
|
+
recognition.abort();
|
|
361
|
+
} catch {}
|
|
362
|
+
}
|
|
363
|
+
drain() {
|
|
364
|
+
const resolve = this.resolved;
|
|
365
|
+
this.resolved = undefined;
|
|
366
|
+
resolve?.();
|
|
367
|
+
}
|
|
368
|
+
async next() {
|
|
369
|
+
for (;; ) {
|
|
370
|
+
const event = this.queue.shift();
|
|
371
|
+
if (event) {
|
|
372
|
+
if (this.finished && this.queue.length === 0)
|
|
373
|
+
this.resolved = undefined;
|
|
374
|
+
return { value: event, done: false };
|
|
375
|
+
}
|
|
376
|
+
if (this.finished)
|
|
377
|
+
return { value: undefined, done: true };
|
|
378
|
+
await new Promise((resolve) => {
|
|
379
|
+
this.resolved = resolve;
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
function mapRecognitionError(event) {
|
|
385
|
+
switch (event.error) {
|
|
386
|
+
case "not-allowed":
|
|
387
|
+
case "service-not-allowed":
|
|
388
|
+
return new VoiceError2("denied", event.message ?? "microphone or recognition permission was denied");
|
|
389
|
+
case "no-speech":
|
|
390
|
+
return new VoiceError2("no_speech");
|
|
391
|
+
case "language-not-supported":
|
|
392
|
+
return new VoiceError2("language_unsupported");
|
|
393
|
+
case "audio-capture":
|
|
394
|
+
return new VoiceError2("unavailable", "no microphone is available");
|
|
395
|
+
case "network":
|
|
396
|
+
return new VoiceError2("failed", "the browser's recognition service could not be reached");
|
|
397
|
+
case "aborted":
|
|
398
|
+
return new VoiceError2("cancelled");
|
|
399
|
+
default:
|
|
400
|
+
return new VoiceError2("failed", event.message ?? `recognition error: ${event.error}`);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
function joinText(left, right) {
|
|
404
|
+
const a = left.trim();
|
|
405
|
+
const b = right.trim();
|
|
406
|
+
if (a.length === 0)
|
|
407
|
+
return b;
|
|
408
|
+
if (b.length === 0)
|
|
409
|
+
return a;
|
|
410
|
+
return `${a} ${b}`;
|
|
411
|
+
}
|
|
412
|
+
// src/web/tts/player.ts
|
|
413
|
+
var defaultAudioContextFactory = {
|
|
414
|
+
create(options) {
|
|
415
|
+
const Constructor = globalThis.AudioContext;
|
|
416
|
+
if (Constructor === undefined) {
|
|
417
|
+
throw new Error("this environment has no AudioContext");
|
|
418
|
+
}
|
|
419
|
+
return new Constructor({ sampleRate: options.sampleRate });
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
|
|
423
|
+
class PlaybackUtterance {
|
|
424
|
+
player;
|
|
425
|
+
sources = new Set;
|
|
426
|
+
sealed = false;
|
|
427
|
+
stoppedFlag = false;
|
|
428
|
+
settled = false;
|
|
429
|
+
resolveDrained = () => {};
|
|
430
|
+
drained;
|
|
431
|
+
constructor(player) {
|
|
432
|
+
this.player = player;
|
|
433
|
+
this.drained = new Promise((resolve) => {
|
|
434
|
+
this.resolveDrained = resolve;
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
get stopped() {
|
|
438
|
+
return this.stoppedFlag;
|
|
439
|
+
}
|
|
440
|
+
enqueue(pcm) {
|
|
441
|
+
if (this.sealed || this.stoppedFlag)
|
|
442
|
+
return null;
|
|
443
|
+
return this.player.schedule(pcm, this);
|
|
444
|
+
}
|
|
445
|
+
finish() {
|
|
446
|
+
this.sealed = true;
|
|
447
|
+
this.check();
|
|
448
|
+
return this.drained;
|
|
449
|
+
}
|
|
450
|
+
stop() {
|
|
451
|
+
if (this.stoppedFlag)
|
|
452
|
+
return;
|
|
453
|
+
this.stoppedFlag = true;
|
|
454
|
+
this.sealed = true;
|
|
455
|
+
this.player.unschedule(this);
|
|
456
|
+
this.settle(false);
|
|
457
|
+
}
|
|
458
|
+
ended(source) {
|
|
459
|
+
this.sources.delete(source);
|
|
460
|
+
this.check();
|
|
461
|
+
}
|
|
462
|
+
check() {
|
|
463
|
+
if (this.sealed && this.sources.size === 0)
|
|
464
|
+
this.settle(!this.stoppedFlag);
|
|
465
|
+
}
|
|
466
|
+
settle(played) {
|
|
467
|
+
if (this.settled)
|
|
468
|
+
return;
|
|
469
|
+
this.settled = true;
|
|
470
|
+
this.resolveDrained(played);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
class StreamingPcmPlayer {
|
|
475
|
+
context;
|
|
476
|
+
sampleRate;
|
|
477
|
+
leadSeconds;
|
|
478
|
+
onFirstAudio;
|
|
479
|
+
onDrained;
|
|
480
|
+
sources = [];
|
|
481
|
+
endsAt = new Map;
|
|
482
|
+
owners = new Map;
|
|
483
|
+
utterances = new Set;
|
|
484
|
+
nextStartTime = 0;
|
|
485
|
+
firstAudioReported = false;
|
|
486
|
+
disposed = false;
|
|
487
|
+
constructor(options) {
|
|
488
|
+
this.sampleRate = options.sampleRate;
|
|
489
|
+
this.context = (options.factory ?? defaultAudioContextFactory).create({ sampleRate: options.sampleRate });
|
|
490
|
+
this.leadSeconds = options.leadSeconds ?? 0.05;
|
|
491
|
+
this.onFirstAudio = options.onFirstAudio;
|
|
492
|
+
this.onDrained = options.onDrained;
|
|
493
|
+
}
|
|
494
|
+
beginUtterance() {
|
|
495
|
+
const utterance = new PlaybackUtterance(this);
|
|
496
|
+
if (this.disposed) {
|
|
497
|
+
utterance.stop();
|
|
498
|
+
return utterance;
|
|
499
|
+
}
|
|
500
|
+
this.utterances.add(utterance);
|
|
501
|
+
utterance.drained.then(() => this.utterances.delete(utterance));
|
|
502
|
+
return utterance;
|
|
503
|
+
}
|
|
504
|
+
enqueue(pcm) {
|
|
505
|
+
return this.schedule(pcm, undefined);
|
|
506
|
+
}
|
|
507
|
+
schedule(pcm, owner) {
|
|
508
|
+
if (this.disposed || pcm.length === 0)
|
|
509
|
+
return null;
|
|
510
|
+
const buffer = this.context.createBuffer(1, pcm.length, this.sampleRate);
|
|
511
|
+
buffer.getChannelData?.(0).set(pcm);
|
|
512
|
+
const source = this.context.createBufferSource();
|
|
513
|
+
source.buffer = buffer;
|
|
514
|
+
source.connect(this.context.destination);
|
|
515
|
+
const startAt = Math.max(this.context.currentTime + this.leadSeconds, this.nextStartTime);
|
|
516
|
+
source.onended = () => {
|
|
517
|
+
this.forget(source);
|
|
518
|
+
source.disconnect?.();
|
|
519
|
+
owner?.ended(source);
|
|
520
|
+
if (this.sources.length === 0)
|
|
521
|
+
this.onDrained?.();
|
|
522
|
+
};
|
|
523
|
+
this.sources.push(source);
|
|
524
|
+
this.endsAt.set(source, startAt + buffer.duration);
|
|
525
|
+
if (owner) {
|
|
526
|
+
this.owners.set(source, owner);
|
|
527
|
+
owner.sources.add(source);
|
|
528
|
+
}
|
|
529
|
+
source.start(startAt);
|
|
530
|
+
this.nextStartTime = startAt + buffer.duration;
|
|
531
|
+
if (!this.firstAudioReported) {
|
|
532
|
+
this.firstAudioReported = true;
|
|
533
|
+
this.onFirstAudio?.(startAt);
|
|
534
|
+
}
|
|
535
|
+
return startAt;
|
|
536
|
+
}
|
|
537
|
+
stop() {
|
|
538
|
+
const scheduled = this.sources;
|
|
539
|
+
this.sources = [];
|
|
540
|
+
this.endsAt.clear();
|
|
541
|
+
this.owners.clear();
|
|
542
|
+
for (const source of scheduled)
|
|
543
|
+
this.halt(source);
|
|
544
|
+
for (const utterance of [...this.utterances]) {
|
|
545
|
+
utterance.sources.clear();
|
|
546
|
+
utterance.stop();
|
|
547
|
+
}
|
|
548
|
+
this.utterances.clear();
|
|
549
|
+
this.nextStartTime = 0;
|
|
550
|
+
this.firstAudioReported = false;
|
|
551
|
+
}
|
|
552
|
+
unschedule(utterance) {
|
|
553
|
+
for (const source of utterance.sources) {
|
|
554
|
+
this.forget(source);
|
|
555
|
+
this.halt(source);
|
|
556
|
+
}
|
|
557
|
+
utterance.sources.clear();
|
|
558
|
+
this.utterances.delete(utterance);
|
|
559
|
+
let latest = 0;
|
|
560
|
+
for (const end of this.endsAt.values())
|
|
561
|
+
latest = Math.max(latest, end);
|
|
562
|
+
this.nextStartTime = latest;
|
|
563
|
+
if (this.sources.length === 0)
|
|
564
|
+
this.firstAudioReported = false;
|
|
565
|
+
}
|
|
566
|
+
forget(source) {
|
|
567
|
+
this.sources = this.sources.filter((candidate) => candidate !== source);
|
|
568
|
+
this.endsAt.delete(source);
|
|
569
|
+
this.owners.delete(source);
|
|
570
|
+
}
|
|
571
|
+
halt(source) {
|
|
572
|
+
source.onended = null;
|
|
573
|
+
try {
|
|
574
|
+
source.stop();
|
|
575
|
+
} catch {}
|
|
576
|
+
source.disconnect?.();
|
|
577
|
+
}
|
|
578
|
+
get isPlaying() {
|
|
579
|
+
return this.sources.length > 0;
|
|
580
|
+
}
|
|
581
|
+
async suspend() {
|
|
582
|
+
await this.context.suspend?.();
|
|
583
|
+
}
|
|
584
|
+
async resume() {
|
|
585
|
+
await this.context.resume?.();
|
|
586
|
+
}
|
|
587
|
+
async dispose() {
|
|
588
|
+
if (this.disposed)
|
|
589
|
+
return;
|
|
590
|
+
this.stop();
|
|
591
|
+
this.disposed = true;
|
|
592
|
+
await this.context.close?.();
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// src/web/tts/phonon.ts
|
|
597
|
+
var defaultPhononRuntime = {
|
|
598
|
+
async load(request) {
|
|
599
|
+
const module = await import("phonon-tts");
|
|
600
|
+
const engine = await module.PhononTTS.load(request);
|
|
601
|
+
return engine;
|
|
602
|
+
}
|
|
603
|
+
};
|
|
604
|
+
async function clearPhononCache() {
|
|
605
|
+
const module = await import("phonon-tts");
|
|
606
|
+
return module.clearCache();
|
|
607
|
+
}
|
|
608
|
+
var PHONON_PROVIDER_ID = "web.phonon";
|
|
609
|
+
var PHONON_EN_FAMILY = "phonon-31m-en";
|
|
610
|
+
|
|
611
|
+
class PhononProvider {
|
|
612
|
+
descriptor;
|
|
613
|
+
options;
|
|
614
|
+
engine;
|
|
615
|
+
player;
|
|
616
|
+
loading;
|
|
617
|
+
loadWaiters = 0;
|
|
618
|
+
progressListeners = new Set;
|
|
619
|
+
constructor(options = {}) {
|
|
620
|
+
this.options = { locale: options.locale ?? "en", family: options.family ?? PHONON_EN_FAMILY, ...options };
|
|
621
|
+
this.descriptor = {
|
|
622
|
+
id: PHONON_PROVIDER_ID,
|
|
623
|
+
displayName: "Phonon 31M (on-device)",
|
|
624
|
+
kind: "textToSpeech",
|
|
625
|
+
platforms: ["web"],
|
|
626
|
+
execution: "onDevice",
|
|
627
|
+
contract: VOICE_CONTRACT2,
|
|
628
|
+
requiresModelDownload: true,
|
|
629
|
+
modelFamilies: [PHONON_EN_FAMILY],
|
|
630
|
+
licenses: [{ spdxIdentifier: "Apache-2.0", commercialUse: true }],
|
|
631
|
+
capabilities: {
|
|
632
|
+
trueCancellation: true,
|
|
633
|
+
voiceSelection: true,
|
|
634
|
+
utteranceQueueing: true,
|
|
635
|
+
localeSelection: false
|
|
636
|
+
}
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
get isLoaded() {
|
|
640
|
+
return this.engine !== undefined;
|
|
641
|
+
}
|
|
642
|
+
get voices() {
|
|
643
|
+
return this.engine?.voices ?? [];
|
|
644
|
+
}
|
|
645
|
+
async availability(locale) {
|
|
646
|
+
if (this.options.family !== PHONON_EN_FAMILY) {
|
|
647
|
+
return unavailable2("licenseNotAccepted", "Phonon 40M weights are CC BY-NC 4.0 and are not approved for commercial distribution", { kind: "switchLocale", detail: "use platform voices for non-English speech" });
|
|
648
|
+
}
|
|
649
|
+
const language = locale.toLowerCase().split(/[-_]/)[0] ?? "";
|
|
650
|
+
if (language !== "en") {
|
|
651
|
+
if (language === "es") {
|
|
652
|
+
return unavailable2("licenseNotAccepted", "Spanish needs the Phonon 40M weights, which are CC BY-NC 4.0 and not approved for commercial use", { kind: "chooseAnotherProvider", detail: "use the platform voice for ES-419" });
|
|
653
|
+
}
|
|
654
|
+
return unavailable2("unsupportedLocale", `${locale} is not supported by Phonon 31M`, {
|
|
655
|
+
kind: "chooseAnotherProvider",
|
|
656
|
+
detail: "use a platform voice for this language"
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
const supportsSimd = this.options.supportsSimd ?? defaultSupportsSimd;
|
|
660
|
+
if (!supportsSimd()) {
|
|
661
|
+
return unavailable2("unsupportedDevice", "this browser has no WebAssembly SIMD, so Phonon cannot run", {
|
|
662
|
+
kind: "chooseAnotherProvider",
|
|
663
|
+
detail: "use a platform voice in this browser"
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
if (this.isLoaded)
|
|
667
|
+
return AVAILABLE2;
|
|
668
|
+
return unavailable2("modelNotInstalled", "the Phonon 31M checkpoint is not installed in this browser", {
|
|
669
|
+
kind: "installModel",
|
|
670
|
+
detail: "download Phonon 31M (about 85 MB) for on-device speech"
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
async load(options = {}) {
|
|
674
|
+
const signal = options.signal;
|
|
675
|
+
if (signal?.aborted)
|
|
676
|
+
throw new VoiceError2("cancelled");
|
|
677
|
+
if (this.engine)
|
|
678
|
+
return this.engine;
|
|
679
|
+
const shared = this.loading ?? this.startLoading();
|
|
680
|
+
const listener = options.onProgress;
|
|
681
|
+
if (listener)
|
|
682
|
+
this.progressListeners.add(listener);
|
|
683
|
+
this.loadWaiters += 1;
|
|
684
|
+
let waiting = true;
|
|
685
|
+
const release = () => {
|
|
686
|
+
if (!waiting)
|
|
687
|
+
return;
|
|
688
|
+
waiting = false;
|
|
689
|
+
this.loadWaiters -= 1;
|
|
690
|
+
if (listener)
|
|
691
|
+
this.progressListeners.delete(listener);
|
|
692
|
+
};
|
|
693
|
+
let detach = () => {};
|
|
694
|
+
const aborted = new Promise((_, reject) => {
|
|
695
|
+
if (signal === undefined)
|
|
696
|
+
return;
|
|
697
|
+
const onAbort = () => {
|
|
698
|
+
release();
|
|
699
|
+
reject(new VoiceError2("cancelled"));
|
|
700
|
+
};
|
|
701
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
702
|
+
detach = () => signal.removeEventListener("abort", onAbort);
|
|
703
|
+
});
|
|
704
|
+
try {
|
|
705
|
+
return await Promise.race([shared, aborted]);
|
|
706
|
+
} finally {
|
|
707
|
+
release();
|
|
708
|
+
detach();
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
startLoading() {
|
|
712
|
+
if (this.options.model === undefined) {
|
|
713
|
+
return Promise.reject(new VoiceError2("assets_missing", "no Phonon model source is configured; the host must pin a revision or serve the assets"));
|
|
714
|
+
}
|
|
715
|
+
const runtime = this.options.runtime ?? defaultPhononRuntime;
|
|
716
|
+
const request = {
|
|
717
|
+
lang: "en",
|
|
718
|
+
model: this.options.model.kind === "pinned" ? undefined : this.options.model.spec,
|
|
719
|
+
quant: "q8",
|
|
720
|
+
cache: this.options.cache ?? true,
|
|
721
|
+
device: this.options.device ?? "cpu",
|
|
722
|
+
threads: this.options.threads ?? "auto",
|
|
723
|
+
onProgress: (progress) => {
|
|
724
|
+
for (const listener of [...this.progressListeners])
|
|
725
|
+
listener(progress);
|
|
726
|
+
}
|
|
727
|
+
};
|
|
728
|
+
const loading = (async () => {
|
|
729
|
+
try {
|
|
730
|
+
const engine = await runtime.load(request);
|
|
731
|
+
if (this.loadWaiters === 0) {
|
|
732
|
+
engine.dispose();
|
|
733
|
+
throw new VoiceError2("cancelled");
|
|
734
|
+
}
|
|
735
|
+
this.engine = engine;
|
|
736
|
+
return engine;
|
|
737
|
+
} catch (error) {
|
|
738
|
+
throw VoiceError2.wrapping(error);
|
|
739
|
+
} finally {
|
|
740
|
+
this.loading = undefined;
|
|
741
|
+
}
|
|
742
|
+
})();
|
|
743
|
+
this.loading = loading;
|
|
744
|
+
return loading;
|
|
745
|
+
}
|
|
746
|
+
speak(text, options = {}) {
|
|
747
|
+
const engine = this.engine;
|
|
748
|
+
if (engine === undefined) {
|
|
749
|
+
return {
|
|
750
|
+
done: Promise.reject(new VoiceError2("assets_missing", "call load() after the person consents to the download")),
|
|
751
|
+
cancel: () => {}
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
const controller = new AbortController;
|
|
755
|
+
const player = this.playerFor(engine.sampleRate);
|
|
756
|
+
const startedAt = (this.options.now ?? defaultNow)();
|
|
757
|
+
const stream = engine.stream(text, {
|
|
758
|
+
voice: options.voice,
|
|
759
|
+
temperature: options.temperature,
|
|
760
|
+
seed: options.seed,
|
|
761
|
+
signal: controller.signal
|
|
762
|
+
});
|
|
763
|
+
const clock = this.options.now ?? defaultNow;
|
|
764
|
+
const playback = player.beginUtterance();
|
|
765
|
+
const signal = controller.signal;
|
|
766
|
+
const done = (async () => {
|
|
767
|
+
let firstChunk = true;
|
|
768
|
+
try {
|
|
769
|
+
for await (const pcm of stream) {
|
|
770
|
+
if (signal.aborted)
|
|
771
|
+
break;
|
|
772
|
+
if (firstChunk) {
|
|
773
|
+
firstChunk = false;
|
|
774
|
+
options.onFirstAudio?.(clock() - startedAt);
|
|
775
|
+
}
|
|
776
|
+
playback.enqueue(pcm);
|
|
777
|
+
options.onChunk?.(pcm.length);
|
|
778
|
+
}
|
|
779
|
+
if (signal.aborted)
|
|
780
|
+
throw new VoiceError2("cancelled");
|
|
781
|
+
const stats = await stream.done;
|
|
782
|
+
await playback.finish();
|
|
783
|
+
if (signal.aborted || playback.stopped)
|
|
784
|
+
throw new VoiceError2("cancelled");
|
|
785
|
+
return stats;
|
|
786
|
+
} catch (error) {
|
|
787
|
+
playback.stop();
|
|
788
|
+
throw VoiceError2.wrapping(error);
|
|
789
|
+
}
|
|
790
|
+
})();
|
|
791
|
+
return {
|
|
792
|
+
done,
|
|
793
|
+
cancel: () => {
|
|
794
|
+
if (signal.aborted)
|
|
795
|
+
return;
|
|
796
|
+
controller.abort();
|
|
797
|
+
stream.cancel();
|
|
798
|
+
playback.stop();
|
|
799
|
+
}
|
|
800
|
+
};
|
|
801
|
+
}
|
|
802
|
+
dispose() {
|
|
803
|
+
this.engine?.dispose();
|
|
804
|
+
this.engine = undefined;
|
|
805
|
+
this.player?.dispose();
|
|
806
|
+
this.player = undefined;
|
|
807
|
+
}
|
|
808
|
+
playerFor(sampleRate) {
|
|
809
|
+
if (this.player === undefined) {
|
|
810
|
+
this.player = new StreamingPcmPlayer({
|
|
811
|
+
sampleRate,
|
|
812
|
+
factory: this.options.audioContextFactory
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
return this.player;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
var defaultNow = () => typeof performance === "undefined" ? Date.now() : performance.now();
|
|
819
|
+
function defaultSupportsSimd() {
|
|
820
|
+
const wasm = globalThis.WebAssembly;
|
|
821
|
+
if (wasm?.validate === undefined)
|
|
822
|
+
return false;
|
|
823
|
+
const probe = new Uint8Array([
|
|
824
|
+
0,
|
|
825
|
+
97,
|
|
826
|
+
115,
|
|
827
|
+
109,
|
|
828
|
+
1,
|
|
829
|
+
0,
|
|
830
|
+
0,
|
|
831
|
+
0,
|
|
832
|
+
1,
|
|
833
|
+
5,
|
|
834
|
+
1,
|
|
835
|
+
96,
|
|
836
|
+
0,
|
|
837
|
+
1,
|
|
838
|
+
123
|
|
839
|
+
]);
|
|
840
|
+
try {
|
|
841
|
+
return wasm.validate(probe);
|
|
842
|
+
} catch {
|
|
843
|
+
return false;
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
// src/web/tts/system-voices.ts
|
|
847
|
+
var SYSTEM_VOICES_ID = "web.system-voices";
|
|
848
|
+
var DEFAULT_VOICES_TIMEOUT_MS = 1500;
|
|
849
|
+
|
|
850
|
+
class SystemVoiceProvider {
|
|
851
|
+
descriptor;
|
|
852
|
+
environment;
|
|
853
|
+
inFlight = [];
|
|
854
|
+
voicesReady;
|
|
855
|
+
constructor(environment = globalThis) {
|
|
856
|
+
this.environment = environment;
|
|
857
|
+
this.descriptor = {
|
|
858
|
+
id: SYSTEM_VOICES_ID,
|
|
859
|
+
displayName: "Platform voices",
|
|
860
|
+
kind: "textToSpeech",
|
|
861
|
+
platforms: ["web"],
|
|
862
|
+
execution: "systemProvided",
|
|
863
|
+
contract: VOICE_CONTRACT2,
|
|
864
|
+
requiresModelDownload: false,
|
|
865
|
+
modelFamilies: ["browser.speechSynthesis"],
|
|
866
|
+
licenses: [{ spdxIdentifier: "Browser-System-Voices", commercialUse: true }],
|
|
867
|
+
capabilities: { trueCancellation: true, voiceSelection: true, wordBoundaryPause: true, localeSelection: true }
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
get Utterance() {
|
|
871
|
+
return this.environment.Utterance ?? this.environment.SpeechSynthesisUtterance;
|
|
872
|
+
}
|
|
873
|
+
voices(locale) {
|
|
874
|
+
const synthesis = this.environment.speechSynthesis;
|
|
875
|
+
if (synthesis === undefined)
|
|
876
|
+
return { local: [], remote: [] };
|
|
877
|
+
const wanted = language(locale);
|
|
878
|
+
const matches = synthesis.getVoices().filter((voice) => language(voice.lang) === wanted);
|
|
879
|
+
return {
|
|
880
|
+
local: matches.filter((voice) => voice.localService === true),
|
|
881
|
+
remote: matches.filter((voice) => voice.localService !== true)
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
waitForVoices() {
|
|
885
|
+
const synthesis = this.environment.speechSynthesis;
|
|
886
|
+
if (synthesis === undefined || synthesis.getVoices().length > 0)
|
|
887
|
+
return Promise.resolve();
|
|
888
|
+
if (this.voicesReady)
|
|
889
|
+
return this.voicesReady;
|
|
890
|
+
this.voicesReady = new Promise((resolve) => {
|
|
891
|
+
let timer;
|
|
892
|
+
const finish = () => {
|
|
893
|
+
synthesis.removeEventListener?.("voiceschanged", finish);
|
|
894
|
+
if (timer !== undefined)
|
|
895
|
+
this.clearTimer(timer);
|
|
896
|
+
resolve();
|
|
897
|
+
};
|
|
898
|
+
if (synthesis.addEventListener === undefined) {
|
|
899
|
+
resolve();
|
|
900
|
+
return;
|
|
901
|
+
}
|
|
902
|
+
synthesis.addEventListener("voiceschanged", finish);
|
|
903
|
+
timer = this.setTimer(finish, this.environment.voicesTimeoutMs ?? DEFAULT_VOICES_TIMEOUT_MS);
|
|
904
|
+
});
|
|
905
|
+
return this.voicesReady;
|
|
906
|
+
}
|
|
907
|
+
async availability(locale) {
|
|
908
|
+
if (this.environment.speechSynthesis === undefined || this.Utterance === undefined) {
|
|
909
|
+
return unavailable2("unsupportedPlatform", "this browser has no speech synthesis", {
|
|
910
|
+
kind: "chooseAnotherProvider",
|
|
911
|
+
detail: "use a browser with platform voices"
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
await this.waitForVoices();
|
|
915
|
+
const { local, remote } = this.voices(locale);
|
|
916
|
+
if (local.length > 0)
|
|
917
|
+
return AVAILABLE2;
|
|
918
|
+
if (remote.length > 0) {
|
|
919
|
+
return unavailable2("networkRequired", `only remote ${locale} voices are installed`, {
|
|
920
|
+
kind: "grantPermission",
|
|
921
|
+
detail: "use a network voice only with an explicit privacy choice"
|
|
922
|
+
});
|
|
923
|
+
}
|
|
924
|
+
return unavailable2("unsupportedLocale", `no ${locale} voice is installed`, {
|
|
925
|
+
kind: "installModel",
|
|
926
|
+
detail: `install a ${locale} voice in the operating system`
|
|
927
|
+
});
|
|
928
|
+
}
|
|
929
|
+
speak(text, options = {}) {
|
|
930
|
+
const synthesis = this.environment.speechSynthesis;
|
|
931
|
+
const Utterance = this.Utterance;
|
|
932
|
+
if (synthesis === undefined || Utterance === undefined) {
|
|
933
|
+
return { done: Promise.reject(new VoiceError2("unavailable")), cancel: () => {} };
|
|
934
|
+
}
|
|
935
|
+
if (text.trim().length === 0) {
|
|
936
|
+
return { done: Promise.reject(new VoiceError2("bad_request", "cannot speak empty text")), cancel: () => {} };
|
|
937
|
+
}
|
|
938
|
+
const selection = this.selectVoice(synthesis.getVoices(), options);
|
|
939
|
+
if (selection instanceof VoiceError2) {
|
|
940
|
+
return { done: Promise.reject(selection), cancel: () => {} };
|
|
941
|
+
}
|
|
942
|
+
const voice = selection;
|
|
943
|
+
const build = () => {
|
|
944
|
+
const utterance = new Utterance(text);
|
|
945
|
+
utterance.lang = voice?.lang ?? options.locale ?? "";
|
|
946
|
+
utterance.voice = voice ?? null;
|
|
947
|
+
utterance.rate = options.rate ?? 1;
|
|
948
|
+
utterance.pitch = options.pitch ?? 1;
|
|
949
|
+
utterance.volume = options.volume ?? 1;
|
|
950
|
+
return utterance;
|
|
951
|
+
};
|
|
952
|
+
let request;
|
|
953
|
+
const done = new Promise((resolve, reject) => {
|
|
954
|
+
request = { build, options, utterance: build(), started: false, settled: false, zombie: false, watchdog: undefined, resolve, reject };
|
|
955
|
+
});
|
|
956
|
+
this.inFlight.push(request);
|
|
957
|
+
this.bind(request);
|
|
958
|
+
const timeout = options.timeoutMs ?? 15000 + text.length * 200 / Math.max(0.1, options.rate ?? 1);
|
|
959
|
+
request.watchdog = this.setTimer(() => {
|
|
960
|
+
this.abandon(request, new VoiceError2("failed", "the platform voice never reported the end of the speech"));
|
|
961
|
+
}, timeout);
|
|
962
|
+
try {
|
|
963
|
+
synthesis.speak(request.utterance);
|
|
964
|
+
} catch (error) {
|
|
965
|
+
this.settle(request, VoiceError2.wrapping(error));
|
|
966
|
+
}
|
|
967
|
+
return { done, cancel: () => this.abandon(request, new VoiceError2("cancelled")) };
|
|
968
|
+
}
|
|
969
|
+
get isSpeaking() {
|
|
970
|
+
return this.environment.speechSynthesis?.speaking === true || this.environment.speechSynthesis?.pending === true;
|
|
971
|
+
}
|
|
972
|
+
selectVoice(available, options) {
|
|
973
|
+
const allowNetwork = options.allowNetwork === true;
|
|
974
|
+
if (options.voiceName) {
|
|
975
|
+
const requested = available.find((voice) => voice.name === options.voiceName);
|
|
976
|
+
if (requested !== undefined) {
|
|
977
|
+
if (requested.localService !== true && !allowNetwork) {
|
|
978
|
+
return new VoiceError2("denied", "a remote voice needs explicit consent");
|
|
979
|
+
}
|
|
980
|
+
return requested;
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
if (options.locale) {
|
|
984
|
+
const wanted = language(options.locale);
|
|
985
|
+
const tag = normalizeTag(options.locale);
|
|
986
|
+
const sameLanguage = available.filter((voice) => language(voice.lang) === wanted);
|
|
987
|
+
const pick = (pool) => pool.find((voice) => normalizeTag(voice.lang) === tag && voice.default === true) ?? pool.find((voice) => normalizeTag(voice.lang) === tag) ?? pool.find((voice) => voice.default === true) ?? pool[0];
|
|
988
|
+
const local = pick(sameLanguage.filter((voice) => voice.localService === true));
|
|
989
|
+
if (local)
|
|
990
|
+
return local;
|
|
991
|
+
if (allowNetwork)
|
|
992
|
+
return pick(sameLanguage);
|
|
993
|
+
return new VoiceError2("language_unsupported", `no local ${options.locale} voice is installed`);
|
|
994
|
+
}
|
|
995
|
+
const fallback = available.find((voice) => voice.localService === true && voice.default === true) ?? available.find((voice) => voice.localService === true);
|
|
996
|
+
if (fallback === undefined && !allowNetwork) {
|
|
997
|
+
return new VoiceError2("language_unsupported", "no local voice is installed");
|
|
998
|
+
}
|
|
999
|
+
return fallback;
|
|
1000
|
+
}
|
|
1001
|
+
bind(request) {
|
|
1002
|
+
const utterance = request.utterance;
|
|
1003
|
+
const options = request.options;
|
|
1004
|
+
utterance.onstart = () => {
|
|
1005
|
+
if (request.utterance !== utterance)
|
|
1006
|
+
return;
|
|
1007
|
+
if (request.zombie) {
|
|
1008
|
+
this.purge();
|
|
1009
|
+
return;
|
|
1010
|
+
}
|
|
1011
|
+
request.started = true;
|
|
1012
|
+
options.onStart?.();
|
|
1013
|
+
};
|
|
1014
|
+
utterance.onend = () => {
|
|
1015
|
+
if (request.utterance !== utterance || request.settled)
|
|
1016
|
+
return;
|
|
1017
|
+
options.onEnd?.();
|
|
1018
|
+
this.settle(request);
|
|
1019
|
+
};
|
|
1020
|
+
utterance.onerror = (event) => {
|
|
1021
|
+
if (request.utterance !== utterance || request.settled)
|
|
1022
|
+
return;
|
|
1023
|
+
this.settle(request, mapSynthesisError(event.error));
|
|
1024
|
+
};
|
|
1025
|
+
}
|
|
1026
|
+
abandon(request, error) {
|
|
1027
|
+
if (request.settled)
|
|
1028
|
+
return;
|
|
1029
|
+
const speakerIsOther = this.inFlight.some((other) => other !== request && other.started);
|
|
1030
|
+
this.settle(request, error);
|
|
1031
|
+
if (!request.started && speakerIsOther) {
|
|
1032
|
+
request.zombie = true;
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1035
|
+
this.purge();
|
|
1036
|
+
}
|
|
1037
|
+
purge() {
|
|
1038
|
+
const synthesis = this.environment.speechSynthesis;
|
|
1039
|
+
if (synthesis === undefined)
|
|
1040
|
+
return;
|
|
1041
|
+
const survivors = this.inFlight.filter((request) => !request.settled && !request.started);
|
|
1042
|
+
for (const request of this.inFlight)
|
|
1043
|
+
detach(request.utterance);
|
|
1044
|
+
synthesis.cancel();
|
|
1045
|
+
for (const request of survivors) {
|
|
1046
|
+
request.utterance = request.build();
|
|
1047
|
+
this.bind(request);
|
|
1048
|
+
try {
|
|
1049
|
+
synthesis.speak(request.utterance);
|
|
1050
|
+
} catch (error) {
|
|
1051
|
+
this.settle(request, VoiceError2.wrapping(error));
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
settle(request, error) {
|
|
1056
|
+
if (request.settled)
|
|
1057
|
+
return;
|
|
1058
|
+
request.settled = true;
|
|
1059
|
+
if (request.watchdog !== undefined)
|
|
1060
|
+
this.clearTimer(request.watchdog);
|
|
1061
|
+
request.watchdog = undefined;
|
|
1062
|
+
this.inFlight = this.inFlight.filter((candidate) => candidate !== request);
|
|
1063
|
+
if (error)
|
|
1064
|
+
request.reject(error);
|
|
1065
|
+
else
|
|
1066
|
+
request.resolve();
|
|
1067
|
+
}
|
|
1068
|
+
setTimer(callback, milliseconds) {
|
|
1069
|
+
if (this.environment.setTimeout)
|
|
1070
|
+
return this.environment.setTimeout(callback, milliseconds);
|
|
1071
|
+
const handle = setTimeout(callback, milliseconds);
|
|
1072
|
+
handle.unref?.();
|
|
1073
|
+
return handle;
|
|
1074
|
+
}
|
|
1075
|
+
clearTimer(handle) {
|
|
1076
|
+
if (this.environment.clearTimeout)
|
|
1077
|
+
this.environment.clearTimeout(handle);
|
|
1078
|
+
else
|
|
1079
|
+
clearTimeout(handle);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
function detach(utterance) {
|
|
1083
|
+
utterance.onstart = null;
|
|
1084
|
+
utterance.onend = null;
|
|
1085
|
+
utterance.onerror = null;
|
|
1086
|
+
}
|
|
1087
|
+
function normalizeTag(tag) {
|
|
1088
|
+
return tag.replace(/_/g, "-").toLowerCase();
|
|
1089
|
+
}
|
|
1090
|
+
function language(locale) {
|
|
1091
|
+
return locale.toLowerCase().split(/[-_]/)[0] ?? locale.toLowerCase();
|
|
1092
|
+
}
|
|
1093
|
+
function mapSynthesisError(error) {
|
|
1094
|
+
switch (error) {
|
|
1095
|
+
case "interrupted":
|
|
1096
|
+
case "canceled":
|
|
1097
|
+
case "cancelled":
|
|
1098
|
+
return new VoiceError2("cancelled");
|
|
1099
|
+
case "not-allowed":
|
|
1100
|
+
return new VoiceError2("denied");
|
|
1101
|
+
case "language-unavailable":
|
|
1102
|
+
case "voice-unavailable":
|
|
1103
|
+
return new VoiceError2("language_unsupported");
|
|
1104
|
+
default:
|
|
1105
|
+
return new VoiceError2("failed", `platform synthesis error: ${error}`);
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
// src/web/turns.ts
|
|
1109
|
+
class VoiceTurnManager {
|
|
1110
|
+
options;
|
|
1111
|
+
listeners = new Set;
|
|
1112
|
+
session;
|
|
1113
|
+
speech;
|
|
1114
|
+
generation = 0;
|
|
1115
|
+
finished = false;
|
|
1116
|
+
constructor(options) {
|
|
1117
|
+
this.options = options;
|
|
1118
|
+
}
|
|
1119
|
+
onEvent(listener) {
|
|
1120
|
+
this.listeners.add(listener);
|
|
1121
|
+
return () => this.listeners.delete(listener);
|
|
1122
|
+
}
|
|
1123
|
+
async startListening() {
|
|
1124
|
+
if (this.finished)
|
|
1125
|
+
throw new VoiceError2("cancelled", "the turn manager was cancelled");
|
|
1126
|
+
const generation = ++this.generation;
|
|
1127
|
+
const previous = this.session;
|
|
1128
|
+
this.session = undefined;
|
|
1129
|
+
if (this.speech)
|
|
1130
|
+
this.stopSpeech("barge-in");
|
|
1131
|
+
if (previous)
|
|
1132
|
+
await previous.cancel();
|
|
1133
|
+
if (this.finished)
|
|
1134
|
+
throw new VoiceError2("cancelled", "the turn manager was cancelled");
|
|
1135
|
+
if (generation !== this.generation)
|
|
1136
|
+
return;
|
|
1137
|
+
let session;
|
|
1138
|
+
try {
|
|
1139
|
+
session = await this.options.transcription.createSession({
|
|
1140
|
+
locale: this.options.locale,
|
|
1141
|
+
allowNetwork: this.options.allowNetwork === true
|
|
1142
|
+
});
|
|
1143
|
+
} catch (error) {
|
|
1144
|
+
if (this.finished)
|
|
1145
|
+
throw new VoiceError2("cancelled", "the turn manager was cancelled");
|
|
1146
|
+
if (generation !== this.generation)
|
|
1147
|
+
return;
|
|
1148
|
+
this.emit({ type: "failed", error: VoiceError2.wrapping(error) });
|
|
1149
|
+
throw error;
|
|
1150
|
+
}
|
|
1151
|
+
if (this.finished || generation !== this.generation) {
|
|
1152
|
+
await session.cancel();
|
|
1153
|
+
if (this.finished)
|
|
1154
|
+
throw new VoiceError2("cancelled", "the turn manager was cancelled");
|
|
1155
|
+
return;
|
|
1156
|
+
}
|
|
1157
|
+
this.session = session;
|
|
1158
|
+
this.emit({ type: "listening" });
|
|
1159
|
+
this.consume(session);
|
|
1160
|
+
}
|
|
1161
|
+
async stopListening() {
|
|
1162
|
+
await this.session?.end();
|
|
1163
|
+
}
|
|
1164
|
+
speak(text) {
|
|
1165
|
+
if (this.finished) {
|
|
1166
|
+
return { done: Promise.reject(new VoiceError2("cancelled")), cancel: () => {} };
|
|
1167
|
+
}
|
|
1168
|
+
if (this.speech)
|
|
1169
|
+
this.stopSpeech("replaced");
|
|
1170
|
+
const handle = this.options.synthesis.speak(text);
|
|
1171
|
+
this.speech = handle;
|
|
1172
|
+
this.emit({ type: "speaking", text });
|
|
1173
|
+
handle.done.then(() => {
|
|
1174
|
+
if (this.speech !== handle)
|
|
1175
|
+
return;
|
|
1176
|
+
this.speech = undefined;
|
|
1177
|
+
this.emit({ type: "speech-finished" });
|
|
1178
|
+
}).catch((error) => {
|
|
1179
|
+
if (this.speech !== handle)
|
|
1180
|
+
return;
|
|
1181
|
+
this.speech = undefined;
|
|
1182
|
+
const wrapped = VoiceError2.wrapping(error);
|
|
1183
|
+
this.emit(wrapped.code === "cancelled" ? { type: "speech-cancelled" } : { type: "failed", error: wrapped });
|
|
1184
|
+
});
|
|
1185
|
+
return {
|
|
1186
|
+
done: handle.done,
|
|
1187
|
+
cancel: () => {
|
|
1188
|
+
if (this.speech === handle)
|
|
1189
|
+
this.stopSpeech("replaced");
|
|
1190
|
+
else
|
|
1191
|
+
handle.cancel();
|
|
1192
|
+
}
|
|
1193
|
+
};
|
|
1194
|
+
}
|
|
1195
|
+
notifySpeechDetected() {
|
|
1196
|
+
if (this.options.bargeInOnSpeech === false)
|
|
1197
|
+
return;
|
|
1198
|
+
this.stopSpeech("barge-in");
|
|
1199
|
+
}
|
|
1200
|
+
async cancel() {
|
|
1201
|
+
if (this.finished)
|
|
1202
|
+
return;
|
|
1203
|
+
this.finished = true;
|
|
1204
|
+
this.generation += 1;
|
|
1205
|
+
this.stopSpeech("cancel");
|
|
1206
|
+
const session = this.session;
|
|
1207
|
+
this.session = undefined;
|
|
1208
|
+
await session?.cancel();
|
|
1209
|
+
this.emit({ type: "cancelled" });
|
|
1210
|
+
}
|
|
1211
|
+
stopSpeech(reason) {
|
|
1212
|
+
const speech = this.speech;
|
|
1213
|
+
if (speech === undefined)
|
|
1214
|
+
return;
|
|
1215
|
+
this.speech = undefined;
|
|
1216
|
+
speech.cancel();
|
|
1217
|
+
if (reason === "barge-in")
|
|
1218
|
+
this.emit({ type: "barge-in" });
|
|
1219
|
+
if (reason !== "cancel")
|
|
1220
|
+
this.emit({ type: "speech-cancelled" });
|
|
1221
|
+
}
|
|
1222
|
+
async consume(session) {
|
|
1223
|
+
try {
|
|
1224
|
+
for await (const event of session.events()) {
|
|
1225
|
+
if (this.session !== session)
|
|
1226
|
+
return;
|
|
1227
|
+
this.forward(event);
|
|
1228
|
+
}
|
|
1229
|
+
} catch (error) {
|
|
1230
|
+
if (this.session !== session)
|
|
1231
|
+
return;
|
|
1232
|
+
this.session = undefined;
|
|
1233
|
+
this.emit({ type: "failed", error: VoiceError2.wrapping(error) });
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
forward(event) {
|
|
1237
|
+
switch (event.type) {
|
|
1238
|
+
case "partial":
|
|
1239
|
+
this.emit({ type: "partial", partial: event.partial });
|
|
1240
|
+
return;
|
|
1241
|
+
case "final":
|
|
1242
|
+
this.session = undefined;
|
|
1243
|
+
this.emit({ type: "transcript", text: event.text });
|
|
1244
|
+
return;
|
|
1245
|
+
case "failed":
|
|
1246
|
+
this.session = undefined;
|
|
1247
|
+
this.emit({ type: "failed", error: event.error });
|
|
1248
|
+
return;
|
|
1249
|
+
case "cancelled":
|
|
1250
|
+
this.session = undefined;
|
|
1251
|
+
this.emit({ type: "cancelled" });
|
|
1252
|
+
return;
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
emit(event) {
|
|
1256
|
+
for (const listener of [...this.listeners]) {
|
|
1257
|
+
try {
|
|
1258
|
+
listener(event);
|
|
1259
|
+
} catch (error) {
|
|
1260
|
+
(this.options.onListenerError ?? defaultListenerError)(error);
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
function defaultListenerError(error) {
|
|
1266
|
+
console.error("voice turn listener threw", error);
|
|
1267
|
+
}
|
|
1268
|
+
export {
|
|
1269
|
+
BrowserRecognitionProvider,
|
|
1270
|
+
DEFAULT_ENDPOINTING2 as DEFAULT_ENDPOINTING,
|
|
1271
|
+
LOCAL_RECOGNITION_ID,
|
|
1272
|
+
PHONON_EN_FAMILY,
|
|
1273
|
+
PHONON_PROVIDER_ID,
|
|
1274
|
+
PhononProvider,
|
|
1275
|
+
PlaybackUtterance,
|
|
1276
|
+
SERVICE_RECOGNITION_ID,
|
|
1277
|
+
SYSTEM_VOICES_ID,
|
|
1278
|
+
StreamingPcmPlayer,
|
|
1279
|
+
SystemVoiceProvider,
|
|
1280
|
+
VoiceTurnManager,
|
|
1281
|
+
browserRecognitionLocal,
|
|
1282
|
+
browserRecognitionService,
|
|
1283
|
+
clearPhononCache,
|
|
1284
|
+
defaultAudioContextFactory,
|
|
1285
|
+
defaultPhononRuntime,
|
|
1286
|
+
recognitionConstructor
|
|
1287
|
+
};
|