diff --git a/src/server/session-audio.test.ts b/src/server/session-audio.test.ts index aaf5c96..5a5989e 100644 --- a/src/server/session-audio.test.ts +++ b/src/server/session-audio.test.ts @@ -2,6 +2,7 @@ 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 { Logger as LoggerType } from "../logger.js"; import type { ServerMessage } from "../shared/server-messages.js"; import type { TSVoiceData } from "./ts-client.js"; @@ -13,6 +14,14 @@ function fixture() { const encoded: Buffer[] = []; const forwarded: Array<{ data: Buffer; codec: number; targets?: number[] }> = []; const notices: ServerMessage[] = []; + const warnings: Array> = []; + const logger: LoggerType = { + debug: () => {}, + info: () => {}, + error: () => {}, + warn: (objOrMsg: Record | string) => { if (typeof objOrMsg !== "string") warnings.push(objOrMsg); }, + child: () => logger, + }; 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 }); }, @@ -23,12 +32,12 @@ function fixture() { dispose() { state.disposed++; }, }; const transport = new SessionAudioTransport({ - audio, socket, client, isCurrent: () => state.current, isReady: () => state.ready, + audio, socket, client, logger, 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 }; + return { transport, audio, state, socket, client, encoder, packets, encoded, forwarded, notices, warnings, remote }; } test("PCM framing preserves codec, whisper routing and timing counters", () => { @@ -49,19 +58,45 @@ test("PCM framing preserves codec, whisper routing and timing counters", () => { test("invalid PCM is rejected and reconnecting sessions do not encode audio", () => { const f = fixture(); f.transport.receivePcm(Buffer.alloc(1_919)); + f.state.now = 5_000; 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 } }); + assert.deepEqual(f.notices[1], f.notices[0]); f.state.ready = false; + f.state.now = 10_000; + f.transport.receivePcm(Buffer.alloc(1_919)); + assert.equal(f.notices.length, 2, "a frame the route discards must not be reported as malformed"); + assert.equal(f.warnings.length, 2, "a frame the route discards must not reach the operator log"); 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.audio.ingressDroppedFrames, 4); assert.equal(f.encoded.length, 0); assert.equal(f.forwarded.length, 0); assert.equal(f.packets.length, 0); }); +test("repeated malformed frames are counted in full but reported once per window", () => { + const f = fixture(); + for (const now of [0, 1, 4_999, 5_000]) { f.state.now = now; f.transport.receivePcm(Buffer.alloc(1_919)); } + assert.equal(f.audio.ingressDroppedFrames, 4, "every discarded frame still reaches the flow counters"); + assert.equal(f.notices.length, 2, "the browser sees one error per window, not one per frame"); + assert.deepEqual(f.warnings, [ + { code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: 1_920, droppedFrames: 1 }, + { code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: 1_920, droppedFrames: 4 }, + ], "operators get the same rate-limited view through the logger"); +}); + +test("an encoder failure and a malformed frame do not suppress each other", t => { + const f = fixture(); + t.mock.method(f.encoder, "encode", () => { throw new Error("Codec failed"); }); + f.transport.receivePcm(Buffer.alloc(1_919)); + f.transport.receivePcm(Buffer.alloc(1_920)); + assert.deepEqual(f.notices.map(message => message.type), ["error", "audioError"]); + t.mock.restoreAll(); +}); + test("WebRTC ingress excludes queued PCM and fallback re-enables PCM", () => { const f = fixture(); f.state.peer = { pushTeamSpeakVoice() {} }; diff --git a/src/server/session-audio.ts b/src/server/session-audio.ts index 73adf46..ae534c2 100644 --- a/src/server/session-audio.ts +++ b/src/server/session-audio.ts @@ -1,4 +1,5 @@ import { WebSocket } from "ws"; +import type { Logger as LoggerType } from "../logger.js"; import type { ServerMessage } from "../shared/server-messages.js"; import type { AudioFlowStats } from "./audio-stats.js"; import type { TSClient, TSVoiceData } from "./ts-client.js"; @@ -7,6 +8,10 @@ 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; +// A client that keeps sending bad audio must not turn into one JSON error per +// frame: the reply is roughly 100x the offending payload, and the browser only +// ever shows the first one because it writes the same error string. +const AUDIO_ISSUE_REPORT_MS = 5_000; export interface VoiceEncoder { encode(frame: Buffer): Buffer; @@ -17,6 +22,8 @@ export interface SessionAudioOptions { audio: AudioFlowStats; socket: Pick & { send(packet: Buffer): void }; client: Pick; + /** Optional: audio faults are also surfaced here so operators can see them. */ + logger?: LoggerType; isCurrent(): boolean; isReady(): boolean; selfId(): number; @@ -29,10 +36,13 @@ export interface SessionAudioOptions { export class SessionAudioTransport { private encoder: VoiceEncoder | null; private closed = false; - private warnedAt: number | null = null; + /** Last report time per audio fault code; see `shouldReportAudioIssue`. */ + private readonly reportedAt = new Map(); + private readonly logger: LoggerType | null; constructor(private readonly options: SessionAudioOptions, encoder: VoiceEncoder, private readonly clock: () => number = Date.now) { this.encoder = encoder; + this.logger = options.logger ?? null; } private isCurrent(): boolean { @@ -64,25 +74,59 @@ export class SessionAudioTransport { } } - private reportEncoderFailure(): void { + /** + * Decide whether an audio fault is worth reporting right now. Repeated faults + * of the same kind collapse into one report per window. Codes are tracked + * separately so that one fault cannot hide a different one, which a single + * shared window would do. + * + * The browser only renders the first error string of a run, so dropping the + * repeats costs the user nothing; what it saves is the server-side cost, which + * is proportional to however fast the client streams bad frames. + */ + private shouldReportAudioIssue(code: string): boolean { const now = this.clock(); - if (this.warnedAt !== null && now - this.warnedAt < 5_000) return; - this.warnedAt = now; + const last = this.reportedAt.get(code); + if (last !== undefined && now - last < AUDIO_ISSUE_REPORT_MS) return false; + this.reportedAt.set(code, now); + return true; + } + + private reportEncoderFailure(): void { + if (!this.shouldReportAudioIssue("AUDIO_ENCODER_UNAVAILABLE")) return; + this.logger?.warn({ code: "AUDIO_ENCODER_UNAVAILABLE" }, "Opus encoder unavailable for the browser uplink"); try { this.options.sendJson({ type: "audioError", code: "AUDIO_ENCODER_UNAVAILABLE", detail: "Opus encoder unavailable" }); } catch { /* the socket may have closed while reporting the failure */ } } + private reportInvalidFrame(length: number): void { + if (!this.shouldReportAudioIssue("INVALID_AUDIO_FRAME")) return; + // Log the faults that the browser is told about: the outbound error is not + // logged anywhere, so without this an operator has no way to notice a client + // that keeps sending malformed audio until the session is torn down. + this.logger?.warn( + { code: "INVALID_AUDIO_FRAME", frameBytes: length, expectedBytes: AUDIO_FRAME_BYTES, droppedFrames: this.options.audio.ingressDroppedFrames }, + "Discarded malformed browser audio frame", + ); + try { + this.options.sendJson({ type: "error", error: { code: "INVALID_AUDIO_FRAME", message: "音频帧格式无效", recoverable: false } }); + } 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; - } + // Resolve the route before judging the frame. A frame that arrives while the + // route is down is discarded whatever its size, so calling it malformed would + // misattribute the drop and raise a spurious client error in the browser. // Late TCP frames from before a WebRTC switch must not duplicate RTP audio. if (!this.options.isReady() || this.options.peer()) { stats.ingressDroppedFrames++; return; } + if (frame.length !== AUDIO_FRAME_BYTES) { + stats.ingressDroppedFrames++; + this.reportInvalidFrame(frame.length); + return; + } this.recordIngress(); const startedAt = this.clock(); let encoded: Buffer; @@ -150,6 +194,7 @@ export class SessionAudioTransport { close(): void { if (this.closed) return; this.closed = true; + this.reportedAt.clear(); const encoder = this.encoder; this.encoder = null; try { encoder?.dispose(); } catch { /* other session resources must still be released */ } diff --git a/src/server/voice-bridge.ts b/src/server/voice-bridge.ts index 89d2665..4eae8d9 100644 --- a/src/server/voice-bridge.ts +++ b/src/server/voice-bridge.ts @@ -235,6 +235,7 @@ export class VoiceBridge { try { entry.audioTransport = new SessionAudioTransport({ audio: entry.audio, socket: ws, client: tsClient, + logger: this.logger.child({ component: "session-audio", entryId }), isCurrent: () => this.entries.get(entryId) === entry, isReady: () => tsReady && session.state === "connected", selfId: () => entry!.events?.selfId ?? 0,