@jskit-ai/assistant-voice 0.2.9 → 0.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,520 @@
1
+ import { computed, ref, watch } from "vue";
2
+
3
+ import {
4
+ VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS,
5
+ VOICE_MAX_SYNTHESIS_TIMEOUT_MS,
6
+ VOICE_OUTPUT_SAMPLE_RATE,
7
+ speechTextFromAssistant
8
+ } from "../shared/protocol.js";
9
+ import { audioContextConstructor, createVoiceTurnId } from "./browser.js";
10
+ import { voiceError, voiceErrorText, voiceSpeechWording } from "./i18n.js";
11
+ import {
12
+ normalizeSpeechSegment,
13
+ pcm16ArrayBufferToFloat32,
14
+ visemeCueAtTime
15
+ } from "./voicePlayback.js";
16
+
17
+ // readable-check: allow module-state - shared resource: the page has one speaker, so a second transport waits until the first stops speaking
18
+ const speechOwner = ref(null);
19
+
20
+ /**
21
+ * The assistant's speech for one voice transport: it requests synthesis over the transport's connection, plays the
22
+ * streamed PCM through Web Audio with viseme timing and a mouth meter, and reports when each turn's playback starts
23
+ * and ends.
24
+ * @param {{
25
+ * connect: () => Promise<boolean>,
26
+ * sendControl: (payload: object) => void,
27
+ * isConnected: () => boolean,
28
+ * enabled: import("vue").ComputedRef<boolean>,
29
+ * selectedVoice: import("vue").Ref<string>,
30
+ * onPlayback: (event: import("./types.js").VoicePlaybackEvent) => unknown,
31
+ * fail: (message: string) => void
32
+ * }} dependencies
33
+ */
34
+ function useVoiceSpeech({ connect, sendControl, isConnected, enabled, selectedVoice, onPlayback, fail }) {
35
+ const speechState = ref("idle");
36
+ const playbackBlocked = ref(false);
37
+ const mouthLevel = ref(0);
38
+ const mouthPose = ref("closed");
39
+ const bufferedSeconds = ref(0);
40
+ const synthesisPending = ref(0);
41
+ const activeSpeechTurnId = ref("");
42
+ const speechInputEnded = ref(true);
43
+ let lastSpeechProgressAt = 0;
44
+ let synthesisTimeoutMs = VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS;
45
+ let lastStartedSegmentIndex = -1;
46
+ const speechClaim = Symbol("voice playback");
47
+ let closed = false;
48
+ let playbackContext = null;
49
+ let playbackGain = null;
50
+ let playbackAnalyser = null;
51
+ let playbackFrame = 0;
52
+ let playbackPreparation = 0;
53
+ let nextPlaybackTime = 0;
54
+ let playbackEpoch = 0;
55
+ let playbackReceipt = null;
56
+ let playbackQueue = Promise.resolve();
57
+ let queuedPlaybackFrames = 0;
58
+ let speechStreamEnded = false;
59
+ let speechSampleRate = VOICE_OUTPUT_SAMPLE_RATE;
60
+ let receivingTurnId = "";
61
+ let receivingSegment = null;
62
+ let stopAfterSegment = Infinity;
63
+ const streamedSegments = new Map();
64
+ let pendingVisemeSegments = [];
65
+ let scheduledVisemeSegments = [];
66
+ const playbackSources = new Set();
67
+
68
+ const speaking = computed(() => speechState.value === "speaking");
69
+ const canAppendSpeech = computed(() => Boolean(activeSpeechTurnId.value) && !speechInputEnded.value &&
70
+ synthesisPending.value < 2 && bufferedSeconds.value < 4);
71
+
72
+ function emitPlayback(phase, reason) {
73
+ const receipt = playbackReceipt;
74
+ if (!receipt || receipt.terminal || (phase === "started" && receipt.started)) return;
75
+ if (phase === "started") receipt.started = true;
76
+ else receipt.terminal = true;
77
+ try {
78
+ Promise.resolve(onPlayback({
79
+ turnId: receipt.turnId, phase, ...(reason ? { reason } : {})
80
+ })).catch(() => {});
81
+ } catch {
82
+ // Observers cannot take ownership of playback or cleanup.
83
+ }
84
+ }
85
+
86
+ function observePlaybackStart(source) {
87
+ if (!source.voiceCancelled && playbackContext.state === "running" &&
88
+ playbackContext.currentTime >= source.voiceStartsAt) emitPlayback("started");
89
+ }
90
+
91
+ function stopMouthMeter() {
92
+ if (playbackFrame) {
93
+ cancelAnimationFrame(playbackFrame);
94
+ playbackFrame = 0;
95
+ }
96
+ mouthLevel.value = 0;
97
+ mouthPose.value = "closed";
98
+ }
99
+
100
+ function startMouthMeter() {
101
+ if (playbackFrame || !playbackAnalyser) {
102
+ return;
103
+ }
104
+ const samples = new Float32Array(playbackAnalyser.fftSize);
105
+ const spectrum = new Uint8Array(playbackAnalyser.frequencyBinCount);
106
+ const averageBand = (fromHz, toHz) => {
107
+ const binWidth = playbackContext.sampleRate / playbackAnalyser.fftSize;
108
+ const start = Math.max(0, Math.floor(fromHz / binWidth));
109
+ const end = Math.min(spectrum.length, Math.ceil(toHz / binWidth));
110
+ let total = 0;
111
+ for (let index = start; index < end; index += 1) {
112
+ total += spectrum[index];
113
+ }
114
+ return total / Math.max(1, end - start);
115
+ };
116
+ const update = () => {
117
+ for (const source of playbackSources) observePlaybackStart(source);
118
+ bufferedSeconds.value = Math.max(0, nextPlaybackTime - playbackContext.currentTime);
119
+ playbackAnalyser.getFloatTimeDomainData(samples);
120
+ playbackAnalyser.getByteFrequencyData(spectrum);
121
+ let sum = 0;
122
+ for (const sample of samples) {
123
+ sum += sample * sample;
124
+ }
125
+ const level = Math.min(1, Math.sqrt(sum / samples.length) * 7);
126
+ scheduledVisemeSegments = scheduledVisemeSegments.filter((segment) => (
127
+ playbackContext.currentTime <= segment.startedAt + (segment.durationMs / 1_000) + 0.5
128
+ ));
129
+ const viseme = visemeCueAtTime(scheduledVisemeSegments, playbackContext.currentTime);
130
+ mouthLevel.value = viseme
131
+ ? Math.max(level, viseme.level)
132
+ : level;
133
+ if (viseme?.pose === "closed" || (!viseme && level < 0.035)) {
134
+ mouthPose.value = "closed";
135
+ } else if (viseme) {
136
+ mouthPose.value = viseme.pose;
137
+ } else {
138
+ const low = averageBand(120, 700);
139
+ const middle = averageBand(700, 2_100);
140
+ const high = averageBand(2_100, 4_800);
141
+ if (level > 0.63) {
142
+ mouthPose.value = "open";
143
+ } else if (low > (middle + high) * 0.72) {
144
+ mouthPose.value = "round";
145
+ } else if (middle + high > low * 1.55) {
146
+ mouthPose.value = "wide";
147
+ } else {
148
+ mouthPose.value = "small";
149
+ }
150
+ }
151
+ if (speaking.value || playbackSources.size) {
152
+ playbackFrame = requestAnimationFrame(update);
153
+ } else {
154
+ stopMouthMeter();
155
+ }
156
+ };
157
+ playbackFrame = requestAnimationFrame(update);
158
+ }
159
+
160
+ async function preparePlayback() {
161
+ const AudioContextCtor = audioContextConstructor();
162
+ if (!AudioContextCtor) {
163
+ playbackBlocked.value = true;
164
+ throw voiceError("jskit.assistant.voice.errors.playbackUnsupported");
165
+ }
166
+ if (!playbackContext || playbackContext.state === "closed") {
167
+ playbackContext = new AudioContextCtor({ latencyHint: "interactive" });
168
+ playbackGain = playbackContext.createGain();
169
+ playbackAnalyser = playbackContext.createAnalyser();
170
+ playbackAnalyser.fftSize = 1_024;
171
+ playbackAnalyser.smoothingTimeConstant = 0.58;
172
+ playbackGain.connect(playbackAnalyser);
173
+ playbackAnalyser.connect(playbackContext.destination);
174
+ }
175
+ playbackGain.gain.value = enabled.value ? 1 : 0;
176
+ const context = playbackContext;
177
+ const preparation = ++playbackPreparation;
178
+ try {
179
+ const resumed = context.resume();
180
+ if (preparation === playbackPreparation && context.state !== "running") playbackBlocked.value = true;
181
+ await resumed;
182
+ if (context.state !== "running") throw voiceError("jskit.assistant.voice.errors.soundBlocked");
183
+ if (preparation === playbackPreparation && !closed) playbackBlocked.value = false;
184
+ } catch (cause) {
185
+ // A newer unlock of this same context supersedes an older resume failure.
186
+ if (preparation !== playbackPreparation && context === playbackContext &&
187
+ context.state === "running" && !closed) return;
188
+ if (preparation === playbackPreparation && !closed) playbackBlocked.value = true;
189
+ throw cause;
190
+ }
191
+ }
192
+
193
+ function finishPlaybackWhenDrained() {
194
+ if (!activeSpeechTurnId.value || !speechStreamEnded || playbackSources.size || queuedPlaybackFrames) {
195
+ return;
196
+ }
197
+ if (playbackReceipt?.started) emitPlayback("completed");
198
+ else emitPlayback("failed", "playback-error");
199
+ activeSpeechTurnId.value = "";
200
+ speechState.value = "idle";
201
+ if (speechOwner.value === speechClaim) speechOwner.value = null;
202
+ stopMouthMeter();
203
+ }
204
+
205
+ function claimVisemeTiming(sampleCount, startsAt) {
206
+ let remaining = sampleCount;
207
+ let offsetSamples = 0;
208
+ while (remaining > 0 && pendingVisemeSegments.length) {
209
+ const segment = pendingVisemeSegments[0];
210
+ if (!Number.isFinite(segment.startedAt)) {
211
+ segment.startedAt = startsAt + (offsetSamples / speechSampleRate);
212
+ scheduledVisemeSegments.push(segment);
213
+ }
214
+ const consumed = Math.min(remaining, segment.remainingSamples);
215
+ segment.remainingSamples -= consumed;
216
+ remaining -= consumed;
217
+ offsetSamples += consumed;
218
+ if (segment.remainingSamples <= 0) {
219
+ pendingVisemeSegments.shift();
220
+ }
221
+ }
222
+ }
223
+
224
+ async function schedulePcm(buffer, epoch = playbackEpoch, segment = null) {
225
+ if (epoch !== playbackEpoch || (segment && segment.index > stopAfterSegment)) return;
226
+ await preparePlayback();
227
+ if (epoch !== playbackEpoch) {
228
+ return;
229
+ }
230
+ if (segment && segment.index > stopAfterSegment) return;
231
+ const samples = pcm16ArrayBufferToFloat32(buffer);
232
+ if (!samples.length) {
233
+ return;
234
+ }
235
+ const audioBuffer = playbackContext.createBuffer(1, samples.length, speechSampleRate);
236
+ audioBuffer.copyToChannel(samples, 0);
237
+ const source = playbackContext.createBufferSource();
238
+ source.buffer = audioBuffer;
239
+ source.voiceSegment = segment;
240
+ source.connect(playbackGain);
241
+ const startsAt = Math.max(playbackContext.currentTime + 0.025, nextPlaybackTime);
242
+ nextPlaybackTime = startsAt + audioBuffer.duration;
243
+ source.voiceStartsAt = startsAt;
244
+ source.voiceEndsAt = nextPlaybackTime;
245
+ if (segment) {
246
+ if (!Number.isFinite(segment.startedAt)) {
247
+ segment.startedAt = startsAt;
248
+ if (segment.metadata) scheduledVisemeSegments.push({ ...segment.metadata, startedAt: startsAt });
249
+ }
250
+ } else claimVisemeTiming(samples.length, startsAt);
251
+ bufferedSeconds.value = Math.max(0, nextPlaybackTime - playbackContext.currentTime);
252
+ playbackSources.add(source);
253
+ speechState.value = "speaking";
254
+ // readable-check: allow fixed-result-shape - platform object: an AudioBufferSourceNode reports its end through onended
255
+ source.onended = () => {
256
+ source.disconnect();
257
+ if (epoch !== playbackEpoch) return;
258
+ // A natural end also observes very short sounds between animation frames.
259
+ if (!source.voiceCancelled && playbackContext.state === "running") emitPlayback("started");
260
+ playbackSources.delete(source);
261
+ bufferedSeconds.value = playbackSources.size ? Math.max(0, nextPlaybackTime - playbackContext.currentTime) : 0;
262
+ if (!playbackSources.size) speechState.value = "thinking";
263
+ finishPlaybackWhenDrained();
264
+ };
265
+ source.start(startsAt);
266
+ startMouthMeter();
267
+ }
268
+
269
+ function enqueuePcm(buffer) {
270
+ const epoch = playbackEpoch;
271
+ const segment = receivingSegment;
272
+ queuedPlaybackFrames += 1;
273
+ playbackQueue = playbackQueue
274
+ .then(() => schedulePcm(buffer, epoch, segment))
275
+ .catch((playbackError) => {
276
+ if (epoch === playbackEpoch) fail(voiceErrorText(playbackError));
277
+ })
278
+ .finally(() => {
279
+ if (epoch !== playbackEpoch) return;
280
+ queuedPlaybackFrames -= 1;
281
+ finishPlaybackWhenDrained();
282
+ });
283
+ }
284
+
285
+ /**
286
+ * Stops the current turn's audio and forgets its stream, reporting the receipt's outcome.
287
+ * @param {string} [phase]
288
+ * @param {string} [reason]
289
+ */
290
+ function stopPlayback(phase = "interrupted", reason = "cancelled") {
291
+ emitPlayback(phase, reason);
292
+ playbackEpoch += 1;
293
+ activeSpeechTurnId.value = "";
294
+ speechState.value = "idle";
295
+ if (speechOwner.value === speechClaim) speechOwner.value = null;
296
+ // Retired continuations keep their old epoch, not ownership of this queue.
297
+ playbackQueue = Promise.resolve();
298
+ queuedPlaybackFrames = 0;
299
+ for (const source of playbackSources) {
300
+ try {
301
+ source.voiceCancelled = true;
302
+ source.stop();
303
+ } catch {
304
+ // A source that already ended needs no further cleanup.
305
+ }
306
+ }
307
+ playbackSources.clear();
308
+ nextPlaybackTime = 0;
309
+ speechStreamEnded = true;
310
+ speechInputEnded.value = true;
311
+ stopAfterSegment = Infinity;
312
+ bufferedSeconds.value = 0;
313
+ synthesisPending.value = 0;
314
+ synthesisTimeoutMs = VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS;
315
+ lastStartedSegmentIndex = -1;
316
+ receivingTurnId = "";
317
+ receivingSegment = null;
318
+ streamedSegments.clear();
319
+ pendingVisemeSegments = [];
320
+ scheduledVisemeSegments = [];
321
+ stopMouthMeter();
322
+ }
323
+
324
+ /**
325
+ * Handles one `speech.*` control message from the voice service.
326
+ * @param {string} type
327
+ * @param {Record<string, any>} message
328
+ */
329
+ function receiveControl(type, message) {
330
+ if (type === "speech.start") {
331
+ receivingTurnId = String(message.turnId || "");
332
+ receivingSegment = null;
333
+ if (!message.turnId || message.turnId !== activeSpeechTurnId.value) {
334
+ return;
335
+ }
336
+ speechSampleRate = Number(message.sampleRate) || VOICE_OUTPUT_SAMPLE_RATE;
337
+ speechStreamEnded = false;
338
+ speechState.value = "thinking";
339
+ nextPlaybackTime = 0;
340
+ return;
341
+ }
342
+ if (type === "speech.segment.start" && message.turnId === activeSpeechTurnId.value) {
343
+ if (!speechStreamEnded && Number.isSafeInteger(message.segmentIndex) &&
344
+ message.segmentIndex > lastStartedSegmentIndex) {
345
+ lastStartedSegmentIndex = message.segmentIndex;
346
+ synthesisTimeoutMs = VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS;
347
+ if (Number.isSafeInteger(message.synthesisTimeoutMs) && message.synthesisTimeoutMs > VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS &&
348
+ message.synthesisTimeoutMs <= VOICE_MAX_SYNTHESIS_TIMEOUT_MS) {
349
+ // The engine acquired its queue slot. Allow its bounded cold job until
350
+ // first PCM; repeated metadata and pongs are not synthesis progress.
351
+ synthesisTimeoutMs = message.synthesisTimeoutMs;
352
+ lastSpeechProgressAt = Date.now();
353
+ }
354
+ }
355
+ receivingSegment = { index: message.segmentIndex };
356
+ streamedSegments.set(message.segmentIndex, receivingSegment);
357
+ return;
358
+ }
359
+ if (type === "speech.chunk.end" && message.turnId === activeSpeechTurnId.value) {
360
+ synthesisTimeoutMs = VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS;
361
+ lastSpeechProgressAt = Date.now();
362
+ synthesisPending.value = Math.max(0, synthesisPending.value - 1);
363
+ return;
364
+ }
365
+ if (type === "speech.segment" && message.turnId === activeSpeechTurnId.value && !speechStreamEnded) {
366
+ const segment = normalizeSpeechSegment(message, speechSampleRate);
367
+ const streamed = streamedSegments.get(message.segmentIndex);
368
+ if (streamed) {
369
+ streamed.metadata = segment;
370
+ if (Number.isFinite(streamed.startedAt)) scheduledVisemeSegments.push({ ...segment, startedAt: streamed.startedAt });
371
+ streamedSegments.delete(message.segmentIndex);
372
+ } else if (segment.sampleCount) pendingVisemeSegments.push(segment);
373
+ return;
374
+ }
375
+ if (type === "speech.end" && message.turnId === activeSpeechTurnId.value) {
376
+ speechStreamEnded = true;
377
+ finishPlaybackWhenDrained();
378
+ }
379
+ }
380
+
381
+ /**
382
+ * Queues one binary PCM frame from the voice service when it belongs to the turn being spoken.
383
+ * @param {ArrayBuffer} buffer
384
+ */
385
+ function receiveAudio(buffer) {
386
+ if (enabled.value && activeSpeechTurnId.value && receivingTurnId === activeSpeechTurnId.value && !speechStreamEnded) {
387
+ synthesisTimeoutMs = VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS;
388
+ lastSpeechProgressAt = Date.now();
389
+ enqueuePcm(buffer);
390
+ }
391
+ }
392
+
393
+ /**
394
+ * Whether the voice service has made no synthesis progress on the current turn for longer than it allows.
395
+ * @returns {boolean}
396
+ */
397
+ function stalled() {
398
+ return Boolean(activeSpeechTurnId.value && synthesisPending.value && Date.now() - lastSpeechProgressAt > synthesisTimeoutMs);
399
+ }
400
+
401
+ async function speak(text, turnId = createVoiceTurnId("speak"), { stream = false } = {}) {
402
+ const speechText = speechTextFromAssistant(text, undefined, voiceSpeechWording());
403
+ if (closed || !enabled.value || !speechText) {
404
+ return false;
405
+ }
406
+ if (activeSpeechTurnId.value && isConnected()) {
407
+ sendControl({ turnId: activeSpeechTurnId.value, type: "cancel" });
408
+ }
409
+ stopPlayback();
410
+ const epoch = playbackEpoch;
411
+ playbackReceipt = { turnId, started: false, terminal: false };
412
+ activeSpeechTurnId.value = turnId;
413
+ speechState.value = "thinking";
414
+ try {
415
+ await preparePlayback();
416
+ if (epoch !== playbackEpoch) return false;
417
+ await connect();
418
+ if (epoch !== playbackEpoch) return false;
419
+ if (speechOwner.value) {
420
+ await new Promise((resolve) => {
421
+ const unwatch = watch([speechOwner, activeSpeechTurnId], () => {
422
+ if (epoch !== playbackEpoch || !speechOwner.value) {
423
+ if (epoch === playbackEpoch) speechOwner.value = speechClaim;
424
+ unwatch();
425
+ resolve();
426
+ }
427
+ }, { flush: "sync" });
428
+ });
429
+ } else speechOwner.value = speechClaim;
430
+ if (epoch !== playbackEpoch) return false;
431
+ speechState.value = "thinking";
432
+ speechInputEnded.value = !stream;
433
+ synthesisPending.value = 1;
434
+ lastSpeechProgressAt = Date.now();
435
+ sendControl({ text: speechText, turnId, type: "speak.start", ...(stream ? { stream: true } : {}), ...(selectedVoice.value ? { voiceId: selectedVoice.value } : {}) });
436
+ return true;
437
+ } catch (speechError) {
438
+ if (epoch !== playbackEpoch) return false;
439
+ stopPlayback("failed", "playback-error");
440
+ speechState.value = "idle";
441
+ throw speechError;
442
+ }
443
+ }
444
+
445
+ function appendSpeech(text) {
446
+ if (!canAppendSpeech.value) return false;
447
+ const speechText = speechTextFromAssistant(text, undefined, voiceSpeechWording());
448
+ if (!speechText) return false;
449
+ if (!synthesisPending.value) lastSpeechProgressAt = Date.now();
450
+ synthesisPending.value += 1;
451
+ sendControl({ text: speechText, turnId: activeSpeechTurnId.value, type: "speak.append" });
452
+ return true;
453
+ }
454
+
455
+ function endSpeech() {
456
+ if (!activeSpeechTurnId.value || speechInputEnded.value) return;
457
+ speechInputEnded.value = true;
458
+ sendControl({ turnId: activeSpeechTurnId.value, type: "speak.end" });
459
+ }
460
+
461
+ /**
462
+ * Lets the phrase playing now finish and drops the rest of the turn.
463
+ * @returns {boolean} False when no phrase is under way, so the caller stops speaking instead.
464
+ */
465
+ function finishAfterCurrentPhrase() {
466
+ emitPlayback("interrupted", "cancelled");
467
+ const now = playbackContext?.currentTime || 0;
468
+ const current = [...playbackSources].find(source => source.voiceEndsAt > now);
469
+ if (!current?.voiceSegment) return false;
470
+ stopAfterSegment = current.voiceSegment.index;
471
+ speechInputEnded.value = true;
472
+ for (const source of [...playbackSources]) {
473
+ if (source.voiceSegment?.index <= stopAfterSegment) continue;
474
+ source.voiceCancelled = true;
475
+ source.stop();
476
+ playbackSources.delete(source);
477
+ }
478
+ nextPlaybackTime = Math.max(now, ...[...playbackSources].map(source => source.voiceEndsAt));
479
+ bufferedSeconds.value = Math.max(0, nextPlaybackTime - now);
480
+ sendControl({ type: "speak.stop-after", turnId: activeSpeechTurnId.value, segmentIndex: stopAfterSegment });
481
+ return true;
482
+ }
483
+
484
+ /** Stops speaking for good and closes the audio context; nothing more is spoken. */
485
+ function dispose() {
486
+ closed = true;
487
+ stopPlayback();
488
+ void playbackContext?.close().catch(() => null);
489
+ playbackContext = null;
490
+ }
491
+
492
+ watch(enabled, (on) => {
493
+ if (playbackGain) {
494
+ playbackGain.gain.value = on ? 1 : 0;
495
+ }
496
+ }, { flush: "sync" });
497
+
498
+ return {
499
+ activeSpeechTurnId,
500
+ appendSpeech,
501
+ bufferedSeconds,
502
+ canAppendSpeech,
503
+ dispose,
504
+ endSpeech,
505
+ finishAfterCurrentPhrase,
506
+ mouthLevel,
507
+ mouthPose,
508
+ playbackBlocked,
509
+ preparePlayback,
510
+ receiveAudio,
511
+ receiveControl,
512
+ speak,
513
+ speaking,
514
+ speechState,
515
+ stalled,
516
+ stopPlayback
517
+ };
518
+ }
519
+
520
+ export { useVoiceSpeech };