Skip to content

Commit 2291171

Browse files
committed
Merge pull request #116734 from vincentkoc/fix/talk-pcm-output-budget
* commit 'b2b3515e04e9780e7c76a6533c35a6c384ed638e': fix(ui): reject oversized Talk audio before decoding fix(ui): cancel overflowing realtime Talk playback fix(ui): bound realtime Talk PCM playback ownership
2 parents 4e4f76f + b2b3515 commit 2291171

6 files changed

Lines changed: 409 additions & 24 deletions

‎ui/src/pages/chat/realtime-talk-audio.test.ts‎

Lines changed: 148 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,52 @@
11
// @vitest-environment jsdom
22
import { afterEach, describe, expect, it, vi } from "vitest";
3-
import { RealtimeTalkMediaStreamMeter } from "./realtime-talk-audio.ts";
3+
import {
4+
bytesToBase64,
5+
RealtimeTalkMediaStreamMeter,
6+
RealtimeTalkPcmOutputQueue,
7+
} from "./realtime-talk-audio.ts";
8+
9+
class MockAudioBufferSource {
10+
buffer: unknown = null;
11+
readonly connect = vi.fn();
12+
readonly start = vi.fn();
13+
readonly stop = vi.fn();
14+
private ended: (() => void) | null = null;
15+
16+
addEventListener(type: string, handler: () => void): void {
17+
if (type === "ended") {
18+
this.ended = handler;
19+
}
20+
}
21+
22+
emitEnded(): void {
23+
this.ended?.();
24+
}
25+
}
26+
27+
class MockOutputAudioContext {
28+
currentTime = 0;
29+
readonly destination = {};
30+
readonly sources: MockAudioBufferSource[] = [];
31+
32+
createBuffer(_channels: number, length: number, sampleRate: number) {
33+
const channel = new Float32Array(length);
34+
return {
35+
duration: length / sampleRate,
36+
getChannelData: () => channel,
37+
};
38+
}
39+
40+
createBufferSource(): MockAudioBufferSource {
41+
const source = new MockAudioBufferSource();
42+
this.sources.push(source);
43+
return source;
44+
}
45+
}
46+
47+
function silentPcmBase64(sampleCount: number): string {
48+
return bytesToBase64(new Uint8Array(sampleCount * 2));
49+
}
450

