@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.
- package/examples/conversation/main.js +1 -1
- package/examples/conversation/package.json +8 -8
- package/package.json +3 -3
- package/src/client/ConversationDialog.vue +2 -1
- package/src/client/VoiceConversation.vue +12 -6
- package/src/client/VoiceConversationControls.vue +6 -6
- package/src/client/VoiceConversationHost.vue +2 -1
- package/src/client/VoiceConversationSettings.vue +2 -1
- package/src/client/VoiceSpeakingVoiceSelect.vue +1 -1
- package/src/client/audioCapture.js +57 -36
- package/src/client/browser.js +89 -0
- package/src/client/conversationNarration.js +4 -1
- package/src/client/conversationVoiceState.js +6 -2
- package/src/client/i18n.js +7 -5
- package/src/client/types.js +104 -0
- package/src/client/voiceAvatar.js +13 -5
- package/src/client/voiceController.js +31 -7
- package/src/client/voiceConversation.js +66 -355
- package/src/client/voiceLauncher.js +18 -5
- package/src/client/voiceReplies.js +389 -0
- package/src/client/voiceSpeech.js +520 -0
- package/src/client/voiceTransport.js +55 -464
- package/src/server/voiceAccessToken.js +4 -1
- package/src/server/voiceDaemon.js +105 -47
- package/src/server/voiceProxy.js +3 -1
- package/src/server/voiceProxyConfig.js +5 -1
- package/src/shared/protocol.js +27 -5
|
@@ -1,29 +1,17 @@
|
|
|
1
|
-
import { computed, onScopeDispose, ref, watch } from "vue";
|
|
1
|
+
import { computed, onScopeDispose, ref, toValue, watch } from "vue";
|
|
2
2
|
|
|
3
|
-
import {
|
|
4
|
-
VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS,
|
|
5
|
-
VOICE_INPUT_SAMPLE_RATE,
|
|
6
|
-
VOICE_MAX_SYNTHESIS_TIMEOUT_MS,
|
|
7
|
-
VOICE_OUTPUT_SAMPLE_RATE,
|
|
8
|
-
speechTextFromAssistant
|
|
9
|
-
} from "../shared/protocol.js";
|
|
3
|
+
import { VOICE_INPUT_SAMPLE_RATE } from "../shared/protocol.js";
|
|
10
4
|
import { createMicrophoneCapture } from "./audioCapture.js";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
|
|
14
|
-
pcm16ArrayBufferToFloat32,
|
|
15
|
-
visemeCueAtTime
|
|
16
|
-
} from "./voicePlayback.js";
|
|
5
|
+
import { createVoiceTurnId, listenToPage } from "./browser.js";
|
|
6
|
+
import { useJskitText, voiceError, voiceErrorText, voiceEventError } from "./i18n.js";
|
|
7
|
+
import { useVoiceSpeech } from "./voiceSpeech.js";
|
|
17
8
|
|
|
18
9
|
const WEBSOCKET_OPEN = 1;
|
|
10
|
+
// readable-check: allow module-state - shared resource: the page has one microphone, so one transport holds it at a time
|
|
19
11
|
let microphoneOwner = null;
|
|
20
|
-
const speechOwner = ref(null);
|
|
21
12
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
25
|
-
return `${prefix}-${id}`;
|
|
26
|
-
}
|
|
13
|
+
/** Receives no playback receipts. */
|
|
14
|
+
function ignorePlayback() {}
|
|
27
15
|
|
|
28
16
|
function resolveWebSocketUrl(value) {
|
|
29
17
|
const url = new URL(value, globalThis.location?.href);
|
|
@@ -35,15 +23,25 @@ function resolveWebSocketUrl(value) {
|
|
|
35
23
|
return url.toString();
|
|
36
24
|
}
|
|
37
25
|
|
|
38
|
-
|
|
26
|
+
/**
|
|
27
|
+
* One duplex connection to the voice service: the socket with its heartbeat and recovery, the microphone and its
|
|
28
|
+
* transcripts, and the assistant's speech, which voiceSpeech.js plays.
|
|
29
|
+
* @param {{
|
|
30
|
+
* socketUrl: import("vue").MaybeRefOrGetter<string>,
|
|
31
|
+
* speechEnabled?: import("vue").MaybeRefOrGetter<boolean>,
|
|
32
|
+
* interruptSpeechOnListen?: boolean,
|
|
33
|
+
* autoReconnect?: boolean,
|
|
34
|
+
* voiceId?: string,
|
|
35
|
+
* onPlayback?: (event: import("./types.js").VoicePlaybackEvent) => unknown
|
|
36
|
+
* }} options
|
|
37
|
+
*/
|
|
38
|
+
function useVoiceTransport({ socketUrl, speechEnabled = true, interruptSpeechOnListen = false, autoReconnect = false, voiceId = "", onPlayback = ignorePlayback }) {
|
|
39
39
|
const { serverMessage, t } = useJskitText();
|
|
40
40
|
const availableVoices = ref([]);
|
|
41
41
|
const selectedVoice = ref(voiceId);
|
|
42
42
|
const connectionState = ref("idle");
|
|
43
43
|
const captureState = ref("idle");
|
|
44
|
-
const speechState = ref("idle");
|
|
45
44
|
const error = ref("");
|
|
46
|
-
const playbackBlocked = ref(false);
|
|
47
45
|
const transcript = ref("");
|
|
48
46
|
const endpoint = ref(null);
|
|
49
47
|
const completedUtterance = ref(null);
|
|
@@ -53,14 +51,9 @@ function useVoiceTransport({ socketUrl, speechEnabled = true, interruptSpeechOnL
|
|
|
53
51
|
const muted = ref(false);
|
|
54
52
|
const microphoneMuted = ref(false);
|
|
55
53
|
const inputLevel = ref(0);
|
|
56
|
-
const mouthLevel = ref(0);
|
|
57
|
-
const mouthPose = ref("closed");
|
|
58
54
|
const ready = ref(false);
|
|
59
55
|
const reconnecting = ref(false);
|
|
60
|
-
const bufferedSeconds = ref(0);
|
|
61
|
-
const synthesisPending = ref(0);
|
|
62
56
|
const activeListenTurnId = ref("");
|
|
63
|
-
const activeSpeechTurnId = ref("");
|
|
64
57
|
let socket = null;
|
|
65
58
|
let connectedSocketPath = "";
|
|
66
59
|
let connectPromise = null;
|
|
@@ -69,78 +62,36 @@ function useVoiceTransport({ socketUrl, speechEnabled = true, interruptSpeechOnL
|
|
|
69
62
|
let recoveryWanted = false;
|
|
70
63
|
let heartbeatTimer;
|
|
71
64
|
let lastPongAt = 0;
|
|
72
|
-
let lastSpeechProgressAt = 0;
|
|
73
|
-
let synthesisTimeoutMs = VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS;
|
|
74
|
-
let lastStartedSegmentIndex = -1;
|
|
75
65
|
let microphone = null;
|
|
76
66
|
let preserveBufferedMicrophone = false;
|
|
77
67
|
const openingMicrophones = new Set();
|
|
78
68
|
let microphoneClaim = null;
|
|
79
|
-
const speechClaim = Symbol("voice playback");
|
|
80
69
|
let pendingListenTurnId = "";
|
|
81
70
|
let unmounted = false;
|
|
82
|
-
let playbackContext = null;
|
|
83
|
-
let playbackGain = null;
|
|
84
|
-
let playbackAnalyser = null;
|
|
85
|
-
let playbackFrame = 0;
|
|
86
|
-
let playbackPreparation = 0;
|
|
87
|
-
let nextPlaybackTime = 0;
|
|
88
|
-
let playbackEpoch = 0;
|
|
89
|
-
let playbackReceipt = null;
|
|
90
|
-
let playbackQueue = Promise.resolve();
|
|
91
|
-
let queuedPlaybackFrames = 0;
|
|
92
|
-
let speechStreamEnded = false;
|
|
93
|
-
let speechSampleRate = VOICE_OUTPUT_SAMPLE_RATE;
|
|
94
|
-
let receivingTurnId = "";
|
|
95
|
-
let receivingSegment = null;
|
|
96
|
-
const speechInputEnded = ref(true);
|
|
97
|
-
let stopAfterSegment = Infinity;
|
|
98
|
-
const streamedSegments = new Map();
|
|
99
|
-
let pendingVisemeSegments = [];
|
|
100
|
-
let scheduledVisemeSegments = [];
|
|
101
|
-
const playbackSources = new Set();
|
|
102
71
|
|
|
103
|
-
const speechOutputEnabled = computed(() =>
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
72
|
+
const speechOutputEnabled = computed(() => toValue(speechEnabled) !== false && !muted.value);
|
|
73
|
+
const selectedSocketPath = computed(() => toValue(socketUrl) || "");
|
|
74
|
+
const speech = useVoiceSpeech({
|
|
75
|
+
connect,
|
|
76
|
+
sendControl,
|
|
77
|
+
isConnected: () => socket?.readyState === WEBSOCKET_OPEN,
|
|
78
|
+
enabled: speechOutputEnabled,
|
|
79
|
+
selectedVoice,
|
|
80
|
+
onPlayback,
|
|
81
|
+
fail: setError
|
|
108
82
|
});
|
|
109
|
-
const
|
|
83
|
+
const { activeSpeechTurnId, speechState } = speech;
|
|
110
84
|
const state = computed(() => error.value ? "error" : captureState.value !== "idle" ? captureState.value
|
|
111
85
|
: speechState.value !== "idle" ? speechState.value : connectionState.value);
|
|
112
86
|
const listening = computed(() => captureState.value === "listening");
|
|
113
|
-
const speaking = computed(() => speechState.value === "speaking");
|
|
114
87
|
const busy = computed(() => captureState.value !== "idle" || connectionState.value === "connecting" || speechState.value === "thinking");
|
|
115
88
|
|
|
116
|
-
const canAppendSpeech = computed(() => Boolean(activeSpeechTurnId.value) && !speechInputEnded.value &&
|
|
117
|
-
synthesisPending.value < 2 && bufferedSeconds.value < 4);
|
|
118
|
-
|
|
119
|
-
function emitPlayback(phase, reason) {
|
|
120
|
-
const receipt = playbackReceipt;
|
|
121
|
-
if (!receipt || receipt.terminal || (phase === "started" && receipt.started)) return;
|
|
122
|
-
if (phase === "started") receipt.started = true;
|
|
123
|
-
else receipt.terminal = true;
|
|
124
|
-
try {
|
|
125
|
-
Promise.resolve(onPlayback?.({
|
|
126
|
-
turnId: receipt.turnId, phase, ...(reason ? { reason } : {})
|
|
127
|
-
})).catch(() => {});
|
|
128
|
-
} catch {
|
|
129
|
-
// Observers cannot take ownership of playback or cleanup.
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
function observePlaybackStart(source) {
|
|
134
|
-
if (!source.voiceCancelled && playbackContext.state === "running" &&
|
|
135
|
-
playbackContext.currentTime >= source.voiceStartsAt) emitPlayback("started");
|
|
136
|
-
}
|
|
137
|
-
|
|
138
89
|
function setError(message = "", reason = "playback-error") {
|
|
139
90
|
pendingListenTurnId = "";
|
|
140
91
|
endpoint.value = null;
|
|
141
92
|
activeListenTurnId.value = "";
|
|
142
93
|
void closeMicrophone().catch(() => null);
|
|
143
|
-
stopPlayback("failed", reason);
|
|
94
|
+
speech.stopPlayback("failed", reason);
|
|
144
95
|
error.value = String(message || t("jskit.assistant.voice.errors.couldNotContinue"));
|
|
145
96
|
captureState.value = "idle";
|
|
146
97
|
connectionState.value = "idle";
|
|
@@ -174,7 +125,7 @@ function useVoiceTransport({ socketUrl, speechEnabled = true, interruptSpeechOnL
|
|
|
174
125
|
connectionLost();
|
|
175
126
|
return;
|
|
176
127
|
}
|
|
177
|
-
if (
|
|
128
|
+
if (speech.stalled()) {
|
|
178
129
|
connectionLost(t("jskit.assistant.voice.errors.speechStalled"));
|
|
179
130
|
return;
|
|
180
131
|
}
|
|
@@ -193,237 +144,10 @@ function useVoiceTransport({ socketUrl, speechEnabled = true, interruptSpeechOnL
|
|
|
193
144
|
const claim = microphoneClaim;
|
|
194
145
|
microphone = null;
|
|
195
146
|
inputLevel.value = 0;
|
|
196
|
-
try { await current?.close
|
|
147
|
+
try { await current?.close(); }
|
|
197
148
|
finally { if (microphoneOwner === claim) microphoneOwner = null; }
|
|
198
149
|
}
|
|
199
150
|
|
|
200
|
-
function stopMouthMeter() {
|
|
201
|
-
if (playbackFrame) {
|
|
202
|
-
cancelAnimationFrame(playbackFrame);
|
|
203
|
-
playbackFrame = 0;
|
|
204
|
-
}
|
|
205
|
-
mouthLevel.value = 0;
|
|
206
|
-
mouthPose.value = "closed";
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
function startMouthMeter() {
|
|
210
|
-
if (playbackFrame || !playbackAnalyser) {
|
|
211
|
-
return;
|
|
212
|
-
}
|
|
213
|
-
const samples = new Float32Array(playbackAnalyser.fftSize);
|
|
214
|
-
const spectrum = new Uint8Array(playbackAnalyser.frequencyBinCount);
|
|
215
|
-
const averageBand = (fromHz, toHz) => {
|
|
216
|
-
const binWidth = playbackContext.sampleRate / playbackAnalyser.fftSize;
|
|
217
|
-
const start = Math.max(0, Math.floor(fromHz / binWidth));
|
|
218
|
-
const end = Math.min(spectrum.length, Math.ceil(toHz / binWidth));
|
|
219
|
-
let total = 0;
|
|
220
|
-
for (let index = start; index < end; index += 1) {
|
|
221
|
-
total += spectrum[index];
|
|
222
|
-
}
|
|
223
|
-
return total / Math.max(1, end - start);
|
|
224
|
-
};
|
|
225
|
-
const update = () => {
|
|
226
|
-
for (const source of playbackSources) observePlaybackStart(source);
|
|
227
|
-
bufferedSeconds.value = Math.max(0, nextPlaybackTime - playbackContext.currentTime);
|
|
228
|
-
playbackAnalyser.getFloatTimeDomainData(samples);
|
|
229
|
-
playbackAnalyser.getByteFrequencyData(spectrum);
|
|
230
|
-
let sum = 0;
|
|
231
|
-
for (const sample of samples) {
|
|
232
|
-
sum += sample * sample;
|
|
233
|
-
}
|
|
234
|
-
const level = Math.min(1, Math.sqrt(sum / samples.length) * 7);
|
|
235
|
-
scheduledVisemeSegments = scheduledVisemeSegments.filter((segment) => (
|
|
236
|
-
playbackContext.currentTime <= segment.startedAt + (segment.durationMs / 1_000) + 0.5
|
|
237
|
-
));
|
|
238
|
-
const viseme = visemeCueAtTime(scheduledVisemeSegments, playbackContext.currentTime);
|
|
239
|
-
mouthLevel.value = viseme
|
|
240
|
-
? Math.max(level, viseme.level)
|
|
241
|
-
: level;
|
|
242
|
-
if (viseme?.pose === "closed" || (!viseme && level < 0.035)) {
|
|
243
|
-
mouthPose.value = "closed";
|
|
244
|
-
} else if (viseme) {
|
|
245
|
-
mouthPose.value = viseme.pose;
|
|
246
|
-
} else {
|
|
247
|
-
const low = averageBand(120, 700);
|
|
248
|
-
const middle = averageBand(700, 2_100);
|
|
249
|
-
const high = averageBand(2_100, 4_800);
|
|
250
|
-
if (level > 0.63) {
|
|
251
|
-
mouthPose.value = "open";
|
|
252
|
-
} else if (low > (middle + high) * 0.72) {
|
|
253
|
-
mouthPose.value = "round";
|
|
254
|
-
} else if (middle + high > low * 1.55) {
|
|
255
|
-
mouthPose.value = "wide";
|
|
256
|
-
} else {
|
|
257
|
-
mouthPose.value = "small";
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
if (speaking.value || playbackSources.size) {
|
|
261
|
-
playbackFrame = requestAnimationFrame(update);
|
|
262
|
-
} else {
|
|
263
|
-
stopMouthMeter();
|
|
264
|
-
}
|
|
265
|
-
};
|
|
266
|
-
playbackFrame = requestAnimationFrame(update);
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
async function preparePlayback() {
|
|
270
|
-
const AudioContextCtor = window.AudioContext || window.webkitAudioContext;
|
|
271
|
-
if (!AudioContextCtor) {
|
|
272
|
-
playbackBlocked.value = true;
|
|
273
|
-
throw voiceError("jskit.assistant.voice.errors.playbackUnsupported");
|
|
274
|
-
}
|
|
275
|
-
if (!playbackContext || playbackContext.state === "closed") {
|
|
276
|
-
playbackContext = new AudioContextCtor({ latencyHint: "interactive" });
|
|
277
|
-
playbackGain = playbackContext.createGain();
|
|
278
|
-
playbackAnalyser = playbackContext.createAnalyser();
|
|
279
|
-
playbackAnalyser.fftSize = 1_024;
|
|
280
|
-
playbackAnalyser.smoothingTimeConstant = 0.58;
|
|
281
|
-
playbackGain.connect(playbackAnalyser);
|
|
282
|
-
playbackAnalyser.connect(playbackContext.destination);
|
|
283
|
-
}
|
|
284
|
-
playbackGain.gain.value = speechOutputEnabled.value ? 1 : 0;
|
|
285
|
-
const context = playbackContext;
|
|
286
|
-
const preparation = ++playbackPreparation;
|
|
287
|
-
try {
|
|
288
|
-
const resumed = context.resume();
|
|
289
|
-
if (preparation === playbackPreparation && context.state !== "running") playbackBlocked.value = true;
|
|
290
|
-
await resumed;
|
|
291
|
-
if (context.state !== "running") throw voiceError("jskit.assistant.voice.errors.soundBlocked");
|
|
292
|
-
if (preparation === playbackPreparation && !unmounted) playbackBlocked.value = false;
|
|
293
|
-
} catch (cause) {
|
|
294
|
-
// A newer unlock of this same context supersedes an older resume failure.
|
|
295
|
-
if (preparation !== playbackPreparation && context === playbackContext &&
|
|
296
|
-
context.state === "running" && !unmounted) return;
|
|
297
|
-
if (preparation === playbackPreparation && !unmounted) playbackBlocked.value = true;
|
|
298
|
-
throw cause;
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
function finishPlaybackWhenDrained() {
|
|
303
|
-
if (!activeSpeechTurnId.value || !speechStreamEnded || playbackSources.size || queuedPlaybackFrames) {
|
|
304
|
-
return;
|
|
305
|
-
}
|
|
306
|
-
if (playbackReceipt?.started) emitPlayback("completed");
|
|
307
|
-
else emitPlayback("failed", "playback-error");
|
|
308
|
-
activeSpeechTurnId.value = "";
|
|
309
|
-
speechState.value = "idle";
|
|
310
|
-
if (speechOwner.value === speechClaim) speechOwner.value = null;
|
|
311
|
-
stopMouthMeter();
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
function claimVisemeTiming(sampleCount, startsAt) {
|
|
315
|
-
let remaining = sampleCount;
|
|
316
|
-
let offsetSamples = 0;
|
|
317
|
-
while (remaining > 0 && pendingVisemeSegments.length) {
|
|
318
|
-
const segment = pendingVisemeSegments[0];
|
|
319
|
-
if (!Number.isFinite(segment.startedAt)) {
|
|
320
|
-
segment.startedAt = startsAt + (offsetSamples / speechSampleRate);
|
|
321
|
-
scheduledVisemeSegments.push(segment);
|
|
322
|
-
}
|
|
323
|
-
const consumed = Math.min(remaining, segment.remainingSamples);
|
|
324
|
-
segment.remainingSamples -= consumed;
|
|
325
|
-
remaining -= consumed;
|
|
326
|
-
offsetSamples += consumed;
|
|
327
|
-
if (segment.remainingSamples <= 0) {
|
|
328
|
-
pendingVisemeSegments.shift();
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
async function schedulePcm(buffer, epoch = playbackEpoch, segment = null) {
|
|
334
|
-
if (epoch !== playbackEpoch || (segment && segment.index > stopAfterSegment)) return;
|
|
335
|
-
await preparePlayback();
|
|
336
|
-
if (epoch !== playbackEpoch) {
|
|
337
|
-
return;
|
|
338
|
-
}
|
|
339
|
-
if (segment && segment.index > stopAfterSegment) return;
|
|
340
|
-
const samples = pcm16ArrayBufferToFloat32(buffer);
|
|
341
|
-
if (!samples.length) {
|
|
342
|
-
return;
|
|
343
|
-
}
|
|
344
|
-
const audioBuffer = playbackContext.createBuffer(1, samples.length, speechSampleRate);
|
|
345
|
-
audioBuffer.copyToChannel(samples, 0);
|
|
346
|
-
const source = playbackContext.createBufferSource();
|
|
347
|
-
source.buffer = audioBuffer;
|
|
348
|
-
source.voiceSegment = segment;
|
|
349
|
-
source.connect(playbackGain);
|
|
350
|
-
const startsAt = Math.max(playbackContext.currentTime + 0.025, nextPlaybackTime);
|
|
351
|
-
nextPlaybackTime = startsAt + audioBuffer.duration;
|
|
352
|
-
source.voiceStartsAt = startsAt;
|
|
353
|
-
source.voiceEndsAt = nextPlaybackTime;
|
|
354
|
-
if (segment) {
|
|
355
|
-
if (!Number.isFinite(segment.startedAt)) {
|
|
356
|
-
segment.startedAt = startsAt;
|
|
357
|
-
if (segment.metadata) scheduledVisemeSegments.push({ ...segment.metadata, startedAt: startsAt });
|
|
358
|
-
}
|
|
359
|
-
} else claimVisemeTiming(samples.length, startsAt);
|
|
360
|
-
bufferedSeconds.value = Math.max(0, nextPlaybackTime - playbackContext.currentTime);
|
|
361
|
-
playbackSources.add(source);
|
|
362
|
-
speechState.value = "speaking";
|
|
363
|
-
source.onended = () => {
|
|
364
|
-
source.disconnect();
|
|
365
|
-
if (epoch !== playbackEpoch) return;
|
|
366
|
-
// A natural end also observes very short sounds between animation frames.
|
|
367
|
-
if (!source.voiceCancelled && playbackContext.state === "running") emitPlayback("started");
|
|
368
|
-
playbackSources.delete(source);
|
|
369
|
-
bufferedSeconds.value = playbackSources.size ? Math.max(0, nextPlaybackTime - playbackContext.currentTime) : 0;
|
|
370
|
-
if (!playbackSources.size) speechState.value = "thinking";
|
|
371
|
-
finishPlaybackWhenDrained();
|
|
372
|
-
};
|
|
373
|
-
source.start(startsAt);
|
|
374
|
-
startMouthMeter();
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
function enqueuePcm(buffer) {
|
|
378
|
-
const epoch = playbackEpoch;
|
|
379
|
-
const segment = receivingSegment;
|
|
380
|
-
queuedPlaybackFrames += 1;
|
|
381
|
-
playbackQueue = playbackQueue
|
|
382
|
-
.then(() => schedulePcm(buffer, epoch, segment))
|
|
383
|
-
.catch((playbackError) => {
|
|
384
|
-
if (epoch === playbackEpoch) setError(voiceErrorText(playbackError));
|
|
385
|
-
})
|
|
386
|
-
.finally(() => {
|
|
387
|
-
if (epoch !== playbackEpoch) return;
|
|
388
|
-
queuedPlaybackFrames -= 1;
|
|
389
|
-
finishPlaybackWhenDrained();
|
|
390
|
-
});
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
function stopPlayback(phase = "interrupted", reason = "cancelled") {
|
|
394
|
-
emitPlayback(phase, reason);
|
|
395
|
-
playbackEpoch += 1;
|
|
396
|
-
activeSpeechTurnId.value = "";
|
|
397
|
-
speechState.value = "idle";
|
|
398
|
-
if (speechOwner.value === speechClaim) speechOwner.value = null;
|
|
399
|
-
// Retired continuations keep their old epoch, not ownership of this queue.
|
|
400
|
-
playbackQueue = Promise.resolve();
|
|
401
|
-
queuedPlaybackFrames = 0;
|
|
402
|
-
for (const source of playbackSources) {
|
|
403
|
-
try {
|
|
404
|
-
source.voiceCancelled = true;
|
|
405
|
-
source.stop();
|
|
406
|
-
} catch {
|
|
407
|
-
// A source that already ended needs no further cleanup.
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
playbackSources.clear();
|
|
411
|
-
nextPlaybackTime = 0;
|
|
412
|
-
speechStreamEnded = true;
|
|
413
|
-
speechInputEnded.value = true;
|
|
414
|
-
stopAfterSegment = Infinity;
|
|
415
|
-
bufferedSeconds.value = 0;
|
|
416
|
-
synthesisPending.value = 0;
|
|
417
|
-
synthesisTimeoutMs = VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS;
|
|
418
|
-
lastStartedSegmentIndex = -1;
|
|
419
|
-
receivingTurnId = "";
|
|
420
|
-
receivingSegment = null;
|
|
421
|
-
streamedSegments.clear();
|
|
422
|
-
pendingVisemeSegments = [];
|
|
423
|
-
scheduledVisemeSegments = [];
|
|
424
|
-
stopMouthMeter();
|
|
425
|
-
}
|
|
426
|
-
|
|
427
151
|
function handleControlMessage(message = {}) {
|
|
428
152
|
const type = String(message.type || "");
|
|
429
153
|
if (type === "pong") { lastPongAt = Date.now(); return; }
|
|
@@ -475,54 +199,8 @@ function useVoiceTransport({ socketUrl, speechEnabled = true, interruptSpeechOnL
|
|
|
475
199
|
}
|
|
476
200
|
return;
|
|
477
201
|
}
|
|
478
|
-
if (type
|
|
479
|
-
|
|
480
|
-
receivingSegment = null;
|
|
481
|
-
if (!message.turnId || message.turnId !== activeSpeechTurnId.value) {
|
|
482
|
-
return;
|
|
483
|
-
}
|
|
484
|
-
speechSampleRate = Number(message.sampleRate) || VOICE_OUTPUT_SAMPLE_RATE;
|
|
485
|
-
speechStreamEnded = false;
|
|
486
|
-
speechState.value = "thinking";
|
|
487
|
-
nextPlaybackTime = 0;
|
|
488
|
-
return;
|
|
489
|
-
}
|
|
490
|
-
if (type === "speech.segment.start" && message.turnId === activeSpeechTurnId.value) {
|
|
491
|
-
if (!speechStreamEnded && Number.isSafeInteger(message.segmentIndex) &&
|
|
492
|
-
message.segmentIndex > lastStartedSegmentIndex) {
|
|
493
|
-
lastStartedSegmentIndex = message.segmentIndex;
|
|
494
|
-
synthesisTimeoutMs = VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS;
|
|
495
|
-
if (Number.isSafeInteger(message.synthesisTimeoutMs) && message.synthesisTimeoutMs > VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS &&
|
|
496
|
-
message.synthesisTimeoutMs <= VOICE_MAX_SYNTHESIS_TIMEOUT_MS) {
|
|
497
|
-
// The engine acquired its queue slot. Allow its bounded cold job until
|
|
498
|
-
// first PCM; repeated metadata and pongs are not synthesis progress.
|
|
499
|
-
synthesisTimeoutMs = message.synthesisTimeoutMs;
|
|
500
|
-
lastSpeechProgressAt = Date.now();
|
|
501
|
-
}
|
|
502
|
-
}
|
|
503
|
-
receivingSegment = { index: message.segmentIndex };
|
|
504
|
-
streamedSegments.set(message.segmentIndex, receivingSegment);
|
|
505
|
-
return;
|
|
506
|
-
}
|
|
507
|
-
if (type === "speech.chunk.end" && message.turnId === activeSpeechTurnId.value) {
|
|
508
|
-
synthesisTimeoutMs = VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS;
|
|
509
|
-
lastSpeechProgressAt = Date.now();
|
|
510
|
-
synthesisPending.value = Math.max(0, synthesisPending.value - 1);
|
|
511
|
-
return;
|
|
512
|
-
}
|
|
513
|
-
if (type === "speech.segment" && message.turnId === activeSpeechTurnId.value && !speechStreamEnded) {
|
|
514
|
-
const segment = normalizeSpeechSegment(message, speechSampleRate);
|
|
515
|
-
const streamed = streamedSegments.get(message.segmentIndex);
|
|
516
|
-
if (streamed) {
|
|
517
|
-
streamed.metadata = segment;
|
|
518
|
-
if (Number.isFinite(streamed.startedAt)) scheduledVisemeSegments.push({ ...segment, startedAt: streamed.startedAt });
|
|
519
|
-
streamedSegments.delete(message.segmentIndex);
|
|
520
|
-
} else if (segment.sampleCount) pendingVisemeSegments.push(segment);
|
|
521
|
-
return;
|
|
522
|
-
}
|
|
523
|
-
if (type === "speech.end" && message.turnId === activeSpeechTurnId.value) {
|
|
524
|
-
speechStreamEnded = true;
|
|
525
|
-
finishPlaybackWhenDrained();
|
|
202
|
+
if (type.startsWith("speech.")) {
|
|
203
|
+
speech.receiveControl(type, message);
|
|
526
204
|
return;
|
|
527
205
|
}
|
|
528
206
|
if (type === "busy" || type === "error") {
|
|
@@ -538,11 +216,7 @@ function useVoiceTransport({ socketUrl, speechEnabled = true, interruptSpeechOnL
|
|
|
538
216
|
|
|
539
217
|
function handleSocketMessage(event) {
|
|
540
218
|
if (event.data instanceof ArrayBuffer) {
|
|
541
|
-
|
|
542
|
-
synthesisTimeoutMs = VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS;
|
|
543
|
-
lastSpeechProgressAt = Date.now();
|
|
544
|
-
enqueuePcm(event.data);
|
|
545
|
-
}
|
|
219
|
+
speech.receiveAudio(event.data);
|
|
546
220
|
return;
|
|
547
221
|
}
|
|
548
222
|
let message;
|
|
@@ -562,7 +236,7 @@ function useVoiceTransport({ socketUrl, speechEnabled = true, interruptSpeechOnL
|
|
|
562
236
|
connectedSocketPath = "";
|
|
563
237
|
connectPromise = null;
|
|
564
238
|
ready.value = false;
|
|
565
|
-
current?.close
|
|
239
|
+
current?.close(1000, "Voice client closed");
|
|
566
240
|
connectionState.value = "idle";
|
|
567
241
|
if (!preserveError) error.value = "";
|
|
568
242
|
}
|
|
@@ -745,89 +419,15 @@ function useVoiceTransport({ socketUrl, speechEnabled = true, interruptSpeechOnL
|
|
|
745
419
|
sendControl({ turnId, type: "listen.stop" });
|
|
746
420
|
}
|
|
747
421
|
|
|
748
|
-
async function speak(text, turnId = createVoiceTurnId("speak"), { stream = false } = {}) {
|
|
749
|
-
const speechText = speechTextFromAssistant(text, undefined, voiceSpeechWording());
|
|
750
|
-
if (unmounted || !speechOutputEnabled.value || !speechText) {
|
|
751
|
-
return false;
|
|
752
|
-
}
|
|
753
|
-
if (activeSpeechTurnId.value && socket?.readyState === WEBSOCKET_OPEN) {
|
|
754
|
-
sendControl({ turnId: activeSpeechTurnId.value, type: "cancel" });
|
|
755
|
-
}
|
|
756
|
-
stopPlayback();
|
|
757
|
-
const epoch = playbackEpoch;
|
|
758
|
-
playbackReceipt = { turnId, started: false, terminal: false };
|
|
759
|
-
activeSpeechTurnId.value = turnId;
|
|
760
|
-
speechState.value = "thinking";
|
|
761
|
-
try {
|
|
762
|
-
await preparePlayback();
|
|
763
|
-
if (epoch !== playbackEpoch) return false;
|
|
764
|
-
await connect();
|
|
765
|
-
if (epoch !== playbackEpoch) return false;
|
|
766
|
-
if (speechOwner.value) {
|
|
767
|
-
await new Promise((resolve) => {
|
|
768
|
-
const unwatch = watch([speechOwner, activeSpeechTurnId], () => {
|
|
769
|
-
if (epoch !== playbackEpoch || !speechOwner.value) {
|
|
770
|
-
if (epoch === playbackEpoch) speechOwner.value = speechClaim;
|
|
771
|
-
unwatch();
|
|
772
|
-
resolve();
|
|
773
|
-
}
|
|
774
|
-
}, { flush: "sync" });
|
|
775
|
-
});
|
|
776
|
-
} else speechOwner.value = speechClaim;
|
|
777
|
-
if (epoch !== playbackEpoch) return false;
|
|
778
|
-
speechState.value = "thinking";
|
|
779
|
-
speechInputEnded.value = !stream;
|
|
780
|
-
synthesisPending.value = 1;
|
|
781
|
-
lastSpeechProgressAt = Date.now();
|
|
782
|
-
sendControl({ text: speechText, turnId, type: "speak.start", ...(stream ? { stream: true } : {}), ...(selectedVoice.value ? { voiceId: selectedVoice.value } : {}) });
|
|
783
|
-
return true;
|
|
784
|
-
} catch (speechError) {
|
|
785
|
-
if (epoch !== playbackEpoch) return false;
|
|
786
|
-
stopPlayback("failed", "playback-error");
|
|
787
|
-
speechState.value = "idle";
|
|
788
|
-
throw speechError;
|
|
789
|
-
}
|
|
790
|
-
}
|
|
791
|
-
|
|
792
|
-
function appendSpeech(text) {
|
|
793
|
-
if (!canAppendSpeech.value) return false;
|
|
794
|
-
const speechText = speechTextFromAssistant(text, undefined, voiceSpeechWording());
|
|
795
|
-
if (!speechText) return false;
|
|
796
|
-
if (!synthesisPending.value) lastSpeechProgressAt = Date.now();
|
|
797
|
-
synthesisPending.value += 1;
|
|
798
|
-
sendControl({ text: speechText, turnId: activeSpeechTurnId.value, type: "speak.append" });
|
|
799
|
-
return true;
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
function endSpeech() {
|
|
803
|
-
if (!activeSpeechTurnId.value || speechInputEnded.value) return;
|
|
804
|
-
speechInputEnded.value = true;
|
|
805
|
-
sendControl({ turnId: activeSpeechTurnId.value, type: "speak.end" });
|
|
806
|
-
}
|
|
807
|
-
|
|
808
422
|
function finishCurrentPhrase() {
|
|
809
423
|
if (!activeSpeechTurnId.value) return;
|
|
810
|
-
|
|
811
|
-
const now = playbackContext?.currentTime || 0;
|
|
812
|
-
const current = [...playbackSources].find(source => source.voiceEndsAt > now);
|
|
813
|
-
if (!current?.voiceSegment) { stopSpeaking(); return; }
|
|
814
|
-
stopAfterSegment = current.voiceSegment.index;
|
|
815
|
-
speechInputEnded.value = true;
|
|
816
|
-
for (const source of [...playbackSources]) {
|
|
817
|
-
if (source.voiceSegment?.index <= stopAfterSegment) continue;
|
|
818
|
-
source.voiceCancelled = true;
|
|
819
|
-
source.stop();
|
|
820
|
-
playbackSources.delete(source);
|
|
821
|
-
}
|
|
822
|
-
nextPlaybackTime = Math.max(now, ...[...playbackSources].map(source => source.voiceEndsAt));
|
|
823
|
-
bufferedSeconds.value = Math.max(0, nextPlaybackTime - now);
|
|
824
|
-
sendControl({ type: "speak.stop-after", turnId: activeSpeechTurnId.value, segmentIndex: stopAfterSegment });
|
|
424
|
+
if (!speech.finishAfterCurrentPhrase()) stopSpeaking();
|
|
825
425
|
}
|
|
826
426
|
|
|
827
427
|
function stopSpeaking(reason = "cancelled") {
|
|
828
428
|
const turnId = activeSpeechTurnId.value;
|
|
829
429
|
const pending = turnId && !ready.value && !activeListenTurnId.value && !pendingListenTurnId;
|
|
830
|
-
stopPlayback("interrupted", reason);
|
|
430
|
+
speech.stopPlayback("interrupted", reason);
|
|
831
431
|
if (turnId && socket?.readyState === WEBSOCKET_OPEN) sendControl({ turnId, type: "cancel" });
|
|
832
432
|
if (pending) disconnect();
|
|
833
433
|
}
|
|
@@ -881,9 +481,6 @@ function useVoiceTransport({ socketUrl, speechEnabled = true, interruptSpeechOnL
|
|
|
881
481
|
}
|
|
882
482
|
|
|
883
483
|
watch(speechOutputEnabled, (enabled) => {
|
|
884
|
-
if (playbackGain) {
|
|
885
|
-
playbackGain.gain.value = enabled ? 1 : 0;
|
|
886
|
-
}
|
|
887
484
|
if (!enabled && activeSpeechTurnId.value) {
|
|
888
485
|
stopSpeaking("muted");
|
|
889
486
|
}
|
|
@@ -903,20 +500,17 @@ function useVoiceTransport({ socketUrl, speechEnabled = true, interruptSpeechOnL
|
|
|
903
500
|
recoveryTimer = null;
|
|
904
501
|
disconnect({ preserveError: true });
|
|
905
502
|
}
|
|
906
|
-
const
|
|
907
|
-
page.addEventListener?.("pagehide", pauseForPageExit);
|
|
503
|
+
const stopPageExitListener = listenToPage("pagehide", pauseForPageExit);
|
|
908
504
|
onScopeDispose(() => {
|
|
909
|
-
|
|
505
|
+
stopPageExitListener();
|
|
910
506
|
unmounted = true;
|
|
911
507
|
clearTimeout(recoveryTimer);
|
|
912
508
|
clearInterval(heartbeatTimer);
|
|
913
509
|
pendingListenTurnId = "";
|
|
914
510
|
activeListenTurnId.value = "";
|
|
915
511
|
void closeMicrophone().catch(() => null);
|
|
916
|
-
|
|
512
|
+
speech.dispose();
|
|
917
513
|
disconnect();
|
|
918
|
-
void playbackContext?.close?.().catch(() => null);
|
|
919
|
-
playbackContext = null;
|
|
920
514
|
});
|
|
921
515
|
|
|
922
516
|
return {
|
|
@@ -924,10 +518,10 @@ function useVoiceTransport({ socketUrl, speechEnabled = true, interruptSpeechOnL
|
|
|
924
518
|
selectedVoice,
|
|
925
519
|
activeListenTurnId,
|
|
926
520
|
activeSpeechTurnId,
|
|
927
|
-
appendSpeech,
|
|
928
|
-
bufferedSeconds,
|
|
929
|
-
canAppendSpeech,
|
|
930
|
-
endSpeech,
|
|
521
|
+
appendSpeech: speech.appendSpeech,
|
|
522
|
+
bufferedSeconds: speech.bufferedSeconds,
|
|
523
|
+
canAppendSpeech: speech.canAppendSpeech,
|
|
524
|
+
endSpeech: speech.endSpeech,
|
|
931
525
|
captureState,
|
|
932
526
|
completedUtterance,
|
|
933
527
|
utteranceReset,
|
|
@@ -943,17 +537,17 @@ function useVoiceTransport({ socketUrl, speechEnabled = true, interruptSpeechOnL
|
|
|
943
537
|
error,
|
|
944
538
|
inputLevel,
|
|
945
539
|
listening,
|
|
946
|
-
mouthLevel,
|
|
947
|
-
mouthPose,
|
|
540
|
+
mouthLevel: speech.mouthLevel,
|
|
541
|
+
mouthPose: speech.mouthPose,
|
|
948
542
|
microphoneMuted,
|
|
949
543
|
muted,
|
|
950
544
|
partialTranscript,
|
|
951
|
-
playbackBlocked,
|
|
952
|
-
preparePlayback,
|
|
545
|
+
playbackBlocked: speech.playbackBlocked,
|
|
546
|
+
preparePlayback: speech.preparePlayback,
|
|
953
547
|
ready,
|
|
954
548
|
reconnecting,
|
|
955
|
-
speak,
|
|
956
|
-
speaking,
|
|
549
|
+
speak: speech.speak,
|
|
550
|
+
speaking: speech.speaking,
|
|
957
551
|
startListening,
|
|
958
552
|
setMicrophoneMuted,
|
|
959
553
|
state,
|
|
@@ -964,7 +558,4 @@ function useVoiceTransport({ socketUrl, speechEnabled = true, interruptSpeechOnL
|
|
|
964
558
|
};
|
|
965
559
|
}
|
|
966
560
|
|
|
967
|
-
export {
|
|
968
|
-
createVoiceTurnId,
|
|
969
|
-
useVoiceTransport
|
|
970
|
-
};
|
|
561
|
+
export { useVoiceTransport };
|