From 47abe356f5901e20c0819d305dbbf523e5106730 Mon Sep 17 00:00:00 2001 From: LabKit Date: Thu, 3 Dec 2026 14:19:17 +0800 Subject: [PATCH] feat(voice): add GTCRN denoise engine with raw/denoised mic test Resolve noise suppression through one plan with four modes (off, browser, rnnoise, gtcrn, default gtcrn): model engines disable the browser suppressor, preload their WASM and worklet before getUserMedia, and fall back to browser denoising (no-worklet, sample-rate, load-failed) without a second permission prompt. Add an 80 Hz high-pass ahead of the model, persist the mode beside the legacy level mirror, and let the microphone test record raw and processed takes side by side. --- CLAUDE.md | 7 +- README.md | 2 +- docs/MICROPHONE_DENOISE.md | 79 +++++++++++ docs/README.zh-CN.md | 2 +- package.json | 2 +- web/src/components/web-client/AudioDock.vue | 11 +- .../web-client/AudioSettingsDialog.vue | 63 ++++++-- web/src/composables/useVoiceWebSocket.ts | 123 ++++++++++++---- .../composables/useWebClientAudioControls.ts | 17 ++- web/src/i18n/web-client.ts | 120 ++++++++++++++-- web/src/services/local-persistence.test.ts | 30 ++++ web/src/services/local-persistence.ts | 1 + web/src/styles/web-client.css | 34 +++++ web/src/views/WebClient.vue | 16 ++- web/src/voice/microphone-capture.ts | 103 +++++++++++--- web/src/voice/microphone-test.ts | 134 ++++++++++++------ web/src/voice/noise-suppression.test.ts | 75 ++++++++++ web/src/voice/noise-suppression.ts | 82 +++++++++++ web/test/voice-session.test.mjs | 46 +++++- 19 files changed, 803 insertions(+), 144 deletions(-) create mode 100644 docs/MICROPHONE_DENOISE.md create mode 100644 web/src/voice/noise-suppression.test.ts create mode 100644 web/src/voice/noise-suppression.ts diff --git a/CLAUDE.md b/CLAUDE.md index eef8943..10f12cb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -25,7 +25,8 @@ WebSpeak connects browser users to TeamSpeak 3 and TeamSpeak 6 through a self-ho | `web/src/voice/screen-share.ts` | Per-session screen capture, peer negotiation, cleanup and diagnostics | | `web/src/voice/remote-playback.ts` | Per-speaker compatibility decoding, bounded scheduling, volume and resource cleanup | | `web/src/voice/microphone-test.ts` | Cancellable recording tests, recorder deadline and playback URL ownership | -| `web/src/voice/microphone-capture.ts` | Prepared microphone processing graphs, per-context worklet loading, optional RNNoise and independent PCM activation/cleanup | +| `web/src/voice/microphone-capture.ts` | Prepared microphone processing graphs, per-context worklet loading, GTCRN/RNNoise engines, 80 Hz high-pass, preload-before-constraints fallback and independent PCM activation/cleanup | +| `web/src/voice/noise-suppression.ts` | Noise-suppression modes, capability/fallback resolution and stored-preference migration | | `web/src/voice/audio-sink.ts` | Serialized device routing per audio endpoint, with stale-operation guards | | `web/src/voice/accompaniment.ts` | Generation-bound display-audio capture, immediate pending-capture cancellation, ended listeners and committed activity | | `web/src/voice/webrtc-input.ts` | Stable WebRTC sender output, microphone gain and transactional accompaniment-source attachment | @@ -110,10 +111,12 @@ Preserve bounded audio buffering and stale-playback recovery. Audio counters sta Remote playback owns each speaker's decoder, gain and source nodes as one resource set. Member departure, decoder failure and session teardown release that set; queued callbacks must not touch its replacement. Preserve the 80 ms playback window and three-frame decoder queue threshold unless audio validation justifies changing them. -Microphone recording tests own their recorder, timeout and object URL, while the capture layer owns the microphone stream. A normal stop may publish its final recording; replacement and session teardown discard late results and revoke the old URL. Stopping a test while connected must preserve room capture. Test cancellation and stale permission failures must not change a newer test's state. +Microphone recording tests own both recorders (raw and denoised), their timeout and object URLs, while the capture layer owns the microphone stream. A normal stop may publish its final recordings; replacement and session teardown discard late results and revoke both old URLs. Stopping a test while connected must preserve room capture. Test cancellation and stale permission failures must not change a newer test's state. Device and noise-suppression changes share one configuration operation. Persist only the last successful settings; stale failures cannot roll back a newer choice. Acquiring a replacement microphone must preserve the current WebRTC peer and compatibility PCM capture until the replacement is ready. Capture callbacks are invalidated when their graph stops, separately from permission-request generations. Closing settings also releases standalone device-preview capture when no recording was started. +Microphone denoising has four modes: off, browser, RNNoise and GTCRN. Model engines are exclusive with the browser noise suppressor; never request both. Preload the selected model before acquiring the microphone so a load failure can fall back to browser denoising without a second permission prompt, and report the active engine plus a visible fallback reason. Both neural engines require a 48 kHz context. An unrecognised stored mode migrates to GTCRN, and the legacy `noiseSuppressionLevel` mirror is written for older builds. + Prepare microphone nodes and streams before replacing the live graph. A failed allocation or delayed worklet load must leave the old capture usable. Aborting preparation releases its candidate resources immediately; only activation enables PCM callbacks. Worklet module caches belong to their AudioContext. Device removal uses the normal input/output configuration transactions, including WebRTC restart and rollback on failed default-device selection. A committed graph becomes the fallback preference before subsequent device enumeration completes. Serialize `setSinkId` on each audio context or media element, since an in-flight browser sink change cannot be cancelled. Bind subsequent work to the original endpoint and current operation; session teardown invalidates queued changes and device enumeration results. If one output endpoint rejects after another changed, attempt to restore the last committed output. diff --git a/README.md b/README.md index ed182f3..720ae4c 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Join voice channels, chat and share your screen from a browser. Deploy your own | 能力 · Capability | 说明 · Highlights | | --- | --- | -| 🎙️ 语音 · Voice | Opus、可选 WebRTC、WebSocket 回退、降噪与成员音量 / Opus, optional WebRTC, fallback, noise suppression and per-member volume | +| 🎙️ 语音 · Voice | Opus、可选 WebRTC、WebSocket 回退、GTCRN / RNNoise 双引擎降噪、成员音量 / Opus, optional WebRTC, fallback, GTCRN/RNNoise denoising and per-member volume | | 💬 频道与聊天 · Channels & chat | 实时频道树、成员状态、私聊与本地历史 / Live channel tree, member state, private chat and local history | | 🖥️ 屏幕共享 · Screen sharing | 浏览器之间及与受支持的 TS6 客户端互通 / Between browsers and supported native TS6 clients | | 🎨 皮肤 · Skins | `.wskin` 外观、布局和小组件,支持 GitHub 分发 / Portable appearance, layouts and widgets, distributed through GitHub | diff --git a/docs/MICROPHONE_DENOISE.md b/docs/MICROPHONE_DENOISE.md new file mode 100644 index 0000000..fca1671 --- /dev/null +++ b/docs/MICROPHONE_DENOISE.md @@ -0,0 +1,79 @@ +# 麦克风降噪(GTCRN / RNNoise) + +WebSpeak 的麦克风链提供四档降噪:关闭、标准(浏览器)、轻量(RNNoise)、强效(GTCRN)。默认使用 GTCRN,全部在浏览器本地运行,不上传音频、不依赖 CDN。 + +## 引擎对比 + +| 引擎 | 模型/体积 | 帧长与延迟 | 说明 | +| --- | --- | --- | --- | +| GTCRN(默认) | 23.7K 参数,`gtcrn.wasm` ≈ 197 KB(gzip ≈ 116 KB) | 768 样本 ≈ 16 ms @48 kHz | ICASSP 2024,同量级质量高于 RNNoise;MIT | +| RNNoise | 85 KB,SIMD 版本 ≈ 157 KB | 480 样本 ≈ 10 ms @48 kHz | 低配设备与兼容兜底 | +| 浏览器 APM | 浏览器内置 | 浏览器内部 | `noiseSuppression: true`;Chrome 默认约 12 dB,档位不可从 `getUserMedia` 选择 | +| 关闭 | — | 0 | 不做任何处理 | + +两个神经引擎都按 48 kHz 设计。音频上下文不是 48 kHz、没有 `AudioWorklet`,或 WASM 预加载失败时,自动回退到浏览器降噪。 + +## 信号链 + +``` +getUserMedia (EC=on, AGC=off, NS=按模式) + → MediaStreamSource + → [模型模式] BiquadFilter(highpass, 80 Hz, Q=0.707) + → [模型模式] GTCRN / RNNoise (AudioWorklet) + → GainNode + → MediaStreamDestination (WebRTC) + capture worklet (兼容 PCM) +``` + +- 模型模式与浏览器降噪**互斥**。浏览器先削语音、模型再处理会损伤音质,也会浪费 CPU。 +- 80 Hz 高通只加在模型链上,去掉风扇、桌面震动和手持低频隆隆声。 +- 不做干湿混合:GTCRN 没有衰减上限 API,干声需精确延迟 768 样本才能对齐,否则产生梳状滤波。 +- 不新增噪声门:现有 VOX 已负责静音门控,模型后再叠 gate 容易切掉字头。 + +## 回退与状态 + +| 条件 | 结果 | +| --- | --- | +| 无 `AudioWorklet` | `browser`,原因 `no-worklet` | +| 音频上下文非 48 kHz | `browser`,原因 `sample-rate` | +| WASM / worklet 预加载失败 | `browser`,原因 `load-failed` | +| 预加载成功但节点构造失败 | 本次不挂模型,`off` + `load-failed`,设置页显示“模型未能启动,本次不降噪”,下次重连重试 | +| 浏览器忽略 `noiseSuppression:false` | 照常运行,状态显示可能叠加 | + +设置页会显示实际生效引擎与回退原因,而不是只显示用户选择。`microphoneProcessing` 同时向皮肤暴露 `noiseSuppressionEnabled` 布尔值,旧契约不变。 + +## 参考项目 + +| 项目 | 采用点 | +| --- | --- | +| Jitsi Meet | RNNoise 跑在 AudioWorklet;模型降噪开启时关闭浏览器降噪 | +| Element Call / matrix-js-sdk | `@sapphi-red/web-noise-suppressor` 的 worklet 生命周期管理 | +| WorkAdventure | 双引擎可切换、48 kHz 上下文要求;其 DFN3 方案因 71 ms 延迟未采用 | +| Mumble | 引擎选择 + 本地回环试听 | +| OBS Studio | RNNoise 作低配档、降噪与噪声门分离 | +| WebRTC APM | NS 档位与 80 Hz 高通;浏览器档位不可编程,只作兜底 | +| LiveKit / Krisp | 商业模型体积与授权不适合自托管,未采用 | +| DeepFilterNet3 | 质量更高但模型 + WASM 约 11 MB、附加 30–71 ms,留作后续可选 | + +## 手工验证记录 + +自动化测试不声称真实音质。每次改动采集链后,在 `web/` 下 `npm run build` 并记录: + +| 环境 | 采样率 | 实际引擎 | 附加延迟 | CPU | 结论 | +| --- | --- | --- | --- | --- | --- | +| Chromium(无头 Chrome,`--autoplay-policy=no-user-gesture-required`,220 Hz 测试音) | 48 kHz | GTCRN | 16 ms | 未测 | 通过:`engine=gtcrn`、`fallback=null`;700 ms 收到 35 帧 PCM,稳态音被模型明显衰减 | +| Chrome / Edge(Windows,真实麦克风) | 48 kHz | GTCRN | 16 ms | 待测 | 待听感与 CPU 复测 | +| Firefox(Windows) | 48 kHz | 待测 | 16 ms | 待测 | 待测 | +| Android WebView | 48 kHz | 待测 | 16 ms | 待测 | 待测 | + +验证项: + +1. 设置页显示“当前生效:GTCRN”,切换四档均能重建采集且不中断语音。 +2. 麦克风测试的“原始 / 降噪后”来自同一段 5 秒采集,能听出风扇/键盘差异。 +3. 稳态噪声段衰减 ≥12 dB,语音电平变化 ≤3 dB;键盘声不出现“抽真空”或字头被切。 +4. 阻断 `gtcrn.wasm` 请求后重新连接,状态回退到浏览器降噪且仍能开麦。 + +## 部署注意 + +- 资源由 Vite 打包进 `web/dist/assets`(`gtcrn-*.wasm`、`workletProcessor-*.js`),随现有静态资源一起部署。 +- 若反向代理额外添加 CSP,需要允许 `wasm-unsafe-eval`(WASM 实例化)与 `worker-src 'self' blob:`(AudioWorklet)。 +- 不需要新增环境变量或服务端配置。 diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.md index de3aaae..29393cf 100644 --- a/docs/README.zh-CN.md +++ b/docs/README.zh-CN.md @@ -34,7 +34,7 @@ WebSpeak 是可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语 | 能力 | 说明 | | --- | --- | -| 实时语音 | Opus 音频、可选 WebRTC、兼容 WebSocket 回退;支持闭麦、VOX、设备选择、浏览器降噪和成员独立音量。 | +| 实时语音 | Opus 音频、可选 WebRTC、兼容 WebSocket 回退;支持闭麦、VOX、设备选择、GTCRN / RNNoise 双引擎降噪、原始/降噪 A/B 试听和成员独立音量。 | | 频道与消息 | 频道树、TeamSpeak 频道分隔栏、成员状态、频道切换、频道/服务器/私聊消息、戳一戳、耳语及本地聊天历史。 | | 屏幕与音频共享 | 浏览器之间及与受支持的 TeamSpeak 6 原生客户端共享屏幕;提供采集质量、码率和统计面板,桌面端还可分享窗口或标签页音频。 | | 身份与连接 | 身份保持、TS3 身份导入/导出、收藏和历史连接、SRV 与 Nickname 地址解析、IPv4/IPv6 及邀请链接。 | diff --git a/package.json b/package.json index 00c830c..46a83fd 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "scripts": { "dev": "tsx src/index.ts", "build": "tsc", - "test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/turn-credentials.test.ts src/server/voice-ice-config.test.ts src/server/audio-pacer.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/voice-ice.test.ts src/shared/voice-profile.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/jitter-buffer.test.ts web/test/remote-playback.test.ts web/test/opus-uplink.test.ts web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs web/src/services/host-recovery-presentation.test.ts web/test/opus-uplink-browser.test.mjs src/shared/voice-audio.test.ts src/server/downlink-batcher.test.ts", + "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/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/turn-credentials.test.ts src/server/voice-ice-config.test.ts src/server/audio-pacer.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/voice-ice.test.ts src/shared/voice-profile.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/jitter-buffer.test.ts web/test/remote-playback.test.ts web/test/opus-uplink.test.ts web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs web/src/services/host-recovery-presentation.test.ts web/test/opus-uplink-browser.test.mjs src/shared/voice-audio.test.ts src/server/downlink-batcher.test.ts", "verify": "npm test && npm run build && npm run web:build", "skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs", "skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs", diff --git a/web/src/components/web-client/AudioDock.vue b/web/src/components/web-client/AudioDock.vue index 5b11719..e978c95 100644 --- a/web/src/components/web-client/AudioDock.vue +++ b/web/src/components/web-client/AudioDock.vue @@ -52,10 +52,11 @@
@@ -131,12 +132,12 @@ import type { useVoiceWebSocket } from "../../composables/useVoiceWebSocket.js"; import type { useWebClientAudioControls } from "../../composables/useWebClientAudioControls.js"; const props = defineProps<{ - model: Pick, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionLevel" | "accompanimentActive">; + model: Pick, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionMode" | "accompanimentActive">; controls: Pick, "toggleMicrophone" | "toggleNoiseSuppression" | "onInputVolume" | "onOutputVolume" | "onNoiseSuppressionChange" | "toggleAccompaniment">; t: (key: string) => string; rangeStyle: (value: number, max: number) => Record; }>(); -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: [] }>(); diff --git a/web/src/components/web-client/AudioSettingsDialog.vue b/web/src/components/web-client/AudioSettingsDialog.vue index a025a48..34635c3 100644 --- a/web/src/components/web-client/AudioSettingsDialog.vue +++ b/web/src/components/web-client/AudioSettingsDialog.vue @@ -78,12 +78,14 @@ >

