forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBf44b458Tahinli3 months ago649 commits

sync.rs511 lines, 20.4 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) if w == MAJOR_SYNC_TRUEHD.to_be_bytes() || w == MAJOR_SYNC_MLP.to_be_bytes() => {
212 Some(MajorSyncInfo::parse(&au[4..])?)
213 }
214 _ => None,
215 };
216 let dir_start = AU_HEADER_LEN + if major_sync.is_some() { MAJOR_SYNC_LEN } else { 0 };
217
218 let mut substreams = Vec::new();
219 let mut pos = dir_start;
220 loop {
221 let word = au
222 .get(pos..pos + 2)
223 .ok_or(Error::NeedMore)?;
224 let word = u16::from_be_bytes([word[0], word[1]]);
225 let flags = (word >> 12) as u8;
226 let end_offset_words = word & 0x0FFF;
227 pos += 2;
228 let extra = if flags & 0x8 != 0 {
229 let w = au.get(pos..pos + 2).ok_or(Error::NeedMore)?;
230 pos += 2;
231 Some(u16::from_be_bytes([w[0], w[1]]))
232 } else {
233 None
234 };
235 substreams.push(SubstreamInfo {
236 flags,
237 end_offset_words,
238 extra,
239 });
240 if substreams.len() >= 4 {
241 return Err(Error::unsupported(
242 "TrueHD 4th (object/16-channel) substream",
243 "only the 2/6/8-channel PCM presentations are implemented",
244 ));
245 }
246 if pos + usize::from(end_offset_words) * 2 == length {
247 break;
248 }
249 if pos >= length {
250 return Err(Error::corrupt(
251 "TrueHD: substream directory did not sum to the access unit's length",
252 ));
253 }
254 }
255
256 Ok(AccessUnitHeader {
257 length,
258 input_timing,
259 major_sync,
260 data_start: pos,
261 substreams,
262 })
263 }
264
265 /// Byte span `(start, end)` of substream `i`'s coded data within the
266 /// access unit, from the directory's cumulative end pointers.
267 pub fn substream_span(&self, i: usize) -> (usize, usize) {
268 let start = if i == 0 {
269 self.data_start
270 } else {
271 self.data_start + usize::from(self.substreams[i - 1].end_offset_words) * 2
272 };
273 (start, self.data_start + usize::from(self.substreams[i].end_offset_words) * 2)
274 }
275
276 /// The channel layout Dolby's substream convention implies: substream 0
277 /// is always a 2-ch presentation, substream 1 (when present) a discrete
278 /// 5.1, substream 2 (when present) a discrete 7.1. [`parse`](Self::parse)
279 /// already refuses a 4th substream, so this never sees one.
280 pub fn channel_layout(&self) -> Result<ChannelLayout> {
281 match self.substreams.len() {
282 1 => Ok(ChannelLayout::Stereo),
283 2 => Ok(ChannelLayout::Surround5_1),
284 3 => Ok(ChannelLayout::Surround7_1),
285 n => Err(Error::corrupt(format!("TrueHD: {n} substreams"))),
286 }
287 }
288}
289
290/// A TrueHD/MLP decoder for one stream: access units in, one interleaved
291/// S32 (24-bit left-justified) [`AudioFrame`] of the highest presentation
292/// out per access unit. See the crate-level docs for scope.
293#[derive(Debug)]
294pub struct TrueHdDecoder {
295 params: CodecParameters,
296 core: crate::decode::Core,
297 pending: Option<AudioFrame>,
298}
299
300impl Default for TrueHdDecoder {
301 fn default() -> Self {
302 Self::new()
303 }
304}
305
306impl TrueHdDecoder {
307 /// A decoder with no stream state yet; TrueHD carries its own format
308 /// info in-band (the major sync), so there is no magic-cookie equivalent
309 /// to hand in up front.
310 pub fn new() -> TrueHdDecoder {
311 TrueHdDecoder {
312 params: CodecParameters::new(CodecId::TrueHd),
313 core: crate::decode::Core::new(),
314 pending: None,
315 }
316 }
317
318 /// The stream-side self-check tallies so far (restart CRC, parity,
319 /// lossless check); all stay zero on a clean decode.
320 pub fn check_stats(&self) -> crate::decode::CheckStats {
321 self.core.stats
322 }
323
324 /// One access unit in; one frame of the highest presentation out —
325 /// `None` until the first major sync and every substream's first
326 /// restart header have been seen.
327 pub fn push(&mut self, data: &[u8]) -> Result<Option<AudioFrame>> {
328 self.decode_access_unit(data)
329 }
330
331 /// See [`TrueHdDecoder::push`].
332 pub fn decode_access_unit(&mut self, data: &[u8]) -> Result<Option<AudioFrame>> {
333 let header = AccessUnitHeader::parse(data)?;
334 self.core.decode(&header, data)
335 }
336}
337
338impl Decoder for TrueHdDecoder {
339 fn codec_parameters(&self) -> &CodecParameters {
340 &self.params
341 }
342
343 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
344 if let Some(mut frame) = self.decode_access_unit(&packet.data)? {
345 frame.pts = packet
346 .pts
347 .map(|ticks| ec_core::timebase::Timestamp::new(ticks, packet.time_base));
348 self.pending = Some(frame);
349 }
350 Ok(())
351 }
352
353 fn receive_frame(&mut self) -> Result<Frame> {
354 self.pending.take().map(Frame::Audio).ok_or(Error::NeedMore)
355 }
356
357 fn flush(&mut self) -> Result<()> {
358 Ok(())
359 }
360
361 fn reset(&mut self) {
362 self.pending = None;
363 self.core.reset();
364 }
365}
366
367#[cfg(test)]
368mod tests {
369 use super::*;
370
371 /// A hand-built access unit with no major sync, one substream (a bare
372 /// 2-channel presentation): 4-byte header + a 2-byte directory entry +
373 /// 4 bytes of "coded data" nobody reads yet.
374 fn stereo_au() -> Vec<u8> {
375 vec![
376 0x30, 0x05, // check nibble 3, length 5 words (10 bytes)
377 0x12, 0x34, // input timing (uninterpreted)
378 0x00, 0x02, // substream 0: flags 0 (no extra word), end +2 words
379 0xAA, 0xBB, 0xCC, 0xDD, // "coded data"
380 ]
381 }
382
383 /// A hand-built access unit that does carry a major sync (TrueHD,
384 /// 48 kHz) and two substreams (a 5.1 presentation on top of the 2-ch
385 /// one).
386 fn surround51_au() -> Vec<u8> {
387 let mut au = vec![
388 0x50, 0x16, // check nibble 5, length 22 words (44 bytes)
389 0x00, 0x00, // input timing
390 ];
391 au.extend_from_slice(&MAJOR_SYNC_TRUEHD.to_be_bytes());
392 au.push(0x0F); // sample rate: group1 code 0 (48000), group2 0xF (absent)
393 au.extend(std::iter::repeat_n(0u8, 23)); // rest of the major sync, unused here
394 au.extend_from_slice(&[0x00, 0x01]); // substream 0: end +1 word (not the last)
395 au.extend_from_slice(&[0x00, 0x04]); // substream 1: end +4 words (lands on EOF)
396 au.extend_from_slice(&[0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
397 au
398 }
399
400 #[test]
401 fn frame_length_reads_the_16_bit_word() {
402 assert_eq!(frame_length(&stereo_au()).unwrap(), 10);
403 assert_eq!(frame_length(&surround51_au()).unwrap(), 44);
404 }
405
406 #[test]
407 fn frame_length_needs_two_bytes() {
408 assert!(matches!(frame_length(&[0x30]), Err(Error::NeedMore)));
409 assert!(matches!(frame_length(&[]), Err(Error::NeedMore)));
410 }
411
412 #[test]
413 fn parses_a_stereo_access_unit_with_no_major_sync() {
414 let au = AccessUnitHeader::parse(&stereo_au()).unwrap();
415 assert_eq!(au.length, 10);
416 assert_eq!(au.input_timing, 0x1234);
417 assert!(au.major_sync.is_none());
418 assert_eq!(au.substreams.len(), 1);
419 assert_eq!(au.channel_layout().unwrap(), ChannelLayout::Stereo);
420 }
421
422 #[test]
423 fn parses_a_5_1_access_unit_with_a_major_sync() {
424 let au = AccessUnitHeader::parse(&surround51_au()).unwrap();
425 assert_eq!(au.length, 44);
426 let sync = au.major_sync.expect("major sync detected");
427 assert_eq!(sync.format, MajorSyncFormat::TrueHd);
428 assert_eq!(sync.sample_rate, 48_000);
429 assert_eq!(au.substreams.len(), 2);
430 assert_eq!(au.channel_layout().unwrap(), ChannelLayout::Surround5_1);
431 }
432
433 #[test]
434 fn a_corrupted_major_sync_word_does_not_panic() {
435 let mut au = surround51_au();
436 // Flip a byte inside the format-sync word so it names neither
437 // TrueHD nor MLP; the directory walk that follows now reads
438 // major-sync bytes as if they were directory entries and cannot
439 // land on the access unit's real end, but must not panic.
440 au[5] = 0x00;
441 assert!(AccessUnitHeader::parse(&au).is_err());
442 }
443
444 #[test]
445 fn a_truncated_access_unit_is_need_more() {
446 let au = surround51_au();
447 // The header claims 44 bytes; hand over fewer.
448 assert!(matches!(
449 AccessUnitHeader::parse(&au[..20]),
450 Err(Error::NeedMore)
451 ));
452 }
453
454 #[test]
455 fn a_fourth_substream_is_named_unsupported() {
456 // A 20-byte access unit, followed by five directory entries whose
457 // end pointers never land on that length -- forces the walk past
458 // the 4-substream cap before it can terminate.
459 let mut au = vec![0x00, 0x0A, 0x00, 0x00]; // length 10 words = 20 bytes
460 for _ in 0..5 {
461 au.extend_from_slice(&[0x00, 0x01]);
462 }
463 au.resize(20, 0);
464 let err = AccessUnitHeader::parse(&au).unwrap_err();
465 assert!(matches!(err, Error::Unsupported { .. }), "{err:?}");
466 }
467
468 #[test]
469 fn a_well_formed_4_entry_directory_is_still_named_unsupported() {
470 // A 20-byte access unit whose directory has exactly 4 entries, the
471 // last of which lands squarely on the access unit's end (the
472 // well-formed object-audio shape, not a walk that overruns a
473 // malformed directory). This must be refused by name, not parsed as
474 // Ok(4) and only caught later in channel_layout().
475 let mut au = vec![0x00, 0x0A, 0x00, 0x00]; // length 10 words = 20 bytes
476 au.extend_from_slice(&[0x00, 0x01]); // substream 0: doesn't land on EOF yet
477 au.extend_from_slice(&[0x00, 0x01]); // substream 1: doesn't land on EOF yet
478 au.extend_from_slice(&[0x00, 0x01]); // substream 2: doesn't land on EOF yet
479 au.extend_from_slice(&[0x00, 0x04]); // substream 3: pos(12) + 4*2 == 20, lands on EOF
480 au.resize(20, 0);
481 let err = AccessUnitHeader::parse(&au).unwrap_err();
482 assert!(matches!(err, Error::Unsupported { .. }), "{err:?}");
483 }
484
485 #[test]
486 fn a_well_formed_3_entry_directory_still_parses() {
487 // Control for the test above: the same shape one entry shorter, its
488 // last pointer landing on the access unit's end, must still parse.
489 let mut au = vec![0x00, 0x0A, 0x00, 0x00]; // length 10 words = 20 bytes
490 au.extend_from_slice(&[0x00, 0x01]); // substream 0: doesn't land on EOF yet
491 au.extend_from_slice(&[0x00, 0x01]); // substream 1: doesn't land on EOF yet
492 au.extend_from_slice(&[0x00, 0x05]); // substream 2: pos(10) + 5*2 == 20, lands on EOF
493 au.resize(20, 0);
494 let parsed = AccessUnitHeader::parse(&au).unwrap();
495 assert_eq!(parsed.substreams.len(), 3);
496 assert_eq!(parsed.channel_layout().unwrap(), ChannelLayout::Surround7_1);
497 }
498
499 #[test]
500 fn decoder_yields_nothing_before_a_major_sync() {
501 let mut decoder = TrueHdDecoder::new();
502 assert_eq!(decoder.decode_access_unit(&stereo_au()).unwrap(), None);
503 }
504
505 #[test]
506 fn substream_spans_follow_the_directory() {
507 let au = AccessUnitHeader::parse(&surround51_au()).unwrap();
508 assert_eq!(au.substream_span(0), (36, 38));
509 assert_eq!(au.substream_span(1), (38, 44));
510 }
511}