From 49481145eff904ad8c083b8378494546826a03e1 Mon Sep 17 00:00:00 2001 From: illusia <64828020+EchoSixHIYA@users.noreply.github.com> Date: Thu, 1 Oct 2026 12:49:44 +0800 Subject: [PATCH] fix: prepare microphone graphs before replacing live capture --- CLAUDE.md | 3 + docs/CODE_REFACTOR_PLAN.zh-CN.md | 42 +-- web/src/composables/useVoiceWebSocket.ts | 348 ++++++++--------------- web/src/composables/useWebClientI18n.ts | 6 + web/src/voice/microphone-capture.ts | 166 +++++++++++ web/test/voice-session.test.mjs | 175 ++++++++++++ 6 files changed, 488 insertions(+), 252 deletions(-) create mode 100644 web/src/voice/microphone-capture.ts diff --git a/CLAUDE.md b/CLAUDE.md index bb258fa..4c7fafc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,6 +22,7 @@ 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/audio-sink.ts` | Serialized device routing per audio endpoint, with stale-operation guards | | `web/src/platform/` | Browser mounting and cancellable Android gateway readiness handshake | | `web/src/services/`, `web/src/i18n/`, `web/src/skins/` | Browser persistence, identity import, skin packages and translations | @@ -61,6 +62,8 @@ Microphone recording tests own their recorder, timeout and object URL, while the 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. +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. `src/server/opus-codec.ts` loads the native `@discordjs/opus` implementation for server deployments and `opusscript` for the Android bundle. Dispose codec and media resources at the end of their owning session. diff --git a/docs/CODE_REFACTOR_PLAN.zh-CN.md b/docs/CODE_REFACTOR_PLAN.zh-CN.md index bfd19f4..b7fc9a9 100644 --- a/docs/CODE_REFACTOR_PLAN.zh-CN.md +++ b/docs/CODE_REFACTOR_PLAN.zh-CN.md @@ -1,17 +1,17 @@ # WebSpeak 代码待修改清单与修改方向 -本文记录 `webspeak-webclient` 的代码边界、待修改事项、优先级、修改方向及验收标准。本轮按持续目标继续施工,已收尾管理页五语文案与窄屏工具栏;后续媒体、页面及平台任务保持在清单中。已实施内容与历史验证单独记录,不将建议或待验收事项写成已确认故障。 +本文记录 `webspeak-webclient` 的代码边界、待修改事项、优先级、修改方向及验收标准。本轮按持续目标继续施工,已收尾管理页五语文案与窄屏工具栏,并提取麦克风采集处理链、修复节点准备和热插拔回退;后续媒体、页面及平台任务保持在清单中。已实施内容与历史验证单独记录,不将建议或待验收事项写成已确认故障。 当前构建与 CI 入口已经统一,共享协议、屏幕共享、远端播放、录音测试、四个服务端桥接子模块和 Android 启动已有实现。管理页请求与状态修复已提交;五语文案、格式化提取及窄屏工具栏已通过本地验证。接下来按资源生命周期整理媒体模块和页面组件;真实 TeamSpeak、Android 真机及发布包验证单独安排。 ## 范围与基线 - 记录日期:2026 年 10 月 1 日。 -- 当前提交基线:`dev` 分支,提交 `11d2fa5c3a06f313b59f9bf54d90c688c2c8e860`,应用版本 `0.2.5-preview`。 +- 当前提交基线:`dev` 分支,提交 `55343c99cd303126b428cc19a9d9774c3503a975`,应用版本 `0.2.5-preview`。 - 分析对象:当前工作区,包含已有未提交改动,不等同于该提交的干净检出。 - `ad83c87` 包含远端播放及录音控制器,`407311d` 包含设备切换与采集连续性调整,`11d2fa5` 包含管理页请求与状态生命周期修复。 -- 本批接续已有五语文案与格式化改动,增加管理页工具栏布局修正;具体实施与验证见文末记录。 -- 已有实施记录显示 189 项测试、后端编译、前端类型检查与生产构建通过,并进行过隔离数据的管理页浏览器检查;`11d2fa5` 的 [CI 与 Docker 检查](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36813991856) 已记录成功。该远端结果不覆盖后续多语言改动;本批重新通过 19 项管理页面测试和前端类型检查、构建,并完成五语浏览器复验。 +- `55343c9` 已提交管理页五语与工具栏整理,其 [CI 与 Docker 检查](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36815965369) 成功。本批后续采集链及热插拔改动的验证范围见下一项。 +- 当前工作区 `npm run verify` 通过 199 项测试、后端编译、前端类型检查与生产构建,包含 10 项新增采集与设备回归用例。前述 CI 仅对应 `55343c9`,不覆盖后续媒体改动;对应提交需独立核对。 - 验证结果只适用于对应提交或工作区快照;模拟边界的生命周期测试、编解码冒烟和应用构建均不能代替真实 TeamSpeak 双向语音及真机验收。 下文按当前工作区更新现状,区分已完成、已有未提交实现、待验证和待实施。优先级表示建议实施顺序,不代表已确认的故障或安全漏洞等级。 @@ -43,7 +43,7 @@ | TeamSpeak 接入 | `src/server/ts-client.ts`、`teamspeak-adapter.ts`、`directory-sync.ts` | SDK 适配、连接、目录同步、聊天及语音收发 | | 管理与持久化 | `src/admin/`、`src/persistence/`、`src/security/` | 认证、配置、邀请、中继节点、审计和 SQLite 存储 | | 网页交互 | `web/src/views/`、`web/src/composables/` | 页面、连接、频道、成员、聊天、音频和屏幕共享交互 | -| 浏览器媒体控制 | `web/src/voice/` | 屏幕共享、远端播放、录音测试及输出设备切换,各自管理所属资源与迟到回调 | +| 浏览器媒体控制 | `web/src/voice/` | 屏幕共享、远端播放、麦克风采集处理链、录音测试及输出设备切换,各自管理所属资源与迟到回调 | | 前端平台启动 | `web/src/platform/` | 浏览器直接挂载、原生容器等待本机网关;已纳入当前提交 | | 前端基础服务 | `web/src/services/`、`web/src/i18n/`、`web/src/skins/` | 身份导入、浏览器存储、皮肤和国际化 | | 独立加速中继 | `src/relay.ts`、`src/server/acceleration-relay.ts` | 中继进程及网关侧中继接入 | @@ -58,9 +58,9 @@ | 01 | P1 | 统一构建命令与 CI 验证入口 | 工程基线 | 已完成,提交 `5c11bd9` 的 CI 已通过 | | 02 | P1 | 补齐会话与媒体关键行为测试 | 测试缺口 | 基础测试已补,媒体及完整连接验证待补 | | 03 | P2 | 集中前后端协议契约 | 重构建议 | WebSocket、WebRTC 和管理请求模型已集中,契约及管理 HTTP 集成测试通过;真实媒体联调待完成 | -| 04 | P2 | 拆分前端语音核心模块 | 生命周期修复及重构建议 | 播放、录音和设备切换回归通过;采集、WebRTC 及连接职责仍待提取与集成验收 | +| 04 | P2 | 拆分前端语音核心模块 | 生命周期修复及重构建议 | 播放、录音、采集处理链及设备切换已有回归;伴奏、WebRTC 及连接职责仍待整理与集成验收 | | 05 | P2 | 拆分服务端实时桥接模块 | 重构建议及行为修复 | 已拆出命令、目录展示、统计和共享协调;音频转发及集成验证待继续 | -| 06 | P2 | 收尾管理页多语言并拆分页面组件 | 展示问题与重构建议 | 请求与状态修复已提交;文案提取和窄屏工具栏本地验证通过,组件边界继续整理 | +| 06 | P2 | 收尾管理页多语言并拆分页面组件 | 展示问题与重构建议 | 请求与状态修复已提交;文案提取与窄屏工具栏已提交,CI 通过;组件边界继续整理 | | 07 | P2 | 明确 Android 平台边界与验证范围 | 预览功能的整理与验证 | 启动测试、三架构 APK 构建及模拟器启动通过;真实连接与设备音频待验收 | | 08 | P1 | 修正文档与实现不一致的说明 | 文档维护 | 本轮更新基线、现状与剩余事项;保留历史验证记录并明确适用范围 | | 09 | P3 | 整理源码与本地产物边界 | 仓库维护建议 | 忽略规则、说明及代表性源码检查完成;干净构建验证待完成 | @@ -77,10 +77,10 @@ P1 为优先修正的衔接问题和验证基线,P2 为职责整理及待核 | 06-A2 | 已修复,本地验证通过 | 旧列表、目录或探测结果可能覆盖新状态;保存也可能回填过期探测时间 | 各功能只采用当前请求结果;目标编辑使探测失效;保存仅合并未过期的探测信息 | 倒序刷新、探测中改地址、改密码及保存期间完成新探测等用例通过 | | 06-A3 | 已修复,本地验证通过 | 登录迟到后跳转、旧会话错误、备份迟到及错误提示残留 | 页面销毁、认证变化与子页切换清理所属请求;退出失败保留当前草稿,成功后清理私有状态 | 页面及 API 用例通过;浏览器复验跨功能页错误清理 | | 02-A | 已完成,本地验证通过 | 新增页面测试原先未进入统一命令 | 已加入根目录显式测试列表,现在包含 28 个测试文件 | 本批统一验证执行 189 项测试,全部通过 | -| 06-B | 本地完成,待对应提交 CI | `useAdminI18n.ts` 集中格式化与错误映射,五语各 267 个显式文案键 | 已补齐字典、缺项类型约束和页面接入;保留两类密码错误的不同含义 | 占位符、五语状态与时长、实际中继错误提示检查通过,19 项页面测试与前端构建通过 | -| 06-D | 已修复,本地验证通过 | 管理页主题长文案曾挤压状态标记 | 状态与控件分组,窄屏主题按钮显示图标并保留可访问名称,状态标签仍可被辅助技术读取 | 五语 × 320、393、740、1440 像素共 20 组边界检查通过;明暗主题与键盘操作复验通过 | +| 06-B | 已完成,CI 通过 | `useAdminI18n.ts` 集中格式化与错误映射,五语各 267 个显式文案键 | 已补齐字典、缺项类型约束和页面接入;保留两类密码错误的不同含义 | 占位符、五语状态与时长、实际中继错误提示检查通过,19 项页面测试与前端构建通过 | +| 06-D | 已修复,CI 通过 | 管理页主题长文案曾挤压状态标记 | 状态与控件分组,窄屏主题按钮显示图标并保留可访问名称,状态标签仍可被辅助技术读取 | 五语 × 320、393、740、1440 像素共 20 组边界检查通过;明暗主题与键盘操作复验通过 | | 06-C | P2,组件及默认文案边界 | `WebClient.vue` 约 1,211 行,工作区 `AdminView.vue` 约 400 行;管理页已复用 `src/site-copy.ts` 的默认欢迎语 | 功能状态已接入,继续按稳定界面拆组件;保留统一默认文案和已整理的中继表单边界 | 保持路由、主题、皮肤钩子和交互;移除字段前确认所有引用及兼容需求 | -| 04-D | P2,采集及传输职责仍集中 | `useVoiceWebSocket.ts` 约 2,253 行,仍拥有采集节点、设备、伴奏、WebRTC 及命令传输 | 先为处理节点创建失败和设备热插拔补行为基线,再依次提取采集、WebRTC 与连接控制 | 拆分前后连接及清理语义一致;新采集失败时的回滚行为明确,资源不泄漏 | +| 04-D | 采集处理链已提取,本地验证通过 | `microphone-capture.ts` 独立管理节点、worklet 加载、准备取消及激活;语音入口约 2,129 行 | 已修复节点失败打断旧采集和热插拔回退;继续分离伴奏、WebRTC 与连接编排 | 10 项新增回归覆盖失败、等待、取消、迟到消息及设备回退;真实媒体链路仍待验收 | | 05-A | P2,服务端音频与事件编排待拆 | `voice-bridge.ts` 约 1,081 行,音频路径与 SDK 事件仍在桥接入口 | 提取音频收发及事件协调,保留现有缓冲上限、调度节拍与统一会话清理 | 验证慢客户端、突发帧、重连及频道隔离,不随结构整理调整音质参数 | | 07-A | P2,移动运行时及真实媒体待验收 | 移动说明记录内嵌 Node.js 18.20.4,而 SDK 声明要求至少 20.19;历史模拟器检查只覆盖启动及首页 | 先验证真实 SDK 连接,再决定升级运行时或适配;双向语音、设备切换及 APK 布局单独验收 | 记录具体设备、环境及结果;后台音频、原生屏幕共享继续作为独立能力规划 | | 09-A | P3,干净输入打包待验收 | 已有忽略规则及本地产物说明;跨平台发布包的干净构建仍缺完整记录 | 验证 Windows、Linux、Docker 与 Android 所需输入,不依赖本机历史产物 | 各目标可从声明的源码及依赖复现构建;不删除未知用途文件 | @@ -91,8 +91,8 @@ P1 为优先修正的衔接问题和验证基线,P2 为职责整理及待核 | 顺序 | 待办与依据 | 大致修改方向 | 完成条件 | | --- | --- | --- | --- | -| 1 | 管理页文案与工具栏已本地完成,页面模板仍集中 | 完成对应提交 CI 后开展 06-C,复用现有功能模块 | 保持表单、认证和请求语义,皮肤及响应式布局验证通过 | -| 2 | 播放、录音和设备切换已有行为基线;语音核心仍集中采集和传输 | 依次提取麦克风与伴奏、WebRTC、连接传输;继续验证处理节点创建失败和设备热插拔 | 保持对外接口稳定,断开释放资源,迟到结果不影响新会话 | +| 1 | 管理页文案与工具栏已提交且 CI 通过,页面模板仍集中 | 开展 06-C,复用现有功能模块 | 保持表单、认证和请求语义,皮肤及响应式布局验证通过 | +| 2 | 播放、录音、采集处理链及设备回退已有行为基线 | 接着分离伴奏、WebRTC 和连接传输,保留现有采集模块 | 保持对外接口稳定,断开释放资源,迟到结果不影响新会话 | | 3 | 服务端桥接仍集中音频转发和 SDK 事件编排 | 提取音频收发和目录事件协调,沿用现有会话状态与清理入口 | 背压、队列上限、重连、目录同步及共享隔离行为保持一致 | | 4 | 网页客户端及管理页仍有较多模板和内联文案 | 按加入表单、频道树、聊天区、音频设置、服务器设置及皮肤等界面拆分,复用已有 composable,补齐五语文案 | 皮肤钩子、语言切换、明暗主题及各尺寸交互保持一致 | | 5 | 真实媒体、Android 运行时及跨平台产物尚有验证缺口 | 单独安排 TeamSpeak 双向语音、WebRTC 回退、真机设备切换,以及干净环境打包 | 每项记录环境、步骤和实际结果;失败项再转为具体修复任务 | @@ -141,7 +141,7 @@ P1 为优先修正的衔接问题和验证基线,P2 为职责整理及待核 ### 04 拆分前端语音核心模块 -**现状与位置:** [useVoiceWebSocket.ts](../web/src/composables/useVoiceWebSocket.ts) 当前约 2,253 行;`9bfe4b9` 时约 2,335 行。屏幕共享位于 [screen-share.ts](../web/src/voice/screen-share.ts),兼容路径远端播放迁至 [remote-playback.ts](../web/src/voice/remote-playback.ts),录音测试迁至 [microphone-test.ts](../web/src/voice/microphone-test.ts),输出设备串行设置位于 [audio-sink.ts](../web/src/voice/audio-sink.ts)。连接、凭证请求、麦克风采集、降噪、设备状态、WebRTC 语音、伴奏和统计仍在核心模块中。 +**现状与位置:** [useVoiceWebSocket.ts](../web/src/composables/useVoiceWebSocket.ts) 当前约 2,129 行;`9bfe4b9` 时约 2,335 行。屏幕共享位于 [screen-share.ts](../web/src/voice/screen-share.ts),兼容路径远端播放迁至 [remote-playback.ts](../web/src/voice/remote-playback.ts),录音测试迁至 [microphone-test.ts](../web/src/voice/microphone-test.ts),输出设备串行设置位于 [audio-sink.ts](../web/src/voice/audio-sink.ts)。连接、凭证请求、麦克风采集、降噪、设备状态、WebRTC 语音、伴奏和统计仍在核心模块中。 **修改方向:** 暂时保留现有 composable 作为页面调用入口,逐项提取连接与命令传输、麦克风处理、远端播放、WebRTC 语音及统计模块,复用已经拆出的屏幕共享控制器。先明确各模块拥有的状态和资源,再移动实现,避免所有模块相互读取同一个大型可变对象。每次只迁移一项职责,并明确初始化、停止和销毁的责任。 @@ -156,9 +156,9 @@ P1 为优先修正的衔接问题和验证基线,P2 为职责整理及待核 | WebRTC 语音 | PeerConnection、协商状态、混音及播放资源 | 建立语音通道、失败回退、释放通道 | | 屏幕共享 | 采集音轨、参与者连接、ICE 配置、共享状态 | 开始、观看、信令处理和退出 | -**已修复的细节:** 旧 WebSocket 消息现在同时校验连接代次、当前 socket 和打开状态;主动断开、异常关闭及服务端断连事件共用资源释放路径。屏幕共享 ICE 配置已改为实例所有,异步协商和统计结果在所属连接失效后不再写回。麦克风授权迟到时释放音轨并取消旧操作,新连接可以独立申请采集。相关问题已通过先失败后通过的回归测试验证;其他音频资源仍需继续检查。 +**已修复的细节:** 旧 WebSocket 消息现在同时校验连接代次、当前 socket 和打开状态;主动断开、异常关闭及服务端断连事件共用资源释放路径。屏幕共享 ICE 配置已改为实例所有,异步协商和统计结果在所属连接失效后不再写回。麦克风授权迟到时释放音轨并取消旧操作,新连接可以独立申请采集。相关问题已通过先失败后通过的回归测试验证。新增 `microphone-capture.ts` 将准备中的节点与运行中的采集隔离:准备失败保留旧流,取消立即释放候选资源,只有成功激活的处理链可发送 PCM;设备移除通过正常事务回退并重新协商 WebRTC。其他媒体编排仍需继续整理。 -**建议切入顺序:** 远端播放、录音和设备切换已有行为基线,接下来提取麦克风及伴奏、WebRTC 语音,最后收拢连接与命令。每个控制器显式拥有其音轨、节点、计时器和取消标识;现有 `releaseSessionResources` 保持统一清理入口。录音控制器只拥有录音测试资源,麦克风流仍由采集入口管理,避免停止试听时结束房间内采集。 +**建议切入顺序:** 远端播放、录音、采集处理链和设备切换已有行为基线,接下来提取伴奏、WebRTC 语音,最后收拢连接与命令。每个控制器显式拥有其音轨、节点、计时器和取消标识;现有 `releaseSessionResources` 保持统一清理入口。录音控制器只拥有录音测试资源,麦克风流仍由采集入口管理,避免停止试听时结束房间内采集。 **验收标准:** 页面调用接口保持兼容,或有范围明确的迁移;连接、断开、重连、设备切换及 WebRTC 回退行为保持一致;音轨、解码器、定时器和事件监听具有明确清理路径,重复连接不会累计资源。 @@ -240,7 +240,8 @@ P1 为优先修正的衔接问题和验证基线,P2 为职责整理及待核 | 已完成的播放与录音 | 04-A、04-B 的远端播放提取,以及 04-C 的录音测试控制器 | `ad83c87` 的 149 项测试及前后端构建、远端 CI、Docker 健康检查通过 | | 已提交的设备修复 | `407311d` 的设备、降噪交错操作及采集连续性 | 既有记录为本地 164 项测试及前后端构建通过;本批已确认该提交 CI 与 Docker 健康检查成功 | | 已提交的管理页修复 | `11d2fa5` 的 06-A 请求与状态接入、02-A 测试入口 | 已有 189 项测试、前后端构建、隔离数据浏览器复验及远端 CI 成功记录 | -| 本批管理页收尾 | 06-B 五语文案与格式化、06-D 窄屏工具栏 | 本地前端构建、19 项页面测试、五语提示与 20 组布局检查通过;提交后继续核对 CI | +| 已提交的管理页收尾 | `55343c9` 的 06-B 五语文案与格式化、06-D 窄屏工具栏 | 本地及 CI 通过,五语提示与 20 组布局检查通过 | +| 本批采集链修复 | 04-D 处理链提取、节点准备及热插拔回退 | 199 项测试、前后端构建通过,10 项新增用例覆盖资源生命周期及实际状态变化 | | 随后 | 为 04、05 的剩余媒体职责补行为用例,再分项拆分 | 每次迁移都能验证连接和媒体行为,并独立回退 | | 页面整理 | 06-C 的剩余组件 | 页面行为、错误反馈、皮肤接口及布局验证通过 | | 独立工作项 | 真实 TeamSpeak 联调、07 的运行时与设备验收、09 的各平台干净打包 | 记录具体环境、实际结果和未支持能力,不混入结构拆分 | @@ -367,3 +368,12 @@ P1 为优先修正的衔接问题和验证基线,P2 为职责整理及待核 - 当前代码通过 19 项实际 SFC 页面测试和前端类型检查、生产构建;此前同批文案快照通过完整 189 项测试和前后端构建。 - 本机隔离数据浏览器检查覆盖五语状态、时长、审计与中继失败提示;五语及 320、393、740、1440 像素共 20 组工具栏边界检查全部通过,键盘主题切换和明暗布局正常,控制台未见警告或错误。临时页面、视口覆盖和预览进程已清理。 - 本批没有验证真实 TeamSpeak 媒体或 Android 真机;后续继续采集失败回滚、设备热插拔、媒体模块提取及页面组件拆分。 + +### 采集处理链与设备热插拔实施记录 + +- 新增 `web/src/voice/microphone-capture.ts`,集中管理原始音轨、处理节点、RNNoise、worklet 加载、PCM 激活和释放;处理设置类型由原入口继续导出,保持调用兼容。 +- 新处理链完全就绪后才替换旧流;节点创建失败、worklet 等待及取消不影响仍在运行的旧链。中断准备立即释放候选音轨与节点,迟到回调不能向新连接发送音频。首次创建失败现在产生麦克风错误提示。 +- 设备热插拔复用输入与输出切换事务,默认输入替换后重新协商 WebRTC;失败保留最后成功设置,输出失败提供五语提示。新的失败切换以实际已运行的处理链作为回滚基线。 +- 新增 10 项回归测试,其中 7 项先复现既有问题;另外覆盖 worklet 正常发送、准备中断的资源清理,以及迁移后初始设备查询期间断开的取消语义。 +- `npm run verify` 通过 199 项测试、后端编译、前端类型检查与生产构建。媒体设备、worklet 和 WebRTC 使用边界替身,不能据此认定真实音质、物理热插拔或 TeamSpeak 双向语音已验收。 +- 伴奏与 WebRTC 控制、服务端音频、剩余页面组件、Android 真机及干净发布包验证尚未完成。 diff --git a/web/src/composables/useVoiceWebSocket.ts b/web/src/composables/useVoiceWebSocket.ts index 08958be..1dd82eb 100644 --- a/web/src/composables/useVoiceWebSocket.ts +++ b/web/src/composables/useVoiceWebSocket.ts @@ -1,5 +1,7 @@ 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 { createAudioSinkRouter } from "../voice/audio-sink.js"; import { createScreenShareController } from "../voice/screen-share.js"; export type { ScreenShareOutputSettings, ScreenShareCaptureStats, ScreenSharePeerStats, ScreenShareWebRtcStats } from "../voice/screen-share.js"; @@ -10,14 +12,8 @@ export type { ScreenShareStreamDescription as ScreenShareStream, ScreenShareView import type { ChannelMember, ChannelInfo, ChatMessage, ServerEvent, VoiceAudioBridgeStats } from "../../../src/shared/voice-models.js"; export type { ChannelMember, ChannelInfo, ChatMessage, ServerEvent, VoiceAudioBridgeStats } from "../../../src/shared/voice-models.js"; import { reactive, ref, shallowRef } from "vue"; -import { RnnoiseWorkletNode, loadRnnoise } from "@sapphi-red/web-noise-suppressor"; -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 { loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js"; -const micCaptureWorkletUrl = "/mic-capture-worklet.js"; - export interface VoiceState { connected: boolean; connecting: boolean; @@ -53,13 +49,6 @@ export interface AudioOutputDevice { export type AudioPermission = "unknown" | "granted" | "denied"; -export interface MicrophoneProcessingSettings { - echoCancellation: boolean | null; - noiseSuppression: boolean | null; - autoGainControl: boolean | null; - rnnoise: boolean | null; -} - type SinkAudioContext = AudioContext & { setSinkId?: (sinkId: string) => Promise; }; @@ -265,18 +254,9 @@ export function useVoiceWebSocket() { // for deployments where the gateway's built-in UDP media range is unavailable. let audioCtx: SinkAudioContext | null = null; let micStream: MediaStream | null = null; - let scriptNode: ScriptProcessorNode | null = null; - let captureGraphGeneration = 0; - let workletNode: AudioWorkletNode | null = null; - let workletContext: AudioContext | null = null; - let workletModulePromise: Promise | null = null; - let rnnoiseNode: RnnoiseWorkletNode | null = null; - let rnnoiseWorkletModulePromise: Promise | null = null; - let rnnoiseWasmPromise: Promise | null = null; - let micSource: MediaStreamAudioSourceNode | null = null; - let micGain: GainNode | null = null; - let silentGain: GainNode | null = null; - let processedMicDestination: MediaStreamAudioDestinationNode | null = null; + const microphoneCaptureFactory = createMicrophoneCaptureFactory(); + let microphoneCapture: MicrophoneCapture | null = null; + let pendingMicrophoneCapture: AbortController | null = null; const accompanimentActive = ref(false); const accompanimentSupported = ref(typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getDisplayMedia)); const accompanimentErrorCode = ref<"" | "unsupported" | "needsWebRtc" | "noAudio" | "permission">(""); @@ -619,210 +599,119 @@ export function useVoiceWebSocket() { .map((device) => ({ deviceId: device.deviceId, label: device.label, groupId: device.groupId })); inputDevices.splice(0, inputDevices.length, ...microphones); outputDevices.splice(0, outputDevices.length, ...speakers); - if (selectedInputDeviceId.value && !microphones.some((device) => device.deviceId === selectedInputDeviceId.value)) { - inputDeviceTouched = true; - selectedInputDeviceId.value = ""; - committedInputDeviceId = ""; - localStorage.setItem("webspeak:input-device", selectedInputDeviceId.value); - void saveAudioPreferences(); - if (micStream) void startMicrophone().catch(() => undefined); - } - if (selectedOutputDeviceId.value && !speakers.some((device) => device.deviceId === selectedOutputDeviceId.value)) { - outputDeviceTouched = true; - selectedOutputDeviceId.value = ""; - committedOutputDeviceId = ""; - localStorage.setItem("webspeak:output-device", ""); - void saveAudioPreferences(); - if (audioCtx && outputDeviceSupported.value) void setAudioSink(audioCtx, "").catch(() => undefined); - } + const missingInput = selectedInputDeviceId.value && !microphones.some(device => device.deviceId === selectedInputDeviceId.value); + const missingOutput = selectedOutputDeviceId.value && !speakers.some(device => device.deviceId === selectedOutputDeviceId.value); + // Use the normal configuration transactions: a replacement input must also + // restart WebRTC, and rejected fallbacks must not be saved as successful. + const fallbackOperations: Promise[] = []; + if (missingInput) fallbackOperations.push(setInputDevice("")); + if (missingOutput) fallbackOperations.push(setOutputDevice("")); + await Promise.allSettled(fallbackOperations); } async function refreshInputDevices(): Promise { await refreshAudioDevices(); } - async function createRnnoiseNode(ctx: AudioContext, generation: number): Promise { - if (typeof AudioWorkletNode === "undefined" || !ctx.audioWorklet) { - microphoneProcessing.rnnoise = false; - return null; - } - try { - if (!rnnoiseWasmPromise) { - rnnoiseWasmPromise = loadRnnoise({ url: rnnoiseWasmUrl, simdUrl: rnnoiseSimdWasmUrl }).catch((error) => { - rnnoiseWasmPromise = null; - throw error; - }); + function handleCaptureChunk(input: Float32Array, rms?: number): void { + if (!input.length) return; + micLevel.value = Math.min(1, (rms ?? Math.sqrt(input.reduce((sum, sample) => sum + sample * sample, 0) / input.length)) * 6); + const socket = ws.value; + const shouldSend = !microphoneMuted.value + && !microphoneTestActive.value + && !webrtcActive.value + && socket?.readyState === WebSocket.OPEN + && voxGate(input); + if (!shouldSend) { + accumLen = 0; + if (microphoneMuted.value) { + voxAttack = 0; + voxRelease = 0; } - if (!rnnoiseWorkletModulePromise) { - rnnoiseWorkletModulePromise = ctx.audioWorklet.addModule(rnnoiseWorkletUrl).catch((error) => { - rnnoiseWorkletModulePromise = null; - throw error; - }); - } - const [wasmBinary] = await Promise.all([rnnoiseWasmPromise, rnnoiseWorkletModulePromise]); - if (generation !== microphoneGeneration) return null; - const node = new RnnoiseWorkletNode(ctx, { maxChannels: 1, wasmBinary }); - microphoneProcessing.rnnoise = true; - return node; - } catch { - // Native browser NS remains active as a fallback. RNNoise is an optional - // enhancement and must never prevent a microphone from starting. - if (generation === microphoneGeneration) microphoneProcessing.rnnoise = false; - return null; + return; } + if (!socket) { + accumLen = 0; + return; + } + const bufferedBytes = socket.bufferedAmount; + if (bufferedBytes > MAX_AUDIO_BUFFERED_BYTES) { + accumLen = 0; + return; + } + + if (convBuf.length < input.length) convBuf = new Int16Array(input.length); + for (let i = 0; i < input.length; i++) { + const sample = Math.max(-1, Math.min(1, input[i]!)); + convBuf[i] = sample < 0 ? sample * 0x8000 : sample * 0x7fff; + } + + const need = accumLen + input.length; + if (accumBuf.length < need) accumBuf = new Int16Array(Math.max(need, accumBuf.length * 2)); + accumBuf.set(convBuf.subarray(0, input.length), accumLen); + 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; + } + if (offset > 0) markSpeaking(state.tsClientId); + accumLen -= offset; + if (offset > 0) accumBuf.set(accumBuf.subarray(offset, offset + accumLen), 0); } async function startMicrophone(): Promise { const generation = ++microphoneGeneration; + pendingMicrophoneCapture?.abort(); + const controller = new AbortController(); + pendingMicrophoneCapture = controller; const ctx = getAudioCtx(); const assertCurrent = (): void => { - if (generation !== microphoneGeneration || audioCtx !== ctx) throw new CancelledMediaOperation(); + if (generation !== microphoneGeneration || audioCtx !== ctx || controller.signal.aborted) throw new CancelledMediaOperation(); }; - if (ctx.state === "suspended") { - try { await ctx.resume(); } catch { /* the audio context notice explains the silence */ } - } - assertCurrent(); - // Acquire the replacement stream before tearing down the current graph so - // changing devices does not interrupt an active microphone on failure. - let nextStream: MediaStream; + let nextStream: MediaStream | null = null; + let nextCapture: MicrophoneCapture | null = null; + let factoryOwnsStream = false; try { - nextStream = await navigator.mediaDevices.getUserMedia({ audio: microphoneConstraints() }); - } catch (error) { + if (ctx.state === "suspended") { + try { await ctx.resume(); } catch { /* the audio context notice explains the silence */ } + } assertCurrent(); - if (error instanceof DOMException && ["NotAllowedError", "SecurityError"].includes(error.name)) audioPermission.value = "denied"; - // Never let the raw DOMException (usually an English message) reach the UI: - // record a readable failure first, then let the caller decide how to show it. - setMicrophoneError(error); - throw error; - } - try { + nextStream = await navigator.mediaDevices.getUserMedia({ audio: microphoneConstraints() }); assertCurrent(); audioPermission.value = "granted"; - clearMicrophoneError(); - const microphoneTrack = nextStream.getAudioTracks()[0]; - const settings = microphoneTrack?.getSettings(); - microphoneProcessing.echoCancellation = typeof settings?.echoCancellation === "boolean" ? settings.echoCancellation : null; - microphoneProcessing.noiseSuppression = typeof settings?.noiseSuppression === "boolean" ? settings.noiseSuppression : null; - microphoneProcessing.autoGainControl = typeof settings?.autoGainControl === "boolean" ? settings.autoGainControl : null; + factoryOwnsStream = true; + nextCapture = await microphoneCaptureFactory.prepare({ + context: ctx, stream: nextStream, signal: controller.signal, assertCurrent, + noiseSuppression: noiseSuppressionEnabled.value, volume: inputVolume.value, onSamples: handleCaptureChunk, + }); + assertCurrent(); + // Commit only a complete graph. Permission and node failures leave the + // previous stream, PCM route and WebRTC peer untouched. stopMicrophone(false); micStream = nextStream; - - micSource = ctx.createMediaStreamSource(micStream); - const nextRnnoiseNode = noiseSuppressionEnabled.value ? await createRnnoiseNode(ctx, generation) : null; - if (generation !== microphoneGeneration || audioCtx !== ctx) { - nextRnnoiseNode?.destroy(); - nextRnnoiseNode?.disconnect(); - throw new CancelledMediaOperation(); - } - rnnoiseNode = nextRnnoiseNode; - if (!noiseSuppressionEnabled.value) microphoneProcessing.rnnoise = false; - const processedSource: AudioNode = rnnoiseNode ?? micSource; - if (rnnoiseNode) micSource.connect(rnnoiseNode); - processedMicDestination = ctx.createMediaStreamDestination(); - processedMicDestination.channelCount = 1; - processedMicDestination.channelCountMode = "explicit"; - processedSource.connect(processedMicDestination); - micGain = ctx.createGain(); - micGain.gain.value = inputVolume.value; - silentGain = ctx.createGain(); - silentGain.gain.value = 0; - - const captureGeneration = captureGraphGeneration; - const handleCaptureChunk = (input: Float32Array, rms?: number): void => { - // A replacement permission request does not invalidate the live graph. - // Only replacing or stopping that graph may silence its callbacks. - if (captureGeneration !== captureGraphGeneration || micStream !== nextStream || audioCtx !== ctx) return; - if (!input.length) return; - micLevel.value = Math.min(1, (rms ?? Math.sqrt(input.reduce((sum, sample) => sum + sample * sample, 0) / input.length)) * 6); - const socket = ws.value; - const shouldSend = !microphoneMuted.value - && !microphoneTestActive.value - && !webrtcActive.value - && socket?.readyState === WebSocket.OPEN - && voxGate(input); - if (!shouldSend) { - accumLen = 0; - if (microphoneMuted.value) { - voxAttack = 0; - voxRelease = 0; - } - return; - } - if (!socket) { - accumLen = 0; - return; - } - const bufferedBytes = socket.bufferedAmount; - if (bufferedBytes > MAX_AUDIO_BUFFERED_BYTES) { - accumLen = 0; - return; - } - - if (convBuf.length < input.length) convBuf = new Int16Array(input.length); - for (let i = 0; i < input.length; i++) { - const sample = Math.max(-1, Math.min(1, input[i]!)); - convBuf[i] = sample < 0 ? sample * 0x8000 : sample * 0x7fff; - } - - const need = accumLen + input.length; - if (accumBuf.length < need) accumBuf = new Int16Array(Math.max(need, accumBuf.length * 2)); - accumBuf.set(convBuf.subarray(0, input.length), accumLen); - 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; - } - if (offset > 0) markSpeaking(state.tsClientId); - accumLen -= offset; - if (offset > 0) accumBuf.set(accumBuf.subarray(offset, offset + accumLen), 0); - }; - - if (typeof AudioWorkletNode !== "undefined" && ctx.audioWorklet) { - try { - if (workletContext !== ctx || !workletModulePromise) { - workletContext = ctx; - workletModulePromise = ctx.audioWorklet.addModule(micCaptureWorkletUrl); - } - await workletModulePromise; - assertCurrent(); - workletNode = new AudioWorkletNode(ctx, "webspeak-mic-capture", { - numberOfInputs: 1, - numberOfOutputs: 1, - outputChannelCount: [1], - }); - workletNode.port.onmessage = (event: MessageEvent<{ samples?: Float32Array; rms?: number }>) => { - const samples = event.data?.samples; - if (samples instanceof Float32Array) handleCaptureChunk(samples, event.data.rms); - }; - } catch { - assertCurrent(); - workletNode?.disconnect(); - workletNode = null; - workletContext = null; - workletModulePromise = null; - } - } - - if (!workletNode) { - scriptNode = ctx.createScriptProcessor(1024, 1, 1); - scriptNode.onaudioprocess = (event) => handleCaptureChunk(event.inputBuffer.getChannelData(0)); - } - - processedSource.connect(micGain); - const captureNode = workletNode ?? scriptNode!; - micGain.connect(captureNode); - captureNode.connect(silentGain); - silentGain.connect(ctx.destination); - await refreshAudioDevices(); - assertCurrent(); - syncAudioContextNotice(); + microphoneCapture = nextCapture; + Object.assign(microphoneProcessing, nextCapture.processing); + 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; + committedNoiseSuppressionEnabled = noiseSuppressionEnabled.value; + clearMicrophoneError(); } catch (error) { - nextStream.getTracks().forEach(track => track.stop()); - if (generation === microphoneGeneration) stopMicrophone(false); + nextCapture?.dispose(); + if (!factoryOwnsStream) nextStream?.getTracks().forEach(track => track.stop()); + if (generation === microphoneGeneration && !(error instanceof CancelledMediaOperation)) { + if (error instanceof DOMException && ["NotAllowedError", "SecurityError"].includes(error.name)) audioPermission.value = "denied"; + setMicrophoneError(error); + } throw error; + } finally { + if (pendingMicrophoneCapture === controller) pendingMicrophoneCapture = null; } + syncAudioContextNotice(); } // 导出给 WebClient:开麦前先 await 此函数完成真实采集,避免出现“假成功” @@ -830,7 +719,11 @@ export function useVoiceWebSocket() { if (microphoneStartPromise) return microphoneStartPromise; if (micStream) return; if (!microphoneStartPromise) { - const pending = startMicrophone().finally(() => { + const generation = microphoneGeneration + 1; + const pending = startMicrophone().then(async () => { + await refreshAudioDevices(); + if (generation !== microphoneGeneration || !micStream) throw new CancelledMediaOperation(); + }).finally(() => { if (microphoneStartPromise === pending) microphoneStartPromise = null; }); microphoneStartPromise = pending; @@ -887,7 +780,7 @@ export function useVoiceWebSocket() { // Use the browser-native processed track plus the browser-side RNNoise // graph. Display/application audio is added separately below and never // passes through this microphone denoiser. - const microphoneStream = processedMicDestination?.stream ?? micStream; + const microphoneStream = microphoneCapture?.processedStream ?? micStream; const microphoneSource = ctx.createMediaStreamSource(microphoneStream); const microphoneGain = ctx.createGain(); microphoneGain.gain.value = microphoneMuted.value ? 0 : inputVolume.value; @@ -1254,56 +1147,37 @@ export function useVoiceWebSocket() { } function stopCaptureGraph(): void { - captureGraphGeneration++; accumLen = 0; voxAttack = 0; voxRelease = 0; micLevel.value = 0; - scriptNode?.disconnect(); - workletNode?.port.close(); - workletNode?.disconnect(); - micGain?.disconnect(); - silentGain?.disconnect(); - scriptNode = null; - workletNode = null; - micGain = null; - silentGain = null; - } - - function stopMicrophoneProcessingGraph(): void { - rnnoiseNode?.destroy(); - rnnoiseNode?.disconnect(); - rnnoiseNode = null; - micSource?.disconnect(); - processedMicDestination?.disconnect(); - processedMicDestination?.stream.getTracks().forEach((track) => track.stop()); - micSource = null; - processedMicDestination = null; + microphoneCapture?.stopCapture(); } function stopMicrophone(closeContext = true): void { if (closeContext) { microphoneGeneration++; microphoneStartPromise = null; + pendingMicrophoneCapture?.abort(); + pendingMicrophoneCapture = null; } stopCaptureGraph(); - stopMicrophoneProcessingGraph(); + microphoneCapture?.dispose(); + microphoneCapture = null; releaseAccompanimentStream(); stopWebRtcMix(); - micStream?.getTracks().forEach((track) => track.stop()); micStream = null; if (closeContext) { void audioCtx?.close().catch(() => undefined); audioCtx = null; - workletContext = null; - workletModulePromise = null; - rnnoiseWorkletModulePromise = null; } } async function prepareInputDevices(): Promise { if (!micStream) await startMicrophone(); - else await refreshAudioDevices(); + const generation = microphoneGeneration; + await refreshAudioDevices(); + if (generation !== microphoneGeneration || !micStream) throw new CancelledMediaOperation(); } async function setInputDevice(deviceId: string): Promise { @@ -1363,10 +1237,11 @@ export function useVoiceWebSocket() { const previousDeviceId = committedOutputDeviceId; selectedOutputDeviceId.value = deviceId; try { - await setAudioSink(getAudioCtx(), deviceId); + if (audioCtx || deviceId) await setAudioSink(audioCtx ?? getAudioCtx(), deviceId); if (!isCurrent()) return; committedOutputDeviceId = deviceId; localStorage.setItem("webspeak:output-device", deviceId); + clearAudioNotice("OUTPUT_DEVICE_UNAVAILABLE"); await saveAudioPreferences(); } catch (error) { if (!isCurrent()) return; @@ -1375,6 +1250,7 @@ export function useVoiceWebSocket() { // One endpoint may have changed before the other rejected the request. if (audioCtx) await setAudioSink(audioCtx, previousDeviceId).catch(() => undefined); if (!isCurrent()) return; + setAudioNotice("OUTPUT_DEVICE_UNAVAILABLE", "无法切换到所选音频输出设备,请检查设备连接或选择其他扬声器"); throw error; } } @@ -2144,7 +2020,7 @@ export function useVoiceWebSocket() { function setInputVolume(volume: number): void { inputVolume.value = Math.max(0, Math.min(1, volume)); - if (micGain) micGain.gain.value = inputVolume.value; + microphoneCapture?.setVolume(inputVolume.value); if (webrtcMixMicGain) webrtcMixMicGain.gain.value = microphoneMuted.value ? 0 : inputVolume.value; void saveAudioPreferences(); } diff --git a/web/src/composables/useWebClientI18n.ts b/web/src/composables/useWebClientI18n.ts index 39142d3..4a44c5c 100644 --- a/web/src/composables/useWebClientI18n.ts +++ b/web/src/composables/useWebClientI18n.ts @@ -246,6 +246,12 @@ function localizedAudioNotice(code: string, message: string) { ru: "Не удалось получить список аудиоустройств. Будут использованы устройства браузера по умолчанию", ja: "オーディオデバイスを一覧表示できません。ブラウザのデフォルトデバイスを使用します", }, + OUTPUT_DEVICE_UNAVAILABLE: { + en: "The selected audio output could not be activated. Check the device connection or choose another speaker", + de: "Die ausgewählte Audioausgabe konnte nicht aktiviert werden. Prüfe die Geräteverbindung oder wähle einen anderen Lautsprecher", + ru: "Не удалось включить выбранное устройство вывода. Проверьте подключение или выберите другие динамики", + ja: "選択した音声出力に切り替えられませんでした。接続を確認するか、別のスピーカーを選択してください", + }, AUDIO_CONTEXT_SUSPENDED: { en: "Browser audio processing is paused. Click the page once to resume microphone and speaker audio", de: "Die Audioverarbeitung des Browsers ist pausiert. Klicke einmal auf die Seite, um Mikrofon und Lautsprecher fortzusetzen", diff --git a/web/src/voice/microphone-capture.ts b/web/src/voice/microphone-capture.ts new file mode 100644 index 0000000..6d050d9 --- /dev/null +++ b/web/src/voice/microphone-capture.ts @@ -0,0 +1,166 @@ +import { RnnoiseWorkletNode, loadRnnoise } from "@sapphi-red/web-noise-suppressor"; +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"; + +export interface MicrophoneProcessingSettings { + echoCancellation: boolean | null; + noiseSuppression: boolean | null; + autoGainControl: boolean | null; + rnnoise: boolean | null; +} + +export interface MicrophoneCapture { + processedStream: MediaStream; + processing: MicrophoneProcessingSettings; + activate(): void; + setVolume(value: number): void; + stopCapture(): void; + dispose(): void; +} + +interface CaptureOptions { + context: AudioContext; + stream: MediaStream; + noiseSuppression: boolean; + volume: number; + signal: AbortSignal; + assertCurrent(): void; + onSamples(input: Float32Array, rms?: number): void; +} + +// 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; + function loadModule(ctx: AudioContext, url: string): Promise { + let cache = modules.get(ctx); + if (!cache) { cache = new Map(); modules.set(ctx, cache); } + let pending = cache.get(url); + if (!pending) { + const ownCache = cache; + pending = ctx.audioWorklet.addModule(url).catch(error => { + if (ownCache.get(url) === pending) ownCache.delete(url); + throw error; + }); + cache.set(url, pending); + } + return pending; + } + + async function prepare(options: CaptureOptions): Promise { + const { context: ctx, stream, assertCurrent } = options; + let source: MediaStreamAudioSourceNode | null = null; + let denoiser: RnnoiseWorkletNode | null = null; + let destination: MediaStreamAudioDestinationNode | null = null; + let gain: GainNode | null = null; + let silent: GainNode | null = null; + let worklet: AudioWorkletNode | null = null; + let script: ScriptProcessorNode | null = null; + let active = false; + let disposed = false; + const clean = (operation: () => void) => { try { operation(); } catch { /* release the other resources too */ } }; + function stopCapture() { + active = false; + if (worklet) { clean(() => worklet!.port.close()); clean(() => worklet!.disconnect()); } + if (script) clean(() => script!.disconnect()); + if (gain) clean(() => gain!.disconnect()); + if (silent) clean(() => silent!.disconnect()); + worklet = null; script = null; gain = null; silent = null; + } + function dispose() { + if (disposed) return; + disposed = true; + stopCapture(); + if (denoiser) { clean(() => denoiser!.destroy()); clean(() => denoiser!.disconnect()); } + if (source) clean(() => source!.disconnect()); + if (destination) { + clean(() => destination!.disconnect()); + for (const track of destination.stream.getTracks()) clean(() => track.stop()); + } + for (const track of stream.getTracks()) clean(() => track.stop()); + } + const onSamples = (samples: Float32Array, rms?: number) => { + if (active && !disposed) options.onSamples(samples, rms); + }; + options.signal.addEventListener("abort", dispose, { once: true }); + try { + assertCurrent(); + const track = stream.getAudioTracks().find(candidate => candidate.readyState === "live"); + if (!track) throw new DOMException("No live microphone track", "NotFoundError"); + const settings = track.getSettings(); + source = ctx.createMediaStreamSource(stream); + const supportsWorklet = typeof AudioWorkletNode !== "undefined" && Boolean(ctx.audioWorklet); + if (options.noiseSuppression && 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)]); + assertCurrent(); + denoiser = new RnnoiseWorkletNode(ctx, { maxChannels: 1, wasmBinary }); + } catch { + assertCurrent(); // RNNoise is optional; cancellation is not a fallback. + } + } + const processedSource = denoiser ?? source; + if (denoiser) source.connect(denoiser); + destination = ctx.createMediaStreamDestination(); + destination.channelCount = 1; + destination.channelCountMode = "explicit"; + processedSource.connect(destination); + gain = ctx.createGain(); + gain.gain.value = options.volume; + silent = ctx.createGain(); + silent.gain.value = 0; + if (supportsWorklet) { + try { + await loadModule(ctx, "/mic-capture-worklet.js"); + assertCurrent(); + worklet = new AudioWorkletNode(ctx, "webspeak-mic-capture", { + numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [1], + }); + worklet.port.onmessage = (event: MessageEvent<{ samples?: Float32Array; rms?: number }>) => { + if (event.data?.samples instanceof Float32Array) onSamples(event.data.samples, event.data.rms); + }; + } catch { + assertCurrent(); + if (worklet) { clean(() => worklet!.port.close()); clean(() => worklet!.disconnect()); } + worklet = null; + } + } + if (!worklet) { + script = ctx.createScriptProcessor(1024, 1, 1); + script.onaudioprocess = event => onSamples(event.inputBuffer.getChannelData(0)); + } + processedSource.connect(gain); + const capture = worklet ?? script!; + gain.connect(capture); + capture.connect(silent); + silent.connect(ctx.destination); + assertCurrent(); + if (track.readyState !== "live") throw new DOMException("Microphone track ended", "NotReadableError"); + return { + processedStream: destination.stream, + processing: { + echoCancellation: typeof settings.echoCancellation === "boolean" ? settings.echoCancellation : null, + noiseSuppression: typeof settings.noiseSuppression === "boolean" ? settings.noiseSuppression : null, + autoGainControl: typeof settings.autoGainControl === "boolean" ? settings.autoGainControl : null, + rnnoise: Boolean(denoiser), + }, + activate() { if (!disposed && (worklet || script)) active = true; }, + setVolume(value) { if (gain) gain.gain.value = value; }, + stopCapture, + dispose, + }; + } catch (error) { + dispose(); + throw error; + } finally { + options.signal.removeEventListener("abort", dispose); + } + } + return { prepare }; +} diff --git a/web/test/voice-session.test.mjs b/web/test/voice-session.test.mjs index 9ebeb5c..6e81dd3 100644 --- a/web/test/voice-session.test.mjs +++ b/web/test/voice-session.test.mjs @@ -190,6 +190,7 @@ beforeEach(() => { replaceGlobal("location", { protocol: "https:", host: "gateway.example" }); replaceGlobal("fetch", async () => ({ ok: true, json: async () => ({ ticket: "test-ticket" }) })); replaceGlobal("AudioContext", AudioContextStub); + replaceGlobal("AudioWorkletNode", class {}); replaceGlobal("AudioDecoder", AudioDecoderStub); replaceGlobal("MediaRecorder", RecorderStub); const storage = new Map(); @@ -968,3 +969,177 @@ test("replacing compatibility capture prevents the old graph from sending into t current.onaudioprocess(event); assert.equal(socket.messages.filter(message => message instanceof ArrayBuffer).length, 1); }); + +test("a failed replacement processing graph preserves the live microphone and PCM path", async t => { + navigator.mediaDevices.enumerateDevices = async () => availableDevices; + const initial = microphoneStream(); + navigator.mediaDevices.getUserMedia = async () => initial; + const socket = await connect(); + socket.receive({ type: "connected", tsClientId: 1 }); + await nextTurn(); + const capture = AudioContextStub.processors.at(-1); + const replacement = microphoneStream(); + navigator.mediaDevices.getUserMedia = async () => replacement; + const ctx = AudioContextStub.instances.at(-1); + const processing = { ...voice.microphoneProcessing }; + t.mock.method(ctx, "createGain", () => { throw new Error("Gain allocation failed"); }); + await assert.rejects(voice.setInputDevice("mic-b"), /Gain allocation failed/); + assert.equal(initial.track.readyState, "live"); + assert.equal(replacement.track.readyState, "ended"); + capture.onaudioprocess({ inputBuffer: { getChannelData: () => new Float32Array(960).fill(0.25) } }); + assert.equal(socket.messages.filter(message => message instanceof ArrayBuffer).length, 1); + assert.deepEqual({ ...voice.microphoneProcessing }, processing); + assert.equal(voice.selectedInputDeviceId.value, ""); + assert.notEqual(voice.state.microphoneErrorCode, ""); +}); + +test("waiting for a replacement worklet keeps the current graph sending", async t => { + navigator.mediaDevices.enumerateDevices = async () => availableDevices; + const socket = await connect(); + socket.receive({ type: "connected", tsClientId: 1 }); + await nextTurn(); + const capture = AudioContextStub.processors.at(-1); + const module = deferred(); + AudioContextStub.instances.at(-1).audioWorklet = { addModule: url => url === "/mic-capture-worklet.js" ? module.promise : Promise.resolve() }; + // A missing worklet constructor must still permit the ScriptProcessor fallback. + replaceGlobal("AudioWorkletNode", class { constructor() { throw new Error("Worklet unavailable"); } }); + t.after(() => module.resolve()); + const pending = voice.setInputDevice("mic-a"); + await nextTurn(); + capture.onaudioprocess({ inputBuffer: { getChannelData: () => new Float32Array(960).fill(0.25) } }); + const framesWhilePreparing = socket.messages.filter(message => message instanceof ArrayBuffer).length; + module.resolve(); + await pending; + assert.equal(framesWhilePreparing, 1); + AudioContextStub.processors.at(-1).onaudioprocess({ inputBuffer: { getChannelData: () => new Float32Array(960).fill(0.25) } }); + assert.equal(socket.messages.filter(message => message instanceof ArrayBuffer).length, 2); +}); + +test("disconnect during worklet preparation releases every candidate node and track", async t => { + navigator.mediaDevices.enumerateDevices = async () => availableDevices; + await voice.ensureMicrophone(); + const module = deferred(); + const ctx = AudioContextStub.instances.at(-1); + ctx.audioWorklet = { addModule: url => url === "/mic-capture-worklet.js" ? module.promise : Promise.resolve() }; + const source = new AudioNodeStub(); + const destination = Object.assign(new AudioNodeStub(), { stream: microphoneStream() }); + t.mock.method(ctx, "createMediaStreamSource", () => source); + t.mock.method(ctx, "createMediaStreamDestination", () => destination); + const stream = microphoneStream(); + navigator.mediaDevices.getUserMedia = async () => stream; + const pending = voice.setInputDevice("mic-a"); + t.after(() => module.resolve()); + await nextTurn(); + voice.disconnect(); + assert.equal(stream.track.readyState, "ended"); + assert.equal(destination.stream.track.readyState, "ended"); + assert.ok(source.disconnects > 0); + module.resolve(); + await pending; + assert.equal(voice.ws.value, null); +}); + +test("a failed first capture graph reports an error and releases its stream", async t => { + const stream = microphoneStream(); + navigator.mediaDevices.getUserMedia = async () => stream; + t.mock.method(AudioContextStub.prototype, "createScriptProcessor", () => { throw new Error("Capture node unavailable"); }); + await assert.rejects(voice.ensureMicrophone(), /Capture node unavailable/); + assert.equal(stream.track.readyState, "ended"); + assert.notEqual(voice.state.microphoneErrorCode, ""); +}); + +test("removing the selected microphone restarts WebRTC with the default input", async () => { + navigator.mediaDevices.enumerateDevices = async () => availableDevices; + await voice.setInputDevice("mic-a"); + const { peer, socket } = await connectWebRtc(); + navigator.mediaDevices.enumerateDevices = async () => availableDevices.filter(device => device.deviceId !== "mic-a"); + const replacement = microphoneStream(); + navigator.mediaDevices.getUserMedia = async () => replacement; + await voice.refreshAudioDevices(); + await nextTurn(); + assert.equal(peer.connectionState, "closed"); + assert.equal(socket.messages.filter(message => message.type === "webrtcOffer").length, 2); + assert.equal(voice.selectedInputDeviceId.value, ""); + assert.equal(localStorage.getItem("webspeak:input-device"), ""); + assert.equal(replacement.track.readyState, "live"); +}); + +test("a failed default input fallback does not overwrite the last successful preference", async () => { + navigator.mediaDevices.enumerateDevices = async () => availableDevices; + await voice.setInputDevice("mic-a"); + await voice.ensureMicrophone(); + navigator.mediaDevices.enumerateDevices = async () => availableDevices.filter(device => device.deviceId !== "mic-a"); + navigator.mediaDevices.getUserMedia = async () => { throw new Error("Default microphone unavailable"); }; + await voice.refreshAudioDevices(); + await nextTurn(); + assert.equal(voice.selectedInputDeviceId.value, "mic-a"); + assert.equal(localStorage.getItem("webspeak:input-device"), "mic-a"); + assert.notEqual(voice.state.microphoneErrorCode, ""); +}); + +test("a rejected default output fallback preserves the last preference and reports the failure", async t => { + navigator.mediaDevices.enumerateDevices = async () => availableDevices; + await voice.prepareInputDevices(); + await voice.setOutputDevice("speaker-a"); + navigator.mediaDevices.enumerateDevices = async () => availableDevices.filter(device => device.deviceId !== "speaker-a"); + const ctx = AudioContextStub.instances.at(-1); + t.mock.method(ctx, "setSinkId", async id => { if (id === "default") throw new Error("Default output unavailable"); ctx.sinkId = id; }); + await voice.refreshAudioDevices(); + await nextTurn(); + assert.equal(voice.selectedOutputDeviceId.value, "speaker-a"); + assert.equal(localStorage.getItem("webspeak:output-device"), "speaker-a"); + assert.equal(voice.state.audioNoticeCode, "OUTPUT_DEVICE_UNAVAILABLE"); +}); + +test("an AudioWorklet capture sends PCM and ignores late port messages after teardown", async () => { + navigator.mediaDevices.enumerateDevices = async () => availableDevices; + const socket = await connect(); + socket.receive({ type: "connected", tsClientId: 1 }); + await nextTurn(); + const worklets = []; + replaceGlobal("AudioWorkletNode", class extends AudioNodeStub { + port = { onmessage: null, closed: false, close() { this.closed = true; } }; + constructor() { super(); worklets.push(this); } + }); + AudioContextStub.instances.at(-1).audioWorklet = { addModule: async () => {} }; + await voice.setInputDevice("mic-b"); + const capture = worklets.at(-1); + const onmessage = capture.port.onmessage; + onmessage({ data: { samples: new Float32Array(960).fill(0.25) } }); + assert.equal(socket.messages.filter(message => message instanceof ArrayBuffer).length, 1); + voice.disconnect(); + assert.equal(capture.port.closed, true); + assert.ok(capture.disconnects > 0); + onmessage({ data: { samples: new Float32Array(960).fill(0.25) } }); + assert.equal(socket.messages.filter(message => message instanceof ArrayBuffer).length, 1); +}); + +test("a failed newer switch restores the device whose graph is already live during enumeration", async () => { + navigator.mediaDevices.enumerateDevices = async () => availableDevices; + await voice.ensureMicrophone(); + const enumeration = deferred(); + let reads = 0; + navigator.mediaDevices.enumerateDevices = () => ++reads === 1 ? enumeration.promise : Promise.resolve(availableDevices); + const replacement = microphoneStream(); + navigator.mediaDevices.getUserMedia = ({ audio }) => audio.deviceId.exact === "mic-a" + ? Promise.resolve(replacement) : Promise.reject(new Error("Newer input failed")); + const first = voice.setInputDevice("mic-a"); + await nextTurn(); + await assert.rejects(voice.setInputDevice("mic-b"), /Newer input failed/); + enumeration.resolve(availableDevices); + await first; + assert.equal(replacement.track.readyState, "live"); + assert.equal(voice.selectedInputDeviceId.value, "mic-a"); + assert.equal(localStorage.getItem("webspeak:input-device"), "mic-a"); +}); + +test("disconnect while initial device labels load still cancels microphone readiness", async () => { + const enumeration = deferred(); + navigator.mediaDevices.enumerateDevices = () => enumeration.promise; + const readiness = voice.ensureMicrophone(); + await nextTurn(); + voice.disconnect(); + enumeration.resolve(availableDevices); + await assert.rejects(readiness, error => error.name === "AbortError"); + assert.equal(voice.state.microphoneErrorCode, ""); +});