forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

sync.rs533 lines, 21.3 KiBHistoryRawDownload
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 (Atmos) carries an object-audio extension, which this build
52//! does not decode: it is located by its directory entry and skipped, so the
53//! PCM presentations are decoded exactly as they would be without it. That
54//! is the same backward-compatible shape ffmpeg's decoder uses. The count
55//! comes from the directory rather than the major sync's own channel-assignment
56//! bitfields, for the reason above.
57
58use ec_core::error::{Error, Result};
59use ec_core::frame::{AudioFrame, ChannelLayout, Frame};
60use ec_core::packet::Packet;
61use ec_core::registry::{CodecId, CodecParameters, Decoder};
62
63/// TrueHD's major sync word, immediately followed by the extension fields
64/// TrueHD adds over plain MLP.
65pub const MAJOR_SYNC_TRUEHD: u32 = 0xF872_6FBA;
66/// MLP's major sync word (lossless-only, no TrueHD extensions).
67pub const MAJOR_SYNC_MLP: u32 = 0xF872_6FBB;
68
69/// Bytes a major sync occupies, format id included, ending where the
70/// substream directory begins.
71const MAJOR_SYNC_LEN: usize = 28;
72
73/// Dolby's cap on substream directory entries per access unit: entries 0..=2
74/// are the 2-ch, 6-ch and 8-ch PCM presentations, entry 3 (when present) is
75/// the object-audio extension.
76const MAX_DIRECTORY_ENTRIES: usize = 4;
77/// How many leading directory entries are PCM presentations: the highest of
78/// them is the stream's output. Entries past this are not decoded.
79pub(crate) const PCM_SUBSTREAMS: usize = 3;
80
81/// Bytes the fixed part of an access unit's own header takes: the 16-bit
82/// length/check word and the 16-bit input timing.
83const AU_HEADER_LEN: usize = 4;
84
85/// Access-unit length in bytes, from the 16-bit length word at `data[0..2]`.
86///
87/// A short buffer is [`Error::NeedMore`]; a length that could not even cover
88/// its own 4-byte header is [`Error::Corrupt`].
89pub fn frame_length(data: &[u8]) -> Result<usize> {
90 if data.len() < 2 {
91 return Err(Error::NeedMore);
92 }
93 let word = u16::from_be_bytes([data[0], data[1]]);
94 let len = usize::from(word & 0x0FFF) * 2;
95 if len < AU_HEADER_LEN {
96 return Err(Error::corrupt(format!(
97 "TrueHD: {len}-byte access unit shorter than its own header"
98 )));
99 }
100 Ok(len)
101}
102
103/// Which format a major sync names.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum MajorSyncFormat {
106 /// `0xF8726FBA`.
107 TrueHd,
108 /// `0xF8726FBB`.
109 Mlp,
110}
111
112/// The format info an access unit's major sync carries.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub struct MajorSyncInfo {
115 /// Which sync word introduced it.
116 pub format: MajorSyncFormat,
117 /// The primary sample rate, decoded from `data[8]`'s high nibble.
118 pub sample_rate: u32,
119 /// The raw 4-bit rate code (`& 7` is the `2^n` multiplier, which also
120 /// sizes the access unit: `40 << n` samples).
121 pub rate_code: u8,
122 /// The 8-channel presentation's 13-bit channel-assignment mask (bit 0 =
123 /// L/R, 1 = C, 2 = LFE, 3 = Ls/Rs, 6 = Lrs/Rrs; `0x4F` is standard 7.1);
124 /// 0 when the major sync is plain MLP, which has no such field.
125 pub ch8_assignment: u16,
126}
127
128/// A rate code's `44.1k*2^n` / `48k*2^n` value, or [`Error::Unsupported`] for
129/// a code the format reserves.
130fn sample_rate(code: u8) -> Result<u32> {
131 match code {
132 0..=2 => Ok(48_000 << code),
133 8..=10 => Ok(44_100 << (code - 8)),
134 0xF => Ok(0), // "not present" (group2's usual value)
135 other => Err(Error::unsupported(
136 format!("TrueHD sample rate code {other}"),
137 "reserved by the format",
138 )),
139 }
140}
141
142impl MajorSyncInfo {
143 /// Parses the major sync starting at `data[0]` (the sync word itself),
144 /// i.e. `data` is `access_unit[4..]`.
145 fn parse(data: &[u8]) -> Result<MajorSyncInfo> {
146 if data.len() < MAJOR_SYNC_LEN {
147 return Err(Error::NeedMore);
148 }
149 let word = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
150 let format = match word {
151 MAJOR_SYNC_TRUEHD => MajorSyncFormat::TrueHd,
152 MAJOR_SYNC_MLP => MajorSyncFormat::Mlp,
153 _ => return Err(Error::corrupt("TrueHD: no major sync word")),
154 };
155 // TrueHD: format_info starts with the rate code; MLP puts its two
156 // 4-bit word-length codes first and the rate codes one byte later.
157 let rate_code = match format {
158 MajorSyncFormat::TrueHd => data[4] >> 4,
159 MajorSyncFormat::Mlp => data[5] >> 4,
160 };
161 let sample_rate = sample_rate(rate_code)?;
162 // format_info's last 13 bits: data[6] low 5 bits + data[7].
163 let ch8_assignment = match format {
164 MajorSyncFormat::TrueHd => (u16::from(data[6] & 0x1F) << 8) | u16::from(data[7]),
165 MajorSyncFormat::Mlp => 0,
166 };
167 Ok(MajorSyncInfo {
168 format,
169 sample_rate,
170 rate_code,
171 ch8_assignment,
172 })
173 }
174}
175
176/// One substream directory entry: where its coded data ends and whether a
177/// checksum/parity/DRC word rides along with the end pointer.
178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
179pub struct SubstreamInfo {
180 /// Raw 4-bit flag nibble; bit `0x8` is the only one this build interprets
181 /// (it gates [`SubstreamInfo::extra`]).
182 pub flags: u8,
183 /// Cumulative end offset of this substream's coded data, in 16-bit words
184 /// from the end of the substream directory.
185 pub end_offset_words: u16,
186 /// The second directory word, when `flags & 0x8` said one follows —
187 /// observed constant (DRC default) across a real substream's directory
188 /// entries; not decoded further.
189 pub extra: Option<u16>,
190}
191
192/// One access unit's header: its own length, optional major sync, and the
193/// substream directory that follows.
194#[derive(Debug, Clone, PartialEq, Eq)]
195pub struct AccessUnitHeader {
196 /// Total access-unit length in bytes, header included.
197 pub length: usize,
198 /// Input timing, carried uninterpreted.
199 pub input_timing: u16,
200 /// Present on roughly one access unit per video frame.
201 pub major_sync: Option<MajorSyncInfo>,
202 /// Byte offset where the substream directory ends and substream 0's
203 /// coded data begins.
204 pub data_start: usize,
205 /// One entry per substream, in stream order (`substreams.len()` is the
206 /// substream count).
207 pub substreams: Vec<SubstreamInfo>,
208}
209
210impl AccessUnitHeader {
211 /// Parses one access unit's header from `data`, which must hold at least
212 /// [`frame_length`]'s worth of bytes.
213 pub fn parse(data: &[u8]) -> Result<AccessUnitHeader> {
214 let length = frame_length(data)?;
215 if data.len() < length {
216 return Err(Error::NeedMore);
217 }
218 let au = &data[..length];
219 let input_timing = u16::from_be_bytes([au[2], au[3]]);
220
221 let major_sync = match au.get(4..8) {
222 Some(w)
223 if w == MAJOR_SYNC_TRUEHD.to_be_bytes() || w == MAJOR_SYNC_MLP.to_be_bytes() =>
224 {
225 Some(MajorSyncInfo::parse(&au[4..])?)
226 }
227 _ => None,
228 };
229 let dir_start = AU_HEADER_LEN
230 + if major_sync.is_some() {
231 MAJOR_SYNC_LEN
232 } else {
233 0
234 };
235
236 let mut substreams = Vec::new();
237 let mut pos = dir_start;
238 loop {
239 if substreams.len() == MAX_DIRECTORY_ENTRIES {
240 return Err(Error::corrupt(
241 "TrueHD: substream directory has more than 4 entries",
242 ));
243 }
244 let word = au.get(pos..pos + 2).ok_or(Error::NeedMore)?;
245 let word = u16::from_be_bytes([word[0], word[1]]);
246 let flags = (word >> 12) as u8;
247 let end_offset_words = word & 0x0FFF;
248 pos += 2;
249 let extra = if flags & 0x8 != 0 {
250 let w = au.get(pos..pos + 2).ok_or(Error::NeedMore)?;
251 pos += 2;
252 Some(u16::from_be_bytes([w[0], w[1]]))
253 } else {
254 None
255 };
256 substreams.push(SubstreamInfo {
257 flags,
258 end_offset_words,
259 extra,
260 });
261 if pos + usize::from(end_offset_words) * 2 == length {
262 break;
263 }
264 if pos >= length {
265 return Err(Error::corrupt(
266 "TrueHD: substream directory did not sum to the access unit's length",
267 ));
268 }
269 }
270
271 Ok(AccessUnitHeader {
272 length,
273 input_timing,
274 major_sync,
275 data_start: pos,
276 substreams,
277 })
278 }
279
280 /// Byte span `(start, end)` of substream `i`'s coded data within the
281 /// access unit, from the directory's cumulative end pointers.
282 pub fn substream_span(&self, i: usize) -> (usize, usize) {
283 let start = if i == 0 {
284 self.data_start
285 } else {
286 self.data_start + usize::from(self.substreams[i - 1].end_offset_words) * 2
287 };
288 (
289 start,
290 self.data_start + usize::from(self.substreams[i].end_offset_words) * 2,
291 )
292 }
293
294 /// The channel layout of the highest PCM presentation this access unit
295 /// carries: substream 0 is always a 2-ch presentation, substream 1 (when
296 /// present) a discrete 5.1, substream 2 (when present) a discrete 7.1.
297 /// A 4th entry (object audio, not decoded) does not change the answer:
298 /// the 7.1 presentation is still the highest PCM one.
299 pub fn channel_layout(&self) -> Result<ChannelLayout> {
300 match self.substreams.len() {
301 1 => Ok(ChannelLayout::Stereo),
302 2 => Ok(ChannelLayout::Surround5_1),
303 3 | 4 => Ok(ChannelLayout::Surround7_1),
304 n => Err(Error::corrupt(format!("TrueHD: {n} substreams"))),
305 }
306 }
307}
308
309/// A TrueHD/MLP decoder for one stream: access units in, one interleaved
310/// S32 (24-bit left-justified) [`AudioFrame`] of the highest presentation
311/// out per access unit. See the crate-level docs for scope.
312#[derive(Debug)]
313pub struct TrueHdDecoder {
314 params: CodecParameters,
315 core: crate::decode::Core,
316 pending: Option<AudioFrame>,
317}
318
319impl Default for TrueHdDecoder {
320 fn default() -> Self {
321 Self::new()
322 }
323}
324
325impl TrueHdDecoder {
326 /// A decoder with no stream state yet; TrueHD carries its own format
327 /// info in-band (the major sync), so there is no magic-cookie equivalent
328 /// to hand in up front.
329 pub fn new() -> TrueHdDecoder {
330 TrueHdDecoder {
331 params: CodecParameters::new(CodecId::TrueHd),
332 core: crate::decode::Core::new(),
333 pending: None,
334 }
335 }
336
337 /// The stream-side self-check tallies so far (restart CRC, parity,
338 /// lossless check); all stay zero on a clean decode.
339 pub fn check_stats(&self) -> crate::decode::CheckStats {
340 self.core.stats
341 }
342
343 /// One access unit in; one frame of the highest presentation out —
344 /// `None` until the first major sync and every substream's first
345 /// restart header have been seen.
346 pub fn push(&mut self, data: &[u8]) -> Result<Option<AudioFrame>> {
347 self.decode_access_unit(data)
348 }
349
350 /// See [`TrueHdDecoder::push`].
351 pub fn decode_access_unit(&mut self, data: &[u8]) -> Result<Option<AudioFrame>> {
352 let header = AccessUnitHeader::parse(data)?;
353 self.core.decode(&header, data)
354 }
355}
356
357impl Decoder for TrueHdDecoder {
358 fn codec_parameters(&self) -> &CodecParameters {
359 &self.params
360 }
361
362 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
363 if let Some(mut frame) = self.decode_access_unit(&packet.data)? {
364 frame.pts = packet
365 .pts
366 .map(|ticks| ec_core::timebase::Timestamp::new(ticks, packet.time_base));
367 self.pending = Some(frame);
368 }
369 Ok(())
370 }
371
372 fn receive_frame(&mut self) -> Result<Frame> {
373 self.pending.take().map(Frame::Audio).ok_or(Error::NeedMore)
374 }
375
376 fn flush(&mut self) -> Result<()> {
377 Ok(())
378 }
379
380 fn reset(&mut self) {
381 self.pending = None;
382 self.core.reset();
383 }
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389
390 /// A hand-built access unit with no major sync, one substream (a bare
391 /// 2-channel presentation): 4-byte header + a 2-byte directory entry +
392 /// 4 bytes of "coded data" nobody reads yet.
393 fn stereo_au() -> Vec<u8> {
394 vec![
395 0x30, 0x05, // check nibble 3, length 5 words (10 bytes)
396 0x12, 0x34, // input timing (uninterpreted)
397 0x00, 0x02, // substream 0: flags 0 (no extra word), end +2 words
398 0xAA, 0xBB, 0xCC, 0xDD, // "coded data"
399 ]
400 }
401
402 /// A hand-built access unit that does carry a major sync (TrueHD,
403 /// 48 kHz) and two substreams (a 5.1 presentation on top of the 2-ch
404 /// one).
405 fn surround51_au() -> Vec<u8> {
406 let mut au = vec![
407 0x50, 0x16, // check nibble 5, length 22 words (44 bytes)
408 0x00, 0x00, // input timing
409 ];
410 au.extend_from_slice(&MAJOR_SYNC_TRUEHD.to_be_bytes());
411 au.push(0x0F); // sample rate: group1 code 0 (48000), group2 0xF (absent)
412 au.extend(std::iter::repeat_n(0u8, 23)); // rest of the major sync, unused here
413 au.extend_from_slice(&[0x00, 0x01]); // substream 0: end +1 word (not the last)
414 au.extend_from_slice(&[0x00, 0x04]); // substream 1: end +4 words (lands on EOF)
415 au.extend_from_slice(&[0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
416 au
417 }
418
419 #[test]
420 fn frame_length_reads_the_16_bit_word() {
421 assert_eq!(frame_length(&stereo_au()).unwrap(), 10);
422 assert_eq!(frame_length(&surround51_au()).unwrap(), 44);
423 }
424
425 #[test]
426 fn frame_length_needs_two_bytes() {
427 assert!(matches!(frame_length(&[0x30]), Err(Error::NeedMore)));
428 assert!(matches!(frame_length(&[]), Err(Error::NeedMore)));
429 }
430
431 #[test]
432 fn parses_a_stereo_access_unit_with_no_major_sync() {
433 let au = AccessUnitHeader::parse(&stereo_au()).unwrap();
434 assert_eq!(au.length, 10);
435 assert_eq!(au.input_timing, 0x1234);
436 assert!(au.major_sync.is_none());
437 assert_eq!(au.substreams.len(), 1);
438 assert_eq!(au.channel_layout().unwrap(), ChannelLayout::Stereo);
439 }
440
441 #[test]
442 fn parses_a_5_1_access_unit_with_a_major_sync() {
443 let au = AccessUnitHeader::parse(&surround51_au()).unwrap();
444 assert_eq!(au.length, 44);
445 let sync = au.major_sync.expect("major sync detected");
446 assert_eq!(sync.format, MajorSyncFormat::TrueHd);
447 assert_eq!(sync.sample_rate, 48_000);
448 assert_eq!(au.substreams.len(), 2);
449 assert_eq!(au.channel_layout().unwrap(), ChannelLayout::Surround5_1);
450 }
451
452 #[test]
453 fn a_corrupted_major_sync_word_does_not_panic() {
454 let mut au = surround51_au();
455 // Flip a byte inside the format-sync word so it names neither
456 // TrueHD nor MLP; the directory walk that follows now reads
457 // major-sync bytes as if they were directory entries and cannot
458 // land on the access unit's real end, but must not panic.
459 au[5] = 0x00;
460 assert!(AccessUnitHeader::parse(&au).is_err());
461 }
462
463 #[test]
464 fn a_truncated_access_unit_is_need_more() {
465 let au = surround51_au();
466 // The header claims 44 bytes; hand over fewer.
467 assert!(matches!(
468 AccessUnitHeader::parse(&au[..20]),
469 Err(Error::NeedMore)
470 ));
471 }
472
473 #[test]
474 fn a_directory_past_four_entries_is_corrupt() {
475 // A 20-byte access unit, followed by five directory entries whose
476 // end pointers never land on that length -- forces the walk past
477 // the 4-entry cap before it can terminate.
478 let mut au = vec![0x00, 0x0A, 0x00, 0x00]; // length 10 words = 20 bytes
479 for _ in 0..5 {
480 au.extend_from_slice(&[0x00, 0x01]);
481 }
482 au.resize(20, 0);
483 let err = AccessUnitHeader::parse(&au).unwrap_err();
484 assert!(matches!(err, Error::Corrupt { .. }), "{err:?}");
485 }
486
487 #[test]
488 fn a_well_formed_4_entry_directory_parses_with_7_1_on_top() {
489 // A 20-byte access unit whose directory has exactly 4 entries, the
490 // last of which lands squarely on the access unit's end: the Atmos
491 // shape. Entry 3 is the object-audio substream and is not decoded;
492 // the highest PCM presentation is still entry 2's 8-ch (7.1), and
493 // that is what channel_layout() reports.
494 let mut au = vec![0x00, 0x0A, 0x00, 0x00]; // length 10 words = 20 bytes
495 au.extend_from_slice(&[0x00, 0x01]); // substream 0: doesn't land on EOF yet
496 au.extend_from_slice(&[0x00, 0x01]); // substream 1: doesn't land on EOF yet
497 au.extend_from_slice(&[0x00, 0x01]); // substream 2: doesn't land on EOF yet
498 au.extend_from_slice(&[0x00, 0x04]); // substream 3: pos(12) + 4*2 == 20, lands on EOF
499 au.resize(20, 0);
500 let parsed = AccessUnitHeader::parse(&au).unwrap();
501 assert_eq!(parsed.substreams.len(), 4);
502 // Entry 3's coded data is the object-audio span the decoder skips.
503 assert_eq!(parsed.substream_span(3), (14, 20));
504 assert_eq!(parsed.channel_layout().unwrap(), ChannelLayout::Surround7_1);
505 }
506
507 #[test]
508 fn a_well_formed_3_entry_directory_still_parses() {
509 // Control for the test above: the same shape one entry shorter, its
510 // last pointer landing on the access unit's end, must still parse.
511 let mut au = vec![0x00, 0x0A, 0x00, 0x00]; // length 10 words = 20 bytes
512 au.extend_from_slice(&[0x00, 0x01]); // substream 0: doesn't land on EOF yet
513 au.extend_from_slice(&[0x00, 0x01]); // substream 1: doesn't land on EOF yet
514 au.extend_from_slice(&[0x00, 0x05]); // substream 2: pos(10) + 5*2 == 20, lands on EOF
515 au.resize(20, 0);
516 let parsed = AccessUnitHeader::parse(&au).unwrap();
517 assert_eq!(parsed.substreams.len(), 3);
518 assert_eq!(parsed.channel_layout().unwrap(), ChannelLayout::Surround7_1);
519 }
520
521 #[test]
522 fn decoder_yields_nothing_before_a_major_sync() {
523 let mut decoder = TrueHdDecoder::new();
524 assert_eq!(decoder.decode_access_unit(&stereo_au()).unwrap(), None);
525 }
526
527 #[test]
528 fn substream_spans_follow_the_directory() {
529 let au = AccessUnitHeader::parse(&surround51_au()).unwrap();
530 assert_eq!(au.substream_span(0), (36, 38));
531 assert_eq!(au.substream_span(1), (38, 44));
532 }
533}