forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

streams.rs324 lines, 11.3 KiBHistoryRawDownload
1//! Every AV1 fixture stream parsed end to end, field-compared against ffprobe.
2//!
3//! `scripts/gen-bitstream-fixtures.sh` remuxes the container fixtures to IVF and
4//! encodes the branch cases (4:4:4, monochrome, tiles, hidden ALTREF). Fixtures
5//! are gitignored, so a checkout without them skips rather than fails.
6
7use std::path::{Path, PathBuf};
8use std::process::Command;
9
10use ec_av1_syntax::{Av1Parser, FrameType, ObuKind};
11use ec_core::Error;
12
13fn bitstreams() -> PathBuf {
14 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/bitstreams")
15}
16
17/// The IVF frames of a file — for AV1, each is one temporal unit.
18fn ivf_frames(data: &[u8]) -> Vec<&[u8]> {
19 let mut out = Vec::new();
20 let mut pos = 32; // DKIF file header
21 while pos + 12 <= data.len() {
22 let size = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize;
23 pos += 12;
24 if pos + size > data.len() {
25 break;
26 }
27 out.push(&data[pos..pos + size]);
28 pos += size;
29 }
30 out
31}
32
33fn ffprobe(path: &Path, entries: &str) -> Vec<String> {
34 let out = Command::new("ffprobe")
35 .args(["-v", "error", "-select_streams", "v:0", "-show_entries"])
36 .arg(entries)
37 .args(["-of", "csv=p=0"])
38 .arg(path)
39 .output()
40 .expect("ffprobe runs");
41 String::from_utf8_lossy(&out.stdout)
42 .lines()
43 .map(|l| l.trim_end_matches(',').to_string())
44 .collect()
45}
46
47/// `(width, height, pix_fmt, seq_profile)` as ffprobe sees the stream.
48fn probe_stream(path: &Path) -> (u32, u32, String, u8) {
49 let line = ffprobe(path, "stream=profile,width,height,pix_fmt")
50 .into_iter()
51 .next()
52 .expect("one video stream");
53 let f: Vec<&str> = line.split(',').collect();
54 let profile = match f[0] {
55 "Main" => 0,
56 "High" => 1,
57 "Professional" => 2,
58 other => panic!("unexpected AV1 profile {other:?}"),
59 };
60 (
61 f[1].parse().unwrap(),
62 f[2].parse().unwrap(),
63 f[3].to_string(),
64 profile,
65 )
66}
67
68/// `bit_depth, mono_chrome, subsampling_x, subsampling_y` from a pixel format.
69fn pix_fmt_geometry(pix_fmt: &str) -> (u8, bool, u8, u8) {
70 let depth = if pix_fmt.contains("10le") {
71 10
72 } else if pix_fmt.contains("12le") {
73 12
74 } else {
75 8
76 };
77 if pix_fmt.starts_with("gray") {
78 // Monochrome codes subsampling as 4:2:0 and has no chroma planes.
79 return (depth, true, 1, 1);
80 }
81 let (sx, sy) = if pix_fmt.starts_with("yuv444") {
82 (0, 0)
83 } else if pix_fmt.starts_with("yuv422") {
84 (1, 0)
85 } else {
86 (1, 1)
87 };
88 (depth, false, sx, sy)
89}
90
91fn fixtures() -> Vec<PathBuf> {
92 let Ok(entries) = std::fs::read_dir(bitstreams()) else {
93 return Vec::new();
94 };
95 let mut files: Vec<PathBuf> = entries
96 .filter_map(|e| e.ok().map(|e| e.path()))
97 .filter(|p| {
98 p.extension().is_some_and(|e| e == "ivf")
99 && p.file_name()
100 .is_some_and(|n| n.to_string_lossy().starts_with("av1-"))
101 })
102 .collect();
103 files.sort();
104 files
105}
106
107/// One pass over a stream: what the parser saw.
108#[derive(Default)]
109struct Tally {
110 frames: usize,
111 shown: Vec<bool>,
112 show_existing: usize,
113 hidden: usize,
114 tiles: usize,
115 max_tiles_per_frame: usize,
116}
117
118#[test]
119fn every_fixture_matches_ffprobe() {
120 let files = fixtures();
121 if files.is_empty() {
122 eprintln!(
123 "skipped: no fixtures/bitstreams/av1-*.ivf — run scripts/gen-bitstream-fixtures.sh"
124 );
125 return;
126 }
127 for path in files {
128 let name = path.file_name().unwrap().to_string_lossy().to_string();
129 let (width, height, pix_fmt, profile) = probe_stream(&path);
130 let (bit_depth, mono, sx, sy) = pix_fmt_geometry(&pix_fmt);
131 let ffprobe_keys: Vec<bool> = ffprobe(&path, "frame=key_frame")
132 .iter()
133 .map(|l| l == "1")
134 .collect();
135
136 let data = std::fs::read(&path).unwrap();
137 let mut parser = Av1Parser::new();
138 let mut t = Tally::default();
139 let mut sequences = 0usize;
140
141 for (unit, chunk) in ivf_frames(&data).iter().enumerate() {
142 let obus = parser
143 .parse_temporal_unit(chunk)
144 .unwrap_or_else(|e| panic!("{name}: temporal unit {unit}: {e}"));
145 for obu in obus {
146 match &obu.kind {
147 ObuKind::SequenceHeader(seq) => {
148 sequences += 1;
149 assert_eq!(seq.seq_profile, profile, "{name}: seq_profile");
150 let c = seq.color_config;
151 assert_eq!(c.bit_depth, bit_depth, "{name}: bit depth ({pix_fmt})");
152 assert_eq!(c.mono_chrome, mono, "{name}: mono_chrome");
153 assert_eq!(
154 (c.subsampling_x, c.subsampling_y),
155 (sx, sy),
156 "{name}: subsampling"
157 );
158 assert_eq!(c.num_planes, if mono { 1 } else { 3 }, "{name}: planes");
159 assert_eq!(seq.max_frame_width, width, "{name}: max width");
160 assert_eq!(seq.max_frame_height, height, "{name}: max height");
161 }
162 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => {
163 t.frames += 1;
164 if h.show_existing_frame {
165 t.show_existing += 1;
166 t.shown.push(false);
167 continue;
168 }
169 assert_eq!(
170 (h.upscaled_width, h.frame_height),
171 (width, height),
172 "{name}: frame size"
173 );
174 assert_eq!(
175 (h.render_width, h.render_height),
176 (width, height),
177 "{name}: render size"
178 );
179 assert!(h.tile_info.cols >= 1 && h.tile_info.rows >= 1);
180 if h.show_frame {
181 t.shown.push(h.frame_type == FrameType::Key);
182 } else {
183 t.hidden += 1;
184 }
185 }
186 _ => {}
187 }
188 if let ObuKind::Frame(_, tiles) | ObuKind::TileGroup(tiles) = &obu.kind {
189 t.tiles += tiles.len();
190 t.max_tiles_per_frame = t.max_tiles_per_frame.max(tiles.len());
191 for tile in tiles {
192 // Every tile must lie inside the temporal unit it came from.
193 assert!(
194 tile.offset + tile.size <= chunk.len(),
195 "{name}: tile {} runs past the temporal unit",
196 tile.tile_num
197 );
198 assert!(tile.size > 0, "{name}: empty tile");
199 }
200 }
201 }
202 }
203
204 assert!(sequences > 0, "{name}: no sequence header");
205 assert_eq!(
206 t.shown.len(),
207 ffprobe_keys.len(),
208 "{name}: shown frame count ({} coded, {} hidden, {} show_existing)",
209 t.frames,
210 t.hidden,
211 t.show_existing
212 );
213 assert_eq!(t.shown, ffprobe_keys, "{name}: key frame flags");
214 if name.contains("tiles") {
215 assert_eq!(
216 t.max_tiles_per_frame, 4,
217 "{name}: -tiles 2x2 should give 4 tiles"
218 );
219 }
220 println!(
221 "{name}: {} coded / {} shown, {} hidden, {} show_existing, {} tiles (max {}/frame), \
222 profile {profile}, {bit_depth}-bit{}, {width}x{height}",
223 t.frames,
224 t.shown.len(),
225 t.hidden,
226 t.show_existing,
227 t.tiles,
228 t.max_tiles_per_frame,
229 if mono { " mono" } else { "" }
230 );
231 }
232}
233
234/// libaom shows its hidden ALTREF with a `show_existing_frame` header; that path
235/// resolves a real reference slot, which is the one thing a synthetic header
236/// cannot prove.
237#[test]
238fn altref_fixture_has_hidden_frames_and_show_existing() {
239 let path = bitstreams().join("av1-altref.ivf");
240 if !path.exists() {
241 eprintln!("skipped: no av1-altref.ivf");
242 return;
243 }
244 let data = std::fs::read(&path).unwrap();
245 let mut parser = Av1Parser::new();
246 let (mut hidden, mut show_existing, mut showable) = (0usize, 0usize, 0usize);
247 for chunk in ivf_frames(&data) {
248 for obu in parser.parse_temporal_unit(chunk).unwrap() {
249 if let ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) = &obu.kind {
250 if h.show_existing_frame {
251 show_existing += 1;
252 let slot = parser.reference_slots()[h.frame_to_show_map_idx as usize];
253 assert!(slot.valid, "show_existing_frame names an empty slot");
254 assert_eq!(
255 (h.frame_width, h.frame_height),
256 (slot.frame_width, slot.frame_height)
257 );
258 } else if !h.show_frame {
259 hidden += 1;
260 // A hidden frame that is shown later must say so; one that is
261 // only ever a reference need not, and libaom codes both.
262 showable += usize::from(h.showable_frame);
263 }
264 }
265 }
266 }
267 assert!(hidden > 0, "no hidden ALTREF frame");
268 assert!(show_existing > 0, "no show_existing_frame header");
269 assert!(showable > 0, "no hidden frame was marked showable");
270 println!(
271 "av1-altref.ivf: {hidden} hidden ({showable} showable), {show_existing} show_existing"
272 );
273}
274
275/// Truncation, bit flips and random noise: an error, never a panic.
276#[test]
277fn fuzz_10k_mutations_never_panics() {
278 let seeds: Vec<Vec<u8>> = fixtures()
279 .iter()
280 .take(3)
281 .filter_map(|p| std::fs::read(p).ok())
282 .flat_map(|data| {
283 ivf_frames(&data)
284 .into_iter()
285 .take(4)
286 .map(|f| f[..f.len().min(512)].to_vec())
287 .collect::<Vec<_>>()
288 })
289 .collect();
290 let seeds = if seeds.is_empty() {
291 vec![vec![
292 0x0au8, 0x0b, 0x00, 0x00, 0x00, 0x24, 0xcf, 0x7f, 0x0d, 0xbf, 0xff, 0x30, 0x08,
293 ]]
294 } else {
295 seeds
296 };
297
298 let mut state = 0x9e37_79b9_7f4a_7c15u64;
299 let mut rng = move || {
300 state ^= state << 13;
301 state ^= state >> 7;
302 state ^= state << 17;
303 state
304 };
305 let mut errors = 0usize;
306 for i in 0..10_000 {
307 let mut buf = seeds[(rng() as usize) % seeds.len()].clone();
308 let mutations = 1 + (rng() as usize) % 8;
309 for _ in 0..mutations {
310 let at = (rng() as usize) % buf.len();
311 buf[at] ^= (rng() % 256) as u8;
312 }
313 if i % 3 == 0 {
314 buf.truncate((rng() as usize) % buf.len().max(1));
315 }
316 let mut parser = Av1Parser::new();
317 match parser.parse_temporal_unit(&buf) {
318 Ok(_) => {}
319 Err(Error::NeedMore | Error::Corrupt { .. }) => errors += 1,
320 Err(e) => panic!("unexpected error kind: {e}"),
321 }
322 }
323 println!("fuzz: 10000 mutations, {errors} rejected");
324}