mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
feat(audio): add experimental WebRTC transport
This commit is contained in:
1 parent
7ff6836a7e
commit
8abd2d6228
6 files changed
+1000
-9
No files matched your search
@@ -11,6 +11,7 @@ import { JoinTicketStore, type JoinTicketPayload } from "./join-ticket.js";
|
||||
import { SessionManager, type ManagedSession, type SessionTeardownReason } from "./session-manager.js";
|
||||
import { parseClientCommand, type ClientCommand } from "./voice-protocol.js";
|
||||
import { isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "./reconnect-policy.js";
|
||||
import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcSessionDescription } from "./webrtc-audio.js";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { OpusEncoder } = require("@discordjs/opus") as {
|
||||
@@ -29,6 +30,7 @@ const MAX_SERVER_AUDIO_BUFFERED_BYTES = 4_096;
|
||||
|
||||
export interface VoiceBridgeOptions {
|
||||
joinTickets: JoinTicketStore;
|
||||
webRtc?: WebRtcAudioOptions;
|
||||
}
|
||||
|
||||
export interface AdminSessionSummary {
|
||||
@@ -94,6 +96,7 @@ interface WebClientEntry {
|
||||
isAlive: boolean;
|
||||
reconnectTimer: ReturnType<typeof setTimeout> | null;
|
||||
audio: AudioFlowStats;
|
||||
webrtc: WebRtcAudioSession | null;
|
||||
}
|
||||
|
||||
export class VoiceBridge {
|
||||
@@ -169,6 +172,7 @@ export class VoiceBridge {
|
||||
isAlive: true,
|
||||
reconnectTimer: null,
|
||||
audio: createAudioFlowStats(),
|
||||
webrtc: null,
|
||||
};
|
||||
this.entries.set(entryId, entry!);
|
||||
try {
|
||||
@@ -263,6 +267,7 @@ export class VoiceBridge {
|
||||
serverEventLog: entry!.eventLog,
|
||||
whisperTargetIds: [...entry!.whisperTargetIds],
|
||||
whisperActive: entry!.whisperActive,
|
||||
webrtcAvailable: this.options.webRtc?.enabled === true,
|
||||
...(entry!.rememberIdentity ? { identity: tsClient.getIdentityString() } : {}),
|
||||
});
|
||||
sendJson({ type: "channelList", channels: entry!.channelTree });
|
||||
@@ -418,6 +423,7 @@ export class VoiceBridge {
|
||||
|
||||
tsClient.on("voiceData", (data: TSVoiceData) => {
|
||||
if (ws.readyState !== WebSocket.OPEN || data.clientId === selfId) return;
|
||||
entry!.webrtc?.pushTeamSpeakVoice(data);
|
||||
const now = Date.now();
|
||||
if (entry!.audio.egressLastAt !== null) entry!.audio.egressMaxGapMs = Math.max(entry!.audio.egressMaxGapMs, now - entry!.audio.egressLastAt);
|
||||
entry!.audio.egressFirstAt ??= now;
|
||||
@@ -497,7 +503,21 @@ export class VoiceBridge {
|
||||
return;
|
||||
}
|
||||
|
||||
const command = parseClientCommand(typeof data === "string" ? data : data.toString("utf-8"));
|
||||
const rawMessage = typeof data === "string" ? data : data.toString("utf-8");
|
||||
const webRtcOffer = parseWebRtcOffer(rawMessage);
|
||||
if (webRtcOffer) {
|
||||
if (this.options.webRtc?.enabled !== true) {
|
||||
sendProtocolError(sendJson, "WEBRTC_DISABLED", "WebRTC 音频传输未启用");
|
||||
return;
|
||||
}
|
||||
if (!tsReady || session.state !== "connected") {
|
||||
sendProtocolError(sendJson, "SESSION_NOT_READY", "TeamSpeak 会话尚未就绪");
|
||||
return;
|
||||
}
|
||||
void this.handleWebRtcOffer(entry!, webRtcOffer, sendJson);
|
||||
return;
|
||||
}
|
||||
const command = parseClientCommand(rawMessage);
|
||||
if ("error" in command) {
|
||||
sendProtocolError(sendJson, command.error.code, command.error.message);
|
||||
return;
|
||||
@@ -607,6 +627,11 @@ export class VoiceBridge {
|
||||
entry.reconnectTimer = null;
|
||||
}
|
||||
entry.opusEncoder = null;
|
||||
const webRtc = entry.webrtc;
|
||||
entry.webrtc = null;
|
||||
if (webRtc) {
|
||||
try { await webRtc.close(); } catch { /* peer teardown is idempotent */ }
|
||||
}
|
||||
entry.whisperTargetIds.clear();
|
||||
entry.whisperActive = false;
|
||||
entry.channelTree = [];
|
||||
@@ -642,6 +667,48 @@ export class VoiceBridge {
|
||||
const token = url.searchParams.get("ticket");
|
||||
return token ? this.options.joinTickets.consume(token) : null;
|
||||
}
|
||||
|
||||
private async handleWebRtcOffer(
|
||||
entry: WebClientEntry,
|
||||
offer: WebRtcSessionDescription,
|
||||
sendJson: (message: Record<string, unknown>) => void,
|
||||
): Promise<void> {
|
||||
if (entry.webrtc) {
|
||||
try { await entry.webrtc.close(); } catch { /* replace a retried offer */ }
|
||||
entry.webrtc = null;
|
||||
}
|
||||
const config = this.options.webRtc;
|
||||
if (!config?.enabled) return;
|
||||
const peer = new WebRtcAudioSession({
|
||||
connectionId: entry.id,
|
||||
config,
|
||||
logger: this.logger,
|
||||
onVoiceFrame: (data) => {
|
||||
try {
|
||||
if (entry.whisperActive && entry.whisperTargetIds.size) entry.tsClient.sendWhisper(data, [...entry.whisperTargetIds], 4);
|
||||
else entry.tsClient.sendVoice(data, 4);
|
||||
} catch {
|
||||
// A packet arriving while the TeamSpeak session is being replaced
|
||||
// is discarded; the WebRTC peer remains independently closable.
|
||||
}
|
||||
},
|
||||
onVoiceActivity: (clientIds) => {
|
||||
if (entry.ws.readyState === WebSocket.OPEN) sendJson({ type: "voiceActivity", clientIds });
|
||||
},
|
||||
});
|
||||
entry.webrtc = peer;
|
||||
try {
|
||||
const answer = await peer.createAnswer(offer);
|
||||
if (entry.webrtc !== peer || entry.ws.readyState !== WebSocket.OPEN) return;
|
||||
sendJson({ type: "webrtcAnswer", payload: { sdp: answer } });
|
||||
this.logger.info({ entryId: entry.id }, "WebRTC audio negotiation completed");
|
||||
} catch (error: unknown) {
|
||||
if (entry.webrtc === peer) entry.webrtc = null;
|
||||
try { await peer.close(); } catch { /* best effort */ }
|
||||
this.logger.warn({ entryId: entry.id, err: error instanceof Error ? error.message : String(error) }, "WebRTC audio negotiation failed");
|
||||
if (entry.ws.readyState === WebSocket.OPEN) sendJson({ type: "webrtcError", code: "WEBRTC_NEGOTIATION_FAILED" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCommand(
|
||||
@@ -734,6 +801,19 @@ function sendProtocolError(sendJson: (message: Record<string, unknown>) => void,
|
||||
sendJson({ type: "error", error: { code, message, recoverable: false } });
|
||||
}
|
||||
|
||||
function parseWebRtcOffer(raw: string): WebRtcSessionDescription | null {
|
||||
let value: unknown;
|
||||
try { value = JSON.parse(raw); } catch { return null; }
|
||||
if (!isRecord(value) || value.type !== "webrtcOffer" || !isRecord(value.payload) || !isRecord(value.payload.sdp)) return null;
|
||||
const description = value.payload.sdp;
|
||||
if (description.type !== "offer" || typeof description.sdp !== "string" || description.sdp.length > 256 * 1024) return null;
|
||||
return { type: "offer", sdp: description.sdp };
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isChannelRecord(value: unknown): value is { id: string; name: string } {
|
||||
return Boolean(value) && typeof value === "object" && typeof (value as { id?: unknown }).id === "string" && typeof (value as { name?: unknown }).name === "string";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
import { randomInt } from "node:crypto";
|
||||
import { createRequire } from "node:module";
|
||||
import {
|
||||
MediaStreamTrack,
|
||||
RtpHeader,
|
||||
RtpPacket,
|
||||
RTCPeerConnection,
|
||||
} from "werift";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
import type { TSVoiceData } from "./ts-client.js";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { OpusDecoder, OpusEncoder } = require("@discordjs/opus") as {
|
||||
OpusDecoder: new (sampleRate: number, channels: number) => { decode(data: Buffer): Buffer };
|
||||
OpusEncoder: new (sampleRate: number, channels: number) => { encode(data: Buffer): Buffer };
|
||||
};
|
||||
|
||||
const AUDIO_SAMPLE_RATE = 48_000;
|
||||
const AUDIO_FRAME_SAMPLES = 960;
|
||||
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
|
||||
const WEBRTC_OPUS_PAYLOAD_TYPE = 111;
|
||||
const AUDIO_CLOCK_INTERVAL_MS = 20;
|
||||
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
|
||||
|
||||
export interface WebRtcAudioOptions {
|
||||
enabled: boolean;
|
||||
publicHost?: string;
|
||||
icePortRange?: [number, number];
|
||||
}
|
||||
|
||||
export interface WebRtcSessionDescription {
|
||||
type: "offer" | "answer";
|
||||
sdp: string;
|
||||
}
|
||||
|
||||
export interface WebRtcAudioSessionOptions {
|
||||
connectionId: string;
|
||||
config: WebRtcAudioOptions;
|
||||
logger: LoggerType;
|
||||
onVoiceFrame: (data: Buffer) => void;
|
||||
onVoiceActivity: (clientIds: number[]) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* One low-latency WebRTC audio session for one browser connection.
|
||||
*
|
||||
* TeamSpeak provides one Opus payload per speaker. WebRTC has one negotiated
|
||||
* audio track in this first transport, so this class mixes only the newest
|
||||
* 20 ms frame from each active speaker and packetizes the result as RTP. The
|
||||
* map is deliberately bounded to one frame per speaker; an old frame is
|
||||
* replaced instead of becoming a playback queue.
|
||||
*/
|
||||
export class WebRtcAudioSession {
|
||||
readonly peer: RTCPeerConnection;
|
||||
private readonly logger: LoggerType;
|
||||
private readonly onVoiceFrame: (data: Buffer) => void;
|
||||
private readonly onVoiceActivity: (clientIds: number[]) => void;
|
||||
private readonly outgoingTrack: MediaStreamTrack;
|
||||
private readonly decoderByClient = new Map<number, { decode(data: Buffer): Buffer }>();
|
||||
private readonly pendingFrames = new Map<number, Buffer>();
|
||||
private readonly activeSpeakerIds = new Set<number>();
|
||||
private readonly audioTimer: ReturnType<typeof setInterval>;
|
||||
private readonly activityTimer: ReturnType<typeof setInterval>;
|
||||
private encoder: { encode(data: Buffer): Buffer } | null;
|
||||
private sequenceNumber = randomInt(0, 65_536);
|
||||
private timestamp = randomInt(0, 0x1_0000_0000) >>> 0;
|
||||
private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0;
|
||||
private closed = false;
|
||||
|
||||
constructor(options: WebRtcAudioSessionOptions) {
|
||||
this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId });
|
||||
this.onVoiceFrame = options.onVoiceFrame;
|
||||
this.onVoiceActivity = options.onVoiceActivity;
|
||||
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
|
||||
|
||||
const iceAdditionalHostAddresses = options.config.publicHost ? [options.config.publicHost] : undefined;
|
||||
this.peer = new RTCPeerConnection({
|
||||
iceServers: [],
|
||||
iceUseIpv4: true,
|
||||
iceUseIpv6: false,
|
||||
iceUseTcp: false,
|
||||
...(options.config.icePortRange ? { icePortRange: options.config.icePortRange } : {}),
|
||||
...(iceAdditionalHostAddresses ? { iceAdditionalHostAddresses } : {}),
|
||||
});
|
||||
|
||||
const audio = this.peer.addTransceiver("audio", { direction: "sendrecv" });
|
||||
audio.onTrack.subscribe((track) => {
|
||||
track.onReceiveRtp.subscribe((rtp) => {
|
||||
if (this.closed || rtp.header.payloadType !== WEBRTC_OPUS_PAYLOAD_TYPE) return;
|
||||
this.onVoiceFrame(Buffer.from(rtp.payload));
|
||||
});
|
||||
void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not attach WebRTC output track");
|
||||
});
|
||||
});
|
||||
void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not prepare WebRTC output track");
|
||||
});
|
||||
|
||||
try {
|
||||
this.encoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
|
||||
} catch (error: unknown) {
|
||||
this.encoder = null;
|
||||
this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer encoder");
|
||||
}
|
||||
if (!this.encoder) {
|
||||
this.outgoingTrack.stop();
|
||||
throw new Error("WebRTC mixer encoder is unavailable");
|
||||
}
|
||||
|
||||
this.audioTimer = setInterval(() => this.flushAudio(), AUDIO_CLOCK_INTERVAL_MS);
|
||||
this.audioTimer.unref?.();
|
||||
this.activityTimer = setInterval(() => this.flushSpeakerActivity(), SPEAKER_ACTIVITY_INTERVAL_MS);
|
||||
this.activityTimer.unref?.();
|
||||
this.peer.onconnectionstatechange = () => {
|
||||
this.logger.info({ state: this.peer.connectionState }, "WebRTC connection state changed");
|
||||
};
|
||||
}
|
||||
|
||||
async createAnswer(offer: WebRtcSessionDescription): Promise<WebRtcSessionDescription> {
|
||||
if (this.closed) throw new Error("WebRTC session is closed");
|
||||
await this.peer.setRemoteDescription(offer);
|
||||
const transceiver = this.peer.getTransceivers().find((candidate) => candidate.kind === "audio");
|
||||
if (transceiver) await transceiver.sender.replaceTrack(this.outgoingTrack);
|
||||
const answer = await this.peer.createAnswer();
|
||||
await this.peer.setLocalDescription(answer);
|
||||
const description = this.peer.localDescription;
|
||||
if (!description) throw new Error("WebRTC answer was not created");
|
||||
if (description.type !== "answer" && description.type !== "offer") throw new Error("Unexpected WebRTC answer type");
|
||||
return { type: description.type, sdp: description.sdp };
|
||||
}
|
||||
|
||||
pushTeamSpeakVoice(data: TSVoiceData): void {
|
||||
if (this.closed || data.codec !== 4) return;
|
||||
this.activeSpeakerIds.add(data.clientId);
|
||||
let decoder = this.decoderByClient.get(data.clientId);
|
||||
if (!decoder) {
|
||||
try {
|
||||
decoder = new OpusDecoder(AUDIO_SAMPLE_RATE, 1);
|
||||
this.decoderByClient.set(data.clientId, decoder);
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer decoder");
|
||||
return;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const pcm = decoder.decode(data.data);
|
||||
if (pcm.length >= AUDIO_FRAME_BYTES) this.pendingFrames.set(data.clientId, pcm.subarray(0, AUDIO_FRAME_BYTES));
|
||||
} catch {
|
||||
// A malformed or codec-transition packet is discarded without touching
|
||||
// the peer connection. The next valid Opus frame can recover the stream.
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
clearInterval(this.audioTimer);
|
||||
clearInterval(this.activityTimer);
|
||||
this.pendingFrames.clear();
|
||||
this.activeSpeakerIds.clear();
|
||||
this.decoderByClient.clear();
|
||||
this.encoder = null;
|
||||
this.outgoingTrack.stop();
|
||||
await this.peer.close();
|
||||
}
|
||||
|
||||
private flushAudio(): void {
|
||||
if (this.closed || !this.encoder || !this.pendingFrames.size) return;
|
||||
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES);
|
||||
let sourceCount = 0;
|
||||
for (const pcm of this.pendingFrames.values()) {
|
||||
sourceCount++;
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) mixed[index] += pcm.readInt16LE(index * 2);
|
||||
}
|
||||
this.pendingFrames.clear();
|
||||
if (!sourceCount) return;
|
||||
|
||||
const pcm = Buffer.allocUnsafe(AUDIO_FRAME_BYTES);
|
||||
const scale = 1 / Math.sqrt(sourceCount);
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
|
||||
const sample = Math.max(-32_768, Math.min(32_767, Math.round(mixed[index]! * scale)));
|
||||
pcm.writeInt16LE(sample, index * 2);
|
||||
}
|
||||
try {
|
||||
const encoded = this.encoder.encode(pcm);
|
||||
const packet = new RtpPacket(new RtpHeader({
|
||||
payloadType: WEBRTC_OPUS_PAYLOAD_TYPE,
|
||||
sequenceNumber: this.sequenceNumber,
|
||||
timestamp: this.timestamp,
|
||||
ssrc: this.ssrc,
|
||||
marker: true,
|
||||
}), encoded);
|
||||
this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff;
|
||||
this.timestamp = (this.timestamp + AUDIO_FRAME_SAMPLES) >>> 0;
|
||||
this.outgoingTrack.writeRtp(packet);
|
||||
} 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 flushSpeakerActivity(): void {
|
||||
if (this.closed || !this.activeSpeakerIds.size) return;
|
||||
const ids = [...this.activeSpeakerIds];
|
||||
this.activeSpeakerIds.clear();
|
||||
this.onVoiceActivity(ids);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user