diff --git a/crates/ec-av1/examples/dump_yuv.rs b/crates/ec-av1/examples/dump_yuv.rs index a253237e..d2924069 100644 --- a/crates/ec-av1/examples/dump_yuv.rs +++ b/crates/ec-av1/examples/dump_yuv.rs @@ -1,20 +1,68 @@ -//! Decode one OBU stream and write every frame's planes as raw little-endian -//! `u16` (`.f.yuv`) — the high-bit-depth companion to -//! `EC_AV1_PREFILT_DUMP`, whose `as u8` narrowing throws away exactly the bits -//! a 10-bit mismatch lives in (lane-rect1d r1 found its defect by diffing this -//! against `ffmpeg -pix_fmt yuv420p10le -f rawvideo`). +//! Decode one OBU stream and write every frame's planes as raw planar video +//! (`.f.yuv`), at the sample depth **the stream's own sequence +//! header carries**: 8-bit as one byte per sample, 10/12-bit as little-endian +//! `u16`. That is the layout `ffmpeg -pix_fmt yuv420p{,10,12}le -f rawvideo` +//! and `aomdec --rawvideo` write, so a byte-exact `cmp` against either is +//! meaningful. +//! +//! It is the high-bit-depth companion to `EC_AV1_PREFILT_DUMP`, whose `as u8` +//! narrowing throws away exactly the bits a 10-bit mismatch lives in +//! (lane-rect1d r1 found its defect by diffing this against +//! `ffmpeg -pix_fmt yuv420p10le -f rawvideo`). //! //! ```text //! cargo run -p ec-av1 --example dump_yuv -- s.obu /tmp/ours //! ffmpeg -v error -i s.obu -pix_fmt yuv420p10le -f rawvideo /tmp/ref.yuv //! cmp /tmp/ours.f0.yuv /tmp/ref.yuv //! ``` +//! +//! The depth is NEVER taken from the file name, the output extension, or the +//! `-pix_fmt` of a reference tool: it is parsed out of the sequence header +//! (spec 5.5.2 `color_config.bit_depth`) before a single byte is written. The +//! old version packed every sample as `u16` unconditionally, so pointing it at +//! an 8-bit stream silently produced a file TWICE the size of the oracle's, +//! and the size mismatch read like a decoder bug. `--depth N` is accepted for +//! the case where you already know what the stream is, and is ASSERTED against +//! the parsed header: a mismatch names both depths and the consequence it +//! would have caused, and writes nothing. +//! +//! `i` in `.f.yuv` indexes `decode_stream`'s output, which is +//! DISPLAY order and SHOWN frames only -- hidden alt-refs are never emitted. +//! Every other `.f{N}` in this crate (EC_AV1_FINAL_DUMP, +//! EC_AV1_DECODE_ORDER_DUMP, EC_AV1_PREFILT_DUMP) uses a DECODE index, so this +//! file does NOT line up with an aomdec dump past frame 0 on a stream with +//! altref. Compare against ffmpeg rawvideo, or against aomdec via +//! `decode_all_frames_vs_oracle`. fn main() { - let mut args = std::env::args().skip(1); - let (Some(path), Some(out)) = (args.next(), args.next()) else { - eprintln!("usage: dump_yuv "); + let argv: Vec = std::env::args().skip(1).collect(); + let (Some(path), Some(out)) = (argv.first().cloned(), argv.get(1).cloned()) else { + eprintln!("usage: dump_yuv [--depth 8|10|12]"); std::process::exit(2); }; + // An ASSERTED expectation, not a switch: the packing always follows the + // parsed header, and a wrong `--depth` is a hard error before any file. + let mut claimed_depth: Option = None; + let mut rest = argv[2.min(argv.len())..].iter(); + while let Some(arg) = rest.next() { + let value = arg + .strip_prefix("--depth=") + .map(str::to_string) + .or_else(|| (arg == "--depth").then(|| rest.next().cloned()).flatten()); + let Some(value) = value else { + eprintln!("dump_yuv: unknown argument `{arg}`"); + eprintln!("usage: dump_yuv [--depth 8|10|12]"); + std::process::exit(2); + }; + let Ok(depth) = value.parse::() else { + eprintln!("dump_yuv: --depth `{value}` is not a bit depth (8, 10 or 12)"); + std::process::exit(2); + }; + if claimed_depth.is_some() { + eprintln!("dump_yuv: --depth given twice; the depth is asserted, not a switch"); + std::process::exit(2); + } + claimed_depth = Some(depth); + } let data = match std::fs::read(&path) { Ok(data) => data, Err(e) => { @@ -22,6 +70,87 @@ fn main() { std::process::exit(2); } }; + + // The stream's OWN header, read before the decode so a depth mismatch is + // reported instead of a file. Scans OBU by OBU because the sequence header + // need not be the first OBU (decode_probe walks it the same way). + let mut parser = ec_av1_syntax::Av1Parser::new(); + let mut pos = 0usize; + while pos < data.len() && parser.sequence_header().is_none() { + let Ok(obu) = parser.parse_obu(&data[pos..]) else { + break; + }; + pos += obu.total_size.max(1); + } + let Some(seq) = parser.sequence_header() else { + eprintln!( + "dump_yuv: {path}: no sequence header parsed, so the sample depth is unknown. \ + Refusing to guess: packing u16 blind is what wrote a 2x-size file for every 8-bit \ + stream. Re-checkout the stream (an IVF container parses as zero frames too), or pass \ + a raw OBU stream." + ); + std::process::exit(1); + }; + let cfg = &seq.color_config; + let bit_depth = cfg.bit_depth; + if let Some(claimed) = claimed_depth { + if claimed != bit_depth { + let theirs = if bit_depth == 8 { + format!( + "aomdec --rawvideo / ffmpeg -pix_fmt yuv420p ({} bytes per sample, \ + W*H*3/2 for 4:2:0)", + 1 + ) + } else { + format!( + "aomdec --rawvideo / ffmpeg -pix_fmt yuv420p{}le ({} bytes per sample, \ + W*H*3 for 4:2:0)", + bit_depth, 2 + ) + }; + eprintln!( + "dump_yuv: {path}: --depth {claimed} contradicts the stream's own sequence \ + header, which carries bit_depth {bit_depth} (seq_profile {}, \ + subsampling {}/{}, mono_chrome {}). Writing {claimed}-bit would emit \ + {} bytes per sample against the oracle's {theirs}, so every `cmp` would fail on \ + size alone and read like a decoder defect. Nothing was written.", + seq.seq_profile, + cfg.subsampling_x, + cfg.subsampling_y, + cfg.mono_chrome, + if claimed == 8 { 1 } else { 2 }, + ); + std::process::exit(1); + } + } + // 8 bit -> one byte per sample; anything above -> little-endian u16, which + // is what both oracles emit for `*p10le` / `*p12le` (they never pack to + // the bit depth itself, they use a full 16-bit container). + let bytes_per_sample = if bit_depth == 8 { 1 } else { 2 }; + // Spec 5.5.3 `subsampling_{x,y}`: 1/1 IS 4:2:0 (measured on this crate's own + // 8-bit 192x128 fixture, which parses 1/1 and yields 36864 samples for a + // 192x128 frame = W*H*3/2), 0/0 is 4:4:4, 1/0 is 4:2:2, 0/1 is 4:4:0. + let chroma = match (cfg.mono_chrome, cfg.subsampling_x, cfg.subsampling_y) { + (true, _, _) => "gray", + (false, 0, 0) => "yuv444p", + (false, 0, 1) => "yuv440p", + (false, 1, 0) => "yuv422p", + _ => "yuv420p", + }; + let pix_fmt = match (chroma, bit_depth) { + (c, 8) => c.to_string(), + ("gray", _) => "gray16le".to_string(), + (c, 10) => format!("{c}10le"), + (c, 12) => format!("{c}12le"), + (c, d) => format!("{c}{d}le"), + }; + let max = (1u32 << bit_depth) - 1; + println!( + "sequence header: bit_depth {bit_depth} -> {bytes_per_sample} byte(s) per sample, \ + seq_profile {}, subsampling {}/{}, mono_chrome {}; ffmpeg -pix_fmt {pix_fmt}", + seq.seq_profile, cfg.subsampling_x, cfg.subsampling_y, cfg.mono_chrome, + ); + let frames = match ec_av1::stream::decode_stream(&data) { Ok(frames) => frames, Err(e) => { @@ -30,24 +159,51 @@ fn main() { } }; for (i, f) in frames.iter().enumerate() { - let mut buf = Vec::with_capacity((f.y.len() + f.u.len() + f.v.len()) * 2); - for plane in [&f.y, &f.u, &f.v] { - for &s in plane.iter() { - buf.extend_from_slice(&s.to_le_bytes()); + let planes: &[&Vec] = if cfg.mono_chrome { + &[&f.y] + } else { + &[&f.y, &f.u, &f.v] + }; + // The OTHER half of the depth contract: samples that do not fit the + // container we are about to write. A `s as u8` on a 10-bit plane (or a + // u16 on a depth we packed narrow) is exactly the bit loss this tool + // exists to rule out, so it is an error, not a truncation. + if let Some((plane_name, sample)) = [("Y", &f.y), ("U", &f.u), ("V", &f.v)] + .into_iter() + .take(if cfg.mono_chrome { 1 } else { 3 }) + .find_map(|(name, plane)| plane.iter().max().map(|&s| (name, s))) + { + if u32::from(sample) > max { + eprintln!( + "dump_yuv: {path}: frame {i} plane {plane_name} carries sample {sample} above \ + the {bit_depth}-bit maximum {max} -- the decoded output does not match the \ + sequence header it was decoded under, and packing it would silently drop the \ + high bits. Nothing was written." + ); + std::process::exit(1); + } + } + let samples: usize = planes.iter().map(|p| p.len()).sum(); + let mut buf = Vec::with_capacity(samples * bytes_per_sample); + for plane in planes { + if bytes_per_sample == 1 { + buf.extend(plane.iter().map(|&s| s as u8)); + } else { + for &s in plane.iter() { + buf.extend_from_slice(&s.to_le_bytes()); + } } } - // `i` indexes `decode_stream`'s output, which is DISPLAY order and - // SHOWN frames only -- hidden alt-refs are never emitted. Every other - // `.f{N}` in this crate (EC_AV1_FINAL_DUMP, EC_AV1_DECODE_ORDER_DUMP, - // EC_AV1_PREFILT_DUMP) uses a DECODE index, so this file does NOT line - // up with an aomdec dump past frame 0 on a stream with altref. Compare - // against ffmpeg rawvideo, or against aomdec via - // `decode_all_frames_vs_oracle`. let name = format!("{out}.f{i}.yuv"); if let Err(e) = std::fs::write(&name, &buf) { eprintln!("{name}: {e}"); std::process::exit(2); } - println!("frame {i}: {}x{} -> {name}", f.width, f.height); + println!( + "frame {i}: {}x{} -> {name} ({samples} samples, {} bytes, {pix_fmt})", + f.width, + f.height, + buf.len(), + ); } } diff --git a/lanes/av1dumpyuv.report.md b/lanes/av1dumpyuv.report.md new file mode 100644 index 00000000..19e9e891 --- /dev/null +++ b/lanes/av1dumpyuv.report.md @@ -0,0 +1,183 @@ +# lane-av1dumpyuv — the depth-packing class outside the test helpers + +Branch `lane-av1dumpyuv`, branched from `afa13bcf` ("Merge lane-whtshape"). +Worktree `~/.cache/wt/av1dumpyuv`. Examples/tools/scripts only: no decoder +logic, no gate touched. The primary checkout was never edited +(`git status --porcelain` there is empty). + +## 1. The class + +`aomdec --rawvideo` and `ffmpeg -f rawvideo` pack **8 bits per sample for an +8-bit stream** and **16 bits per sample (`*p10le` / `*p12le`) for a +high-bit-depth one** — they never pack to the stream's own bit depth. A site +that reads decoded `u16` planes and writes them `as u8`, or writes them `u16` +unconditionally, therefore produces a file of the wrong size, and the next +person's `cmp` against the oracle fails on LENGTH and reads like a decoder +bug. The prior audit (lanes/av1cmpaudit.report.md) fixed the test helper +`assert_rawvideo_matches`'s sibling `EC_AV1_FINAL_DUMP` +(`crates/ec-av1/src/stream.rs:2137-2152`, depth-correct since lane-hidden r1) +and named exactly one unfixed non-test site: `examples/dump_yuv.rs`. + +## 2. Sweep of the non-test surfaces + +Rows verified by reading each file. "Assumes" = what the code takes the +bits-per-sample to be. + +| site | assumes about depth | derived from | failure mode on the wrong depth | +|---|---|---|---| +| `crates/ec-av1/examples/dump_yuv.rs:33` (pre-fix) | always 2 bytes/sample (u16 LE) | **nothing** | silent 2x file on an 8-bit stream; docstring named `yuv420p10le` as the companion, so a reader hands it 8-bit input and diffs the size | +| `crates/ec-av1/examples/dump_yuv.rs` (**fixed**) | sequence header `color_config.bit_depth` | the stream's own parsed header; `--depth` is an ASSERTED argument | hard exit 1 naming both depths, no file | +| `crates/ec-av1/examples/decode_probe.rs:434-462` | `EC_PROBE_OUT16` = 2 B/sample, `EC_PROBE_OUT`/argv[2] = 1 B/sample | two SEPARATE, explicitly named output targets, each a fixed choice by the caller | none for a single file: the 16-bit target is a full 16-bit container (same as `-pix_fmt yuv420p10le` on an 8-bit stream), the 8-bit target narrows. Both are written, so a wrong choice is visible as two files of different sizes, not one mislabelled file. **not fixed** | +| `crates/ec-vp8/examples/dump_frame.rs:28-45` | 1 byte/sample | VP8 has no high-bit-depth profile (its 8-bit 4:2:0 is the format) | none possible. **not flagged** | +| `crates/ec-av1/examples/{alloc_probe,enc_probe,syntax_census}.rs` | — | no plane is read or serialised | none. **not flagged** | +| `crates/ec-h264/examples/bench_decode.rs`, `bench_encode.rs`, `crates/ec-aac/examples/*`, `crates/ec-ac3/examples/ac3dec.rs` | — | audio `f32`/metric only; no video planes | none. **not flagged** | +| `scripts/instrument-aom-oracle.sh:130-145` (rung PREFILT), `:333-350` (POSTDEBLOCK), `:384-398` (PREFILT_WIDE), `:880-896` (POSTCDEF) | 1 byte/sample, no `YV12_FLAG_HIGHBITDEPTH` check | nothing | on a 10/12-bit stream: a **half-length** file (u8 rows of a u16 plane) that can still byte-match a decoder-side `as u8` narrowing. Rung 12 (`FINAL`, `:684-705`) IS depth-correct and is what `EC_AV1_FINAL_DUMP` pairs with. **NOT FIXED** — these are oracle C rungs whose decoder-side counterparts (`EC_AV1_PREFILT_DUMP`, `EC_AV1_DECODE_ORDER_DUMP`, and the `as u8` debug dumps at `stream.rs:2123-2126`) narrow identically on purpose; changing one side alone would break the byte-pairing those rungs exist for, and both sides are decoder/oracle logic, out of this lane's scope. The script's own comment at `:659-660` already calls them the "u8-narrowing debug dumps". | +| `scripts/lr-sgr-pin-harness.c:33-36` (pre-fix) | 1 byte/sample of `/tmp/lr_full.bin`; `bit_depth=8, highbd=0` hardcoded at `:47`, `:54`, `:75` | nothing (the capture is a bare `std::fs::write` from a since-reverted `EC_LR_DUMP` in `apply_sgrproj_stripe`, lanes/lr.report.md:352-354) | a 10-bit re-capture is exactly 2x the bytes; the harness read its first half as plane data and printed plausible A/B taps for the wrong pixels | +| `scripts/lr-sgr-pin-harness.c` (**fixed**) | still reads 8-bit, but the file length is now an ASSERTION | file size, checked against `bw*bh` | 2x capture → exit 1 naming the byte counts, the assumed depth, and the uint16 port; truncated → exit 1 | +| `scripts/raw_to_y4m.py:9` (pre-fix) | `w*h*3//2` = 8-bit 4:2:0, unconditionally; header hardcoded `C420jpeg` | nothing | a 10-bit stream was cut at half frame length, frame N+1's chroma read as frame N's tail, trailing partial frame **dropped silently** — and vpxenc encodes the result without complaint | +| `scripts/raw_to_y4m.py` (**fixed**) | required `DEPTH` argument, asserted against the stdin length | explicit asserted argument (no parser exists for a headerless raw stream) | non-integer frame multiple → exit 1 naming both implied frame sizes; a missing/!8/10/12 depth → usage error | +| `scripts/superres-pin-harness.c:14-17,50,80,89-142` | — | coverage gap, not depth: only the `uint8` `av1_convolve_horiz_rs_c` arm is called and the input rows were transcribed from an 8-bit fixture | a 10-bit superres pin would be silently uncovered. Different class; **not fixed** | +| `tools/oracle/src/main.rs:352-357` (`sample`), `:383-390`, `:414`, `:424-425`, `:479` | bytes-per-sample from the `--pix-fmt` string (or ffprobe of the reference CONTAINER, `:383-388`), never from a parsed header | explicit CLI flag / container probe | a wrong `--pix-fmt` yields `fa != fb`, and `len_ok = fa == fb` feeds the verdict at `:479` → **loud FAIL**, not a silent compare. Acceptable shape (an argument that is checked). **not fixed** | +| `tools/ec-bench/src/main.rs:253`, `:367`, `:557` | 1 byte/sample `frame_len`; `:564-571` widens those 8-bit samples into `Av1Picture`'s `u16` planes | the same forced `-pix_fmt yuv420p` on the extracting ffmpeg (`:242-243`) | self-consistent: the frame arithmetic and the file it slices come from one explicit ffmpeg argument. Mild real hole: `Av1Config` (`:536-544`) has no depth field, so the encoder's own output depth is whatever it defaults to. **not fixed** (bench table, no oracle compare) | +| `tools/ec-bench/src/main.rs:404-410`, `:423`, `:452`, `:485` | 10-bit for the `ec-hw` row | a comment about the local VA driver's stored format, plus a matching `-pix_fmt yuv420p10le` at `:485` | arithmetic agrees with the forced format. **not fixed** | +| `shims/**` | — | 16 Cargo path-shim crates (`Cargo.toml` + thin `lib.rs` re-exports), no video or raw-byte code | none. **out of scope** | +| `scripts/{build-aom-oracle,build-aom-affine-oracle,gen-bitstream-fixtures,gen_vp8_fixtures,gen-still-fixtures,pgs-white-level,scan-real-library,fetch-vectors,link-fixtures}.sh`, `scripts/av1-timeline-report.py` | force an explicit `-pix_fmt` (or read no planes at all); sizes that exist (`gen_vp8_fixtures.sh:60`, `pgs-white-level.sh:27`) are computed from that same argument | CLI flag | none. **not flagged** | + +Sites fixed: 3 (`examples/dump_yuv.rs`, `scripts/raw_to_y4m.py`, +`scripts/lr-sgr-pin-harness.c`). Sites examined and deliberately NOT fixed: +7 (`decode_probe.rs`, `tools/oracle/src/main.rs`, `tools/ec-bench` x2, +`instrument-aom-oracle.sh` rungs 1/6/7/15, `superres-pin-harness.c`), each with +the reason above. + +## 3. `examples/dump_yuv.rs` — what changed + +- The depth comes from the stream's **own parsed sequence header** + (`ec_av1_syntax::Av1Parser` walking OBU by OBU until a sequence header + appears, then `seq.color_config.bit_depth`). It is never taken from the file + name, the extension, or a reference tool's `-pix_fmt`. +- 8 bit → one byte per sample; 10/12 → little-endian `u16` (the container + both oracles use). Monochrome streams write the luma plane only. +- `--depth N` is an **assertion, not a switch**: the packing always follows the + parsed header, and a contradiction exits 1 naming both depths, both + bytes-per-sample values, and the size mismatch the `cmp` would have shown. + Two spellings accepted (`--depth 8`, `--depth=8`); given twice → usage error. +- A stream with no parseable sequence header → hard error instead of a guess. +- A sample that does not fit the container about to be written (an 8-bit + header with a sample above 255) → hard error. That is the mirror of the + original bug and the reason `as u8` may never be applied silently here. +- The docstring no longer says `yuv420p10le`; it states the both-depths + contract and the `--depth` assertion. +- Measured while doing this: the crate's own 8-bit fixture + `av1_192x128_8bit_intra64_in_inter.obu` parses `subsampling_x/y = 1/1`, + which is **4:2:0** (spec 5.5.3) — 36864 samples for 192x128 = W*H*3/2. The + first pix_fmt table I wrote had 1/1 → 4:4:0 and the measurement caught it; + the shipped table is 0/0→444, 0/1→440, 1/0→422, 1/1→420. + +## 4. Proof + +Committed crate fixtures only, worktree at `afa13bcf`, +`CARGO_TARGET_DIR=$HOME/.cache/cargo-target`. + +### 4.1 GREEN — 8-bit stream, committed fixture + +``` +$ dump_yuv crates/ec-av1/fixtures/av1_192x128_8bit_intra64_in_inter.obu /tmp/dy/eight +sequence header: bit_depth 8 -> 1 byte(s) per sample, seq_profile 0, subsampling 1/1, mono_chrome false; ffmpeg -pix_fmt yuv420p +frame 0: 192x128 -> /tmp/dy/eight.f0.yuv (36864 samples, 36864 bytes, yuv420p) +... +eight.f0.yuv 36864 bytes <- W*H*3/2 = 192*128*3/2 = 36864 (Y 24576 + U 6144 + V 6144) +``` +Byte-exact against the oracle at its own depth: +`aomdec --codec=av1 --rawvideo -o ref8.raw ` → 221184 bytes for 6 +frames; our 6 concatenated frames → 221184 bytes; `cmp` → **IDENTICAL**. + +### 4.2 GREEN — high-bit-depth stream, committed fixture + +``` +$ dump_yuv crates/ec-av1/fixtures/av112bit-key.obu /tmp/dy/twelve +sequence header: bit_depth 12 -> 2 byte(s) per sample, seq_profile 2, subsampling 1/1, mono_chrome false; ffmpeg -pix_fmt yuv420p12le +frame 0: 160x128 -> /tmp/dy/twelve.f0.yuv (30720 samples, 61440 bytes, yuv420p12le) +twelve.f0.yuv 61440 bytes <- W*H*3 = 160*128*3 = 61440 (30720 samples x 2 bytes) +cmp twelve.f0.yuv (ffmpeg -f obu -pix_fmt yuv420p12le -f rawvideo) -> IDENTICAL +``` + +### 4.3 The wrong depth fails loudly and writes nothing + +``` +$ dump_yuv .../av1_192x128_8bit_intra64_in_inter.obu /tmp/dy/wrong --depth 10 +dump_yuv: ...: --depth 10 contradicts the stream's own sequence header, which carries +bit_depth 8 (seq_profile 0, subsampling 1/1, mono_chrome false). Writing 10-bit would emit +2 bytes per sample against the oracle's aomdec --rawvideo / ffmpeg -pix_fmt yuv420p (1 bytes +per sample, W*H*3/2 for 4:2:0), so every `cmp` would fail on size alone and read like a decoder +defect. Nothing was written. +exit=1 +ls: cannot access '/tmp/dy/wrong.f0.yuv': No such file or directory + +$ dump_yuv .../av112bit-key.obu /tmp/dy/wrong2 --depth=8 -> same message, exit=1, no file +$ dump_yuv .../av1_192x128_... --depth=8 -> runs, 36864 bytes (assertion holds) +$ dump_yuv .../av112bit-key.obu --depth 12 -> runs, 61440 bytes +``` + +### 4.4 RED-BEFORE — the depth derivation reverted + +`git show HEAD:crates/ec-av1/examples/dump_yuv.rs` restored, rebuilt, same +8-bit fixture, same command: + +``` +--- RED (pre-fix, u16 unconditional) on the 8-bit fixture --- +ours 73728 bytes <- 2 x 36864 +aomdec --rawvideo 221184 bytes <- 6 x 36864 +cmp exit=1 (mismatch on size alone) +``` +73728 = 2 x (W*H*3/2): exactly the silent 2x file the lane was chartered to +close. Fixed tree restored and rebuilt afterwards. + +### 4.5 `scripts/raw_to_y4m.py` + +``` +$ ... | raw_to_y4m.py 64 64 25 g8.y4m 8 -> YUV4MPEG2 ... C420jpeg, 18491 bytes (3 frames) +$ ... | raw_to_y4m.py 64 64 25 g10.y4m 10 -> YUV4MPEG2 ... C420p10, 36922 bytes (3 frames) +$ 12289 bytes | raw_to_y4m.py ... 8 +raw_to_y4m.py: stdin is 12289 bytes, not a whole number of 64x64 4:2:0 frames at 8-bit +(1 bytes per sample, 6144 bytes each): 1 trailing bytes. At the other depth a frame would be +12288 bytes and each frame would carry half a frame of the next one's planes. Refusing to +write a misframed y4m. exit=1, no file +$ DEPTH 7 -> "DEPTH 7 is not 8, 10 or 12 ..." exit=1 +$ DEPTH omitted (the old 4-arg invocation) -> usage error, exit=1 +``` +Documented limit, stated in the script's own docstring: raw planar video +carries no depth, so a 10-bit stream of N frames is exactly 2N 8-bit frames +and no length test can separate them. That case is caught by the caller +asserting the right DEPTH — which is why the argument is required, not +defaulted. + +### 4.6 `scripts/lr-sgr-pin-harness.c` + +Linked against `~/.cache/aom-oracle/build/libaom.a`, `/tmp/lr_full.bin` +faked at three sizes: + +``` +1020 bytes (correct) -> ret=0 / out[1][6] = 151 / dgd[1][6] = 151 (real libaom taps printed) +2040 bytes (2x, HBD) -> "/tmp/lr_full.bin is 2040 bytes, this harness reads it as 8-bit + (1020 bytes: 102x10 at 1 byte per sample). That is exactly a 2x-size + high-bit-depth capture: re-capture it as 8-bit, or port the harness to + the uint16 arm (bit_depth=10, highbd=1) before trusting a single + printed tap." exit=1 + 900 bytes (short) -> "... 900 bytes ... Recapture it, or fix bw/bh to the plane the + capture came from." exit=1 +``` + +## 5. Not done, deliberately + +- `instrument-aom-oracle.sh` rungs 1/6/7/15 (section 2): changing one side of + a byte-paired rung breaks the pairing, and both sides are decoder/oracle C. + Rung 12 is already depth-correct; that is the rung the depth-sensitive + compares use. +- `tools/oracle/src/main.rs` and `tools/ec-bench/src/main.rs`: already the + "explicit argument that is checked" shape (a length/frame-count FAIL), with + no header parser reachable from those binaries to derive a better answer + from (`oracle` drives ffmpeg through std pipes and is deliberately + dependency-free). +- `decode_probe.rs`: its two output targets are separate, explicitly named + files; see section 2. +- No gate, counter, decoder path or fixture was touched. diff --git a/lanes/merge-wave-4.report.md b/lanes/merge-wave-4.report.md new file mode 100644 index 00000000..559b8f4d --- /dev/null +++ b/lanes/merge-wave-4.report.md @@ -0,0 +1,189 @@ +# Merge wave 4 — integration report + +Base `aa0ac8c2` (wave 2, "clean-checkout census"). Four branches, four +`--no-ff` merge commits, **zero conflicts** on any of them. No push. + +## Per-branch table + +| # | Branch | Tip merged | Merge base | True delta (base → tip) | Conflicts | +|---|--------|-----------|-----------|-------------------------|-----------| +| 1 | `lane-av1recipehunt` | `1acf1818` | `aa0ac8c2` | 9 files, +1164/-545 | none | +| 2 | `lane-av1rect8x16` | `ee56661f` | `afa13bcf` | 2 files, +493/-0 | none | +| 3 | `lane-h264reallib` | `25c996b2` | `a21f3680` | 7 files, +562/-96 | none (one auto-merged hunk, `crates/ec-h264/tests/conformance.rs`) | +| 4 | `lane-av1dumpyuv` | `60a7788a` | `afa13bcf` | 4 files, +437/-26 | none | + +**True delta is measured against each branch's own merge base, not against an +older tip.** `git diff a21f3680 1acf1818` for branch 1 shows 52 files / +10975 +of rebase noise; `aa0ac8c2 → 1acf1818` is the real 9-file delta. Branch 3's +merge base is also `a21f3680` (it forked before wave 2), which is why its +delta is quoted against that commit. + +### 1. `lane-av1recipehunt` @ `1acf1818` — merged first + +Landed first by design: it is the only branch touching `src/stream.rs` and +`src/encode.rs`, and it introduces the three fixture pins the later branches' +reports cite. + +- **Three TRACKED fixture pins** (verified with `git ls-tree` at the merged + HEAD, and `stat` on disk): + + | Fixture | Bytes | Blob sha | + |---------|-------|----------| + | `crates/ec-av1/fixtures/rect64_dq_drift.obu` | 8384 | `29f6e5dabcb1630baf593ea977952550a5a2bb49` | + | `crates/ec-av1/fixtures/intra14_256x192_8bit.obu` | 35179 | `1d345e07f94c2a61b7849d88970b4ab0408f05e1` | + | `crates/ec-av1/fixtures/intra14_256x192_10bit.obu` | 34727 | `b16114a42e4ad49c59a1e9d9839556c4caf2ddd9` | + + All three sizes match the reviewer's independent recomputation. +- `src/stream.rs` +952/-545 (the rebase-noise bulk of this branch), plus + `src/encode.rs` +117, `src/tile.rs` +68, and the two example probes. +- **Gates: 3 un-ignored, 1 deleted** (see "Gate count" below). +- Dedupe result: **no duplicate blobs** in `crates/ec-av1/fixtures/` + (`git ls-tree -r` grouped by blob sha — no sha appears under two names). + Nothing to dedupe; no dedupe needed to be mentioned in a message. + +### 2. `lane-av1rect8x16` @ `ee56661f` + +Pure test-only `refusal_inventory.rs` +246/-0 plus its report. Zero merge +surface against wave 3 and against branch 1. + +**Fixed in the merge commit:** the inventory comment at +`crates/ec-av1/src/refusal_inventory.rs:556` read *"All nine call sites"*, +which contradicts the test's own `assert_eq!(sites, 8)` at line 1642 and the +lane report. The nine is a count of **textual `decode_block_rect(` matches in +`decode.rs`**, which is 1 declaration + 8 call sites — the test skips the +declaration explicitly (`if src[..i].ends_with("fn ") { continue; }`). The +comment now states that arithmetic. One line of prose, no code change. + +### 3. `lane-h264reallib` @ `25c996b2` + +Real-media-library test sites reshaped to `#[ignore]` with fact-based reasons, +so a site that cannot run because ffmpeg/ffprobe or a media file is absent no +longer reads as "passed". Four follow-ups in the same tip: + +- `ec-probe`: a silent skip replaced by a **named** SKIP that states what was + missing rather than returning quietly; +- `ec-aac`: two `env::var("HOME").unwrap()` → `unwrap_or_default()`; +- `ec-h264`: one hardcoded absolute manifest path → `CARGO_MANIFEST_DIR`-relative. + +> **Stale line numbers — deliberately not amended.** The branch's commit +> message cites `file:line` locations that the **same commit's** rustfmt pass +> renumbered. The citations were accurate when written and are stale at this +> tip. Recorded here and in the merge message; the message text itself is +> left alone rather than "fixed", because editing it would desynchronise the +> record of what the lane actually did. + +### 4. `lane-av1dumpyuv` @ `60a7788a` + +Three non-test surfaces now carry the sample depth as data: + +- `crates/ec-av1/examples/dump_yuv.rs` — **derives** depth from the stream's + own sequence header (spec 5.5.2 `color_config.bit_depth`) before a byte is + written. Never taken from the file name, the output extension, or a + convention. `--depth N` is accepted only as a claim, and a mismatch against + the parsed header is a hard error naming both depths. +- `scripts/raw_to_y4m.py` — **asserts** depth as an explicit positional + argument (`W H FPS out.y4m DEPTH`, DEPTH = bytes per sample) and validates + the byte count is a whole number of frames at the claimed depth. +- `scripts/lr-sgr-pin-harness.c` — **takes** `bit_depth`/`highbd` as + parameters and names the failure mode when a high-bit-depth capture is fed + to the 8-bit arm. + +> **Disclosed limit, not a silent hole.** A 10-bit stream of N frames is +> *exactly* the same byte count as 2N 8-bit frames, so **length alone can +> never distinguish them** — no length test can. That is stated in the +> `raw_to_y4m.py` module docstring, and is why the depth is an explicit +> argument rather than something inferred from the byte count. + +## Gate count: 742 → 742 (net zero), cause accounted + +`cargo test -p ec-av1 --lib -- --list`: + +``` +742 tests, 0 benchmarks +``` + +Wave 2's baseline was the same measure: wave 2's own report line 155 reads +`25 passed; 0 failed; 0 ignored; 0 measured; 717 filtered out` = 742. After +wave 4 the same filter reads `26 passed; … 716 filtered out` = 742. + +**Net zero is arithmetic, not luck.** Wave 4 moved the lib test count in +three directions at once: + +| Change | Count | Why | +|--------|-------|-----| +| `a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact` **deleted** | −1 | `DRL_CLAMP_HITS` is provably unreachable (its coverage claim moved to `encode.rs:15689`, the pricer's own offer-set enumeration) | +| `every_chroma_unit_decode_block_rect_can_present_has_a_coefficient_table` **added** (branch 2) | +1 | new `refusal_inventory` enumeration + witness gate | +| 3 gates **un-ignored** | ±0 | `#[ignore]`d tests still appear in `--list`; un-ignoring changes runnability, not the roster | + +### The deletion and its replacement + +Deleted in `4eab9e40`/`83a0066e`. The gate asserted `drl_clamp_hits() > 0` on +a real 1280x768 sb128 clip; the counter is unreachable, so the gate was a +guaranteed red once run. Its coverage claim is now carried by the pricer's +offer-set enumeration at `crates/ec-av1/src/encode.rs:15689`, whose doc +comment names the deleted gate so the lineage is greppable. The four +1280x768 `force_sb128(true)` own-reconstruction gates the reviewer verified +remain in the tree (`src/encode.rs:18653`, `:18755`, `:18852`, `:18941`, and +siblings) and justify the deletion. + +`grep -rn a_128_superblock_clip_whose_drl_index crates/` now returns exactly +one hit — the `encode.rs:15691` doc comment naming it as replaced. No dangling +test reference. + +### The three un-ignored gates, run + +``` +test stream::tests::a_real_aomenc_inter_sequence_with_an_intra_1to4_strip_decodes_pixel_exact ... ok +test stream::tests::a_real_aomenc_inter_sequence_with_an_intra_1to4_strip_decodes_pixel_exact_10bit ... ok +test stream::tests::a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact ... ok +test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 739 filtered out +``` + +All three are green **un-ignored**, not vacuously skipped — the un-ignore is +honest. + +## Verification outputs + +`cargo check -p ec-av1 --all-targets`, run after **each** merge, and re-run +with `src/lib.rs` + `examples/dump_yuv.rs` touched so the cached-green case +could not mask a stale binary: + +``` + Checking ec-av1 v0.1.0 (/home/user/Documents/Code/Rust/edith_codecs/crates/ec-av1) + Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.41s +``` + +Clean — zero errors, zero warnings. + +Branch 3 touches four crates outside `ec-av1`, so the check was widened for +that merge only: + +``` +cargo check -p ec-av1 -p ec-aac -p ec-h264 -p ec-matroska -p ec-probe --all-targets + Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.16s +``` + +`cargo test -p ec-av1 --lib -- gate_coverage refusal_inventory`: + +``` +test result: ok. 26 passed; 0 failed; 0 ignored; 0 measured; 716 filtered out; finished in 0.86s +``` + +Green. The +1 against wave 2's 25 is branch 2's new gate. + +`cargo test -p ec-av1 --lib -- --list | wc -l` → **744** lines, of which 742 +are `: test` entries; the summary line itself prints `742 tests, 0 benchmarks`. +(744 = 742 test names + the `running 0 tests` and summary lines.) + +Smoke: `python3 scripts/raw_to_y4m.py` with no args prints the usage line +including the now-required `DEPTH` argument, and the module imports cleanly. + +## Notes + +- **NO PUSH.** The four merge commits are local on `main`. +- Wave 3 was **not** merged and `src/refusal_inventory.rs` was not edited + beyond the one-line comment fix in merge 2. +- The pre-commit hook's whole-staged-tree `format-staged.py` produced **no** + churn in any of the four merges: `git status --porcelain` was empty after + each commit, and the recipehunt merge's tree is byte-identical to `1acf1818`. + The accepted-churn escape hatch was not needed. diff --git a/scripts/lr-sgr-pin-harness.c b/scripts/lr-sgr-pin-harness.c index 6e53aa1b..5ac7c402 100644 --- a/scripts/lr-sgr-pin-harness.c +++ b/scripts/lr-sgr-pin-harness.c @@ -30,10 +30,34 @@ int main(void) { // sized for that max, so replicate the chunking (target col=6 is in // the first 64-wide chunk). const int w = 64, h = 4; - uint8_t *buf = malloc(bw * bh); + // The depth of `/tmp/lr_full.bin` is NOT in the file: the capture is a raw + // plane dump written by an env-gated `std::fs::write` inside + // `apply_sgrproj_stripe`, and whoever re-captures it from a 10/12-bit pin + // gets 2 bytes per sample, i.e. a file TWICE this size whose first half + // still looks like plausible plane data. Reading it at 1 byte per sample + // would then print self-guided-restoration A/B taps for the wrong pixels + // and nothing would fail -- so the size is the assertion: a 2x capture + // must not pass as an 8-bit one. + const size_t expect = (size_t)bw * bh; + uint8_t *buf = malloc(expect); FILE *f = fopen("/tmp/lr_full.bin", "rb"); if (!f) { perror("open"); return 1; } - if (fread(buf, 1, bw * bh, f) != (size_t)(bw * bh)) { fprintf(stderr, "short read\n"); return 1; } + fseek(f, 0, SEEK_END); + const long size = ftell(f); + fseek(f, 0, SEEK_SET); + if (size != (long)expect) { + fprintf(stderr, + "/tmp/lr_full.bin is %ld bytes, this harness reads it as %d-bit (%zu bytes: " + "%dx%d at 1 byte per sample). %s\n", + size, 8, expect, bw, bh, + size == 2 * (long)expect + ? "That is exactly a 2x-size high-bit-depth capture: re-capture it as 8-bit, " + "or port the harness to the uint16 arm (bit_depth=10, highbd=1) before " + "trusting a single printed tap." + : "Recapture it, or fix bw/bh to the plane the capture came from."); + return 1; + } + if (fread(buf, 1, expect, f) != expect) { fprintf(stderr, "short read\n"); return 1; } fclose(f); const uint8_t *dgd8 = buf + 3 * bw + 3; // logical (0,0) diff --git a/scripts/raw_to_y4m.py b/scripts/raw_to_y4m.py index 296ca2a9..82fb1c24 100755 --- a/scripts/raw_to_y4m.py +++ b/scripts/raw_to_y4m.py @@ -1,15 +1,63 @@ #!/usr/bin/env python3 """Wrap raw planar yuv420p frames into a minimal y4m (for vpxenc). - ffmpeg ... -f rawvideo - | raw_to_y4m.py W H FPS out.y4m + ffmpeg ... -f rawvideo - | raw_to_y4m.py W H FPS out.y4m DEPTH + +DEPTH (8, 10 or 12) is REQUIRED and is the number of BYTES per sample in the +raw stream on stdin, not the stream's bit depth: ffmpeg's rawvideo muxer +never packs to the bit depth, it uses 1 byte for `yuv420p` and 2 bytes for +`yuv420p10le` / `yuv420p12le`. This script has no parser and no way to learn +it, so the depth is an ASSERTED argument: it is checked against the stdin +length, and a mismatch is a hard error naming the depth, the byte count it +implied, and the misframed y4m it would have produced. The old version +computed `w*h*3//2` unconditionally, so a 10-bit stream (2 bytes per sample) +was cut into frames at half length, the chroma planes of frame N+1 were read +as the tail of frame N, and the last partial frame was dropped silently -- +a y4m that vpxenc accepts and encodes, with no error anywhere. + +The y4m header's `C` tag follows the same argument, so the wrapped stream +carries the depth it actually has. + +LIMIT, stated because it cannot be fixed here: raw planar video carries NO +depth of its own, so the length check below can only catch a stream whose +byte count is not a whole number of frames at the claimed depth. A 10-bit +stream of N frames is exactly 2N 8-bit frames, and no length test can tell +those apart -- that case is caught only by the caller asserting the right +DEPTH, which is why DEPTH is required and not defaulted. """ + import sys -w, h, fps, out = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] -frame = int(w) * int(h) * 3 // 2 + +if len(sys.argv) != 6: + sys.exit( + "usage: raw_to_y4m.py W H FPS out.y4m DEPTH " + "(DEPTH = 8|10|12, the BYTES per sample on stdin)" + ) +w, h, fps, out, depth = sys.argv[1:6] +try: + depth = int(depth) +except ValueError: + sys.exit(f"raw_to_y4m.py: DEPTH {depth!r} is not a number (8, 10 or 12)") +if depth not in (8, 10, 12): + sys.exit( + f"raw_to_y4m.py: DEPTH {depth} is not 8, 10 or 12 -- the frame size below would be " + "wrong and every frame after the first would be misframed" + ) +bpp = 1 if depth == 8 else 2 +frame = int(w) * int(h) * 3 // 2 * bpp raw = sys.stdin.buffer.read() +if len(raw) % frame: + sys.exit( + f"raw_to_y4m.py: stdin is {len(raw)} bytes, not a whole number of " + f"{int(w)}x{int(h)} 4:2:0 frames at {depth}-bit ({bpp} bytes per sample, " + f"{frame} bytes each): {len(raw) % frame} trailing bytes. At the other depth a " + f"frame would be {int(w) * int(h) * 3 // 2 * (3 - bpp)} bytes and each frame would " + "carry half a frame of the next one's planes. Refusing to write a misframed y4m." + ) +ctag = {8: "C420jpeg", 10: "C420p10", 12: "C420p12"}[depth] with open(out, "wb") as f: - f.write(f"YUV4MPEG2 W{w} H{h} F{fps}:1 Ip A1:1 C420jpeg\n".encode()) + f.write(f"YUV4MPEG2 W{w} H{h} F{fps}:1 Ip A1:1 {ctag}\n".encode()) for i in range(len(raw) // frame): f.write(b"FRAME\n") f.write(raw[i * frame : (i + 1) * frame])