mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
refactor: isolate session audio and harden gateway teardown
This commit is contained in:
1 parent
49481145ef
commit
c8417edd7d
10 files changed
+760
-351
No files matched your search
@@ -0,0 +1,183 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { SessionAudioTransport } from "./session-audio.js";
|
||||
import { createAudioFlowStats } from "./audio-stats.js";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import type { TSVoiceData } from "./ts-client.js";
|
||||
|
||||
function fixture() {
|
||||
const state = { current: true, ready: true, now: 0, targets: null as number[] | null, disposed: 0,
|
||||
peer: null as { pushTeamSpeakVoice(data: TSVoiceData): void } | null };
|
||||
const audio = createAudioFlowStats();
|
||||
const packets: Buffer[] = [];
|
||||
const encoded: Buffer[] = [];
|
||||
const forwarded: Array<{ data: Buffer; codec: number; targets?: number[] }> = [];
|
||||
const notices: ServerMessage[] = [];
|
||||
const socket = { readyState: 1 as 0 | 1 | 2 | 3, bufferedAmount: 0, send: (packet: Buffer) => { packets.push(packet); } };
|
||||
const client = {
|
||||
sendVoice: (data: Buffer, codec: number) => { forwarded.push({ data, codec }); },
|
||||
sendWhisper: (data: Buffer, targets: number[], codec: number) => { forwarded.push({ data, codec, targets }); },
|
||||
};
|
||||
const encoder = {
|
||||
encode(frame: Buffer) { encoded.push(frame); state.now += 3; return Buffer.from([9, 8, 7]); },
|
||||
dispose() { state.disposed++; },
|
||||
};
|
||||
const transport = new SessionAudioTransport({
|
||||
audio, socket, client, isCurrent: () => state.current, isReady: () => state.ready,
|
||||
selfId: () => 1, peer: () => state.peer, whisperTargets: () => state.targets,
|
||||
sendJson: message => { notices.push(message); },
|
||||
}, encoder, () => state.now);
|
||||
const remote = (clientId = 513) => ({ clientId, codec: 4, data: Buffer.from([11, 12, 13]) });
|
||||
return { transport, audio, state, socket, client, encoder, packets, encoded, forwarded, notices, remote };
|
||||
}
|
||||
|
||||
test("PCM framing preserves codec, whisper routing and timing counters", () => {
|
||||
const f = fixture();
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
f.state.now = 20;
|
||||
f.state.targets = [7, 8];
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.deepEqual(f.forwarded.map(({ codec, targets }) => ({ codec, targets })), [
|
||||
{ codec: 4, targets: undefined }, { codec: 4, targets: [7, 8] },
|
||||
]);
|
||||
assert.equal(f.audio.ingressFrames, 2);
|
||||
assert.equal(f.audio.ingressMaxGapMs, 20);
|
||||
assert.equal(f.audio.tsSendMaxGapMs, 20);
|
||||
assert.equal(f.audio.tsEncodeMaxMs, 3);
|
||||
});
|
||||
|
||||
test("invalid PCM is rejected and reconnecting sessions do not encode audio", () => {
|
||||
const f = fixture();
|
||||
f.transport.receivePcm(Buffer.alloc(1_919));
|
||||
f.transport.receivePcm(Buffer.alloc(1_921));
|
||||
assert.equal(f.notices.length, 2);
|
||||
assert.deepEqual(f.notices[0], { type: "error", error: { code: "INVALID_AUDIO_FRAME", message: "音频帧格式无效", recoverable: false } });
|
||||
f.state.ready = false;
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
f.transport.receiveWebRtc(Buffer.from([1]), 4);
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(f.audio.ingressDroppedFrames, 3);
|
||||
assert.equal(f.encoded.length, 0);
|
||||
assert.equal(f.forwarded.length, 0);
|
||||
assert.equal(f.packets.length, 0);
|
||||
});
|
||||
|
||||
test("WebRTC ingress excludes queued PCM and fallback re-enables PCM", () => {
|
||||
const f = fixture();
|
||||
f.state.peer = { pushTeamSpeakVoice() {} };
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
const opus = Buffer.from([3, 2, 1]);
|
||||
f.transport.receiveWebRtc(opus, 5);
|
||||
assert.equal(f.encoded.length, 0);
|
||||
assert.deepEqual(f.forwarded, [{ data: opus, codec: 5 }]);
|
||||
assert.equal(f.audio.ingressDroppedFrames, 1);
|
||||
f.state.peer = null;
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.equal(f.encoded.length, 1);
|
||||
assert.equal(f.audio.tsSendFrames, 2);
|
||||
});
|
||||
|
||||
test("TeamSpeak packets keep the three-byte header and exclude self playback", () => {
|
||||
const f = fixture();
|
||||
f.transport.receiveTeamSpeak(f.remote(1));
|
||||
const remote = f.remote();
|
||||
f.transport.receiveTeamSpeak(remote);
|
||||
remote.data.fill(0);
|
||||
assert.deepEqual([...f.packets[0]!], [4, 2, 1, 11, 12, 13]);
|
||||
assert.equal(f.audio.tsReceiveFrames, 2);
|
||||
assert.equal(f.audio.egressFrames, 1);
|
||||
assert.deepEqual(f.audio.egressFramesByClient, { "513": 1 });
|
||||
});
|
||||
|
||||
test("backpressure drops bursts above 4096 bytes and resumes without a retained queue", () => {
|
||||
const f = fixture();
|
||||
f.socket.bufferedAmount = 4_096;
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
f.socket.bufferedAmount = 4_097;
|
||||
for (let i = 0; i < 100; i++) f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(f.packets.length, 1);
|
||||
assert.equal(f.audio.egressDroppedFrames, 100);
|
||||
f.socket.bufferedAmount = 0;
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(f.packets.length, 2);
|
||||
assert.equal(f.audio.egressPeakBufferedBytes, 4_097);
|
||||
});
|
||||
|
||||
test("WebRTC downlink owns egress without a duplicate WebSocket packet", () => {
|
||||
const f = fixture();
|
||||
const received: TSVoiceData[] = [];
|
||||
f.state.peer = { pushTeamSpeakVoice: data => { received.push(data); } };
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(received.length, 1);
|
||||
assert.equal(f.packets.length, 0);
|
||||
f.state.peer = null;
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(received.length, 1);
|
||||
assert.equal(f.packets.length, 1);
|
||||
});
|
||||
|
||||
test("encoding failures are counted and reported at most once per five seconds", t => {
|
||||
const f = fixture();
|
||||
t.mock.method(f.encoder, "encode", () => { throw new Error("Codec failed"); });
|
||||
for (const now of [0, 1, 4_999, 5_000]) { f.state.now = now; f.transport.receivePcm(Buffer.alloc(1_920)); }
|
||||
assert.equal(f.audio.tsSendErrors, 4);
|
||||
assert.equal(f.audio.ingressDroppedFrames, 4);
|
||||
assert.equal(f.forwarded.length, 0);
|
||||
assert.equal(f.notices.length, 2);
|
||||
assert.deepEqual(f.notices[0], { type: "audioError", code: "AUDIO_ENCODER_UNAVAILABLE", detail: "Opus encoder unavailable" });
|
||||
t.mock.restoreAll();
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.equal(f.audio.tsSendFrames, 1);
|
||||
});
|
||||
|
||||
test("SDK and downlink failures cannot escape the audio callbacks", t => {
|
||||
const f = fixture();
|
||||
t.mock.method(f.client, "sendVoice", () => { throw new Error("SDK disconnected"); });
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.equal(f.audio.tsSendErrors, 1);
|
||||
assert.equal(f.notices.length, 0, "SDK failure must not be reported as an encoder failure");
|
||||
t.mock.method(f.socket, "send", () => { throw new Error("Socket closed"); });
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
f.state.peer = { pushTeamSpeakVoice() { throw new Error("Peer closed"); } };
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(f.audio.egressDroppedFrames, 2);
|
||||
});
|
||||
|
||||
test("removed sessions and closed sockets ignore late frames without changing counters", () => {
|
||||
const f = fixture();
|
||||
const baseline = structuredClone(f.audio);
|
||||
const lateFrames = () => {
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
f.transport.receiveWebRtc(Buffer.from([1]), 4);
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
};
|
||||
f.state.current = false;
|
||||
lateFrames();
|
||||
f.state.current = true;
|
||||
f.socket.readyState = 3;
|
||||
lateFrames();
|
||||
assert.deepEqual(f.audio, baseline);
|
||||
assert.equal(f.encoded.length, 0);
|
||||
});
|
||||
|
||||
test("codec cleanup is idempotent even if disposal throws", t => {
|
||||
const f = fixture();
|
||||
let attempts = 0;
|
||||
t.mock.method(f.encoder, "dispose", () => { attempts++; throw new Error("Already closed"); });
|
||||
f.transport.close();
|
||||
f.transport.close();
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
f.transport.receiveWebRtc(Buffer.from([1]), 4);
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(attempts, 1);
|
||||
assert.equal(f.audio.ingressFrames, 0);
|
||||
assert.equal(f.audio.tsReceiveFrames, 0);
|
||||
});
|
||||
|
||||
test("invalid SDK speaker IDs and codecs cannot throw while packing the header", () => {
|
||||
const f = fixture();
|
||||
for (const clientId of [-1, 65_536, NaN]) f.transport.receiveTeamSpeak(f.remote(clientId));
|
||||
for (const codec of [-1, 256, NaN]) f.transport.receiveTeamSpeak({ ...f.remote(), codec });
|
||||
assert.equal(f.audio.egressDroppedFrames, 6);
|
||||
assert.equal(f.packets.length, 0);
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import { WebSocket } from "ws";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import type { AudioFlowStats } from "./audio-stats.js";
|
||||
import type { TSClient, TSVoiceData } from "./ts-client.js";
|
||||
import type { WebRtcAudioSession } from "./webrtc-audio.js";
|
||||
|
||||
const AUDIO_FRAME_BYTES = 1_920; // 20 ms of 48 kHz mono Int16 PCM.
|
||||
// Keep the established byte guard; the browser also bounds playback by time.
|
||||
const MAX_BUFFERED_BYTES = 4_096;
|
||||
|
||||
export interface VoiceEncoder {
|
||||
encode(frame: Buffer): Buffer;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export interface SessionAudioOptions {
|
||||
audio: AudioFlowStats;
|
||||
socket: Pick<WebSocket, "readyState" | "bufferedAmount"> & { send(packet: Buffer): void };
|
||||
client: Pick<TSClient, "sendVoice" | "sendWhisper">;
|
||||
isCurrent(): boolean;
|
||||
isReady(): boolean;
|
||||
selfId(): number;
|
||||
peer(): Pick<WebRtcAudioSession, "pushTeamSpeakVoice"> | null;
|
||||
whisperTargets(): readonly number[] | null;
|
||||
sendJson(message: ServerMessage): void;
|
||||
}
|
||||
|
||||
/** A session owns one encoder and one active audio route in each direction. */
|
||||
export class SessionAudioTransport {
|
||||
private encoder: VoiceEncoder | null;
|
||||
private closed = false;
|
||||
private warnedAt: number | null = null;
|
||||
|
||||
constructor(private readonly options: SessionAudioOptions, encoder: VoiceEncoder, private readonly clock: () => number = Date.now) {
|
||||
this.encoder = encoder;
|
||||
}
|
||||
|
||||
private isCurrent(): boolean {
|
||||
return !this.closed && this.options.isCurrent() && this.options.socket.readyState === WebSocket.OPEN;
|
||||
}
|
||||
|
||||
private recordIngress(): void {
|
||||
const stats = this.options.audio;
|
||||
const now = this.clock();
|
||||
if (stats.ingressLastAt !== null) stats.ingressMaxGapMs = Math.max(stats.ingressMaxGapMs, now - stats.ingressLastAt);
|
||||
stats.ingressFirstAt ??= now;
|
||||
stats.ingressLastAt = now;
|
||||
stats.ingressFrames++;
|
||||
}
|
||||
|
||||
private sendVoice(data: Buffer, codec: number): void {
|
||||
const stats = this.options.audio;
|
||||
try {
|
||||
const targets = this.options.whisperTargets();
|
||||
if (targets?.length) this.options.client.sendWhisper(data, [...targets], codec);
|
||||
else this.options.client.sendVoice(data, codec);
|
||||
const now = this.clock();
|
||||
if (stats.tsSendLastAt !== null) stats.tsSendMaxGapMs = Math.max(stats.tsSendMaxGapMs, now - stats.tsSendLastAt);
|
||||
stats.tsSendFirstAt ??= now;
|
||||
stats.tsSendLastAt = now;
|
||||
stats.tsSendFrames++;
|
||||
} catch {
|
||||
stats.tsSendErrors++;
|
||||
}
|
||||
}
|
||||
|
||||
private reportEncoderFailure(): void {
|
||||
const now = this.clock();
|
||||
if (this.warnedAt !== null && now - this.warnedAt < 5_000) return;
|
||||
this.warnedAt = now;
|
||||
try {
|
||||
this.options.sendJson({ type: "audioError", code: "AUDIO_ENCODER_UNAVAILABLE", detail: "Opus encoder unavailable" });
|
||||
} catch { /* the socket may have closed while reporting the failure */ }
|
||||
}
|
||||
|
||||
receivePcm(frame: Buffer): void {
|
||||
if (!this.isCurrent()) return;
|
||||
const stats = this.options.audio;
|
||||
if (frame.length !== AUDIO_FRAME_BYTES) {
|
||||
stats.ingressDroppedFrames++;
|
||||
this.options.sendJson({ type: "error", error: { code: "INVALID_AUDIO_FRAME", message: "音频帧格式无效", recoverable: false } });
|
||||
return;
|
||||
}
|
||||
// Late TCP frames from before a WebRTC switch must not duplicate RTP audio.
|
||||
if (!this.options.isReady() || this.options.peer()) { stats.ingressDroppedFrames++; return; }
|
||||
this.recordIngress();
|
||||
const startedAt = this.clock();
|
||||
let encoded: Buffer;
|
||||
try {
|
||||
if (!this.encoder) throw new Error("Encoder unavailable");
|
||||
encoded = this.encoder.encode(frame);
|
||||
stats.tsEncodeMaxMs = Math.max(stats.tsEncodeMaxMs, this.clock() - startedAt);
|
||||
} catch {
|
||||
stats.tsSendErrors++;
|
||||
stats.ingressDroppedFrames++;
|
||||
this.reportEncoderFailure();
|
||||
return;
|
||||
}
|
||||
this.sendVoice(encoded, 4);
|
||||
}
|
||||
|
||||
receiveWebRtc(data: Buffer, codec: number): void {
|
||||
if (!this.isCurrent() || !this.options.isReady()) return;
|
||||
this.recordIngress();
|
||||
this.sendVoice(data, codec);
|
||||
}
|
||||
|
||||
receiveTeamSpeak(data: TSVoiceData): void {
|
||||
if (!this.isCurrent() || !this.options.isReady()) return;
|
||||
const stats = this.options.audio;
|
||||
const now = this.clock();
|
||||
if (stats.tsReceiveLastAt !== null) stats.tsReceiveMaxGapMs = Math.max(stats.tsReceiveMaxGapMs, now - stats.tsReceiveLastAt);
|
||||
stats.tsReceiveFirstAt ??= now;
|
||||
stats.tsReceiveLastAt = now;
|
||||
stats.tsReceiveFrames++;
|
||||
if (data.clientId === this.options.selfId()) return;
|
||||
if (!Number.isInteger(data.clientId) || data.clientId < 1 || data.clientId > 65_535
|
||||
|| !Number.isInteger(data.codec) || data.codec < 0 || data.codec > 255 || !Buffer.isBuffer(data.data)) {
|
||||
stats.egressDroppedFrames++;
|
||||
return;
|
||||
}
|
||||
if (stats.egressLastAt !== null) stats.egressMaxGapMs = Math.max(stats.egressMaxGapMs, now - stats.egressLastAt);
|
||||
stats.egressFirstAt ??= now;
|
||||
stats.egressLastAt = now;
|
||||
const key = String(data.clientId);
|
||||
stats.egressFramesByClient[key] = (stats.egressFramesByClient[key] ?? 0) + 1;
|
||||
const peer = this.options.peer();
|
||||
if (peer) {
|
||||
try { peer.pushTeamSpeakVoice(data); stats.egressFrames++; }
|
||||
catch { stats.egressDroppedFrames++; }
|
||||
return;
|
||||
}
|
||||
const bufferedBytes = this.options.socket.bufferedAmount;
|
||||
stats.egressPeakBufferedBytes = Math.max(stats.egressPeakBufferedBytes, bufferedBytes);
|
||||
if (bufferedBytes > MAX_BUFFERED_BYTES) { stats.egressDroppedFrames++; return; }
|
||||
const packet = Buffer.allocUnsafe(3 + data.data.length);
|
||||
packet[0] = data.codec;
|
||||
packet.writeUInt16BE(data.clientId, 1);
|
||||
data.data.copy(packet, 3);
|
||||
try {
|
||||
this.options.socket.send(packet);
|
||||
stats.egressFrames++;
|
||||
const sentAt = this.clock();
|
||||
if (stats.egressSentLastAt !== null) stats.egressSentMaxGapMs = Math.max(stats.egressSentMaxGapMs, sentAt - stats.egressSentLastAt);
|
||||
stats.egressSentFirstAt ??= sentAt;
|
||||
stats.egressSentLastAt = sentAt;
|
||||
} catch { stats.egressDroppedFrames++; }
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
const encoder = this.encoder;
|
||||
this.encoder = null;
|
||||
try { encoder?.dispose(); } catch { /* other session resources must still be released */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { EventEmitter, once } from "node:events";
|
||||
import { createServer } from "node:http";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import { WebSocket, type WebSocketServer } from "ws";
|
||||
import pino from "pino";
|
||||
import { VoiceBridge } from "./voice-bridge.js";
|
||||
import { JoinTicketStore } from "./join-ticket.js";
|
||||
import { OpusEncoder } from "./opus-codec.js";
|
||||
import type { TSClient } from "./ts-client.js";
|
||||
import type { AudioFlowStats } from "./audio-stats.js";
|
||||
import type { WebRtcAudioSession } from "./webrtc-audio.js";
|
||||
|
||||
// Real loopback HTTP/WebSocket and native codec, with only the external SDK
|
||||
// replaced. This validates gateway wiring, not a connection to TeamSpeak.
|
||||
class TeamSpeakStub extends EventEmitter {
|
||||
disconnected = false;
|
||||
sent: Buffer[] = [];
|
||||
async connect() { this.emit("directorySnapshot", { channels: [], clients: [] }); }
|
||||
async disconnect() { this.disconnected = true; }
|
||||
getClientId() { return 1; }
|
||||
getChannelId() { return 1n; }
|
||||
isConnected() { return !this.disconnected; }
|
||||
async sendProtocolCommand() {}
|
||||
sendVoice(data: Buffer) { this.sent.push(data); this.emit("sent", data); }
|
||||
sendWhisper(data: Buffer) { this.sent.push(data); }
|
||||
}
|
||||
|
||||
async function fixture(t: TestContext, overrides: {
|
||||
createTeamSpeakClient?: () => TSClient;
|
||||
createEncoder?: () => Pick<OpusEncoder, "encode" | "dispose">;
|
||||
} = {}) {
|
||||
const sdk = new TeamSpeakStub();
|
||||
const tickets = new JoinTicketStore();
|
||||
const bridge = new VoiceBridge({ joinTickets: tickets }, pino({ enabled: false }), undefined, {
|
||||
createTeamSpeakClient: overrides.createTeamSpeakClient ?? (() => sdk as unknown as TSClient),
|
||||
...(overrides.createEncoder ? { createEncoder: overrides.createEncoder } : {}),
|
||||
});
|
||||
const server = createServer();
|
||||
bridge.attach(server);
|
||||
const wss = (bridge as unknown as { wss: WebSocketServer }).wss;
|
||||
server.listen(0, "127.0.0.1");
|
||||
await once(server, "listening");
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address !== "string");
|
||||
const ticket = tickets.create({ target: { host: "voice.example.invalid", port: 9987 }, nickname: "Test", serverPassword: "" });
|
||||
const socket = new WebSocket(`ws://127.0.0.1:${address.port}/ws/voice?ticket=${ticket}`);
|
||||
const messages: Array<{ data: Buffer; binary: boolean }> = [];
|
||||
socket.on("message", (data, binary) => messages.push({ data: data as Buffer, binary }));
|
||||
const first = once(socket, "message");
|
||||
t.after(async () => {
|
||||
socket.terminate();
|
||||
// Clean fixtures even when a regression removes the WebSocketServer's own
|
||||
// close listener. The membership assertion below tests that behavior first.
|
||||
for (const peer of wss.clients) peer.terminate();
|
||||
wss.clients.clear();
|
||||
await bridge.shutdown();
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
});
|
||||
await first;
|
||||
const entries = (bridge as unknown as { entries: Map<string, { id: string; ws: WebSocket; audio: AudioFlowStats; webrtc: WebRtcAudioSession | null }> }).entries;
|
||||
return { bridge, sdk, socket, messages, entries, wss };
|
||||
}
|
||||
|
||||
test("a TeamSpeak constructor failure releases the admitted gateway slot", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t, { createTeamSpeakClient() { throw new Error("Identity initialization failed"); } });
|
||||
if (f.socket.readyState !== WebSocket.CLOSED) await once(f.socket, "close");
|
||||
await nextTurn();
|
||||
assert.equal(JSON.parse(f.messages[0]!.data.toString()).code, "TEAM_SPEAK_CLIENT_UNAVAILABLE");
|
||||
assert.equal(f.bridge.getActiveCount(), 0);
|
||||
});
|
||||
|
||||
test("a codec disposal failure cannot abandon TeamSpeak or the browser socket", { timeout: 5_000 }, async t => {
|
||||
const encoder = new OpusEncoder(48000, 1);
|
||||
t.mock.method(encoder, "dispose", () => { throw new Error("Codec already disposed"); });
|
||||
const f = await fixture(t, { createEncoder: () => encoder });
|
||||
const entry = [...f.entries.values()][0]!;
|
||||
await f.bridge.terminateSession(entry.id);
|
||||
assert.equal(f.sdk.disconnected, true);
|
||||
assert.notEqual(entry.ws.readyState, WebSocket.OPEN);
|
||||
assert.equal(f.bridge.getActiveCount(), 0);
|
||||
});
|
||||
|
||||
test("late SDK audio during peer closure cannot write after the session is removed", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t);
|
||||
const entry = [...f.entries.values()][0]!;
|
||||
const onVoice = f.sdk.listeners("voiceData")[0]!;
|
||||
let release!: () => void;
|
||||
const closing = new Promise<void>(resolve => { release = resolve; });
|
||||
entry.webrtc = { close: () => closing, getStats: () => ({}) } as unknown as WebRtcAudioSession;
|
||||
const writes: unknown[] = [];
|
||||
t.mock.method(entry.ws, "send", (data: unknown) => { writes.push(data); });
|
||||
const stopped = f.bridge.terminateSession(entry.id);
|
||||
try {
|
||||
onVoice({ clientId: 2, codec: 4, data: Buffer.from([1, 2, 3]) });
|
||||
assert.equal(writes.length, 0);
|
||||
assert.equal(entry.audio.tsReceiveFrames, 0);
|
||||
} finally {
|
||||
release();
|
||||
await stopped;
|
||||
}
|
||||
});
|
||||
|
||||
test("normal session teardown retains the WebSocketServer close bookkeeping", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t);
|
||||
const entry = [...f.entries.values()][0]!;
|
||||
const closed = once(entry.ws, "close");
|
||||
await f.bridge.terminateSession(entry.id);
|
||||
// Do not await our close listener: a broken removeAllListeners erases it too.
|
||||
await once(f.socket, "close");
|
||||
await nextTurn();
|
||||
assert.equal(f.wss.clients.size, 0);
|
||||
await closed;
|
||||
});
|
||||
|
||||
test("loopback PCM reaches the SDK as native Opus and malformed PCM is rejected", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t);
|
||||
const sent = once(f.sdk, "sent");
|
||||
f.socket.send(Buffer.alloc(1_920));
|
||||
await sent;
|
||||
const encoded = f.sdk.sent[0]!;
|
||||
assert.ok(encoded.length > 0 && encoded.length < 1_920, "must encode Opus, not pass through PCM");
|
||||
const decoder = new OpusEncoder(48_000, 1);
|
||||
try { assert.equal(decoder.decode(encoded).length, 1_920); }
|
||||
finally { decoder.dispose(); }
|
||||
const error = once(f.socket, "message");
|
||||
f.socket.send(Buffer.alloc(1_919));
|
||||
const [raw] = await error;
|
||||
assert.equal(JSON.parse(raw.toString()).error.code, "INVALID_AUDIO_FRAME");
|
||||
assert.equal(f.sdk.sent.length, 1);
|
||||
});
|
||||
|
||||
test("failed final peer statistics do not interrupt session cleanup", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t);
|
||||
const entry = [...f.entries.values()][0]!;
|
||||
entry.webrtc = { close: async () => {}, getStats() { throw new Error("Closed peer"); } } as unknown as WebRtcAudioSession;
|
||||
await f.bridge.terminateSession(entry.id);
|
||||
assert.equal(f.sdk.disconnected, true);
|
||||
assert.notEqual(entry.ws.readyState, WebSocket.OPEN);
|
||||
assert.equal(f.bridge.getActiveCount(), 0);
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import pino from "pino";
|
||||
import { VoiceBridge } from "./voice-bridge.js";
|
||||
import { JoinTicketStore } from "./join-ticket.js";
|
||||
import { createAudioFlowStats } from "./audio-stats.js";
|
||||
import { SessionAudioTransport } from "./session-audio.js";
|
||||
import type { WebRtcAudioSession, WebRtcAudioSessionOptions, WebRtcSessionDescription } from "./webrtc-audio.js";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
|
||||
@@ -21,6 +22,7 @@ class PeerStub {
|
||||
constructor(readonly options: WebRtcAudioSessionOptions) {}
|
||||
async close() { this.closed = true; await this.closeResult; }
|
||||
getStats() { return { webrtcIngressRtpFrames: 10 }; }
|
||||
pushTeamSpeakVoice() {}
|
||||
async createAnswer(offer: WebRtcSessionDescription): Promise<WebRtcSessionDescription> {
|
||||
await this.answerResult;
|
||||
return { type: "answer", sdp: offer.sdp };
|
||||
@@ -31,10 +33,11 @@ function fixture() {
|
||||
const peers: PeerStub[] = [];
|
||||
const messages: ServerMessage[] = [];
|
||||
const entry = {
|
||||
id: "session", session: { state: "connected" }, ws: { readyState: 1 },
|
||||
id: "session", session: { state: "connected" }, ws: { readyState: 1 as 0 | 1 | 2 | 3, bufferedAmount: 0, send() {} },
|
||||
webrtc: null as PeerStub | null, webrtcGeneration: 0,
|
||||
tsClient: { setInputMuted: async (_muted: boolean) => {}, sendVoice: () => { forwarded++; } },
|
||||
tsClient: { setInputMuted: async (_muted: boolean) => {}, sendVoice: () => { forwarded++; }, sendWhisper: () => { forwarded++; } },
|
||||
whisperActive: false, whisperTargetIds: new Set<number>(), audio: createAudioFlowStats(),
|
||||
audioTransport: null as SessionAudioTransport | null,
|
||||
};
|
||||
let forwarded = 0;
|
||||
let configurePeer = (_peer: PeerStub): void => {};
|
||||
@@ -52,6 +55,12 @@ function fixture() {
|
||||
stopWebRtc(entry: Entry): Promise<void>;
|
||||
};
|
||||
bridge.entries.set(entry.id, entry);
|
||||
entry.audioTransport = new SessionAudioTransport({
|
||||
audio: entry.audio, socket: entry.ws, client: entry.tsClient,
|
||||
isCurrent: () => bridge.entries.get(entry.id) === entry,
|
||||
isReady: () => entry.session.state === "connected", selfId: () => 1,
|
||||
peer: () => entry.webrtc, whisperTargets: () => null, sendJson: message => messages.push(message),
|
||||
}, { encode: frame => frame, dispose() {} });
|
||||
const offer = (sdp: string) => bridge.handleWebRtcOffer(entry, { type: "offer", sdp }, message => messages.push(message));
|
||||
return { bridge, entry, peers, messages, offer, forwarded: () => forwarded, configure: (callback: typeof configurePeer) => { configurePeer = callback; } };
|
||||
}
|
||||
|
||||
+40
-127
@@ -1,3 +1,4 @@
|
||||
import { SessionAudioTransport } from "./session-audio.js";
|
||||
import { ScreenShareCoordinator } from "./screen-share-coordinator.js";
|
||||
import { handleCommand } from "./voice-commands.js";
|
||||
import { createAudioFlowStats, snapshotAudioStats, type AudioFlowStats } from "./audio-stats.js";
|
||||
@@ -13,7 +14,7 @@ import { randomUUID } from "node:crypto";
|
||||
import { isIP } from "node:net";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { DirectorySynchronizer } from "./directory-sync.js";
|
||||
import { TSClient, type TSDirectorySnapshot, type TSVoiceData, type TSRawNotification } from "./ts-client.js";
|
||||
import { TSClient, type TSClientOptions, type TSDirectorySnapshot, type TSVoiceData, type TSRawNotification } from "./ts-client.js";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
import { clientConnectionFailureCode, describeTeamSpeakError, normalizeTeamSpeakError, type WebSpeakError } from "../errors.js";
|
||||
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
@@ -28,15 +29,6 @@ import { normalizeScreenShareIceServers, parseScreenShareMessage, type ScreenSha
|
||||
import { OpusEncoder } from "./opus-codec.js";
|
||||
|
||||
const HEARTBEAT_INTERVAL_MS = 30_000;
|
||||
const AUDIO_FRAME_BYTES = 1_920;
|
||||
// A browser audio frame is 20 ms of mono 48 kHz PCM. Keep the server-side
|
||||
// WebSocket egress queue small enough that a slow browser cannot turn old
|
||||
// voice into seconds of latency. Opus frames are variable-sized, so this is
|
||||
// deliberately a conservative byte backpressure guard for roughly 10–20
|
||||
// small Opus frames; the browser also enforces a time-based playback limit
|
||||
// before scheduling decoded audio.
|
||||
const MAX_SERVER_AUDIO_BUFFERED_BYTES = 4_096;
|
||||
|
||||
function publicFailureDetail(error: ReturnType<typeof normalizeTeamSpeakError>): string | undefined {
|
||||
const serverMessage = error.diagnostics.serverMessage?.trim();
|
||||
const serverId = error.diagnostics.id?.trim();
|
||||
@@ -53,6 +45,11 @@ export interface VoiceBridgeOptions {
|
||||
accelerationName?: string | (() => string | undefined);
|
||||
}
|
||||
|
||||
interface VoiceBridgeDependencies {
|
||||
createTeamSpeakClient?(options: TSClientOptions, logger: LoggerType): TSClient;
|
||||
createEncoder?(): Pick<OpusEncoder, "encode" | "dispose">;
|
||||
}
|
||||
|
||||
export interface AdminSessionSummary {
|
||||
id: string;
|
||||
nickname: string;
|
||||
@@ -86,8 +83,7 @@ interface WebClientEntry {
|
||||
members: Map<number, ChannelMember>;
|
||||
avatarCache: Map<string, string | null>;
|
||||
eventLog: ServerEvent[];
|
||||
opusEncoder: OpusEncoder | null;
|
||||
opusEncoderWarnedAt: number; // Opus 编码器不可用告警的时间戳,用于限流避免反复刷屏
|
||||
audioTransport: SessionAudioTransport | null;
|
||||
whisperTargetIds: Set<number>;
|
||||
whisperActive: boolean;
|
||||
isAlive: boolean;
|
||||
@@ -114,6 +110,7 @@ export class VoiceBridge {
|
||||
private options: VoiceBridgeOptions,
|
||||
logger: LoggerType,
|
||||
private readonly createWebRtcSession: (options: WebRtcAudioSessionOptions) => WebRtcAudioSession = options => new WebRtcAudioSession(options),
|
||||
private readonly dependencies: VoiceBridgeDependencies = {},
|
||||
) {
|
||||
this.logger = logger.child({ component: "voice-bridge" });
|
||||
this.screenShares = new ScreenShareCoordinator(this.entries, (entryId, message) => {
|
||||
@@ -186,10 +183,12 @@ export class VoiceBridge {
|
||||
}, "WebClient connecting");
|
||||
let tsClient: TSClient;
|
||||
try {
|
||||
tsClient = new TSClient({ target, nickname, serverPassword, defaultChannel: channelName, identity, ...(acceleration ? { acceleration } : {}) }, this.logger);
|
||||
const createClient = this.dependencies.createTeamSpeakClient ?? ((options, logger) => new TSClient(options, logger));
|
||||
tsClient = createClient({ target, nickname, serverPassword, defaultChannel: channelName, identity, ...(acceleration ? { acceleration } : {}) }, this.logger);
|
||||
} catch (error: unknown) {
|
||||
if (identityLeaseKey) this.identityLeases.release(identityLeaseKey, entryId);
|
||||
this.logger.error({ err: error, entryId }, "Could not create TeamSpeak client");
|
||||
void this.sessionManager.teardown(entryId, "teamSpeak-connect-failed");
|
||||
// A 4003 with a bare close used to be reported as "identity rejected".
|
||||
// Send a structured failure so the browser says the TeamSpeak client
|
||||
// could not be created (server down / unreachable) instead.
|
||||
@@ -214,8 +213,7 @@ export class VoiceBridge {
|
||||
members: new Map(),
|
||||
avatarCache: new Map(),
|
||||
eventLog: [],
|
||||
opusEncoder: null,
|
||||
opusEncoderWarnedAt: 0,
|
||||
audioTransport: null,
|
||||
whisperTargetIds: new Set(),
|
||||
whisperActive: false,
|
||||
isAlive: true,
|
||||
@@ -228,16 +226,27 @@ export class VoiceBridge {
|
||||
screenPeerId: entryId,
|
||||
};
|
||||
this.entries.set(entryId, entry!);
|
||||
let tsReady = false;
|
||||
let selfId = 0;
|
||||
const sendJson = (message: ServerMessage) => {
|
||||
if (this.entries.get(entryId) === entry && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
|
||||
};
|
||||
try {
|
||||
entry!.opusEncoder = new OpusEncoder(48000, 1);
|
||||
entry.audioTransport = new SessionAudioTransport({
|
||||
audio: entry.audio, socket: ws, client: tsClient,
|
||||
isCurrent: () => this.entries.get(entryId) === entry,
|
||||
isReady: () => tsReady && session.state === "connected",
|
||||
selfId: () => selfId,
|
||||
peer: () => entry!.webrtc,
|
||||
whisperTargets: () => entry!.whisperActive ? [...entry!.whisperTargetIds] : null,
|
||||
sendJson: message => sendJson(message),
|
||||
}, this.dependencies.createEncoder?.() ?? new OpusEncoder(48000, 1));
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({ err: error, entryId }, "Could not create Opus encoder");
|
||||
void this.teardown(entryId, "teamSpeak-connect-failed");
|
||||
return;
|
||||
}
|
||||
|
||||
let tsReady = false;
|
||||
let selfId = 0;
|
||||
let selfChannelId = 0n;
|
||||
let initialStateSent = false;
|
||||
let audioReady = true;
|
||||
@@ -254,9 +263,6 @@ export class VoiceBridge {
|
||||
let avatarRefreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let avatarRefreshRunning = false;
|
||||
|
||||
const sendJson = (message: ServerMessage) => {
|
||||
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
|
||||
};
|
||||
const addServerEvent = (kind: ServerEvent["kind"], message: string) => {
|
||||
const event: ServerEvent = {
|
||||
id: `event-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
|
||||
@@ -578,50 +584,7 @@ export class VoiceBridge {
|
||||
this.screenShares.handleNotification(entry!, notification);
|
||||
});
|
||||
|
||||
tsClient.on("voiceData", (data: TSVoiceData) => {
|
||||
const receivedAt = Date.now();
|
||||
if (entry!.audio.tsReceiveLastAt !== null) entry!.audio.tsReceiveMaxGapMs = Math.max(entry!.audio.tsReceiveMaxGapMs, receivedAt - entry!.audio.tsReceiveLastAt);
|
||||
entry!.audio.tsReceiveFirstAt ??= receivedAt;
|
||||
entry!.audio.tsReceiveLastAt = receivedAt;
|
||||
entry!.audio.tsReceiveFrames++;
|
||||
if (ws.readyState !== WebSocket.OPEN || data.clientId === selfId) return;
|
||||
const webRtc = entry!.webrtc;
|
||||
webRtc?.pushTeamSpeakVoice(data);
|
||||
const now = receivedAt;
|
||||
if (entry!.audio.egressLastAt !== null) entry!.audio.egressMaxGapMs = Math.max(entry!.audio.egressMaxGapMs, now - entry!.audio.egressLastAt);
|
||||
entry!.audio.egressFirstAt ??= now;
|
||||
entry!.audio.egressLastAt = now;
|
||||
const sourceKey = String(data.clientId);
|
||||
entry!.audio.egressFramesByClient[sourceKey] = (entry!.audio.egressFramesByClient[sourceKey] ?? 0) + 1;
|
||||
// A negotiated WebRTC session owns the browser's realtime audio
|
||||
// egress. Do not also send the same TeamSpeak packet over the
|
||||
// reliable WebSocket, otherwise the browser plays two copies and
|
||||
// the TCP path can still accumulate stale audio behind the peer.
|
||||
if (webRtc) {
|
||||
entry!.audio.egressFrames++;
|
||||
return;
|
||||
}
|
||||
const packet = Buffer.allocUnsafe(3 + data.data.length);
|
||||
packet[0] = data.codec;
|
||||
packet.writeUInt16BE(data.clientId, 1);
|
||||
data.data.copy(packet, 3);
|
||||
const bufferedBytes = ws.bufferedAmount;
|
||||
entry!.audio.egressPeakBufferedBytes = Math.max(entry!.audio.egressPeakBufferedBytes, bufferedBytes);
|
||||
if (bufferedBytes > MAX_SERVER_AUDIO_BUFFERED_BYTES) {
|
||||
entry!.audio.egressDroppedFrames++;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
ws.send(packet);
|
||||
entry!.audio.egressFrames++;
|
||||
const sentAt = Date.now();
|
||||
if (entry!.audio.egressSentLastAt !== null) entry!.audio.egressSentMaxGapMs = Math.max(entry!.audio.egressSentMaxGapMs, sentAt - entry!.audio.egressSentLastAt);
|
||||
entry!.audio.egressSentFirstAt ??= sentAt;
|
||||
entry!.audio.egressSentLastAt = sentAt;
|
||||
} catch {
|
||||
entry!.audio.egressDroppedFrames++;
|
||||
}
|
||||
});
|
||||
tsClient.on("voiceData", (data: TSVoiceData) => entry!.audioTransport?.receiveTeamSpeak(data));
|
||||
|
||||
tsClient.on("textMessage", (message) => {
|
||||
const scope = message.targetMode === 1 ? "private" : message.targetMode === 3 ? "server" : message.targetMode === 2 ? "channel" : "server";
|
||||
@@ -679,46 +642,9 @@ export class VoiceBridge {
|
||||
|
||||
ws.on("pong", () => { if (entry) entry.isAlive = true; });
|
||||
ws.on("message", (data: Buffer | string, isBinary: boolean) => {
|
||||
if (this.entries.get(entryId) !== entry) return;
|
||||
if (isBinary) {
|
||||
const frame = typeof data === "string" ? Buffer.from(data) : data;
|
||||
if (!tsReady || frame.length !== AUDIO_FRAME_BYTES) {
|
||||
entry!.audio.ingressDroppedFrames++;
|
||||
sendProtocolError(sendJson, "INVALID_AUDIO_FRAME", "音频帧格式无效");
|
||||
return;
|
||||
}
|
||||
const now = Date.now();
|
||||
if (entry!.audio.ingressLastAt !== null) entry!.audio.ingressMaxGapMs = Math.max(entry!.audio.ingressMaxGapMs, now - entry!.audio.ingressLastAt);
|
||||
entry!.audio.ingressFirstAt ??= now;
|
||||
entry!.audio.ingressLastAt = now;
|
||||
entry!.audio.ingressFrames++;
|
||||
const encodeStartedAt = Date.now();
|
||||
try {
|
||||
if (entry!.opusEncoder) {
|
||||
const encoded = entry!.opusEncoder.encode(frame);
|
||||
const encodedAt = Date.now();
|
||||
entry!.audio.tsEncodeMaxMs = Math.max(entry!.audio.tsEncodeMaxMs, encodedAt - encodeStartedAt);
|
||||
if (entry!.whisperActive && entry!.whisperTargetIds.size) tsClient.sendWhisper(encoded, [...entry!.whisperTargetIds], 4);
|
||||
else tsClient.sendVoice(encoded, 4);
|
||||
const sentAt = Date.now();
|
||||
if (entry!.audio.tsSendLastAt !== null) entry!.audio.tsSendMaxGapMs = Math.max(entry!.audio.tsSendMaxGapMs, sentAt - entry!.audio.tsSendLastAt);
|
||||
entry!.audio.tsSendFirstAt ??= sentAt;
|
||||
entry!.audio.tsSendLastAt = sentAt;
|
||||
entry!.audio.tsSendFrames++;
|
||||
} else {
|
||||
// Opus 编码器不可用(初始化失败或销毁后仍有帧在途):显式告知浏览器
|
||||
// 而不是静默丢帧,5 秒限流避免高频告警刷屏。
|
||||
// The Opus encoder is unavailable (init failed or torn down while
|
||||
// frames are still in flight): say it instead of dropping silently.
|
||||
const warnedAt = entry!.opusEncoderWarnedAt;
|
||||
if (Date.now() - warnedAt > 5_000) {
|
||||
entry!.opusEncoderWarnedAt = Date.now();
|
||||
sendJson({ type: "audioError", code: "AUDIO_ENCODER_UNAVAILABLE", detail: "Opus encoder unavailable" });
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// A frame arriving during shutdown is safe to discard.
|
||||
entry!.audio.tsSendErrors++;
|
||||
}
|
||||
entry!.audioTransport?.receivePcm(typeof data === "string" ? Buffer.from(data) : data);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -864,8 +790,8 @@ export class VoiceBridge {
|
||||
clearTimeout(entry.reconnectTimer);
|
||||
entry.reconnectTimer = null;
|
||||
}
|
||||
entry.opusEncoder?.dispose();
|
||||
entry.opusEncoder = null;
|
||||
entry.audioTransport?.close();
|
||||
entry.audioTransport = null;
|
||||
await this.stopWebRtc(entry);
|
||||
entry.whisperTargetIds.clear();
|
||||
entry.whisperActive = false;
|
||||
@@ -873,7 +799,10 @@ export class VoiceBridge {
|
||||
entry.members.clear();
|
||||
entry.tsClient.removeAllListeners();
|
||||
try { await entry.tsClient.disconnect(); } catch { /* disconnect is intentionally idempotent */ }
|
||||
entry.ws.removeAllListeners();
|
||||
// Preserve WebSocketServer's close listener, which removes this socket
|
||||
// from its clients set and allows server shutdown to finish.
|
||||
entry.ws.removeAllListeners("message");
|
||||
entry.ws.removeAllListeners("pong");
|
||||
if (entry.ws.readyState === WebSocket.OPEN || entry.ws.readyState === WebSocket.CONNECTING) {
|
||||
if (reason === "heartbeat-timeout" || reason === "gateway-shutdown") entry.ws.terminate();
|
||||
else entry.ws.close(reason === "protocol-error" ? 1008 : 1000, reason);
|
||||
@@ -940,7 +869,9 @@ export class VoiceBridge {
|
||||
entry.webrtc = null;
|
||||
if (!peer) return;
|
||||
try { await peer.close(); } catch { /* peer teardown is idempotent */ }
|
||||
if (entry.webrtcGeneration === generation) Object.assign(entry.audio, peer.getStats());
|
||||
if (entry.webrtcGeneration === generation) {
|
||||
try { Object.assign(entry.audio, peer.getStats()); } catch { /* diagnostics must not abort cleanup */ }
|
||||
}
|
||||
}
|
||||
|
||||
private async handleWebRtcOffer(
|
||||
@@ -978,25 +909,7 @@ export class VoiceBridge {
|
||||
microphoneMuted: muted,
|
||||
accompanimentActive: offer.accompanimentActive === true,
|
||||
onVoiceFrame: (data, codec) => {
|
||||
if (!isCurrentPeer()) return;
|
||||
const now = Date.now();
|
||||
if (entry.audio.ingressLastAt !== null) entry.audio.ingressMaxGapMs = Math.max(entry.audio.ingressMaxGapMs, now - entry.audio.ingressLastAt);
|
||||
entry.audio.ingressFirstAt ??= now;
|
||||
entry.audio.ingressLastAt = now;
|
||||
entry.audio.ingressFrames++;
|
||||
try {
|
||||
if (entry.whisperActive && entry.whisperTargetIds.size) entry.tsClient.sendWhisper(data, [...entry.whisperTargetIds], codec);
|
||||
else entry.tsClient.sendVoice(data, codec);
|
||||
const sentAt = Date.now();
|
||||
if (entry.audio.tsSendLastAt !== null) entry.audio.tsSendMaxGapMs = Math.max(entry.audio.tsSendMaxGapMs, sentAt - entry.audio.tsSendLastAt);
|
||||
entry.audio.tsSendFirstAt ??= sentAt;
|
||||
entry.audio.tsSendLastAt = sentAt;
|
||||
entry.audio.tsSendFrames++;
|
||||
} catch {
|
||||
entry.audio.tsSendErrors++;
|
||||
// A packet arriving while the TeamSpeak session is being replaced
|
||||
// is discarded; the WebRTC peer remains independently closable.
|
||||
}
|
||||
if (isCurrentPeer()) entry.audioTransport?.receiveWebRtc(data, codec);
|
||||
},
|
||||
onVoiceActivity: (clientIds) => {
|
||||
if (isCurrentPeer()) sendJson({ type: "voiceActivity", clientIds });
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { WebRtcAudioSession } from "./webrtc-audio.js";
|
||||
|
||||
function fixture() {
|
||||
const released: string[] = [];
|
||||
// Exercise the real close path with failures at codec/track/peer boundaries.
|
||||
const resources = {
|
||||
closed: false, closePromise: null, audioTimer: null, activityTimer: undefined,
|
||||
pendingFrames: new Map([[1, []]]), memberVolumes: new Map([[1, 1]]),
|
||||
partialPcmByClient: new Map([[1, Buffer.alloc(2)]]), activeSpeakerIds: new Set([1]),
|
||||
decoderByClient: new Map([
|
||||
[1, { dispose() { released.push("decoder-1"); throw new Error("Decoder failed"); } }],
|
||||
[2, { dispose() { released.push("decoder-2"); } }],
|
||||
]),
|
||||
encoder: { dispose(): void { released.push("encoder"); throw new Error("Encoder failed"); } },
|
||||
outgoingTrack: { stop(): void { released.push("track"); throw new Error("Track failed"); } },
|
||||
peer: { async close() { released.push("peer"); } },
|
||||
};
|
||||
const session = Object.assign(Object.create(WebRtcAudioSession.prototype), resources) as WebRtcAudioSession;
|
||||
return { session, resources, released };
|
||||
}
|
||||
|
||||
test("WebRTC close releases remaining codecs, track and peer after disposal failures", async () => {
|
||||
const f = fixture();
|
||||
await f.session.close();
|
||||
await f.session.close();
|
||||
assert.deepEqual(f.released, ["decoder-1", "decoder-2", "encoder", "track", "peer"]);
|
||||
assert.equal(f.resources.decoderByClient.size, 0);
|
||||
assert.equal(f.resources.pendingFrames.size, 0);
|
||||
assert.equal(f.resources.memberVolumes.size, 0);
|
||||
assert.equal(f.resources.partialPcmByClient.size, 0);
|
||||
assert.equal(f.resources.activeSpeakerIds.size, 0);
|
||||
});
|
||||
|
||||
test("concurrent WebRTC close callers await the same pending peer shutdown", async () => {
|
||||
const f = fixture();
|
||||
f.resources.decoderByClient.clear();
|
||||
f.resources.encoder.dispose = () => {};
|
||||
f.resources.outgoingTrack.stop = () => {};
|
||||
let release!: () => void;
|
||||
const pending = new Promise<void>(resolve => { release = resolve; });
|
||||
let closes = 0;
|
||||
f.resources.peer.close = async () => { closes++; await pending; };
|
||||
const first = f.session.close();
|
||||
let secondCompleted = false;
|
||||
const second = f.session.close().then(() => { secondCompleted = true; });
|
||||
await Promise.resolve();
|
||||
const completedEarly = secondCompleted;
|
||||
release();
|
||||
await Promise.all([first, second]);
|
||||
assert.equal(completedEarly, false);
|
||||
assert.equal(closes, 1);
|
||||
});
|
||||
|
||||
test("a rejected peer shutdown is shared without repeating partial cleanup", async () => {
|
||||
const f = fixture();
|
||||
const failure = new Error("Peer shutdown failed");
|
||||
f.resources.peer.close = async () => { f.released.push("peer"); throw failure; };
|
||||
const first = f.session.close();
|
||||
const second = f.session.close();
|
||||
assert.equal(first, second);
|
||||
await assert.rejects(first, error => error === failure);
|
||||
await assert.rejects(second, error => error === failure);
|
||||
await assert.rejects(f.session.close(), error => error === failure);
|
||||
assert.deepEqual(f.released, ["decoder-1", "decoder-2", "encoder", "track", "peer"]);
|
||||
assert.equal(f.resources.decoderByClient.size, 0);
|
||||
});
|
||||
@@ -110,6 +110,7 @@ export class WebRtcAudioSession {
|
||||
private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0;
|
||||
private outgoingPayloadType = DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE;
|
||||
private closed = false;
|
||||
private closePromise: Promise<void> | null = null;
|
||||
private nextAudioDeadline = 0;
|
||||
private lastIngressRtpAt: number | null = null;
|
||||
private lastEgressRtpAt: number | null = null;
|
||||
@@ -293,8 +294,8 @@ export class WebRtcAudioSession {
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.closed) return;
|
||||
close(): Promise<void> {
|
||||
if (this.closePromise) return this.closePromise;
|
||||
this.closed = true;
|
||||
if (this.audioTimer) clearTimeout(this.audioTimer);
|
||||
this.audioTimer = null;
|
||||
@@ -303,12 +304,21 @@ export class WebRtcAudioSession {
|
||||
this.memberVolumes.clear();
|
||||
this.partialPcmByClient.clear();
|
||||
this.activeSpeakerIds.clear();
|
||||
for (const decoder of this.decoderByClient.values()) decoder.dispose();
|
||||
this.decoderByClient.clear();
|
||||
this.encoder?.dispose();
|
||||
this.encoder = null;
|
||||
this.outgoingTrack.stop();
|
||||
await this.peer.close();
|
||||
// Publish the completion before disposing resources: even reentrant or
|
||||
// concurrent callers must wait for the same physical peer shutdown.
|
||||
this.closePromise = Promise.resolve().then(async () => {
|
||||
const decoders = [...this.decoderByClient.values()];
|
||||
this.decoderByClient.clear();
|
||||
for (const decoder of decoders) {
|
||||
try { decoder.dispose(); } catch { /* continue releasing other resources */ }
|
||||
}
|
||||
const encoder = this.encoder;
|
||||
this.encoder = null;
|
||||
try { encoder?.dispose(); } catch { /* the track and peer still need closing */ }
|
||||
try { this.outgoingTrack.stop(); } catch { /* always attempt peer shutdown */ }
|
||||
await this.peer.close();
|
||||
});
|
||||
return this.closePromise;
|
||||
}
|
||||
|
||||
private scheduleAudioTick(): void {
|
||||
|
||||
Reference in new issue
Block a user