mirror of
https://github.com/motajs/template.git
synced 2026-12-01 11:14:30 +08:00
feat: 音频包补齐 Vorbis 与格式探测并接入解码器注册表
This commit is contained in:
1 parent
928903b497
commit
72599d465b
12 files changed
+2812
-58
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,226 @@
|
||||
---
|
||||
phase: 09-minimum-browser-runnable
|
||||
plan: 65
|
||||
subsystem: audio
|
||||
tags: [audio, probe, vorbis, opus, decoder-registry, tests]
|
||||
status: complete
|
||||
requires:
|
||||
- 09-64
|
||||
provides:
|
||||
- 七容器格式探测(MP4 / WebM / Ogg / Wav / Flac / Mp3 / Adts)
|
||||
- toAudioContainer 与 readDuration(头部优先时长)
|
||||
- Ogg Vorbis 整文件解码会话 createVorbisDecodeSession
|
||||
- OpusCodecDecoder 与注入式 OpusDecodeSession
|
||||
- 可被 MotaAudioContext 委托的 AudioDecoderRegistry
|
||||
affects:
|
||||
- packages/audio/src/probe.ts
|
||||
- packages/audio/src/opusSession.ts
|
||||
- packages/audio/src/context.ts
|
||||
- packages/audio/src/types.ts
|
||||
tech-stack:
|
||||
added: []
|
||||
patterns:
|
||||
- 探测格式与会话格式共用同一份格式表
|
||||
- 编码解码器经注册表注入
|
||||
- 注册表逻辑抽成 Node 可测类
|
||||
key-files:
|
||||
created:
|
||||
- packages/audio/src/vorbisSession.ts
|
||||
- packages/audio/src/decoderRegistry.ts
|
||||
- packages/audio/src/__test__/vorbisDecodeSession.test.ts
|
||||
- packages/audio/src/__test__/probeAudioFormats.test.ts
|
||||
- packages/audio/src/__test__/decoderRegistry.test.ts
|
||||
modified:
|
||||
- packages/audio/src/types.ts
|
||||
- packages/audio/src/probe.ts
|
||||
- packages/audio/src/opusSession.ts
|
||||
- packages/audio/src/context.ts
|
||||
- packages/audio/src/__test__/opusDecodeSession.test.ts
|
||||
decisions:
|
||||
- 探测格式表扩到七个容器,不加入 MATROSKA
|
||||
- 时长先取头部,只有 Ogg / WebM 才整文件扫描
|
||||
- Vorbis 走容器级整文件会话,唯一一处 try / catch 只包 decodeFile
|
||||
- Opus 解码器抽成 OpusCodecDecoder,由注册表注入会话
|
||||
- 注册表逻辑抽成 AudioDecoderRegistry,Node 可直接测试
|
||||
metrics:
|
||||
tasks: 3
|
||||
files: 10
|
||||
duration: 约 10 分钟
|
||||
completed: 2026-11-26
|
||||
actuals:
|
||||
tokens: 7544
|
||||
tasks: 3
|
||||
commits: 0
|
||||
---
|
||||
|
||||
# Phase 09 Plan 65: 补齐音频格式覆盖并接通解码器注册表 Summary
|
||||
|
||||
探测从 2 种容器扩到 7 种并按容器区分时长代价,新增 Ogg Vorbis 整文件会话,Opus 解码器抽成 `OpusCodecDecoder` 经注册表注入会话,并用 mediabunny 现场把 `bgm.opus` 转封装成 WebM 验证 WebM 解码路径。
|
||||
|
||||
## 问题
|
||||
|
||||
1. 探测只认 Ogg / WebM,MP3 / WAV / FLAC / ADTS / MP4 一律探测为 `null`,`IAudioFormatInfo` 对原生格式不可用。
|
||||
2. 时长无条件 `computeDuration()`,MP3 / ADTS 这类没有头部时长的容器等于整文件扫描。
|
||||
3. 浏览器原生不支持 Ogg Vorbis(Safari)时没有 `IAudioDecodeSession` 实现,只能落回 legacy。
|
||||
4. WebM / Opus 分支只有 Ogg fixture,从未被实际跑过。
|
||||
5. 09-60 声明的 `IAudioDecoderRegistry` / `IAudioCodecDecoder` / `AudioCodecDecoderCreateFunc` 没有实现,是死代码。
|
||||
|
||||
## 格式矩阵
|
||||
|
||||
| 容器 | 编码 | `AudioContainer` | `AudioCodec` | 时长来源 | `createDecodeSession` |
|
||||
|------|------|------------------|--------------|----------|------------------------|
|
||||
| Ogg | Opus | `Ogg` | `Opus` | `computeDuration`(头部无) | `OpusCodecDecoder` + `createOpusDecodeSession` |
|
||||
| WebM | Opus | `WebM` | `Opus` | 头部优先,缺失才扫描 | `OpusCodecDecoder` + `createOpusDecodeSession` |
|
||||
| Ogg | Vorbis | `Ogg` | `Vorbis` | `computeDuration`(头部无) | `createVorbisDecodeSession` |
|
||||
| MP4 | AAC | `Mp4` | `Aac` | 头部 | `null` 继续原生 / legacy |
|
||||
| WAVE | PCM | `Wav` | `Pcm` | 头部 | `null` 继续原生 / legacy |
|
||||
| FLAC | FLAC | `Flac` | `Flac` | 头部 | `null` 继续原生 / legacy |
|
||||
| MP3 | MP3 | `Mp3` | `Mp3` | 头部(有 Xing / ID3) | `null` 继续原生 / legacy |
|
||||
| ADTS | AAC | `Adts` | `Aac` | 头部缺失时 `null`,不扫描 | `null` 继续原生 / legacy |
|
||||
| 其它 | 任意 | `Unknown` | 无 | 无 | `logger.error(97)` + `null` |
|
||||
|
||||
MATROSKA 不在范围(`.mka` 超出本计划)。`mediaFormats` 恰为 `[MP4, WEBM, OGG, WAVE, FLAC, MP3, ADTS]`,`toAudioCodec` 的既有映射逐字未动。
|
||||
|
||||
## 新增命名
|
||||
|
||||
### B. probe.ts
|
||||
|
||||
| 名称 | 可见性 | 说明 |
|
||||
|------|--------|------|
|
||||
| `mediaFormats` | 模块常量 | 7 项容器表 |
|
||||
| `toAudioContainer` | 模块私有函数(新增) | `(format: InputFormat): AudioContainer`,未命中返回 `Unknown` |
|
||||
| `readDuration` | 模块私有函数(新增) | `(input: Input, container: AudioContainer): Promise<number | null>` |
|
||||
|
||||
`createMediaSource` / `createMediaInput` / `toAudioCodec` / `probeAudioSource` 签名不变。
|
||||
|
||||
### C. vorbisSession.ts
|
||||
|
||||
| 名称 | 可见性 | 说明 |
|
||||
|------|--------|------|
|
||||
| `IVorbisDecodedAudio` | 非导出 interface | `channelData` / `samplesDecoded` / `sampleRate` / `errors` |
|
||||
| `IVorbisDecoderInstance` | 非导出 interface | `ready` / `decodeFile` / `free` |
|
||||
| `IVorbisDecoderModule` | 非导出 interface | 两个构造签名 |
|
||||
| `vorbisModule` | 模块级 let | 缓存已加载模块 |
|
||||
| `readSourceBytes` | 模块私有函数 | 读取全部字节,不支持的输入返回 null |
|
||||
| `loadVorbisDecoder` | 模块私有函数 | 动态加载,Node 主线程 / 浏览器 Worker |
|
||||
| `VorbisDecodeSession` | export class | `implements IAudioDecodeSession` |
|
||||
| `createVorbisDecodeSession` | export async function | 返回 `VorbisDecodeSession | null` |
|
||||
|
||||
### D. opusSession.ts
|
||||
|
||||
| 名称 | 可见性 | 说明 |
|
||||
|------|--------|------|
|
||||
| `OpusCodecDecoder` | 新增 export class | `implements IAudioCodecDecoder`,`configure` / `decode` / `flush` / `destroy`,零 static |
|
||||
| `OpusDecodeSession` | export class | `decoder` 字段类型改为 `IAudioCodecDecoder` |
|
||||
| `decodePacket` | 删除(private async) | 逻辑移入 `OpusCodecDecoder.decode`,其 jsDoc 一并删除 |
|
||||
| `createOpusDecodeSession` | export async function(签名变更) | 三参 `(source, info, decoder: IAudioCodecDecoder)` |
|
||||
|
||||
### E. decoderRegistry.ts
|
||||
|
||||
| 名称 | 可见性 | 说明 |
|
||||
|------|--------|------|
|
||||
| `AudioDecoderRegistry` | export class | `implements IAudioDecoderRegistry`,`context` + `Map<AudioCodec, AudioCodecDecoderCreateFunc>` |
|
||||
| 构造器 | 参数 | `constructor(context: IMotaAudioContext)` |
|
||||
|
||||
### F. context.ts
|
||||
|
||||
| 名称 | 可见性 | 说明 |
|
||||
|------|--------|------|
|
||||
| `codecRegistry` | 新增 private readonly 字段 | 类型为接口 `IAudioDecoderRegistry` |
|
||||
| `registerCodecDecoder` | 新增 public | 委托 `codecRegistry` |
|
||||
| `createCodecDecoder` | 新增 public | 委托 `codecRegistry` |
|
||||
| 构造器 | 变更 | 末尾 `new AudioDecoderRegistry(this)` + 默认注册 Opus |
|
||||
| `createDecodeSession` | 重写方法体 | Ogg + Vorbis → Vorbis 会话;Opus → 注册表解码器 + Opus 会话 |
|
||||
|
||||
### G. types.ts
|
||||
|
||||
| 项 | 变化 |
|
||||
|----|------|
|
||||
| `IMotaAudioContext` | 父接口追加 `IAudioDecoderRegistry`(1 个 hunk) |
|
||||
| 删除命名 | `OpusDecodeSession.decodePacket` |
|
||||
|
||||
## 既有注释改动
|
||||
|
||||
H 表 6 处逐字:
|
||||
|
||||
1. probe.ts:`// 只声明本 tracer 支持的容器格式,避免为其它格式付解析器体积` → `// 声明本包支持的全部容器格式,原生支持的格式仍优先走浏览器解码`
|
||||
2. probe.ts:`* 用 Ogg / WebM 精选格式表创建一个 mediabunny 输入` → `* 用支持格式表创建一个 mediabunny 输入`
|
||||
3. probe.ts:`// 已注册格式表只有 Ogg / WebM,走到这里说明探测结果异常` → `// 已注册格式表覆盖全部支持的容器,走到这里说明探测结果异常`
|
||||
4. opusSession.ts:保留既有三行 jsDoc,新增 `* @param decoder 已注册的 Opus 编码解码器`
|
||||
5. opusSession.ts:`/** 当前会话使用的 Opus 解码器实例 */` → `/** 当前会话使用的 Opus 编码解码器 */`
|
||||
6. opusDecodeSession.test.ts 首行:`// 校验 Ogg Opus 的格式探测、OpusHead 解析与整文件解码会话` → `// 校验 Ogg Opus 与 WebM Opus 的格式探测、编码解码器与整文件解码会话`
|
||||
|
||||
I 表允许的新增注释:probe.ts 的 `toAudioContainer` / `readDuration` jsDoc 内容行与 `// Ogg 与 WebM 不记录头部时长,整文件解码本来就要遍历全部数据`;opusSession.ts 的 `/** 当前配置好的 Opus 解码器,未配置时为空 */`;context.ts 的 `/** 编码解码器注册表 */` 与 `// Opus 解码器由 opus-decoder 自行管理资源,不需要音频上下文`;vorbisSession.ts / decoderRegistry.ts 全部为新增文件。注释闸门按 `(改前 − removed) ∪ added === 改后` 与 `改后 − (改前 ∪ added) 为空` 双重校验通过。
|
||||
|
||||
## WebM 测试决策
|
||||
|
||||
可行,不加二进制 fixture。用 mediabunny 的 `EncodedPacketSink` + `EncodedAudioPacketSource` + `Output` / `WebMOutputFormat` / `BufferTarget` 现场把 `bgm.opus` 转封装成 WebM,探测为 WebM/Opus、48000、2 声道;测试只消费前 50 个数据块就 break,避免二次整文件全量解码。
|
||||
|
||||
## 注册表测试决策
|
||||
|
||||
注册表逻辑抽到 `decoderRegistry.ts` 的 `AudioDecoderRegistry`,构造参数是 `IMotaAudioContext`,Node 里可直接 `new AudioDecoderRegistry({} as IMotaAudioContext)`,无需伪造 `AudioContext` / `Audio`。`decoderRegistry.test.ts` 的 2 个 it 覆盖「注册后返回同一实例」「未注册返回 null」「工厂收到上下文」。`context.ts` 只做委托,`gate-structure` 另做静态断言。
|
||||
|
||||
## MP3 / WAV 探测决策
|
||||
|
||||
`probeAudioFormats.test.ts` 的 1 个 it 使用仓库既有 fixture:`click.mp3` → Mp3/Mp3/44100/1 声道/0.0794 秒,`click.wav` → Wav/Pcm/44100/1 声道/0.0402 秒,容差 0.01 秒,不新增 fixture。「MP3 / WAV 不作整文件扫描」由结构闸门兜底:`computeDuration(` 全文件 1 处且位于 Ogg / WebM 条件之后。
|
||||
|
||||
## try / catch 例外
|
||||
|
||||
`vorbisSession.ts` 的 `createVorbisDecodeSession` 内 `decodeFile` 外层有本计划唯一一处 `try` / `catch`(AGENTS.md 第 26 行低层库例外,Task 0 已报备),`try` 只包 `decoded = await decoder.decodeFile(bytes);` 一行;catch 内 `void decoder.free();` + `logger.error(97);` + `return null;`,不新增 `throw`、不扩散。`context.ts` 既有的 `decodeNative` 的 try / catch 逐字未动,全仓 try 仅这两处。
|
||||
|
||||
## void 处理
|
||||
|
||||
三处 `void` 悬浮 Promise:`VorbisDecodeSession.close()` 的 `void this.decoder.free();`、`OpusDecodeSession.close()` 的 `void this.decoder.destroy();`、`createVorbisDecodeSession` 内抛错与零采样两处清理的 `void decoder.free();`。`close()` 是同步接口,用 `void` 显式声明不等待,避免悬浮 Promise 告警。
|
||||
|
||||
## 时间关卡
|
||||
|
||||
`gsd-09-65-clock.txt` 采集:账户 `13194`,采集时间 2026-11-26 16:54(本地)。Task 1 结束 17:01,Task 2 结束 17:03,全程未到晚于 22:00 的停止点,未触发时间关卡停止。
|
||||
|
||||
## 日志码
|
||||
|
||||
本计划不新增日志码,复用 error 97(容器未知 / 无主音轨 / Opus 会话创建失败 / Vorbis 解码抛错 / Vorbis 解码零采样)与 warn 217(不支持的输入类型)。已知语义偏差:97 的既有消息偏「音轨或解码描述缺失」,用在 Vorbis 抛错与零采样上并非逐字贴合;本计划未新增 98,留待用户另行批准。
|
||||
|
||||
## 闸门真实输出
|
||||
|
||||
| 闸门 | 真实输出 | 结果 |
|
||||
|------|----------|------|
|
||||
| 结构 --source | `STRUCTURE GATE OK (--source)` | 通过 |
|
||||
| 结构 --full | `STRUCTURE GATE OK (--full)` | 通过 |
|
||||
| 注释 --source | `COMMENTS GATE OK (--source)` | 通过 |
|
||||
| 注释 --full | `COMMENTS GATE OK (--full)` | 通过 |
|
||||
| typesdiff | `TYPESDIFF GATE OK (hunks=1)` | 通过 |
|
||||
| 守卫哈希 | `GUARD GATE OK (16 paths unchanged)` | 通过 |
|
||||
| 文本 7 文件 | `TEXT GATE OK (7 files)` | 通过 |
|
||||
| 文本 10 文件 | `TEXT GATE OK (10 files)` | 通过 |
|
||||
| opus 单文件测试 | `6 passed (6)`(Task 1) | 通过 |
|
||||
| 全量音频测试 | `Test Files 4 passed (4)` / `Tests 14 passed (14)` | 通过 |
|
||||
| tsc 改前 | 基线 279 error 头行,`packages/audio` 0 error | 记录 |
|
||||
| tsc Task 1 | `TSC GATE OK (baseline=279 compare=279 added=0 audio=0)` | 通过 |
|
||||
| tsc Task 2 | `TSC GATE OK (baseline=279 compare=279 added=0 audio=0)` | 通过 |
|
||||
| 范围 Task 1 | `SCOPE GATE OK (--expect-task1, added=7, external=1)` | 通过 |
|
||||
| HEAD | `HEAD GATE OK (unchanged, head=82ae65a)` | 通过 |
|
||||
| prettier | `All matched files use Prettier code style!` | 通过 |
|
||||
| eslint | 退出码 0、0 warning | 通过 |
|
||||
| SUMMARY | `SUMMARY GATE OK` | 通过 |
|
||||
|
||||
## 未改项
|
||||
|
||||
16 条只读守卫路径哈希逐条未变:`packages/common/src/logger.ts`、`packages/common/src/logger.json`、`packages/audio/src/source.ts`、`packages/audio/src/bgm.ts`、`packages/audio/src/decoder.ts`、`packages/audio/src/effect.ts`、`packages/audio/src/sound.ts`、`packages/audio/src/support.ts`、`packages/audio/src/index.ts`、`packages/audio/src/route.ts`、`packages/audio/package.json`、`package.json`、`pnpm-lock.yaml`、`script/build-game.ts`、`vite.config.ts`、`vitest.perf.config.ts`。零新增依赖、零 `logger.json` 改动、零新增 `throw`、零 `static`、`index.ts` barrel 未动。
|
||||
|
||||
## 偏差
|
||||
|
||||
1. 使用了 `prettier --write` 兜底:Write 工具写出 LF,先 `--write` 归一为 CRLF 并重排长行,之后 `--check` 通过(Task 1 与 Task 2 各一次)。
|
||||
2. 外部并发改动:执行期间用户新增 `docs/.vitepress/components/demos/ui/text-demo-materials.ts`,与本计划无关;范围闸门以 `gsd-09-65-external-added.txt` 白名单记录该外部新增并继续,未回退。基线其余条目状态行未变。
|
||||
3. 无其它偏差;规格未放宽任何断言。
|
||||
|
||||
## 未校准估算
|
||||
|
||||
计划估算 `confidence: low`、`tokens: 36000`、3 个任务(advisory)。实测按「修改文件 git diff 字符数 + 新建文件字符数」求和 30176 字符,除以 4 得约 7544 tokens;3 个任务;0 提交。估算明显高于实测,属未校准估算的保守取值。
|
||||
|
||||
## 未提交声明
|
||||
|
||||
本计划 0 提交:未执行任何 `git add` / `git commit` / `git tag` / `git push` / `git stash` / `git checkout` / `git worktree` / `git restore`;显式跳过 `workflow.commit_docs`;未使用 worktree。产物与本文档留在工作树等用户验收。
|
||||
|
||||
## 用户验收
|
||||
|
||||
真实浏览器里原生支持与 WASM 兜底的降级效果(Safari 等不支持 Ogg Vorbis 的环境)由用户手动验收,不作为自动断言。
|
||||
@@ -0,0 +1,56 @@
|
||||
// 校验编码解码器注册表的注册、创建、未注册返回 null 与上下文透传
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
AudioCodec,
|
||||
IAudioCodecDecoder,
|
||||
IAudioDecodedChunk,
|
||||
IAudioFormatInfo,
|
||||
IMotaAudioContext
|
||||
} from '../types';
|
||||
import { AudioDecoderRegistry } from '../decoderRegistry';
|
||||
|
||||
// 注册表测试只需要一个能拿住引用的空解码器,不涉及任何解码行为
|
||||
class StubCodecDecoder implements IAudioCodecDecoder {
|
||||
configured: IAudioFormatInfo | null = null;
|
||||
|
||||
configure(info: IAudioFormatInfo): Promise<void> {
|
||||
this.configured = info;
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
decode(): Promise<IAudioDecodedChunk | null> {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
flush(): Promise<IAudioDecodedChunk | null> {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
destroy(): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
describe('编码解码器注册表', () => {
|
||||
// 注册后应为对应编码创建解码器,未注册的编码返回 null
|
||||
it('注册与创建', () => {
|
||||
const registry = new AudioDecoderRegistry({} as IMotaAudioContext);
|
||||
const decoder = new StubCodecDecoder();
|
||||
registry.registerCodecDecoder(AudioCodec.Vorbis, () => decoder);
|
||||
expect(registry.createCodecDecoder(AudioCodec.Vorbis)).toBe(decoder);
|
||||
expect(registry.createCodecDecoder(AudioCodec.Opus)).toBeNull();
|
||||
});
|
||||
|
||||
// 创建解码器时应把注册表持有的音频上下文透传给工厂
|
||||
it('工厂收到上下文', () => {
|
||||
const context = {} as IMotaAudioContext;
|
||||
const registry = new AudioDecoderRegistry(context);
|
||||
let received: IMotaAudioContext | null = null;
|
||||
registry.registerCodecDecoder(AudioCodec.Opus, passed => {
|
||||
received = passed;
|
||||
return new StubCodecDecoder();
|
||||
});
|
||||
expect(registry.createCodecDecoder(AudioCodec.Opus)).not.toBeNull();
|
||||
expect(received).toBe(context);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,20 @@
|
||||
// 校验 Ogg Opus 的格式探测、OpusHead 解析与整文件解码会话
|
||||
// 校验 Ogg Opus 与 WebM Opus 的格式探测、编码解码器与整文件解码会话
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
BufferSource,
|
||||
BufferTarget,
|
||||
EncodedAudioPacketSource,
|
||||
EncodedPacketSink,
|
||||
Input,
|
||||
OGG,
|
||||
Output,
|
||||
WebMOutputFormat
|
||||
} from 'mediabunny';
|
||||
import { AudioCodec, AudioContainer } from '../types';
|
||||
import {
|
||||
parseOpusIdentificationHeader,
|
||||
createOpusDecodeSession
|
||||
createOpusDecodeSession,
|
||||
OpusCodecDecoder
|
||||
} from '../opusSession';
|
||||
import { probeAudioSource } from '../probe';
|
||||
// 仓库根类型检查未加载 Node 类型,测试需要在 Node 环境下读取音频样例
|
||||
@@ -16,6 +27,30 @@ const fixture = new Uint8Array(
|
||||
)
|
||||
);
|
||||
|
||||
// 把 Ogg Opus 的编码包重新封装为 WebM,供 WebM 解码路径测试使用
|
||||
async function transmuxToWebM(bytes: Uint8Array): Promise<Uint8Array> {
|
||||
const input = new Input({
|
||||
formats: [OGG],
|
||||
source: new BufferSource(bytes)
|
||||
});
|
||||
const track = await input.getPrimaryAudioTrack();
|
||||
const config = await track!.getDecoderConfig();
|
||||
const sink = new EncodedPacketSink(track!);
|
||||
const output = new Output({
|
||||
format: new WebMOutputFormat(),
|
||||
target: new BufferTarget()
|
||||
});
|
||||
const source = new EncodedAudioPacketSource('opus');
|
||||
output.addAudioTrack(source);
|
||||
await output.start();
|
||||
for await (const packet of sink.packets()) {
|
||||
await source.add(packet, { decoderConfig: config! });
|
||||
}
|
||||
await output.finalize();
|
||||
input.dispose();
|
||||
return new Uint8Array(output.target.buffer!);
|
||||
}
|
||||
|
||||
describe('opus 解码', () => {
|
||||
// 探测 bgm.opus 应识别为 Ogg 容器下的 Opus 编码
|
||||
it('探测 Ogg Opus 格式', async () => {
|
||||
@@ -69,7 +104,11 @@ describe('opus 解码', () => {
|
||||
it('整文件解码', async () => {
|
||||
const info = await probeAudioSource(fixture);
|
||||
expect(info).not.toBeNull();
|
||||
const session = await createOpusDecodeSession(fixture, info!);
|
||||
const session = await createOpusDecodeSession(
|
||||
fixture,
|
||||
info!,
|
||||
new OpusCodecDecoder()
|
||||
);
|
||||
expect(session).not.toBeNull();
|
||||
let samples = 0;
|
||||
let channels = 0;
|
||||
@@ -93,4 +132,71 @@ describe('opus 解码', () => {
|
||||
expect(lastTimestamp).toBeGreaterThan(0);
|
||||
expect(peak).toBeGreaterThan(0.001);
|
||||
});
|
||||
|
||||
// 默认注册的 Opus 编码解码器应能在配置后解出单个数据包
|
||||
it('默认 Opus 编码解码器可用', async () => {
|
||||
const info = await probeAudioSource(fixture);
|
||||
expect(info).not.toBeNull();
|
||||
const input = new Input({
|
||||
formats: [OGG],
|
||||
source: new BufferSource(fixture)
|
||||
});
|
||||
const track = await input.getPrimaryAudioTrack();
|
||||
const config = await track!.getDecoderConfig();
|
||||
const description = config!.description as Uint8Array;
|
||||
const decoder = new OpusCodecDecoder();
|
||||
await decoder.configure(info!, description);
|
||||
const sink = new EncodedPacketSink(track!);
|
||||
const packet = await sink.getFirstPacket({});
|
||||
expect(packet).not.toBeNull();
|
||||
const chunk = await decoder.decode(
|
||||
packet!.data,
|
||||
packet!.timestamp,
|
||||
packet!.duration
|
||||
);
|
||||
expect(chunk).not.toBeNull();
|
||||
expect(chunk!.channelData.length).toBe(2);
|
||||
expect(chunk!.samplesDecoded).toBeGreaterThan(0);
|
||||
expect(await decoder.flush()).toBeNull();
|
||||
await decoder.destroy();
|
||||
input.dispose();
|
||||
});
|
||||
|
||||
// 重新封装出的 WebM 应探测为 WebM/Opus,并复用同一条整文件解码路径
|
||||
it('WebM Opus 整文件解码', async () => {
|
||||
const webm = await transmuxToWebM(fixture);
|
||||
const info = await probeAudioSource(webm);
|
||||
expect(info).not.toBeNull();
|
||||
const format = info!;
|
||||
expect(format.container).toBe(AudioContainer.WebM);
|
||||
expect(format.codec).toBe(AudioCodec.Opus);
|
||||
expect(format.sampleRate).toBe(48000);
|
||||
expect(format.channels).toBe(2);
|
||||
const session = await createOpusDecodeSession(
|
||||
webm,
|
||||
format,
|
||||
new OpusCodecDecoder()
|
||||
);
|
||||
expect(session).not.toBeNull();
|
||||
let count = 0;
|
||||
let samples = 0;
|
||||
let channels = 0;
|
||||
let peak = 0;
|
||||
for await (const chunk of session!.chunks) {
|
||||
count++;
|
||||
channels = Math.max(channels, chunk.channelData.length);
|
||||
samples += chunk.samplesDecoded;
|
||||
for (const channel of chunk.channelData) {
|
||||
for (let i = 0; i < channel.length; i++) {
|
||||
const abs = Math.abs(channel[i]);
|
||||
if (abs > peak) peak = abs;
|
||||
}
|
||||
}
|
||||
if (count >= 50) break;
|
||||
}
|
||||
session!.close();
|
||||
expect(channels).toBe(2);
|
||||
expect(samples).toBeGreaterThan(0);
|
||||
expect(peak).toBeGreaterThan(0.001);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
// 校验原生格式(MP3 / WAV)的容器与时长探测
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { AudioCodec, AudioContainer } from '../types';
|
||||
import { probeAudioSource } from '../probe';
|
||||
// 仓库根类型检查未加载 Node 类型,测试需要在 Node 环境下读取音频样例
|
||||
// @ts-expect-error 此处缺少 node:fs 的模块声明,仅测试环境使用
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const mp3Fixture = new Uint8Array(
|
||||
readFileSync(
|
||||
new URL(
|
||||
'../../../../public/_server/blockly/media/click.mp3',
|
||||
import.meta.url
|
||||
)
|
||||
)
|
||||
);
|
||||
const wavFixture = new Uint8Array(
|
||||
readFileSync(
|
||||
new URL(
|
||||
'../../../../public/_server/blockly/media/click.wav',
|
||||
import.meta.url
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
describe('原生格式探测', () => {
|
||||
// MP3 与 WAV 应探测出正确容器与编码,并在头部拿到时长而不扫描整个文件
|
||||
it('探测 MP3 与 WAV 容器和时长', async () => {
|
||||
const mp3 = await probeAudioSource(mp3Fixture);
|
||||
expect(mp3).not.toBeNull();
|
||||
expect(mp3!.container).toBe(AudioContainer.Mp3);
|
||||
expect(mp3!.codec).toBe(AudioCodec.Mp3);
|
||||
expect(mp3!.sampleRate).toBe(44100);
|
||||
expect(mp3!.channels).toBe(1);
|
||||
expect(mp3!.duration).not.toBeNull();
|
||||
expect(Math.abs(mp3!.duration! - 0.0794)).toBeLessThan(0.01);
|
||||
const wav = await probeAudioSource(wavFixture);
|
||||
expect(wav).not.toBeNull();
|
||||
expect(wav!.container).toBe(AudioContainer.Wav);
|
||||
expect(wav!.codec).toBe(AudioCodec.Pcm);
|
||||
expect(wav!.sampleRate).toBe(44100);
|
||||
expect(wav!.channels).toBe(1);
|
||||
expect(wav!.duration).not.toBeNull();
|
||||
expect(Math.abs(wav!.duration! - 0.0402)).toBeLessThan(0.01);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
// 校验 Ogg Vorbis 的格式探测与整文件解码会话
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { AudioCodec, AudioContainer } from '../types';
|
||||
import { createVorbisDecodeSession } from '../vorbisSession';
|
||||
import { probeAudioSource } from '../probe';
|
||||
// 仓库根类型检查未加载 Node 类型,测试需要在 Node 环境下读取音频样例
|
||||
// @ts-expect-error 此处缺少 node:fs 的模块声明,仅测试环境使用
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const fixture = new Uint8Array(
|
||||
readFileSync(
|
||||
new URL(
|
||||
'../../../../public/_server/blockly/media/click.ogg',
|
||||
import.meta.url
|
||||
)
|
||||
)
|
||||
);
|
||||
const opusFixture = new Uint8Array(
|
||||
readFileSync(
|
||||
new URL('../../../../public/project/bgms/bgm.opus', import.meta.url)
|
||||
)
|
||||
);
|
||||
|
||||
describe('vorbis 解码', () => {
|
||||
// 探测 click.ogg 应识别为 Ogg 容器下的 Vorbis 编码
|
||||
it('探测 Ogg Vorbis 格式', async () => {
|
||||
const info = await probeAudioSource(fixture);
|
||||
expect(info).not.toBeNull();
|
||||
const format = info!;
|
||||
expect(format.container).toBe(AudioContainer.Ogg);
|
||||
expect(format.codec).toBe(AudioCodec.Vorbis);
|
||||
expect(format.sampleRate).toBe(44100);
|
||||
expect(format.channels).toBe(1);
|
||||
});
|
||||
|
||||
// 整文件会话应只产出一个数据块,且含非空 PCM
|
||||
it('整文件解码', async () => {
|
||||
const info = await probeAudioSource(fixture);
|
||||
expect(info).not.toBeNull();
|
||||
const session = await createVorbisDecodeSession(fixture, info!);
|
||||
expect(session).not.toBeNull();
|
||||
let count = 0;
|
||||
let samples = 0;
|
||||
let channels = 0;
|
||||
let timestamp = -1;
|
||||
let duration = 0;
|
||||
let peak = 0;
|
||||
for await (const chunk of session!.chunks) {
|
||||
count++;
|
||||
samples += chunk.samplesDecoded;
|
||||
channels = chunk.channelData.length;
|
||||
timestamp = chunk.timestamp;
|
||||
duration = chunk.duration;
|
||||
for (const channel of chunk.channelData) {
|
||||
for (let i = 0; i < channel.length; i++) {
|
||||
const abs = Math.abs(channel[i]);
|
||||
if (abs > peak) peak = abs;
|
||||
}
|
||||
}
|
||||
}
|
||||
session!.close();
|
||||
expect(count).toBe(1);
|
||||
expect(timestamp).toBe(0);
|
||||
expect(channels).toBe(1);
|
||||
expect(samples).toBeGreaterThan(0);
|
||||
expect(duration).toBeCloseTo(samples / 44100, 6);
|
||||
expect(Math.abs(duration - info!.duration!)).toBeLessThan(0.01);
|
||||
expect(peak).toBeGreaterThan(0.001);
|
||||
});
|
||||
|
||||
// 非 Vorbis 编码的数据不应建立 Vorbis 会话
|
||||
it('非 Vorbis 数据不建立会话', async () => {
|
||||
const info = await probeAudioSource(opusFixture);
|
||||
expect(info).not.toBeNull();
|
||||
expect(info!.codec).toBe(AudioCodec.Opus);
|
||||
const session = await createVorbisDecodeSession(opusFixture, info!);
|
||||
expect(session).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -16,10 +16,13 @@ import {
|
||||
AudioDecoderCreateFunc,
|
||||
AudioCodec,
|
||||
AudioContainer,
|
||||
AudioCodecDecoderCreateFunc,
|
||||
AudioInputSource,
|
||||
AudioType,
|
||||
IAudioBufferSource,
|
||||
IAudioChannelVolumeEffect,
|
||||
IAudioCodecDecoder,
|
||||
IAudioDecoderRegistry,
|
||||
IAudioDecodeData,
|
||||
IAudioDecodeError,
|
||||
IAudioDecoder,
|
||||
@@ -38,7 +41,9 @@ import {
|
||||
ISoundPlayer
|
||||
} from './types';
|
||||
import { probeAudioSource } from './probe';
|
||||
import { createOpusDecodeSession } from './opusSession';
|
||||
import { createOpusDecodeSession, OpusCodecDecoder } from './opusSession';
|
||||
import { createVorbisDecodeSession } from './vorbisSession';
|
||||
import { AudioDecoderRegistry } from './decoderRegistry';
|
||||
import { SoundPlayer } from './sound';
|
||||
import { AudioRoute } from './route';
|
||||
|
||||
@@ -68,6 +73,8 @@ export class MotaAudioContext implements IMotaAudioContext {
|
||||
/** 所有注册的解码器 */
|
||||
private readonly decoders: Map<AudioType, AudioDecoderCreateFunc> =
|
||||
new Map();
|
||||
/** 编码解码器注册表 */
|
||||
private readonly codecRegistry: IAudioDecoderRegistry;
|
||||
|
||||
/** 最小音量 */
|
||||
private readonly minDb = -60;
|
||||
@@ -76,6 +83,12 @@ export class MotaAudioContext implements IMotaAudioContext {
|
||||
this.ac = new AudioContext();
|
||||
this.gain = this.ac.createGain();
|
||||
this.gain.connect(this.ac.destination);
|
||||
this.codecRegistry = new AudioDecoderRegistry(this);
|
||||
// Opus 解码器由 opus-decoder 自行管理资源,不需要音频上下文
|
||||
this.registerCodecDecoder(
|
||||
AudioCodec.Opus,
|
||||
() => new OpusCodecDecoder()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -377,6 +390,17 @@ export class MotaAudioContext implements IMotaAudioContext {
|
||||
}
|
||||
}
|
||||
|
||||
registerCodecDecoder(
|
||||
codec: AudioCodec,
|
||||
decoder: AudioCodecDecoderCreateFunc
|
||||
): void {
|
||||
this.codecRegistry.registerCodecDecoder(codec, decoder);
|
||||
}
|
||||
|
||||
createCodecDecoder(codec: AudioCodec): IAudioCodecDecoder | null {
|
||||
return this.codecRegistry.createCodecDecoder(codec);
|
||||
}
|
||||
|
||||
getAudioTypeFromData(data: Uint8Array): AudioType {
|
||||
let audioType: AudioType = AudioType.Unknown;
|
||||
// 检查头文件获取音频类型,仅检查前256个字节
|
||||
@@ -525,15 +549,24 @@ export class MotaAudioContext implements IMotaAudioContext {
|
||||
): Promise<IAudioDecodeSession | null> {
|
||||
const info = await this.probeAudio(source);
|
||||
if (!info) return null;
|
||||
if (info.codec !== AudioCodec.Opus) return null;
|
||||
const container = info.container;
|
||||
if (
|
||||
container !== AudioContainer.Ogg &&
|
||||
container !== AudioContainer.WebM
|
||||
info.container === AudioContainer.Ogg &&
|
||||
info.codec === AudioCodec.Vorbis
|
||||
) {
|
||||
return null;
|
||||
return createVorbisDecodeSession(source, info);
|
||||
} else if (info.codec === AudioCodec.Opus) {
|
||||
const container = info.container;
|
||||
if (
|
||||
container !== AudioContainer.Ogg &&
|
||||
container !== AudioContainer.WebM
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const decoder = this.createCodecDecoder(AudioCodec.Opus);
|
||||
if (!decoder) return null;
|
||||
return createOpusDecodeSession(source, info, decoder);
|
||||
}
|
||||
return createOpusDecodeSession(source, info);
|
||||
return null;
|
||||
}
|
||||
|
||||
async decodeAudio(data: Uint8Array): Promise<IAudioDecodeData | null> {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
AudioCodec,
|
||||
AudioCodecDecoderCreateFunc,
|
||||
IAudioCodecDecoder,
|
||||
IAudioDecoderRegistry,
|
||||
IMotaAudioContext
|
||||
} from './types';
|
||||
|
||||
export class AudioDecoderRegistry implements IAudioDecoderRegistry {
|
||||
/** 创建编码解码器时透传给工厂的音频上下文 */
|
||||
private readonly context: IMotaAudioContext;
|
||||
/** 编码到解码器创建函数的映射 */
|
||||
private readonly decoders: Map<AudioCodec, AudioCodecDecoderCreateFunc> =
|
||||
new Map();
|
||||
|
||||
constructor(context: IMotaAudioContext) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
registerCodecDecoder(
|
||||
codec: AudioCodec,
|
||||
decoder: AudioCodecDecoderCreateFunc
|
||||
): void {
|
||||
this.decoders.set(codec, decoder);
|
||||
}
|
||||
|
||||
createCodecDecoder(codec: AudioCodec): IAudioCodecDecoder | null {
|
||||
const create = this.decoders.get(codec);
|
||||
if (!create) return null;
|
||||
return create(this.context);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import { EncodedPacket, EncodedPacketSink, Input } from 'mediabunny';
|
||||
import { EncodedPacketSink, Input } from 'mediabunny';
|
||||
import { logger } from '@motajs/common';
|
||||
import {
|
||||
AudioCodec,
|
||||
AudioInputSource,
|
||||
IAudioCodecDecoder,
|
||||
IAudioDecodeError,
|
||||
IAudioDecodedChunk,
|
||||
IAudioDecodeSession,
|
||||
@@ -161,40 +163,28 @@ async function loadOpusDecoder(
|
||||
return decoder;
|
||||
}
|
||||
|
||||
export class OpusDecodeSession implements IAudioDecodeSession {
|
||||
readonly info: IAudioFormatInfo;
|
||||
readonly chunks: AsyncIterable<IAudioDecodedChunk>;
|
||||
export class OpusCodecDecoder implements IAudioCodecDecoder {
|
||||
/** 当前配置好的 Opus 解码器,未配置时为空 */
|
||||
private decoder: IOpusDecoderInstance | null = null;
|
||||
|
||||
/** 会话持有的 mediabunny 输入,关闭会话时释放 */
|
||||
private readonly input: Input;
|
||||
/** 按包顺序读取编码数据的包读取器 */
|
||||
private readonly sink: EncodedPacketSink;
|
||||
/** 当前会话使用的 Opus 解码器实例 */
|
||||
private readonly decoder: IOpusDecoderInstance;
|
||||
/** 会话是否已关闭,用于中止异步迭代 */
|
||||
private closed: boolean = false;
|
||||
|
||||
constructor(
|
||||
input: Input,
|
||||
sink: EncodedPacketSink,
|
||||
async configure(
|
||||
info: IAudioFormatInfo,
|
||||
decoder: IOpusDecoderInstance
|
||||
) {
|
||||
this.input = input;
|
||||
this.sink = sink;
|
||||
this.info = info;
|
||||
this.decoder = decoder;
|
||||
this.chunks = this.generateChunks();
|
||||
description?: Uint8Array
|
||||
): Promise<void> {
|
||||
if (info.codec !== AudioCodec.Opus) return;
|
||||
const header = parseOpusIdentificationHeader(description ?? null);
|
||||
if (!header) return;
|
||||
this.decoder = await loadOpusDecoder(header);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解码单个 Opus 包,空包返回 null
|
||||
* @param packet 待解码的编码包
|
||||
*/
|
||||
private async decodePacket(
|
||||
packet: EncodedPacket
|
||||
async decode(
|
||||
packet: Uint8Array,
|
||||
timestamp: number,
|
||||
duration: number
|
||||
): Promise<IAudioDecodedChunk | null> {
|
||||
const decoded = await this.decoder.decodeFrame(packet.data);
|
||||
const decoder = this.decoder;
|
||||
if (!decoder) return null;
|
||||
const decoded = await decoder.decodeFrame(packet);
|
||||
// 零采样但带解码错误时需要保留错误,交给上层记录失败
|
||||
const isEmpty = decoded.samplesDecoded === 0;
|
||||
if (isEmpty && decoded.errors.length === 0) return null;
|
||||
@@ -204,19 +194,61 @@ export class OpusDecodeSession implements IAudioDecodeSession {
|
||||
),
|
||||
samplesDecoded: decoded.samplesDecoded,
|
||||
sampleRate: decoded.sampleRate,
|
||||
timestamp: packet.timestamp,
|
||||
duration: packet.duration,
|
||||
timestamp,
|
||||
duration,
|
||||
errors: decoded.errors
|
||||
};
|
||||
}
|
||||
|
||||
flush(): Promise<IAudioDecodedChunk | null> {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
async destroy(): Promise<void> {
|
||||
const decoder = this.decoder;
|
||||
this.decoder = null;
|
||||
if (!decoder) return;
|
||||
await decoder.free();
|
||||
}
|
||||
}
|
||||
|
||||
export class OpusDecodeSession implements IAudioDecodeSession {
|
||||
readonly info: IAudioFormatInfo;
|
||||
readonly chunks: AsyncIterable<IAudioDecodedChunk>;
|
||||
|
||||
/** 会话持有的 mediabunny 输入,关闭会话时释放 */
|
||||
private readonly input: Input;
|
||||
/** 按包顺序读取编码数据的包读取器 */
|
||||
private readonly sink: EncodedPacketSink;
|
||||
/** 当前会话使用的 Opus 编码解码器 */
|
||||
private readonly decoder: IAudioCodecDecoder;
|
||||
/** 会话是否已关闭,用于中止异步迭代 */
|
||||
private closed: boolean = false;
|
||||
|
||||
constructor(
|
||||
input: Input,
|
||||
sink: EncodedPacketSink,
|
||||
info: IAudioFormatInfo,
|
||||
decoder: IAudioCodecDecoder
|
||||
) {
|
||||
this.input = input;
|
||||
this.sink = sink;
|
||||
this.info = info;
|
||||
this.decoder = decoder;
|
||||
this.chunks = this.generateChunks();
|
||||
}
|
||||
|
||||
/**
|
||||
* 顺序读取并解码全部 Opus 包,会话关闭后提前结束
|
||||
*/
|
||||
private async *generateChunks(): AsyncGenerator<IAudioDecodedChunk> {
|
||||
for await (const packet of this.sink.packets()) {
|
||||
if (this.closed) return;
|
||||
const chunk = await this.decodePacket(packet);
|
||||
const chunk = await this.decoder.decode(
|
||||
packet.data,
|
||||
packet.timestamp,
|
||||
packet.duration
|
||||
);
|
||||
if (chunk) yield chunk;
|
||||
}
|
||||
}
|
||||
@@ -225,7 +257,7 @@ export class OpusDecodeSession implements IAudioDecodeSession {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
this.input.dispose();
|
||||
this.decoder.free();
|
||||
void this.decoder.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -233,10 +265,12 @@ export class OpusDecodeSession implements IAudioDecodeSession {
|
||||
* 为 Ogg / WebM Opus 创建整文件解码会话
|
||||
* @param source 音频输入数据
|
||||
* @param info 探测得到的格式信息
|
||||
* @param decoder 已注册的 Opus 编码解码器
|
||||
*/
|
||||
export async function createOpusDecodeSession(
|
||||
source: AudioInputSource,
|
||||
info: IAudioFormatInfo
|
||||
info: IAudioFormatInfo,
|
||||
decoder: IAudioCodecDecoder
|
||||
): Promise<OpusDecodeSession | null> {
|
||||
const input = createMediaInput(source);
|
||||
if (!input) return null;
|
||||
@@ -258,13 +292,12 @@ export async function createOpusDecodeSession(
|
||||
logger.error(97);
|
||||
return null;
|
||||
}
|
||||
const header = parseOpusIdentificationHeader(config.description);
|
||||
if (!header) {
|
||||
if (!parseOpusIdentificationHeader(config.description)) {
|
||||
input.dispose();
|
||||
logger.error(97);
|
||||
return null;
|
||||
}
|
||||
const decoder = await loadOpusDecoder(header);
|
||||
await decoder.configure(info, config.description);
|
||||
const sink = new EncodedPacketSink(track);
|
||||
return new OpusDecodeSession(input, sink, info, decoder);
|
||||
}
|
||||
@@ -1,9 +1,15 @@
|
||||
import {
|
||||
ADTS,
|
||||
BlobSource,
|
||||
BufferSource,
|
||||
FLAC,
|
||||
Input,
|
||||
InputFormat,
|
||||
MP3,
|
||||
MP4,
|
||||
OGG,
|
||||
UrlSource,
|
||||
WAVE,
|
||||
WEBM
|
||||
} from 'mediabunny';
|
||||
import { logger } from '@motajs/common';
|
||||
@@ -14,8 +20,8 @@ import {
|
||||
IAudioFormatInfo
|
||||
} from './types';
|
||||
|
||||
// 只声明本 tracer 支持的容器格式,避免为其它格式付解析器体积
|
||||
const mediaFormats = [OGG, WEBM];
|
||||
// 声明本包支持的全部容器格式,原生支持的格式仍优先走浏览器解码
|
||||
const mediaFormats = [MP4, WEBM, OGG, WAVE, FLAC, MP3, ADTS];
|
||||
|
||||
/**
|
||||
* 把统一的音频输入类型转换为 mediabunny 支持的数据源,不支持的输入返回 null
|
||||
@@ -33,7 +39,7 @@ function createMediaSource(
|
||||
}
|
||||
|
||||
/**
|
||||
* 用 Ogg / WebM 精选格式表创建一个 mediabunny 输入
|
||||
* 用支持格式表创建一个 mediabunny 输入
|
||||
* @param source 音频输入数据
|
||||
*/
|
||||
export function createMediaInput(source: AudioInputSource): Input | null {
|
||||
@@ -68,6 +74,49 @@ function toAudioCodec(codec: string | null): AudioCodec {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 mediabunny 的容器格式映射为本包的音频容器枚举
|
||||
* @param format mediabunny 返回的容器格式
|
||||
*/
|
||||
function toAudioContainer(format: InputFormat): AudioContainer {
|
||||
switch (format) {
|
||||
case MP4:
|
||||
return AudioContainer.Mp4;
|
||||
case WEBM:
|
||||
return AudioContainer.WebM;
|
||||
case OGG:
|
||||
return AudioContainer.Ogg;
|
||||
case WAVE:
|
||||
return AudioContainer.Wav;
|
||||
case FLAC:
|
||||
return AudioContainer.Flac;
|
||||
case MP3:
|
||||
return AudioContainer.Mp3;
|
||||
case ADTS:
|
||||
return AudioContainer.Adts;
|
||||
default:
|
||||
return AudioContainer.Unknown;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取音频时长,优先使用容器头部信息,必要时才扫描整个文件
|
||||
* @param input mediabunny 输入
|
||||
* @param container 已识别的容器格式
|
||||
*/
|
||||
async function readDuration(
|
||||
input: Input,
|
||||
container: AudioContainer
|
||||
): Promise<number | null> {
|
||||
const duration = await input.getDurationFromMetadata();
|
||||
if (duration !== null) return duration;
|
||||
// Ogg 与 WebM 不记录头部时长,整文件解码本来就要遍历全部数据
|
||||
if (container === AudioContainer.Ogg || container === AudioContainer.WebM) {
|
||||
return input.computeDuration();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 探测音频数据的容器、编码、采样率、声道数与总时长
|
||||
* @param source 音频输入数据
|
||||
@@ -82,12 +131,9 @@ export async function probeAudioSource(
|
||||
input.dispose();
|
||||
return null;
|
||||
}
|
||||
const format = await input.getFormat();
|
||||
let container = AudioContainer.Unknown;
|
||||
if (format === OGG) container = AudioContainer.Ogg;
|
||||
else if (format === WEBM) container = AudioContainer.WebM;
|
||||
const container = toAudioContainer(await input.getFormat());
|
||||
if (container === AudioContainer.Unknown) {
|
||||
// 已注册格式表只有 Ogg / WebM,走到这里说明探测结果异常
|
||||
// 已注册格式表覆盖全部支持的容器,走到这里说明探测结果异常
|
||||
input.dispose();
|
||||
logger.error(97);
|
||||
return null;
|
||||
@@ -101,7 +147,7 @@ export async function probeAudioSource(
|
||||
const codec = toAudioCodec(await track.getCodec());
|
||||
const sampleRate = await track.getSampleRate();
|
||||
const channels = await track.getNumberOfChannels();
|
||||
const duration = await input.computeDuration();
|
||||
const duration = await readDuration(input, container);
|
||||
input.dispose();
|
||||
return { container, codec, sampleRate, channels, duration };
|
||||
}
|
||||
@@ -468,7 +468,10 @@ export type AudioDecoderCreateFunc = (
|
||||
) => IAudioDecoder;
|
||||
|
||||
export interface IMotaAudioContext
|
||||
extends IMotaAudioContextCreator, IAudioDecodeProvider {
|
||||
extends
|
||||
IMotaAudioContextCreator,
|
||||
IAudioDecodeProvider,
|
||||
IAudioDecoderRegistry {
|
||||
/** 音频上下文 */
|
||||
readonly ac: AudioContext;
|
||||
/** 音频播放路由 */
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import { logger } from '@motajs/common';
|
||||
import {
|
||||
AudioCodec,
|
||||
AudioInputSource,
|
||||
IAudioDecodeError,
|
||||
IAudioDecodedChunk,
|
||||
IAudioDecodeSession,
|
||||
IAudioFormatInfo
|
||||
} from './types';
|
||||
|
||||
interface IVorbisDecodedAudio {
|
||||
/** 每个声道的 PCM 数据 */
|
||||
readonly channelData: Float32Array[];
|
||||
/** 每个声道解码出的采样数 */
|
||||
readonly samplesDecoded: number;
|
||||
/** 解码后的采样率 */
|
||||
readonly sampleRate: number;
|
||||
/** 解码过程中产生的错误列表 */
|
||||
readonly errors: IAudioDecodeError[];
|
||||
}
|
||||
|
||||
interface IVorbisDecoderInstance {
|
||||
/** WASM 初始化完成的 Promise */
|
||||
readonly ready: Promise<void>;
|
||||
|
||||
/**
|
||||
* 整文件解码 Ogg Vorbis 数据
|
||||
* @param data 完整的 Ogg Vorbis 文件字节
|
||||
*/
|
||||
decodeFile(data: Uint8Array): Promise<IVorbisDecodedAudio>;
|
||||
|
||||
/**
|
||||
* 释放解码器占用的资源
|
||||
*/
|
||||
free(): void | Promise<void>;
|
||||
}
|
||||
|
||||
interface IVorbisDecoderModule {
|
||||
/** 主线程 Ogg Vorbis 解码器构造函数 */
|
||||
readonly OggVorbisDecoder: new () => IVorbisDecoderInstance;
|
||||
/** Web Worker Ogg Vorbis 解码器构造函数 */
|
||||
readonly OggVorbisDecoderWebWorker: new () => IVorbisDecoderInstance;
|
||||
}
|
||||
|
||||
/** 缓存的 ogg-vorbis 模块,加载成功后才写入,失败可以重试 */
|
||||
let vorbisModule: IVorbisDecoderModule | null = null;
|
||||
|
||||
/**
|
||||
* 读取音频输入的全部字节,不支持的输入返回 null
|
||||
* @param source 音频输入数据
|
||||
*/
|
||||
async function readSourceBytes(
|
||||
source: AudioInputSource
|
||||
): Promise<Uint8Array | null> {
|
||||
if (source instanceof ArrayBuffer) return new Uint8Array(source);
|
||||
if (source instanceof Uint8Array) return source;
|
||||
if (source instanceof Blob) {
|
||||
return new Uint8Array(await source.arrayBuffer());
|
||||
}
|
||||
if (typeof source === 'string') {
|
||||
const response = await fetch(source);
|
||||
return new Uint8Array(await response.arrayBuffer());
|
||||
}
|
||||
// 不支持的输入类型已由 probe 记录 warn 217,这里不重复记录
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 动态加载 Ogg Vorbis 解码器;浏览器使用 Worker 变体,Node 使用主线程变体
|
||||
*/
|
||||
async function loadVorbisDecoder(): Promise<IVorbisDecoderInstance> {
|
||||
let current = vorbisModule;
|
||||
if (!current) {
|
||||
current = await import('@wasm-audio-decoders/ogg-vorbis');
|
||||
vorbisModule = current;
|
||||
}
|
||||
const decoder: IVorbisDecoderInstance =
|
||||
typeof Worker === 'undefined'
|
||||
? new current.OggVorbisDecoder()
|
||||
: new current.OggVorbisDecoderWebWorker();
|
||||
await decoder.ready;
|
||||
return decoder;
|
||||
}
|
||||
|
||||
export class VorbisDecodeSession implements IAudioDecodeSession {
|
||||
readonly info: IAudioFormatInfo;
|
||||
readonly chunks: AsyncIterable<IAudioDecodedChunk>;
|
||||
|
||||
/** 本次整文件解码使用的 Vorbis 解码器 */
|
||||
private readonly decoder: IVorbisDecoderInstance;
|
||||
/** 整文件解码得到的唯一数据块 */
|
||||
private readonly chunk: IAudioDecodedChunk;
|
||||
/** 会话是否已关闭,用于中止异步迭代 */
|
||||
private closed: boolean = false;
|
||||
|
||||
constructor(
|
||||
info: IAudioFormatInfo,
|
||||
decoder: IVorbisDecoderInstance,
|
||||
chunk: IAudioDecodedChunk
|
||||
) {
|
||||
this.info = info;
|
||||
this.decoder = decoder;
|
||||
this.chunk = chunk;
|
||||
this.chunks = this.generateChunks();
|
||||
}
|
||||
|
||||
/**
|
||||
* 产出整文件解码结果,会话关闭后不再产出
|
||||
*/
|
||||
private async *generateChunks(): AsyncGenerator<IAudioDecodedChunk> {
|
||||
if (this.closed) return;
|
||||
yield this.chunk;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
void this.decoder.free();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 为 Ogg Vorbis 创建整文件解码会话
|
||||
* @param source 音频输入数据
|
||||
* @param info 探测得到的格式信息
|
||||
*/
|
||||
export async function createVorbisDecodeSession(
|
||||
source: AudioInputSource,
|
||||
info: IAudioFormatInfo
|
||||
): Promise<VorbisDecodeSession | null> {
|
||||
if (info.codec !== AudioCodec.Vorbis) return null;
|
||||
const bytes = await readSourceBytes(source);
|
||||
if (!bytes) return null;
|
||||
const decoder = await loadVorbisDecoder();
|
||||
let decoded: IVorbisDecodedAudio;
|
||||
try {
|
||||
decoded = await decoder.decodeFile(bytes);
|
||||
} catch {
|
||||
// 解码库对损坏数据可能直接拒绝,按会话创建失败处理
|
||||
void decoder.free();
|
||||
logger.error(97);
|
||||
return null;
|
||||
}
|
||||
if (decoded.samplesDecoded === 0) {
|
||||
void decoder.free();
|
||||
logger.error(97);
|
||||
return null;
|
||||
}
|
||||
const chunk: IAudioDecodedChunk = {
|
||||
channelData: decoded.channelData.map(
|
||||
channel => new Float32Array(channel)
|
||||
),
|
||||
samplesDecoded: decoded.samplesDecoded,
|
||||
sampleRate: decoded.sampleRate,
|
||||
timestamp: 0,
|
||||
duration: decoded.samplesDecoded / decoded.sampleRate,
|
||||
errors: decoded.errors
|
||||
};
|
||||
return new VorbisDecodeSession(info, decoder, chunk);
|
||||
}
|
||||
Reference in new issue
Block a user