diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index 4f9d64ae..2949967d 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -3860,6 +3860,24 @@ pub const TXB_SKIP_LUMA_8: [u16; 3] = [31957, 32768, 0]; /// TXB_SKIP_LUMA_8_Q3, q-context 3: the same table as [`TXB_SKIP_LUMA_8`], for `base_q_idx` 121..=255. pub const TXB_SKIP_LUMA_8_Q3: [u16; 3] = [31903, 32768, 0]; +/// lane-lossless: `av1_default_txb_skip_cdfs[q][TX_4X4][10..13]` +/// (`av1/common/token_cdfs.h:76`), the chroma `txb_skip` rows libaom's +/// `get_txb_ctx` reaches through the `+10` offset -- a chroma plane block +/// LARGER than its transform. At TX_4X4 that only happens on a lossless +/// frame, which is why every q-context but 0 (`base_q_idx <= 20`) leaves +/// them at the neutral 16384. +pub const TXB_SKIP_CHROMA_4_BIG_Q0: [[u16; 3]; 3] = + [[9961, 32768, 0], [30242, 32768, 0], [32117, 32768, 0]]; +/// [`TXB_SKIP_CHROMA_4_BIG_Q0`] for q-context 1. +pub const TXB_SKIP_CHROMA_4_BIG_Q1: [[u16; 3]; 3] = + [[16384, 32768, 0], [16384, 32768, 0], [16384, 32768, 0]]; +/// [`TXB_SKIP_CHROMA_4_BIG_Q0`] for q-context 2. +pub const TXB_SKIP_CHROMA_4_BIG: [[u16; 3]; 3] = + [[16384, 32768, 0], [16384, 32768, 0], [16384, 32768, 0]]; +/// [`TXB_SKIP_CHROMA_4_BIG_Q0`] for q-context 3. +pub const TXB_SKIP_CHROMA_4_BIG_Q3: [[u16; 3]; 3] = + [[16384, 32768, 0], [16384, 32768, 0], [16384, 32768, 0]]; + /// TXB_SKIP_CHROMA_4_Q0, q-context 0: the same table as [`TXB_SKIP_CHROMA_4`], for `base_q_idx` 0..=20. pub const TXB_SKIP_CHROMA_4_Q0: [[u16; 3]; 3] = [[7654, 32768, 0], [19473, 32768, 0], [29984, 32768, 0]]; diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 59a5603b..244f42f2 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -364,7 +364,11 @@ pub(crate) struct Cdfs { /// The all-zero flag of an 8x8 chroma transform. pub txb_skip_chroma_8: [[u16; 3]; 3], /// The all-zero flag of a 4x4 chroma transform. - pub txb_skip_chroma_4: [[u16; 3]; 3], + /// lane-lossless: SIX rows, like [`Self::txb_skip_chroma_32`] -- the last + /// three are `get_txb_ctx`'s `+10` rows (chroma plane block bigger than + /// its transform), which a lossless frame's TX_4X4 chroma reaches at + /// every block above 8x8. + pub txb_skip_chroma_4: [[u16; 3]; 6], /// The end-of-block group of a 16x16 luma transform. pub eob_pt_256_luma: [u16; 10], /// The end-of-block group of an 8x8 luma transform. @@ -1031,13 +1035,23 @@ impl Cdfs { cdf::TXB_SKIP_CHROMA_8, cdf::TXB_SKIP_CHROMA_8_Q3, ), - txb_skip_chroma_4: pick( - q_ctx, - cdf::TXB_SKIP_CHROMA_4_Q0, - cdf::TXB_SKIP_CHROMA_4_Q1, - cdf::TXB_SKIP_CHROMA_4, - cdf::TXB_SKIP_CHROMA_4_Q3, - ), + txb_skip_chroma_4: { + let small = pick( + q_ctx, + cdf::TXB_SKIP_CHROMA_4_Q0, + cdf::TXB_SKIP_CHROMA_4_Q1, + cdf::TXB_SKIP_CHROMA_4, + cdf::TXB_SKIP_CHROMA_4_Q3, + ); + let big = pick( + q_ctx, + cdf::TXB_SKIP_CHROMA_4_BIG_Q0, + cdf::TXB_SKIP_CHROMA_4_BIG_Q1, + cdf::TXB_SKIP_CHROMA_4_BIG, + cdf::TXB_SKIP_CHROMA_4_BIG_Q3, + ); + [small[0], small[1], small[2], big[0], big[1], big[2]] + }, eob_pt_256_luma: pick( q_ctx, cdf::EOB_PT_256_LUMA_Q0, diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 83946ada..16c06bc9 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -69,6 +69,13 @@ pub(crate) struct FrameCtx { pub(crate) capture_stages: std::cell::Cell, pub(crate) stages: std::cell::RefCell>, pub(crate) sb128_flag: 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, pub(crate) cdef_bits: std::cell::Cell, pub(crate) bit_depth: std::cell::Cell, pub(crate) superres: std::cell::Cell<(u32, u32)>, @@ -152,6 +159,7 @@ impl FrameCtx { pub(crate) fn new() -> Self { Self { sb128_flag: std::cell::Cell::new(false), + lossless_flag: std::cell::Cell::new(false), cdef_bits: std::cell::Cell::new(0), bit_depth: std::cell::Cell::new(8), superres: std::cell::Cell::new((0, 8)), @@ -325,6 +333,38 @@ 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)); +} + +/// This frame's `CodedLossless` -- see [`FrameCtx::lossless_flag`]. +pub(crate) fn lossless(fctx: &crate::decode::FrameCtx) -> bool { + fctx.lossless_flag.with(|c| c.get()) +} + +/// 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 +/// `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;`). +pub(crate) fn lossless_tx(px: usize, fctx: &crate::decode::FrameCtx) -> usize { + if lossless(fctx) { 4 } else { px } +} + +/// `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 +/// 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`). +pub(crate) fn cfl_allowed_px(bw: usize, bh: usize, fctx: &crate::decode::FrameCtx) -> bool { + if lossless(fctx) { + bw <= 8 && bh <= 8 + } else { + bw <= 32 && bh <= 32 + } +} + fn sb128(fctx: &crate::decode::FrameCtx) -> bool { fctx.sb128_flag.with(|c| c.get()) } @@ -2131,6 +2171,11 @@ pub(crate) struct TxParams { pub(crate) ac_delta: i32, pub(crate) tx_type: TxType, pub(crate) stride: usize, + /// lane-lossless: this transform unit belongs to a lossless frame, 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, } impl TxParams { @@ -2138,10 +2183,18 @@ impl TxParams { /// 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 = dequant_and_inverse_typed_wh( - grid, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta, - self.tx_type, - ); + let residual = if self.lossless { + debug_assert_eq!((self.w, self.h), (4, 4)); + debug_assert_eq!(self.tx_type, TxType::DctDct); + crate::transform::dequant_and_inverse_wht4x4( + grid, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta, + ) + } else { + dequant_and_inverse_typed_wh( + grid, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta, + self.tx_type, + ) + }; // An all-zero grid transforms to the empty marker, and a strided copy // of zeros is still zeros: the marker passes straight through. if residual.is_empty() { @@ -8848,7 +8901,7 @@ fn read_intra_mode_rect( // through -- a caller passing `true` for a >32 strip used to pick the // 14-symbol CFL CDF, same value but a different range (class // wrong-alphabet-same-value). - let cfl = cfl && bw <= 32 && bh <= 32; + let cfl = cfl && cfl_allowed_px(bw, bh, fctx); let uv_mode = if !has_chroma { DC_PRED } else if cfl { @@ -9100,7 +9153,18 @@ struct RectStripModes { /// TX_32X16`) and only the second reaches a square -- the reason /// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is /// already square) mis-tiled 1:4 strips. -fn depth_to_tx_wh(bw: usize, bh: usize, depth: usize) -> (usize, usize) { +fn depth_to_tx_wh( + bw: usize, + bh: usize, + depth: usize, + fctx: &crate::decode::FrameCtx, +) -> (usize, usize) { + // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom + // `read_tx_size`: the lossless early return comes before + // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here. + if lossless(fctx) { + return (4, 4); + } let (mut w, mut h) = (bw.min(64), bh.min(64)); for _ in 0..depth { match w.cmp(&h) { @@ -9501,6 +9565,58 @@ fn decode_rect_split( m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, fctx, ); (zero.clone(), zero) + } else if lossless(fctx) { + // lane-lossless: the strip's chroma plane block is coded as 4x4 + // transform units too (libaom `read_tx_size` returns TX_4X4 for every + // plane), PLANE-MAJOR inside the block -- U's units first, then V's + // (`decode_token_recon_block`'s mu-chunk loop, measured against + // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1, + // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10` + // offset (our `+3` row base) whenever the plane block is bigger than + // the transform. + let scan4 = default_scan(4); + let offset = (chroma_w > 4 || chroma_h > 4).then_some(3); + let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4); + let mut last = [Grid::Zero(16), Grid::Zero(16)]; + for plane_idx in 1..=2 { + for cu_row in 0..ch_n { + for cu_col in 0..cw_n { + let luma_span = 8; + let cu_mi = ( + mi_r + cu_row * (luma_span / MI), + mi_c + cu_col * (luma_span / MI), + ); + let cu_around = neighbours.around_mi(cu_mi, luma_span); + let cu_reach = tu_reach( + bw, bh, + cu_col * luma_span, cu_row * luma_span, luma_span, + block_reach, px, py, y.width, y.height, fctx, + ); + let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4); + if let Some((ub, vb)) = &m.palette_uv { + set_palette_pred( + if plane_idx == 1 { ub.clone() } else { vb.clone() }, + fctx, + ); + } + let plane = if plane_idx == 1 { &mut *u } else { &mut *v }; + let grid = read_plane( + dec, cdfs, TxbSet::Chroma4, &scan4, plane_idx, + cu_around[plane_idx], m.mode, m.uv_predict_mode, + m.angle_delta_uv, cu_reach, plane, cu_x, cu_y, 4, 4, + base_q_idx, + m.alpha.zip(ac).map(|((au, av), ac)| { + (if plane_idx == 1 { au } else { av }, ac) + }), + None, offset, m.smooth_neighbor_uv, fctx, + )?; + neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_idx, &grid); + last[plane_idx - 1] = grid; + } + } + } + let [ug, vg] = last; + (ug, vg) } else { let (chroma_set, chroma_scan) = chroma.expect("refused above when None"); // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size @@ -10073,7 +10189,7 @@ fn decode_intra_rect_in_inter( // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the // superblock-level strip reads the no-CFL alphabet -- the same split // [`read_intra_mode_rect`] makes for [`decode_block_rect64`]. - let cfl_allowed = bw.max(bh) <= 32; + let cfl_allowed = cfl_allowed_px(bw, bh, fctx); let uv_mode = if cfl_allowed { dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { @@ -10217,7 +10333,7 @@ fn decode_intra_rect_in_inter( } else { 0 }; - if depth != 0 { + if depth != 0 || lossless(fctx) { hit!(TX_DEPTH_HITS); // lane-intrasplit r1: a split intra strip in an inter frame walks the // key frame's own per-TU path ([`decode_rect_split`] below); what was @@ -10236,7 +10352,7 @@ fn decode_intra_rect_in_inter( if crate::envflags::env_flag!("EC_SPLITSTRIP") { eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}"); } - let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); + let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h, // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block // of an inter frame, intra ones included -- with the skip term 0 it @@ -10430,13 +10546,13 @@ fn decode_block_rect( } else { 0 }; - if depth != 0 { + if depth != 0 || lossless(fctx) { hit!(TX_DEPTH_HITS); // lane-rectsplit r1: a split transform is predicted and reconstructed // per transform unit, each unit taking its edges from the previous // unit's reconstruction inside this same strip (spec 5.11.36) -- // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`]. - let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); + let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); if crate::envflags::env_flag!("EC_SBPART_DUMP64") { eprintln!( "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \ @@ -10936,13 +11052,13 @@ fn decode_leaf_rect( } else { 0 }; - if depth != 0 { + if depth != 0 || lossless(fctx) { // The same per-transform-unit walk the bigger strips take // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at // depth 2), addressed at this leaf's own mi position. hit!(TX_DEPTH_HITS); hit!(SUB16_SPLIT_HITS); - let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); + let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); let modes = RectStripModes { skip, mode, @@ -11275,17 +11391,17 @@ fn decode_block_rect4( publish_txfm_bands_if_in_inter( neighbours, (mi_r, mi_c), - depth_to_tx_wh(bw, bh, depth), + depth_to_tx_wh(bw, bh, depth, fctx), (bw, bh), fctx, ); - if depth != 0 { + if depth != 0 || lossless(fctx) { // lane-rectsplitx r1: the per-transform-unit walk, at this strip's // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8; // both interleave in every real stream. hit!(TX_DEPTH_HITS); - let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); + let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); // lane-rectsplitx r2: both depths ship together, as the r1 handoff // predicted -- depth 1 fires FIRST in every attempt that splits at // all, so a depth-2-only lift could never be gated. The r1 mismatch @@ -11800,7 +11916,7 @@ fn decode_rect4_16_strip( hit!(TX_DEPTH_HITS); hit!(RECT4_16_SPLIT_HITS); } - let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); + let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); let (px, py) = (lmi.1 * MI, lmi.0 * MI); let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode); @@ -12291,17 +12407,17 @@ fn decode_block_rect64( publish_txfm_bands_if_in_inter( neighbours, (mi_r, mi_c), - depth_to_tx_wh(bw, bh, depth), + depth_to_tx_wh(bw, bh, depth, fctx), (bw, bh), fctx, ); - if depth != 0 { + if depth != 0 || lossless(fctx) { hit!(TX_DEPTH_HITS); // lane-rectsplit r1/r4: the superblock-level strip splits its // transform through the very same per-unit path as its 32x32-level // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1 // measured the old square formula mis-tiling exactly that strip). - let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); + let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); if bw.max(bh) / bw.min(bh) == 4 { let which = if depth == 1 { &RECT4_SPLIT_DEPTH1_HITS @@ -12888,7 +13004,7 @@ fn read_intra_mode( // lane-sb128c r3 (class sweep): `is_cfl_allowed` on the luma bsize, decided // here so every `decode_block` caller (64x64 and 128x128 roots included) // picks the right alphabet -- see [`read_intra_mode_rect`]'s twin. - let cfl = cfl && side <= 32; + let cfl = cfl && cfl_allowed_px(side, side, fctx); let uv_mode = if cfl { dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { @@ -13654,6 +13770,14 @@ fn read_plane( // filter-intra in AV1). let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode }; let mut coding = cdfs.txb(set, tx_mode); + // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read + // transform type for lossless mode(qindex==0)" -- the symbol is not coded + // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every + // plane of a lossless block (the residual then goes through the WHT, so + // the type only picks the scan, which is the default one). + if lossless(fctx) { + coding.tx_type = None; + } // Luma's `default_tx_type` is only a fallback for the sizes whose // `TxbSet` carries no symbol at all (32-point and up), which the spec // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is @@ -13678,6 +13802,9 @@ fn read_plane( } else { default_intra_tx_type(predict_mode as u8) }; + // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is + // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one. + let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type }; let (grid, tx_type) = read_coeffs( dec, &mut coding, @@ -13703,7 +13830,7 @@ fn read_plane( let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx); let tx = TxParams { w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, - ac_delta, tx_type, stride: 0, + ac_delta, tx_type, stride: 0, lossless: lossless(fctx), }; if crate::envflags::env_flag!("EC_AV1_TRACE") { let residual = tx.run(&levels); @@ -13765,6 +13892,15 @@ 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 { + (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); @@ -13879,7 +14015,7 @@ fn decode_block( // TX_64X64, so a 128x128 block is always FOUR luma transform units // even with `tx_select` off -- the TU loop below, never the // single-unit path. - (side.min(64), luma_tx) + (lossless_tx(side.min(64), fctx), luma_tx) }; if tx_select && logical_tx < side && uv_mode != DC_PRED { hit!(SQ_CHROMA_TX_HITS); @@ -14972,7 +15108,9 @@ fn decode_leaf8( } else if tx_select && intrabc_dv.is_none() { read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None) } else { - 8 + // lane-lossless: TX_4X4 on a lossless frame, no symbol + // (libaom `read_tx_size`). + lossless_tx(8, fctx) }; let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI); let reach = Reach::of(8, px, py, y.width, y.height, fctx); @@ -17395,6 +17533,18 @@ fn read_block_tx_size( is_inter: bool, skip: bool, fctx: &crate::decode::FrameCtx, ) -> Result<(usize, Option>)> { + // lane-lossless: TX_4X4 over the whole block, and NO var-tx tree -- libaom + // `read_block_tx_size` (`decodeframe.c`) sends a lossless block down the + // `read_tx_size` arm, which returns TX_4X4 before it reads anything. + if lossless(fctx) { + let mut leaves = Vec::new(); + for row in 0..side / MI { + for col in 0..side / MI { + leaves.push((row, col, 4, 4)); + } + } + return Ok((4, Some(leaves))); + } if !fctx.tx_select_inter.with(std::cell::Cell::get) { // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64, // so a 128x128 inter block is FOUR luma units even with `tx_mode == @@ -17834,6 +17984,15 @@ fn read_block_tx_size_rect( (mi_cols, mi_rows): (usize, usize), skip: bool, fctx: &crate::decode::FrameCtx, ) -> Result>> { + if lossless(fctx) { + let mut leaves = Vec::new(); + for row in 0..bh / MI { + for col in 0..bw / MI { + leaves.push((row, col, 4, 4)); + } + } + return Ok(Some(leaves)); + } if skip { // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records // its own BLOCK size -- width above, height left -- not a transform. @@ -17993,12 +18152,23 @@ fn read_inter_plane_rect( usize::from(around.0) + usize::from(around.1) }; let mut coding = cdfs.txb(set, tx_mode); + // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read + // transform type for lossless mode(qindex==0)" -- the symbol is not coded + // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every + // plane of a lossless block (the residual then goes through the WHT, so + // the type only picks the scan, which is the default one). + if lossless(fctx) { + coding.tx_type = None; + } // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e. // the *longer* side of this rect transform. let default_tx_type = match inherited_luma_tx_type { Some(t) => reduce_inherited_chroma_tx_type(t, w, h, fctx), None => TxType::DctDct, }; + // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is + // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one. + let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type }; // lane-r14 r2: a 64-length axis codes only its low 32 coefficients // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)` // corner, zero-extended into the true `w x h` grid before the inverse @@ -18053,7 +18223,7 @@ fn read_inter_plane_rect( // (`TxParams::stride`) after the inverse transform. let tx = TxParams { w, h, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type, - stride, + stride, lossless: lossless(fctx), }; push_mc_rect_tx(plane_idx, x, y, stride, w, h, prediction, tx, &grid, fctx); Ok((grid, tx_type)) @@ -18112,6 +18282,9 @@ fn read_inter_luma8( reduced_tx_set: bool, split: bool, fctx: &crate::decode::FrameCtx, ) -> Result<(Grid, TxType)> { + // lane-lossless: an 8x8 inter block is FOUR 4x4 units (libaom + // `read_block_tx_size`'s lossless TX_4X4), tree or no tree. + let split = split || lossless(fctx); if !split { return read_inter_plane( dec, @@ -24208,10 +24381,21 @@ fn read_inter_plane( usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0) }; let mut coding = cdfs.txb(set, tx_mode); + // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read + // transform type for lossless mode(qindex==0)" -- the symbol is not coded + // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every + // plane of a lossless block (the residual then goes through the WHT, so + // the type only picks the scan, which is the default one). + if lossless(fctx) { + coding.tx_type = None; + } let default_tx_type = match inherited_luma_tx_type { Some(t) => reduce_inherited_chroma_tx_type(t, side, side, fctx), None => TxType::DctDct, }; + // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is + // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one. + let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type }; let (grid, tx_type) = read_coeffs( dec, &mut coding, @@ -24237,7 +24421,7 @@ fn read_inter_plane( let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx); let tx = TxParams { w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, - ac_delta, tx_type, stride: 0, + ac_delta, tx_type, stride: 0, lossless: lossless(fctx), }; push_mc_rect_tx(plane_idx, x, y, side, side, side, prediction, tx, &grid, fctx); Ok((grid, tx_type)) @@ -28910,7 +29094,7 @@ fn decode_inter_block( // the 14-symbol CFL one gave the same DC_PRED VALUE but narrowed the // arithmetic coder by the wrong interval, desyncing the tile from this // block on. - let cfl_allowed = write_w.max(write_h) <= 32; + let cfl_allowed = cfl_allowed_px(write_w, write_h, fctx); if !cfl_allowed { hit!(NOCFL_UV_MODE_HITS); } diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 3836a99e..f2b82553 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -57,15 +57,16 @@ const REFUSALS: &[&str] = &[ "intra block copy on a HORZ/VERT/1:4 rect intra strip (reconstruction is not ported at this shape)", "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)", "a bit depth of 12 (this decoder is gated at 8 and 10 only: warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)", - // lane-dpm1: libaom codes his screen-capture row at `-crf 5` with - // `base_q_idx == 0`, i.e. LOSSLESS -- TX_4X4 with the Walsh-Hadamard - // transform over every block (no `tx_depth` symbol at all) and - // `is_cfl_allowed` narrowed to `plane_bsize == BLOCK_4X4`, which changes - // the `uv_mode` alphabet. Nothing here consumes the header's `lossless`, - // so the first block of such a frame read `uv_mode` = UV_CFL_PRED where - // aomdec reads V_PRED. Refused by name (gate - // `a_lossless_libaom_stream_is_refused_by_name`) until the path exists. - "a lossless frame (qindex 0): the TX_4X4 Walsh-Hadamard tile syntax and the lossless CfL rule are unimplemented", + // lane-lossless: the KEY/intra-only half of a lossless frame (base_q_idx + // 0) now decodes sample-exact -- TX_4X4 with the Walsh-Hadamard transform + // on every plane, no `tx_type` symbol, `is_cfl_allowed` narrowed to a + // BLOCK_4X4 chroma plane block. What is left is the INTER chroma walk: an + // inter block's chroma plane is still read as ONE transform per block + // here, so a lossless inter frame is refused by name (gate + // `a_lossless_inter_frame_is_refused_by_name`). A frame whose segments + // disagree is refused separately: every lossless rule is per segment. + "a lossless INTER frame (its chroma plane is still coded as one transform per block here)", + "a frame mixing lossless and lossy segments (the TX_4X4/WHT rules are per segment there)", "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", @@ -285,8 +286,8 @@ const PROVEN: &[(&str, &str)] = &[ "an_inter_frame_opening_a_stream_is_refused_by_name", ), ( - "a lossless frame (qindex 0): the TX_4X4 Walsh-Hadamard tile syntax and the lossless CfL rule are unimplemented", - "a_lossless_libaom_stream_is_refused_by_name", + "a lossless INTER frame (its chroma plane is still coded as one transform per block here)", + "a_lossless_inter_frame_is_refused_by_name", ), // lane-t900 r25, enumeration: a motion_mode/obmc symbol is read only under // `is_motion_variation_allowed_bsize` (min side >= 8), and each of the 17 diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index fb982e04..1d9343b4 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -1603,12 +1603,34 @@ fn decode_frame( // symbol four of the frame. Refuse by name rather than return a picture // that is silently wrong from luma sample 0 (class `refusal-hides-a-defect` // read the other way: a silent wrong decode is worse than a named gap). - if header.lossless.iter().any(|&l| l) { + // lane-lossless: `CodedLossless` (spec 5.9.12) -- every segment at + // `qindex == 0` with zero plane deltas. The tile reader then forces TX_4X4 + // with the Walsh-Hadamard transform on every plane, codes no `tx_type` + // symbol and narrows `is_cfl_allowed` to `plane_bsize == BLOCK_4X4` + // (libaom `read_tx_size`/`read_tx_type`/`is_cfl_allowed`). A frame whose + // segments DISAGREE is still refused by name: every one of those rules is + // per segment there, and no gate covers a mixed frame. + 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 lossless frame (qindex 0): the TX_4X4 Walsh-Hadamard tile syntax and the lossless CfL rule are unimplemented", + "a frame mixing lossless and lossy segments (the TX_4X4/WHT rules are per segment there)", )); } + // lane-lossless r1 ships the KEY/intra-only half: an inter block's chroma + // plane is still read as ONE transform per block here, where a lossless + // frame codes it as 4x4 units like everything else (libaom + // `read_block_tx_size` returns TX_4X4 for every plane). The luma side of + // the inter path is already converted (`read_block_tx_size`'s synthesized + // leaves); the chroma walk and its mu-chunk order are the remaining work, + // so refuse by name rather than return silently wrong pixels. + if coded_lossless && header.frame_type == FrameType::Inter { + return Err(Error::unsupported( + "AV1 decode_stream", + "a lossless INTER frame (its chroma plane is still coded as one transform per block here)", + )); + } + crate::decode::set_lossless(coded_lossless, fctx); crate::decode::set_bit_depth(bit_depth, fctx); // spec 7.16: this frame's superres state, for the filter chain -- // `decode.rs` upscales between CDEF and loop restoration and sizes @@ -3985,18 +4007,20 @@ pub(crate) mod tests { } } - /// lane-dpm1: the lossless refusal is a CLAIM, so it gets a stream that - /// reaches it. libaom at `-crf 0` codes `base_q_idx == 0` -- the same - /// lossless frame his screen-capture row gets at `-crf 5` -- where the tile - /// syntax is TX_4X4 + Walsh-Hadamard and `is_cfl_allowed` narrows to - /// `plane_bsize == BLOCK_4X4`. Before the refusal our decoder returned a - /// picture that was wrong from luma sample 0 (measured on that row: 126 - /// against ffmpeg's 33, the first block's `uv_mode` read off the CfL - /// alphabet). The gate asserts the stream really is lossless and that we - /// refuse it BY NAME rather than decode it wrong. + /// lane-lossless: the refusal became an implementation, so its gate became + /// a DECODE-EXACT one (class `refusal-lifted-without-a-gate`). libaom at + /// `-crf 0` codes `base_q_idx == 0` -- the same lossless frame his + /// screen-capture row gets at `-crf 5` -- where every plane is TX_4X4 with + /// the Walsh-Hadamard transform, no `tx_type` symbol is coded + /// (`read_tx_type`, `decodetxb.c`: "No need to read transform type for + /// lossless mode(qindex==0)") and `is_cfl_allowed` (`blockd.h`) narrows to + /// a BLOCK_4X4 chroma plane block. The gate asserts the stream really is + /// lossless (class `gate-blind-to-feature`), that every KEY frame decodes + /// sample-exact against ffmpeg, and that the still-unimplemented lossless + /// INTER frame is refused BY NAME rather than decoded wrong. #[test] - fn a_lossless_libaom_stream_is_refused_by_name() { - const NAME: &str = "a_lossless_libaom_stream_is_refused_by_name"; + fn a_lossless_libaom_key_frame_decodes_sample_exact() { + const NAME: &str = "a_lossless_libaom_key_frame_decodes_sample_exact"; if !have_ffmpeg() { eprintln!("SKIP {NAME}: no ffmpeg"); return; @@ -4014,17 +4038,21 @@ pub(crate) mod tests { // [[pid-keyed-temp-path]]: parallel test binaries must not share a name. let src = std::env::temp_dir().join(format!("ec-av1-lossless-{}.yuv", std::process::id())); std::fs::write(&src, &raw).expect("raw source"); - let out = Command::new("ffmpeg") - .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"]) - .arg(&src) - .args(["-an", "-threads", "1", "-g", "2", "-c:v", "libaom-av1"]) - .args(["-cpu-used", "6", "-b:v", "0", "-crf", "0", "-f", "obu", "-"]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .output() - .expect("ffmpeg failed to run"); + let encode = |gop: &str| { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) + .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"]) + .arg(&src) + .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"]) + .args(["-cpu-used", "6", "-b:v", "0", "-crf", "0", "-f", "obu", "-"]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + out + }; + let out = encode("1"); let _ = std::fs::remove_file(&src); if !out.status.success() { eprintln!( @@ -4045,15 +4073,68 @@ pub(crate) mod tests { ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h, _ => continue, }; - if header.lossless.iter().any(|&l| l) { + if header.lossless.iter().all(|&l| l) { lossless += 1; } } - assert!(lossless > 0, "{NAME} went blind: libaom coded no lossless frame at -crf 0"); - match decode_stream(&stream) { - Ok(_) => panic!("{NAME}: a lossless stream decoded instead of being refused"), + assert_eq!(lossless, frames, "{NAME} went blind: libaom coded no lossless key frame at -crf 0"); + let ours = decode_stream(&stream).expect("a lossless key-frame stream decodes"); + let refs = ffmpeg_decode_sequence(&stream, w, h, 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}: frame {i} plane {plane}: {bad} samples differ"); + } + } + } + + /// The other half of lane-lossless r1: a lossless INTER frame is refused BY + /// NAME (its chroma plane is still one transform per block here), never + /// decoded into silently wrong pixels -- the refusal this gate pins is the + /// one `refusal_inventory` carries. + #[test] + fn a_lossless_inter_frame_is_refused_by_name() { + const NAME: &str = "a_lossless_inter_frame_is_refused_by_name"; + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + let (w, h, frames) = (128usize, 64usize, 4usize); + let mut raw = Vec::with_capacity(frames * w * h * 3 / 2); + for f in 0..frames { + for row in 0..h { + for col in 0..w { + raw.push(((col * 7 + row * 13 + f * 31) % 251) as u8); + } + } + raw.extend(std::iter::repeat_n(128u8, w * h / 2)); + } + let src = std::env::temp_dir().join(format!("ec-av1-lossless-i-{}.yuv", std::process::id())); + std::fs::write(&src, &raw).expect("raw source"); + let out = Command::new("ffmpeg") + .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) + .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"]) + .arg(&src) + .args(["-an", "-threads", "1", "-g", "4", "-c:v", "libaom-av1"]) + .args(["-cpu-used", "6", "-b:v", "0", "-crf", "0", "-f", "obu", "-"]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + let _ = std::fs::remove_file(&src); + if !out.status.success() { + eprintln!("SKIP {NAME}: ffmpeg has no libaom-av1 encoder"); + return; + } + match decode_stream(&out.stdout) { + Ok(_) => panic!("{NAME}: a lossless inter stream decoded instead of being refused"), Err(e) => assert!( - format!("{e}").contains("a lossless frame (qindex 0)"), + format!("{e}").contains("a lossless INTER frame"), "{NAME}: refused for the wrong reason: {e}" ), } diff --git a/crates/ec-av1/src/transform.rs b/crates/ec-av1/src/transform.rs index a6eadd52..643e59e3 100644 --- a/crates/ec-av1/src/transform.rs +++ b/crates/ec-av1/src/transform.rs @@ -2836,3 +2836,134 @@ mod tests { } } + +/// The lossless inverse transform: libaom `av1_iwht4x4_16_add_c` +/// (`aom_dsp/inv_txfm.c:22`), the 4x4 Walsh-Hadamard a frame with +/// `Lossless == 1` uses for every plane instead of the DCT/ADST network +/// (`inv_txfm_add`, `av1/common/idct.c:69`: `if (txfm_param->lossless) { +/// assert(tx_type == DCT_DCT); av1_iwht4x4_add(...); return; }`). +/// +/// `dq` is the DEQUANTIZED grid; each input is shifted down by +/// `UNIT_QUANT_SHIFT` (2, `aom_dsp/inv_txfm.h`) before the row pass, which at +/// `qindex == 0` (`dc_q(0) == ac_q(0) == 4` at every bit depth) undoes the +/// dequantization exactly -- that is what makes the round trip lossless. +pub fn inverse_wht4x4(dq: &[i32]) -> Vec { + debug_assert_eq!(dq.len(), 16); + // libaom runs pass 1 down the COLUMNS (`ip[4 * k]`, `ip++`) and pass 2 + // along the intermediate's ROWS writing dest COLUMNS (`dest[stride * k]`, + // `dest++`); transposing both passes -- rows first, then columns, output + // in place -- is the same map and is what a raster `dq`/residual pair + // wants here. MEASURED: the other orientation reconstructs sample 0 and + // the DC-only units correctly and drifts by +-1 everywhere else. + let mut out = [0i32; 16]; + for i in 0..4 { + let (mut a1, mut c1, mut d1, mut b1) = + (dq[i * 4] >> 2, dq[i * 4 + 1] >> 2, dq[i * 4 + 2] >> 2, dq[i * 4 + 3] >> 2); + a1 += c1; + d1 -= b1; + let e1 = (a1 - d1) >> 1; + b1 = e1 - b1; + c1 = e1 - c1; + a1 -= b1; + d1 += c1; + out[i * 4] = a1; + out[i * 4 + 1] = b1; + out[i * 4 + 2] = c1; + out[i * 4 + 3] = d1; + } + let mut res = vec![0i32; 16]; + for i in 0..4 { + let (mut a1, mut c1, mut d1, mut b1) = + (out[i], out[4 + i], out[8 + i], out[12 + i]); + a1 += c1; + d1 -= b1; + let e1 = (a1 - d1) >> 1; + b1 = e1 - b1; + c1 = e1 - c1; + a1 -= b1; + d1 += c1; + res[i] = a1; + res[4 + i] = b1; + res[8 + i] = c1; + res[12 + i] = d1; + } + res +} + +/// [`inverse_wht4x4`] with the spec 7.12.3 dequantization in front of it, the +/// lossless twin of [`dequant_and_inverse_typed_wh`] (same empty-grid +/// marker contract). +pub fn dequant_and_inverse_wht4x4( + levels: &[i32], + bit_depth: u8, + q_idx: i32, + dc_delta: i32, + ac_delta: i32, +) -> Vec { + if crate::decode::is_zero_grid(levels) { + return Vec::new(); + } + DQ_SCRATCH.with(|cell| { + let mut dq = cell.borrow_mut(); + crate::quant::dequant_wh_into(levels, &mut dq, 4, 4, bit_depth, q_idx, dc_delta, ac_delta); + inverse_wht4x4(&dq[..16]) + }) +} + +#[cfg(test)] +mod lossless_tx_tests { + /// The WHT is its own inverse up to the `UNIT_QUANT_SHIFT` scaling: a + /// forward pass (libaom `av1_fwht4x4_c`, which scales UP by 4 through + /// `output[i] * UNIT_QUANT_SHIFT`) followed by [`super::inverse_wht4x4`] + /// on the dequantized levels (`q == 4` at qindex 0) returns the residual + /// EXACTLY -- that identity is the whole lossless claim. + #[test] + fn the_walsh_hadamard_round_trip_is_exact() { + // The exact integer inverse of [`super::inverse_wht4x4`]'s two + // butterflies, run in the opposite order (columns then rows) and + // scaled back up by `UNIT_QUANT_SHIFT` -- the encoder side of the + // lossless pair (libaom `av1_fwht4x4_c`). + fn undo(a2: i32, b2: i32, c2: i32, d2: i32) -> (i32, i32, i32, i32) { + let a1 = a2 + b2; + let d1 = d2 - c2; + let e1 = (a1 - d1) >> 1; + let b = e1 - b2; + let c = e1 - c2; + (a1 - c, b, c, d1 + b) + } + fn fwht(residual: &[i32]) -> Vec { + let mut t = [0i32; 16]; + for i in 0..4 { + let (a, b, c, d) = + undo(residual[i], residual[4 + i], residual[8 + i], residual[12 + i]); + t[i] = a; + t[4 + i] = c; + t[8 + i] = d; + t[12 + i] = b; + } + let mut dq = vec![0i32; 16]; + for i in 0..4 { + let (a, b, c, d) = undo(t[i * 4], t[i * 4 + 1], t[i * 4 + 2], t[i * 4 + 3]); + dq[i * 4] = a * 4; + dq[i * 4 + 1] = c * 4; + dq[i * 4 + 2] = d * 4; + dq[i * 4 + 3] = b * 4; + } + dq + } + let mut state = 0x1234_5678u32; + for _ in 0..200 { + let residual: Vec = (0..16) + .map(|_| { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + ((state >> 20) as i32 % 511) - 255 + }) + .collect(); + let levels = fwht(&residual); + // The forward pass already carries libaom's `UNIT_QUANT_SHIFT` + // scale-up, so the coded level is `levels / 4` and qindex 0's + // dequantization (times 4) hands `levels` straight back. + assert_eq!(super::inverse_wht4x4(&levels), residual, "levels={levels:?}"); + } + } +} diff --git a/lanes/lossless.report.md b/lanes/lossless.report.md new file mode 100644 index 00000000..dcce3bcd --- /dev/null +++ b/lanes/lossless.report.md @@ -0,0 +1,33 @@ +# lane-lossless — AV1 lossless (qindex 0) decode + +Branch `lane-lossless`, base `7ba28bcd`. Suite: 556 passed / 0 failed / 43 ignored (`cargo test -p ec-av1 --lib -- --test-threads=1`, 3611 s). `cargo check --workspace --all-targets -j4`: 0 errors, 0 ec-av1 warnings. Native `bd_rate_screen_native` NOT run: its crf-5 point has inter frames and now hits the named lossless-inter refusal (still red on that point). + +## Rules implemented (each with its libaom reference) +| rule | libaom | where | +|---|---|---| +| TX_4X4 on every plane, no `tx_depth`/`txfm_split` symbol | `read_tx_size` (`av1/decoder/decodeframe.c`): `if (xd->lossless[..]) return TX_4X4;` before `max_txsize_rect_lookup` | `decode::lossless_tx`, `decode_block`, `decode_leaf8`, `depth_to_tx_wh`, `read_block_tx_size`(+`_rect`), `read_inter_luma8` | +| Walsh-Hadamard inverse instead of DCT/ADST | `inv_txfm_add` (`av1/common/idct.c`): `if (txfm_param->lossless) { assert(tx_type == DCT_DCT); av1_iwht4x4_add(...); }`; kernel `av1_highbd_iwht4x4_16_add_c` (`av1/common/av1_inv_txfm2d.c:20`), inputs `>> UNIT_QUANT_SHIFT` (2) | `transform::inverse_wht4x4` / `dequant_and_inverse_wht4x4`, `TxParams::lossless` | +| no `tx_type` symbol | `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read transform type for lossless mode(qindex==0)" | `read_plane`/`read_inter_plane`/`read_inter_plane_rect`: `coding.tx_type = None` | +| DCT_DCT on every plane (so the default scan) | `av1_get_tx_type` (`av1/common/blockd.h`): lossless returns DCT_DCT | same three readers' `default_tx_type` | +| `is_cfl_allowed` narrows to a BLOCK_4X4 chroma plane block (luma <= 8x8 at 4:2:0) | `is_cfl_allowed` (`av1/common/blockd.h`) | `decode::cfl_allowed_px`, used by every intra mode reader | +| chroma coded as 4x4 units, plane-major, with `get_txb_ctx`'s `+10` rows | `decode_token_recon_block` mu-chunk loop; `av1_default_txb_skip_cdfs[0][TX_4X4][10..13]` = 9961/30242/32117 (neutral 16384 in every other q-context) | `decode_rect_split` lossless chroma branch; `cdf_state::txb_skip_chroma_4` widened 3 -> 6 rows | +| loop filter / CDEF / LR off | header-level (`coded_lossless`/`all_lossless`), already handled by the frame-header parser | unchanged | +| a frame mixing lossless and lossy segments | every rule above is per segment | refused by name | + +WHT orientation is pinned by MEASUREMENT: libaom's column-then-row-with-transpose +loop equals rows-then-columns in place on a raster grid; the other orientation +reconstructs sample 0 and DC-only units correctly and drifts +-1 elsewhere. + +## Fixtures and results (all `ffmpeg -c:v libaom-av1 -crf 0 -b:v 0`, synthetic source) +| fixture | result | +|---|---| +| 64x64, 1 key frame, 8-bit | EXACT vs ffmpeg (0/6144 samples differ); 6488 entropy steps identical to aomdec `EC_TRACE_COEFF` | +| 256x128, 2 key frames (`-g 1`), 8-bit | EXACT both frames — pinned as `stream::tests::a_lossless_libaom_key_frame_decodes_sample_exact` | +| 192x96, 2 key frames, 10-bit | EXACT both frames | +| 128x64, 4 frames (`-g 4`, inter) | refused by name — pinned as `stream::tests::a_lossless_inter_frame_is_refused_by_name` | + +## Deferred +- `deferred: lossless INTER frames — an inter block's chroma plane is still read as one transform per block (decode_inter_block's two chroma sites + the 128 mu-chunk loop); its luma leaves are already synthesized as TX_4X4 — unblocks: port the 4x4 chroma unit walk (the shape decode_rect_split's lossless branch already has) into decode_inter_block/decode_inter_block8/the sub8 readers.` +- `deferred: the 12-frame bd_rate_screen_native gate's libaom crf-5 point — that stream's inter frames now hit the named refusal instead of decoding, so the deciding gate cannot be green this round — unblocks: the inter chroma walk above.` +- `deferred: mixed lossless/lossy segments — refused by name; no libaom recipe emits one — unblocks: a segmentation fixture with per-segment qindex.` +- `deferred: 4:4:4 / monochrome lossless — the crate is 4:2:0 only.`