551
describe("RealtimeTalkMediaStreamMeter", () => {
652
afterEach(() => {
@@ -66,3 +112,104 @@ describe("RealtimeTalkMediaStreamMeter", () => {
66112
expect(onLevel).toHaveBeenLastCalledWith(0);
67113
});
68114
});
115+
116+
describe("RealtimeTalkPcmOutputQueue", () => {
117+
it("preserves ordered playback while the AudioContext advances normally", () => {
118+
const context = new MockOutputAudioContext();
119+
context.currentTime = 1;
120+
const queue = new RealtimeTalkPcmOutputQueue();
121+
122+
expect(queue.play(silentPcmBase64(100), context as unknown as AudioContext, 100)).toBe(
123+
"queued",
124+
);
125+
context.currentTime = 1.5;
126+
expect(queue.play(silentPcmBase64(50), context as unknown as AudioContext, 100)).toBe("queued");
127+
128+
expect(context.sources.map((source) => source.start.mock.calls[0]?.[0])).toEqual([1, 2]);
129+
expect(queue.queuedUntil).toBe(2.5);
130+
expect(queue.isPlaying).toBe(true);
131+
});
132+
133+
it("bounds a frozen AudioContext by queued seconds before allocating another source", () => {
134+
const context = new MockOutputAudioContext();
135+
const queue = new RealtimeTalkPcmOutputQueue();
136+
137+
expect(queue.play(silentPcmBase64(600), context as unknown as AudioContext, 100)).toBe(
138+
"queued",
139+
);
140+
expect(queue.play(silentPcmBase64(500), context as unknown as AudioContext, 100)).toBe(
141+
"overflow",
142+
);
143+
144+
expect(context.sources).toHaveLength(1);
145+
expect(queue.queuedUntil).toBe(6);
146+
});
147+
148+
it("rejects an oversized frame before base64 decoding", () => {
149+
const context = new MockOutputAudioContext();
150+
const queue = new RealtimeTalkPcmOutputQueue();
151+
152+
expect(queue.play("!".repeat(3_000), context as unknown as AudioContext, 100)).toBe("overflow");
153+
expect(context.sources).toHaveLength(0);
154+
});
155+
156+
it("hard-caps source ownership across ten thousand suspended-context chunks", () => {
157+
const context = new MockOutputAudioContext();
158+
const queue = new RealtimeTalkPcmOutputQueue();
159+
let queued = 0;
160+
let overflowed = 0;
161+
162+
for (let index = 0; index < 10_000; index += 1) {
163+
const result = queue.play(silentPcmBase64(1), context as unknown as AudioContext, 48_000);
164+
if (result === "queued") {
165+
queued += 1;
166+
} else if (result === "overflow") {
167+
overflowed += 1;
168+
}
169+
}
170+
171+
expect(queued).toBe(320);
172+
expect(overflowed).toBe(9_680);
173+
expect(context.sources).toHaveLength(320);
174+
});
175+
176+
it("releases source ownership on ended", () => {
177+
const context = new MockOutputAudioContext();
178+
const queue = new RealtimeTalkPcmOutputQueue();
179+
const chunk = silentPcmBase64(1);
180+
181+
for (let index = 0; index < 320; index += 1) {
182+
expect(queue.play(chunk, context as unknown as AudioContext, 48_000)).toBe("queued");
183+
}
184+
expect(queue.play(chunk, context as unknown as AudioContext, 48_000)).toBe("overflow");
185+
186+
context.sources[0]?.emitEnded();
187+
188+
expect(queue.play(chunk, context as unknown as AudioContext, 48_000)).toBe("queued");
189+
expect(context.sources).toHaveLength(321);
190+
});
191+
192+
it("stops idempotently and isolates late ended events from replacement playback", () => {
193+
const context = new MockOutputAudioContext();
194+
const queue = new RealtimeTalkPcmOutputQueue();
195+
const chunk = silentPcmBase64(100);
196+
197+
expect(queue.play(chunk, context as unknown as AudioContext, 100)).toBe("queued");
198+
const oldSource = context.sources[0];
199+
context.currentTime = 0.25;
200+
queue.stop(context as unknown as AudioContext);
201+
queue.stop(context as unknown as AudioContext);
202+
203+
expect(oldSource?.stop).toHaveBeenCalledOnce();
204+
expect(queue.isPlaying).toBe(false);
205+
expect(queue.queuedUntil).toBe(0.25);
206+
207+
expect(queue.play(chunk, context as unknown as AudioContext, 100)).toBe("queued");
208+
const replacementSource = context.sources[1];
209+
oldSource?.emitEnded();
210+
211+
expect(queue.isPlaying).toBe(true);
212+
expect(queue.queuedUntil).toBe(1.25);
213+
expect(replacementSource?.stop).not.toHaveBeenCalled();
214+
});
215+
});

‎ui/src/pages/chat/realtime-talk-audio.ts‎

Lines changed: 43 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ export function bytesToBase64(bytes: Uint8Array): string {
99
return btoa(binary);
1010
}
1111

12-
export function base64ToBytes(value: string): Uint8Array {
12+
function base64ToBytes(value: string): Uint8Array {
1313
const binary = atob(value);
1414
const bytes = new Uint8Array(binary.length);
1515
for (let i = 0; i < binary.length; i += 1) {
@@ -214,6 +214,16 @@ function pcm16ToFloat(bytes: Uint8Array): Float32Array {
214214
return samples;
215215
}
216216

217+
export function estimateBase64DecodedByteLength(value: string): number {
218+
const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
219+
return Math.max(0, Math.floor((value.length * 3) / 4) - padding);
220+
}
221+
222+
const REALTIME_TALK_PCM_OUTPUT_MAX_QUEUED_SECONDS = 10;
223+
const REALTIME_TALK_PCM_OUTPUT_MAX_SOURCES = 320;
224+
225+
type RealtimeTalkPcmOutputQueuePlayResult = "queued" | "ignored" | "overflow";
226+
217227
export class RealtimeTalkPcmOutputQueue {
218228
private playhead = 0;
219229
private readonly sources = new Set<AudioBufferSourceNode>();
@@ -226,13 +236,34 @@ export class RealtimeTalkPcmOutputQueue {
226236
return this.sources.size > 0;
227237
}
228238

229-
play(base64: string, outputContext: AudioContext | null, outputSampleRateHz: number): void {
239+
play(
240+
base64: string,
241+
outputContext: AudioContext | null,
242+
outputSampleRateHz: number,
243+
): RealtimeTalkPcmOutputQueuePlayResult {
230244
if (!outputContext) {
231-
return;
245+
return "ignored";
246+
}
247+
const startAt = Math.max(outputContext.currentTime, this.playhead);
248+
const queuedSeconds = Math.max(0, startAt - outputContext.currentTime);
249+
const remainingSeconds = REALTIME_TALK_PCM_OUTPUT_MAX_QUEUED_SECONDS - queuedSeconds;
250+
const decodedByteLength = estimateBase64DecodedByteLength(base64);
251+
const sampleCount = Math.floor(decodedByteLength / 2);
252+
if (
253+
this.sources.size >= REALTIME_TALK_PCM_OUTPUT_MAX_SOURCES ||
254+
remainingSeconds <= 0 ||
255+
sampleCount / outputSampleRateHz > remainingSeconds
256+
) {
257+
return "overflow";
232258
}
233259
const samples = pcm16ToFloat(base64ToBytes(base64));
234260
if (samples.length === 0) {
235-
return;
261+
return "ignored";
262+
}
263+
const duration = samples.length / outputSampleRateHz;
264+
const nextPlayhead = startAt + duration;
265+
if (nextPlayhead - outputContext.currentTime > REALTIME_TALK_PCM_OUTPUT_MAX_QUEUED_SECONDS) {
266+
return "overflow";
236267
}
237268
const buffer = outputContext.createBuffer(1, samples.length, outputSampleRateHz);
238269
buffer.getChannelData(0).set(samples);
@@ -241,18 +272,21 @@ export class RealtimeTalkPcmOutputQueue {
241272
source.addEventListener("ended", () => this.sources.delete(source));
242273
source.buffer = buffer;
243274
source.connect(outputContext.destination);
244-
const startAt = Math.max(outputContext.currentTime, this.playhead);
245275
source.start(startAt);
246-
this.playhead = startAt + buffer.duration;
276+
this.playhead = nextPlayhead;
277+
return "queued";
247278
}
248279

249280
stop(outputContext: AudioContext | null): void {
250-
for (const source of this.sources) {
281+
// Release ownership first so synchronous or late `ended` events from stopped
282+
// sources cannot affect audio queued by a replacement playback turn.
283+
const sources = [...this.sources];
284+
this.sources.clear();
285+
this.playhead = outputContext?.currentTime ?? 0;
286+
for (const source of sources) {
251287
try {
252288
source.stop();
253289
} catch {}
254290
}
255-
this.sources.clear();
256-
this.playhead = outputContext?.currentTime ?? 0;
257291
}
258292
}

‎ui/src/pages/chat/realtime-talk-gateway-relay.test.ts‎

Lines changed: 87 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,18 @@ const inputSinks: Array<{
2626
disconnect: ReturnType<typeof vi.fn>;
2727
gain: { value: number };
2828
}> = [];
29+
const createdSources: MockAudioBufferSource[] = [];
2930
let getUserMedia: ReturnType<typeof vi.fn>;
3031
let audioCurrentTime = 0;
3132

33+
class MockAudioBufferSource {
34+
buffer: unknown = null;
35+
readonly addEventListener = vi.fn();
36+
readonly connect = vi.fn();
37+
readonly start = vi.fn();
38+
readonly stop = vi.fn();
39+
}
40+
3241
class MockAudioContext {
3342
get currentTime(): number {
3443
return audioCurrentTime;
@@ -81,13 +90,9 @@ class MockAudioContext {
8190
}
8291

8392
createBufferSource() {
84-
return {
85-
addEventListener: vi.fn(),
86-
buffer: null,
87-
connect: vi.fn(),
88-
start: vi.fn(),
89-
stop: vi.fn(),
90-
};
93+
const source = new MockAudioBufferSource();
94+
createdSources.push(source);
95+
return source;
9196
}
9297
}
9398

@@ -162,6 +167,7 @@ describe("GatewayRelayRealtimeTalkTransport", () => {
162167
listeners.clear();
163168
processors.length = 0;
164169
inputSinks.length = 0;
170+
createdSources.length = 0;
165171
audioCurrentTime = 0;
166172
vi.stubGlobal("AudioContext", MockAudioContext);
167173
getUserMedia = vi.fn(async () => ({
@@ -181,6 +187,7 @@ describe("GatewayRelayRealtimeTalkTransport", () => {
181187
listeners.clear();
182188
processors.length = 0;
183189
inputSinks.length = 0;
190+
createdSources.length = 0;
184191
});
185192

186193
it("preserves audio processing while selecting the exact microphone", async () => {
@@ -325,6 +332,79 @@ describe("GatewayRelayRealtimeTalkTransport", () => {
325332
transport.stop();
326333
});
327334

335+
it("cancels overflowing playback and ignores late audio until provider clear", async () => {
336+
const client = createClient();
337+
const transport = createTransport({ client });
338+
339+
await transport.start();
340+
for (let index = 0; index < 321; index += 1) {
341+
emitTalkEvent({
342+
relaySessionId: "relay-1",
343+
type: "audio",
344+
audioBase64: "AAAA",
345+
});
346+
}
347+
348+
await waitForFast(() =>
349+
expect(requestCallsFor(client, "talk.session.cancelOutput")).toEqual([
350+
[
351+
"talk.session.cancelOutput",
352+
{
353+
sessionId: "relay-1",
354+
reason: "playback-overflow",
355+
},
356+
],
357+
]),
358+
);
359+
expect(createdSources).toHaveLength(320);
360+
expect(createdSources.every((source) => source.stop.mock.calls.length === 1)).toBe(true);
361+
362+
emitTalkEvent({
363+
relaySessionId: "relay-1",
364+
type: "audio",
365+
audioBase64: "AAAA",
366+
});
367+
expect(createdSources).toHaveLength(320);
368+
369+
emitTalkEvent({ relaySessionId: "relay-1", type: "clear" });
370+
emitTalkEvent({
371+
relaySessionId: "relay-1",
372+
type: "audio",
373+
audioBase64: "AAAA",
374+
});
375+
expect(createdSources).toHaveLength(321);
376+
expect(createdSources.at(-1)?.start).toHaveBeenCalledOnce();
377+
378+
transport.stop();
379+
});
380+
381+
it("cancels provider output when the first audio chunk exceeds the time budget", async () => {
382+
const client = createClient();
383+
const transport = createTransport({ client });
384+
385+
await transport.start();
386+
emitTalkEvent({
387+
relaySessionId: "relay-1",
388+
type: "audio",
389+
audioBase64: zeroPcmBase64(24000 * 11),
390+
});
391+
392+
await waitForFast(() =>
393+
expect(requestCallsFor(client, "talk.session.cancelOutput")).toEqual([
394+
[
395+
"talk.session.cancelOutput",
396+
{
397+
sessionId: "relay-1",
398+
reason: "playback-overflow",
399+
},
400+
],
401+
]),
402+
);
403+
expect(createdSources).toHaveLength(0);
404+
405+
transport.stop();
406+
});
407+
328408
it("acknowledges provider marks only after the local playback queue drains", async () => {
329409
vi.useFakeTimers();
330410
const client = createClient();

0 commit comments

Comments
 (0)