diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 2add875e..646a201f 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -30,6 +30,30 @@ use crate::decode::{ }; use crate::encode::Picture; +/// lane-hidden r1: where `EC_AV1_FINAL_DUMP`'s per-frame dump goes for the +/// current thread, overriding the environment variable. Every ffmpeg/aomdec +/// pixel gate in this repo compares SHOWN frames only (class +/// gate-blind-to-hidden-frames), so the hidden alt-ref frames a real aomenc +/// stream carries were never compared at all; the gate that does compare +/// them needs a dump path that cannot race a sibling test's decode on +/// another thread, which a process-global env var cannot give. +thread_local! { + static FINAL_DUMP_PREFIX: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; +} + +/// Sets (or with `None` clears) this thread's `EC_AV1_FINAL_DUMP` prefix. +#[allow(dead_code)] +pub(crate) fn set_final_dump_prefix(prefix: Option) { + FINAL_DUMP_PREFIX.with(|c| *c.borrow_mut() = prefix); +} + +fn final_dump_prefix() -> Option { + FINAL_DUMP_PREFIX + .with(|c| c.borrow().clone()) + .or_else(|| std::env::var("EC_AV1_FINAL_DUMP").ok()) +} + /// Decode every frame in a raw AV1 OBU stream, in coding order. /// /// A key frame becomes the reference for the inter frames that follow it, @@ -46,6 +70,7 @@ use crate::encode::Picture; /// crate's tile decoders do not reconstruct (see their own docs), or when an /// inter frame appears before any key frame has supplied a reference. pub fn decode_stream(data: &[u8]) -> Result> { + let final_dump = final_dump_prefix(); let mut parser = Av1Parser::new(); let mut pictures = Vec::new(); let mut pictures_decoded: usize = 0; @@ -735,6 +760,30 @@ pub fn decode_stream(data: &[u8]) -> Result> { let _ = f.write_all(&narrow(&picture.v)); } } + // lane-hidden r1: the frame exactly as it is about to be stored into + // the reference slots -- after deblock/CDEF/LR/superres, in DECODE + // order, hidden (`show_frame == 0`) alt-ref frames included, and + // bit-depth correct (8-bit as u8, 10/12-bit as u16 LE) unlike the + // u8-narrowing diagnostic dumps above. Matches the instrumented + // aomdec's own `EC_AV1_FINAL_DUMP` rung byte for byte + // (scripts/instrument-aom-oracle.sh rung 12), which is what makes a + // hidden frame's pixels comparable at all. + if let Some(prefix) = &final_dump { + use std::io::Write; + if let Ok(mut f) = std::fs::File::create(format!("{prefix}.f{pictures_decoded}")) { + let mut buf = Vec::new(); + for plane in [&picture.y, &picture.u, &picture.v] { + if bit_depth == 8 { + buf.extend(plane.iter().map(|&s| s as u8)); + } else { + for &s in plane { + buf.extend_from_slice(&s.to_le_bytes()); + } + } + } + let _ = f.write_all(&buf); + } + } pictures_decoded += 1; let decoded_seg_map = decode::take_segment_ids(); for i in 0..NUM_REF_FRAMES { @@ -1636,6 +1685,237 @@ mod tests { present } + /// The instrumented `aomdec` beside the `aomenc` oracle + /// (`scripts/build-aom-oracle.sh` + `scripts/instrument-aom-oracle.sh`). + fn aomdec_path() -> std::path::PathBuf { + if let Some(p) = std::env::var_os("EC_AV1_AOMDEC") { + return std::path::PathBuf::from(p); + } + aomenc_path().with_file_name("aomdec") + } + + /// Decodes `stream` with both this decoder and the instrumented oracle + /// `aomdec`, and compares EVERY decoded frame in DECODE order -- + /// including the hidden (`show_frame == 0`) alt-ref frames no other gate + /// in this repo can see, because `decode_stream` only pushes shown + /// frames and `ffmpeg -f obu ... rawvideo` only emits shown frames + /// (class gate-blind-to-hidden-frames: a hidden frame's defect surfaces + /// only as drift on some later shown frame, if at all). + /// + /// Both sides write the final, post-deblock/CDEF/LR/superres frame as it + /// is stored into the reference buffer (`EC_AV1_FINAL_DUMP`, ours in + /// `decode_stream`, the oracle's in rung 12 of + /// `scripts/instrument-aom-oracle.sh`), 8-bit as u8 / high bitdepth as + /// u16 LE. Returns `(frames_decoded, hidden_frames)`. + fn decode_all_frames_vs_oracle(stream: &[u8], name: &str) -> (usize, usize) { + let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + let obu = dir.join("in.obu"); + std::fs::write(&obu, stream).expect("writing the stream"); + let aom_prefix = dir.join("aom"); + let out = Command::new(aomdec_path()) + .args(["--codec=av1", "-o"]) + .arg(dir.join("out.y4m")) + .arg(&obu) + .env("EC_AV1_FINAL_DUMP", &aom_prefix) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("aomdec failed to run"); + assert!( + out.status.success(), + "{name}: the oracle aomdec refused the stream: {}", + String::from_utf8_lossy(&out.stderr) + ); + let count_dumps = |prefix: &std::path::Path| -> usize { + let mut n = 0usize; + while std::path::PathBuf::from(format!("{}.f{n}", prefix.display())).is_file() { + n += 1; + } + n + }; + let oracle_frames = count_dumps(&aom_prefix); + assert!( + oracle_frames > 0, + "{name}: the oracle wrote no EC_AV1_FINAL_DUMP frames -- rung 12 of \ + scripts/instrument-aom-oracle.sh is missing from {}", + aomdec_path().display() + ); + let ours_prefix = dir.join("ours"); + set_final_dump_prefix(Some(ours_prefix.display().to_string())); + let decoded = decode_stream(stream); + set_final_dump_prefix(None); + let shown = decoded + .unwrap_or_else(|e| panic!("{name}: this decoder refused the stream: {e}")) + .len(); + let our_frames = count_dumps(&ours_prefix); + assert_eq!( + our_frames, oracle_frames, + "{name}: decoded {our_frames} frames in decode order, the oracle decoded \ + {oracle_frames}" + ); + for i in 0..oracle_frames { + let want = + std::fs::read(format!("{}.f{i}", aom_prefix.display())).expect("oracle dump"); + let got = std::fs::read(format!("{}.f{i}", ours_prefix.display())).expect("our dump"); + assert_eq!( + got.len(), + want.len(), + "{name}: decode-order frame {i} is {} bytes, the oracle's is {}", + got.len(), + want.len() + ); + if let Some(at) = got.iter().zip(&want).position(|(a, b)| a != b) { + let differing = got.iter().zip(&want).filter(|(a, b)| a != b).count(); + panic!( + "{name}: decode-order frame {i} of {oracle_frames} ({shown} shown, {} \ + hidden) differs from the oracle at byte {at} (ours {} vs {}), {differing} \ + bytes differ -- stream pinned at {}", + oracle_frames - shown, + got[at], + want[at], + obu.display() + ); + } + } + let hidden = oracle_frames - shown; + let _ = std::fs::remove_dir_all(&dir); + (oracle_frames, hidden) + } + + /// The repo's first hidden-frame pixel gate. Every other aomenc gate + /// here compares `decode_stream`'s output against `ffmpeg -f obu`, and + /// both sides emit SHOWN frames only -- so an alt-ref frame that is + /// decoded, stored into a reference slot and never displayed was, until + /// this gate, never compared to anything (class + /// gate-blind-to-hidden-frames). His films are aomenc-encoded with the + /// default `--lag-in-frames`, so they are full of exactly these frames. + /// + /// `--auto-alt-ref=1 --lag-in-frames=25` on moving content makes aomenc + /// build alt-refs; `--arnr-maxframes=0` is load-bearing -- with libaom's + /// temporal filter on, this fixture's alt-ref candidates get filtered + /// away and the encoder emits ZERO hidden frames (measured: 0 hidden + /// with the filter on, 3 with it off), which would have made the gate + /// vacuous. The `hidden >= 2` assertion is hard, on both bit depths, so + /// a recipe that stops producing hidden frames fails rather than skips. + #[test] + fn a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact() { + const NAME: &str = "a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + for bit_depth in [8u32, 10u32] { + let (width, height, frames) = (64usize, 64usize, 40usize); + let duration = frames as f64 / 25.0; + let source = format!("testsrc2=size={width}x{height}:duration={duration}:rate=25"); + let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(), + "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let depth_arg = format!("--bit-depth={bit_depth}"); + let input_depth_arg = format!("--input-bit-depth={bit_depth}"); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--kf-max-dist=1000", + "--enable-order-hint=1", + "--auto-alt-ref=1", + "--lag-in-frames=25", + "--arnr-maxframes=0", + &depth_arg, + &input_depth_arg, + // The same tool set every sibling inter gate pins -- the + // open capability gaps (rect/AB partitions, warped/OBMC, + // masked compound, palette, ...) are other lanes' work; + // this gate is about hidden frames, not about them. + "--enable-warped-motion=0", + "--enable-obmc=0", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + "--obu", + "-o", + "-", + "-", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "{NAME}: aomenc refused the {bit_depth}-bit fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let (total, hidden) = + decode_all_frames_vs_oracle(&stream, &format!("altref-hidden-{bit_depth}bit")); + assert!( + hidden >= 2, + "{NAME}: the {bit_depth}-bit recipe produced only {hidden} hidden frame(s) of \ + {total} decoded -- the gate would be vacuous (class \ + gate-blind-to-hidden-frames)" + ); + eprintln!( + "{NAME} {bit_depth}-bit: {total} frames decoded, {hidden} hidden, all \ + pixel-exact vs the oracle in decode order" + ); + } + } + /// A real `aomenc` filter-intra fixture: every other intra mode disabled /// (smooth/paeth/directional/angle-delta) and /// `--max-partition-size=32` (past which `av1_filter_intra_allowed_bsize`'s diff --git a/lanes/hidden-r1.report.md b/lanes/hidden-r1.report.md new file mode 100644 index 00000000..e3bc68bd --- /dev/null +++ b/lanes/hidden-r1.report.md @@ -0,0 +1,72 @@ +# lane-hidden r1 — a direct hidden-frame (alt-ref) pixel oracle + gate + +## Premise, re-measured +Charter premise (ledger `constraint|ec-av1 decode_stream pushes a picture only under +header.show_frame`) confirmed at HEAD dc5553f: `crates/ec-av1/src/stream.rs` pushes into +`pictures` only inside `if header.show_frame`, and every pixel gate compares against +`ffmpeg -f obu ... rawvideo` / `aomdec -o y4m`, both shown-frames-only. So no hidden +(`show_frame == 0`) alt-ref frame's pixels were compared anywhere in the repo. + +## What changed +- `scripts/instrument-aom-oracle.sh` (rung 12, appended): `EC_AV1_FINAL_DUMP=` in the + instrumented `aomdec` → `.f`, one file per DECODED frame (decode order, hidden + frames included), written in `decode_frame` after CDEF + superres + loop restoration and + before the `!pbi->dcb.corrupted` block — i.e. the frame exactly as stored into the reference + buffer. Y then U then V, crop-sized rows (post-superres `y_crop_width`), 8-bit as u8 and + high bitdepth as u16 LE via `CONVERT_TO_SHORTPTR` (bit-depth correct; the other dumps in + this repo narrow u16→u8 and silently truncate 10-bit). +- `crates/ec-av1/src/stream.rs`: matching `EC_AV1_FINAL_DUMP` at the ref-slot store site + (immediately before `pictures_decoded += 1;`, so post-deblock/CDEF/LR/superres, decode + order, hidden frames included), same byte layout, `bit_depth == 8` → u8 else u16 LE. The + prefix comes from a thread-local (`set_final_dump_prefix`) falling back to the env var, so + a gate's dump cannot be polluted by a sibling test decoding on another thread. +- `crates/ec-av1/src/stream.rs` tests: `aomdec_path()`, helper + `decode_all_frames_vs_oracle(stream, name) -> (frames, hidden)` (runs both dumps, asserts + equal frame counts, compares every decode-order frame byte for byte, reports first + differing byte + count and pins the stream on failure), and the gate + `a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact`. + +## Gate +`a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact` — 64x64 testsrc2, 40 frames, +`--auto-alt-ref=1 --lag-in-frames=25 --arnr-maxframes=0 --kf-max-dist=1000` plus the tool set +the sibling inter gates pin; run for 8-bit and 10-bit. Hard `assert!(hidden >= 2)` (no skip), +hard per-frame byte equality incl. hidden frames, `decode_stream` error = failure not skip. + +`--arnr-maxframes=0` is load-bearing and was measured, not assumed: with libaom's temporal +alt-ref filter at its default the same recipe emits **0 hidden frames** (the gate would be +vacuous); with it off, 3. + + cd /home/user/Documents/Code/Rust/edith_codecs-hidden + export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-hidden + EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib \ + a_real_aomenc_altref_sequence_hidden -- --nocapture + +EVIDENCE: /tmp/.../t_arnr.f* + t10.f* (oracle dumps), gate stdout | aomenc --auto-alt-ref=1 --lag-in-frames=25 --arnr-maxframes=0, aomdec EC_AV1_FINAL_DUMP, decode_stream EC_AV1_FINAL_DUMP, byte compare | 8-bit: 43 frames decoded, 3 hidden, all pixel-exact; 10-bit: 43 frames decoded, 3 hidden, all pixel-exact +EVIDENCE: oracle rung proof | `EC_AV1_FINAL_DUMP=$PWD/fin aomdec -o out.y4m alt.obu` on a default-settings aomenc stream | dumps=31 vs shown=30 → the rung emits the hidden frame the y4m output does not; 8-bit f0 = 6144 B = 64x64x1.5, 10-bit f0 = 12288 B = 2 bytes/sample +EVIDENCE: recipe-vacuity measurement | same recipe with/without --arnr-maxframes=0 | hidden 0 → 3 + +## Refusals +None lifted (`refusal_inventory.rs` / `gate_coverage.rs` untouched) — this lane adds an +instrument and a gate, it does not widen decode capability. + +## (d) Which existing gates carry hidden frames +Static scan of the 52 encoder-driven gates in stream.rs: **15 pre-existing gates pass +`--auto-alt-ref=1`** (1 with `--lag-in-frames=0`, so no alt-ref is possible there): +reference_select, compound_references, obmc, obmc_8x8, warped_motion, interintra, +interintra_wedge, free_partitions, ab_partitions, masked_compound, cdef, +an_altref_reference, delta_q_and_delta_lf, gradients_with_cdef (lag=25), and +a_golden_reference (lag=0 → none). Measured proxy for that recipe shape (the reference-select +arg list, 20 frames at lag=16, testsrc2 rather than each gate's own `gradients_source` seed): +**1 hidden frame per stream, decoded by us and compared by nothing**. The 40-frame variant of +the same recipe produced 0 (libaom's temporal filter absorbs the candidates), so the count is +content- and length-dependent — a per-gate sweep with each gate's own fixture is the honest +way to size it. + +- deferred: sweeping `decode_all_frames_vs_oracle` over the 14 alt-ref-capable existing gate + recipes — cheap per gate but 14 recipe transcriptions and 14 encodes; unblocked by an + orchestrator decision (the helper it needs now exists and is one call per gate). +- accepted: the gate's fixture is `testsrc2` (deterministic lavfi source, no seed) rather + than `gradients_source` (whose seed lavfi ignores — memory `seeded-fixture-not-reproducible`). + +## Suite +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib` (scoped, per charter): **273 passed, 0 failed, 22 ignored, 0 filtered**, 1060.84s (branch lane-hidden @ 25b7222). diff --git a/scripts/instrument-aom-oracle.sh b/scripts/instrument-aom-oracle.sh index ebbb3651..2dbc1fee 100755 --- a/scripts/instrument-aom-oracle.sh +++ b/scripts/instrument-aom-oracle.sh @@ -641,3 +641,67 @@ s = s.replace(old4, new4, 1) open(path, "w").write(s) print("decodetxb rung 11 (per-symbol coeff ladder) instrumented") PYC11 + +# --- rung 12: FINAL reconstruction dump (lane-hidden r1) ---------------- +# EC_AV1_FINAL_DUMP= -> .f per DECODED frame (decode order, +# hidden alt-ref frames included), written after CDEF + superres + loop +# restoration have all run, i.e. exactly the frame as it is stored into the +# reference buffer. Y then U then V, crop-sized rows (post-superres +# y_crop_width), 8-bit as u8 and high bitdepth as u16 LE -- bit-depth +# correct, unlike the u8-narrowing debug dumps. +# +# Rungs 1/6 (pre-filter / post-deblock) stop before CDEF+LR+superres, and +# every ffmpeg/aomdec pixel gate in this repo compares SHOWN frames only +# (class gate-blind-to-hidden-frames), so before this rung no instrument in +# the repo could compare a hidden frame's final pixels at all. +python3 - "$F" <<'PYF' +import sys +path = sys.argv[1] +s = open(path).read() +if "EC_INSTRUMENTED_FINAL" in s: + print("final dump already instrumented (no-op)") + sys.exit(0) + +anchor = """ if (!pbi->dcb.corrupted) { + if (cm->features.refresh_frame_context == REFRESH_FRAME_CONTEXT_BACKWARD) {""" +dump = """ /* EC_INSTRUMENTED_FINAL */ + { + const char *ec_dump = getenv("EC_AV1_FINAL_DUMP"); + if (ec_dump) { + static int ec_final_idx = 0; + char ec_path[1024]; + snprintf(ec_path, sizeof(ec_path), "%s.f%d", ec_dump, ec_final_idx++); + FILE *ec_f = fopen(ec_path, "wb"); + if (ec_f) { + const YV12_BUFFER_CONFIG *ec_b = &cm->cur_frame->buf; + const int ec_hbd = (ec_b->flags & YV12_FLAG_HIGHBITDEPTH) != 0; + const uint8_t *const ec_p8[3] = { ec_b->y_buffer, ec_b->u_buffer, + ec_b->v_buffer }; + const int ec_st[3] = { ec_b->y_stride, ec_b->uv_stride, + ec_b->uv_stride }; + const int ec_w[3] = { ec_b->y_crop_width, ec_b->uv_crop_width, + ec_b->uv_crop_width }; + const int ec_h[3] = { ec_b->y_crop_height, ec_b->uv_crop_height, + ec_b->uv_crop_height }; + for (int ec_pl = 0; ec_pl < (num_planes > 1 ? 3 : 1); ++ec_pl) { + for (int ec_r = 0; ec_r < ec_h[ec_pl]; ++ec_r) { + if (ec_hbd) { + const uint16_t *ec_s = CONVERT_TO_SHORTPTR(ec_p8[ec_pl]); + fwrite(ec_s + (size_t)ec_r * ec_st[ec_pl], 2, ec_w[ec_pl], ec_f); + } else { + fwrite(ec_p8[ec_pl] + (size_t)ec_r * ec_st[ec_pl], 1, + ec_w[ec_pl], ec_f); + } + } + } + fclose(ec_f); + } + } + } + +""" +assert anchor in s, "final dump anchor moved" +s = s.replace(anchor, dump + anchor, 1) +open(path, "w").write(s) +print("final dump instrumented") +PYF