forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli4 days ago4021 commits

scaledref_exact.rs172 lines, 6.4 KiBHistoryRawDownload
1//! Scaled-reference witness: an inter frame whose reference slot holds a
2//! picture of a DIFFERENT coded size must scale that reference during
3//! prediction (`vp9_setup_scale_factors_for_frame` + the scaled convolve
4//! walk) and come out byte-identical to libvpx. `scaledref.ivf` scales
5//! 1280x720 -> 640x360 (`x_step_q4 == y_step_q4 == 32`); the paired
6//! `scaledref_odd.ivf` is the same stream with the keyframe patched to
7//! 1279x719, so the reference is an ODD coded extent and its chroma crop
8//! ceils — the interaction with the odd-dimension layout.
9//!
10//! The fixtures are committed under `tests/data/` because no ffmpeg
11//! invocation can produce a size change: libvpx's encoder emits one only
12//! through its rate-control resize path (ffmpeg exposes neither
13//! `rc_resize_allowed` nor SVC), and a hand-spliced explicit-size inter frame trips
14//! libvpx's own header reparsing. The generator is recorded in
15//! `lanes/vp9refsetup.report.md`: a 1280x720 one-pass CBR encode at 200 kbps,
16//! whose `vp9_resize_one_pass_cbr` downscales frame 1 to 640x360 against the
17//! keyframe. `scaledref_odd.ivf` is that same file through
18//! `$HOME/.cache/vp9pix/patch_kf_size.py <in> <out> 1279 719` (which rewrites
19//! the IVF container size too).
20//!
21//! Oracle caveat: ffmpeg locks its rawvideo output size to the FIRST decoded
22//! frame's, so a two-size stream cannot be dumped in one pass. Frame 0 is
23//! decoded on its own (`-frames:v 1`, identity); frames 2..N are decoded with
24//! `select=gte(n,1)` at the small size, where the filtergraph has
25//! re-initialised and every frame passes through unchanged. The size-change
26//! frame (file frame 1) is the one ffmpeg mangles during that
27//! re-initialisation, so it is checked INDIRECTLY: every later frame predicts
28//! from its reconstruction, so a wrong scaler fails frames 2..N.
29
30use crate::ivf;
31
32use ec_vp9::decode::Decoder;
33use ec_vp9_syntax::{FrameType, Vp9Parser};
34
35fn fixture(name: &str) -> std::path::PathBuf {
36 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
37 .join("tests/data")
38 .join(name)
39}
40
41/// Run ffmpeg over `path` with `args` and return its rawvideo stdout.
42fn ffmpeg_raw(path: &std::path::Path, args: &[&str]) -> Vec<u8> {
43 let out = std::process::Command::new("ffmpeg")
44 .args(["-v", "error", "-y", "-i"])
45 .arg(path)
46 .args(args)
47 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
48 .output()
49 .expect("ffmpeg on PATH");
50 assert!(out.status.success(), "ffmpeg decode failed: {out:?}");
51 out.stdout
52}
53
54fn frame_bytes(w: usize, h: usize) -> usize {
55 w * h + 2 * w.div_ceil(2) * h.div_ceil(2)
56}
57
58fn assert_planes(pic: &ec_vp9::decode::Picture, want: &[u8], label: &str) {
59 let mut got = Vec::with_capacity(want.len());
60 got.extend(pic.y.iter().map(|&v| v as u8));
61 got.extend(pic.u.iter().map(|&v| v as u8));
62 got.extend(pic.v.iter().map(|&v| v as u8));
63 assert_eq!(got.len(), want.len(), "{label}: plane size");
64 let diff = got.iter().zip(want).position(|(a, b)| a != b);
65 assert!(
66 diff.is_none(),
67 "{label}: pixel mismatch at byte {:?} (ours {} libvpx {})",
68 diff,
69 diff.map(|d| got[d]).unwrap_or(0),
70 diff.map(|d| want[d]).unwrap_or(0)
71 );
72}
73
74fn check(name: &str) {
75 let path = fixture(name);
76 let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
77 let (_, cw, ch, frames) = ivf::parse_ivf(&bytes);
78
79 // Non-vacuity: the stream must carry an inter frame whose coded size
80 // differs from the frame before it — the only shape that makes a
81 // reference scale.
82 let mut parser = Vp9Parser::new();
83 let mut sizes: Vec<(u32, u32, FrameType)> = Vec::new();
84 for f in &frames {
85 for sub in ec_vp9_syntax::split(&f.data).unwrap() {
86 let hdr = parser.parse_frame(sub).unwrap();
87 sizes.push((hdr.width, hdr.height, hdr.frame_type));
88 }
89 }
90 let changed = sizes
91 .windows(2)
92 .filter(|p| p[0].0 != p[1].0 || p[0].1 != p[1].1)
93 .count();
94 assert!(
95 changed >= 1,
96 "{name}: the fixture must change coded size mid-stream (sizes: {sizes:?})"
97 );
98 assert!(
99 sizes
100 .iter()
101 .any(|s| s.2 == FrameType::Inter && (s.0, s.1) != (cw as u32, ch as u32)),
102 "{name}: an inter frame must differ from the container's declared size"
103 );
104
105 let mut decoder = Decoder::new();
106 let ours: Vec<_> = frames
107 .iter()
108 .map(|f| decoder.decode(&f.data).expect("frame decodes"))
109 .collect();
110 let shown: Vec<_> = ours.iter().filter_map(|p| p.as_ref()).collect();
111 assert_eq!(shown.len(), 10, "{name}: the fixture has 10 visible frames");
112
113 // Frame 0 (the keyframe) alone; identity.
114 let oracle0 = ffmpeg_raw(&path, &["-frames:v", "1"]);
115 assert_eq!(
116 oracle0.len(),
117 frame_bytes(shown[0].width as usize, shown[0].height as usize),
118 "{name}: frame 0 oracle size"
119 );
120 assert_planes(shown[0], &oracle0, &format!("{name} frame 0"));
121
122 // Frames 2..N: after the size change every frame passes through the
123 // filtergraph unchanged at the small size.
124 let small = (shown[2].width as usize, shown[2].height as usize);
125 assert!(
126 small != (shown[0].width as usize, shown[0].height as usize),
127 "{name}: frames after the change must be resized"
128 );
129 let oracle_rest = ffmpeg_raw(
130 &path,
131 &[
132 "-vf",
133 "select=gte(n\\,1)",
134 "-fps_mode",
135 "passthrough",
136 "-s",
137 &format!("{}x{}", small.0, small.1),
138 ],
139 );
140 let fbs = frame_bytes(small.0, small.1);
141 assert_eq!(
142 oracle_rest.len(),
143 fbs * (shown.len() - 2),
144 "{name}: ffmpeg must emit frames 2..{}",
145 shown.len() - 1
146 );
147 for (j, pic) in shown[2..].iter().enumerate() {
148 assert_eq!(
149 (pic.width as usize, pic.height as usize),
150 small,
151 "{name}: frame {} size",
152 j + 2
153 );
154 assert_planes(
155 pic,
156 &oracle_rest[j * fbs..(j + 1) * fbs],
157 &format!("{name} frame {}", j + 2),
158 );
159 }
160}
161
162#[test]
163fn size_changing_reference_decodes_byte_exact() {
164 check("scaledref.ivf");
165}
166
167/// The same size change with an ODD coded reference: 1279x719 -> 640x360,
168/// where the reference's chroma crop ceils (`(1279 + 1) / 2`).
169#[test]
170fn size_changing_odd_reference_decodes_byte_exact() {
171 check("scaledref_odd.ivf");
172}