forge
Explore
Log in

Don't you dare go Hollow

Hidden-frame pixel oracle -- EC_AV1_FINAL_DUMP on both sides + the repo's first alt-ref gate

Browse files at this commit

3f461cf7cc1b5c5243277ad287f37de43bc7dd6cAhmet Kaan GümüşParent: d2fe762
  • feat
    • hidden-frame pixel oracle -- EC_AV1_FINAL_DUMP on both sides + the repo's first alt-ref gate
Show full message
feat(av1): hidden-frame pixel oracle -- EC_AV1_FINAL_DUMP on both sides + the repo's first alt-ref gate

Every pixel gate here compared decode_stream's output against ffmpeg/aomdec
y4m, and both emit SHOWN frames only, so a hidden (show_frame=0) alt-ref
frame -- which his films are full of, aomenc's default --lag-in-frames --
was decoded, stored into a reference slot and never compared to anything
(class gate-blind-to-hidden-frames).

- scripts/instrument-aom-oracle.sh rung 12: EC_AV1_FINAL_DUMP=<prefix> in the
  instrumented aomdec -> <prefix>.f<N> per DECODED frame (decode order, hidden
  included), after CDEF+superres+loop restoration, i.e. the frame as stored
  into the reference buffer; Y/U/V crop-sized rows, 8-bit u8 / high bitdepth
  u16 LE (bit-depth correct, unlike the u16->u8 narrowing debug dumps).
- ec-av1 stream.rs: matching EC_AV1_FINAL_DUMP at the ref-slot store site,
  same layout; prefix from a thread-local (set_final_dump_prefix) falling back
  to the env var so a gate cannot race a sibling test's decode.
- test helper decode_all_frames_vs_oracle() + gate
  a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact: aomenc
  --auto-alt-ref=1 --lag-in-frames=25 --arnr-maxframes=0 on moving content,
  8-bit and 10-bit, hard assert hidden >= 2, byte-exact per decode-order
  frame. Result: 43 frames / 3 hidden each depth, all pixel-exact.
  --arnr-maxframes=0 is load-bearing and measured: with libaom's temporal
  alt-ref filter on, the same recipe emits 0 hidden frames (vacuous gate).
