16 Commits
Author SHA1 Message Date
TheM14 9c1bd7ba29 Sync the kernel copy with the OAMD warp and trim controls
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
The kernel copy follows the new kernel: the OAMD parser reads the trim
element, the speaker renderer applies warp, per-object trim and the
front-back balance, and the ADM writer carries them into the BWF metadata.
joc_kernel.vcxproj lists the new speaker_trim translation unit and header,
and the copied joc_version.h reports kernel 1.2.0 in the session log.

The component keeps its playback settings, its speaker layout table and
the side/rear channel swap; the stream interface is unchanged, so the
decoder wrapper needs no edit. A stream whose OAMD asks for warp 2/3 now
stops at the speaker renderer with JOC_ERR_NOT_SUPPORTED, as the reference
refuses it.

Builds Release-Static|x64 and |Win32. layout_table_test and
channel_swap_test still pass; the render harness renders a warp-1 stream
and reports the unimplemented mode for the warp-3 golden stream.
2026-11-03 01:34:32 +08:00
TheM14 43b16687cc Add a side/rear channel swap for speaker output
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
Some receivers and players expect the side pair (Ls/Rs) where the renderer puts
the rear pair (Lrs/Rrs) and the other way round, and the layouts here follow the
reference table, so the delivered PCM cannot match both. The new preference does
the reorder on the way out: Ls with Lrs, Rs with Rrs, everything else untouched.

Which channels to move is decided by name in the layout table, not by channel
count. 7.1, 7.1.2, 7.1.4, 9.1.4 and 9.1.6 carry both pairs; 5.1.2 and 5.1.4 fill
the last two slots with top channels and are left alone, and a layout that has no
rear pair makes the swap a no-op. The decoder only enables it when the layout the
core rendered is the one being delivered, so a binaural stream is never touched.

The reorder happens once per read, before the float32 and the forced int24
delivery branch, so both formats carry it and the peak and clip accounting see the
same samples as before. Decoding, object positions, the layout table and the
rendering itself are unchanged.

channel_swap_test checks the layout selection, the reorder, its inverse and the
int24 packing order. The render harness gained --swap-side-rear and the text fit
check now measures the new label in both languages.

Verified on a 7.1 render: only channels 5-8 change, 5<->7 and 6<->8 byte-exactly,
with float32 and int24 alike; a 5.1.2 render is identical with the switch on.
2026-11-01 23:53:54 +08:00
TheM14 a06ffbdcb9 Offer the model file in the HRTF browse dialog
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
The page still filtered for *.sofa and titled the dialog for a SOFA file unless
the Rosella radio was selected. Only the model is a user-facing input now, so the
picker offers *.personalized_headphone and is titled for it unconditionally, and
the SOFA radio handler and label call go with the control.
2026-11-01 19:58:41 +08:00
TheM14 5d6c6bc45c Sync the kernel copy and drop the SOFA source choice
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
The kernel copy follows the new kernel: the SOFA reader, its compile cache and
the field fit are gone, the compiled-field renderer is jochrtf_renderer.cpp with
jochrtf_runtime.*, and joc_kernel.vcxproj lists the new translation units.

With the Rosella model as the only user-facing input, the preferences page loses
its SOFA radio and the settings drop HrtfSource, hrtf_source,
hrtf_cache_policy, hrtf_cache_dir and hrtf_radius_m. Decoding always sets
personalized_headphone_path, the default lookup is
HRTF\binaural.personalized_headphone, and the page hint names that file alone.
The compiled .jochrtf stays internal: the page names a model file, never a cache.

Builds Release-Static|x64 (foo_input_joc.dll and joc_kernel.lib).
2026-11-01 19:37:51 +08:00
TheM14 b566c364df Sync the kernel copy with the Rosella filterbank changes
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
Bring the kernel copy up to the upstream state that adds the captured
Rosella filterbank and the bank selector: bank 1 is the shared public
bank (13 taps / 6 slots, 961 samples), bank 2 is the captured bank
(11 taps / 3 slots, 448 samples). The copy was still at the state
before the filterbank fix, so both upstream changes land here.

- Add src/hrtf/rosella_bank.{h,cpp}, rosella_filterbank.{h,cpp} and
  rosella_filterbank_tables.h, and list them in joc_kernel.vcxproj
- Carry the updated joc_core.h / joc_stream.h, the renderer, the
  stream and task paths, and the kernel CLI's --rosella-filterbank

The host code needs no change: joc_task_config and joc_stream_config
keep their sizes (the reserved word became rosella_filterbank, and the
task config version went 3 -> 4), so src/joc_decode.cpp builds as is.

Checked: joc_kernel.vcxproj builds for Release-Static|x64, and
`diff -rq kernel\src <upstream>\src` plus the include tree are clean.
2026-10-31 02:28:07 +08:00
TheM14 d3c9818409 Sync the kernel copy with the HRTF bed position fixes
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
2026-10-30 05:23:35 +08:00
TheM14 30e2654a3e Add the missing bed layout map sources
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
2026-10-30 04:25:47 +08:00
TheM14 b43ee8f685 Sync the kernel copy with the bed layout map and the stream path
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
2026-10-30 04:20:06 +08:00
TheM14 9dca991e03 Deliver the renderer's channel order with the host's channel map
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
2026-10-29 01:02:56 +08:00
TheM14 8c7d253d47 Sync the kernel copy with the clipgain fix
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
2026-10-28 19:21:39 +08:00
TheM14 7cebf3e22e Sync the kernel copy with the OAMD ramp timing port
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
2026-10-28 18:11:57 +08:00
TheM14 ff83912f46 Sync the kernel copy with the dbmd identity rename 2026-10-28 18:11:47 +08:00
TheM14 dc3372be27 Support the two 4.0 layouts and localize the preferences page
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-10-27 23:51:57 +08:00
TheM14 0b9f3321fd Support speaker layouts up to 9.1.6 and deliver their channel masks
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-10-25 00:15:02 +08:00
TheM14 2ed87d1dce Synchronize the joc_decoder version with the upstream repository
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-10-17 00:23:19 +08:00
TheM14 40b0b4b6c4 Sync the kernel with the single-definition error detail
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-10-16 20:26:30 +08:00
69 changed files with 4119 additions and 3240 deletions

No files matched your search

+77 -10
View File
@@ -5,7 +5,7 @@
A foobar2000 input component for **E-AC-3 JOC (Dolby Atmos)** files: the JOC object and OAMD A foobar2000 input component for **E-AC-3 JOC (Dolby Atmos)** files: the JOC object and OAMD
metadata is taken from the E-AC-3 syncframes and paired with the core PCM that ffmpeg decodes metadata is taken from the E-AC-3 syncframes and paired with the core PCM that ffmpeg decodes
(5.1 or 7 channels, following $joc\_dmx\_config\_idx$), then rendered in real time to headphones (5.1 or 7 channels, following $joc\_dmx\_config\_idx$), then rendered in real time to headphones
(HRTF) or to a speaker layout up to 7.1. The (HRTF) or to a speaker layout from 2.0 up to 9.1.6. The
rendering core is compiled into the component, so there is nothing to install beside rendering core is compiled into the component, so there is nothing to install beside
`foo_input_joc.dll`. `foo_input_joc.dll`.
@@ -59,11 +59,11 @@ Matroska/WebM Reader** in that list. Bare `.eac3` / `.ec3` files do not depend o
Preferences → Tools → **JOC decoder**: Preferences → Tools → **JOC decoder**:
* **Output** — binaural, or a speaker layout from 2.0 to 7.1; * **Output** — **Binaural (HRTF)**, or a **Speaker layout** from 2.0 to 9.1.6 (names and channel order
in the [table below](#speaker-layouts-and-channel-order));
* **Binaural mode** (near / mid / far) and the room **tail** in seconds; * **Binaural mode** (near / mid / far) and the room **tail** in seconds;
* **HRTF source** — a **SOFA** file or a **Rosella** `.personalized_headphone` model. An empty * **HRTF** — a **Rosella personalized model**. An empty path means the default
path means the default location, `<component directory>\HRTF\binaural.sofa` or location, `<component directory>\HRTF\binaural.personalized_headphone`;
`binaural.personalized_headphone`;
* **Gain** — a switch and a value in dB. Binaural rendering can exceed full scale on material * **Gain** — a switch and a value in dB. Binaural rendering can exceed full scale on material
that does not clip in the core mix, so attenuation belongs here; that does not clip in the core mix, so attenuation belongs here;
* **Force 24-bit output (int24)** — off by default, which delivers float32. When on, every sample * **Force 24-bit output (int24)** — off by default, which delivers float32. When on, every sample
@@ -75,9 +75,24 @@ Preferences → Tools → **JOC decoder**:
from the Media Library and add it again): foobar2000 caches technical information per file, and from the Media Library and add it again): foobar2000 caches technical information per file, and
until it is reloaded Properties and the Converter still go by the old 32-bit floating-point until it is reloaded Properties and the Converter still go by the old 32-bit floating-point
answer, warning that the encoder does not take floating-point input. answer, warning that the encoder does not take floating-point input.
* the **ffmpeg** executable to use. * **Swap side and rear channels** — off by default. When on, `Ls` and `Lrs`, and
`Rs` and `Rrs`, are exchanged just before the PCM is handed over (5↔7 and 6↔8
counting from one in 7.1). It only applies to layouts that carry both a side and
a rear pair — 7.1, 7.1.2, 7.1.4, 9.1.4 and 9.1.6 — so the top channels in the
last two slots of 5.1.2 and 5.1.4 are never touched. Only the delivered channel
order changes; decoding, object positions and the layout table are untouched,
and both the float32 and the int24 delivery carry the swap.
* the **ffmpeg.exe** executable to use.
* **Language** — **Follow system** / **简体中文** / **English**. Every string on the page, the status
lines and the errors a user can see use the selected language, and switching takes effect
immediately; the choice is stored in the component's own configuration. "Follow system" goes by
the Windows user-interface language: Chinese (including Traditional) reads the simplified Chinese
column, everything else reads English. The setting only affects interface text; decoding and
rendering never read it.
No control on the page is disabled, and the status line states what is in effect. No control on the page is disabled, and the status line states what is in effect. The control names
above are the English ones; the Chinese page names the same controls 输出, 扬声器布局, 双耳模式,
HRTF 文件, 增益.
### HRTF data ### HRTF data
@@ -85,6 +100,51 @@ A SOFA measurement set or a personalised headphone model is supplied by whoever
component, and is listed in `.gitignore` so it cannot be committed by accident. Speaker layouts component, and is listed in `.gitignore` so it cannot be committed by accident. Speaker layouts
need none. Binaural rendering without an HRTF fails with a message naming the file it looked for. need none. Binaural rendering without an HRTF fails with a message naming the file it looked for.
## Speaker layouts and channel order
The PCM this component hands to foobar2000, and the multichannel WAV files the Converter writes,
follow the renderer's channel order:
| Layout | Channel order |
|---|---|
| 2.0 | L, R |
| 3.1 | L, R, C, LFE |
| 4.0 | L, R, Lrs, Rrs |
| 5.1 | L, R, C, LFE, Ls, Rs |
| 7.1 | L, R, C, LFE, Ls, Rs, Lrs, Rrs |
| 5.1.2 | L, R, C, LFE, Ls, Rs, Ltm, Rtm |
| 5.1.4 | L, R, C, LFE, Ls, Rs, Ltf, Rtf, Ltr, Rtr |
| 7.1.2 | L, R, C, LFE, Ls, Rs, Lrs, Rrs, Ltm, Rtm |
| 7.1.4 | L, R, C, LFE, Ls, Rs, Lrs, Rrs, Ltf, Rtf, Ltr, Rtr |
| 9.1.4 | L, R, C, LFE, Ls, Rs, Lrs, Rrs, Lw, Rw, Ltf, Rtf, Ltr, Rtr |
| 9.1.6 | L, R, C, LFE, Ls, Rs, Lrs, Rrs, Lw, Rw, Ltf, Rtf, Ltm, Rtm, Ltr, Rtr |
`4.0` is the quad layout this project adds (the traditional `FL FR BL BR`, here `L R Lrs Rrs`): a
front and a back pair with neither a centre nor an LFE — an object straight ahead is a phantom image
of the front pair, and the LFE in the input has no output channel in this layout, so by the core's
rule it is not mixed into the others. Every other layout and channel order follows the Dolby
specifications.
**Channel order and the foobar2000 limitation.** The component hands the renderer's PCM over
unchanged, in the order of the table above; when that stream is written to WAV (the playback chunk or
a Converter output), the order of the 1–16 channels follows the Dolby documentation exactly. The
channel *definitions*, however, are not guaranteed to correspond fully: foobar2000's WAVE writer can
only declare a Windows speaker mask, which has no slot for top-middle (`Ts`) or wide (`Ww`) and cannot
express an order such as 7.1's `Ls Rs Lrs Rrs`. This is a foobar2000 limitation, not a problem with
the rendered order. Properties declares the channel count and no speaker positions; the chunk used
while playing carries foobar2000's default map for that channel count (an unspecified map is rejected
as an invalid audio stream specification and playback fails).
For a multichannel WAV with `dwChannelMask = 0`, download the CLI from
[github.com/TheM14/JustOneCacophony](https://github.com/TheM14/JustOneCacophony) and export with it: it
writes `WAVE_FORMAT_EXTENSIBLE` with `dwChannelMask = 0` and the order above.
Mapping the channels to a player, ASIO, a DAW or a device is up to the user; the component guarantees
the content and numbering of each PCM channel as listed above.
Layout names in the configuration follow the table above; a name that cannot be resolved is logged
and falls back to `7.1`.
## Building ## Building
```powershell ```powershell
@@ -99,9 +159,11 @@ byte-for-byte acceptance rests on, so it must not be changed. `foo_input_joc.vcx
`kernel\joc_kernel.vcxproj` first through a project reference; the rendering core sources in `kernel\joc_kernel.vcxproj` first through a project reference; the rendering core sources in
`kernel/` are compiled with `JOC_STATIC` / `EJOC_STATIC`, so their entry points are neither `kernel/` are compiled with `JOC_STATIC` / `EJOC_STATIC`, so their entry points are neither
imported nor exported. `tests\` holds the offline tools (bitstream self-test and cross-check, imported nor exported. `tests\` holds the offline tools (bitstream self-test and cross-check,
render comparison, preferences-page layout check, container-probe check) and `tools\` the build render comparison, speaker-layout table and channel-order check, preferences-page layout check,
and test-bed scripts. Settings also read `JOC_*` environment overrides for one run (development Chinese and English text-width check, container-probe check) and `tools\` the build and test-bed
only); the list and what each one does is in `src\settings.cpp`. scripts. Settings also read `JOC_*`
environment overrides for one run (development only); the list and what each one does is in
`src\settings.cpp`.
To diagnose a problem, read `joc_decoder.log` beside the DLL: the component writes its own To diagnose a problem, read `joc_decoder.log` beside the DLL: the component writes its own
version, the core version and the log path there at start-up. The log is capped by **bytes**: a version, the core version and the log path there at start-up. The log is capped by **bytes**: a
@@ -113,6 +175,11 @@ every container in the library, which is where the volume comes from.
## Known limitations ## Known limitations
* ADM BWF output is not implemented. * ADM BWF output is not implemented.
* Speaker layouts go up to 9.1.6 (16 channels), the renderer's own output limit; see
[Speaker layouts and channel order](#speaker-layouts-and-channel-order).
* A multichannel layout declares no speaker positions in Properties, and the per-chunk map used for
playback is only foobar2000's default for the channel count; output mapping is up to the user's
channel assignment (same section).
* All five $joc\_dmx\_config\_idx$ configurations are supported: the bed is paired per audio * All five $joc\_dmx\_config\_idx$ configurations are supported: the bed is paired per audio
frame, and its channel count follows the configuration (6 channels for 0/3, 8 for 1/2/4), with frame, and its channel count follows the configuration (6 channels for 0/3, 8 for 1/2/4), with
`-ac 6` passed to ffmpeg only for the 6-channel ones. An AC-3 core plus a dependent substream `-ac 6` passed to ffmpeg only for the 6-channel ones. An AC-3 core plus a dependent substream
+61 -12
View File
@@ -3,8 +3,8 @@
[English](README.en.md) · [安装](#安装) · [设置](#设置) · [构建](#构建) · [已知限制](#已知限制) [English](README.en.md) · [安装](#安装) · [设置](#设置) · [构建](#构建) · [已知限制](#已知限制)
foobar2000 输入组件,播放 **E-AC-3 JOC(Dolby Atmos)** 文件:从 E-AC-3 同步帧里取出 JOC foobar2000 输入组件,播放 **E-AC-3 JOC(Dolby Atmos)** 文件:从 E-AC-3 同步帧里取出 JOC
对象与 OAMD 元数据,与 ffmpeg 解出的核心 PCM(按 $joc\_dmx\_config\_idx$ 为 5.1 或 7 通道)配对后实时渲染,输出双耳(HRTF)或最多 对象与 OAMD 元数据,与 ffmpeg 解出的核心 PCM(按 $joc\_dmx\_config\_idx$ 为 5.1 或 7 通道)配对后实时渲染,输出双耳(HRTF)或
7.1 的扬声器布局。渲染内核直接编译进组件,除 `foo_input_joc.dll` 之外不需要安装任何东西。 2.0 到 9.1.6 的扬声器布局。渲染内核直接编译进组件,除 `foo_input_joc.dll` 之外不需要安装任何东西。
输入是裸流 `.eac3` / `.ec3`,或容器里的 E-AC-3 JOC 轨道(`.mp4` `.m4a` `.m4b` `.m4p` 输入是裸流 `.eac3` / `.ec3`,或容器里的 E-AC-3 JOC 轨道(`.mp4` `.m4a` `.m4b` `.m4p`
`.m4r` `.mov` `.mkv` `.mka` `.webm`)。文件里没有 JOC 就不接管:普通 AC-3 / E-AC-3、音频轨道 `.m4r` `.mov` `.mkv` `.mka` `.webm`)。文件里没有 JOC 就不接管:普通 AC-3 / E-AC-3、音频轨道
@@ -50,28 +50,73 @@ Matroska/WebM Reader** 之前。裸流 `.eac3` / `.ec3` 不受这个顺序影响
## 设置 ## 设置
Preferences → Tools → **JOC decoder**: Preferences → Tools → **JOC 解码器**:
* **Output** —— 双耳,或 2.0 到 7.1 的扬声器布局; * **输出** —— **双耳(HRTF)**,或 **扬声器布局**:2.0 到 9.1.6,布局名与声道顺序见[下表](#扬声器布局与声道顺序);
* **Binaural mode**(near / mid / far)与房间 **tail** 秒数; * **双耳模式**(near / mid / far)与房间**尾音**秒数;
* **HRTF source** —— **SOFA** 文件或 **Rosella** `.personalized_headphone` 模型。路径留空表示 * **HRTF** —— **Rosella 个性化模型**。路径留空表示用默认位置
用默认位置 `<组件目录>\HRTF\` 下的 `binaural.sofa` 或 `binaural.personalized_headphone`; `<组件目录>\HRTFinaural.personalized_headphone`;
* **Gain** —— 开关加 dB 值。双耳渲染在核心混音不削顶的素材上也可能超过满刻度,衰减放在这里; * **增益** —— 开关加 dB 值。双耳渲染在核心混音不削顶的素材上也可能超过满刻度,衰减放在这里;
* **强制 24bit 输出(int24)** —— 默认关闭,交付 float32。打开后,交付前按内核写 WAV 的 int24 * **强制 24bit 输出(int24)** —— 默认关闭,交付 float32。打开后,交付前按内核写 WAV 的 int24
规则量化(截到 ±1 → ×8388607 → 截断),超范围的样本被截断到边缘、次数记进日志;组件同时把该 规则量化(截到 ±1 → ×8388607 → 截断),超范围的样本被截断到边缘、次数记进日志;组件同时把该
文件的技术信息报成 24bit 定点。渲染本身仍是 float32,这一项说的是交付给 foobar2000 的采样精度, 文件的技术信息报成 24bit 定点。渲染本身仍是 float32,这一项说的是交付给 foobar2000 的采样精度,
不是输出设备的位深(那个在 Preferences → Output 里设置)。**切换这个开关后要刷新文件信息** 不是输出设备的位深(那个在 Preferences → Output 里设置)。**切换这个开关后要刷新文件信息**
(Properties → Reload info,或把文件从媒体库移除后重新加入):foobar2000 按文件缓存技术信息, (Properties → Reload info,或把文件从媒体库移除后重新加入):foobar2000 按文件缓存技术信息,
缓存没刷新时 Properties 与转换器仍按旧的 32bit 浮点判断,会提示"编码器不支持浮点输入"。 缓存没刷新时 Properties 与转换器仍按旧的 32bit 浮点判断,会提示"编码器不支持浮点输入"。
* **ffmpeg** 可执行文件路径。 * **交换侧环绕与后环绕声道** —— 默认关闭。打开后,交付前把 `Ls` 与 `Lrs`、`Rs` 与 `Rrs`
对调(7.1 里是 5↔7、6↔8,从 1 数)。只在这种布局同时有侧环绕和后环绕时生效:
7.1、7.1.2、7.1.4、9.1.4、9.1.6;5.1.2/5.1.4 的后两个槽位是天空声道,不会被误换。
它只改交付 PCM 的声道顺序,不动解码、对象位置与布局定义,float32 与 int24 交付都生效。
* **ffmpeg.exe** 可执行文件路径。
* **界面语言** —— **跟随系统** / **简体中文** / **English**。设置页的全部文字、状态行和用户可见的
错误信息都用这一项选定的语言,切换后立刻生效;选择存在组件自己的配置里。"跟随系统"按 Windows 的
界面语言决定:中文(含繁体)用简体中文,其它语言用英文。这一项只影响界面文字,解码与渲染不读它。
页面上的控件都不禁用,状态行会说明当前生效的是什么。 页面上的控件都不禁用,状态行会说明当前生效的是什么。中文页面的控件名与上表一致,英文页面是同一些
控件的译文(例如 **Output**、**Speaker layout**、**Binaural mode**、**HRTF file**、**Apply gain**)。
### HRTF 数据 ### HRTF 数据
SOFA 测量集或个性化耳机模型由使用组件的人自己提供,并且写在 `.gitignore` 里,避免误提交。 SOFA 测量集或个性化耳机模型由使用组件的人自己提供,并且写在 `.gitignore` 里,避免误提交。
扬声器布局不需要 HRTF。双耳渲染缺少 HRTF 时会报错并指出它找的是哪个文件。 扬声器布局不需要 HRTF。双耳渲染缺少 HRTF 时会报错并指出它找的是哪个文件。
## 扬声器布局与声道顺序
组件交给 foobar2000 的 PCM 与转换器写出的多声道 WAV 都按渲染内核的声道顺序排列:
| 布局 | 声道顺序 |
|---|---|
| 2.0 | L, R |
| 3.1 | L, R, C, LFE |
| 4.0 | L, R, Lrs, Rrs |
| 5.1 | L, R, C, LFE, Ls, Rs |
| 7.1 | L, R, C, LFE, Ls, Rs, Lrs, Rrs |
| 5.1.2 | L, R, C, LFE, Ls, Rs, Ltm, Rtm |
| 5.1.4 | L, R, C, LFE, Ls, Rs, Ltf, Rtf, Ltr, Rtr |
| 7.1.2 | L, R, C, LFE, Ls, Rs, Lrs, Rrs, Ltm, Rtm |
| 7.1.4 | L, R, C, LFE, Ls, Rs, Lrs, Rrs, Ltf, Rtf, Ltr, Rtr |
| 9.1.4 | L, R, C, LFE, Ls, Rs, Lrs, Rrs, Lw, Rw, Ltf, Rtf, Ltr, Rtr |
| 9.1.6 | L, R, C, LFE, Ls, Rs, Lrs, Rrs, Lw, Rw, Ltf, Rtf, Ltm, Rtm, Ltr, Rtr |
`4.0` 是本项目补充的 Quad 布局(传统 Quad 的 `FL FR BL BR`),声道为 `L R Lrs Rrs`:前后各一对,
既没有中置也没有 LFE——对象在正前方时由左右两只音箱合成幻像中置,输入里的 LFE 在这种布局下没有
输出声道,按内核规则不混入其它声道。除 `4.0` 外,其余布局及声道顺序均依据杜比相关规范定义。
**声道顺序与 foobar2000 的限制。** 组件把渲染内核的 PCM 原样交出,声道顺序就是上表;写进 WAV 时
(播放的 chunk 或转换器的产物),这 1–16 个声道的排列顺序与杜比规范严格对应。但 foobar2000 的
WAVE 写出只能用一套 Windows 扬声器掩码,它没有 `Ts`(top middle)和 `Ww`(wide)的位置,也无法
表达 7.1 `Ls Rs Lrs Rrs` 这种顺序,所以**声道的定义(掩码/扬声器位置)不保证完全对应**——这是
foobar2000 的限制,不是渲染顺序的问题。Properties 只声明声道数、不声明位置;播放时 chunk 携带
foobar2000 对该声道数的默认映射(未指定掩码会被判“无效的音频流规范”,播放直接失败)。
需要 `dwChannelMask = 0` 的多声道 WAV 时,请自行到
[github.com/TheM14/JustOneCacophony](https://github.com/TheM14/JustOneCacophony) 下载对应的 CLI
程序导出:它写 `WAVE_FORMAT_EXTENSIBLE` + `dwChannelMask = 0`,声道顺序同上表。
播放器、ASIO、DAW 或设备的输出映射要按声道编号自行完成;组件保证各 PCM 声道的内容和编号符合上表。
配置里的布局名按上表读取;无法识别的名字会记一条日志并回落到 `7.1`。
## 构建 ## 构建
```powershell ```powershell
@@ -84,8 +129,8 @@ pwsh -File tools/package.ps1 # 两个架构,打包到 dist\*.fb2k-c
配置固定为 `Release-Static`(静态 CRT,`/MT`);`/fp:precise` 是逐字节验收的前提,不要改。 配置固定为 `Release-Static`(静态 CRT,`/MT`);`/fp:precise` 是逐字节验收的前提,不要改。
`foo_input_joc.vcxproj` 通过项目引用先构建 `kernel\joc_kernel.vcxproj`;`kernel/` 里的渲染内核 `foo_input_joc.vcxproj` 通过项目引用先构建 `kernel\joc_kernel.vcxproj`;`kernel/` 里的渲染内核
源码以 `JOC_STATIC` / `EJOC_STATIC` 编译,入口既不导入也不导出。`tests\` 是离线工具(码流 源码以 `JOC_STATIC` / `EJOC_STATIC` 编译,入口既不导入也不导出。`tests\` 是离线工具(码流
自检与交叉核对、渲染比对、设置页布局检查、容器探测检查),`tools\` 是构建与测试床脚本。设置项 自检与交叉核对、渲染比对、布局表与频道顺序检查、设置页布局检查、中英文文字宽度检查、容器探测
另有 `JOC_*` 环境变量覆盖(仅用于开发运行),清单与含义在 `src\settings.cpp`。 检查),`tools\` 是构建与测试床脚本。设置项另有 `JOC_*` 环境变量覆盖(仅用于开发运行),清单与含义在 `src\settings.cpp`。
排查问题看 DLL 旁边的 `joc_decoder.log`;组件启动时会把自己的版本、核心版本、日志路径写在 排查问题看 DLL 旁边的 `joc_decoder.log`;组件启动时会把自己的版本、核心版本、日志路径写在
里面。日志按**字节**封顶:单个文件写满 16 MiB 就滚到同目录的 `joc_decoder.log.1`(覆盖上一次 里面。日志按**字节**封顶:单个文件写满 16 MiB 就滚到同目录的 `joc_decoder.log.1`(覆盖上一次
@@ -95,6 +140,10 @@ pwsh -File tools/package.ps1 # 两个架构,打包到 dist\*.fb2k-c
## 已知限制 ## 已知限制
* 不实现 ADM BWF 输出。 * 不实现 ADM BWF 输出。
* 扬声器布局到 9.1.6(16 声道)为止;内核输出上限就是 16 声道,见
[扬声器布局与声道顺序](#扬声器布局与声道顺序)。
* 多声道布局在 Properties 里不声明扬声器位置,播放时的块内映射只是 foobar2000 对该声道数的
默认值;输出映射要按声道编号自行完成(同上)。
* $joc\_dmx\_config\_idx$ 全部五个档位都支持:取床按音频帧配对,床通道数由档位决定(0/3 * $joc\_dmx\_config\_idx$ 全部五个档位都支持:取床按音频帧配对,床通道数由档位决定(0/3
为 6 通道,1/2/4 为 8 通道),ffmpeg 只在 6 通道档位传 `-ac 6`。AC-3 核心 + 依赖子流 为 6 通道,1/2/4 为 8 通道),ffmpeg 只在 6 通道档位传 `-ac 6`。AC-3 核心 + 依赖子流
(`strmtyp=1`)与"首个音频帧没有 JOC"都按正常情况处理。 (`strmtyp=1`)与"首个音频帧没有 JOC"都按正常情况处理。
+2
View File
@@ -99,6 +99,7 @@
<ClCompile Include="src\eac3_scan.cpp" /> <ClCompile Include="src\eac3_scan.cpp" />
<ClCompile Include="src\input_joc.cpp" /> <ClCompile Include="src\input_joc.cpp" />
<ClCompile Include="src\joc_decode.cpp" /> <ClCompile Include="src\joc_decode.cpp" />
<ClCompile Include="src\lang.cpp" />
<ClCompile Include="src\log.cpp" /> <ClCompile Include="src\log.cpp" />
<ClCompile Include="src\main.cpp" /> <ClCompile Include="src\main.cpp" />
<ClCompile Include="src\prefs.cpp" /> <ClCompile Include="src\prefs.cpp" />
@@ -110,6 +111,7 @@
<ClInclude Include="src\eac3_scan.h" /> <ClInclude Include="src\eac3_scan.h" />
<ClInclude Include="src\joc_decode.h" /> <ClInclude Include="src\joc_decode.h" />
<ClInclude Include="src\joc_pch.h" /> <ClInclude Include="src\joc_pch.h" />
<ClInclude Include="src\lang.h" />
<ClInclude Include="src\log.h" /> <ClInclude Include="src\log.h" />
<ClInclude Include="src\prefs.h" /> <ClInclude Include="src\prefs.h" />
<ClInclude Include="src\resource.h" /> <ClInclude Include="src\resource.h" />
+61 -21
View File
@@ -23,7 +23,7 @@ extern "C" {
#endif #endif
enum { enum {
EJOC_ABI_VERSION = 2, EJOC_ABI_VERSION = 3,
EJOC_FRAME_SAMPLES = 1536, EJOC_FRAME_SAMPLES = 1536,
EJOC_TIMESLOTS = 24, EJOC_TIMESLOTS = 24,
EJOC_SUBBANDS = 64, EJOC_SUBBANDS = 64,
@@ -35,6 +35,7 @@ enum {
EJOC_MAX_PARAMETER_BANDS = 23, EJOC_MAX_PARAMETER_BANDS = 23,
EJOC_SPEAKER_BLOCK_SAMPLES = 32, EJOC_SPEAKER_BLOCK_SAMPLES = 32,
EJOC_SPEAKER_COORDINATES = 3, EJOC_SPEAKER_COORDINATES = 3,
EJOC_SPEAKER_CONTROLS_VERSION = 1,
EJOC_BINAURAL_BLOCK_SAMPLES = 512, EJOC_BINAURAL_BLOCK_SAMPLES = 512,
EJOC_BINAURAL_INPUT_CHANNELS = 16, EJOC_BINAURAL_INPUT_CHANNELS = 16,
EJOC_BINAURAL_OUTPUT_CHANNELS = 2, EJOC_BINAURAL_OUTPUT_CHANNELS = 2,
@@ -123,6 +124,44 @@ metadata_offsets must be nondecreasing and <= sample_count. sample_count must
be a multiple of EJOC_SPEAKER_BLOCK_SAMPLES. State and unfinished ramps are be a multiple of EJOC_SPEAKER_BLOCK_SAMPLES. State and unfinished ramps are
preserved across calls. preserved across calls.
*/ */
/*
Per-object speaker controls taken from OAMD metadata: warp mode, trim mode,
the three trim levels and the two front-back balances. trim_bypass is indexed
by object slot (1..15); slot 0 carries the LFE and is unused.
warp_mode 0 leaves the floor Y coordinate unchanged; mode 1 maps it through
clamp(2Y, 0, 1). warp modes 2 and 3 have no speaker implementation and are
rejected by the caller that builds this structure.
trim_mode selects where the gain comes from: automatic applies the layout
position compensation, disabled applies no trim, and explicit applies the
position-dependent trim from centre_db / surround_db / height_db. A bypassed
object keeps its warp but loses the balance and the trim gain.
Controls may change between calls; each call's metadata events use the
controls passed with that call. A null pointer means warp 0, no trim and no
balance.
*/
typedef enum ejoc_speaker_trim_mode {
EJOC_SPEAKER_TRIM_AUTOMATIC = 0,
EJOC_SPEAKER_TRIM_DISABLED = 1,
EJOC_SPEAKER_TRIM_EXPLICIT = 2
} ejoc_speaker_trim_mode;
typedef struct ejoc_speaker_controls {
uint32_t struct_size;
uint32_t struct_version;
uint32_t warp_mode;
uint32_t trim_mode; /* ejoc_speaker_trim_mode */
double centre_db;
double surround_db; /* positive values are treated as zero */
double height_db; /* positive values are treated as zero */
double listener_balance; /* [-1, 1] */
double overhead_balance; /* [-1, 1] */
uint8_t trim_bypass[EJOC_MAX_OBJECTS + 1]; /* per object slot, slot 0 unused */
} ejoc_speaker_controls;
EJOC_API uint32_t EJOC_CALL ejoc_speaker_layout_channel_count(uint32_t speaker_bitfield); EJOC_API uint32_t EJOC_CALL ejoc_speaker_layout_channel_count(uint32_t speaker_bitfield);
EJOC_API ejoc_speaker_renderer_handle EJOC_CALL ejoc_speaker_renderer_create(uint32_t speaker_bitfield); EJOC_API ejoc_speaker_renderer_handle EJOC_CALL ejoc_speaker_renderer_create(uint32_t speaker_bitfield);
EJOC_API void EJOC_CALL ejoc_speaker_renderer_destroy(ejoc_speaker_renderer_handle handle); EJOC_API void EJOC_CALL ejoc_speaker_renderer_destroy(ejoc_speaker_renderer_handle handle);
@@ -139,6 +178,7 @@ EJOC_API int EJOC_CALL ejoc_speaker_renderer_process(
const uint8_t* region_indices, const uint8_t* region_indices,
const uint8_t* height_enabled, const uint8_t* height_enabled,
const double* object_gains, const double* object_gains,
const ejoc_speaker_controls* controls,
double* output_interleaved); double* output_interleaved);
EJOC_API ejoc_binaural_renderer_handle EJOC_CALL ejoc_binaural_renderer_create(void); EJOC_API ejoc_binaural_renderer_handle EJOC_CALL ejoc_binaural_renderer_create(void);
@@ -188,19 +228,19 @@ per-object whole-QMF-slot delay histories, six first-order image-source early
reflections, the shared unitary-FDN late room, the 120-180 Hz LFE low-pass and reflections, the shared unitary-FDN late room, the 120-180 Hz LFE low-pass and
the 961-sample latency compensation. The caller configures the filterbank the 961-sample latency compensation. The caller configures the filterbank
tables, the compiled HRTF field and the room constants once, then per 512-sample tables, the compiled HRTF field and the room constants once, then per 512-sample
block updates every source with ejoc_sofa_binaural_set_source() and calls block updates every source with ejoc_jochrtf_set_source() and calls
ejoc_sofa_binaural_process(). Process returns the number of trimmed stereo ejoc_jochrtf_process(). Process returns the number of trimmed stereo
samples written; the first 961 processed samples across calls are discarded. samples written; the first 961 processed samples across calls are discarded.
*/ */
typedef void* ejoc_sofa_binaural_handle; typedef void* ejoc_jochrtf_handle;
EJOC_API ejoc_sofa_binaural_handle EJOC_CALL ejoc_sofa_binaural_create(void); EJOC_API ejoc_jochrtf_handle EJOC_CALL ejoc_jochrtf_create(void);
EJOC_API void EJOC_CALL ejoc_sofa_binaural_destroy(ejoc_sofa_binaural_handle handle); EJOC_API void EJOC_CALL ejoc_jochrtf_destroy(ejoc_jochrtf_handle handle);
EJOC_API int EJOC_CALL ejoc_sofa_binaural_reset(ejoc_sofa_binaural_handle handle); EJOC_API int EJOC_CALL ejoc_jochrtf_reset(ejoc_jochrtf_handle handle);
EJOC_API const char* EJOC_CALL ejoc_sofa_binaural_last_error( EJOC_API const char* EJOC_CALL ejoc_jochrtf_last_error(
ejoc_sofa_binaural_handle handle); ejoc_jochrtf_handle handle);
EJOC_API int EJOC_CALL ejoc_sofa_binaural_configure_kernels( EJOC_API int EJOC_CALL ejoc_jochrtf_configure_kernels(
ejoc_sofa_binaural_handle handle, ejoc_jochrtf_handle handle,
const double* qmf_analysis, const double* qmf_analysis,
const double* hybrid_low, const double* hybrid_low,
const int16_t* hybrid_indices, const int16_t* hybrid_indices,
@@ -208,15 +248,15 @@ EJOC_API int EJOC_CALL ejoc_sofa_binaural_configure_kernels(
uint32_t hybrid_count, uint32_t hybrid_count,
const double* qmf_basis, const double* qmf_basis,
const double* qmf_taps); const double* qmf_taps);
EJOC_API int EJOC_CALL ejoc_sofa_binaural_configure_field( EJOC_API int EJOC_CALL ejoc_jochrtf_configure_field(
ejoc_sofa_binaural_handle handle, ejoc_jochrtf_handle handle,
const double* coefficients, const double* coefficients,
const double* delay_coefficients, const double* delay_coefficients,
const double* delay_bounds, const double* delay_bounds,
const double* band_centers, const double* band_centers,
double measurement_radius_m); double measurement_radius_m);
EJOC_API int EJOC_CALL ejoc_sofa_binaural_configure_room( EJOC_API int EJOC_CALL ejoc_jochrtf_configure_room(
ejoc_sofa_binaural_handle handle, ejoc_jochrtf_handle handle,
const double* room_dims, const double* room_dims,
const double* listener_pos, const double* listener_pos,
const double* wall_gains, const double* wall_gains,
@@ -229,8 +269,8 @@ EJOC_API int EJOC_CALL ejoc_sofa_binaural_configure_room(
const double* allpass_gains, const double* allpass_gains,
uint32_t enable_early_reflections, uint32_t enable_early_reflections,
uint32_t enable_late_room); uint32_t enable_late_room);
EJOC_API int EJOC_CALL ejoc_sofa_binaural_set_source( EJOC_API int EJOC_CALL ejoc_jochrtf_set_source(
ejoc_sofa_binaural_handle handle, ejoc_jochrtf_handle handle,
uint32_t source, uint32_t source,
const double* position_adm, const double* position_adm,
uint32_t profile, uint32_t profile,
@@ -238,14 +278,14 @@ EJOC_API int EJOC_CALL ejoc_sofa_binaural_set_source(
uint32_t enabled, uint32_t enabled,
uint32_t special_lfe, uint32_t special_lfe,
uint32_t fade); uint32_t fade);
EJOC_API int EJOC_CALL ejoc_sofa_binaural_process( EJOC_API int EJOC_CALL ejoc_jochrtf_process(
ejoc_sofa_binaural_handle handle, ejoc_jochrtf_handle handle,
const double* input16_interleaved, const double* input16_interleaved,
uint32_t sample_count, uint32_t sample_count,
double output_gain, double output_gain,
double* output_stereo_interleaved); double* output_stereo_interleaved);
EJOC_API int EJOC_CALL ejoc_sofa_binaural_finish( EJOC_API int EJOC_CALL ejoc_jochrtf_finish(
ejoc_sofa_binaural_handle handle, ejoc_jochrtf_handle handle,
uint32_t flush_samples, uint32_t flush_samples,
double* output_stereo_interleaved, double* output_stereo_interleaved,
uint32_t capacity); uint32_t capacity);
+14 -18
View File
@@ -39,7 +39,7 @@
#define JOC_ABI_VERSION 5u #define JOC_ABI_VERSION 5u
#define JOC_FRAME_PARAMS_VERSION 1u #define JOC_FRAME_PARAMS_VERSION 1u
#define JOC_EMDF_INFO_VERSION 1u #define JOC_EMDF_INFO_VERSION 1u
#define JOC_TASK_CONFIG_VERSION 3u #define JOC_TASK_CONFIG_VERSION 4u
#define JOC_TASK_RESULT_VERSION 2u #define JOC_TASK_RESULT_VERSION 2u
#define JOC_EVENT_VERSION 1u #define JOC_EVENT_VERSION 1u
@@ -82,7 +82,7 @@ enum {
JOC_BINAURAL_QMF_BANDS = 64, JOC_BINAURAL_QMF_BANDS = 64,
JOC_BINAURAL_HYBRID_BANDS = 77, JOC_BINAURAL_HYBRID_BANDS = 77,
JOC_QMF_HOP_SAMPLES = 64, JOC_QMF_HOP_SAMPLES = 64,
JOC_BINAURAL_LATENCY_SAMPLES = 961, JOC_BINAURAL_LATENCY_SAMPLES = 961, /* SOFA/.jochrtf and Rosella bank 1 */
JOC_LFE_DELAY_SAMPLES = 1217 JOC_LFE_DELAY_SAMPLES = 1217
}; };
@@ -358,13 +358,14 @@ typedef enum joc_clip_action {
JOC_CLIP_ABORT = 3 /* fail the task */ JOC_CLIP_ABORT = 3 /* fail the task */
} joc_clip_action; } joc_clip_action;
/* Compiled-HRTF cache policy for a SOFA input; the .jochrtf itself is an /* Which 64-QMF / 77-hybrid filterbank the Rosella .personalized_headphone path
* internal artifact of the compile step. */ * renders through. The two banks differ in coefficients, hybrid tap count,
typedef enum joc_hrtf_cache_policy { * high-band slot delay and total latency, so they are not interchangeable; the
JOC_HRTF_CACHE_NONE = 0, /* compile and discard */ * SOFA and .jochrtf paths always use JOC_ROSELLA_FILTERBANK_PUBLIC. */
JOC_HRTF_CACHE_MEMORY = 1, /* compile and keep in this process (default) */ typedef enum joc_rosella_filterbank {
JOC_HRTF_CACHE_DISK = 2 /* compile, reuse and write <cache_dir>/<name>.jochrtf */ JOC_ROSELLA_FILTERBANK_PUBLIC = 1, /* 13-tap hybrid, 6-slot delay, 961 samples */
} joc_hrtf_cache_policy; JOC_ROSELLA_FILTERBANK_CAPTURED = 2 /* 11-tap hybrid, 3-slot delay, 448 samples */
} joc_rosella_filterbank;
enum { JOC_TASK_F_SKIP_SHA256 = 1u, JOC_TASK_F_KEEP_INTERMEDIATE = 2u, enum { JOC_TASK_F_SKIP_SHA256 = 1u, JOC_TASK_F_KEEP_INTERMEDIATE = 2u,
JOC_TASK_F_QUIET = 4u, JOC_TASK_F_METADATA_ONLY = 8u }; JOC_TASK_F_QUIET = 4u, JOC_TASK_F_METADATA_ONLY = 8u };
@@ -415,16 +416,11 @@ typedef struct joc_task_config {
joc_cancel_token* cancel; /* optional */ joc_cancel_token* cancel; /* optional */
/* Binaural HRTF input (config version 2): when hrtf_sofa_path is set the /* Binaural input (config version 2): a compiled .jochrtf field (hrtf_path)
* library compiles it with hrtf_cache_policy / hrtf_cache_dir / hrtf_radius_m * or a Rosella .personalized_headphone model. */
* and hrtf_path is unused. hrtf_path stays the advanced override that reads
* a .jochrtf directly. */
const char* hrtf_sofa_path; /* SOFA SimpleFreeFieldHRIR input */
const char* personalized_headphone_path; /* Rosella .personalized_headphone input */ const char* personalized_headphone_path; /* Rosella .personalized_headphone input */
const char* hrtf_cache_dir; /* disk policy directory */ uint32_t rosella_filterbank; /* joc_rosella_filterbank; 0 = PUBLIC */
uint32_t hrtf_cache_policy; /* joc_hrtf_cache_policy */ uint32_t jochrtf_room; /* non-zero enables the project room */
uint32_t reserved0;
double hrtf_radius_m; /* SOFA measurement-radius shell */
} joc_task_config; } joc_task_config;
typedef enum joc_task_status { typedef enum joc_task_status {
+4 -10
View File
@@ -63,17 +63,11 @@ typedef struct joc_stream_config {
uint32_t object_delay_samples; /* default 1473 */ uint32_t object_delay_samples; /* default 1473 */
double gain_db; /* default 0 */ double gain_db; /* default 0 */
uint32_t native_threads; uint32_t native_threads;
uint32_t reserved; uint32_t rosella_filterbank; /* joc_rosella_filterbank; Rosella input, 0 = PUBLIC */
/* Binaural HRTF input, the same three shapes joc_task_config accepts: when /* Binaural input, the same shapes joc_task_config accepts: a compiled
* hrtf_sofa_path is set the library compiles it with hrtf_cache_policy / * .jochrtf field (hrtf_path) or a Rosella .personalized_headphone model. */
* hrtf_cache_dir / hrtf_radius_m and hrtf_path is unused; when
* personalized_headphone_path is set the Rosella runtime renders instead.
* hrtf_path stays the fallback/advanced input that reads a .jochrtf directly. */
const char* hrtf_sofa_path; /* SOFA SimpleFreeFieldHRIR input */
const char* personalized_headphone_path; /* Rosella .personalized_headphone input */ const char* personalized_headphone_path; /* Rosella .personalized_headphone input */
const char* hrtf_cache_dir; /* disk cache directory for SOFA compilation */ uint32_t jochrtf_room; /* non-zero enables the project room */
uint32_t hrtf_cache_policy; /* joc_hrtf_cache_policy: 0 none, 1 memory, 2 disk */
double hrtf_radius_m; /* SOFA measurement-radius shell, default 1.0 */
} joc_stream_config; } joc_stream_config;
typedef struct joc_stream_buffer { typedef struct joc_stream_buffer {
+3 -3
View File
@@ -8,9 +8,9 @@
#ifndef JOC_VERSION_H #ifndef JOC_VERSION_H
#define JOC_VERSION_H #define JOC_VERSION_H
#define JOC_VERSION_MAJOR 0 #define JOC_VERSION_MAJOR 1
#define JOC_VERSION_MINOR 1 #define JOC_VERSION_MINOR 2
#define JOC_VERSION_PATCH 0 #define JOC_VERSION_PATCH 0
#define JOC_VERSION_STRING "0.1.0" #define JOC_VERSION_STRING "1.2.0"
#endif /* JOC_VERSION_H */ #endif /* JOC_VERSION_H */
+14 -9
View File
@@ -149,8 +149,8 @@
<!-- Engine internals (JOC_INTERNAL_SOURCES). --> <!-- Engine internals (JOC_INTERNAL_SOURCES). -->
<ClCompile Include="src\adm\adm_metadata.cpp" /> <ClCompile Include="src\adm\adm_metadata.cpp" />
<ClCompile Include="src\adm\adm_tracks.cpp" /> <ClCompile Include="src\adm\adm_tracks.cpp" />
<ClCompile Include="src\binaural\binaural_runtime.cpp" /> <ClCompile Include="src\binaural\jochrtf_runtime.cpp" />
<ClCompile Include="src\binaural\sofa_binaural_renderer.cpp" /> <ClCompile Include="src\binaural\jochrtf_renderer.cpp" />
<ClCompile Include="src\eac3_transport\eac3_reader.cpp" /> <ClCompile Include="src\eac3_transport\eac3_reader.cpp" />
<ClCompile Include="src\emdf\emdf_parser.cpp" /> <ClCompile Include="src\emdf\emdf_parser.cpp" />
<ClCompile Include="src\foundation\bit_reader.cpp" /> <ClCompile Include="src\foundation\bit_reader.cpp" />
@@ -158,14 +158,14 @@
<ClCompile Include="src\foundation\fs_utf8.cpp" /> <ClCompile Include="src\foundation\fs_utf8.cpp" />
<ClCompile Include="src\foundation\mini_json.cpp" /> <ClCompile Include="src\foundation\mini_json.cpp" />
<ClCompile Include="src\foundation\sha256.cpp" /> <ClCompile Include="src\foundation\sha256.cpp" />
<ClCompile Include="src\foundation\status.cpp" />
<ClCompile Include="src\hrtf\jochrtf.cpp" /> <ClCompile Include="src\hrtf\jochrtf.cpp" />
<ClCompile Include="src\hrtf\public_filterbank.cpp" /> <ClCompile Include="src\hrtf\public_filterbank.cpp" />
<ClCompile Include="src\hrtf\rosella_bank.cpp" />
<ClCompile Include="src\hrtf\rosella_filterbank.cpp" />
<ClCompile Include="src\hrtf\rosella_model.cpp" /> <ClCompile Include="src\hrtf\rosella_model.cpp" />
<ClCompile Include="src\hrtf\rosella_renderer.cpp" /> <ClCompile Include="src\hrtf\rosella_renderer.cpp" />
<ClCompile Include="src\hrtf\kernel_tables.cpp" /> <ClCompile Include="src\hrtf\kernel_tables.cpp" />
<ClCompile Include="src\hrtf\sofa.cpp" />
<ClCompile Include="src\hrtf\sofa_cache.cpp" />
<ClCompile Include="src\hrtf\sofa_field.cpp" />
<ClCompile Include="src\io\adm_writer.cpp" /> <ClCompile Include="src\io\adm_writer.cpp" />
<ClCompile Include="src\io\hdf5.cpp" /> <ClCompile Include="src\io\hdf5.cpp" />
<ClCompile Include="src\io\inflate.cpp" /> <ClCompile Include="src\io\inflate.cpp" />
@@ -174,11 +174,13 @@
<ClCompile Include="src\io\process.cpp" /> <ClCompile Include="src\io\process.cpp" />
<ClCompile Include="src\io\wav_writer.cpp" /> <ClCompile Include="src\io\wav_writer.cpp" />
<ClCompile Include="src\io\zip_reader.cpp" /> <ClCompile Include="src\io\zip_reader.cpp" />
<ClCompile Include="src\joc_bitstream\bed_layout_map.cpp" />
<ClCompile Include="src\joc_bitstream\joc_parser.cpp" /> <ClCompile Include="src\joc_bitstream\joc_parser.cpp" />
<ClCompile Include="src\joc_core\objects16.cpp" /> <ClCompile Include="src\joc_core\objects16.cpp" />
<ClCompile Include="src\oamd\oamd_parser.cpp" /> <ClCompile Include="src\oamd\oamd_parser.cpp" />
<ClCompile Include="src\speaker\speaker_layout_lookup.cpp" /> <ClCompile Include="src\speaker\speaker_layout_lookup.cpp" />
<ClCompile Include="src\speaker\speaker_step.cpp" /> <ClCompile Include="src\speaker\speaker_step.cpp" />
<ClCompile Include="src\speaker\speaker_trim.cpp" />
<ClCompile Include="src\stream\stream.cpp" /> <ClCompile Include="src\stream\stream.cpp" />
<ClCompile Include="src\task\task.cpp" /> <ClCompile Include="src\task\task.cpp" />
<ClCompile Include="src\telemetry\event_bus.cpp" /> <ClCompile Include="src\telemetry\event_bus.cpp" />
@@ -222,24 +224,25 @@
<ClInclude Include="include\joc_version.h" /> <ClInclude Include="include\joc_version.h" />
<ClInclude Include="src\adm\adm_metadata.h" /> <ClInclude Include="src\adm\adm_metadata.h" />
<ClInclude Include="src\adm\adm_tracks.h" /> <ClInclude Include="src\adm\adm_tracks.h" />
<ClInclude Include="src\binaural\binaural_runtime.h" /> <ClInclude Include="src\binaural\jochrtf_runtime.h" />
<ClInclude Include="src\eac3_transport\eac3_reader.h" /> <ClInclude Include="src\eac3_transport\eac3_reader.h" />
<ClInclude Include="src\emdf\emdf_parser.h" /> <ClInclude Include="src\emdf\emdf_parser.h" />
<ClInclude Include="src\foundation\bit_reader.h" /> <ClInclude Include="src\foundation\bit_reader.h" />
<ClInclude Include="src\foundation\fft.h" /> <ClInclude Include="src\foundation\fft.h" />
<ClInclude Include="src\foundation\fs_utf8.h" /> <ClInclude Include="src\foundation\fs_utf8.h" />
<ClInclude Include="src\foundation\geometry.h" /> <ClInclude Include="src\foundation\geometry.h" />
<ClInclude Include="src\foundation\metadata_timing.h" />
<ClInclude Include="src\foundation\mini_json.h" /> <ClInclude Include="src\foundation\mini_json.h" />
<ClInclude Include="src\foundation\py_num.h" /> <ClInclude Include="src\foundation\py_num.h" />
<ClInclude Include="src\foundation\sha256.h" /> <ClInclude Include="src\foundation\sha256.h" />
<ClInclude Include="src\foundation\status.h" /> <ClInclude Include="src\foundation\status.h" />
<ClInclude Include="src\hrtf\jochrtf.h" /> <ClInclude Include="src\hrtf\jochrtf.h" />
<ClInclude Include="src\hrtf\public_filterbank.h" /> <ClInclude Include="src\hrtf\public_filterbank.h" />
<ClInclude Include="src\hrtf\rosella_bank.h" />
<ClInclude Include="src\hrtf\rosella_filterbank.h" />
<ClInclude Include="src\hrtf\rosella_filterbank_tables.h" />
<ClInclude Include="src\hrtf\rosella_model.h" /> <ClInclude Include="src\hrtf\rosella_model.h" />
<ClInclude Include="src\hrtf\rosella_renderer.h" /> <ClInclude Include="src\hrtf\rosella_renderer.h" />
<ClInclude Include="src\hrtf\sofa.h" />
<ClInclude Include="src\hrtf\sofa_cache.h" />
<ClInclude Include="src\hrtf\sofa_field.h" />
<ClInclude Include="src\io\adm_writer.h" /> <ClInclude Include="src\io\adm_writer.h" />
<ClInclude Include="src\io\hdf5.h" /> <ClInclude Include="src\io\hdf5.h" />
<ClInclude Include="src\io\inflate.h" /> <ClInclude Include="src\io\inflate.h" />
@@ -248,6 +251,7 @@
<ClInclude Include="src\io\process.h" /> <ClInclude Include="src\io\process.h" />
<ClInclude Include="src\io\wav_writer.h" /> <ClInclude Include="src\io\wav_writer.h" />
<ClInclude Include="src\io\zip_reader.h" /> <ClInclude Include="src\io\zip_reader.h" />
<ClInclude Include="src\joc_bitstream\bed_layout_map.h" />
<ClInclude Include="src\joc_bitstream\joc_huffman_tables.h" /> <ClInclude Include="src\joc_bitstream\joc_huffman_tables.h" />
<ClInclude Include="src\joc_bitstream\joc_parser.h" /> <ClInclude Include="src\joc_bitstream\joc_parser.h" />
<ClInclude Include="src\joc_core\objects16.h" /> <ClInclude Include="src\joc_core\objects16.h" />
@@ -257,6 +261,7 @@
<ClInclude Include="src\simd\simd.h" /> <ClInclude Include="src\simd\simd.h" />
<!-- src\simd\kernels_intrin_neon.cpp is excluded on every platform; see above. --> <!-- src\simd\kernels_intrin_neon.cpp is excluded on every platform; see above. -->
<ClInclude Include="src\speaker\speaker_layout_lookup.h" /> <ClInclude Include="src\speaker\speaker_layout_lookup.h" />
<ClInclude Include="src\speaker\speaker_trim.h" />
<ClInclude Include="src\speaker\speaker_layouts.h" /> <ClInclude Include="src\speaker\speaker_layouts.h" />
<ClInclude Include="src\speaker\speaker_step.h" /> <ClInclude Include="src\speaker\speaker_step.h" />
<ClInclude Include="src\stream\stream.h" /> <ClInclude Include="src\stream\stream.h" />
+105 -4
View File
@@ -54,6 +54,67 @@ std::uint8_t checksum(const std::string& segment) {
return static_cast<std::uint8_t>((~sum + 1) & 0xFF); return static_cast<std::uint8_t>((~sum + 1) & 0xFF);
} }
// OAMD trim element warp mode as the dbmd, DAMF and AXML warp field carry it:
// 0 normal, 1 warping, 2 downmix_pl2x, 3 downmix_loro.
std::uint32_t trim_warp_mode(const oamd::OamdTrim* trim) {
if (trim == nullptr) {
return 0;
}
return std::min<std::uint32_t>(trim->warp_mode, 3u);
}
// Trim records carry the balance as a sign bit plus a 7-bit magnitude on a
// 1/127 grid.
std::uint8_t balance_byte(double value) {
const long long magnitude =
std::min<long long>(pynum::py_round(std::fabs(value) * 127.0), 127);
return static_cast<std::uint8_t>(static_cast<unsigned>(magnitude) |
(value < 0.0 ? 0x80u : 0x00u));
}
void append_trim_records(const oamd::OamdTrim& trim, std::string* out) {
out->append("<DolbyTrimModeSetup>");
for (int index = 0; index < oamd::kTrimConfigs; ++index) {
const oamd::TrimConfig& record = trim.configs[index];
if (record.kind == oamd::TrimConfigKind::kAbsent) {
continue;
}
out->append("<records><type>");
out->append(std::to_string(index));
out->append("</type>");
if (record.kind == oamd::TrimConfigKind::kDefault) {
out->append("</records>");
continue;
}
const bool explicit_record = record.kind == oamd::TrimConfigKind::kExplicit;
const double centre = explicit_record ? record.centre : 0.0;
const double surround = explicit_record ? record.surround : 0.0;
const double height = explicit_record ? record.height : 0.0;
const double overhead = explicit_record ? record.balance_overhead : 0.0;
const double listener = explicit_record ? record.balance_listener : 0.0;
out->append("<centerTrim>" + pynum::format_fixed(centre, 6) + "</centerTrim>");
out->append("<surroundTrim>" + pynum::format_fixed(surround, 6) + "</surroundTrim>");
out->append("<heightTrim>" + pynum::format_fixed(height, 6) + "</heightTrim>");
out->append("<balanceOverhead>" + pynum::format_fixed(overhead, 6) +
"</balanceOverhead>");
out->append("<balanceListener>" + pynum::format_fixed(listener, 6) +
"</balanceListener>");
out->append("</records>");
}
out->append("</DolbyTrimModeSetup>");
}
void append_atmos_master_block(const oamd::OamdTrim& trim, std::string* out) {
const std::string warp = std::to_string(trim_warp_mode(&trim));
out->append("<DolbyAtmosMasterFile><DolbyMasterContentInfo><render_warp_mode>");
out->append(warp);
out->append("</render_warp_mode></DolbyMasterContentInfo>");
append_trim_records(trim, out);
out->append("<DolbyWarpMode>");
out->append(warp);
out->append("</DolbyWarpMode></DolbyAtmosMasterFile>");
}
} // namespace } // namespace
std::string ts(double seconds) { std::string ts(double seconds) {
@@ -102,7 +163,8 @@ std::string build_chna() {
return out; return out;
} }
Status build_dbmd(std::uint32_t object_count, BinauralMode mode, std::string* out) { Status build_dbmd(std::uint32_t object_count, BinauralMode mode, std::string* out,
const oamd::OamdTrim* trim) {
if (out == nullptr) { if (out == nullptr) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kOutput, "null output"); return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kOutput, "null output");
} }
@@ -125,8 +187,8 @@ Status build_dbmd(std::uint32_t object_count, BinauralMode mode, std::string* ou
out->push_back(static_cast<char>(checksum(segment7))); out->push_back(static_cast<char>(checksum(segment7)));
std::string segment9(248, '\0'); std::string segment9(248, '\0');
const std::string creator = "Created with EAC3JOC"; const std::string creator = "JustOneCacophony";
const std::string renderer = "EAC3JOC Python Renderer"; const std::string renderer = "JustOneCacophony";
std::memcpy(&segment9[0], creator.data(), creator.size()); std::memcpy(&segment9[0], creator.data(), creator.size());
std::memcpy(&segment9[32], renderer.data(), renderer.size()); std::memcpy(&segment9[32], renderer.data(), renderer.size());
segment9[96] = 2; segment9[96] = 2;
@@ -136,6 +198,10 @@ Status build_dbmd(std::uint32_t object_count, BinauralMode mode, std::string* ou
segment9[106] = 0x01; segment9[106] = 0x01;
segment9[111] = 0x22; segment9[111] = 0x22;
segment9[112] = static_cast<char>(0xFF); segment9[112] = static_cast<char>(0xFF);
// at[152]: the low three bits are the warp code, the other bits belong to
// the template's packed fields.
segment9[152] = static_cast<char>(
(static_cast<unsigned char>(segment9[152]) & 0xF8u) | trim_warp_mode(trim));
out->push_back(9); out->push_back(9);
put_u16(out, 248); put_u16(out, 248);
out->append(segment9); out->append(segment9);
@@ -151,6 +217,37 @@ Status build_dbmd(std::uint32_t object_count, BinauralMode mode, std::string* ou
for (std::size_t i = 5u + 262u; i < segment10.size(); ++i) { for (std::size_t i = 5u + 262u; i < segment10.size(); ++i) {
segment10[i] = static_cast<char>(0x84); segment10[i] = static_cast<char>(0x84);
} }
// Nine 15-byte configuration trims start at byte 7; the first byte of each
// carries the auto-trim flag in bit 0 (1 = automatic, 0 = manual). A
// configuration without an explicit record stays automatic, so a freshly
// rendered master opens with automatic trims in the renderer.
for (std::size_t layout = 0; layout < static_cast<std::size_t>(oamd::kTrimConfigs);
++layout) {
const std::size_t base = 7u + 15u * layout;
const oamd::TrimConfig* record =
trim != nullptr ? &trim->configs[layout] : nullptr;
const bool manual = record != nullptr &&
(record->kind == oamd::TrimConfigKind::kExplicit ||
record->kind == oamd::TrimConfigKind::kDisabled);
if (!manual) {
segment10[base] =
static_cast<char>(static_cast<unsigned char>(segment10[base]) | 0x01u);
continue;
}
segment10[base] = static_cast<char>(static_cast<unsigned char>(segment10[base]) & 0xFEu);
const bool explicit_record = record->kind == oamd::TrimConfigKind::kExplicit;
const double levels[3] = {explicit_record ? record->centre : 0.0,
explicit_record ? record->surround : 0.0,
explicit_record ? record->height : 0.0};
for (std::size_t index = 0; index < 3; ++index) {
const float stored = static_cast<float>(levels[index]);
std::memcpy(&segment10[base + 1u + 4u * index], &stored, sizeof(stored));
}
const double overhead = explicit_record ? record->balance_overhead : 0.0;
const double listener = explicit_record ? record->balance_listener : 0.0;
segment10[base + 13u] = static_cast<char>(balance_byte(overhead));
segment10[base + 14u] = static_cast<char>(balance_byte(listener));
}
const std::size_t object_modes = 4u + 2u + 1u + 9u * 15u + object_count; const std::size_t object_modes = 4u + 2u + 1u + 9u * 15u + object_count;
for (std::uint32_t i = 10; i < std::min<std::uint32_t>(object_count, 10u + kObjectCount); ++i) { for (std::uint32_t i = 10; i < std::min<std::uint32_t>(object_count, 10u + kObjectCount); ++i) {
const std::size_t index = object_modes + i; const std::size_t index = object_modes + i;
@@ -168,7 +265,8 @@ Status build_dbmd(std::uint32_t object_count, BinauralMode mode, std::string* ou
return Status::success(); return Status::success();
} }
std::string build_axml(const std::vector<Track>& tracks, double duration_sec, std::uint32_t rate) { std::string build_axml(const std::vector<Track>& tracks, double duration_sec, std::uint32_t rate,
const oamd::OamdTrim* trim) {
const double scale = static_cast<double>(rate); const double scale = static_cast<double>(rate);
std::string out; std::string out;
out.reserve(64u * 1024u); out.reserve(64u * 1024u);
@@ -325,6 +423,9 @@ std::string build_axml(const std::vector<Track>& tracks, double duration_sec, st
"_01</audioTrackFormatIDRef>"; "_01</audioTrackFormatIDRef>";
out += "</audioStreamFormat>"; out += "</audioStreamFormat>";
} }
if (trim != nullptr) {
append_atmos_master_block(*trim, &out);
}
out += "</audioFormatExtended></format></coreMetadata>"; out += "</audioFormatExtended></format></coreMetadata>";
out += "</ebuCoreMain>"; out += "</ebuCoreMain>";
return out; return out;
+9 -2
View File
@@ -7,6 +7,7 @@
#include <vector> #include <vector>
#include "foundation/status.h" #include "foundation/status.h"
#include "oamd/oamd_parser.h"
namespace joc::adm { namespace joc::adm {
@@ -34,10 +35,16 @@ enum class BinauralMode : std::uint32_t { Off = 0, Near = 1, Far = 2, Mid = 3, U
bool binaural_mode_from_name(const char* name, BinauralMode* out); bool binaural_mode_from_name(const char* name, BinauralMode* out);
std::string build_axml(const std::vector<Track>& tracks, double duration_sec, std::uint32_t rate); // ``trim`` is the OAMD trim element of the programme; when it is present the
// AXML carries the Dolby master-file block (content info, trim records, warp
// mode) and the dbmd chunk carries the per-configuration records and the warp
// code.
std::string build_axml(const std::vector<Track>& tracks, double duration_sec, std::uint32_t rate,
const oamd::OamdTrim* trim = nullptr);
std::string build_chna(); std::string build_chna();
Status build_dbmd(std::uint32_t object_count, BinauralMode mode, std::string* out); Status build_dbmd(std::uint32_t object_count, BinauralMode mode, std::string* out,
const oamd::OamdTrim* trim = nullptr);
} // namespace joc::adm } // namespace joc::adm
+43 -32
View File
@@ -4,6 +4,7 @@
#include <cmath> #include <cmath>
#include "foundation/geometry.h" #include "foundation/geometry.h"
#include "foundation/metadata_timing.h"
namespace joc::adm { namespace joc::adm {
@@ -66,7 +67,7 @@ Status non_monotonic(const char* name, const char* message, int object_index, st
} // namespace } // namespace
Status expand_compact(const std::vector<OamdEvent>& events, std::int64_t total_samples, std::uint32_t rate, Status expand_compact(const std::vector<OamdEvent>& events, std::int64_t total_samples, std::uint32_t rate,
std::int64_t update_quantum_samples, std::int64_t object_delay_samples, std::int64_t update_block_samples, std::int64_t object_delay_samples,
int object_index, std::vector<Keyframe>* out) { int object_index, std::vector<Keyframe>* out) {
out->clear(); out->clear();
const double scale = static_cast<double>(rate); const double scale = static_cast<double>(rate);
@@ -88,18 +89,17 @@ Status expand_compact(const std::vector<OamdEvent>& events, std::int64_t total_s
for (std::size_t index = 1; index < events.size(); ++index) { for (std::size_t index = 1; index < events.size(); ++index) {
const OamdEvent& event = events[index]; const OamdEvent& event = events[index];
const std::int64_t event_start = event.sample + object_delay_samples; const std::int64_t event_start = timing::align_metadata_sample(
event.sample + object_delay_samples, update_block_samples);
if (event_start >= total_samples) { if (event_start >= total_samples) {
break; break;
} }
const std::int64_t effective_ramp = const std::int64_t ramp = std::max<std::int64_t>(0, event.ramp_samples);
std::max<std::int64_t>(0, event.ramp_samples - update_quantum_samples); const std::int64_t block_start = event_start;
const std::int64_t block_start =
event_start + (effective_ramp != 0 ? update_quantum_samples : 0);
if (block_start >= total_samples) { if (block_start >= total_samples) {
break; break;
} }
const std::int64_t ramp_end = block_start + effective_ramp; const std::int64_t ramp_end = block_start + ramp;
if (block_start < points.back().sample) { if (block_start < points.back().sample) {
return non_monotonic("non_monotonic_compact_position_updates", return non_monotonic("non_monotonic_compact_position_updates",
@@ -107,11 +107,8 @@ Status expand_compact(const std::vector<OamdEvent>& events, std::int64_t total_s
block_start, points.back().sample); block_start, points.back().sample);
} }
if (index + 1 < events.size()) { if (index + 1 < events.size()) {
const std::int64_t next_event_start = events[index + 1].sample + object_delay_samples; const std::int64_t next_block_start = timing::align_metadata_sample(
const std::int64_t next_effective = events[index + 1].sample + object_delay_samples, update_block_samples);
std::max<std::int64_t>(0, events[index + 1].ramp_samples - update_quantum_samples);
const std::int64_t next_block_start =
next_event_start + (next_effective != 0 ? update_quantum_samples : 0);
if (next_block_start < ramp_end) { if (next_block_start < ramp_end) {
return non_monotonic("overlapping_compact_position_ramps", return non_monotonic("overlapping_compact_position_ramps",
"a new position update arrived before the previous compact " "a new position update arrived before the previous compact "
@@ -121,11 +118,10 @@ Status expand_compact(const std::vector<OamdEvent>& events, std::int64_t total_s
} }
double target[3] = {event.x, event.y, event.z}; double target[3] = {event.x, event.y, event.z};
std::int64_t interpolation = effective_ramp; std::int64_t interpolation = ramp;
const std::int64_t available = total_samples - block_start; const std::int64_t available = total_samples - block_start;
if (effective_ramp > available) { if (ramp > available) {
const double amount = const double amount = static_cast<double>(available) / static_cast<double>(ramp);
static_cast<double>(available) / static_cast<double>(effective_ramp);
double x = 0.0; double x = 0.0;
double y = 0.0; double y = 0.0;
double z = 0.0; double z = 0.0;
@@ -147,7 +143,7 @@ Status expand_compact(const std::vector<OamdEvent>& events, std::int64_t total_s
} }
Status expand_dense64(const std::vector<OamdEvent>& events, std::int64_t total_samples, std::uint32_t rate, Status expand_dense64(const std::vector<OamdEvent>& events, std::int64_t total_samples, std::uint32_t rate,
std::int64_t update_quantum_samples, std::int64_t object_delay_samples, std::int64_t update_block_samples, std::int64_t object_delay_samples,
int object_index, std::vector<Keyframe>* out) { int object_index, std::vector<Keyframe>* out) {
out->clear(); out->clear();
(void)rate; (void)rate;
@@ -164,7 +160,8 @@ Status expand_dense64(const std::vector<OamdEvent>& events, std::int64_t total_s
for (std::size_t index = 1; index < events.size(); ++index) { for (std::size_t index = 1; index < events.size(); ++index) {
const OamdEvent& event = events[index]; const OamdEvent& event = events[index];
const std::int64_t start = event.sample + object_delay_samples; const std::int64_t start =
timing::align_metadata_sample(event.sample + object_delay_samples, update_block_samples);
if (start >= total_samples) { if (start >= total_samples) {
break; break;
} }
@@ -176,20 +173,19 @@ Status expand_dense64(const std::vector<OamdEvent>& events, std::int64_t total_s
if (start > points.back().sample) { if (start > points.back().sample) {
append_point(&points, start, current[0], current[1], current[2], 0); append_point(&points, start, current[0], current[1], current[2], 0);
} }
const std::int64_t effective_ramp = const std::int64_t ramp = std::max<std::int64_t>(0, event.ramp_samples);
std::max<std::int64_t>(0, event.ramp_samples - update_quantum_samples); if (ramp == 0) {
if (effective_ramp == 0) {
append_point(&points, start, event.x, event.y, event.z, 0); append_point(&points, start, event.x, event.y, event.z, 0);
current[0] = event.x; current[0] = event.x;
current[1] = event.y; current[1] = event.y;
current[2] = event.z; current[2] = event.z;
continue; continue;
} }
const std::int64_t steps = const std::int64_t steps = (ramp + update_block_samples - 1) / update_block_samples;
(effective_ramp + update_quantum_samples - 1) / update_quantum_samples; const std::int64_t end = start + steps * update_block_samples;
const std::int64_t end = start + steps * update_quantum_samples;
if (index + 1 < events.size()) { if (index + 1 < events.size()) {
const std::int64_t next_start = events[index + 1].sample + object_delay_samples; const std::int64_t next_start = timing::align_metadata_sample(
events[index + 1].sample + object_delay_samples, update_block_samples);
if (next_start < end) { if (next_start < end) {
return non_monotonic("overlapping_position_ramps", return non_monotonic("overlapping_position_ramps",
"a new position update arrived before the previous ramp " "a new position update arrived before the previous ramp "
@@ -197,12 +193,12 @@ Status expand_dense64(const std::vector<OamdEvent>& events, std::int64_t total_s
object_index, start, end); object_index, start, end);
} }
} }
std::int64_t future = effective_ramp; std::int64_t future = ramp;
std::int64_t elapsed = 0; std::int64_t elapsed = 0;
double position[3] = {current[0], current[1], current[2]}; double position[3] = {current[0], current[1], current[2]};
while (future > 0) { while (future > 0) {
const double amount = const double amount =
std::min(static_cast<double>(update_quantum_samples) / static_cast<double>(future), std::min(static_cast<double>(update_block_samples) / static_cast<double>(future),
1.0); 1.0);
double x = 0.0; double x = 0.0;
double y = 0.0; double y = 0.0;
@@ -212,14 +208,14 @@ Status expand_dense64(const std::vector<OamdEvent>& events, std::int64_t total_s
position[0] = x; position[0] = x;
position[1] = y; position[1] = y;
position[2] = z; position[2] = z;
elapsed += update_quantum_samples; elapsed += update_block_samples;
const std::int64_t sample = start + elapsed; const std::int64_t sample = start + elapsed;
if (sample >= total_samples) { if (sample >= total_samples) {
break; break;
} }
append_point(&points, sample, position[0], position[1], position[2], append_point(&points, sample, position[0], position[1], position[2],
update_quantum_samples); update_block_samples);
future -= update_quantum_samples; future -= update_block_samples;
} }
current[0] = event.x; current[0] = event.x;
current[1] = event.y; current[1] = event.y;
@@ -240,6 +236,9 @@ void TrajectoryBuilder::submit_frame(std::int64_t frame_index, const oamd::OamdU
ramp_samples = static_cast<std::int64_t>(update->ramp_duration_samples); ramp_samples = static_cast<std::int64_t>(update->ramp_duration_samples);
} }
for (int object = 1; object <= kObjectCount; ++object) { for (int object = 1; object <= kObjectCount; ++object) {
if (fixed_[object - 1]) {
continue; // 固定 bed 声道:位置由布局给出,不跟 OAMD 更新
}
double x = 0.0; double x = 0.0;
double y = 0.0; double y = 0.0;
double z = 0.0; double z = 0.0;
@@ -264,11 +263,23 @@ Status TrajectoryBuilder::build(std::int64_t total_samples, TrajectoryMode mode,
for (int object = 1; object <= kObjectCount; ++object) { for (int object = 1; object <= kObjectCount; ++object) {
Track track; Track track;
track.name = "JOC_Object_" + std::to_string(object); track.name = "JOC_Object_" + std::to_string(object);
if (fixed_[object - 1]) {
Keyframe block;
block.rtime_samples = 0;
block.x = fixed_xyz_[object - 1][0];
block.y = fixed_xyz_[object - 1][1];
block.z = fixed_xyz_[object - 1][2];
block.duration_samples = total_samples;
block.interpolation_samples = 0;
track.blocks.push_back(block);
out->push_back(std::move(track));
continue;
}
const Status status = const Status status =
(mode == TrajectoryMode::Compact) (mode == TrajectoryMode::Compact)
? expand_compact(events_[object - 1], total_samples, rate_, quantum_, ? expand_compact(events_[object - 1], total_samples, rate_, block_,
object_delay_, object, &track.blocks) object_delay_, object, &track.blocks)
: expand_dense64(events_[object - 1], total_samples, rate_, quantum_, : expand_dense64(events_[object - 1], total_samples, rate_, block_,
object_delay_, object, &track.blocks); object_delay_, object, &track.blocks);
if (!status.ok()) { if (!status.ok()) {
return status; return status;
+21 -5
View File
@@ -7,6 +7,7 @@
#include <vector> #include <vector>
#include "adm/adm_metadata.h" #include "adm/adm_metadata.h"
#include "foundation/metadata_timing.h"
#include "foundation/status.h" #include "foundation/status.h"
#include "oamd/oamd_parser.h" #include "oamd/oamd_parser.h"
@@ -26,36 +27,51 @@ enum class TrajectoryMode { Compact, Dense64 };
// runs, and records one event per object whenever its coordinates change. // runs, and records one event per object whenever its coordinates change.
class TrajectoryBuilder { class TrajectoryBuilder {
public: public:
TrajectoryBuilder(std::uint32_t rate = 48000, std::int64_t update_quantum_samples = 64, TrajectoryBuilder(std::uint32_t rate = 48000,
std::int64_t update_block_samples = timing::kMetadataBlockSamples,
std::int64_t object_delay_samples = 1473) std::int64_t object_delay_samples = 1473)
: rate_(rate), : rate_(rate),
quantum_(update_quantum_samples), block_(update_block_samples),
object_delay_(object_delay_samples) {} object_delay_(object_delay_samples) {}
void submit_frame(std::int64_t frame_index, const oamd::OamdUpdate* update, std::int64_t outer_offset); void submit_frame(std::int64_t frame_index, const oamd::OamdUpdate* update, std::int64_t outer_offset);
Status build(std::int64_t total_samples, TrajectoryMode mode, std::vector<Track>* out) const; Status build(std::int64_t total_samples, TrajectoryMode mode, std::vector<Track>* out) const;
// bed 声道是固定通道:OAMD 不给位置,整片静止在声明的 bed 方位。
void set_fixed_position(int object_index, double x, double y, double z) {
if (object_index < 1 || object_index > kObjectCount) {
return;
}
const int slot = object_index - 1;
fixed_[slot] = true;
fixed_xyz_[slot][0] = x;
fixed_xyz_[slot][1] = y;
fixed_xyz_[slot][2] = z;
}
const std::vector<OamdEvent>& events(int object_index) const { return events_[object_index]; } const std::vector<OamdEvent>& events(int object_index) const { return events_[object_index]; }
std::uint32_t rate() const { return rate_; } std::uint32_t rate() const { return rate_; }
std::int64_t object_delay_samples() const { return object_delay_; } std::int64_t object_delay_samples() const { return object_delay_; }
private: private:
std::uint32_t rate_; std::uint32_t rate_;
std::int64_t quantum_; std::int64_t block_;
std::int64_t object_delay_; std::int64_t object_delay_;
oamd::OamdState state_; oamd::OamdState state_;
std::vector<OamdEvent> events_[kObjectCount]; std::vector<OamdEvent> events_[kObjectCount];
bool has_previous_[kObjectCount] = {}; bool has_previous_[kObjectCount] = {};
double previous_[kObjectCount][3] = {}; double previous_[kObjectCount][3] = {};
bool fixed_[kObjectCount] = {};
double fixed_xyz_[kObjectCount][3] = {};
}; };
Status expand_compact(const std::vector<OamdEvent>& events, std::int64_t total_samples, std::uint32_t rate, Status expand_compact(const std::vector<OamdEvent>& events, std::int64_t total_samples, std::uint32_t rate,
std::int64_t update_quantum_samples, std::int64_t object_delay_samples, std::int64_t update_block_samples, std::int64_t object_delay_samples,
int object_index, std::vector<Keyframe>* out); int object_index, std::vector<Keyframe>* out);
Status expand_dense64(const std::vector<OamdEvent>& events, std::int64_t total_samples, std::uint32_t rate, Status expand_dense64(const std::vector<OamdEvent>& events, std::int64_t total_samples, std::uint32_t rate,
std::int64_t update_quantum_samples, std::int64_t object_delay_samples, std::int64_t update_block_samples, std::int64_t object_delay_samples,
int object_index, std::vector<Keyframe>* out); int object_index, std::vector<Keyframe>* out);
} // namespace joc::adm } // namespace joc::adm
+6 -7
View File
@@ -36,16 +36,15 @@ joc::stream::Config to_config(const joc_stream_config& config) {
} }
out.gain_db = config.gain_db; out.gain_db = config.gain_db;
out.native_threads = config.native_threads; out.native_threads = config.native_threads;
// The binaural HRTF inputs of joc_task_config, copied with the same defaults:
// the policy is taken verbatim (0 is "none", a real choice, not "unset") and
// the radius keeps its documented default of 1.0 when the field is not set.
if (config.hrtf_sofa_path != nullptr) { out.hrtf_sofa_path = config.hrtf_sofa_path; }
if (config.personalized_headphone_path != nullptr) { if (config.personalized_headphone_path != nullptr) {
out.personalized_headphone_path = config.personalized_headphone_path; out.personalized_headphone_path = config.personalized_headphone_path;
} }
if (config.hrtf_cache_dir != nullptr) { out.hrtf_cache_dir = config.hrtf_cache_dir; } // 0 is the documented "off" spelling for the room switch.
out.hrtf_cache_policy = config.hrtf_cache_policy; out.jochrtf_room = config.jochrtf_room;
if (config.hrtf_radius_m > 0.0) { out.hrtf_radius_m = config.hrtf_radius_m; } // 0 is "unset" here as well: the Rosella path defaults to the public bank.
if (config.rosella_filterbank != 0u) {
out.rosella_filterbank = config.rosella_filterbank;
}
return out; return out;
} }
@@ -1,7 +1,7 @@
// Derived from the upstream native/src/sofa_binaural_renderer.cpp (JustOneCacophony // Derived from the upstream native/src/sofa_binaural_renderer.cpp (JustOneCacophony
// @ 6bc2c2885666bb151bb66af93472199af9a99b81, sha256 81b485e4c71907672ab308ddc38228 // @ 6bc2c2885666bb151bb66af93472199af9a99b81, sha256 81b485e4c71907672ab308ddc38228
// 4acf29161cee93d7906785a4cce58941c7) and a drop-in replacement for it: the same // 4acf29161cee93d7906785a4cce58941c7) and a drop-in replacement for it: the same
// ejoc_sofa_binaural_* C ABI. The changes are table hoisting, result memoisation, // ejoc_jochrtf_* C ABI. The changes are table hoisting, result memoisation,
// input validation and a dispatched SIMD cascade -- no arithmetic is reordered, // input validation and a dispatched SIMD cascade -- no arithmetic is reordered,
// reassociated or contracted, so the output is bit-identical to the upstream // reassociated or contracted, so the output is bit-identical to the upstream
// implementation (verified: identical FNV-1a over the exact output bit patterns at // implementation (verified: identical FNV-1a over the exact output bit patterns at
@@ -1378,7 +1378,7 @@ using ejoc::sofa_binaural::Renderer;
extern "C" { extern "C" {
ejoc_sofa_binaural_handle EJOC_CALL ejoc_sofa_binaural_create(void) { ejoc_jochrtf_handle EJOC_CALL ejoc_jochrtf_create(void) {
try { try {
return new (std::nothrow) Renderer(); return new (std::nothrow) Renderer();
} catch (...) { } catch (...) {
@@ -1386,21 +1386,21 @@ ejoc_sofa_binaural_handle EJOC_CALL ejoc_sofa_binaural_create(void) {
} }
} }
void EJOC_CALL ejoc_sofa_binaural_destroy(ejoc_sofa_binaural_handle handle) { void EJOC_CALL ejoc_jochrtf_destroy(ejoc_jochrtf_handle handle) {
delete static_cast<Renderer*>(handle); delete static_cast<Renderer*>(handle);
} }
int EJOC_CALL ejoc_sofa_binaural_reset(ejoc_sofa_binaural_handle handle) { int EJOC_CALL ejoc_jochrtf_reset(ejoc_jochrtf_handle handle) {
return handle ? static_cast<Renderer*>(handle)->reset() : -1; return handle ? static_cast<Renderer*>(handle)->reset() : -1;
} }
const char* EJOC_CALL ejoc_sofa_binaural_last_error( const char* EJOC_CALL ejoc_jochrtf_last_error(
ejoc_sofa_binaural_handle handle) { ejoc_jochrtf_handle handle) {
return handle ? static_cast<Renderer*>(handle)->error() : "null handle"; return handle ? static_cast<Renderer*>(handle)->error() : "null handle";
} }
int EJOC_CALL ejoc_sofa_binaural_configure_kernels( int EJOC_CALL ejoc_jochrtf_configure_kernels(
ejoc_sofa_binaural_handle handle, const double* qmf_analysis, ejoc_jochrtf_handle handle, const double* qmf_analysis,
const double* hybrid_low, const int16_t* hybrid_indices, const double* hybrid_low, const int16_t* hybrid_indices,
const double* hybrid_values, uint32_t hybrid_count, const double* qmf_basis, const double* hybrid_values, uint32_t hybrid_count, const double* qmf_basis,
const double* qmf_taps) { const double* qmf_taps) {
@@ -1409,8 +1409,8 @@ int EJOC_CALL ejoc_sofa_binaural_configure_kernels(
qmf_basis, qmf_taps) : -1; qmf_basis, qmf_taps) : -1;
} }
int EJOC_CALL ejoc_sofa_binaural_configure_field( int EJOC_CALL ejoc_jochrtf_configure_field(
ejoc_sofa_binaural_handle handle, const double* coefficients, ejoc_jochrtf_handle handle, const double* coefficients,
const double* delay_coefficients, const double* delay_bounds, const double* delay_coefficients, const double* delay_bounds,
const double* band_centers, double measurement_radius_m) { const double* band_centers, double measurement_radius_m) {
return handle ? static_cast<Renderer*>(handle)->configure_field( return handle ? static_cast<Renderer*>(handle)->configure_field(
@@ -1418,8 +1418,8 @@ int EJOC_CALL ejoc_sofa_binaural_configure_field(
measurement_radius_m) : -1; measurement_radius_m) : -1;
} }
int EJOC_CALL ejoc_sofa_binaural_configure_room( int EJOC_CALL ejoc_jochrtf_configure_room(
ejoc_sofa_binaural_handle handle, const double* room_dims, ejoc_jochrtf_handle handle, const double* room_dims,
const double* listener_pos, const double* wall_gains, double speed_of_sound, const double* listener_pos, const double* wall_gains, double speed_of_sound,
const uint32_t* fdn_delays, const double* fdn_feedback, double damping, const uint32_t* fdn_delays, const double* fdn_feedback, double damping,
double fdn_output_gain, const uint32_t* allpass_delays, double fdn_output_gain, const uint32_t* allpass_delays,
@@ -1430,24 +1430,24 @@ int EJOC_CALL ejoc_sofa_binaural_configure_room(
enable_early, enable_late) : -1; enable_early, enable_late) : -1;
} }
int EJOC_CALL ejoc_sofa_binaural_set_source( int EJOC_CALL ejoc_jochrtf_set_source(
ejoc_sofa_binaural_handle handle, uint32_t source, const double* position_adm, ejoc_jochrtf_handle handle, uint32_t source, const double* position_adm,
uint32_t profile, double gain, uint32_t enabled, uint32_t special_lfe, uint32_t profile, double gain, uint32_t enabled, uint32_t special_lfe,
uint32_t fade) { uint32_t fade) {
return handle ? static_cast<Renderer*>(handle)->set_source( return handle ? static_cast<Renderer*>(handle)->set_source(
source, position_adm, profile, gain, enabled, special_lfe, fade) : -1; source, position_adm, profile, gain, enabled, special_lfe, fade) : -1;
} }
int EJOC_CALL ejoc_sofa_binaural_process( int EJOC_CALL ejoc_jochrtf_process(
ejoc_sofa_binaural_handle handle, const double* input16_interleaved, ejoc_jochrtf_handle handle, const double* input16_interleaved,
uint32_t sample_count, double output_gain, double* output_stereo_interleaved) { uint32_t sample_count, double output_gain, double* output_stereo_interleaved) {
return handle ? static_cast<Renderer*>(handle)->process( return handle ? static_cast<Renderer*>(handle)->process(
input16_interleaved, sample_count, output_gain, output_stereo_interleaved) input16_interleaved, sample_count, output_gain, output_stereo_interleaved)
: -1; : -1;
} }
int EJOC_CALL ejoc_sofa_binaural_finish( int EJOC_CALL ejoc_jochrtf_finish(
ejoc_sofa_binaural_handle handle, uint32_t flush_samples, ejoc_jochrtf_handle handle, uint32_t flush_samples,
double* output_stereo_interleaved, uint32_t capacity) { double* output_stereo_interleaved, uint32_t capacity) {
return handle ? static_cast<Renderer*>(handle)->finish( return handle ? static_cast<Renderer*>(handle)->finish(
flush_samples, output_stereo_interleaved, capacity) : -1; flush_samples, output_stereo_interleaved, capacity) : -1;
@@ -1,4 +1,4 @@
#include "binaural/binaural_runtime.h" #include "binaural/jochrtf_runtime.h"
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
@@ -29,14 +29,14 @@ bool profile_from_name(const char* name, Profile* out) {
return false; return false;
} }
SofaBinauralRuntime::~SofaBinauralRuntime() { JochrtfRuntime::~JochrtfRuntime() {
if (handle_ != nullptr) { if (handle_ != nullptr) {
ejoc_sofa_binaural_destroy(handle_); ejoc_jochrtf_destroy(handle_);
handle_ = nullptr; handle_ = nullptr;
} }
} }
Status SofaBinauralRuntime::open(const hrtf::Field& field, const hrtf::Kernels& kernels, Status JochrtfRuntime::open(const hrtf::Field& field, const hrtf::Kernels& kernels,
Profile profile, const RoomConstants& room) { Profile profile, const RoomConstants& room) {
if (handle_ != nullptr) { if (handle_ != nullptr) {
return Status::fail(JOC_ERR_STATE, stage::kRender, "binaural runtime already open"); return Status::fail(JOC_ERR_STATE, stage::kRender, "binaural runtime already open");
@@ -47,36 +47,36 @@ Status SofaBinauralRuntime::open(const hrtf::Field& field, const hrtf::Kernels&
return Status::fail(JOC_ERR_HRTF_FORMAT, stage::kRender, return Status::fail(JOC_ERR_HRTF_FORMAT, stage::kRender,
"compiled HRTF field has unexpected array sizes"); "compiled HRTF field has unexpected array sizes");
} }
handle_ = ejoc_sofa_binaural_create(); handle_ = ejoc_jochrtf_create();
if (handle_ == nullptr) { if (handle_ == nullptr) {
return Status::fail(JOC_ERR_OUT_OF_MEMORY, stage::kRender, return Status::fail(JOC_ERR_OUT_OF_MEMORY, stage::kRender,
"ejoc_sofa_binaural_create failed"); "ejoc_jochrtf_create failed");
} }
profile_ = profile; profile_ = profile;
if (ejoc_sofa_binaural_configure_kernels( if (ejoc_jochrtf_configure_kernels(
handle_, kernels.qmf_analysis.data(), kernels.hybrid_low.data(), handle_, kernels.qmf_analysis.data(), kernels.hybrid_low.data(),
kernels.hybrid_indices.data(), kernels.hybrid_values.data(), kernels.hybrid_count, kernels.hybrid_indices.data(), kernels.hybrid_values.data(), kernels.hybrid_count,
kernels.qmf_basis.data(), kernels.qmf_taps.data()) != 0) { kernels.qmf_basis.data(), kernels.qmf_taps.data()) != 0) {
const char* message = ejoc_sofa_binaural_last_error(handle_); const char* message = ejoc_jochrtf_last_error(handle_);
return Status::fail(JOC_ERR_HRTF_FORMAT, stage::kRender, return Status::fail(JOC_ERR_HRTF_FORMAT, stage::kRender,
std::string("configure_kernels failed: ") + std::string("configure_kernels failed: ") +
(message != nullptr ? message : "unknown")); (message != nullptr ? message : "unknown"));
} }
if (ejoc_sofa_binaural_configure_field(handle_, field.coefficients.data(), if (ejoc_jochrtf_configure_field(handle_, field.coefficients.data(),
field.delay_coefficients.data(), field.delay_coefficients.data(),
field.delay_bounds.data(), field.band_centers_hz.data(), field.delay_bounds.data(), field.band_centers_hz.data(),
field.measurement_radius_m) != 0) { field.measurement_radius_m) != 0) {
const char* message = ejoc_sofa_binaural_last_error(handle_); const char* message = ejoc_jochrtf_last_error(handle_);
return Status::fail(JOC_ERR_HRTF_FORMAT, stage::kRender, return Status::fail(JOC_ERR_HRTF_FORMAT, stage::kRender,
std::string("configure_field failed: ") + std::string("configure_field failed: ") +
(message != nullptr ? message : "unknown")); (message != nullptr ? message : "unknown"));
} }
if (ejoc_sofa_binaural_configure_room( if (ejoc_jochrtf_configure_room(
handle_, room.dims, room.listener, room.walls, room.speed_of_sound, room.fdn_delays, handle_, room.dims, room.listener, room.walls, room.speed_of_sound, room.fdn_delays,
room.fdn_feedback, room.damping, room.fdn_output_gain, room.allpass_delays, room.fdn_feedback, room.damping, room.fdn_output_gain, room.allpass_delays,
room.allpass_gains, room.enable_early_reflections, room.enable_late_room) != 0) { room.allpass_gains, room.enable_early_reflections, room.enable_late_room) != 0) {
const char* message = ejoc_sofa_binaural_last_error(handle_); const char* message = ejoc_jochrtf_last_error(handle_);
return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender, return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender,
std::string("configure_room failed: ") + std::string("configure_room failed: ") +
(message != nullptr ? message : "unknown")); (message != nullptr ? message : "unknown"));
@@ -95,7 +95,7 @@ Status SofaBinauralRuntime::open(const hrtf::Field& field, const hrtf::Kernels&
return Status::success(); return Status::success();
} }
Status SofaBinauralRuntime::process_block() { Status JochrtfRuntime::process_block() {
double positions[timeline::kTimelineObjects][3] = {}; double positions[timeline::kTimelineObjects][3] = {};
const Status queried = timeline_.positions_at(static_cast<std::int64_t>(processed_samples_), const Status queried = timeline_.positions_at(static_cast<std::int64_t>(processed_samples_),
positions); positions);
@@ -106,28 +106,28 @@ Status SofaBinauralRuntime::process_block() {
// backend default (fade enabled) applies - the per-object path crossfade is // backend default (fade enabled) applies - the per-object path crossfade is
// part of the reference behaviour, not an optional extra. // part of the reference behaviour, not an optional extra.
constexpr std::uint32_t kFade = 1u; constexpr std::uint32_t kFade = 1u;
if (ejoc_sofa_binaural_set_source(handle_, 0u, kLfePosition, if (ejoc_jochrtf_set_source(handle_, 0u, kLfePosition,
static_cast<std::uint32_t>(profile_), 1.0, 1u, 1u, static_cast<std::uint32_t>(profile_), 1.0, 1u, 1u,
kFade) != 0) { kFade) != 0) {
const char* message = ejoc_sofa_binaural_last_error(handle_); const char* message = ejoc_jochrtf_last_error(handle_);
return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender, return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender,
std::string("set_source(LFE) failed: ") + std::string("set_source(LFE) failed: ") +
(message != nullptr ? message : "unknown")); (message != nullptr ? message : "unknown"));
} }
for (std::uint32_t source = 0; source < timeline::kTimelineObjects; ++source) { for (std::uint32_t source = 0; source < timeline::kTimelineObjects; ++source) {
if (ejoc_sofa_binaural_set_source(handle_, source + 1u, positions[source], if (ejoc_jochrtf_set_source(handle_, source + 1u, positions[source],
static_cast<std::uint32_t>(profile_), 1.0, 1u, 0u, static_cast<std::uint32_t>(profile_), 1.0, 1u, 0u,
kFade) != 0) { kFade) != 0) {
const char* message = ejoc_sofa_binaural_last_error(handle_); const char* message = ejoc_jochrtf_last_error(handle_);
return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender, return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender,
std::string("set_source(object ") + std::to_string(source + 1u) + std::string("set_source(object ") + std::to_string(source + 1u) +
") failed: " + (message != nullptr ? message : "unknown")); ") failed: " + (message != nullptr ? message : "unknown"));
} }
} }
const int trimmed = ejoc_sofa_binaural_process(handle_, staging_.data(), kBlockSamples, 1.0, const int trimmed = ejoc_jochrtf_process(handle_, staging_.data(), kBlockSamples, 1.0,
block_output_.data()); block_output_.data());
if (trimmed < 0) { if (trimmed < 0) {
const char* message = ejoc_sofa_binaural_last_error(handle_); const char* message = ejoc_jochrtf_last_error(handle_);
return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender, return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender,
std::string("sofa process failed: ") + std::string("sofa process failed: ") +
(message != nullptr ? message : "unknown")); (message != nullptr ? message : "unknown"));
@@ -142,7 +142,7 @@ Status SofaBinauralRuntime::process_block() {
return Status::success(); return Status::success();
} }
Status SofaBinauralRuntime::submit_frame(const float* objects16_planar, Status JochrtfRuntime::submit_frame(const float* objects16_planar,
const oamd::OamdUpdate* update, std::int64_t frame_index, const oamd::OamdUpdate* update, std::int64_t frame_index,
std::int64_t outer_sample_offset, std::int64_t outer_sample_offset,
std::int64_t object_delay_samples) { std::int64_t object_delay_samples) {
@@ -186,7 +186,7 @@ Status SofaBinauralRuntime::submit_frame(const float* objects16_planar,
return Status::success(); return Status::success();
} }
std::uint32_t SofaBinauralRuntime::finish_capacity(double tail_seconds) const { std::uint32_t JochrtfRuntime::finish_capacity(double tail_seconds) const {
std::int64_t requested = tail_samples_; std::int64_t requested = tail_samples_;
if (tail_seconds >= 0.0) { if (tail_seconds >= 0.0) {
requested = static_cast<std::int64_t>(std::ceil(tail_seconds * 48000.0 - 1e-9)); requested = static_cast<std::int64_t>(std::ceil(tail_seconds * 48000.0 - 1e-9));
@@ -198,14 +198,14 @@ std::uint32_t SofaBinauralRuntime::finish_capacity(double tail_seconds) const {
return static_cast<std::uint32_t>(drain); return static_cast<std::uint32_t>(drain);
} }
Status SofaBinauralRuntime::reset() { Status JochrtfRuntime::reset() {
if (handle_ == nullptr) { if (handle_ == nullptr) {
return Status::fail(JOC_ERR_STATE, stage::kRender, "binaural runtime is not open"); return Status::fail(JOC_ERR_STATE, stage::kRender, "binaural runtime is not open");
} }
if (ejoc_sofa_binaural_reset(handle_) != 0) { if (ejoc_jochrtf_reset(handle_) != 0) {
return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender, "sofa reset failed"); return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender, "sofa reset failed");
} }
timeline_ = timeline::OamdPositionTimeline(); timeline_.reset();
output_.clear(); output_.clear();
staged_ = 0; staged_ = 0;
input_samples_ = 0; input_samples_ = 0;
@@ -214,7 +214,7 @@ Status SofaBinauralRuntime::reset() {
return Status::success(); return Status::success();
} }
Status SofaBinauralRuntime::finish(std::uint32_t flush_samples, std::vector<double>* out) { Status JochrtfRuntime::finish(std::uint32_t flush_samples, std::vector<double>* out) {
if (handle_ == nullptr) { if (handle_ == nullptr) {
return Status::fail(JOC_ERR_STATE, stage::kRender, "binaural runtime is not open"); return Status::fail(JOC_ERR_STATE, stage::kRender, "binaural runtime is not open");
} }
@@ -230,9 +230,9 @@ Status SofaBinauralRuntime::finish(std::uint32_t flush_samples, std::vector<doub
std::uint32_t remaining = flush_samples; std::uint32_t remaining = flush_samples;
while (remaining > 0) { while (remaining > 0) {
const std::uint32_t request = std::min<std::uint32_t>(remaining, kBlockSamples); const std::uint32_t request = std::min<std::uint32_t>(remaining, kBlockSamples);
const int produced = ejoc_sofa_binaural_finish(handle_, request, chunk.data(), request); const int produced = ejoc_jochrtf_finish(handle_, request, chunk.data(), request);
if (produced < 0) { if (produced < 0) {
const char* message = ejoc_sofa_binaural_last_error(handle_); const char* message = ejoc_jochrtf_last_error(handle_);
return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender, return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender,
std::string("sofa finish failed: ") + std::string("sofa finish failed: ") +
(message != nullptr ? message : "unknown")); (message != nullptr ? message : "unknown"));
@@ -38,13 +38,13 @@ enum class Profile : std::uint32_t { Near = 0, Mid = 1, Far = 2 };
bool profile_from_name(const char* name, Profile* out); bool profile_from_name(const char* name, Profile* out);
class SofaBinauralRuntime { class JochrtfRuntime {
public: public:
SofaBinauralRuntime() = default; JochrtfRuntime() = default;
~SofaBinauralRuntime(); ~JochrtfRuntime();
SofaBinauralRuntime(const SofaBinauralRuntime&) = delete; JochrtfRuntime(const JochrtfRuntime&) = delete;
SofaBinauralRuntime& operator=(const SofaBinauralRuntime&) = delete; JochrtfRuntime& operator=(const JochrtfRuntime&) = delete;
Status open(const hrtf::Field& field, const hrtf::Kernels& kernels, Profile profile, Status open(const hrtf::Field& field, const hrtf::Kernels& kernels, Profile profile,
const RoomConstants& room = RoomConstants{}); const RoomConstants& room = RoomConstants{});
@@ -72,13 +72,18 @@ public:
std::size_t staged_samples() const { return staged_; } std::size_t staged_samples() const { return staged_; }
const timeline::OamdPositionTimeline& timeline() const { return timeline_; } const timeline::OamdPositionTimeline& timeline() const { return timeline_; }
// bed 声道是固定通道:OAMD 不给位置,方位由声明的 bed 布局给出。
void set_fixed_position(int object_index, const double position[3]) {
timeline_.set_fixed_position(object_index, position);
}
// finish_output_capacity as the reference computes it (plan 21.4). // finish_output_capacity as the reference computes it (plan 21.4).
std::uint32_t finish_capacity(double tail_seconds) const; std::uint32_t finish_capacity(double tail_seconds) const;
private: private:
Status process_block(); Status process_block();
ejoc_sofa_binaural_handle handle_ = nullptr; ejoc_jochrtf_handle handle_ = nullptr;
Profile profile_ = Profile::Mid; Profile profile_ = Profile::Mid;
timeline::OamdPositionTimeline timeline_; timeline::OamdPositionTimeline timeline_;
std::vector<double> staging_; std::vector<double> staging_;
+46 -100
View File
@@ -4,7 +4,7 @@
// choices and defaults, and the same default output naming under output/. // choices and defaults, and the same default output naming under output/.
// //
// Options that exist only because this build has no Python side or no Rosella // Options that exist only because this build has no Python side or no Rosella
// import chain (--backend python, --sofa-hrtf, --personalized-headphone, // import chain (--backend python, --personalized-headphone,
// metadata sidecars) fail with an explicit message instead of being ignored. // metadata sidecars) fail with an explicit message instead of being ignored.
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
@@ -40,13 +40,12 @@ struct Options {
std::string clip_action = "ask"; std::string clip_action = "ask";
int speaker_metadata_offset = 1473; int speaker_metadata_offset = 1473;
std::string binaural_mode = "mid"; std::string binaural_mode = "mid";
std::string sofa_hrtf;
std::string compiled_hrtf_cache; std::string compiled_hrtf_cache;
std::string jochrtf_room = "on";
std::string personalized_headphone; std::string personalized_headphone;
bool personalized_headphone_used = false; bool personalized_headphone_used = false;
std::string hrtf_cache_policy; int rosella_filterbank = 1;
std::string hrtf_cache_dir; bool rosella_filterbank_set = false;
double hrtf_radius_m = 1.0;
double binaural_tail_seconds = 5.0; double binaural_tail_seconds = 5.0;
double binaural_tail_threshold = 1.0e-8; double binaural_tail_threshold = 1.0e-8;
int binaural_chunk_frames = 64; int binaural_chunk_frames = 64;
@@ -84,7 +83,7 @@ struct Options {
}; };
const char* kLayoutChoices = const char* kLayoutChoices =
"2.0 3.0 3.1 4.0 5.0 5.1 5.1.2 5.1.4 6.1 7.0 7.1 7.1.2 7.1.4 9.1.4 9.1.6 22.2"; "2.0 3.1 4.0 5.1 7.1 5.1.2 5.1.4 7.1.2 7.1.4 9.1.4 9.1.6";
void print_usage() { void print_usage() {
std::printf( std::printf(
@@ -115,13 +114,12 @@ void print_usage() {
" --speaker-metadata-offset N 扬声器渲染 metadata 相对帧偏移,默认 1473 samples\n" " --speaker-metadata-offset N 扬声器渲染 metadata 相对帧偏移,默认 1473 samples\n"
" --binaural-mode M 双耳渲染模式 off|near|mid|far,默认 mid;\n" " --binaural-mode M 双耳渲染模式 off|near|mid|far,默认 mid;\n"
" off 仅用于 ADM BWF(关闭 DBMD 双耳提示)\n" " off 仅用于 ADM BWF(关闭 DBMD 双耳提示)\n"
" --sofa-hrtf PATH SOFA SimpleFreeFieldHRIR 输入;.jochrtf 由本工具内部编译\n"
" --personalized-headphone [PATH] Rosella 个性化模型,默认 " " --personalized-headphone [PATH] Rosella 个性化模型,默认 "
"HRTF/binaural.personalized_headphone\n" "HRTF/binaural.personalized_headphone\n"
" --compiled-hrtf-cache PATH 直接读取 .jochrtf(高级用法,跳过 SOFA 编译)\n" " --rosella-filterbank N Rosella 模型滤波器组:1=13 taps/6 slots(默认),\n"
" --hrtf-cache-policy P SOFA 编译缓存策略 none|memory|disk,默认 memory\n" " 2=11 taps/3 slots;仅作用于个性化模型\n"
" --hrtf-cache-dir DIR disk cache 目录,默认 <exe>/output/hrtf-cache\n" " --compiled-hrtf-cache PATH 读取离线编译好的 .jochrtf\n"
" --hrtf-radius-m R 选择最近的 SOFA measurement-radius shell,默认 1.0 m\n" " --jochrtf-room on|off .jochrtf 的项目房间,默认 on;off 只输出直达声\n"
" --binaural-tail-seconds S 双耳 room/filterbank flush 上限,默认 5 秒\n" " --binaural-tail-seconds S 双耳 room/filterbank flush 上限,默认 5 秒\n"
" --binaural-tail-threshold T 双耳尾声裁切阈值,默认 1e-8;主体至少保留原时长\n" " --binaural-tail-threshold T 双耳尾声裁切阈值,默认 1e-8;主体至少保留原时长\n"
" --binaural-chunk-frames N 双耳内部批处理帧数,默认 64(本构建按 512 块渲染,\n" " --binaural-chunk-frames N 双耳内部批处理帧数,默认 64(本构建按 512 块渲染,\n"
@@ -227,8 +225,8 @@ void parse_args(const std::vector<std::string>& arguments, Options* options) {
to_int(require_value(arguments, &index), "--speaker-metadata-offset")); to_int(require_value(arguments, &index), "--speaker-metadata-offset"));
} }
else if (arg == "--binaural-mode") { options->binaural_mode = require_value(arguments, &index); } else if (arg == "--binaural-mode") { options->binaural_mode = require_value(arguments, &index); }
else if (arg == "--sofa-hrtf") { options->sofa_hrtf = require_value(arguments, &index); }
else if (arg == "--compiled-hrtf-cache") { options->compiled_hrtf_cache = require_value(arguments, &index); } else if (arg == "--compiled-hrtf-cache") { options->compiled_hrtf_cache = require_value(arguments, &index); }
else if (arg == "--jochrtf-room") { options->jochrtf_room = require_value(arguments, &index); }
else if (arg == "--personalized-headphone") { else if (arg == "--personalized-headphone") {
options->personalized_headphone_used = true; options->personalized_headphone_used = true;
// nargs="?": the path is optional, so the next token may be the input. // nargs="?": the path is optional, so the next token may be the input.
@@ -238,9 +236,11 @@ void parse_args(const std::vector<std::string>& arguments, Options* options) {
options->personalized_headphone = require_value(arguments, &index); options->personalized_headphone = require_value(arguments, &index);
} }
} }
else if (arg == "--hrtf-cache-policy") { options->hrtf_cache_policy = require_value(arguments, &index); } else if (arg == "--rosella-filterbank") {
else if (arg == "--hrtf-cache-dir") { options->hrtf_cache_dir = require_value(arguments, &index); } options->rosella_filterbank = static_cast<int>(
else if (arg == "--hrtf-radius-m") { options->hrtf_radius_m = to_double(require_value(arguments, &index), "--hrtf-radius-m"); } to_int(require_value(arguments, &index), "--rosella-filterbank"));
options->rosella_filterbank_set = true;
}
else if (arg == "--binaural-tail-seconds") { options->binaural_tail_seconds = to_double(require_value(arguments, &index), "--binaural-tail-seconds"); } else if (arg == "--binaural-tail-seconds") { options->binaural_tail_seconds = to_double(require_value(arguments, &index), "--binaural-tail-seconds"); }
else if (arg == "--binaural-tail-threshold") { options->binaural_tail_threshold = to_double(require_value(arguments, &index), "--binaural-tail-threshold"); } else if (arg == "--binaural-tail-threshold") { options->binaural_tail_threshold = to_double(require_value(arguments, &index), "--binaural-tail-threshold"); }
else if (arg == "--binaural-chunk-frames") { options->binaural_chunk_frames = static_cast<int>(to_int(require_value(arguments, &index), "--binaural-chunk-frames")); } else if (arg == "--binaural-chunk-frames") { options->binaural_chunk_frames = static_cast<int>(to_int(require_value(arguments, &index), "--binaural-chunk-frames")); }
@@ -336,16 +336,12 @@ std::string find_kernels(const Options& options, const std::string& argv0) {
return options.kernels; return options.kernels;
} }
// Mirrors the reference binaural HRTF resolution (main.py:89-160): the SOFA file // The binaural input is either an explicitly compiled .jochrtf field or a Rosella
// is the user-facing input and the .jochrtf is only its compiled cache. Paths // .personalized_headphone model. Paths are anchored at the executable directory,
// are anchored at the executable directory, as the reference anchors them at the // as the reference anchors them at the project directory.
// project directory.
struct HrtfInput { struct HrtfInput {
std::string sofa_path; // compile this std::string compiled_path; // read this .jochrtf
std::string compiled_path; // or read this .jochrtf directly
std::string cache_dir; // disk policy directory
std::string personalized_path; // Rosella .personalized_headphone std::string personalized_path; // Rosella .personalized_headphone
bool disk = false;
}; };
std::string resolve_compiled_hrtf(const Options& options, const std::string& project_directory) { std::string resolve_compiled_hrtf(const Options& options, const std::string& project_directory) {
@@ -353,9 +349,7 @@ std::string resolve_compiled_hrtf(const Options& options, const std::string& pro
return options.compiled_hrtf_cache; return options.compiled_hrtf_cache;
} }
const std::string directory_utf8 = const std::string directory_utf8 =
options.hrtf_cache_dir.empty() fs_utf8::from_path(fs_utf8::to_path(project_directory) / "output" / "hrtf-cache");
? fs_utf8::from_path(fs_utf8::to_path(project_directory) / "output" / "hrtf-cache")
: options.hrtf_cache_dir;
if (!fs_utf8::is_directory(directory_utf8)) { if (!fs_utf8::is_directory(directory_utf8)) {
return std::string(); return std::string();
} }
@@ -369,34 +363,18 @@ std::string resolve_compiled_hrtf(const Options& options, const std::string& pro
std::sort(candidates.begin(), candidates.end()); std::sort(candidates.begin(), candidates.end());
if (candidates.size() > 1u) { if (candidates.size() > 1u) {
fail(directory_utf8 + fail(directory_utf8 +
" 下有多个 .jochrtf 缓存,无法自动选择;请用 --sofa-hrtf PATH 或 " " 下有多个 .jochrtf 缓存,无法自动选择;请用 --compiled-hrtf-cache PATH 显式指定");
"--compiled-hrtf-cache PATH 显式指定");
} }
return candidates.empty() ? std::string() : fs_utf8::from_path(candidates.front()); return candidates.empty() ? std::string() : fs_utf8::from_path(candidates.front());
} }
HrtfInput resolve_hrtf_input(const Options& options, const std::string& project_directory) { HrtfInput resolve_hrtf_input(const Options& options, const std::string& project_directory) {
HrtfInput input; HrtfInput input;
const std::string default_sofa =
fs_utf8::from_path(fs_utf8::to_path(project_directory) / "HRTF" / "binaural.sofa");
const std::string default_private = fs_utf8::from_path( const std::string default_private = fs_utf8::from_path(
fs_utf8::to_path(project_directory) / "HRTF" / "binaural.personalized_headphone"); fs_utf8::to_path(project_directory) / "HRTF" / "binaural.personalized_headphone");
const std::string default_cache_dir = const std::string default_cache_dir =
fs_utf8::from_path(fs_utf8::to_path(project_directory) / "output" / "hrtf-cache"); fs_utf8::from_path(fs_utf8::to_path(project_directory) / "output" / "hrtf-cache");
if (!options.compiled_hrtf_cache.empty() && !options.hrtf_cache_policy.empty()) {
fail("显式 .jochrtf 输入不能再指定 --hrtf-cache-policy");
}
if (!options.compiled_hrtf_cache.empty() && options.hrtf_radius_m != 1.0) {
fail("显式 .jochrtf 输入不能再选择 SOFA radius shell");
}
if (options.personalized_headphone_used &&
(!options.hrtf_cache_policy.empty() || !options.hrtf_cache_dir.empty() ||
options.hrtf_radius_m != 1.0)) {
fail("Rosella 模型输入不能使用 --hrtf-cache-policy/--hrtf-cache-dir/--hrtf-radius-m");
}
std::string sofa = options.sofa_hrtf;
std::string compiled = options.compiled_hrtf_cache; std::string compiled = options.compiled_hrtf_cache;
std::string personalized = std::string personalized =
options.personalized_headphone_used ? options.personalized_headphone : std::string(); options.personalized_headphone_used ? options.personalized_headphone : std::string();
@@ -404,16 +382,11 @@ HrtfInput resolve_hrtf_input(const Options& options, const std::string& project_
// "--personalized-headphone" without a path means the project default. // "--personalized-headphone" without a path means the project default.
personalized = default_private; personalized = default_private;
} }
if (sofa.empty() && compiled.empty() && personalized.empty()) { if (compiled.empty() && personalized.empty()) {
// The reference order: the SOFA file, then the unique compiled cache, then the // The compiled cache, then the personalized model.
// personalized model. compiled = resolve_compiled_hrtf(options, project_directory);
if (fs_utf8::exists(default_sofa)) { if (compiled.empty() && fs_utf8::exists(default_private)) {
sofa = default_sofa; personalized = default_private;
} else {
compiled = resolve_compiled_hrtf(options, project_directory);
if (compiled.empty() && fs_utf8::exists(default_private)) {
personalized = default_private;
}
} }
} }
if (!personalized.empty()) { if (!personalized.empty()) {
@@ -423,35 +396,12 @@ HrtfInput resolve_hrtf_input(const Options& options, const std::string& project_
input.personalized_path = personalized; input.personalized_path = personalized;
return input; return input;
} }
if (sofa.empty() && compiled.empty()) { if (compiled.empty()) {
if (!options.hrtf_cache_policy.empty() || !options.hrtf_cache_dir.empty() || fail("--binaural 未找到 HRTF 输入:默认 " + default_private + " 与 " + default_cache_dir +
options.hrtf_radius_m != 1.0) { " 下的 .jochrtf 都不存在,请用 --personalized-headphone PATH 或 "
fail("HRTF cache/radius 选项需要 --sofa-hrtf"); "--compiled-hrtf-cache PATH 指定");
}
fail("--binaural 未找到 HRTF 输入:默认 " + default_sofa + "、" + default_private +
" 或 " + default_cache_dir +
" 下的 .jochrtf 都不存在,请用 --sofa-hrtf PATH、--personalized-headphone PATH "
"或 --compiled-hrtf-cache PATH 指定");
}
if (sofa.empty() && (!options.hrtf_cache_policy.empty() || !options.hrtf_cache_dir.empty() ||
options.hrtf_radius_m != 1.0)) {
fail("HRTF cache/radius 选项需要 --sofa-hrtf");
}
if (sofa.empty()) {
input.compiled_path = compiled;
return input;
}
const std::string effective_policy =
options.hrtf_cache_policy.empty() ? "memory" : options.hrtf_cache_policy;
if (!options.hrtf_cache_dir.empty() && effective_policy != "disk") {
fail("--hrtf-cache-dir 需要 SOFA 与 disk cache policy 一起使用");
}
input.sofa_path = sofa;
input.disk = effective_policy == "disk";
input.cache_dir = options.hrtf_cache_dir.empty() ? default_cache_dir : options.hrtf_cache_dir;
if (!fs_utf8::exists(input.sofa_path)) {
fail("SOFA HRTF 不存在: " + input.sofa_path);
} }
input.compiled_path = compiled;
return input; return input;
} }
@@ -558,9 +508,9 @@ int main(int argc, char** argv) {
check_choice(options.backend, "--backend", {"auto", "native", "python"}); check_choice(options.backend, "--backend", {"auto", "native", "python"});
check_choice(options.print_metadata, "--print-metadata", {"none", "summary", "frames"}); check_choice(options.print_metadata, "--print-metadata", {"none", "summary", "frames"});
check_choice(options.metadata_backend, "--metadata-backend", {"auto", "emdf", "sidecar"}); check_choice(options.metadata_backend, "--metadata-backend", {"auto", "emdf", "sidecar"});
if (!options.hrtf_cache_policy.empty()) { if (options.rosella_filterbank != 1 && options.rosella_filterbank != 2) {
check_choice(options.hrtf_cache_policy, "--hrtf-cache-policy", fail("--rosella-filterbank: invalid choice: " +
{"none", "memory", "disk"}); std::to_string(options.rosella_filterbank) + " (choose from 1, 2)");
} }
const bool speaker_mode = !options.speaker_layout.empty(); const bool speaker_mode = !options.speaker_layout.empty();
@@ -589,13 +539,16 @@ int main(int argc, char** argv) {
if (options.speaker_metadata_offset < 0) { if (options.speaker_metadata_offset < 0) {
fail("speaker-metadata-offset 不能为负数"); fail("speaker-metadata-offset 不能为负数");
} }
check_choice(options.jochrtf_room, "--jochrtf-room", {"on", "off"});
const bool hrtf_options_used = const bool hrtf_options_used =
!options.sofa_hrtf.empty() || !options.compiled_hrtf_cache.empty() || !options.compiled_hrtf_cache.empty() || options.personalized_headphone_used ||
options.personalized_headphone_used || !options.hrtf_cache_policy.empty() || options.jochrtf_room != "on";
!options.hrtf_cache_dir.empty() || options.hrtf_radius_m != 1.0;
if (hrtf_options_used && !binaural_mode) { if (hrtf_options_used && !binaural_mode) {
fail("SOFA/HRTF 选项仅与 --binaural 一起使用"); fail("SOFA/HRTF 选项仅与 --binaural 一起使用");
} }
if (options.rosella_filterbank_set && !binaural_mode) {
fail("--rosella-filterbank 仅与 --binaural 一起使用");
}
if (!std::isfinite(options.binaural_tail_seconds) || if (!std::isfinite(options.binaural_tail_seconds) ||
options.binaural_tail_seconds < 0.0) { options.binaural_tail_seconds < 0.0) {
fail("binaural-tail-seconds 必须是非负有限值"); fail("binaural-tail-seconds 必须是非负有限值");
@@ -607,9 +560,6 @@ int main(int argc, char** argv) {
if (options.binaural_chunk_frames <= 0) { if (options.binaural_chunk_frames <= 0) {
fail("binaural-chunk-frames 必须大于 0"); fail("binaural-chunk-frames 必须大于 0");
} }
if (!std::isfinite(options.hrtf_radius_m) || options.hrtf_radius_m <= 0.0) {
fail("hrtf-radius-m 必须是正有限值");
}
if (options.duration_set && options.duration <= 0.0) { if (options.duration_set && options.duration <= 0.0) {
fail("duration 必须大于 0"); fail("duration 必须大于 0");
} }
@@ -670,6 +620,7 @@ int main(int argc, char** argv) {
config.speaker_metadata_offset = static_cast<std::uint32_t>(options.speaker_metadata_offset); config.speaker_metadata_offset = static_cast<std::uint32_t>(options.speaker_metadata_offset);
config.binaural_mode = binaural_mode_value(options.binaural_mode); config.binaural_mode = binaural_mode_value(options.binaural_mode);
config.adm_binaural_mode = binaural_mode_value(options.binaural_mode); config.adm_binaural_mode = binaural_mode_value(options.binaural_mode);
config.rosella_filterbank = static_cast<std::uint32_t>(options.rosella_filterbank);
config.binaural_tail_seconds = options.binaural_tail_seconds; config.binaural_tail_seconds = options.binaural_tail_seconds;
config.binaural_tail_threshold = options.binaural_tail_threshold; config.binaural_tail_threshold = options.binaural_tail_threshold;
config.binaural_chunk_frames = static_cast<std::uint32_t>(options.binaural_chunk_frames); config.binaural_chunk_frames = static_cast<std::uint32_t>(options.binaural_chunk_frames);
@@ -697,33 +648,28 @@ int main(int argc, char** argv) {
if (options.quiet) { config.flags |= JOC_TASK_F_QUIET; } if (options.quiet) { config.flags |= JOC_TASK_F_QUIET; }
std::string hrtf_path; std::string hrtf_path;
std::string hrtf_sofa_path;
std::string hrtf_cache_dir;
std::string personalized_path; std::string personalized_path;
std::string kernels_path; std::string kernels_path;
if (binaural_mode) { if (binaural_mode) {
try { try {
const HrtfInput input = resolve_hrtf_input(options, project_directory); const HrtfInput input = resolve_hrtf_input(options, project_directory);
hrtf_path = input.compiled_path; hrtf_path = input.compiled_path;
hrtf_sofa_path = input.sofa_path;
hrtf_cache_dir = input.cache_dir;
personalized_path = input.personalized_path; personalized_path = input.personalized_path;
kernels_path = find_kernels(options, arguments.empty() ? std::string() kernels_path = find_kernels(options, arguments.empty() ? std::string()
: arguments.front()); : arguments.front());
if (options.rosella_filterbank_set && personalized_path.empty()) {
fail("--rosella-filterbank 只作用于 Rosella .personalized_headphone 输入;"
"当前 .jochrtf 路径不使用该滤波器组");
}
} catch (const std::exception& error) { } catch (const std::exception& error) {
std::fprintf(stderr, "joc_cli: error: %s\n", error.what()); std::fprintf(stderr, "joc_cli: error: %s\n", error.what());
return 2; return 2;
} }
} }
config.hrtf_path = hrtf_path.empty() ? nullptr : hrtf_path.c_str(); config.hrtf_path = hrtf_path.empty() ? nullptr : hrtf_path.c_str();
config.hrtf_sofa_path = hrtf_sofa_path.empty() ? nullptr : hrtf_sofa_path.c_str();
config.hrtf_cache_dir = hrtf_cache_dir.empty() ? nullptr : hrtf_cache_dir.c_str();
config.personalized_headphone_path = config.personalized_headphone_path =
personalized_path.empty() ? nullptr : personalized_path.c_str(); personalized_path.empty() ? nullptr : personalized_path.c_str();
config.hrtf_cache_policy = options.hrtf_cache_policy == "disk" ? JOC_HRTF_CACHE_DISK config.jochrtf_room = options.jochrtf_room == "off" ? 0u : 1u;
: options.hrtf_cache_policy == "none" ? JOC_HRTF_CACHE_NONE
: JOC_HRTF_CACHE_MEMORY;
config.hrtf_radius_m = options.hrtf_radius_m;
config.kernels_path = kernels_path.empty() ? nullptr : kernels_path.c_str(); config.kernels_path = kernels_path.empty() ? nullptr : kernels_path.c_str();
joc_validation_issue issues[32]; joc_validation_issue issues[32];
+25
View File
@@ -0,0 +1,25 @@
// Port of src/oamd_tracks.py align_metadata_sample: an OAMD position update is
// scheduled on the renderer's processing-block grid, the same 32-sample grid the
// speaker control blocks use. It lives in foundation because both the ADM track
// builder and the object position timeline need it, and the timeline must not
// depend on output.
#pragma once
#include <cstdint>
namespace joc::timing {
inline constexpr std::int64_t kMetadataBlockSamples = 32;
// Nearest block boundary, ties towards the earlier block; the negative branch
// floors like the reference's Python `//`.
inline std::int64_t align_metadata_sample(std::int64_t sample,
std::int64_t block_samples = kMetadataBlockSamples) {
const std::int64_t numerator = sample + block_samples / 2 - 1;
const std::int64_t quotient =
numerator >= 0 ? numerator / block_samples
: -((-numerator + block_samples - 1) / block_samples);
return block_samples * quotient;
}
} // namespace joc::timing
+11
View File
@@ -0,0 +1,11 @@
#include "foundation/status.h"
namespace joc {
// The single definition of the per-thread detail string. It cannot live in the
// header: a thread_local with dynamic initialisation that is included by several
// translation units makes each of them emit its own TLS initialisation routine,
// and ld64 rejects those as duplicate symbols (GNU ld and MSVC fold them).
thread_local std::string last_error_detail;
} // namespace joc
+4 -2
View File
@@ -36,8 +36,10 @@ private:
// Structured detail of the most recent failing call, as returned by // Structured detail of the most recent failing call, as returned by
// joc_last_error_detail(). It is one instance per thread across the whole // joc_last_error_detail(). It is one instance per thread across the whole
// library, so every C entry point -- the task API and the streaming API alike -- // library, so every C entry point -- the task API and the streaming API alike --
// reports through the same string. // reports through the same string. Defined in status.cpp: a thread_local with
inline thread_local std::string last_error_detail; // dynamic initialisation defined in a header emits a TLS initialisation routine
// in every including unit, and ld64 rejects those duplicates.
extern thread_local std::string last_error_detail;
inline void record_error_detail(const Status& status) { inline void record_error_detail(const Status& status) {
if (status.ok()) { if (status.ok()) {
-4
View File
@@ -7,10 +7,6 @@
#include "hrtf/jochrtf.h" #include "hrtf/jochrtf.h"
// Public 64-QMF / 77-hybrid filterbank, shared by the SOFA field compiler and the
// Rosella renderer (upstream public_filterbank.py and rosella_filterbank.py are
// the same bank). Everything is float64/complex128, as the reference computes it,
// and the stateful half-steps are exposed because Rosella drives them directly.
namespace joc::hrtf { namespace joc::hrtf {
inline constexpr int kQmfBands = 64; inline constexpr int kQmfBands = 64;
+89
View File
@@ -0,0 +1,89 @@
#include "hrtf/rosella_bank.h"
#include <utility>
#include "hrtf/rosella_filterbank.h"
namespace joc::hrtf {
namespace {
// The shared public bank. It is also what the SOFA field compiler runs, and it
// is the bank the Rosella renderer used before the Rosella-specific one was
// captured.
class PublicBank final : public RosellaBank {
public:
explicit PublicBank(std::size_t channels) : bank_(builtin_kernels(), channels) {}
void reset() override { bank_.reset(); }
void analyze_qmf(const std::vector<double>& hops, std::size_t slots,
std::vector<Complex>* qmf) override {
bank_.analyze_qmf(hops, slots, qmf);
}
void analyze_hybrid(const std::vector<Complex>& qmf, std::size_t slots,
std::vector<Complex>* hybrid) override {
bank_.analyze_hybrid(qmf, slots, hybrid);
}
void synthesize_hybrid(const std::vector<Complex>& hybrid, std::size_t slots,
std::vector<Complex>* qmf) override {
bank_.synthesize_hybrid(hybrid, slots, qmf);
}
void synthesize_qmf(const std::vector<Complex>& qmf, std::size_t slots,
std::vector<double>* hops) override {
bank_.synthesize_qmf(qmf, slots, hops);
}
private:
PublicFilterbank bank_;
};
// The bank captured from the Rosella headphone renderer.
class CapturedBank final : public RosellaBank {
public:
explicit CapturedBank(std::size_t channels) : bank_(channels) {}
void reset() override { bank_.reset(); }
void analyze_qmf(const std::vector<double>& hops, std::size_t slots,
std::vector<Complex>* qmf) override {
bank_.analyze_qmf(hops, slots, qmf);
}
void analyze_hybrid(const std::vector<Complex>& qmf, std::size_t slots,
std::vector<Complex>* hybrid) override {
bank_.analyze_hybrid(qmf, slots, hybrid);
}
void synthesize_hybrid(const std::vector<Complex>& hybrid, std::size_t slots,
std::vector<Complex>* qmf) override {
bank_.synthesize_hybrid(hybrid, slots, qmf);
}
void synthesize_qmf(const std::vector<Complex>& qmf, std::size_t slots,
std::vector<double>* hops) override {
bank_.synthesize_qmf(qmf, slots, hops);
}
private:
RosellaFilterbank bank_;
};
} // namespace
std::uint32_t rosella_bank_latency(RosellaBankKind kind) {
return kind == RosellaBankKind::Captured
? static_cast<std::uint32_t>(RosellaFilterbank::kLatencySamples)
: static_cast<std::uint32_t>(kLatencySamples);
}
std::unique_ptr<RosellaBank> RosellaBank::create(RosellaBankKind kind, std::size_t channels) {
if (kind == RosellaBankKind::Captured) {
return std::make_unique<CapturedBank>(channels);
}
return std::make_unique<PublicBank>(channels);
}
} // namespace joc::hrtf
+50
View File
@@ -0,0 +1,50 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <memory>
#include <vector>
#include "hrtf/public_filterbank.h"
namespace joc::hrtf {
// Which 64-QMF / 77-hybrid bank the Rosella renderer runs. The two are not
// interchangeable: the QMF prototype, the hybrid tap count, the high-band slot
// delay and the analysis/synthesis latency all differ, so each bank keeps its own
// tables and its own state.
enum class RosellaBankKind : std::int32_t {
Public = 1, // shared bank: 13-tap hybrid, 6-slot delay, 961 samples
Captured = 2, // Rosella bank: 11-tap hybrid, 3-slot delay, 448 samples
};
// Analysis/synthesis latency of `kind` at 48 kHz, in samples.
std::uint32_t rosella_bank_latency(RosellaBankKind kind);
// The four stateful half-steps of either bank, in the order the reference runs
// them. Hops and QMF data are [slots, channels, 64], hybrid data is
// [slots, channels, 77]. State is per instance, so the analysis bank of a
// runtime and its synthesis bank never share buffers.
class RosellaBank {
public:
// `kind` must name one of the enumerators; anything else selects Public.
static std::unique_ptr<RosellaBank> create(RosellaBankKind kind, std::size_t channels);
RosellaBank() = default;
RosellaBank(const RosellaBank&) = delete;
RosellaBank& operator=(const RosellaBank&) = delete;
virtual ~RosellaBank() = default;
virtual void reset() = 0;
virtual void analyze_qmf(const std::vector<double>& hops, std::size_t slots,
std::vector<Complex>* qmf) = 0;
virtual void analyze_hybrid(const std::vector<Complex>& qmf, std::size_t slots,
std::vector<Complex>* hybrid) = 0;
virtual void synthesize_hybrid(const std::vector<Complex>& hybrid, std::size_t slots,
std::vector<Complex>* qmf) = 0;
virtual void synthesize_qmf(const std::vector<Complex>& qmf, std::size_t slots,
std::vector<double>* hops) = 0;
};
} // namespace joc::hrtf
+173
View File
@@ -0,0 +1,173 @@
#include "hrtf/rosella_filterbank.h"
#include <algorithm>
#include <array>
#include "foundation/fft.h"
#include "hrtf/rosella_filterbank_tables.h"
namespace joc::hrtf {
namespace {
constexpr std::size_t kBands = 64;
constexpr std::size_t kQmfTaps = 10;
constexpr std::size_t kHybridTaps = 11;
constexpr std::size_t kHybridDelay = 3;
constexpr std::array<std::size_t, 16> kHybridOrder = {0, 7, 1, 6, 2, 9, 3, 4,
10, 5, 11, 15, 8, 12, 13, 14};
const dsp::FftPlan& qmf_plan() {
static const dsp::FftPlan plan(kBands, false);
return plan;
}
const dsp::FftPlan& hybrid_plan(std::size_t bands) {
static const dsp::FftPlan eight(8, false);
static const dsp::FftPlan four(4, false);
return bands == 8 ? eight : four;
}
double tap_sign(std::size_t tap) { return (tap / 2) % 2 == 0 ? 1.0 : -1.0; }
}
RosellaFilterbank::RosellaFilterbank(std::size_t channels)
: channels_(channels), analysis_history_(kQmfTaps * channels * kBands),
hybrid_history_(kHybridTaps * channels * kBands),
synthesis_history_(kQmfTaps * channels * kBands), spectrum_(kBands), hybrid_eight_(8),
hybrid_four_(4) {}
void RosellaFilterbank::reset() {
analysis_position_ = 0;
hybrid_position_ = 0;
synthesis_position_ = 0;
std::fill(analysis_history_.begin(), analysis_history_.end(), 0.0);
std::fill(hybrid_history_.begin(), hybrid_history_.end(), Complex{});
std::fill(synthesis_history_.begin(), synthesis_history_.end(), Complex{});
}
void RosellaFilterbank::analyze_qmf(const std::vector<double>& hops, std::size_t slots,
std::vector<Complex>* qmf) {
const std::size_t stride = channels_ * kBands;
qmf->resize(slots * stride);
for (std::size_t slot = 0; slot < slots; ++slot) {
std::copy_n(hops.data() + slot * stride, stride,
analysis_history_.data() + analysis_position_ * stride);
for (std::size_t channel = 0; channel < channels_; ++channel) {
for (std::size_t band = 0; band < kBands; ++band) {
double even = 0.0;
double odd = 0.0;
for (std::size_t tap = 0; tap < kQmfTaps; ++tap) {
const std::size_t history_slot = (analysis_position_ + tap + 1) % kQmfTaps;
const double value =
analysis_history_[history_slot * stride + channel * kBands + band];
const double contribution =
value * 0.5 * rosella_filterbank_tables::kPrototype[band * kQmfTaps + tap] *
tap_sign(tap);
(tap % 2 == 0 ? even : odd) += contribution;
}
spectrum_[band] = Complex(odd, even) * rosella_filterbank_tables::kRotation[band];
}
dsp::fft_radix2(&spectrum_, qmf_plan());
Complex* destination = qmf->data() + slot * stride + channel * kBands;
for (std::size_t band = 0; band < kBands / 2; ++band) {
destination[2 * band] = spectrum_[band] / 64.0;
destination[2 * band + 1] = std::conj(spectrum_[63 - band]) / 64.0;
}
}
analysis_position_ = (analysis_position_ + 1) % kQmfTaps;
}
}
void RosellaFilterbank::analyze_hybrid(const std::vector<Complex>& qmf, std::size_t slots,
std::vector<Complex>* hybrid) {
const std::size_t stride = channels_ * kBands;
hybrid->resize(slots * channels_ * kHybridBandCount);
for (std::size_t slot = 0; slot < slots; ++slot) {
std::copy_n(qmf.data() + slot * stride, stride,
hybrid_history_.data() + hybrid_position_ * stride);
for (std::size_t channel = 0; channel < channels_; ++channel) {
std::array<Complex, 16> low{};
for (std::size_t band = 0; band < 3; ++band) {
std::vector<Complex>& spectrum = band == 0 ? hybrid_eight_ : hybrid_four_;
std::fill(spectrum.begin(), spectrum.end(), Complex{});
for (std::size_t tap = 0; tap < kHybridTaps; ++tap) {
const std::size_t history_slot = (hybrid_position_ + tap + 1) % kHybridTaps;
const std::size_t bin =
(tap + kHybridDelay + 1 + 2 * spectrum.size() - kHybridTaps) %
spectrum.size();
spectrum[bin] +=
hybrid_history_[history_slot * stride + channel * kBands + band] *
rosella_filterbank_tables::kHybrid[(band == 0 ? 0 : kHybridTaps) + tap];
}
dsp::fft_radix2(&spectrum, hybrid_plan(spectrum.size()));
std::copy(spectrum.begin(), spectrum.end(),
low.begin() + (band == 0 ? 0 : 4 + band * 4));
}
Complex* destination = hybrid->data() + (slot * channels_ + channel) * kHybridBandCount;
for (std::size_t band = 0; band < low.size(); ++band) {
destination[band] = low[kHybridOrder[band]];
}
destination[1] = std::conj(destination[1]);
destination[3] = std::conj(destination[3]);
const std::size_t delayed =
(hybrid_position_ + kHybridTaps - kHybridDelay) % kHybridTaps;
std::copy_n(hybrid_history_.data() + delayed * stride + channel * kBands + 3,
kBands - 3, destination + 16);
}
hybrid_position_ = (hybrid_position_ + 1) % kHybridTaps;
}
}
void RosellaFilterbank::synthesize_hybrid(const std::vector<Complex>& hybrid, std::size_t slots,
std::vector<Complex>* qmf) {
qmf->resize(slots * channels_ * kBands);
for (std::size_t row = 0; row < slots * channels_; ++row) {
const Complex* source = hybrid.data() + row * kHybridBandCount;
Complex* destination = qmf->data() + row * kBands;
destination[0] = source[0] + source[2] + source[4] + source[6] + source[7] + source[9] +
std::conj(source[3]) + std::conj(source[1]);
destination[1] = source[12] + source[5] + source[8] + source[10];
destination[2] = source[13] + source[14] + source[15] + source[11];
std::copy_n(source + 16, kBands - 3, destination + 3);
}
}
void RosellaFilterbank::synthesize_qmf(const std::vector<Complex>& qmf, std::size_t slots,
std::vector<double>* hops) {
const std::size_t stride = channels_ * kBands;
hops->resize(slots * stride);
for (std::size_t slot = 0; slot < slots; ++slot) {
for (std::size_t channel = 0; channel < channels_; ++channel) {
const Complex* source = qmf.data() + slot * stride + channel * kBands;
for (std::size_t band = 0; band < kBands / 2; ++band) {
spectrum_[band] = std::conj(source[2 * band]);
spectrum_[32 + band] = source[63 - 2 * band];
}
dsp::fft_radix2(&spectrum_, qmf_plan());
Complex* current =
synthesis_history_.data() + synthesis_position_ * stride + channel * kBands;
for (std::size_t band = 0; band < kBands; ++band) {
current[band] = spectrum_[band] * rosella_filterbank_tables::kRotation[band];
}
for (std::size_t band = 0; band < kBands; ++band) {
double value = 0.0;
for (std::size_t lag = 0; lag < kQmfTaps; ++lag) {
const std::size_t history_slot =
(synthesis_position_ + kQmfTaps - lag) % kQmfTaps;
const Complex sample =
synthesis_history_[history_slot * stride + channel * kBands + band];
const double component = lag % 2 == 0 ? sample.real() : sample.imag();
value +=
component *
rosella_filterbank_tables::kPrototype[(63 - band) * kQmfTaps + 9 - lag] *
tap_sign(lag) * 2.0;
}
(*hops)[slot * stride + channel * kBands + band] = value;
}
}
synthesis_position_ = (synthesis_position_ + 1) % kQmfTaps;
}
}
}
+38
View File
@@ -0,0 +1,38 @@
#pragma once
#include <cstddef>
#include <vector>
#include "hrtf/public_filterbank.h"
namespace joc::hrtf {
class RosellaFilterbank {
public:
static constexpr int kLatencySamples = 448;
explicit RosellaFilterbank(std::size_t channels);
void reset();
void analyze_qmf(const std::vector<double>& hops, std::size_t slots, std::vector<Complex>* qmf);
void analyze_hybrid(const std::vector<Complex>& qmf, std::size_t slots,
std::vector<Complex>* hybrid);
void synthesize_hybrid(const std::vector<Complex>& hybrid, std::size_t slots,
std::vector<Complex>* qmf);
void synthesize_qmf(const std::vector<Complex>& qmf, std::size_t slots,
std::vector<double>* hops);
private:
std::size_t channels_;
std::size_t analysis_position_ = 0;
std::size_t hybrid_position_ = 0;
std::size_t synthesis_position_ = 0;
std::vector<double> analysis_history_;
std::vector<Complex> hybrid_history_;
std::vector<Complex> synthesis_history_;
std::vector<Complex> spectrum_;
std::vector<Complex> hybrid_eight_;
std::vector<Complex> hybrid_four_;
};
}
+317
View File
@@ -0,0 +1,317 @@
#pragma once
#include <array>
#include <complex>
namespace joc::hrtf::rosella_filterbank_tables {
inline constexpr std::array<double, 640> kPrototype = {
0x1.89b0a40000000p-14f, -0x1.9405b80000000p-11f, 0x1.caf19e0000000p-11f,
0x1.b88a900000000p-8f, 0x1.a3899a0000000p-8f, -0x1.fa22860000000p-4f,
0x1.5a540e0000000p-4f, 0x1.c420360000000p-1f, 0x1.1fb7200000000p-1f,
-0x1.eb519a0000000p-12f, 0x1.fe69400000000p-14f, -0x1.aebea80000000p-11f,
0x1.0b0c7c0000000p-10f, 0x1.baec6c0000000p-8f, 0x1.7fc1900000000p-8f,
-0x1.0209c80000000p-3f, 0x1.88474c0000000p-4f, 0x1.c7781c0000000p-1f,
0x1.1929680000000p-1f, -0x1.6f0b9e0000000p-9f, 0x1.0c4e040000000p-13f,
-0x1.cabdf80000000p-11f, 0x1.3039ee0000000p-10f, 0x1.bd5e600000000p-8f,
0x1.590ba60000000p-8f, -0x1.06dd700000000p-3f, 0x1.b728e40000000p-4f,
0x1.ca9d100000000p-1f, 0x1.1298c60000000p-1f, -0x1.430d400000000p-8f,
0x1.09af720000000p-13f, -0x1.e7140c0000000p-11f, 0x1.553e000000000p-10f,
0x1.bfe6ee0000000p-8f, 0x1.2f581e0000000p-8f, -0x1.0b89600000000p-3f,
0x1.e6f2b20000000p-4f, 0x1.cd8f8e0000000p-1f, 0x1.0c066e0000000p-1f,
-0x1.c5fd4e0000000p-8f, 0x1.01e0d60000000p-13f, -0x1.01e8060000000p-10f,
0x1.7a2d9e0000000p-10f, 0x1.c2890c0000000p-8f, 0x1.028f2c0000000p-8f,
-0x1.100a6e0000000p-3f, 0x1.0bcf280000000p-3f, 0x1.d04eb00000000p-1f,
0x1.0573b40000000p-1f, -0x1.1fe42e0000000p-7f, 0x1.e4c9900000000p-14f,
-0x1.1083480000000p-10f, 0x1.9ef9b00000000p-10f, 0x1.c548880000000p-8f,
0x1.a536b40000000p-9f, -0x1.145d660000000p-3f, 0x1.2492a60000000p-3f,
0x1.d2d9d00000000p-1f, 0x1.fdc3f40000000p-2f, -0x1.584fbc0000000p-7f,
0x1.bbe1f00000000p-14f, -0x1.1f4cc40000000p-10f, 0x1.c3a28c0000000p-10f,
0x1.c828fe0000000p-8f, 0x1.3ed0ae0000000p-9f, -0x1.187f1e0000000p-3f,
0x1.3dc0340000000p-3f, 0x1.d530800000000p-1f, 0x1.f0a4d80000000p-2f,
-0x1.8c9d380000000p-7f, 0x1.8b83740000000p-14f, -0x1.2e42340000000p-10f,
0x1.e827840000000p-10f, 0x1.cb2f1a0000000p-8f, 0x1.a38bba0000000p-10f,
-0x1.1c6c620000000p-3f, 0x1.5754320000000p-3f, 0x1.d7522c0000000p-1f,
0x1.e38cc40000000p-2f, -0x1.bccca00000000p-7f, 0x1.51b3dc0000000p-14f,
-0x1.3d59c40000000p-10f, 0x1.0642740000000p-9f, 0x1.ce5f720000000p-8f,
0x1.77c5740000000p-11f, -0x1.2021ea0000000p-3f, 0x1.714ae20000000p-3f,
0x1.d93e620000000p-1f, 0x1.d67e3e0000000p-2f, -0x1.e902340000000p-7f,
0x1.1135380000000p-14f, -0x1.4c72680000000p-10f, 0x1.184f0e0000000p-9f,
0x1.d1bcf80000000p-8f, -0x1.cd43660000000p-13f, -0x1.239c8a0000000p-3f,
0x1.8ba0220000000p-3f, 0x1.daf4c80000000p-1f, 0x1.c97bac0000000p-2f,
-0x1.08b5360000000p-6f, 0x1.9380400000000p-15f, -0x1.5b82640000000p-10f,
0x1.2a36bc0000000p-9f, 0x1.d54b040000000p-8f, -0x1.3d508c0000000p-10f,
-0x1.26d9020000000p-3f, 0x1.a64ff60000000p-3f, 0x1.dc75060000000p-1f,
0x1.bc87920000000p-2f, -0x1.1b117c0000000p-6f, 0x1.ef2dd20000000p-16f,
-0x1.6a7bb60000000p-10f, 0x1.3bf6ea0000000p-9f, 0x1.d90d680000000p-8f,
-0x1.27adc40000000p-9f, -0x1.29d4040000000p-3f, 0x1.c156200000000p-3f,
0x1.ddbed80000000p-1f, 0x1.afa4460000000p-2f, -0x1.2ba7240000000p-6f,
0x1.4b90ac0000000p-17f, -0x1.7946720000000p-10f, 0x1.4d8e5a0000000p-9f,
0x1.dd07fe0000000p-8f, -0x1.b800720000000p-9f, -0x1.2c8a500000000p-3f,
0x1.dcae220000000p-3f, 0x1.ded2060000000p-1f, 0x1.a2d44a0000000p-2f,
-0x1.3a80720000000p-6f, -0x1.700b940000000p-17f, -0x1.87d4460000000p-10f,
0x1.5ef8ce0000000p-9f, 0x1.e13c820000000p-8f, -0x1.27dccc0000000p-8f,
-0x1.2ef8a80000000p-3f, 0x1.f853940000000p-3f, 0x1.dfae620000000p-1f,
0x1.9619e20000000p-2f, -0x1.47ad4c0000000p-6f, -0x1.1120780000000p-15f,
-0x1.960c8c0000000p-10f, 0x1.7033800000000p-9f, 0x1.e5adfa0000000p-8f,
-0x1.7778760000000p-8f, -0x1.311bc00000000p-3f, 0x1.0a20dc0000000p-2f,
0x1.e053dc0000000p-1f, 0x1.8977600000000p-2f, -0x1.533fe20000000p-6f,
-0x1.ca9a980000000p-15f, -0x1.a3dfa80000000p-10f, 0x1.813d240000000p-9f,
0x1.ea5d320000000p-8f, -0x1.cade8a0000000p-8f, -0x1.32f0680000000p-3f,
0x1.1839ec0000000p-2f, 0x1.e0c25e0000000p-1f, 0x1.7cef0e0000000p-2f,
-0x1.5d41a40000000p-6f, -0x1.45160a0000000p-14f, -0x1.b13e1c0000000p-10f,
0x1.9211160000000p-9f, 0x1.ef4d0a0000000p-8f, -0x1.110bcc0000000p-7f,
-0x1.3473540000000p-3f, 0x1.2672860000000p-2f, 0x1.e0f9ee0000000p-1f,
0x1.7083220000000p-2f, -0x1.65bf6a0000000p-6f, -0x1.a5d63c0000000p-14f,
-0x1.be0c7c0000000p-10f, 0x1.a2ad420000000p-9f, 0x1.f47de80000000p-8f,
-0x1.3e95720000000p-7f, -0x1.35a15c0000000p-3f, 0x1.34c8260000000p-2f,
0x1.e0faa00000000p-1f, 0x1.6435c80000000p-2f, -0x1.6cc7d80000000p-6f,
-0x1.0363300000000p-13f, -0x1.ca38de0000000p-10f, 0x1.b30fc40000000p-9f,
0x1.f9f0320000000p-8f, -0x1.6e0f4e0000000p-7f, -0x1.3677520000000p-3f,
0x1.43383c0000000p-2f, 0x1.e0c4920000000p-1f, 0x1.58091e0000000p-2f,
-0x1.7268700000000p-6f, -0x1.33a4780000000p-13f, -0x1.d5b2c20000000p-10f,
0x1.c336cc0000000p-9f, 0x1.ffa3600000000p-8f, -0x1.9f7bd20000000p-7f,
-0x1.36f2140000000p-3f, 0x1.51c02e0000000p-2f, 0x1.e057f20000000p-1f,
0x1.4bff340000000p-2f, -0x1.76ae0c0000000p-6f, -0x1.63044a0000000p-13f,
-0x1.e062560000000p-10f, 0x1.d321240000000p-9f, 0x1.02cb720000000p-7f,
-0x1.d2dcc20000000p-7f, -0x1.370e8a0000000p-3f, 0x1.605d580000000p-2f,
0x1.dfb5020000000p-1f, 0x1.401a140000000p-2f, -0x1.79a3480000000p-6f,
-0x1.91dea40000000p-13f, -0x1.ea3a6c0000000p-10f, 0x1.e2cc1c0000000p-9f,
0x1.05e49c0000000p-7f, -0x1.04190e0000000p-6f, -0x1.36c9a00000000p-3f,
0x1.6f0cfe0000000p-2f, 0x1.dedc080000000p-1f, 0x1.345b9e0000000p-2f,
-0x1.7b56a00000000p-6f, -0x1.bfa7220000000p-13f, -0x1.f327920000000p-10f,
0x1.f234380000000p-9f, 0x1.091c860000000p-7f, -0x1.1fbe040000000p-6f,
-0x1.36205c0000000p-3f, 0x1.7dcc500000000p-2f, 0x1.ddcd600000000p-1f,
0x1.28c5be0000000p-2f, -0x1.7bd6c00000000p-6f, -0x1.ebbcb00000000p-13f,
-0x1.fb17ea0000000p-10f, 0x1.00ad9a0000000p-8f, 0x1.0c71000000000p-7f,
-0x1.3c5cfa0000000p-6f, -0x1.350fba0000000p-3f, 0x1.8c989a0000000p-2f,
0x1.dc89760000000p-1f, 0x1.1d5a3e0000000p-2f, -0x1.7b2ea80000000p-6f,
-0x1.0afed40000000p-12f, -0x1.00fdf80000000p-9f, 0x1.081ef40000000p-8f,
0x1.0fe0aa0000000p-7f, -0x1.59f4a60000000p-6f, -0x1.3394de0000000p-3f,
0x1.9b6efe0000000p-2f, 0x1.db10b80000000p-1f, 0x1.121ad80000000p-2f,
-0x1.796b8c0000000p-6f, -0x1.1f023c0000000p-12f, -0x1.03dff00000000p-9f,
0x1.0f6d1a0000000p-8f, 0x1.1368de0000000p-7f, -0x1.7883900000000p-6f,
-0x1.31acee0000000p-3f, 0x1.aa4c940000000p-2f, 0x1.d963ae0000000p-1f,
0x1.07092e0000000p-2f, -0x1.769b420000000p-6f, -0x1.31d35c0000000p-12f,
-0x1.062c000000000p-9f, 0x1.1697660000000p-8f, 0x1.1706fa0000000p-7f,
-0x1.9807dc0000000p-6f, -0x1.2f55300000000p-3f, 0x1.b92e760000000p-2f,
0x1.d782e20000000p-1f, 0x1.f84daa0000000p-3f, -0x1.72cc440000000p-6f,
-0x1.435c0e0000000p-12f, -0x1.07dcd20000000p-9f, 0x1.1d9da20000000p-8f,
0x1.1ab8380000000p-7f, -0x1.b87f060000000p-6f, -0x1.2c8af40000000p-3f,
0x1.c811b40000000p-2f, 0x1.d56ef40000000p-1f, 0x1.e2ea940000000p-3f,
-0x1.6e0bd80000000p-6f, -0x1.5382940000000p-12f, -0x1.08eac40000000p-9f,
0x1.247f400000000p-8f, 0x1.1e79ce0000000p-7f, -0x1.d9e6460000000p-6f,
-0x1.294b8c0000000p-3f, 0x1.d6f34e0000000p-2f, 0x1.d3288c0000000p-1f,
0x1.cdebe00000000p-3f, -0x1.6865f20000000p-6f, -0x1.624b420000000p-12f,
-0x1.0952b80000000p-9f, 0x1.2b3bdc0000000p-8f, 0x1.2247060000000p-7f,
-0x1.fc3a1a0000000p-6f, -0x1.2594900000000p-3f, 0x1.e5d0500000000p-2f,
0x1.d0b05e0000000p-1f, 0x1.b9542e0000000p-3f, -0x1.61ea740000000p-6f,
-0x1.6f8fc20000000p-12f, -0x1.090d6a0000000p-9f, 0x1.31d25e0000000p-8f,
0x1.261bfc0000000p-7f, -0x1.0fbb460000000p-5f, -0x1.21637c0000000p-3f,
0x1.f4a5aa0000000p-2f, 0x1.ce072e0000000p-1f, 0x1.a525de0000000p-3f,
-0x1.5aa7b40000000p-6f, -0x1.7b53da0000000p-12f, -0x1.0819600000000p-9f,
0x1.3842c00000000p-8f, 0x1.29f3580000000p-7f, -0x1.21cbac0000000p-5f,
-0x1.1cb60a0000000p-3f, 0x1.01b82e0000000p-1f, 0x1.cb2dca0000000p-1f,
0x1.9163520000000p-3f, -0x1.52aada0000000p-6f, -0x1.85a5dc0000000p-12f,
-0x1.0671aa0000000p-9f, 0x1.3e8b260000000p-8f, 0x1.2dc77c0000000p-7f,
-0x1.344b9e0000000p-5f, -0x1.1789fc0000000p-3f, 0x1.0916a80000000p-1f,
0x1.c824fc0000000p-1f, 0x1.7e0e860000000p-3f, -0x1.4a023a0000000p-6f,
-0x1.8e754e0000000p-12f, -0x1.0411fc0000000p-9f, 0x1.44aa780000000p-8f,
0x1.3192620000000p-7f, -0x1.4738520000000p-5f, -0x1.11dd300000000p-3f,
0x1.106cbc0000000p-1f, 0x1.c4edac0000000p-1f, 0x1.6b29640000000p-3f,
-0x1.40bbf00000000p-6f, -0x1.95db9a0000000p-12f, -0x1.00fbba0000000p-9f,
0x1.4aa1d60000000p-8f, 0x1.354e160000000p-7f, -0x1.5a8eb80000000p-5f,
-0x1.0bad980000000p-3f, 0x1.17b8dc0000000p-1f, 0x1.c188c20000000p-1f,
0x1.58b59e0000000p-3f, -0x1.36e7a40000000p-6f, -0x1.9be6720000000p-12f,
-0x1.fa5a8a0000000p-10f, 0x1.506fe80000000p-8f, 0x1.38f3740000000p-7f,
-0x1.6e4b4c0000000p-5f, -0x1.04f9500000000p-3f, 0x1.1ef9820000000p-1f,
0x1.bdf7340000000p-1f, 0x1.46b4b40000000p-3f, -0x1.2c935c0000000p-6f,
-0x1.a0ae100000000p-12f, -0x1.f14b760000000p-10f, 0x1.5614b40000000p-8f,
0x1.3c7bfe0000000p-7f, -0x1.826b260000000p-5f, -0x1.fb7d1c0000000p-4f,
0x1.262d200000000p-1f, 0x1.ba3a080000000p-1f, 0x1.3527ea0000000p-3f,
-0x1.21cb9e0000000p-6f, -0x1.a45ab20000000p-12f, -0x1.e6cbec0000000p-10f,
0x1.5b8f3c0000000p-8f, 0x1.3fdefe0000000p-7f, -0x1.96ea060000000p-5f,
-0x1.ebf76a0000000p-4f, 0x1.2d52300000000p-1f, 0x1.b652420000000p-1f,
0x1.24103e0000000p-3f, -0x1.16a0ec0000000p-6f, -0x1.a6fa860000000p-12f,
-0x1.dadcf00000000p-10f, 0x1.60df2e0000000p-8f, 0x1.4315740000000p-7f,
-0x1.abc3c80000000p-5f, -0x1.db5e1e0000000p-4f, 0x1.3467220000000p-1f,
0x1.b240fa0000000p-1f, 0x1.136ebc0000000p-3f, -0x1.0b217a0000000p-6f,
-0x1.a8bb460000000p-12f, -0x1.cd821e0000000p-10f, 0x1.6605500000000p-8f,
0x1.4617c60000000p-7f, -0x1.c0f3f60000000p-5f, -0x1.c9aeee0000000p-4f,
0x1.3b6a700000000p-1f, 0x1.ae07440000000p-1f, 0x1.03441c0000000p-3f,
-0x1.feb4ba0000000p-7f, -0x1.a9e0be0000000p-12f, -0x1.bebef20000000p-10f,
0x1.6b004c0000000p-8f, 0x1.48dc4a0000000p-7f, -0x1.d675c20000000p-5f,
-0x1.b6e6ae0000000p-4f, 0x1.425a960000000p-1f, 0x1.a9a64c0000000p-1f,
0x1.e7217e0000000p-4f, -0x1.e6b55c0000000p-7f, -0x1.aa85020000000p-12f,
-0x1.ae9b460000000p-10f, 0x1.6fd00c0000000p-8f, 0x1.4b59340000000p-7f,
-0x1.ec43c80000000p-5f, -0x1.a303a20000000p-4f, 0x1.49360c0000000p-1f,
0x1.a51f340000000p-1f, 0x1.c8a9d20000000p-4f, -0x1.ce5e0a0000000p-7f,
-0x1.aade480000000p-12f, -0x1.9d1b940000000p-10f, 0x1.7474cc0000000p-8f,
0x1.4d85040000000p-7f, -0x1.012c820000000p-4f, -0x1.8e03600000000p-4f,
0x1.4ffb520000000p-1f, 0x1.a073360000000p-1f, 0x1.ab21ee0000000p-4f,
-0x1.b5ce920000000p-7f, -0x1.ab1c980000000p-12f, -0x1.8a49160000000p-10f,
0x1.78eec60000000p-8f, 0x1.4f55b00000000p-7f, -0x1.0c57ca0000000p-4f,
-0x1.77e4720000000p-4f, 0x1.56a8e60000000p-1f, 0x1.9ba3820000000p-1f,
0x1.8e894a0000000p-4f, -0x1.9d20fe0000000p-7f, -0x1.ab834e0000000p-12f,
-0x1.762b260000000p-10f, 0x1.7d3dde0000000p-8f, 0x1.50c0480000000p-7f,
-0x1.17a0ae0000000p-4f, -0x1.60a5560000000p-4f, 0x1.5d3d4e0000000p-1f,
0x1.96b1680000000p-1f, 0x1.72df7c0000000p-4f, -0x1.846b160000000p-7f,
-0x1.ac64680000000p-12f, -0x1.60cd740000000p-10f, 0x1.81625a0000000p-8f,
0x1.51b9dc0000000p-7f, -0x1.2303ee0000000p-4f, -0x1.4845000000000p-4f,
0x1.63b7140000000p-1f, 0x1.919e200000000p-1f, 0x1.5823340000000p-4f,
-0x1.6bcd900000000p-7f, -0x1.adf08e0000000p-12f, -0x1.4a3ac20000000p-10f,
0x1.855cfe0000000p-8f, 0x1.5237680000000p-7f, -0x1.2e7e4e0000000p-4f,
-0x1.2ec2760000000p-4f, 0x1.6a14c00000000p-1f, 0x1.8c6afe0000000p-1f,
0x1.3e53ba0000000p-4f, -0x1.53608c0000000p-7f, -0x1.b06dac0000000p-12f,
-0x1.327bec0000000p-10f, 0x1.892e780000000p-8f, 0x1.522d9c0000000p-7f,
-0x1.3a0c300000000p-4f, -0x1.141d6e0000000p-4f, 0x1.7054ee0000000p-1f,
0x1.87194e0000000p-1f, 0x1.256f780000000p-4f, -0x1.3b3a720000000p-7f,
-0x1.b4260a0000000p-12f, -0x1.199f100000000p-10f, 0x1.8cd8000000000p-8f,
0x1.5190560000000p-7f, -0x1.45aa140000000p-4f, -0x1.f0ab120000000p-5f,
0x1.7676320000000p-1f, 0x1.81aa700000000p-1f, 0x1.0d73ae0000000p-4f,
-0x1.2378140000000p-7f, -0x1.b946980000000p-12f, -0x1.ff5dae0000000p-11f,
0x1.905a600000000p-8f, 0x1.5053d20000000p-7f, -0x1.5154220000000p-4f,
-0x1.b6d5d40000000p-5f, 0x1.7c772e0000000p-1f, 0x1.7c1fb80000000p-1f,
0x1.ecbc3e0000000p-5f, -0x1.0c29f20000000p-7f, -0x1.c0151e0000000p-12f,
-0x1.c96f140000000p-11f, 0x1.93b7460000000p-8f, 0x1.4e6c1e0000000p-7f,
-0x1.5d064a0000000p-4f, -0x1.7abc7a0000000p-5f, 0x1.8256860000000p-1f,
0x1.767a860000000p-1f, 0x1.c059b00000000p-5f, -0x1.eadf100000000p-8f,
-0x1.c8cc9c0000000p-12f, -0x1.918eb80000000p-11f, 0x1.96effa0000000p-8f,
0x1.4bcc520000000p-7f, -0x1.68bca00000000p-4f, -0x1.3c5fe80000000p-5f,
0x1.8812e80000000p-1f, 0x1.70bc380000000p-1f, 0x1.95b8180000000p-5f,
-0x1.bebb380000000p-8f, -0x1.d3ab2e0000000p-12f, -0x1.57d51e0000000p-11f,
0x1.9a075e0000000p-8f, 0x1.4868760000000p-7f, -0x1.7472b40000000p-4f,
-0x1.f785a60000000p-6f, 0x1.8dab0e0000000p-1f, 0x1.6ae6480000000p-1f,
0x1.6cd0a40000000p-5f, -0x1.93fad20000000p-8f, -0x1.e0dd0e0000000p-12f,
-0x1.1c6a140000000p-11f, 0x1.9cfe1a0000000p-8f, 0x1.44329c0000000p-7f,
-0x1.80243a0000000p-4f, -0x1.71cfa40000000p-6f, 0x1.931db60000000p-1f,
0x1.64fa0a0000000p-1f, 0x1.459afa0000000p-5f, -0x1.6ae5d80000000p-8f,
-0x1.f0751e0000000p-12f, -0x1.bea86e0000000p-12f, 0x1.9fd7d60000000p-8f,
0x1.3f20100000000p-7f, -0x1.8bcca00000000p-4f, -0x1.cf4aee0000000p-7f,
0x1.9869a40000000p-1f, 0x1.5ef8f00000000p-1f, 0x1.2010120000000p-5f,
-0x1.43917e0000000p-8f, -0x1.014d9e0000000p-11f, -0x1.41769a0000000p-12f,
0x1.a2962a0000000p-8f, 0x1.39224a0000000p-7f, -0x1.9767380000000p-4f,
-0x1.643b740000000p-8f, 0x1.9d8dac0000000p-1f, 0x1.58e4620000000p-1f,
0x1.f8505c0000000p-6f, -0x1.1e15b40000000p-8f, -0x1.0bbd1e0000000p-11f,
-0x1.82f5720000000p-13f, 0x1.a53c820000000p-8f, 0x1.322da40000000p-7f,
-0x1.a2ef380000000p-4f, 0x1.cf4bf20000000p-9f, 0x1.a288b20000000p-1f,
0x1.52bdd00000000p-1f, 0x1.b3a9200000000p-6f, -0x1.f55fc60000000p-9f,
-0x1.1795420000000p-11f, -0x1.f78ba40000000p-15f, 0x1.a7cd100000000p-8f,
0x1.2a34100000000p-7f, -0x1.ae5f920000000p-4f, 0x1.a272920000000p-7f,
0x1.a7599a0000000p-1f, 0x1.4c86bc0000000p-1f, 0x1.72191a0000000p-6f,
-0x1.b278bc0000000p-9f, -0x1.24d82e0000000p-11f, 0x1.176aba0000000p-14f,
0x1.aa4b400000000p-8f, 0x1.21297e0000000p-7f, -0x1.b9b3340000000p-4f,
0x1.6cd36a0000000p-6f, 0x1.abff500000000p-1f, 0x1.46406e0000000p-1f,
0x1.3392320000000p-6f, -0x1.7413460000000p-9f, -0x1.3371980000000p-11f,
0x1.9954380000000p-13f, 0x1.acba4a0000000p-8f, 0x1.1700e40000000p-7f,
-0x1.c4e4ec0000000p-4f, 0x1.0655200000000p-5f, 0x1.b078e40000000p-1f,
0x1.3fec680000000p-1f, 0x1.efd5a20000000p-7f, -0x1.3a3eea0000000p-9f,
-0x1.43727a0000000p-11f, 0x1.5542700000000p-12f, 0x1.af1de80000000p-8f,
0x1.0bacb40000000p-7f, -0x1.cfef6c0000000p-4f, 0x1.58574a0000000p-5f,
0x1.b4c5620000000p-1f, 0x1.398c3c0000000p-1f, 0x1.7e1d1c0000000p-7f,
-0x1.039df20000000p-9f, -0x1.54c2b80000000p-11f, 0x1.df54960000000p-12f,
0x1.b17a740000000p-8f, 0x1.fe42040000000p-8f, -0x1.dacd4c0000000p-4f,
0x1.ac68700000000p-5f, 0x1.b8e3f00000000p-1f, 0x1.33211a0000000p-1f,
0x1.11a4f80000000p-7f, -0x1.a3b4ea0000000p-10f, -0x1.671b880000000p-11f,
0x1.3568c80000000p-11f, 0x1.b3d4520000000p-8f, 0x1.e2a46e0000000p-8f,
-0x1.e579200000000p-4f, 0x1.013ff60000000p-4f, 0x1.bcd3ee0000000p-1f,
0x1.2cacd00000000p-1f, 0x1.53b1420000000p-8f, -0x1.42fb1c0000000p-10f,
-0x1.7b9bba0000000p-11f, 0x1.7c27840000000p-11f, 0x1.b62ed40000000p-8f,
0x1.c465e60000000p-8f, -0x1.efecf00000000p-4f, 0x1.2d4b160000000p-4f,
0x1.c093960000000p-1f, 0x1.2631fe0000000p-1f, 0x1.21b5e00000000p-9f,
-0x1.a0c52c0000000p-11f,
};
inline constexpr std::array<std::complex<double>, 64> kRotation = {{
{0x1.fff6220000000p-1f, -0x1.921d200000000p-7f},
{0x1.ffa72e0000000p-1f, -0x1.2d86580000000p-5f},
{0x1.ff09560000000p-1f, -0x1.f656e80000000p-5f},
{0x1.fe1cb00000000p-1f, -0x1.5f6d000000000p-4f},
{0x1.fce1600000000p-1f, -0x1.c3785c0000000p-4f},
{0x1.fb57980000000p-1f, -0x1.139f0c0000000p-3f},
{0x1.f97f920000000p-1f, -0x1.45576c0000000p-3f},
{0x1.f7599a0000000p-1f, -0x1.76dd9e0000000p-3f},
{0x1.f4e6040000000p-1f, -0x1.a82a020000000p-3f},
{0x1.f225300000000p-1f, -0x1.d934fe0000000p-3f},
{0x1.ef178a0000000p-1f, -0x1.04fb800000000p-2f},
{0x1.ebbd8c0000000p-1f, -0x1.1d34440000000p-2f},
{0x1.e817ba0000000p-1f, -0x1.35410c0000000p-2f},
{0x1.e426a40000000p-1f, -0x1.4d1e240000000p-2f},
{0x1.dfeae60000000p-1f, -0x1.64c7de0000000p-2f},
{0x1.db65260000000p-1f, -0x1.7c3a940000000p-2f},
{0x1.d696180000000p-1f, -0x1.9372a60000000p-2f},
{0x1.d17e780000000p-1f, -0x1.aa6c820000000p-2f},
{0x1.cc1f100000000p-1f, -0x1.c1249e0000000p-2f},
{0x1.c678b40000000p-1f, -0x1.d797760000000p-2f},
{0x1.c08c420000000p-1f, -0x1.edc1960000000p-2f},
{0x1.ba5aa60000000p-1f, -0x1.01cfc80000000p-1f},
{0x1.b3e4d40000000p-1f, -0x1.0c97040000000p-1f},
{0x1.ad2bca0000000p-1f, -0x1.1734d60000000p-1f},
{0x1.a630920000000p-1f, -0x1.21a79a0000000p-1f},
{0x1.9ef43e0000000p-1f, -0x1.2bedb20000000p-1f},
{0x1.9777f00000000p-1f, -0x1.36058c0000000p-1f},
{0x1.8fbcca0000000p-1f, -0x1.3fed960000000p-1f},
{0x1.87c4000000000p-1f, -0x1.49a44a0000000p-1f},
{0x1.7f8ece0000000p-1f, -0x1.53282a0000000p-1f},
{0x1.771e760000000p-1f, -0x1.5c77bc0000000p-1f},
{0x1.6e74460000000p-1f, -0x1.6591920000000p-1f},
{0x1.6591920000000p-1f, -0x1.6e74460000000p-1f},
{0x1.5c77bc0000000p-1f, -0x1.771e760000000p-1f},
{0x1.53282a0000000p-1f, -0x1.7f8ece0000000p-1f},
{0x1.49a44a0000000p-1f, -0x1.87c4000000000p-1f},
{0x1.3fed960000000p-1f, -0x1.8fbcca0000000p-1f},
{0x1.36058c0000000p-1f, -0x1.9777f00000000p-1f},
{0x1.2bedb20000000p-1f, -0x1.9ef43e0000000p-1f},
{0x1.21a79a0000000p-1f, -0x1.a630920000000p-1f},
{0x1.1734d60000000p-1f, -0x1.ad2bca0000000p-1f},
{0x1.0c97040000000p-1f, -0x1.b3e4d40000000p-1f},
{0x1.01cfc80000000p-1f, -0x1.ba5aa60000000p-1f},
{0x1.edc1960000000p-2f, -0x1.c08c420000000p-1f},
{0x1.d797760000000p-2f, -0x1.c678b40000000p-1f},
{0x1.c1249e0000000p-2f, -0x1.cc1f100000000p-1f},
{0x1.aa6c820000000p-2f, -0x1.d17e780000000p-1f},
{0x1.9372a60000000p-2f, -0x1.d696180000000p-1f},
{0x1.7c3a940000000p-2f, -0x1.db65260000000p-1f},
{0x1.64c7de0000000p-2f, -0x1.dfeae60000000p-1f},
{0x1.4d1e240000000p-2f, -0x1.e426a40000000p-1f},
{0x1.35410c0000000p-2f, -0x1.e817ba0000000p-1f},
{0x1.1d34440000000p-2f, -0x1.ebbd8c0000000p-1f},
{0x1.04fb800000000p-2f, -0x1.ef178a0000000p-1f},
{0x1.d934fe0000000p-3f, -0x1.f225300000000p-1f},
{0x1.a82a020000000p-3f, -0x1.f4e6040000000p-1f},
{0x1.76dd9e0000000p-3f, -0x1.f7599a0000000p-1f},
{0x1.45576c0000000p-3f, -0x1.f97f920000000p-1f},
{0x1.139f0c0000000p-3f, -0x1.fb57980000000p-1f},
{0x1.c3785c0000000p-4f, -0x1.fce1600000000p-1f},
{0x1.5f6d000000000p-4f, -0x1.fe1cb00000000p-1f},
{0x1.f656e80000000p-5f, -0x1.ff09560000000p-1f},
{0x1.2d86580000000p-5f, -0x1.ffa72e0000000p-1f},
{0x1.921d200000000p-7f, -0x1.fff6220000000p-1f},
}};
inline constexpr std::array<std::complex<double>, 22> kHybrid = {{
{-0x1.3a7de80000000p-7f, 0x1.0488900000000p-8f},
{-0x1.4f39c60000000p-6f, 0x1.4f39c60000000p-6f},
{-0x1.4f65900000000p-6f, 0x1.94dc0e0000000p-5f},
{0x0.0p+0f, 0x1.4382f00000000p-4f},
{0x1.3844900000000p-5f, 0x1.78f0ca0000000p-4f},
{0x1.459b100000000p-4f, 0x1.459b100000000p-4f},
{0x1.c49e200000000p-4f, 0x1.76f5f60000000p-5f},
{0x1.0000000000000p-3f, 0x0.0p+0f},
{0x1.c426000000000p-4f, -0x1.7692720000000p-5f},
{0x1.2d4d820000000p-5f, -0x1.2d4d820000000p-5f},
{0x1.e4029a0000000p-6f, -0x1.2420400000000p-4f},
{-0x1.1ce09c0000000p-7f, 0x1.1ce0900000000p-7f},
{0x0.0p+0f, 0x1.b5bb180000000p-6f},
{0x1.586f240000000p-6f, 0x1.586f2c0000000p-6f},
{0x0.0p+0f, 0x0.0p+0f},
{-0x1.9eb2460000000p-5f, 0x1.9eb2460000000p-5f},
{0x0.0p+0f, 0x1.5019100000000p-3f},
{0x1.515a8e0000000p-3f, 0x1.515a8e0000000p-3f},
{0x1.0000000000000p-2f, 0x0.0p+0f},
{0x1.515b660000000p-3f, -0x1.515b660000000p-3f},
{0x0.0p+0f, -0x1.1f2f040000000p-3f},
{-0x1.af372a0000000p-5f, -0x1.af372a0000000p-5f},
}};
}
+23 -15
View File
@@ -12,7 +12,7 @@
#include <vector> #include <vector>
#include "foundation/fft.h" #include "foundation/fft.h"
#include "hrtf/public_filterbank.h" #include "hrtf/rosella_bank.h"
namespace joc::hrtf { namespace joc::hrtf {
@@ -1003,8 +1003,8 @@ struct RosellaRuntime::Impl {
std::vector<double> field_left; std::vector<double> field_left;
std::vector<double> field_right; std::vector<double> field_right;
Core core; Core core;
std::unique_ptr<PublicFilterbank> analysis_bank; std::unique_ptr<RosellaBank> analysis_bank;
std::unique_ptr<PublicFilterbank> synthesis_bank; std::unique_ptr<RosellaBank> synthesis_bank;
timeline::OamdPositionTimeline timeline{timeline::kTimelineObjects}; timeline::OamdPositionTimeline timeline{timeline::kTimelineObjects};
std::vector<double> buffer; // [chunk_samples][16] std::vector<double> buffer; // [chunk_samples][16]
@@ -1051,9 +1051,7 @@ struct RosellaRuntime::Impl {
analysis_bank->analyze_qmf(hops_, slots, &qmf_); analysis_bank->analyze_qmf(hops_, slots, &qmf_);
analysis_bank->analyze_hybrid(qmf_, slots, &hybrid_); analysis_bank->analyze_hybrid(qmf_, slots, &hybrid_);
if (rendered_.size() < slots * 2u * kHybridBands) { rendered_.resize(slots * 2u * kHybridBands);
rendered_.resize(slots * 2u * kHybridBands);
}
if (room_sends_buffer_.size() != slots * kHybridBands) { if (room_sends_buffer_.size() != slots * kHybridBands) {
room_sends_buffer_.resize(slots * kHybridBands); room_sends_buffer_.resize(slots * kHybridBands);
} }
@@ -1141,11 +1139,13 @@ struct RosellaRuntime::Impl {
return Status::success(); return Status::success();
} }
// The reference drops the first 961 samples of the raw stream (the filterbank's // The reference drops the first `latency` samples of the raw stream (the
// latency) and returns everything after that. // filterbank's own delay) and returns everything after that; the latency is
// the selected bank's, so the two banks start at different sample offsets.
void append_output(const double* stereo, std::size_t count) { void append_output(const double* stereo, std::size_t count) {
const std::int64_t remaining = static_cast<std::int64_t>(kLatencySamples) - const std::int64_t remaining =
static_cast<std::int64_t>(raw_output_samples); static_cast<std::int64_t>(rosella_bank_latency(options.bank)) -
static_cast<std::int64_t>(raw_output_samples);
const std::size_t skip = static_cast<std::size_t>( const std::size_t skip = static_cast<std::size_t>(
std::max<std::int64_t>(0, std::min<std::int64_t>(static_cast<std::int64_t>(count), std::max<std::int64_t>(0, std::min<std::int64_t>(static_cast<std::int64_t>(count),
remaining))); remaining)));
@@ -1191,6 +1191,9 @@ Status RosellaRuntime::open(const RosellaModel& model, const RosellaRenderOption
if (options.object_delay_samples < 0) { if (options.object_delay_samples < 0) {
return render_fail(JOC_ERR_INVALID_ARGUMENT, "object_delay_samples must be non-negative"); return render_fail(JOC_ERR_INVALID_ARGUMENT, "object_delay_samples must be non-negative");
} }
if (options.bank != RosellaBankKind::Public && options.bank != RosellaBankKind::Captured) {
return render_fail(JOC_ERR_INVALID_ARGUMENT, "unknown Rosella filterbank");
}
impl_->model = model; impl_->model = model;
impl_->options = options; impl_->options = options;
logical_field(impl_->model.field_left_padded, &impl_->field_left); logical_field(impl_->model.field_left_padded, &impl_->field_left);
@@ -1203,8 +1206,8 @@ Status RosellaRuntime::open(const RosellaModel& model, const RosellaRenderOption
return status; return status;
} }
// The analysis bank runs sixteen sources, the synthesis bank two output ears. // The analysis bank runs sixteen sources, the synthesis bank two output ears.
impl_->analysis_bank = std::make_unique<PublicFilterbank>(builtin_kernels(), kSourceChannels); impl_->analysis_bank = RosellaBank::create(options.bank, kSourceChannels);
impl_->synthesis_bank = std::make_unique<PublicFilterbank>(builtin_kernels(), kOutputChannels); impl_->synthesis_bank = RosellaBank::create(options.bank, kOutputChannels);
impl_->buffer.assign(impl_->chunk_samples() * kSourceChannels, 0.0); impl_->buffer.assign(impl_->chunk_samples() * kSourceChannels, 0.0);
impl_->room_sends_buffer_.assign( impl_->room_sends_buffer_.assign(
(impl_->chunk_samples() / kQmfHop) * kHybridBands, Complex(0.0, 0.0)); (impl_->chunk_samples() / kQmfHop) * kHybridBands, Complex(0.0, 0.0));
@@ -1309,7 +1312,8 @@ Status RosellaRuntime::finish(std::uint32_t flush_samples, std::vector<double>*
} }
std::uint32_t RosellaRuntime::finish_capacity(double tail_seconds) const { std::uint32_t RosellaRuntime::finish_capacity(double tail_seconds) const {
const double samples = tail_seconds * 48000.0 + static_cast<double>(kLatencySamples) + const double samples = tail_seconds * 48000.0 +
static_cast<double>(rosella_bank_latency(impl_->options.bank)) +
static_cast<double>(kBlockSamples); static_cast<double>(kBlockSamples);
const double blocks = std::ceil(samples / static_cast<double>(kBlockSamples)); const double blocks = std::ceil(samples / static_cast<double>(kBlockSamples));
return static_cast<std::uint32_t>(blocks) * kBlockSamples; return static_cast<std::uint32_t>(blocks) * kBlockSamples;
@@ -1329,7 +1333,7 @@ Status RosellaRuntime::reset() {
impl_->raw_output_samples = 0u; impl_->raw_output_samples = 0u;
impl_->metadata_block_updates = 0u; impl_->metadata_block_updates = 0u;
impl_->finished = false; impl_->finished = false;
impl_->timeline = timeline::OamdPositionTimeline(timeline::kTimelineObjects); impl_->timeline.reset();
return Status::success(); return Status::success();
} }
@@ -1339,7 +1343,7 @@ void RosellaRuntime::take_output(std::vector<double>* out) {
if (out == nullptr) { if (out == nullptr) {
return; return;
} }
// Replace semantics, exactly like SofaBinauralRuntime::take_output: the caller's // Replace semantics, exactly like JochrtfRuntime::take_output: the caller's
// previous contents are discarded, and the internal buffer is emptied afterwards // previous contents are discarded, and the internal buffer is emptied afterwards
// because the swap leaves it holding whatever the caller had. // because the swap leaves it holding whatever the caller had.
out->swap(impl_->output); out->swap(impl_->output);
@@ -1355,4 +1359,8 @@ std::uint64_t RosellaRuntime::metadata_block_updates() const {
} }
const timeline::OamdPositionTimeline& RosellaRuntime::timeline() const { return impl_->timeline; } const timeline::OamdPositionTimeline& RosellaRuntime::timeline() const { return impl_->timeline; }
void RosellaRuntime::set_fixed_position(int object_index, const double position[3]) {
impl_->timeline.set_fixed_position(object_index, position);
}
} // namespace joc::hrtf } // namespace joc::hrtf
+7
View File
@@ -6,6 +6,7 @@
#include <vector> #include <vector>
#include "foundation/status.h" #include "foundation/status.h"
#include "hrtf/rosella_bank.h"
#include "hrtf/rosella_model.h" #include "hrtf/rosella_model.h"
#include "oamd/oamd_parser.h" #include "oamd/oamd_parser.h"
#include "timeline/position_timeline.h" #include "timeline/position_timeline.h"
@@ -21,6 +22,9 @@ enum class RosellaProfile : std::int32_t { Near = 1, Far = 2, Mid = 3 };
struct RosellaRenderOptions { struct RosellaRenderOptions {
RosellaProfile profile = RosellaProfile::Mid; RosellaProfile profile = RosellaProfile::Mid;
// The analysis and synthesis banks both come from this one choice, so the
// latency skip, the flush capacity and the state histories stay consistent.
RosellaBankKind bank = RosellaBankKind::Public;
std::int64_t object_delay_samples = 1473; std::int64_t object_delay_samples = 1473;
double tail_seconds = 5.0; double tail_seconds = 5.0;
double output_gain = 1.0; double output_gain = 1.0;
@@ -56,6 +60,9 @@ public:
std::uint64_t metadata_block_updates() const; std::uint64_t metadata_block_updates() const;
const timeline::OamdPositionTimeline& timeline() const; const timeline::OamdPositionTimeline& timeline() const;
// bed 声道是固定通道:OAMD 不给位置,方位由声明的 bed 布局给出。
void set_fixed_position(int object_index, const double position[3]);
private: private:
struct Impl; struct Impl;
std::unique_ptr<Impl> impl_; std::unique_ptr<Impl> impl_;
-255
View File
@@ -1,255 +0,0 @@
#include "hrtf/sofa.h"
#include <algorithm>
#include <cmath>
#include <cctype>
#include <cstdio>
#include <fstream>
#include <utility>
#include "foundation/fs_utf8.h"
#include "foundation/sha256.h"
#include "io/hdf5.h"
namespace joc::hrtf {
namespace {
Status sofa_fail(joc_error code, const std::string& message) {
return Status::fail(code, stage::kRender, message);
}
std::string format_number(double value) {
if (std::isfinite(value) && value == std::floor(value) && std::fabs(value) < 1.0e15) {
return std::to_string(static_cast<long long>(value));
}
char buffer[32];
std::snprintf(buffer, sizeof(buffer), "%.6g", value);
return std::string(buffer);
}
// Every array is checked against the element count the convention prescribes, so
// a file whose shape disagrees with its metadata is rejected instead of silently
// producing a shifted impulse response.
Status read_doubles(const io::Hdf5File& file, const std::string& path, std::uint64_t expected,
std::vector<double>* out) {
if (!file.has_dataset(path)) {
return sofa_fail(JOC_ERR_HRTF_FORMAT, "SOFA file has no " + path + " dataset");
}
const Status status = file.read_dataset_double(path, out);
if (!status.ok()) {
return sofa_fail(JOC_ERR_HRTF_FORMAT, "SOFA dataset " + path + ": " + status.message());
}
if (out->size() != expected) {
return sofa_fail(JOC_ERR_HRTF_FORMAT,
"SOFA dataset " + path + " holds " + std::to_string(out->size()) +
" values, expected " + std::to_string(expected));
}
return Status::success();
}
Status read_text(const io::Hdf5File& file, const std::string& name, bool required,
std::string* out) {
io::Hdf5Attribute attribute;
const Status status = file.attribute("", name, &attribute);
if (!status.ok()) {
if (required) {
return sofa_fail(JOC_ERR_HRTF_FORMAT,
"SOFA file has no root attribute " + name + ": " + status.message());
}
return Status::success();
}
*out = attribute.text;
return Status::success();
}
// SHA-256 of the whole file: the compiled-cache key is derived from it, so the
// digest is taken over the exact bytes the parse consumed.
std::string file_digest(const std::string& path) {
std::ifstream stream = fs_utf8::open_input(path);
if (!stream.good()) {
return std::string();
}
crypto::Sha256 hash;
std::vector<char> buffer(1u << 20);
while (stream.good()) {
stream.read(buffer.data(), static_cast<std::streamsize>(buffer.size()));
const std::streamsize count = stream.gcount();
if (count > 0) {
hash.update(buffer.data(), static_cast<std::size_t>(count));
}
}
return hash.finish_hex();
}
// The coordinate declaration of one dataset, when the file carries it.
void read_coordinates(const io::Hdf5File& file, const std::string& dataset,
SofaCoordinate* out) {
io::Hdf5Attribute attribute;
if (file.attribute(dataset, "Type", &attribute).ok()) {
out->type = attribute.text;
}
if (file.attribute(dataset, "Units", &attribute).ok()) {
out->units = attribute.text;
}
}
} // namespace
std::string SofaHrir::summary() const {
return "SOFA " + sofa_conventions + ", " + std::to_string(ir_count) + " IRs x " +
std::to_string(ir_length) + " taps @ " + format_number(sample_rate) + " Hz";
}
Status load_sofa(const std::string& path, SofaHrir* out) {
if (out == nullptr) {
return sofa_fail(JOC_ERR_INVALID_ARGUMENT, "null SOFA destination");
}
if (!fs_utf8::exists(path)) {
return sofa_fail(JOC_ERR_HRTF_NOT_FOUND, "SOFA file not found: " + path);
}
io::Hdf5File file;
Status status = file.open(path);
if (!status.ok()) {
return sofa_fail(JOC_ERR_HRTF_FORMAT, "SOFA file " + path + ": " + status.message());
}
SofaHrir sofa;
sofa.source_path = path;
sofa.source_sha256 = file_digest(path);
for (char& character : sofa.source_sha256) {
character = static_cast<char>(std::toupper(static_cast<unsigned char>(character)));
}
status = read_text(file, "Conventions", true, &sofa.conventions);
if (!status.ok()) {
return status;
}
status = read_text(file, "SOFAConventions", true, &sofa.sofa_conventions);
if (!status.ok()) {
return status;
}
if (sofa.conventions != "SOFA" || sofa.sofa_conventions != "SimpleFreeFieldHRIR") {
return sofa_fail(JOC_ERR_HRTF_UNSUPPORTED_CONVENTION,
"SOFA conventions " + sofa.conventions + "/" + sofa.sofa_conventions +
" are not SimpleFreeFieldHRIR");
}
status = read_text(file, "SOFAConventionsVersion", false, &sofa.convention_version);
if (!status.ok()) {
return status;
}
status = read_text(file, "Version", false, &sofa.version);
if (!status.ok()) {
return status;
}
status = read_text(file, "DataType", false, &sofa.data_type);
if (!status.ok()) {
return status;
}
status = read_text(file, "RoomType", false, &sofa.room_type);
if (!status.ok()) {
return status;
}
status = read_text(file, "Title", false, &sofa.title);
if (!status.ok()) {
return status;
}
status = read_text(file, "DatabaseName", false, &sofa.database_name);
if (!status.ok()) {
return status;
}
status = read_text(file, "ListenerShortName", false, &sofa.listener_short_name);
if (!status.ok()) {
return status;
}
status = read_text(file, "Comment", false, &sofa.comment);
if (!status.ok()) {
return status;
}
io::Hdf5DatasetInfo info;
status = file.dataset_info("Data.IR", &info);
if (!status.ok()) {
return sofa_fail(JOC_ERR_HRTF_FORMAT,
"SOFA file has no usable Data.IR dataset: " + status.message());
}
if (info.shape.size() != 3u || info.shape[1] != 2u || info.shape[0] == 0u ||
info.shape[2] == 0u) {
return sofa_fail(JOC_ERR_HRTF_FORMAT, "SOFA Data.IR is not shaped (M, 2, N)");
}
if (info.shape[0] > 0xFFFFFFFFull || info.shape[2] > 0xFFFFFFFFull) {
return sofa_fail(JOC_ERR_HRTF_FORMAT, "SOFA Data.IR is larger than this reader accepts");
}
sofa.ir_count = static_cast<std::uint32_t>(info.shape[0]);
sofa.ir_length = static_cast<std::uint32_t>(info.shape[2]);
const std::uint64_t taps = static_cast<std::uint64_t>(sofa.ir_count) * 2u * sofa.ir_length;
status = read_doubles(file, "Data.IR", taps, &sofa.ir);
if (!status.ok()) {
return status;
}
std::vector<double> scalar;
status = read_doubles(file, "Data.SamplingRate", 1u, &scalar);
if (!status.ok()) {
return status;
}
sofa.sample_rate = scalar[0];
io::Hdf5Attribute attribute;
if (file.attribute("Data.SamplingRate", "Units", &attribute).ok()) {
sofa.sampling_rate_units = attribute.text;
}
// Data.Delay is optional in the wild; absent means "no delay was measured".
if (file.has_dataset("Data.Delay")) {
std::vector<double> delay;
status = read_doubles(file, "Data.Delay", 2u, &delay);
if (!status.ok()) {
return status;
}
sofa.delay[0] = delay[0];
sofa.delay[1] = delay[1];
}
const std::uint64_t measurements = sofa.ir_count;
status = read_doubles(file, "SourcePosition", measurements * 3u, &sofa.source_position);
if (!status.ok()) {
return status;
}
read_coordinates(file, "SourcePosition", &sofa.source_position_coordinates);
std::vector<double> vector;
status = read_doubles(file, "ListenerPosition", 3u, &vector);
if (!status.ok()) {
return status;
}
std::copy(vector.begin(), vector.end(), sofa.listener_position);
read_coordinates(file, "ListenerPosition", &sofa.listener_position_coordinates);
status = read_doubles(file, "ListenerView", 3u, &vector);
if (!status.ok()) {
return status;
}
std::copy(vector.begin(), vector.end(), sofa.listener_view);
read_coordinates(file, "ListenerView", &sofa.listener_view_coordinates);
status = read_doubles(file, "ListenerUp", 3u, &vector);
if (!status.ok()) {
return status;
}
std::copy(vector.begin(), vector.end(), sofa.listener_up);
read_coordinates(file, "ListenerUp", &sofa.listener_up_coordinates);
status = read_doubles(file, "EmitterPosition", 3u, &vector);
if (!status.ok()) {
return status;
}
std::copy(vector.begin(), vector.end(), sofa.emitter_position);
read_coordinates(file, "EmitterPosition", &sofa.emitter_position_coordinates);
status = read_doubles(file, "ReceiverPosition", 6u, &vector);
if (!status.ok()) {
return status;
}
std::copy(vector.begin(), vector.end(), sofa.receiver_position);
read_coordinates(file, "ReceiverPosition", &sofa.receiver_position_coordinates);
*out = std::move(sofa);
return Status::success();
}
} // namespace joc::hrtf
-61
View File
@@ -1,61 +0,0 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include "foundation/status.h"
namespace joc::hrtf {
// Coordinate declaration of one SOFA variable: Type ("spherical"/"cartesian") and
// Units. Empty when the file does not declare them (ListenerUp inherits).
struct SofaCoordinate {
std::string type;
std::string units;
};
// SOFA SimpleFreeFieldHRIR as this project consumes it: the impulse responses,
// the measurement geometry and the metadata needed to report what was loaded.
// All angles are degrees, all distances metres, exactly as the file stores them.
struct SofaHrir {
double sample_rate = 0.0;
std::uint32_t ir_count = 0; // M: number of measurements
std::uint32_t ir_length = 0; // N: taps per impulse response
std::vector<double> ir; // C order [M][2][N]
double delay[2] = {0.0, 0.0};
std::vector<double> source_position; // M*3
double listener_position[3] = {0.0, 0.0, 0.0};
double listener_view[3] = {1.0, 0.0, 0.0};
double listener_up[3] = {0.0, 0.0, 1.0};
double emitter_position[3] = {0.0, 0.0, 0.0};
double receiver_position[6] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
std::string conventions;
std::string sofa_conventions;
std::string convention_version;
std::string version;
std::string data_type;
std::string room_type;
std::string title;
std::string database_name;
std::string listener_short_name;
std::string comment;
std::string sampling_rate_units;
SofaCoordinate source_position_coordinates;
SofaCoordinate listener_position_coordinates;
SofaCoordinate listener_view_coordinates;
SofaCoordinate listener_up_coordinates;
SofaCoordinate emitter_position_coordinates;
SofaCoordinate receiver_position_coordinates;
// Identity of the file itself, needed for the compiled-cache key.
std::string source_path;
std::string source_sha256;
// One line for reports and logs:
// "SOFA SimpleFreeFieldHRIR, <M> IRs x <N> taps @ <rate> Hz".
std::string summary() const;
};
Status load_sofa(const std::string& path, SofaHrir* out);
} // namespace joc::hrtf
-237
View File
@@ -1,237 +0,0 @@
#include "hrtf/sofa_cache.h"
#include <algorithm>
#include <filesystem>
#include <list>
#include <mutex>
#include <utility>
#include <vector>
#include "foundation/fs_utf8.h"
#include "hrtf/sofa.h"
namespace joc::hrtf {
namespace {
namespace fs = std::filesystem;
// Small process-local cache: the reference keeps the last eight compiled fields.
constexpr std::size_t kMemoryCacheEntries = 8;
struct MemoryEntry {
std::string key;
Field field;
};
std::mutex& memory_mutex() {
static std::mutex mutex;
return mutex;
}
std::list<MemoryEntry>& memory_cache() {
static std::list<MemoryEntry> cache;
return cache;
}
bool memory_cache_get(const std::string& key, Field* out) {
std::lock_guard<std::mutex> lock(memory_mutex());
std::list<MemoryEntry>& cache = memory_cache();
for (auto entry = cache.begin(); entry != cache.end(); ++entry) {
if (entry->key == key) {
*out = entry->field;
cache.splice(cache.begin(), cache, entry);
return true;
}
}
return false;
}
void memory_cache_put(const std::string& key, const Field& field) {
std::lock_guard<std::mutex> lock(memory_mutex());
std::list<MemoryEntry>& cache = memory_cache();
for (auto entry = cache.begin(); entry != cache.end(); ++entry) {
if (entry->key == key) {
entry->field = field;
cache.splice(cache.begin(), cache, entry);
return;
}
}
cache.push_front(MemoryEntry{key, field});
while (cache.size() > kMemoryCacheEntries) {
cache.pop_back();
}
}
Status cache_fail(joc_error code, const std::string& message) {
return Status::fail(code, stage::kRender, message);
}
std::string upper(std::string text) {
std::transform(text.begin(), text.end(), text.begin(), [](unsigned char value) {
return static_cast<char>(std::toupper(value));
});
return text;
}
} // namespace
Status parse_cache_policy(const std::string& text, CachePolicy* out) {
if (out == nullptr) {
return cache_fail(JOC_ERR_INVALID_ARGUMENT, "null cache policy");
}
if (text == "none") {
*out = CachePolicy::None;
return Status::success();
}
if (text == "memory") {
*out = CachePolicy::Memory;
return Status::success();
}
if (text == "disk") {
*out = CachePolicy::Disk;
return Status::success();
}
return cache_fail(JOC_ERR_INVALID_CONFIG, "cache_policy must be none, memory, or disk");
}
Status validate_jochrtf(const std::string& path, const std::string& source_sha256,
const std::string& cache_key, Field* out) {
Field field;
const Status status = load_jochrtf(path, &field);
if (!status.ok()) {
return status;
}
if (!source_sha256.empty() && field.source_sha256 != upper(source_sha256)) {
return cache_fail(JOC_ERR_HRTF_HASH, "compiled HRTF source hash mismatch");
}
if (!cache_key.empty() && field.cache_key != upper(cache_key)) {
return cache_fail(JOC_ERR_HRTF_HASH, "compiled HRTF configuration hash mismatch");
}
if (out != nullptr) {
*out = std::move(field);
}
return Status::success();
}
Status save_jochrtf_atomic(const Field& field, const std::string& path) {
if (path.empty()) {
return cache_fail(JOC_ERR_INVALID_ARGUMENT, "empty compiled HRTF cache path");
}
const fs::path target = fs_utf8::to_path(path);
std::error_code error;
if (target.has_parent_path()) {
fs::create_directories(target.parent_path(), error);
if (error) {
return cache_fail(JOC_ERR_OUTPUT_OPEN,
"cannot create " + fs_utf8::from_path(target.parent_path()));
}
}
const std::string temporary = path + ".tmp";
Status status = write_jochrtf(field, temporary);
if (!status.ok()) {
return status;
}
// The rename is what makes a half-written cache impossible to observe.
fs::rename(fs_utf8::to_path(temporary), target, error);
if (error) {
fs::remove(fs_utf8::to_path(temporary), error);
return cache_fail(JOC_ERR_OUTPUT_WRITE, "cannot replace " + path);
}
return Status::success();
}
Status load_or_compile_sofa_field(const SofaFieldRequest& request, Field* out,
std::string* cache_path) {
if (out == nullptr) {
return cache_fail(JOC_ERR_INVALID_ARGUMENT, "null compiled HRTF destination");
}
if (request.sofa_path.empty()) {
return cache_fail(JOC_ERR_INVALID_ARGUMENT, "no SOFA path for the compiled HRTF field");
}
if (request.policy == CachePolicy::Disk && request.cache_dir.empty()) {
return cache_fail(JOC_ERR_INVALID_CONFIG, "the disk cache policy needs a cache directory");
}
SofaHrir sofa;
Status status = load_sofa(request.sofa_path, &sofa);
if (!status.ok()) {
return status;
}
CanonicalHrtf canonical;
status = canonicalize_sofa(sofa, &canonical);
if (!status.ok()) {
return status;
}
// The key depends on the shell that the radius selects, exactly as upstream.
double actual_radius = request.options.shell_radius_m;
(void)canonical_shell_indices(canonical, request.options.shell_radius_m, &actual_radius);
const std::string key = compiled_hrtf_cache_key(
canonical.source_sha256, canonical.sample_rate_hz, actual_radius, request.options.order,
request.options.projection_ridge, request.options.sh_ridge);
if (cache_path != nullptr) {
cache_path->clear();
}
std::string target;
if (request.policy == CachePolicy::Disk) {
target = request.cache_dir;
if (!target.empty() && target.back() != '/' && target.back() != '\\') {
target += "/";
}
target += cache_file_name(canonical.source_path.empty()
? std::string()
: canonical.source_path,
key);
if (fs_utf8::exists(target)) {
Field cached_field;
const Status cached =
validate_jochrtf(target, canonical.source_sha256, key, &cached_field);
if (cached.ok()) {
memory_cache_put(key, cached_field);
*out = std::move(cached_field);
if (cache_path != nullptr) {
*cache_path = target;
}
return Status::success();
}
}
}
Field field;
if (request.policy != CachePolicy::None && memory_cache_get(key, &field)) {
// A memory hit still materialises the disk cache the caller asked for.
if (request.policy == CachePolicy::Disk) {
status = save_jochrtf_atomic(field, target);
if (!status.ok()) {
return status;
}
if (cache_path != nullptr) {
*cache_path = target;
}
}
*out = std::move(field);
return Status::success();
}
status = compile_canonical_field(canonical, request.options, &field);
if (!status.ok()) {
return status;
}
if (field.cache_key != key) {
return cache_fail(JOC_ERR_INTERNAL, "internal compiled HRTF cache-key mismatch");
}
if (request.policy == CachePolicy::Disk) {
status = save_jochrtf_atomic(field, target);
if (!status.ok()) {
return status;
}
if (cache_path != nullptr) {
*cache_path = target;
}
}
if (request.policy != CachePolicy::None) {
memory_cache_put(key, field);
}
*out = std::move(field);
return Status::success();
}
} // namespace joc::hrtf
-38
View File
@@ -1,38 +0,0 @@
#pragma once
#include <string>
#include "foundation/status.h"
#include "hrtf/jochrtf.h"
#include "hrtf/sofa_field.h"
// Compiled-field cache: the .jochrtf is an internal artifact, so the caller only
// names the SOFA file and the policy. "memory" keeps the compiled field in this
// process, "disk" additionally reuses (and writes) <cache_dir>/<name>.<key>.jochrtf.
namespace joc::hrtf {
enum class CachePolicy { None, Memory, Disk };
struct SofaFieldRequest {
std::string sofa_path;
CompileOptions options;
CachePolicy policy = CachePolicy::Memory;
std::string cache_dir; // required for the disk policy
};
// Parses "none"/"memory"/"disk"; anything else is rejected.
Status parse_cache_policy(const std::string& text, CachePolicy* out);
// Returns the compiled field, reusing a valid cache when the policy allows it.
// `cache_path` (optional) receives the cache file that was read or written.
Status load_or_compile_sofa_field(const SofaFieldRequest& request, Field* out,
std::string* cache_path);
// Writes the field to `path` through a temporary file and an atomic rename.
Status save_jochrtf_atomic(const Field& field, const std::string& path);
// Verifies that a cache file belongs to `source_sha256` and `cache_key`.
Status validate_jochrtf(const std::string& path, const std::string& source_sha256,
const std::string& cache_key, Field* out);
} // namespace joc::hrtf
File diff suppressed because it is too large. Load diff
-103
View File
@@ -1,103 +0,0 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include "foundation/status.h"
#include "hrtf/jochrtf.h"
#include "hrtf/sofa.h"
// SOFA SimpleFreeFieldHRIR -> compiled directional field, ported from the
// reference chain (sofa_canonical.py + sofa_hrtf_field.py + the public
// filterbank): the measurement shell is selected, one delay representation is
// separated, the FIRs are projected onto the 64-QMF/77-hybrid filterbank and the
// result is fitted with fifth-order ACN/N3D real spherical harmonics.
namespace joc::hrtf {
inline constexpr int kFieldOrder = 5;
inline constexpr int kFieldTerms = 36;
inline constexpr double kFieldSampleRateHz = 48000.0;
inline constexpr double kDefaultShellRadiusM = 1.0;
inline constexpr double kDefaultProjectionRidge = 1.0e-3;
inline constexpr double kDefaultSphericalHarmonicRidge = 1.0e-5;
inline constexpr const char* kCompilerVersion = "joc-sofa-compiler-v1";
inline constexpr const char* kPhasePolicyVersion = "sofa-delay-exactly-once-v1";
inline constexpr const char* kShConvention = "ACN/N3D real";
inline constexpr const char* kFilterbankTableVersion = "joc-public-64qmf-77hybrid-v1";
// SHA-256 of the standard filterbank archive the embedded tables came from. It
// participates in the cache key, so it is part of the file-format contract.
inline constexpr const char* kFilterbankArchiveSha256 =
"C05BEF4D26E96ECBD4694E2572F05DA400255C777BA5047300B9D3B1F81081CD";
struct CompileOptions {
double shell_radius_m = kDefaultShellRadiusM;
int order = kFieldOrder;
double projection_ridge = kDefaultProjectionRidge;
double sh_ridge = kDefaultSphericalHarmonicRidge;
};
// Canonical HRIR set: Data.IR and Data.Delay stay separate, the listener frame is
// applied to the source positions and the ears are ordered left/right.
struct CanonicalHrtf {
std::string source_path;
std::string source_sha256;
std::string convention;
std::string convention_version;
std::string processing_label;
double sample_rate_hz = 0.0;
std::uint32_t measurements = 0;
std::uint32_t taps = 0;
int left_receiver_index = 0;
int right_receiver_index = 1;
std::vector<double> source_position_cartesian_m; // [M,3] listener-local
std::vector<double> unit_directions; // [M,3]
std::vector<double> measurement_radius_m; // [M]
std::vector<double> hrir; // [M,2,N] canonical L/R
std::vector<double> delay_samples; // [M,2], not applied
};
// Port of load_simple_free_field_hrir(): strict SimpleFreeFieldHRIR import.
Status canonicalize_sofa(const SofaHrir& sofa, CanonicalHrtf* out);
// Compiles the canonical set into the runtime field (port of SofaHrtfField.fit).
Status compile_sofa_field(const SofaHrir& sofa, const CompileOptions& options, Field* out);
// The measurements on the shell nearest to radius_m; actual_radius_m receives the
// mean radius of that shell (upstream CanonicalHrtf.shell_indices).
std::vector<std::size_t> canonical_shell_indices(const CanonicalHrtf& canonical, double radius_m,
double* actual_radius_m);
// Compiles an already canonicalized set (used by tests and the cache layer).
Status compile_canonical_field(const CanonicalHrtf& canonical, const CompileOptions& options,
Field* out);
// Configuration hash that names the cache file (upstream compiled_hrtf_cache_key).
std::string compiled_hrtf_cache_key(const std::string& source_sha256, double sample_rate_hz,
double shell_radius_m, int order, double projection_ridge,
double sh_ridge);
// Payload hash over the four arrays (upstream _payload_sha256).
std::string field_payload_sha256(const Field& field);
// "<stem>.<first 20 key digits>.jochrtf", the upstream cache file name.
std::string cache_file_name(const std::string& display_name, const std::string& cache_key);
// Serializes the field as a .jochrtf cache the upstream loader also accepts.
Status write_jochrtf(const Field& field, const std::string& path);
// The analysis/gain/synthesis dictionary the projection solves against (dev check).
std::vector<double> hybrid_gain_synthesis_dictionary_for_check(std::size_t sample_count);
// Shell directions and their spherical Voronoi weights (dev check).
void shell_directions_and_weights_for_check(const SofaHrir& sofa, double radius_m,
std::vector<double>* directions,
std::vector<double>* weights);
// PublicAnalysis77 on a unit impulse, interleaved complex (dev check).
std::vector<double> analysis_impulse_for_check(std::size_t total_samples);
// The 77 hybrid-band centre frequencies at 48 kHz.
const std::vector<double>& hybrid_band_center_frequencies_hz();
} // namespace joc::hrtf
+331
View File
@@ -0,0 +1,331 @@
#include "joc_bitstream/bed_layout_map.h"
#include <cstring>
#include "speaker/speaker_layouts.h"
namespace joc::joc {
namespace {
constexpr std::uint32_t bit(BedChannel channel) {
return 1u << static_cast<unsigned>(channel);
}
// Table 12 每个 bit 展开的声道(LSB 在前)。
struct StandardBit {
BedChannel first;
BedChannel second; // kCount 表示单声道
};
constexpr StandardBit kStandardBits[10] = {
{BedChannel::kLeft, BedChannel::kRight},
{BedChannel::kCenter, BedChannel::kCount},
{BedChannel::kLfe, BedChannel::kCount},
{BedChannel::kLeftSurround, BedChannel::kRightSurround},
{BedChannel::kLeftRearSurround, BedChannel::kRightRearSurround},
{BedChannel::kTopFrontLeft, BedChannel::kTopFrontRight},
{BedChannel::kTopSideLeft, BedChannel::kTopSideRight},
{BedChannel::kTopBackLeft, BedChannel::kTopBackRight},
{BedChannel::kLeftWide, BedChannel::kRightWide},
{BedChannel::kLfe2, BedChannel::kCount},
};
// Table 13 的 17 bit 非标准掩码(LSB 在前)。
constexpr BedChannel kNonStandardBits[17] = {
BedChannel::kLfe2, BedChannel::kRightWide, BedChannel::kLeftWide,
BedChannel::kTopBackRight, BedChannel::kTopBackLeft,
BedChannel::kTopSideRight, BedChannel::kTopSideLeft,
BedChannel::kTopFrontRight, BedChannel::kTopFrontLeft,
BedChannel::kRightRearSurround, BedChannel::kLeftRearSurround,
BedChannel::kRightSurround, BedChannel::kLeftSurround,
BedChannel::kLfe, BedChannel::kCenter, BedChannel::kRight,
BedChannel::kLeft,
};
struct ChannelSpec {
BedChannel channel;
const char* short_name;
const char* label;
double xyz[3];
};
constexpr ChannelSpec kChannels[] = {
{BedChannel::kLeft, "L", "RC_L", {-1.0, 1.0, 0.0}},
{BedChannel::kRight, "R", "RC_R", {1.0, 1.0, 0.0}},
{BedChannel::kCenter, "C", "RC_C", {0.0, 1.0, 0.0}},
{BedChannel::kLfe, "LFE", "RC_LFE", {0.0, 0.0, 0.0}},
{BedChannel::kLeftSurround, "Ls", "RC_LS", {-1.0, 0.0, 0.0}},
{BedChannel::kRightSurround, "Rs", "RC_RS", {1.0, 0.0, 0.0}},
{BedChannel::kLeftRearSurround, "Lrs", "RC_LB", {-1.0, -1.0, 0.0}},
{BedChannel::kRightRearSurround, "Rrs", "RC_RB", {1.0, -1.0, 0.0}},
{BedChannel::kTopFrontLeft, "Ltf", "RC_TFL", {-0.5, 0.5, 1.0}},
{BedChannel::kTopFrontRight, "Rtf", "RC_TFR", {0.5, 0.5, 1.0}},
{BedChannel::kTopSideLeft, "Ltm", "RC_TSL", {-1.0, 0.0, 1.0}},
{BedChannel::kTopSideRight, "Rtm", "RC_TSR", {1.0, 0.0, 1.0}},
{BedChannel::kTopBackLeft, "Ltr", "RC_TBL", {-0.5, -0.5, 1.0}},
{BedChannel::kTopBackRight, "Rtr", "RC_TBR", {0.5, -0.5, 1.0}},
{BedChannel::kLeftWide, "Lw", "RC_LW", {-1.0, 0.5, 0.0}},
{BedChannel::kRightWide, "Rw", "RC_RW", {1.0, 0.5, 0.0}},
{BedChannel::kLfe2, "LFE2", "RC_LFE2", {0.0, 0.0, 0.0}},
};
const ChannelSpec* spec_of(BedChannel channel) {
for (const ChannelSpec& spec : kChannels) {
if (spec.channel == channel) {
return &spec;
}
}
return nullptr;
}
// 标准 bed 布局名,键是声明声道的集合。
struct LayoutName {
std::uint32_t mask;
const char* name;
};
constexpr std::uint32_t mask_of() { return 0u; }
constexpr LayoutName kLayoutNames[] = {
{bit(BedChannel::kLeft) | bit(BedChannel::kRight), "2.0"},
{bit(BedChannel::kLeft) | bit(BedChannel::kRight) | bit(BedChannel::kCenter), "3.0"},
{bit(BedChannel::kLeft) | bit(BedChannel::kRight) | bit(BedChannel::kCenter) |
bit(BedChannel::kLfe), "3.1"},
{bit(BedChannel::kLeft) | bit(BedChannel::kRight) |
bit(BedChannel::kLeftSurround) | bit(BedChannel::kRightSurround), "4.0"},
{bit(BedChannel::kLeft) | bit(BedChannel::kRight) |
bit(BedChannel::kLeftSurround) | bit(BedChannel::kRightSurround) |
bit(BedChannel::kCenter), "5.0"},
{bit(BedChannel::kLeft) | bit(BedChannel::kRight) |
bit(BedChannel::kLeftSurround) | bit(BedChannel::kRightSurround) |
bit(BedChannel::kCenter) | bit(BedChannel::kLfe), "5.1"},
{bit(BedChannel::kLeft) | bit(BedChannel::kRight) |
bit(BedChannel::kLeftSurround) | bit(BedChannel::kRightSurround) |
bit(BedChannel::kCenter) | bit(BedChannel::kLfe) |
bit(BedChannel::kLeftRearSurround) | bit(BedChannel::kRightRearSurround), "7.1"},
{bit(BedChannel::kLeft) | bit(BedChannel::kRight) |
bit(BedChannel::kLeftSurround) | bit(BedChannel::kRightSurround) |
bit(BedChannel::kCenter) | bit(BedChannel::kLfe) |
bit(BedChannel::kLeftRearSurround) | bit(BedChannel::kRightRearSurround) |
bit(BedChannel::kLeftWide) | bit(BedChannel::kRightWide), "9.1"},
{bit(BedChannel::kLeft) | bit(BedChannel::kRight) |
bit(BedChannel::kLeftSurround) | bit(BedChannel::kRightSurround) |
bit(BedChannel::kCenter) | bit(BedChannel::kLfe) |
bit(BedChannel::kTopSideLeft) | bit(BedChannel::kTopSideRight), "5.1.2"},
{bit(BedChannel::kLeft) | bit(BedChannel::kRight) |
bit(BedChannel::kLeftSurround) | bit(BedChannel::kRightSurround) |
bit(BedChannel::kCenter) | bit(BedChannel::kLfe) |
bit(BedChannel::kTopFrontLeft) | bit(BedChannel::kTopFrontRight) |
bit(BedChannel::kTopBackLeft) | bit(BedChannel::kTopBackRight), "5.1.4"},
{bit(BedChannel::kLeft) | bit(BedChannel::kRight) |
bit(BedChannel::kLeftSurround) | bit(BedChannel::kRightSurround) |
bit(BedChannel::kCenter) | bit(BedChannel::kLfe) |
bit(BedChannel::kLeftRearSurround) | bit(BedChannel::kRightRearSurround) |
bit(BedChannel::kTopSideLeft) | bit(BedChannel::kTopSideRight), "7.1.2"},
{bit(BedChannel::kLeft) | bit(BedChannel::kRight) |
bit(BedChannel::kLeftSurround) | bit(BedChannel::kRightSurround) |
bit(BedChannel::kCenter) | bit(BedChannel::kLfe) |
bit(BedChannel::kLeftRearSurround) | bit(BedChannel::kRightRearSurround) |
bit(BedChannel::kTopFrontLeft) | bit(BedChannel::kTopFrontRight) |
bit(BedChannel::kTopBackLeft) | bit(BedChannel::kTopBackRight), "7.1.4"},
{bit(BedChannel::kLeft) | bit(BedChannel::kRight) |
bit(BedChannel::kLeftSurround) | bit(BedChannel::kRightSurround) |
bit(BedChannel::kCenter) | bit(BedChannel::kLfe) |
bit(BedChannel::kLeftRearSurround) | bit(BedChannel::kRightRearSurround) |
bit(BedChannel::kTopFrontLeft) | bit(BedChannel::kTopFrontRight) |
bit(BedChannel::kTopSideLeft) | bit(BedChannel::kTopSideRight) |
bit(BedChannel::kTopBackLeft) | bit(BedChannel::kTopBackRight), "7.1.6"},
{bit(BedChannel::kLeft) | bit(BedChannel::kRight) |
bit(BedChannel::kLeftSurround) | bit(BedChannel::kRightSurround) |
bit(BedChannel::kCenter) | bit(BedChannel::kLfe) |
bit(BedChannel::kLeftRearSurround) | bit(BedChannel::kRightRearSurround) |
bit(BedChannel::kLeftWide) | bit(BedChannel::kRightWide) |
bit(BedChannel::kTopSideLeft) | bit(BedChannel::kTopSideRight), "9.1.2"},
{bit(BedChannel::kLeft) | bit(BedChannel::kRight) |
bit(BedChannel::kLeftSurround) | bit(BedChannel::kRightSurround) |
bit(BedChannel::kCenter) | bit(BedChannel::kLfe) |
bit(BedChannel::kLeftRearSurround) | bit(BedChannel::kRightRearSurround) |
bit(BedChannel::kLeftWide) | bit(BedChannel::kRightWide) |
bit(BedChannel::kTopFrontLeft) | bit(BedChannel::kTopFrontRight) |
bit(BedChannel::kTopBackLeft) | bit(BedChannel::kTopBackRight), "9.1.4"},
{bit(BedChannel::kLeft) | bit(BedChannel::kRight) |
bit(BedChannel::kLeftSurround) | bit(BedChannel::kRightSurround) |
bit(BedChannel::kCenter) | bit(BedChannel::kLfe) |
bit(BedChannel::kLeftRearSurround) | bit(BedChannel::kRightRearSurround) |
bit(BedChannel::kLeftWide) | bit(BedChannel::kRightWide) |
bit(BedChannel::kTopFrontLeft) | bit(BedChannel::kTopFrontRight) |
bit(BedChannel::kTopSideLeft) | bit(BedChannel::kTopSideRight) |
bit(BedChannel::kTopBackLeft) | bit(BedChannel::kTopBackRight), "9.1.6"},
};
const char* layout_name_for(std::uint32_t mask) {
for (const LayoutName& entry : kLayoutNames) {
if (entry.mask == mask) {
return entry.name;
}
}
return "";
}
// 每个扬声器布局的标准声道名(按该布局的标准声道顺序排列)。
struct LayoutChannels {
std::uint32_t out_ch_config;
std::uint32_t count;
const char* names[16];
};
constexpr LayoutChannels kLayoutChannels[] = {
{0, 2, {"L", "R"}},
{3, 4, {"L", "R", "C", "LFE"}},
{255, 4, {"L", "R", "Lrs", "Rrs"}},
{7, 6, {"L", "R", "C", "LFE", "Ls", "Rs"}},
{11, 8, {"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs"}},
{13, 8, {"L", "R", "C", "LFE", "Ls", "Rs", "Ltm", "Rtm"}},
{14, 10, {"L", "R", "C", "LFE", "Ls", "Rs", "Ltf", "Rtf", "Ltr", "Rtr"}},
{15, 10, {"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs", "Ltm", "Rtm"}},
{16, 12, {"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs", "Ltf", "Rtf", "Ltr", "Rtr"}},
{19, 14, {"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs", "Lw", "Rw",
"Ltf", "Rtf", "Ltr", "Rtr"}},
{20, 16, {"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs", "Lw", "Rw",
"Ltf", "Rtf", "Ltm", "Rtm", "Ltr", "Rtr"}},
};
const ejoc::speaker_tables::LayoutGeometry* geometry_for(std::uint32_t out_ch_config) {
for (const ejoc::speaker_tables::LayoutGeometry& layout : ejoc::speaker_tables::kLayouts) {
if (layout.out_ch_config == out_ch_config) {
return &layout;
}
}
return nullptr;
}
} // namespace
BedLayout resolve_bed_layout(const std::vector<oamd::BedAssignment>& assignments,
bool bed_only) {
BedLayout layout;
layout.bed_only = bed_only;
std::uint32_t mask = 0;
for (const oamd::BedAssignment& assignment : assignments) {
if (assignment.lfe_only) {
mask |= bit(BedChannel::kLfe);
layout.complete = false;
continue;
}
if (assignment.standard) {
for (int index = 0; index < 10; ++index) {
if (((assignment.mask >> index) & 1u) == 0u) {
continue;
}
mask |= bit(kStandardBits[index].first);
if (kStandardBits[index].second != BedChannel::kCount) {
mask |= bit(kStandardBits[index].second);
}
}
continue;
}
for (int index = 0; index < 17; ++index) {
if (((assignment.mask >> index) & 1u) != 0u) {
mask |= bit(kNonStandardBits[index]);
}
}
layout.complete = false; // 非标准掩码的声道名不在本标准表里
}
if (mask == 0u) {
return layout;
}
layout.present = true;
layout.mask = mask;
layout.name = layout_name_for(mask);
for (const ChannelSpec& spec : kChannels) {
const BedChannel channel = spec.channel;
if ((mask & bit(channel)) == 0u) {
continue;
}
if (channel == BedChannel::kLfe || channel == BedChannel::kLfe2) {
continue;
}
layout.channels.push_back(channel);
}
return layout;
}
const char* bed_channel_short_name(BedChannel channel) {
const ChannelSpec* spec = spec_of(channel);
return spec != nullptr ? spec->short_name : "";
}
const char* bed_channel_label(BedChannel channel) {
const ChannelSpec* spec = spec_of(channel);
return spec != nullptr ? spec->label : "";
}
bool bed_channel_adm_position(BedChannel channel, double xyz[3]) {
const ChannelSpec* spec = spec_of(channel);
if (spec == nullptr || xyz == nullptr) {
return false;
}
std::memcpy(xyz, spec->xyz, sizeof(spec->xyz));
return true;
}
bool bed_channel_q15(BedChannel channel, std::uint16_t q15[3]) {
double xyz[3] = {0.0, 0.0, 0.0};
if (!bed_channel_adm_position(channel, xyz) || q15 == nullptr) {
return false;
}
const double q1 = (xyz[0] + 1.0) * 0.5 * 32767.0;
const double q2 = (1.0 - xyz[1]) * 0.5 * 32767.0;
const double q3 = xyz[2] * 32767.0;
q15[0] = static_cast<std::uint16_t>(q1 < 0.0 ? 0.0 : (q1 > 32767.0 ? 32767.0 : q1));
q15[1] = static_cast<std::uint16_t>(q2 < 0.0 ? 0.0 : (q2 > 32767.0 ? 32767.0 : q2));
q15[2] = static_cast<std::uint16_t>(q3 < 0.0 ? 0.0 : (q3 > 32767.0 ? 32767.0 : q3));
return true;
}
bool layout_bed_anchor(std::uint32_t out_ch_config, BedChannel channel,
std::uint16_t q15[3]) {
if (q15 == nullptr) {
return false;
}
const char* name = bed_channel_short_name(channel);
if (name == nullptr || name[0] == '\0' || std::strcmp(name, "LFE") == 0) {
return false;
}
const LayoutChannels* table = nullptr;
for (const LayoutChannels& entry : kLayoutChannels) {
if (entry.out_ch_config == out_ch_config) {
table = &entry;
break;
}
}
const ejoc::speaker_tables::LayoutGeometry* geometry = geometry_for(out_ch_config);
if (table == nullptr || geometry == nullptr) {
return false;
}
int standard_index = -1;
for (std::uint32_t index = 0; index < table->count; ++index) {
if (std::strcmp(table->names[index], name) == 0) {
standard_index = static_cast<int>(index);
break;
}
}
if (standard_index < 0) {
return false;
}
const std::uint8_t internal = geometry->standard_from_internal[standard_index];
const ejoc::speaker_tables::RegionGeometry& region = geometry->regions[0];
for (std::uint32_t point = 0; point < region.point_count; ++point) {
if (region.points[point].speaker_id != internal) {
continue;
}
for (int axis = 0; axis < 3; ++axis) {
q15[axis] = region.points[point].coordinate_q15[axis];
}
return true;
}
return false;
}
} // namespace joc::joc
+68
View File
@@ -0,0 +1,68 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include "oamd/oamd_parser.h"
namespace joc::joc {
// OAMD Table 12 的标准 bed 声道。LSB 顺序与声明顺序一致:L/R、C、LFE、
// Ls/Rs、Lrs/Rrs、TFL/TFR、TSL/TSR、TBL/TBR、LW/RW、LFE2。
enum class BedChannel : std::uint8_t {
kLeft = 0,
kRight,
kCenter,
kLfe,
kLeftSurround,
kRightSurround,
kLeftRearSurround,
kRightRearSurround,
kTopFrontLeft,
kTopFrontRight,
kTopSideLeft,
kTopSideRight,
kTopBackLeft,
kTopBackRight,
kLeftWide,
kRightWide,
kLfe2,
kCount,
};
// 内容声明的 bed 布局。bed 对象在 OAMD 里没有位置字段,位置由这里的布局决定。
struct BedLayout {
bool present = false; // 有 bed_assignment() 声明
bool bed_only = false; // program 只由 bed 组成(无 ISF、无动态对象)
bool complete = true; // 所有声明声道都在本标准表里
const char* name = ""; // "9.1.6" 等;未知集合为空串
std::uint32_t mask = 0; // 声明声道的位集合(1 << BedChannel)
std::vector<BedChannel> channels; // 去掉 LFE/LFE2,按 JOC 对象槽顺序
};
// 声明里是否包含某个 bed 声道。
inline bool bed_layout_has(const BedLayout& layout, BedChannel channel) {
return (layout.mask & (1u << static_cast<unsigned>(channel))) != 0u;
}
// 展开 bed_assignment() 声明;``bed_only`` 来自 program_assignment() 的
// content_description。
BedLayout resolve_bed_layout(const std::vector<oamd::BedAssignment>& assignments,
bool bed_only);
// 扬声器布局里的短名("Lw")与 Table 12 的标签("RC_LW")。
const char* bed_channel_short_name(BedChannel channel);
const char* bed_channel_label(BedChannel channel);
// 固定方位:ADM 笛卡尔坐标(x 右、y 前、z 上)与渲染器使用的 Q15 方位。
bool bed_channel_adm_position(BedChannel channel, double xyz[3]);
bool bed_channel_q15(BedChannel channel, std::uint16_t q15[3]);
// 目标布局里同名扬声器的 Q15 方位:bed 声道直连到该扬声器,而不是参与声像。
// 目标布局没有这个声道时返回 false。
bool layout_bed_anchor(std::uint32_t out_ch_config, BedChannel channel,
std::uint16_t q15[3]);
} // namespace joc::joc
+39 -18
View File
@@ -1,5 +1,7 @@
#include "joc_bitstream/joc_parser.h" #include "joc_bitstream/joc_parser.h"
#include "joc_bitstream/bed_layout_map.h"
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
#include <cstring> #include <cstring>
@@ -545,6 +547,26 @@ std::string position_name(Position position) {
} }
} }
// 核心声道位置 → bed 布局声道;返回 kCount 表示本标准表没有对应身份。
BedChannel bed_channel_for_position(Position position) {
switch (position) {
case Position::kLeft: return BedChannel::kLeft;
case Position::kRight: return BedChannel::kRight;
case Position::kCenter: return BedChannel::kCenter;
case Position::kLfe: return BedChannel::kLfe;
case Position::kLfe2: return BedChannel::kLfe2;
case Position::kLeftSurround: return BedChannel::kLeftSurround;
case Position::kRightSurround: return BedChannel::kRightSurround;
case Position::kLeftRearSurround: return BedChannel::kLeftRearSurround;
case Position::kRightRearSurround: return BedChannel::kRightRearSurround;
case Position::kVerticalHeightLeft: return BedChannel::kTopFrontLeft;
case Position::kVerticalHeightRight: return BedChannel::kTopFrontRight;
case Position::kTopSurroundLeft: return BedChannel::kTopSideLeft;
case Position::kTopSurroundRight: return BedChannel::kTopSideRight;
default: return BedChannel::kCount;
}
}
std::string position_list(const std::vector<Position>& positions) { std::string position_list(const std::vector<Position>& positions) {
std::string text = "["; std::string text = "[";
for (std::size_t index = 0; index < positions.size(); ++index) { for (std::size_t index = 0; index < positions.size(); ++index) {
@@ -917,25 +939,24 @@ Status check_cross_layer(const joc_frame_params& params, const eac3::Frame* core
error); error);
} }
if (bed_assignments != nullptr) { if (bed_assignments != nullptr && !bed_assignments->empty()) {
static constexpr std::uint32_t kBedBitLeftRear = 1u << 4; // RC_LB/RC_RB // OAMD 的 bed 掩码描述的是内容的 bed 布局,可以比核心子流实际编码的声道多
static constexpr std::uint32_t kBedBitTopFront = 1u << 5; // RC_TFL/RC_TFR // (例如 9.1.6 bed 只编 5.1 核心)。只有核心声道在 bed 布局里找不到位置才是
std::vector<Position> declared_pair; // 真正的不一致;多出来的 bed 声道是布局的一部分。
for (const oamd::BedAssignment& assignment : *bed_assignments) { const BedLayout bed = resolve_bed_layout(*bed_assignments, true);
if (!assignment.standard || assignment.mask == 0u) { if (bed.present && bed.complete) {
continue; bool covered = true;
for (const Position position : core_positions) {
const BedChannel channel = bed_channel_for_position(position);
if (channel == BedChannel::kCount) {
continue;
}
if (!bed_layout_has(bed, channel)) {
covered = false;
break;
}
} }
if ((assignment.mask & kBedBitLeftRear) != 0u) { if (!covered && notes != nullptr) {
push_unique(&declared_pair, Position::kLeftRearSurround);
push_unique(&declared_pair, Position::kRightRearSurround);
}
if ((assignment.mask & kBedBitTopFront) != 0u) {
push_unique(&declared_pair, Position::kVerticalHeightLeft);
push_unique(&declared_pair, Position::kVerticalHeightRight);
}
}
if (!declared_pair.empty() && declared_pair != wanted) {
if (notes != nullptr) {
notes->bed_mask_mismatch = true; notes->bed_mask_mismatch = true;
} }
} }
+4 -7
View File
@@ -174,10 +174,10 @@ public:
} }
std::memset(output16, 0, sizeof(float) * EJOC_OUTPUT_CHANNELS * EJOC_FRAME_SAMPLES); std::memset(output16, 0, sizeof(float) * EJOC_OUTPUT_CHANNELS * EJOC_FRAME_SAMPLES);
analysis(bed_planar, phase_new); analysis(bed_planar, phase_new, clipgain);
render_lfe(lfe, output_scale, output16); render_lfe(lfe, output_scale, output16);
process_objects(object_mask, n_bands, n_dpoints, slope_idx, offset_ts, process_objects(object_mask, n_bands, n_dpoints, slope_idx, offset_ts,
dq, clipgain, output_scale, output16); dq, output_scale, output16);
return 0; return 0;
} }
@@ -378,13 +378,13 @@ private:
} }
} }
void analysis(const float* bed_planar, const float phase_new) noexcept { void analysis(const float* bed_planar, const float phase_new, const double clipgain) noexcept {
job_bed_ = bed_planar; job_bed_ = bed_planar;
// Analysis-side scalar = the structural 1/16 times this frame's clipgain. // Analysis-side scalar = the structural 1/16 times this frame's clipgain.
// clipgain enters the analysis at this stage and the x16 at the output // clipgain enters the analysis at this stage and the x16 at the output
// cancels the 1/16, so the net effect is a multiply by joc_clipgain; the // cancels the 1/16, so the net effect is a multiply by joc_clipgain; the
// previous frame's scalar is the ramp start. // previous frame's scalar is the ramp start.
const float scalar = static_cast<float>(phase_new * job_clipgain_); const float scalar = static_cast<float>(phase_new * clipgain);
job_phase_old_ = analysis_phase_; job_phase_old_ = analysis_phase_;
if (job_phase_old_ <= 0.0f && job_phase_old_ != 0.0f) { if (job_phase_old_ <= 0.0f && job_phase_old_ != 0.0f) {
job_phase_old_ = scalar; job_phase_old_ = scalar;
@@ -595,7 +595,6 @@ private:
const uint8_t* slope_idx, const uint8_t* slope_idx,
const uint8_t* offset_ts, const uint8_t* offset_ts,
const double* dq, const double* dq,
const double clipgain,
const float output_scale, const float output_scale,
float* output16) noexcept { float* output16) noexcept {
@@ -615,7 +614,6 @@ private:
job_slope_idx_ = slope_idx; job_slope_idx_ = slope_idx;
job_offset_ts_ = offset_ts; job_offset_ts_ = offset_ts;
job_dq_ = dq; job_dq_ = dq;
job_clipgain_ = clipgain;
job_output_scale_ = output_scale; job_output_scale_ = output_scale;
job_output16_ = output16; job_output16_ = output16;
@@ -657,7 +655,6 @@ private:
const uint8_t* job_slope_idx_ = nullptr; const uint8_t* job_slope_idx_ = nullptr;
const uint8_t* job_offset_ts_ = nullptr; const uint8_t* job_offset_ts_ = nullptr;
const double* job_dq_ = nullptr; const double* job_dq_ = nullptr;
double job_clipgain_ = 1.0;
float job_output_scale_ = 1.0f; float job_output_scale_ = 1.0f;
float* job_output16_ = nullptr; float* job_output16_ = nullptr;
+175
View File
@@ -15,6 +15,13 @@ constexpr int kRampDurationIndex[16] = {32, 64, 128, 256, 320, 480,
1000, 1001, 1024, 1600, 1601, 1602, 1000, 1001, 1024, 1600, 1601, 1602,
1920, 2000, 2002, 2048}; 1920, 2000, 2002, 2048};
constexpr std::uint32_t kObjectElementId = 1; constexpr std::uint32_t kObjectElementId = 1;
// ETSI TS 103 420 Table 12 trim levels, 4-bit index, dB; index 15 is the
// minimum (-36 dB), not silence.
constexpr double kTrimLut[16] = {6.0, 3.0, 1.5, 0.75, -0.75, -1.5,
-3.0, -4.5, -6.0, -7.5, -9.0, -10.5,
-12.0, -13.5, -15.0, -36.0};
// bal3d_y is coded as (code + 1) / 16, so the magnitude never reaches 0.
constexpr double kBalanceStep = 16.0;
constexpr int kIsfObjectCounts[6] = {4, 8, 10, 14, 15, 30}; constexpr int kIsfObjectCounts[6] = {4, 8, 10, 14, 15, 30};
constexpr int kStandardBedChannelCount[10] = {2, 1, 1, 2, 2, 2, 2, 2, 2, 1}; constexpr int kStandardBedChannelCount[10] = {2, 1, 1, 2, 2, 2, 2, 2, 2, 1};
@@ -64,6 +71,9 @@ bool variable_bits_max(bits::BitReader& reader, unsigned width, unsigned max_gro
struct ProgramInfo { struct ProgramInfo {
bool dynamic_object_only = false; bool dynamic_object_only = false;
bool lfe_present = false; bool lfe_present = false;
bool content_bed = false;
bool content_isf = false;
bool content_dynamic = false;
std::uint32_t num_bed_objects = 0; std::uint32_t num_bed_objects = 0;
std::uint32_t num_isf_objects = 0; std::uint32_t num_isf_objects = 0;
std::int32_t num_dynamic_objects = -1; std::int32_t num_dynamic_objects = -1;
@@ -88,6 +98,9 @@ Status parse_program_assignment(bits::BitReader& reader, ProgramInfo* program) {
if (reader.failed()) { if (reader.failed()) {
return syntax("program_assignment truncated"); return syntax("program_assignment truncated");
} }
program->content_bed = (mask & 0x1u) != 0u;
program->content_isf = (mask & 0x2u) != 0u;
program->content_dynamic = (mask & 0x4u) != 0u;
if ((mask & 0x1u) != 0u) { if ((mask & 0x1u) != 0u) {
reader.read(1); reader.read(1);
const std::uint32_t multi = reader.read(1); const std::uint32_t multi = reader.read(1);
@@ -323,6 +336,72 @@ Status parse_object_element(bits::BitReader& reader, std::uint32_t object_count,
return Status::success(); return Status::success();
} }
// trim_element(): one programme-wide record per payload. The first bit of each
// configuration is b_default_trim; b_disable_trim and the value record follow
// only when that bit is clear.
Status parse_trim_element(bits::BitReader& reader, std::uint32_t object_count, OamdTrim* out) {
OamdTrim trim;
trim.warp_mode = reader.read(2);
reader.read(2); // reserved
trim.global_trim_mode = reader.read(2);
if (reader.failed()) {
return syntax("OAMD trim element header truncated");
}
if (trim.global_trim_mode == 2u) {
for (int config = 0; config < kTrimConfigs; ++config) {
TrimConfig& record = trim.configs[config];
if (reader.read(1) != 0u) {
record.kind = TrimConfigKind::kDefault;
continue;
}
if (reader.read(1) != 0u) {
record.kind = TrimConfigKind::kDisabled;
continue;
}
record.kind = TrimConfigKind::kExplicit;
const std::uint32_t presence = reader.read(5);
record.presence = static_cast<std::uint8_t>(presence);
if ((presence & 0x01u) != 0u) {
record.centre = kTrimLut[reader.read(4) & 0x0Fu];
}
if ((presence & 0x02u) != 0u) {
record.surround = kTrimLut[reader.read(4) & 0x0Fu];
}
if ((presence & 0x04u) != 0u) {
record.height = kTrimLut[reader.read(4) & 0x0Fu];
}
if ((presence & 0x08u) != 0u) {
const double sign = reader.read(1) != 0u ? 1.0 : -1.0;
record.balance_overhead =
(static_cast<double>(reader.read(4)) + 1.0) / kBalanceStep * sign;
}
if ((presence & 0x10u) != 0u) {
const double sign = reader.read(1) != 0u ? 1.0 : -1.0;
record.balance_listener =
(static_cast<double>(reader.read(4)) + 1.0) / kBalanceStep * sign;
}
if (reader.failed()) {
return syntax("OAMD trim configuration " + std::to_string(config) +
" truncated");
}
}
}
if (reader.read(1) != 0u) {
for (std::uint32_t index = 0; index < object_count; ++index) {
const bool bypass = reader.read(1) != 0u;
if (index < static_cast<std::uint32_t>(kMaxSlots)) {
trim.disable_per_object[index] = bypass;
}
}
}
if (reader.failed()) {
return syntax("OAMD trim bypass table truncated");
}
trim.object_count = object_count;
*out = trim;
return Status::success();
}
} // namespace } // namespace
int q_of(int k, int n) { int q_of(int k, int n) {
@@ -371,6 +450,85 @@ Status parse_id11_bed_assignments(const std::uint8_t* payload, std::size_t paylo
return Status::success(); return Status::success();
} }
Status parse_trim(const std::uint8_t* payload, std::size_t payload_size, OamdTrim* out,
bool* present) {
if (payload == nullptr || out == nullptr || present == nullptr) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kOamd, "null payload or output");
}
*present = false;
if (payload_size == 0) {
return variant("header_truncated", "OAMD payload is empty");
}
bits::BitReader reader(payload, payload_size);
std::uint32_t version = reader.read(2);
if (reader.failed()) {
return variant("header_truncated", "OAMD payload cannot hold the 2-bit version");
}
if (version == 3u) {
version += reader.read(3);
if (reader.failed()) {
return syntax("OAMD version extension truncated");
}
}
std::uint32_t object_count_bits = reader.read(5);
if (object_count_bits == 0x1Fu) {
object_count_bits += reader.read(7);
}
if (reader.failed()) {
return syntax("OAMD object count truncated");
}
const std::uint32_t object_count = object_count_bits + 1u;
ProgramInfo program;
const Status program_status = parse_program_assignment(reader, &program);
if (!program_status.ok()) {
return program_status;
}
const std::uint32_t alternate_present = reader.read(1);
std::uint32_t element_count = reader.read(4);
if (element_count == 0xFu) {
element_count += reader.read(5);
}
if (reader.failed()) {
return syntax("OAMD element count truncated");
}
for (std::uint32_t ordinal = 0; ordinal < element_count; ++ordinal) {
const std::uint32_t element_id = reader.read(4);
std::uint32_t size_field = 0;
if (!variable_bits_max(reader, 4, 4, &size_field)) {
return syntax("OAMD element header truncated at ordinal " + std::to_string(ordinal));
}
const std::uint32_t size_bytes = size_field + 1u;
const std::size_t region_start = reader.position();
const std::size_t region_end = region_start + static_cast<std::size_t>(size_bytes) * 8u;
if (region_end > reader.limit()) {
return variant("element_bounds",
"element " + std::to_string(ordinal) + " (id " +
std::to_string(element_id) + ") declares " +
std::to_string(size_bytes) + " bytes, beyond the payload");
}
if (alternate_present != 0u) {
reader.read(4);
}
reader.read(1);
if (reader.failed()) {
return syntax("OAMD element control fields truncated at ordinal " +
std::to_string(ordinal));
}
if (element_id == kTrimElementId) {
const Status parsed = parse_trim_element(reader, object_count, out);
if (!parsed.ok()) {
return parsed;
}
*present = true;
return Status::success();
}
if (!reader.skip(region_end - reader.position())) {
return syntax("OAMD element skip past payload end");
}
}
return Status::success();
}
Status parse_id11_verbose(const std::uint8_t* payload, std::size_t payload_size, OamdUpdate* out, Status parse_id11_verbose(const std::uint8_t* payload, std::size_t payload_size, OamdUpdate* out,
ParseTrace* trace) { ParseTrace* trace) {
if (payload == nullptr || out == nullptr) { if (payload == nullptr || out == nullptr) {
@@ -469,6 +627,20 @@ Status parse_id11_verbose(const std::uint8_t* payload, std::size_t payload_size,
reader.set_limit_bits(reader.limit()); reader.set_limit_bits(reader.limit());
reader.skip(region_end - reader.position()); reader.skip(region_end - reader.position());
} }
} else if (element_id == kTrimElementId) {
OamdTrim trim;
const Status parsed = parse_trim_element(reader, object_count, &trim);
if (!parsed.ok()) {
return parsed;
}
if (!out->has_trim) {
out->trim = trim;
out->has_trim = true;
}
if (reader.position() < region_end) {
reader.set_limit_bits(reader.limit());
reader.skip(region_end - reader.position());
}
} else { } else {
if (!reader.skip(region_end - reader.position())) { if (!reader.skip(region_end - reader.position())) {
return syntax("OAMD element skip past payload end"); return syntax("OAMD element skip past payload end");
@@ -520,6 +692,9 @@ Status parse_id11_verbose(const std::uint8_t* payload, std::size_t payload_size,
out->num_bed_objects = program.num_bed_objects; out->num_bed_objects = program.num_bed_objects;
out->num_isf_objects = program.num_isf_objects; out->num_isf_objects = program.num_isf_objects;
out->num_dynamic_objects = program.num_dynamic_objects; out->num_dynamic_objects = program.num_dynamic_objects;
out->content_bed = program.content_bed;
out->content_isf = program.content_isf;
out->content_dynamic = program.content_dynamic;
if (trace != nullptr) { if (trace != nullptr) {
trace->bed_assignments = program.bed_assignments; trace->bed_assignments = program.bed_assignments;
+48
View File
@@ -17,6 +17,38 @@ inline constexpr int kAxes = 3;
inline constexpr int kNQ12 = 62; inline constexpr int kNQ12 = 62;
inline constexpr int kNQ3 = 15; inline constexpr int kNQ3 = 15;
inline constexpr int kQ15Scale = 32768; inline constexpr int kQ15Scale = 32768;
inline constexpr std::uint32_t kTrimElementId = 2;
inline constexpr int kTrimConfigs = 9;
// One of the nine per-configuration trim records of the OAMD trim element.
// ``kAbsent`` means the configuration carries no data (the element only
// carries explicit records when global_trim_mode is 2).
enum class TrimConfigKind : std::uint8_t {
kAbsent = 0,
kDefault,
kDisabled,
kExplicit,
};
struct TrimConfig {
TrimConfigKind kind = TrimConfigKind::kAbsent;
std::uint8_t presence = 0; // b_*_trim_present bits of an explicit record
double centre = 0.0; // dB
double surround = 0.0; // dB
double height = 0.0; // dB
double balance_overhead = 0.0; // bal3d_y_tb, [-1, 1]
double balance_listener = 0.0; // bal3d_y_lis, [-1, 1]
};
// Programme calibration carried by the OAMD trim element: warp mode, global
// trim mode, the nine configuration records and the per-object bypass flags.
struct OamdTrim {
std::uint32_t warp_mode = 0;
std::uint32_t global_trim_mode = 0;
TrimConfig configs[kTrimConfigs];
std::uint32_t object_count = 0;
bool disable_per_object[kMaxSlots] = {};
};
// (the reference's None), i.e. hold the previous position. // (the reference's None), i.e. hold the previous position.
struct SlotUpdate { struct SlotUpdate {
@@ -35,6 +67,15 @@ struct OamdUpdate {
std::uint32_t num_bed_objects = 0; std::uint32_t num_bed_objects = 0;
std::uint32_t num_isf_objects = 0; std::uint32_t num_isf_objects = 0;
std::int32_t num_dynamic_objects = -1; std::int32_t num_dynamic_objects = -1;
// program_assignment() 的 content_description:bed / ISF / 动态对象三类内容。
bool content_bed = false;
bool content_isf = false;
bool content_dynamic = false;
// Trim element of this payload. The element describes the programme, so
// ``has_trim`` only marks the payloads that carry it; a payload without it
// keeps whatever controls the caller already holds.
OamdTrim trim;
bool has_trim = false;
}; };
class OamdState { class OamdState {
@@ -80,6 +121,13 @@ int q_of(int k, int n);
Status parse_id11(const std::uint8_t* payload, std::size_t payload_size, OamdUpdate* out); Status parse_id11(const std::uint8_t* payload, std::size_t payload_size, OamdUpdate* out);
// Parses only the trim element of a payload. ``out`` receives the first trim
// element found; ``*present`` is false when the payload carries none. decode
// paths that need the OAMD calibration but no object state can use this
// without requiring an object element.
Status parse_trim(const std::uint8_t* payload, std::size_t payload_size, OamdTrim* out,
bool* present);
struct BedAssignment { struct BedAssignment {
bool lfe_only = false; bool lfe_only = false;
bool standard = false; bool standard = false;
+17 -10
View File
@@ -10,19 +10,23 @@ struct FrozenLayout {
const char* name; const char* name;
std::uint32_t out_ch_config; std::uint32_t out_ch_config;
std::uint32_t speaker_bitfield; std::uint32_t speaker_bitfield;
std::uint32_t surround_channels;
std::uint32_t height_channels;
bool carries_trim;
}; };
constexpr FrozenLayout kLayouts[kLayoutCount] = { constexpr FrozenLayout kLayouts[kLayoutCount] = {
{"2.0", 0, 1}, {"2.0", 0, 1, 0, 0, true},
{"3.1", 3, 7}, {"3.1", 3, 7, 0, 0, true},
{"5.1", 7, 15}, {"4.0", 0xFF, 9, 2, 0, true},
{"7.1", 11, 31}, {"5.1", 7, 15, 2, 0, true},
{"5.1.2", 13, 1039}, {"7.1", 11, 31, 4, 0, true},
{"5.1.4", 14, 2575}, {"5.1.2", 13, 1039, 2, 2, true},
{"7.1.2", 15, 1055}, {"5.1.4", 14, 2575, 2, 4, true},
{"7.1.4", 16, 2591}, {"7.1.2", 15, 1055, 4, 2, false},
{"9.1.4", 19, 2719}, {"7.1.4", 16, 2591, 4, 4, false},
{"9.1.6", 20, 3743}, {"9.1.4", 19, 2719, 4, 4, false},
{"9.1.6", 20, 3743, 4, 6, false},
}; };
void fill(const FrozenLayout& source, LayoutInfo* out) { void fill(const FrozenLayout& source, LayoutInfo* out) {
@@ -30,6 +34,9 @@ void fill(const FrozenLayout& source, LayoutInfo* out) {
out->out_ch_config = source.out_ch_config; out->out_ch_config = source.out_ch_config;
out->speaker_bitfield = source.speaker_bitfield; out->speaker_bitfield = source.speaker_bitfield;
out->channel_count = ejoc_speaker_layout_channel_count(source.speaker_bitfield); out->channel_count = ejoc_speaker_layout_channel_count(source.speaker_bitfield);
out->surround_channels = source.surround_channels;
out->height_channels = source.height_channels;
out->carries_trim = source.carries_trim;
} }
} // namespace } // namespace
+13 -3
View File
@@ -8,19 +8,29 @@
namespace joc::speaker { namespace joc::speaker {
inline constexpr int kLayoutCount = 10; inline constexpr int kLayoutCount = 11;
struct LayoutInfo { struct LayoutInfo {
const char* name = ""; const char* name = "";
std::uint32_t out_ch_config = 0; std::uint32_t out_ch_config = 0;
std::uint32_t speaker_bitfield = 0; std::uint32_t speaker_bitfield = 0;
std::uint32_t channel_count = 0; std::uint32_t channel_count = 0;
// Ls/Rs/Lrs/Rrs and Ltf/Rtf/Ltr/Rtr/Ltm/Rtm, the labels the OAMD trim
// configuration index counts.
std::uint32_t surround_channels = 0;
std::uint32_t height_channels = 0;
// One of the seven layouts that carry OAMD trim and front-back balance
// semantics; wider layouts leave the programme untrimmed.
bool carries_trim = false;
}; };
// All ten layouts in the reference's order (2.0, 3.1, 5.1, 7.1, 5.1.2, 5.1.4, // All eleven layouts in the reference's order (2.0, 3.1, 4.0, 5.1, 7.1, 5.1.2,
// 5.1.4, 7.1.2, 7.1.4, 9.1.4, 9.1.6).
bool layout_at(int index, LayoutInfo* out); bool layout_at(int index, LayoutInfo* out);
// False when the name is unknown (case-sensitive, exactly as the reference CLI). // False when the name is unknown (case-sensitive, as the reference CLI). "4.0"
// is the quad layout (L R Lrs Rrs); a stored value is normalized by the caller
// before the name is looked up here.
bool layout_by_name(const char* name, LayoutInfo* out); bool layout_by_name(const char* name, LayoutInfo* out);
bool layout_by_bitfield(std::uint32_t bitfield, LayoutInfo* out); bool layout_by_bitfield(std::uint32_t bitfield, LayoutInfo* out);
+49 -1
View File
@@ -39,7 +39,7 @@ struct LayoutGeometry {
std::array<RegionGeometry, 7> regions{}; std::array<RegionGeometry, 7> regions{};
}; };
inline constexpr std::array<LayoutGeometry, 10> kLayouts{{ inline constexpr std::array<LayoutGeometry, 11> kLayouts{{
LayoutGeometry{ LayoutGeometry{
0x1u, 0, 2, 0x1u, 0, 2,
{{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
@@ -136,6 +136,54 @@ inline constexpr std::array<LayoutGeometry, 10> kLayouts{{
} }
}} }}
}, },
LayoutGeometry{
0x9u, 0xFFu, 4,
{{0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{{
RegionGeometry{
4, 2, 2, 0,
{{SpeakerPoint{{0, 0, 0}, 0}, SpeakerPoint{{32767, 0, 0}, 1}, SpeakerPoint{{0, 32767, 0}, 2}, SpeakerPoint{{32767, 32767, 0}, 3}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}}},
{{AxisGroup{2, {0, 1, 0}}, AxisGroup{2, {2, 3, 0}}, AxisGroup{}, AxisGroup{}}},
{{AxisGroup{}, AxisGroup{}, AxisGroup{}, AxisGroup{}}}
},
RegionGeometry{
4, 2, 2, 0,
{{SpeakerPoint{{0, 0, 0}, 0}, SpeakerPoint{{32767, 0, 0}, 1}, SpeakerPoint{{0, 32767, 0}, 2}, SpeakerPoint{{32767, 32767, 0}, 3}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}}},
{{AxisGroup{2, {0, 1, 0}}, AxisGroup{2, {2, 3, 0}}, AxisGroup{}, AxisGroup{}}},
{{AxisGroup{}, AxisGroup{}, AxisGroup{}, AxisGroup{}}}
},
RegionGeometry{
4, 2, 2, 0,
{{SpeakerPoint{{0, 0, 0}, 0}, SpeakerPoint{{32767, 0, 0}, 1}, SpeakerPoint{{0, 32767, 0}, 2}, SpeakerPoint{{32767, 32767, 0}, 3}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}}},
{{AxisGroup{2, {0, 1, 0}}, AxisGroup{2, {2, 3, 0}}, AxisGroup{}, AxisGroup{}}},
{{AxisGroup{}, AxisGroup{}, AxisGroup{}, AxisGroup{}}}
},
RegionGeometry{
2, 1, 1, 0,
{{SpeakerPoint{{0, 32767, 0}, 2}, SpeakerPoint{{32767, 32767, 0}, 3}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}}},
{{AxisGroup{2, {0, 1, 0}}, AxisGroup{}, AxisGroup{}, AxisGroup{}}},
{{AxisGroup{}, AxisGroup{}, AxisGroup{}, AxisGroup{}}}
},
RegionGeometry{
2, 1, 1, 0,
{{SpeakerPoint{{0, 0, 0}, 0}, SpeakerPoint{{32767, 0, 0}, 1}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}}},
{{AxisGroup{2, {0, 1, 0}}, AxisGroup{}, AxisGroup{}, AxisGroup{}}},
{{AxisGroup{}, AxisGroup{}, AxisGroup{}, AxisGroup{}}}
},
RegionGeometry{
2, 1, 1, 0,
{{SpeakerPoint{{0, 32767, 0}, 2}, SpeakerPoint{{32767, 32767, 0}, 3}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}}},
{{AxisGroup{2, {0, 1, 0}}, AxisGroup{}, AxisGroup{}, AxisGroup{}}},
{{AxisGroup{}, AxisGroup{}, AxisGroup{}, AxisGroup{}}}
},
RegionGeometry{
2, 1, 1, 0,
{{SpeakerPoint{{0, 0, 0}, 0}, SpeakerPoint{{32767, 0, 0}, 1}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}}},
{{AxisGroup{2, {0, 1, 0}}, AxisGroup{}, AxisGroup{}, AxisGroup{}}},
{{AxisGroup{}, AxisGroup{}, AxisGroup{}, AxisGroup{}}}
}
}}
},
LayoutGeometry{ LayoutGeometry{
0xFu, 7, 6, 0xFu, 7, 6,
{{0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
+89 -12
View File
@@ -1,5 +1,6 @@
#define EJOC_BUILD_DLL #define EJOC_BUILD_DLL
#include "eac3joc_core.h" #include "eac3joc_core.h"
#include "speaker/speaker_trim.h"
#include "speaker_layouts.h" #include "speaker_layouts.h"
#include <algorithm> #include <algorithm>
@@ -216,6 +217,7 @@ public:
const std::uint8_t* region_indices, const std::uint8_t* region_indices,
const std::uint8_t* height_enabled, const std::uint8_t* height_enabled,
const double* object_gains, const double* object_gains,
const ejoc_speaker_controls* controls,
double* output) noexcept { double* output) noexcept {
error_[0] = '\0'; error_[0] = '\0';
if (!input || !output) { if (!input || !output) {
@@ -227,11 +229,21 @@ public:
if (metadata_count && (!metadata_offsets || !ramp_durations || !positions_q15)) { if (metadata_count && (!metadata_offsets || !ramp_durations || !positions_q15)) {
return fail("metadata arrays are null while metadata_count is nonzero"); return fail("metadata arrays are null while metadata_count is nonzero");
} }
if (!validate_controls(controls)) {
return -1;
}
if (!validate_metadata(sample_count, metadata_count, metadata_offsets, if (!validate_metadata(sample_count, metadata_count, metadata_offsets,
positions_q15, region_indices, object_gains)) { positions_q15, region_indices, object_gains)) {
return -1; return -1;
} }
// A caller that passes no controls gets warp 0, no trim and no balance.
ejoc_speaker_controls fallback{};
fallback.struct_size = sizeof(fallback);
fallback.struct_version = EJOC_SPEAKER_CONTROLS_VERSION;
fallback.trim_mode = EJOC_SPEAKER_TRIM_DISABLED;
const ejoc_speaker_controls& active = controls != nullptr ? *controls : fallback;
std::fill(output, output + static_cast<std::size_t>(sample_count) * layout_->channel_count, 0.0); std::fill(output, output + static_cast<std::size_t>(sample_count) * layout_->channel_count, 0.0);
const bool has_lfe = (layout_->speaker_bitfield & 0x4u) != 0; const bool has_lfe = (layout_->speaker_bitfield & 0x4u) != 0;
const std::size_t total_blocks = sample_count / kBlock; const std::size_t total_blocks = sample_count / kBlock;
@@ -239,14 +251,14 @@ public:
for (std::size_t block = 0; block < total_blocks; ++block) { for (std::size_t block = 0; block < total_blocks; ++block) {
while (event < metadata_count && aligned_block(metadata_offsets[event]) == block) { while (event < metadata_count && aligned_block(metadata_offsets[event]) == block) {
apply_event(event, ramp_durations, positions_q15, region_indices, apply_event(event, ramp_durations, positions_q15, region_indices,
height_enabled, object_gains); height_enabled, object_gains, active);
++event; ++event;
} }
mix_block(input, output, block, has_lfe); mix_block(input, output, block, has_lfe);
} }
while (event < metadata_count && aligned_block(metadata_offsets[event]) == total_blocks) { while (event < metadata_count && aligned_block(metadata_offsets[event]) == total_blocks) {
apply_event(event, ramp_durations, positions_q15, region_indices, apply_event(event, ramp_durations, positions_q15, region_indices,
height_enabled, object_gains); height_enabled, object_gains, active);
++event; ++event;
} }
if (event != metadata_count) { if (event != metadata_count) {
@@ -268,6 +280,42 @@ private:
return -1; return -1;
} }
bool validate_controls(const ejoc_speaker_controls* controls) noexcept {
if (controls == nullptr) {
return true;
}
if (controls->struct_size != sizeof(ejoc_speaker_controls)) {
fail("speaker controls struct_size mismatch");
return false;
}
if (controls->struct_version != EJOC_SPEAKER_CONTROLS_VERSION) {
fail("unknown speaker controls struct_version");
return false;
}
if (controls->warp_mode > 1u) {
fail("speaker rendering implements warp modes 0/1 only");
return false;
}
if (controls->trim_mode > EJOC_SPEAKER_TRIM_EXPLICIT) {
fail("unknown speaker trim mode");
return false;
}
for (const double level :
{controls->centre_db, controls->surround_db, controls->height_db}) {
if (!std::isfinite(level)) {
fail("trim level is not finite");
return false;
}
}
for (const double balance : {controls->listener_balance, controls->overhead_balance}) {
if (!std::isfinite(balance) || balance < -1.0 || balance > 1.0) {
fail("balance is not finite or outside [-1, 1]");
return false;
}
}
return true;
}
bool validate_metadata(const std::uint32_t sample_count, bool validate_metadata(const std::uint32_t sample_count,
const std::uint32_t metadata_count, const std::uint32_t metadata_count,
const std::uint32_t* metadata_offsets, const std::uint32_t* metadata_offsets,
@@ -318,13 +366,28 @@ private:
const std::uint8_t region_index, const std::uint8_t region_index,
const bool enable_height, const bool enable_height,
const double object_gain, const double object_gain,
const ejoc_speaker_controls& controls,
const bool bypass_trim,
ChannelGains& output) const noexcept { ChannelGains& output) const noexcept {
output.fill(0.0); output.fill(0.0);
const auto& region = layout_->regions[region_index]; const auto& region = layout_->regions[region_index];
const double u = static_cast<double>(position[0]) / kQ15Scale; const double u = static_cast<double>(position[0]) / kQ15Scale;
const double v = static_cast<double>(position[1]) / kQ15Scale; const double v = static_cast<double>(position[1]) / kQ15Scale;
const double w = static_cast<double>(position[2]) / kQ15Scale; const double w = std::max(static_cast<double>(position[2]) / kQ15Scale, 0.0);
const double floor_v = clamp(std::ldexp(v, floor_y_exponent_), 0.0, 1.0); const int shift = controls.warp_mode == 1u ? floor_y_exponent_ : 0;
double floor_v = clamp(std::ldexp(v, shift), 0.0, 1.0);
double top_v = clamp(v, 0.0, 1.0);
double trim_v = v;
if (controls.trim_mode == EJOC_SPEAKER_TRIM_EXPLICIT && !bypass_trim) {
// Warp feeds the floor coordinate only: the height and trim
// coordinates see the balance map on the original Y.
floor_v = joc::speaker::apply_balance(floor_v, w, controls.listener_balance,
controls.overhead_balance);
top_v = joc::speaker::apply_balance(top_v, w, controls.listener_balance,
controls.overhead_balance);
trim_v = joc::speaker::apply_balance(v, w, controls.listener_balance,
controls.overhead_balance);
}
PointGains floor{}; PointGains floor{};
plane_gains(region, region.axis0_groups, region.axis0_group_count, plane_gains(region, region.axis0_groups, region.axis0_group_count,
u, floor_v, region.mode, floor); u, floor_v, region.mode, floor);
@@ -332,7 +395,7 @@ private:
if (region.mode == 3) { if (region.mode == 3) {
PointGains height{}; PointGains height{};
plane_gains(region, region.axis1_groups, region.axis1_group_count, plane_gains(region, region.axis1_groups, region.axis1_group_count,
u, v, 3, height); u, top_v, 3, height);
const double z = enable_height ? clamp(w, 0.0, kQ15Max) : 0.0; const double z = enable_height ? clamp(w, 0.0, kQ15Max) : 0.0;
if (z >= kQ15Max) { if (z >= kQ15Max) {
point = height; point = height;
@@ -345,21 +408,33 @@ private:
} }
} }
} }
const double y_term = clamp(v / 0.6, 0.0, 1.0); double gain = object_gain;
const double z_term = clamp((w - 0.2) / 0.8, 0.0, 1.0); if (!bypass_trim) {
const double amount = clamp(y_term + z_term, 0.0, 1.0); if (controls.trim_mode == EJOC_SPEAKER_TRIM_AUTOMATIC) {
const double gain = std::pow(10.0, attenuation_db_ * amount / 20.0) * object_gain; gain *= position_gain(trim_v, w);
} else if (controls.trim_mode == EJOC_SPEAKER_TRIM_EXPLICIT) {
gain *= joc::speaker::explicit_position_gain(controls, u, trim_v, w);
}
}
for (std::size_t index = 0; index < region.point_count; ++index) { for (std::size_t index = 0; index < region.point_count; ++index) {
output[region.points[index].speaker_id] = point[index] * gain; output[region.points[index].speaker_id] = point[index] * gain;
} }
} }
double position_gain(const double v, const double w) const noexcept {
const double y_term = clamp(v / 0.6, 0.0, 1.0);
const double z_term = clamp((w - 0.2) / 0.8, 0.0, 1.0);
const double amount = clamp(y_term + z_term, 0.0, 1.0);
return std::pow(10.0, attenuation_db_ * amount / 20.0);
}
void apply_event(const std::size_t event, void apply_event(const std::size_t event,
const std::uint32_t* ramp_durations, const std::uint32_t* ramp_durations,
const std::uint16_t* positions_q15, const std::uint16_t* positions_q15,
const std::uint8_t* region_indices, const std::uint8_t* region_indices,
const std::uint8_t* height_enabled, const std::uint8_t* height_enabled,
const double* object_gains) noexcept { const double* object_gains,
const ejoc_speaker_controls& controls) noexcept {
const std::uint32_t blocks = ramp_blocks(ramp_durations[event]); const std::uint32_t blocks = ramp_blocks(ramp_durations[event]);
for (std::size_t object = 0; object < kObjects; ++object) { for (std::size_t object = 0; object < kObjects; ++object) {
const std::size_t object_event = event * kObjects + object; const std::size_t object_event = event * kObjects + object;
@@ -367,8 +442,9 @@ private:
const std::uint8_t region = region_indices ? region_indices[object_event] : 0; const std::uint8_t region = region_indices ? region_indices[object_event] : 0;
const bool height = !height_enabled || height_enabled[object_event] != 0; const bool height = !height_enabled || height_enabled[object_event] != 0;
const double object_gain = object_gains ? object_gains[object_event] : 1.0; const double object_gain = object_gains ? object_gains[object_event] : 1.0;
const bool bypass = controls.trim_bypass[object + 1] != 0u;
ChannelGains next{}; ChannelGains next{};
render_point(position, region, height, object_gain, next); render_point(position, region, height, object_gain, controls, bypass, next);
for (std::size_t channel = 0; channel < layout_->channel_count; ++channel) { for (std::size_t channel = 0; channel < layout_->channel_count; ++channel) {
const double difference = next[channel] - current_[object][channel]; const double difference = next[channel] - current_[object][channel];
target_[object][channel] = next[channel]; target_[object][channel] = next[channel];
@@ -482,6 +558,7 @@ int EJOC_CALL ejoc_speaker_renderer_process(
const uint8_t* region_indices, const uint8_t* region_indices,
const uint8_t* height_enabled, const uint8_t* height_enabled,
const double* object_gains, const double* object_gains,
const ejoc_speaker_controls* controls,
double* output_interleaved) { double* output_interleaved) {
if (!handle) { if (!handle) {
return -1; return -1;
@@ -489,7 +566,7 @@ int EJOC_CALL ejoc_speaker_renderer_process(
return static_cast<ejoc::speaker::Renderer*>(handle)->process( return static_cast<ejoc::speaker::Renderer*>(handle)->process(
objects16_interleaved, sample_count, metadata_count, objects16_interleaved, sample_count, metadata_count,
metadata_offsets, ramp_durations, positions_q15, metadata_offsets, ramp_durations, positions_q15,
region_indices, height_enabled, object_gains, output_interleaved); region_indices, height_enabled, object_gains, controls, output_interleaved);
} }
} // extern "C" } // extern "C"
+30 -1
View File
@@ -26,8 +26,29 @@ Status step(SpeakerStep* context, const std::vector<float>& objects16_planar,
static_cast<std::size_t>(JOC_FRAME_SAMPLES) * context->layout.channel_count, 0.0); static_cast<std::size_t>(JOC_FRAME_SAMPLES) * context->layout.channel_count, 0.0);
context->last_had_payload = update != nullptr; context->last_had_payload = update != nullptr;
if (!context->controls_ready) {
const Status status =
parameters_from_oamd(nullptr, context->layout, &context->controls);
if (!status.ok()) {
if (error != nullptr) {
*error = status.message();
}
return status;
}
context->controls_ready = true;
}
std::uint32_t ramp = 0; std::uint32_t ramp = 0;
if (update != nullptr) { if (update != nullptr) {
if (update->has_trim) {
const Status status = parameters_from_oamd(&update->trim, context->layout,
&context->controls);
if (!status.ok()) {
if (error != nullptr) {
*error = status.message();
}
return status;
}
}
context->state.apply(*update); context->state.apply(*update);
ramp = update->ramp_duration_samples; ramp = update->ramp_duration_samples;
context->last_block_offset = update->block_offset_samples; context->last_block_offset = update->block_offset_samples;
@@ -37,6 +58,14 @@ Status step(SpeakerStep* context, const std::vector<float>& objects16_planar,
std::uint16_t positions[oamd::kObjects][3] = {}; std::uint16_t positions[oamd::kObjects][3] = {};
context->state.object_positions_q15(positions); context->state.object_positions_q15(positions);
for (int object = 0; object < oamd::kObjects; ++object) {
if (!context->bed_override[object]) {
continue;
}
for (int axis = 0; axis < oamd::kAxes; ++axis) {
positions[object][axis] = context->bed_positions[object][axis];
}
}
// A frame without OAMD must not touch the gains at all (no event), otherwise a // A frame without OAMD must not touch the gains at all (no event), otherwise a
// pending ramp would snap - matching the reference exactly. // pending ramp would snap - matching the reference exactly.
const std::uint32_t event_count = context->last_had_payload ? 1u : 0u; const std::uint32_t event_count = context->last_had_payload ? 1u : 0u;
@@ -45,7 +74,7 @@ Status step(SpeakerStep* context, const std::vector<float>& objects16_planar,
context->handle, context->interleaved.data(), JOC_FRAME_SAMPLES, event_count, context->handle, context->interleaved.data(), JOC_FRAME_SAMPLES, event_count,
event_count != 0u ? &offset : nullptr, event_count != 0u ? &ramp : nullptr, event_count != 0u ? &offset : nullptr, event_count != 0u ? &ramp : nullptr,
event_count != 0u ? &positions[0][0] : nullptr, nullptr, nullptr, nullptr, event_count != 0u ? &positions[0][0] : nullptr, nullptr, nullptr, nullptr,
context->output.data()); &context->controls, context->output.data());
if (result != 0) { if (result != 0) {
const char* message = ejoc_speaker_renderer_last_error(context->handle); const char* message = ejoc_speaker_renderer_last_error(context->handle);
const std::string text = const std::string text =
+9
View File
@@ -9,6 +9,7 @@
#include "foundation/status.h" #include "foundation/status.h"
#include "oamd/oamd_parser.h" #include "oamd/oamd_parser.h"
#include "speaker/speaker_layout_lookup.h" #include "speaker/speaker_layout_lookup.h"
#include "speaker/speaker_trim.h"
namespace joc::speaker { namespace joc::speaker {
@@ -23,6 +24,14 @@ struct SpeakerStep {
std::uint32_t last_ramp_duration = 0; std::uint32_t last_ramp_duration = 0;
std::uint32_t last_object_count = 0; std::uint32_t last_object_count = 0;
bool last_had_payload = false; bool last_had_payload = false;
// OAMD speaker controls. A payload carrying the trim element replaces
// them; a payload without it keeps the previous set.
ejoc_speaker_controls controls{};
bool controls_ready = false;
// bed 声道是固定通道:OAMD 不给位置,方位由声明的 bed 布局给出。这里存
// 对象槽 → Q15 方位;bed_override 为 false 的槽仍按 OAMD 坐标声像。
std::uint16_t bed_positions[oamd::kObjects][oamd::kAxes] = {};
bool bed_override[oamd::kObjects] = {};
}; };
Status step(SpeakerStep* context, const std::vector<float>& objects16_planar, Status step(SpeakerStep* context, const std::vector<float>& objects16_planar,
+155
View File
@@ -0,0 +1,155 @@
#include "speaker/speaker_trim.h"
#include <algorithm>
#include <cmath>
#include <string>
#include "foundation/py_num.h"
namespace joc::speaker {
namespace {
int height_class(std::uint32_t count) {
if (count == 0u) {
return 0;
}
if (count == 2u) {
return 1;
}
return 2;
}
int floor_class(std::uint32_t count) {
if (count == 0u) {
return 0;
}
if (count == 2u || count == 3u) {
return 1;
}
return 2;
}
} // namespace
int trim_config_index(const LayoutInfo& layout) {
return floor_class(layout.surround_channels) + 3 * height_class(layout.height_channels);
}
Status parameters_from_oamd(const oamd::OamdTrim* trim, const LayoutInfo& layout,
ejoc_speaker_controls* out) {
if (out == nullptr) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kRender,
"null speaker controls");
}
ejoc_speaker_controls controls{};
controls.struct_size = sizeof(controls);
controls.struct_version = EJOC_SPEAKER_CONTROLS_VERSION;
controls.trim_mode = EJOC_SPEAKER_TRIM_AUTOMATIC;
if (trim != nullptr) {
controls.warp_mode = trim->warp_mode;
for (int slot = 0; slot < oamd::kMaxSlots; ++slot) {
controls.trim_bypass[slot] = trim->disable_per_object[slot] ? 1u : 0u;
}
}
if (controls.warp_mode > 1u) {
return Status::fail(JOC_ERR_NOT_SUPPORTED, stage::kRender,
"speaker: warp_mode_not_implemented: speaker rendering "
"implements warp modes 0/1; warp mode " +
std::to_string(controls.warp_mode) + " is reserved");
}
if (!layout.carries_trim) {
controls.trim_mode = EJOC_SPEAKER_TRIM_DISABLED;
*out = controls;
return Status::success();
}
const std::uint32_t mode = trim != nullptr ? trim->global_trim_mode : 0u;
if (mode == 1u) {
controls.trim_mode = EJOC_SPEAKER_TRIM_DISABLED;
*out = controls;
return Status::success();
}
if (mode > 2u) {
return Status::fail(JOC_ERR_NOT_SUPPORTED, stage::kRender,
"speaker: trim_mode_not_implemented: OAMD global trim mode " +
std::to_string(mode) + " is reserved");
}
if (mode == 2u) {
const oamd::TrimConfig& record = trim->configs[trim_config_index(layout)];
if (record.kind == oamd::TrimConfigKind::kDefault ||
record.kind == oamd::TrimConfigKind::kAbsent) {
*out = controls;
return Status::success();
}
if (record.kind == oamd::TrimConfigKind::kDisabled) {
controls.trim_mode = EJOC_SPEAKER_TRIM_DISABLED;
*out = controls;
return Status::success();
}
if (!std::isfinite(record.centre) || !std::isfinite(record.surround) ||
!std::isfinite(record.height)) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kRender,
"speaker: trim levels must be finite");
}
for (const double balance : {record.balance_listener, record.balance_overhead}) {
if (!std::isfinite(balance) || balance < -1.0 || balance > 1.0) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kRender,
"speaker: balance must be finite and in [-1,1]");
}
}
// Surround and height are attenuation-only; the centre level keeps its
// sign.
controls.trim_mode = EJOC_SPEAKER_TRIM_EXPLICIT;
controls.centre_db = record.centre;
controls.surround_db = std::min(record.surround, 0.0);
controls.height_db = std::min(record.height, 0.0);
controls.listener_balance = record.balance_listener;
controls.overhead_balance = record.balance_overhead;
}
*out = controls;
return Status::success();
}
double front_back_balance(double position, double balance) {
const long long steps =
pynum::py_round(std::fabs(balance) * static_cast<double>(kBalanceSteps));
if (steps == 0) {
return position;
}
const double slope = static_cast<double>(steps) / 18.0;
if (position <= kBalanceWall || position >= 1.0 - kBalanceWall) {
return position;
}
if (position < 0.5) {
return balance > 0.0 ? (1.0 + slope) * position - kBalanceWall * slope
: (1.0 - slope) * position + kBalanceWall * slope;
}
return balance > 0.0
? (1.0 - slope) * (position - 0.5) + 0.5 + 0.45 * slope
: (1.0 + slope) * (position - 0.5) + 0.5 - 0.45 * slope;
}
double apply_balance(double position, double height, double listener, double overhead) {
if (listener == 0.0 && overhead == 0.0) {
return position;
}
const double low = front_back_balance(position, listener);
const double high = front_back_balance(position, overhead);
return (1.0 - height) * low + height * high;
}
double explicit_position_gain(const ejoc_speaker_controls& controls, double x, double y,
double z) {
const double surround = std::min(std::max(2.0 * y, 0.0), 1.0) * (1.0 - z);
const double centre = 1.0 - std::min(
std::max(10.0 * std::max(std::max(std::fabs(z) - kBalanceWall,
y - kBalanceWall),
std::fabs(x - 0.5) - kBalanceWall),
0.0),
1.0);
const double db = surround * std::min(controls.surround_db, 0.0) +
z * std::min(controls.height_db, 0.0) + centre * controls.centre_db;
return std::pow(10.0, db / 20.0);
}
} // namespace joc::speaker
+49
View File
@@ -0,0 +1,49 @@
// Port of src/trim_balance.py.
#pragma once
#include <cstdint>
#include "eac3joc_core.h"
#include "foundation/status.h"
#include "oamd/oamd_parser.h"
#include "speaker/speaker_layout_lookup.h"
namespace joc::speaker {
// Front-back balance keeps a 5 percent wall band at each end unmapped.
inline constexpr double kBalanceWall = 0.05;
// bal3d_y is coded on a 1/16 grid, so a balance is quantised to that grid.
inline constexpr int kBalanceSteps = 16;
// Trim configuration a layout selects, from its surround and height counts:
//
// cfg = kappa_f(surrounds) + 3 * kappa_h(heights)
// kappa_f: 0 -> 0, 2..3 -> 1, otherwise 2
// kappa_h: 0 -> 0, 2 -> 1, otherwise 2
int trim_config_index(const LayoutInfo& layout);
// Converts OAMD calibration to the speaker controls of one layout. Warp modes
// 2/3 and the reserved global trim mode are reported as unsupported. A null
// trim selects warp 0 and automatic trim, or disabled trim for a layout that
// carries no trim semantics.
Status parameters_from_oamd(const oamd::OamdTrim* trim, const LayoutInfo& layout,
ejoc_speaker_controls* out);
// Reparameterises a front-back coordinate in [0, 1] by ``balance``: 0 is the
// front wall and 1 the back wall, and the two wall bands pass through
// unchanged.
double front_back_balance(double position, double balance);
// Blends the listener-plane and overhead balance by height: 0 at the listener
// plane, 1 at the top layer.
double apply_balance(double position, double height, double listener, double overhead);
// Position-dependent object trim at the balanced original Y. Surround fades
// in with Y and out towards Z=1, height fades in with Z, and the centre trim is
// local to the front-centre region. The scalar multiplies the object's whole
// panning vector before accumulation.
double explicit_position_gain(const ejoc_speaker_controls& controls, double x, double y,
double z);
} // namespace joc::speaker
+56 -22
View File
@@ -8,7 +8,7 @@
#include "foundation/status.h" #include "foundation/status.h"
#include "hrtf/jochrtf.h" #include "hrtf/jochrtf.h"
#include "hrtf/rosella_model.h" #include "hrtf/rosella_model.h"
#include "hrtf/sofa_cache.h" #include "joc_bitstream/bed_layout_map.h"
#include "joc_bitstream/joc_parser.h" #include "joc_bitstream/joc_parser.h"
#include "joc_core/objects16.h" #include "joc_core/objects16.h"
@@ -59,6 +59,8 @@ void Stream::reset_state() {
speaker_.state.reset(); speaker_.state.reset();
speaker_.output.clear(); speaker_.output.clear();
speaker_.last_had_payload = false; speaker_.last_had_payload = false;
// Back to the initial controls; the next trim element replaces them.
speaker_.controls_ready = false;
} }
if (binaural_ready_) { if (binaural_ready_) {
binaural_.reset(); binaural_.reset();
@@ -126,6 +128,9 @@ Status Stream::create(const Config& config) {
} }
render_options.object_delay_samples = config_.object_delay_samples; render_options.object_delay_samples = config_.object_delay_samples;
render_options.tail_seconds = config_.tail_seconds; render_options.tail_seconds = config_.tail_seconds;
render_options.bank = config_.rosella_filterbank == JOC_ROSELLA_FILTERBANK_CAPTURED
? hrtf::RosellaBankKind::Captured
: hrtf::RosellaBankKind::Public;
if (status.ok()) { if (status.ok()) {
status = rosella_.open(model, render_options); status = rosella_.open(model, render_options);
} }
@@ -139,26 +144,7 @@ Status Stream::create(const Config& config) {
hrtf::Field field; hrtf::Field field;
hrtf::Kernels kernels; hrtf::Kernels kernels;
Status status = Status::success(); Status status = Status::success();
if (!config_.hrtf_sofa_path.empty()) { status = hrtf::load_jochrtf(config_.hrtf_path, &field);
// The .jochrtf is an internal cache: the SOFA is the user-facing input.
hrtf::SofaFieldRequest request;
request.sofa_path = config_.hrtf_sofa_path;
request.options.shell_radius_m = config_.hrtf_radius_m;
request.cache_dir = config_.hrtf_cache_dir;
switch (config_.hrtf_cache_policy) {
case JOC_HRTF_CACHE_NONE: request.policy = hrtf::CachePolicy::None; break;
case JOC_HRTF_CACHE_DISK: request.policy = hrtf::CachePolicy::Disk; break;
default: request.policy = hrtf::CachePolicy::Memory; break;
}
std::string cache_path;
status = hrtf::load_or_compile_sofa_field(request, &field, &cache_path);
if (!status.ok()) {
return Status::fail(status.code(), stage::kRender,
"binaural setup failed: " + status.message());
}
} else {
status = hrtf::load_jochrtf(config_.hrtf_path, &field);
}
if (status.ok()) { if (status.ok()) {
status = config_.kernels_path.empty() status = config_.kernels_path.empty()
? (kernels = hrtf::builtin_kernels(), Status::success()) ? (kernels = hrtf::builtin_kernels(), Status::success())
@@ -171,7 +157,10 @@ Status Stream::create(const Config& config) {
profile = binaural::Profile::Far; profile = binaural::Profile::Far;
} }
if (status.ok()) { if (status.ok()) {
status = binaural_.open(field, kernels, profile); binaural::RoomConstants room;
room.enable_early_reflections = config_.jochrtf_room ? 1u : 0u;
room.enable_late_room = room.enable_early_reflections;
status = binaural_.open(field, kernels, profile, room);
} }
if (!status.ok()) { if (!status.ok()) {
return status; return status;
@@ -186,12 +175,57 @@ Status Stream::create(const Config& config) {
return Status::success(); return Status::success();
} }
void Stream::apply_bed_positions(const FrameMetadata& entry) {
if (bed_positions_ready_ || entry.bed_assignments.empty()) {
return;
}
const bool bed_only = entry.has_update && entry.update.content_bed &&
!entry.update.content_isf && !entry.update.content_dynamic;
const ::joc::joc::BedLayout bed = ::joc::joc::resolve_bed_layout(entry.bed_assignments, bed_only);
if (!bed.present) {
return;
}
bed_positions_ready_ = true;
if (!bed.bed_only) {
return;
}
for (std::size_t slot = 0; slot < bed.channels.size() &&
slot < static_cast<std::size_t>(oamd::kObjects);
++slot) {
const ::joc::joc::BedChannel channel = bed.channels[slot];
double xyz[3] = {0.0, 0.0, 0.0};
if (::joc::joc::bed_channel_adm_position(channel, xyz)) {
if (binaural_ready_) {
binaural_.set_fixed_position(static_cast<int>(slot) + 1, xyz);
}
if (rosella_ready_) {
rosella_.set_fixed_position(static_cast<int>(slot) + 1, xyz);
}
}
if (!speaker_enabled_) {
continue;
}
std::uint16_t q15[3] = {0, 0, 0};
if (!::joc::joc::layout_bed_anchor(speaker_.layout.out_ch_config, channel, q15) &&
!::joc::joc::bed_channel_q15(channel, q15)) {
continue;
}
speaker_.bed_override[slot] = true;
for (int axis = 0; axis < oamd::kAxes; ++axis) {
speaker_.bed_positions[slot][axis] = q15[axis];
}
}
}
Status Stream::flush_pending_frame() { Status Stream::flush_pending_frame() {
if (pending_frame_.streams.empty()) { if (pending_frame_.streams.empty()) {
return Status::success(); return Status::success();
} }
FrameMetadata entry = pending_frame_; FrameMetadata entry = pending_frame_;
pending_frame_ = FrameMetadata(); pending_frame_ = FrameMetadata();
if (entry.has_joc) {
apply_bed_positions(entry);
}
if (entry.has_joc) { if (entry.has_joc) {
std::string error; std::string error;
joc::CrossLayerNotes notes; joc::CrossLayerNotes notes;
+11 -8
View File
@@ -6,7 +6,7 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include "binaural/binaural_runtime.h" #include "binaural/jochrtf_runtime.h"
#include "eac3_transport/eac3_reader.h" #include "eac3_transport/eac3_reader.h"
#include "foundation/status.h" #include "foundation/status.h"
#include "hrtf/rosella_renderer.h" #include "hrtf/rosella_renderer.h"
@@ -30,13 +30,12 @@ struct Config {
std::uint32_t object_delay_samples = 1473; std::uint32_t object_delay_samples = 1473;
double gain_db = 0.0; double gain_db = 0.0;
std::uint32_t native_threads = 0; std::uint32_t native_threads = 0;
// The three HRTF shapes of joc_task_config, in its precedence order: a Rosella // Binaural inputs of joc_task_config: a Rosella model wins over hrtf_path
// model wins over a SOFA, and hrtf_path (.jochrtf) is the fallback. // (.jochrtf).
std::string hrtf_sofa_path;
std::string personalized_headphone_path; std::string personalized_headphone_path;
std::string hrtf_cache_dir; std::uint32_t jochrtf_room = 1;
std::uint32_t hrtf_cache_policy = JOC_HRTF_CACHE_MEMORY; // Filterbank of the Rosella path; the other binaural inputs ignore it.
double hrtf_radius_m = 1.0; std::uint32_t rosella_filterbank = JOC_ROSELLA_FILTERBANK_PUBLIC;
}; };
struct Info { struct Info {
@@ -128,6 +127,9 @@ private:
return rosella_ready_ ? (rosella_pending_.size() - rosella_read_offset_) / 2u : 0u; return rosella_ready_ ? (rosella_pending_.size() - rosella_read_offset_) / 2u : 0u;
} }
void reset_state(); void reset_state();
// 声明的 bed 布局只在首帧解析一次:bed 声道在 OAMD 里没有位置字段,方位由布局
// 给出;流式路径和文件任务走同一套 SpeakerStep/双耳运行时,所以这里也要下发。
void apply_bed_positions(const FrameMetadata& entry);
// Drops the bed samples that have already been rendered, keeping the rest. // Drops the bed samples that have already been rendered, keeping the rest.
void compact_bed_pending(); void compact_bed_pending();
// Closes the audio frame currently being assembled and queues it. // Closes the audio frame currently being assembled and queues it.
@@ -165,7 +167,7 @@ private:
ejoc_renderer_handle rebuilder_ = nullptr; ejoc_renderer_handle rebuilder_ = nullptr;
speaker::SpeakerStep speaker_; speaker::SpeakerStep speaker_;
binaural::SofaBinauralRuntime binaural_; binaural::JochrtfRuntime binaural_;
hrtf::RosellaRuntime rosella_; hrtf::RosellaRuntime rosella_;
std::vector<double> rosella_pending_; std::vector<double> rosella_pending_;
std::size_t rosella_read_offset_ = 0; std::size_t rosella_read_offset_ = 0;
@@ -173,6 +175,7 @@ private:
bool speaker_enabled_ = false; bool speaker_enabled_ = false;
bool binaural_enabled_ = false; bool binaural_enabled_ = false;
bool binaural_ready_ = false; bool binaural_ready_ = false;
bool bed_positions_ready_ = false;
bool rosella_ready_ = false; bool rosella_ready_ = false;
float gain_ = 1.0f; float gain_ = 1.0f;
}; };
+211 -69
View File
@@ -28,19 +28,20 @@
#include "adm/adm_metadata.h" #include "adm/adm_metadata.h"
#include "adm/adm_tracks.h" #include "adm/adm_tracks.h"
#include "binaural/binaural_runtime.h" #include "binaural/jochrtf_runtime.h"
#include "eac3_transport/eac3_reader.h" #include "eac3_transport/eac3_reader.h"
#include "emdf/emdf_parser.h" #include "emdf/emdf_parser.h"
#include "foundation/mini_json.h" #include "foundation/mini_json.h"
#include "foundation/sha256.h" #include "foundation/sha256.h"
#include "hrtf/jochrtf.h" #include "hrtf/jochrtf.h"
#include "hrtf/rosella_bank.h"
#include "hrtf/rosella_model.h" #include "hrtf/rosella_model.h"
#include "hrtf/rosella_renderer.h" #include "hrtf/rosella_renderer.h"
#include "hrtf/sofa_cache.h"
#include "io/adm_writer.h" #include "io/adm_writer.h"
#include "io/process.h" #include "io/process.h"
#include "io/wav_writer.h" #include "io/wav_writer.h"
#include "joc_bitstream/joc_parser.h" #include "joc_bitstream/joc_parser.h"
#include "joc_bitstream/bed_layout_map.h"
#include "joc_core/objects16.h" #include "joc_core/objects16.h"
#include "oamd/oamd_parser.h" #include "oamd/oamd_parser.h"
#include "speaker/speaker_step.h" #include "speaker/speaker_step.h"
@@ -92,11 +93,9 @@ struct Settings {
std::string layout; std::string layout;
std::string hrtf_path; std::string hrtf_path;
std::string kernels_path; std::string kernels_path;
std::string hrtf_sofa_path;
std::string personalized_headphone_path; std::string personalized_headphone_path;
std::string hrtf_cache_dir; std::uint32_t jochrtf_room = 1;
std::uint32_t hrtf_cache_policy = JOC_HRTF_CACHE_MEMORY; std::uint32_t rosella_filterbank = JOC_ROSELLA_FILTERBANK_PUBLIC;
double hrtf_radius_m = 1.0;
std::uint32_t operation = JOC_OP_ADM_BWF; std::uint32_t operation = JOC_OP_ADM_BWF;
std::uint32_t output_format = JOC_FORMAT_FLOAT32; std::uint32_t output_format = JOC_FORMAT_FLOAT32;
std::uint32_t adm_binaural_mode = JOC_BINAURAL_MID; std::uint32_t adm_binaural_mode = JOC_BINAURAL_MID;
@@ -141,13 +140,13 @@ Settings normalise(const joc_task_config& raw) {
if (raw.output_path != nullptr) { cfg.output_path = raw.output_path; } if (raw.output_path != nullptr) { cfg.output_path = raw.output_path; }
if (raw.speaker_layout_name != nullptr) { cfg.layout = raw.speaker_layout_name; } if (raw.speaker_layout_name != nullptr) { cfg.layout = raw.speaker_layout_name; }
if (raw.hrtf_path != nullptr) { cfg.hrtf_path = raw.hrtf_path; } if (raw.hrtf_path != nullptr) { cfg.hrtf_path = raw.hrtf_path; }
if (raw.hrtf_sofa_path != nullptr) { cfg.hrtf_sofa_path = raw.hrtf_sofa_path; }
if (raw.personalized_headphone_path != nullptr) { if (raw.personalized_headphone_path != nullptr) {
cfg.personalized_headphone_path = raw.personalized_headphone_path; cfg.personalized_headphone_path = raw.personalized_headphone_path;
} }
if (raw.hrtf_cache_dir != nullptr) { cfg.hrtf_cache_dir = raw.hrtf_cache_dir; } cfg.jochrtf_room = raw.jochrtf_room;
cfg.hrtf_cache_policy = raw.hrtf_cache_policy; // Kept verbatim so validate() can reject an out-of-range value; 0 is the
cfg.hrtf_radius_m = raw.hrtf_radius_m; // documented "unset" spelling of the public bank.
cfg.rosella_filterbank = raw.rosella_filterbank;
if (raw.kernels_path != nullptr) { cfg.kernels_path = raw.kernels_path; } if (raw.kernels_path != nullptr) { cfg.kernels_path = raw.kernels_path; }
cfg.operation = raw.operation; cfg.operation = raw.operation;
cfg.output_format = raw.output_format; cfg.output_format = raw.output_format;
@@ -314,6 +313,91 @@ int probe_config_idx(const std::string& path) {
return config; return config;
} }
// Reads the programme trim element from the leading audio frames, without
// rendering them. The ADM master metadata carries it, and the reference scans
// the first 64 audio frames for it.
Status probe_atmos_trim(const std::string& path, std::uint64_t max_frames,
oamd::OamdTrim* trim, bool* present) {
*present = false;
std::ifstream input = fs_utf8::open_input(path);
if (!input) {
return Status::success();
}
::joc::eac3::FrameReader reader;
std::vector<char> chunk(1u << 16);
std::vector<::joc::eac3::Frame> group;
std::uint64_t frames = 0;
auto scan_group = [&]() -> bool {
for (const ::joc::eac3::Frame& frame : group) {
bool has_joc = false;
::joc::emdf::Container container;
if (!::joc::emdf::find_joc_emdf_optional(
frame.data, frame.size, &has_joc, &container,
&::joc::joc::score_container_as_joc, nullptr)
.ok() ||
!has_joc) {
continue;
}
const ::joc::emdf::Payload* payload = container.find(::joc::emdf::kIdOamd);
if (payload == nullptr) {
continue;
}
std::vector<std::uint8_t> bytes;
if (!::joc::emdf::extract_payload_bytes(frame.data, frame.size, *payload, &bytes)
.ok()) {
continue;
}
oamd::OamdUpdate update;
if (!oamd::parse_id11(bytes.data(), bytes.size(), &update).ok() ||
!update.has_trim) {
continue;
}
*trim = update.trim;
*present = true;
return true;
}
group.clear();
return false;
};
bool done = false;
while (!done) {
input.read(chunk.data(), static_cast<std::streamsize>(chunk.size()));
const std::streamsize got = input.gcount();
if (got > 0) {
reader.push(reinterpret_cast<const std::uint8_t*>(chunk.data()),
static_cast<std::size_t>(got));
} else {
reader.finish();
done = true;
}
for (;;) {
::joc::eac3::Frame frame;
const ::joc::eac3::FrameReader::Next state = reader.next(&frame);
if (state != ::joc::eac3::FrameReader::Next::Ok) {
break;
}
bool repeats = false;
for (const ::joc::eac3::Frame& prior : group) {
if (prior.same_stream(frame)) {
repeats = true;
break;
}
}
if (repeats) {
++frames;
if (scan_group() || frames >= max_frames) {
return Status::success();
}
}
group.push_back(frame);
}
}
if (!group.empty()) {
scan_group();
}
return Status::success();
}
// Rendered PCM is spooled to a float32 file so the output format can be decided // Rendered PCM is spooled to a float32 file so the output format can be decided
// once the peak is known, which is what makes --clip-action possible; the // once the peak is known, which is what makes --clip-action possible; the
// reference CLI spools for the same reason. // reference CLI spools for the same reason.
@@ -1068,36 +1152,17 @@ Status validate(const joc_task_config& raw, std::vector<joc_validation_issue>* i
} }
} }
if (cfg.operation == JOC_OP_BINAURAL) { if (cfg.operation == JOC_OP_BINAURAL) {
if (cfg.hrtf_path.empty() && cfg.hrtf_sofa_path.empty() && if (cfg.hrtf_path.empty() && cfg.personalized_headphone_path.empty()) {
cfg.personalized_headphone_path.empty()) {
fail(JOC_ERR_INVALID_CONFIG, "hrtf_path", fail(JOC_ERR_INVALID_CONFIG, "hrtf_path",
"a SOFA input, a Rosella model or a compiled HRTF (.jochrtf) is required for the " "a Rosella model or a compiled HRTF (.jochrtf) is required for the "
"binaural operation"); "binaural operation");
} else if (!cfg.personalized_headphone_path.empty() && } else if (!cfg.personalized_headphone_path.empty() &&
!fs_utf8::exists(cfg.personalized_headphone_path)) { !fs_utf8::exists(cfg.personalized_headphone_path)) {
fail(JOC_ERR_HRTF_NOT_FOUND, "personalized_headphone_path", fail(JOC_ERR_HRTF_NOT_FOUND, "personalized_headphone_path",
"personalized headphone model not found: " + cfg.personalized_headphone_path); "personalized headphone model not found: " + cfg.personalized_headphone_path);
} else if (!cfg.hrtf_sofa_path.empty() && !fs_utf8::exists(cfg.hrtf_sofa_path)) { } else if (cfg.personalized_headphone_path.empty() && !fs_utf8::exists(cfg.hrtf_path)) {
fail(JOC_ERR_HRTF_NOT_FOUND, "hrtf_sofa_path",
"SOFA HRTF not found: " + cfg.hrtf_sofa_path);
} else if (cfg.hrtf_sofa_path.empty() && cfg.personalized_headphone_path.empty() &&
!fs_utf8::exists(cfg.hrtf_path)) {
fail(JOC_ERR_HRTF_NOT_FOUND, "hrtf_path", "HRTF cache not found: " + cfg.hrtf_path); fail(JOC_ERR_HRTF_NOT_FOUND, "hrtf_path", "HRTF cache not found: " + cfg.hrtf_path);
} }
if (!cfg.hrtf_sofa_path.empty()) {
if (cfg.hrtf_cache_policy > JOC_HRTF_CACHE_DISK) {
fail(JOC_ERR_INVALID_CONFIG, "hrtf_cache_policy",
"hrtf_cache_policy must be none, memory or disk");
}
if (cfg.hrtf_cache_policy == JOC_HRTF_CACHE_DISK && cfg.hrtf_cache_dir.empty()) {
fail(JOC_ERR_INVALID_CONFIG, "hrtf_cache_dir",
"the disk cache policy needs a cache directory");
}
if (!std::isfinite(cfg.hrtf_radius_m) || cfg.hrtf_radius_m <= 0.0) {
fail(JOC_ERR_INVALID_CONFIG, "hrtf_radius_m",
"hrtf_radius_m must be positive and finite");
}
}
// The filterbank tables are compiled in; a path is only a verification override. // The filterbank tables are compiled in; a path is only a verification override.
if (!cfg.kernels_path.empty() && !fs_utf8::exists(cfg.kernels_path)) { if (!cfg.kernels_path.empty() && !fs_utf8::exists(cfg.kernels_path)) {
fail(JOC_ERR_HRTF_NOT_FOUND, "kernels_path", fail(JOC_ERR_HRTF_NOT_FOUND, "kernels_path",
@@ -1107,6 +1172,14 @@ Status validate(const joc_task_config& raw, std::vector<joc_validation_issue>* i
fail(JOC_ERR_INVALID_CONFIG, "binaural_mode", fail(JOC_ERR_INVALID_CONFIG, "binaural_mode",
"binaural_mode off is only meaningful for ADM output"); "binaural_mode off is only meaningful for ADM output");
} }
if (cfg.rosella_filterbank > JOC_ROSELLA_FILTERBANK_CAPTURED) {
fail(JOC_ERR_INVALID_CONFIG, "rosella_filterbank",
"rosella_filterbank must be 1 (public) or 2 (captured)");
} else if (cfg.rosella_filterbank == JOC_ROSELLA_FILTERBANK_CAPTURED &&
cfg.personalized_headphone_path.empty()) {
fail(JOC_ERR_INVALID_CONFIG, "rosella_filterbank",
"rosella_filterbank 2 only applies to a Rosella .personalized_headphone input");
}
} }
if (cfg.operation == JOC_OP_ADM_BWF) { if (cfg.operation == JOC_OP_ADM_BWF) {
if (cfg.adm_binaural_mode > 4u) { if (cfg.adm_binaural_mode > 4u) {
@@ -1322,6 +1395,14 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu
} }
::joc::speaker::SpeakerStep speaker; ::joc::speaker::SpeakerStep speaker;
bool bed_positions_ready = false;
// The ADM master metadata carries the programme's trim element, scanned
// from the leading frames before rendering starts.
::joc::oamd::OamdTrim adm_trim;
bool adm_trim_present = false;
if (cfg.operation == JOC_OP_ADM_BWF) {
probe_atmos_trim(eac3_path, 64, &adm_trim, &adm_trim_present);
}
const bool speaker_enabled = cfg.operation == JOC_OP_SPEAKER; const bool speaker_enabled = cfg.operation == JOC_OP_SPEAKER;
if (speaker_enabled) { if (speaker_enabled) {
if (!::joc::speaker::layout_by_name(cfg.layout.c_str(), &speaker.layout)) { if (!::joc::speaker::layout_by_name(cfg.layout.c_str(), &speaker.layout)) {
@@ -1334,12 +1415,27 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu
return finalize_with_error(JOC_ERR_RENDER_FAILED, "render", return finalize_with_error(JOC_ERR_RENDER_FAILED, "render",
"cannot create the speaker renderer"); "cannot create the speaker renderer");
} }
// The reference seeds the initial controls from the leading frames, so
// the first trim element is in effect before its own event arrives.
::joc::oamd::OamdTrim initial_trim;
bool has_initial_trim = false;
probe_atmos_trim(eac3_path, 64, &initial_trim, &has_initial_trim);
if (has_initial_trim) {
const Status seeded = ::joc::speaker::parameters_from_oamd(
&initial_trim, speaker.layout, &speaker.controls);
if (!seeded.ok()) {
ejoc_speaker_renderer_destroy(speaker.handle);
speaker.handle = nullptr;
return finalize_with_error(seeded.code(), "render", seeded.message());
}
speaker.controls_ready = true;
}
bus.emit(JOC_EV_RENDERER_INITIALIZED, JOC_STAGE_RENDER, JOC_LOG_INFO, bus.emit(JOC_EV_RENDERER_INITIALIZED, JOC_STAGE_RENDER, JOC_LOG_INFO,
fmt("speaker renderer: %s, %u channels", speaker.layout.name, fmt("speaker renderer: %s, %u channels", speaker.layout.name,
speaker.layout.channel_count)); speaker.layout.channel_count));
} }
::joc::binaural::SofaBinauralRuntime binaural; ::joc::binaural::JochrtfRuntime binaural;
::joc::hrtf::RosellaRuntime rosella; ::joc::hrtf::RosellaRuntime rosella;
const bool binaural_enabled = cfg.operation == JOC_OP_BINAURAL; const bool binaural_enabled = cfg.operation == JOC_OP_BINAURAL;
const bool rosella_enabled = !cfg.personalized_headphone_path.empty(); const bool rosella_enabled = !cfg.personalized_headphone_path.empty();
@@ -1356,14 +1452,22 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu
} }
render_options.object_delay_samples = cfg.object_delay_samples; render_options.object_delay_samples = cfg.object_delay_samples;
render_options.tail_seconds = cfg.tail_seconds; render_options.tail_seconds = cfg.tail_seconds;
render_options.bank =
cfg.rosella_filterbank == JOC_ROSELLA_FILTERBANK_CAPTURED
? ::joc::hrtf::RosellaBankKind::Captured
: ::joc::hrtf::RosellaBankKind::Public;
if (status.ok()) { if (status.ok()) {
status = rosella.open(model, render_options); status = rosella.open(model, render_options);
} }
if (status.ok()) { if (status.ok()) {
bus.emit(JOC_EV_HRTF_LOADED, JOC_STAGE_RENDER, JOC_LOG_INFO, model.summary()); bus.emit(JOC_EV_HRTF_LOADED, JOC_STAGE_RENDER, JOC_LOG_INFO, model.summary());
bus.emit(JOC_EV_RENDERER_INITIALIZED, JOC_STAGE_RENDER, JOC_LOG_INFO, bus.emit(JOC_EV_RENDERER_INITIALIZED, JOC_STAGE_RENDER, JOC_LOG_INFO,
"Rosella binaural runtime ready (the first 961 samples are the " fmt("Rosella binaural runtime ready (%s filterbank, the first %u "
"filterbank latency)"); "samples are the filterbank latency)",
render_options.bank == ::joc::hrtf::RosellaBankKind::Captured
? "captured"
: "public",
::joc::hrtf::rosella_bank_latency(render_options.bank)));
} }
if (!status.ok()) { if (!status.ok()) {
return finalize_with_error(status.code(), "render", return finalize_with_error(status.code(), "render",
@@ -1375,30 +1479,10 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu
::joc::hrtf::Kernels kernels; ::joc::hrtf::Kernels kernels;
::joc::binaural::Profile profile = ::joc::binaural::Profile::Mid; ::joc::binaural::Profile profile = ::joc::binaural::Profile::Mid;
Status status = Status::success(); Status status = Status::success();
if (!cfg.hrtf_sofa_path.empty()) { status = ::joc::hrtf::load_jochrtf(cfg.hrtf_path, &field);
// The .jochrtf is an internal cache: the SOFA is the user-facing input. if (status.ok()) {
::joc::hrtf::SofaFieldRequest request; bus.emit(JOC_EV_HRTF_LOADED, JOC_STAGE_RENDER, JOC_LOG_INFO,
request.sofa_path = cfg.hrtf_sofa_path; "compiled HRTF: " + field.source_sha256.substr(0, 16));
request.options.shell_radius_m = cfg.hrtf_radius_m;
request.cache_dir = cfg.hrtf_cache_dir;
switch (cfg.hrtf_cache_policy) {
case JOC_HRTF_CACHE_NONE: request.policy = ::joc::hrtf::CachePolicy::None; break;
case JOC_HRTF_CACHE_DISK: request.policy = ::joc::hrtf::CachePolicy::Disk; break;
default: request.policy = ::joc::hrtf::CachePolicy::Memory; break;
}
std::string cache_path;
status = ::joc::hrtf::load_or_compile_sofa_field(request, &field, &cache_path);
if (status.ok()) {
bus.emit(JOC_EV_HRTF_LOADED, JOC_STAGE_RENDER, JOC_LOG_INFO,
"SOFA HRTF compiled: " + field.source_sha256.substr(0, 16) +
(cache_path.empty() ? std::string() : " -> " + cache_path));
}
} else {
status = ::joc::hrtf::load_jochrtf(cfg.hrtf_path, &field);
if (status.ok()) {
bus.emit(JOC_EV_HRTF_LOADED, JOC_STAGE_RENDER, JOC_LOG_INFO,
"compiled HRTF: " + field.source_sha256.substr(0, 16));
}
} }
if (status.ok()) { if (status.ok()) {
status = cfg.kernels_path.empty() status = cfg.kernels_path.empty()
@@ -1411,7 +1495,10 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu
profile = ::joc::binaural::Profile::Far; profile = ::joc::binaural::Profile::Far;
} }
if (status.ok()) { if (status.ok()) {
status = binaural.open(field, kernels, profile); ::joc::binaural::RoomConstants room;
room.enable_early_reflections = cfg.jochrtf_room ? 1u : 0u;
room.enable_late_room = room.enable_early_reflections;
status = binaural.open(field, kernels, profile, room);
} }
if (!status.ok()) { if (!status.ok()) {
return finalize_with_error(status.code(), "render", return finalize_with_error(status.code(), "render",
@@ -1423,7 +1510,8 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu
} }
::joc::io::AdmBwfWriter adm_writer; ::joc::io::AdmBwfWriter adm_writer;
::joc::adm::TrajectoryBuilder trajectory(48000, 64, cfg.object_delay_samples); ::joc::adm::TrajectoryBuilder trajectory(48000, ::joc::timing::kMetadataBlockSamples,
cfg.object_delay_samples);
const bool adm_enabled = cfg.operation == JOC_OP_ADM_BWF; const bool adm_enabled = cfg.operation == JOC_OP_ADM_BWF;
if (adm_enabled) { if (adm_enabled) {
const Status status = adm_writer.open(cfg.output_path); const Status status = adm_writer.open(cfg.output_path);
@@ -1744,6 +1832,62 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu
job.outer_offset = static_cast<std::int64_t>(payload->sample_offset); job.outer_offset = static_cast<std::int64_t>(payload->sample_offset);
const Status bed_ok = ::joc::oamd::parse_id11_bed_assignments( const Status bed_ok = ::joc::oamd::parse_id11_bed_assignments(
bytes.data(), bytes.size(), &group_bed_assignments); bytes.data(), bytes.size(), &group_bed_assignments);
if (bed_ok.ok() && !bed_positions_ready &&
!group_bed_assignments.empty()) {
const ::joc::joc::BedLayout bed_layout =
::joc::joc::resolve_bed_layout(
group_bed_assignments,
job.update.content_bed && !job.update.content_isf &&
!job.update.content_dynamic);
if (bed_layout.present) {
bed_positions_ready = true;
bus.emit(JOC_EV_RENDERER_INITIALIZED, JOC_STAGE_RENDER,
JOC_LOG_INFO,
fmt("bed layout: %s (%u bed channels)",
bed_layout.name[0] != '\0'
? bed_layout.name : "custom",
static_cast<unsigned>(
bed_layout.channels.size())));
if (bed_layout.bed_only) {
// bed 声道是固定通道:OAMD 不给位置,方位由声明的 bed 布局给出。
for (std::size_t slot = 0;
slot < bed_layout.channels.size() &&
slot < static_cast<std::size_t>(::joc::oamd::kObjects);
++slot) {
const ::joc::joc::BedChannel channel =
bed_layout.channels[slot];
double xyz[3] = {0.0, 0.0, 0.0};
if (::joc::joc::bed_channel_adm_position(channel, xyz)) {
trajectory.set_fixed_position(
static_cast<int>(slot) + 1, xyz[0], xyz[1],
xyz[2]);
if (binaural_enabled) {
binaural.set_fixed_position(
static_cast<int>(slot) + 1, xyz);
}
if (rosella_enabled) {
rosella.set_fixed_position(
static_cast<int>(slot) + 1, xyz);
}
}
if (!speaker_enabled) {
continue;
}
// 目标布局有同名扬声器时直连该声道,否则按标准方位声像。
std::uint16_t q15[3] = {0, 0, 0};
if (!::joc::joc::layout_bed_anchor(
speaker.layout.out_ch_config, channel, q15) &&
!::joc::joc::bed_channel_q15(channel, q15)) {
continue;
}
speaker.bed_override[slot] = true;
for (int axis = 0; axis < ::joc::oamd::kAxes; ++axis) {
speaker.bed_positions[slot][axis] = q15[axis];
}
}
}
}
}
if (!bed_ok.ok()) { if (!bed_ok.ok()) {
failures.record(produced, StageRank::kJoc, bed_ok.code(), failures.record(produced, StageRank::kJoc, bed_ok.code(),
bed_ok.stage(), bed_ok.message()); bed_ok.stage(), bed_ok.message());
@@ -2038,11 +2182,6 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu
" audio frame(s): the chanmap declares a different extra pair than " " audio frame(s): the chanmap declares a different extra pair than "
"joc_dmx_config_idx; the bed mapping follows the chanmap"); "joc_dmx_config_idx; the bed mapping follows the chanmap");
} }
if (bed_mask_mismatch_frames != 0u) {
bus.warning(std::to_string(bed_mask_mismatch_frames) +
" audio frame(s): the OAMD bed mask declares a different extra pair than "
"joc_dmx_config_idx; the bed mask only affects metadata");
}
StageFailure recorded; StageFailure recorded;
if (failures.earliest(&recorded)) { if (failures.earliest(&recorded)) {
return finalize_with_error(recorded.code, recorded.stage_text, recorded.message); return finalize_with_error(recorded.code, recorded.stage_text, recorded.message);
@@ -2075,13 +2214,16 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu
} else { } else {
const double duration_sec = const double duration_sec =
static_cast<double>(processed) * static_cast<std::int64_t>(JOC_FRAME_SAMPLES) / 48000.0; static_cast<double>(processed) * static_cast<std::int64_t>(JOC_FRAME_SAMPLES) / 48000.0;
const std::string axml = ::joc::adm::build_axml(tracks, duration_sec, 48000); const std::string axml =
::joc::adm::build_axml(tracks, duration_sec, 48000,
adm_trim_present ? &adm_trim : nullptr);
const std::string chna = ::joc::adm::build_chna(); const std::string chna = ::joc::adm::build_chna();
std::string dbmd; std::string dbmd;
const ::joc::adm::BinauralMode mode = const ::joc::adm::BinauralMode mode =
static_cast<::joc::adm::BinauralMode>(cfg.adm_binaural_mode); static_cast<::joc::adm::BinauralMode>(cfg.adm_binaural_mode);
const Status dbmd_status = const Status dbmd_status = ::joc::adm::build_dbmd(
::joc::adm::build_dbmd(::joc::io::AdmBwfWriter::kChannels, mode, &dbmd); ::joc::io::AdmBwfWriter::kChannels, mode, &dbmd,
adm_trim_present ? &adm_trim : nullptr);
if (!dbmd_status.ok()) { if (!dbmd_status.ok()) {
failure = dbmd_status.message(); failure = dbmd_status.message();
} else { } else {
+9 -7
View File
@@ -1,8 +1,10 @@
#include "timeline/position_timeline.h" #include "timeline/position_timeline.h"
#include <algorithm>
#include <cstring> #include <cstring>
#include "foundation/geometry.h" #include "foundation/geometry.h"
#include "foundation/metadata_timing.h"
namespace joc::timeline { namespace joc::timeline {
@@ -112,6 +114,10 @@ Status OamdPositionTimeline::submit_update(const oamd::OamdUpdate& update,
double targets[kTimelineObjects][3] = {}; double targets[kTimelineObjects][3] = {};
for (int index = 0; index < kTimelineObjects; ++index) { for (int index = 0; index < kTimelineObjects; ++index) {
if (fixed_[index]) {
std::memcpy(targets[index], fixed_xyz_[index], sizeof(targets[index]));
continue;
}
geometry::q_to_adm_xyz(state_.q(index + 1, 0), state_.q(index + 1, 1), geometry::q_to_adm_xyz(state_.q(index + 1, 0), state_.q(index + 1, 1),
state_.q(index + 1, 2), &targets[index][0], &targets[index][1], state_.q(index + 1, 2), &targets[index][0], &targets[index][1],
&targets[index][2]); &targets[index][2]);
@@ -145,14 +151,10 @@ Status OamdPositionTimeline::submit_update(const oamd::OamdUpdate& update,
return Status::success(); return Status::success();
} }
const std::int64_t ramp_duration = static_cast<std::int64_t>(update.ramp_duration_samples);
const std::int64_t effective_ramp = const std::int64_t effective_ramp =
ramp_duration - kOamdUpdateQuantumSamples > 0 ? ramp_duration - kOamdUpdateQuantumSamples std::max<std::int64_t>(0, static_cast<std::int64_t>(update.ramp_duration_samples));
: 0; const std::int64_t transition_start =
std::int64_t transition_start = coded_event + object_delay_samples; timing::align_metadata_sample(coded_event + object_delay_samples);
if (effective_ramp != 0) {
transition_start += kOamdUpdateQuantumSamples;
}
for (int index = 0; index < kTimelineObjects; ++index) { for (int index = 0; index < kTimelineObjects; ++index) {
const bool changed = !has_previous_[index] || const bool changed = !has_previous_[index] ||
std::memcmp(previous_targets_[index], targets[index], std::memcmp(previous_targets_[index], targets[index],
+30 -1
View File
@@ -10,7 +10,6 @@
namespace joc::timeline { namespace joc::timeline {
inline constexpr std::int64_t kOamdUpdateQuantumSamples = 64;
inline constexpr int kTimelineObjects = 15; inline constexpr int kTimelineObjects = 15;
struct PositionTransition { struct PositionTransition {
@@ -50,6 +49,34 @@ public:
// positions[15][3]; queries must be monotonically increasing. // positions[15][3]; queries must be monotonically increasing.
Status positions_at(std::int64_t sample, double positions[kTimelineObjects][3]); Status positions_at(std::int64_t sample, double positions[kTimelineObjects][3]);
// bed 声道是固定通道:OAMD 不给位置,方位由声明的 bed 布局给出。
void set_fixed_position(int object_index, const double position[3]) {
if (object_index < 1 || object_index > kTimelineObjects) {
return;
}
fixed_[object_index - 1] = true;
fixed_xyz_[object_index - 1][0] = position[0];
fixed_xyz_[object_index - 1][1] = position[1];
fixed_xyz_[object_index - 1][2] = position[2];
}
// Drops the OAMD state and every transition but keeps the fixed bed positions:
// they describe the content, not the playback position.
void reset() {
state_.reset();
for (int index = 0; index < kTimelineObjects; ++index) {
tracks_[index] = ObjectPositionTrack();
has_previous_[index] = false;
for (int axis = 0; axis < 3; ++axis) {
previous_targets_[index][axis] = 0.0;
}
}
initialized_ = false;
payload_count_ = 0;
transition_count_ = 0;
last_coded_event_sample_ = -1;
}
std::uint64_t payload_count() const { return payload_count_; } std::uint64_t payload_count() const { return payload_count_; }
std::uint64_t transition_count() const { return transition_count_; } std::uint64_t transition_count() const { return transition_count_; }
bool initialized() const { return initialized_; } bool initialized() const { return initialized_; }
@@ -63,6 +90,8 @@ private:
bool initialized_ = false; bool initialized_ = false;
double previous_targets_[kTimelineObjects][3] = {}; double previous_targets_[kTimelineObjects][3] = {};
bool has_previous_[kTimelineObjects] = {}; bool has_previous_[kTimelineObjects] = {};
bool fixed_[kTimelineObjects] = {};
double fixed_xyz_[kTimelineObjects][3] = {};
std::uint64_t payload_count_ = 0; std::uint64_t payload_count_ = 0;
std::uint64_t transition_count_ = 0; std::uint64_t transition_count_ = 0;
std::int64_t last_coded_event_sample_ = -1; std::int64_t last_coded_event_sample_ = -1;
+80 -21
View File
@@ -19,6 +19,7 @@
#include <atomic> #include <atomic>
#include <cstdarg> #include <cstdarg>
#include <cstdio>
#include <cstring> #include <cstring>
#include <string> #include <string>
@@ -196,6 +197,24 @@ void read_local_tags(file::ptr const& source, file_info& info, abort_callback& a
} }
} }
// The chunk channel map handed to the host while playing. A map of zero (the
// SDK's "unspecified") is accepted by audio_chunk but rejected further down the
// output chain ("invalid audio stream specification"), and no WAVE map describes
// the renderer's order for the wider layouts, so the chunks carry the map the
// host itself uses for that channel count: it only transports the channel count
// and makes no claim about Dolby positions. The file properties stay unspecified
// (see get_info), so nothing downstream is told a position this layout does not
// have; the PCM keeps the layout table's order either way.
unsigned channel_map_for(unsigned channels) {
return audio_chunk::g_guess_channel_config(channels);
}
std::string mask_text(unsigned mask) {
char text[16] = {};
std::snprintf(text, sizeof(text), "0x%X", mask);
return text;
}
class input_joc : public input_stubs { class input_joc : public input_stubs {
public: public:
void open(service_ptr_t<file> hint, const char* path, t_input_open_reason reason, void open(service_ptr_t<file> hint, const char* path, t_input_open_reason reason,
@@ -354,6 +373,7 @@ public:
channels = layout_channels != 0 ? layout_channels : 6; channels = layout_channels != 0 ? layout_channels : 6;
render = "speaker " + settings.speaker_layout; render = "speaker " + settings.speaker_layout;
} }
const unsigned mask = channel_map_for(channels);
// The custom field and the log line state the delivery format, because it // The custom field and the log line state the delivery format, because it
// is the one thing about the output that a listener cannot hear. // is the one thing about the output that a listener cannot hear.
if (settings.force_int24) render += ", 24-bit delivery"; if (settings.force_int24) render += ", 24-bit delivery";
@@ -362,7 +382,10 @@ public:
info.info_set("codec_long", "E-AC-3 JOC (Dolby Atmos)"); info.info_set("codec_long", "E-AC-3 JOC (Dolby Atmos)");
info.info_set("encoding", "lossy"); info.info_set("encoding", "lossy");
info.info_set_int("samplerate", kSampleRate); info.info_set_int("samplerate", kSampleRate);
info.info_set_int("channels", channels); // Properties declares the channel count but no channel map: the delivered
// order is not a WAVE speaker order for most layouts, and the chunk map
// used for playback only carries the count (see channel_map_for).
info.info_set_channels_ex(channels, channels == 2 ? mask : 0u);
// What the component hands over, which is what the host keeps if it writes a // What the component hands over, which is what the host keeps if it writes a
// file from this stream: float32 by default, int24 when forced. This is also // file from this stream: float32 by default, int24 when forced. This is also
// what foobar2000's own lossless-conversion warning reads // what foobar2000's own lossless-conversion warning reads
@@ -424,8 +447,10 @@ public:
read_local_tags(m_file, info, abort); read_local_tags(m_file, info, abort);
} }
joc_log::line("decoder: get_info duration=%.3f s frames=%llu channels=%u render=%s%s", joc_log::line("decoder: get_info duration=%.3f s frames=%llu channels=%u mask=%s "
duration, static_cast<unsigned long long>(frames), channels, render.c_str(), "render=%s%s",
duration, static_cast<unsigned long long>(frames), channels,
mask_text(mask).c_str(), render.c_str(),
container ? " (container)" : ""); container ? " (container)" : "");
} }
@@ -448,17 +473,35 @@ public:
std::string error; std::string error;
if (!m_engine.start(m_native_path.get_ptr(), m_settings, &error)) { if (!m_engine.start(m_native_path.get_ptr(), m_settings, &error)) {
joc_log::line("decoder: engine start failed: %s", error.c_str()); joc_log::line("decoder: engine start failed: %s", error.c_str());
// The most common cause by far, and the one a user can act on. // The message the user sees is in the page's language; the engine's own
if (m_settings.output == joc_decode::Output::kBinaural && // line stays English and follows it, because it names the file or the
m_settings.hrtf_file.empty()) { // stream the failure came from.
throw exception_io_data( const joc_lang::Language language =
"JOC:双耳渲染需要先指定 HRTF 文件(Preferences -> Tools -> JOC 解码器)," joc_lang::resolve(joc_settings::read().language);
"或把输出改为扬声器布局。"); std::string message = joc_lang::get(
} language, m_settings.output == joc_decode::Output::kBinaural
throw exception_io_data(error.c_str()); ? joc_lang::Text::kErrorHrtfNeeded
: joc_lang::Text::kErrorRenderStream);
message += "\n";
message += error;
// Logged as well: the dialog the host shows is not part of a support log,
// and which language was in effect is part of the report.
joc_log::line("decoder: reporting to the user (%s):\n%s",
language == joc_lang::Language::kEnglish ? "english" : "chinese",
message.c_str());
throw exception_io_data(message.c_str());
} }
m_channels = m_engine.channels(); m_channels = m_engine.channels();
if (m_channels == 0) m_channels = 2; if (m_channels == 0) m_channels = 2;
// Only the map the component can describe is declared; see channel_map_for().
m_channel_config = channel_map_for(m_channels);
// The swap is a delivery-time reorder of the renderer's own channels, so it
// only applies when the layout the core rendered is the one being delivered.
m_swap_channels = joc_decode::SideRearChannels();
if (m_settings.swap_side_rear && m_settings.output == joc_decode::Output::kSpeaker &&
joc_decode::speaker_channels(m_settings.speaker_layout) == m_channels) {
m_swap_channels = joc_decode::side_rear_channels(m_settings.speaker_layout);
}
m_buffer.resize(kRunFrames * m_channels); m_buffer.resize(kRunFrames * m_channels);
m_frames_delivered = 0; m_frames_delivered = 0;
m_reported = false; m_reported = false;
@@ -468,10 +511,11 @@ public:
// about everything this component handed over. // about everything this component handed over.
m_clipped_samples = 0; m_clipped_samples = 0;
m_clip_reported = false; m_clip_reported = false;
joc_log::line("decoder: engine ready, %u output channel(s), %u frames per read, " joc_log::line("decoder: engine ready, %u output channel(s), mask=%s, %u frames per "
"delivery=%s", "read, delivery=%s",
m_channels, static_cast<unsigned>(kRunFrames), m_channels, mask_text(m_channel_config).c_str(),
m_settings.force_int24 ? "int24" : "float32"); static_cast<unsigned>(kRunFrames),
m_settings.force_int24 ? "int24" : "float32");
} }
bool decode_run(audio_chunk& chunk, abort_callback& abort) { bool decode_run(audio_chunk& chunk, abort_callback& abort) {
@@ -504,11 +548,16 @@ public:
// the pipeline sees is the 24-bit grid rather than the renderer's float -- which // the pipeline sees is the 24-bit grid rather than the renderer's float -- which
// is the whole point of the option. The quantisation happens here and nowhere // is the whole point of the option. The quantisation happens here and nowhere
// else, so a sample is rounded once. // else, so a sample is rounded once.
if (m_swap_channels.complete()) {
joc_decode::swap_side_rear(m_buffer.data(), frames, m_channels, m_swap_channels);
}
const float* samples = m_buffer.data();
double expected_delivered_peak = 0.0; double expected_delivered_peak = 0.0;
if (m_settings.force_int24) { if (m_settings.force_int24) {
m_int24.resize(frames * m_channels * 3); m_int24.resize(frames * m_channels * 3);
const joc_decode::Int24Block block = joc_decode::pack_int24( const joc_decode::Int24Block block = joc_decode::pack_int24(
m_buffer.data(), frames * m_channels, m_int24.data()); samples, frames * m_channels, m_int24.data());
m_clipped_samples += block.clipped; m_clipped_samples += block.clipped;
if (block.clipped != 0 && !m_clip_reported) { if (block.clipped != 0 && !m_clip_reported) {
m_clip_reported = true; m_clip_reported = true;
@@ -518,13 +567,13 @@ public:
static_cast<unsigned long long>(block.clipped)); static_cast<unsigned long long>(block.clipped));
} }
chunk.set_data_fixedpoint_signed(m_int24.data(), m_int24.size(), kSampleRate, chunk.set_data_fixedpoint_signed(m_int24.data(), m_int24.size(), kSampleRate,
m_channels, 24, m_channels, 24, m_channel_config);
audio_chunk::g_guess_channel_config(m_channels));
expected_delivered_peak = expected_delivered_peak =
static_cast<double>(block.peak) / joc_decode::kInt24ImportScale; static_cast<double>(block.peak) / joc_decode::kInt24ImportScale;
} else { } else {
chunk.set_data_32(m_buffer.data(), frames, m_channels, kSampleRate); chunk.set_data_32(samples, frames,
expected_delivered_peak = peak_of(m_buffer.data(), frames * m_channels); audio_chunk::makeSpec(kSampleRate, m_channels, m_channel_config));
expected_delivered_peak = peak_of(samples, frames * m_channels);
} }
m_frames_delivered += frames; m_frames_delivered += frames;
@@ -565,7 +614,12 @@ public:
// An aborted seek reports itself as an abort, not as a decode failure. // An aborted seek reports itself as an abort, not as a decode failure.
abort.check(); abort.check();
joc_log::line("decoder: seek to %.6f s failed: %s", seconds, error.c_str()); joc_log::line("decoder: seek to %.6f s failed: %s", seconds, error.c_str());
throw exception_io_data(error.c_str()); const joc_lang::Language language =
joc_lang::resolve(joc_settings::read().language);
std::string message = joc_lang::get(language, joc_lang::Text::kErrorSeek);
message += "\n";
message += error;
throw exception_io_data(message.c_str());
} }
// The position reporting and the first-read statistics belong to the run // The position reporting and the first-read statistics belong to the run
// that starts here, not to the one that was interrupted. // that starts here, not to the one that was interrupted.
@@ -652,11 +706,16 @@ private:
unsigned m_audio_index = 0; unsigned m_audio_index = 0;
joc_container::Result m_container; joc_container::Result m_container;
std::vector<float> m_buffer; std::vector<float> m_buffer;
// What the host is told about the stream's channel map; see channel_map_for().
unsigned m_channel_config = 0;
// int24 delivery: the packed bytes handed to the host, and what the clip caught. // int24 delivery: the packed bytes handed to the host, and what the clip caught.
std::vector<std::uint8_t> m_int24; std::vector<std::uint8_t> m_int24;
std::uint64_t m_clipped_samples = 0; std::uint64_t m_clipped_samples = 0;
bool m_clip_reported = false; bool m_clip_reported = false;
unsigned m_channels = 2; unsigned m_channels = 2;
// Set at open() when the layout has both a side and a rear pair and the
// setting is on; empty otherwise, which makes the swap a no-op.
joc_decode::SideRearChannels m_swap_channels;
std::uint64_t m_frames_delivered = 0; std::uint64_t m_frames_delivered = 0;
bool m_reported = false; bool m_reported = false;
// Chunks whose delivered samples did not match what the renderer produced. // Chunks whose delivered samples did not match what the renderer produced.
+89 -28
View File
@@ -2,11 +2,13 @@
#include <windows.h> #include <windows.h>
#include <algorithm>
#include <cmath> #include <cmath>
#include <cstdio> #include <cstdio>
#include <cstring> #include <cstring>
#include <cwchar> #include <cwchar>
#include <limits> #include <limits>
#include <utility>
#include <vector> #include <vector>
// The kernel copy that is compiled into this component; see kernel/. // The kernel copy that is compiled into this component; see kernel/.
@@ -301,10 +303,44 @@ private:
HANDLE handle_ = INVALID_HANDLE_VALUE; HANDLE handle_ = INVALID_HANDLE_VALUE;
}; };
const char* const kLayouts[] = {"2.0", "3.0", "3.1", "4.0", "5.0", "5.1", "5.1.2", // The layouts the core accepts, with the channels in the order the renderer
"5.1.4", "6.1", "7.0", "7.1", "7.1.2", "7.1.4", "9.1.4", // emits them. `speakers` are the reference table's names for those channels;
"9.1.6", "22.2"}; // the kernel is the authority on the list and on the channel counts, and
const unsigned kLayoutChannels[] = {2, 3, 4, 4, 5, 6, 8, 10, 7, 7, 8, 10, 12, 14, 16, 24}; // tests/layout_table_test.cpp checks both.
//
// 5.1's surround pair sits behind the listener (which is what the core's geometry
// says and what "5.1" means to WAVE), while 7.1 and up have a separate side pair
// and a rear pair. 9.1.x adds the wide pair in front. The two 5.1.x top pairs
// and the 7.1.x top pair sit above the listener's sides, and 9.1.6 adds the
// top-middle pair.
const LayoutSpec kLayouts[] = {
{"2.0", 2, {"L", "R"}},
{"3.1", 4, {"L", "R", "C", "LFE"}},
{"4.0", 4, {"L", "R", "Lrs", "Rrs"}},
{"5.1", 6, {"L", "R", "C", "LFE", "Ls", "Rs"}},
{"7.1", 8, {"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs"}},
{"5.1.2", 8, {"L", "R", "C", "LFE", "Ls", "Rs", "Ltm", "Rtm"}},
{"5.1.4", 10, {"L", "R", "C", "LFE", "Ls", "Rs", "Ltf", "Rtf", "Ltr", "Rtr"}},
{"7.1.2", 10,
{"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs", "Ltm", "Rtm"}},
{"7.1.4", 12,
{"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs", "Ltf", "Rtf", "Ltr", "Rtr"}},
{"9.1.4", 14,
{"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs", "Lw", "Rw", "Ltf", "Rtf", "Ltr",
"Rtr"}},
{"9.1.6", 16,
{"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs", "Lw", "Rw", "Ltf", "Rtf", "Ltm",
"Rtm", "Ltr", "Rtr"}},
};
constexpr std::size_t kLayoutCount = sizeof(kLayouts) / sizeof(kLayouts[0]);
const LayoutSpec* find_layout(const std::string& name) {
for (std::size_t i = 0; i < kLayoutCount; ++i) {
if (name == kLayouts[i].name) return &kLayouts[i];
}
return nullptr;
}
// Every ffmpeg child writes its diagnostics next to the component rather than into // Every ffmpeg child writes its diagnostics next to the component rather than into
// whatever working directory the host process happens to have; separate files so // whatever working directory the host process happens to have; separate files so
@@ -343,16 +379,47 @@ std::int64_t sample_of_seconds(double seconds) {
} // namespace } // namespace
const char* const* speaker_layouts(std::size_t* count) { const LayoutSpec* layout_table(std::size_t* count) {
if (count != nullptr) *count = sizeof(kLayouts) / sizeof(kLayouts[0]); if (count != nullptr) *count = kLayoutCount;
return kLayouts; return kLayouts;
} }
unsigned speaker_channels(const std::string& layout) { unsigned speaker_channels(const std::string& layout) {
for (std::size_t i = 0; i < sizeof(kLayouts) / sizeof(kLayouts[0]); ++i) { const LayoutSpec* spec = find_layout(layout);
if (layout == kLayouts[i]) return kLayoutChannels[i]; return spec != nullptr ? spec->channels : 0;
}
static int channel_index(const LayoutSpec& spec, const char* name) {
for (unsigned i = 0; i < spec.channels; ++i) {
if (std::strcmp(spec.speakers[i], name) == 0) return static_cast<int>(i);
}
return -1;
}
SideRearChannels side_rear_channels(const std::string& layout) {
SideRearChannels map;
const LayoutSpec* spec = find_layout(layout);
if (spec == nullptr) return map;
map.left_side = channel_index(*spec, "Ls");
map.right_side = channel_index(*spec, "Rs");
map.left_rear = channel_index(*spec, "Lrs");
map.right_rear = channel_index(*spec, "Rrs");
return map;
}
void swap_side_rear(float* interleaved, std::size_t frames, unsigned channels,
const SideRearChannels& map) {
if (interleaved == nullptr || channels == 0 || !map.complete()) return;
int highest = map.left_side;
if (map.right_side > highest) highest = map.right_side;
if (map.left_rear > highest) highest = map.left_rear;
if (map.right_rear > highest) highest = map.right_rear;
if (static_cast<unsigned>(highest) >= channels) return;
for (std::size_t frame = 0; frame < frames; ++frame) {
float* block = interleaved + frame * channels;
std::swap(block[map.left_side], block[map.left_rear]);
std::swap(block[map.right_side], block[map.right_rear]);
} }
return 0;
} }
namespace { namespace {
@@ -423,9 +490,7 @@ std::string resolve_hrtf_file(const Settings& settings) {
if (directory.empty()) return {}; if (directory.empty()) return {};
// Same convention as the reference CLI next to its executable: // Same convention as the reference CLI next to its executable:
// <base>\HRTF\binaural.sofa or <base>\HRTF\binaural.personalized_headphone. // <base>\HRTF\binaural.sofa or <base>\HRTF\binaural.personalized_headphone.
const char* name = (settings.hrtf_source == HrtfSource::kRosella) const char* name = "binaural.personalized_headphone";
? "binaural.personalized_headphone"
: "binaural.sofa";
return directory + "\\HRTF\\" + name; return directory + "\\HRTF\\" + name;
} }
@@ -965,28 +1030,23 @@ bool Engine::start(const std::string& input_path, const Settings& settings, std:
const std::string& hrtf_file = hrtf_in_use; const std::string& hrtf_file = hrtf_in_use;
if (hrtf_file.empty()) { if (hrtf_file.empty()) {
if (error != nullptr) { if (error != nullptr) {
*error = "双耳渲染需要 HRTF 文件,但组件目录无法确定;请在设置页里显式指定路径"; *error = "the component directory is unknown, so the default HRTF location "
"cannot be resolved; name an HRTF file in the preferences page";
} }
return false; return false;
} }
if (!file_exists(hrtf_file)) { if (!file_exists(hrtf_file)) {
if (error != nullptr) { if (error != nullptr) {
*error = std::string("找不到 HRTF 文件:") + hrtf_file + *error = "HRTF file not found: " + hrtf_file +
(settings.hrtf_file.empty() ? "(默认位置,可在设置页里指定其它路径)" (settings.hrtf_file.empty()
: ""); ? " (the default location; another file can be named in the "
"preferences page)"
: "");
} }
return false; return false;
} }
if (settings.hrtf_source == HrtfSource::kRosella) { config.personalized_headphone_path = hrtf_file.c_str();
config.personalized_headphone_path = hrtf_file.c_str();
} else {
config.hrtf_sofa_path = hrtf_file.c_str();
}
} }
config.hrtf_cache_policy = settings.hrtf_cache_policy;
config.hrtf_cache_dir =
settings.hrtf_cache_dir.empty() ? nullptr : settings.hrtf_cache_dir.c_str();
config.hrtf_radius_m = settings.hrtf_radius_m;
config.binaural_tail_seconds = settings.tail_seconds; config.binaural_tail_seconds = settings.tail_seconds;
config.object_delay_samples = settings.object_delay_samples; config.object_delay_samples = settings.object_delay_samples;
config.gain_db = settings.gain_db; config.gain_db = settings.gain_db;
@@ -1073,9 +1133,10 @@ bool Engine::seek(double seconds, double total_seconds, std::string* error) {
impl.delivered = 0; impl.delivered = 0;
} }
// joc_stream_reset keeps the renderer and its HRTF field: it drops the whole // joc_stream_reset keeps the renderer and its HRTF field: it drops the timeline
// timeline, gain ramps, room tail and filter-bank history, which is exactly // state, gain ramps, room tail and filter-bank history, which is exactly what a
// what a restart at another position needs. // restart at another position needs. The fixed bed positions survive: they
// describe the content, not the playback position.
const joc_error reset = impl.api.reset(impl.stream); const joc_error reset = impl.api.reset(impl.stream);
if (reset != JOC_OK) { if (reset != JOC_OK) {
if (error != nullptr) { if (error != nullptr) {
+55 -14
View File
@@ -44,13 +44,6 @@ enum class Output {
kSpeaker = 1, // N channels, named layout kSpeaker = 1, // N channels, named layout
}; };
// Which HRTF to render with. Both inputs are user-facing model/data files; how
// the renderer gets from them to its internal filter field is its own business.
enum class HrtfSource {
kSofa = 0,
kRosella = 1,
};
// Where the E-AC-3 syncframes come from. A bare stream is read straight from the // Where the E-AC-3 syncframes come from. A bare stream is read straight from the
// file; inside a container the track has to be extracted first (ffmpeg, stream copy). // file; inside a container the track has to be extracted first (ffmpeg, stream copy).
enum class InputKind { enum class InputKind {
@@ -64,12 +57,8 @@ struct Settings {
// Which of the container's audio tracks holds the E-AC-3 stream, 0-based. // Which of the container's audio tracks holds the E-AC-3 stream, 0-based.
unsigned audio_index = 0; unsigned audio_index = 0;
std::string speaker_layout = "7.1"; std::string speaker_layout = "7.1";
HrtfSource hrtf_source = HrtfSource::kSofa;
// Empty means the default file in the default folder, see resolve_hrtf_file(). // Empty means the default file in the default folder, see resolve_hrtf_file().
std::string hrtf_file; std::string hrtf_file;
std::string hrtf_cache_dir; // SOFA compile cache (disk policy)
unsigned hrtf_cache_policy = 1; // 0 none, 1 memory, 2 disk
double hrtf_radius_m = 1.0; // SOFA measurement-radius shell
std::uint32_t binaural_mode = 3; // JOC_BINAURAL_MID std::uint32_t binaural_mode = 3; // JOC_BINAURAL_MID
double gain_db = 0.0; double gain_db = 0.0;
double tail_seconds = 5.0; double tail_seconds = 5.0;
@@ -102,12 +91,67 @@ struct Settings {
// rule is reproduced here instead. Out-of-range samples follow the core's // rule is reproduced here instead. Out-of-range samples follow the core's
// JOC_CLIP_CONTINUE policy: truncated to the edge, and reported. // JOC_CLIP_CONTINUE policy: truncated to the edge, and reported.
bool force_int24 = false; bool force_int24 = false;
// Swap Ls with Lrs and Rs with Rrs in the delivered PCM. Only layouts that
// carry both the side and the rear pair are affected, so a 5.1.x layout whose
// rear slots hold top channels is left alone.
bool swap_side_rear = false;
}; };
// ---- speaker delivery ------------------------------------------------------
//
// The renderer emits a layout in the order the reference table defines for it,
// and that order is what foobar2000 receives. The host defines the interleaved
// channel order of a chunk as the ascending order of the channel map's speaker
// flags (SDK audio_chunk.h: "order of interleaved channel data in the stream is
// same as order of these flags"), so a channel map may only be declared when it
// describes exactly that order. Only stereo does, so the component declares no
// map for the file and gives each chunk the host's own default map for the channel
// count (see input_joc.cpp): the map carries the count, not positions, and the PCM
// is handed over unchanged. Channel numbers are the positions in the layout table
// below; mapping them to physical speakers belongs to the player or the user.
// The widest layout the core renders; the channel arrays below are sized for it.
inline constexpr unsigned kMaxLayoutChannels = 16;
// A layout the core accepts, with its channels in the order the renderer emits
// them. The names are the reference table's speaker names, so a channel can be
// checked against the kernel's table and against the reference renderer.
struct LayoutSpec {
const char* name;
unsigned channels;
const char* speakers[kMaxLayoutChannels];
};
// Every layout the core accepts, in the order a settings page should list them.
const LayoutSpec* layout_table(std::size_t* count);
// Channel count of a named layout, or 0 when the layout is not one of the // Channel count of a named layout, or 0 when the layout is not one of the
// layouts the core accepts. // layouts the core accepts.
unsigned speaker_channels(const std::string& layout); unsigned speaker_channels(const std::string& layout);
// The channels a side/rear swap moves, as positions in the layout's own order.
// A layout without both pairs leaves them at -1, which makes the swap a no-op;
// the lookup is by name, so a layout that reuses a slot for something else (5.1.2
// and 5.1.4 put top channels where 7.1 has the rear pair) is never touched.
struct SideRearChannels {
int left_side = -1;
int right_side = -1;
int left_rear = -1;
int right_rear = -1;
bool complete() const {
return left_side >= 0 && right_side >= 0 && left_rear >= 0 && right_rear >= 0;
}
};
// Looks the layout up in the table above and locates its Ls/Rs and Lrs/Rrs.
SideRearChannels side_rear_channels(const std::string& layout);
// Swaps Ls with Lrs and Rs with Rrs in place, `frames` blocks of `channels`
// interleaved float32 samples. Everything else in the block is untouched.
void swap_side_rear(float* interleaved, std::size_t frames, unsigned channels,
const SideRearChannels& map);
// Directory this component's DLL was loaded from. The default HRTF folder is // Directory this component's DLL was loaded from. The default HRTF folder is
// <that directory>\HRTF, the same place the reference CLI looks next to its exe. // <that directory>\HRTF, the same place the reference CLI looks next to its exe.
std::string component_directory(); std::string component_directory();
@@ -117,9 +161,6 @@ std::string component_directory();
// component directory cannot be determined. // component directory cannot be determined.
std::string resolve_hrtf_file(const Settings& settings); std::string resolve_hrtf_file(const Settings& settings);
// Every layout the core accepts, in the order a settings page should list them.
const char* const* speaker_layouts(std::size_t* count);
// Result of examining a file without rendering anything. // Result of examining a file without rendering anything.
struct FileProbe { struct FileProbe {
bool readable = false; bool readable = false;
+97
View File
@@ -0,0 +1,97 @@
// See lang.h: one row per string, Chinese first because it is the source text.
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include "lang.h"
namespace joc_lang {
namespace {
struct Entry {
Text id;
const char* zh;
const char* en;
};
constexpr Entry kTexts[] = {
{Text::kPageName, "JOC 解码器", "JOC decoder"},
{Text::kGroupOutput, "输出", "Output"},
{Text::kRadioBinaural, "双耳(HRTF)", "Binaural (HRTF)"},
{Text::kRadioSpeaker, "扬声器布局", "Speaker layout"},
{Text::kLabelMode, "双耳模式", "Binaural mode"},
{Text::kComboModeNear, "near(近场)", "near"},
{Text::kComboModeMid, "mid(默认)", "mid (default)"},
{Text::kComboModeFar, "far(远场)", "far"},
{Text::kLabelTail, "房间尾音(秒)", "Room tail (s)"},
{Text::kCheckInt24, "强制 24bit 输出(int24)", "Force 24-bit output (int24)"},
{Text::kInt24Hint, "切换后需刷新文件信息", "reload file info after switching"},
{Text::kSpeakerStatus, "扬声器布局 %s", "Speaker layout %s"},
{Text::kGroupHrtf, "HRTF", "HRTF"},
{Text::kRadioSofa, "SOFA 文件", "SOFA file"},
{Text::kRadioRosella, "Rosella 个性化模型", "Rosella personalized model"},
{Text::kLabelHrtfFile, "HRTF 文件", "HRTF file"},
{Text::kButtonBrowse, "浏览…", "Browse…"},
{Text::kHrtfHint,
"留空时读组件目录下 HRTF\\binaural.sofa 或 HRTF\\binaural.personalized_headphone。",
"Empty means HRTF\\binaural.sofa or binaural.personalized_headphone next to "
"the component."},
{Text::kHrtfSourceSofa, "SOFA", "SOFA"},
{Text::kHrtfSourceRosella, "Rosella 个性化模型", "Rosella personalized model"},
{Text::kHrtfDefault, "默认", "default"},
{Text::kHrtfDefaultUnknown, "无法确定默认路径",
"cannot resolve the default location"},
{Text::kGroupGain, "增益", "Gain"},
{Text::kCheckGain, "应用增益", "Apply gain"},
{Text::kLabelGainUnit, "dB", "dB"},
{Text::kGainStatusOn, "增益开 %.2f dB", "gain on, %.2f dB"},
{Text::kGainStatusOff, "增益关(输出不衰减)", "gain off (no attenuation)"},
{Text::kGainHint, "双耳渲染后可能超过 0 dBFS,可用负值衰减。",
"Binaural rendering can exceed 0 dBFS; attenuate with a negative value."},
{Text::kCheckSwapSideRear, "交换侧环绕与后环绕声道",
"Swap side and rear channels"},
{Text::kGroupOther, "其它", "Other"},
{Text::kLabelLanguage, "界面语言", "Language"},
{Text::kLabelFfmpeg, "ffmpeg.exe", "ffmpeg.exe"},
{Text::kLanguageSystem, "跟随系统", "Follow system"},
{Text::kLanguageChinese, "简体中文", "简体中文"},
{Text::kLanguageEnglish, "English", "English"},
{Text::kSeparator, ":", ": "},
{Text::kErrorHrtfNeeded,
"JOC:双耳渲染需要 HRTF 数据文件,请在 Preferences → Tools → JOC 解码器 里指定,"
"或把输出改为扬声器布局。",
"JOC: binaural rendering needs an HRTF data file. Set one in Preferences → "
"Tools → JOC decoder, or switch the output to a speaker layout."},
{Text::kErrorRenderStream, "JOC:无法创建渲染流。",
"JOC: cannot create the render stream."},
{Text::kErrorSeek, "JOC:无法跳转到目标位置。",
"JOC: cannot seek to the target position."},
};
} // namespace
Language resolve(Language language) {
if (language == Language::kChineseSimplified || language == Language::kEnglish) {
return language;
}
// PRIMARYLANGID stays the same across the Chinese variants, so a Traditional
// Chinese Windows reads the simplified column rather than English.
return PRIMARYLANGID(GetUserDefaultUILanguage()) == LANG_CHINESE
? Language::kChineseSimplified
: Language::kEnglish;
}
const char* get(Language language, Text id) {
const bool english = resolve(language) == Language::kEnglish;
for (const Entry& entry : kTexts) {
if (entry.id == id) return english ? entry.en : entry.zh;
}
return "";
}
} // namespace joc_lang
+74
View File
@@ -0,0 +1,74 @@
// User-interface text for the component, in the languages the page offers.
//
// Only strings a user can see belong here: labels, buttons, the status lines under
// the controls, and the messages an error is reported with. Log lines and engine
// diagnostics stay English, so a support log reads the same whatever the page is
// set to.
//
// The Chinese column is the source: the English column translates it rather than
// wording the feature independently, and the two must mean the same thing.
#pragma once
#include <string>
namespace joc_lang {
enum class Language {
kSystem = 0, // follow the Windows user-interface language
kChineseSimplified = 1,
kEnglish = 2,
};
enum class Text {
// preferences page
kPageName,
kGroupOutput,
kRadioBinaural,
kRadioSpeaker,
kLabelMode,
kComboModeNear,
kComboModeMid,
kComboModeFar,
kLabelTail,
kCheckInt24,
kInt24Hint,
kSpeakerStatus,
kGroupHrtf,
kRadioSofa,
kRadioRosella,
kLabelHrtfFile,
kButtonBrowse,
kHrtfHint,
kHrtfSourceSofa,
kHrtfSourceRosella,
kHrtfDefault,
kHrtfDefaultUnknown,
kGroupGain,
kCheckGain,
kLabelGainUnit,
kGainStatusOn,
kGainStatusOff,
kGainHint,
kCheckSwapSideRear,
kGroupOther,
kLabelLanguage,
kLabelFfmpeg,
kLanguageSystem,
kLanguageChinese,
kLanguageEnglish,
// "SOFA": the separator between a label and the value after it
kSeparator,
// messages shown when decoding fails
kErrorHrtfNeeded,
kErrorRenderStream,
kErrorSeek,
};
// The language actually used: kSystem resolves to the Windows user-interface
// language (Chinese if that language is Chinese, English otherwise).
Language resolve(Language language);
// Text for an already resolved language (pass resolve()'s result).
const char* get(Language language, Text id);
} // namespace joc_lang
+13 -2
View File
@@ -8,16 +8,18 @@
#include <SDK/componentversion.h> #include <SDK/componentversion.h>
#include <SDK/coreversion.h> #include <SDK/coreversion.h>
#include <SDK/initquit.h> #include <SDK/initquit.h>
#include "lang.h"
#include "log.h" #include "log.h"
#include "settings.h"
// Kept in one place: the string reported to foobar2000 and written to the log // Kept in one place: the string reported to foobar2000 and written to the log
// must not drift apart. // must not drift apart.
#define JOC_VERSION "0.4.0" #define JOC_VERSION "0.5.0"
DECLARE_COMPONENT_VERSION("JOC decoder (E-AC-3 JOC)", JOC_VERSION, DECLARE_COMPONENT_VERSION("JOC decoder (E-AC-3 JOC)", JOC_VERSION,
"Plays E-AC-3 JOC (Dolby Atmos) files: the JOC objects are " "Plays E-AC-3 JOC (Dolby Atmos) files: the JOC objects are "
"rendered to binaural (SOFA or Rosella HRTF) or to a speaker " "rendered to binaural (SOFA or Rosella HRTF) or to a speaker "
"layout up to 7.1."); "layout up to 9.1.6.");
// Refuses to run when the file has been renamed; the troubleshooter relies on it. // Refuses to run when the file has been renamed; the troubleshooter relies on it.
VALIDATE_COMPONENT_FILENAME("foo_input_joc.dll"); VALIDATE_COMPONENT_FILENAME("foo_input_joc.dll");
@@ -42,6 +44,15 @@ public:
joc_log::line("log file : %s", joc_log::path()); joc_log::line("log file : %s", joc_log::path());
joc_log::line("log limit : %llu byte(s) per file, then rolled to the .1 suffix", joc_log::line("log limit : %llu byte(s) per file, then rolled to the .1 suffix",
joc_log::budget_bytes()); joc_log::budget_bytes());
const joc_settings::Values stored = joc_settings::read();
joc_log::line("interface language: %s (stored: %s)",
joc_lang::resolve(stored.language) == joc_lang::Language::kEnglish
? "english"
: "chinese",
stored.language == joc_lang::Language::kSystem
? "system default"
: (stored.language == joc_lang::Language::kEnglish ? "english"
: "chinese"));
joc_log::line("compiled as : %s", joc_log::line("compiled as : %s",
#if defined(_M_IX86) #if defined(_M_IX86)
"x86 (32-bit)" "x86 (32-bit)"
+246 -112
View File
@@ -4,6 +4,11 @@
// plain Win32 modeless dialog. The SDK's preferences_page_impl<> helper would // plain Win32 modeless dialog. The SDK's preferences_page_impl<> helper would
// pull in the ATL/WTL dialog framework, which the SDK does not ship; nothing in // pull in the ATL/WTL dialog framework, which the SDK does not ship; nothing in
// this page needs it. // this page needs it.
//
// Every visible string comes from src/lang.cpp: the dialog resource carries the
// Chinese text as the design-time default, and the page replaces all of it once it
// knows which language is selected, so changing the language combo takes effect
// without reopening the page.
#include <SDK/foobar2000-lite.h> #include <SDK/foobar2000-lite.h>
@@ -16,8 +21,10 @@
#include <cstdio> #include <cstdio>
#include <string> #include <string>
#include <vector>
#include "joc_decode.h" #include "joc_decode.h"
#include "lang.h"
#include "prefs.h" #include "prefs.h"
#include "log.h" #include "log.h"
#include "resource.h" #include "resource.h"
@@ -60,40 +67,80 @@ void set_text(HWND control, const std::string& text) {
SetWindowTextW(control, wide(text).c_str()); SetWindowTextW(control, wide(text).c_str());
} }
// Layouts are offered up to 7.1 on purpose: output chains handle eight channels // A drop-down list's items are rebuilt whenever the language changes, and the
// comfortably, and wider layouts are only meaningful when writing a file. // selection has to survive that.
struct LayoutChoice { void fill_combo(HWND combo, const std::vector<std::string>& items, int selected) {
const char* name; const int current =
const char* label; selected >= 0 ? selected
}; : static_cast<int>(SendMessageW(combo, CB_GETCURSEL, 0, 0));
const LayoutChoice kLayoutChoices[] = { SendMessageW(combo, CB_RESETCONTENT, 0, 0);
{"2.0", "2.0 (立体声)"}, {"3.0", "3.0"}, {"3.1", "3.1"}, {"4.0", "4.0"}, for (const std::string& item : items) {
{"5.0", "5.0"}, {"5.1", "5.1"}, {"6.1", "6.1"}, {"7.0", "7.0"}, SendMessageW(combo, CB_ADDSTRING, 0,
{"7.1", "7.1"}, reinterpret_cast<LPARAM>(wide(item).c_str()));
}; }
if (current >= 0 && current < static_cast<int>(items.size())) {
SendMessageW(combo, CB_SETCURSEL, static_cast<WPARAM>(current), 0);
}
}
const char* const kModeNames[] = {"near", "far", "mid"}; // The binaural mode combo lists the three modes in the order they widen, with the
const char* const kModeLabels[] = {"near(近场)", "far(远场)", "mid(默认)"}; // default (mid) in the middle.
joc_lang::Text mode_text(unsigned index) {
switch (index) {
case 0: return joc_lang::Text::kComboModeNear;
case 2: return joc_lang::Text::kComboModeFar;
default: return joc_lang::Text::kComboModeMid;
}
}
unsigned mode_index(unsigned mode) { unsigned mode_index(unsigned mode) {
switch (mode) { switch (mode) {
case 1: return 0; case 1: return 0;
case 2: return 1; case 2: return 2;
default: return 2; default: return 1;
} }
} }
unsigned mode_value(unsigned index) { unsigned mode_value(unsigned index) {
switch (index) { switch (index) {
case 0: return 1; case 0: return 1;
case 1: return 2; case 2: return 2;
default: return 3; default: return 3;
} }
} }
int language_index(joc_lang::Language language) {
switch (language) {
case joc_lang::Language::kChineseSimplified: return 1;
case joc_lang::Language::kEnglish: return 2;
default: return 0;
}
}
joc_lang::Language language_value(int index) {
switch (index) {
case 1: return joc_lang::Language::kChineseSimplified;
case 2: return joc_lang::Language::kEnglish;
default: return joc_lang::Language::kSystem;
}
}
std::vector<std::string> mode_items(joc_lang::Language language) {
std::vector<std::string> items;
for (unsigned i = 0; i < 3; ++i) {
items.emplace_back(joc_lang::get(language, mode_text(i)));
}
return items;
}
std::vector<std::string> language_items(joc_lang::Language language) {
return {joc_lang::get(language, joc_lang::Text::kLanguageSystem),
joc_lang::get(language, joc_lang::Text::kLanguageChinese),
joc_lang::get(language, joc_lang::Text::kLanguageEnglish)};
}
bool pick_file(HWND owner, std::string& path, const wchar_t* title, bool pick_file(HWND owner, std::string& path, const wchar_t* title,
const wchar_t* filter) { const wchar_t* filter) { wchar_t buffer[4096] = {};
wchar_t buffer[4096] = {};
const std::wstring current = wide(path); const std::wstring current = wide(path);
if (!current.empty() && current.size() < 4090) { if (!current.empty() && current.size() < 4090) {
std::wcsncpy(buffer, current.c_str(), 4090); std::wcsncpy(buffer, current.c_str(), 4090);
@@ -111,6 +158,42 @@ bool pick_file(HWND owner, std::string& path, const wchar_t* title,
return true; return true;
} }
// Shortens a path to the width a control has, keeping its start and the file name
// and cutting out the middle. The status line under the group is two lines tall,
// and a long user-components path would otherwise push the file name out of view.
std::string elide_path(HWND control, const std::string& path, int max_width) {
HDC dc = GetDC(control);
if (dc == nullptr) return path;
const auto font = reinterpret_cast<HFONT>(SendMessageW(control, WM_GETFONT, 0, 0));
HGDIOBJ previous = font != nullptr ? SelectObject(dc, font) : nullptr;
auto fits = [&](const std::wstring& text) {
SIZE size{};
GetTextExtentPoint32W(dc, text.c_str(), static_cast<int>(text.size()), &size);
return size.cx <= max_width;
};
const std::wstring wide_path = wide(path);
std::string result = path;
if (!fits(wide_path)) {
const std::size_t slash = wide_path.find_last_of(L"\\/");
const std::wstring tail = slash == std::wstring::npos ? wide_path
: wide_path.substr(slash);
const std::wstring head = slash == std::wstring::npos ? std::wstring()
: wide_path.substr(0, slash);
result = narrow(tail);
for (std::size_t keep = head.size(); keep > 0; --keep) {
const std::wstring candidate = head.substr(0, keep) + L"…" + tail;
if (fits(candidate)) {
result = narrow(candidate);
break;
}
}
}
if (previous != nullptr) SelectObject(dc, previous);
ReleaseDC(control, dc);
return result;
}
class prefs_instance : public preferences_page_instance { class prefs_instance : public preferences_page_instance {
public: public:
prefs_instance(HWND parent, preferences_page_callback::ptr callback) prefs_instance(HWND parent, preferences_page_callback::ptr callback)
@@ -142,12 +225,12 @@ public:
joc_settings::write(values); joc_settings::write(values);
m_initial = values; m_initial = values;
joc_log::line("prefs: applied %s", joc_settings::describe(values).c_str()); joc_log::line("prefs: applied %s", joc_settings::describe(values).c_str());
update_status(); apply_texts();
notify(); notify();
} }
void reset() override { void reset() override {
load_controls(joc_settings::defaults()); load_values(joc_settings::defaults());
joc_log::line("prefs: reset to defaults"); joc_log::line("prefs: reset to defaults");
notify(); notify();
} }
@@ -169,24 +252,17 @@ private:
INT_PTR handle(UINT message, WPARAM wparam, LPARAM lparam) { INT_PTR handle(UINT message, WPARAM wparam, LPARAM lparam) {
switch (message) { switch (message) {
case WM_INITDIALOG: case WM_INITDIALOG:
load_controls(joc_settings::read()); load_values(joc_settings::read());
apply_dark_mode(); apply_dark_mode();
update_status();
return TRUE; return TRUE;
case WM_COMMAND: { case WM_COMMAND: {
const int id = LOWORD(wparam); const int id = LOWORD(wparam);
const int code = HIWORD(wparam); const int code = HIWORD(wparam);
if (id == IDC_BROWSE_HRTF) { if (id == IDC_BROWSE_HRTF) {
std::string path = get_text(GetDlgItem(m_hwnd, IDC_EDIT_HRTF)); std::string path = get_text(GetDlgItem(m_hwnd, IDC_EDIT_HRTF));
// The filter follows the selected source, because that is what const wchar_t* filter = L"Rosella 模型 (*.personalized_headphone)\0"
// decides the format the file has to be in. L"*.personalized_headphone\0所有文件 (*.*)\0*.*\0\0";
const wchar_t* filter = L"SOFA (*.sofa)\0*.sofa\0所有文件 (*.*)\0*.*\0\0"; const wchar_t* title = L"选择 Rosella 个性化模型";
const wchar_t* title = L"选择 SOFA HRTF 文件";
if (IsDlgButtonChecked(m_hwnd, IDC_RADIO_HRTF_ROSELLA) == BST_CHECKED) {
filter = L"Rosella 模型 (*.personalized_headphone)\0"
L"*.personalized_headphone\0所有文件 (*.*)\0*.*\0\0";
title = L"选择 Rosella 个性化模型";
}
if (pick_file(m_hwnd, path, title, filter)) { if (pick_file(m_hwnd, path, title, filter)) {
set_text(GetDlgItem(m_hwnd, IDC_EDIT_HRTF), path); set_text(GetDlgItem(m_hwnd, IDC_EDIT_HRTF), path);
update_status(); update_status();
@@ -194,12 +270,6 @@ private:
} }
return TRUE; return TRUE;
} }
if (id == IDC_RADIO_HRTF_SOFA || id == IDC_RADIO_HRTF_ROSELLA) {
update_enabled_state();
update_status();
notify();
return TRUE;
}
if (id == IDC_BROWSE_FFMPEG) { if (id == IDC_BROWSE_FFMPEG) {
std::string path = get_text(GetDlgItem(m_hwnd, IDC_EDIT_FFMPEG)); std::string path = get_text(GetDlgItem(m_hwnd, IDC_EDIT_FFMPEG));
if (pick_file(m_hwnd, path, L"选择 ffmpeg.exe", if (pick_file(m_hwnd, path, L"选择 ffmpeg.exe",
@@ -210,18 +280,30 @@ private:
return TRUE; return TRUE;
} }
if (id == IDC_RADIO_BINAURAL || id == IDC_RADIO_SPEAKER) { if (id == IDC_RADIO_BINAURAL || id == IDC_RADIO_SPEAKER) {
update_enabled_state(); update_status();
notify(); notify();
return TRUE; return TRUE;
} }
if (id == IDC_CHECK_GAIN || id == IDC_CHECK_INT24) { if (id == IDC_CHECK_GAIN || id == IDC_CHECK_INT24 ||
update_enabled_state(); id == IDC_CHECK_SWAP_SIDE_REAR) {
update_status();
notify(); notify();
return TRUE; return TRUE;
} }
if (code == EN_CHANGE || code == CBN_SELCHANGE) { if (code == CBN_SELCHANGE) {
if (id == IDC_EDIT_HRTF || id == IDC_COMBO_LAYOUT || if (id == IDC_COMBO_LANGUAGE) {
id == IDC_EDIT_GAIN) { // The language applies to the page itself, so every text is
// replaced at once. The value is stored when the page is
// applied, like the other controls.
apply_texts();
} else if (id == IDC_COMBO_LAYOUT || id == IDC_COMBO_MODE) {
update_status();
}
notify();
return TRUE;
}
if (code == EN_CHANGE) {
if (id == IDC_EDIT_HRTF || id == IDC_EDIT_GAIN) {
update_status(); update_status();
} }
notify(); notify();
@@ -264,32 +346,55 @@ private:
return FALSE; return FALSE;
} }
void load_controls(const joc_settings::Values& values) { // ---- language ---------------------------------------------------------
joc_lang::Language selected_language() const {
const int index = static_cast<int>(
SendDlgItemMessageW(m_hwnd, IDC_COMBO_LANGUAGE, CB_GETCURSEL, 0, 0));
return language_value(index);
}
// Replaces every visible string with the one for the language the combo has
// selected. Safe to call before the combos have items: their lists are
// (re)built here from the same language, keeping the current selection.
void apply_texts() {
const joc_lang::Language language = joc_lang::resolve(selected_language());
auto label = [&](int control, joc_lang::Text text) {
set_text(GetDlgItem(m_hwnd, control), joc_lang::get(language, text));
};
label(IDC_GROUP_OUTPUT, joc_lang::Text::kGroupOutput);
label(IDC_RADIO_BINAURAL, joc_lang::Text::kRadioBinaural);
label(IDC_RADIO_SPEAKER, joc_lang::Text::kRadioSpeaker);
label(IDC_LABEL_MODE, joc_lang::Text::kLabelMode);
label(IDC_LABEL_TAIL, joc_lang::Text::kLabelTail);
label(IDC_CHECK_INT24, joc_lang::Text::kCheckInt24);
label(IDC_CHECK_SWAP_SIDE_REAR, joc_lang::Text::kCheckSwapSideRear);
label(IDC_LABEL_INT24_HINT, joc_lang::Text::kInt24Hint);
label(IDC_GROUP_HRTF, joc_lang::Text::kGroupHrtf);
label(IDC_RADIO_HRTF_ROSELLA, joc_lang::Text::kRadioRosella);
label(IDC_LABEL_HRTF, joc_lang::Text::kLabelHrtfFile);
label(IDC_BROWSE_HRTF, joc_lang::Text::kButtonBrowse);
label(IDC_LABEL_HRTF_HINT, joc_lang::Text::kHrtfHint);
label(IDC_GROUP_GAIN, joc_lang::Text::kGroupGain);
label(IDC_CHECK_GAIN, joc_lang::Text::kCheckGain);
label(IDC_LABEL_GAIN, joc_lang::Text::kLabelGainUnit);
label(IDC_LABEL_GAIN_HINT, joc_lang::Text::kGainHint);
label(IDC_GROUP_MISC, joc_lang::Text::kGroupOther);
label(IDC_LABEL_LANGUAGE, joc_lang::Text::kLabelLanguage);
label(IDC_LABEL_FFMPEG, joc_lang::Text::kLabelFfmpeg);
label(IDC_BROWSE_FFMPEG, joc_lang::Text::kButtonBrowse);
fill_combo(GetDlgItem(m_hwnd, IDC_COMBO_MODE), mode_items(language), -1);
fill_combo(GetDlgItem(m_hwnd, IDC_COMBO_LANGUAGE), language_items(language), -1);
update_status();
}
// ---- control values ---------------------------------------------------
void load_values(const joc_settings::Values& values) {
CheckRadioButton(m_hwnd, IDC_RADIO_BINAURAL, IDC_RADIO_SPEAKER, CheckRadioButton(m_hwnd, IDC_RADIO_BINAURAL, IDC_RADIO_SPEAKER,
values.output == 0 ? IDC_RADIO_BINAURAL : IDC_RADIO_SPEAKER); values.output == 0 ? IDC_RADIO_BINAURAL : IDC_RADIO_SPEAKER);
HWND layout = GetDlgItem(m_hwnd, IDC_COMBO_LAYOUT);
SendMessageW(layout, CB_RESETCONTENT, 0, 0);
int selected = 0;
for (unsigned i = 0; i < sizeof(kLayoutChoices) / sizeof(kLayoutChoices[0]); ++i) {
SendMessageW(layout, CB_ADDSTRING, 0,
reinterpret_cast<LPARAM>(wide(kLayoutChoices[i].label).c_str()));
if (values.speaker_layout == kLayoutChoices[i].name) selected = static_cast<int>(i);
}
SendMessageW(layout, CB_SETCURSEL, selected, 0);
HWND mode = GetDlgItem(m_hwnd, IDC_COMBO_MODE);
SendMessageW(mode, CB_RESETCONTENT, 0, 0);
for (unsigned i = 0; i < 3; ++i) {
SendMessageW(mode, CB_ADDSTRING, 0,
reinterpret_cast<LPARAM>(wide(kModeLabels[i]).c_str()));
}
SendMessageW(mode, CB_SETCURSEL, mode_index(values.binaural_mode), 0);
CheckRadioButton(m_hwnd, IDC_RADIO_HRTF_SOFA, IDC_RADIO_HRTF_ROSELLA,
values.hrtf_source == joc_settings::HrtfSource::kRosella
? IDC_RADIO_HRTF_ROSELLA
: IDC_RADIO_HRTF_SOFA);
set_text(GetDlgItem(m_hwnd, IDC_EDIT_HRTF), values.hrtf_file); set_text(GetDlgItem(m_hwnd, IDC_EDIT_HRTF), values.hrtf_file);
set_text(GetDlgItem(m_hwnd, IDC_EDIT_FFMPEG), values.ffmpeg_path); set_text(GetDlgItem(m_hwnd, IDC_EDIT_FFMPEG), values.ffmpeg_path);
@@ -303,7 +408,33 @@ private:
values.gain_enabled ? BST_CHECKED : BST_UNCHECKED, 0); values.gain_enabled ? BST_CHECKED : BST_UNCHECKED, 0);
SendMessageW(GetDlgItem(m_hwnd, IDC_CHECK_INT24), BM_SETCHECK, SendMessageW(GetDlgItem(m_hwnd, IDC_CHECK_INT24), BM_SETCHECK,
values.force_int24 ? BST_CHECKED : BST_UNCHECKED, 0); values.force_int24 ? BST_CHECKED : BST_UNCHECKED, 0);
update_enabled_state(); SendMessageW(GetDlgItem(m_hwnd, IDC_CHECK_SWAP_SIDE_REAR), BM_SETCHECK,
values.swap_side_rear ? BST_CHECKED : BST_UNCHECKED, 0);
// The item lists are language-dependent, so they are built (in the stored
// language) before the selections are restored, and the texts are applied
// last: apply_texts() reads the language from the combo, so a selection set
// afterwards would leave the page in the other language.
const joc_lang::Language language = joc_lang::resolve(values.language);
fill_combo(GetDlgItem(m_hwnd, IDC_COMBO_LANGUAGE),
language_items(language), language_index(values.language));
fill_combo(GetDlgItem(m_hwnd, IDC_COMBO_MODE), mode_items(language),
static_cast<int>(mode_index(values.binaural_mode)));
std::size_t layout_count = 0;
const joc_decode::LayoutSpec* layouts = joc_decode::layout_table(&layout_count);
std::vector<std::string> names;
int layout_index = 0;
for (std::size_t i = 0; i < layout_count; ++i) {
names.emplace_back(layouts[i].name);
if (values.speaker_layout == layouts[i].name) {
layout_index = static_cast<int>(i);
}
}
// The list comes from the core-facing table, so the page cannot offer a
// layout the decoder rejects.
fill_combo(GetDlgItem(m_hwnd, IDC_COMBO_LAYOUT), names, layout_index);
apply_texts();
} }
joc_settings::Values read_controls() const { joc_settings::Values read_controls() const {
@@ -312,17 +443,15 @@ private:
const int layout_index = const int layout_index =
static_cast<int>(SendDlgItemMessageW(m_hwnd, IDC_COMBO_LAYOUT, CB_GETCURSEL, 0, 0)); static_cast<int>(SendDlgItemMessageW(m_hwnd, IDC_COMBO_LAYOUT, CB_GETCURSEL, 0, 0));
if (layout_index >= 0 && std::size_t layout_count = 0;
layout_index < static_cast<int>(sizeof(kLayoutChoices) / sizeof(kLayoutChoices[0]))) { const joc_decode::LayoutSpec* layouts = joc_decode::layout_table(&layout_count);
values.speaker_layout = kLayoutChoices[layout_index].name; if (layout_index >= 0 && static_cast<std::size_t>(layout_index) < layout_count) {
values.speaker_layout = layouts[layout_index].name;
} }
const int mode_sel = const int mode_sel =
static_cast<int>(SendDlgItemMessageW(m_hwnd, IDC_COMBO_MODE, CB_GETCURSEL, 0, 0)); static_cast<int>(SendDlgItemMessageW(m_hwnd, IDC_COMBO_MODE, CB_GETCURSEL, 0, 0));
values.binaural_mode = mode_value(mode_sel < 0 ? 2u : static_cast<unsigned>(mode_sel)); values.binaural_mode = mode_value(mode_sel < 0 ? 1u : static_cast<unsigned>(mode_sel));
values.hrtf_source = IsDlgButtonChecked(m_hwnd, IDC_RADIO_HRTF_ROSELLA) == BST_CHECKED
? joc_settings::HrtfSource::kRosella
: joc_settings::HrtfSource::kSofa;
values.hrtf_file = get_text(GetDlgItem(m_hwnd, IDC_EDIT_HRTF)); values.hrtf_file = get_text(GetDlgItem(m_hwnd, IDC_EDIT_HRTF));
values.ffmpeg_path = get_text(GetDlgItem(m_hwnd, IDC_EDIT_FFMPEG)); values.ffmpeg_path = get_text(GetDlgItem(m_hwnd, IDC_EDIT_FFMPEG));
values.tail_seconds = values.tail_seconds =
@@ -332,6 +461,9 @@ private:
IsDlgButtonChecked(m_hwnd, IDC_CHECK_GAIN) == BST_CHECKED; IsDlgButtonChecked(m_hwnd, IDC_CHECK_GAIN) == BST_CHECKED;
values.force_int24 = values.force_int24 =
IsDlgButtonChecked(m_hwnd, IDC_CHECK_INT24) == BST_CHECKED; IsDlgButtonChecked(m_hwnd, IDC_CHECK_INT24) == BST_CHECKED;
values.swap_side_rear =
IsDlgButtonChecked(m_hwnd, IDC_CHECK_SWAP_SIDE_REAR) == BST_CHECKED;
values.language = selected_language();
// Advanced values are not on this page; keep whatever is stored. // Advanced values are not on this page; keep whatever is stored.
const joc_settings::Values stored = joc_settings::read(); const joc_settings::Values stored = joc_settings::read();
values.object_delay_samples = stored.object_delay_samples; values.object_delay_samples = stored.object_delay_samples;
@@ -339,55 +471,49 @@ private:
return values; return values;
} }
// Nothing on this page is ever disabled: a greyed control reads as an option // Updates the lines that describe what is in effect. Nothing on this page is
// that cannot be used, and none of these settings is invalid in the other // disabled: a speaker layout chosen while binaural output is active simply has
// mode. A speaker layout chosen while binaural output is active simply has no // no effect until the output is switched back, and the status line says which
// effect until the output is switched back, and the gain field describes what // layout and how many channels that would be.
// the switch would apply. What is in effect is stated in the status line.
void update_enabled_state() { update_status(); }
void update_status() { void update_status() {
const joc_lang::Language language = joc_lang::resolve(selected_language());
const joc_settings::Values values = read_controls(); const joc_settings::Values values = read_controls();
std::string output_status; std::string output_status;
if (values.output != 0) { if (values.output != 0) {
char text[96] = {}; char text[192] = {};
const unsigned channels = joc_decode::speaker_channels(values.speaker_layout); std::snprintf(text, sizeof(text),
std::snprintf(text, sizeof(text), "扬声器布局 %s(%u 声道)", joc_lang::get(language, joc_lang::Text::kSpeakerStatus),
values.speaker_layout.c_str(), channels); values.speaker_layout.c_str());
output_status = text; output_status = text;
} }
set_text(GetDlgItem(m_hwnd, IDC_LABEL_OUTPUT_STATUS), output_status); set_text(GetDlgItem(m_hwnd, IDC_LABEL_OUTPUT_STATUS), output_status);
// The hint says what the switch does and what the other state means: the
// renderer is float32 either way, so "24bit" is about the delivery, and
// that is not something a checkbox label can carry on its own. The second
// half matters because this switch changes what the component *reports*
// about a file, and foobar2000 caches that per file: an item whose
// information was read before the switch was flipped keeps the old format
// until it is reloaded.
set_text(GetDlgItem(m_hwnd, IDC_LABEL_INT24_HINT),
values.force_int24
? "开启:量化到 int24,超出 ±1 截断;切换后需刷新文件信息"
: "关闭:按 32 位浮点交付(默认)");
joc_decode::Settings effective = joc_settings::current(); joc_decode::Settings effective = joc_settings::current();
effective.hrtf_source =
static_cast<joc_decode::HrtfSource>(values.hrtf_source);
effective.hrtf_file = values.hrtf_file; effective.hrtf_file = values.hrtf_file;
const std::string file = joc_decode::resolve_hrtf_file(effective); const std::string file = joc_decode::resolve_hrtf_file(effective);
std::string hrtf_status = std::string hrtf_status = joc_lang::get(language, joc_lang::Text::kHrtfSourceRosella);
std::string(joc_settings::hrtf_source_name(values.hrtf_source)) + ":"; hrtf_status += joc_lang::get(language, joc_lang::Text::kSeparator);
if (values.hrtf_file.empty()) hrtf_status += "默认"; if (values.hrtf_file.empty()) {
hrtf_status += "\n" + hrtf_status += joc_lang::get(language, joc_lang::Text::kHrtfDefault);
(file.empty() ? std::string("无法确定默认路径") : file); }
hrtf_status += "\n";
if (file.empty()) {
hrtf_status += joc_lang::get(language, joc_lang::Text::kHrtfDefaultUnknown);
} else {
RECT status_rect{};
GetClientRect(GetDlgItem(m_hwnd, IDC_LABEL_STATUS), &status_rect);
hrtf_status += elide_path(GetDlgItem(m_hwnd, IDC_LABEL_STATUS), file,
status_rect.right - 4);
}
set_text(GetDlgItem(m_hwnd, IDC_LABEL_STATUS), hrtf_status); set_text(GetDlgItem(m_hwnd, IDC_LABEL_STATUS), hrtf_status);
char gain[96] = {}; char gain[96] = {};
if (values.gain_enabled) { std::snprintf(
std::snprintf(gain, sizeof(gain), "增益开 %.2f dB", values.gain_db); gain, sizeof(gain),
} else { joc_lang::get(language, values.gain_enabled ? joc_lang::Text::kGainStatusOn
std::snprintf(gain, sizeof(gain), "增益关(输出不衰减)"); : joc_lang::Text::kGainStatusOff),
} values.gain_db);
set_text(GetDlgItem(m_hwnd, IDC_LABEL_GAIN_STATUS), gain); set_text(GetDlgItem(m_hwnd, IDC_LABEL_GAIN_STATUS), gain);
} }
@@ -395,14 +521,15 @@ private:
const joc_settings::Values now = read_controls(); const joc_settings::Values now = read_controls();
if (now.output != m_initial.output) return true; if (now.output != m_initial.output) return true;
if (now.speaker_layout != m_initial.speaker_layout) return true; if (now.speaker_layout != m_initial.speaker_layout) return true;
if (now.hrtf_source != m_initial.hrtf_source) return true;
if (now.hrtf_file != m_initial.hrtf_file) return true; if (now.hrtf_file != m_initial.hrtf_file) return true;
if (now.binaural_mode != m_initial.binaural_mode) return true; if (now.binaural_mode != m_initial.binaural_mode) return true;
if (now.gain_enabled != m_initial.gain_enabled) return true; if (now.gain_enabled != m_initial.gain_enabled) return true;
if (now.force_int24 != m_initial.force_int24) return true; if (now.force_int24 != m_initial.force_int24) return true;
if (now.swap_side_rear != m_initial.swap_side_rear) return true;
if (now.gain_db != m_initial.gain_db) return true; if (now.gain_db != m_initial.gain_db) return true;
if (now.tail_seconds != m_initial.tail_seconds) return true; if (now.tail_seconds != m_initial.tail_seconds) return true;
if (now.ffmpeg_path != m_initial.ffmpeg_path) return true; if (now.ffmpeg_path != m_initial.ffmpeg_path) return true;
if (now.language != m_initial.language) return true;
return false; return false;
} }
@@ -450,12 +577,19 @@ private:
class prefs_page : public preferences_page_v3 { class prefs_page : public preferences_page_v3 {
public: public:
const char* get_name() override { return "JOC 解码器"; } // The page name follows the language setting; foobar2000 asks for it when it
// builds the tree, so a change shows up the next time the page is opened.
const char* get_name() override {
static std::string name;
name = joc_lang::get(joc_lang::resolve(joc_settings::read().language),
joc_lang::Text::kPageName);
return name.c_str();
}
GUID get_guid() override { return kPrefsGuid; } GUID get_guid() override { return kPrefsGuid; }
GUID get_parent_guid() override { return preferences_page::guid_tools; } GUID get_parent_guid() override { return preferences_page::guid_tools; }
preferences_page_instance::ptr instantiate(HWND parent, preferences_page_instance::ptr instantiate(HWND parent,
preferences_page_callback::ptr callback) override { preferences_page_callback::ptr callback) override {
return fb2k::service_new<prefs_instance>(parent, callback); return fb2k::service_new<prefs_instance>(parent, callback);
} }
}; };
+45 -34
View File
@@ -7,51 +7,62 @@
// sample page uses (SDK\foobar2000\foo_sample\foo_sample.rc). A CAPTION statement // sample page uses (SDK\foobar2000\foo_sample\foo_sample.rc). A CAPTION statement
// implies WS_CAPTION, which would draw a second frame inside the host's and shift // implies WS_CAPTION, which would draw a second frame inside the host's and shift
// every control down by the caption height -- visible but not clickable. // every control down by the caption height -- visible but not clickable.
IDD_JOC_PREFS DIALOGEX 0, 0, 330, 299 //
// The height is capped by what the host gives the page: it sizes the page window to
// its own area and clips anything below it, without a scrollbar, so a page that is
// too tall silently loses its lower groups. 268 dialog units keeps every group
// inside the area at 96 and 125 percent scaling; tests/ui_text_fit_test.cpp fails
// if the dialog grows past that.
//
// The texts below are the Chinese ones; the page replaces every one of them at
// start-up with the string for the selected language (src/lang.cpp). Each control
// is therefore as wide as the wider of its two texts.
IDD_JOC_PREFS DIALOGEX 0, 0, 330, 268
STYLE DS_SETFONT | WS_CHILD STYLE DS_SETFONT | WS_CHILD
FONT 8, "Microsoft Sans Serif", 400, 0, 0x0 FONT 8, "Microsoft Sans Serif", 400, 0, 0x0
BEGIN BEGIN
GROUPBOX "输出", IDC_GROUP_OUTPUT, 7, 5, 316, 86 GROUPBOX "输出", IDC_GROUP_OUTPUT, 7, 4, 316, 72
CONTROL "双耳(HRTF)", IDC_RADIO_BINAURAL, "Button", CONTROL "双耳(HRTF)", IDC_RADIO_BINAURAL, "Button",
BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 16, 20, 72, 10 BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 16, 15, 92, 10
CONTROL "扬声器布局", IDC_RADIO_SPEAKER, "Button", CONTROL "扬声器布局", IDC_RADIO_SPEAKER, "Button",
BS_AUTORADIOBUTTON | WS_TABSTOP, 16, 38, 60, 10 BS_AUTORADIOBUTTON | WS_TABSTOP, 16, 28, 84, 10
LTEXT "布局", IDC_LABEL_LAYOUT, 80, 39, 22, 10 COMBOBOX IDC_COMBO_LAYOUT, 104, 25, 110, 160,
COMBOBOX IDC_COMBO_LAYOUT, 104, 36, 60, 120,
CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP
LTEXT "双耳模式", IDC_LABEL_MODE, 172, 22, 42, 10 LTEXT "双耳模式", IDC_LABEL_MODE, 16, 41, 66, 10
COMBOBOX IDC_COMBO_MODE, 216, 19, 96, 90, COMBOBOX IDC_COMBO_MODE, 86, 38, 92, 90,
CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP
LTEXT "房间尾音(秒)", IDC_LABEL_TAIL, 172, 41, 62, 10 LTEXT "房间尾音(秒)", IDC_LABEL_TAIL, 184, 41, 58, 10
EDITTEXT IDC_EDIT_TAIL, 238, 38, 40, 13, ES_AUTOHSCROLL EDITTEXT IDC_EDIT_TAIL, 246, 38, 40, 13, ES_AUTOHSCROLL
LTEXT "", IDC_LABEL_OUTPUT_STATUS, 16, 52, 300, 10 LTEXT "", IDC_LABEL_OUTPUT_STATUS, 16, 53, 300, 10
CONTROL "强制 24bit 输出(int24)", IDC_CHECK_INT24, "Button", CONTROL "强制 24bit 输出(int24)", IDC_CHECK_INT24, "Button",
BS_AUTOCHECKBOX | WS_TABSTOP, 16, 64, 116, 10 BS_AUTOCHECKBOX | WS_TABSTOP, 16, 65, 156, 10
LTEXT "", IDC_LABEL_INT24_HINT, 16, 76, 300, 10 LTEXT "切换后需刷新文件信息", IDC_LABEL_INT24_HINT, 176, 65, 136, 10
GROUPBOX "HRTF", IDC_GROUP_HRTF, 7, 97, 316, 100 GROUPBOX "HRTF", IDC_GROUP_HRTF, 7, 79, 316, 92
CONTROL "SOFA 文件", IDC_RADIO_HRTF_SOFA, "Button", LTEXT "Rosella 个性化模型", IDC_RADIO_HRTF_ROSELLA, 16, 91, 146, 10
BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 16, 112, 56, 10 LTEXT "HRTF 文件", IDC_LABEL_HRTF, 16, 106, 40, 10
CONTROL "Rosella 个性化模型", IDC_RADIO_HRTF_ROSELLA, "Button", EDITTEXT IDC_EDIT_HRTF, 58, 103, 186, 13, ES_AUTOHSCROLL
BS_AUTORADIOBUTTON | WS_TABSTOP, 78, 112, 78, 10 PUSHBUTTON "浏览…", IDC_BROWSE_HRTF, 248, 103, 52, 13
LTEXT "HRTF 文件(留空=默认位置)", IDC_LABEL_HRTF, 16, 131, 106, 10 LTEXT "留空时读组件目录下 HRTF\\binaural.personalized_headphone。",
EDITTEXT IDC_EDIT_HRTF, 126, 128, 148, 13, ES_AUTOHSCROLL IDC_LABEL_HRTF_HINT, 16, 121, 300, 20
PUSHBUTTON "浏览…", IDC_BROWSE_HRTF, 279, 128, 38, 13 LTEXT "", IDC_LABEL_STATUS, 16, 143, 300, 20
LTEXT "留空时读组件目录下 HRTF\\binaural.sofa 或 binaural.personalized_headphone;SOFA 由渲染器内部编译,滤波组表已编入库中。",
IDC_LABEL_HRTF_HINT, 16, 147, 300, 20
LTEXT "", IDC_LABEL_STATUS, 16, 171, 300, 20
GROUPBOX "增益", IDC_GROUP_GAIN, 7, 202, 316, 48 GROUPBOX "增益", IDC_GROUP_GAIN, 7, 174, 316, 42
CONTROL "应用增益", IDC_CHECK_GAIN, "Button", CONTROL "应用增益", IDC_CHECK_GAIN, "Button",
BS_AUTOCHECKBOX | WS_TABSTOP, 16, 218, 58, 10 BS_AUTOCHECKBOX | WS_TABSTOP, 16, 187, 48, 10
LTEXT "dB", IDC_LABEL_GAIN, 80, 218, 12, 10 LTEXT "dB", IDC_LABEL_GAIN, 68, 187, 12, 10
EDITTEXT IDC_EDIT_GAIN, 96, 215, 40, 13, ES_AUTOHSCROLL EDITTEXT IDC_EDIT_GAIN, 84, 184, 44, 13, ES_AUTOHSCROLL
LTEXT "", IDC_LABEL_GAIN_STATUS, 145, 218, 171, 10 LTEXT "", IDC_LABEL_GAIN_STATUS, 134, 187, 182, 10
LTEXT "双耳渲染后可能超过 0 dBFS,可用负值衰减。", LTEXT "双耳渲染后可能超过 0 dBFS,可用负值衰减。",
IDC_LABEL_GAIN_HINT, 16, 234, 300, 10 IDC_LABEL_GAIN_HINT, 16, 202, 300, 10
GROUPBOX "其它", IDC_GROUP_MISC, 7, 255, 316, 38 GROUPBOX "其它", IDC_GROUP_MISC, 7, 219, 316, 48
LTEXT "ffmpeg.exe", IDC_LABEL_FFMPEG, 16, 271, 44, 10 CONTROL "交换侧环绕与后环绕声道", IDC_CHECK_SWAP_SIDE_REAR, "Button",
EDITTEXT IDC_EDIT_FFMPEG, 64, 268, 210, 13, ES_AUTOHSCROLL BS_AUTOCHECKBOX | WS_TABSTOP, 176, 232, 140, 10
PUSHBUTTON "浏览…", IDC_BROWSE_FFMPEG, 279, 268, 38, 13 LTEXT "界面语言", IDC_LABEL_LANGUAGE, 16, 232, 34, 10
COMBOBOX IDC_COMBO_LANGUAGE, 52, 229, 110, 90,
CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP
LTEXT "ffmpeg.exe", IDC_LABEL_FFMPEG, 16, 252, 50, 10
EDITTEXT IDC_EDIT_FFMPEG, 70, 249, 176, 13, ES_AUTOHSCROLL
PUSHBUTTON "浏览…", IDC_BROWSE_FFMPEG, 250, 249, 50, 13
END END
+3 -1
View File
@@ -7,7 +7,6 @@
#define IDC_RADIO_BINAURAL 2011 #define IDC_RADIO_BINAURAL 2011
#define IDC_RADIO_SPEAKER 2012 #define IDC_RADIO_SPEAKER 2012
#define IDC_COMBO_LAYOUT 2013 #define IDC_COMBO_LAYOUT 2013
#define IDC_LABEL_LAYOUT 2014
#define IDC_LABEL_MODE 2015 #define IDC_LABEL_MODE 2015
#define IDC_COMBO_MODE 2016 #define IDC_COMBO_MODE 2016
#define IDC_LABEL_TAIL 2017 #define IDC_LABEL_TAIL 2017
@@ -20,6 +19,7 @@
#define IDC_GROUP_HRTF 2020 #define IDC_GROUP_HRTF 2020
#define IDC_RADIO_HRTF_SOFA 2021 #define IDC_RADIO_HRTF_SOFA 2021
#define IDC_RADIO_HRTF_ROSELLA 2022 #define IDC_RADIO_HRTF_ROSELLA 2022
#define IDC_CHECK_SWAP_SIDE_REAR 2023
#define IDC_LABEL_HRTF 2024 #define IDC_LABEL_HRTF 2024
#define IDC_EDIT_HRTF 2025 #define IDC_EDIT_HRTF 2025
#define IDC_BROWSE_HRTF 2026 #define IDC_BROWSE_HRTF 2026
@@ -37,3 +37,5 @@
#define IDC_EDIT_FFMPEG 2042 #define IDC_EDIT_FFMPEG 2042
#define IDC_BROWSE_FFMPEG 2043 #define IDC_BROWSE_FFMPEG 2043
#define IDC_LABEL_STATUS 2044 #define IDC_LABEL_STATUS 2044
#define IDC_LABEL_LANGUAGE 2045
#define IDC_COMBO_LANGUAGE 2046
+50 -29
View File
@@ -6,6 +6,7 @@
#include <windows.h> #include <windows.h>
#include <atomic>
#include <cstddef> #include <cstddef>
#include <cstdio> #include <cstdio>
#include <cstdlib> #include <cstdlib>
@@ -23,20 +24,19 @@ constexpr GUID kGuidLayout = {0x7b62e5d1, 0x14a8, 0x4c07, {0x83, 0x2f, 0x6b, 0x9
// Reused from the previous build, where it stored the .jochrtf path: it still // Reused from the previous build, where it stored the .jochrtf path: it still
// holds "the HRTF file", so the meaning is unchanged for anyone upgrading. // holds "the HRTF file", so the meaning is unchanged for anyone upgrading.
constexpr GUID kGuidHrtfFile = {0x4e8a1f36, 0x2c95, 0x47d0, {0xb1, 0x68, 0x3e, 0xa2, 0x77, 0x09, 0xf5, 0x8c}}; constexpr GUID kGuidHrtfFile = {0x4e8a1f36, 0x2c95, 0x47d0, {0xb1, 0x68, 0x3e, 0xa2, 0x77, 0x09, 0xf5, 0x8c}};
constexpr GUID kGuidHrtfSource = {0xa3d51b72, 0x6f48, 0x4c19, {0x9e, 0x04, 0x2b, 0x87, 0xd1, 0x53, 0x6a, 0x20}};
constexpr GUID kGuidBinauralMode = {0x1a57c9e4, 0x83b6, 0x42f1, {0x9c, 0x50, 0x24, 0xfd, 0x6a, 0x18, 0x73, 0x0e}}; constexpr GUID kGuidBinauralMode = {0x1a57c9e4, 0x83b6, 0x42f1, {0x9c, 0x50, 0x24, 0xfd, 0x6a, 0x18, 0x73, 0x0e}};
constexpr GUID kGuidGainEnabled = {0x74b1e5c8, 0x2a39, 0x4d16, {0x8f, 0x62, 0x0d, 0x51, 0xb7, 0x3c, 0x9a, 0x28}}; constexpr GUID kGuidGainEnabled = {0x74b1e5c8, 0x2a39, 0x4d16, {0x8f, 0x62, 0x0d, 0x51, 0xb7, 0x3c, 0x9a, 0x28}};
constexpr GUID kGuidGain = {0x6c04d8b2, 0xe75f, 0x4a39, {0x8d, 0x26, 0x51, 0xb3, 0xc8, 0x40, 0x9e, 0x27}}; constexpr GUID kGuidGain = {0x6c04d8b2, 0xe75f, 0x4a39, {0x8d, 0x26, 0x51, 0xb3, 0xc8, 0x40, 0x9e, 0x27}};
constexpr GUID kGuidTail = {0x38f1b6a7, 0x0d24, 0x4e88, {0xb7, 0x95, 0x2c, 0x61, 0x4f, 0xd2, 0x08, 0xa3}}; constexpr GUID kGuidTail = {0x38f1b6a7, 0x0d24, 0x4e88, {0xb7, 0x95, 0x2c, 0x61, 0x4f, 0xd2, 0x08, 0xa3}};
constexpr GUID kGuidForceInt24 = {0xd2c67f41, 0x8b53, 0x4a2e, {0x97, 0x61, 0x0f, 0xc8, 0x35, 0xba, 0x64, 0x12}}; constexpr GUID kGuidForceInt24 = {0xd2c67f41, 0x8b53, 0x4a2e, {0x97, 0x61, 0x0f, 0xc8, 0x35, 0xba, 0x64, 0x12}};
constexpr GUID kGuidSwapSideRear = {0x2b7f6d18, 0x59c4, 0x4a83, {0x8e, 0x15, 0x73, 0xac, 0x06, 0xd9, 0x4b, 0x27}};
constexpr GUID kGuidObjectDelay = {0x5b2e9c18, 0xa640, 0x4d7b, {0x92, 0x0e, 0x37, 0xc5, 0x81, 0x6b, 0x2a, 0x54}}; constexpr GUID kGuidObjectDelay = {0x5b2e9c18, 0xa640, 0x4d7b, {0x92, 0x0e, 0x37, 0xc5, 0x81, 0x6b, 0x2a, 0x54}};
constexpr GUID kGuidThreads = {0xcb7a4015, 0x3f98, 0x4c62, {0xa0, 0x8d, 0x1b, 0x74, 0x29, 0xe6, 0x53, 0x0f}}; constexpr GUID kGuidThreads = {0xcb7a4015, 0x3f98, 0x4c62, {0xa0, 0x8d, 0x1b, 0x74, 0x29, 0xe6, 0x53, 0x0f}};
constexpr GUID kGuidFfmpeg = {0x0e9d37c2, 0x5a18, 0x4b40, {0xb6, 0x3f, 0x88, 0x2d, 0x9a, 0x70, 0x1c, 0x65}}; constexpr GUID kGuidFfmpeg = {0x0e9d37c2, 0x5a18, 0x4b40, {0xb6, 0x3f, 0x88, 0x2d, 0x9a, 0x70, 0x1c, 0x65}};
constexpr GUID kGuidLanguage = {0x58e17a04, 0x3d92, 0x4f6b, {0xa1, 0x27, 0x94, 0xc8, 0x0b, 0x6d, 0x53, 0xe1}};
cfg_uint g_output(kGuidOutput, 0); cfg_uint g_output(kGuidOutput, 0);
cfg_string g_layout(kGuidLayout, "7.1"); cfg_string g_layout(kGuidLayout, "7.1");
// 0 = SOFA, 1 = Rosella model, 2 = compiled .jochrtf (advanced) // 0 = SOFA, 1 = Rosella model, 2 = compiled .jochrtf (advanced)
cfg_uint g_hrtf_source(kGuidHrtfSource, 0);
cfg_string g_hrtf_file(kGuidHrtfFile, ""); cfg_string g_hrtf_file(kGuidHrtfFile, "");
cfg_uint g_binaural_mode(kGuidBinauralMode, 3); cfg_uint g_binaural_mode(kGuidBinauralMode, 3);
cfg_bool g_gain_enabled(kGuidGainEnabled, true); cfg_bool g_gain_enabled(kGuidGainEnabled, true);
@@ -46,9 +46,13 @@ cfg_int g_gain_mdb(kGuidGain, 0);
cfg_uint g_tail_ms(kGuidTail, 5000); cfg_uint g_tail_ms(kGuidTail, 5000);
// Deliver int24 instead of float32. // Deliver int24 instead of float32.
cfg_bool g_force_int24(kGuidForceInt24, false); cfg_bool g_force_int24(kGuidForceInt24, false);
// Swap the side and rear surround pairs in the delivered PCM.
cfg_bool g_swap_side_rear(kGuidSwapSideRear, false);
cfg_uint g_object_delay(kGuidObjectDelay, 1473); cfg_uint g_object_delay(kGuidObjectDelay, 1473);
cfg_uint g_threads(kGuidThreads, 0); cfg_uint g_threads(kGuidThreads, 0);
cfg_string g_ffmpeg(kGuidFfmpeg, "ffmpeg"); cfg_string g_ffmpeg(kGuidFfmpeg, "ffmpeg");
// 0 = follow the Windows user-interface language, 1 = Chinese, 2 = English.
cfg_uint g_language(kGuidLanguage, 0);
// Appends an optional trailing field to one of the fixed describe() buffers, so a // Appends an optional trailing field to one of the fixed describe() buffers, so a
// setting that is off leaves the line exactly as it was. // setting that is off leaves the line exactly as it was.
@@ -96,18 +100,7 @@ bool env_string(const char* name, std::string* out) {
namespace joc_settings { namespace joc_settings {
const char* hrtf_source_name(HrtfSource source) { const char* hrtf_default_file_name() { return "binaural.personalized_headphone"; }
return source == HrtfSource::kRosella ? "Rosella 个性化模型" : "SOFA";
}
const char* hrtf_source_extension(HrtfSource source) {
return source == HrtfSource::kRosella ? "personalized_headphone" : "sofa";
}
const char* hrtf_default_file_name(HrtfSource source) {
return source == HrtfSource::kRosella ? "binaural.personalized_headphone"
: "binaural.sofa";
}
Values defaults() { return Values(); } Values defaults() { return Values(); }
@@ -115,35 +108,60 @@ Values read() {
Values values; Values values;
values.output = static_cast<int>(static_cast<unsigned>(g_output)); values.output = static_cast<int>(static_cast<unsigned>(g_output));
values.speaker_layout = g_layout.get_ptr(); values.speaker_layout = g_layout.get_ptr();
if (values.speaker_layout.empty()) values.speaker_layout = "7.1"; // A layout the core does not accept (an old build offered several it never
const unsigned source = static_cast<unsigned>(g_hrtf_source); // accepted) would fail when the renderer is created, and the page cannot show it
values.hrtf_source = (source == 1u) ? HrtfSource::kRosella : HrtfSource::kSofa; // either, because its list is the core's own table. Falling back here makes the
// stored value usable again and the page show what will actually be rendered.
if (joc_decode::speaker_channels(values.speaker_layout) == 0) {
static std::atomic<bool> warned{false};
if (!warned.exchange(true, std::memory_order_relaxed)) {
joc_log::line("settings: stored speaker layout \"%s\" is not one the core "
"accepts; using 7.1",
values.speaker_layout.c_str());
}
values.speaker_layout = "7.1";
}
values.hrtf_file = g_hrtf_file.get_ptr(); values.hrtf_file = g_hrtf_file.get_ptr();
values.binaural_mode = static_cast<unsigned>(g_binaural_mode); values.binaural_mode = static_cast<unsigned>(g_binaural_mode);
values.gain_enabled = static_cast<bool>(g_gain_enabled); values.gain_enabled = static_cast<bool>(g_gain_enabled);
values.gain_db = static_cast<double>(static_cast<long long>(g_gain_mdb)) / 1000.0; values.gain_db = static_cast<double>(static_cast<long long>(g_gain_mdb)) / 1000.0;
values.tail_seconds = static_cast<double>(static_cast<unsigned>(g_tail_ms)) / 1000.0; values.tail_seconds = static_cast<double>(static_cast<unsigned>(g_tail_ms)) / 1000.0;
values.force_int24 = static_cast<bool>(g_force_int24); values.force_int24 = static_cast<bool>(g_force_int24);
values.swap_side_rear = static_cast<bool>(g_swap_side_rear);
values.object_delay_samples = static_cast<unsigned>(g_object_delay); values.object_delay_samples = static_cast<unsigned>(g_object_delay);
values.native_threads = static_cast<unsigned>(g_threads); values.native_threads = static_cast<unsigned>(g_threads);
values.ffmpeg_path = g_ffmpeg.get_ptr(); values.ffmpeg_path = g_ffmpeg.get_ptr();
if (values.ffmpeg_path.empty()) values.ffmpeg_path = "ffmpeg"; if (values.ffmpeg_path.empty()) values.ffmpeg_path = "ffmpeg";
const unsigned language = static_cast<unsigned>(g_language);
values.language = language <= 2u ? static_cast<joc_lang::Language>(language)
: joc_lang::Language::kSystem;
// The page and the messages both read this far, so the development override
// lives here rather than in current(), where only the decoder would see it.
std::string text;
if (env_string("JOC_LANGUAGE", &text)) {
values.language = (text == "en" || text == "english")
? joc_lang::Language::kEnglish
: (text == "zh" || text == "chinese")
? joc_lang::Language::kChineseSimplified
: joc_lang::Language::kSystem;
}
return values; return values;
} }
void write(const Values& values) { void write(const Values& values) {
g_output = static_cast<unsigned>(values.output); g_output = static_cast<unsigned>(values.output);
g_layout = values.speaker_layout.c_str(); g_layout = values.speaker_layout.c_str();
g_hrtf_source = static_cast<unsigned>(values.hrtf_source);
g_hrtf_file = values.hrtf_file.c_str(); g_hrtf_file = values.hrtf_file.c_str();
g_binaural_mode = values.binaural_mode; g_binaural_mode = values.binaural_mode;
g_gain_enabled = values.gain_enabled; g_gain_enabled = values.gain_enabled;
g_gain_mdb = static_cast<long long>(values.gain_db * 1000.0 + (values.gain_db >= 0 ? 0.5 : -0.5)); g_gain_mdb = static_cast<long long>(values.gain_db * 1000.0 + (values.gain_db >= 0 ? 0.5 : -0.5));
g_tail_ms = static_cast<unsigned>(values.tail_seconds * 1000.0 + 0.5); g_tail_ms = static_cast<unsigned>(values.tail_seconds * 1000.0 + 0.5);
g_force_int24 = values.force_int24; g_force_int24 = values.force_int24;
g_swap_side_rear = values.swap_side_rear;
g_object_delay = values.object_delay_samples; g_object_delay = values.object_delay_samples;
g_threads = values.native_threads; g_threads = values.native_threads;
g_ffmpeg = values.ffmpeg_path.c_str(); g_ffmpeg = values.ffmpeg_path.c_str();
g_language = static_cast<unsigned>(values.language);
} }
joc_decode::Settings current() { joc_decode::Settings current() {
@@ -151,11 +169,8 @@ joc_decode::Settings current() {
std::string text; std::string text;
if (env_string("JOC_OUTPUT", &text)) values.output = (text == "speaker") ? 1 : 0; if (env_string("JOC_OUTPUT", &text)) values.output = (text == "speaker") ? 1 : 0;
(void)env_string("JOC_LAYOUT", &values.speaker_layout); if (env_string("JOC_LAYOUT", &text)) values.speaker_layout = text;
(void)env_string("JOC_HRTF", &values.hrtf_file); (void)env_string("JOC_HRTF", &values.hrtf_file);
if (env_string("JOC_HRTF_SOURCE", &text)) {
values.hrtf_source = (text == "rosella") ? HrtfSource::kRosella : HrtfSource::kSofa;
}
(void)env_string("JOC_FFMPEG", &values.ffmpeg_path); (void)env_string("JOC_FFMPEG", &values.ffmpeg_path);
if (env_string("JOC_BINAURAL_MODE", &text)) { if (env_string("JOC_BINAURAL_MODE", &text)) {
values.binaural_mode = (text == "near") ? 1u : (text == "far") ? 2u : 3u; values.binaural_mode = (text == "near") ? 1u : (text == "far") ? 2u : 3u;
@@ -164,6 +179,7 @@ joc_decode::Settings current() {
if (env_string("JOC_GAIN_ENABLED", &text)) values.gain_enabled = (text != "0"); if (env_string("JOC_GAIN_ENABLED", &text)) values.gain_enabled = (text != "0");
(void)env_double("JOC_TAIL_SECONDS", &values.tail_seconds); (void)env_double("JOC_TAIL_SECONDS", &values.tail_seconds);
if (env_string("JOC_FORCE_INT24", &text)) values.force_int24 = (text != "0"); if (env_string("JOC_FORCE_INT24", &text)) values.force_int24 = (text != "0");
if (env_string("JOC_SWAP_SIDE_REAR", &text)) values.swap_side_rear = (text != "0");
(void)env_uint("JOC_OBJECT_DELAY", &values.object_delay_samples); (void)env_uint("JOC_OBJECT_DELAY", &values.object_delay_samples);
(void)env_uint("JOC_THREADS", &values.native_threads); (void)env_uint("JOC_THREADS", &values.native_threads);
@@ -171,7 +187,6 @@ joc_decode::Settings current() {
settings.output = settings.output =
(values.output == 0) ? joc_decode::Output::kBinaural : joc_decode::Output::kSpeaker; (values.output == 0) ? joc_decode::Output::kBinaural : joc_decode::Output::kSpeaker;
settings.speaker_layout = values.speaker_layout; settings.speaker_layout = values.speaker_layout;
settings.hrtf_source = static_cast<joc_decode::HrtfSource>(values.hrtf_source);
settings.hrtf_file = values.hrtf_file; settings.hrtf_file = values.hrtf_file;
settings.binaural_mode = values.binaural_mode; settings.binaural_mode = values.binaural_mode;
// The switch is explicit rather than implied by the value: binaural rendering // The switch is explicit rather than implied by the value: binaural rendering
@@ -180,6 +195,7 @@ joc_decode::Settings current() {
settings.gain_db = values.gain_enabled ? values.gain_db : 0.0; settings.gain_db = values.gain_enabled ? values.gain_db : 0.0;
settings.tail_seconds = values.tail_seconds; settings.tail_seconds = values.tail_seconds;
settings.force_int24 = values.force_int24; settings.force_int24 = values.force_int24;
settings.swap_side_rear = values.swap_side_rear;
settings.object_delay_samples = values.object_delay_samples; settings.object_delay_samples = values.object_delay_samples;
settings.native_threads = values.native_threads; settings.native_threads = values.native_threads;
settings.ffmpeg_path = values.ffmpeg_path.empty() ? "ffmpeg" : values.ffmpeg_path; settings.ffmpeg_path = values.ffmpeg_path.empty() ? "ffmpeg" : values.ffmpeg_path;
@@ -190,9 +206,8 @@ std::string describe(const joc_decode::Settings& settings) {
char text[640] = {}; char text[640] = {};
if (settings.output == joc_decode::Output::kBinaural) { if (settings.output == joc_decode::Output::kBinaural) {
std::snprintf(text, sizeof(text), std::snprintf(text, sizeof(text),
"binaural, hrtf=%s(%s), mode=%u, gain=%.2f dB, tail=%.2f s, delay=%u, " "binaural, hrtf=%s, mode=%u, gain=%.2f dB, tail=%.2f s, delay=%u, "
"threads=%u, ffmpeg=%s", "threads=%u, ffmpeg=%s",
hrtf_source_name(static_cast<HrtfSource>(settings.hrtf_source)),
settings.hrtf_file.empty() ? "(默认位置)" : settings.hrtf_file.c_str(), settings.hrtf_file.empty() ? "(默认位置)" : settings.hrtf_file.c_str(),
settings.binaural_mode, settings.gain_db, settings.tail_seconds, settings.binaural_mode, settings.gain_db, settings.tail_seconds,
settings.object_delay_samples, settings.native_threads, settings.object_delay_samples, settings.native_threads,
@@ -209,20 +224,26 @@ std::string describe(const joc_decode::Settings& settings) {
// Stated only when it is not the default, so a default log line reads as it // Stated only when it is not the default, so a default log line reads as it
// always did. // always did.
append_to(text, settings.force_int24 ? ", int24=forced" : ""); append_to(text, settings.force_int24 ? ", int24=forced" : "");
append_to(text, settings.swap_side_rear ? ", swap=side/rear" : "");
return text; return text;
} }
std::string describe(const Values& values) { std::string describe(const Values& values) {
char text[640] = {}; char text[640] = {};
std::snprintf(text, sizeof(text), std::snprintf(text, sizeof(text),
"output=%d layout=%s hrtf=%s(%s) mode=%u gain=%s%.2f dB tail=%.2f s delay=%u " "output=%d layout=%s hrtf=%s mode=%u gain=%s%.2f dB tail=%.2f s delay=%u "
"threads=%u ffmpeg=\"%s\"", "threads=%u ffmpeg=\"%s\"",
values.output, values.speaker_layout.c_str(), values.output, values.speaker_layout.c_str(), values.hrtf_file.c_str(),
hrtf_source_name(values.hrtf_source), values.hrtf_file.c_str(),
values.binaural_mode, values.gain_enabled ? "" : "(off) ", values.gain_db, values.binaural_mode, values.gain_enabled ? "" : "(off) ", values.gain_db,
values.tail_seconds, values.object_delay_samples, values.native_threads, values.tail_seconds, values.object_delay_samples, values.native_threads,
values.ffmpeg_path.c_str()); values.ffmpeg_path.c_str());
append_to(text, values.force_int24 ? " int24=forced" : ""); append_to(text, values.force_int24 ? " int24=forced" : "");
append_to(text, values.swap_side_rear ? " swap=side/rear" : "");
append_to(text, values.language == joc_lang::Language::kSystem
? " language=system"
: (values.language == joc_lang::Language::kEnglish
? " language=english"
: " language=chinese"));
return text; return text;
} }
+9 -12
View File
@@ -13,27 +13,18 @@
#include <string> #include <string>
#include "joc_decode.h" #include "joc_decode.h"
#include "lang.h"
namespace joc_settings { namespace joc_settings {
// Which HRTF the binaural renderer uses. Only these two inputs exist: everything
// else (compiling a SOFA into the renderer's field, caching it) is internal.
enum class HrtfSource {
kSofa = 0, // SOFA SimpleFreeFieldHRIR, compiled by the renderer
kRosella = 1, // Rosella .personalized_headphone model
};
const char* hrtf_source_name(HrtfSource source);
const char* hrtf_source_extension(HrtfSource source);
// The file looked up in the default folder (next to the component) when no path // The file looked up in the default folder (next to the component) when no path
// is configured; same names the reference CLI uses. // is configured; same name the reference CLI uses.
const char* hrtf_default_file_name(HrtfSource source); const char* hrtf_default_file_name();
// The stored values, exactly as the preferences page shows them. // The stored values, exactly as the preferences page shows them.
struct Values { struct Values {
int output = 0; // 0 = binaural, 1 = speaker layout int output = 0; // 0 = binaural, 1 = speaker layout
std::string speaker_layout = "7.1"; std::string speaker_layout = "7.1";
HrtfSource hrtf_source = HrtfSource::kSofa;
// Empty means "the default file in the default folder". // Empty means "the default file in the default folder".
std::string hrtf_file; std::string hrtf_file;
unsigned binaural_mode = 3; // JOC_BINAURAL_NEAR/FAR/MID = 1/2/3 unsigned binaural_mode = 3; // JOC_BINAURAL_NEAR/FAR/MID = 1/2/3
@@ -42,9 +33,15 @@ struct Values {
double tail_seconds = 5.0; double tail_seconds = 5.0;
// Deliver int24 instead of float32; see joc_decode::Settings::force_int24. // Deliver int24 instead of float32; see joc_decode::Settings::force_int24.
bool force_int24 = false; bool force_int24 = false;
// Swap Ls with Lrs and Rs with Rrs in the delivered speaker PCM; a layout
// without both pairs is delivered unchanged.
bool swap_side_rear = false;
unsigned object_delay_samples = 1473; unsigned object_delay_samples = 1473;
unsigned native_threads = 0; unsigned native_threads = 0;
std::string ffmpeg_path = "ffmpeg"; std::string ffmpeg_path = "ffmpeg";
// Language of the page, the status lines and the messages; kSystem follows
// the Windows user-interface language. Decoding and rendering never read it.
joc_lang::Language language = joc_lang::Language::kSystem;
}; };
Values defaults(); Values defaults();
+168
View File
@@ -0,0 +1,168 @@
// Offline check of the side/rear channel swap the component applies to the PCM it
// hands to foobar2000.
//
// channel_swap_test
//
// Two things are checked, and neither needs a file or a render:
//
// * which layouts the swap touches. It has to be decided by the channel names
// the layout table gives, because 5.1.2 and 5.1.4 reuse the slots 7.1 keeps
// for the rear pair: a count-based rule would swap top channels there.
// * the reorder itself: exactly Ls<->Lrs and Rs<->Rrs, every other slot
// untouched, and the operation is its own inverse.
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include "../src/joc_decode.h"
namespace {
int g_failures = 0;
void check(bool condition, const char* what, const std::string& detail) {
if (condition) return;
++g_failures;
std::printf("FAIL %s: %s\n", what, detail.c_str());
}
// A block whose sample values are the channel index, so the reorder is readable.
std::vector<float> make_block(unsigned channels, std::size_t frames) {
std::vector<float> block(frames * channels);
for (std::size_t frame = 0; frame < frames; ++frame) {
for (unsigned channel = 0; channel < channels; ++channel) {
block[frame * channels + channel] = static_cast<float>(channel + frame * 100);
}
}
return block;
}
void expect_swappable(const char* layout, bool expected) {
const joc_decode::SideRearChannels map = joc_decode::side_rear_channels(layout);
check(map.complete() == expected, "side_rear_channels", layout);
}
void expect_layout_indices(const char* layout, int ls, int rs, int lrs, int rrs) {
const joc_decode::SideRearChannels map = joc_decode::side_rear_channels(layout);
check(map.left_side == ls, "left side index", layout);
check(map.right_side == rs, "right side index", layout);
check(map.left_rear == lrs, "left rear index", layout);
check(map.right_rear == rrs, "right rear index", layout);
}
void expect_swap(const char* layout, unsigned channels, std::size_t frames) {
const joc_decode::SideRearChannels map = joc_decode::side_rear_channels(layout);
check(map.complete(), "layout carries both pairs", layout);
if (!map.complete()) return;
std::vector<float> block = make_block(channels, frames);
joc_decode::swap_side_rear(block.data(), frames, channels, map);
for (std::size_t frame = 0; frame < frames; ++frame) {
for (unsigned channel = 0; channel < channels; ++channel) {
int expected = static_cast<int>(channel) + static_cast<int>(frame) * 100;
if (static_cast<int>(channel) == map.left_side) expected = map.left_rear + static_cast<int>(frame) * 100;
else if (static_cast<int>(channel) == map.right_side) expected = map.right_rear + static_cast<int>(frame) * 100;
else if (static_cast<int>(channel) == map.left_rear) expected = map.left_side + static_cast<int>(frame) * 100;
else if (static_cast<int>(channel) == map.right_rear) expected = map.right_side + static_cast<int>(frame) * 100;
const float actual = block[frame * channels + channel];
check(actual == static_cast<float>(expected), "swapped sample", layout);
}
}
// Swapping twice restores the original order.
joc_decode::swap_side_rear(block.data(), frames, channels, map);
const std::vector<float> original = make_block(channels, frames);
check(block == original, "swap is its own inverse", layout);
}
// A layout without both pairs must come through untouched, including the 5.1.x
// ones whose last slots are top channels rather than a rear pair.
void expect_untouched(const char* layout, unsigned channels) {
const joc_decode::SideRearChannels map = joc_decode::side_rear_channels(layout);
check(!map.complete(), "layout has no side/rear pair", layout);
std::vector<float> block = make_block(channels, 3);
joc_decode::swap_side_rear(block.data(), 3, channels, map);
check(block == make_block(channels, 3), "untouched", layout);
}
// A caller that passes fewer channels than the map needs is left alone rather than
// reading past the block: the decoder only enables the swap when the counts agree,
// but the guard is cheap.
void expect_guard() {
const joc_decode::SideRearChannels map = joc_decode::side_rear_channels("7.1");
std::vector<float> block = make_block(2, 4);
joc_decode::swap_side_rear(block.data(), 4, 2, map);
check(block == make_block(2, 4), "narrow block untouched", "7.1 in 2 channels");
joc_decode::swap_side_rear(nullptr, 4, 8, map);
}
} // namespace
int main() {
// Layouts with a real side pair and a real rear pair.
expect_swappable("7.1", true);
expect_swappable("7.1.2", true);
expect_swappable("7.1.4", true);
expect_swappable("9.1.4", true);
expect_swappable("9.1.6", true);
// Stereo, 3.1, 4.0 and the 5.1 family have no rear pair to swap with.
expect_swappable("2.0", false);
expect_swappable("3.1", false);
expect_swappable("4.0", false);
expect_swappable("5.1", false);
expect_swappable("5.1.2", false);
expect_swappable("5.1.4", false);
// Unknown layouts are no-ops too.
expect_swappable("", false);
expect_swappable("7.1.8", false);
// In the table's order the side pair is 4/5 and the rear pair 6/7.
expect_layout_indices("7.1", 4, 5, 6, 7);
expect_layout_indices("7.1.2", 4, 5, 6, 7);
expect_layout_indices("7.1.4", 4, 5, 6, 7);
expect_layout_indices("9.1.4", 4, 5, 6, 7);
expect_layout_indices("9.1.6", 4, 5, 6, 7);
expect_swap("7.1", 8, 4);
expect_swap("7.1.2", 10, 2);
expect_swap("7.1.4", 12, 3);
expect_swap("9.1.4", 14, 2);
expect_swap("9.1.6", 16, 2);
expect_untouched("5.1", 6);
expect_untouched("5.1.2", 8);
expect_untouched("5.1.4", 10);
expect_untouched("4.0", 4);
expect_guard();
// The delivery path packs the swapped block to int24 after the reorder, so the
// int24 output is checked as well: the bytes for the swapped block have to
// equal the bytes of a hand-permuted copy, i.e. the packing keeps the order.
{
const joc_decode::SideRearChannels map = joc_decode::side_rear_channels("7.1");
std::vector<float> block(8);
for (unsigned channel = 0; channel < 8; ++channel) {
block[channel] = static_cast<float>(channel + 1) / 32.0f;
}
std::vector<float> expected = block;
std::swap(expected[4], expected[6]);
std::swap(expected[5], expected[7]);
joc_decode::swap_side_rear(block.data(), 1, 8, map);
std::vector<std::uint8_t> packed(8 * 3);
std::vector<std::uint8_t> reference(8 * 3);
joc_decode::pack_int24(block.data(), 8, packed.data());
joc_decode::pack_int24(expected.data(), 8, reference.data());
check(packed == reference, "int24 carries the swapped order", "7.1");
}
if (g_failures != 0) {
std::printf("%d check(s) failed\n", g_failures);
return 1;
}
std::printf("ok: side/rear swap covers 7.1 and 9.1 layouts only\n");
return 0;
}
+142
View File
@@ -0,0 +1,142 @@
// Offline check of the speaker-layout table the component delivers with.
//
// layout_table_test
//
// The table in src/joc_decode.cpp is the one place that says which channels a
// layout has, what each of them is, and in which order they reach foobar2000. It
// is checked from two sides:
//
// * against the kernel's own frozen name table -- the names the renderer accepts
// and the channel counts it reports, so a layout the component offers that the
// kernel would reject (or a count that drifted apart) fails here;
// * against the reference renderer's channel order, which is written out below
// for every layout: the component hands the PCM over in exactly that order.
//
// No rendering and no files are involved, so this runs everywhere the kernel
// archive builds.
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include "../src/joc_decode.h"
#include "speaker/speaker_layout_lookup.h"
namespace {
int g_failures = 0;
void check(bool condition, const char* what, const std::string& detail) {
if (condition) return;
++g_failures;
std::printf("FAIL %s: %s\n", what, detail.c_str());
}
// What the reference renderer emits for each layout, as a space-separated list:
// the names in the order the renderer writes its channels. The PCM handed to the
// host is that order unchanged (the chunk map is the host default for the count).
struct Expected {
const char* name;
const char* order;
};
const Expected kExpected[] = {
{"2.0", "L R"},
{"3.1", "L R C LFE"},
{"4.0", "L R Lrs Rrs"},
{"5.1", "L R C LFE Ls Rs"},
{"7.1", "L R C LFE Ls Rs Lrs Rrs"},
{"5.1.2", "L R C LFE Ls Rs Ltm Rtm"},
{"5.1.4", "L R C LFE Ls Rs Ltf Rtf Ltr Rtr"},
{"7.1.2", "L R C LFE Ls Rs Lrs Rrs Ltm Rtm"},
{"7.1.4", "L R C LFE Ls Rs Lrs Rrs Ltf Rtf Ltr Rtr"},
{"9.1.4", "L R C LFE Ls Rs Lrs Rrs Lw Rw Ltf Rtf Ltr Rtr"},
{"9.1.6", "L R C LFE Ls Rs Lrs Rrs Lw Rw Ltf Rtf Ltm Rtm Ltr Rtr"},
};
std::string join(const std::vector<std::string>& words) {
std::string text;
for (const std::string& word : words) {
if (!text.empty()) text += ' ';
text += word;
}
return text;
}
void check_layout(const Expected& expected) {
const std::string name = expected.name;
const joc_decode::LayoutSpec* spec = nullptr;
std::size_t count = 0;
const joc_decode::LayoutSpec* table = joc_decode::layout_table(&count);
for (std::size_t i = 0; i < count; ++i) {
if (name == table[i].name) spec = &table[i];
}
check(spec != nullptr, "layout is in the table", name);
if (spec == nullptr) return;
check(spec->channels == joc_decode::speaker_channels(name),
"channel count matches speaker_channels()", name);
check(spec->channels <= joc_decode::kMaxLayoutChannels, "channel count fits the table",
name);
// The kernel is the authority on which names exist and how wide they are.
joc::speaker::LayoutInfo kernel;
check(joc::speaker::layout_by_name(name.c_str(), &kernel), "kernel accepts the layout",
name);
check(kernel.channel_count == spec->channels, "kernel channel count",
name + " kernel " + std::to_string(kernel.channel_count) + " table " +
std::to_string(spec->channels));
// The table lists the reference renderer's order, and the reference order is
// what the expected list says.
std::vector<std::string> channels;
for (unsigned i = 0; i < spec->channels; ++i) {
check(spec->speakers[i] != nullptr && spec->speakers[i][0] != '\0',
"channel has a name", name + " channel " + std::to_string(i));
channels.push_back(spec->speakers[i] != nullptr ? spec->speakers[i] : "");
}
check(join(channels) == expected.order, "channel order", name + " got " + join(channels));
}
} // namespace
int main() {
// The component's table and the kernel's frozen table have to be the same list
// of layouts, in the same order: the preferences page shows one, the renderer
// accepts the other.
std::size_t count = 0;
const joc_decode::LayoutSpec* table = joc_decode::layout_table(&count);
check(count == static_cast<std::size_t>(joc::speaker::kLayoutCount),
"layout count matches the kernel",
std::to_string(count) + " vs " + std::to_string(joc::speaker::kLayoutCount));
const std::size_t expected_count = sizeof(kExpected) / sizeof(kExpected[0]);
check(count == expected_count, "layout count matches the expected list",
std::to_string(count) + " vs " + std::to_string(expected_count));
for (std::size_t i = 0; i < count && i < expected_count; ++i) {
check(std::strcmp(table[i].name, kExpected[i].name) == 0, "layout order",
std::string(table[i].name) + " vs " + kExpected[i].name);
joc::speaker::LayoutInfo kernel;
if (joc::speaker::layout_at(static_cast<int>(i), &kernel)) {
check(std::strcmp(table[i].name, kernel.name) == 0, "layout name at index",
std::string(table[i].name) + " vs " + kernel.name);
}
}
for (const Expected& expected : kExpected) check_layout(expected);
// Names the table must not claim: the component and the kernel treat every one
// of them as an unknown layout.
for (const char* rejected : {"3.0", "5.0", "6.1", "7.0", "22.2", "4.0 Surround",
"4.0 Quad", ""}) {
check(joc_decode::speaker_channels(rejected) == 0, "unsupported layout rejected",
rejected);
}
if (g_failures == 0) {
std::printf("layout_table_test: %zu layouts, 0 problem(s)\n", count);
return 0;
}
std::printf("layout_table_test: %d problem(s)\n", g_failures);
return 1;
}
+16 -7
View File
@@ -6,7 +6,6 @@
// --mode binaural|speaker default binaural // --mode binaural|speaker default binaural
// --format float32|int24 delivered sample format (default float32) // --format float32|int24 delivered sample format (default float32)
// --layout NAME speaker layout (default 7.1) // --layout NAME speaker layout (default 7.1)
// --hrtf-source sofa|rosella kind of model --hrtf points at (default sofa)
// --hrtf PATH HRTF to render with; supplied by the caller and // --hrtf PATH HRTF to render with; supplied by the caller and
// never part of this repository. Without it the // never part of this repository. Without it the
// default location beside the executable is used. // default location beside the executable is used.
@@ -63,8 +62,8 @@ struct Options {
std::string mode = "binaural"; std::string mode = "binaural";
std::string format = "float32"; // float32 | int24 std::string format = "float32"; // float32 | int24
std::string layout = "7.1"; std::string layout = "7.1";
std::string hrtf; // SOFA file, or Rosella model file std::string hrtf; // Rosella model file
std::string hrtf_source = "sofa"; // sofa | rosella bool swap_side_rear = false; // --swap-side-rear
std::string ffmpeg = "ffmpeg"; std::string ffmpeg = "ffmpeg";
double gain_db = 0.0; double gain_db = 0.0;
double tail_seconds = 5.0; double tail_seconds = 5.0;
@@ -146,7 +145,7 @@ bool parse(int argc, char** argv, Options* options) {
else if (arg == "--format") options->format = next(); else if (arg == "--format") options->format = next();
else if (arg == "--layout") options->layout = next(); else if (arg == "--layout") options->layout = next();
else if (arg == "--hrtf") options->hrtf = next(); else if (arg == "--hrtf") options->hrtf = next();
else if (arg == "--hrtf-source") options->hrtf_source = next(); else if (arg == "--swap-side-rear") options->swap_side_rear = true;
else if (arg == "--ffmpeg") options->ffmpeg = next(); else if (arg == "--ffmpeg") options->ffmpeg = next();
else if (arg == "--gain-db") options->gain_db = std::atof(next().c_str()); else if (arg == "--gain-db") options->gain_db = std::atof(next().c_str());
else if (arg == "--tail") options->tail_seconds = std::atof(next().c_str()); else if (arg == "--tail") options->tail_seconds = std::atof(next().c_str());
@@ -211,6 +210,16 @@ bool render_once(const joc_decode::Settings& settings, const Options& options,
const std::string header = wav_header(channels, 48000, 0, int24); const std::string header = wav_header(channels, 48000, 0, int24);
std::fwrite(header.data(), 1, header.size(), file); std::fwrite(header.data(), 1, header.size(), file);
// The same lookup the component does, so the harness exercises the delivery
// reorder with the layout's own channel positions.
const joc_decode::SideRearChannels swap_map =
options.swap_side_rear ? joc_decode::side_rear_channels(settings.speaker_layout)
: joc_decode::SideRearChannels();
if (options.swap_side_rear && !swap_map.complete()) {
std::fprintf(stderr, "harness: --swap-side-rear has no effect on layout %s\n",
settings.speaker_layout.c_str());
}
constexpr std::size_t kChunk = 4096; constexpr std::size_t kChunk = 4096;
std::vector<float> buffer(kChunk * channels); std::vector<float> buffer(kChunk * channels);
std::vector<std::uint8_t> packed; std::vector<std::uint8_t> packed;
@@ -236,6 +245,9 @@ bool render_once(const joc_decode::Settings& settings, const Options& options,
if (left < want) want = static_cast<std::size_t>(left); if (left < want) want = static_cast<std::size_t>(left);
} }
const std::size_t frames = engine.read(buffer.data(), want, error); const std::size_t frames = engine.read(buffer.data(), want, error);
if (frames != 0 && options.swap_side_rear) {
joc_decode::swap_side_rear(buffer.data(), frames, channels, swap_map);
}
if (frames == 0) { if (frames == 0) {
if (!error->empty()) { if (!error->empty()) {
std::fclose(file); std::fclose(file);
@@ -291,7 +303,6 @@ int main(int argc, char** argv) {
std::fprintf(stderr, std::fprintf(stderr,
"usage: render_harness --input <eac3> --output <wav> [--mode binaural|speaker]\n" "usage: render_harness --input <eac3> --output <wav> [--mode binaural|speaker]\n"
" [--format float32|int24] [--layout NAME]\n" " [--format float32|int24] [--layout NAME]\n"
" [--hrtf-source sofa|rosella] [--hrtf PATH]\n"
" [--gain-db X] [--tail S] [--ffmpeg path] [--max-frames N]\n" " [--gain-db X] [--tail S] [--ffmpeg path] [--max-frames N]\n"
" [--max-input-frames N] [--seek-to S] [--seek-at N:S]\n" " [--max-input-frames N] [--seek-to S] [--seek-at N:S]\n"
" [--total-seconds S] [--pipeline-delay N] [--preroll-frames N]\n" " [--total-seconds S] [--pipeline-delay N] [--preroll-frames N]\n"
@@ -304,8 +315,6 @@ int main(int argc, char** argv) {
settings.output = (options.mode == "speaker") ? joc_decode::Output::kSpeaker settings.output = (options.mode == "speaker") ? joc_decode::Output::kSpeaker
: joc_decode::Output::kBinaural; : joc_decode::Output::kBinaural;
settings.speaker_layout = options.layout; settings.speaker_layout = options.layout;
settings.hrtf_source = (options.hrtf_source == "rosella") ? joc_decode::HrtfSource::kRosella
: joc_decode::HrtfSource::kSofa;
settings.hrtf_file = options.hrtf; settings.hrtf_file = options.hrtf;
settings.gain_db = options.gain_db; settings.gain_db = options.gain_db;
settings.tail_seconds = options.tail_seconds; settings.tail_seconds = options.tail_seconds;
+377
View File
@@ -0,0 +1,377 @@
// Measures every user-visible string of the preferences page against the control
// it is shown in, in both languages.
//
// ui_text_fit_test <path to foo_input_joc.dll>
//
// The page is bilingual, and the wider language is not always the translated one:
// the English label is sometimes the longer one. This check creates the dialog from
// the component's own resource (the same way the component does), then measures
// each string with the control's own font and compares it with the space that
// control has. Multi-line static controls are wrapped at word boundaries, so a
// hint that needs one line too many is reported as well.
//
// The text itself comes from src/lang.cpp, so the check covers both languages with
// the strings that ship; the mapping below mirrors what the page applies.
//
// The component imports the SDK helpers from the host's shared.dll, so that file
// has to sit beside this executable (and beside the component).
#include <windows.h>
#include <cstdio>
#include <string>
#include <vector>
#include "../src/lang.h"
#include "../src/joc_decode.h"
#include "../src/resource.h"
namespace {
int g_failures = 0;
std::string narrow(const wchar_t* text) {
if (text == nullptr || *text == L'\0') return {};
const int needed = WideCharToMultiByte(CP_UTF8, 0, text, -1, nullptr, 0, nullptr, nullptr);
std::string out(static_cast<std::size_t>(needed), '\0');
WideCharToMultiByte(CP_UTF8, 0, text, -1, out.data(), needed, nullptr, nullptr);
if (!out.empty() && out.back() == '\0') out.pop_back();
return out;
}
std::wstring widen(const char* text) {
if (text == nullptr || *text == '\0') return {};
const int needed = MultiByteToWideChar(CP_UTF8, 0, text, -1, nullptr, 0);
std::wstring out(static_cast<std::size_t>(needed), L'\0');
MultiByteToWideChar(CP_UTF8, 0, text, -1, out.data(), needed);
if (!out.empty() && out.back() == L'\0') out.pop_back();
return out;
}
class Measurer {
public:
Measurer() {
dc_ = CreateCompatibleDC(nullptr);
SetMapMode(dc_, MM_TEXT);
}
~Measurer() {
if (dc_ != nullptr) DeleteDC(dc_);
}
int width(const std::wstring& text, HFONT font) {
HGDIOBJ previous = nullptr;
if (font != nullptr) previous = SelectObject(dc_, font);
SIZE size{};
GetTextExtentPoint32W(dc_, text.c_str(), static_cast<int>(text.size()), &size);
if (previous != nullptr) SelectObject(dc_, previous);
return size.cx;
}
int line_height(HFONT font) {
HGDIOBJ previous = nullptr;
if (font != nullptr) previous = SelectObject(dc_, font);
TEXTMETRICW metrics{};
GetTextMetricsW(dc_, &metrics);
if (previous != nullptr) SelectObject(dc_, previous);
return metrics.tmHeight + metrics.tmExternalLeading;
}
// Greedy word wrap: how many lines the text needs at this width.
int lines(const std::wstring& text, HFONT font, int available) {
int count = 1;
int used = 0;
std::wstring word;
for (std::size_t i = 0; i <= text.size(); ++i) {
const wchar_t ch = i < text.size() ? text[i] : L' ';
if (ch == L' ' || ch == L'\n' || i == text.size()) {
if (!word.empty()) {
const int word_width = width(word, font);
if (used != 0 && used + width(L" ", font) + word_width > available) {
++count;
used = word_width;
} else {
used += (used != 0 ? width(L" ", font) : 0) + word_width;
}
word.clear();
}
if (ch == L'\n') {
++count;
used = 0;
}
} else {
word.push_back(ch);
}
}
return count;
}
private:
HDC dc_ = nullptr;
};
struct Binding {
int control;
joc_lang::Text text;
};
const Binding kBindings[] = {
{IDC_GROUP_OUTPUT, joc_lang::Text::kGroupOutput},
{IDC_RADIO_BINAURAL, joc_lang::Text::kRadioBinaural},
{IDC_RADIO_SPEAKER, joc_lang::Text::kRadioSpeaker},
{IDC_LABEL_MODE, joc_lang::Text::kLabelMode},
{IDC_LABEL_TAIL, joc_lang::Text::kLabelTail},
{IDC_CHECK_INT24, joc_lang::Text::kCheckInt24},
{IDC_CHECK_SWAP_SIDE_REAR, joc_lang::Text::kCheckSwapSideRear},
{IDC_LABEL_INT24_HINT, joc_lang::Text::kInt24Hint},
{IDC_GROUP_HRTF, joc_lang::Text::kGroupHrtf},
{IDC_RADIO_HRTF_ROSELLA, joc_lang::Text::kRadioRosella},
{IDC_LABEL_HRTF, joc_lang::Text::kLabelHrtfFile},
{IDC_BROWSE_HRTF, joc_lang::Text::kButtonBrowse},
{IDC_LABEL_HRTF_HINT, joc_lang::Text::kHrtfHint},
{IDC_GROUP_GAIN, joc_lang::Text::kGroupGain},
{IDC_CHECK_GAIN, joc_lang::Text::kCheckGain},
{IDC_LABEL_GAIN, joc_lang::Text::kLabelGainUnit},
{IDC_LABEL_GAIN_HINT, joc_lang::Text::kGainHint},
{IDC_GROUP_MISC, joc_lang::Text::kGroupOther},
{IDC_LABEL_LANGUAGE, joc_lang::Text::kLabelLanguage},
{IDC_LABEL_FFMPEG, joc_lang::Text::kLabelFfmpeg},
{IDC_BROWSE_FFMPEG, joc_lang::Text::kButtonBrowse},
};
// The host sizes the page window to its own area and clips whatever is below it,
// without a scrollbar, so an oversized page silently loses its lower groups. The
// area measured inside a 125 percent foobar2000 window is 456 px tall, i.e. about
// 273 dialog units; 268 leaves room for the window chrome at both 96 and 125.
void check_page_size(HWND dialog) {
RECT client{};
GetClientRect(dialog, &client);
RECT budget{0, 0, 330, 268};
MapDialogRect(dialog, &budget);
if (client.right > budget.right || client.bottom > budget.bottom) {
++g_failures;
std::printf("PAGE TOO LARGE: %ldx%ld px, budget %ldx%ld px\n", client.right,
client.bottom, budget.right, budget.bottom);
} else {
std::printf("page size %ldx%ld px, budget %ldx%ld px\n", client.right, client.bottom,
budget.right, budget.bottom);
}
}
void report(const std::string& language, const char* what, const std::string& text, int needed,
int available) {
if (needed <= available) return;
++g_failures;
std::printf("OVERFLOW [%s] %s: %d px needed, %d available: %s\n", language.c_str(), what,
needed, available, text.c_str());
}
std::size_t index_of(joc_lang::Text text) {
std::size_t index = 0;
for (const Binding& binding : kBindings) {
if (binding.text == text) return index;
++index;
}
return static_cast<std::size_t>(-1);
}
void check_control(Measurer& measurer, HWND dialog, const Binding& binding,
const std::string& language) {
HWND control = GetDlgItem(dialog, binding.control);
if (control == nullptr) {
++g_failures;
std::printf("MISSING [%s] control %d\n", language.c_str(), binding.control);
return;
}
RECT rect{};
GetClientRect(control, &rect);
const int rect_width = rect.right - rect.left;
const int rect_height = rect.bottom - rect.top;
const auto font = reinterpret_cast<HFONT>(SendMessageW(control, WM_GETFONT, 0, 0));
const std::wstring text = widen(joc_lang::get(
language == "en" ? joc_lang::Language::kEnglish : joc_lang::Language::kChineseSimplified,
binding.text));
wchar_t class_name[64] = {};
GetClassNameW(control, class_name, 64);
const std::string window_class = narrow(class_name);
int available = rect_width;
if (window_class == "Button") {
const LONG_PTR style = GetWindowLongPtrW(control, GWL_STYLE);
const LONG_PTR type = style & BS_TYPEMASK;
// A check box or radio button draws its box inside the control rectangle,
// and a push button its frame: the text has to fit in what is left.
available -= (type == BS_AUTOCHECKBOX || type == BS_AUTORADIOBUTTON) ? 17 : 8;
}
const int line_height = measurer.line_height(font);
if (rect_height >= 2 * line_height) {
const int lines = measurer.lines(text, font, available);
report(language, "wrapped text", narrow(text.c_str()), lines * line_height,
rect_height);
} else {
report(language, "text width", narrow(text.c_str()), measurer.width(text, font),
available);
}
}
void check_line(Measurer& measurer, HWND control, const std::string& language,
const std::string& text) {
if (control == nullptr) {
++g_failures;
std::printf("MISSING [%s] status control\n", language.c_str());
return;
}
RECT rect{};
GetClientRect(control, &rect);
const int rect_height = rect.bottom - rect.top;
const auto font = reinterpret_cast<HFONT>(SendMessageW(control, WM_GETFONT, 0, 0));
const std::wstring wide_text = widen(text.c_str());
const int line_height = measurer.line_height(font);
if (rect_height >= 2 * line_height) {
const int lines = measurer.lines(wide_text, font, rect.right - rect.left);
report(language, "status lines", text, lines * line_height, rect_height);
} else {
report(language, "status width", text, measurer.width(wide_text, font), rect.right);
}
}
void check_combo(Measurer& measurer, HWND control, const std::string& language,
const std::vector<std::string>& items) {
if (control == nullptr) {
++g_failures;
std::printf("MISSING [%s] combo\n", language.c_str());
return;
}
RECT rect{};
GetClientRect(control, &rect);
// Drop-down list: the closed control shows the selected item next to the arrow.
const int available = rect.right - 17;
const auto font = reinterpret_cast<HFONT>(SendMessageW(control, WM_GETFONT, 0, 0));
for (const std::string& item : items) {
report(language, "combo item", item, measurer.width(widen(item.c_str()), font),
available);
}
}
std::string format(const char* pattern, const char* layout) {
char buffer[256] = {};
std::snprintf(buffer, sizeof(buffer), pattern, layout);
return buffer;
}
INT_PTR CALLBACK stub_proc(HWND, UINT, WPARAM, LPARAM) { return FALSE; }
// The page is an embedded WS_CHILD dialog, so it needs a parent window even when
// it is only measured.
HWND create_host() {
static const wchar_t* kClass = L"joc_text_fit_host";
WNDCLASSEXW window_class{};
window_class.cbSize = sizeof(window_class);
window_class.lpfnWndProc = DefWindowProcW;
window_class.hInstance = GetModuleHandleW(nullptr);
window_class.lpszClassName = kClass;
RegisterClassExW(&window_class);
return CreateWindowExW(0, kClass, L"host", WS_OVERLAPPEDWINDOW, 0, 0, 640, 480, nullptr,
nullptr, window_class.hInstance, nullptr);
}
} // namespace
int main(int argc, char** argv) {
if (argc < 2) {
std::fprintf(stderr, "usage: ui_text_fit_test <foo_input_joc.dll>\n");
return 2;
}
const std::wstring dll_path = [&] {
const int needed = MultiByteToWideChar(CP_UTF8, 0, argv[1], -1, nullptr, 0);
std::wstring out(static_cast<std::size_t>(needed), L'\0');
MultiByteToWideChar(CP_UTF8, 0, argv[1], -1, out.data(), needed);
if (!out.empty() && out.back() == L'\0') out.pop_back();
return out;
}();
HMODULE module = LoadLibraryExW(dll_path.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
if (module == nullptr) {
std::fprintf(stderr, "cannot load %s (error %lu)\n", argv[1], GetLastError());
return 1;
}
HWND host = create_host();
if (host == nullptr) {
std::fprintf(stderr, "cannot create the host window (error %lu)\n", GetLastError());
return 1;
}
HWND dialog = CreateDialogParamW(module, MAKEINTRESOURCEW(IDD_JOC_PREFS), host,
stub_proc, 0);
if (dialog == nullptr) {
std::fprintf(stderr, "CreateDialogParamW failed (error %lu)\n", GetLastError());
return 1;
}
check_page_size(dialog);
Measurer measurer;
for (const std::string language : {"zh", "en"}) {
for (const Binding& binding : kBindings) {
check_control(measurer, dialog, binding, language);
}
const joc_lang::Language resolved = language == "en"
? joc_lang::Language::kEnglish
: joc_lang::Language::kChineseSimplified;
// Combo boxes.
std::vector<std::string> modes;
for (unsigned i = 0; i < 3; ++i) {
const joc_lang::Text id = i == 0 ? joc_lang::Text::kComboModeNear
: i == 1 ? joc_lang::Text::kComboModeFar
: joc_lang::Text::kComboModeMid;
modes.emplace_back(joc_lang::get(resolved, id));
}
check_combo(measurer, GetDlgItem(dialog, IDC_COMBO_MODE), language, modes);
check_combo(measurer, GetDlgItem(dialog, IDC_COMBO_LANGUAGE), language,
{joc_lang::get(resolved, joc_lang::Text::kLanguageSystem),
joc_lang::get(resolved, joc_lang::Text::kLanguageChinese),
joc_lang::get(resolved, joc_lang::Text::kLanguageEnglish)});
std::size_t layout_count = 0;
const joc_decode::LayoutSpec* layouts = joc_decode::layout_table(&layout_count);
std::vector<std::string> names;
for (std::size_t i = 0; i < layout_count; ++i) names.emplace_back(layouts[i].name);
check_combo(measurer, GetDlgItem(dialog, IDC_COMBO_LAYOUT), language, names);
// Status lines the page writes at run time.
const HWND output_status = GetDlgItem(dialog, IDC_LABEL_OUTPUT_STATUS);
for (std::size_t i = 0; i < layout_count; ++i) {
check_line(measurer, output_status, language,
format(joc_lang::get(resolved, joc_lang::Text::kSpeakerStatus),
layouts[i].name));
}
// The page shortens the path line before it is shown, so only the two-line
// envelope of the status field is measured: the label, and the longest text
// the elision can leave behind (the file name on its own).
check_line(measurer, GetDlgItem(dialog, IDC_LABEL_STATUS), language,
std::string(joc_lang::get(resolved, joc_lang::Text::kHrtfSourceSofa)) +
joc_lang::get(resolved, joc_lang::Text::kSeparator) +
joc_lang::get(resolved, joc_lang::Text::kHrtfDefault) + "\n" +
"binaural.personalized_headphone");
check_line(measurer, GetDlgItem(dialog, IDC_LABEL_STATUS), language,
std::string(
joc_lang::get(resolved, joc_lang::Text::kHrtfSourceRosella)) +
joc_lang::get(resolved, joc_lang::Text::kSeparator) + "\n" +
joc_lang::get(resolved, joc_lang::Text::kHrtfDefaultUnknown));
char gain[128] = {};
std::snprintf(gain, sizeof(gain),
joc_lang::get(resolved, joc_lang::Text::kGainStatusOn), -12.00);
check_line(measurer, GetDlgItem(dialog, IDC_LABEL_GAIN_STATUS), language, gain);
check_line(measurer, GetDlgItem(dialog, IDC_LABEL_GAIN_STATUS), language,
joc_lang::get(resolved, joc_lang::Text::kGainStatusOff));
}
DestroyWindow(dialog);
if (g_failures == 0) {
std::printf("ui_text_fit_test: both languages fit their controls\n");
return 0;
}
std::printf("ui_text_fit_test: %d string(s) do not fit\n", g_failures);
return 1;
}
+3
View File
@@ -46,6 +46,9 @@ $lines = @(
"cl $common /Fe:`"$outDir\prefs_layout_check.exe`" /Fo:`"$outDir\\`" tests\prefs_layout_check.cpp user32.lib gdi32.lib", "cl $common /Fe:`"$outDir\prefs_layout_check.exe`" /Fo:`"$outDir\\`" tests\prefs_layout_check.cpp user32.lib gdi32.lib",
"cl $common /Fe:`"$outDir\scan_crosscheck.exe`" /Fo:`"$outDir\\`" tests\scan_crosscheck.cpp src\eac3_scan.cpp `"$coreLib`" shell32.lib", "cl $common /Fe:`"$outDir\scan_crosscheck.exe`" /Fo:`"$outDir\\`" tests\scan_crosscheck.cpp src\eac3_scan.cpp `"$coreLib`" shell32.lib",
"cl $common /Fe:`"$outDir\render_harness.exe`" /Fo:`"$outDir\\`" tests\render_harness.cpp src\joc_decode.cpp src\eac3_scan.cpp src\container_scan.cpp src\log.cpp `"$coreLib`" shell32.lib", "cl $common /Fe:`"$outDir\render_harness.exe`" /Fo:`"$outDir\\`" tests\render_harness.cpp src\joc_decode.cpp src\eac3_scan.cpp src\container_scan.cpp src\log.cpp `"$coreLib`" shell32.lib",
"cl $common /Fe:`"$outDir\layout_table_test.exe`" /Fo:`"$outDir\\`" tests\layout_table_test.cpp src\joc_decode.cpp src\eac3_scan.cpp src\container_scan.cpp src\log.cpp `"$coreLib`" shell32.lib",
"cl $common /Fe:`"$outDir\channel_swap_test.exe`" /Fo:`"$outDir\\`" tests\channel_swap_test.cpp src\joc_decode.cpp src\eac3_scan.cpp src\container_scan.cpp src\log.cpp `"$coreLib`" shell32.lib",
"cl $common /Fe:`"$outDir\ui_text_fit_test.exe`" /Fo:`"$outDir\\`" tests\ui_text_fit_test.cpp src\lang.cpp src\joc_decode.cpp src\eac3_scan.cpp src\container_scan.cpp src\log.cpp `"$coreLib`" shell32.lib user32.lib gdi32.lib",
'if errorlevel 1 exit /b 1', 'if errorlevel 1 exit /b 1',
'exit /b 0' 'exit /b 0'
) )