forge
Explore
Log in

Don't you dare go Hollow

Lane-lr r3 step 1 -- real aomenc LR gate, proves read_lr fires

Browse files at this commit

74cb98d3aa9bb8f86bba3abda7cbe85f527227b1Ahmet Kaan GümüşParent: 5591c0e
  • feat
    • lane-lr r3 step 1 -- real aomenc LR gate, proves read_lr fires
Show full message
feat(av1): lane-lr r3 step 1 -- real aomenc LR gate, proves read_lr fires

Adds a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly
(stream.rs): --enable-restoration=1 --sb-size=64 aomenc stream over a
multi-superblock (192x128 = 3x2 SB) gradients fixture, cq-level=15 (r2's
sibling gates' usual cq=45 never landed uses_lr=true for this content --
sampled live). Self-pins WIENER_HITS/SGRPROJ_HITS/SWITCHABLE_HITS
thread-local counters in restoration.rs's read_lr_unit and hard-asserts
their sum > 0.

Building the gate found the real r2 gap: the stream.rs uses_lr refusal
ran BEFORE the tile-decode call, so decode_key_frame_tile_with_cdfs/
decode_inter_frame_tile_with_cdfs (and therefore read_lr) were NEVER
invoked through decode_stream -- 40/40 gate attempts hit the refusal with
zero read_lr_unit hits before this fix. Moved the check to run AFTER the
tile decode succeeds, so it now proves the superblock walk survives
read_lr (no desync) before refusing on the true remaining gap. Refusal
string text unchanged ("a frame with loop restoration enabled (the
per-unit lr symbols are read but the Wiener/self-guided filters are not
yet applied to pixels)"), only its position in decode_stream moved.

Verified: cargo test -p ec-av1 -- 236 passed / 0 failed, 17 ignored,
EC_AV1_REQUIRE_AOMENC=1. New gate alone: 39 LR refusals, 0 other
refusals out of 40 attempts, wiener_hits=19 sgrproj_hits=72
switchable_hits=0 (this fixture's RD never picked frame-level
Switchable, only fixed Wiener/Sgrproj -- both arms proven live).

