Files
WebSpeak-client-for-TeamSpeak/src/server/downlink-scheduler.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

64 lines
2.1 KiB
TypeScript

import { performance } from "node:perf_hooks";
/**
* One timer per cadence, shared by every downlink batcher. A per-session timer
* would mean 50 timers/s per compatibility session (100 sessions -> 5k/s),
* which is measurable event-loop churn for no benefit. The scheduler passes
* the planned tick time only so a batcher can detect a late turn; batch
* timestamps are derived from the batcher's tick buckets.
*/
type Subscriber = (tickAt: number) => void;
interface Slot {
timer: ReturnType<typeof setInterval>;
nextAt: number;
subscribers: Set<Subscriber>;
}
const slots = new Map<number, Slot>();
const LATE_RESET_MS = 100;
export function subscribeDownlink(intervalMs: number, subscriber: Subscriber): () => void {
const interval = Math.max(10, Math.min(60, Math.round(intervalMs)));
let slot = slots.get(interval);
if (!slot) {
slot = {
nextAt: performance.now() + interval,
subscribers: new Set(),
timer: setInterval(() => runSlot(interval, slot!), interval),
};
// Idle voice sessions must not keep the process alive.
(slot.timer as unknown as { unref?: () => void }).unref?.();
slots.set(interval, slot);
}
slot.subscribers.add(subscriber);
return () => {
const current = slots.get(interval);
if (!current) return;
current.subscribers.delete(subscriber);
if (!current.subscribers.size) {
clearInterval(current.timer);
slots.delete(interval);
}
};
}
function runSlot(interval: number, slot: Slot): void {
const now = performance.now();
if (now - slot.nextAt > LATE_RESET_MS) slot.nextAt = now;
const tickAt = slot.nextAt;
slot.nextAt = tickAt + interval;
// Copy so a subscriber that unsubscribes during its callback cannot skip
// another subscriber in the same tick.
for (const subscriber of [...slot.subscribers]) {
try { subscriber(tickAt); } catch { /* one session must not stop the shared timer */ }
}
}
/** Test hook: drop every slot without waiting for an interval to fire. */
export function resetDownlinkSchedulerForTests(): void {
for (const slot of slots.values()) clearInterval(slot.timer);
slots.clear();
}