forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

ffmpeg_exact.rs385 lines, 13.2 KiBHistoryRawDownload
1#![allow(clippy::chunks_exact_to_as_chunks, clippy::manual_is_multiple_of)]
2//! Sample-for-sample equality with ffmpeg's DTS decoder (integer path,
3//! `-flags +bitexact`) on the committed fixtures in `fixtures/`, and the
4//! stream-layout, header and DTS-HD behaviours that follow from them.
5//!
6//! The fixtures are made with ffmpeg's own DTS encoder (`-c:a dca -strict
7//! -2`): stereo and mono tones, a mono sweep at 32 kHz, 5.1 tones at 44.1
8//! kHz and 5.1 noise with ADPCM at 48 kHz. Each is decoded here and by
9//! ffmpeg and every 24-bit sample must be equal. ffmpeg is test tooling and
10//! is driven through `std::process`; without it the comparison skips loudly.
11//! The fixtures themselves are required: a missing one fails.
12//!
13//! The 14-bit and little-endian stream layouts are derived from the same
14//! fixtures here and must decode to identical samples.
15
16use std::path::{Path, PathBuf};
17use std::process::Command;
18
19use ec_core::{Decoder, Error};
20use ec_dts::{DtsDecoder, Options, StreamFormat};
21
22fn fixtures() -> PathBuf {
23 Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures")
24}
25
26fn fixture_names() -> Vec<String> {
27 let mut v: Vec<String> = std::fs::read_dir(fixtures())
28 .expect("fixtures dir")
29 .flatten()
30 .map(|e| e.file_name().to_string_lossy().into_owned())
31 .filter(|n| n.ends_with(".dts"))
32 .collect();
33 v.sort();
34 assert!(!v.is_empty(), "no DTS fixtures");
35 v
36}
37
38fn have_ffmpeg() -> bool {
39 Command::new("ffmpeg")
40 .arg("-version")
41 .output()
42 .map(|o| o.status.success())
43 .unwrap_or(false)
44}
45
46/// Split a BE16 elementary stream into its core frames.
47fn frames(data: &[u8]) -> Vec<&[u8]> {
48 let mut out = Vec::new();
49 let mut pos = 0;
50 while pos + 4 <= data.len() {
51 let Some((s, _)) = ec_dts::find_sync(&data[pos..]) else {
52 break;
53 };
54 pos += s;
55 let Ok(size) = ec_dts::frame_size(&data[pos..]) else {
56 break;
57 };
58 if pos + size > data.len() {
59 break;
60 }
61 out.push(&data[pos..pos + size]);
62 pos += size;
63 }
64 out
65}
66
67/// Decode a sequence of frames to interleaved 24-bit integers.
68fn decode_ours(frames: &[Vec<u8>]) -> (Vec<i32>, usize, u32) {
69 let mut dec = DtsDecoder::new();
70 let mut out = Vec::new();
71 let mut channels = 0;
72 let mut rate = 0;
73 for f in frames {
74 let a = dec.decode_frame(f).expect("decode");
75 channels = a.layout.channel_count();
76 rate = a.rate;
77 for c in a.data[0].chunks_exact(4) {
78 let v = f32::from_le_bytes([c[0], c[1], c[2], c[3]]);
79 out.push((v as f64 * 8388608.0).round() as i32);
80 }
81 }
82 (out, channels, rate)
83}
84
85fn decode_ffmpeg(path: &Path) -> Vec<i32> {
86 let out = Command::new("ffmpeg")
87 .args(["-v", "error", "-nostdin", "-flags", "+bitexact", "-i"])
88 .arg(path)
89 .args(["-f", "s32le", "-"])
90 .output()
91 .expect("run ffmpeg");
92 assert!(
93 out.status.success(),
94 "ffmpeg {}: {}",
95 path.display(),
96 String::from_utf8_lossy(&out.stderr)
97 );
98 out.stdout
99 .chunks_exact(4)
100 .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) >> 8)
101 .collect()
102}
103
104/// Re-pack canonical frames into another stream layout.
105fn to_layout(frame: &[u8], format: StreamFormat) -> Vec<u8> {
106 match format {
107 StreamFormat::Be16 => frame.to_vec(),
108 StreamFormat::Le16 => {
109 let mut v = frame.to_vec();
110 for c in v.chunks_exact_mut(2) {
111 c.swap(0, 1);
112 }
113 v
114 }
115 StreamFormat::Be14 | StreamFormat::Le14 => {
116 let mut out = Vec::new();
117 let mut acc: u32 = 0;
118 let mut n = 0u32;
119 let push = |w14: u16, out: &mut Vec<u8>| {
120 // The two top bits of each word extend the 14-bit value's sign.
121 let w = if w14 & 0x2000 != 0 { w14 | 0xC000 } else { w14 };
122 if format == StreamFormat::Be14 {
123 out.extend_from_slice(&w.to_be_bytes());
124 } else {
125 out.extend_from_slice(&w.to_le_bytes());
126 }
127 };
128 for &b in frame {
129 acc = (acc << 8) | b as u32;
130 n += 8;
131 while n >= 14 {
132 push(((acc >> (n - 14)) & 0x3FFF) as u16, &mut out);
133 n -= 14;
134 }
135 acc &= (1 << n) - 1;
136 }
137 if n > 0 {
138 push(((acc << (14 - n)) & 0x3FFF) as u16, &mut out);
139 }
140 out
141 }
142 }
143}
144
145#[test]
146fn fixtures_are_bit_exact_against_ffmpeg() {
147 let ff = have_ffmpeg();
148 if !ff {
149 eprintln!("skip comparison: ffmpeg not on PATH");
150 }
151 for name in fixture_names() {
152 let path = fixtures().join(&name);
153 let data = std::fs::read(&path).unwrap();
154 let fr: Vec<Vec<u8>> = frames(&data).iter().map(|f| f.to_vec()).collect();
155 assert!(fr.len() > 5, "{name}: frames");
156 let (ours, channels, rate) = decode_ours(&fr);
157 assert!(!ours.is_empty());
158 let peak = ours.iter().map(|v| v.abs()).max().unwrap();
159 assert!(peak > 1000, "{name}: decoded silence (peak {peak})");
160 if ff {
161 let reference = decode_ffmpeg(&path);
162 assert_eq!(ours.len(), reference.len(), "{name}: sample count");
163 let bad = ours.iter().zip(&reference).position(|(a, b)| a != b);
164 assert_eq!(
165 bad,
166 None,
167 "{name}: first mismatch at sample {bad:?} (channel {:?})",
168 bad.map(|i| i % channels)
169 );
170 eprintln!(
171 "{name}: {channels} ch, {rate} Hz, {} samples/ch, bit-exact vs ffmpeg",
172 ours.len() / channels
173 );
174 }
175 }
176}
177
178#[test]
179fn stream_layouts_decode_identically() {
180 let ff = have_ffmpeg();
181 let tmp = std::env::temp_dir().join(format!("ec-dts-layouts-{}", std::process::id()));
182 std::fs::create_dir_all(&tmp).unwrap();
183 for name in fixture_names() {
184 let data = std::fs::read(fixtures().join(&name)).unwrap();
185 let base: Vec<Vec<u8>> = frames(&data).iter().map(|f| f.to_vec()).collect();
186 let (want, _, _) = decode_ours(&base);
187 for fmt in [StreamFormat::Le16, StreamFormat::Be14, StreamFormat::Le14] {
188 let conv: Vec<Vec<u8>> = base.iter().map(|f| to_layout(f, fmt)).collect();
189 // Header API sees through the layout.
190 let h0 = ec_dts::parse_frame_header(&base[0]).unwrap();
191 let h1 = ec_dts::parse_frame_header(&conv[0]).unwrap();
192 assert_eq!(h1.format, fmt, "{name} {fmt:?}");
193 assert_eq!(
194 (h0.sample_rate, h0.channels, h0.samples_per_frame, h0.frame_size),
195 (h1.sample_rate, h1.channels, h1.samples_per_frame, h1.frame_size),
196 "{name} {fmt:?}"
197 );
198 assert_eq!(conv[0].len(), h1.stream_frame_size, "{name} {fmt:?}: stored size");
199 let (got, _, _) = decode_ours(&conv);
200 assert_eq!(got, want, "{name} {fmt:?}: samples differ from BE16");
201 if ff {
202 let p = tmp.join(format!("{name}.{fmt:?}.dts"));
203 std::fs::write(&p, conv.concat()).unwrap();
204 let reference = decode_ffmpeg(&p);
205 let n = want.len().min(reference.len());
206 assert!(n > want.len() / 2, "{name} {fmt:?}: ffmpeg decoded too little");
207 assert_eq!(&reference[..n], &want[..n], "{name} {fmt:?}: vs ffmpeg");
208 }
209 }
210 }
211 let _ = std::fs::remove_dir_all(&tmp);
212}
213
214#[test]
215fn header_api_states_the_stream() {
216 let expect = [
217 ("noise-51-adpcm-48k.dts", 48_000, 6, 1),
218 ("sweep-mono-32k.dts", 32_000, 1, 0),
219 ("tone-stereo-48k.dts", 48_000, 2, 1),
220 ("tones-51-44k.dts", 44_100, 6, 1),
221 ];
222 for (name, rate, channels, lfe) in expect {
223 let data = std::fs::read(fixtures().join(name)).unwrap();
224 let h = ec_dts::parse_frame_header(&data).unwrap();
225 assert_eq!(h.sample_rate, rate, "{name}");
226 assert_eq!(h.channels as usize, channels, "{name}");
227 assert_eq!(h.samples_per_frame % 256, 0, "{name}");
228 assert_eq!(h.format, StreamFormat::Be16);
229 assert_eq!(ec_dts::frame_size(&data).unwrap(), h.frame_size);
230 let _ = lfe;
231 // A frame is exactly followed by the next sync word.
232 let next = &data[h.frame_size..];
233 assert_eq!(&next[..4], &data[..4], "{name}: next frame");
234 }
235 // Probe behaviour on junk and short input.
236 assert!(matches!(ec_dts::parse_frame_header(&[0x7F, 0xFE]), Err(Error::NeedMore)));
237 assert!(matches!(
238 ec_dts::parse_frame_header(&[0u8; 32]),
239 Err(Error::Corrupt { .. })
240 ));
241}
242
243/// MSB-first bit writer for the hand-built DTS-HD substream.
244struct Bw {
245 bytes: Vec<u8>,
246 nbits: usize,
247}
248
249impl Bw {
250 fn new() -> Bw {
251 Bw {
252 bytes: Vec::new(),
253 nbits: 0,
254 }
255 }
256 fn put(&mut self, v: u64, n: usize) {
257 for i in (0..n).rev() {
258 if self.nbits % 8 == 0 {
259 self.bytes.push(0);
260 }
261 let bit = ((v >> i) & 1) as u8;
262 *self.bytes.last_mut().unwrap() |= bit << (7 - self.nbits % 8);
263 self.nbits += 1;
264 }
265 }
266 fn align(&mut self) {
267 self.nbits = self.bytes.len() * 8;
268 }
269}
270
271/// An extension substream with one asset whose only component is XLL, built
272/// by hand from the header syntax (no static fields, no metadata).
273fn exss_with_xll(payload: usize) -> Vec<u8> {
274 // Asset descriptor: size 9, index 3, drc 1, dialnorm 1, coding mode 2,
275 // xll size 16, xll sync present 1, hd stream id 3 -> 36 bits, 5 bytes.
276 let mut d = Bw::new();
277 d.put(5 - 1, 9);
278 d.put(0, 3);
279 d.put(0, 1);
280 d.put(0, 1);
281 d.put(1, 2); // coding mode 1: lossless without a core component
282 d.put(payload as u64 - 1, 16);
283 d.put(0, 1);
284 d.put(0, 3);
285 d.align();
286 assert_eq!(d.bytes.len(), 5);
287 // Header: sync 32, user 8, index 2, wide 1, hdr size 8, exss size 16,
288 // static 1, asset size 16, descriptor, crc 16.
289 let hdr_bits: usize = 32 + 8 + 2 + 1 + 8 + 16 + 1 + 16 + 40;
290 let hdr_bytes = (hdr_bits + 16).div_ceil(8);
291 let total = hdr_bytes + payload;
292 let mut w = Bw::new();
293 w.put(0x6458_2025, 32);
294 w.put(0, 8);
295 w.put(0, 2);
296 w.put(0, 1);
297 w.put(hdr_bytes as u64 - 1, 8);
298 w.put(total as u64 - 1, 16);
299 w.put(0, 1);
300 w.put(payload as u64 - 1, 16);
301 for b in &d.bytes {
302 w.put(*b as u64, 8);
303 }
304 w.align();
305 w.put(0, 16);
306 let mut v = w.bytes;
307 assert_eq!(v.len(), hdr_bytes);
308 v.extend((0..payload).map(|i| (i * 37) as u8));
309 v
310}
311
312#[test]
313fn dts_hd_substream_is_parsed_and_the_core_is_output() {
314 let data = std::fs::read(fixtures().join("tones-51-44k.dts")).unwrap();
315 let fr = frames(&data);
316 let core = fr[3];
317 let hd = exss_with_xll(300);
318
319 let info = ec_dts::exss::parse_exss(&hd).unwrap();
320 assert_eq!(info.size, hd.len());
321 assert!(info.has_xll());
322 assert_eq!(info.assets[0].xll_size, 300);
323 assert_eq!(info.assets[0].xll_offset, hd.len() - 300);
324
325 // Core alone vs core with the HD substream behind it (4-byte aligned).
326 let mut plain = DtsDecoder::new();
327 plain.decode_frame(fr[2]).unwrap();
328 let want = plain.decode_frame(core).unwrap();
329
330 let mut with = core.to_vec();
331 while with.len() % 4 != 0 {
332 with.push(0);
333 }
334 with.extend_from_slice(&hd);
335 let mut dec = DtsDecoder::new();
336 let mut prev = fr[2].to_vec();
337 while prev.len() % 4 != 0 {
338 prev.push(0);
339 }
340 prev.extend_from_slice(&hd);
341 dec.decode_frame(&prev).unwrap();
342 let got = dec.decode_frame(&with).unwrap();
343 assert_eq!(got.data[0].len(), want.data[0].len());
344 assert!(got.data[0] == want.data[0], "HD frame must give the core samples");
345 let i = dec.frame_info().unwrap();
346 assert!(i.hd_substream && i.xll, "XLL flagged: {i:?}");
347
348 // The strict option names the refusal.
349 let mut strict = DtsDecoder::with_options(Options { refuse_xll: true });
350 match strict.decode_frame(&with) {
351 Err(Error::Unsupported { what, .. }) => assert!(what.contains("XLL"), "{what}"),
352 other => panic!("expected an XLL refusal, got {other:?}"),
353 }
354}
355
356#[test]
357fn damaged_streams_never_panic() {
358 let data = std::fs::read(fixtures().join("noise-51-adpcm-48k.dts")).unwrap();
359 let fr = frames(&data);
360 let mut seed = 0x1234_5678u32;
361 let mut next = move || {
362 seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
363 seed >> 8
364 };
365 let mut dec = DtsDecoder::new();
366 let mut errors = 0;
367 for round in 0..400 {
368 let mut f = fr[round % fr.len()].to_vec();
369 let flips = 1 + next() % 8;
370 for _ in 0..flips {
371 let at = (next() as usize) % f.len();
372 f[at] ^= 1 << (next() % 8);
373 }
374 if round % 7 == 0 {
375 f.truncate((next() as usize) % f.len());
376 }
377 if dec.decode_frame(&f).is_err() {
378 errors += 1;
379 }
380 }
381 assert!(errors > 0, "corruption should be noticed at least sometimes");
382 // And the decoder still works on a clean frame afterwards.
383 dec.reset();
384 dec.decode_frame(fr[0]).unwrap();
385}