mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-11-30 18:42:49 +08:00
feat(voice): support Cloudflare Tunnel deployments and WebRTC fallback
Route page and signaling traffic through Cloudflare Tunnel while sending WebRTC media over direct UDP, with optional TURN REST as a fallback. When WebRTC was already offered and then fails, stay in the current session, automatically resume compatibility audio, and keep a Reconnect WebRTC control. A reconnect retries WebRTC only, leaves compatibility running until it succeeds, and stays on compatibility if it fails again. Database schema 14 adds nullable voice override columns and is a one-way boundary: older binaries reject this database. This change is for review, not a production rollout.
This commit is contained in:
1 parent
9a12e2ee7b
commit
b6e7b1e4da
68 files changed
+3525
-189
No files matched your search
@@ -82,6 +82,7 @@ docker compose up -d
|
||||
1. 打开 `http://127.0.0.1:3040/admin`,使用 `admin` / `admin` 登录并设置至少 12 位新密码。Open the console, sign in and replace the default password.
|
||||
2. 配置 TeamSpeak 目标和访问模式;公网使用 HTTPS。Set the TeamSpeak target and access mode; use HTTPS for public access.
|
||||
3. 启用 WebRTC 时放行配置的 UDP 范围,默认 `40000–40099`。Allow the configured UDP range when enabling WebRTC.
|
||||
4. Cloudflare Tunnel 或受限网络可在管理台“服务器 → 语音”配置 TURN 后备、语音模式和自适应音频,保存后对新的语音连接生效。Configure TURN fallback, voice mode, and adaptive audio under Admin → Voice; changes apply to new voice connections after saving.
|
||||
|
||||
数据保存在 `webspeak-data` volume,升级时保留它。Docker 控制台只能检查版本;升级请在宿主机执行 `docker compose pull && docker compose up -d`,且不要执行 `docker compose down -v`。以上 Compose 使用主机网络;Windows 服务端可选择[发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。完整说明:[中文部署指南](./docs/README.zh-CN.md#deployment) · [English deployment guide](./docs/README.en.md#deployment)。
|
||||
|
||||
@@ -96,6 +97,8 @@ Data persists in the `webspeak-data` volume. On Docker, the console only checks
|
||||
- [Deutsch](./docs/README.de.md)
|
||||
- [Русский](./docs/README.ru.md)
|
||||
- [日本語](./docs/README.ja.md)
|
||||
- [Cloudflare Tunnel 语音部署与排障](./docs/CLOUDFLARE_TUNNEL_VOICE.md)
|
||||
- [语音兼容性说明 / Voice compatibility notes](./docs/VOICE_FIX_REPORT.md)
|
||||
- [皮肤开发指南 / Skin development guide](./docs/SKIN_DEVELOPMENT.md)
|
||||
- [皮肤开发 Agent Skill / Skin Development Agent Skill](./.agents/skills/webspeak-skin-development/SKILL.md)
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
# Cloudflare Tunnel for WebSpeak
|
||||
|
||||
Cloudflare Tunnel publishes the WebSpeak **HTTPS/WSS** entry without opening a
|
||||
public inbound port. It does **not** carry WebRTC media UDP, and it does not
|
||||
make the gateway's `40000–40099/UDP` range reachable.
|
||||
|
||||
## Setup
|
||||
|
||||
1. Create a tunnel in the Cloudflare dashboard and copy its UUID and
|
||||
credentials JSON.
|
||||
2. Copy `config.yml.example` to `config.yml` and replace the UUID and
|
||||
hostname. Rename the downloaded credentials file to
|
||||
`REPLACE_WITH_TUNNEL_UUID.json`, or update the credentials path and Compose
|
||||
mount to match its actual name. Point `service` at the WebSpeak HTTP listener
|
||||
(`3040` by default).
|
||||
3. Run cloudflared on the host (recommended on Windows/macOS):
|
||||
|
||||
```bash
|
||||
cloudflared tunnel --config config.yml run
|
||||
```
|
||||
|
||||
On Linux, `docker compose up -d` in this directory can run it in host mode.
|
||||
4. In WebSpeak administration, set **Public media address** to the gateway's
|
||||
public IP (for example `192.0.2.10`), not the Cloudflare hostname.
|
||||
Allow `40000–40099/UDP` on the host firewall and security group.
|
||||
5. Keep `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all` so browsers try direct UDP
|
||||
first. `WEBSPEAK_VOICE_PROFILE=auto` is the default: requests from a trusted
|
||||
Cloudflare hop use the adaptive audio path, while other requests keep the
|
||||
legacy path. The default trusted proxy list contains loopback only; if
|
||||
cloudflared connects from another address, add that IP/CIDR to
|
||||
`WEBSPEAK_TRUSTED_PROXIES`. Headers injected by a direct untrusted client are
|
||||
ignored. Configure TURN only as the fallback for mobile networks or
|
||||
UDP-blocked clients; see `deploy/coturn`.
|
||||
6. Opus over WebSocket is opt-in. It requires an adaptive profile and either
|
||||
the Admin → Voice setting or `WEBSPEAK_VOICE_OPUS_WS=1`; without it the
|
||||
browser uses PCM.
|
||||
|
||||
## Why not use the Cloudflare hostname as the media address?
|
||||
|
||||
A Cloudflare-proxied hostname resolves to Cloudflare edge addresses. Those
|
||||
edges do not forward the gateway's UDP media ports, so using them as ICE
|
||||
candidates produces a path that looks configured but cannot carry audio.
|
||||
WebSpeak therefore no longer infers the request `Host` as an ICE address when
|
||||
the request arrives through a trusted Cloudflare hop and no media host was
|
||||
configured. Without a public media address or TURN, the server reports
|
||||
`NO_MEDIA_PATH` and, because WebRTC was not advertised, the browser uses the
|
||||
compatibility transport. If an advertised WebRTC connection later fails, the
|
||||
browser stays in the session with `WEBRTC_FAILED` and offers WebRTC reconnect;
|
||||
it does not silently switch to compatibility transport.
|
||||
|
||||
## Verify
|
||||
|
||||
- `curl -I https://voice.example.com` succeeds through the tunnel.
|
||||
- `chrome://webrtc-internals` shows host/srflx candidates to the public IP and,
|
||||
when UDP is available, a direct selected pair.
|
||||
- If the selected pair is `relay`, confirm TURN is reachable and that direct
|
||||
UDP is actually blocked; do not switch the global policy to `relay` just
|
||||
because the page is behind a Tunnel.
|
||||
|
||||
For the full voice rollout and rollback notes, see
|
||||
[`docs/CLOUDFLARE_TUNNEL_VOICE.md`](../../docs/CLOUDFLARE_TUNNEL_VOICE.md).
|
||||
|
||||
This template has not been exercised end-to-end with a live coturn/Tunnel
|
||||
deployment. Browser Opus fallback, especially on Safari and Firefox, also
|
||||
requires device testing.
|
||||
@@ -0,0 +1,10 @@
|
||||
tunnel: REPLACE_WITH_TUNNEL_UUID
|
||||
credentials-file: /etc/cloudflared/REPLACE_WITH_TUNNEL_UUID.json
|
||||
|
||||
ingress:
|
||||
- hostname: voice.example.com
|
||||
service: http://127.0.0.1:3040
|
||||
originRequest:
|
||||
connectTimeout: 30s
|
||||
noTLSVerify: false
|
||||
- service: http_status:404
|
||||
@@ -0,0 +1,12 @@
|
||||
services:
|
||||
cloudflared:
|
||||
image: cloudflare/cloudflared:latest
|
||||
container_name: webspeak-cloudflared
|
||||
restart: unless-stopped
|
||||
# Linux only. On Docker Desktop for Windows/macOS, run cloudflared on the
|
||||
# host and use http://127.0.0.1:3040 instead.
|
||||
network_mode: host
|
||||
command: tunnel --config /etc/cloudflared/config.yml run
|
||||
volumes:
|
||||
- ./config.yml:/etc/cloudflared/config.yml:ro
|
||||
- ./REPLACE_WITH_TUNNEL_UUID.json:/etc/cloudflared/REPLACE_WITH_TUNNEL_UUID.json:ro
|
||||
@@ -0,0 +1,8 @@
|
||||
# Copy to .env and replace the secret. Keep this file out of git.
|
||||
TURN_SECRET=replace-with-at-least-32-random-bytes
|
||||
TURN_REALM=webspeak
|
||||
# Public IPv4 of this host. Behind 1:1 NAT, use PUBLIC/PRIVATE, e.g.
|
||||
# 192.0.2.10/10.0.0.5
|
||||
TURN_EXTERNAL_IP=203.0.113.10
|
||||
TURN_MIN_PORT=49160
|
||||
TURN_MAX_PORT=49200
|
||||
@@ -0,0 +1,82 @@
|
||||
# WebSpeak TURN (coturn) deployment
|
||||
|
||||
TURN is a **fallback** for voice media when a browser cannot reach the WebSpeak
|
||||
gateway over UDP, for example on mobile networks or networks that block UDP.
|
||||
It is not required for the normal direct UDP path.
|
||||
|
||||
## 1. Configure
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# Generate a secret and put the same value in WEBSPEAK_TURN_REST_SECRET:
|
||||
openssl rand -hex 32
|
||||
```
|
||||
|
||||
Set `TURN_EXTERNAL_IP` to the host's public IPv4. If the host is behind 1:1
|
||||
NAT, use `PUBLIC/PRIVATE` (for example `203.0.113.10/10.0.0.5`). The relay
|
||||
range `49160–49200/UDP` is separate from WebSpeak's WebRTC range
|
||||
`40000–40099/UDP`; do not reuse the WebRTC range.
|
||||
|
||||
## 2. Start and expose
|
||||
|
||||
```bash
|
||||
docker compose --env-file .env up -d
|
||||
docker compose logs -f coturn
|
||||
```
|
||||
|
||||
Allow inbound:
|
||||
|
||||
- `3478/UDP` and `3478/TCP` for `turn:`
|
||||
- `49160–49200/UDP` for relayed media
|
||||
- `5349/TCP` only if you add TLS certificates for `turns:`
|
||||
|
||||
Do **not** put the TURN relay range behind Cloudflare Tunnel; Cloudflare Tunnel
|
||||
does not carry this UDP traffic.
|
||||
|
||||
## 3. Connect WebSpeak
|
||||
|
||||
Use the same secret as coturn's `static-auth-secret`:
|
||||
|
||||
```bash
|
||||
WEBSPEAK_TURN_REST_URLS='turn:turn.example.com:3478?transport=udp,turn:turn.example.com:3478?transport=tcp'
|
||||
WEBSPEAK_TURN_REST_SECRET='<same value as TURN_SECRET>'
|
||||
WEBSPEAK_TURN_REST_TTL_SECONDS=21600
|
||||
# Keep direct UDP first. Use "relay" only where UDP is known to be blocked.
|
||||
WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all
|
||||
# Auto keeps direct and untrusted-proxy traffic on the legacy audio path.
|
||||
WEBSPEAK_VOICE_PROFILE=auto
|
||||
```
|
||||
|
||||
TURN does not require Opus; `WEBSPEAK_VOICE_OPUS_WS` remains off by default.
|
||||
|
||||
`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`.
|
||||
|
||||
## 4. Verify
|
||||
|
||||
From a network that blocks direct UDP, open the voice page and check:
|
||||
|
||||
- `chrome://webrtc-internals` (Chrome/Edge) or `about:webrtc` (Firefox)
|
||||
- The selected candidate pair should become `relay` only when direct UDP fails.
|
||||
- `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all` must not be changed to `relay`
|
||||
merely because a Tunnel is in front of HTTPS.
|
||||
|
||||
If TURN succeeds but audio still stutters, check whether the connection's
|
||||
`voiceProfile` is `adaptive`; on a direct or legacy profile the old 80 ms
|
||||
compatibility window is expected. TURN reachability alone does not enable the
|
||||
adaptive jitter buffer.
|
||||
|
||||
## Security notes
|
||||
|
||||
- Keep the secret out of shell history, process listings where possible, and
|
||||
git. Prefer an `.env` file with restrictive permissions.
|
||||
- The compose file denies private, loopback and link-local peer ranges to
|
||||
reduce abuse. If the WebSpeak gateway itself is on a private address, add a
|
||||
narrowly scoped `--allowed-peer-ip` for that address and review the risk.
|
||||
- This template has no TLS listener. Add certificates and a `turns:` URL only
|
||||
when you need TURN over TLS on `5349/TCP`; test certificate renewal.
|
||||
- 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.
|
||||
@@ -0,0 +1,40 @@
|
||||
services:
|
||||
coturn:
|
||||
image: coturn/coturn:4.6.3
|
||||
container_name: webspeak-coturn
|
||||
restart: unless-stopped
|
||||
# Host networking keeps the configured relay UDP range and external-ip
|
||||
# mapping predictable. On Linux, replace it with explicit ports only if
|
||||
# your platform does not support host mode.
|
||||
network_mode: host
|
||||
environment:
|
||||
TURN_SECRET: ${TURN_SECRET:?set TURN_SECRET in .env}
|
||||
TURN_REALM: ${TURN_REALM:-webspeak}
|
||||
TURN_EXTERNAL_IP: ${TURN_EXTERNAL_IP:?set TURN_EXTERNAL_IP in .env}
|
||||
TURN_MIN_PORT: ${TURN_MIN_PORT:-49160}
|
||||
TURN_MAX_PORT: ${TURN_MAX_PORT:-49200}
|
||||
command:
|
||||
- -n
|
||||
- --log-file=stdout
|
||||
- --no-cli
|
||||
- --fingerprint
|
||||
- --lt-cred-mech
|
||||
- --use-auth-secret
|
||||
- --static-auth-secret=${TURN_SECRET}
|
||||
- --realm=${TURN_REALM}
|
||||
- --external-ip=${TURN_EXTERNAL_IP}
|
||||
- --listening-port=3478
|
||||
- --min-port=${TURN_MIN_PORT}
|
||||
- --max-port=${TURN_MAX_PORT}
|
||||
- --stale-nonce=600
|
||||
- --no-multicast-peers
|
||||
- --denied-peer-ip=0.0.0.0-0.255.255.255
|
||||
- --denied-peer-ip=10.0.0.0-10.255.255.255
|
||||
- --denied-peer-ip=127.0.0.0-127.255.255.255
|
||||
- --denied-peer-ip=169.254.0.0-169.254.255.255
|
||||
- --denied-peer-ip=172.16.0.0-172.31.255.255
|
||||
- --denied-peer-ip=192.168.0.0-192.168.255.255
|
||||
- --denied-peer-ip=::1
|
||||
- --denied-peer-ip=fc00::-fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
|
||||
- --denied-peer-ip=fe80::-febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff
|
||||
- --denied-peer-ip=ff00::-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
|
||||
@@ -0,0 +1,197 @@
|
||||
# Cloudflare Tunnel 下的 WebSpeak 语音
|
||||
|
||||
本文说明“网页/信令走 Cloudflare Tunnel,媒体尽量直连 UDP”的部署方式。
|
||||
核心原则:
|
||||
|
||||
- **WebRTC 优先直连**:浏览器直接向网关公网 IP 的 `40000–40099/UDP` 发包。
|
||||
- **Tunnel 只承载 HTTPS/WSS**:Cloudflare Tunnel 不转发 UDP,不能把
|
||||
Cloudflare 代理域名当作 ICE 媒体地址。
|
||||
- **TURN 只做后备**:手机流量、公司网络或 UDP 被拦时,才让媒体走
|
||||
`turn:`/`turns:`,不默认全程 `relay`。
|
||||
- **CFT 是增量路径**:默认 `WEBSPEAK_VOICE_PROFILE=auto`,非可信 Cloudflare
|
||||
请求继续使用原有的 80ms 固定窗口、裸 1920 字节 PCM 和旧混音参数;只有
|
||||
经过可信 Cloudflare 代理的请求(或显式 `adaptive`)才启用自适应 buffer /
|
||||
pacer / 修正后的 RTP marker。不配置 CFT、TURN 或新变量时,直连部署保持原行为。
|
||||
|
||||
## 兼容性矩阵
|
||||
|
||||
| 部署 | 媒体路径 | 音频 profile | 需要 TURN |
|
||||
| --- | --- | --- | --- |
|
||||
| 直连,无 CFT | 浏览器 → 网关 UDP `40000–40099` | `legacy`(默认) | 否 |
|
||||
| 直连,显式 `PROFILE=adaptive` | 同上,直连优先 | `adaptive` | 否 |
|
||||
| CFT + 显式公网 IP | 浏览器 → 网关 UDP,CF 只走信令 | `adaptive` | 否 |
|
||||
| CFT + 无公网媒体地址 | 无直连;兼容模式或 TURN | `adaptive` | 是(若需要 WebRTC) |
|
||||
| 手机/UDP 被拦 | TURN relay 后备 | `adaptive` | 是 |
|
||||
|
||||
`legacy` 不是“禁用 WebRTC”,它只锁定旧音频时序和旧帧路径;WebRTC、STUN、
|
||||
UDP 端口仍按原配置工作。
|
||||
|
||||
## 1. 管理控制台与部署检查
|
||||
|
||||
### 1.1 管理控制台(推荐)
|
||||
|
||||
管理台“服务器 → 语音”提供与部署相关的全部开关,不再需要仅为 CFT/TURN
|
||||
修改环境变量:
|
||||
|
||||
- **语音模式**:`自动`(推荐,直连走 `legacy`、可信 Cloudflare 代理走
|
||||
`adaptive`)、`兼容模式`、`自适应`。
|
||||
- **兼容模式 Opus**:仅 `adaptive` 生效,默认关闭;浏览器不支持时自动回退
|
||||
PCM。
|
||||
- **自适应 jitter 上限**:80–500 ms,配置自适应缓冲目标的上限;它不是严格的
|
||||
播放前瞻上限,调低也不会恢复旧版超限 `clear()` 行为。
|
||||
- **TURN 后备**:TURN REST URL、共享密钥和凭证有效期。TURN 只在直连 UDP
|
||||
失败后使用,不作为默认路径。
|
||||
|
||||
保存后对**新的语音连接**生效,不需要重启网关。配置持久化在数据库中:控制台
|
||||
非空值覆盖对应环境变量,未配置的字段继续继承环境变量;清空 TURN URL 或在
|
||||
控制台移除密钥会显式停用 TURN。TURN 共享密钥使用网关主密钥加密存储,管理
|
||||
API 只返回“是否已配置”,不会把明文回传浏览器。
|
||||
|
||||
静态 `WEBSPEAK_VOICE_ICE_SERVERS` 以及浏览器/网关的 `transportPolicy` 仍由
|
||||
环境变量控制,控制台刻意不提供“全程 relay”开关,避免误把直连优先改成中继
|
||||
优先;需要排障时再临时设置环境变量并重启。
|
||||
|
||||
Cloudflare 判定只接受来自 `WEBSPEAK_TRUSTED_PROXIES` 中直接相邻代理的
|
||||
`cf-ray`、`cf-connecting-ip` 或包含 `cloudflare` 的 `cdn-loop`。默认只信任
|
||||
本机回环地址;cloudflared 若从其他地址连接,应把其来源 IP/CIDR 加入该变量。
|
||||
直连客户端自行注入这些头不会被当作 Cloudflare,也不会切换到 `adaptive`。
|
||||
|
||||
### 1.2 部署检查清单
|
||||
|
||||
1. 管理台“服务器 → 语音”先选 `自动`,再在“高级参数 → 公网媒体地址”填写网关的**公网 IP**,例如 `192.0.2.10`,不要填 Cloudflare 的代理域名。保存后重新连接。
|
||||
2. 主机防火墙/安全组放行 `40000–40099/UDP`,并确认云厂商安全组也放行。
|
||||
3. 如果网关本身在 NAT 后面,需要把 UDP 端口映射到网关,或给网关一个
|
||||
可直连的公网地址;仅做 TCP 端口映射不够。
|
||||
4. `webrtc_public_host` 为空时,直连部署仍可按请求入口推断;但通过
|
||||
Cloudflare 的请求不会再拿 CF 边缘 `Host` 当 ICE 地址,避免“看起来
|
||||
配置好了、实际没有媒体路径”。Cloudflare 场景请显式填写公网媒体地址。
|
||||
|
||||
## 2. 服务端环境变量
|
||||
|
||||
在启动 WebSpeak 的环境里设置;修改后重启进程,并对新连接生效。控制台已保存
|
||||
的非空语音配置优先于这里的环境变量;控制台留空的字段才继承环境变量。日常
|
||||
CFT/TURN 调整建议直接用控制台,避免同时维护两套配置。
|
||||
|
||||
| 变量 | 默认 | 作用 |
|
||||
| --- | --- | --- |
|
||||
| `WEBSPEAK_VOICE_PROFILE` | `auto` | `auto`:非可信 Cloudflare 请求用 `legacy`,可信 Cloudflare 代理请求用 `adaptive`;也可显式 `legacy`/`adaptive`。非 CFT 不配置时保持原行为。 |
|
||||
| `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY` | `all` | 浏览器 ICE 策略。直连优先保持 `all`;只有确认 UDP 完全不可用才设 `relay`。 |
|
||||
| `WEBSPEAK_VOICE_GATEWAY_ICE_TRANSPORT_POLICY` | `all` | werift 网关侧策略。网关自身在 NAT 后才考虑 `relay`。 |
|
||||
| `WEBSPEAK_VOICE_ICE_SERVERS` | 空 | 静态 ICE 列表,JSON 数组或逗号分隔的 STUN URL;最多 8 个。 |
|
||||
| `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_JITTER_MAX_MS` | `300` | 自适应 jitter buffer 的上限,范围 80–500;仅 `adaptive` 生效。 |
|
||||
|
||||
示例(直连优先 + TURN 后备):
|
||||
|
||||
```bash
|
||||
WEBSPEAK_VOICE_PROFILE=auto
|
||||
WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all
|
||||
WEBSPEAK_VOICE_GATEWAY_ICE_TRANSPORT_POLICY=all
|
||||
WEBSPEAK_TURN_REST_URLS='turn:turn.example.com:3478?transport=udp,turn:turn.example.com:3478?transport=tcp'
|
||||
WEBSPEAK_TURN_REST_SECRET='<与 coturn 相同的密钥>'
|
||||
WEBSPEAK_TURN_REST_TTL_SECONDS=21600
|
||||
```
|
||||
|
||||
直连部署若也想启用自适应 buffer / pacer,显式设置
|
||||
`WEBSPEAK_VOICE_PROFILE=adaptive`;这会改变非 CFT 的音频时序,但不是开通
|
||||
CFT 的必选项。
|
||||
|
||||
`turn:` 的 UDP/TCP 3478 适合大多数场景;如已给 coturn 配好证书,可再加
|
||||
`turns:turn.example.com:5349?transport=tcp`。TURN 的 relay 端口默认
|
||||
`49160–49200/UDP`,与 WebRTC 的 `40000–40099/UDP` 分开,见
|
||||
`deploy/coturn/`。
|
||||
|
||||
### 关于 werift 与 `turns:`
|
||||
|
||||
已核对 `werift` 源码:`parseIceServers` 会把 `turns:` 解析为
|
||||
`turnTransport: "tls"`,`createTurnClient` 走 `TlsTransport`;
|
||||
`iceUseTcp: false` 只影响 ICE-TCP host candidate 的收集,不会阻止 TURN 的
|
||||
TLS 控制连接。因此 `turns:` 在 `iceUseTcp: false` 下仍可用。该结论是源码
|
||||
级核实,未在真实 coturn 上做端到端联调。
|
||||
|
||||
## 3. 兼容模式(PCM/Opus over WebSocket)
|
||||
|
||||
兼容模式不依赖 UDP,任何部署都可用。以下自适应/Opus/pacer 只在
|
||||
`voiceProfile=adaptive` 时生效;`legacy` 直连保留原来的 80ms 固定窗口,
|
||||
超过窗口会 `clear()` 解码器并重建,和旧版一致。
|
||||
|
||||
自适应分支:
|
||||
|
||||
- jitter buffer:目标超前量按到达 jitter 估算,初始 80ms,上限默认
|
||||
300ms;溢出时只重排播放头、保留 `AudioDecoder`,不再每次超过 80ms
|
||||
就销毁解码器。
|
||||
- 解码队列硬上限 12;只有极深积压才丢最新帧。
|
||||
- 上行 20ms pacer;新帧格式 `0x01 + PCM` 和 `0x02 + Opus`,旧 1920 字节
|
||||
PCM 仍兼容。
|
||||
- 仅当 `adaptive` 且环境变量或控制台显式启用 Opus,同时浏览器支持
|
||||
WebCodecs 时才发 Opus,否则自动回退 PCM。
|
||||
|
||||
legacy 分支:
|
||||
|
||||
- 80ms 固定播放窗口;超限清空当前 speaker 的 source 和 decoder。
|
||||
- 浏览器发送裸 1920 字节 PCM,不创建 Opus encoder。
|
||||
- 服务端不启用 pacer;WebRTC 混音保持 4 帧队列和每包 marker。
|
||||
|
||||
验证:
|
||||
|
||||
1. 在 Chrome/Edge 打开 `chrome://webrtc-internals`:已下发 WebRTC offer 后
|
||||
若建连或传输失败,页面应留在当前 TeamSpeak/WebSocket 会话,自动恢复
|
||||
PCM/Opus over WebSocket 的上下行兼容音频(上行需要已有麦克风权限),
|
||||
同时显示 `WEBRTC_FAILED` 和“重新连接 WebRTC”。
|
||||
2. 点击“重新连接 WebRTC”只重试 WebRTC,不重新连接 TeamSpeak,也不新建
|
||||
语音 WebSocket。重连协商期间保持兼容收发;只有 WebRTC 真正 ready 后才
|
||||
停止兼容传输、清除失败横幅和按钮。再次失败则继续兼容保通话,横幅和
|
||||
按钮保留。
|
||||
3. 网关未 advertise WebRTC 的禁用、浏览器不支持或 `NO_MEDIA_PATH` 路径仍
|
||||
直接使用兼容模式,不显示这块 WebRTC 失败按钮。
|
||||
4. 在管理台或日志看 `audio.opus` trace:`active` 表示 Opus 已启用,
|
||||
`pcm-fallback` 表示回退。
|
||||
5. 连续说话 2–3 分钟,观察是否还有周期性“整段静音/重启”式卡顿;新
|
||||
逻辑不应再因 80ms 硬窗口反复 `clear()`。
|
||||
|
||||
## 4. 验收与回滚
|
||||
|
||||
**验收顺序**
|
||||
|
||||
1. 同一网络下先用直连 UDP:`chrome://webrtc-internals` 选中 pair 应为
|
||||
`host`/`srflx`,不是 `relay`。
|
||||
2. 手机 4G/5G 或关 UDP 的 Wi-Fi 再测:没有直连时才会出现 `relay`,且
|
||||
音频可通。
|
||||
3. 对未下发 WebRTC 的路径(关闭 WebRTC、无媒体路径或浏览器不支持)测
|
||||
2–3 分钟兼容模式。确认连接
|
||||
`connected` 消息中的 `voiceProfile` 为 `adaptive` 后,`bufferResets`
|
||||
不应持续增长、没有解码器反复重建;若为 `legacy`,看到旧 80ms 行为是
|
||||
预期的。
|
||||
|
||||
**回滚**
|
||||
|
||||
- 恢复非 CFT 旧行为:在管理台“语音模式”选 `兼容模式`,或设置
|
||||
`WEBSPEAK_VOICE_PROFILE=legacy`(没有控制台覆盖时)。legacy 会恢复
|
||||
80ms/`clear()`、裸 PCM、旧 WebRTC mixer;不需要回退前端构建。
|
||||
- 关闭兼容模式 Opus:在管理台取消“兼容模式使用 Opus”,或设置
|
||||
`WEBSPEAK_VOICE_OPUS_WS=0`;注意只有 `adaptive` 会下发 Opus 能力。
|
||||
- 限制 jitter 缓冲:管理台把“自适应 jitter 上限”调到 80,或设置
|
||||
`WEBSPEAK_VOICE_JITTER_MAX_MS=80`;这只是把上限压回 80ms,**不会恢复
|
||||
旧版“超过 80ms 就 `clear()` 解码器”的行为**。要完全回到旧行为,使用
|
||||
`兼容模式` / `legacy`。
|
||||
- 关闭 TURN:在管理台清空 TURN URL(或移除密钥,会同时清空 URL),或删除
|
||||
`WEBSPEAK_TURN_REST_URLS` / `WEBSPEAK_TURN_REST_SECRET` 环境变量;浏览器
|
||||
只保留直连/STUN;不要为了“排障”把
|
||||
`WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY` 改成 `relay`,那会掩盖直连问题。
|
||||
- 媒体地址配置错误时,先清空管理台“公网媒体地址”并确认非 Cloudflare
|
||||
直连入口,再检查防火墙;Cloudflare 请求下留空会禁用直连,需要 TURN。
|
||||
- 数据库结构升级:本构建首次启动会把数据库迁移到 schema 14。旧版本二进制
|
||||
会拒绝 schema 14,因此回退二进制前必须先恢复升级前的数据库备份及对应的
|
||||
`master.key`;只回退代码、保留 schema 14 数据库会导致旧版本无法启动。
|
||||
|
||||
## 5. 已知限制
|
||||
|
||||
- 本文的 coturn/cloudflared 模板未做真实端到端联调;部署前必须在
|
||||
目标网络验证 `3478/UDP`、`3478/TCP`、relay 端口和凭证一致性。
|
||||
- Safari/Firefox 的 WebCodecs Opus 支持差异未在真实设备上逐一验证;
|
||||
不支持时会回退 PCM,但兼容模式的 CPU/带宽开销会更高。
|
||||
- Cloudflare Tunnel 不承载本文的 WebRTC UDP 媒体;即使 HTTPS/WSS 正常,
|
||||
仍需要独立可达的公网媒体地址,或配置 TURN/使用兼容模式。
|
||||
+5
-1
@@ -193,7 +193,11 @@ Unter **Server → Erweiterte Einstellungen** die **öffentliche Medienadresse**
|
||||
|
||||
**IPv6-Kandidaten** sind optional und behalten IPv4 bei; IPv6-Routing und Firewall müssen passen. Als **Sprach-STUN** kann `stun:turn.teamspeak.com:3478` eingetragen werden. Browser und Gateway verwenden dann denselben Dienst. Leer behält das bisherige Verhalten bei: STUN des Gateway-SDKs, kein Browser-STUN. Zulässig sind IPv4-erreichbare UDP-STUN-Domains oder IPv4-Adressen, keine IPv6-Literale oder TURN-Zugangsdaten.
|
||||
|
||||
Speichern und neu verbinden. Den gesamten UDP-Portbereich öffnen und bei statischer Weiterleitung die Portnummern erhalten. STUN findet Adressabbildungen, leitet aber keine Audiodaten weiter. Ein reiner TCP-Tunnel ohne nutzbaren UDP-/IPv6-Pfad führt weiter zum kompatiblen Transport.
|
||||
Speichern und neu verbinden. Erreichbare Webseiten und WebSockets bedeuten nicht, dass UDP-Medien erreichbar sind. Den gesamten UDP-Portbereich öffnen und bei statischer Weiterleitung die Portnummern erhalten. STUN findet Adressabbildungen, leitet aber keine Audiodaten weiter und überwindet nicht jedes NAT.
|
||||
|
||||
Für Mobilfunk oder blockiertes UDP kann ein externer TURN-Dienst als optionales Fallback unter **Administration → Sprache** mit TURN-REST-URL, gemeinsamem Geheimnis und Gültigkeitsdauer eingerichtet werden; entsprechende Umgebungsvariablen sind `WEBSPEAK_TURN_REST_URLS` und `WEBSPEAK_TURN_REST_SECRET`. Konsolenwerte haben Vorrang und gelten ohne Neustart für neue Verbindungen. `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all` versucht zuerst direktes UDP.
|
||||
|
||||
`WEBSPEAK_VOICE_PROFILE` ist standardmäßig `auto`: Nur Anfragen über einen vertrauenswürdigen Cloudflare-Proxy verwenden den adaptiven Puffer; direkte und andere Anfragen behalten das bisherige Verhalten mit 80 ms/Roh-PCM. Lokale Tunnel-Verbindungen sind standardmäßig vertrauenswürdig; wenn cloudflared von einer anderen Adresse verbindet, `WEBSPEAK_TRUSTED_PROXIES` konfigurieren. Für adaptive Nutzung auch bei direktem Zugriff explizit `adaptive` wählen oder unter Administration → Sprache festlegen. Opus über WebSocket ist standardmäßig aus und benötigt das adaptive Profil; es lässt sich unter Administration → Sprache oder mit `WEBSPEAK_VOICE_OPUS_WS=1` aktivieren. Ohne direktes UDP oder TURN meldet die Sitzung `NO_MEDIA_PATH` und verwendet den kompatiblen Transport. Details stehen in [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md).
|
||||
|
||||
### ICE-Kandidaten für Bildschirmfreigabe
|
||||
|
||||
|
||||
+4
-2
@@ -195,11 +195,13 @@ The port range is locked while WebRTC is enabled. Disable and save WebRTC before
|
||||
|
||||
### Voice WebRTC behind a reverse proxy or TCP tunnel
|
||||
|
||||
The WebRTC advanced settings now include a **public media address**, **IPv6 candidates**, and a **voice STUN server**. The media address must be a gateway IP or hostname reachable over UDP, without a scheme, path or port. It overrides the address inferred from `Origin`, `X-Forwarded-Host`, or `Host`; DNS names are resolved into IP candidates. IPv6 is opt-in and retains IPv4 candidates.
|
||||
The WebRTC advanced settings now include a **public media address**, **IPv6 candidates**, and a **voice STUN server**. The media address must be a gateway IP or hostname reachable directly over UDP, without a scheme, path or port. Prefer the host's public IP; do not use the Cloudflare-proxied hostname. It overrides the address inferred from `Origin`, `X-Forwarded-Host`, or `Host`; DNS names are resolved into IP candidates. IPv6 is opt-in and retains IPv4 candidates.
|
||||
|
||||
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. Deployments with only a TCP tunnel and no usable UDP/IPv6 path still fall back to 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. 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.
|
||||
|
||||
See [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md) for the direct-UDP-first topology, coturn/cloudflared templates, verification and rollback notes.
|
||||
|
||||
### Screen-share ICE candidates
|
||||
|
||||
|
||||
+5
-1
@@ -180,7 +180,11 @@ WebSpeak 管理画面と音声接続は、この機能に依存しません。
|
||||
|
||||
**IPv6 候補**は任意で、IPv4 も維持します。IPv6 の経路とファイアウォール許可が必要です。**音声 STUN** に `stun:turn.teamspeak.com:3478` を設定すると、ブラウザーとゲートウェイが同じサービスを使います。空欄では従来どおり、ゲートウェイのライブラリ内蔵 STUN を使い、ブラウザーには設定しません。IPv4 で到達可能な UDP STUN ドメイン・IPv4 アドレスに対応し、IPv6 リテラルや TURN 認証情報は指定できません。
|
||||
|
||||
保存後に再接続してください。UDP 範囲全体を許可し、固定ポート転送では番号を維持します。STUN はアドレスを検出するだけで音声を中継しません。利用可能な UDP/IPv6 経路のない TCP Tunnel だけでは、互換転送に戻ります。
|
||||
保存後に再接続してください。ページと WebSocket に到達できても、UDP メディアが到達可能とは限りません。UDP 範囲全体を許可し、固定ポート転送では番号を維持します。STUN はアドレスを検出するだけで音声を中継せず、すべての NAT を通過できるわけでもありません。
|
||||
|
||||
モバイル回線や UDP が遮断される環境では、**管理コンソール → サーバー → 音声**で外部 TURN を任意のフォールバックとして設定できます。TURN REST URL、共有シークレット、認証情報の有効期限を入力してください。対応する環境変数は `WEBSPEAK_TURN_REST_URLS` と `WEBSPEAK_TURN_REST_SECRET` です。コンソールの値が優先され、ゲートウェイの再起動なしで新しい接続に適用されます。`WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all` ではまず直接 UDP を試します。
|
||||
|
||||
`WEBSPEAK_VOICE_PROFILE` の初期値は `auto` です。信頼できる Cloudflare プロキシを経由した要求だけが適応バッファを使い、直接接続などの要求は従来の 80 ms / 生 PCM の動作を維持します。ローカルの Tunnel 接続は初期状態で信頼されます。cloudflared が別のアドレスから接続する場合は `WEBSPEAK_TRUSTED_PROXIES` を設定してください。直接接続でも適応モードを使うには `adaptive` を明示的に選ぶか、「音声」で指定します。WebSocket 経由の Opus は初期状態で無効で、適応モードが必要です。「音声」または `WEBSPEAK_VOICE_OPUS_WS=1` で有効にできます。直接 UDP と TURN のどちらもメディア経路を提供できない場合、セッションは `NO_MEDIA_PATH` を報告して互換トランスポートを使います。詳細は [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md) を参照してください。
|
||||
|
||||
### 画面共有の ICE 候補
|
||||
|
||||
|
||||
+5
-1
@@ -180,7 +180,11 @@ webspeak.example.com {
|
||||
|
||||
**IPv6-кандидаты** включаются отдельно и сохраняют IPv4; необходимы маршрутизация IPv6 и правила firewall. В поле **голосовой STUN** можно указать `stun:turn.teamspeak.com:3478`: браузер и шлюз используют один сервис. Пустое поле сохраняет прежнее поведение: встроенный STUN библиотеки шлюза и отсутствие STUN в браузере. Поле принимает доступный по IPv4 UDP STUN с доменом или IPv4, но не IPv6-литералы и не учётные данные TURN.
|
||||
|
||||
Сохраните настройки и подключитесь заново. Откройте весь диапазон UDP и сохраняйте номера портов при статическом пробросе. STUN обнаруживает отображения адресов, но не ретранслирует звук. Один TCP Tunnel без доступного UDP/IPv6 не предотвращает переход на совместимый транспорт.
|
||||
Сохраните настройки и подключитесь заново. Доступность страницы и WebSocket не означает доступность UDP-медиа. Откройте весь диапазон UDP и сохраняйте номера портов при статическом пробросе. STUN обнаруживает отображения адресов, но не ретранслирует звук и не гарантирует прохождение любого NAT.
|
||||
|
||||
Для мобильных сетей или при блокировке UDP можно настроить внешний TURN как необязательный резерв в разделе **Панель администратора → Сервер → Голос**: укажите TURN REST URL, общий секрет и срок действия учётных данных. Эквивалентные переменные окружения — `WEBSPEAK_TURN_REST_URLS` и `WEBSPEAK_TURN_REST_SECRET`. Значения из консоли имеют приоритет и применяются к новым соединениям без перезапуска. `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all` сначала пытается использовать прямой UDP.
|
||||
|
||||
`WEBSPEAK_VOICE_PROFILE` по умолчанию имеет значение `auto`: адаптивный буфер используется только для запросов через доверенный прокси Cloudflare; прямые и другие запросы сохраняют прежний путь с окном 80 мс и сырым PCM. Локальные подключения Tunnel доверены по умолчанию; если cloudflared подключается с другого адреса, задайте `WEBSPEAK_TRUSTED_PROXIES`. Чтобы использовать адаптивный режим и при прямом подключении, выберите `adaptive` явно или задайте его в разделе «Голос». Opus через WebSocket по умолчанию выключен и требует адаптивного профиля; включите его в разделе «Голос» или через `WEBSPEAK_VOICE_OPUS_WS=1`. Если ни прямой UDP, ни TURN не даёт медиапуть, сессия сообщает `NO_MEDIA_PATH` и использует совместимый транспорт. Подробности: [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md).
|
||||
|
||||
### ICE для демонстрации экрана
|
||||
|
||||
|
||||
@@ -214,11 +214,13 @@ WebRTC 启用后端口范围会锁定。要修改端口,先关闭 WebRTC 并
|
||||
|
||||
在管理后台的 WebRTC 高级参数中可设置:
|
||||
|
||||
- **公网媒体地址**:WebSpeak 网关可被 UDP 访问的 IP 或域名,不含协议、路径或端口。优先于网页入口推断;留空时按 `Origin`、`X-Forwarded-Host`、`Host` 推断。域名会解析为 IP 候选。反代域名不一定是媒体地址。
|
||||
- **公网媒体地址**:WebSpeak 网关可被 UDP 直达的 IP 或域名,不含协议、路径或端口。有公网 IP 时优先填它;Cloudflare Tunnel/纯 TCP 入口不要填 CF 代理域名。优先于网页入口推断;留空时按 `Origin`、`X-Forwarded-Host`、`Host` 推断,但 Cloudflare 请求不会再拿 CF 边缘 Host 当媒体地址。域名会解析为 IP 候选。
|
||||
- **启用 IPv6 候选**:默认关闭;开启后保留 IPv4,同时收集 IPv6。需确保 IPv6 路由及 UDP 防火墙放行。
|
||||
- **语音 STUN 服务**:可设置 `stun:turn.teamspeak.com:3478`,浏览器和网关使用同一服务发现公网映射。留空保留旧行为:werift 网关仍使用库内置 STUN,浏览器不配置 STUN。当前字段仅支持可通过 IPv4 访问的 UDP STUN 域名或 IPv4 地址,不接受 IPv6 字面量、TURN 或凭据;IPv6 媒体候选独立于 STUN 开关。
|
||||
|
||||
保存后重新连接。网页和 WebSocket 经反代可达,不代表媒体 UDP 可达;STUN 仅发现地址,不中继音频,也不保证穿透所有 NAT。只有 TCP 隧道而无可用 UDP/IPv6 路径时,仍会回退兼容传输。应开放配置的整个 UDP 端口范围;静态端口转发需保持相同端口映射。
|
||||
保存后重新连接。网页和 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/`。
|
||||
|
||||
### 屏幕共享的 ICE 候选
|
||||
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
# Cloudflare Tunnel 语音兼容性说明
|
||||
|
||||
## 范围
|
||||
|
||||
本文件说明网页/信令通过 Cloudflare Tunnel、WebRTC 媒体尽量直连 UDP 的兼容性
|
||||
改动。默认行为是 `WEBSPEAK_VOICE_PROFILE=auto`:
|
||||
|
||||
- 非 Cloudflare 请求保持 `legacy`:80ms 固定窗口、超限 `clear()`、裸
|
||||
1920-byte PCM、旧 WebRTC mixer。
|
||||
- 只有来自受信任代理且带 Cloudflare 标记的请求才自动进入 `adaptive`。
|
||||
- 显式 `legacy` 或 `adaptive` 覆盖自动判定。
|
||||
- TURN 是可选后备,不默认强制 `relay`。
|
||||
|
||||
本文件是内部实现说明,不代表整体验收、发布或实际部署证明。
|
||||
|
||||
## 主要改动
|
||||
|
||||
### WebRTC、ICE 与回退
|
||||
|
||||
- `src/server/voice-ice-config.ts`:支持静态 ICE、TURN REST、浏览器/网关
|
||||
transport policy、语音 profile、Opus WebSocket 和 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。
|
||||
- Cloudflare 请求不再把 Tunnel `Host` 当作 ICE 媒体地址。未配置公网媒体
|
||||
地址且没有 TURN 时返回 `NO_MEDIA_PATH`,浏览器使用兼容传输。
|
||||
- 已下发 WebRTC 后建连或传输失败会自动恢复 PCM/Opus over WebSocket 的
|
||||
上下行兼容音频,页面留在当前 TeamSpeak/WebSocket 会话;上行需要已有
|
||||
麦克风权限。横幅继续使用 `WEBRTC_FAILED`,并保留“重新连接 WebRTC”。
|
||||
- “重新连接 WebRTC”只重试 WebRTC,不调用整段连接流程、不新建语音
|
||||
WebSocket。重连期间保持兼容收发,等 `onReady` 后才停止兼容音频并清除
|
||||
失败横幅和按钮,避免双路音频或切换静音。
|
||||
- 重连再次失败时继续留在兼容模式保通话,横幅和按钮保留。网关未
|
||||
advertise WebRTC 的既有兼容路径不变,也不显示这块失败按钮。
|
||||
- `src/server/webrtc-audio.ts` 与 `web/src/voice/webrtc-transport.ts`:浏览器
|
||||
和网关使用完整 ICE 列表;无 TURN 的 `relay` 策略快速失败。
|
||||
- 已从 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。
|
||||
- Safari/Firefox 的 Opus 行为未逐台真机验证。
|
||||
|
||||
### 管理台与持久化
|
||||
|
||||
- 管理台“服务器 → 语音”提供 profile、Opus、jitter 上限和 TURN REST 配置。
|
||||
- 非空控制台值覆盖环境变量;未修改字段保持数据库 `NULL`,继续继承环境变量。
|
||||
- 清空 TURN URL 或移除密钥会显式停用环境变量中的 TURN REST。
|
||||
- TURN 密钥使用网关主密钥加密存储,API 只返回是否已配置。
|
||||
- 无关设置保存不会把未修改的语音字段写成控制台覆盖值。
|
||||
|
||||
## 示例配置
|
||||
|
||||
```bash
|
||||
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_TURN_REST_SECRET='<replace-with-demo-secret>'
|
||||
WEBSPEAK_TURN_REST_TTL_SECONDS=21600
|
||||
```
|
||||
|
||||
公网媒体地址示例使用 `192.0.2.10`;实际部署必须替换为可直接通过 UDP 到达的
|
||||
地址。Cloudflare Tunnel 不转发 WebRTC UDP,也不能作为媒体地址。
|
||||
|
||||
## 数据库与回滚
|
||||
|
||||
- 本构建把数据库迁移到 schema 14。schema 13→14 只新增可空的语音覆盖列,
|
||||
现有行继续继承环境变量;新数据库仍从 schema 1 顺序迁移。
|
||||
- 旧版本二进制会拒绝 schema 14。升级前应备份数据库及对应的 `master.key`;
|
||||
回退二进制时必须恢复匹配的备份。只回退代码而保留 schema 14 数据库会导致
|
||||
旧版本无法启动。
|
||||
- 恢复非 Cloudflare 旧音频行为:选择 `legacy`,或确保没有控制台覆盖后设置
|
||||
`WEBSPEAK_VOICE_PROFILE=legacy`。
|
||||
- 关闭 Opus:取消控制台选项或设置 `WEBSPEAK_VOICE_OPUS_WS=0`。
|
||||
- 关闭 TURN:清空 TURN URL/移除密钥,或删除对应环境变量。
|
||||
|
||||
## 验证边界
|
||||
|
||||
- coturn/cloudflared 模板未在真实目标网络端到端联调。
|
||||
- TURN 的 UDP/TCP/TLS、relay 端口和凭证一致性仍需在目标网络验证。
|
||||
- Safari/Firefox WebCodecs Opus 与真实浏览器 jitter 表现仍需设备测试。
|
||||
- 自动化测试和构建结果以本次审查的测试记录为准;历史报告中的通过数量
|
||||
不应被视为本次独立复跑结果。
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/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/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/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",
|
||||
"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",
|
||||
"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",
|
||||
|
||||
@@ -615,6 +615,13 @@ function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
|
||||
webRtcStunServer: body.webRtcStunServer as string | undefined,
|
||||
webRtcUdpStart: readOptionalInteger(body, "webRtcUdpStart"),
|
||||
webRtcUdpEnd: readOptionalInteger(body, "webRtcUdpEnd"),
|
||||
voiceProfile: body.voiceProfile as AdminSettingsInput["voiceProfile"],
|
||||
voiceTurnUrls: typeof body.voiceTurnUrls === "string" ? body.voiceTurnUrls.slice(0, 4096) : undefined,
|
||||
voiceTurnSecret: typeof body.voiceTurnSecret === "string" ? body.voiceTurnSecret.slice(0, 512) : undefined,
|
||||
voiceTurnSecretAction: readPasswordAction(body.voiceTurnSecretAction),
|
||||
voiceTurnTtlSeconds: readOptionalInteger(body, "voiceTurnTtlSeconds"),
|
||||
voiceOpusWs: typeof body.voiceOpusWs === "boolean" ? body.voiceOpusWs : undefined,
|
||||
voiceJitterMaxMs: readOptionalInteger(body, "voiceJitterMaxMs"),
|
||||
relaySettingsAction: readRelaySettingsAction(body.relaySettingsAction),
|
||||
relayEnabled: body.relayEnabled === true,
|
||||
relayName: typeof body.relayName === "string" ? body.relayName.slice(0, 80) : undefined,
|
||||
|
||||
+122
-1
@@ -15,8 +15,10 @@ import { hashAdminPassword, validateAdminPassword, verifyAdminPassword } from ".
|
||||
import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
|
||||
import { probeTeamSpeak, TeamSpeakProbeError } from "../server/teamspeak-probe.js";
|
||||
import { pingTeamSpeakHost } from "../server/network-probe.js";
|
||||
import { normalizeVoiceMediaHost, normalizeVoiceStunServer } from "../shared/voice-ice.js";
|
||||
import { normalizeVoiceMediaHost, normalizeVoiceStunServer, normalizeVoiceTurnRestUrls, VOICE_JITTER_MAX_MS, VOICE_JITTER_MIN_MS, VOICE_TURN_MIN_SECRET_LENGTH, VOICE_TURN_TTL_DEFAULT_SECONDS, VOICE_TURN_TTL_MAX_SECONDS, VOICE_TURN_TTL_MIN_SECONDS } from "../shared/voice-ice.js";
|
||||
import type { WebRtcAudioOptions } from "../server/webrtc-audio.js";
|
||||
import { DEFAULT_VOICE_ICE_CONFIG, type VoiceIceConfig } from "../server/voice-ice-config.js";
|
||||
import { isVoiceProfileSetting } from "../shared/voice-profile.js";
|
||||
import { DEFAULT_ACCELERATION_RELAY_PORT, type ConfiguredAccelerationRelay } from "../server/acceleration-relay.js";
|
||||
import { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_MAX, WEBRTC_UDP_PORT_MIN } from "../server/webrtc-config.js";
|
||||
import { DEFAULT_WELCOME_TEXTS, resolveWelcomeTexts } from "../site-copy.js";
|
||||
@@ -43,6 +45,7 @@ export interface ManagedInviteView {
|
||||
}
|
||||
|
||||
type ProbeFunction = typeof probeTeamSpeak;
|
||||
const VOICE_TURN_SECRET_PURPOSE = "webspeak:voice-turn-rest-secret:v1";
|
||||
|
||||
export class AdminService {
|
||||
private readonly tsAdmin: TsAdminService;
|
||||
@@ -56,6 +59,8 @@ export class AdminService {
|
||||
private readonly probe: ProbeFunction = probeTeamSpeak,
|
||||
private readonly version = "0.1.0",
|
||||
tsAdminClientFactory?: TsAdminQueryClientFactory,
|
||||
/** Environment baseline; console values override it without requiring a restart. */
|
||||
private readonly voiceIceDefaults: VoiceIceConfig = DEFAULT_VOICE_ICE_CONFIG,
|
||||
) {
|
||||
this.tsAdmin = new TsAdminService(database, masterSecret, logger, () => {
|
||||
const settings = database.getSettings();
|
||||
@@ -124,6 +129,7 @@ export class AdminService {
|
||||
|
||||
getAdminSettings(): AdminSettings {
|
||||
const settings = this.database.getSettings();
|
||||
const turn = this.resolveVoiceTurnSettings(settings);
|
||||
return {
|
||||
target: settingsTarget(settings),
|
||||
hasPassword: Boolean(settings.tsPasswordEncrypted),
|
||||
@@ -144,6 +150,12 @@ export class AdminService {
|
||||
webRtcStunServer: settings.webRtcStunServer,
|
||||
webRtcUdpStart: settings.webRtcUdpStart,
|
||||
webRtcUdpEnd: settings.webRtcUdpEnd,
|
||||
voiceProfile: settings.voiceProfile ?? this.voiceIceDefaults.profile,
|
||||
voiceTurnUrls: turn.urls.join("\n"),
|
||||
hasVoiceTurnSecret: turn.secret.length > 0,
|
||||
voiceTurnTtlSeconds: turn.ttlSeconds,
|
||||
voiceOpusWs: settings.voiceOpusWs ?? this.voiceIceDefaults.opusWebSocket,
|
||||
voiceJitterMaxMs: settings.voiceJitterMaxMs ?? this.voiceIceDefaults.jitterMaxMs,
|
||||
relayConfigured: settings.relayConfigured,
|
||||
relayEnabled: settings.relayEnabled,
|
||||
relayName: settings.relayName,
|
||||
@@ -166,6 +178,43 @@ export class AdminService {
|
||||
};
|
||||
}
|
||||
|
||||
/** Resolve environment defaults plus console overrides for every new voice connection. */
|
||||
getVoiceIceConfig(): VoiceIceConfig {
|
||||
const settings = this.database.getSettings();
|
||||
const turn = this.resolveVoiceTurnSettings(settings);
|
||||
const turnRest = turn.urls.length > 0 && turn.secret.length >= VOICE_TURN_MIN_SECRET_LENGTH
|
||||
? { urls: turn.urls, secret: turn.secret, ttlSeconds: turn.ttlSeconds }
|
||||
: undefined;
|
||||
return {
|
||||
servers: [...this.voiceIceDefaults.servers],
|
||||
...(turnRest ? { turnRest } : {}),
|
||||
transportPolicy: this.voiceIceDefaults.transportPolicy,
|
||||
gatewayTransportPolicy: this.voiceIceDefaults.gatewayTransportPolicy,
|
||||
profile: settings.voiceProfile ?? this.voiceIceDefaults.profile,
|
||||
opusWebSocket: settings.voiceOpusWs ?? this.voiceIceDefaults.opusWebSocket,
|
||||
jitterMaxMs: settings.voiceJitterMaxMs ?? this.voiceIceDefaults.jitterMaxMs,
|
||||
};
|
||||
}
|
||||
|
||||
private resolveVoiceTurnSettings(settings: ReturnType<WebSpeakDatabase["getSettings"]>): { urls: string[]; secret: string; ttlSeconds: number } {
|
||||
const baseline = this.voiceIceDefaults.turnRest;
|
||||
const urls = settings.voiceTurnUrls === null
|
||||
? baseline?.urls ?? []
|
||||
: normalizeVoiceTurnRestUrls(settings.voiceTurnUrls) ?? [];
|
||||
const ttlSeconds = settings.voiceTurnTtlSeconds ?? baseline?.ttlSeconds ?? VOICE_TURN_TTL_DEFAULT_SECONDS;
|
||||
let secret = "";
|
||||
if (settings.voiceTurnSecretEncrypted === null) {
|
||||
secret = baseline?.secret ?? "";
|
||||
} else if (settings.voiceTurnSecretEncrypted !== "") {
|
||||
try {
|
||||
secret = decryptSecret(settings.voiceTurnSecretEncrypted, this.masterSecret, VOICE_TURN_SECRET_PURPOSE);
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Stored TURN shared secret could not be decrypted");
|
||||
}
|
||||
}
|
||||
return { urls, secret, ttlSeconds };
|
||||
}
|
||||
|
||||
getAccelerationRelayOptions(): ConfiguredAccelerationRelay[] {
|
||||
const relays: ConfiguredAccelerationRelay[] = [];
|
||||
for (const node of this.database.listRelayNodes()) {
|
||||
@@ -420,6 +469,60 @@ export class AdminService {
|
||||
throw new AdminInputError("WEBRTC_PORT_LOCKED", "Disable WebRTC and save before changing its UDP port range");
|
||||
}
|
||||
|
||||
const voiceProfile = input.voiceProfile === undefined ? current.voiceProfile : input.voiceProfile;
|
||||
if (voiceProfile !== null && !isVoiceProfileSetting(voiceProfile)) {
|
||||
throw new AdminInputError("INVALID_VOICE_PROFILE", "Voice profile must be auto, legacy or adaptive");
|
||||
}
|
||||
let voiceTurnUrls = current.voiceTurnUrls;
|
||||
let requestedTurnUrls = current.voiceTurnUrls === null
|
||||
? this.voiceIceDefaults.turnRest?.urls ?? []
|
||||
: normalizeVoiceTurnRestUrls(current.voiceTurnUrls) ?? [];
|
||||
if (input.voiceTurnUrls !== undefined) {
|
||||
const normalized = normalizeVoiceTurnRestUrls(input.voiceTurnUrls);
|
||||
if (normalized === null) throw new AdminInputError("INVALID_VOICE_TURN_URLS", "Use one turn:/turns: URL per entry, at most eight");
|
||||
voiceTurnUrls = normalized.join("\n");
|
||||
requestedTurnUrls = normalized;
|
||||
}
|
||||
let voiceTurnSecretEncrypted = current.voiceTurnSecretEncrypted;
|
||||
const voiceTurnSecretAction = input.voiceTurnSecretAction ?? (input.voiceTurnSecret === undefined ? "keep" : "replace");
|
||||
if (voiceTurnSecretAction === "remove") {
|
||||
voiceTurnSecretEncrypted = "";
|
||||
voiceTurnUrls = "";
|
||||
requestedTurnUrls = [];
|
||||
}
|
||||
if (voiceTurnSecretAction === "replace") {
|
||||
const secret = input.voiceTurnSecret?.trim() ?? "";
|
||||
if (secret && secret.length < VOICE_TURN_MIN_SECRET_LENGTH) {
|
||||
throw new AdminInputError("INVALID_VOICE_TURN_SECRET", `The TURN shared secret must contain at least ${VOICE_TURN_MIN_SECRET_LENGTH} characters`);
|
||||
}
|
||||
voiceTurnSecretEncrypted = secret ? encryptSecret(secret, this.masterSecret, VOICE_TURN_SECRET_PURPOSE) : "";
|
||||
}
|
||||
const voiceTurnTtlSeconds = input.voiceTurnTtlSeconds === undefined ? current.voiceTurnTtlSeconds : input.voiceTurnTtlSeconds;
|
||||
if (voiceTurnTtlSeconds !== null && (!Number.isInteger(voiceTurnTtlSeconds) || voiceTurnTtlSeconds < VOICE_TURN_TTL_MIN_SECONDS || voiceTurnTtlSeconds > VOICE_TURN_TTL_MAX_SECONDS)) {
|
||||
throw new AdminInputError("INVALID_VOICE_TURN_TTL", `TURN credential lifetime must be between ${VOICE_TURN_TTL_MIN_SECONDS} and ${VOICE_TURN_TTL_MAX_SECONDS} seconds`);
|
||||
}
|
||||
const voiceOpusWs = input.voiceOpusWs === undefined ? current.voiceOpusWs : input.voiceOpusWs;
|
||||
if (voiceOpusWs !== null && typeof voiceOpusWs !== "boolean") {
|
||||
throw new AdminInputError("INVALID_VOICE_OPUS", "Opus over WebSocket must be a boolean");
|
||||
}
|
||||
const voiceJitterMaxMs = input.voiceJitterMaxMs === undefined ? current.voiceJitterMaxMs : input.voiceJitterMaxMs;
|
||||
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`);
|
||||
}
|
||||
let turnSecret = "";
|
||||
if (voiceTurnSecretEncrypted === null) {
|
||||
turnSecret = this.voiceIceDefaults.turnRest?.secret ?? "";
|
||||
} else if (voiceTurnSecretEncrypted !== "") {
|
||||
try {
|
||||
turnSecret = decryptSecret(voiceTurnSecretEncrypted, this.masterSecret, VOICE_TURN_SECRET_PURPOSE);
|
||||
} catch {
|
||||
throw new AdminInputError("INVALID_VOICE_TURN_SECRET", "The stored TURN shared secret cannot be decrypted; enter it again");
|
||||
}
|
||||
}
|
||||
if (requestedTurnUrls.length > 0 && turnSecret.length < VOICE_TURN_MIN_SECRET_LENGTH) {
|
||||
throw new AdminInputError("INVALID_VOICE_TURN_SECRET", `Configure a TURN shared secret of at least ${VOICE_TURN_MIN_SECRET_LENGTH} characters for the TURN URLs`);
|
||||
}
|
||||
|
||||
let encryptedPassword = current.tsPasswordEncrypted;
|
||||
const action = input.passwordAction ?? (input.serverPassword === undefined ? "keep" : "replace");
|
||||
if (action === "remove") encryptedPassword = null;
|
||||
@@ -489,6 +592,12 @@ export class AdminService {
|
||||
webRtcPublicHost, webRtcIpv6Enabled, webRtcStunServer,
|
||||
webRtcUdpStart,
|
||||
webRtcUdpEnd,
|
||||
voiceProfile,
|
||||
voiceTurnUrls,
|
||||
voiceTurnSecretEncrypted,
|
||||
voiceTurnTtlSeconds,
|
||||
voiceOpusWs,
|
||||
voiceJitterMaxMs,
|
||||
relayConfigured,
|
||||
relayEnabled,
|
||||
relayName,
|
||||
@@ -615,6 +724,12 @@ export class AdminService {
|
||||
webRtcStunServer: settings.webRtcStunServer,
|
||||
webRtcUdpStart: settings.webRtcUdpStart,
|
||||
webRtcUdpEnd: settings.webRtcUdpEnd,
|
||||
voiceProfile: settings.voiceProfile,
|
||||
voiceTurnUrls: settings.voiceTurnUrls,
|
||||
voiceTurnSecretEncrypted: settings.voiceTurnSecretEncrypted,
|
||||
voiceTurnTtlSeconds: settings.voiceTurnTtlSeconds,
|
||||
voiceOpusWs: settings.voiceOpusWs,
|
||||
voiceJitterMaxMs: settings.voiceJitterMaxMs,
|
||||
relayConfigured: settings.relayConfigured,
|
||||
relayEnabled: settings.relayEnabled,
|
||||
relayName: settings.relayName,
|
||||
@@ -647,6 +762,12 @@ export class AdminService {
|
||||
webRtcStunServer: current.webRtcStunServer,
|
||||
webRtcUdpStart: current.webRtcUdpStart,
|
||||
webRtcUdpEnd: current.webRtcUdpEnd,
|
||||
voiceProfile: current.voiceProfile,
|
||||
voiceTurnUrls: current.voiceTurnUrls,
|
||||
voiceTurnSecretEncrypted: current.voiceTurnSecretEncrypted,
|
||||
voiceTurnTtlSeconds: current.voiceTurnTtlSeconds,
|
||||
voiceOpusWs: current.voiceOpusWs,
|
||||
voiceJitterMaxMs: current.voiceJitterMaxMs,
|
||||
relayConfigured: current.relayConfigured,
|
||||
relayEnabled: current.relayEnabled,
|
||||
relayName: current.relayName,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { existsSync, readFileSync, unlinkSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createAccelerationRelayServer } from "./server/acceleration-relay.js";
|
||||
import { normalizeScreenShareIceServers, type ScreenShareIceServer } from "./server/screen-share.js";
|
||||
import { readVoiceIceConfig } from "./server/voice-ice-config.js";
|
||||
import { SkinRegistry } from "./admin/skin-registry.js";
|
||||
import { PluginRegistry } from "./plugins/registry.js";
|
||||
import { UpdateService } from "./updater/update-service.js";
|
||||
@@ -18,6 +19,7 @@ const LOG_DIR = path.join(DATA_DIR, "logs");
|
||||
const STATIC_DIR = path.join(ROOT_DIR, "web", "dist");
|
||||
const APP_VERSION = readPackageVersion();
|
||||
const SCREEN_SHARE_ICE_SERVERS = readScreenShareIceServers(process.env.WEBSPEAK_SCREEN_SHARE_ICE_SERVERS);
|
||||
const VOICE_ICE_CONFIG = readVoiceIceConfig(process.env);
|
||||
|
||||
async function main() {
|
||||
if (process.env.WEBSPEAK_MODE?.trim().toLowerCase() === "relay") {
|
||||
@@ -43,6 +45,8 @@ async function main() {
|
||||
CONFIG_PATH,
|
||||
undefined,
|
||||
APP_VERSION,
|
||||
undefined,
|
||||
VOICE_ICE_CONFIG,
|
||||
);
|
||||
await adminService.initialize();
|
||||
removeObsoleteBootstrapFile();
|
||||
@@ -93,6 +97,8 @@ async function main() {
|
||||
joinTickets,
|
||||
trustedProxies: readTrustedProxies(process.env.WEBSPEAK_TRUSTED_PROXIES),
|
||||
webRtc: () => adminService.getWebRtcAudioOptions(),
|
||||
// Read per new connection so console changes apply without a process restart.
|
||||
voiceIce: () => adminService.getVoiceIceConfig(),
|
||||
screenShareIceServers: () => SCREEN_SHARE_ICE_SERVERS,
|
||||
// The public gateway only uses the relay configuration explicitly
|
||||
// saved in the admin console. Environment variables belong to the
|
||||
@@ -163,6 +169,7 @@ async function runRelayMode(): Promise<void> {
|
||||
: {}),
|
||||
udpPortRange: [webRtcUdpStart, webRtcUdpEnd] as [number, number],
|
||||
},
|
||||
voiceIce: VOICE_ICE_CONFIG,
|
||||
screenShareIceServers: SCREEN_SHARE_ICE_SERVERS,
|
||||
trustedProxies: readTrustedProxies(process.env.WEBSPEAK_TRUSTED_PROXIES),
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@ test("relay voice endpoint is stored by the current database migration", (contex
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
assert.equal(DATABASE_SCHEMA_VERSION, 13);
|
||||
assert.equal(DATABASE_SCHEMA_VERSION, 14);
|
||||
assert.equal(database.schemaVersion, DATABASE_SCHEMA_VERSION);
|
||||
assert.equal(database.getTsAdminSettings().transport, "web");
|
||||
assert.equal(database.getTsAdminSettings().enabled, false);
|
||||
@@ -38,13 +38,13 @@ test("schema 11 migration preserves encrypted SSH credentials and does not silen
|
||||
const original = new WebSpeakDatabase(filename);
|
||||
original.close();
|
||||
const old = new DatabaseSync(filename);
|
||||
old.exec("ALTER TABLE ts_admin_settings DROP COLUMN transport; ALTER TABLE ts_admin_settings DROP COLUMN query_host; ALTER TABLE ts_admin_settings DROP COLUMN web_query_url; ALTER TABLE ts_admin_settings DROP COLUMN api_key_encrypted; ALTER TABLE ts_admin_settings DROP COLUMN server_id; DROP TABLE workspace_invites; PRAGMA user_version = 11;");
|
||||
old.exec("ALTER TABLE ts_admin_settings DROP COLUMN transport; ALTER TABLE ts_admin_settings DROP COLUMN query_host; ALTER TABLE ts_admin_settings DROP COLUMN web_query_url; ALTER TABLE ts_admin_settings DROP COLUMN api_key_encrypted; ALTER TABLE ts_admin_settings DROP COLUMN server_id; DROP TABLE workspace_invites; ALTER TABLE settings DROP COLUMN voice_profile; ALTER TABLE settings DROP COLUMN voice_turn_urls; ALTER TABLE settings DROP COLUMN voice_turn_secret_encrypted; ALTER TABLE settings DROP COLUMN voice_turn_ttl_seconds; ALTER TABLE settings DROP COLUMN voice_opus_ws; ALTER TABLE settings DROP COLUMN voice_jitter_max_ms; PRAGMA user_version = 11;");
|
||||
old.prepare("UPDATE ts_admin_settings SET enabled=1, query_port=10222, username='query-owner', password_encrypted=?, host_key_fingerprint=?").run(encrypted, `SHA256:${"A".repeat(43)}`);
|
||||
old.close();
|
||||
const migrated = new WebSpeakDatabase(filename);
|
||||
t.after(() => { migrated.close(); rmSync(directory, { recursive: true, force: true }); });
|
||||
const settings = migrated.getTsAdminSettings();
|
||||
assert.equal(migrated.schemaVersion, 13);
|
||||
assert.equal(migrated.schemaVersion, 14);
|
||||
assert.equal(settings.transport, "ssh"); assert.equal(settings.enabled, true);
|
||||
assert.equal(settings.queryPort, 10222); assert.equal(settings.username, "query-owner");
|
||||
assert.equal(settings.passwordEncrypted, encrypted);
|
||||
|
||||
@@ -5,8 +5,9 @@ import { DatabaseSync } from "node:sqlite";
|
||||
import type { AdminCredential } from "../security/admin-password.js";
|
||||
import type { TeamSpeakProtocol } from "../server/teamspeak-adapter.js";
|
||||
import { DEFAULT_WEBRTC_UDP_PORT_RANGE } from "../server/webrtc-config.js";
|
||||
import type { VoiceProfileSetting } from "../shared/voice-profile.js";
|
||||
|
||||
export const DATABASE_SCHEMA_VERSION = 13;
|
||||
export const DATABASE_SCHEMA_VERSION = 14;
|
||||
export type AccessMode = "fixed" | "open";
|
||||
|
||||
export interface PersistedSettings {
|
||||
@@ -31,6 +32,13 @@ export interface PersistedSettings {
|
||||
webRtcStunServer: string;
|
||||
webRtcUdpStart: number;
|
||||
webRtcUdpEnd: number;
|
||||
/** Console-owned overrides; null inherits the environment baseline. */
|
||||
voiceProfile: VoiceProfileSetting | null;
|
||||
voiceTurnUrls: string | null;
|
||||
voiceTurnSecretEncrypted: string | null;
|
||||
voiceTurnTtlSeconds: number | null;
|
||||
voiceOpusWs: boolean | null;
|
||||
voiceJitterMaxMs: number | null;
|
||||
relayConfigured: boolean;
|
||||
relayEnabled: boolean;
|
||||
relayName: string;
|
||||
@@ -58,6 +66,12 @@ export interface SettingsUpdate {
|
||||
webRtcStunServer?: string;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
voiceProfile?: VoiceProfileSetting | null;
|
||||
voiceTurnUrls?: string | null;
|
||||
voiceTurnSecretEncrypted?: string | null;
|
||||
voiceTurnTtlSeconds?: number | null;
|
||||
voiceOpusWs?: boolean | null;
|
||||
voiceJitterMaxMs?: number | null;
|
||||
relayConfigured: boolean;
|
||||
relayEnabled: boolean;
|
||||
relayName: string;
|
||||
@@ -144,6 +158,12 @@ interface SettingsRow extends Record<string, unknown> {
|
||||
webrtc_stun_server: string;
|
||||
webrtc_udp_start: number;
|
||||
webrtc_udp_end: number;
|
||||
voice_profile: string | null;
|
||||
voice_turn_urls: string | null;
|
||||
voice_turn_secret_encrypted: string | null;
|
||||
voice_turn_ttl_seconds: number | null;
|
||||
voice_opus_ws: number | null;
|
||||
voice_jitter_max_ms: number | null;
|
||||
relay_configured: number;
|
||||
relay_enabled: number;
|
||||
relay_name: string;
|
||||
@@ -269,6 +289,12 @@ export class WebSpeakDatabase {
|
||||
webRtcStunServer: row.webrtc_stun_server,
|
||||
webRtcUdpStart: row.webrtc_udp_start,
|
||||
webRtcUdpEnd: row.webrtc_udp_end,
|
||||
voiceProfile: row.voice_profile === "legacy" || row.voice_profile === "adaptive" || row.voice_profile === "auto" ? row.voice_profile : null,
|
||||
voiceTurnUrls: row.voice_turn_urls,
|
||||
voiceTurnSecretEncrypted: row.voice_turn_secret_encrypted,
|
||||
voiceTurnTtlSeconds: row.voice_turn_ttl_seconds,
|
||||
voiceOpusWs: row.voice_opus_ws === null ? null : row.voice_opus_ws === 1,
|
||||
voiceJitterMaxMs: row.voice_jitter_max_ms,
|
||||
relayConfigured: row.relay_configured === 1,
|
||||
relayEnabled: row.relay_enabled === 1,
|
||||
relayName: row.relay_name,
|
||||
@@ -754,6 +780,23 @@ export class WebSpeakDatabase {
|
||||
); CREATE INDEX workspace_invites_expiry ON workspace_invites(expires_at);
|
||||
PRAGMA user_version = 13;`);
|
||||
});
|
||||
version = 13;
|
||||
}
|
||||
if (version === 13) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
-- Console-managed voice deployment overrides. NULL keeps the
|
||||
-- environment baseline; an empty TURN URL or secret explicitly
|
||||
-- disables the corresponding environment value.
|
||||
ALTER TABLE settings ADD COLUMN voice_profile TEXT CHECK (voice_profile IS NULL OR voice_profile IN ('auto', 'legacy', 'adaptive'));
|
||||
ALTER TABLE settings ADD COLUMN voice_turn_urls TEXT;
|
||||
ALTER TABLE settings ADD COLUMN voice_turn_secret_encrypted TEXT;
|
||||
ALTER TABLE settings ADD COLUMN voice_turn_ttl_seconds INTEGER CHECK (voice_turn_ttl_seconds IS NULL OR voice_turn_ttl_seconds BETWEEN 300 AND 86400);
|
||||
ALTER TABLE settings ADD COLUMN voice_opus_ws INTEGER CHECK (voice_opus_ws IS NULL OR voice_opus_ws IN (0, 1));
|
||||
ALTER TABLE settings ADD COLUMN voice_jitter_max_ms INTEGER CHECK (voice_jitter_max_ms IS NULL OR voice_jitter_max_ms BETWEEN 80 AND 500);
|
||||
PRAGMA user_version = 14;
|
||||
`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -762,7 +805,8 @@ export class WebSpeakDatabase {
|
||||
`UPDATE settings SET
|
||||
site_name = ?, welcome_text = ?, welcome_text_en = ?, welcome_text_de = ?, welcome_text_ru = ?, welcome_text_ja = ?, access_mode = ?, ts_host = ?, ts_port = ?, ts_target = ?,
|
||||
ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_public_host = ?, webrtc_ipv6_enabled = ?, webrtc_stun_server = ?, webrtc_udp_start = ?,
|
||||
webrtc_udp_end = ?, relay_configured = ?, relay_enabled = ?, relay_name = ?,
|
||||
webrtc_udp_end = ?, voice_profile = ?, voice_turn_urls = ?, voice_turn_secret_encrypted = ?, voice_turn_ttl_seconds = ?, voice_opus_ws = ?, voice_jitter_max_ms = ?,
|
||||
relay_configured = ?, relay_enabled = ?, relay_name = ?,
|
||||
relay_host = ?, relay_port = ?, relay_token_encrypted = ?, updated_at = ?
|
||||
WHERE id = 1`,
|
||||
).run(
|
||||
@@ -783,6 +827,12 @@ export class WebSpeakDatabase {
|
||||
settings.webRtcStunServer ?? "",
|
||||
settings.webRtcUdpStart ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[0],
|
||||
settings.webRtcUdpEnd ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[1],
|
||||
settings.voiceProfile ?? null,
|
||||
settings.voiceTurnUrls ?? null,
|
||||
settings.voiceTurnSecretEncrypted ?? null,
|
||||
settings.voiceTurnTtlSeconds ?? null,
|
||||
settings.voiceOpusWs == null ? null : settings.voiceOpusWs ? 1 : 0,
|
||||
settings.voiceJitterMaxMs ?? null,
|
||||
settings.relayConfigured ? 1 : 0,
|
||||
settings.relayEnabled ? 1 : 0,
|
||||
settings.relayName,
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { AudioPacer } from "./audio-pacer.js";
|
||||
|
||||
function fakeClock() {
|
||||
let now = 0;
|
||||
let nextId = 1;
|
||||
let task: { id: number; at: number; callback: () => void } | null = null;
|
||||
const schedule = (callback: () => void, delayMs: number) => {
|
||||
task = { id: nextId++, at: now + delayMs, callback };
|
||||
return task as unknown as ReturnType<typeof setTimeout>;
|
||||
};
|
||||
const cancel = (handle: ReturnType<typeof setTimeout>) => {
|
||||
if (task && task.id === (handle as unknown as { id: number }).id) task = null;
|
||||
};
|
||||
const runNext = () => {
|
||||
assert.ok(task, "expected a scheduled tick");
|
||||
now = Math.max(now, task.at);
|
||||
const callback = task.callback;
|
||||
task = null;
|
||||
callback();
|
||||
};
|
||||
return { now: () => now, setNow: (value: number) => { now = value; }, schedule, cancel, runNext, hasTask: () => task !== null };
|
||||
}
|
||||
|
||||
test("pacer emits one frame every 20 ms and preserves order", () => {
|
||||
const clock = fakeClock();
|
||||
const sent: number[] = [];
|
||||
const pacer = new AudioPacer((_data, codec) => sent.push(codec), {
|
||||
now: clock.now, schedule: clock.schedule, cancel: clock.cancel, maxFrames: 4,
|
||||
});
|
||||
pacer.push(Buffer.from([1]), 1);
|
||||
pacer.push(Buffer.from([2]), 2);
|
||||
pacer.push(Buffer.from([3]), 3);
|
||||
assert.equal(sent.length, 0, "frames wait for the first timer turn");
|
||||
clock.runNext();
|
||||
assert.deepEqual(sent, [1]);
|
||||
assert.equal(pacer.getStats().currentFrames, 2);
|
||||
clock.runNext();
|
||||
assert.deepEqual(sent, [1, 2]);
|
||||
clock.runNext();
|
||||
assert.deepEqual(sent, [1, 2, 3]);
|
||||
assert.equal(pacer.getStats().currentFrames, 0);
|
||||
assert.equal(clock.hasTask(), false);
|
||||
});
|
||||
|
||||
test("pacer drops the oldest frame when the queue is full and records peak", () => {
|
||||
const clock = fakeClock();
|
||||
const pacer = new AudioPacer(() => {}, { now: clock.now, schedule: clock.schedule, cancel: clock.cancel, maxFrames: 2 });
|
||||
pacer.push(Buffer.from([1]), 1);
|
||||
pacer.push(Buffer.from([2]), 2);
|
||||
pacer.push(Buffer.from([3]), 3);
|
||||
const stats = pacer.getStats();
|
||||
assert.equal(stats.currentFrames, 2);
|
||||
assert.equal(stats.peakFrames, 2);
|
||||
assert.equal(stats.droppedFrames, 1);
|
||||
pacer.close();
|
||||
});
|
||||
|
||||
test("a late event-loop turn resets the deadline instead of bursting", () => {
|
||||
const clock = fakeClock();
|
||||
const sent: number[] = [];
|
||||
const pacer = new AudioPacer(() => sent.push(1), {
|
||||
now: clock.now, schedule: clock.schedule, cancel: clock.cancel, maxFrames: 4,
|
||||
});
|
||||
pacer.push(Buffer.from([1]), 1);
|
||||
pacer.push(Buffer.from([2]), 2);
|
||||
clock.setNow(100);
|
||||
clock.runNext();
|
||||
assert.equal(sent.length, 1);
|
||||
assert.equal(pacer.getStats().lateTicks, 1);
|
||||
pacer.close();
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { performance } from "node:perf_hooks";
|
||||
|
||||
/**
|
||||
* A tiny 20 ms sender for browser PCM/Opus uplink. Cloudflare Tunnel can
|
||||
* deliver a burst of WebSocket frames at once; forwarding those frames to
|
||||
* TeamSpeak immediately preserves the burst and makes the receiving client's
|
||||
* jitter buffer work harder. This pacer absorbs the burst and emits at a fixed
|
||||
* cadence, dropping the oldest frame only when the queue is genuinely behind.
|
||||
*/
|
||||
|
||||
export interface PacerFrame {
|
||||
data: Buffer;
|
||||
codec: number;
|
||||
enqueuedAt: number;
|
||||
}
|
||||
|
||||
export interface AudioPacerOptions {
|
||||
frameMs?: number;
|
||||
maxFrames?: number;
|
||||
maxLagMs?: number;
|
||||
now?: () => number;
|
||||
schedule?: (callback: () => void, delayMs: number) => ReturnType<typeof setTimeout>;
|
||||
cancel?: (timer: ReturnType<typeof setTimeout>) => void;
|
||||
onStats?: (stats: AudioPacerStats) => void;
|
||||
}
|
||||
|
||||
export interface AudioPacerStats {
|
||||
currentFrames: number;
|
||||
peakFrames: number;
|
||||
droppedFrames: number;
|
||||
lateTicks: number;
|
||||
sentFrames: number;
|
||||
}
|
||||
|
||||
export class AudioPacer {
|
||||
private readonly frameMs: number;
|
||||
private readonly maxFrames: number;
|
||||
private readonly maxLagMs: number;
|
||||
private readonly now: () => number;
|
||||
private readonly schedule: NonNullable<AudioPacerOptions["schedule"]>;
|
||||
private readonly cancel: NonNullable<AudioPacerOptions["cancel"]>;
|
||||
private readonly onStats: AudioPacerOptions["onStats"];
|
||||
private readonly queue: PacerFrame[] = [];
|
||||
private timer: ReturnType<typeof setTimeout> | null = null;
|
||||
private nextAt: number | null = null;
|
||||
private closed = false;
|
||||
private droppedFrames = 0;
|
||||
private lateTicks = 0;
|
||||
private sentFrames = 0;
|
||||
private peakFrames = 0;
|
||||
|
||||
constructor(
|
||||
private readonly send: (data: Buffer, codec: number) => void,
|
||||
options: AudioPacerOptions = {},
|
||||
) {
|
||||
this.frameMs = Math.max(1, options.frameMs ?? 20);
|
||||
this.maxFrames = Math.max(1, options.maxFrames ?? 6);
|
||||
this.maxLagMs = Math.max(0, options.maxLagMs ?? 40);
|
||||
this.now = options.now ?? (() => performance.now());
|
||||
this.schedule = options.schedule ?? ((callback, delayMs) => setTimeout(callback, delayMs));
|
||||
this.cancel = options.cancel ?? ((handle) => clearTimeout(handle));
|
||||
this.onStats = options.onStats;
|
||||
}
|
||||
|
||||
push(data: Buffer, codec: number): boolean {
|
||||
if (this.closed || !data.length) return false;
|
||||
while (this.queue.length >= this.maxFrames) {
|
||||
this.queue.shift();
|
||||
this.droppedFrames++;
|
||||
}
|
||||
this.queue.push({ data, codec, enqueuedAt: this.now() });
|
||||
this.peakFrames = Math.max(this.peakFrames, this.queue.length);
|
||||
if (!this.timer) {
|
||||
this.nextAt = this.now();
|
||||
this.arm(0);
|
||||
}
|
||||
this.emitStats();
|
||||
return true;
|
||||
}
|
||||
|
||||
private arm(delayMs: number): void {
|
||||
this.timer = this.schedule(() => this.tick(), Math.max(0, delayMs));
|
||||
// Do not keep the Node process alive solely for an idle voice pacer.
|
||||
(this.timer as unknown as { unref?: () => void }).unref?.();
|
||||
}
|
||||
|
||||
private tick(): void {
|
||||
this.timer = null;
|
||||
if (this.closed) return;
|
||||
if (!this.queue.length) {
|
||||
this.nextAt = null;
|
||||
return;
|
||||
}
|
||||
const now = this.now();
|
||||
if (this.nextAt !== null && now - this.nextAt > this.maxLagMs) {
|
||||
// A late event loop turn must not create a catch-up burst. Drop the
|
||||
// accumulated backlog of time and emit one frame from the current time.
|
||||
this.lateTicks++;
|
||||
this.nextAt = now;
|
||||
}
|
||||
const frame = this.queue.shift()!;
|
||||
try { this.send(frame.data, frame.codec); } catch { /* sendVoice reports its own failure */ }
|
||||
this.sentFrames++;
|
||||
if (this.queue.length) {
|
||||
this.nextAt = this.nextAt === null ? now + this.frameMs : this.nextAt + this.frameMs;
|
||||
if (this.nextAt < now + 1) this.nextAt = now + this.frameMs;
|
||||
this.arm(this.nextAt - now);
|
||||
} else {
|
||||
this.nextAt = null;
|
||||
}
|
||||
this.emitStats();
|
||||
}
|
||||
|
||||
private emitStats(): void {
|
||||
this.onStats?.(this.getStats());
|
||||
}
|
||||
|
||||
getStats(): AudioPacerStats {
|
||||
return {
|
||||
currentFrames: this.queue.length,
|
||||
peakFrames: this.peakFrames,
|
||||
droppedFrames: this.droppedFrames,
|
||||
lateTicks: this.lateTicks,
|
||||
sentFrames: this.sentFrames,
|
||||
};
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true;
|
||||
if (this.timer) {
|
||||
this.cancel(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
this.queue.length = 0;
|
||||
this.nextAt = null;
|
||||
this.emitStats();
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ import type { WebRtcAudioSession, WebRtcAudioStats } from "./webrtc-audio.js";
|
||||
|
||||
export interface AudioFlowStats extends WebRtcAudioStats {
|
||||
ingressFrames: number;
|
||||
ingressPcmFrames: number;
|
||||
ingressOpusFrames: number;
|
||||
ingressDroppedFrames: number;
|
||||
ingressFirstAt: number | null;
|
||||
ingressLastAt: number | null;
|
||||
@@ -13,6 +15,10 @@ export interface AudioFlowStats extends WebRtcAudioStats {
|
||||
tsSendLastAt: number | null;
|
||||
tsSendMaxGapMs: number;
|
||||
tsEncodeMaxMs: number;
|
||||
uplinkQueueCurrentFrames: number;
|
||||
uplinkQueuePeakFrames: number;
|
||||
uplinkQueueDroppedFrames: number;
|
||||
uplinkPacerLateTicks: number;
|
||||
tsReceiveFrames: number;
|
||||
tsReceiveFirstAt: number | null;
|
||||
tsReceiveLastAt: number | null;
|
||||
@@ -38,6 +44,8 @@ export interface AudioStatsSource {
|
||||
export function createAudioFlowStats(): AudioFlowStats {
|
||||
return {
|
||||
ingressFrames: 0,
|
||||
ingressPcmFrames: 0,
|
||||
ingressOpusFrames: 0,
|
||||
ingressDroppedFrames: 0,
|
||||
ingressFirstAt: null,
|
||||
ingressLastAt: null,
|
||||
@@ -48,6 +56,10 @@ export function createAudioFlowStats(): AudioFlowStats {
|
||||
tsSendLastAt: null,
|
||||
tsSendMaxGapMs: 0,
|
||||
tsEncodeMaxMs: 0,
|
||||
uplinkQueueCurrentFrames: 0,
|
||||
uplinkQueuePeakFrames: 0,
|
||||
uplinkQueueDroppedFrames: 0,
|
||||
uplinkPacerLateTicks: 0,
|
||||
tsReceiveFrames: 0,
|
||||
tsReceiveFirstAt: null,
|
||||
tsReceiveLastAt: null,
|
||||
@@ -95,11 +107,16 @@ export function snapshotAudioStatus(entry: AudioStatsSource): VoiceAudioBridgeSt
|
||||
return {
|
||||
transport: entry.webrtc ? "webrtc" : "websocket",
|
||||
ingressFrames: stats.ingressFrames,
|
||||
ingressPcmFrames: stats.ingressPcmFrames,
|
||||
ingressOpusFrames: stats.ingressOpusFrames,
|
||||
ingressDroppedFrames: stats.ingressDroppedFrames,
|
||||
ingressMaxGapMs: stats.ingressMaxGapMs,
|
||||
tsSendFrames: stats.tsSendFrames,
|
||||
tsSendErrors: stats.tsSendErrors,
|
||||
tsSendMaxGapMs: stats.tsSendMaxGapMs,
|
||||
uplinkQueuePeakFrames: stats.uplinkQueuePeakFrames,
|
||||
uplinkQueueDroppedFrames: stats.uplinkQueueDroppedFrames,
|
||||
uplinkPacerLateTicks: stats.uplinkPacerLateTicks,
|
||||
tsReceiveFrames: stats.tsReceiveFrames,
|
||||
tsReceiveMaxGapMs: stats.tsReceiveMaxGapMs,
|
||||
egressFrames: stats.egressFrames,
|
||||
|
||||
@@ -34,7 +34,7 @@ function fixture() {
|
||||
const transport = new SessionAudioTransport({
|
||||
audio, socket, client, logger, isCurrent: () => state.current, isReady: () => state.ready,
|
||||
selfId: () => 1, peer: () => state.peer, whisperTargets: () => state.targets,
|
||||
sendJson: message => { notices.push(message); },
|
||||
sendJson: message => { notices.push(message); }, pacing: false,
|
||||
}, encoder, () => state.now, () => state.now);
|
||||
const remote = (clientId = 513) => ({ clientId, codec: 4, data: Buffer.from([11, 12, 13]) });
|
||||
return { transport, audio, state, socket, client, encoder, packets, encoded, forwarded, notices, warnings, remote };
|
||||
@@ -117,8 +117,8 @@ test("repeated malformed frames are counted in full but reported once per window
|
||||
assert.equal(f.audio.ingressDroppedFrames, 4, "every discarded frame still reaches the flow counters");
|
||||
assert.equal(f.notices.length, 2, "the browser sees one error per window, not one per frame");
|
||||
assert.deepEqual(f.warnings, [
|
||||
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: 1_920, droppedFrames: 1 },
|
||||
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: 1_920, droppedFrames: 4 },
|
||||
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: "1920 or tagged", droppedFrames: 1 },
|
||||
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: "1920 or tagged", droppedFrames: 4 },
|
||||
], "operators get the same rate-limited view through the logger");
|
||||
});
|
||||
|
||||
@@ -131,6 +131,19 @@ test("an encoder failure and a malformed frame do not suppress each other", t =>
|
||||
t.mock.restoreAll();
|
||||
});
|
||||
|
||||
test("tagged PCM and pre-encoded Opus frames share the uplink without double encoding", () => {
|
||||
const f = fixture();
|
||||
f.transport.receivePcm(Buffer.concat([Buffer.from([1]), Buffer.alloc(1_920)]));
|
||||
f.transport.receivePcm(Buffer.concat([Buffer.from([2]), Buffer.from([1, 2, 3])]));
|
||||
assert.equal(f.encoded.length, 1);
|
||||
assert.equal(f.audio.ingressPcmFrames, 1);
|
||||
assert.equal(f.audio.ingressOpusFrames, 1);
|
||||
assert.deepEqual(f.forwarded.map(({ data, codec }) => ({ data: [...data], codec })), [
|
||||
{ data: [9, 8, 7], codec: 4 },
|
||||
{ data: [1, 2, 3], codec: 4 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("WebRTC ingress excludes queued PCM and fallback re-enables PCM", () => {
|
||||
const f = fixture();
|
||||
f.state.peer = { pushTeamSpeakVoice() {} };
|
||||
|
||||
@@ -5,8 +5,19 @@ import type { ServerMessage } from "../shared/server-messages.js";
|
||||
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 {
|
||||
VOICE_MAX_OPUS_FRAME_BYTES,
|
||||
VOICE_OPUS_TAG,
|
||||
VOICE_PCM_FRAME_BYTES,
|
||||
VOICE_PCM_TAG,
|
||||
} from "../shared/voice-audio.js";
|
||||
|
||||
const AUDIO_FRAME_BYTES = 1_920; // 20 ms of 48 kHz mono Int16 PCM.
|
||||
const AUDIO_FRAME_BYTES = VOICE_PCM_FRAME_BYTES;
|
||||
const TAGGED_PCM_FRAME_BYTES = AUDIO_FRAME_BYTES + 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.
|
||||
const MAX_BUFFERED_BYTES = 4_096;
|
||||
// A client that keeps sending bad audio must not turn into one JSON error per
|
||||
@@ -33,6 +44,8 @@ export interface SessionAudioOptions {
|
||||
peer(): Pick<WebRtcAudioSession, "pushTeamSpeakVoice"> | null;
|
||||
whisperTargets(): readonly number[] | null;
|
||||
sendJson(message: ServerMessage): void;
|
||||
/** Tests that assert synchronous SDK calls can opt out; production keeps pacing. */
|
||||
pacing?: boolean;
|
||||
}
|
||||
|
||||
/** A session owns one encoder and one active audio route in each direction. */
|
||||
@@ -42,6 +55,7 @@ export class SessionAudioTransport {
|
||||
/** Last report time per audio fault code; see `shouldReportAudioIssue`. */
|
||||
private readonly reportedAt = new Map<string, number>();
|
||||
private readonly logger: LoggerType | null;
|
||||
private readonly pacer: AudioPacer | null;
|
||||
private pcmTokens = PCM_BURST_FRAMES;
|
||||
private pcmRefilledAt: number | null = null;
|
||||
|
||||
@@ -49,6 +63,18 @@ export class SessionAudioTransport {
|
||||
private readonly rateClock: () => number = performance.now.bind(performance)) {
|
||||
this.encoder = encoder;
|
||||
this.logger = options.logger ?? null;
|
||||
this.pacer = options.pacing === false ? null : new AudioPacer(
|
||||
(data, codec) => this.sendVoice(data, codec),
|
||||
{
|
||||
now: this.rateClock,
|
||||
onStats: stats => {
|
||||
options.audio.uplinkQueueCurrentFrames = stats.currentFrames;
|
||||
options.audio.uplinkQueuePeakFrames = Math.max(options.audio.uplinkQueuePeakFrames, stats.peakFrames);
|
||||
options.audio.uplinkQueueDroppedFrames = stats.droppedFrames;
|
||||
options.audio.uplinkPacerLateTicks = stats.lateTicks;
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private isCurrent(): boolean {
|
||||
@@ -112,7 +138,7 @@ export class SessionAudioTransport {
|
||||
// logged anywhere, so without this an operator has no way to notice a client
|
||||
// that keeps sending malformed audio until the session is torn down.
|
||||
this.logger?.warn(
|
||||
{ code: "INVALID_AUDIO_FRAME", frameBytes: length, expectedBytes: AUDIO_FRAME_BYTES, droppedFrames: this.options.audio.ingressDroppedFrames },
|
||||
{ code: "INVALID_AUDIO_FRAME", frameBytes: length, expectedBytes: `${AUDIO_FRAME_BYTES} or tagged`, droppedFrames: this.options.audio.ingressDroppedFrames },
|
||||
"Discarded malformed browser audio frame",
|
||||
);
|
||||
try {
|
||||
@@ -128,7 +154,11 @@ 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.options.peer()) { stats.ingressDroppedFrames++; return; }
|
||||
if (frame.length !== AUDIO_FRAME_BYTES) {
|
||||
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 opus = frame.length > 1 && frame.length <= MAX_OPUS_FRAME_BYTES + 1 && frame[0] === OPUS_FRAME_TAG
|
||||
? frame.subarray(1) : null;
|
||||
if (!legacyPcm && !taggedPcm && !opus) {
|
||||
stats.ingressDroppedFrames++;
|
||||
this.reportInvalidFrame(frame.length);
|
||||
return;
|
||||
@@ -141,17 +171,26 @@ export class SessionAudioTransport {
|
||||
if (this.pcmTokens < 1) {
|
||||
stats.ingressDroppedFrames++;
|
||||
if (this.shouldReportAudioIssue("AUDIO_RATE_EXCEEDED")) {
|
||||
this.logger?.warn({ code: "AUDIO_RATE_EXCEEDED", droppedFrames: stats.ingressDroppedFrames }, "Discarded browser PCM above the real-time budget");
|
||||
this.logger?.warn({ code: "AUDIO_RATE_EXCEEDED", droppedFrames: stats.ingressDroppedFrames }, "Discarded browser audio above the real-time budget");
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.pcmTokens--;
|
||||
this.recordIngress();
|
||||
if (opus) {
|
||||
stats.ingressOpusFrames++;
|
||||
// The pacer absorbs Cloudflare's bursty WebSocket delivery. Opus is
|
||||
// already encoded, so this costs one buffer copy and no CPU-heavy encode.
|
||||
if (this.pacer) this.pacer.push(opus, 4);
|
||||
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(frame);
|
||||
encoded = this.encoder.encode(taggedPcm ?? legacyPcm!);
|
||||
stats.tsEncodeMaxMs = Math.max(stats.tsEncodeMaxMs, this.clock() - startedAt);
|
||||
} catch {
|
||||
stats.tsSendErrors++;
|
||||
@@ -159,7 +198,8 @@ export class SessionAudioTransport {
|
||||
this.reportEncoderFailure();
|
||||
return;
|
||||
}
|
||||
this.sendVoice(encoded, 4);
|
||||
this.pacer?.push(encoded, 4);
|
||||
if (!this.pacer) this.sendVoice(encoded, 4);
|
||||
}
|
||||
|
||||
receiveWebRtc(data: Buffer, codec: number): void {
|
||||
@@ -214,6 +254,7 @@ export class SessionAudioTransport {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
this.reportedAt.clear();
|
||||
this.pacer?.close();
|
||||
const encoder = this.encoder;
|
||||
this.encoder = null;
|
||||
try { encoder?.dispose(); } catch { /* other session resources must still be released */ }
|
||||
|
||||
@@ -131,11 +131,11 @@ test("schema 8 settings and invites survive the nickname migration", async (cont
|
||||
});
|
||||
database.close();
|
||||
const legacy = new DatabaseSync(file);
|
||||
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; DROP TABLE workspace_invites; PRAGMA user_version = 8;");
|
||||
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; DROP TABLE workspace_invites; ALTER TABLE settings DROP COLUMN voice_profile; ALTER TABLE settings DROP COLUMN voice_turn_urls; ALTER TABLE settings DROP COLUMN voice_turn_secret_encrypted; ALTER TABLE settings DROP COLUMN voice_turn_ttl_seconds; ALTER TABLE settings DROP COLUMN voice_opus_ws; ALTER TABLE settings DROP COLUMN voice_jitter_max_ms; PRAGMA user_version = 8;");
|
||||
legacy.close();
|
||||
const migrated = new WebSpeakDatabase(file);
|
||||
try {
|
||||
assert.equal(migrated.schemaVersion, 13);
|
||||
assert.equal(migrated.schemaVersion, 14);
|
||||
assert.equal(migrated.getSettings().tsHost, "127.0.0.1");
|
||||
assert.equal(migrated.getSettings().tsTarget, null);
|
||||
const invite = migrated.consumeManagedInvite("legacy-token");
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { createHmac } from "node:crypto";
|
||||
import { createTurnRestCredential, createTurnRestUsername } from "./turn-credentials.js";
|
||||
|
||||
test("TURN REST username and credential match coturn's HMAC contract", () => {
|
||||
const secret = "a-test-secret-with-enough-length";
|
||||
const config = { urls: ["turns:turn.example.com:443?transport=tcp"], secret, ttlSeconds: 3_600 };
|
||||
const now = 1_700_000_000_000;
|
||||
const credential = createTurnRestCredential(config, "session-1", now);
|
||||
const expiry = Math.floor(now / 1_000) + 3_600;
|
||||
const username = createTurnRestUsername(expiry, "session-1");
|
||||
assert.equal(credential.username, username);
|
||||
assert.equal(credential.credential, createHmac("sha1", secret).update(username).digest("base64"));
|
||||
});
|
||||
|
||||
test("TURN REST session ids are sanitized and expiry stays in the future", () => {
|
||||
const credential = createTurnRestCredential(
|
||||
{ urls: ["turn:turn.example.com:3478?transport=udp"], secret: "another-long-test-secret", ttlSeconds: 300 },
|
||||
"bad session:id!",
|
||||
1_000,
|
||||
);
|
||||
assert.match(credential.username!, /^[0-9]+:badsessionid/);
|
||||
assert.equal(credential.credential?.length, 28);
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { createHmac, randomBytes } from "node:crypto";
|
||||
import type { VoiceIceServer } from "../shared/voice-ice.js";
|
||||
|
||||
export interface TurnRestConfig {
|
||||
urls: string[];
|
||||
secret: string;
|
||||
ttlSeconds: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* coturn's `use-auth-secret` REST API:
|
||||
* username = "<expiry unix seconds>:<session id>"
|
||||
* credential = base64(HMAC-SHA1(secret, username))
|
||||
*
|
||||
* Credentials are minted per browser connection; they are not shared between
|
||||
* sessions and never need to be persisted.
|
||||
*/
|
||||
export function createTurnRestCredential(
|
||||
config: TurnRestConfig,
|
||||
sessionId: string,
|
||||
nowMs = Date.now(),
|
||||
): VoiceIceServer {
|
||||
const suffix = sessionId.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 64) || randomBytes(8).toString("hex");
|
||||
const expiry = Math.floor(nowMs / 1_000) + Math.max(1, Math.trunc(config.ttlSeconds));
|
||||
const username = `${expiry}:${suffix}`;
|
||||
const credential = createHmac("sha1", config.secret).update(username).digest("base64");
|
||||
return {
|
||||
urls: config.urls.length === 1 ? config.urls[0]! : [...config.urls],
|
||||
username,
|
||||
credential,
|
||||
};
|
||||
}
|
||||
|
||||
export function createTurnRestUsername(expirySeconds: number, sessionId: string): string {
|
||||
return `${Math.trunc(expirySeconds)}:${sessionId}`;
|
||||
}
|
||||
@@ -11,7 +11,8 @@ import { OpusEncoder } from "./opus-codec.js";
|
||||
import { normalizeTeamSpeakKickedReason } from "../errors.js";
|
||||
import type { TSClient, TSClientAvatar, TSDirectorySnapshot } from "./ts-client.js";
|
||||
import type { AudioFlowStats } from "./audio-stats.js";
|
||||
import type { WebRtcAudioSession } from "./webrtc-audio.js";
|
||||
import type { WebRtcAudioSession, WebRtcAudioOptions } from "./webrtc-audio.js";
|
||||
import type { VoiceBridgeOptions } from "./voice-bridge.js";
|
||||
|
||||
// Real loopback HTTP/WebSocket and native codec, with only the external SDK
|
||||
// replaced. This validates gateway wiring, not a connection to TeamSpeak.
|
||||
@@ -52,11 +53,19 @@ async function fixture(t: TestContext, overrides: {
|
||||
waitForFirstMessage?: boolean;
|
||||
createWorkspaceInvite?: import("./voice-bridge.js").VoiceBridgeOptions["createWorkspaceInvite"];
|
||||
connection?: Partial<import("./join-ticket.js").JoinTicketPayload>;
|
||||
webRtc?: WebRtcAudioOptions;
|
||||
voiceIce?: VoiceBridgeOptions["voiceIce"];
|
||||
headers?: Record<string, string>;
|
||||
} = {}) {
|
||||
const sdk = new TeamSpeakStub();
|
||||
overrides.configureSdk?.(sdk);
|
||||
const tickets = new JoinTicketStore();
|
||||
const bridge = new VoiceBridge({ joinTickets: tickets, createWorkspaceInvite: overrides.createWorkspaceInvite }, pino({ enabled: false }), undefined, {
|
||||
const bridge = new VoiceBridge({
|
||||
joinTickets: tickets,
|
||||
createWorkspaceInvite: overrides.createWorkspaceInvite,
|
||||
...(overrides.webRtc ? { webRtc: overrides.webRtc } : {}),
|
||||
...(overrides.voiceIce ? { voiceIce: overrides.voiceIce } : {}),
|
||||
}, pino({ enabled: false }), undefined, {
|
||||
createTeamSpeakClient: overrides.createTeamSpeakClient ?? (() => sdk as unknown as TSClient),
|
||||
...(overrides.createEncoder ? { createEncoder: overrides.createEncoder } : {}),
|
||||
});
|
||||
@@ -68,7 +77,7 @@ async function fixture(t: TestContext, overrides: {
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address !== "string");
|
||||
const ticket = tickets.create({ target: { host: "voice.example.invalid", port: 9987 }, nickname: "Test", serverPassword: "", ...overrides.connection });
|
||||
const socket = new WebSocket(`ws://127.0.0.1:${address.port}/ws/voice?ticket=${ticket}`);
|
||||
const socket = new WebSocket(`ws://127.0.0.1:${address.port}/ws/voice?ticket=${ticket}`, overrides.headers ? { headers: overrides.headers } : undefined);
|
||||
const messages: Array<{ data: Buffer; binary: boolean }> = [];
|
||||
socket.on("message", (data, binary) => messages.push({ data: data as Buffer, binary }));
|
||||
const first = once(socket, "message");
|
||||
@@ -107,6 +116,18 @@ function waitForMessage<T extends Record<string, unknown>>(socket: WebSocket, ty
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForBufferedMessage<T extends Record<string, unknown>>(
|
||||
messages: Array<{ data: Buffer; binary: boolean }>,
|
||||
type: string,
|
||||
): Promise<T> {
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
const found = messages.find(message => !message.binary && (JSON.parse(message.data.toString()) as { type?: string }).type === type);
|
||||
if (found) return JSON.parse(found.data.toString()) as T;
|
||||
await nextTurn();
|
||||
}
|
||||
throw new Error(`message ${type} was not published`);
|
||||
}
|
||||
|
||||
// The native Opus codec is unavailable in some environments. These tests only
|
||||
// exercise gateway wiring, so the encoder is stubbed out.
|
||||
const stubEncoder = () => ({ encode: () => Buffer.alloc(0), dispose: () => {} });
|
||||
@@ -153,6 +174,96 @@ test("server identity lookup waits until the directory sync publishes the connec
|
||||
assert.ok(f.bridge.getActiveCount() > 0);
|
||||
});
|
||||
|
||||
test("a direct connection keeps the legacy audio profile and the original media path", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t, {
|
||||
webRtc: { enabled: true, stunServer: "stun:stun.example.invalid:3478" },
|
||||
voiceIce: {
|
||||
servers: [],
|
||||
transportPolicy: "all",
|
||||
gatewayTransportPolicy: "all",
|
||||
profile: "auto",
|
||||
opusWebSocket: false,
|
||||
jitterMaxMs: 300,
|
||||
},
|
||||
});
|
||||
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
|
||||
assert.equal(connected.voiceProfile, "legacy");
|
||||
assert.equal(connected.webrtcAvailable, true);
|
||||
assert.equal(connected.webrtcUnavailableReason, undefined);
|
||||
assert.equal(connected.audioFrameVersion, undefined);
|
||||
assert.equal(connected.audioUplinkCodecs, undefined);
|
||||
assert.equal(connected.audioJitterMaxMs, undefined);
|
||||
assert.equal(connected.voiceIceTransportPolicy, "all");
|
||||
assert.deepEqual(connected.voiceIceServers, [{ urls: "stun:stun.example.invalid:3478" }]);
|
||||
});
|
||||
|
||||
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 },
|
||||
voiceIce: {
|
||||
servers: [],
|
||||
transportPolicy: "all",
|
||||
gatewayTransportPolicy: "all",
|
||||
profile: "adaptive",
|
||||
opusWebSocket: true,
|
||||
jitterMaxMs: 300,
|
||||
},
|
||||
});
|
||||
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
|
||||
assert.equal(connected.voiceProfile, "adaptive");
|
||||
assert.equal(connected.webrtcAvailable, true);
|
||||
assert.equal(connected.audioFrameVersion, 2);
|
||||
assert.deepEqual(connected.audioUplinkCodecs, ["pcm", "opus"]);
|
||||
assert.equal(connected.audioJitterMaxMs, 300);
|
||||
});
|
||||
|
||||
test("a Cloudflare request opts into adaptive audio without inventing an ICE host", { 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,
|
||||
},
|
||||
headers: { "cf-ray": "test-ray" },
|
||||
});
|
||||
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
|
||||
assert.equal(connected.voiceProfile, "adaptive");
|
||||
assert.equal(connected.webrtcAvailable, false);
|
||||
assert.equal(connected.webrtcUnavailableReason, "NO_MEDIA_PATH");
|
||||
assert.equal(connected.audioFrameVersion, 2);
|
||||
assert.deepEqual(connected.audioUplinkCodecs, ["pcm"]);
|
||||
assert.equal(connected.audioJitterMaxMs, 300);
|
||||
assert.deepEqual(connected.voiceIceServers, []);
|
||||
});
|
||||
|
||||
|
||||
test("a voice ICE getter is resolved when a new connection is accepted", { timeout: 5_000 }, async t => {
|
||||
let calls = 0;
|
||||
const f = await fixture(t, {
|
||||
webRtc: { enabled: true },
|
||||
voiceIce: () => {
|
||||
calls++;
|
||||
return {
|
||||
servers: [],
|
||||
transportPolicy: "all",
|
||||
gatewayTransportPolicy: "all",
|
||||
profile: "auto",
|
||||
opusWebSocket: false,
|
||||
jitterMaxMs: 300,
|
||||
};
|
||||
},
|
||||
headers: { "cf-ray": "console-refresh-ray" },
|
||||
});
|
||||
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
|
||||
assert.equal(calls, 1);
|
||||
assert.equal(connected.voiceProfile, "adaptive");
|
||||
});
|
||||
|
||||
|
||||
test("a TeamSpeak drop before the directory sync fails the connection instead of stalling", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t, {
|
||||
waitForFirstMessage: false,
|
||||
|
||||
@@ -3,7 +3,7 @@ import test from "node:test";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import type { IncomingMessage } from "node:http";
|
||||
import pino from "pino";
|
||||
import { VoiceBridge, createTrustedProxies, resolveClientIp, resolveWebRtcPublicHost } from "./voice-bridge.js";
|
||||
import { VoiceBridge, createTrustedProxies, isCloudflareRequest, resolveClientIp, resolveWebRtcPublicHost } from "./voice-bridge.js";
|
||||
import { JoinTicketStore } from "./join-ticket.js";
|
||||
import { createAudioFlowStats } from "./audio-stats.js";
|
||||
import { SessionAudioTransport } from "./session-audio.js";
|
||||
@@ -40,6 +40,8 @@ function fixture(webRtc = { enabled: true } as import("./webrtc-audio.js").WebRt
|
||||
tsClient: { isConnected: () => true, setInputMuted: async (_muted: boolean) => {}, setAccompanimentActive: async (_active: boolean) => {}, sendVoice: () => { forwarded++; }, sendWhisper: () => { forwarded++; } },
|
||||
whisperActive: false, whisperTargetIds: new Set<number>(), audio: createAudioFlowStats(),
|
||||
audioTransport: null as SessionAudioTransport | null,
|
||||
voiceIceServers: [], voiceIceTransportPolicy: "all" as const, voiceIceGatewayTransportPolicy: "all" as const,
|
||||
voiceProfile: "legacy" as const,
|
||||
};
|
||||
let forwarded = 0;
|
||||
let configurePeer = (_peer: PeerStub): void => {};
|
||||
@@ -62,6 +64,7 @@ function fixture(webRtc = { enabled: true } as import("./webrtc-audio.js").WebRt
|
||||
isCurrent: () => bridge.entries.get(entry.id) === entry,
|
||||
isReady: () => entry.session.state === "connected", selfId: () => 1,
|
||||
peer: () => entry.webrtc, whisperTargets: () => null, sendJson: message => messages.push(message),
|
||||
pacing: false,
|
||||
}, { encode: frame => frame, dispose() {} });
|
||||
const offer = (sdp: string) => bridge.handleWebRtcOffer(entry, { type: "offer", sdp }, message => messages.push(message));
|
||||
return { bridge, entry, peers, messages, offer, forwarded: () => forwarded, configure: (callback: typeof configurePeer) => { configurePeer = callback; } };
|
||||
@@ -174,6 +177,27 @@ test("WebRTC candidates use the voice gateway host when the page Origin belongs
|
||||
assert.equal(resolveWebRtcPublicHost(request), "voice-relay.example.com");
|
||||
});
|
||||
|
||||
test("Cloudflare headers only classify a request from a trusted proxy", () => {
|
||||
const trusted = createTrustedProxies(["127.0.0.1", "198.51.100.0/24"]);
|
||||
const headers = { "cf-ray": "abc123-SJC", "cf-connecting-ip": "203.0.113.10" };
|
||||
assert.equal(isCloudflareRequest(ipRequest("192.0.2.7", headers), trusted), false);
|
||||
assert.equal(isCloudflareRequest(ipRequest("127.0.0.1", headers), trusted), true);
|
||||
assert.equal(isCloudflareRequest(ipRequest("198.51.100.8", { "cdn-loop": "one, cloudflare two" }), trusted), true);
|
||||
assert.equal(isCloudflareRequest(ipRequest("198.51.100.8", { "cdn-loop": "one, other two" }), trusted), false);
|
||||
});
|
||||
|
||||
test("a Cloudflare-proxied request never falls back to the edge hostname for ICE", () => {
|
||||
const request = {
|
||||
headers: {
|
||||
host: "voice.example.com",
|
||||
"cf-ray": "abc123-SJC",
|
||||
"cf-connecting-ip": "203.0.113.10",
|
||||
},
|
||||
} as unknown as IncomingMessage;
|
||||
assert.equal(resolveWebRtcPublicHost(request, { allowHostFallback: false }), undefined);
|
||||
assert.equal(resolveWebRtcPublicHost(request), "voice.example.com");
|
||||
});
|
||||
|
||||
test("initial accompaniment updates TeamSpeak before creating a muted mixer and resets on stop", async () => {
|
||||
const f = fixture();
|
||||
const inputs: Array<[string, boolean]> = [];
|
||||
@@ -234,6 +258,18 @@ test("an unset media override still uses a literal request host", async () => {
|
||||
assert.deepEqual(f.peers[0].options.publicAddresses, ["192.0.2.10"]);
|
||||
});
|
||||
|
||||
test("TURN servers are passed to werift while direct-first remains the default policy", async () => {
|
||||
const f = fixture({ enabled: true, publicHost: "192.0.2.20" });
|
||||
Object.assign(f.entry, {
|
||||
webrtcPublicHost: "192.0.2.20",
|
||||
voiceIceServers: [{ urls: "turns:turn.example.com:443?transport=tcp", username: "u", credential: "c" }],
|
||||
voiceIceGatewayTransportPolicy: "all" as const,
|
||||
});
|
||||
await f.offer("turn");
|
||||
assert.deepEqual(f.peers[0].options.iceServers, f.entry.voiceIceServers);
|
||||
assert.equal(f.peers[0].options.iceTransportPolicy, "all");
|
||||
});
|
||||
|
||||
function ipRequest(remoteAddress: string | undefined, headers: Record<string, string> = {}): IncomingMessage {
|
||||
return { headers, socket: { remoteAddress } } as unknown as IncomingMessage;
|
||||
}
|
||||
|
||||
@@ -28,6 +28,15 @@ import { normalizeScreenShareIceServers, parseScreenShareMessage, type ScreenSha
|
||||
import { OpusEncoder } from "./opus-codec.js";
|
||||
import { avatarDataUrl } from "./directory-view.js";
|
||||
import type { PluginParticipant } from "../shared/plugins.js";
|
||||
import {
|
||||
hasVoiceTurnServer,
|
||||
normalizeVoiceIceServers,
|
||||
normalizeVoiceIceTransportPolicy,
|
||||
type VoiceIceServer,
|
||||
type VoiceIceTransportPolicy,
|
||||
} from "../shared/voice-ice.js";
|
||||
import { resolveVoiceIceServers, type VoiceIceConfig } from "./voice-ice-config.js";
|
||||
import { resolveVoiceProfile, type VoiceProfile } from "../shared/voice-profile.js";
|
||||
|
||||
const HEARTBEAT_INTERVAL_MS = 30_000;
|
||||
const MAX_MISSED_HEARTBEATS = 2;
|
||||
@@ -54,6 +63,8 @@ export interface VoiceBridgeOptions {
|
||||
pluginRuntimeEnabled?: boolean;
|
||||
joinTickets: JoinTicketStore;
|
||||
webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions);
|
||||
/** TURN / ICE deployment configuration; resolved for each new connection. */
|
||||
voiceIce?: VoiceIceConfig | (() => VoiceIceConfig);
|
||||
screenShareIceServers?: ScreenShareIceServer[] | (() => ScreenShareIceServer[]);
|
||||
acceleration?: ConfiguredAccelerationRelay[] | (() => ConfiguredAccelerationRelay[]);
|
||||
accelerationName?: string | (() => string | undefined);
|
||||
@@ -97,6 +108,10 @@ interface WebClientEntry extends SessionDirectoryState {
|
||||
acceleration?: AccelerationRelayOptions;
|
||||
identityLeaseKey?: string;
|
||||
webrtcPublicHost?: string;
|
||||
voiceProfile: VoiceProfile;
|
||||
voiceIceServers: VoiceIceServer[];
|
||||
voiceIceTransportPolicy: VoiceIceTransportPolicy;
|
||||
voiceIceGatewayTransportPolicy: VoiceIceTransportPolicy;
|
||||
events: SessionEventCoordinator | null;
|
||||
eventLog: ServerEvent[];
|
||||
audioTransport: SessionAudioTransport | null;
|
||||
@@ -178,7 +193,13 @@ export class VoiceBridge {
|
||||
return;
|
||||
}
|
||||
const clientIp = resolveClientIp(req, this.trustedProxies);
|
||||
const webrtcPublicHost = resolveWebRtcPublicHost(req);
|
||||
// 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 webrtcPublicHost = resolveWebRtcPublicHost(req, { allowHostFallback: !cloudflareRequest });
|
||||
const voiceIce = this.getVoiceIceConfig();
|
||||
const voiceProfile = resolveVoiceProfile(voiceIce?.profile ?? "auto", cloudflareRequest);
|
||||
let identity;
|
||||
try {
|
||||
identity = connection.identity ? parseIdentity(connection.identity) : undefined;
|
||||
@@ -190,6 +211,9 @@ export class VoiceBridge {
|
||||
return;
|
||||
}
|
||||
const entryId = `w-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
|
||||
const voiceIceServers = this.buildVoiceIceServers(entryId, voiceIce);
|
||||
const voiceIceTransportPolicy = normalizeVoiceIceTransportPolicy(voiceIce?.transportPolicy);
|
||||
const voiceIceGatewayTransportPolicy = normalizeVoiceIceTransportPolicy(voiceIce?.gatewayTransportPolicy);
|
||||
let entry: WebClientEntry | null = null;
|
||||
const session = this.sessionManager.admit(entryId, async (reason) => {
|
||||
if (entry) await this.cleanupEntry(entry, reason);
|
||||
@@ -247,6 +271,10 @@ export class VoiceBridge {
|
||||
...(acceleration ? { acceleration } : {}),
|
||||
...(identityLeaseKey ? { identityLeaseKey } : {}),
|
||||
...(webrtcPublicHost ? { webrtcPublicHost } : {}),
|
||||
voiceProfile,
|
||||
voiceIceServers,
|
||||
voiceIceTransportPolicy,
|
||||
voiceIceGatewayTransportPolicy,
|
||||
channelTree: [],
|
||||
members: new Map(),
|
||||
avatarCache: new Map(),
|
||||
@@ -281,6 +309,7 @@ export class VoiceBridge {
|
||||
peer: () => entry!.webrtc,
|
||||
whisperTargets: () => entry!.whisperActive ? [...entry!.whisperTargetIds] : null,
|
||||
sendJson: message => sendJson(message),
|
||||
pacing: entry!.voiceProfile === "adaptive",
|
||||
}, this.dependencies.createEncoder?.() ?? new OpusEncoder(48000, 1));
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({ err: error, entryId }, "Could not create Opus encoder");
|
||||
@@ -328,6 +357,13 @@ export class VoiceBridge {
|
||||
}
|
||||
session.transition("connected");
|
||||
if (this.options.pluginRuntimeEnabled) entry!.pluginSession = randomBytes(32).toString("base64url");
|
||||
const webRtc = this.getWebRtcOptions();
|
||||
const hasDirectMediaPath = Boolean(webRtc?.publicHost || entry!.webrtcPublicHost);
|
||||
const hasRelayMediaPath = hasVoiceTurnServer(entry!.voiceIceServers);
|
||||
const webRtcAvailable = webRtc?.enabled === true && (hasDirectMediaPath || hasRelayMediaPath);
|
||||
const webRtcUnavailableReason = webRtc?.enabled !== true
|
||||
? "DISABLED" as const
|
||||
: webRtcAvailable ? undefined : "NO_MEDIA_PATH" as const;
|
||||
sendJson({
|
||||
type: "connected",
|
||||
tsClientId: events.selfId,
|
||||
@@ -335,8 +371,19 @@ export class VoiceBridge {
|
||||
serverEventLog: entry!.eventLog,
|
||||
whisperTargetIds: [...entry!.whisperTargetIds],
|
||||
whisperActive: entry!.whisperActive,
|
||||
webrtcAvailable: this.getWebRtcOptions()?.enabled === true,
|
||||
webRtcStunServer: this.getWebRtcOptions()?.stunServer ?? "",
|
||||
webrtcAvailable: webRtcAvailable,
|
||||
...(webRtcUnavailableReason ? { webrtcUnavailableReason: webRtcUnavailableReason } : {}),
|
||||
webRtcStunServer: webRtc?.stunServer ?? "",
|
||||
voiceProfile: entry!.voiceProfile,
|
||||
voiceIceServers: entry!.voiceIceServers,
|
||||
voiceIceTransportPolicy: entry!.voiceIceTransportPolicy,
|
||||
...(entry!.voiceProfile === "adaptive" ? {
|
||||
audioFrameVersion: 2 as const,
|
||||
audioUplinkCodecs: voiceIce?.opusWebSocket === true
|
||||
? ["pcm", "opus"] as ("pcm" | "opus")[]
|
||||
: ["pcm"] as ("pcm" | "opus")[],
|
||||
audioJitterMaxMs: voiceIce?.jitterMaxMs ?? 300,
|
||||
} : {}),
|
||||
screenShareIceServers: this.getScreenShareIceServers(),
|
||||
accelerated: Boolean(entry!.acceleration),
|
||||
...(entry!.pluginSession ? { pluginSession: entry!.pluginSession } : {}),
|
||||
@@ -838,6 +885,18 @@ export class VoiceBridge {
|
||||
return typeof configured === "function" ? configured() : configured;
|
||||
}
|
||||
|
||||
private getVoiceIceConfig(): VoiceIceConfig | undefined {
|
||||
const configured = this.options.voiceIce;
|
||||
return typeof configured === "function" ? configured() : configured;
|
||||
}
|
||||
|
||||
private buildVoiceIceServers(entryId: string, config = this.getVoiceIceConfig()): VoiceIceServer[] {
|
||||
const servers = resolveVoiceIceServers(config, entryId);
|
||||
const stunServer = this.getWebRtcOptions()?.stunServer;
|
||||
if (stunServer) servers.push({ urls: stunServer });
|
||||
return normalizeVoiceIceServers(servers);
|
||||
}
|
||||
|
||||
private getScreenShareIceServers(): ScreenShareIceServer[] {
|
||||
const configured = this.options.screenShareIceServers;
|
||||
const servers = typeof configured === "function" ? configured() : configured;
|
||||
@@ -900,12 +959,25 @@ export class VoiceBridge {
|
||||
try {
|
||||
const publicAddresses = await resolveVoiceMediaAddresses(config.publicHost || entry.webrtcPublicHost, config.ipv6Enabled === true);
|
||||
if (!isCurrent()) return;
|
||||
const iceServers = config.iceServers?.length ? config.iceServers : entry.voiceIceServers;
|
||||
const configuredGatewayPolicy = config.iceTransportPolicy ?? entry.voiceIceGatewayTransportPolicy;
|
||||
// Relay-only gathering without a TURN server would leave the gateway
|
||||
// with no candidates at all. Fall back to direct gathering instead.
|
||||
const gatewayPolicy = configuredGatewayPolicy === "relay" && !hasVoiceTurnServer(iceServers)
|
||||
? "all"
|
||||
: configuredGatewayPolicy;
|
||||
if (configuredGatewayPolicy === "relay" && gatewayPolicy === "all") {
|
||||
this.logger.warn({ entryId: entry.id }, "Relay-only WebRTC gateway policy has no TURN server; using direct candidates");
|
||||
}
|
||||
peer = this.createWebRtcSession({
|
||||
connectionId: entry.id,
|
||||
publicAddresses,
|
||||
...(config.publicHost || entry.webrtcPublicHost ? { publicHost: config.publicHost || entry.webrtcPublicHost } : {}),
|
||||
ipv6Enabled: config.ipv6Enabled,
|
||||
stunServer: config.stunServer,
|
||||
iceServers,
|
||||
iceTransportPolicy: gatewayPolicy,
|
||||
profile: entry.voiceProfile,
|
||||
udpPortRange: config.udpPortRange,
|
||||
logger: this.logger,
|
||||
microphoneMuted: muted,
|
||||
@@ -938,7 +1010,28 @@ export class VoiceBridge {
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveWebRtcPublicHost(request: IncomingMessage): string | undefined {
|
||||
/**
|
||||
* Headers Cloudflare adds to proxied requests (including Tunnel origins).
|
||||
* Only a configured trusted proxy may assert that a request came through
|
||||
* Cloudflare; otherwise a direct client could spoof the adaptive audio path
|
||||
* and suppress the legacy Host-based ICE fallback.
|
||||
*/
|
||||
export function isCloudflareRequest(request: IncomingMessage, trustedProxies: BlockList): boolean {
|
||||
const direct = normalizeClientIp(request.socket.remoteAddress);
|
||||
if (!direct || !isTrustedProxy(direct, trustedProxies)) return false;
|
||||
const cdnLoop = firstHeader(request.headers["cdn-loop"]);
|
||||
return Boolean(
|
||||
firstHeader(request.headers["cf-ray"])
|
||||
|| firstHeader(request.headers["cf-connecting-ip"])
|
||||
|| (cdnLoop && /\bcloudflare\b/i.test(cdnLoop))
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveWebRtcPublicHost(
|
||||
request: IncomingMessage,
|
||||
options: { allowHostFallback?: boolean } = {},
|
||||
): string | undefined {
|
||||
if (options.allowHostFallback === false) return undefined;
|
||||
const origin = firstHeader(request.headers.origin);
|
||||
const forwardedHost = firstHeader(request.headers["x-forwarded-host"]);
|
||||
const directHost = firstHeader(request.headers.host);
|
||||
|
||||
@@ -6,6 +6,7 @@ import { parseDelegatedVoiceSession, VoiceGatewayRequestVerifier } from "./voice
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { WebRtcAudioOptions } from "./webrtc-audio.js";
|
||||
import type { ScreenShareIceServer } from "./screen-share.js";
|
||||
import type { VoiceIceConfig } from "./voice-ice-config.js";
|
||||
|
||||
export interface VoiceGatewayServerOptions {
|
||||
workspaceInvites?: import("./workspace-invites.js").WorkspaceInvites;
|
||||
@@ -14,6 +15,7 @@ export interface VoiceGatewayServerOptions {
|
||||
sharedToken: string;
|
||||
logger: Logger;
|
||||
webRtc: WebRtcAudioOptions;
|
||||
voiceIce?: VoiceIceConfig;
|
||||
screenShareIceServers?: ScreenShareIceServer[];
|
||||
trustedProxies?: readonly string[];
|
||||
}
|
||||
@@ -33,6 +35,7 @@ export function createVoiceGatewayServer(options: VoiceGatewayServerOptions): Vo
|
||||
joinTickets: tickets,
|
||||
...(options.workspaceInvites ? { createWorkspaceInvite: (credentials, minutes) => options.workspaceInvites!.create(credentials, minutes) } : {}),
|
||||
webRtc: options.webRtc,
|
||||
voiceIce: options.voiceIce,
|
||||
screenShareIceServers: options.screenShareIceServers,
|
||||
trustedProxies: options.trustedProxies,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { readVoiceIceConfig, resolveVoiceIceServers } from "./voice-ice-config.js";
|
||||
|
||||
test("voice ICE env parses static servers and direct-first defaults", () => {
|
||||
const config = readVoiceIceConfig({
|
||||
WEBSPEAK_VOICE_ICE_SERVERS: '[{"urls":"stun:stun.example.com:3478"}]',
|
||||
});
|
||||
assert.deepEqual(config.servers, [{ urls: "stun:stun.example.com:3478" }]);
|
||||
assert.equal(config.transportPolicy, "all");
|
||||
assert.equal(config.gatewayTransportPolicy, "all");
|
||||
assert.equal(config.profile, "auto");
|
||||
assert.equal(config.opusWebSocket, false);
|
||||
assert.equal(config.jitterMaxMs, 300);
|
||||
assert.equal(config.turnRest, undefined);
|
||||
});
|
||||
|
||||
test("voice profile is explicit-only for Opus and can force legacy or adaptive", () => {
|
||||
assert.equal(readVoiceIceConfig({}).profile, "auto");
|
||||
assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_PROFILE: "legacy" }).profile, "legacy");
|
||||
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);
|
||||
});
|
||||
|
||||
test("TURN REST env mints a per-session credential and keeps direct-first policy", () => {
|
||||
const config = readVoiceIceConfig({
|
||||
WEBSPEAK_TURN_REST_URLS: "turns:turn.example.com:443?transport=tcp,turn:turn.example.com:3478?transport=udp",
|
||||
WEBSPEAK_TURN_REST_SECRET: "a-test-secret-with-enough-length",
|
||||
WEBSPEAK_TURN_REST_TTL_SECONDS: "3600",
|
||||
WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY: "relay",
|
||||
});
|
||||
assert.equal(config.transportPolicy, "relay");
|
||||
assert.ok(config.turnRest);
|
||||
const servers = resolveVoiceIceServers(config, "session-a", 1_000_000);
|
||||
assert.equal(servers.length, 1);
|
||||
assert.match(servers[0]!.username!, /^[0-9]+:session-a$/);
|
||||
assert.ok(servers[0]!.credential);
|
||||
});
|
||||
|
||||
test("short TURN secret is ignored instead of starting a broken relay", () => {
|
||||
const config = readVoiceIceConfig({
|
||||
WEBSPEAK_TURN_REST_URLS: "turns:turn.example.com:443",
|
||||
WEBSPEAK_TURN_REST_SECRET: "short",
|
||||
});
|
||||
assert.equal(config.turnRest, undefined);
|
||||
assert.deepEqual(resolveVoiceIceServers(config, "x"), []);
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import {
|
||||
hasVoiceTurnServer,
|
||||
normalizeVoiceIceServers,
|
||||
normalizeVoiceIceTransportPolicy,
|
||||
VOICE_JITTER_DEFAULT_MS,
|
||||
VOICE_JITTER_MAX_MS,
|
||||
VOICE_JITTER_MIN_MS,
|
||||
VOICE_TURN_MIN_SECRET_LENGTH,
|
||||
VOICE_TURN_TTL_DEFAULT_SECONDS,
|
||||
VOICE_TURN_TTL_MAX_SECONDS,
|
||||
VOICE_TURN_TTL_MIN_SECONDS,
|
||||
type VoiceIceServer,
|
||||
type VoiceIceTransportPolicy,
|
||||
} from "../shared/voice-ice.js";
|
||||
import { createTurnRestCredential, type TurnRestConfig } from "./turn-credentials.js";
|
||||
import { normalizeVoiceProfileSetting, type VoiceProfileSetting } from "../shared/voice-profile.js";
|
||||
|
||||
export interface VoiceIceConfig {
|
||||
servers: VoiceIceServer[];
|
||||
turnRest?: TurnRestConfig;
|
||||
/** Browser policy; keep `all` for direct UDP-first deployments. */
|
||||
transportPolicy: VoiceIceTransportPolicy;
|
||||
/** werift policy; use `relay` only when the gateway itself is behind NAT. */
|
||||
gatewayTransportPolicy: VoiceIceTransportPolicy;
|
||||
/** Per-connection audio profile: direct traffic defaults to legacy. */
|
||||
profile: VoiceProfileSetting;
|
||||
opusWebSocket: boolean;
|
||||
jitterMaxMs: number;
|
||||
}
|
||||
|
||||
export interface VoiceIceSettings {
|
||||
servers: VoiceIceServer[];
|
||||
transportPolicy: VoiceIceTransportPolicy;
|
||||
gatewayTransportPolicy: VoiceIceTransportPolicy;
|
||||
profile: VoiceProfileSetting;
|
||||
opusWebSocket: boolean;
|
||||
jitterMaxMs: number;
|
||||
}
|
||||
|
||||
/** Baseline used when neither the console nor the environment configures a value. */
|
||||
export const DEFAULT_VOICE_ICE_CONFIG: VoiceIceConfig = {
|
||||
servers: [],
|
||||
transportPolicy: "all",
|
||||
gatewayTransportPolicy: "all",
|
||||
profile: "auto",
|
||||
opusWebSocket: false,
|
||||
jitterMaxMs: VOICE_JITTER_DEFAULT_MS,
|
||||
};
|
||||
|
||||
function parseBoolean(value: string | undefined, fallback: boolean): boolean {
|
||||
if (value === undefined) return fallback;
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (!normalized) return fallback;
|
||||
return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
|
||||
}
|
||||
|
||||
function parseInteger(value: string | undefined, fallback: number, min: number, max: number): number {
|
||||
if (!value?.trim()) return fallback;
|
||||
const parsed = Number(value);
|
||||
if (!Number.isInteger(parsed)) return fallback;
|
||||
return Math.max(min, Math.min(max, parsed));
|
||||
}
|
||||
|
||||
function parseStaticServers(raw: string | undefined): VoiceIceServer[] {
|
||||
const value = raw?.trim();
|
||||
if (!value) return [];
|
||||
if (value.startsWith("[") || value.startsWith("{")) {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (Array.isArray(parsed)) return normalizeVoiceIceServers(parsed);
|
||||
if (parsed && typeof parsed === "object") return normalizeVoiceIceServers([parsed]);
|
||||
return [];
|
||||
} catch {
|
||||
// Fall through to the convenient comma/space-separated STUN form.
|
||||
}
|
||||
}
|
||||
return normalizeVoiceIceServers(value.split(/[\s,]+/).filter(Boolean).map((urls) => ({ urls })));
|
||||
}
|
||||
|
||||
function parseTurnRestUrls(raw: string | undefined): string[] {
|
||||
if (!raw?.trim()) return [];
|
||||
// Environment parsing stays lenient: one bad entry must not disable a
|
||||
// previously working TURN deployment during an upgrade.
|
||||
const urls = raw.split(/[\s,]+/).filter(Boolean).flatMap((token) => {
|
||||
const [server] = normalizeVoiceIceServers([{ urls: token }]);
|
||||
if (!server) return [];
|
||||
const candidates = Array.isArray(server.urls) ? server.urls : [server.urls];
|
||||
return candidates.filter((url) => /^turns?:/i.test(url));
|
||||
});
|
||||
return [...new Set(urls)].slice(0, 8);
|
||||
}
|
||||
|
||||
export function readVoiceIceConfig(env: NodeJS.ProcessEnv = process.env): VoiceIceConfig {
|
||||
const servers = parseStaticServers(env.WEBSPEAK_VOICE_ICE_SERVERS);
|
||||
const turnUrls = parseTurnRestUrls(env.WEBSPEAK_TURN_REST_URLS);
|
||||
const secret = env.WEBSPEAK_TURN_REST_SECRET?.trim() ?? "";
|
||||
const ttlSeconds = parseInteger(env.WEBSPEAK_TURN_REST_TTL_SECONDS, VOICE_TURN_TTL_DEFAULT_SECONDS, VOICE_TURN_TTL_MIN_SECONDS, VOICE_TURN_TTL_MAX_SECONDS);
|
||||
const turnRest = turnUrls.length && secret.length >= VOICE_TURN_MIN_SECRET_LENGTH
|
||||
? { urls: turnUrls, secret, ttlSeconds }
|
||||
: undefined;
|
||||
return {
|
||||
...DEFAULT_VOICE_ICE_CONFIG,
|
||||
servers,
|
||||
...(turnRest ? { turnRest } : {}),
|
||||
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),
|
||||
jitterMaxMs: parseInteger(env.WEBSPEAK_VOICE_JITTER_MAX_MS, VOICE_JITTER_DEFAULT_MS, VOICE_JITTER_MIN_MS, VOICE_JITTER_MAX_MS),
|
||||
};
|
||||
}
|
||||
|
||||
/** Build the per-connection list, minting one short-lived TURN credential. */
|
||||
export function resolveVoiceIceServers(
|
||||
config: VoiceIceConfig | undefined,
|
||||
sessionId: string,
|
||||
nowMs = Date.now(),
|
||||
): VoiceIceServer[] {
|
||||
if (!config) return [];
|
||||
const servers = [...config.servers];
|
||||
if (config.turnRest) {
|
||||
servers.push(createTurnRestCredential(config.turnRest, sessionId, nowMs));
|
||||
}
|
||||
return normalizeVoiceIceServers(servers);
|
||||
}
|
||||
|
||||
export function voiceConfigSettings(config: VoiceIceConfig): VoiceIceSettings {
|
||||
return {
|
||||
servers: normalizeVoiceIceServers(config.servers),
|
||||
transportPolicy: config.transportPolicy,
|
||||
gatewayTransportPolicy: config.gatewayTransportPolicy,
|
||||
profile: config.profile,
|
||||
opusWebSocket: config.opusWebSocket,
|
||||
jitterMaxMs: config.jitterMaxMs,
|
||||
};
|
||||
}
|
||||
|
||||
export { hasVoiceTurnServer };
|
||||
@@ -109,6 +109,89 @@ for (const scenario of ["silence gaps", "alternating speakers", "volume changes"
|
||||
});
|
||||
}
|
||||
|
||||
test("WebRTC marks only the first audible RTP packet after a gap", () => {
|
||||
const packets: RtpPacket[] = [];
|
||||
const session = Object.assign(Object.create(WebRtcAudioSession.prototype), {
|
||||
closed: false,
|
||||
outgoingPayloadType: 111,
|
||||
sequenceNumber: 0,
|
||||
timestamp: 0,
|
||||
ssrc: 7,
|
||||
lastAudioRtpAt: null as number | null,
|
||||
lastEgressRtpAt: null as number | null,
|
||||
outgoingTrack: { writeRtp(packet: RtpPacket) { packets.push(packet); } },
|
||||
stats: { webrtcEgressRtpFrames: 0, webrtcEgressRtpMaxGapMs: 0, webrtcEgressRtpFirstAt: null, webrtcEgressRtpLastAt: null },
|
||||
}) as unknown as WebRtcAudioSession;
|
||||
const send = (session as unknown as { sendRtpAudio(payload: Buffer, hasAudio: boolean): void }).sendRtpAudio.bind(session);
|
||||
send(Buffer.from([1]), true);
|
||||
send(Buffer.from([2]), true);
|
||||
send(Buffer.from([3]), false);
|
||||
assert.deepEqual(packets.map(packet => packet.header.marker), [true, false, false]);
|
||||
(session as unknown as { lastAudioRtpAt: number | null }).lastAudioRtpAt = performance.now() - 50;
|
||||
send(Buffer.from([4]), true);
|
||||
send(Buffer.from([5]), true);
|
||||
assert.deepEqual(packets.map(packet => packet.header.marker), [true, false, false, true, false]);
|
||||
});
|
||||
|
||||
test("legacy RTP pacing keeps the original marker on every packet", () => {
|
||||
const packets: RtpPacket[] = [];
|
||||
const session = Object.assign(Object.create(WebRtcAudioSession.prototype), {
|
||||
closed: false,
|
||||
outgoingPayloadType: 111,
|
||||
sequenceNumber: 0,
|
||||
timestamp: 0,
|
||||
ssrc: 7,
|
||||
lastAudioRtpAt: null as number | null,
|
||||
lastEgressRtpAt: null as number | null,
|
||||
rtpMarkerAlways: true,
|
||||
outgoingTrack: { writeRtp(packet: RtpPacket) { packets.push(packet); } },
|
||||
stats: { webrtcEgressRtpFrames: 0, webrtcEgressRtpMaxGapMs: 0, webrtcEgressRtpFirstAt: null, webrtcEgressRtpLastAt: null },
|
||||
}) as unknown as WebRtcAudioSession;
|
||||
const send = (session as unknown as { sendRtpAudio(payload: Buffer, hasAudio: boolean): void }).sendRtpAudio.bind(session);
|
||||
send(Buffer.from([1]), true);
|
||||
send(Buffer.from([2]), false);
|
||||
assert.deepEqual(packets.map(packet => packet.header.marker), [true, true]);
|
||||
});
|
||||
|
||||
test("legacy WebRTC profile selects the original bounded mixer constants", async t => {
|
||||
const session = new WebRtcAudioSession({ connectionId: "legacy-mixer", logger: pino({ enabled: false }), onVoiceFrame() {}, onVoiceActivity() {} });
|
||||
t.after(() => session.close());
|
||||
const internals = session as unknown as { mixerQueueFrames: number; maxMixerFrameAgeMs: number; mixerQueueAfterLateTick: number; rtpMarkerAlways: boolean };
|
||||
assert.equal(internals.mixerQueueFrames, 4);
|
||||
assert.equal(internals.maxMixerFrameAgeMs, 80);
|
||||
assert.equal(internals.mixerQueueAfterLateTick, 1);
|
||||
assert.equal(internals.rtpMarkerAlways, true);
|
||||
});
|
||||
|
||||
test("adaptive WebRTC profile keeps the longer queue and corrected marker", async t => {
|
||||
const session = new WebRtcAudioSession({ connectionId: "adaptive-mixer", profile: "adaptive", logger: pino({ enabled: false }), onVoiceFrame() {}, onVoiceActivity() {} });
|
||||
t.after(() => session.close());
|
||||
const internals = session as unknown as { mixerQueueFrames: number; maxMixerFrameAgeMs: number; mixerQueueAfterLateTick: number; rtpMarkerAlways: boolean };
|
||||
assert.equal(internals.mixerQueueFrames, 6);
|
||||
assert.equal(internals.maxMixerFrameAgeMs, 200);
|
||||
assert.equal(internals.mixerQueueAfterLateTick, 2);
|
||||
assert.equal(internals.rtpMarkerAlways, false);
|
||||
});
|
||||
|
||||
test("late-tick trimming keeps legacy queue bounds and clears adaptive stale frames", () => {
|
||||
for (const [profile, queueAfterLateTick, frameAgeMs, frameCount, expectedRemaining, expectedDropped] of [
|
||||
["legacy", 1, 0, 3, 1, 2],
|
||||
["legacy", 1, 100, 1, 0, 1],
|
||||
["adaptive", 2, 100, 3, 0, 3],
|
||||
] as const) {
|
||||
const queue = Array.from({ length: frameCount }, () => ({ pcm: Buffer.alloc(4), receivedAt: performance.now() - frameAgeMs - 1 }));
|
||||
const session = Object.assign(Object.create(WebRtcAudioSession.prototype), {
|
||||
pendingFrames: new Map([["speaker", queue]]),
|
||||
mixerQueueAfterLateTick: queueAfterLateTick,
|
||||
maxMixerFrameAgeMs: 100,
|
||||
stats: { webrtcQueueDroppedFrames: 0 },
|
||||
}) as WebRtcAudioSession;
|
||||
(session as unknown as { trimQueuesAfterLateTick(): void }).trimQueuesAfterLateTick();
|
||||
assert.equal(queue.length, expectedRemaining, profile);
|
||||
assert.equal((session as unknown as { stats: { webrtcQueueDroppedFrames: number } }).stats.webrtcQueueDroppedFrames, expectedDropped, profile);
|
||||
}
|
||||
});
|
||||
|
||||
function fixture() {
|
||||
const released: string[] = [];
|
||||
// Exercise the real close path with failures at codec/track/peer boundaries.
|
||||
|
||||
@@ -12,6 +12,8 @@ import { WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
|
||||
import { OpusEncoder } from "./opus-codec.js";
|
||||
import type { WebRtcSessionDescription } from "../shared/webrtc.js";
|
||||
import { addOpusFmtpParameters } from "../shared/opus-sdp.js";
|
||||
import type { VoiceIceServer, VoiceIceTransportPolicy } from "../shared/voice-ice.js";
|
||||
import type { VoiceProfile } from "../shared/voice-profile.js";
|
||||
export type { WebRtcSessionDescription } from "../shared/webrtc.js";
|
||||
|
||||
export { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
|
||||
@@ -23,9 +25,15 @@ const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS * 2;
|
||||
const DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
|
||||
const AUDIO_CLOCK_INTERVAL_MS = 20;
|
||||
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
|
||||
const MAX_MIXER_QUEUE_FRAMES = 4;
|
||||
const MAX_MIXER_QUEUE_FRAMES = 6;
|
||||
const MAX_MIXER_PACER_LAG_MS = AUDIO_CLOCK_INTERVAL_MS * 2;
|
||||
const MAX_MIXER_FRAME_AGE_MS = MAX_MIXER_QUEUE_FRAMES * AUDIO_CLOCK_INTERVAL_MS;
|
||||
const MAX_MIXER_FRAME_AGE_MS = 200;
|
||||
const MAX_MIXER_QUEUE_AFTER_LATE_TICK = 2;
|
||||
// The pre-CFT implementation used a 4-frame queue, an 80 ms age bound and one
|
||||
// retained frame after a late tick. Keep those values for direct deployments.
|
||||
const LEGACY_MAX_MIXER_QUEUE_FRAMES = 4;
|
||||
const LEGACY_MAX_MIXER_FRAME_AGE_MS = LEGACY_MAX_MIXER_QUEUE_FRAMES * AUDIO_CLOCK_INTERVAL_MS;
|
||||
const LEGACY_MAX_MIXER_QUEUE_AFTER_LATE_TICK = 1;
|
||||
const MIXER_UNDERRUN_WINDOW_MS = 200;
|
||||
// This threshold is used only for the speaking indicator. It must never decide
|
||||
// whether a media packet is forwarded or queued: quiet/comfort-noise Opus
|
||||
@@ -40,6 +48,9 @@ export interface WebRtcAudioOptions {
|
||||
publicHost?: string;
|
||||
ipv6Enabled?: boolean;
|
||||
stunServer?: string;
|
||||
/** Full ICE list, including TURN; takes precedence over `stunServer`. */
|
||||
iceServers?: VoiceIceServer[];
|
||||
iceTransportPolicy?: VoiceIceTransportPolicy;
|
||||
udpPortRange?: [number, number];
|
||||
}
|
||||
|
||||
@@ -51,6 +62,10 @@ export interface WebRtcAudioSessionOptions {
|
||||
publicAddresses?: string[];
|
||||
ipv6Enabled?: boolean;
|
||||
stunServer?: string;
|
||||
iceServers?: VoiceIceServer[];
|
||||
iceTransportPolicy?: VoiceIceTransportPolicy;
|
||||
/** `legacy` preserves the direct-deployment mixer; `adaptive` is the CFT path. */
|
||||
profile?: VoiceProfile;
|
||||
publicHost?: string;
|
||||
udpPortRange?: [number, number];
|
||||
logger: LoggerType;
|
||||
@@ -122,7 +137,12 @@ export class WebRtcAudioSession {
|
||||
private nextAudioDeadline = 0;
|
||||
private lastIngressRtpAt: number | null = null;
|
||||
private lastEgressRtpAt: number | null = null;
|
||||
private lastAudioRtpAt: number | null = null;
|
||||
private lastQueueEnqueuedAt: number | null = null;
|
||||
private readonly mixerQueueFrames: number;
|
||||
private readonly maxMixerFrameAgeMs: number;
|
||||
private readonly mixerQueueAfterLateTick: number;
|
||||
private readonly rtpMarkerAlways: boolean;
|
||||
private microphoneMuted: boolean;
|
||||
private accompanimentActive: boolean;
|
||||
private readonly stats: WebRtcAudioStats = {
|
||||
@@ -150,19 +170,31 @@ export class WebRtcAudioSession {
|
||||
this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId });
|
||||
this.onVoiceFrame = options.onVoiceFrame;
|
||||
this.onVoiceActivity = options.onVoiceActivity;
|
||||
const profile = options.profile ?? "legacy";
|
||||
this.mixerQueueFrames = profile === "legacy" ? LEGACY_MAX_MIXER_QUEUE_FRAMES : MAX_MIXER_QUEUE_FRAMES;
|
||||
this.maxMixerFrameAgeMs = profile === "legacy" ? LEGACY_MAX_MIXER_FRAME_AGE_MS : MAX_MIXER_FRAME_AGE_MS;
|
||||
this.mixerQueueAfterLateTick = profile === "legacy" ? LEGACY_MAX_MIXER_QUEUE_AFTER_LATE_TICK : MAX_MIXER_QUEUE_AFTER_LATE_TICK;
|
||||
this.rtpMarkerAlways = profile === "legacy";
|
||||
this.microphoneMuted = options.microphoneMuted === true;
|
||||
this.accompanimentActive = options.accompanimentActive === true;
|
||||
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
|
||||
|
||||
const iceAdditionalHostAddresses = options.publicAddresses ?? (options.publicHost ? [options.publicHost] : undefined);
|
||||
const udpPortRange = options.udpPortRange ?? WEBRTC_UDP_PORT_RANGE;
|
||||
const iceServers = options.iceServers?.length
|
||||
? options.iceServers
|
||||
: options.stunServer ? [{ urls: options.stunServer }] : [];
|
||||
this.peer = new RTCPeerConnection({
|
||||
// Both audio routes carry Opus; accepting PCMU would label Opus output
|
||||
// as another codec and silently discard the peer's incoming audio.
|
||||
codecs: { audio: [useOPUS()] },
|
||||
iceServers: options.stunServer ? [{ urls: options.stunServer }] : [],
|
||||
iceServers,
|
||||
iceTransportPolicy: options.iceTransportPolicy ?? "all",
|
||||
iceUseIpv4: true,
|
||||
iceUseIpv6: options.ipv6Enabled === true,
|
||||
// This controls ICE-TCP host candidates, not TURN control transport.
|
||||
// werift parses `turns:` as a TLS TURN client independently; verified in
|
||||
// peerConnection.ts createTransport() -> parseIceServers().
|
||||
iceUseTcp: false,
|
||||
icePortRange: [...udpPortRange] as [number, number],
|
||||
...(iceAdditionalHostAddresses ? { iceAdditionalHostAddresses } : {}),
|
||||
@@ -315,7 +347,7 @@ export class WebRtcAudioSession {
|
||||
queue = [];
|
||||
this.pendingFrames.set(data.clientId, queue);
|
||||
}
|
||||
if (queue.length >= MAX_MIXER_QUEUE_FRAMES) {
|
||||
if (queue.length >= this.mixerQueueFrames) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
@@ -398,6 +430,7 @@ export class WebRtcAudioSession {
|
||||
}
|
||||
}
|
||||
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS);
|
||||
const hasAudio = this.pendingFrames.size > 0;
|
||||
for (const [clientId, queue] of this.pendingFrames) {
|
||||
const frame = queue.shift();
|
||||
if (queue.length === 0) this.pendingFrames.delete(clientId);
|
||||
@@ -422,25 +455,30 @@ export class WebRtcAudioSession {
|
||||
}
|
||||
try {
|
||||
const encoded = this.encoder.encode(pcm);
|
||||
this.sendRtpAudio(encoded);
|
||||
this.sendRtpAudio(encoded, hasAudio);
|
||||
} catch {
|
||||
// A peer closing concurrently may reject a packet; teardown owns the
|
||||
// session lifecycle and no per-frame error needs to reach the logs.
|
||||
}
|
||||
}
|
||||
|
||||
private sendRtpAudio(encoded: Buffer): void {
|
||||
private sendRtpAudio(encoded: Buffer, hasAudio: boolean): void {
|
||||
const now = performance.now();
|
||||
const marker = this.rtpMarkerAlways
|
||||
? true
|
||||
: hasAudio && (this.lastAudioRtpAt === null || now - this.lastAudioRtpAt > 40);
|
||||
const packet = new RtpPacket(new RtpHeader({
|
||||
payloadType: this.outgoingPayloadType,
|
||||
sequenceNumber: this.sequenceNumber,
|
||||
timestamp: this.timestamp,
|
||||
ssrc: this.ssrc,
|
||||
marker: true,
|
||||
marker,
|
||||
}), encoded);
|
||||
this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff;
|
||||
this.timestamp = (this.timestamp + AUDIO_FRAME_SAMPLES) >>> 0;
|
||||
this.outgoingTrack.writeRtp(packet);
|
||||
const sentAt = performance.now();
|
||||
if (hasAudio) this.lastAudioRtpAt = sentAt;
|
||||
if (this.lastEgressRtpAt !== null) this.stats.webrtcEgressRtpMaxGapMs = Math.max(this.stats.webrtcEgressRtpMaxGapMs, Math.round(sentAt - this.lastEgressRtpAt));
|
||||
this.lastEgressRtpAt = sentAt;
|
||||
this.stats.webrtcEgressRtpFirstAt ??= Date.now();
|
||||
@@ -497,11 +535,11 @@ export class WebRtcAudioSession {
|
||||
private trimQueuesAfterLateTick(): void {
|
||||
const now = performance.now();
|
||||
for (const [clientId, queue] of this.pendingFrames) {
|
||||
while (queue.length > 1) {
|
||||
while (queue.length > this.mixerQueueAfterLateTick) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
if (queue[0] && now - queue[0].receivedAt > MAX_MIXER_FRAME_AGE_MS) {
|
||||
while (queue[0] && now - queue[0].receivedAt > this.maxMixerFrameAgeMs) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
|
||||
@@ -15,6 +15,13 @@ export interface AdminSettingsInput {
|
||||
webRtcStunServer?: string;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
voiceProfile?: "auto" | "legacy" | "adaptive";
|
||||
voiceTurnUrls?: string;
|
||||
voiceTurnSecret?: string;
|
||||
voiceTurnSecretAction?: "keep" | "replace" | "remove";
|
||||
voiceTurnTtlSeconds?: number;
|
||||
voiceOpusWs?: boolean;
|
||||
voiceJitterMaxMs?: number;
|
||||
relaySettingsAction?: "keep" | "replace" | "remove";
|
||||
relayEnabled?: boolean;
|
||||
relayName?: string;
|
||||
|
||||
@@ -33,6 +33,12 @@ const settings = object({
|
||||
webRtcPublicHost: value => value === undefined ? "" : text(value),
|
||||
webRtcIpv6Enabled: value => value === undefined ? false : boolean(value),
|
||||
webRtcStunServer: value => value === undefined ? "" : text(value),
|
||||
voiceProfile: value => value === undefined ? "auto" as const : choice("auto", "legacy", "adaptive")(value),
|
||||
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),
|
||||
voiceJitterMaxMs: value => value === undefined ? 300 : number(value),
|
||||
relayConfigured: boolean, relayEnabled: boolean, relayName: text, relayTarget: text, hasRelayToken: boolean,
|
||||
relayNodes: array(relayNode), internalPort: number, updatedAt: text,
|
||||
});
|
||||
|
||||
@@ -60,12 +60,21 @@ test("every current gateway message survives JSON transport and shared validatio
|
||||
}
|
||||
});
|
||||
|
||||
test("voice profile is optional and invalid values are rejected", () => {
|
||||
const adaptive = parseServerMessage({ type: "connected", tsClientId: 1, voiceProfile: "adaptive" });
|
||||
assert.equal(adaptive?.type === "connected" ? adaptive.voiceProfile : undefined, "adaptive");
|
||||
const legacy = parseServerMessage({ type: "connected", tsClientId: 1, voiceProfile: "legacy" });
|
||||
assert.equal(legacy?.type === "connected" ? legacy.voiceProfile : undefined, "legacy");
|
||||
assert.equal(parseServerMessage({ type: "connected", tsClientId: 1, voiceProfile: "future" }), null);
|
||||
});
|
||||
|
||||
test("malformed nested directory and event data is rejected before client state changes", () => {
|
||||
for (const message of [
|
||||
null, [], {}, { type: "toString" }, { type: "futureMessage" },
|
||||
{ type: "connected", tsClientId: 1, members: [null] },
|
||||
{ type: "connected", tsClientId: 1, members: [{ id: "1", nickname: "bad id" }] },
|
||||
{ type: "connected", tsClientId: 1, serverEventLog: [{ id: "incomplete" }] },
|
||||
{ type: "connected", tsClientId: 1, voiceProfile: "future" },
|
||||
{ type: "serverInfo", name: "TeamSpeak", icon: "https://example.com/icon.png" },
|
||||
{ type: "serverInfo", name: "TeamSpeak", bannerUrl: "javascript:alert(1)" },
|
||||
{ type: "serverInfo", name: "TeamSpeak", welcomeMessage: "x".repeat(4_097) },
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import type { ChannelMember, ChannelInfo, ServerEvent, VoiceAudioBridgeStats } from "./voice-models.js";
|
||||
import { normalizeScreenShareIceServers, parseScreenShareSignal, SCREEN_SHARE_LEGACY_AVATAR_BUDGET, type ScreenShareIceServer, type ScreenSharePeerSignal, type ScreenShareStreamDescription, type ScreenShareViewerDescription } from "./screen-share.js";
|
||||
|
||||
import { normalizeVoiceStunServer } from "./voice-ice.js";
|
||||
import { normalizeVoiceIceServers, normalizeVoiceIceTransportPolicy, normalizeVoiceStunServer, type VoiceIceServer } from "./voice-ice.js";
|
||||
import { isSessionDescription, type SessionDescription } from "./webrtc.js";
|
||||
import { isVoiceProfile, type VoiceProfile } from "./voice-profile.js";
|
||||
export type { SessionDescription } from "./webrtc.js";
|
||||
|
||||
type Message<T extends string, Fields = object> = { type: T } & Fields;
|
||||
@@ -13,7 +14,7 @@ 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; webRtcStunServer?: string; 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"; audioFrameVersion?: 2; audioUplinkCodecs?: ("pcm" | "opus")[]; audioJitterMaxMs?: number; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }>
|
||||
| Message<"serverInfo", { name: string; icon?: string | null; bannerUrl?: string | null; welcomeMessage?: string }>
|
||||
| Message<"memberEnter", ChannelMember>
|
||||
| Message<"memberLeave", { id: number }>
|
||||
@@ -88,8 +89,11 @@ export function parseVoiceAudioBridgeStats(value: unknown): VoiceAudioBridgeStat
|
||||
const count = (key: string): number => finite(value[key]) && value[key] >= 0 ? value[key] : 0;
|
||||
return {
|
||||
transport: value.transport === "webrtc" ? "webrtc" : "websocket",
|
||||
ingressFrames: count("ingressFrames"), ingressDroppedFrames: count("ingressDroppedFrames"), ingressMaxGapMs: count("ingressMaxGapMs"),
|
||||
ingressFrames: count("ingressFrames"), ingressPcmFrames: count("ingressPcmFrames"), ingressOpusFrames: count("ingressOpusFrames"),
|
||||
ingressDroppedFrames: count("ingressDroppedFrames"), ingressMaxGapMs: count("ingressMaxGapMs"),
|
||||
tsSendFrames: count("tsSendFrames"), tsSendErrors: count("tsSendErrors"), tsSendMaxGapMs: count("tsSendMaxGapMs"),
|
||||
uplinkQueuePeakFrames: count("uplinkQueuePeakFrames"), uplinkQueueDroppedFrames: count("uplinkQueueDroppedFrames"),
|
||||
uplinkPacerLateTicks: count("uplinkPacerLateTicks"),
|
||||
tsReceiveFrames: count("tsReceiveFrames"), tsReceiveMaxGapMs: count("tsReceiveMaxGapMs"),
|
||||
egressFrames: count("egressFrames"), egressDroppedFrames: count("egressDroppedFrames"), egressMaxGapMs: count("egressMaxGapMs"),
|
||||
webrtcIngressRtpFrames: count("webrtcIngressRtpFrames"), webrtcIngressRtpMaxGapMs: count("webrtcIngressRtpMaxGapMs"),
|
||||
@@ -138,6 +142,13 @@ export function parseScreenShareStream(value: unknown): ScreenShareStreamDescrip
|
||||
const valid: Record<ServerMessage["type"], (message: RecordValue) => boolean> = {
|
||||
connected: m => optional(m.pluginSession, v => text(v) && /^[A-Za-z0-9_-]{43}$/.test(v)) && clientId(m.tsClientId) && optional(m.members, v => arrayOf(v, member)) && optional(m.serverEventLog, v => arrayOf(v, event))
|
||||
&& optional(m.identity, v => text(v) && v.length <= 8192) && optional(m.webrtcAvailable, boolean) && optional(m.webRtcStunServer, v => normalizeVoiceStunServer(v) !== null)
|
||||
&& optional(m.webrtcUnavailableReason, v => v === "DISABLED" || v === "NO_MEDIA_PATH")
|
||||
&& 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.audioFrameVersion, v => v === 2)
|
||||
&& 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),
|
||||
serverInfo: m => text(m.name) && m.name.length <= 256
|
||||
&& optional(m.icon, v => v === null || (text(v) && v.length <= 180_000
|
||||
@@ -191,6 +202,8 @@ export function parseServerMessage(value: unknown): ServerMessage | null {
|
||||
let result = value;
|
||||
if (value.type === "connected") {
|
||||
result = { ...value, ...(value.webRtcStunServer === undefined ? {} : { webRtcStunServer: normalizeVoiceStunServer(value.webRtcStunServer)! }), screenShareIceServers: normalizeScreenShareIceServers(Array.isArray(value.screenShareIceServers) ? value.screenShareIceServers : undefined) };
|
||||
if (Array.isArray(value.voiceIceServers)) result = { ...result, voiceIceServers: normalizeVoiceIceServers(value.voiceIceServers) };
|
||||
if (value.voiceIceTransportPolicy !== undefined) result = { ...result, voiceIceTransportPolicy: normalizeVoiceIceTransportPolicy(value.voiceIceTransportPolicy) };
|
||||
} else if (value.type === "audioStats") {
|
||||
result = { ...value, stats: parseVoiceAudioBridgeStats(value.stats) };
|
||||
} else if (value.type === "screenShareList") {
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
/** Shared binary framing for the compatibility (PCM/Opus over WebSocket) path. */
|
||||
|
||||
export const VOICE_FRAME_SAMPLES = 960;
|
||||
export const VOICE_PCM_FRAME_BYTES = VOICE_FRAME_SAMPLES * 2;
|
||||
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;
|
||||
@@ -0,0 +1,49 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import {
|
||||
hasVoiceTurnServer,
|
||||
normalizeVoiceIceServers,
|
||||
normalizeVoiceIceTransportPolicy,
|
||||
normalizeVoiceTurnRestUrls,
|
||||
} from "./voice-ice.js";
|
||||
|
||||
test("voice ICE normalization accepts STUN and TURN URLs", () => {
|
||||
const servers = normalizeVoiceIceServers([
|
||||
{ urls: "stun:stun.example.com:3478" },
|
||||
{ urls: "stuns:stun.example.com:5349" },
|
||||
{ urls: ["turns:turn.example.com:443?transport=tcp", "turn:turn.example.com:3478?transport=udp"], username: "u", credential: "c" },
|
||||
]);
|
||||
assert.deepEqual(servers, [
|
||||
{ urls: "stun:stun.example.com:3478" },
|
||||
{ urls: "stuns:stun.example.com:5349" },
|
||||
{ urls: ["turns:turn.example.com:443?transport=tcp", "turn:turn.example.com:3478?transport=udp"], username: "u", credential: "c" },
|
||||
]);
|
||||
assert.equal(hasVoiceTurnServer(servers), true);
|
||||
});
|
||||
|
||||
test("voice ICE normalization drops malformed, half-credentialed, and duplicate entries", () => {
|
||||
assert.deepEqual(normalizeVoiceIceServers([
|
||||
{ urls: "http://turn.example.com" },
|
||||
{ urls: "turns:turn.example.com:443?transport=udp" },
|
||||
{ urls: "turn:turn.example.com:3478", username: "u" },
|
||||
{ urls: "stun:stun.example.com:3478" },
|
||||
{ urls: "stun:stun.example.com:3478" },
|
||||
]), [{ urls: "stun:stun.example.com:3478" }]);
|
||||
});
|
||||
|
||||
test("transport policy defaults to direct-first", () => {
|
||||
assert.equal(normalizeVoiceIceTransportPolicy(undefined), "all");
|
||||
assert.equal(normalizeVoiceIceTransportPolicy("relay"), "relay");
|
||||
assert.equal(normalizeVoiceIceTransportPolicy("invalid"), "all");
|
||||
});
|
||||
|
||||
test("TURN REST URL input is strict and keeps direct-first configuration bounded", () => {
|
||||
assert.deepEqual(normalizeVoiceTurnRestUrls(" turn:turn.example.com:3478\nturns:turn.example.com:5349?transport=tcp "), [
|
||||
"turn:turn.example.com:3478",
|
||||
"turns:turn.example.com:5349?transport=tcp",
|
||||
]);
|
||||
assert.deepEqual(normalizeVoiceTurnRestUrls(""), []);
|
||||
assert.equal(normalizeVoiceTurnRestUrls("stun:stun.example.com:3478"), null);
|
||||
assert.equal(normalizeVoiceTurnRestUrls("https://turn.example.com"), null);
|
||||
assert.equal(normalizeVoiceTurnRestUrls("turn:turn.example.com:3478\nbad"), null);
|
||||
});
|
||||
+109
-1
@@ -15,7 +15,7 @@ export function normalizeVoiceMediaHost(value: unknown): string | null {
|
||||
return host.toLowerCase();
|
||||
}
|
||||
|
||||
/** Voice currently exposes UDP STUN discovery only, without relay credentials. */
|
||||
/** UDP STUN discovery only; TURN credentials are supplied separately. */
|
||||
export function normalizeVoiceStunServer(value: unknown): string | null {
|
||||
if (typeof value !== "string" || value.length > 300) return null;
|
||||
if (!value.trim()) return "";
|
||||
@@ -28,3 +28,111 @@ export function normalizeVoiceStunServer(value: unknown): string | null {
|
||||
if (!host || port < 1 || port > 65535) return null;
|
||||
return `stun:${host}:${port}`;
|
||||
}
|
||||
|
||||
export interface VoiceIceServer {
|
||||
urls: string | string[];
|
||||
username?: string;
|
||||
credential?: string;
|
||||
}
|
||||
|
||||
export type VoiceIceTransportPolicy = "all" | "relay";
|
||||
|
||||
export const VOICE_TURN_TTL_DEFAULT_SECONDS = 21_600;
|
||||
export const VOICE_TURN_TTL_MIN_SECONDS = 300;
|
||||
export const VOICE_TURN_TTL_MAX_SECONDS = 86_400;
|
||||
export const VOICE_TURN_MIN_SECRET_LENGTH = 16;
|
||||
export const VOICE_JITTER_DEFAULT_MS = 300;
|
||||
export const VOICE_JITTER_MIN_MS = 80;
|
||||
export const VOICE_JITTER_MAX_MS = 500;
|
||||
|
||||
const MAX_ICE_SERVER_COUNT = 8;
|
||||
const MAX_ICE_URL_LENGTH = 512;
|
||||
const MAX_ICE_CREDENTIAL_LENGTH = 512;
|
||||
const ICE_URL_PATTERN = /^(stun|stuns|turn|turns):([a-z0-9.-]+|\[[0-9a-f:.]+\])(?::(\d{1,5}))?(?:\?transport=(udp|tcp))?$/i;
|
||||
|
||||
function normalizeIceUrl(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const url = value.trim();
|
||||
if (!url || url.length > MAX_ICE_URL_LENGTH) return null;
|
||||
const match = ICE_URL_PATTERN.exec(url);
|
||||
if (!match) return null;
|
||||
const scheme = match[1]!.toLowerCase();
|
||||
const port = match[3] === undefined ? undefined : Number(match[3]);
|
||||
if (port !== undefined && (port < 1 || port > 65_535)) return null;
|
||||
const transport = match[4]?.toLowerCase();
|
||||
if (scheme === "stun" || scheme === "stuns") {
|
||||
return transport ? null : `${scheme}:${match[2]}${port === undefined ? "" : `:${port}`}`;
|
||||
}
|
||||
if (scheme === "turns" && transport === "udp") return null;
|
||||
return `${scheme}:${match[2]}${port === undefined ? "" : `:${port}`}${transport ? `?transport=${transport}` : ""}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bound server-owned ICE configuration before it reaches a browser or werift.
|
||||
* TURN is accepted only as an explicitly configured external service; no
|
||||
* gateway-owned relay is inserted here.
|
||||
*/
|
||||
export function normalizeVoiceIceServers(value?: readonly unknown[]): VoiceIceServer[] {
|
||||
if (!value?.length) return [];
|
||||
const normalized: VoiceIceServer[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const raw of value) {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
|
||||
const candidate = raw as Record<string, unknown>;
|
||||
const rawUrls = candidate.urls;
|
||||
const urls = (Array.isArray(rawUrls) ? rawUrls : [rawUrls])
|
||||
.map(normalizeIceUrl)
|
||||
.filter((url): url is string => url !== null);
|
||||
const uniqueUrls = [...new Set(urls)];
|
||||
if (!uniqueUrls.length) continue;
|
||||
const username = typeof candidate.username === "string" && candidate.username.length <= MAX_ICE_CREDENTIAL_LENGTH
|
||||
? candidate.username
|
||||
: undefined;
|
||||
const credential = typeof candidate.credential === "string" && candidate.credential.length <= MAX_ICE_CREDENTIAL_LENGTH
|
||||
? candidate.credential
|
||||
: undefined;
|
||||
// Do not forward a half-configured TURN credential pair.
|
||||
if ((username === undefined) !== (credential === undefined)) continue;
|
||||
const key = JSON.stringify([uniqueUrls, username ?? ""]);
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
normalized.push({
|
||||
urls: uniqueUrls.length === 1 ? uniqueUrls[0]! : uniqueUrls,
|
||||
...(username !== undefined ? { username } : {}),
|
||||
...(credential !== undefined ? { credential } : {}),
|
||||
});
|
||||
if (normalized.length >= MAX_ICE_SERVER_COUNT) break;
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function normalizeVoiceIceTransportPolicy(value: unknown): VoiceIceTransportPolicy {
|
||||
return value === "relay" ? "relay" : "all";
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the TURN REST service URL list used by the admin console.
|
||||
* Unlike the environment parser, an invalid token is a configuration error
|
||||
* rather than a silently ignored value.
|
||||
*/
|
||||
export function normalizeVoiceTurnRestUrls(value: unknown): string[] | null {
|
||||
if (typeof value !== "string" || value.length > 4096) return null;
|
||||
const tokens = value.trim() ? value.trim().split(/[\s,]+/).filter(Boolean) : [];
|
||||
if (tokens.length > MAX_ICE_SERVER_COUNT) return null;
|
||||
const urls: string[] = [];
|
||||
for (const token of tokens) {
|
||||
const [server] = normalizeVoiceIceServers([{ urls: token }]);
|
||||
if (!server) return null;
|
||||
const candidates = Array.isArray(server.urls) ? server.urls : [server.urls];
|
||||
if (!candidates.every((url) => /^turns?:/i.test(url))) return null;
|
||||
urls.push(...candidates);
|
||||
}
|
||||
return [...new Set(urls)];
|
||||
}
|
||||
|
||||
export function hasVoiceTurnServer(servers: readonly VoiceIceServer[]): boolean {
|
||||
return servers.some((server) => {
|
||||
const urls = Array.isArray(server.urls) ? server.urls : [server.urls];
|
||||
return urls.some((url) => /^turns?:/i.test(url));
|
||||
});
|
||||
}
|
||||
@@ -58,11 +58,16 @@ export interface ServerEvent {
|
||||
export interface VoiceAudioBridgeStats {
|
||||
transport: "webrtc" | "websocket";
|
||||
ingressFrames: number;
|
||||
ingressPcmFrames?: number;
|
||||
ingressOpusFrames?: number;
|
||||
ingressDroppedFrames: number;
|
||||
ingressMaxGapMs: number;
|
||||
tsSendFrames: number;
|
||||
tsSendErrors: number;
|
||||
tsSendMaxGapMs: number;
|
||||
uplinkQueuePeakFrames?: number;
|
||||
uplinkQueueDroppedFrames?: number;
|
||||
uplinkPacerLateTicks?: number;
|
||||
tsReceiveFrames: number;
|
||||
tsReceiveMaxGapMs: number;
|
||||
egressFrames: number;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { normalizeVoiceProfileSetting, resolveVoiceProfile } from "./voice-profile.js";
|
||||
|
||||
test("auto keeps direct requests on legacy and opts Cloudflare requests into adaptive", () => {
|
||||
assert.equal(normalizeVoiceProfileSetting(undefined), "auto");
|
||||
assert.equal(normalizeVoiceProfileSetting(""), "auto");
|
||||
assert.equal(normalizeVoiceProfileSetting("unknown"), "auto");
|
||||
assert.equal(resolveVoiceProfile("auto", false), "legacy");
|
||||
assert.equal(resolveVoiceProfile("auto", true), "adaptive");
|
||||
});
|
||||
|
||||
test("explicit profile settings override request detection in both directions", () => {
|
||||
assert.equal(resolveVoiceProfile("legacy", true), "legacy");
|
||||
assert.equal(resolveVoiceProfile("adaptive", false), "adaptive");
|
||||
assert.equal(normalizeVoiceProfileSetting(" LEGACY "), "legacy");
|
||||
assert.equal(normalizeVoiceProfileSetting("Adaptive"), "adaptive");
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
export type VoiceProfile = "legacy" | "adaptive";
|
||||
export type VoiceProfileSetting = VoiceProfile | "auto";
|
||||
|
||||
/**
|
||||
* `auto` is the deployment default: direct HTTP/WebSocket traffic keeps the
|
||||
* historical audio path, while Cloudflare-proxied connections opt into the
|
||||
* adaptive path automatically. Explicit `legacy`/`adaptive` wins everywhere.
|
||||
*/
|
||||
export function normalizeVoiceProfileSetting(value: unknown): VoiceProfileSetting {
|
||||
if (typeof value !== "string") return "auto";
|
||||
const normalized = value.trim().toLowerCase();
|
||||
return normalized === "legacy" || normalized === "adaptive" ? normalized : "auto";
|
||||
}
|
||||
|
||||
export function resolveVoiceProfile(setting: VoiceProfileSetting, cloudflareRequest: boolean): VoiceProfile {
|
||||
if (setting === "legacy" || setting === "adaptive") return setting;
|
||||
return cloudflareRequest ? "adaptive" : "legacy";
|
||||
}
|
||||
|
||||
export function isVoiceProfile(value: unknown): value is VoiceProfile {
|
||||
return value === "legacy" || value === "adaptive";
|
||||
}
|
||||
|
||||
export function isVoiceProfileSetting(value: unknown): value is VoiceProfileSetting {
|
||||
return value === "auto" || isVoiceProfile(value);
|
||||
}
|
||||
@@ -67,7 +67,7 @@ test("official relative .bin symlinks are accepted and resolve inside the packag
|
||||
await extractReleaseArchive(archive, destination, "release.tar.gz");
|
||||
const link = path.join(destination, "webspeak/node_modules/.bin/nanoid");
|
||||
assert.equal(lstatSync(link).isSymbolicLink(), true);
|
||||
assert.equal(readlinkSync(link), "../nanoid/bin/nanoid.cjs");
|
||||
assert.equal(readlinkSync(link), path.normalize("../nanoid/bin/nanoid.cjs"));
|
||||
assert.equal(readFileSync(link, "utf8"), "#!/usr/bin/env node\nconsole.log('nanoid');\n");
|
||||
});
|
||||
|
||||
|
||||
@@ -299,6 +299,53 @@
|
||||
><small class="field-help">{{ tr("relayManagedHint") }}</small></section
|
||||
>
|
||||
</div></article>
|
||||
<article v-show="activeSection === 'voice'" class="settings-card admin-setting-card admin-settings-section" data-admin-section="voice">
|
||||
<header class="admin-card-heading"><h3>{{ tr('voiceSettings') }}</h3><p>{{ tr('voiceSettingsLead') }}</p></header>
|
||||
<div class="advanced-settings-grid">
|
||||
<section class="settings-subsection voice-profile-card">
|
||||
<header class="settings-subsection-heading"><div><h4>{{ tr('voiceProfile') }}</h4><p class="card-help">{{ tr('voiceProfileLead') }}</p></div></header>
|
||||
<div class="voice-profile-options">
|
||||
<label class="choice" :class="{ selected: serverForm.voiceProfile === 'auto' }">
|
||||
<input v-model="serverForm.voiceProfile" type="radio" value="auto" />
|
||||
<span><strong>{{ tr('voiceProfileAuto') }}</strong><small>{{ tr('voiceProfileAutoLead') }}</small></span>
|
||||
</label>
|
||||
<label class="choice" :class="{ selected: serverForm.voiceProfile === 'legacy' }">
|
||||
<input v-model="serverForm.voiceProfile" type="radio" value="legacy" />
|
||||
<span><strong>{{ tr('voiceProfileLegacy') }}</strong><small>{{ tr('voiceProfileLegacyLead') }}</small></span>
|
||||
</label>
|
||||
<label class="choice" :class="{ selected: serverForm.voiceProfile === 'adaptive' }">
|
||||
<input v-model="serverForm.voiceProfile" type="radio" value="adaptive" />
|
||||
<span><strong>{{ tr('voiceProfileAdaptive') }}</strong><small>{{ tr('voiceProfileAdaptiveLead') }}</small></span>
|
||||
</label>
|
||||
</div>
|
||||
<label class="choice toggle-choice" :class="{ selected: serverForm.voiceOpusWs }">
|
||||
<input v-model="serverForm.voiceOpusWs" type="checkbox" :disabled="serverForm.voiceProfile === 'legacy'" />
|
||||
<span><strong>{{ tr('voiceOpusWs') }}</strong><small>{{ tr('voiceOpusWsLead') }}</small></span>
|
||||
</label>
|
||||
<div class="voice-fields">
|
||||
<label><span>{{ tr('voiceJitterMaxMs') }}</span><input v-model.number="serverForm.voiceJitterMaxMs" type="number" inputmode="numeric" min="80" max="500" :disabled="serverForm.voiceProfile === 'legacy'" /><small class="field-help">{{ tr('voiceJitterLead') }}</small></label>
|
||||
</div>
|
||||
<small class="field-help">{{ tr('voiceApplyHint') }}</small>
|
||||
</section>
|
||||
<section class="settings-subsection turn-card">
|
||||
<header class="settings-subsection-heading"><div><h4>{{ tr('turnSettings') }}</h4><p class="card-help">{{ tr('turnLead') }}</p></div></header>
|
||||
<label class="webrtc-network-field">
|
||||
<span>{{ tr('turnUrls') }}</span>
|
||||
<textarea v-model="serverForm.voiceTurnUrls" rows="3" maxlength="4096" spellcheck="false" autocomplete="off" placeholder="turn:turn.example.com:3478 turns:turn.example.com:5349"></textarea>
|
||||
<small class="field-help">{{ tr('turnUrlsLead') }}</small>
|
||||
</label>
|
||||
<div class="password-row">
|
||||
<label><span>{{ tr('turnSecret') }}</span><input v-model="serverForm.voiceTurnSecret" type="password" autocomplete="off" :disabled="serverForm.voiceTurnSecretAction !== 'replace'" :placeholder="serverForm.hasVoiceTurnSecret ? tr('turnSecretConfigured') : tr('turnSecretPlaceholder')" /></label>
|
||||
<div class="password-actions"><button type="button" :class="{ active: serverForm.voiceTurnSecretAction === 'replace' }" @click="serverForm.voiceTurnSecretAction = 'replace'">{{ tr('change') }}</button><button v-if="serverForm.hasVoiceTurnSecret" type="button" :class="{ danger: serverForm.voiceTurnSecretAction === 'remove' }" @click="serverForm.voiceTurnSecretAction = 'remove'">{{ tr('remove') }}</button></div>
|
||||
</div>
|
||||
<small class="field-help">{{ tr('turnSecretLead') }}</small>
|
||||
<div class="voice-fields">
|
||||
<label><span>{{ tr('turnTtl') }}</span><input v-model.number="serverForm.voiceTurnTtlSeconds" type="number" inputmode="numeric" min="300" max="86400" /><small class="field-help">{{ tr('turnTtlLead') }}</small></label>
|
||||
</div>
|
||||
<small class="field-help">{{ tr('turnApplyHint') }}</small>
|
||||
</section>
|
||||
</div>
|
||||
</article>
|
||||
<p class="admin-save-scope"><Icon name="info" :size="15"/>{{ tr('adminSaveScope') }}</p>
|
||||
</section>
|
||||
</template>
|
||||
@@ -323,14 +370,15 @@ const emit = defineEmits<{ webrtcToggle: [] }>();
|
||||
// The page owns one stable feature controller across route changes.
|
||||
const { serverForm, serverSaving, testing, testResult, saveServerSettings, testServerConnection, addRelayNode, removeRelayNode } = props.model;
|
||||
const { tr, formatDate, connectionFailureText } = props.i18n;
|
||||
type SettingsSection = 'access' | 'site' | 'network';
|
||||
const normalizeSection = (value?: string): SettingsSection => value === 'site' || value === 'network' ? value : 'access';
|
||||
type SettingsSection = 'access' | 'site' | 'network' | 'voice';
|
||||
const normalizeSection = (value?: string): SettingsSection => value === 'site' || value === 'network' || value === 'voice' ? value : 'access';
|
||||
const activeSection = ref<SettingsSection>(normalizeSection(props.initialSection));
|
||||
watch(() => props.initialSection, value => { activeSection.value = normalizeSection(value); });
|
||||
const sections = computed(() => [
|
||||
{ id: 'access' as const, label: tr('adminAccessSection') },
|
||||
{ id: 'site' as const, label: tr('adminSiteSection') },
|
||||
{ id: 'network' as const, label: tr('adminNetworkSection') },
|
||||
{ id: 'voice' as const, label: tr('adminVoiceSection') },
|
||||
]);
|
||||
|
||||
function handleWebRtcToggle() { emit("webrtcToggle"); }
|
||||
|
||||
@@ -37,6 +37,9 @@ const errorLabels: Record<string, AdminTranslationKey> = {
|
||||
INVALID_PASSWORD: "invalidPassword", INVALID_ADMIN_PASSWORD: "setupPasswordShort", PASSWORD_CHANGE_REQUIRED: "changePasswordLead", RATE_LIMITED: "rateLimited",
|
||||
INVALID_WEBRTC_PUBLIC_HOST: "invalidWebRtcNetworkError", INVALID_WEBRTC_STUN_SERVER: "invalidWebRtcNetworkError", INVALID_WEBRTC_IPV6: "invalidWebRtcNetworkError",
|
||||
INVALID_WEBRTC_PORT_RANGE: "invalidWebRtcPortRangeError", WEBRTC_PORT_LOCKED: "webRtcPortLockedError",
|
||||
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_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",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { onScopeDispose, reactive, ref, watch, type Ref } from "vue";
|
||||
import { DEFAULT_WELCOME_TEXTS } from "../../../src/site-copy.js";
|
||||
import type { AdminSettings } from "../../../src/shared/admin-responses.js";
|
||||
import type { AdminSettingsInput } from "../../../src/shared/admin-inputs.js";
|
||||
import { isAdminRequestCancelled, type AdminApi } from "../services/admin-api.js";
|
||||
import { createAdminRequests } from "../services/admin-requests.js";
|
||||
import { combineTeamSpeakTarget, splitTeamSpeakTarget, suggestedTeamSpeakPort } from "../services/teamspeak-target.js";
|
||||
@@ -14,10 +15,12 @@ function emptyForm() {
|
||||
return { address: "", port: "9987", serverPassword: "", passwordAction: "keep" as SecretAction, hasPassword: false,
|
||||
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,
|
||||
relayNodes: [] as RelayNodeForm[], lastTestAt: null as string | null, lastTestLatencyMs: null as number | null };
|
||||
}
|
||||
type ServerForm = ReturnType<typeof emptyForm>;
|
||||
const editable = ["address", "port", "accessMode", "siteName", "welcomeText", "welcomeTextEn", "welcomeTextDe", "welcomeTextRu", "welcomeTextJa", "webRtcEnabled", "webRtcPublicHost", "webRtcIpv6Enabled", "webRtcStunServer", "webRtcUdpStart", "webRtcUdpEnd"] as const;
|
||||
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 snapshot = (form: ServerForm): ServerForm => JSON.parse(JSON.stringify(form));
|
||||
|
||||
export function useAdminServerSettings(options: Options) {
|
||||
@@ -73,6 +76,11 @@ export function useAdminServerSettings(options: Options) {
|
||||
serverForm.passwordAction = "keep";
|
||||
}
|
||||
serverForm.hasPassword = next.hasPassword;
|
||||
if (serverForm.voiceTurnSecret === baseline.voiceTurnSecret && serverForm.voiceTurnSecretAction === baseline.voiceTurnSecretAction) {
|
||||
serverForm.voiceTurnSecret = "";
|
||||
serverForm.voiceTurnSecretAction = "keep";
|
||||
}
|
||||
serverForm.hasVoiceTurnSecret = next.hasVoiceTurnSecret;
|
||||
serverForm.welcomeDefaults = next.welcomeDefaults;
|
||||
if (applyProbeMetadata && serverForm.address === next.address && serverForm.port === next.port) {
|
||||
serverForm.lastTestAt = next.lastTestAt;
|
||||
@@ -99,13 +107,24 @@ export function useAdminServerSettings(options: Options) {
|
||||
} finally { applyingSettings = false; }
|
||||
}
|
||||
|
||||
function serverPayload() {
|
||||
return { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined,
|
||||
function serverPayload(): AdminSettingsInput {
|
||||
const payload: AdminSettingsInput = { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined,
|
||||
passwordAction: serverForm.passwordAction, accessMode: serverForm.accessMode, siteName: serverForm.siteName,
|
||||
welcomeText: serverForm.welcomeText, welcomeTextEn: serverForm.welcomeTextEn, welcomeTextDe: serverForm.welcomeTextDe, welcomeTextRu: serverForm.welcomeTextRu, welcomeTextJa: serverForm.welcomeTextJa,
|
||||
webRtcPublicHost: serverForm.webRtcPublicHost, webRtcIpv6Enabled: serverForm.webRtcIpv6Enabled, webRtcStunServer: serverForm.webRtcStunServer,
|
||||
webRtcEnabled: serverForm.webRtcEnabled, webRtcUdpStart: serverForm.webRtcUdpStart, webRtcUdpEnd: serverForm.webRtcUdpEnd,
|
||||
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) {
|
||||
if (serverForm[key] !== saved[key]) Object.assign(payload, { [key]: serverForm[key] });
|
||||
}
|
||||
}
|
||||
if (serverForm.voiceTurnSecretAction !== "keep") {
|
||||
payload.voiceTurnSecretAction = serverForm.voiceTurnSecretAction;
|
||||
if (serverForm.voiceTurnSecretAction === "replace") payload.voiceTurnSecret = serverForm.voiceTurnSecret;
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
function report(error: unknown) {
|
||||
if (!isAdminRequestCancelled(error)) options.errorMessage.value = options.errorText((error as { code?: string }).code);
|
||||
|
||||
@@ -14,6 +14,8 @@ import { createVoiceSessionTrace } from "../voice/session-trace.js";
|
||||
export type { AudioPermission, BrowserVoiceAudioStats, VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
|
||||
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 { 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";
|
||||
@@ -42,6 +44,7 @@ export interface VoiceState {
|
||||
microphoneErrorCode: string;
|
||||
audioNotice: string;
|
||||
audioNoticeCode: string;
|
||||
webrtcReconnecting: boolean;
|
||||
channelSwitchedChannelId: string;
|
||||
}
|
||||
|
||||
@@ -201,7 +204,7 @@ export function useVoiceWebSocket() {
|
||||
const sessionTrace = createVoiceSessionTrace();
|
||||
const ws = shallowRef<WebSocket | null>(null);
|
||||
const serverInfo = shallowRef<VoiceServerInfo | null>(null);
|
||||
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", microphoneError: "", microphoneErrorCode: "", audioNotice: "", audioNoticeCode: "", channelSwitchedChannelId: "" });
|
||||
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", microphoneError: "", microphoneErrorCode: "", audioNotice: "", audioNoticeCode: "", webrtcReconnecting: false, channelSwitchedChannelId: "" });
|
||||
const pluginSession = ref("");
|
||||
const sessionState = createVoiceSessionState({
|
||||
selfId: () => state.tsClientId,
|
||||
@@ -332,23 +335,37 @@ export function useVoiceWebSocket() {
|
||||
const SPEAKING_HOLD_MS = 360;
|
||||
const AUDIO_FRAME_SAMPLES = 960;
|
||||
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
|
||||
const MAX_AUDIO_BUFFERED_FRAMES = 10;
|
||||
const MAX_AUDIO_BUFFERED_BYTES = AUDIO_FRAME_BYTES * MAX_AUDIO_BUFFERED_FRAMES;
|
||||
const LEGACY_AUDIO_BUFFERED_FRAMES = 10;
|
||||
const ADAPTIVE_AUDIO_BUFFERED_FRAMES = 15;
|
||||
let maxAudioBufferedFrames = LEGACY_AUDIO_BUFFERED_FRAMES;
|
||||
let maxAudioBufferedBytes = AUDIO_FRAME_BYTES * maxAudioBufferedFrames;
|
||||
const MAX_OPUS_BUFFERED_BYTES = 4_096;
|
||||
let voiceProfile: "legacy" | "adaptive" = "legacy";
|
||||
let audioJitterMaxMs = 80;
|
||||
let audioFrameVersion = 1;
|
||||
let audioUplinkCodecs: ("pcm" | "opus")[] = ["pcm"];
|
||||
const remotePlayback = createRemotePlayback({
|
||||
getContext: getAudioCtx,
|
||||
getVolume: clientId => (volumes[clientId] ?? 1) * effectiveOutputVolume(),
|
||||
onDecodeError: () => audioDiagnostics.count("decodeErrors"),
|
||||
onDrop: () => audioDiagnostics.count("framesDropped"),
|
||||
mode: () => voiceProfile,
|
||||
maxBufferAheadMs: () => audioJitterMaxMs,
|
||||
});
|
||||
let webRtcStunServer = "";
|
||||
let webRtcAvailable = false;
|
||||
let webRtcFailed = false;
|
||||
let voiceIceServers: VoiceIceServer[] = [];
|
||||
let voiceIceTransportPolicy: VoiceIceTransportPolicy = "all";
|
||||
const webrtc = createWebRtcTransport({
|
||||
stunServer: () => webRtcStunServer,
|
||||
iceServers: () => voiceIceServers,
|
||||
iceTransportPolicy: () => voiceIceTransportPolicy,
|
||||
prepareMicrophone: async () => {
|
||||
await ensureMicrophone();
|
||||
return micStream ? { context: getAudioCtx(), stream: micStream,
|
||||
processedStream: microphoneCapture?.processedStream ?? micStream } : null;
|
||||
},
|
||||
stopPcm: stopCaptureGraph,
|
||||
muted: () => microphoneMuted.value,
|
||||
inputVolume: () => inputVolume.value,
|
||||
accompanimentActive: () => accompanimentActive.value,
|
||||
@@ -359,16 +376,29 @@ export function useVoiceWebSocket() {
|
||||
else if (state.tsClientId) clearSpeaking(state.tsClientId);
|
||||
},
|
||||
onReady() {
|
||||
const switchingFromCompatibility = webRtcFailed;
|
||||
webRtcFailed = false;
|
||||
state.webrtcReconnecting = false;
|
||||
stopCaptureGraph();
|
||||
if (switchingFromCompatibility) remotePlayback.clearAll();
|
||||
clearAudioNotice("WEBRTC_FAILED");
|
||||
sessionTrace.record("webrtc.media", { state: "active" });
|
||||
syncWebRtcMemberVolumes();
|
||||
},
|
||||
onConnectionState(stateName) { sessionTrace.record("webrtc.connection", { state: stateName }); },
|
||||
async onFallback(reason, isCurrent) {
|
||||
onIceCandidateError(errorCode, url) {
|
||||
sessionTrace.record("webrtc.icecandidateerror", { errorCode, ...(url ? { url: url.slice(0, 300) } : {}) });
|
||||
},
|
||||
async onFailure(reason, isCurrent) {
|
||||
if (!isCurrent()) return;
|
||||
sessionTrace.record("webrtc.fallback", { code: safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE" });
|
||||
setAudioNotice("WEBRTC_FALLBACK", `实时语音(WebRTC)不可用(错误代码:${safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE"}),已切换为兼容传输:延迟与音质可能下降`);
|
||||
try { await startMicrophone(); }
|
||||
catch (error) { if (isCurrent()) setMicrophoneError(error); }
|
||||
const switchingFromWebRtc = !webRtcFailed;
|
||||
webRtcFailed = true;
|
||||
state.webrtcReconnecting = false;
|
||||
const code = safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE";
|
||||
sessionTrace.record("webrtc.failed", { code });
|
||||
if (switchingFromWebRtc) remotePlayback.clearAll();
|
||||
resumeCompatibilityCapture();
|
||||
setAudioNotice("WEBRTC_FAILED", webRtcFailureMessage(code));
|
||||
},
|
||||
playback: {
|
||||
context: () => audioCtx,
|
||||
@@ -387,25 +417,41 @@ export function useVoiceWebSocket() {
|
||||
onPlaying: syncAudioContextNotice,
|
||||
},
|
||||
});
|
||||
|
||||
function webRtcCarriesAudio(): boolean {
|
||||
return webrtc.active && !webRtcFailed;
|
||||
}
|
||||
|
||||
const audioDiagnostics = createAudioDiagnostics({
|
||||
source() {
|
||||
const socket = ws.value;
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN || !state.connected) return null;
|
||||
const peer = webrtc.peer;
|
||||
return { socket, connection: voiceConnection.generation, transportGeneration: webrtc.generation, peer,
|
||||
transport: webrtc.active ? "webrtc" : peer ? "negotiating" : "websocket" };
|
||||
transport: webRtcFailed ? "websocket" : webrtc.active ? "webrtc" : peer ? "negotiating" : "websocket" };
|
||||
},
|
||||
presentation({ peer }) {
|
||||
return {
|
||||
microphoneMuted: microphoneMuted.value,
|
||||
microphoneReady: Boolean(micStream?.getAudioTracks().some(track => track.readyState === "live")),
|
||||
microphonePermission: audioPermission.value,
|
||||
playbackState: peer
|
||||
playbackState: peer && !webRtcFailed
|
||||
? webrtc.output ? webrtc.output.paused ? "paused" : "playing" : "unavailable"
|
||||
: audioCtx ? audioCtx.state === "running" ? "playing" : "paused" : null,
|
||||
};
|
||||
},
|
||||
send: (source, sequence) => source.socket.send(JSON.stringify({ type: "audioStatsProbe", payload: { sequence } })),
|
||||
bufferStats: () => remotePlayback.getStats(),
|
||||
});
|
||||
let opusStreamOpen = false;
|
||||
const opusUplink = createOpusUplink({
|
||||
send(frame) {
|
||||
const socket = ws.value;
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN || socket.bufferedAmount > MAX_OPUS_BUFFERED_BYTES) return false;
|
||||
try { socket.send(frame); return true; } catch { return false; }
|
||||
},
|
||||
onDrop: () => audioDiagnostics.count("framesDropped"),
|
||||
onFallback: reason => sessionTrace.record("audio.opus.fallback", { reason: reason.slice(0, 120) }),
|
||||
});
|
||||
|
||||
async function saveAudioPreferences(): Promise<void> {
|
||||
@@ -535,7 +581,11 @@ export function useVoiceWebSocket() {
|
||||
state.microphoneErrorCode = "";
|
||||
}
|
||||
|
||||
/** Non-fatal audio notice (WebRTC fallback, blocked autoplay, device list failure...). */
|
||||
/** Non-fatal audio notice (WebRTC failure, blocked autoplay, device list failure...). */
|
||||
function webRtcFailureMessage(reason: string): string {
|
||||
return `实时语音(WebRTC)不可用(错误代码:${reason})。已自动切换到兼容传输(PCM/Opus over WebSocket)保通话;你仍在当前语音会话中,可点击“重新连接 WebRTC”重试`;
|
||||
}
|
||||
|
||||
function setAudioNotice(code: string, message: string): void {
|
||||
state.audioNoticeCode = safeClientErrorCode(code) || "AUDIO_NOTICE";
|
||||
state.audioNotice = message;
|
||||
@@ -655,11 +705,15 @@ export function useVoiceWebSocket() {
|
||||
const socket = ws.value;
|
||||
const shouldSend = !microphoneMuted.value
|
||||
&& !microphoneTestActive.value
|
||||
&& !webrtc.active
|
||||
&& !webRtcCarriesAudio()
|
||||
&& socket?.readyState === WebSocket.OPEN
|
||||
&& voxGate(input);
|
||||
if (!shouldSend) {
|
||||
accumLen = 0;
|
||||
if (opusStreamOpen) {
|
||||
opusUplink.resetStream();
|
||||
opusStreamOpen = false;
|
||||
}
|
||||
if (microphoneMuted.value) {
|
||||
voxAttack = 0;
|
||||
voxRelease = 0;
|
||||
@@ -668,10 +722,20 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
if (!socket) {
|
||||
accumLen = 0;
|
||||
if (opusStreamOpen) {
|
||||
opusUplink.resetStream();
|
||||
opusStreamOpen = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (opusUplink.active) {
|
||||
if (!opusStreamOpen) opusStreamOpen = true;
|
||||
accumLen = 0;
|
||||
if (opusUplink.push(input)) markSpeaking(state.tsClientId);
|
||||
return;
|
||||
}
|
||||
const bufferedBytes = socket.bufferedAmount;
|
||||
if (bufferedBytes > MAX_AUDIO_BUFFERED_BYTES) {
|
||||
if (bufferedBytes > maxAudioBufferedBytes) {
|
||||
accumLen = 0;
|
||||
return;
|
||||
}
|
||||
@@ -688,7 +752,7 @@ export function useVoiceWebSocket() {
|
||||
accumLen = need;
|
||||
|
||||
let offset = 0;
|
||||
while (offset + AUDIO_FRAME_SAMPLES <= accumLen && socket.readyState === WebSocket.OPEN && socket.bufferedAmount <= MAX_AUDIO_BUFFERED_BYTES) {
|
||||
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;
|
||||
}
|
||||
@@ -810,12 +874,19 @@ export function useVoiceWebSocket() {
|
||||
|
||||
function stopCaptureGraph(): void {
|
||||
accumLen = 0;
|
||||
opusStreamOpen = false;
|
||||
opusUplink.resetStream();
|
||||
voxAttack = 0;
|
||||
voxRelease = 0;
|
||||
micLevel.value = 0;
|
||||
microphoneCapture?.stopCapture();
|
||||
}
|
||||
|
||||
function resumeCompatibilityCapture(): void {
|
||||
try { microphoneCapture?.activate(); }
|
||||
catch (error) { setMicrophoneError(error); }
|
||||
}
|
||||
|
||||
function stopMicrophone(closeContext = true): void {
|
||||
if (closeContext) {
|
||||
microphoneGeneration++;
|
||||
@@ -1068,6 +1139,19 @@ export function useVoiceWebSocket() {
|
||||
screenShare.stopTransport(sendScreenStop);
|
||||
webrtc.stop();
|
||||
remotePlayback.clearAll();
|
||||
webRtcAvailable = false;
|
||||
webRtcFailed = false;
|
||||
state.webrtcReconnecting = false;
|
||||
voiceIceServers = [];
|
||||
voiceIceTransportPolicy = "all";
|
||||
voiceProfile = "legacy";
|
||||
maxAudioBufferedFrames = LEGACY_AUDIO_BUFFERED_FRAMES;
|
||||
maxAudioBufferedBytes = AUDIO_FRAME_BYTES * maxAudioBufferedFrames;
|
||||
audioJitterMaxMs = 80;
|
||||
audioFrameVersion = 1;
|
||||
audioUplinkCodecs = ["pcm"];
|
||||
opusUplink.disable();
|
||||
opusStreamOpen = false;
|
||||
stopMicrophone();
|
||||
clearSpeakingState();
|
||||
whisperTargetIds.clear();
|
||||
@@ -1098,6 +1182,9 @@ export function useVoiceWebSocket() {
|
||||
state.errorCode = "";
|
||||
state.channelSwitchedChannelId = "";
|
||||
state.tsClientId = Number(msg.tsClientId) || 0;
|
||||
webRtcAvailable = msg.webrtcAvailable === true;
|
||||
state.webrtcReconnecting = false;
|
||||
clearAudioNotice("WEBRTC_FAILED");
|
||||
pluginSession.value = msg.pluginSession ?? "";
|
||||
// The mute preference is local to the browser, while TeamSpeak shows
|
||||
// the gateway's own client_input_muted flag to other clients. Send it
|
||||
@@ -1106,6 +1193,22 @@ export function useVoiceWebSocket() {
|
||||
sendCmd("setMicrophoneMuted", { muted: microphoneMuted.value });
|
||||
screenShare.setIceServers(msg.screenShareIceServers);
|
||||
webRtcStunServer = msg.webRtcStunServer ?? "";
|
||||
voiceIceServers = msg.voiceIceServers ?? [];
|
||||
voiceIceTransportPolicy = msg.voiceIceTransportPolicy ?? "all";
|
||||
voiceProfile = msg.voiceProfile ?? "legacy";
|
||||
const adaptiveProfile = voiceProfile === "adaptive";
|
||||
maxAudioBufferedFrames = adaptiveProfile ? ADAPTIVE_AUDIO_BUFFERED_FRAMES : LEGACY_AUDIO_BUFFERED_FRAMES;
|
||||
maxAudioBufferedBytes = AUDIO_FRAME_BYTES * maxAudioBufferedFrames;
|
||||
audioJitterMaxMs = adaptiveProfile ? (msg.audioJitterMaxMs ?? 300) : 80;
|
||||
audioFrameVersion = msg.audioFrameVersion ?? 1;
|
||||
audioUplinkCodecs = adaptiveProfile ? (msg.audioUplinkCodecs ?? ["pcm"]) : ["pcm"];
|
||||
if (adaptiveProfile && audioUplinkCodecs.includes("opus")) {
|
||||
void opusUplink.init().then(active => sessionTrace.record("audio.opus", { state: active ? "active" : "pcm-fallback" }));
|
||||
} else {
|
||||
opusUplink.disable();
|
||||
opusStreamOpen = false;
|
||||
}
|
||||
if (msg.webrtcUnavailableReason) sessionTrace.record("webrtc.unavailable", { reason: msg.webrtcUnavailableReason });
|
||||
sessionState.connected(msg);
|
||||
applyWhisperState(msg.whisperTargetIds, msg.whisperActive);
|
||||
if (typeof msg.identity === "string" && msg.identity.length <= 8192) {
|
||||
@@ -1188,7 +1291,7 @@ export function useVoiceWebSocket() {
|
||||
void webrtc.applyAnswer(msg.payload?.sdp);
|
||||
break;
|
||||
case "webrtcError":
|
||||
if (ws.value) void webrtc.fallback(safeClientErrorCode(msg.code) || "WEBRTC_NEGOTIATION_FAILED");
|
||||
if (ws.value) void webrtc.fail(safeClientErrorCode(msg.code) || "WEBRTC_NEGOTIATION_FAILED");
|
||||
break;
|
||||
case "audioError": {
|
||||
// The gateway could not encode our microphone audio (for example its Opus
|
||||
@@ -1228,10 +1331,9 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
function handleAudioFrame(data: Uint8Array): void {
|
||||
// WebRTC carries the realtime downlink after negotiation. Ignore any
|
||||
// in-flight fallback WebSocket packets so a transport switch cannot
|
||||
// produce duplicate or delayed playback.
|
||||
if (webrtc.active) return;
|
||||
// Ignore in-flight fallback packets only while WebRTC actually carries
|
||||
// audio; a failed or reconnecting attempt must keep the WebSocket downlink.
|
||||
if (webRtcCarriesAudio()) return;
|
||||
if (data.length < 4) {
|
||||
audioDiagnostics.count("framesDropped");
|
||||
return;
|
||||
@@ -1356,6 +1458,28 @@ export function useVoiceWebSocket() {
|
||||
connect(lastConnection.target, lastConnection.channel, lastConnection.nickname, lastConnection.serverPassword, lastConnection.rememberIdentity ? identityMaterial.value || lastConnection.identity : "", lastConnection.rememberIdentity, "", lastConnection.accelerated, lastConnection.accelerationRelayId);
|
||||
}
|
||||
|
||||
async function reconnectWebRtc(): Promise<void> {
|
||||
const socket = ws.value;
|
||||
if (state.webrtcReconnecting || !state.connected || !socket || socket.readyState !== WebSocket.OPEN) return;
|
||||
if (!webRtcAvailable || typeof RTCPeerConnection === "undefined") {
|
||||
webRtcFailed = true;
|
||||
resumeCompatibilityCapture();
|
||||
setAudioNotice("WEBRTC_FAILED", webRtcFailureMessage("WEBRTC_UNAVAILABLE"));
|
||||
return;
|
||||
}
|
||||
const sequence = voiceConnection.generation;
|
||||
state.webrtcReconnecting = true;
|
||||
clearMicrophoneError();
|
||||
if (webRtcFailed) resumeCompatibilityCapture();
|
||||
try {
|
||||
await startWebRtcTransport(sequence, socket);
|
||||
} catch (error) {
|
||||
if (sequence !== voiceConnection.generation || ws.value !== socket || !state.connected) return;
|
||||
state.webrtcReconnecting = false;
|
||||
setMicrophoneError(error);
|
||||
}
|
||||
}
|
||||
|
||||
function setMicrophoneMuted(muted: boolean): void {
|
||||
microphoneMuted.value = muted;
|
||||
voxAttack = 0;
|
||||
@@ -1538,6 +1662,7 @@ export function useVoiceWebSocket() {
|
||||
playNotification,
|
||||
connect,
|
||||
reconnectNow,
|
||||
reconnectWebRtc,
|
||||
createInvite,
|
||||
disconnect,
|
||||
switchChannel,
|
||||
|
||||
@@ -228,12 +228,15 @@ function localizedMessage(message: string) {
|
||||
function localizedAudioNotice(code: string, message: string) {
|
||||
if (language.value === "zh") return message;
|
||||
const normalizedCode = visibleErrorCode(code || "AUDIO_NOTICE");
|
||||
const webRtcReason = code === "WEBRTC_FAILED"
|
||||
? message.match(/错误代码:([A-Z0-9_-]{1,64})/)?.[1] ?? normalizedCode
|
||||
: normalizedCode;
|
||||
const messages: Record<string, { en: string; de: string; ru: string; ja: string }> = {
|
||||
WEBRTC_FALLBACK: {
|
||||
en: `WebRTC realtime voice is unavailable (error code: ${normalizedCode}). Compatibility transport is active; latency and audio quality may be lower`,
|
||||
de: `Echtzeitstimme über WebRTC ist nicht verfügbar (Fehlercode: ${normalizedCode}). Der Kompatibilitätstransport ist aktiv; Latenz und Audioqualität können schlechter sein`,
|
||||
ru: `Голосовая связь WebRTC недоступна (код ошибки: ${normalizedCode}). Используется совместимый транспорт; задержка и качество звука могут быть ниже`,
|
||||
ja: `WebRTC のリアルタイム音声は利用できません(エラーコード: ${normalizedCode})。互換トランスポートを使用するため、遅延や音質が低下する場合があります`,
|
||||
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`,
|
||||
ru: `Голосовая связь WebRTC недоступна (код ошибки: ${webRtcReason}). Включён совместимый аудиоканал (PCM/Opus через WebSocket), чтобы сохранить текущую голосовую сессию; нажмите «Переподключить WebRTC», чтобы повторить попытку`,
|
||||
ja: `WebRTC のリアルタイム音声は利用できません(エラーコード: ${webRtcReason})。現在のボイスセッションを維持するため、互換オーディオ(PCM/Opus over WebSocket)が有効です。「WebRTC を再接続」から再試行できます`,
|
||||
},
|
||||
PLAYBACK_BLOCKED: {
|
||||
en: "The browser blocked automatic audio playback. Click the page or allow audio playback for this site",
|
||||
|
||||
+170
-5
@@ -209,7 +209,7 @@ export const copy = {
|
||||
webrtcPortEnd: "结束端口",
|
||||
webrtcApplyHint: "端口范围仅可在 WebRTC 关闭时修改;开启后会锁定,保存后对新连接生效。",
|
||||
webrtcPublicHost: "公网媒体地址",
|
||||
webrtcPublicHostLead: "填写网关可被 UDP 访问的 IP 或域名,不含协议或端口。留空按网页入口推断;反向代理或 TCP 隧道部署应单独指定媒体地址。保存后重新连接生效。",
|
||||
webrtcPublicHostLead: "填写网关可被 UDP 直达的 IP 或域名,不含协议或端口。有公网 IP 时优先填它,WebRTC 会先尝试直连;Cloudflare Tunnel 等纯 TCP 入口不要填 CF 代理域名,留空会禁用直连,需另行配置 TURN。保存后重新连接生效。",
|
||||
webrtcIpv6: "启用 IPv6 候选",
|
||||
webrtcIpv6Lead: "服务器需具备可达的 IPv6 和已放行的 UDP 端口;默认关闭。",
|
||||
webrtcStunServer: "语音 STUN 服务",
|
||||
@@ -217,6 +217,39 @@ export const copy = {
|
||||
invalidWebRtcNetworkError: "WebRTC 网络配置无效:媒体地址不含协议和端口,STUN 使用 stun:host:port,IPv6 必须为开关值。",
|
||||
webrtcPortNoticeTitle: "请先放行 WebRTC 端口",
|
||||
webrtcPortNotice: "需要开启端口,范围是 {{range}}(UDP)。请先在主机防火墙、安全组和 Docker 端口映射中放行该范围。",
|
||||
adminVoiceSection: "语音",
|
||||
voiceSettings: "语音传输",
|
||||
voiceSettingsLead: "按部署方式选择兼容或自适应音频,并为 Cloudflare Tunnel / 受限网络配置 TURN 后备。保存后对新连接生效。",
|
||||
voiceProfile: "语音模式",
|
||||
voiceProfileLead: "自动模式按入口选择:直连连接保持旧版兼容路径,Cloudflare 请求走自适应路径。",
|
||||
voiceProfileAuto: "自动(推荐)",
|
||||
voiceProfileAutoLead: "直连 → 兼容模式;Cloudflare Tunnel → 自适应。无需按入口手动切换。",
|
||||
voiceProfileLegacy: "兼容模式",
|
||||
voiceProfileLegacyLead: "恢复旧版 80ms 播放窗口、PCM over WebSocket 与固定发送节奏。适合需要与旧客户端行为完全一致的部署。",
|
||||
voiceProfileAdaptive: "自适应",
|
||||
voiceProfileAdaptiveLead: "启用自适应 jitter buffer、20ms pacer 和新帧协议。Cloudflare Tunnel 或明显抖动的网络优先使用。",
|
||||
voiceOpusWs: "兼容模式使用 Opus",
|
||||
voiceOpusWsLead: "仅在自适应模式生效;显式启用后浏览器可上传 Opus,减少带宽。默认关闭。",
|
||||
voiceJitterMaxMs: "自适应 jitter 上限",
|
||||
voiceJitterLead: "80–500 ms。只限制缓冲上限;调低不能恢复旧版超限 clear() 行为。",
|
||||
voiceApplyHint: "语音模式与 TURN 配置保存后对新的语音连接生效,不需要重启网关。",
|
||||
turnSettings: "TURN 后备",
|
||||
turnLead: "直连 UDP 不通时,浏览器再使用 TURN 中继;不要把它当作默认路径。",
|
||||
turnUrls: "TURN 服务地址",
|
||||
turnUrlsLead: "每行一个 turn: 或 turns: URL,最多 8 个。Cloudflare Tunnel 的纯 TCP 入口没有直连媒体路径时必须配置 TURN。",
|
||||
turnSecret: "TURN 共享密钥",
|
||||
turnSecretLead: "与 coturn 的 static-auth-secret / use-auth-secret 保持一致,至少 16 个字符。密钥加密保存,不会回传到浏览器。移除密钥会同时清空 TURN 地址并停用 TURN。",
|
||||
turnSecretConfigured: "已配置,点击“更改”替换",
|
||||
turnSecretPlaceholder: "至少 16 个字符",
|
||||
turnTtl: "凭证有效期(秒)",
|
||||
turnTtlLead: "300–86400 秒。浏览器每次连接都会获取短期 TURN 凭证。",
|
||||
turnApplyHint: "TURN 仅在直连失败时使用;保存后对新连接生效。留空 TURN 地址即可关闭控制台配置。",
|
||||
invalidVoiceProfileError: "语音模式无效,请选择自动、兼容或自适应。",
|
||||
invalidVoiceTurnUrlsError: "TURN 地址无效:每行一个 turn:/turns: URL,最多 8 个。",
|
||||
invalidVoiceTurnSecretError: "TURN 共享密钥无效:至少 16 个字符,且配置 TURN 地址时必须填写。",
|
||||
invalidVoiceTurnTtlError: "TURN 凭证有效期应为 300–86400 秒。",
|
||||
invalidVoiceJitterError: "自适应 jitter 上限应为 80–500 毫秒。",
|
||||
invalidVoiceSettingsError: "语音高级设置无效,请检查 Opus 开关和 jitter 上限。",
|
||||
relaySettings: "中继服务器",
|
||||
relaySettingsLead: "配置访客连接使用的中继节点;名称会显示在首页加速选项中。",
|
||||
relayEnabled: "启用中继加速",
|
||||
@@ -550,7 +583,7 @@ export const copy = {
|
||||
webrtcPortEnd: "End port",
|
||||
webrtcApplyHint: "The range can only be edited while WebRTC is off. It is locked while enabled and applies to new connections after saving.",
|
||||
webrtcPublicHost: "Public media address",
|
||||
webrtcPublicHostLead: "Gateway IP or hostname reachable over UDP, without a scheme or port. Empty uses the web entry address; reverse proxies and TCP tunnels may need a separate media address. Reconnect after saving.",
|
||||
webrtcPublicHostLead: "Gateway IP or hostname reachable directly over UDP, without a scheme or port. Prefer the public IP so WebRTC tries direct UDP first. Behind Cloudflare Tunnel or another TCP-only entry, do not use the CF-proxied hostname; leaving it empty disables direct candidates and requires TURN. Reconnect after saving.",
|
||||
webrtcIpv6: "Enable IPv6 candidates",
|
||||
webrtcIpv6Lead: "Requires reachable server IPv6 and open UDP ports. Disabled by default.",
|
||||
webrtcStunServer: "Voice STUN server",
|
||||
@@ -558,6 +591,39 @@ export const copy = {
|
||||
invalidWebRtcNetworkError: "Invalid WebRTC network settings: media host must have no scheme or port, STUN must be stun:host:port, and IPv6 must be a boolean.",
|
||||
webrtcPortNoticeTitle: "Allow WebRTC ports first",
|
||||
webrtcPortNotice: "Ports must be opened: {{range}} (UDP). Allow this range in the host firewall, security group, and Docker port mapping first.",
|
||||
adminVoiceSection: "Voice",
|
||||
voiceSettings: "Voice transport",
|
||||
voiceSettingsLead: "Choose compatibility or adaptive audio for this deployment and configure TURN fallback for Cloudflare Tunnel or restricted networks. Applies to new connections after saving.",
|
||||
voiceProfile: "Voice mode",
|
||||
voiceProfileLead: "Automatic picks by entry path: direct connections keep the legacy compatibility path, while Cloudflare requests use the adaptive path.",
|
||||
voiceProfileAuto: "Automatic (recommended)",
|
||||
voiceProfileAutoLead: "Direct → compatibility mode; Cloudflare Tunnel → adaptive. No need to switch manually per entry.",
|
||||
voiceProfileLegacy: "Compatibility mode",
|
||||
voiceProfileLegacyLead: "Restores the legacy 80 ms playback window, PCM over WebSocket, and fixed send cadence. Use when behavior must match older clients exactly.",
|
||||
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.",
|
||||
voiceJitterMaxMs: "Adaptive jitter limit",
|
||||
voiceJitterLead: "80–500 ms. This only caps buffering; lowering it does not restore the legacy clear() overrun behavior.",
|
||||
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.",
|
||||
turnUrls: "TURN service URLs",
|
||||
turnUrlsLead: "One turn: or turns: URL per line, up to eight. A TCP-only Cloudflare Tunnel entry with no direct media path requires TURN.",
|
||||
turnSecret: "TURN shared secret",
|
||||
turnSecretLead: "Must match coturn's static-auth-secret / use-auth-secret and contain at least 16 characters. The secret is stored encrypted and never returned to browsers. Removing the secret also clears the TURN URLs and disables TURN.",
|
||||
turnSecretConfigured: "Configured; choose Change to replace",
|
||||
turnSecretPlaceholder: "At least 16 characters",
|
||||
turnTtl: "Credential lifetime (seconds)",
|
||||
turnTtlLead: "300–86400 seconds. Browsers receive short-lived TURN credentials for each connection.",
|
||||
turnApplyHint: "TURN is used only after direct connection fails; changes apply to new connections. Leave the TURN URL field empty to disable console TURN.",
|
||||
invalidVoiceProfileError: "Invalid voice mode. Choose automatic, compatibility, or adaptive.",
|
||||
invalidVoiceTurnUrlsError: "Invalid TURN URL list: one turn:/turns: URL per line, up to eight.",
|
||||
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.",
|
||||
relaySettings: "Relay server",
|
||||
relaySettingsLead: "Configure the relay used by accelerated guest connections; its name is shown on the welcome page.",
|
||||
relayEnabled: "Enable relay acceleration",
|
||||
@@ -699,7 +765,7 @@ export const germanCopy = {
|
||||
webrtcPortRangeLead: "Gib den gesamten Bereich in der Host-Firewall und der Sicherheitsgruppe frei.",
|
||||
webrtcApplyHint: "Der Bereich kann nur bei deaktiviertem WebRTC geändert werden. Bei aktiviertem WebRTC ist er gesperrt; gespeicherte Änderungen gelten für neue Verbindungen.",
|
||||
webrtcPublicHost: "Öffentliche Medienadresse",
|
||||
webrtcPublicHostLead: "Über UDP erreichbare IP oder Hostname des Gateways ohne Protokoll oder Port. Leer: Webadresse verwenden. Reverse-Proxys und TCP-Tunnel benötigen eventuell eine separate Adresse. Nach dem Speichern neu verbinden.",
|
||||
webrtcPublicHostLead: "Direkt per UDP erreichbare IP oder Hostname des Gateways, ohne Protokoll oder Port. Bevorzuge die öffentliche IP, damit WebRTC zuerst direktes UDP versucht. Hinter Cloudflare Tunnel oder einem reinen TCP-Eingang niemals den CF-Proxy-Hostnamen eintragen; leer deaktiviert direkte Kandidaten und erfordert TURN. Nach dem Speichern neu verbinden.",
|
||||
webrtcIpv6: "IPv6-Kandidaten aktivieren",
|
||||
webrtcIpv6Lead: "Erfordert erreichbares IPv6 und offene UDP-Ports am Server. Standardmäßig deaktiviert.",
|
||||
webrtcStunServer: "STUN-Server für Sprache",
|
||||
@@ -707,6 +773,39 @@ export const germanCopy = {
|
||||
invalidWebRtcNetworkError: "Ungültige WebRTC-Netzwerkeinstellungen: Medienadresse ohne Protokoll oder Port, STUN als stun:host:port und IPv6 als Schalter.",
|
||||
webrtcPortNoticeTitle: "Zuerst WebRTC-Ports freigeben",
|
||||
webrtcPortNotice: "Erforderliche Ports: {{range}} (UDP). Gib diesen Bereich zuerst in der Host-Firewall, der Sicherheitsgruppe und der Docker-Portzuordnung frei.",
|
||||
adminVoiceSection: "Sprache",
|
||||
voiceSettings: "Sprachtransport",
|
||||
voiceSettingsLead: "Wähle je nach Betriebsart den Kompatibilitäts- oder adaptiven Audiopfad und konfiguriere TURN als Ausweichweg für Cloudflare Tunnel oder eingeschränkte Netze. Änderungen gelten nach dem Speichern für neue Verbindungen.",
|
||||
voiceProfile: "Sprachmodus",
|
||||
voiceProfileLead: "Automatisch entscheidet nach Eingang: direkte Verbindungen behalten den bisherigen Kompatibilitätsweg, Cloudflare-Anfragen nutzen den adaptiven Weg.",
|
||||
voiceProfileAuto: "Automatisch (empfohlen)",
|
||||
voiceProfileAutoLead: "Direkt → Kompatibilitätsmodus; Cloudflare Tunnel → adaptiv. Kein manuelles Umschalten je Eingang nötig.",
|
||||
voiceProfileLegacy: "Kompatibilitätsmodus",
|
||||
voiceProfileLegacyLead: "Stellt das bisherige 80-ms-Wiedergabefenster, PCM over WebSocket und den festen Sendetakt wieder her. Für Deployments, die sich exakt wie ältere Clients verhalten müssen.",
|
||||
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.",
|
||||
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.",
|
||||
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.",
|
||||
turnUrls: "TURN-Dienst-URLs",
|
||||
turnUrlsLead: "Eine turn:- oder turns:-URL pro Zeile, höchstens acht. Ein reiner TCP-Eingang über Cloudflare Tunnel ohne direkten Medienpfad benötigt TURN.",
|
||||
turnSecret: "TURN-Shared-Secret",
|
||||
turnSecretLead: "Muss mit static-auth-secret / use-auth-secret von coturn übereinstimmen und mindestens 16 Zeichen enthalten. Das Secret wird verschlüsselt gespeichert und nie an Browser zurückgegeben. Beim Entfernen werden auch die TURN-URLs gelöscht und TURN deaktiviert.",
|
||||
turnSecretConfigured: "Konfiguriert; zum Ersetzen „Ändern“ wählen",
|
||||
turnSecretPlaceholder: "Mindestens 16 Zeichen",
|
||||
turnTtl: "Gültigkeit der Zugangsdaten (Sekunden)",
|
||||
turnTtlLead: "300–86400 Sekunden. Browser erhalten bei jeder Verbindung kurzlebige TURN-Zugangsdaten.",
|
||||
turnApplyHint: "TURN wird nur nach fehlgeschlagener Direktverbindung verwendet; Änderungen gelten für neue Verbindungen. Leeres TURN-URL-Feld deaktiviert TURN aus der Konsole.",
|
||||
invalidVoiceProfileError: "Ungültiger Sprachmodus. Wähle Automatisch, Kompatibel oder Adaptiv.",
|
||||
invalidVoiceTurnUrlsError: "Ungültige TURN-URL-Liste: eine turn:/turns:-URL pro Zeile, höchstens acht.",
|
||||
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.",
|
||||
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.",
|
||||
@@ -1041,7 +1140,7 @@ export const russianCopy = {
|
||||
webrtcPortRangeLead: "Разрешите весь диапазон в брандмауэре сервера и группе безопасности.",
|
||||
webrtcApplyHint: "Диапазон можно изменить только при выключенном WebRTC. При включённом WebRTC он заблокирован; после сохранения изменения применяются к новым подключениям.",
|
||||
webrtcPublicHost: "Публичный адрес медиаданных",
|
||||
webrtcPublicHostLead: "IP или имя шлюза, доступное по UDP, без протокола и порта. Пусто: адрес веб-сайта. Для обратного прокси или TCP-туннеля может потребоваться отдельный адрес. После сохранения подключитесь заново.",
|
||||
webrtcPublicHostLead: "IP или имя шлюза, доступное напрямую по UDP, без протокола и порта. Укажите публичный IP, чтобы WebRTC сначала пробовал прямое UDP. За Cloudflare Tunnel или другим TCP-входом не используйте прокси-домен CF; пустое поле отключает прямые кандидаты и требует TURN. После сохранения подключитесь заново.",
|
||||
webrtcIpv6: "Включить кандидаты IPv6",
|
||||
webrtcIpv6Lead: "Нужны доступный IPv6 сервера и открытые порты UDP. По умолчанию выключено.",
|
||||
webrtcStunServer: "STUN-сервер голосовой связи",
|
||||
@@ -1049,6 +1148,39 @@ export const russianCopy = {
|
||||
invalidWebRtcNetworkError: "Неверные настройки WebRTC: адрес без протокола и порта, STUN в формате stun:host:port, IPv6 — логическое значение.",
|
||||
webrtcPortNoticeTitle: "Сначала откройте порты WebRTC",
|
||||
webrtcPortNotice: "Необходимо открыть порты {{range}} (UDP). Сначала разрешите этот диапазон в брандмауэре, группе безопасности и настройках проброса портов Docker.",
|
||||
adminVoiceSection: "Голос",
|
||||
voiceSettings: "Голосовой транспорт",
|
||||
voiceSettingsLead: "Выберите режим совместимости или адаптивный звук для этого развертывания и настройте TURN как резерв для Cloudflare Tunnel или ограниченных сетей. Изменения применяются к новым подключениям после сохранения.",
|
||||
voiceProfile: "Голосовой режим",
|
||||
voiceProfileLead: "Автоматический режим выбирает по входу: прямые подключения сохраняют прежний путь совместимости, запросы Cloudflare используют адаптивный путь.",
|
||||
voiceProfileAuto: "Автоматически (рекомендуется)",
|
||||
voiceProfileAutoLead: "Прямое подключение → режим совместимости; Cloudflare Tunnel → адаптивный. Переключать вручную для каждого входа не нужно.",
|
||||
voiceProfileLegacy: "Режим совместимости",
|
||||
voiceProfileLegacyLead: "Возвращает прежнее 80-мс окно воспроизведения, PCM over WebSocket и фиксированный темп отправки. Подходит, если поведение должно точно совпадать со старыми клиентами.",
|
||||
voiceProfileAdaptive: "Адаптивный",
|
||||
voiceProfileAdaptiveLead: "Включает адаптивный jitter buffer, пейсер 20 мс и новый протокол кадров. Предпочтителен для Cloudflare Tunnel или сетей с заметным джиттером.",
|
||||
voiceOpusWs: "Opus в режиме совместимости",
|
||||
voiceOpusWsLead: "Действует только в адаптивном режиме. При явном включении браузеры могут отправлять Opus, снижая трафик. По умолчанию выключено.",
|
||||
voiceJitterMaxMs: "Предел адаптивного jitter",
|
||||
voiceJitterLead: "80–500 мс. Ограничивает только буфер; снижение не возвращает прежнее поведение clear() при переполнении.",
|
||||
voiceApplyHint: "Режим и настройки TURN применяются к новым голосовым подключениям после сохранения; перезапуск шлюза не требуется.",
|
||||
turnSettings: "Резервный TURN",
|
||||
turnLead: "Браузер использует TURN только при неудачном прямом UDP-подключении; не делайте его основным путём.",
|
||||
turnUrls: "URL TURN-сервиса",
|
||||
turnUrlsLead: "Один URL turn: или turns: в строке, не более восьми. Чистый TCP-вход Cloudflare Tunnel без прямого медиапути требует TURN.",
|
||||
turnSecret: "Общий секрет TURN",
|
||||
turnSecretLead: "Должен совпадать с static-auth-secret / use-auth-secret в coturn и содержать не менее 16 символов. Секрет хранится в зашифрованном виде и не возвращается браузерам. Удаление секрета также очищает URL TURN и отключает TURN.",
|
||||
turnSecretConfigured: "Настроен; нажмите «Изменить», чтобы заменить",
|
||||
turnSecretPlaceholder: "Не менее 16 символов",
|
||||
turnTtl: "Срок действия учётных данных (с)",
|
||||
turnTtlLead: "300–86400 секунд. Браузер получает краткосрочные учётные данные TURN при каждом подключении.",
|
||||
turnApplyHint: "TURN используется только после неудачного прямого подключения; изменения применяются к новым подключениям. Пустое поле URL отключает TURN из консоли.",
|
||||
invalidVoiceProfileError: "Неверный голосовой режим. Выберите автоматический, совместимый или адаптивный.",
|
||||
invalidVoiceTurnUrlsError: "Неверный список URL TURN: один turn:/turns: URL в строке, не более восьми.",
|
||||
invalidVoiceTurnSecretError: "Неверный общий секрет TURN: не менее 16 символов и обязателен при настроенных URL TURN.",
|
||||
invalidVoiceTurnTtlError: "Срок действия учётных данных TURN должен быть от 300 до 86400 секунд.",
|
||||
invalidVoiceJitterError: "Предел адаптивного jitter должен быть от 80 до 500 мс.",
|
||||
invalidVoiceSettingsError: "Неверные расширенные настройки звука. Проверьте переключатель Opus и предел jitter.",
|
||||
fixedModeLead: "Гости вводят только имя; адрес сервера и пароль задаются в WebSpeak.",
|
||||
openModeLead: "Гости могут вводить публичные адреса TeamSpeak; частные и зарезервированные сети заблокированы.",
|
||||
legacyImported: "Прежний файл config.json импортирован. Теперь WebSpeak настраивается здесь; изменения старого файла больше не влияют на текущую конфигурацию.",
|
||||
@@ -1383,7 +1515,7 @@ export const japaneseCopy = {
|
||||
webrtcPortRangeLead: "ホストのファイアウォールとセキュリティグループで範囲全体を許可してください。",
|
||||
webrtcApplyHint: "ポート範囲は WebRTC が無効なときのみ変更できます。有効中はロックされ、保存後の新しい接続に適用されます。",
|
||||
webrtcPublicHost: "公開メディアアドレス",
|
||||
webrtcPublicHostLead: "UDP で到達できるゲートウェイの IP またはホスト名。スキームやポートは不要です。空欄では Web のアドレスを使用します。リバースプロキシや TCP トンネルでは別のアドレスが必要な場合があります。保存後に再接続してください。",
|
||||
webrtcPublicHostLead: "UDP で直接到達できるゲートウェイの IP またはホスト名。スキームやポートは不要です。公開 IP を優先すると WebRTC は直連 UDP を先に試します。Cloudflare Tunnel などの TCP のみの入口では CF 代理ホスト名を入れないでください。空欄では直連候補が無効になり TURN が必要です。保存後に再接続してください。",
|
||||
webrtcIpv6: "IPv6 候補を有効化",
|
||||
webrtcIpv6Lead: "サーバーの IPv6 到達性と UDP ポートの開放が必要です。初期設定は無効です。",
|
||||
webrtcStunServer: "音声 STUN サーバー",
|
||||
@@ -1391,6 +1523,39 @@ export const japaneseCopy = {
|
||||
invalidWebRtcNetworkError: "WebRTC 設定が無効です。メディアアドレスにはスキームやポートを含めず、STUN は stun:host:port、IPv6 は真偽値にしてください。",
|
||||
webrtcPortNoticeTitle: "先に WebRTC のポートを開放してください",
|
||||
webrtcPortNotice: "開放が必要なポートは {{range}}(UDP)です。先にホストのファイアウォール、セキュリティグループ、Docker のポートマッピングで許可してください。",
|
||||
adminVoiceSection: "音声",
|
||||
voiceSettings: "音声伝送",
|
||||
voiceSettingsLead: "デプロイに応じて互換モードまたは適応型音声を選び、Cloudflare Tunnel や制限されたネットワーク向けに TURN フォールバックを設定します。保存後の新規接続に適用されます。",
|
||||
voiceProfile: "音声モード",
|
||||
voiceProfileLead: "自動では入口に応じて選択します。直連は従来の互換パス、Cloudflare リクエストは適応パスを使用します。",
|
||||
voiceProfileAuto: "自動(推奨)",
|
||||
voiceProfileAutoLead: "直連 → 互換モード、Cloudflare Tunnel → 適応型。入口ごとに手動で切り替える必要はありません。",
|
||||
voiceProfileLegacy: "互換モード",
|
||||
voiceProfileLegacyLead: "従来の 80ms 再生ウィンドウ、PCM over WebSocket、固定送信ペースを復元します。旧クライアントと完全に同じ動作が必要な場合に使用します。",
|
||||
voiceProfileAdaptive: "適応型",
|
||||
voiceProfileAdaptiveLead: "適応型 jitter buffer、20ms ペーサー、新しいフレームプロトコルを有効にします。Cloudflare Tunnel やジッターの目立つネットワークに適しています。",
|
||||
voiceOpusWs: "互換モードで Opus を使用",
|
||||
voiceOpusWsLead: "適応モードでのみ有効です。明示的に有効にするとブラウザーが Opus を送信でき、帯域を節約できます。既定では無効です。",
|
||||
voiceJitterMaxMs: "適応型 jitter 上限",
|
||||
voiceJitterLead: "80〜500 ms。バッファ上限のみを制限します。下げても旧版の clear() オーバーラン動作は復元されません。",
|
||||
voiceApplyHint: "音声モードと TURN 設定は保存後の新規音声接続に適用され、ゲートウェイの再起動は不要です。",
|
||||
turnSettings: "TURN フォールバック",
|
||||
turnLead: "直連 UDP が失敗した場合にのみ TURN 中継を使用します。既定の経路にしないでください。",
|
||||
turnUrls: "TURN サービス URL",
|
||||
turnUrlsLead: "1 行に 1 つの turn: または turns: URL、最大 8 個。直連メディアパスがない Cloudflare Tunnel の TCP のみの入口では TURN が必要です。",
|
||||
turnSecret: "TURN 共有シークレット",
|
||||
turnSecretLead: "coturn の static-auth-secret / use-auth-secret と一致し、16 文字以上必要です。シークレットは暗号化して保存され、ブラウザーには返されません。シークレットを削除すると TURN URL も消去され、TURN が無効になります。",
|
||||
turnSecretConfigured: "設定済み。「変更」で置き換えます",
|
||||
turnSecretPlaceholder: "16 文字以上",
|
||||
turnTtl: "資格情報の有効期間(秒)",
|
||||
turnTtlLead: "300〜86400 秒。ブラウザーは接続ごとに短期 TURN 資格情報を受け取ります。",
|
||||
turnApplyHint: "TURN は直連失敗時のみ使用されます。保存後は新規接続に適用されます。TURN URL を空にするとコンソール設定の TURN が無効になります。",
|
||||
invalidVoiceProfileError: "音声モードが無効です。自動、互換、適応型のいずれかを選択してください。",
|
||||
invalidVoiceTurnUrlsError: "TURN URL が無効です。1 行に 1 つの turn:/turns: URL、最大 8 個にしてください。",
|
||||
invalidVoiceTurnSecretError: "TURN 共有シークレットが無効です。16 文字以上必要で、TURN URL 設定時は必須です。",
|
||||
invalidVoiceTurnTtlError: "TURN 資格情報の有効期間は 300〜86400 秒にしてください。",
|
||||
invalidVoiceJitterError: "適応型 jitter 上限は 80〜500 ミリ秒にしてください。",
|
||||
invalidVoiceSettingsError: "音声の詳細設定が無効です。Opus スイッチと jitter 上限を確認してください。",
|
||||
fixedModeLead: "ゲストはニックネームのみを入力します。接続先とパスワードは WebSpeak が管理します。",
|
||||
openModeLead: "ゲストは公開 TeamSpeak アドレスを入力できます。プライベートネットワークと予約済みネットワークへの接続は制限されます。",
|
||||
legacyImported: "旧 config.json をインポートしました。WebSpeak はこの画面で管理され、旧ファイルの変更は現在の設定に反映されません。",
|
||||
|
||||
@@ -299,6 +299,8 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
|
||||
reconnectingAttempt: "第 {{attempt}} 次重连",
|
||||
reconnectFailed: "无法恢复连接",
|
||||
reconnectNow: "立即重连",
|
||||
reconnectWebRtc: "重新连接 WebRTC",
|
||||
reconnectingWebRtc: "正在重新连接 WebRTC…",
|
||||
back: "返回",
|
||||
volumeToast: "成员音量可以在列表中单独调整",
|
||||
copiedToast: "邀请链接已复制",
|
||||
@@ -731,6 +733,8 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
|
||||
reconnectingAttempt: "Reconnecting… Attempt {{attempt}}",
|
||||
reconnectFailed: "Could not restore the connection",
|
||||
reconnectNow: "Reconnect now",
|
||||
reconnectWebRtc: "Reconnect WebRTC",
|
||||
reconnectingWebRtc: "Reconnecting WebRTC…",
|
||||
back: "Back",
|
||||
volumeToast: "Adjust each member's volume from the list",
|
||||
copiedToast: "Invite link copied",
|
||||
@@ -1156,6 +1160,8 @@ webClientTranslations.de = {
|
||||
reconnectingAttempt: "Verbindungsversuch {{attempt}}",
|
||||
reconnectFailed: "Verbindung konnte nicht wiederhergestellt werden",
|
||||
reconnectNow: "Jetzt neu verbinden",
|
||||
reconnectWebRtc: "WebRTC neu verbinden",
|
||||
reconnectingWebRtc: "WebRTC wird neu verbunden…",
|
||||
back: "Zurück",
|
||||
volumeToast: "Die Lautstärke jedes Mitglieds kann separat angepasst werden.",
|
||||
copiedToast: "Einladungslink kopiert",
|
||||
@@ -1448,6 +1454,8 @@ webClientTranslations.ru = {
|
||||
favoriteConnectionFailed: "Не удалось подключиться к {{server}}",
|
||||
quickConnectFailed: "Не удалось подключиться. Проверьте адрес сервера и имя.",
|
||||
reconnectNow: "Подключиться снова",
|
||||
reconnectWebRtc: "Переподключить WebRTC",
|
||||
reconnectingWebRtc: "Переподключение WebRTC…",
|
||||
removeFavorite: "Удалить из избранного",
|
||||
cancel: "Отмена",
|
||||
close: "Закрыть",
|
||||
@@ -1681,6 +1689,8 @@ webClientTranslations.ja = {
|
||||
voiceStatus: "音声状態",
|
||||
voiceStatusHint: "実音声フレームを表示。WebRTC ではブラウザー統計、互換モードではフレーム数を計測。テスト音は送信しません",
|
||||
reconnectNow: "今すぐ再接続",
|
||||
reconnectWebRtc: "WebRTC を再接続",
|
||||
reconnectingWebRtc: "WebRTC を再接続中…",
|
||||
voiceHealthDisconnected: "音声セッション未接続",
|
||||
voiceHealthSampling: "メディア情報を取得中",
|
||||
voiceHealthConnecting: "音声経路を接続中",
|
||||
|
||||
@@ -1570,6 +1570,29 @@
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
:deep(.voice-profile-options) {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
:deep(.voice-fields) {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 180px), 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
:deep(.voice-fields .field-help) {
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
:deep(.turn-card textarea) {
|
||||
min-height: 76px;
|
||||
resize: vertical;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
:deep(.toggle-choice) {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@@ -595,6 +595,17 @@
|
||||
><span>{{
|
||||
localizedAudioNotice(voiceState.audioNoticeCode, voiceState.audioNotice)
|
||||
}}</span></div
|
||||
><div
|
||||
v-if="voiceState.audioNoticeCode === 'WEBRTC_FAILED'"
|
||||
class="reconnect-actions"
|
||||
><button
|
||||
type="button"
|
||||
class="secondary-button"
|
||||
data-action="reconnect-webrtc"
|
||||
:disabled="voiceState.webrtcReconnecting"
|
||||
@click="reconnectWebRtc"
|
||||
>{{ voiceState.webrtcReconnecting ? t("reconnectingWebRtc") : t("reconnectWebRtc") }}</button
|
||||
></div
|
||||
></div
|
||||
>
|
||||
<div
|
||||
@@ -1086,6 +1097,7 @@ const {
|
||||
playNotification,
|
||||
connect,
|
||||
reconnectNow,
|
||||
reconnectWebRtc,
|
||||
disconnect,
|
||||
switchChannel,
|
||||
moveClient,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { VoiceAudioBridgeStats } from "../../../src/shared/voice-models.js";
|
||||
import type { FallbackPlaybackStats } from "./remote-playback.js";
|
||||
|
||||
export type AudioPermission = "unknown" | "granted" | "denied";
|
||||
|
||||
@@ -28,7 +29,7 @@ export interface VoiceAudioStatusSample {
|
||||
playbackState: "playing" | "paused" | "unavailable" | null;
|
||||
bridge: VoiceAudioBridgeStats;
|
||||
browser: BrowserVoiceAudioStats | null;
|
||||
fallbackPlayback: { framesReceived: number; framesDropped: number; decodeErrors: number };
|
||||
fallbackPlayback: { framesReceived: number; framesDropped: number; decodeErrors: number } & FallbackPlaybackStats;
|
||||
}
|
||||
|
||||
interface DiagnosticSource {
|
||||
@@ -44,6 +45,7 @@ interface DiagnosticOptions {
|
||||
presentation(source: DiagnosticSource): Pick<VoiceAudioStatusSample,
|
||||
"microphoneMuted" | "microphoneReady" | "microphonePermission" | "playbackState">;
|
||||
send(source: DiagnosticSource, sequence: string): void;
|
||||
bufferStats?(): FallbackPlaybackStats;
|
||||
}
|
||||
|
||||
async function browserStats(peer: RTCPeerConnection | null): Promise<BrowserVoiceAudioStats | null> {
|
||||
@@ -105,6 +107,7 @@ function sameSource(left: DiagnosticSource | null, right: DiagnosticSource | nul
|
||||
export function createAudioDiagnostics(options: DiagnosticOptions) {
|
||||
const pending = new Map<string, { receive(bridge: VoiceAudioBridgeStats): void; finish(sample: VoiceAudioStatusSample | null): void }>();
|
||||
const fallback = { framesReceived: 0, framesDropped: 0, decodeErrors: 0 };
|
||||
const emptyBuffer: FallbackPlaybackStats = { bufferTargetMs: 0, bufferResets: 0, maxBufferAheadMs: 0 };
|
||||
let sequence = 0;
|
||||
let scopeId = 0;
|
||||
let previousSource: DiagnosticSource | null = null;
|
||||
@@ -142,7 +145,8 @@ export function createAudioDiagnostics(options: DiagnosticOptions) {
|
||||
finish({
|
||||
scopeId: scope, sampledAt: performance.now(), transport: source.transport,
|
||||
connectionState: source.peer?.connectionState ?? null,
|
||||
...options.presentation(source), bridge, browser: stats, fallbackPlayback: { ...fallback },
|
||||
...options.presentation(source), bridge, browser: stats,
|
||||
fallbackPlayback: { ...fallback, ...(options.bufferStats?.() ?? emptyBuffer) },
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Playback buffer policy for the PCM-over-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.
|
||||
*/
|
||||
|
||||
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 MAX_OBSERVED_JITTER_MS = 500;
|
||||
|
||||
/** Target play-ahead for a measured 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));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export class JitterEstimator {
|
||||
private jitterMs = 0;
|
||||
private lastArrivalAt: number | null = null;
|
||||
private lastDurationMs = 20;
|
||||
|
||||
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);
|
||||
}
|
||||
this.lastArrivalAt = arrivalAt;
|
||||
this.lastDurationMs = duration;
|
||||
return this.targetAheadMs(maxMs);
|
||||
}
|
||||
|
||||
targetAheadMs(maxMs = MAX_TARGET_AHEAD_MS): number {
|
||||
return computeTargetAheadMs(this.jitterMs, maxMs);
|
||||
}
|
||||
|
||||
get jitter(): number {
|
||||
return this.jitterMs;
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.jitterMs = 0;
|
||||
this.lastArrivalAt = null;
|
||||
this.lastDurationMs = 20;
|
||||
}
|
||||
}
|
||||
|
||||
/** A large positive overrun: drop only the schedule, never the decoder. */
|
||||
export function shouldResetSchedule(aheadMs: number, targetMs: number): boolean {
|
||||
return aheadMs > targetMs + 60;
|
||||
}
|
||||
|
||||
/** The play head is close to real time; pull it back to the target. */
|
||||
export function shouldRecover(aheadMs: number): boolean {
|
||||
return aheadMs < 20;
|
||||
}
|
||||
@@ -59,20 +59,23 @@ export function createMicrophoneCaptureFactory() {
|
||||
let worklet: AudioWorkletNode | null = null;
|
||||
let script: ScriptProcessorNode | null = null;
|
||||
let active = false;
|
||||
let captureConnected = false;
|
||||
let disposed = false;
|
||||
const clean = (operation: () => void) => { try { operation(); } catch { /* release the other resources too */ } };
|
||||
function stopCapture() {
|
||||
active = false;
|
||||
if (worklet) { clean(() => worklet!.port.close()); clean(() => worklet!.disconnect()); }
|
||||
if (!captureConnected) return;
|
||||
if (worklet) clean(() => worklet!.disconnect());
|
||||
if (script) clean(() => script!.disconnect());
|
||||
if (gain) clean(() => gain!.disconnect());
|
||||
if (silent) clean(() => silent!.disconnect());
|
||||
worklet = null; script = null; gain = null; silent = null;
|
||||
captureConnected = false;
|
||||
}
|
||||
function dispose() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
stopCapture();
|
||||
if (worklet) clean(() => worklet!.port.close());
|
||||
if (denoiser) { clean(() => denoiser!.destroy()); clean(() => denoiser!.disconnect()); }
|
||||
if (source) clean(() => source!.disconnect());
|
||||
if (destination) {
|
||||
@@ -140,6 +143,7 @@ export function createMicrophoneCaptureFactory() {
|
||||
gain.connect(capture);
|
||||
capture.connect(silent);
|
||||
silent.connect(ctx.destination);
|
||||
captureConnected = true;
|
||||
assertCurrent();
|
||||
if (track.readyState !== "live") throw new DOMException("Microphone track ended", "NotReadableError");
|
||||
return {
|
||||
@@ -150,7 +154,17 @@ export function createMicrophoneCaptureFactory() {
|
||||
autoGainControl: typeof settings.autoGainControl === "boolean" ? settings.autoGainControl : null,
|
||||
rnnoise: Boolean(denoiser),
|
||||
},
|
||||
activate() { if (!disposed && (worklet || script)) active = true; },
|
||||
activate() {
|
||||
if (disposed || !(worklet || script)) return;
|
||||
if (!captureConnected) {
|
||||
processedSource.connect(gain!);
|
||||
gain!.connect(capture);
|
||||
capture.connect(silent!);
|
||||
silent!.connect(ctx.destination);
|
||||
captureConnected = true;
|
||||
}
|
||||
active = true;
|
||||
},
|
||||
setVolume(value) { if (gain) gain.gain.value = value; },
|
||||
stopCapture,
|
||||
dispose,
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* Optional Opus uplink for the PCM-over-WebSocket fallback path.
|
||||
*
|
||||
* The browser already has a microphone AudioWorklet that produces 48 kHz
|
||||
* mono Float32 samples. WebCodecs encodes the same 20 ms frames that the PCM
|
||||
* path would have sent, but at 16-24 kbps instead of ~96 KB/s. Safari and
|
||||
* older browsers do not expose an audio AudioEncoder, so the caller keeps the
|
||||
* PCM path and this module simply reports itself inactive.
|
||||
*/
|
||||
|
||||
import { VOICE_FRAME_SAMPLES, VOICE_MAX_OPUS_FRAME_BYTES, VOICE_OPUS_TAG } from "../../../src/shared/voice-audio.js";
|
||||
|
||||
interface AudioEncoderLike {
|
||||
readonly state: "unconfigured" | "configured" | "closed";
|
||||
readonly encodeQueueSize: number;
|
||||
configure(config: AudioEncoderConfig): void;
|
||||
encode(data: AudioData): void;
|
||||
reset(): void;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
interface OpusUplinkOptions {
|
||||
/** Return false when the socket is closed or above its outbound budget. */
|
||||
send(frame: Uint8Array): boolean;
|
||||
onDrop(): void;
|
||||
onFallback(reason: string): void;
|
||||
createEncoder?: (output: (chunk: EncodedAudioChunk) => void, error: (error: DOMException) => void) => AudioEncoderLike;
|
||||
createAudioData?: (frame: Float32Array, timestampUs: number) => AudioData;
|
||||
}
|
||||
|
||||
const FRAME_DURATION_US = 20_000;
|
||||
const MAX_ENCODE_QUEUE = 4;
|
||||
const OPUS_CONFIG: AudioEncoderConfig = {
|
||||
codec: "opus",
|
||||
sampleRate: 48_000,
|
||||
numberOfChannels: 1,
|
||||
bitrate: 24_000,
|
||||
opus: {
|
||||
frameDuration: FRAME_DURATION_US,
|
||||
complexity: 5,
|
||||
packetlossperc: 0,
|
||||
useinbandfec: false,
|
||||
usedtx: false,
|
||||
},
|
||||
};
|
||||
|
||||
export function createOpusUplink(options: OpusUplinkOptions) {
|
||||
let encoder: AudioEncoderLike | null = null;
|
||||
let active = false;
|
||||
let closed = false;
|
||||
let lifecycle = 0;
|
||||
let timestampUs = 0;
|
||||
let pending = new Float32Array(VOICE_FRAME_SAMPLES);
|
||||
let pendingLength = 0;
|
||||
|
||||
function emit(frame: Uint8Array): void {
|
||||
if (!active || closed) return;
|
||||
if (!options.send(frame)) options.onDrop();
|
||||
}
|
||||
|
||||
function handleOutput(chunk: EncodedAudioChunk): void {
|
||||
try {
|
||||
if (!active || closed || chunk.byteLength <= 0) return;
|
||||
if (chunk.byteLength > VOICE_MAX_OPUS_FRAME_BYTES) {
|
||||
options.onFallback("OPUS_FRAME_TOO_LARGE");
|
||||
deactivate();
|
||||
return;
|
||||
}
|
||||
const frame = new Uint8Array(1 + chunk.byteLength);
|
||||
frame[0] = VOICE_OPUS_TAG;
|
||||
chunk.copyTo(frame.subarray(1));
|
||||
emit(frame);
|
||||
} catch (error) {
|
||||
options.onFallback(error instanceof Error ? error.message : "OPUS_OUTPUT_FAILED");
|
||||
deactivate();
|
||||
}
|
||||
}
|
||||
|
||||
function handleError(error: DOMException): void {
|
||||
if (!active) return;
|
||||
options.onFallback(error?.name || "OPUS_ENCODER_ERROR");
|
||||
deactivate();
|
||||
}
|
||||
|
||||
function deactivate(): void {
|
||||
lifecycle++;
|
||||
active = false;
|
||||
try { encoder?.close(); } catch { /* already closed */ }
|
||||
encoder = null;
|
||||
pendingLength = 0;
|
||||
}
|
||||
|
||||
async function init(): Promise<boolean> {
|
||||
if (closed) return false;
|
||||
deactivate();
|
||||
const attempt = lifecycle;
|
||||
const factory = options.createEncoder;
|
||||
const Encoder = factory ? null : (globalThis as unknown as { AudioEncoder?: typeof AudioEncoder }).AudioEncoder;
|
||||
if (!factory && !Encoder) return false;
|
||||
try {
|
||||
if (!factory && Encoder?.isConfigSupported) {
|
||||
const support = await Encoder.isConfigSupported(OPUS_CONFIG);
|
||||
if (!support.supported) return false;
|
||||
}
|
||||
if (closed || attempt !== lifecycle) return false;
|
||||
const output = (chunk: EncodedAudioChunk) => { if (attempt === lifecycle) handleOutput(chunk); };
|
||||
const error = (reason: DOMException) => { if (attempt === lifecycle) handleError(reason); };
|
||||
const next = factory ? factory(output, error) : new Encoder!({ output, error });
|
||||
next.configure(OPUS_CONFIG);
|
||||
encoder = next;
|
||||
active = true;
|
||||
timestampUs = 0;
|
||||
pendingLength = 0;
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (closed || attempt !== lifecycle) return false;
|
||||
options.onFallback(error instanceof Error ? error.message : "OPUS_CONFIG_UNSUPPORTED");
|
||||
deactivate();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function encodePending(): void {
|
||||
if (!encoder || !active || pendingLength < VOICE_FRAME_SAMPLES) return;
|
||||
if (encoder.encodeQueueSize >= MAX_ENCODE_QUEUE) {
|
||||
// The encoder is behind; drop the oldest unsent frame rather than
|
||||
// building an ever-growing latency tail.
|
||||
options.onDrop();
|
||||
pending.copyWithin(0, VOICE_FRAME_SAMPLES, pendingLength);
|
||||
pendingLength -= VOICE_FRAME_SAMPLES;
|
||||
return;
|
||||
}
|
||||
const frame = pending.slice(0, VOICE_FRAME_SAMPLES);
|
||||
try {
|
||||
const audioData = options.createAudioData
|
||||
? options.createAudioData(frame, timestampUs)
|
||||
: new AudioData({
|
||||
format: "f32-planar",
|
||||
sampleRate: 48_000,
|
||||
numberOfFrames: VOICE_FRAME_SAMPLES,
|
||||
numberOfChannels: 1,
|
||||
timestamp: timestampUs,
|
||||
data: frame.buffer as ArrayBuffer,
|
||||
});
|
||||
encoder.encode(audioData);
|
||||
audioData.close?.();
|
||||
timestampUs += FRAME_DURATION_US;
|
||||
} catch (error) {
|
||||
options.onFallback(error instanceof Error ? error.message : "OPUS_ENCODE_FAILED");
|
||||
deactivate();
|
||||
return;
|
||||
}
|
||||
pendingLength -= VOICE_FRAME_SAMPLES;
|
||||
if (pendingLength > 0) pending.copyWithin(0, VOICE_FRAME_SAMPLES, VOICE_FRAME_SAMPLES + pendingLength);
|
||||
}
|
||||
|
||||
function push(samples: Float32Array): boolean {
|
||||
if (!active || closed || !samples.length) return active;
|
||||
let offset = 0;
|
||||
while (offset < samples.length) {
|
||||
const copy = Math.min(VOICE_FRAME_SAMPLES - pendingLength, samples.length - offset);
|
||||
pending.set(samples.subarray(offset, offset + copy), pendingLength);
|
||||
pendingLength += copy;
|
||||
offset += copy;
|
||||
if (pendingLength === VOICE_FRAME_SAMPLES) encodePending();
|
||||
}
|
||||
return active;
|
||||
}
|
||||
|
||||
/** Called when VOX closes or the input graph restarts; keeps the encoder configured. */
|
||||
function resetStream(): void {
|
||||
pendingLength = 0;
|
||||
timestampUs = 0;
|
||||
try { encoder?.reset(); } catch { /* reset is best effort */ }
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
closed = true;
|
||||
deactivate();
|
||||
}
|
||||
|
||||
function disable(): void {
|
||||
deactivate();
|
||||
}
|
||||
|
||||
return {
|
||||
init,
|
||||
push,
|
||||
resetStream,
|
||||
close,
|
||||
disable,
|
||||
get active() { return active; },
|
||||
};
|
||||
}
|
||||
@@ -1,13 +1,24 @@
|
||||
import { opusPacketDurationUs } from "./opus-packet.js";
|
||||
import { computeTargetAheadMs, JitterEstimator, shouldRecover, shouldResetSchedule } from "./jitter-buffer.js";
|
||||
|
||||
type RemotePlaybackMode = "legacy" | "adaptive";
|
||||
|
||||
interface RemotePlaybackOptions {
|
||||
getContext(): AudioContext;
|
||||
getVolume(clientId: number): number;
|
||||
onDecodeError(): void;
|
||||
onDrop(): void;
|
||||
/**
|
||||
* Legacy keeps the original fixed 80 ms window and decoder teardown. Adaptive
|
||||
* is the CFT-oriented path. Defaults to legacy for direct deployments.
|
||||
*/
|
||||
mode?: RemotePlaybackMode | (() => RemotePlaybackMode);
|
||||
/** Upper bound for the adaptive buffer; ignored in legacy mode. */
|
||||
maxBufferAheadMs?: number | (() => number);
|
||||
}
|
||||
|
||||
interface SpeakerPlayback {
|
||||
mode: RemotePlaybackMode;
|
||||
codec: 4 | 5;
|
||||
context: AudioContext;
|
||||
decoder: AudioDecoder | null;
|
||||
@@ -15,15 +26,45 @@ interface SpeakerPlayback {
|
||||
sources: Set<AudioBufferSourceNode>;
|
||||
playTime: number;
|
||||
timestamp: number;
|
||||
jitter: JitterEstimator;
|
||||
resets: number;
|
||||
maxAheadMs: number;
|
||||
}
|
||||
|
||||
export interface FallbackPlaybackStats {
|
||||
bufferTargetMs: number;
|
||||
bufferResets: number;
|
||||
maxBufferAheadMs: number;
|
||||
}
|
||||
|
||||
// Preserve the compatibility path's bounded jitter buffer and decoder queue.
|
||||
const MAX_PLAY_AHEAD_SECONDS = 0.08;
|
||||
const MAX_DECODE_QUEUE_FRAMES = 3;
|
||||
const LEGACY_MAX_PLAY_AHEAD_SECONDS = 0.08;
|
||||
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;
|
||||
|
||||
export function createRemotePlayback(options: RemotePlaybackOptions) {
|
||||
const speakers = new Map<number, SpeakerPlayback>();
|
||||
|
||||
function mode(): RemotePlaybackMode {
|
||||
const configured = options.mode;
|
||||
try {
|
||||
return typeof configured === "function" ? configured() : configured ?? "legacy";
|
||||
} catch {
|
||||
return "legacy";
|
||||
}
|
||||
}
|
||||
|
||||
function maxBufferAheadMs(): number {
|
||||
const configured = options.maxBufferAheadMs;
|
||||
try {
|
||||
return typeof configured === "function" ? configured() : configured ?? 300;
|
||||
} catch {
|
||||
return 300;
|
||||
}
|
||||
}
|
||||
|
||||
function clear(clientId: number): void {
|
||||
const stream = speakers.get(clientId);
|
||||
if (!stream) return;
|
||||
@@ -38,34 +79,80 @@ export function createRemotePlayback(options: RemotePlaybackOptions) {
|
||||
stream.gain.disconnect();
|
||||
}
|
||||
|
||||
function resetSchedule(stream: SpeakerPlayback, targetSeconds: number): void {
|
||||
for (const source of stream.sources) {
|
||||
try { source.stop(); } catch { /* not started or already ended */ }
|
||||
source.disconnect();
|
||||
}
|
||||
stream.sources.clear();
|
||||
stream.playTime = stream.context.currentTime + targetSeconds;
|
||||
stream.resets++;
|
||||
}
|
||||
|
||||
function enqueueChunk(stream: SpeakerPlayback, chunk: AudioData, startTime: number): number {
|
||||
const { context, gain, sources } = stream;
|
||||
const { sampleRate, numberOfChannels, numberOfFrames } = chunk;
|
||||
const duration = numberOfFrames / sampleRate;
|
||||
const buffer = context.createBuffer(numberOfChannels, numberOfFrames, sampleRate);
|
||||
for (let channel = 0; channel < numberOfChannels; channel++) {
|
||||
const samples = new Float32Array(numberOfFrames);
|
||||
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);
|
||||
return duration;
|
||||
}
|
||||
|
||||
function outputLegacy(clientId: number, stream: SpeakerPlayback, chunk: AudioData): void {
|
||||
const context = stream.context;
|
||||
const playTime = Math.max(stream.playTime, context.currentTime);
|
||||
const duration = chunk.numberOfFrames / chunk.sampleRate;
|
||||
if (playTime + duration > context.currentTime + LEGACY_MAX_PLAY_AHEAD_SECONDS) {
|
||||
stream.resets++;
|
||||
clear(clientId);
|
||||
return;
|
||||
}
|
||||
enqueueChunk(stream, chunk, playTime);
|
||||
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 {
|
||||
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 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;
|
||||
stream.maxAheadMs = Math.max(stream.maxAheadMs, (stream.playTime - context.currentTime) * 1_000);
|
||||
}
|
||||
|
||||
function output(clientId: number, stream: SpeakerPlayback, chunk: AudioData): void {
|
||||
try {
|
||||
if (speakers.get(clientId) !== stream) return;
|
||||
const { context, gain, sources } = stream;
|
||||
const { sampleRate, numberOfChannels, numberOfFrames } = chunk;
|
||||
const playTime = Math.max(stream.playTime, context.currentTime);
|
||||
const duration = numberOfFrames / sampleRate;
|
||||
if (playTime + duration > context.currentTime + MAX_PLAY_AHEAD_SECONDS) {
|
||||
clear(clientId);
|
||||
return;
|
||||
}
|
||||
const buffer = context.createBuffer(numberOfChannels, numberOfFrames, sampleRate);
|
||||
for (let channel = 0; channel < numberOfChannels; channel++) {
|
||||
const samples = new Float32Array(numberOfFrames);
|
||||
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(playTime);
|
||||
stream.playTime = playTime + duration;
|
||||
if (stream.mode === "legacy") outputLegacy(clientId, stream, chunk);
|
||||
else outputAdaptive(clientId, stream, chunk);
|
||||
} catch {
|
||||
if (speakers.get(clientId) === stream) {
|
||||
options.onDecodeError();
|
||||
@@ -76,10 +163,12 @@ export function createRemotePlayback(options: RemotePlaybackOptions) {
|
||||
}
|
||||
}
|
||||
|
||||
function create(clientId: number, context: AudioContext, codec: 4 | 5): SpeakerPlayback {
|
||||
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 = {
|
||||
codec, context, decoder: null, gain: context.createGain(), sources: new Set(),
|
||||
playTime: context.currentTime, timestamp: 0,
|
||||
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,
|
||||
};
|
||||
speakers.set(clientId, stream);
|
||||
stream.gain.gain.value = options.getVolume(clientId);
|
||||
@@ -101,13 +190,40 @@ export function createRemotePlayback(options: RemotePlaybackOptions) {
|
||||
if (!duration || opusData.length < 3) { options.onDrop(); return; }
|
||||
try {
|
||||
const context = options.getContext();
|
||||
const streamMode = mode();
|
||||
let stream = speakers.get(clientId);
|
||||
if (stream && (stream.codec !== codec || stream.context !== context || stream.playTime > context.currentTime + MAX_PLAY_AHEAD_SECONDS || (stream.decoder?.decodeQueueSize ?? 0) >= MAX_DECODE_QUEUE_FRAMES)) {
|
||||
const legacyOverflow = stream !== undefined && streamMode === "legacy"
|
||||
&& (stream.playTime > context.currentTime + LEGACY_MAX_PLAY_AHEAD_SECONDS
|
||||
|| (stream.decoder?.decodeQueueSize ?? 0) >= LEGACY_MAX_DECODE_QUEUE_FRAMES);
|
||||
if (stream && (stream.codec !== codec || stream.context !== context || stream.mode !== streamMode || legacyOverflow)) {
|
||||
clear(clientId);
|
||||
stream = undefined;
|
||||
}
|
||||
stream ??= create(clientId, context, codec);
|
||||
stream ??= create(clientId, context, codec, streamMode);
|
||||
if (speakers.get(clientId) !== stream) return;
|
||||
|
||||
if (streamMode === "legacy") {
|
||||
stream.decoder?.decode(new EncodedAudioChunk({ type: "key", timestamp: stream.timestamp, duration, data: opusData }));
|
||||
stream.timestamp += duration;
|
||||
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 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.
|
||||
options.onDrop();
|
||||
return;
|
||||
}
|
||||
stream.decoder?.decode(new EncodedAudioChunk({ type: "key", timestamp: stream.timestamp, duration, data: opusData }));
|
||||
stream.timestamp += duration;
|
||||
} catch {
|
||||
@@ -116,10 +232,29 @@ export function createRemotePlayback(options: RemotePlaybackOptions) {
|
||||
}
|
||||
}
|
||||
|
||||
function getStats(): FallbackPlaybackStats {
|
||||
let target = 0;
|
||||
let resets = 0;
|
||||
let maxAhead = 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);
|
||||
}
|
||||
return {
|
||||
bufferTargetMs: Math.round(target),
|
||||
bufferResets: resets,
|
||||
maxBufferAheadMs: Math.round(maxAhead),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
play,
|
||||
clear,
|
||||
clearAll() { for (const id of speakers.keys()) clear(id); },
|
||||
getStats,
|
||||
updateVolume(clientId: number) {
|
||||
const stream = speakers.get(clientId);
|
||||
if (stream) stream.gain.gain.value = options.getVolume(clientId);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { isSessionDescription, type WebRtcClientMessage } from "../../../src/shared/webrtc.js";
|
||||
import { hasVoiceTurnServer, type VoiceIceServer } from "../../../src/shared/voice-ice.js";
|
||||
import { createWebRtcInput, type WebRtcInput } from "./webrtc-input.js";
|
||||
import { createMicrophoneMeter, type MicrophoneMeter } from "./microphone-meter.js";
|
||||
import { createWebRtcPlayback, type WebRtcPlaybackOptions } from "./webrtc-playback.js";
|
||||
@@ -18,7 +19,8 @@ interface Connection {
|
||||
interface TransportOptions {
|
||||
prepareMicrophone(): Promise<Microphone | null>;
|
||||
stunServer?(): string;
|
||||
stopPcm(): void;
|
||||
iceServers?(): VoiceIceServer[];
|
||||
iceTransportPolicy?(): RTCIceTransportPolicy;
|
||||
muted(): boolean;
|
||||
inputVolume(): number;
|
||||
accompanimentActive(): boolean;
|
||||
@@ -26,7 +28,8 @@ interface TransportOptions {
|
||||
onLevel(rms: number | null, track: MediaStreamTrack): void;
|
||||
onReady(): void;
|
||||
onConnectionState?(state: RTCPeerConnectionState): void;
|
||||
onFallback(reason: string, isCurrent: () => boolean): Promise<void>;
|
||||
onIceCandidateError?(errorCode: number, url?: string): void;
|
||||
onFailure(reason: string, isCurrent: () => boolean): Promise<void>;
|
||||
playback: WebRtcPlaybackOptions;
|
||||
}
|
||||
|
||||
@@ -85,15 +88,14 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
}
|
||||
}
|
||||
|
||||
async function fail(record: Attempt, reason: string): Promise<void> {
|
||||
async function failAttempt(record: Attempt, reason: string): Promise<void> {
|
||||
if (!isCurrent(record)) return;
|
||||
// Signaling is best-effort once the transport fails. It cannot prevent
|
||||
// local teardown or compatibility capture when the socket send throws.
|
||||
// Signaling is best-effort once the transport fails. It cannot prevent local teardown when the socket send throws.
|
||||
clean(() => record.connection.send({ type: "webrtcStop" }));
|
||||
stop();
|
||||
const fallbackGeneration = generation;
|
||||
const isFallbackCurrent = (): boolean => generation === fallbackGeneration && record.connection.isCurrent();
|
||||
if (isFallbackCurrent()) await options.onFallback(reason, isFallbackCurrent);
|
||||
const failureGeneration = generation;
|
||||
const isFailureCurrent = (): boolean => generation === failureGeneration && record.connection.isCurrent();
|
||||
if (isFailureCurrent()) await options.onFailure(reason, isFailureCurrent);
|
||||
}
|
||||
|
||||
async function waitForIce(record: Attempt, peer: RTCPeerConnection): Promise<void> {
|
||||
@@ -109,7 +111,7 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
resolve();
|
||||
};
|
||||
const onStateChange = (): void => { if (peer.iceGatheringState === "complete") finish(); };
|
||||
const timer = window.setTimeout(finish, 5_000);
|
||||
const timer = window.setTimeout(finish, 6_000);
|
||||
record.cancelIce = finish;
|
||||
peer.addEventListener("icegatheringstatechange", onStateChange);
|
||||
});
|
||||
@@ -129,10 +131,23 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
if (!track || track.readyState !== "live") throw new Error("没有可用的麦克风音轨");
|
||||
|
||||
try {
|
||||
options.stopPcm();
|
||||
const stunServer = options.stunServer?.();
|
||||
const peer = new RTCPeerConnection({ iceServers: stunServer ? [{ urls: stunServer }] : [] });
|
||||
const configuredIceServers = options.iceServers?.() ?? [];
|
||||
const iceServers = configuredIceServers.length ? configuredIceServers : (stunServer ? [{ urls: stunServer }] : []);
|
||||
const iceTransportPolicy = options.iceTransportPolicy?.() ?? "all";
|
||||
if (iceTransportPolicy === "relay" && !hasVoiceTurnServer(iceServers)) {
|
||||
await failAttempt(record, "WEBRTC_NO_RELAY");
|
||||
return;
|
||||
}
|
||||
const peer = new RTCPeerConnection({
|
||||
iceServers,
|
||||
iceTransportPolicy,
|
||||
bundlePolicy: "max-bundle",
|
||||
});
|
||||
record.peer = peer;
|
||||
peer.onicecandidateerror = event => {
|
||||
options.onIceCandidateError?.(event.errorCode, event.url);
|
||||
};
|
||||
track.enabled = !options.muted();
|
||||
const input = createWebRtcInput(context, processedStream, options.muted() ? 0 : options.inputVolume());
|
||||
record.input = input;
|
||||
@@ -140,12 +155,12 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
peer.ontrack = event => {
|
||||
if (!isCurrent(record)) return;
|
||||
try { playback.attach(event.streams[0] ?? new MediaStream([event.track])); }
|
||||
catch { void fail(record, "WEBRTC_PLAYBACK_FAILED"); }
|
||||
catch { void failAttempt(record, "WEBRTC_PLAYBACK_FAILED"); }
|
||||
};
|
||||
record.meter = createMicrophoneMeter(context, stream, rms => options.onLevel(rms, track));
|
||||
peer.onconnectionstatechange = () => {
|
||||
options.onConnectionState?.(peer.connectionState);
|
||||
if (isCurrent(record) && peer.connectionState === "failed") void fail(record, "WEBRTC_CONNECTION_FAILED");
|
||||
if (isCurrent(record) && peer.connectionState === "failed") void failAttempt(record, "WEBRTC_CONNECTION_FAILED");
|
||||
};
|
||||
options.onConnectionState?.(peer.connectionState);
|
||||
|
||||
@@ -165,10 +180,10 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
record.answerTimer = window.setTimeout(() => {
|
||||
if (!isCurrent(record)) return;
|
||||
record.answerTimer = null;
|
||||
if (!peer.remoteDescription) void fail(record, "WEBRTC_ANSWER_TIMEOUT");
|
||||
if (!peer.remoteDescription) void failAttempt(record, "WEBRTC_ANSWER_TIMEOUT");
|
||||
}, 8_000);
|
||||
} catch {
|
||||
await fail(record, "WEBRTC_NEGOTIATION_FAILED");
|
||||
await failAttempt(record, "WEBRTC_NEGOTIATION_FAILED");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,14 +198,14 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
record.answerTimer = null;
|
||||
record.active = true;
|
||||
options.onReady();
|
||||
} catch { await fail(record, "WEBRTC_ANSWER_REJECTED"); }
|
||||
} catch { await failAttempt(record, "WEBRTC_ANSWER_REJECTED"); }
|
||||
}
|
||||
|
||||
return {
|
||||
start, stop, applyAnswer,
|
||||
get generation(): number { return generation; },
|
||||
releaseInput(): void { releaseInput(); },
|
||||
async fallback(reason: string): Promise<void> { if (current) await fail(current, reason); },
|
||||
async fail(reason: string): Promise<void> { if (current) await failAttempt(current, reason); },
|
||||
get peer(): RTCPeerConnection | null { return current?.peer ?? null; },
|
||||
get input(): WebRtcInput | null { return current?.input ?? null; },
|
||||
get active(): boolean { return current?.active ?? false; },
|
||||
|
||||
@@ -14,6 +14,7 @@ import { createAdminApi } from "../src/services/admin-api.js";
|
||||
import { adminResponses } from "../../src/shared/admin-responses.js";
|
||||
import type { QueryClient, QueryClientOptions } from "@honeybbq/teamspeak/query";
|
||||
import { decryptSecret } from "../../src/security/secret-crypto.js";
|
||||
import { DEFAULT_VOICE_ICE_CONFIG, type VoiceIceConfig } from "../../src/server/voice-ice-config.js";
|
||||
|
||||
const logger: Logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
|
||||
|
||||
@@ -23,7 +24,7 @@ test("schema 7 upgrades preserve the previously unused public host and initializ
|
||||
const original = new WebSpeakDatabase(filename);
|
||||
original.close();
|
||||
const legacy = new DatabaseSync(filename);
|
||||
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; ALTER TABLE settings DROP COLUMN webrtc_ipv6_enabled; ALTER TABLE settings DROP COLUMN webrtc_stun_server; DROP TABLE workspace_invites; PRAGMA user_version = 7;");
|
||||
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; ALTER TABLE settings DROP COLUMN webrtc_ipv6_enabled; ALTER TABLE settings DROP COLUMN webrtc_stun_server; DROP TABLE workspace_invites; ALTER TABLE settings DROP COLUMN voice_profile; ALTER TABLE settings DROP COLUMN voice_turn_urls; ALTER TABLE settings DROP COLUMN voice_turn_secret_encrypted; ALTER TABLE settings DROP COLUMN voice_turn_ttl_seconds; ALTER TABLE settings DROP COLUMN voice_opus_ws; ALTER TABLE settings DROP COLUMN voice_jitter_max_ms; PRAGMA user_version = 7;");
|
||||
legacy.prepare("UPDATE settings SET webrtc_public_host = ?").run("media.example.com");
|
||||
legacy.close();
|
||||
const migrated = new WebSpeakDatabase(filename);
|
||||
@@ -38,6 +39,45 @@ test("schema 7 upgrades preserve the previously unused public host and initializ
|
||||
assert.equal(migrated.getSettings().webRtcStunServer, "");
|
||||
});
|
||||
|
||||
test("voice console overrides preserve environment inheritance until explicitly changed", t => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "webspeak-voice-admin-"));
|
||||
const database = new WebSpeakDatabase(join(directory, "test.db"));
|
||||
t.after(() => {
|
||||
database.close();
|
||||
assert.equal(dirname(resolve(directory)), resolve(tmpdir()));
|
||||
assert.ok(directory.includes("webspeak-voice-admin-"));
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
const defaults: VoiceIceConfig = {
|
||||
...DEFAULT_VOICE_ICE_CONFIG,
|
||||
profile: "adaptive",
|
||||
opusWebSocket: true,
|
||||
jitterMaxMs: 180,
|
||||
turnRest: { urls: ["turn:turn.example.com:3478"], secret: "environment-turn-secret", ttlSeconds: 3600 },
|
||||
};
|
||||
const service = new AdminService(database, Buffer.alloc(32, 7), logger, join(directory, "absent-config.json"), undefined, "test-version", undefined, defaults);
|
||||
const view = service.getAdminSettings();
|
||||
const base = { target: view.target, accessMode: view.accessMode, siteName: view.siteName, welcomeText: view.welcomeText, webRtcEnabled: view.webRtcEnabled };
|
||||
service.updateSettings({ ...base, siteName: "Renamed" });
|
||||
const inherited = database.getSettings();
|
||||
assert.equal(inherited.voiceProfile, null);
|
||||
assert.equal(inherited.voiceTurnUrls, null);
|
||||
assert.equal(inherited.voiceTurnSecretEncrypted, null);
|
||||
assert.equal(inherited.voiceTurnTtlSeconds, null);
|
||||
assert.equal(inherited.voiceOpusWs, null);
|
||||
assert.equal(inherited.voiceJitterMaxMs, null);
|
||||
assert.deepEqual(service.getVoiceIceConfig(), defaults);
|
||||
|
||||
service.updateSettings({ ...base, voiceProfile: "legacy", voiceTurnUrls: "", voiceTurnSecretAction: "remove", voiceOpusWs: false, voiceJitterMaxMs: 80 });
|
||||
const overridden = database.getSettings();
|
||||
assert.equal(overridden.voiceProfile, "legacy");
|
||||
assert.equal(overridden.voiceTurnUrls, "");
|
||||
assert.equal(overridden.voiceTurnSecretEncrypted, "");
|
||||
assert.equal(overridden.voiceOpusWs, false);
|
||||
assert.equal(overridden.voiceJitterMaxMs, 80);
|
||||
assert.equal(service.getVoiceIceConfig().turnRest, undefined);
|
||||
});
|
||||
|
||||
test("browser admin API consumes the actual HTTP router and preserves keep/replace/remove secrets", async t => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "webspeak-admin-api-"));
|
||||
const database = new WebSpeakDatabase(join(directory, "test.db"));
|
||||
@@ -108,17 +148,35 @@ test("browser admin API consumes the actual HTTP router and preserves keep/repla
|
||||
const tsAdminInitial = await api.tsAdminSettings();
|
||||
assert.deepEqual({ fixedMode: tsAdminInitial.fixedMode, enabled: tsAdminInitial.enabled, hasPassword: tsAdminInitial.hasPassword }, { fixedMode: true, enabled: false, hasPassword: false });
|
||||
const original = await api.settings();
|
||||
const voiceKeys = new Set(["voiceProfile", "voiceTurnUrls", "hasVoiceTurnSecret", "voiceTurnTtlSeconds", "voiceOpusWs", "voiceJitterMaxMs"]);
|
||||
const withoutVoiceSettings = (value: typeof original) => Object.fromEntries(Object.entries(value).filter(([key]) => !voiceKeys.has(key))) as typeof original;
|
||||
assert.equal(original.webRtcPublicHost, "");
|
||||
assert.equal(original.webRtcIpv6Enabled, false);
|
||||
assert.equal(original.webRtcStunServer, "");
|
||||
assert.equal(original.voiceProfile, "auto");
|
||||
assert.equal(original.voiceTurnUrls, "");
|
||||
assert.equal(original.hasVoiceTurnSecret, false);
|
||||
assert.equal(original.voiceTurnTtlSeconds, 21600);
|
||||
assert.equal(original.voiceOpusWs, false);
|
||||
assert.equal(original.voiceJitterMaxMs, 300);
|
||||
const network = { webRtcPublicHost: " MEDIA.example.com ", webRtcIpv6Enabled: true, webRtcStunServer: "stun:stun.example.com" };
|
||||
const updated = await api.saveSettings({ ...original, ...network });
|
||||
const updated = await api.saveSettings({ ...withoutVoiceSettings(original), ...network });
|
||||
assert.equal(updated.settings.webRtcPublicHost, "media.example.com");
|
||||
assert.equal(updated.settings.webRtcStunServer, "stun:stun.example.com:3478");
|
||||
assert.deepEqual(service.getWebRtcAudioOptions(), { enabled: false, publicHost: "media.example.com", ipv6Enabled: true, stunServer: "stun:stun.example.com:3478", udpPortRange: [40000, 40099] });
|
||||
const { webRtcPublicHost, webRtcIpv6Enabled, webRtcStunServer, ...legacyInput } = original;
|
||||
const legacyInput = withoutVoiceSettings(original);
|
||||
delete (legacyInput as Partial<typeof original>).webRtcPublicHost;
|
||||
delete (legacyInput as Partial<typeof original>).webRtcIpv6Enabled;
|
||||
delete (legacyInput as Partial<typeof original>).webRtcStunServer;
|
||||
await api.saveSettings(legacyInput);
|
||||
assert.equal((await api.settings()).webRtcPublicHost, "media.example.com", "older clients must preserve the new settings");
|
||||
const inheritedVoice = database.getSettings();
|
||||
assert.equal(inheritedVoice.voiceProfile, null);
|
||||
assert.equal(inheritedVoice.voiceTurnUrls, null);
|
||||
assert.equal(inheritedVoice.voiceTurnSecretEncrypted, null);
|
||||
assert.equal(inheritedVoice.voiceTurnTtlSeconds, null);
|
||||
assert.equal(inheritedVoice.voiceOpusWs, null);
|
||||
assert.equal(inheritedVoice.voiceJitterMaxMs, null);
|
||||
for (const [key, value, code] of [
|
||||
["webRtcPublicHost", "https://media.example.com", "INVALID_WEBRTC_PUBLIC_HOST"],
|
||||
["webRtcPublicHost", null, "INVALID_WEBRTC_PUBLIC_HOST"],
|
||||
@@ -172,6 +230,41 @@ test("browser admin API consumes the actual HTTP router and preserves keep/repla
|
||||
assert.equal((await api.tsAdminSettings()).enabled, false, "switching to open mode disables the TeamSpeak admin panel");
|
||||
await assert.rejects(api.tsAdminOverview(), (error: any) => error.code === "TS_ADMIN_FIXED_MODE_REQUIRED");
|
||||
await assert.rejects(api.saveTsAdminSettings({ enabled: true, queryPort: 10022, username: "query-admin", hostKeyFingerprint: verifiedFingerprint }), (error: any) => error.code === "TS_ADMIN_FIXED_MODE_REQUIRED");
|
||||
const voiceInput = {
|
||||
...(await api.settings()),
|
||||
voiceProfile: "adaptive" as const,
|
||||
voiceTurnUrls: "turn:turn.example.com:3478\nturns:turn.example.com:5349?transport=tcp",
|
||||
voiceTurnSecret: "fixture-turn-shared-secret",
|
||||
voiceTurnSecretAction: "replace" as const,
|
||||
voiceTurnTtlSeconds: 3600,
|
||||
voiceOpusWs: true,
|
||||
voiceJitterMaxMs: 200,
|
||||
};
|
||||
const savedVoice = await api.saveSettings(voiceInput);
|
||||
assert.equal(savedVoice.settings.voiceProfile, "adaptive");
|
||||
assert.equal(savedVoice.settings.hasVoiceTurnSecret, true);
|
||||
assert.equal(savedVoice.settings.voiceTurnTtlSeconds, 3600);
|
||||
assert.equal(savedVoice.settings.voiceOpusWs, true);
|
||||
assert.equal(savedVoice.settings.voiceJitterMaxMs, 200);
|
||||
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");
|
||||
assert.notEqual(storedVoice.voiceTurnSecretEncrypted, "fixture-turn-shared-secret");
|
||||
assert.equal(decryptSecret(storedVoice.voiceTurnSecretEncrypted, Buffer.alloc(32, 7), "webspeak:voice-turn-rest-secret:v1"), "fixture-turn-shared-secret");
|
||||
const voiceConfig = service.getVoiceIceConfig();
|
||||
assert.equal(voiceConfig.profile, "adaptive");
|
||||
assert.equal(voiceConfig.opusWebSocket, true);
|
||||
assert.equal(voiceConfig.jitterMaxMs, 200);
|
||||
assert.deepEqual(voiceConfig.turnRest, {
|
||||
urls: ["turn:turn.example.com:3478", "turns:turn.example.com:5349?transport=tcp"],
|
||||
secret: "fixture-turn-shared-secret",
|
||||
ttlSeconds: 3600,
|
||||
});
|
||||
await assert.rejects(api.saveSettings({ ...voiceInput, voiceTurnUrls: "stun:stun.example.com:3478" }), (error: any) => error.code === "INVALID_VOICE_TURN_URLS");
|
||||
await assert.rejects(api.saveSettings({ ...voiceInput, voiceTurnSecret: "short-secret", voiceTurnSecretAction: "replace" }), (error: any) => error.code === "INVALID_VOICE_TURN_SECRET");
|
||||
const removedTurnSecret = await api.saveSettings({ ...(await api.settings()), voiceTurnSecretAction: "remove" });
|
||||
assert.equal(removedTurnSecret.settings.hasVoiceTurnSecret, false);
|
||||
assert.equal(service.getVoiceIceConfig().turnRest, undefined);
|
||||
const settings = service.getAdminSettings();
|
||||
assert.deepEqual(adminResponses.settings({ ...settings, passwordAction: "remove", serverPassword: "injected" }), settings);
|
||||
const created = await api.createInvite({ channel: "Lobby", expiresInHours: 1, maxUses: 1 });
|
||||
|
||||
@@ -27,6 +27,7 @@ const settings = (extra = {}) => ({
|
||||
welcomeDefaults: { zh: "", en: "", de: "", ru: "", ja: "" },
|
||||
lastTestAt: null, lastTestLatencyMs: null, lastTestError: null,
|
||||
webRtcEnabled: false, webRtcUdpStart: 40000, webRtcUdpEnd: 40099,
|
||||
voiceProfile: "auto", voiceTurnUrls: "", hasVoiceTurnSecret: false, voiceTurnTtlSeconds: 21600, voiceOpusWs: false, voiceJitterMaxMs: 300,
|
||||
relayConfigured: false, relayEnabled: false, relayName: "", relayTarget: "", hasRelayToken: false,
|
||||
relayNodes: [], internalPort: 3040, updatedAt: "2026-10-01T00:00:00Z", ...extra,
|
||||
});
|
||||
@@ -230,6 +231,60 @@ test("ICE settings load, submit and preserve edits made during a pending save",
|
||||
assert.equal(serverModel.serverForm.webRtcStunServer, "");
|
||||
});
|
||||
|
||||
test("an unrelated settings save omits untouched voice overrides", async () => {
|
||||
await mount();
|
||||
const inheritedVoice = { voiceProfile: "adaptive", voiceTurnUrls: "turn:turn.example.com:3478", hasVoiceTurnSecret: true,
|
||||
voiceTurnTtlSeconds: 3600, voiceOpusWs: true, voiceJitterMaxMs: 200 };
|
||||
handler = path => Promise.resolve(json(path === "/server" ? settings(inheritedVoice) : defaults(path)));
|
||||
await serverModel.loadServerSettings();
|
||||
serverModel.serverForm.siteName = "Renamed";
|
||||
handler = (path, init) => {
|
||||
if (path !== "/server" || init.method !== "PUT") return Promise.resolve(json(defaults(path)));
|
||||
const submitted = JSON.parse(init.body);
|
||||
assert.equal(submitted.siteName, "Renamed");
|
||||
for (const key of ["voiceProfile", "voiceTurnUrls", "voiceTurnSecret", "voiceTurnSecretAction", "voiceTurnTtlSeconds", "voiceOpusWs", "voiceJitterMaxMs"]) {
|
||||
assert.equal(Object.hasOwn(submitted, key), false, `${key} must remain inherited when untouched`);
|
||||
}
|
||||
return Promise.resolve(json({ ok: true, settings: settings({ ...inheritedVoice, siteName: "Renamed" }) }));
|
||||
};
|
||||
await serverModel.saveServerSettings();
|
||||
assert.equal(state.errorMessage, "");
|
||||
});
|
||||
|
||||
test("voice settings load, submit secrets once, and preserve edits made during a pending save", async () => {
|
||||
await mount();
|
||||
const voice = { voiceProfile: "adaptive", voiceTurnUrls: "turn:turn.example.com:3478", hasVoiceTurnSecret: true,
|
||||
voiceTurnTtlSeconds: 3600, voiceOpusWs: true, voiceJitterMaxMs: 200 };
|
||||
handler = path => Promise.resolve(json(path === "/server" ? settings(voice) : defaults(path)));
|
||||
await serverModel.loadServerSettings();
|
||||
for (const [key, value] of Object.entries(voice)) assert.equal(serverModel.serverForm[key], value);
|
||||
Object.assign(serverModel.serverForm, {
|
||||
voiceProfile: "legacy", voiceTurnUrls: "turn:changed.example.com:3478", voiceTurnTtlSeconds: 7200,
|
||||
voiceOpusWs: false, voiceJitterMaxMs: 240, voiceTurnSecret: "fixture-turn-shared-secret", voiceTurnSecretAction: "replace",
|
||||
});
|
||||
const save = deferred();
|
||||
handler = (path, init) => {
|
||||
if (path !== "/server" || init.method !== "PUT") return Promise.resolve(json(defaults(path)));
|
||||
const submitted = JSON.parse(init.body);
|
||||
assert.equal(submitted.voiceProfile, "legacy");
|
||||
assert.equal(submitted.voiceTurnUrls, "turn:changed.example.com:3478");
|
||||
assert.equal(submitted.voiceTurnSecret, "fixture-turn-shared-secret");
|
||||
assert.equal(submitted.voiceTurnSecretAction, "replace");
|
||||
assert.equal(submitted.voiceTurnTtlSeconds, 7200);
|
||||
assert.equal(submitted.voiceOpusWs, false);
|
||||
assert.equal(submitted.voiceJitterMaxMs, 240);
|
||||
return save.promise;
|
||||
};
|
||||
const pending = serverModel.saveServerSettings();
|
||||
serverModel.serverForm.voiceTurnUrls = "turn:new-turn.example.com:3478";
|
||||
save.resolve(json({ ok: true, settings: settings(voice) }));
|
||||
await pending;
|
||||
assert.equal(serverModel.serverForm.voiceTurnUrls, "turn:new-turn.example.com:3478");
|
||||
assert.equal(serverModel.serverForm.voiceTurnSecret, "");
|
||||
assert.equal(serverModel.serverForm.voiceTurnSecretAction, "keep");
|
||||
assert.equal(serverModel.serverForm.hasVoiceTurnSecret, true);
|
||||
});
|
||||
|
||||
test("settings saves preserve relay edits, removals and additions made while awaiting the server", async () => {
|
||||
await mount();
|
||||
serverModel.addRelayNode(); serverModel.addRelayNode();
|
||||
@@ -717,6 +772,9 @@ test("settings and operations render explicit localized sections with valid deep
|
||||
const settingsHtml = await renderToString(createSSRApp(Settings, { model: state.serverSettings, i18n: state.i18n, initialSection: "site", welcomeLanguage: "zh" }));
|
||||
assert.ok(settingsHtml.includes(translations.adminSiteAnnouncement));
|
||||
assert.ok(settingsHtml.includes('data-admin-section="site"'));
|
||||
assert.ok(settingsHtml.includes('data-admin-section="voice"'));
|
||||
assert.ok(settingsHtml.includes(state.i18n.tr("voiceSettings")));
|
||||
assert.ok(settingsHtml.includes(state.i18n.tr("turnSettings")));
|
||||
assert.ok(!settingsHtml.includes("undefined"));
|
||||
const operationsHtml = await renderToString(createSSRApp(Operations, { model: state.adminOperations, i18n: state.i18n, initialSection: "maintenance" }));
|
||||
assert.ok(operationsHtml.includes(translations.adminBrowserSessionsLead));
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import {
|
||||
computeTargetAheadMs,
|
||||
JitterEstimator,
|
||||
shouldRecover,
|
||||
shouldResetSchedule,
|
||||
} from "../src/voice/jitter-buffer.ts";
|
||||
|
||||
test("target buffer maps 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(1_000), 300);
|
||||
});
|
||||
|
||||
test("a configured 80 ms ceiling restores the old buffer bound", () => {
|
||||
assert.equal(computeTargetAheadMs(100, 80), 80);
|
||||
assert.equal(computeTargetAheadMs(0, 80), 80);
|
||||
});
|
||||
|
||||
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.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(shouldRecover(10), true);
|
||||
assert.equal(shouldRecover(30), false);
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { createOpusUplink } from "../src/voice/opus-uplink.ts";
|
||||
|
||||
function fakeUplink() {
|
||||
let output: ((chunk: { byteLength: number; copyTo(target: Uint8Array): void }) => void) | null = null;
|
||||
const encoded: AudioData[] = [];
|
||||
const sent: Uint8Array[] = [];
|
||||
let dropped = 0;
|
||||
let configured = false;
|
||||
const encoder = {
|
||||
state: "configured" as const,
|
||||
encodeQueueSize: 0,
|
||||
configure() { configured = true; },
|
||||
encode(data: AudioData) {
|
||||
encoded.push(data);
|
||||
output?.({ byteLength: 3, copyTo(target: Uint8Array) { target.set([1, 2, 3]); } });
|
||||
},
|
||||
reset() {},
|
||||
close() {},
|
||||
};
|
||||
const uplink = createOpusUplink({
|
||||
send(frame) { sent.push(frame); return true; },
|
||||
onDrop() { dropped++; },
|
||||
onFallback() {},
|
||||
createEncoder: (nextOutput) => { output = nextOutput; return encoder; },
|
||||
createAudioData: () => ({}) as AudioData,
|
||||
});
|
||||
return { uplink, encoded, sent, encoder, configured: () => configured, dropped: () => dropped };
|
||||
}
|
||||
|
||||
test("Opus uplink accumulates 960 samples, emits tagged frames and resets on VOX close", async () => {
|
||||
const f = fakeUplink();
|
||||
assert.equal(await f.uplink.init(), true);
|
||||
assert.equal(f.configured(), true);
|
||||
f.uplink.push(new Float32Array(960));
|
||||
assert.equal(f.encoded.length, 1);
|
||||
assert.deepEqual([...f.sent[0]!], [2, 1, 2, 3]);
|
||||
f.uplink.push(new Float32Array(480));
|
||||
assert.equal(f.encoded.length, 1);
|
||||
f.uplink.push(new Float32Array(480));
|
||||
assert.equal(f.encoded.length, 2);
|
||||
f.uplink.resetStream();
|
||||
f.uplink.push(new Float32Array(960));
|
||||
assert.equal(f.encoded.length, 3);
|
||||
f.uplink.disable();
|
||||
assert.equal(f.uplink.active, false);
|
||||
});
|
||||
|
||||
test("Opus uplink cancels initialization when disabled during capability detection", async t => {
|
||||
const previousEncoder = globalThis.AudioEncoder;
|
||||
let resolveSupport!: (value: { supported: boolean }) => void;
|
||||
let constructed = 0;
|
||||
(globalThis as unknown as { AudioEncoder: unknown }).AudioEncoder = class {
|
||||
static isConfigSupported() {
|
||||
return new Promise<{ supported: boolean }>(resolve => { resolveSupport = resolve; });
|
||||
}
|
||||
constructor() { constructed++; }
|
||||
};
|
||||
t.after(() => { (globalThis as unknown as { AudioEncoder: unknown }).AudioEncoder = previousEncoder; });
|
||||
|
||||
const uplink = createOpusUplink({ send() { return true; }, onDrop() {}, onFallback() {} });
|
||||
const initializing = uplink.init();
|
||||
uplink.disable();
|
||||
resolveSupport({ supported: true });
|
||||
assert.equal(await initializing, false);
|
||||
assert.equal(uplink.active, false);
|
||||
assert.equal(constructed, 0);
|
||||
});
|
||||
|
||||
test("Opus uplink drops a frame when the encoder queue is full", async () => {
|
||||
const f = fakeUplink();
|
||||
assert.equal(await f.uplink.init(), true);
|
||||
f.encoder.encodeQueueSize = 4;
|
||||
f.uplink.push(new Float32Array(960));
|
||||
assert.equal(f.encoded.length, 0);
|
||||
assert.equal(f.dropped(), 1);
|
||||
f.encoder.encodeQueueSize = 0;
|
||||
f.uplink.push(new Float32Array(960));
|
||||
assert.equal(f.encoded.length, 1);
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createRemotePlayback } from "../src/voice/remote-playback.js";
|
||||
|
||||
class FakeChunk {
|
||||
closed = 0;
|
||||
constructor(public readonly init: { timestamp: number; duration: number; data: Uint8Array }) {}
|
||||
close() { this.closed++; }
|
||||
}
|
||||
|
||||
class FakeDecoder {
|
||||
static instances: FakeDecoder[] = [];
|
||||
static failConfigure = false;
|
||||
decodeQueueSize = 0;
|
||||
closed = 0;
|
||||
configured: unknown;
|
||||
chunks: FakeChunk[] = [];
|
||||
constructor(public readonly callbacks: { output: (chunk: unknown) => void; error: (error: unknown) => void }) {
|
||||
FakeDecoder.instances.push(this);
|
||||
}
|
||||
configure(config: unknown) {
|
||||
if (FakeDecoder.failConfigure) throw new Error("codec unavailable");
|
||||
this.configured = config;
|
||||
}
|
||||
decode(chunk: FakeChunk) { this.chunks.push(chunk); }
|
||||
close() { this.closed++; }
|
||||
}
|
||||
|
||||
class FakeSource {
|
||||
static instances: FakeSource[] = [];
|
||||
stopped = 0;
|
||||
startedAt = 0;
|
||||
buffer: unknown;
|
||||
constructor() { FakeSource.instances.push(this); }
|
||||
connect() {}
|
||||
disconnect() {}
|
||||
start(time: number) { this.startedAt = time; }
|
||||
stop() { this.stopped++; }
|
||||
addEventListener() {}
|
||||
}
|
||||
|
||||
class FakeContext {
|
||||
currentTime = 0;
|
||||
destination = {};
|
||||
createGain() { return { gain: { value: 0 }, connect() {}, disconnect() {} }; }
|
||||
createBuffer(_channels: number, frames: number, sampleRate: number) { return { duration: frames / sampleRate, copyToChannel() {} }; }
|
||||
createBufferSource() { return new FakeSource(); }
|
||||
}
|
||||
|
||||
function decodedChunk(closed = 0) {
|
||||
return { sampleRate: 48_000, numberOfChannels: 1, numberOfFrames: 960, closed, copyTo() {}, close() { this.closed++; } };
|
||||
}
|
||||
|
||||
function installFakes(t: { after: (callback: () => void) => void }): void {
|
||||
const previousDecoder = globalThis.AudioDecoder;
|
||||
const previousChunk = globalThis.EncodedAudioChunk;
|
||||
FakeDecoder.instances.length = 0;
|
||||
FakeSource.instances.length = 0;
|
||||
(globalThis as unknown as { AudioDecoder: unknown }).AudioDecoder = FakeDecoder;
|
||||
(globalThis as unknown as { EncodedAudioChunk: unknown }).EncodedAudioChunk = FakeChunk;
|
||||
t.after(() => {
|
||||
(globalThis as unknown as { AudioDecoder: unknown }).AudioDecoder = previousDecoder;
|
||||
(globalThis as unknown as { EncodedAudioChunk: unknown }).EncodedAudioChunk = previousChunk;
|
||||
});
|
||||
}
|
||||
|
||||
const opusFrame = new Uint8Array([0x78, 1, 2, 3]);
|
||||
|
||||
test("legacy playback keeps the original 80 ms window and tears down on overflow", async t => {
|
||||
installFakes(t);
|
||||
const context = new FakeContext();
|
||||
const playback = createRemotePlayback({
|
||||
getContext: () => context as unknown as AudioContext,
|
||||
getVolume: () => 1,
|
||||
onDecodeError() {},
|
||||
onDrop() {},
|
||||
});
|
||||
playback.play(7, 4, opusFrame);
|
||||
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 });
|
||||
const chunk = decodedChunk();
|
||||
decoder.callbacks.output(chunk);
|
||||
assert.equal(chunk.closed, 1);
|
||||
assert.equal(decoder.closed, 1);
|
||||
assert.equal(FakeSource.instances.length, 4);
|
||||
});
|
||||
|
||||
test("adaptive playback resets its schedule without destroying the decoder", 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);
|
||||
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.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 });
|
||||
});
|
||||
+313
-50
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
|
||||
import { before, after, beforeEach, afterEach, test } from "node:test";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { createServer } from "vite";
|
||||
import { computed, effectScope, nextTick, ref } from "vue";
|
||||
|
||||
@@ -70,9 +71,30 @@ class RecorderStub {
|
||||
function decodedChunk() {
|
||||
return { sampleRate: 48000, numberOfChannels: 1, numberOfFrames: 960, closed: 0, copyTo() {}, close() { this.closed++; } };
|
||||
}
|
||||
let compatibilityAudioClientId = 7;
|
||||
function receiveAudio(socket, clientId = 7) {
|
||||
socket.onmessage({ data: new Uint8Array([4, clientId >> 8, clientId & 255, 1, 2, 3]).buffer });
|
||||
}
|
||||
function assertCompatibilityAudio(socket) {
|
||||
const sentBefore = socket.messages.length;
|
||||
for (const processor of AudioContextStub.processors) {
|
||||
processor.onaudioprocess?.({ inputBuffer: { getChannelData: () => new Float32Array(960).fill(0.2) } });
|
||||
}
|
||||
assert.ok(socket.messages.slice(sentBefore).some(message => message instanceof ArrayBuffer && message.byteLength === 1920));
|
||||
const decodersBefore = AudioDecoderStub.instances.length;
|
||||
receiveAudio(socket, compatibilityAudioClientId++);
|
||||
assert.equal(AudioDecoderStub.instances.length, decodersBefore + 1);
|
||||
}
|
||||
function assertNoCompatibilityAudio(socket) {
|
||||
const sentBefore = socket.messages.length;
|
||||
const decodersBefore = AudioDecoderStub.instances.length;
|
||||
for (const processor of AudioContextStub.processors) {
|
||||
processor.onaudioprocess?.({ inputBuffer: { getChannelData: () => new Float32Array(960).fill(0.2) } });
|
||||
}
|
||||
assert.equal(socket.messages.slice(sentBefore).some(message => message instanceof ArrayBuffer), false);
|
||||
receiveAudio(socket);
|
||||
assert.equal(AudioDecoderStub.instances.length, decodersBefore);
|
||||
}
|
||||
class AudioContextStub extends EventTarget {
|
||||
static instances = [];
|
||||
static processors = [];
|
||||
@@ -181,6 +203,7 @@ before(async () => {
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
compatibilityAudioClientId = 7;
|
||||
TestSocket.instances.length = 0;
|
||||
TestPeer.instances.length = 0;
|
||||
AudioContextStub.processors.length = 0;
|
||||
@@ -733,6 +756,39 @@ async function connectWebRtc() {
|
||||
return { socket, peer: TestPeer.instances.at(-1) };
|
||||
}
|
||||
|
||||
test("an unadvertised WebRTC session stays on compatibility audio without a failure banner", async () => {
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: false, webrtcUnavailableReason: "NO_MEDIA_PATH" });
|
||||
await nextTurn();
|
||||
assert.equal(TestPeer.instances.length, 0);
|
||||
assert.equal(voice.state.audioNoticeCode, "");
|
||||
assert.equal(voice.state.webrtcReconnecting, false);
|
||||
assertCompatibilityAudio(socket);
|
||||
assert.equal((await audioSample(socket)).transport, "websocket");
|
||||
});
|
||||
|
||||
test("the WebRTC failure banner compiles with a localized in-session reconnect action", async () => {
|
||||
const source = await readFile(new URL("../src/views/WebClient.vue", import.meta.url), "utf8");
|
||||
const { parse, compileTemplate } = await import("@vue/compiler-sfc");
|
||||
const { descriptor, errors } = parse(source);
|
||||
assert.deepEqual(errors, []);
|
||||
const template = compileTemplate({ source: descriptor.template.content, filename: "WebClient.vue", id: "webrtc-reconnect-test" });
|
||||
assert.deepEqual(template.errors, []);
|
||||
assert.match(source, /data-action="reconnect-webrtc"/);
|
||||
assert.match(source, /@click="reconnectWebRtc"/);
|
||||
assert.match(source, /:disabled="voiceState\.webrtcReconnecting"/);
|
||||
const notice = "实时语音(WebRTC)不可用(错误代码:WEBRTC_NO_RELAY)。已自动切换到兼容传输(PCM/Opus over WebSocket)保通话;你仍在当前语音会话中,可点击“重新连接 WebRTC”重试";
|
||||
for (const language of ["zh", "en", "de", "ru", "ja"]) {
|
||||
const translations = webClientTranslations[language];
|
||||
assert.ok(translations.reconnectWebRtc);
|
||||
assert.ok(translations.reconnectingWebRtc);
|
||||
const localized = useWebClientI18n(ref(language)).localizedAudioNotice("WEBRTC_FAILED", notice);
|
||||
assert.match(localized, /WEBRTC_NO_RELAY/);
|
||||
assert.match(localized, language === "zh" ? /已自动切换到兼容传输/ : /PCM\/Opus/);
|
||||
}
|
||||
assert.equal(new Set(["zh", "en", "de", "ru", "ja"].map(language => webClientTranslations[language].reconnectWebRtc)).size, 5);
|
||||
});
|
||||
|
||||
function enableMicrophoneMeter(t) {
|
||||
const analysers = [];
|
||||
const intervals = [];
|
||||
@@ -1247,13 +1303,16 @@ test("an optional content hint failure does not abandon or fail accompaniment ca
|
||||
assert.equal(stream.track.readyState, "ended");
|
||||
});
|
||||
|
||||
test("failed initial WebRTC input allocation releases partial nodes before PCM fallback", async t => {
|
||||
test("failed initial WebRTC input allocation releases partial nodes and restores PCM fallback", async t => {
|
||||
const createGain = AudioContextStub.prototype.createGain;
|
||||
let gainCalls = 0;
|
||||
t.mock.method(AudioContextStub.prototype, "createGain", function () {
|
||||
if (++gainCalls === 3) throw new Error("Mixed input gain unavailable");
|
||||
return createGain.call(this);
|
||||
});
|
||||
const getUserMedia = navigator.mediaDevices.getUserMedia;
|
||||
let microphoneRequests = 0;
|
||||
navigator.mediaDevices.getUserMedia = async (...args) => { microphoneRequests++; return getUserMedia(...args); };
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: true });
|
||||
await nextTurn();
|
||||
@@ -1261,7 +1320,15 @@ test("failed initial WebRTC input allocation releases partial nodes before PCM f
|
||||
assert.equal(AudioContextStub.destinations[1].stream.track.readyState, "ended");
|
||||
assert.ok(AudioContextStub.mediaSources[1].disconnects > 0);
|
||||
assert.equal(voice.state.microphoneErrorCode, "");
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FALLBACK");
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
|
||||
assert.match(voice.state.audioNotice, /WEBRTC_NEGOTIATION_FAILED/);
|
||||
assert.match(voice.state.audioNotice, /已自动切换到兼容传输/);
|
||||
assert.equal(microphoneRequests, 1);
|
||||
assert.equal(AudioContextStub.processors.length, 1);
|
||||
assertCompatibilityAudio(socket);
|
||||
assert.equal(voice.state.connected, true);
|
||||
assert.equal(voice.state.tsClientId, 1);
|
||||
assert.equal(TestSocket.instances.length, 1);
|
||||
});
|
||||
|
||||
test("a failing mix-node disconnect cannot prevent peer and microphone cleanup", async t => {
|
||||
@@ -1442,7 +1509,7 @@ test("microphone metering preserves its cadence and bounded level and stops on d
|
||||
assert.equal(meter.analysers[0].reads, reads);
|
||||
});
|
||||
|
||||
test("a rejected old WebRTC answer cannot force the new peer into fallback", async () => {
|
||||
test("a rejected old WebRTC answer cannot force the new peer into failure", async () => {
|
||||
const first = await connectWebRtc();
|
||||
const answer = deferred();
|
||||
first.peer.setRemoteDescription = () => answer.promise;
|
||||
@@ -1455,7 +1522,7 @@ test("a rejected old WebRTC answer cannot force the new peer into fallback", asy
|
||||
assert.equal(voice.state.audioNoticeCode, "");
|
||||
});
|
||||
|
||||
test("a successful old WebRTC answer cannot activate WebRTC for a compatibility connection", async () => {
|
||||
test("a successful old WebRTC answer cannot activate WebRTC for a replacement compatibility session", async () => {
|
||||
const first = await connectWebRtc();
|
||||
const answer = deferred();
|
||||
first.peer.setRemoteDescription = () => answer.promise;
|
||||
@@ -1467,6 +1534,140 @@ test("a successful old WebRTC answer cannot activate WebRTC for a compatibility
|
||||
await nextTurn();
|
||||
voice.setVolume(9, 0.4);
|
||||
assert.equal(current.messages.some(message => message.type === "setMemberVolume"), false);
|
||||
assert.equal(voice.state.audioNoticeCode, "");
|
||||
AudioContextStub.processors.at(-1).onaudioprocess({ inputBuffer: { getChannelData: () => new Float32Array(960).fill(0.2) } });
|
||||
assert.ok(current.messages.some(message => message instanceof ArrayBuffer && message.byteLength === 1920));
|
||||
});
|
||||
|
||||
test("reconnect WebRTC keeps compatibility audio until ready without reconnecting TeamSpeak", async () => {
|
||||
const getUserMedia = navigator.mediaDevices.getUserMedia;
|
||||
let microphoneRequests = 0;
|
||||
navigator.mediaDevices.getUserMedia = async (...args) => { microphoneRequests++; return getUserMedia(...args); };
|
||||
const { socket, peer } = await connectWebRtc();
|
||||
socket.receive({ type: "webrtcAnswer", payload: { sdp: { type: "answer", sdp: "initial-answer" } } });
|
||||
await nextTurn();
|
||||
assertNoCompatibilityAudio(socket);
|
||||
peer.connectionState = "failed";
|
||||
peer.onconnectionstatechange();
|
||||
await nextTurn();
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
|
||||
assertCompatibilityAudio(socket);
|
||||
const pending = voice.reconnectWebRtc();
|
||||
assert.equal(voice.state.webrtcReconnecting, true);
|
||||
assert.equal(TestSocket.instances.length, 1);
|
||||
assert.equal(voice.state.connected, true);
|
||||
assert.equal(voice.state.tsClientId, 1);
|
||||
await pending;
|
||||
const current = TestPeer.instances.at(-1);
|
||||
assert.notEqual(current, peer);
|
||||
assert.notEqual(current.connectionState, "closed");
|
||||
assert.equal(socket.messages.filter(message => message.type === "webrtcOffer").length, 2);
|
||||
assert.equal(socket.messages.filter(message => message.type === "webrtcStop").length, 1);
|
||||
assert.equal(microphoneRequests, 1);
|
||||
assert.equal(voice.state.webrtcReconnecting, true);
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
|
||||
assertCompatibilityAudio(socket);
|
||||
socket.receive({ type: "webrtcAnswer", payload: { sdp: { type: "answer", sdp: "reconnected-answer" } } });
|
||||
await nextTurn();
|
||||
assert.equal(current.remoteDescription.sdp, "reconnected-answer");
|
||||
assert.equal(voice.state.webrtcReconnecting, false);
|
||||
assert.equal(voice.state.audioNoticeCode, "");
|
||||
assert.equal(voice.state.connected, true);
|
||||
assert.equal(voice.state.tsClientId, 1);
|
||||
assert.equal(TestSocket.instances.length, 1);
|
||||
assertNoCompatibilityAudio(socket);
|
||||
assert.equal((await audioSample(socket)).transport, "webrtc");
|
||||
});
|
||||
|
||||
test("a failed WebRTC reconnect keeps compatibility audio and the retry banner", async () => {
|
||||
const { socket, peer } = await connectWebRtc();
|
||||
peer.connectionState = "failed";
|
||||
peer.onconnectionstatechange();
|
||||
await nextTurn();
|
||||
assertCompatibilityAudio(socket);
|
||||
await voice.reconnectWebRtc();
|
||||
const retry = TestPeer.instances.at(-1);
|
||||
assert.equal(socket.messages.filter(message => message.type === "webrtcOffer").length, 2);
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
|
||||
assertCompatibilityAudio(socket);
|
||||
retry.connectionState = "failed";
|
||||
retry.onconnectionstatechange();
|
||||
await nextTurn();
|
||||
assert.equal(retry.connectionState, "closed");
|
||||
assert.equal(voice.state.webrtcReconnecting, false);
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
|
||||
assert.equal(voice.state.connected, true);
|
||||
assert.equal(TestSocket.instances.length, 1);
|
||||
assert.equal(socket.messages.filter(message => message.type === "webrtcStop").length, 2);
|
||||
assertCompatibilityAudio(socket);
|
||||
await voice.reconnectWebRtc();
|
||||
assert.equal(socket.messages.filter(message => message.type === "webrtcOffer").length, 3);
|
||||
assert.equal(TestSocket.instances.length, 1);
|
||||
assert.equal(voice.state.webrtcReconnecting, true);
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
|
||||
assertCompatibilityAudio(socket);
|
||||
});
|
||||
|
||||
test("a stale answer from a failed attempt cannot complete a WebRTC reconnect", async () => {
|
||||
const first = await connectWebRtc();
|
||||
const answer = deferred();
|
||||
first.peer.setRemoteDescription = () => answer.promise;
|
||||
first.socket.receive({ type: "webrtcAnswer", payload: { sdp: { type: "answer", sdp: "old-answer" } } });
|
||||
first.peer.connectionState = "failed";
|
||||
first.peer.onconnectionstatechange();
|
||||
await nextTurn();
|
||||
await voice.reconnectWebRtc();
|
||||
const current = TestPeer.instances.at(-1);
|
||||
answer.resolve();
|
||||
await nextTurn();
|
||||
assert.equal(current.remoteDescription, null);
|
||||
assert.notEqual(current.connectionState, "closed");
|
||||
assert.equal(voice.state.webrtcReconnecting, true);
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
|
||||
assert.equal(first.socket.messages.filter(message => message.type === "webrtcStop").length, 1);
|
||||
assert.equal(first.socket.messages.filter(message => message.type === "webrtcOffer").length, 2);
|
||||
assertCompatibilityAudio(first.socket);
|
||||
first.socket.receive({ type: "webrtcAnswer", payload: { sdp: { type: "answer", sdp: "current-answer" } } });
|
||||
await nextTurn();
|
||||
assert.equal(current.remoteDescription.sdp, "current-answer");
|
||||
assert.equal(voice.state.webrtcReconnecting, false);
|
||||
assert.equal(voice.state.audioNoticeCode, "");
|
||||
assertNoCompatibilityAudio(first.socket);
|
||||
});
|
||||
|
||||
test("a stale peer state event cannot fail a successful WebRTC reconnect", async () => {
|
||||
const first = await connectWebRtc();
|
||||
const staleStateChange = first.peer.onconnectionstatechange;
|
||||
first.peer.connectionState = "failed";
|
||||
first.peer.onconnectionstatechange();
|
||||
await nextTurn();
|
||||
await voice.reconnectWebRtc();
|
||||
const current = TestPeer.instances.at(-1);
|
||||
first.socket.receive({ type: "webrtcAnswer", payload: { sdp: { type: "answer", sdp: "current-answer" } } });
|
||||
await nextTurn();
|
||||
staleStateChange();
|
||||
await nextTurn();
|
||||
assert.notEqual(current.connectionState, "closed");
|
||||
assert.equal(voice.state.audioNoticeCode, "");
|
||||
assert.equal(first.socket.messages.filter(message => message.type === "webrtcStop").length, 1);
|
||||
assertNoCompatibilityAudio(first.socket);
|
||||
});
|
||||
|
||||
test("a stale peer failure cannot disable a replacement compatibility session", async () => {
|
||||
const first = await connectWebRtc();
|
||||
const staleStateChange = first.peer.onconnectionstatechange;
|
||||
const current = await connect();
|
||||
current.receive({ type: "connected", tsClientId: 2 });
|
||||
await nextTurn();
|
||||
first.peer.connectionState = "failed";
|
||||
staleStateChange();
|
||||
await nextTurn();
|
||||
assert.equal(voice.state.audioNoticeCode, "");
|
||||
assert.equal(current.messages.some(message => message.type === "webrtcStop"), false);
|
||||
AudioContextStub.processors.at(-1).onaudioprocess({ inputBuffer: { getChannelData: () => new Float32Array(960).fill(0.2) } });
|
||||
assert.ok(current.messages.some(message => message instanceof ArrayBuffer && message.byteLength === 1920));
|
||||
receiveAudio(current);
|
||||
assert.equal(AudioDecoderStub.instances.length, 1);
|
||||
});
|
||||
|
||||
test("a queued track event from a closed peer cannot replace current playback", async () => {
|
||||
@@ -1531,9 +1732,11 @@ test("a playback setup failure releases its element and restores compatibility a
|
||||
await nextTurn();
|
||||
assert.equal(removed, true);
|
||||
assert.equal(peer.connectionState, "closed");
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FALLBACK");
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
|
||||
assert.match(voice.state.audioNotice, /WEBRTC_PLAYBACK_FAILED/);
|
||||
assert.equal(voice.state.microphoneErrorCode, "");
|
||||
assert.equal(socket.messages.filter(message => message.type === "webrtcStop").length, 1);
|
||||
assertCompatibilityAudio(socket);
|
||||
});
|
||||
|
||||
test("a queued old playback retry cannot play a replacement session", async t => {
|
||||
@@ -1583,7 +1786,7 @@ test("overlapping playback retry gestures share one in-flight play attempt", asy
|
||||
assert.equal(voice.state.audioNoticeCode, "");
|
||||
});
|
||||
|
||||
test("failed fallback signaling still releases WebRTC and resumes compatibility capture", async t => {
|
||||
test("failed WebRTC signaling still releases resources and restores compatibility capture", async t => {
|
||||
t.mock.method(TestPeer.prototype, "createOffer", async () => { throw new Error("Negotiation unavailable"); });
|
||||
const send = TestSocket.prototype.send;
|
||||
t.mock.method(TestSocket.prototype, "send", function (raw) {
|
||||
@@ -1595,24 +1798,22 @@ test("failed fallback signaling still releases WebRTC and resumes compatibility
|
||||
await nextTurn();
|
||||
assert.equal(TestPeer.instances[0].connectionState, "closed");
|
||||
assert.equal(voice.state.microphoneErrorCode, "");
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FALLBACK");
|
||||
AudioContextStub.processors.at(-1).onaudioprocess({ inputBuffer: { getChannelData: () => new Float32Array(960).fill(0.2) } });
|
||||
assert.ok(socket.messages.some(message => message instanceof ArrayBuffer && message.byteLength === 1920));
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
|
||||
assert.equal(AudioContextStub.processors.length, 1);
|
||||
assertCompatibilityAudio(socket);
|
||||
});
|
||||
|
||||
test("an old fallback microphone failure cannot report into a replacement connection", async () => {
|
||||
const { peer } = await connectWebRtc();
|
||||
const permission = deferred();
|
||||
navigator.mediaDevices.getUserMedia = () => permission.promise;
|
||||
test("a WebRTC failure does not request fallback microphone permission", async () => {
|
||||
const { peer, socket } = await connectWebRtc();
|
||||
const getUserMedia = navigator.mediaDevices.getUserMedia;
|
||||
let microphoneRequests = 0;
|
||||
navigator.mediaDevices.getUserMedia = async (...args) => { microphoneRequests++; return getUserMedia(...args); };
|
||||
peer.connectionState = "failed";
|
||||
peer.onconnectionstatechange();
|
||||
await nextTurn();
|
||||
navigator.mediaDevices.getUserMedia = async () => microphoneStream();
|
||||
await connectWebRtc();
|
||||
permission.reject(new DOMException("Old permission rejected", "NotAllowedError"));
|
||||
await nextTurn();
|
||||
assert.equal(voice.state.microphoneErrorCode, "");
|
||||
assert.equal(voice.state.audioNoticeCode, "");
|
||||
assert.equal(microphoneRequests, 0);
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
|
||||
assertCompatibilityAudio(socket);
|
||||
});
|
||||
|
||||
test("an old answer timeout cannot hide the replacement deadline from cleanup", async t => {
|
||||
@@ -1715,7 +1916,7 @@ async function audioSample(socket, bridge = {}) {
|
||||
return pending;
|
||||
}
|
||||
|
||||
test("diagnostic sample scopes follow peer replacement and fallback on one socket", async () => {
|
||||
test("diagnostic sample scopes follow peer replacement and WebRTC failure on one socket", async () => {
|
||||
const { socket } = await connectWebRtc();
|
||||
const first = await audioSample(socket);
|
||||
const next = await audioSample(socket);
|
||||
@@ -1726,9 +1927,11 @@ test("diagnostic sample scopes follow peer replacement and fallback on one socke
|
||||
assert.notEqual(replaced.scopeId, first.scopeId);
|
||||
socket.receive({ type: "webrtcError", code: "WEBRTC_UNAVAILABLE" });
|
||||
await nextTurn();
|
||||
const fallback = await audioSample(socket);
|
||||
assert.notEqual(fallback.scopeId, replaced.scopeId);
|
||||
assert.equal(fallback.transport, "websocket");
|
||||
const failed = await audioSample(socket);
|
||||
assert.notEqual(failed.scopeId, replaced.scopeId);
|
||||
assert.equal(failed.transport, "websocket");
|
||||
assert.match(voice.state.audioNotice, /WEBRTC_UNAVAILABLE/);
|
||||
assertCompatibilityAudio(socket);
|
||||
});
|
||||
|
||||
test("session recovery resets compatibility diagnostics without mutating old snapshots", async () => {
|
||||
@@ -1746,7 +1949,10 @@ test("session recovery resets compatibility diagnostics without mutating old sna
|
||||
await nextTurn();
|
||||
const current = await audioSample(socket);
|
||||
assert.notEqual(current.scopeId, previous.scopeId);
|
||||
assert.deepEqual(current.fallbackPlayback, { framesReceived: 0, framesDropped: 0, decodeErrors: 0 });
|
||||
assert.deepEqual(current.fallbackPlayback, {
|
||||
framesReceived: 0, framesDropped: 0, decodeErrors: 0,
|
||||
bufferTargetMs: 0, bufferResets: 0, maxBufferAheadMs: 0,
|
||||
});
|
||||
assert.equal(previous.fallbackPlayback.framesReceived, 2);
|
||||
});
|
||||
|
||||
@@ -1769,30 +1975,76 @@ test("disconnect clears the WebRTC answer deadline immediately", async () => {
|
||||
assert.equal(browserTimers.size, 0);
|
||||
});
|
||||
|
||||
test("negotiation failure resumes bounded PCM capture without a false microphone error", async t => {
|
||||
test("negotiation failure keeps the session and starts PCM compatibility capture", async t => {
|
||||
t.mock.method(TestPeer.prototype, "createOffer", async () => { throw new Error("negotiation failed"); });
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: true });
|
||||
await nextTurn();
|
||||
assert.equal(TestPeer.instances[0].connectionState, "closed");
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FALLBACK");
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
|
||||
assert.match(voice.state.audioNotice, /WEBRTC_NEGOTIATION_FAILED/);
|
||||
assert.equal(voice.state.microphoneErrorCode, "");
|
||||
const capture = AudioContextStub.processors.at(-1);
|
||||
capture.onaudioprocess({ inputBuffer: { getChannelData: () => new Float32Array(960).fill(0.2) } });
|
||||
assert.ok(socket.messages.some(message => message instanceof ArrayBuffer && message.byteLength === 1920));
|
||||
assert.equal(AudioContextStub.processors.length, 1);
|
||||
assertCompatibilityAudio(socket);
|
||||
assert.equal(socket.messages.filter(message => message.type === "webrtcStop").length, 1);
|
||||
});
|
||||
|
||||
test("track setup failure also releases the peer and restores compatibility capture", async t => {
|
||||
test("track setup failure releases the peer and starts compatibility capture", async t => {
|
||||
t.mock.method(TestPeer.prototype, "addTrack", () => { throw new Error("track rejected"); });
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: true });
|
||||
await nextTurn();
|
||||
assert.equal(TestPeer.instances[0].connectionState, "closed");
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FALLBACK");
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
|
||||
assert.equal(voice.state.microphoneErrorCode, "");
|
||||
AudioContextStub.processors.at(-1).onaudioprocess({ inputBuffer: { getChannelData: () => new Float32Array(960).fill(0.2) } });
|
||||
assert.ok(socket.messages.some(message => message instanceof ArrayBuffer && message.byteLength === 1920));
|
||||
assert.equal(AudioContextStub.processors.length, 1);
|
||||
assertCompatibilityAudio(socket);
|
||||
});
|
||||
|
||||
test("a relay-only WebRTC policy without TURN fails into compatibility capture", async () => {
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: true, voiceIceTransportPolicy: "relay", voiceIceServers: [] });
|
||||
await nextTurn();
|
||||
assert.equal(TestPeer.instances.length, 0);
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
|
||||
assert.match(voice.state.audioNotice, /WEBRTC_NO_RELAY/);
|
||||
assert.equal(AudioContextStub.processors.length, 1);
|
||||
assertCompatibilityAudio(socket);
|
||||
});
|
||||
|
||||
test("an answer timeout keeps the session and offers a WebRTC retry", async t => {
|
||||
const deadlines = [];
|
||||
const setTimer = window.setTimeout.bind(window);
|
||||
t.mock.method(window, "setTimeout", (callback, ms) => {
|
||||
if (ms === 8_000) deadlines.push(callback);
|
||||
return setTimer(callback, ms);
|
||||
});
|
||||
const { socket, peer } = await connectWebRtc();
|
||||
assert.equal(deadlines.length, 1);
|
||||
deadlines[0]();
|
||||
await nextTurn();
|
||||
assert.equal(peer.connectionState, "closed");
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
|
||||
assert.match(voice.state.audioNotice, /WEBRTC_ANSWER_TIMEOUT/);
|
||||
assert.equal(voice.state.connected, true);
|
||||
assertCompatibilityAudio(socket);
|
||||
await voice.reconnectWebRtc();
|
||||
assert.equal(socket.messages.filter(message => message.type === "webrtcOffer").length, 2);
|
||||
assert.equal(TestSocket.instances.length, 1);
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
|
||||
assertCompatibilityAudio(socket);
|
||||
});
|
||||
|
||||
test("a rejected current answer releases WebRTC and restores compatibility capture", async () => {
|
||||
const { socket, peer } = await connectWebRtc();
|
||||
peer.setRemoteDescription = async () => { throw new Error("Answer rejected"); };
|
||||
socket.receive({ type: "webrtcAnswer", payload: { sdp: { type: "answer", sdp: "rejected-answer" } } });
|
||||
await nextTurn();
|
||||
assert.equal(peer.connectionState, "closed");
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
|
||||
assert.match(voice.state.audioNotice, /WEBRTC_ANSWER_REJECTED/);
|
||||
assert.equal(socket.messages.filter(message => message.type === "webrtcStop").length, 1);
|
||||
assertCompatibilityAudio(socket);
|
||||
});
|
||||
|
||||
test("a current answer completes negotiation and removes its timeout", async () => {
|
||||
@@ -1836,14 +2088,16 @@ test("an offer rejected after a new connection opens cannot report a microphone
|
||||
});
|
||||
|
||||
|
||||
test("resetting an overloaded remote decoder disconnects its old gain", async () => {
|
||||
test("legacy playback overflow rebuilds the decoder instead of retaining an unbounded queue", async () => {
|
||||
const socket = await connect();
|
||||
receiveAudio(socket);
|
||||
const gain = AudioContextStub.gains.at(-1);
|
||||
AudioDecoderStub.instances.at(-1).decodeQueueSize = 3;
|
||||
const decoder = AudioDecoderStub.instances.at(-1);
|
||||
decoder.decodeQueueSize = 3;
|
||||
receiveAudio(socket);
|
||||
assert.equal(gain.disconnects, 1);
|
||||
assert.equal(AudioDecoderStub.instances.length, 2);
|
||||
assert.equal(decoder.closed, 1);
|
||||
});
|
||||
|
||||
test("an old source ending cannot hide replacement playback from session cleanup", async () => {
|
||||
@@ -1923,7 +2177,7 @@ test("a departing speaker releases only its own playback", async () => {
|
||||
assert.equal(currentSource.stopped, 0);
|
||||
});
|
||||
|
||||
test("remote playback preserves member volume through output mute and decoder reset", async () => {
|
||||
test("remote playback preserves member volume through output mute and decoder overload", async () => {
|
||||
const socket = await connect();
|
||||
voice.setVolume(7, 0.4);
|
||||
voice.setOutputVolume(0.5);
|
||||
@@ -1932,33 +2186,42 @@ test("remote playback preserves member volume through output mute and decoder re
|
||||
assert.deepEqual(AudioContextStub.gains.map(node => node.gain.value), [0.2, 0.5]);
|
||||
voice.toggleOutputMute();
|
||||
assert.deepEqual(AudioContextStub.gains.map(node => node.gain.value), [0, 0]);
|
||||
const old = AudioDecoderStub.instances[0];
|
||||
old.decodeQueueSize = 3;
|
||||
const decoder = AudioDecoderStub.instances[0];
|
||||
decoder.decodeQueueSize = 12;
|
||||
receiveAudio(socket, 7);
|
||||
const replacement = AudioDecoderStub.instances.at(-1);
|
||||
old.callbacks.error(new Error("stale decoder error"));
|
||||
assert.equal(replacement.closed, 0);
|
||||
assert.equal(AudioContextStub.gains.at(-1).gain.value, 0);
|
||||
assert.equal(decoder.closed, 1);
|
||||
assert.equal(AudioContextStub.gains[0].gain.value, 0);
|
||||
voice.toggleOutputMute();
|
||||
assert.equal(AudioContextStub.gains.at(-1).gain.value, 0.2);
|
||||
assert.equal(AudioContextStub.gains[1].gain.value, 0.5);
|
||||
});
|
||||
|
||||
test("decoded audio stays within the 80 ms playback window and recovers after overflow", async () => {
|
||||
test("adaptive profile from connected switches playback without requiring CFT transport", async () => {
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1, voiceProfile: "adaptive", audioJitterMaxMs: 300, audioUplinkCodecs: ["pcm"] });
|
||||
await nextTurn();
|
||||
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.equal(decoder.closed, 0);
|
||||
assert.equal(initialGain.disconnects, 0);
|
||||
assert.ok(chunks.every(chunk => chunk.closed === 1));
|
||||
});
|
||||
|
||||
test("legacy playback stays within its 80 ms window and tears down the decoder on overflow", async () => {
|
||||
const socket = await connect();
|
||||
receiveAudio(socket);
|
||||
const decoder = AudioDecoderStub.instances[0];
|
||||
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 => source.startedAt), [0, 0.02, 0.04, 0.06]);
|
||||
assert.deepEqual(AudioContextStub.sources.map(source => Math.round(source.startedAt * 1_000)), [0, 20, 40, 60]);
|
||||
assert.equal(decoder.closed, 1);
|
||||
assert.ok(AudioContextStub.sources.every(source => source.stopped === 1));
|
||||
assert.equal(initialGain.disconnects, 1);
|
||||
assert.ok(chunks.every(chunk => chunk.closed === 1));
|
||||
receiveAudio(socket);
|
||||
const replacement = AudioDecoderStub.instances.at(-1);
|
||||
replacement.callbacks.output(decodedChunk());
|
||||
assert.notEqual(replacement, decoder);
|
||||
assert.equal(AudioContextStub.sources.at(-1).startedAt, 0);
|
||||
});
|
||||
|
||||
test("old socket audio cannot create a decoder in a replacement session", async () => {
|
||||
|
||||
Reference in new issue
Block a user