feat: make WebRTC media service self-contained

This commit is contained in:
illusia committed 2026-09-03 10:56:39 +08:00
1 parent d6c8ccb73f
commit c7def28a8f
14 files changed
+160 -121

No files matched your search

-3
View File
@@ -333,9 +333,6 @@ function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
siteName: readString(body, "siteName", 80),
welcomeText: readOptionalString(body, "welcomeText", 500),
webRtcEnabled: body.webRtcEnabled === true,
webRtcPublicHost: readOptionalString(body, "webRtcPublicHost", 253),
webRtcUdpStart: readOptionalNumber(body, "webRtcUdpStart", 40000),
webRtcUdpEnd: readOptionalNumber(body, "webRtcUdpEnd", 40099),
};
}
+1 -34
View File
@@ -9,8 +9,6 @@ import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
import { probeTeamSpeak, TeamSpeakProbeError, type TeamSpeakProbeResult } from "../server/teamspeak-probe.js";
import type { WebRtcAudioOptions } from "../server/webrtc-audio.js";
const MAX_WEBRTC_UDP_PORTS = 100;
export interface AdminSettingsInput {
target: string;
serverPassword?: string;
@@ -19,9 +17,6 @@ export interface AdminSettingsInput {
siteName: string;
welcomeText: string;
webRtcEnabled: boolean;
webRtcPublicHost: string;
webRtcUdpStart: number;
webRtcUdpEnd: number;
}
export interface ConnectionPolicy {
@@ -116,9 +111,6 @@ export class AdminService {
lastTestLatencyMs: settings.lastTestLatencyMs,
lastTestError: settings.lastTestError,
webRtcEnabled: settings.webRtcEnabled,
webRtcPublicHost: settings.webRtcPublicHost,
webRtcUdpStart: settings.webRtcUdpStart,
webRtcUdpEnd: settings.webRtcUdpEnd,
internalPort: 3040,
updatedAt: settings.updatedAt,
};
@@ -126,11 +118,7 @@ export class AdminService {
getWebRtcAudioOptions(): WebRtcAudioOptions {
const settings = this.database.getSettings();
return {
enabled: settings.webRtcEnabled,
...(settings.webRtcPublicHost ? { publicHost: settings.webRtcPublicHost } : {}),
icePortRange: [settings.webRtcUdpStart, settings.webRtcUdpEnd],
};
return { enabled: settings.webRtcEnabled };
}
updateSettings(input: AdminSettingsInput): void {
@@ -275,18 +263,6 @@ export class AdminService {
if (typeof input.webRtcEnabled !== "boolean") {
throw new AdminInputError("INVALID_WEBRTC_ENABLED", "WebRTC enabled value is invalid");
}
const webRtcPublicHost = input.webRtcPublicHost.trim();
if (webRtcPublicHost.length > 253 || /[\s/\\]/.test(webRtcPublicHost)) {
throw new AdminInputError("INVALID_WEBRTC_HOST", "WebRTC public host is invalid");
}
if (
!Number.isInteger(input.webRtcUdpStart) || input.webRtcUdpStart < 1 || input.webRtcUdpStart > 65_535
|| !Number.isInteger(input.webRtcUdpEnd) || input.webRtcUdpEnd < 1 || input.webRtcUdpEnd > 65_535
|| input.webRtcUdpStart > input.webRtcUdpEnd
|| input.webRtcUdpEnd - input.webRtcUdpStart + 1 > MAX_WEBRTC_UDP_PORTS
) {
throw new AdminInputError("INVALID_WEBRTC_PORTS", "WebRTC UDP port range is invalid");
}
let encryptedPassword = current.tsPasswordEncrypted;
const action = input.passwordAction ?? (input.serverPassword === undefined ? "keep" : "replace");
@@ -300,9 +276,6 @@ export class AdminService {
tsPort: target.port,
tsPasswordEncrypted: encryptedPassword,
webRtcEnabled: input.webRtcEnabled,
webRtcPublicHost,
webRtcUdpStart: input.webRtcUdpStart,
webRtcUdpEnd: input.webRtcUdpEnd,
};
}
@@ -332,9 +305,6 @@ export class AdminService {
tsPort: settings.tsPort,
tsPasswordEncrypted: settings.tsPasswordEncrypted,
webRtcEnabled: settings.webRtcEnabled,
webRtcPublicHost: settings.webRtcPublicHost,
webRtcUdpStart: settings.webRtcUdpStart,
webRtcUdpEnd: settings.webRtcUdpEnd,
};
}
@@ -351,9 +321,6 @@ export class AdminService {
tsPort: legacy.tsPort,
tsPasswordEncrypted: legacy.tsServerPassword ? encryptSecret(legacy.tsServerPassword, this.masterSecret) : null,
webRtcEnabled: current.webRtcEnabled,
webRtcPublicHost: current.webRtcPublicHost,
webRtcUdpStart: current.webRtcUdpStart,
webRtcUdpEnd: current.webRtcUdpEnd,
}, "LEGACY_CONFIG_IMPORTED");
this.database.setMeta("legacy_config_imported", "1");
this.database.setMeta("legacy_import_notice_pending", "1");
+4 -14
View File
@@ -20,9 +20,6 @@ export interface PersistedSettings {
lastTestLatencyMs: number | null;
lastTestError: string | null;
webRtcEnabled: boolean;
webRtcPublicHost: string;
webRtcUdpStart: number;
webRtcUdpEnd: number;
updatedAt: string;
}
@@ -34,9 +31,6 @@ export interface SettingsUpdate {
tsPort: number;
tsPasswordEncrypted: string | null;
webRtcEnabled: boolean;
webRtcPublicHost: string;
webRtcUdpStart: number;
webRtcUdpEnd: number;
}
export interface ManagedInviteRecord {
@@ -153,9 +147,6 @@ export class WebSpeakDatabase {
lastTestLatencyMs: row.last_test_latency_ms,
lastTestError: row.last_test_error,
webRtcEnabled: row.webrtc_enabled === 1,
webRtcPublicHost: row.webrtc_public_host,
webRtcUdpStart: row.webrtc_udp_start,
webRtcUdpEnd: row.webrtc_udp_end,
updatedAt: row.updated_at,
};
}
@@ -370,6 +361,9 @@ export class WebSpeakDatabase {
if (version === 2) {
this.transaction(() => {
this.database.exec(`
-- The host and range columns are retained for v3 database compatibility.
-- WebSpeak no longer reads or exposes them; WebRTC now owns its media
-- endpoint and derives the public host from each browser connection.
ALTER TABLE settings ADD COLUMN webrtc_enabled INTEGER NOT NULL DEFAULT 0 CHECK (webrtc_enabled IN (0, 1));
ALTER TABLE settings ADD COLUMN webrtc_public_host TEXT NOT NULL DEFAULT '';
ALTER TABLE settings ADD COLUMN webrtc_udp_start INTEGER NOT NULL DEFAULT 40000 CHECK (webrtc_udp_start BETWEEN 1 AND 65535);
@@ -384,8 +378,7 @@ export class WebSpeakDatabase {
this.database.prepare(
`UPDATE settings SET
site_name = ?, welcome_text = ?, access_mode = ?, ts_host = ?, ts_port = ?,
ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_public_host = ?,
webrtc_udp_start = ?, webrtc_udp_end = ?, updated_at = ?
ts_password_encrypted = ?, webrtc_enabled = ?, updated_at = ?
WHERE id = 1`,
).run(
settings.siteName,
@@ -395,9 +388,6 @@ export class WebSpeakDatabase {
settings.tsPort,
settings.tsPasswordEncrypted,
settings.webRtcEnabled ? 1 : 0,
settings.webRtcPublicHost,
settings.webRtcUdpStart,
settings.webRtcUdpEnd,
now,
);
}
+76 -2
View File
@@ -52,11 +52,24 @@ export interface AudioFlowStats {
ingressFirstAt: number | null;
ingressLastAt: number | null;
ingressMaxGapMs: number;
tsSendFrames: number;
tsSendErrors: number;
tsSendFirstAt: number | null;
tsSendLastAt: number | null;
tsSendMaxGapMs: number;
tsEncodeMaxMs: number;
tsReceiveFrames: number;
tsReceiveFirstAt: number | null;
tsReceiveLastAt: number | null;
tsReceiveMaxGapMs: number;
egressFrames: number;
egressDroppedFrames: number;
egressFirstAt: number | null;
egressLastAt: number | null;
egressMaxGapMs: number;
egressSentFirstAt: number | null;
egressSentLastAt: number | null;
egressSentMaxGapMs: number;
egressPeakBufferedBytes: number;
egressFramesByClient: Record<string, number>;
}
@@ -87,6 +100,7 @@ interface WebClientEntry {
nickname: string;
rememberIdentity: boolean;
target: TeamSpeakTarget;
webrtcPublicHost?: string;
channelTree: unknown[];
members: Map<number, ChannelMember>;
eventLog: ServerEvent[];
@@ -127,6 +141,7 @@ export class VoiceBridge {
const { target, serverPassword, nickname } = connection;
const channelName = connection.channel;
const webrtcPublicHost = resolveWebRtcPublicHost(req);
let identity;
try {
identity = connection.identity ? identityFromString(connection.identity) : undefined;
@@ -163,6 +178,7 @@ export class VoiceBridge {
nickname,
rememberIdentity: connection.rememberIdentity === true,
target,
...(webrtcPublicHost ? { webrtcPublicHost } : {}),
channelTree: [],
members: new Map(),
eventLog: [],
@@ -422,10 +438,15 @@ export class VoiceBridge {
});
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 = Date.now();
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;
@@ -452,6 +473,10 @@ export class VoiceBridge {
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++;
}
@@ -500,14 +525,23 @@ export class VoiceBridge {
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++;
}
} catch {
// A frame arriving during shutdown is safe to discard.
entry!.audio.tsSendErrors++;
}
return;
}
@@ -701,7 +735,7 @@ export class VoiceBridge {
if (!config?.enabled) return;
const peer = new WebRtcAudioSession({
connectionId: entry.id,
config,
...(entry.webrtcPublicHost ? { publicHost: entry.webrtcPublicHost } : {}),
logger: this.logger,
onVoiceFrame: (data) => {
const now = Date.now();
@@ -736,6 +770,33 @@ export class VoiceBridge {
}
}
function resolveWebRtcPublicHost(request: IncomingMessage): string | undefined {
const origin = firstHeader(request.headers.origin);
const forwardedHost = firstHeader(request.headers["x-forwarded-host"]);
const directHost = firstHeader(request.headers.host);
for (const candidate of [origin, forwardedHost, directHost]) {
const host = normalizeWebRtcHost(candidate);
if (host) return host;
}
return undefined;
}
function firstHeader(value: string | string[] | undefined): string | undefined {
return Array.isArray(value) ? value[0] : value;
}
function normalizeWebRtcHost(value: string | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.split(",", 1)[0]?.trim();
if (!trimmed || trimmed.toLowerCase() === "null") return undefined;
try {
const parsed = new URL(trimmed.includes("://") ? trimmed : `https://${trimmed}`);
return parsed.hostname || undefined;
} catch {
return undefined;
}
}
async function handleCommand(
entry: WebClientEntry,
command: ClientCommand,
@@ -859,11 +920,24 @@ function createAudioFlowStats(): AudioFlowStats {
ingressFirstAt: null,
ingressLastAt: null,
ingressMaxGapMs: 0,
tsSendFrames: 0,
tsSendErrors: 0,
tsSendFirstAt: null,
tsSendLastAt: null,
tsSendMaxGapMs: 0,
tsEncodeMaxMs: 0,
tsReceiveFrames: 0,
tsReceiveFirstAt: null,
tsReceiveLastAt: null,
tsReceiveMaxGapMs: 0,
egressFrames: 0,
egressDroppedFrames: 0,
egressFirstAt: null,
egressLastAt: null,
egressMaxGapMs: 0,
egressSentFirstAt: null,
egressSentLastAt: null,
egressSentMaxGapMs: 0,
egressPeakBufferedBytes: 0,
egressFramesByClient: {},
};
+8 -5
View File
@@ -24,10 +24,13 @@ const DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
const AUDIO_CLOCK_INTERVAL_MS = 20;
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
// WebRTC is served by the WebSpeak process itself. Docker publishes this
// fixed range so the administrator only needs to enable the transport; the
// advertised host is derived from the browser's current WebSpeak address.
export const WEBRTC_UDP_PORT_RANGE: [number, number] = [40000, 40099];
export interface WebRtcAudioOptions {
enabled: boolean;
publicHost?: string;
icePortRange?: [number, number];
}
export interface WebRtcSessionDescription {
@@ -37,7 +40,7 @@ export interface WebRtcSessionDescription {
export interface WebRtcAudioSessionOptions {
connectionId: string;
config: WebRtcAudioOptions;
publicHost?: string;
logger: LoggerType;
onVoiceFrame: (data: Buffer) => void;
onVoiceActivity: (clientIds: number[]) => void;
@@ -77,13 +80,13 @@ export class WebRtcAudioSession {
this.onVoiceActivity = options.onVoiceActivity;
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
const iceAdditionalHostAddresses = options.config.publicHost ? [options.config.publicHost] : undefined;
const iceAdditionalHostAddresses = options.publicHost ? [options.publicHost] : undefined;
this.peer = new RTCPeerConnection({
iceServers: [],
iceUseIpv4: true,
iceUseIpv6: false,
iceUseTcp: false,
...(options.config.icePortRange ? { icePortRange: options.config.icePortRange } : {}),
icePortRange: [...WEBRTC_UDP_PORT_RANGE] as [number, number],
...(iceAdditionalHostAddresses ? { iceAdditionalHostAddresses } : {}),
});