@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.
Files changed (52) hide show
  1. package/README.md +51 -2
  2. package/dist/cli/helpers-cli.d.ts +2 -0
  3. package/dist/cli/helpers-cli.js +102 -0
  4. package/dist/contract/contract.d.ts +138 -0
  5. package/dist/contract/errors.d.ts +26 -0
  6. package/dist/contract/index.d.ts +9 -0
  7. package/dist/contract/index.js +54 -0
  8. package/dist/contract/session.d.ts +58 -0
  9. package/dist/contract/wire.d.ts +188 -0
  10. package/dist/desktop/desktop-voice.d.ts +152 -0
  11. package/dist/desktop/helper-lock.d.ts +83 -0
  12. package/dist/desktop/helper-process.d.ts +92 -0
  13. package/dist/desktop/index.d.ts +7 -0
  14. package/dist/desktop/index.js +1042 -0
  15. package/dist/index-9kerqn9r.js +150 -0
  16. package/dist/index-acm1yvvv.js +290 -0
  17. package/dist/index-r4hz8gk0.js +10 -0
  18. package/dist/index-rehs788p.js +42 -0
  19. package/dist/index-s270cw30.js +295 -0
  20. package/dist/index-tvz9s9nz.js +77 -0
  21. package/dist/index.d.ts +7 -0
  22. package/dist/index.js +86 -0
  23. package/dist/settings/index.d.ts +5 -0
  24. package/dist/settings/index.js +34 -0
  25. package/dist/settings/settings.d.ts +163 -0
  26. package/dist/web/index.d.ts +15 -0
  27. package/dist/web/index.js +1287 -0
  28. package/dist/web/stt/speech-recognition.d.ts +105 -0
  29. package/dist/web/tts/phonon.d.ts +139 -0
  30. package/dist/web/tts/player.d.ts +115 -0
  31. package/dist/web/tts/system-voices.d.ts +122 -0
  32. package/dist/web/turns.d.ts +101 -0
  33. package/package.json +68 -4
  34. package/src/cli/helpers-cli.ts +119 -0
  35. package/src/contract/contract.ts +365 -0
  36. package/src/contract/errors.ts +98 -0
  37. package/src/contract/index.ts +9 -0
  38. package/src/contract/session.ts +65 -0
  39. package/src/contract/wire.ts +263 -0
  40. package/src/desktop/desktop-voice.ts +933 -0
  41. package/src/desktop/helper-lock.ts +375 -0
  42. package/src/desktop/helper-process.ts +401 -0
  43. package/src/desktop/index.ts +16 -0
  44. package/src/index.ts +7 -0
  45. package/src/settings/index.ts +5 -0
  46. package/src/settings/settings.ts +478 -0
  47. package/src/web/index.ts +15 -0
  48. package/src/web/stt/speech-recognition.ts +583 -0
  49. package/src/web/tts/phonon.ts +386 -0
  50. package/src/web/tts/player.ts +271 -0
  51. package/src/web/tts/system-voices.ts +401 -0
  52. package/src/web/turns.ts +224 -0
