forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

atmos_synth.rs315 lines, 12.0 KiBHistoryRawDownload
1//! Atmos backward compatibility, tested on a synthetic 4-substream stream.
2//!
3//! No real Atmos TrueHD stream is available to this build, so the stream is
4//! built from the real 7.1 Blu-ray remux's own access units (the first
5//! [`AUS`] of its TrueHD track, 3 substreams each). For every access unit,
6//! [`with_object_substream`] rebuilds it with a 4th directory entry: the
7//! object-audio substream, here a run of [`FILLER_WORDS`] stand-in words
8//! appended after substream 2's coded data. The rebuilt access unit is:
9//!
10//! - header: length word (new word count, parity nibble recomputed) and the
11//! original input timing;
12//! - major sync, when the original has one: `num_substreams` (top nibble of
13//! byte 16) set to 4, and the major sync's own CRC-16 (bytes 26..28)
14//! recomputed;
15//! - directory: the original three entries unchanged (their cumulative end
16//! pointers are relative to the directory end, so the coded data they name
17//! does not move relative to it), then a fourth entry whose end pointer is
18//! the old last pointer plus the filler length;
19//! - substream data: the original substreams 0..2 bytes verbatim, then the
20//! filler.
21//!
22//! Decoding the synthetic stream must therefore equal decoding the original
23//! bit-exactly: the 8-channel (7.1) presentation is the one decoded and
24//! output, substream 3 is skipped via its end pointer, and the parity and
25//! checksum of substreams 0..2 are still checked. Object audio itself is out
26//! of scope and never decoded, so the filler's contents must not matter; a
27//! second test checks that.
28//!
29//! Optional cross-check: with `EC_ATMOS_SYNTH_OUT=<path>` set, the synthetic
30//! access units are also written there as a raw TrueHD elementary stream, so
31//! `ffmpeg -f truehd -i <path> -f s32le` can be compared against this
32//! decoder's output (ffmpeg decodes the same 8-channel presentation).
33//!
34//! Needs the 7.1 remux under `~/Downloads`. Absent, the tests skip loudly; with
35//! `EC_REQUIRE_FIXTURES=1` an absent remux is a hard failure.
36
37use std::fs::File;
38use std::io::BufReader;
39use std::path::{Path, PathBuf};
40
41use ec_core::CodecId;
42use ec_core::Demuxer;
43use ec_core::frame::ChannelLayout;
44use ec_matroska::MatroskaDemuxer;
45use ec_truehd::TrueHdDecoder;
46use ec_truehd::sync::AccessUnitHeader;
47
48/// Access units taken from the start of the remux: 1 s of 48 kHz audio, one
49/// major sync among them.
50const AUS: usize = 1200;
51/// Length of the object-audio stand-in, in 16-bit words.
52const FILLER_WORDS: u16 = 4;
53/// The 12-bit access-unit length word's maximum, in 16-bit words.
54const MAX_AU_WORDS: usize = 0x0FFF;
55const MAJOR_SYNC_LEN: usize = 28;
56
57fn find_file() -> Option<PathBuf> {
58 fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
59 let Ok(entries) = std::fs::read_dir(dir) else {
60 return;
61 };
62 for e in entries.flatten() {
63 let p = e.path();
64 if p.is_dir() {
65 walk(&p, out);
66 } else {
67 out.push(p);
68 }
69 }
70 }
71 let home = std::env::var("HOME").ok()?;
72 let mut all = Vec::new();
73 walk(&PathBuf::from(home).join("Downloads"), &mut all);
74 all.into_iter().find(|p| {
75 p.file_name()
76 .and_then(|n| n.to_str())
77 .is_some_and(|n| n.contains("ReelR") && n.ends_with(".mkv"))
78 })
79}
80
81/// The first [`AUS`] access units of the remux's TrueHD track, or `None`
82/// (after a loud skip, or a hard failure under `EC_REQUIRE_FIXTURES`).
83fn truehd_access_units() -> Option<Vec<Vec<u8>>> {
84 let Some(path) = find_file() else {
85 assert!(
86 std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
87 "EC_REQUIRE_FIXTURES=1 but the 7.1 TrueHD remux is absent under ~/Downloads"
88 );
89 eprintln!("skip: no 'ReelR ... TrueHD ...mkv' under ~/Downloads");
90 return None;
91 };
92 let file = File::open(&path).expect("open the remux");
93 let mut demux = MatroskaDemuxer::new(BufReader::new(file)).expect("open the container");
94 let stream_index = demux
95 .streams()
96 .iter()
97 .find(|s| s.params.codec == CodecId::TrueHd)
98 .expect("a TrueHD track")
99 .index;
100 let mut aus = Vec::with_capacity(AUS);
101 while aus.len() < AUS {
102 let packet = match demux.next_packet() {
103 Ok(p) => p,
104 Err(e) if e.is_eof() => break,
105 Err(e) => panic!("demux error: {e}"),
106 };
107 if packet.stream == stream_index {
108 aus.push(packet.data.as_ref().to_vec());
109 }
110 }
111 assert_eq!(
112 aus.len(),
113 AUS,
114 "the remux has at least {AUS} TrueHD access units"
115 );
116 Some(aus)
117}
118
119/// The major sync's CRC-16 (poly `0x002D`, MSB-first table form), the same
120/// one the crate's encoder writes and ffmpeg checks.
121fn crc16_table() -> [u32; 256] {
122 let mut table = [0u32; 256];
123 for (i, entry) in table.iter_mut().enumerate() {
124 let mut c = (i as i32) << 24;
125 for _ in 0..8 {
126 let overflow = c >> 31;
127 c = (c << 1) ^ ((0x002D_i32 << 16) & overflow);
128 }
129 *entry = (c as u32).swap_bytes();
130 }
131 table
132}
133
134/// The major sync's checksum field value: CRC-16 over bytes `0..24`, XORed
135/// with the little-endian word at `24..26`, stored little-endian at `26..28`.
136fn major_sync_checksum(sync: &[u8]) -> u16 {
137 let table = crc16_table();
138 let mut crc: u32 = 0;
139 for &b in &sync[..24] {
140 crc = table[usize::from((crc as u8) ^ b)] ^ (crc >> 8);
141 }
142 (crc as u16) ^ u16::from_le_bytes([sync[24], sync[25]])
143}
144
145/// The access-unit header's parity fold: the 4 header bytes and every
146/// directory byte, XORed together, must leave a nibble pair that is bitwise
147/// complementary (`((p >> 4) ^ p) & 0xF == 0xF`).
148fn parity_ok(header: &[u8], directory: &[u8]) -> bool {
149 let p = header.iter().chain(directory).fold(0u8, |a, &b| a ^ b);
150 ((p >> 4) ^ p) & 0xF == 0xF
151}
152
153/// Rebuilds one access unit of the 7.1 remux with a 4th (object-audio)
154/// directory entry whose coded data is `FILLER_WORDS` words of `filler`.
155fn with_object_substream(au: &[u8], filler: u8) -> Vec<u8> {
156 let header = AccessUnitHeader::parse(au).expect("the original access unit parses");
157 assert_eq!(
158 header.substreams.len(),
159 3,
160 "the remux is a 3-substream 7.1 stream"
161 );
162 let sync_len = if header.major_sync.is_some() {
163 MAJOR_SYNC_LEN
164 } else {
165 0
166 };
167 let dir_start = 4 + sync_len;
168 let old_dir = &au[dir_start..header.data_start];
169 let old_last_end = header.substreams[2].end_offset_words;
170 let new_last_end = old_last_end + FILLER_WORDS;
171
172 // The original directory bytes are reused verbatim. The new entry is a
173 // plain 2-byte word: no extra word, no check data, and the non-restart bit
174 // (0x4) copied from substream 2. That bit is set exactly on access units
175 // without a major sync, and ffmpeg rejects an entry that disagrees with
176 // the access unit's major sync. Its end pointer is cumulative.
177 let nonrestart = header.substreams[2].flags & 0x4;
178 let mut dir = old_dir.to_vec();
179 let entry = (u16::from(nonrestart) << 12) | new_last_end;
180 dir.extend_from_slice(&entry.to_be_bytes());
181
182 let coded = &au[header.data_start..header.length];
183 let filler_bytes = usize::from(FILLER_WORDS) * 2;
184
185 let mut body = Vec::new();
186 if header.major_sync.is_some() {
187 let mut sync = au[4..4 + MAJOR_SYNC_LEN].to_vec();
188 assert_eq!(
189 u16::from_le_bytes([sync[26], sync[27]]),
190 major_sync_checksum(&sync),
191 "the remux's major sync checksum matches the formula"
192 );
193 sync[16] = (sync[16] & 0x0F) | (4 << 4); // num_substreams = 4
194 let checksum = major_sync_checksum(&sync);
195 sync[26..28].copy_from_slice(&checksum.to_le_bytes());
196 body.extend_from_slice(&sync);
197 }
198 body.extend_from_slice(&dir);
199 body.extend_from_slice(coded);
200 body.extend(std::iter::repeat_n(filler, filler_bytes));
201
202 let total = 4 + body.len();
203 let words = total / 2;
204 assert!(words <= MAX_AU_WORDS, "synthetic access unit too long");
205 let timing = [au[2], au[3]];
206 // The parity nibble is the one value that makes the fold complementary.
207 let nibble = (0u8..16)
208 .find(|&cn| {
209 let len_hi = (words >> 8) as u8 & 0x0F;
210 let len_lo = (words & 0xFF) as u8;
211 let head = [(cn << 4) | len_hi, len_lo, timing[0], timing[1]];
212 parity_ok(&head, &dir)
213 })
214 .expect("one of the 16 nibble values satisfies the fold");
215 let word = (u16::from(nibble) << 12) | words as u16;
216
217 // Sanity: the same fold rule holds for the original access unit.
218 assert!(
219 parity_ok(&au[..4], old_dir),
220 "the remux's own parity fold holds"
221 );
222
223 let mut out = Vec::with_capacity(total);
224 out.extend_from_slice(&word.to_be_bytes());
225 out.extend_from_slice(&timing);
226 out.extend_from_slice(&body);
227 out
228}
229
230/// One decoded frame: its layout and its planes.
231type Decoded = Vec<(ChannelLayout, Vec<Vec<u8>>)>;
232
233/// Decodes `aus` with a fresh decoder and returns every output frame's planes
234/// plus the decoder's self-check tallies.
235fn decode_all(aus: &[Vec<u8>]) -> (Decoded, ec_truehd::CheckStats) {
236 let mut decoder = TrueHdDecoder::new();
237 let mut frames = Vec::new();
238 for au in aus {
239 if let Some(frame) = decoder.push(au).expect("access unit decodes") {
240 let planes = frame.data.iter().map(|b| b.as_ref().to_vec()).collect();
241 frames.push((frame.layout, planes));
242 }
243 }
244 (frames, decoder.check_stats())
245}
246
247#[test]
248fn synthetic_atmos_decodes_bit_exact_to_the_original_7_1() {
249 let Some(originals) = truehd_access_units() else {
250 return;
251 };
252 let synthetic: Vec<Vec<u8>> = originals
253 .iter()
254 .map(|au| with_object_substream(au, 0xA5))
255 .collect();
256
257 for au in &synthetic {
258 let header = AccessUnitHeader::parse(au).expect("synthetic access unit parses");
259 assert_eq!(header.substreams.len(), 4, "a 4-entry directory");
260 assert_eq!(
261 header.channel_layout().expect("a layout"),
262 ChannelLayout::Surround7_1,
263 "the 8-ch presentation is the top PCM one"
264 );
265 }
266
267 if let Some(out) = std::env::var_os("EC_ATMOS_SYNTH_OUT") {
268 let raw: Vec<u8> = synthetic.iter().flatten().copied().collect();
269 std::fs::write(&out, raw).expect("write the synthetic TrueHD stream");
270 eprintln!("wrote synthetic stream to {}", Path::new(&out).display());
271 }
272
273 let (ours, _) = decode_all(&originals);
274 let (synth, stats) = decode_all(&synthetic);
275 assert!(!ours.is_empty(), "the original stream decodes to frames");
276 assert_eq!(synth.len(), ours.len(), "same number of frames");
277 for (i, ((la, pa), (lb, pb))) in ours.iter().zip(&synth).enumerate() {
278 assert_eq!(*la, ChannelLayout::Surround7_1, "frame {i} is 7.1");
279 assert_eq!(*lb, ChannelLayout::Surround7_1, "frame {i} is 7.1");
280 assert_eq!(pa, pb, "frame {i} differs from the original");
281 }
282 eprintln!(
283 "{} frames, 8-channel, bit-exact vs the original",
284 ours.len()
285 );
286
287 // The PCM substreams' own checks still run on the synthetic stream.
288 assert_eq!(stats.parity_failures, 0, "substream parity");
289 assert_eq!(stats.restart_crc_failures, 0, "restart header CRC");
290 assert_eq!(stats.lossless_check_failures, 0, "lossless check");
291 assert_eq!(stats.length_mismatches, 0, "substream lengths");
292}
293
294#[test]
295fn object_substream_contents_do_not_change_the_pcm_output() {
296 let Some(originals) = truehd_access_units() else {
297 return;
298 };
299 // Filler bytes are never read, so any value must decode identically.
300 let zeros: Vec<Vec<u8>> = originals
301 .iter()
302 .map(|au| with_object_substream(au, 0x00))
303 .collect();
304 let ones: Vec<Vec<u8>> = originals
305 .iter()
306 .map(|au| with_object_substream(au, 0xFF))
307 .collect();
308 let (a, _) = decode_all(&zeros);
309 let (b, _) = decode_all(&ones);
310 assert!(!a.is_empty());
311 assert_eq!(
312 a, b,
313 "the object substream's bytes are skipped, not decoded"
314 );
315}