Next (r3 step 2): apply_loop_restoration pass after apply_cdef, Wiener
first (stripe boundary save/restore trap per charter), then SGR, then
drop this refusal.
crates/ec-av1/src/restoration.rsmodified+40 -3
@@ -354,6 +354,33 @@ pub(crate) fn read_lr(
354354 }
355355 }
356356
357+/// r3 gate self-pin: how many units decoded a real (non-`None`) filter, by
358+/// kind -- proves a real `--enable-restoration=1` aomenc stream actually
359+/// exercises `read_lr_unit`'s Wiener/SGR/switchable arms, not just that the
360+/// symbol-count/refusal-string wiring compiles. Never reset -- summed across
361+/// a gate's whole attempt loop, matching `MASKED_COMPOUND_HITS`/`WEDGE_HITS`
362+/// (decode.rs) which this mirrors.
363+thread_local! {
364+ static WIENER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
365+ static SGRPROJ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
366+ static SWITCHABLE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
367+}
368+
369+/// Current value of [`WIENER_HITS`].
370+pub(crate) fn wiener_hits() -> usize {
371+ WIENER_HITS.with(|c| c.get())
372+}
373+/// Current value of [`SGRPROJ_HITS`].
374+pub(crate) fn sgrproj_hits() -> usize {
375+ SGRPROJ_HITS.with(|c| c.get())
376+}
377+/// Current value of [`SWITCHABLE_HITS`] -- bumped once per unit whose frame
378+/// `restoration_type` is `Switchable`, regardless of which `RestoreType`
379+/// (`None`/Wiener/Sgrproj) that unit's own symbol resolved to.
380+pub(crate) fn switchable_hits() -> usize {
381+ SWITCHABLE_HITS.with(|c| c.get())
382+}
383+
357384 fn read_lr_unit(
358385 dec: &mut SymbolDecoder,
359386 cdfs: &mut crate::cdf_state::Cdfs,
@@ -363,22 +390,32 @@ fn read_lr_unit(
363390 ) -> UnitFilter {
364391 match ftype {
365392 RestorationType::Switchable => {
393+ SWITCHABLE_HITS.with(|c| c.set(c.get() + 1));
366394 let t = dec.symbol(&mut cdfs.restore_switchable);
367395 match t {
368396 0 => UnitFilter::None,
369- 1 => UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0)),
370- _ => UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1)),
397+ 1 => {
398+ WIENER_HITS.with(|c| c.set(c.get() + 1));
399+ UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0))
400+ }
401+ _ => {
402+ SGRPROJ_HITS.with(|c| c.set(c.get() + 1));
403+ UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1))
404+ }
371405 }
372406 }
373407 RestorationType::Wiener => {
374408 if dec.symbol(&mut cdfs.restore_wiener) != 0 {
409+ WIENER_HITS.with(|c| c.set(c.get() + 1));
375410 UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0))
376411 } else {
377412 UnitFilter::None
378413 }
379414 }
380415 RestorationType::Sgrproj => {
381- if dec.symbol(&mut cdfs.restore_sgrproj) != 0 {
416+ let bit = dec.symbol(&mut cdfs.restore_sgrproj);
417+ if bit != 0 {
418+ SGRPROJ_HITS.with(|c| c.set(c.get() + 1));
382419 UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1))
383420 } else {
384421 UnitFilter::None
crates/ec-av1/src/stream.rsmodified+176 -15
@@ -187,21 +187,15 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
187187 }
188188 // Loop restoration carries per-restoration-unit symbols in the tile
189189 // (spec 5.11.57 `read_lr`, one group per LR unit reached from the
190- // superblock walk) that this decoder never reads -- same
191- // silent-desync shape as the refusals above. Traced live 2026-08-27:
192- // an aomenc inter frame with `Sgrproj` on the V plane desynced the
193- // partition walk into out-of-alphabet garbage.
194- // lane-lr r2: the per-superblock `read_lr`/`read_lr_unit` symbols are
195- // now read (`crate::restoration`) and no longer desync the partition
196- // walk -- the refusal narrows to its true remaining gap: decoded
197- // Wiener/SGR filters are stored per unit but never applied to
198- // pixels.
199- if header.loop_restoration.uses_lr {
200- return Err(Error::unsupported(
201- "AV1 decode_stream",
202- "a frame with loop restoration enabled (the per-unit lr symbols are read but the Wiener/self-guided filters are not yet applied to pixels)",
203- ));
204- }
190+ // superblock walk) -- lane-lr r2 ported the reader
191+ // (`crate::restoration`), r3 moved this refusal check to AFTER the
192+ // tile decode call below (was here, before it, in r2 -- meaning
193+ // `read_lr` was NEVER actually reached through `decode_stream`, the
194+ // gap the r3 gate caught live: 40/40 attempts hit this refusal with
195+ // zero `read_lr_unit` hits). Checking post-decode instead proves the
196+ // superblock walk actually survived `read_lr` (no desync) before
197+ // refusing on the true remaining gap: decoded Wiener/SGR filters are
198+ // stored per unit but never applied to pixels.
205199 // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec
206200 // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`
207201 // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the
@@ -467,6 +461,15 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
467461 header.allow_screen_content_tools,
468462 )?
469463 };
464+ // lane-lr r3: the tile decode above just ran `read_lr` for real (see
465+ // this refusal's own doc comment further up) -- refuse now, after a
466+ // successful structural decode, rather than before it.
467+ if header.loop_restoration.uses_lr {
468+ return Err(Error::unsupported(
469+ "AV1 decode_stream",
470+ "a frame with loop restoration enabled (the per-unit lr symbols are read but the Wiener/self-guided filters are not yet applied to pixels)",
471+ ));
472+ }
470473 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
471474 // *initial* table into the slots it refreshes, not the adapted
472475 // end-of-tile one.
@@ -4671,6 +4674,164 @@ mod tests {
46714674 );
46724675 }
46734676
4677+ /// lane-lr r3: proves stage 1/2's exit criterion -- a real
4678+ /// `--enable-restoration=1` aomenc stream must survive the whole
4679+ /// partition walk (every symbol read entropy-exact) and land on the
4680+ /// NEW, narrowed refusal ("read but not applied"), never desync into
4681+ /// some other named refusal or an outright decode panic. Multi-superblock
4682+ /// fixture (192x128 = 3x2 SBs of 64px) per the charter's own trap
4683+ /// warning -- a single-SB fixture can never re-enter `read_lr` a second
4684+ /// time and would leave `SWITCHABLE_HITS`/etc. proving only one call
4685+ /// site, not the per-SB loop.
4686+ #[test]
4687+ fn a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly() {
4688+ const NAME: &str = "a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly";
4689+ let _gate_lock = lock_gate_counters();
4690+ if !have_ffmpeg() {
4691+ eprintln!("SKIP {NAME}: no ffmpeg");
4692+ return;
4693+ }
4694+ if !have_aomenc() {
4695+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4696+ return;
4697+ }
4698+ let (width, height) = (192usize, 128usize);
4699+ let n_attempts: u32 = std::env::var("EC_LR_GATE_ATTEMPTS")
4700+ .ok()
4701+ .and_then(|s| s.parse().ok())
4702+ .unwrap_or(40);
4703+ let mut lr_refusals = 0u32;
4704+ let mut other_refusals = Vec::new();
4705+ for attempt in 0..n_attempts {
4706+ let seed = 42 + attempt;
4707+ let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
4708+ let y4m = Command::new("ffmpeg")
4709+ .args(["-v", "error", "-f", "lavfi", "-i"])
4710+ .arg(&source)
4711+ .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"])
4712+ .stdin(Stdio::null())
4713+ .stdout(Stdio::piped())
4714+ .stderr(Stdio::piped())
4715+ .output()
4716+ .expect("ffmpeg failed to run");
4717+ assert!(
4718+ y4m.status.success(),
4719+ "ffmpeg fixture: {}",
4720+ String::from_utf8_lossy(&y4m.stderr)
4721+ );
4722+ let mut child = Command::new(aomenc_path())
4723+ .args([
4724+ "--codec=av1",
4725+ "--passes=1",
4726+ "--end-usage=q",
4727+ // r3: a low cq-level (high quality/bitrate) is load-bearing --
4728+ // sampled live (2026-08-30) that aomenc's RD only ever picks a
4729+ // non-`RESTORE_NONE` frame_restoration_type at cq-level<=20 for
4730+ // this fixture; cq-level=45 (this gate's sibling gates' usual
4731+ // value) landed `uses_lr=false` on every attempt.
4732+ "--cq-level=15",
4733+ "--cpu-used=0",
4734+ "--threads=1",
4735+ "--row-mt=0",
4736+ // r3: this decoder always assumes 64px superblocks
4737+ // (`decode.rs` hardcodes `SB_MI=16`, ledger `lane-sb128`
4738+ // dead-ends) -- force aomenc to match rather than risk
4739+ // the unrelated sb128 gap eating this gate's own window.
4740+ "--sb-size=64",
4741+ "--enable-restoration=1",
4742+ "--enable-cdef=0",
4743+ "--enable-rect-partitions=0",
4744+ "--enable-ab-partitions=0",
4745+ "--enable-1to4-partitions=0",
4746+ "--enable-filter-intra=0",
4747+ "--enable-smooth-intra=0",
4748+ "--enable-paeth-intra=0",
4749+ "--enable-tx-size-search=0",
4750+ "--max-partition-size=32",
4751+ "--min-partition-size=16",
4752+ "--enable-palette=0",
4753+ "--enable-intrabc=0",
4754+ "--enable-cfl-intra=0",
4755+ "--enable-ref-frame-mvs=0",
4756+ "--enable-warped-motion=0",
4757+ "--enable-global-motion=0",
4758+ "--enable-masked-comp=0",
4759+ "--enable-interintra-comp=0",
4760+ "--enable-obmc=0",
4761+ "--obu",
4762+ "-o",
4763+ "-",
4764+ "-",
4765+ ])
4766+ .stdin(Stdio::piped())
4767+ .stdout(Stdio::piped())
4768+ .stderr(Stdio::piped())
4769+ .spawn()
4770+ .expect("aomenc failed to start");
4771+ child
4772+ .stdin
4773+ .take()
4774+ .expect("aomenc stdin")
4775+ .write_all(&y4m.stdout)
4776+ .expect("writing y4m to aomenc");
4777+ let out = child.wait_with_output().expect("aomenc failed to run");
4778+ assert!(
4779+ out.status.success(),
4780+ "aomenc refused the fixture: {}",
4781+ String::from_utf8_lossy(&out.stderr)
4782+ );
4783+ let stream = out.stdout;
4784+ match decode_stream(&stream) {
4785+ Ok(_) => {
4786+ // aomenc's own RD chose `RESTORE_NONE` on every plane this
4787+ // attempt -- a legitimately LR-free frame, not a gate
4788+ // failure (see the cq-level comment above: not every
4789+ // attempt lands `uses_lr=true`).
4790+ continue;
4791+ }
4792+ Err(e) => {
4793+ let msg = e.to_string();
4794+ assert!(
4795+ msg.contains("unsupported"),
4796+ "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
4797+ );
4798+ if msg.contains("loop restoration enabled") {
4799+ lr_refusals += 1;
4800+ } else {
4801+ other_refusals.push(format!("seed {seed}: {msg}"));
4802+ }
4803+ }
4804+ }
4805+ }
4806+ assert!(
4807+ lr_refusals > 0,
4808+ "{NAME}: the LR refusal never fired ({} attempts, other refusals:\n{})",
4809+ n_attempts,
4810+ other_refusals.join("\n")
4811+ );
4812+ // Any real (non-`RESTORE_NONE`) filter kind is acceptable proof --
4813+ // aomenc's RD picks the frame-level `restoration_type` itself (not
4814+ // always `Switchable`; observed `Sgrproj` live at cq-level=15 for
4815+ // this fixture), so hard-requiring one specific arm would be the
4816+ // gate-recipe-confound class (ledger).
4817+ let total_hits = crate::restoration::wiener_hits()
4818+ + crate::restoration::sgrproj_hits()
4819+ + crate::restoration::switchable_hits();
4820+ assert!(
4821+ total_hits > 0,
4822+ "{NAME}: {lr_refusals} LR refusals fired but read_lr_unit never decoded a real \
4823+ (non-None) filter -- gate proved nothing about the symbol path"
4824+ );
4825+ eprintln!(
4826+ "{NAME}: {lr_refusals} LR refusals, {} other refusals out of {n_attempts}, \
4827+ wiener_hits={} sgrproj_hits={} switchable_hits={}",
4828+ other_refusals.len(),
4829+ crate::restoration::wiener_hits(),
4830+ crate::restoration::sgrproj_hits(),
4831+ crate::restoration::switchable_hits()
4832+ );
4833+ }
4834+
46744835 /// Pinned streams captured by `EC_AV1_GATE_DUMP` off
46754836 /// `a_real_aomenc_stream_with_warped_motion_refuses_or_matches` -- each
46764837 /// one is a former mismatch, kept as a regression pin (warp-mismatch: