forge
Explore
Log in

Don't you dare go Hollow

Lossless decode groundwork -- WHT, TX_4X4 forcing, CfL narrowing

Browse files at this commit

f0a5a15bca5c1f3b9e2ce21380ab021097d90644Ahmet Kaan GümüşParent: bb30488
  • feat
    • lossless decode groundwork -- WHT, TX_4X4 forcing, CfL narrowing
Show full message
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.rsmodified+18 -0
@@ -3860,6 +3860,24 @@ pub const TXB_SKIP_LUMA_8: [u16; 3] = [31957, 32768, 0];
38603860 /// TXB_SKIP_LUMA_8_Q3, q-context 3: the same table as [`TXB_SKIP_LUMA_8`], for `base_q_idx` 121..=255.
38613861 pub const TXB_SKIP_LUMA_8_Q3: [u16; 3] = [31903, 32768, 0];
38623862
3863+/// lane-lossless: `av1_default_txb_skip_cdfs[q][TX_4X4][10..13]`
3864+/// (`av1/common/token_cdfs.h:76`), the chroma `txb_skip` rows libaom's
3865+/// `get_txb_ctx` reaches through the `+10` offset -- a chroma plane block
3866+/// LARGER than its transform. At TX_4X4 that only happens on a lossless
3867+/// frame, which is why every q-context but 0 (`base_q_idx <= 20`) leaves
3868+/// them at the neutral 16384.
3869+pub const TXB_SKIP_CHROMA_4_BIG_Q0: [[u16; 3]; 3] =
3870+ [[9961, 32768, 0], [30242, 32768, 0], [32117, 32768, 0]];
3871+/// [`TXB_SKIP_CHROMA_4_BIG_Q0`] for q-context 1.
3872+pub const TXB_SKIP_CHROMA_4_BIG_Q1: [[u16; 3]; 3] =
3873+ [[16384, 32768, 0], [16384, 32768, 0], [16384, 32768, 0]];
3874+/// [`TXB_SKIP_CHROMA_4_BIG_Q0`] for q-context 2.
3875+pub const TXB_SKIP_CHROMA_4_BIG: [[u16; 3]; 3] =
3876+ [[16384, 32768, 0], [16384, 32768, 0], [16384, 32768, 0]];
3877+/// [`TXB_SKIP_CHROMA_4_BIG_Q0`] for q-context 3.
3878+pub const TXB_SKIP_CHROMA_4_BIG_Q3: [[u16; 3]; 3] =
3879+ [[16384, 32768, 0], [16384, 32768, 0], [16384, 32768, 0]];
3880+
38633881 /// TXB_SKIP_CHROMA_4_Q0, q-context 0: the same table as [`TXB_SKIP_CHROMA_4`], for `base_q_idx` 0..=20.
38643882 pub const TXB_SKIP_CHROMA_4_Q0: [[u16; 3]; 3] =
38653883 [[7654, 32768, 0], [19473, 32768, 0], [29984, 32768, 0]];
crates/ec-av1/src/cdf_state.rsmodified+22 -8
@@ -364,7 +364,11 @@ pub(crate) struct Cdfs {
364364 /// The all-zero flag of an 8x8 chroma transform.
365365 pub txb_skip_chroma_8: [[u16; 3]; 3],
366366 /// The all-zero flag of a 4x4 chroma transform.
367- pub txb_skip_chroma_4: [[u16; 3]; 3],
367+ /// lane-lossless: SIX rows, like [`Self::txb_skip_chroma_32`] -- the last
368+ /// three are `get_txb_ctx`'s `+10` rows (chroma plane block bigger than
369+ /// its transform), which a lossless frame's TX_4X4 chroma reaches at
370+ /// every block above 8x8.
371+ pub txb_skip_chroma_4: [[u16; 3]; 6],
368372 /// The end-of-block group of a 16x16 luma transform.
369373 pub eob_pt_256_luma: [u16; 10],
370374 /// The end-of-block group of an 8x8 luma transform.
@@ -1031,13 +1035,23 @@ impl Cdfs {
10311035 cdf::TXB_SKIP_CHROMA_8,
10321036 cdf::TXB_SKIP_CHROMA_8_Q3,
10331037 ),
1034- txb_skip_chroma_4: pick(
1035- q_ctx,
1036- cdf::TXB_SKIP_CHROMA_4_Q0,
1037- cdf::TXB_SKIP_CHROMA_4_Q1,
1038- cdf::TXB_SKIP_CHROMA_4,
1039- cdf::TXB_SKIP_CHROMA_4_Q3,
1040- ),
1038+ txb_skip_chroma_4: {
1039+ let small = pick(
1040+ q_ctx,
1041+ cdf::TXB_SKIP_CHROMA_4_Q0,
1042+ cdf::TXB_SKIP_CHROMA_4_Q1,
1043+ cdf::TXB_SKIP_CHROMA_4,
1044+ cdf::TXB_SKIP_CHROMA_4_Q3,
1045+ );
1046+ let big = pick(
1047+ q_ctx,
1048+ cdf::TXB_SKIP_CHROMA_4_BIG_Q0,
1049+ cdf::TXB_SKIP_CHROMA_4_BIG_Q1,
1050+ cdf::TXB_SKIP_CHROMA_4_BIG,
1051+ cdf::TXB_SKIP_CHROMA_4_BIG_Q3,
1052+ );
1053+ [small[0], small[1], small[2], big[0], big[1], big[2]]
1054+ },
10411055 eob_pt_256_luma: pick(
10421056 q_ctx,
10431057 cdf::EOB_PT_256_LUMA_Q0,
crates/ec-av1/src/decode.rsmodified+110 -13
@@ -69,6 +69,13 @@ pub(crate) struct FrameCtx {
6969 pub(crate) capture_stages: std::cell::Cell<bool>,
7070 pub(crate) stages: std::cell::RefCell<Option<FilterStages>>,
7171 pub(crate) sb128_flag: std::cell::Cell<bool>,
72+ /// lane-lossless: this frame's `CodedLossless` (spec 5.9.12) -- every
73+ /// segment at `qindex == 0` with zero plane deltas. It forces TX_4X4 with
74+ /// the Walsh-Hadamard transform on every plane, drops the `tx_type`
75+ /// symbol and narrows `is_cfl_allowed` (libaom `read_tx_size`
76+ /// (`decodeframe.c`), `read_tx_type` (`decodetxb.c`), `is_cfl_allowed`
77+ /// (`blockd.h`)).
78+ pub(crate) lossless_flag: std::cell::Cell<bool>,
7279 pub(crate) cdef_bits: std::cell::Cell<u8>,
7380 pub(crate) bit_depth: std::cell::Cell<u8>,
7481 pub(crate) superres: std::cell::Cell<(u32, u32)>,
@@ -152,6 +159,7 @@ impl FrameCtx {
152159 pub(crate) fn new() -> Self {
153160 Self {
154161 sb128_flag: std::cell::Cell::new(false),
162+ lossless_flag: std::cell::Cell::new(false),
155163 cdef_bits: std::cell::Cell::new(0),
156164 bit_depth: std::cell::Cell::new(8),
157165 superres: std::cell::Cell::new((0, 8)),
@@ -325,6 +333,38 @@ pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {
325333 crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx);
326334 }
327335
336+/// Sets [`FrameCtx::lossless_flag`] (called once per frame from `stream.rs`).
337+pub(crate) fn set_lossless(v: bool, fctx: &crate::decode::FrameCtx) {
338+ fctx.lossless_flag.with(|c| c.set(v));
339+}
340+
341+/// This frame's `CodedLossless` -- see [`FrameCtx::lossless_flag`].
342+pub(crate) fn lossless(fctx: &crate::decode::FrameCtx) -> bool {
343+ fctx.lossless_flag.with(|c| c.get())
344+}
345+
346+/// The transform side a block of `side` pixels codes: its own (capped at the
347+/// caller's own largest) normally, 4 on a lossless frame, where libaom's
348+/// `read_tx_size` returns TX_4X4 before it looks at anything else
349+/// (`decodeframe.c`: `if (xd->lossless[xd->mi[0]->segment_id]) return
350+/// TX_4X4;`).
351+pub(crate) fn lossless_tx(px: usize, fctx: &crate::decode::FrameCtx) -> usize {
352+ if lossless(fctx) { 4 } else { px }
353+}
354+
355+/// `is_cfl_allowed` (libaom `blockd.h`): CfL is offered on a block up to
356+/// 32x32 -- but on a LOSSLESS frame only when the block's CHROMA plane block
357+/// is exactly BLOCK_4X4, i.e. (at 4:2:0) a luma block of 8x8 or smaller.
358+/// Getting this wrong picks the 14-symbol CFL `uv_mode` alphabet where libaom
359+/// picks the 13-symbol one (class `wrong-alphabet-same-value`).
360+pub(crate) fn cfl_allowed_px(bw: usize, bh: usize, fctx: &crate::decode::FrameCtx) -> bool {
361+ if lossless(fctx) {
362+ bw <= 8 && bh <= 8
363+ } else {
364+ bw <= 32 && bh <= 32
365+ }
366+}
367+
328368 fn sb128(fctx: &crate::decode::FrameCtx) -> bool {
329369 fctx.sb128_flag.with(|c| c.get())
330370 }
@@ -2131,6 +2171,11 @@ pub(crate) struct TxParams {
21312171 pub(crate) ac_delta: i32,
21322172 pub(crate) tx_type: TxType,
21332173 pub(crate) stride: usize,
2174+ /// lane-lossless: this transform unit belongs to a lossless frame, so the
2175+ /// residual comes off the 4x4 Walsh-Hadamard
2176+ /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the
2177+ /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`).
2178+ pub(crate) lossless: bool,
21342179 }
21352180
21362181 impl TxParams {
@@ -2138,10 +2183,18 @@ impl TxParams {
21382183 /// on the parse thread, the wavefront worker calls it on its own, so both
21392184 /// are the same function on the same inputs and byte-identical.
21402185 fn run(self, grid: &[i32]) -> Vec<i32> {
2141- let residual = dequant_and_inverse_typed_wh(
2142- grid, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2143- self.tx_type,
2144- );
2186+ let residual = if self.lossless {
2187+ debug_assert_eq!((self.w, self.h), (4, 4));
2188+ debug_assert_eq!(self.tx_type, TxType::DctDct);
2189+ crate::transform::dequant_and_inverse_wht4x4(
2190+ grid, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2191+ )
2192+ } else {
2193+ dequant_and_inverse_typed_wh(
2194+ grid, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2195+ self.tx_type,
2196+ )
2197+ };
21452198 // An all-zero grid transforms to the empty marker, and a strided copy
21462199 // of zeros is still zeros: the marker passes straight through.
21472200 if residual.is_empty() {
@@ -8848,7 +8901,7 @@ fn read_intra_mode_rect(
88488901 // through -- a caller passing `true` for a >32 strip used to pick the
88498902 // 14-symbol CFL CDF, same value but a different range (class
88508903 // wrong-alphabet-same-value).
8851- let cfl = cfl && bw <= 32 && bh <= 32;
8904+ let cfl = cfl && cfl_allowed_px(bw, bh, fctx);
88528905 let uv_mode = if !has_chroma {
88538906 DC_PRED
88548907 } else if cfl {
@@ -10073,7 +10126,7 @@ fn decode_intra_rect_in_inter(
1007310126 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
1007410127 // superblock-level strip reads the no-CFL alphabet -- the same split
1007510128 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
10076- let cfl_allowed = bw.max(bh) <= 32;
10129+ let cfl_allowed = cfl_allowed_px(bw, bh, fctx);
1007710130 let uv_mode = if cfl_allowed {
1007810131 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
1007910132 } else {
@@ -12888,7 +12941,7 @@ fn read_intra_mode(
1288812941 // lane-sb128c r3 (class sweep): `is_cfl_allowed` on the luma bsize, decided
1288912942 // here so every `decode_block` caller (64x64 and 128x128 roots included)
1289012943 // picks the right alphabet -- see [`read_intra_mode_rect`]'s twin.
12891- let cfl = cfl && side <= 32;
12944+ let cfl = cfl && cfl_allowed_px(side, side, fctx);
1289212945 let uv_mode = if cfl {
1289312946 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
1289412947 } else {
@@ -13654,6 +13707,14 @@ fn read_plane(
1365413707 // filter-intra in AV1).
1365513708 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
1365613709 let mut coding = cdfs.txb(set, tx_mode);
13710+ // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
13711+ // transform type for lossless mode(qindex==0)" -- the symbol is not coded
13712+ // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
13713+ // plane of a lossless block (the residual then goes through the WHT, so
13714+ // the type only picks the scan, which is the default one).
13715+ if lossless(fctx) {
13716+ coding.tx_type = None;
13717+ }
1365713718 // Luma's `default_tx_type` is only a fallback for the sizes whose
1365813719 // `TxbSet` carries no symbol at all (32-point and up), which the spec
1365913720 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
@@ -13678,6 +13739,9 @@ fn read_plane(
1367813739 } else {
1367913740 default_intra_tx_type(predict_mode as u8)
1368013741 };
13742+ // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
13743+ // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
13744+ let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type };
1368113745 let (grid, tx_type) = read_coeffs(
1368213746 dec,
1368313747 &mut coding,
@@ -13703,7 +13767,7 @@ fn read_plane(
1370313767 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
1370413768 let tx = TxParams {
1370513769 w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta,
13706- ac_delta, tx_type, stride: 0,
13770+ ac_delta, tx_type, stride: 0, lossless: lossless(fctx),
1370713771 };
1370813772 if crate::envflags::env_flag!("EC_AV1_TRACE") {
1370913773 let residual = tx.run(&levels);
@@ -13765,6 +13829,15 @@ fn decode_block(
1376513829 tx_select: bool,
1376613830 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
1376713831 ) -> Result<()> {
13832+ // lane-lossless: a lossless frame's transform is TX_4X4 on every plane
13833+ // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
13834+ // tables/scans are replaced by the 4x4 ones and the block always takes the
13835+ // multi-transform-unit path below.
13836+ let (luma_set, chroma_set, luma_tx, chroma_tx, scans) = if lossless(fctx) {
13837+ (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, (scan4, scan4))
13838+ } else {
13839+ (luma_set, chroma_set, luma_tx, chroma_tx, scans)
13840+ };
1376813841 let (r, c) = at;
1376913842 let (px, py) = (c * SUB, r * SUB);
1377013843 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
@@ -13879,7 +13952,7 @@ fn decode_block(
1387913952 // TX_64X64, so a 128x128 block is always FOUR luma transform units
1388013953 // even with `tx_select` off -- the TU loop below, never the
1388113954 // single-unit path.
13882- (side.min(64), luma_tx)
13955+ (lossless_tx(side.min(64), fctx), luma_tx)
1388313956 };
1388413957 if tx_select && logical_tx < side && uv_mode != DC_PRED {
1388513958 hit!(SQ_CHROMA_TX_HITS);
@@ -14972,7 +15045,9 @@ fn decode_leaf8(
1497215045 } else if tx_select && intrabc_dv.is_none() {
1497315046 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
1497415047 } else {
14975- 8
15048+ // lane-lossless: TX_4X4 on a lossless frame, no symbol
15049+ // (libaom `read_tx_size`).
15050+ lossless_tx(8, fctx)
1497615051 };
1497715052 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
1497815053 let reach = Reach::of(8, px, py, y.width, y.height, fctx);
@@ -17993,12 +18068,23 @@ fn read_inter_plane_rect(
1799318068 usize::from(around.0) + usize::from(around.1)
1799418069 };
1799518070 let mut coding = cdfs.txb(set, tx_mode);
18071+ // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
18072+ // transform type for lossless mode(qindex==0)" -- the symbol is not coded
18073+ // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
18074+ // plane of a lossless block (the residual then goes through the WHT, so
18075+ // the type only picks the scan, which is the default one).
18076+ if lossless(fctx) {
18077+ coding.tx_type = None;
18078+ }
1799618079 // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e.
1799718080 // the *longer* side of this rect transform.
1799818081 let default_tx_type = match inherited_luma_tx_type {
1799918082 Some(t) => reduce_inherited_chroma_tx_type(t, w, h, fctx),
1800018083 None => TxType::DctDct,
1800118084 };
18085+ // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
18086+ // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
18087+ let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type };
1800218088 // lane-r14 r2: a 64-length axis codes only its low 32 coefficients
1800318089 // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)`
1800418090 // corner, zero-extended into the true `w x h` grid before the inverse
@@ -18053,7 +18139,7 @@ fn read_inter_plane_rect(
1805318139 // (`TxParams::stride`) after the inverse transform.
1805418140 let tx = TxParams {
1805518141 w, h, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type,
18056- stride,
18142+ stride, lossless: lossless(fctx),
1805718143 };
1805818144 push_mc_rect_tx(plane_idx, x, y, stride, w, h, prediction, tx, &grid, fctx);
1805918145 Ok((grid, tx_type))
@@ -24208,10 +24294,21 @@ fn read_inter_plane(
2420824294 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
2420924295 };
2421024296 let mut coding = cdfs.txb(set, tx_mode);
24297+ // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
24298+ // transform type for lossless mode(qindex==0)" -- the symbol is not coded
24299+ // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
24300+ // plane of a lossless block (the residual then goes through the WHT, so
24301+ // the type only picks the scan, which is the default one).
24302+ if lossless(fctx) {
24303+ coding.tx_type = None;
24304+ }
2421124305 let default_tx_type = match inherited_luma_tx_type {
2421224306 Some(t) => reduce_inherited_chroma_tx_type(t, side, side, fctx),
2421324307 None => TxType::DctDct,
2421424308 };
24309+ // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
24310+ // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
24311+ let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type };
2421524312 let (grid, tx_type) = read_coeffs(
2421624313 dec,
2421724314 &mut coding,
@@ -24237,7 +24334,7 @@ fn read_inter_plane(
2423724334 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
2423824335 let tx = TxParams {
2423924336 w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta,
24240- ac_delta, tx_type, stride: 0,
24337+ ac_delta, tx_type, stride: 0, lossless: lossless(fctx),
2424124338 };
2424224339 push_mc_rect_tx(plane_idx, x, y, side, side, side, prediction, tx, &grid, fctx);
2424324340 Ok((grid, tx_type))
@@ -28910,7 +29007,7 @@ fn decode_inter_block(
2891029007 // the 14-symbol CFL one gave the same DC_PRED VALUE but narrowed the
2891129008 // arithmetic coder by the wrong interval, desyncing the tile from this
2891229009 // block on.
28913- let cfl_allowed = write_w.max(write_h) <= 32;
29010+ let cfl_allowed = cfl_allowed_px(write_w, write_h, fctx);
2891429011 if !cfl_allowed {
2891529012 hit!(NOCFL_UV_MODE_HITS);
2891629013 }
crates/ec-av1/src/stream.rsmodified+11 -2
@@ -1603,12 +1603,21 @@ fn decode_frame(
16031603 // symbol four of the frame. Refuse by name rather than return a picture
16041604 // that is silently wrong from luma sample 0 (class `refusal-hides-a-defect`
16051605 // read the other way: a silent wrong decode is worse than a named gap).
1606- if header.lossless.iter().any(|&l| l) {
1606+ // lane-lossless: `CodedLossless` (spec 5.9.12) -- every segment at
1607+ // `qindex == 0` with zero plane deltas. The tile reader then forces TX_4X4
1608+ // with the Walsh-Hadamard transform on every plane, codes no `tx_type`
1609+ // symbol and narrows `is_cfl_allowed` to `plane_bsize == BLOCK_4X4`
1610+ // (libaom `read_tx_size`/`read_tx_type`/`is_cfl_allowed`). A frame whose
1611+ // segments DISAGREE is still refused by name: every one of those rules is
1612+ // per segment there, and no gate covers a mixed frame.
1613+ let coded_lossless = header.lossless.iter().all(|&l| l);
1614+ if header.lossless.iter().any(|&l| l) && !coded_lossless {
16071615 return Err(Error::unsupported(
16081616 "AV1 decode_stream",
1609- "a lossless frame (qindex 0): the TX_4X4 Walsh-Hadamard tile syntax and the lossless CfL rule are unimplemented",
1617+ "a frame mixing lossless and lossy segments (the TX_4X4/WHT rules are per segment there)",
16101618 ));
16111619 }
1620+ crate::decode::set_lossless(coded_lossless, fctx);
16121621 crate::decode::set_bit_depth(bit_depth, fctx);
16131622 // spec 7.16: this frame's superres state, for the filter chain --
16141623 // `decode.rs` upscales between CDEF and loop restoration and sizes
crates/ec-av1/src/transform.rsmodified+123 -0
@@ -2836,3 +2836,126 @@ mod tests {
28362836 }
28372837
28382838 }
2839+
2840+/// The lossless inverse transform: libaom `av1_iwht4x4_16_add_c`
2841+/// (`aom_dsp/inv_txfm.c:22`), the 4x4 Walsh-Hadamard a frame with
2842+/// `Lossless == 1` uses for every plane instead of the DCT/ADST network
2843+/// (`inv_txfm_add`, `av1/common/idct.c:69`: `if (txfm_param->lossless) {
2844+/// assert(tx_type == DCT_DCT); av1_iwht4x4_add(...); return; }`).
2845+///
2846+/// `dq` is the DEQUANTIZED grid; each input is shifted down by
2847+/// `UNIT_QUANT_SHIFT` (2, `aom_dsp/inv_txfm.h`) before the row pass, which at
2848+/// `qindex == 0` (`dc_q(0) == ac_q(0) == 4` at every bit depth) undoes the
2849+/// dequantization exactly -- that is what makes the round trip lossless.
2850+pub fn inverse_wht4x4(dq: &[i32]) -> Vec<i32> {
2851+ debug_assert_eq!(dq.len(), 16);
2852+ let mut out = [0i32; 16];
2853+ for i in 0..4 {
2854+ let ip = &dq[i * 4..];
2855+ let (mut a1, mut c1, mut d1, mut b1) = (ip[0] >> 2, ip[1] >> 2, ip[2] >> 2, ip[3] >> 2);
2856+ a1 += c1;
2857+ d1 -= b1;
2858+ let e1 = (a1 - d1) >> 1;
2859+ b1 = e1 - b1;
2860+ c1 = e1 - c1;
2861+ a1 -= b1;
2862+ d1 += c1;
2863+ out[i * 4] = a1;
2864+ out[i * 4 + 1] = b1;
2865+ out[i * 4 + 2] = c1;
2866+ out[i * 4 + 3] = d1;
2867+ }
2868+ let mut res = vec![0i32; 16];
2869+ for i in 0..4 {
2870+ let (mut a1, mut c1, mut d1, mut b1) = (out[i], out[4 + i], out[8 + i], out[12 + i]);
2871+ a1 += c1;
2872+ d1 -= b1;
2873+ let e1 = (a1 - d1) >> 1;
2874+ b1 = e1 - b1;
2875+ c1 = e1 - c1;
2876+ a1 -= b1;
2877+ d1 += c1;
2878+ res[i] = a1;
2879+ res[4 + i] = b1;
2880+ res[8 + i] = c1;
2881+ res[12 + i] = d1;
2882+ }
2883+ res
2884+}
2885+
2886+/// [`inverse_wht4x4`] with the spec 7.12.3 dequantization in front of it, the
2887+/// lossless twin of [`dequant_and_inverse_typed_wh`] (same empty-grid
2888+/// marker contract).
2889+pub fn dequant_and_inverse_wht4x4(
2890+ levels: &[i32],
2891+ bit_depth: u8,
2892+ q_idx: i32,
2893+ dc_delta: i32,
2894+ ac_delta: i32,
2895+) -> Vec<i32> {
2896+ if crate::decode::is_zero_grid(levels) {
2897+ return Vec::new();
2898+ }
2899+ DQ_SCRATCH.with(|cell| {
2900+ let mut dq = cell.borrow_mut();
2901+ crate::quant::dequant_wh_into(levels, &mut dq, 4, 4, bit_depth, q_idx, dc_delta, ac_delta);
2902+ inverse_wht4x4(&dq[..16])
2903+ })
2904+}
2905+
2906+#[cfg(test)]
2907+mod lossless_tx_tests {
2908+ /// The WHT is its own inverse up to the `UNIT_QUANT_SHIFT` scaling: a
2909+ /// forward pass (libaom `av1_fwht4x4_c`, which scales UP by 4 through
2910+ /// `output[i] * UNIT_QUANT_SHIFT`) followed by [`super::inverse_wht4x4`]
2911+ /// on the dequantized levels (`q == 4` at qindex 0) returns the residual
2912+ /// EXACTLY -- that identity is the whole lossless claim.
2913+ #[test]
2914+ fn the_walsh_hadamard_round_trip_is_exact() {
2915+ // The exact integer inverse of [`super::inverse_wht4x4`]'s two
2916+ // butterflies, run in the opposite order (columns then rows) and
2917+ // scaled back up by `UNIT_QUANT_SHIFT` -- the encoder side of the
2918+ // lossless pair (libaom `av1_fwht4x4_c`).
2919+ fn undo(a2: i32, b2: i32, c2: i32, d2: i32) -> (i32, i32, i32, i32) {
2920+ let a1 = a2 + b2;
2921+ let d1 = d2 - c2;
2922+ let e1 = (a1 - d1) >> 1;
2923+ let b = e1 - b2;
2924+ let c = e1 - c2;
2925+ (a1 - c, b, c, d1 + b)
2926+ }
2927+ fn fwht(residual: &[i32]) -> Vec<i32> {
2928+ let mut t = residual.to_vec();
2929+ for i in 0..4 {
2930+ let (a, b, c, d) = undo(t[i], t[4 + i], t[8 + i], t[12 + i]);
2931+ t[i] = a;
2932+ t[4 + i] = c;
2933+ t[8 + i] = d;
2934+ t[12 + i] = b;
2935+ }
2936+ let mut out = vec![0i32; 16];
2937+ for i in 0..4 {
2938+ let (a, b, c, d) = undo(t[i * 4], t[i * 4 + 1], t[i * 4 + 2], t[i * 4 + 3]);
2939+ out[i * 4] = a * 4;
2940+ out[i * 4 + 1] = c * 4;
2941+ out[i * 4 + 2] = d * 4;
2942+ out[i * 4 + 3] = b * 4;
2943+ }
2944+ out
2945+ }
2946+ let mut state = 0x1234_5678u32;
2947+ for _ in 0..200 {
2948+ let residual: Vec<i32> = (0..16)
2949+ .map(|_| {
2950+ state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
2951+ ((state >> 20) as i32 % 511) - 255
2952+ })
2953+ .collect();
2954+ let levels = fwht(&residual);
2955+ // The forward pass already carries libaom's `UNIT_QUANT_SHIFT`
2956+ // scale-up, so the coded level is `levels / 4` and qindex 0's
2957+ // dequantization (times 4) hands `levels` straight back.
2958+ assert_eq!(super::inverse_wht4x4(&levels), residual, "levels={levels:?}");
2959+ }
2960+ }
2961+}