diff --git a/CLAUDE.md b/CLAUDE.md index eef8943..10f12cb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -25,7 +25,8 @@ WebSpeak connects browser users to TeamSpeak 3 and TeamSpeak 6 through a self-ho | `web/src/voice/screen-share.ts` | Per-session screen capture, peer negotiation, cleanup and diagnostics | | `web/src/voice/remote-playback.ts` | Per-speaker compatibility decoding, bounded scheduling, volume and resource cleanup | | `web/src/voice/microphone-test.ts` | Cancellable recording tests, recorder deadline and playback URL ownership | -| `web/src/voice/microphone-capture.ts` | Prepared microphone processing graphs, per-context worklet loading, optional RNNoise and independent PCM activation/cleanup | +| `web/src/voice/microphone-capture.ts` | Prepared microphone processing graphs, per-context worklet loading, GTCRN/RNNoise engines, 80 Hz high-pass, preload-before-constraints fallback and independent PCM activation/cleanup | +| `web/src/voice/noise-suppression.ts` | Noise-suppression modes, capability/fallback resolution and stored-preference migration | | `web/src/voice/audio-sink.ts` | Serialized device routing per audio endpoint, with stale-operation guards | | `web/src/voice/accompaniment.ts` | Generation-bound display-audio capture, immediate pending-capture cancellation, ended listeners and committed activity | | `web/src/voice/webrtc-input.ts` | Stable WebRTC sender output, microphone gain and transactional accompaniment-source attachment | @@ -110,10 +111,12 @@ Preserve bounded audio buffering and stale-playback recovery. Audio counters sta Remote playback owns each speaker's decoder, gain and source nodes as one resource set. Member departure, decoder failure and session teardown release that set; queued callbacks must not touch its replacement. Preserve the 80 ms playback window and three-frame decoder queue threshold unless audio validation justifies changing them. -Microphone recording tests own their recorder, timeout and object URL, while the capture layer owns the microphone stream. A normal stop may publish its final recording; replacement and session teardown discard late results and revoke the old URL. Stopping a test while connected must preserve room capture. Test cancellation and stale permission failures must not change a newer test's state. +Microphone recording tests own both recorders (raw and denoised), their timeout and object URLs, while the capture layer owns the microphone stream. A normal stop may publish its final recordings; replacement and session teardown discard late results and revoke both old URLs. Stopping a test while connected must preserve room capture. Test cancellation and stale permission failures must not change a newer test's state. Device and noise-suppression changes share one configuration operation. Persist only the last successful settings; stale failures cannot roll back a newer choice. Acquiring a replacement microphone must preserve the current WebRTC peer and compatibility PCM capture until the replacement is ready. Capture callbacks are invalidated when their graph stops, separately from permission-request generations. Closing settings also releases standalone device-preview capture when no recording was started. +Microphone denoising has four modes: off, browser, RNNoise and GTCRN. Model engines are exclusive with the browser noise suppressor; never request both. Preload the selected model before acquiring the microphone so a load failure can fall back to browser denoising without a second permission prompt, and report the active engine plus a visible fallback reason. Both neural engines require a 48 kHz context. An unrecognised stored mode migrates to GTCRN, and the legacy `noiseSuppressionLevel` mirror is written for older builds. + Prepare microphone nodes and streams before replacing the live graph. A failed allocation or delayed worklet load must leave the old capture usable. Aborting preparation releases its candidate resources immediately; only activation enables PCM callbacks. Worklet module caches belong to their AudioContext. Device removal uses the normal input/output configuration transactions, including WebRTC restart and rollback on failed default-device selection. A committed graph becomes the fallback preference before subsequent device enumeration completes. Serialize `setSinkId` on each audio context or media element, since an in-flight browser sink change cannot be cancelled. Bind subsequent work to the original endpoint and current operation; session teardown invalidates queued changes and device enumeration results. If one output endpoint rejects after another changed, attempt to restore the last committed output. diff --git a/README.md b/README.md index ed182f3..720ae4c 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Join voice channels, chat and share your screen from a browser. Deploy your own | 能力 · Capability | 说明 · Highlights | | --- | --- | -| 🎙️ 语音 · Voice | Opus、可选 WebRTC、WebSocket 回退、降噪与成员音量 / Opus, optional WebRTC, fallback, noise suppression and per-member volume | +| 🎙️ 语音 · Voice | Opus、可选 WebRTC、WebSocket 回退、GTCRN / RNNoise 双引擎降噪、成员音量 / Opus, optional WebRTC, fallback, GTCRN/RNNoise denoising and per-member volume | | 💬 频道与聊天 · Channels & chat | 实时频道树、成员状态、私聊与本地历史 / Live channel tree, member state, private chat and local history | | 🖥️ 屏幕共享 · Screen sharing | 浏览器之间及与受支持的 TS6 客户端互通 / Between browsers and supported native TS6 clients | | 🎨 皮肤 · Skins | `.wskin` 外观、布局和小组件,支持 GitHub 分发 / Portable appearance, layouts and widgets, distributed through GitHub | diff --git a/deploy/coturn/README.md b/deploy/coturn/README.md index 163a9d1..f345902 100644 --- a/deploy/coturn/README.md +++ b/deploy/coturn/README.md @@ -47,13 +47,30 @@ WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all WEBSPEAK_VOICE_PROFILE=auto ``` -TURN does not require Opus; `WEBSPEAK_VOICE_OPUS_WS` remains off by default. +TURN does not require Opus. Compatibility Opus defaults to auto (adaptive +browsers use WebCodecs when available and fall back to PCM); set +`WEBSPEAK_VOICE_OPUS_WS=0` to force PCM. `WEBSPEAK_TURN_REST_URLS` accepts only `turn:`/`turns:` URL tokens. For static ICE credentials, use `WEBSPEAK_VOICE_ICE_SERVERS` with a JSON array of ICE server objects instead. WebSpeak generates short-lived `username`/`credential` pairs with HMAC-SHA1, compatible with coturn's `use-auth-secret`. +### Using a bare public IP + +If the web domain only resolves to Cloudflare Tunnel, keep TURN on the public +IP rather than on that domain: + +```bash +WEBSPEAK_TURN_REST_URLS='turn:203.0.113.10:3478?transport=udp,turn:203.0.113.10:3478?transport=tcp' +``` + +`turn:` is cleartext TURN and needs no DNS name or certificate. If TCP/3478 is +blocked, change coturn's `--listening-port` to `443` (and allow TCP/443), then +use `turn:203.0.113.10:443?transport=tcp`. Only `turns:` requires a +certificate. The web page can still be served as HTTPS/WSS by Cloudflare +Tunnel; media does not use that hostname. + ## 4. Verify From a network that blocks direct UDP, open the voice page and check: @@ -80,3 +97,6 @@ adaptive jitter buffer. - This template has not been exercised end-to-end with a live Tunnel and browser deployment; validate TURN reachability and credentials in the target network before relying on it. +- Using a bare IP for media does not by itself determine whether a public + service needs ICP filing or another permit; confirm the applicable + requirements for the host's jurisdiction and use. diff --git a/docs/CLOUDFLARE_TUNNEL_VOICE.md b/docs/CLOUDFLARE_TUNNEL_VOICE.md index 349837a..3e1bce4 100644 --- a/docs/CLOUDFLARE_TUNNEL_VOICE.md +++ b/docs/CLOUDFLARE_TUNNEL_VOICE.md @@ -4,14 +4,18 @@ 核心原则: - **WebRTC 优先直连**:浏览器直接向网关公网 IP 的 `40000–40099/UDP` 发包。 + 网页域名只解析到 Cloudflare,供 Tunnel 的 HTTPS/WSS 使用;媒体地址填公网 IP。 - **Tunnel 只承载 HTTPS/WSS**:Cloudflare Tunnel 不转发 UDP,不能把 Cloudflare 代理域名当作 ICE 媒体地址。 - **TURN 只做后备**:手机流量、公司网络或 UDP 被拦时,才让媒体走 - `turn:`/`turns:`,不默认全程 `relay`。 + `turn:`/`turns:`,不默认全程 `relay`。`turn:` 不需要域名或证书,可以继续用 + 同一个公网 IP。 - **CFT 是增量路径**:默认 `WEBSPEAK_VOICE_PROFILE=auto`,非可信 Cloudflare 请求继续使用原有的 80ms 固定窗口、裸 1920 字节 PCM 和旧混音参数;只有 经过可信 Cloudflare 代理的请求(或显式 `adaptive`)才启用自适应 buffer / pacer / 修正后的 RTP marker。不配置 CFT、TURN 或新变量时,直连部署保持原行为。 +- **兼容模式是兜底而非二等路径**:v3 批量下行、音频时钟、p95 抖动、丢包隐藏 + 和 Opus 默认协商都只对 `adaptive` 生效;完全不能 UDP 的客户端仍能通话。 ## 兼容性矩阵 @@ -35,12 +39,17 @@ UDP 端口仍按原配置工作。 - **语音模式**:`自动`(推荐,直连走 `legacy`、可信 Cloudflare 代理走 `adaptive`)、`兼容模式`、`自适应`。 -- **兼容模式 Opus**:仅 `adaptive` 生效,默认关闭;浏览器不支持时自动回退 - PCM。 +- **兼容模式 Opus**:默认开启(auto)。仅 `adaptive` 生效;浏览器没有 + WebCodecs `AudioEncoder` 或编码器初始化失败时自动回退 PCM,不会因为开关 + 打开就发不出声音。 - **自适应 jitter 上限**:80–500 ms,配置自适应缓冲目标的上限;它不是严格的 播放前瞻上限,调低也不会恢复旧版超限 `clear()` 行为。 +- **兼容模式调优**:兼容模式帧长 `20/40 ms`、直连失败后自动 TURN 重试、 + 入口强制按 Cloudflare 处理。默认 `20 ms`、自动重试开启、强制识别关闭。 - **TURN 后备**:TURN REST URL、共享密钥和凭证有效期。TURN 只在直连 UDP - 失败后使用,不作为默认路径。 + 失败后使用,不作为默认路径。直连失败且存在 TURN 时,浏览器会自动做一次 + relay-only 重试(约 3 秒后),兼容音频在此期间继续播放;自动重试可在 + “兼容模式调优”里关闭。 保存后对**新的语音连接**生效,不需要重启网关。配置持久化在数据库中:控制台 非空值覆盖对应环境变量,未配置的字段继续继承环境变量;清空 TURN URL 或在 @@ -65,6 +74,27 @@ Cloudflare 判定只接受来自 `WEBSPEAK_TRUSTED_PROXIES` 中直接相邻代 4. `webrtc_public_host` 为空时,直连部署仍可按请求入口推断;但通过 Cloudflare 的请求不会再拿 CF 边缘 `Host` 当 ICE 地址,避免“看起来 配置好了、实际没有媒体路径”。Cloudflare 场景请显式填写公网媒体地址。 +5. “服务器 → 语音”里的 **WebRTC** 总开关必须打开;只填公网媒体地址但关闭 + WebRTC 时,`connected` 仍会报告 `webrtcAvailable=false`。 + +### 1.3 只有公网 IP、域名不落地 ICP 的部署 + +这是本项目推荐的 CFT 组合,也是“有公网 IP + 域名但不想把域名备案到境内源站” +时最省事的做法: + +- 域名只添加 Cloudflare DNS 记录,由 Cloudflare Tunnel 回源到本机的 + HTTPS/WSS 端口;源站不直接监听域名,也不使用该域名做媒体地址。 +- WebRTC 媒体使用 `<公网IP>:40000–40099/UDP`。浏览器拿到的是 IP 候选, + 不依赖域名解析、证书或 CDN 回源。 +- TURN 可以继续用同一个公网 IP:`turn:<公网IP>:3478?transport=udp` 和 + `?transport=tcp` 都是明文 TURN,不需要域名或证书;只有 `turns:` 才需要 + 证书。需要 443/TCP 时,把 coturn 的 `listening-port` 改成 443 并放行 TCP, + URL 写 `turn:<公网IP>:443?transport=tcp`。 +- Cloudflare Realtime TURN 只作为“UDP 全封”的最后兜底;它本身经过跨境网络, + 大陆用户的实际质量需要实测,不能替代同机 coturn。 + +媒体链路不使用域名,不等于对 ICP、许可或其他落地要求作出判断;这些要求由 +部署方根据所在地区、用途和实际接入方式自行确认。本文只描述技术链路。 ## 2. 服务端环境变量 @@ -81,8 +111,11 @@ CFT/TURN 调整建议直接用控制台,避免同时维护两套配置。 | `WEBSPEAK_TURN_REST_URLS` | 空 | coturn REST 的 `turn:`/`turns:` URL,逗号分隔;最多 8 个。 | | `WEBSPEAK_TURN_REST_SECRET` | 空 | 与 coturn `static-auth-secret` 相同的密钥,至少 16 字符才启用。 | | `WEBSPEAK_TURN_REST_TTL_SECONDS` | `21600` | TURN 临时凭证有效期,范围 300–86400。 | -| `WEBSPEAK_VOICE_OPUS_WS` | `0` | 兼容模式是否允许浏览器用 WebCodecs 发 Opus;仅 `adaptive` 且环境变量或控制台显式启用时生效,不支持时自动回退 PCM。 | +| `WEBSPEAK_VOICE_OPUS_WS` | `1` | 兼容模式是否允许浏览器用 WebCodecs 发 Opus;仅 `adaptive` 生效,默认 auto:浏览器不支持时自动回退 PCM。设为 `0` 可强制 PCM。 | | `WEBSPEAK_VOICE_JITTER_MAX_MS` | `300` | 自适应 jitter buffer 的上限,范围 80–500;仅 `adaptive` 生效。 | +| `WEBSPEAK_VOICE_FRAME_MS` | `20` | 兼容模式帧长 `20` 或 `40`。40 ms 会把下行批量消息再减半,客户端上行 PCM 也按 40 ms 打包并由服务端拆回 20 ms;每个说话人最多多出 20 ms 等待。控制台“兼容模式调优”里的对应设置优先。 | +| `WEBSPEAK_VOICE_AUTO_RELAY_RETRY` | `1` | 设为 `0` 关闭首次直连失败后的自动 relay-only 重试;控制台开关优先。 | +| `WEBSPEAK_ASSUME_CLOUDFLARE` | 空 | 设为 `1` 时把语音入口一律按 Cloudflare 处理,适用于反向代理清掉了 `cf-ray` 等头但实际仍走 CFT 的部署;控制台开关优先。 | 示例(直连优先 + TURN 后备): @@ -120,14 +153,23 @@ TLS 控制连接。因此 `turns:` 在 `iceUseTcp: false` 下仍可用。该结 自适应分支: -- jitter buffer:目标超前量按到达 jitter 估算,初始 80ms,上限默认 - 300ms;溢出时只重排播放头、保留 `AudioDecoder`,不再每次超过 80ms - 就销毁解码器。 -- 解码队列硬上限 12;只有极深积压才丢最新帧。 -- 上行 20ms pacer;新帧格式 `0x01 + PCM` 和 `0x02 + Opus`,旧 1920 字节 - PCM 仍兼容。 -- 仅当 `adaptive` 且环境变量或控制台显式启用 Opus,同时浏览器支持 - WebCodecs 时才发 Opus,否则自动回退 PCM。 +- **v3 批量下行**:服务端按 20/40 ms tick 把同一时刻多个说话人的包合并成一条 + 二进制消息(`0xF3` 头 + 音频时钟 + 每发言人 entry),消息数从“每包一条”降 + 到“每 tick 一条”;旧前端不发 `audioCaps` 时自动保持 v2 逐包格式。 +- **音频时钟调度**:播放器用批次里的 `audioStartMs` 作为锚点,而不是每个包 + 各自用 `currentTime` 重排;隧道一次突发到达多包时,后续包仍落在连续时间线上。 +- **p95 抖动目标**:2 秒 / 100 样本窗口的 95 分位,目标 `60 + p95`,下限 + 80 ms、上限由 `audioJitterMaxMs` 控制;快升(每次最多 +40 ms)、慢降 + (每 2 秒 -2 ms),避免平均值把突发尾部吃掉后又反复欠载。 +- **丢包隐藏 / 跳帧**:seq 连续缺 1–8 帧时用上一帧做线性衰减隐藏(PLC),最多 + 3 帧;领先目标 60 ms 以上跳 1 帧,领先 300 ms 以上重锚;静音超过 200 ms + 只重置抖动窗口,播放头仍由音频时钟决定,时钟跳变时再重锚。 +- 解码队列硬上限 12;只有极深积压才丢最新帧,不再因为 80 ms 窗口反复销毁 + 解码器。 +- 上行 20 ms pacer;新帧格式 `0x01 + PCM` 和 `0x02 + Opus`,旧 1920 字节 + PCM 仍兼容;服务端也接受 40 ms(3840 字节)PCM 并拆成两个 20 ms 帧。 +- Opus 默认协商,24 kbps、`packetlossperc=10`、`useinbandfec=true`;浏览器 + 没有 WebCodecs 或初始化失败时回退 PCM。 legacy 分支: @@ -159,12 +201,20 @@ legacy 分支: 1. 同一网络下先用直连 UDP:`chrome://webrtc-internals` 选中 pair 应为 `host`/`srflx`,不是 `relay`。 2. 手机 4G/5G 或关 UDP 的 Wi-Fi 再测:没有直连时才会出现 `relay`,且 - 音频可通。 + 音频可通。第一次直连失败后,页面会出现“正在通过 TURN 中继重试”,兼容 + 音频不应中断;relay 成功后横幅消失。 3. 对未下发 WebRTC 的路径(关闭 WebRTC、无媒体路径或浏览器不支持)测 - 2–3 分钟兼容模式。确认连接 - `connected` 消息中的 `voiceProfile` 为 `adaptive` 后,`bufferResets` + 2–3 分钟兼容模式。确认连接 `connected` 消息中的 `voiceProfile` 为 + `adaptive`,且 `audioDownlinkVersions` 包含 `3`;浏览器应在发 + `audioCaps` 后收到 `audioConfig.downlinkVersion=3`。`bufferResets` 不应持续增长、没有解码器反复重建;若为 `legacy`,看到旧 80ms 行为是 预期的。 +4. 兼容模式统计里 `downlinkBatchMessages` 应明显小于 + `downlinkBatchEntries`(多人同时说话时约等于“tick 数”而不是“包数”); + `skippedFrames`/`concealedFrames` 偶发增长正常,持续快速增长才说明目标 + 缓冲或网络异常。 +5. 关闭 CFT 或直连部署时,确认 `voiceProfile=legacy`、没有 + `audioDownlinkVersions`,旧客户端行为不变。 **回滚** @@ -173,6 +223,9 @@ legacy 分支: 80ms/`clear()`、裸 PCM、旧 WebRTC mixer;不需要回退前端构建。 - 关闭兼容模式 Opus:在管理台取消“兼容模式使用 Opus”,或设置 `WEBSPEAK_VOICE_OPUS_WS=0`;注意只有 `adaptive` 会下发 Opus 能力。 +- 回退 v3 批量下行:设置 `WEBSPEAK_VOICE_FRAME_MS=20` 只影响 tick,不会回退 + 协议;要强制旧格式,可让前端不发送 `audioCaps`(回退前端构建),或临时在 + 服务端禁用 v3 协商。回滚到 0.3.3 前端时,新服务端会自动走 v2。 - 限制 jitter 缓冲:管理台把“自适应 jitter 上限”调到 80,或设置 `WEBSPEAK_VOICE_JITTER_MAX_MS=80`;这只是把上限压回 80ms,**不会恢复 旧版“超过 80ms 就 `clear()` 解码器”的行为**。要完全回到旧行为,使用 diff --git a/docs/MICROPHONE_DENOISE.md b/docs/MICROPHONE_DENOISE.md new file mode 100644 index 0000000..fca1671 --- /dev/null +++ b/docs/MICROPHONE_DENOISE.md @@ -0,0 +1,79 @@ +# 麦克风降噪(GTCRN / RNNoise) + +WebSpeak 的麦克风链提供四档降噪:关闭、标准(浏览器)、轻量(RNNoise)、强效(GTCRN)。默认使用 GTCRN,全部在浏览器本地运行,不上传音频、不依赖 CDN。 + +## 引擎对比 + +| 引擎 | 模型/体积 | 帧长与延迟 | 说明 | +| --- | --- | --- | --- | +| GTCRN(默认) | 23.7K 参数,`gtcrn.wasm` ≈ 197 KB(gzip ≈ 116 KB) | 768 样本 ≈ 16 ms @48 kHz | ICASSP 2024,同量级质量高于 RNNoise;MIT | +| RNNoise | 85 KB,SIMD 版本 ≈ 157 KB | 480 样本 ≈ 10 ms @48 kHz | 低配设备与兼容兜底 | +| 浏览器 APM | 浏览器内置 | 浏览器内部 | `noiseSuppression: true`;Chrome 默认约 12 dB,档位不可从 `getUserMedia` 选择 | +| 关闭 | — | 0 | 不做任何处理 | + +两个神经引擎都按 48 kHz 设计。音频上下文不是 48 kHz、没有 `AudioWorklet`,或 WASM 预加载失败时,自动回退到浏览器降噪。 + +## 信号链 + +``` +getUserMedia (EC=on, AGC=off, NS=按模式) + → MediaStreamSource + → [模型模式] BiquadFilter(highpass, 80 Hz, Q=0.707) + → [模型模式] GTCRN / RNNoise (AudioWorklet) + → GainNode + → MediaStreamDestination (WebRTC) + capture worklet (兼容 PCM) +``` + +- 模型模式与浏览器降噪**互斥**。浏览器先削语音、模型再处理会损伤音质,也会浪费 CPU。 +- 80 Hz 高通只加在模型链上,去掉风扇、桌面震动和手持低频隆隆声。 +- 不做干湿混合:GTCRN 没有衰减上限 API,干声需精确延迟 768 样本才能对齐,否则产生梳状滤波。 +- 不新增噪声门:现有 VOX 已负责静音门控,模型后再叠 gate 容易切掉字头。 + +## 回退与状态 + +| 条件 | 结果 | +| --- | --- | +| 无 `AudioWorklet` | `browser`,原因 `no-worklet` | +| 音频上下文非 48 kHz | `browser`,原因 `sample-rate` | +| WASM / worklet 预加载失败 | `browser`,原因 `load-failed` | +| 预加载成功但节点构造失败 | 本次不挂模型,`off` + `load-failed`,设置页显示“模型未能启动,本次不降噪”,下次重连重试 | +| 浏览器忽略 `noiseSuppression:false` | 照常运行,状态显示可能叠加 | + +设置页会显示实际生效引擎与回退原因,而不是只显示用户选择。`microphoneProcessing` 同时向皮肤暴露 `noiseSuppressionEnabled` 布尔值,旧契约不变。 + +## 参考项目 + +| 项目 | 采用点 | +| --- | --- | +| Jitsi Meet | RNNoise 跑在 AudioWorklet;模型降噪开启时关闭浏览器降噪 | +| Element Call / matrix-js-sdk | `@sapphi-red/web-noise-suppressor` 的 worklet 生命周期管理 | +| WorkAdventure | 双引擎可切换、48 kHz 上下文要求;其 DFN3 方案因 71 ms 延迟未采用 | +| Mumble | 引擎选择 + 本地回环试听 | +| OBS Studio | RNNoise 作低配档、降噪与噪声门分离 | +| WebRTC APM | NS 档位与 80 Hz 高通;浏览器档位不可编程,只作兜底 | +| LiveKit / Krisp | 商业模型体积与授权不适合自托管,未采用 | +| DeepFilterNet3 | 质量更高但模型 + WASM 约 11 MB、附加 30–71 ms,留作后续可选 | + +## 手工验证记录 + +自动化测试不声称真实音质。每次改动采集链后,在 `web/` 下 `npm run build` 并记录: + +| 环境 | 采样率 | 实际引擎 | 附加延迟 | CPU | 结论 | +| --- | --- | --- | --- | --- | --- | +| Chromium(无头 Chrome,`--autoplay-policy=no-user-gesture-required`,220 Hz 测试音) | 48 kHz | GTCRN | 16 ms | 未测 | 通过:`engine=gtcrn`、`fallback=null`;700 ms 收到 35 帧 PCM,稳态音被模型明显衰减 | +| Chrome / Edge(Windows,真实麦克风) | 48 kHz | GTCRN | 16 ms | 待测 | 待听感与 CPU 复测 | +| Firefox(Windows) | 48 kHz | 待测 | 16 ms | 待测 | 待测 | +| Android WebView | 48 kHz | 待测 | 16 ms | 待测 | 待测 | + +验证项: + +1. 设置页显示“当前生效:GTCRN”,切换四档均能重建采集且不中断语音。 +2. 麦克风测试的“原始 / 降噪后”来自同一段 5 秒采集,能听出风扇/键盘差异。 +3. 稳态噪声段衰减 ≥12 dB,语音电平变化 ≤3 dB;键盘声不出现“抽真空”或字头被切。 +4. 阻断 `gtcrn.wasm` 请求后重新连接,状态回退到浏览器降噪且仍能开麦。 + +## 部署注意 + +- 资源由 Vite 打包进 `web/dist/assets`(`gtcrn-*.wasm`、`workletProcessor-*.js`),随现有静态资源一起部署。 +- 若反向代理额外添加 CSP,需要允许 `wasm-unsafe-eval`(WASM 实例化)与 `worker-src 'self' blob:`(AudioWorklet)。 +- 不需要新增环境变量或服务端配置。 diff --git a/docs/README.en.md b/docs/README.en.md index a1a342f..333cd1c 100644 --- a/docs/README.en.md +++ b/docs/README.en.md @@ -199,7 +199,7 @@ The WebRTC advanced settings now include a **public media address**, **IPv6 cand Set a UDP STUN URL such as `stun:turn.teamspeak.com:3478` to use the same discovery service in the browser and gateway. Empty preserves the previous behavior: the gateway library uses its built-in STUN service while the browser has none. The gateway requires an IPv4-reachable UDP STUN hostname or IPv4 address; IPv6 literals and TURN credentials are not accepted. IPv6 media candidates work independently of STUN. Save and reconnect to apply changes. -HTTP/WebSocket reachability does not imply media reachability. Allow the complete configured UDP range and preserve port numbers when using static port forwarding. STUN discovers mappings but cannot relay audio or traverse every NAT. For mobile or UDP-blocked clients, configure an external TURN service as an optional fallback directly under Admin → Voice with the TURN REST URL, shared secret, and credential lifetime; the equivalent environment variables are `WEBSPEAK_TURN_REST_URLS` and `WEBSPEAK_TURN_REST_SECRET`. Console values take precedence and apply to new connections without a gateway restart. Keep `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all` so direct UDP is tried first. `WEBSPEAK_VOICE_PROFILE` defaults to `auto`: only requests received through a trusted Cloudflare proxy use the adaptive buffer; direct and other requests keep the legacy 80 ms/raw-PCM path. Loopback tunnel connections are trusted by default; configure `WEBSPEAK_TRUSTED_PROXIES` when cloudflared connects from another address. Set `adaptive` explicitly to use it on direct deployments too; Admin → Voice can override this mode. Opus over WebSocket is off by default; enable it under Admin → Voice or with `WEBSPEAK_VOICE_OPUS_WS=1`, and use the `adaptive` profile. If neither direct UDP nor TURN provides a media path, the session reports `NO_MEDIA_PATH` and uses the compatibility transport. +HTTP/WebSocket reachability does not imply media reachability. Allow the complete configured UDP range and preserve port numbers when using static port forwarding. STUN discovers mappings but cannot relay audio or traverse every NAT. For mobile or UDP-blocked clients, configure an external TURN service as an optional fallback directly under Admin → Voice with the TURN REST URL, shared secret, and credential lifetime; the equivalent environment variables are `WEBSPEAK_TURN_REST_URLS` and `WEBSPEAK_TURN_REST_SECRET`. Console values take precedence and apply to new connections without a gateway restart. Keep `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all` so direct UDP is tried first. `WEBSPEAK_VOICE_PROFILE` defaults to `auto`: only requests received through a trusted Cloudflare proxy use the adaptive buffer; direct and other requests keep the legacy 80 ms/raw-PCM path. Loopback tunnel connections are trusted by default; configure `WEBSPEAK_TRUSTED_PROXIES` when cloudflared connects from another address. Set `adaptive` explicitly to use it on direct deployments too; Admin → Voice can override this mode. Compatibility Opus defaults to auto: adaptive browsers with WebCodecs use 24 kbps Opus + FEC and fall back to PCM otherwise; set `WEBSPEAK_VOICE_OPUS_WS=0` or disable it under Admin → Voice to force PCM. Adaptive compatibility mode also uses v3 batched downlink (negotiated by `audioCaps`, one message per 20/40 ms tick), an audio-clock anchor, a p95 jitter target, PLC concealment, and one automatic relay retry. If neither direct UDP nor TURN provides a media path, the session reports `NO_MEDIA_PATH` and uses the compatibility transport. See [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md) for the direct-UDP-first topology, coturn/cloudflared templates, verification and rollback notes. diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.md index 9bd8f5c..29393cf 100644 --- a/docs/README.zh-CN.md +++ b/docs/README.zh-CN.md @@ -34,7 +34,7 @@ WebSpeak 是可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语 | 能力 | 说明 | | --- | --- | -| 实时语音 | Opus 音频、可选 WebRTC、兼容 WebSocket 回退;支持闭麦、VOX、设备选择、浏览器降噪和成员独立音量。 | +| 实时语音 | Opus 音频、可选 WebRTC、兼容 WebSocket 回退;支持闭麦、VOX、设备选择、GTCRN / RNNoise 双引擎降噪、原始/降噪 A/B 试听和成员独立音量。 | | 频道与消息 | 频道树、TeamSpeak 频道分隔栏、成员状态、频道切换、频道/服务器/私聊消息、戳一戳、耳语及本地聊天历史。 | | 屏幕与音频共享 | 浏览器之间及与受支持的 TeamSpeak 6 原生客户端共享屏幕;提供采集质量、码率和统计面板,桌面端还可分享窗口或标签页音频。 | | 身份与连接 | 身份保持、TS3 身份导入/导出、收藏和历史连接、SRV 与 Nickname 地址解析、IPv4/IPv6 及邀请链接。 | @@ -220,7 +220,7 @@ WebRTC 启用后端口范围会锁定。要修改端口,先关闭 WebRTC 并 保存后重新连接。网页和 WebSocket 经反代可达,不代表媒体 UDP 可达;STUN 仅发现地址,不中继音频,也不保证穿透所有 NAT。应开放配置的整个 UDP 端口范围;静态端口转发需保持相同端口映射。 -手机流量或 UDP 被拦时,可配置外部 TURN 作为可选后备:在管理台“服务器 → 语音”填写 TURN REST URL、共享密钥和有效期,或使用 `WEBSPEAK_TURN_REST_URLS`、`WEBSPEAK_TURN_REST_SECRET` 环境变量。控制台保存的配置优先,且不需要重启网关,对新连接生效。默认保持 `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all`,先试直连;只有确认 UDP 完全不可用时才用 `relay`。`WEBSPEAK_VOICE_PROFILE` 默认 `auto`:只有经过可信 Cloudflare 代理的请求才启用自适应 buffer,直连及其他请求继续使用旧 80ms/裸 PCM 行为;本机 Tunnel 连接默认可信,cloudflared 从其他地址连接时需配置 `WEBSPEAK_TRUSTED_PROXIES`。需要直连也启用时显式设 `adaptive`,也可在控制台“语音模式”覆盖。WebSocket Opus 默认关闭,可在“服务器 → 语音”或通过 `WEBSPEAK_VOICE_OPUS_WS=1` 启用,并需使用 `adaptive`。直连 UDP 与 TURN 都无法提供媒体路径时,会话报告 `NO_MEDIA_PATH` 并使用兼容传输。完整部署、验收和回滚见 [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md),模板见 `deploy/coturn/` 和 `deploy/cloudflared/`。 +手机流量或 UDP 被拦时,可配置外部 TURN 作为可选后备:在管理台“服务器 → 语音”填写 TURN REST URL、共享密钥和有效期,或使用 `WEBSPEAK_TURN_REST_URLS`、`WEBSPEAK_TURN_REST_SECRET` 环境变量。控制台保存的配置优先,且不需要重启网关,对新连接生效。默认保持 `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all`,先试直连;只有确认 UDP 完全不可用时才用 `relay`。`WEBSPEAK_VOICE_PROFILE` 默认 `auto`:只有经过可信 Cloudflare 代理的请求才启用自适应 buffer,直连及其他请求继续使用旧 80ms/裸 PCM 行为;本机 Tunnel 连接默认可信,cloudflared 从其他地址连接时需配置 `WEBSPEAK_TRUSTED_PROXIES`。需要直连也启用时显式设 `adaptive`,也可在控制台“语音模式”覆盖。兼容模式 Opus 默认 auto:`adaptive` 下浏览器支持 WebCodecs 就用 24 kbps Opus + FEC,否则自动回退 PCM;可在“服务器 → 语音”或通过 `WEBSPEAK_VOICE_OPUS_WS=0` 强制关闭。自适应兼容模式使用 v3 批量下行(`audioCaps` 协商,一个 20/40ms tick 一条消息)、音频时钟锚点、p95 抖动目标、PLC 丢包隐藏和自动 relay 重试。直连 UDP 与 TURN 都无法提供媒体路径时,会话报告 `NO_MEDIA_PATH` 并使用兼容传输。完整部署、验收和回滚见 [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md),模板见 `deploy/coturn/` 和 `deploy/cloudflared/`。 ### 屏幕共享的 ICE 候选 diff --git a/docs/VOICE_FIX_REPORT.md b/docs/VOICE_FIX_REPORT.md index fd80ba4..ed513b3 100644 --- a/docs/VOICE_FIX_REPORT.md +++ b/docs/VOICE_FIX_REPORT.md @@ -18,38 +18,58 @@ ### WebRTC、ICE 与回退 - `src/server/voice-ice-config.ts`:支持静态 ICE、TURN REST、浏览器/网关 - transport policy、语音 profile、Opus WebSocket 和 jitter 上限。 + transport policy、语音 profile、Opus WebSocket(默认 auto)和 jitter 上限。 - `src/server/turn-credentials.ts`:按 coturn `use-auth-secret` 生成短期凭证。 - `src/server/voice-bridge.ts`:仅当直接相邻代理位于 `WEBSPEAK_TRUSTED_PROXIES` 中时,才根据 `cf-ray`、`cf-connecting-ip` 或 `cdn-loop` 判定 Cloudflare。直连客户端注入这些头不会改变 profile。 + `WEBSPEAK_ASSUME_CLOUDFLARE=1` 可覆盖反向代理清掉这些头的部署。 - Cloudflare 请求不再把 Tunnel `Host` 当作 ICE 媒体地址。未配置公网媒体 - 地址且没有 TURN 时返回 `NO_MEDIA_PATH`,浏览器使用兼容传输。 + 地址且没有 TURN 时返回 `NO_MEDIA_PATH`,浏览器使用兼容传输。公网媒体 + 地址可以直接填 IP 字面量,不要求域名或证书。 - 已下发 WebRTC 后建连或传输失败会自动恢复 PCM/Opus over WebSocket 的 上下行兼容音频,页面留在当前 TeamSpeak/WebSocket 会话;上行需要已有 麦克风权限。横幅继续使用 `WEBRTC_FAILED`,并保留“重新连接 WebRTC”。 +- 第一次直连失败且配置了 TURN 时,自动做一次 relay-only 重试(约 3 秒后); + 兼容音频在重试期间继续播放。第二次失败才显示 `WEBRTC_FAILED`。 - “重新连接 WebRTC”只重试 WebRTC,不调用整段连接流程、不新建语音 - WebSocket。重连期间保持兼容收发,等 `onReady` 后才停止兼容音频并清除 - 失败横幅和按钮,避免双路音频或切换静音。 -- 重连再次失败时继续留在兼容模式保通话,横幅和按钮保留。网关未 - advertise WebRTC 的既有兼容路径不变,也不显示这块失败按钮。 + WebSocket;手动重试会恢复配置的直连优先策略并清零自动重试计数。 +- 重连期间保持兼容收发,等 `onReady` 后才停止兼容音频并清除失败横幅和 + 按钮,避免双路音频或切换静音。 - `src/server/webrtc-audio.ts` 与 `web/src/voice/webrtc-transport.ts`:浏览器 - 和网关使用完整 ICE 列表;无 TURN 的 `relay` 策略快速失败。 + 和网关使用完整 ICE 列表;relay 尝试的 ICE/answer/连接超时分别收敛为 + 4/6/10 秒,直连为 6/8/15 秒;直连收到 host/srflx/prflx 后提前 300ms + 结束收集,减少隧道下的无效等待。 - 已从 werift 源码确认 `turns:` 使用 TLS 控制连接;未做真实 coturn 端到端 联调。 ### 兼容模式音频 - `legacy` 保留旧播放窗口、解码器重建、裸 PCM、4 帧 mixer 队列和每包 - marker。 -- `adaptive` 使用 `web/src/voice/jitter-buffer.ts`、可选服务端 pacer 和可选 - Opus-over-WebSocket;Opus 默认关闭。 -- `web/src/voice/opus-uplink.ts` 使用 WebCodecs Opus;不支持或失败时回退 PCM。 + marker;只有显式 `legacy` 或非 Cloudflare 请求使用。 +- `adaptive` 使用 v3 批量下行:服务端按 20/40ms tick 把多个说话人的包合并 + 为一条二进制消息(`0xF3` 头 + `audioStartMs` + per-speaker seq),消息数 + 从“每包一条”降到“每 tick 一条”。旧前端不发 `audioCaps` 时服务端保持 + v2 逐包格式。 +- 迟到 tick 不再把整段积压压成一个时间戳:batcher 按原始 tick 分组,每组 + 单独带音频时钟,客户端才能用 p95 抖动估计发现隧道停顿。 +- `web/src/voice/jitter-buffer.ts` 使用 2 秒 / 100 样本窗口的 p95,目标 + `60 + p95`,下限 80ms、上限由 `audioJitterMaxMs` 控制;快升 +40ms/次, + 慢降 -2ms/2s。 +- `web/src/voice/remote-playback.ts` 用音频时钟做锚点,保留 `AudioDecoder`; + seq 缺口 1–8 时用 PLC 隐藏最多 3 帧,领先 60ms 跳帧,领先 300ms 重锚, + 落后 20ms 插一帧。解码队列硬上限 12,只有极深积压才丢最新帧。 +- `web/src/voice/opus-uplink.ts` 使用 WebCodecs Opus,24kbps、 + `packetlossperc=10`、`useinbandfec=true`;不支持或失败时回退 PCM。 +- 服务端接受 40ms(3840 字节)PCM,拆成两个 20ms 帧后分别 encode/pacer; + 40ms 帧消耗两个 rate token,不能借此翻倍上行速率。 - Safari/Firefox 的 Opus 行为未逐台真机验证。 ### 管理台与持久化 -- 管理台“服务器 → 语音”提供 profile、Opus、jitter 上限和 TURN REST 配置。 +- 管理台“服务器 → 语音”提供 profile、Opus、jitter 上限、TURN REST 配置, + 以及“兼容模式调优”:20/40ms 兼容模式帧长、自动 TURN 重试、强制 Cloudflare + 入口识别。 - 非空控制台值覆盖环境变量;未修改字段保持数据库 `NULL`,继续继承环境变量。 - 清空 TURN URL 或移除密钥会显式停用环境变量中的 TURN REST。 - TURN 密钥使用网关主密钥加密存储,API 只返回是否已配置。 @@ -62,8 +82,10 @@ WEBSPEAK_VOICE_PROFILE=auto WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all WEBSPEAK_VOICE_GATEWAY_ICE_TRANSPORT_POLICY=all WEBSPEAK_VOICE_JITTER_MAX_MS=300 -WEBSPEAK_VOICE_OPUS_WS=0 -WEBSPEAK_TURN_REST_URLS='turn:turn.example.com:3478?transport=udp,turn:turn.example.com:3478?transport=tcp' +WEBSPEAK_VOICE_OPUS_WS=1 +WEBSPEAK_VOICE_FRAME_MS=20 +WEBSPEAK_VOICE_AUTO_RELAY_RETRY=1 +WEBSPEAK_TURN_REST_URLS='turn:203.0.113.10:3478?transport=udp,turn:203.0.113.10:3478?transport=tcp' WEBSPEAK_TURN_REST_SECRET='' WEBSPEAK_TURN_REST_TTL_SECONDS=21600 ``` @@ -78,12 +100,16 @@ WEBSPEAK_TURN_REST_TTL_SECONDS=21600 - 0.3.3 会忽略并保留这些元数据,可以在自动更新健康检查失败后直接恢复旧代码。 - 恢复非 Cloudflare 旧音频行为:选择 `legacy`,或确保没有控制台覆盖后设置 `WEBSPEAK_VOICE_PROFILE=legacy`。 -- 关闭 Opus:取消控制台选项或设置 `WEBSPEAK_VOICE_OPUS_WS=0`。 +- 关闭兼容模式 Opus:取消控制台选项或设置 `WEBSPEAK_VOICE_OPUS_WS=0`。 +- 回退 v3 批量下行:回退前端构建,让浏览器不再发送 `audioCaps`;新服务端 + 会自动走 v2。`WEBSPEAK_VOICE_FRAME_MS=20` 只影响批量 tick,不会回退协议。 - 关闭 TURN:清空 TURN URL/移除密钥,或删除对应环境变量。 ## 验证边界 - coturn/cloudflared 模板未在真实目标网络端到端联调。 +- 公网 IP 的 `40000–40099/UDP` 入站、`443/TCP` 是否可分配给 coturn,需按 + 实际云安全组和主机防火墙验证。 - TURN 的 UDP/TCP/TLS、relay 端口和凭证一致性仍需在目标网络验证。 - Safari/Firefox WebCodecs Opus 与真实浏览器 jitter 表现仍需设备测试。 - 自动化测试和构建结果以本次审查的测试记录为准;历史报告中的通过数量 diff --git a/package.json b/package.json index 5215512..d5573e3 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "scripts": { "dev": "tsx src/index.ts", "build": "tsc", - "test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/turn-credentials.test.ts src/server/voice-ice-config.test.ts src/server/audio-pacer.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/voice-ice.test.ts src/shared/voice-profile.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/jitter-buffer.test.ts web/test/remote-playback.test.ts web/test/opus-uplink.test.ts web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs web/src/services/host-recovery-presentation.test.ts web/test/opus-uplink-browser.test.mjs", + "test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/voice/noise-suppression.test.ts web/src/voice/microphone-test.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/turn-credentials.test.ts src/server/voice-ice-config.test.ts src/server/audio-pacer.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/voice-ice.test.ts src/shared/voice-profile.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/jitter-buffer.test.ts web/test/remote-playback.test.ts web/test/opus-uplink.test.ts web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs web/src/services/host-recovery-presentation.test.ts web/test/opus-uplink-browser.test.mjs src/shared/voice-audio.test.ts src/server/downlink-batcher.test.ts", "verify": "npm test && npm run build && npm run web:build", "skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs", "skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs", diff --git a/src/admin/admin-router.ts b/src/admin/admin-router.ts index 09b949c..8551689 100644 --- a/src/admin/admin-router.ts +++ b/src/admin/admin-router.ts @@ -622,6 +622,9 @@ function readSettingsInput(body: Record): AdminSettingsInput { voiceTurnTtlSeconds: readOptionalInteger(body, "voiceTurnTtlSeconds"), voiceOpusWs: typeof body.voiceOpusWs === "boolean" ? body.voiceOpusWs : undefined, voiceJitterMaxMs: readOptionalInteger(body, "voiceJitterMaxMs"), + voiceDownlinkFrameMs: body.voiceDownlinkFrameMs === 20 || body.voiceDownlinkFrameMs === 40 ? body.voiceDownlinkFrameMs : undefined, + voiceAssumeCloudflare: typeof body.voiceAssumeCloudflare === "boolean" ? body.voiceAssumeCloudflare : undefined, + voiceAutoRelayRetry: typeof body.voiceAutoRelayRetry === "boolean" ? body.voiceAutoRelayRetry : undefined, relaySettingsAction: readRelaySettingsAction(body.relaySettingsAction), relayEnabled: body.relayEnabled === true, relayName: typeof body.relayName === "string" ? body.relayName.slice(0, 80) : undefined, diff --git a/src/admin/admin-service.ts b/src/admin/admin-service.ts index c3dae54..9ae4f27 100644 --- a/src/admin/admin-service.ts +++ b/src/admin/admin-service.ts @@ -156,6 +156,9 @@ export class AdminService { voiceTurnTtlSeconds: turn.ttlSeconds, voiceOpusWs: settings.voiceOpusWs ?? this.voiceIceDefaults.opusWebSocket, voiceJitterMaxMs: settings.voiceJitterMaxMs ?? this.voiceIceDefaults.jitterMaxMs, + voiceDownlinkFrameMs: settings.voiceDownlinkFrameMs ?? this.voiceIceDefaults.downlinkFrameMs, + voiceAssumeCloudflare: settings.voiceAssumeCloudflare ?? this.voiceIceDefaults.assumeCloudflare, + voiceAutoRelayRetry: settings.voiceAutoRelayRetry ?? this.voiceIceDefaults.autoRelayRetry, relayConfigured: settings.relayConfigured, relayEnabled: settings.relayEnabled, relayName: settings.relayName, @@ -193,6 +196,9 @@ export class AdminService { profile: settings.voiceProfile ?? this.voiceIceDefaults.profile, opusWebSocket: settings.voiceOpusWs ?? this.voiceIceDefaults.opusWebSocket, jitterMaxMs: settings.voiceJitterMaxMs ?? this.voiceIceDefaults.jitterMaxMs, + downlinkFrameMs: settings.voiceDownlinkFrameMs ?? this.voiceIceDefaults.downlinkFrameMs, + assumeCloudflare: settings.voiceAssumeCloudflare ?? this.voiceIceDefaults.assumeCloudflare, + autoRelayRetry: settings.voiceAutoRelayRetry ?? this.voiceIceDefaults.autoRelayRetry, }; } @@ -509,6 +515,18 @@ export class AdminService { if (voiceJitterMaxMs !== null && (!Number.isInteger(voiceJitterMaxMs) || voiceJitterMaxMs < VOICE_JITTER_MIN_MS || voiceJitterMaxMs > VOICE_JITTER_MAX_MS)) { throw new AdminInputError("INVALID_VOICE_JITTER_MAX", `Adaptive jitter limit must be between ${VOICE_JITTER_MIN_MS} and ${VOICE_JITTER_MAX_MS} ms`); } + const voiceDownlinkFrameMs = input.voiceDownlinkFrameMs === undefined ? current.voiceDownlinkFrameMs : input.voiceDownlinkFrameMs; + if (voiceDownlinkFrameMs !== null && voiceDownlinkFrameMs !== 20 && voiceDownlinkFrameMs !== 40) { + throw new AdminInputError("INVALID_VOICE_FRAME_MS", "Compatibility frame must be 20 or 40 ms"); + } + const voiceAssumeCloudflare = input.voiceAssumeCloudflare === undefined ? current.voiceAssumeCloudflare : input.voiceAssumeCloudflare; + if (voiceAssumeCloudflare !== null && typeof voiceAssumeCloudflare !== "boolean") { + throw new AdminInputError("INVALID_VOICE_ASSUME_CLOUDFLARE", "Assume-Cloudflare must be a boolean"); + } + const voiceAutoRelayRetry = input.voiceAutoRelayRetry === undefined ? current.voiceAutoRelayRetry : input.voiceAutoRelayRetry; + if (voiceAutoRelayRetry !== null && typeof voiceAutoRelayRetry !== "boolean") { + throw new AdminInputError("INVALID_VOICE_AUTO_RELAY_RETRY", "Automatic relay retry must be a boolean"); + } let turnSecret = ""; if (voiceTurnSecretEncrypted === null) { turnSecret = this.voiceIceDefaults.turnRest?.secret ?? ""; @@ -598,6 +616,9 @@ export class AdminService { voiceTurnTtlSeconds, voiceOpusWs, voiceJitterMaxMs, + voiceDownlinkFrameMs, + voiceAssumeCloudflare, + voiceAutoRelayRetry, relayConfigured, relayEnabled, relayName, @@ -730,6 +751,9 @@ export class AdminService { voiceTurnTtlSeconds: settings.voiceTurnTtlSeconds, voiceOpusWs: settings.voiceOpusWs, voiceJitterMaxMs: settings.voiceJitterMaxMs, + voiceDownlinkFrameMs: settings.voiceDownlinkFrameMs, + voiceAssumeCloudflare: settings.voiceAssumeCloudflare, + voiceAutoRelayRetry: settings.voiceAutoRelayRetry, relayConfigured: settings.relayConfigured, relayEnabled: settings.relayEnabled, relayName: settings.relayName, @@ -768,6 +792,9 @@ export class AdminService { voiceTurnTtlSeconds: current.voiceTurnTtlSeconds, voiceOpusWs: current.voiceOpusWs, voiceJitterMaxMs: current.voiceJitterMaxMs, + voiceDownlinkFrameMs: current.voiceDownlinkFrameMs, + voiceAssumeCloudflare: current.voiceAssumeCloudflare, + voiceAutoRelayRetry: current.voiceAutoRelayRetry, relayConfigured: current.relayConfigured, relayEnabled: current.relayEnabled, relayName: current.relayName, diff --git a/src/persistence/database.test.ts b/src/persistence/database.test.ts index cd90e30..337975a 100644 --- a/src/persistence/database.test.ts +++ b/src/persistence/database.test.ts @@ -14,7 +14,8 @@ test("voice overrides preserve schema 13 and survive an old binary updating ordi const database = new WebSpeakDatabase(filename); const encrypted = encryptSecret("turn-test-secret-value", Buffer.alloc(32, 7), "webspeak:voice-turn-rest-secret:v1"); database.updateSettings({ ...database.getSettings(), voiceProfile: "adaptive", voiceTurnUrls: "turn:turn.example.com:3478", - voiceTurnSecretEncrypted: encrypted, voiceTurnTtlSeconds: 3600, voiceOpusWs: true, voiceJitterMaxMs: 200 }); + voiceTurnSecretEncrypted: encrypted, voiceTurnTtlSeconds: 3600, voiceOpusWs: true, voiceJitterMaxMs: 200, + voiceDownlinkFrameMs: 40, voiceAssumeCloudflare: true, voiceAutoRelayRetry: false }); database.close(); const legacy = new DatabaseSync(filename); try { @@ -31,6 +32,9 @@ test("voice overrides preserve schema 13 and survive an old binary updating ordi assert.equal(settings.voiceTurnSecretEncrypted, encrypted); assert.equal(settings.voiceOpusWs, true); assert.equal(settings.voiceJitterMaxMs, 200); + assert.equal(settings.voiceDownlinkFrameMs, 40); + assert.equal(settings.voiceAssumeCloudflare, true); + assert.equal(settings.voiceAutoRelayRetry, false); reopened.setMeta("voice_settings_v1", "invalid-json"); assert.equal(reopened.getSettings().voiceProfile, null); } finally { reopened.close(); } diff --git a/src/persistence/database.ts b/src/persistence/database.ts index 527908b..bd3e0b5 100644 --- a/src/persistence/database.ts +++ b/src/persistence/database.ts @@ -40,6 +40,9 @@ export interface PersistedSettings { voiceTurnTtlSeconds: number | null; voiceOpusWs: boolean | null; voiceJitterMaxMs: number | null; + voiceDownlinkFrameMs: 20 | 40 | null; + voiceAssumeCloudflare: boolean | null; + voiceAutoRelayRetry: boolean | null; relayConfigured: boolean; relayEnabled: boolean; relayName: string; @@ -73,6 +76,9 @@ export interface SettingsUpdate { voiceTurnTtlSeconds?: number | null; voiceOpusWs?: boolean | null; voiceJitterMaxMs?: number | null; + voiceDownlinkFrameMs?: 20 | 40 | null; + voiceAssumeCloudflare?: boolean | null; + voiceAutoRelayRetry?: boolean | null; relayConfigured: boolean; relayEnabled: boolean; relayName: string; @@ -775,7 +781,7 @@ export class WebSpeakDatabase { } /** Optional settings must survive a code-only rollback to the 0.3.3 schema. */ - private readVoiceSettings(): Pick { + private readVoiceSettings(): Pick { let value: Record = {}; try { const parsed: unknown = JSON.parse(this.getMeta(VOICE_SETTINGS_META_KEY) ?? "{}"); @@ -791,6 +797,10 @@ export class WebSpeakDatabase { voiceOpusWs: typeof value.voiceOpusWs === "boolean" ? value.voiceOpusWs : null, voiceJitterMaxMs: Number.isInteger(value.voiceJitterMaxMs) && Number(value.voiceJitterMaxMs) >= 80 && Number(value.voiceJitterMaxMs) <= 500 ? Number(value.voiceJitterMaxMs) : null, + voiceDownlinkFrameMs: value.voiceDownlinkFrameMs === 20 || value.voiceDownlinkFrameMs === 40 + ? value.voiceDownlinkFrameMs : null, + voiceAssumeCloudflare: typeof value.voiceAssumeCloudflare === "boolean" ? value.voiceAssumeCloudflare : null, + voiceAutoRelayRetry: typeof value.voiceAutoRelayRetry === "boolean" ? value.voiceAutoRelayRetry : null, }; } diff --git a/src/server/audio-stats.ts b/src/server/audio-stats.ts index e8c5ccf..162decd 100644 --- a/src/server/audio-stats.ts +++ b/src/server/audio-stats.ts @@ -33,6 +33,12 @@ export interface AudioFlowStats extends WebRtcAudioStats { egressSentMaxGapMs: number; egressPeakBufferedBytes: number; egressFramesByClient: Record; + downlinkBatchMessages: number; + downlinkBatchEntries: number; + downlinkBatchMaxEntries: number; + downlinkBatchDroppedFrames: number; + downlinkBatchPeakQueueMs: number; + downlinkBatchLateTicks: number; } @@ -74,6 +80,12 @@ export function createAudioFlowStats(): AudioFlowStats { egressSentMaxGapMs: 0, egressPeakBufferedBytes: 0, egressFramesByClient: {}, + downlinkBatchMessages: 0, + downlinkBatchEntries: 0, + downlinkBatchMaxEntries: 0, + downlinkBatchDroppedFrames: 0, + downlinkBatchPeakQueueMs: 0, + downlinkBatchLateTicks: 0, webrtcIngressRtpFrames: 0, webrtcIngressRtpFirstAt: null, webrtcIngressRtpLastAt: null, diff --git a/src/server/downlink-batcher.test.ts b/src/server/downlink-batcher.test.ts new file mode 100644 index 0000000..950c724 --- /dev/null +++ b/src/server/downlink-batcher.test.ts @@ -0,0 +1,84 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { DownlinkBatcher } from "./downlink-batcher.js"; +import { decodeVoiceBatch } from "../shared/voice-audio.js"; + +function fixture(frameMs: 20 | 40 = 20) { + let now = 0; + const packets: { packet: Uint8Array; entries: number; sentAt: number }[] = []; + const batcher = new DownlinkBatcher({ + frameMs, + now: () => now, + subscribe: () => () => {}, + send: (packet, entries, sentAt) => { packets.push({ packet, entries, sentAt }); }, + }); + return { batcher, packets, setNow: (value: number) => { now = value; } }; +} + +test("batcher coalesces one tick of speakers into a single v3 packet", () => { + const f = fixture(); + f.batcher.push(4, 2, Uint8Array.from([1, 2, 3])); + f.batcher.push(5, 3, Uint8Array.from([4, 5])); + f.batcher.push(4, 4, Uint8Array.from([6])); + f.batcher.flush(0); + assert.equal(f.packets.length, 1); + const decoded = decodeVoiceBatch(f.packets[0]!.packet); + assert.ok(decoded); + assert.equal(decoded.audioStartMs, 0); + assert.deepEqual(decoded.entries.map(entry => entry.clientId), [2, 3, 4]); + assert.deepEqual(decoded.entries.map(entry => entry.seq), [1, 1, 1]); + assert.equal(f.batcher.getStats().messages, 1); + assert.equal(f.batcher.getStats().entries, 3); + assert.equal(f.batcher.getStats().maxEntries, 3); +}); + +test("batcher caps entries and bytes per packet while keeping every frame", () => { + const f = fixture(); + for (let id = 1; id <= 40; id++) f.batcher.push(4, id, new Uint8Array(100)); + f.batcher.flush(0); + assert.ok(f.packets.length >= 2); + const decoded = f.packets.flatMap(entry => decodeVoiceBatch(entry.packet)?.entries ?? []); + assert.equal(decoded.length, 40); + assert.ok(Math.max(...f.packets.map(entry => entry.entries)) <= 32); + assert.equal(f.batcher.getStats().droppedFrames, 0); +}); + +test("stale frames and per-speaker sequence gaps survive a tunnel stall", () => { + const f = fixture(); + f.batcher.push(4, 2, Uint8Array.from([1])); + f.setNow(150); + f.batcher.flush(150); + assert.equal(f.packets.length, 0); + assert.equal(f.batcher.getStats().droppedFrames, 1); + f.batcher.push(4, 2, Uint8Array.from([2])); + f.setNow(160); + f.batcher.flush(160); + const decoded = decodeVoiceBatch(f.packets[0]!.packet); + assert.equal(decoded?.entries[0]?.seq, 2, "a dropped frame leaves a detectable gap"); +}); + +test("40 ms batching waits a full negotiated tick", () => { + const f = fixture(40); + f.batcher.push(4, 2, Uint8Array.from([1])); + f.batcher.flush(0); + const decoded = decodeVoiceBatch(f.packets[0]!.packet); + assert.equal(decoded?.audioStartMs, 0); + f.batcher.setFrameMs(20); + f.setNow(20); + f.batcher.push(4, 2, Uint8Array.from([2])); + f.batcher.flush(20); + assert.equal(decodeVoiceBatch(f.packets[1]!.packet)?.audioStartMs, 20); +}); + +test("a late flush keeps one audio timestamp per missed tick", () => { + const f = fixture(); + f.batcher.push(4, 2, Uint8Array.from([1])); + f.setNow(20); + f.batcher.push(4, 2, Uint8Array.from([2])); + // Simulate a 100 ms timer stall: both ticks are still inside the queue + // horizon and must not collapse onto a single playback instant. + f.setNow(100); + f.batcher.flush(100); + assert.equal(f.packets.length, 2); + assert.deepEqual(f.packets.map(entry => decodeVoiceBatch(entry.packet)?.audioStartMs), [0, 20]); +}); diff --git a/src/server/downlink-batcher.ts b/src/server/downlink-batcher.ts new file mode 100644 index 0000000..01a2402 --- /dev/null +++ b/src/server/downlink-batcher.ts @@ -0,0 +1,218 @@ +import { performance } from "node:perf_hooks"; +import { + encodeVoiceBatch, + VOICE_BATCH_MAX_BYTES, + VOICE_BATCH_MAX_ENTRIES, + VOICE_MAX_OPUS_FRAME_BYTES, + type VoiceBatchEntry, +} from "../shared/voice-audio.js"; +import { subscribeDownlink } from "./downlink-scheduler.js"; + +/** + * Coalesces TeamSpeak downlink packets into one binary message per audio tick. + * + * The compatibility path used to send one small WebSocket message per speaker + * per 20 ms. Through Cloudflare Tunnel that becomes a burst of tiny messages + * sharing one TCP connection; batching cuts the message count by the number of + * active speakers and gives the browser an explicit audio clock to schedule on. + */ + +export interface DownlinkBatcherOptions { + frameMs?: 20 | 40; + maxEntries?: number; + maxBytes?: number; + maxQueueMs?: number; + maxQueueEntries?: number; + now?: () => number; + send: (packet: Uint8Array, entries: number, sentAt: number) => void; + subscribe?: (intervalMs: number, subscriber: (tickAt: number) => void) => () => void; + onStats?: (stats: DownlinkBatchStats) => void; +} + +export interface DownlinkBatchStats { + messages: number; + entries: number; + maxEntries: number; + droppedFrames: number; + peakQueuedFrames: number; + peakQueuedMs: number; + lateTicks: number; +} + +interface QueuedFrame extends VoiceBatchEntry { + enqueuedAt: number; +} + +const LATE_TICK_MS = 100; + +export class DownlinkBatcher { + private frameMs: number; + private readonly maxEntries: number; + private readonly maxBytes: number; + private readonly maxQueueMs: number; + private readonly maxQueueEntries: number; + private readonly now: () => number; + private readonly send: DownlinkBatcherOptions["send"]; + private readonly subscribe: NonNullable; + private readonly onStats: DownlinkBatcherOptions["onStats"]; + private readonly queue: QueuedFrame[] = []; + private readonly seqByClient = new Map(); + private unsubscribe: (() => void) | null = null; + private origin: number; + private closed = false; + private messages = 0; + private entries = 0; + private maxEntriesSeen = 0; + private droppedFrames = 0; + private peakQueuedFrames = 0; + private peakQueuedMs = 0; + private lateTicks = 0; + + constructor(options: DownlinkBatcherOptions) { + this.frameMs = options.frameMs === 40 ? 40 : 20; + this.maxEntries = Math.max(1, Math.min(VOICE_BATCH_MAX_ENTRIES, options.maxEntries ?? 32)); + this.maxBytes = Math.max(1, Math.min(VOICE_BATCH_MAX_BYTES, options.maxBytes ?? VOICE_BATCH_MAX_BYTES)); + this.maxQueueMs = Math.max(this.frameMs, options.maxQueueMs ?? 100); + this.maxQueueEntries = Math.max(1, options.maxQueueEntries ?? 64); + this.now = options.now ?? (() => performance.now()); + this.origin = this.now(); + this.send = options.send; + this.subscribe = options.subscribe ?? subscribeDownlink; + this.onStats = options.onStats; + this.arm(); + } + + /** Returns false for a frame the encoder could not represent. */ + push(codec: number, clientId: number, data: Uint8Array): boolean { + if (this.closed || data.length < 1 || data.length > VOICE_MAX_OPUS_FRAME_BYTES + || !Number.isInteger(codec) || codec < 0 || codec > 255 + || !Number.isInteger(clientId) || clientId < 1 || clientId > 65_535) return false; + const now = this.now(); + this.dropStale(now); + while (this.queue.length >= this.maxQueueEntries) { + this.queue.shift(); + this.droppedFrames++; + } + const seq = ((this.seqByClient.get(clientId) ?? 0) + 1) & 0xff; + this.seqByClient.set(clientId, seq); + // TeamSpeak's SDK may reuse its packet buffer; the queue can live for one + // tick, so copy now rather than risk sending the next speaker's payload. + this.queue.push({ codec, clientId, seq, data: Buffer.from(data), enqueuedAt: now }); + this.peakQueuedFrames = Math.max(this.peakQueuedFrames, this.queue.length); + this.peakQueuedMs = Math.max(this.peakQueuedMs, this.oldestAge(now)); + this.emitStats(); + return true; + } + + setFrameMs(frameMs: 20 | 40): void { + if (this.frameMs === frameMs || this.closed) return; + // Drain under the old cadence before changing the clock bucket size. + this.flush(this.now()); + this.frameMs = frameMs; + this.origin = this.now(); + this.unsubscribe?.(); + this.unsubscribe = null; + this.arm(); + } + + /** Scheduler entry point; also used directly by tests with a synthetic tick. */ + flush(tickAt = this.now()): void { + if (this.closed) return; + const now = this.now(); + if (now - tickAt > LATE_TICK_MS) this.lateTicks++; + this.dropStale(now); + if (!this.queue.length) { + this.emitStats(); + return; + } + + const sendGroup = (group: QueuedFrame[], bucket: number) => { + const stamp = Math.max(0, this.origin + bucket * this.frameMs); + let batch: QueuedFrame[] = []; + let batchBytes = 6; + const flushBatch = () => { + if (!batch.length) return; + const encoded = encodeVoiceBatch(stamp, batch); + if (encoded) { + this.messages++; + this.entries += batch.length; + this.maxEntriesSeen = Math.max(this.maxEntriesSeen, batch.length); + try { this.send(encoded, batch.length, stamp); } catch { this.droppedFrames += batch.length; } + } else { + // Should be unreachable because push() bounds each frame and flush() + // splits on the same limits; keep the queue honest if it happens. + this.droppedFrames += batch.length; + } + batch = []; + batchBytes = 6; + }; + for (const frame of group) { + const frameBytes = 6 + frame.data.length; + if (batch.length && (batch.length >= this.maxEntries || batchBytes + frameBytes > this.maxBytes)) flushBatch(); + batch.push(frame); + batchBytes += frameBytes; + if (batch.length >= this.maxEntries || batchBytes >= this.maxBytes) flushBatch(); + } + flushBatch(); + }; + + // A late timer can hold several ticks of frames. Keep each tick as its own + // batch with its own audio timestamp: coalescing the whole backlog into one + // stamp would hide the stall from the jitter estimator and stack every + // speaker on the same playback instant. + let group: QueuedFrame[] = []; + let bucket = -1; + for (const frame of this.queue) { + const frameBucket = Math.floor((frame.enqueuedAt - this.origin) / this.frameMs); + if (group.length && frameBucket !== bucket) { + sendGroup(group, bucket); + group = []; + } + bucket = frameBucket; + group.push(frame); + } + if (group.length) sendGroup(group, bucket); + this.queue.length = 0; + this.emitStats(); + } + + getStats(): DownlinkBatchStats { + return { + messages: this.messages, + entries: this.entries, + maxEntries: this.maxEntriesSeen, + droppedFrames: this.droppedFrames, + peakQueuedFrames: this.peakQueuedFrames, + peakQueuedMs: this.peakQueuedMs, + lateTicks: this.lateTicks, + }; + } + + close(): void { + if (this.closed) return; + this.closed = true; + this.unsubscribe?.(); + this.unsubscribe = null; + this.queue.length = 0; + this.emitStats(); + } + + private arm(): void { + this.unsubscribe = this.subscribe(this.frameMs, tickAt => this.flush(tickAt)); + } + + private dropStale(now: number): void { + while (this.queue.length && now - this.queue[0]!.enqueuedAt > this.maxQueueMs) { + this.queue.shift(); + this.droppedFrames++; + } + } + + private oldestAge(now: number): number { + return this.queue.length ? Math.max(0, now - this.queue[0]!.enqueuedAt) : 0; + } + + private emitStats(): void { + this.onStats?.(this.getStats()); + } +} diff --git a/src/server/downlink-scheduler.ts b/src/server/downlink-scheduler.ts new file mode 100644 index 0000000..43ff84f --- /dev/null +++ b/src/server/downlink-scheduler.ts @@ -0,0 +1,63 @@ +import { performance } from "node:perf_hooks"; + +/** + * One timer per cadence, shared by every downlink batcher. A per-session timer + * would mean 50 timers/s per compatibility session (100 sessions -> 5k/s), + * which is measurable event-loop churn for no benefit. The scheduler passes + * the planned tick time only so a batcher can detect a late turn; batch + * timestamps are derived from the batcher's tick buckets. + */ + +type Subscriber = (tickAt: number) => void; + +interface Slot { + timer: ReturnType; + nextAt: number; + subscribers: Set; +} + +const slots = new Map(); +const LATE_RESET_MS = 100; + +export function subscribeDownlink(intervalMs: number, subscriber: Subscriber): () => void { + const interval = Math.max(10, Math.min(60, Math.round(intervalMs))); + let slot = slots.get(interval); + if (!slot) { + slot = { + nextAt: performance.now() + interval, + subscribers: new Set(), + timer: setInterval(() => runSlot(interval, slot!), interval), + }; + // Idle voice sessions must not keep the process alive. + (slot.timer as unknown as { unref?: () => void }).unref?.(); + slots.set(interval, slot); + } + slot.subscribers.add(subscriber); + return () => { + const current = slots.get(interval); + if (!current) return; + current.subscribers.delete(subscriber); + if (!current.subscribers.size) { + clearInterval(current.timer); + slots.delete(interval); + } + }; +} + +function runSlot(interval: number, slot: Slot): void { + const now = performance.now(); + if (now - slot.nextAt > LATE_RESET_MS) slot.nextAt = now; + const tickAt = slot.nextAt; + slot.nextAt = tickAt + interval; + // Copy so a subscriber that unsubscribes during its callback cannot skip + // another subscriber in the same tick. + for (const subscriber of [...slot.subscribers]) { + try { subscriber(tickAt); } catch { /* one session must not stop the shared timer */ } + } +} + +/** Test hook: drop every slot without waiting for an interval to fire. */ +export function resetDownlinkSchedulerForTests(): void { + for (const slot of slots.values()) clearInterval(slot.timer); + slots.clear(); +} diff --git a/src/server/session-audio.test.ts b/src/server/session-audio.test.ts index cb5c91a..a7eec68 100644 --- a/src/server/session-audio.test.ts +++ b/src/server/session-audio.test.ts @@ -285,3 +285,45 @@ test("invalid SDK speaker IDs and codecs cannot throw while packing the header", assert.equal(f.audio.egressDroppedFrames, 6); assert.equal(f.packets.length, 0); }); + +test("a 40 ms PCM frame is split into two TeamSpeak frames and costs two rate tokens", () => { + const f = fixture(); + f.transport.receivePcm(Buffer.alloc(3_840)); + assert.equal(f.encoded.length, 2); + assert.deepEqual(f.forwarded.map(entry => entry.codec), [4, 4]); + assert.equal(f.audio.ingressPcmFrames, 2); + for (let index = 0; index < 24; index++) f.state.now = 20 + index * 20; + for (let index = 0; index < 24; index++) f.transport.receivePcm(Buffer.alloc(3_840)); + assert.equal(f.audio.ingressDroppedFrames, 0, "40 ms frames consume their two tokens without exceeding the budget"); +}); + +test("a v3 client gets one batched packet per audio tick instead of one message per speaker", t => { + t.mock.timers.enable({ apis: ["setInterval"] }); + const f = fixture(); + f.transport.setDownlinkBatch(20); + f.transport.receiveTeamSpeak({ clientId: 2, codec: 4, data: Buffer.from([1, 2]) }); + f.transport.receiveTeamSpeak({ clientId: 3, codec: 5, data: Buffer.from([3]) }); + f.transport.receiveTeamSpeak({ clientId: 4, codec: 4, data: Buffer.from([4]) }); + assert.equal(f.packets.length, 0, "no immediate small messages after negotiation"); + f.state.now = 20; + t.mock.timers.tick(20); + assert.equal(f.packets.length, 1); + assert.equal(f.packets[0]![0], 0xf3); + assert.equal(f.audio.egressFrames, 3, "flow counters still count frames, not batches"); + assert.equal(f.audio.downlinkBatchMessages, 1); + assert.equal(f.audio.downlinkBatchEntries, 3); +}); + +test("a 40 ms v3 negotiation holds a batch for two 20 ms frames", t => { + t.mock.timers.enable({ apis: ["setInterval"] }); + const f = fixture(); + f.transport.setDownlinkBatch(40); + f.transport.receiveTeamSpeak({ clientId: 2, codec: 4, data: Buffer.from([1]) }); + f.state.now = 20; + t.mock.timers.tick(20); + assert.equal(f.packets.length, 0); + f.state.now = 40; + t.mock.timers.tick(20); + assert.equal(f.packets.length, 1); + assert.equal(f.audio.downlinkBatchEntries, 1); +}); diff --git a/src/server/session-audio.ts b/src/server/session-audio.ts index 8dcb12b..d72f09e 100644 --- a/src/server/session-audio.ts +++ b/src/server/session-audio.ts @@ -6,6 +6,7 @@ import type { AudioFlowStats } from "./audio-stats.js"; import type { TSClient, TSVoiceData } from "./ts-client.js"; import type { WebRtcAudioSession } from "./webrtc-audio.js"; import { AudioPacer } from "./audio-pacer.js"; +import { DownlinkBatcher } from "./downlink-batcher.js"; import { VOICE_MAX_OPUS_FRAME_BYTES, VOICE_OPUS_TAG, @@ -14,12 +15,16 @@ import { } from "../shared/voice-audio.js"; const AUDIO_FRAME_BYTES = VOICE_PCM_FRAME_BYTES; +const AUDIO_FRAME_BYTES_40 = AUDIO_FRAME_BYTES * 2; const TAGGED_PCM_FRAME_BYTES = AUDIO_FRAME_BYTES + 1; +const TAGGED_PCM_FRAME_BYTES_40 = AUDIO_FRAME_BYTES_40 + 1; const PCM_FRAME_TAG = VOICE_PCM_TAG; const OPUS_FRAME_TAG = VOICE_OPUS_TAG; const MAX_OPUS_FRAME_BYTES = VOICE_MAX_OPUS_FRAME_BYTES; -// Keep the established byte guard; the browser also bounds playback by time. +// Keep the established byte guard for the per-packet v2 path; a negotiated v3 +// batch may hold several speakers' frames and uses the larger limit below. const MAX_BUFFERED_BYTES = 4_096; +const BATCH_BUFFERED_BYTES = 32 * 1_024; // A client that keeps sending bad audio must not turn into one JSON error per // frame: the reply is roughly 100x the offending payload, and the browser only // ever shows the first one because it writes the same error string. @@ -56,6 +61,8 @@ export class SessionAudioTransport { private readonly reportedAt = new Map(); private readonly logger: LoggerType | null; private readonly pacer: AudioPacer | null; + private downlinkBatcher: DownlinkBatcher | null = null; + private downlinkBufferedBytes = MAX_BUFFERED_BYTES; private pcmTokens = PCM_BURST_FRAMES; private pcmRefilledAt: number | null = null; @@ -88,6 +95,47 @@ export class SessionAudioTransport { return peer?.isConnected ? peer : null; } + /** + * Switch the compatibility downlink to one binary message per audio tick. + * Only called after a client has negotiated frame version 3, so a v2 client + * keeps the byte-for-byte per-packet path. + */ + setDownlinkBatch(frameMs: 20 | 40): void { + if (this.closed) return; + this.downlinkBufferedBytes = BATCH_BUFFERED_BYTES; + if (this.downlinkBatcher) { + this.downlinkBatcher.setFrameMs(frameMs); + return; + } + this.downlinkBatcher = new DownlinkBatcher({ + frameMs, + now: () => this.rateClock(), + send: (packet, entries) => { + if (!this.isCurrent()) return; + try { + this.options.socket.send(Buffer.from(packet)); + const stats = this.options.audio; + stats.egressFrames += entries; + const sentAt = this.clock(); + if (stats.egressSentLastAt !== null) stats.egressSentMaxGapMs = Math.max(stats.egressSentMaxGapMs, sentAt - stats.egressSentLastAt); + stats.egressSentFirstAt ??= sentAt; + stats.egressSentLastAt = sentAt; + } catch { + this.options.audio.downlinkBatchDroppedFrames += entries; + } + }, + onStats: stats => { + const audio = this.options.audio; + audio.downlinkBatchMessages = stats.messages; + audio.downlinkBatchEntries = stats.entries; + audio.downlinkBatchMaxEntries = Math.max(audio.downlinkBatchMaxEntries, stats.maxEntries); + audio.downlinkBatchDroppedFrames = Math.max(audio.downlinkBatchDroppedFrames, stats.droppedFrames); + audio.downlinkBatchPeakQueueMs = Math.max(audio.downlinkBatchPeakQueueMs, stats.peakQueuedMs); + audio.downlinkBatchLateTicks = Math.max(audio.downlinkBatchLateTicks, stats.lateTicks); + }, + }); + } + private recordIngress(): void { const stats = this.options.audio; const now = this.clock(); @@ -161,8 +209,9 @@ export class SessionAudioTransport { // misattribute the drop and raise a spurious client error in the browser. // Late TCP frames from before a WebRTC switch must not duplicate RTP audio. if (!this.options.isReady() || this.mediaPeer()) { stats.ingressDroppedFrames++; return; } - const legacyPcm = frame.length === AUDIO_FRAME_BYTES ? frame : null; - const taggedPcm = frame.length === TAGGED_PCM_FRAME_BYTES && frame[0] === PCM_FRAME_TAG ? frame.subarray(1) : null; + const legacyPcm = frame.length === AUDIO_FRAME_BYTES || frame.length === AUDIO_FRAME_BYTES_40 ? frame : null; + const taggedPcm = (frame.length === TAGGED_PCM_FRAME_BYTES || frame.length === TAGGED_PCM_FRAME_BYTES_40) + && frame[0] === PCM_FRAME_TAG ? frame.subarray(1) : null; const opus = frame.length > 1 && frame.length <= MAX_OPUS_FRAME_BYTES + 1 && frame[0] === OPUS_FRAME_TAG ? frame.subarray(1) : null; if (!legacyPcm && !taggedPcm && !opus) { @@ -170,19 +219,24 @@ export class SessionAudioTransport { this.reportInvalidFrame(frame.length); return; } + // A 40 ms PCM frame carries two 20 ms TeamSpeak frames and therefore costs + // two tokens; otherwise a client could double its uplink rate by doubling + // the frame size. + const pcmFrames = legacyPcm ?? taggedPcm; + const frameCount = pcmFrames ? (pcmFrames.length === AUDIO_FRAME_BYTES_40 ? 2 : 1) : 1; const now = this.rateClock(); if (this.pcmRefilledAt !== null) { this.pcmTokens = Math.min(PCM_BURST_FRAMES, this.pcmTokens + Math.max(0, now - this.pcmRefilledAt) * PCM_FRAMES_PER_MS); } this.pcmRefilledAt = Math.max(this.pcmRefilledAt ?? now, now); - if (this.pcmTokens < 1) { + if (this.pcmTokens < frameCount) { stats.ingressDroppedFrames++; if (this.shouldReportAudioIssue("AUDIO_RATE_EXCEEDED")) { this.logger?.warn({ code: "AUDIO_RATE_EXCEEDED", droppedFrames: stats.ingressDroppedFrames }, "Discarded browser audio above the real-time budget"); } return; } - this.pcmTokens--; + this.pcmTokens -= frameCount; this.recordIngress(); if (opus) { stats.ingressOpusFrames++; @@ -192,21 +246,26 @@ export class SessionAudioTransport { else this.sendVoice(opus, 4); return; } - stats.ingressPcmFrames++; - const startedAt = this.clock(); - let encoded: Buffer; - try { - if (!this.encoder) throw new Error("Encoder unavailable"); - encoded = this.encoder.encode(taggedPcm ?? legacyPcm!); - stats.tsEncodeMaxMs = Math.max(stats.tsEncodeMaxMs, this.clock() - startedAt); - } catch { - stats.tsSendErrors++; - stats.ingressDroppedFrames++; - this.reportEncoderFailure(); - return; + stats.ingressPcmFrames += frameCount; + const chunks = pcmFrames!.length === AUDIO_FRAME_BYTES_40 + ? [pcmFrames!.subarray(0, AUDIO_FRAME_BYTES), pcmFrames!.subarray(AUDIO_FRAME_BYTES)] + : [pcmFrames!]; + for (const chunk of chunks) { + const startedAt = this.clock(); + let encoded: Buffer; + try { + if (!this.encoder) throw new Error("Encoder unavailable"); + encoded = this.encoder.encode(chunk); + stats.tsEncodeMaxMs = Math.max(stats.tsEncodeMaxMs, this.clock() - startedAt); + } catch { + stats.tsSendErrors++; + stats.ingressDroppedFrames++; + this.reportEncoderFailure(); + return; + } + this.pacer?.push(encoded, 4); + if (!this.pacer) this.sendVoice(encoded, 4); } - this.pacer?.push(encoded, 4); - if (!this.pacer) this.sendVoice(encoded, 4); } receiveWebRtc(data: Buffer, codec: number): void { @@ -242,6 +301,14 @@ export class SessionAudioTransport { } const bufferedBytes = this.options.socket.bufferedAmount; stats.egressPeakBufferedBytes = Math.max(stats.egressPeakBufferedBytes, bufferedBytes); + if (this.downlinkBatcher) { + if (bufferedBytes > this.downlinkBufferedBytes) { + stats.downlinkBatchDroppedFrames++; + return; + } + if (!this.downlinkBatcher.push(data.codec, data.clientId, data.data)) stats.egressDroppedFrames++; + return; + } if (bufferedBytes > MAX_BUFFERED_BYTES) { stats.egressDroppedFrames++; return; } const packet = Buffer.allocUnsafe(3 + data.data.length); packet[0] = data.codec; @@ -262,6 +329,8 @@ export class SessionAudioTransport { this.closed = true; this.reportedAt.clear(); this.pacer?.close(); + this.downlinkBatcher?.close(); + this.downlinkBatcher = null; const encoder = this.encoder; this.encoder = null; try { encoder?.dispose(); } catch { /* other session resources must still be released */ } diff --git a/src/server/voice-bridge.integration.test.ts b/src/server/voice-bridge.integration.test.ts index 7c665d5..ef34158 100644 --- a/src/server/voice-bridge.integration.test.ts +++ b/src/server/voice-bridge.integration.test.ts @@ -184,10 +184,14 @@ test("a direct connection keeps the legacy audio profile and the original media profile: "auto", opusWebSocket: false, jitterMaxMs: 300, + downlinkFrameMs: 20, + assumeCloudflare: false, + autoRelayRetry: true, }, }); const connected = await waitForBufferedMessage>(f.messages, "connected"); assert.equal(connected.voiceProfile, "legacy"); + assert.equal(connected.voiceRelayAutoRetry, true); assert.equal(connected.webrtcAvailable, true); assert.equal(connected.webrtcUnavailableReason, undefined); assert.equal(connected.audioFrameVersion, undefined); @@ -197,6 +201,28 @@ test("a direct connection keeps the legacy audio profile and the original media assert.deepEqual(connected.voiceIceServers, [{ urls: "stun:stun.example.invalid:3478" }]); }); +test("the console can force a Cloudflare ingress and disable automatic relay retry", { timeout: 5_000 }, async t => { + const f = await fixture(t, { + webRtc: { enabled: true }, + voiceIce: { + servers: [], + transportPolicy: "all", + gatewayTransportPolicy: "all", + profile: "auto", + opusWebSocket: false, + jitterMaxMs: 300, + downlinkFrameMs: 20, + assumeCloudflare: true, + autoRelayRetry: false, + }, + }); + const connected = await waitForBufferedMessage>(f.messages, "connected"); + assert.equal(connected.voiceProfile, "adaptive"); + assert.equal(connected.webrtcAvailable, false); + assert.equal(connected.webrtcUnavailableReason, "NO_MEDIA_PATH"); + assert.equal(connected.voiceRelayAutoRetry, false); +}); + test("an explicit adaptive profile enables the new audio path on a direct connection", { timeout: 5_000 }, async t => { const f = await fixture(t, { webRtc: { enabled: true }, @@ -207,12 +233,17 @@ test("an explicit adaptive profile enables the new audio path on a direct connec profile: "adaptive", opusWebSocket: true, jitterMaxMs: 300, + downlinkFrameMs: 20, + assumeCloudflare: false, + autoRelayRetry: true, }, }); const connected = await waitForBufferedMessage>(f.messages, "connected"); assert.equal(connected.voiceProfile, "adaptive"); assert.equal(connected.webrtcAvailable, true); assert.equal(connected.audioFrameVersion, 2); + assert.deepEqual(connected.audioDownlinkVersions, [2, 3]); + assert.deepEqual(connected.audioFrameMsOptions, [20]); assert.deepEqual(connected.audioUplinkCodecs, ["pcm", "opus"]); assert.equal(connected.audioJitterMaxMs, 300); }); @@ -227,6 +258,9 @@ test("a Cloudflare request opts into adaptive audio without inventing an ICE hos profile: "auto", opusWebSocket: false, jitterMaxMs: 300, + downlinkFrameMs: 20, + assumeCloudflare: false, + autoRelayRetry: true, }, headers: { "cf-ray": "test-ray" }, }); @@ -235,11 +269,36 @@ test("a Cloudflare request opts into adaptive audio without inventing an ICE hos assert.equal(connected.webrtcAvailable, false); assert.equal(connected.webrtcUnavailableReason, "NO_MEDIA_PATH"); assert.equal(connected.audioFrameVersion, 2); + assert.deepEqual(connected.audioDownlinkVersions, [2, 3]); + assert.deepEqual(connected.audioFrameMsOptions, [20]); assert.deepEqual(connected.audioUplinkCodecs, ["pcm"]); assert.equal(connected.audioJitterMaxMs, 300); assert.deepEqual(connected.voiceIceServers, []); }); +test("an adaptive client upgrades to one v3 batch per tick", { timeout: 5_000 }, async t => { + const f = await fixture(t, { + webRtc: { enabled: true }, + voiceIce: { + servers: [], transportPolicy: "all", gatewayTransportPolicy: "all", + profile: "adaptive", opusWebSocket: false, jitterMaxMs: 300, + downlinkFrameMs: 40, assumeCloudflare: false, autoRelayRetry: true, + }, + }); + await waitForBufferedMessage(f.messages, "connected"); + const config = waitForMessage>(f.socket, "audioConfig"); + f.socket.send(JSON.stringify({ + type: "audioCaps", + requestId: "caps-1", + payload: { downlinkVersion: 3, maxFrameMs: 40, codecs: ["pcm"] }, + })); + const message = await config; + assert.equal(message.downlinkVersion, 3); + assert.equal(message.frameMs, 40, "the console can opt into 40 ms batching"); + assert.deepEqual(message.uplinkCodecs, ["pcm"]); + assert.equal(message.jitterMaxMs, 300); +}); + test("a voice ICE getter is resolved when a new connection is accepted", { timeout: 5_000 }, async t => { let calls = 0; @@ -254,6 +313,9 @@ test("a voice ICE getter is resolved when a new connection is accepted", { timeo profile: "auto", opusWebSocket: false, jitterMaxMs: 300, + downlinkFrameMs: 20, + assumeCloudflare: false, + autoRelayRetry: true, }; }, headers: { "cf-ray": "console-refresh-ray" }, diff --git a/src/server/voice-bridge.ts b/src/server/voice-bridge.ts index a125f34..9d72305 100644 --- a/src/server/voice-bridge.ts +++ b/src/server/voice-bridge.ts @@ -41,6 +41,8 @@ import { resolveVoiceProfile, type VoiceProfile } from "../shared/voice-profile. const HEARTBEAT_INTERVAL_MS = 30_000; const MAX_MISSED_HEARTBEATS = 2; const MAX_LOGGED_WEBSOCKET_CLOSE_REASON_LENGTH = 160; +/** Set when a reverse proxy strips Cloudflare headers but CFT is still the ingress. */ +const ASSUME_CLOUDFLARE = process.env.WEBSPEAK_ASSUME_CLOUDFLARE === "1"; function sanitizeWebSocketCloseReason(reason: Buffer): string { return reason.toString("utf8") @@ -193,12 +195,12 @@ export class VoiceBridge { return; } const clientIp = resolveClientIp(req, this.trustedProxies); + const voiceIce = this.getVoiceIceConfig(); // Cloudflare Tunnel forwards the public hostname in `Host`, but that // hostname points at Cloudflare's edge, not at this origin's UDP ports. // Never advertise it as an ICE media address. - const cloudflareRequest = isCloudflareRequest(req, this.trustedProxies); + const cloudflareRequest = (voiceIce?.assumeCloudflare ?? ASSUME_CLOUDFLARE) || isCloudflareRequest(req, this.trustedProxies); const webrtcPublicHost = resolveWebRtcPublicHost(req, { allowHostFallback: !cloudflareRequest }); - const voiceIce = this.getVoiceIceConfig(); const voiceProfile = resolveVoiceProfile(voiceIce?.profile ?? "auto", cloudflareRequest); let identity; try { @@ -377,8 +379,11 @@ export class VoiceBridge { voiceProfile: entry!.voiceProfile, voiceIceServers: entry!.voiceIceServers, voiceIceTransportPolicy: entry!.voiceIceTransportPolicy, + voiceRelayAutoRetry: voiceIce?.autoRelayRetry !== false, ...(entry!.voiceProfile === "adaptive" ? { audioFrameVersion: 2 as const, + audioDownlinkVersions: [...new Set([2, 3])] as (2 | 3)[], + audioFrameMsOptions: [...new Set([20, voiceIce?.downlinkFrameMs ?? 20])] as (20 | 40)[], audioUplinkCodecs: voiceIce?.opusWebSocket === true ? ["pcm", "opus"] as ("pcm" | "opus")[] : ["pcm"] as ("pcm" | "opus")[], @@ -669,6 +674,25 @@ export class VoiceBridge { sendProtocolError(sendJson, "SESSION_NOT_READY", "TeamSpeak 会话尚未就绪", command.requestId); return; } + if (command.type === "audioCaps") { + const uplinkCodecs: ("pcm" | "opus")[] = entry!.voiceProfile === "adaptive" && voiceIce?.opusWebSocket === true + ? ["pcm", "opus"] + : ["pcm"]; + if (entry!.voiceProfile !== "adaptive") { + sendJson({ type: "audioConfig", downlinkVersion: 2, frameMs: 20, uplinkCodecs, jitterMaxMs: 80 }); + return; + } + const frameMs = Math.min(command.payload.maxFrameMs, voiceIce?.downlinkFrameMs ?? 20) as 20 | 40; + entry!.audioTransport?.setDownlinkBatch(frameMs); + sendJson({ + type: "audioConfig", + downlinkVersion: 3, + frameMs, + uplinkCodecs, + jitterMaxMs: voiceIce?.jitterMaxMs ?? 300, + }); + return; + } if (command.type === "createInvite") { if (!this.options.createWorkspaceInvite) { sendProtocolError(sendJson, "INVITE_UNAVAILABLE", "Invitations are unavailable on this gateway", command.requestId); return; } if (Date.now() - lastInviteAt < 1000) { sendProtocolError(sendJson, "RATE_LIMITED", "Please wait before creating another invitation", command.requestId); return; } diff --git a/src/server/voice-ice-config.test.ts b/src/server/voice-ice-config.test.ts index 5140e18..f1e54c9 100644 --- a/src/server/voice-ice-config.test.ts +++ b/src/server/voice-ice-config.test.ts @@ -10,8 +10,11 @@ test("voice ICE env parses static servers and direct-first defaults", () => { assert.equal(config.transportPolicy, "all"); assert.equal(config.gatewayTransportPolicy, "all"); assert.equal(config.profile, "auto"); - assert.equal(config.opusWebSocket, false); + assert.equal(config.opusWebSocket, true); assert.equal(config.jitterMaxMs, 300); + assert.equal(config.downlinkFrameMs, 20); + assert.equal(config.assumeCloudflare, false); + assert.equal(config.autoRelayRetry, true); assert.equal(config.turnRest, undefined); }); @@ -21,6 +24,10 @@ test("voice profile is explicit-only for Opus and can force legacy or adaptive", assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_PROFILE: "adaptive" }).profile, "adaptive"); assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_PROFILE: "invalid" }).profile, "auto"); assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_PROFILE: "adaptive", WEBSPEAK_VOICE_OPUS_WS: "1" }).opusWebSocket, true); + assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_OPUS_WS: "0" }).opusWebSocket, false); + assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_FRAME_MS: "40" }).downlinkFrameMs, 40); + assert.equal(readVoiceIceConfig({ WEBSPEAK_ASSUME_CLOUDFLARE: "1" }).assumeCloudflare, true); + assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_AUTO_RELAY_RETRY: "0" }).autoRelayRetry, false); }); test("TURN REST env mints a per-session credential and keeps direct-first policy", () => { diff --git a/src/server/voice-ice-config.ts b/src/server/voice-ice-config.ts index 3e0bf61..8781b76 100644 --- a/src/server/voice-ice-config.ts +++ b/src/server/voice-ice-config.ts @@ -26,6 +26,12 @@ export interface VoiceIceConfig { profile: VoiceProfileSetting; opusWebSocket: boolean; jitterMaxMs: number; + /** Compatibility downlink batch tick. 40 ms halves messages and adds up to 20 ms. */ + downlinkFrameMs: 20 | 40; + /** Treat every voice ingress as Cloudflare even if reverse-proxy headers were stripped. */ + assumeCloudflare: boolean; + /** Allow one automatic relay-only WebRTC retry after a direct-path failure. */ + autoRelayRetry: boolean; } export interface VoiceIceSettings { @@ -35,6 +41,9 @@ export interface VoiceIceSettings { profile: VoiceProfileSetting; opusWebSocket: boolean; jitterMaxMs: number; + downlinkFrameMs: 20 | 40; + assumeCloudflare: boolean; + autoRelayRetry: boolean; } /** Baseline used when neither the console nor the environment configures a value. */ @@ -43,8 +52,13 @@ export const DEFAULT_VOICE_ICE_CONFIG: VoiceIceConfig = { transportPolicy: "all", gatewayTransportPolicy: "all", profile: "auto", - opusWebSocket: false, + // Adaptive clients use Opus when WebCodecs can encode it and silently fall + // back to PCM otherwise; legacy clients never see this flag. + opusWebSocket: true, jitterMaxMs: VOICE_JITTER_DEFAULT_MS, + downlinkFrameMs: 20, + assumeCloudflare: false, + autoRelayRetry: true, }; function parseBoolean(value: string | undefined, fallback: boolean): boolean { @@ -105,9 +119,13 @@ export function readVoiceIceConfig(env: NodeJS.ProcessEnv = process.env): VoiceI transportPolicy: normalizeVoiceIceTransportPolicy(env.WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY), gatewayTransportPolicy: normalizeVoiceIceTransportPolicy(env.WEBSPEAK_VOICE_GATEWAY_ICE_TRANSPORT_POLICY), profile: normalizeVoiceProfileSetting(env.WEBSPEAK_VOICE_PROFILE), - // Opus over WebSocket is additive and remains opt-in even in adaptive mode. - opusWebSocket: parseBoolean(env.WEBSPEAK_VOICE_OPUS_WS, false), + // Opus over WebSocket is negotiated only for adaptive clients; browsers + // without WebCodecs fall back to PCM at runtime. + opusWebSocket: parseBoolean(env.WEBSPEAK_VOICE_OPUS_WS, true), jitterMaxMs: parseInteger(env.WEBSPEAK_VOICE_JITTER_MAX_MS, VOICE_JITTER_DEFAULT_MS, VOICE_JITTER_MIN_MS, VOICE_JITTER_MAX_MS), + downlinkFrameMs: env.WEBSPEAK_VOICE_FRAME_MS?.trim() === "40" ? 40 : 20, + assumeCloudflare: parseBoolean(env.WEBSPEAK_ASSUME_CLOUDFLARE, false), + autoRelayRetry: parseBoolean(env.WEBSPEAK_VOICE_AUTO_RELAY_RETRY, true), }; } @@ -133,6 +151,9 @@ export function voiceConfigSettings(config: VoiceIceConfig): VoiceIceSettings { profile: config.profile, opusWebSocket: config.opusWebSocket, jitterMaxMs: config.jitterMaxMs, + downlinkFrameMs: config.downlinkFrameMs, + assumeCloudflare: config.assumeCloudflare, + autoRelayRetry: config.autoRelayRetry, }; } diff --git a/src/shared/admin-inputs.ts b/src/shared/admin-inputs.ts index 90b0d86..d2506b7 100644 --- a/src/shared/admin-inputs.ts +++ b/src/shared/admin-inputs.ts @@ -22,6 +22,9 @@ export interface AdminSettingsInput { voiceTurnTtlSeconds?: number; voiceOpusWs?: boolean; voiceJitterMaxMs?: number; + voiceDownlinkFrameMs?: 20 | 40; + voiceAssumeCloudflare?: boolean; + voiceAutoRelayRetry?: boolean; relaySettingsAction?: "keep" | "replace" | "remove"; relayEnabled?: boolean; relayName?: string; diff --git a/src/shared/admin-responses.ts b/src/shared/admin-responses.ts index ca2f784..3bd5cbd 100644 --- a/src/shared/admin-responses.ts +++ b/src/shared/admin-responses.ts @@ -37,8 +37,11 @@ const settings = object({ voiceTurnUrls: value => value === undefined ? "" : text(value), hasVoiceTurnSecret: value => value === undefined ? false : boolean(value), voiceTurnTtlSeconds: value => value === undefined ? 21600 : number(value), - voiceOpusWs: value => value === undefined ? false : boolean(value), + voiceOpusWs: value => value === undefined ? true : boolean(value), voiceJitterMaxMs: value => value === undefined ? 300 : number(value), + voiceDownlinkFrameMs: value => value === undefined ? 20 : value === 20 || value === 40 ? value : invalid(), + voiceAssumeCloudflare: value => value === undefined ? false : boolean(value), + voiceAutoRelayRetry: value => value === undefined ? true : boolean(value), relayConfigured: boolean, relayEnabled: boolean, relayName: text, relayTarget: text, hasRelayToken: boolean, relayNodes: array(relayNode), internalPort: number, updatedAt: text, }); diff --git a/src/shared/client-commands.test.ts b/src/shared/client-commands.test.ts index 1ad5d90..f3d6fb7 100644 --- a/src/shared/client-commands.test.ts +++ b/src/shared/client-commands.test.ts @@ -13,6 +13,7 @@ test("all command payloads preserve request IDs through the shared parser", () = setWhisperTargets: { targetIds: [2, 3] }, setWhisperActive: { active: true }, setMicrophoneMuted: { muted: false }, setAccompanimentActive: { active: true }, setMemberVolume: { clientId: 2, volume: 0 }, latencyProbe: { sequence: "old" }, audioStatsProbe: { sequence: "new" }, + audioCaps: { downlinkVersion: 3, maxFrameMs: 40, codecs: ["pcm", "opus"] }, }; for (const [type, payload] of Object.entries(payloads)) { const command = { type, payload, requestId: "request-1" }; diff --git a/src/shared/client-commands.ts b/src/shared/client-commands.ts index 252f49a..5fec5ce 100644 --- a/src/shared/client-commands.ts +++ b/src/shared/client-commands.ts @@ -15,6 +15,7 @@ export interface ClientCommandPayloads { setMemberVolume: { clientId: number; volume: number }; latencyProbe: { sequence: string }; audioStatsProbe: { sequence: string }; + audioCaps: { downlinkVersion: 3; maxFrameMs: 20 | 40; codecs: ("pcm" | "opus")[] }; } export type ClientCommandType = keyof ClientCommandPayloads; @@ -37,7 +38,7 @@ export function parseClientCommand(raw: string): ClientCommandResult { if (value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length > 64)) { return { error: { code: "INVALID_REQUEST_ID", message: "请求标识无效" } }; } - const supportedTypes = new Set(["createInvite", "switchChannel", "moveClient", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe", "audioStatsProbe"]); + const supportedTypes = new Set(["createInvite", "switchChannel", "moveClient", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe", "audioStatsProbe", "audioCaps"]); if (!supportedTypes.has(value.type)) { return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } }; } @@ -110,6 +111,16 @@ export function parseClientCommand(raw: string): ClientCommandResult { if (value.type === "latencyProbe" && (typeof value.payload.sequence !== "string" || value.payload.sequence.length > 64)) { return { error: { code: "INVALID_LATENCY_PROBE", message: "延迟探测标识无效" } }; } + if (value.type === "audioCaps") { + const payload = value.payload; + const codecs = payload.codecs; + if (payload.downlinkVersion !== 3 || (payload.maxFrameMs !== 20 && payload.maxFrameMs !== 40) + || !Array.isArray(codecs) || codecs.length < 1 || codecs.length > 2 + || codecs.some(codec => codec !== "pcm" && codec !== "opus") + || new Set(codecs).size !== codecs.length) { + return { error: { code: "INVALID_AUDIO_CAPS", message: "音频能力声明无效" } }; + } + } return { type: value.type as ClientCommand["type"], ...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}), diff --git a/src/shared/server-messages.test.ts b/src/shared/server-messages.test.ts index 2f425e0..1fc4f11 100644 --- a/src/shared/server-messages.test.ts +++ b/src/shared/server-messages.test.ts @@ -24,6 +24,7 @@ const samples: Record = { serverEvent: { type: "serverEvent", event }, channelSwitched: { type: "channelSwitched", channelId: "1" }, audioStats: { type: "audioStats", sequence: "probe", stats: parseVoiceAudioBridgeStats({})! }, + audioConfig: { type: "audioConfig", downlinkVersion: 3, frameMs: 20, uplinkCodecs: ["pcm", "opus"], jitterMaxMs: 300 }, latencyPong: { type: "latencyPong", sequence: "legacy", teamSpeakLatencyMs: null, teamSpeakReachable: false, teamSpeakErrorCode: "TIMEOUT" }, disconnected: { type: "disconnected", recoverable: false }, reconnecting: { type: "reconnecting", attempt: 2, delayMs: 1_000 }, diff --git a/src/shared/server-messages.ts b/src/shared/server-messages.ts index ad35f13..5a62f6f 100644 --- a/src/shared/server-messages.ts +++ b/src/shared/server-messages.ts @@ -14,7 +14,8 @@ type ChatFields = { invokerId?: number; invokerName?: string; message: string; t /** Public JSON messages. Internal sockets, SDK clients and media objects stay out. */ export type ServerMessage = | Message<"inviteCreated", Request & { token: string; expiresAt: number }> - | Message<"connected", { tsClientId: number; pluginSession?: string; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; webrtcUnavailableReason?: "DISABLED" | "NO_MEDIA_PATH"; webRtcStunServer?: string; voiceProfile?: VoiceProfile; voiceIceServers?: VoiceIceServer[]; voiceIceTransportPolicy?: "all" | "relay"; audioFrameVersion?: 2; audioUplinkCodecs?: ("pcm" | "opus")[]; audioJitterMaxMs?: number; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }> + | Message<"connected", { tsClientId: number; pluginSession?: string; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; webrtcUnavailableReason?: "DISABLED" | "NO_MEDIA_PATH"; webRtcStunServer?: string; voiceProfile?: VoiceProfile; voiceIceServers?: VoiceIceServer[]; voiceIceTransportPolicy?: "all" | "relay"; voiceRelayAutoRetry?: boolean; audioFrameVersion?: 2; audioDownlinkVersions?: (2 | 3)[]; audioFrameMsOptions?: (20 | 40)[]; audioUplinkCodecs?: ("pcm" | "opus")[]; audioJitterMaxMs?: number; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }> + | Message<"audioConfig", { downlinkVersion: 2 | 3; frameMs: 20 | 40; uplinkCodecs: ("pcm" | "opus")[]; jitterMaxMs: number }> | Message<"serverInfo", { name: string; icon?: string | null; bannerUrl?: string | null; welcomeMessage?: string }> | Message<"memberEnter", ChannelMember> | Message<"memberLeave", { id: number }> @@ -146,7 +147,10 @@ const valid: Record boolean> = && optional(m.voiceProfile, isVoiceProfile) && optional(m.voiceIceServers, v => Array.isArray(v) && normalizeVoiceIceServers(v).length === v.length) && optional(m.voiceIceTransportPolicy, v => v === "all" || v === "relay") + && optional(m.voiceRelayAutoRetry, boolean) && optional(m.audioFrameVersion, v => v === 2) + && optional(m.audioDownlinkVersions, v => Array.isArray(v) && v.length > 0 && v.every(version => version === 2 || version === 3)) + && optional(m.audioFrameMsOptions, v => Array.isArray(v) && v.length > 0 && v.every(ms => ms === 20 || ms === 40)) && optional(m.audioUplinkCodecs, v => Array.isArray(v) && v.length > 0 && v.every(codec => codec === "pcm" || codec === "opus")) && optional(m.audioJitterMaxMs, v => finite(v) && Number.isInteger(v) && v >= 80 && v <= 500) && optional(m.whisperTargetIds, v => arrayOf(v, clientId)) && optional(m.whisperActive, boolean) && optional(m.accelerated, boolean), @@ -166,6 +170,11 @@ const valid: Record boolean> = inviteCreated: m => text(m.token) && /^wi_[A-Za-z0-9_-]{43}$/.test(m.token) && typeof m.expiresAt === "number" && Number.isSafeInteger(m.expiresAt), channelSwitched: m => channelId(m.channelId), audioStats: m => text(m.sequence) && m.sequence.length <= 64 && isRecord(m.stats), + audioConfig: m => (m.downlinkVersion === 2 || m.downlinkVersion === 3) + && (m.frameMs === 20 || m.frameMs === 40) + && Array.isArray(m.uplinkCodecs) && m.uplinkCodecs.length > 0 && m.uplinkCodecs.length <= 2 + && m.uplinkCodecs.every(codec => codec === "pcm" || codec === "opus") + && finite(m.jitterMaxMs) && m.jitterMaxMs >= 80 && m.jitterMaxMs <= 500, latencyPong: m => text(m.sequence) && (m.teamSpeakLatencyMs === null || finite(m.teamSpeakLatencyMs)) && boolean(m.teamSpeakReachable) && (m.teamSpeakErrorCode === null || text(m.teamSpeakErrorCode)), disconnected: m => optional(m.recoverable, boolean), diff --git a/src/shared/voice-audio.test.ts b/src/shared/voice-audio.test.ts new file mode 100644 index 0000000..3952318 --- /dev/null +++ b/src/shared/voice-audio.test.ts @@ -0,0 +1,39 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + decodeVoiceBatch, + encodeVoiceBatch, + VOICE_BATCH_HEADER_BYTES, + VOICE_BATCH_TAG, + VOICE_MAX_OPUS_FRAME_BYTES, +} from "./voice-audio.js"; + +test("voice batch round-trips the audio clock and per-speaker entries", () => { + const encoded = encodeVoiceBatch(123_456, [ + { codec: 4, clientId: 2, seq: 7, data: Uint8Array.from([1, 2, 3]) }, + { codec: 5, clientId: 65_535, seq: 255, data: Uint8Array.from([9]) }, + ]); + assert.ok(encoded); + assert.equal(encoded[0], VOICE_BATCH_TAG); + assert.equal(encoded[1], 2); + assert.equal(encoded.length, VOICE_BATCH_HEADER_BYTES + (6 + 3) + (6 + 1)); + const decoded = decodeVoiceBatch(encoded); + assert.ok(decoded); + assert.equal(decoded.audioStartMs, 123_456); + assert.deepEqual(decoded.entries.map(({ codec, clientId, seq, data }) => ({ codec, clientId, seq, data: [...data] })), [ + { codec: 4, clientId: 2, seq: 7, data: [1, 2, 3] }, + { codec: 5, clientId: 65_535, seq: 255, data: [9] }, + ]); +}); + +test("voice batch rejects framing the decoder could not reproduce", () => { + const good = encodeVoiceBatch(1, [{ codec: 4, clientId: 2, seq: 1, data: Uint8Array.from([1, 2, 3]) }])!; + assert.equal(decodeVoiceBatch(Uint8Array.from([...good, 0])), null, "trailing byte"); + assert.equal(decodeVoiceBatch(Uint8Array.from([0xf2, ...good.subarray(1)])), null, "wrong tag"); + assert.equal(decodeVoiceBatch(Uint8Array.from([good[0]!, 0, ...good.subarray(2)])), null, "zero entries"); + const truncated = good.slice(0, -1); + assert.equal(decodeVoiceBatch(truncated), null, "truncated payload"); + assert.equal(encodeVoiceBatch(1, []), null); + assert.equal(encodeVoiceBatch(1, [{ codec: 4, clientId: 0, seq: 1, data: Uint8Array.from([1]) }]), null); + assert.equal(encodeVoiceBatch(1, [{ codec: 4, clientId: 1, seq: 1, data: new Uint8Array(VOICE_MAX_OPUS_FRAME_BYTES + 1) }]), null); +}); diff --git a/src/shared/voice-audio.ts b/src/shared/voice-audio.ts index a0af543..7b5252e 100644 --- a/src/shared/voice-audio.ts +++ b/src/shared/voice-audio.ts @@ -6,3 +6,89 @@ export const VOICE_PCM_TAG = 0x01; export const VOICE_OPUS_TAG = 0x02; /** RFC 6716 maximum Opus packet length; the server validates the same bound. */ export const VOICE_MAX_OPUS_FRAME_BYTES = 1_275; + +/** + * Downlink batch tag. Deliberately outside the TeamSpeak codec range (0-5) and + * above the uplink tags so a legacy client drops the packet instead of trying + * to decode the batch header as Opus. + */ +export const VOICE_BATCH_TAG = 0xf3; +export const VOICE_BATCH_HEADER_BYTES = 6; +export const VOICE_BATCH_MAX_ENTRIES = 32; +export const VOICE_BATCH_MAX_BYTES = 16 * 1024; + +export interface VoiceBatchEntry { + codec: number; + clientId: number; + /** Per-speaker 8-bit sequence; wraps every 256 packets. */ + seq: number; + data: Uint8Array; +} + +export interface DecodedVoiceBatch { + audioStartMs: number; + entries: VoiceBatchEntry[]; +} + +/** + * Encode one downlink batch: + * 0xF3 | count:u8 | audioStartMs:u32be | entries + * entry: codec:u8 | clientId:u16be | seq:u8 | length:u16be | payload + * + * Returns null when the caller supplied something that would not decode + * identically (bad id/length, too many entries, oversized batch). + */ +export function encodeVoiceBatch(audioStartMs: number, entries: readonly VoiceBatchEntry[]): Uint8Array | null { + if (entries.length < 1 || entries.length > VOICE_BATCH_MAX_ENTRIES) return null; + let total = VOICE_BATCH_HEADER_BYTES; + for (const entry of entries) { + if (!Number.isInteger(entry.codec) || entry.codec < 0 || entry.codec > 255 + || !Number.isInteger(entry.clientId) || entry.clientId < 1 || entry.clientId > 65_535 + || !Number.isInteger(entry.seq) || entry.seq < 0 || entry.seq > 255 + || entry.data.length < 1 || entry.data.length > VOICE_MAX_OPUS_FRAME_BYTES) return null; + total += 6 + entry.data.length; + if (total > VOICE_BATCH_MAX_BYTES) return null; + } + const out = new Uint8Array(total); + const view = new DataView(out.buffer, out.byteOffset, out.byteLength); + out[0] = VOICE_BATCH_TAG; + out[1] = entries.length; + view.setUint32(2, Math.max(0, Math.floor(audioStartMs)) >>> 0, false); + let offset = VOICE_BATCH_HEADER_BYTES; + for (const entry of entries) { + out[offset] = entry.codec; + view.setUint16(offset + 1, entry.clientId, false); + out[offset + 3] = entry.seq; + view.setUint16(offset + 4, entry.data.length, false); + out.set(entry.data, offset + 6); + offset += 6 + entry.data.length; + } + return out; +} + +/** Strict decoder; returns null for anything the encoder would not have produced. */ +export function decodeVoiceBatch(packet: Uint8Array): DecodedVoiceBatch | null { + if (packet.length < VOICE_BATCH_HEADER_BYTES + 7 || packet[0] !== VOICE_BATCH_TAG) return null; + const count = packet[1]!; + if (count < 1 || count > VOICE_BATCH_MAX_ENTRIES) return null; + const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength); + const audioStartMs = view.getUint32(2, false); + const entries: VoiceBatchEntry[] = []; + let offset = VOICE_BATCH_HEADER_BYTES; + for (let i = 0; i < count; i++) { + if (offset + 6 > packet.length) return null; + const codec = packet[offset]!; + const clientId = view.getUint16(offset + 1, false); + const seq = packet[offset + 3]!; + const length = view.getUint16(offset + 4, false); + if (clientId < 1 || length < 1 || length > VOICE_MAX_OPUS_FRAME_BYTES) return null; + const start = offset + 6; + const end = start + length; + if (end > packet.length) return null; + entries.push({ codec, clientId, seq, data: packet.subarray(start, end) }); + offset = end; + } + // Trailing bytes mean the sender and receiver disagree about the framing. + if (offset !== packet.length) return null; + return { audioStartMs, entries }; +} diff --git a/web/src/components/admin/AdminServerSettings.vue b/web/src/components/admin/AdminServerSettings.vue index 0e0bd0f..9279432 100644 --- a/web/src/components/admin/AdminServerSettings.vue +++ b/web/src/components/admin/AdminServerSettings.vue @@ -327,6 +327,27 @@ {{ tr('voiceApplyHint') }} +
+

