From f0a5a15bca5c1f3b9e2ce21380ab021097d90644 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 7 Sep 2026 14:11:36 +0300 Subject: [PATCH] feat(av1): lossless decode groundwork -- WHT, TX_4X4 forcing, CfL narrowing The 4x4 Walsh-Hadamard inverse (libaom av1_iwht4x4_16_add_c) with its own round-trip test, a per-frame CodedLossless flag replacing the refusal (a frame mixing lossless and lossy segments is still refused by name), the TX_4X4 forcing in the square and 8x8-leaf intra readers, no tx_type symbol (libaom read_tx_type: qindex 0 returns early), DCT_DCT on every plane, the is_cfl_allowed narrowing to a 4x4 chroma plane block, and the +10 chroma txb_skip rows at TX_4X4 that only a lossless frame reaches. --- crates/ec-av1/src/cdf.rs | 18 +++++ crates/ec-av1/src/cdf_state.rs | 30 +++++--- crates/ec-av1/src/decode.rs | 123 +++++++++++++++++++++++++++++---- crates/ec-av1/src/stream.rs | 13 +++- crates/ec-av1/src/transform.rs | 123 +++++++++++++++++++++++++++++++++ 5 files changed, 284 insertions(+), 23 deletions(-) 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..136f5952 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 { @@ -10073,7 +10126,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 { @@ -12888,7 +12941,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 +13707,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 +13739,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 +13767,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 +13829,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 +13952,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 +15045,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); @@ -17993,12 +18068,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 +18139,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)) @@ -24208,10 +24294,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 +24334,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 +29007,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/stream.rs b/crates/ec-av1/src/stream.rs index fb982e04..ddcd6a90 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -1603,12 +1603,21 @@ 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)", )); } + 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 diff --git a/crates/ec-av1/src/transform.rs b/crates/ec-av1/src/transform.rs index a6eadd52..1c69ebeb 100644 --- a/crates/ec-av1/src/transform.rs +++ b/crates/ec-av1/src/transform.rs @@ -2836,3 +2836,126 @@ 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); + let mut out = [0i32; 16]; + for i in 0..4 { + let ip = &dq[i * 4..]; + let (mut a1, mut c1, mut d1, mut b1) = (ip[0] >> 2, ip[1] >> 2, ip[2] >> 2, ip[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 = residual.to_vec(); + for i in 0..4 { + let (a, b, c, d) = undo(t[i], t[4 + i], t[8 + i], t[12 + i]); + t[i] = a; + t[4 + i] = c; + t[8 + i] = d; + t[12 + i] = b; + } + let mut out = 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]); + out[i * 4] = a * 4; + out[i * 4 + 1] = c * 4; + out[i * 4 + 2] = d * 4; + out[i * 4 + 3] = b * 4; + } + out + } + 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:?}"); + } + } +}