forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiB6c331afTahinli11 hours ago4261 commits

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