{{ processingStatus }}

{{ t("optimal") }}{{ t("loud") }}

{{ t("localMicTestHint") }}

+
+ + +
+ +

{{ t("micTestCompareHint") }}

+
, | "audioPermission" | "audioContextState" | "microphoneMuted" - | "noiseSuppressionLevel" + | "noiseSuppressionMode" + | "microphoneProcessing" | "inputVolume" | "outputVolume" | "voxThreshold" @@ -271,6 +281,7 @@ type AudioSettingsState = Pick, | "micLevel" | "microphoneTestActive" | "testAudioUrl" + | "testAudioDryUrl" >; type AudioSettingsControls = Pick, | "settingsError" @@ -308,7 +319,8 @@ const { audioPermission, audioContextState, microphoneMuted, - noiseSuppressionLevel, + noiseSuppressionMode, + microphoneProcessing, inputVolume, outputVolume, voxThreshold, @@ -316,6 +328,7 @@ const { micLevel, microphoneTestActive, testAudioUrl, + testAudioDryUrl, } = props.model; const { settingsError: audioSettingsError, @@ -346,4 +359,30 @@ const outputDeviceOptions = computed(() => [ label: device.label || props.t("speakerNumber", { index: index + 1 }), })), ]); + +const testVariant = ref<"processed" | "dry">("processed"); +const testAudioSrc = computed(() => testVariant.value === "dry" + ? testAudioDryUrl.value + : (testAudioUrl.value || testAudioDryUrl.value)); +const processingFallback = computed(() => microphoneProcessing.fallback); +const processingWarning = computed(() => microphoneProcessing.warning); +// Reflect the engine that really ran, not the stored preference. +const processingStatus = computed(() => { + const fallback = microphoneProcessing.fallback; + if (fallback === "no-worklet") return props.t("noiseSuppressionFallbackNoWorklet"); + if (fallback === "sample-rate") return props.t("noiseSuppressionFallbackSampleRate"); + // A model that died after the browser suppressor was already disabled leaves + // no denoising at all: say so instead of promising a browser fallback. + if (fallback === "load-failed") { + return microphoneProcessing.engine === "off" + ? props.t("noiseSuppressionModelInactive") + : props.t("noiseSuppressionFallbackLoad"); + } + if (microphoneProcessing.warning === "browser-ns-active") return props.t("noiseSuppressionBrowserStacking"); + if (microphoneProcessing.engine === "gtcrn") return `${props.t("noiseSuppressionActive")}:${props.t("noiseSuppressionEngineGtcrn")}`; + if (microphoneProcessing.engine === "rnnoise") return `${props.t("noiseSuppressionActive")}:${props.t("noiseSuppressionEngineRnnoise")}`; + if (microphoneProcessing.engine === "browser") return `${props.t("noiseSuppressionActive")}:${props.t("noiseSuppressionEngineBrowser")}`; + if (microphoneProcessing.requestedEngine !== "off") return props.t("noiseSuppressionPreparing"); + return props.t("noiseSuppressionEngineOff"); +}); diff --git a/web/src/composables/useVoiceWebSocket.ts b/web/src/composables/useVoiceWebSocket.ts index 2b104b8..a38cd18 100644 --- a/web/src/composables/useVoiceWebSocket.ts +++ b/web/src/composables/useVoiceWebSocket.ts @@ -2,6 +2,15 @@ import { createRemotePlayback } from "../voice/remote-playback.js"; import { createMicrophoneTest } from "../voice/microphone-test.js"; import { createMicrophoneCaptureFactory, type MicrophoneCapture, type MicrophoneProcessingSettings } from "../voice/microphone-capture.js"; export type { MicrophoneProcessingSettings } from "../voice/microphone-capture.js"; +import { + isNeuralDenoiseEngine, + legacyNoiseSuppressionLevel, + migrateStoredNoiseSuppression, + resolveDenoisePlan, + type DenoisePlan, + type NoiseSuppressionMode, + type StoredNoiseSuppressionLevel, +} from "../voice/noise-suppression.js"; import { createAudioSinkRouter } from "../voice/audio-sink.js"; import { createAccompaniment, type AccompanimentErrorCode } from "../voice/accompaniment.js"; import { createWebRtcTransport } from "../voice/webrtc-transport.js"; @@ -298,24 +307,35 @@ export function useVoiceWebSocket() { echoCancellation: null, noiseSuppression: null, autoGainControl: null, - rnnoise: null, + engine: "off", + requestedEngine: "gtcrn", + fallback: null, + warning: null, }); const audioContextState = ref("unknown"); const micLevel = ref(0); const microphoneTestActive = ref(false); const testAudioUrl = ref(""); + const testAudioDryUrl = ref(""); const microphoneTest = createMicrophoneTest({ - prepare: async () => { await prepareInputDevices(); return micStream; }, + prepare: async () => { + await prepareInputDevices(); + if (!micStream) return null; + return { dry: micStream, processed: microphoneCapture?.processedStream ?? micStream }; + }, onActive: active => { microphoneTestActive.value = active; }, onUrl: url => { testAudioUrl.value = url; }, + onDryUrl: url => { testAudioDryUrl.value = url; }, onStopped: () => { if (!state.connected) stopMicrophone(); }, onError: error => { setMicrophoneError(error); }, }); const microphoneMuted = ref(false); - const noiseSuppressionLevel = ref<"off" | "standard" | "strong">("strong"); - const noiseSuppressionEnabled = computed(() => noiseSuppressionLevel.value !== "off"); + const noiseSuppressionMode = ref("gtcrn"); + // Compatibility view for existing skins/tests: the old three-value field. + const noiseSuppressionLevel = computed(() => legacyNoiseSuppressionLevel(noiseSuppressionMode.value)); + const noiseSuppressionEnabled = computed(() => noiseSuppressionMode.value !== "off"); let noiseSuppressionTouched = false; - let committedNoiseSuppressionLevel = noiseSuppressionLevel.value; + let committedNoiseSuppressionMode = noiseSuppressionMode.value; const inputVolume = ref(1); const outputVolume = ref(1); const outputMuted = ref(false); @@ -509,8 +529,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, @@ -534,14 +555,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)); @@ -688,12 +708,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, @@ -822,9 +848,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(); @@ -832,7 +881,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 @@ -849,12 +898,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(); @@ -984,13 +1039,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; } @@ -1181,7 +1236,7 @@ export function useVoiceWebSocket() { deviceListGeneration++; selectedInputDeviceId.value = committedInputDeviceId; selectedOutputDeviceId.value = committedOutputDeviceId; - noiseSuppressionLevel.value = committedNoiseSuppressionLevel; + noiseSuppressionMode.value = committedNoiseSuppressionMode; microphoneTest.dispose(); audioDiagnostics.reset(); commands.clear(new Error("语音连接已关闭")); @@ -1672,21 +1727,28 @@ export function useVoiceWebSocket() { void saveAudioPreferences(); } - async function setNoiseSuppressionLevel(level: "off" | "standard" | "strong"): Promise { - if (noiseSuppressionLevel.value === level) return; + async function setNoiseSuppressionMode(mode: NoiseSuppressionMode): Promise { + if (noiseSuppressionMode.value === mode) return; noiseSuppressionTouched = true; - const previousLevel = noiseSuppressionLevel.value; - noiseSuppressionLevel.value = level; + const previousMode = noiseSuppressionMode.value; + noiseSuppressionMode.value = mode; try { await reconfigureMicrophone(); } catch (error) { - noiseSuppressionLevel.value = previousLevel; + noiseSuppressionMode.value = previousMode; setMicrophoneError(error); } } + /** Legacy three-value entry point; kept for external callers and skins. */ + async function setNoiseSuppressionLevel(level: StoredNoiseSuppressionLevel): Promise { + await setNoiseSuppressionMode(level === "off" ? "off" : level === "standard" ? "browser" : "gtcrn"); + } + function setNoiseSuppressionEnabled(enabled: boolean): Promise { - return setNoiseSuppressionLevel(enabled ? (noiseSuppressionLevel.value === "off" ? "strong" : noiseSuppressionLevel.value) : "off"); + return setNoiseSuppressionMode(enabled + ? (noiseSuppressionMode.value === "off" ? "gtcrn" : noiseSuppressionMode.value) + : "off"); } function setOutputVolume(volume: number): void { @@ -1727,6 +1789,7 @@ export function useVoiceWebSocket() { pokeNotifications, microphoneMuted, noiseSuppressionEnabled, + noiseSuppressionMode, noiseSuppressionLevel, inputVolume, outputVolume, @@ -1745,6 +1808,7 @@ export function useVoiceWebSocket() { micLevel, microphoneTestActive, testAudioUrl, + testAudioDryUrl, speakingIds, whisperTargetIds, whisperActive, @@ -1754,6 +1818,7 @@ export function useVoiceWebSocket() { accompanimentErrorCode, setVolume, setInputVolume, + setNoiseSuppressionMode, setNoiseSuppressionLevel, setNoiseSuppressionEnabled, setOutputVolume, diff --git a/web/src/composables/useWebClientAudioControls.ts b/web/src/composables/useWebClientAudioControls.ts index 3ff02ab..dddba2b 100644 --- a/web/src/composables/useWebClientAudioControls.ts +++ b/web/src/composables/useWebClientAudioControls.ts @@ -1,11 +1,10 @@ import { computed, onScopeDispose, ref, watch, type Ref } from "vue"; -import type { LocalPreferences } from "../services/local-persistence.js"; -type NoiseSuppressionLevel = NonNullable; +import type { NoiseSuppressionMode } from "../voice/noise-suppression.js"; interface UseWebClientAudioControlsOptions { settingsOpen: Ref; microphoneMuted: Readonly>; - noiseSuppressionLevel: Readonly>; + noiseSuppressionMode: Readonly>; inputVolume: Readonly>; voxThreshold: Readonly>; notificationVolume: Readonly>; @@ -16,7 +15,7 @@ interface UseWebClientAudioControlsOptions { whisperTargetIds: Set; prepareInputDevices: () => Promise; setInputVolume: (value: number) => void; - setNoiseSuppressionLevel: (level: NoiseSuppressionLevel) => Promise; + setNoiseSuppressionMode: (mode: NoiseSuppressionMode) => Promise; setOutputVolume: (value: number) => void; setVoxThreshold: (value: number) => void; setNotificationVolume: (value: number) => void; @@ -36,7 +35,7 @@ interface UseWebClientAudioControlsOptions { export function useWebClientAudioControls({ settingsOpen, microphoneMuted, - noiseSuppressionLevel, + noiseSuppressionMode, inputVolume, voxThreshold, notificationVolume, @@ -47,7 +46,7 @@ export function useWebClientAudioControls({ whisperTargetIds, prepareInputDevices, setInputVolume, - setNoiseSuppressionLevel, + setNoiseSuppressionMode, setOutputVolume, setVoxThreshold, setNotificationVolume, @@ -95,12 +94,12 @@ export function useWebClientAudioControls({ } function onNoiseSuppressionChange(event: Event): void { - const level = (event.target as HTMLSelectElement).value; - if (level === "off" || level === "standard" || level === "strong") void setNoiseSuppressionLevel(level); + const mode = (event.target as HTMLSelectElement).value; + if (mode === "off" || mode === "browser" || mode === "rnnoise" || mode === "gtcrn") void setNoiseSuppressionMode(mode); } function toggleNoiseSuppression(): void { - void setNoiseSuppressionLevel(noiseSuppressionLevel.value === "off" ? "strong" : "off"); + void setNoiseSuppressionMode(noiseSuppressionMode.value === "off" ? "gtcrn" : "off"); } function onOutputVolume(event: Event): void { diff --git a/web/src/i18n/web-client.ts b/web/src/i18n/web-client.ts index a4cbc18..83c08dc 100644 --- a/web/src/i18n/web-client.ts +++ b/web/src/i18n/web-client.ts @@ -341,11 +341,29 @@ export const webClientTranslations: Record> = { notificationVolume: "通知音量", audioStatus: "音频状态", audioReady: "音频已就绪", - noiseSuppression: "浏览器降噪", - noiseSuppressionHint: "标准使用浏览器降噪;强效模式会叠加 RNNoise(设备支持时)。", + noiseSuppression: "麦克风降噪", + noiseSuppressionHint: "强效使用本地 AI 模型 GTCRN,轻量使用 RNNoise;模型模式会关闭浏览器降噪,避免叠加。", noiseSuppressionOff: "关闭", noiseSuppressionStandard: "标准(浏览器)", - noiseSuppressionStrong: "强效(RNNoise)", + noiseSuppressionStandardShort: "标准", + noiseSuppressionLight: "轻量(RNNoise)", + noiseSuppressionLightShort: "轻量", + noiseSuppressionStrong: "强效(GTCRN)", + noiseSuppressionStrongShort: "强效", + noiseSuppressionActive: "当前生效", + noiseSuppressionEngineGtcrn: "GTCRN · 本地 WASM · 约 16 ms", + noiseSuppressionEngineRnnoise: "RNNoise · 约 10 ms", + noiseSuppressionEngineBrowser: "浏览器降噪", + noiseSuppressionEngineOff: "已关闭", + noiseSuppressionPreparing: "正在准备降噪模型…", + noiseSuppressionFallbackNoWorklet: "已回退到浏览器降噪:当前浏览器不支持 AudioWorklet。", + noiseSuppressionFallbackSampleRate: "已回退到浏览器降噪:音频上下文不是 48 kHz。", + noiseSuppressionFallbackLoad: "已回退到浏览器降噪:降噪模型加载失败。", + noiseSuppressionModelInactive: "降噪模型未能启动,本次不降噪;重新连接后会自动重试。", + noiseSuppressionBrowserStacking: "浏览器仍启用了降噪,可能与模型叠加;建议改用轻量或标准模式。", + micTestOriginal: "原始", + micTestDenoised: "降噪后", + micTestCompareHint: "同一段录音分别播放原始与降噪后音频,便于对比。", exportAudioTrace: "导出最近两分钟的音频诊断", audioTraceHint: "可导出不含语音内容、昵称或服务器地址的本地诊断记录。", backgroundVoiceHint: "浏览器后台麦克风受浏览器和系统策略限制;锁屏或切后台后可能暂停。", @@ -775,11 +793,29 @@ export const webClientTranslations: Record> = { notificationVolume: "Notification volume", audioStatus: "Audio status", audioReady: "Audio ready", - noiseSuppression: "Browser noise suppression", - noiseSuppressionHint: "Standard uses browser filtering; strong also enables RNNoise when supported.", + noiseSuppression: "Microphone noise suppression", + noiseSuppressionHint: "Strong uses the local GTCRN model; Light uses RNNoise. Model modes disable browser denoising so the two never stack.", noiseSuppressionOff: "Off", noiseSuppressionStandard: "Standard (browser)", - noiseSuppressionStrong: "Strong (RNNoise)", + noiseSuppressionStandardShort: "Standard", + noiseSuppressionLight: "Light (RNNoise)", + noiseSuppressionLightShort: "Light", + noiseSuppressionStrong: "Strong (GTCRN)", + noiseSuppressionStrongShort: "Strong", + noiseSuppressionActive: "Active", + noiseSuppressionEngineGtcrn: "GTCRN · local WASM · about 16 ms", + noiseSuppressionEngineRnnoise: "RNNoise · about 10 ms", + noiseSuppressionEngineBrowser: "Browser noise suppression", + noiseSuppressionEngineOff: "Off", + noiseSuppressionPreparing: "Preparing the denoise model…", + noiseSuppressionFallbackNoWorklet: "Fell back to browser denoising: AudioWorklet is unavailable.", + noiseSuppressionFallbackSampleRate: "Fell back to browser denoising: the audio context is not 48 kHz.", + noiseSuppressionFallbackLoad: "Fell back to browser denoising: the model failed to load.", + noiseSuppressionModelInactive: "The denoise model could not start, so this session runs without denoising. It retries on the next connection.", + noiseSuppressionBrowserStacking: "The browser still applies its own denoising, so it may stack with the model. Try Light or Standard.", + micTestOriginal: "Original", + micTestDenoised: "Denoised", + micTestCompareHint: "The same take plays raw and denoised so you can compare them.", exportAudioTrace: "Export the last two minutes of audio diagnostics", audioTraceHint: "The local trace excludes audio content, nicknames, and server addresses.", backgroundVoiceHint: "Background microphone capture depends on browser and OS policy and may pause when hidden or locked.", @@ -1202,11 +1238,29 @@ webClientTranslations.de = { notificationVolume: "Benachrichtigungslautstärke", audioStatus: "Audiostatus", audioReady: "Audio bereit", - noiseSuppression: "Browser-Geräuschunterdrückung", - noiseSuppressionHint: "Standard nutzt die Browserfilterung; Stark aktiviert zusätzlich RNNoise, sofern unterstützt.", + noiseSuppression: "Mikrofon-Geräuschunterdrückung", + noiseSuppressionHint: "Stark nutzt das lokale GTCRN-Modell, Leicht nutzt RNNoise. Modus mit Modell deaktiviert die Browser-Filterung, damit sich beide nicht überlagern.", noiseSuppressionOff: "Aus", noiseSuppressionStandard: "Standard (Browser)", - noiseSuppressionStrong: "Stark (RNNoise)", + noiseSuppressionStandardShort: "Standard", + noiseSuppressionLight: "Leicht (RNNoise)", + noiseSuppressionLightShort: "Leicht", + noiseSuppressionStrong: "Stark (GTCRN)", + noiseSuppressionStrongShort: "Stark", + noiseSuppressionActive: "Aktiv", + noiseSuppressionEngineGtcrn: "GTCRN · lokales WASM · ca. 16 ms", + noiseSuppressionEngineRnnoise: "RNNoise · ca. 10 ms", + noiseSuppressionEngineBrowser: "Browser-Geräuschunterdrückung", + noiseSuppressionEngineOff: "Aus", + noiseSuppressionPreparing: "Geräuschmodell wird vorbereitet…", + noiseSuppressionFallbackNoWorklet: "Auf Browser-Filterung zurückgefallen: AudioWorklet ist nicht verfügbar.", + noiseSuppressionFallbackSampleRate: "Auf Browser-Filterung zurückgefallen: Der Audiokontext läuft nicht mit 48 kHz.", + noiseSuppressionFallbackLoad: "Auf Browser-Filterung zurückgefallen: Das Modell konnte nicht geladen werden.", + noiseSuppressionModelInactive: "Das Geräuschmodell konnte nicht starten; diese Sitzung läuft ohne Geräuschunterdrückung. Beim nächsten Verbinden wird es erneut versucht.", + noiseSuppressionBrowserStacking: "Der Browser filtert weiterhin selbst; das kann sich mit dem Modell überlagern. Bitte Leicht oder Standard verwenden.", + micTestOriginal: "Original", + micTestDenoised: "Entrauscht", + micTestCompareHint: "Dieselbe Aufnahme wird roh und entrauscht abgespielt, damit du vergleichen kannst.", exportAudioTrace: "Letzte zwei Minuten der Audiodiagnose exportieren", audioTraceHint: "Der lokale Verlauf enthält keine Audioinhalte, Namen oder Serveradressen.", backgroundVoiceHint: "Die Mikrofonaufnahme im Hintergrund hängt von Browser und Betriebssystem ab und kann pausieren.", @@ -1377,11 +1431,29 @@ webClientTranslations.ru = { screenShareBitrate8M: "8 Мбит/с", screenShareBitrate12M: "12 Мбит/с", screenShareSettingsNote: "Настройки применятся при следующем запуске трансляции", - noiseSuppression: "Шумоподавление", - noiseSuppressionHint: "Стандартный режим использует фильтр браузера; усиленный также включает RNNoise, если он поддерживается.", + noiseSuppression: "Шумоподавление микрофона", + noiseSuppressionHint: "Усиленный режим использует локальную модель GTCRN, лёгкий — RNNoise. Режимы с моделью отключают шумоподавление браузера, чтобы они не складывались.", noiseSuppressionOff: "Выкл.", noiseSuppressionStandard: "Стандартный (браузер)", - noiseSuppressionStrong: "Усиленный (RNNoise)", + noiseSuppressionStandardShort: "Стандарт", + noiseSuppressionLight: "Лёгкий (RNNoise)", + noiseSuppressionLightShort: "Лёгкий", + noiseSuppressionStrong: "Усиленный (GTCRN)", + noiseSuppressionStrongShort: "Усиленный", + noiseSuppressionActive: "Активно", + noiseSuppressionEngineGtcrn: "GTCRN · локальный WASM · около 16 мс", + noiseSuppressionEngineRnnoise: "RNNoise · около 10 мс", + noiseSuppressionEngineBrowser: "Шумоподавление браузера", + noiseSuppressionEngineOff: "Выключено", + noiseSuppressionPreparing: "Подготовка модели шумоподавления…", + noiseSuppressionFallbackNoWorklet: "Используется шумоподавление браузера: AudioWorklet недоступен.", + noiseSuppressionFallbackSampleRate: "Используется шумоподавление браузера: аудиоконтекст работает не на 48 кГц.", + noiseSuppressionFallbackLoad: "Используется шумоподавление браузера: модель не загрузилась.", + noiseSuppressionModelInactive: "Модель шумоподавления не запустилась, поэтому в этой сессии шумоподавление не применяется. Повторная попытка — при следующем подключении.", + noiseSuppressionBrowserStacking: "Браузер всё ещё применяет своё шумоподавление, возможна перегрузка. Попробуйте лёгкий или стандартный режим.", + micTestOriginal: "Оригинал", + micTestDenoised: "После обработки", + micTestCompareHint: "Одна и та же запись воспроизводится в исходном и обработанном виде для сравнения.", exportAudioTrace: "Экспортировать диагностику звука за последние две минуты", audioTraceHint: "Локальная запись не содержит аудио, имён или адресов серверов.", backgroundVoiceHint: "Фоновая запись с микрофона зависит от браузера и ОС и может приостанавливаться.", @@ -1598,11 +1670,29 @@ webClientTranslations.ja = { screenShareBitrate8M: "8 Mbps", screenShareBitrate12M: "12 Mbps", screenShareSettingsNote: "次回の共有開始時に適用されます", - noiseSuppression: "ノイズ抑制", - noiseSuppressionHint: "標準はブラウザーのフィルターを使用し、強力は対応環境で RNNoise も有効にします。", + noiseSuppression: "マイクのノイズ抑制", + noiseSuppressionHint: "強力はローカルの GTCRN モデル、軽量は RNNoise を使用します。モデル使用時はブラウザーのノイズ抑制を切るため、二重にはかかりません。", noiseSuppressionOff: "オフ", noiseSuppressionStandard: "標準(ブラウザー)", - noiseSuppressionStrong: "強力(RNNoise)", + noiseSuppressionStandardShort: "標準", + noiseSuppressionLight: "軽量(RNNoise)", + noiseSuppressionLightShort: "軽量", + noiseSuppressionStrong: "強力(GTCRN)", + noiseSuppressionStrongShort: "強力", + noiseSuppressionActive: "現在の適用", + noiseSuppressionEngineGtcrn: "GTCRN · ローカル WASM · 約 16 ms", + noiseSuppressionEngineRnnoise: "RNNoise · 約 10 ms", + noiseSuppressionEngineBrowser: "ブラウザーのノイズ抑制", + noiseSuppressionEngineOff: "オフ", + noiseSuppressionPreparing: "ノイズ抑制モデルを準備中…", + noiseSuppressionFallbackNoWorklet: "ブラウザーのノイズ抑制に戻しました:AudioWorklet が利用できません。", + noiseSuppressionFallbackSampleRate: "ブラウザーのノイズ抑制に戻しました:オーディオコンテキストが 48 kHz ではありません。", + noiseSuppressionFallbackLoad: "ブラウザーのノイズ抑制に戻しました:モデルを読み込めませんでした。", + noiseSuppressionModelInactive: "ノイズ抑制モデルを起動できなかったため、この接続ではノイズ抑制なしで動作します。次回接続時に再試行します。", + noiseSuppressionBrowserStacking: "ブラウザーのノイズ抑制も有効なため、モデルと重なる可能性があります。軽量または標準をお試しください。", + micTestOriginal: "元の音声", + micTestDenoised: "処理後", + micTestCompareHint: "同じ録音を元の音声と処理後の音声で再生して比較できます。", exportAudioTrace: "直近 2 分間の音声診断をエクスポート", audioTraceHint: "音声、ニックネーム、サーバーアドレスを含まないローカル診断です。", backgroundVoiceHint: "バックグラウンドでのマイク利用はブラウザーと OS の制御を受け、停止する場合があります。", diff --git a/web/src/services/local-persistence.test.ts b/web/src/services/local-persistence.test.ts index a8caaa8..8a9c53e 100644 --- a/web/src/services/local-persistence.test.ts +++ b/web/src/services/local-persistence.test.ts @@ -120,3 +120,33 @@ test("storage read success still returns its original data after transaction com tx.read({ schemaVersion: 1, skinId: "builtin.dark" }); tx.commit(); assert.deepEqual(await pending, { schemaVersion: 1, skinId: "builtin.dark", volumesByUid: {} }); }); +test("noise suppression mode is stored beside the legacy level for older builds", async () => { + const pending = saveLocalPreferences({ + schemaVersion: 1, + noiseSuppressionMode: "gtcrn", + noiseSuppressionLevel: "strong", + noiseSuppressionEnabled: true, + }); + await nextTurn(); const tx = transactions[0]; + tx.read({ schemaVersion: 1, noiseSuppressionMode: "browser", noiseSuppressionLevel: "standard" }); + assert.deepEqual(tx.written, { + id: "singleton", + schemaVersion: 1, + noiseSuppressionMode: "gtcrn", + noiseSuppressionLevel: "strong", + noiseSuppressionEnabled: true, + volumesByUid: {}, + }); + tx.writtenSuccessfully(); tx.commit(); await pending; + + const read = loadLocalPreferences(); + await nextTurn(); const readTx = transactions[1]; + readTx.read({ schemaVersion: 1, noiseSuppressionLevel: "strong", noiseSuppressionEnabled: true }); + readTx.commit(); + assert.deepEqual(await read, { + schemaVersion: 1, + noiseSuppressionLevel: "strong", + noiseSuppressionEnabled: true, + volumesByUid: {}, + }); +}); diff --git a/web/src/services/local-persistence.ts b/web/src/services/local-persistence.ts index 1d226c6..eb0c859 100644 --- a/web/src/services/local-persistence.ts +++ b/web/src/services/local-persistence.ts @@ -146,6 +146,7 @@ export interface LocalPreferences { skinId?: string; microphoneMuted?: boolean; noiseSuppressionEnabled?: boolean; + noiseSuppressionMode?: "off" | "browser" | "rnnoise" | "gtcrn"; noiseSuppressionLevel?: "off" | "standard" | "strong"; voxThreshold?: number; language?: "zh" | "en" | "de" | "ru" | "ja"; diff --git a/web/src/styles/web-client.css b/web/src/styles/web-client.css index 5664649..28a4c35 100644 --- a/web/src/styles/web-client.css +++ b/web/src/styles/web-client.css @@ -4648,6 +4648,40 @@ margin-top: 11px; } +:deep(.noise-suppression-status) { + margin: 2px 0 12px; +} + +:deep(.mic-test-compare) { + margin-top: 11px; +} + +:deep(.mic-test-tabs) { + display: flex; + gap: 6px; + margin-bottom: 8px; +} + +:deep(.mic-test-tabs button) { + padding: 6px 10px; + color: #006a64; + background: #eef7f5; + border: 1px solid #d5e7e2; + border-radius: 6px; + font-size: 10px; + cursor: pointer; +} + +:deep(.mic-test-tabs button.active) { + color: #fff; + background: #006a64; + border-color: #006a64; +} + +:deep(.mic-test-compare .test-audio) { + margin-top: 0; +} + /* Shared interaction/layout rules; appearance is supplied by a built-in skin package. */ .join-page .join-card { diff --git a/web/src/views/WebClient.vue b/web/src/views/WebClient.vue index 3b7ce03..17a7422 100644 --- a/web/src/views/WebClient.vue +++ b/web/src/views/WebClient.vue @@ -1060,7 +1060,7 @@ const { pokeNotifications, microphoneMuted, noiseSuppressionEnabled, - noiseSuppressionLevel, + noiseSuppressionMode, inputVolume, outputVolume, outputMuted, @@ -1073,17 +1073,19 @@ const { outputDeviceSupported, audioPermission, audioContextState, + microphoneProcessing, identityMaterial, micLevel, microphoneTestActive, testAudioUrl, + testAudioDryUrl, speakingIds, volumes, whisperTargetIds, whisperActive, setVolume, setInputVolume, - setNoiseSuppressionLevel, + setNoiseSuppressionMode, setOutputVolume, toggleOutputMute, setVoxThreshold, @@ -1279,7 +1281,7 @@ const skinHomeFeatures = computed(() => { const audioControls = useWebClientAudioControls({ settingsOpen, microphoneMuted, - noiseSuppressionLevel, + noiseSuppressionMode, inputVolume, voxThreshold, notificationVolume, @@ -1290,7 +1292,7 @@ const audioControls = useWebClientAudioControls({ whisperTargetIds, prepareInputDevices, setInputVolume, - setNoiseSuppressionLevel, + setNoiseSuppressionMode, setOutputVolume, setVoxThreshold, setNotificationVolume, @@ -1314,7 +1316,7 @@ function reconnectMobile(): void { reconnectNow(); } const { toggleMicrophone, stopWhisperTalk } = audioControls; -const audioDockState = { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive }; +const audioDockState = { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionMode, accompanimentActive }; const audioSettingsState = { inputDevices, outputDevices, @@ -1323,8 +1325,9 @@ const audioSettingsState = { outputDeviceSupported, audioPermission, audioContextState, + microphoneProcessing, microphoneMuted, - noiseSuppressionLevel, + noiseSuppressionMode, inputVolume, outputVolume, voxThreshold, @@ -1332,6 +1335,7 @@ const audioSettingsState = { micLevel, microphoneTestActive, testAudioUrl, + testAudioDryUrl, }; diff --git a/web/src/voice/microphone-capture.ts b/web/src/voice/microphone-capture.ts index 1308fdf..5f96b6e 100644 --- a/web/src/voice/microphone-capture.ts +++ b/web/src/voice/microphone-capture.ts @@ -1,13 +1,22 @@ -import { RnnoiseWorkletNode, loadRnnoise } from "@sapphi-red/web-noise-suppressor"; +import { GtcrnWorkletNode, RnnoiseWorkletNode, loadGtcrn, loadRnnoise } from "@sapphi-red/web-noise-suppressor"; +import gtcrnWasmUrl from "@sapphi-red/web-noise-suppressor/gtcrn.wasm?url"; +import gtcrnWorkletUrl from "@sapphi-red/web-noise-suppressor/gtcrnWorklet.js?url"; import rnnoiseSimdWasmUrl from "@sapphi-red/web-noise-suppressor/rnnoise_simd.wasm?url"; import rnnoiseWasmUrl from "@sapphi-red/web-noise-suppressor/rnnoise.wasm?url"; import rnnoiseWorkletUrl from "@sapphi-red/web-noise-suppressor/rnnoiseWorklet.js?url"; +import { isNeuralDenoiseEngine, type DenoiseEngine, type DenoiseFallback, type DenoisePlan } from "./noise-suppression.js"; export interface MicrophoneProcessingSettings { echoCancellation: boolean | null; noiseSuppression: boolean | null; autoGainControl: boolean | null; - rnnoise: boolean | null; + /** Engine that actually ran, after capability/load fallbacks. */ + engine: DenoiseEngine; + /** Engine the user asked for before fallbacks. */ + requestedEngine: DenoiseEngine; + fallback: DenoiseFallback; + /** The browser ignored `noiseSuppression:false`; model and browser NS may stack. */ + warning: "browser-ns-active" | null; } export interface MicrophoneCapture { @@ -22,18 +31,24 @@ export interface MicrophoneCapture { interface CaptureOptions { context: AudioContext; stream: MediaStream; - rnnoiseEnabled: boolean; + plan: DenoisePlan; volume: number; signal: AbortSignal; assertCurrent(): void; onSamples(input: Float32Array, rms?: number): void; } +// A single high-pass before the neural model removes rumble the model would +// otherwise have to separate from speech. Chrome's APM uses the same corner. +const DENOISE_HIGHPASS_HZ = 80; + // Each prepared graph owns its stream and nodes. It cannot publish PCM before // activation, and aborting preparation never touches the currently live graph. export function createMicrophoneCaptureFactory() { const modules = new WeakMap>>(); - let wasmPromise: Promise | null = null; + let rnnoiseWasmPromise: Promise | null = null; + let gtcrnWasmPromise: Promise | null = null; + function loadModule(ctx: AudioContext, url: string): Promise { let cache = modules.get(ctx); if (!cache) { cache = new Map(); modules.set(ctx, cache); } @@ -49,10 +64,44 @@ export function createMicrophoneCaptureFactory() { return pending; } + function loadWasm(engine: "rnnoise" | "gtcrn"): Promise { + if (engine === "gtcrn") { + if (!gtcrnWasmPromise) { + gtcrnWasmPromise = loadGtcrn({ url: gtcrnWasmUrl }).catch(error => { + gtcrnWasmPromise = null; + throw error; + }); + } + return gtcrnWasmPromise; + } + if (!rnnoiseWasmPromise) { + rnnoiseWasmPromise = loadRnnoise({ url: rnnoiseWasmUrl, simdUrl: rnnoiseSimdWasmUrl }).catch(error => { + rnnoiseWasmPromise = null; + throw error; + }); + } + return rnnoiseWasmPromise; + } + + function engineWorkletUrl(engine: "rnnoise" | "gtcrn"): string { + return engine === "gtcrn" ? gtcrnWorkletUrl : rnnoiseWorkletUrl; + } + + /** + * Load WASM and the AudioWorklet module before getUserMedia. This lets the + * capture path request `noiseSuppression:false` only when the model is really + * available, without re-acquiring the microphone for a fallback. + */ + async function preload(ctx: AudioContext, engine: DenoiseEngine): Promise { + if (!isNeuralDenoiseEngine(engine)) return; + await Promise.all([loadWasm(engine), loadModule(ctx, engineWorkletUrl(engine))]); + } + async function prepare(options: CaptureOptions): Promise { const { context: ctx, stream, assertCurrent } = options; let source: MediaStreamAudioSourceNode | null = null; - let denoiser: RnnoiseWorkletNode | null = null; + let highpass: BiquadFilterNode | null = null; + let denoiser: RnnoiseWorkletNode | GtcrnWorkletNode | null = null; let destination: MediaStreamAudioDestinationNode | null = null; let gain: GainNode | null = null; let silent: GainNode | null = null; @@ -61,6 +110,9 @@ export function createMicrophoneCaptureFactory() { let active = false; let captureConnected = false; let disposed = false; + const requestedEngine = options.plan.engine; + let activeEngine: DenoiseEngine = requestedEngine === "browser" ? "browser" : requestedEngine === "off" ? "off" : "off"; + let fallback: DenoiseFallback = options.plan.fallback; const clean = (operation: () => void) => { try { operation(); } catch { /* release the other resources too */ } }; function stopCapture() { active = false; @@ -77,6 +129,7 @@ export function createMicrophoneCaptureFactory() { stopCapture(); if (worklet) clean(() => worklet!.port.close()); if (denoiser) { clean(() => denoiser!.destroy()); clean(() => denoiser!.disconnect()); } + if (highpass) clean(() => highpass!.disconnect()); if (source) clean(() => source!.disconnect()); if (destination) { clean(() => destination!.disconnect()); @@ -95,21 +148,34 @@ export function createMicrophoneCaptureFactory() { const settings = track.getSettings(); source = ctx.createMediaStreamSource(stream); const supportsWorklet = typeof AudioWorkletNode !== "undefined" && Boolean(ctx.audioWorklet); - if (options.rnnoiseEnabled && supportsWorklet) { + if (isNeuralDenoiseEngine(requestedEngine) && supportsWorklet) { try { - if (!wasmPromise) wasmPromise = loadRnnoise({ url: rnnoiseWasmUrl, simdUrl: rnnoiseSimdWasmUrl }).catch(error => { - wasmPromise = null; - throw error; - }); - const [wasmBinary] = await Promise.all([wasmPromise, loadModule(ctx, rnnoiseWorkletUrl)]); + const [wasmBinary] = await Promise.all([ + loadWasm(requestedEngine), + loadModule(ctx, engineWorkletUrl(requestedEngine)), + ]); assertCurrent(); - denoiser = new RnnoiseWorkletNode(ctx, { maxChannels: 1, wasmBinary }); + denoiser = requestedEngine === "gtcrn" + ? new GtcrnWorkletNode(ctx, { maxChannels: 1, wasmBinary }) + : new RnnoiseWorkletNode(ctx, { maxChannels: 1, wasmBinary }); + activeEngine = requestedEngine; } catch { - assertCurrent(); // RNNoise is optional; cancellation is not a fallback. + assertCurrent(); // A model failure must not consume cancellation as a fallback. + denoiser = null; + activeEngine = "off"; + fallback = "load-failed"; } } - const processedSource = denoiser ?? source; - if (denoiser) source.connect(denoiser); + let processedSource: AudioNode = source; + if (denoiser) { + highpass = ctx.createBiquadFilter(); + highpass.type = "highpass"; + highpass.frequency.value = DENOISE_HIGHPASS_HZ; + highpass.Q.value = Math.SQRT1_2; + source.connect(highpass); + highpass.connect(denoiser); + processedSource = denoiser; + } destination = ctx.createMediaStreamDestination(); destination.channelCount = 1; destination.channelCountMode = "explicit"; @@ -152,7 +218,10 @@ export function createMicrophoneCaptureFactory() { echoCancellation: typeof settings.echoCancellation === "boolean" ? settings.echoCancellation : null, noiseSuppression: typeof settings.noiseSuppression === "boolean" ? settings.noiseSuppression : null, autoGainControl: typeof settings.autoGainControl === "boolean" ? settings.autoGainControl : null, - rnnoise: Boolean(denoiser), + engine: activeEngine, + requestedEngine: options.plan.mode, + fallback, + warning: isNeuralDenoiseEngine(activeEngine) && settings.noiseSuppression === true ? "browser-ns-active" : null, }, activate() { if (disposed || !(worklet || script)) return; @@ -176,5 +245,5 @@ export function createMicrophoneCaptureFactory() { options.signal.removeEventListener("abort", dispose); } } - return { prepare }; + return { prepare, preload }; } diff --git a/web/src/voice/microphone-test.ts b/web/src/voice/microphone-test.ts index 7dc2d68..ba6513e 100644 --- a/web/src/voice/microphone-test.ts +++ b/web/src/voice/microphone-test.ts @@ -1,28 +1,51 @@ +export interface MicrophoneTestStreams { + /** Raw getUserMedia stream, before any denoising. */ + dry: MediaStream; + /** Graph output that is actually sent to the room. */ + processed: MediaStream; +} + interface MicrophoneTestOptions { - prepare(): Promise; + prepare(): Promise; onActive(active: boolean): void; onUrl(url: string): void; + onDryUrl(url: string): void; onStopped(): void; onError(error: unknown): void; } -interface Recording { - recorder: MediaRecorder | null; - timer: number | null; +type RecordingKind = "dry" | "processed"; + +interface RecorderSlot { + kind: RecordingKind; + recorder: MediaRecorder; chunks: Blob[]; stopped: boolean; } +interface Recording { + slots: RecorderSlot[]; + timer: number | null; + stopped: boolean; +} + // Capture belongs to the caller. This controller owns only the test operation, -// recorder, deadline and playback URL, including results queued after stop(). +// recorders, deadline and both playback URLs, including results queued after stop(). export function createMicrophoneTest(options: MicrophoneTestOptions) { let current: Recording | null = null; - let url = ""; + const urls: Record = { dry: "", processed: "" }; - function clearUrl(): void { + function clearUrl(kind: RecordingKind): void { + const url = urls[kind]; if (url) URL.revokeObjectURL(url); - url = ""; - options.onUrl(""); + urls[kind] = ""; + if (kind === "dry") options.onDryUrl(""); + else options.onUrl(""); + } + + function clearUrls(): void { + clearUrl("dry"); + clearUrl("processed"); } function finishCapture(recording: Recording): void { @@ -39,60 +62,85 @@ export function createMicrophoneTest(options: MicrophoneTestOptions) { current = null; if (recording) { finishCapture(recording); - if (recording.recorder?.state !== "inactive") { - try { recording.recorder?.stop(); } catch { /* already ended */ } + for (const slot of recording.slots) { + if (slot.recorder.state !== "inactive") { + try { slot.recorder.stop(); } catch { /* already ended */ } + } + slot.chunks.length = 0; } - recording.chunks.length = 0; + recording.slots.length = 0; } - clearUrl(); + clearUrls(); } function stop(): void { const recording = current; if (!recording) return; // A pending permission or device enumeration must not create a recorder. - if (!recording.recorder) current = null; + if (!recording.slots.length) current = null; finishCapture(recording); - if (recording.recorder?.state !== "inactive") { - try { recording.recorder?.stop(); } - catch (error) { dispose(); options.onError(error); } + for (const slot of recording.slots) { + if (slot.recorder.state === "inactive") continue; + try { slot.recorder.stop(); } + catch (error) { dispose(); options.onError(error); return; } + } + } + + function finalizeSlot(recording: Recording, slot: RecorderSlot): void { + slot.stopped = true; + if (current !== recording) return; + if (!recording.slots.every(candidate => candidate.stopped || candidate.recorder.state === "inactive")) return; + current = null; + finishCapture(recording); + for (const candidate of recording.slots) { + if (!candidate.chunks.length) continue; + try { + const url = URL.createObjectURL(new Blob(candidate.chunks, { type: candidate.recorder.mimeType || "audio/webm" })); + clearUrl(candidate.kind); + urls[candidate.kind] = url; + if (candidate.kind === "dry") options.onDryUrl(url); + else options.onUrl(url); + } catch (error) { options.onError(error); } + candidate.chunks.length = 0; } } async function start(): Promise { dispose(); - const recording: Recording = { recorder: null, timer: null, chunks: [], stopped: false }; + const recording: Recording = { slots: [], timer: null, stopped: false }; current = recording; options.onActive(true); try { - const stream = await options.prepare(); + const streams = await options.prepare(); if (current !== recording) return; // Keep the existing level-meter-only test on browsers without recording. - if (typeof MediaRecorder === "undefined" || !stream) return; - const recorder = new MediaRecorder(stream); - recording.recorder = recorder; - recorder.ondataavailable = event => { - if (current === recording && event.data.size) recording.chunks.push(event.data); - }; - recorder.onstop = () => { - if (current !== recording) return; - current = null; - finishCapture(recording); + if (typeof MediaRecorder === "undefined" || !streams) return; + let startError: unknown = null; + for (const kind of ["processed", "dry"] as const) { try { - if (recording.chunks.length) { - clearUrl(); - url = URL.createObjectURL(new Blob(recording.chunks, { type: recorder.mimeType || "audio/webm" })); - options.onUrl(url); - } - } catch (error) { options.onError(error); } - recording.chunks.length = 0; - }; - recorder.onerror = event => { - if (current !== recording) return; - dispose(); - options.onError("error" in event ? event.error : new Error("Microphone recording failed")); - }; - recorder.start(); + const recorder = new MediaRecorder(streams[kind]); + const slot: RecorderSlot = { kind, recorder, chunks: [], stopped: false }; + recorder.ondataavailable = event => { + if (current === recording && event.data.size) slot.chunks.push(event.data); + }; + recorder.onstop = () => finalizeSlot(recording, slot); + recorder.onerror = event => { + if (current !== recording) return; + dispose(); + options.onError("error" in event ? event.error : new Error("Microphone recording failed")); + }; + recorder.start(); + recording.slots.push(slot); + } catch (error) { + // One path failing must not disable the other; A/B degrades to mono. + startError ??= error; + } + } + // Nothing could record: surface the recorder failure, not a silent test. + if (!recording.slots.length) { + if (startError) throw startError; + return; + } recording.timer = window.setTimeout(() => { if (current === recording) stop(); }, 5_000); diff --git a/web/src/voice/noise-suppression.test.ts b/web/src/voice/noise-suppression.test.ts new file mode 100644 index 0000000..d938e13 --- /dev/null +++ b/web/src/voice/noise-suppression.test.ts @@ -0,0 +1,75 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + denoiseLatencyMs, + legacyNoiseSuppressionLevel, + migrateStoredNoiseSuppression, + resolveDenoisePlan, +} from "./noise-suppression.js"; + +test("resolveDenoisePlan keeps off and browser modes explicit", () => { + assert.deepEqual( + resolveDenoisePlan({ mode: "off", sampleRate: 48_000, workletSupported: true }), + { mode: "off", engine: "off", requestBrowserNs: false, fallback: null }, + ); + assert.deepEqual( + resolveDenoisePlan({ mode: "browser", sampleRate: 48_000, workletSupported: true }), + { mode: "browser", engine: "browser", requestBrowserNs: true, fallback: null }, + ); +}); + +test("model modes disable browser denoising only when they can run", () => { + assert.deepEqual( + resolveDenoisePlan({ mode: "gtcrn", sampleRate: 48_000, workletSupported: true }), + { mode: "gtcrn", engine: "gtcrn", requestBrowserNs: false, fallback: null }, + ); + assert.deepEqual( + resolveDenoisePlan({ mode: "rnnoise", sampleRate: 48_000, workletSupported: true }), + { mode: "rnnoise", engine: "rnnoise", requestBrowserNs: false, fallback: null }, + ); +}); + +test("model modes fall back to browser denoising without Worklet support", () => { + assert.deepEqual( + resolveDenoisePlan({ mode: "gtcrn", sampleRate: 48_000, workletSupported: false }), + { mode: "gtcrn", engine: "browser", requestBrowserNs: true, fallback: "no-worklet" }, + ); +}); + +test("both neural models require a 48 kHz context", () => { + for (const mode of ["gtcrn", "rnnoise"] as const) { + assert.deepEqual( + resolveDenoisePlan({ mode, sampleRate: 44_100, workletSupported: true }), + { mode, engine: "browser", requestBrowserNs: true, fallback: "sample-rate" }, + ); + } +}); + +test("unknown modes default to GTCRN rather than silently turning denoising off", () => { + assert.equal(resolveDenoisePlan({ mode: "nope" as never, sampleRate: 48_000, workletSupported: true }).engine, "gtcrn"); +}); + +test("stored preferences migrate from mode, then level, then boolean", () => { + assert.equal(migrateStoredNoiseSuppression({ mode: "rnnoise", level: "off" }), "rnnoise"); + assert.equal(migrateStoredNoiseSuppression({ level: "off" }), "off"); + assert.equal(migrateStoredNoiseSuppression({ level: "standard" }), "browser"); + assert.equal(migrateStoredNoiseSuppression({ level: "strong" }), "gtcrn"); + assert.equal(migrateStoredNoiseSuppression({ enabled: false }), "off"); + assert.equal(migrateStoredNoiseSuppression({ enabled: true }), "gtcrn"); + assert.equal(migrateStoredNoiseSuppression({}), "gtcrn"); + assert.equal(migrateStoredNoiseSuppression({ mode: "bogus", level: "bogus" }), "gtcrn"); +}); + +test("legacy level mirrors the new mode", () => { + assert.equal(legacyNoiseSuppressionLevel("off"), "off"); + assert.equal(legacyNoiseSuppressionLevel("browser"), "standard"); + assert.equal(legacyNoiseSuppressionLevel("rnnoise"), "strong"); + assert.equal(legacyNoiseSuppressionLevel("gtcrn"), "strong"); +}); + +test("latency estimates reflect one model frame", () => { + assert.equal(denoiseLatencyMs("gtcrn"), 16); + assert.equal(denoiseLatencyMs("rnnoise"), 10); + assert.equal(denoiseLatencyMs("browser"), 0); + assert.equal(denoiseLatencyMs("off"), 0); +}); diff --git a/web/src/voice/noise-suppression.ts b/web/src/voice/noise-suppression.ts new file mode 100644 index 0000000..3368d4c --- /dev/null +++ b/web/src/voice/noise-suppression.ts @@ -0,0 +1,82 @@ +export type NoiseSuppressionMode = "off" | "browser" | "rnnoise" | "gtcrn"; +export type DenoiseEngine = NoiseSuppressionMode; +export type DenoiseFallback = "no-worklet" | "sample-rate" | "load-failed" | null; +export type StoredNoiseSuppressionLevel = "off" | "standard" | "strong"; + +export interface DenoisePlan { + mode: NoiseSuppressionMode; + engine: DenoiseEngine; + /** Whether getUserMedia should ask the browser to denoise the raw track. */ + requestBrowserNs: boolean; + /** Why the requested model could not run. Visible in audio settings. */ + fallback: DenoiseFallback; +} + +export interface ResolveDenoisePlanOptions { + mode: NoiseSuppressionMode; + sampleRate: number; + workletSupported: boolean; +} + +export interface StoredNoiseSuppression { + mode?: unknown; + level?: unknown; + enabled?: unknown; +} + +/** Both neural engines are trained for 48 kHz contexts; resampling is not free. */ +export const DENOISE_SAMPLE_RATE = 48_000; + +export function isNoiseSuppressionMode(value: unknown): value is NoiseSuppressionMode { + return value === "off" || value === "browser" || value === "rnnoise" || value === "gtcrn"; +} + +export function isNeuralDenoiseEngine(engine: DenoiseEngine): engine is "rnnoise" | "gtcrn" { + return engine === "rnnoise" || engine === "gtcrn"; +} + +/** GTCRN uses 768-sample frames, RNNoise 480; both are one-frame delays. */ +export function denoiseLatencyMs(engine: DenoiseEngine): number { + if (engine === "gtcrn") return 16; + if (engine === "rnnoise") return 10; + return 0; +} + +/** + * Resolve a requested mode into the engine that can actually run. + * Model-based engines are exclusive with the browser noise suppressor: + * stacking the two damages speech before the model sees it. + */ +export function resolveDenoisePlan({ mode, sampleRate, workletSupported }: ResolveDenoisePlanOptions): DenoisePlan { + const requested = isNoiseSuppressionMode(mode) ? mode : "gtcrn"; + if (requested === "off") return { mode: requested, engine: "off", requestBrowserNs: false, fallback: null }; + if (requested === "browser") return { mode: requested, engine: "browser", requestBrowserNs: true, fallback: null }; + if (!workletSupported) { + return { mode: requested, engine: "browser", requestBrowserNs: true, fallback: "no-worklet" }; + } + if (sampleRate !== DENOISE_SAMPLE_RATE) { + return { mode: requested, engine: "browser", requestBrowserNs: true, fallback: "sample-rate" }; + } + return { mode: requested, engine: requested, requestBrowserNs: false, fallback: null }; +} + +/** + * Read a stored preference. New installs have `mode`; older ones only have + * `level` (off/standard/strong) or the boolean `enabled`. A stored "strong" + * migrates to GTCRN because that is the quality tier this build ships. + */ +export function migrateStoredNoiseSuppression(stored: StoredNoiseSuppression): NoiseSuppressionMode { + if (isNoiseSuppressionMode(stored.mode)) return stored.mode; + if (stored.level === "off" || stored.level === "standard" || stored.level === "strong") { + return stored.level === "off" ? "off" : stored.level === "standard" ? "browser" : "gtcrn"; + } + if (typeof stored.enabled === "boolean") return stored.enabled ? "gtcrn" : "off"; + return "gtcrn"; +} + +/** Mirror the new mode into the legacy three-value field for older builds. */ +export function legacyNoiseSuppressionLevel(mode: NoiseSuppressionMode): StoredNoiseSuppressionLevel { + if (mode === "off") return "off"; + if (mode === "browser") return "standard"; + return "strong"; +} diff --git a/web/test/voice-session.test.mjs b/web/test/voice-session.test.mjs index 2852b0b..c8d1f50 100644 --- a/web/test/voice-session.test.mjs +++ b/web/test/voice-session.test.mjs @@ -64,10 +64,20 @@ class RecorderStub { state = "inactive"; mimeType = "audio/webm"; stops = 0; + finished = false; constructor(stream) { this.stream = stream; RecorderStub.instances.push(this); } start() { if (RecorderStub.failStart) throw new Error("Recorder start failed"); this.state = "recording"; } stop() { this.stops++; this.state = "inactive"; } - finish() { this.state = "inactive"; this.ondataavailable?.({ data: new Blob(["audio"]) }); this.onstop?.(); } + finish() { + // A/B tests start two recorders; finishing simulates both stopping together. + for (const recorder of RecorderStub.instances) { + if (recorder.finished) continue; + recorder.finished = true; + recorder.state = "inactive"; + recorder.ondataavailable?.({ data: new Blob(["audio"]) }); + recorder.onstop?.(); + } + } } function decodedChunk() { return { sampleRate: 48000, numberOfChannels: 1, numberOfFrames: 960, closed: 0, copyTo() {}, close() { this.closed++; } }; @@ -2331,7 +2341,7 @@ test("a replacement microphone test stops the old recorder and ignores its late const currentUrl = voice.testAudioUrl.value; old.finish(); assert.equal(voice.testAudioUrl.value, currentUrl); - assert.equal(created.length, 1); + assert.equal(created.length, 2, "denoised and dry takes each produce one URL"); }); test("an old microphone test permission failure cannot stop a new recording", async () => { @@ -2371,9 +2381,11 @@ test("a naturally finished microphone recording clears active state and standalo assert.equal(voice.microphoneTestActive.value, false); assert.equal(recorder.stream.track.readyState, "ended"); assert.equal(voice.testAudioUrl.value, "blob:finished"); + assert.equal(voice.testAudioDryUrl.value, "blob:finished"); voice.disconnect(); - assert.deepEqual(revoked, ["blob:finished"]); + assert.deepEqual(revoked, ["blob:finished", "blob:finished"]); assert.equal(voice.testAudioUrl.value, ""); + assert.equal(voice.testAudioDryUrl.value, ""); }); test("recorder startup failure releases standalone microphone capture", async () => { @@ -2580,10 +2592,38 @@ test("a failed noise suppression change restores its setting and preserves WebRT await voice.setNoiseSuppressionEnabled(false); assert.notEqual(peer.connectionState, "closed"); assert.equal(voice.noiseSuppressionEnabled.value, true); + assert.equal(voice.noiseSuppressionMode.value, "gtcrn", "a failed change restores the committed engine"); assert.equal(initial.track.readyState, "live"); assert.notEqual(voice.state.microphoneErrorCode, ""); }); +test("the default denoise mode reports a browser fallback when AudioWorklet is unavailable", async () => { + const getUserMedia = navigator.mediaDevices.getUserMedia; + let lastConstraints; + navigator.mediaDevices.getUserMedia = async constraints => { lastConstraints = constraints; return getUserMedia(constraints); }; + await connectWebRtc(); + assert.equal(voice.noiseSuppressionMode.value, "gtcrn"); + assert.equal(voice.microphoneProcessing.requestedEngine, "gtcrn"); + assert.equal(voice.microphoneProcessing.engine, "browser"); + assert.equal(voice.microphoneProcessing.fallback, "no-worklet"); + assert.equal(lastConstraints.audio.noiseSuppression, true, "the fallback must still ask for browser denoising"); +}); + +test("browser and off modes request the matching native constraint without a model", async () => { + const getUserMedia = navigator.mediaDevices.getUserMedia; + let lastConstraints; + navigator.mediaDevices.getUserMedia = async constraints => { lastConstraints = constraints; return getUserMedia(constraints); }; + await connectWebRtc(); + await voice.setNoiseSuppressionMode("browser"); + assert.equal(lastConstraints.audio.noiseSuppression, true); + assert.equal(voice.microphoneProcessing.engine, "browser"); + assert.equal(voice.microphoneProcessing.fallback, null); + await voice.setNoiseSuppressionMode("off"); + assert.equal(lastConstraints.audio.noiseSuppression, false); + assert.equal(voice.microphoneProcessing.engine, "off"); + assert.equal(voice.noiseSuppressionEnabled.value, false); +}); + test("changing processing during an input switch commits the device actually acquired", async () => { navigator.mediaDevices.enumerateDevices = async () => availableDevices; await voice.ensureMicrophone();