crates/ec-av1/src/stream.rsmodified+280 -0
@@ -30,6 +30,30 @@ use crate::decode::{
3030 };
3131 use crate::encode::Picture;
3232
33+/// lane-hidden r1: where `EC_AV1_FINAL_DUMP`'s per-frame dump goes for the
34+/// current thread, overriding the environment variable. Every ffmpeg/aomdec
35+/// pixel gate in this repo compares SHOWN frames only (class
36+/// gate-blind-to-hidden-frames), so the hidden alt-ref frames a real aomenc
37+/// stream carries were never compared at all; the gate that does compare
38+/// them needs a dump path that cannot race a sibling test's decode on
39+/// another thread, which a process-global env var cannot give.
40+thread_local! {
41+ static FINAL_DUMP_PREFIX: std::cell::RefCell<Option<String>> =
42+ const { std::cell::RefCell::new(None) };
43+}
44+
45+/// Sets (or with `None` clears) this thread's `EC_AV1_FINAL_DUMP` prefix.
46+#[allow(dead_code)]
47+pub(crate) fn set_final_dump_prefix(prefix: Option<String>) {
48+ FINAL_DUMP_PREFIX.with(|c| *c.borrow_mut() = prefix);
49+}
50+
51+fn final_dump_prefix() -> Option<String> {
52+ FINAL_DUMP_PREFIX
53+ .with(|c| c.borrow().clone())
54+ .or_else(|| std::env::var("EC_AV1_FINAL_DUMP").ok())
55+}
56+
3357 /// Decode every frame in a raw AV1 OBU stream, in coding order.
3458 ///
3559 /// A key frame becomes the reference for the inter frames that follow it,
@@ -46,6 +70,7 @@ use crate::encode::Picture;
4670 /// crate's tile decoders do not reconstruct (see their own docs), or when an
4771 /// inter frame appears before any key frame has supplied a reference.
4872 pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
73+ let final_dump = final_dump_prefix();
4974 let mut parser = Av1Parser::new();
5075 let mut pictures = Vec::new();
5176 let mut pictures_decoded: usize = 0;
@@ -722,6 +747,30 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
722747 let _ = f.write_all(&narrow(&picture.v));
723748 }
724749 }
750+ // lane-hidden r1: the frame exactly as it is about to be stored into
751+ // the reference slots -- after deblock/CDEF/LR/superres, in DECODE
752+ // order, hidden (`show_frame == 0`) alt-ref frames included, and
753+ // bit-depth correct (8-bit as u8, 10/12-bit as u16 LE) unlike the
754+ // u8-narrowing diagnostic dumps above. Matches the instrumented
755+ // aomdec's own `EC_AV1_FINAL_DUMP` rung byte for byte
756+ // (scripts/instrument-aom-oracle.sh rung 12), which is what makes a
757+ // hidden frame's pixels comparable at all.
758+ if let Some(prefix) = &final_dump {
759+ use std::io::Write;
760+ if let Ok(mut f) = std::fs::File::create(format!("{prefix}.f{pictures_decoded}")) {
761+ let mut buf = Vec::new();
762+ for plane in [&picture.y, &picture.u, &picture.v] {
763+ if bit_depth == 8 {
764+ buf.extend(plane.iter().map(|&s| s as u8));
765+ } else {
766+ for &s in plane {
767+ buf.extend_from_slice(&s.to_le_bytes());
768+ }
769+ }
770+ }
771+ let _ = f.write_all(&buf);
772+ }
773+ }
725774 pictures_decoded += 1;
726775 let decoded_seg_map = decode::take_segment_ids();
727776 for i in 0..NUM_REF_FRAMES {
@@ -1591,6 +1640,237 @@ mod tests {
15911640 present
15921641 }
15931642
1643+ /// The instrumented `aomdec` beside the `aomenc` oracle
1644+ /// (`scripts/build-aom-oracle.sh` + `scripts/instrument-aom-oracle.sh`).
1645+ fn aomdec_path() -> std::path::PathBuf {
1646+ if let Some(p) = std::env::var_os("EC_AV1_AOMDEC") {
1647+ return std::path::PathBuf::from(p);
1648+ }
1649+ aomenc_path().with_file_name("aomdec")
1650+ }
1651+
1652+ /// Decodes `stream` with both this decoder and the instrumented oracle
1653+ /// `aomdec`, and compares EVERY decoded frame in DECODE order --
1654+ /// including the hidden (`show_frame == 0`) alt-ref frames no other gate
1655+ /// in this repo can see, because `decode_stream` only pushes shown
1656+ /// frames and `ffmpeg -f obu ... rawvideo` only emits shown frames
1657+ /// (class gate-blind-to-hidden-frames: a hidden frame's defect surfaces
1658+ /// only as drift on some later shown frame, if at all).
1659+ ///
1660+ /// Both sides write the final, post-deblock/CDEF/LR/superres frame as it
1661+ /// is stored into the reference buffer (`EC_AV1_FINAL_DUMP`, ours in
1662+ /// `decode_stream`, the oracle's in rung 12 of
1663+ /// `scripts/instrument-aom-oracle.sh`), 8-bit as u8 / high bitdepth as
1664+ /// u16 LE. Returns `(frames_decoded, hidden_frames)`.
1665+ fn decode_all_frames_vs_oracle(stream: &[u8], name: &str) -> (usize, usize) {
1666+ let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
1667+ let _ = std::fs::remove_dir_all(&dir);
1668+ std::fs::create_dir_all(&dir).expect("scratch dir");
1669+ let obu = dir.join("in.obu");
1670+ std::fs::write(&obu, stream).expect("writing the stream");
1671+ let aom_prefix = dir.join("aom");
1672+ let out = Command::new(aomdec_path())
1673+ .args(["--codec=av1", "-o"])
1674+ .arg(dir.join("out.y4m"))
1675+ .arg(&obu)
1676+ .env("EC_AV1_FINAL_DUMP", &aom_prefix)
1677+ .stdin(Stdio::null())
1678+ .stdout(Stdio::piped())
1679+ .stderr(Stdio::piped())
1680+ .output()
1681+ .expect("aomdec failed to run");
1682+ assert!(
1683+ out.status.success(),
1684+ "{name}: the oracle aomdec refused the stream: {}",
1685+ String::from_utf8_lossy(&out.stderr)
1686+ );
1687+ let count_dumps = |prefix: &std::path::Path| -> usize {
1688+ let mut n = 0usize;
1689+ while std::path::PathBuf::from(format!("{}.f{n}", prefix.display())).is_file() {
1690+ n += 1;
1691+ }
1692+ n
1693+ };
1694+ let oracle_frames = count_dumps(&aom_prefix);
1695+ assert!(
1696+ oracle_frames > 0,
1697+ "{name}: the oracle wrote no EC_AV1_FINAL_DUMP frames -- rung 12 of \
1698+ scripts/instrument-aom-oracle.sh is missing from {}",
1699+ aomdec_path().display()
1700+ );
1701+ let ours_prefix = dir.join("ours");
1702+ set_final_dump_prefix(Some(ours_prefix.display().to_string()));
1703+ let decoded = decode_stream(stream);
1704+ set_final_dump_prefix(None);
1705+ let shown = decoded
1706+ .unwrap_or_else(|e| panic!("{name}: this decoder refused the stream: {e}"))
1707+ .len();
1708+ let our_frames = count_dumps(&ours_prefix);
1709+ assert_eq!(
1710+ our_frames, oracle_frames,
1711+ "{name}: decoded {our_frames} frames in decode order, the oracle decoded \
1712+ {oracle_frames}"
1713+ );
1714+ for i in 0..oracle_frames {
1715+ let want =
1716+ std::fs::read(format!("{}.f{i}", aom_prefix.display())).expect("oracle dump");
1717+ let got = std::fs::read(format!("{}.f{i}", ours_prefix.display())).expect("our dump");
1718+ assert_eq!(
1719+ got.len(),
1720+ want.len(),
1721+ "{name}: decode-order frame {i} is {} bytes, the oracle's is {}",
1722+ got.len(),
1723+ want.len()
1724+ );
1725+ if let Some(at) = got.iter().zip(&want).position(|(a, b)| a != b) {
1726+ let differing = got.iter().zip(&want).filter(|(a, b)| a != b).count();
1727+ panic!(
1728+ "{name}: decode-order frame {i} of {oracle_frames} ({shown} shown, {} \
1729+ hidden) differs from the oracle at byte {at} (ours {} vs {}), {differing} \
1730+ bytes differ -- stream pinned at {}",
1731+ oracle_frames - shown,
1732+ got[at],
1733+ want[at],
1734+ obu.display()
1735+ );
1736+ }
1737+ }
1738+ let hidden = oracle_frames - shown;
1739+ let _ = std::fs::remove_dir_all(&dir);
1740+ (oracle_frames, hidden)
1741+ }
1742+
1743+ /// The repo's first hidden-frame pixel gate. Every other aomenc gate
1744+ /// here compares `decode_stream`'s output against `ffmpeg -f obu`, and
1745+ /// both sides emit SHOWN frames only -- so an alt-ref frame that is
1746+ /// decoded, stored into a reference slot and never displayed was, until
1747+ /// this gate, never compared to anything (class
1748+ /// gate-blind-to-hidden-frames). His films are aomenc-encoded with the
1749+ /// default `--lag-in-frames`, so they are full of exactly these frames.
1750+ ///
1751+ /// `--auto-alt-ref=1 --lag-in-frames=25` on moving content makes aomenc
1752+ /// build alt-refs; `--arnr-maxframes=0` is load-bearing -- with libaom's
1753+ /// temporal filter on, this fixture's alt-ref candidates get filtered
1754+ /// away and the encoder emits ZERO hidden frames (measured: 0 hidden
1755+ /// with the filter on, 3 with it off), which would have made the gate
1756+ /// vacuous. The `hidden >= 2` assertion is hard, on both bit depths, so
1757+ /// a recipe that stops producing hidden frames fails rather than skips.
1758+ #[test]
1759+ fn a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact() {
1760+ const NAME: &str = "a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact";
1761+ let _gate_lock = lock_gate_counters();
1762+ if !have_ffmpeg() {
1763+ eprintln!("SKIP {NAME}: no ffmpeg");
1764+ return;
1765+ }
1766+ if !have_aomenc() {
1767+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1768+ return;
1769+ }
1770+ for bit_depth in [8u32, 10u32] {
1771+ let (width, height, frames) = (64usize, 64usize, 40usize);
1772+ let duration = frames as f64 / 25.0;
1773+ let source = format!("testsrc2=size={width}x{height}:duration={duration}:rate=25");
1774+ let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
1775+ let y4m = Command::new("ffmpeg")
1776+ .args([
1777+ "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
1778+ "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
1779+ ])
1780+ .stdin(Stdio::null())
1781+ .stdout(Stdio::piped())
1782+ .stderr(Stdio::piped())
1783+ .output()
1784+ .expect("ffmpeg failed to run");
1785+ assert!(
1786+ y4m.status.success(),
1787+ "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
1788+ String::from_utf8_lossy(&y4m.stderr)
1789+ );
1790+ let depth_arg = format!("--bit-depth={bit_depth}");
1791+ let input_depth_arg = format!("--input-bit-depth={bit_depth}");
1792+ let mut child = Command::new(aomenc_path())
1793+ .args([
1794+ "--codec=av1",
1795+ "--passes=1",
1796+ "--end-usage=q",
1797+ "--cq-level=45",
1798+ "--cpu-used=0",
1799+ "--threads=1",
1800+ "--row-mt=0",
1801+ "--kf-max-dist=1000",
1802+ "--enable-order-hint=1",
1803+ "--auto-alt-ref=1",
1804+ "--lag-in-frames=25",
1805+ "--arnr-maxframes=0",
1806+ &depth_arg,
1807+ &input_depth_arg,
1808+ // The same tool set every sibling inter gate pins -- the
1809+ // open capability gaps (rect/AB partitions, warped/OBMC,
1810+ // masked compound, palette, ...) are other lanes' work;
1811+ // this gate is about hidden frames, not about them.
1812+ "--enable-warped-motion=0",
1813+ "--enable-obmc=0",
1814+ "--enable-masked-comp=0",
1815+ "--enable-interintra-comp=0",
1816+ "--enable-onesided-comp=0",
1817+ "--enable-interintra-wedge=0",
1818+ "--enable-smooth-interintra=0",
1819+ "--enable-rect-partitions=0",
1820+ "--enable-ab-partitions=0",
1821+ "--enable-1to4-partitions=0",
1822+ "--enable-filter-intra=0",
1823+ "--enable-smooth-intra=0",
1824+ "--enable-paeth-intra=0",
1825+ "--enable-directional-intra=0",
1826+ "--enable-angle-delta=0",
1827+ "--enable-tx-size-search=0",
1828+ "--enable-cdef=0",
1829+ "--enable-restoration=0",
1830+ "--max-partition-size=32",
1831+ "--min-partition-size=32",
1832+ "--enable-palette=0",
1833+ "--enable-intrabc=0",
1834+ "--enable-cfl-intra=0",
1835+ "--enable-ref-frame-mvs=0",
1836+ "--obu",
1837+ "-o",
1838+ "-",
1839+ "-",
1840+ ])
1841+ .stdin(Stdio::piped())
1842+ .stdout(Stdio::piped())
1843+ .stderr(Stdio::piped())
1844+ .spawn()
1845+ .expect("aomenc failed to start");
1846+ child
1847+ .stdin
1848+ .take()
1849+ .expect("aomenc stdin")
1850+ .write_all(&y4m.stdout)
1851+ .expect("writing y4m to aomenc");
1852+ let out = child.wait_with_output().expect("aomenc failed to run");
1853+ assert!(
1854+ out.status.success(),
1855+ "{NAME}: aomenc refused the {bit_depth}-bit fixture: {}",
1856+ String::from_utf8_lossy(&out.stderr)
1857+ );
1858+ let stream = out.stdout;
1859+ let (total, hidden) =
1860+ decode_all_frames_vs_oracle(&stream, &format!("altref-hidden-{bit_depth}bit"));
1861+ assert!(
1862+ hidden >= 2,
1863+ "{NAME}: the {bit_depth}-bit recipe produced only {hidden} hidden frame(s) of \
1864+ {total} decoded -- the gate would be vacuous (class \
1865+ gate-blind-to-hidden-frames)"
1866+ );
1867+ eprintln!(
1868+ "{NAME} {bit_depth}-bit: {total} frames decoded, {hidden} hidden, all \
1869+ pixel-exact vs the oracle in decode order"
1870+ );
1871+ }
1872+ }
1873+
15941874 /// A real `aomenc` filter-intra fixture: every other intra mode disabled
15951875 /// (smooth/paeth/directional/angle-delta) and
15961876 /// `--max-partition-size=32` (past which `av1_filter_intra_allowed_bsize`'s
lanes/hidden-r1.report.mdadded+72 -0
@@ -0,0 +1,72 @@
1+# lane-hidden r1 — a direct hidden-frame (alt-ref) pixel oracle + gate
2+
3+## Premise, re-measured
4+Charter premise (ledger `constraint|ec-av1 decode_stream pushes a picture only under
5+header.show_frame`) confirmed at HEAD dc5553f: `crates/ec-av1/src/stream.rs` pushes into
6+`pictures` only inside `if header.show_frame`, and every pixel gate compares against
7+`ffmpeg -f obu ... rawvideo` / `aomdec -o y4m`, both shown-frames-only. So no hidden
8+(`show_frame == 0`) alt-ref frame's pixels were compared anywhere in the repo.
9+
10+## What changed
11+- `scripts/instrument-aom-oracle.sh` (rung 12, appended): `EC_AV1_FINAL_DUMP=<prefix>` in the
12+ instrumented `aomdec` → `<prefix>.f<N>`, one file per DECODED frame (decode order, hidden
13+ frames included), written in `decode_frame` after CDEF + superres + loop restoration and
14+ before the `!pbi->dcb.corrupted` block — i.e. the frame exactly as stored into the reference
15+ buffer. Y then U then V, crop-sized rows (post-superres `y_crop_width`), 8-bit as u8 and
16+ high bitdepth as u16 LE via `CONVERT_TO_SHORTPTR` (bit-depth correct; the other dumps in
17+ this repo narrow u16→u8 and silently truncate 10-bit).
18+- `crates/ec-av1/src/stream.rs`: matching `EC_AV1_FINAL_DUMP` at the ref-slot store site
19+ (immediately before `pictures_decoded += 1;`, so post-deblock/CDEF/LR/superres, decode
20+ order, hidden frames included), same byte layout, `bit_depth == 8` → u8 else u16 LE. The
21+ prefix comes from a thread-local (`set_final_dump_prefix`) falling back to the env var, so
22+ a gate's dump cannot be polluted by a sibling test decoding on another thread.
23+- `crates/ec-av1/src/stream.rs` tests: `aomdec_path()`, helper
24+ `decode_all_frames_vs_oracle(stream, name) -> (frames, hidden)` (runs both dumps, asserts
25+ equal frame counts, compares every decode-order frame byte for byte, reports first
26+ differing byte + count and pins the stream on failure), and the gate
27+ `a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact`.
28+
29+## Gate
30+`a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact` — 64x64 testsrc2, 40 frames,
31+`--auto-alt-ref=1 --lag-in-frames=25 --arnr-maxframes=0 --kf-max-dist=1000` plus the tool set
32+the sibling inter gates pin; run for 8-bit and 10-bit. Hard `assert!(hidden >= 2)` (no skip),
33+hard per-frame byte equality incl. hidden frames, `decode_stream` error = failure not skip.
34+
35+`--arnr-maxframes=0` is load-bearing and was measured, not assumed: with libaom's temporal
36+alt-ref filter at its default the same recipe emits **0 hidden frames** (the gate would be
37+vacuous); with it off, 3.
38+
39+ cd /home/user/Documents/Code/Rust/edith_codecs-hidden
40+ export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-hidden
41+ EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib \
42+ a_real_aomenc_altref_sequence_hidden -- --nocapture
43+
44+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
45+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
46+EVIDENCE: recipe-vacuity measurement | same recipe with/without --arnr-maxframes=0 | hidden 0 → 3
47+
48+## Refusals
49+None lifted (`refusal_inventory.rs` / `gate_coverage.rs` untouched) — this lane adds an
50+instrument and a gate, it does not widen decode capability.
51+
52+## (d) Which existing gates carry hidden frames
53+Static scan of the 52 encoder-driven gates in stream.rs: **15 pre-existing gates pass
54+`--auto-alt-ref=1`** (1 with `--lag-in-frames=0`, so no alt-ref is possible there):
55+reference_select, compound_references, obmc, obmc_8x8, warped_motion, interintra,
56+interintra_wedge, free_partitions, ab_partitions, masked_compound, cdef,
57+an_altref_reference, delta_q_and_delta_lf, gradients_with_cdef (lag=25), and
58+a_golden_reference (lag=0 → none). Measured proxy for that recipe shape (the reference-select
59+arg list, 20 frames at lag=16, testsrc2 rather than each gate's own `gradients_source` seed):
60+**1 hidden frame per stream, decoded by us and compared by nothing**. The 40-frame variant of
61+the same recipe produced 0 (libaom's temporal filter absorbs the candidates), so the count is
62+content- and length-dependent — a per-gate sweep with each gate's own fixture is the honest
63+way to size it.
64+
65+- deferred: sweeping `decode_all_frames_vs_oracle` over the 14 alt-ref-capable existing gate
66+ recipes — cheap per gate but 14 recipe transcriptions and 14 encodes; unblocked by an
67+ orchestrator decision (the helper it needs now exists and is one call per gate).
68+- accepted: the gate's fixture is `testsrc2` (deterministic lavfi source, no seed) rather
69+ than `gradients_source` (whose seed lavfi ignores — memory `seeded-fixture-not-reproducible`).
70+
71+## Suite
72+`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib` (scoped, per charter): TOTALS_PLACEHOLDER
scripts/instrument-aom-oracle.shmodified+64 -0
@@ -641,3 +641,67 @@ s = s.replace(old4, new4, 1)
641641 open(path, "w").write(s)
642642 print("decodetxb rung 11 (per-symbol coeff ladder) instrumented")
643643 PYC11
644+
645+# --- rung 12: FINAL reconstruction dump (lane-hidden r1) ----------------
646+# EC_AV1_FINAL_DUMP=<prefix> -> <prefix>.f<N> per DECODED frame (decode order,
647+# hidden alt-ref frames included), written after CDEF + superres + loop
648+# restoration have all run, i.e. exactly the frame as it is stored into the
649+# reference buffer. Y then U then V, crop-sized rows (post-superres
650+# y_crop_width), 8-bit as u8 and high bitdepth as u16 LE -- bit-depth
651+# correct, unlike the u8-narrowing debug dumps.
652+#
653+# Rungs 1/6 (pre-filter / post-deblock) stop before CDEF+LR+superres, and
654+# every ffmpeg/aomdec pixel gate in this repo compares SHOWN frames only
655+# (class gate-blind-to-hidden-frames), so before this rung no instrument in
656+# the repo could compare a hidden frame's final pixels at all.
657+python3 - "$F" <<'PYF'
658+import sys
659+path = sys.argv[1]
660+s = open(path).read()
661+if "EC_INSTRUMENTED_FINAL" in s:
662+ print("final dump already instrumented (no-op)")
663+ sys.exit(0)
664+
665+anchor = """ if (!pbi->dcb.corrupted) {
666+ if (cm->features.refresh_frame_context == REFRESH_FRAME_CONTEXT_BACKWARD) {"""
667+dump = """ /* EC_INSTRUMENTED_FINAL */
668+ {
669+ const char *ec_dump = getenv("EC_AV1_FINAL_DUMP");
670+ if (ec_dump) {
671+ static int ec_final_idx = 0;
672+ char ec_path[1024];
673+ snprintf(ec_path, sizeof(ec_path), "%s.f%d", ec_dump, ec_final_idx++);
674+ FILE *ec_f = fopen(ec_path, "wb");
675+ if (ec_f) {
676+ const YV12_BUFFER_CONFIG *ec_b = &cm->cur_frame->buf;
677+ const int ec_hbd = (ec_b->flags & YV12_FLAG_HIGHBITDEPTH) != 0;
678+ const uint8_t *const ec_p8[3] = { ec_b->y_buffer, ec_b->u_buffer,
679+ ec_b->v_buffer };
680+ const int ec_st[3] = { ec_b->y_stride, ec_b->uv_stride,
681+ ec_b->uv_stride };
682+ const int ec_w[3] = { ec_b->y_crop_width, ec_b->uv_crop_width,
683+ ec_b->uv_crop_width };
684+ const int ec_h[3] = { ec_b->y_crop_height, ec_b->uv_crop_height,
685+ ec_b->uv_crop_height };
686+ for (int ec_pl = 0; ec_pl < (num_planes > 1 ? 3 : 1); ++ec_pl) {
687+ for (int ec_r = 0; ec_r < ec_h[ec_pl]; ++ec_r) {
688+ if (ec_hbd) {
689+ const uint16_t *ec_s = CONVERT_TO_SHORTPTR(ec_p8[ec_pl]);
690+ fwrite(ec_s + (size_t)ec_r * ec_st[ec_pl], 2, ec_w[ec_pl], ec_f);
691+ } else {
692+ fwrite(ec_p8[ec_pl] + (size_t)ec_r * ec_st[ec_pl], 1,
693+ ec_w[ec_pl], ec_f);
694+ }
695+ }
696+ }
697+ fclose(ec_f);
698+ }
699+ }
700+ }
701+
702+"""
703+assert anchor in s, "final dump anchor moved"
704+s = s.replace(anchor, dump + anchor, 1)
705+open(path, "w").write(s)
706+print("final dump instrumented")
707+PYF