mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
feat(voice): support Cloudflare Tunnel deployments and WebRTC fallback
Route page and signaling traffic through Cloudflare Tunnel while sending WebRTC media over direct UDP, with optional TURN REST as a fallback. When WebRTC was already offered and then fails, stay in the current session, automatically resume compatibility audio, and keep a Reconnect WebRTC control. A reconnect retries WebRTC only, leaves compatibility running until it succeeds, and stays on compatibility if it fails again. Database schema 14 adds nullable voice override columns and is a one-way boundary: older binaries reject this database. This change is for review, not a production rollout.
This commit is contained in:
1 parent
9a12e2ee7b
commit
b6e7b1e4da
68 files changed
+3525
-189
No files matched your search
@@ -0,0 +1,73 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { AudioPacer } from "./audio-pacer.js";
|
||||
|
||||
function fakeClock() {
|
||||
let now = 0;
|
||||
let nextId = 1;
|
||||
let task: { id: number; at: number; callback: () => void } | null = null;
|
||||
const schedule = (callback: () => void, delayMs: number) => {
|
||||
task = { id: nextId++, at: now + delayMs, callback };
|
||||
return task as unknown as ReturnType<typeof setTimeout>;
|
||||
};
|
||||
const cancel = (handle: ReturnType<typeof setTimeout>) => {
|
||||
if (task && task.id === (handle as unknown as { id: number }).id) task = null;
|
||||
};
|
||||
const runNext = () => {
|
||||
assert.ok(task, "expected a scheduled tick");
|
||||
now = Math.max(now, task.at);
|
||||
const callback = task.callback;
|
||||
task = null;
|
||||
callback();
|
||||
};
|
||||
return { now: () => now, setNow: (value: number) => { now = value; }, schedule, cancel, runNext, hasTask: () => task !== null };
|
||||
}
|
||||
|
||||
test("pacer emits one frame every 20 ms and preserves order", () => {
|
||||
const clock = fakeClock();
|
||||
const sent: number[] = [];
|
||||
const pacer = new AudioPacer((_data, codec) => sent.push(codec), {
|
||||
now: clock.now, schedule: clock.schedule, cancel: clock.cancel, maxFrames: 4,
|
||||
});
|
||||
pacer.push(Buffer.from([1]), 1);
|
||||
pacer.push(Buffer.from([2]), 2);
|
||||
pacer.push(Buffer.from([3]), 3);
|
||||
assert.equal(sent.length, 0, "frames wait for the first timer turn");
|
||||
clock.runNext();
|
||||
assert.deepEqual(sent, [1]);
|
||||
assert.equal(pacer.getStats().currentFrames, 2);
|
||||
clock.runNext();
|
||||
assert.deepEqual(sent, [1, 2]);
|
||||
clock.runNext();
|
||||
assert.deepEqual(sent, [1, 2, 3]);
|
||||
assert.equal(pacer.getStats().currentFrames, 0);
|
||||
assert.equal(clock.hasTask(), false);
|
||||
});
|
||||
|
||||
test("pacer drops the oldest frame when the queue is full and records peak", () => {
|
||||
const clock = fakeClock();
|
||||
const pacer = new AudioPacer(() => {}, { now: clock.now, schedule: clock.schedule, cancel: clock.cancel, maxFrames: 2 });
|
||||
pacer.push(Buffer.from([1]), 1);
|
||||
pacer.push(Buffer.from([2]), 2);
|
||||
pacer.push(Buffer.from([3]), 3);
|
||||
const stats = pacer.getStats();
|
||||
assert.equal(stats.currentFrames, 2);
|
||||
assert.equal(stats.peakFrames, 2);
|
||||
assert.equal(stats.droppedFrames, 1);
|
||||
pacer.close();
|
||||
});
|
||||
|
||||
test("a late event-loop turn resets the deadline instead of bursting", () => {
|
||||
const clock = fakeClock();
|
||||
const sent: number[] = [];
|
||||
const pacer = new AudioPacer(() => sent.push(1), {
|
||||
now: clock.now, schedule: clock.schedule, cancel: clock.cancel, maxFrames: 4,
|
||||
});
|
||||
pacer.push(Buffer.from([1]), 1);
|
||||
pacer.push(Buffer.from([2]), 2);
|
||||
clock.setNow(100);
|
||||
clock.runNext();
|
||||
assert.equal(sent.length, 1);
|
||||
assert.equal(pacer.getStats().lateTicks, 1);
|
||||
pacer.close();
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { performance } from "node:perf_hooks";
|
||||
|
||||
/**
|
||||
* A tiny 20 ms sender for browser PCM/Opus uplink. Cloudflare Tunnel can
|
||||
* deliver a burst of WebSocket frames at once; forwarding those frames to
|
||||
* TeamSpeak immediately preserves the burst and makes the receiving client's
|
||||
* jitter buffer work harder. This pacer absorbs the burst and emits at a fixed
|
||||
* cadence, dropping the oldest frame only when the queue is genuinely behind.
|
||||
*/
|
||||
|
||||
export interface PacerFrame {
|
||||
data: Buffer;
|
||||
codec: number;
|
||||
enqueuedAt: number;
|
||||
}
|
||||
|
||||
export interface AudioPacerOptions {
|
||||
frameMs?: number;
|
||||
maxFrames?: number;
|
||||
maxLagMs?: number;
|
||||
now?: () => number;
|
||||
schedule?: (callback: () => void, delayMs: number) => ReturnType<typeof setTimeout>;
|
||||
cancel?: (timer: ReturnType<typeof setTimeout>) => void;
|
||||
onStats?: (stats: AudioPacerStats) => void;
|
||||
}
|
||||
|
||||
export interface AudioPacerStats {
|
||||
currentFrames: number;
|
||||
peakFrames: number;
|
||||
droppedFrames: number;
|
||||
lateTicks: number;
|
||||
sentFrames: number;
|
||||
}
|
||||
|
||||
export class AudioPacer {
|
||||
private readonly frameMs: number;
|
||||
private readonly maxFrames: number;
|
||||
private readonly maxLagMs: number;
|
||||
private readonly now: () => number;
|
||||
private readonly schedule: NonNullable<AudioPacerOptions["schedule"]>;
|
||||
private readonly cancel: NonNullable<AudioPacerOptions["cancel"]>;
|
||||
private readonly onStats: AudioPacerOptions["onStats"];
|
||||
private readonly queue: PacerFrame[] = [];
|
||||
private timer: ReturnType<typeof setTimeout> | null = null;
|
||||
private nextAt: number | null = null;
|
||||
private closed = false;
|
||||
private droppedFrames = 0;
|
||||
private lateTicks = 0;
|
||||
private sentFrames = 0;
|
||||
private peakFrames = 0;
|
||||
|
||||
constructor(
|
||||
private readonly send: (data: Buffer, codec: number) => void,
|
||||
options: AudioPacerOptions = {},
|
||||
) {
|
||||
this.frameMs = Math.max(1, options.frameMs ?? 20);
|
||||
this.maxFrames = Math.max(1, options.maxFrames ?? 6);
|
||||
this.maxLagMs = Math.max(0, options.maxLagMs ?? 40);
|
||||
this.now = options.now ?? (() => performance.now());
|
||||
this.schedule = options.schedule ?? ((callback, delayMs) => setTimeout(callback, delayMs));
|
||||
this.cancel = options.cancel ?? ((handle) => clearTimeout(handle));
|
||||
this.onStats = options.onStats;
|
||||
}
|
||||
|
||||
push(data: Buffer, codec: number): boolean {
|
||||
if (this.closed || !data.length) return false;
|
||||
while (this.queue.length >= this.maxFrames) {
|
||||
this.queue.shift();
|
||||
this.droppedFrames++;
|
||||
}
|
||||
this.queue.push({ data, codec, enqueuedAt: this.now() });
|
||||
this.peakFrames = Math.max(this.peakFrames, this.queue.length);
|
||||
if (!this.timer) {
|
||||
this.nextAt = this.now();
|
||||
this.arm(0);
|
||||
}
|
||||
this.emitStats();
|
||||
return true;
|
||||
}
|
||||
|
||||
private arm(delayMs: number): void {
|
||||
this.timer = this.schedule(() => this.tick(), Math.max(0, delayMs));
|
||||
// Do not keep the Node process alive solely for an idle voice pacer.
|
||||
(this.timer as unknown as { unref?: () => void }).unref?.();
|
||||
}
|
||||
|
||||
private tick(): void {
|
||||
this.timer = null;
|
||||
if (this.closed) return;
|
||||
if (!this.queue.length) {
|
||||
this.nextAt = null;
|
||||
return;
|
||||
}
|
||||
const now = this.now();
|
||||
if (this.nextAt !== null && now - this.nextAt > this.maxLagMs) {
|
||||
// A late event loop turn must not create a catch-up burst. Drop the
|
||||
// accumulated backlog of time and emit one frame from the current time.
|
||||
this.lateTicks++;
|
||||
this.nextAt = now;
|
||||
}
|
||||
const frame = this.queue.shift()!;
|
||||
try { this.send(frame.data, frame.codec); } catch { /* sendVoice reports its own failure */ }
|
||||
this.sentFrames++;
|
||||
if (this.queue.length) {
|
||||
this.nextAt = this.nextAt === null ? now + this.frameMs : this.nextAt + this.frameMs;
|
||||
if (this.nextAt < now + 1) this.nextAt = now + this.frameMs;
|
||||
this.arm(this.nextAt - now);
|
||||
} else {
|
||||
this.nextAt = null;
|
||||
}
|
||||
this.emitStats();
|
||||
}
|
||||
|
||||
private emitStats(): void {
|
||||
this.onStats?.(this.getStats());
|
||||
}
|
||||
|
||||
getStats(): AudioPacerStats {
|
||||
return {
|
||||
currentFrames: this.queue.length,
|
||||
peakFrames: this.peakFrames,
|
||||
droppedFrames: this.droppedFrames,
|
||||
lateTicks: this.lateTicks,
|
||||
sentFrames: this.sentFrames,
|
||||
};
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true;
|
||||
if (this.timer) {
|
||||
this.cancel(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
this.queue.length = 0;
|
||||
this.nextAt = null;
|
||||
this.emitStats();
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ import type { WebRtcAudioSession, WebRtcAudioStats } from "./webrtc-audio.js";
|
||||
|
||||
export interface AudioFlowStats extends WebRtcAudioStats {
|
||||
ingressFrames: number;
|
||||
ingressPcmFrames: number;
|
||||
ingressOpusFrames: number;
|
||||
ingressDroppedFrames: number;
|
||||
ingressFirstAt: number | null;
|
||||
ingressLastAt: number | null;
|
||||
@@ -13,6 +15,10 @@ export interface AudioFlowStats extends WebRtcAudioStats {
|
||||
tsSendLastAt: number | null;
|
||||
tsSendMaxGapMs: number;
|
||||
tsEncodeMaxMs: number;
|
||||
uplinkQueueCurrentFrames: number;
|
||||
uplinkQueuePeakFrames: number;
|
||||
uplinkQueueDroppedFrames: number;
|
||||
uplinkPacerLateTicks: number;
|
||||
tsReceiveFrames: number;
|
||||
tsReceiveFirstAt: number | null;
|
||||
tsReceiveLastAt: number | null;
|
||||
@@ -38,6 +44,8 @@ export interface AudioStatsSource {
|
||||
export function createAudioFlowStats(): AudioFlowStats {
|
||||
return {
|
||||
ingressFrames: 0,
|
||||
ingressPcmFrames: 0,
|
||||
ingressOpusFrames: 0,
|
||||
ingressDroppedFrames: 0,
|
||||
ingressFirstAt: null,
|
||||
ingressLastAt: null,
|
||||
@@ -48,6 +56,10 @@ export function createAudioFlowStats(): AudioFlowStats {
|
||||
tsSendLastAt: null,
|
||||
tsSendMaxGapMs: 0,
|
||||
tsEncodeMaxMs: 0,
|
||||
uplinkQueueCurrentFrames: 0,
|
||||
uplinkQueuePeakFrames: 0,
|
||||
uplinkQueueDroppedFrames: 0,
|
||||
uplinkPacerLateTicks: 0,
|
||||
tsReceiveFrames: 0,
|
||||
tsReceiveFirstAt: null,
|
||||
tsReceiveLastAt: null,
|
||||
@@ -95,11 +107,16 @@ export function snapshotAudioStatus(entry: AudioStatsSource): VoiceAudioBridgeSt
|
||||
return {
|
||||
transport: entry.webrtc ? "webrtc" : "websocket",
|
||||
ingressFrames: stats.ingressFrames,
|
||||
ingressPcmFrames: stats.ingressPcmFrames,
|
||||
ingressOpusFrames: stats.ingressOpusFrames,
|
||||
ingressDroppedFrames: stats.ingressDroppedFrames,
|
||||
ingressMaxGapMs: stats.ingressMaxGapMs,
|
||||
tsSendFrames: stats.tsSendFrames,
|
||||
tsSendErrors: stats.tsSendErrors,
|
||||
tsSendMaxGapMs: stats.tsSendMaxGapMs,
|
||||
uplinkQueuePeakFrames: stats.uplinkQueuePeakFrames,
|
||||
uplinkQueueDroppedFrames: stats.uplinkQueueDroppedFrames,
|
||||
uplinkPacerLateTicks: stats.uplinkPacerLateTicks,
|
||||
tsReceiveFrames: stats.tsReceiveFrames,
|
||||
tsReceiveMaxGapMs: stats.tsReceiveMaxGapMs,
|
||||
egressFrames: stats.egressFrames,
|
||||
|
||||
@@ -34,7 +34,7 @@ function fixture() {
|
||||
const transport = new SessionAudioTransport({
|
||||
audio, socket, client, logger, isCurrent: () => state.current, isReady: () => state.ready,
|
||||
selfId: () => 1, peer: () => state.peer, whisperTargets: () => state.targets,
|
||||
sendJson: message => { notices.push(message); },
|
||||
sendJson: message => { notices.push(message); }, pacing: false,
|
||||
}, encoder, () => state.now, () => 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, warnings, remote };
|
||||
@@ -117,8 +117,8 @@ test("repeated malformed frames are counted in full but reported once per window
|
||||
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 },
|
||||
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: "1920 or tagged", droppedFrames: 1 },
|
||||
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: "1920 or tagged", droppedFrames: 4 },
|
||||
], "operators get the same rate-limited view through the logger");
|
||||
});
|
||||
|
||||
@@ -131,6 +131,19 @@ test("an encoder failure and a malformed frame do not suppress each other", t =>
|
||||
t.mock.restoreAll();
|
||||
});
|
||||
|
||||
test("tagged PCM and pre-encoded Opus frames share the uplink without double encoding", () => {
|
||||
const f = fixture();
|
||||
f.transport.receivePcm(Buffer.concat([Buffer.from([1]), Buffer.alloc(1_920)]));
|
||||
f.transport.receivePcm(Buffer.concat([Buffer.from([2]), Buffer.from([1, 2, 3])]));
|
||||
assert.equal(f.encoded.length, 1);
|
||||
assert.equal(f.audio.ingressPcmFrames, 1);
|
||||
assert.equal(f.audio.ingressOpusFrames, 1);
|
||||
assert.deepEqual(f.forwarded.map(({ data, codec }) => ({ data: [...data], codec })), [
|
||||
{ data: [9, 8, 7], codec: 4 },
|
||||
{ data: [1, 2, 3], codec: 4 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("WebRTC ingress excludes queued PCM and fallback re-enables PCM", () => {
|
||||
const f = fixture();
|
||||
f.state.peer = { pushTeamSpeakVoice() {} };
|
||||
|
||||
@@ -5,8 +5,19 @@ 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";
|
||||
import { AudioPacer } from "./audio-pacer.js";
|
||||
import {
|
||||
VOICE_MAX_OPUS_FRAME_BYTES,
|
||||
VOICE_OPUS_TAG,
|
||||
VOICE_PCM_FRAME_BYTES,
|
||||
VOICE_PCM_TAG,
|
||||
} from "../shared/voice-audio.js";
|
||||
|
||||
const AUDIO_FRAME_BYTES = 1_920; // 20 ms of 48 kHz mono Int16 PCM.
|
||||
const AUDIO_FRAME_BYTES = VOICE_PCM_FRAME_BYTES;
|
||||
const TAGGED_PCM_FRAME_BYTES = AUDIO_FRAME_BYTES + 1;
|
||||
const PCM_FRAME_TAG = VOICE_PCM_TAG;
|
||||
const OPUS_FRAME_TAG = VOICE_OPUS_TAG;
|
||||
const MAX_OPUS_FRAME_BYTES = VOICE_MAX_OPUS_FRAME_BYTES;
|
||||
// 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
|
||||
@@ -33,6 +44,8 @@ export interface SessionAudioOptions {
|
||||
peer(): Pick<WebRtcAudioSession, "pushTeamSpeakVoice"> | null;
|
||||
whisperTargets(): readonly number[] | null;
|
||||
sendJson(message: ServerMessage): void;
|
||||
/** Tests that assert synchronous SDK calls can opt out; production keeps pacing. */
|
||||
pacing?: boolean;
|
||||
}
|
||||
|
||||
/** A session owns one encoder and one active audio route in each direction. */
|
||||
@@ -42,6 +55,7 @@ export class SessionAudioTransport {
|
||||
/** Last report time per audio fault code; see `shouldReportAudioIssue`. */
|
||||
private readonly reportedAt = new Map<string, number>();
|
||||
private readonly logger: LoggerType | null;
|
||||
private readonly pacer: AudioPacer | null;
|
||||
private pcmTokens = PCM_BURST_FRAMES;
|
||||
private pcmRefilledAt: number | null = null;
|
||||
|
||||
@@ -49,6 +63,18 @@ export class SessionAudioTransport {
|
||||
private readonly rateClock: () => number = performance.now.bind(performance)) {
|
||||
this.encoder = encoder;
|
||||
this.logger = options.logger ?? null;
|
||||
this.pacer = options.pacing === false ? null : new AudioPacer(
|
||||
(data, codec) => this.sendVoice(data, codec),
|
||||
{
|
||||
now: this.rateClock,
|
||||
onStats: stats => {
|
||||
options.audio.uplinkQueueCurrentFrames = stats.currentFrames;
|
||||
options.audio.uplinkQueuePeakFrames = Math.max(options.audio.uplinkQueuePeakFrames, stats.peakFrames);
|
||||
options.audio.uplinkQueueDroppedFrames = stats.droppedFrames;
|
||||
options.audio.uplinkPacerLateTicks = stats.lateTicks;
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private isCurrent(): boolean {
|
||||
@@ -112,7 +138,7 @@ export class SessionAudioTransport {
|
||||
// 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 },
|
||||
{ code: "INVALID_AUDIO_FRAME", frameBytes: length, expectedBytes: `${AUDIO_FRAME_BYTES} or tagged`, droppedFrames: this.options.audio.ingressDroppedFrames },
|
||||
"Discarded malformed browser audio frame",
|
||||
);
|
||||
try {
|
||||
@@ -128,7 +154,11 @@ export class SessionAudioTransport {
|
||||
// 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) {
|
||||
const legacyPcm = frame.length === AUDIO_FRAME_BYTES ? frame : null;
|
||||
const taggedPcm = frame.length === TAGGED_PCM_FRAME_BYTES && frame[0] === PCM_FRAME_TAG ? frame.subarray(1) : null;
|
||||
const opus = frame.length > 1 && frame.length <= MAX_OPUS_FRAME_BYTES + 1 && frame[0] === OPUS_FRAME_TAG
|
||||
? frame.subarray(1) : null;
|
||||
if (!legacyPcm && !taggedPcm && !opus) {
|
||||
stats.ingressDroppedFrames++;
|
||||
this.reportInvalidFrame(frame.length);
|
||||
return;
|
||||
@@ -141,17 +171,26 @@ export class SessionAudioTransport {
|
||||
if (this.pcmTokens < 1) {
|
||||
stats.ingressDroppedFrames++;
|
||||
if (this.shouldReportAudioIssue("AUDIO_RATE_EXCEEDED")) {
|
||||
this.logger?.warn({ code: "AUDIO_RATE_EXCEEDED", droppedFrames: stats.ingressDroppedFrames }, "Discarded browser PCM above the real-time budget");
|
||||
this.logger?.warn({ code: "AUDIO_RATE_EXCEEDED", droppedFrames: stats.ingressDroppedFrames }, "Discarded browser audio above the real-time budget");
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.pcmTokens--;
|
||||
this.recordIngress();
|
||||
if (opus) {
|
||||
stats.ingressOpusFrames++;
|
||||
// The pacer absorbs Cloudflare's bursty WebSocket delivery. Opus is
|
||||
// already encoded, so this costs one buffer copy and no CPU-heavy encode.
|
||||
if (this.pacer) this.pacer.push(opus, 4);
|
||||
else this.sendVoice(opus, 4);
|
||||
return;
|
||||
}
|
||||
stats.ingressPcmFrames++;
|
||||
const startedAt = this.clock();
|
||||
let encoded: Buffer;
|
||||
try {
|
||||
if (!this.encoder) throw new Error("Encoder unavailable");
|
||||
encoded = this.encoder.encode(frame);
|
||||
encoded = this.encoder.encode(taggedPcm ?? legacyPcm!);
|
||||
stats.tsEncodeMaxMs = Math.max(stats.tsEncodeMaxMs, this.clock() - startedAt);
|
||||
} catch {
|
||||
stats.tsSendErrors++;
|
||||
@@ -159,7 +198,8 @@ export class SessionAudioTransport {
|
||||
this.reportEncoderFailure();
|
||||
return;
|
||||
}
|
||||
this.sendVoice(encoded, 4);
|
||||
this.pacer?.push(encoded, 4);
|
||||
if (!this.pacer) this.sendVoice(encoded, 4);
|
||||
}
|
||||
|
||||
receiveWebRtc(data: Buffer, codec: number): void {
|
||||
@@ -214,6 +254,7 @@ export class SessionAudioTransport {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
this.reportedAt.clear();
|
||||
this.pacer?.close();
|
||||
const encoder = this.encoder;
|
||||
this.encoder = null;
|
||||
try { encoder?.dispose(); } catch { /* other session resources must still be released */ }
|
||||
|
||||
@@ -131,11 +131,11 @@ test("schema 8 settings and invites survive the nickname migration", async (cont
|
||||
});
|
||||
database.close();
|
||||
const legacy = new DatabaseSync(file);
|
||||
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; DROP TABLE workspace_invites; PRAGMA user_version = 8;");
|
||||
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; DROP TABLE workspace_invites; ALTER TABLE settings DROP COLUMN voice_profile; ALTER TABLE settings DROP COLUMN voice_turn_urls; ALTER TABLE settings DROP COLUMN voice_turn_secret_encrypted; ALTER TABLE settings DROP COLUMN voice_turn_ttl_seconds; ALTER TABLE settings DROP COLUMN voice_opus_ws; ALTER TABLE settings DROP COLUMN voice_jitter_max_ms; PRAGMA user_version = 8;");
|
||||
legacy.close();
|
||||
const migrated = new WebSpeakDatabase(file);
|
||||
try {
|
||||
assert.equal(migrated.schemaVersion, 13);
|
||||
assert.equal(migrated.schemaVersion, 14);
|
||||
assert.equal(migrated.getSettings().tsHost, "127.0.0.1");
|
||||
assert.equal(migrated.getSettings().tsTarget, null);
|
||||
const invite = migrated.consumeManagedInvite("legacy-token");
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { createHmac } from "node:crypto";
|
||||
import { createTurnRestCredential, createTurnRestUsername } from "./turn-credentials.js";
|
||||
|
||||
test("TURN REST username and credential match coturn's HMAC contract", () => {
|
||||
const secret = "a-test-secret-with-enough-length";
|
||||
const config = { urls: ["turns:turn.example.com:443?transport=tcp"], secret, ttlSeconds: 3_600 };
|
||||
const now = 1_700_000_000_000;
|
||||
const credential = createTurnRestCredential(config, "session-1", now);
|
||||
const expiry = Math.floor(now / 1_000) + 3_600;
|
||||
const username = createTurnRestUsername(expiry, "session-1");
|
||||
assert.equal(credential.username, username);
|
||||
assert.equal(credential.credential, createHmac("sha1", secret).update(username).digest("base64"));
|
||||
});
|
||||
|
||||
test("TURN REST session ids are sanitized and expiry stays in the future", () => {
|
||||
const credential = createTurnRestCredential(
|
||||
{ urls: ["turn:turn.example.com:3478?transport=udp"], secret: "another-long-test-secret", ttlSeconds: 300 },
|
||||
"bad session:id!",
|
||||
1_000,
|
||||
);
|
||||
assert.match(credential.username!, /^[0-9]+:badsessionid/);
|
||||
assert.equal(credential.credential?.length, 28);
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { createHmac, randomBytes } from "node:crypto";
|
||||
import type { VoiceIceServer } from "../shared/voice-ice.js";
|
||||
|
||||
export interface TurnRestConfig {
|
||||
urls: string[];
|
||||
secret: string;
|
||||
ttlSeconds: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* coturn's `use-auth-secret` REST API:
|
||||
* username = "<expiry unix seconds>:<session id>"
|
||||
* credential = base64(HMAC-SHA1(secret, username))
|
||||
*
|
||||
* Credentials are minted per browser connection; they are not shared between
|
||||
* sessions and never need to be persisted.
|
||||
*/
|
||||
export function createTurnRestCredential(
|
||||
config: TurnRestConfig,
|
||||
sessionId: string,
|
||||
nowMs = Date.now(),
|
||||
): VoiceIceServer {
|
||||
const suffix = sessionId.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 64) || randomBytes(8).toString("hex");
|
||||
const expiry = Math.floor(nowMs / 1_000) + Math.max(1, Math.trunc(config.ttlSeconds));
|
||||
const username = `${expiry}:${suffix}`;
|
||||
const credential = createHmac("sha1", config.secret).update(username).digest("base64");
|
||||
return {
|
||||
urls: config.urls.length === 1 ? config.urls[0]! : [...config.urls],
|
||||
username,
|
||||
credential,
|
||||
};
|
||||
}
|
||||
|
||||
export function createTurnRestUsername(expirySeconds: number, sessionId: string): string {
|
||||
return `${Math.trunc(expirySeconds)}:${sessionId}`;
|
||||
}
|
||||
@@ -11,7 +11,8 @@ import { OpusEncoder } from "./opus-codec.js";
|
||||
import { normalizeTeamSpeakKickedReason } from "../errors.js";
|
||||
import type { TSClient, TSClientAvatar, TSDirectorySnapshot } from "./ts-client.js";
|
||||
import type { AudioFlowStats } from "./audio-stats.js";
|
||||
import type { WebRtcAudioSession } from "./webrtc-audio.js";
|
||||
import type { WebRtcAudioSession, WebRtcAudioOptions } from "./webrtc-audio.js";
|
||||
import type { VoiceBridgeOptions } from "./voice-bridge.js";
|
||||
|
||||
// Real loopback HTTP/WebSocket and native codec, with only the external SDK
|
||||
// replaced. This validates gateway wiring, not a connection to TeamSpeak.
|
||||
@@ -52,11 +53,19 @@ async function fixture(t: TestContext, overrides: {
|
||||
waitForFirstMessage?: boolean;
|
||||
createWorkspaceInvite?: import("./voice-bridge.js").VoiceBridgeOptions["createWorkspaceInvite"];
|
||||
connection?: Partial<import("./join-ticket.js").JoinTicketPayload>;
|
||||
webRtc?: WebRtcAudioOptions;
|
||||
voiceIce?: VoiceBridgeOptions["voiceIce"];
|
||||
headers?: Record<string, string>;
|
||||
} = {}) {
|
||||
const sdk = new TeamSpeakStub();
|
||||
overrides.configureSdk?.(sdk);
|
||||
const tickets = new JoinTicketStore();
|
||||
const bridge = new VoiceBridge({ joinTickets: tickets, createWorkspaceInvite: overrides.createWorkspaceInvite }, pino({ enabled: false }), undefined, {
|
||||
const bridge = new VoiceBridge({
|
||||
joinTickets: tickets,
|
||||
createWorkspaceInvite: overrides.createWorkspaceInvite,
|
||||
...(overrides.webRtc ? { webRtc: overrides.webRtc } : {}),
|
||||
...(overrides.voiceIce ? { voiceIce: overrides.voiceIce } : {}),
|
||||
}, pino({ enabled: false }), undefined, {
|
||||
createTeamSpeakClient: overrides.createTeamSpeakClient ?? (() => sdk as unknown as TSClient),
|
||||
...(overrides.createEncoder ? { createEncoder: overrides.createEncoder } : {}),
|
||||
});
|
||||
@@ -68,7 +77,7 @@ async function fixture(t: TestContext, overrides: {
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address !== "string");
|
||||
const ticket = tickets.create({ target: { host: "voice.example.invalid", port: 9987 }, nickname: "Test", serverPassword: "", ...overrides.connection });
|
||||
const socket = new WebSocket(`ws://127.0.0.1:${address.port}/ws/voice?ticket=${ticket}`);
|
||||
const socket = new WebSocket(`ws://127.0.0.1:${address.port}/ws/voice?ticket=${ticket}`, overrides.headers ? { headers: overrides.headers } : undefined);
|
||||
const messages: Array<{ data: Buffer; binary: boolean }> = [];
|
||||
socket.on("message", (data, binary) => messages.push({ data: data as Buffer, binary }));
|
||||
const first = once(socket, "message");
|
||||
@@ -107,6 +116,18 @@ function waitForMessage<T extends Record<string, unknown>>(socket: WebSocket, ty
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForBufferedMessage<T extends Record<string, unknown>>(
|
||||
messages: Array<{ data: Buffer; binary: boolean }>,
|
||||
type: string,
|
||||
): Promise<T> {
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
const found = messages.find(message => !message.binary && (JSON.parse(message.data.toString()) as { type?: string }).type === type);
|
||||
if (found) return JSON.parse(found.data.toString()) as T;
|
||||
await nextTurn();
|
||||
}
|
||||
throw new Error(`message ${type} was not published`);
|
||||
}
|
||||
|
||||
// The native Opus codec is unavailable in some environments. These tests only
|
||||
// exercise gateway wiring, so the encoder is stubbed out.
|
||||
const stubEncoder = () => ({ encode: () => Buffer.alloc(0), dispose: () => {} });
|
||||
@@ -153,6 +174,96 @@ test("server identity lookup waits until the directory sync publishes the connec
|
||||
assert.ok(f.bridge.getActiveCount() > 0);
|
||||
});
|
||||
|
||||
test("a direct connection keeps the legacy audio profile and the original media path", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t, {
|
||||
webRtc: { enabled: true, stunServer: "stun:stun.example.invalid:3478" },
|
||||
voiceIce: {
|
||||
servers: [],
|
||||
transportPolicy: "all",
|
||||
gatewayTransportPolicy: "all",
|
||||
profile: "auto",
|
||||
opusWebSocket: false,
|
||||
jitterMaxMs: 300,
|
||||
},
|
||||
});
|
||||
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
|
||||
assert.equal(connected.voiceProfile, "legacy");
|
||||
assert.equal(connected.webrtcAvailable, true);
|
||||
assert.equal(connected.webrtcUnavailableReason, undefined);
|
||||
assert.equal(connected.audioFrameVersion, undefined);
|
||||
assert.equal(connected.audioUplinkCodecs, undefined);
|
||||
assert.equal(connected.audioJitterMaxMs, undefined);
|
||||
assert.equal(connected.voiceIceTransportPolicy, "all");
|
||||
assert.deepEqual(connected.voiceIceServers, [{ urls: "stun:stun.example.invalid:3478" }]);
|
||||
});
|
||||
|
||||
test("an explicit adaptive profile enables the new audio path on a direct connection", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t, {
|
||||
webRtc: { enabled: true },
|
||||
voiceIce: {
|
||||
servers: [],
|
||||
transportPolicy: "all",
|
||||
gatewayTransportPolicy: "all",
|
||||
profile: "adaptive",
|
||||
opusWebSocket: true,
|
||||
jitterMaxMs: 300,
|
||||
},
|
||||
});
|
||||
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
|
||||
assert.equal(connected.voiceProfile, "adaptive");
|
||||
assert.equal(connected.webrtcAvailable, true);
|
||||
assert.equal(connected.audioFrameVersion, 2);
|
||||
assert.deepEqual(connected.audioUplinkCodecs, ["pcm", "opus"]);
|
||||
assert.equal(connected.audioJitterMaxMs, 300);
|
||||
});
|
||||
|
||||
test("a Cloudflare request opts into adaptive audio without inventing an ICE host", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t, {
|
||||
webRtc: { enabled: true },
|
||||
voiceIce: {
|
||||
servers: [],
|
||||
transportPolicy: "all",
|
||||
gatewayTransportPolicy: "all",
|
||||
profile: "auto",
|
||||
opusWebSocket: false,
|
||||
jitterMaxMs: 300,
|
||||
},
|
||||
headers: { "cf-ray": "test-ray" },
|
||||
});
|
||||
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
|
||||
assert.equal(connected.voiceProfile, "adaptive");
|
||||
assert.equal(connected.webrtcAvailable, false);
|
||||
assert.equal(connected.webrtcUnavailableReason, "NO_MEDIA_PATH");
|
||||
assert.equal(connected.audioFrameVersion, 2);
|
||||
assert.deepEqual(connected.audioUplinkCodecs, ["pcm"]);
|
||||
assert.equal(connected.audioJitterMaxMs, 300);
|
||||
assert.deepEqual(connected.voiceIceServers, []);
|
||||
});
|
||||
|
||||
|
||||
test("a voice ICE getter is resolved when a new connection is accepted", { timeout: 5_000 }, async t => {
|
||||
let calls = 0;
|
||||
const f = await fixture(t, {
|
||||
webRtc: { enabled: true },
|
||||
voiceIce: () => {
|
||||
calls++;
|
||||
return {
|
||||
servers: [],
|
||||
transportPolicy: "all",
|
||||
gatewayTransportPolicy: "all",
|
||||
profile: "auto",
|
||||
opusWebSocket: false,
|
||||
jitterMaxMs: 300,
|
||||
};
|
||||
},
|
||||
headers: { "cf-ray": "console-refresh-ray" },
|
||||
});
|
||||
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
|
||||
assert.equal(calls, 1);
|
||||
assert.equal(connected.voiceProfile, "adaptive");
|
||||
});
|
||||
|
||||
|
||||
test("a TeamSpeak drop before the directory sync fails the connection instead of stalling", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t, {
|
||||
waitForFirstMessage: false,
|
||||
|
||||
@@ -3,7 +3,7 @@ import test from "node:test";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import type { IncomingMessage } from "node:http";
|
||||
import pino from "pino";
|
||||
import { VoiceBridge, createTrustedProxies, resolveClientIp, resolveWebRtcPublicHost } from "./voice-bridge.js";
|
||||
import { VoiceBridge, createTrustedProxies, isCloudflareRequest, resolveClientIp, resolveWebRtcPublicHost } from "./voice-bridge.js";
|
||||
import { JoinTicketStore } from "./join-ticket.js";
|
||||
import { createAudioFlowStats } from "./audio-stats.js";
|
||||
import { SessionAudioTransport } from "./session-audio.js";
|
||||
@@ -40,6 +40,8 @@ function fixture(webRtc = { enabled: true } as import("./webrtc-audio.js").WebRt
|
||||
tsClient: { isConnected: () => true, setInputMuted: async (_muted: boolean) => {}, setAccompanimentActive: async (_active: boolean) => {}, sendVoice: () => { forwarded++; }, sendWhisper: () => { forwarded++; } },
|
||||
whisperActive: false, whisperTargetIds: new Set<number>(), audio: createAudioFlowStats(),
|
||||
audioTransport: null as SessionAudioTransport | null,
|
||||
voiceIceServers: [], voiceIceTransportPolicy: "all" as const, voiceIceGatewayTransportPolicy: "all" as const,
|
||||
voiceProfile: "legacy" as const,
|
||||
};
|
||||
let forwarded = 0;
|
||||
let configurePeer = (_peer: PeerStub): void => {};
|
||||
@@ -62,6 +64,7 @@ function fixture(webRtc = { enabled: true } as import("./webrtc-audio.js").WebRt
|
||||
isCurrent: () => bridge.entries.get(entry.id) === entry,
|
||||
isReady: () => entry.session.state === "connected", selfId: () => 1,
|
||||
peer: () => entry.webrtc, whisperTargets: () => null, sendJson: message => messages.push(message),
|
||||
pacing: false,
|
||||
}, { 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; } };
|
||||
@@ -174,6 +177,27 @@ test("WebRTC candidates use the voice gateway host when the page Origin belongs
|
||||
assert.equal(resolveWebRtcPublicHost(request), "voice-relay.example.com");
|
||||
});
|
||||
|
||||
test("Cloudflare headers only classify a request from a trusted proxy", () => {
|
||||
const trusted = createTrustedProxies(["127.0.0.1", "198.51.100.0/24"]);
|
||||
const headers = { "cf-ray": "abc123-SJC", "cf-connecting-ip": "203.0.113.10" };
|
||||
assert.equal(isCloudflareRequest(ipRequest("192.0.2.7", headers), trusted), false);
|
||||
assert.equal(isCloudflareRequest(ipRequest("127.0.0.1", headers), trusted), true);
|
||||
assert.equal(isCloudflareRequest(ipRequest("198.51.100.8", { "cdn-loop": "one, cloudflare two" }), trusted), true);
|
||||
assert.equal(isCloudflareRequest(ipRequest("198.51.100.8", { "cdn-loop": "one, other two" }), trusted), false);
|
||||
});
|
||||
|
||||
test("a Cloudflare-proxied request never falls back to the edge hostname for ICE", () => {
|
||||
const request = {
|
||||
headers: {
|
||||
host: "voice.example.com",
|
||||
"cf-ray": "abc123-SJC",
|
||||
"cf-connecting-ip": "203.0.113.10",
|
||||
},
|
||||
} as unknown as IncomingMessage;
|
||||
assert.equal(resolveWebRtcPublicHost(request, { allowHostFallback: false }), undefined);
|
||||
assert.equal(resolveWebRtcPublicHost(request), "voice.example.com");
|
||||
});
|
||||
|
||||
test("initial accompaniment updates TeamSpeak before creating a muted mixer and resets on stop", async () => {
|
||||
const f = fixture();
|
||||
const inputs: Array<[string, boolean]> = [];
|
||||
@@ -234,6 +258,18 @@ test("an unset media override still uses a literal request host", async () => {
|
||||
assert.deepEqual(f.peers[0].options.publicAddresses, ["192.0.2.10"]);
|
||||
});
|
||||
|
||||
test("TURN servers are passed to werift while direct-first remains the default policy", async () => {
|
||||
const f = fixture({ enabled: true, publicHost: "192.0.2.20" });
|
||||
Object.assign(f.entry, {
|
||||
webrtcPublicHost: "192.0.2.20",
|
||||
voiceIceServers: [{ urls: "turns:turn.example.com:443?transport=tcp", username: "u", credential: "c" }],
|
||||
voiceIceGatewayTransportPolicy: "all" as const,
|
||||
});
|
||||
await f.offer("turn");
|
||||
assert.deepEqual(f.peers[0].options.iceServers, f.entry.voiceIceServers);
|
||||
assert.equal(f.peers[0].options.iceTransportPolicy, "all");
|
||||
});
|
||||
|
||||
function ipRequest(remoteAddress: string | undefined, headers: Record<string, string> = {}): IncomingMessage {
|
||||
return { headers, socket: { remoteAddress } } as unknown as IncomingMessage;
|
||||
}
|
||||
|
||||
@@ -28,6 +28,15 @@ import { normalizeScreenShareIceServers, parseScreenShareMessage, type ScreenSha
|
||||
import { OpusEncoder } from "./opus-codec.js";
|
||||
import { avatarDataUrl } from "./directory-view.js";
|
||||
import type { PluginParticipant } from "../shared/plugins.js";
|
||||
import {
|
||||
hasVoiceTurnServer,
|
||||
normalizeVoiceIceServers,
|
||||
normalizeVoiceIceTransportPolicy,
|
||||
type VoiceIceServer,
|
||||
type VoiceIceTransportPolicy,
|
||||
} from "../shared/voice-ice.js";
|
||||
import { resolveVoiceIceServers, type VoiceIceConfig } from "./voice-ice-config.js";
|
||||
import { resolveVoiceProfile, type VoiceProfile } from "../shared/voice-profile.js";
|
||||
|
||||
const HEARTBEAT_INTERVAL_MS = 30_000;
|
||||
const MAX_MISSED_HEARTBEATS = 2;
|
||||
@@ -54,6 +63,8 @@ export interface VoiceBridgeOptions {
|
||||
pluginRuntimeEnabled?: boolean;
|
||||
joinTickets: JoinTicketStore;
|
||||
webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions);
|
||||
/** TURN / ICE deployment configuration; resolved for each new connection. */
|
||||
voiceIce?: VoiceIceConfig | (() => VoiceIceConfig);
|
||||
screenShareIceServers?: ScreenShareIceServer[] | (() => ScreenShareIceServer[]);
|
||||
acceleration?: ConfiguredAccelerationRelay[] | (() => ConfiguredAccelerationRelay[]);
|
||||
accelerationName?: string | (() => string | undefined);
|
||||
@@ -97,6 +108,10 @@ interface WebClientEntry extends SessionDirectoryState {
|
||||
acceleration?: AccelerationRelayOptions;
|
||||
identityLeaseKey?: string;
|
||||
webrtcPublicHost?: string;
|
||||
voiceProfile: VoiceProfile;
|
||||
voiceIceServers: VoiceIceServer[];
|
||||
voiceIceTransportPolicy: VoiceIceTransportPolicy;
|
||||
voiceIceGatewayTransportPolicy: VoiceIceTransportPolicy;
|
||||
events: SessionEventCoordinator | null;
|
||||
eventLog: ServerEvent[];
|
||||
audioTransport: SessionAudioTransport | null;
|
||||
@@ -178,7 +193,13 @@ export class VoiceBridge {
|
||||
return;
|
||||
}
|
||||
const clientIp = resolveClientIp(req, this.trustedProxies);
|
||||
const webrtcPublicHost = resolveWebRtcPublicHost(req);
|
||||
// Cloudflare Tunnel forwards the public hostname in `Host`, but that
|
||||
// hostname points at Cloudflare's edge, not at this origin's UDP ports.
|
||||
// Never advertise it as an ICE media address.
|
||||
const cloudflareRequest = isCloudflareRequest(req, this.trustedProxies);
|
||||
const webrtcPublicHost = resolveWebRtcPublicHost(req, { allowHostFallback: !cloudflareRequest });
|
||||
const voiceIce = this.getVoiceIceConfig();
|
||||
const voiceProfile = resolveVoiceProfile(voiceIce?.profile ?? "auto", cloudflareRequest);
|
||||
let identity;
|
||||
try {
|
||||
identity = connection.identity ? parseIdentity(connection.identity) : undefined;
|
||||
@@ -190,6 +211,9 @@ export class VoiceBridge {
|
||||
return;
|
||||
}
|
||||
const entryId = `w-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
|
||||
const voiceIceServers = this.buildVoiceIceServers(entryId, voiceIce);
|
||||
const voiceIceTransportPolicy = normalizeVoiceIceTransportPolicy(voiceIce?.transportPolicy);
|
||||
const voiceIceGatewayTransportPolicy = normalizeVoiceIceTransportPolicy(voiceIce?.gatewayTransportPolicy);
|
||||
let entry: WebClientEntry | null = null;
|
||||
const session = this.sessionManager.admit(entryId, async (reason) => {
|
||||
if (entry) await this.cleanupEntry(entry, reason);
|
||||
@@ -247,6 +271,10 @@ export class VoiceBridge {
|
||||
...(acceleration ? { acceleration } : {}),
|
||||
...(identityLeaseKey ? { identityLeaseKey } : {}),
|
||||
...(webrtcPublicHost ? { webrtcPublicHost } : {}),
|
||||
voiceProfile,
|
||||
voiceIceServers,
|
||||
voiceIceTransportPolicy,
|
||||
voiceIceGatewayTransportPolicy,
|
||||
channelTree: [],
|
||||
members: new Map(),
|
||||
avatarCache: new Map(),
|
||||
@@ -281,6 +309,7 @@ export class VoiceBridge {
|
||||
peer: () => entry!.webrtc,
|
||||
whisperTargets: () => entry!.whisperActive ? [...entry!.whisperTargetIds] : null,
|
||||
sendJson: message => sendJson(message),
|
||||
pacing: entry!.voiceProfile === "adaptive",
|
||||
}, this.dependencies.createEncoder?.() ?? new OpusEncoder(48000, 1));
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({ err: error, entryId }, "Could not create Opus encoder");
|
||||
@@ -328,6 +357,13 @@ export class VoiceBridge {
|
||||
}
|
||||
session.transition("connected");
|
||||
if (this.options.pluginRuntimeEnabled) entry!.pluginSession = randomBytes(32).toString("base64url");
|
||||
const webRtc = this.getWebRtcOptions();
|
||||
const hasDirectMediaPath = Boolean(webRtc?.publicHost || entry!.webrtcPublicHost);
|
||||
const hasRelayMediaPath = hasVoiceTurnServer(entry!.voiceIceServers);
|
||||
const webRtcAvailable = webRtc?.enabled === true && (hasDirectMediaPath || hasRelayMediaPath);
|
||||
const webRtcUnavailableReason = webRtc?.enabled !== true
|
||||
? "DISABLED" as const
|
||||
: webRtcAvailable ? undefined : "NO_MEDIA_PATH" as const;
|
||||
sendJson({
|
||||
type: "connected",
|
||||
tsClientId: events.selfId,
|
||||
@@ -335,8 +371,19 @@ export class VoiceBridge {
|
||||
serverEventLog: entry!.eventLog,
|
||||
whisperTargetIds: [...entry!.whisperTargetIds],
|
||||
whisperActive: entry!.whisperActive,
|
||||
webrtcAvailable: this.getWebRtcOptions()?.enabled === true,
|
||||
webRtcStunServer: this.getWebRtcOptions()?.stunServer ?? "",
|
||||
webrtcAvailable: webRtcAvailable,
|
||||
...(webRtcUnavailableReason ? { webrtcUnavailableReason: webRtcUnavailableReason } : {}),
|
||||
webRtcStunServer: webRtc?.stunServer ?? "",
|
||||
voiceProfile: entry!.voiceProfile,
|
||||
voiceIceServers: entry!.voiceIceServers,
|
||||
voiceIceTransportPolicy: entry!.voiceIceTransportPolicy,
|
||||
...(entry!.voiceProfile === "adaptive" ? {
|
||||
audioFrameVersion: 2 as const,
|
||||
audioUplinkCodecs: voiceIce?.opusWebSocket === true
|
||||
? ["pcm", "opus"] as ("pcm" | "opus")[]
|
||||
: ["pcm"] as ("pcm" | "opus")[],
|
||||
audioJitterMaxMs: voiceIce?.jitterMaxMs ?? 300,
|
||||
} : {}),
|
||||
screenShareIceServers: this.getScreenShareIceServers(),
|
||||
accelerated: Boolean(entry!.acceleration),
|
||||
...(entry!.pluginSession ? { pluginSession: entry!.pluginSession } : {}),
|
||||
@@ -838,6 +885,18 @@ export class VoiceBridge {
|
||||
return typeof configured === "function" ? configured() : configured;
|
||||
}
|
||||
|
||||
private getVoiceIceConfig(): VoiceIceConfig | undefined {
|
||||
const configured = this.options.voiceIce;
|
||||
return typeof configured === "function" ? configured() : configured;
|
||||
}
|
||||
|
||||
private buildVoiceIceServers(entryId: string, config = this.getVoiceIceConfig()): VoiceIceServer[] {
|
||||
const servers = resolveVoiceIceServers(config, entryId);
|
||||
const stunServer = this.getWebRtcOptions()?.stunServer;
|
||||
if (stunServer) servers.push({ urls: stunServer });
|
||||
return normalizeVoiceIceServers(servers);
|
||||
}
|
||||
|
||||
private getScreenShareIceServers(): ScreenShareIceServer[] {
|
||||
const configured = this.options.screenShareIceServers;
|
||||
const servers = typeof configured === "function" ? configured() : configured;
|
||||
@@ -900,12 +959,25 @@ export class VoiceBridge {
|
||||
try {
|
||||
const publicAddresses = await resolveVoiceMediaAddresses(config.publicHost || entry.webrtcPublicHost, config.ipv6Enabled === true);
|
||||
if (!isCurrent()) return;
|
||||
const iceServers = config.iceServers?.length ? config.iceServers : entry.voiceIceServers;
|
||||
const configuredGatewayPolicy = config.iceTransportPolicy ?? entry.voiceIceGatewayTransportPolicy;
|
||||
// Relay-only gathering without a TURN server would leave the gateway
|
||||
// with no candidates at all. Fall back to direct gathering instead.
|
||||
const gatewayPolicy = configuredGatewayPolicy === "relay" && !hasVoiceTurnServer(iceServers)
|
||||
? "all"
|
||||
: configuredGatewayPolicy;
|
||||
if (configuredGatewayPolicy === "relay" && gatewayPolicy === "all") {
|
||||
this.logger.warn({ entryId: entry.id }, "Relay-only WebRTC gateway policy has no TURN server; using direct candidates");
|
||||
}
|
||||
peer = this.createWebRtcSession({
|
||||
connectionId: entry.id,
|
||||
publicAddresses,
|
||||
...(config.publicHost || entry.webrtcPublicHost ? { publicHost: config.publicHost || entry.webrtcPublicHost } : {}),
|
||||
ipv6Enabled: config.ipv6Enabled,
|
||||
stunServer: config.stunServer,
|
||||
iceServers,
|
||||
iceTransportPolicy: gatewayPolicy,
|
||||
profile: entry.voiceProfile,
|
||||
udpPortRange: config.udpPortRange,
|
||||
logger: this.logger,
|
||||
microphoneMuted: muted,
|
||||
@@ -938,7 +1010,28 @@ export class VoiceBridge {
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveWebRtcPublicHost(request: IncomingMessage): string | undefined {
|
||||
/**
|
||||
* Headers Cloudflare adds to proxied requests (including Tunnel origins).
|
||||
* Only a configured trusted proxy may assert that a request came through
|
||||
* Cloudflare; otherwise a direct client could spoof the adaptive audio path
|
||||
* and suppress the legacy Host-based ICE fallback.
|
||||
*/
|
||||
export function isCloudflareRequest(request: IncomingMessage, trustedProxies: BlockList): boolean {
|
||||
const direct = normalizeClientIp(request.socket.remoteAddress);
|
||||
if (!direct || !isTrustedProxy(direct, trustedProxies)) return false;
|
||||
const cdnLoop = firstHeader(request.headers["cdn-loop"]);
|
||||
return Boolean(
|
||||
firstHeader(request.headers["cf-ray"])
|
||||
|| firstHeader(request.headers["cf-connecting-ip"])
|
||||
|| (cdnLoop && /\bcloudflare\b/i.test(cdnLoop))
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveWebRtcPublicHost(
|
||||
request: IncomingMessage,
|
||||
options: { allowHostFallback?: boolean } = {},
|
||||
): string | undefined {
|
||||
if (options.allowHostFallback === false) return undefined;
|
||||
const origin = firstHeader(request.headers.origin);
|
||||
const forwardedHost = firstHeader(request.headers["x-forwarded-host"]);
|
||||
const directHost = firstHeader(request.headers.host);
|
||||
|
||||
@@ -6,6 +6,7 @@ import { parseDelegatedVoiceSession, VoiceGatewayRequestVerifier } from "./voice
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { WebRtcAudioOptions } from "./webrtc-audio.js";
|
||||
import type { ScreenShareIceServer } from "./screen-share.js";
|
||||
import type { VoiceIceConfig } from "./voice-ice-config.js";
|
||||
|
||||
export interface VoiceGatewayServerOptions {
|
||||
workspaceInvites?: import("./workspace-invites.js").WorkspaceInvites;
|
||||
@@ -14,6 +15,7 @@ export interface VoiceGatewayServerOptions {
|
||||
sharedToken: string;
|
||||
logger: Logger;
|
||||
webRtc: WebRtcAudioOptions;
|
||||
voiceIce?: VoiceIceConfig;
|
||||
screenShareIceServers?: ScreenShareIceServer[];
|
||||
trustedProxies?: readonly string[];
|
||||
}
|
||||
@@ -33,6 +35,7 @@ export function createVoiceGatewayServer(options: VoiceGatewayServerOptions): Vo
|
||||
joinTickets: tickets,
|
||||
...(options.workspaceInvites ? { createWorkspaceInvite: (credentials, minutes) => options.workspaceInvites!.create(credentials, minutes) } : {}),
|
||||
webRtc: options.webRtc,
|
||||
voiceIce: options.voiceIce,
|
||||
screenShareIceServers: options.screenShareIceServers,
|
||||
trustedProxies: options.trustedProxies,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { readVoiceIceConfig, resolveVoiceIceServers } from "./voice-ice-config.js";
|
||||
|
||||
test("voice ICE env parses static servers and direct-first defaults", () => {
|
||||
const config = readVoiceIceConfig({
|
||||
WEBSPEAK_VOICE_ICE_SERVERS: '[{"urls":"stun:stun.example.com:3478"}]',
|
||||
});
|
||||
assert.deepEqual(config.servers, [{ urls: "stun:stun.example.com:3478" }]);
|
||||
assert.equal(config.transportPolicy, "all");
|
||||
assert.equal(config.gatewayTransportPolicy, "all");
|
||||
assert.equal(config.profile, "auto");
|
||||
assert.equal(config.opusWebSocket, false);
|
||||
assert.equal(config.jitterMaxMs, 300);
|
||||
assert.equal(config.turnRest, undefined);
|
||||
});
|
||||
|
||||
test("voice profile is explicit-only for Opus and can force legacy or adaptive", () => {
|
||||
assert.equal(readVoiceIceConfig({}).profile, "auto");
|
||||
assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_PROFILE: "legacy" }).profile, "legacy");
|
||||
assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_PROFILE: "adaptive" }).profile, "adaptive");
|
||||
assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_PROFILE: "invalid" }).profile, "auto");
|
||||
assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_PROFILE: "adaptive", WEBSPEAK_VOICE_OPUS_WS: "1" }).opusWebSocket, true);
|
||||
});
|
||||
|
||||
test("TURN REST env mints a per-session credential and keeps direct-first policy", () => {
|
||||
const config = readVoiceIceConfig({
|
||||
WEBSPEAK_TURN_REST_URLS: "turns:turn.example.com:443?transport=tcp,turn:turn.example.com:3478?transport=udp",
|
||||
WEBSPEAK_TURN_REST_SECRET: "a-test-secret-with-enough-length",
|
||||
WEBSPEAK_TURN_REST_TTL_SECONDS: "3600",
|
||||
WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY: "relay",
|
||||
});
|
||||
assert.equal(config.transportPolicy, "relay");
|
||||
assert.ok(config.turnRest);
|
||||
const servers = resolveVoiceIceServers(config, "session-a", 1_000_000);
|
||||
assert.equal(servers.length, 1);
|
||||
assert.match(servers[0]!.username!, /^[0-9]+:session-a$/);
|
||||
assert.ok(servers[0]!.credential);
|
||||
});
|
||||
|
||||
test("short TURN secret is ignored instead of starting a broken relay", () => {
|
||||
const config = readVoiceIceConfig({
|
||||
WEBSPEAK_TURN_REST_URLS: "turns:turn.example.com:443",
|
||||
WEBSPEAK_TURN_REST_SECRET: "short",
|
||||
});
|
||||
assert.equal(config.turnRest, undefined);
|
||||
assert.deepEqual(resolveVoiceIceServers(config, "x"), []);
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import {
|
||||
hasVoiceTurnServer,
|
||||
normalizeVoiceIceServers,
|
||||
normalizeVoiceIceTransportPolicy,
|
||||
VOICE_JITTER_DEFAULT_MS,
|
||||
VOICE_JITTER_MAX_MS,
|
||||
VOICE_JITTER_MIN_MS,
|
||||
VOICE_TURN_MIN_SECRET_LENGTH,
|
||||
VOICE_TURN_TTL_DEFAULT_SECONDS,
|
||||
VOICE_TURN_TTL_MAX_SECONDS,
|
||||
VOICE_TURN_TTL_MIN_SECONDS,
|
||||
type VoiceIceServer,
|
||||
type VoiceIceTransportPolicy,
|
||||
} from "../shared/voice-ice.js";
|
||||
import { createTurnRestCredential, type TurnRestConfig } from "./turn-credentials.js";
|
||||
import { normalizeVoiceProfileSetting, type VoiceProfileSetting } from "../shared/voice-profile.js";
|
||||
|
||||
export interface VoiceIceConfig {
|
||||
servers: VoiceIceServer[];
|
||||
turnRest?: TurnRestConfig;
|
||||
/** Browser policy; keep `all` for direct UDP-first deployments. */
|
||||
transportPolicy: VoiceIceTransportPolicy;
|
||||
/** werift policy; use `relay` only when the gateway itself is behind NAT. */
|
||||
gatewayTransportPolicy: VoiceIceTransportPolicy;
|
||||
/** Per-connection audio profile: direct traffic defaults to legacy. */
|
||||
profile: VoiceProfileSetting;
|
||||
opusWebSocket: boolean;
|
||||
jitterMaxMs: number;
|
||||
}
|
||||
|
||||
export interface VoiceIceSettings {
|
||||
servers: VoiceIceServer[];
|
||||
transportPolicy: VoiceIceTransportPolicy;
|
||||
gatewayTransportPolicy: VoiceIceTransportPolicy;
|
||||
profile: VoiceProfileSetting;
|
||||
opusWebSocket: boolean;
|
||||
jitterMaxMs: number;
|
||||
}
|
||||
|
||||
/** Baseline used when neither the console nor the environment configures a value. */
|
||||
export const DEFAULT_VOICE_ICE_CONFIG: VoiceIceConfig = {
|
||||
servers: [],
|
||||
transportPolicy: "all",
|
||||
gatewayTransportPolicy: "all",
|
||||
profile: "auto",
|
||||
opusWebSocket: false,
|
||||
jitterMaxMs: VOICE_JITTER_DEFAULT_MS,
|
||||
};
|
||||
|
||||
function parseBoolean(value: string | undefined, fallback: boolean): boolean {
|
||||
if (value === undefined) return fallback;
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (!normalized) return fallback;
|
||||
return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
|
||||
}
|
||||
|
||||
function parseInteger(value: string | undefined, fallback: number, min: number, max: number): number {
|
||||
if (!value?.trim()) return fallback;
|
||||
const parsed = Number(value);
|
||||
if (!Number.isInteger(parsed)) return fallback;
|
||||
return Math.max(min, Math.min(max, parsed));
|
||||
}
|
||||
|
||||
function parseStaticServers(raw: string | undefined): VoiceIceServer[] {
|
||||
const value = raw?.trim();
|
||||
if (!value) return [];
|
||||
if (value.startsWith("[") || value.startsWith("{")) {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (Array.isArray(parsed)) return normalizeVoiceIceServers(parsed);
|
||||
if (parsed && typeof parsed === "object") return normalizeVoiceIceServers([parsed]);
|
||||
return [];
|
||||
} catch {
|
||||
// Fall through to the convenient comma/space-separated STUN form.
|
||||
}
|
||||
}
|
||||
return normalizeVoiceIceServers(value.split(/[\s,]+/).filter(Boolean).map((urls) => ({ urls })));
|
||||
}
|
||||
|
||||
function parseTurnRestUrls(raw: string | undefined): string[] {
|
||||
if (!raw?.trim()) return [];
|
||||
// Environment parsing stays lenient: one bad entry must not disable a
|
||||
// previously working TURN deployment during an upgrade.
|
||||
const urls = raw.split(/[\s,]+/).filter(Boolean).flatMap((token) => {
|
||||
const [server] = normalizeVoiceIceServers([{ urls: token }]);
|
||||
if (!server) return [];
|
||||
const candidates = Array.isArray(server.urls) ? server.urls : [server.urls];
|
||||
return candidates.filter((url) => /^turns?:/i.test(url));
|
||||
});
|
||||
return [...new Set(urls)].slice(0, 8);
|
||||
}
|
||||
|
||||
export function readVoiceIceConfig(env: NodeJS.ProcessEnv = process.env): VoiceIceConfig {
|
||||
const servers = parseStaticServers(env.WEBSPEAK_VOICE_ICE_SERVERS);
|
||||
const turnUrls = parseTurnRestUrls(env.WEBSPEAK_TURN_REST_URLS);
|
||||
const secret = env.WEBSPEAK_TURN_REST_SECRET?.trim() ?? "";
|
||||
const ttlSeconds = parseInteger(env.WEBSPEAK_TURN_REST_TTL_SECONDS, VOICE_TURN_TTL_DEFAULT_SECONDS, VOICE_TURN_TTL_MIN_SECONDS, VOICE_TURN_TTL_MAX_SECONDS);
|
||||
const turnRest = turnUrls.length && secret.length >= VOICE_TURN_MIN_SECRET_LENGTH
|
||||
? { urls: turnUrls, secret, ttlSeconds }
|
||||
: undefined;
|
||||
return {
|
||||
...DEFAULT_VOICE_ICE_CONFIG,
|
||||
servers,
|
||||
...(turnRest ? { turnRest } : {}),
|
||||
transportPolicy: normalizeVoiceIceTransportPolicy(env.WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY),
|
||||
gatewayTransportPolicy: normalizeVoiceIceTransportPolicy(env.WEBSPEAK_VOICE_GATEWAY_ICE_TRANSPORT_POLICY),
|
||||
profile: normalizeVoiceProfileSetting(env.WEBSPEAK_VOICE_PROFILE),
|
||||
// Opus over WebSocket is additive and remains opt-in even in adaptive mode.
|
||||
opusWebSocket: parseBoolean(env.WEBSPEAK_VOICE_OPUS_WS, false),
|
||||
jitterMaxMs: parseInteger(env.WEBSPEAK_VOICE_JITTER_MAX_MS, VOICE_JITTER_DEFAULT_MS, VOICE_JITTER_MIN_MS, VOICE_JITTER_MAX_MS),
|
||||
};
|
||||
}
|
||||
|
||||
/** Build the per-connection list, minting one short-lived TURN credential. */
|
||||
export function resolveVoiceIceServers(
|
||||
config: VoiceIceConfig | undefined,
|
||||
sessionId: string,
|
||||
nowMs = Date.now(),
|
||||
): VoiceIceServer[] {
|
||||
if (!config) return [];
|
||||
const servers = [...config.servers];
|
||||
if (config.turnRest) {
|
||||
servers.push(createTurnRestCredential(config.turnRest, sessionId, nowMs));
|
||||
}
|
||||
return normalizeVoiceIceServers(servers);
|
||||
}
|
||||
|
||||
export function voiceConfigSettings(config: VoiceIceConfig): VoiceIceSettings {
|
||||
return {
|
||||
servers: normalizeVoiceIceServers(config.servers),
|
||||
transportPolicy: config.transportPolicy,
|
||||
gatewayTransportPolicy: config.gatewayTransportPolicy,
|
||||
profile: config.profile,
|
||||
opusWebSocket: config.opusWebSocket,
|
||||
jitterMaxMs: config.jitterMaxMs,
|
||||
};
|
||||
}
|
||||
|
||||
export { hasVoiceTurnServer };
|
||||
@@ -109,6 +109,89 @@ for (const scenario of ["silence gaps", "alternating speakers", "volume changes"
|
||||
});
|
||||
}
|
||||
|
||||
test("WebRTC marks only the first audible RTP packet after a gap", () => {
|
||||
const packets: RtpPacket[] = [];
|
||||
const session = Object.assign(Object.create(WebRtcAudioSession.prototype), {
|
||||
closed: false,
|
||||
outgoingPayloadType: 111,
|
||||
sequenceNumber: 0,
|
||||
timestamp: 0,
|
||||
ssrc: 7,
|
||||
lastAudioRtpAt: null as number | null,
|
||||
lastEgressRtpAt: null as number | null,
|
||||
outgoingTrack: { writeRtp(packet: RtpPacket) { packets.push(packet); } },
|
||||
stats: { webrtcEgressRtpFrames: 0, webrtcEgressRtpMaxGapMs: 0, webrtcEgressRtpFirstAt: null, webrtcEgressRtpLastAt: null },
|
||||
}) as unknown as WebRtcAudioSession;
|
||||
const send = (session as unknown as { sendRtpAudio(payload: Buffer, hasAudio: boolean): void }).sendRtpAudio.bind(session);
|
||||
send(Buffer.from([1]), true);
|
||||
send(Buffer.from([2]), true);
|
||||
send(Buffer.from([3]), false);
|
||||
assert.deepEqual(packets.map(packet => packet.header.marker), [true, false, false]);
|
||||
(session as unknown as { lastAudioRtpAt: number | null }).lastAudioRtpAt = performance.now() - 50;
|
||||
send(Buffer.from([4]), true);
|
||||
send(Buffer.from([5]), true);
|
||||
assert.deepEqual(packets.map(packet => packet.header.marker), [true, false, false, true, false]);
|
||||
});
|
||||
|
||||
test("legacy RTP pacing keeps the original marker on every packet", () => {
|
||||
const packets: RtpPacket[] = [];
|
||||
const session = Object.assign(Object.create(WebRtcAudioSession.prototype), {
|
||||
closed: false,
|
||||
outgoingPayloadType: 111,
|
||||
sequenceNumber: 0,
|
||||
timestamp: 0,
|
||||
ssrc: 7,
|
||||
lastAudioRtpAt: null as number | null,
|
||||
lastEgressRtpAt: null as number | null,
|
||||
rtpMarkerAlways: true,
|
||||
outgoingTrack: { writeRtp(packet: RtpPacket) { packets.push(packet); } },
|
||||
stats: { webrtcEgressRtpFrames: 0, webrtcEgressRtpMaxGapMs: 0, webrtcEgressRtpFirstAt: null, webrtcEgressRtpLastAt: null },
|
||||
}) as unknown as WebRtcAudioSession;
|
||||
const send = (session as unknown as { sendRtpAudio(payload: Buffer, hasAudio: boolean): void }).sendRtpAudio.bind(session);
|
||||
send(Buffer.from([1]), true);
|
||||
send(Buffer.from([2]), false);
|
||||
assert.deepEqual(packets.map(packet => packet.header.marker), [true, true]);
|
||||
});
|
||||
|
||||
test("legacy WebRTC profile selects the original bounded mixer constants", async t => {
|
||||
const session = new WebRtcAudioSession({ connectionId: "legacy-mixer", logger: pino({ enabled: false }), onVoiceFrame() {}, onVoiceActivity() {} });
|
||||
t.after(() => session.close());
|
||||
const internals = session as unknown as { mixerQueueFrames: number; maxMixerFrameAgeMs: number; mixerQueueAfterLateTick: number; rtpMarkerAlways: boolean };
|
||||
assert.equal(internals.mixerQueueFrames, 4);
|
||||
assert.equal(internals.maxMixerFrameAgeMs, 80);
|
||||
assert.equal(internals.mixerQueueAfterLateTick, 1);
|
||||
assert.equal(internals.rtpMarkerAlways, true);
|
||||
});
|
||||
|
||||
test("adaptive WebRTC profile keeps the longer queue and corrected marker", async t => {
|
||||
const session = new WebRtcAudioSession({ connectionId: "adaptive-mixer", profile: "adaptive", logger: pino({ enabled: false }), onVoiceFrame() {}, onVoiceActivity() {} });
|
||||
t.after(() => session.close());
|
||||
const internals = session as unknown as { mixerQueueFrames: number; maxMixerFrameAgeMs: number; mixerQueueAfterLateTick: number; rtpMarkerAlways: boolean };
|
||||
assert.equal(internals.mixerQueueFrames, 6);
|
||||
assert.equal(internals.maxMixerFrameAgeMs, 200);
|
||||
assert.equal(internals.mixerQueueAfterLateTick, 2);
|
||||
assert.equal(internals.rtpMarkerAlways, false);
|
||||
});
|
||||
|
||||
test("late-tick trimming keeps legacy queue bounds and clears adaptive stale frames", () => {
|
||||
for (const [profile, queueAfterLateTick, frameAgeMs, frameCount, expectedRemaining, expectedDropped] of [
|
||||
["legacy", 1, 0, 3, 1, 2],
|
||||
["legacy", 1, 100, 1, 0, 1],
|
||||
["adaptive", 2, 100, 3, 0, 3],
|
||||
] as const) {
|
||||
const queue = Array.from({ length: frameCount }, () => ({ pcm: Buffer.alloc(4), receivedAt: performance.now() - frameAgeMs - 1 }));
|
||||
const session = Object.assign(Object.create(WebRtcAudioSession.prototype), {
|
||||
pendingFrames: new Map([["speaker", queue]]),
|
||||
mixerQueueAfterLateTick: queueAfterLateTick,
|
||||
maxMixerFrameAgeMs: 100,
|
||||
stats: { webrtcQueueDroppedFrames: 0 },
|
||||
}) as WebRtcAudioSession;
|
||||
(session as unknown as { trimQueuesAfterLateTick(): void }).trimQueuesAfterLateTick();
|
||||
assert.equal(queue.length, expectedRemaining, profile);
|
||||
assert.equal((session as unknown as { stats: { webrtcQueueDroppedFrames: number } }).stats.webrtcQueueDroppedFrames, expectedDropped, profile);
|
||||
}
|
||||
});
|
||||
|
||||
function fixture() {
|
||||
const released: string[] = [];
|
||||
// Exercise the real close path with failures at codec/track/peer boundaries.
|
||||
|
||||
@@ -12,6 +12,8 @@ import { WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
|
||||
import { OpusEncoder } from "./opus-codec.js";
|
||||
import type { WebRtcSessionDescription } from "../shared/webrtc.js";
|
||||
import { addOpusFmtpParameters } from "../shared/opus-sdp.js";
|
||||
import type { VoiceIceServer, VoiceIceTransportPolicy } from "../shared/voice-ice.js";
|
||||
import type { VoiceProfile } from "../shared/voice-profile.js";
|
||||
export type { WebRtcSessionDescription } from "../shared/webrtc.js";
|
||||
|
||||
export { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
|
||||
@@ -23,9 +25,15 @@ const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS * 2;
|
||||
const DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
|
||||
const AUDIO_CLOCK_INTERVAL_MS = 20;
|
||||
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
|
||||
const MAX_MIXER_QUEUE_FRAMES = 4;
|
||||
const MAX_MIXER_QUEUE_FRAMES = 6;
|
||||
const MAX_MIXER_PACER_LAG_MS = AUDIO_CLOCK_INTERVAL_MS * 2;
|
||||
const MAX_MIXER_FRAME_AGE_MS = MAX_MIXER_QUEUE_FRAMES * AUDIO_CLOCK_INTERVAL_MS;
|
||||
const MAX_MIXER_FRAME_AGE_MS = 200;
|
||||
const MAX_MIXER_QUEUE_AFTER_LATE_TICK = 2;
|
||||
// The pre-CFT implementation used a 4-frame queue, an 80 ms age bound and one
|
||||
// retained frame after a late tick. Keep those values for direct deployments.
|
||||
const LEGACY_MAX_MIXER_QUEUE_FRAMES = 4;
|
||||
const LEGACY_MAX_MIXER_FRAME_AGE_MS = LEGACY_MAX_MIXER_QUEUE_FRAMES * AUDIO_CLOCK_INTERVAL_MS;
|
||||
const LEGACY_MAX_MIXER_QUEUE_AFTER_LATE_TICK = 1;
|
||||
const MIXER_UNDERRUN_WINDOW_MS = 200;
|
||||
// This threshold is used only for the speaking indicator. It must never decide
|
||||
// whether a media packet is forwarded or queued: quiet/comfort-noise Opus
|
||||
@@ -40,6 +48,9 @@ export interface WebRtcAudioOptions {
|
||||
publicHost?: string;
|
||||
ipv6Enabled?: boolean;
|
||||
stunServer?: string;
|
||||
/** Full ICE list, including TURN; takes precedence over `stunServer`. */
|
||||
iceServers?: VoiceIceServer[];
|
||||
iceTransportPolicy?: VoiceIceTransportPolicy;
|
||||
udpPortRange?: [number, number];
|
||||
}
|
||||
|
||||
@@ -51,6 +62,10 @@ export interface WebRtcAudioSessionOptions {
|
||||
publicAddresses?: string[];
|
||||
ipv6Enabled?: boolean;
|
||||
stunServer?: string;
|
||||
iceServers?: VoiceIceServer[];
|
||||
iceTransportPolicy?: VoiceIceTransportPolicy;
|
||||
/** `legacy` preserves the direct-deployment mixer; `adaptive` is the CFT path. */
|
||||
profile?: VoiceProfile;
|
||||
publicHost?: string;
|
||||
udpPortRange?: [number, number];
|
||||
logger: LoggerType;
|
||||
@@ -122,7 +137,12 @@ export class WebRtcAudioSession {
|
||||
private nextAudioDeadline = 0;
|
||||
private lastIngressRtpAt: number | null = null;
|
||||
private lastEgressRtpAt: number | null = null;
|
||||
private lastAudioRtpAt: number | null = null;
|
||||
private lastQueueEnqueuedAt: number | null = null;
|
||||
private readonly mixerQueueFrames: number;
|
||||
private readonly maxMixerFrameAgeMs: number;
|
||||
private readonly mixerQueueAfterLateTick: number;
|
||||
private readonly rtpMarkerAlways: boolean;
|
||||
private microphoneMuted: boolean;
|
||||
private accompanimentActive: boolean;
|
||||
private readonly stats: WebRtcAudioStats = {
|
||||
@@ -150,19 +170,31 @@ export class WebRtcAudioSession {
|
||||
this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId });
|
||||
this.onVoiceFrame = options.onVoiceFrame;
|
||||
this.onVoiceActivity = options.onVoiceActivity;
|
||||
const profile = options.profile ?? "legacy";
|
||||
this.mixerQueueFrames = profile === "legacy" ? LEGACY_MAX_MIXER_QUEUE_FRAMES : MAX_MIXER_QUEUE_FRAMES;
|
||||
this.maxMixerFrameAgeMs = profile === "legacy" ? LEGACY_MAX_MIXER_FRAME_AGE_MS : MAX_MIXER_FRAME_AGE_MS;
|
||||
this.mixerQueueAfterLateTick = profile === "legacy" ? LEGACY_MAX_MIXER_QUEUE_AFTER_LATE_TICK : MAX_MIXER_QUEUE_AFTER_LATE_TICK;
|
||||
this.rtpMarkerAlways = profile === "legacy";
|
||||
this.microphoneMuted = options.microphoneMuted === true;
|
||||
this.accompanimentActive = options.accompanimentActive === true;
|
||||
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
|
||||
|
||||
const iceAdditionalHostAddresses = options.publicAddresses ?? (options.publicHost ? [options.publicHost] : undefined);
|
||||
const udpPortRange = options.udpPortRange ?? WEBRTC_UDP_PORT_RANGE;
|
||||
const iceServers = options.iceServers?.length
|
||||
? options.iceServers
|
||||
: options.stunServer ? [{ urls: options.stunServer }] : [];
|
||||
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: options.stunServer ? [{ urls: options.stunServer }] : [],
|
||||
iceServers,
|
||||
iceTransportPolicy: options.iceTransportPolicy ?? "all",
|
||||
iceUseIpv4: true,
|
||||
iceUseIpv6: options.ipv6Enabled === true,
|
||||
// This controls ICE-TCP host candidates, not TURN control transport.
|
||||
// werift parses `turns:` as a TLS TURN client independently; verified in
|
||||
// peerConnection.ts createTransport() -> parseIceServers().
|
||||
iceUseTcp: false,
|
||||
icePortRange: [...udpPortRange] as [number, number],
|
||||
...(iceAdditionalHostAddresses ? { iceAdditionalHostAddresses } : {}),
|
||||
@@ -315,7 +347,7 @@ export class WebRtcAudioSession {
|
||||
queue = [];
|
||||
this.pendingFrames.set(data.clientId, queue);
|
||||
}
|
||||
if (queue.length >= MAX_MIXER_QUEUE_FRAMES) {
|
||||
if (queue.length >= this.mixerQueueFrames) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
@@ -398,6 +430,7 @@ export class WebRtcAudioSession {
|
||||
}
|
||||
}
|
||||
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS);
|
||||
const hasAudio = this.pendingFrames.size > 0;
|
||||
for (const [clientId, queue] of this.pendingFrames) {
|
||||
const frame = queue.shift();
|
||||
if (queue.length === 0) this.pendingFrames.delete(clientId);
|
||||
@@ -422,25 +455,30 @@ export class WebRtcAudioSession {
|
||||
}
|
||||
try {
|
||||
const encoded = this.encoder.encode(pcm);
|
||||
this.sendRtpAudio(encoded);
|
||||
this.sendRtpAudio(encoded, hasAudio);
|
||||
} catch {
|
||||
// A peer closing concurrently may reject a packet; teardown owns the
|
||||
// session lifecycle and no per-frame error needs to reach the logs.
|
||||
}
|
||||
}
|
||||
|
||||
private sendRtpAudio(encoded: Buffer): void {
|
||||
private sendRtpAudio(encoded: Buffer, hasAudio: boolean): void {
|
||||
const now = performance.now();
|
||||
const marker = this.rtpMarkerAlways
|
||||
? true
|
||||
: hasAudio && (this.lastAudioRtpAt === null || now - this.lastAudioRtpAt > 40);
|
||||
const packet = new RtpPacket(new RtpHeader({
|
||||
payloadType: this.outgoingPayloadType,
|
||||
sequenceNumber: this.sequenceNumber,
|
||||
timestamp: this.timestamp,
|
||||
ssrc: this.ssrc,
|
||||
marker: true,
|
||||
marker,
|
||||
}), encoded);
|
||||
this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff;
|
||||
this.timestamp = (this.timestamp + AUDIO_FRAME_SAMPLES) >>> 0;
|
||||
this.outgoingTrack.writeRtp(packet);
|
||||
const sentAt = performance.now();
|
||||
if (hasAudio) this.lastAudioRtpAt = sentAt;
|
||||
if (this.lastEgressRtpAt !== null) this.stats.webrtcEgressRtpMaxGapMs = Math.max(this.stats.webrtcEgressRtpMaxGapMs, Math.round(sentAt - this.lastEgressRtpAt));
|
||||
this.lastEgressRtpAt = sentAt;
|
||||
this.stats.webrtcEgressRtpFirstAt ??= Date.now();
|
||||
@@ -497,11 +535,11 @@ export class WebRtcAudioSession {
|
||||
private trimQueuesAfterLateTick(): void {
|
||||
const now = performance.now();
|
||||
for (const [clientId, queue] of this.pendingFrames) {
|
||||
while (queue.length > 1) {
|
||||
while (queue.length > this.mixerQueueAfterLateTick) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
if (queue[0] && now - queue[0].receivedAt > MAX_MIXER_FRAME_AGE_MS) {
|
||||
while (queue[0] && now - queue[0].receivedAt > this.maxMixerFrameAgeMs) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user