From 587b6a0fd26f54e6c21ae48abf00061a67d353b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 24 Sep 2026 02:28:51 +0300 Subject: [PATCH] ec-av1: inherit segment maps verbatim (lane-av1seglvl): census ALT_Q-only, map-inheritance stream byte-exact --- crates/ec-av1/src/decode.rs | 35 ++- crates/ec-av1/src/refusal_inventory.rs | 159 ++++++++-- crates/ec-av1/src/stream.rs | 420 ++++++++++++++++++++++++- 3 files changed, 568 insertions(+), 46 deletions(-) diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index ea4a8fc4..11fc4e80 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1089,6 +1089,27 @@ fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8, SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id)); } +/// `copy_segment_id` (libaom `decodemv.c:342`): the previous frame's map is +/// inherited VERBATIM over this block's own mi footprint -- per-cell copies, +/// not the minified id [`predicted_segment_id`] hands the block. Without a +/// previous map the footprint is zeroed, exactly as the C NULL branch does. +fn copy_segment_ids(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, fctx: &crate::decode::FrameCtx) { + let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get()); + let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r))); + fctx.seg_ids.with(|m| { + let mut m = m.borrow_mut(); + fctx.prev_seg_ids.with(|p| { + let p = p.borrow(); + for y in 0..y_mis { + for x in 0..x_mis { + let idx = (mi_r + y) * mi_cols + mi_c + x; + m[idx] = p.get(idx).copied().unwrap_or(0); + } + } + }); + }); +} + /// `get_predicted_segment_id` (libaom `dec_get_segment_id` over /// `last_frame_seg_map`): the minimum previous-frame segment id over the /// block's own mi footprint. `0` when there is no previous map. @@ -1230,9 +1251,19 @@ fn inter_segment_id( return; } if !update_map { - // The map is inherited wholesale from the previous frame. + // The map is inherited from the previous frame, and libaom's + // `copy_segment_id` (decodemv.c:342) does that VERBATIM -- a memcpy of + // the previous map over the block's own footprint, mixed ids intact -- + // while the id the BLOCK itself carries is the min over that footprint + // (`get_predicted_segment_id`). Stamping the min here flattened mixed + // footprints into the saved map, and every later frame whose + // `update_map == 0` copy or temporal prediction read that position + // dequantized with the wrong segment's `SEG_LVL_ALT_Q` (class + // `simplified-inheritance`). + copy_segment_ids(mi_r, mi_c, w_mi, h_mi, fctx); let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx); - write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx); + fctx.cur_segment_id.with(|c| c.set(id)); + SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id)); return; } if pre_skip && !pre_skip_frame { diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 82d1dd3b..801f86bf 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -407,10 +407,18 @@ const PROVEN: &[(&str, &str)] = &[ ), // lane-t900 r27, negative gate + census: a written key frame carrying // each of the three mode-overriding features (over three segment ids) is - // refused by name with no picture; and six real aomenc recipes - // (`--aq-mode=1/2/3`, `--deltaq-mode=1`, plus a baseline for arrival) - // never enable one -- only `--aq-mode=3` changes the stream at all, and - // what it codes is `segment_id` symbols under `SEG_LVL_ALT_Q`. + // refused by name with no picture; and real aomenc recipes never enable + // one. lane-av1seglvl re-scoped the census: beyond r27's six 1-pass + // no-lag recipes it now parses EVERY frame header's feature table over + // alt-ref-lag and genuine two-pass arms (`--aq-mode=1/2`, cq45 and the + // branch's own high-q cq63, screen + film sources) -- the shapes that + // reach `configure_static_seg_features`, the only setter of ALT_LF/ + // REF_FRAME/SKIP in the tree, which is gated on `hl_sf.static_segmentation` + // ("Always set to 0", speed_features.h) and the second pass + // (encoder_utils.c:738). What aomenc codes is `SEG_LVL_ALT_Q` tables and + // `segment_id` symbols, and nothing else; the map-inheritance defect that + // census surfaced (verbatim copy, decodemv.c:342) is fixed and witnessed + // by `a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_ // pixel_exact`. ( "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV (this decoder reads segment_id but never lets a segment override a block's reference, skip or mode)", "a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name", @@ -589,7 +597,11 @@ mod tests { .chain(REFUSALS) .map(|&s| s.to_owned()) .collect(); - assert!(found.len() >= 30, "the refusal scan found only {} reasons -- it is broken, not the decoder", found.len()); + assert!( + found.len() >= 30, + "the refusal scan found only {} reasons -- it is broken, not the decoder", + found.len() + ); let added: Vec<&String> = found.difference(&listed).collect(); assert!( @@ -635,9 +647,14 @@ mod tests { let mut found: BTreeSet = BTreeSet::new(); for (i, _) in src.match_indices("\"SKIP ") { let rest = &src[i + "\"SKIP ".len()..]; - let Some(colon) = rest.find(':') else { continue }; + let Some(colon) = rest.find(':') else { + continue; + }; let name = &rest[..colon]; - if !name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') { + if !name + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') + { continue; } // The tail of the message says what was skipped. Only "{e}" -- the @@ -650,7 +667,10 @@ mod tests { } } let listed: BTreeSet<&str> = GATES_THAT_SKIP_ON_A_DECODE_ERROR.iter().copied().collect(); - let added: Vec<&String> = found.iter().filter(|n| !listed.contains(n.as_str())).collect(); + let added: Vec<&String> = found + .iter() + .filter(|n| !listed.contains(n.as_str())) + .collect(); assert!( added.is_empty(), "these gates turn a decode error into a printed SKIP and are not declared: \ @@ -723,9 +743,18 @@ mod tests { fn every_partition_value_of_an_enumerated_alphabet_has_an_arm() { // (the refusal in the fallback arm, the alphabet its CDF codes) let blocks: [(&str, usize); 4] = [ - ("a 32x32 partition type this decoder does not code", crate::cdf::PARTITION_W32[0].len() - 1), - ("an INTER 32x32 partition type this decoder does not code", crate::cdf::PARTITION_W32[0].len() - 1), - ("a 128x128 superblock partition value outside the 8-symbol alphabet", crate::cdf::PARTITION_W128[0].len() - 1), + ( + "a 32x32 partition type this decoder does not code", + crate::cdf::PARTITION_W32[0].len() - 1, + ), + ( + "an INTER 32x32 partition type this decoder does not code", + crate::cdf::PARTITION_W32[0].len() - 1, + ), + ( + "a 128x128 superblock partition value outside the 8-symbol alphabet", + crate::cdf::PARTITION_W128[0].len() - 1, + ), // lane-t900 r24: the key-frame superblock root. Its `part` is // either a `partition_w64` symbol or, at a frame edge, one of the // three gathered outcomes (PARTITION_HORZ, PARTITION_VERT, @@ -779,7 +808,10 @@ mod tests { "the `match` at decode.rs:{} refuses {reason:?} but has no arm for {:?} -- that \ is a real gap in its {alphabet}-value alphabet, not a dead refusal", i + 1, - missing.iter().map(|v| PARTITION_NAMES[*v]).collect::>() + missing + .iter() + .map(|v| PARTITION_NAMES[*v]) + .collect::>() ); } assert_eq!( @@ -833,7 +865,11 @@ mod tests { .next() .unwrap_or("") .to_owned(); - assert!(!var.is_empty(), "the chain at decode.rs:{} tests nothing", head + 1); + assert!( + !var.is_empty(), + "the chain at decode.rs:{} tests nothing", + head + 1 + ); // Walk up collecting every branch head of this chain, each read to // the line that opens its body. @@ -843,7 +879,8 @@ mod tests { loop { i -= 1; let t = lines[i].trim_start(); - if indent(lines[i]) != outer || !(t.starts_with("} else if ") || t.starts_with("if ")) + if indent(lines[i]) != outer + || !(t.starts_with("} else if ") || t.starts_with("if ")) { if i == 0 { break; @@ -893,7 +930,10 @@ mod tests { "the chain at decode.rs:{} refuses {reason:?} but no branch names {:?} -- that \ is a real gap in its {alphabet}-value alphabet, not a dead refusal", head + 1, - missing.iter().map(|v| PARTITION_NAMES[*v]).collect::>() + missing + .iter() + .map(|v| PARTITION_NAMES[*v]) + .collect::>() ); } assert_eq!(found, chains.len()); @@ -996,11 +1036,18 @@ mod tests { values.insert(((1u64 << length) - 2) as u32); } let max = *values.iter().max().unwrap(); - assert_eq!(max, (1u32 << 20) - 2, "the enumeration misses the spec's own ceiling"); + assert_eq!( + max, + (1u32 << 20) - 2, + "the enumeration misses the spec's own ceiling" + ); // A coefficient is masked to 20 bits (spec 5.11.39), and the base and // base-range syntax contribute at most 15 of that before the tail, so // this is the largest tail a legal coefficient can need. - assert!(max >= 0xF_FFFF - 15, "the ceiling is below the largest legal tail"); + assert!( + max >= 0xF_FFFF - 15, + "the ceiling is below the largest legal tail" + ); for value in values { match roundtrip(value) { Ok(read) => assert_eq!(read, value, "the Golomb tail {value} read back as {read}"), @@ -1056,7 +1103,11 @@ mod tests { ]; assert_eq!(alphabets[0].1, 13, "the y_mode alphabet changed size"); for group in &crate::cdf::Y_MODE { - assert_eq!(group.len() - 1, alphabets[0].1, "the y_mode rows disagree on width"); + assert_eq!( + group.len() - 1, + alphabets[0].1, + "the y_mode rows disagree on width" + ); } let src = include_str!("decode.rs"); @@ -1064,12 +1115,17 @@ mod tests { let mut sites = 0usize; for (i, line) in lines.iter().enumerate() { let t = line.trim(); - let Some(rest) = t.strip_prefix("if mode >= ") else { continue }; + let Some(rest) = t.strip_prefix("if mode >= ") else { + continue; + }; let Some(threshold) = rest.trim_end_matches(" {").parse::().ok() else { continue; }; // Only the guards carrying THIS refusal. - if !lines[i..(i + 4).min(lines.len())].join("\n").contains(REFUSAL) { + if !lines[i..(i + 4).min(lines.len())] + .join("\n") + .contains(REFUSAL) + { continue; } sites += 1; @@ -1099,7 +1155,10 @@ mod tests { i + 1 ); } - assert_eq!(sites, 3, "the intra-mode guard is at three sites, found {sites}"); + assert_eq!( + sites, 3, + "the intra-mode guard is at three sites, found {sites}" + ); } /// lane-t900 r31, ENUMERATION for "a HORZ/VERT intra strip in a @@ -1159,7 +1218,10 @@ mod tests { } } } - assert!(with_128 > 0, "enumeration is vacuous -- no 128-sided footprint was tried"); + assert!( + with_128 > 0, + "enumeration is vacuous -- no 128-sided footprint was tried" + ); assert_eq!( allowed_at_128, 0, "a footprint with a 128-pixel side passed av1_allow_palette's bound -- the \ @@ -1271,11 +1333,17 @@ mod tests { // (3) The two tables, read out of decode_rect_split's own text: every // `(w, h) =>` / `(w, h) |` match arm head between the table's `let` // and the guard that follows it. - let body_at = src.find("fn decode_rect_split(").expect("decode_rect_split is gone"); + let body_at = src + .find("fn decode_rect_split(") + .expect("decode_rect_split is gone"); let body = &src[body_at..]; let slice = |from: &str, to: &str| -> &str { - let a = body.find(from).unwrap_or_else(|| panic!("{from:?} is gone from decode_rect_split")); - let b = body[a..].find(to).unwrap_or_else(|| panic!("{to:?} is gone from decode_rect_split")); + let a = body + .find(from) + .unwrap_or_else(|| panic!("{from:?} is gone from decode_rect_split")); + let b = body[a..] + .find(to) + .unwrap_or_else(|| panic!("{to:?} is gone from decode_rect_split")); &body[a..a + b] }; let arm_shapes = |text: &str| -> BTreeSet<(usize, usize)> { @@ -1348,7 +1416,10 @@ mod tests { } } } - assert_eq!(checked, 40, "the strip domain is not the ten rect shapes x four depths"); + assert_eq!( + checked, 40, + "the strip domain is not the ten rect shapes x four depths" + ); } /// lane-t900 r33, ENUMERATION for "CfL, filter intra or a palette on a @@ -1458,9 +1529,15 @@ mod tests { } continue; } - let Some(rest) = line.strip_prefix('(') else { continue }; - let Some((pair, _)) = rest.split_once(") =>") else { continue }; - let Some((a, b)) = pair.split_once(',') else { continue }; + let Some(rest) = line.strip_prefix('(') else { + continue; + }; + let Some((pair, _)) = rest.split_once(") =>") else { + continue; + }; + let Some((a, b)) = pair.split_once(',') else { + continue; + }; let bw: usize = a.trim().parse().expect("arm bw"); let bh: usize = b.trim().parse().expect("arm bh"); assert!( @@ -1472,9 +1549,18 @@ mod tests { seen.push((bw, bh)); arms += 1; } - assert!(arms >= 10, "only {arms} arms parsed -- the table's shape changed"); - assert!(saw_none_fallback, "filter_intra_size_class_rect lost its `_ => None` fallback"); - assert!(saw_square_delegate, "filter_intra_size_class_rect lost its square-delegate arm"); + assert!( + arms >= 10, + "only {arms} arms parsed -- the table's shape changed" + ); + assert!( + saw_none_fallback, + "filter_intra_size_class_rect lost its `_ => None` fallback" + ); + assert!( + saw_square_delegate, + "filter_intra_size_class_rect lost its square-delegate arm" + ); // The guard arm delegates square strips to `filter_intra_size_class`; // drive the delegate directly, so a widening there turns THIS test red // (the numeric walk never reaches the guard arm). @@ -1524,7 +1610,10 @@ mod tests { ); } } - assert_eq!(sites, 8, "the call-site audit found {sites} sites, not the 8 it enumerated"); + assert_eq!( + sites, 8, + "the call-site audit found {sites} sites, not the 8 it enumerated" + ); } /// Every entry of [`PROVEN`] must still name a live refusal and a test @@ -1543,7 +1632,9 @@ mod tests { "{reason:?} is listed as proven but is no longer a decode-path refusal -- drop it from PROVEN (the capability landed) or fix the string" ); assert!( - sources.iter().any(|src| src.contains(&format!("fn {gate}("))), + sources + .iter() + .any(|src| src.contains(&format!("fn {gate}("))), "{reason:?} names the proving test {gate}, which exists in neither stream.rs \ nor decode.rs" ); diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 1dcca8c2..d1cde544 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -17,7 +17,7 @@ use ec_av1_syntax::{ Av1Parser, FrameHeader, FrameType, MAX_SEGMENTS, NUM_REF_FRAMES, ObuKind, PRIMARY_REF_NONE, - SEG_LVL_GLOBALMV, SEG_LVL_REF_FRAME, SEG_LVL_SKIP, Tile, TxMode, + SEG_LVL_ALT_Q, SEG_LVL_GLOBALMV, SEG_LVL_MAX, SEG_LVL_REF_FRAME, SEG_LVL_SKIP, Tile, TxMode, }; use ec_core::{Error, Result}; @@ -851,7 +851,9 @@ pub fn decode_stream_with_threads( // symbols `decode_inter_block` unconditionally reads) -- have no // reader on the inter path, so they still refuse by name rather than // desyncing. aomenc's `--aq-mode` segmentation only ever sets - // `SEG_LVL_ALT_Q`. + // `SEG_LVL_ALT_Q` (census gate + // `a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature`: + // 1-pass, alt-ref-lag and two-pass arms, every frame header parsed). let tile_bufs: Vec<&[u8]> = tiles .iter() .map(|t| { @@ -1432,14 +1434,20 @@ fn decode_frame( // SEG_LVL_GLOBALMV, `:1071` in `read_ref_frames`, `:1350` in // `read_is_inter_block`), so a conformant stream CAN carry them and // this is a capability gap, not a spec-conformant guard. Reachability - // from `aomenc` is nil -- its AQ modes set `SEG_LVL_ALT_Q` only - // (`aq_variance.c:89`, `aq_complexity.c:118`, `aq_cyclicrefresh.c:630`) - // and the mode-overriding features come only from the library API - // (`av1_apply_roi_map` `encoder_utils.c:515`, `av1_apply_active_map` - // `encoder_utils.c:557`, the alt-ref overlap case `:401-413`); the CLI - // exposes no ROI/active-map flag (checked). Kept as a named gap: the - // lift is an INTER-block-path change (ref/skip/mode selection) outside - // this lane's region. See `lanes/av1hdr.report.md` §4.1. + // from `aomenc` is nil, for three independent reasons (lane-av1seglvl + // census): the AQ modules clear the table then set `SEG_LVL_ALT_Q` + // only (`aq_variance.c:61` clear + `:89` enable, `aq_complexity.c:74` + // + `:118`, `aq_cyclicrefresh.c:616` + `:630`); the one other setter, + // `configure_static_seg_features` (`encoder_utils.c:315`, which would + // set ALT_LF/REF_FRAME/SKIP around alt-ref groups), is gated on + // `hl_sf.static_segmentation` -- a speed feature libaom's own + // `speed_features.h` documents as "Always set to 0" -- AND on the + // second pass of a two-pass encode (`encoder_utils.c:738`); and + // ROI/active-map maps are control-API only (`av1_apply_roi_map`, + // `av1_apply_active_map`: the CLI exposes no flag for either). Kept as + // a named gap: the lift is an INTER-block-path change (ref/skip/mode + // selection) outside this lane's region. See `lanes/av1hdr.report.md` + // §4.1 and `lanes/av1seglvl.report.md`. for segment in 0..MAX_SEGMENTS { for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] { if header.segmentation.feature_enabled[segment][feature] { @@ -2500,6 +2508,163 @@ pub(crate) mod tests { (stream.len(), result) } + /// lane-av1seglvl: encode `frames` frames of `source` with real aomenc + /// plus `extra` args and return the raw `.obu` bytes -- the census's + /// half-sibling of [`census_attempt`] that keeps the STREAM instead of + /// only its decode verdict, so the caller can parse the frame headers' + /// segmentation tables themselves. + fn encode_aomenc_stream( + source: &str, + width: usize, + height: usize, + frames: usize, + extra: &[&str], + ) -> Vec { + let duration = format!("{}", frames as f64 / 25.0); + let src = format!("{source}=size={width}x{height}:rate=25"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &src, "-t", &duration, "-pix_fmt", "yuv420p", + "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!(y4m.status.success(), "ffmpeg refused the {width}x{height} fixture"); + let limit = format!("--limit={frames}"); + let mut args: Vec = [ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--threads=1", + "--row-mt=0", + "--kf-max-dist=9999", + "--lag-in-frames=0", + ] + .iter() + .map(|s| (*s).to_owned()) + .collect(); + args.push(limit); + args.extend(extra.iter().map(|s| (*s).to_owned())); + args.extend(["--obu".to_owned(), "-o".to_owned(), "-".to_owned(), "-".to_owned()]); + let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout); + assert!(out.status.success(), "aomenc refused {args:?}: {}", String::from_utf8_lossy(&out.stderr)); + out.stdout + } + + /// lane-av1seglvl: encode `frames` frames with a real TWO-PASS aomenc + /// (pass 1 writes the stats file into the session temp dir, pass 2 + /// consumes it) and return the `.obu` bytes. This is the only shape that + /// reaches libaom's `is_stat_consumption_stage_twopass` segmentation + /// setup (`configure_static_seg_features`), so the census is not proven + /// over the encoder's whole reachable surface without it. + fn encode_aomenc_stream_twopass( + source: &str, + width: usize, + height: usize, + frames: usize, + extra: &[&str], + ) -> Vec { + let duration = format!("{}", frames as f64 / 25.0); + let src = format!("{source}=size={width}x{height}:rate=25"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &src, "-t", &duration, "-pix_fmt", "yuv420p", + "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!(y4m.status.success(), "ffmpeg refused the {width}x{height} fixture"); + let limit = format!("--limit={frames}"); + let fpf = std::env::temp_dir().join(format!("ec-av1-segldapass-{}.fpf", std::process::id())); + let mut base: Vec = [ + "--codec=av1", + "--passes=2", + "--end-usage=q", + "--threads=1", + "--row-mt=0", + "--kf-max-dist=9999", + "--lag-in-frames=0", + ] + .iter() + .map(|s| (*s).to_owned()) + .collect(); + base.push(limit); + base.extend(extra.iter().map(|s| (*s).to_owned())); + let mut pass1 = base.clone(); + pass1.extend(["--pass=1".to_owned(), format!("--fpf={}", fpf.display())]); + pass1.extend(["--obu".to_owned(), "-o".to_owned(), "/dev/null".to_owned(), "-".to_owned()]); + let out1 = run_with_stdin(Command::new(aomenc_path()).args(&pass1), &y4m.stdout); + assert!(out1.status.success(), "aomenc pass 1 refused {pass1:?}: {}", String::from_utf8_lossy(&out1.stderr)); + let mut pass2 = base; + pass2.extend(["--pass=2".to_owned(), format!("--fpf={}", fpf.display())]); + pass2.extend(["--obu".to_owned(), "-o".to_owned(), "-".to_owned(), "-".to_owned()]); + let out2 = run_with_stdin(Command::new(aomenc_path()).args(&pass2), &y4m.stdout); + let _ = std::fs::remove_file(&fpf); + assert!(out2.status.success(), "aomenc pass 2 refused {pass2:?}: {}", String::from_utf8_lossy(&out2.stderr)); + out2.stdout + } + + /// lane-av1seglvl: walk every frame OBU of `stream` and tally which + /// `SEG_LVL` features the frame headers actually ENABLE, plus the shape + /// counters a census premise is asserted against: frames with + /// segmentation on, of which `update_map == 1` (the map is coded) and + /// `update_map == 0` (every block's id is INHERITED), and frames whose + /// table carries a real `SEG_LVL_ALT_Q` delta. + /// The last vector counts per SEGMENT-FEATURE INSTANCE (a frame with + /// ALT_Q on all 8 segments contributes 8), which is all the verdict + /// needs: only index `SEG_LVL_ALT_Q` may be non-zero. + /// Returns `(enabled_frames, update_map_frames, inherited_frames, + /// alt_q_frames, feature_instances: [usize; SEG_LVL_MAX])`. + #[allow(clippy::type_complexity)] + fn segmentation_feature_census( + stream: &[u8], + ) -> (usize, usize, usize, usize, [usize; SEG_LVL_MAX]) { + let mut parser = Av1Parser::new(); + let obus = parser + .parse_temporal_unit(stream) + .unwrap_or_else(|e| panic!("the census stream does not even parse: {e}")); + let mut enabled = 0usize; + let mut update_map = 0usize; + let mut inherited = 0usize; + let mut alt_q = 0usize; + let mut feature_frames = [0usize; SEG_LVL_MAX]; + for obu in &obus { + if let ObuKind::Frame(header, _) = &obu.kind { + let seg = &header.segmentation; + if !seg.enabled { + continue; + } + enabled += 1; + if seg.update_map { + update_map += 1; + } else { + inherited += 1; + } + let mut any_q = false; + for segment in 0..MAX_SEGMENTS { + for feature in 0..SEG_LVL_MAX { + if seg.feature_enabled[segment][feature] { + feature_frames[feature] += 1; + if feature == SEG_LVL_ALT_Q { + any_q = true; + } + } + } + } + if any_q { + alt_q += 1; + } + } + } + (enabled, update_map, inherited, alt_q, feature_frames) + } + /// lane-hdrlossless: WITNESS for the one refusal the pilot report left /// without a proving test -- "a frame mixing lossless and lossy /// segments". It is a REAL encoder output, not a defensive pin: @@ -2633,6 +2798,16 @@ pub(crate) mod tests { /// `--aq-mode=1/2/3` (variance, complexity and cyclic-refresh AQ) and /// `--deltaq-mode=1` -- with the refusal as the instrument: if one of /// those features appeared, the decode would stop by name. + /// + /// lane-av1seglvl re-scope: r27's arms were all `--passes=1 + /// --lag-in-frames=0`, so they never coded an alt-ref frame or ran an + /// encoder second pass -- the only shapes where libaom's OTHER seg + /// feature setup (`configure_static_seg_features`) could ever run. The + /// re-scoped half below adds alt-ref-group arms and a real two-pass arm, + /// and upgrades the instrument from the refusal (blind to a pure-ALT_LF + /// stream) to a direct parse of every frame header's `feature_enabled` + /// table: over all of it, aomenc enables `SEG_LVL_ALT_Q` and nothing + /// else. #[test] fn a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature() { if !have_aomenc() { @@ -2700,6 +2875,231 @@ pub(crate) mod tests { "no recipe coded a single segment_id symbol -- segmentation never arrived, so \ this census measures nothing about the three mode-overriding features" ); + + // lane-av1seglvl re-scope: the r27 arms above are all `--passes=1 + // --lag-in-frames=0`, which never codes an alt-ref frame -- the one + // frame type whose segmentation libaom sets up differently + // (`configure_static_seg_features`, encoder_utils.c:738, is further + // gated on the second pass AND on `hl_sf.static_segmentation`, which + // speed_features.h itself documents as "Always set to 0"). The arms + // below cover that whole remaining surface: alt-ref groups under + // `--aq-mode`, a high-cq arm (the branch's own `high_q` gate is + // `avg_q > 48`), and a genuine two-pass encode. The instrument is no + // longer the refusal -- the refusal only fires on + // REF_FRAME/SKIP/GLOBALMV, so an ALT_LF-only stream would decode + // silently past it -- but a direct parse of every frame header's + // `feature_enabled` table. + let lag_recipes: [(&str, &str, usize, usize, Vec<&str>); 4] = [ + ( + "aq-mode=1 lag16 mandelbrot", + "mandelbrot", + 192, + 128, + vec!["--cpu-used=4", "--aq-mode=1", "--cq-level=45", "--lag-in-frames=16", "--auto-alt-ref=1"], + ), + ( + "aq-mode=1 lag16 screen", + "testsrc2", + 256, + 192, + vec!["--cpu-used=4", "--aq-mode=1", "--cq-level=45", "--lag-in-frames=16", "--auto-alt-ref=1"], + ), + ( + "aq-mode=1 lag16 cq63 high_q", + "mandelbrot", + 192, + 128, + vec!["--cpu-used=4", "--aq-mode=1", "--cq-level=63", "--lag-in-frames=16", "--auto-alt-ref=1"], + ), + ( + "aq-mode=2 lag16", + "mandelbrot", + 192, + 128, + vec!["--cpu-used=4", "--aq-mode=2", "--cq-level=45", "--lag-in-frames=16", "--auto-alt-ref=1"], + ), + ]; + let mut total_enabled = 0usize; + let mut total_inherited = 0usize; + let mut total_alt_q = 0usize; + let mut feature_frames = [0usize; SEG_LVL_MAX]; + for (name, source, w, h, extra) in &lag_recipes { + let stream = encode_aomenc_stream(source, *w, *h, 40, extra); + let (enabled, umap, inherited, alt_q, frames_per_feature) = + segmentation_feature_census(&stream); + eprintln!( + "SEGCENSUS {name}: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q {alt_q}, per-feature {frames_per_feature:?}" + ); + total_enabled += enabled; + total_inherited += inherited; + total_alt_q += alt_q; + for (f, n) in frames_per_feature.iter().enumerate() { + feature_frames[f] += n; + } + } + // The two-pass arm: `configure_static_seg_features` runs ONLY at + // `is_stat_consumption_stage_twopass`, so this is the arm that would + // catch its ALT_LF/REF_FRAME/SKIP tables if the dead speed feature + // were ever revived. + { + let stream = encode_aomenc_stream_twopass( + "mandelbrot", + 192, + 128, + 40, + &["--cpu-used=4", "--aq-mode=1", "--cq-level=45", "--lag-in-frames=16", "--auto-alt-ref=1"], + ); + let (enabled, umap, inherited, alt_q, frames_per_feature) = + segmentation_feature_census(&stream); + eprintln!( + "SEGCENSUS twopass aq-mode=1 lag16: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q {alt_q}, per-feature {frames_per_feature:?}" + ); + total_enabled += enabled; + total_inherited += inherited; + total_alt_q += alt_q; + for (f, n) in frames_per_feature.iter().enumerate() { + feature_frames[f] += n; + } + } + // Premise (class gate-blind-to-feature): the arms must actually reach + // the shapes the census speaks about -- segmentation-carrying frames, + // frames whose map is INHERITED (update_map == 0), and frames with a + // real ALT_Q table -- or the "only ALT_Q" verdict below measures + // nothing. + assert!( + total_enabled > 0 && total_alt_q > 0, + "no lag/two-pass arm carried a segmentation-enabled frame -- the census premise \ + never arrived" + ); + assert!( + total_inherited > 0, + "no arm carried an update_map == 0 frame -- the map-inheritance path the decoder \ + reads segment ids through is unmeasured" + ); + // The census verdict, over every frame of every arm: segmentation on + // aomenc's CLI carries SEG_LVL_ALT_Q and NOTHING else. The three + // mode-overriding features and the four ALT_LF deltas have no encoder + // path: `configure_static_seg_features` (the only setter of ALT_LF/ + // REF_FRAME/SKIP in the tree) is gated on `hl_sf.static_segmentation`, + // documented "Always set to 0" (speed_features.h), and ROI/active-map + // are control-API only (aomenc.c has no flag for either). + for (feature, frames) in feature_frames.iter().enumerate() { + if feature == SEG_LVL_ALT_Q { + continue; + } + assert_eq!( + *frames, 0, + "feature index {feature} appeared on {frames} frames of real aomenc output -- \ + the refusal's encoder-never-writes claim is FALSE and the mode path needs \ + porting before this census can stay green" + ); + } + eprintln!( + "SEGCENSUS lag/twopass: {total_enabled} seg-enabled frames over 5 arms, {total_inherited} inherited-map frames, {total_alt_q} with ALT_Q, all other SEG_LVL features: 0 frames" + ); + } + + /// lane-av1seglvl WITNESS: the reaching stream. `--aq-mode=1` turns + /// segmentation on for every frame; `--lag-in-frames=16 --auto-alt-ref=1` + /// adds real alt-ref groups, so the stream mixes map-CODING frames + /// (`update_map == 1`: the key frame and each group's arf) with dozens of + /// map-INHERITING frames (`update_map == 0`), and an inheriting block's + /// id is the MIN of the previous map over its own footprint while the + /// saved map itself inherits that footprint VERBATIM + /// (`copy_segment_id`, decodemv.c:342) -- heterogeneous footprints are + /// exactly what a 1:4-split arf leaves behind. Stamping the minified id + /// (the pre-lane defect) flattened those footprints and mis-dequantized + /// scattered blocks frames later: 2 luma bytes of mandelbrot frame 35 + /// differed from the oracle, everything else exact. + /// + /// Both arms decode EVERY frame in decode order -- hidden arfs included + /// -- byte-exact against the instrumented oracle, and every SHOWN frame + /// pixel-exact against ffmpeg; the census counters prove the premise + /// (segmentation symbols read, a wider-than-zero quantizer span from + /// `SEG_LVL_ALT_Q`, and an inheritance-heavy shape). + #[test] + fn a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact"; + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc"); + return; + } + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + let extra = [ + "--cpu-used=4", + "--aq-mode=1", + "--cq-level=45", + "--lag-in-frames=16", + "--auto-alt-ref=1", + ]; + let arms: [(&str, &str, usize, usize); 2] = [ + ("screen testsrc2", "testsrc2", 256, 192), + ("film mandelbrot", "mandelbrot", 192, 128), + ]; + for (arm, source, width, height) in &arms { + let stream = encode_aomenc_stream(source, *width, *height, 40, &extra); + // Premise: the shape under test really arrived -- segmentation on + // every frame, the map both coded and inherited, and real ALT_Q + // tables. An aomenc drift that dropped any of these would make + // the decode below prove nothing (class gate-blind-to-feature). + let (enabled, umap, inherited, alt_q, _) = segmentation_feature_census(&stream); + eprintln!( + "{NAME} {arm}: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q-carrying {alt_q}" + ); + assert!( + enabled > 0 && umap > 0, + "{arm}: no segmentation-carrying/map-coding frame -- the premise is gone" + ); + assert!( + inherited > 0, + "{arm}: no update_map == 0 frame -- the map-inheritance path under test never runs" + ); + assert!( + alt_q > 0, + "{arm}: no frame carries a SEG_LVL_ALT_Q table -- the feature under test never fires" + ); + // Every frame in decode order -- hidden arfs included (each one + // re-surfaces via show-existing in this recipe, so `hidden == 0` + // is possible while `frames` still covers the whole coded set) -- + // byte-exact against the oracle. + let (frames, hidden) = decode_all_frames_vs_oracle(&stream, arm); + assert!(frames > 0, "{arm}: decoded nothing"); + assert_eq!( + frames, enabled, + "{arm}: decode-order frame count != segmentation-enabled frame count -- the \ + parse and the decode disagree about the stream" + ); + let _ = hidden; + // And every shown frame pixel-exact against ffmpeg. + crate::decode::reset_segment_hits(); + let pictures = decode_stream(&stream) + .unwrap_or_else(|e| panic!("{NAME} {arm}: decode refused: {e}")); + assert!( + crate::decode::segment_id_hits() > 0, + "{arm}: zero segment_id symbols read -- the decode proved nothing about \ + segmentation" + ); + let (lo, hi) = crate::decode::block_q_span(); + assert!( + hi > lo, + "{arm}: every block dequantized at the same qindex ({lo}) -- SEG_LVL_ALT_Q \ + never changed any block's quantizer" + ); + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, *width, *height, pictures.len()); + for (i, (ours, theirs)) in pictures.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(ours.y, theirs.y, "{NAME} {arm}: frame {i} luma vs ffmpeg"); + assert_eq!(ours.u, theirs.u, "{NAME} {arm}: frame {i} U vs ffmpeg"); + assert_eq!(ours.v, theirs.v, "{NAME} {arm}: frame {i} V vs ffmpeg"); + } + eprintln!( + "{NAME} {arm}: {frames} frames decode-order exact vs oracle ({hidden} hidden), {} shown frames exact vs ffmpeg, q span {lo}..{hi}, segment_id symbols {}", + pictures.len(), + crate::decode::segment_id_hits() + ); + } } /// lane-t900 r27, WITNESS half of the proof for "an OBMC neighbour whose