Files
WebSpeak-client-for-TeamSpeak/src/server/downlink-batcher.ts
T
LabKit de16417474 feat(voice): harden tunnel fallback and add tuning controls
Add v3 batched downlink with tick-aligned timestamps, audio-clock playback and PLC; add adaptive Opus/PCM uplink and one-shot TURN relay retry. Expose frame size, automatic relay retry and Cloudflare ingress assumptions in the admin console, with persistence, i18n, docs and regression tests.
2026-12-03 02:40:19 +08:00

219 lines
7.5 KiB
TypeScript

import { performance } from "node:perf_hooks";
import {
encodeVoiceBatch,
VOICE_BATCH_MAX_BYTES,
VOICE_BATCH_MAX_ENTRIES,
VOICE_MAX_OPUS_FRAME_BYTES,
type VoiceBatchEntry,
} from "../shared/voice-audio.js";
import { subscribeDownlink } from "./downlink-scheduler.js";
/**
* Coalesces TeamSpeak downlink packets into one binary message per audio tick.
*
* The compatibility path used to send one small WebSocket message per speaker
* per 20 ms. Through Cloudflare Tunnel that becomes a burst of tiny messages
* sharing one TCP connection; batching cuts the message count by the number of
* active speakers and gives the browser an explicit audio clock to schedule on.
*/
export interface DownlinkBatcherOptions {
frameMs?: 20 | 40;
maxEntries?: number;
maxBytes?: number;
maxQueueMs?: number;
maxQueueEntries?: number;
now?: () => number;
send: (packet: Uint8Array, entries: number, sentAt: number) => void;
subscribe?: (intervalMs: number, subscriber: (tickAt: number) => void) => () => void;
onStats?: (stats: DownlinkBatchStats) => void;
}
export interface DownlinkBatchStats {
messages: number;
entries: number;
maxEntries: number;
droppedFrames: number;
peakQueuedFrames: number;
peakQueuedMs: number;
lateTicks: number;
}
interface QueuedFrame extends VoiceBatchEntry {
enqueuedAt: number;
}
const LATE_TICK_MS = 100;
export class DownlinkBatcher {
private frameMs: number;
private readonly maxEntries: number;
private readonly maxBytes: number;
private readonly maxQueueMs: number;
private readonly maxQueueEntries: number;
private readonly now: () => number;
private readonly send: DownlinkBatcherOptions["send"];
private readonly subscribe: NonNullable<DownlinkBatcherOptions["subscribe"]>;
private readonly onStats: DownlinkBatcherOptions["onStats"];
private readonly queue: QueuedFrame[] = [];
private readonly seqByClient = new Map<number, number>();
private unsubscribe: (() => void) | null = null;
private origin: number;
private closed = false;
private messages = 0;
private entries = 0;
private maxEntriesSeen = 0;
private droppedFrames = 0;
private peakQueuedFrames = 0;
private peakQueuedMs = 0;
private lateTicks = 0;
constructor(options: DownlinkBatcherOptions) {
this.frameMs = options.frameMs === 40 ? 40 : 20;
this.maxEntries = Math.max(1, Math.min(VOICE_BATCH_MAX_ENTRIES, options.maxEntries ?? 32));
this.maxBytes = Math.max(1, Math.min(VOICE_BATCH_MAX_BYTES, options.maxBytes ?? VOICE_BATCH_MAX_BYTES));
this.maxQueueMs = Math.max(this.frameMs, options.maxQueueMs ?? 100);
this.maxQueueEntries = Math.max(1, options.maxQueueEntries ?? 64);
this.now = options.now ?? (() => performance.now());
this.origin = this.now();
this.send = options.send;
this.subscribe = options.subscribe ?? subscribeDownlink;
this.onStats = options.onStats;
this.arm();
}
/** Returns false for a frame the encoder could not represent. */
push(codec: number, clientId: number, data: Uint8Array): boolean {
if (this.closed || data.length < 1 || data.length > VOICE_MAX_OPUS_FRAME_BYTES
|| !Number.isInteger(codec) || codec < 0 || codec > 255
|| !Number.isInteger(clientId) || clientId < 1 || clientId > 65_535) return false;
const now = this.now();
this.dropStale(now);
while (this.queue.length >= this.maxQueueEntries) {
this.queue.shift();
this.droppedFrames++;
}
const seq = ((this.seqByClient.get(clientId) ?? 0) + 1) & 0xff;
this.seqByClient.set(clientId, seq);
// TeamSpeak's SDK may reuse its packet buffer; the queue can live for one
// tick, so copy now rather than risk sending the next speaker's payload.
this.queue.push({ codec, clientId, seq, data: Buffer.from(data), enqueuedAt: now });
this.peakQueuedFrames = Math.max(this.peakQueuedFrames, this.queue.length);
this.peakQueuedMs = Math.max(this.peakQueuedMs, this.oldestAge(now));
this.emitStats();
return true;
}
setFrameMs(frameMs: 20 | 40): void {
if (this.frameMs === frameMs || this.closed) return;
// Drain under the old cadence before changing the clock bucket size.
this.flush(this.now());
this.frameMs = frameMs;
this.origin = this.now();
this.unsubscribe?.();
this.unsubscribe = null;
this.arm();
}
/** Scheduler entry point; also used directly by tests with a synthetic tick. */
flush(tickAt = this.now()): void {
if (this.closed) return;
const now = this.now();
if (now - tickAt > LATE_TICK_MS) this.lateTicks++;
this.dropStale(now);
if (!this.queue.length) {
this.emitStats();
return;
}
const sendGroup = (group: QueuedFrame[], bucket: number) => {
const stamp = Math.max(0, this.origin + bucket * this.frameMs);
let batch: QueuedFrame[] = [];
let batchBytes = 6;
const flushBatch = () => {
if (!batch.length) return;
const encoded = encodeVoiceBatch(stamp, batch);
if (encoded) {
this.messages++;
this.entries += batch.length;
this.maxEntriesSeen = Math.max(this.maxEntriesSeen, batch.length);
try { this.send(encoded, batch.length, stamp); } catch { this.droppedFrames += batch.length; }
} else {
// Should be unreachable because push() bounds each frame and flush()
// splits on the same limits; keep the queue honest if it happens.
this.droppedFrames += batch.length;
}
batch = [];
batchBytes = 6;
};
for (const frame of group) {
const frameBytes = 6 + frame.data.length;
if (batch.length && (batch.length >= this.maxEntries || batchBytes + frameBytes > this.maxBytes)) flushBatch();
batch.push(frame);
batchBytes += frameBytes;
if (batch.length >= this.maxEntries || batchBytes >= this.maxBytes) flushBatch();
}
flushBatch();
};
// A late timer can hold several ticks of frames. Keep each tick as its own
// batch with its own audio timestamp: coalescing the whole backlog into one
// stamp would hide the stall from the jitter estimator and stack every
// speaker on the same playback instant.
let group: QueuedFrame[] = [];
let bucket = -1;
for (const frame of this.queue) {
const frameBucket = Math.floor((frame.enqueuedAt - this.origin) / this.frameMs);
if (group.length && frameBucket !== bucket) {
sendGroup(group, bucket);
group = [];
}
bucket = frameBucket;
group.push(frame);
}
if (group.length) sendGroup(group, bucket);
this.queue.length = 0;
this.emitStats();
}
getStats(): DownlinkBatchStats {
return {
messages: this.messages,
entries: this.entries,
maxEntries: this.maxEntriesSeen,
droppedFrames: this.droppedFrames,
peakQueuedFrames: this.peakQueuedFrames,
peakQueuedMs: this.peakQueuedMs,
lateTicks: this.lateTicks,
};
}
close(): void {
if (this.closed) return;
this.closed = true;
this.unsubscribe?.();
this.unsubscribe = null;
this.queue.length = 0;
this.emitStats();
}
private arm(): void {
this.unsubscribe = this.subscribe(this.frameMs, tickAt => this.flush(tickAt));
}
private dropStale(now: number): void {
while (this.queue.length && now - this.queue[0]!.enqueuedAt > this.maxQueueMs) {
this.queue.shift();
this.droppedFrames++;
}
}
private oldestAge(now: number): number {
return this.queue.length ? Math.max(0, now - this.queue[0]!.enqueuedAt) : 0;
}
private emitStats(): void {
this.onStats?.(this.getStats());
}
}