@@ -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
+ }
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Scheduled PCM playback for streaming synthesis.
3
+ *
4
+ * The engine yields mono float chunks in real time; this player schedules each one on the
5
+ * AudioContext clock with a small lead so chunk boundaries do not click, and it owns the only
6
+ * mutable playback state: stop (barge-in) flushes every scheduled source, suspend/resume follow
7
+ * the platform's audio focus rules, and dispose closes the context so nothing outlives the
8
+ * component.
9
+ *
10
+ * Browser globals are injected (`AudioContextFactory`), so the scheduling logic is testable.
11
+ */
12
+
13
+ export interface AudioBufferLike {
14
+ readonly duration: number;
15
+ readonly numberOfChannels?: number;
16
+ readonly length?: number;
17
+ getChannelData?(channel: number): Float32Array;
18
+ }
19
+
20
+ export interface AudioBufferSourceLike {
21
+ buffer: unknown;
22
+ onended: (() => void) | null;
23
+ connect(destination: unknown): void;
24
+ disconnect?(destination?: unknown): void;
25
+ start(when?: number): void;
26
+ stop(when?: number): void;
27
+ }
28
+
29
+ export interface AudioContextLike {
30
+ readonly currentTime: number;
31
+ readonly destination: unknown;
32
+ readonly state?: string;
33
+ createBuffer(channels: number, length: number, sampleRate: number): AudioBufferLike;
34
+ createBufferSource(): AudioBufferSourceLike;
35
+ resume?(): Promise<void>;
36
+ suspend?(): Promise<void>;
37
+ close?(): Promise<void>;
38
+ }
39
+
40
+ export interface AudioContextFactory {
41
+ create(options: { sampleRate: number }): AudioContextLike;
42
+ }
43
+
44
+ export interface StreamingPcmPlayerOptions {
45
+ readonly sampleRate: number;
46
+ readonly factory?: AudioContextFactory;
47
+ /** Scheduling lead ahead of the context clock, in seconds. Default 0.05. */
48
+ readonly leadSeconds?: number;
49
+ /** Called when the first chunk of the current utterance is scheduled. */
50
+ readonly onFirstAudio?: (atContextTime: number) => void;
51
+ /** Called when every scheduled chunk has played. */
52
+ readonly onDrained?: () => void;
53
+ }
54
+
55
+ export const defaultAudioContextFactory: AudioContextFactory = {
56
+ create(options) {
57
+ const Constructor = (globalThis as { AudioContext?: new (options?: { sampleRate?: number }) => AudioContextLike })
58
+ .AudioContext;
59
+ if (Constructor === undefined) {
60
+ throw new Error("this environment has no AudioContext");
61
+ }
62
+ return new Constructor({ sampleRate: options.sampleRate });
63
+ },
64
+ };
65
+
66
+ /**
67
+ * One utterance's slice of the player's schedule: its own sources, its own stop, and a `drained`
68
+ * promise that settles when its last scheduled chunk has played (or it was stopped). Stopping one
69
+ * utterance leaves the others scheduled.
70
+ */
71
+ export class PlaybackUtterance {
72
+ private readonly player: StreamingPcmPlayer;
73
+ readonly sources = new Set<AudioBufferSourceLike>();
74
+ private sealed = false;
75
+ private stoppedFlag = false;
76
+ private settled = false;
77
+ private resolveDrained: (played: boolean) => void = () => {};
78
+ /** Resolves `true` when everything scheduled played, `false` when the utterance was stopped. */
79
+ readonly drained: Promise<boolean>;
80
+
81
+ constructor(player: StreamingPcmPlayer) {
82
+ this.player = player;
83
+ this.drained = new Promise<boolean>((resolve) => {
84
+ this.resolveDrained = resolve;
85
+ });
86
+ }
87
+
88
+ /** Whether `stop()` (or the player's stop/dispose) ended this utterance. */
89
+ get stopped(): boolean {
90
+ return this.stoppedFlag;
91
+ }
92
+
93
+ /** Schedules one chunk of this utterance; null after `finish()`/`stop()` or when disposed. */
94
+ enqueue(pcm: Float32Array): number | null {
95
+ if (this.sealed || this.stoppedFlag) return null;
96
+ return this.player.schedule(pcm, this);
97
+ }
98
+
99
+ /** No more chunks will come: `drained` resolves once the scheduled ones have played. */
100
+ finish(): Promise<boolean> {
101
+ this.sealed = true;
102
+ this.check();
103
+ return this.drained;
104
+ }
105
+
106
+ /** Stops and discards only this utterance's scheduled audio. Idempotent. */
107
+ stop(): void {
108
+ if (this.stoppedFlag) return;
109
+ this.stoppedFlag = true;
110
+ this.sealed = true;
111
+ this.player.unschedule(this);
112
+ this.settle(false);
113
+ }
114
+
115
+ /** @internal called by the player when one of this utterance's sources ended. */
116
+ ended(source: AudioBufferSourceLike): void {
117
+ this.sources.delete(source);
118
+ this.check();
119
+ }
120
+
121
+ private check(): void {
122
+ if (this.sealed && this.sources.size === 0) this.settle(!this.stoppedFlag);
123
+ }
124
+
125
+ private settle(played: boolean): void {
126
+ if (this.settled) return;
127
+ this.settled = true;
128
+ this.resolveDrained(played);
129
+ }
130
+ }
131
+
132
+ export class StreamingPcmPlayer {
133
+ private readonly context: AudioContextLike;
134
+ private readonly sampleRate: number;
135
+ private readonly leadSeconds: number;
136
+ private readonly onFirstAudio: ((atContextTime: number) => void) | undefined;
137
+ private readonly onDrained: (() => void) | undefined;
138
+
139
+ private sources: AudioBufferSourceLike[] = [];
140
+ private readonly endsAt = new Map<AudioBufferSourceLike, number>();
141
+ private readonly owners = new Map<AudioBufferSourceLike, PlaybackUtterance>();
142
+ private readonly utterances = new Set<PlaybackUtterance>();
143
+ private nextStartTime = 0;
144
+ private firstAudioReported = false;
145
+ private disposed = false;
146
+
147
+ constructor(options: StreamingPcmPlayerOptions) {
148
+ this.sampleRate = options.sampleRate;
149
+ this.context = (options.factory ?? defaultAudioContextFactory).create({ sampleRate: options.sampleRate });
150
+ this.leadSeconds = options.leadSeconds ?? 0.05;
151
+ this.onFirstAudio = options.onFirstAudio;
152
+ this.onDrained = options.onDrained;
153
+ }
154
+
155
+ /**
156
+ * Starts an utterance: a group of chunks with its own stop and drain. Utterances queue behind
157
+ * each other on the same schedule, so they never overlap.
158
+ */
159
+ beginUtterance(): PlaybackUtterance {
160
+ const utterance = new PlaybackUtterance(this);
161
+ if (this.disposed) {
162
+ utterance.stop();
163
+ return utterance;
164
+ }
165
+ this.utterances.add(utterance);
166
+ void utterance.drained.then(() => this.utterances.delete(utterance));
167
+ return utterance;
168
+ }
169
+
170
+ /** Schedules one chunk and returns the context time it starts at, or null when disposed. */
171
+ enqueue(pcm: Float32Array): number | null {
172
+ return this.schedule(pcm, undefined);
173
+ }
174
+
175
+ /** @internal Schedules one chunk for `owner` (or for no utterance). */
176
+ schedule(pcm: Float32Array, owner: PlaybackUtterance | undefined): number | null {
177
+ if (this.disposed || pcm.length === 0) return null;
178
+ const buffer = this.context.createBuffer(1, pcm.length, this.sampleRate);
179
+ buffer.getChannelData?.(0).set(pcm);
180
+ const source = this.context.createBufferSource();
181
+ source.buffer = buffer;
182
+ source.connect(this.context.destination);
183
+ const startAt = Math.max(this.context.currentTime + this.leadSeconds, this.nextStartTime);
184
+ source.onended = () => {
185
+ this.forget(source);
186
+ source.disconnect?.();
187
+ owner?.ended(source);
188
+ if (this.sources.length === 0) this.onDrained?.();
189
+ };
190
+ this.sources.push(source);
191
+ this.endsAt.set(source, startAt + buffer.duration);
192
+ if (owner) {
193
+ this.owners.set(source, owner);
194
+ owner.sources.add(source);
195
+ }
196
+ source.start(startAt);
197
+ this.nextStartTime = startAt + buffer.duration;
198
+ if (!this.firstAudioReported) {
199
+ this.firstAudioReported = true;
200
+ this.onFirstAudio?.(startAt);
201
+ }
202
+ return startAt;
203
+ }
204
+
205
+ /** Stops playback and throws away everything scheduled, for every utterance: the barge-in path. */
206
+ stop(): void {
207
+ const scheduled = this.sources;
208
+ this.sources = [];
209
+ this.endsAt.clear();
210
+ this.owners.clear();
211
+ for (const source of scheduled) this.halt(source);
212
+ for (const utterance of [...this.utterances]) {
213
+ utterance.sources.clear();
214
+ utterance.stop();
215
+ }
216
+ this.utterances.clear();
217
+ this.nextStartTime = 0;
218
+ this.firstAudioReported = false;
219
+ }
220
+
221
+ /** @internal Stops only `utterance`'s sources and closes the gap they leave in the schedule. */
222
+ unschedule(utterance: PlaybackUtterance): void {
223
+ for (const source of utterance.sources) {
224
+ this.forget(source);
225
+ this.halt(source);
226
+ }
227
+ utterance.sources.clear();
228
+ this.utterances.delete(utterance);
229
+ let latest = 0;
230
+ for (const end of this.endsAt.values()) latest = Math.max(latest, end);
231
+ this.nextStartTime = latest;
232
+ if (this.sources.length === 0) this.firstAudioReported = false;
233
+ }
234
+
235
+ private forget(source: AudioBufferSourceLike): void {
236
+ this.sources = this.sources.filter((candidate) => candidate !== source);
237
+ this.endsAt.delete(source);
238
+ this.owners.delete(source);
239
+ }
240
+
241
+ private halt(source: AudioBufferSourceLike): void {
242
+ source.onended = null;
243
+ try {
244
+ source.stop();
245
+ } catch {
246
+ // stopping a source that already ended is not an error
247
+ }
248
+ source.disconnect?.();
249
+ }
250
+
251
+ /** Whether something is scheduled or playing. */
252
+ get isPlaying(): boolean {
253
+ return this.sources.length > 0;
254
+ }
255
+
256
+ async suspend(): Promise<void> {
257
+ await this.context.suspend?.();
258
+ }
259
+
260
+ async resume(): Promise<void> {
261
+ await this.context.resume?.();
262
+ }
263
+
264
+ /** Stops playback and closes the context. Idempotent. */
265
+ async dispose(): Promise<void> {
266
+ if (this.disposed) return;
267
+ this.stop();
268
+ this.disposed = true;
269
+ await this.context.close?.();
270
+ }
271
+ }