fix: isolate remote playback and microphone recording lifecycles

This commit is contained in:
illusia committed 2026-10-01 11:16:05 +08:00
1 parent f0712fa3fc
commit 797fc135a9
7 files changed
+621 -199

No files matched your search

+6
View File
@@ -20,6 +20,8 @@ WebSpeak connects browser users to TeamSpeak 3 and TeamSpeak 6 through a self-ho
| `src/relay.ts` and `src/server/acceleration-relay.ts` | Standalone relay and gateway-side relay transport |
| `web/src/views/` and `web/src/composables/` | Vue pages, connection state, audio controls, chat and screen sharing |
| `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/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 |
@@ -50,6 +52,10 @@ Screen sharing has its own peer connections. The gateway coordinates stream memb
Preserve bounded audio buffering and stale-playback recovery. Audio counters stay in memory and are exposed in session diagnostics. Do not add per-frame persistent logging to the voice path.
Remote playback owns each speaker's decoder, gain and source nodes as one resource set. Member departure, decoder failure and session teardown release that set; queued callbacks must not touch its replacement. Preserve the 80 ms playback window and three-frame decoder queue threshold unless audio validation justifies changing them.
Microphone recording tests own their recorder, timeout and object URL, while the capture layer owns the microphone stream. A normal stop may publish its final recording; replacement and session teardown discard late results and revoke the old URL. Stopping a test while connected must preserve room capture. Test cancellation and stale permission failures must not change a newer test's state.
`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
+54 -21
View File
@@ -1,16 +1,16 @@
# WebSpeak 代码待修改清单与修改方向
本文记录 `webspeak-webclient` 的代码边界、待修改事项、修改方向及验收标准。前轮只读核对已经完成;现按“开始施工,直到所有问题修复”的持续目标实施。正文区分已实现和剩余工作,文末保留各批次验证范围。
本文记录 `webspeak-webclient` 的代码边界、待修改事项、修改方向及验收标准。前轮只读梳理已结束,现按“开始施工,直到所有问题修复”的持续目标实施。正文区分已有实现、待验证行为和剩余工作,文末保留各批次验证范围。
当前构建与 CI 入口已经统一,主要共享协议、前端屏幕共享、四个服务端桥接子模块和 Android 启动已经拆出。本批完成 WebRTC 控制契约、管理 API 层、管理文案与样式提取、首页头部及路由延迟加载,并修正页面样式边界。剩余重点是前后端媒体职责拆分、管理功能组件及真实媒体和平台验收。
当前构建与 CI 入口已经统一,共享协议、前端屏幕共享、四个服务端桥接子模块、Android 启动及管理请求层已有实现。本批完成远端播放接入和录音测试控制器,补充行为验证。剩余重点是采集与设备切换、服务端音频转发、页面状态及组件边界,以及真实媒体和平台验收。
## 范围与基线
- 记录日期:2026 年 10 月 1 日。
- 本批起始基线:`dev` 分支,提交 `813896904100dcfbb28a133520c6cf8402b01623`,应用版本 `0.2.5-preview`。
- 本批起始基线:`dev` 分支,提交 `9bfe4b9dcb5834897c78c410b096fe6d45794db2`,应用版本 `0.2.5-preview`。
- 分析对象:当前工作区,包含已有未提交改动,不等同于该提交的干净检出。
- 本批沿用并完成已有共享协议、头部组件和页面拆分改动,没有覆盖或丢弃这些实现。
- 本地 `npm run verify` 通过 130 项测试、后端编译、前端类型检查及生产构建;随后样式和页面错误反馈调整再次通过前端构建及浏览器复测。新提交的远端 CI 结果需单独记录。
- 本批沿用并完成已有远端播放控制器、composable 接入和会话测试,保留前轮只读整理记录。
- 当前工作区 `npm run verify` 通过 149 项测试、后端编译、前端类型检查和生产构建。另已确认提交 `9bfe4b9` 的远端 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,20 +41,35 @@
| 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 构建及模拟器启动通过;真实连接与设备音频待验收 |
| 08 | P1 | 修正文档与实现不一致的说明 | 文档维护 | 本轮更新基线、现状与剩余事项;保留历史验证记录并明确适用范围 |
| 09 | P3 | 整理源码与本地产物边界 | 仓库维护建议 | 忽略规则、说明及代表性源码检查完成;干净构建验证待完成 |
P1 为后续重构的准备工作,P2 为模块整理,P3 为维护便利性改进。大文件行数仅用于定位职责集中处,不作为拆分目标或质量评分。
P1 为优先修正的衔接问题和验证基线,P2 为职责整理及待核验行为,P3 为维护便利性改进。大文件行数仅用于定位职责集中处,不作为拆分目标或质量评分。
## 本轮优先待办
以下保留前轮登记项并更新实施状态。行号来自登记时的快照,后续按函数名定位;未执行的真实媒体和设备验证继续保持待验收。
| 编号 | 优先级与判断 | 位置与依据 | 大致修改方向 | 验收方式 |
| --- | --- | --- | --- | --- |
| 04-A | 已修复,本地验证通过 | 成员离开分支的旧函数引用导致后续成员删除被中断;回归测试先复现失败 | 已接到 `remotePlayback.clear`,成员状态和所属播放资源一起清理 | 类型检查通过;成员退出测试确认仅清理离开者,不影响其他说话者 |
| 04-B | 已实现,本地验证通过;实际听音待验收 | `remote-playback.ts` 约 125 行,集中解码器、源节点、增益节点与队列状态 | 保持 80 ms 播放上限与 3 帧解码排队阈值;旧回调仅处理原资源 | 10 项远端播放及二进制帧用例通过,包括音量、静音、队列恢复和成员隔离;完整构建通过 |
| 04-C | 录音已修复,设备切换仍待核验 | 原录音器、计时器及对象 URL 缺少独立操作身份;输入设备切换的异步回滚仍在核心模块 | 已提取 `microphone-test.ts`;下一步核验设备切换,再整理采集控制器 | 9 项录音用例通过,其中 6 项先失败后修复;设备切换失败、切换期间断开仍需覆盖 |
| 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 的管理请求仍是待核验任务,不将其提前描述为已发生的故障。
## 后续可直接执行的清单
| 顺序 | 待办与依据 | 大致修改方向 | 完成条件 |
| --- | --- | --- | --- |
| 1 | 前端语音核心仍集中采集、播放、协商与连接状态 | 先补解码、录音和设备切换用例,再依次提取远端播放、麦克风与伴奏、WebRTC、连接传输 | 对外接口稳定,断开和重连释放资源,迟到结果不影响新会话 |
| 1 | 远端播放与录音控制器已有验证;语音核心仍集中采集和设备选择 | 补设备切换用例,依次提取麦克风与伴奏、WebRTC、连接传输 | 保持对外接口稳定,断开释放资源,迟到结果不影响新会话 |
| 2 | 服务端桥接仍集中音频转发和 SDK 事件编排 | 提取音频收发和目录事件协调,沿用现有会话状态与清理入口 | 背压、队列上限、重连、目录同步及共享隔离行为保持一致 |
| 3 | 管理网络层已提取,但页面状态和各功能模板仍集中 | 拆分服务器、会话、邀请、皮肤和诊断状态及组件;继续检查迟到请求和页面退出 | 保留已验证的错误反馈、登录失效、CSRF 和凭据更新语义 |
| 4 | 网页客户端仍有较多页面模板 | 沿加入表单、频道树、聊天区、音频设置和弹窗拆分,继续复用已有 composable | 皮肤钩子、语言切换、明暗主题及各尺寸交互保持一致 |
@@ -84,11 +99,11 @@ P1 为后续重构的准备工作,P2 为模块整理,P3 为维护便利性
### 02 补齐会话与媒体关键行为测试
**现状与位置:** 根目录 `test` 脚本显式列出 27 个测试文件,当前 130 项测试通过。本批新增 3 项 WebRTC 契约测试和 9 项管理 API 测试,其中一项通过真实 HTTP 路由和临时 SQLite 数据库验证浏览器请求层。已有桥接与 composable 测试覆盖伴奏取消、协商失效、播放清理和 PCM 回退,Android 启动有 7 项测试。仍缺真实浏览器到 TeamSpeak 的完整连接及 WebRTC 回退验收;模拟媒体边界的测试不能替代真实媒体测试。尚未测量覆盖率。
**现状与位置:** 根目录 `test` 脚本显式列出 27 个测试文件。当前完整验证通过 149 项测试;相对起始提交新增 10 项播放及二进制帧用例、9 项录音用例,实际运行 composable,浏览器媒体边界使用替身。已有共享契约、管理 HTTP 集成、伴奏取消、协商失效、PCM 回退和 Android 启动测试继续通过。仍缺真实浏览器到 TeamSpeak 的完整连接及 WebRTC 回退验收;模拟媒体边界的测试不能替代真实媒体测试。尚未测量覆盖率。
**修改方向:** 优先为即将拆分的模块建立行为基线。覆盖加入凭证过期及重复消费、会话重复清理、目录快照与实时事件合并、重连成功与失败、WebRTC 失败回退、屏幕共享退出后的资源释放。通过可替换的时钟、传输和 SDK 边界验证正常与异常路径;真实 TeamSpeak、浏览器媒体和 Android 行为另设可重复执行的集成验证步骤。
**下一批优先用例:** 在已完成的协商与伴奏回归上,覆盖迟到的二进制音频帧、麦克风测试录音、连续连接后的解码器与播放源清理,以及设备切换。服务端音频需要覆盖慢客户端背压、突发帧和延迟调度时的队列上限。随后补充真实浏览器和 TeamSpeak 的回退及双向语音验证。
**下一批优先用例:** 迟到二进制帧、录音、解码器及播放源清理已补,继续覆盖设备切换。服务端音频需要覆盖慢客户端背压、突发帧和延迟调度时的队列上限。随后补充真实浏览器和 TeamSpeak 的回退及双向语音验证。
**验收标准:** 核心测试能在 CI 中运行;测试能够发现重复消费、重复清理、状态不同步和回退失败等行为回归;需要设备或真实服务的步骤记录环境与结果,不以类型检查或 HTTP 健康检查代替音频验证。
@@ -98,13 +113,13 @@ P1 为后续重构的准备工作,P2 为模块整理,P3 为维护便利性
**修改方向:** 在已有迁移上收尾:逐项核对实际发送字段与接收校验,保留旧客户端的可选字段、数字频道标识和默认值行为;明确未知消息、非法消息及列表中非法条目的处理方式。用真实消息样本补充契约测试,避免只用类型定义生成样本。共享目录保持无 Node.js、DOM 或 Vue 运行时依赖,并验证 Vite 开发服务器、前后端生产构建和 Android 打包都能解析它。后端 `rootDir` 为 `src`,当前放置位置与编译边界相符。
**本批完成:** `src/shared/webrtc.ts` 已统一 offer、stop 的客户端消息模型和 offer、answer 的 SDP 校验;两端均已接入,原有私有解析器已移除。测试覆盖可选字段默认值、非法输入、SDP 长度边界和旧版空字符串行为。`admin-inputs.ts` 与 `admin-responses.ts` 集中管理请求类型和响应投影,设置与概览的服务端返回值使用同一模型。构建和相关测试通过,真实媒体协商仍需联调。
**已提交内容:** `src/shared/webrtc.ts` 已统一 offer、stop 的客户端消息模型和 offer、answer 的 SDP 校验;两端均已接入,原有私有解析器已移除。测试覆盖可选字段默认值、非法输入、SDP 长度边界和旧版空字符串行为。`admin-inputs.ts` 与 `admin-responses.ts` 集中管理请求类型和响应投影,设置与概览的服务端返回值使用同一模型。历史记录载明构建和相关测试通过,真实媒体协商仍需联调。
**验收标准:** 已迁移消息的字段与类型只有一处权威定义;非法消息得到明确处理;现有错误码、请求标识和旧客户端兼容行为不因整理而变化;后端及前端均可独立构建。
### 04 拆分前端语音核心模块
**现状与位置:** [useVoiceWebSocket.ts](../web/src/composables/useVoiceWebSocket.ts) 当前约 2,335 行,屏幕共享已迁至 [screen-share.ts](../web/src/voice/screen-share.ts)。连接、凭证请求、麦克风采集、降噪、播放、WebRTC 语音、伴奏和语音统计仍需进一步拆分。
**现状与位置:** [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 语音、伴奏和统计仍在核心模块中。
**修改方向:** 暂时保留现有 composable 作为页面调用入口,逐项提取连接与命令传输、麦克风处理、远端播放、WebRTC 语音及统计模块,复用已经拆出的屏幕共享控制器。先明确各模块拥有的状态和资源,再移动实现,避免所有模块相互读取同一个大型可变对象。每次只迁移一项职责,并明确初始化、停止和销毁的责任。
@@ -115,12 +130,13 @@ P1 为后续重构的准备工作,P2 为模块整理,P3 为维护便利性
| 连接与命令 | WebSocket、连接代次、请求超时、待响应命令 | 连接、发送、处理确认及取消请求 |
| 麦克风与伴奏 | 音轨、AudioContext、处理节点、设备选择 | 采集、静音、切换设备、停止采集 |
| 远端播放 | 成员解码器、播放队列、音量节点 | 接收音频、更新音量、清理单个成员或全部播放 |
| 录音测试 | 录音器、录音块、五秒计时器和试听 URL | 启动、停止并保留当前录音结果;取消或断开时丢弃迟到结果 |
| WebRTC 语音 | PeerConnection、协商状态、混音及播放资源 | 建立语音通道、失败回退、释放通道 |
| 屏幕共享 | 采集音轨、参与者连接、ICE 配置、共享状态 | 开始、观看、信令处理和退出 |
**已修复的细节:** 旧 WebSocket 消息现在同时校验连接代次、当前 socket 和打开状态;主动断开、异常关闭及服务端断连事件共用资源释放路径。屏幕共享 ICE 配置已改为实例所有,异步协商和统计结果在所属连接失效后不再写回。麦克风授权迟到时释放音轨并取消旧操作,新连接可以独立申请采集。相关问题已通过先失败后通过的回归测试验证;其他音频资源仍需继续检查。
**建议切入顺序:** 伴奏和 WebRTC 的失效检查已经补齐;继续提取远端播放、麦克风及伴奏、WebRTC 语音,最后收拢连接与命令。每个控制器显式拥有其音轨、节点、计时器和取消标识;现有 `releaseSessionResources` 保持统一清理入口。保留已建立的行为断言,并核验尚未覆盖的录音、设备切换和解码器路径。
**建议切入顺序:** 远端播放和录音测试已有控制器及回归,接下来核验设备切换并提取麦克风及伴奏、WebRTC 语音,最后收拢连接与命令。每个控制器显式拥有其音轨、节点、计时器和取消标识;现有 `releaseSessionResources` 保持统一清理入口。录音控制器只拥有录音测试资源,麦克风流仍由采集入口管理,避免停止试听时结束房间内采集。
**验收标准:** 页面调用接口保持兼容,或有范围明确的迁移;连接、断开、重连、设备切换及 WebRTC 回退行为保持一致;音轨、解码器、定时器和事件监听具有明确清理路径,重复连接不会累计资源。
@@ -142,7 +158,7 @@ P1 为后续重构的准备工作,P2 为模块整理,P3 为维护便利性
**修改方向:** 网页客户端按加入表单、频道树、聊天区、音频设置和弹窗等稳定界面边界拆组件;管理页按服务器设置、会话、邀请、皮肤和诊断等功能拆分。将数据请求和业务状态与展示分开,优先复用已有 composable,避免重建一套平行状态。
文案提取和 [main.ts](../web/src/main.ts) 的路由延迟加载已通过构建及页面复测。当前主要 JavaScript 产物为入口约 125 kB、客户端约 279 kB、管理页约 102 kB,构建不再报告单个产物超过 500 kB。此处为构建大小,不是首屏加载性能或运行内存测量。
历史记录载明文案提取和 [main.ts](../web/src/main.ts) 的路由延迟加载通过构建及页面复测。上一批主要 JavaScript 产物为入口约 125 kB、客户端约 279 kB、管理页约 102 kB,没有单个产物超过 500 kB 的构建提示;本轮未重新构建。此处为历史构建大小,不是首屏加载性能或运行内存测量。
**已整理的样式边界:** `main.ts` 按路由设置 `html[data-ws-route]`,客户端和管理页的全局规则均限定到所属路由。浏览器检查确认管理页样式保留在文档后,返回首页时没有管理路由规则命中。首页本身采用内部滚动,因此不能用 `html/body` 的 `overflow:hidden` 单独判断发生了样式污染。管理样式统一提取后,另修正默认皮肤选择框引用未定义变量导致的暗色白底浅字问题,明暗两种配色已复测。
@@ -170,7 +186,7 @@ P1 为后续重构的准备工作,P2 为模块整理,P3 为维护便利性
**现状与位置:** [CLAUDE.md](../CLAUDE.md) 已修正早期 WebQuery、旧配置字段及 32 用户的说明。当前文档与实现对应:通过 SDK 客户端协议获取目录、SQLite 保存主要配置,[constants.ts](../src/constants.ts) 定义的网关会话上限为 100。该上限不代表目标 TeamSpeak 服务器容量或已验证的性能。
**后续方向:** 共享协议及模块拆分落地后,同步架构目录与开发说明;平台构建步骤和功能支持状态同步到对应 README。继续区分 `config.json` 遗留导入、SQLite、浏览器存储和环境变量的用途,并在本清单中及时更新状态,避免正文仍将已完成事项写为待实施。
**后续方向:** 共享协议及模块拆分落地后,同步架构目录与开发说明;平台构建步骤和功能支持状态同步到对应 README。08-A 的头部布局状态差异已修正。继续区分 `config.json` 遗留导入、SQLite、浏览器存储和环境变量的用途,并在本清单中及时更新状态,避免正文仍将已完成事项写为待实施。
**验收标准:** 架构说明能够对应实际入口、配置和协议;不再要求已不使用的 WebQuery 凭证;区分网关代码上限、目标服务器限制及性能验证结果;部署与开发命令和实际脚本一致。
@@ -189,8 +205,9 @@ P1 为后续重构的准备工作,P2 为模块整理,P3 为维护便利性
| 批次 | 内容 | 完成条件 |
| --- | --- | --- |
| 已建立的基线 | 01、08,以及 02 的基础行为测试 | 保留已通过的统一验证入口和文档修正 |
| 已补充的行为基线 | 02 的媒体生命周期、Android 启动、WebRTC 契约和管理 API;09 的代表性路径检查 | 本批 130 项测试及前后端构建通过 |
| 本批页面整理 | 06 的路由样式隔离、头部布局、文案与样式提取和管理 API;03 的 WebRTC 契约 | 已完成本地测试、构建及所述浏览器复测,远端 CI 单独记录 |
| 历史行为基线 | 02 的媒体生命周期、Android 启动、WebRTC 契约和管理 API;09 的代表性路径检查 | 上一批记录为 130 项测试及前后端构建通过,不能覆盖当前未提交内容 |
| 已提交的页面整理 | 06 的路由样式隔离、头部布局、文案与样式提取和管理 API;03 的 WebRTC 契约 | 保留历史验证范围,后续变更重新验证 |
| 本批完成 | 04-A、04-B 的远端播放提取,以及 04-C 的录音测试控制器 | 149 项测试、后端编译、前端类型检查和构建通过;本批远端 CI 单独确认 |
| 随后 | 为 04、05 的剩余媒体职责补行为用例,再分项拆分 | 每次迁移都能验证连接和媒体行为,并独立回退 |
| 页面整理 | 06 的业务状态与剩余组件 | 页面行为、错误反馈、皮肤接口及布局验证通过 |
| 独立工作项 | 真实 TeamSpeak 联调、07 的运行时与设备验收、09 的各平台干净打包 | 记录具体环境、实际结果和未支持能力,不混入结构拆分 |
@@ -199,7 +216,7 @@ P1 为后续重构的准备工作,P2 为模块整理,P3 为维护便利性
## 实施时需要保留的边界
- 当前未提交工作是后续实施的输入;开始修改前重新确认差异,避免覆盖已有 WebRTC 契约、管理文案、头部组件和路由样式改动。
- 开始每批修改前重新确认工作区差异,保留已有工作;新模块纳入同一验证入口,不用历史成功结果替代当前代码验收。
- 纯结构调整保持现有公共 API、错误码、浏览器持久化格式和皮肤接口兼容;确需改变行为时另行说明迁移范围。
- SQLite schema、依赖主版本及新增原生功能按独立变更处理,以便验证和回退。
- 普通代码修改执行相关测试与前后端构建;涉及媒体行为时补充真实连接验证;涉及打包流程时执行对应平台构建。
@@ -207,7 +224,7 @@ P1 为后续重构的准备工作,P2 为模块整理,P3 为维护便利性
## 已有实施与验证记录
以下保留此前实施与验证记录;旧结果仅适用于各自批次,本批结果见末尾。Android 预览及首次清单提交为 `0276b6e`;第一批构建、测试及文档修正记录对应 `5c11bd9`。
以下保留实施与验证记录,段落内“本批”指该批次。旧结果仅适用于各自提交或快照,最新播放及录音验证见末尾。Android 预览及首次清单提交为 `0276b6e`;第一批构建、测试及文档修正记录对应 `5c11bd9`。
| 事项 | 已实施内容 | 验证依据 |
| --- | --- | --- |
@@ -256,8 +273,24 @@ P1 为后续重构的准备工作,P2 为模块整理,P3 为维护便利性
### 共享契约与页面请求层实施记录
- 对应提交 `9bfe4b9`;本批重新查询确认其 [CI](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36808150705) 的应用验证、Docker 构建和健康检查成功。
- 完成 WebRTC 控制契约与 SDP 校验统一,新增 3 项兼容和边界测试。
- 管理输入与响应模型集中到共享目录;新增 8 项请求层用例和 1 项真实 HTTP 集成用例,临时数据库覆盖配置、密码和中继令牌动作、邀请、登录状态及 SQLite 备份。未连接外部 TeamSpeak 服务。
- 管理页文案、样式、网络请求及首页头部独立成模块,路由改为延迟加载。修复头部窄屏分行、长品牌名溢出、状态圆点、管理样式路由限制及暗色选择框。
- 本地 130 项测试、后端编译、前端类型检查和生产构建通过。最后的样式与错误反馈调整再次通过前端构建;浏览器用隔离的本机测试数据验证保存失败和成功、登录过期、退出失败以及管理页面展示。
- 本批没有重做真实语音、Android 设备和跨平台发布包验收,也没有完成 04、05 和 06 的所有剩余拆分。持续目标保持未完成。
- 该批没有重做真实语音、Android 设备和跨平台发布包验收,也没有完成 04、05 和 06 的所有剩余拆分。
### 前轮只读梳理补充记录
- 核对 Git 状态、主要模块、测试定义、构建与发布工作流,以及现有文档;更新本文的基线、待办、修改方向与验收要求。
- 记录远端播放迁移的旧函数引用,补充录音、设备切换、管理请求竞态、剩余文案及平台文档状态等待办。
- 仅更新本文;未修改业务代码、测试、配置或依赖,未运行测试与构建,未提交或推送。已有未提交源码继续保留。
### 远端播放与录音测试实施记录
- 远端播放控制器统一拥有每位成员的解码器、播放源、增益节点和排队时间;重置、失败和成员退出都释放所属资源,旧回调不能清理替代资源。
- 修复提取过程中遗漏的成员退出调用点。该用例先复现成员无法移除,修复后验证只停止离开者的音频。
- 录音测试独立管理操作身份、录音器、五秒期限与试听 URL。六项录音问题先复现失败后修复:断开未停止、连续启动未停止旧录音、旧权限错误清除新状态、取消后仍创建录音器、自然结束仍显示活动,以及启动失败遗留采集。
- 相对起始提交新增 19 项测试。当前 149 项测试、后端编译、前端类型检查和生产构建通过;录音与解码使用浏览器边界替身,未声称真实音质或设备兼容性已通过。
- 输入输出设备切换、管理请求竞态、剩余模块提取、真实 TeamSpeak、Android 真机与各平台发布包仍待完成,持续目标保持未完成。
+1 -1
View File
@@ -39,4 +39,4 @@ Gradle writes one APK per supported CPU architecture under `web/android/app/buil
On October 1, 2026, the platform startup tests passed as part of 118 application tests. Backend compilation, frontend type checking, Vite production build, asset packaging, Capacitor sync and `assembleDebug` passed. Gradle produced arm64-v8a, armeabi-v7a and x86_64 debug APKs.
The x86_64 APK installed and cold-started in a read-only Android 15 emulator. The embedded gateway returned `webspeak-android` from `/health` and `mobile: true` from `/api/public-config`; a screenshot confirmed that the WebView reached the join homepage. The narrow header still needs a layout correction, tracked in the code refactoring plan. This checks startup and rendering only; real TeamSpeak connectivity, two-way audio and physical-device behavior remain unverified.
The x86_64 APK installed and cold-started in a read-only Android 15 emulator. The embedded gateway returned `webspeak-android` from `/health` and `mobile: true` from `/api/public-config`; a screenshot confirmed that the WebView reached the join homepage. The narrow header was subsequently corrected and checked in desktop responsive viewports; an APK rebuild and Android layout check for that change remain pending. This checks startup and rendering only; real TeamSpeak connectivity, two-way audio and physical-device behavior remain unverified.
+23 -175
View File
@@ -1,3 +1,5 @@
import { createRemotePlayback } from "../voice/remote-playback.js";
import { createMicrophoneTest } from "../voice/microphone-test.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";
@@ -307,8 +309,13 @@ export function useVoiceWebSocket() {
const micLevel = ref(0);
const microphoneTestActive = ref(false);
const testAudioUrl = ref("");
let testRecorder: MediaRecorder | null = null;
let testRecorderTimer: ReturnType<typeof setTimeout> | null = null;
const microphoneTest = createMicrophoneTest({
prepare: async () => { await prepareInputDevices(); return micStream; },
onActive: active => { microphoneTestActive.value = active; },
onUrl: url => { testAudioUrl.value = url; },
onStopped: () => { if (!state.connected) stopMicrophone(); },
onError: error => { setMicrophoneError(error); },
});
const microphoneMuted = ref(false);
const noiseSuppressionEnabled = ref(true);
const inputVolume = ref(1);
@@ -324,15 +331,6 @@ export function useVoiceWebSocket() {
let accumBuf = new Int16Array(2048);
let accumLen = 0;
// Playback is kept per client so frames from multiple speakers cannot
// interleave into one decoder or one scheduling queue.
const remoteDecoders = new Map<number, AudioDecoder>();
const remoteDecoderGenerations = new Map<number, number>();
let nextRemoteDecoderGeneration = 0;
const remotePlayTimes = new Map<number, number>();
const remotePlaybackSources = new Map<number, Set<AudioBufferSourceNode>>();
const remoteGains = new Map<number, GainNode>();
const remoteDecodeTimestamps = new Map<number, number>();
const volumes = reactive<Record<number, number>>({});
const speakingIds = reactive(new Set<number>());
const whisperTargetIds = reactive(new Set<number>());
@@ -343,11 +341,12 @@ export function useVoiceWebSocket() {
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
const MAX_AUDIO_BUFFERED_FRAMES = 10;
const MAX_AUDIO_BUFFERED_BYTES = AUDIO_FRAME_BYTES * MAX_AUDIO_BUFFERED_FRAMES;
// Keep the WebSocket playback buffer below the 100 ms latency target. A
// 20 ms frame plus three queued decoder frames leaves only a short cushion
// for jitter; stale audio is discarded instead of being played late.
const MAX_REMOTE_PLAY_AHEAD_SECONDS = 0.08;
const MAX_REMOTE_DECODE_QUEUE_FRAMES = 3;
const remotePlayback = createRemotePlayback({
getContext: getAudioCtx,
getVolume: clientId => (volumes[clientId] ?? 1) * effectiveOutputVolume(),
onDecodeError: () => { fallbackAudioDecodeErrors++; },
onDrop: () => { fallbackAudioFramesDropped++; },
});
async function saveAudioPreferences(): Promise<void> {
await saveLocalPreferences({
@@ -417,7 +416,7 @@ export function useVoiceWebSocket() {
function applyOutputVolume(): void {
const level = effectiveOutputVolume();
for (const [clientId, gain] of remoteGains) gain.gain.value = (volumes[clientId] ?? 1) * level;
remotePlayback.updateVolumes();
if (webrtcOutputElement) webrtcOutputElement.volume = level;
}
@@ -1288,41 +1287,11 @@ export function useVoiceWebSocket() {
}
async function startMicrophoneTest(): Promise<void> {
microphoneTestActive.value = true;
if (testAudioUrl.value) {
URL.revokeObjectURL(testAudioUrl.value);
testAudioUrl.value = "";
}
try {
await prepareInputDevices();
if (typeof MediaRecorder !== "undefined" && micStream) {
const chunks: Blob[] = [];
const recorder = new MediaRecorder(micStream);
testRecorder = recorder;
recorder.ondataavailable = (event) => {
if (event.data.size) chunks.push(event.data);
};
recorder.onstop = () => {
if (chunks.length) {
testAudioUrl.value = URL.createObjectURL(new Blob(chunks, { type: recorder.mimeType || "audio/webm" }));
}
if (testRecorder === recorder) testRecorder = null;
};
recorder.start();
testRecorderTimer = setTimeout(() => stopMicrophoneTest(), 5_000);
}
} catch (error) {
microphoneTestActive.value = false;
throw error;
}
await microphoneTest.start();
}
function stopMicrophoneTest(): void {
microphoneTestActive.value = false;
if (testRecorderTimer) clearTimeout(testRecorderTimer);
testRecorderTimer = null;
if (testRecorder && testRecorder.state !== "inactive") testRecorder.stop();
if (!state.connected) stopMicrophone();
microphoneTest.stop();
}
async function setOutputDevice(deviceId: string): Promise<void> {
@@ -1371,122 +1340,6 @@ export function useVoiceWebSocket() {
}
}
function playAudioFrame(clientId: number, opusData: Uint8Array): void {
if (opusData.length < 3) {
fallbackAudioFramesDropped++;
return;
}
let decoder = remoteDecoders.get(clientId);
const ctx = getAudioCtx();
const now = ctx.currentTime;
const scheduledUntil = remotePlayTimes.get(clientId) ?? now;
const decodeQueueSize = decoder?.decodeQueueSize ?? 0;
if (
decoder &&
(scheduledUntil > now + MAX_REMOTE_PLAY_AHEAD_SECONDS || decodeQueueSize >= MAX_REMOTE_DECODE_QUEUE_FRAMES)
) {
resetRemotePlayback(clientId);
decoder = undefined;
}
if (!decoder) {
const gainNode = ctx.createGain();
gainNode.gain.value = (volumes[clientId] ?? 1) * effectiveOutputVolume();
gainNode.connect(ctx.destination);
remoteGains.set(clientId, gainNode);
const generation = ++nextRemoteDecoderGeneration;
const nextDecoder = new AudioDecoder({
output: (chunk: AudioData) => {
if (remoteDecoderGenerations.get(clientId) !== generation) {
chunk.close();
return;
}
try {
const { sampleRate, numberOfChannels, numberOfFrames } = chunk;
const buffer = ctx.createBuffer(numberOfChannels, numberOfFrames, sampleRate);
for (let ch = 0; ch < numberOfChannels; ch++) {
const data = new Float32Array(numberOfFrames);
chunk.copyTo(data, { planeIndex: ch, format: "f32-planar" });
buffer.copyToChannel(data, ch);
}
const source = ctx.createBufferSource();
source.buffer = buffer;
source.connect(gainNode);
let sources = remotePlaybackSources.get(clientId);
if (!sources) {
sources = new Set<AudioBufferSourceNode>();
remotePlaybackSources.set(clientId, sources);
}
sources.add(source);
source.addEventListener("ended", () => {
source.disconnect();
sources?.delete(source);
if (sources?.size === 0) remotePlaybackSources.delete(clientId);
}, { once: true });
let playTime = remotePlayTimes.get(clientId) ?? ctx.currentTime;
if (playTime < ctx.currentTime) playTime = ctx.currentTime;
if (playTime + numberOfFrames / sampleRate > ctx.currentTime + MAX_REMOTE_PLAY_AHEAD_SECONDS) {
source.disconnect();
sources.delete(source);
if (sources.size === 0) remotePlaybackSources.delete(clientId);
chunk.close();
resetRemotePlayback(clientId);
return;
}
source.start(playTime);
remotePlayTimes.set(clientId, playTime + numberOfFrames / sampleRate);
} catch {
// A decoder can finish while the audio context is being torn down.
}
chunk.close();
},
error: () => {
if (remoteDecoderGenerations.get(clientId) === generation) {
fallbackAudioDecodeErrors++;
remoteDecoderGenerations.delete(clientId);
remoteDecoders.delete(clientId);
}
},
});
nextDecoder.configure({ codec: "opus", sampleRate: 48000, numberOfChannels: 1 });
decoder = nextDecoder;
remoteDecoderGenerations.set(clientId, generation);
remoteDecoders.set(clientId, decoder);
}
try {
const timestamp = remoteDecodeTimestamps.get(clientId) ?? 0;
decoder.decode(new EncodedAudioChunk({ type: "key", timestamp, duration: 20_000, data: opusData }));
remoteDecodeTimestamps.set(clientId, timestamp + 20_000);
} catch {
fallbackAudioDecodeErrors++;
// Ignore malformed frames; the next valid frame can still be decoded.
}
}
function clearRemotePlayback(clientId: number): void {
const decoder = remoteDecoders.get(clientId);
if (decoder) {
try { decoder.close(); } catch { /* already closed */ }
}
remoteDecoders.delete(clientId);
remoteDecoderGenerations.delete(clientId);
remotePlayTimes.delete(clientId);
remoteDecodeTimestamps.delete(clientId);
const sources = remotePlaybackSources.get(clientId);
if (sources) {
for (const source of sources) {
try { source.stop(); } catch { /* already ended */ }
source.disconnect();
}
remotePlaybackSources.delete(clientId);
}
}
function resetRemotePlayback(clientId: number): void {
clearRemotePlayback(clientId);
}
function connect(target: string, channel: string, nickname: string, serverPassword = "", identity = "", rememberIdentity = false, inviteToken = "", accelerated = false, accelerationRelayId = ""): void {
disconnect(true);
lastConnection = { target, channel, nickname, serverPassword, ...(identity ? { identity } : {}), rememberIdentity, accelerated, accelerationRelayId };
@@ -1668,16 +1521,12 @@ export function useVoiceWebSocket() {
/** All ways a session ends release the same owned media and pending work. */
function releaseSessionResources(sendScreenStop = false): void {
microphoneTest.dispose();
clearAudioStatusProbes();
rejectPendingCommands(new Error("语音连接已关闭"));
screenShare.stopTransport(sendScreenStop);
stopWebRtcTransport();
for (const clientId of new Set([...remoteDecoders.keys(), ...remotePlaybackSources.keys()])) clearRemotePlayback(clientId);
remoteDecoderGenerations.clear();
remotePlayTimes.clear();
remoteDecodeTimestamps.clear();
for (const gain of remoteGains.values()) gain.disconnect();
remoteGains.clear();
remotePlayback.clearAll();
stopMicrophone();
clearSpeakingState();
whisperTargetIds.clear();
@@ -1758,7 +1607,7 @@ export function useVoiceWebSocket() {
case "memberLeave": {
const clientId = Number(msg.id);
clearSpeaking(clientId);
clearRemotePlayback(clientId);
remotePlayback.clear(clientId);
const index = members.findIndex((member) => member.id === clientId);
if (index >= 0) members.splice(index, 1);
break;
@@ -1932,7 +1781,7 @@ export function useVoiceWebSocket() {
if (clientId === state.tsClientId) return;
fallbackAudioFramesReceived++;
markSpeaking(clientId);
playAudioFrame(clientId, data.slice(3));
remotePlayback.play(clientId, data.slice(3));
}
function sendCmd<K extends ClientCommandType>(type: K, payload: ClientCommandPayloads[K], requestId = ""): void {
@@ -2206,8 +2055,7 @@ export function useVoiceWebSocket() {
storedVolumesByUid[member.uid] = normalized;
void saveAudioPreferences();
}
const gain = remoteGains.get(clientId);
if (gain) gain.gain.value = normalized * effectiveOutputVolume();
remotePlayback.updateVolume(clientId);
if (webrtcPeer || webrtcActive.value) sendCmd("setMemberVolume", { clientId, volume: normalized });
}
+107
View File
@@ -0,0 +1,107 @@
interface MicrophoneTestOptions {
prepare(): Promise<MediaStream | null>;
onActive(active: boolean): void;
onUrl(url: string): void;
onStopped(): void;
onError(error: unknown): void;
}
interface Recording {
recorder: MediaRecorder | null;
timer: number | null;
chunks: Blob[];
stopped: boolean;
}
// Capture belongs to the caller. This controller owns only the test operation,
// recorder, deadline and playback URL, including results queued after stop().
export function createMicrophoneTest(options: MicrophoneTestOptions) {
let current: Recording | null = null;
let url = "";
function clearUrl(): void {
if (url) URL.revokeObjectURL(url);
url = "";
options.onUrl("");
}
function finishCapture(recording: Recording): void {
if (recording.timer !== null) window.clearTimeout(recording.timer);
recording.timer = null;
if (recording.stopped) return;
recording.stopped = true;
options.onActive(false);
options.onStopped();
}
function dispose(): void {
const recording = current;
current = null;
if (recording) {
finishCapture(recording);
if (recording.recorder?.state !== "inactive") {
try { recording.recorder?.stop(); } catch { /* already ended */ }
}
recording.chunks.length = 0;
}
clearUrl();
}
function stop(): void {
const recording = current;
if (!recording) return;
// A pending permission or device enumeration must not create a recorder.
if (!recording.recorder) current = null;
finishCapture(recording);
if (recording.recorder?.state !== "inactive") {
try { recording.recorder?.stop(); }
catch (error) { dispose(); options.onError(error); }
}
}
async function start(): Promise<void> {
dispose();
const recording: Recording = { recorder: null, timer: null, chunks: [], stopped: false };
current = recording;
options.onActive(true);
try {
const stream = await options.prepare();
if (current !== recording) return;
// Keep the existing level-meter-only test on browsers without recording.
if (typeof MediaRecorder === "undefined" || !stream) return;
const recorder = new MediaRecorder(stream);
recording.recorder = recorder;
recorder.ondataavailable = event => {
if (current === recording && event.data.size) recording.chunks.push(event.data);
};
recorder.onstop = () => {
if (current !== recording) return;
current = null;
finishCapture(recording);
try {
if (recording.chunks.length) {
clearUrl();
url = URL.createObjectURL(new Blob(recording.chunks, { type: recorder.mimeType || "audio/webm" }));
options.onUrl(url);
}
} catch (error) { options.onError(error); }
recording.chunks.length = 0;
};
recorder.onerror = event => {
if (current !== recording) return;
dispose();
options.onError("error" in event ? event.error : new Error("Microphone recording failed"));
};
recorder.start();
recording.timer = window.setTimeout(() => {
if (current === recording) stop();
}, 5_000);
} catch (error) {
if (current !== recording) return;
dispose();
throw error;
}
}
return { start, stop, dispose };
}
+125
View File
@@ -0,0 +1,125 @@
interface RemotePlaybackOptions {
getContext(): AudioContext;
getVolume(clientId: number): number;
onDecodeError(): void;
onDrop(): void;
}
interface SpeakerPlayback {
context: AudioContext;
decoder: AudioDecoder | null;
gain: GainNode;
sources: Set<AudioBufferSourceNode>;
playTime: number;
timestamp: number;
}
// Preserve the compatibility path's bounded jitter buffer and decoder queue.
const MAX_PLAY_AHEAD_SECONDS = 0.08;
const MAX_DECODE_QUEUE_FRAMES = 3;
export function createRemotePlayback(options: RemotePlaybackOptions) {
const speakers = new Map<number, SpeakerPlayback>();
function clear(clientId: number): void {
const stream = speakers.get(clientId);
if (!stream) return;
// Invalidate callbacks before closing their resources.
speakers.delete(clientId);
try { stream.decoder?.close(); } catch { /* decoder may already be closed */ }
for (const source of stream.sources) {
try { source.stop(); } catch { /* not started or already ended */ }
source.disconnect();
}
stream.sources.clear();
stream.gain.disconnect();
}
function output(clientId: number, stream: SpeakerPlayback, chunk: AudioData): void {
try {
if (speakers.get(clientId) !== stream) return;
const { context, gain, sources } = stream;
const { sampleRate, numberOfChannels, numberOfFrames } = chunk;
const playTime = Math.max(stream.playTime, context.currentTime);
const duration = numberOfFrames / sampleRate;
if (playTime + duration > context.currentTime + MAX_PLAY_AHEAD_SECONDS) {
clear(clientId);
return;
}
const buffer = context.createBuffer(numberOfChannels, numberOfFrames, sampleRate);
for (let channel = 0; channel < numberOfChannels; channel++) {
const samples = new Float32Array(numberOfFrames);
chunk.copyTo(samples, { planeIndex: channel, format: "f32-planar" });
buffer.copyToChannel(samples, channel);
}
const source = context.createBufferSource();
sources.add(source);
source.buffer = buffer;
source.connect(gain);
source.addEventListener("ended", () => {
source.disconnect();
// The old stream owns this set; never delete a replacement's resources.
sources.delete(source);
}, { once: true });
source.start(playTime);
stream.playTime = playTime + duration;
} catch {
if (speakers.get(clientId) === stream) {
options.onDecodeError();
clear(clientId);
}
} finally {
chunk.close();
}
}
function create(clientId: number, context: AudioContext): SpeakerPlayback {
const stream: SpeakerPlayback = {
context, decoder: null, gain: context.createGain(), sources: new Set(),
playTime: context.currentTime, timestamp: 0,
};
speakers.set(clientId, stream);
stream.gain.gain.value = options.getVolume(clientId);
stream.gain.connect(context.destination);
stream.decoder = new AudioDecoder({
output: chunk => output(clientId, stream, chunk),
error: () => {
if (speakers.get(clientId) !== stream) return;
options.onDecodeError();
clear(clientId);
},
});
stream.decoder.configure({ codec: "opus", sampleRate: 48000, numberOfChannels: 1 });
return stream;
}
function play(clientId: number, opusData: Uint8Array): void {
if (opusData.length < 3) { options.onDrop(); return; }
try {
const context = options.getContext();
let stream = speakers.get(clientId);
if (stream && (stream.context !== context || stream.playTime > context.currentTime + MAX_PLAY_AHEAD_SECONDS || (stream.decoder?.decodeQueueSize ?? 0) >= MAX_DECODE_QUEUE_FRAMES)) {
clear(clientId);
stream = undefined;
}
stream ??= create(clientId, context);
if (speakers.get(clientId) !== stream) return;
stream.decoder?.decode(new EncodedAudioChunk({ type: "key", timestamp: stream.timestamp, duration: 20_000, data: opusData }));
stream.timestamp += 20_000;
} catch {
options.onDecodeError();
clear(clientId);
}
}
return {
play,
clear,
clearAll() { for (const id of speakers.keys()) clear(id); },
updateVolume(clientId: number) {
const stream = speakers.get(clientId);
if (stream) stream.gain.gain.value = options.getVolume(clientId);
},
updateVolumes() { for (const [id, stream] of speakers) stream.gain.gain.value = options.getVolume(id); },
};
}
+305 -2
View File
@@ -32,12 +32,52 @@ class TestTrack extends EventTarget {
class AudioNodeStub {
gain = { value: 1 };
disconnects = 0;
connect() {}
disconnect() {}
disconnect() { this.disconnects++; }
}
class AudioSourceStub extends EventTarget {
static failStart = false;
stopped = 0;
disconnects = 0;
connect() {}
disconnect() { this.disconnects++; }
start(time) { if (AudioSourceStub.failStart) throw new Error("Source cannot start"); this.startedAt = time; }
stop() { this.stopped++; }
}
class AudioDecoderStub {
static instances = [];
static failConfigure = false;
decodeQueueSize = 0;
closed = 0;
constructor(callbacks) { this.callbacks = callbacks; AudioDecoderStub.instances.push(this); }
configure() { if (AudioDecoderStub.failConfigure) throw new Error("Codec unavailable"); }
decode(chunk) { this.lastChunk = chunk; }
close() { this.closed++; }
}
class RecorderStub {
static instances = [];
static failStart = false;
state = "inactive";
mimeType = "audio/webm";
stops = 0;
constructor(stream) { this.stream = stream; RecorderStub.instances.push(this); }
start() { if (RecorderStub.failStart) throw new Error("Recorder start failed"); this.state = "recording"; }
stop() { this.stops++; this.state = "inactive"; }
finish() { this.state = "inactive"; this.ondataavailable?.({ data: new Blob(["audio"]) }); this.onstop?.(); }
}
function decodedChunk() {
return { sampleRate: 48000, numberOfChannels: 1, numberOfFrames: 960, closed: 0, copyTo() {}, close() { this.closed++; } };
}
function receiveAudio(socket, clientId = 7) {
socket.onmessage({ data: new Uint8Array([4, clientId >> 8, clientId & 255, 1, 2, 3]).buffer });
}
class AudioContextStub extends EventTarget {
static processors = [];
static sources = [];
static gains = [];
state = "running";
currentTime = 0;
sampleRate = 48000;
destination = new AudioNodeStub();
close() { this.state = "closed"; return Promise.resolve(); }
@@ -46,7 +86,9 @@ class AudioContextStub extends EventTarget {
return new AudioNodeStub();
}
createMediaStreamDestination() { return Object.assign(new AudioNodeStub(), { stream: microphoneStream() }); }
createGain() { return new AudioNodeStub(); }
createGain() { const node = new AudioNodeStub(); AudioContextStub.gains.push(node); return node; }
createBuffer(channels, frames, sampleRate) { return { duration: frames / sampleRate, copyToChannel() {} }; }
createBufferSource() { const node = new AudioSourceStub(); AudioContextStub.sources.push(node); return node; }
createScriptProcessor() { const node = new AudioNodeStub(); AudioContextStub.processors.push(node); return node; }
}
function microphoneStream() {
@@ -119,6 +161,13 @@ beforeEach(() => {
TestSocket.instances.length = 0;
TestPeer.instances.length = 0;
AudioContextStub.processors.length = 0;
AudioContextStub.sources.length = 0;
AudioContextStub.gains.length = 0;
AudioDecoderStub.instances.length = 0;
AudioDecoderStub.failConfigure = false;
AudioSourceStub.failStart = false;
RecorderStub.instances.length = 0;
RecorderStub.failStart = false;
audioElements.clear();
replaceGlobal("RTCPeerConnection", TestPeer);
replaceGlobal("window", Object.assign(new EventTarget(), {
@@ -137,6 +186,9 @@ beforeEach(() => {
replaceGlobal("location", { protocol: "https:", host: "gateway.example" });
replaceGlobal("fetch", async () => ({ ok: true, json: async () => ({ ticket: "test-ticket" }) }));
replaceGlobal("AudioContext", AudioContextStub);
replaceGlobal("AudioDecoder", AudioDecoderStub);
replaceGlobal("MediaRecorder", RecorderStub);
replaceGlobal("EncodedAudioChunk", class { constructor(init) { Object.assign(this, init); } });
replaceGlobal("HTMLMediaElement", class {});
replaceGlobal("navigator", { mediaDevices: {
getDisplayMedia: async () => displayStream(),
@@ -147,6 +199,7 @@ beforeEach(() => {
});
afterEach(() => {
voice?.stopMicrophoneTest();
voice?.disconnect();
for (const timer of browserTimers) clearTimeout(timer);
browserTimers.clear();
@@ -436,3 +489,253 @@ test("an offer rejected after a new connection opens cannot report a microphone
assert.equal(voice.state.microphoneErrorCode, "");
assert.equal(voice.state.audioNoticeCode, "");
});
test("resetting an overloaded remote decoder disconnects its old gain", async () => {
const socket = await connect();
receiveAudio(socket);
const gain = AudioContextStub.gains.at(-1);
AudioDecoderStub.instances.at(-1).decodeQueueSize = 3;
receiveAudio(socket);
assert.equal(gain.disconnects, 1);
assert.equal(AudioDecoderStub.instances.length, 2);
});
test("an old source ending cannot hide replacement playback from session cleanup", async () => {
const socket = await connect();
receiveAudio(socket);
const first = AudioDecoderStub.instances.at(-1);
first.callbacks.output(decodedChunk());
const oldSource = AudioContextStub.sources.at(-1);
first.decodeQueueSize = 3;
receiveAudio(socket);
AudioDecoderStub.instances.at(-1).callbacks.output(decodedChunk());
const replacement = AudioContextStub.sources.at(-1);
oldSource.dispatchEvent(new Event("ended"));
voice.disconnect();
assert.equal(replacement.stopped, 1);
});
test("decoder failure releases the speaker's queued sources and gain immediately", async () => {
const socket = await connect();
receiveAudio(socket);
const decoder = AudioDecoderStub.instances.at(-1);
decoder.callbacks.output(decodedChunk());
const source = AudioContextStub.sources.at(-1);
const gain = AudioContextStub.gains.at(-1);
decoder.callbacks.error(new Error("Decode failed"));
assert.equal(source.stopped, 1);
assert.equal(gain.disconnects, 1);
});
test("codec configuration failure is contained and releases the partially created stream", async () => {
const socket = await connect();
AudioDecoderStub.failConfigure = true;
assert.doesNotThrow(() => receiveAudio(socket));
assert.equal(AudioDecoderStub.instances.at(-1).closed, 1);
assert.equal(AudioContextStub.gains.at(-1).disconnects, 1);
AudioDecoderStub.failConfigure = false;
receiveAudio(socket);
assert.equal(AudioDecoderStub.instances.length, 2);
});
test("a failed audio source start does not retain a connected playback node", async () => {
const socket = await connect();
receiveAudio(socket);
AudioSourceStub.failStart = true;
const chunk = decodedChunk();
AudioDecoderStub.instances.at(-1).callbacks.output(chunk);
assert.ok(AudioContextStub.sources.at(-1).disconnects > 0);
assert.equal(chunk.closed, 1);
});
test("late decoded chunks after disconnect close without creating playback", async () => {
const socket = await connect();
receiveAudio(socket);
const old = AudioDecoderStub.instances.at(-1);
voice.disconnect();
const chunk = decodedChunk();
old.callbacks.output(chunk);
assert.equal(chunk.closed, 1);
assert.equal(AudioContextStub.sources.length, 0);
});
test("a departing speaker releases only its own playback", async () => {
const socket = await connect();
socket.receive({ type: "memberEnter", id: 7, nickname: "Leaving" });
socket.receive({ type: "memberEnter", id: 8, nickname: "Staying" });
receiveAudio(socket, 7);
receiveAudio(socket, 8);
const [leaving, staying] = AudioDecoderStub.instances;
leaving.callbacks.output(decodedChunk());
staying.callbacks.output(decodedChunk());
const [oldSource, currentSource] = AudioContextStub.sources;
socket.receive({ type: "memberLeave", id: 7 });
assert.deepEqual(voice.members.map(member => member.id), [8]);
assert.equal(leaving.closed, 1);
assert.equal(oldSource.stopped, 1);
assert.equal(staying.closed, 0);
assert.equal(currentSource.stopped, 0);
});
test("remote playback preserves member volume through output mute and decoder reset", async () => {
const socket = await connect();
voice.setVolume(7, 0.4);
voice.setOutputVolume(0.5);
receiveAudio(socket, 7);
receiveAudio(socket, 8);
assert.deepEqual(AudioContextStub.gains.map(node => node.gain.value), [0.2, 0.5]);
voice.toggleOutputMute();
assert.deepEqual(AudioContextStub.gains.map(node => node.gain.value), [0, 0]);
const old = AudioDecoderStub.instances[0];
old.decodeQueueSize = 3;
receiveAudio(socket, 7);
const replacement = AudioDecoderStub.instances.at(-1);
old.callbacks.error(new Error("stale decoder error"));
assert.equal(replacement.closed, 0);
assert.equal(AudioContextStub.gains.at(-1).gain.value, 0);
voice.toggleOutputMute();
assert.equal(AudioContextStub.gains.at(-1).gain.value, 0.2);
assert.equal(AudioContextStub.gains[1].gain.value, 0.5);
});
test("decoded audio stays within the 80 ms playback window and recovers after overflow", async () => {
const socket = await connect();
receiveAudio(socket);
const decoder = AudioDecoderStub.instances[0];
const chunks = Array.from({ length: 5 }, decodedChunk);
for (const chunk of chunks) decoder.callbacks.output(chunk);
assert.deepEqual(AudioContextStub.sources.map(source => source.startedAt), [0, 0.02, 0.04, 0.06]);
assert.equal(decoder.closed, 1);
assert.ok(AudioContextStub.sources.every(source => source.stopped === 1));
assert.ok(chunks.every(chunk => chunk.closed === 1));
receiveAudio(socket);
const replacement = AudioDecoderStub.instances.at(-1);
replacement.callbacks.output(decodedChunk());
assert.notEqual(replacement, decoder);
assert.equal(AudioContextStub.sources.at(-1).startedAt, 0);
});
test("old socket audio cannot create a decoder in a replacement session", async () => {
const old = await connect();
const current = await connect();
receiveAudio(old);
assert.equal(AudioDecoderStub.instances.length, 0);
receiveAudio(current);
assert.equal(AudioDecoderStub.instances.length, 1);
});
test("disconnect stops a microphone test and discards its late recording", async () => {
await voice.startMicrophoneTest();
const recorder = RecorderStub.instances.at(-1);
voice.disconnect();
assert.equal(recorder.stops, 1);
assert.equal(voice.microphoneTestActive.value, false);
recorder.finish();
assert.equal(voice.testAudioUrl.value, "");
});
test("a replacement microphone test stops the old recorder and ignores its late result", async t => {
const created = [];
t.mock.method(URL, "createObjectURL", blob => { created.push(blob); return `blob:test-${created.length}`; });
t.mock.method(URL, "revokeObjectURL", () => {});
await voice.startMicrophoneTest();
const old = RecorderStub.instances.at(-1);
await voice.startMicrophoneTest();
const current = RecorderStub.instances.at(-1);
assert.equal(old.stops, 1);
current.finish();
const currentUrl = voice.testAudioUrl.value;
old.finish();
assert.equal(voice.testAudioUrl.value, currentUrl);
assert.equal(created.length, 1);
});
test("an old microphone test permission failure cannot stop a new recording", async () => {
const oldPermission = deferred();
let requests = 0;
navigator.mediaDevices.getUserMedia = () => ++requests === 1 ? oldPermission.promise : Promise.resolve(microphoneStream());
const old = voice.startMicrophoneTest().catch(() => {});
voice.stopMicrophoneTest();
await voice.startMicrophoneTest();
oldPermission.reject(new Error("Old permission failed"));
await old;
assert.equal(voice.microphoneTestActive.value, true);
assert.equal(RecorderStub.instances.at(-1).state, "recording");
});
test("stopping a microphone test while devices refresh prevents recorder creation", async () => {
const socket = await connect();
socket.receive({ type: "connected", tsClientId: 1 });
await nextTurn();
const refresh = deferred();
navigator.mediaDevices.enumerateDevices = () => refresh.promise;
const pending = voice.startMicrophoneTest();
voice.stopMicrophoneTest();
refresh.resolve([]);
await pending;
assert.equal(RecorderStub.instances.length, 0);
assert.equal(voice.microphoneTestActive.value, false);
});
test("a naturally finished microphone recording clears active state and standalone capture", async t => {
const revoked = [];
t.mock.method(URL, "createObjectURL", () => "blob:finished");
t.mock.method(URL, "revokeObjectURL", url => revoked.push(url));
await voice.startMicrophoneTest();
const recorder = RecorderStub.instances.at(-1);
recorder.finish();
assert.equal(voice.microphoneTestActive.value, false);
assert.equal(recorder.stream.track.readyState, "ended");
assert.equal(voice.testAudioUrl.value, "blob:finished");
voice.disconnect();
assert.deepEqual(revoked, ["blob:finished"]);
assert.equal(voice.testAudioUrl.value, "");
});
test("recorder startup failure releases standalone microphone capture", async () => {
RecorderStub.failStart = true;
await assert.rejects(voice.startMicrophoneTest(), /Recorder start failed/);
assert.equal(voice.microphoneTestActive.value, false);
assert.equal(RecorderStub.instances.at(-1).stream.track.readyState, "ended");
});
test("stopping a connected microphone test publishes its recording without stopping room capture", async t => {
t.mock.method(URL, "createObjectURL", () => "blob:connected");
t.mock.method(URL, "revokeObjectURL", () => {});
const socket = await connect();
socket.receive({ type: "connected", tsClientId: 1 });
await nextTurn();
await voice.startMicrophoneTest();
const recorder = RecorderStub.instances.at(-1);
voice.stopMicrophoneTest();
recorder.finish();
assert.equal(voice.testAudioUrl.value, "blob:connected");
assert.equal(recorder.stream.track.readyState, "live");
assert.equal(voice.state.connected, true);
});
test("the microphone test deadline stops recording and is removed on completion", async t => {
let deadline;
const cleared = [];
t.mock.method(window, "setTimeout", (callback, delay) => { assert.equal(delay, 5_000); deadline = callback; return 123; });
t.mock.method(window, "clearTimeout", timer => cleared.push(timer));
await voice.startMicrophoneTest();
const recorder = RecorderStub.instances.at(-1);
deadline();
assert.equal(recorder.stops, 1);
assert.equal(voice.microphoneTestActive.value, false);
assert.deepEqual(cleared, [123]);
});
test("an asynchronous recorder failure stops capture and reports a microphone error", async () => {
await voice.startMicrophoneTest();
const recorder = RecorderStub.instances.at(-1);
recorder.onerror({ error: new Error("Recorder failed") });
assert.equal(recorder.stops, 1);
assert.equal(recorder.stream.track.readyState, "ended");
assert.equal(voice.microphoneTestActive.value, false);
assert.notEqual(voice.state.microphoneErrorCode, "");
recorder.finish();
assert.equal(voice.testAudioUrl.value, "");
});