@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.
@@ -0,0 +1,404 @@
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
+ /** Seconds past the worklet's last position report the heard position may be extrapolated. */
20
+ const REPORT_STALE = 0.1;
21
+ const SILENCE_RMS = 0.008;
22
+ const SILENCE_WINDOW = 0.03;
23
+ /** Decode a base64 16-bit little-endian PCM chunk to mono Float32. */
24
+ export function decodePcm16(base64, channels) {
25
+ const bin = atob(base64);
26
+ const frames = Math.floor(bin.length / 2 / Math.max(1, channels));
27
+ const out = new Float32Array(frames);
28
+ for (let i = 0; i < frames; i++) {
29
+ let sum = 0;
30
+ for (let c = 0; c < channels; c++) {
31
+ const k = 2 * (i * channels + c);
32
+ let v = bin.charCodeAt(k) | (bin.charCodeAt(k + 1) << 8);
33
+ if (v >= 32768)
34
+ v -= 65536;
35
+ sum += v / 32768;
36
+ }
37
+ out[i] = sum / Math.max(1, channels);
38
+ }
39
+ return out;
40
+ }
41
+ export class DataAudioPlayer extends EventEmitter {
42
+ constructor(options = {}) {
43
+ super();
44
+ this.stats = { chunks: 0, pauses: 0, underruns: 0 };
45
+ /** The server's speaking flag: true sending, false done sending, null never heard. */
46
+ this.serverSending = null;
47
+ this.sink = null;
48
+ this.sinkPromise = null;
49
+ this.pending = [];
50
+ this.muted = false;
51
+ this.read = 0; // last reported read index
52
+ this.readAt = 0; // wall s of that report
53
+ this.playing = false;
54
+ this.written = 0; // samples pushed in total
55
+ this.replyStart = 0; // sample index where the open reply begins
56
+ this.replyPcm = [];
57
+ this.announced = null;
58
+ this.lastChunkAt = 0;
59
+ this.heardStarted = false;
60
+ this.endedAt = null;
61
+ this.rtpBase = 0;
62
+ this.timer = null;
63
+ this.controller = new StreamController(options.controller);
64
+ this.makeSink = options.createSink ?? createWorkletSink;
65
+ this.now = options.now ?? (() => performance.now() / 1000);
66
+ this.idleEnd = options.idleEnd ?? 1.5;
67
+ this.stallEnd = options.stallEnd ?? 10;
68
+ }
69
+ /** Where playback is in the open reply's lifecycle. */
70
+ get state() {
71
+ return this.controller.state;
72
+ }
73
+ /** Queue an audio-data chunk. */
74
+ pushChunk(chunk) {
75
+ if (chunk.includes_wav_header)
76
+ return; // the data channel sends raw PCM; a WAV file is not a stream chunk
77
+ this.pending.push(chunk);
78
+ void this.ensureSink(chunk.sample_rate).then(() => this.flushPending());
79
+ }
80
+ /** The turn announced the reply's audio length (blendshape-turn-stats). */
81
+ setTurnTotal(seconds) {
82
+ if (!(seconds > 0))
83
+ return;
84
+ this.announced = seconds;
85
+ this.controller.onTotal(seconds);
86
+ this.checkEnded();
87
+ }
88
+ /** The server's own speaking flag: true while it is still sending this reply. */
89
+ setServerSpeaking(speaking) {
90
+ this.serverSending = speaking;
91
+ }
92
+ /** Lipsync seconds that arrived for the open reply. */
93
+ addFrames(seconds) {
94
+ this.controller.onFrames(seconds);
95
+ }
96
+ /** Drop everything (an interruption). */
97
+ clear() {
98
+ this.pending = [];
99
+ this.sink?.clear();
100
+ this.read = this.written;
101
+ this.playing = false;
102
+ const wasActive = this.heardStarted && this.endedAt == null;
103
+ this.controller.reset();
104
+ this.replyPcm = [];
105
+ this.announced = null;
106
+ this.heardStarted = false;
107
+ this.endedAt = null;
108
+ if (wasActive)
109
+ this.emit("replyEnded", { interrupted: true });
110
+ }
111
+ setMuted(muted) {
112
+ this.muted = muted;
113
+ this.sink?.setMuted(muted);
114
+ }
115
+ /** Resume the audio context (call from a user gesture if the page blocks autoplay). */
116
+ async resume() {
117
+ await this.sink?.resume();
118
+ }
119
+ /** Seconds of the open reply heard so far; null before it starts. Holds through a pause, runs on 3 s past the end. */
120
+ position() {
121
+ const st = this.controller.state;
122
+ if (!this.sink || st === "idle" || st === "buffering")
123
+ return null;
124
+ if (this.endedAt != null) {
125
+ const extra = this.now() - this.endedAt;
126
+ return extra < 3 ? this.controller.snapshot.audio + extra : null;
127
+ }
128
+ return this.replyPlayed();
129
+ }
130
+ /** RMS of the voice now playing; null when nothing can be read. */
131
+ level() {
132
+ return this.sink?.level() ?? null;
133
+ }
134
+ /** Seconds buffered ahead of what is heard. */
135
+ queuedSeconds() {
136
+ if (!this.sink)
137
+ return 0;
138
+ return Math.max(0, (this.written - this.heardIndex()) / this.sink.sampleRate);
139
+ }
140
+ /** RTCRtpReceiver-shaped clock: the open reply's heard position in 48 kHz RTP units. */
141
+ getSynchronizationSources() {
142
+ const p = this.position();
143
+ if (p == null)
144
+ return [];
145
+ return [{ rtpTimestamp: this.rtpBase + p * RTP_RATE, timestamp: Date.now(), audioLevel: this.level() ?? 0 }];
146
+ }
147
+ dispose() {
148
+ if (this.timer)
149
+ clearInterval(this.timer);
150
+ this.timer = null;
151
+ this.sink?.dispose();
152
+ this.sink = null;
153
+ this.sinkPromise = null;
154
+ }
155
+ // ── internals ─────────────────────────────────────────────────────────────
156
+ ensureSink(rate) {
157
+ this.sinkPromise ?? (this.sinkPromise = this.makeSink(rate).then((sink) => {
158
+ this.sink = sink;
159
+ sink.setMuted(this.muted);
160
+ sink.onReport((read, playing) => {
161
+ this.read = read;
162
+ this.readAt = this.now();
163
+ this.playing = playing;
164
+ });
165
+ sink.onUnderrun((read) => {
166
+ // Running out at the true end of a reply is not a stutter.
167
+ const atEnd = this.controller.snapshot.ended && this.written - read < 0.05 * sink.sampleRate;
168
+ if (!atEnd) {
169
+ this.stats.underruns++;
170
+ this.emit("underrun", { read });
171
+ }
172
+ });
173
+ this.timer ?? (this.timer = setInterval(() => this.tick(), 20));
174
+ return sink;
175
+ }));
176
+ return this.sinkPromise;
177
+ }
178
+ flushPending() {
179
+ const sink = this.sink;
180
+ if (!sink)
181
+ return;
182
+ while (this.pending.length) {
183
+ const chunk = this.pending.shift();
184
+ let samples = decodePcm16(chunk.audio, chunk.channels);
185
+ if (chunk.sample_rate !== sink.sampleRate)
186
+ samples = resampleLinear(samples, chunk.sample_rate, sink.sampleRate);
187
+ const st = this.controller.state;
188
+ if (st === "idle" || st === "done")
189
+ this.beginReply();
190
+ this.replyPcm.push([this.written, samples]);
191
+ sink.push(samples);
192
+ this.written += samples.length;
193
+ this.lastChunkAt = this.now();
194
+ this.controller.onAudio(this.now(), samples.length / sink.sampleRate);
195
+ this.stats.chunks++;
196
+ this.checkEnded();
197
+ }
198
+ }
199
+ beginReply() {
200
+ this.replyStart = this.written;
201
+ this.replyPcm = [];
202
+ this.announced = null;
203
+ this.heardStarted = false;
204
+ this.endedAt = null;
205
+ // A "stopped" left over from the last reply says nothing about this one.
206
+ if (this.serverSending === false)
207
+ this.serverSending = null;
208
+ this.rtpBase += 10 * RTP_RATE; // a jump the RTP clock reads as a new talk spurt
209
+ }
210
+ checkEnded() {
211
+ const s = this.controller.snapshot;
212
+ if (s.ended || s.state === "idle")
213
+ return;
214
+ if (this.announced != null && s.audio >= this.announced - 0.02)
215
+ this.controller.onEnded();
216
+ }
217
+ heardIndex() {
218
+ const sink = this.sink;
219
+ // Between the worklet's reports (every ~21 ms) the position is extrapolated, but never
220
+ // further than REPORT_STALE past the last one: a worklet that has stopped reporting is not
221
+ // playing. A suspended AudioContext (no user gesture yet) runs no worklet at all, and counting
222
+ // wall time as heard there "played" a reply nobody heard and ran the lipsync clock ahead.
223
+ const since = Math.min(Math.max(0, this.now() - this.readAt), REPORT_STALE);
224
+ const est = this.playing ? this.read + since * sink.sampleRate : this.read;
225
+ return Math.min(est, this.written) - (this.playing ? sink.outputLatency() * sink.sampleRate : 0);
226
+ }
227
+ replyPlayed() {
228
+ return Math.max(0, (this.heardIndex() - this.replyStart) / this.sink.sampleRate);
229
+ }
230
+ tick() {
231
+ const sink = this.sink;
232
+ if (!sink)
233
+ return;
234
+ const t = this.now();
235
+ const s = this.controller.snapshot;
236
+ // Has the reply fully arrived? The server's stop follows its last chunk on the same
237
+ // channel, so once it has stopped nothing more is coming. While it is still sending,
238
+ // a gap is a slow link: ending on it would play a fragment as the whole reply.
239
+ const quiet = t - this.lastChunkAt;
240
+ const endAfter = this.serverSending === false ? 0.25 : this.serverSending ? this.stallEnd : this.idleEnd;
241
+ if (!s.ended && s.state !== "idle" && s.state !== "done" && quiet > endAfter)
242
+ this.controller.onEnded();
243
+ // The sink has played everything this reply had: it is over, whatever the latency estimate says.
244
+ if (s.ended && s.state === "playing" && this.read >= this.written)
245
+ this.controller.finish();
246
+ const syncedEnd = () => Math.min(this.written, this.replyStart + Math.floor(this.controller.synced * sink.sampleRate));
247
+ const searchFrom = () => Math.ceil(this.heardIndex() + 0.05 * sink.sampleRate);
248
+ const silenceAhead = () => this.lastSilence(searchFrom(), syncedEnd() - Math.round(0.02 * sink.sampleRate)) != null;
249
+ const cmd = this.controller.tick(t, this.replyPlayed(), silenceAhead);
250
+ if (cmd === "play") {
251
+ // The worklet's next report says whether it is really playing; asserting it here made a
252
+ // suspended context look like playback.
253
+ sink.play();
254
+ if (this.controller.snapshot.pauses > 0)
255
+ this.emit("resumed", {});
256
+ }
257
+ else if (cmd === "pause") {
258
+ this.stats.pauses++;
259
+ // Only synced audio (blendshapes in hand) may play: stop at its end, or at the last
260
+ // silence before it.
261
+ const end = syncedEnd();
262
+ const at = this.lastSilence(searchFrom(), end - Math.round(0.02 * sink.sampleRate));
263
+ sink.pauseAt(at ?? end);
264
+ this.emit("paused", { atSilence: at != null });
265
+ }
266
+ if (!this.heardStarted && (this.state === "playing" || this.state === "paused") && this.replyPlayed() > 0) {
267
+ this.heardStarted = true;
268
+ this.emit("replyStarted", {});
269
+ }
270
+ if (this.state === "done" && this.endedAt == null) {
271
+ this.endedAt = t;
272
+ if (this.heardStarted)
273
+ this.emit("replyEnded", { interrupted: false });
274
+ }
275
+ }
276
+ /** The last silent window in the buffered audio between two sample indices; null if none. */
277
+ lastSilence(from, to) {
278
+ const rate = this.sink.sampleRate;
279
+ const win = Math.max(1, Math.round(SILENCE_WINDOW * rate));
280
+ let best = null;
281
+ for (const [start, f] of this.replyPcm) {
282
+ for (let i = 0; i + win <= f.length; i += win >> 1) {
283
+ const at = start + i;
284
+ if (at < from || at + win > to)
285
+ continue;
286
+ let sum = 0;
287
+ for (let k = 0; k < win; k++)
288
+ sum += f[i + k] * f[i + k];
289
+ if (Math.sqrt(sum / win) < SILENCE_RMS)
290
+ best = at + (win >> 1);
291
+ }
292
+ }
293
+ return best;
294
+ }
295
+ }
296
+ function resampleLinear(input, from, to) {
297
+ const n = Math.max(1, Math.round((input.length * to) / from));
298
+ const out = new Float32Array(n);
299
+ for (let i = 0; i < n; i++) {
300
+ const x = (i * from) / to;
301
+ const a = Math.floor(x);
302
+ const b = Math.min(a + 1, input.length - 1);
303
+ out[i] = input[a] + (input[b] - input[a]) * (x - a);
304
+ }
305
+ return out;
306
+ }
307
+ // ── The default sink: an AudioWorklet ring buffer ─────────────────────────────
308
+ const RING_SECONDS = 180;
309
+ function workletSource(capacity) {
310
+ return `
311
+ class ConvaiDataAudioRing extends AudioWorkletProcessor {
312
+ constructor() {
313
+ super()
314
+ this.L = ${capacity}; this.buf = new Float32Array(this.L); this.w = 0; this.r = 0
315
+ this.playing = false; this.pauseAt = -1; this.n = 0; this.under = false
316
+ this.port.onmessage = (e) => {
317
+ const m = e.data
318
+ 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 }
319
+ else if (m.cmd === 'play') { this.playing = true; this.pauseAt = -1; this.under = false }
320
+ else if (m.cmd === 'pauseAt') { this.pauseAt = Math.max(this.r, m.at) }
321
+ else if (m.cmd === 'clear') { this.r = this.w; this.playing = false; this.pauseAt = -1 }
322
+ }
323
+ }
324
+ process(_inputs, outputs) {
325
+ const out = outputs[0][0]
326
+ for (let i = 0; i < out.length; i++) {
327
+ if (this.playing && this.pauseAt >= 0 && this.r >= this.pauseAt) { this.playing = false; this.pauseAt = -1 }
328
+ if (this.playing && this.r < this.w) { out[i] = this.buf[this.r % this.L]; this.r++ }
329
+ else { out[i] = 0; if (this.playing && !this.under) { this.under = true; this.port.postMessage({ ev: 'underrun', r: this.r }) } }
330
+ }
331
+ if (++this.n % 4 === 0) this.port.postMessage({ ev: 'pos', r: this.r, playing: this.playing })
332
+ return true
333
+ }
334
+ }
335
+ registerProcessor('convai-data-audio-ring', ConvaiDataAudioRing)`;
336
+ }
337
+ const GESTURES = ["pointerdown", "keydown", "touchstart"];
338
+ /** An AudioWorklet ring buffer at the stream's own sample rate (no per-chunk resampling). */
339
+ export async function createWorkletSink(sampleRate) {
340
+ const ctx = new AudioContext({ sampleRate });
341
+ const url = URL.createObjectURL(new Blob([workletSource(sampleRate * RING_SECONDS)], { type: "text/javascript" }));
342
+ try {
343
+ await ctx.audioWorklet.addModule(url);
344
+ }
345
+ finally {
346
+ URL.revokeObjectURL(url);
347
+ }
348
+ const node = new AudioWorkletNode(ctx, "convai-data-audio-ring", { numberOfOutputs: 1, outputChannelCount: [1] });
349
+ const gain = ctx.createGain();
350
+ const analyser = ctx.createAnalyser();
351
+ analyser.fftSize = 512;
352
+ node.connect(gain);
353
+ gain.connect(analyser);
354
+ analyser.connect(ctx.destination);
355
+ const abuf = new Float32Array(analyser.fftSize);
356
+ let report = () => { };
357
+ let underrun = () => { };
358
+ node.port.onmessage = (e) => {
359
+ const m = e.data;
360
+ if (m.ev === "pos")
361
+ report(m.r, m.playing);
362
+ else if (m.ev === "underrun")
363
+ underrun(m.r);
364
+ };
365
+ // Autoplay policy: a context made before a gesture starts suspended.
366
+ const unlock = () => { void ctx.resume(); };
367
+ if (typeof document !== "undefined")
368
+ for (const g of GESTURES)
369
+ document.addEventListener(g, unlock, { capture: true, passive: true });
370
+ if (ctx.state !== "running")
371
+ void ctx.resume().catch(() => { });
372
+ return {
373
+ sampleRate: ctx.sampleRate,
374
+ push: (samples) => {
375
+ if (ctx.state !== "running")
376
+ void ctx.resume().catch(() => { });
377
+ node.port.postMessage({ cmd: "push", samples });
378
+ },
379
+ play: () => node.port.postMessage({ cmd: "play" }),
380
+ pauseAt: (index) => node.port.postMessage({ cmd: "pauseAt", at: index }),
381
+ clear: () => node.port.postMessage({ cmd: "clear" }),
382
+ setMuted: (muted) => { gain.gain.value = muted ? 0 : 1; },
383
+ level: () => {
384
+ if (ctx.state !== "running")
385
+ return null;
386
+ analyser.getFloatTimeDomainData(abuf);
387
+ let s = 0;
388
+ for (let i = 0; i < abuf.length; i++)
389
+ s += abuf[i] * abuf[i];
390
+ return Math.sqrt(s / abuf.length);
391
+ },
392
+ outputLatency: () => ctx.outputLatency || ctx.baseLatency || 0,
393
+ onReport: (cb) => { report = cb; },
394
+ onUnderrun: (cb) => { underrun = cb; },
395
+ resume: () => ctx.resume(),
396
+ dispose: () => {
397
+ if (typeof document !== "undefined")
398
+ for (const g of GESTURES)
399
+ document.removeEventListener(g, unlock, { capture: true });
400
+ node.disconnect();
401
+ void ctx.close().catch(() => { });
402
+ },
403
+ };
404
+ }
@@ -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);
@@ -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';
@@ -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
+ }