forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b5376dTahinli2 months ago2535 commits

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