forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

ffmpeg_parity.rs401 lines, 16.7 KiBHistoryRawDownload
1#![allow(clippy::too_many_arguments, clippy::needless_range_loop, clippy::len_zero)]
2//! Byte-exact comparison with ffmpeg's dnxhd decoder on streams ffmpeg's own
3//! encoder produces from synthetic sources (and on header-patched variants for
4//! the corners the encoder cannot reach: 12-bit samples, MBAFF).
5
6mod common;
7use common::*;
8use ec_dnxhd::{Chroma, DnxhdDecoder, Picture};
9use ec_core::registry::{CodecId, CodecParameters};
10
11struct Case {
12 tag: &'static str,
13 size: &'static str,
14 rate: &'static str,
15 src: &'static str,
16 pix_in: &'static str,
17 enc: &'static [&'static str],
18 frames: u32,
19 /// Expected compression id.
20 cid: u32,
21 /// Expected interlace.
22 interlaced: bool,
23}
24
25const fn c(
26 tag: &'static str,
27 size: &'static str,
28 rate: &'static str,
29 src: &'static str,
30 pix_in: &'static str,
31 enc: &'static [&'static str],
32 frames: u32,
33 cid: u32,
34 interlaced: bool,
35) -> Case {
36 Case { tag, size, rate, src, pix_in, enc, frames, cid, interlaced }
37}
38
39const T: &str = "testsrc2";
40const N: &str = "testsrc2,noise=alls=30:allf=t";
41const M: &str = "mandelbrot";
42
43fn ff_pix(pic: &Picture) -> &'static str {
44 match (pic.info.chroma, pic.info.bit_depth) {
45 (Chroma::C422, 8) => "yuv422p",
46 (Chroma::C422, 10) => "yuv422p10le",
47 (Chroma::C422, _) => "yuv422p12le",
48 (Chroma::C444, 10) => "yuv444p10le",
49 (Chroma::C444, _) => "yuv444p12le",
50 }
51}
52
53fn native_bytes(p: &Picture) -> Vec<u8> {
54 let mut v = Vec::new();
55 for pl in &p.planes {
56 for &s in pl {
57 if p.info.bit_depth == 8 {
58 v.push(s as u8);
59 } else {
60 v.extend_from_slice(&s.to_le_bytes());
61 }
62 }
63 }
64 v
65}
66
67fn encode(c: &Case, dir: &std::path::Path) -> Option<std::path::PathBuf> {
68 let out = dir.join(format!("{}.mov", c.tag));
69 let (base, chain) = match c.src.split_once(',') {
70 Some((b, r)) => (b, format!(",{r}")),
71 None => (c.src, String::new()),
72 };
73 let lavfi = format!("{base}=size={}:rate={}{chain},format={}", c.size, c.rate, c.pix_in);
74 let n = c.frames.to_string();
75 let mut args: Vec<&str> = vec!["-f", "lavfi", "-i", &lavfi, "-frames:v", &n, "-c:v", "dnxhd"];
76 args.extend_from_slice(c.enc);
77 args.push(out.to_str().unwrap());
78 ffmpeg(&args).then_some(out)
79}
80
81/// ffmpeg's rawvideo decode of `raw` with the given `-cpuflags`.
82fn ffmpeg_decode(dir: &std::path::Path, raw: &std::path::Path, pix: &str, cpu: &str) -> Result<Vec<u8>, String> {
83 let refp = dir.join(format!("ref-{cpu}.yuv"));
84 if !ffmpeg(&[
85 "-cpuflags", cpu, "-f", "dnxhd", "-i", raw.to_str().unwrap(), "-f", "rawvideo", "-pix_fmt", pix,
86 "-fps_mode", "passthrough", refp.to_str().unwrap(),
87 ]) {
88 return Err("ffmpeg decode failed".into());
89 }
90 std::fs::read(&refp).map_err(|e| e.to_string())
91}
92
93/// (max abs error, PSNR dB over `peak`) between two sample streams of `bytes_per` width.
94fn diff_stats(a: &[u8], b: &[u8], bytes_per: usize, peak: f64) -> (u32, f64) {
95 let (mut max, mut sse, mut n) = (0u32, 0f64, 0f64);
96 for (x, y) in a.chunks(bytes_per).zip(b.chunks(bytes_per)) {
97 let (x, y) = if bytes_per == 1 {
98 (u32::from(x[0]), u32::from(y[0]))
99 } else {
100 (u32::from(u16::from_le_bytes([x[0], x[1]])), u32::from(u16::from_le_bytes([y[0], y[1]])))
101 };
102 let d = x.abs_diff(y);
103 max = max.max(d);
104 sse += f64::from(d * d);
105 n += 1.0;
106 }
107 let psnr = if sse == 0.0 { f64::INFINITY } else { 10.0 * (peak * peak * n / sse).log10() };
108 (max, psnr)
109}
110
111/// Decode `frames` with ffmpeg (raw dnxhd stream) and with us. Against
112/// ffmpeg's C code (`-cpuflags 0`) the bytes must be identical. Against its
113/// default x86 SIMD IDCT they must be identical too, unless that IDCT
114/// differs from its own C version on overflowing coefficients (noise-heavy
115/// 10-bit content); then we ask for max abs error <= 1... measured in `note`.
116fn compare(tag: &str, frames: &[Vec<u8>], threads: usize) -> Result<Picture, String> {
117 let dir = scratch(&format!("cmp-{tag}"));
118 let raw = dir.join("in.dnxhd");
119 std::fs::write(&raw, frames.concat()).map_err(|e| e.to_string())?;
120 let mut dec = DnxhdDecoder::new(CodecParameters::new(CodecId::Dnxhd)).unwrap();
121 dec.set_threads(threads);
122 let mut ours = Vec::new();
123 let mut last = None;
124 for f in frames {
125 let pic = dec.decode_native(f).map_err(|e| format!("{tag}: decode: {e}"))?;
126 ours.extend_from_slice(&native_bytes(&pic));
127 last = Some(pic);
128 }
129 let last = last.ok_or("no frames")?;
130 let pix = ff_pix(&last);
131 let reference = ffmpeg_decode(&dir, &raw, pix, "0").map_err(|e| format!("{tag}: {e}"))?;
132 if reference.len() != ours.len() {
133 return Err(format!("{tag}: size {} != ffmpeg {}", ours.len(), reference.len()));
134 }
135 if let Some(i) = reference.iter().zip(&ours).position(|(a, b)| a != b) {
136 let bad = reference.iter().zip(&ours).filter(|(a, b)| a != b).count();
137 return Err(format!("{tag}: {bad} bytes differ from ffmpeg's C decoder, first at {i}"));
138 }
139 // The default build of ffmpeg on this machine (x86 SIMD IDCT). Its 10-bit
140 // SIMD IDCT is not bit-identical to its own C code on coefficient sets
141 // that overflow 16 bits (saturated noise at very high bit rates), so a
142 // handful of samples there differ by a whole code range; we follow the C
143 // code. Everywhere else the two agree, and the difference stays below
144 // 0.1% of the samples.
145 let simd = ffmpeg_decode(&dir, &raw, pix, "all").map_err(|e| format!("{tag}: {e}"))?;
146 let bytes_per = if last.info.bit_depth == 8 { 1 } else { 2 };
147 if simd != ours {
148 let (max, psnr) = diff_stats(&simd, &ours, bytes_per, f64::from((1u32 << last.info.bit_depth) - 1));
149 let bad = simd.chunks(bytes_per).zip(ours.chunks(bytes_per)).filter(|(a, b)| a != b).count();
150 let frac = bad as f64 / (ours.len() / bytes_per) as f64;
151 eprintln!("note {tag}: vs ffmpeg SIMD {bad} samples differ ({frac:.5}), max abs error {max}, PSNR {psnr:.1} dB");
152 // 12-bit: ffmpeg's SIMD IDCT rounds differently from its C code by one
153 // code value (>= 60 dB PSNR, max abs error 1).
154 if !((max <= 1 && psnr >= 60.0) || frac <= 0.001) {
155 return Err(format!("{tag}: vs ffmpeg SIMD {bad} samples differ"));
156 }
157 }
158 let _ = std::fs::remove_dir_all(&dir);
159 Ok(last)
160}
161
162fn run_cases(tag: &str, cases: &[Case]) {
163 if !can_run() {
164 return;
165 }
166 let dir = scratch(tag);
167 let mut failures = Vec::new();
168 for case in cases {
169 let Some(path) = encode(case, &dir) else {
170 failures.push(format!("{}: ffmpeg encode failed", case.tag));
171 continue;
172 };
173 let frames = mov_frames(&path);
174 if frames.len() != case.frames as usize {
175 failures.push(format!("{}: {} frames", case.tag, frames.len()));
176 continue;
177 }
178 match compare(case.tag, &frames, 3) {
179 Ok(pic) => {
180 if pic.info.cid != case.cid || pic.info.interlaced != case.interlaced {
181 failures.push(format!("{}: cid {} interlaced {}", case.tag, pic.info.cid, pic.info.interlaced));
182 }
183 }
184 Err(e) => failures.push(e),
185 }
186 // Single-threaded decode must agree too.
187 if let Err(e) = compare(&format!("{}-t1", case.tag), &frames, 1) {
188 failures.push(e);
189 }
190 }
191 let _ = std::fs::remove_dir_all(&dir);
192 assert!(failures.is_empty(), "{}", failures.join("\n"));
193}
194
195#[test]
196fn every_dnxhd_cid_ffmpeg_can_encode() {
197 run_cases("cids", &[
198 c("1235", "1920x1080", "24000/1001", T, "yuv422p10le", &["-b:v", "175M"], 3, 1235, false),
199 c("1235_50p", "1920x1080", "50", N, "yuv422p10le", &["-b:v", "365M"], 3, 1235, false),
200 c("1235_60p", "1920x1080", "60000/1001", M, "yuv422p10le", &["-b:v", "440M"], 2, 1235, false),
201 c("1237", "1920x1080", "30000/1001", T, "yuv422p", &["-b:v", "145M"], 3, 1237, false),
202 c("1237_noise", "1920x1080", "25", N, "yuv422p", &["-b:v", "120M"], 2, 1237, false),
203 c("1238", "1920x1080", "24000/1001", T, "yuv422p", &["-b:v", "175M"], 3, 1238, false),
204 c("1238_60p", "1920x1080", "60000/1001", N, "yuv422p", &["-b:v", "440M"], 2, 1238, false),
205 c("1241", "1920x1080", "24000/1001", T, "yuv422p10le", &["-b:v", "185M", "-flags", "+ildct"], 3, 1241, true),
206 c("1241_30i", "1920x1080", "30000/1001", N, "yuv422p10le", &["-b:v", "220M", "-flags", "+ildct"], 2, 1241, true),
207 c("1242", "1920x1080", "24000/1001", T, "yuv422p", &["-b:v", "120M", "-flags", "+ildct"], 3, 1242, true),
208 c("1243", "1920x1080", "24000/1001", N, "yuv422p", &["-b:v", "185M", "-flags", "+ildct"], 3, 1243, true),
209 c("1244", "1440x1080", "24000/1001", T, "yuv422p", &["-b:v", "120M", "-flags", "+ildct"], 3, 1244, true),
210 c("1250", "1280x720", "24000/1001", T, "yuv422p10le", &["-b:v", "90M"], 3, 1250, false),
211 c("1250_60p", "1280x720", "60000/1001", N, "yuv422p10le", &["-b:v", "220M"], 3, 1250, false),
212 c("1251", "1280x720", "24000/1001", T, "yuv422p", &["-b:v", "90M"], 3, 1251, false),
213 c("1251_60p", "1280x720", "60000/1001", M, "yuv422p", &["-b:v", "220M"], 3, 1251, false),
214 c("1252", "1280x720", "24000/1001", T, "yuv422p", &["-b:v", "60M"], 3, 1252, false),
215 c("1253", "1920x1080", "24000/1001", T, "yuv422p", &["-b:v", "36M"], 3, 1253, false),
216 c("1258", "960x720", "24000/1001", T, "yuv422p", &["-b:v", "42M"], 3, 1258, false),
217 c("1259", "1440x1080", "24000/1001", T, "yuv422p", &["-b:v", "63M"], 3, 1259, false),
218 ]);
219}
220
221fn profile_args(name: &str) -> &'static [&'static str] {
222 match name {
223 "lb" | "dnxhr_lb" => &["-profile:v", "dnxhr_lb"],
224 "sq" | "dnxhr_sq" => &["-profile:v", "dnxhr_sq"],
225 "hq" | "dnxhr_hq" => &["-profile:v", "dnxhr_hq"],
226 "hqx" | "dnxhr_hqx" => &["-profile:v", "dnxhr_hqx"],
227 _ => &["-profile:v", "dnxhr_444"],
228 }
229}
230
231#[test]
232fn dnxhr_profiles_at_odd_sizes() {
233 let p = profile_args;
234 let mut cases = Vec::new();
235 for (sz, tagsz) in [("1280x544", "1280x544"), ("322x178", "322x178"), ("258x122", "258x122"), ("256x120", "256x120"), ("1000x300", "1000x300")] {
236 let _ = tagsz;
237 for (prof, cid, pix) in [
238 ("lb", 1274, "yuv422p"),
239 ("sq", 1273, "yuv422p"),
240 ("hq", 1272, "yuv422p"),
241 ("hqx", 1271, "yuv422p10le"),
242 ("444", 1270, "yuv444p10le"),
243 ] {
244 let tag: &'static str = Box::leak(format!("hr_{prof}_{sz}").into_boxed_str());
245 let src = if prof == "444" || prof == "hq" { N } else { T };
246 let size: &'static str = Box::leak(sz.to_string().into_boxed_str());
247 cases.push(c(tag, size, "25", src, pix, p(prof), 3, cid, false));
248 }
249 }
250 run_cases("hr_odd", &cases);
251}
252
253#[test]
254fn dnxhr_2160p_has_a_long_scan_index() {
255 run_cases("uhd", &[
256 c("uhd_hq", "3840x2160", "25", T, "yuv422p", &["-profile:v", "dnxhr_hq"], 1, 1272, false),
257 c("uhd_444", "3840x2160", "25", N, "yuv444p10le", &["-profile:v", "dnxhr_444"], 1, 1270, false),
258 ]);
259}
260
261#[test]
262fn dnxhr_1080p_all_profiles() {
263 run_cases("fhd", &[
264 c("fhd_lb", "1920x1080", "25", M, "yuv422p", &["-profile:v", "dnxhr_lb"], 2, 1274, false),
265 c("fhd_sq", "1920x1080", "25", M, "yuv422p", &["-profile:v", "dnxhr_sq"], 2, 1273, false),
266 c("fhd_hq", "1920x1080", "25", M, "yuv422p", &["-profile:v", "dnxhr_hq"], 2, 1272, false),
267 c("fhd_hqx", "1920x1080", "25", M, "yuv422p10le", &["-profile:v", "dnxhr_hqx"], 2, 1271, false),
268 ]);
269}
270
271/// Patch a header byte in every frame (and every field of an interlaced frame)
272/// so the ffmpeg decoder and ours read the same stream the encoder cannot make.
273fn patched(frames: &[Vec<u8>], f: impl Fn(&mut [u8])) -> Vec<Vec<u8>> {
274 frames
275 .iter()
276 .map(|fr| {
277 let mut fr = fr.clone();
278 f(&mut fr);
279 fr
280 })
281 .collect()
282}
283
284#[test]
285fn twelve_bit_streams_by_patching_the_depth_field() {
286 if !can_run() {
287 return;
288 }
289 let dir = scratch("p12");
290 let mut failures = Vec::new();
291 for (tag, size, pix, prof, src) in [
292 ("hqx12", "320x176", "yuv422p10le", "dnxhr_hqx", N),
293 ("hqx12_mand", "320x176", "yuv422p10le", "dnxhr_hqx", M),
294 ("444_12", "320x176", "yuv444p10le", "dnxhr_444", N),
295 ("444_12_t", "322x178", "yuv444p10le", "dnxhr_444", T),
296 ] {
297 let case = c(tag, size, "25", src, pix, profile_args(prof), 3, 0, false);
298 let Some(path) = encode(&case, &dir) else {
299 failures.push(format!("{tag}: encode"));
300 continue;
301 };
302 let frames = patched(&mov_frames(&path), |fr| fr[0x21] = (fr[0x21] & 0x1f) | (3 << 5));
303 match compare(tag, &frames, 2) {
304 Ok(p) => assert_eq!(p.info.bit_depth, 12),
305 Err(e) => failures.push(e),
306 }
307 }
308 let _ = std::fs::remove_dir_all(&dir);
309 assert!(failures.is_empty(), "{}", failures.join("\n"));
310}
311
312#[test]
313fn mbaff_cid_1260_by_patching_the_header() {
314 if !can_run() {
315 return;
316 }
317 let dir = scratch("mbaff");
318 let mut failures = Vec::new();
319 for (tag, src) in [("mbaff_t", T), ("mbaff_n", N)] {
320 let case = c(tag, "1440x1080", "25", src, "yuv422p", &["-b:v", "120M", "-flags", "+ildct"], 2, 1244, true);
321 let Some(path) = encode(&case, &dir) else {
322 failures.push(format!("{tag}: encode"));
323 continue;
324 };
325 let frames = mov_frames(&path);
326 // CID 1260 (1440x1080 MBAFF, 417792-byte coding units) from a 1244
327 // stream: the macroblock header is 12 bits either way (11-bit qscale,
328 // or interlace flag + 10-bit qscale), so the payload stays valid. The
329 // first macroblock of every row is flipped to an interlaced one.
330 let frames: Vec<Vec<u8>> = frames
331 .iter()
332 .map(|fr| {
333 let unit = fr.len() / 2;
334 let mut out = Vec::new();
335 for k in 0..2 {
336 let mut u = fr[k * unit..(k + 1) * unit].to_vec();
337 u[0x28..0x2c].copy_from_slice(&1260u32.to_be_bytes());
338 u[6] |= 0x20;
339 let rows = u16::from_be_bytes([u[0x16c], u[0x16d]]) as usize;
340 for r in 0..rows {
341 let off = u32::from_be_bytes(u[0x170 + 4 * r..0x174 + 4 * r].try_into().unwrap()) as usize;
342 u[0x280 + off] |= 0x80;
343 }
344 u.resize(417_792, 0);
345 out.extend_from_slice(&u);
346 }
347 out
348 })
349 .collect();
350 match compare(tag, &frames, 3) {
351 Ok(p) => assert!(p.info.mbaff && p.info.cid == 1260 && p.info.interlaced),
352 Err(e) => failures.push(e),
353 }
354 }
355 let _ = std::fs::remove_dir_all(&dir);
356 assert!(failures.is_empty(), "{}", failures.join("\n"));
357}
358
359#[test]
360fn video_frame_output_formats_and_interlace_flag() {
361 if !can_run() {
362 return;
363 }
364 use ec_core::frame::{Interlace, PixelFormat};
365 let dir = scratch("vf");
366 let mut dec = DnxhdDecoder::new(CodecParameters::new(CodecId::Dnxhd)).unwrap();
367 for (case, fmt, il) in [
368 (c("vf_422", "320x176", "25", T, "yuv422p", &["-profile:v", "dnxhr_hq"], 1, 1272, false), PixelFormat::I422, Interlace::Progressive),
369 (c("vf_hqx", "320x176", "25", T, "yuv422p10le", &["-profile:v", "dnxhr_hqx"], 1, 1271, false), PixelFormat::I210, Interlace::Progressive),
370 (c("vf_444", "320x176", "25", T, "yuv444p10le", &["-profile:v", "dnxhr_444"], 1, 1270, false), PixelFormat::I410, Interlace::Progressive),
371 (c("vf_il", "1920x1080", "25", T, "yuv422p", &["-b:v", "120M", "-flags", "+ildct"], 1, 1242, true), PixelFormat::I422, Interlace::TopFieldFirst),
372 ] {
373 let path = encode(&case, &dir).unwrap();
374 let fr = &mov_frames(&path)[0];
375 let f = dec.decode_bytes(fr).unwrap();
376 assert_eq!(f.format, fmt, "{}", case.tag);
377 assert_eq!(f.interlace, il, "{}", case.tag);
378 assert!(!frame_bytes(&f).is_empty());
379 }
380 let _ = std::fs::remove_dir_all(&dir);
381}
382
383#[test]
384fn matroska_carries_dnxhd_too() {
385 if !can_run() {
386 return;
387 }
388 let dir = scratch("mkv");
389 let mkv = dir.join("a.mkv");
390 let mov = dir.join("a.mov");
391 let avi = dir.join("a.avi");
392 for out in [&mkv, &mov, &avi] {
393 assert!(ffmpeg(&[
394 "-f", "lavfi", "-i", "testsrc2=size=320x176:rate=25,format=yuv422p", "-frames:v", "2",
395 "-c:v", "dnxhd", "-profile:v", "dnxhr_sq", out.to_str().unwrap(),
396 ]));
397 }
398 assert_eq!(mkv_frames(&mkv), mov_frames(&mov));
399 assert_eq!(avi_frames(&avi), mov_frames(&mov));
400 let _ = std::fs::remove_dir_all(&dir);
401}