@convai/web-sdk 2.1.0-beta.0 → 2.1.0-beta.1
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 +37 -0
- package/dist/core/ConvaiClient.d.ts +11 -0
- package/dist/core/ConvaiClient.js +59 -1
- package/dist/core/DataAudioPlayer.d.ts +131 -0
- package/dist/core/DataAudioPlayer.js +397 -0
- package/dist/core/MessageHandler.d.ts +13 -0
- package/dist/core/MessageHandler.js +57 -0
- package/dist/core/index.d.ts +4 -0
- package/dist/core/index.js +2 -0
- package/dist/core/streamController.d.ts +72 -0
- package/dist/core/streamController.js +110 -0
- package/dist/core/types.d.ts +84 -0
- package/dist/react/hooks/useConvaiClient.js +1 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -10,6 +10,11 @@ TypeScript-first SDK for embedding Convai AI characters into React and vanilla J
|
|
|
10
10
|
|
|
11
11
|
---
|
|
12
12
|
|
|
13
|
+
## What's new in 2.1 (beta)
|
|
14
|
+
|
|
15
|
+
- **Voice over the data channel** — set `audioRouting: 'data_only'` and the character's voice arrives as audio chunks next to the lipsync frames, played by the SDK (`client.dataAudio`). Only audio whose lipsync has also arrived plays: a reply starts once 0.9 s of both is in hand (`dataAudioBufferSeconds`), plays as one continuous stream, and on a slow network pauses between words to refill instead of stuttering or speaking with a still face. A pause in delivery never ends a reply early. [Usage below.](#voice-over-the-data-channel-beta)
|
|
16
|
+
- **Speaking state follows what is heard** — on that path `speakingChange` and `state.isSpeaking` turn on when the reply is first heard and off when it finishes playing. The server's own flags, which follow when it sent the audio, arrive as the new `serverSpeakingChange` event.
|
|
17
|
+
|
|
13
18
|
## What's new in 2.0
|
|
14
19
|
|
|
15
20
|
Install with `npm install @convai/web-sdk @convai/web-widget` (the widget only if you use the bundled chat UI). 2.0 also carries every fix from 1.9.1 – 1.9.4: SSE sends `authToken` as `API-AUTH-TOKEN` and ends each request at `done`; the character-info lookup sends `CONVAI-API-KEY`; audio, video and screen-share controls follow tracks changed outside them; a disconnected mic reads as muted; the `mha` helpers no longer hold a frozen sneer.
|
|
@@ -312,6 +317,38 @@ your bundler handle the ESM.
|
|
|
312
317
|
|
|
313
318
|
---
|
|
314
319
|
|
|
320
|
+
## Voice over the data channel (beta)
|
|
321
|
+
|
|
322
|
+
Receive the character's voice next to its lipsync and let the SDK play it, so a 3D character's mouth and voice stay in step on every reply.
|
|
323
|
+
|
|
324
|
+
```ts
|
|
325
|
+
import { ConvaiClient } from '@convai/web-sdk/core';
|
|
326
|
+
|
|
327
|
+
const client = new ConvaiClient({
|
|
328
|
+
authToken: token,
|
|
329
|
+
characterId: 'YOUR_CHARACTER_ID',
|
|
330
|
+
enableLipsync: true,
|
|
331
|
+
audioRouting: 'data_only',
|
|
332
|
+
dataAudioBufferSeconds: 0.9, // voice + lipsync to have in hand before playing; the default
|
|
333
|
+
});
|
|
334
|
+
await client.connect();
|
|
335
|
+
|
|
336
|
+
client.on('speakingChange', (speaking) => console.log('heard:', speaking));
|
|
337
|
+
client.dataAudio?.on('paused', () => showRefilling());
|
|
338
|
+
client.dataAudio?.on('resumed', () => hideRefilling());
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
| `client.dataAudio` | Description |
|
|
342
|
+
|---|---|
|
|
343
|
+
| `state` | `'idle'`, `'buffering'`, `'playing'`, `'paused'` or `'done'` |
|
|
344
|
+
| `position()` | Seconds of the reply heard so far; holds while paused |
|
|
345
|
+
| `level()` | Loudness of the voice now playing, 0–1 |
|
|
346
|
+
| `queuedSeconds()` | Audio buffered ahead of what is heard |
|
|
347
|
+
| `getSynchronizationSources()` | The heard position in RTP form, for lipsync clocks written for WebRTC |
|
|
348
|
+
| `on(event, cb)` | `replyStarted`, `replyEnded`, `paused`, `resumed`, `underrun` |
|
|
349
|
+
|
|
350
|
+
Browsers start audio only after a user gesture; the player resumes on the page's next click, or call `client.dataAudio.resume()` from your own button. The player runs in an AudioWorklet loaded from a `blob:` URL, so a Content-Security-Policy must allow `worker-src blob:`. Available on the default LiveKit transport. Full guide: [Audio over the data channel](https://docs.convai.com/api-docs/plugins-and-integrations/web-plugins/convai-web-sdk/audio-over-the-data-channel).
|
|
351
|
+
|
|
315
352
|
## WebSocket transport
|
|
316
353
|
|
|
317
354
|
The default transport is WebRTC (LiveKit). A WebSocket-based transport is available for environments where WebRTC is unavailable or undesirable.
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Room } from "livekit-client";
|
|
2
2
|
import { ConvaiConfig, ConvaiClientState, ChatMessage, IConvaiClient, PublishedChatConnectOptions, AudioControls, CharacterMuteOptions, VideoControls, ScreenShareControls, DynamicInfo, ContextUpdateOptions, UploadFileOptions, ServerResponse, WebSocketSessionFactory, RespondModeUpdateOptions, UpdateSceneMetadataOptions, VisionStatusOptions, VisionTriggerOptions, ConnectionData, SendUserTextMessageOptions, StateOfMindInput, ConvaiCharacterInstance, ConvaiRoomSession, JoinRoomOptions, ActiveCharacterChange, CharacterRosterChange, UpdateCharacterRosterOptions, AppendMessageOptions, ConvaiEventMap, ActionResult, ActionResultAck, ActionResultAckFailureReason, ActionResultAckOptions } from "./types.js";
|
|
3
|
+
import { DataAudioPlayer } from "./DataAudioPlayer.js";
|
|
3
4
|
import { EventEmitter } from "./EventEmitter.js";
|
|
4
5
|
import { BlendshapeQueue } from "./BlendshapeQueue.js";
|
|
5
6
|
import { MemoryManager } from "./MemoryManager.js";
|
|
@@ -79,6 +80,9 @@ export declare class ConvaiClient extends EventEmitter implements IConvaiClient
|
|
|
79
80
|
* room, or a track republished by a reconnect.
|
|
80
81
|
*/
|
|
81
82
|
private _characterMuted;
|
|
83
|
+
/** Plays the voice when it arrives over the data channel (audioRouting: 'data_only'). */
|
|
84
|
+
private _dataAudio;
|
|
85
|
+
private _audioRouting;
|
|
82
86
|
/**
|
|
83
87
|
* Per-membership overrides of `_characterMuted`. A session-wide call clears
|
|
84
88
|
* this, so "mute everything" never leaves a member behind as an exception.
|
|
@@ -246,6 +250,13 @@ export declare class ConvaiClient extends EventEmitter implements IConvaiClient
|
|
|
246
250
|
private _applyCharacterMute;
|
|
247
251
|
get videoControls(): VideoControls;
|
|
248
252
|
get screenShareControls(): ScreenShareControls;
|
|
253
|
+
get dataAudio(): DataAudioPlayer | null;
|
|
254
|
+
/**
|
|
255
|
+
* Data-channel audio (audioRouting: 'data_only'): make the player and hand it
|
|
256
|
+
* the say over "speaking". Idempotent; on the WebRTC path speaking goes back
|
|
257
|
+
* to the server's flags.
|
|
258
|
+
*/
|
|
259
|
+
private _configureAudioRouting;
|
|
249
260
|
get blendshapeQueue(): BlendshapeQueue;
|
|
250
261
|
get conversationSessionId(): number;
|
|
251
262
|
get memoryManager(): MemoryManager | null;
|
|
@@ -6,6 +6,7 @@ import { secureWebSocketUrl } from "./websocketUrl.js";
|
|
|
6
6
|
import { VideoManager } from "./VideoManager.js";
|
|
7
7
|
import { ScreenShareManager } from "./ScreenShareManager.js";
|
|
8
8
|
import { MessageHandler } from "./MessageHandler.js";
|
|
9
|
+
import { DataAudioPlayer } from "./DataAudioPlayer.js";
|
|
9
10
|
import { CharacterRoster } from "./CharacterRoster.js";
|
|
10
11
|
import { buildJoinRequestBody, buildRosterConnectFields, isRosterConfig, validateJoinOptions, validateProtocolTopology, validateRosterConfig, } from "./rosterRequest.js";
|
|
11
12
|
import { ConvaiRoomError, roomErrorFromResponse } from "./ConvaiRoomError.js";
|
|
@@ -179,6 +180,9 @@ export class ConvaiClient extends EventEmitter {
|
|
|
179
180
|
* room, or a track republished by a reconnect.
|
|
180
181
|
*/
|
|
181
182
|
this._characterMuted = false;
|
|
183
|
+
/** Plays the voice when it arrives over the data channel (audioRouting: 'data_only'). */
|
|
184
|
+
this._dataAudio = null;
|
|
185
|
+
this._audioRouting = "webrtc";
|
|
182
186
|
/**
|
|
183
187
|
* Per-membership overrides of `_characterMuted`. A session-wide call clears
|
|
184
188
|
* this, so "mute everything" never leaves a member behind as an exception.
|
|
@@ -483,6 +487,8 @@ export class ConvaiClient extends EventEmitter {
|
|
|
483
487
|
// Pipecat's WebSocket transport plays the character's audio itself and
|
|
484
488
|
// exposes no track, so the session silences its own player instead.
|
|
485
489
|
this._wsSession?.setBotAudioMuted?.(this._characterMuted);
|
|
490
|
+
// Data-channel audio: the SDK's player is the character's voice; mute it there.
|
|
491
|
+
this._dataAudio?.setMuted(this._characterMuted);
|
|
486
492
|
if (this._room.state !== ConnectionState.Connected)
|
|
487
493
|
return;
|
|
488
494
|
this._room.remoteParticipants.forEach((participant) => {
|
|
@@ -499,11 +505,16 @@ export class ConvaiClient extends EventEmitter {
|
|
|
499
505
|
return;
|
|
500
506
|
membershipId = candidate;
|
|
501
507
|
}
|
|
502
|
-
|
|
508
|
+
// Data-channel audio: the voice is played from the data channel, so the
|
|
509
|
+
// WebRTC track stays silent and the server is asked to stop forwarding it.
|
|
510
|
+
const dataOnly = this._audioRouting === "data_only";
|
|
511
|
+
const muted = dataOnly || this.isCharacterMuted(membershipId);
|
|
503
512
|
participant.audioTrackPublications.forEach((publication) => {
|
|
504
513
|
const track = publication.track?.mediaStreamTrack;
|
|
505
514
|
if (track)
|
|
506
515
|
track.enabled = !muted;
|
|
516
|
+
if (dataOnly)
|
|
517
|
+
publication.setEnabled?.(false);
|
|
507
518
|
});
|
|
508
519
|
});
|
|
509
520
|
}
|
|
@@ -513,6 +524,41 @@ export class ConvaiClient extends EventEmitter {
|
|
|
513
524
|
get screenShareControls() {
|
|
514
525
|
return this._screenShareManager;
|
|
515
526
|
}
|
|
527
|
+
get dataAudio() {
|
|
528
|
+
return this._dataAudio;
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* Data-channel audio (audioRouting: 'data_only'): make the player and hand it
|
|
532
|
+
* the say over "speaking". Idempotent; on the WebRTC path speaking goes back
|
|
533
|
+
* to the server's flags.
|
|
534
|
+
*/
|
|
535
|
+
_configureAudioRouting(config) {
|
|
536
|
+
const dataOnly = config.audioRouting === "data_only";
|
|
537
|
+
this._audioRouting = dataOnly ? "data_only" : "webrtc";
|
|
538
|
+
this._messageHandler.setSpeakingFromPlayback(dataOnly);
|
|
539
|
+
if (!dataOnly || this._dataAudio)
|
|
540
|
+
return;
|
|
541
|
+
const minBuffer = config.dataAudioBufferSeconds;
|
|
542
|
+
const player = new DataAudioPlayer(minBuffer && minBuffer > 0 ? { controller: { minBuffer } } : {});
|
|
543
|
+
this._dataAudio = player;
|
|
544
|
+
player.setMuted(this._characterMuted);
|
|
545
|
+
player.on("replyStarted", () => this._messageHandler.playbackStarted());
|
|
546
|
+
player.on("replyEnded", () => this._messageHandler.playbackEnded());
|
|
547
|
+
this._messageHandler.on("playbackInterrupted", () => player.clear());
|
|
548
|
+
// The server's own flag says when it has finished SENDING the reply; the player uses it
|
|
549
|
+
// to tell a pause in delivery from the reply's end.
|
|
550
|
+
this._messageHandler.on("serverSpeakingChange", (speaking) => player.setServerSpeaking(speaking));
|
|
551
|
+
this._messageHandler.on("blendshapeStatsReceived", (data) => {
|
|
552
|
+
const ms = data?.stats?.total_audio_duration_ms;
|
|
553
|
+
if (typeof ms === "number")
|
|
554
|
+
player.setTurnTotal(ms / 1000);
|
|
555
|
+
});
|
|
556
|
+
this._messageHandler.on("blendshapes", (data) => {
|
|
557
|
+
const n = data?.blendshapes?.length ?? 0;
|
|
558
|
+
if (n)
|
|
559
|
+
player.addFrames(n / (this.blendshapeQueue.getPlaybackFps() || 60));
|
|
560
|
+
});
|
|
561
|
+
}
|
|
516
562
|
get blendshapeQueue() {
|
|
517
563
|
return this._messageHandler.getBlendshapeQueue();
|
|
518
564
|
}
|
|
@@ -623,6 +669,11 @@ export class ConvaiClient extends EventEmitter {
|
|
|
623
669
|
this._messageHandler.on("userTranscriptionChange", (transcription) => {
|
|
624
670
|
this.emit("userTranscriptionChange", transcription);
|
|
625
671
|
});
|
|
672
|
+
// Data-channel audio: the server's own speaking flags, for display or logging;
|
|
673
|
+
// speakingChange follows the player instead (audioRouting: 'data_only').
|
|
674
|
+
this._messageHandler.on("serverSpeakingChange", (isSpeaking) => {
|
|
675
|
+
this.emit("serverSpeakingChange", isSpeaking);
|
|
676
|
+
});
|
|
626
677
|
this._messageHandler.on("speakingChange", (isSpeaking) => {
|
|
627
678
|
this.updateState({ isSpeaking });
|
|
628
679
|
this.emit("speakingChange", isSpeaking);
|
|
@@ -742,6 +793,7 @@ export class ConvaiClient extends EventEmitter {
|
|
|
742
793
|
this.emit("botTtsStopped");
|
|
743
794
|
});
|
|
744
795
|
this._messageHandler.on("audioData", (data, request) => {
|
|
796
|
+
this._dataAudio?.pushChunk(data);
|
|
745
797
|
this.emit("audioData", data, request);
|
|
746
798
|
});
|
|
747
799
|
// Forward server-side muting events
|
|
@@ -923,6 +975,7 @@ export class ConvaiClient extends EventEmitter {
|
|
|
923
975
|
// Store config for reconnection
|
|
924
976
|
this._storedConfig = { ...finalConfig };
|
|
925
977
|
this._isPublishedChatSession = false;
|
|
978
|
+
this._configureAudioRouting(finalConfig);
|
|
926
979
|
// Use characterSessionId from config when reconnecting (so we resume the same session)
|
|
927
980
|
if (finalConfig.characterSessionId &&
|
|
928
981
|
finalConfig.characterSessionId !== "-1") {
|
|
@@ -1054,6 +1107,10 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1054
1107
|
emotion_config: buildEmotionConnectConfig(configWithDefaults),
|
|
1055
1108
|
}),
|
|
1056
1109
|
default_tts_enabled: this._latestTtsEnabled(configWithDefaults) ?? true,
|
|
1110
|
+
// Data-channel audio: the voice comes as PCM chunks next to the lipsync, played by the SDK.
|
|
1111
|
+
...(configWithDefaults.audioRouting === "data_only" && {
|
|
1112
|
+
audio_config: { output: { audio_routing: "data_only" } },
|
|
1113
|
+
}),
|
|
1057
1114
|
default_stt_enabled: true,
|
|
1058
1115
|
...(effectiveVisionInputConfig && {
|
|
1059
1116
|
vision_input_config: serializeVisionInputConfig(effectiveVisionInputConfig),
|
|
@@ -2235,6 +2292,7 @@ export class ConvaiClient extends EventEmitter {
|
|
|
2235
2292
|
* Clear all manager states
|
|
2236
2293
|
*/
|
|
2237
2294
|
clearAllManagers() {
|
|
2295
|
+
this._dataAudio?.clear();
|
|
2238
2296
|
this._connectionType = null;
|
|
2239
2297
|
this._activeTransport = null;
|
|
2240
2298
|
this._wsSession = null;
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plays a character's voice delivered over the data channel
|
|
3
|
+
* (`audioRouting: 'data_only'`): `audio-data` chunks of 16-bit PCM go into ONE
|
|
4
|
+
* continuous ring buffer played by an AudioWorklet (the web counterpart of the
|
|
5
|
+
* Unreal plugin's USoundWaveProcedural), so chunks join with no seams.
|
|
6
|
+
*
|
|
7
|
+
* A {@link StreamController} decides when each reply starts, pauses and resumes;
|
|
8
|
+
* a pause is placed on the last silent stretch already buffered, never mid-word.
|
|
9
|
+
* The player is the source of truth for "the bot is speaking" on this path: the
|
|
10
|
+
* server's speaking flags follow when it SENT the audio, which is seconds before
|
|
11
|
+
* a buffered reply is heard.
|
|
12
|
+
*
|
|
13
|
+
* Embody-style consumers clock lipsync from {@link DataAudioPlayer.getSynchronizationSources},
|
|
14
|
+
* which mirrors an RTCRtpReceiver's: the reply's heard position in 48 kHz RTP units.
|
|
15
|
+
*/
|
|
16
|
+
import { EventEmitter } from "./EventEmitter.js";
|
|
17
|
+
import { StreamController, type StreamControllerOptions, type StreamState } from "./streamController.js";
|
|
18
|
+
import type { AudioDataEvent, DataAudioPlayback } from "./types.js";
|
|
19
|
+
/** Where the samples go. The default is an AudioWorklet ring buffer; tests use a fake. */
|
|
20
|
+
export interface DataAudioSink {
|
|
21
|
+
readonly sampleRate: number;
|
|
22
|
+
/** Append samples to the stream. */
|
|
23
|
+
push(samples: Float32Array): void;
|
|
24
|
+
/** Start (or resume) consuming the stream. */
|
|
25
|
+
play(): void;
|
|
26
|
+
/** Stop consuming when the read position reaches `index` (immediately if already past it). */
|
|
27
|
+
pauseAt(index: number): void;
|
|
28
|
+
/** Drop everything not yet played. */
|
|
29
|
+
clear(): void;
|
|
30
|
+
setMuted(muted: boolean): void;
|
|
31
|
+
/** RMS of what is being played, 0–1; null before audio can be read. */
|
|
32
|
+
level(): number | null;
|
|
33
|
+
/** Seconds between a sample being consumed and being heard. */
|
|
34
|
+
outputLatency(): number;
|
|
35
|
+
/** The sink reports its read position (absolute sample index) and whether it is playing. */
|
|
36
|
+
onReport(cb: (read: number, playing: boolean) => void): void;
|
|
37
|
+
/** The sink ran out while playing. */
|
|
38
|
+
onUnderrun(cb: (read: number) => void): void;
|
|
39
|
+
resume(): Promise<void>;
|
|
40
|
+
dispose(): void;
|
|
41
|
+
}
|
|
42
|
+
export interface DataAudioPlayerOptions {
|
|
43
|
+
controller?: Partial<StreamControllerOptions>;
|
|
44
|
+
/** Build the sink for a sample rate. Default: an AudioWorklet ring buffer. */
|
|
45
|
+
createSink?: (sampleRate: number) => Promise<DataAudioSink>;
|
|
46
|
+
/** Wall clock in seconds. */
|
|
47
|
+
now?: () => number;
|
|
48
|
+
/**
|
|
49
|
+
* With no word from the server on whether it is still sending: a reply with no
|
|
50
|
+
* new audio for this long, s, is treated as fully arrived. Default 1.5.
|
|
51
|
+
*/
|
|
52
|
+
idleEnd?: number;
|
|
53
|
+
/**
|
|
54
|
+
* While the server says it is still sending, a gap in delivery is a slow link,
|
|
55
|
+
* not the end of the reply; only a gap this long, s, ends it. Default 10.
|
|
56
|
+
*/
|
|
57
|
+
stallEnd?: number;
|
|
58
|
+
}
|
|
59
|
+
export interface DataAudioStats {
|
|
60
|
+
chunks: number;
|
|
61
|
+
pauses: number;
|
|
62
|
+
underruns: number;
|
|
63
|
+
}
|
|
64
|
+
/** Decode a base64 16-bit little-endian PCM chunk to mono Float32. */
|
|
65
|
+
export declare function decodePcm16(base64: string, channels: number): Float32Array;
|
|
66
|
+
export declare class DataAudioPlayer extends EventEmitter implements DataAudioPlayback {
|
|
67
|
+
readonly controller: StreamController;
|
|
68
|
+
readonly stats: DataAudioStats;
|
|
69
|
+
private readonly makeSink;
|
|
70
|
+
private readonly now;
|
|
71
|
+
private readonly idleEnd;
|
|
72
|
+
private readonly stallEnd;
|
|
73
|
+
/** The server's speaking flag: true sending, false done sending, null never heard. */
|
|
74
|
+
private serverSending;
|
|
75
|
+
private sink;
|
|
76
|
+
private sinkPromise;
|
|
77
|
+
private pending;
|
|
78
|
+
private muted;
|
|
79
|
+
private read;
|
|
80
|
+
private readAt;
|
|
81
|
+
private playing;
|
|
82
|
+
private written;
|
|
83
|
+
private replyStart;
|
|
84
|
+
private replyPcm;
|
|
85
|
+
private announced;
|
|
86
|
+
private lastChunkAt;
|
|
87
|
+
private heardStarted;
|
|
88
|
+
private endedAt;
|
|
89
|
+
private rtpBase;
|
|
90
|
+
private timer;
|
|
91
|
+
constructor(options?: DataAudioPlayerOptions);
|
|
92
|
+
/** Where playback is in the open reply's lifecycle. */
|
|
93
|
+
get state(): StreamState;
|
|
94
|
+
/** Queue an audio-data chunk. */
|
|
95
|
+
pushChunk(chunk: AudioDataEvent): void;
|
|
96
|
+
/** The turn announced the reply's audio length (blendshape-turn-stats). */
|
|
97
|
+
setTurnTotal(seconds: number): void;
|
|
98
|
+
/** The server's own speaking flag: true while it is still sending this reply. */
|
|
99
|
+
setServerSpeaking(speaking: boolean): void;
|
|
100
|
+
/** Lipsync seconds that arrived for the open reply. */
|
|
101
|
+
addFrames(seconds: number): void;
|
|
102
|
+
/** Drop everything (an interruption). */
|
|
103
|
+
clear(): void;
|
|
104
|
+
setMuted(muted: boolean): void;
|
|
105
|
+
/** Resume the audio context (call from a user gesture if the page blocks autoplay). */
|
|
106
|
+
resume(): Promise<void>;
|
|
107
|
+
/** Seconds of the open reply heard so far; null before it starts. Holds through a pause, runs on 3 s past the end. */
|
|
108
|
+
position(): number | null;
|
|
109
|
+
/** RMS of the voice now playing; null when nothing can be read. */
|
|
110
|
+
level(): number | null;
|
|
111
|
+
/** Seconds buffered ahead of what is heard. */
|
|
112
|
+
queuedSeconds(): number;
|
|
113
|
+
/** RTCRtpReceiver-shaped clock: the open reply's heard position in 48 kHz RTP units. */
|
|
114
|
+
getSynchronizationSources(): Array<{
|
|
115
|
+
rtpTimestamp: number;
|
|
116
|
+
timestamp: number;
|
|
117
|
+
audioLevel?: number;
|
|
118
|
+
}>;
|
|
119
|
+
dispose(): void;
|
|
120
|
+
private ensureSink;
|
|
121
|
+
private flushPending;
|
|
122
|
+
private beginReply;
|
|
123
|
+
private checkEnded;
|
|
124
|
+
private heardIndex;
|
|
125
|
+
private replyPlayed;
|
|
126
|
+
private tick;
|
|
127
|
+
/** The last silent window in the buffered audio between two sample indices; null if none. */
|
|
128
|
+
private lastSilence;
|
|
129
|
+
}
|
|
130
|
+
/** An AudioWorklet ring buffer at the stream's own sample rate (no per-chunk resampling). */
|
|
131
|
+
export declare function createWorkletSink(sampleRate: number): Promise<DataAudioSink>;
|
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plays a character's voice delivered over the data channel
|
|
3
|
+
* (`audioRouting: 'data_only'`): `audio-data` chunks of 16-bit PCM go into ONE
|
|
4
|
+
* continuous ring buffer played by an AudioWorklet (the web counterpart of the
|
|
5
|
+
* Unreal plugin's USoundWaveProcedural), so chunks join with no seams.
|
|
6
|
+
*
|
|
7
|
+
* A {@link StreamController} decides when each reply starts, pauses and resumes;
|
|
8
|
+
* a pause is placed on the last silent stretch already buffered, never mid-word.
|
|
9
|
+
* The player is the source of truth for "the bot is speaking" on this path: the
|
|
10
|
+
* server's speaking flags follow when it SENT the audio, which is seconds before
|
|
11
|
+
* a buffered reply is heard.
|
|
12
|
+
*
|
|
13
|
+
* Embody-style consumers clock lipsync from {@link DataAudioPlayer.getSynchronizationSources},
|
|
14
|
+
* which mirrors an RTCRtpReceiver's: the reply's heard position in 48 kHz RTP units.
|
|
15
|
+
*/
|
|
16
|
+
import { EventEmitter } from "./EventEmitter.js";
|
|
17
|
+
import { StreamController } from "./streamController.js";
|
|
18
|
+
const RTP_RATE = 48000;
|
|
19
|
+
const SILENCE_RMS = 0.008;
|
|
20
|
+
const SILENCE_WINDOW = 0.03;
|
|
21
|
+
/** Decode a base64 16-bit little-endian PCM chunk to mono Float32. */
|
|
22
|
+
export function decodePcm16(base64, channels) {
|
|
23
|
+
const bin = atob(base64);
|
|
24
|
+
const frames = Math.floor(bin.length / 2 / Math.max(1, channels));
|
|
25
|
+
const out = new Float32Array(frames);
|
|
26
|
+
for (let i = 0; i < frames; i++) {
|
|
27
|
+
let sum = 0;
|
|
28
|
+
for (let c = 0; c < channels; c++) {
|
|
29
|
+
const k = 2 * (i * channels + c);
|
|
30
|
+
let v = bin.charCodeAt(k) | (bin.charCodeAt(k + 1) << 8);
|
|
31
|
+
if (v >= 32768)
|
|
32
|
+
v -= 65536;
|
|
33
|
+
sum += v / 32768;
|
|
34
|
+
}
|
|
35
|
+
out[i] = sum / Math.max(1, channels);
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
export class DataAudioPlayer extends EventEmitter {
|
|
40
|
+
constructor(options = {}) {
|
|
41
|
+
super();
|
|
42
|
+
this.stats = { chunks: 0, pauses: 0, underruns: 0 };
|
|
43
|
+
/** The server's speaking flag: true sending, false done sending, null never heard. */
|
|
44
|
+
this.serverSending = null;
|
|
45
|
+
this.sink = null;
|
|
46
|
+
this.sinkPromise = null;
|
|
47
|
+
this.pending = [];
|
|
48
|
+
this.muted = false;
|
|
49
|
+
this.read = 0; // last reported read index
|
|
50
|
+
this.readAt = 0; // wall s of that report
|
|
51
|
+
this.playing = false;
|
|
52
|
+
this.written = 0; // samples pushed in total
|
|
53
|
+
this.replyStart = 0; // sample index where the open reply begins
|
|
54
|
+
this.replyPcm = [];
|
|
55
|
+
this.announced = null;
|
|
56
|
+
this.lastChunkAt = 0;
|
|
57
|
+
this.heardStarted = false;
|
|
58
|
+
this.endedAt = null;
|
|
59
|
+
this.rtpBase = 0;
|
|
60
|
+
this.timer = null;
|
|
61
|
+
this.controller = new StreamController(options.controller);
|
|
62
|
+
this.makeSink = options.createSink ?? createWorkletSink;
|
|
63
|
+
this.now = options.now ?? (() => performance.now() / 1000);
|
|
64
|
+
this.idleEnd = options.idleEnd ?? 1.5;
|
|
65
|
+
this.stallEnd = options.stallEnd ?? 10;
|
|
66
|
+
}
|
|
67
|
+
/** Where playback is in the open reply's lifecycle. */
|
|
68
|
+
get state() {
|
|
69
|
+
return this.controller.state;
|
|
70
|
+
}
|
|
71
|
+
/** Queue an audio-data chunk. */
|
|
72
|
+
pushChunk(chunk) {
|
|
73
|
+
if (chunk.includes_wav_header)
|
|
74
|
+
return; // the data channel sends raw PCM; a WAV file is not a stream chunk
|
|
75
|
+
this.pending.push(chunk);
|
|
76
|
+
void this.ensureSink(chunk.sample_rate).then(() => this.flushPending());
|
|
77
|
+
}
|
|
78
|
+
/** The turn announced the reply's audio length (blendshape-turn-stats). */
|
|
79
|
+
setTurnTotal(seconds) {
|
|
80
|
+
if (!(seconds > 0))
|
|
81
|
+
return;
|
|
82
|
+
this.announced = seconds;
|
|
83
|
+
this.controller.onTotal(seconds);
|
|
84
|
+
this.checkEnded();
|
|
85
|
+
}
|
|
86
|
+
/** The server's own speaking flag: true while it is still sending this reply. */
|
|
87
|
+
setServerSpeaking(speaking) {
|
|
88
|
+
this.serverSending = speaking;
|
|
89
|
+
}
|
|
90
|
+
/** Lipsync seconds that arrived for the open reply. */
|
|
91
|
+
addFrames(seconds) {
|
|
92
|
+
this.controller.onFrames(seconds);
|
|
93
|
+
}
|
|
94
|
+
/** Drop everything (an interruption). */
|
|
95
|
+
clear() {
|
|
96
|
+
this.pending = [];
|
|
97
|
+
this.sink?.clear();
|
|
98
|
+
this.read = this.written;
|
|
99
|
+
this.playing = false;
|
|
100
|
+
const wasActive = this.heardStarted && this.endedAt == null;
|
|
101
|
+
this.controller.reset();
|
|
102
|
+
this.replyPcm = [];
|
|
103
|
+
this.announced = null;
|
|
104
|
+
this.heardStarted = false;
|
|
105
|
+
this.endedAt = null;
|
|
106
|
+
if (wasActive)
|
|
107
|
+
this.emit("replyEnded", { interrupted: true });
|
|
108
|
+
}
|
|
109
|
+
setMuted(muted) {
|
|
110
|
+
this.muted = muted;
|
|
111
|
+
this.sink?.setMuted(muted);
|
|
112
|
+
}
|
|
113
|
+
/** Resume the audio context (call from a user gesture if the page blocks autoplay). */
|
|
114
|
+
async resume() {
|
|
115
|
+
await this.sink?.resume();
|
|
116
|
+
}
|
|
117
|
+
/** Seconds of the open reply heard so far; null before it starts. Holds through a pause, runs on 3 s past the end. */
|
|
118
|
+
position() {
|
|
119
|
+
const st = this.controller.state;
|
|
120
|
+
if (!this.sink || st === "idle" || st === "buffering")
|
|
121
|
+
return null;
|
|
122
|
+
if (this.endedAt != null) {
|
|
123
|
+
const extra = this.now() - this.endedAt;
|
|
124
|
+
return extra < 3 ? this.controller.snapshot.audio + extra : null;
|
|
125
|
+
}
|
|
126
|
+
return this.replyPlayed();
|
|
127
|
+
}
|
|
128
|
+
/** RMS of the voice now playing; null when nothing can be read. */
|
|
129
|
+
level() {
|
|
130
|
+
return this.sink?.level() ?? null;
|
|
131
|
+
}
|
|
132
|
+
/** Seconds buffered ahead of what is heard. */
|
|
133
|
+
queuedSeconds() {
|
|
134
|
+
if (!this.sink)
|
|
135
|
+
return 0;
|
|
136
|
+
return Math.max(0, (this.written - this.heardIndex()) / this.sink.sampleRate);
|
|
137
|
+
}
|
|
138
|
+
/** RTCRtpReceiver-shaped clock: the open reply's heard position in 48 kHz RTP units. */
|
|
139
|
+
getSynchronizationSources() {
|
|
140
|
+
const p = this.position();
|
|
141
|
+
if (p == null)
|
|
142
|
+
return [];
|
|
143
|
+
return [{ rtpTimestamp: this.rtpBase + p * RTP_RATE, timestamp: Date.now(), audioLevel: this.level() ?? 0 }];
|
|
144
|
+
}
|
|
145
|
+
dispose() {
|
|
146
|
+
if (this.timer)
|
|
147
|
+
clearInterval(this.timer);
|
|
148
|
+
this.timer = null;
|
|
149
|
+
this.sink?.dispose();
|
|
150
|
+
this.sink = null;
|
|
151
|
+
this.sinkPromise = null;
|
|
152
|
+
}
|
|
153
|
+
// ── internals ─────────────────────────────────────────────────────────────
|
|
154
|
+
ensureSink(rate) {
|
|
155
|
+
this.sinkPromise ?? (this.sinkPromise = this.makeSink(rate).then((sink) => {
|
|
156
|
+
this.sink = sink;
|
|
157
|
+
sink.setMuted(this.muted);
|
|
158
|
+
sink.onReport((read, playing) => {
|
|
159
|
+
this.read = read;
|
|
160
|
+
this.readAt = this.now();
|
|
161
|
+
this.playing = playing;
|
|
162
|
+
});
|
|
163
|
+
sink.onUnderrun((read) => {
|
|
164
|
+
// Running out at the true end of a reply is not a stutter.
|
|
165
|
+
const atEnd = this.controller.snapshot.ended && this.written - read < 0.05 * sink.sampleRate;
|
|
166
|
+
if (!atEnd) {
|
|
167
|
+
this.stats.underruns++;
|
|
168
|
+
this.emit("underrun", { read });
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
this.timer ?? (this.timer = setInterval(() => this.tick(), 20));
|
|
172
|
+
return sink;
|
|
173
|
+
}));
|
|
174
|
+
return this.sinkPromise;
|
|
175
|
+
}
|
|
176
|
+
flushPending() {
|
|
177
|
+
const sink = this.sink;
|
|
178
|
+
if (!sink)
|
|
179
|
+
return;
|
|
180
|
+
while (this.pending.length) {
|
|
181
|
+
const chunk = this.pending.shift();
|
|
182
|
+
let samples = decodePcm16(chunk.audio, chunk.channels);
|
|
183
|
+
if (chunk.sample_rate !== sink.sampleRate)
|
|
184
|
+
samples = resampleLinear(samples, chunk.sample_rate, sink.sampleRate);
|
|
185
|
+
const st = this.controller.state;
|
|
186
|
+
if (st === "idle" || st === "done")
|
|
187
|
+
this.beginReply();
|
|
188
|
+
this.replyPcm.push([this.written, samples]);
|
|
189
|
+
sink.push(samples);
|
|
190
|
+
this.written += samples.length;
|
|
191
|
+
this.lastChunkAt = this.now();
|
|
192
|
+
this.controller.onAudio(this.now(), samples.length / sink.sampleRate);
|
|
193
|
+
this.stats.chunks++;
|
|
194
|
+
this.checkEnded();
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
beginReply() {
|
|
198
|
+
this.replyStart = this.written;
|
|
199
|
+
this.replyPcm = [];
|
|
200
|
+
this.announced = null;
|
|
201
|
+
this.heardStarted = false;
|
|
202
|
+
this.endedAt = null;
|
|
203
|
+
// A "stopped" left over from the last reply says nothing about this one.
|
|
204
|
+
if (this.serverSending === false)
|
|
205
|
+
this.serverSending = null;
|
|
206
|
+
this.rtpBase += 10 * RTP_RATE; // a jump the RTP clock reads as a new talk spurt
|
|
207
|
+
}
|
|
208
|
+
checkEnded() {
|
|
209
|
+
const s = this.controller.snapshot;
|
|
210
|
+
if (s.ended || s.state === "idle")
|
|
211
|
+
return;
|
|
212
|
+
if (this.announced != null && s.audio >= this.announced - 0.02)
|
|
213
|
+
this.controller.onEnded();
|
|
214
|
+
}
|
|
215
|
+
heardIndex() {
|
|
216
|
+
const sink = this.sink;
|
|
217
|
+
const est = this.playing ? this.read + (this.now() - this.readAt) * sink.sampleRate : this.read;
|
|
218
|
+
return Math.min(est, this.written) - (this.playing ? sink.outputLatency() * sink.sampleRate : 0);
|
|
219
|
+
}
|
|
220
|
+
replyPlayed() {
|
|
221
|
+
return Math.max(0, (this.heardIndex() - this.replyStart) / this.sink.sampleRate);
|
|
222
|
+
}
|
|
223
|
+
tick() {
|
|
224
|
+
const sink = this.sink;
|
|
225
|
+
if (!sink)
|
|
226
|
+
return;
|
|
227
|
+
const t = this.now();
|
|
228
|
+
const s = this.controller.snapshot;
|
|
229
|
+
// Has the reply fully arrived? The server's stop follows its last chunk on the same
|
|
230
|
+
// channel, so once it has stopped nothing more is coming. While it is still sending,
|
|
231
|
+
// a gap is a slow link: ending on it would play a fragment as the whole reply.
|
|
232
|
+
const quiet = t - this.lastChunkAt;
|
|
233
|
+
const endAfter = this.serverSending === false ? 0.25 : this.serverSending ? this.stallEnd : this.idleEnd;
|
|
234
|
+
if (!s.ended && s.state !== "idle" && s.state !== "done" && quiet > endAfter)
|
|
235
|
+
this.controller.onEnded();
|
|
236
|
+
// The sink has played everything this reply had: it is over, whatever the latency estimate says.
|
|
237
|
+
if (s.ended && s.state === "playing" && this.read >= this.written)
|
|
238
|
+
this.controller.finish();
|
|
239
|
+
const syncedEnd = () => Math.min(this.written, this.replyStart + Math.floor(this.controller.synced * sink.sampleRate));
|
|
240
|
+
const searchFrom = () => Math.ceil(this.heardIndex() + 0.05 * sink.sampleRate);
|
|
241
|
+
const silenceAhead = () => this.lastSilence(searchFrom(), syncedEnd() - Math.round(0.02 * sink.sampleRate)) != null;
|
|
242
|
+
const cmd = this.controller.tick(t, this.replyPlayed(), silenceAhead);
|
|
243
|
+
if (cmd === "play") {
|
|
244
|
+
sink.play();
|
|
245
|
+
this.playing = true;
|
|
246
|
+
this.readAt = t;
|
|
247
|
+
if (this.controller.snapshot.pauses > 0)
|
|
248
|
+
this.emit("resumed", {});
|
|
249
|
+
}
|
|
250
|
+
else if (cmd === "pause") {
|
|
251
|
+
this.stats.pauses++;
|
|
252
|
+
// Only synced audio (blendshapes in hand) may play: stop at its end, or at the last
|
|
253
|
+
// silence before it.
|
|
254
|
+
const end = syncedEnd();
|
|
255
|
+
const at = this.lastSilence(searchFrom(), end - Math.round(0.02 * sink.sampleRate));
|
|
256
|
+
sink.pauseAt(at ?? end);
|
|
257
|
+
this.emit("paused", { atSilence: at != null });
|
|
258
|
+
}
|
|
259
|
+
if (!this.heardStarted && (this.state === "playing" || this.state === "paused") && this.replyPlayed() > 0) {
|
|
260
|
+
this.heardStarted = true;
|
|
261
|
+
this.emit("replyStarted", {});
|
|
262
|
+
}
|
|
263
|
+
if (this.state === "done" && this.endedAt == null) {
|
|
264
|
+
this.endedAt = t;
|
|
265
|
+
if (this.heardStarted)
|
|
266
|
+
this.emit("replyEnded", { interrupted: false });
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
/** The last silent window in the buffered audio between two sample indices; null if none. */
|
|
270
|
+
lastSilence(from, to) {
|
|
271
|
+
const rate = this.sink.sampleRate;
|
|
272
|
+
const win = Math.max(1, Math.round(SILENCE_WINDOW * rate));
|
|
273
|
+
let best = null;
|
|
274
|
+
for (const [start, f] of this.replyPcm) {
|
|
275
|
+
for (let i = 0; i + win <= f.length; i += win >> 1) {
|
|
276
|
+
const at = start + i;
|
|
277
|
+
if (at < from || at + win > to)
|
|
278
|
+
continue;
|
|
279
|
+
let sum = 0;
|
|
280
|
+
for (let k = 0; k < win; k++)
|
|
281
|
+
sum += f[i + k] * f[i + k];
|
|
282
|
+
if (Math.sqrt(sum / win) < SILENCE_RMS)
|
|
283
|
+
best = at + (win >> 1);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return best;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
function resampleLinear(input, from, to) {
|
|
290
|
+
const n = Math.max(1, Math.round((input.length * to) / from));
|
|
291
|
+
const out = new Float32Array(n);
|
|
292
|
+
for (let i = 0; i < n; i++) {
|
|
293
|
+
const x = (i * from) / to;
|
|
294
|
+
const a = Math.floor(x);
|
|
295
|
+
const b = Math.min(a + 1, input.length - 1);
|
|
296
|
+
out[i] = input[a] + (input[b] - input[a]) * (x - a);
|
|
297
|
+
}
|
|
298
|
+
return out;
|
|
299
|
+
}
|
|
300
|
+
// ── The default sink: an AudioWorklet ring buffer ─────────────────────────────
|
|
301
|
+
const RING_SECONDS = 180;
|
|
302
|
+
function workletSource(capacity) {
|
|
303
|
+
return `
|
|
304
|
+
class ConvaiDataAudioRing extends AudioWorkletProcessor {
|
|
305
|
+
constructor() {
|
|
306
|
+
super()
|
|
307
|
+
this.L = ${capacity}; this.buf = new Float32Array(this.L); this.w = 0; this.r = 0
|
|
308
|
+
this.playing = false; this.pauseAt = -1; this.n = 0; this.under = false
|
|
309
|
+
this.port.onmessage = (e) => {
|
|
310
|
+
const m = e.data
|
|
311
|
+
if (m.cmd === 'push') { const s = m.samples; for (let i = 0; i < s.length; i++) this.buf[(this.w + i) % this.L] = s[i]; this.w += s.length }
|
|
312
|
+
else if (m.cmd === 'play') { this.playing = true; this.pauseAt = -1; this.under = false }
|
|
313
|
+
else if (m.cmd === 'pauseAt') { this.pauseAt = Math.max(this.r, m.at) }
|
|
314
|
+
else if (m.cmd === 'clear') { this.r = this.w; this.playing = false; this.pauseAt = -1 }
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
process(_inputs, outputs) {
|
|
318
|
+
const out = outputs[0][0]
|
|
319
|
+
for (let i = 0; i < out.length; i++) {
|
|
320
|
+
if (this.playing && this.pauseAt >= 0 && this.r >= this.pauseAt) { this.playing = false; this.pauseAt = -1 }
|
|
321
|
+
if (this.playing && this.r < this.w) { out[i] = this.buf[this.r % this.L]; this.r++ }
|
|
322
|
+
else { out[i] = 0; if (this.playing && !this.under) { this.under = true; this.port.postMessage({ ev: 'underrun', r: this.r }) } }
|
|
323
|
+
}
|
|
324
|
+
if (++this.n % 4 === 0) this.port.postMessage({ ev: 'pos', r: this.r, playing: this.playing })
|
|
325
|
+
return true
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
registerProcessor('convai-data-audio-ring', ConvaiDataAudioRing)`;
|
|
329
|
+
}
|
|
330
|
+
const GESTURES = ["pointerdown", "keydown", "touchstart"];
|
|
331
|
+
/** An AudioWorklet ring buffer at the stream's own sample rate (no per-chunk resampling). */
|
|
332
|
+
export async function createWorkletSink(sampleRate) {
|
|
333
|
+
const ctx = new AudioContext({ sampleRate });
|
|
334
|
+
const url = URL.createObjectURL(new Blob([workletSource(sampleRate * RING_SECONDS)], { type: "text/javascript" }));
|
|
335
|
+
try {
|
|
336
|
+
await ctx.audioWorklet.addModule(url);
|
|
337
|
+
}
|
|
338
|
+
finally {
|
|
339
|
+
URL.revokeObjectURL(url);
|
|
340
|
+
}
|
|
341
|
+
const node = new AudioWorkletNode(ctx, "convai-data-audio-ring", { numberOfOutputs: 1, outputChannelCount: [1] });
|
|
342
|
+
const gain = ctx.createGain();
|
|
343
|
+
const analyser = ctx.createAnalyser();
|
|
344
|
+
analyser.fftSize = 512;
|
|
345
|
+
node.connect(gain);
|
|
346
|
+
gain.connect(analyser);
|
|
347
|
+
analyser.connect(ctx.destination);
|
|
348
|
+
const abuf = new Float32Array(analyser.fftSize);
|
|
349
|
+
let report = () => { };
|
|
350
|
+
let underrun = () => { };
|
|
351
|
+
node.port.onmessage = (e) => {
|
|
352
|
+
const m = e.data;
|
|
353
|
+
if (m.ev === "pos")
|
|
354
|
+
report(m.r, m.playing);
|
|
355
|
+
else if (m.ev === "underrun")
|
|
356
|
+
underrun(m.r);
|
|
357
|
+
};
|
|
358
|
+
// Autoplay policy: a context made before a gesture starts suspended.
|
|
359
|
+
const unlock = () => { void ctx.resume(); };
|
|
360
|
+
if (typeof document !== "undefined")
|
|
361
|
+
for (const g of GESTURES)
|
|
362
|
+
document.addEventListener(g, unlock, { capture: true, passive: true });
|
|
363
|
+
if (ctx.state !== "running")
|
|
364
|
+
void ctx.resume().catch(() => { });
|
|
365
|
+
return {
|
|
366
|
+
sampleRate: ctx.sampleRate,
|
|
367
|
+
push: (samples) => {
|
|
368
|
+
if (ctx.state !== "running")
|
|
369
|
+
void ctx.resume().catch(() => { });
|
|
370
|
+
node.port.postMessage({ cmd: "push", samples });
|
|
371
|
+
},
|
|
372
|
+
play: () => node.port.postMessage({ cmd: "play" }),
|
|
373
|
+
pauseAt: (index) => node.port.postMessage({ cmd: "pauseAt", at: index }),
|
|
374
|
+
clear: () => node.port.postMessage({ cmd: "clear" }),
|
|
375
|
+
setMuted: (muted) => { gain.gain.value = muted ? 0 : 1; },
|
|
376
|
+
level: () => {
|
|
377
|
+
if (ctx.state !== "running")
|
|
378
|
+
return null;
|
|
379
|
+
analyser.getFloatTimeDomainData(abuf);
|
|
380
|
+
let s = 0;
|
|
381
|
+
for (let i = 0; i < abuf.length; i++)
|
|
382
|
+
s += abuf[i] * abuf[i];
|
|
383
|
+
return Math.sqrt(s / abuf.length);
|
|
384
|
+
},
|
|
385
|
+
outputLatency: () => ctx.outputLatency || ctx.baseLatency || 0,
|
|
386
|
+
onReport: (cb) => { report = cb; },
|
|
387
|
+
onUnderrun: (cb) => { underrun = cb; },
|
|
388
|
+
resume: () => ctx.resume(),
|
|
389
|
+
dispose: () => {
|
|
390
|
+
if (typeof document !== "undefined")
|
|
391
|
+
for (const g of GESTURES)
|
|
392
|
+
document.removeEventListener(g, unlock, { capture: true });
|
|
393
|
+
node.disconnect();
|
|
394
|
+
void ctx.close().catch(() => { });
|
|
395
|
+
},
|
|
396
|
+
};
|
|
397
|
+
}
|
|
@@ -15,6 +15,8 @@ export declare class MessageHandler extends EventEmitter {
|
|
|
15
15
|
private isBotResponding;
|
|
16
16
|
private isSpeaking;
|
|
17
17
|
private isListening;
|
|
18
|
+
/** Data-channel audio: speaking follows the client's player, not the server's flags. */
|
|
19
|
+
private speakingFromPlayback;
|
|
18
20
|
private totalBlendshapesReceived;
|
|
19
21
|
private blendshapeQueue;
|
|
20
22
|
private _currentEmotion;
|
|
@@ -68,6 +70,17 @@ export declare class MessageHandler extends EventEmitter {
|
|
|
68
70
|
* next bot-started-speaking can activate cleanly.
|
|
69
71
|
*/
|
|
70
72
|
interruptLipsyncPlayback(): void;
|
|
73
|
+
/**
|
|
74
|
+
* Data-channel audio (`audioRouting: 'data_only'`): the client's player, not
|
|
75
|
+
* the server's bot-started/stopped-speaking, says when the bot is speaking.
|
|
76
|
+
* Those flags follow when the server SENT the audio; a buffered reply is
|
|
77
|
+
* heard seconds later, and a stop flag ended lipsync mid-sentence.
|
|
78
|
+
*/
|
|
79
|
+
setSpeakingFromPlayback(enabled: boolean): void;
|
|
80
|
+
/** The player started hearing a reply (data-channel audio). */
|
|
81
|
+
playbackStarted(): void;
|
|
82
|
+
/** The player finished a reply (data-channel audio). */
|
|
83
|
+
playbackEnded(): void;
|
|
71
84
|
/**
|
|
72
85
|
* Finalize local response state after the client intentionally aborts a
|
|
73
86
|
* transport before the server can deliver its terminal response frame.
|
|
@@ -35,6 +35,8 @@ export class MessageHandler extends EventEmitter {
|
|
|
35
35
|
this.isBotResponding = false;
|
|
36
36
|
this.isSpeaking = false;
|
|
37
37
|
this.isListening = false;
|
|
38
|
+
/** Data-channel audio: speaking follows the client's player, not the server's flags. */
|
|
39
|
+
this.speakingFromPlayback = false;
|
|
38
40
|
this.totalBlendshapesReceived = 0;
|
|
39
41
|
this._currentEmotion = null;
|
|
40
42
|
this.modelOutputVersion = 1;
|
|
@@ -114,10 +116,38 @@ export class MessageHandler extends EventEmitter {
|
|
|
114
116
|
const wasSpeaking = this.isSpeaking;
|
|
115
117
|
this.isSpeaking = false;
|
|
116
118
|
this.blendshapeQueue.interrupt();
|
|
119
|
+
this.emit("playbackInterrupted");
|
|
117
120
|
if (wasSpeaking) {
|
|
118
121
|
this.emit("speakingChange", false);
|
|
119
122
|
}
|
|
120
123
|
}
|
|
124
|
+
/**
|
|
125
|
+
* Data-channel audio (`audioRouting: 'data_only'`): the client's player, not
|
|
126
|
+
* the server's bot-started/stopped-speaking, says when the bot is speaking.
|
|
127
|
+
* Those flags follow when the server SENT the audio; a buffered reply is
|
|
128
|
+
* heard seconds later, and a stop flag ended lipsync mid-sentence.
|
|
129
|
+
*/
|
|
130
|
+
setSpeakingFromPlayback(enabled) {
|
|
131
|
+
this.speakingFromPlayback = enabled;
|
|
132
|
+
}
|
|
133
|
+
/** The player started hearing a reply (data-channel audio). */
|
|
134
|
+
playbackStarted() {
|
|
135
|
+
if (this.isSpeaking)
|
|
136
|
+
return;
|
|
137
|
+
const allowed = this.blendshapeQueue.startBotSpeaking();
|
|
138
|
+
if (allowed) {
|
|
139
|
+
this.isSpeaking = true;
|
|
140
|
+
this.emit("speakingChange", true);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** The player finished a reply (data-channel audio). */
|
|
144
|
+
playbackEnded() {
|
|
145
|
+
if (!this.isSpeaking)
|
|
146
|
+
return;
|
|
147
|
+
this.isSpeaking = false;
|
|
148
|
+
this.blendshapeQueue.stopBotSpeaking();
|
|
149
|
+
this.emit("speakingChange", false);
|
|
150
|
+
}
|
|
121
151
|
/**
|
|
122
152
|
* Finalize local response state after the client intentionally aborts a
|
|
123
153
|
* transport before the server can deliver its terminal response frame.
|
|
@@ -637,6 +667,11 @@ export class MessageHandler extends EventEmitter {
|
|
|
637
667
|
break;
|
|
638
668
|
// Bot Started Speaking (priority over listening: state becomes speaking)
|
|
639
669
|
case "bot-started-speaking": {
|
|
670
|
+
if (this.speakingFromPlayback) {
|
|
671
|
+
// Data-channel audio: the player decides (see setSpeakingFromPlayback).
|
|
672
|
+
this.emit("serverSpeakingChange", true);
|
|
673
|
+
break;
|
|
674
|
+
}
|
|
640
675
|
const owner = this.lifecycleOwner(messageData.data);
|
|
641
676
|
if (this.blendshapeQueue.isStaleOwner(owner)) {
|
|
642
677
|
break;
|
|
@@ -651,6 +686,10 @@ export class MessageHandler extends EventEmitter {
|
|
|
651
686
|
}
|
|
652
687
|
// Bot Stopped Speaking
|
|
653
688
|
case "bot-stopped-speaking":
|
|
689
|
+
if (this.speakingFromPlayback) {
|
|
690
|
+
this.emit("serverSpeakingChange", false);
|
|
691
|
+
break;
|
|
692
|
+
}
|
|
654
693
|
if (this.blendshapeQueue.isStaleOwner(this.lifecycleOwner(messageData.data))) {
|
|
655
694
|
break;
|
|
656
695
|
}
|
|
@@ -695,6 +734,22 @@ export class MessageHandler extends EventEmitter {
|
|
|
695
734
|
if (messageData.data) {
|
|
696
735
|
const serverData = messageData.data;
|
|
697
736
|
switch (serverData.type) {
|
|
737
|
+
// Data-channel audio (audio_routing: data_only) arrives wrapped in a
|
|
738
|
+
// server-message on LiveKit; same payload as the top-level audio-data.
|
|
739
|
+
case "audio-data": {
|
|
740
|
+
const data = serverData;
|
|
741
|
+
if (typeof data.audio === "string" &&
|
|
742
|
+
typeof data.sample_rate === "number" &&
|
|
743
|
+
typeof data.channels === "number") {
|
|
744
|
+
this.emit("audioData", {
|
|
745
|
+
audio: data.audio,
|
|
746
|
+
sample_rate: data.sample_rate,
|
|
747
|
+
channels: data.channels,
|
|
748
|
+
includes_wav_header: data.includes_wav_header === true,
|
|
749
|
+
}, sseRequest);
|
|
750
|
+
}
|
|
751
|
+
break;
|
|
752
|
+
}
|
|
698
753
|
// How production delivers usage: wrapped in a server-message,
|
|
699
754
|
// the record's fields beside `type`. Strip the envelope's type.
|
|
700
755
|
case "usage-update": {
|
|
@@ -793,6 +848,8 @@ export class MessageHandler extends EventEmitter {
|
|
|
793
848
|
break;
|
|
794
849
|
case "neurosync-blendshapes-cancel": {
|
|
795
850
|
const cancelledActive = this.blendshapeQueue.cancelOwner(this.lifecycleOwner(serverData));
|
|
851
|
+
if (cancelledActive)
|
|
852
|
+
this.emit("playbackInterrupted");
|
|
796
853
|
if (cancelledActive && this.isSpeaking) {
|
|
797
854
|
this.isSpeaking = false;
|
|
798
855
|
this.emit("speakingChange", false);
|
package/dist/core/index.d.ts
CHANGED
|
@@ -6,6 +6,10 @@ export { AudioManager } from './AudioManager.js';
|
|
|
6
6
|
export { VideoManager } from './VideoManager.js';
|
|
7
7
|
export { ScreenShareManager } from './ScreenShareManager.js';
|
|
8
8
|
export { MessageHandler } from './MessageHandler.js';
|
|
9
|
+
export { DataAudioPlayer, createWorkletSink, decodePcm16 } from './DataAudioPlayer.js';
|
|
10
|
+
export type { DataAudioSink, DataAudioPlayerOptions, DataAudioStats } from './DataAudioPlayer.js';
|
|
11
|
+
export { StreamController, STREAM_DEFAULTS } from './streamController.js';
|
|
12
|
+
export type { StreamControllerOptions, StreamState, StreamSnapshot } from './streamController.js';
|
|
9
13
|
export { MemoryManager } from './MemoryManager.js';
|
|
10
14
|
export { CharacterRoster } from './CharacterRoster.js';
|
|
11
15
|
export { ConvaiRoomError } from './ConvaiRoomError.js';
|
package/dist/core/index.js
CHANGED
|
@@ -9,6 +9,8 @@ export { AudioManager } from './AudioManager.js';
|
|
|
9
9
|
export { VideoManager } from './VideoManager.js';
|
|
10
10
|
export { ScreenShareManager } from './ScreenShareManager.js';
|
|
11
11
|
export { MessageHandler } from './MessageHandler.js';
|
|
12
|
+
export { DataAudioPlayer, createWorkletSink, decodePcm16 } from './DataAudioPlayer.js';
|
|
13
|
+
export { StreamController, STREAM_DEFAULTS } from './streamController.js';
|
|
12
14
|
export { MemoryManager } from './MemoryManager.js';
|
|
13
15
|
export { CharacterRoster } from './CharacterRoster.js';
|
|
14
16
|
export { ConvaiRoomError } from './ConvaiRoomError.js';
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* When to play and pause a reply whose voice arrives over the data channel
|
|
3
|
+
* (`audioRouting: 'data_only'`).
|
|
4
|
+
*
|
|
5
|
+
* Pure decision logic: it is told what arrived and where playback is, and answers
|
|
6
|
+
* play or pause. {@link DataAudioPlayer} drives it every 20 ms.
|
|
7
|
+
*
|
|
8
|
+
* One rule, from the Convai Unreal plugin's ConvaiAudioStreamer, which plays
|
|
9
|
+
* min(audio, lipsync): only SYNCED data is playable, the seconds for which both the
|
|
10
|
+
* audio and its blendshapes are in hand. Playback starts or resumes once `minBuffer`
|
|
11
|
+
* seconds of synced data are ahead of the playhead, and pauses when less than
|
|
12
|
+
* `lowWater` is left, or a little earlier, below `silenceWater`, if the buffer holds
|
|
13
|
+
* a silence to pause on so the stop falls between words. Once the reply has fully arrived, everything left plays out. The mouth is
|
|
14
|
+
* never asked to follow audio it has no frames for.
|
|
15
|
+
*/
|
|
16
|
+
export type StreamState = "idle" | "buffering" | "playing" | "paused" | "done";
|
|
17
|
+
export interface StreamControllerOptions {
|
|
18
|
+
/** Seconds of synced audio + blendshapes to have ahead before playing or resuming. */
|
|
19
|
+
minBuffer: number;
|
|
20
|
+
/** Pause when less than this much synced data is left ahead of the playhead, s. */
|
|
21
|
+
lowWater: number;
|
|
22
|
+
/** Below this much synced data ahead, s, pause early if the caller has a silence to pause on. */
|
|
23
|
+
silenceWater: number;
|
|
24
|
+
}
|
|
25
|
+
export declare const STREAM_DEFAULTS: StreamControllerOptions;
|
|
26
|
+
export interface StreamSnapshot {
|
|
27
|
+
state: StreamState;
|
|
28
|
+
/** Seconds of audio received this reply. */
|
|
29
|
+
audio: number;
|
|
30
|
+
/** Seconds of lipsync received this reply. */
|
|
31
|
+
frames: number;
|
|
32
|
+
/** The reply's length, once the turn has announced it. */
|
|
33
|
+
total: number | null;
|
|
34
|
+
/** All of the reply's audio is in. */
|
|
35
|
+
ended: boolean;
|
|
36
|
+
/** Pauses taken this reply. */
|
|
37
|
+
pauses: number;
|
|
38
|
+
}
|
|
39
|
+
export declare class StreamController {
|
|
40
|
+
readonly o: StreamControllerOptions;
|
|
41
|
+
private s;
|
|
42
|
+
/**
|
|
43
|
+
* Frames that arrived while no reply was open. On SaaS a reply's blendshapes start
|
|
44
|
+
* arriving before its first audio chunk (2.4 s of them, measured); they belong to it.
|
|
45
|
+
*/
|
|
46
|
+
private early;
|
|
47
|
+
constructor(options?: Partial<StreamControllerOptions>);
|
|
48
|
+
get snapshot(): Readonly<StreamSnapshot>;
|
|
49
|
+
get state(): StreamState;
|
|
50
|
+
/** Start a fresh reply. */
|
|
51
|
+
newReply(): void;
|
|
52
|
+
/** `seconds` of audio arrived. Starts a reply if none is open. */
|
|
53
|
+
onAudio(_t: number, seconds: number): void;
|
|
54
|
+
/** `seconds` of lipsync arrived for the open reply. */
|
|
55
|
+
onFrames(seconds: number): void;
|
|
56
|
+
/** The turn announced the reply's length. */
|
|
57
|
+
onTotal(seconds: number): void;
|
|
58
|
+
/** All of the reply's audio is in: play it out, no more waiting. */
|
|
59
|
+
onEnded(): void;
|
|
60
|
+
/** Drop the open reply (an interruption). */
|
|
61
|
+
reset(): void;
|
|
62
|
+
/** Mark the open reply as played out (the player reached its end). */
|
|
63
|
+
finish(): void;
|
|
64
|
+
/** Seconds of the reply with both audio and blendshapes in hand. */
|
|
65
|
+
get synced(): number;
|
|
66
|
+
/**
|
|
67
|
+
* Decide at wall time `t` (s), with `played` seconds of the reply already played.
|
|
68
|
+
* `silenceAhead` says whether the synced audio left holds a silence to pause on.
|
|
69
|
+
* Returns 'play', 'pause', or null for no change.
|
|
70
|
+
*/
|
|
71
|
+
tick(_t: number, played: number, silenceAhead?: () => boolean): "play" | "pause" | null;
|
|
72
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* When to play and pause a reply whose voice arrives over the data channel
|
|
3
|
+
* (`audioRouting: 'data_only'`).
|
|
4
|
+
*
|
|
5
|
+
* Pure decision logic: it is told what arrived and where playback is, and answers
|
|
6
|
+
* play or pause. {@link DataAudioPlayer} drives it every 20 ms.
|
|
7
|
+
*
|
|
8
|
+
* One rule, from the Convai Unreal plugin's ConvaiAudioStreamer, which plays
|
|
9
|
+
* min(audio, lipsync): only SYNCED data is playable, the seconds for which both the
|
|
10
|
+
* audio and its blendshapes are in hand. Playback starts or resumes once `minBuffer`
|
|
11
|
+
* seconds of synced data are ahead of the playhead, and pauses when less than
|
|
12
|
+
* `lowWater` is left, or a little earlier, below `silenceWater`, if the buffer holds
|
|
13
|
+
* a silence to pause on so the stop falls between words. Once the reply has fully arrived, everything left plays out. The mouth is
|
|
14
|
+
* never asked to follow audio it has no frames for.
|
|
15
|
+
*/
|
|
16
|
+
export const STREAM_DEFAULTS = {
|
|
17
|
+
minBuffer: 0.9,
|
|
18
|
+
// Low: the stretch between resume and pause is minBuffer - lowWater. At 0.6 a 0.9 s
|
|
19
|
+
// buffer played 0.3 s at a time (116 pauses on a 71 s story at 0.68x; 32 at 0.15).
|
|
20
|
+
lowWater: 0.15,
|
|
21
|
+
silenceWater: 0.4,
|
|
22
|
+
};
|
|
23
|
+
const fresh = (state) => ({ state, audio: 0, frames: 0, total: null, ended: false, pauses: 0 });
|
|
24
|
+
export class StreamController {
|
|
25
|
+
constructor(options = {}) {
|
|
26
|
+
this.s = fresh("idle");
|
|
27
|
+
/**
|
|
28
|
+
* Frames that arrived while no reply was open. On SaaS a reply's blendshapes start
|
|
29
|
+
* arriving before its first audio chunk (2.4 s of them, measured); they belong to it.
|
|
30
|
+
*/
|
|
31
|
+
this.early = 0;
|
|
32
|
+
this.o = { ...STREAM_DEFAULTS, ...options };
|
|
33
|
+
}
|
|
34
|
+
get snapshot() {
|
|
35
|
+
return this.s;
|
|
36
|
+
}
|
|
37
|
+
get state() {
|
|
38
|
+
return this.s.state;
|
|
39
|
+
}
|
|
40
|
+
/** Start a fresh reply. */
|
|
41
|
+
newReply() {
|
|
42
|
+
this.s = fresh("buffering");
|
|
43
|
+
this.s.frames = this.early;
|
|
44
|
+
this.early = 0;
|
|
45
|
+
}
|
|
46
|
+
/** `seconds` of audio arrived. Starts a reply if none is open. */
|
|
47
|
+
onAudio(_t, seconds) {
|
|
48
|
+
if (this.s.state === "idle" || this.s.state === "done")
|
|
49
|
+
this.newReply();
|
|
50
|
+
this.s.audio += seconds;
|
|
51
|
+
}
|
|
52
|
+
/** `seconds` of lipsync arrived for the open reply. */
|
|
53
|
+
onFrames(seconds) {
|
|
54
|
+
if (this.s.state !== "idle" && this.s.state !== "done")
|
|
55
|
+
this.s.frames += seconds;
|
|
56
|
+
else
|
|
57
|
+
this.early += seconds;
|
|
58
|
+
}
|
|
59
|
+
/** The turn announced the reply's length. */
|
|
60
|
+
onTotal(seconds) {
|
|
61
|
+
this.s.total = seconds;
|
|
62
|
+
}
|
|
63
|
+
/** All of the reply's audio is in: play it out, no more waiting. */
|
|
64
|
+
onEnded() {
|
|
65
|
+
this.s.ended = true;
|
|
66
|
+
}
|
|
67
|
+
/** Drop the open reply (an interruption). */
|
|
68
|
+
reset() {
|
|
69
|
+
this.s = fresh("idle");
|
|
70
|
+
this.early = 0;
|
|
71
|
+
}
|
|
72
|
+
/** Mark the open reply as played out (the player reached its end). */
|
|
73
|
+
finish() {
|
|
74
|
+
if (this.s.state === "playing" || this.s.state === "paused")
|
|
75
|
+
this.s.state = "done";
|
|
76
|
+
}
|
|
77
|
+
/** Seconds of the reply with both audio and blendshapes in hand. */
|
|
78
|
+
get synced() {
|
|
79
|
+
return Math.min(this.s.audio, this.s.frames);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Decide at wall time `t` (s), with `played` seconds of the reply already played.
|
|
83
|
+
* `silenceAhead` says whether the synced audio left holds a silence to pause on.
|
|
84
|
+
* Returns 'play', 'pause', or null for no change.
|
|
85
|
+
*/
|
|
86
|
+
tick(_t, played, silenceAhead = () => false) {
|
|
87
|
+
const s = this.s;
|
|
88
|
+
const ahead = this.synced - played;
|
|
89
|
+
if (s.state === "buffering" || s.state === "paused") {
|
|
90
|
+
if (s.ended || ahead >= this.o.minBuffer) {
|
|
91
|
+
s.state = "playing";
|
|
92
|
+
return "play";
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
if (s.state === "playing") {
|
|
97
|
+
// 50 ms: the heard position trails what has been played by the output latency.
|
|
98
|
+
if (s.ended && s.audio - played <= 0.05) {
|
|
99
|
+
s.state = "done";
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
if (!s.ended && (ahead < this.o.lowWater || (ahead < this.o.silenceWater && silenceAhead()))) {
|
|
103
|
+
s.state = "paused";
|
|
104
|
+
s.pauses++;
|
|
105
|
+
return "pause";
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
}
|
package/dist/core/types.d.ts
CHANGED
|
@@ -801,6 +801,30 @@ export interface ConvaiConfig {
|
|
|
801
801
|
iceTransportPolicy?: RTCIceTransportPolicy;
|
|
802
802
|
/** Enable text-to-speech audio generation (default: true for LiveKit, false for SSE). */
|
|
803
803
|
ttsEnabled?: boolean;
|
|
804
|
+
/**
|
|
805
|
+
* How the character's voice reaches the client (LiveKit transport).
|
|
806
|
+
*
|
|
807
|
+
* - `"webrtc"` (default): an audio track, played by the browser as it arrives.
|
|
808
|
+
* - `"data_only"`: PCM chunks over the data channel, next to the lipsync
|
|
809
|
+
* frames. The SDK plays them itself ({@link IConvaiClient.dataAudio}): it
|
|
810
|
+
* holds a reply until enough audio and lipsync are in hand, plays it as one
|
|
811
|
+
* continuous stream, and on a link slower than real time pauses on a
|
|
812
|
+
* silence instead of stuttering. On this path `speakingChange` and
|
|
813
|
+
* `state.isSpeaking` follow what is HEARD, not when the server sent it.
|
|
814
|
+
*
|
|
815
|
+
* @example
|
|
816
|
+
* ```ts
|
|
817
|
+
* const client = new ConvaiClient({ apiKey, characterId, enableLipsync: true, audioRouting: 'data_only' })
|
|
818
|
+
* ```
|
|
819
|
+
*/
|
|
820
|
+
audioRouting?: AudioRouting;
|
|
821
|
+
/**
|
|
822
|
+
* With `audioRouting: 'data_only'`: seconds of synced audio and lipsync to have in hand
|
|
823
|
+
* before a reply plays, and again before it resumes after running low. Larger values
|
|
824
|
+
* mean fewer, longer pauses on a link slower than real time; on a fast link they only
|
|
825
|
+
* delay the start a little. Default 0.9 (the Convai Unreal plugin's MinBufferDuration).
|
|
826
|
+
*/
|
|
827
|
+
dataAudioBufferSeconds?: number;
|
|
804
828
|
/**
|
|
805
829
|
* Enable lipsync/facial animation blendshapes (default: false).
|
|
806
830
|
* When true, sets blendshape_provider to "neurosync".
|
|
@@ -1226,6 +1250,49 @@ export type RawMessageEvent = {
|
|
|
1226
1250
|
/** @deprecated Use {@link SSERequestContext}; retained for error-listener compatibility. */
|
|
1227
1251
|
export type SSERequestErrorContext = SSERequestContext;
|
|
1228
1252
|
/** A streamed signed 16-bit little-endian PCM audio chunk. */
|
|
1253
|
+
/** How the character's voice is delivered: a WebRTC audio track, or PCM chunks over the data channel. */
|
|
1254
|
+
export type AudioRouting = "webrtc" | "data_only";
|
|
1255
|
+
/** The lifecycle of the reply now being played on the data-channel audio path. */
|
|
1256
|
+
export type DataAudioState = "idle" | "buffering" | "playing" | "paused" | "done";
|
|
1257
|
+
/**
|
|
1258
|
+
* The SDK's player for `audioRouting: 'data_only'`. One per client; null on the
|
|
1259
|
+
* WebRTC path.
|
|
1260
|
+
*
|
|
1261
|
+
* Events (`on(name, cb)`, returning an unsubscribe):
|
|
1262
|
+
* - `replyStarted` — the reply's first sample is heard.
|
|
1263
|
+
* - `replyEnded` `{ interrupted }` — the reply has played out, or was interrupted.
|
|
1264
|
+
* - `paused` `{ atSilence }` / `resumed` — a rebuffer on a link slower than real time.
|
|
1265
|
+
* - `underrun` — playback ran out mid-reply (should not happen; counted in `stats`).
|
|
1266
|
+
*/
|
|
1267
|
+
export interface DataAudioPlayback {
|
|
1268
|
+
/** Where the open reply is: buffering before it starts, playing, paused to refill, done. */
|
|
1269
|
+
readonly state: DataAudioState;
|
|
1270
|
+
/** Chunks received, clean pauses taken, and underruns (stutters) since the client was made. */
|
|
1271
|
+
readonly stats: {
|
|
1272
|
+
chunks: number;
|
|
1273
|
+
pauses: number;
|
|
1274
|
+
underruns: number;
|
|
1275
|
+
};
|
|
1276
|
+
/** Seconds of the open reply heard so far; null before it starts. Holds while paused. */
|
|
1277
|
+
position(): number | null;
|
|
1278
|
+
/** RMS of the voice now playing (0–1); null when it cannot be read yet. */
|
|
1279
|
+
level(): number | null;
|
|
1280
|
+
/** Seconds of audio buffered ahead of what is heard. */
|
|
1281
|
+
queuedSeconds(): number;
|
|
1282
|
+
/**
|
|
1283
|
+
* The reply's heard position as an RTCRtpReceiver synchronization source
|
|
1284
|
+
* (48 kHz RTP units), so a lipsync clock written for a WebRTC receiver can
|
|
1285
|
+
* follow this player unchanged. Empty before a reply starts.
|
|
1286
|
+
*/
|
|
1287
|
+
getSynchronizationSources(): Array<{
|
|
1288
|
+
rtpTimestamp: number;
|
|
1289
|
+
timestamp: number;
|
|
1290
|
+
audioLevel?: number;
|
|
1291
|
+
}>;
|
|
1292
|
+
/** Resume audio output; call from a user gesture where the page blocks autoplay. */
|
|
1293
|
+
resume(): Promise<void>;
|
|
1294
|
+
on(event: "replyStarted" | "replyEnded" | "paused" | "resumed" | "underrun", callback: (detail: unknown) => void): () => void;
|
|
1295
|
+
}
|
|
1229
1296
|
export interface AudioDataEvent {
|
|
1230
1297
|
/** Sample rate of this chunk in hertz. */
|
|
1231
1298
|
sample_rate: number;
|
|
@@ -1263,6 +1330,12 @@ export interface ConvaiEventMap {
|
|
|
1263
1330
|
messagesChange: [messages: ChatMessage[]];
|
|
1264
1331
|
userTranscriptionChange: [transcription: string];
|
|
1265
1332
|
speakingChange: [isSpeaking: boolean];
|
|
1333
|
+
/**
|
|
1334
|
+
* The server's own bot-started/stopped-speaking flags, with
|
|
1335
|
+
* `audioRouting: 'data_only'`. They follow when the server SENT the audio;
|
|
1336
|
+
* `speakingChange` follows when it is heard.
|
|
1337
|
+
*/
|
|
1338
|
+
serverSpeakingChange: [isSpeaking: boolean];
|
|
1266
1339
|
listeningChange: [isListening: boolean];
|
|
1267
1340
|
botRespondingChange: [isResponding: boolean];
|
|
1268
1341
|
turnEnd: [turn: {
|
|
@@ -2101,6 +2174,17 @@ export interface IConvaiClient {
|
|
|
2101
2174
|
readonly screenShareControls: ScreenShareControls;
|
|
2102
2175
|
/** Blendshape queue for time-based lipsync synchronization */
|
|
2103
2176
|
readonly blendshapeQueue: BlendshapeQueue;
|
|
2177
|
+
/**
|
|
2178
|
+
* The player for the character's voice when `audioRouting: 'data_only'`;
|
|
2179
|
+
* null on the WebRTC path.
|
|
2180
|
+
*
|
|
2181
|
+
* @example
|
|
2182
|
+
* ```ts
|
|
2183
|
+
* client.dataAudio?.on('paused', () => console.log('waiting for the network'))
|
|
2184
|
+
* const heard = client.dataAudio?.position() // seconds into the reply
|
|
2185
|
+
* ```
|
|
2186
|
+
*/
|
|
2187
|
+
readonly dataAudio: DataAudioPlayback | null;
|
|
2104
2188
|
/** Incremental turn session ID used by conversation events (e.g. conversationStart, turnEnd) */
|
|
2105
2189
|
readonly conversationSessionId: number;
|
|
2106
2190
|
/**
|
|
@@ -201,6 +201,7 @@ export const useConvaiClient = (config) => {
|
|
|
201
201
|
videoControls: client.videoControls,
|
|
202
202
|
screenShareControls: client.screenShareControls,
|
|
203
203
|
blendshapeQueue: client.blendshapeQueue,
|
|
204
|
+
dataAudio: client.dataAudio,
|
|
204
205
|
conversationSessionId: client.conversationSessionId,
|
|
205
206
|
memoryManager: client.memoryManager,
|
|
206
207
|
characterVersions: client.characterVersions,
|
package/dist/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const SDK_VERSION = "2.1.0-beta.
|
|
1
|
+
export declare const SDK_VERSION = "2.1.0-beta.1";
|
package/dist/version.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@convai/web-sdk",
|
|
3
|
-
"version": "2.1.0-beta.
|
|
3
|
+
"version": "2.1.0-beta.1",
|
|
4
4
|
"description": "Build web apps with lifelike AI characters. The Convai Web SDK gives you real-time voice, lipsync, emotions, and dynamic context — with first-class support for React and vanilla TypeScript.",
|
|
5
5
|
"private": false,
|
|
6
6
|
"type": "module",
|