forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

interlaced.rs213 lines, 7.1 KiBHistoryRawDownload
1//! Interlaced H.264 (frame_mbs_only_flag 0): field pictures (PAFF) and
2//! macroblock-adaptive frame/field coding (MBAFF), woven into frames.
3//!
4//! The authority is the JVT conformance suite: each vector's reference YUV is
5//! compared frame by frame. Fixtures live in the gitignored root `fixtures/`
6//! (`scripts/fetch-vectors.sh`); a missing one skips with a message, or fails
7//! when `EC_REQUIRE_FIXTURES` is set, like the other conformance tests.
8
9use std::path::{Path, PathBuf};
10
11use ec_core::frame::{Interlace, VideoFrame};
12use ec_h264::{Decoder, NalOutcome};
13
14/// Where a vector lives: the interlaced set (`scripts/fetch-vectors.sh`), or
15/// the general JVT set for the few interlaced streams that were fetched first.
16fn vector_dir(name: &str) -> PathBuf {
17 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/vectors");
18 let own = root.join("h264-jvt-interlaced").join(name);
19 if own.exists() {
20 own
21 } else {
22 root.join("h264-jvt").join(name)
23 }
24}
25
26/// True when `path` exists; otherwise skip (or fail under `EC_REQUIRE_FIXTURES`).
27fn have_fixture(path: &Path, what: &str) -> bool {
28 if path.exists() {
29 return true;
30 }
31 assert!(
32 std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
33 "{what} missing at {} - this gate would prove nothing; run \
34 scripts/link-fixtures.sh or scripts/fetch-vectors.sh",
35 path.display()
36 );
37 eprintln!("SKIP {what} missing at {}", path.display());
38 false
39}
40
41fn find_with_ext(dir: &Path, exts: &[&str]) -> Option<PathBuf> {
42 let mut found: Vec<PathBuf> = std::fs::read_dir(dir)
43 .ok()?
44 .flatten()
45 .map(|e| e.path())
46 .filter(|p| {
47 p.extension()
48 .and_then(|x| x.to_str())
49 .is_some_and(|x| exts.contains(&x.to_ascii_lowercase().as_str()))
50 })
51 .collect();
52 found.sort();
53 found.into_iter().next()
54}
55
56fn frame_bytes(frame: &VideoFrame) -> Vec<u8> {
57 let (w, h) = (frame.width as usize, frame.height as usize);
58 let dims = [
59 (w, h),
60 (w.div_ceil(2), h.div_ceil(2)),
61 (w.div_ceil(2), h.div_ceil(2)),
62 ];
63 let mut out = Vec::new();
64 for (plane, (pw, ph)) in frame.planes.iter().zip(dims) {
65 for y in 0..ph {
66 out.extend_from_slice(plane.row(y, pw).expect("plane row"));
67 }
68 }
69 out
70}
71
72/// Every output frame (display order) with its interlace flag.
73fn decode_all(bytes: &[u8]) -> Result<Vec<(Vec<u8>, Interlace)>, ec_h264::Error> {
74 let mut dec = Decoder::new();
75 let mut frames = Vec::new();
76 for nal in ec_h264_syntax::AnnexBIter::new(bytes) {
77 if dec.push_nal(nal)? == NalOutcome::PictureBoundary {
78 dec.end_picture()?;
79 dec.push_nal(nal)?;
80 }
81 while let Some(f) = dec.next_frame() {
82 frames.push((frame_bytes(&f), f.interlace));
83 }
84 }
85 dec.flush()?;
86 while let Some(f) = dec.next_frame() {
87 frames.push((frame_bytes(&f), f.interlace));
88 }
89 Ok(frames)
90}
91
92/// Decode one JVT vector and compare it with its reference YUV.
93fn check_vector(name: &str) -> Result<usize, String> {
94 let dir = vector_dir(name);
95 if !have_fixture(&dir, &format!("JVT vector {name}")) {
96 return Ok(0);
97 }
98 let stream = find_with_ext(&dir, &["jsv", "264", "avc", "26l", "h264", "jvt"])
99 .ok_or(format!("{name}: no bitstream"))?;
100 let yuv = find_with_ext(&dir, &["yuv"]).ok_or(format!("{name}: no reference YUV"))?;
101 let frames =
102 decode_all(&std::fs::read(&stream).unwrap()).map_err(|e| format!("{name}: {e}"))?;
103 let reference = std::fs::read(&yuv).unwrap();
104 let len = frames.first().ok_or(format!("{name}: no frames"))?.0.len();
105 if frames.len() * len != reference.len() {
106 return Err(format!(
107 "{name}: {} frames decoded, reference has {}",
108 frames.len(),
109 reference.len() / len
110 ));
111 }
112 for (i, (f, il)) in frames.iter().enumerate() {
113 let want = &reference[i * len..(i + 1) * len];
114 if let Some(pos) = f.iter().zip(want).position(|(a, b)| a != b) {
115 return Err(format!("{name}: frame {i} differs at byte {pos}"));
116 }
117 if !il.is_interlaced() {
118 return Err(format!("{name}: frame {i} is not flagged interlaced"));
119 }
120 }
121 Ok(frames.len())
122}
123
124fn sweep(names: &[&str]) {
125 let mut failed = Vec::new();
126 for name in names {
127 match check_vector(name) {
128 Ok(n) => eprintln!("exact {name} ({n} frames)"),
129 Err(e) => {
130 eprintln!("MISMATCH {e}");
131 failed.push(e);
132 }
133 }
134 }
135 assert!(failed.is_empty(), "{failed:#?}");
136}
137
138/// The three interlaced groups, each formerly its own `#[test]`:
139///
140/// * Field pictures: I/P/B fields, field pairs and lone fields, frame and field
141/// pictures mixed (PAFF), CAVLC and CABAC, field reference marking with MMCO.
142/// * High profile field pictures: 8x8 transform with the field scans, CABAC,
143/// 8x8 intra prediction in field pictures.
144/// * MBAFF frames: macroblock pairs with a per-pair field flag, CAVLC and CABAC,
145/// I/P/B slices, spatial and temporal direct, implicit and explicit weights,
146/// constrained intra prediction, 8x8 transform with scaling lists, and PAFF
147/// pictures mixed with MBAFF frames. Every JVT MBAFF vector is bit-exact.
148const GROUPS: &[(&str, &[&str])] = &[
149 (
150 "jvt_paff_vectors_bit_exact",
151 &[
152 "CVFI1_Sony_D",
153 "CVFI1_SVA_C",
154 "CVFI2_SVA_C",
155 "CVNLFI1_Sony_C",
156 "CVNLFI2_Sony_H",
157 "FI1_Sony_E",
158 "CAFI1_SVA_C",
159 "Sharp_MP_Field_1_B",
160 "Sharp_MP_Field_3_B",
161 "Sharp_MP_PAFF_1r2",
162 "CVPA1_TOSHIBA_B",
163 "CABREF3_Sand_D",
164 "MR6_BT_B",
165 "MR7_BT_B",
166 "MR8_BT_B",
167 ],
168 ),
169 ("jvt_frext_field_vectors_bit_exact", &["HCAFF1_HHI_B"]),
170 (
171 "jvt_mbaff_vectors_bit_exact",
172 &[
173 "CVMA1_Sony_D",
174 "CVMA1_TOSHIBA_B",
175 "CVMANL1_TOSHIBA_B",
176 "CVMANL2_TOSHIBA_B",
177 "CVMAQP2_Sony_G",
178 "CVMAQP3_Sony_D",
179 "CVMAPAQP3_Sony_E",
180 "CAMA1_Sony_C",
181 "CAMA1_TOSHIBA_B",
182 "CAMANL1_TOSHIBA_B",
183 "CAMANL2_TOSHIBA_B",
184 "CAMANL3_Sand_E",
185 "CAMA3_Sand_E",
186 "CAMACI3_Sony_C",
187 "CAMASL3_Sony_B",
188 "cama1_vtc_c",
189 "cama2_vtc_b",
190 "cama3_vtc_b",
191 "CAMP_MOT_MBAFF_L30",
192 "CAMP_MOT_MBAFF_L31",
193 "CAPAMA3_Sand_F",
194 "FRExt2_Panasonic_C",
195 "FRExt4_Panasonic_B",
196 "MR9_BT_B",
197 ],
198 ),
199];
200
201/// Every group in [`GROUPS`] is bit-exact. Each group runs under
202/// `catch_unwind`, so one failing group does not hide the others.
203#[test]
204fn jvt_interlaced_vectors_bit_exact() {
205 let mut failures = Vec::new();
206 for (name, vectors) in GROUPS {
207 let run = std::panic::AssertUnwindSafe(|| sweep(vectors));
208 if std::panic::catch_unwind(run).is_err() {
209 failures.push(*name);
210 }
211 }
212 assert!(failures.is_empty(), "failed cases: {failures:?}");
213}