forge
Explore
Log in

Don't you dare go Hollow

lane-av1rawhelper: derive assert_rawvideo_matches packing from the stream's bit depth

Browse files at this commit

e95fa153c3e4b0d792d9140f824ab2fa761358f0Ahmet Kaan GümüşParent: 6f07b44
The helper packed our samples as u16 for every stream while aomdec --rawvideo
writes 8 bits per sample for an 8-bit stream, so an 8-bit caller died on a
raw-SIZE assert (ours 2x the oracle) without comparing a single sample, and the
failure read like a data bug. Nothing in the signature said the helper was
high-bit-depth only.

- stream_bit_depth(): the depth comes from the stream's own sequence header
- pack_rawvideo(): 1 byte/sample at 8-bit, 2 LE at 10/12-bit, u8 range asserted
- assert_rawvideo_matches(): takes the caller's depth label and asserts it
  against the parsed header, failing by name before any packing
- new gate: a real aomenc 8-bit stream compared sample-for-sample, plus a
  wrong-label arm that pins the loud failure so a reverted check is caught
crates/ec-av1/src/stream.rsmodified+193 -11
@@ -5019,9 +5019,77 @@ pub(crate) mod tests {
5019 bytes5019 bytes
5020 }5020 }
5021 5021
5022+ /// The bit depth the stream's OWN sequence header declares, read from
5023+ /// the bytes rather than taken from the gate's name or recipe (class
5024+ /// `helper-packs-u16-for-an-8-bit-stream`: aomdec's `--rawvideo`
5025+ /// writes 8 bits per sample for an 8-bit stream and 16 bits LE for a
5026+ /// high-bitdepth one, so a u16 packer turns every 8-bit compare into a
5027+ /// raw-SIZE failure that never looks at a sample).
5028+ fn stream_bit_depth(stream: &[u8], name: &str) -> u8 {
5029+ let mut probe = Av1Parser::new();
5030+ let mut pos = 0usize;
5031+ while pos < stream.len() && probe.sequence_header().is_none() {
5032+ let obu = probe
5033+ .parse_obu(&stream[pos..])
5034+ .unwrap_or_else(|e| panic!("{name}: OBU at byte {pos} does not parse: {e:?}"));
5035+ pos += obu.total_size;
5036+ }
5037+ probe
5038+ .sequence_header()
5039+ .unwrap_or_else(|| panic!("{name}: the stream carries no sequence header OBU"))
5040+ .color_config
5041+ .bit_depth
5042+ }
5043+
5044+ /// Packs decoded planes the way `aomdec --rawvideo` writes them for
5045+ /// `bit_depth`: 1 byte per sample at 8-bit, 2 bytes little-endian at
5046+ /// 10/12-bit. Plane order is Y, U, V at the frame's own subsampled
5047+ /// shape, which is exactly what rawvideo emits.
5048+ fn pack_rawvideo(decoded: &[Pic], bit_depth: u8, name: &str) -> Vec<u8> {
5049+ let mut ours: Vec<u8> = Vec::new();
5050+ for (fi, f) in decoded.iter().enumerate() {
5051+ for p in [&f.y, &f.u, &f.v] {
5052+ if bit_depth == 8 {
5053+ for &s in p {
5054+ assert!(
5055+ s <= 0xff,
5056+ "{name}: decode-order frame {fi} carries the sample {s}, which an \
5057+ 8-bit stream cannot hold -- the stream is not the one this gate thinks \
5058+ it is"
5059+ );
5060+ ours.push(s as u8);
5061+ }
5062+ } else {
5063+ for &s in p {
5064+ ours.extend_from_slice(&s.to_le_bytes());
5065+ }
5066+ }
5067+ }
5068+ }
5069+ ours
5070+ }
5071+
5022 /// Decodes `stream` and the oracle's `aomdec --rawvideo` output and5072 /// Decodes `stream` and the oracle's `aomdec --rawvideo` output and
5023 /// requires every sample of every frame to agree, in decode order.5073 /// requires every sample of every frame to agree, in decode order.
5024- fn assert_rawvideo_matches(obu: &std::path::Path, stream: &[u8], name: &str, frames: usize) {5074+ ///
5075+ /// `bit_depth` is the depth the CALLER believes the stream has; it is
5076+ /// asserted against the stream's own sequence header, so a gate that
5077+ /// hands this an 8-bit stream under a 10-bit label fails here by name
5078+ /// instead of dying on a raw-size mismatch that reads like a pixel bug.
5079+ fn assert_rawvideo_matches(
5080+ obu: &std::path::Path,
5081+ stream: &[u8],
5082+ name: &str,
5083+ frames: usize,
5084+ bit_depth: u8,
5085+ ) {
5086+ let actual_depth = stream_bit_depth(stream, name);
5087+ assert_eq!(
5088+ actual_depth, bit_depth,
5089+ "{name}: the stream's sequence header says {actual_depth}-bit, the gate passed \
5090+ {bit_depth}-bit -- aomdec's --rawvideo writes {actual_depth} bits per sample for it, \
5091+ so packing for {bit_depth} compares nothing"
5092+ );
5025 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));5093 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
5026 let _ = std::fs::remove_dir_all(&dir);5094 let _ = std::fs::remove_dir_all(&dir);
5027 std::fs::create_dir_all(&dir).expect("scratch dir");5095 std::fs::create_dir_all(&dir).expect("scratch dir");
@@ -5043,15 +5111,20 @@ pub(crate) mod tests {
5043 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");5111 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
5044 let _ = std::fs::remove_dir_all(&dir);5112 let _ = std::fs::remove_dir_all(&dir);
5045 let decoded = decode_stream(stream).expect("decode for comparison");5113 let decoded = decode_stream(stream).expect("decode for comparison");
5046- let mut ours: Vec<u8> = Vec::with_capacity(ref_raw.len());5114+ let ours = pack_rawvideo(&decoded, bit_depth, name);
5047- for f in &decoded {5115+ assert_eq!(
5048- for p in [&f.y, &f.u, &f.v] {5116+ ours.len(),
5049- for s in p {5117+ ref_raw.len(),
5050- ours.extend_from_slice(&s.to_le_bytes());5118+ "{name}: {bit_depth}-bit raw sizes differ -- ours packs {} bytes ({} samples at \
5051- }5119+ {} bit/sample), aomdec wrote {}",
5052- }5120+ ours.len(),
5053- }5121+ decoded
5054- assert_eq!(ours.len(), ref_raw.len(), "{name}: raw sizes differ");5122+ .iter()
5123+ .map(|f| f.y.len() + f.u.len() + f.v.len())
5124+ .sum::<usize>(),
5125+ bit_depth,
5126+ ref_raw.len()
5127+ );
5055 assert_eq!(decoded.len(), frames, "{name}: frame count");5128 assert_eq!(decoded.len(), frames, "{name}: frame count");
5056 let first = ours5129 let first = ours
5057 .iter()5130 .iter()
@@ -5067,6 +5140,115 @@ pub(crate) mod tests {
5067 );5140 );
5068 }5141 }
5069 5142
5143+ /// lane-av1rawhelper: `assert_rawvideo_matches` used to pack our samples
5144+ /// as `u16` for EVERY stream, while `aomdec --rawvideo` writes 8 bits
5145+ /// per sample for an 8-bit stream. An 8-bit caller therefore died on a
5146+ /// raw-SIZE assertion (2359296 vs 1179648) without comparing a single
5147+ /// sample, and a high-bitdepth caller was the only one that could work.
5148+ ///
5149+ /// Two arms, both on a real `aomenc` 8-bit stream:
5150+ ///
5151+ /// 1. the correct label compares real samples -- the byte counts it
5152+ /// walks equal the oracle's, so every `u8` in the 8-bit pack is
5153+ /// zipped against a real oracle byte;
5154+ /// 2. a WRONG label fails by name, quoting both depths and the fact that
5155+ /// the pack would compare nothing, rather than by size. Arm 2 is what
5156+ /// keeps arm 1 from being a green that a reverted check would also
5157+ /// give.
5158+ #[test]
5159+ fn the_rawvideo_helper_compares_real_samples_at_the_streams_own_bit_depth() {
5160+ const NAME: &str = "the_rawvideo_helper_compares_real_samples_at_the_streams_own_bit_depth";
5161+ let _gate_lock = lock_gate_counters();
5162+ if !have_aomenc() || !have_ffmpeg() {
5163+ eprintln!("SKIP {NAME}: no aomenc/aomdec oracle or no ffmpeg");
5164+ return;
5165+ }
5166+ let (w, h) = (192usize, 128usize);
5167+ let y4m = Command::new("ffmpeg")
5168+ .args([
5169+ "-v",
5170+ "error",
5171+ "-f",
5172+ "lavfi",
5173+ "-i",
5174+ &gradients_source(7, w, h, "duration=0.24:rate=25"),
5175+ "-pix_fmt",
5176+ "yuv420p",
5177+ "-t",
5178+ "0.24",
5179+ "-f",
5180+ "yuv4mpegpipe",
5181+ "-",
5182+ ])
5183+ .stdin(Stdio::null())
5184+ .stdout(Stdio::piped())
5185+ .stderr(Stdio::piped())
5186+ .output()
5187+ .expect("ffmpeg failed to run");
5188+ assert!(
5189+ y4m.status.success(),
5190+ "{NAME}: ffmpeg fixture: {}",
5191+ String::from_utf8_lossy(&y4m.stderr)
5192+ );
5193+ let args: Vec<&str> = vec![
5194+ "--codec=av1",
5195+ "--passes=1",
5196+ "--end-usage=q",
5197+ "--cq-level=40",
5198+ "--cpu-used=2",
5199+ "--threads=1",
5200+ "--row-mt=0",
5201+ "--limit=6",
5202+ "--obu",
5203+ "-o",
5204+ "-",
5205+ "-",
5206+ ];
5207+ let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
5208+ assert!(
5209+ out.status.success(),
5210+ "{NAME}: aomenc refused the fixture: {}",
5211+ String::from_utf8_lossy(&out.stderr)
5212+ );
5213+ let stream = out.stdout;
5214+ assert_eq!(
5215+ stream_bit_depth(&stream, NAME),
5216+ 8,
5217+ "{NAME}: the fixture must really be 8-bit, or this gate measures nothing"
5218+ );
5219+ let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-raw8-{}", std::process::id()));
5220+ let _ = std::fs::remove_dir_all(&dir);
5221+ std::fs::create_dir_all(&dir).expect("scratch dir");
5222+ let obu = dir.join("in.obu");
5223+ std::fs::write(&obu, &stream).expect("writing the stream");
5224+ let frames = decode_stream(&stream)
5225+ .unwrap_or_else(|e| panic!("{NAME}: the 8-bit stream no longer decodes: {e}"))
5226+ .len();
5227+ assert!(frames > 0, "{NAME}: nothing decoded");
5228+
5229+ // ARM 2 first: the wrong label must be refused BY NAME. A helper that
5230+ // packed u16 unconditionally got this far and then failed on size.
5231+ let wrong = std::panic::catch_unwind(|| {
5232+ assert_rawvideo_matches(&obu, &stream, NAME, frames, 10);
5233+ });
5234+ let boom = wrong
5235+ .err()
5236+ .map(|e| e.downcast_ref::<String>().cloned().unwrap_or_default())
5237+ .unwrap_or_default();
5238+ assert!(
5239+ boom.contains("sequence header says 8-bit") && boom.contains("compares nothing"),
5240+ "{NAME}: a 10-bit label on an 8-bit stream must be refused by the depth check \
5241+ naming both depths; the panic read: {boom}"
5242+ );
5243+
5244+ // ARM 1: the correct label compares real samples. The pre-fix helper
5245+ // reached a size mismatch here (ours 2x the oracle); reaching the
5246+ // sample compare is what this arm proves.
5247+ assert_rawvideo_matches(&obu, &stream, NAME, frames, 8);
5248+ let _ = std::fs::remove_dir_all(&dir);
5249+ eprintln!("{NAME}: {frames} 8-bit frame(s) byte-identical to aomdec --rawvideo");
5250+ }
5251+
5070 fn fnv1a64(bytes: &[u8]) -> u64 {5252 fn fnv1a64(bytes: &[u8]) -> u64 {
5071 let mut hash = 0xcbf29ce484222325u64;5253 let mut hash = 0xcbf29ce484222325u64;
5072 for &b in bytes {5254 for &b in bytes {
@@ -6886,7 +7068,7 @@ pub(crate) mod tests {
6886 let _ = decode_stream(&ctrl_stream)7068 let _ = decode_stream(&ctrl_stream)
6887 .unwrap_or_else(|e| panic!("{NAME}: the control arm no longer decodes cleanly: {e}"));7069 .unwrap_or_else(|e| panic!("{NAME}: the control arm no longer decodes cleanly: {e}"));
6888 if aomdec_path().is_file() {7070 if aomdec_path().is_file() {
6889- assert_rawvideo_matches(&ctrl, &ctrl_stream, NAME, FRAMES);7071+ assert_rawvideo_matches(&ctrl, &ctrl_stream, NAME, FRAMES, 10);
6890 } else {7072 } else {
6891 eprintln!(7073 eprintln!(
6892 "SKIP {NAME} control aomdec arm: no oracle aomdec at {}",7074 "SKIP {NAME} control aomdec arm: no oracle aomdec at {}",
lanes/av1rawhelper.report.mdadded+144 -0
@@ -0,0 +1,144 @@
1+# lane-av1rawhelper — `assert_rawvideo_matches` cannot judge an 8-bit stream
2+
3+**Branch:** `lane-av1rawhelper`
4+**Base:** `7f8817cbcbb567fd1c037c2d3780bdf12c0d2b14` ("Merge lane-av1pins @ 44a05b40 — three
5+recovered pins committed under the crate + gate rewiring"), taken at lane start while the
6+13-branch merge wave was landing in main. Worktree `~/.cache/wt/av1rawhelper`; main was never
7+touched.
8+**Scope:** tests + test helpers only. No decoder logic touched (`git diff --stat`:
9+`crates/ec-av1/src/stream.rs` only, and only its `#[cfg(test)]` module).
10+
11+## 1. Audit
12+
13+### 1a. `assert_rawvideo_matches` call sites
14+
15+Before this lane the helper had exactly **one** call site in the whole crate. It packed our
16+samples as `u16` unconditionally (`for s in p { ours.extend_from_slice(&s.to_le_bytes()) }`)
17+while `aomdec --rawvideo` writes 8 bits/sample for an 8-bit stream.
18+
19+| file:line | gate | stream bit depth (source) | helper packing matches? | outcome on a real run |
20+|---|---|---|---|---|
21+| `stream.rs:6877` (pre-fix) | `a_lossless_444_128_root_lossless_stream_reads_chunks_chunk_major` control arm | **10-bit**, from the gate's own recipe doc (`testsrc2 128x96 yuv444p10le`, `--profile=1 --lossless=1`) and from the fixture's parsed sequence header | YES — `u16` LE is what `--rawvideo` writes at 10-bit | PASS, a real compare: 6 frames byte-identical. Re-verified post-fix (see §3) |
22+| *(none — the defect was latent)* | any 8-bit gate | 8-bit | NO — `u16` pack vs 8-bit oracle | dies on `raw sizes differ` with no sample compared |
23+
24+There was no in-tree 8-bit caller. That is exactly why the defect survived: the single caller
25+happened to be high-bit-depth. The handing lane hit it the moment an 8-bit gate appeared.
26+
27+### 1b. Every other raw-comparison helper in the crate
28+
29+| helper | file:line | oracle | packing | 8-bit safe? | verdict |
30+|---|---|---|---|---|---|
31+| `decode_all_frames_vs_oracle` | `stream.rs:9217` | `EC_AV1_FINAL_DUMP` rung 12, both sides | **depth-aware on BOTH sides** — ours at `stream.rs:2142` (`if bit_depth == 8 { as u8 } else { to_le_bytes() }`), the oracle at `scripts/instrument-aom-oracle.sh` rung 12 (`YV12_FLAG_HIGHBITDEPTH` → `fwrite(...,2,...)` else `(...,1,...)`) | YES | correct as written; the depth is the frame's own `bit_depth`, not the gate's label |
32+| `ffmpeg_decode_sequence` | `stream.rs:5270` | `ffmpeg -pix_fmt yuv420p` | 8-bit by construction, size-asserted before unpacking | n/a (8-bit only) | correct |
33+| `ffmpeg_decode_gray_sequence` | `stream.rs:5322` | `ffmpeg -pix_fmt gray` | 8-bit, mono | n/a | correct |
34+| `ffmpeg_decode_sequence_10bit` | `stream.rs:5353` | `-pix_fmt yuv420p10le` | 2-byte LE, size-asserted | n/a | correct |
35+| `ffmpeg_decode_sequence_12bit` | `stream.rs:13211` | `-pix_fmt yuv420p12le` | 2-byte LE, size-asserted | n/a | correct |
36+| `dump_yuv` (example) | `examples/dump_yuv.rs:33` | none — a dump tool the user diffs by hand | `u16` LE, documented as the **high-bit-depth companion** to `EC_AV1_PREFILT_DUMP` | not a gate; its doc names `yuv420p10le` | left alone — not a gate, and its contract is explicitly HBD |
37+| `assert_rawvideo_matches` | `stream.rs:5012` (pre-fix) | `aomdec --rawvideo` | `u16` unconditional | **NO** | **the defect** |
38+
39+`decode_all_frames_vs_oracle` is the model the fix follows: it already derives the packing from
40+the decoded frame's own bit depth, and its oracle side is bit-depth correct in the instrument
41+script, so both sides agree at any depth.
42+
43+## 2. Fix
44+
45+Three changes, all in the `#[cfg(test)]` module of `crates/ec-av1/src/stream.rs`:
46+
47+1. **`stream_bit_depth(stream, name) -> u8`** (new, `stream.rs:5016`): parses the stream's own
48+ sequence-header OBU and returns `color_config.bit_depth`. The depth comes from the bytes, not
49+ from the gate's name or recipe.
50+2. **`pack_rawvideo(decoded, bit_depth, name)`** (new, `stream.rs:5036`): packs Y, U, V per
51+ frame in the frame's own subsampled shape — 1 byte/sample at 8-bit, 2 bytes LE at 10/12-bit.
52+ At 8-bit it hard-asserts every sample `<= 0xff` and names the frame, so a decode that
53+ produced out-of-range samples is caught as "this is not an 8-bit stream", not as a pixel
54+ diff.
55+3. **`assert_rawvideo_matches(..., bit_depth: u8)`** (`stream.rs:5067`): the label is now an
56+ explicit argument, asserted against `stream_bit_depth` before anything else runs. A
57+ mismatched label panics naming both depths and the consequence ("packing for 10 compares
58+ nothing") instead of dying later on a raw-size mismatch. The size assertion now prints
59+ `{bit_depth}-bit`, our byte count, the sample count, and the oracle's byte count, so a size
60+ failure reads as a packing problem rather than a data bug.
61+
62+An 8-bit call now **works correctly** rather than being refused: the u8 path is the tightly
63+packed planes, which is what `aomdec --rawvideo` emits. The loud failure is reserved for the
64+genuinely-wrong case (a label that contradicts the header), and it names the depths.
65+
66+The one existing call site (`stream.rs:7056`) now passes `10`, which the new assert confirms
67+against the fixture's own header.
68+
69+## 3. Proof, both directions
70+
71+New gate: `the_rawvideo_helper_compares_real_samples_at_the_streams_own_bit_depth`
72+(`stream.rs:5144`). It builds a real `aomenc` 8-bit stream from an ffmpeg `gradients` source
73+(192x128, `--limit=6`, `--obu`), asserts the stream really is 8-bit from its parsed header, and
74+then runs **two** arms.
75+
76+**Green-after (8-bit, compares real samples):**
77+```
78+the_rawvideo_helper_compares_real_samples_at_the_streams_own_bit_depth:
79+ 6 8-bit frame(s) byte-identical to aomdec --rawvideo
80+test result: ok. 1 passed; 0 failed
81+```
82+
83+**Wrong-label arm (must fail by name, not by size):** the same stream handed in with a
84+`10` label panics with
85+```
86+the stream's sequence header says 8-bit, the gate passed 10-bit -- aomdec's --rawvideo
87+writes 8 bits per sample for it, so packing for 10 compares nothing
88+```
89+caught by `catch_unwind` and asserted on its text. Without this arm the gate would be a green
90+that a reverted depth check would also give.
91+
92+**Red-before (fix reverted, both symptoms return):** I set `pack_rawvideo`'s depth branch to
93+`if false` and deleted the depth assert, rebuilt, and reran. The 8-bit gate fails exactly the
94+way the handing lane measured:
95+```
96+10-bit raw sizes differ -- ours packs 442368 bytes (221184 samples at 10 bit/sample),
97+aomdec wrote 221184
98+ left: 442368
99+ right: 221184
100+...
101+a 10-bit label on an 8-bit stream must be refused by the depth check naming both depths;
102+the panic read: ... raw sizes differ ...
103+test result: FAILED
104+```
105+221184 vs 442368 is the same 2x raw-size class as the handing lane's 2359296 vs 1179648, at
106+this gate's smaller geometry. **Not one sample is compared on that path.** The fix was then
107+restored and both arms went green again.
108+
109+**Unchanged high-bit-depth gate:** the helper's only pre-existing caller,
110+`a_lossless_444_128_root_lossless_stream_reads_chunks_chunk_major`, passes post-fix
111+(`test result: ok. 1 passed`). Its control arm still runs the same 6-frame `u16` LE compare
112+against `aomdec --rawvideo` — the new label argument matches what the packing already did, so
113+the arm's substance is untouched.
114+
115+**Cross-check on the other helper:** `a_pinned_rect_stream_with_a_64x64_intra_block_in_an_inter_frame_decodes_pixel_exact`
116+(an 8-bit stream through `decode_all_frames_vs_oracle`) passes, confirming that helper's
117+depth-aware path is sound at 8-bit and is not part of the defect.
118+
119+## 4. False greens
120+
121+**None found, and the reason matters: the defect produced a hard failure, never a silent
122+pass.** The pre-fix helper asserted `ours.len() == ref_raw.len()` before comparing anything,
123+and a `u16` pack of an 8-bit stream is exactly 2x the oracle's size, so the assert always
124+fired. The 8-bit cell was a **loud, misleading failure**, not a vacuous green: the test
125+reported "raw sizes differ" and a reader would reasonably read that as a decoder or fixture
126+bug rather than as "this helper cannot judge this stream". No gate in the suite was reporting
127+a pass it had not earned through this helper.
128+
129+What *was* silently absent: any 8-bit coverage of `assert_rawvideo_matches` itself. The only
130+caller was 10-bit, so the helper's 8-bit path had never been exercised and no test asserted
131+anything about it. The new gate closes that, and its wrong-label arm is what makes the depth
132+check itself non-vacuous.
133+
134+Two adjacent traps checked and left alone, both outside this lane's scope (tests/helpers only,
135+and neither is a false green):
136+
137+- `dump_yuv` (`examples/dump_yuv.rs`) packs `u16` unconditionally, like the old helper. It is
138+ a diagnostic dump tool, not a gate, and its docstring states it is the high-bit-depth
139+ companion to `EC_AV1_PREFILT_DUMP` and names `yuv420p10le` as the reference. Handing an
140+ 8-bit stream to it produces a dump that will not `cmp` against `yuv420p10le` — same trap,
141+ but the contract is documented and nothing asserts on it. Flagging for a follow-up lane, not
142+ fixing here.
143+- `ffmpeg_decode_sequence*` all hard-code their own pix_fmt and size-assert before unpacking,
144+ so a depth mismatch is a loud failure there too.