mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-04 20:43:02 +08:00
Compare commits
18
Commits
9a12e2ee7b
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e563b04108 | ||
|
|
a2571442d4 | ||
|
|
f64e42429a | ||
|
|
25b0a01ae7 | ||
|
|
1fda6db59c | ||
|
|
5d3af8dfbb | ||
|
|
47abe356f5 | ||
|
|
de16417474 | ||
|
|
001457d004 | ||
|
|
02509ea551 | ||
|
|
b3104e1411 | ||
|
|
b6e7b1e4da | ||
|
|
4e8ea3081c | ||
|
|
df826f575e | ||
|
|
4131d9c319 | ||
|
|
e5c891fc94 | ||
|
|
cfbf488f75 | ||
|
|
881354e283 |
No files matched your search
@@ -51,4 +51,4 @@ Minimizing or switching to the library retains the same iframe and app session.
|
||||
|
||||
## Instance authorization
|
||||
|
||||
The public host asks once per browser origin for third-party skins and functional applications together. No decision or refusal allows only Day, Night and ILLUSIA; KAAK also requires consent. The last item in the skin menu reopens this setting. Revocation must close/revoke the active frontend application while preserving independently enabled backend services. Do not add per-app copies of the same host authorization prompt, bypass the host gate or confuse this user decision with administrator package trust or browser-native permission prompts.
|
||||
The public host asks once per browser origin for third-party skins and functional applications together. No decision or refusal allows only Day, Night and ILLUSIA; KAAK and Classic also require consent. The last item in the skin menu reopens this setting. Revocation must close/revoke the active frontend application while preserving independently enabled backend services. Do not add per-app copies of the same host authorization prompt, bypass the host gate or confuse this user decision with administrator package trust or browser-native permission prompts.
|
||||
@@ -25,6 +25,7 @@ When a WebSpeak checkout is unavailable, read the [published skin guide](https:/
|
||||
- Use component schema v3 and set `minAppVersion` to at least `0.3.2` when using `voice.plugin-launcher`. Place it once in the voice surface, inside a visible slot. Set `options.pluginPresentation` to `drawer-side` for a sidebar, `drawer-below` for a header button, or `dialog` for the default library. The built-in Day, Night and ILLUSIA skins use the header drawer. The KAAK and Discord examples use the sidebar drawer.
|
||||
- Style `voice.plugin-launcher`, `voice.plugin-drawer` and `voice.plugin-drawer.app` through the published parts. WebSpeak owns app availability, pinning, authorization and the app window. Layouts without a usable mount can fall back to the host library. In a connected, authorized voice session verify that the launcher mounts in the intended slot, that the drawer stays within desktop and narrow viewports, and that both pinned and unpinned apps open. For KAAK, verify the rail itself and check the package version served by the instance if the launcher still floats.
|
||||
- For a compact rail, `home.social-links` accepts `options.communityLinks: false` to keep the admin entry and hide community links. The admin console uses host styling. Use `chrome.json#visibleParts` only for documented host decorations. Confirm that the host-owned recovery action remains usable after applying the skin.
|
||||
- To fold recovery into a skin top bar, declare `chrome.json#slots` with `"mode": "toolbar"` (one grouped entry) or the independent `host.recovery.built-in` / `host.recovery.library` keys. Supply page-specific anchor candidates and `--skin-recovery-toolbar-*` / `--skin-host-toolbar-*` tokens; never target the host toolbar DOM. The host keeps the button labels, click handlers, minimum hit target and floating-capsule fallback, and hides the ordinary plugin launcher so the library has one entry. See [Host chrome toolbar example](../../../docs/examples/HOST-CHROME-TOOLBAR.md).
|
||||
- Test changes to the public home and voice surfaces with the same released archive. Check cold load for a theme flash, long translations for clipping, and live/shared media for artwork layering. Use a real voice session for interaction claims.
|
||||
|
||||
## Automatic distribution PR
|
||||
@@ -56,4 +57,4 @@ Return the actual PR URL and validation outcome, and attach the PR to the chat w
|
||||
|
||||
## Instance authorization
|
||||
|
||||
WebSpeak v0.3.0 replaces per-skin consent dialogs with one origin-scoped user decision covering third-party skins and functional apps. Without consent only the fixed official Day, Night and ILLUSIA skins are available; bundled KAAK also requires consent. The host skin switcher owns the final authorization item. Packages must not duplicate or bypass it. Revocation must cancel pending activation, remove third-party CSS/components and stop workers. Continue enforcing manifest permissions, credential redaction, trusted action validation and package digests internally; one-time consent does not extend the public API. See the current guide for release compatibility.
|
||||
WebSpeak v0.3.0 replaces per-skin consent dialogs with one origin-scoped user decision covering third-party skins and functional apps. Without consent only the fixed official Day, Night and ILLUSIA skins are available; bundled KAAK and Classic also require consent. The host skin switcher owns the final authorization item. Packages must not duplicate or bypass it. Revocation must cancel pending activation, remove third-party CSS/components and stop workers. Continue enforcing manifest permissions, credential redaction, trusted action validation and package digests internally; one-time consent does not extend the public API. See the current guide for release compatibility.
|
||||
@@ -25,7 +25,8 @@ WebSpeak connects browser users to TeamSpeak 3 and TeamSpeak 6 through a self-ho
|
||||
| `web/src/voice/screen-share.ts` | Per-session screen capture, peer negotiation, cleanup and diagnostics |
|
||||
| `web/src/voice/remote-playback.ts` | Per-speaker compatibility decoding, bounded scheduling, volume and resource cleanup |
|
||||
| `web/src/voice/microphone-test.ts` | Cancellable recording tests, recorder deadline and playback URL ownership |
|
||||
| `web/src/voice/microphone-capture.ts` | Prepared microphone processing graphs, per-context worklet loading, optional RNNoise and independent PCM activation/cleanup |
|
||||
| `web/src/voice/microphone-capture.ts` | Prepared microphone processing graphs, per-context worklet loading, GTCRN/RNNoise engines, 80 Hz high-pass, preload-before-constraints fallback and independent PCM activation/cleanup |
|
||||
| `web/src/voice/noise-suppression.ts` | Noise-suppression modes, capability/fallback resolution and stored-preference migration |
|
||||
| `web/src/voice/audio-sink.ts` | Serialized device routing per audio endpoint, with stale-operation guards |
|
||||
| `web/src/voice/accompaniment.ts` | Generation-bound display-audio capture, immediate pending-capture cancellation, ended listeners and committed activity |
|
||||
| `web/src/voice/webrtc-input.ts` | Stable WebRTC sender output, microphone gain and transactional accompaniment-source attachment |
|
||||
@@ -110,10 +111,12 @@ Preserve bounded audio buffering and stale-playback recovery. Audio counters sta
|
||||
|
||||
Remote playback owns each speaker's decoder, gain and source nodes as one resource set. Member departure, decoder failure and session teardown release that set; queued callbacks must not touch its replacement. Preserve the 80 ms playback window and three-frame decoder queue threshold unless audio validation justifies changing them.
|
||||
|
||||
Microphone recording tests own their recorder, timeout and object URL, while the capture layer owns the microphone stream. A normal stop may publish its final recording; replacement and session teardown discard late results and revoke the old URL. Stopping a test while connected must preserve room capture. Test cancellation and stale permission failures must not change a newer test's state.
|
||||
Microphone recording tests own both recorders (raw and denoised), their timeout and object URLs, while the capture layer owns the microphone stream. A normal stop may publish its final recordings; replacement and session teardown discard late results and revoke both old URLs. Stopping a test while connected must preserve room capture. Test cancellation and stale permission failures must not change a newer test's state.
|
||||
|
||||
Device and noise-suppression changes share one configuration operation. Persist only the last successful settings; stale failures cannot roll back a newer choice. Acquiring a replacement microphone must preserve the current WebRTC peer and compatibility PCM capture until the replacement is ready. Capture callbacks are invalidated when their graph stops, separately from permission-request generations. Closing settings also releases standalone device-preview capture when no recording was started.
|
||||
|
||||
Microphone denoising has four modes: off, browser, RNNoise and GTCRN. Model engines are exclusive with the browser noise suppressor; never request both. Preload the selected model before acquiring the microphone so a load failure can fall back to browser denoising without a second permission prompt, and report the active engine plus a visible fallback reason. Both neural engines require a 48 kHz context. An unrecognised stored mode migrates to GTCRN, and the legacy `noiseSuppressionLevel` mirror is written for older builds.
|
||||
|
||||
Prepare microphone nodes and streams before replacing the live graph. A failed allocation or delayed worklet load must leave the old capture usable. Aborting preparation releases its candidate resources immediately; only activation enables PCM callbacks. Worklet module caches belong to their AudioContext. Device removal uses the normal input/output configuration transactions, including WebRTC restart and rollback on failed default-device selection. A committed graph becomes the fallback preference before subsequent device enumeration completes.
|
||||
|
||||
Serialize `setSinkId` on each audio context or media element, since an in-flight browser sink change cannot be cancelled. Bind subsequent work to the original endpoint and current operation; session teardown invalidates queued changes and device enumeration results. If one output endpoint rejects after another changed, attempt to restore the last committed output.
|
||||
|
||||
@@ -29,7 +29,7 @@ Join voice channels, chat and share your screen from a browser. Deploy your own
|
||||
|
||||
| 能力 · Capability | 说明 · Highlights |
|
||||
| --- | --- |
|
||||
| 🎙️ 语音 · Voice | Opus、可选 WebRTC、WebSocket 回退、降噪与成员音量 / Opus, optional WebRTC, fallback, noise suppression and per-member volume |
|
||||
| 🎙️ 语音 · Voice | Opus、可选 WebRTC、WebSocket 回退、GTCRN / RNNoise 双引擎降噪、成员音量 / Opus, optional WebRTC, fallback, GTCRN/RNNoise denoising and per-member volume |
|
||||
| 💬 频道与聊天 · Channels & chat | 实时频道树、成员状态、私聊与本地历史 / Live channel tree, member state, private chat and local history |
|
||||
| 🖥️ 屏幕共享 · Screen sharing | 浏览器之间及与受支持的 TS6 客户端互通 / Between browsers and supported native TS6 clients |
|
||||
| 🎨 皮肤 · Skins | `.wskin` 外观、布局和小组件,支持 GitHub 分发 / Portable appearance, layouts and widgets, distributed through GitHub |
|
||||
@@ -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,102 @@
|
||||
# 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. Compatibility Opus defaults to auto (adaptive
|
||||
browsers use WebCodecs when available and fall back to PCM); set
|
||||
`WEBSPEAK_VOICE_OPUS_WS=0` to force PCM.
|
||||
|
||||
`WEBSPEAK_TURN_REST_URLS` accepts only `turn:`/`turns:` URL tokens. For static
|
||||
ICE credentials, use `WEBSPEAK_VOICE_ICE_SERVERS` with a JSON array of ICE
|
||||
server objects instead. WebSpeak generates short-lived `username`/`credential`
|
||||
pairs with HMAC-SHA1, compatible with coturn's `use-auth-secret`.
|
||||
|
||||
### Using a bare public IP
|
||||
|
||||
If the web domain only resolves to Cloudflare Tunnel, keep TURN on the public
|
||||
IP rather than on that domain:
|
||||
|
||||
```bash
|
||||
WEBSPEAK_TURN_REST_URLS='turn:203.0.113.10:3478?transport=udp,turn:203.0.113.10:3478?transport=tcp'
|
||||
```
|
||||
|
||||
`turn:` is cleartext TURN and needs no DNS name or certificate. If TCP/3478 is
|
||||
blocked, change coturn's `--listening-port` to `443` (and allow TCP/443), then
|
||||
use `turn:203.0.113.10:443?transport=tcp`. Only `turns:` requires a
|
||||
certificate. The web page can still be served as HTTPS/WSS by Cloudflare
|
||||
Tunnel; media does not use that hostname.
|
||||
|
||||
## 4. Verify
|
||||
|
||||
From a network that blocks direct UDP, open the voice page and check:
|
||||
|
||||
- `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.
|
||||
- Using a bare IP for media does not by itself determine whether a public
|
||||
service needs ICP filing or another permit; confirm the applicable
|
||||
requirements for the host's jurisdiction and use.
|
||||
@@ -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,250 @@
|
||||
# Cloudflare Tunnel 下的 WebSpeak 语音
|
||||
|
||||
本文说明“网页/信令走 Cloudflare Tunnel,媒体尽量直连 UDP”的部署方式。
|
||||
核心原则:
|
||||
|
||||
- **WebRTC 优先直连**:浏览器直接向网关公网 IP 的 `40000–40099/UDP` 发包。
|
||||
网页域名只解析到 Cloudflare,供 Tunnel 的 HTTPS/WSS 使用;媒体地址填公网 IP。
|
||||
- **Tunnel 只承载 HTTPS/WSS**:Cloudflare Tunnel 不转发 UDP,不能把
|
||||
Cloudflare 代理域名当作 ICE 媒体地址。
|
||||
- **TURN 只做后备**:手机流量、公司网络或 UDP 被拦时,才让媒体走
|
||||
`turn:`/`turns:`,不默认全程 `relay`。`turn:` 不需要域名或证书,可以继续用
|
||||
同一个公网 IP。
|
||||
- **CFT 是增量路径**:默认 `WEBSPEAK_VOICE_PROFILE=auto`,非可信 Cloudflare
|
||||
请求继续使用原有的 80ms 固定窗口、裸 1920 字节 PCM 和旧混音参数;只有
|
||||
经过可信 Cloudflare 代理的请求(或显式 `adaptive`)才启用自适应 buffer /
|
||||
pacer / 修正后的 RTP marker。不配置 CFT、TURN 或新变量时,直连部署保持原行为。
|
||||
- **兼容模式是兜底而非二等路径**:v3 批量下行、音频时钟、p95 抖动、丢包隐藏
|
||||
和 Opus 默认协商都只对 `adaptive` 生效;完全不能 UDP 的客户端仍能通话。
|
||||
|
||||
## 兼容性矩阵
|
||||
|
||||
| 部署 | 媒体路径 | 音频 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**:默认开启(auto)。仅 `adaptive` 生效;浏览器没有
|
||||
WebCodecs `AudioEncoder` 或编码器初始化失败时自动回退 PCM,不会因为开关
|
||||
打开就发不出声音。
|
||||
- **自适应 jitter 上限**:80–500 ms,配置自适应缓冲目标的上限;它不是严格的
|
||||
播放前瞻上限,调低也不会恢复旧版超限 `clear()` 行为。
|
||||
- **兼容模式调优**:兼容模式帧长 `20/40 ms`、直连失败后自动 TURN 重试、
|
||||
入口强制按 Cloudflare 处理。默认 `20 ms`、自动重试开启、强制识别关闭。
|
||||
- **TURN 后备**:TURN REST URL、共享密钥和凭证有效期。TURN 只在直连 UDP
|
||||
失败后使用,不作为默认路径。直连失败且存在 TURN 时,浏览器会自动做一次
|
||||
relay-only 重试(约 3 秒后),兼容音频在此期间继续播放;自动重试可在
|
||||
“兼容模式调优”里关闭。
|
||||
|
||||
保存后对**新的语音连接**生效,不需要重启网关。配置持久化在数据库中:控制台
|
||||
非空值覆盖对应环境变量,未配置的字段继续继承环境变量;清空 TURN URL 或在
|
||||
控制台移除密钥会显式停用 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 场景请显式填写公网媒体地址。
|
||||
5. “服务器 → 语音”里的 **WebRTC** 总开关必须打开;只填公网媒体地址但关闭
|
||||
WebRTC 时,`connected` 仍会报告 `webrtcAvailable=false`。
|
||||
|
||||
### 1.3 只有公网 IP、域名不落地 ICP 的部署
|
||||
|
||||
这是本项目推荐的 CFT 组合,也是“有公网 IP + 域名但不想把域名备案到境内源站”
|
||||
时最省事的做法:
|
||||
|
||||
- 域名只添加 Cloudflare DNS 记录,由 Cloudflare Tunnel 回源到本机的
|
||||
HTTPS/WSS 端口;源站不直接监听域名,也不使用该域名做媒体地址。
|
||||
- WebRTC 媒体使用 `<公网IP>:40000–40099/UDP`。浏览器拿到的是 IP 候选,
|
||||
不依赖域名解析、证书或 CDN 回源。
|
||||
- TURN 可以继续用同一个公网 IP:`turn:<公网IP>:3478?transport=udp` 和
|
||||
`?transport=tcp` 都是明文 TURN,不需要域名或证书;只有 `turns:` 才需要
|
||||
证书。需要 443/TCP 时,把 coturn 的 `listening-port` 改成 443 并放行 TCP,
|
||||
URL 写 `turn:<公网IP>:443?transport=tcp`。
|
||||
- Cloudflare Realtime TURN 只作为“UDP 全封”的最后兜底;它本身经过跨境网络,
|
||||
大陆用户的实际质量需要实测,不能替代同机 coturn。
|
||||
|
||||
媒体链路不使用域名,不等于对 ICP、许可或其他落地要求作出判断;这些要求由
|
||||
部署方根据所在地区、用途和实际接入方式自行确认。本文只描述技术链路。
|
||||
|
||||
## 2. 服务端环境变量
|
||||
|
||||
在启动 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` | `1` | 兼容模式是否允许浏览器用 WebCodecs 发 Opus;仅 `adaptive` 生效,默认 auto:浏览器不支持时自动回退 PCM。设为 `0` 可强制 PCM。 |
|
||||
| `WEBSPEAK_VOICE_JITTER_MAX_MS` | `300` | 自适应 jitter buffer 的上限,范围 80–500;仅 `adaptive` 生效。 |
|
||||
| `WEBSPEAK_VOICE_FRAME_MS` | `20` | 兼容模式帧长 `20` 或 `40`。40 ms 会把下行批量消息再减半,客户端上行 PCM 也按 40 ms 打包并由服务端拆回 20 ms;每个说话人最多多出 20 ms 等待。控制台“兼容模式调优”里的对应设置优先。 |
|
||||
| `WEBSPEAK_VOICE_AUTO_RELAY_RETRY` | `1` | 设为 `0` 关闭首次直连失败后的自动 relay-only 重试;控制台开关优先。 |
|
||||
| `WEBSPEAK_ASSUME_CLOUDFLARE` | 空 | 设为 `1` 时把语音入口一律按 Cloudflare 处理,适用于反向代理清掉了 `cf-ray` 等头但实际仍走 CFT 的部署;控制台开关优先。 |
|
||||
|
||||
示例(直连优先 + TURN 后备):
|
||||
|
||||
```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()` 解码器并重建,和旧版一致。
|
||||
|
||||
自适应分支:
|
||||
|
||||
- **v3 批量下行**:服务端按 20/40 ms tick 把同一时刻多个说话人的包合并成一条
|
||||
二进制消息(`0xF3` 头 + 音频时钟 + 每发言人 entry),消息数从“每包一条”降
|
||||
到“每 tick 一条”;旧前端不发 `audioCaps` 时自动保持 v2 逐包格式。
|
||||
- **音频时钟调度**:播放器用批次里的 `audioStartMs` 作为锚点,而不是每个包
|
||||
各自用 `currentTime` 重排;隧道一次突发到达多包时,后续包仍落在连续时间线上。
|
||||
- **p95 抖动目标**:2 秒 / 100 样本窗口的 95 分位,目标 `60 + p95`,下限
|
||||
80 ms、上限由 `audioJitterMaxMs` 控制;快升(每次最多 +40 ms)、慢降
|
||||
(每 2 秒 -2 ms),避免平均值把突发尾部吃掉后又反复欠载。
|
||||
- **丢包隐藏 / 跳帧**:seq 连续缺 1–8 帧时用上一帧做线性衰减隐藏(PLC),最多
|
||||
3 帧;领先目标 60 ms 以上跳 1 帧,领先 300 ms 以上重锚;静音超过 200 ms
|
||||
只重置抖动窗口,播放头仍由音频时钟决定,时钟跳变时再重锚。
|
||||
- 解码队列硬上限 12;只有极深积压才丢最新帧,不再因为 80 ms 窗口反复销毁
|
||||
解码器。
|
||||
- 上行 20 ms pacer;新帧格式 `0x01 + PCM` 和 `0x02 + Opus`,旧 1920 字节
|
||||
PCM 仍兼容;服务端也接受 40 ms(3840 字节)PCM 并拆成两个 20 ms 帧。
|
||||
- Opus 默认协商,24 kbps、`packetlossperc=10`、`useinbandfec=true`;浏览器
|
||||
没有 WebCodecs 或初始化失败时回退 PCM。
|
||||
|
||||
legacy 分支:
|
||||
|
||||
- 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`,且
|
||||
音频可通。第一次直连失败后,页面会出现“正在通过 TURN 中继重试”,兼容
|
||||
音频不应中断;relay 成功后横幅消失。
|
||||
3. 对未下发 WebRTC 的路径(关闭 WebRTC、无媒体路径或浏览器不支持)测
|
||||
2–3 分钟兼容模式。确认连接 `connected` 消息中的 `voiceProfile` 为
|
||||
`adaptive`,且 `audioDownlinkVersions` 包含 `3`;浏览器应在发
|
||||
`audioCaps` 后收到 `audioConfig.downlinkVersion=3`。`bufferResets`
|
||||
不应持续增长、没有解码器反复重建;若为 `legacy`,看到旧 80ms 行为是
|
||||
预期的。
|
||||
4. 兼容模式统计里 `downlinkBatchMessages` 应明显小于
|
||||
`downlinkBatchEntries`(多人同时说话时约等于“tick 数”而不是“包数”);
|
||||
`skippedFrames`/`concealedFrames` 偶发增长正常,持续快速增长才说明目标
|
||||
缓冲或网络异常。
|
||||
5. 关闭 CFT 或直连部署时,确认 `voiceProfile=legacy`、没有
|
||||
`audioDownlinkVersions`,旧客户端行为不变。
|
||||
|
||||
**回滚**
|
||||
|
||||
- 恢复非 CFT 旧行为:在管理台“语音模式”选 `兼容模式`,或设置
|
||||
`WEBSPEAK_VOICE_PROFILE=legacy`(没有控制台覆盖时)。legacy 会恢复
|
||||
80ms/`clear()`、裸 PCM、旧 WebRTC mixer;不需要回退前端构建。
|
||||
- 关闭兼容模式 Opus:在管理台取消“兼容模式使用 Opus”,或设置
|
||||
`WEBSPEAK_VOICE_OPUS_WS=0`;注意只有 `adaptive` 会下发 Opus 能力。
|
||||
- 回退 v3 批量下行:设置 `WEBSPEAK_VOICE_FRAME_MS=20` 只影响 tick,不会回退
|
||||
协议;要强制旧格式,可让前端不发送 `audioCaps`(回退前端构建),或临时在
|
||||
服务端禁用 v3 协商。回滚到 0.3.3 前端时,新服务端会自动走 v2。
|
||||
- 限制 jitter 缓冲:管理台把“自适应 jitter 上限”调到 80,或设置
|
||||
`WEBSPEAK_VOICE_JITTER_MAX_MS=80`;这只是把上限压回 80ms,**不会恢复
|
||||
旧版“超过 80ms 就 `clear()` 解码器”的行为**。要完全回到旧行为,使用
|
||||
`兼容模式` / `legacy`。
|
||||
- 关闭 TURN:在管理台清空 TURN URL(或移除密钥,会同时清空 URL),或删除
|
||||
`WEBSPEAK_TURN_REST_URLS` / `WEBSPEAK_TURN_REST_SECRET` 环境变量;浏览器
|
||||
只保留直连/STUN;不要为了“排障”把
|
||||
`WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY` 改成 `relay`,那会掩盖直连问题。
|
||||
- 媒体地址配置错误时,先清空管理台“公网媒体地址”并确认非 Cloudflare
|
||||
直连入口,再检查防火墙;Cloudflare 请求下留空会禁用直连,需要 TURN。
|
||||
- 语音覆盖配置保存在现有 metadata 表,数据库保持 schema 13;TURN 密钥仍加密。
|
||||
回退到 0.3.3 时旧程序会忽略新增元数据,不影响启动,也不会清除这些配置。
|
||||
自动更新失败时可以继续使用现有代码回滚流程,无需降级数据库。
|
||||
|
||||
## 5. 已知限制
|
||||
|
||||
- 本文的 coturn/cloudflared 模板未做真实端到端联调;部署前必须在
|
||||
目标网络验证 `3478/UDP`、`3478/TCP`、relay 端口和凭证一致性。
|
||||
- Safari/Firefox 的 WebCodecs Opus 支持差异未在真实设备上逐一验证;
|
||||
不支持时会回退 PCM,但兼容模式的 CPU/带宽开销会更高。
|
||||
- Cloudflare Tunnel 不承载本文的 WebRTC UDP 媒体;即使 HTTPS/WSS 正常,
|
||||
仍需要独立可达的公网媒体地址,或配置 TURN/使用兼容模式。
|
||||
@@ -0,0 +1,79 @@
|
||||
# 麦克风降噪(GTCRN / RNNoise)
|
||||
|
||||
WebSpeak 的麦克风链提供四档降噪:关闭、标准(浏览器)、轻量(RNNoise)、强效(GTCRN)。默认使用 GTCRN,全部在浏览器本地运行,不上传音频、不依赖 CDN。
|
||||
|
||||
## 引擎对比
|
||||
|
||||
| 引擎 | 模型/体积 | 帧长与延迟 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| GTCRN(默认) | 23.7K 参数,`gtcrn.wasm` ≈ 197 KB(gzip ≈ 116 KB) | 768 样本 ≈ 16 ms @48 kHz | ICASSP 2024,同量级质量高于 RNNoise;MIT |
|
||||
| RNNoise | 85 KB,SIMD 版本 ≈ 157 KB | 480 样本 ≈ 10 ms @48 kHz | 低配设备与兼容兜底 |
|
||||
| 浏览器 APM | 浏览器内置 | 浏览器内部 | `noiseSuppression: true`;Chrome 默认约 12 dB,档位不可从 `getUserMedia` 选择 |
|
||||
| 关闭 | — | 0 | 不做任何处理 |
|
||||
|
||||
两个神经引擎都按 48 kHz 设计。音频上下文不是 48 kHz、没有 `AudioWorklet`,或 WASM 预加载失败时,自动回退到浏览器降噪。
|
||||
|
||||
## 信号链
|
||||
|
||||
```
|
||||
getUserMedia (EC=on, AGC=off, NS=按模式)
|
||||
→ MediaStreamSource
|
||||
→ [模型模式] BiquadFilter(highpass, 80 Hz, Q=0.707)
|
||||
→ [模型模式] GTCRN / RNNoise (AudioWorklet)
|
||||
→ GainNode
|
||||
→ MediaStreamDestination (WebRTC) + capture worklet (兼容 PCM)
|
||||
```
|
||||
|
||||
- 模型模式与浏览器降噪**互斥**。浏览器先削语音、模型再处理会损伤音质,也会浪费 CPU。
|
||||
- 80 Hz 高通只加在模型链上,去掉风扇、桌面震动和手持低频隆隆声。
|
||||
- 不做干湿混合:GTCRN 没有衰减上限 API,干声需精确延迟 768 样本才能对齐,否则产生梳状滤波。
|
||||
- 不新增噪声门:现有 VOX 已负责静音门控,模型后再叠 gate 容易切掉字头。
|
||||
|
||||
## 回退与状态
|
||||
|
||||
| 条件 | 结果 |
|
||||
| --- | --- |
|
||||
| 无 `AudioWorklet` | `browser`,原因 `no-worklet` |
|
||||
| 音频上下文非 48 kHz | `browser`,原因 `sample-rate` |
|
||||
| WASM / worklet 预加载失败 | `browser`,原因 `load-failed` |
|
||||
| 预加载成功但节点构造失败 | 本次不挂模型,`off` + `load-failed`,设置页显示“模型未能启动,本次不降噪”,下次重连重试 |
|
||||
| 浏览器忽略 `noiseSuppression:false` | 照常运行,状态显示可能叠加 |
|
||||
|
||||
设置页会显示实际生效引擎与回退原因,而不是只显示用户选择。`microphoneProcessing` 同时向皮肤暴露 `noiseSuppressionEnabled` 布尔值,旧契约不变。
|
||||
|
||||
## 参考项目
|
||||
|
||||
| 项目 | 采用点 |
|
||||
| --- | --- |
|
||||
| Jitsi Meet | RNNoise 跑在 AudioWorklet;模型降噪开启时关闭浏览器降噪 |
|
||||
| Element Call / matrix-js-sdk | `@sapphi-red/web-noise-suppressor` 的 worklet 生命周期管理 |
|
||||
| WorkAdventure | 双引擎可切换、48 kHz 上下文要求;其 DFN3 方案因 71 ms 延迟未采用 |
|
||||
| Mumble | 引擎选择 + 本地回环试听 |
|
||||
| OBS Studio | RNNoise 作低配档、降噪与噪声门分离 |
|
||||
| WebRTC APM | NS 档位与 80 Hz 高通;浏览器档位不可编程,只作兜底 |
|
||||
| LiveKit / Krisp | 商业模型体积与授权不适合自托管,未采用 |
|
||||
| DeepFilterNet3 | 质量更高但模型 + WASM 约 11 MB、附加 30–71 ms,留作后续可选 |
|
||||
|
||||
## 手工验证记录
|
||||
|
||||
自动化测试不声称真实音质。每次改动采集链后,在 `web/` 下 `npm run build` 并记录:
|
||||
|
||||
| 环境 | 采样率 | 实际引擎 | 附加延迟 | CPU | 结论 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| Chromium(无头 Chrome,`--autoplay-policy=no-user-gesture-required`,220 Hz 测试音) | 48 kHz | GTCRN | 16 ms | 未测 | 通过:`engine=gtcrn`、`fallback=null`;700 ms 收到 35 帧 PCM,稳态音被模型明显衰减 |
|
||||
| Chrome / Edge(Windows,真实麦克风) | 48 kHz | GTCRN | 16 ms | 待测 | 待听感与 CPU 复测 |
|
||||
| Firefox(Windows) | 48 kHz | 待测 | 16 ms | 待测 | 待测 |
|
||||
| Android WebView | 48 kHz | 待测 | 16 ms | 待测 | 待测 |
|
||||
|
||||
验证项:
|
||||
|
||||
1. 设置页显示“当前生效:GTCRN”,切换四档均能重建采集且不中断语音。
|
||||
2. 麦克风测试的“原始 / 降噪后”来自同一段 5 秒采集,能听出风扇/键盘差异。
|
||||
3. 稳态噪声段衰减 ≥12 dB,语音电平变化 ≤3 dB;键盘声不出现“抽真空”或字头被切。
|
||||
4. 阻断 `gtcrn.wasm` 请求后重新连接,状态回退到浏览器降噪且仍能开麦。
|
||||
|
||||
## 部署注意
|
||||
|
||||
- 资源由 Vite 打包进 `web/dist/assets`(`gtcrn-*.wasm`、`workletProcessor-*.js`),随现有静态资源一起部署。
|
||||
- 若反向代理额外添加 CSP,需要允许 `wasm-unsafe-eval`(WASM 实例化)与 `worker-src 'self' blob:`(AudioWorklet)。
|
||||
- 不需要新增环境变量或服务端配置。
|
||||
@@ -151,4 +151,4 @@ export default async function activate({ dataDir, config, publicConfig, events,
|
||||
|
||||
## 实例级用户授权
|
||||
|
||||
首次访问时,宿主统一征求第三方皮肤与功能应用的使用授权;决定按浏览器源保存,不迁移旧的逐皮肤授权。拒绝或未选择时,只显示日间、夜间、ILLUSIA 三款官方皮肤,KAAK 和功能应用入口均隐藏。皮肤菜单最后的“授权”可随时更改。撤回会关闭 iframe 并撤销当前打开操作/应用会话,不停止管理员启用的全实例后台服务。应用不得以入口以外的方式绕过宿主授权,也无需重复询问同一份宿主上下文授权;相机、麦克风等浏览器原生许可仍由浏览器处理。
|
||||
首次访问时,宿主统一征求第三方皮肤与功能应用的使用授权;决定按浏览器源保存,不迁移旧的逐皮肤授权。拒绝或未选择时,只显示日间、夜间、ILLUSIA 三款官方皮肤,KAAK、Classic 和功能应用入口均隐藏。皮肤菜单最后的“授权”可随时更改。撤回会关闭 iframe 并撤销当前打开操作/应用会话,不停止管理员启用的全实例后台服务。应用不得以入口以外的方式绕过宿主授权,也无需重复询问同一份宿主上下文授权;相机、麦克风等浏览器原生许可仍由浏览器处理。
|
||||
+6
-2
@@ -39,7 +39,7 @@ Willkommensseite und Sprachbereich direkt ausprobieren. Netzwerk, Auslastung und
|
||||
| Bildschirm & Audio | Bildschirmfreigabe zwischen Browsern und unterstützten nativen TeamSpeak-6-Clients mit Qualitäts-, Bitraten- und Statistikoptionen; Fenster-/Tab-Audio auf dem Desktop. |
|
||||
| Identität & Verbindungen | Gespeicherte Identitäten, TS3-Identitätsimport/-export, Favoriten und Verlauf, SRV-/Nickname-Auflösung, IPv4/IPv6 und Einladungen. |
|
||||
| Instanzverwaltung | Feste oder offene Ziele, Zugriffsregeln, Einladungen, Sitzungen, Logs, Diagnosen, Backups und optionale TeamSpeak-Verwaltung. |
|
||||
| Skins & Oberfläche | Tag, Nacht, ILLUSIA und KAAK, `.wskin`-Pakete über GitHub, fünf Sprachen und responsive Ansichten. |
|
||||
| Skins & Oberfläche | Tag, Nacht, ILLUSIA, KAAK und Classic, `.wskin`-Pakete über GitHub, fünf Sprachen und responsive Ansichten. |
|
||||
| Verteilte Sprache | Der Browser verbindet sich direkt mit dem gewählten Relay-Sprach-Gateway; die URL der Eingangsinstanz bleibt erhalten. |
|
||||
| Bereitstellung | Docker amd64/arm64, Serverpakete für Windows x64 und Linux x64/ARM64 sowie Android-Vorschau-APKs. |
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
+6
-4
@@ -39,7 +39,7 @@ Try the welcome page and voice workspace. Network conditions, load and availabil
|
||||
| Screen & audio sharing | Screen sharing between browsers and supported native TeamSpeak 6 clients, with quality, bitrate and statistics controls; desktop window or tab audio sharing. |
|
||||
| Identity & connections | Remembered identities, TS3 identity import/export, favorites and history, SRV and Nickname resolution, IPv4/IPv6 and invitation links. |
|
||||
| Instance administration | Fixed or open targets, access policy, invitations, sessions, logs, diagnostics, backups and optional TeamSpeak management connections. |
|
||||
| Skins & interface | Day, Night, ILLUSIA and KAAK, plus GitHub distribution of `.wskin` packages, five interface languages and responsive layouts. |
|
||||
| Skins & interface | Day, Night, ILLUSIA, KAAK and Classic, plus GitHub distribution of `.wskin` packages, five interface languages and responsive layouts. |
|
||||
| Distributed voice | Browsers connect directly to the selected relay voice gateway while the page stays on the ingress instance URL. |
|
||||
| Deployment | Docker amd64/arm64, Windows x64 and Linux x64/ARM64 server packages, plus Android preview APKs. |
|
||||
|
||||
@@ -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. Compatibility Opus defaults to auto: adaptive browsers with WebCodecs use 24 kbps Opus + FEC and fall back to PCM otherwise; set `WEBSPEAK_VOICE_OPUS_WS=0` or disable it under Admin → Voice to force PCM. Adaptive compatibility mode also uses v3 batched downlink (negotiated by `audioCaps`, one message per 20/40 ms tick), an audio-clock anchor, a p95 jitter target, PLC concealment, and one automatic relay retry. If neither direct UDP nor TURN provides a media path, the session reports `NO_MEDIA_PATH` and uses the compatibility transport.
|
||||
|
||||
See [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md) for the direct-UDP-first topology, coturn/cloudflared templates, verification and rollback notes.
|
||||
|
||||
### Screen-share ICE candidates
|
||||
|
||||
@@ -308,7 +310,7 @@ Disable and save the relay configuration to remove the relay option from the wel
|
||||
|
||||
Skins own appearance, layout and their attached widgets. Administrators install, enable and choose the default skin. Authors use the public contract without changing WebSpeak source code.
|
||||
|
||||
[Development guide](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [Skin catalog](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice example](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)
|
||||
[Development guide](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [Skin catalog](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice example](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice) · [Host chrome toolbar example](./examples/HOST-CHROME-TOOLBAR.md)
|
||||
|
||||
### Functional plugins `.wplugin`
|
||||
|
||||
|
||||
+6
-2
@@ -39,7 +39,7 @@ WebSpeak はセルフホスト型の TeamSpeak 3 / TeamSpeak 6 ブラウザー
|
||||
| 画面と音声の共有 | ブラウザー間および対応する TeamSpeak 6 クライアントとの画面共有。品質、ビットレート、統計を設定でき、デスクトップではウィンドウやタブの音声も共有可能。 |
|
||||
| ID と接続 | ID 保持、TS3 ID インポート・エクスポート、お気に入りと履歴、SRV・Nickname 名前解決、IPv4/IPv6、招待リンク。 |
|
||||
| インスタンス管理 | 固定・公開接続先、アクセス方針、招待、セッション、ログ、診断、バックアップ、任意の TeamSpeak 管理接続。 |
|
||||
| スキンと画面 | 昼・夜・ILLUSIA・KAAK、GitHub 経由の `.wskin` 配布、5 言語、レスポンシブ表示。 |
|
||||
| スキンと画面 | 昼・夜・ILLUSIA・KAAK・Classic、GitHub 経由の `.wskin` 配布、5 言語、レスポンシブ表示。 |
|
||||
| 分散音声 | ブラウザーが選択した中継の音声ゲートウェイに直接接続し、ページの URL は入口インスタンスのまま維持。 |
|
||||
| デプロイ方法 | Docker amd64/arm64、Windows x64・Linux x64/ARM64 サーバーパッケージ、Android プレビュー APK。 |
|
||||
|
||||
@@ -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 候補
|
||||
|
||||
|
||||
+6
-2
@@ -39,7 +39,7 @@ WebSpeak — самостоятельно размещаемый браузер
|
||||
| Экран и аудио | Обмен экраном между браузерами и поддерживаемыми нативными клиентами TeamSpeak 6, настройки качества, битрейта и статистика; звук окна или вкладки на компьютере. |
|
||||
| Идентичность и подключения | Сохранение идентичности, импорт/экспорт TS3, избранное и история, разрешение SRV и Nickname, IPv4/IPv6 и приглашения. |
|
||||
| Управление экземпляром | Фиксированные или открытые цели, доступ, приглашения, сессии, журналы, диагностика, резервные копии и необязательное управление TeamSpeak. |
|
||||
| Скины и интерфейс | Дневная, ночная, ILLUSIA и KAAK, пакеты `.wskin` через GitHub, пять языков и адаптивная вёрстка. |
|
||||
| Скины и интерфейс | Дневная, ночная, ILLUSIA, KAAK и Classic, пакеты `.wskin` через GitHub, пять языков и адаптивная вёрстка. |
|
||||
| Распределённый голос | Браузер подключается напрямую к выбранному голосовому ретранслятору, сохраняя URL входного экземпляра. |
|
||||
| Развёртывание | Docker amd64/arm64, серверные пакеты Windows x64 и Linux x64/ARM64, а также предварительные Android APK. |
|
||||
|
||||
@@ -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 для демонстрации экрана
|
||||
|
||||
|
||||
@@ -34,12 +34,12 @@ WebSpeak 是可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语
|
||||
|
||||
| 能力 | 说明 |
|
||||
| --- | --- |
|
||||
| 实时语音 | Opus 音频、可选 WebRTC、兼容 WebSocket 回退;支持闭麦、VOX、设备选择、浏览器降噪和成员独立音量。 |
|
||||
| 实时语音 | Opus 音频、可选 WebRTC、兼容 WebSocket 回退;支持闭麦、VOX、设备选择、GTCRN / RNNoise 双引擎降噪、原始/降噪 A/B 试听和成员独立音量。 |
|
||||
| 频道与消息 | 频道树、TeamSpeak 频道分隔栏、成员状态、频道切换、频道/服务器/私聊消息、戳一戳、耳语及本地聊天历史。 |
|
||||
| 屏幕与音频共享 | 浏览器之间及与受支持的 TeamSpeak 6 原生客户端共享屏幕;提供采集质量、码率和统计面板,桌面端还可分享窗口或标签页音频。 |
|
||||
| 身份与连接 | 身份保持、TS3 身份导入/导出、收藏和历史连接、SRV 与 Nickname 地址解析、IPv4/IPv6 及邀请链接。 |
|
||||
| 实例管理 | 固定或公开目标、访问策略、邀请、会话、日志、诊断、备份及可选的 TeamSpeak 管理连接。 |
|
||||
| 皮肤与界面 | 日间、夜间、ILLUSIA 和 KAAK;可通过 GitHub 皮肤商店管理 `.wskin` 包,支持五种语言和响应式布局。 |
|
||||
| 皮肤与界面 | 日间、夜间、ILLUSIA、KAAK 和 Classic;可通过 GitHub 皮肤商店管理 `.wskin` 包,支持五种语言和响应式布局。 |
|
||||
| 分布式语音 | 配置中继后,浏览器直接连接所选中继的语音网关,网页地址仍保留在入口实例。 |
|
||||
| 部署方式 | Docker amd64/arm64、Windows x64 与 Linux x64/ARM64 发布包;另有 Android 预览 APK。 |
|
||||
|
||||
@@ -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`,也可在控制台“语音模式”覆盖。兼容模式 Opus 默认 auto:`adaptive` 下浏览器支持 WebCodecs 就用 24 kbps Opus + FEC,否则自动回退 PCM;可在“服务器 → 语音”或通过 `WEBSPEAK_VOICE_OPUS_WS=0` 强制关闭。自适应兼容模式使用 v3 批量下行(`audioCaps` 协商,一个 20/40ms tick 一条消息)、音频时钟锚点、p95 抖动目标、PLC 丢包隐藏和自动 relay 重试。直连 UDP 与 TURN 都无法提供媒体路径时,会话报告 `NO_MEDIA_PATH` 并使用兼容传输。完整部署、验收和回滚见 [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md),模板见 `deploy/coturn/` 和 `deploy/cloudflared/`。
|
||||
|
||||
### 屏幕共享的 ICE 候选
|
||||
|
||||
@@ -329,7 +331,7 @@ relay.example.com {
|
||||
|
||||
皮肤包负责外观、布局及其附属小组件。管理员可安装、启用和设置默认皮肤;开发时遵循公开接口,无需修改 WebSpeak 源码。
|
||||
|
||||
[开发指南](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [皮肤索引仓库](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice 示例](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)
|
||||
[开发指南](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [皮肤索引仓库](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice 示例](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice) · [宿主顶栏 toolbar 示例](./examples/HOST-CHROME-TOOLBAR.md)
|
||||
|
||||
### 功能插件 `.wplugin`
|
||||
|
||||
|
||||
+141
-16
@@ -26,9 +26,11 @@ v3 保留安全的标准元素和属性白名单;组件可通过完整页面 s
|
||||
|
||||
可直接查看 [ILLUSIA 风示例源码](examples/illusia-voice/) 与 [示例说明](examples/ILLUSIA-VOICE.md)。它使用本地美术素材和 CSS 完整定制首页、语音房间、成员区、聊天空状态及播放器,同时沿用 WebSpeak 提供的基础翻译;也是管理控制台内置且不可移除的示例皮肤。
|
||||
|
||||
宿主外壳与恢复入口的 toolbar 停靠见 [Host Chrome Toolbar 示例](examples/HOST-CHROME-TOOLBAR.md):它用最小包演示 `mode: "toolbar"`、按页候选锚点、工具栏令牌、应用库去重和坏锚点回退,不包含任何真实服务器或成员数据。
|
||||
|
||||
## 使用与发布
|
||||
|
||||
管理员在 `/admin/skins` 查看三款随 WebSpeak 提供的内置皮肤,并可导入、替换、启用/停用或删除实例自定义皮肤;还可指定访客首次访问时使用的默认皮肤。默认日间、默认夜间和 ILLUSIA 风为受保护内置项,不可替换、停用或移除。访客手动选择的皮肤保存在该浏览器,后续实例默认值变更不会覆盖该明确选择;仅自动套用过旧默认值的浏览器会采用最新实例默认值。皮肤包会缓存在浏览器本地;页面启动时会查询实例目录,目录可用且版本更新时拉取新包。若网络不可用,已缓存的版本仍可使用。
|
||||
管理员在 `/admin/skins` 查看随 WebSpeak 提供的内置皮肤(默认日间、默认夜间、ILLUSIA 风、KAAK 和 Classic),并可导入、替换、启用/停用或删除实例自定义皮肤;还可指定访客首次访问时使用的默认皮肤。这些随包内置皮肤均为受保护内置项,不可替换、停用或移除。访客手动选择的皮肤保存在该浏览器,后续实例默认值变更不会覆盖该明确选择;仅自动套用过旧默认值的浏览器会采用最新实例默认值。皮肤包会缓存在浏览器本地;页面启动时会查询实例目录,目录可用且版本更新时拉取新包。若网络不可用,已缓存的版本仍可使用。
|
||||
|
||||
选择器提供默认日间、默认夜间、内置 ILLUSIA 风和已启用的实例皮肤;没有“跟随系统”选项。停用的实例皮肤不向访客展示,也不能从服务端下载;若它是当前默认皮肤,系统会安全回退到默认日间。管理员设置的默认值只影响未手动选择皮肤的访客。自定义皮肤是独立的外观选择,不继承之前的日间或夜间模式;皮肤未覆盖的部件回退到浅色基础外观,避免一套组件混入另一套模式。自定义皮肤可自行声明 `color-scheme` 并定义深色外观;切换为日间或夜间时,会停用当前自定义包。文档级 `data-theme` 仍由 WebSpeak 保留给管理后台使用。
|
||||
|
||||
@@ -127,7 +129,7 @@ plugins/<plugin-id>/assets/ # v4 插件专属的本地图片或字体素材
|
||||
| 字段 | 规则 |
|
||||
| --- | --- |
|
||||
| `schemaVersion` | 当前必须为数字 `1`。 |
|
||||
| `id` | 必需,最多 80 个字符;只允许小写字母、数字、点和连字符;不能以 `builtin.` 开头,也不能使用受保护 ID `builtin.light`、`builtin.dark` 或 `community.illusia-voice`。发布后不要更改。 |
|
||||
| `id` | 必需,最多 80 个字符;只允许小写字母、数字、点和连字符;不能以 `builtin.` 开头,也不能使用受保护 ID `builtin.light`、`builtin.dark`、`community.illusia-voice`、`community.kaak-voice` 或 `community.ts3-classic-console`。发布后不要更改。 |
|
||||
| `name`、`author`、`license` | 必需,各最多 80 个字符。资源授权由作者负责确认。 |
|
||||
| `version`、`minAppVersion` | 必需,使用语义化版本号,例如 `1.2.0`。 |
|
||||
| `entry` | 必需,包内 CSS 文件路径,最多 120 个字符。 |
|
||||
@@ -406,7 +408,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
| 聊天与菜单 | `voice.chat`、`voice.chat.tabs`、`voice.chat.tab`、`voice.chat.heading`、`voice.chat.messages`、`voice.chat.event`、`voice.chat.message`、`voice.chat.message-avatar`、`voice.chat.message-body`、`voice.chat.message-bubble`、`voice.chat.empty`、`voice.chat.composer`、`voice.chat.status`、`voice.context-menu-backdrop`、`voice.context-menu`、`voice.context-menu.header`、`voice.context-menu.move-submenu` |
|
||||
| 屏幕共享 | `voice.screen-share-settings`、`voice.screen-share-settings.heading`、`voice.screen-share-settings.fields`、`voice.screen-share-settings.note`、`voice.screen-share-settings.actions`、`voice.screen-player`、`voice.screen-player.stage`、`voice.screen-player.video`、`voice.screen-player.placeholder`、`voice.screen-player.exit`、`voice.screen-player.viewers`、`voice.screen-player.viewer-avatar`、`voice.screen-player.live`、`voice.screen-player.source`、`voice.screen-player.controls`、`voice.screen-player.volume`、`voice.screen-player.fullscreen` |
|
||||
| `/demo` 演示页 | `demo.header`、`demo.brand`、`demo.header-tools`、`demo.badge`、`demo.skin-switcher`、`demo.language-switcher`、`demo.home-link`、`demo.reconnect`、`demo.reconnect.restore`、`demo.layout`、`demo.channels`、`demo.channels.heading`、`demo.channel`、`demo.channel.select`、`demo.channel.members`、`demo.main`、`demo.hero`、`demo.live`、`demo.hero.title`、`demo.hero.description`、`demo.hero.online`、`demo.wave`、`demo.voice-heading`、`demo.voice-grid`、`demo.voice-card`、`demo.avatar`、`demo.member-name`、`demo.member-status`、`demo.chat.heading`、`demo.chat.tabs`、`demo.chat.tab`、`demo.chat.messages`、`demo.chat.message`、`demo.chat.empty`、`demo.chat.composer`、`demo.chat.input`、`demo.chat.send`、`demo.actions`、`demo.actions.heading`、`demo.action.speaking`、`demo.action.poke`、`demo.action.reconnect`、`demo.note`、`demo.user`、`demo.poke-notification`、`demo.poke.dismiss` |
|
||||
| 宿主外壳(皮肤根之外 / 宿主固定绘制) | 可主题化:`host.plugins.launcher`、`host.plugins.overlay`、`host.watermark`、`host.hint`、`host.voice-status-decoration`;`host.recovery`(可经 `chrome.json#slots` 停靠,并可用 `--skin-recovery-*` / `--skin-host-*` 令牌换肤)/ `host.permission` 与 `app.skin-load-recovery`(无 CSS 钩子;分别用 `--skin-permission-*` / `--skin-load-recovery-*` 令牌换肤,见下文);`skin.library` 是皮肤菜单里的应用库入口 |
|
||||
| 宿主外壳(皮肤根之外 / 宿主固定绘制) | 可主题化:`host.plugins.launcher`、`host.plugins.overlay`、`host.watermark`、`host.hint`、`host.voice-status-decoration`;`host.recovery`(可经 `chrome.json#slots` 以胶囊或 `mode: "toolbar"` 的宿主按钮停靠,并可用 `--skin-recovery-*` / `--skin-host-*` 以及 `--skin-recovery-toolbar-*` / `--skin-host-toolbar-*` 令牌换肤)/ `host.permission` 与 `app.skin-load-recovery`(无 CSS 钩子;分别用 `--skin-permission-*` / `--skin-load-recovery-*` 令牌换肤,见下文);`skin.library` 是皮肤菜单里的应用库入口 |
|
||||
| 首页页脚拆分 | `home.footer`(容器,不可隐藏)、`home.footer.decoration`(装饰文案,可隐藏)、`home.footer.clear`(必要链接,受保护) |
|
||||
|
||||
`voice.member.avatar` 是语音活动区头像;`voice.member.mic-status` 在成员麦克风静音时显示,状态值为 `muted`;`voice.member.action-trigger` 是打开宿主成员操作菜单的按钮,由成员卡片小组件的 `options.memberActions` 控制;`voice.member-row.avatar` 是右侧成员树头像。语音成员列表的动态项提供 `.ws-voice-member-enter-active`、`.ws-voice-member-leave-active`、`.ws-voice-member-enter-from`、`.ws-voice-member-leave-to` 和 `.ws-voice-member-move` 动效钩子,可分别设置加入、离开和排序变化的过渡。状态属性还会使用 `current`、`drag-over`、`dragging`、`self`、`events-empty` 和 `messages-empty`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
|
||||
@@ -438,7 +440,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
- 宿主外壳的布局与层级:应用库外壳 `host.plugins.overlay` 仍由 WebSpeak 拥有——皮肤可改颜色、边框、圆角、阴影和素材,但不能用 `position`、`inset`、`z-index`、`transform`、尺寸等把它或其子元素变成全屏遮罩。装饰性宿主部件(`host.watermark`、`host.hint`、`host.voice-status-decoration`、`host.plugins.launcher`)可以被重定位、改变尺寸和动画化;恢复路径不依赖它们。
|
||||
- 自定义变量仍必须使用 `--skin-` 前缀(不能覆盖宿主内部令牌),`@import`、脚本、`expression()`、`javascript:` 等仍被拒绝。
|
||||
- 皮肤根作用域只在根内部向下生效。编译器会拒绝任何以 `:root` 开头、紧跟兄弟组合符(`+` / `~`)的选择器,例如 `:root ~ *`、`:root ~ [data-ws-host-layer]` 或 `:root:hover + div`;这类规则会被改写为皮肤根的兄弟选择器,从而够到 body 上的宿主层。`:root [data-ws-part="home.header"]`、`:root > [data-ws-part=…]` 这类后代/子代写法仍然可用。
|
||||
- 宿主自有层的属性 `data-ws-host-layer`、`data-ws-host-recovery`、`data-ws-host-layer-content` 与 `data-ws-recovery-action` **不是皮肤钩子**:它们不在公开部件表中,编译器会按名称拒绝引用它们的皮肤选择器(包括 `:root [data-ws-host-layer]` 这类带公开钩子的混合写法)。
|
||||
- 宿主自有层的属性 `data-ws-host-layer`、`data-ws-host-recovery`、`data-ws-host-recovery-toolbar`、`data-ws-host-layer-content` 与 `data-ws-recovery-action` **不是皮肤钩子**:它们不在公开部件表中,编译器会按名称拒绝引用它们的皮肤选择器(包括 `:root [data-ws-host-layer]`、`:root [data-ws-part="home.header"] [data-ws-host-recovery-toolbar]` 这类带公开钩子的混合写法)。
|
||||
- 无 Popover API 或顶层提升被拒绝时,恢复胶囊会退回固定宿主层并使用 32 位最大 `z-index: 2147483647`。宿主层在 `#app` 之后追加到 `document.body`;与树内皮肤层同为最大层级时,后绘制的宿主层仍在上面。顶层(top layer)路径的 `showPopover()` / `showModal()` 仍高于两者。
|
||||
|
||||
可主题化的宿主部件:
|
||||
@@ -453,15 +455,15 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
|
||||
### 恢复入口与授权对话框:结构上不可被皮肤触及
|
||||
|
||||
`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或直接改写的 CSS 钩子;当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们。皮肤可以通过下文「受保护控件的主题化」中的受控令牌让它们融入外观,`host.recovery` 还可以通过 `chrome.json#slots` 停靠到皮肤布局:
|
||||
`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或直接改写的 CSS 钩子;当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们。皮肤可以通过下文「受保护控件的主题化」中的受控令牌让它们融入外观,`host.recovery` 还可以通过 `chrome.json#slots` 停靠到皮肤布局,或声明 `mode: "toolbar"` 后以无胶囊壳的宿主按钮并入皮肤顶栏(见下文「工具栏模式」):
|
||||
|
||||
1. **闭合 Shadow DOM**:内容位于 `attachShadow({ mode: "closed" })` 的根内。作者 CSS(无论影子根开或闭)不能跨越 shadow 边界;宿主层元素本身也不带任何 `data-ws-part`,因此连文档级宿主作用域(`:root[data-ws-host-skin="…"] [data-ws-part="host.…"]`)也匹配不到。
|
||||
2. **顶层(top layer)**:恢复入口是 `popover="manual"`,授权对话框是 `<dialog>` + `showModal()`。顶层绘制高于所有普通层叠上下文,包括皮肤把某个公开部件写成 `position: fixed; inset: 0; z-index: 2147483647` 的全屏层。
|
||||
3. **不依赖可主题化浮层**:恢复面板的「使用内置皮肤」直接重置到内置 Day/Night 皮肤,不经过 `host.plugins.overlay`;即使皮肤把该浮层写成 `display: none !important` 或 `pointer-events: none`,重置仍然生效。「应用库」按钮只是一条便利路径,会走常规应用库浮层,因此不是兜底路径。
|
||||
|
||||
**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角(皮肤可通过下文的 `chrome.json#slots` 申请停靠到自己的锚点);它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。
|
||||
**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角(皮肤可通过下文的 `chrome.json#slots` 申请停靠到自己的锚点,或用 `mode: "toolbar"` 改成宿主顶栏按钮);它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。
|
||||
|
||||
**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。监听器运行在捕获阶段,皮肤或插件脚本提前调用 `preventDefault()` 不会吞掉该组合键。
|
||||
**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;无论胶囊是停靠、浮动还是被 `mode: "toolbar"` 替换,快捷键都会临时隐藏工具栏并显示完整胶囊。macOS 上 ⌥ 会把字母键变成派生字符(美式为 `®`),宿主同时按物理键码 `KeyR` 判定,所以该组合键仍然生效。它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。监听器运行在捕获阶段,皮肤或插件脚本提前调用 `preventDefault()` 不会吞掉该组合键。
|
||||
|
||||
`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不对应可被皮肤命中的 DOM 钩子**。当前客户端没有渲染 `host.permission` 元素;授权界面由宿主自己的 `InstanceAuthorization` 对话框绘制,它和恢复胶囊一样位于闭合 Shadow DOM 的顶层。皮肤加载失败的横幅保留 `app.skin-load-recovery` 部件标识(「切换到内置皮肤」),它同样运行在闭合 Shadow DOM 宿主层中。三者都只能通过受保护控件令牌间接换肤,编译后的皮肤 CSS 无法命中或改写它们。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。
|
||||
|
||||
@@ -469,7 +471,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
|
||||
#### 将恢复入口停靠到皮肤布局(`chrome.json#slots`)
|
||||
|
||||
第三方皮肤可以在 `chrome.json` 中用 `slots` 声明一个自己已经拥有的布局锚点,让恢复胶囊停靠在皮肤界面里,而不是固定盖在左下角。胶囊仍然是宿主控件:皮肤只提供锚点部件名和视觉令牌,无法取得它的 DOM、点击处理或 CSS 选择器;未知的 `data-ws-*` 属性仍由生成界面拒绝。内置/官方皮肤没有 `chrome.json`,行为完全不变。
|
||||
第三方皮肤可以在 `chrome.json` 中用 `slots` 声明一个自己已经拥有的布局锚点,让恢复入口停靠在皮肤界面里,而不是固定盖在左下角。默认仍是带胶囊壳的恢复胶囊;显式写 `mode: "toolbar"` 时改为无胶囊壳的宿主按钮,可直接并入皮肤顶栏。两种形态都是宿主控件:皮肤只提供锚点部件名和视觉令牌,无法取得它们的 DOM、点击处理或 CSS 选择器;未知的 `data-ws-*` 属性仍由生成界面拒绝。内置/官方皮肤没有 `chrome.json`,行为完全不变。
|
||||
|
||||
```json
|
||||
"slots": {
|
||||
@@ -479,10 +481,12 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
|
||||
| 字段 | 规则 |
|
||||
| --- | --- |
|
||||
| 键名 | 目前只接受 `host.recovery`(`src/shared/skin-visual-parts.ts` 的 `HOST_SLOTTABLE_PART_IDS`;后续可加入其他受保护控件)。未知键或未开放控件会被拒绝,错误码为 `SKIN_CHROME_SLOT_INVALID`。 |
|
||||
| `anchor` | 必填,必须是 `.ws-skin-root` 内已存在的 `data-ws-part` 名称。不能是 `host.*`,也不能是任何可信宿主部件(如 `app`、`voice.connection-status`、`auth.password.*`)。宿主只取第一个可见匹配;锚点不存在、`display:none`、`visibility:hidden`、完全透明、被裁剪、尺寸过小或大部分移出视口时都会回退。 |
|
||||
| `align` | 可选,`start`、`center` 或 `end`,默认 `end`;胶囊在锚点矩形内按此水平对齐,并垂直居中。 |
|
||||
| `compact` | 可选布尔值;为 `true` 时停靠后的胶囊折叠为 ◈ 标记,悬停或聚焦后展开。 |
|
||||
| 键名 | `host.recovery` 表示整组恢复入口(胶囊或 toolbar 组合);`host.recovery.built-in` 与 `host.recovery.library` 表示两个独立按钮,只接受 toolbar 形态。同一份 `chrome.json` 只能二选一:声明了 `host.recovery` 就不能再声明独立按钮键,反之亦然。未知键或未开放控件会被拒绝,错误码为 `SKIN_CHROME_SLOT_INVALID`。 |
|
||||
| `anchor` | 必填,必须是 `.ws-skin-root` 内已存在的 `data-ws-part` 名称,或 1–8 个候选名称组成的数组(按页面/组件变体排列,重复项自动去重);宿主按顺序取第一个可见匹配,因此同一份声明可同时覆盖首页和语音页。每个候选名最长 240 字符,不能是 `host.*`,也不能是任何可信宿主部件(如 `app`、`voice.connection-status`、`auth.password.*`)。锚点不存在、`display:none`、`visibility:hidden`、完全透明、被裁剪、尺寸过小或大部分移出视口时都会回退。 |
|
||||
| `align` | 可选,`start`、`center` 或 `end`,默认 `end`;控件在锚点矩形内按此水平对齐,并垂直居中。 |
|
||||
| `compact` | 可选布尔值;为 `true` 时停靠后的胶囊折叠为 ◈ 标记,悬停或聚焦后展开。仅胶囊模式可用;`mode: "toolbar"` 与 `compact: true` 同时出现会被拒绝。 |
|
||||
| `mode` | 可选,`"capsule"` 或 `"toolbar"`。`host.recovery` 省略时保持历史默认 `"capsule"`(旧皮肤无需改动);`host.recovery.built-in` / `host.recovery.library` 省略时为 `"toolbar"`,且显式写 `"capsule"` 会被拒绝。模式必须显式声明,宿主不会从 `compact` 或其他字段推断。 |
|
||||
| `appearance` | 可选,`"label"`(默认)、`"icon"` 或 `"icon-and-label"`,只接受 toolbar 模式。`label` 保持旧文字按钮;`icon` 使用宿主 16px 图标、24px 宽按钮和零内边距;`icon-and-label` 同时显示图标和本地化文字。三种形态都保留 `aria-label` / `title`。胶囊只接受 `label`;未知值或胶囊中的图标形态会以 `SKIN_CHROME_SLOT_INVALID` 拒绝。 |
|
||||
|
||||
`anchor` 写的是宿主渲染后的完整部件名,而不是组件 id:
|
||||
|
||||
@@ -490,11 +494,11 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
- v3 组件中带 `part` 的节点:`skin.<page>.<componentId>.part-<part>`;按钮、链接、输入、`role="button"` 或绑定了用户事件的可交互节点会渲染为 `skin.<page>.<componentId>.control-part-<part>`。推荐在 surface 里放一个专门的非交互空节点并设置稳定的 `part`(例如 `skin.voice.harbor-dock.part-anchor`),避免名称随交互语义变化。
|
||||
- v4 运行时插件生成的节点:`skin.<page>.runtime_plugin_<pluginId>__<componentId>.part-<part>`(同样有 `control-` 变体)。插件 UI 与 `data-ws-skin-mount` 挂载点都位于 `.ws-skin-root` 内,因此也能作为锚点。
|
||||
|
||||
**这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。胶囊位于顶层,会挡住它下面的一切,因此宿主还会检查胶囊的占位(按观察到的最大尺寸计算,紧凑模式展开后的宽度也算在内)是否压到了可见的受保护控件(`PROTECTED_PART_IDS`,例如 `voice.audio-dock.microphone`、`voice.audio-dock.output`、`home.footer.clear`、`voice.connection-status.reconnect`);锚点的祖先容器(如包住专用锚点的 `voice.audio-dock`)不算,锚点自身只有在它是或包含可交互控件时才算。压到时同样回退。示例 `host-chrome-demo` 因此把胶囊靠 `start` 对齐在音频栏左侧的说明文字上,避开右侧的麦克风/输出按钮。锚点一旦不可用,胶囊立即回到默认左下角(仍在闭合 Shadow DOM 和顶层,皮肤无法遮挡或隐藏)。为避免闪烁,回退后需要连续 2 次检查都通过才会重新停靠;停靠期间约每 400 ms 复查一次,浮动态保持原来的 1 s 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。
|
||||
**这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。胶囊或 toolbar 按钮位于顶层,会挡住它下面的一切,因此宿主还会检查控件的占位(按观察到的最大尺寸计算,紧凑模式展开后的宽度也算在内)是否压到了可见的受保护控件(`PROTECTED_PART_IDS`,例如 `voice.audio-dock.microphone`、`voice.audio-dock.output`、`home.footer.clear`、`voice.connection-status.reconnect`);锚点的祖先容器(如包住专用锚点的 `voice.audio-dock`)不算,锚点自身只有在它是或包含可交互控件时才算。压到时同样回退。示例 `host-chrome-demo` 因此把胶囊靠 `start` 对齐在音频栏左侧的说明文字上,避开右侧的麦克风/输出按钮。锚点一旦不可用,胶囊立即回到默认左下角(仍在闭合 Shadow DOM 和顶层,皮肤无法遮挡或隐藏)。为避免闪烁,回退后需要连续 2 次检查都通过才会重新停靠;停靠期间约每 400 ms 复查一次,浮动态保持原来的 1 s 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。
|
||||
|
||||
**浮动位置的运行时避让。** 没有停靠(未声明 `slots`,或锚点回退)时,恢复胶囊默认在左下角;宿主约每 400 ms(以及每次点击后约 150 ms)检查一次它是否盖住了皮肤里可见、处于最上层的可交互控件(按钮、链接、输入框、`[tabindex]` 自定义按钮、iframe 等;禁用的“发送”按钮也算,透明度为 0 的不算;受保护部件权重最高,其次是打开的对话框/底部弹层里的控件;只因位于皮肤根 `app` 之内的普通按钮不算受保护)。盖住时,胶囊会换到左下、右下、左上、右上、左中、右中、底部居中、顶部居中里遮挡最少的位置,但不会换到鼠标最后所在的位置或当前聚焦的控件上;只有收起能至少让出一个控件时,才收成只显示 ◈ 的紧凑形态(悬停、聚焦或点按展开)。鼠标悬停(触屏上不算残留的悬停)或焦点在胶囊内时不会移动。为避免闪动:遮挡要持续约 250 ms 才移动,两次移动至少相隔 1 s,10 s 内移动超过 6 次就停在默认角落 10 s(期间若默认角落盖住了控件,最多再挪开一次,之后保持不动);判断某个控件是否被盖住时会“看穿”短暂出现的提示条(`app.toast`)和另一个宿主浮动控件,提示条暂时挡住的控件仍按存在计算,不会因此把那个角落误判为空闲;同一页面内,当前位置不遮挡时不会为了回到默认角落而移动(默认角落“看起来空”可能只是被模态对话框的遮罩或提示条暂时挡住);进入或离开语音页、切换皮肤时,宿主会在约 1.5 s 内跳过确认等待和最短间隔、连续复查几次,并在默认角落和当前位置都空闲(鼠标也不在那里)时回到默认角落,免得为上一屏选的位置盖住下一屏新出现的控件。位置计算和 CSS 一样计入 `env(safe-area-inset-*)`(刘海屏、底部手势条)。宿主自带的应用库悬浮按钮(皮肤没有提供 `voice.plugin-launcher` 挂载点时出现在右下角)使用同一套避让,两者也互相避开。这同样只是运行时行为,不新增任何 `skin.css` 编译期限制;皮肤作者无需为它做任何事,但如果希望胶囊固定在设计好的位置,仍建议用 `slots` 停靠。
|
||||
|
||||
**样式令牌**:皮肤可在皮肤根(`:root`)、锚点或锚点的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点(存在时)或活动皮肤根的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。没有声明 `slots` 的皮肤也能用这些令牌给浮动态胶囊换肤;锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。每个 `--skin-recovery-*` 都有全局回退 `--skin-host-<同名>`,`--skin-recovery-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。
|
||||
**样式令牌**:皮肤可在皮肤根(`:root`)、锚点或锚点的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点(存在时)或活动皮肤根的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。没有声明 `slots` 的皮肤也能用这些令牌给浮动态胶囊换肤;锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。每个 `--skin-recovery-*` 都有全局回退 `--skin-host-<同名>`,`--skin-recovery-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。这些胶囊令牌也是 toolbar 颜色的最终回退;toolbar 的圆角、内边距、高度和阴影使用下一节自己的默认值,不会继承胶囊的 999px 圆角或浮动阴影。
|
||||
|
||||
| 令牌 | 规则 |
|
||||
| --- | --- |
|
||||
@@ -512,6 +516,106 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
|
||||
**键盘快捷键**:`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)在停靠、浮动态和紧凑模式下行为一致:显示完整胶囊并聚焦第一个按钮,焦点离开胶囊后紧凑模式重新生效;它仍在捕获阶段处理,皮肤或插件的 `preventDefault()` 无法吞掉。
|
||||
|
||||
#### 工具栏模式:把恢复按钮并进皮肤顶栏(`mode: "toolbar"`)
|
||||
|
||||
默认的恢复入口是带胶囊壳的浮动/停靠胶囊。若皮肤顶栏已有自己的按钮风格,可以在 `chrome.json` 中显式声明 `mode: "toolbar"`,让宿主在锚点位置绘制**无胶囊壳的真实宿主按钮**。按钮仍由宿主创建、标注、聚焦和点击,位于闭合 Shadow DOM 的顶层;皮肤只提供锚点、`appearance` 形态声明和 `--skin-recovery-toolbar-*` 令牌,不能替换宿主图标、文案、顺序、点击处理或取得 DOM。`.ws-host-toolbar`、`data-ws-host-recovery-toolbar` 与 `data-ws-recovery-action` 都不是公开钩子,皮肤选择器引用它们会被拒绝。
|
||||
|
||||
两种声明方式互斥,同一份 `chrome.json` 只能选一种:
|
||||
|
||||
**组合式**(两个动作共用一个锚点,并排成一组,顺序为先「使用内置皮肤」、后「应用库」):
|
||||
|
||||
```json
|
||||
"slots": {
|
||||
"host.recovery": {
|
||||
"mode": "toolbar",
|
||||
"appearance": "icon",
|
||||
"anchor": ["home.header", "voice.header"],
|
||||
"align": "end"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**独立式**(每个动作有自己的锚点,可放在顶栏两侧或不同部件上):
|
||||
|
||||
```json
|
||||
"slots": {
|
||||
"host.recovery.built-in": {
|
||||
"mode": "toolbar",
|
||||
"appearance": "icon-and-label",
|
||||
"anchor": ["home.header-tools", "voice.header-actions"],
|
||||
"align": "end"
|
||||
},
|
||||
"host.recovery.library": {
|
||||
"mode": "toolbar",
|
||||
"appearance": "icon",
|
||||
"anchor": ["home.header-tools", "voice.header-actions"],
|
||||
"align": "start"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
上面只是示意:两个独立按钮若使用同一锚点,应选不同的 `align` 或不同锚点,否则会互相覆盖。
|
||||
|
||||
规则:
|
||||
|
||||
- `mode` 省略时,`host.recovery` 仍是 `capsule`,旧皮肤行为不变;独立按钮键省略时是 `toolbar`,显式写 `capsule` 会被拒绝。模式必须显式声明,宿主不会从 `compact` 或其他字段推断。
|
||||
- `compact` 只适用于胶囊;toolbar 配 `compact` 会被拒绝。toolbar 不会折叠成 ◈;`appearance` 省略时仍显示完整文字按钮。
|
||||
- `appearance: "icon"` 只改变 toolbar 的可见内容,不移除按钮的可访问名称。宿主图标为内联 SVG,`aria-hidden="true"`;按钮保留当前语言的 `aria-label`,`title` 仍说明动作/快捷键。`icon-and-label` 同时显示图标和文字。快捷键与失败回退始终使用完整文字胶囊,不受 toolbar 外观影响。
|
||||
- 组合式下「应用库」按钮只在应用库可用(已连接且插件会话就绪)时渲染;「使用内置皮肤」始终渲染。
|
||||
- 独立式下每个动作独立停靠:一个锚点失效只把该动作放回浮动胶囊,另一个仍留在工具栏;两个都失效时显示完整浮动胶囊。toolbar 模式下的胶囊永不折叠,因为它是兜底入口而不是设计目标。
|
||||
- 回退、抗抖动和复查节奏与胶囊相同:锚点失效立即回退;恢复后需连续 2 次检查通过才重新停靠;停靠时约 400 ms 复查,浮动时约 1 s。
|
||||
- 锚点候选数组按顺序取第一个可见项;页面切换、皮肤重载或锚点显隐后会重新解析,不要求重新绑定。
|
||||
- 快捷键 `Ctrl+Alt+Shift+R` / `⌘+⌥+⇧+R` 会隐藏工具栏并召唤完整胶囊;关闭(Escape 或焦点离开)后,锚点仍有效的 toolbar 自动恢复。快捷键仍在捕获阶段处理。
|
||||
- 按钮的最小命中高度、可见图标/文字、焦点环和指针/键盘操作都由宿主保证;皮肤不能通过选择器隐藏 toolbar、移除可访问名称或把按钮变成零尺寸。`appearance` 只能选择宿主提供的三种形态。
|
||||
|
||||
**应用库去重**:只要皮肤声明了 toolbar 形式的恢复入口(组合式的 `host.recovery`,或独立式的 `host.recovery.library`),并且应用库可用,宿主就把工具栏里的「应用库」按钮当作该页唯一的应用库入口,并隐藏普通的 `host.plugins.launcher`。即使锚点失效、入口退回浮动胶囊,启动器仍保持隐藏(胶囊继续提供应用库按钮),避免同一页出现两个入口;应用库不可用时启动器照常显示,工具栏也不渲染该按钮。这个去重只影响 toolbar 声明,不改变普通胶囊皮肤或内置皮肤。
|
||||
|
||||
**工具栏令牌**:皮肤在皮肤根、锚点或锚点祖先上声明下列普通变量;宿主从每个按钮当前锚点的计算样式读取、校验,再写入闭合 Shadow DOM。每个 `--skin-recovery-toolbar-*` 都有全局回退 `--skin-host-toolbar-*`,前者优先。组合式和独立式按钮共用同一组变量名;由于值按锚点继承,不同页面或不同锚点可以给同一变量不同的值。
|
||||
|
||||
| 令牌 | 默认与规则 |
|
||||
| --- | --- |
|
||||
| `--skin-recovery-toolbar-background` | 按钮背景。省略时沿用已解析的胶囊底色(`--skin-recovery-background` / `--skin-host-background` / 宿主白色)。完全透明(`transparent` 或 alpha 0)会保留;非零 alpha 仍按旧规则转为不透明 RGB。 |
|
||||
| `--skin-recovery-toolbar-foreground` | 图标/文字色。与不透明按钮背景的对比度必须 ≥ 4.5;背景透明时改与 `surface` 令牌或宿主采样的锚点/祖先不透明底色比较。整组颜色不可读时,背景和文字一起回退到已解析的胶囊配色。 |
|
||||
| `--skin-recovery-toolbar-border` | 边框色。完全不透明时与有效背景的对比度必须 ≥ 3,否则使用已解析的胶囊边框;完全透明边框有效。 |
|
||||
| `--skin-recovery-toolbar-hover-background` | 悬停背景,默认使用正常背景;宿主独立检查悬停后的文字对比度,不合格时回退到正常背景。 |
|
||||
| `--skin-recovery-toolbar-hover-border` | 悬停边框,默认使用正常边框;校验颜色语法,允许 Classic 的 subtle `#b8cfe8` 边缘,不强制 3:1。 |
|
||||
| `--skin-recovery-toolbar-surface` | 可选的完全不透明底色,仅用于透明按钮/悬停背景的文字对比度检查,不绘制按钮本身。优先级为 per-part、global、锚点/祖先计算背景采样、宿主白色。渐变或图片顶栏应显式提供该令牌。 |
|
||||
| `--skin-recovery-toolbar-radius` | 圆角,px 长度,限制 0–24,默认 6;胶囊的 999px 不会带入 toolbar。 |
|
||||
| `--skin-recovery-toolbar-font` | 字体族列表,规则与胶囊相同:只接受已安装字体或通用族名,皮肤 `@font-face`(包括 `ws-` 前缀)整项忽略。 |
|
||||
| `--skin-recovery-toolbar-font-size` | 字号,px,默认沿用当前尺寸档位的宿主字号(≥ 11/12/13 px),限制 11–20 px;不能低于宿主下限。 |
|
||||
| `--skin-recovery-toolbar-padding` | 一个或两个长度值(`上下 左右`,或一个值表示四边相同),默认 `6px 12px`,每个方向限制 0–48 px;接受 px 和无单位 `0`。`appearance: "icon"` 时宿主强制零内边距。 |
|
||||
| `--skin-recovery-toolbar-height` | 最小高度,px。省略时保持当前尺寸档位的 28/32/36 px;显式值限制 22–72 px,因此 Classic 22px 仅在 toolbar 生效。胶囊仍保持 28/32/36 px。 |
|
||||
| `--skin-recovery-toolbar-shadow` | `none` 或单个简单 `box-shadow`(2–4 个 px 偏移/尺寸加一个颜色,最长 160 字符),默认 `none`。`url()`、`var()`、多个阴影和额外声明一律忽略为 `none`,胶囊阴影不会带入。 |
|
||||
| `--skin-recovery-toolbar-gap` | 组合式两个宿主按钮之间的间距,px,默认 4,限制 0–16;Classic 可设 `1px`。独立式各自只有一个按钮。 |
|
||||
| `--skin-recovery-toolbar-icon-size` | 宿主图标边长,px,默认 16,限制 12–24。`appearance: "icon"` 时按钮宽度为 `max(24px, icon-size + 8px)`,16px 图标对应 Classic 24px 按钮。 |
|
||||
|
||||
无效、不可读的颜色,越界的字号/高度/内边距/间距/图标尺寸,皮肤字体和非法阴影都只会回退到可见的宿主默认值,不会隐藏按钮。toolbar 文案由宿主按当前界面语言本地化,长文本换行而不是裁掉;`prefers-reduced-motion` 下同样没有过渡。
|
||||
|
||||
**Classic 麦克风按钮对齐示例**(22px 高、透明底、1px 边框、2px 圆角、11px 字号、16px 图标、1px 组间距):
|
||||
|
||||
```css
|
||||
:root {
|
||||
--skin-host-toolbar-background: transparent;
|
||||
--skin-host-toolbar-foreground: #1a1a1a;
|
||||
--skin-host-toolbar-border: transparent;
|
||||
--skin-host-toolbar-hover-background: #eaf2fd;
|
||||
--skin-host-toolbar-hover-border: #b8cfe8;
|
||||
--skin-host-toolbar-radius: 2px;
|
||||
--skin-host-toolbar-font-size: 11px;
|
||||
--skin-host-toolbar-padding: 0 4px;
|
||||
--skin-host-toolbar-height: 22px;
|
||||
--skin-host-toolbar-gap: 1px;
|
||||
--skin-host-toolbar-icon-size: 16px;
|
||||
--skin-host-toolbar-surface: #ffffff;
|
||||
}
|
||||
```
|
||||
|
||||
配合 `"appearance": "icon"` 使用。`surface` 只参与可读性计算;顶栏实际不是白色时应改成真实不透明底色。图标按钮的零内边距由宿主强制执行,`padding` 令牌仍用于 `label` / `icon-and-label`。
|
||||
|
||||
**旧 slots 兼容**:旧包里的 `{ "anchor": ..., "align": ..., "compact": ... }` 没有 `mode`,仍按胶囊停靠,行为不变;`chrome.json` 的其它字段(`visibleParts`、`hiddenParts`、`icons`)不受影响。只有显式写 `mode: "toolbar"` 才会切换形态。
|
||||
|
||||
**不影响其它宿主控件**:工具栏令牌只作用于恢复按钮。授权对话框(`--skin-permission-*`)和皮肤加载失败横幅(`--skin-load-recovery-*`)继续使用各自令牌与默认外观;本节的变量不会改变它们。
|
||||
|
||||
#### 受保护控件的主题化
|
||||
|
||||
28 个受保护部件里,`host.recovery`、`app.skin-load-recovery` 和授权对话框由宿主在闭合 Shadow DOM 中绘制,`host.permission` 目前没有渲染点;其余 25 个都渲染在 `.ws-skin-root` 内(服务器/频道密码弹窗也在根内,不是 `Teleport`)。开放皮肤(schemaVersion 3/4)可以直接用 `skin.css` 给它们换肤;宿主只保留「不能隐藏 / 不能移出视口 / 不能禁用 / 使用内置皮肤的路径不能被切断」四条底线。
|
||||
@@ -628,7 +732,28 @@ v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根
|
||||
| `visibleParts` | 可选,最多 32 项,只能是本文档「可隐藏的装饰部件」白名单中的宿主装饰名。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认隐藏;皮肤需在这里明确列出才会渲染。省略该字段时装饰保持隐藏,即使包内已有 `hiddenParts` 或 `icons`(宿主不再根据生成的 CSS 猜测旧包意图)。内置皮肤没有 `chrome.json`,因此始终不显示这些装饰。实例级 `hiddenParts` 与皮肤 `hiddenParts` 仍然优先。 |
|
||||
| `hiddenParts` | 最多 32 项,只能是本文档「可隐藏的装饰部件」白名单中的名字;编译成 `display:none` 并写入皮肤 CSS。可信控件、恢复入口与必要音频路径(如 `voice.audio-dock`、`voice.connection-status`、`home.footer.clear`)永不允许出现,皮肤 CSS 直接隐藏它们也会被拒绝。 |
|
||||
| `icons` | 最多 16 项;键必须是上表的图标槽名;值必须是包内 `assets/icons/<文件名>` 的位图相对路径。 |
|
||||
| `slots` | 可选,最多 8 项;键名目前只能是 `host.recovery`,值只能包含 `anchor`、`align`、`compact`。详见上文「将恢复入口停靠到皮肤布局」。未知键、指向 `host.*` 或可信宿主部件的锚点会被拒绝。 |
|
||||
| `slots` | 可选,最多 8 项;键名只能是 `host.recovery`(整组)或 `host.recovery.built-in` / `host.recovery.library`(独立 toolbar 按钮),两种写法互斥。值只能包含 `anchor`、`align`、`compact`、`mode`、`appearance`;`anchor` 可以是单个部件名或最多 8 个候选名的数组。详见上文「将恢复入口停靠到皮肤布局」与「工具栏模式」。未知键、指向 `host.*` 或可信宿主部件的锚点、`toolbar` 配 `compact`、非法 `appearance` 或胶囊中的图标形态都会被拒绝。 |
|
||||
|
||||
工具栏形态只需在 `host.recovery` 上写 `"mode": "toolbar"`(两个按钮共用一个锚点):
|
||||
|
||||
```json
|
||||
"slots": {
|
||||
"host.recovery": {
|
||||
"mode": "toolbar",
|
||||
"anchor": ["home.header", "voice.header"],
|
||||
"align": "end"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
也可以改用独立按钮键,让两个动作各自停靠:
|
||||
|
||||
```json
|
||||
"slots": {
|
||||
"host.recovery.built-in": { "anchor": ["home.header-tools", "voice.header-actions"], "align": "end" },
|
||||
"host.recovery.library": { "anchor": ["home.header-tools", "voice.header-actions"], "align": "start" }
|
||||
}
|
||||
```
|
||||
|
||||
图标文件约定:仅 PNG / JPG / WebP / AVIF / GIF(**不接受 SVG**),路径必须位于 `assets/icons/` 下且只有一层文件名(不允许 `..`、绝对路径、`\`、`%`、空格或外部 URL)。导入端与服务端登记时都会校验路径、文件是否存在、MIME 是否为位图、单张不超过 64 KiB、总量不超过 512 KiB。宿主把位图编译进皮肤 CSS 的 `background-image`,并隐藏槽内的矢量图形;`url()` 仍走包内资源解析,无法引用外部地址。
|
||||
|
||||
@@ -765,6 +890,6 @@ CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删
|
||||
|
||||
用户首次访问公开页面时,由宿主统一询问是否允许当前实例的第三方皮肤和功能插件使用已公开的频道/成员/聊天等上下文;不包含连接凭据。不再逐个皮肤弹窗确认。选择按浏览器源(协议、域名、端口)保存,旧版本的逐包授权记录不会自动替代这次选择。管理员对应用的审核与信任仍单独保留。
|
||||
|
||||
未作选择或拒绝时,仅可使用固定三款官方皮肤:`builtin.light`、`builtin.dark`、`community.illusia-voice`;KAAK 即使随包分发也不在免授权名单中,其他第三方皮肤及功能插件入口隐藏。缓存、直接激活、进行中的加载也必须经过同一授权检查,不能仅过滤菜单。皮肤菜单末尾的“授权”可以随时修改选择。撤回时立即退回内置皮肤、停止第三方皮肤组件/worker,并关闭与撤销当前功能应用会话;服务端由管理员启用的后台应用不因此停机。
|
||||
未作选择或拒绝时,仅可使用固定三款官方皮肤:`builtin.light`、`builtin.dark`、`community.illusia-voice`;KAAK 和 Classic 即使随包分发也不在免授权名单中,其他第三方皮肤及功能插件入口隐藏。缓存、直接激活、进行中的加载也必须经过同一授权检查,不能仅过滤菜单。皮肤菜单末尾的“授权”可以随时修改选择。撤回时立即退回内置皮肤、停止第三方皮肤组件/worker,并关闭与撤销当前功能应用会话;服务端由管理员启用的后台应用不因此停机。
|
||||
|
||||
清单权限、数据投影、宿主动作校验和 Wasm 文件摘要校验继续保留,统一授权不是扩大皮肤 API 的理由。作者不应再自行增加重复授权弹窗。原文中的逐包授权记录与 SHA-256 绑定描述指内部校验记录,其创建必须在实例授权允许之后(或固定官方皮肤之内)。
|
||||
@@ -0,0 +1,116 @@
|
||||
# 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(默认 auto)和 jitter 上限。
|
||||
- `src/server/turn-credentials.ts`:按 coturn `use-auth-secret` 生成短期凭证。
|
||||
- `src/server/voice-bridge.ts`:仅当直接相邻代理位于
|
||||
`WEBSPEAK_TRUSTED_PROXIES` 中时,才根据 `cf-ray`、`cf-connecting-ip` 或
|
||||
`cdn-loop` 判定 Cloudflare。直连客户端注入这些头不会改变 profile。
|
||||
`WEBSPEAK_ASSUME_CLOUDFLARE=1` 可覆盖反向代理清掉这些头的部署。
|
||||
- Cloudflare 请求不再把 Tunnel `Host` 当作 ICE 媒体地址。未配置公网媒体
|
||||
地址且没有 TURN 时返回 `NO_MEDIA_PATH`,浏览器使用兼容传输。公网媒体
|
||||
地址可以直接填 IP 字面量,不要求域名或证书。
|
||||
- 已下发 WebRTC 后建连或传输失败会自动恢复 PCM/Opus over WebSocket 的
|
||||
上下行兼容音频,页面留在当前 TeamSpeak/WebSocket 会话;上行需要已有
|
||||
麦克风权限。横幅继续使用 `WEBRTC_FAILED`,并保留“重新连接 WebRTC”。
|
||||
- 第一次直连失败且配置了 TURN 时,自动做一次 relay-only 重试(约 3 秒后);
|
||||
兼容音频在重试期间继续播放。第二次失败才显示 `WEBRTC_FAILED`。
|
||||
- “重新连接 WebRTC”只重试 WebRTC,不调用整段连接流程、不新建语音
|
||||
WebSocket;手动重试会恢复配置的直连优先策略并清零自动重试计数。
|
||||
- 重连期间保持兼容收发,等 `onReady` 后才停止兼容音频并清除失败横幅和
|
||||
按钮,避免双路音频或切换静音。
|
||||
- `src/server/webrtc-audio.ts` 与 `web/src/voice/webrtc-transport.ts`:浏览器
|
||||
和网关使用完整 ICE 列表;relay 尝试的 ICE/answer/连接超时分别收敛为
|
||||
4/6/10 秒,直连为 6/8/15 秒;直连收到 host/srflx/prflx 后提前 300ms
|
||||
结束收集,减少隧道下的无效等待。
|
||||
- 已从 werift 源码确认 `turns:` 使用 TLS 控制连接;未做真实 coturn 端到端
|
||||
联调。
|
||||
|
||||
### 兼容模式音频
|
||||
|
||||
- `legacy` 保留旧播放窗口、解码器重建、裸 PCM、4 帧 mixer 队列和每包
|
||||
marker;只有显式 `legacy` 或非 Cloudflare 请求使用。
|
||||
- `adaptive` 使用 v3 批量下行:服务端按 20/40ms tick 把多个说话人的包合并
|
||||
为一条二进制消息(`0xF3` 头 + `audioStartMs` + per-speaker seq),消息数
|
||||
从“每包一条”降到“每 tick 一条”。旧前端不发 `audioCaps` 时服务端保持
|
||||
v2 逐包格式。
|
||||
- 迟到 tick 不再把整段积压压成一个时间戳:batcher 按原始 tick 分组,每组
|
||||
单独带音频时钟,客户端才能用 p95 抖动估计发现隧道停顿。
|
||||
- `web/src/voice/jitter-buffer.ts` 使用 2 秒 / 100 样本窗口的 p95,目标
|
||||
`60 + p95`,下限 80ms、上限由 `audioJitterMaxMs` 控制;快升 +40ms/次,
|
||||
慢降 -2ms/2s。
|
||||
- `web/src/voice/remote-playback.ts` 用音频时钟做锚点,保留 `AudioDecoder`;
|
||||
seq 缺口 1–8 时用 PLC 隐藏最多 3 帧,领先 60ms 跳帧,领先 300ms 重锚,
|
||||
落后 20ms 插一帧。解码队列硬上限 12,只有极深积压才丢最新帧。
|
||||
- `web/src/voice/opus-uplink.ts` 使用 WebCodecs Opus,24kbps、
|
||||
`packetlossperc=10`、`useinbandfec=true`;不支持或失败时回退 PCM。
|
||||
- 服务端接受 40ms(3840 字节)PCM,拆成两个 20ms 帧后分别 encode/pacer;
|
||||
40ms 帧消耗两个 rate token,不能借此翻倍上行速率。
|
||||
- Safari/Firefox 的 Opus 行为未逐台真机验证。
|
||||
|
||||
### 管理台与持久化
|
||||
|
||||
- 管理台“服务器 → 语音”提供 profile、Opus、jitter 上限、TURN REST 配置,
|
||||
以及“兼容模式调优”:20/40ms 兼容模式帧长、自动 TURN 重试、强制 Cloudflare
|
||||
入口识别。
|
||||
- 非空控制台值覆盖环境变量;未修改字段保持数据库 `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=1
|
||||
WEBSPEAK_VOICE_FRAME_MS=20
|
||||
WEBSPEAK_VOICE_AUTO_RELAY_RETRY=1
|
||||
WEBSPEAK_TURN_REST_URLS='turn:203.0.113.10:3478?transport=udp,turn:203.0.113.10:3478?transport=tcp'
|
||||
WEBSPEAK_TURN_REST_SECRET='<replace-with-demo-secret>'
|
||||
WEBSPEAK_TURN_REST_TTL_SECONDS=21600
|
||||
```
|
||||
|
||||
公网媒体地址示例使用 `192.0.2.10`;实际部署必须替换为可直接通过 UDP 到达的
|
||||
地址。Cloudflare Tunnel 不转发 WebRTC UDP,也不能作为媒体地址。
|
||||
|
||||
## 数据库与回滚
|
||||
|
||||
- 语音覆盖配置写入现有 metadata 表,数据库保持 schema 13;未设置的值继承
|
||||
环境变量,TURN 密钥继续加密保存。
|
||||
- 0.3.3 会忽略并保留这些元数据,可以在自动更新健康检查失败后直接恢复旧代码。
|
||||
- 恢复非 Cloudflare 旧音频行为:选择 `legacy`,或确保没有控制台覆盖后设置
|
||||
`WEBSPEAK_VOICE_PROFILE=legacy`。
|
||||
- 关闭兼容模式 Opus:取消控制台选项或设置 `WEBSPEAK_VOICE_OPUS_WS=0`。
|
||||
- 回退 v3 批量下行:回退前端构建,让浏览器不再发送 `audioCaps`;新服务端
|
||||
会自动走 v2。`WEBSPEAK_VOICE_FRAME_MS=20` 只影响批量 tick,不会回退协议。
|
||||
- 关闭 TURN:清空 TURN URL/移除密钥,或删除对应环境变量。
|
||||
|
||||
## 验证边界
|
||||
|
||||
- coturn/cloudflared 模板未在真实目标网络端到端联调。
|
||||
- 公网 IP 的 `40000–40099/UDP` 入站、`443/TCP` 是否可分配给 coturn,需按
|
||||
实际云安全组和主机防火墙验证。
|
||||
- TURN 的 UDP/TCP/TLS、relay 端口和凭证一致性仍需在目标网络验证。
|
||||
- Safari/Firefox WebCodecs Opus 与真实浏览器 jitter 表现仍需设备测试。
|
||||
- 自动化测试和构建结果以本次审查的测试记录为准;历史报告中的通过数量
|
||||
不应被视为本次独立复跑结果。
|
||||
@@ -0,0 +1,106 @@
|
||||
# Host chrome toolbar example
|
||||
|
||||
A minimal schema v3 open skin that docks the trusted recovery entry into the page header as Classic-aligned, host-owned icon buttons instead of the floating capsule shell. It is the smallest reference for `chrome.json` `mode: "toolbar"`, `appearance`, page-specific anchor candidates, transparent toolbar tokens, application-library de-duplication and the floating-capsule fallback.
|
||||
|
||||
- Source: [host-chrome-toolbar](./host-chrome-toolbar/)
|
||||
- Importable package: [host-chrome-toolbar.wskin](./host-chrome-toolbar.wskin)
|
||||
- Author: WebSpeak Community
|
||||
- Shared component and permission rules: [skin development guide](../SKIN_DEVELOPMENT.md)
|
||||
- Host chrome and toolbar contract: [skin development guide](../SKIN_DEVELOPMENT.md) (see the `chrome.json#slots` and toolbar-mode sections)
|
||||
|
||||
## Package layout
|
||||
|
||||
```text
|
||||
host-chrome-toolbar/
|
||||
manifest.json # schema v3, version 1.1.2, minAppVersion 0.3.4-dev.0, author WebSpeak Community
|
||||
chrome.json # one grouped toolbar slot with a home/voice anchor list
|
||||
skin.css # light page theme, Classic toolbar tokens and header space
|
||||
```
|
||||
|
||||
This package requires WebSpeak 0.3.4-dev.0 or later. Released WebSpeak 0.3.3 and earlier do not accept `mode`, `appearance`, or anchor candidate arrays, so importing it there cannot provide toolbar-mode behavior. Older slots without those fields remain valid and keep their capsule presentation.
|
||||
|
||||
`skin.css` uses only public `data-ws-part` hooks and sets `--skin-host-toolbar-*` / `--skin-recovery-toolbar-*` variables. It never targets the host toolbar DOM, the recovery capsule, the authorization dialog or the load-failure banner.
|
||||
|
||||
## Grouped declaration
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"slots": {
|
||||
"host.recovery": {
|
||||
"mode": "toolbar",
|
||||
"appearance": "icon",
|
||||
"anchor": ["home.header", "voice.header"],
|
||||
"align": "end"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `mode: "toolbar"` asks the host to render two real host buttons without the capsule shell.
|
||||
- `appearance: "icon"` selects the host-owned 16px built-in-skin and application-library SVGs. Each button is 24px wide, has zero padding and keeps its localized `aria-label` and `title`.
|
||||
- The anchor list covers both pages; the host picks the first visible one and re-resolves it after a page switch. A missing or hidden anchor returns the complete, visible floating capsule.
|
||||
- While the library is available, the host hides the ordinary application-library launcher so the page keeps exactly one library entry. The fallback capsule keeps that entry when the anchor fails.
|
||||
- The host owns the icons, labels, click handlers, focus behaviour, shortcut handling and fallback. The skin only supplies the anchor, appearance and token values.
|
||||
- Old slots without `mode` keep the capsule presentation; this example opts in explicitly.
|
||||
|
||||
## Classic tokens
|
||||
|
||||
```css
|
||||
:root {
|
||||
--skin-host-toolbar-background: transparent;
|
||||
--skin-host-toolbar-foreground: #1a1a1a;
|
||||
--skin-host-toolbar-border: transparent;
|
||||
--skin-host-toolbar-hover-background: #eaf2fd;
|
||||
--skin-host-toolbar-hover-border: #b8cfe8;
|
||||
--skin-host-toolbar-surface: #f4f7fb;
|
||||
--skin-host-toolbar-radius: 2px;
|
||||
--skin-host-toolbar-font-size: 11px;
|
||||
--skin-host-toolbar-padding: 0 4px;
|
||||
--skin-host-toolbar-height: 22px;
|
||||
--skin-host-toolbar-gap: 1px;
|
||||
--skin-host-toolbar-icon-size: 16px;
|
||||
}
|
||||
```
|
||||
|
||||
This produces 22px-high buttons, a transparent normal surface, a 1px transparent border, 2px corners, 11px type, 16px icons and a 1px gap. Hover uses `#eaf2fd` with a `#b8cfe8` edge. `surface` is not painted; it tells the host which opaque colour to use for contrast checks. Set it to the real header colour when adapting the example.
|
||||
|
||||
The package also declares an opaque `--skin-recovery-*` capsule palette. Capsule mode keeps its historical 28/32/36px size floors, full text labels and fixed `#fff7ed` built-in action; toolbar tokens never shrink or restyle that escape hatch.
|
||||
|
||||
## Independent declaration
|
||||
|
||||
Use the per-action keys when the two actions need different anchors or appearances. Do not declare them together with `host.recovery`.
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"slots": {
|
||||
"host.recovery.built-in": {
|
||||
"mode": "toolbar",
|
||||
"appearance": "icon-and-label",
|
||||
"anchor": ["home.header-tools", "voice.header-actions"],
|
||||
"align": "end"
|
||||
},
|
||||
"host.recovery.library": {
|
||||
"mode": "toolbar",
|
||||
"appearance": "icon",
|
||||
"anchor": ["home.header-tools", "voice.header-actions"],
|
||||
"align": "start"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`appearance` defaults to `"label"` for backward compatibility. The accepted toolbar values are `"label"`, `"icon"` and `"icon-and-label"`; unknown values and icon appearances in capsule mode are rejected with `SKIN_CHROME_SLOT_INVALID`.
|
||||
|
||||
## Trying it
|
||||
|
||||
1. Build or import [host-chrome-toolbar.wskin](./host-chrome-toolbar.wskin) in a local WebSpeak instance.
|
||||
2. Allow the third-party skin when the host asks.
|
||||
3. Connect to **Demo Server**, join **Demo Lobby**, and check the header as **Demo User**.
|
||||
4. Confirm the two 24px host icons appear at the end of the home and voice headers, remain transparent at rest, use the Classic hover colours, and open the built-in-skin and application-library actions.
|
||||
5. Remove or hide the anchor in the page inspector; the complete floating capsule should appear at a free corner. Restore the anchor; the toolbar should re-dock after the anti-flap check.
|
||||
6. Press `Ctrl+Alt+Shift+R` (`⌘+⌥+⇧+R` on macOS); the toolbar hides, the complete full-text capsule appears and focuses its first button. Press Escape to return to the toolbar.
|
||||
7. Check a narrow viewport and all five interface languages. Icon-only names must remain available to assistive technology, and the fallback capsule must keep readable localized labels.
|
||||
|
||||
The example contains no server addresses, member names, chat contents or other real instance data. Public descriptions use only the Demo Server / Demo Lobby / Demo User placeholders.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"slots": {
|
||||
"host.recovery": {
|
||||
"mode": "toolbar",
|
||||
"appearance": "icon",
|
||||
"anchor": ["home.header", "voice.header"],
|
||||
"align": "end"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"schemaVersion": 3,
|
||||
"packageType": "open-skin",
|
||||
"id": "community.host-chrome-toolbar",
|
||||
"name": "Host Chrome Toolbar",
|
||||
"version": "1.1.2",
|
||||
"author": "WebSpeak Community",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "Minimal open skin that docks Classic-aligned host-owned recovery icons into the page header.",
|
||||
"entry": "skin.css",
|
||||
"chrome": "chrome.json",
|
||||
"minAppVersion": "0.3.4-dev.0"
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/* Host chrome toolbar demo — v3 open skin (schemaVersion 3).
|
||||
The host owns the recovery structure, icons, labels, focus and actions.
|
||||
This package only declares an anchor, appearance and validated tokens. */
|
||||
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--skin-demo-surface: #f4f7fb;
|
||||
--skin-demo-foreground: #1a1a1a;
|
||||
--skin-demo-border: #d5dee8;
|
||||
--skin-demo-accent: #1d4ed8;
|
||||
|
||||
/* Classic microphone-button geometry and colours. `surface` is the opaque
|
||||
colour used to check text contrast behind the transparent toolbar. */
|
||||
--skin-host-toolbar-background: transparent;
|
||||
--skin-host-toolbar-foreground: #1a1a1a;
|
||||
--skin-host-toolbar-border: transparent;
|
||||
--skin-host-toolbar-hover-background: #eaf2fd;
|
||||
--skin-host-toolbar-hover-border: #b8cfe8;
|
||||
--skin-host-toolbar-surface: #f4f7fb;
|
||||
--skin-host-toolbar-radius: 2px;
|
||||
--skin-host-toolbar-font: Tahoma, "Segoe UI", sans-serif;
|
||||
--skin-host-toolbar-font-size: 11px;
|
||||
--skin-host-toolbar-padding: 0 4px;
|
||||
--skin-host-toolbar-height: 22px;
|
||||
--skin-host-toolbar-gap: 1px;
|
||||
--skin-host-toolbar-icon-size: 16px;
|
||||
--skin-host-toolbar-shadow: none;
|
||||
|
||||
/* The fallback and shortcut capsule remains opaque and full-text. */
|
||||
--skin-recovery-background: #ffffff;
|
||||
--skin-recovery-foreground: #1a1a1a;
|
||||
--skin-recovery-border: #9db6b2;
|
||||
--skin-recovery-accent: #1d4ed8;
|
||||
--skin-recovery-radius: 8px;
|
||||
}
|
||||
|
||||
[data-ws-page] {
|
||||
color: #1a1a1a;
|
||||
background: #ffffff;
|
||||
font-family: Tahoma, "Segoe UI", "Microsoft YaHei", sans-serif;
|
||||
}
|
||||
|
||||
[data-ws-part="home.header"],
|
||||
[data-ws-part="voice.header"] {
|
||||
background: #f4f7fb;
|
||||
border-bottom: 1px solid var(--skin-demo-border);
|
||||
color: var(--skin-demo-foreground);
|
||||
}
|
||||
|
||||
/* Keep the two 24px icon buttons clear of ordinary header actions. */
|
||||
[data-ws-part="home.header"],
|
||||
[data-ws-part="voice.header"] {
|
||||
padding-right: 72px;
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card"],
|
||||
[data-ws-part="home.content"],
|
||||
[data-ws-part="voice.workspace"],
|
||||
[data-ws-part="voice.content"] {
|
||||
color: var(--skin-demo-foreground);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card"] {
|
||||
background: #ffffff;
|
||||
border: 1px solid var(--skin-demo-border);
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 16px 40px #10203012;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] {
|
||||
background: #f4f7fb;
|
||||
border-top: 1px solid var(--skin-demo-border);
|
||||
}
|
||||
|
||||
[data-ws-part="home.footer"] { color: #52606d; }
|
||||
[data-ws-part="home.footer.clear"] { color: var(--skin-demo-accent); }
|
||||
Binary file not shown.
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"visibleParts": [],
|
||||
"hiddenParts": ["host.plugins.launcher"],
|
||||
"slots": {
|
||||
"host.recovery": {
|
||||
"mode": "toolbar",
|
||||
"appearance": "icon",
|
||||
"anchor": [
|
||||
"skin.home.ts3-home-console.part-ts-recovery-slot",
|
||||
"skin.voice.ts3-voice-console.part-ts-recovery-slot"
|
||||
],
|
||||
"align": "end"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,908 @@
|
||||
{
|
||||
"schemaVersion": 3,
|
||||
"components": [
|
||||
{
|
||||
"id": "ts3-home-console",
|
||||
"name": "TS3 Legacy connection console",
|
||||
"page": "home",
|
||||
"mode": "surface",
|
||||
"accessibleName": "WebSpeak connection console",
|
||||
"permissions": [
|
||||
"ui.surface.replace",
|
||||
"session.status.read",
|
||||
"voice.connect"
|
||||
],
|
||||
"actions": {},
|
||||
"root": {
|
||||
"tag": "main",
|
||||
"part": "ts-home",
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "ts-home",
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "ts-toolbar",
|
||||
"className": "ts-toolbar",
|
||||
"attributes": {
|
||||
"role": "toolbar",
|
||||
"aria-label": "{{skin.messages.toolbar.homeNote}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"widget": "home.social-links",
|
||||
"part": "ts-tool-admin",
|
||||
"className": "ts-tool-admin",
|
||||
"options": { "communityLinks": false }
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-toolbar-brand",
|
||||
"children": [
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-toolbar-mark",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
}
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-toolbar-note",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.toolbar.homeNote}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-toolbar-spacer",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
}
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"part": "ts-recovery-slot",
|
||||
"className": "ts-recovery-slot",
|
||||
"attributes": { "aria-hidden": "true" }
|
||||
},
|
||||
{
|
||||
"widget": "app.language-switcher",
|
||||
"part": "ts-language",
|
||||
"className": "ts-language"
|
||||
},
|
||||
{
|
||||
"widget": "app.skin-switcher",
|
||||
"part": "ts-skin",
|
||||
"className": "ts-skin"
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-toolbar-edition",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.shell.edition}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "ts-home-body",
|
||||
"className": "ts-home-body",
|
||||
"children": [
|
||||
{
|
||||
"tag": "section",
|
||||
"part": "ts-home-main",
|
||||
"className": "ts-home-main",
|
||||
"attributes": {
|
||||
"aria-label": "{{skin.messages.home.windowTitle}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "ts-connect-window",
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "ts-window-titlebar",
|
||||
"children": [
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-window-icon",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
}
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-window-title",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.home.windowTitle}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-window-edition",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.shell.edition}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "ts-window-body",
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "ts-home-reconnect",
|
||||
"className": "ts-conn-strip ts-home-reconnect",
|
||||
"children": [
|
||||
{
|
||||
"widget": "voice.connection-status",
|
||||
"part": "ts-home-connection-status",
|
||||
"className": "ts-home-connection-status"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "p",
|
||||
"className": "ts-home-lead",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.home.lead}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "fieldset",
|
||||
"className": "ts-group-box",
|
||||
"children": [
|
||||
{
|
||||
"tag": "legend",
|
||||
"className": "ts-group-legend",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.home.panelLabel}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"widget": "home.connection-form",
|
||||
"part": "ts-connection-form",
|
||||
"className": "ts-connection-form"
|
||||
},
|
||||
{
|
||||
"widget": "home.identity-provider",
|
||||
"part": "ts-home-identity-provider",
|
||||
"className": "ts-home-identity-provider",
|
||||
"options": {
|
||||
"identityProviderId": "myts",
|
||||
"identityProviderLabel": "myts"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"widget": "home.connection-status",
|
||||
"part": "ts-home-connection",
|
||||
"className": "ts-home-connection"
|
||||
},
|
||||
{
|
||||
"widget": "home.server-announcement",
|
||||
"part": "ts-home-announcement",
|
||||
"className": "ts-home-announcement"
|
||||
},
|
||||
{
|
||||
"widget": "home.visitor-count",
|
||||
"part": "ts-home-visitors",
|
||||
"className": "ts-home-visitors"
|
||||
},
|
||||
{
|
||||
"tag": "p",
|
||||
"className": "ts-home-notice",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.home.notice}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "footer",
|
||||
"part": "ts-statusbar",
|
||||
"className": "ts-statusbar",
|
||||
"children": [
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-status-led",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
}
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-status-text",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.home.footer}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-status-spacer",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
}
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-status-edition",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.footer.skin}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ts3-voice-console",
|
||||
"name": "TS3 Legacy voice workspace",
|
||||
"page": "voice",
|
||||
"mode": "surface",
|
||||
"accessibleName": "WebSpeak voice workspace",
|
||||
"permissions": [
|
||||
"ui.surface.replace",
|
||||
"session.status.read",
|
||||
"servers.quickList.read",
|
||||
"servers.quickList.switch",
|
||||
"session.channels.read",
|
||||
"session.members.read",
|
||||
"session.memberAvatars.read",
|
||||
"session.channel.join",
|
||||
"chat.channel.read",
|
||||
"chat.channel.send",
|
||||
"audio.status.read",
|
||||
"audio.microphone.control",
|
||||
"audio.output.control",
|
||||
"voice.disconnect",
|
||||
"voice.screenShare.read",
|
||||
"voice.screenShare.control",
|
||||
"voice.whisper.status.read",
|
||||
"voice.whisper.control",
|
||||
"voice.connect",
|
||||
"audio.settings.open"
|
||||
],
|
||||
"actions": {
|
||||
"open-audio-settings": {
|
||||
"type": "audio.openSettings",
|
||||
"args": {}
|
||||
},
|
||||
"toggle-noise-suppression": {
|
||||
"type": "audio.toggleNoiseSuppression",
|
||||
"args": {}
|
||||
},
|
||||
"toggle-accompaniment": {
|
||||
"type": "audio.toggleAccompaniment",
|
||||
"args": {}
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"tag": "main",
|
||||
"part": "ts-voice",
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "ts-app",
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "ts-toolbar",
|
||||
"className": "ts-toolbar",
|
||||
"attributes": {
|
||||
"role": "toolbar",
|
||||
"aria-label": "{{skin.messages.toolbar.voiceLabel}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "ts-toolgroup",
|
||||
"children": [
|
||||
{
|
||||
"widget": "voice.server-switcher",
|
||||
"part": "ts-tool-server",
|
||||
"className": "ts-tool-server"
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-tool-sep",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
}
|
||||
},
|
||||
{
|
||||
"widget": "voice.connection-controls",
|
||||
"part": "ts-tool-connection",
|
||||
"className": "ts-tool-connection"
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-tool-sep",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
}
|
||||
},
|
||||
{
|
||||
"widget": "voice.audio-controls",
|
||||
"part": "ts-tool-audio",
|
||||
"className": "ts-tool-audio"
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "ts-tool-mobile-audio",
|
||||
"className": "ts-tool-mobile-audio",
|
||||
"attributes": {
|
||||
"role": "group",
|
||||
"aria-label": "{{skin.messages.toolbar.mobileAudio}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"tag": "button",
|
||||
"part": "ts-tool-noise",
|
||||
"className": "ts-mtool ts-mtool-noise",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "{{skin.messages.toolbar.noise}}",
|
||||
"title": "{{skin.messages.toolbar.noise}}",
|
||||
"aria-pressed": "{{audio.status.noiseSuppressionEnabled}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "toggle-noise-suppression"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-mtool-glyph",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "button",
|
||||
"part": "ts-tool-accompaniment",
|
||||
"className": "ts-mtool ts-mtool-accompaniment",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "{{skin.messages.toolbar.accompaniment}}",
|
||||
"title": "{{skin.messages.toolbar.accompaniment}}",
|
||||
"aria-pressed": "{{audio.status.accompanimentActive}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "toggle-accompaniment"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-mtool-glyph",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "button",
|
||||
"part": "ts-tool-audio-settings",
|
||||
"className": "ts-mtool ts-mtool-settings",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "{{skin.messages.toolbar.audioSettings}}",
|
||||
"title": "{{skin.messages.toolbar.audioSettings}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "open-audio-settings"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-mtool-glyph",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-tool-sep",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
}
|
||||
},
|
||||
{
|
||||
"widget": "voice.screen-share-start",
|
||||
"part": "ts-tool-share",
|
||||
"className": "ts-tool-share"
|
||||
},
|
||||
{
|
||||
"widget": "voice.whisper-controls",
|
||||
"part": "ts-tool-whisper",
|
||||
"className": "ts-tool-whisper"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-toolbar-spacer",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
}
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "ts-toolgroup ts-toolgroup-end",
|
||||
"children": [
|
||||
{
|
||||
"tag": "span",
|
||||
"part": "ts-recovery-slot",
|
||||
"className": "ts-recovery-slot",
|
||||
"attributes": { "aria-hidden": "true" }
|
||||
},
|
||||
{
|
||||
"widget": "home.social-links",
|
||||
"part": "ts-tool-admin",
|
||||
"className": "ts-tool-admin",
|
||||
"options": { "communityLinks": false }
|
||||
},
|
||||
{
|
||||
"widget": "app.language-switcher",
|
||||
"part": "ts-language",
|
||||
"className": "ts-language"
|
||||
},
|
||||
{
|
||||
"widget": "app.skin-switcher",
|
||||
"part": "ts-skin",
|
||||
"className": "ts-skin"
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-toolbar-edition",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.shell.edition}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "ts-conn-strip",
|
||||
"className": "ts-conn-strip",
|
||||
"children": [
|
||||
{
|
||||
"widget": "voice.connection-status",
|
||||
"part": "ts-connection-status",
|
||||
"className": "ts-connection-status"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "ts-workspace",
|
||||
"className": "ts-workspace",
|
||||
"children": [
|
||||
{
|
||||
"tag": "aside",
|
||||
"part": "ts-tree",
|
||||
"className": "ts-tree",
|
||||
"attributes": {
|
||||
"aria-label": "{{skin.messages.tree.heading}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "ts-pane-caption",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.tree.heading}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"widget": "voice.server-header",
|
||||
"part": "ts-server-header",
|
||||
"className": "ts-server-header"
|
||||
},
|
||||
{
|
||||
"widget": "voice.channel-tree",
|
||||
"part": "ts-channel-tree",
|
||||
"className": "ts-channel-tree",
|
||||
"options": {
|
||||
"layout": "default",
|
||||
"memberActions": true,
|
||||
"memberDragDrop": true
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "ts-right",
|
||||
"className": "ts-right",
|
||||
"children": [
|
||||
{
|
||||
"tag": "section",
|
||||
"part": "ts-info",
|
||||
"className": "ts-info",
|
||||
"attributes": {
|
||||
"aria-label": "{{skin.messages.info.heading}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "ts-info-heading",
|
||||
"children": [
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-info-icon",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
}
|
||||
},
|
||||
{
|
||||
"tag": "h1",
|
||||
"className": "ts-info-title",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.info.heading}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "ts-info-facts",
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "ts-fact-row",
|
||||
"children": [
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-fact-label",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.info.nickname}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-fact-value",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{session.status.userName}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "ts-fact-row",
|
||||
"children": [
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-fact-label",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.info.channel}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-fact-value",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{session.status.channelName}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "ts-fact-row",
|
||||
"children": [
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-fact-label",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.info.server}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-fact-value",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{session.status.serverLabel}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "ts-fact-row",
|
||||
"children": [
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-fact-label",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.info.state}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-fact-value",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{session.status.connectionState}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "ts-info-voice",
|
||||
"className": "ts-info-voice",
|
||||
"children": [
|
||||
{
|
||||
"widget": "voice.performance-panel",
|
||||
"part": "ts-performance",
|
||||
"className": "ts-performance",
|
||||
"options": {
|
||||
"screenShare": false
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"widget": "voice.screen-share-player",
|
||||
"part": "ts-screen-share",
|
||||
"className": "ts-screen-share"
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-watermark",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.watermark}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"widget": "voice.server-banner",
|
||||
"part": "ts-server-banner",
|
||||
"className": "ts-server-banner"
|
||||
},
|
||||
{
|
||||
"tag": "section",
|
||||
"part": "ts-log",
|
||||
"className": "ts-log",
|
||||
"attributes": {
|
||||
"aria-label": "{{skin.messages.log.heading}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "ts-log-heading",
|
||||
"children": [
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-log-title",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.log.heading}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "small",
|
||||
"className": "ts-log-notice",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.log.notice}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"widget": "voice.chat-panel",
|
||||
"part": "ts-chat",
|
||||
"className": "ts-chat"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "footer",
|
||||
"part": "ts-statusbar",
|
||||
"className": "ts-statusbar",
|
||||
"children": [
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-status-led",
|
||||
"attributes": {
|
||||
"aria-hidden": "true",
|
||||
"data-state": "{{session.status.connectionState}}"
|
||||
}
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-status-text",
|
||||
"children": [
|
||||
{
|
||||
"tag": "span",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.status.connected}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-status-name",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{session.status.userName}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.status.on}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-status-server",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{session.status.serverLabel}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"when": {
|
||||
"path": "session.status.connected",
|
||||
"equals": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-status-text ts-status-offline",
|
||||
"when": {
|
||||
"path": "session.status.connected",
|
||||
"equals": false
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-status-state",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{session.status.connectionState}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-status-sep",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"text": "·"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-status-server",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{session.status.serverLabel}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-status-spacer",
|
||||
"attributes": {
|
||||
"aria-hidden": "true"
|
||||
}
|
||||
},
|
||||
{
|
||||
"widget": "voice.disconnect-control",
|
||||
"part": "ts-disconnect",
|
||||
"className": "ts-disconnect"
|
||||
},
|
||||
{
|
||||
"tag": "span",
|
||||
"className": "ts-status-edition",
|
||||
"children": [
|
||||
{
|
||||
"text": "{{skin.messages.footer.skin}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
{
|
||||
"defaultLocale": "en",
|
||||
"locales": {
|
||||
"en": {
|
||||
"home": {
|
||||
"brandName": "WebSpeak",
|
||||
"title": "Connect to a",
|
||||
"titleAccent": "voice server",
|
||||
"description": "Open a TeamSpeak channel from your browser. Your gateway manages the connection and your identity.",
|
||||
"welcomeTitle": "Connection console",
|
||||
"welcomeDescription": "Choose a server, set your nickname, and join the room."
|
||||
},
|
||||
"messages": {
|
||||
"shell.brand": "WebSpeak",
|
||||
"shell.edition": "Classic",
|
||||
"toolbar.homeNote": "Connection console",
|
||||
"toolbar.voiceLabel": "Voice controls",
|
||||
"tree.heading": "CHANNELS",
|
||||
"info.heading": "SERVER INFORMATION",
|
||||
"info.nickname": "Nickname",
|
||||
"nicknamePlaceholder": "e.g. Demo User",
|
||||
"info.channel": "Channel",
|
||||
"info.server": "Server",
|
||||
"info.state": "State",
|
||||
"watermark": "WebSpeak",
|
||||
"log.heading": "SERVER LOG",
|
||||
"log.notice": "Conversation and session events appear below.",
|
||||
"status.connected": "Connected as",
|
||||
"status.on": "on",
|
||||
"footer.status": "Audio controls remain available in every layout",
|
||||
"footer.skin": "Classic",
|
||||
"home.windowTitle": "Connect to Server",
|
||||
"home.lead": "Enter a server address and a nickname to join a voice channel. Your gateway manages the connection and your identity.",
|
||||
"home.panelLabel": "SERVER CONNECTION",
|
||||
"home.notice": "Connection details and identity are handled by WebSpeak.",
|
||||
"home.footer": "WebSpeak gateway · Classic skin · Not affiliated with TeamSpeak",
|
||||
"toolbar.audioSettings": "Audio settings",
|
||||
"toolbar.noise": "Noise suppression",
|
||||
"toolbar.accompaniment": "Share accompaniment",
|
||||
"toolbar.mobileAudio": "Phone audio tools"
|
||||
}
|
||||
},
|
||||
"zh-CN": {
|
||||
"home": {
|
||||
"brandName": "WebSpeak",
|
||||
"title": "连接到",
|
||||
"titleAccent": "语音服务器",
|
||||
"description": "在浏览器中打开 TeamSpeak 频道。网关负责连接与身份管理。",
|
||||
"welcomeTitle": "连接控制台",
|
||||
"welcomeDescription": "选择服务器、设置昵称,然后加入房间。"
|
||||
},
|
||||
"messages": {
|
||||
"shell.brand": "WebSpeak",
|
||||
"shell.edition": "Classic",
|
||||
"toolbar.homeNote": "连接控制台",
|
||||
"toolbar.voiceLabel": "语音控制",
|
||||
"tree.heading": "频道",
|
||||
"info.heading": "服务器信息",
|
||||
"info.nickname": "昵称",
|
||||
"nicknamePlaceholder": "例如:Demo User",
|
||||
"info.channel": "频道",
|
||||
"info.server": "服务器",
|
||||
"info.state": "状态",
|
||||
"watermark": "WebSpeak",
|
||||
"log.heading": "服务器日志",
|
||||
"log.notice": "会话与连接事件显示在下方的聊天面板中。",
|
||||
"status.connected": "已连接为",
|
||||
"status.on": "于",
|
||||
"footer.status": "任何布局下音频控制均可用",
|
||||
"footer.skin": "Classic",
|
||||
"home.windowTitle": "连接到服务器",
|
||||
"home.lead": "输入服务器地址与昵称,加入语音频道。网关负责连接与身份管理。",
|
||||
"home.panelLabel": "服务器连接",
|
||||
"home.notice": "连接信息与身份由 WebSpeak 管理。",
|
||||
"home.footer": "WebSpeak 网关 · Classic 皮肤 · 与 TeamSpeak 官方无关联",
|
||||
"toolbar.audioSettings": "音频设置",
|
||||
"toolbar.noise": "降噪",
|
||||
"toolbar.accompaniment": "共享伴奏",
|
||||
"toolbar.mobileAudio": "手机音频工具"
|
||||
}
|
||||
},
|
||||
"de": {
|
||||
"home": {
|
||||
"brandName": "WebSpeak",
|
||||
"title": "Mit einem",
|
||||
"titleAccent": "Sprachserver verbinden",
|
||||
"description": "Öffne einen TeamSpeak-Kanal im Browser. Dein Gateway verwaltet Verbindung und Identität.",
|
||||
"welcomeTitle": "Verbindungskonsole",
|
||||
"welcomeDescription": "Server wählen, Spitznamen festlegen und dem Raum beitreten."
|
||||
},
|
||||
"messages": {
|
||||
"shell.brand": "WebSpeak",
|
||||
"shell.edition": "Classic",
|
||||
"toolbar.homeNote": "Verbindungskonsole",
|
||||
"toolbar.voiceLabel": "Sprachsteuerung",
|
||||
"tree.heading": "KANÄLE",
|
||||
"info.heading": "SERVERINFORMATIONEN",
|
||||
"info.nickname": "Spitzname",
|
||||
"nicknamePlaceholder": "z. B. Demo User",
|
||||
"info.channel": "Kanal",
|
||||
"info.server": "Server",
|
||||
"info.state": "Status",
|
||||
"watermark": "WebSpeak",
|
||||
"log.heading": "SERVERPROTOKOLL",
|
||||
"log.notice": "Gesprächs- und Sitzungsereignisse erscheinen unten im Chat.",
|
||||
"status.connected": "Verbunden als",
|
||||
"status.on": "auf",
|
||||
"footer.status": "Audiosteuerung in jedem Layout erreichbar",
|
||||
"footer.skin": "Classic",
|
||||
"home.windowTitle": "Mit Server verbinden",
|
||||
"home.lead": "Serveradresse und Spitznamen eingeben, um einem Sprachkanal beizutreten. Das Gateway verwaltet Verbindung und Identität.",
|
||||
"home.panelLabel": "SERVERVERBINDUNG",
|
||||
"home.notice": "Verbindungsdaten und Identität werden von WebSpeak verwaltet.",
|
||||
"home.footer": "WebSpeak Gateway · Design Classic · Nicht mit TeamSpeak verbunden",
|
||||
"toolbar.audioSettings": "Audioeinstellungen",
|
||||
"toolbar.noise": "Rauschunterdrückung",
|
||||
"toolbar.accompaniment": "Begleitung teilen",
|
||||
"toolbar.mobileAudio": "Audio-Werkzeuge"
|
||||
}
|
||||
},
|
||||
"ru": {
|
||||
"home": {
|
||||
"brandName": "WebSpeak",
|
||||
"title": "Подключение к",
|
||||
"titleAccent": "голосовому серверу",
|
||||
"description": "Откройте канал TeamSpeak в браузере. Шлюз управляет соединением и вашей учётной записью.",
|
||||
"welcomeTitle": "Консоль подключения",
|
||||
"welcomeDescription": "Выберите сервер, укажите имя и войдите в комнату."
|
||||
},
|
||||
"messages": {
|
||||
"shell.brand": "WebSpeak",
|
||||
"shell.edition": "Classic",
|
||||
"toolbar.homeNote": "Консоль подключения",
|
||||
"toolbar.voiceLabel": "Управление звуком",
|
||||
"tree.heading": "КАНАЛЫ",
|
||||
"info.heading": "СВЕДЕНИЯ О СЕРВЕРЕ",
|
||||
"info.nickname": "Имя",
|
||||
"nicknamePlaceholder": "например, Demo User",
|
||||
"info.channel": "Канал",
|
||||
"info.server": "Сервер",
|
||||
"info.state": "Состояние",
|
||||
"watermark": "WebSpeak",
|
||||
"log.heading": "ЖУРНАЛ СЕРВЕРА",
|
||||
"log.notice": "События беседы и сессии отображаются ниже в чате.",
|
||||
"status.connected": "Подключён как",
|
||||
"status.on": "на",
|
||||
"footer.status": "Управление звуком доступно в любой раскладке",
|
||||
"footer.skin": "Classic",
|
||||
"home.windowTitle": "Подключение к серверу",
|
||||
"home.lead": "Введите адрес сервера и имя, чтобы войти в голосовой канал. Шлюз управляет соединением и учётной записью.",
|
||||
"home.panelLabel": "ПОДКЛЮЧЕНИЕ К СЕРВЕРУ",
|
||||
"home.notice": "Данные подключения и удостоверение обрабатывает WebSpeak.",
|
||||
"home.footer": "Шлюз WebSpeak · Оформление Classic · Не связано с TeamSpeak",
|
||||
"toolbar.audioSettings": "Настройки звука",
|
||||
"toolbar.noise": "Шумоподавление",
|
||||
"toolbar.accompaniment": "Поделиться аккомпанементом",
|
||||
"toolbar.mobileAudio": "Аудиоинструменты"
|
||||
}
|
||||
},
|
||||
"ja-JP": {
|
||||
"home": {
|
||||
"brandName": "WebSpeak",
|
||||
"title": "音声サーバーに",
|
||||
"titleAccent": "接続",
|
||||
"description": "ブラウザーから TeamSpeak チャンネルを開きます。接続と認証はゲートウェイが管理します。",
|
||||
"welcomeTitle": "接続コンソール",
|
||||
"welcomeDescription": "サーバーを選び、名前を入力してルームに参加します。"
|
||||
},
|
||||
"messages": {
|
||||
"shell.brand": "WebSpeak",
|
||||
"shell.edition": "Classic",
|
||||
"toolbar.homeNote": "接続コンソール",
|
||||
"toolbar.voiceLabel": "音声操作",
|
||||
"tree.heading": "チャンネル",
|
||||
"info.heading": "サーバー情報",
|
||||
"info.nickname": "ニックネーム",
|
||||
"nicknamePlaceholder": "例: Demo User",
|
||||
"info.channel": "チャンネル",
|
||||
"info.server": "サーバー",
|
||||
"info.state": "状態",
|
||||
"watermark": "WebSpeak",
|
||||
"log.heading": "サーバーログ",
|
||||
"log.notice": "会話とセッションのイベントは下のチャットに表示されます。",
|
||||
"status.connected": "接続中:",
|
||||
"status.on": "サーバー",
|
||||
"footer.status": "どのレイアウトでも音声操作は利用できます",
|
||||
"footer.skin": "Classic",
|
||||
"home.windowTitle": "サーバーに接続",
|
||||
"home.lead": "サーバーアドレスとニックネームを入力して音声チャンネルに参加します。接続と認証はゲートウェイが管理します。",
|
||||
"home.panelLabel": "サーバー接続",
|
||||
"home.notice": "接続情報と認証は WebSpeak が管理します。",
|
||||
"home.footer": "WebSpeak ゲートウェイ · Classic スキン · TeamSpeak 公式とは無関係",
|
||||
"toolbar.audioSettings": "オーディオ設定",
|
||||
"toolbar.noise": "ノイズ抑制",
|
||||
"toolbar.accompaniment": "伴奏を共有",
|
||||
"toolbar.mobileAudio": "オーディオツール"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"schemaVersion": 3,
|
||||
"packageType": "open-skin",
|
||||
"id": "community.ts3-classic-console",
|
||||
"name": "Classic",
|
||||
"version": "4.1.16",
|
||||
"author": "WebSpeak Community",
|
||||
"license": "CC-BY-4.0",
|
||||
"description": "A community visual homage to the classic TeamSpeak 3 light desktop client for both the connection page and the voice workspace: a classic group-box connect window, a compact icon toolbar, a full-height server tree with members, a SERVER INFORMATION facts pane and a bottom SERVER LOG with chat.",
|
||||
"entry": "skin.css",
|
||||
"components": "components.json",
|
||||
"content": "content.json",
|
||||
"chrome": "chrome.json",
|
||||
"minAppVersion": "0.3.3"
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "webspeak-android-gateway",
|
||||
"version": "0.3.3",
|
||||
"version": "0.3.4-dev.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-android-gateway",
|
||||
"version": "0.3.3",
|
||||
"version": "0.3.4-dev.0",
|
||||
"dependencies": {
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.23",
|
||||
"express": "^4.21.2",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-android-gateway",
|
||||
"version": "0.3.3",
|
||||
"version": "0.3.4-dev.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.cjs",
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.3.3",
|
||||
"version": "0.3.4-dev.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.3.3",
|
||||
"version": "0.3.4-dev.0",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.3.3",
|
||||
"version": "0.3.4-dev.0",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
@@ -11,12 +11,13 @@
|
||||
"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/voice/noise-suppression.test.ts web/src/voice/microphone-test.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/turn-credentials.test.ts src/server/voice-ice-config.test.ts src/server/audio-pacer.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/voice-ice.test.ts src/shared/voice-profile.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/jitter-buffer.test.ts web/test/remote-playback.test.ts web/test/opus-uplink.test.ts web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs web/src/services/host-recovery-presentation.test.ts web/test/opus-uplink-browser.test.mjs src/shared/voice-audio.test.ts src/server/downlink-batcher.test.ts",
|
||||
"verify": "npm test && npm run build && npm run web:build",
|
||||
"skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
|
||||
"skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs",
|
||||
"skin:host-chrome:build": "node web/scripts/build-host-chrome-demo-skin.mjs",
|
||||
"skin:kaak:build": "node web/scripts/build-kaak-voice-skin.mjs",
|
||||
"skin:classic:build": "node web/scripts/build-classic-skin.mjs",
|
||||
"skin:illusia:build": "node web/scripts/build-illusia-voice-skin.mjs",
|
||||
"start": "node dist/index.js",
|
||||
"web:dev": "cd web && npx vite --host",
|
||||
|
||||
@@ -615,6 +615,16 @@ 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"),
|
||||
voiceDownlinkFrameMs: body.voiceDownlinkFrameMs === 20 || body.voiceDownlinkFrameMs === 40 ? body.voiceDownlinkFrameMs : undefined,
|
||||
voiceAssumeCloudflare: typeof body.voiceAssumeCloudflare === "boolean" ? body.voiceAssumeCloudflare : undefined,
|
||||
voiceAutoRelayRetry: typeof body.voiceAutoRelayRetry === "boolean" ? body.voiceAutoRelayRetry : undefined,
|
||||
relaySettingsAction: readRelaySettingsAction(body.relaySettingsAction),
|
||||
relayEnabled: body.relayEnabled === true,
|
||||
relayName: typeof body.relayName === "string" ? body.relayName.slice(0, 80) : undefined,
|
||||
|
||||
+149
-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,15 @@ 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,
|
||||
voiceDownlinkFrameMs: settings.voiceDownlinkFrameMs ?? this.voiceIceDefaults.downlinkFrameMs,
|
||||
voiceAssumeCloudflare: settings.voiceAssumeCloudflare ?? this.voiceIceDefaults.assumeCloudflare,
|
||||
voiceAutoRelayRetry: settings.voiceAutoRelayRetry ?? this.voiceIceDefaults.autoRelayRetry,
|
||||
relayConfigured: settings.relayConfigured,
|
||||
relayEnabled: settings.relayEnabled,
|
||||
relayName: settings.relayName,
|
||||
@@ -166,6 +181,46 @@ 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,
|
||||
downlinkFrameMs: settings.voiceDownlinkFrameMs ?? this.voiceIceDefaults.downlinkFrameMs,
|
||||
assumeCloudflare: settings.voiceAssumeCloudflare ?? this.voiceIceDefaults.assumeCloudflare,
|
||||
autoRelayRetry: settings.voiceAutoRelayRetry ?? this.voiceIceDefaults.autoRelayRetry,
|
||||
};
|
||||
}
|
||||
|
||||
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 +475,72 @@ 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`);
|
||||
}
|
||||
const voiceDownlinkFrameMs = input.voiceDownlinkFrameMs === undefined ? current.voiceDownlinkFrameMs : input.voiceDownlinkFrameMs;
|
||||
if (voiceDownlinkFrameMs !== null && voiceDownlinkFrameMs !== 20 && voiceDownlinkFrameMs !== 40) {
|
||||
throw new AdminInputError("INVALID_VOICE_FRAME_MS", "Compatibility frame must be 20 or 40 ms");
|
||||
}
|
||||
const voiceAssumeCloudflare = input.voiceAssumeCloudflare === undefined ? current.voiceAssumeCloudflare : input.voiceAssumeCloudflare;
|
||||
if (voiceAssumeCloudflare !== null && typeof voiceAssumeCloudflare !== "boolean") {
|
||||
throw new AdminInputError("INVALID_VOICE_ASSUME_CLOUDFLARE", "Assume-Cloudflare must be a boolean");
|
||||
}
|
||||
const voiceAutoRelayRetry = input.voiceAutoRelayRetry === undefined ? current.voiceAutoRelayRetry : input.voiceAutoRelayRetry;
|
||||
if (voiceAutoRelayRetry !== null && typeof voiceAutoRelayRetry !== "boolean") {
|
||||
throw new AdminInputError("INVALID_VOICE_AUTO_RELAY_RETRY", "Automatic relay retry must be a boolean");
|
||||
}
|
||||
let turnSecret = "";
|
||||
if (voiceTurnSecretEncrypted === null) {
|
||||
turnSecret = this.voiceIceDefaults.turnRest?.secret ?? "";
|
||||
} 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 +610,15 @@ export class AdminService {
|
||||
webRtcPublicHost, webRtcIpv6Enabled, webRtcStunServer,
|
||||
webRtcUdpStart,
|
||||
webRtcUdpEnd,
|
||||
voiceProfile,
|
||||
voiceTurnUrls,
|
||||
voiceTurnSecretEncrypted,
|
||||
voiceTurnTtlSeconds,
|
||||
voiceOpusWs,
|
||||
voiceJitterMaxMs,
|
||||
voiceDownlinkFrameMs,
|
||||
voiceAssumeCloudflare,
|
||||
voiceAutoRelayRetry,
|
||||
relayConfigured,
|
||||
relayEnabled,
|
||||
relayName,
|
||||
@@ -615,6 +745,15 @@ 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,
|
||||
voiceDownlinkFrameMs: settings.voiceDownlinkFrameMs,
|
||||
voiceAssumeCloudflare: settings.voiceAssumeCloudflare,
|
||||
voiceAutoRelayRetry: settings.voiceAutoRelayRetry,
|
||||
relayConfigured: settings.relayConfigured,
|
||||
relayEnabled: settings.relayEnabled,
|
||||
relayName: settings.relayName,
|
||||
@@ -647,6 +786,15 @@ 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,
|
||||
voiceDownlinkFrameMs: current.voiceDownlinkFrameMs,
|
||||
voiceAssumeCloudflare: current.voiceAssumeCloudflare,
|
||||
voiceAutoRelayRetry: current.voiceAutoRelayRetry,
|
||||
relayConfigured: current.relayConfigured,
|
||||
relayEnabled: current.relayEnabled,
|
||||
relayName: current.relayName,
|
||||
|
||||
@@ -98,6 +98,17 @@ test("the bundled KAAK skin can be selected as the instance default without a cu
|
||||
assert.deepEqual(await registry.list(), []);
|
||||
});
|
||||
|
||||
test("the bundled Classic skin can be selected as the instance default without a custom installation", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-classic-default-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
|
||||
await registry.setDefaultSkin("community.ts3-classic-console");
|
||||
|
||||
assert.equal(await registry.getDefaultSkinId(), "community.ts3-classic-console");
|
||||
assert.deepEqual(await registry.list(), []);
|
||||
});
|
||||
|
||||
test("server accepts validated declarative v2 layouts and rejects permissions or unregistered components", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-v2-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
@@ -384,11 +395,11 @@ test("skin registry rejects path traversal and mismatched local ZIP headers", as
|
||||
assert.deepEqual(await registry.list(), []);
|
||||
});
|
||||
|
||||
test("the four bundled skins cannot be replaced or removed through the registry", async (context) => {
|
||||
test("the five bundled skins cannot be replaced or removed through the registry", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-builtins-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
for (const id of ["builtin.light", "builtin.dark", "community.illusia-voice", "community.kaak-voice"]) {
|
||||
for (const id of ["builtin.light", "builtin.dark", "community.illusia-voice", "community.kaak-voice", "community.ts3-classic-console"]) {
|
||||
await assert.rejects(registry.save(Buffer.alloc(22), id), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
|
||||
await assert.rejects(registry.remove(id), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
|
||||
await assert.rejects(registry.setEnabled(id, false), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
|
||||
|
||||
@@ -31,7 +31,7 @@ const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
|
||||
const MAX_FONT_BYTES = 4 * 1024 * 1024;
|
||||
const MAX_SKINS = 50;
|
||||
const MAX_TOTAL_ARCHIVES = 200 * 1024 * 1024;
|
||||
export const BUILTIN_SKIN_IDS = ["builtin.light", "builtin.dark", "community.illusia-voice", "community.kaak-voice"] as const;
|
||||
export const BUILTIN_SKIN_IDS = ["builtin.light", "builtin.dark", "community.illusia-voice", "community.kaak-voice", "community.ts3-classic-console"] as const;
|
||||
const BUILTIN_SKIN_ID_SET = new Set<string>(BUILTIN_SKIN_IDS);
|
||||
const EOCD_SIGNATURE = 0x06054b50;
|
||||
const CENTRAL_SIGNATURE = 0x02014b50;
|
||||
|
||||
+10
-4
@@ -27,12 +27,18 @@ function parseIndex(value: unknown): { id: string; repository: string }[] {
|
||||
const root = record(value);
|
||||
if (root.schemaVersion !== 1 || !Array.isArray(root.skins) || root.skins.length > 50) return fail("SKIN_STORE_INVALID");
|
||||
const seen = new Set<string>();
|
||||
return root.skins.map(item => {
|
||||
const sources: { id: string; repository: string }[] = [];
|
||||
for (const item of root.skins) {
|
||||
const entry = record(item);
|
||||
if (typeof entry.id !== "string" || !ID.test(entry.id) || isBuiltinSkinId(entry.id) || entry.id.startsWith("builtin.") || seen.has(entry.id)) return fail("SKIN_STORE_INVALID");
|
||||
if (typeof entry.id !== "string" || !ID.test(entry.id) || seen.has(entry.id)) return fail("SKIN_STORE_INVALID");
|
||||
seen.add(entry.id);
|
||||
return { id: entry.id, repository: skinRepository(entry.repository) };
|
||||
});
|
||||
// Skins that ship with the client are not installable from the store. Skip
|
||||
// such an index entry instead of rejecting the whole index, so an index
|
||||
// that still lists a newly bundled skin keeps working for every other skin.
|
||||
if (isBuiltinSkinId(entry.id) || entry.id.startsWith("builtin.")) continue;
|
||||
sources.push({ id: entry.id, repository: skinRepository(entry.repository) });
|
||||
}
|
||||
return sources;
|
||||
}
|
||||
|
||||
function parseMetadata(value: unknown, id: string): SkinStoreMetadata {
|
||||
|
||||
@@ -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),
|
||||
});
|
||||
|
||||
@@ -7,6 +7,39 @@ import { DatabaseSync } from "node:sqlite";
|
||||
import { encryptSecret, decryptSecret } from "../security/secret-crypto.js";
|
||||
import { DATABASE_SCHEMA_VERSION, WebSpeakDatabase } from "./database.js";
|
||||
|
||||
test("voice overrides preserve schema 13 and survive an old binary updating ordinary settings", t => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-voice-rollback-"));
|
||||
const filename = path.join(directory, "webspeak.db");
|
||||
t.after(() => rmSync(directory, { recursive: true, force: true }));
|
||||
const database = new WebSpeakDatabase(filename);
|
||||
const encrypted = encryptSecret("turn-test-secret-value", Buffer.alloc(32, 7), "webspeak:voice-turn-rest-secret:v1");
|
||||
database.updateSettings({ ...database.getSettings(), voiceProfile: "adaptive", voiceTurnUrls: "turn:turn.example.com:3478",
|
||||
voiceTurnSecretEncrypted: encrypted, voiceTurnTtlSeconds: 3600, voiceOpusWs: true, voiceJitterMaxMs: 200,
|
||||
voiceDownlinkFrameMs: 40, voiceAssumeCloudflare: true, voiceAutoRelayRetry: false });
|
||||
database.close();
|
||||
const legacy = new DatabaseSync(filename);
|
||||
try {
|
||||
const version = legacy.prepare("PRAGMA user_version").get() as { user_version: number };
|
||||
assert.equal(version.user_version, 13, "0.3.3 rejects any schema version above 13");
|
||||
assert.equal((legacy.prepare("PRAGMA table_info(settings)").all() as { name: string }[]).some(row => row.name.startsWith("voice_")), false);
|
||||
legacy.prepare("UPDATE settings SET site_name = ? WHERE id = 1").run("Updated by old binary");
|
||||
} finally { legacy.close(); }
|
||||
const reopened = new WebSpeakDatabase(filename);
|
||||
try {
|
||||
const settings = reopened.getSettings();
|
||||
assert.equal(settings.siteName, "Updated by old binary");
|
||||
assert.equal(settings.voiceProfile, "adaptive");
|
||||
assert.equal(settings.voiceTurnSecretEncrypted, encrypted);
|
||||
assert.equal(settings.voiceOpusWs, true);
|
||||
assert.equal(settings.voiceJitterMaxMs, 200);
|
||||
assert.equal(settings.voiceDownlinkFrameMs, 40);
|
||||
assert.equal(settings.voiceAssumeCloudflare, true);
|
||||
assert.equal(settings.voiceAutoRelayRetry, false);
|
||||
reopened.setMeta("voice_settings_v1", "invalid-json");
|
||||
assert.equal(reopened.getSettings().voiceProfile, null);
|
||||
} finally { reopened.close(); }
|
||||
});
|
||||
|
||||
test("relay voice endpoint is stored by the current database migration", (context) => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-relay-db-"));
|
||||
const database = new WebSpeakDatabase(path.join(directory, "webspeak.sqlite"));
|
||||
|
||||
@@ -5,8 +5,10 @@ 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;
|
||||
const VOICE_SETTINGS_META_KEY = "voice_settings_v1";
|
||||
export type AccessMode = "fixed" | "open";
|
||||
|
||||
export interface PersistedSettings {
|
||||
@@ -31,6 +33,16 @@ 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;
|
||||
voiceDownlinkFrameMs: 20 | 40 | null;
|
||||
voiceAssumeCloudflare: boolean | null;
|
||||
voiceAutoRelayRetry: boolean | null;
|
||||
relayConfigured: boolean;
|
||||
relayEnabled: boolean;
|
||||
relayName: string;
|
||||
@@ -58,6 +70,15 @@ 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;
|
||||
voiceDownlinkFrameMs?: 20 | 40 | null;
|
||||
voiceAssumeCloudflare?: boolean | null;
|
||||
voiceAutoRelayRetry?: boolean | null;
|
||||
relayConfigured: boolean;
|
||||
relayEnabled: boolean;
|
||||
relayName: string;
|
||||
@@ -247,6 +268,7 @@ export class WebSpeakDatabase {
|
||||
|
||||
getSettings(): PersistedSettings {
|
||||
const row = this.database.prepare("SELECT * FROM settings WHERE id = 1").get() as SettingsRow;
|
||||
const voice = this.readVoiceSettings();
|
||||
return {
|
||||
siteName: row.site_name,
|
||||
welcomeText: row.welcome_text,
|
||||
@@ -269,6 +291,7 @@ export class WebSpeakDatabase {
|
||||
webRtcStunServer: row.webrtc_stun_server,
|
||||
webRtcUdpStart: row.webrtc_udp_start,
|
||||
webRtcUdpEnd: row.webrtc_udp_end,
|
||||
...voice,
|
||||
relayConfigured: row.relay_configured === 1,
|
||||
relayEnabled: row.relay_enabled === 1,
|
||||
relayName: row.relay_name,
|
||||
@@ -757,6 +780,30 @@ export class WebSpeakDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/** Optional settings must survive a code-only rollback to the 0.3.3 schema. */
|
||||
private readVoiceSettings(): Pick<PersistedSettings, "voiceProfile" | "voiceTurnUrls" | "voiceTurnSecretEncrypted" | "voiceTurnTtlSeconds" | "voiceOpusWs" | "voiceJitterMaxMs" | "voiceDownlinkFrameMs" | "voiceAssumeCloudflare" | "voiceAutoRelayRetry"> {
|
||||
let value: Record<string, unknown> = {};
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(this.getMeta(VOICE_SETTINGS_META_KEY) ?? "{}");
|
||||
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) value = parsed as Record<string, unknown>;
|
||||
} catch { /* A malformed optional value inherits the deployment defaults. */ }
|
||||
return {
|
||||
voiceProfile: value.voiceProfile === "legacy" || value.voiceProfile === "adaptive" || value.voiceProfile === "auto"
|
||||
? value.voiceProfile : null,
|
||||
voiceTurnUrls: typeof value.voiceTurnUrls === "string" ? value.voiceTurnUrls : null,
|
||||
voiceTurnSecretEncrypted: typeof value.voiceTurnSecretEncrypted === "string" ? value.voiceTurnSecretEncrypted : null,
|
||||
voiceTurnTtlSeconds: Number.isInteger(value.voiceTurnTtlSeconds) && Number(value.voiceTurnTtlSeconds) >= 300 && Number(value.voiceTurnTtlSeconds) <= 86400
|
||||
? Number(value.voiceTurnTtlSeconds) : null,
|
||||
voiceOpusWs: typeof value.voiceOpusWs === "boolean" ? value.voiceOpusWs : null,
|
||||
voiceJitterMaxMs: Number.isInteger(value.voiceJitterMaxMs) && Number(value.voiceJitterMaxMs) >= 80 && Number(value.voiceJitterMaxMs) <= 500
|
||||
? Number(value.voiceJitterMaxMs) : null,
|
||||
voiceDownlinkFrameMs: value.voiceDownlinkFrameMs === 20 || value.voiceDownlinkFrameMs === 40
|
||||
? value.voiceDownlinkFrameMs : null,
|
||||
voiceAssumeCloudflare: typeof value.voiceAssumeCloudflare === "boolean" ? value.voiceAssumeCloudflare : null,
|
||||
voiceAutoRelayRetry: typeof value.voiceAutoRelayRetry === "boolean" ? value.voiceAutoRelayRetry : null,
|
||||
};
|
||||
}
|
||||
|
||||
private writeSettings(settings: SettingsUpdate, now: string): void {
|
||||
this.database.prepare(
|
||||
`UPDATE settings SET
|
||||
@@ -791,6 +838,12 @@ export class WebSpeakDatabase {
|
||||
settings.relayTokenEncrypted,
|
||||
now,
|
||||
);
|
||||
// writeSettings is called within the caller's settings transaction. Older
|
||||
// binaries ignore this key and keep it intact when updating other fields.
|
||||
this.setMeta(VOICE_SETTINGS_META_KEY, JSON.stringify({
|
||||
...this.readVoiceSettings(),
|
||||
...Object.fromEntries(Object.entries(settings).filter(([key, value]) => key.startsWith("voice") && value !== undefined)),
|
||||
}));
|
||||
}
|
||||
|
||||
private insertAudit(event: string, details: Record<string, unknown>, now: string): void {
|
||||
|
||||
@@ -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;
|
||||
@@ -27,6 +33,12 @@ export interface AudioFlowStats extends WebRtcAudioStats {
|
||||
egressSentMaxGapMs: number;
|
||||
egressPeakBufferedBytes: number;
|
||||
egressFramesByClient: Record<string, number>;
|
||||
downlinkBatchMessages: number;
|
||||
downlinkBatchEntries: number;
|
||||
downlinkBatchMaxEntries: number;
|
||||
downlinkBatchDroppedFrames: number;
|
||||
downlinkBatchPeakQueueMs: number;
|
||||
downlinkBatchLateTicks: number;
|
||||
|
||||
}
|
||||
|
||||
@@ -38,6 +50,8 @@ export interface AudioStatsSource {
|
||||
export function createAudioFlowStats(): AudioFlowStats {
|
||||
return {
|
||||
ingressFrames: 0,
|
||||
ingressPcmFrames: 0,
|
||||
ingressOpusFrames: 0,
|
||||
ingressDroppedFrames: 0,
|
||||
ingressFirstAt: null,
|
||||
ingressLastAt: null,
|
||||
@@ -48,6 +62,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,
|
||||
@@ -62,6 +80,12 @@ export function createAudioFlowStats(): AudioFlowStats {
|
||||
egressSentMaxGapMs: 0,
|
||||
egressPeakBufferedBytes: 0,
|
||||
egressFramesByClient: {},
|
||||
downlinkBatchMessages: 0,
|
||||
downlinkBatchEntries: 0,
|
||||
downlinkBatchMaxEntries: 0,
|
||||
downlinkBatchDroppedFrames: 0,
|
||||
downlinkBatchPeakQueueMs: 0,
|
||||
downlinkBatchLateTicks: 0,
|
||||
webrtcIngressRtpFrames: 0,
|
||||
webrtcIngressRtpFirstAt: null,
|
||||
webrtcIngressRtpLastAt: null,
|
||||
@@ -95,11 +119,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,
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { DownlinkBatcher } from "./downlink-batcher.js";
|
||||
import { decodeVoiceBatch } from "../shared/voice-audio.js";
|
||||
|
||||
function fixture(frameMs: 20 | 40 = 20) {
|
||||
let now = 0;
|
||||
const packets: { packet: Uint8Array; entries: number; sentAt: number }[] = [];
|
||||
const batcher = new DownlinkBatcher({
|
||||
frameMs,
|
||||
now: () => now,
|
||||
subscribe: () => () => {},
|
||||
send: (packet, entries, sentAt) => { packets.push({ packet, entries, sentAt }); },
|
||||
});
|
||||
return { batcher, packets, setNow: (value: number) => { now = value; } };
|
||||
}
|
||||
|
||||
test("batcher coalesces one tick of speakers into a single v3 packet", () => {
|
||||
const f = fixture();
|
||||
f.batcher.push(4, 2, Uint8Array.from([1, 2, 3]));
|
||||
f.batcher.push(5, 3, Uint8Array.from([4, 5]));
|
||||
f.batcher.push(4, 4, Uint8Array.from([6]));
|
||||
f.batcher.flush(0);
|
||||
assert.equal(f.packets.length, 1);
|
||||
const decoded = decodeVoiceBatch(f.packets[0]!.packet);
|
||||
assert.ok(decoded);
|
||||
assert.equal(decoded.audioStartMs, 0);
|
||||
assert.deepEqual(decoded.entries.map(entry => entry.clientId), [2, 3, 4]);
|
||||
assert.deepEqual(decoded.entries.map(entry => entry.seq), [1, 1, 1]);
|
||||
assert.equal(f.batcher.getStats().messages, 1);
|
||||
assert.equal(f.batcher.getStats().entries, 3);
|
||||
assert.equal(f.batcher.getStats().maxEntries, 3);
|
||||
});
|
||||
|
||||
test("batcher caps entries and bytes per packet while keeping every frame", () => {
|
||||
const f = fixture();
|
||||
for (let id = 1; id <= 40; id++) f.batcher.push(4, id, new Uint8Array(100));
|
||||
f.batcher.flush(0);
|
||||
assert.ok(f.packets.length >= 2);
|
||||
const decoded = f.packets.flatMap(entry => decodeVoiceBatch(entry.packet)?.entries ?? []);
|
||||
assert.equal(decoded.length, 40);
|
||||
assert.ok(Math.max(...f.packets.map(entry => entry.entries)) <= 32);
|
||||
assert.equal(f.batcher.getStats().droppedFrames, 0);
|
||||
});
|
||||
|
||||
test("stale frames and per-speaker sequence gaps survive a tunnel stall", () => {
|
||||
const f = fixture();
|
||||
f.batcher.push(4, 2, Uint8Array.from([1]));
|
||||
f.setNow(150);
|
||||
f.batcher.flush(150);
|
||||
assert.equal(f.packets.length, 0);
|
||||
assert.equal(f.batcher.getStats().droppedFrames, 1);
|
||||
f.batcher.push(4, 2, Uint8Array.from([2]));
|
||||
f.setNow(160);
|
||||
f.batcher.flush(160);
|
||||
const decoded = decodeVoiceBatch(f.packets[0]!.packet);
|
||||
assert.equal(decoded?.entries[0]?.seq, 2, "a dropped frame leaves a detectable gap");
|
||||
});
|
||||
|
||||
test("40 ms batching waits a full negotiated tick", () => {
|
||||
const f = fixture(40);
|
||||
f.batcher.push(4, 2, Uint8Array.from([1]));
|
||||
f.batcher.flush(0);
|
||||
const decoded = decodeVoiceBatch(f.packets[0]!.packet);
|
||||
assert.equal(decoded?.audioStartMs, 0);
|
||||
f.batcher.setFrameMs(20);
|
||||
f.setNow(20);
|
||||
f.batcher.push(4, 2, Uint8Array.from([2]));
|
||||
f.batcher.flush(20);
|
||||
assert.equal(decodeVoiceBatch(f.packets[1]!.packet)?.audioStartMs, 20);
|
||||
});
|
||||
|
||||
test("a late flush keeps one audio timestamp per missed tick", () => {
|
||||
const f = fixture();
|
||||
f.batcher.push(4, 2, Uint8Array.from([1]));
|
||||
f.setNow(20);
|
||||
f.batcher.push(4, 2, Uint8Array.from([2]));
|
||||
// Simulate a 100 ms timer stall: both ticks are still inside the queue
|
||||
// horizon and must not collapse onto a single playback instant.
|
||||
f.setNow(100);
|
||||
f.batcher.flush(100);
|
||||
assert.equal(f.packets.length, 2);
|
||||
assert.deepEqual(f.packets.map(entry => decodeVoiceBatch(entry.packet)?.audioStartMs), [0, 20]);
|
||||
});
|
||||
@@ -0,0 +1,218 @@
|
||||
import { performance } from "node:perf_hooks";
|
||||
import {
|
||||
encodeVoiceBatch,
|
||||
VOICE_BATCH_MAX_BYTES,
|
||||
VOICE_BATCH_MAX_ENTRIES,
|
||||
VOICE_MAX_OPUS_FRAME_BYTES,
|
||||
type VoiceBatchEntry,
|
||||
} from "../shared/voice-audio.js";
|
||||
import { subscribeDownlink } from "./downlink-scheduler.js";
|
||||
|
||||
/**
|
||||
* Coalesces TeamSpeak downlink packets into one binary message per audio tick.
|
||||
*
|
||||
* The compatibility path used to send one small WebSocket message per speaker
|
||||
* per 20 ms. Through Cloudflare Tunnel that becomes a burst of tiny messages
|
||||
* sharing one TCP connection; batching cuts the message count by the number of
|
||||
* active speakers and gives the browser an explicit audio clock to schedule on.
|
||||
*/
|
||||
|
||||
export interface DownlinkBatcherOptions {
|
||||
frameMs?: 20 | 40;
|
||||
maxEntries?: number;
|
||||
maxBytes?: number;
|
||||
maxQueueMs?: number;
|
||||
maxQueueEntries?: number;
|
||||
now?: () => number;
|
||||
send: (packet: Uint8Array, entries: number, sentAt: number) => void;
|
||||
subscribe?: (intervalMs: number, subscriber: (tickAt: number) => void) => () => void;
|
||||
onStats?: (stats: DownlinkBatchStats) => void;
|
||||
}
|
||||
|
||||
export interface DownlinkBatchStats {
|
||||
messages: number;
|
||||
entries: number;
|
||||
maxEntries: number;
|
||||
droppedFrames: number;
|
||||
peakQueuedFrames: number;
|
||||
peakQueuedMs: number;
|
||||
lateTicks: number;
|
||||
}
|
||||
|
||||
interface QueuedFrame extends VoiceBatchEntry {
|
||||
enqueuedAt: number;
|
||||
}
|
||||
|
||||
const LATE_TICK_MS = 100;
|
||||
|
||||
export class DownlinkBatcher {
|
||||
private frameMs: number;
|
||||
private readonly maxEntries: number;
|
||||
private readonly maxBytes: number;
|
||||
private readonly maxQueueMs: number;
|
||||
private readonly maxQueueEntries: number;
|
||||
private readonly now: () => number;
|
||||
private readonly send: DownlinkBatcherOptions["send"];
|
||||
private readonly subscribe: NonNullable<DownlinkBatcherOptions["subscribe"]>;
|
||||
private readonly onStats: DownlinkBatcherOptions["onStats"];
|
||||
private readonly queue: QueuedFrame[] = [];
|
||||
private readonly seqByClient = new Map<number, number>();
|
||||
private unsubscribe: (() => void) | null = null;
|
||||
private origin: number;
|
||||
private closed = false;
|
||||
private messages = 0;
|
||||
private entries = 0;
|
||||
private maxEntriesSeen = 0;
|
||||
private droppedFrames = 0;
|
||||
private peakQueuedFrames = 0;
|
||||
private peakQueuedMs = 0;
|
||||
private lateTicks = 0;
|
||||
|
||||
constructor(options: DownlinkBatcherOptions) {
|
||||
this.frameMs = options.frameMs === 40 ? 40 : 20;
|
||||
this.maxEntries = Math.max(1, Math.min(VOICE_BATCH_MAX_ENTRIES, options.maxEntries ?? 32));
|
||||
this.maxBytes = Math.max(1, Math.min(VOICE_BATCH_MAX_BYTES, options.maxBytes ?? VOICE_BATCH_MAX_BYTES));
|
||||
this.maxQueueMs = Math.max(this.frameMs, options.maxQueueMs ?? 100);
|
||||
this.maxQueueEntries = Math.max(1, options.maxQueueEntries ?? 64);
|
||||
this.now = options.now ?? (() => performance.now());
|
||||
this.origin = this.now();
|
||||
this.send = options.send;
|
||||
this.subscribe = options.subscribe ?? subscribeDownlink;
|
||||
this.onStats = options.onStats;
|
||||
this.arm();
|
||||
}
|
||||
|
||||
/** Returns false for a frame the encoder could not represent. */
|
||||
push(codec: number, clientId: number, data: Uint8Array): boolean {
|
||||
if (this.closed || data.length < 1 || data.length > VOICE_MAX_OPUS_FRAME_BYTES
|
||||
|| !Number.isInteger(codec) || codec < 0 || codec > 255
|
||||
|| !Number.isInteger(clientId) || clientId < 1 || clientId > 65_535) return false;
|
||||
const now = this.now();
|
||||
this.dropStale(now);
|
||||
while (this.queue.length >= this.maxQueueEntries) {
|
||||
this.queue.shift();
|
||||
this.droppedFrames++;
|
||||
}
|
||||
const seq = ((this.seqByClient.get(clientId) ?? 0) + 1) & 0xff;
|
||||
this.seqByClient.set(clientId, seq);
|
||||
// TeamSpeak's SDK may reuse its packet buffer; the queue can live for one
|
||||
// tick, so copy now rather than risk sending the next speaker's payload.
|
||||
this.queue.push({ codec, clientId, seq, data: Buffer.from(data), enqueuedAt: now });
|
||||
this.peakQueuedFrames = Math.max(this.peakQueuedFrames, this.queue.length);
|
||||
this.peakQueuedMs = Math.max(this.peakQueuedMs, this.oldestAge(now));
|
||||
this.emitStats();
|
||||
return true;
|
||||
}
|
||||
|
||||
setFrameMs(frameMs: 20 | 40): void {
|
||||
if (this.frameMs === frameMs || this.closed) return;
|
||||
// Drain under the old cadence before changing the clock bucket size.
|
||||
this.flush(this.now());
|
||||
this.frameMs = frameMs;
|
||||
this.origin = this.now();
|
||||
this.unsubscribe?.();
|
||||
this.unsubscribe = null;
|
||||
this.arm();
|
||||
}
|
||||
|
||||
/** Scheduler entry point; also used directly by tests with a synthetic tick. */
|
||||
flush(tickAt = this.now()): void {
|
||||
if (this.closed) return;
|
||||
const now = this.now();
|
||||
if (now - tickAt > LATE_TICK_MS) this.lateTicks++;
|
||||
this.dropStale(now);
|
||||
if (!this.queue.length) {
|
||||
this.emitStats();
|
||||
return;
|
||||
}
|
||||
|
||||
const sendGroup = (group: QueuedFrame[], bucket: number) => {
|
||||
const stamp = Math.max(0, this.origin + bucket * this.frameMs);
|
||||
let batch: QueuedFrame[] = [];
|
||||
let batchBytes = 6;
|
||||
const flushBatch = () => {
|
||||
if (!batch.length) return;
|
||||
const encoded = encodeVoiceBatch(stamp, batch);
|
||||
if (encoded) {
|
||||
this.messages++;
|
||||
this.entries += batch.length;
|
||||
this.maxEntriesSeen = Math.max(this.maxEntriesSeen, batch.length);
|
||||
try { this.send(encoded, batch.length, stamp); } catch { this.droppedFrames += batch.length; }
|
||||
} else {
|
||||
// Should be unreachable because push() bounds each frame and flush()
|
||||
// splits on the same limits; keep the queue honest if it happens.
|
||||
this.droppedFrames += batch.length;
|
||||
}
|
||||
batch = [];
|
||||
batchBytes = 6;
|
||||
};
|
||||
for (const frame of group) {
|
||||
const frameBytes = 6 + frame.data.length;
|
||||
if (batch.length && (batch.length >= this.maxEntries || batchBytes + frameBytes > this.maxBytes)) flushBatch();
|
||||
batch.push(frame);
|
||||
batchBytes += frameBytes;
|
||||
if (batch.length >= this.maxEntries || batchBytes >= this.maxBytes) flushBatch();
|
||||
}
|
||||
flushBatch();
|
||||
};
|
||||
|
||||
// A late timer can hold several ticks of frames. Keep each tick as its own
|
||||
// batch with its own audio timestamp: coalescing the whole backlog into one
|
||||
// stamp would hide the stall from the jitter estimator and stack every
|
||||
// speaker on the same playback instant.
|
||||
let group: QueuedFrame[] = [];
|
||||
let bucket = -1;
|
||||
for (const frame of this.queue) {
|
||||
const frameBucket = Math.floor((frame.enqueuedAt - this.origin) / this.frameMs);
|
||||
if (group.length && frameBucket !== bucket) {
|
||||
sendGroup(group, bucket);
|
||||
group = [];
|
||||
}
|
||||
bucket = frameBucket;
|
||||
group.push(frame);
|
||||
}
|
||||
if (group.length) sendGroup(group, bucket);
|
||||
this.queue.length = 0;
|
||||
this.emitStats();
|
||||
}
|
||||
|
||||
getStats(): DownlinkBatchStats {
|
||||
return {
|
||||
messages: this.messages,
|
||||
entries: this.entries,
|
||||
maxEntries: this.maxEntriesSeen,
|
||||
droppedFrames: this.droppedFrames,
|
||||
peakQueuedFrames: this.peakQueuedFrames,
|
||||
peakQueuedMs: this.peakQueuedMs,
|
||||
lateTicks: this.lateTicks,
|
||||
};
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
this.unsubscribe?.();
|
||||
this.unsubscribe = null;
|
||||
this.queue.length = 0;
|
||||
this.emitStats();
|
||||
}
|
||||
|
||||
private arm(): void {
|
||||
this.unsubscribe = this.subscribe(this.frameMs, tickAt => this.flush(tickAt));
|
||||
}
|
||||
|
||||
private dropStale(now: number): void {
|
||||
while (this.queue.length && now - this.queue[0]!.enqueuedAt > this.maxQueueMs) {
|
||||
this.queue.shift();
|
||||
this.droppedFrames++;
|
||||
}
|
||||
}
|
||||
|
||||
private oldestAge(now: number): number {
|
||||
return this.queue.length ? Math.max(0, now - this.queue[0]!.enqueuedAt) : 0;
|
||||
}
|
||||
|
||||
private emitStats(): void {
|
||||
this.onStats?.(this.getStats());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { performance } from "node:perf_hooks";
|
||||
|
||||
/**
|
||||
* One timer per cadence, shared by every downlink batcher. A per-session timer
|
||||
* would mean 50 timers/s per compatibility session (100 sessions -> 5k/s),
|
||||
* which is measurable event-loop churn for no benefit. The scheduler passes
|
||||
* the planned tick time only so a batcher can detect a late turn; batch
|
||||
* timestamps are derived from the batcher's tick buckets.
|
||||
*/
|
||||
|
||||
type Subscriber = (tickAt: number) => void;
|
||||
|
||||
interface Slot {
|
||||
timer: ReturnType<typeof setInterval>;
|
||||
nextAt: number;
|
||||
subscribers: Set<Subscriber>;
|
||||
}
|
||||
|
||||
const slots = new Map<number, Slot>();
|
||||
const LATE_RESET_MS = 100;
|
||||
|
||||
export function subscribeDownlink(intervalMs: number, subscriber: Subscriber): () => void {
|
||||
const interval = Math.max(10, Math.min(60, Math.round(intervalMs)));
|
||||
let slot = slots.get(interval);
|
||||
if (!slot) {
|
||||
slot = {
|
||||
nextAt: performance.now() + interval,
|
||||
subscribers: new Set(),
|
||||
timer: setInterval(() => runSlot(interval, slot!), interval),
|
||||
};
|
||||
// Idle voice sessions must not keep the process alive.
|
||||
(slot.timer as unknown as { unref?: () => void }).unref?.();
|
||||
slots.set(interval, slot);
|
||||
}
|
||||
slot.subscribers.add(subscriber);
|
||||
return () => {
|
||||
const current = slots.get(interval);
|
||||
if (!current) return;
|
||||
current.subscribers.delete(subscriber);
|
||||
if (!current.subscribers.size) {
|
||||
clearInterval(current.timer);
|
||||
slots.delete(interval);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function runSlot(interval: number, slot: Slot): void {
|
||||
const now = performance.now();
|
||||
if (now - slot.nextAt > LATE_RESET_MS) slot.nextAt = now;
|
||||
const tickAt = slot.nextAt;
|
||||
slot.nextAt = tickAt + interval;
|
||||
// Copy so a subscriber that unsubscribes during its callback cannot skip
|
||||
// another subscriber in the same tick.
|
||||
for (const subscriber of [...slot.subscribers]) {
|
||||
try { subscriber(tickAt); } catch { /* one session must not stop the shared timer */ }
|
||||
}
|
||||
}
|
||||
|
||||
/** Test hook: drop every slot without waiting for an interval to fire. */
|
||||
export function resetDownlinkSchedulerForTests(): void {
|
||||
for (const slot of slots.values()) clearInterval(slot.timer);
|
||||
slots.clear();
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import type { TSVoiceData } from "./ts-client.js";
|
||||
|
||||
function fixture() {
|
||||
const state = { current: true, ready: true, now: 0, targets: null as number[] | null, disposed: 0,
|
||||
peer: null as { pushTeamSpeakVoice(data: TSVoiceData): void } | null };
|
||||
peer: null as { isConnected: boolean; pushTeamSpeakVoice(data: TSVoiceData): void } | null };
|
||||
const audio = createAudioFlowStats();
|
||||
const packets: Buffer[] = [];
|
||||
const encoded: Buffer[] = [];
|
||||
@@ -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,9 +131,22 @@ 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() {} };
|
||||
f.state.peer = { isConnected: true, pushTeamSpeakVoice() {} };
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
const opus = Buffer.from([3, 2, 1]);
|
||||
f.transport.receiveWebRtc(opus, 5);
|
||||
@@ -175,7 +188,7 @@ test("backpressure drops bursts above 4096 bytes and resumes without a retained
|
||||
test("WebRTC downlink owns egress without a duplicate WebSocket packet", () => {
|
||||
const f = fixture();
|
||||
const received: TSVoiceData[] = [];
|
||||
f.state.peer = { pushTeamSpeakVoice: data => { received.push(data); } };
|
||||
f.state.peer = { isConnected: true, pushTeamSpeakVoice: data => { received.push(data); } };
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(received.length, 1);
|
||||
assert.equal(f.packets.length, 0);
|
||||
@@ -185,6 +198,28 @@ test("WebRTC downlink owns egress without a duplicate WebSocket packet", () => {
|
||||
assert.equal(f.packets.length, 1);
|
||||
});
|
||||
|
||||
test("negotiating WebRTC keeps both compatibility directions until the media path connects", () => {
|
||||
const f = fixture();
|
||||
const received: TSVoiceData[] = [];
|
||||
f.state.peer = { isConnected: false, pushTeamSpeakVoice: data => received.push(data) };
|
||||
f.transport.receivePcm(Buffer.alloc(1920));
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(f.forwarded.length, 1);
|
||||
assert.equal(f.packets.length, 1);
|
||||
assert.equal(received.length, 0);
|
||||
f.state.peer.isConnected = true;
|
||||
f.transport.receivePcm(Buffer.alloc(1920));
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(f.forwarded.length, 1);
|
||||
assert.equal(f.packets.length, 1);
|
||||
assert.equal(received.length, 1);
|
||||
f.state.peer.isConnected = false;
|
||||
f.transport.receivePcm(Buffer.alloc(1920));
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(f.forwarded.length, 2);
|
||||
assert.equal(f.packets.length, 2);
|
||||
});
|
||||
|
||||
test("encoding failures are counted and reported at most once per five seconds", t => {
|
||||
const f = fixture();
|
||||
t.mock.method(f.encoder, "encode", () => { throw new Error("Codec failed"); });
|
||||
@@ -207,7 +242,7 @@ test("SDK and downlink failures cannot escape the audio callbacks", t => {
|
||||
assert.equal(f.notices.length, 0, "SDK failure must not be reported as an encoder failure");
|
||||
t.mock.method(f.socket, "send", () => { throw new Error("Socket closed"); });
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
f.state.peer = { pushTeamSpeakVoice() { throw new Error("Peer closed"); } };
|
||||
f.state.peer = { isConnected: true, pushTeamSpeakVoice() { throw new Error("Peer closed"); } };
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(f.audio.egressDroppedFrames, 2);
|
||||
});
|
||||
@@ -250,3 +285,45 @@ test("invalid SDK speaker IDs and codecs cannot throw while packing the header",
|
||||
assert.equal(f.audio.egressDroppedFrames, 6);
|
||||
assert.equal(f.packets.length, 0);
|
||||
});
|
||||
|
||||
test("a 40 ms PCM frame is split into two TeamSpeak frames and costs two rate tokens", () => {
|
||||
const f = fixture();
|
||||
f.transport.receivePcm(Buffer.alloc(3_840));
|
||||
assert.equal(f.encoded.length, 2);
|
||||
assert.deepEqual(f.forwarded.map(entry => entry.codec), [4, 4]);
|
||||
assert.equal(f.audio.ingressPcmFrames, 2);
|
||||
for (let index = 0; index < 24; index++) f.state.now = 20 + index * 20;
|
||||
for (let index = 0; index < 24; index++) f.transport.receivePcm(Buffer.alloc(3_840));
|
||||
assert.equal(f.audio.ingressDroppedFrames, 0, "40 ms frames consume their two tokens without exceeding the budget");
|
||||
});
|
||||
|
||||
test("a v3 client gets one batched packet per audio tick instead of one message per speaker", t => {
|
||||
t.mock.timers.enable({ apis: ["setInterval"] });
|
||||
const f = fixture();
|
||||
f.transport.setDownlinkBatch(20);
|
||||
f.transport.receiveTeamSpeak({ clientId: 2, codec: 4, data: Buffer.from([1, 2]) });
|
||||
f.transport.receiveTeamSpeak({ clientId: 3, codec: 5, data: Buffer.from([3]) });
|
||||
f.transport.receiveTeamSpeak({ clientId: 4, codec: 4, data: Buffer.from([4]) });
|
||||
assert.equal(f.packets.length, 0, "no immediate small messages after negotiation");
|
||||
f.state.now = 20;
|
||||
t.mock.timers.tick(20);
|
||||
assert.equal(f.packets.length, 1);
|
||||
assert.equal(f.packets[0]![0], 0xf3);
|
||||
assert.equal(f.audio.egressFrames, 3, "flow counters still count frames, not batches");
|
||||
assert.equal(f.audio.downlinkBatchMessages, 1);
|
||||
assert.equal(f.audio.downlinkBatchEntries, 3);
|
||||
});
|
||||
|
||||
test("a 40 ms v3 negotiation holds a batch for two 20 ms frames", t => {
|
||||
t.mock.timers.enable({ apis: ["setInterval"] });
|
||||
const f = fixture();
|
||||
f.transport.setDownlinkBatch(40);
|
||||
f.transport.receiveTeamSpeak({ clientId: 2, codec: 4, data: Buffer.from([1]) });
|
||||
f.state.now = 20;
|
||||
t.mock.timers.tick(20);
|
||||
assert.equal(f.packets.length, 0);
|
||||
f.state.now = 40;
|
||||
t.mock.timers.tick(20);
|
||||
assert.equal(f.packets.length, 1);
|
||||
assert.equal(f.audio.downlinkBatchEntries, 1);
|
||||
});
|
||||
+138
-21
@@ -5,10 +5,26 @@ 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 { DownlinkBatcher } from "./downlink-batcher.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.
|
||||
// Keep the established byte guard; the browser also bounds playback by time.
|
||||
const AUDIO_FRAME_BYTES = VOICE_PCM_FRAME_BYTES;
|
||||
const AUDIO_FRAME_BYTES_40 = AUDIO_FRAME_BYTES * 2;
|
||||
const TAGGED_PCM_FRAME_BYTES = AUDIO_FRAME_BYTES + 1;
|
||||
const TAGGED_PCM_FRAME_BYTES_40 = AUDIO_FRAME_BYTES_40 + 1;
|
||||
const PCM_FRAME_TAG = VOICE_PCM_TAG;
|
||||
const OPUS_FRAME_TAG = VOICE_OPUS_TAG;
|
||||
const MAX_OPUS_FRAME_BYTES = VOICE_MAX_OPUS_FRAME_BYTES;
|
||||
// Keep the established byte guard for the per-packet v2 path; a negotiated v3
|
||||
// batch may hold several speakers' frames and uses the larger limit below.
|
||||
const MAX_BUFFERED_BYTES = 4_096;
|
||||
const BATCH_BUFFERED_BYTES = 32 * 1_024;
|
||||
// A client that keeps sending bad audio must not turn into one JSON error per
|
||||
// frame: the reply is roughly 100x the offending payload, and the browser only
|
||||
// ever shows the first one because it writes the same error string.
|
||||
@@ -30,9 +46,11 @@ export interface SessionAudioOptions {
|
||||
isCurrent(): boolean;
|
||||
isReady(): boolean;
|
||||
selfId(): number;
|
||||
peer(): Pick<WebRtcAudioSession, "pushTeamSpeakVoice"> | null;
|
||||
peer(): Pick<WebRtcAudioSession, "pushTeamSpeakVoice" | "isConnected"> | 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 +60,9 @@ 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 downlinkBatcher: DownlinkBatcher | null = null;
|
||||
private downlinkBufferedBytes = MAX_BUFFERED_BYTES;
|
||||
private pcmTokens = PCM_BURST_FRAMES;
|
||||
private pcmRefilledAt: number | null = null;
|
||||
|
||||
@@ -49,12 +70,72 @@ 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) => {
|
||||
if (!this.mediaPeer()) 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 {
|
||||
return !this.closed && this.options.isCurrent() && this.options.socket.readyState === WebSocket.OPEN;
|
||||
}
|
||||
|
||||
private mediaPeer() {
|
||||
const peer = this.options.peer();
|
||||
return peer?.isConnected ? peer : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch the compatibility downlink to one binary message per audio tick.
|
||||
* Only called after a client has negotiated frame version 3, so a v2 client
|
||||
* keeps the byte-for-byte per-packet path.
|
||||
*/
|
||||
setDownlinkBatch(frameMs: 20 | 40): void {
|
||||
if (this.closed) return;
|
||||
this.downlinkBufferedBytes = BATCH_BUFFERED_BYTES;
|
||||
if (this.downlinkBatcher) {
|
||||
this.downlinkBatcher.setFrameMs(frameMs);
|
||||
return;
|
||||
}
|
||||
this.downlinkBatcher = new DownlinkBatcher({
|
||||
frameMs,
|
||||
now: () => this.rateClock(),
|
||||
send: (packet, entries) => {
|
||||
if (!this.isCurrent()) return;
|
||||
try {
|
||||
this.options.socket.send(Buffer.from(packet));
|
||||
const stats = this.options.audio;
|
||||
stats.egressFrames += entries;
|
||||
const sentAt = this.clock();
|
||||
if (stats.egressSentLastAt !== null) stats.egressSentMaxGapMs = Math.max(stats.egressSentMaxGapMs, sentAt - stats.egressSentLastAt);
|
||||
stats.egressSentFirstAt ??= sentAt;
|
||||
stats.egressSentLastAt = sentAt;
|
||||
} catch {
|
||||
this.options.audio.downlinkBatchDroppedFrames += entries;
|
||||
}
|
||||
},
|
||||
onStats: stats => {
|
||||
const audio = this.options.audio;
|
||||
audio.downlinkBatchMessages = stats.messages;
|
||||
audio.downlinkBatchEntries = stats.entries;
|
||||
audio.downlinkBatchMaxEntries = Math.max(audio.downlinkBatchMaxEntries, stats.maxEntries);
|
||||
audio.downlinkBatchDroppedFrames = Math.max(audio.downlinkBatchDroppedFrames, stats.droppedFrames);
|
||||
audio.downlinkBatchPeakQueueMs = Math.max(audio.downlinkBatchPeakQueueMs, stats.peakQueuedMs);
|
||||
audio.downlinkBatchLateTicks = Math.max(audio.downlinkBatchLateTicks, stats.lateTicks);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private recordIngress(): void {
|
||||
const stats = this.options.audio;
|
||||
const now = this.clock();
|
||||
@@ -112,7 +193,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 {
|
||||
@@ -127,39 +208,64 @@ export class SessionAudioTransport {
|
||||
// route is down is discarded whatever its size, so calling it malformed would
|
||||
// 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) {
|
||||
if (!this.options.isReady() || this.mediaPeer()) { stats.ingressDroppedFrames++; return; }
|
||||
const legacyPcm = frame.length === AUDIO_FRAME_BYTES || frame.length === AUDIO_FRAME_BYTES_40 ? frame : null;
|
||||
const taggedPcm = (frame.length === TAGGED_PCM_FRAME_BYTES || frame.length === TAGGED_PCM_FRAME_BYTES_40)
|
||||
&& frame[0] === PCM_FRAME_TAG ? frame.subarray(1) : null;
|
||||
const opus = frame.length > 1 && frame.length <= MAX_OPUS_FRAME_BYTES + 1 && frame[0] === OPUS_FRAME_TAG
|
||||
? frame.subarray(1) : null;
|
||||
if (!legacyPcm && !taggedPcm && !opus) {
|
||||
stats.ingressDroppedFrames++;
|
||||
this.reportInvalidFrame(frame.length);
|
||||
return;
|
||||
}
|
||||
// A 40 ms PCM frame carries two 20 ms TeamSpeak frames and therefore costs
|
||||
// two tokens; otherwise a client could double its uplink rate by doubling
|
||||
// the frame size.
|
||||
const pcmFrames = legacyPcm ?? taggedPcm;
|
||||
const frameCount = pcmFrames ? (pcmFrames.length === AUDIO_FRAME_BYTES_40 ? 2 : 1) : 1;
|
||||
const now = this.rateClock();
|
||||
if (this.pcmRefilledAt !== null) {
|
||||
this.pcmTokens = Math.min(PCM_BURST_FRAMES, this.pcmTokens + Math.max(0, now - this.pcmRefilledAt) * PCM_FRAMES_PER_MS);
|
||||
}
|
||||
this.pcmRefilledAt = Math.max(this.pcmRefilledAt ?? now, now);
|
||||
if (this.pcmTokens < 1) {
|
||||
if (this.pcmTokens < frameCount) {
|
||||
stats.ingressDroppedFrames++;
|
||||
if (this.shouldReportAudioIssue("AUDIO_RATE_EXCEEDED")) {
|
||||
this.logger?.warn({ code: "AUDIO_RATE_EXCEEDED", droppedFrames: stats.ingressDroppedFrames }, "Discarded browser 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.pcmTokens -= frameCount;
|
||||
this.recordIngress();
|
||||
const startedAt = this.clock();
|
||||
let encoded: Buffer;
|
||||
try {
|
||||
if (!this.encoder) throw new Error("Encoder unavailable");
|
||||
encoded = this.encoder.encode(frame);
|
||||
stats.tsEncodeMaxMs = Math.max(stats.tsEncodeMaxMs, this.clock() - startedAt);
|
||||
} catch {
|
||||
stats.tsSendErrors++;
|
||||
stats.ingressDroppedFrames++;
|
||||
this.reportEncoderFailure();
|
||||
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;
|
||||
}
|
||||
this.sendVoice(encoded, 4);
|
||||
stats.ingressPcmFrames += frameCount;
|
||||
const chunks = pcmFrames!.length === AUDIO_FRAME_BYTES_40
|
||||
? [pcmFrames!.subarray(0, AUDIO_FRAME_BYTES), pcmFrames!.subarray(AUDIO_FRAME_BYTES)]
|
||||
: [pcmFrames!];
|
||||
for (const chunk of chunks) {
|
||||
const startedAt = this.clock();
|
||||
let encoded: Buffer;
|
||||
try {
|
||||
if (!this.encoder) throw new Error("Encoder unavailable");
|
||||
encoded = this.encoder.encode(chunk);
|
||||
stats.tsEncodeMaxMs = Math.max(stats.tsEncodeMaxMs, this.clock() - startedAt);
|
||||
} catch {
|
||||
stats.tsSendErrors++;
|
||||
stats.ingressDroppedFrames++;
|
||||
this.reportEncoderFailure();
|
||||
return;
|
||||
}
|
||||
this.pacer?.push(encoded, 4);
|
||||
if (!this.pacer) this.sendVoice(encoded, 4);
|
||||
}
|
||||
}
|
||||
|
||||
receiveWebRtc(data: Buffer, codec: number): void {
|
||||
@@ -187,7 +293,7 @@ export class SessionAudioTransport {
|
||||
stats.egressLastAt = now;
|
||||
const key = String(data.clientId);
|
||||
stats.egressFramesByClient[key] = (stats.egressFramesByClient[key] ?? 0) + 1;
|
||||
const peer = this.options.peer();
|
||||
const peer = this.mediaPeer();
|
||||
if (peer) {
|
||||
try { peer.pushTeamSpeakVoice(data); stats.egressFrames++; }
|
||||
catch { stats.egressDroppedFrames++; }
|
||||
@@ -195,6 +301,14 @@ export class SessionAudioTransport {
|
||||
}
|
||||
const bufferedBytes = this.options.socket.bufferedAmount;
|
||||
stats.egressPeakBufferedBytes = Math.max(stats.egressPeakBufferedBytes, bufferedBytes);
|
||||
if (this.downlinkBatcher) {
|
||||
if (bufferedBytes > this.downlinkBufferedBytes) {
|
||||
stats.downlinkBatchDroppedFrames++;
|
||||
return;
|
||||
}
|
||||
if (!this.downlinkBatcher.push(data.codec, data.clientId, data.data)) stats.egressDroppedFrames++;
|
||||
return;
|
||||
}
|
||||
if (bufferedBytes > MAX_BUFFERED_BYTES) { stats.egressDroppedFrames++; return; }
|
||||
const packet = Buffer.allocUnsafe(3 + data.data.length);
|
||||
packet[0] = data.codec;
|
||||
@@ -214,6 +328,9 @@ export class SessionAudioTransport {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
this.reportedAt.clear();
|
||||
this.pacer?.close();
|
||||
this.downlinkBatcher?.close();
|
||||
this.downlinkBatcher = null;
|
||||
const encoder = this.encoder;
|
||||
this.encoder = null;
|
||||
try { encoder?.dispose(); } catch { /* other session resources must still be released */ }
|
||||
|
||||
@@ -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,158 @@ 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,
|
||||
downlinkFrameMs: 20,
|
||||
assumeCloudflare: false,
|
||||
autoRelayRetry: true,
|
||||
},
|
||||
});
|
||||
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
|
||||
assert.equal(connected.voiceProfile, "legacy");
|
||||
assert.equal(connected.voiceRelayAutoRetry, true);
|
||||
assert.equal(connected.webrtcAvailable, true);
|
||||
assert.equal(connected.webrtcUnavailableReason, undefined);
|
||||
assert.equal(connected.audioFrameVersion, undefined);
|
||||
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("the console can force a Cloudflare ingress and disable automatic relay retry", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t, {
|
||||
webRtc: { enabled: true },
|
||||
voiceIce: {
|
||||
servers: [],
|
||||
transportPolicy: "all",
|
||||
gatewayTransportPolicy: "all",
|
||||
profile: "auto",
|
||||
opusWebSocket: false,
|
||||
jitterMaxMs: 300,
|
||||
downlinkFrameMs: 20,
|
||||
assumeCloudflare: true,
|
||||
autoRelayRetry: false,
|
||||
},
|
||||
});
|
||||
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
|
||||
assert.equal(connected.voiceProfile, "adaptive");
|
||||
assert.equal(connected.webrtcAvailable, false);
|
||||
assert.equal(connected.webrtcUnavailableReason, "NO_MEDIA_PATH");
|
||||
assert.equal(connected.voiceRelayAutoRetry, false);
|
||||
});
|
||||
|
||||
test("an explicit adaptive profile enables the new audio path on a direct connection", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t, {
|
||||
webRtc: { enabled: true },
|
||||
voiceIce: {
|
||||
servers: [],
|
||||
transportPolicy: "all",
|
||||
gatewayTransportPolicy: "all",
|
||||
profile: "adaptive",
|
||||
opusWebSocket: true,
|
||||
jitterMaxMs: 300,
|
||||
downlinkFrameMs: 20,
|
||||
assumeCloudflare: false,
|
||||
autoRelayRetry: true,
|
||||
},
|
||||
});
|
||||
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
|
||||
assert.equal(connected.voiceProfile, "adaptive");
|
||||
assert.equal(connected.webrtcAvailable, true);
|
||||
assert.equal(connected.audioFrameVersion, 2);
|
||||
assert.deepEqual(connected.audioDownlinkVersions, [2, 3]);
|
||||
assert.deepEqual(connected.audioFrameMsOptions, [20]);
|
||||
assert.deepEqual(connected.audioUplinkCodecs, ["pcm", "opus"]);
|
||||
assert.equal(connected.audioJitterMaxMs, 300);
|
||||
});
|
||||
|
||||
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,
|
||||
downlinkFrameMs: 20,
|
||||
assumeCloudflare: false,
|
||||
autoRelayRetry: true,
|
||||
},
|
||||
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.audioDownlinkVersions, [2, 3]);
|
||||
assert.deepEqual(connected.audioFrameMsOptions, [20]);
|
||||
assert.deepEqual(connected.audioUplinkCodecs, ["pcm"]);
|
||||
assert.equal(connected.audioJitterMaxMs, 300);
|
||||
assert.deepEqual(connected.voiceIceServers, []);
|
||||
});
|
||||
|
||||
test("an adaptive client upgrades to one v3 batch per tick", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t, {
|
||||
webRtc: { enabled: true },
|
||||
voiceIce: {
|
||||
servers: [], transportPolicy: "all", gatewayTransportPolicy: "all",
|
||||
profile: "adaptive", opusWebSocket: false, jitterMaxMs: 300,
|
||||
downlinkFrameMs: 40, assumeCloudflare: false, autoRelayRetry: true,
|
||||
},
|
||||
});
|
||||
await waitForBufferedMessage(f.messages, "connected");
|
||||
const config = waitForMessage<Record<string, unknown>>(f.socket, "audioConfig");
|
||||
f.socket.send(JSON.stringify({
|
||||
type: "audioCaps",
|
||||
requestId: "caps-1",
|
||||
payload: { downlinkVersion: 3, maxFrameMs: 40, codecs: ["pcm"] },
|
||||
}));
|
||||
const message = await config;
|
||||
assert.equal(message.downlinkVersion, 3);
|
||||
assert.equal(message.frameMs, 40, "the console can opt into 40 ms batching");
|
||||
assert.deepEqual(message.uplinkCodecs, ["pcm"]);
|
||||
assert.equal(message.jitterMaxMs, 300);
|
||||
});
|
||||
|
||||
|
||||
test("a voice ICE getter is resolved when a new connection is accepted", { timeout: 5_000 }, async t => {
|
||||
let calls = 0;
|
||||
const f = await fixture(t, {
|
||||
webRtc: { enabled: true },
|
||||
voiceIce: () => {
|
||||
calls++;
|
||||
return {
|
||||
servers: [],
|
||||
transportPolicy: "all",
|
||||
gatewayTransportPolicy: "all",
|
||||
profile: "auto",
|
||||
opusWebSocket: false,
|
||||
jitterMaxMs: 300,
|
||||
downlinkFrameMs: 20,
|
||||
assumeCloudflare: false,
|
||||
autoRelayRetry: true,
|
||||
};
|
||||
},
|
||||
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";
|
||||
@@ -18,6 +18,7 @@ function deferred() {
|
||||
}
|
||||
|
||||
class PeerStub {
|
||||
isConnected = true;
|
||||
closed = false;
|
||||
closeResult = Promise.resolve();
|
||||
answerResult = Promise.resolve();
|
||||
@@ -40,6 +41,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 +65,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 +178,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 +259,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;
|
||||
}
|
||||
|
||||
+121
-4
@@ -28,10 +28,21 @@ 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;
|
||||
const MAX_LOGGED_WEBSOCKET_CLOSE_REASON_LENGTH = 160;
|
||||
/** Set when a reverse proxy strips Cloudflare headers but CFT is still the ingress. */
|
||||
const ASSUME_CLOUDFLARE = process.env.WEBSPEAK_ASSUME_CLOUDFLARE === "1";
|
||||
|
||||
function sanitizeWebSocketCloseReason(reason: Buffer): string {
|
||||
return reason.toString("utf8")
|
||||
@@ -54,6 +65,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 +110,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 +195,13 @@ export class VoiceBridge {
|
||||
return;
|
||||
}
|
||||
const clientIp = resolveClientIp(req, this.trustedProxies);
|
||||
const webrtcPublicHost = resolveWebRtcPublicHost(req);
|
||||
const voiceIce = this.getVoiceIceConfig();
|
||||
// Cloudflare Tunnel forwards the public hostname in `Host`, but that
|
||||
// hostname points at Cloudflare's edge, not at this origin's UDP ports.
|
||||
// Never advertise it as an ICE media address.
|
||||
const cloudflareRequest = (voiceIce?.assumeCloudflare ?? ASSUME_CLOUDFLARE) || isCloudflareRequest(req, this.trustedProxies);
|
||||
const webrtcPublicHost = resolveWebRtcPublicHost(req, { allowHostFallback: !cloudflareRequest });
|
||||
const voiceProfile = resolveVoiceProfile(voiceIce?.profile ?? "auto", cloudflareRequest);
|
||||
let identity;
|
||||
try {
|
||||
identity = connection.identity ? parseIdentity(connection.identity) : undefined;
|
||||
@@ -190,6 +213,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 +273,10 @@ export class VoiceBridge {
|
||||
...(acceleration ? { acceleration } : {}),
|
||||
...(identityLeaseKey ? { identityLeaseKey } : {}),
|
||||
...(webrtcPublicHost ? { webrtcPublicHost } : {}),
|
||||
voiceProfile,
|
||||
voiceIceServers,
|
||||
voiceIceTransportPolicy,
|
||||
voiceIceGatewayTransportPolicy,
|
||||
channelTree: [],
|
||||
members: new Map(),
|
||||
avatarCache: new Map(),
|
||||
@@ -281,6 +311,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 +359,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 +373,22 @@ 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,
|
||||
voiceRelayAutoRetry: voiceIce?.autoRelayRetry !== false,
|
||||
...(entry!.voiceProfile === "adaptive" ? {
|
||||
audioFrameVersion: 2 as const,
|
||||
audioDownlinkVersions: [...new Set([2, 3])] as (2 | 3)[],
|
||||
audioFrameMsOptions: [...new Set([20, voiceIce?.downlinkFrameMs ?? 20])] as (20 | 40)[],
|
||||
audioUplinkCodecs: voiceIce?.opusWebSocket === true
|
||||
? ["pcm", "opus"] as ("pcm" | "opus")[]
|
||||
: ["pcm"] as ("pcm" | "opus")[],
|
||||
audioJitterMaxMs: voiceIce?.jitterMaxMs ?? 300,
|
||||
} : {}),
|
||||
screenShareIceServers: this.getScreenShareIceServers(),
|
||||
accelerated: Boolean(entry!.acceleration),
|
||||
...(entry!.pluginSession ? { pluginSession: entry!.pluginSession } : {}),
|
||||
@@ -622,6 +674,25 @@ export class VoiceBridge {
|
||||
sendProtocolError(sendJson, "SESSION_NOT_READY", "TeamSpeak 会话尚未就绪", command.requestId);
|
||||
return;
|
||||
}
|
||||
if (command.type === "audioCaps") {
|
||||
const uplinkCodecs: ("pcm" | "opus")[] = entry!.voiceProfile === "adaptive" && voiceIce?.opusWebSocket === true
|
||||
? ["pcm", "opus"]
|
||||
: ["pcm"];
|
||||
if (entry!.voiceProfile !== "adaptive") {
|
||||
sendJson({ type: "audioConfig", downlinkVersion: 2, frameMs: 20, uplinkCodecs, jitterMaxMs: 80 });
|
||||
return;
|
||||
}
|
||||
const frameMs = Math.min(command.payload.maxFrameMs, voiceIce?.downlinkFrameMs ?? 20) as 20 | 40;
|
||||
entry!.audioTransport?.setDownlinkBatch(frameMs);
|
||||
sendJson({
|
||||
type: "audioConfig",
|
||||
downlinkVersion: 3,
|
||||
frameMs,
|
||||
uplinkCodecs,
|
||||
jitterMaxMs: voiceIce?.jitterMaxMs ?? 300,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (command.type === "createInvite") {
|
||||
if (!this.options.createWorkspaceInvite) { sendProtocolError(sendJson, "INVITE_UNAVAILABLE", "Invitations are unavailable on this gateway", command.requestId); return; }
|
||||
if (Date.now() - lastInviteAt < 1000) { sendProtocolError(sendJson, "RATE_LIMITED", "Please wait before creating another invitation", command.requestId); return; }
|
||||
@@ -838,6 +909,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 +983,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 +1034,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,55 @@
|
||||
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, true);
|
||||
assert.equal(config.jitterMaxMs, 300);
|
||||
assert.equal(config.downlinkFrameMs, 20);
|
||||
assert.equal(config.assumeCloudflare, false);
|
||||
assert.equal(config.autoRelayRetry, true);
|
||||
assert.equal(config.turnRest, undefined);
|
||||
});
|
||||
|
||||
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);
|
||||
assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_OPUS_WS: "0" }).opusWebSocket, false);
|
||||
assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_FRAME_MS: "40" }).downlinkFrameMs, 40);
|
||||
assert.equal(readVoiceIceConfig({ WEBSPEAK_ASSUME_CLOUDFLARE: "1" }).assumeCloudflare, true);
|
||||
assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_AUTO_RELAY_RETRY: "0" }).autoRelayRetry, false);
|
||||
});
|
||||
|
||||
test("TURN REST env mints a per-session credential and keeps direct-first policy", () => {
|
||||
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,160 @@
|
||||
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;
|
||||
/** Compatibility downlink batch tick. 40 ms halves messages and adds up to 20 ms. */
|
||||
downlinkFrameMs: 20 | 40;
|
||||
/** Treat every voice ingress as Cloudflare even if reverse-proxy headers were stripped. */
|
||||
assumeCloudflare: boolean;
|
||||
/** Allow one automatic relay-only WebRTC retry after a direct-path failure. */
|
||||
autoRelayRetry: boolean;
|
||||
}
|
||||
|
||||
export interface VoiceIceSettings {
|
||||
servers: VoiceIceServer[];
|
||||
transportPolicy: VoiceIceTransportPolicy;
|
||||
gatewayTransportPolicy: VoiceIceTransportPolicy;
|
||||
profile: VoiceProfileSetting;
|
||||
opusWebSocket: boolean;
|
||||
jitterMaxMs: number;
|
||||
downlinkFrameMs: 20 | 40;
|
||||
assumeCloudflare: boolean;
|
||||
autoRelayRetry: boolean;
|
||||
}
|
||||
|
||||
/** Baseline used when neither the console nor the environment configures a value. */
|
||||
export const DEFAULT_VOICE_ICE_CONFIG: VoiceIceConfig = {
|
||||
servers: [],
|
||||
transportPolicy: "all",
|
||||
gatewayTransportPolicy: "all",
|
||||
profile: "auto",
|
||||
// Adaptive clients use Opus when WebCodecs can encode it and silently fall
|
||||
// back to PCM otherwise; legacy clients never see this flag.
|
||||
opusWebSocket: true,
|
||||
jitterMaxMs: VOICE_JITTER_DEFAULT_MS,
|
||||
downlinkFrameMs: 20,
|
||||
assumeCloudflare: false,
|
||||
autoRelayRetry: true,
|
||||
};
|
||||
|
||||
function parseBoolean(value: string | undefined, fallback: boolean): boolean {
|
||||
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 negotiated only for adaptive clients; browsers
|
||||
// without WebCodecs fall back to PCM at runtime.
|
||||
opusWebSocket: parseBoolean(env.WEBSPEAK_VOICE_OPUS_WS, true),
|
||||
jitterMaxMs: parseInteger(env.WEBSPEAK_VOICE_JITTER_MAX_MS, VOICE_JITTER_DEFAULT_MS, VOICE_JITTER_MIN_MS, VOICE_JITTER_MAX_MS),
|
||||
downlinkFrameMs: env.WEBSPEAK_VOICE_FRAME_MS?.trim() === "40" ? 40 : 20,
|
||||
assumeCloudflare: parseBoolean(env.WEBSPEAK_ASSUME_CLOUDFLARE, false),
|
||||
autoRelayRetry: parseBoolean(env.WEBSPEAK_VOICE_AUTO_RELAY_RETRY, true),
|
||||
};
|
||||
}
|
||||
|
||||
/** 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,
|
||||
downlinkFrameMs: config.downlinkFrameMs,
|
||||
assumeCloudflare: config.assumeCloudflare,
|
||||
autoRelayRetry: config.autoRelayRetry,
|
||||
};
|
||||
}
|
||||
|
||||
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 } : {}),
|
||||
@@ -226,6 +258,10 @@ export class WebRtcAudioSession {
|
||||
};
|
||||
}
|
||||
|
||||
get isConnected(): boolean {
|
||||
return !this.closed && this.peer.connectionState === "connected";
|
||||
}
|
||||
|
||||
getStats(): WebRtcAudioStats {
|
||||
return { ...this.stats, webrtcQueueCurrentFrames: this.getQueueFrameCount() };
|
||||
}
|
||||
@@ -315,7 +351,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 +434,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 +459,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 +539,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,16 @@ 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;
|
||||
voiceDownlinkFrameMs?: 20 | 40;
|
||||
voiceAssumeCloudflare?: boolean;
|
||||
voiceAutoRelayRetry?: boolean;
|
||||
relaySettingsAction?: "keep" | "replace" | "remove";
|
||||
relayEnabled?: boolean;
|
||||
relayName?: string;
|
||||
|
||||
@@ -33,6 +33,15 @@ 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 ? true : boolean(value),
|
||||
voiceJitterMaxMs: value => value === undefined ? 300 : number(value),
|
||||
voiceDownlinkFrameMs: value => value === undefined ? 20 : value === 20 || value === 40 ? value : invalid(),
|
||||
voiceAssumeCloudflare: value => value === undefined ? false : boolean(value),
|
||||
voiceAutoRelayRetry: value => value === undefined ? true : boolean(value),
|
||||
relayConfigured: boolean, relayEnabled: boolean, relayName: text, relayTarget: text, hasRelayToken: boolean,
|
||||
relayNodes: array(relayNode), internalPort: number, updatedAt: text,
|
||||
});
|
||||
|
||||
@@ -13,6 +13,7 @@ test("all command payloads preserve request IDs through the shared parser", () =
|
||||
setWhisperTargets: { targetIds: [2, 3] }, setWhisperActive: { active: true },
|
||||
setMicrophoneMuted: { muted: false }, setAccompanimentActive: { active: true },
|
||||
setMemberVolume: { clientId: 2, volume: 0 }, latencyProbe: { sequence: "old" }, audioStatsProbe: { sequence: "new" },
|
||||
audioCaps: { downlinkVersion: 3, maxFrameMs: 40, codecs: ["pcm", "opus"] },
|
||||
};
|
||||
for (const [type, payload] of Object.entries(payloads)) {
|
||||
const command = { type, payload, requestId: "request-1" };
|
||||
|
||||
@@ -15,6 +15,7 @@ export interface ClientCommandPayloads {
|
||||
setMemberVolume: { clientId: number; volume: number };
|
||||
latencyProbe: { sequence: string };
|
||||
audioStatsProbe: { sequence: string };
|
||||
audioCaps: { downlinkVersion: 3; maxFrameMs: 20 | 40; codecs: ("pcm" | "opus")[] };
|
||||
}
|
||||
|
||||
export type ClientCommandType = keyof ClientCommandPayloads;
|
||||
@@ -37,7 +38,7 @@ export function parseClientCommand(raw: string): ClientCommandResult {
|
||||
if (value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length > 64)) {
|
||||
return { error: { code: "INVALID_REQUEST_ID", message: "请求标识无效" } };
|
||||
}
|
||||
const supportedTypes = new Set(["createInvite", "switchChannel", "moveClient", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe", "audioStatsProbe"]);
|
||||
const supportedTypes = new Set(["createInvite", "switchChannel", "moveClient", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe", "audioStatsProbe", "audioCaps"]);
|
||||
if (!supportedTypes.has(value.type)) {
|
||||
return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } };
|
||||
}
|
||||
@@ -110,6 +111,16 @@ export function parseClientCommand(raw: string): ClientCommandResult {
|
||||
if (value.type === "latencyProbe" && (typeof value.payload.sequence !== "string" || value.payload.sequence.length > 64)) {
|
||||
return { error: { code: "INVALID_LATENCY_PROBE", message: "延迟探测标识无效" } };
|
||||
}
|
||||
if (value.type === "audioCaps") {
|
||||
const payload = value.payload;
|
||||
const codecs = payload.codecs;
|
||||
if (payload.downlinkVersion !== 3 || (payload.maxFrameMs !== 20 && payload.maxFrameMs !== 40)
|
||||
|| !Array.isArray(codecs) || codecs.length < 1 || codecs.length > 2
|
||||
|| codecs.some(codec => codec !== "pcm" && codec !== "opus")
|
||||
|| new Set(codecs).size !== codecs.length) {
|
||||
return { error: { code: "INVALID_AUDIO_CAPS", message: "音频能力声明无效" } };
|
||||
}
|
||||
}
|
||||
return {
|
||||
type: value.type as ClientCommand["type"],
|
||||
...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}),
|
||||
|
||||
@@ -24,6 +24,7 @@ const samples: Record<ServerMessage["type"], ServerMessage> = {
|
||||
serverEvent: { type: "serverEvent", event },
|
||||
channelSwitched: { type: "channelSwitched", channelId: "1" },
|
||||
audioStats: { type: "audioStats", sequence: "probe", stats: parseVoiceAudioBridgeStats({})! },
|
||||
audioConfig: { type: "audioConfig", downlinkVersion: 3, frameMs: 20, uplinkCodecs: ["pcm", "opus"], jitterMaxMs: 300 },
|
||||
latencyPong: { type: "latencyPong", sequence: "legacy", teamSpeakLatencyMs: null, teamSpeakReachable: false, teamSpeakErrorCode: "TIMEOUT" },
|
||||
disconnected: { type: "disconnected", recoverable: false },
|
||||
reconnecting: { type: "reconnecting", attempt: 2, delayMs: 1_000 },
|
||||
@@ -60,12 +61,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,8 @@ type ChatFields = { invokerId?: number; invokerName?: string; message: string; t
|
||||
/** Public JSON messages. Internal sockets, SDK clients and media objects stay out. */
|
||||
export type ServerMessage =
|
||||
| Message<"inviteCreated", Request & { token: string; expiresAt: number }>
|
||||
| Message<"connected", { tsClientId: number; pluginSession?: string; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; 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"; voiceRelayAutoRetry?: boolean; audioFrameVersion?: 2; audioDownlinkVersions?: (2 | 3)[]; audioFrameMsOptions?: (20 | 40)[]; audioUplinkCodecs?: ("pcm" | "opus")[]; audioJitterMaxMs?: number; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }>
|
||||
| Message<"audioConfig", { downlinkVersion: 2 | 3; frameMs: 20 | 40; uplinkCodecs: ("pcm" | "opus")[]; jitterMaxMs: number }>
|
||||
| Message<"serverInfo", { name: string; icon?: string | null; bannerUrl?: string | null; welcomeMessage?: string }>
|
||||
| Message<"memberEnter", ChannelMember>
|
||||
| Message<"memberLeave", { id: number }>
|
||||
@@ -88,8 +90,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 +143,16 @@ 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.voiceRelayAutoRetry, boolean)
|
||||
&& optional(m.audioFrameVersion, v => v === 2)
|
||||
&& optional(m.audioDownlinkVersions, v => Array.isArray(v) && v.length > 0 && v.every(version => version === 2 || version === 3))
|
||||
&& optional(m.audioFrameMsOptions, v => Array.isArray(v) && v.length > 0 && v.every(ms => ms === 20 || ms === 40))
|
||||
&& optional(m.audioUplinkCodecs, v => Array.isArray(v) && v.length > 0 && v.every(codec => codec === "pcm" || codec === "opus"))
|
||||
&& optional(m.audioJitterMaxMs, v => finite(v) && Number.isInteger(v) && v >= 80 && v <= 500)
|
||||
&& optional(m.whisperTargetIds, v => arrayOf(v, clientId)) && optional(m.whisperActive, boolean) && optional(m.accelerated, boolean),
|
||||
serverInfo: m => text(m.name) && m.name.length <= 256
|
||||
&& optional(m.icon, v => v === null || (text(v) && v.length <= 180_000
|
||||
@@ -155,6 +170,11 @@ const valid: Record<ServerMessage["type"], (message: RecordValue) => boolean> =
|
||||
inviteCreated: m => text(m.token) && /^wi_[A-Za-z0-9_-]{43}$/.test(m.token) && typeof m.expiresAt === "number" && Number.isSafeInteger(m.expiresAt),
|
||||
channelSwitched: m => channelId(m.channelId),
|
||||
audioStats: m => text(m.sequence) && m.sequence.length <= 64 && isRecord(m.stats),
|
||||
audioConfig: m => (m.downlinkVersion === 2 || m.downlinkVersion === 3)
|
||||
&& (m.frameMs === 20 || m.frameMs === 40)
|
||||
&& Array.isArray(m.uplinkCodecs) && m.uplinkCodecs.length > 0 && m.uplinkCodecs.length <= 2
|
||||
&& m.uplinkCodecs.every(codec => codec === "pcm" || codec === "opus")
|
||||
&& finite(m.jitterMaxMs) && m.jitterMaxMs >= 80 && m.jitterMaxMs <= 500,
|
||||
latencyPong: m => text(m.sequence) && (m.teamSpeakLatencyMs === null || finite(m.teamSpeakLatencyMs)) && boolean(m.teamSpeakReachable)
|
||||
&& (m.teamSpeakErrorCode === null || text(m.teamSpeakErrorCode)),
|
||||
disconnected: m => optional(m.recoverable, boolean),
|
||||
@@ -191,6 +211,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") {
|
||||
|
||||
@@ -18,7 +18,8 @@ import {
|
||||
* - `icons`: bitmap overrides for stable icon slots, keyed by part name.
|
||||
* - `slots`: declarative anchors for trusted host controls. A skin never
|
||||
* receives the control; it only names a part it already renders so the
|
||||
* host can position its own top-layer capsule there and fall back to the
|
||||
* host can position its own top-layer capsule (or, with an explicit
|
||||
* `mode: "toolbar"`, chrome-less host buttons) there and fall back to the
|
||||
* default corner when the anchor stops being usable.
|
||||
*
|
||||
* Both the browser importer and the server-side registry parse the exact same
|
||||
@@ -29,6 +30,7 @@ export const SKIN_CHROME_MAX_BYTES = 32 * 1024;
|
||||
export const SKIN_CHROME_MAX_HIDDEN_PARTS = 32;
|
||||
export const SKIN_CHROME_MAX_ICONS = 16;
|
||||
export const SKIN_CHROME_MAX_SLOTS = 8;
|
||||
export const SKIN_CHROME_MAX_SLOT_ANCHORS = 8;
|
||||
export const SKIN_ICON_MAX_BYTES = 64 * 1024;
|
||||
export const SKIN_ICONS_MAX_TOTAL_BYTES = 512 * 1024;
|
||||
export const SKIN_ICON_DIRECTORY = "assets/icons/";
|
||||
@@ -72,13 +74,39 @@ export interface SkinChromeDocument {
|
||||
|
||||
export type SkinChromeSlotAlign = "start" | "center" | "end";
|
||||
|
||||
/**
|
||||
* How a slotted recovery control is presented:
|
||||
* - `capsule` (default): the existing rounded host capsule with its own shell.
|
||||
* - `toolbar`: independent, chrome-less host buttons that can match a skin's
|
||||
* top bar. The host still creates the buttons, their labels, focus and
|
||||
* click handlers; the skin only names anchors and style tokens.
|
||||
*
|
||||
* The mode is explicit and never inferred from `compact`: an old slot without
|
||||
* `mode` keeps docking the capsule exactly as before.
|
||||
*/
|
||||
export type SkinChromeSlotMode = "capsule" | "toolbar";
|
||||
|
||||
/** Toolbar buttons may show host-owned icons without losing their accessible names. */
|
||||
export type SkinChromeSlotAppearance = "label" | "icon" | "icon-and-label";
|
||||
|
||||
/** One anchor name, or ordered candidates (for example one per page). */
|
||||
export type SkinChromeSlotAnchor = string | string[];
|
||||
|
||||
export interface SkinChromeSlot {
|
||||
/** Existing `data-ws-part` inside `.ws-skin-root` used as the anchor box. */
|
||||
anchor: string;
|
||||
/**
|
||||
* Existing `data-ws-part` inside `.ws-skin-root` used as the anchor box.
|
||||
* A list lists page/component candidates: the host takes the first visible
|
||||
* one, so one slot can cover both the home and the voice page.
|
||||
*/
|
||||
anchor: SkinChromeSlotAnchor;
|
||||
/** Horizontal alignment inside the anchor; the control is vertically centred. */
|
||||
align: SkinChromeSlotAlign;
|
||||
/** Collapse to the mark only until hovered or focused. */
|
||||
/** Collapse to the mark only until hovered or focused (capsule mode only). */
|
||||
compact: boolean;
|
||||
/** Explicit presentation; see `SkinChromeSlotMode`. */
|
||||
mode: SkinChromeSlotMode;
|
||||
/** Toolbar-only label/icon shape; the host always supplies the icon and name. */
|
||||
appearance: SkinChromeSlotAppearance;
|
||||
}
|
||||
|
||||
export interface SkinChromeAssetInfo {
|
||||
@@ -147,10 +175,36 @@ function normalizeSlotAnchor(raw: unknown): string {
|
||||
return raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* A slot may name one anchor or an ordered candidate list (one per page or
|
||||
* per component variant). Candidates are validated exactly like a single
|
||||
* anchor; duplicates are removed so a page cannot be tried twice per check.
|
||||
*/
|
||||
function normalizeSlotAnchors(raw: unknown): SkinChromeSlotAnchor {
|
||||
if (!Array.isArray(raw)) return normalizeSlotAnchor(raw);
|
||||
if (!raw.length || raw.length > SKIN_CHROME_MAX_SLOT_ANCHORS) {
|
||||
return reject(`A slot anchor list must contain between 1 and ${SKIN_CHROME_MAX_SLOT_ANCHORS} part names.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
const anchors: string[] = [];
|
||||
for (const entry of raw) {
|
||||
const anchor = normalizeSlotAnchor(entry);
|
||||
if (!anchors.includes(anchor)) anchors.push(anchor);
|
||||
}
|
||||
return anchors;
|
||||
}
|
||||
|
||||
function isSlotMode(value: unknown): value is SkinChromeSlotMode {
|
||||
return value === "capsule" || value === "toolbar";
|
||||
}
|
||||
|
||||
function isSlotAlign(value: unknown): value is SkinChromeSlotAlign {
|
||||
return value === "start" || value === "center" || value === "end";
|
||||
}
|
||||
|
||||
function isSlotAppearance(value: unknown): value is SkinChromeSlotAppearance {
|
||||
return value === "label" || value === "icon" || value === "icon-and-label";
|
||||
}
|
||||
|
||||
export function parseSkinChromeDocument(source: string): SkinChromeDocument {
|
||||
const bytes = new TextEncoder().encode(source).byteLength;
|
||||
if (!bytes || bytes > SKIN_CHROME_MAX_BYTES) {
|
||||
@@ -226,20 +280,49 @@ export function parseSkinChromeDocument(source: string): SkinChromeDocument {
|
||||
return reject(`Slot ${part} must be an object.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
for (const key of Object.keys(value)) {
|
||||
if (key !== "anchor" && key !== "align" && key !== "compact") {
|
||||
if (key !== "anchor" && key !== "align" && key !== "compact" && key !== "mode" && key !== "appearance") {
|
||||
return reject(`Slot ${part} contains an unsupported field: ${key}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
}
|
||||
const anchor = normalizeSlotAnchor(value.anchor);
|
||||
const anchor = normalizeSlotAnchors(value.anchor);
|
||||
const align = value.align === undefined ? "end" : value.align;
|
||||
if (!isSlotAlign(align)) {
|
||||
return reject(`Slot ${part} has an invalid align value: ${String(align)}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
// The group slot keeps the historical capsule default. The two
|
||||
// single-action slots only exist for toolbar presentation; a one-button
|
||||
// capsule would be a new, ambiguous surface with no product need.
|
||||
const mode = value.mode === undefined
|
||||
? (part === "host.recovery" ? "capsule" : "toolbar")
|
||||
: value.mode;
|
||||
if (!isSlotMode(mode)) {
|
||||
return reject(`Slot ${part} has an invalid mode value: ${String(mode)}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
if (part !== "host.recovery" && mode !== "toolbar") {
|
||||
return reject(`Slot ${part} only supports toolbar mode.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
const compact = value.compact === undefined ? false : value.compact;
|
||||
if (typeof compact !== "boolean") {
|
||||
return reject(`Slot ${part} compact must be a boolean.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
slots[part] = { anchor, align, compact };
|
||||
if (mode === "toolbar" && compact) {
|
||||
return reject(`Slot ${part} compact is only valid in capsule mode.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
const appearance = value.appearance === undefined ? "label" : value.appearance;
|
||||
if (!isSlotAppearance(appearance)) {
|
||||
return reject(`Slot ${part} has an invalid appearance value: ${String(appearance)}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
if (mode !== "toolbar" && appearance !== "label") {
|
||||
return reject(`Slot ${part} appearance is only available in toolbar mode.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
slots[part] = { anchor, align, compact, mode, appearance };
|
||||
}
|
||||
const perAction = slots["host.recovery.built-in"] !== undefined || slots["host.recovery.library"] !== undefined;
|
||||
if (slots["host.recovery"] && perAction) {
|
||||
return reject(
|
||||
"Declare either host.recovery or its per-action slots (host.recovery.built-in / host.recovery.library), not both.",
|
||||
"SKIN_CHROME_SLOT_INVALID",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+102
-4
@@ -108,12 +108,15 @@ test("host-owned layer attributes are not skin hooks", () => {
|
||||
for (const attribute of [
|
||||
"data-ws-host-layer",
|
||||
"data-ws-host-recovery",
|
||||
"data-ws-host-recovery-toolbar",
|
||||
"data-ws-host-layer-content",
|
||||
"data-ws-recovery-action",
|
||||
]) {
|
||||
// A public hook in the same selector gets past the "must use a public hook"
|
||||
// check, so the attribute-name rejection is what stops the selector.
|
||||
assert.throws(() => compile(`:root [${attribute}] { display: none; }`), /host attribute/, attribute);
|
||||
// A :root-prefixed mixed selector with a public part hook must also fail.
|
||||
assert.throws(() => compile(`:root [data-ws-part="home.header"] [${attribute}] { color: red; }`), /host attribute/, attribute);
|
||||
assert.throws(() => compile(`[data-ws-part="home.header"] [${attribute}] { color: red; }`), /host attribute/, attribute);
|
||||
assert.throws(() => compile(`[data-ws-part="home.header"] [${attribute}="x"] { color: red; }`), /host attribute/, attribute);
|
||||
}
|
||||
@@ -121,6 +124,21 @@ test("host-owned layer attributes are not skin hooks", () => {
|
||||
assert.doesNotThrow(() => compile(':root [data-ws-part="home.header"] { color: teal; }'));
|
||||
});
|
||||
|
||||
test("the host toolbar's private class is not a skin hook", () => {
|
||||
for (const css of [
|
||||
':root .ws-host-toolbar { color: red; }',
|
||||
':root [data-ws-part="home.header"] .ws-host-toolbar { color: red; }',
|
||||
'[data-ws-part="home.header"] .ws-host-toolbar { color: red; }',
|
||||
'[data-ws-part="home.header"].ws-host-toolbar { color: red; }',
|
||||
':root .WS-HOST-TOOLBAR { color: red; }',
|
||||
':root .\\77 s-host-toolbar { color: red; }',
|
||||
]) {
|
||||
assert.throws(() => compile(css), /private host class/i, css);
|
||||
}
|
||||
// Ordinary descendant classes remain available when a public hook anchors them.
|
||||
assert.doesNotThrow(() => compile(':root [data-ws-part="home.header"] .skin-button { color: teal; }'));
|
||||
});
|
||||
|
||||
test("trusted, permission, recovery and essential audio controls stay available even for v3 skins", () => {
|
||||
for (const part of [
|
||||
"voice.audio-dock",
|
||||
@@ -197,22 +215,28 @@ test("chrome.json declares hidden parts and icon bitmaps, with path and size val
|
||||
});
|
||||
|
||||
test("chrome.json slots accept skin-owned anchors and reject trusted host UI", () => {
|
||||
assert.deepEqual([...HOST_SLOTTABLE_PART_IDS], ["host.recovery"]);
|
||||
assert.deepEqual([...HOST_SLOTTABLE_PART_IDS], [
|
||||
"host.recovery",
|
||||
"host.recovery.built-in",
|
||||
"host.recovery.library",
|
||||
]);
|
||||
|
||||
const explicit = parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: {
|
||||
"host.recovery": { anchor: "voice.audio-dock", align: "start", compact: true },
|
||||
"host.recovery": { anchor: "voice.audio-dock", align: "start", compact: true, appearance: "label" },
|
||||
},
|
||||
}));
|
||||
assert.deepEqual(explicit.slots?.["host.recovery"], {
|
||||
anchor: "voice.audio-dock",
|
||||
align: "start",
|
||||
compact: true,
|
||||
mode: "capsule",
|
||||
appearance: "label",
|
||||
});
|
||||
|
||||
// Defaults: align "end", compact off. Component and runtime-plugin parts are
|
||||
// ordinary anchors; only host/trusted parts are off limits.
|
||||
// Old slots without `mode` keep the docked capsule: the presentation is
|
||||
// explicit, never inferred from compact or any other field.
|
||||
const defaults = parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: {
|
||||
@@ -223,6 +247,8 @@ test("chrome.json slots accept skin-owned anchors and reject trusted host UI", (
|
||||
anchor: "skin.voice.harbor-dock.part-anchor",
|
||||
align: "end",
|
||||
compact: false,
|
||||
mode: "capsule",
|
||||
appearance: "label",
|
||||
});
|
||||
assert.doesNotThrow(() => parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
@@ -246,6 +272,78 @@ test("chrome.json slots accept skin-owned anchors and reject trusted host UI", (
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "../escape" } } }, /not a valid part name/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "Voice Audio Dock" } } }, /not a valid part name/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "" } } }, /at most 240 characters/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", mode: "float" } } }, /invalid mode/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", mode: "toolbar", appearance: "text" } } }, /invalid appearance/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", appearance: "icon" } } }, /appearance is only available in toolbar mode/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", mode: "capsule", appearance: "icon-and-label" } } }, /appearance is only available in toolbar mode/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", mode: "toolbar", compact: true } } }, /compact is only valid in capsule mode/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery.built-in": { anchor: "voice.audio-dock", mode: "capsule" } } }, /only supports toolbar mode/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery.built-in": { anchor: "voice.audio-dock", compact: true } } }, /compact is only valid in capsule mode/],
|
||||
];
|
||||
for (const [value, message] of invalidDocuments) {
|
||||
assert.throws(() => parseSkinChromeDocument(JSON.stringify(value)), message, JSON.stringify(value));
|
||||
}
|
||||
});
|
||||
|
||||
test("chrome.json toolbar slots support page candidates and separate action buttons", () => {
|
||||
const toolbar = parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: {
|
||||
"host.recovery": {
|
||||
mode: "toolbar",
|
||||
anchor: [
|
||||
"skin.home.topbar.part-host-actions",
|
||||
"skin.voice.topbar.part-host-actions",
|
||||
"skin.home.topbar.part-host-actions",
|
||||
],
|
||||
align: "end",
|
||||
appearance: "icon",
|
||||
},
|
||||
},
|
||||
}));
|
||||
assert.deepEqual(toolbar.slots?.["host.recovery"], {
|
||||
anchor: [
|
||||
"skin.home.topbar.part-host-actions",
|
||||
"skin.voice.topbar.part-host-actions",
|
||||
],
|
||||
align: "end",
|
||||
compact: false,
|
||||
mode: "toolbar",
|
||||
appearance: "icon",
|
||||
});
|
||||
|
||||
const perAction = parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: {
|
||||
"host.recovery.built-in": {
|
||||
mode: "toolbar",
|
||||
anchor: "skin.voice.topbar.part-built-in",
|
||||
align: "start",
|
||||
appearance: "icon-and-label",
|
||||
},
|
||||
"host.recovery.library": {
|
||||
mode: "toolbar",
|
||||
anchor: "skin.voice.topbar.part-library",
|
||||
},
|
||||
},
|
||||
}));
|
||||
assert.deepEqual(perAction.slots?.["host.recovery.built-in"], {
|
||||
anchor: "skin.voice.topbar.part-built-in",
|
||||
align: "start",
|
||||
compact: false,
|
||||
mode: "toolbar",
|
||||
appearance: "icon-and-label",
|
||||
});
|
||||
// Single-action slots are toolbar-only and default to toolbar mode.
|
||||
assert.equal(perAction.slots?.["host.recovery.library"]?.mode, "toolbar");
|
||||
assert.equal(perAction.slots?.["host.recovery.library"]?.align, "end");
|
||||
assert.equal(perAction.slots?.["host.recovery.library"]?.appearance, "label");
|
||||
|
||||
const invalidDocuments: Array<[unknown, RegExp]> = [
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { mode: "toolbar", anchor: [] } } }, /between 1 and 8/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { mode: "toolbar", anchor: Array.from({ length: 9 }, (_, index) => `part-${index}`) } } }, /between 1 and 8/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { mode: "toolbar", anchor: ["voice.audio-dock", "host.plugins.launcher"] } } }, /trusted host UI/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { mode: "toolbar", anchor: "voice.audio-dock" }, "host.recovery.built-in": { mode: "toolbar", anchor: "voice.audio-dock" } } }, /either host.recovery or its per-action slots/],
|
||||
];
|
||||
for (const [value, message] of invalidDocuments) {
|
||||
assert.throws(() => parseSkinChromeDocument(JSON.stringify(value)), message, JSON.stringify(value));
|
||||
|
||||
@@ -104,9 +104,11 @@ const FORBIDDEN_SCOPE_ATTRIBUTES = new Set([
|
||||
// opting into the element by attribute.
|
||||
"data-ws-host-layer",
|
||||
"data-ws-host-recovery",
|
||||
"data-ws-host-recovery-toolbar",
|
||||
"data-ws-host-layer-content",
|
||||
"data-ws-recovery-action",
|
||||
]);
|
||||
const FORBIDDEN_SCOPE_CLASSES = new Set(["ws-host-toolbar"]);
|
||||
/** CSS-wide keywords never name a keyframe and reset an animatable slot. */
|
||||
const CSS_WIDE_KEYWORDS = new Set(["initial", "inherit", "unset", "revert", "revert-layer"]);
|
||||
/** Shorthand keyword slots; a repeated category frees the word to be the name. */
|
||||
@@ -456,6 +458,9 @@ function assertHostChromeSelector(selector: string, schemaVersion: SkinCssSchema
|
||||
if (node.type === "attribute" && FORBIDDEN_SCOPE_ATTRIBUTES.has(node.attribute.toLowerCase())) {
|
||||
throw new SkinCssValidationError(`Skin selectors cannot reference the host attribute ${node.attribute}.`, "SKIN_CSS_SELECTOR");
|
||||
}
|
||||
if (node.type === "class" && FORBIDDEN_SCOPE_CLASSES.has(decodeCssEscapes(node.value).toLowerCase())) {
|
||||
throw new SkinCssValidationError(`Skin selectors cannot reference the private host class .${node.value}.`, "SKIN_CSS_SELECTOR");
|
||||
}
|
||||
if (node.type === "attribute" && node.attribute.toLowerCase() === "data-ws-part" && node.value) {
|
||||
partNames.push(node.value.replace(/^['"]|['"]$/g, ""));
|
||||
}
|
||||
|
||||
@@ -47,11 +47,18 @@ export const HOST_TRUSTED_PART_IDS: ReadonlySet<string> = new Set([
|
||||
* Trusted host controls that an open skin may fold into its own layout through
|
||||
* `chrome.json#slots`. The key names the protected part, not a CSS hook: the
|
||||
* skin only declares an anchor rectangle, the host still owns, paints and
|
||||
* hit-tests the control. Extend this set (for example with `host.permission`)
|
||||
* when another protected control learns the same runtime placement.
|
||||
* hit-tests the control.
|
||||
*
|
||||
* `host.recovery` is the historical capsule group. The two action keys only
|
||||
* exist for `mode: "toolbar"` and let a skin dock the "use built-in skin" and
|
||||
* "application library" host buttons separately; they are still host-owned
|
||||
* buttons, never DOM hooks. Extend this set when another protected control
|
||||
* learns the same runtime placement.
|
||||
*/
|
||||
export const HOST_SLOTTABLE_PART_IDS: ReadonlySet<string> = new Set([
|
||||
"host.recovery",
|
||||
"host.recovery.built-in",
|
||||
"host.recovery.library",
|
||||
]);
|
||||
|
||||
/** All host-owned parts (used by the part registry and documentation). */
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
decodeVoiceBatch,
|
||||
encodeVoiceBatch,
|
||||
VOICE_BATCH_HEADER_BYTES,
|
||||
VOICE_BATCH_TAG,
|
||||
VOICE_MAX_OPUS_FRAME_BYTES,
|
||||
} from "./voice-audio.js";
|
||||
|
||||
test("voice batch round-trips the audio clock and per-speaker entries", () => {
|
||||
const encoded = encodeVoiceBatch(123_456, [
|
||||
{ codec: 4, clientId: 2, seq: 7, data: Uint8Array.from([1, 2, 3]) },
|
||||
{ codec: 5, clientId: 65_535, seq: 255, data: Uint8Array.from([9]) },
|
||||
]);
|
||||
assert.ok(encoded);
|
||||
assert.equal(encoded[0], VOICE_BATCH_TAG);
|
||||
assert.equal(encoded[1], 2);
|
||||
assert.equal(encoded.length, VOICE_BATCH_HEADER_BYTES + (6 + 3) + (6 + 1));
|
||||
const decoded = decodeVoiceBatch(encoded);
|
||||
assert.ok(decoded);
|
||||
assert.equal(decoded.audioStartMs, 123_456);
|
||||
assert.deepEqual(decoded.entries.map(({ codec, clientId, seq, data }) => ({ codec, clientId, seq, data: [...data] })), [
|
||||
{ codec: 4, clientId: 2, seq: 7, data: [1, 2, 3] },
|
||||
{ codec: 5, clientId: 65_535, seq: 255, data: [9] },
|
||||
]);
|
||||
});
|
||||
|
||||
test("voice batch rejects framing the decoder could not reproduce", () => {
|
||||
const good = encodeVoiceBatch(1, [{ codec: 4, clientId: 2, seq: 1, data: Uint8Array.from([1, 2, 3]) }])!;
|
||||
assert.equal(decodeVoiceBatch(Uint8Array.from([...good, 0])), null, "trailing byte");
|
||||
assert.equal(decodeVoiceBatch(Uint8Array.from([0xf2, ...good.subarray(1)])), null, "wrong tag");
|
||||
assert.equal(decodeVoiceBatch(Uint8Array.from([good[0]!, 0, ...good.subarray(2)])), null, "zero entries");
|
||||
const truncated = good.slice(0, -1);
|
||||
assert.equal(decodeVoiceBatch(truncated), null, "truncated payload");
|
||||
assert.equal(encodeVoiceBatch(1, []), null);
|
||||
assert.equal(encodeVoiceBatch(1, [{ codec: 4, clientId: 0, seq: 1, data: Uint8Array.from([1]) }]), null);
|
||||
assert.equal(encodeVoiceBatch(1, [{ codec: 4, clientId: 1, seq: 1, data: new Uint8Array(VOICE_MAX_OPUS_FRAME_BYTES + 1) }]), null);
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
/** 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;
|
||||
|
||||
/**
|
||||
* Downlink batch tag. Deliberately outside the TeamSpeak codec range (0-5) and
|
||||
* above the uplink tags so a legacy client drops the packet instead of trying
|
||||
* to decode the batch header as Opus.
|
||||
*/
|
||||
export const VOICE_BATCH_TAG = 0xf3;
|
||||
export const VOICE_BATCH_HEADER_BYTES = 6;
|
||||
export const VOICE_BATCH_MAX_ENTRIES = 32;
|
||||
export const VOICE_BATCH_MAX_BYTES = 16 * 1024;
|
||||
|
||||
export interface VoiceBatchEntry {
|
||||
codec: number;
|
||||
clientId: number;
|
||||
/** Per-speaker 8-bit sequence; wraps every 256 packets. */
|
||||
seq: number;
|
||||
data: Uint8Array;
|
||||
}
|
||||
|
||||
export interface DecodedVoiceBatch {
|
||||
audioStartMs: number;
|
||||
entries: VoiceBatchEntry[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode one downlink batch:
|
||||
* 0xF3 | count:u8 | audioStartMs:u32be | entries
|
||||
* entry: codec:u8 | clientId:u16be | seq:u8 | length:u16be | payload
|
||||
*
|
||||
* Returns null when the caller supplied something that would not decode
|
||||
* identically (bad id/length, too many entries, oversized batch).
|
||||
*/
|
||||
export function encodeVoiceBatch(audioStartMs: number, entries: readonly VoiceBatchEntry[]): Uint8Array | null {
|
||||
if (entries.length < 1 || entries.length > VOICE_BATCH_MAX_ENTRIES) return null;
|
||||
let total = VOICE_BATCH_HEADER_BYTES;
|
||||
for (const entry of entries) {
|
||||
if (!Number.isInteger(entry.codec) || entry.codec < 0 || entry.codec > 255
|
||||
|| !Number.isInteger(entry.clientId) || entry.clientId < 1 || entry.clientId > 65_535
|
||||
|| !Number.isInteger(entry.seq) || entry.seq < 0 || entry.seq > 255
|
||||
|| entry.data.length < 1 || entry.data.length > VOICE_MAX_OPUS_FRAME_BYTES) return null;
|
||||
total += 6 + entry.data.length;
|
||||
if (total > VOICE_BATCH_MAX_BYTES) return null;
|
||||
}
|
||||
const out = new Uint8Array(total);
|
||||
const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
|
||||
out[0] = VOICE_BATCH_TAG;
|
||||
out[1] = entries.length;
|
||||
view.setUint32(2, Math.max(0, Math.floor(audioStartMs)) >>> 0, false);
|
||||
let offset = VOICE_BATCH_HEADER_BYTES;
|
||||
for (const entry of entries) {
|
||||
out[offset] = entry.codec;
|
||||
view.setUint16(offset + 1, entry.clientId, false);
|
||||
out[offset + 3] = entry.seq;
|
||||
view.setUint16(offset + 4, entry.data.length, false);
|
||||
out.set(entry.data, offset + 6);
|
||||
offset += 6 + entry.data.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Strict decoder; returns null for anything the encoder would not have produced. */
|
||||
export function decodeVoiceBatch(packet: Uint8Array): DecodedVoiceBatch | null {
|
||||
if (packet.length < VOICE_BATCH_HEADER_BYTES + 7 || packet[0] !== VOICE_BATCH_TAG) return null;
|
||||
const count = packet[1]!;
|
||||
if (count < 1 || count > VOICE_BATCH_MAX_ENTRIES) return null;
|
||||
const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
|
||||
const audioStartMs = view.getUint32(2, false);
|
||||
const entries: VoiceBatchEntry[] = [];
|
||||
let offset = VOICE_BATCH_HEADER_BYTES;
|
||||
for (let i = 0; i < count; i++) {
|
||||
if (offset + 6 > packet.length) return null;
|
||||
const codec = packet[offset]!;
|
||||
const clientId = view.getUint16(offset + 1, false);
|
||||
const seq = packet[offset + 3]!;
|
||||
const length = view.getUint16(offset + 4, false);
|
||||
if (clientId < 1 || length < 1 || length > VOICE_MAX_OPUS_FRAME_BYTES) return null;
|
||||
const start = offset + 6;
|
||||
const end = start + length;
|
||||
if (end > packet.length) return null;
|
||||
entries.push({ codec, clientId, seq, data: packet.subarray(start, end) });
|
||||
offset = end;
|
||||
}
|
||||
// Trailing bytes mean the sender and receiver disagree about the framing.
|
||||
if (offset !== packet.length) return null;
|
||||
return { audioStartMs, entries };
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
apply plugin: 'com.android.application'
|
||||
|
||||
def appVersion = project.hasProperty('appVersion') ? project.property('appVersion').toString() : '0.3.3'
|
||||
def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 303
|
||||
def appVersion = project.hasProperty('appVersion') ? project.property('appVersion').toString() : '0.3.4-dev.0'
|
||||
def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 304
|
||||
|
||||
android {
|
||||
namespace = "io.webspeak.client"
|
||||
|
||||
Generated
+2
-2
@@ -25,7 +25,7 @@
|
||||
"vite": "^6.4.3",
|
||||
"vue-tsc": "^2.2.8"
|
||||
},
|
||||
"version": "0.3.3"
|
||||
"version": "0.3.4-dev.0"
|
||||
},
|
||||
"node_modules/@babel/helper-string-parser": {
|
||||
"version": "7.27.1",
|
||||
@@ -2952,5 +2952,5 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"version": "0.3.3"
|
||||
"version": "0.3.4-dev.0"
|
||||
}
|
||||
+1
-1
@@ -27,5 +27,5 @@
|
||||
"vite": "^6.4.3",
|
||||
"vue-tsc": "^2.2.8"
|
||||
},
|
||||
"version": "0.3.3"
|
||||
"version": "0.3.4-dev.0"
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,22 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { zipSync } from "fflate";
|
||||
|
||||
// Classic release 4.1.16 layout: the five package files sit at the ZIP root,
|
||||
// in this order, and the archive also carries the skin's chrome.json.
|
||||
const sourceDirectory = new URL("../../docs/examples/ts3-classic-console/", import.meta.url);
|
||||
const sourceFiles = ["manifest.json", "skin.css", "content.json", "components.json", "chrome.json"];
|
||||
const files = Object.fromEntries(await Promise.all(sourceFiles.map(async (name) => [
|
||||
name,
|
||||
await readFile(new URL(name, sourceDirectory)),
|
||||
])));
|
||||
// Fixed ZIP timestamp (local-component constructor, independent of the build
|
||||
// machine's time zone) so rebuilding reproduces the published 4.1.16 archive
|
||||
// byte for byte instead of stamping the current time.
|
||||
const releaseTimestamp = new Date(2026, 11, 4, 13, 10, 52);
|
||||
const archive = zipSync(files, { level: 9, mtime: releaseTimestamp });
|
||||
|
||||
await Promise.all([
|
||||
writeFile(fileURLToPath(new URL("../../docs/examples/ts3-classic-console.wskin", import.meta.url)), archive),
|
||||
writeFile(fileURLToPath(new URL("../public/skins/ts3-classic-console.wskin", import.meta.url)), archive),
|
||||
]);
|
||||
@@ -3,8 +3,11 @@ import { deflateSync } from "node:zlib";
|
||||
import { zipSync, strToU8 } from "fflate";
|
||||
|
||||
const source = new URL("../../docs/examples/host-chrome-demo/", import.meta.url);
|
||||
const toolbarSource = new URL("../../docs/examples/host-chrome-toolbar/", import.meta.url);
|
||||
const examples = new URL("../../docs/examples/", import.meta.url);
|
||||
const publicDir = new URL("../public/", import.meta.url);
|
||||
// Keep rebuilt archives byte-stable when their inputs do not change.
|
||||
const archiveMtime = new Date(2026, 10, 15, 16, 33, 0);
|
||||
|
||||
const crcTable = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
@@ -66,12 +69,20 @@ const icons = {
|
||||
"assets/icons/status.png": iconPng([150, 60, 90], [84, 28, 52]),
|
||||
};
|
||||
|
||||
const [manifestText, cssText, chromeText] = await Promise.all([
|
||||
const [manifestText, cssText, chromeText, toolbarManifestText, toolbarCssText, toolbarChromeText] = await Promise.all([
|
||||
readFile(new URL("manifest.json", source), "utf8"),
|
||||
readFile(new URL("skin.css", source)),
|
||||
readFile(new URL("chrome.json", source), "utf8"),
|
||||
readFile(new URL("manifest.json", toolbarSource), "utf8"),
|
||||
readFile(new URL("skin.css", toolbarSource)),
|
||||
readFile(new URL("chrome.json", toolbarSource), "utf8"),
|
||||
]);
|
||||
|
||||
const toolbarManifest = JSON.parse(toolbarManifestText);
|
||||
if (toolbarManifest.author !== "WebSpeak Community") {
|
||||
throw new Error("host-chrome-toolbar manifest author must be WebSpeak Community");
|
||||
}
|
||||
|
||||
const chrome = JSON.parse(chromeText);
|
||||
const sharedFiles = {
|
||||
"skin.css": new Uint8Array(cssText),
|
||||
@@ -85,20 +96,30 @@ const themed = zipSync({
|
||||
"manifest.json": strToU8(themedManifest),
|
||||
"chrome.json": strToU8(themedChrome),
|
||||
...sharedFiles,
|
||||
}, { level: 9 });
|
||||
}, { level: 9, mtime: archiveMtime });
|
||||
|
||||
// Variant B: the same package plus declarative hiding of non-critical chrome.
|
||||
const hidden = zipSync({
|
||||
"manifest.json": strToU8(manifestText),
|
||||
"chrome.json": strToU8(chromeText),
|
||||
...sharedFiles,
|
||||
}, { level: 9 });
|
||||
}, { level: 9, mtime: archiveMtime });
|
||||
|
||||
// Minimal toolbar-mode sample: host-owned recovery buttons docked into the
|
||||
// header, with page-wide anchor candidates and toolbar tokens.
|
||||
const toolbar = zipSync({
|
||||
"manifest.json": strToU8(toolbarManifestText),
|
||||
"chrome.json": strToU8(toolbarChromeText),
|
||||
"skin.css": new Uint8Array(toolbarCssText),
|
||||
}, { level: 9, mtime: archiveMtime });
|
||||
|
||||
await Promise.all([
|
||||
writeFile(new URL("host-chrome-themed.wskin", examples), themed),
|
||||
writeFile(new URL("host-chrome-demo.wskin", examples), hidden),
|
||||
writeFile(new URL("host-chrome-toolbar.wskin", examples), toolbar),
|
||||
writeFile(new URL("host-chrome-themed.wskin", publicDir), themed),
|
||||
writeFile(new URL("host-chrome-demo.wskin", publicDir), hidden),
|
||||
writeFile(new URL("host-chrome-toolbar.wskin", publicDir), toolbar),
|
||||
]);
|
||||
|
||||
console.log(`Built host chrome demo skins (${themed.byteLength} / ${hidden.byteLength} bytes) into docs/examples and web/public.`);
|
||||
console.log(`Built host chrome demo skins (${themed.byteLength} / ${hidden.byteLength} / ${toolbar.byteLength} bytes) into docs/examples and web/public.`);
|
||||
@@ -28,8 +28,125 @@
|
||||
<!-- Trusted recovery entry. It lives in a closed shadow root and a manual
|
||||
popover, so no compiled skin selector can target it (shadow boundary)
|
||||
and no normal stacking context can cover it (top layer). It carries no
|
||||
`data-ws-part`: there is intentionally no skin hook for this control. -->
|
||||
`data-ws-part`: there is intentionally no skin hook for this control.
|
||||
|
||||
With an explicit `chrome.json` `mode: "toolbar"` the host paints plain
|
||||
host buttons instead of the capsule shell. The buttons are still owned,
|
||||
labelled, focusable and clickable by the host; the skin only supplies
|
||||
an anchor and style tokens. -->
|
||||
<Teleport v-if="layer" :to="layer.container">
|
||||
<!-- One grouped toolbar entry: both actions share an anchor. -->
|
||||
<div
|
||||
v-if="groupToolbarConfig"
|
||||
ref="groupToolbarElement"
|
||||
popover="manual"
|
||||
class="ws-host-toolbar"
|
||||
data-ws-host-recovery-toolbar
|
||||
role="group"
|
||||
:aria-label="copy.recovery"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="ws-host-toolbar-action"
|
||||
:class="{ 'ws-host-toolbar-action-icon': groupToolbarConfig.appearance === 'icon' }"
|
||||
data-ws-recovery-action="built-in"
|
||||
:aria-label="copy.useBuiltIn"
|
||||
:title="copy.shortcut"
|
||||
@click="useBuiltInSkin"
|
||||
>
|
||||
<span v-if="groupToolbarConfig.appearance !== 'label'" class="ws-host-toolbar-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" focusable="false">
|
||||
<path d="M8 2.2a5.8 5.8 0 1 0 0 11.6h.9a1.5 1.5 0 0 0 .7-2.83 1.2 1.2 0 0 1 .6-2.25H12A2 2 0 0 0 14 6.8C14 4.1 11.3 2.2 8 2.2Z"/>
|
||||
<circle cx="5" cy="6" r=".7" fill="currentColor" stroke="none"/>
|
||||
<circle cx="7.2" cy="4.6" r=".7" fill="currentColor" stroke="none"/>
|
||||
<circle cx="10" cy="4.9" r=".7" fill="currentColor" stroke="none"/>
|
||||
</svg>
|
||||
</span>
|
||||
<span v-if="groupToolbarConfig.appearance !== 'icon'" class="ws-host-toolbar-label">{{ copy.useBuiltIn }}</span>
|
||||
</button>
|
||||
<button
|
||||
v-if="pluginLibraryAvailable"
|
||||
type="button"
|
||||
class="ws-host-toolbar-action"
|
||||
:class="{ 'ws-host-toolbar-action-icon': groupToolbarConfig.appearance === 'icon' }"
|
||||
data-ws-recovery-action="library"
|
||||
:aria-label="copy.library"
|
||||
:title="copy.library"
|
||||
@click="openLibrary"
|
||||
>
|
||||
<span v-if="groupToolbarConfig.appearance !== 'label'" class="ws-host-toolbar-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" focusable="false">
|
||||
<rect x="2.2" y="2.2" width="4.6" height="4.6" rx=".8"/>
|
||||
<rect x="9.2" y="2.2" width="4.6" height="4.6" rx=".8"/>
|
||||
<rect x="2.2" y="9.2" width="4.6" height="4.6" rx=".8"/>
|
||||
<rect x="9.2" y="9.2" width="4.6" height="4.6" rx=".8"/>
|
||||
</svg>
|
||||
</span>
|
||||
<span v-if="groupToolbarConfig.appearance !== 'icon'" class="ws-host-toolbar-label">{{ copy.library }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Per-action toolbar entries: each action has its own anchor. -->
|
||||
<div
|
||||
v-if="builtInToolbarConfig"
|
||||
ref="builtInToolbarElement"
|
||||
popover="manual"
|
||||
class="ws-host-toolbar"
|
||||
data-ws-host-recovery-toolbar
|
||||
role="group"
|
||||
:aria-label="copy.recovery"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="ws-host-toolbar-action"
|
||||
:class="{ 'ws-host-toolbar-action-icon': builtInToolbarConfig.appearance === 'icon' }"
|
||||
data-ws-recovery-action="built-in"
|
||||
:aria-label="copy.useBuiltIn"
|
||||
:title="copy.shortcut"
|
||||
@click="useBuiltInSkin"
|
||||
>
|
||||
<span v-if="builtInToolbarConfig.appearance !== 'label'" class="ws-host-toolbar-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" focusable="false">
|
||||
<path d="M8 2.2a5.8 5.8 0 1 0 0 11.6h.9a1.5 1.5 0 0 0 .7-2.83 1.2 1.2 0 0 1 .6-2.25H12A2 2 0 0 0 14 6.8C14 4.1 11.3 2.2 8 2.2Z"/>
|
||||
<circle cx="5" cy="6" r=".7" fill="currentColor" stroke="none"/>
|
||||
<circle cx="7.2" cy="4.6" r=".7" fill="currentColor" stroke="none"/>
|
||||
<circle cx="10" cy="4.9" r=".7" fill="currentColor" stroke="none"/>
|
||||
</svg>
|
||||
</span>
|
||||
<span v-if="builtInToolbarConfig.appearance !== 'icon'" class="ws-host-toolbar-label">{{ copy.useBuiltIn }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="libraryToolbarConfig"
|
||||
ref="libraryToolbarElement"
|
||||
popover="manual"
|
||||
class="ws-host-toolbar"
|
||||
data-ws-host-recovery-toolbar
|
||||
role="group"
|
||||
:aria-label="copy.recovery"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="ws-host-toolbar-action"
|
||||
:class="{ 'ws-host-toolbar-action-icon': libraryToolbarConfig.appearance === 'icon' }"
|
||||
data-ws-recovery-action="library"
|
||||
:aria-label="copy.library"
|
||||
:title="copy.library"
|
||||
@click="openLibrary"
|
||||
>
|
||||
<span v-if="libraryToolbarConfig.appearance !== 'label'" class="ws-host-toolbar-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" focusable="false">
|
||||
<rect x="2.2" y="2.2" width="4.6" height="4.6" rx=".8"/>
|
||||
<rect x="9.2" y="2.2" width="4.6" height="4.6" rx=".8"/>
|
||||
<rect x="2.2" y="9.2" width="4.6" height="4.6" rx=".8"/>
|
||||
<rect x="9.2" y="9.2" width="4.6" height="4.6" rx=".8"/>
|
||||
</svg>
|
||||
</span>
|
||||
<span v-if="libraryToolbarConfig.appearance !== 'icon'" class="ws-host-toolbar-label">{{ copy.library }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref="recoveryPopover"
|
||||
popover="manual"
|
||||
@@ -38,7 +155,7 @@
|
||||
@focusout="onRecoveryFocusOut"
|
||||
class="ws-host-recovery"
|
||||
:class="{ 'ws-host-recovery-compact': compact }"
|
||||
:data-ws-float="slotMode === 'slotted' ? undefined : floatPosition"
|
||||
:data-ws-float="capsuleSlotConfig && slotMode === 'slotted' ? undefined : floatPosition"
|
||||
:tabindex="compact || compactPinned ? 0 : undefined"
|
||||
data-ws-host-recovery
|
||||
role="region"
|
||||
@@ -46,6 +163,7 @@
|
||||
>
|
||||
<span class="ws-host-recovery-mark" aria-hidden="true">◈</span>
|
||||
<button
|
||||
v-if="capsuleActions.includes('built-in')"
|
||||
type="button"
|
||||
class="ws-host-recovery-action"
|
||||
data-ws-recovery-action="built-in"
|
||||
@@ -53,9 +171,9 @@
|
||||
@click="useBuiltInSkin"
|
||||
>{{ copy.useBuiltIn }}</button>
|
||||
<button
|
||||
v-if="capsuleActions.includes('library') && pluginLibraryAvailable"
|
||||
type="button"
|
||||
class="ws-host-recovery-action"
|
||||
v-if="pluginLibraryAvailable"
|
||||
data-ws-recovery-action="library"
|
||||
:title="copy.library"
|
||||
@click="openLibrary"
|
||||
@@ -65,8 +183,9 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch, watchEffect, type Ref } from "vue";
|
||||
import type { SiteLanguage } from "../../../src/site-copy.js";
|
||||
import type { SkinChromeSlot } from "../../../src/shared/skin-chrome.js";
|
||||
import { hostChromeCopy } from "../i18n/host-chrome.js";
|
||||
import {
|
||||
activeHostSlot,
|
||||
@@ -77,6 +196,7 @@ import {
|
||||
isThirdPartySkinActive,
|
||||
openPluginLibrary,
|
||||
requestBuiltInSkin,
|
||||
setInlineLibraryEntryVisible,
|
||||
} from "../services/host-chrome.js";
|
||||
import {
|
||||
createHostOwnedLayer,
|
||||
@@ -89,13 +209,16 @@ import {
|
||||
type FloatingAvoidance,
|
||||
type FloatingPosition,
|
||||
} from "../services/host-floating-placement.js";
|
||||
import { shouldShowRecovery } from "../services/host-chrome-visibility.js";
|
||||
import { shouldShowRecovery, type HostPartRect } from "../services/host-chrome-visibility.js";
|
||||
import { thirdPartyAllowed } from "../services/instance-authorization.js";
|
||||
import {
|
||||
RECOVERY_CONTROL_DEFAULTS,
|
||||
bindHostControlTheme,
|
||||
findSkinRoot,
|
||||
} from "../services/host-control-tokens.js";
|
||||
import {
|
||||
resolveHostRecoveryPresentation,
|
||||
} from "../services/host-recovery-presentation.js";
|
||||
|
||||
const props = withDefaults(defineProps<{ language: SiteLanguage; connected?: boolean; pluginLibraryAvailable?: boolean }>(), { connected: false });
|
||||
const copy = computed(() => hostChromeCopy[props.language] ?? hostChromeCopy.en);
|
||||
@@ -164,8 +287,70 @@ const RECOVERY_LAYER_CSS = `
|
||||
min-height: var(--ws-control-hit, 28px);
|
||||
}
|
||||
.ws-host-recovery.ws-host-recovery-compact:focus-visible { outline: 2px solid var(--ws-control-accent, #4c8f88); outline-offset: 2px; }
|
||||
|
||||
/* Toolbar mode: no capsule shell, margin, border or fixed shadow. The wrapper
|
||||
only lays the host buttons out; every visible surface comes from the
|
||||
--ws-toolbar-* variables resolved from the skin's validated tokens. */
|
||||
.ws-host-toolbar {
|
||||
position: fixed;
|
||||
inset: auto;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--ws-toolbar-gap, 4px);
|
||||
max-width: calc(100vw - 8px);
|
||||
pointer-events: auto;
|
||||
}
|
||||
.ws-host-toolbar:popover-open { display: flex; }
|
||||
.ws-host-toolbar-action {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
box-sizing: border-box;
|
||||
min-height: var(--ws-toolbar-min-height, var(--ws-control-hit, 28px));
|
||||
max-width: min(320px, calc(100vw - 8px));
|
||||
padding: var(--ws-toolbar-padding-y, 6px) var(--ws-toolbar-padding-x, 12px);
|
||||
border: 1px solid var(--ws-toolbar-border, #9db6b2);
|
||||
border-radius: var(--ws-toolbar-radius, 6px);
|
||||
background: var(--ws-toolbar-background, #fff);
|
||||
color: var(--ws-toolbar-foreground, #31524f);
|
||||
box-shadow: var(--ws-toolbar-shadow, none);
|
||||
font-family: var(--ws-toolbar-font, ui-sans-serif, system-ui, sans-serif);
|
||||
font-size: var(--ws-toolbar-font-size, 11px);
|
||||
line-height: 1.25;
|
||||
text-align: center;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
cursor: pointer;
|
||||
touch-action: manipulation;
|
||||
}
|
||||
.ws-host-toolbar-action:hover {
|
||||
border-color: var(--ws-toolbar-hover-border, var(--ws-toolbar-border, #9db6b2));
|
||||
background: var(--ws-toolbar-hover-background, var(--ws-toolbar-background, #fff));
|
||||
}
|
||||
.ws-host-toolbar-action:focus-visible {
|
||||
outline: 2px solid var(--ws-toolbar-focus, var(--ws-control-accent, #4c8f88));
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.ws-host-toolbar-icon {
|
||||
display: block;
|
||||
flex: 0 0 auto;
|
||||
width: var(--ws-toolbar-icon-size, 16px);
|
||||
height: var(--ws-toolbar-icon-size, 16px);
|
||||
}
|
||||
.ws-host-toolbar-icon svg { display: block; width: 100%; height: 100%; }
|
||||
.ws-host-toolbar-action-icon {
|
||||
width: max(24px, calc(var(--ws-toolbar-icon-size, 16px) + 8px));
|
||||
padding: 0;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ws-host-recovery, .ws-host-recovery button { transition: none !important; }
|
||||
.ws-host-recovery, .ws-host-recovery button, .ws-host-toolbar-action { transition: none !important; }
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -190,14 +375,32 @@ const showRecovery = computed(() => shouldShowRecovery({
|
||||
// already reset). It never renders decoration on its own.
|
||||
const shortcutOpen = ref(false);
|
||||
const recoveryPopover = ref<HTMLElement | null>(null);
|
||||
const groupToolbarElement = ref<HTMLElement | null>(null);
|
||||
const builtInToolbarElement = ref<HTMLElement | null>(null);
|
||||
const libraryToolbarElement = ref<HTMLElement | null>(null);
|
||||
|
||||
let slotBinding: HostSlotBinding | undefined;
|
||||
const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value));
|
||||
|
||||
/**
|
||||
* Theme the capsule even when the skin does not declare a slot. While a slot
|
||||
* binding exists it reads the anchor first and owns the tokens; this
|
||||
* root-level pass covers the slot-less capsule and refreshes itself when the
|
||||
* skin stylesheet arrives after the stored skin id.
|
||||
* Optional anchor from the active skin's chrome.json. Only third-party skins
|
||||
* can declare it; the host still owns the controls and the module falls back
|
||||
* to the default corner whenever an anchor stops being usable.
|
||||
*/
|
||||
const slotConfig = computed(() => activeHostSlot("host.recovery"));
|
||||
const builtInSlotConfig = computed(() => activeHostSlot("host.recovery.built-in"));
|
||||
const librarySlotConfig = computed(() => activeHostSlot("host.recovery.library"));
|
||||
const groupToolbarConfig = computed<SkinChromeSlot | undefined>(() => slotConfig.value?.mode === "toolbar" ? slotConfig.value : undefined);
|
||||
const capsuleSlotConfig = computed<SkinChromeSlot | undefined>(() => slotConfig.value?.mode === "toolbar" ? undefined : slotConfig.value);
|
||||
const builtInToolbarConfig = computed<SkinChromeSlot | undefined>(() => builtInSlotConfig.value?.mode === "toolbar" ? builtInSlotConfig.value : undefined);
|
||||
const libraryToolbarConfig = computed<SkinChromeSlot | undefined>(() => librarySlotConfig.value?.mode === "toolbar" ? librarySlotConfig.value : undefined);
|
||||
|
||||
/**
|
||||
* Theme the capsule even when the skin does not declare a slot. While a
|
||||
* capsule slot binding exists it reads the anchor first and owns the tokens;
|
||||
* this root-level pass covers the slot-less capsule and refreshes itself when
|
||||
* the skin stylesheet arrives after the stored skin id. Toolbar bindings keep
|
||||
* their own `--ws-toolbar-*` variables and do not disable this pass, so the
|
||||
* floating fallback keeps the capsule palette.
|
||||
*/
|
||||
const recoveryTheme = layer ? bindHostControlTheme({
|
||||
layer,
|
||||
@@ -205,19 +408,43 @@ const recoveryTheme = layer ? bindHostControlTheme({
|
||||
part: "host.recovery",
|
||||
defaults: RECOVERY_CONTROL_DEFAULTS,
|
||||
source: () => findSkinRoot(hostChromeActiveSkinId.value),
|
||||
// While a slot binding exists it owns the capsule tokens (anchor first).
|
||||
active: () => !slotBinding,
|
||||
active: () => !capsuleBinding,
|
||||
}) : null;
|
||||
|
||||
const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value));
|
||||
|
||||
/**
|
||||
* Optional anchor from the active skin's chrome.json. Only third-party skins
|
||||
* can declare it; the host still owns the capsule and the module falls back to
|
||||
* the default corner whenever the anchor stops being usable.
|
||||
*/
|
||||
const slotConfig = computed(() => activeHostSlot("host.recovery"));
|
||||
const slotMode = ref<"floating" | "slotted">("floating");
|
||||
const groupToolbarMode = ref<"floating" | "slotted">("floating");
|
||||
const builtInToolbarMode = ref<"floating" | "slotted">("floating");
|
||||
const libraryToolbarMode = ref<"floating" | "slotted">("floating");
|
||||
|
||||
const builtInActionState = computed(() => ({
|
||||
available: Boolean(groupToolbarConfig.value || builtInToolbarConfig.value),
|
||||
docked: groupToolbarConfig.value
|
||||
? groupToolbarMode.value === "slotted"
|
||||
: builtInToolbarMode.value === "slotted",
|
||||
}));
|
||||
const libraryActionState = computed(() => ({
|
||||
available: Boolean(props.pluginLibraryAvailable) && Boolean(groupToolbarConfig.value || libraryToolbarConfig.value),
|
||||
docked: groupToolbarConfig.value
|
||||
? groupToolbarMode.value === "slotted"
|
||||
: libraryToolbarMode.value === "slotted",
|
||||
}));
|
||||
|
||||
const presentation = computed(() => resolveHostRecoveryPresentation({
|
||||
visible: recoveryVisible.value,
|
||||
shortcutOpen: shortcutOpen.value,
|
||||
libraryAvailable: Boolean(props.pluginLibraryAvailable),
|
||||
builtIn: builtInActionState.value,
|
||||
library: libraryActionState.value,
|
||||
}));
|
||||
const capsuleActions = computed(() => presentation.value.capsuleActions);
|
||||
|
||||
// Exactly one application-library entry per page: the host toolbar button is
|
||||
// the library entry while a toolbar slot exists, so PluginPanel hides its
|
||||
// ordinary launcher (including while the capsule fallback shows the button).
|
||||
watchEffect(() => {
|
||||
setInlineLibraryEntryVisible(presentation.value.suppressLauncher);
|
||||
});
|
||||
|
||||
const compactHold = ref(true);
|
||||
let compactHoldTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
@@ -255,11 +482,15 @@ let floatingElement: HTMLElement | null = null;
|
||||
/** Sticky `:hover` after a tap on touch screens must not pause avoidance. */
|
||||
const canHover = () => typeof matchMedia === "function" && matchMedia("(hover: hover)").matches;
|
||||
|
||||
const compact = computed(() => !shortcutExpanded.value
|
||||
&& !compactPinned.value
|
||||
&& (slotMode.value === "slotted"
|
||||
? Boolean(slotConfig.value?.compact) && !compactHold.value
|
||||
: floatCompact.value));
|
||||
const compact = computed(() => {
|
||||
if (shortcutExpanded.value || compactPinned.value) return false;
|
||||
const config = capsuleSlotConfig.value;
|
||||
if (config) return Boolean(config.compact) && !compactHold.value;
|
||||
// A toolbar-mode capsule is the fallback entry, not the target look: never
|
||||
// fold it, otherwise a failed anchor could leave only a small mark.
|
||||
if (groupToolbarConfig.value || builtInToolbarConfig.value || libraryToolbarConfig.value) return false;
|
||||
return floatCompact.value;
|
||||
});
|
||||
|
||||
function onRecoveryEscape() {
|
||||
shortcutOpen.value = false;
|
||||
@@ -267,40 +498,145 @@ function onRecoveryEscape() {
|
||||
compactPinned.value = false;
|
||||
}
|
||||
|
||||
/** Unpin when the pointer goes down anywhere outside the host layer. */
|
||||
/** Dismiss shortcut expansion and unpin on pointer down outside the host layer. */
|
||||
function onDocumentPointerDown(event: PointerEvent) {
|
||||
if (!compactPinned.value || !layer) return;
|
||||
if (!layer) return;
|
||||
// Events from inside the closed shadow root are retargeted to its host.
|
||||
if (event.composedPath().includes(layer.host)) return;
|
||||
shortcutOpen.value = false;
|
||||
shortcutExpanded.value = false;
|
||||
compactPinned.value = false;
|
||||
}
|
||||
|
||||
function onRecoveryFocusOut(event: FocusEvent) {
|
||||
const next = event.relatedTarget;
|
||||
if (next instanceof Node && recoveryPopover.value?.contains(next)) return;
|
||||
shortcutOpen.value = false;
|
||||
shortcutExpanded.value = false;
|
||||
compactPinned.value = false;
|
||||
}
|
||||
|
||||
function syncSlotBinding() {
|
||||
slotBinding?.dispose();
|
||||
slotBinding = undefined;
|
||||
// Disposing a slot clears its inline tokens; restore the root-level theme
|
||||
// before deciding whether a new anchor should override it.
|
||||
recoveryTheme?.apply();
|
||||
// A fresh binding starts floating and reports its first successful dock.
|
||||
slotMode.value = "floating";
|
||||
const control = recoveryPopover.value;
|
||||
const config = slotConfig.value;
|
||||
if (!control || !config || !layer) return;
|
||||
slotBinding = bindHostSlot({
|
||||
let capsuleBinding: HostSlotBinding | undefined;
|
||||
let toolbarBindings: HostSlotBinding[] = [];
|
||||
|
||||
function syncPopover() {
|
||||
syncRecoveryPopover(recoveryPopover.value, presentation.value.capsuleVisible);
|
||||
}
|
||||
|
||||
function syncToolbarPopovers() {
|
||||
const visible = presentation.value.toolbar.visible;
|
||||
syncRecoveryPopover(
|
||||
groupToolbarElement.value,
|
||||
Boolean(groupToolbarConfig.value) && visible && groupToolbarMode.value === "slotted",
|
||||
);
|
||||
syncRecoveryPopover(
|
||||
builtInToolbarElement.value,
|
||||
Boolean(builtInToolbarConfig.value) && visible && builtInToolbarMode.value === "slotted",
|
||||
);
|
||||
syncRecoveryPopover(
|
||||
libraryToolbarElement.value,
|
||||
Boolean(libraryToolbarConfig.value) && Boolean(props.pluginLibraryAvailable)
|
||||
&& visible && libraryToolbarMode.value === "slotted",
|
||||
);
|
||||
}
|
||||
|
||||
/** A toolbar that is currently displayed (top layer or display fallback). */
|
||||
function isToolbarShown(control: HTMLElement | null): boolean {
|
||||
if (!control) return false;
|
||||
if (control.matches?.(":popover-open")) return true;
|
||||
const rect = control.getBoundingClientRect();
|
||||
return getComputedStyle(control).display !== "none" && rect.width > 0 && rect.height > 0;
|
||||
}
|
||||
|
||||
function rectOf(control: HTMLElement): HostPartRect {
|
||||
const rect = control.getBoundingClientRect();
|
||||
return {
|
||||
left: rect.left, top: rect.top, width: rect.width, height: rect.height,
|
||||
right: rect.right, bottom: rect.bottom,
|
||||
};
|
||||
}
|
||||
|
||||
/** Every recovery toolbar currently docked in the top layer. */
|
||||
function dockedToolbarRects(): HostPartRect[] {
|
||||
return [groupToolbarElement.value, builtInToolbarElement.value, libraryToolbarElement.value]
|
||||
.filter((element): element is HTMLElement => Boolean(element) && isToolbarShown(element))
|
||||
.map(rectOf);
|
||||
}
|
||||
|
||||
/** Other docked recovery toolbars this entry must not cover on a narrow screen. */
|
||||
function otherToolbarRects(control: HTMLElement): HostPartRect[] {
|
||||
return [groupToolbarElement.value, builtInToolbarElement.value, libraryToolbarElement.value]
|
||||
.filter((element): element is HTMLElement => Boolean(element)
|
||||
&& element !== control && isToolbarShown(element))
|
||||
.map(rectOf);
|
||||
}
|
||||
|
||||
function bindToolbarEntry(
|
||||
control: HTMLElement | null,
|
||||
config: SkinChromeSlot | undefined,
|
||||
mode: Ref<"floating" | "slotted">,
|
||||
) {
|
||||
if (!layer || !control || !config) return;
|
||||
toolbarBindings.push(bindHostSlot({
|
||||
layer,
|
||||
control,
|
||||
anchor: config.anchor,
|
||||
skinId: hostChromeActiveSkinId.value,
|
||||
align: config.align,
|
||||
onModeChange: change => { slotMode.value = change.mode; },
|
||||
});
|
||||
presentation: "toolbar",
|
||||
otherControls: () => otherToolbarRects(control),
|
||||
// A floating toolbar is a closed popover (display:none). Show it for the
|
||||
// synchronous measurement/hit test and hide it again unless it docked.
|
||||
prepare: () => syncRecoveryPopover(control, true),
|
||||
settle: slotted => {
|
||||
if (!slotted || !presentation.value.toolbar.visible) syncRecoveryPopover(control, false);
|
||||
},
|
||||
onModeChange: change => {
|
||||
mode.value = change.mode;
|
||||
syncPopover();
|
||||
syncToolbarPopovers();
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
function syncSlotBindings() {
|
||||
capsuleBinding?.dispose();
|
||||
capsuleBinding = undefined;
|
||||
for (const binding of toolbarBindings) binding.dispose();
|
||||
toolbarBindings = [];
|
||||
// Disposing a slot clears its inline tokens; restore the root-level theme
|
||||
// before deciding whether a new anchor should override it.
|
||||
recoveryTheme?.apply();
|
||||
// A fresh binding starts floating and reports its first successful dock.
|
||||
slotMode.value = "floating";
|
||||
groupToolbarMode.value = "floating";
|
||||
builtInToolbarMode.value = "floating";
|
||||
libraryToolbarMode.value = "floating";
|
||||
const capsuleConfig = capsuleSlotConfig.value;
|
||||
if (recoveryPopover.value && capsuleConfig && layer) {
|
||||
capsuleBinding = bindHostSlot({
|
||||
layer,
|
||||
control: recoveryPopover.value,
|
||||
anchor: capsuleConfig.anchor,
|
||||
skinId: hostChromeActiveSkinId.value,
|
||||
align: capsuleConfig.align,
|
||||
// A slotted capsule must not cover a still-docked split toolbar either.
|
||||
otherControls: () => dockedToolbarRects(),
|
||||
onModeChange: change => { slotMode.value = change.mode; },
|
||||
});
|
||||
}
|
||||
bindToolbarEntry(groupToolbarElement.value, groupToolbarConfig.value, groupToolbarMode);
|
||||
bindToolbarEntry(builtInToolbarElement.value, builtInToolbarConfig.value, builtInToolbarMode);
|
||||
if (props.pluginLibraryAvailable) {
|
||||
bindToolbarEntry(libraryToolbarElement.value, libraryToolbarConfig.value, libraryToolbarMode);
|
||||
}
|
||||
syncPopover();
|
||||
syncToolbarPopovers();
|
||||
}
|
||||
|
||||
function revalidateBindings() {
|
||||
capsuleBinding?.revalidate();
|
||||
for (const binding of toolbarBindings) binding.revalidate();
|
||||
}
|
||||
|
||||
function bindFloating() {
|
||||
@@ -331,6 +667,11 @@ function bindFloating() {
|
||||
return { width: hit + 10, height: hit + 10 };
|
||||
},
|
||||
onCompactChange: next => { floatCompact.value = next; },
|
||||
// Docked toolbars are inside the closed shadow root, so the light-DOM
|
||||
// obstacle scan cannot see them. In split mode the library toolbar falls
|
||||
// back to this capsule while the built-in toolbar stays docked; without
|
||||
// this exclusion the capsule could cover it (320px GUI failure).
|
||||
avoidRects: () => dockedToolbarRects(),
|
||||
// Never move the capsule under the user's pointer or focus, and leave a
|
||||
// docked capsule to the slot binding.
|
||||
paused: () => slotMode.value === "slotted"
|
||||
@@ -341,10 +682,6 @@ function bindFloating() {
|
||||
});
|
||||
}
|
||||
|
||||
function syncPopover() {
|
||||
syncRecoveryPopover(recoveryPopover.value, recoveryVisible.value);
|
||||
}
|
||||
|
||||
function useBuiltInSkin() {
|
||||
shortcutOpen.value = false;
|
||||
requestBuiltInSkin();
|
||||
@@ -364,8 +701,11 @@ function onKeydown(event: KeyboardEvent) {
|
||||
shortcutOpen.value = true;
|
||||
shortcutExpanded.value = true;
|
||||
void nextTick(() => {
|
||||
// The shortcut always brings back the complete capsule, even while a
|
||||
// toolbar anchor is healthy.
|
||||
syncPopover();
|
||||
slotBinding?.revalidate();
|
||||
syncToolbarPopovers();
|
||||
revalidateBindings();
|
||||
recoveryPopover.value?.querySelector("button")?.focus();
|
||||
});
|
||||
}
|
||||
@@ -376,30 +716,66 @@ function refreshLauncherReachability() {
|
||||
launcherReachable.value = isHostPartVisuallyReachable("host.plugins.launcher");
|
||||
}
|
||||
|
||||
watch([recoveryVisible, recoveryPopover], () => {
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
slotBinding?.revalidate();
|
||||
bindFloating();
|
||||
floatingAvoidance?.revalidate();
|
||||
});
|
||||
}, { flush: "post" });
|
||||
watch(
|
||||
[recoveryVisible, recoveryPopover, groupToolbarElement, builtInToolbarElement, libraryToolbarElement],
|
||||
() => {
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
syncToolbarPopovers();
|
||||
revalidateBindings();
|
||||
bindFloating();
|
||||
floatingAvoidance?.revalidate();
|
||||
});
|
||||
},
|
||||
{ flush: "post" },
|
||||
);
|
||||
watch([recoveryPopover, hostChromeActiveSkinId], () => {
|
||||
void nextTick(() => recoveryTheme?.apply());
|
||||
}, { flush: "post", immediate: true });
|
||||
watch([slotConfig, hostChromeActiveSkinId], () => {
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
syncSlotBinding();
|
||||
});
|
||||
}, { flush: "post" });
|
||||
watch(
|
||||
[
|
||||
slotConfig,
|
||||
builtInSlotConfig,
|
||||
librarySlotConfig,
|
||||
hostChromeActiveSkinId,
|
||||
groupToolbarElement,
|
||||
builtInToolbarElement,
|
||||
libraryToolbarElement,
|
||||
() => props.pluginLibraryAvailable,
|
||||
],
|
||||
() => {
|
||||
void nextTick(() => {
|
||||
syncSlotBindings();
|
||||
bindFloating();
|
||||
});
|
||||
},
|
||||
{ flush: "post" },
|
||||
);
|
||||
// Home <-> voice page and skin switches replace the controls the floating
|
||||
// capsule was avoiding; re-place it promptly (and back to its default corner
|
||||
// when that is free) instead of leaving it where the previous screen needed it.
|
||||
watch([() => props.connected, hostChromeActiveSkinId], () => {
|
||||
void nextTick(() => floatingAvoidance?.screenChanged());
|
||||
void nextTick(() => {
|
||||
revalidateBindings();
|
||||
floatingAvoidance?.screenChanged();
|
||||
});
|
||||
}, { flush: "post" });
|
||||
watch(thirdPartyAllowed, allowed => { if (!allowed) shortcutOpen.value = false; });
|
||||
// Opening or closing the shortcut changes which presentation is active; docked
|
||||
// toolbar buttons must hide while the complete capsule is summoned, and come
|
||||
// back (if their anchor is still valid) when it closes.
|
||||
watch(shortcutOpen, () => {
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
syncToolbarPopovers();
|
||||
revalidateBindings();
|
||||
});
|
||||
}, { flush: "post" });
|
||||
|
||||
// A page switch can mount a new `.ws-skin-root` with a different
|
||||
// `data-ws-page` without changing the skin id. Re-resolve the declared anchor
|
||||
// candidates promptly instead of waiting for the periodic safety check.
|
||||
let pageObserver: MutationObserver | undefined;
|
||||
|
||||
onMounted(() => {
|
||||
refreshLauncherReachability();
|
||||
@@ -407,16 +783,37 @@ onMounted(() => {
|
||||
window.addEventListener("resize", refreshLauncherReachability);
|
||||
window.addEventListener("keydown", onKeydown, true);
|
||||
window.addEventListener("pointerdown", onDocumentPointerDown, true);
|
||||
if (typeof MutationObserver === "function") {
|
||||
pageObserver = new MutationObserver(() => {
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
syncToolbarPopovers();
|
||||
revalidateBindings();
|
||||
floatingAvoidance?.screenChanged();
|
||||
});
|
||||
});
|
||||
pageObserver.observe(document.documentElement, {
|
||||
subtree: true,
|
||||
attributes: true,
|
||||
attributeFilter: ["data-ws-page", "data-ws-skin"],
|
||||
});
|
||||
}
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
syncSlotBinding();
|
||||
syncSlotBindings();
|
||||
bindFloating();
|
||||
});
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
if (reachabilityTimer) clearInterval(reachabilityTimer);
|
||||
if (compactHoldTimer) clearTimeout(compactHoldTimer);
|
||||
slotBinding?.dispose();
|
||||
pageObserver?.disconnect();
|
||||
pageObserver = undefined;
|
||||
capsuleBinding?.dispose();
|
||||
capsuleBinding = undefined;
|
||||
for (const binding of toolbarBindings) binding.dispose();
|
||||
toolbarBindings = [];
|
||||
setInlineLibraryEntryVisible(false);
|
||||
floatingAvoidance?.dispose();
|
||||
floatingAvoidance = undefined;
|
||||
floatingElement = null;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<Teleport :to="toolbarTarget ?? 'body'">
|
||||
<div v-if="thirdPartyAllowed && connected && sessionToken" ref="toolbar" class="ws-plugin-toolbar" :class="{ 'ws-plugin-toolbar-fallback': !toolbarTarget }" :data-ws-float="toolbarTarget ? undefined : fallbackPosition" data-ws-part="voice.plugin-launcher" :data-presentation="presentation" :data-theme="theme" @keydown.esc="dismissDrawer">
|
||||
<button v-if="!isHostPartHidden('host.plugins.launcher')" ref="launcher" class="header-action ws-plugin-toolbar-trigger" data-ws-part="host.plugins.launcher" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="presentation === 'dialog' ? visible : drawerOpen" :aria-controls="drawerOpen ? drawerId : undefined" @click="toggle">
|
||||
<button v-if="!isHostPartHidden('host.plugins.launcher') && !inlineLibraryEntry" ref="launcher" class="header-action ws-plugin-toolbar-trigger" data-ws-part="host.plugins.launcher" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="presentation === 'dialog' ? visible : drawerOpen" :aria-controls="drawerOpen ? drawerId : undefined" @click="toggle">
|
||||
<svg viewBox="0 0 24 24" data-ws-icon-slot="host.plugins.launcher" aria-hidden="true"><path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z" /></svg>
|
||||
<span v-if="presentation === 'drawer-side'">{{ tr('title') }}</span>
|
||||
</button>
|
||||
@@ -68,7 +68,7 @@ import { pluginTranslations, type PluginTextKey } from '../i18n/plugins.js';
|
||||
import { pluginWindowTranslations } from '../i18n/plugin-window.js';
|
||||
import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
import { thirdPartyAllowed } from '../services/instance-authorization.js';
|
||||
import { isHostPartHidden, isHostPartVisuallyReachable, pluginLibraryRequests } from '../services/host-chrome.js';
|
||||
import { isHostPartHidden, isHostPartVisuallyReachable, isInlineLibraryEntryVisible, pluginLibraryRequests } from '../services/host-chrome.js';
|
||||
import type { SkinPluginWidgetOptions } from '../../../src/shared/skin-plugin.js';
|
||||
import { bindFloatingAvoidance, type FloatingAvoidance, type FloatingPosition } from '../services/host-floating-placement.js';
|
||||
const props = defineProps<{ sessionToken: string; gatewayUrl: string; connected: boolean; language: SiteLanguage; toolbarTarget: HTMLElement | null; presentation: NonNullable<SkinPluginWidgetOptions['pluginPresentation']> }>();
|
||||
@@ -77,6 +77,9 @@ const ui = computed(() => pluginWindowTranslations[props.language]);
|
||||
const windowElement = ref<HTMLElement | null>(null), launcher = ref<HTMLButtonElement | null>(null), frame = ref<HTMLIFrameElement | null>(null);
|
||||
const available = shallowRef<AvailablePluginApp[]>([]), current = shallowRef<PluginAppLaunch | null>(null);
|
||||
const toolbar = ref<HTMLElement | null>(null);
|
||||
// A toolbar-mode recovery slot already renders the host-owned application
|
||||
// library button; do not render a second launcher on the same page.
|
||||
const inlineLibraryEntry = computed(() => isInlineLibraryEntryVisible());
|
||||
// The fallback toolbar floats in a viewport corner the skin knows nothing
|
||||
// about; move it off any skin control it would cover (runtime only).
|
||||
const fallbackPosition = ref<FloatingPosition>('bottom-right');
|
||||
|
||||
@@ -299,6 +299,74 @@
|
||||
><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 voice-tuning-card">
|
||||
<header class="settings-subsection-heading"><div><h4>{{ tr('voiceTuning') }}</h4><p class="card-help">{{ tr('voiceTuningLead') }}</p></div></header>
|
||||
<div class="voice-fields">
|
||||
<label><span>{{ tr('voiceDownlinkFrameMs') }}</span>
|
||||
<select v-model.number="serverForm.voiceDownlinkFrameMs" :disabled="serverForm.voiceProfile === 'legacy'">
|
||||
<option :value="20">20 ms</option>
|
||||
<option :value="40">40 ms</option>
|
||||
</select>
|
||||
<small class="field-help">{{ tr('voiceDownlinkFrameLead') }}</small>
|
||||
</label>
|
||||
</div>
|
||||
<label class="choice toggle-choice" :class="{ selected: serverForm.voiceAutoRelayRetry }">
|
||||
<input v-model="serverForm.voiceAutoRelayRetry" type="checkbox" />
|
||||
<span><strong>{{ tr('voiceAutoRelayRetry') }}</strong><small>{{ tr('voiceAutoRelayRetryLead') }}</small></span>
|
||||
</label>
|
||||
<label class="choice toggle-choice" :class="{ selected: serverForm.voiceAssumeCloudflare }">
|
||||
<input v-model="serverForm.voiceAssumeCloudflare" type="checkbox" />
|
||||
<span><strong>{{ tr('voiceAssumeCloudflare') }}</strong><small>{{ tr('voiceAssumeCloudflareLead') }}</small></span>
|
||||
</label>
|
||||
<small class="field-help">{{ tr('voiceApplyHint') }}</small>
|
||||
</section>
|
||||
<section class="settings-subsection turn-card">
|
||||
<header class="settings-subsection-heading"><div><h4>{{ tr('turnSettings') }}</h4><p class="card-help">{{ tr('turnLead') }}</p></div></header>
|
||||
<label class="webrtc-network-field">
|
||||
<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 +391,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"); }
|
||||
|
||||
@@ -52,10 +52,11 @@
|
||||
<div class="dock-panel-divider"></div>
|
||||
<label class="dock-switch-row">
|
||||
<span><strong>{{ t("noiseSuppression") }}</strong></span>
|
||||
<select class="noise-suppression-level" :value="noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
|
||||
<select class="noise-suppression-level" :value="noiseSuppressionMode" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
|
||||
<option value="off">{{ t("noiseSuppressionOff") }}</option>
|
||||
<option value="standard">{{ t("noiseSuppressionStandard") }}</option>
|
||||
<option value="strong">{{ t("noiseSuppressionStrong") }}</option>
|
||||
<option value="browser">{{ t("noiseSuppressionStandardShort") }}</option>
|
||||
<option value="rnnoise">{{ t("noiseSuppressionLightShort") }}</option>
|
||||
<option value="gtcrn">{{ t("noiseSuppressionStrongShort") }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
@@ -131,12 +132,12 @@ import type { useVoiceWebSocket } from "../../composables/useVoiceWebSocket.js";
|
||||
import type { useWebClientAudioControls } from "../../composables/useWebClientAudioControls.js";
|
||||
|
||||
const props = defineProps<{
|
||||
model: Pick<ReturnType<typeof useVoiceWebSocket>, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionLevel" | "accompanimentActive">;
|
||||
model: Pick<ReturnType<typeof useVoiceWebSocket>, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionMode" | "accompanimentActive">;
|
||||
controls: Pick<ReturnType<typeof useWebClientAudioControls>, "toggleMicrophone" | "toggleNoiseSuppression" | "onInputVolume" | "onOutputVolume" | "onNoiseSuppressionChange" | "toggleAccompaniment">;
|
||||
t: (key: string) => string;
|
||||
rangeStyle: (value: number, max: number) => Record<string, string>;
|
||||
}>();
|
||||
const { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive } = props.model;
|
||||
const { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionMode, accompanimentActive } = props.model;
|
||||
const { toggleMicrophone, onInputVolume, onOutputVolume, onNoiseSuppressionChange, toggleAccompaniment } = props.controls;
|
||||
const emit = defineEmits<{ settings: []; outputMute: [] }>();
|
||||
</script>
|
||||
@@ -78,12 +78,14 @@
|
||||
></div
|
||||
><label class="settings-form-row">
|
||||
<span><strong>{{ t("noiseSuppression") }}</strong><small>{{ t("noiseSuppressionHint") }}</small></span>
|
||||
<select class="noise-suppression-level" :value="noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
|
||||
<select class="noise-suppression-level" :value="noiseSuppressionMode" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
|
||||
<option value="off">{{ t("noiseSuppressionOff") }}</option>
|
||||
<option value="standard">{{ t("noiseSuppressionStandard") }}</option>
|
||||
<option value="strong">{{ t("noiseSuppressionStrong") }}</option>
|
||||
<option value="browser">{{ t("noiseSuppressionStandard") }}</option>
|
||||
<option value="rnnoise">{{ t("noiseSuppressionLight") }}</option>
|
||||
<option value="gtcrn">{{ t("noiseSuppressionStrong") }}</option>
|
||||
</select>
|
||||
</label
|
||||
><p class="settings-hint noise-suppression-status" :class="{ 'settings-error': Boolean(processingFallback) || Boolean(processingWarning) }">{{ processingStatus }}</p
|
||||
><div class="settings-form-row settings-range-form-row"
|
||||
><label class="settings-label">{{ t("inputVolume") }}</label
|
||||
><div class="settings-form-control"
|
||||
@@ -141,13 +143,25 @@
|
||||
><span>{{ t("optimal") }}</span
|
||||
><span>{{ t("loud") }}</span></div
|
||||
><p class="settings-hint">{{ t("localMicTestHint") }}</p
|
||||
><audio
|
||||
v-if="testAudioUrl"
|
||||
class="test-audio"
|
||||
:src="testAudioUrl"
|
||||
controls
|
||||
:aria-label="t('microphoneTest')"
|
||||
></audio></div
|
||||
><div v-if="testAudioUrl || testAudioDryUrl" class="mic-test-compare">
|
||||
<div class="mic-test-tabs" role="group" :aria-label="t('micTestCompareHint')">
|
||||
<button type="button" :class="{ active: testVariant === 'processed' }" :aria-pressed="testVariant === 'processed'" @click="testVariant = 'processed'">{{ t("micTestDenoised") }}</button>
|
||||
<button type="button" :class="{ active: testVariant === 'dry' }" :aria-pressed="testVariant === 'dry'" @click="testVariant = 'dry'">{{ t("micTestOriginal") }}</button>
|
||||
</div>
|
||||
<audio
|
||||
v-if="testAudioSrc"
|
||||
class="test-audio"
|
||||
:src="testAudioSrc"
|
||||
controls
|
||||
:aria-label="t('microphoneTest')"
|
||||
></audio>
|
||||
<p
|
||||
v-else
|
||||
class="settings-hint mic-test-missing"
|
||||
role="status"
|
||||
>{{ t(testAudioMissingKey) }}</p>
|
||||
<p class="settings-hint">{{ t("micTestCompareHint") }}</p>
|
||||
</div></div
|
||||
></section>
|
||||
<div class="settings-separator"></div
|
||||
><section class="settings-section"
|
||||
@@ -248,6 +262,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, type CSSProperties } from "vue";
|
||||
import { micTestPlaybackSource } from "../../voice/microphone-test.js";
|
||||
import Icon from "../Icon.vue";
|
||||
import AudioDeviceSelect from "./AudioDeviceSelect.vue";
|
||||
import { useDialogFocus } from "../../composables/useDialogFocus.js";
|
||||
@@ -263,7 +278,8 @@ type AudioSettingsState = Pick<ReturnType<typeof useVoiceWebSocket>,
|
||||
| "audioPermission"
|
||||
| "audioContextState"
|
||||
| "microphoneMuted"
|
||||
| "noiseSuppressionLevel"
|
||||
| "noiseSuppressionMode"
|
||||
| "microphoneProcessing"
|
||||
| "inputVolume"
|
||||
| "outputVolume"
|
||||
| "voxThreshold"
|
||||
@@ -271,6 +287,7 @@ type AudioSettingsState = Pick<ReturnType<typeof useVoiceWebSocket>,
|
||||
| "micLevel"
|
||||
| "microphoneTestActive"
|
||||
| "testAudioUrl"
|
||||
| "testAudioDryUrl"
|
||||
>;
|
||||
type AudioSettingsControls = Pick<ReturnType<typeof useWebClientAudioControls>,
|
||||
| "settingsError"
|
||||
@@ -308,7 +325,8 @@ const {
|
||||
audioPermission,
|
||||
audioContextState,
|
||||
microphoneMuted,
|
||||
noiseSuppressionLevel,
|
||||
noiseSuppressionMode,
|
||||
microphoneProcessing,
|
||||
inputVolume,
|
||||
outputVolume,
|
||||
voxThreshold,
|
||||
@@ -316,6 +334,7 @@ const {
|
||||
micLevel,
|
||||
microphoneTestActive,
|
||||
testAudioUrl,
|
||||
testAudioDryUrl,
|
||||
} = props.model;
|
||||
const {
|
||||
settingsError: audioSettingsError,
|
||||
@@ -346,4 +365,33 @@ const outputDeviceOptions = computed(() => [
|
||||
label: device.label || props.t("speakerNumber", { index: index + 1 }),
|
||||
})),
|
||||
]);
|
||||
|
||||
const testVariant = ref<"processed" | "dry">("processed");
|
||||
const testPlayback = computed(() => micTestPlaybackSource(testVariant.value, {
|
||||
processed: testAudioUrl.value,
|
||||
dry: testAudioDryUrl.value,
|
||||
}));
|
||||
const testAudioSrc = computed(() => testPlayback.value.src);
|
||||
const testAudioMissingKey = computed(() => testPlayback.value.missingKey);
|
||||
const processingFallback = computed(() => microphoneProcessing.fallback);
|
||||
const processingWarning = computed(() => microphoneProcessing.warning);
|
||||
// Reflect the engine that really ran, not the stored preference.
|
||||
const processingStatus = computed(() => {
|
||||
const fallback = microphoneProcessing.fallback;
|
||||
if (fallback === "no-worklet") return props.t("noiseSuppressionFallbackNoWorklet");
|
||||
if (fallback === "sample-rate") return props.t("noiseSuppressionFallbackSampleRate");
|
||||
// A model that died after the browser suppressor was already disabled leaves
|
||||
// no denoising at all: say so instead of promising a browser fallback.
|
||||
if (fallback === "load-failed") {
|
||||
return microphoneProcessing.engine === "off"
|
||||
? props.t("noiseSuppressionModelInactive")
|
||||
: props.t("noiseSuppressionFallbackLoad");
|
||||
}
|
||||
if (microphoneProcessing.warning === "browser-ns-active") return props.t("noiseSuppressionBrowserStacking");
|
||||
if (microphoneProcessing.engine === "gtcrn") return `${props.t("noiseSuppressionActive")}:${props.t("noiseSuppressionEngineGtcrn")}`;
|
||||
if (microphoneProcessing.engine === "rnnoise") return `${props.t("noiseSuppressionActive")}:${props.t("noiseSuppressionEngineRnnoise")}`;
|
||||
if (microphoneProcessing.engine === "browser") return `${props.t("noiseSuppressionActive")}:${props.t("noiseSuppressionEngineBrowser")}`;
|
||||
if (microphoneProcessing.requestedEngine !== "off") return props.t("noiseSuppressionPreparing");
|
||||
return props.t("noiseSuppressionEngineOff");
|
||||
});
|
||||
</script>
|
||||
@@ -37,6 +37,11 @@ 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_VOICE_FRAME_MS: "invalidVoiceFrameMsError", INVALID_VOICE_ASSUME_CLOUDFLARE: "invalidVoiceSettingsError",
|
||||
INVALID_VOICE_AUTO_RELAY_RETRY: "invalidVoiceSettingsError",
|
||||
INVALID_RELAY_NAME: "invalidRelayNameError", INVALID_RELAY_TARGET: "invalidRelayTargetError", INVALID_RELAY_VOICE_ENDPOINT: "invalidRelayVoiceEndpointError", INVALID_RELAY_TOKEN: "invalidRelayTokenError",
|
||||
INVALID_TARGET: "invalidTargetError", PING_UNAVAILABLE: "icmpUnavailableError", HOST_NOT_FOUND: "probeHostNotFoundError",
|
||||
UNREACHABLE: "probeUnreachableError", TIMEOUT: "probeTimeoutError", PROTOCOL_NEGOTIATION_FAILED: "probeProtocolError",
|
||||
|
||||
@@ -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,13 @@ 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: true, voiceJitterMaxMs: 300,
|
||||
voiceDownlinkFrameMs: 20 as 20 | 40, voiceAssumeCloudflare: false, voiceAutoRelayRetry: true,
|
||||
relayNodes: [] as RelayNodeForm[], lastTestAt: null as string | null, lastTestLatencyMs: null as number | null };
|
||||
}
|
||||
type ServerForm = ReturnType<typeof emptyForm>;
|
||||
const editable = ["address", "port", "accessMode", "siteName", "welcomeText", "welcomeTextEn", "welcomeTextDe", "welcomeTextRu", "welcomeTextJa", "webRtcEnabled", "webRtcPublicHost", "webRtcIpv6Enabled", "webRtcStunServer", "webRtcUdpStart", "webRtcUdpEnd"] as const;
|
||||
const editable = ["address", "port", "accessMode", "siteName", "welcomeText", "welcomeTextEn", "welcomeTextDe", "welcomeTextRu", "welcomeTextJa", "webRtcEnabled", "webRtcPublicHost", "webRtcIpv6Enabled", "webRtcStunServer", "webRtcUdpStart", "webRtcUdpEnd", "voiceProfile", "voiceTurnUrls", "voiceTurnTtlSeconds", "voiceOpusWs", "voiceJitterMaxMs", "voiceDownlinkFrameMs", "voiceAssumeCloudflare", "voiceAutoRelayRetry"] as const;
|
||||
const snapshot = (form: ServerForm): ServerForm => JSON.parse(JSON.stringify(form));
|
||||
|
||||
export function useAdminServerSettings(options: Options) {
|
||||
@@ -73,6 +77,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 +108,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", "voiceDownlinkFrameMs", "voiceAssumeCloudflare", "voiceAutoRelayRetry"] 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);
|
||||
|
||||
@@ -2,6 +2,15 @@ import { createRemotePlayback } from "../voice/remote-playback.js";
|
||||
import { createMicrophoneTest } from "../voice/microphone-test.js";
|
||||
import { createMicrophoneCaptureFactory, type MicrophoneCapture, type MicrophoneProcessingSettings } from "../voice/microphone-capture.js";
|
||||
export type { MicrophoneProcessingSettings } from "../voice/microphone-capture.js";
|
||||
import {
|
||||
isNeuralDenoiseEngine,
|
||||
legacyNoiseSuppressionLevel,
|
||||
migrateStoredNoiseSuppression,
|
||||
resolveDenoisePlan,
|
||||
type DenoisePlan,
|
||||
type NoiseSuppressionMode,
|
||||
type StoredNoiseSuppressionLevel,
|
||||
} from "../voice/noise-suppression.js";
|
||||
import { createAudioSinkRouter } from "../voice/audio-sink.js";
|
||||
import { createAccompaniment, type AccompanimentErrorCode } from "../voice/accompaniment.js";
|
||||
import { createWebRtcTransport } from "../voice/webrtc-transport.js";
|
||||
@@ -14,9 +23,13 @@ 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 { hasVoiceTurnServer } from "../../../src/shared/voice-ice.js";
|
||||
import { createOpusUplink } from "../voice/opus-uplink.js";
|
||||
import { requestMediaBeforeAudioResume } from "../services/microphone-start.js";
|
||||
export type { ScreenShareOutputSettings, ScreenShareCaptureStats, ScreenSharePeerStats, ScreenShareWebRtcStats } from "../voice/screen-share.js";
|
||||
import { parseServerMessage } from "../../../src/shared/server-messages.js";
|
||||
import { decodeVoiceBatch, VOICE_BATCH_TAG } from "../../../src/shared/voice-audio.js";
|
||||
import type { ChatMessage } from "../../../src/shared/voice-models.js";
|
||||
import type { ClientCommandPayloads, ClientCommandType } from "../../../src/shared/client-commands.js";
|
||||
export type { ScreenShareStreamDescription as ScreenShareStream, ScreenShareViewerDescription as ScreenShareViewer, ScreenSharePeerSignal as ScreenShareSignal } from "../../../src/shared/screen-share.js";
|
||||
@@ -42,6 +55,7 @@ export interface VoiceState {
|
||||
microphoneErrorCode: string;
|
||||
audioNotice: string;
|
||||
audioNoticeCode: string;
|
||||
webrtcReconnecting: boolean;
|
||||
channelSwitchedChannelId: string;
|
||||
}
|
||||
|
||||
@@ -201,7 +215,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,
|
||||
@@ -293,24 +307,38 @@ export function useVoiceWebSocket() {
|
||||
echoCancellation: null,
|
||||
noiseSuppression: null,
|
||||
autoGainControl: null,
|
||||
rnnoise: null,
|
||||
engine: "off",
|
||||
requestedEngine: "gtcrn",
|
||||
fallback: null,
|
||||
warning: null,
|
||||
});
|
||||
const audioContextState = ref<AudioContextState | "unknown">("unknown");
|
||||
const micLevel = ref(0);
|
||||
const microphoneTestActive = ref(false);
|
||||
const testAudioUrl = ref("");
|
||||
const testAudioDryUrl = ref("");
|
||||
const microphoneTest = createMicrophoneTest({
|
||||
prepare: async () => { await prepareInputDevices(); return micStream; },
|
||||
prepare: async () => {
|
||||
await prepareInputDevices();
|
||||
if (!micStream) return null;
|
||||
return {
|
||||
dry: microphoneCapture?.dryStream ?? micStream,
|
||||
processed: microphoneCapture?.processedStream ?? micStream,
|
||||
};
|
||||
},
|
||||
onActive: active => { microphoneTestActive.value = active; },
|
||||
onUrl: url => { testAudioUrl.value = url; },
|
||||
onDryUrl: url => { testAudioDryUrl.value = url; },
|
||||
onStopped: () => { if (!state.connected) stopMicrophone(); },
|
||||
onError: error => { setMicrophoneError(error); },
|
||||
});
|
||||
const microphoneMuted = ref(false);
|
||||
const noiseSuppressionLevel = ref<"off" | "standard" | "strong">("strong");
|
||||
const noiseSuppressionEnabled = computed(() => noiseSuppressionLevel.value !== "off");
|
||||
const noiseSuppressionMode = ref<NoiseSuppressionMode>("gtcrn");
|
||||
// Compatibility view for existing skins/tests: the old three-value field.
|
||||
const noiseSuppressionLevel = computed<StoredNoiseSuppressionLevel>(() => legacyNoiseSuppressionLevel(noiseSuppressionMode.value));
|
||||
const noiseSuppressionEnabled = computed(() => noiseSuppressionMode.value !== "off");
|
||||
let noiseSuppressionTouched = false;
|
||||
let committedNoiseSuppressionLevel = noiseSuppressionLevel.value;
|
||||
let committedNoiseSuppressionMode = noiseSuppressionMode.value;
|
||||
const inputVolume = ref(1);
|
||||
const outputVolume = ref(1);
|
||||
const outputMuted = ref(false);
|
||||
@@ -330,25 +358,45 @@ export function useVoiceWebSocket() {
|
||||
const whisperActive = ref(false);
|
||||
const speakingTimers = new Map<number, ReturnType<typeof setTimeout>>();
|
||||
const SPEAKING_HOLD_MS = 360;
|
||||
const AUDIO_FRAME_SAMPLES = 960;
|
||||
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
|
||||
const MAX_AUDIO_BUFFERED_FRAMES = 10;
|
||||
const MAX_AUDIO_BUFFERED_BYTES = AUDIO_FRAME_BYTES * MAX_AUDIO_BUFFERED_FRAMES;
|
||||
const AUDIO_FRAME_SAMPLES_20 = 960;
|
||||
const AUDIO_FRAME_BYTES_20 = AUDIO_FRAME_SAMPLES_20 * 2;
|
||||
let audioFrameSamples = AUDIO_FRAME_SAMPLES_20;
|
||||
let audioFrameBytes = AUDIO_FRAME_BYTES_20;
|
||||
const LEGACY_AUDIO_BUFFERED_FRAMES = 10;
|
||||
const ADAPTIVE_AUDIO_BUFFERED_FRAMES = 15;
|
||||
let maxAudioBufferedFrames = LEGACY_AUDIO_BUFFERED_FRAMES;
|
||||
let maxAudioBufferedBytes = audioFrameBytes * maxAudioBufferedFrames;
|
||||
const MAX_OPUS_BUFFERED_BYTES = 4_096;
|
||||
let voiceProfile: "legacy" | "adaptive" = "legacy";
|
||||
let audioJitterMaxMs = 80;
|
||||
let audioFrameMs: 20 | 40 = 20;
|
||||
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";
|
||||
let voiceIceTransportPolicyBase: VoiceIceTransportPolicy = "all";
|
||||
let voiceAutoRelayRetry = true;
|
||||
let webRtcRetryCount = 0;
|
||||
let webRtcRetryTimer: number | null = null;
|
||||
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 +407,70 @@ export function useVoiceWebSocket() {
|
||||
else if (state.tsClientId) clearSpeaking(state.tsClientId);
|
||||
},
|
||||
onReady() {
|
||||
// An automatic relay retry succeeds while `webRtcFailed` is still false;
|
||||
// compatibility playback has been running during the retry and must be
|
||||
// stopped here as well, or WebRTC and WebSocket audio would mix.
|
||||
const switchingFromCompatibility = webRtcFailed || webRtcRetryCount > 0;
|
||||
webRtcFailed = false;
|
||||
state.webrtcReconnecting = false;
|
||||
webRtcRetryCount = 0;
|
||||
if (webRtcRetryTimer !== null) window.clearTimeout(webRtcRetryTimer);
|
||||
webRtcRetryTimer = null;
|
||||
stopCaptureGraph();
|
||||
if (switchingFromCompatibility) remotePlayback.clearAll();
|
||||
clearAudioNotice("WEBRTC_FAILED");
|
||||
clearAudioNotice("WEBRTC_RETRYING");
|
||||
sessionTrace.record("webrtc.media", { state: "active" });
|
||||
syncWebRtcMemberVolumes();
|
||||
},
|
||||
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;
|
||||
const code = safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE";
|
||||
sessionTrace.record("webrtc.failed", { code });
|
||||
if (switchingFromWebRtc) remotePlayback.clearAll();
|
||||
resumeCompatibilityCapture();
|
||||
// Direct UDP through a tunnel often fails without an ICE failure event
|
||||
// that names the cause. If a TURN server is configured, make one
|
||||
// automatic relay-only attempt while compatibility audio keeps playing.
|
||||
if (!webRtcFailed && webRtcRetryCount < 1 && voiceAutoRelayRetry
|
||||
&& voiceIceTransportPolicy !== "relay" && hasVoiceTurnServer(voiceIceServers)) {
|
||||
webRtcRetryCount++;
|
||||
voiceIceTransportPolicy = "relay";
|
||||
state.webrtcReconnecting = true;
|
||||
setAudioNotice("WEBRTC_RETRYING", "实时语音直连失败,正在通过 TURN 中继重试;兼容音频会继续播放");
|
||||
sessionTrace.record("webrtc.relay-retry", { code });
|
||||
if (webRtcRetryTimer !== null) window.clearTimeout(webRtcRetryTimer);
|
||||
webRtcRetryTimer = window.setTimeout(() => {
|
||||
webRtcRetryTimer = null;
|
||||
const socket = ws.value;
|
||||
if (!state.connected || !socket || socket.readyState !== WebSocket.OPEN) return;
|
||||
void startWebRtcTransport(voiceConnection.generation, socket).catch(error => {
|
||||
state.webrtcReconnecting = false;
|
||||
if (!state.connected) return;
|
||||
// `webrtc.start` can reject before it ever reports onFailure
|
||||
// (microphone permission, missing device, ICE setup). Without
|
||||
// settling the retry state here the banner would stay on
|
||||
// "retrying" forever while compatibility audio keeps playing.
|
||||
webRtcFailed = true;
|
||||
clearAudioNotice("WEBRTC_RETRYING");
|
||||
const retryCode = safeClientErrorCode(error) || "WEBRTC_UNAVAILABLE";
|
||||
setAudioNotice("WEBRTC_FAILED", webRtcFailureMessage(retryCode));
|
||||
setMicrophoneError(error);
|
||||
});
|
||||
}, 3_000);
|
||||
return;
|
||||
}
|
||||
webRtcFailed = true;
|
||||
state.webrtcReconnecting = false;
|
||||
if (webRtcRetryTimer !== null) window.clearTimeout(webRtcRetryTimer);
|
||||
webRtcRetryTimer = null;
|
||||
clearAudioNotice("WEBRTC_RETRYING");
|
||||
setAudioNotice("WEBRTC_FAILED", webRtcFailureMessage(code));
|
||||
},
|
||||
playback: {
|
||||
context: () => audioCtx,
|
||||
@@ -387,25 +489,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> {
|
||||
@@ -414,8 +532,9 @@ export function useVoiceWebSocket() {
|
||||
preferredInputDeviceId: committedInputDeviceId,
|
||||
inputDeviceId: committedInputDeviceId,
|
||||
microphoneMuted: microphoneMuted.value,
|
||||
noiseSuppressionEnabled: committedNoiseSuppressionLevel !== "off",
|
||||
noiseSuppressionLevel: committedNoiseSuppressionLevel,
|
||||
noiseSuppressionEnabled: committedNoiseSuppressionMode !== "off",
|
||||
noiseSuppressionMode: committedNoiseSuppressionMode,
|
||||
noiseSuppressionLevel: legacyNoiseSuppressionLevel(committedNoiseSuppressionMode),
|
||||
voxThreshold: voxThreshold.value,
|
||||
inputGain: inputVolume.value,
|
||||
outputVolume: outputVolume.value,
|
||||
@@ -439,14 +558,13 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
if (typeof preferences.microphoneMuted === "boolean") microphoneMuted.value = preferences.microphoneMuted;
|
||||
if (!noiseSuppressionTouched) {
|
||||
const storedLevel = preferences.noiseSuppressionLevel;
|
||||
if (storedLevel === "off" || storedLevel === "standard" || storedLevel === "strong") {
|
||||
noiseSuppressionLevel.value = storedLevel;
|
||||
committedNoiseSuppressionLevel = storedLevel;
|
||||
} else if (typeof preferences.noiseSuppressionEnabled === "boolean") {
|
||||
noiseSuppressionLevel.value = preferences.noiseSuppressionEnabled ? "strong" : "off";
|
||||
committedNoiseSuppressionLevel = noiseSuppressionLevel.value;
|
||||
}
|
||||
const storedMode = migrateStoredNoiseSuppression({
|
||||
mode: preferences.noiseSuppressionMode,
|
||||
level: preferences.noiseSuppressionLevel,
|
||||
enabled: preferences.noiseSuppressionEnabled,
|
||||
});
|
||||
noiseSuppressionMode.value = storedMode;
|
||||
committedNoiseSuppressionMode = storedMode;
|
||||
}
|
||||
if (typeof preferences.voxThreshold === "number") voxThreshold.value = clamp(preferences.voxThreshold, 0.001, 0.08);
|
||||
if (typeof preferences.inputGain === "number") inputVolume.value = Math.max(0, Math.min(1, preferences.inputGain));
|
||||
@@ -535,7 +653,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;
|
||||
@@ -589,12 +711,18 @@ export function useVoiceWebSocket() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function microphoneConstraints(): MediaTrackConstraints {
|
||||
function audioWorkletSupported(ctx: AudioContext): boolean {
|
||||
return typeof AudioWorkletNode !== "undefined" && Boolean(ctx.audioWorklet);
|
||||
}
|
||||
|
||||
function microphoneConstraints(plan: DenoisePlan): MediaTrackConstraints {
|
||||
const constraints: MediaTrackConstraints = {
|
||||
sampleRate: { ideal: 48000 },
|
||||
channelCount: { ideal: 1 },
|
||||
echoCancellation: true,
|
||||
noiseSuppression: noiseSuppressionLevel.value !== "off",
|
||||
// Model-based denoise and the browser suppressor are mutually exclusive:
|
||||
// Chrome's NS smears speech before GTCRN/RNNoise sees it.
|
||||
noiseSuppression: plan.requestBrowserNs,
|
||||
// Keep the microphone's natural dynamics. Browser AGC can make speech
|
||||
// pump in volume, especially while background noise changes.
|
||||
autoGainControl: false,
|
||||
@@ -655,11 +783,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 +800,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,9 +830,9 @@ export function useVoiceWebSocket() {
|
||||
accumLen = need;
|
||||
|
||||
let offset = 0;
|
||||
while (offset + AUDIO_FRAME_SAMPLES <= accumLen && socket.readyState === WebSocket.OPEN && socket.bufferedAmount <= MAX_AUDIO_BUFFERED_BYTES) {
|
||||
socket.send(accumBuf.slice(offset, offset + AUDIO_FRAME_SAMPLES).buffer);
|
||||
offset += AUDIO_FRAME_SAMPLES;
|
||||
while (offset + audioFrameSamples <= accumLen && socket.readyState === WebSocket.OPEN && socket.bufferedAmount <= maxAudioBufferedBytes) {
|
||||
socket.send(accumBuf.slice(offset, offset + audioFrameSamples).buffer);
|
||||
offset += audioFrameSamples;
|
||||
}
|
||||
if (offset > 0) markSpeaking(state.tsClientId);
|
||||
accumLen -= offset;
|
||||
@@ -709,9 +851,32 @@ export function useVoiceWebSocket() {
|
||||
let nextStream: MediaStream | null = null;
|
||||
let nextCapture: MicrophoneCapture | null = null;
|
||||
let factoryOwnsStream = false;
|
||||
const requestedMode = noiseSuppressionMode.value;
|
||||
let plan = resolveDenoisePlan({
|
||||
mode: requestedMode,
|
||||
sampleRate: ctx.sampleRate,
|
||||
workletSupported: audioWorkletSupported(ctx),
|
||||
});
|
||||
try {
|
||||
if (isNeuralDenoiseEngine(plan.engine)) {
|
||||
try {
|
||||
// Probe the model before asking for the microphone: if it loads, the
|
||||
// constraint below keeps browser NS off; if it fails, we still get
|
||||
// browser denoising without a second permission prompt.
|
||||
await microphoneCaptureFactory.preload(ctx, plan.engine);
|
||||
assertCurrent();
|
||||
} catch {
|
||||
assertCurrent();
|
||||
plan = {
|
||||
mode: requestedMode,
|
||||
engine: "browser",
|
||||
requestBrowserNs: true,
|
||||
fallback: "load-failed",
|
||||
};
|
||||
}
|
||||
}
|
||||
nextStream = await requestMediaBeforeAudioResume(
|
||||
() => navigator.mediaDevices.getUserMedia({ audio: microphoneConstraints() }),
|
||||
() => navigator.mediaDevices.getUserMedia({ audio: microphoneConstraints(plan) }),
|
||||
() => ctx.state === "suspended" ? ctx.resume() : Promise.resolve(),
|
||||
);
|
||||
assertCurrent();
|
||||
@@ -719,7 +884,7 @@ export function useVoiceWebSocket() {
|
||||
factoryOwnsStream = true;
|
||||
nextCapture = await microphoneCaptureFactory.prepare({
|
||||
context: ctx, stream: nextStream, signal: controller.signal, assertCurrent,
|
||||
rnnoiseEnabled: noiseSuppressionLevel.value === "strong", volume: inputVolume.value, onSamples: handleCaptureChunk,
|
||||
plan, volume: inputVolume.value, onSamples: handleCaptureChunk,
|
||||
});
|
||||
assertCurrent();
|
||||
// Commit only a complete graph. Permission and node failures leave the
|
||||
@@ -736,12 +901,18 @@ export function useVoiceWebSocket() {
|
||||
microphoneTrack.addEventListener("ended", () => recordTrack("ended"));
|
||||
}
|
||||
Object.assign(microphoneProcessing, nextCapture.processing);
|
||||
sessionTrace.record("microphone.denoise", {
|
||||
requested: nextCapture.processing.requestedEngine,
|
||||
active: nextCapture.processing.engine,
|
||||
fallback: nextCapture.processing.fallback ?? "",
|
||||
sampleRate: ctx.sampleRate,
|
||||
});
|
||||
nextCapture.setVolume(inputVolume.value);
|
||||
nextCapture.activate();
|
||||
// The fallback for a later failed change is this actual live graph, even
|
||||
// if device enumeration or WebRTC negotiation is still in progress.
|
||||
committedInputDeviceId = selectedInputDeviceId.value;
|
||||
committedNoiseSuppressionLevel = noiseSuppressionLevel.value;
|
||||
committedNoiseSuppressionMode = requestedMode;
|
||||
clearMicrophoneError();
|
||||
} catch (error) {
|
||||
nextCapture?.dispose();
|
||||
@@ -810,12 +981,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++;
|
||||
@@ -854,7 +1032,7 @@ export function useVoiceWebSocket() {
|
||||
const sequence = voiceConnection.generation;
|
||||
const socket = ws.value;
|
||||
const isCurrent = () => generation === inputDeviceGeneration && sequence === voiceConnection.generation;
|
||||
const shouldRestartWebRtc = webrtc.active && Boolean(ws.value);
|
||||
const shouldRestartWebRtc = Boolean(webrtc.peer) && Boolean(ws.value);
|
||||
try {
|
||||
// Keep the current peer alive until the replacement microphone is ready.
|
||||
if (micStream) await startMicrophone();
|
||||
@@ -864,13 +1042,13 @@ export function useVoiceWebSocket() {
|
||||
await refreshAudioDevices();
|
||||
if (!isCurrent()) return;
|
||||
committedInputDeviceId = selectedInputDeviceId.value;
|
||||
committedNoiseSuppressionLevel = noiseSuppressionLevel.value;
|
||||
committedNoiseSuppressionMode = noiseSuppressionMode.value;
|
||||
localStorage.setItem("webspeak:input-device", committedInputDeviceId);
|
||||
await saveAudioPreferences();
|
||||
} catch (error) {
|
||||
if (!isCurrent() || error instanceof CancelledMediaOperation) return;
|
||||
selectedInputDeviceId.value = committedInputDeviceId;
|
||||
noiseSuppressionLevel.value = committedNoiseSuppressionLevel;
|
||||
noiseSuppressionMode.value = committedNoiseSuppressionMode;
|
||||
localStorage.setItem("webspeak:input-device", committedInputDeviceId);
|
||||
throw error;
|
||||
}
|
||||
@@ -1061,13 +1239,33 @@ export function useVoiceWebSocket() {
|
||||
deviceListGeneration++;
|
||||
selectedInputDeviceId.value = committedInputDeviceId;
|
||||
selectedOutputDeviceId.value = committedOutputDeviceId;
|
||||
noiseSuppressionLevel.value = committedNoiseSuppressionLevel;
|
||||
noiseSuppressionMode.value = committedNoiseSuppressionMode;
|
||||
microphoneTest.dispose();
|
||||
audioDiagnostics.reset();
|
||||
commands.clear(new Error("语音连接已关闭"));
|
||||
if (webRtcRetryTimer !== null) window.clearTimeout(webRtcRetryTimer);
|
||||
webRtcRetryTimer = null;
|
||||
webRtcRetryCount = 0;
|
||||
voiceAutoRelayRetry = true;
|
||||
voiceIceTransportPolicyBase = "all";
|
||||
screenShare.stopTransport(sendScreenStop);
|
||||
webrtc.stop();
|
||||
remotePlayback.clearAll();
|
||||
webRtcAvailable = false;
|
||||
webRtcFailed = false;
|
||||
state.webrtcReconnecting = false;
|
||||
voiceIceServers = [];
|
||||
voiceIceTransportPolicy = "all";
|
||||
voiceProfile = "legacy";
|
||||
maxAudioBufferedFrames = LEGACY_AUDIO_BUFFERED_FRAMES;
|
||||
audioFrameSamples = AUDIO_FRAME_SAMPLES_20;
|
||||
audioFrameBytes = AUDIO_FRAME_BYTES_20;
|
||||
maxAudioBufferedBytes = audioFrameBytes * maxAudioBufferedFrames;
|
||||
audioJitterMaxMs = 80;
|
||||
audioFrameMs = 20;
|
||||
audioUplinkCodecs = ["pcm"];
|
||||
opusUplink.disable();
|
||||
opusStreamOpen = false;
|
||||
stopMicrophone();
|
||||
clearSpeakingState();
|
||||
whisperTargetIds.clear();
|
||||
@@ -1098,6 +1296,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 +1307,37 @@ export function useVoiceWebSocket() {
|
||||
sendCmd("setMicrophoneMuted", { muted: microphoneMuted.value });
|
||||
screenShare.setIceServers(msg.screenShareIceServers);
|
||||
webRtcStunServer = msg.webRtcStunServer ?? "";
|
||||
voiceIceServers = msg.voiceIceServers ?? [];
|
||||
voiceIceTransportPolicy = msg.voiceIceTransportPolicy ?? "all";
|
||||
voiceIceTransportPolicyBase = voiceIceTransportPolicy;
|
||||
voiceAutoRelayRetry = msg.voiceRelayAutoRetry !== false;
|
||||
webRtcRetryCount = 0;
|
||||
if (webRtcRetryTimer !== null) window.clearTimeout(webRtcRetryTimer);
|
||||
webRtcRetryTimer = null;
|
||||
clearAudioNotice("WEBRTC_RETRYING");
|
||||
voiceProfile = msg.voiceProfile ?? "legacy";
|
||||
const adaptiveProfile = voiceProfile === "adaptive";
|
||||
maxAudioBufferedFrames = adaptiveProfile ? ADAPTIVE_AUDIO_BUFFERED_FRAMES : LEGACY_AUDIO_BUFFERED_FRAMES;
|
||||
audioFrameSamples = AUDIO_FRAME_SAMPLES_20;
|
||||
audioFrameBytes = AUDIO_FRAME_BYTES_20;
|
||||
maxAudioBufferedBytes = audioFrameBytes * maxAudioBufferedFrames;
|
||||
audioJitterMaxMs = adaptiveProfile ? (msg.audioJitterMaxMs ?? 300) : 80;
|
||||
audioFrameMs = 20;
|
||||
audioUplinkCodecs = adaptiveProfile ? (msg.audioUplinkCodecs ?? ["pcm"]) : ["pcm"];
|
||||
if (adaptiveProfile && msg.audioDownlinkVersions?.includes(3)) {
|
||||
sendCmd("audioCaps", {
|
||||
downlinkVersion: 3,
|
||||
maxFrameMs: 40,
|
||||
codecs: audioUplinkCodecs.includes("opus") ? ["pcm", "opus"] : ["pcm"],
|
||||
});
|
||||
}
|
||||
if (adaptiveProfile && audioUplinkCodecs.includes("opus")) {
|
||||
void opusUplink.init().then(active => sessionTrace.record("audio.opus", { state: active ? "active" : "pcm-fallback" }));
|
||||
} else {
|
||||
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) {
|
||||
@@ -1131,6 +1363,15 @@ export function useVoiceWebSocket() {
|
||||
state.error = "";
|
||||
state.errorCode = "";
|
||||
break;
|
||||
case "audioConfig": {
|
||||
audioFrameMs = msg.frameMs === 40 ? 40 : 20;
|
||||
audioFrameSamples = audioFrameMs * 48;
|
||||
audioFrameBytes = audioFrameSamples * 2;
|
||||
maxAudioBufferedBytes = audioFrameBytes * maxAudioBufferedFrames;
|
||||
audioJitterMaxMs = msg.jitterMaxMs;
|
||||
audioUplinkCodecs = msg.uplinkCodecs;
|
||||
break;
|
||||
}
|
||||
case "audioStats": {
|
||||
const sequence = typeof msg.sequence === "string" ? msg.sequence : "";
|
||||
audioDiagnostics.receive(sequence, msg.stats);
|
||||
@@ -1188,7 +1429,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,14 +1469,34 @@ 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;
|
||||
}
|
||||
if (data[0] === VOICE_BATCH_TAG) {
|
||||
const batch = decodeVoiceBatch(data);
|
||||
if (!batch) {
|
||||
audioDiagnostics.count("framesDropped");
|
||||
return;
|
||||
}
|
||||
for (const entry of batch.entries) {
|
||||
if (entry.clientId === state.tsClientId) continue;
|
||||
if (entry.codec !== 4 && entry.codec !== 5) {
|
||||
audioDiagnostics.count("framesDropped");
|
||||
continue;
|
||||
}
|
||||
audioDiagnostics.count("framesReceived");
|
||||
markSpeaking(entry.clientId);
|
||||
remotePlayback.play(entry.clientId, entry.codec, entry.data, {
|
||||
audioStartMs: batch.audioStartMs,
|
||||
seq: entry.seq,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
const clientId = (data[1] << 8) | data[2];
|
||||
const codec = data[0];
|
||||
if (clientId === state.tsClientId) return;
|
||||
@@ -1356,12 +1617,40 @@ 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;
|
||||
// A manual retry starts from the configured policy (direct first) instead
|
||||
// of inheriting the previous automatic relay attempt.
|
||||
voiceIceTransportPolicy = voiceIceTransportPolicyBase;
|
||||
webRtcRetryCount = 0;
|
||||
if (webRtcRetryTimer !== null) window.clearTimeout(webRtcRetryTimer);
|
||||
webRtcRetryTimer = null;
|
||||
clearMicrophoneError();
|
||||
if (webRtcFailed) resumeCompatibilityCapture();
|
||||
try {
|
||||
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;
|
||||
voxRelease = 0;
|
||||
accumLen = 0;
|
||||
if (webrtc.active) micStream?.getAudioTracks().forEach((track) => { track.enabled = !muted; });
|
||||
if (webrtc.peer) micStream?.getAudioTracks().forEach((track) => { track.enabled = !muted; });
|
||||
webrtc.input?.setVolume(muted ? 0 : inputVolume.value);
|
||||
sendCmd("setMicrophoneMuted", { muted });
|
||||
if (muted && state.tsClientId) clearSpeaking(state.tsClientId);
|
||||
@@ -1441,21 +1730,28 @@ export function useVoiceWebSocket() {
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
|
||||
async function setNoiseSuppressionLevel(level: "off" | "standard" | "strong"): Promise<void> {
|
||||
if (noiseSuppressionLevel.value === level) return;
|
||||
async function setNoiseSuppressionMode(mode: NoiseSuppressionMode): Promise<void> {
|
||||
if (noiseSuppressionMode.value === mode) return;
|
||||
noiseSuppressionTouched = true;
|
||||
const previousLevel = noiseSuppressionLevel.value;
|
||||
noiseSuppressionLevel.value = level;
|
||||
const previousMode = noiseSuppressionMode.value;
|
||||
noiseSuppressionMode.value = mode;
|
||||
try {
|
||||
await reconfigureMicrophone();
|
||||
} catch (error) {
|
||||
noiseSuppressionLevel.value = previousLevel;
|
||||
noiseSuppressionMode.value = previousMode;
|
||||
setMicrophoneError(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Legacy three-value entry point; kept for external callers and skins. */
|
||||
async function setNoiseSuppressionLevel(level: StoredNoiseSuppressionLevel): Promise<void> {
|
||||
await setNoiseSuppressionMode(level === "off" ? "off" : level === "standard" ? "browser" : "gtcrn");
|
||||
}
|
||||
|
||||
function setNoiseSuppressionEnabled(enabled: boolean): Promise<void> {
|
||||
return setNoiseSuppressionLevel(enabled ? (noiseSuppressionLevel.value === "off" ? "strong" : noiseSuppressionLevel.value) : "off");
|
||||
return setNoiseSuppressionMode(enabled
|
||||
? (noiseSuppressionMode.value === "off" ? "gtcrn" : noiseSuppressionMode.value)
|
||||
: "off");
|
||||
}
|
||||
|
||||
function setOutputVolume(volume: number): void {
|
||||
@@ -1496,6 +1792,7 @@ export function useVoiceWebSocket() {
|
||||
pokeNotifications,
|
||||
microphoneMuted,
|
||||
noiseSuppressionEnabled,
|
||||
noiseSuppressionMode,
|
||||
noiseSuppressionLevel,
|
||||
inputVolume,
|
||||
outputVolume,
|
||||
@@ -1514,6 +1811,7 @@ export function useVoiceWebSocket() {
|
||||
micLevel,
|
||||
microphoneTestActive,
|
||||
testAudioUrl,
|
||||
testAudioDryUrl,
|
||||
speakingIds,
|
||||
whisperTargetIds,
|
||||
whisperActive,
|
||||
@@ -1523,6 +1821,7 @@ export function useVoiceWebSocket() {
|
||||
accompanimentErrorCode,
|
||||
setVolume,
|
||||
setInputVolume,
|
||||
setNoiseSuppressionMode,
|
||||
setNoiseSuppressionLevel,
|
||||
setNoiseSuppressionEnabled,
|
||||
setOutputVolume,
|
||||
@@ -1538,6 +1837,7 @@ export function useVoiceWebSocket() {
|
||||
playNotification,
|
||||
connect,
|
||||
reconnectNow,
|
||||
reconnectWebRtc,
|
||||
createInvite,
|
||||
disconnect,
|
||||
switchChannel,
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { computed, onScopeDispose, ref, watch, type Ref } from "vue";
|
||||
import type { LocalPreferences } from "../services/local-persistence.js";
|
||||
type NoiseSuppressionLevel = NonNullable<LocalPreferences["noiseSuppressionLevel"]>;
|
||||
import type { NoiseSuppressionMode } from "../voice/noise-suppression.js";
|
||||
|
||||
interface UseWebClientAudioControlsOptions {
|
||||
settingsOpen: Ref<boolean>;
|
||||
microphoneMuted: Readonly<Ref<boolean>>;
|
||||
noiseSuppressionLevel: Readonly<Ref<NoiseSuppressionLevel>>;
|
||||
noiseSuppressionMode: Readonly<Ref<NoiseSuppressionMode>>;
|
||||
inputVolume: Readonly<Ref<number>>;
|
||||
voxThreshold: Readonly<Ref<number>>;
|
||||
notificationVolume: Readonly<Ref<number>>;
|
||||
@@ -16,7 +15,7 @@ interface UseWebClientAudioControlsOptions {
|
||||
whisperTargetIds: Set<number>;
|
||||
prepareInputDevices: () => Promise<void>;
|
||||
setInputVolume: (value: number) => void;
|
||||
setNoiseSuppressionLevel: (level: NoiseSuppressionLevel) => Promise<void>;
|
||||
setNoiseSuppressionMode: (mode: NoiseSuppressionMode) => Promise<void>;
|
||||
setOutputVolume: (value: number) => void;
|
||||
setVoxThreshold: (value: number) => void;
|
||||
setNotificationVolume: (value: number) => void;
|
||||
@@ -36,7 +35,7 @@ interface UseWebClientAudioControlsOptions {
|
||||
export function useWebClientAudioControls({
|
||||
settingsOpen,
|
||||
microphoneMuted,
|
||||
noiseSuppressionLevel,
|
||||
noiseSuppressionMode,
|
||||
inputVolume,
|
||||
voxThreshold,
|
||||
notificationVolume,
|
||||
@@ -47,7 +46,7 @@ export function useWebClientAudioControls({
|
||||
whisperTargetIds,
|
||||
prepareInputDevices,
|
||||
setInputVolume,
|
||||
setNoiseSuppressionLevel,
|
||||
setNoiseSuppressionMode,
|
||||
setOutputVolume,
|
||||
setVoxThreshold,
|
||||
setNotificationVolume,
|
||||
@@ -95,12 +94,12 @@ export function useWebClientAudioControls({
|
||||
}
|
||||
|
||||
function onNoiseSuppressionChange(event: Event): void {
|
||||
const level = (event.target as HTMLSelectElement).value;
|
||||
if (level === "off" || level === "standard" || level === "strong") void setNoiseSuppressionLevel(level);
|
||||
const mode = (event.target as HTMLSelectElement).value;
|
||||
if (mode === "off" || mode === "browser" || mode === "rnnoise" || mode === "gtcrn") void setNoiseSuppressionMode(mode);
|
||||
}
|
||||
|
||||
function toggleNoiseSuppression(): void {
|
||||
void setNoiseSuppressionLevel(noiseSuppressionLevel.value === "off" ? "strong" : "off");
|
||||
void setNoiseSuppressionMode(noiseSuppressionMode.value === "off" ? "gtcrn" : "off");
|
||||
}
|
||||
|
||||
function onOutputVolume(event: Event): void {
|
||||
|
||||
@@ -228,12 +228,21 @@ 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_RETRYING: {
|
||||
en: "The direct WebRTC path failed; retrying through TURN in a few seconds. Compatibility audio keeps playing",
|
||||
de: "Der direkte WebRTC-Weg ist fehlgeschlagen; in wenigen Sekunden wird über TURN erneut versucht. Kompatibilitätsaudio läuft weiter",
|
||||
ru: "Прямой путь WebRTC не удался; через несколько секунд будет выполнена повторная попытка через TURN. Совместимое аудио продолжает работать",
|
||||
ja: "WebRTC の直接経路に失敗しました。数秒後に TURN 経由で再試行します。互換オーディオは継続します",
|
||||
},
|
||||
WEBRTC_FAILED: {
|
||||
en: `WebRTC realtime voice is unavailable (error code: ${webRtcReason}). Compatibility audio (PCM/Opus over WebSocket) is active to keep this voice session working; use “Reconnect WebRTC” to try again`,
|
||||
de: `Echtzeitstimme über WebRTC ist nicht verfügbar (Fehlercode: ${webRtcReason}). Der kompatible Audioweg (PCM/Opus über WebSocket) ist aktiv, damit diese Sprachsitzung bestehen bleibt; klicke auf „WebRTC neu verbinden“, um es erneut zu versuchen`,
|
||||
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",
|
||||
|
||||
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user