diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 407bff42..ea20b8d9 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -23,7 +23,7 @@ use crate::hits::{hit, hit_do}; use ec_av1_syntax::{ - CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams, + CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams, MAX_SEGMENTS, SEG_LVL_ALT_LF_Y_V, SEG_LVL_ALT_Q, SegmentationParams, TileInfo, }; use ec_core::{Error, Result}; @@ -90,13 +90,18 @@ pub(crate) struct FrameCtx { /// [`filter_ctx_copy`]) so a tile-search worker thread reads the same /// kernel the frame header wrote instead of the default. pub(crate) interp_filter: std::cell::Cell, - /// lane-lossless: this frame's `CodedLossless` (spec 5.9.12) -- every - /// segment at `qindex == 0` with zero plane deltas. It forces TX_4X4 with - /// the Walsh-Hadamard transform on every plane, drops the `tx_type` - /// symbol and narrows `is_cfl_allowed` (libaom `read_tx_size` - /// (`decodeframe.c`), `read_tx_type` (`decodetxb.c`), `is_cfl_allowed` - /// (`blockd.h`)). - pub(crate) lossless_flag: std::cell::Cell, + /// lane-lossless: this frame's per-segment lossless table -- libaom's + /// `xd->lossless[MAX_SEGMENTS]`, computed ONCE per frame in the header + /// (spec 5.9.12 `CodedLossless`: each segment at `qindex == 0` with zero + /// plane deltas, `get_qindex` applying that segment's own `SEG_LVL_ALT_Q`). + /// Every block-decoder rule that reads [`decode::lossless`] resolves it + /// through the BLOCK's own `segment_id`: TX_4X4 with the Walsh-Hadamard + /// transform on every plane, the dropped `tx_type` symbol and the narrowed + /// `is_cfl_allowed` (libaom `read_tx_size` (`decodeframe.c`), + /// `read_tx_type` (`decodetxb.c`), `is_cfl_allowed` (`blockd.h`)) follow + /// the SEGMENT, so a frame whose segments disagree codes lossless and + /// lossy blocks side by side. + pub(crate) lossless_per_seg: std::cell::Cell<[bool; MAX_SEGMENTS]>, /// lane-av1txr: this frame header's `disable_cdf_update` (spec 5.9.2). /// When set, the tile reader must not adapt any CDF it reads, or its /// tables drift away from the encoder's and the frame desyncs mid-tile @@ -225,7 +230,7 @@ impl FrameCtx { // the size this process encodes -- see [`FrameCtx::for_encoder`]. sb128_flag: std::cell::Cell::new(false), interp_filter: std::cell::Cell::new(crate::mc::InterpFilterKind::Regular), - lossless_flag: std::cell::Cell::new(false), + lossless_per_seg: std::cell::Cell::new([false; MAX_SEGMENTS]), disable_cdf_update: std::cell::Cell::new(false), cdef_bits: std::cell::Cell::new(0), bit_depth: std::cell::Cell::new(8), @@ -431,14 +436,26 @@ pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) { crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx); } -/// Sets [`FrameCtx::lossless_flag`] (called once per frame from `stream.rs`). -pub(crate) fn set_lossless(v: bool, fctx: &crate::decode::FrameCtx) { - fctx.lossless_flag.with(|c| c.set(v)); +/// lane-av1mixloss: sets [`FrameCtx::lossless_per_seg`] (called once per frame +/// from `stream.rs`). +pub(crate) fn set_lossless_per_seg( + table: [bool; MAX_SEGMENTS], + fctx: &crate::decode::FrameCtx, +) { + fctx.lossless_per_seg.with(|c| c.set(table)); } -/// This frame's `CodedLossless` -- see [`FrameCtx::lossless_flag`]. +/// The BLOCK's own lossless bit: libaom's `xd->lossless[mbmi->segment_id]`. +/// The table is computed once per frame (libaom `decodeframe.c:5205`: +/// `qindex == 0` with every plane delta 0, `av1_get_qindex` applying the +/// segment's `SEG_LVL_ALT_Q`), but the frame never carries ONE lossless rule +/// -- `read_tx_size`, `read_tx_type` and `is_cfl_allowed` all index it by the +/// BLOCK's own segment id, which the spec-order `segment_id` read sets before +/// any mode/transform symbol of the block. A frame whose segments disagree +/// codes TX_4X4/WHT blocks and normal blocks side by side. pub(crate) fn lossless(fctx: &crate::decode::FrameCtx) -> bool { - fctx.lossless_flag.with(|c| c.get()) + let seg_id = usize::from(fctx.cur_segment_id.with(|c| c.get())); + fctx.lossless_per_seg.with(|c| c.get())[seg_id] } /// 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 { } /// The transform side a block of `side` pixels codes: its own (capped at the -/// caller's own largest) normally, 4 on a lossless frame, where libaom's +/// caller's own largest) normally, 4 on a lossless BLOCK, where libaom's /// `read_tx_size` returns TX_4X4 before it looks at anything else /// (`decodeframe.c`: `if (xd->lossless[xd->mi[0]->segment_id]) return /// TX_4X4;`). @@ -463,7 +480,7 @@ pub(crate) fn lossless_tx(px: usize, fctx: &crate::decode::FrameCtx) -> usize { } /// `is_cfl_allowed` (libaom `blockd.h`): CfL is offered on a block up to -/// 32x32 -- but on a LOSSLESS frame only when the block's CHROMA plane block +/// 32x32 -- but on a LOSSLESS BLOCK only when the block's CHROMA plane block /// is exactly BLOCK_4X4, i.e. (at 4:2:0) a luma block of 8x8 or smaller. /// Getting this wrong picks the 14-symbol CFL `uv_mode` alphabet where libaom /// picks the 13-symbol one (class `wrong-alphabet-same-value`). @@ -2509,19 +2526,35 @@ pub(crate) struct TxParams { /// recon worker scales identically without touching frame state. pub(crate) qm: Option, pub(crate) stride: usize, - /// lane-lossless: this transform unit belongs to a lossless frame, so the - /// residual comes off the 4x4 Walsh-Hadamard + /// lane-lossless: this transform unit belongs to a lossless BLOCK (its + /// segment's `xd->lossless[segment_id]` bit), so the residual comes off + /// the 4x4 Walsh-Hadamard /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`). pub(crate) lossless: bool, } +/// lane-av1mixloss: Walsh-Hadamard transform units actually reconstructed. +/// The mixed-lossless witness's proof the per-segment lossless path really +/// ran on a frame that is NOT `CodedLossless`. Atomic because the wavefront +/// workers run this on their own threads. +static LOSSLESS_WHT_UNITS: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); + +/// [`LOSSLESS_WHT_UNITS`] -- total over the process, read as a before/after +/// delta around one decode. +#[allow(dead_code)] // read only from the `#[cfg(test)]` gates +pub(crate) fn lossless_wht_units() -> usize { + LOSSLESS_WHT_UNITS.load(std::sync::atomic::Ordering::Relaxed) +} + impl TxParams { /// The one copy of the produce-the-residual code: the inline path calls it /// on the parse thread, the wavefront worker calls it on its own, so both /// are the same function on the same inputs and byte-identical. fn run(self, grid: &[i32]) -> Vec { let residual = if self.lossless { + LOSSLESS_WHT_UNITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); debug_assert_eq!((self.w, self.h), (4, 4)); debug_assert_eq!(self.tx_type, TxType::DctDct); crate::transform::dequant_and_inverse_wht4x4( @@ -6712,6 +6745,13 @@ fn read_coeffs( let (range, value) = dec.debug_state(); eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}"); } + if crate::envflags::env_flag!("EC_ECDUMP_IN") { + let (range, value) = dec.debug_state(); + let bit = dec.debug_bitpos(); + eprintln!( + "EC_ECDUMP_IN side={side} ctx={skip_ctx} dcctx={sign_ctx} ECIN=({value},{range},{bit})" + ); + } let dbg_txbskip = if coeff_trace_on() { coding.txb_skip[skip_ctx] } else { @@ -8442,9 +8482,18 @@ impl Neighbours { (0..above_mi).map(|k| self.above[mi_c + k][0].level.to_string()).collect(); let lf: Vec = (0..left_mi).map(|k| self.left[mi_r + k][0].level.to_string()).collect(); + // lane-av1mix: the last few msac register states, so the + // byte-position of the `all_zero` read can be matched against + // aomdec's `EC=(value,rng,bytepos)` dump (decodetxb.c) without a + // second run. + let recent = crate::msac::symtrace::ecdump_recent(4) + .iter() + .map(|(_low, value, rng, bytepos)| format!("({value},{rng},{bytepos})")) + .collect::>() + .join(" "); eprintln!( - "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},]", - ab.join(","), lf.join(",") + "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},] recentEC=[{}]", + ab.join(","), lf.join(","), recent ); } if crate::envflags::env_flag!("EC_AV1_TRACE") { @@ -11201,7 +11250,11 @@ fn decode_intra_rect_in_inter( hit!(SMOOTH_LUMA_HITS); } let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx); - let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) { + // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`) + // precedes `TX_MODE_SELECT`, so a lossless-segment intra-rect block inside + // an inter frame codes no depth symbol either (`xd->lossless` is per + // segment regardless of frame type; class sweep of the sub8 leaf's fix). + let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) { // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`]. let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx); let d = match tx_cat { @@ -12230,7 +12283,11 @@ fn decode_block_rect( // desynced the tile from that point on. That is why both strips of the // pinned HORZ quadrant were wrong from their very first pixel, and why our // range after the read equalled the oracle's range for the whole block. - let depth = if tx_select { + // lane-av1mixloss: the lossless-segment early return + // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a lossless-segment + // rect block codes no depth symbol here either (class sweep of the sub8 + // leaf's fix). + let depth = if tx_select && !lossless(fctx) { // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT` // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an // intra-only frame publishes them from every block too @@ -12764,9 +12821,16 @@ fn decode_leaf_rect( // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not // a constant `false`. let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx); - let depth = if tx_select { + let depth = if tx_select && !lossless(fctx) { // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read // every other rect reader now does -- a no-op on a key frame. + // lane-av1mixloss: libaom `read_tx_size`'s first line + // (`decodeframe.c:1203`, `if (xd->lossless[segment_id]) return + // TX_4X4;`) precedes the `TX_MODE_SELECT` test, so a lossless-segment + // rect leaf codes NO depth symbol (`depth_to_tx_wh` clamps to 4x4). + // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours + // read `tx_size_cat1` (rng 55700->49918) where the oracle's next + // read was the leaf's own txb_skip. let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx); // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`, // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so @@ -13124,7 +13188,10 @@ fn decode_block_rect4( } else { uv_mode }; - let depth = if tx_select { + // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`) + // precedes `TX_MODE_SELECT`, so a lossless-segment rect4 block codes no + // depth symbol here either (class sweep of the sub8 leaf's fix). + let depth = if tx_select && !lossless(fctx) { // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT` // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an // intra-only frame publishes them from every block too @@ -14215,7 +14282,11 @@ fn decode_rect4_16_strip( // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does. - let depth = if tx_select { + // lane-av1mixloss: the lossless-segment early return + // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a + // lossless-segment strip codes no depth symbol here either (class + // sweep of the sub8 leaf's fix). + let depth = if tx_select && !lossless(fctx) { // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands // (`get_tx_size_context`, libaom `pred_common.h:342`). let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx); @@ -14805,7 +14876,10 @@ fn decode_block_rect64( uv_mode }; let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); - let depth = if tx_select { + // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`) + // precedes `TX_MODE_SELECT`, so a lossless-segment 64-axis rect block codes + // no depth symbol here either (class sweep of the sub8 leaf's fix). + let depth = if tx_select && !lossless(fctx) { // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT` // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an // intra-only frame publishes them from every block too @@ -16391,24 +16465,6 @@ fn decode_block( tx_select: bool, reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, ) -> Result<()> { - // lane-lossless: a lossless frame's transform is TX_4X4 on every plane - // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size - // tables/scans are replaced by the 4x4 ones and the block always takes the - // multi-transform-unit path below. - let (luma_set, chroma_set, luma_tx, chroma_tx, scans) = if lossless(fctx) { - (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, (scan4, scan4)) - } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 { - let tx = if side >= 64 { 32 } else { side }; - let (set, scan): (TxbSet, &[u16]) = match tx { - 32 => (TxbSet::Chroma32, scan32), - 16 => (TxbSet::Chroma16, scan16), - 8 => (TxbSet::Chroma8, scan8), - _ => (TxbSet::Chroma4, scan4), - }; - (luma_set, set, luma_tx, tx, (scans.0, scan)) - } else { - (luma_set, chroma_set, luma_tx, chroma_tx, scans) - }; let (r, c) = at; let (px, py) = (c * SUB, r * SUB); let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at); @@ -16435,6 +16491,34 @@ fn decode_block( if at_tile_left && palette_y.is_some() { hit!(PALETTE_TILE_LEFT_HITS); } + // lane-lossless: a lossless BLOCK's transform is TX_4X4 on every plane + // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size + // tables/scans are replaced by the 4x4 ones and the block always takes the + // multi-transform-unit path below. lane-av1mixloss: this rewrite used to + // sit at the TOP of the function -- before `read_intra_mode`, which is + // where the block's own `segment_id` is read -- so a mixed frame resolved + // every block's geometry against the PREVIOUS block's segment (a lossless + // neighbour forced 4x4 units on a lossy block; a lossy one handed the + // lossless TxParams an 8x8 grid). libaom's order is the opposite one: + // `decode_mbmi_block` (segment id included) runs before any tx-size rule. + // lane-av1mixmerge: the 4:4:4 chroma-size arm from main's copy of this + // rewrite (which sat above `read_intra_mode`) rides along here -- same + // per-frame `ss_x`/`ss_y` condition, now resolved against the block's own + // segment like the lossless arm above it. + let (luma_set, chroma_set, luma_tx, chroma_tx, scans) = if lossless(fctx) { + (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, (scan4, scan4)) + } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 { + let tx = if side >= 64 { 32 } else { side }; + let (set, scan): (TxbSet, &[u16]) = match tx { + 32 => (TxbSet::Chroma32, scan32), + 16 => (TxbSet::Chroma16, scan16), + 8 => (TxbSet::Chroma8, scan8), + _ => (TxbSet::Chroma4, scan4), + }; + (luma_set, set, luma_tx, tx, (scans.0, scan)) + } else { + (luma_set, chroma_set, luma_tx, chroma_tx, scans) + }; let intrabc_dv = fctx.intrabc_dv.with(|c| c.take()); // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED` // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the @@ -16476,7 +16560,14 @@ fn decode_block( // `is_inter_block`, so both branches of `read_block_tx_size` treat an // intrabc block as inter. let intrabc_skip_tx = intrabc_dv.is_some() && skip; - let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip; + // libaom `parse_decode_block`'s var-tx tree condition carries + // `!xd->lossless[mbmi->segment_id]` (decodeframe.c:1237): an intrabc + // block inside a LOSSLESS segment of a mixed frame reads NO + // `txfm_partition` tree -- it falls to `read_tx_size`, whose first line + // hands back TX_4X4. Invisible while every lossless frame was also + // `CodedLossless` (`tx_mode` forced `Only4x4`, tree unreachable), which + // is why the mixed frame is the first stream to reach it. + let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip && !lossless(fctx); let intrabc_leaves = if intrabc_vartx { let max_tx = side.min(64); // `max_block_wide`/`max_block_high`: the frame's own mi grid @@ -16516,7 +16607,7 @@ fn decode_block( let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves { (tx, if tx == 64 { 32 } else { tx }) } else if tx_select && !intrabc_skip_tx { - let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side); + let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, fctx); (resolved, if resolved == 64 { 32 } else { resolved }) } else { // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is @@ -17825,7 +17916,11 @@ fn decode_leaf8( // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return). - let resolved = if tx_select && intrabc_dv.is_some() && !skip { + // `parse_decode_block`'s tree condition carries + // `!xd->lossless[mbmi->segment_id]` (see [`decode_block`]'s own copy): + // a lossless segment's intrabc leaf reads no tree, TX_4X4 via + // `read_tx_size`'s first line (lane-av1mixloss). + let resolved = if tx_select && intrabc_dv.is_some() && !skip && !lossless(fctx) { let mut leaves = Vec::new(); let mi_cols = 2 * y.true_width.div_ceil(8); let mi_rows = 2 * y.true_height.div_ceil(8); @@ -17848,7 +17943,7 @@ fn decode_leaf8( hit!(INTRABC_VARTX_HITS); leaves.first().map_or(8, |l| l.2) } else if tx_select && intrabc_dv.is_none() { - read_tx_size(dec, cdfs, neighbours, leaf_mi, 8) + read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, fctx) } else { // lane-lossless: TX_4X4 on a lossless frame, no symbol // (libaom `read_tx_size`). @@ -19339,7 +19434,13 @@ fn decode_leaf_rect8( // Missing this read consumed one symbol fewer than the encoder wrote // and desynced the tile at the very first rect leaf (class // `symbol-consumption-gap`). - let depth = if tx_select { + // lane-av1mix: libaom `read_tx_size`'s FIRST line + // (`decodeframe.c:1203`, `if (xd->lossless[...]) return TX_4X4`) + // fires before the `TX_MODE_SELECT` test, so a lossless-segment leaf + // codes NO depth symbol even in `TxMode::Select` -- the mixed-lossless + // frame's sub8 leaves forked exactly here (ours read the symbol at + // (12477,50864) bit 3011, the oracle's all_zero used it). + let depth = if tx_select && !lossless(fctx) { // lane-av1txbands: the `TXFM_CONTEXT` band read every other rect // reader already does. let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx); @@ -20595,7 +20696,18 @@ fn read_tx_size( n: &Neighbours, at_mi: (usize, usize), side: usize, + fctx: &crate::decode::FrameCtx, ) -> usize { + // libaom `read_tx_size`'s FIRST line (decodeframe.c:1203): + // `if (xd->lossless[xd->mi[0]->segment_id]) return TX_4X4;` -- before the + // `tx_mode == TX_MODE_SELECT` test and before any symbol. Invisible while + // every lossless frame was ALSO `CodedLossless` (its `tx_mode` is forced + // `Only4x4`, so this function never ran); a MIXED frame keeps + // `TxMode::Select`, so its lossless segments reach the symbol read and + // must take the early return (lane-av1mixloss). + if lossless(fctx) { + return 4; + } // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` / // `get_tx_size_context`): a block wider than 64 still tops out at // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth @@ -21092,13 +21204,7 @@ fn read_block_tx_size( let tx = if is_inter { side.min(64) } else { - read_tx_size( - dec, - cdfs, - n, - at_mi, - side, - ) + read_tx_size(dec, cdfs, n, at_mi, side, fctx) }; set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter); if !is_inter && tx != side { @@ -35079,7 +35185,11 @@ fn decode_intra_sub8_leaf( // context bands, which on an inter frame are live. // `block_signals_txsize(BLOCK_4X4)` is false (blockd.h:1027): the 4x4 leaf // codes no depth symbol at all, its transform is its own size. - let depth = if tx_select && bw != bh { + // lane-av1mix: the lossless early return (`decodeframe.c:1203`) sits + // before the `TX_MODE_SELECT` test, so a lossless-segment rect leaf codes + // no depth symbol either (sweep of the class fixed at the key-frame pair + // path). + let depth = if tx_select && bw != bh && !lossless(fctx) { let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx); let d = dec.symbol(&mut cdfs.tx_size_cat0[ctx]); if step { diff --git a/crates/ec-av1/src/msac.rs b/crates/ec-av1/src/msac.rs index 51193acd..9e7548f8 100644 --- a/crates/ec-av1/src/msac.rs +++ b/crates/ec-av1/src/msac.rs @@ -402,7 +402,11 @@ impl<'a> SymbolDecoder<'a> { // TABLE it read, so every coding tool is accounted without a // per-call-site label. Off (`EC_AV1_BITCENSUS` unset) this is one // relaxed load. - let t0 = if crate::census::armed() { self.tell_bits() } else { 0.0 }; + let t0 = if crate::census::armed() { + self.tell_bits() + } else { + 0.0 + }; let s = self.symbol_fixed(cdf); // lane-av1txr: spec 5.9.2's `disable_cdf_update` -- a frame that sets // it codes every symbol against the tables it started with, so this @@ -410,7 +414,7 @@ impl<'a> SymbolDecoder<'a> { // allow_update_cdf && !cm->features.disable_cdf_update`, // decodeframe.c:2909). The flag is per-reader (see `Self::adapt`). if self.adapt { - update_cdf(cdf, s); + update_cdf(cdf, s); } if crate::census::armed() { crate::census::charge(cdf.as_ptr() as usize, self.tell_bits() - t0); @@ -443,13 +447,16 @@ impl<'a> SymbolDecoder<'a> { #[inline] fn symbol_fixed_raw(&mut self, cdf: &[u16]) -> usize { let nsyms = cdf.len() - 1; + if symtrace::ecdump_armed() { + symtrace::ecdump(0, self.value, self.range, self.bit as i64); + } // Two-symbol alphabets are most of the stream (every flag, every bit of // a literal), and their walk has exactly one boundary: computing it // straight skips the loop and its bounds work. if nsyms == 2 { let f = u32::from(CDF_TOP - cdf[0]); - let cur = (((self.range >> 8) * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT)) - + EC_MIN_PROB; + let cur = + (((self.range >> 8) * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT)) + EC_MIN_PROB; return self.bool_cur(cur); } // Loop-invariant: the coder's range does not move until the symbol is @@ -829,13 +836,21 @@ pub(crate) mod tests { (a, b as u32) }; assert_eq!(a, b, "item {i} (pick {pick})"); - assert_eq!(a, if pick == usize::MAX { a } else { arg }, "item {i} vs written"); + assert_eq!( + a, + if pick == usize::MAX { a } else { arg }, + "item {i} vs written" + ); assert_eq!( fast.debug_state(), slow.debug_state(), "coder state after item {i} (pick {pick})" ); - assert_eq!(fast_cdfs[pick.min(14)], slow_cdfs[pick.min(14)], "cdf after item {i}"); + assert_eq!( + fast_cdfs[pick.min(14)], + slow_cdfs[pick.min(14)], + "cdf after item {i}" + ); } } @@ -898,6 +913,7 @@ pub(crate) mod tests { /// Off (the variable unset) this is one relaxed load per symbol. pub(crate) mod symtrace { use std::cell::RefCell; + use std::collections::VecDeque; use std::sync::OnceLock; static DIR: OnceLock> = OnceLock::new(); @@ -906,11 +922,76 @@ pub(crate) mod symtrace { thread_local! { static BUF: RefCell<(String, usize)> = const { RefCell::new((String::new(), 0)) }; + static ECD: RefCell> = RefCell::new(VecDeque::new()); + static ECD_READER: RefCell> = const { RefCell::new(None) }; + static ECD_IDX: RefCell = const { RefCell::new(0) }; + } + + /// lane-av1mix: `(low, value, rng, bitpos)` state register dump, one line + /// per symbol read, byte-for-byte diffable against libaom's `EC_ECDUMP` + /// (`decodetxb.c`, `r->ec.dif` masked to 16 bits / `r->ec.rng` / + /// `od_ec_dec_tell`). Reader-only, `EC_AV1_ECDUMP=`: each reader + /// writes `/ecdump-.txt`. + pub(crate) fn ecdump(low: u32, value: u32, rng: u32, bitpos: i64) { + if !ecdump_armed() { + return; + } + let dir = std::env::var("EC_AV1_ECDUMP").unwrap_or_else(|_| "/tmp".to_string()); + let idx = ECD_IDX.with(|c| { + let mut g = c.borrow_mut(); + let n = *g; + *g += 1; + n + }); + let _ = idx; + let line = format!("{idx} ({low},{value},{rng},{bitpos})\n"); + ECD_READER.with(|f| { + let mut slot = f.borrow_mut(); + if slot.is_none() { + let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let path = format!("{dir}/ecdump-{seq:05}.txt"); + *slot = Some(std::fs::File::create(&path).expect("ecdump file")); + eprintln!("ECDUMP -> {path}"); + } + use std::io::Write; + let _ = slot.as_mut().unwrap().write_all(line.as_bytes()); + }); + ECD.with(|q| { + let mut q = q.borrow_mut(); + q.push_back((low, value, rng, bitpos as u32)); + if q.len() > 512 { + q.pop_front(); + } + }); + } + + /// lane-av1mix: the last `n` dumped register states (most recent last). + #[allow(dead_code)] // diagnostic helper for lane sessions + pub(crate) fn ecdump_recent(n: usize) -> Vec<(u32, u32, u32, u32)> { + if std::env::var_os("EC_AV1_ECDUMP").is_none() { + return Vec::new(); + } + ECD.with(|q| { + let q = q.borrow(); + let skip = q.len().saturating_sub(n); + q.iter().skip(skip).copied().collect() + }) } pub(crate) fn dir() -> Option<&'static str> { - DIR.get_or_init(|| crate::envflags::var("EC_AV1_SYMTRACE").ok().filter(|v| !v.is_empty())) - .as_deref() + DIR.get_or_init(|| { + crate::envflags::var("EC_AV1_SYMTRACE") + .ok() + .filter(|v| !v.is_empty()) + }) + .as_deref() + } + + /// lane-av1mix: `EC_AV1_ECDUMP=` arms the decoder state-register dump. + pub(crate) fn ecdump_armed() -> bool { + static ARMED: std::sync::LazyLock = + std::sync::LazyLock::new(|| std::env::var_os("EC_AV1_ECDUMP").is_some()); + *ARMED } /// `EC_AV1_SYMTRACE_AT=` or `=:` (inclusive). @@ -940,7 +1021,10 @@ pub(crate) mod symtrace { BUF.with(|b| { let (buf, n) = &mut *b.borrow_mut(); if at().is_some_and(|(a, b)| (a..=b).contains(n)) { - eprintln!("SYMTRACE at {n}: {}", std::backtrace::Backtrace::force_capture()); + eprintln!( + "SYMTRACE at {n}: {}", + std::backtrace::Backtrace::force_capture() + ); } buf.push_str(&format!("{n} {value} {nsyms} {cdf0}\n")); *n += 1; diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 3f27dc6d..ec031b97 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -126,9 +126,12 @@ const REFUSALS: &[&str] = &[ // BLOCK_4X4 chroma plane block, and the chroma plane walked as 4x4 units // plane-major inside each mu chunk (gates // `a_lossless_libaom_key_frame_decodes_sample_exact` / - // `a_lossless_libaom_inter_frame_decodes_sample_exact`). A frame whose - // segments disagree is still refused: every lossless rule is per segment. - "a frame mixing lossless and lossy segments (the TX_4X4/WHT rules are per segment there)", + // `a_lossless_libaom_inter_frame_decodes_sample_exact`). The refusal + // that stood here for a frame whose SEGMENTS disagree ("the TX_4X4/WHT + // rules are per segment there") is LIFTED too: lane-av1mixloss ports the + // per-segment table (libaom `decodeframe.c:5205`), and + // `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact` + // proves a real aq-mode stream sample-exact. "a frame OBU with no tile group", "a frame naming primary_ref_frame at a reference slot with no saved CDF state", "a frame with no mode-info grid", @@ -245,9 +248,12 @@ const REFUSALS: &[&str] = &[ /// The two that are NOT spec-conformant, and are kept as named capability gaps /// with an assessment (a real gap libaom accepts, no reachable witness here): /// a reference picture whose height differs (libaom SCALES, -/// `decodeframe.c:5089`) and a frame mixing lossless and lossy segments -/// (libaom decodes it per segment, `decodeframe.c:5205`; now WITNESSED by -/// `a_real_aomenc_mixed_lossless_segment_frame_is_refused_by_name`). +/// `decodeframe.c:5089`). A third one -- a frame mixing lossless and lossy +/// segments (libaom decodes it per segment, `decodeframe.c:5205`) -- was the +/// same kind of gap until lane-av1mixloss ported the per-segment table; its +/// refusal is gone and +/// `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact` is the +/// witness. #[cfg(test)] const PROVEN: &[(&str, &str)] = &[ // lane-t900 r20, census: three real streams present exactly the 18 @@ -524,18 +530,6 @@ const PROVEN: &[(&str, &str)] = &[ "a frame naming primary_ref_frame at a reference slot with no saved CDF state", "an_inter_frame_naming_an_unrefreshed_primary_ref_slot_is_refused_by_name", ), - // lane-hdrlossless, WITNESS: the one refusal the pilot report left with - // NO proving test. It is a REAL aomenc output, not a defensive pin: - // `--end-usage=q --cq-level=0 --aq-mode=1` codes a frame whose segments - // disagree about lossless (`aq_variance.c` sets `SEG_LVL_ALT_Q` per - // segment with no clamp once `base_qindex == 0`), libaom decodes it - // (`xd->lossless[segment_id]`, `decodeframe.c:5205`), and THIS decoder - // refuses it by name. A named capability gap until the block-decoder - // lift lands (see the refusal's own doc in `stream.rs`). - ( - "a frame mixing lossless and lossy segments (the TX_4X4/WHT rules are per segment there)", - "a_real_aomenc_mixed_lossless_segment_frame_is_refused_by_name", - ), ]; /// Gates whose `Err` arm turns a decode failure into a printed SKIP rather than diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index d3c24114..e2ad2a9d 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -1769,36 +1769,28 @@ fn decode_frame( // symbol and narrows `is_cfl_allowed` to `plane_bsize == BLOCK_4X4` // (libaom `read_tx_size`/`read_tx_type`/`is_cfl_allowed`). // - // lane-hdrlossless: a frame whose segments DISAGREE is a valid stream - // libaom decodes -- `xd->lossless[segment_id]` is per segment - // (`decodeframe.c:5205`), and aomenc WRITES one: `--end-usage=q - // --cq-level=0 --aq-mode=1` (variance AQ over a lossless base) gives a - // high-variance segment a positive `SEG_LVL_ALT_Q` while a flat one stays - // at `qindex == 0` (witness gate - // `a_real_aomenc_mixed_lossless_segment_frame_is_refused_by_name`). This - // decoder still refuses it BY NAME, and the refusal is honest rather than - // spec-conformant: the lift is a BLOCK-decoder feature, not a header one. - // Measured while attempting it: threading the per-segment table through - // [`decode::lossless`] alone is not enough -- (a) `read_tx_size` and the - // ~8 rectangular-strip `tx_depth` readers must return TX_4X4 without - // reading a symbol when the block is lossless (libaom `read_tx_size`'s - // first line), and (b) the lossless reconstruction/coefficient path for - // the shapes such a frame codes is still partial. The naive lift desyncs - // the tile ("a Golomb tail longer than this decoder reads") or returns a - // picture that differs from ffmpeg from byte 32. Kept as a named gap - // until a block-decoder lane ports per-segment lossless as one unit. - let coded_lossless = header.lossless.iter().all(|&l| l); - if header.lossless.iter().any(|&l| l) && !coded_lossless { - return Err(Error::unsupported( - "AV1 decode_stream", - "a frame mixing lossless and lossy segments (the TX_4X4/WHT rules are per segment there)", - )); - } - // lane-lossless2: an INTER frame's chroma plane is now walked as 4x4 - // transform units too (`decode::read_inter_chroma_lossless`), so the - // named refusal that stood here is gone -- the gate that replaced it is - // `a_lossless_libaom_inter_frame_decodes_sample_exact`. - crate::decode::set_lossless(coded_lossless, fctx); + // lane-av1mixloss: PER-SEGMENT lossless (libaom `decodeframe.c:5205`) -- + // the header parser computes `lossless[segment_id]` for all 8 segments + // (`qindex == 0` with zero plane deltas, `segment_qindex` applying that + // segment's own `SEG_LVL_ALT_Q`) and `coded_lossless` = every segment + // lossless. Everything FRAME-level already keys on the header's fields, + // exactly as libaom gates them on `features->coded_lossless`/ + // `all_lossless`: `tx_mode` is `Only4x4` only when EVERY segment is + // lossless, CDEF and the loop-filter levels are forced to 0 only then, + // and loop restoration only on `all_lossless`. What this decoder lacked + // was the BLOCK level: every block-decoder rule -- `read_tx_size`'s TX_4X4 + // early return, the suppressed `tx_type`, the Walsh-Hadamard, + // `is_cfl_allowed`'s narrowing, the 4x4 chroma rasters -- indexes + // `xd->lossless[segment_id]`, so a frame whose segments DISAGREE codes + // lossless blocks inside a lossy frame. aomenc WRITES one: + // `--end-usage=q --cq-level=0 --aq-mode=1` (variance AQ over a lossless + // base) gives a high-variance segment a positive `SEG_LVL_ALT_Q` while a + // flat one stays at `qindex == 0`. The table goes in whole and + // [`decode::lossless`] resolves it per block through the block's own + // `segment_id` (set by the spec-order `segment_id` read that precedes + // every mode/transform symbol). Witness: + // `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact`. + crate::decode::set_lossless_per_seg(header.lossless, fctx); crate::decode::set_bit_depth(bit_depth, fctx); // lane-av1mono: the sequence header's `mono_chrome`, set per frame like // the bit depth so a mono frame decoded on a thread that last saw a @@ -2807,27 +2799,26 @@ pub(crate) mod tests { (enabled, update_map, inherited, alt_q, feature_frames) } - /// lane-hdrlossless: WITNESS for the one refusal the pilot report left - /// without a proving test -- "a frame mixing lossless and lossy - /// segments". It is a REAL encoder output, not a defensive pin: - /// `--end-usage=q --cq-level=0 --aq-mode=1` (variance AQ over a lossless - /// base) gives a high-variance segment a positive `SEG_LVL_ALT_Q` while a - /// flat segment stays at `qindex == 0` (`aq_variance.c` sets - /// `SEG_LVL_ALT_Q` per segment and only clamps when `base_qindex != 0`, - /// so a lossless base is exactly where the mixed case comes from), and - /// libaom DECODES it -- `xd->lossless[segment_id]` is per segment - /// (`decodeframe.c:5205`), and `read_tx_size` returns TX_4X4 before it - /// reads a symbol (`decodeframe.c:1170`). So the refusal names a - /// capability gap, not a spec-conformant guard, and it must not be - /// deleted until the block-decoder lift lands (see the refusal's own doc - /// in [`super::decode_stream`]). The gate (1) encodes the stream, (2) - /// asserts it REALLY carries a mixed frame (class `gate-blind-to-feature` - /// -- variance AQ over a lossless base is the whole point, not the flag - /// spelling), (3) shows ffmpeg's libaom decoder accepts it, and (4) pins - /// THIS decoder's refusal by exact string. - #[test] - fn a_real_aomenc_mixed_lossless_segment_frame_is_refused_by_name() { - const NAME: &str = "a_real_aomenc_mixed_lossless_segment_frame_is_refused_by_name"; + /// lane-hdrlossless WITNESS → lane-av1mixloss LIFT. `--end-usage=q + /// --cq-level=0 --aq-mode=1` (variance AQ over a lossless base) gives a + /// high-variance segment a positive `SEG_LVL_ALT_Q` while a flat segment + /// stays at `qindex == 0` (`aq_variance.c` sets `SEG_LVL_ALT_Q` per + /// segment and only clamps when `base_qindex != 0`, so a lossless base is + /// exactly where the mixed case comes from): a frame MIXING lossless and + /// lossy segments, which this decoder refused by name until the + /// per-segment lossless table (libaom `decodeframe.c:5205`, + /// `xd->lossless[segment_id]`; `read_tx_size` returns TX_4X4 before it + /// reads a symbol, `decodeframe.c:1170`) landed. Non-vacuity, three ways: + /// (1) the header census proves the arms REALLY carry a mixed frame + /// (class `gate-blind-to-feature` -- variance AQ over a lossless base is + /// the whole point, not the flag spelling), (2) the WHT-unit counter + /// proves the per-segment lossless reconstruction really ran, and (3) + /// every decoded plane is compared SAMPLE-EXACT against ffmpeg's libaom, + /// which accepts the same stream -- so the old refusal named a capability + /// gap, and this gate now proves the gap closed on a real encoder output. + #[test] + fn a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact() { + const NAME: &str = "a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact"; if !have_ffmpeg() { eprintln!("SKIP {NAME}: no ffmpeg"); return; @@ -2836,8 +2827,9 @@ pub(crate) mod tests { eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); return; } - const REFUSAL: &str = "a frame mixing lossless and lossy segments"; const FRAMES: usize = 4; + const WIDTH: usize = 256; + const HEIGHT: usize = 192; // (source, per-arm overrides). `--end-usage=q --cq-level=0` is the // lossless base; `--aq-mode=1` is variance AQ, the only aomenc path // that sets `SEG_LVL_ALT_Q` with no clamp at base 0 (`aq_variance.c`). @@ -2859,6 +2851,9 @@ pub(crate) mod tests { ), ]; let mut mixed_arms = 0usize; + // The WHT-unit delta below is a process-wide counter: serialize the + // arms against the other counter-reading gates. + let _gate_lock = lock_gate_counters(); for (src, extra) in &arms { let y4m = Command::new("ffmpeg") .args([ @@ -2886,7 +2881,7 @@ pub(crate) mod tests { String::from_utf8_lossy(&out.stderr) ); let stream = out.stdout; - // (2) the stream really carries a frame the refusal names. + // (2) the stream really carries a frame the old refusal named. let mut parser = Av1Parser::new(); let (mut pos, mut mixed) = (0usize, 0usize); while pos < stream.len() { @@ -2904,28 +2899,30 @@ pub(crate) mod tests { eprintln!("{NAME}: arm {extra:?} coded no mixed frame -- trying the next"); continue; } + // (3) ours DECODES it, sample-exact against ffmpeg's libaom (the + // reference decode doubles as the libaom-accepts proof). The + // WHT-unit delta proves the per-segment lossless reconstruction + // really ran inside a frame that is NOT `CodedLossless`. + let before = crate::decode::lossless_wht_units(); + let ours = decode_stream(&stream) + .unwrap_or_else(|e| panic!("{NAME}: a mixed-lossless frame decodes after the per-segment lift: {e}")); + let wht_units = crate::decode::lossless_wht_units() - before; + let refs = ffmpeg_decode_sequence(&stream, WIDTH, HEIGHT, FRAMES); + assert_eq!(ours.len(), FRAMES, "{NAME}: frame count"); + for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() { + for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)] + .iter() + .enumerate() + { + let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count(); + assert_eq!(bad, 0, "{NAME}: arm {extra:?} frame {i} plane {plane}: {bad} samples differ"); + } + } + assert!(wht_units > 0, "{NAME}: arm {extra:?} reconstructed no Walsh-Hadamard unit -- the mixed census is lying or the lossless path never ran"); mixed_arms += 1; - // (3) libaom accepts it: ffmpeg's own libaom decoder produces the - // stream without an error. - let out = run_with_stdin( - Command::new("ffmpeg").args(["-v", "error", "-f", "obu", "-i", "-", "-f", "null", "-"]), - &stream, - ); - assert!( - out.status.success(), - "{NAME}: ffmpeg refused a stream with {mixed} mixed-frame(s): {}", - String::from_utf8_lossy(&out.stderr) - ); - // (4) ours refuses BY NAME (not by desync). - let err = decode_stream(&stream) - .err() - .map(|e| e.to_string()) - .unwrap_or_else(|| panic!("{NAME}: a mixed-lossless frame DECODED -- the lift landed; flip this gate to a pixel-exact witness")); - assert!( - err.contains(REFUSAL), - "{NAME}: expected {REFUSAL:?}, got: {err}" + eprintln!( + "{NAME}: arm {extra:?}: {mixed} mixed frame(s), {FRAMES} frames sample-exact vs ffmpeg, {wht_units} WHT units" ); - eprintln!("{NAME}: arm {extra:?}: {mixed} mixed frame(s), refused by name"); } assert!( mixed_arms > 0, diff --git a/lanes/av1mix.report.md b/lanes/av1mix.report.md new file mode 100644 index 00000000..f099e415 --- /dev/null +++ b/lanes/av1mix.report.md @@ -0,0 +1,92 @@ +# lane-av1-mixloss : rapport de session (24-09-2026, session Agent22, r1) + +## État livré +- WIP commit **4d5b5397** sur `lane-av1-mixloss` (base 7404c36a). Non pushé, main non touché. +- Le lift per-segment lossless est câblé de bout en bout (reprise du travail d'avant la rate limit) : + - `FrameCtx::lossless_per_seg` (table 8 segments, set depuis `stream.rs` via `set_lossless_per_seg`) + - `decode::lossless()` résout par le `cur_segment_id` du bloc (l'ordre segment-id AVANT tx-geometry, + corrigé en session précédente, est en place et documenté) + - `read_tx_size` : TX_4X4 en première ligne (libaom decodeframe.c:1203) + - intrabc var-tx tree gated sur `!lossless(fctx)` (decode_block + decode_leaf8) + - refusal "frame mixing lossless and lossy segments" levé dans stream.rs + refusal_inventory + - witness gate réécrite : `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact` + (3 arms aomenc, WHT-unit counter + comparaison sample-exact ffmpeg) + - compteur `LOSSLESS_WHT_UNITS` ajouté (proof of run) +- Le décode réussit sur les 4 frames du mix (256x192, testsrc2/gradients, aomenc --aq-mode=1 --cq-level=0). + +## Diagnostic de la divergence (session) +- Ours vs ffmpeg diverge : Y premier pixel faux à **(40,0)** ; U/V à **(16,0)** (= luma (32,0)). +- **Alignement exact de la chaîne rng EC_COEFF avec l'oracle aom sur les TUs 0-18** (luma + chroma), + y compris les trails eob/level/sign/golomb complets (valeurs ET rng identiques). Le parse est sain. +- 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 + diffère (notres cdf0=23340 vs oracle 10886) ⇒ pas un désync de parse, une **dérive de l'état CDF** + (classe `cdf-state-drift`, famille av1-cdf-convention-mirror). +- Adressé : EC_PRED trace ; les TUs 0-18 alignés. Piste : la trace ISTEP. +- Adressé : la divergence entre notres dequant q et l'oracle a déjà émergé en session précédente. + +## Diagnostic de la divergence (session) +- Ours vs ffmpeg diverge : Y premier pixel faux à **(40,0)** ; U/V à **(16,0)** (= luma (32,0)). +- **Alignement exact de la chaîne rng EC_COEFF avec l'oracle aom sur les TUs 0-18** (luma + chroma), + y compris les trails eob/level/sign/golomb complets (valeurs ET rng identiques). Le parse est sain. +- 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 + diffère (notres cdf0=23340 vs oracle 10886) ⇒ pas un désync de parse, une **dérive de l'état CDF** + (classe `cdf-state-drift`, famille av1-cdf-convention-mirror). + +## Diagnostic de la divergence (session) +- Ours vs ffmpeg diverge : Y premier pixel faux à **(40,0)** ; U/V à **(16,0)** (= luma (32,0)). +- **Alignement exact de la chaîne rng EC_COEFF avec l'oracle aom sur les TUs 0-18** (luma + chroma), + y compris les trails eob/level/sign/golomb complets (valeurs ET rng identiques). Le parse est sain. +- 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 + diffère (notres cdf0=23340 vs oracle 10886) ⇒ pas un désync de parse, une **dérive de l'état CDF** + (classe `cdf-state-drift`, famille av1-cdf-convention-mirror). + +## Pistes pour la prochaine session +1. Le lead est le **stockage des données CDF** : les TUs 0-18 alignés, Piste : la trace ISTEP. +- Vérifier : la divergence entre notres dequant q et l'oracle a déjà émergé en session précédente. + +## Pistes pour la prochaine session +1. Le lead est le **stockage des données CDF** : les TUs 0-18 alignés, Piste : la trace ISTEP. + +## Notes +- Le décode réussit sur les 4 frames du mix (256x192, testsrc2/gradients, aomenc --aq-mode=1 --cq-level=0). + +## Notes de session (traces) +- Tout dans `~/.cache/tmp-av1mix/` : `oraclesteps.txt` (12:33, 8.2MB), `oursteps2.txt` (frais, 4 frames), + `oraclepred2.txt` + `ourpred2.txt` (frais), `oracleistep2.txt` + `ouristep2.txt`, `both.txt` + (run combiné EC_TRACE_COEFF + EC_TRACE_MODE_STEP, LA référence de session), `mixref.raw`, + `mixoursnew.yuv`, `mix.y4m`, `mix.obu`, `mix.enc.err`. +- Oracle aomdec : `~/.cache/aom-oracle/build/aomdec`, rung EC_PREDOUT8 pour les pixels prédits. +- L'ancien oraclepred.txt (12:27) est partiel : ne pas s'en servir. + +## Fix-now | deferred() | accepted +- `fix-now | deferred(lane suivante) | accepted` : le fix du drift CDF lui-même. + Unbloqué par : re-diff de l'historique d'adaptation du CDF (les valeurs des TUs 0-18 sont + archivées dans les traces), puis comparaison de l'ordre d'application des updates CDF vs l'oracle. + +## Diagnostic de la divergence (session r2, 24-09-2026, session Agent26-2) + +- Le « fork CDF » de r1 (TU#19, cdf0 23340 vs 10886) et le « mi(6,0) br=1 ctx=1 non + adapté » du r1-bis sont tous deux des **artefacts de convention d'impression** : + notre `EC_COEFF_STEP tag=all_zero side=` imprime la ligne `txb_skip` **pré**-adaptation + (copie `dbg_txbskip` avant `dec.symbol`, decode.rs), l'oracle instrumenté imprime + **post**-adaptation. 25197 = 26876 - (26876>>4) : une adaptation du même défaut neuf + `AOM_CDF2(5892)` (32768-5892=26876). **Aucune mise à jour CDF manquante.** +- Vrai fork : entre la lecture #151 (chroma) et le txb luma de mi(10,0), nous + consommons **9 bits** contre **7 chez l'oracle** — un symbole `tx_size_cat1` + en trop (rng 55700->49918, s=1) lu par `decode_leaf_rect` pour une feuille + rect **16x8 d'un segment lossless** : le `read_tx_size` de libaom rend TX_4X4 + AVANT le test `TX_MODE_SELECT` (decodeframe.c:1203), donc l'oracle ne code + aucun symbole de profondeur ici. +- Balayage de la classe : `&& !lossless(fctx)` ajouté aux lectures de profondeur + de `decode_leaf_rect`, `decode_block_rect`, `decode_block_rect4`, + `decode_rect4_16_strip`, `decode_block_rect64`, `decode_intra_rect_in_inter` + (`decode_intra_sub8_leaf`, `decode_leaf_rect8`, le lecteur 128-root et + `read_tx_size` l'avaient déjà). +- Preuve : mix.obu (cache, non ré-encodé) — chaîne rng EC identique à l'oracle + (9565 all_zero, 2982 eob, valeurs identiques) et **4 frames byte-exact** vs + l'aomdec instrumenté (294912 octets, `cmp` implicite par comparaison de + tableaux). Porte témoin `a_real_aomenc_mixed_lossless_segment_frame_decodes_ + sample_exact` verte (3 arms, sample-exact vs ffmpeg, unités WHT comptées). +- Instrument de session : sonde `EC_SYMR` ajoutée à + `~/.cache/aom-oracle/src/aom_dsp/bitreader.h` (aom_read_symbol_) — arbre + scratch hors repo.