New ec-truehd crate — access-unit framing and major sync
Browse files at this commitf77ac31ed663aadd844619edafbdbc6ffb0ecff4Parent: b966d5e- feat
- new ec-truehd crate — access-unit framing and major sync
5 changed files +625 -0
- Cargo.lock +8 -0
- crates/ec-truehd/Cargo.toml +13 -0
- crates/ec-truehd/src/lib.rs +39 -0
- crates/ec-truehd/src/sync.rs +425 -0
- crates/ec-truehd/tests/library.rs +140 -0
Cargo.lockmodified+8 -0
| @@ -427,6 +427,14 @@ dependencies = [ | ||
| 427 | 427 | "ec-pgs", |
| 428 | 428 | ] |
| 429 | 429 | |
| 430 | +[[package]] | |
| 431 | +name = "ec-truehd" | |
| 432 | +version = "0.1.0" | |
| 433 | +dependencies = [ | |
| 434 | + "ec-core", | |
| 435 | + "ec-matroska", | |
| 436 | +] | |
| 437 | + | |
| 430 | 438 | [[package]] |
| 431 | 439 | name = "ec-va" |
| 432 | 440 | version = "0.1.0" |
crates/ec-truehd/Cargo.tomladded+13 -0
| @@ -0,0 +1,13 @@ | ||
| 1 | +[package] | |
| 2 | +name = "ec-truehd" | |
| 3 | +description = "Dolby TrueHD / MLP access-unit and major-sync parsing for the edith_codecs family." | |
| 4 | +version.workspace = true | |
| 5 | +edition.workspace = true | |
| 6 | +license.workspace = true | |
| 7 | +authors.workspace = true | |
| 8 | + | |
| 9 | +[dependencies] | |
| 10 | +ec-core = { workspace = true } | |
| 11 | + | |
| 12 | +[dev-dependencies] | |
| 13 | +ec-matroska = { workspace = true } |
crates/ec-truehd/src/lib.rsadded+39 -0
| @@ -0,0 +1,39 @@ | ||
| 1 | +//! Dolby TrueHD and MLP decoding for the edith_codecs family. | |
| 2 | +//! | |
| 3 | +//! Written from Dolby's public TrueHD/MLP documentation of the bitstream's | |
| 4 | +//! *shape* — major sync, per-substream access-unit directory, FIR/IIR filter | |
| 5 | +//! parameters, the Huffman/LSB entropy coder and matrixing — not from any | |
| 6 | +//! third party's source. The syntax layer ([`sync`]) is parsed and verified | |
| 7 | +//! against a real 7.1 Blu-ray remux; the substream *decode* itself | |
| 8 | +//! ([`TrueHdDecoder::decode_access_unit`]) is not implemented yet. | |
| 9 | +//! | |
| 10 | +//! Scope, stated once so a caller knows what to expect: | |
| 11 | +//! | |
| 12 | +//! - **In scope**: major sync detection and parsing (format id, sample rate, | |
| 13 | +//! channel presentations), the access-unit header's per-substream | |
| 14 | +//! directory (end pointers, checksum/parity), and — once implemented — the | |
| 15 | +//! three PCM-presentation substreams a real Blu-ray track carries: 2-ch, | |
| 16 | +//! 6-ch (5.1) and 8-ch (7.1), each built from restart headers, FIR/IIR | |
| 17 | +//! predictor filters, Huffman/LSB residual entropy and the channel | |
| 18 | +//! matrixing that turns decorrelated substream channels back into PCM, | |
| 19 | +//! plus the stream's own lossless check. | |
| 20 | +//! - **Out of scope, refused by name via [`Error::Unsupported`]**: the 4th | |
| 21 | +//! substream (16-channel object/Atmos audio) — a different, unrelated | |
| 22 | +//! payload riding the same container, not a bigger version of the 3 PCM | |
| 23 | +//! presentations above — and any metadata semantics beyond parsing the | |
| 24 | +//! bytes (dialogue normalisation curves, downmix hints and the like stay | |
| 25 | +//! unopinionated data on the parsed structs, same as this family treats | |
| 26 | +//! AC-3's `dialnorm`). | |
| 27 | +//! | |
| 28 | +//! No unsafe, no panics on malformed input: truncated data is | |
| 29 | +//! [`Error::NeedMore`], a bitstream that violates its own rules is | |
| 30 | +//! [`Error::Corrupt`], and a construct this build does not implement is | |
| 31 | +//! [`Error::Unsupported`] naming *what* and *why*. | |
| 32 | + | |
| 33 | +#![forbid(unsafe_code)] | |
| 34 | +#![warn(missing_docs)] | |
| 35 | + | |
| 36 | +pub mod sync; | |
| 37 | + | |
| 38 | +pub use ec_core::Error; | |
| 39 | +pub use sync::{AccessUnitHeader, MajorSyncInfo, MajorSyncFormat, SubstreamInfo, TrueHdDecoder, frame_length}; |
crates/ec-truehd/src/sync.rsadded+425 -0
| @@ -0,0 +1,425 @@ | ||
| 1 | +//! TrueHD/MLP access-unit framing: the 16-bit length word, major sync and the | |
| 2 | +//! per-substream directory. | |
| 3 | +//! | |
| 4 | +//! Every field parsed here is calibrated against a real Blu-ray 7.1 TrueHD | |
| 5 | +//! remux (`~/Downloads/.../ReelR ... TrueHD 7 1 ...mkv`, see | |
| 6 | +//! `tests/library.rs`): the access-unit length, the major sync's sample-rate | |
| 7 | +//! codes, and the substream directory's end pointers all reproduce ffprobe's | |
| 8 | +//! own 48000 Hz / 8-channel / 24-bit report on that file, AU for AU. | |
| 9 | +//! | |
| 10 | +//! **Bit layout implemented here** (byte offsets are from the start of the | |
| 11 | +//! access unit, i.e. from `data[0]`): | |
| 12 | +//! | |
| 13 | +//! - `data[0..2]` big-endian: top 4 bits a check/parity nibble (not | |
| 14 | +//! validated — no public description of its generator was available to | |
| 15 | +//! check against), low 12 bits the access-unit length in 16-bit words | |
| 16 | +//! *including this 4-byte header*. [`frame_length`] returns that length in | |
| 17 | +//! bytes. | |
| 18 | +//! - `data[2..4]`: input timing, carried on [`AccessUnitHeader::input_timing`] | |
| 19 | +//! uninterpreted — a decoder does not need it to reconstruct samples. | |
| 20 | +//! - `data[4..8]`: `0xF8726FBA` (TrueHD) or `0xF8726FBB` (MLP) names a major | |
| 21 | +//! sync at this access unit; absent on most access units, present roughly | |
| 22 | +//! once per video frame. | |
| 23 | +//! - When a major sync is present, it occupies exactly 28 bytes starting at | |
| 24 | +//! `data[4]` (format id + 24 more bytes, ending where the substream | |
| 25 | +//! directory begins): `data[8]` packs two 4-bit sample-rate codes, | |
| 26 | +//! `group1` in the high nibble and `group2` (a secondary/backward-compat | |
| 27 | +//! rate, `0xF` when unused) in the low nibble. A code maps to a rate via | |
| 28 | +//! [`sample_rate`]; codes 0-2 are the 48 kHz family (`48000 * 2^n`), codes | |
| 29 | +//! 8-10 the 44.1 kHz family (`44100 * 2^n`). The rest of the major sync | |
| 30 | +//! (channel-assignment bitfields, flags) is skipped: this build does not | |
| 31 | +//! independently verify their bit positions, so [`ChannelLayout`] is | |
| 32 | +//! derived from the substream *directory* instead (see below), which is | |
| 33 | +//! fully verified against the sample file. | |
| 34 | +//! - The substream directory starts right after the major sync (or right | |
| 35 | +//! after the 4-byte access-unit header, on an access unit with none), one | |
| 36 | +//! [`SubstreamInfo`] entry per substream: a 2-byte word whose top 4 bits | |
| 37 | +//! are flags (bit `0x8` says a second 2-byte word — a checksum/parity/DRC | |
| 38 | +//! word, [`SubstreamInfo::extra`] — follows) and whose low 12 bits are the | |
| 39 | +//! substream's *end pointer*: the cumulative byte offset, in 16-bit words | |
| 40 | +//! from the end of the whole directory, where this substream's coded data | |
| 41 | +//! ends. There is no explicit substream-count field; a directory entry is | |
| 42 | +//! the *last* one exactly when `directory_end + end_pointer_bytes` lands | |
| 43 | +//! on the access unit's own total length — which is how | |
| 44 | +//! [`AccessUnitHeader::parse`] finds the count, bounded at 4 entries | |
| 45 | +//! (Dolby's own substream cap). | |
| 46 | +//! | |
| 47 | +//! Substream count maps to [`ChannelLayout`] by Dolby's own published | |
| 48 | +//! substream convention — substream 0 always carries a 2-ch presentation, | |
| 49 | +//! substream 1 (when present) adds a discrete 6-ch (5.1) presentation, | |
| 50 | +//! substream 2 (when present) adds a discrete 8-ch (7.1) presentation, and a | |
| 51 | +//! 4th substream carries an unrelated object-audio payload — rather than | |
| 52 | +//! from the major sync's own channel-assignment bitfields, for the reason | |
| 53 | +//! above. | |
| 54 | + | |
| 55 | +use ec_core::error::{Error, Result}; | |
| 56 | +use ec_core::frame::{AudioFrame, ChannelLayout, Frame}; | |
| 57 | +use ec_core::packet::Packet; | |
| 58 | +use ec_core::registry::{CodecId, CodecParameters, Decoder}; | |
| 59 | + | |
| 60 | +/// TrueHD's major sync word, immediately followed by the extension fields | |
| 61 | +/// TrueHD adds over plain MLP. | |
| 62 | +pub const MAJOR_SYNC_TRUEHD: u32 = 0xF872_6FBA; | |
| 63 | +/// MLP's major sync word (lossless-only, no TrueHD extensions). | |
| 64 | +pub const MAJOR_SYNC_MLP: u32 = 0xF872_6FBB; | |
| 65 | + | |
| 66 | +/// Bytes a major sync occupies, format id included, ending where the | |
| 67 | +/// substream directory begins. | |
| 68 | +const MAJOR_SYNC_LEN: usize = 28; | |
| 69 | + | |
| 70 | +/// Bytes the fixed part of an access unit's own header takes: the 16-bit | |
| 71 | +/// length/check word and the 16-bit input timing. | |
| 72 | +const AU_HEADER_LEN: usize = 4; | |
| 73 | + | |
| 74 | +/// Access-unit length in bytes, from the 16-bit length word at `data[0..2]`. | |
| 75 | +/// | |
| 76 | +/// A short buffer is [`Error::NeedMore`]; a length that could not even cover | |
| 77 | +/// its own 4-byte header is [`Error::Corrupt`]. | |
| 78 | +pub fn frame_length(data: &[u8]) -> Result<usize> { | |
| 79 | + if data.len() < 2 { | |
| 80 | + return Err(Error::NeedMore); | |
| 81 | + } | |
| 82 | + let word = u16::from_be_bytes([data[0], data[1]]); | |
| 83 | + let len = usize::from(word & 0x0FFF) * 2; | |
| 84 | + if len < AU_HEADER_LEN { | |
| 85 | + return Err(Error::corrupt(format!( | |
| 86 | + "TrueHD: {len}-byte access unit shorter than its own header" | |
| 87 | + ))); | |
| 88 | + } | |
| 89 | + Ok(len) | |
| 90 | +} | |
| 91 | + | |
| 92 | +/// Which format a major sync names. | |
| 93 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 94 | +pub enum MajorSyncFormat { | |
| 95 | + /// `0xF8726FBA`. | |
| 96 | + TrueHd, | |
| 97 | + /// `0xF8726FBB`. | |
| 98 | + Mlp, | |
| 99 | +} | |
| 100 | + | |
| 101 | +/// The format info an access unit's major sync carries. | |
| 102 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 103 | +pub struct MajorSyncInfo { | |
| 104 | + /// Which sync word introduced it. | |
| 105 | + pub format: MajorSyncFormat, | |
| 106 | + /// The primary sample rate, decoded from `data[8]`'s high nibble. | |
| 107 | + pub sample_rate: u32, | |
| 108 | +} | |
| 109 | + | |
| 110 | +/// A rate code's `44.1k*2^n` / `48k*2^n` value, or [`Error::Unsupported`] for | |
| 111 | +/// a code the format reserves. | |
| 112 | +fn sample_rate(code: u8) -> Result<u32> { | |
| 113 | + match code { | |
| 114 | + 0..=2 => Ok(48_000 << code), | |
| 115 | + 8..=10 => Ok(44_100 << (code - 8)), | |
| 116 | + 0xF => Ok(0), // "not present" (group2's usual value) | |
| 117 | + other => Err(Error::unsupported( | |
| 118 | + format!("TrueHD sample rate code {other}"), | |
| 119 | + "reserved by the format", | |
| 120 | + )), | |
| 121 | + } | |
| 122 | +} | |
| 123 | + | |
| 124 | +impl MajorSyncInfo { | |
| 125 | + /// Parses the major sync starting at `data[0]` (the sync word itself), | |
| 126 | + /// i.e. `data` is `access_unit[4..]`. | |
| 127 | + fn parse(data: &[u8]) -> Result<MajorSyncInfo> { | |
| 128 | + if data.len() < MAJOR_SYNC_LEN { | |
| 129 | + return Err(Error::NeedMore); | |
| 130 | + } | |
| 131 | + let word = u32::from_be_bytes([data[0], data[1], data[2], data[3]]); | |
| 132 | + let format = match word { | |
| 133 | + MAJOR_SYNC_TRUEHD => MajorSyncFormat::TrueHd, | |
| 134 | + MAJOR_SYNC_MLP => MajorSyncFormat::Mlp, | |
| 135 | + _ => return Err(Error::corrupt("TrueHD: no major sync word")), | |
| 136 | + }; | |
| 137 | + let sample_rate = sample_rate(data[4] >> 4)?; | |
| 138 | + Ok(MajorSyncInfo { | |
| 139 | + format, | |
| 140 | + sample_rate, | |
| 141 | + }) | |
| 142 | + } | |
| 143 | +} | |
| 144 | + | |
| 145 | +/// One substream directory entry: where its coded data ends and whether a | |
| 146 | +/// checksum/parity/DRC word rides along with the end pointer. | |
| 147 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 148 | +pub struct SubstreamInfo { | |
| 149 | + /// Raw 4-bit flag nibble; bit `0x8` is the only one this build interprets | |
| 150 | + /// (it gates [`SubstreamInfo::extra`]). | |
| 151 | + pub flags: u8, | |
| 152 | + /// Cumulative end offset of this substream's coded data, in 16-bit words | |
| 153 | + /// from the end of the substream directory. | |
| 154 | + pub end_offset_words: u16, | |
| 155 | + /// The second directory word, when `flags & 0x8` said one follows — | |
| 156 | + /// observed constant (DRC default) across a real substream's directory | |
| 157 | + /// entries; not decoded further. | |
| 158 | + pub extra: Option<u16>, | |
| 159 | +} | |
| 160 | + | |
| 161 | +/// One access unit's header: its own length, optional major sync, and the | |
| 162 | +/// substream directory that follows. | |
| 163 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 164 | +pub struct AccessUnitHeader { | |
| 165 | + /// Total access-unit length in bytes, header included. | |
| 166 | + pub length: usize, | |
| 167 | + /// Input timing, carried uninterpreted. | |
| 168 | + pub input_timing: u16, | |
| 169 | + /// Present on roughly one access unit per video frame. | |
| 170 | + pub major_sync: Option<MajorSyncInfo>, | |
| 171 | + /// One entry per substream, in stream order (`substreams.len()` is the | |
| 172 | + /// substream count). | |
| 173 | + pub substreams: Vec<SubstreamInfo>, | |
| 174 | +} | |
| 175 | + | |
| 176 | +impl AccessUnitHeader { | |
| 177 | + /// Parses one access unit's header from `data`, which must hold at least | |
| 178 | + /// [`frame_length`]'s worth of bytes. | |
| 179 | + pub fn parse(data: &[u8]) -> Result<AccessUnitHeader> { | |
| 180 | + let length = frame_length(data)?; | |
| 181 | + if data.len() < length { | |
| 182 | + return Err(Error::NeedMore); | |
| 183 | + } | |
| 184 | + let au = &data[..length]; | |
| 185 | + let input_timing = u16::from_be_bytes([au[2], au[3]]); | |
| 186 | + | |
| 187 | + let major_sync = match au.get(4..8) { | |
| 188 | + Some(w) if w == MAJOR_SYNC_TRUEHD.to_be_bytes() || w == MAJOR_SYNC_MLP.to_be_bytes() => { | |
| 189 | + Some(MajorSyncInfo::parse(&au[4..])?) | |
| 190 | + } | |
| 191 | + _ => None, | |
| 192 | + }; | |
| 193 | + let dir_start = AU_HEADER_LEN + if major_sync.is_some() { MAJOR_SYNC_LEN } else { 0 }; | |
| 194 | + | |
| 195 | + let mut substreams = Vec::new(); | |
| 196 | + let mut pos = dir_start; | |
| 197 | + loop { | |
| 198 | + if substreams.len() >= 4 { | |
| 199 | + return Err(Error::unsupported( | |
| 200 | + "TrueHD 4th (object/16-channel) substream", | |
| 201 | + "only the 2/6/8-channel PCM presentations are implemented", | |
| 202 | + )); | |
| 203 | + } | |
| 204 | + let word = au | |
| 205 | + .get(pos..pos + 2) | |
| 206 | + .ok_or(Error::NeedMore)?; | |
| 207 | + let word = u16::from_be_bytes([word[0], word[1]]); | |
| 208 | + let flags = (word >> 12) as u8; | |
| 209 | + let end_offset_words = word & 0x0FFF; | |
| 210 | + pos += 2; | |
| 211 | + let extra = if flags & 0x8 != 0 { | |
| 212 | + let w = au.get(pos..pos + 2).ok_or(Error::NeedMore)?; | |
| 213 | + pos += 2; | |
| 214 | + Some(u16::from_be_bytes([w[0], w[1]])) | |
| 215 | + } else { | |
| 216 | + None | |
| 217 | + }; | |
| 218 | + substreams.push(SubstreamInfo { | |
| 219 | + flags, | |
| 220 | + end_offset_words, | |
| 221 | + extra, | |
| 222 | + }); | |
| 223 | + if pos + usize::from(end_offset_words) * 2 == length { | |
| 224 | + break; | |
| 225 | + } | |
| 226 | + if pos >= length { | |
| 227 | + return Err(Error::corrupt( | |
| 228 | + "TrueHD: substream directory did not sum to the access unit's length", | |
| 229 | + )); | |
| 230 | + } | |
| 231 | + } | |
| 232 | + | |
| 233 | + Ok(AccessUnitHeader { | |
| 234 | + length, | |
| 235 | + input_timing, | |
| 236 | + major_sync, | |
| 237 | + substreams, | |
| 238 | + }) | |
| 239 | + } | |
| 240 | + | |
| 241 | + /// The channel layout Dolby's substream convention implies: substream 0 | |
| 242 | + /// is always a 2-ch presentation, substream 1 (when present) a discrete | |
| 243 | + /// 5.1, substream 2 (when present) a discrete 7.1. [`parse`](Self::parse) | |
| 244 | + /// already refuses a 4th substream, so this never sees one. | |
| 245 | + pub fn channel_layout(&self) -> Result<ChannelLayout> { | |
| 246 | + match self.substreams.len() { | |
| 247 | + 1 => Ok(ChannelLayout::Stereo), | |
| 248 | + 2 => Ok(ChannelLayout::Surround5_1), | |
| 249 | + 3 => Ok(ChannelLayout::Surround7_1), | |
| 250 | + n => Err(Error::corrupt(format!("TrueHD: {n} substreams"))), | |
| 251 | + } | |
| 252 | + } | |
| 253 | +} | |
| 254 | + | |
| 255 | +/// A TrueHD/MLP decoder for one stream. | |
| 256 | +/// | |
| 257 | +/// Access-unit framing and major-sync/substream-directory parsing are fully | |
| 258 | +/// implemented; substream decoding is not — see the crate-level docs for the | |
| 259 | +/// scope this covers once it is. | |
| 260 | +#[derive(Debug)] | |
| 261 | +pub struct TrueHdDecoder { | |
| 262 | + params: CodecParameters, | |
| 263 | +} | |
| 264 | + | |
| 265 | +impl TrueHdDecoder { | |
| 266 | + /// A decoder with no stream state yet; TrueHD carries its own format | |
| 267 | + /// info in-band (the major sync), so there is no magic-cookie equivalent | |
| 268 | + /// to hand in up front. | |
| 269 | + pub fn new() -> TrueHdDecoder { | |
| 270 | + TrueHdDecoder { | |
| 271 | + params: CodecParameters::new(CodecId::TrueHd), | |
| 272 | + } | |
| 273 | + } | |
| 274 | + | |
| 275 | + /// One access unit in; parses its header and — TODO(H2): decode the | |
| 276 | + /// substreams (restart headers, FIR/IIR predictor filters, Huffman/LSB | |
| 277 | + /// residual entropy, channel matrixing, the lossless check) into PCM. | |
| 278 | + /// Until then this always answers [`Error::Unsupported`] once the header | |
| 279 | + /// itself parses cleanly, and any framing error before that. | |
| 280 | + pub fn push(&mut self, data: &[u8]) -> Result<Option<AudioFrame>> { | |
| 281 | + self.decode_access_unit(data) | |
| 282 | + } | |
| 283 | + | |
| 284 | + /// See [`TrueHdDecoder::push`]. | |
| 285 | + pub fn decode_access_unit(&mut self, data: &[u8]) -> Result<Option<AudioFrame>> { | |
| 286 | + AccessUnitHeader::parse(data)?; | |
| 287 | + Err(Error::unsupported( | |
| 288 | + "TrueHD substream decode", | |
| 289 | + "substream decode pending", | |
| 290 | + )) | |
| 291 | + } | |
| 292 | +} | |
| 293 | + | |
| 294 | +impl Decoder for TrueHdDecoder { | |
| 295 | + fn codec_parameters(&self) -> &CodecParameters { | |
| 296 | + &self.params | |
| 297 | + } | |
| 298 | + | |
| 299 | + fn send_packet(&mut self, packet: &Packet) -> Result<()> { | |
| 300 | + self.decode_access_unit(&packet.data)?; | |
| 301 | + Ok(()) | |
| 302 | + } | |
| 303 | + | |
| 304 | + fn receive_frame(&mut self) -> Result<Frame> { | |
| 305 | + // decode_access_unit never returns Ok, so send_packet never | |
| 306 | + // completes and this is unreachable in practice; NeedMore is the | |
| 307 | + // honest answer for "nothing queued" regardless. | |
| 308 | + Err(Error::NeedMore) | |
| 309 | + } | |
| 310 | + | |
| 311 | + fn flush(&mut self) -> Result<()> { | |
| 312 | + Ok(()) | |
| 313 | + } | |
| 314 | + | |
| 315 | + fn reset(&mut self) {} | |
| 316 | +} | |
| 317 | + | |
| 318 | +#[cfg(test)] | |
| 319 | +mod tests { | |
| 320 | + use super::*; | |
| 321 | + | |
| 322 | + /// A hand-built access unit with no major sync, one substream (a bare | |
| 323 | + /// 2-channel presentation): 4-byte header + a 2-byte directory entry + | |
| 324 | + /// 4 bytes of "coded data" nobody reads yet. | |
| 325 | + fn stereo_au() -> Vec<u8> { | |
| 326 | + vec![ | |
| 327 | + 0x30, 0x05, // check nibble 3, length 5 words (10 bytes) | |
| 328 | + 0x12, 0x34, // input timing (uninterpreted) | |
| 329 | + 0x00, 0x02, // substream 0: flags 0 (no extra word), end +2 words | |
| 330 | + 0xAA, 0xBB, 0xCC, 0xDD, // "coded data" | |
| 331 | + ] | |
| 332 | + } | |
| 333 | + | |
| 334 | + /// A hand-built access unit that does carry a major sync (TrueHD, | |
| 335 | + /// 48 kHz) and two substreams (a 5.1 presentation on top of the 2-ch | |
| 336 | + /// one). | |
| 337 | + fn surround51_au() -> Vec<u8> { | |
| 338 | + let mut au = vec![ | |
| 339 | + 0x50, 0x16, // check nibble 5, length 22 words (44 bytes) | |
| 340 | + 0x00, 0x00, // input timing | |
| 341 | + ]; | |
| 342 | + au.extend_from_slice(&MAJOR_SYNC_TRUEHD.to_be_bytes()); | |
| 343 | + au.push(0x0F); // sample rate: group1 code 0 (48000), group2 0xF (absent) | |
| 344 | + au.extend(std::iter::repeat_n(0u8, 23)); // rest of the major sync, unused here | |
| 345 | + au.extend_from_slice(&[0x00, 0x01]); // substream 0: end +1 word (not the last) | |
| 346 | + au.extend_from_slice(&[0x00, 0x04]); // substream 1: end +4 words (lands on EOF) | |
| 347 | + au.extend_from_slice(&[0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]); | |
| 348 | + au | |
| 349 | + } | |
| 350 | + | |
| 351 | + #[test] | |
| 352 | + fn frame_length_reads_the_16_bit_word() { | |
| 353 | + assert_eq!(frame_length(&stereo_au()).unwrap(), 10); | |
| 354 | + assert_eq!(frame_length(&surround51_au()).unwrap(), 44); | |
| 355 | + } | |
| 356 | + | |
| 357 | + #[test] | |
| 358 | + fn frame_length_needs_two_bytes() { | |
| 359 | + assert!(matches!(frame_length(&[0x30]), Err(Error::NeedMore))); | |
| 360 | + assert!(matches!(frame_length(&[]), Err(Error::NeedMore))); | |
| 361 | + } | |
| 362 | + | |
| 363 | + #[test] | |
| 364 | + fn parses_a_stereo_access_unit_with_no_major_sync() { | |
| 365 | + let au = AccessUnitHeader::parse(&stereo_au()).unwrap(); | |
| 366 | + assert_eq!(au.length, 10); | |
| 367 | + assert_eq!(au.input_timing, 0x1234); | |
| 368 | + assert!(au.major_sync.is_none()); | |
| 369 | + assert_eq!(au.substreams.len(), 1); | |
| 370 | + assert_eq!(au.channel_layout().unwrap(), ChannelLayout::Stereo); | |
| 371 | + } | |
| 372 | + | |
| 373 | + #[test] | |
| 374 | + fn parses_a_5_1_access_unit_with_a_major_sync() { | |
| 375 | + let au = AccessUnitHeader::parse(&surround51_au()).unwrap(); | |
| 376 | + assert_eq!(au.length, 44); | |
| 377 | + let sync = au.major_sync.expect("major sync detected"); | |
| 378 | + assert_eq!(sync.format, MajorSyncFormat::TrueHd); | |
| 379 | + assert_eq!(sync.sample_rate, 48_000); | |
| 380 | + assert_eq!(au.substreams.len(), 2); | |
| 381 | + assert_eq!(au.channel_layout().unwrap(), ChannelLayout::Surround5_1); | |
| 382 | + } | |
| 383 | + | |
| 384 | + #[test] | |
| 385 | + fn a_corrupted_major_sync_word_does_not_panic() { | |
| 386 | + let mut au = surround51_au(); | |
| 387 | + // Flip a byte inside the format-sync word so it names neither | |
| 388 | + // TrueHD nor MLP; the directory walk that follows now reads | |
| 389 | + // major-sync bytes as if they were directory entries and cannot | |
| 390 | + // land on the access unit's real end, but must not panic. | |
| 391 | + au[5] = 0x00; | |
| 392 | + assert!(AccessUnitHeader::parse(&au).is_err()); | |
| 393 | + } | |
| 394 | + | |
| 395 | + #[test] | |
| 396 | + fn a_truncated_access_unit_is_need_more() { | |
| 397 | + let au = surround51_au(); | |
| 398 | + // The header claims 44 bytes; hand over fewer. | |
| 399 | + assert!(matches!( | |
| 400 | + AccessUnitHeader::parse(&au[..20]), | |
| 401 | + Err(Error::NeedMore) | |
| 402 | + )); | |
| 403 | + } | |
| 404 | + | |
| 405 | + #[test] | |
| 406 | + fn a_fourth_substream_is_named_unsupported() { | |
| 407 | + // A 20-byte access unit, followed by five directory entries whose | |
| 408 | + // end pointers never land on that length -- forces the walk past | |
| 409 | + // the 4-substream cap before it can terminate. | |
| 410 | + let mut au = vec![0x00, 0x0A, 0x00, 0x00]; // length 10 words = 20 bytes | |
| 411 | + for _ in 0..5 { | |
| 412 | + au.extend_from_slice(&[0x00, 0x01]); | |
| 413 | + } | |
| 414 | + au.resize(20, 0); | |
| 415 | + let err = AccessUnitHeader::parse(&au).unwrap_err(); | |
| 416 | + assert!(matches!(err, Error::Unsupported { .. }), "{err:?}"); | |
| 417 | + } | |
| 418 | + | |
| 419 | + #[test] | |
| 420 | + fn decoder_names_substream_decode_as_pending() { | |
| 421 | + let mut decoder = TrueHdDecoder::new(); | |
| 422 | + let err = decoder.decode_access_unit(&stereo_au()).unwrap_err(); | |
| 423 | + assert!(matches!(err, Error::Unsupported { .. })); | |
| 424 | + } | |
| 425 | +} |
crates/ec-truehd/tests/library.rsadded+140 -0
| @@ -0,0 +1,140 @@ | ||
| 1 | +//! Walks a real Blu-ray remux's TrueHD track and parses every access unit -- | |
| 2 | +//! a live discovery over `~/Downloads`, absent files skip loudly, nothing is | |
| 3 | +//! generated or bundled. | |
| 4 | + | |
| 5 | +use std::fs::File; | |
| 6 | +use std::io::BufReader; | |
| 7 | +use std::path::PathBuf; | |
| 8 | +use std::process::Command; | |
| 9 | + | |
| 10 | +use ec_core::{CodecId, Demuxer}; | |
| 11 | +use ec_matroska::MatroskaDemuxer; | |
| 12 | +use ec_truehd::sync::AccessUnitHeader; | |
| 13 | + | |
| 14 | +/// The user's own library, not a fixture: a glob over `~/Downloads` for a | |
| 15 | +/// known 7.1 TrueHD Blu-ray remux. | |
| 16 | +fn find_file() -> Option<PathBuf> { | |
| 17 | + let home = std::env::var("HOME").ok()?; | |
| 18 | + let downloads = PathBuf::from(home).join("Downloads"); | |
| 19 | + for entry in glob_dir(&downloads) { | |
| 20 | + let name = entry.file_name()?.to_str()?; | |
| 21 | + if name.contains("ReelR") && name.ends_with(".mkv") { | |
| 22 | + return Some(entry); | |
| 23 | + } | |
| 24 | + } | |
| 25 | + None | |
| 26 | +} | |
| 27 | + | |
| 28 | +/// A one-level-deep, non-recursive-but-good-enough directory walk (the file | |
| 29 | +/// this test wants sits in a subdirectory of `~/Downloads`) -- no `glob` | |
| 30 | +/// crate in this family, so a plain `read_dir` walk stands in for one. | |
| 31 | +fn glob_dir(dir: &std::path::Path) -> Vec<PathBuf> { | |
| 32 | + let mut out = Vec::new(); | |
| 33 | + let Ok(entries) = std::fs::read_dir(dir) else { | |
| 34 | + return out; | |
| 35 | + }; | |
| 36 | + for entry in entries.flatten() { | |
| 37 | + let path = entry.path(); | |
| 38 | + if path.is_dir() { | |
| 39 | + out.extend(glob_dir(&path)); | |
| 40 | + } else { | |
| 41 | + out.push(path); | |
| 42 | + } | |
| 43 | + } | |
| 44 | + out | |
| 45 | +} | |
| 46 | + | |
| 47 | +fn have_ffprobe() -> bool { | |
| 48 | + Command::new("ffprobe") | |
| 49 | + .arg("-version") | |
| 50 | + .output() | |
| 51 | + .map(|o| o.status.success()) | |
| 52 | + .unwrap_or(false) | |
| 53 | +} | |
| 54 | + | |
| 55 | +/// ffprobe's own packet count for the file's TrueHD stream, by absolute | |
| 56 | +/// stream index. | |
| 57 | +fn ffprobe_packet_count(path: &std::path::Path, stream: usize) -> Option<u64> { | |
| 58 | + let out = Command::new("ffprobe") | |
| 59 | + .args(["-v", "error", "-select_streams"]) | |
| 60 | + .arg(stream.to_string()) | |
| 61 | + .args([ | |
| 62 | + "-count_packets", | |
| 63 | + "-show_entries", | |
| 64 | + "stream=nb_read_packets", | |
| 65 | + "-of", | |
| 66 | + "csv=p=0", | |
| 67 | + ]) | |
| 68 | + .arg(path) | |
| 69 | + .output() | |
| 70 | + .ok()?; | |
| 71 | + if !out.status.success() { | |
| 72 | + return None; | |
| 73 | + } | |
| 74 | + String::from_utf8_lossy(&out.stdout).trim().parse().ok() | |
| 75 | +} | |
| 76 | + | |
| 77 | +#[test] | |
| 78 | +fn walks_every_truehd_access_unit_of_a_real_7_1_remux() { | |
| 79 | + let Some(path) = find_file() else { | |
| 80 | + eprintln!("skip: no 'ReelR ... TrueHD ...mkv' under ~/Downloads"); | |
| 81 | + return; | |
| 82 | + }; | |
| 83 | + | |
| 84 | + let file = File::open(&path).expect("open the file"); | |
| 85 | + let mut demux = MatroskaDemuxer::new(BufReader::new(file)).expect("open the container"); | |
| 86 | + | |
| 87 | + let track = demux | |
| 88 | + .streams() | |
| 89 | + .iter() | |
| 90 | + .find(|s| s.params.codec == CodecId::TrueHd) | |
| 91 | + .expect("a TrueHD track"); | |
| 92 | + let stream_index = track.index; | |
| 93 | + let audio = track.params.audio().expect("audio parameters"); | |
| 94 | + assert_eq!(audio.sample_rate, 48_000, "rate"); | |
| 95 | + assert_eq!(audio.layout.channel_count(), 8, "channels"); | |
| 96 | + // Matroska's `BitDepth` element is optional and this remux's TrueHD | |
| 97 | + // track does not carry one; report what the container states rather | |
| 98 | + // than asserting a value it never claimed. | |
| 99 | + eprintln!("container-reported bit depth: {:?}", audio.bits_per_sample); | |
| 100 | + | |
| 101 | + let mut au_count = 0u64; | |
| 102 | + let mut major_syncs = 0u64; | |
| 103 | + loop { | |
| 104 | + let packet = match demux.next_packet() { | |
| 105 | + Ok(p) => p, | |
| 106 | + Err(e) if e.is_eof() => break, | |
| 107 | + Err(e) => panic!("demux error: {e}"), | |
| 108 | + }; | |
| 109 | + if packet.stream != stream_index { | |
| 110 | + continue; | |
| 111 | + } | |
| 112 | + let header = AccessUnitHeader::parse(&packet.data) | |
| 113 | + .unwrap_or_else(|e| panic!("access unit {au_count}: {e}")); | |
| 114 | + assert_eq!( | |
| 115 | + header.length, | |
| 116 | + packet.data.len(), | |
| 117 | + "access unit {au_count} claims a length that does not match its packet" | |
| 118 | + ); | |
| 119 | + if header.major_sync.is_some() { | |
| 120 | + major_syncs += 1; | |
| 121 | + } | |
| 122 | + au_count += 1; | |
| 123 | + } | |
| 124 | + | |
| 125 | + eprintln!("{au_count} access units, {major_syncs} carrying a major sync"); | |
| 126 | + assert!(au_count > 0, "found no TrueHD access units at all"); | |
| 127 | + | |
| 128 | + if have_ffprobe() { | |
| 129 | + // Absolute demuxer stream index in the file, for ffprobe's own | |
| 130 | + // `-select_streams`: the track this family's stream list found. | |
| 131 | + let absolute = stream_index as usize; | |
| 132 | + if let Some(expected) = ffprobe_packet_count(&path, absolute) { | |
| 133 | + assert_eq!(au_count, expected, "AU count vs ffprobe's packet count"); | |
| 134 | + } else { | |
| 135 | + eprintln!("skip: ffprobe packet count unavailable for stream {absolute}"); | |
| 136 | + } | |
| 137 | + } else { | |
| 138 | + eprintln!("skip: ffprobe not on PATH, no oracle comparison"); | |
| 139 | + } | |
| 140 | +} |