fix: preserve continuous Opus state in WebRTC downlink

This commit is contained in:
illusia committed 2026-10-03 09:28:11 +08:00
1 parent 777c779d79
commit 7baeff00ba
3 files changed
+61 -20

No files matched your search

+45
View File
@@ -1,7 +1,52 @@
import assert from "node:assert/strict";
import test from "node:test";
import pino from "pino";
import type { RtpPacket } from "werift";
import { OpusEncoder } from "./opus-codec.js";
import { WebRtcAudioSession } from "./webrtc-audio.js";
function rms(pcm: Buffer): number {
let energy = 0;
for (let index = 0; index < pcm.length; index += 2) energy += pcm.readInt16LE(index) ** 2;
return Math.sqrt(energy / (pcm.length / 2));
}
for (const scenario of ["silence gaps", "alternating speakers", "volume changes"] as const) {
test(`WebRTC output preserves audible Opus across ${scenario}`, async t => {
const session = new WebRtcAudioSession({ connectionId: scenario, logger: pino({ enabled: false }), onVoiceFrame() {}, onVoiceActivity() {} });
const source = [new OpusEncoder(48000, 1), new OpusEncoder(48000, 1)];
const receiver = new OpusEncoder(48000, 1);
t.after(async () => { source.forEach(codec => codec.dispose()); receiver.dispose(); await session.close(); });
// Advance the real mixer explicitly so network/timer jitter cannot hide
// codec-state discontinuities. Encoding and decoding remain native Opus.
const mixer = session as unknown as {
audioTimer: ReturnType<typeof setTimeout>; activityTimer: ReturnType<typeof setInterval>;
outgoingTrack: { writeRtp(packet: RtpPacket): void }; mixAndSendAudio(): void;
};
clearTimeout(mixer.audioTimer);
clearInterval(mixer.activityTimer);
let level = 0;
mixer.outgoingTrack.writeRtp = packet => { level = rms(receiver.decode(packet.payload)); };
for (let tick = 0; tick < 50; tick++) mixer.mixAndSendAudio();
for (let frame = 0; frame < 50; frame++) {
const speaker = scenario === "alternating speakers" ? frame % 2 : 0;
const gain = scenario === "volume changes" && frame % 2 === 1 ? 0.5 : 1;
session.setMemberVolume(speaker + 2, gain);
const pcm = Buffer.alloc(1920);
const frequency = speaker === 0 ? 660 : 440;
for (let sample = 0; sample < 960; sample++) pcm.writeInt16LE(Math.round(1800 * Math.sin(2 * Math.PI * frequency * (frame * 960 + sample) / 48000)), sample * 2);
session.pushTeamSpeakVoice({ clientId: speaker + 2, codec: 4, data: source[speaker]!.encode(pcm) });
mixer.mixAndSendAudio();
assert.ok(level > 500 * gain, `${scenario}, frame ${frame}: unexpectedly quiet RMS ${level}`);
if (scenario === "silence gaps") mixer.mixAndSendAudio();
}
const stats = session.getStats();
assert.equal(stats.webrtcDownlinkDecodedFrames, 50);
assert.equal(stats.webrtcDownlinkDecodeErrors, 0);
assert.equal(stats.webrtcQueueDroppedFrames, 0);
});
}
function fixture() {
const released: string[] = [];
// Exercise the real close path with failures at codec/track/peer boundaries.
+3 -16
View File
@@ -72,13 +72,6 @@ export interface WebRtcAudioStats {
interface PendingAudioFrame {
pcm: Buffer;
receivedAt: number;
/** Preserve a native 20 ms Opus frame when no mix is required. */
opus?: Buffer;
}
interface SelectedAudioFrame extends PendingAudioFrame {
clientId: number;
volume: number;
}
/**
@@ -260,7 +253,6 @@ export class WebRtcAudioSession {
// including quiet/comfort-noise frames, continues into the queue so the
// receiver keeps an uninterrupted codec timeline.
if (rms >= SPEAKER_ACTIVITY_RMS) this.activeSpeakerIds.add(data.clientId);
const canForwardOpus = !pendingPcm && pcm.length === AUDIO_FRAME_BYTES;
let offset = 0;
let enqueued = false;
let queue = this.pendingFrames.get(data.clientId);
@@ -276,7 +268,6 @@ export class WebRtcAudioSession {
queue.push({
pcm: Buffer.from(combined.subarray(offset, offset + AUDIO_FRAME_BYTES)),
receivedAt: performance.now(),
...(canForwardOpus && offset === 0 ? { opus: Buffer.from(data.data) } : {}),
});
enqueued = true;
offset += AUDIO_FRAME_BYTES;
@@ -352,23 +343,19 @@ export class WebRtcAudioSession {
}
}
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES);
const selectedFrames: SelectedAudioFrame[] = [];
for (const [clientId, queue] of this.pendingFrames) {
const frame = queue.shift();
if (queue.length === 0) this.pendingFrames.delete(clientId);
if (!frame) continue;
const volume = this.memberVolumes.get(clientId) ?? 1;
selectedFrames.push({ ...frame, clientId, volume });
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
mixed[index] += Math.round(frame.pcm.readInt16LE(index * 2) * volume);
}
}
if (selectedFrames.length === 1 && selectedFrames[0]?.opus && selectedFrames[0].volume === 1) {
this.sendRtpAudio(selectedFrames[0].opus);
return;
}
// One RTP stream needs one continuous Opus encoder state. Alternating
// source packets with our encoded silence/mixes corrupts decoder history
// and can suppress otherwise valid speech without any packet loss.
const pcm = Buffer.allocUnsafe(AUDIO_FRAME_BYTES);
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
// Keep a fixed gain for the mixed path. Per-sample soft limiting changes