38 Commits
Author SHA1 Message Date
TheM14 8372c1160c Bump foo_input_joc to 0.6.4 and sync the vendored kernel to 1.3.4
build / windows (push) Waiting to run
- Bump JOC_VERSION to 0.6.4.
- Bed channel table: Tfl/Tfr, Tsl/Tsr and Tbl/Tbr take x = -1 / +1 with Y =
  1 / 0 / -1, Lw/Rw take Y = 21/31, and LFE/LFE2 stay at the origin.
- bed_channel_q15 converts with the 32768 full scale and rounds instead of
  truncating, so half-step positions (16384, 5285) come out exact.
- layout_bed_anchor resolves a bed channel by its own index instead of passing
  its name through standard_from_internal, which had swapped the side/rear
  anchors of 7.1.x/9.1.x and the top front/back anchors of 9.1.6.
- 5.1, 5.1.2 and 5.1.4 keep their single surround pair at the rear corners
  (Y = 32767) instead of Y = 16384.
- Report kernel 1.3.4 and component 0.6.4; the notices and READMEs that name
  the vendored version follow.
2026-11-18 19:53:47 +08:00
TheM14 8be8e895c0 Bump foo_input_joc to 0.6.3 and fix long PCM playback
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
- Bump JOC_VERSION to 0.6.3.
- Give each PcmSource a unique temp WAV name (PID + serial + tick) so
  info, playback and next-track instances cannot overwrite or delete each
  other's decoded file.
- Cap read() at the decoded file length so the binaural room tail is not
  delivered as extra playback time.
- Reset the emitted-frame counter on seek.
2026-11-13 13:32:47 +08:00
TheM14 b52b384145 Bump component to 0.6.2 and add Dolby Dialnorm loudness control
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
- Bump JOC_VERSION to 0.6.2.
- Add a "Dolby Dialnorm loudness (-31 dBFS)" preference switch.
- Persist the setting as dialnorm and allow JOC_DIALNORM to override it.
- Apply -target_level -31 only to the ffmpeg-decoded 5.1 E-AC-3 core; leave
  the 7-channel core and ordinary PCM takeover paths unchanged.
- Remove stale SOFA measurement-set wording from the READMEs.
- Rebuild and deploy both x86 and x64 components.
2026-11-12 14:53:32 +08:00
TheM14 b0751d82b6 Add ffmpeg PCM and non-JOC E-AC-3/TrueHD takeover
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
- Add the take_over_pcm preference, persistence and input registration.
- Decode takeover sources with ffmpeg to 48 kHz float32 and feed the kernel
  PCM_LAYOUT stream for binaural output.
- Keep JOC priority: bare E-AC-3/EC3 and MP4/Matroska/WebM are probed first,
  then non-JOC audio falls back to ffmpeg.
- Cover AC3, DTS/DTS-HD, WavPack, APE, TTA, MPC, AU/SND/CAF and TrueHD/MLP;
  TrueHD in containers follows the same fallback.
- Sync the kernel to 1.3.3 with the virtual_speaker module and fix the PCM
  gain path.
- Update the preferences UI, HRTF hint and README.
2026-11-12 14:32:45 +08:00
TheM14 5c0f9ea2ff Sync the 1.3.1 kernel and read the stream until its first JOC frame
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
The kernel copy follows JustOneCacophonyCXX 1.3.1: a frame without JOC metadata
mid-stream now holds the previous matrices instead of switching to the core
planes, which removes the clicks the 6.0 kernels produced on encoders that drop
the JOC metadata for single frames.

resolve_bed_channels() called ReadFile once and scanned that single chunk.  A
read returns only the bytes that are available (a pipe hands over a partial
chunk), and an encoder may leave the first audio frames without JOC metadata,
so the first JOC frame could sit past the window.  The scan then fell back to 6
bed channels, and the first JOC frame (joc_dmx_config_idx=1, 8 channels) was
rejected with core_channel_count_mismatch.  The scan now reads 64 KiB chunks
until the first syncframe carrying the JOC EMDF container is seen, keeps the
trailing partial frame between reads, and rewinds the stream as before; the
container path and the bare-file path both use it.

Bump the component version to 0.6.1, and pin the kernel notices to 1.3.1.

Verified with the offline harness: the reported GNR M4A now reports
"joc_dmx_config_idx=1 -> 8 bed channel(s)" and decodes the whole track (8906
frames), and the Smooth Criminal opening no longer steps at the two frames
without metadata (6.016 s and 7.328 s).
2026-11-10 15:35:32 +08:00
TheM14 886ff036cd Release 0.6.0
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
Bump JOC_VERSION to 0.6.0.  The component ships the 1.3.0 kernel (abce846),
which carries the truncated-JOC-payload fix: an ID14 payload that ends inside
joc_data is a frame status (7) instead of a stream error, so the renderer
holds the previous matrices and playback continues; the stream status struct
gains an appended truncated_joc_frames field.  The offline render harness
decodes the reported M4A to the end (8751 frames, 13,441,536 samples) and the
output is byte-identical to the fixed core CLI.

tools/package.ps1 and the workflow's tag check read this define, so the
packages are named foo_input_joc-0.6.0-{x86,x64}.fb2k-component and the
release tag must be v0.6.0.
2026-11-10 00:17:12 +08:00
TheM14 b0ce3a162f Sync the kernel copy with the truncated JOC payload fix
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
The kernel copy follows JustOneCacophonyCXX abce846 (version 1.3.0).  An ID14
payload that ends inside joc_data is now a frame status (7) instead of a
stream error, so the renderer holds the previous matrices and playback
continues; the file task counts those frames and the stream status struct
gains an appended truncated_joc_frames field that joc_stream_status()
accepts in both struct sizes.  The nine kernel files are byte-identical to
the upstream checkout again, and the component needs no code change because
the fix lives inside the vendored kernel.

README, THIRD_PARTY_NOTICES, the kernel project and the CI comment now pin
the copy to abce846 (version 1.3.0).

Built Release-Static|x64.  The offline test tools build and pass, and
render_harness decodes the reported M4A to the end: 8 channels, 13,441,536
samples (8751 frames), peak 0.742114365, byte-identical to the fixed core
CLI output.
2026-11-10 00:08:19 +08:00
TheM14 defe9538fe Sync the kernel copy with the OAMD frame-level core
The kernel copy follows the new kernel. The renderer has a frame-level state
machine (normal, hold, hard cut and passthrough, the 8-plane passthrough, the
LFE clipgain ramp and interpolation when no previous state exists), the OAMD
parser carries the complete frame state (several blocks, more than 16 objects)
and the speaker renderer applies the metadata (gain and inactive flags,
zone/elevation, size, snap, divergence, ISF and bed distribution). oamd_math and
oamd_params are new modules, the ISF tables are compiled in now that the
upstream data/ directory is gone, and the binaural timeline accepts a complete
frame state. joc_core.h moves to ABI 6 (frame parameters and EMDF payload info
at v2, JOC_FRAME_STATUS_*, raw 5-bit offset_ts) and eac3joc_core.h to EJOC ABI 4
(EJOC_FRAME_STATUS_*, ejoc_frame_input v1, ejoc_renderer_render_frame,
EJOC_CORE_OUT_CHANNELS and EJOC_LFE_SLOT; the old ejoc_renderer_process stays).
joc_stream.h and joc_version.h are unchanged.

joc_kernel.vcxproj lists the two new translation units and the four new
headers. The component's layout table gains the kernel's 6.0 layout (L R Ls Rs
Lrs Rrs) after 9.1.6, and layout_table_test expects twelve layouts, so the list
the preferences page shows and the list the renderer accepts are the same
again. README, THIRD_PARTY_NOTICES and the CI comment pin the copy to commit
3f0d5e87fe41b90d9350528d2dca2ca82a637a3f; tag v1.2.0 points at the older
a276028 and is not the sync baseline.

Builds Release-Static|x64 and |Win32 with no errors. The offline test tools
build and pass on both architectures: layout_table_test reports 12 layouts, and
channel_swap_test, log_rotation_test and long_path_test pass. scan_crosscheck
agrees with the core on the upstream test material, and the render harness
delivers 7.1.4 speaker output and binaural output on both architectures, with
the speaker-path WAV byte-identical between them.

The core is still vendored under kernel/; building it from the upstream
checkout at build time is a separate change.
2026-11-08 16:11:57 +08:00
TheM14 5b41868e94 Sync the kernel copy with the warp 2/3 surround fold
build / windows (push) Canceled after 0s
build / release (push) Canceled after 0s
The kernel copy follows the new kernel: the OAMD parser and the speaker
controls accept warp modes 2 and 3, and the renderer pans the 5.1-family and
4.0 layouts in an expanded surround layout before folding the rear pair into
the target. Trim selection, balance and automatic compensation stay with the
final target layout, and the folded result feeds the existing ramp and mix.

Builds Release-Static|x64 and |Win32. layout_table_test and
channel_swap_test still pass; the render harness now renders a warp-3
stream instead of reporting the unimplemented mode.
2026-11-03 13:36:40 +08:00
TheM14 d35f6abe7a Sync the kernel copy with the OAMD warp and trim controls
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 a warp-3 stream.
2026-11-03 13:35:01 +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
TheM14 2cfebe914d Support JOC downmix configurations 0..4 and update the vendored kernel
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-10-16 19:56:00 +08:00
TheM14 cb840af52f Update the vendored kernel to the temporary path fix
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-10-14 18:08:43 +08:00
TheM14 f0cab2eec5 Update the vendored kernel to the ffmpeg path fix
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-10-14 17:37:17 +08:00
TheM14 5c3083b11c Add forced 24-bit output (int24) for the delivered samples
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-10-14 17:34:29 +08:00
TheM14 ce3de51f8f Update the vendored kernel to the JSON writer fix
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-10-09 00:12:41 +08:00
TheM14 49f3a0f040 Update the vendored kernel to the bounded objects16 render-ahead
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-10-06 15:05:35 +08:00
TheM14 4d22797130 Fix 32-bit dropouts: enable AVX2 and bound the render-ahead
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-10-06 02:43:44 +08:00
TheM14 ea30786711 Fix files past MAX_PATH not being claimed or decoded
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-10-01 14:07:34 +08:00
TheM14 89508a372a Bound the diagnostic log and cut the per-file scan noise
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-09-29 18:44:14 +08:00
TheM14 8f28c69df7 Fix THIRD_PARTY_NOTICES to cover third-party sources only
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-09-28 22:56:02 +08:00
TheM14 8f44bf8a68 Clean up leftover gain assignments in the kernel
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-09-28 19:02:14 +08:00
TheM14 4d8118684f Fix MP4 probe when moov exceeds the window
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-09-27 15:58:23 +08:00
TheM14 bb464b2c03 Fix bed decoded off the E-AC-3 frame grid
build / windows (push) Has been cancelled
build / release (push) Has been cancelled
2026-09-27 14:46:12 +08:00
107 changed files with 15220 additions and 4170 deletions

No files matched your search

+2 -1
View File
@@ -3,7 +3,8 @@ name: build
# Builds both architectures, publishes the two installable component packages as
# workflow artifacts, and — when a tag is pushed — turns them into a GitHub release.
# The SDK is fetched from foobar2000.org at build time (tools/setup_sdk.ps1) and the
# renderer sources are part of this repository (kernel/), so nothing else is needed.
# renderer sources are part of this repository (kernel/, synced from JustOneCacophonyCXX
# version 1.3.1), so nothing else is needed.
on:
push:
+2 -1
View File
@@ -27,8 +27,9 @@
*.personalized_headphone
rosella_kernels.npz
# The component writes its own log next to the DLL
# The component writes its own log next to the DLL, and rolls it to a .1 sibling
joc_decoder.log
joc_decoder.log.1
# Measurement record: local working notes, kept on disk and never published.
VERIFICATION.md
+106 -15
View File
@@ -3,8 +3,9 @@
[简体中文](README.md) · [Install](#install) · [Settings](#settings) · [Building](#building) · [Known limitations](#known-limitations)
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 5.1 core PCM that ffmpeg
decodes, then rendered in real time to headphones (HRTF) or to a speaker layout up to 7.1. The
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
(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
`foo_input_joc.dll`.
@@ -58,23 +59,92 @@ Matroska/WebM Reader** in that list. Bare `.eac3` / `.ec3` files do not depend o
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;
* **HRTF source** — a **SOFA** file or a **Rosella** `.personalized_headphone` model. An empty
path means the default location, `<component directory>\HRTF\binaural.sofa` or
`binaural.personalized_headphone`;
* **HRTF** — a **Rosella personalized model**. An empty path means the default
location, `<component directory>\HRTF\binaural.personalized_headphone`;
* **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;
* the **ffmpeg** executable to use.
* **Force 24-bit output (int24)** — off by default, which delivers float32. When on, every sample
is quantised with the core's own int24 rule (clip to ±1, ×8388607, truncate) before it is handed
over, the samples that had to be clipped are counted in the log, and the component reports the
file as 24-bit fixed point. The renderer itself stays float32: this is the precision the decoder
delivers, not the output device's bit depth, which is set in Preferences → Output. **Reload a
file's information after flipping this switch** (Properties → *Reload info*, or remove the file
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
answer, warning that the encoder does not take floating-point input.
* **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
A SOFA measurement set or a personalised headphone model is supplied by whoever runs the
component, and is listed in `.gitignore` so it cannot be committed by accident. Speaker layouts
A personalised headphone model (`HRTF\binaural.personalized_headphone`) is supplied by whoever
runs the 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.
## 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
```powershell
@@ -89,16 +159,31 @@ 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/` 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,
render comparison, preferences-page layout check, container-probe check) and `tools\` the build
and test-bed scripts. Settings also read `JOC_*` environment overrides for one run (development
only); the list and what each one does is in `src\settings.cpp`.
render comparison, speaker-layout table and channel-order check, preferences-page layout check,
Chinese and English text-width check, container-probe check) and `tools\` the build and test-bed
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
version, the core version and the log path there at start-up.
version, the core version and the log path there at start-up. The log is capped by **bytes**: a
file that reaches 16 MiB is rolled to `joc_decoder.log.1` beside it, replacing the previous roll
rather than accumulating, so the two together never exceed 32 MiB and the newest lines are always
in `joc_decoder.log`. The version banner is written again after a roll. A Media Library scan logs
every container in the library, which is where the volume comes from.
## Known limitations
* 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
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
(`strmtyp=1`) and a first audio frame without JOC are both normal cases.
* A container is only claimed when this component is ahead of the built-in container reader in
Preferences → Decoding (see [Install](#containers-need-one-look-at-the-decoder-list)); the core
does not let a decoder ask for a file another entry has already taken. Such a file's tags stay
@@ -107,6 +192,11 @@ version, the core version and the log path there at start-up.
behind it) can be **read but not written**: no component claims raw E-AC-3 for writing, and
rewriting the whole file to insert a tag is not this component's job.
* Transport streams (`.ts`, `.m2ts`) are not claimed.
* **Force 24-bit output** only changes the precision the decoder delivers: foobar2000 converts the
int24 it receives into its own floating-point samples, and which bit depth the output device runs
at is still decided in Preferences → Output, not by this component. Samples outside ±1 follow the
core's `continue` clip policy (binaural rendering can exceed full scale, so use **Gain** when
attenuation is wanted).
* Playback length is exactly the file's duration. The binaural renderer still computes its room
tail, but it is not delivered as playback time the file does not have.
* A seek re-enters the bitstream at the frame holding the target instead of decoding everything
@@ -118,4 +208,5 @@ version, the core version and the log path there at start-up.
## Licence
`LICENSE` is the upstream MIT licence, copied unchanged; `kernel/` is a copy of the upstream
rendering core sources and keeps their notices. See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
rendering core sources, synced to JustOneCacophonyCXX 1.3.4, and keeps their notices. See
[THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
+88 -15
View File
@@ -3,8 +3,8 @@
[English](README.en.md) · [安装](#安装) · [设置](#设置) · [构建](#构建) · [已知限制](#已知限制)
foobar2000 输入组件,播放 **E-AC-3 JOC(Dolby Atmos)** 文件:从 E-AC-3 同步帧里取出 JOC
对象与 OAMD 元数据,与 ffmpeg 解出的 5.1 核心 PCM 配对后实时渲染,输出双耳(HRTF)或最多
7.1 的扬声器布局。渲染内核直接编译进组件,除 `foo_input_joc.dll` 之外不需要安装任何东西。
对象与 OAMD 元数据,与 ffmpeg 解出的核心 PCM(按 $joc\_dmx\_config\_idx$ 为 5.1 或 7 通道)配对后实时渲染,输出双耳(HRTF)或
2.0 到 9.1.6 的扬声器布局。渲染内核直接编译进组件,除 `foo_input_joc.dll` 之外不需要安装任何东西。
输入是裸流 `.eac3` / `.ec3`,或容器里的 E-AC-3 JOC 轨道(`.mp4` `.m4a` `.m4b` `.m4p`
`.m4r` `.mov` `.mkv` `.mka` `.webm`)。文件里没有 JOC 就不接管:普通 AC-3 / E-AC-3、音频轨道
@@ -50,22 +50,82 @@ Matroska/WebM Reader** 之前。裸流 `.eac3` / `.ec3` 不受这个顺序影响
## 设置
Preferences → Tools → **JOC decoder**:
Preferences → Tools → **JOC 解码器**:
* **Output** —— 双耳,或 2.0 到 7.1 的扬声器布局;
* **Binaural mode**(near / mid / far)与房间 **tail** 秒数;
* **HRTF source** —— **SOFA** 文件或 **Rosella** `.personalized_headphone` 模型。路径留空表示
用默认位置 `<组件目录>\HRTF\` 下的 `binaural.sofa` 或 `binaural.personalized_headphone`;
* **Gain** —— 开关加 dB 值。双耳渲染在核心混音不削顶的素材上也可能超过满刻度,衰减放在这里;
* **ffmpeg** 可执行文件路径。
* **输出** —— **双耳(HRTF)**,或 **扬声器布局**:2.0 到 9.1.6,布局名与声道顺序见[下表](#扬声器布局与声道顺序);
* **双耳模式**(near / mid / far)与房间**尾音**秒数;
* **HRTF** —— **Rosella 个性化模型**。路径留空表示用默认位置
`<组件目录>\HRTFinaural.personalized_headphone`;
* **增益** —— 开关加 dB 值。双耳渲染在核心混音不削顶的素材上也可能超过满刻度,衰减放在这里;
* **强制 24bit 输出(int24)** —— 默认关闭,交付 float32。打开后,交付前按内核写 WAV 的 int24
规则量化(截到 ±1 → ×8388607 → 截断),超范围的样本被截断到边缘、次数记进日志;组件同时把该
文件的技术信息报成 24bit 定点。渲染本身仍是 float32,这一项说的是交付给 foobar2000 的采样精度,
不是输出设备的位深(那个在 Preferences → Output 里设置)。**切换这个开关后要刷新文件信息**
(Properties → Reload info,或把文件从媒体库移除后重新加入):foobar2000 按文件缓存技术信息,
缓存没刷新时 Properties 与转换器仍按旧的 32bit 浮点判断,会提示"编码器不支持浮点输入"。
* **交换侧环绕与后环绕声道** —— 默认关闭。打开后,交付前把 `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 交付都生效。
* **接管普通 PCM 源(ffmpeg 解码)** —— 默认关闭。打开后接管
`wav/flac/mp3/aac/ogg/opus/wma/aif/aiff/ac3/dts/dtshd/dtsma/wv/ape/tta/mpc/au/snd/caf/thd/mlp/truehd`,
由 ffmpeg 唯一负责解码到 48 kHz float32,再交给内核的 PCM layout 输入做 2.0/5.1/7.1 的 binaural 渲染;
此时不再把这个文件交给其他解码器。TrueHD/MLP 也接管;带 Atmos 的 TrueHD 经 ffmpeg 解成 PCM 后对象信息会丢失,暂按普通多声道处理。TrueHD 在 MKV 等容器里同样走容器回退,不受扩展名列表限制。DSD(`.dsf/.dff`)不在接管范围。
`.mp4/.m4a/.mkv/.mka/.mov/.webm` 仍先做 JOC 检测,非 JOC 的 E-AC-3 音轨才回退到 ffmpeg。
如果内置解码器在 foobar2000 的 input priority 里排在前面,WAV/AC3/MP3 等文件会先被内置解码器拿走,
本组件不会收到 open 调用;需要把 **JOC decoder** 提到对应内置解码器之前。
* **Dolby Dialnorm 响度均衡(-31 dBFS)** —— 默认关闭。打开后只对 ffmpeg 解码的 E-AC-3 5.1 core 施加 `-target_level -31`,
用于按码流 dialnorm 做响度均衡;普通 PCM 和 7 声道 core 不受影响。
* **ffmpeg.exe** 可执行文件路径。
* **界面语言** —— **跟随系统** / **简体中文** / **English**。设置页的全部文字、状态行和用户可见的
错误信息都用这一项选定的语言,切换后立刻生效;选择存在组件自己的配置里。"跟随系统"按 Windows 的
界面语言决定:中文(含繁体)用简体中文,其它语言用英文。这一项只影响界面文字,解码与渲染不读它。
页面上的控件都不禁用,状态行会说明当前生效的是什么。
页面上的控件都不禁用,状态行会说明当前生效的是什么。中文页面的控件名与上表一致,英文页面是同一些
控件的译文(例如 **Output**、**Speaker layout**、**Binaural mode**、**HRTF file**、**Apply gain**)。
### HRTF 数据
SOFA 测量集或个性化耳机模型由使用组件的人自己提供,并且写在 `.gitignore` 里,避免误提交。
个性化耳机模型(`HRTF\binaural.personalized_headphone`)由使用组件的人自己提供,并且写在 `.gitignore` 里,避免误提交。
扬声器布局不需要 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
@@ -78,20 +138,32 @@ pwsh -File tools/package.ps1 # 两个架构,打包到 dist\*.fb2k-c
配置固定为 `Release-Static`(静态 CRT,`/MT`);`/fp:precise` 是逐字节验收的前提,不要改。
`foo_input_joc.vcxproj` 通过项目引用先构建 `kernel\joc_kernel.vcxproj`;`kernel/` 里的渲染内核
源码以 `JOC_STATIC` / `EJOC_STATIC` 编译,入口既不导入也不导出。`tests\` 是离线工具(码流
自检与交叉核对、渲染比对、设置页布局检查、容器探测检查),`tools\` 是构建与测试床脚本。设置项
另有 `JOC_*` 环境变量覆盖(仅用于开发运行),清单与含义在 `src\settings.cpp`。
自检与交叉核对、渲染比对、布局表与频道顺序检查、设置页布局检查、中英文文字宽度检查、容器探测
检查),`tools\` 是构建与测试床脚本。设置项另有 `JOC_*` 环境变量覆盖(仅用于开发运行),清单与含义在 `src\settings.cpp`。
排查问题看 DLL 旁边的 `joc_decoder.log`;组件启动时会把自己的版本、核心版本、日志路径写在
里面。
里面。日志按**字节**封顶:单个文件写满 16 MiB 就滚到同目录的 `joc_decoder.log.1`(覆盖上一次
滚动,不累积),所以两份加起来不超过 32 MiB,最新的内容始终在 `joc_decoder.log`。滚动之后版本
信息会重写一遍。媒体库扫描会给库里每个容器写日志,体量主要来自这里。
## 已知限制
* 不实现 ADM BWF 输出。
* 扬声器布局到 9.1.6(16 声道)为止;内核输出上限就是 16 声道,见
[扬声器布局与声道顺序](#扬声器布局与声道顺序)。
* 多声道布局在 Properties 里不声明扬声器位置,播放时的块内映射只是 foobar2000 对该声道数的
默认值;输出映射要按声道编号自行完成(同上)。
* $joc\_dmx\_config\_idx$ 全部五个档位都支持:取床按音频帧配对,床通道数由档位决定(0/3
为 6 通道,1/2/4 为 8 通道),ffmpeg 只在 6 通道档位传 `-ac 6`。AC-3 核心 + 依赖子流
(`strmtyp=1`)与"首个音频帧没有 JOC"都按正常情况处理。
* 容器只有在它排在内置容器读取器之前时才会被接管(见[安装](#容器需要调一次解码器顺序));核心
不允许某个解码器去要一个已经被别的条目拿走的文件。这类文件的标签也仍旧归那个读取器。
* 裸流 `.eac3` / `.ec3` 的标签(流前面的 ID3v2,或后面的 APEv2/ID3v1)**能读不能写**:没有
组件声明可以写裸 E-AC-3,为插入标签重写整个文件也不是本组件该做的事。
* 传输流(`.ts`、`.m2ts`)不接管。
* **强制 24bit 输出**只改变解码器交付的采样精度:交付的 int24 会被 foobar2000 转成它内部的
浮点,输出设备用什么位深仍由 Preferences → Output 决定,组件不能替它选。超出 ±1 的样本按内核
的 `continue` 策略截断(双耳渲染可能超过满刻度,需要衰减时用 **Gain**)。
* 播放长度严格等于文件时长。双耳渲染器仍会算出房间尾音,但它不作为文件本身没有的播放时间交付。
* 跳转会从包含目标位置的那个帧重新进入码流,而不是把前面的内容全部解码一遍——这是跳转代价与
目标位置无关的原因。位置精确、不漂移;样本是同一段波形交给了从该处开始的解码器,与从头播放
@@ -99,5 +171,6 @@ pwsh -File tools/package.ps1 # 两个架构,打包到 dist\*.fb2k-c
## 许可
`LICENSE` 是上游 MIT 许可,原样复制;`kernel/` 是上游渲染内核源码的副本,保留其声明。见
`LICENSE` 是上游 MIT 许可,原样复制;`kernel/` 是上游渲染内核源码的副本,同步自 JustOneCacophonyCXX 的
1.3.4 版本,保留其声明。见
[THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。
+13 -25
View File
@@ -1,31 +1,11 @@
# Third-party notices / 第三方通知
本仓库包含 JustOneCacophony 原生库的逐字节副本(下称"复用文件"),以及遵循公开标准实现的
滤波器组表。本文件记录这些来源、公开标准依据与权利边界。
本文件记录 64-QMF / 77-hybrid 滤波器组表(`kernel/src/hrtf/public_filterbank.h`、
`kernel/src/joc_core/qmf_tables.h`)与 JOC Huffman 表
(`kernel/src/joc_bitstream/joc_huffman_tables.h`)的公开标准来源,以及 HRTF 数据与
专利的边界说明。
## 复用文件
以下文件是本项目(JustOneCacophony,MIT)原生 C++ 库的逐字节副本,不修改、不追加注释:
| 本仓库路径 | 上游路径 | SHA-256(前 16 位) |
|---|---|---|
| `src/joc_core/eac3joc_core.cpp` | `native/src/eac3joc_core.cpp` | `1978eea64a2616fa` |
| `src/joc_core/qmf_tables.h` | `native/src/qmf_tables.h` | `c205ea187e956e87` |
| `src/speaker/speaker_renderer.cpp` | `native/src/speaker_renderer.cpp` | `96f36f40daf86eec` |
| `src/speaker/speaker_layouts.h` | `native/src/speaker_layouts.h` | `51e24c11be09787f` |
| `src/binaural/binaural_renderer.cpp` | `native/src/binaural_renderer.cpp` | `d579803f0f5a6699` |
| `src/joc_bitstream/joc_huffman_tables.h` | `native/src/joc_huffman_tables.h` | `698498b3778d88db` |
| `include/eac3joc_core.h` | `native/include/eac3joc_core.h` | `7392f48dfd840656` |
上游修订:`6bc2c2885666bb151bb66af93472199af9a99b81`。
## 派生文件
`src/binaural/sofa_binaural_renderer.cpp` 是上游 `native/src/sofa_binaural_renderer.cpp` 的派生
实现:同一 `ejoc_sofa_binaural_*` C ABI,增加表提升、结果记忆化、输入校验与 SIMD 派发。它
**不属于**逐字节副本,也不受"不得修改"约束,但来源固定为上述上游修订,对应上游源文件的
SHA-256 为 `81b485e4c71907672ab308ddc382284acf29161cee93d7906785a4cce58941c7`,输出与原
实现逐位相同(见该文件头部的验证记录)。
`kernel/` 整体是 JustOneCacophonyCXX 1.3.4 的逐字副本。
## 公开标准来源
@@ -52,6 +32,14 @@ $$Y_p = \sum_{q\in C_p}\Bigl(\mathrm{Re}X_q + j\,s_q\,\mathrm{Im}X_q\Bigr),\qqua
相同数值可在 FFmpeg(`aacps_tablegen.h`、`aacsbrdata.h`)等公开实现中查到。
### AC-3 / E-AC-3 传输层与通道码表
`kernel/src/eac3_transport/eac3_reader.cpp` 的 AC-3 同步帧长度表由 A/52 的
`fscod`/`frmsizecod` 比特率表换算得到(48/44.1/32 kHz 三列),E-AC-3 帧长用标准
`frmsiz` 字段;`kernel/src/joc_bitstream/joc_parser.cpp` 的 16 bit `chanmap` 位表与
A/52 `acmod` 通道序来自 **ATSC A/52 Annex E**(等同 ETSI TS 102 366 Annex E)的
Table E2.5 / `chanmap` 定义。这些表是按公开标准写的数值,不含任何第三方实现代码。
## HRTF 数据与 `.jochrtf`
`.jochrtf` 含有特定源 SOFA/HRTF 数据集的变换系数与 delay;其使用、复制与再分发仍受源
+6 -1
View File
@@ -80,7 +80,7 @@
-->
<PreprocessorDefinitions>NDEBUG;_WINDLL;WIN32_LEAN_AND_MEAN;NOMINMAX;_CRT_SECURE_NO_WARNINGS;JOC_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ForcedIncludeFiles>$(ProjectDir)src\joc_pch.h;%(ForcedIncludeFiles)</ForcedIncludeFiles>
<AdditionalIncludeDirectories>$(ProjectDir)src;$(ProjectDir)SDK\foobar2000;$(ProjectDir)SDK;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>$(ProjectDir)src;$(ProjectDir)kernel\include;$(ProjectDir)kernel\src;$(ProjectDir)SDK\foobar2000;$(ProjectDir)SDK;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<DisableSpecificWarnings>4100;4127;%(DisableSpecificWarnings)</DisableSpecificWarnings>
</ClCompile>
<Link>
@@ -99,6 +99,8 @@
<ClCompile Include="src\eac3_scan.cpp" />
<ClCompile Include="src\input_joc.cpp" />
<ClCompile Include="src\joc_decode.cpp" />
<ClCompile Include="src\pcm_source.cpp" />
<ClCompile Include="src\lang.cpp" />
<ClCompile Include="src\log.cpp" />
<ClCompile Include="src\main.cpp" />
<ClCompile Include="src\prefs.cpp" />
@@ -109,11 +111,14 @@
<ClInclude Include="src\container_scan.h" />
<ClInclude Include="src\eac3_scan.h" />
<ClInclude Include="src\joc_decode.h" />
<ClInclude Include="src\pcm_source.h" />
<ClInclude Include="src\joc_pch.h" />
<ClInclude Include="src\lang.h" />
<ClInclude Include="src\log.h" />
<ClInclude Include="src\prefs.h" />
<ClInclude Include="src\resource.h" />
<ClInclude Include="src\settings.h" />
<ClInclude Include="src\win_path.h" />
</ItemGroup>
<ItemGroup>
+162 -35
View File
@@ -3,19 +3,22 @@
#include <stdint.h>
/* EJOC_STATIC: this branch exists for building the sources directly into an application, where nothing is imported or exported. */
#if defined(_WIN32)
#define EJOC_CALL __cdecl
#else
#define EJOC_CALL
#endif
#if defined(EJOC_STATIC)
#define EJOC_API
#define EJOC_CALL __cdecl
#elif defined(_WIN32)
#if defined(EJOC_BUILD_DLL)
#define EJOC_API __declspec(dllexport)
#else
#define EJOC_API __declspec(dllimport)
#endif
#define EJOC_CALL __cdecl
#else
#define EJOC_API __attribute__((visibility("default")))
#define EJOC_CALL
#endif
#ifdef __cplusplus
@@ -23,17 +26,21 @@ extern "C" {
#endif
enum {
EJOC_ABI_VERSION = 1,
EJOC_ABI_VERSION = 4,
EJOC_FRAME_SAMPLES = 1536,
EJOC_TIMESLOTS = 24,
EJOC_SUBBANDS = 64,
EJOC_CORE_CHANNELS = 5,
EJOC_CORE_CHANNELS = 5, /* downmix configurations 0 and 3 */
EJOC_MAX_CORE_CHANNELS = 7, /* downmix configurations 1, 2 and 4 */
EJOC_OUTPUT_CHANNELS = 16,
EJOC_CORE_OUT_CHANNELS = 8, /* passthrough order: L,R,C,LFE,Ls,Rs,(Lrs,Rrs) */
EJOC_LFE_SLOT = 3, /* LFE slot of the passthrough order */
EJOC_MAX_OBJECTS = 15,
EJOC_MAX_DPOINTS = 2,
EJOC_MAX_PARAMETER_BANDS = 23,
EJOC_SPEAKER_BLOCK_SAMPLES = 32,
EJOC_SPEAKER_COORDINATES = 3,
EJOC_SPEAKER_CONTROLS_VERSION = 1,
EJOC_BINAURAL_BLOCK_SAMPLES = 512,
EJOC_BINAURAL_INPUT_CHANNELS = 16,
EJOC_BINAURAL_OUTPUT_CHANNELS = 2,
@@ -41,21 +48,39 @@ enum {
EJOC_BINAURAL_HYBRID_BANDS = 77
};
/* Per-frame status of ejoc_renderer_render_frame(). A status outside 0..6 is
* the renderer's own no-metadata marker; the parse-status values match
* joc_frame_params.status (JOC_FRAME_STATUS_* in joc_core.h). Any non-zero
* status makes the frame invalid for matrix rendering: the renderer holds the
* previous matrices or passes the core PCM through instead of decoding it. */
enum {
EJOC_FRAME_STATUS_OK = 0,
EJOC_FRAME_STATUS_UNSUPPORTED_DMX = 2,
EJOC_FRAME_STATUS_OBJECTS_CLAMPED = 3,
EJOC_FRAME_STATUS_BAD_PARAMETER_BAND = 4,
EJOC_FRAME_STATUS_BAD_OFFSET_TS = 5,
EJOC_FRAME_STATUS_TRAILING_DATA = 6,
EJOC_FRAME_STATUS_NO_METADATA = 8
};
typedef void* ejoc_renderer_handle;
typedef void* ejoc_speaker_renderer_handle;
typedef void* ejoc_binaural_renderer_handle;
/*
Fixed array layouts used by ejoc_renderer_process():
bed5_planar [5][1536]
bed_planar [core_channel_count][1536]
lfe [1536] or NULL
n_bands [15]
n_dpoints [15]
slope_idx [15]
offset_ts [15][2]
dq [15][2][5][23]
dq [15][2][7][23]
output16 [16][1536]
core_channel_count comes from ejoc_renderer_set_core_channels() and defaults to
EJOC_CORE_CHANNELS; the dq stride is always EJOC_MAX_CORE_CHANNELS.
Only objects selected by object_mask are read from the descriptor arrays.
dq carries already dequantized matrix coefficients in double precision; the
caller performs the JOC bitstream differential decoding for both dense and
@@ -69,21 +94,24 @@ EJOC_API void EJOC_CALL ejoc_renderer_destroy(ejoc_renderer_handle handle);
EJOC_API int EJOC_CALL ejoc_renderer_reset(ejoc_renderer_handle handle);
EJOC_API int EJOC_CALL ejoc_renderer_set_threads(ejoc_renderer_handle handle, uint32_t total_threads);
/*
Enables or disables the Ls/Rs band-0 21-tap DC compensation. The caller derives
it from the JOC downmix configuration: only configurations 3 and 4 enable the
filter. When disabled, band 0 keeps the common per-band processing (surround
delay plus -j rotation) instead of being overwritten by the FIR. The delay line
and DC history advance either way, so the flag may change between frames.
Defaults to enabled when never called.
core_channel_count comes from joc_dmx_config_idx: 5 for configurations 0 and 3,
7 for 1, 2 and 4. bed_planar is then [core_channel_count][1536] and only channels
below core_channel_count are read from dq, whose stride stays [15][2][7][23].
phase_shift is sigma(k) = (k in {3,4}): it enables the Ls/Rs -j rotation of
subbands above 0 together with the band-0 21-tap DC compensation. With the switch
off, channels 3 and 4 only take the common ten-slot surround delay. The delay
line and DC history advance either way, so the flag may change between frames.
*/
EJOC_API int EJOC_CALL ejoc_renderer_set_dc_filter(ejoc_renderer_handle handle, uint32_t enabled);
EJOC_API uint32_t EJOC_CALL ejoc_renderer_thread_count(ejoc_renderer_handle handle);
EJOC_API const char* EJOC_CALL ejoc_renderer_last_error(ejoc_renderer_handle handle);
EJOC_API int EJOC_CALL ejoc_renderer_process(
ejoc_renderer_handle handle,
const float* bed5_planar,
const float* bed_planar,
const float* lfe,
uint32_t core_channel_count,
uint32_t phase_shift,
uint32_t object_mask,
const uint8_t* n_bands,
const uint8_t* n_dpoints,
@@ -95,6 +123,63 @@ EJOC_API int EJOC_CALL ejoc_renderer_process(
float output_scale,
float* output16_planar);
/*
Frame-level entry point: one E-AC-3 audio frame per call, with the seq state
machine and the per-object previous-matrix state kept inside the renderer. This
is what produces the 16-channel object result for the ADM, speaker and binaural
backends; ejoc_renderer_process() stays as a single-frame kernel for A/B tests.
Fixed array layouts, identical to ejoc_renderer_process():
bed_planar [core_channel_count][1536] (JOC lane order L,R,C,Ls,Rs,(pair))
lfe [1536] or NULL (zeros; the LFE delay ring still advances)
n_bands, n_dpoints, slope_idx [15]
offset_ts [15][2] (raw 5-bit JOC offsets, 0..23)
dq [15][2][7][23]
output16 [16][1536] (ch0 = LFE, ch1..15 = objects)
frame_status is a JOC_FRAME_STATUS_* / EJOC_FRAME_STATUS_* value. has_metadata
is 0 for an audio frame without a JOC EMDF container (frame_status must then be
EJOC_FRAME_STATUS_NO_METADATA); such a frame always passes the 8 core planes
through to output slots 0..7, delayed by 1217 samples, with slots 8..15 zero.
declared_core_channels is the JOC header's n_channels (0 when unknown); a declared
change against the previous frame's actual count turns the frame into a hard cut
with the LFE ring cleared. phase_shift is sigma(k) = (k in {3,4}) for the frame's
downmix configuration; phase_shift_valid = 0 keeps the previous switch (an
unsupported downmix configuration has no usable one). clipgain is the frame's
joc_clipgain when frame_status == 0. seq is the 10-bit JOC sequence counter.
When has_metadata is 0 the object descriptors are ignored.
Slot 0 of output16 is the LFE, slots 1..15 are the 15 objects; each frame's
values are float32(clamped PCM) * output_scale, exactly like the reference.
*/
typedef struct ejoc_frame_input {
uint32_t struct_size;
uint32_t struct_version;
const float* bed_planar;
const float* lfe;
uint32_t core_channel_count;
uint32_t declared_core_channels;
uint32_t phase_shift;
uint32_t phase_shift_valid;
uint32_t frame_status;
uint32_t seq;
uint32_t has_metadata;
uint32_t object_mask;
const uint8_t* n_bands;
const uint8_t* n_dpoints;
const uint8_t* slope_idx;
const uint8_t* offset_ts;
const double* dq;
double clipgain;
float output_scale;
float* output16_planar;
} ejoc_frame_input;
enum { EJOC_FRAME_INPUT_VERSION = 1 };
EJOC_API int EJOC_CALL ejoc_renderer_render_frame(ejoc_renderer_handle handle,
const ejoc_frame_input* input);
/*
High-precision object-to-speaker renderer.
@@ -116,6 +201,47 @@ metadata_offsets must be nondecreasing and <= sample_count. sample_count must
be a multiple of EJOC_SPEAKER_BLOCK_SAMPLES. State and unfinished ramps are
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). Modes 2 and 3 render the 5.1-family and 4.0 layouts through an
expanded surround layout (7.1-family, or a rear pair added to 4.0 without a
centre or LFE) and fold the rear pair into the target surround pair: mode 2
uses the PLIIx coefficients (sqrt(3)/2 and 1/2), mode 3 the Standard (Lo/Ro)
coefficients (1 and 0). Layouts without a single surround pair render directly.
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 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);
@@ -132,6 +258,7 @@ EJOC_API int EJOC_CALL ejoc_speaker_renderer_process(
const uint8_t* region_indices,
const uint8_t* height_enabled,
const double* object_gains,
const ejoc_speaker_controls* controls,
double* output_interleaved);
EJOC_API ejoc_binaural_renderer_handle EJOC_CALL ejoc_binaural_renderer_create(void);
@@ -181,19 +308,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
the 961-sample latency compensation. The caller configures the filterbank
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
ejoc_sofa_binaural_process(). Process returns the number of trimmed stereo
block updates every source with ejoc_jochrtf_set_source() and calls
ejoc_jochrtf_process(). Process returns the number of trimmed stereo
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 void EJOC_CALL ejoc_sofa_binaural_destroy(ejoc_sofa_binaural_handle handle);
EJOC_API int EJOC_CALL ejoc_sofa_binaural_reset(ejoc_sofa_binaural_handle handle);
EJOC_API const char* EJOC_CALL ejoc_sofa_binaural_last_error(
ejoc_sofa_binaural_handle handle);
EJOC_API int EJOC_CALL ejoc_sofa_binaural_configure_kernels(
ejoc_sofa_binaural_handle handle,
EJOC_API ejoc_jochrtf_handle EJOC_CALL ejoc_jochrtf_create(void);
EJOC_API void EJOC_CALL ejoc_jochrtf_destroy(ejoc_jochrtf_handle handle);
EJOC_API int EJOC_CALL ejoc_jochrtf_reset(ejoc_jochrtf_handle handle);
EJOC_API const char* EJOC_CALL ejoc_jochrtf_last_error(
ejoc_jochrtf_handle handle);
EJOC_API int EJOC_CALL ejoc_jochrtf_configure_kernels(
ejoc_jochrtf_handle handle,
const double* qmf_analysis,
const double* hybrid_low,
const int16_t* hybrid_indices,
@@ -201,15 +328,15 @@ EJOC_API int EJOC_CALL ejoc_sofa_binaural_configure_kernels(
uint32_t hybrid_count,
const double* qmf_basis,
const double* qmf_taps);
EJOC_API int EJOC_CALL ejoc_sofa_binaural_configure_field(
ejoc_sofa_binaural_handle handle,
EJOC_API int EJOC_CALL ejoc_jochrtf_configure_field(
ejoc_jochrtf_handle handle,
const double* coefficients,
const double* delay_coefficients,
const double* delay_bounds,
const double* band_centers,
double measurement_radius_m);
EJOC_API int EJOC_CALL ejoc_sofa_binaural_configure_room(
ejoc_sofa_binaural_handle handle,
EJOC_API int EJOC_CALL ejoc_jochrtf_configure_room(
ejoc_jochrtf_handle handle,
const double* room_dims,
const double* listener_pos,
const double* wall_gains,
@@ -222,8 +349,8 @@ EJOC_API int EJOC_CALL ejoc_sofa_binaural_configure_room(
const double* allpass_gains,
uint32_t enable_early_reflections,
uint32_t enable_late_room);
EJOC_API int EJOC_CALL ejoc_sofa_binaural_set_source(
ejoc_sofa_binaural_handle handle,
EJOC_API int EJOC_CALL ejoc_jochrtf_set_source(
ejoc_jochrtf_handle handle,
uint32_t source,
const double* position_adm,
uint32_t profile,
@@ -231,14 +358,14 @@ EJOC_API int EJOC_CALL ejoc_sofa_binaural_set_source(
uint32_t enabled,
uint32_t special_lfe,
uint32_t fade);
EJOC_API int EJOC_CALL ejoc_sofa_binaural_process(
ejoc_sofa_binaural_handle handle,
EJOC_API int EJOC_CALL ejoc_jochrtf_process(
ejoc_jochrtf_handle handle,
const double* input16_interleaved,
uint32_t sample_count,
double output_gain,
double* output_stereo_interleaved);
EJOC_API int EJOC_CALL ejoc_sofa_binaural_finish(
ejoc_sofa_binaural_handle handle,
EJOC_API int EJOC_CALL ejoc_jochrtf_finish(
ejoc_jochrtf_handle handle,
uint32_t flush_samples,
double* output_stereo_interleaved,
uint32_t capacity);
+64 -34
View File
@@ -34,27 +34,32 @@
#include <stdint.h>
#include <stddef.h>
#define JOC_ABI_VERSION 3u
#define JOC_FRAME_PARAMS_VERSION 1u
#define JOC_EMDF_INFO_VERSION 1u
#define JOC_TASK_CONFIG_VERSION 3u
#include "joc_version.h"
#define JOC_ABI_VERSION 6u
#define JOC_FRAME_PARAMS_VERSION 2u
#define JOC_EMDF_INFO_VERSION 2u
#define JOC_TASK_CONFIG_VERSION 4u
#define JOC_TASK_RESULT_VERSION 2u
#define JOC_EVENT_VERSION 1u
/* JOC_STATIC: this branch exists for building the sources directly into an application, where nothing is imported or exported. */
#if defined(_WIN32)
#define JOC_CALL __cdecl
#else
#define JOC_CALL
#endif
#if defined(JOC_STATIC)
#define JOC_API
#define JOC_CALL __cdecl
#elif defined(_WIN32)
#if defined(JOC_BUILD_DLL)
#define JOC_API __declspec(dllexport)
#else
#define JOC_API __declspec(dllimport)
#endif
#define JOC_CALL __cdecl
#else
#define JOC_API __attribute__((visibility("default")))
#define JOC_CALL
#endif
#ifdef __cplusplus
@@ -80,7 +85,7 @@ enum {
JOC_BINAURAL_QMF_BANDS = 64,
JOC_BINAURAL_HYBRID_BANDS = 77,
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
};
@@ -150,8 +155,7 @@ JOC_API const char* JOC_CALL joc_last_error_detail(void);
typedef struct joc_emdf_payload_info {
uint8_t id;
uint8_t reserved[3];
uint16_t sample_offset; /* EMDF outer smpoffst, 11 bits */
uint16_t reserved2;
uint32_t sample_offset; /* EMDF outer smpoffst: variable_bits(11) */
uint32_t bit_offset;
uint32_t size; /* payload bytes */
} joc_emdf_payload_info;
@@ -168,7 +172,8 @@ typedef struct joc_emdf_info {
/* Per-object ID14/JOC descriptor plus its dequantized matrix.
* dq[dp][ch][pb] is zero filled outside [0,n_dpoints) x [0,n_channels) x
* [0,n_bands). Absent objects are entirely zero. */
* [0,n_bands). Absent objects are entirely zero. offset_ts holds the raw
* 5-bit JOC offsets (legal range 0..23, strictly increasing per object). */
typedef struct joc_object_params {
uint8_t present;
uint8_t num_bands_idx;
@@ -183,6 +188,26 @@ typedef struct joc_object_params {
double dq[JOC_MAX_DPOINTS][JOC_MAX_CORE_CHANNELS][JOC_MAX_PARAMETER_BANDS];
} joc_object_params;
/* Per-frame JOC parse status (joc_frame_params.status). A non-zero status makes
* the frame invalid for rendering: the renderer holds the previous matrices or
* passes the core PCM through instead of decoding the matrix. Statuses 3 and 7
* still carry the complete header and object list for diagnostics; statuses 2
* and 4 stop the parse after the failing header field, and 7 stops inside
* joc_data, so only the per-object matrices are missing there. */
enum {
JOC_FRAME_STATUS_OK = 0,
JOC_FRAME_STATUS_UNSUPPORTED_DMX = 2, /* joc_dmx_config_idx outside 0..4 */
JOC_FRAME_STATUS_OBJECTS_CLAMPED = 3, /* declared object count above 15 */
JOC_FRAME_STATUS_BAD_PARAMETER_BAND = 4, /* unknown num_bands index */
JOC_FRAME_STATUS_BAD_OFFSET_TS = 5, /* offset_ts outside 0..23 or not */
/* strictly increasing */
JOC_FRAME_STATUS_TRAILING_DATA = 6, /* bytes after joc_data alignment */
/* The ID14 payload ends before its joc_data is complete. The header,
* clipgain, sequence counter and object parameters are intact, so the frame
* stays classified and is concealed by holding the previous matrices. */
JOC_FRAME_STATUS_TRUNCATED = 7
};
typedef struct joc_frame_params {
uint32_t struct_size;
uint32_t struct_version;
@@ -193,22 +218,30 @@ typedef struct joc_frame_params {
uint8_t n_channels; /* 5 or 7 */
uint8_t clipgain_x_bits;
uint8_t clipgain_y_bits;
uint8_t reserved;
uint32_t seq_count; /* 10-bit JOC sequence counter, parsed only */
uint8_t objects_clamped; /* num_objects_bits+1 exceeded 15 */
uint32_t seq_count; /* 10-bit JOC sequence counter */
uint32_t present_mask; /* bit i == object i present */
uint8_t status; /* JOC_FRAME_STATUS_* */
uint8_t reserved[3];
uint32_t data_end_bits; /* bit position just after joc_data */
uint32_t trailing_bits; /* bits left after joc_data (padding/ext) */
uint8_t tail_bytes[8]; /* first up to 8 trailing bytes, for A/B */
double clipgain; /* 1 + (y/32) * 2^(x-4), bit-exact */
double clipgain; /* 2^(x-4) * (1 + y/32), bit-exact */
joc_object_params objects[JOC_MAX_OBJECTS];
} joc_frame_params;
/* Parse an EMDF ID14 (JOC) payload. */
/* Parse an EMDF ID14 (JOC) payload. A payload that ends inside joc_data is a
* damaged frame rather than a transport error: the call succeeds, the header and
* object parameters are filled in, and out_params->status is
* JOC_FRAME_STATUS_TRUNCATED. A payload too short for the 12-bit joc_header is
* unclassifiable and stays JOC_ERR_BITSTREAM_TRUNCATED. */
JOC_API joc_error JOC_CALL joc_parse_id14(const uint8_t* payload, size_t payload_size,
joc_frame_params* out_params);
/* Locate the contiguous JOC EMDF container inside one E-AC-3 syncframe and
* parse its ID14 payload. out_emdf may be NULL. */
* parse its ID14 payload. out_emdf may be NULL. A damaged ID14 payload is
* reported through out_params->status like joc_parse_id14(); an incomplete
* container stays a transport error. */
JOC_API joc_error JOC_CALL joc_parse_eac3_frame(const uint8_t* frame, size_t frame_size,
joc_frame_params* out_params,
joc_emdf_info* out_emdf);
@@ -229,7 +262,8 @@ JOC_API joc_error JOC_CALL joc_eac3_frame_bytes(const uint8_t* data, size_t size
/* Strict trailing-bit check for the JOC payload (A/B robustness corpus).
* Returns JOC_ERR_BITSTREAM_PADDING when more than 7 bits are left over or the
* leftover bits are not zero. */
* leftover bits are not zero, and JOC_ERR_BITSTREAM_TRUNCATED when the payload
* ends inside joc_data. */
JOC_API joc_error JOC_CALL joc_check_id14_padding(const uint8_t* payload, size_t payload_size,
uint32_t* out_trailing_bits);
@@ -356,13 +390,14 @@ typedef enum joc_clip_action {
JOC_CLIP_ABORT = 3 /* fail the task */
} joc_clip_action;
/* Compiled-HRTF cache policy for a SOFA input; the .jochrtf itself is an
* internal artifact of the compile step. */
typedef enum joc_hrtf_cache_policy {
JOC_HRTF_CACHE_NONE = 0, /* compile and discard */
JOC_HRTF_CACHE_MEMORY = 1, /* compile and keep in this process (default) */
JOC_HRTF_CACHE_DISK = 2 /* compile, reuse and write <cache_dir>/<name>.jochrtf */
} joc_hrtf_cache_policy;
/* Which 64-QMF / 77-hybrid filterbank the Rosella .personalized_headphone path
* renders through. The two banks differ in coefficients, hybrid tap count,
* high-band slot delay and total latency, so they are not interchangeable; the
* SOFA and .jochrtf paths always use JOC_ROSELLA_FILTERBANK_PUBLIC. */
typedef enum joc_rosella_filterbank {
JOC_ROSELLA_FILTERBANK_PUBLIC = 1, /* 13-tap hybrid, 6-slot delay, 961 samples */
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,
JOC_TASK_F_QUIET = 4u, JOC_TASK_F_METADATA_ONLY = 8u };
@@ -373,7 +408,7 @@ typedef struct joc_task_config {
/* input */
const char* input_path; /* .eac3/.ec3/.m4a/... */
const char* ffmpeg_path; /* NULL = "ffmpeg" from PATH */
const char* ffmpeg_path; /* NULL = FFMPEG, then "ffmpeg" on PATH */
const char* bed_path; /* NULL = decode the core PCM with ffmpeg */
const char* work_dir; /* NULL = a temporary directory */
double eac3_drc_scale; /* 0 = DRC off (reference default) */
@@ -413,16 +448,11 @@ typedef struct joc_task_config {
joc_cancel_token* cancel; /* optional */
/* Binaural HRTF input (config version 2): when hrtf_sofa_path is set the
* library compiles it with hrtf_cache_policy / hrtf_cache_dir / hrtf_radius_m
* and hrtf_path is unused. hrtf_path stays the advanced override that reads
* a .jochrtf directly. */
const char* hrtf_sofa_path; /* SOFA SimpleFreeFieldHRIR input */
/* Binaural input (config version 2): a compiled .jochrtf field (hrtf_path)
* or a Rosella .personalized_headphone model. */
const char* personalized_headphone_path; /* Rosella .personalized_headphone input */
const char* hrtf_cache_dir; /* disk policy directory */
uint32_t hrtf_cache_policy; /* joc_hrtf_cache_policy */
uint32_t reserved0;
double hrtf_radius_m; /* SOFA measurement-radius shell */
uint32_t rosella_filterbank; /* joc_rosella_filterbank; 0 = PUBLIC */
uint32_t jochrtf_room; /* non-zero enables the project room */
} joc_task_config;
typedef enum joc_task_status {
+26 -15
View File
@@ -39,14 +39,15 @@ typedef struct joc_stream joc_stream;
typedef enum joc_stream_input {
JOC_STREAM_IN_EAC3 = 0, /* bare E-AC-3 syncframes (the metadata stream) */
JOC_STREAM_IN_PCM_OBJECTS16 = 1, /* 16-channel objects16, decoded by the host */
JOC_STREAM_IN_CORE_PCM = 3 /* the 5.1 core PCM of the pushed E-AC-3 frames */
JOC_STREAM_IN_PCM_OBJECTS16 = 1, /* objects16 frames, planar [16][1536] each */
JOC_STREAM_IN_CORE_PCM = 3, /* the 5.1 core PCM of the pushed E-AC-3 frames */
JOC_STREAM_IN_PCM_LAYOUT = 4 /* interleaved 48k f32, mapped by pcm_layout */
} joc_stream_input;
typedef enum joc_stream_output {
JOC_STREAM_OUT_PCM_OBJECTS16 = 0, /* planar [16][samples] float32 */
JOC_STREAM_OUT_SPEAKER = 1, /* interleaved [samples][channels] f32 */
JOC_STREAM_OUT_BINAURAL = 2 /* interleaved [samples][2] f32 */
JOC_STREAM_OUT_PCM_OBJECTS16 = 0, /* objects16 frames, planar [16][1536] each */
JOC_STREAM_OUT_SPEAKER = 1, /* interleaved [samples][channels] f32 */
JOC_STREAM_OUT_BINAURAL = 2 /* interleaved [samples][2] f32 */
} joc_stream_output;
typedef struct joc_stream_config {
@@ -63,17 +64,13 @@ typedef struct joc_stream_config {
uint32_t object_delay_samples; /* default 1473 */
double gain_db; /* default 0 */
uint32_t native_threads;
uint32_t reserved;
/* Binaural HRTF input, the same three shapes joc_task_config accepts: when
* hrtf_sofa_path is set the library compiles it with hrtf_cache_policy /
* 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 */
uint32_t rosella_filterbank; /* joc_rosella_filterbank; Rosella input, 0 = PUBLIC */
/* Binaural input, the same shapes joc_task_config accepts: a compiled
* .jochrtf field (hrtf_path) or a Rosella .personalized_headphone model. */
const char* personalized_headphone_path; /* Rosella .personalized_headphone input */
const char* hrtf_cache_dir; /* disk cache directory for SOFA compilation */
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 */
uint32_t jochrtf_room; /* non-zero enables the project room */
/* PCM_LAYOUT input: "2.0", "5.1", "7.1", or NULL/"" to infer by channels. */
const char* pcm_layout;
} joc_stream_config;
typedef struct joc_stream_buffer {
@@ -102,8 +99,22 @@ typedef struct joc_stream_status_info {
uint64_t buffered_samples; /* rendered but not yet pulled, per channel */
uint64_t oamd_payloads;
uint64_t oamd_transitions;
/* Metadata the renderer had to work around, per audio frame: no JOC payload at
* all, an ID14 payload that ends inside joc_data (that frame holds the previous
* matrices), a declared object count clamped to 15, and a syncframe carrying a
* second EMDF container that is not this frame's JOC metadata. */
uint64_t missing_joc_frames;
uint64_t objects_clamped_frames;
uint64_t extra_container_frames;
/* Extra-pair identity disagreements across layers (spec 11.2 checks 1 and 2).
* The identity is metadata only, so those frames still render. */
uint64_t chanmap_pair_mismatch_frames;
uint64_t bed_mask_mismatch_frames;
uint32_t output_channels;
uint32_t ended; /* 1 after flush() */
/* Appended field: joc_stream_status() accepts the size that ends at `ended`
* as well, so a caller built against the previous header keeps working. */
uint64_t truncated_joc_frames;
} joc_stream_status_info;
JOC_API joc_error JOC_CALL joc_stream_create(const joc_stream_config* config, joc_stream** out);
+16
View File
@@ -0,0 +1,16 @@
/* Product version of joc_core and joc_cli.
*
* This file is the single source of truth: CMakeLists.txt reads these numbers for
* project(VERSION ...), joc_version_string() returns JOC_VERSION_STRING, and the
* release workflow refuses a tag that does not match it. Bump the three numbers
* and the string together, then tag the commit with v<JOC_VERSION_STRING>.
*/
#ifndef JOC_VERSION_H
#define JOC_VERSION_H
#define JOC_VERSION_MAJOR 1
#define JOC_VERSION_MINOR 3
#define JOC_VERSION_PATCH 4
#define JOC_VERSION_STRING "1.3.4"
#endif /* JOC_VERSION_H */
+45 -19
View File
@@ -5,10 +5,13 @@
shipping and loading joc_core.dll.
The sources under kernel\src and kernel\include are a verbatim copy of the
upstream library (see JustOneCacophonyCXX\CMakeLists.txt); the only edits are
the JOC_STATIC branch in kernel\include\joc_core.h / joc_stream.h and the
EJOC_STATIC branch in kernel\include\eac3joc_core.h, which turn JOC_API and
EJOC_API into empty macros for a static build.
upstream library at version 1.3.1 (see
JustOneCacophonyCXX\CMakeLists.txt): nothing under either
tree is edited here, and both are kept identical to it, so a single core serves
the upstream tools and this component alike. The static build needs no branch
of its own: JOC_STATIC (kernel\include\joc_core.h / joc_stream.h) and
EJOC_STATIC (kernel\include\eac3joc_core.h) are already part of the shared
headers, turning JOC_API and EJOC_API into empty macros.
Conventions deliberately mirror the component project (foo_input_joc.vcxproj)
and the kernel's own CMake build:
@@ -113,18 +116,17 @@
</ItemDefinitionGroup>
<!--
SIMD units, mirroring CMakeLists.txt (the JOC_SIMD_* block) exactly.
SIMD units, mirroring CMakeLists.txt (the JOC_SIMD_* block).
The ISA in the file name, one translation unit per ISA, each compiled with
its own /arch because MSVC has no function-level ISA attribute; dispatch.cpp
(a baseline unit) picks one at run time from CPUID/XGETBV. The kernel
enables SIMD only for x86_64 and aarch64, so:
(a baseline unit) picks one at run time from CPUID/XGETBV.
* Win32 (x86) gets NO SIMD unit and NO SIMD define: the scalar reference
and the probe/dispatch baseline are all it builds, exactly as
CMAKE_SIZEOF_VOID_P EQUAL 8 gates them out upstream;
* x64 gets the AVX2 and AVX-512 units, JOC_SIMD_HAVE_SSE2 / _AVX2 /
_AVX512, and a per-file /arch for those two files only;
* Win32 (x86) gets the AVX2 unit and JOC_SIMD_HAVE_AVX2: AVX2 is not an
x86-64-only ISA. AVX-512 stays x64-only, because 32-bit mode addresses
ZMM0-7 only.
* src\simd\kernels_intrin_neon.cpp is excluded everywhere here: the CMake
build lists it only for aarch64 (CMakeLists.txt lines 177-180), which no
configuration of this project targets.
@@ -134,6 +136,11 @@
<PreprocessorDefinitions>JOC_SIMD_HAVE_SSE2=1;JOC_SIMD_HAVE_AVX2=1;JOC_SIMD_HAVE_AVX512=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Platform)'=='Win32'">
<ClCompile>
<PreprocessorDefinitions>JOC_SIMD_HAVE_AVX2=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<!-- Verbatim copies of the upstream native library (JOC_REUSED_SOURCES). -->
@@ -143,8 +150,8 @@
<!-- Engine internals (JOC_INTERNAL_SOURCES). -->
<ClCompile Include="src\adm\adm_metadata.cpp" />
<ClCompile Include="src\adm\adm_tracks.cpp" />
<ClCompile Include="src\binaural\binaural_runtime.cpp" />
<ClCompile Include="src\binaural\sofa_binaural_renderer.cpp" />
<ClCompile Include="src\binaural\jochrtf_runtime.cpp" />
<ClCompile Include="src\binaural\jochrtf_renderer.cpp" />
<ClCompile Include="src\eac3_transport\eac3_reader.cpp" />
<ClCompile Include="src\emdf\emdf_parser.cpp" />
<ClCompile Include="src\foundation\bit_reader.cpp" />
@@ -152,14 +159,14 @@
<ClCompile Include="src\foundation\fs_utf8.cpp" />
<ClCompile Include="src\foundation\mini_json.cpp" />
<ClCompile Include="src\foundation\sha256.cpp" />
<ClCompile Include="src\foundation\status.cpp" />
<ClCompile Include="src\hrtf\jochrtf.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_renderer.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\hdf5.cpp" />
<ClCompile Include="src\io\inflate.cpp" />
@@ -168,12 +175,17 @@
<ClCompile Include="src\io\process.cpp" />
<ClCompile Include="src\io\wav_writer.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_core\objects16.cpp" />
<ClCompile Include="src\oamd\oamd_math.cpp" />
<ClCompile Include="src\oamd\oamd_params.cpp" />
<ClCompile Include="src\oamd\oamd_parser.cpp" />
<ClCompile Include="src\speaker\speaker_layout_lookup.cpp" />
<ClCompile Include="src\speaker\speaker_step.cpp" />
<ClCompile Include="src\speaker\speaker_trim.cpp" />
<ClCompile Include="src\stream\stream.cpp" />
<ClCompile Include="src\virtual_speaker\virtual_speaker.cpp" />
<ClCompile Include="src\task\task.cpp" />
<ClCompile Include="src\telemetry\event_bus.cpp" />
<ClCompile Include="src\timeline\position_timeline.cpp" />
@@ -203,30 +215,38 @@
</ClCompile>
</ItemGroup>
<ItemGroup Condition="'$(Platform)'=='Win32'">
<ClCompile Include="src\simd\kernels_intrin_avx2.cpp">
<AdditionalOptions>/arch:AVX2 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="include\eac3joc_core.h" />
<ClInclude Include="include\joc_core.h" />
<ClInclude Include="include\joc_stream.h" />
<ClInclude Include="include\joc_version.h" />
<ClInclude Include="src\adm\adm_metadata.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\emdf\emdf_parser.h" />
<ClInclude Include="src\foundation\bit_reader.h" />
<ClInclude Include="src\foundation\fft.h" />
<ClInclude Include="src\foundation\fs_utf8.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\py_num.h" />
<ClInclude Include="src\foundation\sha256.h" />
<ClInclude Include="src\foundation\status.h" />
<ClInclude Include="src\hrtf\jochrtf.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_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\hdf5.h" />
<ClInclude Include="src\io\inflate.h" />
@@ -235,17 +255,23 @@
<ClInclude Include="src\io\process.h" />
<ClInclude Include="src\io\wav_writer.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_parser.h" />
<ClInclude Include="src\joc_core\objects16.h" />
<ClInclude Include="src\joc_core\qmf_tables.h" />
<ClInclude Include="src\oamd\isf_tables.h" />
<ClInclude Include="src\oamd\oamd_math.h" />
<ClInclude Include="src\oamd\oamd_params.h" />
<ClInclude Include="src\oamd\oamd_parser.h" />
<ClInclude Include="src\simd\cpu_probe.h" />
<ClInclude Include="src\simd\simd.h" />
<!-- 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_trim.h" />
<ClInclude Include="src\speaker\speaker_layouts.h" />
<ClInclude Include="src\speaker\speaker_step.h" />
<ClInclude Include="src\speaker\speaker_meta.h" />
<ClInclude Include="src\stream\stream.h" />
<ClInclude Include="src\task\task.h" />
<ClInclude Include="src\telemetry\event_bus.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);
}
// 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
std::string ts(double seconds) {
@@ -102,7 +163,8 @@ std::string build_chna() {
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) {
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)));
std::string segment9(248, '\0');
const std::string creator = "Created with EAC3JOC";
const std::string renderer = "EAC3JOC Python Renderer";
const std::string creator = "JustOneCacophony";
const std::string renderer = "JustOneCacophony";
std::memcpy(&segment9[0], creator.data(), creator.size());
std::memcpy(&segment9[32], renderer.data(), renderer.size());
segment9[96] = 2;
@@ -136,6 +198,10 @@ Status build_dbmd(std::uint32_t object_count, BinauralMode mode, std::string* ou
segment9[106] = 0x01;
segment9[111] = 0x22;
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);
put_u16(out, 248);
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) {
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;
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;
@@ -168,7 +265,8 @@ Status build_dbmd(std::uint32_t object_count, BinauralMode mode, std::string* ou
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);
std::string out;
out.reserve(64u * 1024u);
@@ -325,6 +423,9 @@ std::string build_axml(const std::vector<Track>& tracks, double duration_sec, st
"_01</audioTrackFormatIDRef>";
out += "</audioStreamFormat>";
}
if (trim != nullptr) {
append_atmos_master_block(*trim, &out);
}
out += "</audioFormatExtended></format></coreMetadata>";
out += "</ebuCoreMain>";
return out;
+9 -2
View File
@@ -7,6 +7,7 @@
#include <vector>
#include "foundation/status.h"
#include "oamd/oamd_parser.h"
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);
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();
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
+43 -32
View File
@@ -4,6 +4,7 @@
#include <cmath>
#include "foundation/geometry.h"
#include "foundation/metadata_timing.h"
namespace joc::adm {
@@ -66,7 +67,7 @@ Status non_monotonic(const char* name, const char* message, int object_index, st
} // namespace
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) {
out->clear();
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) {
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) {
break;
}
const std::int64_t effective_ramp =
std::max<std::int64_t>(0, event.ramp_samples - update_quantum_samples);
const std::int64_t block_start =
event_start + (effective_ramp != 0 ? update_quantum_samples : 0);
const std::int64_t ramp = std::max<std::int64_t>(0, event.ramp_samples);
const std::int64_t block_start = event_start;
if (block_start >= total_samples) {
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) {
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);
}
if (index + 1 < events.size()) {
const std::int64_t next_event_start = events[index + 1].sample + object_delay_samples;
const std::int64_t next_effective =
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);
const std::int64_t next_block_start = timing::align_metadata_sample(
events[index + 1].sample + object_delay_samples, update_block_samples);
if (next_block_start < ramp_end) {
return non_monotonic("overlapping_compact_position_ramps",
"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};
std::int64_t interpolation = effective_ramp;
std::int64_t interpolation = ramp;
const std::int64_t available = total_samples - block_start;
if (effective_ramp > available) {
const double amount =
static_cast<double>(available) / static_cast<double>(effective_ramp);
if (ramp > available) {
const double amount = static_cast<double>(available) / static_cast<double>(ramp);
double x = 0.0;
double y = 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,
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) {
out->clear();
(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) {
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) {
break;
}
@@ -176,20 +173,19 @@ Status expand_dense64(const std::vector<OamdEvent>& events, std::int64_t total_s
if (start > points.back().sample) {
append_point(&points, start, current[0], current[1], current[2], 0);
}
const std::int64_t effective_ramp =
std::max<std::int64_t>(0, event.ramp_samples - update_quantum_samples);
if (effective_ramp == 0) {
const std::int64_t ramp = std::max<std::int64_t>(0, event.ramp_samples);
if (ramp == 0) {
append_point(&points, start, event.x, event.y, event.z, 0);
current[0] = event.x;
current[1] = event.y;
current[2] = event.z;
continue;
}
const std::int64_t steps =
(effective_ramp + update_quantum_samples - 1) / update_quantum_samples;
const std::int64_t end = start + steps * update_quantum_samples;
const std::int64_t steps = (ramp + update_block_samples - 1) / update_block_samples;
const std::int64_t end = start + steps * update_block_samples;
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) {
return non_monotonic("overlapping_position_ramps",
"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);
}
}
std::int64_t future = effective_ramp;
std::int64_t future = ramp;
std::int64_t elapsed = 0;
double position[3] = {current[0], current[1], current[2]};
while (future > 0) {
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);
double x = 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[1] = y;
position[2] = z;
elapsed += update_quantum_samples;
elapsed += update_block_samples;
const std::int64_t sample = start + elapsed;
if (sample >= total_samples) {
break;
}
append_point(&points, sample, position[0], position[1], position[2],
update_quantum_samples);
future -= update_quantum_samples;
update_block_samples);
future -= update_block_samples;
}
current[0] = event.x;
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);
}
for (int object = 1; object <= kObjectCount; ++object) {
if (fixed_[object - 1]) {
continue; // 固定 bed 声道:位置由布局给出,不跟 OAMD 更新
}
double x = 0.0;
double y = 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) {
Track track;
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 =
(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)
: expand_dense64(events_[object - 1], total_samples, rate_, quantum_,
: expand_dense64(events_[object - 1], total_samples, rate_, block_,
object_delay_, object, &track.blocks);
if (!status.ok()) {
return status;
+21 -5
View File
@@ -7,6 +7,7 @@
#include <vector>
#include "adm/adm_metadata.h"
#include "foundation/metadata_timing.h"
#include "foundation/status.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.
class TrajectoryBuilder {
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)
: rate_(rate),
quantum_(update_quantum_samples),
block_(update_block_samples),
object_delay_(object_delay_samples) {}
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;
// 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]; }
std::uint32_t rate() const { return rate_; }
std::int64_t object_delay_samples() const { return object_delay_; }
private:
std::uint32_t rate_;
std::int64_t quantum_;
std::int64_t block_;
std::int64_t object_delay_;
oamd::OamdState state_;
std::vector<OamdEvent> events_[kObjectCount];
bool has_previous_[kObjectCount] = {};
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,
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);
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);
} // namespace joc::adm
+3 -11
View File
@@ -11,16 +11,8 @@
namespace {
thread_local std::string g_detail;
joc_error finish(const joc::Status& status) {
if (status.ok()) {
g_detail.clear();
return JOC_OK;
}
g_detail.assign(status.stage());
g_detail.append(": ");
g_detail.append(status.message());
joc::record_error_detail(status);
return status.code();
}
@@ -49,7 +41,7 @@ extern "C" {
std::uint32_t JOC_CALL joc_abi_version(void) { return JOC_ABI_VERSION; }
const char* JOC_CALL joc_version_string(void) { return "0.1.0-m1"; }
const char* JOC_CALL joc_version_string(void) { return JOC_VERSION_STRING; }
std::uint32_t JOC_CALL joc_event_size(void) { return static_cast<std::uint32_t>(sizeof(joc_event)); }
std::uint32_t JOC_CALL joc_task_config_size(void) {
@@ -167,7 +159,7 @@ const char* JOC_CALL joc_error_stage(joc_error code) {
}
}
const char* JOC_CALL joc_last_error_detail(void) { return g_detail.c_str(); }
const char* JOC_CALL joc_last_error_detail(void) { return joc::last_error_detail.c_str(); }
joc_error JOC_CALL joc_parse_id14(const std::uint8_t* payload, std::size_t payload_size,
joc_frame_params* out_params) {
+42 -10
View File
@@ -1,3 +1,4 @@
#include <cstddef>
#include <cstring>
#include <string>
@@ -13,6 +14,9 @@ struct joc_stream {
namespace {
joc_error finish_stream(const joc::Status& status) {
// The structured detail is not dropped here: joc_last_error_detail() reports
// it for the streaming entry points as well as for the task API.
joc::record_error_detail(status);
return status.code();
}
@@ -33,16 +37,16 @@ joc::stream::Config to_config(const joc_stream_config& config) {
}
out.gain_db = config.gain_db;
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) {
out.personalized_headphone_path = config.personalized_headphone_path;
}
if (config.hrtf_cache_dir != nullptr) { out.hrtf_cache_dir = config.hrtf_cache_dir; }
out.hrtf_cache_policy = config.hrtf_cache_policy;
if (config.hrtf_radius_m > 0.0) { out.hrtf_radius_m = config.hrtf_radius_m; }
// 0 is the documented "off" spelling for the room switch.
out.jochrtf_room = config.jochrtf_room;
// 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;
}
if (config.pcm_layout != nullptr) { out.pcm_layout = config.pcm_layout; }
return out;
}
@@ -92,13 +96,28 @@ joc_error JOC_CALL joc_stream_push(joc_stream* stream, const joc_stream_buffer*
}
return pushed;
}
if (input->kind == JOC_STREAM_IN_PCM_LAYOUT) {
if (input->sample_rate != 0u && input->sample_rate != 48000u) {
return joc::Status::fail(JOC_ERR_INVALID_ARGUMENT, joc::stage::kRender,
"PCM layout input must be 48 kHz");
}
std::size_t consumed = 0;
const joc::Status pushed = stream->instance.push_pcm_layout(
input->pcm, input->sample_count, input->channels, &consumed);
if (consumed_samples != nullptr) {
*consumed_samples = static_cast<std::uint32_t>(consumed);
}
return pushed;
}
std::size_t consumed = 0;
const std::uint32_t channels = input->channels != 0u ? input->channels : 6u;
const joc::Status pushed =
stream->instance.push_bed(input->pcm, input->sample_count, &consumed);
stream->instance.push_bed(input->pcm, input->sample_count, channels, &consumed);
if (consumed_samples != nullptr) {
*consumed_samples = static_cast<std::uint32_t>(consumed);
}
return pushed; }();
return pushed;
}();
return finish_stream(status);
}
@@ -136,8 +155,13 @@ joc_error JOC_CALL joc_stream_reset(joc_stream* stream) {
}
joc_error JOC_CALL joc_stream_status(const joc_stream* stream, joc_stream_status_info* out) {
// The info struct only grows by appending fields, so a caller built against
// the previous size still gets every field it knows about.
constexpr uint32_t kSizeBeforeTruncatedFrames = static_cast<uint32_t>(
offsetof(joc_stream_status_info, truncated_joc_frames));
if (stream == nullptr || out == nullptr ||
out->struct_size != sizeof(joc_stream_status_info)) {
(out->struct_size != sizeof(joc_stream_status_info) &&
out->struct_size != kSizeBeforeTruncatedFrames)) {
return JOC_ERR_INVALID_ARGUMENT;
}
const joc::stream::Info& info = stream->instance.info();
@@ -149,8 +173,16 @@ joc_error JOC_CALL joc_stream_status(const joc_stream* stream, joc_stream_status
out->buffered_samples = stream->instance.buffered_samples();
out->oamd_payloads = info.oamd_payloads;
out->oamd_transitions = info.oamd_transitions;
out->missing_joc_frames = info.missing_joc_frames;
out->objects_clamped_frames = info.objects_clamped_frames;
out->extra_container_frames = info.extra_container_frames;
out->chanmap_pair_mismatch_frames = info.chanmap_pair_mismatch_frames;
out->bed_mask_mismatch_frames = info.bed_mask_mismatch_frames;
out->output_channels = info.output_channels;
out->ended = info.ended;
if (out->struct_size > kSizeBeforeTruncatedFrames) {
out->truncated_joc_frames = info.truncated_joc_frames;
}
return JOC_OK;
}
@@ -1,7 +1,7 @@
// Derived from the upstream native/src/sofa_binaural_renderer.cpp (JustOneCacophony
// @ 6bc2c2885666bb151bb66af93472199af9a99b81, sha256 81b485e4c71907672ab308ddc38228
// 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,
// reassociated or contracted, so the output is bit-identical to the upstream
// implementation (verified: identical FNV-1a over the exact output bit patterns at
@@ -1378,7 +1378,7 @@ using ejoc::sofa_binaural::Renderer;
extern "C" {
ejoc_sofa_binaural_handle EJOC_CALL ejoc_sofa_binaural_create(void) {
ejoc_jochrtf_handle EJOC_CALL ejoc_jochrtf_create(void) {
try {
return new (std::nothrow) Renderer();
} 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);
}
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;
}
const char* EJOC_CALL ejoc_sofa_binaural_last_error(
ejoc_sofa_binaural_handle handle) {
const char* EJOC_CALL ejoc_jochrtf_last_error(
ejoc_jochrtf_handle handle) {
return handle ? static_cast<Renderer*>(handle)->error() : "null handle";
}
int EJOC_CALL ejoc_sofa_binaural_configure_kernels(
ejoc_sofa_binaural_handle handle, const double* qmf_analysis,
int EJOC_CALL ejoc_jochrtf_configure_kernels(
ejoc_jochrtf_handle handle, const double* qmf_analysis,
const double* hybrid_low, const int16_t* hybrid_indices,
const double* hybrid_values, uint32_t hybrid_count, const double* qmf_basis,
const double* qmf_taps) {
@@ -1409,8 +1409,8 @@ int EJOC_CALL ejoc_sofa_binaural_configure_kernels(
qmf_basis, qmf_taps) : -1;
}
int EJOC_CALL ejoc_sofa_binaural_configure_field(
ejoc_sofa_binaural_handle handle, const double* coefficients,
int EJOC_CALL ejoc_jochrtf_configure_field(
ejoc_jochrtf_handle handle, const double* coefficients,
const double* delay_coefficients, const double* delay_bounds,
const double* band_centers, double measurement_radius_m) {
return handle ? static_cast<Renderer*>(handle)->configure_field(
@@ -1418,8 +1418,8 @@ int EJOC_CALL ejoc_sofa_binaural_configure_field(
measurement_radius_m) : -1;
}
int EJOC_CALL ejoc_sofa_binaural_configure_room(
ejoc_sofa_binaural_handle handle, const double* room_dims,
int EJOC_CALL ejoc_jochrtf_configure_room(
ejoc_jochrtf_handle handle, const double* room_dims,
const double* listener_pos, const double* wall_gains, double speed_of_sound,
const uint32_t* fdn_delays, const double* fdn_feedback, double damping,
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;
}
int EJOC_CALL ejoc_sofa_binaural_set_source(
ejoc_sofa_binaural_handle handle, uint32_t source, const double* position_adm,
int EJOC_CALL ejoc_jochrtf_set_source(
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 fade) {
return handle ? static_cast<Renderer*>(handle)->set_source(
source, position_adm, profile, gain, enabled, special_lfe, fade) : -1;
}
int EJOC_CALL ejoc_sofa_binaural_process(
ejoc_sofa_binaural_handle handle, const double* input16_interleaved,
int EJOC_CALL ejoc_jochrtf_process(
ejoc_jochrtf_handle handle, const double* input16_interleaved,
uint32_t sample_count, double output_gain, double* output_stereo_interleaved) {
return handle ? static_cast<Renderer*>(handle)->process(
input16_interleaved, sample_count, output_gain, output_stereo_interleaved)
: -1;
}
int EJOC_CALL ejoc_sofa_binaural_finish(
ejoc_sofa_binaural_handle handle, uint32_t flush_samples,
int EJOC_CALL ejoc_jochrtf_finish(
ejoc_jochrtf_handle handle, uint32_t flush_samples,
double* output_stereo_interleaved, uint32_t capacity) {
return handle ? static_cast<Renderer*>(handle)->finish(
flush_samples, output_stereo_interleaved, capacity) : -1;
@@ -1,4 +1,4 @@
#include "binaural/binaural_runtime.h"
#include "binaural/jochrtf_runtime.h"
#include <algorithm>
#include <cmath>
@@ -29,14 +29,14 @@ bool profile_from_name(const char* name, Profile* out) {
return false;
}
SofaBinauralRuntime::~SofaBinauralRuntime() {
JochrtfRuntime::~JochrtfRuntime() {
if (handle_ != nullptr) {
ejoc_sofa_binaural_destroy(handle_);
ejoc_jochrtf_destroy(handle_);
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) {
if (handle_ != nullptr) {
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,
"compiled HRTF field has unexpected array sizes");
}
handle_ = ejoc_sofa_binaural_create();
handle_ = ejoc_jochrtf_create();
if (handle_ == nullptr) {
return Status::fail(JOC_ERR_OUT_OF_MEMORY, stage::kRender,
"ejoc_sofa_binaural_create failed");
"ejoc_jochrtf_create failed");
}
profile_ = profile;
if (ejoc_sofa_binaural_configure_kernels(
if (ejoc_jochrtf_configure_kernels(
handle_, kernels.qmf_analysis.data(), kernels.hybrid_low.data(),
kernels.hybrid_indices.data(), kernels.hybrid_values.data(), kernels.hybrid_count,
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,
std::string("configure_kernels failed: ") +
(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_bounds.data(), field.band_centers_hz.data(),
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,
std::string("configure_field failed: ") +
(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,
room.fdn_feedback, room.damping, room.fdn_output_gain, room.allpass_delays,
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,
std::string("configure_room failed: ") +
(message != nullptr ? message : "unknown"));
@@ -95,10 +95,11 @@ Status SofaBinauralRuntime::open(const hrtf::Field& field, const hrtf::Kernels&
return Status::success();
}
Status SofaBinauralRuntime::process_block() {
Status JochrtfRuntime::process_block() {
double positions[timeline::kTimelineObjects][3] = {};
const Status queried = timeline_.positions_at(static_cast<std::int64_t>(processed_samples_),
positions);
&positions[0][0],
timeline::kTimelineObjects);
if (!queried.ok()) {
return queried;
}
@@ -106,28 +107,28 @@ Status SofaBinauralRuntime::process_block() {
// backend default (fade enabled) applies - the per-object path crossfade is
// part of the reference behaviour, not an optional extra.
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,
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,
std::string("set_source(LFE) failed: ") +
(message != nullptr ? message : "unknown"));
}
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,
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,
std::string("set_source(object ") + std::to_string(source + 1u) +
") 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());
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,
std::string("sofa process failed: ") +
(message != nullptr ? message : "unknown"));
@@ -142,7 +143,7 @@ Status SofaBinauralRuntime::process_block() {
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,
std::int64_t outer_sample_offset,
std::int64_t object_delay_samples) {
@@ -186,7 +187,7 @@ Status SofaBinauralRuntime::submit_frame(const float* objects16_planar,
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_;
if (tail_seconds >= 0.0) {
requested = static_cast<std::int64_t>(std::ceil(tail_seconds * 48000.0 - 1e-9));
@@ -198,14 +199,14 @@ std::uint32_t SofaBinauralRuntime::finish_capacity(double tail_seconds) const {
return static_cast<std::uint32_t>(drain);
}
Status SofaBinauralRuntime::reset() {
Status JochrtfRuntime::reset() {
if (handle_ == nullptr) {
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");
}
timeline_ = timeline::OamdPositionTimeline();
timeline_.reset();
output_.clear();
staged_ = 0;
input_samples_ = 0;
@@ -214,7 +215,7 @@ Status SofaBinauralRuntime::reset() {
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) {
return Status::fail(JOC_ERR_STATE, stage::kRender, "binaural runtime is not open");
}
@@ -230,9 +231,9 @@ Status SofaBinauralRuntime::finish(std::uint32_t flush_samples, std::vector<doub
std::uint32_t remaining = flush_samples;
while (remaining > 0) {
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) {
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,
std::string("sofa finish failed: ") +
(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);
class SofaBinauralRuntime {
class JochrtfRuntime {
public:
SofaBinauralRuntime() = default;
~SofaBinauralRuntime();
JochrtfRuntime() = default;
~JochrtfRuntime();
SofaBinauralRuntime(const SofaBinauralRuntime&) = delete;
SofaBinauralRuntime& operator=(const SofaBinauralRuntime&) = delete;
JochrtfRuntime(const JochrtfRuntime&) = delete;
JochrtfRuntime& operator=(const JochrtfRuntime&) = delete;
Status open(const hrtf::Field& field, const hrtf::Kernels& kernels, Profile profile,
const RoomConstants& room = RoomConstants{});
@@ -72,13 +72,18 @@ public:
std::size_t staged_samples() const { return staged_; }
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).
std::uint32_t finish_capacity(double tail_seconds) const;
private:
Status process_block();
ejoc_sofa_binaural_handle handle_ = nullptr;
ejoc_jochrtf_handle handle_ = nullptr;
Profile profile_ = Profile::Mid;
timeline::OamdPositionTimeline timeline_;
std::vector<double> staging_;
+58 -102
View File
@@ -4,7 +4,7 @@
// 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
// 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.
#include <algorithm>
#include <cmath>
@@ -40,13 +40,12 @@ struct Options {
std::string clip_action = "ask";
int speaker_metadata_offset = 1473;
std::string binaural_mode = "mid";
std::string sofa_hrtf;
std::string compiled_hrtf_cache;
std::string jochrtf_room = "on";
std::string personalized_headphone;
bool personalized_headphone_used = false;
std::string hrtf_cache_policy;
std::string hrtf_cache_dir;
double hrtf_radius_m = 1.0;
int rosella_filterbank = 1;
bool rosella_filterbank_set = false;
double binaural_tail_seconds = 5.0;
double binaural_tail_threshold = 1.0e-8;
int binaural_chunk_frames = 64;
@@ -80,14 +79,17 @@ struct Options {
bool dry_run = false;
bool quiet = false;
bool help = false;
bool version = false;
};
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 6.0";
void print_usage() {
std::printf(
"usage: joc_cli [options] input\n"
" -h, --help 显示本帮助\n"
" --version 显示版本并退出\n"
"\n"
"JustOneCacophony (JOC):E-AC-3 JOC → 25ch ADM BWF、扬声器 WAV 或双耳 WAV\n"
"\n"
@@ -95,7 +97,7 @@ void print_usage() {
" input 输入 .m4a/.eac3/.ec3\n"
"\n"
"模式(默认输出 ADM BWF):\n"
" --speaker-layout L 直接扬声器渲染布局,例如 2.0、5.1、7.1.2\n"
" --speaker-layout L 直接扬声器渲染布局,例如 2.0、5.1、6.0、7.1.2\n"
" 可选值: %s\n"
" --binaural 直接双耳渲染;不生成临时 ADM BWF\n"
"\n"
@@ -112,13 +114,12 @@ void print_usage() {
" --speaker-metadata-offset N 扬声器渲染 metadata 相对帧偏移,默认 1473 samples\n"
" --binaural-mode M 双耳渲染模式 off|near|mid|far,默认 mid;\n"
" off 仅用于 ADM BWF(关闭 DBMD 双耳提示)\n"
" --sofa-hrtf PATH SOFA SimpleFreeFieldHRIR 输入;.jochrtf 由本工具内部编译\n"
" --personalized-headphone [PATH] Rosella 个性化模型,默认 "
"HRTF/binaural.personalized_headphone\n"
" --compiled-hrtf-cache PATH 直接读取 .jochrtf(高级用法,跳过 SOFA 编译)\n"
" --hrtf-cache-policy P SOFA 编译缓存策略 none|memory|disk,默认 memory\n"
" --hrtf-cache-dir DIR disk cache 目录,默认 <exe>/output/hrtf-cache\n"
" --hrtf-radius-m R 选择最近的 SOFA measurement-radius shell,默认 1.0 m\n"
" --rosella-filterbank N Rosella 模型滤波器组:1=13 taps/6 slots(默认),\n"
" 2=11 taps/3 slots;仅作用于个性化模型\n"
" --compiled-hrtf-cache PATH 读取离线编译好的 .jochrtf\n"
" --jochrtf-room on|off .jochrtf 的项目房间,默认 on;off 只输出直达声\n"
" --binaural-tail-seconds S 双耳 room/filterbank flush 上限,默认 5 秒\n"
" --binaural-tail-threshold T 双耳尾声裁切阈值,默认 1e-8;主体至少保留原时长\n"
" --binaural-chunk-frames N 双耳内部批处理帧数,默认 64(本构建按 512 块渲染,\n"
@@ -129,7 +130,8 @@ void print_usage() {
" --trajectory-mode M ADM 对象轨迹表示 compact|dense64,默认 compact\n"
"\n"
"输入与解码:\n"
" --ffmpeg PATH ffmpeg 可执行文件,默认取 FFMPEG 环境变量或 PATH\n"
" --ffmpeg PATH ffmpeg 可执行文件;本选项优先,默认先取 FFMPEG 环境变量,\n"
" 再在 PATH 中查找\n"
" --eac3-drc-scale X E-AC-3 解码器 -drc_scale,0=关闭码流 dynrng,默认 0\n"
" --eac3-target-level N E-AC-3 解码器 -target_level,0=不施加,默认 0\n"
" --backend B JOC/扬声器 DSP 后端 auto|native;本构建无 python 后端\n"
@@ -209,6 +211,7 @@ void parse_args(const std::vector<std::string>& arguments, Options* options) {
for (int index = 1; index < argc; ++index) {
const std::string arg = arguments[static_cast<std::size_t>(index)];
if (arg == "-h" || arg == "--help") { options->help = true; }
else if (arg == "--version") { options->version = true; }
else if (arg == "-o" || arg == "--output") { options->output = require_value(arguments, &index); }
else if (arg == "--speaker-output") { options->speaker_output = require_value(arguments, &index); }
else if (arg == "--binaural-output") { options->binaural_output = require_value(arguments, &index); }
@@ -222,8 +225,8 @@ void parse_args(const std::vector<std::string>& arguments, Options* options) {
to_int(require_value(arguments, &index), "--speaker-metadata-offset"));
}
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 == "--jochrtf-room") { options->jochrtf_room = require_value(arguments, &index); }
else if (arg == "--personalized-headphone") {
options->personalized_headphone_used = true;
// nargs="?": the path is optional, so the next token may be the input.
@@ -233,9 +236,11 @@ void parse_args(const std::vector<std::string>& arguments, Options* options) {
options->personalized_headphone = require_value(arguments, &index);
}
}
else if (arg == "--hrtf-cache-policy") { options->hrtf_cache_policy = require_value(arguments, &index); }
else if (arg == "--hrtf-cache-dir") { options->hrtf_cache_dir = require_value(arguments, &index); }
else if (arg == "--hrtf-radius-m") { options->hrtf_radius_m = to_double(require_value(arguments, &index), "--hrtf-radius-m"); }
else if (arg == "--rosella-filterbank") {
options->rosella_filterbank = static_cast<int>(
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-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")); }
@@ -331,16 +336,12 @@ std::string find_kernels(const Options& options, const std::string& argv0) {
return options.kernels;
}
// Mirrors the reference binaural HRTF resolution (main.py:89-160): the SOFA file
// is the user-facing input and the .jochrtf is only its compiled cache. Paths
// are anchored at the executable directory, as the reference anchors them at the
// project directory.
// The binaural input is either an explicitly compiled .jochrtf field or a Rosella
// .personalized_headphone model. Paths are anchored at the executable directory,
// as the reference anchors them at the project directory.
struct HrtfInput {
std::string sofa_path; // compile this
std::string compiled_path; // or read this .jochrtf directly
std::string cache_dir; // disk policy directory
std::string compiled_path; // read this .jochrtf
std::string personalized_path; // Rosella .personalized_headphone
bool disk = false;
};
std::string resolve_compiled_hrtf(const Options& options, const std::string& project_directory) {
@@ -348,9 +349,7 @@ std::string resolve_compiled_hrtf(const Options& options, const std::string& pro
return options.compiled_hrtf_cache;
}
const std::string directory_utf8 =
options.hrtf_cache_dir.empty()
? fs_utf8::from_path(fs_utf8::to_path(project_directory) / "output" / "hrtf-cache")
: options.hrtf_cache_dir;
fs_utf8::from_path(fs_utf8::to_path(project_directory) / "output" / "hrtf-cache");
if (!fs_utf8::is_directory(directory_utf8)) {
return std::string();
}
@@ -364,34 +363,18 @@ std::string resolve_compiled_hrtf(const Options& options, const std::string& pro
std::sort(candidates.begin(), candidates.end());
if (candidates.size() > 1u) {
fail(directory_utf8 +
" 下有多个 .jochrtf 缓存,无法自动选择;请用 --sofa-hrtf PATH 或 "
"--compiled-hrtf-cache PATH 显式指定");
" 下有多个 .jochrtf 缓存,无法自动选择;请用 --compiled-hrtf-cache PATH 显式指定");
}
return candidates.empty() ? std::string() : fs_utf8::from_path(candidates.front());
}
HrtfInput resolve_hrtf_input(const Options& options, const std::string& project_directory) {
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(
fs_utf8::to_path(project_directory) / "HRTF" / "binaural.personalized_headphone");
const std::string default_cache_dir =
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 personalized =
options.personalized_headphone_used ? options.personalized_headphone : std::string();
@@ -399,16 +382,11 @@ HrtfInput resolve_hrtf_input(const Options& options, const std::string& project_
// "--personalized-headphone" without a path means the project default.
personalized = default_private;
}
if (sofa.empty() && compiled.empty() && personalized.empty()) {
// The reference order: the SOFA file, then the unique compiled cache, then the
// personalized model.
if (fs_utf8::exists(default_sofa)) {
sofa = default_sofa;
} else {
compiled = resolve_compiled_hrtf(options, project_directory);
if (compiled.empty() && fs_utf8::exists(default_private)) {
personalized = default_private;
}
if (compiled.empty() && personalized.empty()) {
// The compiled cache, then the personalized model.
compiled = resolve_compiled_hrtf(options, project_directory);
if (compiled.empty() && fs_utf8::exists(default_private)) {
personalized = default_private;
}
}
if (!personalized.empty()) {
@@ -418,35 +396,12 @@ HrtfInput resolve_hrtf_input(const Options& options, const std::string& project_
input.personalized_path = personalized;
return input;
}
if (sofa.empty() && compiled.empty()) {
if (!options.hrtf_cache_policy.empty() || !options.hrtf_cache_dir.empty() ||
options.hrtf_radius_m != 1.0) {
fail("HRTF cache/radius 选项需要 --sofa-hrtf");
}
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);
if (compiled.empty()) {
fail("--binaural 未找到 HRTF 输入:默认 " + default_private + " 与 " + default_cache_dir +
" 下的 .jochrtf 都不存在,请用 --personalized-headphone PATH 或 "
"--compiled-hrtf-cache PATH 指定");
}
input.compiled_path = compiled;
return input;
}
@@ -529,6 +484,11 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "joc_cli: error: %s\n", error.what());
return 2;
}
if (options.version) {
std::printf("joc_cli %s (joc_core ABI %u)\n", joc_version_string(),
static_cast<unsigned>(joc_abi_version()));
return 0;
}
if (options.help) {
print_usage();
return 0;
@@ -548,9 +508,9 @@ int main(int argc, char** argv) {
check_choice(options.backend, "--backend", {"auto", "native", "python"});
check_choice(options.print_metadata, "--print-metadata", {"none", "summary", "frames"});
check_choice(options.metadata_backend, "--metadata-backend", {"auto", "emdf", "sidecar"});
if (!options.hrtf_cache_policy.empty()) {
check_choice(options.hrtf_cache_policy, "--hrtf-cache-policy",
{"none", "memory", "disk"});
if (options.rosella_filterbank != 1 && options.rosella_filterbank != 2) {
fail("--rosella-filterbank: invalid choice: " +
std::to_string(options.rosella_filterbank) + " (choose from 1, 2)");
}
const bool speaker_mode = !options.speaker_layout.empty();
@@ -579,13 +539,16 @@ int main(int argc, char** argv) {
if (options.speaker_metadata_offset < 0) {
fail("speaker-metadata-offset 不能为负数");
}
check_choice(options.jochrtf_room, "--jochrtf-room", {"on", "off"});
const bool hrtf_options_used =
!options.sofa_hrtf.empty() || !options.compiled_hrtf_cache.empty() ||
options.personalized_headphone_used || !options.hrtf_cache_policy.empty() ||
!options.hrtf_cache_dir.empty() || options.hrtf_radius_m != 1.0;
!options.compiled_hrtf_cache.empty() || options.personalized_headphone_used ||
options.jochrtf_room != "on";
if (hrtf_options_used && !binaural_mode) {
fail("SOFA/HRTF 选项仅与 --binaural 一起使用");
}
if (options.rosella_filterbank_set && !binaural_mode) {
fail("--rosella-filterbank 仅与 --binaural 一起使用");
}
if (!std::isfinite(options.binaural_tail_seconds) ||
options.binaural_tail_seconds < 0.0) {
fail("binaural-tail-seconds 必须是非负有限值");
@@ -597,9 +560,6 @@ int main(int argc, char** argv) {
if (options.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) {
fail("duration 必须大于 0");
}
@@ -660,6 +620,7 @@ int main(int argc, char** argv) {
config.speaker_metadata_offset = static_cast<std::uint32_t>(options.speaker_metadata_offset);
config.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_threshold = options.binaural_tail_threshold;
config.binaural_chunk_frames = static_cast<std::uint32_t>(options.binaural_chunk_frames);
@@ -687,33 +648,28 @@ int main(int argc, char** argv) {
if (options.quiet) { config.flags |= JOC_TASK_F_QUIET; }
std::string hrtf_path;
std::string hrtf_sofa_path;
std::string hrtf_cache_dir;
std::string personalized_path;
std::string kernels_path;
if (binaural_mode) {
try {
const HrtfInput input = resolve_hrtf_input(options, project_directory);
hrtf_path = input.compiled_path;
hrtf_sofa_path = input.sofa_path;
hrtf_cache_dir = input.cache_dir;
personalized_path = input.personalized_path;
kernels_path = find_kernels(options, arguments.empty() ? std::string()
: arguments.front());
if (options.rosella_filterbank_set && personalized_path.empty()) {
fail("--rosella-filterbank 只作用于 Rosella .personalized_headphone 输入;"
"当前 .jochrtf 路径不使用该滤波器组");
}
} catch (const std::exception& error) {
std::fprintf(stderr, "joc_cli: error: %s\n", error.what());
return 2;
}
}
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 =
personalized_path.empty() ? nullptr : personalized_path.c_str();
config.hrtf_cache_policy = options.hrtf_cache_policy == "disk" ? JOC_HRTF_CACHE_DISK
: options.hrtf_cache_policy == "none" ? JOC_HRTF_CACHE_NONE
: JOC_HRTF_CACHE_MEMORY;
config.hrtf_radius_m = options.hrtf_radius_m;
config.jochrtf_room = options.jochrtf_room == "off" ? 0u : 1u;
config.kernels_path = kernels_path.empty() ? nullptr : kernels_path.c_str();
joc_validation_issue issues[32];
+125 -29
View File
@@ -7,9 +7,111 @@
namespace joc::eac3 {
namespace {
constexpr std::size_t kHeaderBytes = 4;
constexpr std::size_t kHeaderBytesAc3 = 6;
// AC-3 syncframe length in 16-bit words, indexed by fscod (0 = 48 kHz,
// 1 = 44.1 kHz, 2 = 32 kHz) and then frmsizecod (A/52 5.4.1.2).
constexpr std::uint16_t kAc3FrameWords[3][38] = {
{64, 64, 80, 80, 96, 96, 112, 112, 128, 128, 160, 160, 192, 192, 224, 224,
256, 256, 320, 320, 384, 384, 448, 448, 512, 512, 640, 640, 768, 768,
896, 896, 1024, 1024, 1152, 1152, 1280, 1280},
{69, 70, 87, 88, 104, 105, 121, 122, 139, 140, 174, 175, 208, 209, 243, 244,
278, 278, 348, 348, 417, 418, 487, 487, 557, 557, 696, 696, 835, 835,
975, 975, 1114, 1114, 1253, 1253, 1393, 1393},
{96, 96, 120, 120, 144, 144, 168, 168, 192, 192, 240, 240, 288, 288, 336, 336,
384, 384, 480, 480, 576, 576, 672, 672, 768, 768, 960, 960, 1152, 1152,
1344, 1344, 1536, 1536, 1728, 1728, 1920, 1920},
};
std::uint32_t read_bits(const std::uint8_t* data, std::size_t start, std::size_t count) {
std::uint32_t value = 0;
for (std::size_t index = start; index < start + count; ++index) {
const std::uint32_t bit = (data[index >> 3] >> (7u - (index & 7u))) & 1u;
value = (value << 1) | bit;
}
return value;
}
} // namespace
bool parse_syncframe_header(const std::uint8_t* data, std::size_t size, std::size_t offset,
Frame* out) {
if (data == nullptr || offset + kHeaderBytesAc3 > size) {
return false;
}
if (static_cast<std::uint16_t>((static_cast<std::uint16_t>(data[offset]) << 8) |
data[offset + 1]) != FrameReader::kSyncword) {
return false;
}
Frame frame;
frame.data = data + offset;
frame.offset = offset;
const std::size_t base = offset * 8u;
const std::uint32_t bsid = read_bits(data, base + 40u, 5u);
frame.bsid = static_cast<std::uint8_t>(bsid);
if (bsid <= 8u) {
frame.codec = 0;
const std::uint32_t fscod = read_bits(data, base + 32u, 2u);
const std::uint32_t frmsizecod = read_bits(data, base + 34u, 6u);
if (fscod > 2u || frmsizecod >= 38u) {
return false;
}
frame.size = static_cast<std::size_t>(kAc3FrameWords[fscod][frmsizecod]) * 2u;
frame.acmod = static_cast<std::uint8_t>(read_bits(data, base + 48u, 3u));
std::size_t bit = 51u;
if ((frame.acmod & 0x1u) != 0u && frame.acmod != 0x1u) {
bit += 2u; // cmixlev
}
if ((frame.acmod & 0x4u) != 0u) {
bit += 2u; // surmixlev
}
if (frame.acmod == 0x2u) {
bit += 2u; // dsurmod
}
frame.lfeon = static_cast<std::uint8_t>(read_bits(data, base + bit, 1u));
if (out != nullptr) {
*out = frame;
}
return true;
}
frame.codec = 1;
frame.strmtyp = static_cast<std::uint8_t>(read_bits(data, base + 16u, 2u));
frame.substreamid = static_cast<std::uint8_t>(read_bits(data, base + 18u, 3u));
const std::uint32_t frmsiz = read_bits(data, base + 21u, 11u);
frame.size = (static_cast<std::size_t>(frmsiz) + 1u) * 2u;
// fscod==3 also consumes two bits (fscod2), so acmod always starts at bit 36.
frame.acmod = static_cast<std::uint8_t>(read_bits(data, base + 36u, 3u));
frame.lfeon = static_cast<std::uint8_t>(read_bits(data, base + 39u, 1u));
std::size_t bit = 45u + 5u; // bsid, then dialnorm
const std::uint32_t compre = read_bits(data, base + bit, 1u);
++bit;
if (compre != 0u) {
bit += 8u; // compr
}
if (frame.acmod == 0u) {
bit += 5u; // dialnorm2
const std::uint32_t compr2 = read_bits(data, base + bit, 1u);
++bit;
if (compr2 != 0u) {
bit += 8u;
}
}
if (frame.strmtyp == 1u) {
if (read_bits(data, base + bit, 1u) != 0u) {
frame.has_chanmap = 1;
frame.chanmap = static_cast<std::uint16_t>(read_bits(data, base + bit + 1u, 16u));
}
}
if (out != nullptr) {
*out = frame;
}
return true;
}
void FrameReader::push(const std::uint8_t* data, std::size_t size) {
if (failed_ || data == nullptr || size == 0) {
return;
@@ -45,44 +147,43 @@ FrameReader::Next FrameReader::next(Frame* out) {
}
const std::uint8_t* p = buffer_.data() + consumed_;
// The reference implementation rejects a frame whose header does not fit,
// rather than silently resynchronising on the next 0x0B77.
// A frame whose header does not fit is rejected rather than silently
// resynchronised on the next 0x0B77.
if (available < kHeaderBytes) {
if (finished_) {
fail(JOC_ERR_EAC3_SYNCFRAME, "E-AC-3 syncframe header truncated at end of input");
fail(JOC_ERR_EAC3_SYNCFRAME, "syncframe header truncated at end of input");
return Next::Fail;
}
return Next::End;
}
const std::uint16_t syncword = static_cast<std::uint16_t>((static_cast<std::uint16_t>(p[0]) << 8) | p[1]);
if (syncword != kSyncword) {
fail(JOC_ERR_EAC3_SYNCFRAME, "invalid E-AC-3 syncword (silent resynchronisation is not allowed)");
Frame frame;
if (!parse_syncframe_header(p, available, 0, &frame) || frame.size == 0u) {
if (available < kHeaderBytesAc3 && !finished_) {
return Next::End;
}
fail(JOC_ERR_EAC3_SYNCFRAME,
"invalid syncframe header (silent resynchronisation is not allowed)");
return Next::Fail;
}
// frmsiz: 11 bits spread over the low 3 bits of byte 2 and all of byte 3,
const std::size_t words =
static_cast<std::size_t>(((p[2] & 0x07u) << 8) | p[3]) + 1u;
const std::size_t frame_bytes = words * 2u;
if (frame_bytes > available) {
if (frame.size > available) {
if (!finished_) {
return Next::End;
}
fail(JOC_ERR_BITSTREAM_TRUNCATED,
"last E-AC-3 syncframe extends past end of input (declared " +
std::to_string(frame_bytes) + " bytes, remaining " +
"last syncframe extends past end of input (declared " +
std::to_string(frame.size) + " bytes, remaining " +
std::to_string(available) + ")");
return Next::Fail;
}
if (out != nullptr) {
out->data = p;
out->size = frame_bytes;
out->offset = base_offset_ + consumed_;
frame.data = p;
frame.offset = base_offset_ + consumed_;
*out = frame;
}
consumed_ += frame_bytes;
consumed_ += frame.size;
stream_offset_ = base_offset_ + consumed_;
++frames_emitted_;
return Next::Ok;
@@ -93,20 +194,15 @@ joc_error FrameReader::frame_bytes(const std::uint8_t* data, std::size_t size, s
if (data == nullptr || out_frame_bytes == nullptr) {
return JOC_ERR_INVALID_ARGUMENT;
}
if (offset + kHeaderBytes > size) {
return JOC_ERR_EAC3_SYNCFRAME;
Frame frame;
if (!parse_syncframe_header(data, size, offset, &frame)) {
return offset + kHeaderBytes > size ? JOC_ERR_EAC3_SYNCFRAME
: JOC_ERR_EAC3_SYNCFRAME;
}
if (static_cast<std::uint16_t>((static_cast<std::uint16_t>(data[offset]) << 8) | data[offset + 1]) !=
kSyncword) {
return JOC_ERR_EAC3_SYNCFRAME;
}
const std::size_t words =
static_cast<std::size_t>(((data[offset + 2] & 0x07u) << 8) | data[offset + 3]) + 1u;
const std::size_t frame_bytes = words * 2u;
if (offset + frame_bytes > size) {
if (offset + frame.size > size) {
return JOC_ERR_BITSTREAM_TRUNCATED;
}
*out_frame_bytes = frame_bytes;
*out_frame_bytes = frame.size;
return JOC_OK;
}
+22 -1
View File
@@ -1,4 +1,3 @@
#pragma once
#include <cstddef>
@@ -10,12 +9,34 @@
namespace joc::eac3 {
// One syncframe plus its transport-layer (L2) header. codec/strmtyp/substreamid
// identify the substream: within one audio frame each combination appears once.
struct Frame {
const std::uint8_t* data = nullptr;
std::size_t size = 0;
std::size_t offset = 0; // byte offset of the frame start in the fed stream
std::uint8_t codec = 0; // 0 = AC-3, 1 = E-AC-3
std::uint8_t strmtyp = 0;
std::uint8_t substreamid = 0;
std::uint8_t acmod = 0;
std::uint8_t lfeon = 0;
std::uint8_t bsid = 0;
std::uint8_t has_chanmap = 0;
std::uint16_t chanmap = 0;
bool same_stream(const Frame& other) const {
return codec == other.codec && strmtyp == other.strmtyp &&
substreamid == other.substreamid;
}
};
// Parses the syncframe header at `offset`. Returns false when the syncword is
// missing or the declared size cannot be derived. `out` may be null to query
// only the size. AC-3 and E-AC-3 are told apart by bsid (bits 40..44): <= 8 is
// AC-3, whose frame size comes from fscod/frmsizecod, everything above is E-AC-3.
bool parse_syncframe_header(const std::uint8_t* data, std::size_t size, std::size_t offset,
Frame* out);
class FrameReader {
public:
enum class Next {
+68 -5
View File
@@ -102,9 +102,15 @@ Status parse_at(const std::uint8_t* data, std::size_t size, std::size_t start_bi
}
const std::uint32_t has_sample_offset = reader.read(1);
std::uint16_t sample_offset = 0;
std::uint32_t sample_offset = 0;
if (has_sample_offset != 0u) {
sample_offset = static_cast<std::uint16_t>(reader.read(12) >> 1);
std::uint32_t value = 0;
if (!bits::variable_bits(reader, 11, 8, &value)) {
return reader.error() == JOC_ERR_BITSTREAM_TRUNCATED
? truncated_fail(reader)
: syntax_fail(reader.error_message());
}
sample_offset = value;
}
if (reader.read(1) != 0u) {
std::uint32_t ignored = 0;
@@ -113,12 +119,16 @@ Status parse_at(const std::uint8_t* data, std::size_t size, std::size_t start_bi
: syntax_fail(reader.error_message());
}
}
std::uint8_t group_id = 0;
std::uint8_t has_group_id = 0;
if (reader.read(1) != 0u) {
std::uint32_t ignored = 0;
if (!bits::variable_bits(reader, 2, 8, &ignored)) {
std::uint32_t value = 0;
if (!bits::variable_bits(reader, 2, 8, &value)) {
return reader.error() == JOC_ERR_BITSTREAM_TRUNCATED ? truncated_fail(reader)
: syntax_fail(reader.error_message());
}
group_id = static_cast<std::uint8_t>(value);
has_group_id = 1;
}
if (reader.read(1) != 0u) {
if (!reader.skip(8)) {
@@ -160,6 +170,8 @@ Status parse_at(const std::uint8_t* data, std::size_t size, std::size_t start_bi
Payload& entry = container.payloads[container.payload_count++];
entry.id = static_cast<std::uint8_t>(payload_id);
entry.sample_offset = sample_offset;
entry.group_id = group_id;
entry.has_group_id = has_group_id;
entry.bit_offset = reader.position();
entry.size = payload_size;
@@ -206,7 +218,8 @@ void marker_offsets(const std::uint8_t* data, std::size_t size, std::vector<std:
std::sort(out->begin(), out->end());
}
Status find_joc_emdf(const std::uint8_t* data, std::size_t size, Container* out) {
Status find_joc_emdf(const std::uint8_t* data, std::size_t size, Container* out,
ContainerPredicate usable, bool* ignored_extra) {
if (data == nullptr || out == nullptr) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kEmdf, "null buffer or output");
}
@@ -264,6 +277,31 @@ Status find_joc_emdf(const std::uint8_t* data, std::size_t size, Container* out)
}
if (top_level.size() != 1u) {
// Several containers can be genuine: a real stream carries a second
// container whose ID14 is a different structure altogether. The predicate
// tells those apart; what it leaves ambiguous stays an error.
if (usable != nullptr) {
int best = 0;
const Container* winner = nullptr;
int winners = 0;
for (const Container& candidate : top_level) {
const int score = usable(data, size, candidate);
if (score > best) {
best = score;
winner = &candidate;
winners = 1;
} else if (score == best && score > 0) {
++winners;
}
}
if (best > 0 && winners == 1 && winner != nullptr) {
if (ignored_extra != nullptr) {
*ignored_extra = true;
}
*out = *winner;
return Status::success();
}
}
return Status::fail(JOC_ERR_EMDF_TRANSPORT, stage::kEmdf,
"multiple top-level JOC EMDF containers (" +
std::to_string(top_level.size()) +
@@ -273,6 +311,31 @@ Status find_joc_emdf(const std::uint8_t* data, std::size_t size, Container* out)
return Status::success();
}
Status find_joc_emdf_optional(const std::uint8_t* data, std::size_t size, bool* present,
Container* out, ContainerPredicate usable, bool* ignored_extra) {
if (present == nullptr) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kEmdf, "null presence flag");
}
const Status status = find_joc_emdf(data, size, out, usable, ignored_extra);
if (status.ok()) {
*present = true;
return status;
}
if (status.code() != JOC_ERR_EMDF_TRANSPORT) {
return status;
}
// find_joc_emdf reports "no usable container in this syncframe" and "several
// usable containers" with the same code. Only the former is normal for a
// core syncframe (audio data can contain bytes that look like a marker);
// an ambiguous frame stays an error.
static constexpr const char* kAmbiguous = "multiple top-level";
if (status.message().rfind(kAmbiguous, 0) == 0) {
return status;
}
*present = false;
return Status::success();
}
void extract_container_bytes(const std::uint8_t* data, std::size_t size, const Container& container,
std::vector<std::uint8_t>* out) {
out->assign(container.raw_size, 0u);
+26 -2
View File
@@ -17,9 +17,14 @@ inline constexpr std::size_t kMaxPayloads = JOC_MAX_EMDF_PAYLOADS;
struct Payload {
std::uint8_t id = 0;
std::uint16_t sample_offset = 0;
std::uint32_t sample_offset = 0; // EMDF outer smpoffst: variable_bits(11)
std::size_t bit_offset = 0; // MSB-first bit position of the payload bytes
std::size_t size = 0; // payload byte count
// Payload configuration data (ETSI TS 102 366 H.2.2.3). Spec section 8.2 and
// its Table 56 associate the OAMD and JOC payloads of one frame by an equal
// group id, which is how several containers in one syncframe are told apart.
std::uint8_t group_id = 0;
std::uint8_t has_group_id = 0;
};
struct Container {
@@ -43,7 +48,26 @@ Status parse_at(const std::uint8_t* data, std::size_t size, std::size_t start_bi
// All candidate 0x5838 bit offsets over the eight alignments, ascending.
void marker_offsets(const std::uint8_t* data, std::size_t size, std::vector<std::size_t>* out);
Status find_joc_emdf(const std::uint8_t* data, std::size_t size, Container* out);
// Scores how well a candidate container can serve as the frame's metadata when a
// syncframe carries more than one: 0 = not at all, higher = more credible. A null
// predicate keeps the strict behaviour: several top-level candidates are an error,
// never a choice.
using ContainerPredicate = int (*)(const std::uint8_t* data, std::size_t size,
const Container& container);
// When a syncframe holds several top-level candidates and `usable` leaves exactly
// one with the highest non-zero score, that one is returned and `ignored_extra` is
// set; otherwise the frame stays an ambiguity error.
Status find_joc_emdf(const std::uint8_t* data, std::size_t size, Container* out,
ContainerPredicate usable = nullptr, bool* ignored_extra = nullptr);
// Like find_joc_emdf(), but a syncframe that carries no EMDF marker at all is a
// normal "absent" result rather than an error. A syncframe that does carry
// markers but no usable JOC container still fails, so a real transport problem
// is never mistaken for a core substream.
Status find_joc_emdf_optional(const std::uint8_t* data, std::size_t size, bool* present,
Container* out, ContainerPredicate usable = nullptr,
bool* ignored_extra = nullptr);
// Extract the container's bytes exactly as the bit reader sees them (identical
// to a memcpy for byte-aligned containers).
+2 -2
View File
@@ -21,8 +21,8 @@ bool variable_bits(BitReader& reader, unsigned width, unsigned max_groups, std::
}
value = (value + 1u) << width;
}
// Same failure mode as the reference implementation: an extension chain
// that never terminates is a syntax error, not a truncation.
// An extension chain that never terminates is a syntax error, not a
// truncation.
reader.fail(JOC_ERR_EMDF_SYNTAX, "variable_bits extension groups exceeded");
return false;
}
+96 -1
View File
@@ -1,5 +1,6 @@
#include "foundation/fs_utf8.h"
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <vector>
@@ -12,7 +13,6 @@
#include <fcntl.h>
#include <io.h>
#else
#include <cstdlib>
#include <unistd.h>
#endif
@@ -20,6 +20,70 @@ namespace joc::fs_utf8 {
namespace fs = std::filesystem;
namespace {
#if defined(_WIN32)
constexpr char kPathListSeparator = ';';
#else
constexpr char kPathListSeparator = ':';
#endif
// PATH (and PATHEXT) are separator-delimited lists. An empty entry is kept: on both
// platforms it means the current directory.
std::vector<std::string> split_list(const char* value, char separator) {
std::vector<std::string> parts;
if (value == nullptr) {
return parts;
}
std::string current;
for (const char c : std::string(value)) {
if (c == separator) {
parts.push_back(current);
current.clear();
continue;
}
current.push_back(c);
}
parts.push_back(current);
return parts;
}
bool is_runnable_file(const std::string& utf8_path) {
std::error_code error;
if (!fs::is_regular_file(to_path(utf8_path), error) || error) {
return false;
}
#if defined(_WIN32)
return true;
#else
// Existence is not enough: a file without the execute bit cannot be started, so
// deciding here names the real problem instead of a later "exit code 126".
return ::access(utf8_path.c_str(), X_OK) == 0;
#endif
}
bool carries_directory(const std::string& utf8_path) {
#if defined(_WIN32)
return utf8_path.find_first_of("/\\") != std::string::npos;
#else
return utf8_path.find('/') != std::string::npos;
#endif
}
#if defined(_WIN32)
// A bare name only resolves through PATHEXT on Windows. The environment is the
// authority; the classic four are the fallback when it is unset.
std::vector<std::string> executable_extensions() {
std::vector<std::string> extensions = split_list(std::getenv("PATHEXT"), ';');
if (extensions.empty()) {
extensions = {".COM", ".EXE", ".BAT", ".CMD"};
}
return extensions;
}
#endif
} // namespace
fs::path to_path(const std::string& utf8) {
return fs::path(std::u8string(reinterpret_cast<const char8_t*>(utf8.data()), utf8.size()));
}
@@ -112,6 +176,37 @@ std::string executable_path() {
#endif
}
std::string find_executable(const std::string& reference) {
if (reference.empty()) {
return std::string();
}
if (carries_directory(reference)) {
// A reference that already names a location is the caller's own decision:
// keep it verbatim rather than searching for a same-named program elsewhere.
return is_runnable_file(reference) ? reference : std::string();
}
#if defined(_WIN32)
const bool named_with_extension = to_path(reference).has_extension();
#endif
for (const std::string& entry : split_list(std::getenv("PATH"), kPathListSeparator)) {
const fs::path directory = to_path(entry.empty() ? std::string(".") : entry);
const std::string candidate = from_path(directory / to_path(reference));
if (is_runnable_file(candidate)) {
return candidate;
}
#if defined(_WIN32)
if (!named_with_extension) {
for (const std::string& extension : executable_extensions()) {
if (is_runnable_file(candidate + extension)) {
return candidate + extension;
}
}
}
#endif
}
return std::string();
}
std::ifstream open_input(const std::string& utf8_path) {
return std::ifstream(to_path(utf8_path), std::ios::binary);
}
+8
View File
@@ -33,6 +33,14 @@ std::string temp_directory();
// report it. Defaults are anchored here so they never depend on the CWD.
std::string executable_path();
// Resolves an executable reference to a concrete path. A reference that carries a
// directory separator is a location the caller chose, so it is kept verbatim when
// it names a runnable file and rejected otherwise; a bare name is looked up on PATH
// (through PATHEXT on Windows). Empty means "could not be resolved", which lets a
// caller report the name it was given instead of starting a child process that the
// shell would have to find.
std::string find_executable(const std::string& reference);
// Streams: std::ifstream/ofstream accept a std::filesystem::path, which is the
// portable way to open a UTF-8 path.
std::ifstream open_input(const std::string& utf8_path);
+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
+46
View File
@@ -7,6 +7,8 @@ namespace joc::json {
namespace {
const char kHexDigits[] = "0123456789abcdef";
void skip_space(const std::string& text, std::size_t* index) {
while (*index < text.size() &&
(text[*index] == ' ' || text[*index] == '\t' || text[*index] == '\n' ||
@@ -109,6 +111,50 @@ bool read_compound(const std::string& text, std::size_t* index, std::string* out
} // namespace
std::string quote(const std::string& text) {
std::string out;
out.reserve(text.size() + 2u);
out.push_back('"');
for (const char character : text) {
const unsigned char value = static_cast<unsigned char>(character);
switch (character) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\b': out += "\\b"; break;
case '\f': out += "\\f"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (value < 0x20u) {
out += "\\u00";
out.push_back(kHexDigits[value >> 4u]);
out.push_back(kHexDigits[value & 0x0Fu]);
} else {
out.push_back(character);
}
break;
}
}
out.push_back('"');
return out;
}
std::string pretty_object(const std::vector<Field>& fields) {
if (fields.empty()) {
return "{}";
}
std::string out = "{";
for (std::size_t index = 0u; index < fields.size(); ++index) {
out += index == 0u ? "\n " : ",\n ";
out += quote(fields[index].key);
out += ": ";
out += fields[index].value;
}
out += "\n}";
return out;
}
bool parse_object(const std::string& text, std::vector<Member>* out, std::string* error) {
out->clear();
std::size_t index = 0;
+18
View File
@@ -16,6 +16,24 @@ struct Member {
// Parses a top-level JSON object. Rejects non-objects and duplicate keys.
bool parse_object(const std::string& text, std::vector<Member>* out, std::string* error);
// One member of an object being written: `key` is escaped here, `value` is
// already JSON text (a quoted string, a number, a literal).
struct Field {
std::string key;
std::string value;
};
// Escapes `text` as a JSON string literal, quotes included. Matches
// json.dumps(..., ensure_ascii=False): the named escapes for `"` and `\` and
// for U+0008/U+0009/U+000A/U+000C/U+000D, `\u00XX` for the other control
// characters, and every other byte - UTF-8 included - passed through.
std::string quote(const std::string& text);
// Renders a flat object the way json.dumps(members, ensure_ascii=False,
// indent=2) does: two-space indentation, one member per line, the members in
// the order given, and no trailing newline.
std::string pretty_object(const std::vector<Field>& fields);
const Member* find(const std::vector<Member>& members, const std::string& key);
bool as_string(const Member& member, std::string* out);
+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
+18
View File
@@ -33,6 +33,24 @@ private:
std::string message_;
};
// Structured detail of the most recent failing call, as returned by
// 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 --
// reports through the same string. Defined in status.cpp: a thread_local with
// 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) {
if (status.ok()) {
last_error_detail.clear();
return;
}
last_error_detail.assign(status.stage());
last_error_detail.append(": ");
last_error_detail.append(status.message());
}
// Stage names are kept as plain literals so that C++ and the Python frontend
namespace stage {
inline constexpr const char* kFoundation = "foundation";
-4
View File
@@ -7,10 +7,6 @@
#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 {
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},
}};
}
+25 -16
View File
@@ -12,7 +12,7 @@
#include <vector>
#include "foundation/fft.h"
#include "hrtf/public_filterbank.h"
#include "hrtf/rosella_bank.h"
namespace joc::hrtf {
@@ -1003,8 +1003,8 @@ struct RosellaRuntime::Impl {
std::vector<double> field_left;
std::vector<double> field_right;
Core core;
std::unique_ptr<PublicFilterbank> analysis_bank;
std::unique_ptr<PublicFilterbank> synthesis_bank;
std::unique_ptr<RosellaBank> analysis_bank;
std::unique_ptr<RosellaBank> synthesis_bank;
timeline::OamdPositionTimeline timeline{timeline::kTimelineObjects};
std::vector<double> buffer; // [chunk_samples][16]
@@ -1051,9 +1051,7 @@ struct RosellaRuntime::Impl {
analysis_bank->analyze_qmf(hops_, slots, &qmf_);
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) {
room_sends_buffer_.resize(slots * kHybridBands);
}
@@ -1122,7 +1120,8 @@ struct RosellaRuntime::Impl {
// rosella_binaural_renderer._set_block_parameters.
Status set_block_parameters(std::int64_t sample) {
double positions[timeline::kTimelineObjects][3] = {};
Status status = timeline.positions_at(sample, positions);
Status status = timeline.positions_at(sample, &positions[0][0],
timeline::kTimelineObjects);
if (!status.ok()) {
return status;
}
@@ -1141,11 +1140,13 @@ struct RosellaRuntime::Impl {
return Status::success();
}
// The reference drops the first 961 samples of the raw stream (the filterbank's
// latency) and returns everything after that.
// The reference drops the first `latency` samples of the raw stream (the
// 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) {
const std::int64_t remaining = static_cast<std::int64_t>(kLatencySamples) -
static_cast<std::int64_t>(raw_output_samples);
const std::int64_t remaining =
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>(
std::max<std::int64_t>(0, std::min<std::int64_t>(static_cast<std::int64_t>(count),
remaining)));
@@ -1191,6 +1192,9 @@ Status RosellaRuntime::open(const RosellaModel& model, const RosellaRenderOption
if (options.object_delay_samples < 0) {
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_->options = options;
logical_field(impl_->model.field_left_padded, &impl_->field_left);
@@ -1203,8 +1207,8 @@ Status RosellaRuntime::open(const RosellaModel& model, const RosellaRenderOption
return status;
}
// The analysis bank runs sixteen sources, the synthesis bank two output ears.
impl_->analysis_bank = std::make_unique<PublicFilterbank>(builtin_kernels(), kSourceChannels);
impl_->synthesis_bank = std::make_unique<PublicFilterbank>(builtin_kernels(), kOutputChannels);
impl_->analysis_bank = RosellaBank::create(options.bank, kSourceChannels);
impl_->synthesis_bank = RosellaBank::create(options.bank, kOutputChannels);
impl_->buffer.assign(impl_->chunk_samples() * kSourceChannels, 0.0);
impl_->room_sends_buffer_.assign(
(impl_->chunk_samples() / kQmfHop) * kHybridBands, Complex(0.0, 0.0));
@@ -1309,7 +1313,8 @@ Status RosellaRuntime::finish(std::uint32_t flush_samples, std::vector<double>*
}
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);
const double blocks = std::ceil(samples / static_cast<double>(kBlockSamples));
return static_cast<std::uint32_t>(blocks) * kBlockSamples;
@@ -1329,7 +1334,7 @@ Status RosellaRuntime::reset() {
impl_->raw_output_samples = 0u;
impl_->metadata_block_updates = 0u;
impl_->finished = false;
impl_->timeline = timeline::OamdPositionTimeline(timeline::kTimelineObjects);
impl_->timeline.reset();
return Status::success();
}
@@ -1339,7 +1344,7 @@ void RosellaRuntime::take_output(std::vector<double>* out) {
if (out == nullptr) {
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
// because the swap leaves it holding whatever the caller had.
out->swap(impl_->output);
@@ -1355,4 +1360,8 @@ std::uint64_t RosellaRuntime::metadata_block_updates() const {
}
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
+7
View File
@@ -6,6 +6,7 @@
#include <vector>
#include "foundation/status.h"
#include "hrtf/rosella_bank.h"
#include "hrtf/rosella_model.h"
#include "oamd/oamd_parser.h"
#include "timeline/position_timeline.h"
@@ -21,6 +22,9 @@ enum class RosellaProfile : std::int32_t { Near = 1, Far = 2, Mid = 3 };
struct RosellaRenderOptions {
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;
double tail_seconds = 5.0;
double output_gain = 1.0;
@@ -56,6 +60,9 @@ public:
std::uint64_t metadata_block_updates() const;
const timeline::OamdPositionTimeline& timeline() const;
// bed 声道是固定通道:OAMD 不给位置,方位由声明的 bed 布局给出。
void set_fixed_position(int object_index, const double position[3]);
private:
struct 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
+644
View File
@@ -0,0 +1,644 @@
#include "joc_bitstream/bed_layout_map.h"
#include <cmath>
#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,
};
// 每个 bed 声道的固定方位:speakerLabel 各自对应唯一的 ADM (X,Y,Z),与目标扬声器
// 布局无关。天空声道的 X 取墙边(±1):点声源的横向声像只在扬声器跨度的端点之间分摊,
// 取端点仍落在输出布局顶部声道的满功率区里,与顶部声道互相下混的结果一致。Lw/Rw 的 Y
// 记作 0,677419,即 42/62 = 21/31。LFE/LFE2 不参与摆位,位置记为原点。
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", {-1.0, 1.0, 1.0}},
{BedChannel::kTopFrontRight, "Rtf", "RC_TFR", {1.0, 1.0, 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", {-1.0, -1.0, 1.0}},
{BedChannel::kTopBackRight, "Rtr", "RC_TBR", {1.0, -1.0, 1.0}},
{BedChannel::kLeftWide, "Lw", "RC_LW", {-1.0, 21.0 / 31.0, 0.0}},
{BedChannel::kRightWide, "Rw", "RC_RW", {1.0, 21.0 / 31.0, 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::kLeftRearSurround) | bit(BedChannel::kRightRearSurround), "6.0"},
{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;
}
// Q15 满刻度是 32768(渲染器按 q / 32768 还原方位),所以用 32768 定标并四舍五入;
// 截断会让半格位置(16384、7928)各低 1。
const double q1 = (xyz[0] + 1.0) * 0.5 * 32768.0;
const double q2 = (1.0 - xyz[1]) * 0.5 * 32768.0;
const double q3 = xyz[2] * 32768.0;
const double rounded[3] = {q1 + 0.5, q2 + 0.5, q3 + 0.5};
for (int axis = 0; axis < 3; ++axis) {
const double value = rounded[axis] < 0.0
? 0.0
: (rounded[axis] > 32767.0 ? 32767.0 : rounded[axis]);
q15[axis] = static_cast<std::uint16_t>(value);
}
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;
}
// channel_names 与区域几何同序(region 的 speaker_id 就是这里的下标),
// 因此同名声道不需要再经 standard_from_internal 换序。
int internal_index = -1;
for (std::uint32_t index = 0; index < table->count; ++index) {
if (std::strcmp(table->names[index], name) == 0) {
internal_index = static_cast<int>(index);
break;
}
}
if (internal_index < 0) {
return false;
}
const std::uint8_t internal = static_cast<std::uint8_t>(internal_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 {
// ETSI TS 103 420 Table B.10: the fixed ADM position of every Table 12 bed
// channel. bed_output_description() matches these points against the target
// layout; the kChannels table above keeps the ADM/binaural path's coordinates.
struct TableB10Position {
BedChannel channel;
double xyz[3];
};
constexpr TableB10Position kTableB10[oamd::kBedLabelCount] = {
{BedChannel::kLeft, {-1.0, 1.0, 0.0}},
{BedChannel::kRight, {1.0, 1.0, 0.0}},
{BedChannel::kCenter, {0.0, 1.0, 0.0}},
{BedChannel::kLfe, {-1.0, 1.0, -1.0}},
{BedChannel::kLeftSurround, {-1.0, 0.0, 0.0}},
{BedChannel::kRightSurround, {1.0, 0.0, 0.0}},
{BedChannel::kLeftRearSurround, {-1.0, -1.0, 0.0}},
{BedChannel::kRightRearSurround, {1.0, -1.0, 0.0}},
{BedChannel::kTopFrontLeft, {-1.0, 1.0, 1.0}},
{BedChannel::kTopFrontRight, {1.0, 1.0, 1.0}},
{BedChannel::kTopSideLeft, {-1.0, 0.0, 1.0}},
{BedChannel::kTopSideRight, {1.0, 0.0, 1.0}},
{BedChannel::kTopBackLeft, {-1.0, -1.0, 1.0}},
{BedChannel::kTopBackRight, {1.0, -1.0, 1.0}},
{BedChannel::kLeftWide, {-1.0, 21.0 / 31.0, 0.0}},
{BedChannel::kRightWide, {1.0, 21.0 / 31.0, 0.0}},
{BedChannel::kLfe2, {1.0, 1.0, -1.0}},
};
// bed_layout.BED_REFERENCE_POSITIONS_Q15; index 3 is the non-spatial sentinel.
constexpr std::int32_t kReferencePositions[kBedReferencePositionCount][3] = {
{0, 0, 0}, {32767, 0, 0}, {16384, 0, 0}, {-1, -1, -1},
{0, 16384, 0}, {32767, 16384, 0}, {0, 32767, 0}, {32767, 32767, 0},
{16384, 32767, 0}, {5285, 0, 0}, {27483, 0, 0}, {0, 5285, 0},
{32767, 5285, 0}, {7928, 0, 32767}, {24840, 0, 32767}, {7928, 7928, 32767},
{24840, 7928, 32767}, {7928, 16384, 32767}, {24840, 16384, 32767},
{7928, 24840, 32767}, {24840, 24840, 32767}, {7928, 32767, 32767},
{24840, 32767, 32767}, {11099, 0, 0}, {21669, 0, 0}, {0, 11099, 0},
{32767, 11099, 0}, {0, 21669, 0}, {32767, 21669, 0}, {0, 27483, 0},
{32767, 27483, 0}, {5285, 32767, 0}, {27483, 32767, 0}, {11099, 32767, 0},
{21669, 32767, 0}, {16384, 0, 32767}, {16384, 16384, 32767},
{16384, 32767, 32767},
};
// 自动 trim 的每个布局基准衰减,单位 dB。
struct AttenuationEntry {
const char* compact_name;
double db;
};
constexpr AttenuationEntry kAttenuation[] = {
{"20", -4.5}, {"31", -4.5}, {"40", -3.0}, {"51", -3.0},
{"60", -1.5}, {"71", -1.5}, {"512", -2.25}, {"514", -1.5},
{"712", -0.75}, {"714", 0.0}, {"914", 0.0}, {"916", 0.0},
};
constexpr int kMaxChannels = static_cast<int>(ejoc::speaker_tables::kMaxChannels);
void set_sentinel(std::int32_t coordinate[3]) {
coordinate[0] = -1;
coordinate[1] = -1;
coordinate[2] = -1;
}
bool is_sentinel(const std::int32_t coordinate[3]) {
return coordinate[0] == -1 && coordinate[1] == -1 && coordinate[2] == -1;
}
bool is_lfe_label(BedChannel channel) {
return channel == BedChannel::kLfe || channel == BedChannel::kLfe2;
}
const TableB10Position* table_b10(BedChannel channel) {
for (const TableB10Position& entry : kTableB10) {
if (entry.channel == channel) {
return &entry;
}
}
return nullptr;
}
// ADM 笛卡尔坐标 -> 渲染器方位 (u 右, v 后, w 上)。
void render_coordinates(const double xyz[3], double out[3]) {
out[0] = (xyz[0] + 1.0) * 0.5;
out[1] = (1.0 - xyz[1]) * 0.5;
out[2] = xyz[2];
}
// 渲染器方位的欧氏距离,比较的是归一化到 0..1 的坐标。
double render_distance(const double left[3], const double right[3]) {
const double du = left[0] - right[0];
const double dv = left[1] - right[1];
const double dw = left[2] - right[2];
return std::sqrt(du * du + dv * dv + dw * dw);
}
// Reference-position matching: the non-spatial sentinel resolves to index 3.
int nearest_reference(const std::int32_t coordinate[3]) {
if (is_sentinel(coordinate)) {
return 3;
}
const double position[3] = {
static_cast<double>(coordinate[0]) / 32768.0,
static_cast<double>(coordinate[1]) / 32768.0,
static_cast<double>(coordinate[2]) / 32768.0,
};
int best = 3;
double best_distance = 0.0;
bool have_best = false;
for (int index = 0; index < kBedReferencePositionCount; ++index) {
const std::int32_t* candidate = kReferencePositions[index];
if (candidate[0] == -1 && candidate[1] == -1 && candidate[2] == -1) {
continue;
}
const double point[3] = {
static_cast<double>(candidate[0]) / 32768.0,
static_cast<double>(candidate[1]) / 32768.0,
static_cast<double>(candidate[2]) / 32768.0,
};
const double distance = render_distance(position, point);
if (!have_best || distance < best_distance) {
best = index;
best_distance = distance;
have_best = true;
}
}
return best;
}
// 目标布局里离 desired 最近、且在 0.05 容差内的输出声道;没有返回 -1。
int nearest_channel(const double desired[3], const std::int32_t positions[][3],
std::uint32_t channel_count) {
int best = -1;
double best_distance = 0.0;
bool have_best = false;
for (std::uint32_t index = 0; index < channel_count; ++index) {
if (is_sentinel(positions[index])) {
continue;
}
const double point[3] = {
static_cast<double>(positions[index][0]) / 32768.0,
static_cast<double>(positions[index][1]) / 32768.0,
static_cast<double>(positions[index][2]) / 32768.0,
};
const double distance = render_distance(desired, point);
if (!have_best || distance < best_distance) {
best = static_cast<int>(index);
best_distance = distance;
have_best = true;
}
}
if (have_best && best_distance <= 0.05) {
return best;
}
return -1;
}
// 输出声道 index -> 该声道的 Q15 方位;LFE 与非空间声道给 sentinel。
void channel_positions(const speaker::LayoutInfo& layout,
std::int32_t positions[][3]) {
for (int index = 0; index < kMaxChannels; ++index) {
set_sentinel(positions[index]);
}
const auto* geometry = ejoc::speaker_tables::find_layout(layout.speaker_bitfield);
if (geometry != nullptr) {
bool known[kMaxChannels] = {};
std::int32_t found[kMaxChannels][3];
for (int index = 0; index < kMaxChannels; ++index) {
set_sentinel(found[index]);
}
for (const auto& region : geometry->regions) {
for (std::size_t point = 0; point < region.point_count; ++point) {
const auto speaker = static_cast<int>(region.points[point].speaker_id);
if (speaker < 0 || speaker >= kMaxChannels || known[speaker]) {
continue;
}
for (int axis = 0; axis < 3; ++axis) {
found[speaker][axis] =
static_cast<std::int32_t>(region.points[point].coordinate_q15[axis]);
}
known[speaker] = true;
}
}
const std::uint32_t count =
layout.channel_count < static_cast<std::uint32_t>(kMaxChannels)
? layout.channel_count
: static_cast<std::uint32_t>(kMaxChannels);
for (std::uint32_t index = 0; index < count; ++index) {
const char* name = layout.channel_names != nullptr ? layout.channel_names[index]
: nullptr;
if (name != nullptr && std::strcmp(name, "LFE") == 0) {
continue;
}
if (known[index]) {
for (int axis = 0; axis < 3; ++axis) {
positions[index][axis] = found[index][axis];
}
}
}
}
}
int channel_index(const speaker::LayoutInfo& layout, const char* name) {
if (name == nullptr || layout.channel_names == nullptr) {
return -1;
}
for (std::uint32_t index = 0; index < layout.channel_count; ++index) {
if (std::strcmp(layout.channel_names[index], name) == 0) {
return static_cast<int>(index);
}
}
return -1;
}
double attenuation_db(const speaker::LayoutInfo& layout) {
for (const AttenuationEntry& entry : kAttenuation) {
if (std::strcmp(entry.compact_name, layout.compact_name) == 0) {
return entry.db;
}
}
return 0.0;
}
} // namespace
const std::int32_t (*bed_reference_positions_q15())[3] {
return kReferencePositions;
}
BedOutputDescription bed_output_description(const speaker::LayoutInfo& layout) {
BedOutputDescription description;
std::int32_t positions[kMaxChannels][3];
channel_positions(layout, positions);
const std::uint32_t output_count =
layout.channel_count < static_cast<std::uint32_t>(kMaxChannels)
? layout.channel_count
: static_cast<std::uint32_t>(kMaxChannels);
description.output_labels.reserve(output_count);
for (std::uint32_t index = 0; index < output_count; ++index) {
description.output_labels.push_back(nearest_reference(positions[index]));
}
for (int label = 0; label < oamd::kBedLabelCount; ++label) {
const BedChannel channel = static_cast<BedChannel>(label);
const char* name = channel == BedChannel::kLfe2 ? nullptr
: bed_channel_short_name(channel);
int slot = -1;
if (name != nullptr && name[0] != '\0') {
slot = channel_index(layout, name);
}
if (slot < 0 && channel == BedChannel::kLfe2) {
slot = channel_index(layout, "LFE");
}
const TableB10Position* position = table_b10(channel);
double desired[3] = {0.0, 0.0, 0.0};
if (position != nullptr) {
render_coordinates(position->xyz, desired);
}
if (slot < 0 && position != nullptr) {
slot = nearest_channel(desired, positions, output_count);
}
if (slot < 0) {
description.label_to_slot[label] = is_lfe_label(channel) ? -1 : -2;
} else {
description.label_to_slot[label] = slot;
}
if (is_lfe_label(channel)) {
description.direct_output_labels[label] = 3;
} else {
int best = 3;
double best_distance = 0.0;
bool have_best = false;
for (int index = 0; index < kBedReferencePositionCount; ++index) {
const std::int32_t* candidate = kReferencePositions[index];
if (candidate[0] == -1 && candidate[1] == -1 && candidate[2] == -1) {
continue;
}
const double point[3] = {
static_cast<double>(candidate[0]) / 32768.0,
static_cast<double>(candidate[1]) / 32768.0,
static_cast<double>(candidate[2]) / 32768.0,
};
const double distance = render_distance(desired, point);
if (!have_best || distance < best_distance) {
best = index;
best_distance = distance;
have_best = true;
}
}
description.direct_output_labels[label] = best;
}
}
description.automatic_attenuation_db = attenuation_db(layout);
return description;
}
} // namespace joc::joc
+69
View File
@@ -0,0 +1,69 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include "oamd/oamd_parser.h"
#include "speaker/speaker_layout_lookup.h"
namespace joc::joc {
// BedChannel lives in oamd/oamd_parser.h: the enum is the OAMD Table 12
// label order and OAMD frame state carries it directly.
// 内容声明的 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。4.0 与 6.0 共用未分配的 out_ch_config
// 0xFF,因此这里按 4.0 的声道集合解释 0xFF。
bool layout_bed_anchor(std::uint32_t out_ch_config, BedChannel channel,
std::uint16_t q15[3]);
// 参考位置网格 ``BED_REFERENCE_POSITIONS_Q15``:bed 标签与输出 slots 的最近邻
// 匹配都用这一组固定 Q15 点。索引 3 是 (-1,-1,-1),表示 LFE 那样的非空间声源。
inline constexpr int kBedReferencePositionCount = 38;
const std::int32_t (*bed_reference_positions_q15())[3];
// 一个目标扬声器布局的 bed 路由描述(bed_layout.bed_output_description):
// 按标准 bed 标签序(Table 12 的 17 个标签)给出目标 layout 的输出参考位置、
// 每个标签的输出 slot 与直连参考位置,以及该布局的自动 trim 基准衰减。
struct BedOutputDescription {
std::vector<int> output_labels; // 每个输出声道最近邻的参考位置索引
int label_to_slot[oamd::kBedLabelCount] = {}; // -2 不可达,-1 LFE 通路
int direct_output_labels[oamd::kBedLabelCount] = {};
double automatic_attenuation_db = 0.0;
};
// 由布局名/几何派生 bed 路由描述;``layout.channel_names`` 必须按标准声道
// 顺序给出 ``layout.channel_count`` 个名字。
BedOutputDescription bed_output_description(const speaker::LayoutInfo& layout);
} // namespace joc::joc
+745 -46
View File
@@ -1,5 +1,7 @@
#include "joc_bitstream/joc_parser.h"
#include "joc_bitstream/bed_layout_map.h"
#include <algorithm>
#include <cmath>
#include <cstring>
@@ -180,6 +182,77 @@ std::int16_t num_bands_for_index(std::uint32_t num_bands_idx) {
return -1;
}
namespace {
// Reads the 12-bit joc_header at the start of the payload. Mirrors
// parse_joc_header(): a downmix configuration outside 0..4 is a frame status,
// not an exception, because a metadata scan records it as an unsupported
// variant while the frame itself stays classified.
Status parse_id14_header(const std::uint8_t* payload, std::size_t payload_size,
joc_frame_params* out) {
bits::BitReader reader(payload, payload_size);
out->dmx_config_idx = static_cast<std::uint8_t>(reader.read(3));
out->num_objects_bits = static_cast<std::uint8_t>(reader.read(6));
out->ext_config_idx = static_cast<std::uint8_t>(reader.read(3));
if (reader.failed()) {
return truncated_fail(reader);
}
const std::int16_t n_channels = num_channels_for_config(out->dmx_config_idx);
if (n_channels < 0) {
// The core channel count decides how the object syntax expands, so an
// unknown configuration stops the parse after the header fields.
out->status = JOC_FRAME_STATUS_UNSUPPORTED_DMX;
out->objects_clamped = 0u;
out->n_objects = 0u;
return Status::success();
}
out->n_channels = static_cast<std::uint8_t>(n_channels);
const std::uint32_t declared = static_cast<std::uint32_t>(out->num_objects_bits) + 1u;
out->objects_clamped = declared > JOC_MAX_OBJECTS ? 1u : 0u;
out->n_objects = static_cast<std::uint8_t>(
std::min<std::uint32_t>(declared, static_cast<std::uint32_t>(JOC_MAX_OBJECTS)));
if (out->objects_clamped != 0u) {
out->status = JOC_FRAME_STATUS_OBJECTS_CLAMPED;
}
return Status::success();
}
// Records where joc_data ends and the first trailing bytes, like _tail_info().
void tail_info(joc_frame_params* out, const bits::BitReader& reader, const std::uint8_t* payload,
std::size_t payload_size) {
out->data_end_bits = static_cast<std::uint32_t>(reader.position());
out->trailing_bits = static_cast<std::uint32_t>(payload_size * 8u - reader.position());
const std::size_t tail_offset = reader.position() / 8u;
if (tail_offset < payload_size) {
const std::size_t tail_bytes = std::min<std::size_t>(8u, payload_size - tail_offset);
std::memcpy(out->tail_bytes, payload + tail_offset, tail_bytes);
}
}
// A payload that runs out of bits after the joc_header is a damaged but
// identifiable JOC frame: the header, clipgain, sequence counter and object
// parameters are intact, so the frame keeps its identity and the renderer can
// hold the previous matrices instead of stopping the stream. A payload that
// ends before the header cannot be classified and stays a transport error; a
// Huffman walk that leaves the tree is a syntax error, never a truncation.
Status truncated_frame(const bits::BitReader& reader, joc_frame_params* out,
const std::uint8_t* payload, std::size_t payload_size) {
if (reader.error() != JOC_ERR_BITSTREAM_TRUNCATED) {
return syntax_fail(reader.error_message());
}
out->status = JOC_FRAME_STATUS_TRUNCATED;
out->present_mask = 0u;
for (std::uint32_t obj = 0; obj < out->n_objects; ++obj) {
if (out->objects[obj].present != 0u) {
out->present_mask |= 1u << obj;
}
}
tail_info(out, reader, payload, payload_size);
return Status::success();
}
} // namespace
Status parse_id14(const std::uint8_t* payload, std::size_t payload_size, joc_frame_params* out,
FrameSymbols* symbols) {
if (payload == nullptr || out == nullptr) {
@@ -193,48 +266,53 @@ Status parse_id14(const std::uint8_t* payload, std::size_t payload_size, joc_fra
FrameSymbols& capture = (symbols != nullptr) ? *symbols : local_symbols;
std::memset(&capture, 0, sizeof(capture));
const Status header = parse_id14_header(payload, payload_size, out);
if (!header.ok()) {
return header;
}
bits::BitReader reader(payload, payload_size);
out->dmx_config_idx = static_cast<std::uint8_t>(reader.read(3));
out->num_objects_bits = static_cast<std::uint8_t>(reader.read(6));
out->ext_config_idx = static_cast<std::uint8_t>(reader.read(3));
const std::uint32_t n_objects = static_cast<std::uint32_t>(out->num_objects_bits) + 1u;
const std::int16_t n_channels = num_channels_for_config(out->dmx_config_idx);
if (n_channels < 0) {
return syntax_fail("unknown JOC downmix configuration " +
std::to_string(out->dmx_config_idx));
}
out->n_channels = static_cast<std::uint8_t>(n_channels);
if (n_objects > JOC_MAX_OBJECTS) {
// The reference implementation has no check here and fails later inside
// NumPy; the port reports it explicitly (plan 28.2).
return Status::fail(JOC_ERR_JOC_UNSUPPORTED_VARIANT, stage::kJoc,
"JOC frame declares " + std::to_string(n_objects) +
" objects, the ABI supports at most " +
std::to_string(static_cast<int>(JOC_MAX_OBJECTS)));
}
out->n_objects = static_cast<std::uint8_t>(n_objects);
reader.skip(12);
out->clipgain_x_bits = static_cast<std::uint8_t>(reader.read(3));
out->clipgain_y_bits = static_cast<std::uint8_t>(reader.read(5));
out->seq_count = reader.read(10);
// clipgain = 1 + (y/32) * 2^(x-4). The reference multiplies by an exact
// exactly for the whole legal range.
out->clipgain = 1.0 + static_cast<double>(out->clipgain_y_bits) / 32.0 *
std::ldexp(1.0, static_cast<int>(out->clipgain_x_bits) - 4);
if (reader.failed()) {
return truncated_frame(reader, out, payload, payload_size);
}
// clipgain = 2^(x-4) * (1 + y/32); ldexp builds the power of two exactly
// over the whole legal range, so the result is bit-exact to the reference.
out->clipgain = std::ldexp(1.0, static_cast<int>(out->clipgain_x_bits) - 4) *
(1.0 + static_cast<double>(out->clipgain_y_bits) / 32.0);
if (out->status == JOC_FRAME_STATUS_UNSUPPORTED_DMX) {
tail_info(out, reader, payload, payload_size);
return Status::success();
}
const std::int16_t n_channels = num_channels_for_config(out->dmx_config_idx);
const std::uint32_t n_objects = out->n_objects;
for (std::uint32_t obj = 0; obj < n_objects; ++obj) {
joc_object_params& info = out->objects[obj];
info.present = static_cast<std::uint8_t>(reader.read(1));
if (reader.failed()) {
return truncated_frame(reader, out, payload, payload_size);
}
if (info.present == 0u) {
continue;
}
info.num_bands_idx = static_cast<std::uint8_t>(reader.read(3));
if (reader.failed()) {
return truncated_frame(reader, out, payload, payload_size);
}
const std::int16_t bands = num_bands_for_index(info.num_bands_idx);
if (bands < 0) {
return syntax_fail("unknown JOC num_bands index " +
std::to_string(info.num_bands_idx));
// The symbol count depends on the parameter-band count, so the rest
// of the payload cannot be parsed.
if (out->status == JOC_FRAME_STATUS_OK) {
out->status = JOC_FRAME_STATUS_BAD_PARAMETER_BAND;
}
tail_info(out, reader, payload, payload_size);
return Status::success();
}
info.n_bands = static_cast<std::uint8_t>(bands);
info.sparse = static_cast<std::uint8_t>(reader.read(1));
@@ -242,16 +320,42 @@ Status parse_id14(const std::uint8_t* payload, std::size_t payload_size, joc_fra
info.slope_idx = static_cast<std::uint8_t>(reader.read(1));
info.num_dpoints_bits = static_cast<std::uint8_t>(reader.read(1));
info.n_dpoints = static_cast<std::uint8_t>(info.num_dpoints_bits + 1u);
if (reader.failed()) {
return truncated_frame(reader, out, payload, payload_size);
}
if (info.slope_idx == 1u) {
for (std::uint32_t dp = 0; dp < info.n_dpoints; ++dp) {
info.offset_ts[dp] = static_cast<std::uint8_t>(reader.read(5) + 1u);
info.offset_ts[dp] = static_cast<std::uint8_t>(reader.read(5));
}
if (reader.failed()) {
return truncated_frame(reader, out, payload, payload_size);
}
// offset_ts is the raw 5-bit slot index (legal range 0..23) and one
// object's data points must be strictly increasing.
bool invalid = false;
for (std::uint32_t dp = 0; dp < info.n_dpoints; ++dp) {
if (info.offset_ts[dp] >= JOC_TIMESLOTS) {
invalid = true;
break;
}
}
if (!invalid && info.n_dpoints > 1u) {
for (std::uint32_t dp = 1; dp < info.n_dpoints; ++dp) {
if (info.offset_ts[dp] <= info.offset_ts[dp - 1u]) {
invalid = true;
break;
}
}
}
if (invalid && out->status == JOC_FRAME_STATUS_OK) {
out->status = JOC_FRAME_STATUS_BAD_OFFSET_TS;
}
}
}
if (reader.failed()) {
return truncated_fail(reader);
}
// joc_data (Huffman): dense reads MTX per channel and band, sparse reads IDX
// then VEC. A frame whose status is already non-zero dequantizes below but
// is never rendered, so a misaligned parse cannot reach the DSP.
for (std::uint32_t obj = 0; obj < n_objects; ++obj) {
const joc_object_params& info = out->objects[obj];
if (info.present == 0u) {
@@ -268,13 +372,13 @@ Status parse_id14(const std::uint8_t* payload, std::size_t payload_size, joc_fra
const Tree idx_tree = select_tree(info.quant_idx, SymbolKind::Idx, n_channels);
const std::uint32_t first = reader.read(3);
if (reader.failed()) {
return truncated_fail(reader);
return truncated_frame(reader, out, payload, payload_size);
}
symbol->idx[dp][0] = static_cast<std::uint8_t>(first);
for (int pb = 1; pb < info.n_bands; ++pb) {
std::int16_t value = 0;
if (!huff_decode(idx_tree, reader, &value)) {
return truncated_fail(reader);
return truncated_frame(reader, out, payload, payload_size);
}
symbol->idx[dp][pb] = static_cast<std::uint8_t>(value);
}
@@ -282,7 +386,7 @@ Status parse_id14(const std::uint8_t* payload, std::size_t payload_size, joc_fra
for (int pb = 0; pb < info.n_bands; ++pb) {
std::int16_t value = 0;
if (!huff_decode(vec_tree, reader, &value)) {
return truncated_fail(reader);
return truncated_frame(reader, out, payload, payload_size);
}
symbol->vec[dp][pb] = value;
}
@@ -292,7 +396,7 @@ Status parse_id14(const std::uint8_t* payload, std::size_t payload_size, joc_fra
for (int pb = 0; pb < info.n_bands; ++pb) {
std::int16_t value = 0;
if (!huff_decode(mtx_tree, reader, &value)) {
return truncated_fail(reader);
return truncated_frame(reader, out, payload, payload_size);
}
symbol->mtx[dp][ch][pb] = value;
}
@@ -301,12 +405,16 @@ Status parse_id14(const std::uint8_t* payload, std::size_t payload_size, joc_fra
}
}
out->data_end_bits = static_cast<std::uint32_t>(reader.position());
out->trailing_bits = static_cast<std::uint32_t>(payload_size * 8u - reader.position());
const std::size_t tail_offset = reader.position() / 8u;
if (tail_offset < payload_size) {
const std::size_t tail_bytes = std::min<std::size_t>(8u, payload_size - tail_offset);
std::memcpy(out->tail_bytes, payload + tail_offset, tail_bytes);
tail_info(out, reader, payload, payload_size);
if (out->status == JOC_FRAME_STATUS_OK && out->ext_config_idx == 0u) {
// The tail pads with zero bits up to the next byte; a whole byte after
// that alignment is unexpected data.
const std::uint32_t pad =
(8u - (static_cast<std::uint32_t>(reader.position()) % 8u)) % 8u;
const std::uint32_t total_bits = static_cast<std::uint32_t>(payload_size * 8u);
if (total_bits > static_cast<std::uint32_t>(reader.position()) + pad) {
out->status = JOC_FRAME_STATUS_TRAILING_DATA;
}
}
for (std::uint32_t obj = 0; obj < n_objects; ++obj) {
@@ -314,8 +422,7 @@ Status parse_id14(const std::uint8_t* payload, std::size_t payload_size, joc_fra
if (info.present == 0u) {
continue;
}
std::uint32_t mask_bit = 1u << obj;
out->present_mask |= mask_bit;
out->present_mask |= 1u << obj;
const std::int64_t nquant = (info.quant_idx == 0u) ? 96 : 192;
std::int64_t q[JOC_MAX_DPOINTS][JOC_MAX_CORE_CHANNELS][JOC_MAX_PARAMETER_BANDS] = {};
@@ -361,13 +468,45 @@ Status parse_id14(const std::uint8_t* payload, std::size_t payload_size, joc_fra
return Status::success();
}
int score_container_as_joc(const std::uint8_t* data, std::size_t size,
const emdf::Container& container) {
const emdf::Payload* payload = container.find(emdf::kIdJoc);
const emdf::Payload* oamd = container.find(emdf::kIdOamd);
if (payload == nullptr || oamd == nullptr) {
return 0;
}
bool parses = false;
std::vector<std::uint8_t> bytes;
if (emdf::extract_payload_bytes(data, size, *payload, &bytes).ok()) {
joc_frame_params params;
FrameSymbols symbols;
if (parse_id14(bytes.data(), bytes.size(), &params, &symbols).ok()) {
// The reference scores a payload by the frame status: an unsupported
// downmix configuration (2), an unknown parameter-band count (4) or a
// payload that ends inside joc_data (7) must not win the container
// choice, because another candidate may carry the frame's complete
// metadata.
parses = params.status != JOC_FRAME_STATUS_UNSUPPORTED_DMX &&
params.status != JOC_FRAME_STATUS_BAD_PARAMETER_BAND &&
params.status != JOC_FRAME_STATUS_TRUNCATED;
}
}
const bool associated = oamd->has_group_id != 0u && payload->has_group_id != 0u &&
oamd->group_id == payload->group_id;
if (associated && parses) {
return 2;
}
return parses ? 1 : 0;
}
Status parse_eac3_frame(const std::uint8_t* frame, std::size_t frame_size, joc_frame_params* out,
emdf::Container* container, FrameSymbols* symbols) {
if (frame == nullptr || out == nullptr) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kJoc, "null frame or output");
}
emdf::Container local;
const Status status = emdf::find_joc_emdf(frame, frame_size, &local);
const Status status =
emdf::find_joc_emdf(frame, frame_size, &local, &score_container_as_joc, nullptr);
if (!status.ok()) {
return status;
}
@@ -384,7 +523,20 @@ Status parse_eac3_frame(const std::uint8_t* frame, std::size_t frame_size, joc_f
if (!extract.ok()) {
return extract;
}
return parse_id14(bytes.data(), bytes.size(), out, symbols);
const Status parsed = parse_id14(bytes.data(), bytes.size(), out, symbols);
if (!parsed.ok()) {
return parsed;
}
// A metadata scan rejects an unsupported downmix configuration outright: the
// core channel count decides how every later frame is expanded, so this is a
// variant error rather than a per-frame status.
if (out->status == JOC_FRAME_STATUS_UNSUPPORTED_DMX) {
const std::string message =
"downmix_config_unsupported: ID14 declares joc_dmx_config_idx=" +
std::to_string(out->dmx_config_idx) + " (legal values are 0..4)";
return Status::fail(JOC_ERR_JOC_UNSUPPORTED_VARIANT, stage::kJoc, message);
}
return Status::success();
}
Status check_id14_padding(const std::uint8_t* payload, std::size_t payload_size,
@@ -395,6 +547,21 @@ Status check_id14_padding(const std::uint8_t* payload, std::size_t payload_size,
if (!status.ok()) {
return status;
}
// The statuses that stop the parse early leave the payload without a
// joc_data end position, so they keep reporting the failure they reported
// before the frame-status split.
if (params.status == JOC_FRAME_STATUS_UNSUPPORTED_DMX) {
return Status::fail(JOC_ERR_JOC_UNSUPPORTED_VARIANT, stage::kJoc,
"downmix_config_unsupported: joc_dmx_config_idx outside 0..4");
}
if (params.status == JOC_FRAME_STATUS_BAD_PARAMETER_BAND) {
return Status::fail(JOC_ERR_JOC_SYNTAX, stage::kJoc,
"unknown JOC num_bands index stops the payload");
}
if (params.status == JOC_FRAME_STATUS_TRUNCATED) {
return Status::fail(JOC_ERR_BITSTREAM_TRUNCATED, stage::kJoc,
"the ID14 payload ends before its joc_data is complete");
}
if (out_trailing_bits != nullptr) {
*out_trailing_bits = params.trailing_bits;
}
@@ -412,4 +579,536 @@ Status check_id14_padding(const std::uint8_t* payload, std::size_t payload_size,
return Status::success();
}
void make_silent_frame_params(joc_frame_params* out) {
if (out == nullptr) {
return;
}
std::memset(out, 0, sizeof(*out));
out->struct_size = sizeof(joc_frame_params);
out->struct_version = JOC_FRAME_PARAMS_VERSION;
out->dmx_config_idx = 0u;
out->n_channels = static_cast<std::uint8_t>(JOC_CORE_CHANNELS);
out->n_objects = static_cast<std::uint8_t>(JOC_MAX_OBJECTS);
out->present_mask = (1u << JOC_MAX_OBJECTS) - 1u;
out->clipgain = 1.0;
for (unsigned object = 0; object < JOC_MAX_OBJECTS; ++object) {
out->objects[object].present = 1u;
out->objects[object].num_bands_idx = 0u; // one parameter band
out->objects[object].n_bands = 1u;
out->objects[object].sparse = 0u;
out->objects[object].quant_idx = 0u;
out->objects[object].slope_idx = 0u;
out->objects[object].num_dpoints_bits = 0u;
out->objects[object].n_dpoints = 1u;
}
}
// ---------------------------------------------------------------------------
// Channel identity / bed layout (spec sections 3, 10.2, 10.4)
// ---------------------------------------------------------------------------
namespace {
struct PositionBit {
Position position;
std::uint32_t bit;
};
// Position -> ffmpeg channel bit. A decoded bed frame lists its channels in
// ascending bit order, so sorting the positions by bit reproduces the decoder's
// channel order without asking the decoder.
constexpr PositionBit kPositionBits[] = {
{Position::kLeft, 0x1u},
{Position::kRight, 0x2u},
{Position::kCenter, 0x4u},
{Position::kLfe, 0x8u},
{Position::kLeftRearSurround, 0x10u},
{Position::kRightRearSurround, 0x20u},
{Position::kCenterSurround, 0x100u},
{Position::kLeftSurround, 0x200u},
{Position::kRightSurround, 0x400u},
{Position::kTopSurround, 0x800u},
{Position::kVerticalHeightLeft, 0x1000u},
{Position::kVerticalHeightCenter, 0x2000u},
{Position::kVerticalHeightRight, 0x4000u},
{Position::kTopSurroundLeft, 0x8000u},
{Position::kTopSurroundRight, 0x20000u},
};
std::uint32_t position_bit(Position position) {
for (const PositionBit& entry : kPositionBits) {
if (entry.position == position) {
return entry.bit;
}
}
return 0u;
}
void push_unique(std::vector<Position>* positions, Position position) {
if (position == Position::kNone) {
return;
}
for (const Position existing : *positions) {
if (existing == position) {
return;
}
}
positions->push_back(position);
}
// ADM 10-slot skeleton placement of the extra pair, indexed by joc_dmx_config_idx.
constexpr int kExtraPairSlots[5][2] = {
{-1, -1}, {6, 7}, {8, 9}, {-1, -1}, {8, 9},
};
Status variant_error(const char* stage_name, const char* name, const std::string& message,
std::string* error) {
const std::string text = std::string(name) + ": " + message;
if (error != nullptr) {
*error = text;
}
return Status::fail(JOC_ERR_JOC_UNSUPPORTED_VARIANT, stage_name, text);
}
std::string position_name(Position position) {
switch (position) {
case Position::kLeft: return "L";
case Position::kRight: return "R";
case Position::kCenter: return "C";
case Position::kLfe: return "LFE";
case Position::kLeftSurround: return "Ls";
case Position::kRightSurround: return "Rs";
case Position::kLeftRearSurround: return "Lrs";
case Position::kRightRearSurround: return "Rrs";
case Position::kVerticalHeightLeft: return "Vhl";
case Position::kVerticalHeightRight: return "Vhr";
case Position::kTopSurroundLeft: return "Lts";
case Position::kTopSurroundRight: return "Rts";
case Position::kCenterSurround: return "Cs";
case Position::kTopSurround: return "Ts";
case Position::kVerticalHeightCenter: return "Vhc";
case Position::kLfe2: return "LFE2";
default: return "?";
}
}
// 核心声道位置 → 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 text = "[";
for (std::size_t index = 0; index < positions.size(); ++index) {
if (index != 0) {
text += ",";
}
text += position_name(positions[index]);
}
return text + "]";
}
} // namespace
void expand_chanmap(std::uint16_t chanmap, std::vector<Position>* out) {
if (out == nullptr) {
return;
}
// Table E2.5; bit 0 sits in the field's most significant bit.
static const Position kSingles[16] = {
Position::kLeft, Position::kCenter, Position::kRight,
Position::kLeftSurround, Position::kRightSurround, Position::kNone,
Position::kNone, Position::kCenterSurround, Position::kTopSurround,
Position::kNone, Position::kNone, Position::kNone,
Position::kVerticalHeightCenter, Position::kNone, Position::kLfe2,
Position::kLfe,
};
for (int bit = 0; bit < 16; ++bit) {
if (((chanmap >> (15 - bit)) & 1u) == 0u) {
continue;
}
switch (bit) {
case 5:
out->push_back(Position::kLeftSurround);
out->push_back(Position::kRightSurround);
break;
case 6:
out->push_back(Position::kLeftRearSurround);
out->push_back(Position::kRightRearSurround);
break;
case 9:
case 10:
// Lsd/Rsd and Lw/Rw have no JOC counterpart and stay unmapped.
break;
case 11:
out->push_back(Position::kVerticalHeightLeft);
out->push_back(Position::kVerticalHeightRight);
break;
case 13:
out->push_back(Position::kTopSurroundLeft);
out->push_back(Position::kTopSurroundRight);
break;
default:
out->push_back(kSingles[bit]);
break;
}
}
}
void acmod_positions(std::uint8_t acmod, std::vector<Position>* out) {
if (out == nullptr) {
return;
}
switch (acmod) {
case 0:
case 1:
out->push_back(Position::kCenter);
break;
case 2:
out->push_back(Position::kLeft);
out->push_back(Position::kRight);
break;
case 3:
out->push_back(Position::kLeft);
out->push_back(Position::kCenter);
out->push_back(Position::kRight);
break;
case 4:
out->push_back(Position::kLeft);
out->push_back(Position::kRight);
out->push_back(Position::kCenterSurround);
break;
case 5:
out->push_back(Position::kLeft);
out->push_back(Position::kCenter);
out->push_back(Position::kRight);
out->push_back(Position::kCenterSurround);
break;
case 6:
out->push_back(Position::kLeft);
out->push_back(Position::kRight);
out->push_back(Position::kLeftSurround);
out->push_back(Position::kRightSurround);
break;
case 7:
default:
out->push_back(Position::kLeft);
out->push_back(Position::kCenter);
out->push_back(Position::kRight);
out->push_back(Position::kLeftSurround);
out->push_back(Position::kRightSurround);
break;
}
}
void expected_pair(std::uint8_t dmx_config_idx, std::vector<Position>* out) {
if (out == nullptr) {
return;
}
if (dmx_config_idx == 1u) {
out->push_back(Position::kLeftRearSurround);
out->push_back(Position::kRightRearSurround);
} else if (dmx_config_idx == 2u || dmx_config_idx == 4u) {
out->push_back(Position::kVerticalHeightLeft);
out->push_back(Position::kVerticalHeightRight);
}
}
void chanmap_extra_pair(const std::vector<Position>& core, std::uint16_t chanmap,
std::vector<Position>* out) {
if (out == nullptr) {
return;
}
std::vector<Position> declared;
expand_chanmap(chanmap, &declared);
for (const Position position : declared) {
bool in_core = false;
for (const Position existing : core) {
if (existing == position) {
in_core = true;
break;
}
}
if (!in_core) {
push_unique(out, position);
}
}
}
int bed_channels_for_core(int core_channels) {
return core_channels == 7 ? 8 : 6;
}
Status compute_bed_plan(const eac3::Frame* core_frame, bool has_core, bool has_dependent,
bool has_chanmap, std::uint16_t chanmap, std::uint8_t dmx_config_idx,
BedPlan* out) {
if (out == nullptr) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kJoc, "null bed plan");
}
const std::int16_t core_channels = num_channels_for_config(dmx_config_idx);
if (core_channels < 0) {
return variant_error("joc", "unsupported_configuration",
"unknown JOC downmix configuration " +
std::to_string(dmx_config_idx), nullptr);
}
std::vector<Position> core_positions;
if (has_core && core_frame != nullptr) {
acmod_positions(core_frame->acmod, &core_positions);
if (core_frame->lfeon != 0u) {
core_positions.push_back(Position::kLfe);
}
}
std::vector<Position> extra;
std::vector<Position> locations = core_positions;
if (has_dependent && has_chanmap) {
std::vector<Position> declared;
expand_chanmap(chanmap, &declared);
chanmap_extra_pair(core_positions, chanmap, &extra);
locations.insert(locations.end(), declared.begin(), declared.end());
}
std::vector<Position> ordered;
for (const Position position : locations) {
push_unique(&ordered, position);
}
std::sort(ordered.begin(), ordered.end(), [](Position left, Position right) {
return position_bit(left) < position_bit(right);
});
for (const Position position : ordered) {
if (position_bit(position) == 0u) {
return variant_error("eac3", "bed_channel_mapping_unsupported",
"unmapped channel position " + position_name(position),
nullptr);
}
}
BedPlan plan;
plan.channels = static_cast<int>(ordered.size());
const int expected_channels = bed_channels_for_core(core_channels);
if (plan.channels != expected_channels) {
return variant_error("eac3", "core_channel_count_mismatch",
"the bed declares " + std::to_string(plan.channels) +
" channels, configuration " + std::to_string(dmx_config_idx) +
" needs " + std::to_string(expected_channels),
nullptr);
}
for (int index = 0; index < plan.channels; ++index) {
if (ordered[index] == Position::kLfe) {
plan.lfe_channel = index;
}
}
std::vector<Position> wanted = {Position::kLeft, Position::kRight, Position::kCenter,
Position::kLeftSurround, Position::kRightSurround};
wanted.insert(wanted.end(), extra.begin(), extra.end());
if (wanted.size() != static_cast<std::size_t>(core_channels)) {
return variant_error("eac3", "chanmap_cfg_mismatch",
"the bed cannot supply " + std::to_string(core_channels) +
" JOC core channels (found " + std::to_string(wanted.size()) +
")",
nullptr);
}
for (std::size_t lane = 0; lane < wanted.size(); ++lane) {
int found = -1;
for (int index = 0; index < plan.channels; ++index) {
if (ordered[index] == wanted[lane]) {
found = index;
break;
}
}
if (found < 0) {
return variant_error("eac3", "bed_channel_mapping_unsupported",
"channel " + position_name(wanted[lane]) +
" is missing from the bed " + position_list(ordered),
nullptr);
}
plan.lane[lane] = found;
}
if (dmx_config_idx < 5u) {
plan.extra_pair_slot[0] = kExtraPairSlots[dmx_config_idx][0];
plan.extra_pair_slot[1] = kExtraPairSlots[dmx_config_idx][1];
}
*out = plan;
return Status::success();
}
Status compute_bed_plan_for_config(std::uint8_t dmx_config_idx, BedPlan* out) {
if (out == nullptr) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kJoc, "null bed plan");
}
const std::int16_t core_channels = num_channels_for_config(dmx_config_idx);
if (core_channels < 0) {
return variant_error("joc", "unsupported_configuration",
"unknown JOC downmix configuration " +
std::to_string(dmx_config_idx), nullptr);
}
std::vector<Position> extra;
expected_pair(dmx_config_idx, &extra);
std::vector<Position> wanted = {Position::kLeft, Position::kRight, Position::kCenter,
Position::kLeftSurround, Position::kRightSurround};
wanted.insert(wanted.end(), extra.begin(), extra.end());
std::vector<Position> ordered = {Position::kLeft, Position::kRight, Position::kCenter,
Position::kLfe, Position::kLeftSurround,
Position::kRightSurround};
ordered.insert(ordered.end(), extra.begin(), extra.end());
std::sort(ordered.begin(), ordered.end(), [](Position left, Position right) {
return position_bit(left) < position_bit(right);
});
ordered.erase(std::unique(ordered.begin(), ordered.end()), ordered.end());
BedPlan plan;
plan.channels = static_cast<int>(ordered.size());
for (int index = 0; index < plan.channels; ++index) {
if (ordered[index] == Position::kLfe) {
plan.lfe_channel = index;
}
}
for (std::size_t lane = 0; lane < wanted.size(); ++lane) {
for (int index = 0; index < plan.channels; ++index) {
if (ordered[index] == wanted[lane]) {
plan.lane[lane] = index;
break;
}
}
if (plan.lane[lane] < 0) {
return variant_error("eac3", "bed_channel_mapping_unsupported",
"channel " + position_name(wanted[lane]) +
" is missing from the bed " + position_list(ordered),
nullptr);
}
}
if (dmx_config_idx < 5u) {
plan.extra_pair_slot[0] = kExtraPairSlots[dmx_config_idx][0];
plan.extra_pair_slot[1] = kExtraPairSlots[dmx_config_idx][1];
}
*out = plan;
return Status::success();
}
Status check_cross_layer(const joc_frame_params& params, const eac3::Frame* core_frame,
bool has_core, bool has_dependent, bool has_chanmap,
std::uint16_t chanmap,
const std::vector<oamd::BedAssignment>* bed_assignments,
std::string* error, CrossLayerNotes* notes) {
(void)has_dependent;
const std::uint8_t config_idx = params.dmx_config_idx;
const int core_channels = params.n_channels;
std::vector<Position> wanted;
expected_pair(config_idx, &wanted);
if (params.ext_config_idx != 0u) {
return variant_error("joc", "ext_config_idx_unsupported",
"joc_ext_config_idx=" + std::to_string(params.ext_config_idx) +
" has no mapping in this implementation",
error);
}
if (core_channels != JOC_CORE_CHANNELS && core_channels != JOC_MAX_CORE_CHANNELS) {
return variant_error("joc", "unsupported_configuration",
"unsupported JOC core channel count " +
std::to_string(core_channels),
error);
}
std::vector<Position> core_positions;
if (has_core && core_frame != nullptr) {
acmod_positions(core_frame->acmod, &core_positions);
if (core_frame->lfeon != 0u) {
core_positions.push_back(Position::kLfe);
}
}
if (core_channels == JOC_MAX_CORE_CHANNELS) {
if (!has_core || !has_chanmap) {
return variant_error(
"eac3", "core_extension_pair",
"a 7-channel configuration needs both an independent substream and a "
"dependent-substream chanmap",
error);
}
std::vector<Position> pair;
chanmap_extra_pair(core_positions, chanmap, &pair);
if (pair != wanted) {
// The bed mapping follows the chanmap's channel codes; the name a
// configuration implies does not reach the DSP, so the frame renders
// and the disagreement is reported instead.
if (notes != nullptr) {
notes->chanmap_pair_mismatch = true;
}
}
} else if (has_chanmap) {
std::vector<Position> pair;
chanmap_extra_pair(core_positions, chanmap, &pair);
if (!pair.empty()) {
return variant_error("eac3", "core_channel_count_mismatch",
"a 5-channel configuration declares extra dependent "
"channels " + position_list(pair),
error);
}
}
std::vector<Position> declared = core_positions;
if (has_chanmap) {
std::vector<Position> expanded;
expand_chanmap(chanmap, &expanded);
for (const Position position : expanded) {
push_unique(&declared, position);
}
}
int full_band = 0;
for (const Position position : declared) {
if (position != Position::kLfe && position != Position::kLfe2) {
++full_band;
}
}
if (!declared.empty() && full_band != core_channels) {
return variant_error("eac3", "core_channel_count_mismatch",
"the substreams declare " + std::to_string(full_band) +
" full-band channels, joc_dmx_config_idx=" +
std::to_string(config_idx) + " declares " +
std::to_string(core_channels),
error);
}
if (bed_assignments != nullptr && !bed_assignments->empty()) {
// OAMD 的 bed 掩码描述的是内容的 bed 布局,可以比核心子流实际编码的声道多
// (例如 9.1.6 bed 只编 5.1 核心)。只有核心声道在 bed 布局里找不到位置才是
// 真正的不一致;多出来的 bed 声道是布局的一部分。
const BedLayout bed = resolve_bed_layout(*bed_assignments, true);
if (bed.present && bed.complete) {
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 (!covered && notes != nullptr) {
notes->bed_mask_mismatch = true;
}
}
}
return Status::success();
}
} // namespace joc::joc
+93
View File
@@ -6,9 +6,11 @@
#include <cstdint>
#include <vector>
#include "eac3_transport/eac3_reader.h"
#include "joc_core.h"
#include "emdf/emdf_parser.h"
#include "foundation/status.h"
#include "oamd/oamd_parser.h"
namespace joc::joc {
@@ -39,8 +41,99 @@ Status parse_eac3_frame(const std::uint8_t* frame, std::size_t frame_size, joc_f
Status check_id14_padding(const std::uint8_t* payload, std::size_t payload_size,
std::uint32_t* out_trailing_bits);
// Scores this container as the frame's JOC metadata when the syncframe holds more
// than one (spec section 8.2 and its Table 56 associate the OAMD and JOC payloads
// of one frame by an equal group id). 2 = the two payloads share a group id and
// ID14 parses as a complete joc() payload, 1 = ID14 parses, 0 = neither. A
// container whose ID14 declares far more objects than its bytes could hold, or
// whose ID11 carries no group id at all, is some other structure.
int score_container_as_joc(const std::uint8_t* data, std::size_t size,
const emdf::Container& container);
// Parameters for an audio frame that carries no JOC payload: every object is
// "present" with an all-zero matrix, so the kernel renders silence while its
// analysis and synthesis state keep advancing in step with the stream.
void make_silent_frame_params(joc_frame_params* out);
std::int16_t num_channels_for_config(std::uint32_t dmx_config_idx);
std::int16_t num_bands_for_index(std::uint32_t num_bands_idx);
// ---------------------------------------------------------------------------
// Channel identity / bed layout (spec sections 3, 10.2, 10.4)
//
// This is the position layer only: it decides which decoded bed channel feeds
// which JOC input lane and which ADM bed slot the extra pair occupies. The DSP
// never reads it.
// ---------------------------------------------------------------------------
enum class Position : std::uint8_t {
kNone = 0,
kLeft,
kRight,
kCenter,
kLfe,
kLeftSurround,
kRightSurround,
kLeftRearSurround,
kRightRearSurround,
kVerticalHeightLeft,
kVerticalHeightRight,
kTopSurroundLeft,
kTopSurroundRight,
kCenterSurround,
kTopSurround,
kVerticalHeightCenter,
kLfe2,
};
// Table E2.5 expansion; the field's most significant bit is table bit 0.
void expand_chanmap(std::uint16_t chanmap, std::vector<Position>* out);
// A/52 acmod -> full-band positions in decoding order (LFE excluded).
void acmod_positions(std::uint8_t acmod, std::vector<Position>* out);
// The pair joc_dmx_config_idx declares; empty for configurations 0 and 3.
void expected_pair(std::uint8_t dmx_config_idx, std::vector<Position>* out);
// The extra pair a dependent-substream chanmap adds on top of the core channels.
void chanmap_extra_pair(const std::vector<Position>& core, std::uint16_t chanmap,
std::vector<Position>* out);
// Decoded-bed channel count implied by the JOC core channel count.
int bed_channels_for_core(int core_channels);
// bed[lane] = decoded PCM channel index feeding JOC lane 'lane'.
struct BedPlan {
int channels = 0; // 6 or 8
int lfe_channel = -1;
int lane[JOC_MAX_CORE_CHANNELS] = {-1, -1, -1, -1, -1, -1, -1};
int extra_pair_slot[2] = {-1, -1}; // ADM skeleton
};
Status compute_bed_plan(const eac3::Frame* core_frame, bool has_core, bool has_dependent,
bool has_chanmap, std::uint16_t chanmap, std::uint8_t dmx_config_idx,
BedPlan* out);
// Bed plan driven by joc_dmx_config_idx alone, for callers that hold no L2
// header: the extra pair is the one the configuration declares.
Status compute_bed_plan_for_config(std::uint8_t dmx_config_idx, BedPlan* out);
// Identity disagreements that leave the DSP input unchanged (spec section 10.1:
// channel identity never enters the DSP): the extra pair's name is metadata only,
// so a mismatch is reported through CrossLayerNotes instead of refusing the frame.
struct CrossLayerNotes {
bool chanmap_pair_mismatch = false; // spec 11.2 check 1: chanmap vs k
bool bed_mask_mismatch = false; // spec 11.2 check 2: OAMD bed mask vs k
};
// Spec section 11.2 cross-layer consistency. A mismatch in the core channel count
// or in joc_ext_config_idx changes the DSP input and is a variant error; the two
// identity checks are recorded in `notes` and the frame still renders.
Status check_cross_layer(const joc_frame_params& params, const eac3::Frame* core_frame,
bool has_core, bool has_dependent, bool has_chanmap,
std::uint16_t chanmap,
const std::vector<oamd::BedAssignment>* bed_assignments,
std::string* error, CrossLayerNotes* notes = nullptr);
} // namespace joc::joc
+617 -72
View File
@@ -69,7 +69,22 @@ public:
std::memset(synthesis_state_, 0, sizeof(synthesis_state_));
std::memset(x_, 0, sizeof(x_));
std::memset(z_, 0, sizeof(z_));
analysis_phase_ = 0.0625f;
// Frame-level state: per-object previous matrices and presence markers,
// the seq state machine, the 8-plane passthrough history, the LFE ramp
// start value and the previous actual core-channel count.
std::memset(prev_matrix_, 0, sizeof(prev_matrix_));
std::memset(prev_present_, 0, sizeof(prev_present_));
std::memset(core_history_, 0, sizeof(core_history_));
state_ = 0;
expected_seq_ = 0;
invalid_count_ = 0;
last_frame_valid_ = false;
n_channels_prev_ = -1;
has_lfe_clipgain_ = false;
lfe_clipgain_ = 0.0;
// Sentinel: the first frame after reset takes the new scalar directly,
// without an intra-frame transition.
analysis_phase_ = -0.5f;
error_[0] = '\0';
return 0;
}
@@ -125,13 +140,11 @@ public:
return error_[0] ? error_ : "";
}
void set_dc_filter(const bool enabled) noexcept {
dc_filter_enabled_ = enabled;
}
int process(
const float* bed5,
const float* bed_planar,
const float* lfe,
const uint32_t core_channel_count,
const uint32_t phase_shift,
const uint32_t object_mask,
const uint8_t* n_bands,
const uint8_t* n_dpoints,
@@ -144,9 +157,14 @@ public:
float* output16) noexcept {
error_[0] = '\0';
if (!bed5 || !n_bands || !n_dpoints || !slope_idx || !offset_ts || !dq || !output16) {
if (!bed_planar || !n_bands || !n_dpoints || !slope_idx || !offset_ts || !dq || !output16) {
return fail("null pointer passed to ejoc_renderer_process");
}
if (core_channel_count < EJOC_CORE_CHANNELS || core_channel_count > EJOC_MAX_CORE_CHANNELS) {
return fail("core_channel_count must be 5 or 7");
}
core_channels_ = core_channel_count;
phase_shift_enabled_ = phase_shift != 0u;
if (object_mask & ~((1u << EJOC_MAX_OBJECTS) - 1u)) {
return fail("object_mask contains an object index above 14");
}
@@ -169,13 +187,22 @@ public:
}
std::memset(output16, 0, sizeof(float) * EJOC_OUTPUT_CHANNELS * EJOC_FRAME_SAMPLES);
analysis(bed5, phase_new);
render_lfe(lfe, output_scale, output16);
// 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
// cancels the 1/16, so the net effect is a multiply by joc_clipgain.
analysis(bed_planar, static_cast<float>(phase_new * clipgain));
decode_lfe(lfe, clipgain, output16, output_scale);
process_objects(object_mask, n_bands, n_dpoints, slope_idx, offset_ts,
dq, clipgain, output_scale, output16);
dq, output_scale, output16);
return 0;
}
// Frame-level entry point; the state machine and per-object history live
// inside the renderer (see render_frame_impl()).
int render_frame(const ejoc_frame_input& input) noexcept {
return render_frame_impl(input);
}
private:
void initialize_tables() noexcept {
for (int i = 0; i < 64; ++i) {
@@ -299,7 +326,8 @@ private:
for (int band = 0; band < 64; ++band) {
current[slot][band] = x_[channel][band][group + slot];
const Complex delayed = surround_delay_[surround][slot][band];
x_[channel][band][group + slot] = {delayed.im, -delayed.re};
x_[channel][band][group + slot] =
phase_shift_enabled_ ? Complex{delayed.im, -delayed.re} : delayed;
}
}
@@ -309,7 +337,7 @@ private:
for (int i = 0; i < 4; ++i) {
dc_buffer[20 + i] = current[i][0];
}
if (dc_filter_enabled_) {
if (phase_shift_enabled_) {
for (int slot = 0; slot < 4; ++slot) {
Complex sum{0.0, 0.0};
for (int tap = 0; tap < 21; ++tap) {
@@ -338,7 +366,7 @@ private:
}
void analysis_channel(const int channel) noexcept {
const float* bed5 = job_bed5_;
const float* bed_planar = job_bed_;
const float phase_old = job_phase_old_;
const float phase_new = job_phase_new_;
const bool ramp_phase = phase_old != phase_new;
@@ -354,37 +382,48 @@ private:
const float product = static_cast<float>(static_cast<float>(frame_sample) * phase_step);
gain = static_cast<float>(phase_old + product);
}
scaled[sample] = static_cast<float>(bed5[channel * 1536 + frame_sample] * gain);
scaled[sample] = static_cast<float>(bed_planar[channel * 1536 + frame_sample] * gain);
}
// L/R/C and, for 7 core channels, the extra pair (5 and 6) take the
// ten-slot delay here; Ls/Rs take the same delay inside surround_post().
const float* analysis_input = scaled;
if (channel < 3) {
std::memcpy(delayed, analysis_delay_[channel][0], sizeof(delayed));
std::memmove(&analysis_delay_[channel][0][0],
&analysis_delay_[channel][1][0],
const int delay_lane = channel < 3 ? channel : channel - 2;
if (channel < 3 || channel >= 5) {
std::memcpy(delayed, analysis_delay_[delay_lane][0], sizeof(delayed));
std::memmove(&analysis_delay_[delay_lane][0][0],
&analysis_delay_[delay_lane][1][0],
sizeof(float) * 9 * 64);
std::memcpy(analysis_delay_[channel][9], scaled, sizeof(scaled));
std::memcpy(analysis_delay_[delay_lane][9], scaled, sizeof(scaled));
analysis_input = delayed;
}
analysis_slot(channel, analysis_input, timeslot);
}
}
void analysis(const float* bed5, const float phase_new) noexcept {
job_bed5_ = bed5;
// Frames the analysis QMF of the core PCM with the given analysis-side
// scalar (the structural 1/16 times joc_clipgain). The scalar ramps over the
// frame's first 256 samples from the previous frame's value; the first frame
// after a reset takes it directly.
void analysis(const float* bed_planar, const float scalar) noexcept {
job_bed_ = bed_planar;
job_phase_old_ = analysis_phase_;
job_phase_new_ = phase_new;
if (job_phase_old_ <= 0.0f && job_phase_old_ != 0.0f) {
job_phase_old_ = scalar;
}
job_phase_new_ = scalar;
job_kind_ = JobKind::Analysis;
job_count_ = 5;
for (int channel = 0; channel < 5; ++channel) {
job_objects_[channel] = channel;
job_count_ = static_cast<int>(core_channels_);
for (uint32_t channel = 0; channel < core_channels_; ++channel) {
job_objects_[channel] = static_cast<int>(channel);
}
dispatch_jobs();
analysis_phase_ = phase_new;
analysis_phase_ = scalar;
surround_post();
}
static std::size_t dq_index(const int object, const int point, const int channel, const int band) noexcept {
return static_cast<std::size_t>((((object * 2 + point) * 5 + channel) * kMaxBands) + band);
return static_cast<std::size_t>(
(((object * 2 + point) * EJOC_MAX_CORE_CHANNELS + channel) * kMaxBands) + band);
}
void matrix_object(
@@ -401,7 +440,7 @@ private:
const int slope = slope_idx[object];
const uint8_t* pb_map = parameter_band_map(bands);
for (int channel = 0; channel < 5; ++channel) {
for (uint32_t channel = 0; channel < core_channels_; ++channel) {
for (int subband = 0; subband < 64; ++subband) {
const int parameter_band = pb_map[subband];
const double previous = matrix_previous_[object][channel][subband];
@@ -465,7 +504,6 @@ private:
void synthesis_object(
const int object,
const double clipgain,
const float output_scale,
float* output16) noexcept {
@@ -492,9 +530,11 @@ private:
}
qmf5_step(state, rotated, pcm64);
for (int sample = 0; sample < 64; ++sample) {
// The clamp is on the ×16 object PCM; joc_clipgain already
// entered the analysis, so only the user output gain remains, and
// it is a float32 multiply like the reference.
const double clipped = clamp_unit(16.0 * pcm64[sample]);
const float value = static_cast<float>(clipped * clipgain);
destination[timeslot * 64 + sample] = static_cast<float>(value * output_scale);
destination[timeslot * 64 + sample] = static_cast<float>(clipped) * output_scale;
}
}
}
@@ -502,7 +542,7 @@ private:
void process_one_object(const int object) noexcept {
matrix_object(object, job_n_bands_, job_n_dpoints_, job_slope_idx_,
job_offset_ts_, job_dq_);
synthesis_object(object, job_clipgain_, job_output_scale_, job_output16_);
synthesis_object(object, job_output_scale_, job_output16_);
}
void execute_job_loop() noexcept {
@@ -514,8 +554,10 @@ private:
const int item = job_objects_[index];
if (job_kind_ == JobKind::Analysis) {
analysis_channel(item);
} else {
} else if (job_kind_ == JobKind::Objects) {
process_one_object(item);
} else {
process_one_object_frame(item);
}
}
}
@@ -576,7 +618,6 @@ private:
const uint8_t* slope_idx,
const uint8_t* offset_ts,
const double* dq,
const double clipgain,
const float output_scale,
float* output16) noexcept {
@@ -596,31 +637,509 @@ private:
job_slope_idx_ = slope_idx;
job_offset_ts_ = offset_ts;
job_dq_ = dq;
job_clipgain_ = clipgain;
job_output_scale_ = output_scale;
job_output16_ = output16;
dispatch_jobs();
}
void render_lfe(const float* lfe, const float output_scale, float* output16) noexcept {
if (!lfe) {
return;
// Core LFE: the full joc_clipgain is applied as a sample-wise ramp before the
// 1217-sample delay, and the read-out is only clamped. The ramp is
// G_old + n*(G_new-G_old)/256 for n < 256 and G_new afterwards; the first
// frame after a reset uses G_old = G_new.
void decode_lfe(const float* lfe, const double clipgain, float* output16,
const float output_scale) noexcept {
const double new_gain = clipgain;
const double old_gain = has_lfe_clipgain_ ? lfe_clipgain_ : new_gain;
const bool ramped = old_gain != new_gain;
const double step = (new_gain - old_gain) / 256.0;
double ramp[256];
for (int n = 0; n < 256; ++n) {
ramp[n] = ramped ? old_gain + static_cast<double>(n) * step : new_gain;
}
has_lfe_clipgain_ = true;
lfe_clipgain_ = new_gain;
float* channel0 = output16;
for (int sample = 0; sample < kLfeDelay; ++sample) {
channel0[sample] =
static_cast<float>(clamp_unit(lfe_delay_[sample])) * output_scale;
}
for (int sample = kLfeDelay; sample < EJOC_FRAME_SAMPLES; ++sample) {
const int input = sample - kLfeDelay;
const double gain = input < 256 ? ramp[input] : new_gain;
const double value = (lfe != nullptr) ? static_cast<double>(lfe[input]) : 0.0;
channel0[sample] =
static_cast<float>(clamp_unit(value * gain)) * output_scale;
}
for (int sample = 0; sample < kLfeDelay; ++sample) {
const float value = static_cast<float>(clamp_unit(lfe_delay_[sample]));
output16[sample] = static_cast<float>(value * output_scale);
}
for (int sample = kLfeDelay; sample < 1536; ++sample) {
const float value = static_cast<float>(clamp_unit(static_cast<double>(lfe[sample - kLfeDelay])));
output16[sample] = static_cast<float>(value * output_scale);
}
for (int sample = 0; sample < kLfeDelay; ++sample) {
lfe_delay_[sample] = static_cast<double>(lfe[sample + (1536 - kLfeDelay)]);
const int input = sample + (EJOC_FRAME_SAMPLES - kLfeDelay);
const double gain = input < 256 ? ramp[input] : new_gain;
const double value = (lfe != nullptr) ? static_cast<double>(lfe[input]) : 0.0;
lfe_delay_[sample] = value * gain;
}
}
enum class JobKind : uint8_t { Analysis, Objects };
enum class FrameMode : uint8_t { Normal, Hold, HardCut, Passthrough };
// ---- frame-level state machine ------------------------------------- //
// The Renderer owns the seq state machine (normal / hold / hard cut /
// passthrough), the per-object previous matrix and its presence marker, the
// analysis/synthesis state, the LFE delay ring with its clipgain ramp, and
// the 8-plane core history of the passthrough path, so one audio frame in
// produces the complete 16-channel object frame.
float held_analysis_scalar() const noexcept {
// Sentinel: a renderer that has not seen a JOC frame yet reports the
// structural 1/16, i.e. clipgain 1.0.
return (analysis_phase_ <= 0.0f && analysis_phase_ != 0.0f) ? 0.0625f
: analysis_phase_;
}
double held_clipgain() const noexcept {
return static_cast<double>(held_analysis_scalar()) * 16.0;
}
// The 10-bit JOC sequence counter wraps from 1023 back to 1.
static uint32_t next_seq(const uint32_t value) noexcept {
return value == 1023u ? 1u : value + 1u;
}
// Drops the state of the core channels a smaller layout does not use.
void clear_unused_channels(const uint32_t n_channels) noexcept {
if (n_channels >= EJOC_MAX_CORE_CHANNELS) {
return;
}
for (uint32_t channel = n_channels; channel < EJOC_MAX_CORE_CHANNELS; ++channel) {
std::memset(analysis_fifo_[channel], 0, sizeof(analysis_fifo_[channel]));
}
for (int object = 0; object < EJOC_MAX_OBJECTS; ++object) {
for (uint32_t channel = n_channels; channel < EJOC_MAX_CORE_CHANNELS; ++channel) {
std::memset(prev_matrix_[object][channel], 0,
sizeof(prev_matrix_[object][channel]));
}
}
if (n_channels == 5u) {
// A 5-channel frame does not drive the extra-pair delay lanes.
std::memset(analysis_delay_[3], 0, sizeof(analysis_delay_[3]));
std::memset(analysis_delay_[4], 0, sizeof(analysis_delay_[4]));
}
}
// A declared core-channel-count change (renderer status 9) clears the LFE
// ring; the clipgain ramp state is kept, so the gain does not retune.
void maybe_clear_lfe_ring(const uint32_t status) noexcept {
if (status == 9u) {
std::memset(lfe_delay_, 0, sizeof(lfe_delay_));
}
}
// Advances the seq state machine for this frame and reports the state the
// renderer was in before the frame. status 8 (no metadata) neither advances
// the expected counter nor compares the sequence.
uint32_t advance_state(const uint32_t status, const uint32_t seq) noexcept {
const uint32_t pre_state = state_;
const bool valid = status == 0u || status == 9u;
if (status == EJOC_FRAME_STATUS_NO_METADATA && pre_state != 0u) {
state_ = 3;
return pre_state;
}
expected_seq_ = next_seq(expected_seq_);
if (valid && seq == 0u && pre_state != 0u) {
// The programme restarted: hard cut and drop the object history.
state_ = 4;
return pre_state;
}
uint32_t state = state_;
if (state == 0u) {
if (valid) {
state = 1u;
expected_seq_ = seq;
}
} else if (state == 1u) {
if (valid) {
if (seq != expected_seq_) {
state = 4u;
}
} else {
state = 2u;
invalid_count_ = 1u;
}
} else if (state == 2u) {
if (valid) {
state = 1u;
expected_seq_ = seq;
} else if (invalid_count_ == 5u) {
state = 3u;
} else {
++invalid_count_;
}
} else if (state == 3u) {
if (valid) {
state = 1u;
expected_seq_ = seq;
} else {
++invalid_count_;
}
} else {
// state 4: the hard cut lasted one frame; a valid frame resyncs and
// an invalid one starts the invalid-frame count.
if (valid) {
state = 1u;
expected_seq_ = seq;
} else {
state = 2u;
invalid_count_ = 1u;
}
}
state_ = state;
if (status == 9u) {
state_ = 4u;
}
last_frame_valid_ = valid;
return pre_state;
}
// Compatibility note for frames without JOC metadata (status 8).
//
// The state machine used to map status 8 to Passthrough unconditionally,
// including in the middle of a stream. That is only meaningful before the
// first valid JOC frame: a plain E-AC-3 stream (or a stream whose first JOC
// frame comes late) has no object state yet, so the core planes are all
// there is and the delayed core PCM is the right output. In the middle of
// a JOC stream a frame without metadata is a damaged frame, not "no
// objects": the Passthrough output replaces the object render with the core
// planes, and the object synthesis restarts from silence on the next frame.
// Every such frame therefore produced a step at the frame boundary and a
// second one when the metadata came back; encoders that are not careful
// with the JOC EMDF container emit exactly those frames.
//
// After the change status 8 follows the state machine like the other
// invalid statuses: state 0 (no valid frame rendered yet) stays Passthrough,
// and state 3 (mid-stream) selects Hold, which reuses the previous object
// matrices and keeps the bed and object rendering continuous.
//
// This is a compatibility choice, not a claim about the normative reading
// of the specification: a frame without metadata can be argued to be the
// Passthrough case. It exists so that non-standard streams stay click-free;
// if the reference behaviour is preferred, re-add the unconditional
// Passthrough branch here.
FrameMode select_mode(const uint32_t status) const noexcept {
if (status == EJOC_FRAME_STATUS_NO_METADATA) {
// See the note above: only a stream that has not rendered a valid
// frame yet has nothing to hold.
return state_ == 0u ? FrameMode::Passthrough : FrameMode::Hold;
}
if (state_ == 4u) {
return FrameMode::HardCut;
}
if (state_ == 2u || state_ == 3u) {
return FrameMode::Hold;
}
if (state_ == 1u && status == 0u) {
return FrameMode::Normal;
}
return FrameMode::Passthrough;
}
// JOC input order 5/7 channels (without LFE) -> 8-plane core order
// L,R,C,LFE,Ls,Rs,(Lrs,Rrs). Used by the passthrough path and its history.
void build_core8(const float* bed_planar, const float* lfe,
const uint32_t n_channels) noexcept {
std::memset(core8_, 0, sizeof(core8_));
for (uint32_t channel = 0; channel < 3u && channel < n_channels; ++channel) {
for (int sample = 0; sample < EJOC_FRAME_SAMPLES; ++sample) {
core8_[channel][sample] =
static_cast<double>(bed_planar[channel * EJOC_FRAME_SAMPLES + sample]);
}
}
if (lfe != nullptr) {
for (int sample = 0; sample < EJOC_FRAME_SAMPLES; ++sample) {
core8_[EJOC_LFE_SLOT][sample] = static_cast<double>(lfe[sample]);
}
}
const uint32_t rest = n_channels > 3u ? n_channels - 3u : 0u;
for (uint32_t index = 0; index < rest; ++index) {
const uint32_t channel = 3u + index;
for (int sample = 0; sample < EJOC_FRAME_SAMPLES; ++sample) {
core8_[4u + index][sample] =
static_cast<double>(bed_planar[channel * EJOC_FRAME_SAMPLES + sample]);
}
}
}
// Passthrough output: slots 0..7 take the previous frame's 8 core planes
// delayed by 1217 samples plus this frame's leading 319 samples; slots 8..15
// stay zero.
void write_passthrough(float* output16, const float output_scale) const noexcept {
for (int channel = 0; channel < EJOC_CORE_OUT_CHANNELS; ++channel) {
float* destination = output16 + channel * EJOC_FRAME_SAMPLES;
for (int sample = 0; sample < kLfeDelay; ++sample) {
destination[sample] = static_cast<float>(
core_history_[channel][EJOC_FRAME_SAMPLES - kLfeDelay + sample]) *
output_scale;
}
for (int sample = kLfeDelay; sample < EJOC_FRAME_SAMPLES; ++sample) {
destination[sample] =
static_cast<float>(core8_[channel][sample - kLfeDelay]) * output_scale;
}
}
}
// Normal rendering: interpolate the per-object matrix from its previous
// frame-end value (or hard cut when there is none) and publish objects that
// disappeared as an all-zero matrix until they come back.
void matrix_object_frame(const int object) noexcept {
std::memset(z_[object], 0, sizeof(z_[object]));
const int n_channels = static_cast<int>(core_channels_);
const bool present = (job_object_mask_ & (1u << object)) != 0u;
if (!present) {
if (prev_present_[object]) {
for (int channel = 0; channel < n_channels; ++channel) {
std::memset(prev_matrix_[object][channel], 0,
sizeof(prev_matrix_[object][channel]));
}
prev_present_[object] = true;
}
return;
}
const int bands = job_n_bands_[object];
const int points = job_n_dpoints_[object];
const int slope = job_slope_idx_[object];
const uint8_t* pb_map = parameter_band_map(bands);
const bool has_previous = prev_present_[object];
for (int channel = 0; channel < n_channels; ++channel) {
for (int subband = 0; subband < EJOC_SUBBANDS; ++subband) {
const int parameter_band = pb_map[subband];
const double target0 = job_dq_[dq_index(object, 0, channel, parameter_band)];
const double target1 = points == 2
? job_dq_[dq_index(object, 1, channel, parameter_band)]
: target0;
const double previous =
has_previous ? prev_matrix_[object][channel][subband] : 0.0;
double last = target0;
for (int timeslot = 0; timeslot < EJOC_TIMESLOTS; ++timeslot) {
double coefficient = 0.0;
if (slope == 0) {
if (!has_previous) {
if (points == 1 || timeslot < EJOC_TIMESLOTS / 2) {
// Hard cut: no fade-in from zero. With two data
// points the second half still interpolates.
coefficient = target0;
} else {
const double alpha =
static_cast<double>(timeslot - (EJOC_TIMESLOTS / 2 - 1)) /
static_cast<double>(EJOC_TIMESLOTS / 2);
coefficient = target0 * (1.0 - alpha) + target1 * alpha;
}
} else if (points == 1) {
const double alpha =
static_cast<double>(timeslot + 1) /
static_cast<double>(EJOC_TIMESLOTS);
coefficient = previous * (1.0 - alpha) + target0 * alpha;
} else if (timeslot < EJOC_TIMESLOTS / 2) {
const double alpha = static_cast<double>(timeslot + 1) /
(EJOC_TIMESLOTS / 2);
coefficient = previous * (1.0 - alpha) + target0 * alpha;
} else {
const double alpha =
static_cast<double>(timeslot - (EJOC_TIMESLOTS / 2 - 1)) /
static_cast<double>(EJOC_TIMESLOTS / 2);
coefficient = target0 * (1.0 - alpha) + target1 * alpha;
}
} else {
// Step mode switches targets at the raw offset slots.
const double base = has_previous ? previous : target0;
coefficient = timeslot < job_offset_ts_[object * EJOC_MAX_DPOINTS]
? base
: target0;
if (points == 2 &&
timeslot >= job_offset_ts_[object * EJOC_MAX_DPOINTS + 1]) {
coefficient = target1;
}
}
z_[object][subband][timeslot].re +=
x_[channel][subband][timeslot].re * coefficient;
z_[object][subband][timeslot].im +=
x_[channel][subband][timeslot].im * coefficient;
last = coefficient;
}
prev_matrix_[object][channel][subband] = last;
}
}
prev_present_[object] = true;
}
// Hold rendering: all 24 slots reuse the previous frame-end matrix and the
// previous state is not updated.
void matrix_object_hold(const int object) noexcept {
std::memset(z_[object], 0, sizeof(z_[object]));
const int n_channels = static_cast<int>(core_channels_);
for (int channel = 0; channel < n_channels; ++channel) {
for (int subband = 0; subband < EJOC_SUBBANDS; ++subband) {
const double previous = prev_matrix_[object][channel][subband];
for (int timeslot = 0; timeslot < EJOC_TIMESLOTS; ++timeslot) {
z_[object][subband][timeslot].re +=
x_[channel][subband][timeslot].re * previous;
z_[object][subband][timeslot].im +=
x_[channel][subband][timeslot].im * previous;
}
}
}
}
void process_one_object_frame(const int object) noexcept {
if (frame_mode_ == FrameMode::Normal) {
matrix_object_frame(object);
} else if (frame_mode_ == FrameMode::Hold) {
matrix_object_hold(object);
} else {
// Hard cut and passthrough publish silence, but every object slot is
// still synthesised so the synthesis state stays aligned.
std::memset(z_[object], 0, sizeof(z_[object]));
}
synthesis_object(object, job_output_scale_, job_output16_);
}
// One E-AC-3 audio frame: validates the description, advances the state
// machine and dispatches one of the four rendering modes.
int render_frame_impl(const ejoc_frame_input& input) noexcept {
error_[0] = '\0';
if (input.struct_size != sizeof(ejoc_frame_input) ||
input.struct_version != EJOC_FRAME_INPUT_VERSION) {
return fail("unsupported ejoc_frame_input struct version");
}
if (input.bed_planar == nullptr || input.output16_planar == nullptr) {
return fail("null bed or output pointer passed to ejoc_renderer_render_frame");
}
const uint32_t n_channels = input.core_channel_count;
if (n_channels != EJOC_CORE_CHANNELS && n_channels != EJOC_MAX_CORE_CHANNELS) {
return fail("core_channel_count must be 5 or 7");
}
if (!std::isfinite(input.clipgain) || !std::isfinite(input.output_scale)) {
return fail("clipgain and output_scale must be finite");
}
const bool has_metadata = input.has_metadata != 0u;
uint32_t status = input.frame_status;
if (!has_metadata) {
if (status != EJOC_FRAME_STATUS_NO_METADATA) {
return fail("a frame without JOC metadata must use frame_status 8");
}
} else if (status != 0u && (status < 2u || status > 7u)) {
return fail("frame_status is not a JOC parse status");
}
if ((input.object_mask & ~((1u << EJOC_MAX_OBJECTS) - 1u)) != 0u) {
return fail("object_mask contains an object index above 14");
}
if (has_metadata && status == 0u) {
for (int object = 0; object < EJOC_MAX_OBJECTS; ++object) {
if ((input.object_mask & (1u << object)) == 0u) {
continue;
}
if (parameter_band_map(input.n_bands[object]) == nullptr) {
return fail("unsupported parameter-band count");
}
if (input.n_dpoints[object] < 1u || input.n_dpoints[object] > 2u) {
return fail("n_dpoints must be 1 or 2");
}
if (input.slope_idx[object] > 1u) {
return fail("slope_idx must be 0 or 1");
}
if (input.slope_idx[object] == 1u) {
const uint8_t* offsets =
input.offset_ts + object * EJOC_MAX_DPOINTS;
for (uint32_t point = 0; point < input.n_dpoints[object]; ++point) {
if (offsets[point] >= EJOC_TIMESLOTS) {
return fail("offset_ts leaves the 0..23 range");
}
if (point != 0u && offsets[point] <= offsets[point - 1u]) {
return fail("offset_ts is not strictly increasing");
}
}
}
}
}
if (n_channels_prev_ >= 0 && n_channels != static_cast<uint32_t>(n_channels_prev_)) {
clear_unused_channels(n_channels);
}
// The parse status decides whether the frame's clipgain is usable; a
// declared-channel-count change (status 9) is only the renderer's own
// dispatch tag, so the new gain still applies to that frame.
const uint32_t parse_status = status;
// A declared core-channel-count change is the renderer's status 9: hard
// cut with the LFE ring cleared, while the clipgain ramp state is kept.
if (has_metadata && status == 0u && input.declared_core_channels != 0u &&
n_channels_prev_ >= 0 &&
input.declared_core_channels != static_cast<uint32_t>(n_channels_prev_)) {
status = 9u;
}
advance_state(status, input.seq);
maybe_clear_lfe_ring(status);
const FrameMode mode = select_mode(status);
if (input.phase_shift_valid != 0u) {
phase_shift_enabled_ = input.phase_shift != 0u;
}
const bool valid_metadata =
has_metadata && parse_status == 0u && input.declared_core_channels != 0u;
double clipgain;
float phase_new;
if ((mode == FrameMode::Normal || mode == FrameMode::HardCut) && valid_metadata) {
clipgain = input.clipgain;
phase_new = static_cast<float>(0.0625 * clipgain);
} else {
// Held frames reuse the current clipgain; they do not retune it.
clipgain = held_clipgain();
phase_new = held_analysis_scalar();
}
core_channels_ = n_channels;
std::memset(input.output16_planar, 0,
sizeof(float) * EJOC_OUTPUT_CHANNELS * EJOC_FRAME_SAMPLES);
build_core8(input.bed_planar, input.lfe, n_channels);
analysis(input.bed_planar, phase_new);
job_kind_ = JobKind::FrameObjects;
frame_mode_ = mode;
job_object_mask_ = mode == FrameMode::Normal ? input.object_mask : 0u;
job_n_bands_ = input.n_bands;
job_n_dpoints_ = input.n_dpoints;
job_slope_idx_ = input.slope_idx;
job_offset_ts_ = input.offset_ts;
job_dq_ = input.dq;
job_output_scale_ = input.output_scale;
job_output16_ = input.output16_planar;
job_count_ = EJOC_MAX_OBJECTS;
for (int object = 0; object < EJOC_MAX_OBJECTS; ++object) {
job_objects_[object] = object;
}
dispatch_jobs();
decode_lfe(input.lfe, clipgain, input.output16_planar, input.output_scale);
if (mode == FrameMode::HardCut) {
// All matrices are zero this frame; the presence markers stay set so
// the next valid frame fades in from zero.
std::memset(input.output16_planar, 0,
sizeof(float) * EJOC_OUTPUT_CHANNELS * EJOC_FRAME_SAMPLES);
for (int object = 0; object < EJOC_MAX_OBJECTS; ++object) {
prev_present_[object] = true;
for (int channel = 0; channel < EJOC_MAX_CORE_CHANNELS; ++channel) {
std::memset(prev_matrix_[object][channel], 0,
sizeof(prev_matrix_[object][channel]));
}
}
} else if (mode == FrameMode::Passthrough) {
write_passthrough(input.output16_planar, input.output_scale);
}
// The 8-plane history is updated on every frame so a later passthrough
// frame is continuous with the last core PCM.
std::memcpy(core_history_, core8_, sizeof(core_history_));
n_channels_prev_ = static_cast<int>(n_channels);
return 0;
}
enum class JobKind : uint8_t { Analysis, Objects, FrameObjects };
std::vector<std::thread> workers_;
std::unique_ptr<std::barrier<>> work_barrier_;
@@ -630,7 +1149,7 @@ private:
int job_objects_[EJOC_MAX_OBJECTS]{};
int job_count_ = 0;
JobKind job_kind_ = JobKind::Objects;
const float* job_bed5_ = nullptr;
const float* job_bed_ = nullptr;
float job_phase_old_ = 0.0625f;
float job_phase_new_ = 0.0625f;
const uint8_t* job_n_bands_ = nullptr;
@@ -638,23 +1157,44 @@ private:
const uint8_t* job_slope_idx_ = nullptr;
const uint8_t* job_offset_ts_ = nullptr;
const double* job_dq_ = nullptr;
double job_clipgain_ = 1.0;
float job_output_scale_ = 1.0f;
float* job_output16_ = nullptr;
uint32_t job_object_mask_ = 0;
FrameMode frame_mode_ = FrameMode::Normal;
alignas(64) double analysis_fifo_[5][9][64];
alignas(64) float analysis_delay_[3][10][64];
float analysis_phase_;
uint32_t core_channels_ = EJOC_CORE_CHANNELS;
alignas(64) double analysis_fifo_[EJOC_MAX_CORE_CHANNELS][9][64];
// Delay lanes: 0..2 hold L/R/C, 3..4 hold the extra pair of a 7-channel frame.
alignas(64) float analysis_delay_[5][10][64];
float analysis_phase_ = -0.5f;
alignas(64) Complex surround_delay_[2][10][64];
alignas(64) Complex surround_history_[2][20];
// band-0 的 21-tap DC 补偿开关;仅 downmix 配置 3/4 由调用方置位。
bool dc_filter_enabled_ = true;
// sigma(k) switch; the caller sets it for downmix configurations 3 and 4.
bool phase_shift_enabled_ = true;
alignas(64) double lfe_delay_[kLfeDelay];
alignas(64) double matrix_previous_[15][5][64];
// LFE gain ramp start; cleared by reset() and cleared/unset only there, so a
// held frame keeps the last applied gain.
double lfe_clipgain_ = 0.0;
bool has_lfe_clipgain_ = false;
alignas(64) double matrix_previous_[15][EJOC_MAX_CORE_CHANNELS][64];
alignas(64) double synthesis_state_[15][640];
alignas(64) Complex x_[5][64][24];
alignas(64) Complex x_[EJOC_MAX_CORE_CHANNELS][64][24];
alignas(64) Complex z_[15][64][24];
// Frame-level state: the seq state machine and the per-object interpolation
// previous matrix (frame-end timeslot of the last published matrix).
uint32_t state_ = 0;
uint32_t expected_seq_ = 0;
uint32_t invalid_count_ = 0;
bool last_frame_valid_ = false;
int n_channels_prev_ = -1;
alignas(64) double prev_matrix_[EJOC_MAX_OBJECTS][EJOC_MAX_CORE_CHANNELS][64];
bool prev_present_[EJOC_MAX_OBJECTS];
// Passthrough history: the 8 core planes of the previous frame and of this
// frame, in the order L,R,C,LFE,Ls,Rs,(Lrs,Rrs).
alignas(64) double core_history_[EJOC_CORE_OUT_CHANNELS][EJOC_FRAME_SAMPLES];
alignas(64) double core8_[EJOC_CORE_OUT_CHANNELS][EJOC_FRAME_SAMPLES];
uint8_t bit_reverse_[64];
Complex fft_twiddle_[32];
double rotation_sin_[64];
@@ -672,13 +1212,13 @@ uint32_t EJOC_CALL ejoc_abi_version(void) {
const char* EJOC_CALL ejoc_build_info(void) {
#if defined(_MSC_VER)
return "eac3joc-core abi=1 compiler=MSVC fft=fixed64 speaker=double binaural=double crt=static-by-build";
return "eac3joc-core abi=4 compiler=MSVC fft=fixed64 speaker=double binaural=double crt=static-by-build";
#elif defined(__clang__)
return "eac3joc-core abi=1 compiler=Clang fft=fixed64 speaker=double binaural=double";
return "eac3joc-core abi=4 compiler=Clang fft=fixed64 speaker=double binaural=double";
#elif defined(__GNUC__)
return "eac3joc-core abi=1 compiler=GCC fft=fixed64 speaker=double binaural=double";
return "eac3joc-core abi=4 compiler=GCC fft=fixed64 speaker=double binaural=double";
#else
return "eac3joc-core abi=1 compiler=unknown fft=fixed64 speaker=double binaural=double";
return "eac3joc-core abi=4 compiler=unknown fft=fixed64 speaker=double binaural=double";
#endif
}
@@ -704,14 +1244,6 @@ int EJOC_CALL ejoc_renderer_set_threads(ejoc_renderer_handle handle, uint32_t to
return static_cast<ejoc::Renderer*>(handle)->set_threads(total_threads);
}
int EJOC_CALL ejoc_renderer_set_dc_filter(ejoc_renderer_handle handle, uint32_t enabled) {
if (!handle) {
return -1;
}
static_cast<ejoc::Renderer*>(handle)->set_dc_filter(enabled != 0);
return 0;
}
uint32_t EJOC_CALL ejoc_renderer_thread_count(ejoc_renderer_handle handle) {
if (!handle) {
return 0;
@@ -728,8 +1260,10 @@ const char* EJOC_CALL ejoc_renderer_last_error(ejoc_renderer_handle handle) {
int EJOC_CALL ejoc_renderer_process(
ejoc_renderer_handle handle,
const float* bed5_planar,
const float* bed_planar,
const float* lfe,
const uint32_t core_channel_count,
const uint32_t phase_shift,
const uint32_t object_mask,
const uint8_t* n_bands,
const uint8_t* n_dpoints,
@@ -744,8 +1278,19 @@ int EJOC_CALL ejoc_renderer_process(
return -1;
}
return static_cast<ejoc::Renderer*>(handle)->process(
bed5_planar, lfe, object_mask, n_bands, n_dpoints, slope_idx,
offset_ts, dq, clipgain, phase_new, output_scale, output16_planar);
bed_planar, lfe, core_channel_count, phase_shift, object_mask, n_bands, n_dpoints,
slope_idx, offset_ts, dq, clipgain, phase_new, output_scale, output16_planar);
}
int EJOC_CALL ejoc_renderer_render_frame(ejoc_renderer_handle handle,
const ejoc_frame_input* input) {
if (!handle) {
return -1;
}
if (!input) {
return -1;
}
return static_cast<ejoc::Renderer*>(handle)->render_frame(*input);
}
} // extern "C"
+43 -21
View File
@@ -6,21 +6,23 @@
namespace joc::joc {
Status rebuild_objects16(ejoc_renderer_handle handle, const joc_frame_params& params,
const float* bed5_planar, const float* lfe, float gain,
const float* bed_planar, const float* lfe,
std::uint32_t core_channel_count, bool has_metadata, float gain,
std::vector<float>* out16, std::string* error) {
if (handle == nullptr || bed5_planar == nullptr || out16 == nullptr) {
if (handle == nullptr || bed_planar == nullptr || out16 == nullptr) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kDsp, "null argument");
}
if (params.n_channels != JOC_CORE_CHANNELS) {
if (core_channel_count != JOC_CORE_CHANNELS &&
core_channel_count != JOC_MAX_CORE_CHANNELS) {
if (error != nullptr) {
*error = "the reused JOC kernel requires 5 core channels, frame declares " +
std::to_string(static_cast<unsigned>(params.n_channels));
*error = "the reused JOC kernel requires 5 or 7 core channels, the frame has " +
std::to_string(core_channel_count);
}
return Status::fail(JOC_ERR_JOC_UNSUPPORTED_VARIANT, stage::kDsp, *error);
}
std::vector<double> dq(static_cast<std::size_t>(JOC_MAX_OBJECTS) * JOC_MAX_DPOINTS *
JOC_CORE_CHANNELS * JOC_MAX_PARAMETER_BANDS,
JOC_MAX_CORE_CHANNELS * JOC_MAX_PARAMETER_BANDS,
0.0);
std::uint8_t n_bands[JOC_MAX_OBJECTS] = {};
std::uint8_t n_dpoints[JOC_MAX_OBJECTS] = {};
@@ -38,10 +40,11 @@ Status rebuild_objects16(ejoc_renderer_handle handle, const joc_frame_params& pa
offset_ts[obj * JOC_MAX_DPOINTS + dp] = object.offset_ts[dp];
}
for (unsigned dp = 0; dp < object.n_dpoints; ++dp) {
for (unsigned ch = 0; ch < JOC_CORE_CHANNELS; ++ch) {
for (unsigned ch = 0; ch < core_channel_count; ++ch) {
for (unsigned pb = 0; pb < object.n_bands; ++pb) {
const std::size_t index =
((static_cast<std::size_t>(obj) * JOC_MAX_DPOINTS + dp) * JOC_CORE_CHANNELS +
((static_cast<std::size_t>(obj) * JOC_MAX_DPOINTS + dp) *
JOC_MAX_CORE_CHANNELS +
ch) *
JOC_MAX_PARAMETER_BANDS +
pb;
@@ -51,23 +54,42 @@ Status rebuild_objects16(ejoc_renderer_handle handle, const joc_frame_params& pa
}
}
ejoc_frame_input input{};
input.struct_size = sizeof(input);
input.struct_version = EJOC_FRAME_INPUT_VERSION;
input.bed_planar = bed_planar;
input.lfe = lfe;
input.core_channel_count = core_channel_count;
// A frame without metadata has no declared channel count; the renderer's
// status-9 path is gated on has_metadata, so the value is not consulted.
input.declared_core_channels =
has_metadata ? static_cast<std::uint32_t>(params.n_channels) : 0u;
// sigma(k) = (k in {3,4}) gates the Ls/Rs -j rotation and the band-0 21-tap
// DC compensation together; other configurations keep the common processing.
// An unsupported downmix configuration (status 2) has no usable switch, so
// the renderer keeps the previous one.
input.phase_shift =
(params.dmx_config_idx == 3u || params.dmx_config_idx == 4u) ? 1u : 0u;
input.phase_shift_valid = params.status == JOC_FRAME_STATUS_UNSUPPORTED_DMX ? 0u : 1u;
input.frame_status = has_metadata ? params.status : EJOC_FRAME_STATUS_NO_METADATA;
input.seq = params.seq_count;
input.has_metadata = has_metadata ? 1u : 0u;
input.object_mask = params.present_mask;
input.n_bands = n_bands;
input.n_dpoints = n_dpoints;
input.slope_idx = slope_idx;
input.offset_ts = offset_ts;
input.dq = dq.data();
input.clipgain = params.clipgain;
input.output_scale = gain;
out16->assign(static_cast<std::size_t>(JOC_OUTPUT_CHANNELS) * JOC_FRAME_SAMPLES, 0.0f);
// band-0 的 21-tap DC 补偿只在 downmix 配置 3/4 下启用,其余配置 band 0
// 走与其他 band 相同的处理。
const bool dc_filter = params.dmx_config_idx == 3 || params.dmx_config_idx == 4;
if (ejoc_renderer_set_dc_filter(handle, dc_filter ? 1u : 0u) != 0) {
if (error != nullptr) {
*error = "ejoc_renderer_set_dc_filter failed";
}
return Status::fail(JOC_ERR_RENDER_FAILED, stage::kDsp, "ejoc_renderer_set_dc_filter failed");
}
const int result = ejoc_renderer_process(
handle, bed5_planar, lfe, params.present_mask, n_bands, n_dpoints, slope_idx, offset_ts,
dq.data(), params.clipgain, 0.0625f, gain, out16->data());
input.output16_planar = out16->data();
const int result = ejoc_renderer_render_frame(handle, &input);
if (result != 0) {
const char* detail = ejoc_renderer_last_error(handle);
const std::string message =
"ejoc_renderer_process failed (" + std::to_string(result) + "): " +
"ejoc_renderer_render_frame failed (" + std::to_string(result) + "): " +
(detail != nullptr ? detail : "unknown");
if (error != nullptr) {
*error = message;
+14 -2
View File
@@ -1,6 +1,7 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
@@ -10,9 +11,20 @@
namespace joc::joc {
// [16][1536] planar float32. The kernel requires exactly 5 core channels.
// Rebuilds the 16-channel object frame ([16][1536] planar float32) for one
// audio frame through the renderer's frame-level state machine. bed_planar is
// [core_channel_count][1536] in JOC lane order (L,R,C,Ls,Rs,(extra pair)), where
// core_channel_count is the actual bed lane count (5 or 7) and lfe is the
// separate core LFE plane (NULL = zeros; the LFE ring still advances).
//
// has_metadata is false for an audio frame without a JOC EMDF container: such a
// frame always passes the 8 core planes through to output slots 0..7. For a
// frame with metadata, params.status selects normal rendering or the invalid
// frame path (hold / hard cut), and params.seq_count drives the state machine.
// gain is the user output gain (not joc_clipgain).
Status rebuild_objects16(ejoc_renderer_handle handle, const joc_frame_params& params,
const float* bed5_planar, const float* lfe, float gain,
const float* bed_planar, const float* lfe,
std::uint32_t core_channel_count, bool has_metadata, float gain,
std::vector<float>* out16, std::string* error);
} // namespace joc::joc
+8 -8
View File
@@ -338,7 +338,7 @@ inline constexpr uint8_t kPbMap1[64] = {
};
inline constexpr uint8_t kPbMap3[64] = {
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
@@ -346,8 +346,8 @@ inline constexpr uint8_t kPbMap3[64] = {
inline constexpr uint8_t kPbMap5[64] = {
0, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
};
@@ -359,8 +359,8 @@ inline constexpr uint8_t kPbMap7[64] = {
};
inline constexpr uint8_t kPbMap9[64] = {
0, 1, 2, 3, 3, 3, 4, 5, 5, 6, 6, 6, 7, 7, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
0, 1, 2, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7,
7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
};
@@ -373,9 +373,9 @@ inline constexpr uint8_t kPbMap12[64] = {
};
inline constexpr uint8_t kPbMap15[64] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10, 10, 11, 11, 11,
12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10, 10, 10, 11, 11,
11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
};
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+101
View File
@@ -0,0 +1,101 @@
// Port of src/oamd_math.py: float32 equations for the metadata application path.
//
// The routines implement the fixed float32 equations for the size tables, ISF
// basis assembly, bed channel routing and the position-dependent compensation.
// The size tables are generated from the region geometry with grouped equal-power
// panning, an S448 weight and a power sum; every operation is evaluated in
// float32 in a fixed order so the coefficients are reproducible.
//
// The caller passes the parameter mappings from oamd_params; this module does
// not read files itself.
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <vector>
#include "oamd/oamd_params.h"
#include "speaker/speaker_layout_lookup.h"
#include "speaker/speaker_layouts.h"
namespace joc::oamd {
// The specified 2**x approximation used by the compensation kernels.
float exp2_approx(float value);
// The specified x**power approximation; power is a float32.
float pow_approx(float value, float power);
// Stable float32 normalisation with the tiny-norm floor.
std::vector<float> norm(const std::vector<float>& vector);
// One boundary weight of the size kernel.
float boundary(int axis, int edge, float position, float t);
// Maps a scalar size in [0, 1] to t on the size curve.
float size_curve_value(double size);
// Size kernel response in region-speaker order (the region point order).
std::vector<float> size_kernel(const ::ejoc::speaker_tables::RegionGeometry& region,
const float position[3], float t, bool height);
// Size-kernel target vector in layout channel order.
std::vector<float> size_targets(const MetadataParams& meta,
const ::ejoc::speaker_tables::LayoutGeometry& layout,
int region_index, const double position[3],
double size, bool height);
// One assembled ISF basis matrix (row_count x layout output_count, row major).
struct IsfBasis {
int rows = 0;
int columns = 0;
std::vector<float> values;
float at(int row, int column) const {
return values[static_cast<std::size_t>(row) * static_cast<std::size_t>(columns) +
static_cast<std::size_t>(column)];
}
};
// Assembles one ISF basis matrix from the compressed base tables.
IsfBasis assemble_isf(const MetadataParams& meta, const char* layout_key, int isf_idx);
// Returns the per-basis ISF compensation gain.
float isf_compensation(const MetadataParams& meta, const char* layout_key, int isf_idx,
int row, bool disabled);
// Per-label bed redistribution weight, in the reference-position index space
// used by the layout descriptors.
float bed_weight(int label, std::uint32_t mask, int target_label);
// The five height-candidate flags for one input bed label.
std::array<int, 5> bed_candidates(int label, std::uint32_t mask,
const std::vector<int>& output_labels);
// Route and weights for one input bed label. route == -1 means the returned
// weights are the target; otherwise route is the reference position used to
// synthesise a point source.
struct BedDistribution {
int route = -1;
std::vector<float> weights;
};
// Derives the bed routing of one input bed label from the target layout.
BedDistribution bed_distribution(const ::joc::speaker::LayoutInfo& layout, int label,
std::uint32_t mask, bool distribute);
// Returns the Q15 reference position used by the bed fallback path.
void bed_reference_position(int index, int q15[3]);
// Returns the bed path compensation gain for one input bed label. ``mode`` is
// the trim mode (0 automatic, 1 disabled, 2 explicit) and ``levels`` holds the
// surround, height and centre levels in dB.
float bed_compensation(const ::joc::speaker::LayoutInfo& layout, int label, int mode,
bool bypass, const double levels[3]);
// Automatic attenuation of a target layout in dB.
float bed_attenuation_db(const ::joc::speaker::LayoutInfo& layout);
} // namespace joc::oamd
+108
View File
@@ -0,0 +1,108 @@
#include "oamd/oamd_params.h"
#include <cstddef>
#include <utility>
#include <vector>
#include "oamd/isf_tables.h"
namespace joc::oamd {
namespace {
namespace tables = isf_tables;
// Builds the renderer-facing view from the checked-in table header. There is no
// file I/O and no runtime parsing: the numbers are compiled in as static data.
MetadataParams build_params() {
MetadataParams params;
params.configs.reserve(tables::kConfigCount);
for (const tables::Config& source : tables::kConfigs) {
IsfConfig config;
for (std::size_t index = 0; index < config.counts.size(); ++index) {
config.counts[index] = source.counts[index];
}
const std::size_t rows = static_cast<std::size_t>(config.row_count());
config.primary_row_map.assign(source.primary_row_map, source.primary_row_map + rows);
config.secondary_row_map.assign(source.secondary_row_map,
source.secondary_row_map + rows);
const std::size_t coefficients = rows * static_cast<std::size_t>(tables::kMatrixColumns);
config.matrix.assign(source.matrix, source.matrix + coefficients);
params.configs.push_back(std::move(config));
}
params.layouts.reserve(tables::kLayoutCount);
for (const tables::Layout& source : tables::kLayouts) {
IsfLayout layout;
layout.output_count = source.output_count;
for (std::size_t index = 0; index < layout.selectors.size(); ++index) {
layout.selectors[index] = source.selectors[index];
}
layout.compensation_value = source.compensation_value;
layout.output_ids.assign(source.output_ids,
source.output_ids + tables::kOutputIdSlots);
params.layouts.emplace(source.key, std::move(layout));
}
const auto copy_groups = [](const tables::GroupRecord* records, int count,
std::vector<IsfGroupRecord>* out) {
out->reserve(static_cast<std::size_t>(count));
for (int index = 0; index < count; ++index) {
out->push_back(IsfGroupRecord{records[index].selector, records[index].begin,
records[index].end});
}
};
copy_groups(tables::kLayoutGroups.floor_a, tables::kLayoutGroups.floor_a_count,
&params.layout_groups.floor_a);
copy_groups(tables::kLayoutGroups.floor_b, tables::kLayoutGroups.floor_b_count,
&params.layout_groups.floor_b);
copy_groups(tables::kLayoutGroups.height, tables::kLayoutGroups.height_count,
&params.layout_groups.height);
copy_groups(tables::kLayoutGroups.additional, tables::kLayoutGroups.additional_count,
&params.layout_groups.additional);
params.paired_columns.assign(tables::kPairedColumns,
tables::kPairedColumns + tables::kPairedColumnCount);
return params;
}
const MetadataParams& loaded_params() {
static const MetadataParams params = build_params();
return params;
}
} // namespace
const std::vector<IsfGroupRecord>* IsfLayoutGroups::find(const char* name) const {
if (name == nullptr) {
return nullptr;
}
const std::string key(name);
if (key == "floor_a") {
return &floor_a;
}
if (key == "floor_b") {
return &floor_b;
}
if (key == "height") {
return &height;
}
if (key == "additional") {
return &additional;
}
return nullptr;
}
const IsfLayout* MetadataParams::layout(const char* key) const {
if (key == nullptr) {
return nullptr;
}
const auto found = layouts.find(key);
return found != layouts.end() ? &found->second : nullptr;
}
const MetadataParams* metadata_params() { return &loaded_params(); }
const char* metadata_params_error() { return ""; }
} // namespace joc::oamd
+82
View File
@@ -0,0 +1,82 @@
// Port of src/oamd_params.py: the static ISF lookup data of the metadata path.
//
// The numbers are compiled in as the generated header `oamd/isf_tables.h`:
// ISF base coefficients and layout descriptors, applied as lookup tables.
// The remaining values (gain, size, priority, position, delta and refinement
// tables) are computed in code; the size tables are generated from the region
// geometry at runtime, and bed routing is derived from the speaker layouts.
// The arrays are adapted once per process into the structures below; nothing
// reads a data file.
#pragma once
#include <array>
#include <cstdint>
#include <string>
#include <unordered_map>
#include <vector>
#include "foundation/status.h"
namespace joc::oamd {
// One ISF configuration: the compressed basis matrix and the two row maps
// that expand it to the layout output channels.
struct IsfConfig {
// mid, upper, lower, zenith, row_count (the reference's counts tuple).
std::array<int, 5> counts{};
std::vector<int> primary_row_map;
std::vector<int> secondary_row_map;
// row_count * 73 float32 coefficients, row major.
std::vector<float> matrix;
int row_count() const { return counts[4]; }
};
// One layout descriptor: how many output channels the basis has,
// the layout-group selectors and the automatic compensation value.
struct IsfLayout {
int output_count = 0;
std::array<int, 4> selectors{}; // floor_a, floor_b, height, additional
double compensation_value = 0.0;
// ISF channel id of each matrix output column, padded with zeros to 37.
std::vector<std::uint8_t> output_ids;
};
// One record of a layout group: selector id and the half-open column range
// [begin, end).
struct IsfGroupRecord {
int selector = 0;
int begin = 0;
int end = 0;
};
// The four layout groups of the ISF tables.
struct IsfLayoutGroups {
std::vector<IsfGroupRecord> floor_a;
std::vector<IsfGroupRecord> floor_b;
std::vector<IsfGroupRecord> height;
std::vector<IsfGroupRecord> additional;
const std::vector<IsfGroupRecord>* find(const char* name) const;
};
// The ISF lookup data in the shape the metadata renderer consumes.
struct MetadataParams {
std::vector<IsfConfig> configs;
std::unordered_map<std::string, IsfLayout> layouts;
IsfLayoutGroups layout_groups;
// One flag per matrix column: whether the column also contributes through
// the secondary row map.
std::vector<bool> paired_columns;
const IsfLayout* layout(const char* key) const;
};
// Returns the process-wide tables. They are compiled in, so the pointer is
// never null; ``metadata_params_error`` is kept for callers that log a load
// failure and always returns an empty string.
const MetadataParams* metadata_params();
const char* metadata_params_error();
} // namespace joc::oamd
File diff suppressed because it is too large. Load diff
+218 -4
View File
@@ -9,6 +9,34 @@
#include "foundation/status.h"
#include "joc_core.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。
// The enum values are the reference's BED_LABEL_INDEX - 1.
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,
};
} // namespace joc::joc
namespace joc::oamd {
inline constexpr int kMaxSlots = 16;
@@ -17,6 +45,132 @@ inline constexpr int kAxes = 3;
inline constexpr int kNQ12 = 62;
inline constexpr int kNQ3 = 15;
inline constexpr int kQ15Scale = 32768;
// Largest ISF configuration of Table 11b (5.6.0.11). A frame cannot carry more
// objects than this through any of the standard programmes, but the parser does
// not reject a larger count: it only bounds the legacy 16-slot view.
inline constexpr int kMaxObjects = 30;
inline constexpr int kMaxBlocks = 8;
inline constexpr std::uint32_t kTrimElementId = 2;
inline constexpr std::uint32_t kObjectElementId = 1;
inline constexpr std::uint32_t kExtendedElementId = 5;
inline constexpr int kTrimConfigs = 9;
inline constexpr int kBedLabelCount = 17;
// 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] = {};
};
// OAMD object kind: the programme assigns objects to the bed, to an ISF
// configuration, or to the dynamic (positional) set, in that order.
enum class ObjectKind : std::uint8_t {
kBed = 0,
kIsf = 1,
kDynamic = 2,
};
// Render state of one object in one block (5.5.9 object_info_block).
struct ObjectRenderState {
bool not_active = false;
std::int32_t gain_q = 0; // integer gain, unity = 4096
std::int32_t priority_q = 0; // Q10 priority, 32767 = default
std::int32_t qx = 0; // Q15 room position, 0..32767
std::int32_t qy = 0; // Q15 room position, 0..32767
std::int32_t qz = 0; // signed Q15 elevation
std::uint8_t zone_idx = 0;
bool enable_elevation = true;
std::uint8_t size_mode = 0; // 0 none, 1 isotropic, 2 per-axis
std::uint16_t size_q[3] = {0, 0, 0}; // Q15 size per axis
bool snap = false;
std::uint16_t divergence_q = 0; // Q15 divergence width
};
struct ObjectBlockState {
ObjectRenderState render;
};
// One object of the frame: its kind and the state of every block.
struct ObjectElementState {
ObjectKind kind = ObjectKind::kDynamic;
std::vector<ObjectBlockState> blocks;
};
// Timing shared by every object of one block. ``block_offset_samples`` already
// includes the element's sample_offset, like the reference block dictionary.
struct BlockTiming {
std::uint32_t block_offset_samples = 0;
std::uint32_t ramp_duration_samples = 0;
};
// Program assignment (5.5.3) as consumed by the speaker renderer.
struct ProgramState {
bool dynamic_object_only = false;
bool lfe_present = false;
bool b_bed_chan_distribute = false;
// program_assignment() content_description flags.
bool content_reserved = false;
bool content_bed = false;
bool content_isf = false;
bool content_dynamic = false;
std::uint32_t num_bed_objects = 0;
std::uint32_t num_isf_objects = 0;
std::int32_t num_dynamic_objects = -1; // -1 when the frame declares none
std::uint32_t bed_mask = 0; // 17-bit non-standard bed mask
std::int32_t isf_idx = -1; // -1 when the frame declares none
// Declared bed labels in channel order, including LFE/LFE2. Index i is the
// label of object i for i < num_bed_objects.
std::vector<::joc::joc::BedChannel> bed_labels;
};
// One element whose parsed content ended past its declared size. The reference
// keeps parsing such elements and only records the difference.
struct ElementSizeMismatch {
std::uint32_t element_ordinal = 0;
std::uint32_t element_id = 0;
std::uint32_t declared_size_bytes = 0;
std::uint32_t declared_end_bit = 0;
std::uint32_t parsed_end_bit = 0;
};
// Full frame state (frame_state() in the reference): per-object per-block
// render state plus programme assignment, timing and trim.
struct FrameState {
std::uint32_t object_count = 0;
std::uint32_t block_count = 0;
std::uint32_t sample_offset = 0; // object_element sample offset
std::uint32_t ramp_duration_samples = 0; // block 0
std::vector<BlockTiming> blocks;
std::vector<ObjectElementState> objects;
ProgramState program;
bool has_trim = false;
OamdTrim trim;
std::vector<ElementSizeMismatch> size_mismatch;
};
// (the reference's None), i.e. hold the previous position.
struct SlotUpdate {
@@ -35,6 +189,21 @@ struct OamdUpdate {
std::uint32_t num_bed_objects = 0;
std::uint32_t num_isf_objects = 0;
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;
// Full per-object per-block state of this payload. ``has_frame_state`` is
// true whenever the parser produced it; the speaker metadata path and the
// binaural position timeline consume it, while the legacy slot fields above
// stay authoritative for ADM export and the point-renderer path.
bool has_frame_state = false;
FrameState frame_state;
};
class OamdState {
@@ -62,6 +231,23 @@ public:
std::int16_t q(int slot, int axis) const { return q_[slot][axis]; }
// Resolves one frame-state position block for one object. The legacy
// apply() entry above keeps the reference frame_update() view (16 slots,
// block 0); the binaural position timeline uses this entry so a frame may
// carry more objects and more blocks than that view can express. Callers
// skip inactive and non-dynamic objects themselves, exactly like the
// reference's frame_update() value construction.
void apply_render_state(int object_index, const ObjectRenderState& render) {
if (object_index < 0 || object_index >= kMaxObjects) {
return;
}
q_[object_index][0] = static_cast<std::int16_t>(render.qx);
q_[object_index][1] = static_cast<std::int16_t>(render.qy);
const std::int32_t elevation = render.enable_elevation ? render.qz : 0;
q_[object_index][2] =
static_cast<std::int16_t>(elevation > 0 ? elevation : 0);
}
// Objects 1..15 as q15 triples, the layout the speaker renderer consumes.
void object_positions_q15(std::uint16_t out[kObjects][kAxes]) const {
for (int object = 0; object < kObjects; ++object) {
@@ -72,18 +258,18 @@ public:
}
private:
std::int16_t q_[kMaxSlots][kAxes] = {};
std::int16_t q_[kMaxObjects][kAxes] = {};
};
// q_of(k, n) = min(32767, floor(32768 k / n + 0.5)), the reference's quantiser.
int q_of(int k, int n);
Status parse_id11(const std::uint8_t* payload, std::size_t payload_size, OamdUpdate* out);
struct BedAssignment {
bool lfe_only = false;
bool standard = false;
std::uint32_t mask = 0;
std::uint32_t mask = 0; // 10-bit standard or 17-bit non-standard mask
// Declared channels in channel order; LFE is kept in place.
std::vector<::joc::joc::BedChannel> channels;
};
struct ParseTrace {
@@ -97,7 +283,35 @@ struct ParseTrace {
bool reserved_data_not_present = false;
};
// Legacy single-frame view (frame_update() in the reference): the 16-slot
// position update plus programme and trim. A payload carrying more than 16
// objects or more than one position block is rejected, exactly like the
// reference legacy entry point. The ADM export path keeps this view; the
// speaker and binaural renderers use parse_id11_state().
Status parse_id11(const std::uint8_t* payload, std::size_t payload_size, OamdUpdate* out);
// Full frame_state() view: per-object per-block state, no 16-slot or
// single-block restriction. The legacy fields are filled as well whenever the
// frame fits them, so a caller can parse once and hand the same update to the
// renderers and to the ADM export path where its shape allows it.
Status parse_id11_state(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);
Status parse_id11_verbose(const std::uint8_t* payload, std::size_t payload_size, OamdUpdate* out,
ParseTrace* trace);
// Parses only the OAMD header and program_assignment(), which is all the
// cross-layer bed-mask check (spec section 11.2 item 2) needs.
Status parse_id11_bed_assignments(const std::uint8_t* payload, std::size_t payload_size,
std::vector<BedAssignment>* out);
// 10-bit standard bed mask -> 17-bit non-standard bed mask (5.6.1.1.4).
std::uint32_t standard_bed_mask(std::uint32_t bed_mask);
} // namespace joc::oamd
+7 -6
View File
@@ -7,10 +7,10 @@
#include "simd/cpu_probe.h"
#if defined(_M_X64)
#if defined(_M_X64) || defined(_M_IX86)
#include <immintrin.h>
#include <intrin.h>
#elif defined(__x86_64__)
#elif defined(__x86_64__) || defined(__i386__)
#include <cpuid.h>
#endif
@@ -21,10 +21,11 @@
namespace joc::simd {
namespace {
// ------------------------------------------------------------------- x86-64 --
#if defined(_M_X64) || defined(__x86_64__)
// ---------------------------------------------------------------------- x86 --
// AVX2 is not an x86-64-only ISA, so both pointer sizes are probed.
#if defined(_M_X64) || defined(_M_IX86) || defined(__x86_64__) || defined(__i386__)
#if defined(_M_X64)
#if defined(_M_X64) || defined(_M_IX86)
// CPUID tells us what the silicon can do; XCR0 tells us whether the OS saves the
// state the wider registers need. Both have to agree, or the first AVX
@@ -53,7 +54,7 @@ CpuFeatures probe_x86() noexcept {
return features;
}
#else // GCC/Clang on x86-64
#else // GCC/Clang on x86
// The compiler runtime performs the same CPUID + XGETBV probe (libgcc's cpuinfo
// checks XCR0 before it reports AVX), which keeps this file free of inline
+40 -10
View File
@@ -8,28 +8,58 @@ namespace {
struct FrozenLayout {
const char* name;
const char* compact_name;
std::uint32_t out_ch_config;
std::uint32_t speaker_bitfield;
std::uint32_t surround_channels;
std::uint32_t height_channels;
bool carries_trim;
const char* const* channel_names;
};
const char* const kChannels20[] = {"L", "R"};
const char* const kChannels31[] = {"L", "R", "C", "LFE"};
const char* const kChannels40[] = {"L", "R", "Lrs", "Rrs"};
const char* const kChannels51[] = {"L", "R", "C", "LFE", "Ls", "Rs"};
const char* const kChannels71[] = {"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs"};
const char* const kChannels512[] = {"L", "R", "C", "LFE", "Ls", "Rs", "Ltm", "Rtm"};
const char* const kChannels514[] = {"L", "R", "C", "LFE", "Ls", "Rs", "Ltf", "Rtf",
"Ltr", "Rtr"};
const char* const kChannels712[] = {"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs",
"Ltm", "Rtm"};
const char* const kChannels714[] = {"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs",
"Ltf", "Rtf", "Ltr", "Rtr"};
const char* const kChannels914[] = {"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs",
"Lw", "Rw", "Ltf", "Rtf", "Ltr", "Rtr"};
const char* const kChannels916[] = {"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs",
"Lw", "Rw", "Ltf", "Rtf", "Ltm", "Rtm", "Ltr", "Rtr"};
const char* const kChannels60[] = {"L", "R", "Ls", "Rs", "Lrs", "Rrs"};
constexpr FrozenLayout kLayouts[kLayoutCount] = {
{"2.0", 0, 1},
{"3.1", 3, 7},
{"5.1", 7, 15},
{"7.1", 11, 31},
{"5.1.2", 13, 1039},
{"5.1.4", 14, 2575},
{"7.1.2", 15, 1055},
{"7.1.4", 16, 2591},
{"9.1.4", 19, 2719},
{"9.1.6", 20, 3743},
{"2.0", "20", 0, 1, 0, 0, true, kChannels20},
{"3.1", "31", 3, 7, 0, 0, true, kChannels31},
{"4.0", "40", 0xFF, 9, 2, 0, true, kChannels40},
{"5.1", "51", 7, 15, 2, 0, true, kChannels51},
{"7.1", "71", 11, 31, 4, 0, true, kChannels71},
{"5.1.2", "512", 13, 1039, 2, 2, true, kChannels512},
{"5.1.4", "514", 14, 2575, 2, 4, true, kChannels514},
{"7.1.2", "712", 15, 1055, 4, 2, false, kChannels712},
{"7.1.4", "714", 16, 2591, 4, 4, false, kChannels714},
{"9.1.4", "914", 19, 2719, 4, 4, false, kChannels914},
{"9.1.6", "916", 20, 3743, 4, 6, false, kChannels916},
{"6.0", "60", 0xFF, 25, 4, 0, false, kChannels60},
};
void fill(const FrozenLayout& source, LayoutInfo* out) {
out->name = source.name;
out->compact_name = source.compact_name;
out->out_ch_config = source.out_ch_config;
out->speaker_bitfield = source.speaker_bitfield;
out->channel_count = ejoc_speaker_layout_channel_count(source.speaker_bitfield);
out->channel_names = source.channel_names;
out->surround_channels = source.surround_channels;
out->height_channels = source.height_channels;
out->carries_trim = source.carries_trim;
}
} // namespace
+18 -3
View File
@@ -8,19 +8,34 @@
namespace joc::speaker {
inline constexpr int kLayoutCount = 10;
inline constexpr int kLayoutCount = 12;
struct LayoutInfo {
const char* name = "";
// The reference's compact layout key ("2.0" -> "20", ...), the key of the
// automatic-attenuation and divide-by-default tables.
const char* compact_name = "";
std::uint32_t out_ch_config = 0;
std::uint32_t speaker_bitfield = 0;
std::uint32_t channel_count = 0;
// Standard channel names in output order, ``channel_count`` entries.
const char* const* channel_names = nullptr;
// 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 twelve 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, 6.0).
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_bitfield(std::uint32_t bitfield, LayoutInfo* out);
+98 -2
View File
@@ -39,7 +39,7 @@ struct LayoutGeometry {
std::array<RegionGeometry, 7> regions{};
};
inline constexpr std::array<LayoutGeometry, 10> kLayouts{{
inline constexpr std::array<LayoutGeometry, 12> kLayouts{{
LayoutGeometry{
0x1u, 0, 2,
{{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{
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, 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{
0xFu, 7, 6,
{{0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
@@ -519,7 +567,55 @@ inline constexpr std::array<LayoutGeometry, 10> kLayouts{{
{{AxisGroup{2, {5, 6, 0}}, AxisGroup{}, AxisGroup{}, AxisGroup{}}}
}
}}
}
},
LayoutGeometry{
0x19u, 0xFFu, 6,
{{0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{{
RegionGeometry{
6, 2, 3, 0,
{{SpeakerPoint{{0, 0, 0}, 0}, SpeakerPoint{{32767, 0, 0}, 1}, SpeakerPoint{{0, 16384, 0}, 2}, SpeakerPoint{{32767, 16384, 0}, 3}, SpeakerPoint{{0, 32767, 0}, 4}, SpeakerPoint{{32767, 32767, 0}, 5}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}, SpeakerPoint{}}},
{{AxisGroup{2, {0, 1, 0}}, AxisGroup{2, {2, 3, 0}}, AxisGroup{2, {4, 5, 0}}, AxisGroup{}}},
{{AxisGroup{}, AxisGroup{}, AxisGroup{}, AxisGroup{}}}
},
RegionGeometry{
4, 2, 2, 0,
{{SpeakerPoint{{0, 0, 0}, 0}, SpeakerPoint{{32767, 0, 0}, 1}, SpeakerPoint{{0, 16384, 0}, 2}, SpeakerPoint{{32767, 16384, 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}, 4}, SpeakerPoint{{32767, 32767, 0}, 5}, 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, 2, 1, 0,
{{SpeakerPoint{{0, 32767, 0}, 4}, SpeakerPoint{{32767, 32767, 0}, 5}, 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{
4, 2, 2, 0,
{{SpeakerPoint{{0, 16384, 0}, 2}, SpeakerPoint{{32767, 16384, 0}, 3}, SpeakerPoint{{0, 32767, 0}, 4}, SpeakerPoint{{32767, 32767, 0}, 5}, 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, 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{}}}
}
}}
},
}};
inline constexpr const LayoutGeometry* find_layout(const std::uint32_t speaker_bitfield) noexcept {
+90
View File
@@ -0,0 +1,90 @@
// Port of the metadata application path of src/speaker_renderer.py HEAD.
//
// The metadata path consumes the full per-object per-block OAMD frame state and
// schedules block targets frame by frame: object gain/inactive, zone/elevation,
// snap, divergence, size kernel fusion, priority size budget, ISF basis rows and
// bed channel distribution, with the same float64 gain ramps and block alignment
// as the reference renderer.
#pragma once
#include <cstdint>
#include <memory>
#include <vector>
#include "eac3joc_core.h"
#include "foundation/status.h"
#include "oamd/oamd_parser.h"
#include "speaker/speaker_layout_lookup.h"
#include "speaker/speaker_trim.h"
namespace joc::speaker {
// One metadata target matrix: object_count x layout channel_count in the
// renderer's internal channel order, before the ramp/timing stage.
struct MetadataTargets {
std::uint32_t object_count = 0;
std::uint32_t channel_count = 0;
std::vector<double> values; // object major
double at(std::uint32_t object, std::uint32_t channel) const {
return values[static_cast<std::size_t>(object) * channel_count + channel];
}
};
// Computes the metadata target matrix of one block of a parsed frame without
// touching renderer state: the reference's _init_meta validation plus
// _block_targets. ``trim`` carries the current programme trim (bypass flags),
// ``controls`` the derived per-layout controls, ``size_budget`` the priority
// budget (0 means unlimited, the production value).
Status metadata_block_targets(const LayoutInfo& layout, const oamd::OamdUpdate& update,
std::uint32_t block_index,
const ejoc_speaker_controls& controls,
const oamd::OamdTrim* trim, std::uint32_t size_budget,
MetadataTargets* out);
// Stateful metadata-path renderer. It owns the object target ramps and the
// cross-block pending schedule; the legacy point-renderer state stays in the
// C ABI renderer, which is used for the blocks of a frame that precede the first
// metadata targets (the reference renders those with its legacy block path).
class MetaRenderer {
public:
MetaRenderer();
~MetaRenderer();
MetaRenderer(MetaRenderer&&) noexcept;
MetaRenderer& operator=(MetaRenderer&&) noexcept;
MetaRenderer(const MetaRenderer&) = delete;
MetaRenderer& operator=(const MetaRenderer&) = delete;
// Binds the target layout. Must be called once before process_frame().
Status configure(const LayoutInfo& layout);
// Drops the ramp, schedule and metadata state (the layout stays bound).
Status reset();
bool configured() const;
// True once a metadata frame has been accepted (the reference's _meta_mode).
bool engaged() const;
const char* last_error() const;
Status process_frame(ejoc_speaker_renderer_handle legacy,
const float* objects16_interleaved, std::uint32_t sample_count,
const oamd::OamdUpdate* update, std::uint32_t metadata_offset,
const ejoc_speaker_controls& controls, const oamd::OamdTrim* trim,
std::uint32_t raw_trim_mode, std::uint32_t size_budget,
double* output_interleaved);
// Computes the target matrix of one block of ``update`` into ``out`` using a
// scratch context; unlike metadata_block_targets() this validates through
// the renderer's own state-independent path.
Status block_targets(const oamd::OamdUpdate& update, std::uint32_t block_index,
const ejoc_speaker_controls& controls, const oamd::OamdTrim* trim,
std::uint32_t size_budget, MetadataTargets* out) const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace joc::speaker
File diff suppressed because it is too large. Load diff
+64 -1
View File
@@ -26,6 +26,61 @@ Status step(SpeakerStep* context, const std::vector<float>& objects16_planar,
static_cast<std::size_t>(JOC_FRAME_SAMPLES) * context->layout.channel_count, 0.0);
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;
}
if (update != nullptr && 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->trim = update->trim;
context->has_trim = true;
context->raw_trim_mode = update->trim.global_trim_mode;
}
const bool metadata_frame =
update != nullptr && update->has_frame_state &&
update->frame_state.object_count != 0u;
if (metadata_frame || context->meta_engaged) {
if (!context->meta_configured) {
const Status configured = context->meta.configure(context->layout);
if (!configured.ok()) {
if (error != nullptr) {
*error = configured.message();
}
return configured;
}
context->meta_configured = true;
}
const oamd::OamdTrim* trim = context->has_trim ? &context->trim : nullptr;
const Status processed = context->meta.process_frame(
context->handle, context->interleaved.data(), JOC_FRAME_SAMPLES,
metadata_frame ? update : nullptr, context->metadata_offset,
context->controls, trim, context->raw_trim_mode, 0u,
context->output.data());
if (!processed.ok()) {
if (error != nullptr) {
*error = processed.message();
}
return processed;
}
context->meta_engaged = context->meta.engaged();
return Status::success();
}
std::uint32_t ramp = 0;
if (update != nullptr) {
context->state.apply(*update);
@@ -37,6 +92,14 @@ Status step(SpeakerStep* context, const std::vector<float>& objects16_planar,
std::uint16_t positions[oamd::kObjects][3] = {};
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
// pending ramp would snap - matching the reference exactly.
const std::uint32_t event_count = context->last_had_payload ? 1u : 0u;
@@ -45,7 +108,7 @@ Status step(SpeakerStep* context, const std::vector<float>& objects16_planar,
context->handle, context->interleaved.data(), JOC_FRAME_SAMPLES, event_count,
event_count != 0u ? &offset : nullptr, event_count != 0u ? &ramp : nullptr,
event_count != 0u ? &positions[0][0] : nullptr, nullptr, nullptr, nullptr,
context->output.data());
&context->controls, context->output.data());
if (result != 0) {
const char* message = ejoc_speaker_renderer_last_error(context->handle);
const std::string text =
+20
View File
@@ -9,6 +9,8 @@
#include "foundation/status.h"
#include "oamd/oamd_parser.h"
#include "speaker/speaker_layout_lookup.h"
#include "speaker/speaker_meta.h"
#include "speaker/speaker_trim.h"
namespace joc::speaker {
@@ -23,6 +25,24 @@ struct SpeakerStep {
std::uint32_t last_ramp_duration = 0;
std::uint32_t last_object_count = 0;
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] = {};
// Metadata path: a frame that carries the full per-object block state
// switches the speaker output to the metadata renderer. The programme trim
// element and its raw global mode stay here because the metadata path needs
// the per-object bypass flags and the ISF compensation mode.
MetaRenderer meta;
bool meta_configured = false;
bool meta_engaged = false;
oamd::OamdTrim trim{};
bool has_trim = false;
std::uint32_t raw_trim_mode = 0;
};
Status step(SpeakerStep* context, const std::vector<float>& objects16_planar,
+154
View File
@@ -0,0 +1,154 @@
#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 > 3u) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kRender,
"speaker: invalid warp mode " +
std::to_string(controls.warp_mode));
}
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
+50
View File
@@ -0,0 +1,50 @@
// 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 0
// renders directly, 1 scales the floor Y, and 2/3 render through an expanded
// surround layout before folding; the reserved global trim mode is 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
+436 -81
View File
@@ -6,9 +6,10 @@
#include "adm/adm_metadata.h"
#include "foundation/status.h"
#include "virtual_speaker/virtual_speaker.h"
#include "hrtf/jochrtf.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_core/objects16.h"
@@ -17,9 +18,6 @@ namespace joc::stream {
namespace {
constexpr std::size_t kFrameSamples = JOC_FRAME_SAMPLES;
constexpr std::size_t kBedChannels = 6;
constexpr int kCoreChannels[5] = {0, 1, 2, 4, 5};
constexpr int kLfeChannel = 3;
} // namespace
@@ -37,8 +35,20 @@ Stream::~Stream() {
void Stream::reset_state() {
reader_ = eac3::FrameReader();
metadata_.clear();
pending_frame_ = FrameMetadata();
bed_plan_ = joc::BedPlan();
bed_channels_ = 0;
config_idx_ = -1;
core_channels_ = 0;
bed_plan_failed_ = false;
bed_plan_error_ = Status::success();
bed_input_channels_ = 0;
bed_pending_.clear();
bed_read_offset_ = 0;
objects16_.clear();
pcm_input_.reset();
objects_pending_.clear();
objects_read_offset_ = 0;
output_.clear();
read_offset_ = 0;
info_ = Info();
@@ -51,6 +61,8 @@ void Stream::reset_state() {
speaker_.state.reset();
speaker_.output.clear();
speaker_.last_had_payload = false;
// Back to the initial controls; the next trim element replaces them.
speaker_.controls_ready = false;
}
if (binaural_ready_) {
binaural_.reset();
@@ -67,7 +79,7 @@ Status Stream::create(const Config& config) {
return Status::fail(JOC_ERR_STATE, stage::kRender, "stream already created");
}
config_ = config;
if (config_.input > JOC_STREAM_IN_PCM_OBJECTS16 ||
if (config_.input > JOC_STREAM_IN_PCM_LAYOUT ||
config_.output > JOC_STREAM_OUT_BINAURAL) {
return Status::fail(JOC_ERR_INVALID_CONFIG, stage::kRender, "unknown stream kind");
}
@@ -77,6 +89,20 @@ Status Stream::create(const Config& config) {
"objects16 input with objects16 output would do nothing");
}
gain_ = static_cast<float>(std::pow(10.0, config_.gain_db / 20.0));
if (config_.input == JOC_STREAM_IN_PCM_LAYOUT && !config_.pcm_layout.empty() &&
config_.pcm_layout != "auto") {
const virtual_speaker::Layout* layout =
virtual_speaker::find_layout(config_.pcm_layout);
if (layout == nullptr) {
return Status::fail(JOC_ERR_INVALID_CONFIG, stage::kRender,
"unknown PCM layout: " + config_.pcm_layout);
}
const Status configured =
pcm_input_.configure(config_.pcm_layout, layout->channels, config_.gain_db);
if (!configured.ok()) {
return configured;
}
}
if (config_.input == JOC_STREAM_IN_EAC3) {
rebuilder_ = ejoc_renderer_create();
@@ -118,7 +144,9 @@ Status Stream::create(const Config& config) {
}
render_options.object_delay_samples = config_.object_delay_samples;
render_options.tail_seconds = config_.tail_seconds;
render_options.output_gain = 1.0;
render_options.bank = config_.rosella_filterbank == JOC_ROSELLA_FILTERBANK_CAPTURED
? hrtf::RosellaBankKind::Captured
: hrtf::RosellaBankKind::Public;
if (status.ok()) {
status = rosella_.open(model, render_options);
}
@@ -132,26 +160,7 @@ Status Stream::create(const Config& config) {
hrtf::Field field;
hrtf::Kernels kernels;
Status status = Status::success();
if (!config_.hrtf_sofa_path.empty()) {
// 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);
}
status = hrtf::load_jochrtf(config_.hrtf_path, &field);
if (status.ok()) {
status = config_.kernels_path.empty()
? (kernels = hrtf::builtin_kernels(), Status::success())
@@ -164,7 +173,10 @@ Status Stream::create(const Config& config) {
profile = binaural::Profile::Far;
}
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()) {
return status;
@@ -179,6 +191,91 @@ Status Stream::create(const Config& config) {
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() {
if (pending_frame_.streams.empty()) {
return Status::success();
}
FrameMetadata entry = pending_frame_;
pending_frame_ = FrameMetadata();
if (entry.has_joc) {
apply_bed_positions(entry);
}
if (entry.has_joc) {
std::string error;
joc::CrossLayerNotes notes;
const Status checked = joc::check_cross_layer(
entry.params, entry.has_core ? &entry.core_frame : nullptr, entry.has_core,
entry.has_dependent, entry.has_chanmap, entry.chanmap,
entry.bed_assignments.empty() ? nullptr : &entry.bed_assignments, &error, &notes);
if (!checked.ok()) {
return Status::fail(checked.code(), checked.stage(),
error.empty() ? checked.message() : error);
}
if (notes.chanmap_pair_mismatch) {
++info_.chanmap_pair_mismatch_frames;
}
if (notes.bed_mask_mismatch) {
++info_.bed_mask_mismatch_frames;
}
if (entry.params.objects_clamped != 0u) {
++info_.objects_clamped_frames;
}
if (entry.params.status == JOC_FRAME_STATUS_TRUNCATED) {
++info_.truncated_joc_frames;
}
} else {
// No JOC metadata for this audio frame: the object channels stay silent
// while the kernel state still advances for the frame.
++info_.missing_joc_frames;
joc::make_silent_frame_params(&entry.params);
entry.has_update = false;
}
metadata_.push_back(entry);
return Status::success();
}
Status Stream::push_eac3(const std::uint8_t* data, std::size_t size, std::size_t* consumed) {
if (rebuilder_ == nullptr) {
return Status::fail(JOC_ERR_STATE, stage::kEmdf, "stream is not an E-AC-3 input");
@@ -199,13 +296,65 @@ Status Stream::push_eac3(const std::uint8_t* data, std::size_t size, std::size_t
if (state == eac3::FrameReader::Next::Fail) {
return Status::fail(reader_.error(), stage::kEac3, reader_.error_message());
}
FrameMetadata entry;
// A repeated (codec, strmtyp, substreamid) combination starts the next
// audio frame, so the group that is still open is complete.
bool repeats = false;
for (const eac3::Frame& prior : pending_frame_.streams) {
if (prior.same_stream(frame)) {
repeats = true;
break;
}
}
if (repeats) {
const Status flushed = flush_pending_frame();
if (!flushed.ok()) {
return flushed;
}
}
eac3::Frame header = frame;
header.data = nullptr;
header.size = 0;
header.offset = frame.offset;
pending_frame_.streams.push_back(header);
if (frame.codec == 0u || frame.strmtyp == 0u) {
pending_frame_.core_frame = header;
pending_frame_.has_core = true;
} else {
pending_frame_.has_dependent = true;
if (frame.has_chanmap != 0u) {
pending_frame_.has_chanmap = true;
pending_frame_.chanmap = frame.chanmap;
}
}
bool present = false;
bool ignored_extra = false;
emdf::Container container;
const Status found = emdf::find_joc_emdf_optional(
frame.data, frame.size, &present, &container, &joc::score_container_as_joc,
&ignored_extra);
if (!found.ok()) {
return found;
}
if (ignored_extra) {
++info_.extra_container_frames;
}
if (!present) {
continue;
}
if (container.find(emdf::kIdJoc) == nullptr) {
continue;
}
joc_frame_params params;
const Status parsed =
joc::parse_eac3_frame(frame.data, frame.size, &entry.params, &container, nullptr);
joc::parse_eac3_frame(frame.data, frame.size, &params, &container, nullptr);
if (!parsed.ok()) {
return parsed;
}
pending_frame_.params = params;
pending_frame_.has_joc = true;
pending_frame_.syncframe_offset = frame.offset;
pending_frame_.syncframe_size = frame.size;
if (const emdf::Payload* payload = container.find(emdf::kIdOamd)) {
std::vector<std::uint8_t> bytes;
const Status extracted =
@@ -213,30 +362,87 @@ Status Stream::push_eac3(const std::uint8_t* data, std::size_t size, std::size_t
if (!extracted.ok()) {
return extracted;
}
const Status oamd = oamd::parse_id11(bytes.data(), bytes.size(), &entry.update);
// Speaker and binaural consume the full per-object block state; the
// other stream paths keep the reference's legacy single-block view.
const bool full_metadata_state = speaker_enabled_ || binaural_enabled_;
const Status oamd =
full_metadata_state ? oamd::parse_id11_state(bytes.data(), bytes.size(),
&pending_frame_.update)
: oamd::parse_id11(bytes.data(), bytes.size(),
&pending_frame_.update);
if (!oamd.ok()) {
return oamd;
}
entry.has_update = true;
entry.outer_offset = static_cast<std::int64_t>(payload->sample_offset);
pending_frame_.has_update = true;
pending_frame_.outer_offset = static_cast<std::int64_t>(payload->sample_offset);
const Status bed = oamd::parse_id11_bed_assignments(
bytes.data(), bytes.size(), &pending_frame_.bed_assignments);
if (!bed.ok()) {
return bed;
}
}
metadata_.push_back(entry);
}
return process_ready_frames();
resolve_bed_plan();
return process_ready_frames(false);
}
Status Stream::push_bed(const float* interleaved6, std::size_t samples, std::size_t* consumed) {
Status Stream::push_bed(const float* interleaved, std::size_t samples, std::uint32_t channels,
std::size_t* consumed) {
if (rebuilder_ == nullptr) {
return Status::fail(JOC_ERR_STATE, stage::kDsp, "stream is not an E-AC-3 input");
}
if (channels != 6u && channels != 8u) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kDsp,
"the core PCM must be interleaved as 6 or 8 channels, got " +
std::to_string(channels));
}
if (bed_input_channels_ == 0u) {
bed_input_channels_ = channels;
} else if (bed_input_channels_ != channels) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kDsp,
"the core PCM channel count changed from " +
std::to_string(bed_input_channels_) + " to " +
std::to_string(channels));
}
if (consumed != nullptr) {
*consumed = samples;
}
if (interleaved6 != nullptr && samples != 0u) {
bed_pending_.insert(bed_pending_.end(), interleaved6,
interleaved6 + samples * kBedChannels);
if (interleaved != nullptr && samples != 0u) {
bed_pending_.insert(bed_pending_.end(), interleaved,
interleaved + samples * static_cast<std::size_t>(channels));
}
return process_ready_frames();
return process_ready_frames(false);
}
bool Stream::resolve_bed_plan() {
if (bed_channels_ != 0u) {
return true;
}
const FrameMetadata* joc_entry = nullptr;
for (const FrameMetadata& candidate : metadata_) {
if (candidate.has_joc) {
joc_entry = &candidate;
break;
}
}
if (joc_entry == nullptr) {
return false;
}
joc::BedPlan plan;
const Status status = joc::compute_bed_plan(
joc_entry->has_core ? &joc_entry->core_frame : nullptr, joc_entry->has_core,
joc_entry->has_dependent, joc_entry->has_chanmap, joc_entry->chanmap,
joc_entry->params.dmx_config_idx, &plan);
if (!status.ok()) {
bed_plan_failed_ = true;
bed_plan_error_ = status;
return false;
}
bed_plan_ = plan;
bed_channels_ = static_cast<std::size_t>(plan.channels);
config_idx_ = static_cast<int>(joc_entry->params.dmx_config_idx);
core_channels_ = static_cast<int>(joc_entry->params.n_channels);
return true;
}
Status Stream::push_objects16(const float* planar16, std::size_t samples, std::size_t* consumed) {
@@ -246,49 +452,161 @@ Status Stream::push_objects16(const float* planar16, std::size_t samples, std::s
if (planar16 == nullptr || samples == 0u) {
return Status::success();
}
// Rendered immediately: the host has already done the JOC rebuild.
// Queued as whole frames, each planar [16][kFrameSamples]: the shape the
// objects16 output writes, so a host can feed a batch back unchanged.
constexpr std::size_t kFrameValues =
static_cast<std::size_t>(JOC_OUTPUT_CHANNELS) * kFrameSamples;
for (std::size_t offset = 0; offset < samples; offset += kFrameSamples) {
const std::size_t count = std::min(kFrameSamples, samples - offset);
std::vector<float> frame(static_cast<std::size_t>(JOC_OUTPUT_CHANNELS) * kFrameSamples,
0.0f);
const std::size_t base = objects_pending_.size();
const float* frame = planar16 + (offset / kFrameSamples) * kFrameValues;
objects_pending_.resize(base + kFrameValues, 0.0f);
for (std::size_t channel = 0; channel < JOC_OUTPUT_CHANNELS; ++channel) {
std::memcpy(frame.data() + channel * kFrameSamples,
planar16 + channel * samples + offset, count * sizeof(float));
std::memcpy(objects_pending_.data() + base + channel * kFrameSamples,
frame + channel * kFrameSamples, count * sizeof(float));
}
++info_.frames_in;
info_.samples_in += count;
const Status rendered = render_objects16(frame);
if (!rendered.ok()) {
return rendered;
}
return process_objects16_frames(false);
}
Status Stream::push_pcm_layout(const float* interleaved, std::size_t samples,
std::uint32_t channels, std::size_t* consumed) {
if (consumed != nullptr) {
*consumed = 0;
}
if (interleaved == nullptr || samples == 0u) {
return Status::success();
}
if (pcm_input_.layout() == nullptr) {
const Status configured = pcm_input_.configure(config_.pcm_layout,
static_cast<int>(channels),
config_.gain_db);
if (!configured.ok()) {
return configured;
}
if (count != kFrameSamples) {
break; // a partial frame is dropped; the host should push whole frames
} else if (pcm_input_.channels() != static_cast<int>(channels)) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kRender,
"PCM channel count changed mid-stream");
}
Status status = pcm_input_.append(interleaved, samples);
if (!status.ok()) {
return status;
}
std::size_t processed = 0;
while (pcm_input_.frame_ready()) {
status = pcm_input_.take_frame(&objects_frame_);
if (!status.ok()) {
return status;
}
status = push_objects16(objects_frame_.data(), kFrameSamples, nullptr);
if (!status.ok()) {
return status;
}
processed += kFrameSamples;
}
if (consumed != nullptr) {
*consumed = processed;
}
return Status::success();
}
Status Stream::process_ready_frames() {
while (bed_pending_.size() / kBedChannels >= kFrameSamples && !metadata_.empty()) {
const FrameMetadata entry = metadata_.front();
Status Stream::process_objects16_frames(bool drain_all) {
constexpr std::size_t kFrameValues =
static_cast<std::size_t>(JOC_OUTPUT_CHANNELS) * kFrameSamples;
while (objects_pending_.size() - objects_read_offset_ >= kFrameValues) {
// Leave the rest queued, in order, for a later push or for flush().
if (!drain_all && buffered_samples() >= kMaxRenderAheadSamples) {
break;
}
const auto first = objects_pending_.begin() +
static_cast<std::ptrdiff_t>(objects_read_offset_);
objects_frame_.assign(first, first + static_cast<std::ptrdiff_t>(kFrameValues));
objects_read_offset_ += kFrameValues;
const Status rendered = render_objects16(objects_frame_);
if (!rendered.ok()) {
return rendered;
}
++info_.frames_in;
info_.samples_in += kFrameSamples;
}
if (objects_read_offset_ == objects_pending_.size()) {
objects_pending_.clear();
objects_read_offset_ = 0;
} else if (objects_read_offset_ >= (1u << 20)) {
// Erasing from the front moves the remainder, so it is only worth doing
// once the consumed prefix is large enough to pay for the move.
objects_pending_.erase(
objects_pending_.begin(),
objects_pending_.begin() + static_cast<std::ptrdiff_t>(objects_read_offset_));
objects_read_offset_ = 0;
}
return Status::success();
}
Status Stream::process_ready_frames(bool drain_all) {
if (bed_plan_failed_) {
return bed_plan_error_;
}
resolve_bed_plan();
if (bed_channels_ == 0u) {
if (!drain_all || metadata_.empty()) {
return Status::success(); // waiting for the first JOC-bearing frame
}
return Status::fail(JOC_ERR_EMDF_TRANSPORT, stage::kEmdf,
"no_contiguous_joc_container: the input carries no JOC EMDF "
"container in any audio frame");
}
if (bed_input_channels_ != 0u && bed_input_channels_ != bed_channels_) {
return Status::fail(JOC_ERR_JOC_UNSUPPORTED_VARIANT, "eac3",
"core_channel_count_mismatch: the caller pushed " +
std::to_string(bed_input_channels_) +
"-channel bed PCM but joc_dmx_config_idx=" +
std::to_string(config_idx_) + " decodes to " +
std::to_string(bed_channels_) + " channels");
}
while (bed_pending_.size() - bed_read_offset_ >= kFrameSamples * bed_channels_ &&
!metadata_.empty()) {
// Leave the rest queued, in order, for a later push or for flush().
if (!drain_all && buffered_samples() >= kMaxRenderAheadSamples) {
break;
}
FrameMetadata entry = metadata_.front();
metadata_.pop_front();
std::vector<float> bed5(static_cast<std::size_t>(JOC_CORE_CHANNELS) * kFrameSamples, 0.0f);
std::vector<float> lfe(kFrameSamples, 0.0f);
for (std::size_t sample = 0; sample < kFrameSamples; ++sample) {
for (std::size_t channel = 0; channel < JOC_CORE_CHANNELS; ++channel) {
bed5[channel * kFrameSamples + sample] =
bed_pending_[sample * kBedChannels + kCoreChannels[channel]];
}
lfe[sample] = bed_pending_[sample * kBedChannels + kLfeChannel];
const int core_channels = entry.has_joc ? static_cast<int>(entry.params.n_channels)
: core_channels_;
if (core_channels <= 0) {
return Status::fail(JOC_ERR_STATE, stage::kDsp,
"the JOC core channel count is not known yet");
}
bed_pending_.erase(bed_pending_.begin(),
bed_pending_.begin() + static_cast<std::ptrdiff_t>(kFrameSamples *
kBedChannels));
if (!entry.has_joc) {
entry.params.dmx_config_idx = static_cast<std::uint8_t>(config_idx_);
entry.params.n_channels = static_cast<std::uint8_t>(core_channels);
}
const float* bed = bed_pending_.data() + bed_read_offset_;
bed5_.assign(static_cast<std::size_t>(core_channels) * kFrameSamples, 0.0f);
lfe_.assign(kFrameSamples, 0.0f);
for (std::size_t sample = 0; sample < kFrameSamples; ++sample) {
for (int lane = 0; lane < core_channels; ++lane) {
const int source = bed_plan_.lane[lane];
if (source >= 0) {
bed5_[static_cast<std::size_t>(lane) * kFrameSamples + sample] =
bed[sample * bed_channels_ + static_cast<std::size_t>(source)];
}
}
if (bed_plan_.lfe_channel >= 0) {
lfe_[sample] = bed[sample * bed_channels_ +
static_cast<std::size_t>(bed_plan_.lfe_channel)];
}
}
bed_read_offset_ += kFrameSamples * bed_channels_;
compact_bed_pending();
std::string error;
const Status rebuilt = joc::rebuild_objects16(rebuilder_, entry.params, bed5.data(),
lfe.data(), gain_, &objects16_, &error);
const Status rebuilt = joc::rebuild_objects16(
rebuilder_, entry.params, bed5_.data(), lfe_.data(),
static_cast<std::uint32_t>(core_channels), entry.has_joc, gain_, &objects16_,
&error);
if (!rebuilt.ok()) {
return Status::fail(rebuilt.code(), stage::kDsp, error);
}
@@ -303,6 +621,22 @@ Status Stream::process_ready_frames() {
return Status::success();
}
void Stream::compact_bed_pending() {
if (bed_read_offset_ == 0) {
return;
}
if (bed_read_offset_ == bed_pending_.size()) {
bed_pending_.clear();
bed_read_offset_ = 0;
} else if (bed_read_offset_ >= (1u << 20)) {
// Erasing from the front moves the remainder, so it is only worth doing
// once the consumed prefix is large enough to pay for the move.
bed_pending_.erase(bed_pending_.begin(),
bed_pending_.begin() + static_cast<std::ptrdiff_t>(bed_read_offset_));
bed_read_offset_ = 0;
}
}
Status Stream::render_objects16(const std::vector<float>& objects16) {
if (config_.output == JOC_STREAM_OUT_PCM_OBJECTS16) {
output_.insert(output_.end(), objects16.begin(), objects16.end());
@@ -313,13 +647,16 @@ Status Stream::render_objects16(const std::vector<float>& objects16) {
if (speaker_enabled_) {
std::string error;
const Status stepped =
speaker::step(&speaker_, objects16, pending_metadata_.has_update
? &pending_metadata_.update
: nullptr,
speaker::step(&speaker_, objects16,
pending_metadata_.has_update
? &pending_metadata_.update
: (pcm_input_.layout() != nullptr ? &pcm_input_.fixed_update()
: nullptr),
&error);
if (!stepped.ok()) {
return Status::fail(stepped.code(), stage::kRender, error);
}
output_.reserve(output_.size() + speaker_.output.size());
for (const double value : speaker_.output) {
output_.push_back(static_cast<float>(value));
}
@@ -333,20 +670,21 @@ Status Stream::render_objects16(const std::vector<float>& objects16) {
const Status submitted =
binaural_.submit_frame(objects16.data(),
pending_metadata_.has_update ? &pending_metadata_.update : nullptr,
pending_metadata_.has_update ? &pending_metadata_.update
: (pcm_input_.layout() != nullptr ? &pcm_input_.fixed_update() : nullptr),
static_cast<std::int64_t>(info_.frames_out),
pending_metadata_.outer_offset,
static_cast<std::int64_t>(config_.object_delay_samples));
if (!submitted.ok()) {
return submitted;
}
std::vector<double> produced;
binaural_.take_output(&produced);
for (const double value : produced) {
binaural_.take_output(&produced_);
output_.reserve(output_.size() + produced_.size());
for (const double value : produced_) {
output_.push_back(static_cast<float>(value));
}
info_.frames_out++;
info_.samples_out += produced.size() / 2u;
info_.samples_out += produced_.size() / 2u;
return Status::success();
}
@@ -360,23 +698,23 @@ Status Stream::render_objects16(const std::vector<float>& objects16) {
Status Stream::render_rosella_objects16(const std::vector<float>& objects16) {
const Status submitted =
rosella_.submit_frame(objects16.data(),
pending_metadata_.has_update ? &pending_metadata_.update : nullptr,
pending_metadata_.has_update ? &pending_metadata_.update
: (pcm_input_.layout() != nullptr ? &pcm_input_.fixed_update() : nullptr),
static_cast<std::int64_t>(info_.frames_out),
pending_metadata_.outer_offset,
static_cast<std::int64_t>(config_.object_delay_samples));
if (!submitted.ok()) {
return submitted;
}
std::vector<double> produced;
rosella_.take_output(&produced);
if (!produced.empty()) {
rosella_pending_.insert(rosella_pending_.end(), produced.begin(), produced.end());
rosella_.take_output(&produced_);
if (!produced_.empty()) {
rosella_pending_.insert(rosella_pending_.end(), produced_.begin(), produced_.end());
}
release_rosella_output(kFrameSamples);
info_.frames_out++;
// Counted as the runtime produces it, which is also how the SOFA path counts:
// the totals are identical, only the frame they appear on differs.
info_.samples_out += produced.size() / 2u;
info_.samples_out += produced_.size() / 2u;
return Status::success();
}
@@ -389,6 +727,7 @@ void Stream::release_rosella_output(std::size_t limit) {
return;
}
const std::size_t values = count * 2u;
output_.reserve(output_.size() + values);
for (std::size_t index = 0; index < values; ++index) {
output_.push_back(static_cast<float>(rosella_pending_[rosella_read_offset_ + index]));
}
@@ -430,6 +769,20 @@ Status Stream::pull(float* destination, std::size_t capacity_samples, std::size_
}
Status Stream::flush() {
// Input has ended, so drain what the cap held back: nothing else will
// trigger rendering.
const Status pending = flush_pending_frame();
if (!pending.ok()) {
return pending;
}
const Status remaining = process_ready_frames(true);
if (!remaining.ok()) {
return remaining;
}
const Status objects = process_objects16_frames(true);
if (!objects.ok()) {
return objects;
}
if (binaural_ready_) {
std::vector<double> tail;
const Status drained =
@@ -437,6 +790,7 @@ Status Stream::flush() {
if (!drained.ok()) {
return drained;
}
output_.reserve(output_.size() + tail.size());
for (const double value : tail) {
output_.push_back(static_cast<float>(value));
}
@@ -453,6 +807,7 @@ Status Stream::flush() {
// tail only sounds after it. The program samples were already counted by
// render_rosella_objects16, so only the tail is added here.
release_rosella_output(rosella_pending_samples());
output_.reserve(output_.size() + tail.size());
for (const double value : tail) {
output_.push_back(static_cast<float>(value));
}
+80 -12
View File
@@ -6,14 +6,16 @@
#include <string>
#include <vector>
#include "binaural/binaural_runtime.h"
#include "binaural/jochrtf_runtime.h"
#include "eac3_transport/eac3_reader.h"
#include "foundation/status.h"
#include "hrtf/rosella_renderer.h"
#include "joc_bitstream/joc_parser.h"
#include "joc_core.h"
#include "joc_stream.h"
#include "oamd/oamd_parser.h"
#include "speaker/speaker_step.h"
#include "virtual_speaker/virtual_speaker.h"
namespace joc::stream {
@@ -29,13 +31,13 @@ struct Config {
std::uint32_t object_delay_samples = 1473;
double gain_db = 0.0;
std::uint32_t native_threads = 0;
// The three HRTF shapes of joc_task_config, in its precedence order: a Rosella
// model wins over a SOFA, and hrtf_path (.jochrtf) is the fallback.
std::string hrtf_sofa_path;
// Binaural inputs of joc_task_config: a Rosella model wins over hrtf_path
// (.jochrtf).
std::string personalized_headphone_path;
std::string hrtf_cache_dir;
std::uint32_t hrtf_cache_policy = JOC_HRTF_CACHE_MEMORY;
double hrtf_radius_m = 1.0;
std::uint32_t jochrtf_room = 1;
std::string pcm_layout;
// Filterbank of the Rosella path; the other binaural inputs ignore it.
std::uint32_t rosella_filterbank = JOC_ROSELLA_FILTERBANK_PUBLIC;
};
struct Info {
@@ -46,16 +48,44 @@ struct Info {
std::uint64_t bytes_in = 0;
std::uint64_t oamd_payloads = 0;
std::uint64_t oamd_transitions = 0;
std::uint64_t missing_joc_frames = 0;
// Audio frames whose ID14 payload ended inside joc_data; they render as
// invalid frames and hold the previous matrices.
std::uint64_t truncated_joc_frames = 0;
std::uint64_t objects_clamped_frames = 0;
// Audio frames whose syncframe held more than one top-level JOC container and
// were decoded from the single one that carries a complete joc() payload.
std::uint64_t extra_container_frames = 0;
// Audio frames whose extra-pair identity disagreed across layers (spec 11.2
// checks 1 and 2). The identity is metadata only, so these still render.
std::uint64_t chanmap_pair_mismatch_frames = 0;
std::uint64_t bed_mask_mismatch_frames = 0;
std::uint32_t output_channels = 0;
std::uint32_t ended = 0;
};
// One frame's metadata, queued while the matching core PCM arrives.
// One audio frame's metadata, queued while the matching core PCM arrives.
//
// One audio frame is the group of syncframes up to (and excluding) the first
// repeated (codec, strmtyp, substreamid) combination; the JOC payload usually
// lives in the dependent substream while the independent substream carries only
// the 5.1 core. The L2 fields below feed the spec section 11.2 cross-layer
// checks.
struct FrameMetadata {
joc_frame_params params{};
oamd::OamdUpdate update{};
bool has_update = false;
std::int64_t outer_offset = 0;
bool has_joc = false;
eac3::Frame core_frame{}; // independent substream header (codec/strmtyp=0)
bool has_core = false;
bool has_dependent = false;
bool has_chanmap = false;
std::uint16_t chanmap = 0;
std::size_t syncframe_offset = 0;
std::size_t syncframe_size = 0;
std::vector<eac3::Frame> streams;
std::vector<oamd::BedAssignment> bed_assignments;
};
class Stream {
@@ -68,8 +98,11 @@ public:
Status create(const Config& config);
Status push_eac3(const std::uint8_t* data, std::size_t size, std::size_t* consumed);
Status push_bed(const float* interleaved6, std::size_t samples, std::size_t* consumed);
Status push_bed(const float* interleaved, std::size_t samples, std::uint32_t channels,
std::size_t* consumed);
Status push_objects16(const float* planar16, std::size_t samples, std::size_t* consumed);
Status push_pcm_layout(const float* interleaved, std::size_t samples, std::uint32_t channels,
std::size_t* consumed);
Status pull(float* destination, std::size_t capacity_samples, std::size_t* produced);
Status flush();
Status reset();
@@ -85,8 +118,13 @@ public:
: 0u;
}
// Cap on rendered samples that have not been pulled. A push renders what it
// makes ready, so a caller that feeds faster than it pulls renders ahead.
static constexpr std::size_t kMaxRenderAheadSamples = 16384;
private:
Status process_ready_frames();
// `drain_all` ignores kMaxRenderAheadSamples and renders every ready frame.
Status process_ready_frames(bool drain_all);
Status render_objects16(const std::vector<float>& objects16);
Status render_rosella_objects16(const std::vector<float>& objects16);
// Moves at most `limit` rendered stereo samples per channel out of the FIFO
@@ -96,14 +134,42 @@ private:
return rosella_ready_ ? (rosella_pending_.size() - rosella_read_offset_) / 2u : 0u;
}
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.
void compact_bed_pending();
// Closes the audio frame currently being assembled and queues it.
Status flush_pending_frame();
// Resolves the bed layout from the first queued frame that carries JOC;
// returns false while it is still unknown and more input may arrive.
bool resolve_bed_plan();
// Renders the queued objects16 frames, bounded by kMaxRenderAheadSamples.
Status process_objects16_frames(bool drain_all);
Config config_;
Info info_;
eac3::FrameReader reader_;
std::deque<FrameMetadata> metadata_;
FrameMetadata pending_metadata_;
FrameMetadata pending_frame_;
joc::BedPlan bed_plan_;
std::size_t bed_channels_ = 0;
int config_idx_ = -1;
int core_channels_ = 0;
bool bed_plan_failed_ = false;
Status bed_plan_error_;
std::uint32_t bed_input_channels_ = 0;
std::vector<float> bed_pending_;
std::vector<std::uint8_t> frame_copy_;
std::size_t bed_read_offset_ = 0;
std::vector<float> bed5_;
std::vector<float> lfe_;
virtual_speaker::Input pcm_input_;
oamd::OamdUpdate fixed_update_{};
bool has_fixed_update_ = false;
std::vector<float> objects_pending_;
std::size_t objects_read_offset_ = 0;
std::vector<float> objects_frame_;
std::vector<float> objects16_;
std::vector<float> output_;
std::size_t read_offset_ = 0;
@@ -111,13 +177,15 @@ private:
ejoc_renderer_handle rebuilder_ = nullptr;
speaker::SpeakerStep speaker_;
binaural::SofaBinauralRuntime binaural_;
binaural::JochrtfRuntime binaural_;
hrtf::RosellaRuntime rosella_;
std::vector<double> rosella_pending_;
std::size_t rosella_read_offset_ = 0;
std::vector<double> produced_;
bool speaker_enabled_ = false;
bool binaural_enabled_ = false;
bool binaural_ready_ = false;
bool bed_positions_ready_ = false;
bool rosella_ready_ = false;
float gain_ = 1.0f;
};
+714 -179
View File
File diff suppressed because it is too large. Load diff
+170 -44
View File
@@ -1,8 +1,10 @@
#include "timeline/position_timeline.h"
#include <algorithm>
#include <cstring>
#include "foundation/geometry.h"
#include "foundation/metadata_timing.h"
namespace joc::timeline {
@@ -93,33 +95,100 @@ Status ObjectPositionTrack::position_at(std::int64_t sample, double out[3]) {
return Status::success();
}
OamdPositionTimeline::OamdPositionTimeline(int object_count) : object_count_(object_count) {
if (object_count != kTimelineObjects) {
object_count_ = kTimelineObjects;
OamdPositionTimeline::OamdPositionTimeline(int object_count)
: object_count_(std::clamp(object_count, 1, oamd::kMaxObjects - 1)) {
const std::size_t count = static_cast<std::size_t>(object_count_);
tracks_.resize(count);
previous_targets_.resize(count);
has_previous_.assign(count, false);
fixed_.assign(count, false);
fixed_xyz_.resize(count);
}
void OamdPositionTimeline::ensure_tracks(int count) {
const int capped = std::clamp(count, 1, oamd::kMaxObjects - 1);
if (capped <= object_count_) {
return;
}
const std::size_t size = static_cast<std::size_t>(capped);
object_count_ = capped;
tracks_.resize(size);
previous_targets_.resize(size);
has_previous_.resize(size, false);
fixed_.resize(size, false);
fixed_xyz_.resize(size);
}
void OamdPositionTimeline::set_fixed_position(int object_index, const double position[3]) {
if (object_index < 1 || object_index > object_count_) {
return;
}
const std::size_t index = static_cast<std::size_t>(object_index - 1);
fixed_[index] = true;
for (int axis = 0; axis < 3; ++axis) {
fixed_xyz_[index][static_cast<std::size_t>(axis)] = position[axis];
}
}
Status OamdPositionTimeline::submit_update(const oamd::OamdUpdate& update,
std::int64_t frame_start_sample,
std::int64_t outer_sample_offset,
std::int64_t object_delay_samples,
std::int64_t processed_sample) {
if (frame_start_sample < 0 || outer_sample_offset < 0 || object_delay_samples < 0) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kOamd,
"OAMD frame, outer offset and object delay must be non-negative");
void OamdPositionTimeline::reset() {
state_.reset();
for (int index = 0; index < object_count_; ++index) {
tracks_[static_cast<std::size_t>(index)] = ObjectPositionTrack();
has_previous_[static_cast<std::size_t>(index)] = false;
previous_targets_[static_cast<std::size_t>(index)] = {0.0, 0.0, 0.0};
}
state_.apply(update);
initialized_ = false;
payload_count_ = 0;
transition_count_ = 0;
last_coded_event_sample_ = -1;
}
double targets[kTimelineObjects][3] = {};
for (int index = 0; index < kTimelineObjects; ++index) {
void OamdPositionTimeline::apply_block(const oamd::FrameState& state,
std::uint32_t block_index) {
// Track i reads OAMD object i + 1: object 0 is the LFE/bed slot the JOC
// renderers do not position. Bed and ISF objects carry no position field,
// and an inactive block keeps the previous position, exactly like the
// reference frame_update() value construction.
for (int track = 0; track < object_count_; ++track) {
const int object_index = track + 1;
if (object_index >= static_cast<int>(state.objects.size())) {
break;
}
const oamd::ObjectElementState& element =
state.objects[static_cast<std::size_t>(object_index)];
if (block_index >= element.blocks.size()) {
continue;
}
const oamd::ObjectRenderState& render =
element.blocks[static_cast<std::size_t>(block_index)].render;
if (render.not_active || element.kind != oamd::ObjectKind::kDynamic) {
continue;
}
state_.apply_render_state(object_index, render);
}
}
void OamdPositionTimeline::targets(std::vector<std::array<double, 3>>* out) const {
out->resize(static_cast<std::size_t>(object_count_));
for (int index = 0; index < object_count_; ++index) {
const std::size_t slot = static_cast<std::size_t>(index);
if (fixed_[slot]) {
(*out)[slot] = fixed_xyz_[slot];
continue;
}
double x = 0.0;
double y = 0.0;
double z = 0.0;
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],
&targets[index][2]);
state_.q(index + 1, 2), &x, &y, &z);
(*out)[slot] = {x, y, z};
}
}
const std::int64_t coded_event =
frame_start_sample + outer_sample_offset +
static_cast<std::int64_t>(update.block_offset_samples);
Status OamdPositionTimeline::schedule(const std::vector<std::array<double, 3>>& targets,
std::int64_t coded_event, std::int64_t ramp_samples,
std::int64_t object_delay_samples,
std::int64_t processed_sample) {
if (coded_event < last_coded_event_sample_) {
return timeline_fail(JOC_ERR_OAMD_UNSUPPORTED_VARIANT,
"non_monotonic_binaural_updates: event sample " +
@@ -135,48 +204,105 @@ Status OamdPositionTimeline::submit_update(const oamd::OamdUpdate& update,
"sample " + std::to_string(processed_sample) +
" had been processed, so sample 0 cannot be backfilled");
}
for (int index = 0; index < kTimelineObjects; ++index) {
tracks_[index].set_initial(targets[index]);
std::memcpy(previous_targets_[index], targets[index], sizeof(targets[index]));
has_previous_[index] = true;
for (int index = 0; index < object_count_; ++index) {
const std::size_t slot = static_cast<std::size_t>(index);
tracks_[slot].set_initial(targets[slot].data());
previous_targets_[slot] = targets[slot];
has_previous_[slot] = true;
}
initialized_ = true;
++payload_count_;
return Status::success();
}
const std::int64_t ramp_duration = static_cast<std::int64_t>(update.ramp_duration_samples);
const std::int64_t effective_ramp =
ramp_duration - kOamdUpdateQuantumSamples > 0 ? ramp_duration - kOamdUpdateQuantumSamples
: 0;
std::int64_t transition_start = coded_event + object_delay_samples;
if (effective_ramp != 0) {
transition_start += kOamdUpdateQuantumSamples;
}
for (int index = 0; index < kTimelineObjects; ++index) {
const bool changed = !has_previous_[index] ||
std::memcmp(previous_targets_[index], targets[index],
sizeof(targets[index])) != 0;
const std::int64_t effective_ramp = std::max<std::int64_t>(0, ramp_samples);
const std::int64_t transition_start =
timing::align_metadata_sample(coded_event + object_delay_samples);
for (int index = 0; index < object_count_; ++index) {
const std::size_t slot = static_cast<std::size_t>(index);
const bool changed =
!has_previous_[slot] ||
std::memcmp(previous_targets_[slot].data(), targets[slot].data(),
sizeof(targets[slot])) != 0;
if (!changed) {
continue;
}
const Status status = tracks_[index].append(transition_start, effective_ramp,
targets[index], index + 1);
const Status status =
tracks_[slot].append(transition_start, effective_ramp, targets[slot].data(),
index + 1);
if (!status.ok()) {
return status;
}
std::memcpy(previous_targets_[index], targets[index], sizeof(targets[index]));
has_previous_[index] = true;
previous_targets_[slot] = targets[slot];
has_previous_[slot] = true;
++transition_count_;
}
return Status::success();
}
Status OamdPositionTimeline::submit_update(const oamd::OamdUpdate& update,
std::int64_t frame_start_sample,
std::int64_t outer_sample_offset,
std::int64_t object_delay_samples,
std::int64_t processed_sample) {
if (frame_start_sample < 0 || outer_sample_offset < 0 || object_delay_samples < 0) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kOamd,
"OAMD frame, outer offset and object delay must be non-negative");
}
if (!update.has_frame_state) {
state_.apply(update);
targets(&targets_);
const std::int64_t coded_event =
frame_start_sample + outer_sample_offset +
static_cast<std::int64_t>(update.block_offset_samples);
const Status status =
schedule(targets_, coded_event, update.ramp_duration_samples, object_delay_samples,
processed_sample);
if (status.ok()) {
++payload_count_;
}
return status;
}
const oamd::FrameState& state = update.frame_state;
ensure_tracks(state.object_count > 0u ? static_cast<int>(state.object_count) - 1 : 0);
const std::uint32_t block_count =
state.blocks.empty() ? 1u : static_cast<std::uint32_t>(state.blocks.size());
for (std::uint32_t block = 0; block < block_count; ++block) {
apply_block(state, block);
targets(&targets_);
std::int64_t block_offset = 0;
std::int64_t ramp_samples = 0;
if (block < state.blocks.size()) {
block_offset = static_cast<std::int64_t>(state.blocks[block].block_offset_samples);
ramp_samples = static_cast<std::int64_t>(state.blocks[block].ramp_duration_samples);
}
const std::int64_t coded_event =
frame_start_sample + outer_sample_offset + block_offset;
const Status status = schedule(targets_, coded_event, ramp_samples,
object_delay_samples, processed_sample);
if (!status.ok()) {
return status;
}
}
++payload_count_;
return Status::success();
}
Status OamdPositionTimeline::positions_at(std::int64_t sample,
double positions[kTimelineObjects][3]) {
for (int index = 0; index < kTimelineObjects; ++index) {
const Status status = tracks_[index].position_at(sample, positions[index]);
Status OamdPositionTimeline::positions_at(std::int64_t sample, double* positions,
int count) {
if (positions == nullptr || count < 0) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kOamd,
"binaural positions need a non-negative count and a buffer");
}
if (count > object_count_) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kOamd,
"binaural positions requested " + std::to_string(count) +
" objects but the timeline tracks " +
std::to_string(object_count_));
}
for (int index = 0; index < count; ++index) {
const Status status = tracks_[static_cast<std::size_t>(index)].position_at(
sample, positions + static_cast<std::size_t>(index) * 3u);
if (!status.ok()) {
return status;
}
+39 -7
View File
@@ -2,6 +2,7 @@
#pragma once
#include <array>
#include <cstdint>
#include <vector>
@@ -10,7 +11,11 @@
namespace joc::timeline {
inline constexpr std::int64_t kOamdUpdateQuantumSamples = 64;
// The JOC binaural renderers carry one LFE plus fifteen object sources, but the
// timeline is not tied to that product: it keeps one track per declared OAMD
// object (bounded only by oamd::kMaxObjects) and the renderer reads as many as
// its source layout consumes. A binaural output with a different source count
// (for example one fed by a TrueHD decode) can ask for more tracks.
inline constexpr int kTimelineObjects = 15;
struct PositionTransition {
@@ -43,26 +48,53 @@ class OamdPositionTimeline {
public:
explicit OamdPositionTimeline(int object_count = kTimelineObjects);
// Schedules one OAMD payload. A payload parsed by parse_id11_state() carries
// the full frame state: every position block is applied at its own offset and
// ramp, and the track list grows to cover every declared object. The legacy
// single-block slot view is still accepted for direct callers.
Status submit_update(const oamd::OamdUpdate& update, std::int64_t frame_start_sample,
std::int64_t outer_sample_offset, std::int64_t object_delay_samples,
std::int64_t processed_sample);
// positions[15][3]; queries must be monotonically increasing.
Status positions_at(std::int64_t sample, double positions[kTimelineObjects][3]);
// positions[count][3]; queries must be monotonically increasing.
Status positions_at(std::int64_t sample, double* positions, int count);
// bed 声道是固定通道:OAMD 不给位置,方位由声明的 bed 布局给出。
void set_fixed_position(int object_index, const double position[3]);
// Drops the OAMD state and every transition but keeps the fixed bed positions:
// they describe the content, not the playback position.
void reset();
int object_count() const { return object_count_; }
std::uint64_t payload_count() const { return payload_count_; }
std::uint64_t transition_count() const { return transition_count_; }
bool initialized() const { return initialized_; }
const ObjectPositionTrack& track(int index) const { return tracks_[index]; }
const ObjectPositionTrack& track(int index) const { return tracks_[static_cast<std::size_t>(index)]; }
private:
// Grows the track list so every declared OAMD object has one (the JOC
// renderers use the first kTimelineObjects).
void ensure_tracks(int count);
// OAMD position state after applying one frame-state block.
void apply_block(const oamd::FrameState& state, std::uint32_t block_index);
// Current ADM cartesian target of every track.
void targets(std::vector<std::array<double, 3>>* out) const;
// Initialises from the first update or appends the changed transitions.
Status schedule(const std::vector<std::array<double, 3>>& targets,
std::int64_t coded_event, std::int64_t ramp_samples,
std::int64_t object_delay_samples, std::int64_t processed_sample);
int object_count_;
oamd::OamdState state_;
ObjectPositionTrack tracks_[kTimelineObjects];
std::vector<ObjectPositionTrack> tracks_;
bool initialized_ = false;
double previous_targets_[kTimelineObjects][3] = {};
bool has_previous_[kTimelineObjects] = {};
std::vector<std::array<double, 3>> previous_targets_;
std::vector<bool> has_previous_;
std::vector<bool> fixed_;
std::vector<std::array<double, 3>> fixed_xyz_;
std::vector<std::array<double, 3>> targets_;
std::uint64_t payload_count_ = 0;
std::uint64_t transition_count_ = 0;
std::int64_t last_coded_event_sample_ = -1;
@@ -0,0 +1,161 @@
#include "virtual_speaker/virtual_speaker.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include "joc_core.h"
namespace joc::virtual_speaker {
namespace {
constexpr std::size_t kFrameSamples = JOC_FRAME_SAMPLES;
constexpr std::size_t kSourceChannels = JOC_OUTPUT_CHANNELS;
// WAV order follows the ffmpeg layouts: 5.1 = L R C LFE BL BR,
// 7.1 = L R C LFE BL BR SL SR.
constexpr Layout kLayouts[] = {
{"2.0",
2,
{{false, -1.0, 1.0, 0.0},
{false, 1.0, 1.0, 0.0}}},
{"5.1",
6,
{{false, -1.0, 1.0, 0.0},
{false, 1.0, 1.0, 0.0},
{false, 0.0, 1.0, 0.0},
{true, 0.0, 1.0, 0.0},
{false, -1.0, -1.0, 0.0},
{false, 1.0, -1.0, 0.0}}},
{"7.1",
8,
{{false, -1.0, 1.0, 0.0},
{false, 1.0, 1.0, 0.0},
{false, 0.0, 1.0, 0.0},
{true, 0.0, 1.0, 0.0},
{false, -1.0, -1.0, 0.0},
{false, 1.0, -1.0, 0.0},
{false, -1.0, 0.0, 0.0},
{false, 1.0, 0.0, 0.0}}},
};
std::int16_t q_for_axis(double value) {
if (value <= -0.999) {
return 0;
}
if (value >= 0.999) {
return 32767;
}
return 16384;
}
void fill_fixed_positions(const Layout& layout, oamd::OamdUpdate* update) {
update->object_count = static_cast<std::uint32_t>(kSourceChannels);
update->block_offset_samples = 0;
update->ramp_duration_samples = 0;
int slot = 1;
for (int channel = 0; channel < layout.channels; ++channel) {
const ChannelSpec& spec = layout.channel_specs[channel];
const int destination = spec.lfe ? 0 : slot++;
update->slots[destination].q1 = q_for_axis(spec.x);
update->slots[destination].q2 = q_for_axis(-spec.y);
update->slots[destination].q3 = q_for_axis(spec.z);
}
}
} // namespace
const Layout* find_layout(const std::string& name) {
for (const Layout& layout : kLayouts) {
if (name == layout.name) {
return &layout;
}
}
return nullptr;
}
const Layout* detect_layout(int channels) {
for (const Layout& layout : kLayouts) {
if (layout.channels == channels) {
return &layout;
}
}
return nullptr;
}
Status Input::configure(const std::string& layout_name, int channels, double gain_db) {
const Layout* layout =
(layout_name.empty() || layout_name == "auto")
? detect_layout(channels)
: find_layout(layout_name);
if (layout == nullptr || layout->channels != channels) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kRender,
"PCM layout does not match the channel count");
}
layout_ = layout;
channels_ = channels;
gain_ = static_cast<double>(std::pow(10.0, gain_db / 20.0));
pending_.clear();
read_offset_ = 0;
fill_fixed_positions(*layout_, &fixed_update_);
return Status::success();
}
void Input::reset() {
pending_.clear();
read_offset_ = 0;
}
Status Input::append(const float* interleaved, std::size_t frames) {
if (interleaved == nullptr || frames == 0u) {
return Status::success();
}
if (layout_ == nullptr || channels_ <= 0) {
return Status::fail(JOC_ERR_STATE, stage::kRender,
"virtual speaker input is not configured");
}
pending_.insert(pending_.end(), interleaved,
interleaved + frames * static_cast<std::size_t>(channels_));
return Status::success();
}
bool Input::frame_ready() const {
return layout_ != nullptr &&
pending_.size() - read_offset_ >=
kFrameSamples * static_cast<std::size_t>(channels_);
}
Status Input::take_frame(std::vector<float>* objects16) {
if (objects16 == nullptr) {
return Status::fail(JOC_ERR_INVALID_ARGUMENT, stage::kRender,
"objects16 output is null");
}
if (!frame_ready()) {
return Status::fail(JOC_ERR_STATE, stage::kRender,
"no complete PCM frame is buffered");
}
objects16->assign(kSourceChannels * kFrameSamples, 0.0f);
const float* source = pending_.data() + read_offset_;
int slot = 1;
for (int channel = 0; channel < layout_->channels; ++channel) {
const int destination = layout_->channel_specs[channel].lfe ? 0 : slot++;
for (std::size_t sample = 0; sample < kFrameSamples; ++sample) {
(*objects16)[static_cast<std::size_t>(destination) * kFrameSamples + sample] =
source[sample * static_cast<std::size_t>(channels_) + channel] *
static_cast<float>(gain_);
}
}
read_offset_ += kFrameSamples * static_cast<std::size_t>(channels_);
if (read_offset_ == pending_.size()) {
pending_.clear();
read_offset_ = 0;
} else if (read_offset_ >= (1u << 20)) {
pending_.erase(pending_.begin(),
pending_.begin() + static_cast<std::ptrdiff_t>(read_offset_));
read_offset_ = 0;
}
return Status::success();
}
} // namespace joc::virtual_speaker
@@ -0,0 +1,57 @@
// Virtual speaker input: ordinary multichannel PCM as fixed-direction JOC
// objects. It owns only the layout mapping and the PCM-to-objects16 shape;
// decoding, speaker rendering and binaural rendering stay in their own modules.
#pragma once
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
#include "foundation/status.h"
#include "oamd/oamd_parser.h"
namespace joc::virtual_speaker {
struct ChannelSpec {
bool lfe;
double x;
double y;
double z;
};
struct Layout {
const char* name;
int channels;
ChannelSpec channel_specs[8];
};
const Layout* find_layout(const std::string& name);
const Layout* detect_layout(int channels);
class Input {
public:
// gain_db is the module's master attenuation; it is applied to every
// mapped channel once, before the objects16 frame leaves the module.
Status configure(const std::string& layout_name, int channels, double gain_db = 0.0);
void reset();
const oamd::OamdUpdate& fixed_update() const { return fixed_update_; }
int channels() const { return channels_; }
const Layout* layout() const { return layout_; }
// Appends interleaved frames; take_frame() emits whole 1536-frame blocks.
Status append(const float* interleaved, std::size_t frames);
bool frame_ready() const;
Status take_frame(std::vector<float>* objects16);
private:
const Layout* layout_ = nullptr;
int channels_ = 0;
double gain_ = 1.0;
oamd::OamdUpdate fixed_update_{};
std::vector<float> pending_;
std::size_t read_offset_ = 0;
};
} // namespace joc::virtual_speaker
+28 -12
View File
@@ -8,18 +8,19 @@
#include <vector>
#include "log.h"
#include "win_path.h"
namespace joc_container {
namespace {
std::wstring utf8_to_wide(const std::string& text) {
if (text.empty()) return {};
const int needed = MultiByteToWideChar(CP_UTF8, 0, text.c_str(),
static_cast<int>(text.size()), nullptr, 0);
std::wstring out(static_cast<std::size_t>(needed), L'\0');
MultiByteToWideChar(CP_UTF8, 0, text.c_str(), static_cast<int>(text.size()), out.data(),
needed);
return out;
// A library scan probes every container in the library, and most of them are
// declined; they also mostly share a directory, so the path would spend the log's
// byte budget repeating the same prefix once per file. The file name is what
// identifies the line. Files this component claims are logged with their full
// path by the caller.
std::string file_name_of(const std::string& path) {
const std::string::size_type slash = path.find_last_of("\\/");
return (slash == std::string::npos) ? path : path.substr(slash + 1);
}
// A bounded, read-only view of the file. Every accessor returns false instead of
@@ -27,7 +28,7 @@ std::wstring utf8_to_wide(const std::string& text) {
class Window {
public:
bool open(const std::string& path) {
const std::wstring wide = utf8_to_wide(path);
const std::wstring wide = joc_path::to_wide_extended(path);
handle_ = CreateFileW(wide.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (handle_ == INVALID_HANDLE_VALUE) {
@@ -200,15 +201,24 @@ Result scan_mp4(const Window& file, std::size_t max_bytes) {
Result result;
result.kind = Kind::kMp4;
// moov is usually at the start for streamed files and at the end otherwise.
// moov is usually at the start for streamed files and at the end otherwise. The
// walk reads box headers where they lie and steps over mdat in one go, so the
// whole file is walked from the top: a fixed prefix window cannot reach a moov
// that is larger than the window, which is what an MP4 with its cover art stored
// as a video track produces (a 4.9 MB moov against a 4 MiB window). The tail
// range stays as a fallback for a file whose leading boxes do not parse.
struct Range {
std::uint64_t begin;
std::uint64_t end;
};
std::vector<Range> ranges{{0, (std::min<std::uint64_t>)(file.size(), max_bytes)}};
std::vector<Range> ranges{{0, file.size()}};
if (file.size() > max_bytes) {
ranges.push_back({file.size() - max_bytes, file.size()});
}
// An oversized moov is a file this probe cannot describe, and walking it would be
// unbounded work; it is reported instead of entered.
constexpr std::uint64_t kMaxMoovBytes = 64ull * 1024ull * 1024ull;
bool oversized_moov = false;
unsigned audio_seen = 0;
bool found_any_audio = false;
@@ -218,6 +228,10 @@ Result scan_mp4(const Window& file, std::size_t max_bytes) {
[&](const std::string& type, std::uint64_t payload, std::uint64_t box_end,
std::size_t) {
if (type != "moov") return true;
if (box_end - payload > kMaxMoovBytes) {
oversized_moov = true;
return true;
}
walk_boxes(file, payload, box_end, 1,
[&](const std::string& inner, std::uint64_t inner_payload,
std::uint64_t inner_end, std::size_t) {
@@ -273,6 +287,8 @@ Result scan_mp4(const Window& file, std::size_t max_bytes) {
result.detail = "mp4: first audio track is " +
(first_audio_format.empty() ? std::string("unknown")
: first_audio_format);
} else if (oversized_moov) {
result.detail = "mp4: moov is larger than the scan limit";
} else {
result.detail = "mp4: no audio track found in the scanned window";
}
@@ -519,7 +535,7 @@ Result scan(const std::string& path, std::size_t max_bytes) {
} else {
result = scan_mp4(file, max_bytes);
}
joc_log::line("container: %s -> %s (eac3=%d audio#%u codec=%s)", path.c_str(),
joc_log::line("container: %s -> %s (eac3=%d audio#%u codec=%s)", file_name_of(path).c_str(),
result.detail.c_str(), result.eac3 ? 1 : 0, result.audio_index,
result.codec.empty() ? "-" : result.codec.c_str());
return result;
+112 -5
View File
@@ -249,16 +249,120 @@ bool contains_payload(const std::uint8_t* frame, std::size_t size, std::uint8_t
} // namespace
std::size_t frame_bytes_at(const std::uint8_t* data, std::size_t size, std::size_t offset) {
if (data == nullptr || offset + 4u > size) return 0;
namespace {
std::uint32_t read_bits(const std::uint8_t* data, std::size_t start, std::size_t count) {
std::uint32_t value = 0;
for (std::size_t index = start; index < start + count; ++index) {
value = (value << 1) | ((data[index >> 3] >> (7u - (index & 7u))) & 1u);
}
return value;
}
// AC-3 syncframe length in 16-bit words, indexed by fscod then frmsizecod.
const std::uint16_t kAc3FrameWords[3][38] = {
{64, 64, 80, 80, 96, 96, 112, 112, 128, 128, 160, 160, 192, 192, 224, 224,
256, 256, 320, 320, 384, 384, 448, 448, 512, 512, 640, 640, 768, 768,
896, 896, 1024, 1024, 1152, 1152, 1280, 1280},
{69, 70, 87, 88, 104, 105, 121, 122, 139, 140, 174, 175, 208, 209, 243, 244,
278, 278, 348, 348, 417, 418, 487, 487, 557, 557, 696, 696, 835, 835,
975, 975, 1114, 1114, 1253, 1253, 1393, 1393},
{96, 96, 120, 120, 144, 144, 168, 168, 192, 192, 240, 240, 288, 288, 336, 336,
384, 384, 480, 480, 576, 576, 672, 672, 768, 768, 960, 960, 1152, 1152,
1344, 1344, 1536, 1536, 1728, 1728, 1920, 1920},
};
} // namespace
std::size_t frame_header_at(const std::uint8_t* data, std::size_t size, std::size_t offset,
FrameHeader* out) {
if (data == nullptr || offset + 6u > size) return 0;
const std::uint16_t syncword =
static_cast<std::uint16_t>((static_cast<std::uint16_t>(data[offset]) << 8) | data[offset + 1]);
if (syncword != kEac3Syncword) return 0;
const std::size_t base = offset * 8u;
const std::uint32_t bsid = read_bits(data, base + 40u, 5u);
if (bsid <= 8u) {
const std::uint32_t fscod = read_bits(data, base + 32u, 2u);
const std::uint32_t frmsizecod = read_bits(data, base + 34u, 6u);
if (fscod > 2u || frmsizecod >= 38u) return 0;
if (out != nullptr) {
out->frame_bytes = static_cast<std::size_t>(kAc3FrameWords[fscod][frmsizecod]) * 2u;
out->offset = offset;
out->codec = 0;
out->strmtyp = 0;
out->substreamid = 0;
}
return static_cast<std::size_t>(kAc3FrameWords[fscod][frmsizecod]) * 2u;
}
const std::size_t words =
(static_cast<std::size_t>(data[offset + 2] & 0x07u) << 8) | data[offset + 3];
if (out != nullptr) {
out->frame_bytes = (words + 1u) * 2u;
out->offset = offset;
out->codec = 1;
out->strmtyp = static_cast<std::uint8_t>(read_bits(data, base + 16u, 2u));
out->substreamid = static_cast<std::uint8_t>(read_bits(data, base + 18u, 3u));
}
return (words + 1u) * 2u;
}
std::size_t frame_bytes_at(const std::uint8_t* data, std::size_t size, std::size_t offset) {
return frame_header_at(data, size, offset, nullptr);
}
std::size_t audio_frame_bytes_at(const std::uint8_t* data, std::size_t size, std::size_t offset,
bool end_of_stream) {
constexpr std::size_t kMaxSubstreams = 8;
FrameHeader seen[kMaxSubstreams];
std::size_t count = 0;
std::size_t consumed = 0;
while (count < kMaxSubstreams) {
FrameHeader header;
const std::size_t bytes = frame_header_at(data, size, offset + consumed, &header);
if (bytes == 0 || offset + consumed + bytes > size) break;
bool repeats = false;
for (std::size_t index = 0; index < count; ++index) {
if (seen[index].same_stream(header)) {
repeats = true;
break;
}
}
if (repeats) return consumed;
seen[count++] = header;
consumed += bytes;
}
if (count != 0u && consumed != 0u && end_of_stream) return consumed;
return 0;
}
bool joc_config_idx(const std::uint8_t* frame, std::size_t frame_bytes, unsigned* out) {
if (out == nullptr || frame == nullptr || frame_bytes < 8u) return false;
std::size_t offsets[4096];
std::size_t count = 0;
marker_offsets(frame, frame_bytes, offsets, 4096, &count);
for (std::size_t i = 0; i < count; ++i) {
Container candidate;
if (!parse_container(frame, frame_bytes * 8u, offsets[i], &candidate)) continue;
if (!candidate.has(kIdOamd) || !candidate.has(kIdJoc)) continue;
for (std::size_t p = 0; p < candidate.payload_count; ++p) {
if (candidate.payloads[p].id != kIdJoc) continue;
// joc_dmx_config_idx is the first 3 bits of the JOC payload, followed by
// joc_num_objects_bits (6) and joc_ext_config_idx (3).
const std::size_t bit = candidate.payloads[p].bit_offset;
std::uint32_t value = 0;
for (unsigned index = 0; index < 3u; ++index) {
const std::size_t position = bit + index;
if (position / 8u >= frame_bytes) return false;
value = (value << 1) | ((frame[position / 8u] >> (7u - (position % 8u))) & 1u);
}
*out = value;
return true;
}
}
return false;
}
bool frame_has_joc(const std::uint8_t* frame, std::size_t frame_bytes) {
if (frame == nullptr || frame_bytes < 8u) return false;
@@ -333,12 +437,15 @@ ScanResult scan(const std::uint8_t* data, std::size_t size, std::size_t max_fram
if (frames == 0) {
result.joc = JocState::kUnknown;
if (result.detail[0] == '\0') result.detail = "no syncframes";
} else if (with_joc == frames) {
} else if (with_joc != 0) {
result.joc = JocState::kYes;
result.detail = "every examined syncframe carries the JOC EMDF container";
result.detail = (with_joc == frames)
? "every examined syncframe carries the JOC EMDF container"
: "the JOC EMDF container is present in part of the examined "
"audio frames (dependent substream or a late first frame)";
} else {
result.joc = JocState::kNo;
result.detail = "at least one examined syncframe has no JOC EMDF container";
result.detail = "no examined syncframe carries a JOC EMDF container";
}
return result;
}
+43 -11
View File
@@ -4,12 +4,14 @@
// because container metadata (MP4 dec3, Matroska A_EAC3) says only "E-AC-3" and
// the JOC flag inside it is frequently missing.
//
// The criterion implemented here is deliberately the same one the rendering core
// applies before it will render a frame: a syncframe carries JOC when it holds
// exactly one top-level EMDF container (syncword 0x5838, any of the eight bit
// alignments) whose payload list contains both ID11 (OAMD) and ID14 (JOC).
// Agreeing with the core matters: a looser test would claim files the core then
// refuses, which is worse than declining them.
// A syncframe carries JOC when it holds exactly one top-level EMDF container
// (syncword 0x5838, any of the eight bit alignments) whose payload list contains
// both ID11 (OAMD) and ID14 (JOC) — the same per-frame test the rendering core
// applies. The stream counts as JOC when at least one examined audio frame
// carries one: in a 7-channel program the JOC payload lives in the dependent
// substream while the independent substream is a plain 5.1 core, and an AC-3
// core may precede it, so "every syncframe carries JOC" is not a valid rule.
// The first audio frame may also carry no metadata at all.
#pragma once
#include <cstddef>
@@ -17,16 +19,26 @@
namespace joc_eac3 {
// E-AC-3 syncframe header fields the plugin needs.
// Syncframe header fields the plugin needs. codec/strmtyp/substreamid identify
// the substream: within one audio frame each combination appears once, which is
// what turns a syncframe stream into audio frames.
struct FrameHeader {
std::size_t frame_bytes = 0;
std::size_t offset = 0;
std::uint8_t codec = 0; // 0 = AC-3, 1 = E-AC-3
std::uint8_t strmtyp = 0;
std::uint8_t substreamid = 0;
bool same_stream(const FrameHeader& other) const {
return codec == other.codec && strmtyp == other.strmtyp &&
substreamid == other.substreamid;
}
};
enum class JocState {
kYes, // every frame examined carried a JOC EMDF container
kNo, // at least one frame examined did not
kUnknown, // not enough data, or the stream is not walkable E-AC-3
kYes, // at least one examined syncframe carried a JOC EMDF container
kNo, // no examined syncframe carried one
kUnknown, // not enough data, or the stream is not walkable ac3/eac3
};
struct ScanResult {
@@ -42,9 +54,29 @@ struct ScanResult {
ScanResult scan(const std::uint8_t* data, std::size_t size, std::size_t max_frames);
// Length of the syncframe starting at data[offset], or 0 when there is no valid
// header there. Mirrors the core's frmsiz handling exactly.
// header there. AC-3 and E-AC-3 are told apart by bsid exactly as the core does:
// bsid <= 8 sizes the frame from fscod/frmsizecod, anything above uses frmsiz.
std::size_t frame_bytes_at(const std::uint8_t* data, std::size_t size, std::size_t offset);
// Same, and fills the substream identity. Returns 0 when no header is there.
std::size_t frame_header_at(const std::uint8_t* data, std::size_t size, std::size_t offset,
FrameHeader* out);
// Length of the whole audio frame starting at data[offset]: every syncframe up to
// (and excluding) the first repeated (codec, strmtyp, substreamid) combination.
// A 7-channel program interleaves an independent and a dependent substream, so one
// audio frame is two syncframes and one bed frame.
//
// Returns 0 when the group is still open inside the buffer -- the caller has to ask
// again with more data -- unless `end_of_stream` says no more bytes will arrive, in
// which case the trailing group is complete by definition.
std::size_t audio_frame_bytes_at(const std::uint8_t* data, std::size_t size, std::size_t offset,
bool end_of_stream);
// Reads joc_dmx_config_idx (the first 3 bits of the JOC payload) out of one
// syncframe. False when the frame carries no JOC payload.
bool joc_config_idx(const std::uint8_t* frame, std::size_t frame_bytes, unsigned* out);
// True when this single syncframe carries the JOC EMDF container.
bool frame_has_joc(const std::uint8_t* frame, std::size_t frame_bytes);
+327 -40
View File
@@ -17,6 +17,9 @@
#include <SDK/input_impl.h>
#include <SDK/tag_processor.h>
#include <atomic>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <string>
@@ -24,6 +27,7 @@
#include "eac3_scan.h"
#include "joc_decode.h"
#include "log.h"
#include "pcm_source.h"
#include "prefs.h"
#include "settings.h"
@@ -33,6 +37,22 @@ constexpr std::size_t kSniffBytes = 256u * 1024u;
constexpr std::size_t kRunFrames = 4096u;
constexpr unsigned kSampleRate = 48000;
// Formats the PCM takeover owns. Containers are deliberately absent: MP4/M4A
// may carry a JOC track, so those still go through the E-AC-3/JOC probe first.
bool is_pcm_takeover_extension(const char* extension) {
static const char* const kExtensions[] = {
// Decode to PCM; the kernel then maps 2.0/5.1/7.1. TrueHD/MLP is
// included too, but an Atmos TrueHD stream loses its objects when ffmpeg
// decodes it to PCM. DSD (DSF/DFF) is deliberately absent.
"wav", "flac", "mp3", "aac", "ogg", "opus", "wma", "aif", "aiff",
"ac3", "dts", "dtshd", "dtsma", "wv", "ape", "tta", "mpc", "au",
"snd", "caf", "thd", "mlp", "truehd"};
for (const char* candidate : kExtensions) {
if (extension != nullptr && stricmp_utf8(extension, candidate) == 0) return true;
}
return false;
}
// Largest magnitude in a block, for the delivery check in decode_run().
template <typename Sample>
double peak_of(const Sample* values, std::size_t count) {
@@ -66,6 +86,31 @@ std::string file_name_of(const std::string& path) {
return slash == std::string::npos ? path : path.substr(slash + 1);
}
// A library scan opens every container in the library through open(), and all but
// a few of them are declined because their audio is not E-AC-3 JOC. The per-file
// lines are what makes a scan diagnosable -- "the file that should have been
// claimed was not, and here is why" -- but a large library is hundreds of
// thousands of them, so a running summary is logged as well. It is short enough
// to survive the log rolling over, which is what a scan of that size makes it do.
constexpr unsigned kDeclineSummaryEvery = 1000;
std::atomic<unsigned> g_declined{0};
std::atomic<unsigned> g_claimed{0};
// One place for "this file is not ours". The message stays the caller's, so a
// decline that failed rather than decided still reads as one.
void decline(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
joc_log::line_v(fmt, args);
va_end(args);
const unsigned count = g_declined.fetch_add(1, std::memory_order_relaxed) + 1;
if ((count % kDeclineSummaryEvery) == 0u) {
joc_log::line("scan: %u file(s) declined, %u claimed so far", count,
g_claimed.load(std::memory_order_relaxed));
}
}
// ---------------------------------------------------------------------------
// Tags of a file this component has taken over.
//
@@ -169,6 +214,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 {
public:
void open(service_ptr_t<file> hint, const char* path, t_input_open_reason reason,
@@ -200,19 +263,28 @@ public:
try {
m_native_path = filesystem::g_get_native_path(m_path.c_str());
} catch (const pfc::exception& error) {
joc_log::line("decoder: not a native file path (%s): %s", m_path.c_str(),
error.what());
decline("decoder: not a native file path (%s): %s", m_path.c_str(), error.what());
throw exception_io_unsupported_format();
}
const char* extension = std::strrchr(m_native_path.get_ptr(), '.');
extension = (extension != nullptr) ? extension + 1 : "";
const joc_decode::Settings current = joc_settings::current();
joc_log::line("decoder: PCM takeover=%s, extension=%s",
current.take_over_pcm ? "on" : "off",
extension != nullptr ? extension : "");
if (current.take_over_pcm && is_pcm_takeover_extension(extension)) {
open_pcm(current, abort);
return;
}
if (joc_container::is_container_extension(extension)) {
open_container(extension);
open_container(extension, abort);
} else {
open_bare(abort);
}
if (m_pcm_mode) return;
// Whatever else happens, the tags of this file are read by the component
// that owns its format; failing to find one is not fatal, the technical
@@ -226,10 +298,49 @@ public:
}
}
// A non-JOC E-AC-3 input (bare or in a container) can still be rendered:
// ffmpeg decodes it to 48 kHz float32 and the kernel's PCM_LAYOUT input maps
// the channels. JOC always wins; this only runs after the JOC probe said no.
void open_pcm_fallback(abort_callback& abort, unsigned audio_index,
const char* reason) {
joc_decode::Settings settings = joc_settings::current();
if (!settings.take_over_pcm) {
decline("decoder: yielding to the built-in decoder (%s)", reason);
throw exception_io_unsupported_format();
}
joc_log::line("decoder: no JOC (%s); routing audio track %u through ffmpeg",
reason, audio_index);
settings.audio_index = audio_index;
settings.take_over_pcm = true;
open_pcm(settings, abort);
}
// A bare stream is either read from the file or handed back. One thing has to
// happen first: a tag area in front of the syncframes is not part of the
// stream, and treating it as one would hand the file to the built-in decoder,
// which plays it without the Atmos objects.
// Ordinary PCM: ffmpeg is the only decoder. The kernel's PCM_LAYOUT stream
// maps 2.0/5.1/7.1 to fixed objects and renders binaural; this component does
// not hand the file to any other decoder.
void open_pcm(const joc_decode::Settings& settings, abort_callback& abort) {
std::string error;
if (!m_pcm.open(m_native_path.get_ptr(), settings, &error)) {
decline("decoder: PCM takeover could not decode the file (%s)", error.c_str());
throw exception_io_unsupported_format();
}
m_pcm_mode = true;
m_length = m_pcm.length_seconds();
m_channels = 2;
m_channel_config = channel_map_for(m_channels);
g_claimed.fetch_add(1, std::memory_order_relaxed);
joc_log::line("decoder: claiming PCM source via ffmpeg (%.3f s, binaural)",
m_length);
if (!open_forwarded(m_forward_reader, input_info_reader::class_guid,
m_path.c_str(), abort, &m_forward_name)) {
joc_log::line("decoder: no other component reads this file's tags");
}
}
void open_bare(abort_callback& abort) {
m_stream_start = leading_tag_bytes(m_file, abort);
if (m_stream_start != 0) {
@@ -248,11 +359,11 @@ public:
static_cast<unsigned long long>(scan.frames_with_joc));
if (scan.joc != joc_eac3::JocState::kYes) {
// Hand the file to the next entry in the priority table.
joc_log::line("decoder: yielding to the built-in decoder (%s)", scan.detail);
throw exception_io_unsupported_format();
open_pcm_fallback(abort, 0, scan.detail);
return;
}
joc_log::line("decoder: claiming this file as E-AC-3 JOC (bare stream)");
g_claimed.fetch_add(1, std::memory_order_relaxed);
m_input_kind = joc_decode::InputKind::kBare;
}
@@ -260,11 +371,17 @@ public:
// the container's own headers, so a library scan pays nothing for the MP4s that
// hold AAC), and does that track carry JOC (answered from a copied prefix of
// the track). Either "no" hands the file to the next decoder in the table.
void open_container(const char* extension) {
void open_container(const char* extension, abort_callback& abort) {
m_container = joc_container::scan(m_native_path.get_ptr());
if (!m_container.eac3) {
joc_log::line("decoder: yielding to the built-in decoder (%s)",
m_container.detail.c_str());
const joc_decode::Settings settings = joc_settings::current();
if (settings.take_over_pcm) {
open_pcm_fallback(abort, m_container.audio_index,
m_container.detail.c_str());
return;
}
decline("decoder: yielding to the built-in decoder (%s)",
m_container.detail.c_str());
throw exception_io_unsupported_format();
}
@@ -273,20 +390,22 @@ public:
std::string detail;
if (!joc_decode::probe_container_joc(settings.ffmpeg_path, m_native_path.get_ptr(),
m_container.audio_index, &joc, &detail)) {
joc_log::line("decoder: cannot examine the E-AC-3 track (%s); yielding",
detail.c_str());
if (settings.take_over_pcm) {
open_pcm_fallback(abort, m_container.audio_index, detail.c_str());
return;
}
decline("decoder: cannot examine the E-AC-3 track (%s); yielding", detail.c_str());
throw exception_io_unsupported_format();
}
if (!joc) {
joc_log::line("decoder: yielding to the built-in decoder (E-AC-3 track %u carries "
"no JOC: %s)",
m_container.audio_index, detail.c_str());
throw exception_io_unsupported_format();
open_pcm_fallback(abort, m_container.audio_index, detail.c_str());
return;
}
joc_log::line("decoder: claiming this file as E-AC-3 JOC (%s, audio track %u, .%s)",
joc_container::kind_name(m_container.kind), m_container.audio_index,
extension);
g_claimed.fetch_add(1, std::memory_order_relaxed);
m_input_kind = joc_decode::InputKind::kContainer;
m_audio_index = m_container.audio_index;
}
@@ -302,6 +421,32 @@ public:
throw exception_tagging_unsupported();
}
if (m_pcm_mode) {
const joc_decode::Settings settings = joc_settings::current();
info.info_set("codec", "PCM");
info.info_set("codec_long", "PCM via ffmpeg (JOC binaural takeover)");
info.info_set_int("samplerate", kSampleRate);
info.info_set_channels_ex(2, channel_map_for(2));
info.info_set_bitspersample(32u, true);
info.set_length(m_length);
info.info_set("joc_render", "binaural (PCM takeover)");
info.info_set("joc_hrtf", settings.hrtf_file.empty()
? "(未设置)"
: file_name_of(settings.hrtf_file).c_str());
if (m_forward_reader.is_valid()) {
try {
file_info_impl tags;
m_forward_reader->get_info(0, tags, abort);
info.copy_meta(tags);
} catch (const pfc::exception& error) {
joc_log::line("decoder: reading this file's own tags failed: %s",
error.what());
}
}
joc_log::line("decoder: get_info PCM takeover duration=%.3f s", m_length);
return;
}
const joc_decode::FileProbe probe =
joc_decode::probe_file(m_native_path.get_ptr(), 0, m_stream_start);
const joc_decode::Settings settings = joc_settings::current();
@@ -327,14 +472,26 @@ public:
channels = layout_channels != 0 ? layout_channels : 6;
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
// is the one thing about the output that a listener cannot hear.
if (settings.force_int24) render += ", 24-bit delivery";
info.info_set("codec", "E-AC-3 JOC");
info.info_set("codec_long", "E-AC-3 JOC (Dolby Atmos)");
info.info_set("encoding", "lossy");
info.info_set_int("samplerate", kSampleRate);
info.info_set_int("channels", channels);
info.info_set_int("bitspersample", 32);
info.info_set("bitspersample_extra", "floating-point");
// 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
// file from this stream: float32 by default, int24 when forced. This is also
// what foobar2000's own lossless-conversion warning reads
// (SDK file_info.cpp:is_encoding_float), so it has to use the SDK's convention:
// 32 bits with "floating-point", or a bit depth that is fixed-point by
// definition (anything but 32/64, with no extra field at all).
info.info_set_bitspersample(settings.force_int24 ? 24u : 32u, !settings.force_int24);
info.set_length(duration);
m_length = duration;
// The renderer keeps its room tail, but the stream this component hands over
@@ -389,8 +546,10 @@ public:
read_local_tags(m_file, info, abort);
}
joc_log::line("decoder: get_info duration=%.3f s frames=%llu channels=%u render=%s%s",
duration, static_cast<unsigned long long>(frames), channels, render.c_str(),
joc_log::line("decoder: get_info duration=%.3f s frames=%llu channels=%u mask=%s "
"render=%s%s",
duration, static_cast<unsigned long long>(frames), channels,
mask_text(mask).c_str(), render.c_str(),
container ? " (container)" : "");
}
@@ -402,6 +561,19 @@ public:
void decode_initialize(unsigned flags, abort_callback& abort) {
(void)abort;
if (m_pcm_mode) {
m_settings = joc_settings::current();
m_channels = 2;
m_channel_config = channel_map_for(m_channels);
m_buffer.resize(kRunFrames * m_channels);
m_frames_delivered = 0;
m_reported = false;
m_delivery_mismatches = 0;
m_clipped_samples = 0;
m_clip_reported = false;
joc_log::line("decoder: PCM takeover ready (binaural, ffmpeg only)");
return;
}
m_settings = joc_settings::current();
m_settings.input_kind = m_input_kind;
m_settings.audio_index = m_audio_index;
@@ -413,28 +585,74 @@ public:
std::string error;
if (!m_engine.start(m_native_path.get_ptr(), m_settings, &error)) {
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.
if (m_settings.output == joc_decode::Output::kBinaural &&
m_settings.hrtf_file.empty()) {
throw exception_io_data(
"JOC:双耳渲染需要先指定 HRTF 文件(Preferences -> Tools -> JOC 解码器),"
"或把输出改为扬声器布局。");
}
throw exception_io_data(error.c_str());
// The message the user sees is in the page's language; the engine's own
// line stays English and follows it, because it names the file or the
// stream the failure came from.
const joc_lang::Language language =
joc_lang::resolve(joc_settings::read().language);
std::string message = joc_lang::get(
language, m_settings.output == joc_decode::Output::kBinaural
? 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();
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_frames_delivered = 0;
m_reported = false;
m_delivery_mismatches = 0;
joc_log::line("decoder: engine ready, %u output channel(s), %u frames per read",
m_channels, static_cast<unsigned>(kRunFrames));
// The clip total belongs to the file rather than to one run of it, so a seek
// does not clear it: the log line at the end of the stream is a statement
// about everything this component handed over.
m_clipped_samples = 0;
m_clip_reported = false;
joc_log::line("decoder: engine ready, %u output channel(s), mask=%s, %u frames per "
"read, delivery=%s",
m_channels, mask_text(m_channel_config).c_str(),
static_cast<unsigned>(kRunFrames),
m_settings.force_int24 ? "int24" : "float32");
}
bool decode_run(audio_chunk& chunk, abort_callback& abort) {
(void)abort;
std::string error;
if (m_pcm_mode) {
const std::size_t pcm_frames = m_pcm.read(m_buffer.data(), kRunFrames, &error);
if (pcm_frames == 0) {
if (!error.empty()) {
joc_log::line("decoder: PCM read failed: %s", error.c_str());
throw exception_io_data(error.c_str());
}
return false;
}
chunk.set_data_32(m_buffer.data(), pcm_frames,
audio_chunk::makeSpec(kSampleRate, m_channels,
m_channel_config));
m_frames_delivered += pcm_frames;
if (!m_reported) {
m_reported = true;
joc_log::line("decoder: first %llu PCM frames delivered (binaural)",
static_cast<unsigned long long>(pcm_frames));
}
return true;
}
const std::size_t frames = m_engine.read(m_buffer.data(), kRunFrames, &error);
if (frames == 0) {
if (!error.empty()) {
@@ -445,6 +663,10 @@ public:
static_cast<unsigned long long>(m_frames_delivered),
m_delivery_mismatches == 0 ? ""
: " (the delivery changed samples)");
if (m_clipped_samples != 0) {
joc_log::line("decoder: forced int24 truncated %llu sample(s) in total",
static_cast<unsigned long long>(m_clipped_samples));
}
return false;
}
@@ -452,30 +674,63 @@ public:
// 32-bit builds and double on 64-bit ones (SDK audio_math.h): the samples are
// converted, not copied. set_data_32() is the SDK's conversion for a float32
// source, and it sets the channel count, the sample rate and the sample count.
chunk.set_data_32(m_buffer.data(), frames, m_channels, kSampleRate);
//
// A forced int24 delivery goes the other way: the samples are packed to the
// core's int24 bytes and the host converts them back, so the audio the rest of
// 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
// 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;
if (m_settings.force_int24) {
m_int24.resize(frames * m_channels * 3);
const joc_decode::Int24Block block = joc_decode::pack_int24(
samples, frames * m_channels, m_int24.data());
m_clipped_samples += block.clipped;
if (block.clipped != 0 && !m_clip_reported) {
m_clip_reported = true;
joc_log::line("decoder: forced int24: %llu sample(s) outside [-1,1] in this "
"block are truncated to the edge (the core's clip policy; "
"attenuate with the gain setting to avoid it)",
static_cast<unsigned long long>(block.clipped));
}
chunk.set_data_fixedpoint_signed(m_int24.data(), m_int24.size(), kSampleRate,
m_channels, 24, m_channel_config);
expected_delivered_peak =
static_cast<double>(block.peak) / joc_decode::kInt24ImportScale;
} else {
chunk.set_data_32(samples, frames,
audio_chunk::makeSpec(kSampleRate, m_channels, m_channel_config));
expected_delivered_peak = peak_of(samples, frames * m_channels);
}
m_frames_delivered += frames;
// A delivery that mangled the samples would be heard as noise rather than reported
// as a failure, so every chunk is checked: the conversion is exact, and the peak of
// what the chunk holds has to equal the peak of what the renderer produced.
const double produced = peak_of(m_buffer.data(), frames * m_channels);
// what the chunk holds has to equal the peak of what the renderer produced -- or,
// for int24, the peak the packing step actually wrote.
const double delivered =
peak_of(chunk.get_data(), chunk.get_sample_count() * chunk.get_channels());
if (delivered > produced + 1e-6 + produced * 1e-6 ||
delivered < produced - 1e-6 - produced * 1e-6) {
if (delivered > expected_delivered_peak + 1e-6 + expected_delivered_peak * 1e-6 ||
delivered < expected_delivered_peak - 1e-6 - expected_delivered_peak * 1e-6) {
++m_delivery_mismatches;
if (m_delivery_mismatches == 1) {
joc_log::line("decoder: delivery changed the samples: peak %.9f produced, "
"%.9f delivered",
produced, delivered);
expected_delivered_peak, delivered);
}
}
if (!m_reported) {
m_reported = true;
joc_log::line("decoder: first %llu frames delivered (%u ch), peak %.6f, "
joc_log::line("decoder: first %llu frames delivered (%u ch, %s), peak %.6f, "
"delivered peak %.6f",
static_cast<unsigned long long>(frames), m_channels, produced,
delivered);
static_cast<unsigned long long>(frames), m_channels,
m_settings.force_int24 ? "int24" : "float32",
peak_of(m_buffer.data(), frames * m_channels), delivered);
}
return true;
}
@@ -483,6 +738,19 @@ public:
void decode_seek(double seconds, abort_callback& abort) {
// Walking the syncframe index of a long file is the only part of a seek
// that can take a while, and it polls this.
if (m_pcm_mode) {
std::string error;
if (!m_pcm.seek(seconds, &error)) {
abort.check();
joc_log::line("decoder: PCM seek to %.6f s failed: %s", seconds, error.c_str());
throw exception_io_data(error.c_str());
}
m_frames_delivered = 0;
m_reported = false;
m_delivery_mismatches = 0;
joc_log::line("decoder: PCM seek to %.6f s", seconds);
return;
}
m_engine.set_abort_check([&abort] { return !abort.is_aborting(); });
std::string error;
const bool ok = m_engine.seek(seconds, m_length, &error);
@@ -491,7 +759,12 @@ public:
// An aborted seek reports itself as an abort, not as a decode failure.
abort.check();
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
// that starts here, not to the one that was interrupted.
@@ -543,6 +816,9 @@ public:
// track is commonly wrapped in MP4 or Matroska; the container walk in
// open() is what keeps the other files cheap to decline.
if (joc_container::is_container_extension(extension)) return true;
if (joc_settings::read().take_over_pcm && is_pcm_takeover_extension(extension)) {
return true;
}
return (extension != nullptr) &&
((stricmp_utf8(extension, "eac3") == 0) || (stricmp_utf8(extension, "ec3") == 0));
}
@@ -572,13 +848,24 @@ private:
pfc::string8 m_native_path;
joc_decode::Settings m_settings;
joc_decode::Engine m_engine;
joc_pcm::Source m_pcm;
bool m_pcm_mode = false;
// Set by open(): a bare stream is read directly, an E-AC-3 track inside a
// container is extracted by ffmpeg before it reaches the renderer.
joc_decode::InputKind m_input_kind = joc_decode::InputKind::kBare;
unsigned m_audio_index = 0;
joc_container::Result m_container;
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.
std::vector<std::uint8_t> m_int24;
std::uint64_t m_clipped_samples = 0;
bool m_clip_reported = false;
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;
bool m_reported = false;
// Chunks whose delivered samples did not match what the renderer produced.
+429 -109
View File
@@ -2,10 +2,13 @@
#include <windows.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <limits>
#include <utility>
#include <vector>
// The kernel copy that is compiled into this component; see kernel/.
@@ -14,13 +17,23 @@
#include "eac3_scan.h"
#include "log.h"
#include "win_path.h"
namespace joc_decode {
namespace {
constexpr std::size_t kEac3Chunk = 96u * 1024u; // bytes read per push
// The core renders during the push, so a read queues about as much as it is
// about to consume rather than everything it just read.
constexpr std::uint64_t kEac3FramesPerRead = 3u;
// Rendered audio the caller has not taken yet.
constexpr std::size_t kMaxRenderedAheadSamples = 4096u;
constexpr std::size_t kBedFramesChunk = 8192u; // staging capacity, in frames
constexpr std::size_t kBedChannels = 6; // ffmpeg -ac 6
// The bed channel count follows joc_dmx_config_idx: the 5.1 configurations
// (0 and 3) decode to 6 channels through `ffmpeg -ac 6`, the 7-channel ones
// (1, 2 and 4) to 8 channels in the decoder's own layout. See bed_channels.
constexpr std::size_t kDefaultBedChannels = 6;
constexpr std::size_t kMaxBedChannels = 8;
// A read on an anonymous pipe only completes once the whole request is available,
// so each read asks for a slice ffmpeg can always fill, and the pipe buffer is
// sized well above that slice. Requesting the whole staging buffer deadlocks:
@@ -28,8 +41,102 @@ constexpr std::size_t kBedChannels = 6; // ffmpeg -ac 6
// can ever hold.
constexpr std::size_t kBedReadBytes = 48u * 1024u;
constexpr std::size_t kBedPipeBytes = 1u << 20;
// The open-time JOC scan reads in chunks: a pipe read returns what is available,
// not the whole request, and the first JOC frame can sit past the first chunk.
constexpr std::size_t kScanChunkBytes = 64u * 1024u;
// Cap on the trailing partial frame kept between reads.
constexpr std::size_t kMaxScanWindow = 1u << 20;
constexpr std::size_t kFrameSamples = JOC_FRAME_SAMPLES;
// The decoded bed has to stay on the E-AC-3 frame grid that the JOC matrix and the
// OAMD are indexed by. An mp4/mov edit list trims the decoded audio instead, which
// takes the bed off that grid by however much the list removes -- a Dolby Atmos
// download loses 2432 samples (1.58 frames) -- and every frame's matrix would then be
// applied to audio tens of milliseconds away from it, so a subset of the objects comes
// out attenuated. The demuxer's own option drops the trim; the option exists only on
// the mov/mp4 demuxer, so it is passed for that family alone.
bool has_mov_timeline(const std::string& path) {
static const char* const kExtensions[] = {".mp4", ".m4a", ".m4b", ".m4v",
".mov", ".3gp", ".3g2", ".mj2"};
std::string lowered = path;
for (char& character : lowered) {
if (character >= 'A' && character <= 'Z') {
character = static_cast<char>(character - 'A' + 'a');
}
}
for (const char* extension : kExtensions) {
const std::size_t length = std::strlen(extension);
if (lowered.size() >= length &&
lowered.compare(lowered.size() - length, length, extension) == 0) {
return true;
}
}
return false;
}
// joc_dmx_config_idx of the first syncframe in the window that carries JOC, or -1
// when the window holds none. Only the first three bits of the JOC payload are
// read, so this costs nothing next to a decode.
int scan_config_idx(const std::uint8_t* data, std::size_t size) {
std::size_t offset = 0;
while (offset + 6u <= size) {
const std::size_t bytes = joc_eac3::frame_bytes_at(data, size, offset);
if (bytes == 0 || offset + bytes > size) break;
if (joc_eac3::frame_has_joc(data + offset, bytes)) {
unsigned config = 0;
if (joc_eac3::joc_config_idx(data + offset, bytes, &config)) {
return static_cast<int>(config);
}
}
offset += bytes;
}
return -1;
}
// True when the JOC configuration declares 7 core channels.
bool seven_channel_config(int config) {
return config == 1 || config == 2 || config == 4;
}
// Scans an E-AC-3 stream through `read` until a syncframe carrying the JOC EMDF
// container is seen, and returns its joc_dmx_config_idx. One read is not enough:
// ReadFile returns as soon as some bytes are available (a pipe hands over a
// partial chunk, not the whole request), and an encoder may leave the first
// audio frames without JOC metadata, so the first JOC frame can sit past the
// first read. Returns -1 when the stream ends without one.
template <typename ReadFn>
int scan_config_idx_streaming(ReadFn&& read, std::size_t chunk_bytes) {
std::vector<std::uint8_t> window;
std::vector<std::uint8_t> chunk(chunk_bytes);
while (true) {
const std::size_t got = read(chunk.data(), chunk.size());
if (got == 0) break;
window.insert(window.end(), chunk.begin(),
chunk.begin() + static_cast<std::ptrdiff_t>(got));
std::size_t offset = 0;
while (offset + 6u <= window.size()) {
const std::size_t bytes =
joc_eac3::frame_bytes_at(window.data(), window.size(), offset);
if (bytes == 0 || offset + bytes > window.size()) break;
if (joc_eac3::frame_has_joc(window.data() + offset, bytes)) {
unsigned config = 0;
if (joc_eac3::joc_config_idx(window.data() + offset, bytes, &config)) {
return static_cast<int>(config);
}
}
offset += bytes;
}
// Only the trailing incomplete frame has to survive into the next read;
// the rest was examined above.
if (offset != 0) {
window.erase(window.begin(),
window.begin() + static_cast<std::ptrdiff_t>(offset));
}
if (window.size() > kMaxScanWindow) break;
}
return -1;
}
// ---------------------------------------------------------------------------
// Kernel entry points.
//
@@ -50,20 +157,11 @@ struct CoreApi {
std::uint32_t(JOC_CALL* abi_version)() = joc_abi_version;
const char*(JOC_CALL* version_string)() = joc_version_string;
const char*(JOC_CALL* error_name)(joc_error) = joc_error_name;
const char*(JOC_CALL* last_error_detail)() = joc_last_error_detail;
};
std::wstring utf8_to_wide(const std::string& text) {
if (text.empty()) return {};
const int needed = MultiByteToWideChar(CP_UTF8, 0, text.c_str(),
static_cast<int>(text.size()), nullptr, 0);
std::wstring out(static_cast<std::size_t>(needed), L'\0');
MultiByteToWideChar(CP_UTF8, 0, text.c_str(), static_cast<int>(text.size()), out.data(),
needed);
return out;
}
bool file_exists(const std::string& path) {
const std::wstring wide = utf8_to_wide(path);
const std::wstring wide = joc_path::to_wide_extended(path);
if (wide.empty()) return false;
const DWORD attributes = GetFileAttributesW(wide.c_str());
return attributes != INVALID_FILE_ATTRIBUTES &&
@@ -88,6 +186,22 @@ const char* error_text(const CoreApi& api, joc_error code) {
return "unknown core error";
}
// The core keeps a structured detail for the last failing call ("eac3: chanmap
// declares [Lts,Rts] but joc_dmx_config_idx=2 expects [Vhl,Vhr]"). The plugin
// reports the variant rather than only its error code, so a stream the renderer
// deliberately refuses says why.
std::string error_with_detail(const CoreApi& api, joc_error code) {
std::string text = error_text(api, code);
if (api.last_error_detail != nullptr) {
const char* detail = api.last_error_detail();
if (detail != nullptr && *detail != '\0') {
text += ": ";
text += detail;
}
}
return text;
}
// ---------------------------------------------------------------------------
// ffmpeg child process producing the 5.1 core PCM on a pipe.
// ---------------------------------------------------------------------------
@@ -121,11 +235,11 @@ public:
FILE_SHARE_READ | FILE_SHARE_WRITE, &attributes,
CREATE_ALWAYS, 0, nullptr);
std::wstring command = L"\"" + utf8_to_wide(ffmpeg_path) + L"\"";
std::wstring command = L"\"" + joc_path::to_wide_extended(ffmpeg_path) + L"\"";
command += L" -hide_banner -loglevel error -nostdin -y ";
command += input_arguments; // input options must precede -i
command += L" -i \"";
command += utf8_to_wide(input_path);
command += joc_path::to_wide_extended(input_path);
command += L"\" ";
command += output_arguments;
@@ -197,7 +311,7 @@ class InputFile {
public:
~InputFile() { close(); }
bool open(const std::string& path) {
handle_ = CreateFileW(utf8_to_wide(path).c_str(), GENERIC_READ,
handle_ = CreateFileW(joc_path::to_wide_extended(path).c_str(), GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
return handle_ != INVALID_HANDLE_VALUE;
@@ -233,10 +347,45 @@ private:
HANDLE handle_ = INVALID_HANDLE_VALUE;
};
const char* const kLayouts[] = {"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"};
const unsigned kLayoutChannels[] = {2, 3, 4, 4, 5, 6, 8, 10, 7, 7, 8, 10, 12, 14, 16, 24};
// The layouts the core accepts, with the channels in the order the renderer
// emits them. `speakers` are the reference table's names for those channels;
// the kernel is the authority on the list and on the channel counts, and
// 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"}},
{"6.0", 6, {"L", "R", "Ls", "Rs", "Lrs", "Rrs"}},
};
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
// whatever working directory the host process happens to have; separate files so
@@ -275,16 +424,86 @@ std::int64_t sample_of_seconds(double seconds) {
} // namespace
const char* const* speaker_layouts(std::size_t* count) {
if (count != nullptr) *count = sizeof(kLayouts) / sizeof(kLayouts[0]);
const LayoutSpec* layout_table(std::size_t* count) {
if (count != nullptr) *count = kLayoutCount;
return kLayouts;
}
unsigned speaker_channels(const std::string& layout) {
for (std::size_t i = 0; i < sizeof(kLayouts) / sizeof(kLayouts[0]); ++i) {
if (layout == kLayouts[i]) return kLayoutChannels[i];
const LayoutSpec* spec = find_layout(layout);
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 0;
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]);
}
}
namespace {
// The core's conversion, reproduced: kernel/src/io/wav_writer.cpp:to_int32.
// (min)() is written that way because the test tools compile this file without
// NOMINMAX, and windows.h's min macro would otherwise swallow the call.
std::int32_t to_int32(const float value) {
if (!std::isfinite(value)) {
return (std::numeric_limits<std::int32_t>::min)();
}
return static_cast<std::int32_t>(value);
}
} // namespace
Int24Block pack_int24(const float* interleaved, std::size_t count, std::uint8_t* out) {
Int24Block block;
for (std::size_t i = 0; i < count; ++i) {
float value = interleaved[i];
if (value > 1.0f) {
value = 1.0f;
++block.clipped;
} else if (value < -1.0f) {
value = -1.0f;
++block.clipped;
}
const std::int32_t scaled = to_int32(value * 8388607.0f);
const std::uint32_t bits = static_cast<std::uint32_t>(scaled);
out[i * 3 + 0] = static_cast<std::uint8_t>(bits & 0xFFu);
out[i * 3 + 1] = static_cast<std::uint8_t>((bits >> 8) & 0xFFu);
out[i * 3 + 2] = static_cast<std::uint8_t>((bits >> 16) & 0xFFu);
// What the host will read back is the sign-extended low 24 bits.
std::int32_t written = static_cast<std::int32_t>(bits & 0xFFFFFFu);
if ((written & 0x800000) != 0) written -= 0x1000000;
const std::int32_t magnitude = (written < 0) ? -written : written;
if (magnitude > block.peak) block.peak = magnitude;
}
return block;
}
std::string component_directory() {
@@ -316,9 +535,7 @@ std::string resolve_hrtf_file(const Settings& settings) {
if (directory.empty()) return {};
// Same convention as the reference CLI next to its executable:
// <base>\HRTF\binaural.sofa or <base>\HRTF\binaural.personalized_headphone.
const char* name = (settings.hrtf_source == HrtfSource::kRosella)
? "binaural.personalized_headphone"
: "binaural.sofa";
const char* name = "binaural.personalized_headphone";
return directory + "\\HRTF\\" + name;
}
@@ -364,40 +581,47 @@ FileProbe probe_file(const std::string& path, std::size_t max_scan_bytes,
return probe;
}
// The renderer pairs one audio frame with exactly 1536 bed samples, so the
// stream length is counted in audio frames: a 7-channel program interleaves an
// independent and a dependent substream, and one audio frame is two syncframes.
const bool whole_file = (buffer.size() == stream_bytes);
std::size_t offset = 0;
std::size_t first_audio_frame = 0;
bool same_audio_frame_size = true;
std::uint64_t seen = 0;
while (true) {
const std::size_t bytes =
joc_eac3::audio_frame_bytes_at(buffer.data(), got, offset, whole_file);
if (bytes == 0 || offset + bytes > got) break;
if (seen == 0) {
first_audio_frame = bytes;
} else if (bytes != first_audio_frame) {
same_audio_frame_size = false;
}
offset += bytes;
++seen;
}
std::uint64_t frames = 0;
if (buffer.size() == stream_bytes) {
std::size_t offset = 0;
while (true) {
const std::size_t bytes = joc_eac3::frame_bytes_at(buffer.data(), got, offset);
if (bytes == 0 || offset + bytes > got) break;
offset += bytes;
++frames;
}
if (whole_file) {
frames = seen;
probe.detail = "frame count walked over the whole file";
} else if (scan.all_frames_same_size) {
frames = stream_bytes / scan.first_frame_bytes;
} else if (seen != 0 && same_audio_frame_size) {
frames = stream_bytes / first_audio_frame;
probe.detail = "frame count extrapolated from a constant frame size";
} else {
} else if (offset != 0) {
// Variable frame size: count in the window and scale by the byte ratio.
std::size_t offset = 0;
std::uint64_t seen = 0;
while (true) {
const std::size_t bytes = joc_eac3::frame_bytes_at(buffer.data(), got, offset);
if (bytes == 0 || offset + bytes > got) break;
offset += bytes;
++seen;
}
frames = (offset != 0) ? static_cast<std::uint64_t>(
(static_cast<double>(stream_bytes) /
static_cast<double>(offset)) *
static_cast<double>(seen))
: 0;
frames = static_cast<std::uint64_t>(
(static_cast<double>(stream_bytes) / static_cast<double>(offset)) *
static_cast<double>(seen));
probe.detail = "frame count estimated from a variable frame size";
}
const int config = scan_config_idx(buffer.data(), got);
probe.frames = frames;
probe.sample_rate = 48000;
probe.channels = 6; // the core audio of an E-AC-3 JOC stream
// Core audio channel count: the 5.1 configurations give 6, the 7-channel ones 8.
probe.channels = static_cast<unsigned>(seven_channel_config(config) ? 8 : 6);
probe.duration_seconds =
static_cast<double>(frames) * static_cast<double>(kFrameSamples) / 48000.0;
return probe;
@@ -422,8 +646,8 @@ bool probe_container_joc(const std::string& ffmpeg_path, const std::string& path
std::uint64_t modified = 0;
{
WIN32_FILE_ATTRIBUTE_DATA data{};
if (GetFileAttributesExW(utf8_to_wide(path).c_str(), GetFileExInfoStandard, &data) !=
FALSE) {
if (GetFileAttributesExW(joc_path::to_wide_extended(path).c_str(), GetFileExInfoStandard,
&data) != FALSE) {
size = (static_cast<std::uint64_t>(data.nFileSizeHigh) << 32) | data.nFileSizeLow;
modified = (static_cast<std::uint64_t>(data.ftLastWriteTime.dwHighDateTime) << 32) |
data.ftLastWriteTime.dwLowDateTime;
@@ -508,7 +732,10 @@ struct Engine::Impl {
}
unsigned channels = 0;
std::uint64_t frames_queued = 0; // E-AC-3 frames handed to the core
// Decoded bed channel count, resolved from joc_dmx_config_idx before the bed
// decoder starts: 6 for configurations 0/3, 8 for 1/2/4.
std::size_t bed_channels = kDefaultBedChannels;
std::uint64_t frames_queued = 0; // audio frames handed to the core
std::uint64_t bed_frames_pushed = 0;
bool eac3_eof = false;
bool bed_eof = false;
@@ -588,6 +815,10 @@ struct Engine::Impl {
bool position_bare(std::uint64_t frame, std::string* error);
bool start_bed(std::uint64_t source_sample, std::string* error);
bool start_metadata(std::string* error);
// Resolves bed_channels from the stream's own joc_dmx_config_idx. For a
// container this starts the metadata pipe once, reads a prefix and stops it
// again; for a bare stream it reads a prefix from the file and seeks back.
bool resolve_bed_channels(std::string* error);
};
bool Engine::Impl::grow_frame_index(std::uint64_t wanted, std::string* error) {
@@ -619,9 +850,14 @@ bool Engine::Impl::grow_frame_index(std::uint64_t wanted, std::string* error) {
index_complete = true;
break;
}
// The index holds audio frames, not syncframes: the renderer consumes one
// bed frame per audio frame, and a 7-channel program makes two syncframes
// into one audio frame.
const bool at_end = (index_file_offset + got >= size);
std::size_t consumed = 0;
while (frame_offsets.size() < wanted) {
const std::size_t bytes = joc_eac3::frame_bytes_at(buffer.data(), got, consumed);
const std::size_t bytes =
joc_eac3::audio_frame_bytes_at(buffer.data(), got, consumed, at_end);
if (bytes == 0 || consumed + bytes > got) break;
frame_offsets.push_back(index_stream_offset + consumed);
consumed += bytes;
@@ -672,12 +908,51 @@ bool Engine::Impl::position_bare(std::uint64_t frame, std::string* error) {
return true;
}
bool Engine::Impl::resolve_bed_channels(std::string* error) {
bed_channels = kDefaultBedChannels;
int config = -1;
if (eac3_from_pipe) {
// The metadata stream has to run once to be sniffed; it is stopped again and
// restarted from the beginning, which costs one extra ffmpeg spawn per track.
if (!start_metadata(error)) return false;
config = scan_config_idx_streaming(
[this](void* data, std::size_t bytes) { return eac3_pipe.read(data, bytes); },
kScanChunkBytes);
eac3_pipe.stop();
} else {
if (!eac3.is_open() && !eac3.open(input_path)) {
if (error != nullptr) *error = "cannot open the input file";
return false;
}
config = scan_config_idx_streaming(
[this](void* data, std::size_t bytes) { return eac3.read(data, bytes); },
kScanChunkBytes);
// Put the file back where the feed loop expects it.
if (!eac3.seek(index_base)) {
if (error != nullptr) *error = "cannot position the input file";
return false;
}
}
bed_channels = seven_channel_config(config)
? static_cast<std::size_t>(7u + 1u)
: kDefaultBedChannels;
if (bed_channels > kMaxBedChannels) bed_channels = kMaxBedChannels;
joc_log::line("core: joc_dmx_config_idx=%d -> %llu bed channel(s)", config,
static_cast<unsigned long long>(bed_channels));
return true;
}
bool Engine::Impl::start_bed(std::uint64_t source_sample, std::string* error) {
// The 5.1 core PCM, exactly as the reference renderer's own core decode does
// it: 5.1 interleaved float32 at 48 kHz, the layout the renderer expects
// (L R C LFE Ls Rs).
// The core PCM the kernel expects: interleaved float32 at 48 kHz, laid out as
// L R C LFE Ls Rs for 5.1 and L R C LFE BL BR SL SR for 7.1.
// -drc_scale 0 -target_level 0: the bed is taken as stored, without the
// stream's dynrng or target-level metadata being applied by the decoder.
// With Dialnorm enabled the 5.1 core is normalized to -31 dBFS; the 7-channel
// configurations keep the stored bed because this switch is specified for 5.1.
//
// -ac is only passed for the 5.1 configurations: `-ac 6` downmixes 5.1.2/7.1
// into 5.1 and drops the extra pair, and `-ac 8` would remap 5.1.2 into 7.1.
// The 7-channel configurations take the decoder's own layout instead.
//
// -ss is an input option: the demuxer is positioned on the frame boundary and
// decoding starts there, so a seek costs the same wherever it lands. The price is
@@ -685,11 +960,20 @@ bool Engine::Impl::start_bed(std::uint64_t source_sample, std::string* error) {
// at the start of the file, which is a low-level, noise-like difference from a
// play-through rather than a misalignment: the position stays exact.
std::wstring input_arguments = L"-drc_scale 0 -target_level 0";
if (settings.dialnorm && bed_channels == kDefaultBedChannels) {
input_arguments = L"-drc_scale 0 -target_level -31";
joc_log::line("core bed: Dolby Dialnorm enabled (-target_level -31)");
}
if (has_mov_timeline(input_path)) input_arguments += L" -ignore_editlist 1";
const std::wstring offset = seek_time(source_sample);
if (!offset.empty()) input_arguments += L" -ss " + offset;
std::wstring bed_arguments = L"-map 0:a:";
bed_arguments += std::to_wstring(settings.audio_index);
bed_arguments += L" -vn -ac 6 -ar 48000 -c:a pcm_f32le -f f32le -";
bed_arguments += L" -vn";
if (bed_channels == kDefaultBedChannels) {
bed_arguments += L" -ac 6";
}
bed_arguments += L" -ar 48000 -c:a pcm_f32le -f f32le -";
return bed.start(settings.ffmpeg_path, input_path, input_arguments, bed_arguments, "bed",
stderr_path_for(L"joc_ffmpeg_bed.log"), error);
}
@@ -741,7 +1025,6 @@ bool Engine::start(const std::string& input_path, const Settings& settings, std:
impl.reset_feed_state();
impl.end_sample = sample_of_seconds(settings.length_seconds);
impl.eac3_buffer.resize(kEac3Chunk);
impl.bed_buffer.resize(kBedFramesChunk * kBedChannels);
if (!load_api(std::string(), &impl.api, error)) return false;
const std::uint32_t abi = impl.api.abi_version();
@@ -771,6 +1054,11 @@ bool Engine::start(const std::string& input_path, const Settings& settings, std:
}
}
// The bed decoder has to know how many channels to produce before it starts,
// and that comes from the stream's own joc_dmx_config_idx.
if (!impl.resolve_bed_channels(error)) return false;
impl.bed_buffer.resize(kBedFramesChunk * impl.bed_channels);
joc_stream_config config{};
config.struct_size = sizeof(config);
config.struct_version = 1;
@@ -794,28 +1082,23 @@ bool Engine::start(const std::string& input_path, const Settings& settings, std:
const std::string& hrtf_file = hrtf_in_use;
if (hrtf_file.empty()) {
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;
}
if (!file_exists(hrtf_file)) {
if (error != nullptr) {
*error = std::string("找不到 HRTF 文件:") + hrtf_file +
(settings.hrtf_file.empty() ? "(默认位置,可在设置页里指定其它路径)"
: "");
*error = "HRTF file not found: " + hrtf_file +
(settings.hrtf_file.empty()
? " (the default location; another file can be named in the "
"preferences page)"
: "");
}
return false;
}
if (settings.hrtf_source == HrtfSource::kRosella) {
config.personalized_headphone_path = hrtf_file.c_str();
} else {
config.hrtf_sofa_path = hrtf_file.c_str();
}
config.personalized_headphone_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.object_delay_samples = settings.object_delay_samples;
config.gain_db = settings.gain_db;
@@ -825,7 +1108,7 @@ bool Engine::start(const std::string& input_path, const Settings& settings, std:
if (created != JOC_OK) {
if (error != nullptr) {
*error = std::string("cannot create the render stream: ") +
error_text(impl.api, created);
error_with_detail(impl.api, created);
}
return false;
}
@@ -902,14 +1185,15 @@ bool Engine::seek(double seconds, double total_seconds, std::string* error) {
impl.delivered = 0;
}
// joc_stream_reset keeps the renderer and its HRTF field: it drops the whole
// timeline, gain ramps, room tail and filter-bank history, which is exactly
// what a restart at another position needs.
// joc_stream_reset keeps the renderer and its HRTF field: it drops the timeline
// state, gain ramps, room tail and filter-bank history, which is exactly what a
// 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);
if (reset != JOC_OK) {
if (error != nullptr) {
*error = std::string("cannot reset the render stream: ") +
error_text(impl.api, reset);
error_with_detail(impl.api, reset);
}
return false;
}
@@ -956,7 +1240,19 @@ std::size_t Engine::read(float* destination, std::size_t frames, std::string* er
impl.eac3_eof = true;
}
if (!impl.eac3_eof && impl.frames_queued <= impl.bed_frames_pushed + 2u &&
// Queue more input only while less than one read's worth is waiting.
std::size_t rendered_ahead = 0;
{
joc_stream_status_info pending{};
pending.struct_size = sizeof(pending);
pending.struct_version = 1;
if (impl.api.status(impl.stream, &pending) == JOC_OK) {
rendered_ahead = static_cast<std::size_t>(pending.buffered_samples);
}
}
if (!impl.eac3_eof && rendered_ahead < kMaxRenderedAheadSamples &&
impl.frames_queued <= impl.bed_frames_pushed + 2u &&
(impl.settings.input_frame_limit == 0 ||
impl.frames_queued < impl.settings.input_frame_limit)) {
// The tail of a chunk is usually the head of the next syncframe. It
@@ -967,6 +1263,10 @@ std::size_t Engine::read(float* destination, std::size_t frames, std::string* er
const std::size_t got = impl.read_eac3(impl.eac3_buffer.data() + impl.eac3_carry,
impl.eac3_buffer.size() - impl.eac3_carry);
std::size_t total = impl.eac3_carry + got;
// A read that returns nothing means no more bytes will arrive, so the
// audio frame still open in the buffer is complete by definition. Without
// this the last audio frame of every file is left in the carry.
const bool at_eof = (got == 0) || impl.eac3_eof;
if (total == 0) {
impl.eac3_eof = true;
} else {
@@ -976,8 +1276,8 @@ std::size_t Engine::read(float* destination, std::size_t frames, std::string* er
if (impl.metadata_skip != 0) {
std::size_t dropped = 0;
while (impl.metadata_skip != 0) {
const std::size_t bytes =
joc_eac3::frame_bytes_at(impl.eac3_buffer.data(), total, dropped);
const std::size_t bytes = joc_eac3::audio_frame_bytes_at(
impl.eac3_buffer.data(), total, dropped, at_eof);
if (bytes == 0 || dropped + bytes > total) break;
dropped += bytes;
--impl.metadata_skip;
@@ -999,32 +1299,34 @@ std::size_t Engine::read(float* destination, std::size_t frames, std::string* er
std::size_t offset = 0;
std::uint64_t complete = 0;
while (true) {
const std::size_t bytes =
joc_eac3::frame_bytes_at(impl.eac3_buffer.data(), total, offset);
const std::size_t bytes = joc_eac3::audio_frame_bytes_at(
impl.eac3_buffer.data(), total, offset, at_eof);
if (bytes == 0 || offset + bytes > total) break;
offset += bytes;
++complete;
}
// With an input limit the chunk is cut at a frame boundary: the
// renderer's output depends on how many frames it was given, so a
// limit that overshoots to the end of the read buffer would not
// reproduce a run that stopped earlier.
std::size_t push_bytes = offset;
std::uint64_t pushed_frames = complete;
// Both cuts land on a frame boundary because the renderer's output
// depends on how many frames it was given: the input limit has to
// stop where it says, and a read queues only its own budget.
std::uint64_t allowed = complete;
if (impl.settings.input_frame_limit != 0) {
const std::uint64_t room =
impl.settings.input_frame_limit - impl.frames_queued;
if (complete > room) {
pushed_frames = room;
std::size_t walk = 0;
for (std::uint64_t index = 0; index < pushed_frames; ++index) {
const std::size_t bytes = joc_eac3::frame_bytes_at(
impl.eac3_buffer.data(), total, walk);
if (bytes == 0 || walk + bytes > total) break;
walk += bytes;
}
push_bytes = walk;
if (allowed > room) allowed = room;
}
if (allowed > kEac3FramesPerRead) allowed = kEac3FramesPerRead;
std::size_t push_bytes = offset;
std::uint64_t pushed_frames = complete;
if (allowed < complete) {
pushed_frames = allowed;
std::size_t walk = 0;
for (std::uint64_t index = 0; index < pushed_frames; ++index) {
const std::size_t bytes = joc_eac3::audio_frame_bytes_at(
impl.eac3_buffer.data(), total, walk, at_eof);
if (bytes == 0 || walk + bytes > total) break;
walk += bytes;
}
push_bytes = walk;
}
joc_stream_buffer input{};
input.struct_size = sizeof(input);
@@ -1036,7 +1338,7 @@ std::size_t Engine::read(float* destination, std::size_t frames, std::string* er
if (pushed != JOC_OK) {
if (error != nullptr) {
*error = std::string("E-AC-3 push failed: ") +
error_text(impl.api, pushed);
error_with_detail(impl.api, pushed);
}
return 0;
}
@@ -1046,7 +1348,9 @@ std::size_t Engine::read(float* destination, std::size_t frames, std::string* er
std::memmove(impl.eac3_buffer.data(), impl.eac3_buffer.data() + push_bytes,
impl.eac3_carry);
}
if (got == 0) impl.eac3_eof = true;
// The pipe can end with complete syncframes still buffered; they
// are queued next, so end of input is only real once none remain.
if (got == 0 && pushed_frames >= complete) impl.eac3_eof = true;
}
}
@@ -1057,27 +1361,27 @@ std::size_t Engine::read(float* destination, std::size_t frames, std::string* er
// return any number of bytes, and rounding a read down to whole samples
// quietly drops the rest of the stream's alignment.
while (!impl.bed_eof && impl.bed_frames_pushed < impl.frames_queued) {
constexpr std::size_t kFrameBytes = kFrameSamples * kBedChannels * sizeof(float);
const std::size_t whole_frames = impl.bed_staged_bytes / kFrameBytes;
const std::size_t frame_bytes = kFrameSamples * impl.bed_channels * sizeof(float);
const std::size_t whole_frames = impl.bed_staged_bytes / frame_bytes;
if (whole_frames != 0) {
joc_stream_buffer input{};
input.struct_size = sizeof(input);
input.struct_version = 1;
input.kind = JOC_STREAM_IN_CORE_PCM;
input.pcm = impl.bed_buffer.data();
input.channels = static_cast<std::uint32_t>(kBedChannels);
input.channels = static_cast<std::uint32_t>(impl.bed_channels);
input.sample_rate = 48000;
input.sample_count = static_cast<std::uint32_t>(whole_frames * kFrameSamples);
const joc_error pushed = impl.api.push(impl.stream, &input, nullptr, nullptr);
if (pushed != JOC_OK) {
if (error != nullptr) {
*error = std::string("core PCM push failed: ") +
error_text(impl.api, pushed);
error_with_detail(impl.api, pushed);
}
return 0;
}
impl.bed_frames_pushed += whole_frames;
const std::size_t pushed_bytes = whole_frames * kFrameBytes;
const std::size_t pushed_bytes = whole_frames * frame_bytes;
impl.bed_staged_bytes -= pushed_bytes;
if (impl.bed_staged_bytes != 0) {
std::memmove(impl.bed_buffer.data(),
@@ -1119,7 +1423,7 @@ std::size_t Engine::read(float* destination, std::size_t frames, std::string* er
const joc_error pulled = impl.api.pull(impl.stream, &output, &produced);
if (pulled != JOC_OK) {
if (error != nullptr) {
*error = std::string("pull failed: ") + error_text(impl.api, pulled);
*error = std::string("pull failed: ") + error_with_detail(impl.api, pulled);
}
return 0;
}
@@ -1169,7 +1473,7 @@ std::size_t Engine::read(float* destination, std::size_t frames, std::string* er
const joc_error flushed = impl.api.flush(impl.stream);
if (flushed != JOC_OK) {
if (error != nullptr) {
*error = std::string("flush failed: ") + error_text(impl.api, flushed);
*error = std::string("flush failed: ") + error_with_detail(impl.api, flushed);
}
return 0;
}
@@ -1188,6 +1492,22 @@ std::size_t Engine::read(float* destination, std::size_t frames, std::string* er
static_cast<unsigned long long>(status.frames_out),
static_cast<unsigned long long>(status.samples_out),
static_cast<unsigned long long>(status.buffered_samples));
// Metadata the renderer had to work around; each one is per audio
// frame and a non-zero count is worth reporting with the rest.
if (status.missing_joc_frames != 0u || status.objects_clamped_frames != 0u ||
status.extra_container_frames != 0u ||
status.chanmap_pair_mismatch_frames != 0u ||
status.bed_mask_mismatch_frames != 0u) {
joc_log::line(
"core: metadata workarounds: missing_joc_frames=%llu "
"objects_clamped_frames=%llu extra_container_frames=%llu "
"chanmap_pair_mismatch_frames=%llu bed_mask_mismatch_frames=%llu",
static_cast<unsigned long long>(status.missing_joc_frames),
static_cast<unsigned long long>(status.objects_clamped_frames),
static_cast<unsigned long long>(status.extra_container_frames),
static_cast<unsigned long long>(status.chanmap_pair_mismatch_frames),
static_cast<unsigned long long>(status.bed_mask_mismatch_frames));
}
joc_log::line("core: bed bytes read=%llu, staged samples left=%llu",
static_cast<unsigned long long>(impl.bed_bytes_read),
static_cast<unsigned long long>(impl.bed_staged_bytes));
+96 -23
View File
@@ -4,17 +4,14 @@
// drives when the output has to be compared byte for byte against joc_cli.
//
// Two inputs are needed to render, and they come from different places:
// * the bare E-AC-3 syncframes -- the metadata stream -- read straight from the
// file, since the plugin only claims bare .eac3/.ec3 today;
// * the E-AC-3 syncframes -- the metadata stream -- read straight from the file;
// * the 5.1 core PCM of those same frames -- the rendering core does not decode
// the core (it has no AC-3 decoder at all), so ffmpeg produces it exactly the
// way the reference CLI does.
// the core (it has no AC-3 decoder at all), so ffmpeg produces it.
//
// The core is loaded from joc_core.dll through the public C ABI and called via
// function pointers. Static linking is not an option: the core's static library
// carries the internals but not the API layer in src/api, and the plugin is not
// allowed to compile core sources. Loading explicitly also lets the component
// ship its own copy of the DLL and check its ABI version at start-up.
// The core is the C++ kernel under kernel/, compiled into this component and called
// through its public C API via the CoreApi table. No DLL is shipped or loaded: the
// table is filled with the linked entry points and start-up only checks the ABI
// version.
#pragma once
#include <cstddef>
@@ -47,13 +44,6 @@ enum class Output {
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
// file; inside a container the track has to be extracted first (ffmpeg, stream copy).
enum class InputKind {
@@ -67,12 +57,8 @@ struct Settings {
// Which of the container's audio tracks holds the E-AC-3 stream, 0-based.
unsigned audio_index = 0;
std::string speaker_layout = "7.1";
HrtfSource hrtf_source = HrtfSource::kSofa;
// Empty means the default file in the default folder, see resolve_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
double gain_db = 0.0;
double tail_seconds = 5.0;
@@ -96,12 +82,80 @@ struct Settings {
// is what the reference CLI's --duration does. Zero means "the whole file".
// Only the comparison harness sets it; playback leaves it at zero.
std::uint64_t input_frame_limit = 0;
// Deliver 24-bit fixed-point PCM instead of float32. The renderer itself is
// always float32 and this does not change it: the flag says how the *caller*
// hands the samples on, and the quantisation happens once, where the format is
// decided (see pack_int24 below). It exists because the streaming interface
// has no int24 output -- the core's int24 rule lives in its file-writing path
// (kernel/src/io/wav_writer.cpp), which the component cannot reach, so the
// rule is reproduced here instead. Out-of-range samples follow the core's
// JOC_CLIP_CONTINUE policy: truncated to the edge, and reported.
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;
// ffmpeg is the sole decoder for this input; the kernel maps the channels.
bool take_over_pcm = false;
// Apply Dolby Dialnorm to the ffmpeg E-AC-3 5.1 core decode.
bool dialnorm = 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
// layouts the core accepts.
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
// <that directory>\HRTF, the same place the reference CLI looks next to its exe.
std::string component_directory();
@@ -111,9 +165,6 @@ std::string component_directory();
// component directory cannot be determined.
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.
struct FileProbe {
bool readable = false;
@@ -139,6 +190,28 @@ FileProbe probe_file(const std::string& path, std::size_t max_scan_bytes = 0,
bool probe_container_joc(const std::string& ffmpeg_path, const std::string& path,
unsigned audio_index, bool* joc, std::string* detail);
// ---- forced int24 delivery ------------------------------------------------
//
// The core's own int24 rule, reproduced byte for byte from
// kernel/src/io/wav_writer.cpp: clip to [-1, 1], multiply by 8388607, truncate
// toward zero (the core's comment: the int32 conversion is "identical to NumPy's
// float32 -> int32 cast after clipping"), write the low three bytes, little
// endian; a non-finite sample becomes 0, exactly as the core writes it.
//
// Sample values that have been through this are what foobar2000's int24 import
// gives back, i.e. n / 2^23 (SDK/pfc audio_math.cpp:_import24). That is the scale
// a caller should use when it wants to check what the host received.
constexpr double kInt24ImportScale = 8388608.0;
struct Int24Block {
std::size_t clipped = 0; // samples that were outside [-1, 1]
std::int32_t peak = 0; // largest magnitude actually written
};
// Packs `count` interleaved float32 samples into `out`, which must hold
// count * 3 bytes, and reports what the clip caught.
Int24Block pack_int24(const float* interleaved, std::size_t count, std::uint8_t* out);
class Engine {
public:
Engine();
+100
View File
@@ -0,0 +1,100 @@
// 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::kCheckPcm, "接管普通 PCM 源(ffmpeg 解码)", "Take over ordinary PCM (ffmpeg decode)"},
{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.personalized_headphone(Rosella 模型)。",
"Empty means HRTF\\binaural.personalized_headphone (Rosella model) 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 / loudness"},
{Text::kCheckGain, "应用增益", "Apply gain"},
{Text::kCheckDialnorm, "Dolby Dialnorm 响度均衡(-31 dBFS)",
"Dolby Dialnorm loudness (-31 dBFS)"},
{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
+76
View File
@@ -0,0 +1,76 @@
// 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,
kCheckPcm,
kInt24Hint,
kSpeakerStatus,
kGroupHrtf,
kRadioSofa,
kRadioRosella,
kLabelHrtfFile,
kButtonBrowse,
kHrtfHint,
kHrtfSourceSofa,
kHrtfSourceRosella,
kHrtfDefault,
kHrtfDefaultUnknown,
kGroupGain,
kCheckGain,
kCheckDialnorm,
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
+90 -36
View File
@@ -8,6 +8,8 @@
#include <mutex>
#include <string>
#include "win_path.h"
namespace joc_log {
namespace {
@@ -16,12 +18,20 @@ FILE* g_file = nullptr;
bool g_opened = false;
std::string g_path; // UTF-8, for reporting
std::wstring g_wide_path; // for _wfopen
unsigned long long g_lines = 0;
bool g_capped = false;
std::wstring g_wide_rolled; // g_wide_path with the .1 suffix
unsigned long long g_bytes = 0;
// A Media Library scan calls into us for every file; the cap keeps a long
// session from filling the disk, and says so once when it is reached.
constexpr unsigned long long kMaxLines = 500000;
// A Media Library scan calls into us for every file it walks, so the cap has to
// be on bytes: the lines a scan produces run from 40 to 2048 bytes each, and a
// cap on their number leaves the file they build unpredictable by a factor of
// fifty. Sixteen mebibytes per file, one previous file kept, so the component
// never holds more than 32 MiB of log.
constexpr unsigned long long kMaxBytes = 16ull << 20;
// The lines recorded between header_begin() and header_end(): the version
// banner, a handful of lines written once per process.
bool g_recording = false;
std::string g_header;
std::wstring module_directory() {
HMODULE module = nullptr;
@@ -39,32 +49,26 @@ std::wstring module_directory() {
return dir;
}
std::string to_utf8(const std::wstring& text) {
if (text.empty()) return {};
const int needed = WideCharToMultiByte(CP_UTF8, 0, text.c_str(),
static_cast<int>(text.size()), nullptr, 0,
nullptr, nullptr);
std::string out(static_cast<std::string::size_type>(needed), '\0');
WideCharToMultiByte(CP_UTF8, 0, text.c_str(), static_cast<int>(text.size()),
out.data(), needed, nullptr, nullptr);
return out;
}
void open_locked() {
g_opened = true;
wchar_t from_env[4096] = {};
const DWORD env_length = GetEnvironmentVariableW(L"JOC_LOG", from_env,
static_cast<DWORD>(4096));
std::wstring plain;
if (env_length > 0 && env_length < 4096) {
g_wide_path.assign(from_env, env_length);
plain.assign(from_env, env_length);
} else {
const std::wstring dir = module_directory();
if (dir.empty()) return;
g_wide_path = dir + L"\\joc_decoder.log";
plain = dir + L"\\joc_decoder.log";
}
g_path = to_utf8(g_wide_path);
// g_path is the one the component reports and a user reads; the handles work on
// the extended form, because a portable install can sit deeper than MAX_PATH.
g_path = joc_path::to_utf8(plain);
g_wide_path = joc_path::to_wide_extended(plain);
g_wide_rolled = g_wide_path + L".1";
g_file = _wfopen(g_wide_path.c_str(), L"wb");
if (g_file == nullptr) {
g_path.clear();
@@ -74,6 +78,52 @@ void open_locked() {
std::setvbuf(g_file, nullptr, _IONBF, 0);
}
// Composes one line with its timestamp, writes it, and accounts for it. Returns
// the bytes written, 0 when there was nowhere to write them.
unsigned long long write_locked(const char* text) {
if (g_file == nullptr) return 0;
SYSTEMTIME now;
GetLocalTime(&now);
char composed[2100];
const int length =
std::snprintf(composed, sizeof(composed), "%02u:%02u:%02u.%03u [t%05lu] %s\n", now.wHour,
now.wMinute, now.wSecond, now.wMilliseconds,
static_cast<unsigned long>(GetCurrentThreadId()), text);
if (length <= 0) return 0;
// snprintf reports the length it would have needed, which for a truncated
// line is past the end of the buffer.
const std::size_t size = (static_cast<std::size_t>(length) < sizeof(composed))
? static_cast<std::size_t>(length)
: sizeof(composed) - 1;
std::fwrite(composed, 1, size, g_file);
g_bytes += size;
if (g_recording) g_header.append(composed, size);
return size;
}
// Moves the full file aside and starts an empty one. Called with the mutex held,
// once the budget is spent. The banner is written again afterwards, so a log
// that has rolled still opens with the versions it was produced by.
void roll_locked() {
std::fclose(g_file);
g_file = nullptr;
// One previous window, replaced rather than chained: a chain of rolls would
// be the same unbounded log under another name. A move that fails -- the .1
// file held open by a reader -- leaves the truncation below to bound the file
// anyway, at the cost of the window that would have been kept.
MoveFileExW(g_wide_path.c_str(), g_wide_rolled.c_str(), MOVEFILE_REPLACE_EXISTING);
g_file = _wfopen(g_wide_path.c_str(), L"wb");
if (g_file == nullptr) return;
std::setvbuf(g_file, nullptr, _IONBF, 0);
g_bytes = 0;
write_locked("[log rolled: the previous window is in the .1 file beside this one]");
if (!g_header.empty()) {
std::fwrite(g_header.c_str(), 1, g_header.size(), g_file);
g_bytes += g_header.size();
}
}
} // namespace
void open() {
@@ -86,30 +136,34 @@ const char* path() {
return g_path.c_str();
}
void line(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
unsigned long long budget_bytes() { return kMaxBytes; }
void line_v(const char* fmt, va_list args) {
char text[2048];
std::vsnprintf(text, sizeof(text), fmt, args);
va_end(args);
std::lock_guard<std::mutex> guard(g_mutex);
if (!g_opened) open_locked();
if (g_file == nullptr) return;
if (g_lines >= kMaxLines) {
if (!g_capped) {
g_capped = true;
std::fputs("[log capped]\n", g_file);
}
return;
}
++g_lines;
if (write_locked(text) != 0 && g_bytes >= kMaxBytes) roll_locked();
}
SYSTEMTIME now;
GetLocalTime(&now);
std::fprintf(g_file, "%02u:%02u:%02u.%03u [t%05lu] %s\n", now.wHour, now.wMinute,
now.wSecond, now.wMilliseconds,
static_cast<unsigned long>(GetCurrentThreadId()), text);
void line(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
line_v(fmt, args);
va_end(args);
}
void header_begin() {
std::lock_guard<std::mutex> guard(g_mutex);
g_header.clear();
g_recording = true;
}
void header_end() {
std::lock_guard<std::mutex> guard(g_mutex);
g_recording = false;
}
} // namespace joc_log
+25 -2
View File
@@ -4,10 +4,22 @@
// harness and so that it is safe to call from any thread the core queries us on.
//
// Path: %JOC_LOG% if set, otherwise <directory of this DLL>\joc_decoder.log.
// The file is truncated once per process, line-buffered, and every line is
// flushed so the log can be read while foobar2000 is still running.
// The file is truncated once per process, unbuffered, and every line is written
// straight out so the log can be read while foobar2000 is still running.
//
// Size: what is bounded is bytes, not lines. A line is anywhere between 40 and
// 2048 bytes, so a cap on the number of lines leaves the size of the file
// unpredictable by a factor of fifty. A file that reaches budget_bytes() is
// moved to <path>.1 -- replacing any previous roll, so there is never a chain of
// them -- and a fresh one is started. Two files of the budget is therefore the
// most the component ever holds, and the newest lines are always the ones in
// <path>. Lines written between header_begin() and header_end() are written
// again at the top of every window, so a rolled log still says which build
// produced it.
#pragma once
#include <cstdarg>
namespace joc_log {
// Opens (truncating) the log. Called lazily by line(); call it explicitly to
@@ -17,7 +29,18 @@ void open();
// Absolute path of the log file, or "" when it could not be opened.
const char* path();
// Bytes one file holds before it is rolled to <path>.1.
unsigned long long budget_bytes();
// printf-style, thread safe, appends one line.
void line(const char* fmt, ...);
// The va_list form, for a wrapper that forwards its own arguments.
void line_v(const char* fmt, va_list args);
// Remembers the lines written in between and writes them again after every roll.
// Meant for the version banner: a handful of lines, written once.
void header_begin();
void header_end();
} // namespace joc_log
+19 -2
View File
@@ -8,16 +8,18 @@
#include <SDK/componentversion.h>
#include <SDK/coreversion.h>
#include <SDK/initquit.h>
#include "lang.h"
#include "log.h"
#include "settings.h"
// Kept in one place: the string reported to foobar2000 and written to the log
// must not drift apart.
#define JOC_VERSION "0.2.1"
#define JOC_VERSION "0.6.4"
DECLARE_COMPONENT_VERSION("JOC decoder (E-AC-3 JOC)", JOC_VERSION,
"Plays E-AC-3 JOC (Dolby Atmos) files: the JOC objects are "
"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.
VALIDATE_COMPONENT_FILENAME("foo_input_joc.dll");
@@ -30,6 +32,9 @@ class joc_initquit : public initquit {
public:
void on_init() override {
joc_log::open();
// Recorded, so that a log which has rolled still opens with the versions
// it was produced by.
joc_log::header_begin();
joc_log::line("=== foo_input_joc %s ===", JOC_VERSION);
joc_log::line("foobar2000 core : %s", core_version_info::g_get_version_string());
joc_log::line("component file : %s", core_api::get_my_file_name());
@@ -37,6 +42,17 @@ public:
joc_log::line("portable mode : %s",
core_api::is_portable_mode_enabled() ? "yes" : "no");
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::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",
#if defined(_M_IX86)
"x86 (32-bit)"
@@ -46,6 +62,7 @@ public:
"other"
#endif
);
joc_log::header_end();
}
void on_quit() override { joc_log::line("=== foo_input_joc shutdown ==="); }
+371
View File
@@ -0,0 +1,371 @@
#include "pcm_source.h"
#include <windows.h>
#include <algorithm>
#include <atomic>
#include <cstring>
#include <vector>
#include "joc_stream.h"
#include "log.h"
#include "win_path.h"
namespace joc_pcm {
namespace {
constexpr std::size_t kFrameSamples = 1536;
constexpr std::uint32_t kRate = 48000;
std::atomic<std::uint64_t> g_temp_serial{0};
std::uint16_t u16(const unsigned char* data) {
return static_cast<std::uint16_t>(data[0] | (data[1] << 8));
}
std::uint32_t u32(const unsigned char* data) {
return static_cast<std::uint32_t>(data[0]) |
(static_cast<std::uint32_t>(data[1]) << 8) |
(static_cast<std::uint32_t>(data[2]) << 16) |
(static_cast<std::uint32_t>(data[3]) << 24);
}
bool read_exact(std::FILE* file, void* data, std::size_t bytes) {
return std::fread(data, 1, bytes, file) == bytes;
}
std::uint64_t file_size(std::FILE* file) {
const long long current = _ftelli64(file);
_fseeki64(file, 0, SEEK_END);
const long long end = _ftelli64(file);
_fseeki64(file, current, SEEK_SET);
return end < 0 ? 0 : static_cast<std::uint64_t>(end);
}
} // namespace
Source::~Source() { close(); }
bool Source::decode_temp(const std::string& input_path, const std::string& ffmpeg,
unsigned audio_index, std::string* error) {
wchar_t directory[MAX_PATH] = {};
if (GetTempPathW(MAX_PATH, directory) == 0) {
if (error != nullptr) *error = "cannot locate the temp directory";
return false;
}
std::wstring temp = directory;
if (!temp.empty() && temp.back() != L'\\') temp.push_back(L'\\');
temp += L"foo_input_joc_pcm_";
temp += std::to_wstring(GetCurrentProcessId());
temp += L"_";
temp += std::to_wstring(g_temp_serial.fetch_add(1, std::memory_order_relaxed));
temp += L"_";
temp += std::to_wstring(GetTickCount64());
temp += L".wav";
temp_path_ = joc_path::to_utf8(temp.c_str());
DeleteFileW(joc_path::to_wide_extended(temp_path_).c_str());
std::wstring command = L"\"" + joc_path::to_wide_extended(ffmpeg) + L"\"";
command += L" -hide_banner -loglevel error -nostdin -y -i \"";
command += joc_path::to_wide_extended(input_path);
command += L"\" -map 0:a:";
command += std::to_wstring(audio_index);
command += L" -af \"aresample=resampler=soxr:precision=28:osr=48000\" "
L"-c:a pcm_f32le \"";
command += joc_path::to_wide_extended(temp_path_);
command += L"\"";
SECURITY_ATTRIBUTES inheritable{};
inheritable.nLength = sizeof(inheritable);
inheritable.bInheritHandle = TRUE;
HANDLE null_input = CreateFileW(L"NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
&inheritable, OPEN_EXISTING, 0, nullptr);
const std::wstring log_path = joc_path::to_wide_extended(temp_path_ + ".log");
HANDLE log = CreateFileW(log_path.c_str(), GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, &inheritable,
CREATE_ALWAYS, 0, nullptr);
STARTUPINFOW startup{};
startup.cb = sizeof(startup);
startup.dwFlags = STARTF_USESTDHANDLES;
startup.hStdInput = null_input;
startup.hStdOutput = log;
startup.hStdError = (log != INVALID_HANDLE_VALUE) ? log : null_input;
PROCESS_INFORMATION process{};
std::vector<wchar_t> mutable_command(command.begin(), command.end());
mutable_command.push_back(L'\0');
const BOOL created = CreateProcessW(nullptr, mutable_command.data(), nullptr, nullptr,
TRUE, CREATE_NO_WINDOW, nullptr, nullptr, &startup,
&process);
if (null_input != INVALID_HANDLE_VALUE) CloseHandle(null_input);
if (log != INVALID_HANDLE_VALUE) CloseHandle(log);
if (created == FALSE) {
if (error != nullptr) *error = "cannot start ffmpeg";
return false;
}
WaitForSingleObject(process.hProcess, INFINITE);
DWORD exit_code = 1;
GetExitCodeProcess(process.hProcess, &exit_code);
CloseHandle(process.hThread);
CloseHandle(process.hProcess);
if (exit_code != 0) {
WIN32_FILE_ATTRIBUTE_DATA attributes{};
const bool wrote_output =
GetFileAttributesExW(temp.c_str(), GetFileExInfoStandard, &attributes) != FALSE &&
(static_cast<std::uint64_t>(attributes.nFileSizeHigh) << 32 |
attributes.nFileSizeLow) > 44u;
if (!wrote_output) {
std::FILE* log_file = _wfopen(log_path.c_str(), L"rb");
if (log_file != nullptr) {
char line[512];
while (std::fgets(line, sizeof(line), log_file) != nullptr) {
std::printf("ffmpeg: %s", line);
}
std::fclose(log_file);
}
if (error != nullptr) {
*error = "ffmpeg could not decode the PCM source (exit " +
std::to_string(exit_code) + ")";
}
return false;
}
joc_log::line("pcm: ffmpeg exited with %lu but produced the WAV", exit_code);
}
return true;
}
bool Source::parse_wav(const std::string& path, Header* header, std::string* error) {
std::FILE* file = _wfopen(joc_path::to_wide_extended(path).c_str(), L"rb");
if (file == nullptr) {
if (error != nullptr) *error = "cannot open the decoded WAV";
return false;
}
unsigned char riff[12] = {};
if (!read_exact(file, riff, sizeof(riff)) || std::memcmp(riff, "RIFF", 4) != 0 ||
std::memcmp(riff + 8, "WAVE", 4) != 0) {
std::fclose(file);
if (error != nullptr) *error = "ffmpeg did not produce a RIFF/WAVE file";
return false;
}
Header parsed{};
bool have_format = false;
for (;;) {
unsigned char chunk[8] = {};
if (!read_exact(file, chunk, sizeof(chunk))) break;
const std::uint32_t size = u32(chunk + 4);
const std::uint64_t payload = static_cast<std::uint64_t>(_ftelli64(file));
if (std::memcmp(chunk, "fmt ", 4) == 0 && size >= 16u) {
unsigned char fmt[40] = {};
const std::size_t fmt_bytes = std::min<std::size_t>(size, sizeof(fmt));
if (!read_exact(file, fmt, fmt_bytes)) break;
std::uint16_t format = u16(fmt);
parsed.channels = u16(fmt + 2);
parsed.sample_rate = u32(fmt + 4);
parsed.bits = u16(fmt + 14);
if (format == 0xFFFEu && fmt_bytes >= 40u) {
format = u16(fmt + 24); // WAVEFORMATEXTENSIBLE sub-format
}
if (format != 3u || parsed.bits != 32u) {
std::fclose(file);
if (error != nullptr) *error = "decoded WAV is not 32-bit float";
return false;
}
have_format = true;
} else if (std::memcmp(chunk, "data", 4) == 0) {
parsed.data_offset = payload;
parsed.data_bytes = size;
}
_fseeki64(file, static_cast<long long>(payload + size + (size & 1u)), SEEK_SET);
}
const std::uint64_t file_bytes = file_size(file);
std::fclose(file);
if (!have_format || parsed.channels < 2 || parsed.channels > 8 ||
parsed.data_offset == 0) {
if (error != nullptr) *error = "decoded WAV has no usable audio data";
return false;
}
if (parsed.data_bytes == 0u || parsed.data_bytes == 0xFFFFFFFFu ||
parsed.data_offset + parsed.data_bytes > file_bytes) {
parsed.data_bytes = file_bytes - parsed.data_offset;
}
*header = parsed;
return true;
}
bool Source::open(const std::string& input_path, const joc_decode::Settings& settings,
std::string* error) {
close();
if (!decode_temp(input_path, settings.ffmpeg_path, settings.audio_index, error)) return false;
Header header{};
if (!parse_wav(temp_path_, &header, error)) {
close();
return false;
}
if (header.sample_rate != kRate) {
if (error != nullptr) *error = "ffmpeg did not produce 48 kHz audio";
close();
return false;
}
header_ = header;
channels_ = header.channels;
file_ = _wfopen(joc_path::to_wide_extended(temp_path_).c_str(), L"rb");
if (file_ == nullptr) {
if (error != nullptr) *error = "cannot reopen the decoded WAV";
close();
return false;
}
total_frames_ = header.data_bytes / (static_cast<std::uint64_t>(channels_) * 4u);
length_seconds_ = static_cast<double>(total_frames_) / kRate;
feed_.assign(kFrameSamples * static_cast<std::size_t>(channels_), 0.0f);
joc_stream_config config{};
config.struct_size = sizeof(config);
config.struct_version = 1;
config.input = JOC_STREAM_IN_PCM_LAYOUT;
config.output = JOC_STREAM_OUT_BINAURAL;
config.pcm_layout = "auto";
const std::string hrtf = joc_decode::resolve_hrtf_file(settings);
config.personalized_headphone_path = hrtf.c_str();
config.binaural_mode = settings.binaural_mode;
config.binaural_tail_seconds = settings.tail_seconds;
config.object_delay_samples = settings.object_delay_samples;
config.gain_db = settings.gain_db;
config.rosella_filterbank = 1u;
const joc_error created = joc_stream_create(&config, &stream_);
if (created != JOC_OK || stream_ == nullptr) {
if (error != nullptr) *error = "kernel PCM layout stream creation failed";
close();
return false;
}
_fseeki64(file_, static_cast<long long>(header_.data_offset), SEEK_SET);
frames_read_ = 0;
emitted_frames_ = 0;
eof_ = false;
flushed_ = false;
return true;
}
bool Source::push_block(std::string* error) {
if (file_ == nullptr || stream_ == nullptr || eof_) return false;
std::size_t frames = kFrameSamples;
const std::uint64_t remaining = total_frames_ - frames_read_;
if (remaining < frames) frames = static_cast<std::size_t>(remaining);
std::fill(feed_.begin(), feed_.end(), 0.0f);
if (frames != 0u &&
std::fread(feed_.data(), sizeof(float), frames * static_cast<std::size_t>(channels_),
file_) != frames * static_cast<std::size_t>(channels_)) {
if (error != nullptr) *error = "cannot read the decoded WAV";
return false;
}
if (frames != 0u) {
joc_stream_buffer input{};
input.struct_size = sizeof(input);
input.struct_version = 1;
input.kind = JOC_STREAM_IN_PCM_LAYOUT;
input.channels = static_cast<std::uint32_t>(channels_);
input.sample_rate = kRate;
input.sample_count = static_cast<std::uint32_t>(frames);
input.pcm = feed_.data();
std::uint32_t consumed = 0;
std::uint32_t consumed_bytes = 0;
if (joc_stream_push(stream_, &input, &consumed, &consumed_bytes) != JOC_OK) {
if (error != nullptr) *error = "kernel PCM layout push failed";
return false;
}
}
frames_read_ += frames;
if (frames_read_ >= total_frames_ || frames == 0u) eof_ = true;
return true;
}
bool Source::pull(std::size_t frames, float* destination, std::size_t* produced,
std::string* error) {
*produced = 0;
if (stream_ == nullptr || frames == 0u) return true;
joc_stream_buffer output{};
output.struct_size = sizeof(output);
output.struct_version = 1;
output.out_pcm = destination;
output.sample_count = static_cast<std::uint32_t>(frames);
std::uint32_t rendered = 0;
if (joc_stream_pull(stream_, &output, &rendered) != JOC_OK) {
if (error != nullptr) *error = "kernel binaural pull failed";
return false;
}
*produced = rendered;
return true;
}
std::size_t Source::read(float* destination, std::size_t frames, std::string* error) {
if (stream_ == nullptr || destination == nullptr || frames == 0u) return 0;
if (emitted_frames_ >= total_frames_) return 0;
const std::size_t wanted = static_cast<std::size_t>(
std::min<std::uint64_t>(frames, total_frames_ - emitted_frames_));
std::size_t written = 0;
while (written < wanted) {
std::size_t produced = 0;
if (!pull(wanted - written, destination + written * 2u, &produced, error)) {
return written;
}
written += produced;
if (written == wanted) break;
if (!eof_) {
if (!push_block(error)) return written;
continue;
}
if (!flushed_) {
if (joc_stream_flush(stream_) != JOC_OK) {
if (error != nullptr) *error = "kernel flush failed";
return written;
}
flushed_ = true;
continue;
}
break;
}
emitted_frames_ += written;
return written;
}
bool Source::seek(double seconds, std::string* error) {
if (stream_ == nullptr || file_ == nullptr) return false;
if (seconds < 0.0) seconds = 0.0;
std::uint64_t frame = static_cast<std::uint64_t>(seconds * kRate + 0.5);
frame = std::min(frame, total_frames_);
if (joc_stream_reset(stream_) != JOC_OK) {
if (error != nullptr) *error = "kernel reset failed";
return false;
}
_fseeki64(file_, static_cast<long long>(header_.data_offset +
frame * static_cast<std::uint64_t>(channels_) * 4u),
SEEK_SET);
frames_read_ = frame;
emitted_frames_ = frame;
eof_ = frames_read_ >= total_frames_;
flushed_ = false;
return true;
}
void Source::close() {
if (stream_ != nullptr) {
joc_stream_destroy(stream_);
stream_ = nullptr;
}
if (file_ != nullptr) {
std::fclose(file_);
file_ = nullptr;
}
if (!temp_path_.empty()) {
DeleteFileW(joc_path::to_wide_extended(temp_path_).c_str());
DeleteFileW(joc_path::to_wide_extended(temp_path_ + ".log").c_str());
temp_path_.clear();
}
feed_.clear();
frames_read_ = 0;
emitted_frames_ = 0;
total_frames_ = 0;
length_seconds_ = 0.0;
eof_ = false;
flushed_ = false;
channels_ = 0;
}
} // namespace joc_pcm
+69
View File
@@ -0,0 +1,69 @@
// Whole-file PCM takeover for foo_input_joc.
//
// ffmpeg is the only decoder here: it produces a 48 kHz float32 WAV, and the
// kernel's PCM_LAYOUT stream maps 2.0/5.1/7.1 to fixed objects and renders
// binaural. The temp WAV exists so the component can seek without a second
// decoder; it is deleted when the input closes.
#pragma once
#include <cstdint>
#include <cstdio>
#include <string>
#include <vector>
#include "joc_decode.h"
struct joc_stream;
namespace joc_pcm {
class Source {
public:
Source() = default;
~Source();
Source(const Source&) = delete;
Source& operator=(const Source&) = delete;
bool open(const std::string& input_path, const joc_decode::Settings& settings,
std::string* error);
// Fills interleaved stereo float32 frames; returns frames written.
std::size_t read(float* destination, std::size_t frames, std::string* error);
bool seek(double seconds, std::string* error);
void close();
double length_seconds() const { return length_seconds_; }
unsigned channels() const { return 2; }
unsigned sample_rate() const { return 48000; }
bool is_open() const { return stream_ != nullptr; }
private:
struct Header {
std::uint32_t sample_rate = 0;
std::uint16_t channels = 0;
std::uint16_t bits = 0;
std::uint64_t data_offset = 0;
std::uint64_t data_bytes = 0;
};
bool decode_temp(const std::string& input_path, const std::string& ffmpeg,
unsigned audio_index, std::string* error);
bool parse_wav(const std::string& path, Header* header, std::string* error);
bool push_block(std::string* error);
bool pull(std::size_t frames, float* destination, std::size_t* produced,
std::string* error);
std::FILE* file_ = nullptr;
joc_stream* stream_ = nullptr;
Header header_{};
std::string temp_path_;
std::vector<float> feed_;
std::uint64_t frames_read_ = 0;
std::uint64_t emitted_frames_ = 0;
std::uint64_t total_frames_ = 0;
double length_seconds_ = 0.0;
bool eof_ = false;
bool flushed_ = false;
int channels_ = 0;
};
} // namespace joc_pcm
+262 -100
View File
@@ -4,6 +4,11 @@
// 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
// 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>
@@ -16,8 +21,10 @@
#include <cstdio>
#include <string>
#include <vector>
#include "joc_decode.h"
#include "lang.h"
#include "prefs.h"
#include "log.h"
#include "resource.h"
@@ -60,40 +67,80 @@ void set_text(HWND control, const std::string& text) {
SetWindowTextW(control, wide(text).c_str());
}
// Layouts are offered up to 7.1 on purpose: output chains handle eight channels
// comfortably, and wider layouts are only meaningful when writing a file.
struct LayoutChoice {
const char* name;
const char* label;
};
const LayoutChoice kLayoutChoices[] = {
{"2.0", "2.0 (立体声)"}, {"3.0", "3.0"}, {"3.1", "3.1"}, {"4.0", "4.0"},
{"5.0", "5.0"}, {"5.1", "5.1"}, {"6.1", "6.1"}, {"7.0", "7.0"},
{"7.1", "7.1"},
};
// A drop-down list's items are rebuilt whenever the language changes, and the
// selection has to survive that.
void fill_combo(HWND combo, const std::vector<std::string>& items, int selected) {
const int current =
selected >= 0 ? selected
: static_cast<int>(SendMessageW(combo, CB_GETCURSEL, 0, 0));
SendMessageW(combo, CB_RESETCONTENT, 0, 0);
for (const std::string& item : items) {
SendMessageW(combo, CB_ADDSTRING, 0,
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"};
const char* const kModeLabels[] = {"near(近场)", "far(远场)", "mid(默认)"};
// The binaural mode combo lists the three modes in the order they widen, with the
// 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) {
switch (mode) {
case 1: return 0;
case 2: return 1;
default: return 2;
case 2: return 2;
default: return 1;
}
}
unsigned mode_value(unsigned index) {
switch (index) {
case 0: return 1;
case 1: return 2;
case 2: return 2;
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,
const wchar_t* filter) {
wchar_t buffer[4096] = {};
const wchar_t* filter) { wchar_t buffer[4096] = {};
const std::wstring current = wide(path);
if (!current.empty() && current.size() < 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;
}
// 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 {
public:
prefs_instance(HWND parent, preferences_page_callback::ptr callback)
@@ -142,12 +225,12 @@ public:
joc_settings::write(values);
m_initial = values;
joc_log::line("prefs: applied %s", joc_settings::describe(values).c_str());
update_status();
apply_texts();
notify();
}
void reset() override {
load_controls(joc_settings::defaults());
load_values(joc_settings::defaults());
joc_log::line("prefs: reset to defaults");
notify();
}
@@ -169,24 +252,17 @@ private:
INT_PTR handle(UINT message, WPARAM wparam, LPARAM lparam) {
switch (message) {
case WM_INITDIALOG:
load_controls(joc_settings::read());
load_values(joc_settings::read());
apply_dark_mode();
update_status();
return TRUE;
case WM_COMMAND: {
const int id = LOWORD(wparam);
const int code = HIWORD(wparam);
if (id == IDC_BROWSE_HRTF) {
std::string path = get_text(GetDlgItem(m_hwnd, IDC_EDIT_HRTF));
// The filter follows the selected source, because that is what
// decides the format the file has to be in.
const wchar_t* filter = L"SOFA (*.sofa)\0*.sofa\0所有文件 (*.*)\0*.*\0\0";
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 个性化模型";
}
const wchar_t* filter = L"Rosella 模型 (*.personalized_headphone)\0"
L"*.personalized_headphone\0所有文件 (*.*)\0*.*\0\0";
const wchar_t* title = L"选择 Rosella 个性化模型";
if (pick_file(m_hwnd, path, title, filter)) {
set_text(GetDlgItem(m_hwnd, IDC_EDIT_HRTF), path);
update_status();
@@ -194,12 +270,6 @@ private:
}
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) {
std::string path = get_text(GetDlgItem(m_hwnd, IDC_EDIT_FFMPEG));
if (pick_file(m_hwnd, path, L"选择 ffmpeg.exe",
@@ -210,18 +280,31 @@ private:
return TRUE;
}
if (id == IDC_RADIO_BINAURAL || id == IDC_RADIO_SPEAKER) {
update_enabled_state();
update_status();
notify();
return TRUE;
}
if (id == IDC_CHECK_GAIN) {
update_enabled_state();
if (id == IDC_CHECK_GAIN || id == IDC_CHECK_INT24 ||
id == IDC_CHECK_SWAP_SIDE_REAR || id == IDC_CHECK_PCM ||
id == IDC_CHECK_DIALNORM) {
update_status();
notify();
return TRUE;
}
if (code == EN_CHANGE || code == CBN_SELCHANGE) {
if (id == IDC_EDIT_HRTF || id == IDC_COMBO_LAYOUT ||
id == IDC_EDIT_GAIN) {
if (code == CBN_SELCHANGE) {
if (id == IDC_COMBO_LANGUAGE) {
// 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();
}
notify();
@@ -264,32 +347,55 @@ private:
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_CHECK_PCM, joc_lang::Text::kCheckPcm);
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_CHECK_DIALNORM, joc_lang::Text::kCheckDialnorm);
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,
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_FFMPEG), values.ffmpeg_path);
@@ -301,7 +407,39 @@ private:
SendMessageW(GetDlgItem(m_hwnd, IDC_CHECK_GAIN), BM_SETCHECK,
values.gain_enabled ? BST_CHECKED : BST_UNCHECKED, 0);
update_enabled_state();
SendMessageW(GetDlgItem(m_hwnd, IDC_CHECK_DIALNORM), BM_SETCHECK,
values.dialnorm ? BST_CHECKED : BST_UNCHECKED, 0);
SendMessageW(GetDlgItem(m_hwnd, IDC_CHECK_INT24), BM_SETCHECK,
values.force_int24 ? BST_CHECKED : BST_UNCHECKED, 0);
SendMessageW(GetDlgItem(m_hwnd, IDC_CHECK_PCM), BM_SETCHECK,
values.take_over_pcm ? BST_CHECKED : BST_UNCHECKED, 0);
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 {
@@ -310,17 +448,15 @@ private:
const int layout_index =
static_cast<int>(SendDlgItemMessageW(m_hwnd, IDC_COMBO_LAYOUT, CB_GETCURSEL, 0, 0));
if (layout_index >= 0 &&
layout_index < static_cast<int>(sizeof(kLayoutChoices) / sizeof(kLayoutChoices[0]))) {
values.speaker_layout = kLayoutChoices[layout_index].name;
std::size_t layout_count = 0;
const joc_decode::LayoutSpec* layouts = joc_decode::layout_table(&layout_count);
if (layout_index >= 0 && static_cast<std::size_t>(layout_index) < layout_count) {
values.speaker_layout = layouts[layout_index].name;
}
const int mode_sel =
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.ffmpeg_path = get_text(GetDlgItem(m_hwnd, IDC_EDIT_FFMPEG));
values.tail_seconds =
@@ -328,6 +464,15 @@ private:
values.gain_db = std::atof(get_text(GetDlgItem(m_hwnd, IDC_EDIT_GAIN)).c_str());
values.gain_enabled =
IsDlgButtonChecked(m_hwnd, IDC_CHECK_GAIN) == BST_CHECKED;
values.dialnorm =
IsDlgButtonChecked(m_hwnd, IDC_CHECK_DIALNORM) == BST_CHECKED;
values.force_int24 =
IsDlgButtonChecked(m_hwnd, IDC_CHECK_INT24) == BST_CHECKED;
values.swap_side_rear =
IsDlgButtonChecked(m_hwnd, IDC_CHECK_SWAP_SIDE_REAR) == BST_CHECKED;
values.take_over_pcm =
IsDlgButtonChecked(m_hwnd, IDC_CHECK_PCM) == BST_CHECKED;
values.language = selected_language();
// Advanced values are not on this page; keep whatever is stored.
const joc_settings::Values stored = joc_settings::read();
values.object_delay_samples = stored.object_delay_samples;
@@ -335,43 +480,49 @@ private:
return values;
}
// Nothing on this page is ever disabled: a greyed control reads as an option
// that cannot be used, and none of these settings is invalid in the other
// mode. A speaker layout chosen while binaural output is active simply has no
// effect until the output is switched back, and the gain field describes what
// the switch would apply. What is in effect is stated in the status line.
void update_enabled_state() { update_status(); }
// Updates the lines that describe what is in effect. Nothing on this page is
// disabled: a speaker layout chosen while binaural output is active simply has
// no effect until the output is switched back, and the status line says which
// layout and how many channels that would be.
void update_status() {
const joc_lang::Language language = joc_lang::resolve(selected_language());
const joc_settings::Values values = read_controls();
std::string output_status;
if (values.output != 0) {
char text[96] = {};
const unsigned channels = joc_decode::speaker_channels(values.speaker_layout);
std::snprintf(text, sizeof(text), "扬声器布局 %s(%u 声道)",
values.speaker_layout.c_str(), channels);
char text[192] = {};
std::snprintf(text, sizeof(text),
joc_lang::get(language, joc_lang::Text::kSpeakerStatus),
values.speaker_layout.c_str());
output_status = text;
}
set_text(GetDlgItem(m_hwnd, IDC_LABEL_OUTPUT_STATUS), output_status);
joc_decode::Settings effective = joc_settings::current();
effective.hrtf_source =
static_cast<joc_decode::HrtfSource>(values.hrtf_source);
effective.hrtf_file = values.hrtf_file;
const std::string file = joc_decode::resolve_hrtf_file(effective);
std::string hrtf_status =
std::string(joc_settings::hrtf_source_name(values.hrtf_source)) + ":";
if (values.hrtf_file.empty()) hrtf_status += "默认";
hrtf_status += "\n" +
(file.empty() ? std::string("无法确定默认路径") : file);
std::string hrtf_status = joc_lang::get(language, joc_lang::Text::kHrtfSourceRosella);
hrtf_status += joc_lang::get(language, joc_lang::Text::kSeparator);
if (values.hrtf_file.empty()) {
hrtf_status += joc_lang::get(language, joc_lang::Text::kHrtfDefault);
}
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);
char gain[96] = {};
if (values.gain_enabled) {
std::snprintf(gain, sizeof(gain), "增益开 %.2f dB", values.gain_db);
} else {
std::snprintf(gain, sizeof(gain), "增益关(输出不衰减)");
}
std::snprintf(
gain, sizeof(gain),
joc_lang::get(language, values.gain_enabled ? joc_lang::Text::kGainStatusOn
: joc_lang::Text::kGainStatusOff),
values.gain_db);
set_text(GetDlgItem(m_hwnd, IDC_LABEL_GAIN_STATUS), gain);
}
@@ -379,13 +530,17 @@ private:
const joc_settings::Values now = read_controls();
if (now.output != m_initial.output) 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.binaural_mode != m_initial.binaural_mode) return true;
if (now.gain_enabled != m_initial.gain_enabled) return true;
if (now.dialnorm != m_initial.dialnorm) 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.take_over_pcm != m_initial.take_over_pcm) return true;
if (now.gain_db != m_initial.gain_db) return true;
if (now.tail_seconds != m_initial.tail_seconds) return true;
if (now.ffmpeg_path != m_initial.ffmpeg_path) return true;
if (now.language != m_initial.language) return true;
return false;
}
@@ -433,12 +588,19 @@ private:
class prefs_page : public preferences_page_v3 {
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_parent_guid() override { return preferences_page::guid_tools; }
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);
}
};
+47 -32
View File
@@ -7,48 +7,63 @@
// 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
// every control down by the caption height -- visible but not clickable.
IDD_JOC_PREFS DIALOGEX 0, 0, 330, 273
//
// 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
FONT 8, "Microsoft Sans Serif", 400, 0, 0x0
BEGIN
GROUPBOX "输出", IDC_GROUP_OUTPUT, 7, 5, 316, 61
GROUPBOX "输出", IDC_GROUP_OUTPUT, 7, 4, 316, 72
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",
BS_AUTORADIOBUTTON | WS_TABSTOP, 16, 38, 60, 10
LTEXT "布局", IDC_LABEL_LAYOUT, 80, 39, 22, 10
COMBOBOX IDC_COMBO_LAYOUT, 104, 36, 60, 120,
BS_AUTORADIOBUTTON | WS_TABSTOP, 16, 28, 84, 10
COMBOBOX IDC_COMBO_LAYOUT, 104, 25, 110, 160,
CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP
LTEXT "双耳模式", IDC_LABEL_MODE, 172, 22, 42, 10
COMBOBOX IDC_COMBO_MODE, 216, 19, 96, 90,
LTEXT "双耳模式", IDC_LABEL_MODE, 16, 41, 66, 10
COMBOBOX IDC_COMBO_MODE, 86, 38, 92, 90,
CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP
LTEXT "房间尾音(秒)", IDC_LABEL_TAIL, 172, 41, 62, 10
EDITTEXT IDC_EDIT_TAIL, 238, 38, 40, 13, ES_AUTOHSCROLL
LTEXT "", IDC_LABEL_OUTPUT_STATUS, 16, 52, 300, 10
LTEXT "房间尾音(秒)", IDC_LABEL_TAIL, 184, 41, 58, 10
EDITTEXT IDC_EDIT_TAIL, 246, 38, 40, 13, ES_AUTOHSCROLL
LTEXT "", IDC_LABEL_OUTPUT_STATUS, 16, 53, 300, 10
CONTROL "强制 24bit 输出(int24)", IDC_CHECK_INT24, "Button",
BS_AUTOCHECKBOX | WS_TABSTOP, 16, 65, 156, 10
CONTROL "接管普通 PCM 源(ffmpeg 解码)", IDC_CHECK_PCM, "Button",
BS_AUTOCHECKBOX | WS_TABSTOP, 176, 65, 140, 10
GROUPBOX "HRTF", IDC_GROUP_HRTF, 7, 71, 316, 100
CONTROL "SOFA 文件", IDC_RADIO_HRTF_SOFA, "Button",
BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 16, 86, 56, 10
CONTROL "Rosella 个性化模型", IDC_RADIO_HRTF_ROSELLA, "Button",
BS_AUTORADIOBUTTON | WS_TABSTOP, 78, 86, 78, 10
LTEXT "HRTF 文件(留空=默认位置)", IDC_LABEL_HRTF, 16, 105, 106, 10
EDITTEXT IDC_EDIT_HRTF, 126, 102, 148, 13, ES_AUTOHSCROLL
PUSHBUTTON "浏览…", IDC_BROWSE_HRTF, 279, 102, 38, 13
LTEXT "留空时读组件目录下 HRTF\\binaural.sofa 或 binaural.personalized_headphone;SOFA 由渲染器内部编译,滤波组表已编入库中。",
GROUPBOX "HRTF", IDC_GROUP_HRTF, 7, 79, 316, 92
LTEXT "Rosella 个性化模型", IDC_RADIO_HRTF_ROSELLA, 16, 91, 146, 10
LTEXT "HRTF 文件", IDC_LABEL_HRTF, 16, 106, 40, 10
EDITTEXT IDC_EDIT_HRTF, 58, 103, 186, 13, ES_AUTOHSCROLL
PUSHBUTTON "浏览…", IDC_BROWSE_HRTF, 248, 103, 52, 13
LTEXT "留空时读组件目录下 HRTF\\binaural.personalized_headphone。",
IDC_LABEL_HRTF_HINT, 16, 121, 300, 20
LTEXT "", IDC_LABEL_STATUS, 16, 145, 300, 20
LTEXT "", IDC_LABEL_STATUS, 16, 143, 300, 20
GROUPBOX "增益", IDC_GROUP_GAIN, 7, 176, 316, 48
GROUPBOX "增益", IDC_GROUP_GAIN, 7, 174, 316, 42
CONTROL "应用增益", IDC_CHECK_GAIN, "Button",
BS_AUTOCHECKBOX | WS_TABSTOP, 16, 192, 58, 10
LTEXT "dB", IDC_LABEL_GAIN, 80, 192, 12, 10
EDITTEXT IDC_EDIT_GAIN, 96, 189, 40, 13, ES_AUTOHSCROLL
LTEXT "", IDC_LABEL_GAIN_STATUS, 145, 192, 171, 10
LTEXT "双耳渲染后可能超过 0 dBFS,可用负值衰减。",
IDC_LABEL_GAIN_HINT, 16, 208, 300, 10
BS_AUTOCHECKBOX | WS_TABSTOP, 16, 187, 48, 10
LTEXT "dB", IDC_LABEL_GAIN, 68, 187, 12, 10
EDITTEXT IDC_EDIT_GAIN, 84, 184, 44, 13, ES_AUTOHSCROLL
LTEXT "", IDC_LABEL_GAIN_STATUS, 134, 187, 182, 10
CONTROL "Dolby Dialnorm 响度均衡(-31 dBFS)", IDC_CHECK_DIALNORM, "Button",
BS_AUTOCHECKBOX | WS_TABSTOP, 16, 202, 300, 10
GROUPBOX "其它", IDC_GROUP_MISC, 7, 229, 316, 38
LTEXT "ffmpeg.exe", IDC_LABEL_FFMPEG, 16, 245, 44, 10
EDITTEXT IDC_EDIT_FFMPEG, 64, 242, 210, 13, ES_AUTOHSCROLL
PUSHBUTTON "浏览…", IDC_BROWSE_FFMPEG, 279, 242, 38, 13
GROUPBOX "其它", IDC_GROUP_MISC, 7, 219, 316, 48
CONTROL "交换侧环绕与后环绕声道", IDC_CHECK_SWAP_SIDE_REAR, "Button",
BS_AUTOCHECKBOX | WS_TABSTOP, 176, 232, 140, 10
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
+8 -1
View File
@@ -7,16 +7,20 @@
#define IDC_RADIO_BINAURAL 2011
#define IDC_RADIO_SPEAKER 2012
#define IDC_COMBO_LAYOUT 2013
#define IDC_LABEL_LAYOUT 2014
#define IDC_LABEL_MODE 2015
#define IDC_COMBO_MODE 2016
#define IDC_LABEL_TAIL 2017
#define IDC_EDIT_TAIL 2018
#define IDC_LABEL_OUTPUT_STATUS 2019
// Delivery format, in the same group: what the decoder hands to foobar2000.
#define IDC_CHECK_INT24 2050
#define IDC_CHECK_PCM 2052
#define IDC_LABEL_INT24_HINT 2051
#define IDC_GROUP_HRTF 2020
#define IDC_RADIO_HRTF_SOFA 2021
#define IDC_RADIO_HRTF_ROSELLA 2022
#define IDC_CHECK_SWAP_SIDE_REAR 2023
#define IDC_LABEL_HRTF 2024
#define IDC_EDIT_HRTF 2025
#define IDC_BROWSE_HRTF 2026
@@ -28,9 +32,12 @@
#define IDC_EDIT_GAIN 2033
#define IDC_LABEL_GAIN_HINT 2034
#define IDC_LABEL_GAIN_STATUS 2035
#define IDC_CHECK_DIALNORM 2036
#define IDC_GROUP_MISC 2040
#define IDC_LABEL_FFMPEG 2041
#define IDC_EDIT_FFMPEG 2042
#define IDC_BROWSE_FFMPEG 2043
#define IDC_LABEL_STATUS 2044
#define IDC_LABEL_LANGUAGE 2045
#define IDC_COMBO_LANGUAGE 2046
+85 -29
View File
@@ -6,6 +6,8 @@
#include <windows.h>
#include <atomic>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
@@ -22,19 +24,21 @@ constexpr GUID kGuidLayout = {0x7b62e5d1, 0x14a8, 0x4c07, {0x83, 0x2f, 0x6b, 0x9
// 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.
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 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 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 kGuidSwapSideRear = {0x2b7f6d18, 0x59c4, 0x4a83, {0x8e, 0x15, 0x73, 0xac, 0x06, 0xd9, 0x4b, 0x27}};
constexpr GUID kGuidDialnorm = {0x47e2a9b3, 0x6c14, 0x4d78, {0x81, 0x5f, 0x2a, 0xc7, 0x90, 0x3e, 0x64, 0xb1}};
constexpr GUID kGuidTakeOverPcm = {0x9f2b6c41, 0x7d38, 0x4a05, {0x86, 0x1e, 0x52, 0xb9, 0x0c, 0x74, 0xe3, 0x28}};
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 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_string g_layout(kGuidLayout, "7.1");
// 0 = SOFA, 1 = Rosella model, 2 = compiled .jochrtf (advanced)
cfg_uint g_hrtf_source(kGuidHrtfSource, 0);
cfg_string g_hrtf_file(kGuidHrtfFile, "");
cfg_uint g_binaural_mode(kGuidBinauralMode, 3);
cfg_bool g_gain_enabled(kGuidGainEnabled, true);
@@ -42,9 +46,28 @@ cfg_bool g_gain_enabled(kGuidGainEnabled, true);
cfg_int g_gain_mdb(kGuidGain, 0);
// milli-seconds
cfg_uint g_tail_ms(kGuidTail, 5000);
// Deliver int24 instead of float32.
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_bool g_take_over_pcm(kGuidTakeOverPcm, false);
cfg_bool g_dialnorm(kGuidDialnorm, false);
cfg_uint g_object_delay(kGuidObjectDelay, 1473);
cfg_uint g_threads(kGuidThreads, 0);
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
// setting that is off leaves the line exactly as it was.
template <std::size_t N>
void append_to(char (&buffer)[N], const char* text) {
if (text == nullptr || *text == '\0') return;
const std::size_t used = std::strlen(buffer);
const std::size_t extra = std::strlen(text);
if (used + extra + 1u > N) return;
std::memcpy(buffer + used, text, extra + 1u);
}
std::string environment(const char* name) {
char buffer[4096] = {};
@@ -81,18 +104,7 @@ bool env_string(const char* name, std::string* out) {
namespace joc_settings {
const char* hrtf_source_name(HrtfSource source) {
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";
}
const char* hrtf_default_file_name() { return "binaural.personalized_headphone"; }
Values defaults() { return Values(); }
@@ -100,33 +112,64 @@ Values read() {
Values values;
values.output = static_cast<int>(static_cast<unsigned>(g_output));
values.speaker_layout = g_layout.get_ptr();
if (values.speaker_layout.empty()) values.speaker_layout = "7.1";
const unsigned source = static_cast<unsigned>(g_hrtf_source);
values.hrtf_source = (source == 1u) ? HrtfSource::kRosella : HrtfSource::kSofa;
// A layout the core does not accept (an old build offered several it never
// accepted) would fail when the renderer is created, and the page cannot show it
// 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.binaural_mode = static_cast<unsigned>(g_binaural_mode);
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.tail_seconds = static_cast<double>(static_cast<unsigned>(g_tail_ms)) / 1000.0;
values.force_int24 = static_cast<bool>(g_force_int24);
values.swap_side_rear = static_cast<bool>(g_swap_side_rear);
values.take_over_pcm = static_cast<bool>(g_take_over_pcm);
values.dialnorm = static_cast<bool>(g_dialnorm);
values.object_delay_samples = static_cast<unsigned>(g_object_delay);
values.native_threads = static_cast<unsigned>(g_threads);
values.ffmpeg_path = g_ffmpeg.get_ptr();
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;
}
void write(const Values& values) {
g_output = static_cast<unsigned>(values.output);
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_binaural_mode = values.binaural_mode;
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_tail_ms = static_cast<unsigned>(values.tail_seconds * 1000.0 + 0.5);
g_force_int24 = values.force_int24;
g_swap_side_rear = values.swap_side_rear;
g_take_over_pcm = values.take_over_pcm;
g_dialnorm = values.dialnorm;
g_object_delay = values.object_delay_samples;
g_threads = values.native_threads;
g_ffmpeg = values.ffmpeg_path.c_str();
g_language = static_cast<unsigned>(values.language);
}
joc_decode::Settings current() {
@@ -134,11 +177,8 @@ joc_decode::Settings current() {
std::string text;
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);
if (env_string("JOC_HRTF_SOURCE", &text)) {
values.hrtf_source = (text == "rosella") ? HrtfSource::kRosella : HrtfSource::kSofa;
}
(void)env_string("JOC_FFMPEG", &values.ffmpeg_path);
if (env_string("JOC_BINAURAL_MODE", &text)) {
values.binaural_mode = (text == "near") ? 1u : (text == "far") ? 2u : 3u;
@@ -146,6 +186,10 @@ joc_decode::Settings current() {
(void)env_double("JOC_GAIN_DB", &values.gain_db);
if (env_string("JOC_GAIN_ENABLED", &text)) values.gain_enabled = (text != "0");
(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_SWAP_SIDE_REAR", &text)) values.swap_side_rear = (text != "0");
if (env_string("JOC_TAKE_OVER_PCM", &text)) values.take_over_pcm = (text != "0");
if (env_string("JOC_DIALNORM", &text)) values.dialnorm = (text != "0");
(void)env_uint("JOC_OBJECT_DELAY", &values.object_delay_samples);
(void)env_uint("JOC_THREADS", &values.native_threads);
@@ -153,7 +197,6 @@ joc_decode::Settings current() {
settings.output =
(values.output == 0) ? joc_decode::Output::kBinaural : joc_decode::Output::kSpeaker;
settings.speaker_layout = values.speaker_layout;
settings.hrtf_source = static_cast<joc_decode::HrtfSource>(values.hrtf_source);
settings.hrtf_file = values.hrtf_file;
settings.binaural_mode = values.binaural_mode;
// The switch is explicit rather than implied by the value: binaural rendering
@@ -161,6 +204,10 @@ joc_decode::Settings current() {
// attenuation has to be visible and switchable.
settings.gain_db = values.gain_enabled ? values.gain_db : 0.0;
settings.tail_seconds = values.tail_seconds;
settings.force_int24 = values.force_int24;
settings.swap_side_rear = values.swap_side_rear;
settings.take_over_pcm = values.take_over_pcm;
settings.dialnorm = values.dialnorm;
settings.object_delay_samples = values.object_delay_samples;
settings.native_threads = values.native_threads;
settings.ffmpeg_path = values.ffmpeg_path.empty() ? "ffmpeg" : values.ffmpeg_path;
@@ -171,9 +218,8 @@ std::string describe(const joc_decode::Settings& settings) {
char text[640] = {};
if (settings.output == joc_decode::Output::kBinaural) {
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",
hrtf_source_name(static_cast<HrtfSource>(settings.hrtf_source)),
settings.hrtf_file.empty() ? "(默认位置)" : settings.hrtf_file.c_str(),
settings.binaural_mode, settings.gain_db, settings.tail_seconds,
settings.object_delay_samples, settings.native_threads,
@@ -187,19 +233,29 @@ std::string describe(const joc_decode::Settings& settings) {
settings.object_delay_samples, settings.native_threads,
settings.ffmpeg_path.c_str());
}
// Stated only when it is not the default, so a default log line reads as it
// always did.
append_to(text, settings.force_int24 ? ", int24=forced" : "");
append_to(text, settings.swap_side_rear ? ", swap=side/rear" : "");
return text;
}
std::string describe(const Values& values) {
char text[640] = {};
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\"",
values.output, values.speaker_layout.c_str(),
hrtf_source_name(values.hrtf_source), values.hrtf_file.c_str(),
values.output, values.speaker_layout.c_str(), values.hrtf_file.c_str(),
values.binaural_mode, values.gain_enabled ? "" : "(off) ", values.gain_db,
values.tail_seconds, values.object_delay_samples, values.native_threads,
values.ffmpeg_path.c_str());
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;
}
+15 -12
View File
@@ -13,36 +13,39 @@
#include <string>
#include "joc_decode.h"
#include "lang.h"
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
// is configured; same names the reference CLI uses.
const char* hrtf_default_file_name(HrtfSource source);
// is configured; same name the reference CLI uses.
const char* hrtf_default_file_name();
// The stored values, exactly as the preferences page shows them.
struct Values {
int output = 0; // 0 = binaural, 1 = speaker layout
std::string speaker_layout = "7.1";
HrtfSource hrtf_source = HrtfSource::kSofa;
// Empty means "the default file in the default folder".
std::string hrtf_file;
unsigned binaural_mode = 3; // JOC_BINAURAL_NEAR/FAR/MID = 1/2/3
bool gain_enabled = true;
double gain_db = 0.0;
double tail_seconds = 5.0;
// Deliver int24 instead of float32; see joc_decode::Settings::force_int24.
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;
// Take over ordinary PCM files and render them binaurally through ffmpeg.
bool take_over_pcm = false;
// Apply Dolby Dialnorm to the ffmpeg E-AC-3 5.1 core decode (-target_level -31).
bool dialnorm = false;
unsigned object_delay_samples = 1473;
unsigned native_threads = 0;
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();
+90
View File
@@ -0,0 +1,90 @@
// Paths handed to the Win32 file APIs.
//
// Windows refuses a path of MAX_PATH characters or more to any call that does not
// carry the \\?\ prefix. The prefix is a property of the path, not of the process:
// a component cannot inherit it from the host's manifest, so whoever calls the API
// has to add it. A file that plays from the desktop therefore stops being found
// once its folder tree is deep enough, which is what this header exists to prevent.
//
// Everything in this component that hands a path to Win32 -- or puts one on an
// ffmpeg command line, which is the same call made by the child process -- goes
// through to_wide_extended(). What is deliberately not routed through it is the
// path the component keeps for itself: the one it logs, and the one it uses as the
// container-probe cache key. Those stay in their plain form, so a log line reads
// like a path a user can paste into Explorer.
#pragma once
#include <windows.h>
#include <string>
namespace joc_path {
// UTF-8 -> UTF-16, for the W APIs. Every path crosses into the OS through here:
// the narrow CRT would convert it through the ANSI code page, which is what breaks
// names like "Les Fêtes d'Hébé".
inline std::wstring to_wide(const std::string& utf8) {
if (utf8.empty()) return {};
const int needed = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(),
static_cast<int>(utf8.size()), nullptr, 0);
if (needed <= 0) return {};
std::wstring out(static_cast<std::size_t>(needed), L'\0');
MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), static_cast<int>(utf8.size()), out.data(),
needed);
return out;
}
// The same path in the form the Win32 file APIs need. Three kinds of path are left
// exactly as they came in, and each of them would be broken by a prefix:
//
// * one that already carries \\?\, which makes this idempotent;
// * one that is not fully qualified -- a relative path, or the ffmpeg setting
// when it is a bare executable name that PATH resolves. \\?\ is undefined for
// those;
// * one with a "." or ".." segment, because \\?\ switches off the normalization
// that would resolve it.
//
// The separators are settled first for the same reason: once the prefix is on,
// nothing turns a forward slash into a backslash any more, and both of the checks
// above have to see the path the way the file system will.
inline std::wstring to_wide_extended(const std::wstring& path) {
if (path.empty()) return path;
if (path.compare(0, 4, L"\\\\?\\") == 0) return path;
std::wstring plain = path;
for (wchar_t& character : plain) {
if (character == L'/') character = L'\\';
}
const bool unc = plain.size() >= 2 && plain[0] == L'\\' && plain[1] == L'\\';
const bool drive = plain.size() >= 3 && plain[1] == L':' && plain[2] == L'\\';
if (!unc && !drive) return path;
if (plain.find(L"\\.\\") != std::wstring::npos ||
plain.find(L"\\..\\") != std::wstring::npos) {
return path;
}
// A UNC path drops its two leading separators; everything else is copied whole.
std::wstring out = unc ? L"\\\\?\\UNC\\" : L"\\\\?\\";
out.append(plain, unc ? 2 : 0, std::wstring::npos);
return out;
}
inline std::wstring to_wide_extended(const std::string& utf8) {
return to_wide_extended(to_wide(utf8));
}
// UTF-16 -> UTF-8, the direction the component reports paths in.
inline std::string to_utf8(const std::wstring& wide) {
if (wide.empty()) return {};
const int needed = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(),
static_cast<int>(wide.size()), nullptr, 0, nullptr,
nullptr);
if (needed <= 0) return {};
std::string out(static_cast<std::string::size_type>(needed), '\0');
WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), static_cast<int>(wide.size()), out.data(),
needed, nullptr, nullptr);
return out;
}
} // namespace joc_path
+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;
}
+143
View File
@@ -0,0 +1,143 @@
// 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"},
{"6.0", "L R Ls Rs Lrs Rrs"},
};
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;
}
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more