From de16417474648cd58524728daf1235c21de19cf6 Mon Sep 17 00:00:00 2001 From: LabKit Date: Thu, 3 Dec 2026 02:40:19 +0800 Subject: [PATCH] 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. --- deploy/coturn/README.md | 22 +- docs/CLOUDFLARE_TUNNEL_VOICE.md | 85 ++++-- docs/README.en.md | 2 +- docs/README.zh-CN.md | 2 +- docs/VOICE_FIX_REPORT.md | 56 ++-- package.json | 2 +- src/admin/admin-router.ts | 3 + src/admin/admin-service.ts | 27 ++ src/persistence/database.test.ts | 6 +- src/persistence/database.ts | 12 +- src/server/audio-stats.ts | 12 + src/server/downlink-batcher.test.ts | 84 ++++++ src/server/downlink-batcher.ts | 218 +++++++++++++++ src/server/downlink-scheduler.ts | 63 +++++ src/server/session-audio.test.ts | 42 +++ src/server/session-audio.ts | 107 ++++++-- src/server/voice-bridge.integration.test.ts | 62 +++++ src/server/voice-bridge.ts | 28 +- src/server/voice-ice-config.test.ts | 9 +- src/server/voice-ice-config.ts | 27 +- src/shared/admin-inputs.ts | 3 + src/shared/admin-responses.ts | 5 +- src/shared/client-commands.test.ts | 1 + src/shared/client-commands.ts | 13 +- src/shared/server-messages.test.ts | 1 + src/shared/server-messages.ts | 11 +- src/shared/voice-audio.test.ts | 39 +++ src/shared/voice-audio.ts | 86 ++++++ .../components/admin/AdminServerSettings.vue | 21 ++ web/src/composables/useAdminI18n.ts | 2 + web/src/composables/useAdminServerSettings.ts | 7 +- web/src/composables/useVoiceWebSocket.ts | 135 +++++++++- web/src/composables/useWebClientI18n.ts | 6 + web/src/i18n/admin.ts | 65 ++++- web/src/voice/audio-diagnostics.ts | 9 +- web/src/voice/jitter-buffer.ts | 118 ++++++-- web/src/voice/opus-uplink.ts | 4 +- web/src/voice/plc.ts | 17 ++ web/src/voice/remote-playback.ts | 252 ++++++++++++++---- web/src/voice/webrtc-transport.ts | 28 +- web/test/admin-api.integration.test.ts | 11 +- web/test/jitter-buffer.test.ts | 16 +- web/test/remote-playback.test.ts | 41 ++- web/test/voice-session.test.mjs | 37 ++- 44 files changed, 1605 insertions(+), 192 deletions(-) create mode 100644 src/server/downlink-batcher.test.ts create mode 100644 src/server/downlink-batcher.ts create mode 100644 src/server/downlink-scheduler.ts create mode 100644 src/shared/voice-audio.test.ts create mode 100644 web/src/voice/plc.ts diff --git a/deploy/coturn/README.md b/deploy/coturn/README.md index 163a9d1..f345902 100644 --- a/deploy/coturn/README.md +++ b/deploy/coturn/README.md @@ -47,13 +47,30 @@ WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all WEBSPEAK_VOICE_PROFILE=auto ``` -TURN does not require Opus; `WEBSPEAK_VOICE_OPUS_WS` remains off by default. +TURN does not require Opus. Compatibility Opus defaults to auto (adaptive +browsers use WebCodecs when available and fall back to PCM); set +`WEBSPEAK_VOICE_OPUS_WS=0` to force PCM. `WEBSPEAK_TURN_REST_URLS` accepts only `turn:`/`turns:` URL tokens. For static ICE credentials, use `WEBSPEAK_VOICE_ICE_SERVERS` with a JSON array of ICE server objects instead. WebSpeak generates short-lived `username`/`credential` pairs with HMAC-SHA1, compatible with coturn's `use-auth-secret`. +### Using a bare public IP + +If the web domain only resolves to Cloudflare Tunnel, keep TURN on the public +IP rather than on that domain: + +```bash +WEBSPEAK_TURN_REST_URLS='turn:203.0.113.10:3478?transport=udp,turn:203.0.113.10:3478?transport=tcp' +``` + +`turn:` is cleartext TURN and needs no DNS name or certificate. If TCP/3478 is +blocked, change coturn's `--listening-port` to `443` (and allow TCP/443), then +use `turn:203.0.113.10:443?transport=tcp`. Only `turns:` requires a +certificate. The web page can still be served as HTTPS/WSS by Cloudflare +Tunnel; media does not use that hostname. + ## 4. Verify From a network that blocks direct UDP, open the voice page and check: @@ -80,3 +97,6 @@ adaptive jitter buffer. - This template has not been exercised end-to-end with a live Tunnel and browser deployment; validate TURN reachability and credentials in the target network before relying on it. +- Using a bare IP for media does not by itself determine whether a public + service needs ICP filing or another permit; confirm the applicable + requirements for the host's jurisdiction and use. diff --git a/docs/CLOUDFLARE_TUNNEL_VOICE.md b/docs/CLOUDFLARE_TUNNEL_VOICE.md index 349837a..3e1bce4 100644 --- a/docs/CLOUDFLARE_TUNNEL_VOICE.md +++ b/docs/CLOUDFLARE_TUNNEL_VOICE.md @@ -4,14 +4,18 @@ 核心原则: - **WebRTC 优先直连**:浏览器直接向网关公网 IP 的 `40000–40099/UDP` 发包。 + 网页域名只解析到 Cloudflare,供 Tunnel 的 HTTPS/WSS 使用;媒体地址填公网 IP。 - **Tunnel 只承载 HTTPS/WSS**:Cloudflare Tunnel 不转发 UDP,不能把 Cloudflare 代理域名当作 ICE 媒体地址。 - **TURN 只做后备**:手机流量、公司网络或 UDP 被拦时,才让媒体走 - `turn:`/`turns:`,不默认全程 `relay`。 + `turn:`/`turns:`,不默认全程 `relay`。`turn:` 不需要域名或证书,可以继续用 + 同一个公网 IP。 - **CFT 是增量路径**:默认 `WEBSPEAK_VOICE_PROFILE=auto`,非可信 Cloudflare 请求继续使用原有的 80ms 固定窗口、裸 1920 字节 PCM 和旧混音参数;只有 经过可信 Cloudflare 代理的请求(或显式 `adaptive`)才启用自适应 buffer / pacer / 修正后的 RTP marker。不配置 CFT、TURN 或新变量时,直连部署保持原行为。 +- **兼容模式是兜底而非二等路径**:v3 批量下行、音频时钟、p95 抖动、丢包隐藏 + 和 Opus 默认协商都只对 `adaptive` 生效;完全不能 UDP 的客户端仍能通话。 ## 兼容性矩阵 @@ -35,12 +39,17 @@ UDP 端口仍按原配置工作。 - **语音模式**:`自动`(推荐,直连走 `legacy`、可信 Cloudflare 代理走 `adaptive`)、`兼容模式`、`自适应`。 -- **兼容模式 Opus**:仅 `adaptive` 生效,默认关闭;浏览器不支持时自动回退 - PCM。 +- **兼容模式 Opus**:默认开启(auto)。仅 `adaptive` 生效;浏览器没有 + WebCodecs `AudioEncoder` 或编码器初始化失败时自动回退 PCM,不会因为开关 + 打开就发不出声音。 - **自适应 jitter 上限**:80–500 ms,配置自适应缓冲目标的上限;它不是严格的 播放前瞻上限,调低也不会恢复旧版超限 `clear()` 行为。 +- **兼容模式调优**:兼容模式帧长 `20/40 ms`、直连失败后自动 TURN 重试、 + 入口强制按 Cloudflare 处理。默认 `20 ms`、自动重试开启、强制识别关闭。 - **TURN 后备**:TURN REST URL、共享密钥和凭证有效期。TURN 只在直连 UDP - 失败后使用,不作为默认路径。 + 失败后使用,不作为默认路径。直连失败且存在 TURN 时,浏览器会自动做一次 + relay-only 重试(约 3 秒后),兼容音频在此期间继续播放;自动重试可在 + “兼容模式调优”里关闭。 保存后对**新的语音连接**生效,不需要重启网关。配置持久化在数据库中:控制台 非空值覆盖对应环境变量,未配置的字段继续继承环境变量;清空 TURN URL 或在 @@ -65,6 +74,27 @@ Cloudflare 判定只接受来自 `WEBSPEAK_TRUSTED_PROXIES` 中直接相邻代 4. `webrtc_public_host` 为空时,直连部署仍可按请求入口推断;但通过 Cloudflare 的请求不会再拿 CF 边缘 `Host` 当 ICE 地址,避免“看起来 配置好了、实际没有媒体路径”。Cloudflare 场景请显式填写公网媒体地址。 +5. “服务器 → 语音”里的 **WebRTC** 总开关必须打开;只填公网媒体地址但关闭 + WebRTC 时,`connected` 仍会报告 `webrtcAvailable=false`。 + +### 1.3 只有公网 IP、域名不落地 ICP 的部署 + +这是本项目推荐的 CFT 组合,也是“有公网 IP + 域名但不想把域名备案到境内源站” +时最省事的做法: + +- 域名只添加 Cloudflare DNS 记录,由 Cloudflare Tunnel 回源到本机的 + HTTPS/WSS 端口;源站不直接监听域名,也不使用该域名做媒体地址。 +- WebRTC 媒体使用 `<公网IP>:40000–40099/UDP`。浏览器拿到的是 IP 候选, + 不依赖域名解析、证书或 CDN 回源。 +- TURN 可以继续用同一个公网 IP:`turn:<公网IP>:3478?transport=udp` 和 + `?transport=tcp` 都是明文 TURN,不需要域名或证书;只有 `turns:` 才需要 + 证书。需要 443/TCP 时,把 coturn 的 `listening-port` 改成 443 并放行 TCP, + URL 写 `turn:<公网IP>:443?transport=tcp`。 +- Cloudflare Realtime TURN 只作为“UDP 全封”的最后兜底;它本身经过跨境网络, + 大陆用户的实际质量需要实测,不能替代同机 coturn。 + +媒体链路不使用域名,不等于对 ICP、许可或其他落地要求作出判断;这些要求由 +部署方根据所在地区、用途和实际接入方式自行确认。本文只描述技术链路。 ## 2. 服务端环境变量 @@ -81,8 +111,11 @@ CFT/TURN 调整建议直接用控制台,避免同时维护两套配置。 | `WEBSPEAK_TURN_REST_URLS` | 空 | coturn REST 的 `turn:`/`turns:` URL,逗号分隔;最多 8 个。 | | `WEBSPEAK_TURN_REST_SECRET` | 空 | 与 coturn `static-auth-secret` 相同的密钥,至少 16 字符才启用。 | | `WEBSPEAK_TURN_REST_TTL_SECONDS` | `21600` | TURN 临时凭证有效期,范围 300–86400。 | -| `WEBSPEAK_VOICE_OPUS_WS` | `0` | 兼容模式是否允许浏览器用 WebCodecs 发 Opus;仅 `adaptive` 且环境变量或控制台显式启用时生效,不支持时自动回退 PCM。 | +| `WEBSPEAK_VOICE_OPUS_WS` | `1` | 兼容模式是否允许浏览器用 WebCodecs 发 Opus;仅 `adaptive` 生效,默认 auto:浏览器不支持时自动回退 PCM。设为 `0` 可强制 PCM。 | | `WEBSPEAK_VOICE_JITTER_MAX_MS` | `300` | 自适应 jitter buffer 的上限,范围 80–500;仅 `adaptive` 生效。 | +| `WEBSPEAK_VOICE_FRAME_MS` | `20` | 兼容模式帧长 `20` 或 `40`。40 ms 会把下行批量消息再减半,客户端上行 PCM 也按 40 ms 打包并由服务端拆回 20 ms;每个说话人最多多出 20 ms 等待。控制台“兼容模式调优”里的对应设置优先。 | +| `WEBSPEAK_VOICE_AUTO_RELAY_RETRY` | `1` | 设为 `0` 关闭首次直连失败后的自动 relay-only 重试;控制台开关优先。 | +| `WEBSPEAK_ASSUME_CLOUDFLARE` | 空 | 设为 `1` 时把语音入口一律按 Cloudflare 处理,适用于反向代理清掉了 `cf-ray` 等头但实际仍走 CFT 的部署;控制台开关优先。 | 示例(直连优先 + TURN 后备): @@ -120,14 +153,23 @@ TLS 控制连接。因此 `turns:` 在 `iceUseTcp: false` 下仍可用。该结 自适应分支: -- jitter buffer:目标超前量按到达 jitter 估算,初始 80ms,上限默认 - 300ms;溢出时只重排播放头、保留 `AudioDecoder`,不再每次超过 80ms - 就销毁解码器。 -- 解码队列硬上限 12;只有极深积压才丢最新帧。 -- 上行 20ms pacer;新帧格式 `0x01 + PCM` 和 `0x02 + Opus`,旧 1920 字节 - PCM 仍兼容。 -- 仅当 `adaptive` 且环境变量或控制台显式启用 Opus,同时浏览器支持 - WebCodecs 时才发 Opus,否则自动回退 PCM。 +- **v3 批量下行**:服务端按 20/40 ms tick 把同一时刻多个说话人的包合并成一条 + 二进制消息(`0xF3` 头 + 音频时钟 + 每发言人 entry),消息数从“每包一条”降 + 到“每 tick 一条”;旧前端不发 `audioCaps` 时自动保持 v2 逐包格式。 +- **音频时钟调度**:播放器用批次里的 `audioStartMs` 作为锚点,而不是每个包 + 各自用 `currentTime` 重排;隧道一次突发到达多包时,后续包仍落在连续时间线上。 +- **p95 抖动目标**:2 秒 / 100 样本窗口的 95 分位,目标 `60 + p95`,下限 + 80 ms、上限由 `audioJitterMaxMs` 控制;快升(每次最多 +40 ms)、慢降 + (每 2 秒 -2 ms),避免平均值把突发尾部吃掉后又反复欠载。 +- **丢包隐藏 / 跳帧**:seq 连续缺 1–8 帧时用上一帧做线性衰减隐藏(PLC),最多 + 3 帧;领先目标 60 ms 以上跳 1 帧,领先 300 ms 以上重锚;静音超过 200 ms + 只重置抖动窗口,播放头仍由音频时钟决定,时钟跳变时再重锚。 +- 解码队列硬上限 12;只有极深积压才丢最新帧,不再因为 80 ms 窗口反复销毁 + 解码器。 +- 上行 20 ms pacer;新帧格式 `0x01 + PCM` 和 `0x02 + Opus`,旧 1920 字节 + PCM 仍兼容;服务端也接受 40 ms(3840 字节)PCM 并拆成两个 20 ms 帧。 +- Opus 默认协商,24 kbps、`packetlossperc=10`、`useinbandfec=true`;浏览器 + 没有 WebCodecs 或初始化失败时回退 PCM。 legacy 分支: @@ -159,12 +201,20 @@ legacy 分支: 1. 同一网络下先用直连 UDP:`chrome://webrtc-internals` 选中 pair 应为 `host`/`srflx`,不是 `relay`。 2. 手机 4G/5G 或关 UDP 的 Wi-Fi 再测:没有直连时才会出现 `relay`,且 - 音频可通。 + 音频可通。第一次直连失败后,页面会出现“正在通过 TURN 中继重试”,兼容 + 音频不应中断;relay 成功后横幅消失。 3. 对未下发 WebRTC 的路径(关闭 WebRTC、无媒体路径或浏览器不支持)测 - 2–3 分钟兼容模式。确认连接 - `connected` 消息中的 `voiceProfile` 为 `adaptive` 后,`bufferResets` + 2–3 分钟兼容模式。确认连接 `connected` 消息中的 `voiceProfile` 为 + `adaptive`,且 `audioDownlinkVersions` 包含 `3`;浏览器应在发 + `audioCaps` 后收到 `audioConfig.downlinkVersion=3`。`bufferResets` 不应持续增长、没有解码器反复重建;若为 `legacy`,看到旧 80ms 行为是 预期的。 +4. 兼容模式统计里 `downlinkBatchMessages` 应明显小于 + `downlinkBatchEntries`(多人同时说话时约等于“tick 数”而不是“包数”); + `skippedFrames`/`concealedFrames` 偶发增长正常,持续快速增长才说明目标 + 缓冲或网络异常。 +5. 关闭 CFT 或直连部署时,确认 `voiceProfile=legacy`、没有 + `audioDownlinkVersions`,旧客户端行为不变。 **回滚** @@ -173,6 +223,9 @@ legacy 分支: 80ms/`clear()`、裸 PCM、旧 WebRTC mixer;不需要回退前端构建。 - 关闭兼容模式 Opus:在管理台取消“兼容模式使用 Opus”,或设置 `WEBSPEAK_VOICE_OPUS_WS=0`;注意只有 `adaptive` 会下发 Opus 能力。 +- 回退 v3 批量下行:设置 `WEBSPEAK_VOICE_FRAME_MS=20` 只影响 tick,不会回退 + 协议;要强制旧格式,可让前端不发送 `audioCaps`(回退前端构建),或临时在 + 服务端禁用 v3 协商。回滚到 0.3.3 前端时,新服务端会自动走 v2。 - 限制 jitter 缓冲:管理台把“自适应 jitter 上限”调到 80,或设置 `WEBSPEAK_VOICE_JITTER_MAX_MS=80`;这只是把上限压回 80ms,**不会恢复 旧版“超过 80ms 就 `clear()` 解码器”的行为**。要完全回到旧行为,使用 diff --git a/docs/README.en.md b/docs/README.en.md index a1a342f..333cd1c 100644 --- a/docs/README.en.md +++ b/docs/README.en.md @@ -199,7 +199,7 @@ The WebRTC advanced settings now include a **public media address**, **IPv6 cand Set a UDP STUN URL such as `stun:turn.teamspeak.com:3478` to use the same discovery service in the browser and gateway. Empty preserves the previous behavior: the gateway library uses its built-in STUN service while the browser has none. The gateway requires an IPv4-reachable UDP STUN hostname or IPv4 address; IPv6 literals and TURN credentials are not accepted. IPv6 media candidates work independently of STUN. Save and reconnect to apply changes. -HTTP/WebSocket reachability does not imply media reachability. Allow the complete configured UDP range and preserve port numbers when using static port forwarding. STUN discovers mappings but cannot relay audio or traverse every NAT. For mobile or UDP-blocked clients, configure an external TURN service as an optional fallback directly under Admin → Voice with the TURN REST URL, shared secret, and credential lifetime; the equivalent environment variables are `WEBSPEAK_TURN_REST_URLS` and `WEBSPEAK_TURN_REST_SECRET`. Console values take precedence and apply to new connections without a gateway restart. Keep `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all` so direct UDP is tried first. `WEBSPEAK_VOICE_PROFILE` defaults to `auto`: only requests received through a trusted Cloudflare proxy use the adaptive buffer; direct and other requests keep the legacy 80 ms/raw-PCM path. Loopback tunnel connections are trusted by default; configure `WEBSPEAK_TRUSTED_PROXIES` when cloudflared connects from another address. Set `adaptive` explicitly to use it on direct deployments too; Admin → Voice can override this mode. Opus over WebSocket is off by default; enable it under Admin → Voice or with `WEBSPEAK_VOICE_OPUS_WS=1`, and use the `adaptive` profile. If neither direct UDP nor TURN provides a media path, the session reports `NO_MEDIA_PATH` and uses the compatibility transport. +HTTP/WebSocket reachability does not imply media reachability. Allow the complete configured UDP range and preserve port numbers when using static port forwarding. STUN discovers mappings but cannot relay audio or traverse every NAT. For mobile or UDP-blocked clients, configure an external TURN service as an optional fallback directly under Admin → Voice with the TURN REST URL, shared secret, and credential lifetime; the equivalent environment variables are `WEBSPEAK_TURN_REST_URLS` and `WEBSPEAK_TURN_REST_SECRET`. Console values take precedence and apply to new connections without a gateway restart. Keep `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all` so direct UDP is tried first. `WEBSPEAK_VOICE_PROFILE` defaults to `auto`: only requests received through a trusted Cloudflare proxy use the adaptive buffer; direct and other requests keep the legacy 80 ms/raw-PCM path. Loopback tunnel connections are trusted by default; configure `WEBSPEAK_TRUSTED_PROXIES` when cloudflared connects from another address. Set `adaptive` explicitly to use it on direct deployments too; Admin → Voice can override this mode. Compatibility Opus defaults to auto: adaptive browsers with WebCodecs use 24 kbps Opus + FEC and fall back to PCM otherwise; set `WEBSPEAK_VOICE_OPUS_WS=0` or disable it under Admin → Voice to force PCM. Adaptive compatibility mode also uses v3 batched downlink (negotiated by `audioCaps`, one message per 20/40 ms tick), an audio-clock anchor, a p95 jitter target, PLC concealment, and one automatic relay retry. If neither direct UDP nor TURN provides a media path, the session reports `NO_MEDIA_PATH` and uses the compatibility transport. See [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md) for the direct-UDP-first topology, coturn/cloudflared templates, verification and rollback notes. diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.md index 9bd8f5c..de3aaae 100644 --- a/docs/README.zh-CN.md +++ b/docs/README.zh-CN.md @@ -220,7 +220,7 @@ WebRTC 启用后端口范围会锁定。要修改端口,先关闭 WebRTC 并 保存后重新连接。网页和 WebSocket 经反代可达,不代表媒体 UDP 可达;STUN 仅发现地址,不中继音频,也不保证穿透所有 NAT。应开放配置的整个 UDP 端口范围;静态端口转发需保持相同端口映射。 -手机流量或 UDP 被拦时,可配置外部 TURN 作为可选后备:在管理台“服务器 → 语音”填写 TURN REST URL、共享密钥和有效期,或使用 `WEBSPEAK_TURN_REST_URLS`、`WEBSPEAK_TURN_REST_SECRET` 环境变量。控制台保存的配置优先,且不需要重启网关,对新连接生效。默认保持 `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all`,先试直连;只有确认 UDP 完全不可用时才用 `relay`。`WEBSPEAK_VOICE_PROFILE` 默认 `auto`:只有经过可信 Cloudflare 代理的请求才启用自适应 buffer,直连及其他请求继续使用旧 80ms/裸 PCM 行为;本机 Tunnel 连接默认可信,cloudflared 从其他地址连接时需配置 `WEBSPEAK_TRUSTED_PROXIES`。需要直连也启用时显式设 `adaptive`,也可在控制台“语音模式”覆盖。WebSocket Opus 默认关闭,可在“服务器 → 语音”或通过 `WEBSPEAK_VOICE_OPUS_WS=1` 启用,并需使用 `adaptive`。直连 UDP 与 TURN 都无法提供媒体路径时,会话报告 `NO_MEDIA_PATH` 并使用兼容传输。完整部署、验收和回滚见 [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md),模板见 `deploy/coturn/` 和 `deploy/cloudflared/`。 +手机流量或 UDP 被拦时,可配置外部 TURN 作为可选后备:在管理台“服务器 → 语音”填写 TURN REST URL、共享密钥和有效期,或使用 `WEBSPEAK_TURN_REST_URLS`、`WEBSPEAK_TURN_REST_SECRET` 环境变量。控制台保存的配置优先,且不需要重启网关,对新连接生效。默认保持 `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all`,先试直连;只有确认 UDP 完全不可用时才用 `relay`。`WEBSPEAK_VOICE_PROFILE` 默认 `auto`:只有经过可信 Cloudflare 代理的请求才启用自适应 buffer,直连及其他请求继续使用旧 80ms/裸 PCM 行为;本机 Tunnel 连接默认可信,cloudflared 从其他地址连接时需配置 `WEBSPEAK_TRUSTED_PROXIES`。需要直连也启用时显式设 `adaptive`,也可在控制台“语音模式”覆盖。兼容模式 Opus 默认 auto:`adaptive` 下浏览器支持 WebCodecs 就用 24 kbps Opus + FEC,否则自动回退 PCM;可在“服务器 → 语音”或通过 `WEBSPEAK_VOICE_OPUS_WS=0` 强制关闭。自适应兼容模式使用 v3 批量下行(`audioCaps` 协商,一个 20/40ms tick 一条消息)、音频时钟锚点、p95 抖动目标、PLC 丢包隐藏和自动 relay 重试。直连 UDP 与 TURN 都无法提供媒体路径时,会话报告 `NO_MEDIA_PATH` 并使用兼容传输。完整部署、验收和回滚见 [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md),模板见 `deploy/coturn/` 和 `deploy/cloudflared/`。 ### 屏幕共享的 ICE 候选 diff --git a/docs/VOICE_FIX_REPORT.md b/docs/VOICE_FIX_REPORT.md index fd80ba4..ed513b3 100644 --- a/docs/VOICE_FIX_REPORT.md +++ b/docs/VOICE_FIX_REPORT.md @@ -18,38 +18,58 @@ ### WebRTC、ICE 与回退 - `src/server/voice-ice-config.ts`:支持静态 ICE、TURN REST、浏览器/网关 - transport policy、语音 profile、Opus WebSocket 和 jitter 上限。 + transport policy、语音 profile、Opus WebSocket(默认 auto)和 jitter 上限。 - `src/server/turn-credentials.ts`:按 coturn `use-auth-secret` 生成短期凭证。 - `src/server/voice-bridge.ts`:仅当直接相邻代理位于 `WEBSPEAK_TRUSTED_PROXIES` 中时,才根据 `cf-ray`、`cf-connecting-ip` 或 `cdn-loop` 判定 Cloudflare。直连客户端注入这些头不会改变 profile。 + `WEBSPEAK_ASSUME_CLOUDFLARE=1` 可覆盖反向代理清掉这些头的部署。 - Cloudflare 请求不再把 Tunnel `Host` 当作 ICE 媒体地址。未配置公网媒体 - 地址且没有 TURN 时返回 `NO_MEDIA_PATH`,浏览器使用兼容传输。 + 地址且没有 TURN 时返回 `NO_MEDIA_PATH`,浏览器使用兼容传输。公网媒体 + 地址可以直接填 IP 字面量,不要求域名或证书。 - 已下发 WebRTC 后建连或传输失败会自动恢复 PCM/Opus over WebSocket 的 上下行兼容音频,页面留在当前 TeamSpeak/WebSocket 会话;上行需要已有 麦克风权限。横幅继续使用 `WEBRTC_FAILED`,并保留“重新连接 WebRTC”。 +- 第一次直连失败且配置了 TURN 时,自动做一次 relay-only 重试(约 3 秒后); + 兼容音频在重试期间继续播放。第二次失败才显示 `WEBRTC_FAILED`。 - “重新连接 WebRTC”只重试 WebRTC,不调用整段连接流程、不新建语音 - WebSocket。重连期间保持兼容收发,等 `onReady` 后才停止兼容音频并清除 - 失败横幅和按钮,避免双路音频或切换静音。 -- 重连再次失败时继续留在兼容模式保通话,横幅和按钮保留。网关未 - advertise WebRTC 的既有兼容路径不变,也不显示这块失败按钮。 + WebSocket;手动重试会恢复配置的直连优先策略并清零自动重试计数。 +- 重连期间保持兼容收发,等 `onReady` 后才停止兼容音频并清除失败横幅和 + 按钮,避免双路音频或切换静音。 - `src/server/webrtc-audio.ts` 与 `web/src/voice/webrtc-transport.ts`:浏览器 - 和网关使用完整 ICE 列表;无 TURN 的 `relay` 策略快速失败。 + 和网关使用完整 ICE 列表;relay 尝试的 ICE/answer/连接超时分别收敛为 + 4/6/10 秒,直连为 6/8/15 秒;直连收到 host/srflx/prflx 后提前 300ms + 结束收集,减少隧道下的无效等待。 - 已从 werift 源码确认 `turns:` 使用 TLS 控制连接;未做真实 coturn 端到端 联调。 ### 兼容模式音频 - `legacy` 保留旧播放窗口、解码器重建、裸 PCM、4 帧 mixer 队列和每包 - marker。 -- `adaptive` 使用 `web/src/voice/jitter-buffer.ts`、可选服务端 pacer 和可选 - Opus-over-WebSocket;Opus 默认关闭。 -- `web/src/voice/opus-uplink.ts` 使用 WebCodecs Opus;不支持或失败时回退 PCM。 + marker;只有显式 `legacy` 或非 Cloudflare 请求使用。 +- `adaptive` 使用 v3 批量下行:服务端按 20/40ms tick 把多个说话人的包合并 + 为一条二进制消息(`0xF3` 头 + `audioStartMs` + per-speaker seq),消息数 + 从“每包一条”降到“每 tick 一条”。旧前端不发 `audioCaps` 时服务端保持 + v2 逐包格式。 +- 迟到 tick 不再把整段积压压成一个时间戳:batcher 按原始 tick 分组,每组 + 单独带音频时钟,客户端才能用 p95 抖动估计发现隧道停顿。 +- `web/src/voice/jitter-buffer.ts` 使用 2 秒 / 100 样本窗口的 p95,目标 + `60 + p95`,下限 80ms、上限由 `audioJitterMaxMs` 控制;快升 +40ms/次, + 慢降 -2ms/2s。 +- `web/src/voice/remote-playback.ts` 用音频时钟做锚点,保留 `AudioDecoder`; + seq 缺口 1–8 时用 PLC 隐藏最多 3 帧,领先 60ms 跳帧,领先 300ms 重锚, + 落后 20ms 插一帧。解码队列硬上限 12,只有极深积压才丢最新帧。 +- `web/src/voice/opus-uplink.ts` 使用 WebCodecs Opus,24kbps、 + `packetlossperc=10`、`useinbandfec=true`;不支持或失败时回退 PCM。 +- 服务端接受 40ms(3840 字节)PCM,拆成两个 20ms 帧后分别 encode/pacer; + 40ms 帧消耗两个 rate token,不能借此翻倍上行速率。 - Safari/Firefox 的 Opus 行为未逐台真机验证。 ### 管理台与持久化 -- 管理台“服务器 → 语音”提供 profile、Opus、jitter 上限和 TURN REST 配置。 +- 管理台“服务器 → 语音”提供 profile、Opus、jitter 上限、TURN REST 配置, + 以及“兼容模式调优”:20/40ms 兼容模式帧长、自动 TURN 重试、强制 Cloudflare + 入口识别。 - 非空控制台值覆盖环境变量;未修改字段保持数据库 `NULL`,继续继承环境变量。 - 清空 TURN URL 或移除密钥会显式停用环境变量中的 TURN REST。 - TURN 密钥使用网关主密钥加密存储,API 只返回是否已配置。 @@ -62,8 +82,10 @@ WEBSPEAK_VOICE_PROFILE=auto WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all WEBSPEAK_VOICE_GATEWAY_ICE_TRANSPORT_POLICY=all WEBSPEAK_VOICE_JITTER_MAX_MS=300 -WEBSPEAK_VOICE_OPUS_WS=0 -WEBSPEAK_TURN_REST_URLS='turn:turn.example.com:3478?transport=udp,turn:turn.example.com:3478?transport=tcp' +WEBSPEAK_VOICE_OPUS_WS=1 +WEBSPEAK_VOICE_FRAME_MS=20 +WEBSPEAK_VOICE_AUTO_RELAY_RETRY=1 +WEBSPEAK_TURN_REST_URLS='turn:203.0.113.10:3478?transport=udp,turn:203.0.113.10:3478?transport=tcp' WEBSPEAK_TURN_REST_SECRET='' WEBSPEAK_TURN_REST_TTL_SECONDS=21600 ``` @@ -78,12 +100,16 @@ WEBSPEAK_TURN_REST_TTL_SECONDS=21600 - 0.3.3 会忽略并保留这些元数据,可以在自动更新健康检查失败后直接恢复旧代码。 - 恢复非 Cloudflare 旧音频行为:选择 `legacy`,或确保没有控制台覆盖后设置 `WEBSPEAK_VOICE_PROFILE=legacy`。 -- 关闭 Opus:取消控制台选项或设置 `WEBSPEAK_VOICE_OPUS_WS=0`。 +- 关闭兼容模式 Opus:取消控制台选项或设置 `WEBSPEAK_VOICE_OPUS_WS=0`。 +- 回退 v3 批量下行:回退前端构建,让浏览器不再发送 `audioCaps`;新服务端 + 会自动走 v2。`WEBSPEAK_VOICE_FRAME_MS=20` 只影响批量 tick,不会回退协议。 - 关闭 TURN:清空 TURN URL/移除密钥,或删除对应环境变量。 ## 验证边界 - coturn/cloudflared 模板未在真实目标网络端到端联调。 +- 公网 IP 的 `40000–40099/UDP` 入站、`443/TCP` 是否可分配给 coturn,需按 + 实际云安全组和主机防火墙验证。 - TURN 的 UDP/TCP/TLS、relay 端口和凭证一致性仍需在目标网络验证。 - Safari/Firefox WebCodecs Opus 与真实浏览器 jitter 表现仍需设备测试。 - 自动化测试和构建结果以本次审查的测试记录为准;历史报告中的通过数量 diff --git a/package.json b/package.json index 5215512..00c830c 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "scripts": { "dev": "tsx src/index.ts", "build": "tsc", - "test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/turn-credentials.test.ts src/server/voice-ice-config.test.ts src/server/audio-pacer.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/voice-ice.test.ts src/shared/voice-profile.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/jitter-buffer.test.ts web/test/remote-playback.test.ts web/test/opus-uplink.test.ts web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs web/src/services/host-recovery-presentation.test.ts web/test/opus-uplink-browser.test.mjs", + "test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/turn-credentials.test.ts src/server/voice-ice-config.test.ts src/server/audio-pacer.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/voice-ice.test.ts src/shared/voice-profile.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/jitter-buffer.test.ts web/test/remote-playback.test.ts web/test/opus-uplink.test.ts web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs web/src/services/host-recovery-presentation.test.ts web/test/opus-uplink-browser.test.mjs src/shared/voice-audio.test.ts src/server/downlink-batcher.test.ts", "verify": "npm test && npm run build && npm run web:build", "skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs", "skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs", diff --git a/src/admin/admin-router.ts b/src/admin/admin-router.ts index 09b949c..8551689 100644 --- a/src/admin/admin-router.ts +++ b/src/admin/admin-router.ts @@ -622,6 +622,9 @@ function readSettingsInput(body: Record): AdminSettingsInput { voiceTurnTtlSeconds: readOptionalInteger(body, "voiceTurnTtlSeconds"), voiceOpusWs: typeof body.voiceOpusWs === "boolean" ? body.voiceOpusWs : undefined, voiceJitterMaxMs: readOptionalInteger(body, "voiceJitterMaxMs"), + voiceDownlinkFrameMs: body.voiceDownlinkFrameMs === 20 || body.voiceDownlinkFrameMs === 40 ? body.voiceDownlinkFrameMs : undefined, + voiceAssumeCloudflare: typeof body.voiceAssumeCloudflare === "boolean" ? body.voiceAssumeCloudflare : undefined, + voiceAutoRelayRetry: typeof body.voiceAutoRelayRetry === "boolean" ? body.voiceAutoRelayRetry : undefined, relaySettingsAction: readRelaySettingsAction(body.relaySettingsAction), relayEnabled: body.relayEnabled === true, relayName: typeof body.relayName === "string" ? body.relayName.slice(0, 80) : undefined, diff --git a/src/admin/admin-service.ts b/src/admin/admin-service.ts index c3dae54..9ae4f27 100644 --- a/src/admin/admin-service.ts +++ b/src/admin/admin-service.ts @@ -156,6 +156,9 @@ export class AdminService { voiceTurnTtlSeconds: turn.ttlSeconds, voiceOpusWs: settings.voiceOpusWs ?? this.voiceIceDefaults.opusWebSocket, voiceJitterMaxMs: settings.voiceJitterMaxMs ?? this.voiceIceDefaults.jitterMaxMs, + voiceDownlinkFrameMs: settings.voiceDownlinkFrameMs ?? this.voiceIceDefaults.downlinkFrameMs, + voiceAssumeCloudflare: settings.voiceAssumeCloudflare ?? this.voiceIceDefaults.assumeCloudflare, + voiceAutoRelayRetry: settings.voiceAutoRelayRetry ?? this.voiceIceDefaults.autoRelayRetry, relayConfigured: settings.relayConfigured, relayEnabled: settings.relayEnabled, relayName: settings.relayName, @@ -193,6 +196,9 @@ export class AdminService { profile: settings.voiceProfile ?? this.voiceIceDefaults.profile, opusWebSocket: settings.voiceOpusWs ?? this.voiceIceDefaults.opusWebSocket, jitterMaxMs: settings.voiceJitterMaxMs ?? this.voiceIceDefaults.jitterMaxMs, + downlinkFrameMs: settings.voiceDownlinkFrameMs ?? this.voiceIceDefaults.downlinkFrameMs, + assumeCloudflare: settings.voiceAssumeCloudflare ?? this.voiceIceDefaults.assumeCloudflare, + autoRelayRetry: settings.voiceAutoRelayRetry ?? this.voiceIceDefaults.autoRelayRetry, }; } @@ -509,6 +515,18 @@ export class AdminService { if (voiceJitterMaxMs !== null && (!Number.isInteger(voiceJitterMaxMs) || voiceJitterMaxMs < VOICE_JITTER_MIN_MS || voiceJitterMaxMs > VOICE_JITTER_MAX_MS)) { throw new AdminInputError("INVALID_VOICE_JITTER_MAX", `Adaptive jitter limit must be between ${VOICE_JITTER_MIN_MS} and ${VOICE_JITTER_MAX_MS} ms`); } + const voiceDownlinkFrameMs = input.voiceDownlinkFrameMs === undefined ? current.voiceDownlinkFrameMs : input.voiceDownlinkFrameMs; + if (voiceDownlinkFrameMs !== null && voiceDownlinkFrameMs !== 20 && voiceDownlinkFrameMs !== 40) { + throw new AdminInputError("INVALID_VOICE_FRAME_MS", "Compatibility frame must be 20 or 40 ms"); + } + const voiceAssumeCloudflare = input.voiceAssumeCloudflare === undefined ? current.voiceAssumeCloudflare : input.voiceAssumeCloudflare; + if (voiceAssumeCloudflare !== null && typeof voiceAssumeCloudflare !== "boolean") { + throw new AdminInputError("INVALID_VOICE_ASSUME_CLOUDFLARE", "Assume-Cloudflare must be a boolean"); + } + const voiceAutoRelayRetry = input.voiceAutoRelayRetry === undefined ? current.voiceAutoRelayRetry : input.voiceAutoRelayRetry; + if (voiceAutoRelayRetry !== null && typeof voiceAutoRelayRetry !== "boolean") { + throw new AdminInputError("INVALID_VOICE_AUTO_RELAY_RETRY", "Automatic relay retry must be a boolean"); + } let turnSecret = ""; if (voiceTurnSecretEncrypted === null) { turnSecret = this.voiceIceDefaults.turnRest?.secret ?? ""; @@ -598,6 +616,9 @@ export class AdminService { voiceTurnTtlSeconds, voiceOpusWs, voiceJitterMaxMs, + voiceDownlinkFrameMs, + voiceAssumeCloudflare, + voiceAutoRelayRetry, relayConfigured, relayEnabled, relayName, @@ -730,6 +751,9 @@ export class AdminService { voiceTurnTtlSeconds: settings.voiceTurnTtlSeconds, voiceOpusWs: settings.voiceOpusWs, voiceJitterMaxMs: settings.voiceJitterMaxMs, + voiceDownlinkFrameMs: settings.voiceDownlinkFrameMs, + voiceAssumeCloudflare: settings.voiceAssumeCloudflare, + voiceAutoRelayRetry: settings.voiceAutoRelayRetry, relayConfigured: settings.relayConfigured, relayEnabled: settings.relayEnabled, relayName: settings.relayName, @@ -768,6 +792,9 @@ export class AdminService { voiceTurnTtlSeconds: current.voiceTurnTtlSeconds, voiceOpusWs: current.voiceOpusWs, voiceJitterMaxMs: current.voiceJitterMaxMs, + voiceDownlinkFrameMs: current.voiceDownlinkFrameMs, + voiceAssumeCloudflare: current.voiceAssumeCloudflare, + voiceAutoRelayRetry: current.voiceAutoRelayRetry, relayConfigured: current.relayConfigured, relayEnabled: current.relayEnabled, relayName: current.relayName, diff --git a/src/persistence/database.test.ts b/src/persistence/database.test.ts index cd90e30..337975a 100644 --- a/src/persistence/database.test.ts +++ b/src/persistence/database.test.ts @@ -14,7 +14,8 @@ test("voice overrides preserve schema 13 and survive an old binary updating ordi const database = new WebSpeakDatabase(filename); const encrypted = encryptSecret("turn-test-secret-value", Buffer.alloc(32, 7), "webspeak:voice-turn-rest-secret:v1"); database.updateSettings({ ...database.getSettings(), voiceProfile: "adaptive", voiceTurnUrls: "turn:turn.example.com:3478", - voiceTurnSecretEncrypted: encrypted, voiceTurnTtlSeconds: 3600, voiceOpusWs: true, voiceJitterMaxMs: 200 }); + voiceTurnSecretEncrypted: encrypted, voiceTurnTtlSeconds: 3600, voiceOpusWs: true, voiceJitterMaxMs: 200, + voiceDownlinkFrameMs: 40, voiceAssumeCloudflare: true, voiceAutoRelayRetry: false }); database.close(); const legacy = new DatabaseSync(filename); try { @@ -31,6 +32,9 @@ test("voice overrides preserve schema 13 and survive an old binary updating ordi assert.equal(settings.voiceTurnSecretEncrypted, encrypted); assert.equal(settings.voiceOpusWs, true); assert.equal(settings.voiceJitterMaxMs, 200); + assert.equal(settings.voiceDownlinkFrameMs, 40); + assert.equal(settings.voiceAssumeCloudflare, true); + assert.equal(settings.voiceAutoRelayRetry, false); reopened.setMeta("voice_settings_v1", "invalid-json"); assert.equal(reopened.getSettings().voiceProfile, null); } finally { reopened.close(); } diff --git a/src/persistence/database.ts b/src/persistence/database.ts index 527908b..bd3e0b5 100644 --- a/src/persistence/database.ts +++ b/src/persistence/database.ts @@ -40,6 +40,9 @@ export interface PersistedSettings { voiceTurnTtlSeconds: number | null; voiceOpusWs: boolean | null; voiceJitterMaxMs: number | null; + voiceDownlinkFrameMs: 20 | 40 | null; + voiceAssumeCloudflare: boolean | null; + voiceAutoRelayRetry: boolean | null; relayConfigured: boolean; relayEnabled: boolean; relayName: string; @@ -73,6 +76,9 @@ export interface SettingsUpdate { voiceTurnTtlSeconds?: number | null; voiceOpusWs?: boolean | null; voiceJitterMaxMs?: number | null; + voiceDownlinkFrameMs?: 20 | 40 | null; + voiceAssumeCloudflare?: boolean | null; + voiceAutoRelayRetry?: boolean | null; relayConfigured: boolean; relayEnabled: boolean; relayName: string; @@ -775,7 +781,7 @@ export class WebSpeakDatabase { } /** Optional settings must survive a code-only rollback to the 0.3.3 schema. */ - private readVoiceSettings(): Pick { + private readVoiceSettings(): Pick { let value: Record = {}; try { const parsed: unknown = JSON.parse(this.getMeta(VOICE_SETTINGS_META_KEY) ?? "{}"); @@ -791,6 +797,10 @@ export class WebSpeakDatabase { voiceOpusWs: typeof value.voiceOpusWs === "boolean" ? value.voiceOpusWs : null, voiceJitterMaxMs: Number.isInteger(value.voiceJitterMaxMs) && Number(value.voiceJitterMaxMs) >= 80 && Number(value.voiceJitterMaxMs) <= 500 ? Number(value.voiceJitterMaxMs) : null, + voiceDownlinkFrameMs: value.voiceDownlinkFrameMs === 20 || value.voiceDownlinkFrameMs === 40 + ? value.voiceDownlinkFrameMs : null, + voiceAssumeCloudflare: typeof value.voiceAssumeCloudflare === "boolean" ? value.voiceAssumeCloudflare : null, + voiceAutoRelayRetry: typeof value.voiceAutoRelayRetry === "boolean" ? value.voiceAutoRelayRetry : null, }; } diff --git a/src/server/audio-stats.ts b/src/server/audio-stats.ts index e8c5ccf..162decd 100644 --- a/src/server/audio-stats.ts +++ b/src/server/audio-stats.ts @@ -33,6 +33,12 @@ export interface AudioFlowStats extends WebRtcAudioStats { egressSentMaxGapMs: number; egressPeakBufferedBytes: number; egressFramesByClient: Record; + downlinkBatchMessages: number; + downlinkBatchEntries: number; + downlinkBatchMaxEntries: number; + downlinkBatchDroppedFrames: number; + downlinkBatchPeakQueueMs: number; + downlinkBatchLateTicks: number; } @@ -74,6 +80,12 @@ export function createAudioFlowStats(): AudioFlowStats { egressSentMaxGapMs: 0, egressPeakBufferedBytes: 0, egressFramesByClient: {}, + downlinkBatchMessages: 0, + downlinkBatchEntries: 0, + downlinkBatchMaxEntries: 0, + downlinkBatchDroppedFrames: 0, + downlinkBatchPeakQueueMs: 0, + downlinkBatchLateTicks: 0, webrtcIngressRtpFrames: 0, webrtcIngressRtpFirstAt: null, webrtcIngressRtpLastAt: null, diff --git a/src/server/downlink-batcher.test.ts b/src/server/downlink-batcher.test.ts new file mode 100644 index 0000000..950c724 --- /dev/null +++ b/src/server/downlink-batcher.test.ts @@ -0,0 +1,84 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { DownlinkBatcher } from "./downlink-batcher.js"; +import { decodeVoiceBatch } from "../shared/voice-audio.js"; + +function fixture(frameMs: 20 | 40 = 20) { + let now = 0; + const packets: { packet: Uint8Array; entries: number; sentAt: number }[] = []; + const batcher = new DownlinkBatcher({ + frameMs, + now: () => now, + subscribe: () => () => {}, + send: (packet, entries, sentAt) => { packets.push({ packet, entries, sentAt }); }, + }); + return { batcher, packets, setNow: (value: number) => { now = value; } }; +} + +test("batcher coalesces one tick of speakers into a single v3 packet", () => { + const f = fixture(); + f.batcher.push(4, 2, Uint8Array.from([1, 2, 3])); + f.batcher.push(5, 3, Uint8Array.from([4, 5])); + f.batcher.push(4, 4, Uint8Array.from([6])); + f.batcher.flush(0); + assert.equal(f.packets.length, 1); + const decoded = decodeVoiceBatch(f.packets[0]!.packet); + assert.ok(decoded); + assert.equal(decoded.audioStartMs, 0); + assert.deepEqual(decoded.entries.map(entry => entry.clientId), [2, 3, 4]); + assert.deepEqual(decoded.entries.map(entry => entry.seq), [1, 1, 1]); + assert.equal(f.batcher.getStats().messages, 1); + assert.equal(f.batcher.getStats().entries, 3); + assert.equal(f.batcher.getStats().maxEntries, 3); +}); + +test("batcher caps entries and bytes per packet while keeping every frame", () => { + const f = fixture(); + for (let id = 1; id <= 40; id++) f.batcher.push(4, id, new Uint8Array(100)); + f.batcher.flush(0); + assert.ok(f.packets.length >= 2); + const decoded = f.packets.flatMap(entry => decodeVoiceBatch(entry.packet)?.entries ?? []); + assert.equal(decoded.length, 40); + assert.ok(Math.max(...f.packets.map(entry => entry.entries)) <= 32); + assert.equal(f.batcher.getStats().droppedFrames, 0); +}); + +test("stale frames and per-speaker sequence gaps survive a tunnel stall", () => { + const f = fixture(); + f.batcher.push(4, 2, Uint8Array.from([1])); + f.setNow(150); + f.batcher.flush(150); + assert.equal(f.packets.length, 0); + assert.equal(f.batcher.getStats().droppedFrames, 1); + f.batcher.push(4, 2, Uint8Array.from([2])); + f.setNow(160); + f.batcher.flush(160); + const decoded = decodeVoiceBatch(f.packets[0]!.packet); + assert.equal(decoded?.entries[0]?.seq, 2, "a dropped frame leaves a detectable gap"); +}); + +test("40 ms batching waits a full negotiated tick", () => { + const f = fixture(40); + f.batcher.push(4, 2, Uint8Array.from([1])); + f.batcher.flush(0); + const decoded = decodeVoiceBatch(f.packets[0]!.packet); + assert.equal(decoded?.audioStartMs, 0); + f.batcher.setFrameMs(20); + f.setNow(20); + f.batcher.push(4, 2, Uint8Array.from([2])); + f.batcher.flush(20); + assert.equal(decodeVoiceBatch(f.packets[1]!.packet)?.audioStartMs, 20); +}); + +test("a late flush keeps one audio timestamp per missed tick", () => { + const f = fixture(); + f.batcher.push(4, 2, Uint8Array.from([1])); + f.setNow(20); + f.batcher.push(4, 2, Uint8Array.from([2])); + // Simulate a 100 ms timer stall: both ticks are still inside the queue + // horizon and must not collapse onto a single playback instant. + f.setNow(100); + f.batcher.flush(100); + assert.equal(f.packets.length, 2); + assert.deepEqual(f.packets.map(entry => decodeVoiceBatch(entry.packet)?.audioStartMs), [0, 20]); +}); diff --git a/src/server/downlink-batcher.ts b/src/server/downlink-batcher.ts new file mode 100644 index 0000000..01a2402 --- /dev/null +++ b/src/server/downlink-batcher.ts @@ -0,0 +1,218 @@ +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; + private readonly onStats: DownlinkBatcherOptions["onStats"]; + private readonly queue: QueuedFrame[] = []; + private readonly seqByClient = new Map(); + 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()); + } +} diff --git a/src/server/downlink-scheduler.ts b/src/server/downlink-scheduler.ts new file mode 100644 index 0000000..43ff84f --- /dev/null +++ b/src/server/downlink-scheduler.ts @@ -0,0 +1,63 @@ +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; + nextAt: number; + subscribers: Set; +} + +const slots = new Map(); +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(); +} diff --git a/src/server/session-audio.test.ts b/src/server/session-audio.test.ts index cb5c91a..a7eec68 100644 --- a/src/server/session-audio.test.ts +++ b/src/server/session-audio.test.ts @@ -285,3 +285,45 @@ test("invalid SDK speaker IDs and codecs cannot throw while packing the header", assert.equal(f.audio.egressDroppedFrames, 6); assert.equal(f.packets.length, 0); }); + +test("a 40 ms PCM frame is split into two TeamSpeak frames and costs two rate tokens", () => { + const f = fixture(); + f.transport.receivePcm(Buffer.alloc(3_840)); + assert.equal(f.encoded.length, 2); + assert.deepEqual(f.forwarded.map(entry => entry.codec), [4, 4]); + assert.equal(f.audio.ingressPcmFrames, 2); + for (let index = 0; index < 24; index++) f.state.now = 20 + index * 20; + for (let index = 0; index < 24; index++) f.transport.receivePcm(Buffer.alloc(3_840)); + assert.equal(f.audio.ingressDroppedFrames, 0, "40 ms frames consume their two tokens without exceeding the budget"); +}); + +test("a v3 client gets one batched packet per audio tick instead of one message per speaker", t => { + t.mock.timers.enable({ apis: ["setInterval"] }); + const f = fixture(); + f.transport.setDownlinkBatch(20); + f.transport.receiveTeamSpeak({ clientId: 2, codec: 4, data: Buffer.from([1, 2]) }); + f.transport.receiveTeamSpeak({ clientId: 3, codec: 5, data: Buffer.from([3]) }); + f.transport.receiveTeamSpeak({ clientId: 4, codec: 4, data: Buffer.from([4]) }); + assert.equal(f.packets.length, 0, "no immediate small messages after negotiation"); + f.state.now = 20; + t.mock.timers.tick(20); + assert.equal(f.packets.length, 1); + assert.equal(f.packets[0]![0], 0xf3); + assert.equal(f.audio.egressFrames, 3, "flow counters still count frames, not batches"); + assert.equal(f.audio.downlinkBatchMessages, 1); + assert.equal(f.audio.downlinkBatchEntries, 3); +}); + +test("a 40 ms v3 negotiation holds a batch for two 20 ms frames", t => { + t.mock.timers.enable({ apis: ["setInterval"] }); + const f = fixture(); + f.transport.setDownlinkBatch(40); + f.transport.receiveTeamSpeak({ clientId: 2, codec: 4, data: Buffer.from([1]) }); + f.state.now = 20; + t.mock.timers.tick(20); + assert.equal(f.packets.length, 0); + f.state.now = 40; + t.mock.timers.tick(20); + assert.equal(f.packets.length, 1); + assert.equal(f.audio.downlinkBatchEntries, 1); +}); diff --git a/src/server/session-audio.ts b/src/server/session-audio.ts index 8dcb12b..d72f09e 100644 --- a/src/server/session-audio.ts +++ b/src/server/session-audio.ts @@ -6,6 +6,7 @@ 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 { DownlinkBatcher } from "./downlink-batcher.js"; import { VOICE_MAX_OPUS_FRAME_BYTES, VOICE_OPUS_TAG, @@ -14,12 +15,16 @@ import { } from "../shared/voice-audio.js"; const AUDIO_FRAME_BYTES = VOICE_PCM_FRAME_BYTES; +const AUDIO_FRAME_BYTES_40 = AUDIO_FRAME_BYTES * 2; const TAGGED_PCM_FRAME_BYTES = AUDIO_FRAME_BYTES + 1; +const TAGGED_PCM_FRAME_BYTES_40 = AUDIO_FRAME_BYTES_40 + 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. +// Keep the established byte guard for the per-packet v2 path; a negotiated v3 +// batch may hold several speakers' frames and uses the larger limit below. const MAX_BUFFERED_BYTES = 4_096; +const BATCH_BUFFERED_BYTES = 32 * 1_024; // A client that keeps sending bad audio must not turn into one JSON error per // frame: the reply is roughly 100x the offending payload, and the browser only // ever shows the first one because it writes the same error string. @@ -56,6 +61,8 @@ export class SessionAudioTransport { private readonly reportedAt = new Map(); private readonly logger: LoggerType | null; private readonly pacer: AudioPacer | null; + private downlinkBatcher: DownlinkBatcher | null = null; + private downlinkBufferedBytes = MAX_BUFFERED_BYTES; private pcmTokens = PCM_BURST_FRAMES; private pcmRefilledAt: number | null = null; @@ -88,6 +95,47 @@ export class SessionAudioTransport { return peer?.isConnected ? peer : null; } + /** + * Switch the compatibility downlink to one binary message per audio tick. + * Only called after a client has negotiated frame version 3, so a v2 client + * keeps the byte-for-byte per-packet path. + */ + setDownlinkBatch(frameMs: 20 | 40): void { + if (this.closed) return; + this.downlinkBufferedBytes = BATCH_BUFFERED_BYTES; + if (this.downlinkBatcher) { + this.downlinkBatcher.setFrameMs(frameMs); + return; + } + this.downlinkBatcher = new DownlinkBatcher({ + frameMs, + now: () => this.rateClock(), + send: (packet, entries) => { + if (!this.isCurrent()) return; + try { + this.options.socket.send(Buffer.from(packet)); + const stats = this.options.audio; + stats.egressFrames += entries; + const sentAt = this.clock(); + if (stats.egressSentLastAt !== null) stats.egressSentMaxGapMs = Math.max(stats.egressSentMaxGapMs, sentAt - stats.egressSentLastAt); + stats.egressSentFirstAt ??= sentAt; + stats.egressSentLastAt = sentAt; + } catch { + this.options.audio.downlinkBatchDroppedFrames += entries; + } + }, + onStats: stats => { + const audio = this.options.audio; + audio.downlinkBatchMessages = stats.messages; + audio.downlinkBatchEntries = stats.entries; + audio.downlinkBatchMaxEntries = Math.max(audio.downlinkBatchMaxEntries, stats.maxEntries); + audio.downlinkBatchDroppedFrames = Math.max(audio.downlinkBatchDroppedFrames, stats.droppedFrames); + audio.downlinkBatchPeakQueueMs = Math.max(audio.downlinkBatchPeakQueueMs, stats.peakQueuedMs); + audio.downlinkBatchLateTicks = Math.max(audio.downlinkBatchLateTicks, stats.lateTicks); + }, + }); + } + private recordIngress(): void { const stats = this.options.audio; const now = this.clock(); @@ -161,8 +209,9 @@ 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.mediaPeer()) { stats.ingressDroppedFrames++; return; } - 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 legacyPcm = frame.length === AUDIO_FRAME_BYTES || frame.length === AUDIO_FRAME_BYTES_40 ? frame : null; + const taggedPcm = (frame.length === TAGGED_PCM_FRAME_BYTES || frame.length === TAGGED_PCM_FRAME_BYTES_40) + && 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) { @@ -170,19 +219,24 @@ export class SessionAudioTransport { this.reportInvalidFrame(frame.length); return; } + // A 40 ms PCM frame carries two 20 ms TeamSpeak frames and therefore costs + // two tokens; otherwise a client could double its uplink rate by doubling + // the frame size. + const pcmFrames = legacyPcm ?? taggedPcm; + const frameCount = pcmFrames ? (pcmFrames.length === AUDIO_FRAME_BYTES_40 ? 2 : 1) : 1; const now = this.rateClock(); if (this.pcmRefilledAt !== null) { this.pcmTokens = Math.min(PCM_BURST_FRAMES, this.pcmTokens + Math.max(0, now - this.pcmRefilledAt) * PCM_FRAMES_PER_MS); } this.pcmRefilledAt = Math.max(this.pcmRefilledAt ?? now, now); - if (this.pcmTokens < 1) { + if (this.pcmTokens < frameCount) { stats.ingressDroppedFrames++; if (this.shouldReportAudioIssue("AUDIO_RATE_EXCEEDED")) { this.logger?.warn({ code: "AUDIO_RATE_EXCEEDED", droppedFrames: stats.ingressDroppedFrames }, "Discarded browser audio above the real-time budget"); } return; } - this.pcmTokens--; + this.pcmTokens -= frameCount; this.recordIngress(); if (opus) { stats.ingressOpusFrames++; @@ -192,21 +246,26 @@ export class SessionAudioTransport { 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(taggedPcm ?? legacyPcm!); - stats.tsEncodeMaxMs = Math.max(stats.tsEncodeMaxMs, this.clock() - startedAt); - } catch { - stats.tsSendErrors++; - stats.ingressDroppedFrames++; - this.reportEncoderFailure(); - return; + stats.ingressPcmFrames += frameCount; + const chunks = pcmFrames!.length === AUDIO_FRAME_BYTES_40 + ? [pcmFrames!.subarray(0, AUDIO_FRAME_BYTES), pcmFrames!.subarray(AUDIO_FRAME_BYTES)] + : [pcmFrames!]; + for (const chunk of chunks) { + const startedAt = this.clock(); + let encoded: Buffer; + try { + if (!this.encoder) throw new Error("Encoder unavailable"); + encoded = this.encoder.encode(chunk); + stats.tsEncodeMaxMs = Math.max(stats.tsEncodeMaxMs, this.clock() - startedAt); + } catch { + stats.tsSendErrors++; + stats.ingressDroppedFrames++; + this.reportEncoderFailure(); + return; + } + this.pacer?.push(encoded, 4); + if (!this.pacer) this.sendVoice(encoded, 4); } - this.pacer?.push(encoded, 4); - if (!this.pacer) this.sendVoice(encoded, 4); } receiveWebRtc(data: Buffer, codec: number): void { @@ -242,6 +301,14 @@ export class SessionAudioTransport { } const bufferedBytes = this.options.socket.bufferedAmount; stats.egressPeakBufferedBytes = Math.max(stats.egressPeakBufferedBytes, bufferedBytes); + if (this.downlinkBatcher) { + if (bufferedBytes > this.downlinkBufferedBytes) { + stats.downlinkBatchDroppedFrames++; + return; + } + if (!this.downlinkBatcher.push(data.codec, data.clientId, data.data)) stats.egressDroppedFrames++; + return; + } if (bufferedBytes > MAX_BUFFERED_BYTES) { stats.egressDroppedFrames++; return; } const packet = Buffer.allocUnsafe(3 + data.data.length); packet[0] = data.codec; @@ -262,6 +329,8 @@ export class SessionAudioTransport { this.closed = true; this.reportedAt.clear(); this.pacer?.close(); + this.downlinkBatcher?.close(); + this.downlinkBatcher = null; const encoder = this.encoder; this.encoder = null; try { encoder?.dispose(); } catch { /* other session resources must still be released */ } diff --git a/src/server/voice-bridge.integration.test.ts b/src/server/voice-bridge.integration.test.ts index 7c665d5..ef34158 100644 --- a/src/server/voice-bridge.integration.test.ts +++ b/src/server/voice-bridge.integration.test.ts @@ -184,10 +184,14 @@ test("a direct connection keeps the legacy audio profile and the original media profile: "auto", opusWebSocket: false, jitterMaxMs: 300, + downlinkFrameMs: 20, + assumeCloudflare: false, + autoRelayRetry: true, }, }); const connected = await waitForBufferedMessage>(f.messages, "connected"); assert.equal(connected.voiceProfile, "legacy"); + assert.equal(connected.voiceRelayAutoRetry, true); assert.equal(connected.webrtcAvailable, true); assert.equal(connected.webrtcUnavailableReason, undefined); assert.equal(connected.audioFrameVersion, undefined); @@ -197,6 +201,28 @@ test("a direct connection keeps the legacy audio profile and the original media assert.deepEqual(connected.voiceIceServers, [{ urls: "stun:stun.example.invalid:3478" }]); }); +test("the console can force a Cloudflare ingress and disable automatic relay retry", { 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, + downlinkFrameMs: 20, + assumeCloudflare: true, + autoRelayRetry: false, + }, + }); + const connected = await waitForBufferedMessage>(f.messages, "connected"); + assert.equal(connected.voiceProfile, "adaptive"); + assert.equal(connected.webrtcAvailable, false); + assert.equal(connected.webrtcUnavailableReason, "NO_MEDIA_PATH"); + assert.equal(connected.voiceRelayAutoRetry, false); +}); + 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 }, @@ -207,12 +233,17 @@ test("an explicit adaptive profile enables the new audio path on a direct connec profile: "adaptive", opusWebSocket: true, jitterMaxMs: 300, + downlinkFrameMs: 20, + assumeCloudflare: false, + autoRelayRetry: true, }, }); const connected = await waitForBufferedMessage>(f.messages, "connected"); assert.equal(connected.voiceProfile, "adaptive"); assert.equal(connected.webrtcAvailable, true); assert.equal(connected.audioFrameVersion, 2); + assert.deepEqual(connected.audioDownlinkVersions, [2, 3]); + assert.deepEqual(connected.audioFrameMsOptions, [20]); assert.deepEqual(connected.audioUplinkCodecs, ["pcm", "opus"]); assert.equal(connected.audioJitterMaxMs, 300); }); @@ -227,6 +258,9 @@ test("a Cloudflare request opts into adaptive audio without inventing an ICE hos profile: "auto", opusWebSocket: false, jitterMaxMs: 300, + downlinkFrameMs: 20, + assumeCloudflare: false, + autoRelayRetry: true, }, headers: { "cf-ray": "test-ray" }, }); @@ -235,11 +269,36 @@ test("a Cloudflare request opts into adaptive audio without inventing an ICE hos assert.equal(connected.webrtcAvailable, false); assert.equal(connected.webrtcUnavailableReason, "NO_MEDIA_PATH"); assert.equal(connected.audioFrameVersion, 2); + assert.deepEqual(connected.audioDownlinkVersions, [2, 3]); + assert.deepEqual(connected.audioFrameMsOptions, [20]); assert.deepEqual(connected.audioUplinkCodecs, ["pcm"]); assert.equal(connected.audioJitterMaxMs, 300); assert.deepEqual(connected.voiceIceServers, []); }); +test("an adaptive client upgrades to one v3 batch per tick", { timeout: 5_000 }, async t => { + const f = await fixture(t, { + webRtc: { enabled: true }, + voiceIce: { + servers: [], transportPolicy: "all", gatewayTransportPolicy: "all", + profile: "adaptive", opusWebSocket: false, jitterMaxMs: 300, + downlinkFrameMs: 40, assumeCloudflare: false, autoRelayRetry: true, + }, + }); + await waitForBufferedMessage(f.messages, "connected"); + const config = waitForMessage>(f.socket, "audioConfig"); + f.socket.send(JSON.stringify({ + type: "audioCaps", + requestId: "caps-1", + payload: { downlinkVersion: 3, maxFrameMs: 40, codecs: ["pcm"] }, + })); + const message = await config; + assert.equal(message.downlinkVersion, 3); + assert.equal(message.frameMs, 40, "the console can opt into 40 ms batching"); + assert.deepEqual(message.uplinkCodecs, ["pcm"]); + assert.equal(message.jitterMaxMs, 300); +}); + test("a voice ICE getter is resolved when a new connection is accepted", { timeout: 5_000 }, async t => { let calls = 0; @@ -254,6 +313,9 @@ test("a voice ICE getter is resolved when a new connection is accepted", { timeo profile: "auto", opusWebSocket: false, jitterMaxMs: 300, + downlinkFrameMs: 20, + assumeCloudflare: false, + autoRelayRetry: true, }; }, headers: { "cf-ray": "console-refresh-ray" }, diff --git a/src/server/voice-bridge.ts b/src/server/voice-bridge.ts index a125f34..9d72305 100644 --- a/src/server/voice-bridge.ts +++ b/src/server/voice-bridge.ts @@ -41,6 +41,8 @@ import { resolveVoiceProfile, type VoiceProfile } from "../shared/voice-profile. const HEARTBEAT_INTERVAL_MS = 30_000; const MAX_MISSED_HEARTBEATS = 2; const MAX_LOGGED_WEBSOCKET_CLOSE_REASON_LENGTH = 160; +/** Set when a reverse proxy strips Cloudflare headers but CFT is still the ingress. */ +const ASSUME_CLOUDFLARE = process.env.WEBSPEAK_ASSUME_CLOUDFLARE === "1"; function sanitizeWebSocketCloseReason(reason: Buffer): string { return reason.toString("utf8") @@ -193,12 +195,12 @@ export class VoiceBridge { return; } const clientIp = resolveClientIp(req, this.trustedProxies); + const voiceIce = this.getVoiceIceConfig(); // 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 cloudflareRequest = (voiceIce?.assumeCloudflare ?? ASSUME_CLOUDFLARE) || isCloudflareRequest(req, this.trustedProxies); const webrtcPublicHost = resolveWebRtcPublicHost(req, { allowHostFallback: !cloudflareRequest }); - const voiceIce = this.getVoiceIceConfig(); const voiceProfile = resolveVoiceProfile(voiceIce?.profile ?? "auto", cloudflareRequest); let identity; try { @@ -377,8 +379,11 @@ export class VoiceBridge { voiceProfile: entry!.voiceProfile, voiceIceServers: entry!.voiceIceServers, voiceIceTransportPolicy: entry!.voiceIceTransportPolicy, + voiceRelayAutoRetry: voiceIce?.autoRelayRetry !== false, ...(entry!.voiceProfile === "adaptive" ? { audioFrameVersion: 2 as const, + audioDownlinkVersions: [...new Set([2, 3])] as (2 | 3)[], + audioFrameMsOptions: [...new Set([20, voiceIce?.downlinkFrameMs ?? 20])] as (20 | 40)[], audioUplinkCodecs: voiceIce?.opusWebSocket === true ? ["pcm", "opus"] as ("pcm" | "opus")[] : ["pcm"] as ("pcm" | "opus")[], @@ -669,6 +674,25 @@ export class VoiceBridge { sendProtocolError(sendJson, "SESSION_NOT_READY", "TeamSpeak 会话尚未就绪", command.requestId); return; } + if (command.type === "audioCaps") { + const uplinkCodecs: ("pcm" | "opus")[] = entry!.voiceProfile === "adaptive" && voiceIce?.opusWebSocket === true + ? ["pcm", "opus"] + : ["pcm"]; + if (entry!.voiceProfile !== "adaptive") { + sendJson({ type: "audioConfig", downlinkVersion: 2, frameMs: 20, uplinkCodecs, jitterMaxMs: 80 }); + return; + } + const frameMs = Math.min(command.payload.maxFrameMs, voiceIce?.downlinkFrameMs ?? 20) as 20 | 40; + entry!.audioTransport?.setDownlinkBatch(frameMs); + sendJson({ + type: "audioConfig", + downlinkVersion: 3, + frameMs, + uplinkCodecs, + jitterMaxMs: voiceIce?.jitterMaxMs ?? 300, + }); + return; + } if (command.type === "createInvite") { if (!this.options.createWorkspaceInvite) { sendProtocolError(sendJson, "INVITE_UNAVAILABLE", "Invitations are unavailable on this gateway", command.requestId); return; } if (Date.now() - lastInviteAt < 1000) { sendProtocolError(sendJson, "RATE_LIMITED", "Please wait before creating another invitation", command.requestId); return; } diff --git a/src/server/voice-ice-config.test.ts b/src/server/voice-ice-config.test.ts index 5140e18..f1e54c9 100644 --- a/src/server/voice-ice-config.test.ts +++ b/src/server/voice-ice-config.test.ts @@ -10,8 +10,11 @@ test("voice ICE env parses static servers and direct-first defaults", () => { assert.equal(config.transportPolicy, "all"); assert.equal(config.gatewayTransportPolicy, "all"); assert.equal(config.profile, "auto"); - assert.equal(config.opusWebSocket, false); + assert.equal(config.opusWebSocket, true); assert.equal(config.jitterMaxMs, 300); + assert.equal(config.downlinkFrameMs, 20); + assert.equal(config.assumeCloudflare, false); + assert.equal(config.autoRelayRetry, true); assert.equal(config.turnRest, undefined); }); @@ -21,6 +24,10 @@ test("voice profile is explicit-only for Opus and can force legacy or adaptive", 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); + assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_OPUS_WS: "0" }).opusWebSocket, false); + assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_FRAME_MS: "40" }).downlinkFrameMs, 40); + assert.equal(readVoiceIceConfig({ WEBSPEAK_ASSUME_CLOUDFLARE: "1" }).assumeCloudflare, true); + assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_AUTO_RELAY_RETRY: "0" }).autoRelayRetry, false); }); test("TURN REST env mints a per-session credential and keeps direct-first policy", () => { diff --git a/src/server/voice-ice-config.ts b/src/server/voice-ice-config.ts index 3e0bf61..8781b76 100644 --- a/src/server/voice-ice-config.ts +++ b/src/server/voice-ice-config.ts @@ -26,6 +26,12 @@ export interface VoiceIceConfig { profile: VoiceProfileSetting; opusWebSocket: boolean; jitterMaxMs: number; + /** Compatibility downlink batch tick. 40 ms halves messages and adds up to 20 ms. */ + downlinkFrameMs: 20 | 40; + /** Treat every voice ingress as Cloudflare even if reverse-proxy headers were stripped. */ + assumeCloudflare: boolean; + /** Allow one automatic relay-only WebRTC retry after a direct-path failure. */ + autoRelayRetry: boolean; } export interface VoiceIceSettings { @@ -35,6 +41,9 @@ export interface VoiceIceSettings { profile: VoiceProfileSetting; opusWebSocket: boolean; jitterMaxMs: number; + downlinkFrameMs: 20 | 40; + assumeCloudflare: boolean; + autoRelayRetry: boolean; } /** Baseline used when neither the console nor the environment configures a value. */ @@ -43,8 +52,13 @@ export const DEFAULT_VOICE_ICE_CONFIG: VoiceIceConfig = { transportPolicy: "all", gatewayTransportPolicy: "all", profile: "auto", - opusWebSocket: false, + // Adaptive clients use Opus when WebCodecs can encode it and silently fall + // back to PCM otherwise; legacy clients never see this flag. + opusWebSocket: true, jitterMaxMs: VOICE_JITTER_DEFAULT_MS, + downlinkFrameMs: 20, + assumeCloudflare: false, + autoRelayRetry: true, }; function parseBoolean(value: string | undefined, fallback: boolean): boolean { @@ -105,9 +119,13 @@ export function readVoiceIceConfig(env: NodeJS.ProcessEnv = process.env): VoiceI 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), + // Opus over WebSocket is negotiated only for adaptive clients; browsers + // without WebCodecs fall back to PCM at runtime. + opusWebSocket: parseBoolean(env.WEBSPEAK_VOICE_OPUS_WS, true), jitterMaxMs: parseInteger(env.WEBSPEAK_VOICE_JITTER_MAX_MS, VOICE_JITTER_DEFAULT_MS, VOICE_JITTER_MIN_MS, VOICE_JITTER_MAX_MS), + downlinkFrameMs: env.WEBSPEAK_VOICE_FRAME_MS?.trim() === "40" ? 40 : 20, + assumeCloudflare: parseBoolean(env.WEBSPEAK_ASSUME_CLOUDFLARE, false), + autoRelayRetry: parseBoolean(env.WEBSPEAK_VOICE_AUTO_RELAY_RETRY, true), }; } @@ -133,6 +151,9 @@ export function voiceConfigSettings(config: VoiceIceConfig): VoiceIceSettings { profile: config.profile, opusWebSocket: config.opusWebSocket, jitterMaxMs: config.jitterMaxMs, + downlinkFrameMs: config.downlinkFrameMs, + assumeCloudflare: config.assumeCloudflare, + autoRelayRetry: config.autoRelayRetry, }; } diff --git a/src/shared/admin-inputs.ts b/src/shared/admin-inputs.ts index 90b0d86..d2506b7 100644 --- a/src/shared/admin-inputs.ts +++ b/src/shared/admin-inputs.ts @@ -22,6 +22,9 @@ export interface AdminSettingsInput { voiceTurnTtlSeconds?: number; voiceOpusWs?: boolean; voiceJitterMaxMs?: number; + voiceDownlinkFrameMs?: 20 | 40; + voiceAssumeCloudflare?: boolean; + voiceAutoRelayRetry?: boolean; relaySettingsAction?: "keep" | "replace" | "remove"; relayEnabled?: boolean; relayName?: string; diff --git a/src/shared/admin-responses.ts b/src/shared/admin-responses.ts index ca2f784..3bd5cbd 100644 --- a/src/shared/admin-responses.ts +++ b/src/shared/admin-responses.ts @@ -37,8 +37,11 @@ const settings = object({ voiceTurnUrls: value => value === undefined ? "" : text(value), hasVoiceTurnSecret: value => value === undefined ? false : boolean(value), voiceTurnTtlSeconds: value => value === undefined ? 21600 : number(value), - voiceOpusWs: value => value === undefined ? false : boolean(value), + voiceOpusWs: value => value === undefined ? true : boolean(value), voiceJitterMaxMs: value => value === undefined ? 300 : number(value), + voiceDownlinkFrameMs: value => value === undefined ? 20 : value === 20 || value === 40 ? value : invalid(), + voiceAssumeCloudflare: value => value === undefined ? false : boolean(value), + voiceAutoRelayRetry: value => value === undefined ? true : boolean(value), relayConfigured: boolean, relayEnabled: boolean, relayName: text, relayTarget: text, hasRelayToken: boolean, relayNodes: array(relayNode), internalPort: number, updatedAt: text, }); diff --git a/src/shared/client-commands.test.ts b/src/shared/client-commands.test.ts index 1ad5d90..f3d6fb7 100644 --- a/src/shared/client-commands.test.ts +++ b/src/shared/client-commands.test.ts @@ -13,6 +13,7 @@ test("all command payloads preserve request IDs through the shared parser", () = setWhisperTargets: { targetIds: [2, 3] }, setWhisperActive: { active: true }, setMicrophoneMuted: { muted: false }, setAccompanimentActive: { active: true }, setMemberVolume: { clientId: 2, volume: 0 }, latencyProbe: { sequence: "old" }, audioStatsProbe: { sequence: "new" }, + audioCaps: { downlinkVersion: 3, maxFrameMs: 40, codecs: ["pcm", "opus"] }, }; for (const [type, payload] of Object.entries(payloads)) { const command = { type, payload, requestId: "request-1" }; diff --git a/src/shared/client-commands.ts b/src/shared/client-commands.ts index 252f49a..5fec5ce 100644 --- a/src/shared/client-commands.ts +++ b/src/shared/client-commands.ts @@ -15,6 +15,7 @@ export interface ClientCommandPayloads { setMemberVolume: { clientId: number; volume: number }; latencyProbe: { sequence: string }; audioStatsProbe: { sequence: string }; + audioCaps: { downlinkVersion: 3; maxFrameMs: 20 | 40; codecs: ("pcm" | "opus")[] }; } export type ClientCommandType = keyof ClientCommandPayloads; @@ -37,7 +38,7 @@ export function parseClientCommand(raw: string): ClientCommandResult { if (value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length > 64)) { return { error: { code: "INVALID_REQUEST_ID", message: "请求标识无效" } }; } - const supportedTypes = new Set(["createInvite", "switchChannel", "moveClient", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe", "audioStatsProbe"]); + const supportedTypes = new Set(["createInvite", "switchChannel", "moveClient", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe", "audioStatsProbe", "audioCaps"]); if (!supportedTypes.has(value.type)) { return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } }; } @@ -110,6 +111,16 @@ export function parseClientCommand(raw: string): ClientCommandResult { if (value.type === "latencyProbe" && (typeof value.payload.sequence !== "string" || value.payload.sequence.length > 64)) { return { error: { code: "INVALID_LATENCY_PROBE", message: "延迟探测标识无效" } }; } + if (value.type === "audioCaps") { + const payload = value.payload; + const codecs = payload.codecs; + if (payload.downlinkVersion !== 3 || (payload.maxFrameMs !== 20 && payload.maxFrameMs !== 40) + || !Array.isArray(codecs) || codecs.length < 1 || codecs.length > 2 + || codecs.some(codec => codec !== "pcm" && codec !== "opus") + || new Set(codecs).size !== codecs.length) { + return { error: { code: "INVALID_AUDIO_CAPS", message: "音频能力声明无效" } }; + } + } return { type: value.type as ClientCommand["type"], ...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}), diff --git a/src/shared/server-messages.test.ts b/src/shared/server-messages.test.ts index 2f425e0..1fc4f11 100644 --- a/src/shared/server-messages.test.ts +++ b/src/shared/server-messages.test.ts @@ -24,6 +24,7 @@ const samples: Record = { serverEvent: { type: "serverEvent", event }, channelSwitched: { type: "channelSwitched", channelId: "1" }, audioStats: { type: "audioStats", sequence: "probe", stats: parseVoiceAudioBridgeStats({})! }, + audioConfig: { type: "audioConfig", downlinkVersion: 3, frameMs: 20, uplinkCodecs: ["pcm", "opus"], jitterMaxMs: 300 }, latencyPong: { type: "latencyPong", sequence: "legacy", teamSpeakLatencyMs: null, teamSpeakReachable: false, teamSpeakErrorCode: "TIMEOUT" }, disconnected: { type: "disconnected", recoverable: false }, reconnecting: { type: "reconnecting", attempt: 2, delayMs: 1_000 }, diff --git a/src/shared/server-messages.ts b/src/shared/server-messages.ts index ad35f13..5a62f6f 100644 --- a/src/shared/server-messages.ts +++ b/src/shared/server-messages.ts @@ -14,7 +14,8 @@ type ChatFields = { invokerId?: number; invokerName?: string; message: string; t /** Public JSON messages. Internal sockets, SDK clients and media objects stay out. */ export type ServerMessage = | Message<"inviteCreated", Request & { token: string; expiresAt: number }> - | Message<"connected", { tsClientId: number; pluginSession?: string; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; webrtcUnavailableReason?: "DISABLED" | "NO_MEDIA_PATH"; webRtcStunServer?: string; voiceProfile?: VoiceProfile; voiceIceServers?: VoiceIceServer[]; voiceIceTransportPolicy?: "all" | "relay"; audioFrameVersion?: 2; audioUplinkCodecs?: ("pcm" | "opus")[]; audioJitterMaxMs?: number; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }> + | Message<"connected", { tsClientId: number; pluginSession?: string; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; webrtcUnavailableReason?: "DISABLED" | "NO_MEDIA_PATH"; webRtcStunServer?: string; voiceProfile?: VoiceProfile; voiceIceServers?: VoiceIceServer[]; voiceIceTransportPolicy?: "all" | "relay"; voiceRelayAutoRetry?: boolean; audioFrameVersion?: 2; audioDownlinkVersions?: (2 | 3)[]; audioFrameMsOptions?: (20 | 40)[]; audioUplinkCodecs?: ("pcm" | "opus")[]; audioJitterMaxMs?: number; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }> + | Message<"audioConfig", { downlinkVersion: 2 | 3; frameMs: 20 | 40; uplinkCodecs: ("pcm" | "opus")[]; jitterMaxMs: number }> | Message<"serverInfo", { name: string; icon?: string | null; bannerUrl?: string | null; welcomeMessage?: string }> | Message<"memberEnter", ChannelMember> | Message<"memberLeave", { id: number }> @@ -146,7 +147,10 @@ const valid: Record boolean> = && optional(m.voiceProfile, isVoiceProfile) && optional(m.voiceIceServers, v => Array.isArray(v) && normalizeVoiceIceServers(v).length === v.length) && optional(m.voiceIceTransportPolicy, v => v === "all" || v === "relay") + && optional(m.voiceRelayAutoRetry, boolean) && optional(m.audioFrameVersion, v => v === 2) + && optional(m.audioDownlinkVersions, v => Array.isArray(v) && v.length > 0 && v.every(version => version === 2 || version === 3)) + && optional(m.audioFrameMsOptions, v => Array.isArray(v) && v.length > 0 && v.every(ms => ms === 20 || ms === 40)) && optional(m.audioUplinkCodecs, v => Array.isArray(v) && v.length > 0 && v.every(codec => codec === "pcm" || codec === "opus")) && optional(m.audioJitterMaxMs, v => finite(v) && Number.isInteger(v) && v >= 80 && v <= 500) && optional(m.whisperTargetIds, v => arrayOf(v, clientId)) && optional(m.whisperActive, boolean) && optional(m.accelerated, boolean), @@ -166,6 +170,11 @@ const valid: Record boolean> = inviteCreated: m => text(m.token) && /^wi_[A-Za-z0-9_-]{43}$/.test(m.token) && typeof m.expiresAt === "number" && Number.isSafeInteger(m.expiresAt), channelSwitched: m => channelId(m.channelId), audioStats: m => text(m.sequence) && m.sequence.length <= 64 && isRecord(m.stats), + audioConfig: m => (m.downlinkVersion === 2 || m.downlinkVersion === 3) + && (m.frameMs === 20 || m.frameMs === 40) + && Array.isArray(m.uplinkCodecs) && m.uplinkCodecs.length > 0 && m.uplinkCodecs.length <= 2 + && m.uplinkCodecs.every(codec => codec === "pcm" || codec === "opus") + && finite(m.jitterMaxMs) && m.jitterMaxMs >= 80 && m.jitterMaxMs <= 500, latencyPong: m => text(m.sequence) && (m.teamSpeakLatencyMs === null || finite(m.teamSpeakLatencyMs)) && boolean(m.teamSpeakReachable) && (m.teamSpeakErrorCode === null || text(m.teamSpeakErrorCode)), disconnected: m => optional(m.recoverable, boolean), diff --git a/src/shared/voice-audio.test.ts b/src/shared/voice-audio.test.ts new file mode 100644 index 0000000..3952318 --- /dev/null +++ b/src/shared/voice-audio.test.ts @@ -0,0 +1,39 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + decodeVoiceBatch, + encodeVoiceBatch, + VOICE_BATCH_HEADER_BYTES, + VOICE_BATCH_TAG, + VOICE_MAX_OPUS_FRAME_BYTES, +} from "./voice-audio.js"; + +test("voice batch round-trips the audio clock and per-speaker entries", () => { + const encoded = encodeVoiceBatch(123_456, [ + { codec: 4, clientId: 2, seq: 7, data: Uint8Array.from([1, 2, 3]) }, + { codec: 5, clientId: 65_535, seq: 255, data: Uint8Array.from([9]) }, + ]); + assert.ok(encoded); + assert.equal(encoded[0], VOICE_BATCH_TAG); + assert.equal(encoded[1], 2); + assert.equal(encoded.length, VOICE_BATCH_HEADER_BYTES + (6 + 3) + (6 + 1)); + const decoded = decodeVoiceBatch(encoded); + assert.ok(decoded); + assert.equal(decoded.audioStartMs, 123_456); + assert.deepEqual(decoded.entries.map(({ codec, clientId, seq, data }) => ({ codec, clientId, seq, data: [...data] })), [ + { codec: 4, clientId: 2, seq: 7, data: [1, 2, 3] }, + { codec: 5, clientId: 65_535, seq: 255, data: [9] }, + ]); +}); + +test("voice batch rejects framing the decoder could not reproduce", () => { + const good = encodeVoiceBatch(1, [{ codec: 4, clientId: 2, seq: 1, data: Uint8Array.from([1, 2, 3]) }])!; + assert.equal(decodeVoiceBatch(Uint8Array.from([...good, 0])), null, "trailing byte"); + assert.equal(decodeVoiceBatch(Uint8Array.from([0xf2, ...good.subarray(1)])), null, "wrong tag"); + assert.equal(decodeVoiceBatch(Uint8Array.from([good[0]!, 0, ...good.subarray(2)])), null, "zero entries"); + const truncated = good.slice(0, -1); + assert.equal(decodeVoiceBatch(truncated), null, "truncated payload"); + assert.equal(encodeVoiceBatch(1, []), null); + assert.equal(encodeVoiceBatch(1, [{ codec: 4, clientId: 0, seq: 1, data: Uint8Array.from([1]) }]), null); + assert.equal(encodeVoiceBatch(1, [{ codec: 4, clientId: 1, seq: 1, data: new Uint8Array(VOICE_MAX_OPUS_FRAME_BYTES + 1) }]), null); +}); diff --git a/src/shared/voice-audio.ts b/src/shared/voice-audio.ts index a0af543..7b5252e 100644 --- a/src/shared/voice-audio.ts +++ b/src/shared/voice-audio.ts @@ -6,3 +6,89 @@ export const VOICE_PCM_TAG = 0x01; export const VOICE_OPUS_TAG = 0x02; /** RFC 6716 maximum Opus packet length; the server validates the same bound. */ export const VOICE_MAX_OPUS_FRAME_BYTES = 1_275; + +/** + * Downlink batch tag. Deliberately outside the TeamSpeak codec range (0-5) and + * above the uplink tags so a legacy client drops the packet instead of trying + * to decode the batch header as Opus. + */ +export const VOICE_BATCH_TAG = 0xf3; +export const VOICE_BATCH_HEADER_BYTES = 6; +export const VOICE_BATCH_MAX_ENTRIES = 32; +export const VOICE_BATCH_MAX_BYTES = 16 * 1024; + +export interface VoiceBatchEntry { + codec: number; + clientId: number; + /** Per-speaker 8-bit sequence; wraps every 256 packets. */ + seq: number; + data: Uint8Array; +} + +export interface DecodedVoiceBatch { + audioStartMs: number; + entries: VoiceBatchEntry[]; +} + +/** + * Encode one downlink batch: + * 0xF3 | count:u8 | audioStartMs:u32be | entries + * entry: codec:u8 | clientId:u16be | seq:u8 | length:u16be | payload + * + * Returns null when the caller supplied something that would not decode + * identically (bad id/length, too many entries, oversized batch). + */ +export function encodeVoiceBatch(audioStartMs: number, entries: readonly VoiceBatchEntry[]): Uint8Array | null { + if (entries.length < 1 || entries.length > VOICE_BATCH_MAX_ENTRIES) return null; + let total = VOICE_BATCH_HEADER_BYTES; + for (const entry of entries) { + if (!Number.isInteger(entry.codec) || entry.codec < 0 || entry.codec > 255 + || !Number.isInteger(entry.clientId) || entry.clientId < 1 || entry.clientId > 65_535 + || !Number.isInteger(entry.seq) || entry.seq < 0 || entry.seq > 255 + || entry.data.length < 1 || entry.data.length > VOICE_MAX_OPUS_FRAME_BYTES) return null; + total += 6 + entry.data.length; + if (total > VOICE_BATCH_MAX_BYTES) return null; + } + const out = new Uint8Array(total); + const view = new DataView(out.buffer, out.byteOffset, out.byteLength); + out[0] = VOICE_BATCH_TAG; + out[1] = entries.length; + view.setUint32(2, Math.max(0, Math.floor(audioStartMs)) >>> 0, false); + let offset = VOICE_BATCH_HEADER_BYTES; + for (const entry of entries) { + out[offset] = entry.codec; + view.setUint16(offset + 1, entry.clientId, false); + out[offset + 3] = entry.seq; + view.setUint16(offset + 4, entry.data.length, false); + out.set(entry.data, offset + 6); + offset += 6 + entry.data.length; + } + return out; +} + +/** Strict decoder; returns null for anything the encoder would not have produced. */ +export function decodeVoiceBatch(packet: Uint8Array): DecodedVoiceBatch | null { + if (packet.length < VOICE_BATCH_HEADER_BYTES + 7 || packet[0] !== VOICE_BATCH_TAG) return null; + const count = packet[1]!; + if (count < 1 || count > VOICE_BATCH_MAX_ENTRIES) return null; + const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength); + const audioStartMs = view.getUint32(2, false); + const entries: VoiceBatchEntry[] = []; + let offset = VOICE_BATCH_HEADER_BYTES; + for (let i = 0; i < count; i++) { + if (offset + 6 > packet.length) return null; + const codec = packet[offset]!; + const clientId = view.getUint16(offset + 1, false); + const seq = packet[offset + 3]!; + const length = view.getUint16(offset + 4, false); + if (clientId < 1 || length < 1 || length > VOICE_MAX_OPUS_FRAME_BYTES) return null; + const start = offset + 6; + const end = start + length; + if (end > packet.length) return null; + entries.push({ codec, clientId, seq, data: packet.subarray(start, end) }); + offset = end; + } + // Trailing bytes mean the sender and receiver disagree about the framing. + if (offset !== packet.length) return null; + return { audioStartMs, entries }; +} diff --git a/web/src/components/admin/AdminServerSettings.vue b/web/src/components/admin/AdminServerSettings.vue index 0e0bd0f..9279432 100644 --- a/web/src/components/admin/AdminServerSettings.vue +++ b/web/src/components/admin/AdminServerSettings.vue @@ -327,6 +327,27 @@ {{ tr('voiceApplyHint') }} +
+

{{ tr('voiceTuning') }}

{{ tr('voiceTuningLead') }}

+
+ +
+ + + {{ tr('voiceApplyHint') }} +

{{ tr('turnSettings') }}

{{ tr('turnLead') }}