forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

gen_coverage_cells.rs323 lines, 14.1 KiBHistoryRawDownload
1//! Generator for the two AV1 coverage cells no encoder emits, so both are
2//! GATED rather than left as declared debt (`lanes/av1formatsweep.report.md`
3//! §6.4 and its "declared debt" note: the `4:2:0 with an odd luma dimension`
4//! and `4:4:0 (ss 0,1)` rows were "unmeasured and unproducible by recipe").
5//!
6//! Both cells are produced here, offline, with no encoder and no ffmpeg:
7//!
8//! 1. **`420_odd65x65_key.obu`** -- a 4:2:0 key frame whose header declares
9//! an ODD luma size (65x65). aomenc cannot produce this one: it rounds the
10//! coded size DOWN to even (`av1enc_set_frame_size`; the measured
11//! `testsrc2 131x131` y4m comes out as `max_frame=130x130`), so the cell
12//! needs the encoder to be told what size to DECLARE. That is
13//! [`ec_av1::encode::encode_key_frame_at_size`]: a 96x96 picture padded to
14//! the block grid, coded with a 65x65 frame header. The result is a real,
15//! fully decodable AV1 stream -- the gate compares it sample for sample
16//! against the instrumented `aomdec`.
17//!
18//! 2. **`440_request_is_422.obu`** -- what this crate's writer produces when
19//! it is HANDED 4:4:0 (`subsampling_x = 0`, `subsampling_y = 1`). The
20//! cell turns out not to exist: `subsampling_y` is coded only when
21//! `subsampling_x` is 1 (spec 5.5.2 `color_config`), so a sequence header
22//! carries 4:2:0 `(1,1)`, 4:2:2 `(1,0)` or 4:4:4 `(0,0)` and never
23//! `(0,1)` -- libaom's own writer ASSERTS it ("4:4:0 subsampling not
24//! allowed in AV1", `av1/encoder/bitstream.c:2467-2468`) and its reader
25//! forces
26//! `subsampling_y = 0` when `subsampling_x` is 0
27//! (`av1_read_color_config`, `av1/decoder/decodeframe.c:4171-4175`).
28//! aomenc having no `yuv440p` input path and ffmpeg's y4m muxer refusing
29//! the format ("yuv4mpeg can only handle yuv444p, yuv422p, yuv420p,
30//! yuv411p and gray8") are consequences of that, not the reason. The pin
31//! is the byte-level evidence: a 4:4:0 request at profile 2 (4:2:2, and
32//! no coded subsampling bit below 12 bits) lands on `(1,0)`. The frame OBU
33//! behind it is a real 4:2:0 key frame's, byte for byte -- the subsampling
34//! lives only in the sequence header -- so the pin is a HEADER witness, NOT
35//! a decodable 4:2:2 stream. lane-av1422lift: it was never decodable as
36//! one; the decoder used to refuse it at the sequence header, and now
37//! admits the header, which is exactly why this pin may not be turned into
38//! a 4:2:2 exactness gate. The gate
39//! `the_440_cell_is_not_a_codable_chroma_shape` says exactly that, and the
40//! real 4:2:2 exactness lives in `a_real_422_stream_decodes_pixel_exact`
41//! and `the_pinned_422_corpus_cells_decode_pixel_exact`, which read
42//! genuinely 4:2:2 pins.
43//!
44//! ```text
45//! cargo run -p ec-av1 --example gen_coverage_cells -- crates/ec-av1/fixtures
46//! sha256sum crates/ec-av1/fixtures/420_odd65x65_key.obu \
47//! crates/ec-av1/fixtures/440_request_is_422.obu
48//! ```
49//!
50//! Both files are deterministic: the source card is a fixed integer pattern
51//! and the encoder is deterministic, so re-running this overwrites the pins
52//! with the same bytes. `ec-av1` is a hand-code-only repository -- do NOT run
53//! `cargo fmt` on this file; rustfmt runs at commit time and its churn is
54//! accepted, never reverted.
55
56use ec_av1::encode::Picture;
57use ec_av1_syntax::{ColorConfig, ObuKind};
58
59/// The padded coding surface the odd cell is cut from: a whole number of
60/// 32x32 blocks (`Picture::check`'s own rule), and a multiple of 8 above the
61/// 65x65 it declares, so no declared column is already block-aligned.
62const PAD: usize = 96;
63
64/// The odd-luma cell's DECLARED frame size. Both dimensions odd on purpose:
65/// the 4:2:0 chroma extent is then `ROUND_POWER_OF_TWO(65, 1) = 33` in each
66/// axis (libaom `av1_common_plane_width`, `av1/common/av1_common_int.h`),
67/// which is where a floor (32) and a ceil (33) disagree -- the whole reason
68/// the cell was worth closing.
69const ODD: usize = 65;
70
71/// The 4:4:0 witness's frame size, and the quantizer both streams are coded
72/// at. Even, so nothing else about the witness is unusual: the shape is 4:4:0
73/// and nothing else.
74const WITNESS: usize = 64;
75
76/// `base_q_idx` for both cells. Mid-scale on purpose: high enough that a
77/// block carries real coefficients (so a wrong chroma extent shows in the
78/// output), low enough that the stream stays small.
79const Q_IDX: u8 = 100;
80
81/// A deterministic, high-frequency card: a 2-D pattern whose wrapped
82/// diagonal jumps, so every 8x8 block has real high-frequency content and
83/// therefore real coefficients. That matters for the odd cell -- a flat or
84/// smooth card predicts to within a quantizer step of a constant in its last
85/// column too, so a wrong chroma extent could leave the OUTPUT unchanged and
86/// the gate would then be green on broken code.
87fn card(width: usize, height: usize) -> Picture {
88 let mut picture = Picture::grey(width, height);
89 for row in 0..height {
90 for col in 0..width {
91 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
92 }
93 }
94 for row in 0..height / 2 {
95 for col in 0..width / 2 {
96 let i = row * (width / 2) + col;
97 picture.u[i] = ((row * 13 + col * 29) % 241) as u16;
98 picture.v[i] = ((row * 17 + col * 5) % 239) as u16;
99 }
100 }
101 picture
102}
103
104/// The chroma shape of the 4:4:0 witness: profile 0 with `subsampling_x = 0`
105/// and `subsampling_y = 1`. Profile 0 forces neither subsampling bit (only
106/// profile 1 forces 4:4:4 and profile 2 below 12 bits forces 4:2:2, spec
107/// 5.5.2), so both are coded in the header and `(0, 1)` -- 4:4:0 -- is legal
108/// there.
109fn yuv440() -> ColorConfig {
110 ColorConfig {
111 bit_depth: 8,
112 mono_chrome: false,
113 num_planes: 3,
114 color_primaries: 2,
115 transfer_characteristics: 2,
116 matrix_coefficients: 2,
117 color_range: false,
118 subsampling_x: 0,
119 subsampling_y: 1,
120 chroma_sample_position: ec_av1_syntax::ChromaSamplePosition::Unknown,
121 separate_uv_delta_q: false,
122 }
123}
124
125/// Writes `bytes` to `<dir>/<name>`, then reports size, FNV-1a64 and sha256.
126fn emit(dir: &str, name: &str, bytes: &[u8]) {
127 let path = std::path::Path::new(dir).join(name);
128 std::fs::write(&path, bytes).unwrap_or_else(|e| panic!("writing {}: {e}", path.display()));
129 let mut fnv: u64 = 0xcbf2_9ce4_8422_2325;
130 for &b in bytes {
131 fnv = (fnv ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
132 }
133 println!("{name}: {} bytes, fnv1a64 {fnv:016x}", bytes.len());
134 // sha256sum is coreutils, present on every host this runs on; the pins'
135 // provenance comments in `stream.rs` quote its output.
136 let out = std::process::Command::new("sha256sum")
137 .arg(&path)
138 .output()
139 .expect("sha256sum");
140 assert!(
141 out.status.success(),
142 "sha256sum failed on {}",
143 path.display()
144 );
145 println!(
146 "{name}: sha256 {}",
147 String::from_utf8_lossy(&out.stdout)
148 .split_whitespace()
149 .next()
150 .expect("a sha256sum line")
151 );
152}
153
154/// The subsampling and the max frame size a reader gets back out of `bytes`
155/// -- the generator never takes the shape it wrote on faith, it re-parses
156/// its own output.
157fn read_back(name: &str, bytes: &[u8]) -> (u8, u8, u32, u32) {
158 let mut parser = ec_av1_syntax::Av1Parser::new();
159 let mut pos = 0usize;
160 while pos < bytes.len() && parser.sequence_header().is_none() {
161 let obu = parser
162 .parse_obu(&bytes[pos..])
163 .unwrap_or_else(|e| panic!("{name}: OBU at byte {pos} does not parse: {e:?}"));
164 pos += obu.total_size;
165 }
166 let seq = parser
167 .sequence_header()
168 .unwrap_or_else(|| panic!("{name}: no sequence header parsed back out of its own bytes"));
169 (
170 seq.color_config.subsampling_x,
171 seq.color_config.subsampling_y,
172 seq.max_frame_width,
173 seq.max_frame_height,
174 )
175}
176
177/// The bytes of `stream`'s single `OBU_FRAME`, OBU header and size field
178/// included. An example cannot reach `Encoded::tile` (crate-private, and
179/// documented as a `crate::decode` test-only reader) and does not need to:
180/// the OBU is right there in the stream the encoder just wrote.
181fn frame_obu_of(stream: &[u8], name: &str) -> Vec<u8> {
182 let mut parser = ec_av1_syntax::Av1Parser::new();
183 let mut pos = 0usize;
184 while pos < stream.len() {
185 let obu = parser
186 .parse_obu(&stream[pos..])
187 .unwrap_or_else(|e| panic!("{name}: OBU at byte {pos} does not parse: {e:?}"));
188 if matches!(obu.kind, ObuKind::Frame(..)) {
189 return stream[pos..pos + obu.total_size].to_vec();
190 }
191 pos += obu.total_size;
192 }
193 panic!(
194 "{name}: no frame OBU in a {}-byte key frame stream",
195 stream.len()
196 );
197}
198
199fn main() {
200 let dir = std::env::args()
201 .nth(1)
202 .unwrap_or_else(|| "crates/ec-av1/fixtures".to_string());
203 std::fs::create_dir_all(&dir).expect("output dir");
204
205 // ---- cell 1: 4:2:0 with an odd luma dimension -------------------------
206 let encoded = ec_av1::encode::encode_key_frame_at_size(&card(PAD, PAD), ODD, ODD, Q_IDX, 0.5)
207 .expect("encoding the odd-luma key frame");
208 let (sx, sy, mw, mh) = read_back("420_odd65x65_key", &encoded.stream);
209 assert_eq!(
210 (sx, sy),
211 (1, 1),
212 "the odd cell must stay 4:2:0 -- it is the luma SIZE that is odd, not the shape"
213 );
214 assert_eq!(
215 (mw, mh),
216 (ODD as u32, ODD as u32),
217 "the odd cell's sequence header must declare {ODD}x{ODD}"
218 );
219 assert_eq!(
220 (encoded.reconstruction.width, encoded.reconstruction.height),
221 (ODD, ODD),
222 "the returned reconstruction must be cropped to the DECLARED size"
223 );
224 assert_eq!(
225 encoded.reconstruction.u.len(),
226 ODD.div_ceil(2) * ODD.div_ceil(2),
227 "a 4:2:0 frame of odd luma size keeps the ceil chroma extent"
228 );
229 println!(
230 "420_odd65x65_key: max_frame {mw}x{mh} at ({sx},{sy}), chroma {}x{} \
231 (ROUND_POWER_OF_TWO({ODD},1) = {}), mi {}x{}, reconstruction {}x{} luma + {} chroma \
232 samples",
233 ODD.div_ceil(2),
234 ODD.div_ceil(2),
235 ODD.div_ceil(2),
236 2 * ((ODD + 7) >> 3),
237 2 * ((ODD + 7) >> 3),
238 encoded.reconstruction.width,
239 encoded.reconstruction.height,
240 encoded.reconstruction.u.len(),
241 );
242 emit(&dir, "420_odd65x65_key.obu", &encoded.stream);
243
244 // ---- cell 2: the 4:4:0 (ss 0,1) row ------------------------------------
245 // 4:4:0 is NOT A CELL: `subsampling_y` is coded only when
246 // `subsampling_x` is 1 (spec 5.5.2 `color_config`), so a header can
247 // carry 4:2:0 (1,1), 4:2:2 (1,0) or 4:4:4 (0,0) and never (0,1).
248 // libaom asserts it in its own writer --
249 // `assert(seq_params->subsampling_y == 0 && "4:4:0 subsampling not
250 // allowed in AV1")`, av1/encoder/bitstream.c:2467-2468 -- and its reader
251 // leaves `subsampling_y = 0` when `subsampling_x` is 0
252 // (`av1_read_color_config`, av1/decoder/decodeframe.c:4171-4175).
253 //
254 // So this file pins WHAT A 4:4:0 REQUEST PRODUCES: the writer handed
255 // subsampling (0,1) at profile 2, which below 12 bits is 4:2:2 and codes
256 // no subsampling bit at all, and the request lands on (1,0). The frame
257 // OBU behind it is a real 4:2:0 key frame's, byte for byte: the
258 // subsampling lives only in the sequence header, so the frame header is
259 // the same one either way. The stream is NOT a decodable 4:2:2 stream
260 // (its tile is 4:2:0). lane-av1422lift: the decoder no longer refuses it
261 // by name, and that is NOT an endorsement -- the header now claims 4:2:2
262 // over a 4:2:0 tile, so a decode of these bytes is a header/tile
263 // mismatch. This pin stays a byte-level shape witness; every 4:2:2
264 // exactness claim lives on genuinely 4:2:2 pins in `stream.rs`.
265 let tile_stream = ec_av1::encode::encode_key_frame(&card(WITNESS, WITNESS), Q_IDX, 0.5)
266 .expect("encoding the witness tile")
267 .stream;
268 let frame_bytes = frame_obu_of(&tile_stream, "the 4:4:0 request's tile");
269 let (mut seq, _header) =
270 ec_av1::encode::key_frame_headers_colour(WITNESS, WITNESS, Q_IDX, yuv440())
271 .expect("building the 4:4:0-request sequence header");
272 seq.seq_profile = 2;
273 let mut witness =
274 ec_av1::sequence::sequence_header_obu(&seq).expect("writing that sequence header");
275 witness.extend_from_slice(&frame_bytes);
276 let (sx, sy, mw, mh) = read_back("440_request_is_422", &witness);
277 assert_eq!(
278 (sx, sy),
279 (1, 0),
280 "a 4:4:0 request at profile 2 must land on 4:2:2 (1,0). If it ever reads back (0,1), \
281 4:4:0 became codable and the whole cell-2 story is wrong."
282 );
283 assert_eq!(
284 (mw, mh),
285 (WITNESS as u32, WITNESS as u32),
286 "the request stream's frame size"
287 );
288 // The frame OBU behind the header must still parse as the frame header
289 // the 4:2:0 stream carried.
290 let mut parser = ec_av1_syntax::Av1Parser::new();
291 let first = parser
292 .parse_obu(&witness)
293 .expect("the request's sequence header OBU parses");
294 let frame = match parser
295 .parse_obu(&witness[first.total_size..])
296 .expect("the request's frame OBU parses")
297 .kind
298 {
299 ObuKind::Frame(h, tiles) => {
300 assert_eq!(
301 tiles.len(),
302 1,
303 "the request stream carries exactly one tile"
304 );
305 h
306 }
307 other => panic!("440_request_is_422: expected a frame OBU, got {other:?}"),
308 };
309 assert_eq!(
310 (frame.frame_width, frame.frame_height),
311 (WITNESS as u32, WITNESS as u32),
312 "the request stream's frame header must name its own size"
313 );
314 println!(
315 "440_request_is_422: asked for subsampling (0,1) at profile {} -- got ({sx},{sy}) at \
316 max_frame {mw}x{mh}, i.e. 4:2:2 (DECODED since lane-av1422lift, but these bytes carry \
317 a 4:2:0 tile, so the pin is a shape witness and not an exactness witness); frame header + \
318 one tile ({} bytes) from a 4:2:0 {WITNESS}x{WITNESS} key frame",
319 seq.seq_profile,
320 frame_bytes.len()
321 );
322 emit(&dir, "440_request_is_422.obu", &witness);
323}