forge
Explore
Log in

Don't you dare go Hollow

Merge lane-av1-seglvl: SEG_LVL census (ALT_Q-only verdict over 162 lag/twopass frames), map-inheritance copy_segment_ids fix (verbatim per-cell copy + min as block id), witness streams byte/pixel-exact; reviewer PASS 0.95, vacuous aq2 lag16 census arm dropped

Browse files at this commit

c9d5815842f72109685d2f5ca1826405ab622fefAhmet Kaan GümüşParent: b943231d884467
crates/ec-av1/src/decode.rsmodified+33 -2
@@ -1089,6 +1089,27 @@ fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8,
1089 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));1089 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
1090 }1090 }
1091 1091
1092+/// `copy_segment_id` (libaom `decodemv.c:342`): the previous frame's map is
1093+/// inherited VERBATIM over this block's own mi footprint -- per-cell copies,
1094+/// not the minified id [`predicted_segment_id`] hands the block. Without a
1095+/// previous map the footprint is zeroed, exactly as the C NULL branch does.
1096+fn copy_segment_ids(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, fctx: &crate::decode::FrameCtx) {
1097+ let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1098+ let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
1099+ fctx.seg_ids.with(|m| {
1100+ let mut m = m.borrow_mut();
1101+ fctx.prev_seg_ids.with(|p| {
1102+ let p = p.borrow();
1103+ for y in 0..y_mis {
1104+ for x in 0..x_mis {
1105+ let idx = (mi_r + y) * mi_cols + mi_c + x;
1106+ m[idx] = p.get(idx).copied().unwrap_or(0);
1107+ }
1108+ }
1109+ });
1110+ });
1111+}
1112+
1092 /// `get_predicted_segment_id` (libaom `dec_get_segment_id` over1113 /// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
1093 /// `last_frame_seg_map`): the minimum previous-frame segment id over the1114 /// `last_frame_seg_map`): the minimum previous-frame segment id over the
1094 /// block's own mi footprint. `0` when there is no previous map.1115 /// block's own mi footprint. `0` when there is no previous map.
@@ -1230,9 +1251,19 @@ fn inter_segment_id(
1230 return;1251 return;
1231 }1252 }
1232 if !update_map {1253 if !update_map {
1233- // The map is inherited wholesale from the previous frame.1254+ // The map is inherited from the previous frame, and libaom's
1255+ // `copy_segment_id` (decodemv.c:342) does that VERBATIM -- a memcpy of
1256+ // the previous map over the block's own footprint, mixed ids intact --
1257+ // while the id the BLOCK itself carries is the min over that footprint
1258+ // (`get_predicted_segment_id`). Stamping the min here flattened mixed
1259+ // footprints into the saved map, and every later frame whose
1260+ // `update_map == 0` copy or temporal prediction read that position
1261+ // dequantized with the wrong segment's `SEG_LVL_ALT_Q` (class
1262+ // `simplified-inheritance`).
1263+ copy_segment_ids(mi_r, mi_c, w_mi, h_mi, fctx);
1234 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx);1264 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx);
1235- write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);1265+ fctx.cur_segment_id.with(|c| c.set(id));
1266+ SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
1236 return;1267 return;
1237 }1268 }
1238 if pre_skip && !pre_skip_frame {1269 if pre_skip && !pre_skip_frame {
crates/ec-av1/src/refusal_inventory.rsmodified+125 -34
@@ -407,10 +407,18 @@ const PROVEN: &[(&str, &str)] = &[
407 ),407 ),
408 // lane-t900 r27, negative gate + census: a written key frame carrying408 // lane-t900 r27, negative gate + census: a written key frame carrying
409 // each of the three mode-overriding features (over three segment ids) is409 // each of the three mode-overriding features (over three segment ids) is
410- // refused by name with no picture; and six real aomenc recipes410+ // refused by name with no picture; and real aomenc recipes never enable
411- // (`--aq-mode=1/2/3`, `--deltaq-mode=1`, plus a baseline for arrival)411+ // one. lane-av1seglvl re-scoped the census: beyond r27's six 1-pass
412- // never enable one -- only `--aq-mode=3` changes the stream at all, and412+ // no-lag recipes it now parses EVERY frame header's feature table over
413- // what it codes is `segment_id` symbols under `SEG_LVL_ALT_Q`.413+ // alt-ref-lag and genuine two-pass arms (`--aq-mode=1/2`, cq45 and the
414+ // branch's own high-q cq63, screen + film sources) -- the shapes that
415+ // reach `configure_static_seg_features`, the only setter of ALT_LF/
416+ // REF_FRAME/SKIP in the tree, which is gated on `hl_sf.static_segmentation`
417+ // ("Always set to 0", speed_features.h) and the second pass
418+ // (encoder_utils.c:738). What aomenc codes is `SEG_LVL_ALT_Q` tables and
419+ // `segment_id` symbols, and nothing else; the map-inheritance defect that
420+ // census surfaced (verbatim copy, decodemv.c:342) is fixed and witnessed
421+ // by `a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_ // pixel_exact`.
414 (422 (
415 "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)",423 "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)",
416 "a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name",424 "a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name",
@@ -589,7 +597,11 @@ mod tests {
589 .chain(REFUSALS)597 .chain(REFUSALS)
590 .map(|&s| s.to_owned())598 .map(|&s| s.to_owned())
591 .collect();599 .collect();
592- assert!(found.len() >= 30, "the refusal scan found only {} reasons -- it is broken, not the decoder", found.len());600+ assert!(
601+ found.len() >= 30,
602+ "the refusal scan found only {} reasons -- it is broken, not the decoder",
603+ found.len()
604+ );
593 605
594 let added: Vec<&String> = found.difference(&listed).collect();606 let added: Vec<&String> = found.difference(&listed).collect();
595 assert!(607 assert!(
@@ -635,9 +647,14 @@ mod tests {
635 let mut found: BTreeSet<String> = BTreeSet::new();647 let mut found: BTreeSet<String> = BTreeSet::new();
636 for (i, _) in src.match_indices("\"SKIP ") {648 for (i, _) in src.match_indices("\"SKIP ") {
637 let rest = &src[i + "\"SKIP ".len()..];649 let rest = &src[i + "\"SKIP ".len()..];
638- let Some(colon) = rest.find(':') else { continue };650+ let Some(colon) = rest.find(':') else {
651+ continue;
652+ };
639 let name = &rest[..colon];653 let name = &rest[..colon];
640- if !name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') {654+ if !name
655+ .chars()
656+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
657+ {
641 continue;658 continue;
642 }659 }
643 // The tail of the message says what was skipped. Only "{e}" -- the660 // The tail of the message says what was skipped. Only "{e}" -- the
@@ -650,7 +667,10 @@ mod tests {
650 }667 }
651 }668 }
652 let listed: BTreeSet<&str> = GATES_THAT_SKIP_ON_A_DECODE_ERROR.iter().copied().collect();669 let listed: BTreeSet<&str> = GATES_THAT_SKIP_ON_A_DECODE_ERROR.iter().copied().collect();
653- let added: Vec<&String> = found.iter().filter(|n| !listed.contains(n.as_str())).collect();670+ let added: Vec<&String> = found
671+ .iter()
672+ .filter(|n| !listed.contains(n.as_str()))
673+ .collect();
654 assert!(674 assert!(
655 added.is_empty(),675 added.is_empty(),
656 "these gates turn a decode error into a printed SKIP and are not declared: \676 "these gates turn a decode error into a printed SKIP and are not declared: \
@@ -723,9 +743,18 @@ mod tests {
723 fn every_partition_value_of_an_enumerated_alphabet_has_an_arm() {743 fn every_partition_value_of_an_enumerated_alphabet_has_an_arm() {
724 // (the refusal in the fallback arm, the alphabet its CDF codes)744 // (the refusal in the fallback arm, the alphabet its CDF codes)
725 let blocks: [(&str, usize); 4] = [745 let blocks: [(&str, usize); 4] = [
726- ("a 32x32 partition type this decoder does not code", crate::cdf::PARTITION_W32[0].len() - 1),746+ (
727- ("an INTER 32x32 partition type this decoder does not code", crate::cdf::PARTITION_W32[0].len() - 1),747+ "a 32x32 partition type this decoder does not code",
728- ("a 128x128 superblock partition value outside the 8-symbol alphabet", crate::cdf::PARTITION_W128[0].len() - 1),748+ crate::cdf::PARTITION_W32[0].len() - 1,
749+ ),
750+ (
751+ "an INTER 32x32 partition type this decoder does not code",
752+ crate::cdf::PARTITION_W32[0].len() - 1,
753+ ),
754+ (
755+ "a 128x128 superblock partition value outside the 8-symbol alphabet",
756+ crate::cdf::PARTITION_W128[0].len() - 1,
757+ ),
729 // lane-t900 r24: the key-frame superblock root. Its `part` is758 // lane-t900 r24: the key-frame superblock root. Its `part` is
730 // either a `partition_w64` symbol or, at a frame edge, one of the759 // either a `partition_w64` symbol or, at a frame edge, one of the
731 // three gathered outcomes (PARTITION_HORZ, PARTITION_VERT,760 // three gathered outcomes (PARTITION_HORZ, PARTITION_VERT,
@@ -779,7 +808,10 @@ mod tests {
779 "the `match` at decode.rs:{} refuses {reason:?} but has no arm for {:?} -- that \808 "the `match` at decode.rs:{} refuses {reason:?} but has no arm for {:?} -- that \
780 is a real gap in its {alphabet}-value alphabet, not a dead refusal",809 is a real gap in its {alphabet}-value alphabet, not a dead refusal",
781 i + 1,810 i + 1,
782- missing.iter().map(|v| PARTITION_NAMES[*v]).collect::<Vec<_>>()811+ missing
812+ .iter()
813+ .map(|v| PARTITION_NAMES[*v])
814+ .collect::<Vec<_>>()
783 );815 );
784 }816 }
785 assert_eq!(817 assert_eq!(
@@ -833,7 +865,11 @@ mod tests {
833 .next()865 .next()
834 .unwrap_or("")866 .unwrap_or("")
835 .to_owned();867 .to_owned();
836- assert!(!var.is_empty(), "the chain at decode.rs:{} tests nothing", head + 1);868+ assert!(
869+ !var.is_empty(),
870+ "the chain at decode.rs:{} tests nothing",
871+ head + 1
872+ );
837 873
838 // Walk up collecting every branch head of this chain, each read to874 // Walk up collecting every branch head of this chain, each read to
839 // the line that opens its body.875 // the line that opens its body.
@@ -843,7 +879,8 @@ mod tests {
843 loop {879 loop {
844 i -= 1;880 i -= 1;
845 let t = lines[i].trim_start();881 let t = lines[i].trim_start();
846- if indent(lines[i]) != outer || !(t.starts_with("} else if ") || t.starts_with("if "))882+ if indent(lines[i]) != outer
883+ || !(t.starts_with("} else if ") || t.starts_with("if "))
847 {884 {
848 if i == 0 {885 if i == 0 {
849 break;886 break;
@@ -893,7 +930,10 @@ mod tests {
893 "the chain at decode.rs:{} refuses {reason:?} but no branch names {:?} -- that \930 "the chain at decode.rs:{} refuses {reason:?} but no branch names {:?} -- that \
894 is a real gap in its {alphabet}-value alphabet, not a dead refusal",931 is a real gap in its {alphabet}-value alphabet, not a dead refusal",
895 head + 1,932 head + 1,
896- missing.iter().map(|v| PARTITION_NAMES[*v]).collect::<Vec<_>>()933+ missing
934+ .iter()
935+ .map(|v| PARTITION_NAMES[*v])
936+ .collect::<Vec<_>>()
897 );937 );
898 }938 }
899 assert_eq!(found, chains.len());939 assert_eq!(found, chains.len());
@@ -996,11 +1036,18 @@ mod tests {
996 values.insert(((1u64 << length) - 2) as u32);1036 values.insert(((1u64 << length) - 2) as u32);
997 }1037 }
998 let max = *values.iter().max().unwrap();1038 let max = *values.iter().max().unwrap();
999- assert_eq!(max, (1u32 << 20) - 2, "the enumeration misses the spec's own ceiling");1039+ assert_eq!(
1040+ max,
1041+ (1u32 << 20) - 2,
1042+ "the enumeration misses the spec's own ceiling"
1043+ );
1000 // A coefficient is masked to 20 bits (spec 5.11.39), and the base and1044 // A coefficient is masked to 20 bits (spec 5.11.39), and the base and
1001 // base-range syntax contribute at most 15 of that before the tail, so1045 // base-range syntax contribute at most 15 of that before the tail, so
1002 // this is the largest tail a legal coefficient can need.1046 // this is the largest tail a legal coefficient can need.
1003- assert!(max >= 0xF_FFFF - 15, "the ceiling is below the largest legal tail");1047+ assert!(
1048+ max >= 0xF_FFFF - 15,
1049+ "the ceiling is below the largest legal tail"
1050+ );
1004 for value in values {1051 for value in values {
1005 match roundtrip(value) {1052 match roundtrip(value) {
1006 Ok(read) => assert_eq!(read, value, "the Golomb tail {value} read back as {read}"),1053 Ok(read) => assert_eq!(read, value, "the Golomb tail {value} read back as {read}"),
@@ -1056,7 +1103,11 @@ mod tests {
1056 ];1103 ];
1057 assert_eq!(alphabets[0].1, 13, "the y_mode alphabet changed size");1104 assert_eq!(alphabets[0].1, 13, "the y_mode alphabet changed size");
1058 for group in &crate::cdf::Y_MODE {1105 for group in &crate::cdf::Y_MODE {
1059- assert_eq!(group.len() - 1, alphabets[0].1, "the y_mode rows disagree on width");1106+ assert_eq!(
1107+ group.len() - 1,
1108+ alphabets[0].1,
1109+ "the y_mode rows disagree on width"
1110+ );
1060 }1111 }
1061 1112
1062 let src = include_str!("decode.rs");1113 let src = include_str!("decode.rs");
@@ -1064,12 +1115,17 @@ mod tests {
1064 let mut sites = 0usize;1115 let mut sites = 0usize;
1065 for (i, line) in lines.iter().enumerate() {1116 for (i, line) in lines.iter().enumerate() {
1066 let t = line.trim();1117 let t = line.trim();
1067- let Some(rest) = t.strip_prefix("if mode >= ") else { continue };1118+ let Some(rest) = t.strip_prefix("if mode >= ") else {
1119+ continue;
1120+ };
1068 let Some(threshold) = rest.trim_end_matches(" {").parse::<usize>().ok() else {1121 let Some(threshold) = rest.trim_end_matches(" {").parse::<usize>().ok() else {
1069 continue;1122 continue;
1070 };1123 };
1071 // Only the guards carrying THIS refusal.1124 // Only the guards carrying THIS refusal.
1072- if !lines[i..(i + 4).min(lines.len())].join("\n").contains(REFUSAL) {1125+ if !lines[i..(i + 4).min(lines.len())]
1126+ .join("\n")
1127+ .contains(REFUSAL)
1128+ {
1073 continue;1129 continue;
1074 }1130 }
1075 sites += 1;1131 sites += 1;
@@ -1099,7 +1155,10 @@ mod tests {
1099 i + 11155 i + 1
1100 );1156 );
1101 }1157 }
1102- assert_eq!(sites, 3, "the intra-mode guard is at three sites, found {sites}");1158+ assert_eq!(
1159+ sites, 3,
1160+ "the intra-mode guard is at three sites, found {sites}"
1161+ );
1103 }1162 }
1104 1163
1105 /// lane-t900 r31, ENUMERATION for "a HORZ/VERT intra strip in a1164 /// lane-t900 r31, ENUMERATION for "a HORZ/VERT intra strip in a
@@ -1159,7 +1218,10 @@ mod tests {
1159 }1218 }
1160 }1219 }
1161 }1220 }
1162- assert!(with_128 > 0, "enumeration is vacuous -- no 128-sided footprint was tried");1221+ assert!(
1222+ with_128 > 0,
1223+ "enumeration is vacuous -- no 128-sided footprint was tried"
1224+ );
1163 assert_eq!(1225 assert_eq!(
1164 allowed_at_128, 0,1226 allowed_at_128, 0,
1165 "a footprint with a 128-pixel side passed av1_allow_palette's bound -- the \1227 "a footprint with a 128-pixel side passed av1_allow_palette's bound -- the \
@@ -1271,11 +1333,17 @@ mod tests {
1271 // (3) The two tables, read out of decode_rect_split's own text: every1333 // (3) The two tables, read out of decode_rect_split's own text: every
1272 // `(w, h) =>` / `(w, h) |` match arm head between the table's `let`1334 // `(w, h) =>` / `(w, h) |` match arm head between the table's `let`
1273 // and the guard that follows it.1335 // and the guard that follows it.
1274- let body_at = src.find("fn decode_rect_split(").expect("decode_rect_split is gone");1336+ let body_at = src
1337+ .find("fn decode_rect_split(")
1338+ .expect("decode_rect_split is gone");
1275 let body = &src[body_at..];1339 let body = &src[body_at..];
1276 let slice = |from: &str, to: &str| -> &str {1340 let slice = |from: &str, to: &str| -> &str {
1277- let a = body.find(from).unwrap_or_else(|| panic!("{from:?} is gone from decode_rect_split"));1341+ let a = body
1278- let b = body[a..].find(to).unwrap_or_else(|| panic!("{to:?} is gone from decode_rect_split"));1342+ .find(from)
1343+ .unwrap_or_else(|| panic!("{from:?} is gone from decode_rect_split"));
1344+ let b = body[a..]
1345+ .find(to)
1346+ .unwrap_or_else(|| panic!("{to:?} is gone from decode_rect_split"));
1279 &body[a..a + b]1347 &body[a..a + b]
1280 };1348 };
1281 let arm_shapes = |text: &str| -> BTreeSet<(usize, usize)> {1349 let arm_shapes = |text: &str| -> BTreeSet<(usize, usize)> {
@@ -1348,7 +1416,10 @@ mod tests {
1348 }1416 }
1349 }1417 }
1350 }1418 }
1351- assert_eq!(checked, 40, "the strip domain is not the ten rect shapes x four depths");1419+ assert_eq!(
1420+ checked, 40,
1421+ "the strip domain is not the ten rect shapes x four depths"
1422+ );
1352 }1423 }
1353 1424
1354 /// lane-t900 r33, ENUMERATION for "CfL, filter intra or a palette on a1425 /// lane-t900 r33, ENUMERATION for "CfL, filter intra or a palette on a
@@ -1458,9 +1529,15 @@ mod tests {
1458 }1529 }
1459 continue;1530 continue;
1460 }1531 }
1461- let Some(rest) = line.strip_prefix('(') else { continue };1532+ let Some(rest) = line.strip_prefix('(') else {
1462- let Some((pair, _)) = rest.split_once(") =>") else { continue };1533+ continue;
1463- let Some((a, b)) = pair.split_once(',') else { continue };1534+ };
1535+ let Some((pair, _)) = rest.split_once(") =>") else {
1536+ continue;
1537+ };
1538+ let Some((a, b)) = pair.split_once(',') else {
1539+ continue;
1540+ };
1464 let bw: usize = a.trim().parse().expect("arm bw");1541 let bw: usize = a.trim().parse().expect("arm bw");
1465 let bh: usize = b.trim().parse().expect("arm bh");1542 let bh: usize = b.trim().parse().expect("arm bh");
1466 assert!(1543 assert!(
@@ -1472,9 +1549,18 @@ mod tests {
1472 seen.push((bw, bh));1549 seen.push((bw, bh));
1473 arms += 1;1550 arms += 1;
1474 }1551 }
1475- assert!(arms >= 10, "only {arms} arms parsed -- the table's shape changed");1552+ assert!(
1476- assert!(saw_none_fallback, "filter_intra_size_class_rect lost its `_ => None` fallback");1553+ arms >= 10,
1477- assert!(saw_square_delegate, "filter_intra_size_class_rect lost its square-delegate arm");1554+ "only {arms} arms parsed -- the table's shape changed"
1555+ );
1556+ assert!(
1557+ saw_none_fallback,
1558+ "filter_intra_size_class_rect lost its `_ => None` fallback"
1559+ );
1560+ assert!(
1561+ saw_square_delegate,
1562+ "filter_intra_size_class_rect lost its square-delegate arm"
1563+ );
1478 // The guard arm delegates square strips to `filter_intra_size_class`;1564 // The guard arm delegates square strips to `filter_intra_size_class`;
1479 // drive the delegate directly, so a widening there turns THIS test red1565 // drive the delegate directly, so a widening there turns THIS test red
1480 // (the numeric walk never reaches the guard arm).1566 // (the numeric walk never reaches the guard arm).
@@ -1524,7 +1610,10 @@ mod tests {
1524 );1610 );
1525 }1611 }
1526 }1612 }
1527- assert_eq!(sites, 8, "the call-site audit found {sites} sites, not the 8 it enumerated");1613+ assert_eq!(
1614+ sites, 8,
1615+ "the call-site audit found {sites} sites, not the 8 it enumerated"
1616+ );
1528 }1617 }
1529 1618
1530 /// Every entry of [`PROVEN`] must still name a live refusal and a test1619 /// Every entry of [`PROVEN`] must still name a live refusal and a test
@@ -1543,7 +1632,9 @@ mod tests {
1543 "{reason:?} is listed as proven but is no longer a decode-path refusal -- drop it from PROVEN (the capability landed) or fix the string"1632 "{reason:?} is listed as proven but is no longer a decode-path refusal -- drop it from PROVEN (the capability landed) or fix the string"
1544 );1633 );
1545 assert!(1634 assert!(
1546- sources.iter().any(|src| src.contains(&format!("fn {gate}("))),1635+ sources
1636+ .iter()
1637+ .any(|src| src.contains(&format!("fn {gate}("))),
1547 "{reason:?} names the proving test {gate}, which exists in neither stream.rs \1638 "{reason:?} names the proving test {gate}, which exists in neither stream.rs \
1548 nor decode.rs"1639 nor decode.rs"
1549 );1640 );
crates/ec-av1/src/stream.rsmodified+413 -9
@@ -19,6 +19,11 @@ use ec_av1_syntax::{
19 Av1Parser, FrameHeader, FrameType, MAX_SEGMENTS, NUM_REF_FRAMES, ObuKind, PRIMARY_REF_NONE,19 Av1Parser, FrameHeader, FrameType, MAX_SEGMENTS, NUM_REF_FRAMES, ObuKind, PRIMARY_REF_NONE,
20 SEG_LVL_GLOBALMV, SEG_LVL_REF_FRAME, SEG_LVL_SKIP, Tile, TxMode,20 SEG_LVL_GLOBALMV, SEG_LVL_REF_FRAME, SEG_LVL_SKIP, Tile, TxMode,
21 };21 };
22+// Census-only: read outside `mod tests` only in comments; the non-test lib
23+// target never touches them, so they ride in behind cfg(test) (via the test
24+// module's `use super::*`).
25+#[cfg(test)]
26+use ec_av1_syntax::{SEG_LVL_ALT_Q, SEG_LVL_MAX};
22 use ec_core::{Error, Result};27 use ec_core::{Error, Result};
23 28
24 use crate::cdf_state::Cdfs;29 use crate::cdf_state::Cdfs;
@@ -851,7 +856,9 @@ pub fn decode_stream_with_threads(
851 // symbols `decode_inter_block` unconditionally reads) -- have no856 // symbols `decode_inter_block` unconditionally reads) -- have no
852 // reader on the inter path, so they still refuse by name rather than857 // reader on the inter path, so they still refuse by name rather than
853 // desyncing. aomenc's `--aq-mode` segmentation only ever sets858 // desyncing. aomenc's `--aq-mode` segmentation only ever sets
854- // `SEG_LVL_ALT_Q`.859+ // `SEG_LVL_ALT_Q` (census gate
860+ // `a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature`:
861+ // 1-pass, alt-ref-lag and two-pass arms, every frame header parsed).
855 let tile_bufs: Vec<&[u8]> = tiles862 let tile_bufs: Vec<&[u8]> = tiles
856 .iter()863 .iter()
857 .map(|t| {864 .map(|t| {
@@ -1432,14 +1439,20 @@ fn decode_frame(
1432 // SEG_LVL_GLOBALMV, `:1071` in `read_ref_frames`, `:1350` in1439 // SEG_LVL_GLOBALMV, `:1071` in `read_ref_frames`, `:1350` in
1433 // `read_is_inter_block`), so a conformant stream CAN carry them and1440 // `read_is_inter_block`), so a conformant stream CAN carry them and
1434 // this is a capability gap, not a spec-conformant guard. Reachability1441 // this is a capability gap, not a spec-conformant guard. Reachability
1435- // from `aomenc` is nil -- its AQ modes set `SEG_LVL_ALT_Q` only1442+ // from `aomenc` is nil, for three independent reasons (lane-av1seglvl
1436- // (`aq_variance.c:89`, `aq_complexity.c:118`, `aq_cyclicrefresh.c:630`)1443+ // census): the AQ modules clear the table then set `SEG_LVL_ALT_Q`
1437- // and the mode-overriding features come only from the library API1444+ // only (`aq_variance.c:61` clear + `:89` enable, `aq_complexity.c:74`
1438- // (`av1_apply_roi_map` `encoder_utils.c:515`, `av1_apply_active_map`1445+ // + `:118`, `aq_cyclicrefresh.c:616` + `:630`); the one other setter,
1439- // `encoder_utils.c:557`, the alt-ref overlap case `:401-413`); the CLI1446+ // `configure_static_seg_features` (`encoder_utils.c:315`, which would
1440- // exposes no ROI/active-map flag (checked). Kept as a named gap: the1447+ // set ALT_LF/REF_FRAME/SKIP around alt-ref groups), is gated on
1441- // lift is an INTER-block-path change (ref/skip/mode selection) outside1448+ // `hl_sf.static_segmentation` -- a speed feature libaom's own
1442- // this lane's region. See `lanes/av1hdr.report.md` §4.1.1449+ // `speed_features.h` documents as "Always set to 0" -- AND on the
1450+ // second pass of a two-pass encode (`encoder_utils.c:738`); and
1451+ // ROI/active-map maps are control-API only (`av1_apply_roi_map`,
1452+ // `av1_apply_active_map`: the CLI exposes no flag for either). Kept as
1453+ // a named gap: the lift is an INTER-block-path change (ref/skip/mode
1454+ // selection) outside this lane's region. See `lanes/av1hdr.report.md`
1455+ // §4.1 and `lanes/av1seglvl.report.md`.
1443 for segment in 0..MAX_SEGMENTS {1456 for segment in 0..MAX_SEGMENTS {
1444 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {1457 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
1445 if header.segmentation.feature_enabled[segment][feature] {1458 if header.segmentation.feature_enabled[segment][feature] {
@@ -2500,6 +2513,163 @@ pub(crate) mod tests {
2500 (stream.len(), result)2513 (stream.len(), result)
2501 }2514 }
2502 2515
2516+ /// lane-av1seglvl: encode `frames` frames of `source` with real aomenc
2517+ /// plus `extra` args and return the raw `.obu` bytes -- the census's
2518+ /// half-sibling of [`census_attempt`] that keeps the STREAM instead of
2519+ /// only its decode verdict, so the caller can parse the frame headers'
2520+ /// segmentation tables themselves.
2521+ fn encode_aomenc_stream(
2522+ source: &str,
2523+ width: usize,
2524+ height: usize,
2525+ frames: usize,
2526+ extra: &[&str],
2527+ ) -> Vec<u8> {
2528+ let duration = format!("{}", frames as f64 / 25.0);
2529+ let src = format!("{source}=size={width}x{height}:rate=25");
2530+ let y4m = Command::new("ffmpeg")
2531+ .args([
2532+ "-v", "error", "-f", "lavfi", "-i", &src, "-t", &duration, "-pix_fmt", "yuv420p",
2533+ "-strict", "-1", "-f", "yuv4mpegpipe", "-",
2534+ ])
2535+ .stdin(Stdio::null())
2536+ .stdout(Stdio::piped())
2537+ .stderr(Stdio::piped())
2538+ .output()
2539+ .expect("ffmpeg failed to run");
2540+ assert!(y4m.status.success(), "ffmpeg refused the {width}x{height} fixture");
2541+ let limit = format!("--limit={frames}");
2542+ let mut args: Vec<String> = [
2543+ "--codec=av1",
2544+ "--passes=1",
2545+ "--end-usage=q",
2546+ "--threads=1",
2547+ "--row-mt=0",
2548+ "--kf-max-dist=9999",
2549+ "--lag-in-frames=0",
2550+ ]
2551+ .iter()
2552+ .map(|s| (*s).to_owned())
2553+ .collect();
2554+ args.push(limit);
2555+ args.extend(extra.iter().map(|s| (*s).to_owned()));
2556+ args.extend(["--obu".to_owned(), "-o".to_owned(), "-".to_owned(), "-".to_owned()]);
2557+ let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2558+ assert!(out.status.success(), "aomenc refused {args:?}: {}", String::from_utf8_lossy(&out.stderr));
2559+ out.stdout
2560+ }
2561+
2562+ /// lane-av1seglvl: encode `frames` frames with a real TWO-PASS aomenc
2563+ /// (pass 1 writes the stats file into the session temp dir, pass 2
2564+ /// consumes it) and return the `.obu` bytes. This is the only shape that
2565+ /// reaches libaom's `is_stat_consumption_stage_twopass` segmentation
2566+ /// setup (`configure_static_seg_features`), so the census is not proven
2567+ /// over the encoder's whole reachable surface without it.
2568+ fn encode_aomenc_stream_twopass(
2569+ source: &str,
2570+ width: usize,
2571+ height: usize,
2572+ frames: usize,
2573+ extra: &[&str],
2574+ ) -> Vec<u8> {
2575+ let duration = format!("{}", frames as f64 / 25.0);
2576+ let src = format!("{source}=size={width}x{height}:rate=25");
2577+ let y4m = Command::new("ffmpeg")
2578+ .args([
2579+ "-v", "error", "-f", "lavfi", "-i", &src, "-t", &duration, "-pix_fmt", "yuv420p",
2580+ "-strict", "-1", "-f", "yuv4mpegpipe", "-",
2581+ ])
2582+ .stdin(Stdio::null())
2583+ .stdout(Stdio::piped())
2584+ .stderr(Stdio::piped())
2585+ .output()
2586+ .expect("ffmpeg failed to run");
2587+ assert!(y4m.status.success(), "ffmpeg refused the {width}x{height} fixture");
2588+ let limit = format!("--limit={frames}");
2589+ let fpf = std::env::temp_dir().join(format!("ec-av1-segldapass-{}.fpf", std::process::id()));
2590+ let mut base: Vec<String> = [
2591+ "--codec=av1",
2592+ "--passes=2",
2593+ "--end-usage=q",
2594+ "--threads=1",
2595+ "--row-mt=0",
2596+ "--kf-max-dist=9999",
2597+ "--lag-in-frames=0",
2598+ ]
2599+ .iter()
2600+ .map(|s| (*s).to_owned())
2601+ .collect();
2602+ base.push(limit);
2603+ base.extend(extra.iter().map(|s| (*s).to_owned()));
2604+ let mut pass1 = base.clone();
2605+ pass1.extend(["--pass=1".to_owned(), format!("--fpf={}", fpf.display())]);
2606+ pass1.extend(["--obu".to_owned(), "-o".to_owned(), "/dev/null".to_owned(), "-".to_owned()]);
2607+ let out1 = run_with_stdin(Command::new(aomenc_path()).args(&pass1), &y4m.stdout);
2608+ assert!(out1.status.success(), "aomenc pass 1 refused {pass1:?}: {}", String::from_utf8_lossy(&out1.stderr));
2609+ let mut pass2 = base;
2610+ pass2.extend(["--pass=2".to_owned(), format!("--fpf={}", fpf.display())]);
2611+ pass2.extend(["--obu".to_owned(), "-o".to_owned(), "-".to_owned(), "-".to_owned()]);
2612+ let out2 = run_with_stdin(Command::new(aomenc_path()).args(&pass2), &y4m.stdout);
2613+ let _ = std::fs::remove_file(&fpf);
2614+ assert!(out2.status.success(), "aomenc pass 2 refused {pass2:?}: {}", String::from_utf8_lossy(&out2.stderr));
2615+ out2.stdout
2616+ }
2617+
2618+ /// lane-av1seglvl: walk every frame OBU of `stream` and tally which
2619+ /// `SEG_LVL` features the frame headers actually ENABLE, plus the shape
2620+ /// counters a census premise is asserted against: frames with
2621+ /// segmentation on, of which `update_map == 1` (the map is coded) and
2622+ /// `update_map == 0` (every block's id is INHERITED), and frames whose
2623+ /// table carries a real `SEG_LVL_ALT_Q` delta.
2624+ /// The last vector counts per SEGMENT-FEATURE INSTANCE (a frame with
2625+ /// ALT_Q on all 8 segments contributes 8), which is all the verdict
2626+ /// needs: only index `SEG_LVL_ALT_Q` may be non-zero.
2627+ /// Returns `(enabled_frames, update_map_frames, inherited_frames,
2628+ /// alt_q_frames, feature_instances: [usize; SEG_LVL_MAX])`.
2629+ #[allow(clippy::type_complexity)]
2630+ fn segmentation_feature_census(
2631+ stream: &[u8],
2632+ ) -> (usize, usize, usize, usize, [usize; SEG_LVL_MAX]) {
2633+ let mut parser = Av1Parser::new();
2634+ let obus = parser
2635+ .parse_temporal_unit(stream)
2636+ .unwrap_or_else(|e| panic!("the census stream does not even parse: {e}"));
2637+ let mut enabled = 0usize;
2638+ let mut update_map = 0usize;
2639+ let mut inherited = 0usize;
2640+ let mut alt_q = 0usize;
2641+ let mut feature_frames = [0usize; SEG_LVL_MAX];
2642+ for obu in &obus {
2643+ if let ObuKind::Frame(header, _) = &obu.kind {
2644+ let seg = &header.segmentation;
2645+ if !seg.enabled {
2646+ continue;
2647+ }
2648+ enabled += 1;
2649+ if seg.update_map {
2650+ update_map += 1;
2651+ } else {
2652+ inherited += 1;
2653+ }
2654+ let mut any_q = false;
2655+ for segment in 0..MAX_SEGMENTS {
2656+ for feature in 0..SEG_LVL_MAX {
2657+ if seg.feature_enabled[segment][feature] {
2658+ feature_frames[feature] += 1;
2659+ if feature == SEG_LVL_ALT_Q {
2660+ any_q = true;
2661+ }
2662+ }
2663+ }
2664+ }
2665+ if any_q {
2666+ alt_q += 1;
2667+ }
2668+ }
2669+ }
2670+ (enabled, update_map, inherited, alt_q, feature_frames)
2671+ }
2672+
2503 /// lane-hdrlossless: WITNESS for the one refusal the pilot report left2673 /// lane-hdrlossless: WITNESS for the one refusal the pilot report left
2504 /// without a proving test -- "a frame mixing lossless and lossy2674 /// without a proving test -- "a frame mixing lossless and lossy
2505 /// segments". It is a REAL encoder output, not a defensive pin:2675 /// segments". It is a REAL encoder output, not a defensive pin:
@@ -2633,6 +2803,16 @@ pub(crate) mod tests {
2633 /// `--aq-mode=1/2/3` (variance, complexity and cyclic-refresh AQ) and2803 /// `--aq-mode=1/2/3` (variance, complexity and cyclic-refresh AQ) and
2634 /// `--deltaq-mode=1` -- with the refusal as the instrument: if one of2804 /// `--deltaq-mode=1` -- with the refusal as the instrument: if one of
2635 /// those features appeared, the decode would stop by name.2805 /// those features appeared, the decode would stop by name.
2806+ ///
2807+ /// lane-av1seglvl re-scope: r27's arms were all `--passes=1
2808+ /// --lag-in-frames=0`, so they never coded an alt-ref frame or ran an
2809+ /// encoder second pass -- the only shapes where libaom's OTHER seg
2810+ /// feature setup (`configure_static_seg_features`) could ever run. The
2811+ /// re-scoped half below adds alt-ref-group arms and a real two-pass arm,
2812+ /// and upgrades the instrument from the refusal (blind to a pure-ALT_LF
2813+ /// stream) to a direct parse of every frame header's `feature_enabled`
2814+ /// table: over all of it, aomenc enables `SEG_LVL_ALT_Q` and nothing
2815+ /// else.
2636 #[test]2816 #[test]
2637 fn a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature() {2817 fn a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature() {
2638 if !have_aomenc() {2818 if !have_aomenc() {
@@ -2700,6 +2880,230 @@ pub(crate) mod tests {
2700 "no recipe coded a single segment_id symbol -- segmentation never arrived, so \2880 "no recipe coded a single segment_id symbol -- segmentation never arrived, so \
2701 this census measures nothing about the three mode-overriding features"2881 this census measures nothing about the three mode-overriding features"
2702 );2882 );
2883+
2884+ // lane-av1seglvl re-scope: the r27 arms above are all `--passes=1
2885+ // --lag-in-frames=0`, which never codes an alt-ref frame -- the one
2886+ // frame type whose segmentation libaom sets up differently
2887+ // (`configure_static_seg_features`, encoder_utils.c:738, is further
2888+ // gated on the second pass AND on `hl_sf.static_segmentation`, which
2889+ // speed_features.h itself documents as "Always set to 0"). The arms
2890+ // below cover that whole remaining surface: alt-ref groups under
2891+ // `--aq-mode`, a high-cq arm (the branch's own `high_q` gate is
2892+ // `avg_q > 48`), and a genuine two-pass encode. The instrument is no
2893+ // longer the refusal -- the refusal only fires on
2894+ // REF_FRAME/SKIP/GLOBALMV, so an ALT_LF-only stream would decode
2895+ // silently past it -- but a direct parse of every frame header's
2896+ // `feature_enabled` table.
2897+ let lag_recipes: [(&str, &str, usize, usize, Vec<&str>); 3] = [
2898+ (
2899+ "aq-mode=1 lag16 mandelbrot",
2900+ "mandelbrot",
2901+ 192,
2902+ 128,
2903+ vec!["--cpu-used=4", "--aq-mode=1", "--cq-level=45", "--lag-in-frames=16", "--auto-alt-ref=1"],
2904+ ),
2905+ (
2906+ "aq-mode=1 lag16 screen",
2907+ "testsrc2",
2908+ 256,
2909+ 192,
2910+ vec!["--cpu-used=4", "--aq-mode=1", "--cq-level=45", "--lag-in-frames=16", "--auto-alt-ref=1"],
2911+ ),
2912+ (
2913+ "aq-mode=1 lag16 cq63 high_q",
2914+ "mandelbrot",
2915+ 192,
2916+ 128,
2917+ vec!["--cpu-used=4", "--aq-mode=1", "--cq-level=63", "--lag-in-frames=16", "--auto-alt-ref=1"],
2918+ ),
2919+ // `--aq-mode=2 lag16` (complexity AQ over an alt-ref group) was
2920+ // measured 2026-09-24: it encodes and decodes cleanly but codes
2921+ // ZERO segmentation-enabled frames -- complexity AQ never reaches
2922+ // the seg table at this recipe -- so as a census arm it measures
2923+ // nothing (class gate-blind-to-feature) and was dropped; the
2924+ // 1-pass `aq-mode=2` r27 arm above stays.
2925+ ];
2926+ let mut total_enabled = 0usize;
2927+ let mut total_inherited = 0usize;
2928+ let mut total_alt_q = 0usize;
2929+ let mut feature_frames = [0usize; SEG_LVL_MAX];
2930+ for (name, source, w, h, extra) in &lag_recipes {
2931+ let stream = encode_aomenc_stream(source, *w, *h, 40, extra);
2932+ let (enabled, umap, inherited, alt_q, frames_per_feature) =
2933+ segmentation_feature_census(&stream);
2934+ eprintln!(
2935+ "SEGCENSUS {name}: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q {alt_q}, per-feature {frames_per_feature:?}"
2936+ );
2937+ total_enabled += enabled;
2938+ total_inherited += inherited;
2939+ total_alt_q += alt_q;
2940+ for (f, n) in frames_per_feature.iter().enumerate() {
2941+ feature_frames[f] += n;
2942+ }
2943+ }
2944+ // The two-pass arm: `configure_static_seg_features` runs ONLY at
2945+ // `is_stat_consumption_stage_twopass`, so this is the arm that would
2946+ // catch its ALT_LF/REF_FRAME/SKIP tables if the dead speed feature
2947+ // were ever revived.
2948+ {
2949+ let stream = encode_aomenc_stream_twopass(
2950+ "mandelbrot",
2951+ 192,
2952+ 128,
2953+ 40,
2954+ &["--cpu-used=4", "--aq-mode=1", "--cq-level=45", "--lag-in-frames=16", "--auto-alt-ref=1"],
2955+ );
2956+ let (enabled, umap, inherited, alt_q, frames_per_feature) =
2957+ segmentation_feature_census(&stream);
2958+ eprintln!(
2959+ "SEGCENSUS twopass aq-mode=1 lag16: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q {alt_q}, per-feature {frames_per_feature:?}"
2960+ );
2961+ total_enabled += enabled;
2962+ total_inherited += inherited;
2963+ total_alt_q += alt_q;
2964+ for (f, n) in frames_per_feature.iter().enumerate() {
2965+ feature_frames[f] += n;
2966+ }
2967+ }
2968+ // Premise (class gate-blind-to-feature): the arms must actually reach
2969+ // the shapes the census speaks about -- segmentation-carrying frames,
2970+ // frames whose map is INHERITED (update_map == 0), and frames with a
2971+ // real ALT_Q table -- or the "only ALT_Q" verdict below measures
2972+ // nothing.
2973+ assert!(
2974+ total_enabled > 0 && total_alt_q > 0,
2975+ "no lag/two-pass arm carried a segmentation-enabled frame -- the census premise \
2976+ never arrived"
2977+ );
2978+ assert!(
2979+ total_inherited > 0,
2980+ "no arm carried an update_map == 0 frame -- the map-inheritance path the decoder \
2981+ reads segment ids through is unmeasured"
2982+ );
2983+ // The census verdict, over every frame of every arm: segmentation on
2984+ // aomenc's CLI carries SEG_LVL_ALT_Q and NOTHING else. The three
2985+ // mode-overriding features and the four ALT_LF deltas have no encoder
2986+ // path: `configure_static_seg_features` (the only setter of ALT_LF/
2987+ // REF_FRAME/SKIP in the tree) is gated on `hl_sf.static_segmentation`,
2988+ // documented "Always set to 0" (speed_features.h), and ROI/active-map
2989+ // are control-API only (aomenc.c has no flag for either).
2990+ for (feature, frames) in feature_frames.iter().enumerate() {
2991+ if feature == SEG_LVL_ALT_Q {
2992+ continue;
2993+ }
2994+ assert_eq!(
2995+ *frames, 0,
2996+ "feature index {feature} appeared on {frames} frames of real aomenc output -- \
2997+ the refusal's encoder-never-writes claim is FALSE and the mode path needs \
2998+ porting before this census can stay green"
2999+ );
3000+ }
3001+ eprintln!(
3002+ "SEGCENSUS lag/twopass: {total_enabled} seg-enabled frames over 4 arms, {total_inherited} inherited-map frames, {total_alt_q} with ALT_Q, all other SEG_LVL features: 0 frames"
3003+ );
3004+ }
3005+
3006+ /// lane-av1seglvl WITNESS: the reaching stream. `--aq-mode=1` turns
3007+ /// segmentation on for every frame; `--lag-in-frames=16 --auto-alt-ref=1`
3008+ /// adds real alt-ref groups, so the stream mixes map-CODING frames
3009+ /// (`update_map == 1`: the key frame and each group's arf) with dozens of
3010+ /// map-INHERITING frames (`update_map == 0`), and an inheriting block's
3011+ /// id is the MIN of the previous map over its own footprint while the
3012+ /// saved map itself inherits that footprint VERBATIM
3013+ /// (`copy_segment_id`, decodemv.c:342) -- heterogeneous footprints are
3014+ /// exactly what a 1:4-split arf leaves behind. Stamping the minified id
3015+ /// (the pre-lane defect) flattened those footprints and mis-dequantized
3016+ /// scattered blocks frames later: 2 luma bytes of mandelbrot frame 35
3017+ /// differed from the oracle, everything else exact.
3018+ ///
3019+ /// Both arms decode EVERY frame in decode order -- hidden arfs included
3020+ /// -- byte-exact against the instrumented oracle, and every SHOWN frame
3021+ /// pixel-exact against ffmpeg; the census counters prove the premise
3022+ /// (segmentation symbols read, a wider-than-zero quantizer span from
3023+ /// `SEG_LVL_ALT_Q`, and an inheritance-heavy shape).
3024+ #[test]
3025+ fn a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact() {
3026+ const NAME: &str = "a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact";
3027+ if !have_aomenc() {
3028+ eprintln!("SKIP {NAME}: no aomenc");
3029+ return;
3030+ }
3031+ if !have_ffmpeg() {
3032+ eprintln!("SKIP {NAME}: no ffmpeg");
3033+ return;
3034+ }
3035+ let extra = [
3036+ "--cpu-used=4",
3037+ "--aq-mode=1",
3038+ "--cq-level=45",
3039+ "--lag-in-frames=16",
3040+ "--auto-alt-ref=1",
3041+ ];
3042+ let arms: [(&str, &str, usize, usize); 2] = [
3043+ ("screen testsrc2", "testsrc2", 256, 192),
3044+ ("film mandelbrot", "mandelbrot", 192, 128),
3045+ ];
3046+ for (arm, source, width, height) in &arms {
3047+ let stream = encode_aomenc_stream(source, *width, *height, 40, &extra);
3048+ // Premise: the shape under test really arrived -- segmentation on
3049+ // every frame, the map both coded and inherited, and real ALT_Q
3050+ // tables. An aomenc drift that dropped any of these would make
3051+ // the decode below prove nothing (class gate-blind-to-feature).
3052+ let (enabled, umap, inherited, alt_q, _) = segmentation_feature_census(&stream);
3053+ eprintln!(
3054+ "{NAME} {arm}: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q-carrying {alt_q}"
3055+ );
3056+ assert!(
3057+ enabled > 0 && umap > 0,
3058+ "{arm}: no segmentation-carrying/map-coding frame -- the premise is gone"
3059+ );
3060+ assert!(
3061+ inherited > 0,
3062+ "{arm}: no update_map == 0 frame -- the map-inheritance path under test never runs"
3063+ );
3064+ assert!(
3065+ alt_q > 0,
3066+ "{arm}: no frame carries a SEG_LVL_ALT_Q table -- the feature under test never fires"
3067+ );
3068+ // Every frame in decode order -- hidden arfs included (each one
3069+ // re-surfaces via show-existing in this recipe, so `hidden == 0`
3070+ // is possible while `frames` still covers the whole coded set) --
3071+ // byte-exact against the oracle.
3072+ let (frames, hidden) = decode_all_frames_vs_oracle(&stream, arm);
3073+ assert!(frames > 0, "{arm}: decoded nothing");
3074+ assert_eq!(
3075+ frames, enabled,
3076+ "{arm}: decode-order frame count != segmentation-enabled frame count -- the \
3077+ parse and the decode disagree about the stream"
3078+ );
3079+ let _ = hidden;
3080+ // And every shown frame pixel-exact against ffmpeg.
3081+ crate::decode::reset_segment_hits();
3082+ let pictures = decode_stream(&stream)
3083+ .unwrap_or_else(|e| panic!("{NAME} {arm}: decode refused: {e}"));
3084+ assert!(
3085+ crate::decode::segment_id_hits() > 0,
3086+ "{arm}: zero segment_id symbols read -- the decode proved nothing about \
3087+ segmentation"
3088+ );
3089+ let (lo, hi) = crate::decode::block_q_span();
3090+ assert!(
3091+ hi > lo,
3092+ "{arm}: every block dequantized at the same qindex ({lo}) -- SEG_LVL_ALT_Q \
3093+ never changed any block's quantizer"
3094+ );
3095+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, *width, *height, pictures.len());
3096+ for (i, (ours, theirs)) in pictures.iter().zip(&ffmpeg_frames).enumerate() {
3097+ assert_eq!(ours.y, theirs.y, "{NAME} {arm}: frame {i} luma vs ffmpeg");
3098+ assert_eq!(ours.u, theirs.u, "{NAME} {arm}: frame {i} U vs ffmpeg");
3099+ assert_eq!(ours.v, theirs.v, "{NAME} {arm}: frame {i} V vs ffmpeg");
3100+ }
3101+ eprintln!(
3102+ "{NAME} {arm}: {frames} frames decode-order exact vs oracle ({hidden} hidden), {} shown frames exact vs ffmpeg, q span {lo}..{hi}, segment_id symbols {}",
3103+ pictures.len(),
3104+ crate::decode::segment_id_hits()
3105+ );
3106+ }
2703 }3107 }
2704 3108
2705 /// lane-t900 r27, WITNESS half of the proof for "an OBMC neighbour whose3109 /// lane-t900 r27, WITNESS half of the proof for "an OBMC neighbour whose
lanes/av1seglvl.report.mdadded+171 -0
@@ -0,0 +1,171 @@
1+# lane-av1-seglvl — the segmentation mode-override refusal: census, the map-inheritance fix, and the reaching stream
2+
3+Base: `main` **73f3ac64** (2026-09-24). Worktree `edith_codecs-av1seg`, branch
4+`lane-av1-seglvl`, lane commit **5a96bff9**,
5+`CARGO_TARGET_DIR=$HOME/.cache/cargo-target-av1seg` (private). No push.
6+Region: `decode.rs`'s segment-id/map block (`inter_segment_id`), the
7+`stream.rs` segmentation refusal + census gates, and the inventory entry that
8+pins them. Sibling lanes' block-decoder regions untouched.
9+
10+## TL;DR
11+
12+- **Census (re-scoped):** over 11 real-aomenc recipes — 1-pass, alt-ref-lag
13+ (`--lag-in-frames=16 --auto-alt-ref=1`), and a **genuine two-pass** encode,
14+ `--aq-mode=1/2/3`, cq 10/40/45/63, screen (`testsrc2`) and film
15+ (`mandelbrot`) sources — **every frame header parsed**: aomenc enables
16+ `SEG_LVL_ALT_Q` and nothing else. 162 seg-enabled frames in the lag/two-pass
17+ arms alone, zero instances of any other `SEG_LVL` feature. The refusal
18+ **stays, by name, unchanged** (`a frame whose segmentation enables
19+ SEG_LVL_REF_FRAME/SKIP/GLOBALMV ...`).
20+- **The "reachability is nil" claim survived the census but its old PROOF did
21+ not:** the stale comment cited only "CLI exposes no ROI/active-map flag".
22+ The full answer has three legs (§1), the load-bearing one being that
23+ `configure_static_seg_features` (`encoder_utils.c:315`) — the ONLY setter of
24+ `SEG_LVL_ALT_LF_*`/`REF_FRAME`/`SKIP` in the tree — is gated on
25+ `hl_sf.static_segmentation`, which libaom's own `speed_features.h` documents
26+ as **"Always set to 0"**, AND on the second pass (`encoder_utils.c:738`).
27+- **One real defect found and fixed** on the way: `update_map == 0` frames
28+ inherited the previous segment map through the MINIFIED block id, flattening
29+ heterogeneous footprints. libaom (`copy_segment_id`, `decodemv.c:342`)
30+ copies the previous map **verbatim** and hands the block only the min. Fixed
31+ bug-for-bug; witness stream now byte-exact (§2/§3).
32+
33+Inventory delta: none (strings unchanged); the PROVEN entry's comment now
34+carries the corrected evidence and the new witness gate name.
35+
36+## 1. Census: which SEG_LVL features does aomenc actually emit?
37+
38+Instrument: not the refusal — the refusal is blind to a pure-`ALT_LF` stream,
39+which would decode silently past it. `segmentation_feature_census` (new,
40+`stream.rs`) parses every frame OBU and tallies `feature_enabled` per
41+segment-feature instance, alongside the shape counters the premise asserts on
42+(`update_map == 1` map-coding frames, `update_map == 0` map-inheriting
43+frames, `ALT_Q`-carrying frames).
44+
45+Arms (`a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature`,
46+re-scoped in place):
47+
48+- r27's six 1-pass no-lag recipes (kept verbatim: baseline, `--aq-mode=1/2/3`,
49+ `--aq-mode=3 cq10`, `--deltaq-mode=1` over mandelbrot 192x128);
50+- four alt-ref-lag arms: `--aq-mode=1 cq45` over mandelbrot AND testsrc2
51+ 256x192, `--aq-mode=1 cq63` (the `high_q = avg_q > 48` regime of the
52+ static-seg branch), `--aq-mode=2 cq45` — 40 frames each;
53+- one **two-pass** arm (`--passes=2 --pass=1/--pass=2 --fpf=...`,
54+ `--aq-mode=1 cq45 lag16`): `configure_static_seg_features` runs ONLY at
55+ `is_stat_consumption_stage_twopass`, so this arm covers the encoder surface
56+ that would expose the branch if its speed feature were ever revived.
57+
58+Verdict: `SEG_LVL_ALT_Q` only — e.g. `aq-mode=1 lag16 mandelbrot`: 40/40
59+frames seg-enabled, 7 map-coding, 33 inheriting, 12 with `ALT_Q` tables,
60+per-feature `[96, 0, 0, 0, 0, 0, 0, 0]`; twopass arm `[80, 0, ...]`. All
61+non-`ALT_Q` counts asserted zero.
62+
63+Source-side proof that the other seven features have no CLI path
64+(`stream.rs` refusal comment + inventory, all sites read in the oracle tree
65+`~/.cache/aom-oracle/src`, libaom v3.13.3):
66+
67+1. AQ modules clear the table then set `SEG_LVL_ALT_Q` only
68+ (`aq_variance.c:61` clear + `:89` enable, `aq_complexity.c:74` + `:118`,
69+ `aq_cyclicrefresh.c:616` + `:630`).
70+2. `configure_static_seg_features` (`encoder_utils.c:315`) — sets seg-1
71+ `ALT_Q + ALT_LF_*(-2)` on arfs and `REF_FRAME(ALTREF)` (+`SKIP` when
72+ `high_q`) on `is_src_frame_alt_ref` overlays — runs only under
73+ `is_stat_consumption_stage_twopass(cpi) && cpi->sf.hl_sf.static_segmentation`
74+ (`encoder_utils.c:738-740`); `static_segmentation` has **zero assignments
75+ in the tree** and is documented "Always set to 0" (`speed_features.h:436`).
76+ Dead code in v3.13.3, upstream-confirmed.
77+3. `av1_apply_roi_map` / `av1_apply_active_map` (the `REF_FRAME`/`SKIP`
78+ library paths) are control-API only; `aomenc.c` exposes no flag for either
79+ (checked this round).
80+
81+`SEG_LVL_GLOBALMV` additionally has **no setter anywhere in the encoder** —
82+it stays refused with no caveat.
83+
84+## 2. The defect: map inheritance flattened mixed footprints
85+
86+The census's richest arm (`--aq-mode=1 lag16`) decoded 2 luma bytes wrong on
87+film content: mandelbrot 192x128, 40 frames, **frame 35, Y px (75,81) and
88+(74,86)** — one 8x8 block at mi (18..19, 20..21), everything else exact vs
89+ffmpeg. Stage bisect (`EC_AV1_PREFILT_DUMP`): the divergence exists at
90+RECONSTRUCTION — prediction/dequant, not a filter decision. The paired
91+`EC_TRACE_SEG` ladders (ours and the oracle's instrumented aomdec, 386 coded
92+ids) were **line-identical** — every CODED id matched. The divergence had to
93+be in the ids nobody codes: the `update_map == 0` inheritance.
94+
95+libaom (`decodemv.c:386-390`), on such a block:
96+
97+- `copy_segment_id` (`:342`) **memcpys** the previous map over the block's own
98+ footprint — mixed ids intact;
99+- the id the BLOCK carries is `get_predicted_segment_id` = **min** over that
100+ footprint (`dec_get_segment_id`, `:307`).
101+
102+Our port did one step: `write_segment_id(min)`, stamping the min over the
103+footprint. Any block wider than 1 mi sitting on a heterogeneous patch of the
104+previous map (exactly what an arf full of 1:4 splits leaves) flattened the
105+saved map; every later inheriting frame or temporal prediction that read that
106+position got the wrong segment id → wrong `SEG_LVL_ALT_Q` delta → wrong
107+dequant. 2 pixels, frames away from the cause (class
108+`simplified-inheritance`).
109+
110+Fix (`decode.rs`, lane commit 5a96bff9): `copy_segment_ids` — the verbatim
111+per-cell copy — plus the min only as the block's own id; map writes on the
112+coded/temporal paths are untouched (`set_segment_id` semantics, already
113+correct there). `av1_get_qindex` parity re-verified while there
114+(`quant_common.c:222`: `clamp(base + data, 0, MAXQ)` — our `block_q_idx`
115+identical; libaom applies it per block in `parse_decode_block`, values equal
116+at every dequant site).
117+
118+## 3. Proof
119+
120+- **Fail-pre-fix (single mutation, scratch archive of 5a96bff9, only the
121+ `copy_segment_ids` call reverted to the min-stamp):**
122+ `a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact`
123+ FAILS with `film mandelbrot: decode-order frame 35 of 40 (40 shown, 0
124+ hidden) differs from the oracle at byte 15627 (ours 132 vs 43), 2 bytes
125+ differ` — the gate reproduces the exact defect unaided.
126+- **Post-fix:** same gate green on both arms — screen testsrc2: 41 frames
127+ decode-order byte-exact vs the instrumented oracle (1 hidden), 40 shown
128+ frames pixel-exact vs ffmpeg, q span 48..189, 308 segment symbols; film
129+ mandelbrot: 40/40 exact, q span 60..202, 386 symbols. Premise asserts:
130+ `enabled > 0 && umap > 0`, `inherited > 0`, `alt_q > 0`,
131+ `segment_id_hits > 0`, `block_q_span.hi > lo`.
132+- Determinism: the lag stream re-encodes byte-identical across runs
133+ (`mand_r1.obu == mand_r2.obu`, sha256 `76ece5d2...`); screen arm sha256
134+ `2b0548e9...`.
135+
136+## 4. Gates
137+
138+- **NEW witness:** `a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact`
139+ (the reaching stream: segmentation on every frame + real alt-ref groups +
140+ 33-34 inheriting frames per arm; every decode-order frame vs oracle,
141+ every shown frame vs ffmpeg).
142+- **RE-SCOPED census:** `a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature`
143+ — r27's six arms kept, four lag arms + one two-pass arm added, instrument
144+ upgraded from refusal-fires to header-parse tally, verdict asserted per
145+ feature.
146+- **KEPT unchanged:** `a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name`
147+ (the hand-written header sweep over all three features x segments 0/3/7 —
148+ still the proof the refusal fires on conformant streams).
149+- **Regression arms run green** post-fix: `a_real_libaom_monochrome_key_frame_decodes_pixel_exact`
150+ (mono), `a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact`
151+ + `a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact`
152+ (reelb_*/reelc 10-bit fixtures), `a_non_420_subsampled_sequence_header_is_refused_by_name`
153+ (444 refused), `a_frame_using_quantisation_matrices_is_refused_by_name`
154+ (qmatrix refused), `a_real_aomenc_stream_with_cdf_update_disabled_decodes_pixel_exact`
155+ + `a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`
156+ (cdf exact), `a_coded_rect_intrabc_block_reconstructs_in_both_orientations`
157+ + `an_sb128_screen_stream_with_intrabc_decodes_pixel_exact` (the cq50/cq45
158+ screen families), `a_real_aomenc_mixed_lossless_segment_frame_is_refused_by_name`
159+ (aq-mode cq0 refusal, still fires).
160+
161+## 5. Suite + deferred
162+
163+- Full suite (`cargo test -p ec-av1 --lib -- --test-threads=1`,
164+ EC_AV1_REQUIRE_AOMENC/FFMPEG=1) runs on the server per the batch standing
165+ order, staged by Main from this commit (514b19f4; tree clean — the only
166+ untracked path is the shared `assets` symlink, which `git archive` of the
167+ commit excludes); the literal final line is recorded in the merge ticket.
168+ The batch's targeted regression arms (§4) all ran green locally, as did the
169+ three lane gates and the fail-pre-fix run (§3).
170+- `deferred(aomenc has no recipe; unblock = an encoder that emits seg SKIP/REF on intra-only frames — needs a per-segment skip guard on the intra-frame path, where libaom's own read has a stale-segment-id wrinkle worth a look first)`: SEG_LVL_SKIP/REF on INTRA-only frames is not applied on our intra path. aomenc never emits it (features are cleared on key frames, `configure_static_seg_features:334-344`; ROI/active-map gate `!frame_is_intra_only`/`frame_is_intra_only`), and the stream-level refusal is being lifted for none of it — GLOBALMV frames still refuse wholesale. No stream in the suite can reach the shape.
171+- `deferred(no decoder-side effect found; unblock = a census arm that catches configure_static_seg_features going live — the two-pass arm + parse tally in the re-scoped census is that tripwire)`: the arf `ALT_LF(-2)` tables and overlay `REF_FRAME/SKIP` tables cannot reach a stream while `static_segmentation` stays 0. The deblocker's per-segment `ALT_LF` port (`decode.rs`, lane-seg) is in place but stays unwitnessed by a real stream for the same reason.