mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-02 19:42:51 +08:00
fix: preserve audio capture across device reconfiguration
This commit is contained in:
1 parent
797fc135a9
commit
0785f82386
5 files changed
+382
-45
No files matched your search
@@ -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/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 |
|
||||
| `web/src/services/admin-api.ts` | Admin HTTP transport, response validation, current CSRF and authentication-expiry notification, including skin uploads and backup downloads |
|
||||
@@ -56,6 +57,10 @@ Remote playback owns each speaker's decoder, gain and source nodes as one resour
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
## Configuration and persistence
|
||||
|
||||
@@ -2,15 +2,15 @@
|
||||
|
||||
本文记录 `webspeak-webclient` 的代码边界、待修改事项、修改方向及验收标准。前轮只读梳理已结束,现按“开始施工,直到所有问题修复”的持续目标实施。正文区分已有实现、待验证行为和剩余工作,文末保留各批次验证范围。
|
||||
|
||||
当前构建与 CI 入口已经统一,共享协议、前端屏幕共享、四个服务端桥接子模块、Android 启动及管理请求层已有实现。本批完成远端播放接入和录音测试控制器,补充行为验证。剩余重点是采集与设备切换、服务端音频转发、页面状态及组件边界,以及真实媒体和平台验收。
|
||||
当前构建与 CI 入口已经统一,共享协议、前端屏幕共享、四个服务端桥接子模块、Android 启动及管理请求层已有实现。远端播放和录音测试已独立;最新批次修复设备选择、降噪重建和采集连续性的交错操作。剩余重点是采集模块提取、服务端音频转发、页面状态及组件边界,以及真实媒体和平台验收。
|
||||
|
||||
## 范围与基线
|
||||
|
||||
- 记录日期:2026 年 10 月 1 日。
|
||||
- 本批起始基线:`dev` 分支,提交 `9bfe4b9dcb5834897c78c410b096fe6d45794db2`,应用版本 `0.2.5-preview`。
|
||||
- 最新批次起始基线:`dev` 分支,提交 `ad83c87a79f8aa73b589f629a3f070203b9e96cd`,应用版本 `0.2.5-preview`。
|
||||
- 分析对象:当前工作区,包含已有未提交改动,不等同于该提交的干净检出。
|
||||
- 本批沿用并完成已有远端播放控制器、composable 接入和会话测试,保留前轮只读整理记录。
|
||||
- 当前工作区 `npm run verify` 通过 149 项测试、后端编译、前端类型检查和生产构建。另已确认提交 `9bfe4b9` 的远端 CI 与 Docker 健康检查成功;这项远端结果不覆盖本批新增代码。
|
||||
- 远端播放及录音实现已在 `ad83c87` 提交并推送;最新批次继续修复输入输出设备及降噪配置,保留前轮只读整理记录。
|
||||
- 当前工作区 `npm run verify` 通过 164 项测试、后端编译、前端类型检查和生产构建。另已确认提交 `ad83c87` 的远端 CI 与 Docker 健康检查成功;这项远端结果不覆盖最新设备切换改动。
|
||||
- 验证结果只适用于对应提交或工作区快照;模拟边界的生命周期测试、编解码冒烟和应用构建均不能代替真实 TeamSpeak 双向语音及真机验收。
|
||||
|
||||
下文按当前工作区更新现状,区分已完成、已有未提交实现、待验证和待实施。优先级表示建议实施顺序,不代表已确认的故障或安全漏洞等级。
|
||||
@@ -26,7 +26,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` | 中继进程及网关侧中继接入 |
|
||||
@@ -41,7 +41,7 @@
|
||||
| 01 | P1 | 统一构建命令与 CI 验证入口 | 工程基线 | 已完成,提交 `5c11bd9` 的 CI 已通过 |
|
||||
| 02 | P1 | 补齐会话与媒体关键行为测试 | 测试缺口 | 基础测试已补,媒体及完整连接验证待补 |
|
||||
| 03 | P2 | 集中前后端协议契约 | 重构建议 | WebSocket、WebRTC 和管理请求模型已集中,契约及管理 HTTP 集成测试通过;真实媒体联调待完成 |
|
||||
| 04 | P2 | 拆分前端语音核心模块 | 生命周期修复及重构建议 | 远端播放与录音测试已提取并通过本地验证;采集、设备切换、WebRTC 及连接职责待继续 |
|
||||
| 04 | P2 | 拆分前端语音核心模块 | 生命周期修复及重构建议 | 播放、录音和设备切换回归通过;采集、WebRTC 及连接职责仍待提取与集成验收 |
|
||||
| 05 | P2 | 拆分服务端实时桥接模块 | 重构建议及行为修复 | 已拆出命令、目录展示、统计和共享协调;音频转发及集成验证待继续 |
|
||||
| 06 | P2 | 拆分页面组件与管理页逻辑 | 重构建议及布局修复 | 文案、样式、头部、路由分包及管理 API 已提取;页面状态与剩余业务组件待拆分 |
|
||||
| 07 | P2 | 明确 Android 平台边界与验证范围 | 预览功能的整理与验证 | 启动测试、三架构 APK 构建及模拟器启动通过;真实连接与设备音频待验收 |
|
||||
@@ -58,18 +58,18 @@ P1 为优先修正的衔接问题和验证基线,P2 为职责整理及待核
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 04-A | 已修复,本地验证通过 | 成员离开分支的旧函数引用导致后续成员删除被中断;回归测试先复现失败 | 已接到 `remotePlayback.clear`,成员状态和所属播放资源一起清理 | 类型检查通过;成员退出测试确认仅清理离开者,不影响其他说话者 |
|
||||
| 04-B | 已实现,本地验证通过;实际听音待验收 | `remote-playback.ts` 约 125 行,集中解码器、源节点、增益节点与队列状态 | 保持 80 ms 播放上限与 3 帧解码排队阈值;旧回调仅处理原资源 | 10 项远端播放及二进制帧用例通过,包括音量、静音、队列恢复和成员隔离;完整构建通过 |
|
||||
| 04-C | 录音已修复,设备切换仍待核验 | 原录音器、计时器及对象 URL 缺少独立操作身份;输入设备切换的异步回滚仍在核心模块 | 已提取 `microphone-test.ts`;下一步核验设备切换,再整理采集控制器 | 9 项录音用例通过,其中 6 项先失败后修复;设备切换失败、切换期间断开仍需覆盖 |
|
||||
| 04-C | 录音与设备切换已修复,本地验证通过;真机待验收 | 原录音和设备操作缺少完整身份检查;切换失败可能关闭通话或回滚新选择 | 录音控制器独立;设备和降噪统一应用与回滚,输出切换按端点串行,已运行采集与权限申请分别失效 | 9 项录音及随后 15 项设备、采集用例通过;实际设备热插拔、浏览器与 Android 音频仍需验收 |
|
||||
| 06-A | P2,请求竞态待复现 | `AdminView.vue` 的 `loadOperations`、`loadSkinCatalog`、`runTest` 和 `saveServerSettings` 均在等待后直接写页面状态;当前没有对应请求代次或页面退出取消机制 | 先约定请求过期规则,再按功能拆状态;对同类刷新只接收最新结果,保存时明确如何保留请求发出后的用户编辑,退出页面后使旧结果失效 | 人为颠倒响应顺序、慢请求期间改字段、离开管理页、退出后重新登录;旧响应不覆盖新状态或触发过期跳转 |
|
||||
| 06-B | P2,静态确认的文案分散 | `AdminView.vue:399` 之后仍有内联时间、事件及错误文案;`sessionStateLabel` 和部分错误映射仅处理中、英、德,俄、日回退英文 | 将剩余文案迁入现有 `i18n/admin.ts`,补齐支持语言;格式化函数只处理日期、数值和翻译键 | 五种语言逐项核对会话状态、连接错误与中继错误,保持错误码和业务行为不变 |
|
||||
| 08-A | 文档已同步,APK 复验待完成 | `mobile/README.md` 原有头部待修说明落后于网页代码,`CLAUDE.md` 尚未记录新媒体控制器 | 已区分网页布局修复与 APK 复验,并补充远端播放和录音模块的资源边界 | 文档不再沿用过期的待修结论;设备实测仍列为未完成 |
|
||||
|
||||
04-A 是提取过程中的衔接遗漏,不归因于起始提交。04-C 的录音问题已复现并修复;设备切换和 06-A 的管理请求仍是待核验任务,不将其提前描述为已发生的故障。
|
||||
04-A 是播放提取过程中的衔接遗漏。04-C 的录音、设备和采集问题已有复现与修复,验证范围见末尾;06-A 的管理请求仍是待核验任务,不将其提前描述为已发生的故障。
|
||||
|
||||
## 后续可直接执行的清单
|
||||
|
||||
| 顺序 | 待办与依据 | 大致修改方向 | 完成条件 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 远端播放与录音控制器已有验证;语音核心仍集中采集和设备选择 | 补设备切换用例,依次提取麦克风与伴奏、WebRTC、连接传输 | 保持对外接口稳定,断开释放资源,迟到结果不影响新会话 |
|
||||
| 1 | 播放、录音和设备切换已有行为基线;语音核心仍集中采集和传输 | 依次提取麦克风与伴奏、WebRTC、连接传输;继续验证处理节点创建失败和设备热插拔 | 保持对外接口稳定,断开释放资源,迟到结果不影响新会话 |
|
||||
| 2 | 服务端桥接仍集中音频转发和 SDK 事件编排 | 提取音频收发和目录事件协调,沿用现有会话状态与清理入口 | 背压、队列上限、重连、目录同步及共享隔离行为保持一致 |
|
||||
| 3 | 管理网络层已提取,但页面状态和各功能模板仍集中 | 拆分服务器、会话、邀请、皮肤和诊断状态及组件;继续检查迟到请求和页面退出 | 保留已验证的错误反馈、登录失效、CSRF 和凭据更新语义 |
|
||||
| 4 | 网页客户端仍有较多页面模板 | 沿加入表单、频道树、聊天区、音频设置和弹窗拆分,继续复用已有 composable | 皮肤钩子、语言切换、明暗主题及各尺寸交互保持一致 |
|
||||
@@ -99,11 +99,11 @@ P1 为优先修正的衔接问题和验证基线,P2 为职责整理及待核
|
||||
|
||||
### 02 补齐会话与媒体关键行为测试
|
||||
|
||||
**现状与位置:** 根目录 `test` 脚本显式列出 27 个测试文件。当前完整验证通过 149 项测试;相对起始提交新增 10 项播放及二进制帧用例、9 项录音用例,实际运行 composable,浏览器媒体边界使用替身。已有共享契约、管理 HTTP 集成、伴奏取消、协商失效、PCM 回退和 Android 启动测试继续通过。仍缺真实浏览器到 TeamSpeak 的完整连接及 WebRTC 回退验收;模拟媒体边界的测试不能替代真实媒体测试。尚未测量覆盖率。
|
||||
**现状与位置:** 根目录 `test` 脚本显式列出 27 个测试文件。当前完整验证通过 164 项测试;播放与录音批次新增 19 项,随后设备和采集批次新增 15 项,实际运行 composable,浏览器媒体边界使用替身。已有共享契约、管理 HTTP 集成、伴奏取消、协商失效、PCM 回退和 Android 启动测试继续通过。仍缺真实浏览器到 TeamSpeak 的完整连接及 WebRTC 回退验收;模拟媒体边界的测试不能替代真实媒体测试。尚未测量覆盖率。
|
||||
|
||||
**修改方向:** 优先为即将拆分的模块建立行为基线。覆盖加入凭证过期及重复消费、会话重复清理、目录快照与实时事件合并、重连成功与失败、WebRTC 失败回退、屏幕共享退出后的资源释放。通过可替换的时钟、传输和 SDK 边界验证正常与异常路径;真实 TeamSpeak、浏览器媒体和 Android 行为另设可重复执行的集成验证步骤。
|
||||
|
||||
**下一批优先用例:** 迟到二进制帧、录音、解码器及播放源清理已补,继续覆盖设备切换。服务端音频需要覆盖慢客户端背压、突发帧和延迟调度时的队列上限。随后补充真实浏览器和 TeamSpeak 的回退及双向语音验证。
|
||||
**下一批优先用例:** 迟到二进制帧、录音、播放清理和设备切换已有覆盖,继续检查麦克风处理节点创建失败与设备热插拔。服务端音频需要覆盖慢客户端背压、突发帧和延迟调度时的队列上限。随后补充真实浏览器和 TeamSpeak 的回退及双向语音验证。
|
||||
|
||||
**验收标准:** 核心测试能在 CI 中运行;测试能够发现重复消费、重复清理、状态不同步和回退失败等行为回归;需要设备或真实服务的步骤记录环境与结果,不以类型检查或 HTTP 健康检查代替音频验证。
|
||||
|
||||
@@ -119,7 +119,7 @@ P1 为优先修正的衔接问题和验证基线,P2 为职责整理及待核
|
||||
|
||||
### 04 拆分前端语音核心模块
|
||||
|
||||
**现状与位置:** [useVoiceWebSocket.ts](../web/src/composables/useVoiceWebSocket.ts) 当前约 2,183 行,起始提交约 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)。连接、凭证请求、麦克风采集、降噪、设备选择、WebRTC 语音、伴奏和统计仍在核心模块中。
|
||||
**现状与位置:** [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 语音、伴奏和统计仍在核心模块中。
|
||||
|
||||
**修改方向:** 暂时保留现有 composable 作为页面调用入口,逐项提取连接与命令传输、麦克风处理、远端播放、WebRTC 语音及统计模块,复用已经拆出的屏幕共享控制器。先明确各模块拥有的状态和资源,再移动实现,避免所有模块相互读取同一个大型可变对象。每次只迁移一项职责,并明确初始化、停止和销毁的责任。
|
||||
|
||||
@@ -136,7 +136,7 @@ P1 为优先修正的衔接问题和验证基线,P2 为职责整理及待核
|
||||
|
||||
**已修复的细节:** 旧 WebSocket 消息现在同时校验连接代次、当前 socket 和打开状态;主动断开、异常关闭及服务端断连事件共用资源释放路径。屏幕共享 ICE 配置已改为实例所有,异步协商和统计结果在所属连接失效后不再写回。麦克风授权迟到时释放音轨并取消旧操作,新连接可以独立申请采集。相关问题已通过先失败后通过的回归测试验证;其他音频资源仍需继续检查。
|
||||
|
||||
**建议切入顺序:** 远端播放和录音测试已有控制器及回归,接下来核验设备切换并提取麦克风及伴奏、WebRTC 语音,最后收拢连接与命令。每个控制器显式拥有其音轨、节点、计时器和取消标识;现有 `releaseSessionResources` 保持统一清理入口。录音控制器只拥有录音测试资源,麦克风流仍由采集入口管理,避免停止试听时结束房间内采集。
|
||||
**建议切入顺序:** 远端播放、录音和设备切换已有行为基线,接下来提取麦克风及伴奏、WebRTC 语音,最后收拢连接与命令。每个控制器显式拥有其音轨、节点、计时器和取消标识;现有 `releaseSessionResources` 保持统一清理入口。录音控制器只拥有录音测试资源,麦克风流仍由采集入口管理,避免停止试听时结束房间内采集。
|
||||
|
||||
**验收标准:** 页面调用接口保持兼容,或有范围明确的迁移;连接、断开、重连、设备切换及 WebRTC 回退行为保持一致;音轨、解码器、定时器和事件监听具有明确清理路径,重复连接不会累计资源。
|
||||
|
||||
@@ -207,7 +207,8 @@ P1 为优先修正的衔接问题和验证基线,P2 为职责整理及待核
|
||||
| 已建立的基线 | 01、08,以及 02 的基础行为测试 | 保留已通过的统一验证入口和文档修正 |
|
||||
| 历史行为基线 | 02 的媒体生命周期、Android 启动、WebRTC 契约和管理 API;09 的代表性路径检查 | 上一批记录为 130 项测试及前后端构建通过,不能覆盖当前未提交内容 |
|
||||
| 已提交的页面整理 | 06 的路由样式隔离、头部布局、文案与样式提取和管理 API;03 的 WebRTC 契约 | 保留历史验证范围,后续变更重新验证 |
|
||||
| 本批完成 | 04-A、04-B 的远端播放提取,以及 04-C 的录音测试控制器 | 149 项测试、后端编译、前端类型检查和构建通过;本批远端 CI 单独确认 |
|
||||
| 已完成的播放与录音 | 04-A、04-B 的远端播放提取,以及 04-C 的录音测试控制器 | `ad83c87` 的 149 项测试及前后端构建、远端 CI、Docker 健康检查通过 |
|
||||
| 最新设备修复 | 04-C 的设备、降噪交错操作及采集连续性 | 本地 164 项测试及前后端构建通过;新提交远端 CI 单独确认 |
|
||||
| 随后 | 为 04、05 的剩余媒体职责补行为用例,再分项拆分 | 每次迁移都能验证连接和媒体行为,并独立回退 |
|
||||
| 页面整理 | 06 的业务状态与剩余组件 | 页面行为、错误反馈、皮肤接口及布局验证通过 |
|
||||
| 独立工作项 | 真实 TeamSpeak 联调、07 的运行时与设备验收、09 的各平台干净打包 | 记录具体环境、实际结果和未支持能力,不混入结构拆分 |
|
||||
@@ -289,8 +290,18 @@ P1 为优先修正的衔接问题和验证基线,P2 为职责整理及待核
|
||||
|
||||
### 远端播放与录音测试实施记录
|
||||
|
||||
- 对应提交 `ad83c87`;[远端 CI](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36809738335) 的应用验证、Docker 构建和健康检查已确认成功。
|
||||
- 远端播放控制器统一拥有每位成员的解码器、播放源、增益节点和排队时间;重置、失败和成员退出都释放所属资源,旧回调不能清理替代资源。
|
||||
- 修复提取过程中遗漏的成员退出调用点。该用例先复现成员无法移除,修复后验证只停止离开者的音频。
|
||||
- 录音测试独立管理操作身份、录音器、五秒期限与试听 URL。六项录音问题先复现失败后修复:断开未停止、连续启动未停止旧录音、旧权限错误清除新状态、取消后仍创建录音器、自然结束仍显示活动,以及启动失败遗留采集。
|
||||
- 相对起始提交新增 19 项测试。当前 149 项测试、后端编译、前端类型检查和生产构建通过;录音与解码使用浏览器边界替身,未声称真实音质或设备兼容性已通过。
|
||||
- 输入输出设备切换、管理请求竞态、剩余模块提取、真实 TeamSpeak、Android 真机与各平台发布包仍待完成,持续目标保持未完成。
|
||||
|
||||
### 设备切换与采集连续性实施记录
|
||||
|
||||
- 输入设备和降噪设置共用配置操作,只有当前操作能够提交或回滚,持久化保存最后成功的选择。麦克风授权失败保留原有 WebRTC peer 和采集流。
|
||||
- 输出切换按 AudioContext 或音频元素分别串行执行;断开后跳过排队任务,旧端点回调不能设置新端点。某个端点拒绝时尝试恢复先前输出。
|
||||
- 设备列表只采用当前查询结果;迟到的成功或失败不能覆盖新列表,或在断开后恢复错误提示。
|
||||
- 分离采集申请与已运行处理链的失效标识,保持等待新设备及授权失败时的兼容 PCM 发送。替换处理链或断开后,旧回调失效。
|
||||
- 新增 15 项测试,其中 10 项先复现失败后修复,包括复查发现的上一批录音提取遗漏:关闭设置但未启动录音时,仍须释放独立采集。
|
||||
- `npm run verify` 通过 164 项测试、后端编译、前端类型检查及生产构建。实际媒体设备和 TeamSpeak 仍未验收;剩余采集模块提取、管理页面与服务端任务继续推进。
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createRemotePlayback } from "../voice/remote-playback.js";
|
||||
import { createMicrophoneTest } from "../voice/microphone-test.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";
|
||||
import { parseServerMessage } from "../../../src/shared/server-messages.js";
|
||||
@@ -265,6 +266,7 @@ export function useVoiceWebSocket() {
|
||||
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<void> | null = null;
|
||||
@@ -297,6 +299,14 @@ export function useVoiceWebSocket() {
|
||||
const outputDevices = reactive<AudioOutputDevice[]>([]);
|
||||
const selectedInputDeviceId = ref(typeof localStorage !== "undefined" ? localStorage.getItem("webspeak:input-device") ?? "" : "");
|
||||
const selectedOutputDeviceId = ref(typeof localStorage !== "undefined" ? localStorage.getItem("webspeak:output-device") ?? "" : "");
|
||||
let committedInputDeviceId = selectedInputDeviceId.value;
|
||||
let committedOutputDeviceId = selectedOutputDeviceId.value;
|
||||
let inputDeviceTouched = false;
|
||||
let outputDeviceTouched = false;
|
||||
let inputDeviceGeneration = 0;
|
||||
let outputDeviceGeneration = 0;
|
||||
let deviceListGeneration = 0;
|
||||
const audioSinkRouter = createAudioSinkRouter();
|
||||
const outputDeviceSupported = ref(false);
|
||||
const audioPermission = ref<AudioPermission>("unknown");
|
||||
const microphoneProcessing = reactive<MicrophoneProcessingSettings>({
|
||||
@@ -318,6 +328,8 @@ export function useVoiceWebSocket() {
|
||||
});
|
||||
const microphoneMuted = ref(false);
|
||||
const noiseSuppressionEnabled = ref(true);
|
||||
let noiseSuppressionTouched = false;
|
||||
let committedNoiseSuppressionEnabled = noiseSuppressionEnabled.value;
|
||||
const inputVolume = ref(1);
|
||||
const outputVolume = ref(1);
|
||||
const outputMuted = ref(false);
|
||||
@@ -351,15 +363,15 @@ export function useVoiceWebSocket() {
|
||||
async function saveAudioPreferences(): Promise<void> {
|
||||
await saveLocalPreferences({
|
||||
schemaVersion: 1,
|
||||
preferredInputDeviceId: selectedInputDeviceId.value,
|
||||
inputDeviceId: selectedInputDeviceId.value,
|
||||
preferredInputDeviceId: committedInputDeviceId,
|
||||
inputDeviceId: committedInputDeviceId,
|
||||
microphoneMuted: microphoneMuted.value,
|
||||
noiseSuppressionEnabled: noiseSuppressionEnabled.value,
|
||||
noiseSuppressionEnabled: committedNoiseSuppressionEnabled,
|
||||
voxThreshold: voxThreshold.value,
|
||||
inputGain: inputVolume.value,
|
||||
outputVolume: outputVolume.value,
|
||||
notificationVolume: notificationVolume.value,
|
||||
preferredOutputDeviceId: selectedOutputDeviceId.value,
|
||||
preferredOutputDeviceId: committedOutputDeviceId,
|
||||
volumesByUid: { ...storedVolumesByUid },
|
||||
});
|
||||
}
|
||||
@@ -373,13 +385,22 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
const audioPreferencesReady = loadLocalPreferences().then((preferences) => {
|
||||
if (!selectedInputDeviceId.value) selectedInputDeviceId.value = preferences.preferredInputDeviceId ?? preferences.inputDeviceId ?? "";
|
||||
if (!inputDeviceTouched) {
|
||||
if (!selectedInputDeviceId.value) selectedInputDeviceId.value = preferences.preferredInputDeviceId ?? preferences.inputDeviceId ?? "";
|
||||
committedInputDeviceId = selectedInputDeviceId.value;
|
||||
}
|
||||
if (typeof preferences.microphoneMuted === "boolean") microphoneMuted.value = preferences.microphoneMuted;
|
||||
if (typeof preferences.noiseSuppressionEnabled === "boolean") noiseSuppressionEnabled.value = preferences.noiseSuppressionEnabled;
|
||||
if (!noiseSuppressionTouched && typeof preferences.noiseSuppressionEnabled === "boolean") {
|
||||
noiseSuppressionEnabled.value = preferences.noiseSuppressionEnabled;
|
||||
committedNoiseSuppressionEnabled = preferences.noiseSuppressionEnabled;
|
||||
}
|
||||
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));
|
||||
if (typeof preferences.outputVolume === "number") outputVolume.value = Math.max(0, Math.min(1, preferences.outputVolume));
|
||||
if (!selectedOutputDeviceId.value) selectedOutputDeviceId.value = preferences.preferredOutputDeviceId ?? "";
|
||||
if (!outputDeviceTouched) {
|
||||
if (!selectedOutputDeviceId.value) selectedOutputDeviceId.value = preferences.preferredOutputDeviceId ?? "";
|
||||
committedOutputDeviceId = selectedOutputDeviceId.value;
|
||||
}
|
||||
if (typeof preferences.notificationVolume === "number") notificationVolume.value = clamp(preferences.notificationVolume, 0, 1);
|
||||
Object.assign(storedVolumesByUid, preferences.volumesByUid ?? {});
|
||||
syncKnownMemberVolumes();
|
||||
@@ -487,6 +508,10 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
async function setAudioSink(ctx: SinkAudioContext, deviceId: string): Promise<void> {
|
||||
const generation = outputDeviceGeneration;
|
||||
const output = webrtcOutputElement;
|
||||
const isCurrent = () => generation === outputDeviceGeneration && audioCtx === ctx
|
||||
&& selectedOutputDeviceId.value === deviceId;
|
||||
const mediaSinkSupported = typeof (HTMLMediaElement.prototype as SinkAudioElement).setSinkId === "function";
|
||||
if (!ctx.setSinkId && !mediaSinkSupported) {
|
||||
outputDeviceSupported.value = false;
|
||||
@@ -494,8 +519,8 @@ export function useVoiceWebSocket() {
|
||||
return;
|
||||
}
|
||||
outputDeviceSupported.value = true;
|
||||
if (ctx.setSinkId) await ctx.setSinkId(deviceId || "default");
|
||||
if (webrtcOutputElement?.setSinkId) await webrtcOutputElement.setSinkId(deviceId || "default");
|
||||
if (ctx.setSinkId) await audioSinkRouter.set(ctx, deviceId, isCurrent);
|
||||
if (output?.setSinkId) await audioSinkRouter.set(output, deviceId, () => isCurrent() && output === webrtcOutputElement);
|
||||
}
|
||||
|
||||
function installWebRtcPlaybackRetry(): void {
|
||||
@@ -563,6 +588,9 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
async function refreshAudioDevices(): Promise<void> {
|
||||
const generation = ++deviceListGeneration;
|
||||
const sequence = connectionSequence;
|
||||
const isCurrent = () => generation === deviceListGeneration && sequence === connectionSequence;
|
||||
if (!navigator.mediaDevices?.enumerateDevices) {
|
||||
inputDevices.length = 0;
|
||||
outputDevices.length = 0;
|
||||
@@ -572,8 +600,10 @@ export function useVoiceWebSocket() {
|
||||
let devices: MediaDeviceInfo[];
|
||||
try {
|
||||
devices = await navigator.mediaDevices.enumerateDevices();
|
||||
if (!isCurrent()) return;
|
||||
clearAudioNotice("DEVICE_LIST_UNAVAILABLE");
|
||||
} catch {
|
||||
if (!isCurrent()) return;
|
||||
// enumerateDevices rejects when the device list is blocked (for example in a
|
||||
// locked-down iframe). Use the browser defaults and explain the limitation.
|
||||
inputDevices.length = 0;
|
||||
@@ -590,13 +620,17 @@ export function useVoiceWebSocket() {
|
||||
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);
|
||||
@@ -693,8 +727,11 @@ export function useVoiceWebSocket() {
|
||||
silentGain = ctx.createGain();
|
||||
silentGain.gain.value = 0;
|
||||
|
||||
const captureGeneration = captureGraphGeneration;
|
||||
const handleCaptureChunk = (input: Float32Array, rms?: number): void => {
|
||||
if (generation !== microphoneGeneration) return;
|
||||
// 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;
|
||||
@@ -1044,8 +1081,11 @@ export function useVoiceWebSocket() {
|
||||
document.body.append(output);
|
||||
webrtcOutputElement = output;
|
||||
webrtcPlaybackStream = stream;
|
||||
if (selectedOutputDeviceId.value && output.setSinkId) {
|
||||
void output.setSinkId(selectedOutputDeviceId.value).catch(() => undefined);
|
||||
if (selectedOutputDeviceId.value && typeof output.setSinkId === "function") {
|
||||
const deviceId = selectedOutputDeviceId.value;
|
||||
const generation = outputDeviceGeneration;
|
||||
void audioSinkRouter.set(output, deviceId, () => generation === outputDeviceGeneration
|
||||
&& webrtcOutputElement === output && selectedOutputDeviceId.value === deviceId).catch(() => undefined);
|
||||
}
|
||||
void syncWebRtcPlayback();
|
||||
};
|
||||
@@ -1214,6 +1254,7 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
function stopCaptureGraph(): void {
|
||||
captureGraphGeneration++;
|
||||
accumLen = 0;
|
||||
voxAttack = 0;
|
||||
voxRelease = 0;
|
||||
@@ -1266,22 +1307,35 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
async function setInputDevice(deviceId: string): Promise<void> {
|
||||
const previousDeviceId = selectedInputDeviceId.value;
|
||||
const shouldRestartWebRtc = webrtcActive.value && Boolean(ws.value);
|
||||
inputDeviceTouched = true;
|
||||
selectedInputDeviceId.value = deviceId;
|
||||
localStorage.setItem("webspeak:input-device", deviceId);
|
||||
void saveAudioPreferences();
|
||||
await reconfigureMicrophone();
|
||||
}
|
||||
|
||||
async function reconfigureMicrophone(): Promise<void> {
|
||||
const generation = ++inputDeviceGeneration;
|
||||
deviceListGeneration++;
|
||||
const sequence = connectionSequence;
|
||||
const socket = ws.value;
|
||||
const isCurrent = () => generation === inputDeviceGeneration && sequence === connectionSequence;
|
||||
const shouldRestartWebRtc = webrtcActive.value && Boolean(ws.value);
|
||||
try {
|
||||
if (shouldRestartWebRtc) stopWebRtcTransport();
|
||||
// Keep the current peer alive until the replacement microphone is ready.
|
||||
if (micStream) await startMicrophone();
|
||||
if (shouldRestartWebRtc && ws.value) {
|
||||
stopWebRtcTransport();
|
||||
await startWebRtcTransport(connectionSequence, ws.value);
|
||||
}
|
||||
if (!isCurrent()) return;
|
||||
if (shouldRestartWebRtc && socket) await startWebRtcTransport(sequence, socket);
|
||||
if (!isCurrent()) return;
|
||||
await refreshAudioDevices();
|
||||
if (!isCurrent()) return;
|
||||
committedInputDeviceId = selectedInputDeviceId.value;
|
||||
committedNoiseSuppressionEnabled = noiseSuppressionEnabled.value;
|
||||
localStorage.setItem("webspeak:input-device", committedInputDeviceId);
|
||||
await saveAudioPreferences();
|
||||
} catch (error) {
|
||||
selectedInputDeviceId.value = previousDeviceId;
|
||||
localStorage.setItem("webspeak:input-device", previousDeviceId);
|
||||
if (!isCurrent() || error instanceof CancelledMediaOperation) return;
|
||||
selectedInputDeviceId.value = committedInputDeviceId;
|
||||
noiseSuppressionEnabled.value = committedNoiseSuppressionEnabled;
|
||||
localStorage.setItem("webspeak:input-device", committedInputDeviceId);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1292,21 +1346,35 @@ export function useVoiceWebSocket() {
|
||||
|
||||
function stopMicrophoneTest(): void {
|
||||
microphoneTest.stop();
|
||||
// Closing settings also releases device-preview capture when no recorder
|
||||
// was started. Room capture remains owned by the connected session.
|
||||
if (!state.connected) stopMicrophone();
|
||||
}
|
||||
|
||||
async function setOutputDevice(deviceId: string): Promise<void> {
|
||||
const previousDeviceId = selectedOutputDeviceId.value;
|
||||
if (deviceId && !outputDevices.some((device) => device.deviceId === deviceId)) {
|
||||
throw new Error("所选扬声器当前不可用");
|
||||
}
|
||||
outputDeviceTouched = true;
|
||||
const generation = ++outputDeviceGeneration;
|
||||
deviceListGeneration++;
|
||||
const sequence = connectionSequence;
|
||||
const isCurrent = () => generation === outputDeviceGeneration && sequence === connectionSequence;
|
||||
const previousDeviceId = committedOutputDeviceId;
|
||||
selectedOutputDeviceId.value = deviceId;
|
||||
localStorage.setItem("webspeak:output-device", deviceId);
|
||||
try {
|
||||
await setAudioSink(getAudioCtx(), deviceId);
|
||||
if (!isCurrent()) return;
|
||||
committedOutputDeviceId = deviceId;
|
||||
localStorage.setItem("webspeak:output-device", deviceId);
|
||||
await saveAudioPreferences();
|
||||
} catch (error) {
|
||||
if (!isCurrent()) return;
|
||||
selectedOutputDeviceId.value = previousDeviceId;
|
||||
localStorage.setItem("webspeak:output-device", previousDeviceId);
|
||||
// One endpoint may have changed before the other rejected the request.
|
||||
if (audioCtx) await setAudioSink(audioCtx, previousDeviceId).catch(() => undefined);
|
||||
if (!isCurrent()) return;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1521,6 +1589,12 @@ export function useVoiceWebSocket() {
|
||||
|
||||
/** All ways a session ends release the same owned media and pending work. */
|
||||
function releaseSessionResources(sendScreenStop = false): void {
|
||||
inputDeviceGeneration++;
|
||||
outputDeviceGeneration++;
|
||||
deviceListGeneration++;
|
||||
selectedInputDeviceId.value = committedInputDeviceId;
|
||||
selectedOutputDeviceId.value = committedOutputDeviceId;
|
||||
noiseSuppressionEnabled.value = committedNoiseSuppressionEnabled;
|
||||
microphoneTest.dispose();
|
||||
clearAudioStatusProbes();
|
||||
rejectPendingCommands(new Error("语音连接已关闭"));
|
||||
@@ -2077,14 +2151,10 @@ export function useVoiceWebSocket() {
|
||||
|
||||
async function setNoiseSuppressionEnabled(enabled: boolean): Promise<void> {
|
||||
if (noiseSuppressionEnabled.value === enabled) return;
|
||||
const shouldRestartWebRtc = webrtcActive.value && Boolean(ws.value);
|
||||
noiseSuppressionTouched = true;
|
||||
noiseSuppressionEnabled.value = enabled;
|
||||
void saveAudioPreferences();
|
||||
if (!micStream) return;
|
||||
try {
|
||||
if (shouldRestartWebRtc) stopWebRtcTransport();
|
||||
await startMicrophone();
|
||||
if (shouldRestartWebRtc && ws.value) await startWebRtcTransport(connectionSequence, ws.value);
|
||||
await reconfigureMicrophone();
|
||||
} catch (error) {
|
||||
setMicrophoneError(error);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
interface AudioSink {
|
||||
setSinkId?(deviceId: string): Promise<void>;
|
||||
}
|
||||
|
||||
// Browser sink changes cannot be cancelled once started. Serialize each
|
||||
// endpoint so an older completion cannot leave it on the wrong device.
|
||||
export function createAudioSinkRouter() {
|
||||
const pending = new WeakMap<AudioSink, Promise<void>>();
|
||||
|
||||
function set(sink: AudioSink, deviceId: string, isCurrent: () => boolean): Promise<void> {
|
||||
const previous = pending.get(sink) ?? Promise.resolve();
|
||||
const task = previous.catch(() => {}).then(async () => {
|
||||
if (isCurrent()) await sink.setSinkId?.(deviceId || "default");
|
||||
});
|
||||
pending.set(sink, task);
|
||||
const cleanup = () => { if (pending.get(sink) === task) pending.delete(sink); };
|
||||
void task.then(cleanup, cleanup);
|
||||
return task;
|
||||
}
|
||||
|
||||
return { set };
|
||||
}
|
||||
@@ -73,6 +73,7 @@ function receiveAudio(socket, clientId = 7) {
|
||||
socket.onmessage({ data: new Uint8Array([4, clientId >> 8, clientId & 255, 1, 2, 3]).buffer });
|
||||
}
|
||||
class AudioContextStub extends EventTarget {
|
||||
static instances = [];
|
||||
static processors = [];
|
||||
static sources = [];
|
||||
static gains = [];
|
||||
@@ -80,6 +81,8 @@ class AudioContextStub extends EventTarget {
|
||||
currentTime = 0;
|
||||
sampleRate = 48000;
|
||||
destination = new AudioNodeStub();
|
||||
constructor() { super(); AudioContextStub.instances.push(this); }
|
||||
async setSinkId(id) { this.sinkId = id; }
|
||||
close() { this.state = "closed"; return Promise.resolve(); }
|
||||
createMediaStreamSource() {
|
||||
if (this.state === "closed") throw new Error("Audio context closed");
|
||||
@@ -161,6 +164,7 @@ beforeEach(() => {
|
||||
TestSocket.instances.length = 0;
|
||||
TestPeer.instances.length = 0;
|
||||
AudioContextStub.processors.length = 0;
|
||||
AudioContextStub.instances.length = 0;
|
||||
AudioContextStub.sources.length = 0;
|
||||
AudioContextStub.gains.length = 0;
|
||||
AudioDecoderStub.instances.length = 0;
|
||||
@@ -188,6 +192,8 @@ beforeEach(() => {
|
||||
replaceGlobal("AudioContext", AudioContextStub);
|
||||
replaceGlobal("AudioDecoder", AudioDecoderStub);
|
||||
replaceGlobal("MediaRecorder", RecorderStub);
|
||||
const storage = new Map();
|
||||
replaceGlobal("localStorage", { getItem: key => storage.get(key) ?? null, setItem: (key, value) => storage.set(key, String(value)), removeItem: key => storage.delete(key) });
|
||||
replaceGlobal("EncodedAudioChunk", class { constructor(init) { Object.assign(this, init); } });
|
||||
replaceGlobal("HTMLMediaElement", class {});
|
||||
replaceGlobal("navigator", { mediaDevices: {
|
||||
@@ -739,3 +745,226 @@ test("an asynchronous recorder failure stops capture and reports a microphone er
|
||||
recorder.finish();
|
||||
assert.equal(voice.testAudioUrl.value, "");
|
||||
});
|
||||
|
||||
const availableDevices = [
|
||||
...["mic-a", "mic-b"].map(deviceId => ({ deviceId, kind: "audioinput", label: deviceId, groupId: "" })),
|
||||
...["speaker-a", "speaker-b"].map(deviceId => ({ deviceId, kind: "audiooutput", label: deviceId, groupId: "" })),
|
||||
];
|
||||
|
||||
test("an old input switch failure cannot roll back a newer microphone selection", async () => {
|
||||
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
|
||||
await voice.ensureMicrophone();
|
||||
const permission = deferred();
|
||||
const current = microphoneStream();
|
||||
navigator.mediaDevices.getUserMedia = ({ audio }) => audio.deviceId.exact === "mic-a" ? permission.promise : Promise.resolve(current);
|
||||
const old = voice.setInputDevice("mic-a").catch(() => {});
|
||||
await voice.setInputDevice("mic-b");
|
||||
permission.reject(new Error("Old microphone unavailable"));
|
||||
await old;
|
||||
assert.equal(voice.selectedInputDeviceId.value, "mic-b");
|
||||
assert.equal(localStorage.getItem("webspeak:input-device"), "mic-b");
|
||||
assert.equal(current.track.readyState, "live");
|
||||
});
|
||||
|
||||
test("a failed microphone switch leaves an existing WebRTC peer and capture alive", async () => {
|
||||
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
|
||||
const stream = microphoneStream();
|
||||
navigator.mediaDevices.getUserMedia = async () => stream;
|
||||
const { peer, socket } = await connectWebRtc();
|
||||
navigator.mediaDevices.getUserMedia = async () => { throw new Error("New device unavailable"); };
|
||||
await assert.rejects(voice.setInputDevice("mic-a"), /New device unavailable/);
|
||||
assert.notEqual(peer.connectionState, "closed");
|
||||
receiveAudio(socket);
|
||||
assert.equal(AudioDecoderStub.instances.length, 0, "WebRTC still owns playback");
|
||||
assert.equal(stream.track.readyState, "live");
|
||||
assert.equal(voice.selectedInputDeviceId.value, "");
|
||||
});
|
||||
|
||||
test("an old output switch rejection cannot roll back the latest selection", async t => {
|
||||
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
|
||||
await voice.ensureMicrophone();
|
||||
const ctx = AudioContextStub.instances.at(-1);
|
||||
const oldSink = deferred();
|
||||
t.mock.method(ctx, "setSinkId", id => id === "speaker-a" ? oldSink.promise : Promise.resolve());
|
||||
const old = voice.setOutputDevice("speaker-a").catch(() => {});
|
||||
await nextTurn();
|
||||
const current = voice.setOutputDevice("speaker-b");
|
||||
oldSink.reject(new Error("Old output unavailable"));
|
||||
await Promise.all([old, current]);
|
||||
assert.equal(voice.selectedOutputDeviceId.value, "speaker-b");
|
||||
assert.equal(localStorage.getItem("webspeak:output-device"), "speaker-b");
|
||||
});
|
||||
|
||||
test("overlapping output switches leave the actual sink on the latest device", async t => {
|
||||
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
|
||||
await voice.ensureMicrophone();
|
||||
const ctx = AudioContextStub.instances.at(-1);
|
||||
const oldSink = deferred();
|
||||
t.mock.method(ctx, "setSinkId", async id => { if (id === "speaker-a") await oldSink.promise; ctx.sinkId = id; });
|
||||
const old = voice.setOutputDevice("speaker-a");
|
||||
await nextTurn();
|
||||
const current = voice.setOutputDevice("speaker-b");
|
||||
oldSink.resolve();
|
||||
await Promise.all([old, current]);
|
||||
assert.equal(ctx.sinkId, "speaker-b");
|
||||
assert.equal(voice.selectedOutputDeviceId.value, "speaker-b");
|
||||
});
|
||||
|
||||
test("an older device enumeration cannot replace a newer device list", async () => {
|
||||
const oldDevices = deferred();
|
||||
let calls = 0;
|
||||
navigator.mediaDevices.enumerateDevices = () => ++calls === 1 ? oldDevices.promise : Promise.resolve(availableDevices);
|
||||
const old = voice.refreshAudioDevices();
|
||||
await voice.refreshAudioDevices();
|
||||
oldDevices.resolve([]);
|
||||
await old;
|
||||
assert.deepEqual(voice.inputDevices.map(device => device.deviceId), ["mic-a", "mic-b"]);
|
||||
});
|
||||
|
||||
test("device enumeration rejected after disconnect cannot restore an audio notice", async () => {
|
||||
const devices = deferred();
|
||||
navigator.mediaDevices.enumerateDevices = () => devices.promise;
|
||||
const pending = voice.refreshAudioDevices();
|
||||
voice.disconnect();
|
||||
devices.reject(new Error("Old device query rejected"));
|
||||
await pending;
|
||||
assert.equal(voice.state.audioNoticeCode, "");
|
||||
});
|
||||
|
||||
test("a successful microphone switch replaces the WebRTC peer and persists the new device", async () => {
|
||||
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
|
||||
const initial = microphoneStream();
|
||||
navigator.mediaDevices.getUserMedia = async () => initial;
|
||||
const { peer: old, socket } = await connectWebRtc();
|
||||
const replacement = microphoneStream();
|
||||
navigator.mediaDevices.getUserMedia = async () => replacement;
|
||||
await voice.setInputDevice("mic-b");
|
||||
assert.equal(old.connectionState, "closed");
|
||||
assert.notEqual(TestPeer.instances.at(-1), old);
|
||||
assert.equal(initial.track.readyState, "ended");
|
||||
assert.equal(replacement.track.readyState, "live");
|
||||
assert.equal(socket.messages.filter(message => message.type === "webrtcOffer").length, 2);
|
||||
assert.equal(localStorage.getItem("webspeak:input-device"), "mic-b");
|
||||
});
|
||||
|
||||
test("a failed replacement input restores the last working device instead of another pending choice", async () => {
|
||||
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
|
||||
await voice.ensureMicrophone();
|
||||
const permission = deferred();
|
||||
navigator.mediaDevices.getUserMedia = ({ audio }) => audio.deviceId.exact === "mic-a"
|
||||
? permission.promise : Promise.reject(new Error("Replacement failed"));
|
||||
const old = voice.setInputDevice("mic-a");
|
||||
await assert.rejects(voice.setInputDevice("mic-b"), /Replacement failed/);
|
||||
const late = microphoneStream();
|
||||
permission.resolve(late);
|
||||
await old;
|
||||
assert.equal(voice.selectedInputDeviceId.value, "");
|
||||
assert.equal(localStorage.getItem("webspeak:input-device"), "");
|
||||
assert.equal(late.track.readyState, "ended");
|
||||
});
|
||||
|
||||
test("disconnect skips queued output changes and keeps only the last committed device", async t => {
|
||||
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
|
||||
await voice.ensureMicrophone();
|
||||
const ctx = AudioContextStub.instances.at(-1);
|
||||
const oldSink = deferred();
|
||||
const applied = [];
|
||||
t.mock.method(ctx, "setSinkId", async id => { applied.push(id); await oldSink.promise; });
|
||||
const first = voice.setOutputDevice("speaker-a");
|
||||
await nextTurn();
|
||||
const second = voice.setOutputDevice("speaker-b");
|
||||
voice.disconnect();
|
||||
oldSink.resolve();
|
||||
await Promise.all([first, second]);
|
||||
assert.deepEqual(applied, ["speaker-a"]);
|
||||
assert.equal(voice.selectedOutputDeviceId.value, "");
|
||||
assert.equal(localStorage.getItem("webspeak:output-device"), null);
|
||||
});
|
||||
|
||||
test("failure on the WebRTC output restores the previously committed context sink", async t => {
|
||||
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
|
||||
const { peer } = await connectWebRtc();
|
||||
peer.ontrack({ streams: [microphoneStream()] });
|
||||
const output = [...audioElements][0];
|
||||
output.setSinkId = async id => { if (id === "speaker-a") throw new Error("Output denied"); output.sinkId = id; };
|
||||
const ctx = AudioContextStub.instances.at(-1);
|
||||
await assert.rejects(voice.setOutputDevice("speaker-a"), /Output denied/);
|
||||
assert.equal(ctx.sinkId, "default");
|
||||
assert.equal(output.sinkId, "default");
|
||||
assert.equal(voice.selectedOutputDeviceId.value, "");
|
||||
});
|
||||
|
||||
test("a failed noise suppression change restores its setting and preserves WebRTC capture", async () => {
|
||||
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
|
||||
const initial = microphoneStream();
|
||||
navigator.mediaDevices.getUserMedia = async () => initial;
|
||||
const { peer } = await connectWebRtc();
|
||||
navigator.mediaDevices.getUserMedia = async () => { throw new Error("Capture reconfiguration failed"); };
|
||||
await voice.setNoiseSuppressionEnabled(false);
|
||||
assert.notEqual(peer.connectionState, "closed");
|
||||
assert.equal(voice.noiseSuppressionEnabled.value, true);
|
||||
assert.equal(initial.track.readyState, "live");
|
||||
assert.notEqual(voice.state.microphoneErrorCode, "");
|
||||
});
|
||||
|
||||
test("changing processing during an input switch commits the device actually acquired", async () => {
|
||||
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
|
||||
await voice.ensureMicrophone();
|
||||
const permission = deferred();
|
||||
let calls = 0;
|
||||
navigator.mediaDevices.getUserMedia = () => ++calls === 1 ? permission.promise : Promise.resolve(microphoneStream());
|
||||
const input = voice.setInputDevice("mic-a");
|
||||
await voice.setNoiseSuppressionEnabled(false);
|
||||
const late = microphoneStream();
|
||||
permission.resolve(late);
|
||||
await input;
|
||||
assert.equal(localStorage.getItem("webspeak:input-device"), "mic-a");
|
||||
assert.equal(late.track.readyState, "ended");
|
||||
voice.disconnect();
|
||||
assert.equal(voice.selectedInputDeviceId.value, "mic-a");
|
||||
});
|
||||
|
||||
test("closing audio settings releases standalone capture even without a recording test", async () => {
|
||||
const stream = microphoneStream();
|
||||
navigator.mediaDevices.getUserMedia = async () => stream;
|
||||
await voice.prepareInputDevices();
|
||||
voice.stopMicrophoneTest();
|
||||
assert.equal(stream.track.readyState, "ended");
|
||||
});
|
||||
|
||||
test("compatibility capture keeps sending while a replacement permission is pending or fails", async () => {
|
||||
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1 });
|
||||
await nextTurn();
|
||||
const capture = AudioContextStub.processors.at(-1);
|
||||
const permission = deferred();
|
||||
navigator.mediaDevices.getUserMedia = () => permission.promise;
|
||||
const pending = voice.setInputDevice("mic-a");
|
||||
const rejected = assert.rejects(pending, /Device denied/);
|
||||
const samples = new Float32Array(960).fill(0.25);
|
||||
capture.onaudioprocess({ inputBuffer: { getChannelData: () => samples } });
|
||||
const beforeFailure = socket.messages.filter(message => message instanceof ArrayBuffer).length;
|
||||
permission.reject(new Error("Device denied"));
|
||||
await rejected;
|
||||
capture.onaudioprocess({ inputBuffer: { getChannelData: () => samples } });
|
||||
assert.equal(beforeFailure, 1);
|
||||
assert.equal(socket.messages.filter(message => message instanceof ArrayBuffer).length, 2);
|
||||
});
|
||||
|
||||
test("replacing compatibility capture prevents the old graph from sending into the new session", async () => {
|
||||
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1 });
|
||||
await nextTurn();
|
||||
const old = AudioContextStub.processors.at(-1);
|
||||
await voice.setInputDevice("mic-b");
|
||||
const current = AudioContextStub.processors.at(-1);
|
||||
const event = { inputBuffer: { getChannelData: () => new Float32Array(960).fill(0.25) } };
|
||||
old.onaudioprocess(event);
|
||||
current.onaudioprocess(event);
|
||||
assert.equal(socket.messages.filter(message => message instanceof ArrayBuffer).length, 1);
|
||||
voice.disconnect();
|
||||
current.onaudioprocess(event);
|
||||
assert.equal(socket.messages.filter(message => message instanceof ArrayBuffer).length, 1);
|
||||
});
|
||||
Reference in new issue
Block a user