fix: negotiate only supported Opus audio before WebRTC activation

This commit is contained in:
illusia committed 2026-10-03 09:38:59 +08:00
1 parent 7baeff00ba
commit d327c6f179
3 files changed
+55 -16

No files matched your search

+30 -1
View File
@@ -1,10 +1,39 @@
import assert from "node:assert/strict";
import test from "node:test";
import pino from "pino";
import type { RtpPacket } from "werift";
import { RTCPeerConnection, useOPUS, usePCMU, type RtpPacket } from "werift";
import { OpusEncoder } from "./opus-codec.js";
import { WebRtcAudioSession } from "./webrtc-audio.js";
test("WebRTC rejects an offer without negotiated audio instead of returning an empty answer", async t => {
const session = new WebRtcAudioSession({ connectionId: "invalid-offer", logger: pino({ enabled: false }), onVoiceFrame() {}, onVoiceActivity() {} });
t.after(() => session.close());
await assert.rejects(session.createAnswer({ type: "offer", sdp: "invalid sdp" }), /did not negotiate Opus audio/);
});
for (const scenario of ["PCMU only", "Opus only", "PCMU before Opus"] as const) {
test(`WebRTC negotiates only supported audio with ${scenario}`, async t => {
const codecs = scenario === "PCMU only" ? [usePCMU()]
: scenario === "Opus only" ? [useOPUS({ payloadType: 109 })]
: [usePCMU(), useOPUS({ payloadType: 109 })];
const source = new RTCPeerConnection({ iceServers: [], codecs: { audio: codecs } });
const session = new WebRtcAudioSession({ connectionId: scenario, logger: pino({ enabled: false }), onVoiceFrame() {}, onVoiceActivity() {} });
t.after(async () => { await session.close(); await source.close(); });
source.addTransceiver("audio", { direction: "sendrecv" });
const offer = await source.createOffer();
if (scenario === "PCMU only") {
await assert.rejects(session.createAnswer({ type: "offer", sdp: offer.sdp }));
return;
}
const answer = await session.createAnswer({ type: "offer", sdp: offer.sdp });
assert.equal(answer.type, "answer");
assert.match(answer.sdp, /a=rtpmap:109 opus\/48000\/2/i);
assert.doesNotMatch(answer.sdp, /PCMU/i);
const audio = session.peer.getTransceivers().find(transceiver => transceiver.kind === "audio")!;
assert.deepEqual(audio.codecs.map(codec => codec.payloadType), [109]);
});
}
function rms(pcm: Buffer): number {
let energy = 0;
for (let index = 0; index < pcm.length; index += 2) energy += pcm.readInt16LE(index) ** 2;
+12 -12
View File
@@ -4,6 +4,7 @@ import {
RtpHeader,
RtpPacket,
RTCPeerConnection,
useOPUS,
} from "werift";
import type { Logger as LoggerType } from "../logger.js";
import type { TSVoiceData } from "./ts-client.js";
@@ -142,6 +143,9 @@ export class WebRtcAudioSession {
const iceAdditionalHostAddresses = options.publicHost ? [options.publicHost] : undefined;
const udpPortRange = options.udpPortRange ?? WEBRTC_UDP_PORT_RANGE;
this.peer = new RTCPeerConnection({
// Both audio routes carry Opus; accepting PCMU would label Opus output
// as another codec and silently discard the peer's incoming audio.
codecs: { audio: [useOPUS()] },
iceServers: [],
iceUseIpv4: true,
iceUseIpv6: false,
@@ -209,10 +213,16 @@ export class WebRtcAudioSession {
async createAnswer(offer: WebRtcSessionDescription): Promise<WebRtcSessionDescription> {
if (this.closed) throw new Error("WebRTC session is closed");
this.setOpusPayloadTypes(offer.sdp);
await this.peer.setRemoteDescription(offer);
const transceiver = this.peer.getTransceivers().find((candidate) => candidate.kind === "audio");
if (transceiver) await transceiver.sender.replaceTrack(this.outgoingTrack);
const opus = transceiver?.codecs.filter(codec => codec.mimeType.toLowerCase() === "audio/opus" && codec.clockRate === AUDIO_SAMPLE_RATE) ?? [];
if (!transceiver || !opus.length) throw new Error("WebRTC offer did not negotiate Opus audio");
// Use negotiated audio codecs, not rtpmap lines from unrelated media or
// a guessed payload type when the offer contains no usable audio.
this.opusPayloadTypes.clear();
for (const codec of opus) this.opusPayloadTypes.add(codec.payloadType);
this.outgoingPayloadType = opus[0]!.payloadType;
await transceiver.sender.replaceTrack(this.outgoingTrack);
const answer = await this.peer.createAnswer();
await this.peer.setLocalDescription(answer);
const description = this.peer.localDescription;
@@ -447,14 +457,4 @@ export class WebRtcAudioSession {
return count;
}
private setOpusPayloadTypes(sdp: string): void {
this.opusPayloadTypes.clear();
for (const match of sdp.matchAll(/^a=rtpmap:(\d+)\s+opus\/48000(?:\/\d+)?/gim)) {
const payloadType = Number(match[1]);
if (!Number.isInteger(payloadType) || payloadType < 0 || payloadType > 127) continue;
this.opusPayloadTypes.add(payloadType);
this.outgoingPayloadType = payloadType;
}
if (!this.opusPayloadTypes.size) this.opusPayloadTypes.add(DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE);
}
}