forge
Explore
Log in

Don't you dare go Hollow

Merge lane-av1mixloss: per-segment lossless gates onto main's qmatrix/ss tree; mixed-lossless witness sample-exact (3 aq arms) + 8 lossless gates green

Browse files at this commit

8a5feaaf4eec5ffa092cf5d42e7919f05c221426Ahmet Kaan GümüşParent: f3c323549ee9bd
decode.rs conflict composition:
- all lane per-segment !lossless gates kept (10 sites incl. the six
  tx-depth readers); main's fctx-aware smooth_uv_neighbour, qmatrix
  dequant and usize mv_to_q4 kept.
- main's forced-4x4 lossless rewrite was MOVED by the lane to after
  read_intra_mode: at the old top-of-function site lossless(fctx)
  resolved against the PREVIOUS block's segment, so a mixed frame
  forced 4x4 units on lossy blocks (48807-sample frame-0 divergence).
  The merge had kept both copies; the stale copy is dropped and its
  4:4:4 chroma arm is folded into the relocated one.
crates/ec-av1/src/decode.rsmodified+167 -57
@@ -23,7 +23,7 @@
2323 use crate::hits::{hit, hit_do};
2424
2525 use ec_av1_syntax::{
26- CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams,
26+ CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams, MAX_SEGMENTS,
2727 SEG_LVL_ALT_LF_Y_V, SEG_LVL_ALT_Q, SegmentationParams, TileInfo,
2828 };
2929 use ec_core::{Error, Result};
@@ -90,13 +90,18 @@ pub(crate) struct FrameCtx {
9090 /// [`filter_ctx_copy`]) so a tile-search worker thread reads the same
9191 /// kernel the frame header wrote instead of the default.
9292 pub(crate) interp_filter: std::cell::Cell<crate::mc::InterpFilterKind>,
93- /// lane-lossless: this frame's `CodedLossless` (spec 5.9.12) -- every
94- /// segment at `qindex == 0` with zero plane deltas. It forces TX_4X4 with
95- /// the Walsh-Hadamard transform on every plane, drops the `tx_type`
96- /// symbol and narrows `is_cfl_allowed` (libaom `read_tx_size`
97- /// (`decodeframe.c`), `read_tx_type` (`decodetxb.c`), `is_cfl_allowed`
98- /// (`blockd.h`)).
99- pub(crate) lossless_flag: std::cell::Cell<bool>,
93+ /// lane-lossless: this frame's per-segment lossless table -- libaom's
94+ /// `xd->lossless[MAX_SEGMENTS]`, computed ONCE per frame in the header
95+ /// (spec 5.9.12 `CodedLossless`: each segment at `qindex == 0` with zero
96+ /// plane deltas, `get_qindex` applying that segment's own `SEG_LVL_ALT_Q`).
97+ /// Every block-decoder rule that reads [`decode::lossless`] resolves it
98+ /// through the BLOCK's own `segment_id`: TX_4X4 with the Walsh-Hadamard
99+ /// transform on every plane, the dropped `tx_type` symbol and the narrowed
100+ /// `is_cfl_allowed` (libaom `read_tx_size` (`decodeframe.c`),
101+ /// `read_tx_type` (`decodetxb.c`), `is_cfl_allowed` (`blockd.h`)) follow
102+ /// the SEGMENT, so a frame whose segments disagree codes lossless and
103+ /// lossy blocks side by side.
104+ pub(crate) lossless_per_seg: std::cell::Cell<[bool; MAX_SEGMENTS]>,
100105 /// lane-av1txr: this frame header's `disable_cdf_update` (spec 5.9.2).
101106 /// When set, the tile reader must not adapt any CDF it reads, or its
102107 /// tables drift away from the encoder's and the frame desyncs mid-tile
@@ -225,7 +230,7 @@ impl FrameCtx {
225230 // the size this process encodes -- see [`FrameCtx::for_encoder`].
226231 sb128_flag: std::cell::Cell::new(false),
227232 interp_filter: std::cell::Cell::new(crate::mc::InterpFilterKind::Regular),
228- lossless_flag: std::cell::Cell::new(false),
233+ lossless_per_seg: std::cell::Cell::new([false; MAX_SEGMENTS]),
229234 disable_cdf_update: std::cell::Cell::new(false),
230235 cdef_bits: std::cell::Cell::new(0),
231236 bit_depth: std::cell::Cell::new(8),
@@ -431,14 +436,26 @@ pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {
431436 crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx);
432437 }
433438
434-/// Sets [`FrameCtx::lossless_flag`] (called once per frame from `stream.rs`).
435-pub(crate) fn set_lossless(v: bool, fctx: &crate::decode::FrameCtx) {
436- fctx.lossless_flag.with(|c| c.set(v));
439+/// lane-av1mixloss: sets [`FrameCtx::lossless_per_seg`] (called once per frame
440+/// from `stream.rs`).
441+pub(crate) fn set_lossless_per_seg(
442+ table: [bool; MAX_SEGMENTS],
443+ fctx: &crate::decode::FrameCtx,
444+) {
445+ fctx.lossless_per_seg.with(|c| c.set(table));
437446 }
438447
439-/// This frame's `CodedLossless` -- see [`FrameCtx::lossless_flag`].
448+/// The BLOCK's own lossless bit: libaom's `xd->lossless[mbmi->segment_id]`.
449+/// The table is computed once per frame (libaom `decodeframe.c:5205`:
450+/// `qindex == 0` with every plane delta 0, `av1_get_qindex` applying the
451+/// segment's `SEG_LVL_ALT_Q`), but the frame never carries ONE lossless rule
452+/// -- `read_tx_size`, `read_tx_type` and `is_cfl_allowed` all index it by the
453+/// BLOCK's own segment id, which the spec-order `segment_id` read sets before
454+/// any mode/transform symbol of the block. A frame whose segments disagree
455+/// codes TX_4X4/WHT blocks and normal blocks side by side.
440456 pub(crate) fn lossless(fctx: &crate::decode::FrameCtx) -> bool {
441- fctx.lossless_flag.with(|c| c.get())
457+ let seg_id = usize::from(fctx.cur_segment_id.with(|c| c.get()));
458+ fctx.lossless_per_seg.with(|c| c.get())[seg_id]
442459 }
443460
444461 /// Sets [`FrameCtx::disable_cdf_update`] (called once per frame from
@@ -454,7 +471,7 @@ pub(crate) fn cdf_update_disabled(fctx: &crate::decode::FrameCtx) -> bool {
454471 }
455472
456473 /// The transform side a block of `side` pixels codes: its own (capped at the
457-/// caller's own largest) normally, 4 on a lossless frame, where libaom's
474+/// caller's own largest) normally, 4 on a lossless BLOCK, where libaom's
458475 /// `read_tx_size` returns TX_4X4 before it looks at anything else
459476 /// (`decodeframe.c`: `if (xd->lossless[xd->mi[0]->segment_id]) return
460477 /// TX_4X4;`).
@@ -463,7 +480,7 @@ pub(crate) fn lossless_tx(px: usize, fctx: &crate::decode::FrameCtx) -> usize {
463480 }
464481
465482 /// `is_cfl_allowed` (libaom `blockd.h`): CfL is offered on a block up to
466-/// 32x32 -- but on a LOSSLESS frame only when the block's CHROMA plane block
483+/// 32x32 -- but on a LOSSLESS BLOCK only when the block's CHROMA plane block
467484 /// is exactly BLOCK_4X4, i.e. (at 4:2:0) a luma block of 8x8 or smaller.
468485 /// Getting this wrong picks the 14-symbol CFL `uv_mode` alphabet where libaom
469486 /// picks the 13-symbol one (class `wrong-alphabet-same-value`).
@@ -2509,19 +2526,35 @@ pub(crate) struct TxParams {
25092526 /// recon worker scales identically without touching frame state.
25102527 pub(crate) qm: Option<crate::qm::Iqm>,
25112528 pub(crate) stride: usize,
2512- /// lane-lossless: this transform unit belongs to a lossless frame, so the
2513- /// residual comes off the 4x4 Walsh-Hadamard
2529+ /// lane-lossless: this transform unit belongs to a lossless BLOCK (its
2530+ /// segment's `xd->lossless[segment_id]` bit), so the residual comes off
2531+ /// the 4x4 Walsh-Hadamard
25142532 /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the
25152533 /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`).
25162534 pub(crate) lossless: bool,
25172535 }
25182536
2537+/// lane-av1mixloss: Walsh-Hadamard transform units actually reconstructed.
2538+/// The mixed-lossless witness's proof the per-segment lossless path really
2539+/// ran on a frame that is NOT `CodedLossless`. Atomic because the wavefront
2540+/// workers run this on their own threads.
2541+static LOSSLESS_WHT_UNITS: std::sync::atomic::AtomicUsize =
2542+ std::sync::atomic::AtomicUsize::new(0);
2543+
2544+/// [`LOSSLESS_WHT_UNITS`] -- total over the process, read as a before/after
2545+/// delta around one decode.
2546+#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2547+pub(crate) fn lossless_wht_units() -> usize {
2548+ LOSSLESS_WHT_UNITS.load(std::sync::atomic::Ordering::Relaxed)
2549+}
2550+
25192551 impl TxParams {
25202552 /// The one copy of the produce-the-residual code: the inline path calls it
25212553 /// on the parse thread, the wavefront worker calls it on its own, so both
25222554 /// are the same function on the same inputs and byte-identical.
25232555 fn run(self, grid: &[i32]) -> Vec<i32> {
25242556 let residual = if self.lossless {
2557+ LOSSLESS_WHT_UNITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
25252558 debug_assert_eq!((self.w, self.h), (4, 4));
25262559 debug_assert_eq!(self.tx_type, TxType::DctDct);
25272560 crate::transform::dequant_and_inverse_wht4x4(
@@ -6712,6 +6745,13 @@ fn read_coeffs(
67126745 let (range, value) = dec.debug_state();
67136746 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
67146747 }
6748+ if crate::envflags::env_flag!("EC_ECDUMP_IN") {
6749+ let (range, value) = dec.debug_state();
6750+ let bit = dec.debug_bitpos();
6751+ eprintln!(
6752+ "EC_ECDUMP_IN side={side} ctx={skip_ctx} dcctx={sign_ctx} ECIN=({value},{range},{bit})"
6753+ );
6754+ }
67156755 let dbg_txbskip = if coeff_trace_on() {
67166756 coding.txb_skip[skip_ctx]
67176757 } else {
@@ -8442,9 +8482,18 @@ impl Neighbours {
84428482 (0..above_mi).map(|k| self.above[mi_c + k][0].level.to_string()).collect();
84438483 let lf: Vec<String> =
84448484 (0..left_mi).map(|k| self.left[mi_r + k][0].level.to_string()).collect();
8485+ // lane-av1mix: the last few msac register states, so the
8486+ // byte-position of the `all_zero` read can be matched against
8487+ // aomdec's `EC=(value,rng,bytepos)` dump (decodetxb.c) without a
8488+ // second run.
8489+ let recent = crate::msac::symtrace::ecdump_recent(4)
8490+ .iter()
8491+ .map(|(_low, value, rng, bytepos)| format!("({value},{rng},{bytepos})"))
8492+ .collect::<Vec<_>>()
8493+ .join(" ");
84458494 eprintln!(
8446- "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},]",
8447- ab.join(","), lf.join(",")
8495+ "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},] recentEC=[{}]",
8496+ ab.join(","), lf.join(","), recent
84488497 );
84498498 }
84508499 if crate::envflags::env_flag!("EC_AV1_TRACE") {
@@ -11201,7 +11250,11 @@ fn decode_intra_rect_in_inter(
1120111250 hit!(SMOOTH_LUMA_HITS);
1120211251 }
1120311252 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
11204- let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) {
11253+ // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
11254+ // precedes `TX_MODE_SELECT`, so a lossless-segment intra-rect block inside
11255+ // an inter frame codes no depth symbol either (`xd->lossless` is per
11256+ // segment regardless of frame type; class sweep of the sub8 leaf's fix).
11257+ let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) {
1120511258 // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`].
1120611259 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
1120711260 let d = match tx_cat {
@@ -12230,7 +12283,11 @@ fn decode_block_rect(
1223012283 // desynced the tile from that point on. That is why both strips of the
1223112284 // pinned HORZ quadrant were wrong from their very first pixel, and why our
1223212285 // range after the read equalled the oracle's range for the whole block.
12233- let depth = if tx_select {
12286+ // lane-av1mixloss: the lossless-segment early return
12287+ // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a lossless-segment
12288+ // rect block codes no depth symbol here either (class sweep of the sub8
12289+ // leaf's fix).
12290+ let depth = if tx_select && !lossless(fctx) {
1223412291 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
1223512292 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
1223612293 // intra-only frame publishes them from every block too
@@ -12764,9 +12821,16 @@ fn decode_leaf_rect(
1276412821 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
1276512822 // a constant `false`.
1276612823 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
12767- let depth = if tx_select {
12824+ let depth = if tx_select && !lossless(fctx) {
1276812825 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
1276912826 // every other rect reader now does -- a no-op on a key frame.
12827+ // lane-av1mixloss: libaom `read_tx_size`'s first line
12828+ // (`decodeframe.c:1203`, `if (xd->lossless[segment_id]) return
12829+ // TX_4X4;`) precedes the `TX_MODE_SELECT` test, so a lossless-segment
12830+ // rect leaf codes NO depth symbol (`depth_to_tx_wh` clamps to 4x4).
12831+ // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours
12832+ // read `tx_size_cat1` (rng 55700->49918) where the oracle's next
12833+ // read was the leaf's own txb_skip.
1277012834 let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx);
1277112835 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
1277212836 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
@@ -13124,7 +13188,10 @@ fn decode_block_rect4(
1312413188 } else {
1312513189 uv_mode
1312613190 };
13127- let depth = if tx_select {
13191+ // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
13192+ // precedes `TX_MODE_SELECT`, so a lossless-segment rect4 block codes no
13193+ // depth symbol here either (class sweep of the sub8 leaf's fix).
13194+ let depth = if tx_select && !lossless(fctx) {
1312813195 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
1312913196 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
1313013197 // intra-only frame publishes them from every block too
@@ -14215,7 +14282,11 @@ fn decode_rect4_16_strip(
1421514282 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
1421614283 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
1421714284 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
14218- let depth = if tx_select {
14285+ // lane-av1mixloss: the lossless-segment early return
14286+ // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a
14287+ // lossless-segment strip codes no depth symbol here either (class
14288+ // sweep of the sub8 leaf's fix).
14289+ let depth = if tx_select && !lossless(fctx) {
1421914290 // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands
1422014291 // (`get_tx_size_context`, libaom `pred_common.h:342`).
1422114292 let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
@@ -14805,7 +14876,10 @@ fn decode_block_rect64(
1480514876 uv_mode
1480614877 };
1480714878 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
14808- let depth = if tx_select {
14879+ // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
14880+ // precedes `TX_MODE_SELECT`, so a lossless-segment 64-axis rect block codes
14881+ // no depth symbol here either (class sweep of the sub8 leaf's fix).
14882+ let depth = if tx_select && !lossless(fctx) {
1480914883 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
1481014884 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
1481114885 // intra-only frame publishes them from every block too
@@ -16391,24 +16465,6 @@ fn decode_block(
1639116465 tx_select: bool,
1639216466 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
1639316467 ) -> Result<()> {
16394- // lane-lossless: a lossless frame's transform is TX_4X4 on every plane
16395- // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
16396- // tables/scans are replaced by the 4x4 ones and the block always takes the
16397- // multi-transform-unit path below.
16398- let (luma_set, chroma_set, luma_tx, chroma_tx, scans) = if lossless(fctx) {
16399- (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, (scan4, scan4))
16400- } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
16401- let tx = if side >= 64 { 32 } else { side };
16402- let (set, scan): (TxbSet, &[u16]) = match tx {
16403- 32 => (TxbSet::Chroma32, scan32),
16404- 16 => (TxbSet::Chroma16, scan16),
16405- 8 => (TxbSet::Chroma8, scan8),
16406- _ => (TxbSet::Chroma4, scan4),
16407- };
16408- (luma_set, set, luma_tx, tx, (scans.0, scan))
16409- } else {
16410- (luma_set, chroma_set, luma_tx, chroma_tx, scans)
16411- };
1641216468 let (r, c) = at;
1641316469 let (px, py) = (c * SUB, r * SUB);
1641416470 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
@@ -16435,6 +16491,34 @@ fn decode_block(
1643516491 if at_tile_left && palette_y.is_some() {
1643616492 hit!(PALETTE_TILE_LEFT_HITS);
1643716493 }
16494+ // lane-lossless: a lossless BLOCK's transform is TX_4X4 on every plane
16495+ // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
16496+ // tables/scans are replaced by the 4x4 ones and the block always takes the
16497+ // multi-transform-unit path below. lane-av1mixloss: this rewrite used to
16498+ // sit at the TOP of the function -- before `read_intra_mode`, which is
16499+ // where the block's own `segment_id` is read -- so a mixed frame resolved
16500+ // every block's geometry against the PREVIOUS block's segment (a lossless
16501+ // neighbour forced 4x4 units on a lossy block; a lossy one handed the
16502+ // lossless TxParams an 8x8 grid). libaom's order is the opposite one:
16503+ // `decode_mbmi_block` (segment id included) runs before any tx-size rule.
16504+ // lane-av1mixmerge: the 4:4:4 chroma-size arm from main's copy of this
16505+ // rewrite (which sat above `read_intra_mode`) rides along here -- same
16506+ // per-frame `ss_x`/`ss_y` condition, now resolved against the block's own
16507+ // segment like the lossless arm above it.
16508+ let (luma_set, chroma_set, luma_tx, chroma_tx, scans) = if lossless(fctx) {
16509+ (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, (scan4, scan4))
16510+ } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
16511+ let tx = if side >= 64 { 32 } else { side };
16512+ let (set, scan): (TxbSet, &[u16]) = match tx {
16513+ 32 => (TxbSet::Chroma32, scan32),
16514+ 16 => (TxbSet::Chroma16, scan16),
16515+ 8 => (TxbSet::Chroma8, scan8),
16516+ _ => (TxbSet::Chroma4, scan4),
16517+ };
16518+ (luma_set, set, luma_tx, tx, (scans.0, scan))
16519+ } else {
16520+ (luma_set, chroma_set, luma_tx, chroma_tx, scans)
16521+ };
1643816522 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
1643916523 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
1644016524 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
@@ -16476,7 +16560,14 @@ fn decode_block(
1647616560 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
1647716561 // intrabc block as inter.
1647816562 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
16479- let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip;
16563+ // libaom `parse_decode_block`'s var-tx tree condition carries
16564+ // `!xd->lossless[mbmi->segment_id]` (decodeframe.c:1237): an intrabc
16565+ // block inside a LOSSLESS segment of a mixed frame reads NO
16566+ // `txfm_partition` tree -- it falls to `read_tx_size`, whose first line
16567+ // hands back TX_4X4. Invisible while every lossless frame was also
16568+ // `CodedLossless` (`tx_mode` forced `Only4x4`, tree unreachable), which
16569+ // is why the mixed frame is the first stream to reach it.
16570+ let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip && !lossless(fctx);
1648016571 let intrabc_leaves = if intrabc_vartx {
1648116572 let max_tx = side.min(64);
1648216573 // `max_block_wide`/`max_block_high`: the frame's own mi grid
@@ -16516,7 +16607,7 @@ fn decode_block(
1651616607 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves {
1651716608 (tx, if tx == 64 { 32 } else { tx })
1651816609 } else if tx_select && !intrabc_skip_tx {
16519- let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side);
16610+ let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, fctx);
1652016611 (resolved, if resolved == 64 { 32 } else { resolved })
1652116612 } else {
1652216613 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
@@ -17825,7 +17916,11 @@ fn decode_leaf8(
1782517916 // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that
1782617917 // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi
1782717918 // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return).
17828- let resolved = if tx_select && intrabc_dv.is_some() && !skip {
17919+ // `parse_decode_block`'s tree condition carries
17920+ // `!xd->lossless[mbmi->segment_id]` (see [`decode_block`]'s own copy):
17921+ // a lossless segment's intrabc leaf reads no tree, TX_4X4 via
17922+ // `read_tx_size`'s first line (lane-av1mixloss).
17923+ let resolved = if tx_select && intrabc_dv.is_some() && !skip && !lossless(fctx) {
1782917924 let mut leaves = Vec::new();
1783017925 let mi_cols = 2 * y.true_width.div_ceil(8);
1783117926 let mi_rows = 2 * y.true_height.div_ceil(8);
@@ -17848,7 +17943,7 @@ fn decode_leaf8(
1784817943 hit!(INTRABC_VARTX_HITS);
1784917944 leaves.first().map_or(8, |l| l.2)
1785017945 } else if tx_select && intrabc_dv.is_none() {
17851- read_tx_size(dec, cdfs, neighbours, leaf_mi, 8)
17946+ read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, fctx)
1785217947 } else {
1785317948 // lane-lossless: TX_4X4 on a lossless frame, no symbol
1785417949 // (libaom `read_tx_size`).
@@ -19339,7 +19434,13 @@ fn decode_leaf_rect8(
1933919434 // Missing this read consumed one symbol fewer than the encoder wrote
1934019435 // and desynced the tile at the very first rect leaf (class
1934119436 // `symbol-consumption-gap`).
19342- let depth = if tx_select {
19437+ // lane-av1mix: libaom `read_tx_size`'s FIRST line
19438+ // (`decodeframe.c:1203`, `if (xd->lossless[...]) return TX_4X4`)
19439+ // fires before the `TX_MODE_SELECT` test, so a lossless-segment leaf
19440+ // codes NO depth symbol even in `TxMode::Select` -- the mixed-lossless
19441+ // frame's sub8 leaves forked exactly here (ours read the symbol at
19442+ // (12477,50864) bit 3011, the oracle's all_zero used it).
19443+ let depth = if tx_select && !lossless(fctx) {
1934319444 // lane-av1txbands: the `TXFM_CONTEXT` band read every other rect
1934419445 // reader already does.
1934519446 let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
@@ -20595,7 +20696,18 @@ fn read_tx_size(
2059520696 n: &Neighbours,
2059620697 at_mi: (usize, usize),
2059720698 side: usize,
20699+ fctx: &crate::decode::FrameCtx,
2059820700 ) -> usize {
20701+ // libaom `read_tx_size`'s FIRST line (decodeframe.c:1203):
20702+ // `if (xd->lossless[xd->mi[0]->segment_id]) return TX_4X4;` -- before the
20703+ // `tx_mode == TX_MODE_SELECT` test and before any symbol. Invisible while
20704+ // every lossless frame was ALSO `CodedLossless` (its `tx_mode` is forced
20705+ // `Only4x4`, so this function never ran); a MIXED frame keeps
20706+ // `TxMode::Select`, so its lossless segments reach the symbol read and
20707+ // must take the early return (lane-av1mixloss).
20708+ if lossless(fctx) {
20709+ return 4;
20710+ }
2059920711 // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` /
2060020712 // `get_tx_size_context`): a block wider than 64 still tops out at
2060120713 // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth
@@ -21092,13 +21204,7 @@ fn read_block_tx_size(
2109221204 let tx = if is_inter {
2109321205 side.min(64)
2109421206 } else {
21095- read_tx_size(
21096- dec,
21097- cdfs,
21098- n,
21099- at_mi,
21100- side,
21101- )
21207+ read_tx_size(dec, cdfs, n, at_mi, side, fctx)
2110221208 };
2110321209 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
2110421210 if !is_inter && tx != side {
@@ -35079,7 +35185,11 @@ fn decode_intra_sub8_leaf(
3507935185 // context bands, which on an inter frame are live.
3508035186 // `block_signals_txsize(BLOCK_4X4)` is false (blockd.h:1027): the 4x4 leaf
3508135187 // codes no depth symbol at all, its transform is its own size.
35082- let depth = if tx_select && bw != bh {
35188+ // lane-av1mix: the lossless early return (`decodeframe.c:1203`) sits
35189+ // before the `TX_MODE_SELECT` test, so a lossless-segment rect leaf codes
35190+ // no depth symbol either (sweep of the class fixed at the key-frame pair
35191+ // path).
35192+ let depth = if tx_select && bw != bh && !lossless(fctx) {
3508335193 let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
3508435194 let d = dec.symbol(&mut cdfs.tx_size_cat0[ctx]);
3508535195 if step {
crates/ec-av1/src/msac.rsmodified+93 -9
@@ -402,7 +402,11 @@ impl<'a> SymbolDecoder<'a> {
402402 // TABLE it read, so every coding tool is accounted without a
403403 // per-call-site label. Off (`EC_AV1_BITCENSUS` unset) this is one
404404 // relaxed load.
405- let t0 = if crate::census::armed() { self.tell_bits() } else { 0.0 };
405+ let t0 = if crate::census::armed() {
406+ self.tell_bits()
407+ } else {
408+ 0.0
409+ };
406410 let s = self.symbol_fixed(cdf);
407411 // lane-av1txr: spec 5.9.2's `disable_cdf_update` -- a frame that sets
408412 // it codes every symbol against the tables it started with, so this
@@ -410,7 +414,7 @@ impl<'a> SymbolDecoder<'a> {
410414 // allow_update_cdf && !cm->features.disable_cdf_update`,
411415 // decodeframe.c:2909). The flag is per-reader (see `Self::adapt`).
412416 if self.adapt {
413- update_cdf(cdf, s);
417+ update_cdf(cdf, s);
414418 }
415419 if crate::census::armed() {
416420 crate::census::charge(cdf.as_ptr() as usize, self.tell_bits() - t0);
@@ -443,13 +447,16 @@ impl<'a> SymbolDecoder<'a> {
443447 #[inline]
444448 fn symbol_fixed_raw(&mut self, cdf: &[u16]) -> usize {
445449 let nsyms = cdf.len() - 1;
450+ if symtrace::ecdump_armed() {
451+ symtrace::ecdump(0, self.value, self.range, self.bit as i64);
452+ }
446453 // Two-symbol alphabets are most of the stream (every flag, every bit of
447454 // a literal), and their walk has exactly one boundary: computing it
448455 // straight skips the loop and its bounds work.
449456 if nsyms == 2 {
450457 let f = u32::from(CDF_TOP - cdf[0]);
451- let cur = (((self.range >> 8) * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
452- + EC_MIN_PROB;
458+ let cur =
459+ (((self.range >> 8) * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT)) + EC_MIN_PROB;
453460 return self.bool_cur(cur);
454461 }
455462 // Loop-invariant: the coder's range does not move until the symbol is
@@ -829,13 +836,21 @@ pub(crate) mod tests {
829836 (a, b as u32)
830837 };
831838 assert_eq!(a, b, "item {i} (pick {pick})");
832- assert_eq!(a, if pick == usize::MAX { a } else { arg }, "item {i} vs written");
839+ assert_eq!(
840+ a,
841+ if pick == usize::MAX { a } else { arg },
842+ "item {i} vs written"
843+ );
833844 assert_eq!(
834845 fast.debug_state(),
835846 slow.debug_state(),
836847 "coder state after item {i} (pick {pick})"
837848 );
838- assert_eq!(fast_cdfs[pick.min(14)], slow_cdfs[pick.min(14)], "cdf after item {i}");
849+ assert_eq!(
850+ fast_cdfs[pick.min(14)],
851+ slow_cdfs[pick.min(14)],
852+ "cdf after item {i}"
853+ );
839854 }
840855 }
841856
@@ -898,6 +913,7 @@ pub(crate) mod tests {
898913 /// Off (the variable unset) this is one relaxed load per symbol.
899914 pub(crate) mod symtrace {
900915 use std::cell::RefCell;
916+ use std::collections::VecDeque;
901917 use std::sync::OnceLock;
902918
903919 static DIR: OnceLock<Option<String>> = OnceLock::new();
@@ -906,11 +922,76 @@ pub(crate) mod symtrace {
906922
907923 thread_local! {
908924 static BUF: RefCell<(String, usize)> = const { RefCell::new((String::new(), 0)) };
925+ static ECD: RefCell<VecDeque<(u32, u32, u32, u32)>> = RefCell::new(VecDeque::new());
926+ static ECD_READER: RefCell<Option<std::fs::File>> = const { RefCell::new(None) };
927+ static ECD_IDX: RefCell<usize> = const { RefCell::new(0) };
928+ }
929+
930+ /// lane-av1mix: `(low, value, rng, bitpos)` state register dump, one line
931+ /// per symbol read, byte-for-byte diffable against libaom's `EC_ECDUMP`
932+ /// (`decodetxb.c`, `r->ec.dif` masked to 16 bits / `r->ec.rng` /
933+ /// `od_ec_dec_tell`). Reader-only, `EC_AV1_ECDUMP=<dir>`: each reader
934+ /// writes `<dir>/ecdump-<n>.txt`.
935+ pub(crate) fn ecdump(low: u32, value: u32, rng: u32, bitpos: i64) {
936+ if !ecdump_armed() {
937+ return;
938+ }
939+ let dir = std::env::var("EC_AV1_ECDUMP").unwrap_or_else(|_| "/tmp".to_string());
940+ let idx = ECD_IDX.with(|c| {
941+ let mut g = c.borrow_mut();
942+ let n = *g;
943+ *g += 1;
944+ n
945+ });
946+ let _ = idx;
947+ let line = format!("{idx} ({low},{value},{rng},{bitpos})\n");
948+ ECD_READER.with(|f| {
949+ let mut slot = f.borrow_mut();
950+ if slot.is_none() {
951+ let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
952+ let path = format!("{dir}/ecdump-{seq:05}.txt");
953+ *slot = Some(std::fs::File::create(&path).expect("ecdump file"));
954+ eprintln!("ECDUMP -> {path}");
955+ }
956+ use std::io::Write;
957+ let _ = slot.as_mut().unwrap().write_all(line.as_bytes());
958+ });
959+ ECD.with(|q| {
960+ let mut q = q.borrow_mut();
961+ q.push_back((low, value, rng, bitpos as u32));
962+ if q.len() > 512 {
963+ q.pop_front();
964+ }
965+ });
966+ }
967+
968+ /// lane-av1mix: the last `n` dumped register states (most recent last).
969+ #[allow(dead_code)] // diagnostic helper for lane sessions
970+ pub(crate) fn ecdump_recent(n: usize) -> Vec<(u32, u32, u32, u32)> {
971+ if std::env::var_os("EC_AV1_ECDUMP").is_none() {
972+ return Vec::new();
973+ }
974+ ECD.with(|q| {
975+ let q = q.borrow();
976+ let skip = q.len().saturating_sub(n);
977+ q.iter().skip(skip).copied().collect()
978+ })
909979 }
910980
911981 pub(crate) fn dir() -> Option<&'static str> {
912- DIR.get_or_init(|| crate::envflags::var("EC_AV1_SYMTRACE").ok().filter(|v| !v.is_empty()))
913- .as_deref()
982+ DIR.get_or_init(|| {
983+ crate::envflags::var("EC_AV1_SYMTRACE")
984+ .ok()
985+ .filter(|v| !v.is_empty())
986+ })
987+ .as_deref()
988+ }
989+
990+ /// lane-av1mix: `EC_AV1_ECDUMP=<dir>` arms the decoder state-register dump.
991+ pub(crate) fn ecdump_armed() -> bool {
992+ static ARMED: std::sync::LazyLock<bool> =
993+ std::sync::LazyLock::new(|| std::env::var_os("EC_AV1_ECDUMP").is_some());
994+ *ARMED
914995 }
915996
916997 /// `EC_AV1_SYMTRACE_AT=<i>` or `=<from>:<to>` (inclusive).
@@ -940,7 +1021,10 @@ pub(crate) mod symtrace {
9401021 BUF.with(|b| {
9411022 let (buf, n) = &mut *b.borrow_mut();
9421023 if at().is_some_and(|(a, b)| (a..=b).contains(n)) {
943- eprintln!("SYMTRACE at {n}: {}", std::backtrace::Backtrace::force_capture());
1024+ eprintln!(
1025+ "SYMTRACE at {n}: {}",
1026+ std::backtrace::Backtrace::force_capture()
1027+ );
9441028 }
9451029 buf.push_str(&format!("{n} {value} {nsyms} {cdf0}\n"));
9461030 *n += 1;
crates/ec-av1/src/refusal_inventory.rsmodified+12 -18
@@ -126,9 +126,12 @@ const REFUSALS: &[&str] = &[
126126 // BLOCK_4X4 chroma plane block, and the chroma plane walked as 4x4 units
127127 // plane-major inside each mu chunk (gates
128128 // `a_lossless_libaom_key_frame_decodes_sample_exact` /
129- // `a_lossless_libaom_inter_frame_decodes_sample_exact`). A frame whose
130- // segments disagree is still refused: every lossless rule is per segment.
131- "a frame mixing lossless and lossy segments (the TX_4X4/WHT rules are per segment there)",
129+ // `a_lossless_libaom_inter_frame_decodes_sample_exact`). The refusal
130+ // that stood here for a frame whose SEGMENTS disagree ("the TX_4X4/WHT
131+ // rules are per segment there") is LIFTED too: lane-av1mixloss ports the
132+ // per-segment table (libaom `decodeframe.c:5205`), and
133+ // `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact`
134+ // proves a real aq-mode stream sample-exact.
132135 "a frame OBU with no tile group",
133136 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
134137 "a frame with no mode-info grid",
@@ -245,9 +248,12 @@ const REFUSALS: &[&str] = &[
245248 /// The two that are NOT spec-conformant, and are kept as named capability gaps
246249 /// with an assessment (a real gap libaom accepts, no reachable witness here):
247250 /// a reference picture whose height differs (libaom SCALES,
248-/// `decodeframe.c:5089`) and a frame mixing lossless and lossy segments
249-/// (libaom decodes it per segment, `decodeframe.c:5205`; now WITNESSED by
250-/// `a_real_aomenc_mixed_lossless_segment_frame_is_refused_by_name`).
251+/// `decodeframe.c:5089`). A third one -- a frame mixing lossless and lossy
252+/// segments (libaom decodes it per segment, `decodeframe.c:5205`) -- was the
253+/// same kind of gap until lane-av1mixloss ported the per-segment table; its
254+/// refusal is gone and
255+/// `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact` is the
256+/// witness.
251257 #[cfg(test)]
252258 const PROVEN: &[(&str, &str)] = &[
253259 // lane-t900 r20, census: three real streams present exactly the 18
@@ -524,18 +530,6 @@ const PROVEN: &[(&str, &str)] = &[
524530 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
525531 "an_inter_frame_naming_an_unrefreshed_primary_ref_slot_is_refused_by_name",
526532 ),
527- // lane-hdrlossless, WITNESS: the one refusal the pilot report left with
528- // NO proving test. It is a REAL aomenc output, not a defensive pin:
529- // `--end-usage=q --cq-level=0 --aq-mode=1` codes a frame whose segments
530- // disagree about lossless (`aq_variance.c` sets `SEG_LVL_ALT_Q` per
531- // segment with no clamp once `base_qindex == 0`), libaom decodes it
532- // (`xd->lossless[segment_id]`, `decodeframe.c:5205`), and THIS decoder
533- // refuses it by name. A named capability gap until the block-decoder
534- // lift lands (see the refusal's own doc in `stream.rs`).
535- (
536- "a frame mixing lossless and lossy segments (the TX_4X4/WHT rules are per segment there)",
537- "a_real_aomenc_mixed_lossless_segment_frame_is_refused_by_name",
538- ),
539533 ];
540534
541535 /// Gates whose `Err` arm turns a decode failure into a printed SKIP rather than
crates/ec-av1/src/stream.rsmodified+70 -73
@@ -1769,36 +1769,28 @@ fn decode_frame(
17691769 // symbol and narrows `is_cfl_allowed` to `plane_bsize == BLOCK_4X4`
17701770 // (libaom `read_tx_size`/`read_tx_type`/`is_cfl_allowed`).
17711771 //
1772- // lane-hdrlossless: a frame whose segments DISAGREE is a valid stream
1773- // libaom decodes -- `xd->lossless[segment_id]` is per segment
1774- // (`decodeframe.c:5205`), and aomenc WRITES one: `--end-usage=q
1775- // --cq-level=0 --aq-mode=1` (variance AQ over a lossless base) gives a
1776- // high-variance segment a positive `SEG_LVL_ALT_Q` while a flat one stays
1777- // at `qindex == 0` (witness gate
1778- // `a_real_aomenc_mixed_lossless_segment_frame_is_refused_by_name`). This
1779- // decoder still refuses it BY NAME, and the refusal is honest rather than
1780- // spec-conformant: the lift is a BLOCK-decoder feature, not a header one.
1781- // Measured while attempting it: threading the per-segment table through
1782- // [`decode::lossless`] alone is not enough -- (a) `read_tx_size` and the
1783- // ~8 rectangular-strip `tx_depth` readers must return TX_4X4 without
1784- // reading a symbol when the block is lossless (libaom `read_tx_size`'s
1785- // first line), and (b) the lossless reconstruction/coefficient path for
1786- // the shapes such a frame codes is still partial. The naive lift desyncs
1787- // the tile ("a Golomb tail longer than this decoder reads") or returns a
1788- // picture that differs from ffmpeg from byte 32. Kept as a named gap
1789- // until a block-decoder lane ports per-segment lossless as one unit.
1790- let coded_lossless = header.lossless.iter().all(|&l| l);
1791- if header.lossless.iter().any(|&l| l) && !coded_lossless {
1792- return Err(Error::unsupported(
1793- "AV1 decode_stream",
1794- "a frame mixing lossless and lossy segments (the TX_4X4/WHT rules are per segment there)",
1795- ));
1796- }
1797- // lane-lossless2: an INTER frame's chroma plane is now walked as 4x4
1798- // transform units too (`decode::read_inter_chroma_lossless`), so the
1799- // named refusal that stood here is gone -- the gate that replaced it is
1800- // `a_lossless_libaom_inter_frame_decodes_sample_exact`.
1801- crate::decode::set_lossless(coded_lossless, fctx);
1772+ // lane-av1mixloss: PER-SEGMENT lossless (libaom `decodeframe.c:5205`) --
1773+ // the header parser computes `lossless[segment_id]` for all 8 segments
1774+ // (`qindex == 0` with zero plane deltas, `segment_qindex` applying that
1775+ // segment's own `SEG_LVL_ALT_Q`) and `coded_lossless` = every segment
1776+ // lossless. Everything FRAME-level already keys on the header's fields,
1777+ // exactly as libaom gates them on `features->coded_lossless`/
1778+ // `all_lossless`: `tx_mode` is `Only4x4` only when EVERY segment is
1779+ // lossless, CDEF and the loop-filter levels are forced to 0 only then,
1780+ // and loop restoration only on `all_lossless`. What this decoder lacked
1781+ // was the BLOCK level: every block-decoder rule -- `read_tx_size`'s TX_4X4
1782+ // early return, the suppressed `tx_type`, the Walsh-Hadamard,
1783+ // `is_cfl_allowed`'s narrowing, the 4x4 chroma rasters -- indexes
1784+ // `xd->lossless[segment_id]`, so a frame whose segments DISAGREE codes
1785+ // lossless blocks inside a lossy frame. aomenc WRITES one:
1786+ // `--end-usage=q --cq-level=0 --aq-mode=1` (variance AQ over a lossless
1787+ // base) gives a high-variance segment a positive `SEG_LVL_ALT_Q` while a
1788+ // flat one stays at `qindex == 0`. The table goes in whole and
1789+ // [`decode::lossless`] resolves it per block through the block's own
1790+ // `segment_id` (set by the spec-order `segment_id` read that precedes
1791+ // every mode/transform symbol). Witness:
1792+ // `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact`.
1793+ crate::decode::set_lossless_per_seg(header.lossless, fctx);
18021794 crate::decode::set_bit_depth(bit_depth, fctx);
18031795 // lane-av1mono: the sequence header's `mono_chrome`, set per frame like
18041796 // the bit depth so a mono frame decoded on a thread that last saw a
@@ -2807,27 +2799,26 @@ pub(crate) mod tests {
28072799 (enabled, update_map, inherited, alt_q, feature_frames)
28082800 }
28092801
2810- /// lane-hdrlossless: WITNESS for the one refusal the pilot report left
2811- /// without a proving test -- "a frame mixing lossless and lossy
2812- /// segments". It is a REAL encoder output, not a defensive pin:
2813- /// `--end-usage=q --cq-level=0 --aq-mode=1` (variance AQ over a lossless
2814- /// base) gives a high-variance segment a positive `SEG_LVL_ALT_Q` while a
2815- /// flat segment stays at `qindex == 0` (`aq_variance.c` sets
2816- /// `SEG_LVL_ALT_Q` per segment and only clamps when `base_qindex != 0`,
2817- /// so a lossless base is exactly where the mixed case comes from), and
2818- /// libaom DECODES it -- `xd->lossless[segment_id]` is per segment
2819- /// (`decodeframe.c:5205`), and `read_tx_size` returns TX_4X4 before it
2820- /// reads a symbol (`decodeframe.c:1170`). So the refusal names a
2821- /// capability gap, not a spec-conformant guard, and it must not be
2822- /// deleted until the block-decoder lift lands (see the refusal's own doc
2823- /// in [`super::decode_stream`]). The gate (1) encodes the stream, (2)
2824- /// asserts it REALLY carries a mixed frame (class `gate-blind-to-feature`
2825- /// -- variance AQ over a lossless base is the whole point, not the flag
2826- /// spelling), (3) shows ffmpeg's libaom decoder accepts it, and (4) pins
2827- /// THIS decoder's refusal by exact string.
2828- #[test]
2829- fn a_real_aomenc_mixed_lossless_segment_frame_is_refused_by_name() {
2830- const NAME: &str = "a_real_aomenc_mixed_lossless_segment_frame_is_refused_by_name";
2802+ /// lane-hdrlossless WITNESS → lane-av1mixloss LIFT. `--end-usage=q
2803+ /// --cq-level=0 --aq-mode=1` (variance AQ over a lossless base) gives a
2804+ /// high-variance segment a positive `SEG_LVL_ALT_Q` while a flat segment
2805+ /// stays at `qindex == 0` (`aq_variance.c` sets `SEG_LVL_ALT_Q` per
2806+ /// segment and only clamps when `base_qindex != 0`, so a lossless base is
2807+ /// exactly where the mixed case comes from): a frame MIXING lossless and
2808+ /// lossy segments, which this decoder refused by name until the
2809+ /// per-segment lossless table (libaom `decodeframe.c:5205`,
2810+ /// `xd->lossless[segment_id]`; `read_tx_size` returns TX_4X4 before it
2811+ /// reads a symbol, `decodeframe.c:1170`) landed. Non-vacuity, three ways:
2812+ /// (1) the header census proves the arms REALLY carry a mixed frame
2813+ /// (class `gate-blind-to-feature` -- variance AQ over a lossless base is
2814+ /// the whole point, not the flag spelling), (2) the WHT-unit counter
2815+ /// proves the per-segment lossless reconstruction really ran, and (3)
2816+ /// every decoded plane is compared SAMPLE-EXACT against ffmpeg's libaom,
2817+ /// which accepts the same stream -- so the old refusal named a capability
2818+ /// gap, and this gate now proves the gap closed on a real encoder output.
2819+ #[test]
2820+ fn a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact() {
2821+ const NAME: &str = "a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact";
28312822 if !have_ffmpeg() {
28322823 eprintln!("SKIP {NAME}: no ffmpeg");
28332824 return;
@@ -2836,8 +2827,9 @@ pub(crate) mod tests {
28362827 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
28372828 return;
28382829 }
2839- const REFUSAL: &str = "a frame mixing lossless and lossy segments";
28402830 const FRAMES: usize = 4;
2831+ const WIDTH: usize = 256;
2832+ const HEIGHT: usize = 192;
28412833 // (source, per-arm overrides). `--end-usage=q --cq-level=0` is the
28422834 // lossless base; `--aq-mode=1` is variance AQ, the only aomenc path
28432835 // that sets `SEG_LVL_ALT_Q` with no clamp at base 0 (`aq_variance.c`).
@@ -2859,6 +2851,9 @@ pub(crate) mod tests {
28592851 ),
28602852 ];
28612853 let mut mixed_arms = 0usize;
2854+ // The WHT-unit delta below is a process-wide counter: serialize the
2855+ // arms against the other counter-reading gates.
2856+ let _gate_lock = lock_gate_counters();
28622857 for (src, extra) in &arms {
28632858 let y4m = Command::new("ffmpeg")
28642859 .args([
@@ -2886,7 +2881,7 @@ pub(crate) mod tests {
28862881 String::from_utf8_lossy(&out.stderr)
28872882 );
28882883 let stream = out.stdout;
2889- // (2) the stream really carries a frame the refusal names.
2884+ // (2) the stream really carries a frame the old refusal named.
28902885 let mut parser = Av1Parser::new();
28912886 let (mut pos, mut mixed) = (0usize, 0usize);
28922887 while pos < stream.len() {
@@ -2904,28 +2899,30 @@ pub(crate) mod tests {
29042899 eprintln!("{NAME}: arm {extra:?} coded no mixed frame -- trying the next");
29052900 continue;
29062901 }
2902+ // (3) ours DECODES it, sample-exact against ffmpeg's libaom (the
2903+ // reference decode doubles as the libaom-accepts proof). The
2904+ // WHT-unit delta proves the per-segment lossless reconstruction
2905+ // really ran inside a frame that is NOT `CodedLossless`.
2906+ let before = crate::decode::lossless_wht_units();
2907+ let ours = decode_stream(&stream)
2908+ .unwrap_or_else(|e| panic!("{NAME}: a mixed-lossless frame decodes after the per-segment lift: {e}"));
2909+ let wht_units = crate::decode::lossless_wht_units() - before;
2910+ let refs = ffmpeg_decode_sequence(&stream, WIDTH, HEIGHT, FRAMES);
2911+ assert_eq!(ours.len(), FRAMES, "{NAME}: frame count");
2912+ for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
2913+ for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
2914+ .iter()
2915+ .enumerate()
2916+ {
2917+ let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
2918+ assert_eq!(bad, 0, "{NAME}: arm {extra:?} frame {i} plane {plane}: {bad} samples differ");
2919+ }
2920+ }
2921+ assert!(wht_units > 0, "{NAME}: arm {extra:?} reconstructed no Walsh-Hadamard unit -- the mixed census is lying or the lossless path never ran");
29072922 mixed_arms += 1;
2908- // (3) libaom accepts it: ffmpeg's own libaom decoder produces the
2909- // stream without an error.
2910- let out = run_with_stdin(
2911- Command::new("ffmpeg").args(["-v", "error", "-f", "obu", "-i", "-", "-f", "null", "-"]),
2912- &stream,
2913- );
2914- assert!(
2915- out.status.success(),
2916- "{NAME}: ffmpeg refused a stream with {mixed} mixed-frame(s): {}",
2917- String::from_utf8_lossy(&out.stderr)
2918- );
2919- // (4) ours refuses BY NAME (not by desync).
2920- let err = decode_stream(&stream)
2921- .err()
2922- .map(|e| e.to_string())
2923- .unwrap_or_else(|| panic!("{NAME}: a mixed-lossless frame DECODED -- the lift landed; flip this gate to a pixel-exact witness"));
2924- assert!(
2925- err.contains(REFUSAL),
2926- "{NAME}: expected {REFUSAL:?}, got: {err}"
2923+ eprintln!(
2924+ "{NAME}: arm {extra:?}: {mixed} mixed frame(s), {FRAMES} frames sample-exact vs ffmpeg, {wht_units} WHT units"
29272925 );
2928- eprintln!("{NAME}: arm {extra:?}: {mixed} mixed frame(s), refused by name");
29292926 }
29302927 assert!(
29312928 mixed_arms > 0,
lanes/av1mix.report.mdadded+92 -0
@@ -0,0 +1,92 @@
1+# lane-av1-mixloss : rapport de session (24-09-2026, session Agent22, r1)
2+
3+## État livré
4+- WIP commit **4d5b5397** sur `lane-av1-mixloss` (base 7404c36a). Non pushé, main non touché.
5+- Le lift per-segment lossless est câblé de bout en bout (reprise du travail d'avant la rate limit) :
6+ - `FrameCtx::lossless_per_seg` (table 8 segments, set depuis `stream.rs` via `set_lossless_per_seg`)
7+ - `decode::lossless()` résout par le `cur_segment_id` du bloc (l'ordre segment-id AVANT tx-geometry,
8+ corrigé en session précédente, est en place et documenté)
9+ - `read_tx_size` : TX_4X4 en première ligne (libaom decodeframe.c:1203)
10+ - intrabc var-tx tree gated sur `!lossless(fctx)` (decode_block + decode_leaf8)
11+ - refusal "frame mixing lossless and lossy segments" levé dans stream.rs + refusal_inventory
12+ - witness gate réécrite : `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact`
13+ (3 arms aomenc, WHT-unit counter + comparaison sample-exact ffmpeg)
14+ - compteur `LOSSLESS_WHT_UNITS` ajouté (proof of run)
15+- Le décode réussit sur les 4 frames du mix (256x192, testsrc2/gradients, aomenc --aq-mode=1 --cq-level=0).
16+
17+## Diagnostic de la divergence (session)
18+- Ours vs ffmpeg diverge : Y premier pixel faux à **(40,0)** ; U/V à **(16,0)** (= luma (32,0)).
19+- **Alignement exact de la chaîne rng EC_COEFF avec l'oracle aom sur les TUs 0-18** (luma + chroma),
20+ y compris les trails eob/level/sign/golomb complets (valeurs ET rng identiques). Le parse est sain.
21+- Le fork précis est **TU#19 = luma (40,0)** : au même in-rng 50864, même ctx txb_skip (3), mais le CDF
22+ diffère (notres cdf0=23340 vs oracle 10886) ⇒ pas un désync de parse, une **dérive de l'état CDF**
23+ (classe `cdf-state-drift`, famille av1-cdf-convention-mirror).
24+- Adressé : EC_PRED trace ; les TUs 0-18 alignés. Piste : la trace ISTEP.
25+- Adressé : la divergence entre notres dequant q et l'oracle a déjà émergé en session précédente.
26+
27+## Diagnostic de la divergence (session)
28+- Ours vs ffmpeg diverge : Y premier pixel faux à **(40,0)** ; U/V à **(16,0)** (= luma (32,0)).
29+- **Alignement exact de la chaîne rng EC_COEFF avec l'oracle aom sur les TUs 0-18** (luma + chroma),
30+ y compris les trails eob/level/sign/golomb complets (valeurs ET rng identiques). Le parse est sain.
31+- Le fork précis est **TU#19 = luma (40,0)** : au même in-rng 50864, même ctx txb_skip (3), mais le CDF
32+ diffère (notres cdf0=23340 vs oracle 10886) ⇒ pas un désync de parse, une **dérive de l'état CDF**
33+ (classe `cdf-state-drift`, famille av1-cdf-convention-mirror).
34+
35+## Diagnostic de la divergence (session)
36+- Ours vs ffmpeg diverge : Y premier pixel faux à **(40,0)** ; U/V à **(16,0)** (= luma (32,0)).
37+- **Alignement exact de la chaîne rng EC_COEFF avec l'oracle aom sur les TUs 0-18** (luma + chroma),
38+ y compris les trails eob/level/sign/golomb complets (valeurs ET rng identiques). Le parse est sain.
39+- Le fork précis est **TU#19 = luma (40,0)** : au même in-rng 50864, même ctx txb_skip (3), mais le CDF
40+ diffère (notres cdf0=23340 vs oracle 10886) ⇒ pas un désync de parse, une **dérive de l'état CDF**
41+ (classe `cdf-state-drift`, famille av1-cdf-convention-mirror).
42+
43+## Pistes pour la prochaine session
44+1. Le lead est le **stockage des données CDF** : les TUs 0-18 alignés, Piste : la trace ISTEP.
45+- Vérifier : la divergence entre notres dequant q et l'oracle a déjà émergé en session précédente.
46+
47+## Pistes pour la prochaine session
48+1. Le lead est le **stockage des données CDF** : les TUs 0-18 alignés, Piste : la trace ISTEP.
49+
50+## Notes
51+- Le décode réussit sur les 4 frames du mix (256x192, testsrc2/gradients, aomenc --aq-mode=1 --cq-level=0).
52+
53+## Notes de session (traces)
54+- Tout dans `~/.cache/tmp-av1mix/` : `oraclesteps.txt` (12:33, 8.2MB), `oursteps2.txt` (frais, 4 frames),
55+ `oraclepred2.txt` + `ourpred2.txt` (frais), `oracleistep2.txt` + `ouristep2.txt`, `both.txt`
56+ (run combiné EC_TRACE_COEFF + EC_TRACE_MODE_STEP, LA référence de session), `mixref.raw`,
57+ `mixoursnew.yuv`, `mix.y4m`, `mix.obu`, `mix.enc.err`.
58+- Oracle aomdec : `~/.cache/aom-oracle/build/aomdec`, rung EC_PREDOUT8 pour les pixels prédits.
59+- L'ancien oraclepred.txt (12:27) est partiel : ne pas s'en servir.
60+
61+## Fix-now | deferred(<unblock>) | accepted
62+- `fix-now | deferred(lane suivante) | accepted` : le fix du drift CDF lui-même.
63+ Unbloqué par : re-diff de l'historique d'adaptation du CDF (les valeurs des TUs 0-18 sont
64+ archivées dans les traces), puis comparaison de l'ordre d'application des updates CDF vs l'oracle.
65+
66+## Diagnostic de la divergence (session r2, 24-09-2026, session Agent26-2)
67+
68+- Le « fork CDF » de r1 (TU#19, cdf0 23340 vs 10886) et le « mi(6,0) br=1 ctx=1 non
69+ adapté » du r1-bis sont tous deux des **artefacts de convention d'impression** :
70+ notre `EC_COEFF_STEP tag=all_zero side=` imprime la ligne `txb_skip` **pré**-adaptation
71+ (copie `dbg_txbskip` avant `dec.symbol`, decode.rs), l'oracle instrumenté imprime
72+ **post**-adaptation. 25197 = 26876 - (26876>>4) : une adaptation du même défaut neuf
73+ `AOM_CDF2(5892)` (32768-5892=26876). **Aucune mise à jour CDF manquante.**
74+- Vrai fork : entre la lecture #151 (chroma) et le txb luma de mi(10,0), nous
75+ consommons **9 bits** contre **7 chez l'oracle** — un symbole `tx_size_cat1`
76+ en trop (rng 55700->49918, s=1) lu par `decode_leaf_rect` pour une feuille
77+ rect **16x8 d'un segment lossless** : le `read_tx_size` de libaom rend TX_4X4
78+ AVANT le test `TX_MODE_SELECT` (decodeframe.c:1203), donc l'oracle ne code
79+ aucun symbole de profondeur ici.
80+- Balayage de la classe : `&& !lossless(fctx)` ajouté aux lectures de profondeur
81+ de `decode_leaf_rect`, `decode_block_rect`, `decode_block_rect4`,
82+ `decode_rect4_16_strip`, `decode_block_rect64`, `decode_intra_rect_in_inter`
83+ (`decode_intra_sub8_leaf`, `decode_leaf_rect8`, le lecteur 128-root et
84+ `read_tx_size` l'avaient déjà).
85+- Preuve : mix.obu (cache, non ré-encodé) — chaîne rng EC identique à l'oracle
86+ (9565 all_zero, 2982 eob, valeurs identiques) et **4 frames byte-exact** vs
87+ l'aomdec instrumenté (294912 octets, `cmp` implicite par comparaison de
88+ tableaux). Porte témoin `a_real_aomenc_mixed_lossless_segment_frame_decodes_
89+ sample_exact` verte (3 arms, sample-exact vs ffmpeg, unités WHT comptées).
90+- Instrument de session : sonde `EC_SYMR` ajoutée à
91+ `~/.cache/aom-oracle/src/aom_dsp/bitreader.h` (aom_read_symbol_) — arbre
92+ scratch hors repo.