{{ tr('voiceTuning') }}

{{ tr('voiceTuningLead') }}

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

{{ tr('turnSettings') }}

{{ tr('turnLead') }}

import { computed, ref, type CSSProperties } from "vue"; +import { micTestPlaybackSource } from "../../voice/microphone-test.js"; import Icon from "../Icon.vue"; import AudioDeviceSelect from "./AudioDeviceSelect.vue"; import { useDialogFocus } from "../../composables/useDialogFocus.js"; @@ -263,7 +278,8 @@ type AudioSettingsState = Pick, | "audioPermission" | "audioContextState" | "microphoneMuted" - | "noiseSuppressionLevel" + | "noiseSuppressionMode" + | "microphoneProcessing" | "inputVolume" | "outputVolume" | "voxThreshold" @@ -271,6 +287,7 @@ type AudioSettingsState = Pick, | "micLevel" | "microphoneTestActive" | "testAudioUrl" + | "testAudioDryUrl" >; type AudioSettingsControls = Pick, | "settingsError" @@ -308,7 +325,8 @@ const { audioPermission, audioContextState, microphoneMuted, - noiseSuppressionLevel, + noiseSuppressionMode, + microphoneProcessing, inputVolume, outputVolume, voxThreshold, @@ -316,6 +334,7 @@ const { micLevel, microphoneTestActive, testAudioUrl, + testAudioDryUrl, } = props.model; const { settingsError: audioSettingsError, @@ -346,4 +365,33 @@ const outputDeviceOptions = computed(() => [ label: device.label || props.t("speakerNumber", { index: index + 1 }), })), ]); + +const testVariant = ref<"processed" | "dry">("processed"); +const testPlayback = computed(() => micTestPlaybackSource(testVariant.value, { + processed: testAudioUrl.value, + dry: testAudioDryUrl.value, +})); +const testAudioSrc = computed(() => testPlayback.value.src); +const testAudioMissingKey = computed(() => testPlayback.value.missingKey); +const processingFallback = computed(() => microphoneProcessing.fallback); +const processingWarning = computed(() => microphoneProcessing.warning); +// Reflect the engine that really ran, not the stored preference. +const processingStatus = computed(() => { + const fallback = microphoneProcessing.fallback; + if (fallback === "no-worklet") return props.t("noiseSuppressionFallbackNoWorklet"); + if (fallback === "sample-rate") return props.t("noiseSuppressionFallbackSampleRate"); + // A model that died after the browser suppressor was already disabled leaves + // no denoising at all: say so instead of promising a browser fallback. + if (fallback === "load-failed") { + return microphoneProcessing.engine === "off" + ? props.t("noiseSuppressionModelInactive") + : props.t("noiseSuppressionFallbackLoad"); + } + if (microphoneProcessing.warning === "browser-ns-active") return props.t("noiseSuppressionBrowserStacking"); + if (microphoneProcessing.engine === "gtcrn") return `${props.t("noiseSuppressionActive")}:${props.t("noiseSuppressionEngineGtcrn")}`; + if (microphoneProcessing.engine === "rnnoise") return `${props.t("noiseSuppressionActive")}:${props.t("noiseSuppressionEngineRnnoise")}`; + if (microphoneProcessing.engine === "browser") return `${props.t("noiseSuppressionActive")}:${props.t("noiseSuppressionEngineBrowser")}`; + if (microphoneProcessing.requestedEngine !== "off") return props.t("noiseSuppressionPreparing"); + return props.t("noiseSuppressionEngineOff"); +}); diff --git a/web/src/composables/useAdminI18n.ts b/web/src/composables/useAdminI18n.ts index f472298..63f3775 100644 --- a/web/src/composables/useAdminI18n.ts +++ b/web/src/composables/useAdminI18n.ts @@ -40,6 +40,8 @@ const errorLabels: Record = { 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", diff --git a/web/src/composables/useAdminServerSettings.ts b/web/src/composables/useAdminServerSettings.ts index 8c902be..84e58e7 100644 --- a/web/src/composables/useAdminServerSettings.ts +++ b/web/src/composables/useAdminServerSettings.ts @@ -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; -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] }); } } diff --git a/web/src/composables/useVoiceWebSocket.ts b/web/src/composables/useVoiceWebSocket.ts index 2bd694f..6b8288d 100644 --- a/web/src/composables/useVoiceWebSocket.ts +++ b/web/src/composables/useVoiceWebSocket.ts @@ -2,6 +2,15 @@ import { createRemotePlayback } from "../voice/remote-playback.js"; import { createMicrophoneTest } from "../voice/microphone-test.js"; import { createMicrophoneCaptureFactory, type MicrophoneCapture, type MicrophoneProcessingSettings } from "../voice/microphone-capture.js"; export type { MicrophoneProcessingSettings } from "../voice/microphone-capture.js"; +import { + isNeuralDenoiseEngine, + legacyNoiseSuppressionLevel, + migrateStoredNoiseSuppression, + resolveDenoisePlan, + type DenoisePlan, + type NoiseSuppressionMode, + type StoredNoiseSuppressionLevel, +} from "../voice/noise-suppression.js"; import { createAudioSinkRouter } from "../voice/audio-sink.js"; import { createAccompaniment, type AccompanimentErrorCode } from "../voice/accompaniment.js"; import { createWebRtcTransport } from "../voice/webrtc-transport.js"; @@ -15,10 +24,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"; @@ -296,24 +307,38 @@ export function useVoiceWebSocket() { echoCancellation: null, noiseSuppression: null, autoGainControl: null, - rnnoise: null, + engine: "off", + requestedEngine: "gtcrn", + fallback: null, + warning: null, }); const audioContextState = ref("unknown"); const micLevel = ref(0); const microphoneTestActive = ref(false); const testAudioUrl = ref(""); + const testAudioDryUrl = ref(""); const microphoneTest = createMicrophoneTest({ - prepare: async () => { await prepareInputDevices(); return micStream; }, + prepare: async () => { + await prepareInputDevices(); + if (!micStream) return null; + return { + dry: microphoneCapture?.dryStream ?? micStream, + processed: microphoneCapture?.processedStream ?? micStream, + }; + }, onActive: active => { microphoneTestActive.value = active; }, onUrl: url => { testAudioUrl.value = url; }, + onDryUrl: url => { testAudioDryUrl.value = url; }, onStopped: () => { if (!state.connected) stopMicrophone(); }, onError: error => { setMicrophoneError(error); }, }); const microphoneMuted = ref(false); - const noiseSuppressionLevel = ref<"off" | "standard" | "strong">("strong"); - const noiseSuppressionEnabled = computed(() => noiseSuppressionLevel.value !== "off"); + const noiseSuppressionMode = ref("gtcrn"); + // Compatibility view for existing skins/tests: the old three-value field. + const noiseSuppressionLevel = computed(() => legacyNoiseSuppressionLevel(noiseSuppressionMode.value)); + const noiseSuppressionEnabled = computed(() => noiseSuppressionMode.value !== "off"); let noiseSuppressionTouched = false; - let committedNoiseSuppressionLevel = noiseSuppressionLevel.value; + let committedNoiseSuppressionMode = noiseSuppressionMode.value; const inputVolume = ref(1); const outputVolume = ref(1); const outputMuted = ref(false); @@ -333,16 +358,18 @@ export function useVoiceWebSocket() { const whisperActive = ref(false); const speakingTimers = new Map>(); 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 +384,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 +407,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 +430,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: { @@ -460,8 +532,9 @@ export function useVoiceWebSocket() { preferredInputDeviceId: committedInputDeviceId, inputDeviceId: committedInputDeviceId, microphoneMuted: microphoneMuted.value, - noiseSuppressionEnabled: committedNoiseSuppressionLevel !== "off", - noiseSuppressionLevel: committedNoiseSuppressionLevel, + noiseSuppressionEnabled: committedNoiseSuppressionMode !== "off", + noiseSuppressionMode: committedNoiseSuppressionMode, + noiseSuppressionLevel: legacyNoiseSuppressionLevel(committedNoiseSuppressionMode), voxThreshold: voxThreshold.value, inputGain: inputVolume.value, outputVolume: outputVolume.value, @@ -485,14 +558,13 @@ export function useVoiceWebSocket() { } if (typeof preferences.microphoneMuted === "boolean") microphoneMuted.value = preferences.microphoneMuted; if (!noiseSuppressionTouched) { - const storedLevel = preferences.noiseSuppressionLevel; - if (storedLevel === "off" || storedLevel === "standard" || storedLevel === "strong") { - noiseSuppressionLevel.value = storedLevel; - committedNoiseSuppressionLevel = storedLevel; - } else if (typeof preferences.noiseSuppressionEnabled === "boolean") { - noiseSuppressionLevel.value = preferences.noiseSuppressionEnabled ? "strong" : "off"; - committedNoiseSuppressionLevel = noiseSuppressionLevel.value; - } + const storedMode = migrateStoredNoiseSuppression({ + mode: preferences.noiseSuppressionMode, + level: preferences.noiseSuppressionLevel, + enabled: preferences.noiseSuppressionEnabled, + }); + noiseSuppressionMode.value = storedMode; + committedNoiseSuppressionMode = storedMode; } if (typeof preferences.voxThreshold === "number") voxThreshold.value = clamp(preferences.voxThreshold, 0.001, 0.08); if (typeof preferences.inputGain === "number") inputVolume.value = Math.max(0, Math.min(1, preferences.inputGain)); @@ -639,12 +711,18 @@ export function useVoiceWebSocket() { return null; } - function microphoneConstraints(): MediaTrackConstraints { + function audioWorkletSupported(ctx: AudioContext): boolean { + return typeof AudioWorkletNode !== "undefined" && Boolean(ctx.audioWorklet); + } + + function microphoneConstraints(plan: DenoisePlan): MediaTrackConstraints { const constraints: MediaTrackConstraints = { sampleRate: { ideal: 48000 }, channelCount: { ideal: 1 }, echoCancellation: true, - noiseSuppression: noiseSuppressionLevel.value !== "off", + // Model-based denoise and the browser suppressor are mutually exclusive: + // Chrome's NS smears speech before GTCRN/RNNoise sees it. + noiseSuppression: plan.requestBrowserNs, // Keep the microphone's natural dynamics. Browser AGC can make speech // pump in volume, especially while background noise changes. autoGainControl: false, @@ -752,9 +830,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; @@ -773,9 +851,32 @@ export function useVoiceWebSocket() { let nextStream: MediaStream | null = null; let nextCapture: MicrophoneCapture | null = null; let factoryOwnsStream = false; + const requestedMode = noiseSuppressionMode.value; + let plan = resolveDenoisePlan({ + mode: requestedMode, + sampleRate: ctx.sampleRate, + workletSupported: audioWorkletSupported(ctx), + }); try { + if (isNeuralDenoiseEngine(plan.engine)) { + try { + // Probe the model before asking for the microphone: if it loads, the + // constraint below keeps browser NS off; if it fails, we still get + // browser denoising without a second permission prompt. + await microphoneCaptureFactory.preload(ctx, plan.engine); + assertCurrent(); + } catch { + assertCurrent(); + plan = { + mode: requestedMode, + engine: "browser", + requestBrowserNs: true, + fallback: "load-failed", + }; + } + } nextStream = await requestMediaBeforeAudioResume( - () => navigator.mediaDevices.getUserMedia({ audio: microphoneConstraints() }), + () => navigator.mediaDevices.getUserMedia({ audio: microphoneConstraints(plan) }), () => ctx.state === "suspended" ? ctx.resume() : Promise.resolve(), ); assertCurrent(); @@ -783,7 +884,7 @@ export function useVoiceWebSocket() { factoryOwnsStream = true; nextCapture = await microphoneCaptureFactory.prepare({ context: ctx, stream: nextStream, signal: controller.signal, assertCurrent, - rnnoiseEnabled: noiseSuppressionLevel.value === "strong", volume: inputVolume.value, onSamples: handleCaptureChunk, + plan, volume: inputVolume.value, onSamples: handleCaptureChunk, }); assertCurrent(); // Commit only a complete graph. Permission and node failures leave the @@ -800,12 +901,18 @@ export function useVoiceWebSocket() { microphoneTrack.addEventListener("ended", () => recordTrack("ended")); } Object.assign(microphoneProcessing, nextCapture.processing); + sessionTrace.record("microphone.denoise", { + requested: nextCapture.processing.requestedEngine, + active: nextCapture.processing.engine, + fallback: nextCapture.processing.fallback ?? "", + sampleRate: ctx.sampleRate, + }); nextCapture.setVolume(inputVolume.value); nextCapture.activate(); // The fallback for a later failed change is this actual live graph, even // if device enumeration or WebRTC negotiation is still in progress. committedInputDeviceId = selectedInputDeviceId.value; - committedNoiseSuppressionLevel = noiseSuppressionLevel.value; + committedNoiseSuppressionMode = requestedMode; clearMicrophoneError(); } catch (error) { nextCapture?.dispose(); @@ -935,13 +1042,13 @@ export function useVoiceWebSocket() { await refreshAudioDevices(); if (!isCurrent()) return; committedInputDeviceId = selectedInputDeviceId.value; - committedNoiseSuppressionLevel = noiseSuppressionLevel.value; + committedNoiseSuppressionMode = noiseSuppressionMode.value; localStorage.setItem("webspeak:input-device", committedInputDeviceId); await saveAudioPreferences(); } catch (error) { if (!isCurrent() || error instanceof CancelledMediaOperation) return; selectedInputDeviceId.value = committedInputDeviceId; - noiseSuppressionLevel.value = committedNoiseSuppressionLevel; + noiseSuppressionMode.value = committedNoiseSuppressionMode; localStorage.setItem("webspeak:input-device", committedInputDeviceId); throw error; } @@ -1132,10 +1239,15 @@ export function useVoiceWebSocket() { deviceListGeneration++; selectedInputDeviceId.value = committedInputDeviceId; selectedOutputDeviceId.value = committedOutputDeviceId; - noiseSuppressionLevel.value = committedNoiseSuppressionLevel; + noiseSuppressionMode.value = committedNoiseSuppressionMode; 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 +1258,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 +1309,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 +1363,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 +1476,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 +1628,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 { @@ -1565,21 +1730,28 @@ export function useVoiceWebSocket() { void saveAudioPreferences(); } - async function setNoiseSuppressionLevel(level: "off" | "standard" | "strong"): Promise { - if (noiseSuppressionLevel.value === level) return; + async function setNoiseSuppressionMode(mode: NoiseSuppressionMode): Promise { + if (noiseSuppressionMode.value === mode) return; noiseSuppressionTouched = true; - const previousLevel = noiseSuppressionLevel.value; - noiseSuppressionLevel.value = level; + const previousMode = noiseSuppressionMode.value; + noiseSuppressionMode.value = mode; try { await reconfigureMicrophone(); } catch (error) { - noiseSuppressionLevel.value = previousLevel; + noiseSuppressionMode.value = previousMode; setMicrophoneError(error); } } + /** Legacy three-value entry point; kept for external callers and skins. */ + async function setNoiseSuppressionLevel(level: StoredNoiseSuppressionLevel): Promise { + await setNoiseSuppressionMode(level === "off" ? "off" : level === "standard" ? "browser" : "gtcrn"); + } + function setNoiseSuppressionEnabled(enabled: boolean): Promise { - return setNoiseSuppressionLevel(enabled ? (noiseSuppressionLevel.value === "off" ? "strong" : noiseSuppressionLevel.value) : "off"); + return setNoiseSuppressionMode(enabled + ? (noiseSuppressionMode.value === "off" ? "gtcrn" : noiseSuppressionMode.value) + : "off"); } function setOutputVolume(volume: number): void { @@ -1620,6 +1792,7 @@ export function useVoiceWebSocket() { pokeNotifications, microphoneMuted, noiseSuppressionEnabled, + noiseSuppressionMode, noiseSuppressionLevel, inputVolume, outputVolume, @@ -1638,6 +1811,7 @@ export function useVoiceWebSocket() { micLevel, microphoneTestActive, testAudioUrl, + testAudioDryUrl, speakingIds, whisperTargetIds, whisperActive, @@ -1647,6 +1821,7 @@ export function useVoiceWebSocket() { accompanimentErrorCode, setVolume, setInputVolume, + setNoiseSuppressionMode, setNoiseSuppressionLevel, setNoiseSuppressionEnabled, setOutputVolume, diff --git a/web/src/composables/useWebClientAudioControls.ts b/web/src/composables/useWebClientAudioControls.ts index 3ff02ab..dddba2b 100644 --- a/web/src/composables/useWebClientAudioControls.ts +++ b/web/src/composables/useWebClientAudioControls.ts @@ -1,11 +1,10 @@ import { computed, onScopeDispose, ref, watch, type Ref } from "vue"; -import type { LocalPreferences } from "../services/local-persistence.js"; -type NoiseSuppressionLevel = NonNullable; +import type { NoiseSuppressionMode } from "../voice/noise-suppression.js"; interface UseWebClientAudioControlsOptions { settingsOpen: Ref; microphoneMuted: Readonly>; - noiseSuppressionLevel: Readonly>; + noiseSuppressionMode: Readonly>; inputVolume: Readonly>; voxThreshold: Readonly>; notificationVolume: Readonly>; @@ -16,7 +15,7 @@ interface UseWebClientAudioControlsOptions { whisperTargetIds: Set; prepareInputDevices: () => Promise; setInputVolume: (value: number) => void; - setNoiseSuppressionLevel: (level: NoiseSuppressionLevel) => Promise; + setNoiseSuppressionMode: (mode: NoiseSuppressionMode) => Promise; setOutputVolume: (value: number) => void; setVoxThreshold: (value: number) => void; setNotificationVolume: (value: number) => void; @@ -36,7 +35,7 @@ interface UseWebClientAudioControlsOptions { export function useWebClientAudioControls({ settingsOpen, microphoneMuted, - noiseSuppressionLevel, + noiseSuppressionMode, inputVolume, voxThreshold, notificationVolume, @@ -47,7 +46,7 @@ export function useWebClientAudioControls({ whisperTargetIds, prepareInputDevices, setInputVolume, - setNoiseSuppressionLevel, + setNoiseSuppressionMode, setOutputVolume, setVoxThreshold, setNotificationVolume, @@ -95,12 +94,12 @@ export function useWebClientAudioControls({ } function onNoiseSuppressionChange(event: Event): void { - const level = (event.target as HTMLSelectElement).value; - if (level === "off" || level === "standard" || level === "strong") void setNoiseSuppressionLevel(level); + const mode = (event.target as HTMLSelectElement).value; + if (mode === "off" || mode === "browser" || mode === "rnnoise" || mode === "gtcrn") void setNoiseSuppressionMode(mode); } function toggleNoiseSuppression(): void { - void setNoiseSuppressionLevel(noiseSuppressionLevel.value === "off" ? "strong" : "off"); + void setNoiseSuppressionMode(noiseSuppressionMode.value === "off" ? "gtcrn" : "off"); } function onOutputVolume(event: Event): void { diff --git a/web/src/composables/useWebClientI18n.ts b/web/src/composables/useWebClientI18n.ts index 7374630..d9bd68a 100644 --- a/web/src/composables/useWebClientI18n.ts +++ b/web/src/composables/useWebClientI18n.ts @@ -232,6 +232,12 @@ function localizedAudioNotice(code: string, message: string) { ? message.match(/错误代码:([A-Z0-9_-]{1,64})/)?.[1] ?? normalizedCode : normalizedCode; const messages: Record = { + 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`, diff --git a/web/src/i18n/admin.ts b/web/src/i18n/admin.ts index 72dbed5..226402f 100644 --- a/web/src/i18n/admin.ts +++ b/web/src/i18n/admin.ts @@ -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 はこの画面で管理され、旧ファイルの変更は現在の設定に反映されません。", diff --git a/web/src/i18n/web-client.ts b/web/src/i18n/web-client.ts index a4cbc18..5234548 100644 --- a/web/src/i18n/web-client.ts +++ b/web/src/i18n/web-client.ts @@ -341,11 +341,31 @@ export const webClientTranslations: Record> = { notificationVolume: "通知音量", audioStatus: "音频状态", audioReady: "音频已就绪", - noiseSuppression: "浏览器降噪", - noiseSuppressionHint: "标准使用浏览器降噪;强效模式会叠加 RNNoise(设备支持时)。", + noiseSuppression: "麦克风降噪", + noiseSuppressionHint: "强效使用本地 AI 模型 GTCRN,轻量使用 RNNoise;模型模式会关闭浏览器降噪,避免叠加。", noiseSuppressionOff: "关闭", noiseSuppressionStandard: "标准(浏览器)", - noiseSuppressionStrong: "强效(RNNoise)", + noiseSuppressionStandardShort: "标准", + noiseSuppressionLight: "轻量(RNNoise)", + noiseSuppressionLightShort: "轻量", + noiseSuppressionStrong: "强效(GTCRN)", + noiseSuppressionStrongShort: "强效", + noiseSuppressionActive: "当前生效", + noiseSuppressionEngineGtcrn: "GTCRN · 本地 WASM · 约 16 ms", + noiseSuppressionEngineRnnoise: "RNNoise · 约 10 ms", + noiseSuppressionEngineBrowser: "浏览器降噪", + noiseSuppressionEngineOff: "已关闭", + noiseSuppressionPreparing: "正在准备降噪模型…", + noiseSuppressionFallbackNoWorklet: "已回退到浏览器降噪:当前浏览器不支持 AudioWorklet。", + noiseSuppressionFallbackSampleRate: "已回退到浏览器降噪:音频上下文不是 48 kHz。", + noiseSuppressionFallbackLoad: "已回退到浏览器降噪:降噪模型加载失败。", + noiseSuppressionModelInactive: "降噪模型未能启动,本次不降噪;重新连接后会自动重试。", + noiseSuppressionBrowserStacking: "浏览器仍启用了降噪,可能与模型叠加;建议改用轻量或标准模式。", + micTestOriginal: "原始", + micTestDenoised: "降噪后", + micTestCompareHint: "同一段录音分别播放原始与降噪后音频,便于对比。", + micTestOriginalUnavailable: "原始录音没有可播放的音频。请重新测试麦克风。", + micTestDenoisedUnavailable: "降噪后录音没有可播放的音频。请重新测试麦克风。", exportAudioTrace: "导出最近两分钟的音频诊断", audioTraceHint: "可导出不含语音内容、昵称或服务器地址的本地诊断记录。", backgroundVoiceHint: "浏览器后台麦克风受浏览器和系统策略限制;锁屏或切后台后可能暂停。", @@ -775,11 +795,31 @@ export const webClientTranslations: Record> = { notificationVolume: "Notification volume", audioStatus: "Audio status", audioReady: "Audio ready", - noiseSuppression: "Browser noise suppression", - noiseSuppressionHint: "Standard uses browser filtering; strong also enables RNNoise when supported.", + noiseSuppression: "Microphone noise suppression", + noiseSuppressionHint: "Strong uses the local GTCRN model; Light uses RNNoise. Model modes disable browser denoising so the two never stack.", noiseSuppressionOff: "Off", noiseSuppressionStandard: "Standard (browser)", - noiseSuppressionStrong: "Strong (RNNoise)", + noiseSuppressionStandardShort: "Standard", + noiseSuppressionLight: "Light (RNNoise)", + noiseSuppressionLightShort: "Light", + noiseSuppressionStrong: "Strong (GTCRN)", + noiseSuppressionStrongShort: "Strong", + noiseSuppressionActive: "Active", + noiseSuppressionEngineGtcrn: "GTCRN · local WASM · about 16 ms", + noiseSuppressionEngineRnnoise: "RNNoise · about 10 ms", + noiseSuppressionEngineBrowser: "Browser noise suppression", + noiseSuppressionEngineOff: "Off", + noiseSuppressionPreparing: "Preparing the denoise model…", + noiseSuppressionFallbackNoWorklet: "Fell back to browser denoising: AudioWorklet is unavailable.", + noiseSuppressionFallbackSampleRate: "Fell back to browser denoising: the audio context is not 48 kHz.", + noiseSuppressionFallbackLoad: "Fell back to browser denoising: the model failed to load.", + noiseSuppressionModelInactive: "The denoise model could not start, so this session runs without denoising. It retries on the next connection.", + noiseSuppressionBrowserStacking: "The browser still applies its own denoising, so it may stack with the model. Try Light or Standard.", + micTestOriginal: "Original", + micTestDenoised: "Denoised", + micTestCompareHint: "The same take plays raw and denoised so you can compare them.", + micTestOriginalUnavailable: "The original take has no playable audio. Please run the microphone test again.", + micTestDenoisedUnavailable: "The denoised take has no playable audio. Please run the microphone test again.", exportAudioTrace: "Export the last two minutes of audio diagnostics", audioTraceHint: "The local trace excludes audio content, nicknames, and server addresses.", backgroundVoiceHint: "Background microphone capture depends on browser and OS policy and may pause when hidden or locked.", @@ -1202,11 +1242,31 @@ webClientTranslations.de = { notificationVolume: "Benachrichtigungslautstärke", audioStatus: "Audiostatus", audioReady: "Audio bereit", - noiseSuppression: "Browser-Geräuschunterdrückung", - noiseSuppressionHint: "Standard nutzt die Browserfilterung; Stark aktiviert zusätzlich RNNoise, sofern unterstützt.", + noiseSuppression: "Mikrofon-Geräuschunterdrückung", + noiseSuppressionHint: "Stark nutzt das lokale GTCRN-Modell, Leicht nutzt RNNoise. Modus mit Modell deaktiviert die Browser-Filterung, damit sich beide nicht überlagern.", noiseSuppressionOff: "Aus", noiseSuppressionStandard: "Standard (Browser)", - noiseSuppressionStrong: "Stark (RNNoise)", + noiseSuppressionStandardShort: "Standard", + noiseSuppressionLight: "Leicht (RNNoise)", + noiseSuppressionLightShort: "Leicht", + noiseSuppressionStrong: "Stark (GTCRN)", + noiseSuppressionStrongShort: "Stark", + noiseSuppressionActive: "Aktiv", + noiseSuppressionEngineGtcrn: "GTCRN · lokales WASM · ca. 16 ms", + noiseSuppressionEngineRnnoise: "RNNoise · ca. 10 ms", + noiseSuppressionEngineBrowser: "Browser-Geräuschunterdrückung", + noiseSuppressionEngineOff: "Aus", + noiseSuppressionPreparing: "Geräuschmodell wird vorbereitet…", + noiseSuppressionFallbackNoWorklet: "Auf Browser-Filterung zurückgefallen: AudioWorklet ist nicht verfügbar.", + noiseSuppressionFallbackSampleRate: "Auf Browser-Filterung zurückgefallen: Der Audiokontext läuft nicht mit 48 kHz.", + noiseSuppressionFallbackLoad: "Auf Browser-Filterung zurückgefallen: Das Modell konnte nicht geladen werden.", + noiseSuppressionModelInactive: "Das Geräuschmodell konnte nicht starten; diese Sitzung läuft ohne Geräuschunterdrückung. Beim nächsten Verbinden wird es erneut versucht.", + noiseSuppressionBrowserStacking: "Der Browser filtert weiterhin selbst; das kann sich mit dem Modell überlagern. Bitte Leicht oder Standard verwenden.", + micTestOriginal: "Original", + micTestDenoised: "Entrauscht", + micTestCompareHint: "Dieselbe Aufnahme wird roh und entrauscht abgespielt, damit du vergleichen kannst.", + micTestOriginalUnavailable: "Die Originalaufnahme enthält kein abspielbares Audio. Bitte den Mikrofontest erneut ausführen.", + micTestDenoisedUnavailable: "Die entrauschte Aufnahme enthält kein abspielbares Audio. Bitte den Mikrofontest erneut ausführen.", exportAudioTrace: "Letzte zwei Minuten der Audiodiagnose exportieren", audioTraceHint: "Der lokale Verlauf enthält keine Audioinhalte, Namen oder Serveradressen.", backgroundVoiceHint: "Die Mikrofonaufnahme im Hintergrund hängt von Browser und Betriebssystem ab und kann pausieren.", @@ -1377,11 +1437,31 @@ webClientTranslations.ru = { screenShareBitrate8M: "8 Мбит/с", screenShareBitrate12M: "12 Мбит/с", screenShareSettingsNote: "Настройки применятся при следующем запуске трансляции", - noiseSuppression: "Шумоподавление", - noiseSuppressionHint: "Стандартный режим использует фильтр браузера; усиленный также включает RNNoise, если он поддерживается.", + noiseSuppression: "Шумоподавление микрофона", + noiseSuppressionHint: "Усиленный режим использует локальную модель GTCRN, лёгкий — RNNoise. Режимы с моделью отключают шумоподавление браузера, чтобы они не складывались.", noiseSuppressionOff: "Выкл.", noiseSuppressionStandard: "Стандартный (браузер)", - noiseSuppressionStrong: "Усиленный (RNNoise)", + noiseSuppressionStandardShort: "Стандарт", + noiseSuppressionLight: "Лёгкий (RNNoise)", + noiseSuppressionLightShort: "Лёгкий", + noiseSuppressionStrong: "Усиленный (GTCRN)", + noiseSuppressionStrongShort: "Усиленный", + noiseSuppressionActive: "Активно", + noiseSuppressionEngineGtcrn: "GTCRN · локальный WASM · около 16 мс", + noiseSuppressionEngineRnnoise: "RNNoise · около 10 мс", + noiseSuppressionEngineBrowser: "Шумоподавление браузера", + noiseSuppressionEngineOff: "Выключено", + noiseSuppressionPreparing: "Подготовка модели шумоподавления…", + noiseSuppressionFallbackNoWorklet: "Используется шумоподавление браузера: AudioWorklet недоступен.", + noiseSuppressionFallbackSampleRate: "Используется шумоподавление браузера: аудиоконтекст работает не на 48 кГц.", + noiseSuppressionFallbackLoad: "Используется шумоподавление браузера: модель не загрузилась.", + noiseSuppressionModelInactive: "Модель шумоподавления не запустилась, поэтому в этой сессии шумоподавление не применяется. Повторная попытка — при следующем подключении.", + noiseSuppressionBrowserStacking: "Браузер всё ещё применяет своё шумоподавление, возможна перегрузка. Попробуйте лёгкий или стандартный режим.", + micTestOriginal: "Оригинал", + micTestDenoised: "После обработки", + micTestCompareHint: "Одна и та же запись воспроизводится в исходном и обработанном виде для сравнения.", + micTestOriginalUnavailable: "Исходная запись не содержит воспроизводимого аудио. Повторите тест микрофона.", + micTestDenoisedUnavailable: "Обработанная запись не содержит воспроизводимого аудио. Повторите тест микрофона.", exportAudioTrace: "Экспортировать диагностику звука за последние две минуты", audioTraceHint: "Локальная запись не содержит аудио, имён или адресов серверов.", backgroundVoiceHint: "Фоновая запись с микрофона зависит от браузера и ОС и может приостанавливаться.", @@ -1598,11 +1678,31 @@ webClientTranslations.ja = { screenShareBitrate8M: "8 Mbps", screenShareBitrate12M: "12 Mbps", screenShareSettingsNote: "次回の共有開始時に適用されます", - noiseSuppression: "ノイズ抑制", - noiseSuppressionHint: "標準はブラウザーのフィルターを使用し、強力は対応環境で RNNoise も有効にします。", + noiseSuppression: "マイクのノイズ抑制", + noiseSuppressionHint: "強力はローカルの GTCRN モデル、軽量は RNNoise を使用します。モデル使用時はブラウザーのノイズ抑制を切るため、二重にはかかりません。", noiseSuppressionOff: "オフ", noiseSuppressionStandard: "標準(ブラウザー)", - noiseSuppressionStrong: "強力(RNNoise)", + noiseSuppressionStandardShort: "標準", + noiseSuppressionLight: "軽量(RNNoise)", + noiseSuppressionLightShort: "軽量", + noiseSuppressionStrong: "強力(GTCRN)", + noiseSuppressionStrongShort: "強力", + noiseSuppressionActive: "現在の適用", + noiseSuppressionEngineGtcrn: "GTCRN · ローカル WASM · 約 16 ms", + noiseSuppressionEngineRnnoise: "RNNoise · 約 10 ms", + noiseSuppressionEngineBrowser: "ブラウザーのノイズ抑制", + noiseSuppressionEngineOff: "オフ", + noiseSuppressionPreparing: "ノイズ抑制モデルを準備中…", + noiseSuppressionFallbackNoWorklet: "ブラウザーのノイズ抑制に戻しました:AudioWorklet が利用できません。", + noiseSuppressionFallbackSampleRate: "ブラウザーのノイズ抑制に戻しました:オーディオコンテキストが 48 kHz ではありません。", + noiseSuppressionFallbackLoad: "ブラウザーのノイズ抑制に戻しました:モデルを読み込めませんでした。", + noiseSuppressionModelInactive: "ノイズ抑制モデルを起動できなかったため、この接続ではノイズ抑制なしで動作します。次回接続時に再試行します。", + noiseSuppressionBrowserStacking: "ブラウザーのノイズ抑制も有効なため、モデルと重なる可能性があります。軽量または標準をお試しください。", + micTestOriginal: "元の音声", + micTestDenoised: "処理後", + micTestCompareHint: "同じ録音を元の音声と処理後の音声で再生して比較できます。", + micTestOriginalUnavailable: "元の録音を再生できる音声がありません。マイクテストをやり直してください。", + micTestDenoisedUnavailable: "処理後の録音を再生できる音声がありません。マイクテストをやり直してください。", exportAudioTrace: "直近 2 分間の音声診断をエクスポート", audioTraceHint: "音声、ニックネーム、サーバーアドレスを含まないローカル診断です。", backgroundVoiceHint: "バックグラウンドでのマイク利用はブラウザーと OS の制御を受け、停止する場合があります。", diff --git a/web/src/services/local-persistence.test.ts b/web/src/services/local-persistence.test.ts index a8caaa8..8a9c53e 100644 --- a/web/src/services/local-persistence.test.ts +++ b/web/src/services/local-persistence.test.ts @@ -120,3 +120,33 @@ test("storage read success still returns its original data after transaction com tx.read({ schemaVersion: 1, skinId: "builtin.dark" }); tx.commit(); assert.deepEqual(await pending, { schemaVersion: 1, skinId: "builtin.dark", volumesByUid: {} }); }); +test("noise suppression mode is stored beside the legacy level for older builds", async () => { + const pending = saveLocalPreferences({ + schemaVersion: 1, + noiseSuppressionMode: "gtcrn", + noiseSuppressionLevel: "strong", + noiseSuppressionEnabled: true, + }); + await nextTurn(); const tx = transactions[0]; + tx.read({ schemaVersion: 1, noiseSuppressionMode: "browser", noiseSuppressionLevel: "standard" }); + assert.deepEqual(tx.written, { + id: "singleton", + schemaVersion: 1, + noiseSuppressionMode: "gtcrn", + noiseSuppressionLevel: "strong", + noiseSuppressionEnabled: true, + volumesByUid: {}, + }); + tx.writtenSuccessfully(); tx.commit(); await pending; + + const read = loadLocalPreferences(); + await nextTurn(); const readTx = transactions[1]; + readTx.read({ schemaVersion: 1, noiseSuppressionLevel: "strong", noiseSuppressionEnabled: true }); + readTx.commit(); + assert.deepEqual(await read, { + schemaVersion: 1, + noiseSuppressionLevel: "strong", + noiseSuppressionEnabled: true, + volumesByUid: {}, + }); +}); diff --git a/web/src/services/local-persistence.ts b/web/src/services/local-persistence.ts index 1d226c6..eb0c859 100644 --- a/web/src/services/local-persistence.ts +++ b/web/src/services/local-persistence.ts @@ -146,6 +146,7 @@ export interface LocalPreferences { skinId?: string; microphoneMuted?: boolean; noiseSuppressionEnabled?: boolean; + noiseSuppressionMode?: "off" | "browser" | "rnnoise" | "gtcrn"; noiseSuppressionLevel?: "off" | "standard" | "strong"; voxThreshold?: number; language?: "zh" | "en" | "de" | "ru" | "ja"; diff --git a/web/src/styles/web-client.css b/web/src/styles/web-client.css index 5664649..28a4c35 100644 --- a/web/src/styles/web-client.css +++ b/web/src/styles/web-client.css @@ -4648,6 +4648,40 @@ margin-top: 11px; } +:deep(.noise-suppression-status) { + margin: 2px 0 12px; +} + +:deep(.mic-test-compare) { + margin-top: 11px; +} + +:deep(.mic-test-tabs) { + display: flex; + gap: 6px; + margin-bottom: 8px; +} + +:deep(.mic-test-tabs button) { + padding: 6px 10px; + color: #006a64; + background: #eef7f5; + border: 1px solid #d5e7e2; + border-radius: 6px; + font-size: 10px; + cursor: pointer; +} + +:deep(.mic-test-tabs button.active) { + color: #fff; + background: #006a64; + border-color: #006a64; +} + +:deep(.mic-test-compare .test-audio) { + margin-top: 0; +} + /* Shared interaction/layout rules; appearance is supplied by a built-in skin package. */ .join-page .join-card { diff --git a/web/src/views/WebClient.vue b/web/src/views/WebClient.vue index 3b7ce03..17a7422 100644 --- a/web/src/views/WebClient.vue +++ b/web/src/views/WebClient.vue @@ -1060,7 +1060,7 @@ const { pokeNotifications, microphoneMuted, noiseSuppressionEnabled, - noiseSuppressionLevel, + noiseSuppressionMode, inputVolume, outputVolume, outputMuted, @@ -1073,17 +1073,19 @@ const { outputDeviceSupported, audioPermission, audioContextState, + microphoneProcessing, identityMaterial, micLevel, microphoneTestActive, testAudioUrl, + testAudioDryUrl, speakingIds, volumes, whisperTargetIds, whisperActive, setVolume, setInputVolume, - setNoiseSuppressionLevel, + setNoiseSuppressionMode, setOutputVolume, toggleOutputMute, setVoxThreshold, @@ -1279,7 +1281,7 @@ const skinHomeFeatures = computed(() => { const audioControls = useWebClientAudioControls({ settingsOpen, microphoneMuted, - noiseSuppressionLevel, + noiseSuppressionMode, inputVolume, voxThreshold, notificationVolume, @@ -1290,7 +1292,7 @@ const audioControls = useWebClientAudioControls({ whisperTargetIds, prepareInputDevices, setInputVolume, - setNoiseSuppressionLevel, + setNoiseSuppressionMode, setOutputVolume, setVoxThreshold, setNotificationVolume, @@ -1314,7 +1316,7 @@ function reconnectMobile(): void { reconnectNow(); } const { toggleMicrophone, stopWhisperTalk } = audioControls; -const audioDockState = { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive }; +const audioDockState = { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionMode, accompanimentActive }; const audioSettingsState = { inputDevices, outputDevices, @@ -1323,8 +1325,9 @@ const audioSettingsState = { outputDeviceSupported, audioPermission, audioContextState, + microphoneProcessing, microphoneMuted, - noiseSuppressionLevel, + noiseSuppressionMode, inputVolume, outputVolume, voxThreshold, @@ -1332,6 +1335,7 @@ const audioSettingsState = { micLevel, microphoneTestActive, testAudioUrl, + testAudioDryUrl, }; diff --git a/web/src/voice/audio-diagnostics.ts b/web/src/voice/audio-diagnostics.ts index 097fd3e..a48a79d 100644 --- a/web/src/voice/audio-diagnostics.ts +++ b/web/src/voice/audio-diagnostics.ts @@ -107,7 +107,14 @@ function sameSource(left: DiagnosticSource | null, right: DiagnosticSource | nul export function createAudioDiagnostics(options: DiagnosticOptions) { const pending = new Map(); 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; diff --git a/web/src/voice/jitter-buffer.ts b/web/src/voice/jitter-buffer.ts index f8a712d..9b9b1c7 100644 --- a/web/src/voice/jitter-buffer.ts +++ b/web/src/voice/jitter-buffer.ts @@ -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. */ diff --git a/web/src/voice/microphone-capture.ts b/web/src/voice/microphone-capture.ts index 1308fdf..505effb 100644 --- a/web/src/voice/microphone-capture.ts +++ b/web/src/voice/microphone-capture.ts @@ -1,17 +1,28 @@ -import { RnnoiseWorkletNode, loadRnnoise } from "@sapphi-red/web-noise-suppressor"; +import { GtcrnWorkletNode, RnnoiseWorkletNode, loadGtcrn, loadRnnoise } from "@sapphi-red/web-noise-suppressor"; +import gtcrnWasmUrl from "@sapphi-red/web-noise-suppressor/gtcrn.wasm?url"; +import gtcrnWorkletUrl from "@sapphi-red/web-noise-suppressor/gtcrnWorklet.js?url"; import rnnoiseSimdWasmUrl from "@sapphi-red/web-noise-suppressor/rnnoise_simd.wasm?url"; import rnnoiseWasmUrl from "@sapphi-red/web-noise-suppressor/rnnoise.wasm?url"; import rnnoiseWorkletUrl from "@sapphi-red/web-noise-suppressor/rnnoiseWorklet.js?url"; +import { isNeuralDenoiseEngine, type DenoiseEngine, type DenoiseFallback, type DenoisePlan } from "./noise-suppression.js"; export interface MicrophoneProcessingSettings { echoCancellation: boolean | null; noiseSuppression: boolean | null; autoGainControl: boolean | null; - rnnoise: boolean | null; + /** Engine that actually ran, after capability/load fallbacks. */ + engine: DenoiseEngine; + /** Engine the user asked for before fallbacks. */ + requestedEngine: DenoiseEngine; + fallback: DenoiseFallback; + /** The browser ignored `noiseSuppression:false`; model and browser NS may stack. */ + warning: "browser-ns-active" | null; } export interface MicrophoneCapture { processedStream: MediaStream; + /** Pre-denoise tap of the same capture, safe to hand to MediaRecorder. */ + dryStream: MediaStream; processing: MicrophoneProcessingSettings; activate(): void; setVolume(value: number): void; @@ -22,18 +33,24 @@ export interface MicrophoneCapture { interface CaptureOptions { context: AudioContext; stream: MediaStream; - rnnoiseEnabled: boolean; + plan: DenoisePlan; volume: number; signal: AbortSignal; assertCurrent(): void; onSamples(input: Float32Array, rms?: number): void; } +// A single high-pass before the neural model removes rumble the model would +// otherwise have to separate from speech. Chrome's APM uses the same corner. +const DENOISE_HIGHPASS_HZ = 80; + // Each prepared graph owns its stream and nodes. It cannot publish PCM before // activation, and aborting preparation never touches the currently live graph. export function createMicrophoneCaptureFactory() { const modules = new WeakMap>>(); - let wasmPromise: Promise | null = null; + let rnnoiseWasmPromise: Promise | null = null; + let gtcrnWasmPromise: Promise | null = null; + function loadModule(ctx: AudioContext, url: string): Promise { let cache = modules.get(ctx); if (!cache) { cache = new Map(); modules.set(ctx, cache); } @@ -49,11 +66,46 @@ export function createMicrophoneCaptureFactory() { return pending; } + function loadWasm(engine: "rnnoise" | "gtcrn"): Promise { + if (engine === "gtcrn") { + if (!gtcrnWasmPromise) { + gtcrnWasmPromise = loadGtcrn({ url: gtcrnWasmUrl }).catch(error => { + gtcrnWasmPromise = null; + throw error; + }); + } + return gtcrnWasmPromise; + } + if (!rnnoiseWasmPromise) { + rnnoiseWasmPromise = loadRnnoise({ url: rnnoiseWasmUrl, simdUrl: rnnoiseSimdWasmUrl }).catch(error => { + rnnoiseWasmPromise = null; + throw error; + }); + } + return rnnoiseWasmPromise; + } + + function engineWorkletUrl(engine: "rnnoise" | "gtcrn"): string { + return engine === "gtcrn" ? gtcrnWorkletUrl : rnnoiseWorkletUrl; + } + + /** + * Load WASM and the AudioWorklet module before getUserMedia. This lets the + * capture path request `noiseSuppression:false` only when the model is really + * available, without re-acquiring the microphone for a fallback. + */ + async function preload(ctx: AudioContext, engine: DenoiseEngine): Promise { + if (!isNeuralDenoiseEngine(engine)) return; + await Promise.all([loadWasm(engine), loadModule(ctx, engineWorkletUrl(engine))]); + } + async function prepare(options: CaptureOptions): Promise { const { context: ctx, stream, assertCurrent } = options; let source: MediaStreamAudioSourceNode | null = null; - let denoiser: RnnoiseWorkletNode | null = null; + let highpass: BiquadFilterNode | null = null; + let denoiser: RnnoiseWorkletNode | GtcrnWorkletNode | null = null; let destination: MediaStreamAudioDestinationNode | null = null; + let dryDestination: MediaStreamAudioDestinationNode | null = null; let gain: GainNode | null = null; let silent: GainNode | null = null; let worklet: AudioWorkletNode | null = null; @@ -61,6 +113,9 @@ export function createMicrophoneCaptureFactory() { let active = false; let captureConnected = false; let disposed = false; + const requestedEngine = options.plan.engine; + let activeEngine: DenoiseEngine = requestedEngine === "browser" ? "browser" : requestedEngine === "off" ? "off" : "off"; + let fallback: DenoiseFallback = options.plan.fallback; const clean = (operation: () => void) => { try { operation(); } catch { /* release the other resources too */ } }; function stopCapture() { active = false; @@ -77,7 +132,12 @@ export function createMicrophoneCaptureFactory() { stopCapture(); if (worklet) clean(() => worklet!.port.close()); if (denoiser) { clean(() => denoiser!.destroy()); clean(() => denoiser!.disconnect()); } + if (highpass) clean(() => highpass!.disconnect()); if (source) clean(() => source!.disconnect()); + if (dryDestination) { + clean(() => dryDestination!.disconnect()); + for (const track of dryDestination.stream.getTracks()) clean(() => track.stop()); + } if (destination) { clean(() => destination!.disconnect()); for (const track of destination.stream.getTracks()) clean(() => track.stop()); @@ -95,21 +155,41 @@ export function createMicrophoneCaptureFactory() { const settings = track.getSettings(); source = ctx.createMediaStreamSource(stream); const supportsWorklet = typeof AudioWorkletNode !== "undefined" && Boolean(ctx.audioWorklet); - if (options.rnnoiseEnabled && supportsWorklet) { + if (isNeuralDenoiseEngine(requestedEngine) && supportsWorklet) { try { - if (!wasmPromise) wasmPromise = loadRnnoise({ url: rnnoiseWasmUrl, simdUrl: rnnoiseSimdWasmUrl }).catch(error => { - wasmPromise = null; - throw error; - }); - const [wasmBinary] = await Promise.all([wasmPromise, loadModule(ctx, rnnoiseWorkletUrl)]); + const [wasmBinary] = await Promise.all([ + loadWasm(requestedEngine), + loadModule(ctx, engineWorkletUrl(requestedEngine)), + ]); assertCurrent(); - denoiser = new RnnoiseWorkletNode(ctx, { maxChannels: 1, wasmBinary }); + denoiser = requestedEngine === "gtcrn" + ? new GtcrnWorkletNode(ctx, { maxChannels: 1, wasmBinary }) + : new RnnoiseWorkletNode(ctx, { maxChannels: 1, wasmBinary }); + activeEngine = requestedEngine; } catch { - assertCurrent(); // RNNoise is optional; cancellation is not a fallback. + assertCurrent(); // A model failure must not consume cancellation as a fallback. + denoiser = null; + activeEngine = "off"; + fallback = "load-failed"; } } - const processedSource = denoiser ?? source; - if (denoiser) source.connect(denoiser); + let processedSource: AudioNode = source; + if (denoiser) { + highpass = ctx.createBiquadFilter(); + highpass.type = "highpass"; + highpass.frequency.value = DENOISE_HIGHPASS_HZ; + highpass.Q.value = Math.SQRT1_2; + source.connect(highpass); + highpass.connect(denoiser); + processedSource = denoiser; + } + // A destination tap of the raw source, before the high-pass / model. + // MediaRecorder cannot reliably record a getUserMedia track that is + // already attached to an AudioContext as a MediaStreamSource. + dryDestination = ctx.createMediaStreamDestination(); + dryDestination.channelCount = 1; + dryDestination.channelCountMode = "explicit"; + source.connect(dryDestination); destination = ctx.createMediaStreamDestination(); destination.channelCount = 1; destination.channelCountMode = "explicit"; @@ -148,11 +228,15 @@ export function createMicrophoneCaptureFactory() { if (track.readyState !== "live") throw new DOMException("Microphone track ended", "NotReadableError"); return { processedStream: destination.stream, + dryStream: dryDestination.stream, processing: { echoCancellation: typeof settings.echoCancellation === "boolean" ? settings.echoCancellation : null, noiseSuppression: typeof settings.noiseSuppression === "boolean" ? settings.noiseSuppression : null, autoGainControl: typeof settings.autoGainControl === "boolean" ? settings.autoGainControl : null, - rnnoise: Boolean(denoiser), + engine: activeEngine, + requestedEngine: options.plan.mode, + fallback, + warning: isNeuralDenoiseEngine(activeEngine) && settings.noiseSuppression === true ? "browser-ns-active" : null, }, activate() { if (disposed || !(worklet || script)) return; @@ -176,5 +260,5 @@ export function createMicrophoneCaptureFactory() { options.signal.removeEventListener("abort", dispose); } } - return { prepare }; + return { prepare, preload }; } diff --git a/web/src/voice/microphone-test.test.ts b/web/src/voice/microphone-test.test.ts new file mode 100644 index 0000000..3e76260 --- /dev/null +++ b/web/src/voice/microphone-test.test.ts @@ -0,0 +1,280 @@ +import assert from "node:assert/strict"; +import { afterEach, test } from "node:test"; +import { + MICROPHONE_TEST_DURATION_MS, + createMicrophoneTest, + micTestPlaybackSource, +} from "./microphone-test.ts"; +import { webClientTranslations } from "../i18n/web-client.ts"; + +class Track { + readyState: "live" | "ended" = "live"; + stopped = 0; + stop() { this.stopped++; this.readyState = "ended"; } + clone() { + const copy = new Track(); + copy.readyState = this.readyState; + return copy; + } +} + +class FakeStream { + kind?: string; + constructor(readonly track = new Track()) {} + getTracks() { return [this.track]; } + getAudioTracks() { return [this.track]; } + getVideoTracks() { return []; } + clone() { + const copy = new FakeStream(this.track.clone()); + copy.kind = this.kind; + return copy; + } +} + +class FakeRecorder { + static instances: FakeRecorder[] = []; + static failKinds = new Set(); + static emptyKinds = new Set(); + state: "inactive" | "recording" = "inactive"; + mimeType = "audio/webm"; + stops = 0; + startTimeslice: number | undefined; + ondataavailable: ((event: { data: Blob }) => void) | null = null; + onstop: (() => void) | null = null; + onerror: ((event: { error: Error }) => void) | null = null; + constructor(readonly stream: FakeStream, _options?: unknown) { + FakeRecorder.instances.push(this); + } + start(timeslice?: number) { + const kind = (this.stream as FakeStream & { kind?: string }).kind; + if (kind && FakeRecorder.failKinds.has(kind)) throw new Error(`${kind} recorder start failed`); + this.startTimeslice = timeslice; + this.state = "recording"; + } + requestData() {} + stop() { + this.stops++; + this.state = "inactive"; + } + finish() { + if (!FakeRecorder.emptyKinds.has((this.stream as FakeStream & { kind?: string }).kind ?? "")) { + this.ondataavailable?.({ data: new Blob(["audio"]) }); + } else { + this.ondataavailable?.({ data: new Blob([]) }); + } + this.onstop?.(); + } +} + +const originalRecorder = globalThis.MediaRecorder; +const originalURL = { createObjectURL: URL.createObjectURL, revokeObjectURL: URL.revokeObjectURL }; + +afterEach(() => { + FakeRecorder.instances = []; + FakeRecorder.failKinds = new Set(); + FakeRecorder.emptyKinds = new Set(); + // @ts-expect-error test stub restore + globalThis.MediaRecorder = originalRecorder; + URL.createObjectURL = originalURL.createObjectURL; + URL.revokeObjectURL = originalURL.revokeObjectURL; +}); + +function installRecorder() { + // @ts-expect-error test stub + globalThis.MediaRecorder = FakeRecorder; +} + +test("the raw tab must not reuse the denoised URL when the original take is missing", () => { + const missingDry = micTestPlaybackSource("dry", { processed: "blob:processed", dry: "" }); + assert.equal(missingDry.src, ""); + assert.equal(missingDry.missing, true); + assert.equal(missingDry.missingKey, "micTestOriginalUnavailable"); + + const processed = micTestPlaybackSource("processed", { processed: "blob:processed", dry: "" }); + assert.equal(processed.src, "blob:processed"); + assert.equal(processed.missing, false); + assert.equal(processed.missingKey, "micTestDenoisedUnavailable"); +}); + +test("the denoised tab must not reuse the original URL when the processed take is missing", () => { + const missingProcessed = micTestPlaybackSource("processed", { processed: "", dry: "blob:dry" }); + assert.equal(missingProcessed.src, ""); + assert.equal(missingProcessed.missing, true); + assert.equal(missingProcessed.missingKey, "micTestDenoisedUnavailable"); + + const dry = micTestPlaybackSource("dry", { processed: "", dry: "blob:dry" }); + assert.equal(dry.src, "blob:dry"); + assert.equal(dry.missing, false); +}); + +test("both sides of one take publish playback URLs after the shared deadline", async t => { + installRecorder(); + const created: string[] = []; + const urls = { processed: "", dry: "" }; + let active = false; + let stopped = 0; + t.mock.method(URL, "createObjectURL", () => `blob:${created.push("x")}`); + t.mock.method(URL, "revokeObjectURL", () => {}); + let deadline: (() => void) | undefined; + t.mock.method(globalThis, "setTimeout", (callback: () => void, delay: number) => { + assert.equal(delay, MICROPHONE_TEST_DURATION_MS); + deadline = callback; + return 1; + }); + t.mock.method(globalThis, "clearTimeout", () => {}); + const dry = Object.assign(new FakeStream(), { kind: "dry" }); + const processed = Object.assign(new FakeStream(), { kind: "processed" }); + const test = createMicrophoneTest({ + prepare: async () => ({ dry, processed }), + onActive(value) { active = value; }, + onUrl(url) { urls.processed = url; }, + onDryUrl(url) { urls.dry = url; }, + onStopped() { stopped++; }, + onError(error) { throw error; }, + }); + await test.start(); + assert.equal(FakeRecorder.instances.length, 2); + assert.ok(FakeRecorder.instances.every(recorder => recorder.startTimeslice === 1_000)); + assert.equal(active, true); + assert.ok(deadline); + deadline(); + assert.equal(active, false); + assert.equal(stopped, 0, "source teardown waits until recorders have flushed"); + assert.ok(FakeRecorder.instances.every(recorder => recorder.stops === 1)); + for (const recorder of FakeRecorder.instances) recorder.finish(); + assert.equal(stopped, 1); + assert.equal(urls.processed, "blob:1"); + assert.equal(urls.dry, "blob:2"); + assert.equal(dry.track.readyState, "live"); + assert.equal(processed.track.readyState, "live"); +}); + +test("empty dry chunks leave the denoised URL and an empty original URL", async t => { + installRecorder(); + FakeRecorder.emptyKinds.add("dry"); + const urls = { processed: "pending", dry: "pending" }; + t.mock.method(URL, "createObjectURL", () => "blob:processed-only"); + t.mock.method(URL, "revokeObjectURL", () => {}); + t.mock.method(globalThis, "setTimeout", () => 1); + t.mock.method(globalThis, "clearTimeout", () => {}); + const test = createMicrophoneTest({ + prepare: async () => ({ + dry: Object.assign(new FakeStream(), { kind: "dry" }), + processed: Object.assign(new FakeStream(), { kind: "processed" }), + }), + onActive() {}, + onUrl(url) { urls.processed = url; }, + onDryUrl(url) { urls.dry = url; }, + onStopped() {}, + onError(error) { throw error; }, + }); + await test.start(); + test.stop(); + for (const recorder of FakeRecorder.instances) recorder.finish(); + assert.equal(urls.processed, "blob:processed-only"); + assert.equal(urls.dry, ""); + const playback = micTestPlaybackSource("dry", urls); + assert.equal(playback.missing, true); + assert.equal(playback.src, ""); + assert.equal(micTestPlaybackSource("processed", urls).src, "blob:processed-only"); +}); + +test("a dry start failure still records the processed side", async t => { + installRecorder(); + FakeRecorder.failKinds.add("dry"); + const urls = { processed: "", dry: "" }; + t.mock.method(URL, "createObjectURL", () => "blob:processed-only"); + t.mock.method(URL, "revokeObjectURL", () => {}); + t.mock.method(globalThis, "setTimeout", () => 1); + t.mock.method(globalThis, "clearTimeout", () => {}); + const test = createMicrophoneTest({ + prepare: async () => ({ + dry: Object.assign(new FakeStream(), { kind: "dry" }), + processed: Object.assign(new FakeStream(), { kind: "processed" }), + }), + onActive() {}, + onUrl(url) { urls.processed = url; }, + onDryUrl(url) { urls.dry = url; }, + onStopped() {}, + onError(error) { throw error; }, + }); + await test.start(); + assert.equal(FakeRecorder.instances.length, 2); + assert.equal(FakeRecorder.instances.filter(recorder => recorder.state === "recording").length, 1); + test.stop(); + for (const recorder of FakeRecorder.instances) { + if (recorder.stops) recorder.finish(); + } + assert.equal(urls.processed, "blob:processed-only"); + assert.equal(urls.dry, ""); +}); + +test("recording uses clones so stopping the test does not end the live tracks", async t => { + installRecorder(); + t.mock.method(URL, "createObjectURL", () => "blob:ok"); + t.mock.method(URL, "revokeObjectURL", () => {}); + t.mock.method(globalThis, "setTimeout", () => 1); + t.mock.method(globalThis, "clearTimeout", () => {}); + const dry = Object.assign(new FakeStream(), { kind: "dry" }); + const processed = Object.assign(new FakeStream(), { kind: "processed" }); + const test = createMicrophoneTest({ + prepare: async () => ({ dry, processed }), + onActive() {}, + onUrl() {}, + onDryUrl() {}, + onStopped() {}, + onError(error) { throw error; }, + }); + await test.start(); + const clones = FakeRecorder.instances.map(recorder => recorder.stream); + assert.ok(clones.every(stream => stream !== dry && stream !== processed)); + test.stop(); + for (const recorder of FakeRecorder.instances) recorder.finish(); + assert.equal(dry.track.readyState, "live"); + assert.equal(processed.track.readyState, "live"); + assert.ok(clones.every(stream => stream.track.readyState === "ended")); +}); + + + +test("a processed onstop that arrives before the dry dataavailable still keeps the original take", async t => { + installRecorder(); + const urls = { processed: "", dry: "" }; + t.mock.method(URL, "createObjectURL", (blob: Blob) => blob.size ? `blob:${blob.size}` : "blob:empty"); + t.mock.method(URL, "revokeObjectURL", () => {}); + t.mock.method(globalThis, "setTimeout", () => 1); + t.mock.method(globalThis, "clearTimeout", () => {}); + const test = createMicrophoneTest({ + prepare: async () => ({ + dry: Object.assign(new FakeStream(), { kind: "dry" }), + processed: Object.assign(new FakeStream(), { kind: "processed" }), + }), + onActive() {}, + onUrl(url) { urls.processed = url; }, + onDryUrl(url) { urls.dry = url; }, + onStopped() {}, + onError(error) { throw error; }, + }); + await test.start(); + test.stop(); + const processed = FakeRecorder.instances.find(recorder => (recorder.stream as FakeStream & { kind?: string }).kind === "processed"); + const dry = FakeRecorder.instances.find(recorder => (recorder.stream as FakeStream & { kind?: string }).kind === "dry"); + assert.ok(processed && dry); + processed!.ondataavailable?.({ data: new Blob(["processed-audio"]) }); + processed!.onstop?.(); + assert.equal(urls.processed, "", "must not publish until the dry recorder also stops"); + assert.equal(urls.dry, ""); + dry!.ondataavailable?.({ data: new Blob(["dry-audio"]) }); + dry!.onstop?.(); + assert.ok(urls.processed.startsWith("blob:")); + assert.ok(urls.dry.startsWith("blob:")); + assert.notEqual(urls.dry, ""); +}); + +test("original and denoised unavailable copy exists in every UI language", () => { + for (const key of ["micTestOriginalUnavailable", "micTestDenoisedUnavailable"] as const) { + const values = (["zh", "en", "de", "ru", "ja"] as const).map(language => webClientTranslations[language][key]); + assert.ok(values.every(value => typeof value === "string" && value.length > 0), key); + assert.equal(new Set(values).size, 5, key); + } +}); diff --git a/web/src/voice/microphone-test.ts b/web/src/voice/microphone-test.ts index 7dc2d68..dced7e0 100644 --- a/web/src/voice/microphone-test.ts +++ b/web/src/voice/microphone-test.ts @@ -1,101 +1,258 @@ +export interface MicrophoneTestStreams { + /** Raw pre-denoise stream (graph dry tap, or a raw getUserMedia stream). */ + dry: MediaStream; + /** Graph output that is actually sent to the room. */ + processed: MediaStream; +} + interface MicrophoneTestOptions { - prepare(): Promise; + prepare(): Promise; onActive(active: boolean): void; onUrl(url: string): void; + onDryUrl(url: string): void; onStopped(): void; onError(error: unknown): void; } -interface Recording { - recorder: MediaRecorder | null; - timer: number | null; +type RecordingKind = "dry" | "processed"; + +interface RecorderSlot { + kind: RecordingKind; + recorder: MediaRecorder; chunks: Blob[]; stopped: boolean; + release(): void; +} + +interface Recording { + slots: RecorderSlot[]; + timer: number | null; + stopped: boolean; + inactive: boolean; +} + +export const MICROPHONE_TEST_DURATION_MS = 5_000; + + +function scheduleTimeout(callback: () => void, ms: number): number { + const host = typeof window !== "undefined" ? window : globalThis; + return host.setTimeout(callback, ms) as unknown as number; +} + +function cancelTimeout(timer: number): void { + const host = typeof window !== "undefined" ? window : globalThis; + host.clearTimeout(timer); +} + + +export type MicTestPlaybackVariant = "dry" | "processed"; + +export function micTestPlaybackSource( + variant: MicTestPlaybackVariant, + urls: { processed: string; dry: string }, +): { + src: string; + missing: boolean; + missingKey: "micTestOriginalUnavailable" | "micTestDenoisedUnavailable"; +} { + // Each tab shows only its own take. Falling back to the other URL would + // hide a missing recording by swapping in the wrong audio. + const src = variant === "dry" ? urls.dry : urls.processed; + return { + src, + missing: !src, + missingKey: variant === "dry" ? "micTestOriginalUnavailable" : "micTestDenoisedUnavailable", + }; +} + +function preferredRecorderOptions(): MediaRecorderOptions | undefined { + if (typeof MediaRecorder === "undefined" || typeof MediaRecorder.isTypeSupported !== "function") return undefined; + for (const mimeType of ["audio/webm;codecs=opus", "audio/webm", "audio/mp4"]) { + try { + if (MediaRecorder.isTypeSupported(mimeType)) return { mimeType }; + } catch { /* some stubs throw */ } + } + return undefined; +} + +function cloneForRecording(stream: MediaStream): { stream: MediaStream; release(): void } { + const cloned = typeof stream.clone === "function" ? stream.clone() : stream; + const owns = cloned !== stream; + return { + stream: cloned, + release() { + if (!owns) return; + for (const track of cloned.getTracks()) { + try { track.stop(); } catch { /* already ended */ } + } + }, + }; } // Capture belongs to the caller. This controller owns only the test operation, -// recorder, deadline and playback URL, including results queued after stop(). +// recorders, deadline and both playback URLs, including results queued after stop(). export function createMicrophoneTest(options: MicrophoneTestOptions) { let current: Recording | null = null; - let url = ""; + const urls: Record = { dry: "", processed: "" }; - function clearUrl(): void { + function clearUrl(kind: RecordingKind): void { + const url = urls[kind]; if (url) URL.revokeObjectURL(url); - url = ""; - options.onUrl(""); + urls[kind] = ""; + if (kind === "dry") options.onDryUrl(""); + else options.onUrl(""); + } + + function clearUrls(): void { + clearUrl("dry"); + clearUrl("processed"); + } + + function markInactive(recording: Recording): void { + if (recording.timer !== null) cancelTimeout(recording.timer); + recording.timer = null; + if (recording.inactive) return; + recording.inactive = true; + options.onActive(false); } function finishCapture(recording: Recording): void { - if (recording.timer !== null) window.clearTimeout(recording.timer); - recording.timer = null; + markInactive(recording); if (recording.stopped) return; recording.stopped = true; - options.onActive(false); options.onStopped(); } + function releaseSlots(recording: Recording): void { + for (const slot of recording.slots) { + if (slot.recorder.state !== "inactive") { + try { slot.recorder.stop(); } catch { /* already ended */ } + } + slot.release(); + slot.chunks.length = 0; + } + recording.slots.length = 0; + } + function dispose(): void { const recording = current; current = null; if (recording) { finishCapture(recording); - if (recording.recorder?.state !== "inactive") { - try { recording.recorder?.stop(); } catch { /* already ended */ } - } - recording.chunks.length = 0; + releaseSlots(recording); } - clearUrl(); + clearUrls(); } function stop(): void { const recording = current; if (!recording) return; // A pending permission or device enumeration must not create a recorder. - if (!recording.recorder) current = null; - finishCapture(recording); - if (recording.recorder?.state !== "inactive") { - try { recording.recorder?.stop(); } - catch (error) { dispose(); options.onError(error); } + if (!recording.slots.length) { + current = null; + finishCapture(recording); + return; } + // Stop recorders first, while source tracks are still live. Releasing the + // standalone microphone is deferred until finalizeSlot so the last chunk + // can flush. Active is cleared immediately so the UI can leave the + // recording state. + markInactive(recording); + for (const slot of recording.slots) { + if (slot.recorder.state === "inactive") continue; + try { + if (typeof slot.recorder.requestData === "function" && slot.recorder.state === "recording") { + try { slot.recorder.requestData(); } catch { /* optional flush */ } + } + slot.recorder.stop(); + } catch (error) { + dispose(); + options.onError(error); + return; + } + } + } + + function publishSlot(candidate: RecorderSlot): void { + if (!candidate.chunks.length) { + if (candidate.kind === "dry") options.onDryUrl(""); + else options.onUrl(""); + return; + } + try { + const url = URL.createObjectURL(new Blob(candidate.chunks, { type: candidate.recorder.mimeType || "audio/webm" })); + clearUrl(candidate.kind); + urls[candidate.kind] = url; + if (candidate.kind === "dry") options.onDryUrl(url); + else options.onUrl(url); + } catch (error) { options.onError(error); } + candidate.chunks.length = 0; + } + + function finalizeSlot(recording: Recording, slot: RecorderSlot): void { + slot.stopped = true; + if (current !== recording) { + slot.release(); + return; + } + // Wait for every recorder's onstop. `state === "inactive"` only means + // stop() was called; the last dataavailable may not have arrived yet. + if (!recording.slots.every(candidate => candidate.stopped)) return; + current = null; + finishCapture(recording); + for (const candidate of recording.slots) publishSlot(candidate); + for (const candidate of recording.slots) candidate.release(); + } + + function armDeadline(recording: Recording): void { + if (recording.timer !== null || recording.inactive) return; + recording.timer = scheduleTimeout(() => { + if (current === recording) stop(); + }, MICROPHONE_TEST_DURATION_MS); } async function start(): Promise { dispose(); - const recording: Recording = { recorder: null, timer: null, chunks: [], stopped: false }; + const recording: Recording = { slots: [], timer: null, stopped: false, inactive: false }; current = recording; options.onActive(true); try { - const stream = await options.prepare(); + const streams = await options.prepare(); if (current !== recording) return; // Keep the existing level-meter-only test on browsers without recording. - if (typeof MediaRecorder === "undefined" || !stream) return; - const recorder = new MediaRecorder(stream); - recording.recorder = recorder; - recorder.ondataavailable = event => { - if (current === recording && event.data.size) recording.chunks.push(event.data); - }; - recorder.onstop = () => { - if (current !== recording) return; - current = null; - finishCapture(recording); + if (typeof MediaRecorder === "undefined" || !streams) return; + let startError: unknown = null; + const optionsForRecorder = preferredRecorderOptions(); + for (const kind of ["processed", "dry"] as const) { + const cloned = cloneForRecording(streams[kind]); try { - if (recording.chunks.length) { - clearUrl(); - url = URL.createObjectURL(new Blob(recording.chunks, { type: recorder.mimeType || "audio/webm" })); - options.onUrl(url); - } - } catch (error) { options.onError(error); } - recording.chunks.length = 0; - }; - recorder.onerror = event => { - if (current !== recording) return; - dispose(); - options.onError("error" in event ? event.error : new Error("Microphone recording failed")); - }; - recorder.start(); - recording.timer = window.setTimeout(() => { - if (current === recording) stop(); - }, 5_000); + const recorder = optionsForRecorder + ? new MediaRecorder(cloned.stream, optionsForRecorder) + : new MediaRecorder(cloned.stream); + const slot: RecorderSlot = { kind, recorder, chunks: [], stopped: false, release: cloned.release }; + recorder.ondataavailable = event => { + if (current === recording && event.data?.size) slot.chunks.push(event.data); + }; + recorder.onstop = () => finalizeSlot(recording, slot); + recorder.onerror = event => { + if (current !== recording) return; + dispose(); + options.onError("error" in event ? event.error : new Error("Microphone recording failed")); + }; + recorder.start(1_000); + recording.slots.push(slot); + } catch (error) { + // One path failing must not disable the other; A/B degrades to mono. + cloned.release(); + startError ??= error; + } + } + // Nothing could record: surface the recorder failure, not a silent test. + if (!recording.slots.length) { + if (startError) throw startError; + return; + } + armDeadline(recording); } catch (error) { if (current !== recording) return; dispose(); diff --git a/web/src/voice/noise-suppression.test.ts b/web/src/voice/noise-suppression.test.ts new file mode 100644 index 0000000..d938e13 --- /dev/null +++ b/web/src/voice/noise-suppression.test.ts @@ -0,0 +1,75 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + denoiseLatencyMs, + legacyNoiseSuppressionLevel, + migrateStoredNoiseSuppression, + resolveDenoisePlan, +} from "./noise-suppression.js"; + +test("resolveDenoisePlan keeps off and browser modes explicit", () => { + assert.deepEqual( + resolveDenoisePlan({ mode: "off", sampleRate: 48_000, workletSupported: true }), + { mode: "off", engine: "off", requestBrowserNs: false, fallback: null }, + ); + assert.deepEqual( + resolveDenoisePlan({ mode: "browser", sampleRate: 48_000, workletSupported: true }), + { mode: "browser", engine: "browser", requestBrowserNs: true, fallback: null }, + ); +}); + +test("model modes disable browser denoising only when they can run", () => { + assert.deepEqual( + resolveDenoisePlan({ mode: "gtcrn", sampleRate: 48_000, workletSupported: true }), + { mode: "gtcrn", engine: "gtcrn", requestBrowserNs: false, fallback: null }, + ); + assert.deepEqual( + resolveDenoisePlan({ mode: "rnnoise", sampleRate: 48_000, workletSupported: true }), + { mode: "rnnoise", engine: "rnnoise", requestBrowserNs: false, fallback: null }, + ); +}); + +test("model modes fall back to browser denoising without Worklet support", () => { + assert.deepEqual( + resolveDenoisePlan({ mode: "gtcrn", sampleRate: 48_000, workletSupported: false }), + { mode: "gtcrn", engine: "browser", requestBrowserNs: true, fallback: "no-worklet" }, + ); +}); + +test("both neural models require a 48 kHz context", () => { + for (const mode of ["gtcrn", "rnnoise"] as const) { + assert.deepEqual( + resolveDenoisePlan({ mode, sampleRate: 44_100, workletSupported: true }), + { mode, engine: "browser", requestBrowserNs: true, fallback: "sample-rate" }, + ); + } +}); + +test("unknown modes default to GTCRN rather than silently turning denoising off", () => { + assert.equal(resolveDenoisePlan({ mode: "nope" as never, sampleRate: 48_000, workletSupported: true }).engine, "gtcrn"); +}); + +test("stored preferences migrate from mode, then level, then boolean", () => { + assert.equal(migrateStoredNoiseSuppression({ mode: "rnnoise", level: "off" }), "rnnoise"); + assert.equal(migrateStoredNoiseSuppression({ level: "off" }), "off"); + assert.equal(migrateStoredNoiseSuppression({ level: "standard" }), "browser"); + assert.equal(migrateStoredNoiseSuppression({ level: "strong" }), "gtcrn"); + assert.equal(migrateStoredNoiseSuppression({ enabled: false }), "off"); + assert.equal(migrateStoredNoiseSuppression({ enabled: true }), "gtcrn"); + assert.equal(migrateStoredNoiseSuppression({}), "gtcrn"); + assert.equal(migrateStoredNoiseSuppression({ mode: "bogus", level: "bogus" }), "gtcrn"); +}); + +test("legacy level mirrors the new mode", () => { + assert.equal(legacyNoiseSuppressionLevel("off"), "off"); + assert.equal(legacyNoiseSuppressionLevel("browser"), "standard"); + assert.equal(legacyNoiseSuppressionLevel("rnnoise"), "strong"); + assert.equal(legacyNoiseSuppressionLevel("gtcrn"), "strong"); +}); + +test("latency estimates reflect one model frame", () => { + assert.equal(denoiseLatencyMs("gtcrn"), 16); + assert.equal(denoiseLatencyMs("rnnoise"), 10); + assert.equal(denoiseLatencyMs("browser"), 0); + assert.equal(denoiseLatencyMs("off"), 0); +}); diff --git a/web/src/voice/noise-suppression.ts b/web/src/voice/noise-suppression.ts new file mode 100644 index 0000000..3368d4c --- /dev/null +++ b/web/src/voice/noise-suppression.ts @@ -0,0 +1,82 @@ +export type NoiseSuppressionMode = "off" | "browser" | "rnnoise" | "gtcrn"; +export type DenoiseEngine = NoiseSuppressionMode; +export type DenoiseFallback = "no-worklet" | "sample-rate" | "load-failed" | null; +export type StoredNoiseSuppressionLevel = "off" | "standard" | "strong"; + +export interface DenoisePlan { + mode: NoiseSuppressionMode; + engine: DenoiseEngine; + /** Whether getUserMedia should ask the browser to denoise the raw track. */ + requestBrowserNs: boolean; + /** Why the requested model could not run. Visible in audio settings. */ + fallback: DenoiseFallback; +} + +export interface ResolveDenoisePlanOptions { + mode: NoiseSuppressionMode; + sampleRate: number; + workletSupported: boolean; +} + +export interface StoredNoiseSuppression { + mode?: unknown; + level?: unknown; + enabled?: unknown; +} + +/** Both neural engines are trained for 48 kHz contexts; resampling is not free. */ +export const DENOISE_SAMPLE_RATE = 48_000; + +export function isNoiseSuppressionMode(value: unknown): value is NoiseSuppressionMode { + return value === "off" || value === "browser" || value === "rnnoise" || value === "gtcrn"; +} + +export function isNeuralDenoiseEngine(engine: DenoiseEngine): engine is "rnnoise" | "gtcrn" { + return engine === "rnnoise" || engine === "gtcrn"; +} + +/** GTCRN uses 768-sample frames, RNNoise 480; both are one-frame delays. */ +export function denoiseLatencyMs(engine: DenoiseEngine): number { + if (engine === "gtcrn") return 16; + if (engine === "rnnoise") return 10; + return 0; +} + +/** + * Resolve a requested mode into the engine that can actually run. + * Model-based engines are exclusive with the browser noise suppressor: + * stacking the two damages speech before the model sees it. + */ +export function resolveDenoisePlan({ mode, sampleRate, workletSupported }: ResolveDenoisePlanOptions): DenoisePlan { + const requested = isNoiseSuppressionMode(mode) ? mode : "gtcrn"; + if (requested === "off") return { mode: requested, engine: "off", requestBrowserNs: false, fallback: null }; + if (requested === "browser") return { mode: requested, engine: "browser", requestBrowserNs: true, fallback: null }; + if (!workletSupported) { + return { mode: requested, engine: "browser", requestBrowserNs: true, fallback: "no-worklet" }; + } + if (sampleRate !== DENOISE_SAMPLE_RATE) { + return { mode: requested, engine: "browser", requestBrowserNs: true, fallback: "sample-rate" }; + } + return { mode: requested, engine: requested, requestBrowserNs: false, fallback: null }; +} + +/** + * Read a stored preference. New installs have `mode`; older ones only have + * `level` (off/standard/strong) or the boolean `enabled`. A stored "strong" + * migrates to GTCRN because that is the quality tier this build ships. + */ +export function migrateStoredNoiseSuppression(stored: StoredNoiseSuppression): NoiseSuppressionMode { + if (isNoiseSuppressionMode(stored.mode)) return stored.mode; + if (stored.level === "off" || stored.level === "standard" || stored.level === "strong") { + return stored.level === "off" ? "off" : stored.level === "standard" ? "browser" : "gtcrn"; + } + if (typeof stored.enabled === "boolean") return stored.enabled ? "gtcrn" : "off"; + return "gtcrn"; +} + +/** Mirror the new mode into the legacy three-value field for older builds. */ +export function legacyNoiseSuppressionLevel(mode: NoiseSuppressionMode): StoredNoiseSuppressionLevel { + if (mode === "off") return "off"; + if (mode === "browser") return "standard"; + return "strong"; +} diff --git a/web/src/voice/opus-uplink.ts b/web/src/voice/opus-uplink.ts index 0289c7b..5dc5cf2 100644 --- a/web/src/voice/opus-uplink.ts +++ b/web/src/voice/opus-uplink.ts @@ -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, }, }; diff --git a/web/src/voice/plc.ts b/web/src/voice/plc.ts new file mode 100644 index 0000000..41ef7a4 --- /dev/null +++ b/web/src/voice/plc.ts @@ -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; +} diff --git a/web/src/voice/remote-playback.ts b/web/src/voice/remote-playback.ts index a179701..c289a5e 100644 --- a/web/src/voice/remote-playback.ts +++ b/web/src/voice/remote-playback.ts @@ -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; + /** 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(); @@ -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, }; } diff --git a/web/src/voice/webrtc-transport.ts b/web/src/voice/webrtc-transport.ts index f530cab..1719b0c 100644 --- a/web/src/voice/webrtc-transport.ts +++ b/web/src/voice/webrtc-transport.ts @@ -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 { + async function waitForIce(record: Attempt, peer: RTCPeerConnection, relay: boolean): Promise { if (peer.iceGatheringState === "complete") return; await new Promise(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 { 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"); } } diff --git a/web/test/admin-api.integration.test.ts b/web/test/admin-api.integration.test.ts index 92fb0b3..e0de6bd 100644 --- a/web/test/admin-api.integration.test.ts +++ b/web/test/admin-api.integration.test.ts @@ -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", diff --git a/web/test/jitter-buffer.test.ts b/web/test/jitter-buffer.test.ts index aadc3c8..76ea727 100644 --- a/web/test/jitter-buffer.test.ts +++ b/web/test/jitter-buffer.test.ts @@ -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); }); diff --git a/web/test/remote-playback.test.ts b/web/test/remote-playback.test.ts index babff41..c44d6c9 100644 --- a/web/test/remote-playback.test.ts +++ b/web/test/remote-playback.test.ts @@ -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); }); diff --git a/web/test/voice-session.test.mjs b/web/test/voice-session.test.mjs index 5ed9341..cd4a066 100644 --- a/web/test/voice-session.test.mjs +++ b/web/test/voice-session.test.mjs @@ -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. @@ -28,6 +29,12 @@ class TestTrack extends EventTarget { readyState = "live"; stopped = 0; stop() { this.stopped++; this.readyState = "ended"; } + clone() { + const copy = new TestTrack(); + copy.kind = this.kind; + copy.readyState = this.readyState; + return copy; + } getSettings() { return { displaySurface: "monitor", width: 1920, height: 1080, frameRate: 60 }; } async applyConstraints() {} } @@ -63,10 +70,20 @@ class RecorderStub { state = "inactive"; mimeType = "audio/webm"; stops = 0; + finished = false; constructor(stream) { this.stream = stream; RecorderStub.instances.push(this); } start() { if (RecorderStub.failStart) throw new Error("Recorder start failed"); this.state = "recording"; } stop() { this.stops++; this.state = "inactive"; } - finish() { this.state = "inactive"; this.ondataavailable?.({ data: new Blob(["audio"]) }); this.onstop?.(); } + finish() { + // A/B tests start two recorders; finishing simulates both stopping together. + for (const recorder of RecorderStub.instances) { + if (recorder.finished) continue; + recorder.finished = true; + recorder.state = "inactive"; + recorder.ondataavailable?.({ data: new Blob(["audio"]) }); + recorder.onstop?.(); + } + } } function decodedChunk() { return { sampleRate: 48000, numberOfChannels: 1, numberOfFrames: 960, closed: 0, copyTo() {}, close() { this.closed++; } }; @@ -129,7 +146,18 @@ class AudioContextStub extends EventTarget { function microphoneStream() { const track = new TestTrack(); track.kind = "audio"; - return { track, getTracks: () => [track], getVideoTracks: () => [], getAudioTracks: () => [track] }; + const stream = { + track, + getTracks: () => [track], + getVideoTracks: () => [], + getAudioTracks: () => [track], + clone() { + const copy = microphoneStream(); + copy.track.kind = "audio"; + return copy; + }, + }; + return stream; } function displayStream() { @@ -1329,7 +1357,9 @@ test("failed initial WebRTC input allocation releases partial nodes and restores socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: true }); await nextTurn(); assert.equal(TestPeer.instances[0].connectionState, "closed"); - assert.equal(AudioContextStub.destinations[1].stream.track.readyState, "ended"); + const destinationStates = AudioContextStub.destinations.map(node => node.stream.track.readyState); + assert.ok(destinationStates.includes("ended"), "failed WebRTC mix destination is released"); + assert.ok(destinationStates.filter(state => state === "live").length >= 2, "dry and processed capture taps stay live for PCM fallback"); assert.ok(AudioContextStub.mediaSources[1].disconnects > 0); assert.equal(voice.state.microphoneErrorCode, ""); assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED"); @@ -1993,6 +2023,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 +2272,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); @@ -2298,7 +2360,7 @@ test("a replacement microphone test stops the old recorder and ignores its late const currentUrl = voice.testAudioUrl.value; old.finish(); assert.equal(voice.testAudioUrl.value, currentUrl); - assert.equal(created.length, 1); + assert.equal(created.length, 2, "denoised and dry takes each produce one URL"); }); test("an old microphone test permission failure cannot stop a new recording", async () => { @@ -2338,9 +2400,11 @@ test("a naturally finished microphone recording clears active state and standalo assert.equal(voice.microphoneTestActive.value, false); assert.equal(recorder.stream.track.readyState, "ended"); assert.equal(voice.testAudioUrl.value, "blob:finished"); + assert.equal(voice.testAudioDryUrl.value, "blob:finished"); voice.disconnect(); - assert.deepEqual(revoked, ["blob:finished"]); + assert.deepEqual(revoked, ["blob:finished", "blob:finished"]); assert.equal(voice.testAudioUrl.value, ""); + assert.equal(voice.testAudioDryUrl.value, ""); }); test("recorder startup failure releases standalone microphone capture", async () => { @@ -2358,10 +2422,13 @@ test("stopping a connected microphone test publishes its recording without stopp await nextTurn(); await voice.startMicrophoneTest(); const recorder = RecorderStub.instances.at(-1); + const liveTracks = AudioContextStub.mediaSources.map(node => node.stream.track); + assert.ok(liveTracks.length, "expected a live capture graph"); voice.stopMicrophoneTest(); recorder.finish(); assert.equal(voice.testAudioUrl.value, "blob:connected"); - assert.equal(recorder.stream.track.readyState, "live"); + assert.equal(voice.testAudioDryUrl.value, "blob:connected"); + assert.ok(liveTracks.every(track => track.readyState === "live"), "room capture must stay live"); assert.equal(voice.state.connected, true); }); @@ -2547,10 +2614,38 @@ test("a failed noise suppression change restores its setting and preserves WebRT await voice.setNoiseSuppressionEnabled(false); assert.notEqual(peer.connectionState, "closed"); assert.equal(voice.noiseSuppressionEnabled.value, true); + assert.equal(voice.noiseSuppressionMode.value, "gtcrn", "a failed change restores the committed engine"); assert.equal(initial.track.readyState, "live"); assert.notEqual(voice.state.microphoneErrorCode, ""); }); +test("the default denoise mode reports a browser fallback when AudioWorklet is unavailable", async () => { + const getUserMedia = navigator.mediaDevices.getUserMedia; + let lastConstraints; + navigator.mediaDevices.getUserMedia = async constraints => { lastConstraints = constraints; return getUserMedia(constraints); }; + await connectWebRtc(); + assert.equal(voice.noiseSuppressionMode.value, "gtcrn"); + assert.equal(voice.microphoneProcessing.requestedEngine, "gtcrn"); + assert.equal(voice.microphoneProcessing.engine, "browser"); + assert.equal(voice.microphoneProcessing.fallback, "no-worklet"); + assert.equal(lastConstraints.audio.noiseSuppression, true, "the fallback must still ask for browser denoising"); +}); + +test("browser and off modes request the matching native constraint without a model", async () => { + const getUserMedia = navigator.mediaDevices.getUserMedia; + let lastConstraints; + navigator.mediaDevices.getUserMedia = async constraints => { lastConstraints = constraints; return getUserMedia(constraints); }; + await connectWebRtc(); + await voice.setNoiseSuppressionMode("browser"); + assert.equal(lastConstraints.audio.noiseSuppression, true); + assert.equal(voice.microphoneProcessing.engine, "browser"); + assert.equal(voice.microphoneProcessing.fallback, null); + await voice.setNoiseSuppressionMode("off"); + assert.equal(lastConstraints.audio.noiseSuppression, false); + assert.equal(voice.microphoneProcessing.engine, "off"); + assert.equal(voice.noiseSuppressionEnabled.value, false); +}); + test("changing processing during an input switch commits the device actually acquired", async () => { navigator.mediaDevices.enumerateDevices = async () => availableDevices; await voice.ensureMicrophone(); diff --git a/web/tsconfig.json b/web/tsconfig.json index d4c3d07..7b2da8f 100644 --- a/web/tsconfig.json +++ b/web/tsconfig.json @@ -15,5 +15,6 @@ "@/*": ["./src/*"] } }, - "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.vue"] + "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.vue"], + "exclude": ["src/**/*.test.ts"] }