Skip to content

Commit 42c3139

Browse files
committed
fix(voice-call): avoid audio pacing slowdowns on long replies (#117162)
Merge PR #117162 without squash to preserve the signed commit series.
2 parents 7fba71e + cd1e3b4 commit 42c3139

2 files changed

Lines changed: 110 additions & 5 deletions

File tree

‎extensions/voice-call/src/webhook/realtime-audio-pacer.test.ts‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,27 @@ function createTelnyxSerializer(): RealtimeAudioSerializer {
2020
};
2121
}
2222

23+
function createCompactSerializer(): RealtimeAudioSerializer {
24+
return {
25+
media: (payload) => payload,
26+
clear: () => "clear",
27+
mark: (name) => `mark:${name}`,
28+
};
29+
}
30+
31+
function createSequencedAudio(frameCount: number): Buffer {
32+
const audio = Buffer.alloc(frameCount * 160);
33+
for (let index = 0; index < frameCount; index += 1) {
34+
audio.fill(index % 256, index * 160, (index + 1) * 160);
35+
}
36+
return audio;
37+
}
38+
39+
function inspectQueue(pacer: RealtimeAudioPacer): { length: number; head: number } {
40+
const state = pacer as unknown as { queue: unknown[]; queueHead: number };
41+
return { length: state.queue.length, head: state.queueHead };
42+
}
43+
2344
describe("RealtimeAudioPacer", () => {
2445
afterEach(() => {
2546
vi.useRealTimers();
@@ -119,4 +140,57 @@ describe("RealtimeAudioPacer", () => {
119140
{ event: "clear" },
120141
]);
121142
});
143+
144+
it("drains the full default audio backlog in order and resets queue storage", async () => {
145+
vi.useFakeTimers();
146+
const frameCount = 6_000;
147+
const sentFrames: number[] = [];
148+
const sentMarks: string[] = [];
149+
const pacer = new RealtimeAudioPacer({
150+
serializer: createCompactSerializer(),
151+
send: (message) => {
152+
if (message.startsWith("mark:")) {
153+
sentMarks.push(message);
154+
} else {
155+
sentFrames.push(Buffer.from(message, "base64")[0] ?? -1);
156+
}
157+
return true;
158+
},
159+
});
160+
161+
pacer.sendAudio(createSequencedAudio(frameCount));
162+
pacer.sendMark("complete");
163+
await vi.advanceTimersByTimeAsync(frameCount * 20);
164+
165+
expect(sentFrames).toEqual(Array.from({ length: frameCount }, (_, index) => index % 256));
166+
expect(sentMarks).toEqual(["mark:complete"]);
167+
expect(inspectQueue(pacer)).toEqual({ length: 0, head: 0 });
168+
expect(pacer.hasPendingAudio()).toBe(false);
169+
});
170+
171+
it("compacts a long queue while preserving pending bytes through clear", async () => {
172+
vi.useFakeTimers();
173+
const frameCount = 800;
174+
const sent: string[] = [];
175+
const pacer = new RealtimeAudioPacer({
176+
serializer: createCompactSerializer(),
177+
send: (message) => {
178+
sent.push(message);
179+
return true;
180+
},
181+
});
182+
183+
pacer.sendAudio(createSequencedAudio(frameCount));
184+
await vi.advanceTimersByTimeAsync(500 * 20);
185+
186+
expect(sent).toHaveLength(501);
187+
expect(inspectQueue(pacer)).toEqual({ length: 399, head: 100 });
188+
expect(pacer.clearAudio()).toBe(299 * 160);
189+
await vi.advanceTimersByTimeAsync(frameCount * 20);
190+
191+
expect(sent).toHaveLength(502);
192+
expect(sent.at(-1)).toBe("clear");
193+
expect(inspectQueue(pacer)).toEqual({ length: 0, head: 0 });
194+
expect(pacer.hasPendingAudio()).toBe(false);
195+
});
122196
});

‎extensions/voice-call/src/webhook/realtime-audio-pacer.ts‎

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ const TELEPHONY_SAMPLE_RATE = 8_000;
44
const TELEPHONY_CHUNK_BYTES = 160;
55
const TELEPHONY_CHUNK_MS = 20;
66
const DEFAULT_MAX_QUEUED_AUDIO_BYTES = TELEPHONY_SAMPLE_RATE * 120;
7+
const QUEUE_COMPACT_HEAD_THRESHOLD = 256;
78

89
/** Queue item sent over the realtime provider media stream. */
910
type RealtimeAudioQueueItem =
@@ -30,6 +31,7 @@ interface RealtimeAudioSerializer {
3031
/** Paces outgoing mulaw audio frames at telephony cadence. */
3132
export class RealtimeAudioPacer {
3233
private queue: RealtimeAudioQueueItem[] = [];
34+
private queueHead = 0;
3335
private timer: ReturnType<typeof setTimeout> | null = null;
3436
private queuedAudioBytes = 0;
3537
private closed = false;
@@ -81,7 +83,7 @@ export class RealtimeAudioPacer {
8183
}
8284
const clearedAudioBytes = this.queuedAudioBytes;
8385
this.clearTimer();
84-
this.queue = [];
86+
this.resetQueue();
8587
this.queuedAudioBytes = 0;
8688
this.params.send(this.params.serializer.clear());
8789
return clearedAudioBytes;
@@ -96,7 +98,7 @@ export class RealtimeAudioPacer {
9698
close(): void {
9799
this.closed = true;
98100
this.clearTimer();
99-
this.queue = [];
101+
this.resetQueue();
100102
this.queuedAudioBytes = 0;
101103
}
102104

@@ -122,13 +124,42 @@ export class RealtimeAudioPacer {
122124
this.params.onBackpressure?.();
123125
}
124126

127+
private get pendingQueueSize(): number {
128+
return Math.max(0, this.queue.length - this.queueHead);
129+
}
130+
131+
/** Take one queued item without shifting the remaining paced-audio backlog. */
132+
private takeNextItem(): RealtimeAudioQueueItem | undefined {
133+
if (this.queueHead >= this.queue.length) {
134+
this.resetQueue();
135+
return undefined;
136+
}
137+
const item = this.queue[this.queueHead];
138+
this.queueHead += 1;
139+
if (this.queueHead >= this.queue.length) {
140+
this.resetQueue();
141+
} else if (
142+
this.queueHead > QUEUE_COMPACT_HEAD_THRESHOLD &&
143+
this.queueHead * 2 > this.queue.length
144+
) {
145+
this.queue.splice(0, this.queueHead);
146+
this.queueHead = 0;
147+
}
148+
return item;
149+
}
150+
151+
private resetQueue(): void {
152+
this.queue.length = 0;
153+
this.queueHead = 0;
154+
}
155+
125156
/** Send one queued item and schedule the next send based on audio duration. */
126157
private pump(): void {
127158
this.timer = null;
128159
if (this.closed) {
129160
return;
130161
}
131-
const item = this.queue.shift();
162+
const item = this.takeNextItem();
132163
if (!item) {
133164
return;
134165
}
@@ -144,11 +175,11 @@ export class RealtimeAudioPacer {
144175
}
145176

146177
if (!sent) {
147-
this.queue = [];
178+
this.resetQueue();
148179
this.queuedAudioBytes = 0;
149180
return;
150181
}
151-
if (this.queue.length > 0) {
182+
if (this.pendingQueueSize > 0) {
152183
this.timer = setTimeout(() => this.pump(), delayMs);
153184
}
154185
}

0 commit comments

Comments
 (0)