Skip to content

Commit 10b0557

Browse files
committed
refactor(realtime): share audio duration calculation
Fix xAI barge-in truncation that reported 3760 ms after only 3700 ms of decoded audio. Share exact audio-duration math across OpenAI, xAI, and Google while keeping provider-specific rounding at each caller.
1 parent 916aca1 commit 10b0557

8 files changed

Lines changed: 104 additions & 55 deletions

‎extensions/google/realtime-voice-provider.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import {
4242
REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ,
4343
REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ,
4444
REALTIME_VOICE_AGENT_CONSULT_TOOL_NAME,
45+
realtimeVoiceAudioDurationMs,
4546
resamplePcm,
4647
} from "openclaw/plugin-sdk/realtime-voice";
4748
import { warn } from "openclaw/plugin-sdk/runtime-env";
@@ -693,9 +694,8 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
693694
typeof this.config.silenceDurationMs === "number"
694695
? Math.max(0, Math.floor(this.config.silenceDurationMs))
695696
: DEFAULT_AUDIO_STREAM_END_SILENCE_MS;
696-
const bytesPerSample = this.audioFormat.encoding === "pcm16" ? 2 : 1;
697697
this.consecutiveSilenceMs += Math.round(
698-
(audio.length / bytesPerSample / this.audioFormat.sampleRateHz) * 1000,
698+
realtimeVoiceAudioDurationMs(this.audioFormat, audio.length),
699699
);
700700
if (!this.audioStreamEnded && this.consecutiveSilenceMs >= silenceThresholdMs) {
701701
this.session.sendRealtimeInput({ audioStreamEnd: true });

‎extensions/openai/realtime-voice-protocol.ts‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ import type {
44
RealtimeVoiceBargeInOptions,
55
RealtimeVoiceToolResultOptions,
66
} from "openclaw/plugin-sdk/realtime-voice";
7-
import { REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ } from "openclaw/plugin-sdk/realtime-voice";
7+
import {
8+
REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ,
9+
realtimeVoiceAudioDurationMs,
10+
} from "openclaw/plugin-sdk/realtime-voice";
811
import {
912
AZURE_OPENAI_REALTIME_TOOL_NAME_MAX_LENGTH,
1013
OPENAI_REALTIME_DEFAULT_MIN_BARGE_IN_AUDIO_END_MS,
@@ -239,14 +242,10 @@ export abstract class OpenAIRealtimeProtocol {
239242
(this.oldestOutstandingMarkSequence !== null ||
240243
options?.audioPlaybackActive === true ||
241244
force);
242-
const bytesPerSample = this.audioFormat.encoding === "pcm16" ? 2 : 1;
243245
const audioEndMs =
244246
shouldInterruptProvider && assistantAudioItem
245247
? Math.min(
246-
Math.floor(
247-
(assistantAudioItem.bytes * 1000) /
248-
(this.audioFormat.sampleRateHz * this.audioFormat.channels * bytesPerSample),
249-
),
248+
Math.floor(realtimeVoiceAudioDurationMs(this.audioFormat, assistantAudioItem.bytes)),
250249
Math.max(0, this.latestMediaTimestamp - assistantAudioItem.startTimestamp),
251250
)
252251
: null;

‎extensions/xai/realtime-voice-events.ts‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,7 @@ export abstract class XaiRealtimeVoiceEvents extends XaiRealtimeVoiceProtocol {
7272
this.responseActive = true;
7373
this.responseCreateInFlight = false;
7474
this.markQueue = [];
75-
this.lastAssistantItemId = null;
76-
this.responseStartTimestamp = null;
75+
this.assistantAudioItem = null;
7776
this.resetAssistantTranscript();
7877
return;
7978
case "response.output_audio.delta": {
@@ -87,12 +86,17 @@ export abstract class XaiRealtimeVoiceEvents extends XaiRealtimeVoiceProtocol {
8786
"xAI realtime voice stream returned malformed base64 audio data",
8887
);
8988
}
90-
this.emitAudioWithPlaybackMark(Buffer.from(canonicalAudio, "base64"));
91-
if (event.item_id && event.item_id !== this.lastAssistantItemId) {
92-
this.lastAssistantItemId = event.item_id;
93-
this.responseStartTimestamp = this.latestMediaTimestamp;
94-
} else if (this.responseStartTimestamp === null) {
95-
this.responseStartTimestamp = this.latestMediaTimestamp;
89+
const audio = Buffer.from(canonicalAudio, "base64");
90+
this.emitAudioWithPlaybackMark(audio);
91+
if (event.item_id && event.item_id !== this.assistantAudioItem?.itemId) {
92+
this.assistantAudioItem = {
93+
itemId: event.item_id,
94+
bytes: 0,
95+
startTimestamp: this.latestMediaTimestamp,
96+
};
97+
}
98+
if (this.assistantAudioItem) {
99+
this.assistantAudioItem.bytes += audio.byteLength;
96100
}
97101
this.responseActive = true;
98102
return;

‎extensions/xai/realtime-voice-protocol.ts‎

Lines changed: 29 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@ import type {
55
RealtimeVoiceSessionConnection,
66
RealtimeVoiceToolResultOptions,
77
} from "openclaw/plugin-sdk/realtime-voice";
8-
import { REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ } from "openclaw/plugin-sdk/realtime-voice";
8+
import {
9+
REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ,
10+
realtimeVoiceAudioDurationMs,
11+
} from "openclaw/plugin-sdk/realtime-voice";
912
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
1013
import {
1114
XAI_REALTIME_DEFAULT_PREFIX_PADDING_MS,
@@ -22,18 +25,23 @@ import {
2225

2326
export class XaiRealtimePlaybackMarkOverflowError extends Error {}
2427

28+
type XaiAssistantAudioItem = {
29+
itemId: string;
30+
bytes: number;
31+
startTimestamp: number;
32+
};
33+
2534
export abstract class XaiRealtimeVoiceProtocol {
2635
protected readonly audioFormat: RealtimeVoiceAudioFormat;
2736
protected markQueue: string[] = [];
28-
protected responseStartTimestamp: number | null = null;
2937
protected responseActive = false;
3038
protected responseCreateInFlight = false;
3139
protected responseCancelInFlight = false;
3240
protected responseCreatePending = false;
3341
protected continuingToolCallIds = new Set<string>();
3442
protected pendingToolCallIds = new Set<string>();
3543
protected latestMediaTimestamp = 0;
36-
protected lastAssistantItemId: string | null = null;
44+
protected assistantAudioItem: XaiAssistantAudioItem | null = null;
3745
protected toolCallBuffers = new Map<string, { name: string; callId: string; args: string }>();
3846
protected deliveredToolCallKeys = new Set<string>();
3947
protected pendingToolResultAcks = new Set<string>();
@@ -101,20 +109,11 @@ export abstract class XaiRealtimeVoiceProtocol {
101109
}
102110

103111
handleBargeIn(options?: RealtimeVoiceBargeInOptions): void {
104-
const assistantItemId = this.lastAssistantItemId;
105-
const responseStartTimestamp = this.responseStartTimestamp;
106-
const outputInterruptible =
107-
responseStartTimestamp !== null &&
112+
const assistantAudioItem = this.assistantAudioItem;
113+
const shouldInterruptProvider =
114+
assistantAudioItem !== null &&
108115
(this.responseActive || this.markQueue.length > 0 || options?.audioPlaybackActive === true);
109-
const shouldInterruptProvider = assistantItemId !== null && outputInterruptible;
110-
const audioEndMs = shouldInterruptProvider
111-
? Math.max(
112-
0,
113-
responseStartTimestamp === null
114-
? this.latestMediaTimestamp
115-
: this.latestMediaTimestamp - responseStartTimestamp,
116-
)
117-
: null;
116+
const audioEndMs = shouldInterruptProvider ? this.audioEndMs(assistantAudioItem) : null;
118117
if (this.responseActive && !this.responseCancelInFlight) {
119118
this.sendEvent({ type: "response.cancel" }, "reason=barge-in");
120119
this.responseCancelInFlight = true;
@@ -123,16 +122,15 @@ export abstract class XaiRealtimeVoiceProtocol {
123122
this.sendEvent(
124123
{
125124
type: "conversation.item.truncate",
126-
item_id: assistantItemId,
125+
item_id: assistantAudioItem.itemId,
127126
content_index: 0,
128127
audio_end_ms: audioEndMs,
129128
},
130129
`reason=barge-in audioEndMs=${audioEndMs}`,
131130
);
132131
this.config.onClearAudio("barge-in");
133132
this.markQueue = [];
134-
this.lastAssistantItemId = null;
135-
this.responseStartTimestamp = null;
133+
this.assistantAudioItem = null;
136134
return;
137135
}
138136
this.config.onClearAudio("barge-in");
@@ -142,16 +140,13 @@ export abstract class XaiRealtimeVoiceProtocol {
142140
protected handleServerVadBargeIn(): void {
143141
// xAI owns server-VAD cancellation, but only the relay knows how much
144142
// queued audio actually played. Trim provider history to that boundary.
145-
if (
146-
this.lastAssistantItemId !== null &&
147-
this.responseStartTimestamp !== null &&
148-
this.markQueue.length > 0
149-
) {
150-
const audioEndMs = Math.max(0, this.latestMediaTimestamp - this.responseStartTimestamp);
143+
const assistantAudioItem = this.assistantAudioItem;
144+
if (assistantAudioItem !== null && this.markQueue.length > 0) {
145+
const audioEndMs = this.audioEndMs(assistantAudioItem);
151146
this.sendEvent(
152147
{
153148
type: "conversation.item.truncate",
154-
item_id: this.lastAssistantItemId,
149+
item_id: assistantAudioItem.itemId,
155150
content_index: 0,
156151
audio_end_ms: audioEndMs,
157152
},
@@ -160,8 +155,13 @@ export abstract class XaiRealtimeVoiceProtocol {
160155
}
161156
this.config.onClearAudio("barge-in");
162157
this.markQueue = [];
163-
this.lastAssistantItemId = null;
164-
this.responseStartTimestamp = null;
158+
this.assistantAudioItem = null;
159+
}
160+
161+
private audioEndMs(item: XaiAssistantAudioItem): number {
162+
const producedAudioMs = Math.floor(realtimeVoiceAudioDurationMs(this.audioFormat, item.bytes));
163+
const playbackAudioMs = Math.max(0, this.latestMediaTimestamp - item.startTimestamp);
164+
return Math.min(producedAudioMs, playbackAudioMs);
165165
}
166166

167167
protected buildSessionUpdate(): XaiRealtimeSessionUpdate {
@@ -300,12 +300,11 @@ export abstract class XaiRealtimeVoiceProtocol {
300300

301301
protected resetRealtimeSessionState(options: { preserveToolCallState?: boolean } = {}): void {
302302
this.markQueue = [];
303-
this.responseStartTimestamp = null;
304303
this.responseActive = false;
305304
this.responseCreateInFlight = false;
306305
this.responseCancelInFlight = false;
307306
this.responseCreatePending = false;
308-
this.lastAssistantItemId = null;
307+
this.assistantAudioItem = null;
309308
this.resetInputTranscripts();
310309
if (!options.preserveToolCallState) {
311310
this.continuingToolCallIds.clear();

‎extensions/xai/realtime-voice-provider.test.ts‎

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
// Xai tests cover realtime voice provider plugin behavior.
2-
import { REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ } from "openclaw/plugin-sdk/realtime-voice";
2+
import {
3+
REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ,
4+
REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ,
5+
} from "openclaw/plugin-sdk/realtime-voice";
36
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
47
import { XAI_REALTIME_MAX_PENDING_PLAYBACK_MARKS } from "./realtime-voice-config.js";
58
import { buildXaiRealtimeVoiceProvider } from "./realtime-voice-provider.js";
@@ -892,30 +895,34 @@ describe("buildXaiRealtimeVoiceProvider", () => {
892895
expectedActions: [],
893896
},
894897
{
895-
name: "cancels and truncates active response audio on barge-in",
898+
name: "clamps manual barge-in to produced G.711 audio",
896899
hasAudio: true,
897900
manual: true,
898-
timestamp: 1300,
901+
audioBytes: 3_700 * 8,
902+
audioFormat: REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ,
903+
timestamp: 4760,
899904
expectedActions: [
900905
{ type: "response.cancel" },
901906
{
902907
type: "conversation.item.truncate",
903908
item_id: "item_1",
904909
content_index: 0,
905-
audio_end_ms: 300,
910+
audio_end_ms: 3_700,
906911
},
907912
],
908913
},
909914
{
910-
name: "truncates queued playback on server-VAD barge-in without cancelling xAI",
915+
name: "clamps server-VAD barge-in to produced PCM16 audio without cancelling xAI",
911916
hasAudio: true,
912-
timestamp: 1250,
917+
audioBytes: 3_700 * 48,
918+
audioFormat: REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ,
919+
timestamp: 4760,
913920
expectedActions: [
914921
{
915922
type: "conversation.item.truncate",
916923
item_id: "item_1",
917924
content_index: 0,
918-
audio_end_ms: 250,
925+
audio_end_ms: 3_700,
919926
},
920927
],
921928
},
@@ -940,6 +947,7 @@ describe("buildXaiRealtimeVoiceProvider", () => {
940947
acknowledged: true,
941948
completed: true,
942949
manual: true,
950+
audioBytes: 300 * 8,
943951
timestamp: 1300,
944952
expectedActions: [
945953
{
@@ -967,14 +975,16 @@ describe("buildXaiRealtimeVoiceProvider", () => {
967975
completed,
968976
startNewResponse,
969977
manual,
978+
audioBytes,
979+
audioFormat,
970980
timestamp,
971981
expectedActions,
972982
}) => {
973983
vi.stubEnv("XAI_API_KEY", "xai-env"); // pragma: allowlist secret
974984
const onAudio = vi.fn();
975985
const onClearAudio = vi.fn();
976986
const bridge = createTestBridge({
977-
audioFormat: REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ,
987+
...(audioFormat ? { audioFormat } : {}),
978988
onAudio,
979989
onClearAudio,
980990
});
@@ -986,7 +996,7 @@ describe("buildXaiRealtimeVoiceProvider", () => {
986996
socket.emitServer({
987997
type: "response.output_audio.delta",
988998
item_id: "item_1",
989-
delta: Buffer.from("assistant audio").toString("base64"),
999+
delta: Buffer.alloc(audioBytes ?? 16).toString("base64"),
9901000
});
9911001
}
9921002
if (acknowledged) {

‎src/plugin-sdk/realtime-voice.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,38 @@ import { describe, expect, it, vi } from "vitest";
22
import {
33
createRealtimeVoiceAudioQueue,
44
normalizeRealtimeVoiceResponseOutcome,
5+
REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ,
6+
REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ,
7+
realtimeVoiceAudioDurationMs,
58
RealtimeVoiceSessionLifecycle,
69
type RealtimeVoiceSessionConnection,
710
} from "./realtime-voice.js";
811

12+
describe("realtimeVoiceAudioDurationMs", () => {
13+
it.each([
14+
{
15+
name: "G.711 μ-law 8 kHz mono",
16+
format: REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ,
17+
byteLength: 8_000,
18+
durationMs: 1_000,
19+
},
20+
{
21+
name: "PCM16 24 kHz mono",
22+
format: REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ,
23+
byteLength: 48_000,
24+
durationMs: 1_000,
25+
},
26+
{
27+
name: "one G.711 μ-law sample without rounding",
28+
format: REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ,
29+
byteLength: 1,
30+
durationMs: 0.125,
31+
},
32+
])("calculates $name", ({ format, byteLength, durationMs }) => {
33+
expect(realtimeVoiceAudioDurationMs(format, byteLength)).toBe(durationMs);
34+
});
35+
});
36+
937
function connectLifecycle(
1038
lifecycle: RealtimeVoiceSessionLifecycle,
1139
): RealtimeVoiceSessionConnection {

‎src/plugin-sdk/realtime-voice.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ export {
2828
normalizeRealtimeVoiceResponseOutcome,
2929
REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ,
3030
REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ,
31+
realtimeVoiceAudioDurationMs,
3132
} from "../talk/provider-types.js";
3233
export {
3334
createTalkEventSequencer,

‎src/talk/provider-types.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,14 @@ export type RealtimeVoiceAudioFormat =
2222
channels: 1;
2323
};
2424

25+
export function realtimeVoiceAudioDurationMs(
26+
format: RealtimeVoiceAudioFormat,
27+
byteLength: number,
28+
): number {
29+
const bytesPerSample = format.encoding === "pcm16" ? 2 : 1;
30+
return (byteLength * 1000) / (format.sampleRateHz * format.channels * bytesPerSample);
31+
}
32+
2533
export const REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ: RealtimeVoiceAudioFormat = {
2634
encoding: "g711_ulaw",
2735
sampleRateHz: 8000,

0 commit comments

Comments
 (0)