mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-06 21:42:50 +08:00
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.
This commit is contained in:
1 parent
001457d004
commit
de16417474
44 files changed
+1605
-192
No files matched your search
+21
-1
@@ -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.
|
||||
@@ -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()` 解码器”的行为**。要完全回到旧行为,使用
|
||||
|
||||
+1
-1
@@ -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.
|
||||
|
||||
|
||||
@@ -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 候选
|
||||
|
||||
|
||||
+41
-15
@@ -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='<replace-with-demo-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 表现仍需设备测试。
|
||||
- 自动化测试和构建结果以本次审查的测试记录为准;历史报告中的通过数量
|
||||
|
||||
+1
-1
@@ -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",
|
||||
|
||||
@@ -622,6 +622,9 @@ function readSettingsInput(body: Record<string, unknown>): 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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(); }
|
||||
|
||||
@@ -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<PersistedSettings, "voiceProfile" | "voiceTurnUrls" | "voiceTurnSecretEncrypted" | "voiceTurnTtlSeconds" | "voiceOpusWs" | "voiceJitterMaxMs"> {
|
||||
private readVoiceSettings(): Pick<PersistedSettings, "voiceProfile" | "voiceTurnUrls" | "voiceTurnSecretEncrypted" | "voiceTurnTtlSeconds" | "voiceOpusWs" | "voiceJitterMaxMs" | "voiceDownlinkFrameMs" | "voiceAssumeCloudflare" | "voiceAutoRelayRetry"> {
|
||||
let value: Record<string, unknown> = {};
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,12 @@ export interface AudioFlowStats extends WebRtcAudioStats {
|
||||
egressSentMaxGapMs: number;
|
||||
egressPeakBufferedBytes: number;
|
||||
egressFramesByClient: Record<string, number>;
|
||||
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,
|
||||
|
||||
@@ -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]);
|
||||
});
|
||||
@@ -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<DownlinkBatcherOptions["subscribe"]>;
|
||||
private readonly onStats: DownlinkBatcherOptions["onStats"];
|
||||
private readonly queue: QueuedFrame[] = [];
|
||||
private readonly seqByClient = new Map<number, number>();
|
||||
private unsubscribe: (() => void) | null = null;
|
||||
private origin: number;
|
||||
private closed = false;
|
||||
private messages = 0;
|
||||
private entries = 0;
|
||||
private maxEntriesSeen = 0;
|
||||
private droppedFrames = 0;
|
||||
private peakQueuedFrames = 0;
|
||||
private peakQueuedMs = 0;
|
||||
private lateTicks = 0;
|
||||
|
||||
constructor(options: DownlinkBatcherOptions) {
|
||||
this.frameMs = options.frameMs === 40 ? 40 : 20;
|
||||
this.maxEntries = Math.max(1, Math.min(VOICE_BATCH_MAX_ENTRIES, options.maxEntries ?? 32));
|
||||
this.maxBytes = Math.max(1, Math.min(VOICE_BATCH_MAX_BYTES, options.maxBytes ?? VOICE_BATCH_MAX_BYTES));
|
||||
this.maxQueueMs = Math.max(this.frameMs, options.maxQueueMs ?? 100);
|
||||
this.maxQueueEntries = Math.max(1, options.maxQueueEntries ?? 64);
|
||||
this.now = options.now ?? (() => performance.now());
|
||||
this.origin = this.now();
|
||||
this.send = options.send;
|
||||
this.subscribe = options.subscribe ?? subscribeDownlink;
|
||||
this.onStats = options.onStats;
|
||||
this.arm();
|
||||
}
|
||||
|
||||
/** Returns false for a frame the encoder could not represent. */
|
||||
push(codec: number, clientId: number, data: Uint8Array): boolean {
|
||||
if (this.closed || data.length < 1 || data.length > VOICE_MAX_OPUS_FRAME_BYTES
|
||||
|| !Number.isInteger(codec) || codec < 0 || codec > 255
|
||||
|| !Number.isInteger(clientId) || clientId < 1 || clientId > 65_535) return false;
|
||||
const now = this.now();
|
||||
this.dropStale(now);
|
||||
while (this.queue.length >= this.maxQueueEntries) {
|
||||
this.queue.shift();
|
||||
this.droppedFrames++;
|
||||
}
|
||||
const seq = ((this.seqByClient.get(clientId) ?? 0) + 1) & 0xff;
|
||||
this.seqByClient.set(clientId, seq);
|
||||
// TeamSpeak's SDK may reuse its packet buffer; the queue can live for one
|
||||
// tick, so copy now rather than risk sending the next speaker's payload.
|
||||
this.queue.push({ codec, clientId, seq, data: Buffer.from(data), enqueuedAt: now });
|
||||
this.peakQueuedFrames = Math.max(this.peakQueuedFrames, this.queue.length);
|
||||
this.peakQueuedMs = Math.max(this.peakQueuedMs, this.oldestAge(now));
|
||||
this.emitStats();
|
||||
return true;
|
||||
}
|
||||
|
||||
setFrameMs(frameMs: 20 | 40): void {
|
||||
if (this.frameMs === frameMs || this.closed) return;
|
||||
// Drain under the old cadence before changing the clock bucket size.
|
||||
this.flush(this.now());
|
||||
this.frameMs = frameMs;
|
||||
this.origin = this.now();
|
||||
this.unsubscribe?.();
|
||||
this.unsubscribe = null;
|
||||
this.arm();
|
||||
}
|
||||
|
||||
/** Scheduler entry point; also used directly by tests with a synthetic tick. */
|
||||
flush(tickAt = this.now()): void {
|
||||
if (this.closed) return;
|
||||
const now = this.now();
|
||||
if (now - tickAt > LATE_TICK_MS) this.lateTicks++;
|
||||
this.dropStale(now);
|
||||
if (!this.queue.length) {
|
||||
this.emitStats();
|
||||
return;
|
||||
}
|
||||
|
||||
const sendGroup = (group: QueuedFrame[], bucket: number) => {
|
||||
const stamp = Math.max(0, this.origin + bucket * this.frameMs);
|
||||
let batch: QueuedFrame[] = [];
|
||||
let batchBytes = 6;
|
||||
const flushBatch = () => {
|
||||
if (!batch.length) return;
|
||||
const encoded = encodeVoiceBatch(stamp, batch);
|
||||
if (encoded) {
|
||||
this.messages++;
|
||||
this.entries += batch.length;
|
||||
this.maxEntriesSeen = Math.max(this.maxEntriesSeen, batch.length);
|
||||
try { this.send(encoded, batch.length, stamp); } catch { this.droppedFrames += batch.length; }
|
||||
} else {
|
||||
// Should be unreachable because push() bounds each frame and flush()
|
||||
// splits on the same limits; keep the queue honest if it happens.
|
||||
this.droppedFrames += batch.length;
|
||||
}
|
||||
batch = [];
|
||||
batchBytes = 6;
|
||||
};
|
||||
for (const frame of group) {
|
||||
const frameBytes = 6 + frame.data.length;
|
||||
if (batch.length && (batch.length >= this.maxEntries || batchBytes + frameBytes > this.maxBytes)) flushBatch();
|
||||
batch.push(frame);
|
||||
batchBytes += frameBytes;
|
||||
if (batch.length >= this.maxEntries || batchBytes >= this.maxBytes) flushBatch();
|
||||
}
|
||||
flushBatch();
|
||||
};
|
||||
|
||||
// A late timer can hold several ticks of frames. Keep each tick as its own
|
||||
// batch with its own audio timestamp: coalescing the whole backlog into one
|
||||
// stamp would hide the stall from the jitter estimator and stack every
|
||||
// speaker on the same playback instant.
|
||||
let group: QueuedFrame[] = [];
|
||||
let bucket = -1;
|
||||
for (const frame of this.queue) {
|
||||
const frameBucket = Math.floor((frame.enqueuedAt - this.origin) / this.frameMs);
|
||||
if (group.length && frameBucket !== bucket) {
|
||||
sendGroup(group, bucket);
|
||||
group = [];
|
||||
}
|
||||
bucket = frameBucket;
|
||||
group.push(frame);
|
||||
}
|
||||
if (group.length) sendGroup(group, bucket);
|
||||
this.queue.length = 0;
|
||||
this.emitStats();
|
||||
}
|
||||
|
||||
getStats(): DownlinkBatchStats {
|
||||
return {
|
||||
messages: this.messages,
|
||||
entries: this.entries,
|
||||
maxEntries: this.maxEntriesSeen,
|
||||
droppedFrames: this.droppedFrames,
|
||||
peakQueuedFrames: this.peakQueuedFrames,
|
||||
peakQueuedMs: this.peakQueuedMs,
|
||||
lateTicks: this.lateTicks,
|
||||
};
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
this.unsubscribe?.();
|
||||
this.unsubscribe = null;
|
||||
this.queue.length = 0;
|
||||
this.emitStats();
|
||||
}
|
||||
|
||||
private arm(): void {
|
||||
this.unsubscribe = this.subscribe(this.frameMs, tickAt => this.flush(tickAt));
|
||||
}
|
||||
|
||||
private dropStale(now: number): void {
|
||||
while (this.queue.length && now - this.queue[0]!.enqueuedAt > this.maxQueueMs) {
|
||||
this.queue.shift();
|
||||
this.droppedFrames++;
|
||||
}
|
||||
}
|
||||
|
||||
private oldestAge(now: number): number {
|
||||
return this.queue.length ? Math.max(0, now - this.queue[0]!.enqueuedAt) : 0;
|
||||
}
|
||||
|
||||
private emitStats(): void {
|
||||
this.onStats?.(this.getStats());
|
||||
}
|
||||
}
|
||||
@@ -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<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();
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
+88
-19
@@ -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<string, number>();
|
||||
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 */ }
|
||||
|
||||
@@ -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<Record<string, unknown>>(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<Record<string, unknown>>(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<Record<string, unknown>>(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<Record<string, unknown>>(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" },
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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" };
|
||||
|
||||
@@ -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 } : {}),
|
||||
|
||||
@@ -24,6 +24,7 @@ const samples: Record<ServerMessage["type"], ServerMessage> = {
|
||||
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 },
|
||||
|
||||
@@ -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<ServerMessage["type"], (message: RecordValue) => 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<ServerMessage["type"], (message: RecordValue) => 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),
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -327,6 +327,27 @@
|
||||
</div>
|
||||
<small class="field-help">{{ tr('voiceApplyHint') }}</small>
|
||||
</section>
|
||||
<section class="settings-subsection voice-tuning-card">
|
||||
<header class="settings-subsection-heading"><div><h4>{{ tr('voiceTuning') }}</h4><p class="card-help">{{ tr('voiceTuningLead') }}</p></div></header>
|
||||
<div class="voice-fields">
|
||||
<label><span>{{ tr('voiceDownlinkFrameMs') }}</span>
|
||||
<select v-model.number="serverForm.voiceDownlinkFrameMs" :disabled="serverForm.voiceProfile === 'legacy'">
|
||||
<option :value="20">20 ms</option>
|
||||
<option :value="40">40 ms</option>
|
||||
</select>
|
||||
<small class="field-help">{{ tr('voiceDownlinkFrameLead') }}</small>
|
||||
</label>
|
||||
</div>
|
||||
<label class="choice toggle-choice" :class="{ selected: serverForm.voiceAutoRelayRetry }">
|
||||
<input v-model="serverForm.voiceAutoRelayRetry" type="checkbox" />
|
||||
<span><strong>{{ tr('voiceAutoRelayRetry') }}</strong><small>{{ tr('voiceAutoRelayRetryLead') }}</small></span>
|
||||
</label>
|
||||
<label class="choice toggle-choice" :class="{ selected: serverForm.voiceAssumeCloudflare }">
|
||||
<input v-model="serverForm.voiceAssumeCloudflare" type="checkbox" />
|
||||
<span><strong>{{ tr('voiceAssumeCloudflare') }}</strong><small>{{ tr('voiceAssumeCloudflareLead') }}</small></span>
|
||||
</label>
|
||||
<small class="field-help">{{ tr('voiceApplyHint') }}</small>
|
||||
</section>
|
||||
<section class="settings-subsection turn-card">
|
||||
<header class="settings-subsection-heading"><div><h4>{{ tr('turnSettings') }}</h4><p class="card-help">{{ tr('turnLead') }}</p></div></header>
|
||||
<label class="webrtc-network-field">
|
||||
|
||||
@@ -40,6 +40,8 @@ const errorLabels: Record<string, AdminTranslationKey> = {
|
||||
INVALID_VOICE_PROFILE: "invalidVoiceProfileError", INVALID_VOICE_TURN_URLS: "invalidVoiceTurnUrlsError",
|
||||
INVALID_VOICE_TURN_SECRET: "invalidVoiceTurnSecretError", INVALID_VOICE_TURN_TTL: "invalidVoiceTurnTtlError",
|
||||
INVALID_VOICE_OPUS: "invalidVoiceSettingsError", INVALID_VOICE_JITTER_MAX: "invalidVoiceJitterError",
|
||||
INVALID_VOICE_FRAME_MS: "invalidVoiceFrameMsError", INVALID_VOICE_ASSUME_CLOUDFLARE: "invalidVoiceSettingsError",
|
||||
INVALID_VOICE_AUTO_RELAY_RETRY: "invalidVoiceSettingsError",
|
||||
INVALID_RELAY_NAME: "invalidRelayNameError", INVALID_RELAY_TARGET: "invalidRelayTargetError", INVALID_RELAY_VOICE_ENDPOINT: "invalidRelayVoiceEndpointError", INVALID_RELAY_TOKEN: "invalidRelayTokenError",
|
||||
INVALID_TARGET: "invalidTargetError", PING_UNAVAILABLE: "icmpUnavailableError", HOST_NOT_FOUND: "probeHostNotFoundError",
|
||||
UNREACHABLE: "probeUnreachableError", TIMEOUT: "probeTimeoutError", PROTOCOL_NEGOTIATION_FAILED: "probeProtocolError",
|
||||
|
||||
@@ -16,11 +16,12 @@ function emptyForm() {
|
||||
accessMode: "fixed" as "fixed" | "open", siteName: "WebSpeak", welcomeText: "", welcomeTextEn: "", welcomeTextDe: "", welcomeTextRu: "", welcomeTextJa: "",
|
||||
welcomeDefaults: { ...DEFAULT_WELCOME_TEXTS }, webRtcPublicHost: "", webRtcIpv6Enabled: false, webRtcStunServer: "", webRtcEnabled: false, webRtcUdpStart: 40000, webRtcUdpEnd: 40099,
|
||||
voiceProfile: "auto" as "auto" | "legacy" | "adaptive", voiceTurnUrls: "", voiceTurnSecret: "", voiceTurnSecretAction: "keep" as SecretAction,
|
||||
hasVoiceTurnSecret: false, voiceTurnTtlSeconds: 21600, voiceOpusWs: false, voiceJitterMaxMs: 300,
|
||||
hasVoiceTurnSecret: false, voiceTurnTtlSeconds: 21600, voiceOpusWs: true, voiceJitterMaxMs: 300,
|
||||
voiceDownlinkFrameMs: 20 as 20 | 40, voiceAssumeCloudflare: false, voiceAutoRelayRetry: true,
|
||||
relayNodes: [] as RelayNodeForm[], lastTestAt: null as string | null, lastTestLatencyMs: null as number | null };
|
||||
}
|
||||
type ServerForm = ReturnType<typeof emptyForm>;
|
||||
const editable = ["address", "port", "accessMode", "siteName", "welcomeText", "welcomeTextEn", "welcomeTextDe", "welcomeTextRu", "welcomeTextJa", "webRtcEnabled", "webRtcPublicHost", "webRtcIpv6Enabled", "webRtcStunServer", "webRtcUdpStart", "webRtcUdpEnd", "voiceProfile", "voiceTurnUrls", "voiceTurnTtlSeconds", "voiceOpusWs", "voiceJitterMaxMs"] as const;
|
||||
const editable = ["address", "port", "accessMode", "siteName", "welcomeText", "welcomeTextEn", "welcomeTextDe", "welcomeTextRu", "welcomeTextJa", "webRtcEnabled", "webRtcPublicHost", "webRtcIpv6Enabled", "webRtcStunServer", "webRtcUdpStart", "webRtcUdpEnd", "voiceProfile", "voiceTurnUrls", "voiceTurnTtlSeconds", "voiceOpusWs", "voiceJitterMaxMs", "voiceDownlinkFrameMs", "voiceAssumeCloudflare", "voiceAutoRelayRetry"] as const;
|
||||
const snapshot = (form: ServerForm): ServerForm => JSON.parse(JSON.stringify(form));
|
||||
|
||||
export function useAdminServerSettings(options: Options) {
|
||||
@@ -116,7 +117,7 @@ export function useAdminServerSettings(options: Options) {
|
||||
relayNodes: serverForm.relayNodes.map(node => ({ id: node.id, name: node.name, target: node.target, voiceEndpoint: node.voiceEndpoint, enabled: node.enabled, tokenAction: node.tokenAction, ...(node.tokenAction === "replace" ? { token: node.token } : {}) })) };
|
||||
const saved = savedSettings.value;
|
||||
if (saved) {
|
||||
for (const key of ["voiceProfile", "voiceTurnUrls", "voiceTurnTtlSeconds", "voiceOpusWs", "voiceJitterMaxMs"] as const) {
|
||||
for (const key of ["voiceProfile", "voiceTurnUrls", "voiceTurnTtlSeconds", "voiceOpusWs", "voiceJitterMaxMs", "voiceDownlinkFrameMs", "voiceAssumeCloudflare", "voiceAutoRelayRetry"] as const) {
|
||||
if (serverForm[key] !== saved[key]) Object.assign(payload, { [key]: serverForm[key] });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,10 +15,12 @@ export type { AudioPermission, BrowserVoiceAudioStats, VoiceAudioStatusSample }
|
||||
import type { SinkAudioElement } from "../voice/webrtc-playback.js";
|
||||
import { createScreenShareController } from "../voice/screen-share.js";
|
||||
import type { VoiceIceServer, VoiceIceTransportPolicy } from "../../../src/shared/voice-ice.js";
|
||||
import { hasVoiceTurnServer } from "../../../src/shared/voice-ice.js";
|
||||
import { createOpusUplink } from "../voice/opus-uplink.js";
|
||||
import { requestMediaBeforeAudioResume } from "../services/microphone-start.js";
|
||||
export type { ScreenShareOutputSettings, ScreenShareCaptureStats, ScreenSharePeerStats, ScreenShareWebRtcStats } from "../voice/screen-share.js";
|
||||
import { parseServerMessage } from "../../../src/shared/server-messages.js";
|
||||
import { decodeVoiceBatch, VOICE_BATCH_TAG } from "../../../src/shared/voice-audio.js";
|
||||
import type { ChatMessage } from "../../../src/shared/voice-models.js";
|
||||
import type { ClientCommandPayloads, ClientCommandType } from "../../../src/shared/client-commands.js";
|
||||
export type { ScreenShareStreamDescription as ScreenShareStream, ScreenShareViewerDescription as ScreenShareViewer, ScreenSharePeerSignal as ScreenShareSignal } from "../../../src/shared/screen-share.js";
|
||||
@@ -333,16 +335,18 @@ export function useVoiceWebSocket() {
|
||||
const whisperActive = ref(false);
|
||||
const speakingTimers = new Map<number, ReturnType<typeof setTimeout>>();
|
||||
const SPEAKING_HOLD_MS = 360;
|
||||
const AUDIO_FRAME_SAMPLES = 960;
|
||||
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
|
||||
const AUDIO_FRAME_SAMPLES_20 = 960;
|
||||
const AUDIO_FRAME_BYTES_20 = AUDIO_FRAME_SAMPLES_20 * 2;
|
||||
let audioFrameSamples = AUDIO_FRAME_SAMPLES_20;
|
||||
let audioFrameBytes = AUDIO_FRAME_BYTES_20;
|
||||
const LEGACY_AUDIO_BUFFERED_FRAMES = 10;
|
||||
const ADAPTIVE_AUDIO_BUFFERED_FRAMES = 15;
|
||||
let maxAudioBufferedFrames = LEGACY_AUDIO_BUFFERED_FRAMES;
|
||||
let maxAudioBufferedBytes = AUDIO_FRAME_BYTES * maxAudioBufferedFrames;
|
||||
let maxAudioBufferedBytes = audioFrameBytes * maxAudioBufferedFrames;
|
||||
const MAX_OPUS_BUFFERED_BYTES = 4_096;
|
||||
let voiceProfile: "legacy" | "adaptive" = "legacy";
|
||||
let audioJitterMaxMs = 80;
|
||||
let audioFrameVersion = 1;
|
||||
let audioFrameMs: 20 | 40 = 20;
|
||||
let audioUplinkCodecs: ("pcm" | "opus")[] = ["pcm"];
|
||||
const remotePlayback = createRemotePlayback({
|
||||
getContext: getAudioCtx,
|
||||
@@ -357,6 +361,10 @@ export function useVoiceWebSocket() {
|
||||
let webRtcFailed = false;
|
||||
let voiceIceServers: VoiceIceServer[] = [];
|
||||
let voiceIceTransportPolicy: VoiceIceTransportPolicy = "all";
|
||||
let voiceIceTransportPolicyBase: VoiceIceTransportPolicy = "all";
|
||||
let voiceAutoRelayRetry = true;
|
||||
let webRtcRetryCount = 0;
|
||||
let webRtcRetryTimer: number | null = null;
|
||||
const webrtc = createWebRtcTransport({
|
||||
stunServer: () => webRtcStunServer,
|
||||
iceServers: () => voiceIceServers,
|
||||
@@ -376,12 +384,19 @@ export function useVoiceWebSocket() {
|
||||
else if (state.tsClientId) clearSpeaking(state.tsClientId);
|
||||
},
|
||||
onReady() {
|
||||
const switchingFromCompatibility = webRtcFailed;
|
||||
// An automatic relay retry succeeds while `webRtcFailed` is still false;
|
||||
// compatibility playback has been running during the retry and must be
|
||||
// stopped here as well, or WebRTC and WebSocket audio would mix.
|
||||
const switchingFromCompatibility = webRtcFailed || webRtcRetryCount > 0;
|
||||
webRtcFailed = false;
|
||||
state.webrtcReconnecting = false;
|
||||
webRtcRetryCount = 0;
|
||||
if (webRtcRetryTimer !== null) window.clearTimeout(webRtcRetryTimer);
|
||||
webRtcRetryTimer = null;
|
||||
stopCaptureGraph();
|
||||
if (switchingFromCompatibility) remotePlayback.clearAll();
|
||||
clearAudioNotice("WEBRTC_FAILED");
|
||||
clearAudioNotice("WEBRTC_RETRYING");
|
||||
sessionTrace.record("webrtc.media", { state: "active" });
|
||||
syncWebRtcMemberVolumes();
|
||||
},
|
||||
@@ -392,12 +407,46 @@ export function useVoiceWebSocket() {
|
||||
async onFailure(reason, isCurrent) {
|
||||
if (!isCurrent()) return;
|
||||
const switchingFromWebRtc = !webRtcFailed;
|
||||
webRtcFailed = true;
|
||||
state.webrtcReconnecting = false;
|
||||
const code = safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE";
|
||||
sessionTrace.record("webrtc.failed", { code });
|
||||
if (switchingFromWebRtc) remotePlayback.clearAll();
|
||||
resumeCompatibilityCapture();
|
||||
// Direct UDP through a tunnel often fails without an ICE failure event
|
||||
// that names the cause. If a TURN server is configured, make one
|
||||
// automatic relay-only attempt while compatibility audio keeps playing.
|
||||
if (!webRtcFailed && webRtcRetryCount < 1 && voiceAutoRelayRetry
|
||||
&& voiceIceTransportPolicy !== "relay" && hasVoiceTurnServer(voiceIceServers)) {
|
||||
webRtcRetryCount++;
|
||||
voiceIceTransportPolicy = "relay";
|
||||
state.webrtcReconnecting = true;
|
||||
setAudioNotice("WEBRTC_RETRYING", "实时语音直连失败,正在通过 TURN 中继重试;兼容音频会继续播放");
|
||||
sessionTrace.record("webrtc.relay-retry", { code });
|
||||
if (webRtcRetryTimer !== null) window.clearTimeout(webRtcRetryTimer);
|
||||
webRtcRetryTimer = window.setTimeout(() => {
|
||||
webRtcRetryTimer = null;
|
||||
const socket = ws.value;
|
||||
if (!state.connected || !socket || socket.readyState !== WebSocket.OPEN) return;
|
||||
void startWebRtcTransport(voiceConnection.generation, socket).catch(error => {
|
||||
state.webrtcReconnecting = false;
|
||||
if (!state.connected) return;
|
||||
// `webrtc.start` can reject before it ever reports onFailure
|
||||
// (microphone permission, missing device, ICE setup). Without
|
||||
// settling the retry state here the banner would stay on
|
||||
// "retrying" forever while compatibility audio keeps playing.
|
||||
webRtcFailed = true;
|
||||
clearAudioNotice("WEBRTC_RETRYING");
|
||||
const retryCode = safeClientErrorCode(error) || "WEBRTC_UNAVAILABLE";
|
||||
setAudioNotice("WEBRTC_FAILED", webRtcFailureMessage(retryCode));
|
||||
setMicrophoneError(error);
|
||||
});
|
||||
}, 3_000);
|
||||
return;
|
||||
}
|
||||
webRtcFailed = true;
|
||||
state.webrtcReconnecting = false;
|
||||
if (webRtcRetryTimer !== null) window.clearTimeout(webRtcRetryTimer);
|
||||
webRtcRetryTimer = null;
|
||||
clearAudioNotice("WEBRTC_RETRYING");
|
||||
setAudioNotice("WEBRTC_FAILED", webRtcFailureMessage(code));
|
||||
},
|
||||
playback: {
|
||||
@@ -752,9 +801,9 @@ export function useVoiceWebSocket() {
|
||||
accumLen = need;
|
||||
|
||||
let offset = 0;
|
||||
while (offset + AUDIO_FRAME_SAMPLES <= accumLen && socket.readyState === WebSocket.OPEN && socket.bufferedAmount <= maxAudioBufferedBytes) {
|
||||
socket.send(accumBuf.slice(offset, offset + AUDIO_FRAME_SAMPLES).buffer);
|
||||
offset += AUDIO_FRAME_SAMPLES;
|
||||
while (offset + audioFrameSamples <= accumLen && socket.readyState === WebSocket.OPEN && socket.bufferedAmount <= maxAudioBufferedBytes) {
|
||||
socket.send(accumBuf.slice(offset, offset + audioFrameSamples).buffer);
|
||||
offset += audioFrameSamples;
|
||||
}
|
||||
if (offset > 0) markSpeaking(state.tsClientId);
|
||||
accumLen -= offset;
|
||||
@@ -1136,6 +1185,11 @@ export function useVoiceWebSocket() {
|
||||
microphoneTest.dispose();
|
||||
audioDiagnostics.reset();
|
||||
commands.clear(new Error("语音连接已关闭"));
|
||||
if (webRtcRetryTimer !== null) window.clearTimeout(webRtcRetryTimer);
|
||||
webRtcRetryTimer = null;
|
||||
webRtcRetryCount = 0;
|
||||
voiceAutoRelayRetry = true;
|
||||
voiceIceTransportPolicyBase = "all";
|
||||
screenShare.stopTransport(sendScreenStop);
|
||||
webrtc.stop();
|
||||
remotePlayback.clearAll();
|
||||
@@ -1146,9 +1200,11 @@ export function useVoiceWebSocket() {
|
||||
voiceIceTransportPolicy = "all";
|
||||
voiceProfile = "legacy";
|
||||
maxAudioBufferedFrames = LEGACY_AUDIO_BUFFERED_FRAMES;
|
||||
maxAudioBufferedBytes = AUDIO_FRAME_BYTES * maxAudioBufferedFrames;
|
||||
audioFrameSamples = AUDIO_FRAME_SAMPLES_20;
|
||||
audioFrameBytes = AUDIO_FRAME_BYTES_20;
|
||||
maxAudioBufferedBytes = audioFrameBytes * maxAudioBufferedFrames;
|
||||
audioJitterMaxMs = 80;
|
||||
audioFrameVersion = 1;
|
||||
audioFrameMs = 20;
|
||||
audioUplinkCodecs = ["pcm"];
|
||||
opusUplink.disable();
|
||||
opusStreamOpen = false;
|
||||
@@ -1195,13 +1251,28 @@ export function useVoiceWebSocket() {
|
||||
webRtcStunServer = msg.webRtcStunServer ?? "";
|
||||
voiceIceServers = msg.voiceIceServers ?? [];
|
||||
voiceIceTransportPolicy = msg.voiceIceTransportPolicy ?? "all";
|
||||
voiceIceTransportPolicyBase = voiceIceTransportPolicy;
|
||||
voiceAutoRelayRetry = msg.voiceRelayAutoRetry !== false;
|
||||
webRtcRetryCount = 0;
|
||||
if (webRtcRetryTimer !== null) window.clearTimeout(webRtcRetryTimer);
|
||||
webRtcRetryTimer = null;
|
||||
clearAudioNotice("WEBRTC_RETRYING");
|
||||
voiceProfile = msg.voiceProfile ?? "legacy";
|
||||
const adaptiveProfile = voiceProfile === "adaptive";
|
||||
maxAudioBufferedFrames = adaptiveProfile ? ADAPTIVE_AUDIO_BUFFERED_FRAMES : LEGACY_AUDIO_BUFFERED_FRAMES;
|
||||
maxAudioBufferedBytes = AUDIO_FRAME_BYTES * maxAudioBufferedFrames;
|
||||
audioFrameSamples = AUDIO_FRAME_SAMPLES_20;
|
||||
audioFrameBytes = AUDIO_FRAME_BYTES_20;
|
||||
maxAudioBufferedBytes = audioFrameBytes * maxAudioBufferedFrames;
|
||||
audioJitterMaxMs = adaptiveProfile ? (msg.audioJitterMaxMs ?? 300) : 80;
|
||||
audioFrameVersion = msg.audioFrameVersion ?? 1;
|
||||
audioFrameMs = 20;
|
||||
audioUplinkCodecs = adaptiveProfile ? (msg.audioUplinkCodecs ?? ["pcm"]) : ["pcm"];
|
||||
if (adaptiveProfile && msg.audioDownlinkVersions?.includes(3)) {
|
||||
sendCmd("audioCaps", {
|
||||
downlinkVersion: 3,
|
||||
maxFrameMs: 40,
|
||||
codecs: audioUplinkCodecs.includes("opus") ? ["pcm", "opus"] : ["pcm"],
|
||||
});
|
||||
}
|
||||
if (adaptiveProfile && audioUplinkCodecs.includes("opus")) {
|
||||
void opusUplink.init().then(active => sessionTrace.record("audio.opus", { state: active ? "active" : "pcm-fallback" }));
|
||||
} else {
|
||||
@@ -1234,6 +1305,15 @@ export function useVoiceWebSocket() {
|
||||
state.error = "";
|
||||
state.errorCode = "";
|
||||
break;
|
||||
case "audioConfig": {
|
||||
audioFrameMs = msg.frameMs === 40 ? 40 : 20;
|
||||
audioFrameSamples = audioFrameMs * 48;
|
||||
audioFrameBytes = audioFrameSamples * 2;
|
||||
maxAudioBufferedBytes = audioFrameBytes * maxAudioBufferedFrames;
|
||||
audioJitterMaxMs = msg.jitterMaxMs;
|
||||
audioUplinkCodecs = msg.uplinkCodecs;
|
||||
break;
|
||||
}
|
||||
case "audioStats": {
|
||||
const sequence = typeof msg.sequence === "string" ? msg.sequence : "";
|
||||
audioDiagnostics.receive(sequence, msg.stats);
|
||||
@@ -1338,6 +1418,27 @@ export function useVoiceWebSocket() {
|
||||
audioDiagnostics.count("framesDropped");
|
||||
return;
|
||||
}
|
||||
if (data[0] === VOICE_BATCH_TAG) {
|
||||
const batch = decodeVoiceBatch(data);
|
||||
if (!batch) {
|
||||
audioDiagnostics.count("framesDropped");
|
||||
return;
|
||||
}
|
||||
for (const entry of batch.entries) {
|
||||
if (entry.clientId === state.tsClientId) continue;
|
||||
if (entry.codec !== 4 && entry.codec !== 5) {
|
||||
audioDiagnostics.count("framesDropped");
|
||||
continue;
|
||||
}
|
||||
audioDiagnostics.count("framesReceived");
|
||||
markSpeaking(entry.clientId);
|
||||
remotePlayback.play(entry.clientId, entry.codec, entry.data, {
|
||||
audioStartMs: batch.audioStartMs,
|
||||
seq: entry.seq,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
const clientId = (data[1] << 8) | data[2];
|
||||
const codec = data[0];
|
||||
if (clientId === state.tsClientId) return;
|
||||
@@ -1469,6 +1570,12 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
const sequence = voiceConnection.generation;
|
||||
state.webrtcReconnecting = true;
|
||||
// A manual retry starts from the configured policy (direct first) instead
|
||||
// of inheriting the previous automatic relay attempt.
|
||||
voiceIceTransportPolicy = voiceIceTransportPolicyBase;
|
||||
webRtcRetryCount = 0;
|
||||
if (webRtcRetryTimer !== null) window.clearTimeout(webRtcRetryTimer);
|
||||
webRtcRetryTimer = null;
|
||||
clearMicrophoneError();
|
||||
if (webRtcFailed) resumeCompatibilityCapture();
|
||||
try {
|
||||
|
||||
@@ -232,6 +232,12 @@ function localizedAudioNotice(code: string, message: string) {
|
||||
? message.match(/错误代码:([A-Z0-9_-]{1,64})/)?.[1] ?? normalizedCode
|
||||
: normalizedCode;
|
||||
const messages: Record<string, { en: string; de: string; ru: string; ja: string }> = {
|
||||
WEBRTC_RETRYING: {
|
||||
en: "The direct WebRTC path failed; retrying through TURN in a few seconds. Compatibility audio keeps playing",
|
||||
de: "Der direkte WebRTC-Weg ist fehlgeschlagen; in wenigen Sekunden wird über TURN erneut versucht. Kompatibilitätsaudio läuft weiter",
|
||||
ru: "Прямой путь WebRTC не удался; через несколько секунд будет выполнена повторная попытка через TURN. Совместимое аудио продолжает работать",
|
||||
ja: "WebRTC の直接経路に失敗しました。数秒後に TURN 経由で再試行します。互換オーディオは継続します",
|
||||
},
|
||||
WEBRTC_FAILED: {
|
||||
en: `WebRTC realtime voice is unavailable (error code: ${webRtcReason}). Compatibility audio (PCM/Opus over WebSocket) is active to keep this voice session working; use “Reconnect WebRTC” to try again`,
|
||||
de: `Echtzeitstimme über WebRTC ist nicht verfügbar (Fehlercode: ${webRtcReason}). Der kompatible Audioweg (PCM/Opus über WebSocket) ist aktiv, damit diese Sprachsitzung bestehen bleibt; klicke auf „WebRTC neu verbinden“, um es erneut zu versuchen`,
|
||||
|
||||
+55
-10
@@ -229,9 +229,17 @@ export const copy = {
|
||||
voiceProfileAdaptive: "自适应",
|
||||
voiceProfileAdaptiveLead: "启用自适应 jitter buffer、20ms pacer 和新帧协议。Cloudflare Tunnel 或明显抖动的网络优先使用。",
|
||||
voiceOpusWs: "兼容模式使用 Opus",
|
||||
voiceOpusWsLead: "仅在自适应模式生效;显式启用后浏览器可上传 Opus,减少带宽。默认关闭。",
|
||||
voiceOpusWsLead: "仅在自适应模式生效;开启后浏览器可用 WebCodecs 上传 Opus,编码失败自动回退 PCM。默认开启(auto)。",
|
||||
voiceJitterMaxMs: "自适应 jitter 上限",
|
||||
voiceJitterLead: "80–500 ms。只限制缓冲上限;调低不能恢复旧版超限 clear() 行为。",
|
||||
voiceTuning: "兼容模式调优",
|
||||
voiceTuningLead: "Cloudflare Tunnel 下的批量下行、TURN 重试和入口识别。默认值适合大多数部署。",
|
||||
voiceDownlinkFrameMs: "兼容模式帧长",
|
||||
voiceDownlinkFrameLead: "20 ms 延迟更低;40 ms 下行消息减半,上行 PCM 也按 40 ms 打包并由服务端拆成 20 ms 发送,每个说话人最多多等 20 ms。",
|
||||
voiceAutoRelayRetry: "直连失败后自动 TURN 重试",
|
||||
voiceAutoRelayRetryLead: "仅在配置了 TURN 时生效;首次直连失败约 3 秒后自动改用 relay,兼容音频不中断。",
|
||||
voiceAssumeCloudflare: "入口强制按 Cloudflare 处理",
|
||||
voiceAssumeCloudflareLead: "反向代理清掉 cf-ray 等头、但实际仍走 Cloudflare Tunnel 时开启;会启用自适应路径并禁用 Host 回退媒体地址。",
|
||||
voiceApplyHint: "语音模式与 TURN 配置保存后对新的语音连接生效,不需要重启网关。",
|
||||
turnSettings: "TURN 后备",
|
||||
turnLead: "直连 UDP 不通时,浏览器再使用 TURN 中继;不要把它当作默认路径。",
|
||||
@@ -249,7 +257,8 @@ export const copy = {
|
||||
invalidVoiceTurnSecretError: "TURN 共享密钥无效:至少 16 个字符,且配置 TURN 地址时必须填写。",
|
||||
invalidVoiceTurnTtlError: "TURN 凭证有效期应为 300–86400 秒。",
|
||||
invalidVoiceJitterError: "自适应 jitter 上限应为 80–500 毫秒。",
|
||||
invalidVoiceSettingsError: "语音高级设置无效,请检查 Opus 开关和 jitter 上限。",
|
||||
invalidVoiceFrameMsError: "下行批量帧长只能是 20 或 40 毫秒。",
|
||||
invalidVoiceSettingsError: "语音高级设置无效,请检查 Opus、帧长、Cloudflare 入口识别和自动重试开关。",
|
||||
relaySettings: "中继服务器",
|
||||
relaySettingsLead: "配置访客连接使用的中继节点;名称会显示在首页加速选项中。",
|
||||
relayEnabled: "启用中继加速",
|
||||
@@ -603,9 +612,17 @@ export const copy = {
|
||||
voiceProfileAdaptive: "Adaptive",
|
||||
voiceProfileAdaptiveLead: "Enables the adaptive jitter buffer, 20 ms pacer, and new frame protocol. Prefer it for Cloudflare Tunnel or networks with noticeable jitter.",
|
||||
voiceOpusWs: "Use Opus in compatibility mode",
|
||||
voiceOpusWsLead: "Only effective in adaptive mode. When explicitly enabled, browsers may upload Opus to reduce bandwidth. Off by default.",
|
||||
voiceOpusWsLead: "Only effective in adaptive mode. Browsers with WebCodecs upload 24 kbps Opus and fall back to PCM if encoding fails. On by default (auto).",
|
||||
voiceJitterMaxMs: "Adaptive jitter limit",
|
||||
voiceJitterLead: "80–500 ms. This only caps buffering; lowering it does not restore the legacy clear() overrun behavior.",
|
||||
voiceTuning: "Compatibility tuning",
|
||||
voiceTuningLead: "Batched downlink, TURN retry and ingress detection for Cloudflare Tunnel. Defaults suit most deployments.",
|
||||
voiceDownlinkFrameMs: "Compatibility frame size",
|
||||
voiceDownlinkFrameLead: "20 ms has lower latency; 40 ms halves downlink messages and also batches uplink PCM into 40 ms (the server splits it back to 20 ms), adding up to 20 ms per speaker.",
|
||||
voiceAutoRelayRetry: "Automatic TURN retry after direct failure",
|
||||
voiceAutoRelayRetryLead: "Only when TURN is configured. After the first direct failure it retries relay-only in about 3 s while compatibility audio continues.",
|
||||
voiceAssumeCloudflare: "Treat every ingress as Cloudflare",
|
||||
voiceAssumeCloudflareLead: "Enable when a reverse proxy strips cf-ray and similar headers but traffic still uses Cloudflare Tunnel; enables the adaptive path and disables Host fallback for the media address.",
|
||||
voiceApplyHint: "Voice mode and TURN settings apply to new voice connections after saving; no gateway restart is required.",
|
||||
turnSettings: "TURN fallback",
|
||||
turnLead: "Browsers use TURN relay only when direct UDP fails; do not treat it as the default path.",
|
||||
@@ -623,7 +640,8 @@ export const copy = {
|
||||
invalidVoiceTurnSecretError: "Invalid TURN shared secret: at least 16 characters, and required when TURN URLs are configured.",
|
||||
invalidVoiceTurnTtlError: "TURN credential lifetime must be between 300 and 86400 seconds.",
|
||||
invalidVoiceJitterError: "Adaptive jitter limit must be between 80 and 500 ms.",
|
||||
invalidVoiceSettingsError: "Invalid advanced voice settings. Check the Opus switch and jitter limit.",
|
||||
invalidVoiceFrameMsError: "Downlink batch frame must be 20 or 40 ms.",
|
||||
invalidVoiceSettingsError: "Invalid advanced voice settings. Check Opus, frame size, Cloudflare ingress detection and automatic retry.",
|
||||
relaySettings: "Relay server",
|
||||
relaySettingsLead: "Configure the relay used by accelerated guest connections; its name is shown on the welcome page.",
|
||||
relayEnabled: "Enable relay acceleration",
|
||||
@@ -785,9 +803,17 @@ export const germanCopy = {
|
||||
voiceProfileAdaptive: "Adaptiv",
|
||||
voiceProfileAdaptiveLead: "Aktiviert adaptiven Jitter-Puffer, 20-ms-Pacer und das neue Frame-Protokoll. Bevorzugt für Cloudflare Tunnel oder Netze mit merklichem Jitter.",
|
||||
voiceOpusWs: "Opus im Kompatibilitätsmodus",
|
||||
voiceOpusWsLead: "Nur im adaptiven Modus wirksam. Wenn ausdrücklich aktiviert, können Browser Opus hochladen, um Bandbreite zu sparen. Standardmäßig aus.",
|
||||
voiceOpusWsLead: "Nur im adaptiven Modus wirksam. Browser mit WebCodecs laden 24-kbps-Opus hoch und fallen bei Kodierungsfehlern auf PCM zurück. Standardmäßig an (auto).",
|
||||
voiceJitterMaxMs: "Adaptives Jitter-Limit",
|
||||
voiceJitterLead: "80–500 ms. Begrenzt nur den Puffer; ein niedrigerer Wert stellt das alte clear()-Verhalten bei Überlauf nicht wieder her.",
|
||||
voiceTuning: "Kompatibilitäts-Tuning",
|
||||
voiceTuningLead: "Batch-Downlink, TURN-Wiederholung und Eingangserkennung für Cloudflare Tunnel. Die Standardwerte passen für die meisten Deployments.",
|
||||
voiceDownlinkFrameMs: "Kompatibilitäts-Framegröße",
|
||||
voiceDownlinkFrameLead: "20 ms ist latenzärmer; 40 ms halbiert die Downlink-Nachrichten und bündelt auch Uplink-PCM in 40-ms-Pakete (der Server teilt sie wieder in 20 ms), was pro Sprecher bis zu 20 ms hinzufügt.",
|
||||
voiceAutoRelayRetry: "Automatische TURN-Wiederholung nach Direktfehler",
|
||||
voiceAutoRelayRetryLead: "Nur mit konfiguriertem TURN. Nach dem ersten Direktfehler wird nach etwa 3 s relay-only erneut versucht; Kompatibilitätsaudio läuft weiter.",
|
||||
voiceAssumeCloudflare: "Jeden Eingang als Cloudflare behandeln",
|
||||
voiceAssumeCloudflareLead: "Aktivieren, wenn ein Reverse-Proxy cf-ray und ähnliche Header entfernt, der Verkehr aber weiterhin über Cloudflare Tunnel läuft; aktiviert den adaptiven Pfad und deaktiviert den Host-Fallback für die Medienadresse.",
|
||||
voiceApplyHint: "Sprachmodus und TURN-Einstellungen gelten nach dem Speichern für neue Sprachverbindungen; ein Neustart des Gateways ist nicht erforderlich.",
|
||||
turnSettings: "TURN-Ausweichweg",
|
||||
turnLead: "Browser nutzen TURN nur, wenn direkter UDP-Verkehr fehlschlägt; nicht als Standardweg verwenden.",
|
||||
@@ -805,7 +831,8 @@ export const germanCopy = {
|
||||
invalidVoiceTurnSecretError: "Ungültiges TURN-Shared-Secret: mindestens 16 Zeichen und erforderlich, wenn TURN-URLs konfiguriert sind.",
|
||||
invalidVoiceTurnTtlError: "Die Gültigkeit der TURN-Zugangsdaten muss zwischen 300 und 86400 Sekunden liegen.",
|
||||
invalidVoiceJitterError: "Das adaptive Jitter-Limit muss zwischen 80 und 500 ms liegen.",
|
||||
invalidVoiceSettingsError: "Ungültige erweiterte Spracheinstellungen. Prüfe Opus-Schalter und Jitter-Limit.",
|
||||
invalidVoiceFrameMsError: "Der Downlink-Batch-Frame muss 20 oder 40 ms betragen.",
|
||||
invalidVoiceSettingsError: "Ungültige erweiterte Spracheinstellungen. Prüfe Opus, Framegröße, Cloudflare-Eingangserkennung und automatische Wiederholung.",
|
||||
fixedModeLead: "Gäste geben nur einen Namen ein; WebSpeak verwaltet Ziel und Passwort.",
|
||||
openModeLead: "Gäste können öffentliche TeamSpeak-Adressen eingeben; private und reservierte Netze sind gesperrt.",
|
||||
legacyImported: "Die bisherige config.json wurde importiert. WebSpeak wird jetzt hier verwaltet; Änderungen an der alten Datei wirken sich nicht mehr auf die laufende Konfiguration aus.",
|
||||
@@ -1160,9 +1187,17 @@ export const russianCopy = {
|
||||
voiceProfileAdaptive: "Адаптивный",
|
||||
voiceProfileAdaptiveLead: "Включает адаптивный jitter buffer, пейсер 20 мс и новый протокол кадров. Предпочтителен для Cloudflare Tunnel или сетей с заметным джиттером.",
|
||||
voiceOpusWs: "Opus в режиме совместимости",
|
||||
voiceOpusWsLead: "Действует только в адаптивном режиме. При явном включении браузеры могут отправлять Opus, снижая трафик. По умолчанию выключено.",
|
||||
voiceOpusWsLead: "Действует только в адаптивном режиме. Браузеры с WebCodecs отправляют Opus 24 кбит/с и при ошибке кодирования возвращаются к PCM. По умолчанию включено (auto).",
|
||||
voiceJitterMaxMs: "Предел адаптивного jitter",
|
||||
voiceJitterLead: "80–500 мс. Ограничивает только буфер; снижение не возвращает прежнее поведение clear() при переполнении.",
|
||||
voiceTuning: "Настройка режима совместимости",
|
||||
voiceTuningLead: "Пакетный downlink, повтор TURN и определение входа для Cloudflare Tunnel. Значения по умолчанию подходят большинству развёртываний.",
|
||||
voiceDownlinkFrameMs: "Размер кадра совместимости",
|
||||
voiceDownlinkFrameLead: "20 мс — меньше задержка; 40 мс вдвое сокращает сообщения downlink и также пакетирует uplink PCM по 40 мс (сервер снова делит его на 20 мс), добавляя до 20 мс на говорящего.",
|
||||
voiceAutoRelayRetry: "Автоповтор TURN после ошибки прямого пути",
|
||||
voiceAutoRelayRetryLead: "Только при настроенном TURN. После первой ошибки примерно через 3 с выполняется повтор только через relay; совместимое аудио продолжает работать.",
|
||||
voiceAssumeCloudflare: "Считать любой вход Cloudflare",
|
||||
voiceAssumeCloudflareLead: "Включите, если обратный прокси удаляет cf-ray и похожие заголовки, но трафик всё ещё идёт через Cloudflare Tunnel; включает адаптивный путь и отключает подстановку Host для медиаадреса.",
|
||||
voiceApplyHint: "Режим и настройки TURN применяются к новым голосовым подключениям после сохранения; перезапуск шлюза не требуется.",
|
||||
turnSettings: "Резервный TURN",
|
||||
turnLead: "Браузер использует TURN только при неудачном прямом UDP-подключении; не делайте его основным путём.",
|
||||
@@ -1180,7 +1215,8 @@ export const russianCopy = {
|
||||
invalidVoiceTurnSecretError: "Неверный общий секрет TURN: не менее 16 символов и обязателен при настроенных URL TURN.",
|
||||
invalidVoiceTurnTtlError: "Срок действия учётных данных TURN должен быть от 300 до 86400 секунд.",
|
||||
invalidVoiceJitterError: "Предел адаптивного jitter должен быть от 80 до 500 мс.",
|
||||
invalidVoiceSettingsError: "Неверные расширенные настройки звука. Проверьте переключатель Opus и предел jitter.",
|
||||
invalidVoiceFrameMsError: "Длина кадра downlink-пакета должна быть 20 или 40 мс.",
|
||||
invalidVoiceSettingsError: "Неверные расширенные настройки звука. Проверьте Opus, размер кадра, определение входа Cloudflare и автоповтор.",
|
||||
fixedModeLead: "Гости вводят только имя; адрес сервера и пароль задаются в WebSpeak.",
|
||||
openModeLead: "Гости могут вводить публичные адреса TeamSpeak; частные и зарезервированные сети заблокированы.",
|
||||
legacyImported: "Прежний файл config.json импортирован. Теперь WebSpeak настраивается здесь; изменения старого файла больше не влияют на текущую конфигурацию.",
|
||||
@@ -1535,9 +1571,17 @@ export const japaneseCopy = {
|
||||
voiceProfileAdaptive: "適応型",
|
||||
voiceProfileAdaptiveLead: "適応型 jitter buffer、20ms ペーサー、新しいフレームプロトコルを有効にします。Cloudflare Tunnel やジッターの目立つネットワークに適しています。",
|
||||
voiceOpusWs: "互換モードで Opus を使用",
|
||||
voiceOpusWsLead: "適応モードでのみ有効です。明示的に有効にするとブラウザーが Opus を送信でき、帯域を節約できます。既定では無効です。",
|
||||
voiceOpusWsLead: "適応モードでのみ有効です。WebCodecs 対応ブラウザーは 24 kbps Opus を送信し、エンコード失敗時は PCM に戻ります。既定で有効(auto)です。",
|
||||
voiceJitterMaxMs: "適応型 jitter 上限",
|
||||
voiceJitterLead: "80〜500 ms。バッファ上限のみを制限します。下げても旧版の clear() オーバーラン動作は復元されません。",
|
||||
voiceTuning: "互換モード調整",
|
||||
voiceTuningLead: "Cloudflare Tunnel 向けのバッチ downlink、TURN 再試行、入口判定。既定値はほとんどのデプロイに適しています。",
|
||||
voiceDownlinkFrameMs: "互換モードのフレーム長",
|
||||
voiceDownlinkFrameLead: "20 ms は低遅延。40 ms は downlink メッセージを半減し、uplink PCM も 40 ms 単位にまとめます(サーバーが 20 ms に分割)。話者ごとに最大 20 ms 遅れます。",
|
||||
voiceAutoRelayRetry: "直連失敗後の TURN 自動再試行",
|
||||
voiceAutoRelayRetryLead: "TURN 設定時のみ有効。最初の直連失敗から約 3 秒後に relay のみで再試行し、互換音声は継続します。",
|
||||
voiceAssumeCloudflare: "すべての入口を Cloudflare として扱う",
|
||||
voiceAssumeCloudflareLead: "リバースプロキシが cf-ray などを削除しても Cloudflare Tunnel 経由のときに有効化します。適応パスを有効にし、メディアアドレスの Host フォールバックを無効にします。",
|
||||
voiceApplyHint: "音声モードと TURN 設定は保存後の新規音声接続に適用され、ゲートウェイの再起動は不要です。",
|
||||
turnSettings: "TURN フォールバック",
|
||||
turnLead: "直連 UDP が失敗した場合にのみ TURN 中継を使用します。既定の経路にしないでください。",
|
||||
@@ -1555,7 +1599,8 @@ export const japaneseCopy = {
|
||||
invalidVoiceTurnSecretError: "TURN 共有シークレットが無効です。16 文字以上必要で、TURN URL 設定時は必須です。",
|
||||
invalidVoiceTurnTtlError: "TURN 資格情報の有効期間は 300〜86400 秒にしてください。",
|
||||
invalidVoiceJitterError: "適応型 jitter 上限は 80〜500 ミリ秒にしてください。",
|
||||
invalidVoiceSettingsError: "音声の詳細設定が無効です。Opus スイッチと jitter 上限を確認してください。",
|
||||
invalidVoiceFrameMsError: "Downlink バッチフレームは 20 または 40 ミリ秒にしてください。",
|
||||
invalidVoiceSettingsError: "音声の詳細設定が無効です。Opus、フレーム長、Cloudflare 入口判定、自動再試行を確認してください。",
|
||||
fixedModeLead: "ゲストはニックネームのみを入力します。接続先とパスワードは WebSpeak が管理します。",
|
||||
openModeLead: "ゲストは公開 TeamSpeak アドレスを入力できます。プライベートネットワークと予約済みネットワークへの接続は制限されます。",
|
||||
legacyImported: "旧 config.json をインポートしました。WebSpeak はこの画面で管理され、旧ファイルの変更は現在の設定に反映されません。",
|
||||
|
||||
@@ -107,7 +107,14 @@ function sameSource(left: DiagnosticSource | null, right: DiagnosticSource | nul
|
||||
export function createAudioDiagnostics(options: DiagnosticOptions) {
|
||||
const pending = new Map<string, { receive(bridge: VoiceAudioBridgeStats): void; finish(sample: VoiceAudioStatusSample | null): void }>();
|
||||
const fallback = { framesReceived: 0, framesDropped: 0, decodeErrors: 0 };
|
||||
const emptyBuffer: FallbackPlaybackStats = { bufferTargetMs: 0, bufferResets: 0, maxBufferAheadMs: 0 };
|
||||
const emptyBuffer: FallbackPlaybackStats = {
|
||||
bufferTargetMs: 0,
|
||||
bufferResets: 0,
|
||||
maxBufferAheadMs: 0,
|
||||
skippedFrames: 0,
|
||||
concealedFrames: 0,
|
||||
lateFrames: 0,
|
||||
};
|
||||
let sequence = 0;
|
||||
let scopeId = 0;
|
||||
let previousSource: DiagnosticSource | null = null;
|
||||
|
||||
@@ -1,71 +1,131 @@
|
||||
/**
|
||||
* Playback buffer policy for the PCM-over-WebSocket compatibility path.
|
||||
* Playback buffer policy for the WebSocket compatibility path.
|
||||
*
|
||||
* Cloudflare Tunnel adds bursty delivery on top of normal network jitter. The
|
||||
* old player treated every 80 ms overrun as a fatal error and rebuilt the
|
||||
* decoder, which turned a short tunnel stall into repeated audible gaps.
|
||||
* This policy keeps a small target buffer that grows with observed jitter and
|
||||
* lets the player reschedule queued audio without discarding decoder state.
|
||||
* Cloudflare Tunnel turns steady 20 ms frames into bursts. A mean/EWMA jitter
|
||||
* estimate hides those bursts behind a comfortably large average and then
|
||||
* still underruns on the tail, so the adaptive player uses a windowed p95 of
|
||||
* the audio-clock deviation instead. The target rises quickly when the tunnel
|
||||
* is late and decays slowly, which trades a little latency for far fewer
|
||||
* audible gaps.
|
||||
*/
|
||||
|
||||
export const MIN_TARGET_AHEAD_MS = 80;
|
||||
export const MAX_TARGET_AHEAD_MS = 300;
|
||||
export const MAX_BUFFER_AHEAD_SETTING_MS = 500;
|
||||
|
||||
const JITTER_EWMA_FACTOR = 0.9;
|
||||
const TARGET_JITTER_FACTOR = 2.5;
|
||||
const JITTER_WINDOW_SAMPLES = 100;
|
||||
const JITTER_WINDOW_MS = 2_000;
|
||||
const TARGET_JITTER_MS = 60;
|
||||
const MAX_OBSERVED_JITTER_MS = 500;
|
||||
const TARGET_RISE_PER_UPDATE_MS = 40;
|
||||
const TARGET_FALL_PER_STEP_MS = 2;
|
||||
const TARGET_FALL_INTERVAL_MS = 2_000;
|
||||
const SILENCE_RESET_MS = 200;
|
||||
|
||||
/** Target play-ahead for a measured jitter; 0 ms maps to the 80 ms floor. */
|
||||
/** Target play-ahead for a measured p95 jitter; 0 ms maps to the 80 ms floor. */
|
||||
export function computeTargetAheadMs(jitterMs: number, maxMs = MAX_TARGET_AHEAD_MS): number {
|
||||
const boundedMax = Math.max(
|
||||
MIN_TARGET_AHEAD_MS,
|
||||
Math.min(MAX_BUFFER_AHEAD_SETTING_MS, Number.isFinite(maxMs) ? maxMs : MAX_TARGET_AHEAD_MS),
|
||||
);
|
||||
const boundedJitter = Math.max(0, Math.min(MAX_OBSERVED_JITTER_MS, Number.isFinite(jitterMs) ? jitterMs : 0));
|
||||
return Math.min(boundedMax, Math.max(MIN_TARGET_AHEAD_MS, MIN_TARGET_AHEAD_MS + boundedJitter * TARGET_JITTER_FACTOR));
|
||||
return Math.min(boundedMax, Math.max(MIN_TARGET_AHEAD_MS, TARGET_JITTER_MS + boundedJitter));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks inter-arrival deviation from the frame duration (RFC 3550 style,
|
||||
* simplified for a fixed 20 ms Opus stream). A burst or a late packet raises
|
||||
* the estimate; sustained stable delivery brings it back down.
|
||||
* Tracks the difference between arrival spacing and audio-clock spacing. The
|
||||
* audio clock is carried in every v3 batch, so this needs no wall-clock sync
|
||||
* between the gateway and the browser.
|
||||
*/
|
||||
export class JitterEstimator {
|
||||
private jitterMs = 0;
|
||||
private samples: { at: number; value: number }[] = [];
|
||||
private lastAudioStartMs: number | null = null;
|
||||
private lastArrivalAt: number | null = null;
|
||||
private lastDurationMs = 20;
|
||||
private currentTargetMs = MIN_TARGET_AHEAD_MS;
|
||||
private lastDecreaseAt = 0;
|
||||
private p95 = 0;
|
||||
|
||||
observe(arrivalAt: number, durationMs: number, maxMs = MAX_TARGET_AHEAD_MS): number {
|
||||
const duration = Number.isFinite(durationMs) && durationMs > 0 ? durationMs : 20;
|
||||
if (this.lastArrivalAt !== null) {
|
||||
const delta = arrivalAt - this.lastArrivalAt - this.lastDurationMs;
|
||||
const observed = Math.min(MAX_OBSERVED_JITTER_MS, Math.abs(delta));
|
||||
this.jitterMs = this.jitterMs * JITTER_EWMA_FACTOR + observed * (1 - JITTER_EWMA_FACTOR);
|
||||
/**
|
||||
* Record one batch arrival. `audioStartMs` is the sender's audio clock;
|
||||
* `arrivalAt` defaults to `performance.now()`.
|
||||
*/
|
||||
observe(audioStartMs: number, arrivalAt = performance.now(), maxMs = MAX_TARGET_AHEAD_MS): number {
|
||||
if (!Number.isFinite(audioStartMs) || !Number.isFinite(arrivalAt)) return this.targetAheadMs(maxMs);
|
||||
if (this.lastAudioStartMs !== null && this.lastArrivalAt !== null) {
|
||||
const audioDelta = audioStartMs - this.lastAudioStartMs;
|
||||
if (audioDelta < -1_000 || audioDelta > 5_000) {
|
||||
// Sender restart or a huge clock jump: start a fresh window.
|
||||
this.resetWindow();
|
||||
} else {
|
||||
const deviation = (arrivalAt - this.lastArrivalAt) - audioDelta;
|
||||
// Early delivery does not need a larger buffer; only late delivery does.
|
||||
this.push(Math.max(0, Math.min(MAX_OBSERVED_JITTER_MS, deviation)), arrivalAt);
|
||||
}
|
||||
}
|
||||
this.lastAudioStartMs = audioStartMs;
|
||||
this.lastArrivalAt = arrivalAt;
|
||||
this.lastDurationMs = duration;
|
||||
this.recomputeTarget(maxMs, arrivalAt);
|
||||
return this.targetAheadMs(maxMs);
|
||||
}
|
||||
|
||||
targetAheadMs(maxMs = MAX_TARGET_AHEAD_MS): number {
|
||||
return computeTargetAheadMs(this.jitterMs, maxMs);
|
||||
/** A long silence invalidates inter-arrival spacing; keep the target but reset the window. */
|
||||
noteSilence(gapMs: number): void {
|
||||
if (gapMs >= SILENCE_RESET_MS) this.resetWindow();
|
||||
}
|
||||
|
||||
targetAheadMs(maxMs = MAX_TARGET_AHEAD_MS): number {
|
||||
const boundedMax = Math.max(
|
||||
MIN_TARGET_AHEAD_MS,
|
||||
Math.min(MAX_BUFFER_AHEAD_SETTING_MS, Number.isFinite(maxMs) ? maxMs : MAX_TARGET_AHEAD_MS),
|
||||
);
|
||||
return Math.min(boundedMax, Math.max(MIN_TARGET_AHEAD_MS, Math.round(this.currentTargetMs)));
|
||||
}
|
||||
|
||||
/** Current p95 deviation, useful for diagnostics. */
|
||||
get jitter(): number {
|
||||
return this.jitterMs;
|
||||
return this.p95;
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.jitterMs = 0;
|
||||
this.resetWindow();
|
||||
this.currentTargetMs = MIN_TARGET_AHEAD_MS;
|
||||
this.lastDecreaseAt = 0;
|
||||
this.p95 = 0;
|
||||
}
|
||||
|
||||
private resetWindow(): void {
|
||||
this.samples = [];
|
||||
this.lastAudioStartMs = null;
|
||||
this.lastArrivalAt = null;
|
||||
this.lastDurationMs = 20;
|
||||
}
|
||||
|
||||
private push(value: number, at: number): void {
|
||||
this.samples.push({ at, value });
|
||||
while (this.samples.length > JITTER_WINDOW_SAMPLES || (this.samples[0] && at - this.samples[0].at > JITTER_WINDOW_MS)) {
|
||||
this.samples.shift();
|
||||
}
|
||||
}
|
||||
|
||||
private recomputeTarget(maxMs: number, now: number): void {
|
||||
if (this.samples.length === 0) { this.p95 = 0; return; }
|
||||
const sorted = this.samples.map(sample => sample.value).sort((left, right) => left - right);
|
||||
this.p95 = sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * 0.95))] ?? 0;
|
||||
const desired = computeTargetAheadMs(this.p95, maxMs);
|
||||
if (desired > this.currentTargetMs) {
|
||||
this.currentTargetMs = Math.min(desired, this.currentTargetMs + TARGET_RISE_PER_UPDATE_MS);
|
||||
this.lastDecreaseAt = now;
|
||||
return;
|
||||
}
|
||||
if (now - this.lastDecreaseAt >= TARGET_FALL_INTERVAL_MS) {
|
||||
this.currentTargetMs = Math.max(desired, this.currentTargetMs - TARGET_FALL_PER_STEP_MS);
|
||||
this.lastDecreaseAt = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A large positive overrun: drop only the schedule, never the decoder. */
|
||||
/** A large positive overrun: re-anchor only, never tear down the decoder. */
|
||||
export function shouldResetSchedule(aheadMs: number, targetMs: number): boolean {
|
||||
return aheadMs > targetMs + 60;
|
||||
return aheadMs > targetMs + 300;
|
||||
}
|
||||
|
||||
/** The play head is close to real time; pull it back to the target. */
|
||||
|
||||
@@ -38,8 +38,8 @@ const OPUS_CONFIG: AudioEncoderConfig = {
|
||||
opus: {
|
||||
frameDuration: FRAME_DURATION_US,
|
||||
complexity: 5,
|
||||
packetlossperc: 0,
|
||||
useinbandfec: false,
|
||||
packetlossperc: 10,
|
||||
useinbandfec: true,
|
||||
usedtx: false,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Packet-loss concealment for the compatibility player. The last decoded frame
|
||||
* is looped with a linear fade so a dropped Opus frame becomes a short decay
|
||||
* instead of a click or a hole in the timeline.
|
||||
*/
|
||||
export function buildConcealmentFrame(lastFrame: Float32Array | undefined, frameSamples: number, sourceSampleRate = 48_000): Float32Array {
|
||||
const length = Math.max(1, Math.round(frameSamples));
|
||||
const output = new Float32Array(length);
|
||||
if (!lastFrame || lastFrame.length === 0) return output;
|
||||
const source = lastFrame;
|
||||
const playbackLength = Math.max(1, Math.round(source.length * (48_000 / Math.max(1, sourceSampleRate))));
|
||||
for (let index = 0; index < length; index++) {
|
||||
const fade = 1 - index / Math.max(1, length - 1);
|
||||
output[index] = (source[index % playbackLength] ?? 0) * fade;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
@@ -1,8 +1,16 @@
|
||||
import { opusPacketDurationUs } from "./opus-packet.js";
|
||||
import { computeTargetAheadMs, JitterEstimator, shouldRecover, shouldResetSchedule } from "./jitter-buffer.js";
|
||||
import { buildConcealmentFrame } from "./plc.js";
|
||||
import { JitterEstimator, shouldResetSchedule } from "./jitter-buffer.js";
|
||||
|
||||
type RemotePlaybackMode = "legacy" | "adaptive";
|
||||
|
||||
export interface PlaybackTiming {
|
||||
/** Sender audio clock for the start of this batch (v3 batches only). */
|
||||
audioStartMs?: number;
|
||||
/** Per-speaker sequence number carried in the v3 batch entry. */
|
||||
seq?: number;
|
||||
}
|
||||
|
||||
interface RemotePlaybackOptions {
|
||||
getContext(): AudioContext;
|
||||
getVolume(clientId: number): number;
|
||||
@@ -24,10 +32,23 @@ interface SpeakerPlayback {
|
||||
decoder: AudioDecoder | null;
|
||||
gain: GainNode;
|
||||
sources: Set<AudioBufferSourceNode>;
|
||||
/** End of the audio already reserved for this speaker. */
|
||||
playTime: number;
|
||||
timestamp: number;
|
||||
jitter: JitterEstimator;
|
||||
anchorSet: boolean;
|
||||
anchorCtx: number;
|
||||
baseAudioMs: number;
|
||||
pendingStarts: number[];
|
||||
lastSeq: number | null;
|
||||
lastPcm: Float32Array[] | null;
|
||||
lastFrameSamples: number;
|
||||
lastPacketAt: number;
|
||||
lastCorrectionAt: number;
|
||||
resets: number;
|
||||
skippedFrames: number;
|
||||
concealedFrames: number;
|
||||
lateFrames: number;
|
||||
maxAheadMs: number;
|
||||
}
|
||||
|
||||
@@ -35,6 +56,9 @@ export interface FallbackPlaybackStats {
|
||||
bufferTargetMs: number;
|
||||
bufferResets: number;
|
||||
maxBufferAheadMs: number;
|
||||
skippedFrames: number;
|
||||
concealedFrames: number;
|
||||
lateFrames: number;
|
||||
}
|
||||
|
||||
// Preserve the compatibility path's bounded jitter buffer and decoder queue.
|
||||
@@ -43,6 +67,9 @@ const LEGACY_MAX_DECODE_QUEUE_FRAMES = 3;
|
||||
// A decoded-frame queue above this is unusual; adaptive keeps decoding instead
|
||||
// of tearing down the decoder. Only a deeply stalled queue drops the newest frame.
|
||||
const MAX_DECODE_QUEUE_FRAMES_HARD = 12;
|
||||
const TARGET_CORRECTION_COOLDOWN_MS = 200;
|
||||
const MAX_INSERT_FRAMES = 3;
|
||||
const MAX_SEQ_GAP = 8;
|
||||
|
||||
export function createRemotePlayback(options: RemotePlaybackOptions) {
|
||||
const speakers = new Map<number, SpeakerPlayback>();
|
||||
@@ -76,21 +103,54 @@ export function createRemotePlayback(options: RemotePlaybackOptions) {
|
||||
source.disconnect();
|
||||
}
|
||||
stream.sources.clear();
|
||||
stream.pendingStarts.length = 0;
|
||||
stream.gain.disconnect();
|
||||
}
|
||||
|
||||
function resetSchedule(stream: SpeakerPlayback, targetSeconds: number): void {
|
||||
function stopSources(stream: SpeakerPlayback): void {
|
||||
for (const source of stream.sources) {
|
||||
try { source.stop(); } catch { /* not started or already ended */ }
|
||||
source.disconnect();
|
||||
}
|
||||
stream.sources.clear();
|
||||
}
|
||||
|
||||
function resetSchedule(stream: SpeakerPlayback, targetSeconds: number): void {
|
||||
stopSources(stream);
|
||||
stream.pendingStarts.length = 0;
|
||||
stream.playTime = stream.context.currentTime + targetSeconds;
|
||||
stream.anchorSet = false;
|
||||
stream.resets++;
|
||||
}
|
||||
|
||||
function enqueueChunk(stream: SpeakerPlayback, chunk: AudioData, startTime: number): number {
|
||||
const { context, gain, sources } = stream;
|
||||
function attachSource(stream: SpeakerPlayback, buffer: AudioBuffer, startTime: number): AudioBufferSourceNode {
|
||||
const source = stream.context.createBufferSource();
|
||||
stream.sources.add(source);
|
||||
source.buffer = buffer;
|
||||
source.connect(stream.gain);
|
||||
source.addEventListener("ended", () => {
|
||||
source.disconnect();
|
||||
// The old stream owns this set; never delete a replacement's resources.
|
||||
stream.sources.delete(source);
|
||||
}, { once: true });
|
||||
source.start(Math.max(startTime, stream.context.currentTime));
|
||||
return source;
|
||||
}
|
||||
|
||||
function rememberPcm(stream: SpeakerPlayback, chunk: AudioData): void {
|
||||
const channels = chunk.numberOfChannels;
|
||||
const pcm: Float32Array[] = [];
|
||||
for (let channel = 0; channel < channels; channel++) {
|
||||
const samples = new Float32Array(chunk.numberOfFrames);
|
||||
chunk.copyTo(samples, { planeIndex: channel, format: "f32-planar" });
|
||||
pcm.push(samples);
|
||||
}
|
||||
stream.lastPcm = pcm;
|
||||
stream.lastFrameSamples = chunk.numberOfFrames;
|
||||
}
|
||||
|
||||
function enqueueChunk(stream: SpeakerPlayback, chunk: AudioData, startTime: number, remember: boolean): number {
|
||||
const { context } = stream;
|
||||
const { sampleRate, numberOfChannels, numberOfFrames } = chunk;
|
||||
const duration = numberOfFrames / sampleRate;
|
||||
const buffer = context.createBuffer(numberOfChannels, numberOfFrames, sampleRate);
|
||||
@@ -99,19 +159,28 @@ export function createRemotePlayback(options: RemotePlaybackOptions) {
|
||||
chunk.copyTo(samples, { planeIndex: channel, format: "f32-planar" });
|
||||
buffer.copyToChannel(samples, channel);
|
||||
}
|
||||
const source = context.createBufferSource();
|
||||
sources.add(source);
|
||||
source.buffer = buffer;
|
||||
source.connect(gain);
|
||||
source.addEventListener("ended", () => {
|
||||
source.disconnect();
|
||||
// The old stream owns this set; never delete a replacement's resources.
|
||||
sources.delete(source);
|
||||
}, { once: true });
|
||||
source.start(startTime);
|
||||
if (remember) rememberPcm(stream, chunk);
|
||||
attachSource(stream, buffer, startTime);
|
||||
return duration;
|
||||
}
|
||||
|
||||
function insertConcealment(stream: SpeakerPlayback, startTime: number, count: number): number {
|
||||
const frameSamples = stream.lastFrameSamples || 960;
|
||||
const channels = stream.lastPcm?.length || (stream.codec === 4 ? 1 : 2);
|
||||
let at = startTime;
|
||||
for (let index = 0; index < count; index++) {
|
||||
const buffer = stream.context.createBuffer(channels, frameSamples, 48_000);
|
||||
for (let channel = 0; channel < channels; channel++) {
|
||||
const last = stream.lastPcm?.[channel] ?? stream.lastPcm?.[0];
|
||||
buffer.copyToChannel(buildConcealmentFrame(last, frameSamples), channel);
|
||||
}
|
||||
attachSource(stream, buffer, at);
|
||||
at += frameSamples / 48_000;
|
||||
stream.concealedFrames++;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
function outputLegacy(clientId: number, stream: SpeakerPlayback, chunk: AudioData): void {
|
||||
const context = stream.context;
|
||||
const playTime = Math.max(stream.playTime, context.currentTime);
|
||||
@@ -121,30 +190,23 @@ export function createRemotePlayback(options: RemotePlaybackOptions) {
|
||||
clear(clientId);
|
||||
return;
|
||||
}
|
||||
enqueueChunk(stream, chunk, playTime);
|
||||
enqueueChunk(stream, chunk, playTime, true);
|
||||
stream.playTime = playTime + duration;
|
||||
stream.maxAheadMs = Math.max(stream.maxAheadMs, (stream.playTime - context.currentTime) * 1_000);
|
||||
}
|
||||
|
||||
function outputAdaptive(clientId: number, stream: SpeakerPlayback, chunk: AudioData): void {
|
||||
function outputAdaptive(stream: SpeakerPlayback, chunk: AudioData): void {
|
||||
const context = stream.context;
|
||||
const duration = chunk.numberOfFrames / chunk.sampleRate;
|
||||
const targetMs = stream.jitter.targetAheadMs(maxBufferAheadMs());
|
||||
const targetSeconds = targetMs / 1_000;
|
||||
let playTime = stream.playTime;
|
||||
if (playTime < context.currentTime - 0.05) {
|
||||
// The decoder produced audio after a longer pause. Re-anchor near the
|
||||
// target without throwing away decoder state or the stream identity.
|
||||
playTime = context.currentTime + targetSeconds;
|
||||
const start = stream.pendingStarts.shift();
|
||||
if (start === undefined) {
|
||||
// A schedule reset (or a decoder error) discarded this frame's slot.
|
||||
options.onDrop();
|
||||
return;
|
||||
}
|
||||
const aheadMs = (playTime - context.currentTime) * 1_000;
|
||||
if (shouldResetSchedule(aheadMs, targetMs)) {
|
||||
resetSchedule(stream, targetSeconds);
|
||||
playTime = stream.playTime;
|
||||
}
|
||||
const startTime = Math.max(playTime, context.currentTime + 0.005);
|
||||
enqueueChunk(stream, chunk, startTime);
|
||||
stream.playTime = startTime + duration;
|
||||
const actualStart = Math.max(start, context.currentTime + 0.005);
|
||||
if (start < context.currentTime) stream.lateFrames++;
|
||||
const duration = enqueueChunk(stream, chunk, actualStart, true);
|
||||
stream.playTime = Math.max(stream.playTime, actualStart + duration);
|
||||
stream.maxAheadMs = Math.max(stream.maxAheadMs, (stream.playTime - context.currentTime) * 1_000);
|
||||
}
|
||||
|
||||
@@ -152,7 +214,7 @@ export function createRemotePlayback(options: RemotePlaybackOptions) {
|
||||
try {
|
||||
if (speakers.get(clientId) !== stream) return;
|
||||
if (stream.mode === "legacy") outputLegacy(clientId, stream, chunk);
|
||||
else outputAdaptive(clientId, stream, chunk);
|
||||
else outputAdaptive(stream, chunk);
|
||||
} catch {
|
||||
if (speakers.get(clientId) === stream) {
|
||||
options.onDecodeError();
|
||||
@@ -164,11 +226,12 @@ export function createRemotePlayback(options: RemotePlaybackOptions) {
|
||||
}
|
||||
|
||||
function create(clientId: number, context: AudioContext, codec: 4 | 5, streamMode: RemotePlaybackMode): SpeakerPlayback {
|
||||
const target = streamMode === "legacy" ? 0 : computeTargetAheadMs(0, maxBufferAheadMs()) / 1_000;
|
||||
const stream: SpeakerPlayback = {
|
||||
mode: streamMode, codec, context, decoder: null, gain: context.createGain(), sources: new Set(),
|
||||
playTime: context.currentTime + target, timestamp: 0,
|
||||
jitter: new JitterEstimator(), resets: 0, maxAheadMs: target * 1_000,
|
||||
playTime: context.currentTime + (streamMode === "adaptive" ? 0.08 : 0), timestamp: 0,
|
||||
jitter: new JitterEstimator(), anchorSet: false, anchorCtx: 0, baseAudioMs: 0, pendingStarts: [],
|
||||
lastSeq: null, lastPcm: null, lastFrameSamples: 960, lastPacketAt: 0, lastCorrectionAt: 0,
|
||||
resets: 0, skippedFrames: 0, concealedFrames: 0, lateFrames: 0, maxAheadMs: 0,
|
||||
};
|
||||
speakers.set(clientId, stream);
|
||||
stream.gain.gain.value = options.getVolume(clientId);
|
||||
@@ -185,7 +248,100 @@ export function createRemotePlayback(options: RemotePlaybackOptions) {
|
||||
return stream;
|
||||
}
|
||||
|
||||
function play(clientId: number, codec: 4 | 5, opusData: Uint8Array): void {
|
||||
function targetSecondsFor(stream: SpeakerPlayback): number {
|
||||
return stream.jitter.targetAheadMs(maxBufferAheadMs()) / 1_000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide when this packet should play. The sender's audio clock is the
|
||||
* primary anchor; the per-speaker play head only fills gaps and absorbs
|
||||
* bursts, so a TCP retransmit does not move every later packet.
|
||||
*/
|
||||
function scheduleAdaptive(
|
||||
stream: SpeakerPlayback,
|
||||
timing: PlaybackTiming | undefined,
|
||||
duration: number,
|
||||
): { startTime: number; targetMs: number } | null {
|
||||
const context = stream.context;
|
||||
const now = performance.now();
|
||||
if (stream.lastPacketAt > 0 && now - stream.lastPacketAt >= 200) {
|
||||
stream.jitter.noteSilence(now - stream.lastPacketAt);
|
||||
}
|
||||
stream.lastPacketAt = now;
|
||||
|
||||
const audioStartMs = timing?.audioStartMs ?? stream.timestamp / 1_000;
|
||||
const targetMs = stream.jitter.observe(audioStartMs, now, maxBufferAheadMs());
|
||||
const target = targetMs / 1_000;
|
||||
|
||||
let desired: number;
|
||||
if (timing?.audioStartMs !== undefined) {
|
||||
if (!stream.anchorSet) {
|
||||
stream.baseAudioMs = audioStartMs;
|
||||
stream.anchorCtx = context.currentTime + target + 0.02;
|
||||
stream.anchorSet = true;
|
||||
}
|
||||
desired = stream.anchorCtx + (audioStartMs - stream.baseAudioMs) / 1_000;
|
||||
if (desired < context.currentTime - 0.2 || desired > context.currentTime + 1.5) {
|
||||
// The speaker restarted, the tab slept, or the clock drifted too far.
|
||||
stream.baseAudioMs = audioStartMs;
|
||||
stream.anchorCtx = context.currentTime + target + 0.02;
|
||||
stream.anchorSet = true;
|
||||
desired = stream.anchorCtx;
|
||||
}
|
||||
} else {
|
||||
desired = Math.max(stream.playTime, context.currentTime + 0.005);
|
||||
}
|
||||
|
||||
if (timing?.seq !== undefined) {
|
||||
if (stream.lastSeq !== null) {
|
||||
const gap = (timing.seq - stream.lastSeq + 256) % 256;
|
||||
if (gap === 0) return null;
|
||||
if (gap > MAX_SEQ_GAP) {
|
||||
// Too much missing audio to conceal; re-anchor rather than replay stale frames.
|
||||
stream.playTime = Math.max(desired, context.currentTime + target);
|
||||
stream.anchorSet = false;
|
||||
stream.pendingStarts.length = 0;
|
||||
} else if (gap > 1) {
|
||||
const fillStart = Math.max(stream.playTime, desired, context.currentTime + 0.005);
|
||||
const filled = insertConcealment(stream, fillStart, Math.min(gap - 1, MAX_INSERT_FRAMES));
|
||||
stream.playTime = Math.max(stream.playTime, filled);
|
||||
}
|
||||
}
|
||||
stream.lastSeq = timing.seq;
|
||||
}
|
||||
|
||||
let playTime = Math.max(stream.playTime, desired);
|
||||
const ahead = playTime - context.currentTime;
|
||||
if (shouldResetSchedule(ahead * 1_000, targetMs)) {
|
||||
resetSchedule(stream, target);
|
||||
playTime = stream.playTime;
|
||||
} else if (ahead > target + 0.06) {
|
||||
// This speaker is well ahead of the rest of the mix; skip one frame to
|
||||
// drain the lead instead of adding more latency.
|
||||
if (now - stream.lastCorrectionAt >= TARGET_CORRECTION_COOLDOWN_MS) {
|
||||
stream.skippedFrames++;
|
||||
stream.lastCorrectionAt = now;
|
||||
return null;
|
||||
}
|
||||
} else if (ahead < target - 0.02 && stream.lastPcm) {
|
||||
// The target just grew (or a burst drained the queue); stretch with a
|
||||
// concealed frame rather than waiting for the next arrival.
|
||||
if (now - stream.lastCorrectionAt >= TARGET_CORRECTION_COOLDOWN_MS) {
|
||||
const filled = insertConcealment(stream, Math.max(playTime, context.currentTime + 0.005), 1);
|
||||
stream.playTime = filled;
|
||||
stream.lastCorrectionAt = now;
|
||||
playTime = filled;
|
||||
}
|
||||
}
|
||||
|
||||
const startTime = Math.max(playTime, context.currentTime + 0.005);
|
||||
stream.playTime = startTime + duration;
|
||||
stream.pendingStarts.push(startTime);
|
||||
stream.maxAheadMs = Math.max(stream.maxAheadMs, (stream.playTime - context.currentTime) * 1_000);
|
||||
return { startTime, targetMs };
|
||||
}
|
||||
|
||||
function play(clientId: number, codec: 4 | 5, opusData: Uint8Array, timing?: PlaybackTiming): void {
|
||||
const duration = opusPacketDurationUs(opusData);
|
||||
if (!duration || opusData.length < 3) { options.onDrop(); return; }
|
||||
try {
|
||||
@@ -208,19 +364,14 @@ export function createRemotePlayback(options: RemotePlaybackOptions) {
|
||||
return;
|
||||
}
|
||||
|
||||
const targetMs = stream.jitter.observe(performance.now(), duration / 1_000, maxBufferAheadMs());
|
||||
const targetSeconds = targetMs / 1_000;
|
||||
const aheadMs = (stream.playTime - context.currentTime) * 1_000;
|
||||
if (shouldResetSchedule(aheadMs, targetMs)) {
|
||||
resetSchedule(stream, targetSeconds);
|
||||
} else if (shouldRecover(aheadMs)) {
|
||||
stream.playTime = context.currentTime + targetSeconds;
|
||||
}
|
||||
|
||||
const scheduled = scheduleAdaptive(stream, timing, duration / 1_000_000);
|
||||
if (!scheduled) return;
|
||||
const queueSize = stream.decoder?.decodeQueueSize ?? 0;
|
||||
if (queueSize >= MAX_DECODE_QUEUE_FRAMES_HARD) {
|
||||
// The decoder is deeply backlogged (for example a suspended context).
|
||||
// Drop the newest frame rather than destroying a healthy decoder.
|
||||
stream.pendingStarts.pop();
|
||||
stream.playTime = Math.max(context.currentTime + 0.005, stream.playTime - duration / 1_000_000);
|
||||
options.onDrop();
|
||||
return;
|
||||
}
|
||||
@@ -236,17 +387,26 @@ export function createRemotePlayback(options: RemotePlaybackOptions) {
|
||||
let target = 0;
|
||||
let resets = 0;
|
||||
let maxAhead = 0;
|
||||
let skipped = 0;
|
||||
let concealed = 0;
|
||||
let late = 0;
|
||||
for (const stream of speakers.values()) {
|
||||
target = Math.max(target, stream.mode === "legacy"
|
||||
? LEGACY_MAX_PLAY_AHEAD_SECONDS * 1_000
|
||||
: stream.jitter.targetAheadMs(maxBufferAheadMs()));
|
||||
resets += stream.resets;
|
||||
maxAhead = Math.max(maxAhead, stream.maxAheadMs);
|
||||
skipped += stream.skippedFrames;
|
||||
concealed += stream.concealedFrames;
|
||||
late += stream.lateFrames;
|
||||
}
|
||||
return {
|
||||
bufferTargetMs: Math.round(target),
|
||||
bufferResets: resets,
|
||||
maxBufferAheadMs: Math.round(maxAhead),
|
||||
skippedFrames: skipped,
|
||||
concealedFrames: concealed,
|
||||
lateFrames: late,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ interface Attempt {
|
||||
meter: MicrophoneMeter | null;
|
||||
active: boolean;
|
||||
closed: boolean;
|
||||
relay: boolean;
|
||||
answerTimer: number | null;
|
||||
connectionTimer: number | null;
|
||||
cancelIce: (() => void) | null;
|
||||
@@ -111,29 +112,43 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
options.onReady();
|
||||
}
|
||||
|
||||
async function waitForIce(record: Attempt, peer: RTCPeerConnection): Promise<void> {
|
||||
async function waitForIce(record: Attempt, peer: RTCPeerConnection, relay: boolean): Promise<void> {
|
||||
if (peer.iceGatheringState === "complete") return;
|
||||
await new Promise<void>(resolve => {
|
||||
let settled = false;
|
||||
let directTimer: number | null = null;
|
||||
const finish = (): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
window.clearTimeout(timer);
|
||||
if (directTimer !== null) window.clearTimeout(directTimer);
|
||||
clean(() => peer.removeEventListener("icegatheringstatechange", onStateChange));
|
||||
clean(() => peer.removeEventListener("icecandidate", onCandidate));
|
||||
record.cancelIce = null;
|
||||
resolve();
|
||||
};
|
||||
const onStateChange = (): void => { if (peer.iceGatheringState === "complete") finish(); };
|
||||
const timer = window.setTimeout(finish, 6_000);
|
||||
// A direct host/srflx candidate is enough to offer; waiting for the full
|
||||
// gathering timeout only delays signaling and leaves the tunnel fallback
|
||||
// running longer than necessary.
|
||||
const onCandidate = (event: RTCPeerConnectionIceEvent): void => {
|
||||
if (relay || directTimer !== null) return;
|
||||
const type = event.candidate?.type;
|
||||
if (type === "host" || type === "srflx" || type === "prflx") {
|
||||
directTimer = window.setTimeout(finish, 300);
|
||||
}
|
||||
};
|
||||
const timer = window.setTimeout(finish, relay ? 4_000 : 6_000);
|
||||
record.cancelIce = finish;
|
||||
peer.addEventListener("icegatheringstatechange", onStateChange);
|
||||
peer.addEventListener("icecandidate", onCandidate);
|
||||
});
|
||||
}
|
||||
|
||||
async function start(connection: Connection): Promise<void> {
|
||||
stop();
|
||||
const record: Attempt = { connection, peer: null, input: null, meter: null,
|
||||
active: false, closed: false, answerTimer: null, connectionTimer: null, cancelIce: null };
|
||||
active: false, closed: false, relay: false, answerTimer: null, connectionTimer: null, cancelIce: null };
|
||||
current = record;
|
||||
let microphone: Microphone | null;
|
||||
try { microphone = await options.prepareMicrophone(); }
|
||||
@@ -148,6 +163,7 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
const configuredIceServers = options.iceServers?.() ?? [];
|
||||
const iceServers = configuredIceServers.length ? configuredIceServers : (stunServer ? [{ urls: stunServer }] : []);
|
||||
const iceTransportPolicy = options.iceTransportPolicy?.() ?? "all";
|
||||
record.relay = iceTransportPolicy === "relay";
|
||||
if (iceTransportPolicy === "relay" && !hasVoiceTurnServer(iceServers)) {
|
||||
await failAttempt(record, "WEBRTC_NO_RELAY");
|
||||
return;
|
||||
@@ -182,7 +198,7 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
if (!isCurrent(record)) return;
|
||||
await peer.setLocalDescription({ ...offer, sdp: addOpusFmtpParameters(offer.sdp ?? "", ["stereo=1"]) });
|
||||
if (!isCurrent(record)) return;
|
||||
await waitForIce(record, peer);
|
||||
await waitForIce(record, peer, record.relay);
|
||||
if (!isCurrent(record)) return;
|
||||
const description = peer.localDescription;
|
||||
if (!description || description.type !== "offer") throw new Error("WebRTC offer was not created");
|
||||
@@ -194,7 +210,7 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
if (!isCurrent(record)) return;
|
||||
record.answerTimer = null;
|
||||
if (!peer.remoteDescription) void failAttempt(record, "WEBRTC_ANSWER_TIMEOUT");
|
||||
}, 8_000);
|
||||
}, record.relay ? 6_000 : 8_000);
|
||||
} catch {
|
||||
await failAttempt(record, "WEBRTC_NEGOTIATION_FAILED");
|
||||
}
|
||||
@@ -217,7 +233,7 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
record.connectionTimer = window.setTimeout(() => {
|
||||
record.connectionTimer = null;
|
||||
if (isCurrent(record) && !record.active) void failAttempt(record, "WEBRTC_CONNECTION_TIMEOUT");
|
||||
}, 15_000);
|
||||
}, record.relay ? 10_000 : 15_000);
|
||||
}
|
||||
} catch { await failAttempt(record, "WEBRTC_ANSWER_REJECTED"); }
|
||||
}
|
||||
|
||||
@@ -157,7 +157,7 @@ test("browser admin API consumes the actual HTTP router and preserves keep/repla
|
||||
assert.equal(original.voiceTurnUrls, "");
|
||||
assert.equal(original.hasVoiceTurnSecret, false);
|
||||
assert.equal(original.voiceTurnTtlSeconds, 21600);
|
||||
assert.equal(original.voiceOpusWs, false);
|
||||
assert.equal(original.voiceOpusWs, true);
|
||||
assert.equal(original.voiceJitterMaxMs, 300);
|
||||
const network = { webRtcPublicHost: " MEDIA.example.com ", webRtcIpv6Enabled: true, webRtcStunServer: "stun:stun.example.com" };
|
||||
const updated = await api.saveSettings({ ...withoutVoiceSettings(original), ...network });
|
||||
@@ -239,6 +239,9 @@ test("browser admin API consumes the actual HTTP router and preserves keep/repla
|
||||
voiceTurnTtlSeconds: 3600,
|
||||
voiceOpusWs: true,
|
||||
voiceJitterMaxMs: 200,
|
||||
voiceDownlinkFrameMs: 40 as const,
|
||||
voiceAssumeCloudflare: true,
|
||||
voiceAutoRelayRetry: false,
|
||||
};
|
||||
const savedVoice = await api.saveSettings(voiceInput);
|
||||
assert.equal(savedVoice.settings.voiceProfile, "adaptive");
|
||||
@@ -246,6 +249,9 @@ test("browser admin API consumes the actual HTTP router and preserves keep/repla
|
||||
assert.equal(savedVoice.settings.voiceTurnTtlSeconds, 3600);
|
||||
assert.equal(savedVoice.settings.voiceOpusWs, true);
|
||||
assert.equal(savedVoice.settings.voiceJitterMaxMs, 200);
|
||||
assert.equal(savedVoice.settings.voiceDownlinkFrameMs, 40);
|
||||
assert.equal(savedVoice.settings.voiceAssumeCloudflare, true);
|
||||
assert.equal(savedVoice.settings.voiceAutoRelayRetry, false);
|
||||
assert.equal(JSON.stringify(savedVoice).includes("fixture-turn-shared-secret"), false, "the TURN secret must never be returned");
|
||||
const storedVoice = database.getSettings();
|
||||
assert.ok(storedVoice.voiceTurnSecretEncrypted, "stored TURN secret must not be plaintext or empty");
|
||||
@@ -255,6 +261,9 @@ test("browser admin API consumes the actual HTTP router and preserves keep/repla
|
||||
assert.equal(voiceConfig.profile, "adaptive");
|
||||
assert.equal(voiceConfig.opusWebSocket, true);
|
||||
assert.equal(voiceConfig.jitterMaxMs, 200);
|
||||
assert.equal(voiceConfig.downlinkFrameMs, 40);
|
||||
assert.equal(voiceConfig.assumeCloudflare, true);
|
||||
assert.equal(voiceConfig.autoRelayRetry, false);
|
||||
assert.deepEqual(voiceConfig.turnRest, {
|
||||
urls: ["turn:turn.example.com:3478", "turns:turn.example.com:5349?transport=tcp"],
|
||||
secret: "fixture-turn-shared-secret",
|
||||
|
||||
@@ -7,10 +7,10 @@ import {
|
||||
shouldResetSchedule,
|
||||
} from "../src/voice/jitter-buffer.ts";
|
||||
|
||||
test("target buffer maps jitter to the 80-300 ms adaptive range", () => {
|
||||
test("target buffer maps p95 jitter to the 80-300 ms adaptive range", () => {
|
||||
assert.equal(computeTargetAheadMs(0), 80);
|
||||
assert.equal(computeTargetAheadMs(30), 155);
|
||||
assert.equal(computeTargetAheadMs(100), 300);
|
||||
assert.equal(computeTargetAheadMs(30), 90);
|
||||
assert.equal(computeTargetAheadMs(100), 160);
|
||||
assert.equal(computeTargetAheadMs(1_000), 300);
|
||||
});
|
||||
|
||||
@@ -21,16 +21,16 @@ test("a configured 80 ms ceiling restores the old buffer bound", () => {
|
||||
|
||||
test("jitter estimator raises the target after a late burst", () => {
|
||||
const estimator = new JitterEstimator();
|
||||
assert.equal(estimator.observe(0, 20), 80);
|
||||
assert.equal(estimator.observe(20, 20), 80);
|
||||
const target = estimator.observe(100, 20);
|
||||
assert.equal(estimator.observe(0, 1_000), 80);
|
||||
assert.equal(estimator.observe(20, 1_020), 80);
|
||||
const target = estimator.observe(40, 1_080);
|
||||
assert.ok(target > 80, `expected target above 80 ms, received ${target}`);
|
||||
assert.ok(target <= 300);
|
||||
});
|
||||
|
||||
test("schedule reset and recovery thresholds keep hysteresis", () => {
|
||||
assert.equal(shouldResetSchedule(200, 80), true);
|
||||
assert.equal(shouldResetSchedule(130, 80), false);
|
||||
assert.equal(shouldResetSchedule(400, 80), true);
|
||||
assert.equal(shouldResetSchedule(300, 80), false);
|
||||
assert.equal(shouldRecover(10), true);
|
||||
assert.equal(shouldRecover(30), false);
|
||||
});
|
||||
@@ -79,7 +79,14 @@ test("legacy playback keeps the original 80 ms window and tears down on overflow
|
||||
const decoder = FakeDecoder.instances.at(-1)!;
|
||||
for (let index = 0; index < 4; index++) decoder.callbacks.output(decodedChunk());
|
||||
assert.deepEqual(FakeSource.instances.map(source => Math.round(source.startedAt * 1_000)), [0, 20, 40, 60]);
|
||||
assert.deepEqual(playback.getStats(), { bufferTargetMs: 80, bufferResets: 0, maxBufferAheadMs: 80 });
|
||||
assert.deepEqual(playback.getStats(), {
|
||||
bufferTargetMs: 80,
|
||||
bufferResets: 0,
|
||||
maxBufferAheadMs: 80,
|
||||
skippedFrames: 0,
|
||||
concealedFrames: 0,
|
||||
lateFrames: 0,
|
||||
});
|
||||
const chunk = decodedChunk();
|
||||
decoder.callbacks.output(chunk);
|
||||
assert.equal(chunk.closed, 1);
|
||||
@@ -87,6 +94,27 @@ test("legacy playback keeps the original 80 ms window and tears down on overflow
|
||||
assert.equal(FakeSource.instances.length, 4);
|
||||
});
|
||||
|
||||
test("a late sequence gap never schedules concealment in the past", async t => {
|
||||
installFakes(t);
|
||||
const context = new FakeContext();
|
||||
const playback = createRemotePlayback({
|
||||
getContext: () => context as unknown as AudioContext,
|
||||
getVolume: () => 1,
|
||||
onDecodeError() {},
|
||||
onDrop() {},
|
||||
mode: "adaptive",
|
||||
maxBufferAheadMs: 80,
|
||||
});
|
||||
playback.play(7, 4, opusFrame, { audioStartMs: 0, seq: 1 });
|
||||
FakeDecoder.instances.at(-1)!.callbacks.output(decodedChunk());
|
||||
context.currentTime = 0.5;
|
||||
playback.play(7, 4, opusFrame, { audioStartMs: 20, seq: 3 });
|
||||
FakeDecoder.instances.at(-1)!.callbacks.output(decodedChunk());
|
||||
const starts = FakeSource.instances.map(source => source.startedAt);
|
||||
assert.ok(starts.slice(1).every(start => start >= 0.5), `concealment must not start in the past: ${starts.join(",")}`);
|
||||
assert.ok(starts.some(start => start >= 0.52), "the concealed frame occupies a future slot");
|
||||
});
|
||||
|
||||
test("adaptive playback resets its schedule without destroying the decoder", async t => {
|
||||
installFakes(t);
|
||||
const context = new FakeContext();
|
||||
@@ -98,11 +126,14 @@ test("adaptive playback resets its schedule without destroying the decoder", asy
|
||||
mode: "adaptive",
|
||||
maxBufferAheadMs: 80,
|
||||
});
|
||||
playback.play(7, 4, opusFrame);
|
||||
for (let index = 0; index < 5; index++) playback.play(7, 4, opusFrame);
|
||||
const decoder = FakeDecoder.instances.at(-1)!;
|
||||
for (let index = 0; index < 5; index++) decoder.callbacks.output(decodedChunk());
|
||||
assert.deepEqual(FakeSource.instances.map(source => Math.round(source.startedAt * 1_000)), [80, 100, 120, 140, 80]);
|
||||
assert.deepEqual(FakeSource.instances.map(source => Math.round(source.startedAt * 1_000)), [80, 100, 120, 140]);
|
||||
assert.equal(decoder.closed, 0);
|
||||
assert.equal(FakeSource.instances.filter(source => source.stopped === 1).length, 4);
|
||||
assert.deepEqual(playback.getStats(), { bufferTargetMs: 80, bufferResets: 1, maxBufferAheadMs: 160 });
|
||||
assert.equal(FakeSource.instances.filter(source => source.stopped === 1).length, 0);
|
||||
const stats = playback.getStats();
|
||||
assert.equal(stats.bufferResets, 0);
|
||||
assert.equal(stats.skippedFrames, 1, "a burst that would exceed the target drops its newest frame");
|
||||
assert.equal(stats.maxBufferAheadMs, 160);
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { createServer } from "vite";
|
||||
import { computed, effectScope, nextTick, ref } from "vue";
|
||||
import { encodeVoiceBatch } from "../../src/shared/voice-audio.ts";
|
||||
|
||||
// Exercise the actual composable and shared wire parser. Only browser/network
|
||||
// boundaries are simulated; these tests make no claim about real audio quality.
|
||||
@@ -1993,6 +1994,7 @@ test("session recovery resets compatibility diagnostics without mutating old sna
|
||||
assert.deepEqual(current.fallbackPlayback, {
|
||||
framesReceived: 0, framesDropped: 0, decodeErrors: 0,
|
||||
bufferTargetMs: 0, bufferResets: 0, maxBufferAheadMs: 0,
|
||||
skippedFrames: 0, concealedFrames: 0, lateFrames: 0,
|
||||
});
|
||||
assert.equal(previous.fallbackPlayback.framesReceived, 2);
|
||||
});
|
||||
@@ -2241,17 +2243,48 @@ test("adaptive profile from connected switches playback without requiring CFT tr
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1, voiceProfile: "adaptive", audioJitterMaxMs: 300, audioUplinkCodecs: ["pcm"] });
|
||||
await nextTurn();
|
||||
receiveAudio(socket);
|
||||
for (let index = 0; index < 5; index++) receiveAudio(socket);
|
||||
const decoder = AudioDecoderStub.instances.at(-1);
|
||||
const initialGain = AudioContextStub.gains.at(-1);
|
||||
const chunks = Array.from({ length: 5 }, decodedChunk);
|
||||
for (const chunk of chunks) decoder.callbacks.output(chunk);
|
||||
assert.deepEqual(AudioContextStub.sources.map(source => Math.round(source.startedAt * 1_000)), [80, 100, 120, 140, 80]);
|
||||
assert.deepEqual(AudioContextStub.sources.map(source => Math.round(source.startedAt * 1_000)), [80, 100, 120, 140]);
|
||||
assert.equal(decoder.closed, 0);
|
||||
assert.equal(initialGain.disconnects, 0);
|
||||
assert.ok(chunks.every(chunk => chunk.closed === 1));
|
||||
});
|
||||
|
||||
test("v3 negotiation sends audioCaps and plays one batched tunnel message", async () => {
|
||||
const socket = await connect();
|
||||
socket.receive({
|
||||
type: "connected", tsClientId: 1, voiceProfile: "adaptive",
|
||||
audioDownlinkVersions: [2, 3], audioUplinkCodecs: ["pcm"], audioJitterMaxMs: 300,
|
||||
});
|
||||
const caps = socket.messages.find(message => message?.type === "audioCaps");
|
||||
assert.deepEqual(caps?.payload, { downlinkVersion: 3, maxFrameMs: 40, codecs: ["pcm"] });
|
||||
socket.receive({ type: "audioConfig", downlinkVersion: 3, frameMs: 20, uplinkCodecs: ["pcm"], jitterMaxMs: 300 });
|
||||
const decodersBefore = AudioDecoderStub.instances.length;
|
||||
const packet = encodeVoiceBatch(1_000, [
|
||||
{ codec: 4, clientId: 7, seq: 1, data: new Uint8Array([1, 2, 3]) },
|
||||
{ codec: 4, clientId: 1, seq: 1, data: new Uint8Array([4, 5, 6]) },
|
||||
]);
|
||||
assert.ok(packet);
|
||||
socket.onmessage({ data: packet.buffer });
|
||||
assert.equal(AudioDecoderStub.instances.length, decodersBefore + 1, "one batch creates one decoder for the remote speaker");
|
||||
});
|
||||
|
||||
test("a 40 ms audioConfig changes the compatibility capture frame size", async () => {
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1, voiceProfile: "adaptive" });
|
||||
await nextTurn();
|
||||
socket.receive({ type: "audioConfig", downlinkVersion: 3, frameMs: 40, uplinkCodecs: ["pcm"], jitterMaxMs: 300 });
|
||||
const sentBefore = socket.messages.length;
|
||||
for (const processor of AudioContextStub.processors) {
|
||||
processor.onaudioprocess?.({ inputBuffer: { getChannelData: () => new Float32Array(1_920).fill(0.2) } });
|
||||
}
|
||||
assert.ok(socket.messages.slice(sentBefore).some(message => message instanceof ArrayBuffer && message.byteLength === 3_840));
|
||||
});
|
||||
|
||||
test("legacy playback stays within its 80 ms window and tears down the decoder on overflow", async () => {
|
||||
const socket = await connect();
|
||||
receiveAudio(socket);
|
||||
|
||||
Reference in new issue
Block a user