forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

common.rs463 lines, 16.4 KiBHistoryRawDownload
1//! Shared fixtures for the integration tests.
2//!
3//! Each test binary compiles this module and uses part of it.
4#![allow(dead_code)]
5
6use ec_core::frame::{PixelFormat, Plane, VideoFrame};
7use ec_h265::decode::DecodedPicture;
8use ec_h265_syntax::ConformanceWindow;
9use ec_h265_syntax::sei::{PictureHash, SeiMessage, decoded_picture_hash_rbsp, parse_sei_rbsp};
10
11/// A synthetic picture with gradients, edges and texture — enough structure
12/// that every intra direction gets used somewhere.
13pub fn test_frame(width: u32, height: u32, phase: u32) -> VideoFrame {
14 let (w, h) = (width as usize, height as usize);
15 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
16 let mut y = vec![0u8; w * h];
17 for row in 0..h {
18 for col in 0..w {
19 let diag = ((row + col + phase as usize) % 64) as i32;
20 let ramp = (col * 200 / w) as i32;
21 let ring = if (row * row + col * col) % 977 < 60 {
22 60
23 } else {
24 0
25 };
26 let texture = ((row * 7 + col * 13) % 17) as i32 * 3;
27 y[row * w + col] = (16 + ramp + diag / 2 + ring + texture).clamp(0, 255) as u8;
28 }
29 }
30 let mut cb = vec![0u8; cw * ch];
31 let mut cr = vec![0u8; cw * ch];
32 for row in 0..ch {
33 for col in 0..cw {
34 cb[row * cw + col] = (128 + (col as i32 * 60 / (cw as i32)) - 30).clamp(0, 255) as u8;
35 cr[row * cw + col] = (128 + (row as i32 * 60 / (ch as i32)) - 30).clamp(0, 255) as u8;
36 }
37 }
38 VideoFrame::try_new(
39 PixelFormat::I420,
40 width,
41 height,
42 vec![Plane::new(y, w), Plane::new(cb, cw), Plane::new(cr, cw)],
43 )
44 .expect("test frame")
45}
46
47/// A picture with the statistics of camera video rather than of a noise
48/// generator: smooth gradients, a few hard edges, and detail that decays with
49/// distance from them.
50///
51/// The speed bar this family carries was measured on real 1080p footage, so the
52/// fixture the bar is asserted against has to look like footage. The textured
53/// [`test_frame`] above is the opposite fixture — worst case for the residual
54/// coder — and both numbers are worth printing.
55pub fn natural_frame(width: u32, height: u32, phase: u32) -> VideoFrame {
56 let (w, h) = (width as usize, height as usize);
57 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
58 let mut y = vec![0u8; w * h];
59 for row in 0..h {
60 for col in 0..w {
61 let fx = col as f32 / w as f32;
62 let fy = row as f32 / h as f32;
63 // Two soft gradients, a horizon and a couple of objects.
64 let sky = 200.0 - 90.0 * fy;
65 let ground = 60.0 + 40.0 * fx;
66 let mut value = if fy < 0.55 { sky } else { ground };
67 let dx = fx - 0.3;
68 let dy = fy - 0.65;
69 if dx * dx + dy * dy < 0.02 {
70 value = 150.0 - 40.0 * fx;
71 }
72 if (fx - 0.72).abs() < 0.06 && fy > 0.35 {
73 value = 40.0;
74 }
75 // Sensor grain, small and local.
76 let grain = (((row * 31 + col * 17 + phase as usize) % 7) as f32) - 3.0;
77 y[row * w + col] = (value + grain).clamp(0.0, 255.0) as u8;
78 }
79 }
80 let mut cb = vec![0u8; cw * ch];
81 let mut cr = vec![0u8; cw * ch];
82 for row in 0..ch {
83 for col in 0..cw {
84 let fy = row as f32 / ch as f32;
85 cb[row * cw + col] = (140.0 - 30.0 * fy) as u8;
86 cr[row * cw + col] = (110.0 + 25.0 * fy) as u8;
87 }
88 }
89 VideoFrame::try_new(
90 PixelFormat::I420,
91 width,
92 height,
93 vec![Plane::new(y, w), Plane::new(cb, cw), Plane::new(cr, cw)],
94 )
95 .expect("natural frame")
96}
97
98/// Write `bytes` to `path` and PROVE the file on disk is exactly that long.
99///
100/// lane-h26xpinloud: the encode gate's sites used `std::fs::write(..).ok()?`
101/// and [`write_au`] used `File::create` + `write_all(..).expect(..)`, then all
102/// three handed `path` to ffmpeg. Checking the `Result` closes only the ERROR
103/// path. An Ok-but-short write -- a filesystem that reports success and stores
104/// fewer bytes (ENOSPC on a full mount, EFBIG under a size cap, a quota, a
105/// failed final flush) -- left ffmpeg decoding a truncated stream, and the
106/// failure surfaced as a plausible-looking wrong pixel or a shifted PSNR
107/// number, not as a write failure. MEASURED: 1234 bytes written through a path
108/// that LOOKS like a stream file in a scratch directory but whose filesystem
109/// accepts every byte and stores none returns `Ok`, and the file on disk is 0
110/// bytes. So the length is checked here once, from the same `bytes.len()` the
111/// writer used, and any shortfall carries the path, both counts, and the OS
112/// error -- or, for the write that reported success and left a short file, the
113/// plain statement that there was no OS error, which is exactly the case that
114/// used to print nothing.
115///
116/// This is the ec-av1 `dumpio::LoudDump` idea replicated per crate: there is no
117/// shared test-support crate here and none is being added for one function.
118/// Returns the failure LINE rather than a bare bool, so the bail callers and the
119/// panic caller all end on one format that cannot drift apart. The success path
120/// is byte-identical to the old write: same bytes, same path, truncate then
121/// write.
122pub fn pin_loud(site: &str, path: &std::path::Path, bytes: &[u8]) -> Result<(), String> {
123 let expected = bytes.len();
124 if let Err(e) = std::fs::write(path, bytes) {
125 // The count here is the file's REAL length, not what the writer had
126 // confirmed in hand: under a size cap the kernel stores everything up
127 // to the cap and only THEN returns the error, and the write confirms
128 // none of it.
129 let on_disk = std::fs::metadata(path)
130 .map(|m| m.len() as usize)
131 .unwrap_or(0);
132 return Err(short_line(
133 site,
134 path,
135 on_disk,
136 expected,
137 &format!("the write failed: {e}"),
138 ));
139 }
140 match std::fs::metadata(path) {
141 Ok(m) if m.len() as usize == expected => Ok(()),
142 Ok(m) => Err(short_line(
143 site,
144 path,
145 m.len() as usize,
146 expected,
147 "the write reported success and the file on disk is still not that long (no OS error)",
148 )),
149 Err(e) => Err(short_line(
150 site,
151 path,
152 0,
153 expected,
154 &format!("the written file could not be stat'ed: {e}"),
155 )),
156 }
157}
158
159/// The one failure line every short pin ends on: site, path, the bytes the file
160/// holds vs the bytes owed, and the reason.
161fn short_line(
162 site: &str,
163 path: &std::path::Path,
164 on_disk: usize,
165 expected: usize,
166 why: &str,
167) -> String {
168 format!(
169 "ec-h265 test pin SHORT [{}] {}: file holds {on_disk} of {expected} bytes: {why}",
170 site,
171 path.display()
172 )
173}
174
175/// A pin whose shortfall is reported and then BAILED on, for a caller that
176/// returns `None` today. Prints the same line [`pin_loud`] returns, so `None`
177/// from here never reads as a plain "ffmpeg said no".
178pub fn pin_or_bail(site: &str, path: &std::path::Path, bytes: &[u8]) -> Option<()> {
179 pin_loud(site, path, bytes)
180 .map_err(|why| eprintln!("{why}"))
181 .ok()
182}
183
184/// [`pin_loud`] with the shortfall PANICKING, for a caller that fails loudly
185/// today. The panic message IS the failure line, so the two callers of this
186/// shape cannot drift apart either.
187pub fn pin_or_panic(site: &str, path: &std::path::Path, bytes: &[u8]) {
188 if let Err(why) = pin_loud(site, path, bytes) {
189 panic!("{why}");
190 }
191}
192
193pub const PLANE_NAMES: [&str; 3] = ["Y", "Cb", "Cr"];
194
195/// Bytes per sample of component `c`: 1 for 8-bit, 2 (little endian) above 8 bits.
196pub fn bytes_per_sample(pic: &DecodedPicture, c: usize) -> usize {
197 if pic.bit_depth_of(c) > 8 { 2 } else { 1 }
198}
199
200/// The samples of a picture cropped to its conformance window, as the bytes a YUV
201/// file of that frame holds (planar, 8-bit or little-endian 16-bit).
202pub fn cropped_bytes(pic: &DecodedPicture, win: &ConformanceWindow) -> Vec<u8> {
203 // The reference YUV holds every plane at the wider sample size.
204 let bps = bytes_per_sample(pic, 0).max(bytes_per_sample(pic, 1));
205 let (w, h) = (pic.width, pic.height);
206 let (cw, ch) = pic.chroma_dims();
207 // The conformance window offsets are in chroma units: luma units are SubWidthC and
208 // SubHeightC times as large.
209 let (sw, sh) = (
210 1usize << pic.chroma_shifts().0,
211 1usize << pic.chroma_shifts().1,
212 );
213 let (l, r, t, b) = (
214 win.left as usize,
215 win.right as usize,
216 win.top as usize,
217 win.bottom as usize,
218 );
219 let mut out = Vec::new();
220 for (samples, pw, ph, (x0, x1, y0, y1)) in [
221 (
222 &pic.y,
223 w,
224 h,
225 (
226 sw * l,
227 w.saturating_sub(sw * r),
228 sh * t,
229 h.saturating_sub(sh * b),
230 ),
231 ),
232 (
233 &pic.cb,
234 cw,
235 ch,
236 (l, cw.saturating_sub(r), t, ch.saturating_sub(b)),
237 ),
238 (
239 &pic.cr,
240 cw,
241 ch,
242 (l, cw.saturating_sub(r), t, ch.saturating_sub(b)),
243 ),
244 ] {
245 for y in y0..y1.min(ph) {
246 for x in x0..x1.min(pw) {
247 let s = samples.get(y * pw + x).copied().unwrap_or(0);
248 if bps == 1 {
249 out.push(s as u8);
250 } else {
251 out.extend_from_slice(&s.to_le_bytes());
252 }
253 }
254 }
255 }
256 out
257}
258
259/// A description of one mismatched plane: its location when the reference is known.
260pub fn describe(
261 reference: Option<&[u8]>,
262 out_index: usize,
263 pic: &DecodedPicture,
264 poc: i32,
265 plane: usize,
266) -> String {
267 let label = PLANE_NAMES.get(plane).copied().unwrap_or("?");
268 match reference {
269 None => format!("hash mismatch poc={poc} plane={label}"),
270 Some(r) => match first_diff(r, out_index, pic, plane) {
271 Ok(Some((x, y))) => format!("poc={poc} plane={label} x={x} y={y}"),
272 Ok(None) => format!("hash mismatch poc={poc} plane={label} (no sample differs)"),
273 Err(e) => format!("hash mismatch poc={poc} plane={label} ({e})"),
274 },
275 }
276}
277
278/// The first sample (x, y) of `plane` that differs from the reference YUV, where
279/// frame `out_index` in output order starts at byte `out_index * frame_bytes`.
280pub fn first_diff(
281 reference: &[u8],
282 out_index: usize,
283 pic: &DecodedPicture,
284 plane: usize,
285) -> Result<Option<(usize, usize)>, String> {
286 // The reference YUV holds every plane at the wider sample size.
287 let bps = bytes_per_sample(pic, 0).max(bytes_per_sample(pic, 1));
288 let dims = plane_dims(pic);
289 let luma = dims[0].0 * dims[0].1;
290 let chroma = dims[1].0 * dims[1].1;
291 let frame_bytes = bps * (luma + 2 * chroma);
292 let (offset, samples) = match plane {
293 0 => (0, &pic.y),
294 1 => (bps * luma, &pic.cb),
295 _ => (bps * (luma + chroma), &pic.cr),
296 };
297 let width = dims[plane].0.max(1);
298 let base = out_index * frame_bytes + offset;
299 for (i, &s) in samples.iter().enumerate() {
300 let at = base + i * bps;
301 let value = if bps == 1 {
302 reference.get(at).map(|&b| u16::from(b))
303 } else {
304 reference
305 .get(at..at + 2)
306 .map(|b| u16::from_le_bytes([b[0], b[1]]))
307 };
308 let Some(value) = value else {
309 return Err(format!(
310 "reference YUV ends inside plane {}",
311 PLANE_NAMES[plane]
312 ));
313 };
314 if value != s {
315 return Ok(Some((i % width, i / width)));
316 }
317 }
318 Ok(None)
319}
320
321/// The 32-bit checksum of one plane of `width` samples a row (D.3.19, hash_type 2).
322pub fn plane_checksum(samples: &[u16], width: usize, bit_depth: u32) -> u32 {
323 let mut sum: u32 = 0;
324 for (i, &s) in samples.iter().enumerate() {
325 let (x, y) = (i % width.max(1), i / width.max(1));
326 let mask = ((x & 0xff) ^ (y & 0xff) ^ (x >> 8) ^ (y >> 8)) as u32;
327 sum = sum.wrapping_add((u32::from(s) & 0xff) ^ mask);
328 if bit_depth > 8 {
329 sum = sum.wrapping_add((u32::from(s) >> 8) ^ mask);
330 }
331 }
332 sum
333}
334
335/// The 16-bit CRC of one plane (D.3.19, hash_type 1): the samples as bytes, low
336/// byte first above 8 bits, then 16 zero bits.
337pub fn plane_crc(samples: &[u16], bit_depth: u32) -> u16 {
338 let mut crc: u32 = 0xffff;
339 let mut feed = |byte: u8| {
340 for bit in 0..8 {
341 let msb = (crc >> 15) & 1;
342 let bit_val = u32::from((byte >> (7 - bit)) & 1);
343 crc = (((crc << 1) + bit_val) & 0xffff) ^ (msb * 0x1021);
344 }
345 };
346 for &s in samples {
347 feed(s as u8);
348 if bit_depth > 8 {
349 feed((s >> 8) as u8);
350 }
351 }
352 for _ in 0..16 {
353 let msb = (crc >> 15) & 1;
354 crc = ((crc << 1) & 0xffff) ^ (msb * 0x1021);
355 }
356 crc as u16
357}
358
359/// The MD5 digest of each plane, as the SEI hash defines it. `None` when the
360/// sample arrays do not match the picture size.
361pub fn plane_digests(pic: &DecodedPicture) -> Option<Vec<[u8; 16]>> {
362 let planes = [&pic.y, &pic.cb, &pic.cr];
363 let mut bytes: Vec<Vec<u8>> = Vec::new();
364 let mut dims: Vec<(usize, usize)> = Vec::new();
365 for (c, ((samples, (w, h)), _)) in planes
366 .iter()
367 .zip(plane_dims(pic))
368 .zip(PLANE_NAMES)
369 .enumerate()
370 {
371 if samples.is_empty() {
372 continue;
373 }
374 if samples.len() != w * h {
375 return None;
376 }
377 let bps = bytes_per_sample(pic, c);
378 let mut buf = Vec::with_capacity(samples.len() * bps);
379 for &s in samples.iter() {
380 if bps == 1 {
381 buf.push(s as u8);
382 } else {
383 buf.extend_from_slice(&s.to_le_bytes());
384 }
385 }
386 bytes.push(buf);
387 dims.push((w * bytes_per_sample(pic, c), h));
388 }
389 let refs: Vec<(&[u8], usize, usize, usize)> = bytes
390 .iter()
391 .zip(&dims)
392 .map(|(b, &(row_bytes, h))| (b.as_slice(), row_bytes, row_bytes, h))
393 .collect();
394 let rbsp = decoded_picture_hash_rbsp(&refs);
395 let messages = parse_sei_rbsp(&rbsp).ok()?;
396 messages.into_iter().find_map(|m| match m {
397 SeiMessage::DecodedPictureHash(PictureHash::Md5(digests)) => Some(digests),
398 _ => None,
399 })
400}
401
402/// Plane sizes as (width, height) for Y, Cb and Cr, at the picture's chroma format.
403pub fn plane_dims(pic: &DecodedPicture) -> [(usize, usize); 3] {
404 let (cw, ch) = pic.chroma_dims();
405 [(pic.width, pic.height), (cw, ch), (cw, ch)]
406}
407
408/// Per plane, whether the picture matches the SEI hash of the same kind. An MD5
409/// digest is compared with the whole digest; a CRC or checksum with its value.
410pub fn plane_matches(pic: &DecodedPicture, expected: &PictureHash) -> Vec<bool> {
411 let planes = [&pic.y, &pic.cb, &pic.cr];
412 let dims = plane_dims(pic);
413 match expected {
414 PictureHash::Md5(want) => {
415 let got = plane_digests(pic).unwrap_or_default();
416 want.iter()
417 .enumerate()
418 .map(|(i, w)| got.get(i) == Some(w))
419 .collect()
420 }
421 PictureHash::Crc(want) => want
422 .iter()
423 .enumerate()
424 .map(|(i, &w)| {
425 planes
426 .get(i)
427 .is_some_and(|p| plane_crc(p, pic.bit_depth_of(i)) == w)
428 })
429 .collect(),
430 PictureHash::Checksum(want) => want
431 .iter()
432 .enumerate()
433 .map(|(i, &w)| {
434 planes
435 .get(i)
436 .is_some_and(|p| plane_checksum(p, dims[i].0, pic.bit_depth_of(i)) == w)
437 })
438 .collect(),
439 }
440}
441
442/// The digest in a `<name>_md5.txt` file: its first word, as 32 hex digits. That file holds the
443/// MD5 of the whole decoded output (every frame, cropped, in output order).
444pub fn whole_output_digest(text: &str) -> Option<[u8; 16]> {
445 let word = text.split_whitespace().next()?;
446 if word.len() != 32 {
447 return None;
448 }
449 let mut out = [0u8; 16];
450 for (i, byte) in out.iter_mut().enumerate() {
451 *byte = u8::from_str_radix(word.get(2 * i..2 * i + 2)?, 16).ok()?;
452 }
453 Some(out)
454}
455
456pub fn fnv1a(bytes: &[u8]) -> u64 {
457 let mut hash = 0xcbf29ce484222325u64;
458 for &b in bytes {
459 hash ^= b as u64;
460 hash = hash.wrapping_mul(0x100000001b3);
461 }
462 hash
463}