@convai/web-sdk 2.1.0-beta.0 → 2.1.0-beta.2
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/BlendshapeQueue.d.ts +17 -0
- package/dist/core/BlendshapeQueue.js +43 -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 +404 -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.
|
|
@@ -53,9 +53,18 @@ export declare class BlendshapeQueue {
|
|
|
53
53
|
private playbackFps;
|
|
54
54
|
private ownerReplacementStoppedSpeaking;
|
|
55
55
|
private missingExpectedFramesSinceMs;
|
|
56
|
+
/** When the queue ran dry with indexed frames waiting beyond a hole; null otherwise. */
|
|
57
|
+
private holeSinceMs;
|
|
56
58
|
private readonly now;
|
|
57
59
|
private static readonly TARGET_FPS;
|
|
58
60
|
private static readonly MAX_RETIRED_TIMELINE_ALIASES;
|
|
61
|
+
/**
|
|
62
|
+
* How long a dry queue waits for a missing indexed chunk before skipping it, ms. A hole
|
|
63
|
+
* never filled used to hold every later frame in the pending map, freezing the face for
|
|
64
|
+
* the rest of the reply (measured on production, 2026-11-16: 63 frames missing ~6.9 s
|
|
65
|
+
* into a reply, the remaining 18 s without lipsync).
|
|
66
|
+
*/
|
|
67
|
+
private static readonly HOLE_GRACE_MS;
|
|
59
68
|
private static readonly MISSING_INDEXED_FRAME_GRACE_MS;
|
|
60
69
|
/**
|
|
61
70
|
* Create a new BlendshapeQueue
|
|
@@ -150,6 +159,14 @@ export declare class BlendshapeQueue {
|
|
|
150
159
|
* Check if queue has frames
|
|
151
160
|
*/
|
|
152
161
|
hasFrames(): boolean;
|
|
162
|
+
/**
|
|
163
|
+
* The queue is dry, but indexed frames wait beyond a hole: give the missing chunk
|
|
164
|
+
* HOLE_GRACE_MS to arrive, then count the hole as consumed and play on from the
|
|
165
|
+
* frames beyond it. A consumer that follows `getFramesConsumed()` lands on them at
|
|
166
|
+
* the voice's time for them; a chunk for the hole that arrives later is dropped
|
|
167
|
+
* (its frames are behind `framesConsumed`).
|
|
168
|
+
*/
|
|
169
|
+
private skipLateHole;
|
|
153
170
|
/**
|
|
154
171
|
* Check if conversation is active
|
|
155
172
|
*/
|
|
@@ -62,6 +62,8 @@ export class BlendshapeQueue {
|
|
|
62
62
|
this.playbackFps = 60;
|
|
63
63
|
this.ownerReplacementStoppedSpeaking = false;
|
|
64
64
|
this.missingExpectedFramesSinceMs = null;
|
|
65
|
+
/** When the queue ran dry with indexed frames waiting beyond a hole; null otherwise. */
|
|
66
|
+
this.holeSinceMs = null;
|
|
65
67
|
this.mapper = mapper;
|
|
66
68
|
this.now = now;
|
|
67
69
|
}
|
|
@@ -289,6 +291,7 @@ export class BlendshapeQueue {
|
|
|
289
291
|
this.activeTimelineAliases = new Set(ownerAliases);
|
|
290
292
|
this.queue = [];
|
|
291
293
|
this.pendingTimelineFrames.clear();
|
|
294
|
+
this.holeSinceMs = null;
|
|
292
295
|
this.framesConsumed = 0;
|
|
293
296
|
this.turnStats = null;
|
|
294
297
|
this.missingExpectedFramesSinceMs = null;
|
|
@@ -357,6 +360,7 @@ export class BlendshapeQueue {
|
|
|
357
360
|
}
|
|
358
361
|
this.queue = [];
|
|
359
362
|
this.pendingTimelineFrames.clear();
|
|
363
|
+
this.holeSinceMs = null;
|
|
360
364
|
this.framesConsumed = 0;
|
|
361
365
|
this.missingExpectedFramesSinceMs = null;
|
|
362
366
|
this.botSpeaking = false;
|
|
@@ -470,8 +474,37 @@ export class BlendshapeQueue {
|
|
|
470
474
|
* Check if queue has frames
|
|
471
475
|
*/
|
|
472
476
|
hasFrames() {
|
|
477
|
+
this.skipLateHole();
|
|
473
478
|
return this.queue.length > 0;
|
|
474
479
|
}
|
|
480
|
+
/**
|
|
481
|
+
* The queue is dry, but indexed frames wait beyond a hole: give the missing chunk
|
|
482
|
+
* HOLE_GRACE_MS to arrive, then count the hole as consumed and play on from the
|
|
483
|
+
* frames beyond it. A consumer that follows `getFramesConsumed()` lands on them at
|
|
484
|
+
* the voice's time for them; a chunk for the hole that arrives later is dropped
|
|
485
|
+
* (its frames are behind `framesConsumed`).
|
|
486
|
+
*/
|
|
487
|
+
skipLateHole() {
|
|
488
|
+
if (this.queue.length > 0 || this.pendingTimelineFrames.size === 0) {
|
|
489
|
+
this.holeSinceMs = null;
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
const t = this.now();
|
|
493
|
+
if (this.holeSinceMs === null) {
|
|
494
|
+
this.holeSinceMs = t;
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
if (t - this.holeSinceMs < BlendshapeQueue.HOLE_GRACE_MS)
|
|
498
|
+
return;
|
|
499
|
+
let next = Infinity;
|
|
500
|
+
for (const k of this.pendingTimelineFrames.keys())
|
|
501
|
+
if (k < next)
|
|
502
|
+
next = k;
|
|
503
|
+
if (next > this.framesConsumed)
|
|
504
|
+
this.framesConsumed = next;
|
|
505
|
+
this.holeSinceMs = null;
|
|
506
|
+
this.flushContiguousTimelineFrames();
|
|
507
|
+
}
|
|
475
508
|
/**
|
|
476
509
|
* Check if conversation is active
|
|
477
510
|
*/
|
|
@@ -554,6 +587,7 @@ export class BlendshapeQueue {
|
|
|
554
587
|
// Clear any leftover frames from previous conversation
|
|
555
588
|
this.queue = [];
|
|
556
589
|
this.pendingTimelineFrames.clear();
|
|
590
|
+
this.holeSinceMs = null;
|
|
557
591
|
this.rememberRetiredTimelineAliases(this.activeTimelineAliases);
|
|
558
592
|
this.clearTimelineOwner();
|
|
559
593
|
this.conversationActive = true;
|
|
@@ -660,6 +694,7 @@ export class BlendshapeQueue {
|
|
|
660
694
|
this.needsNormalization = true; // Signal lipsync player to lerp morphs back to 0
|
|
661
695
|
this.ownerReplacementStoppedSpeaking = false;
|
|
662
696
|
this.pendingTimelineFrames.clear();
|
|
697
|
+
this.holeSinceMs = null;
|
|
663
698
|
this.missingExpectedFramesSinceMs = null;
|
|
664
699
|
// Ahead-delivered turns may have many seconds of future frames buffered.
|
|
665
700
|
// On interrupt, audio stops immediately, so visuals must hard-stop too.
|
|
@@ -731,6 +766,7 @@ export class BlendshapeQueue {
|
|
|
731
766
|
reset() {
|
|
732
767
|
this.queue = [];
|
|
733
768
|
this.pendingTimelineFrames.clear();
|
|
769
|
+
this.holeSinceMs = null;
|
|
734
770
|
this.rememberRetiredTimelineAliases(this.activeTimelineAliases);
|
|
735
771
|
this.clearTimelineOwner();
|
|
736
772
|
this.conversationActive = false;
|
|
@@ -784,4 +820,11 @@ export class BlendshapeQueue {
|
|
|
784
820
|
// Constants
|
|
785
821
|
BlendshapeQueue.TARGET_FPS = 60;
|
|
786
822
|
BlendshapeQueue.MAX_RETIRED_TIMELINE_ALIASES = 48;
|
|
823
|
+
/**
|
|
824
|
+
* How long a dry queue waits for a missing indexed chunk before skipping it, ms. A hole
|
|
825
|
+
* never filled used to hold every later frame in the pending map, freezing the face for
|
|
826
|
+
* the rest of the reply (measured on production, 2026-11-16: 63 frames missing ~6.9 s
|
|
827
|
+
* into a reply, the remaining 18 s without lipsync).
|
|
828
|
+
*/
|
|
829
|
+
BlendshapeQueue.HOLE_GRACE_MS = 150;
|
|
787
830
|
BlendshapeQueue.MISSING_INDEXED_FRAME_GRACE_MS = (24 / BlendshapeQueue.TARGET_FPS) * 1000;
|
|
@@ -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>;
|