diff --git a/crates/ec-av1/src/quant.rs b/crates/ec-av1/src/quant.rs index 229a7355..79974541 100644 --- a/crates/ec-av1/src/quant.rs +++ b/crates/ec-av1/src/quant.rs @@ -144,7 +144,16 @@ pub fn ac_q(bit_depth: u8, b: i32) -> i32 { /// `dqDenom` (spec 7.12.3): what the dequantized coefficient is divided by, /// which is driven by the transform's area rather than its side. pub fn dq_denom(side: usize) -> i64 { - match side * side { + dq_denom_area(side * side) +} + +/// [`dq_denom`] keyed directly on the transform's area (lane-recttx): a +/// rectangular block's denominator is an area threshold too, not a +/// per-side one (`av1_get_tx_scale`, `av1/common/idct.c:24-28`: +/// `(pels > 256) + (pels > 1024)` on `tx_size_2d[tx_size]`, which is +/// `w * h`). +pub fn dq_denom_area(pels: usize) -> i64 { + match pels { 0..=256 => 1, 257..=1024 => 2, _ => 4, @@ -155,6 +164,12 @@ pub fn dq_denom(side: usize) -> i64 { /// quantizer, mask to 24 bits, divide by the transform's denominator toward /// zero, and clip to the coefficient range. pub fn dequant_coeff(level: i32, is_dc: bool, bit_depth: u8, q_idx: i32, side: usize) -> i32 { + dequant_coeff_wh(level, is_dc, bit_depth, q_idx, side, side) +} + +/// [`dequant_coeff`] widened to `(w, h)` (lane-recttx): only the denominator +/// (an area threshold, [`dq_denom_area`]) depends on the transform's shape. +pub fn dequant_coeff_wh(level: i32, is_dc: bool, bit_depth: u8, q_idx: i32, w: usize, h: usize) -> i32 { let q = i64::from(if is_dc { dc_q(bit_depth, q_idx) } else { @@ -162,7 +177,7 @@ pub fn dequant_coeff(level: i32, is_dc: bool, bit_depth: u8, q_idx: i32, side: u }); let dq = i64::from(level) * q; let sign = if dq < 0 { -1 } else { 1 }; - let dq2 = sign * ((dq.abs() & 0xFF_FFFF) / dq_denom(side)); + let dq2 = sign * ((dq.abs() & 0xFF_FFFF) / dq_denom_area(w * h)); let bound = 1i64 << (7 + u32::from(bit_depth)); dq2.clamp(-bound, bound - 1) as i32 } @@ -170,10 +185,15 @@ pub fn dequant_coeff(level: i32, is_dc: bool, bit_depth: u8, q_idx: i32, side: u /// Dequantize a whole raster-order coefficient grid of a `side` x `side` /// transform. pub fn dequant(levels: &[i32], side: usize, bit_depth: u8, q_idx: i32) -> Vec { + dequant_wh(levels, side, side, bit_depth, q_idx) +} + +/// [`dequant`] widened to `(w, h)` (lane-recttx). +pub fn dequant_wh(levels: &[i32], w: usize, h: usize, bit_depth: u8, q_idx: i32) -> Vec { levels .iter() .enumerate() - .map(|(i, &l)| dequant_coeff(l, i == 0, bit_depth, q_idx, side)) + .map(|(i, &l)| dequant_coeff_wh(l, i == 0, bit_depth, q_idx, w, h)) .collect() } diff --git a/crates/ec-av1/src/transform.rs b/crates/ec-av1/src/transform.rs index 7c764d35..d6bdad54 100644 --- a/crates/ec-av1/src/transform.rs +++ b/crates/ec-av1/src/transform.rs @@ -280,12 +280,24 @@ pub fn inverse_dct(t: &mut [i32], n: u32, r: usize) { } } -/// `Transform_Row_Shift` (spec 7.13.3) for the square transforms. -fn row_shift(log2: u32) -> usize { - match log2 { - 2 => 0, - 3 => 1, - _ => 2, +/// `Transform_Row_Shift` (spec 7.13.3) / `av1_inv_txfm_shift_ls` +/// (`av1_inv_txfm2d.c:132-158`): `shift[0]`, keyed on the full `(w, h)` TX +/// size, not a single log2 -- the five square values (unchanged from the +/// pre-lane `row_shift(log2)`) plus the fourteen rectangular ones the lane +/// charter transcribed from the same table. +fn row_shift_wh(w: usize, h: usize) -> usize { + match (w, h) { + (4, 4) => 0, + (8, 8) => 1, + (16, 16) | (32, 32) | (64, 64) => 2, + (4, 8) | (8, 4) => 0, + (8, 16) | (16, 8) => 1, + (16, 32) | (32, 16) => 1, + (32, 64) | (64, 32) => 1, + (4, 16) | (16, 4) => 1, + (8, 32) | (32, 8) => 2, + (16, 64) | (64, 16) => 2, + _ => unreachable!("unsupported transform size {w}x{h}"), } } @@ -790,29 +802,55 @@ pub fn inverse_transform_2d_typed( bit_depth: u8, tx_type: TxType, ) -> Vec { - let log2 = side.trailing_zeros(); - assert_eq!(1usize << log2, side, "the transform is square"); - assert_eq!(dequant.len(), side * side, "one coefficient per position"); + inverse_transform_2d_typed_wh(dequant, side, side, bit_depth, tx_type) +} + +/// [`inverse_transform_2d_typed`] widened to `(w, h)` (lane-recttx): the row +/// pass transforms `w`-point vectors (`log2(w)`), the column pass +/// `h`-point vectors (`log2(h)`), and a rect-only pre-row-transform scale +/// is applied when the two axes are exactly one power-of-two apart (spec +/// 7.13.3; `av1_inv_txfm2d.c:272-276`, `abs(rect_type) == 1`). `dequant` is +/// still raster order (`dequant[i * w + j]`, row `i` of `h`, column `j` of +/// `w`) -- libaom's own buffer for the same math is column-major, an +/// unrelated fact about ITS storage, not the spec's arithmetic (class +/// `reference-layout-not-spec`). +pub fn inverse_transform_2d_typed_wh( + dequant: &[i32], + w: usize, + h: usize, + bit_depth: u8, + tx_type: TxType, +) -> Vec { + let log2w = w.trailing_zeros(); + let log2h = h.trailing_zeros(); + assert_eq!(1usize << log2w, w, "width must be a power of two"); + assert_eq!(1usize << log2h, h, "height must be a power of two"); + assert_eq!(dequant.len(), w * h, "one coefficient per position"); let row_clamp = usize::from(bit_depth) + 8; let col_clamp = (usize::from(bit_depth) + 6).max(16); - let mut residual = vec![0i32; side * side]; + let mut residual = vec![0i32; w * h]; let (row_kind, col_kind) = tx_type.axes(); let (ud_flip, lr_flip) = tx_type.flip(); + // `get_rect_tx_log_ratio` (`av1_inv_txfm2d.c:248`): the scale fires only + // at ratio exactly 1, never 0 (square) or 2 (e.g. 4x16/16x4/8x32/32x8/ + // 16x64/64x16). + let rect_scale = (log2w as i32 - log2h as i32).abs() == 1; let mut t = [0i32; 64]; - for i in 0..side { - for j in 0..side { - t[j] = if i < 32 && j < 32 { - dequant[i * side + j] + for i in 0..h { + for j in 0..w { + let c = if i < 32 && j < 32 { dequant[i * w + j] } else { 0 }; + t[j] = if rect_scale { + round2(c * 2896, 12) } else { - 0 + c }; } - inverse_1d(&mut t, log2, row_clamp, row_kind); - for j in 0..side { + inverse_1d(&mut t, log2w, row_clamp, row_kind); + for j in 0..w { // The row's output is shifted, then clamped before the column // transform reads it back. - residual[i * side + j] = clamp_range(round2(t[j], row_shift(log2)), col_clamp); + residual[i * w + j] = clamp_range(round2(t[j], row_shift_wh(w, h)), col_clamp); } } @@ -822,16 +860,17 @@ pub fn inverse_transform_2d_typed( // place, because a flipped read/write pair aliases a column this same // loop has not visited yet (column `j`'s write target under `lr_flip` // is a column an unflipped loop would still need to read from later). - let mut out = vec![0i32; side * side]; - for j in 0..side { - let src_col = if lr_flip { side - 1 - j } else { j }; - for i in 0..side { - t[i] = residual[i * side + src_col]; + // `lr_flip` mirrors over `w` (the row axis), `ud_flip` over `h`. + let mut out = vec![0i32; w * h]; + for j in 0..w { + let src_col = if lr_flip { w - 1 - j } else { j }; + for i in 0..h { + t[i] = residual[i * w + src_col]; } - inverse_1d(&mut t, log2, col_clamp, col_kind); - for i in 0..side { - let dst_row = if ud_flip { side - 1 - i } else { i }; - out[dst_row * side + j] = round2(t[i], 4); + inverse_1d(&mut t, log2h, col_clamp, col_kind); + for i in 0..h { + let dst_row = if ud_flip { h - 1 - i } else { i }; + out[dst_row * w + j] = round2(t[i], 4); } } out @@ -856,8 +895,20 @@ pub fn dequant_and_inverse_typed( q_idx: i32, tx_type: TxType, ) -> Vec { - let dq = crate::quant::dequant(levels, side, bit_depth, q_idx); - inverse_transform_2d_typed(&dq, side, bit_depth, tx_type) + dequant_and_inverse_typed_wh(levels, side, side, bit_depth, q_idx, tx_type) +} + +/// [`dequant_and_inverse_typed`] widened to `(w, h)` (lane-recttx). +pub fn dequant_and_inverse_typed_wh( + levels: &[i32], + w: usize, + h: usize, + bit_depth: u8, + q_idx: i32, + tx_type: TxType, +) -> Vec { + let dq = crate::quant::dequant_wh(levels, w, h, bit_depth, q_idx); + inverse_transform_2d_typed_wh(&dq, w, h, bit_depth, tx_type) } /// [`dequant_and_inverse_typed`] at `DCT_DCT`. @@ -1572,4 +1623,83 @@ mod tests { assert_ne!(dct_adst, dct_dct); assert_ne!(adst_adst, dct_dct); } + + /// The lane-recttx charter's asymmetric coefficient block (`coeff` in + /// `lanes/recttx_dump.c`, which this pin was transcribed alongside): a + /// DC of 640 plus a distinct row-weighted/col-weighted 4x4 corner, zero + /// elsewhere, so a transposed axis produces a genuinely different + /// checksum rather than a coincidentally equal one. + fn recttx_coeff(w: usize, h: usize) -> Vec { + let mut d = vec![0i32; w * h]; + for i in 0..h { + for j in 0..w { + d[i * w + j] = if i == 0 && j == 0 { + 640 + } else if i < 4 && j < 4 { + (i as i32 + 1) * 24 - (j as i32 + 1) * 17 + } else { + 0 + }; + } + } + d + } + + fn weighted_checksum(residual: &[i32]) -> i64 { + residual + .iter() + .enumerate() + .map(|(idx, &v)| i64::from(v) * (idx as i64 + 1)) + .sum() + } + + /// Every one of the 14 rectangular sizes, DCT_DCT, `bit_depth = 8`, + /// pinned against `lanes/recttx_dump.c` / `.expected.txt` -- a real + /// libaom 1D-kernel-linked C harness, not a from-scratch reimplement. + /// The transposed HxW twin runs in the SAME test (class + /// `scan-weights-cross-axis`): a swapped-axis bug in + /// `inverse_transform_2d_typed_wh` would either fail its own pin or + /// accidentally match its twin's pin, and the two expected values here + /// are deliberately different, so neither escape is possible. + #[test] + fn rect_sizes_pinned_against_libaom() { + let cases: &[(usize, usize, i64)] = &[ + (4, 8, 7290), + (8, 4, 7223), + (8, 16, 56211), + (16, 8, 56161), + (16, 32, 893635), + (32, 16, 893210), + (32, 64, 14260693), + (64, 32, 14265125), + (4, 16, 20091), + (16, 4, 20156), + (8, 32, 159207), + (32, 8, 159430), + (16, 64, 2537255), + (64, 16, 2548119), + ]; + for &(w, h, expected) in cases { + let dequant = recttx_coeff(w, h); + let residual = inverse_transform_2d_typed_wh(&dequant, w, h, 8, TxType::DctDct); + assert_eq!( + weighted_checksum(&residual), + expected, + "{w}x{h} checksum mismatch" + ); + } + } + + /// The square path must not move: `row_shift_wh(side, side)` reduces to + /// the pre-lane `row_shift(log2)` table, and the `side`-taking wrapper + /// must still equal the `(w, h)` core called with `w == h == side`. + #[test] + fn square_wrapper_matches_wh_core() { + for side in [4, 8, 16, 32, 64] { + let dequant = recttx_coeff(side, side); + let via_wrapper = inverse_transform_2d_typed(&dequant, side, 8, TxType::DctDct); + let via_wh = inverse_transform_2d_typed_wh(&dequant, side, side, 8, TxType::DctDct); + assert_eq!(via_wrapper, via_wh, "side {side}"); + } + } } diff --git a/lanes/recttx_dump.c b/lanes/recttx_dump.c new file mode 100644 index 00000000..00e22ecc --- /dev/null +++ b/lanes/recttx_dump.c @@ -0,0 +1,145 @@ +/* lane-recttx r1: pins the 14 rectangular inverse transform sizes against + * the REAL libaom 1D kernels (av1_idct4/8/16/32/64, DCT_DCT only), linked + * from libaom.a -- NOT the higher-level `av1_inv_txfm2d_add_WxH_c` facade, + * which segfaults called standalone from a bare harness (its + * `av1_get_inv_txfm_cfg` path resolves a NULL function pointer outside a + * real decoder's init sequence; root cause not chased further -- turn + * budget). Calling the plain per-axis kernels directly sidesteps that and + * is still linked, not transcribed, code for the part that actually needs + * checking here: the axis-swap / rect-scale / row-shift PLUMBING is this + * harness's own C, ported line-for-line from `inv_txfm2d_add_c` + * (av1_inv_txfm2d.c:234-315) -- see the charter's `reference-layout-not-spec` + * note: libaom's row-pass input is COLUMN-major (`input[c * txfm_size_row + + * r]`, av1_inv_txfm2d.c:275), our own `dequant` is ROW-major + * (`dequant[i * w + j]`) -- this harness transposes at the boundary, + * feeding the SAME logical coefficient grid the Rust side gets, so a + * transposed-axis bug in the Rust port cannot be cancelled by an + * equally-transposed harness. + * + * stage_range is fixed at 16 for every stage: `av1_gen_inv_stage_range` + * (av1_inv_txfm2d.c:194-196) sets `opt_range_row = opt_range_col = 16` for + * `bd == 8`, which is exactly what this lane's row_clamp/col_clamp already + * are at bit_depth 8 (`bit_depth + 8 = 16`, `max(bit_depth + 6, 16) = 16`). + * + * Build: cc -O2 -I lanes/recttx_dump.c /libaom.a \ + * -lm -lpthread -o /tmp/recttx_dump + */ +#include +#include +#include + +typedef int32_t tran_low_t; + +extern void av1_idct4(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range); +extern void av1_idct8(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range); +extern void av1_idct16(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range); +extern void av1_idct32(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range); +extern void av1_idct64(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range); + +#define INV_COS_BIT 12 +static const int8_t STAGE_RANGE[16] = { 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 }; + +typedef void (*idct_fn)(const int32_t *, int32_t *, int8_t, const int8_t *); + +static idct_fn idct_for(int n) { + switch (n) { + case 4: return av1_idct4; + case 8: return av1_idct8; + case 16: return av1_idct16; + case 32: return av1_idct32; + case 64: return av1_idct64; + } + return NULL; +} + +static int round_shift(int64_t x, int bit) { return (int)((x + (1LL << (bit - 1))) >> bit); } + +/* `Transform_Row_Shift` / `av1_inv_txfm_shift_ls` (av1_inv_txfm2d.c:132-158, + * `shift[0]`): keyed on the full (w, h) TX size, identical table the Rust + * side's `row_shift_wh` carries. */ +static int row_shift_wh(int w, int h) { + if (w == 4 && h == 4) return 0; + if (w == 8 && h == 8) return 1; + if ((w == 16 && h == 16) || (w == 32 && h == 32) || (w == 64 && h == 64)) return 2; + if ((w == 4 && h == 8) || (w == 8 && h == 4)) return 0; + if ((w == 8 && h == 16) || (w == 16 && h == 8)) return 1; + if ((w == 16 && h == 32) || (w == 32 && h == 16)) return 1; + if ((w == 32 && h == 64) || (w == 64 && h == 32)) return 1; + if ((w == 4 && h == 16) || (w == 16 && h == 4)) return 1; + if ((w == 8 && h == 32) || (w == 32 && h == 8)) return 2; + if ((w == 16 && h == 64) || (w == 64 && h == 16)) return 2; + fprintf(stderr, "no row shift for %dx%d\n", w, h); + return -1; +} + +/* Asymmetric per (row, col) coefficient in the coded corner (min(w,32) x + * min(h,32)), zero elsewhere -- row weight (24) and col weight (17) differ + * so a transposed-axis bug lands on a different value, not a + * coincidentally equal one. */ +static int32_t coeff(int i, int j) { + if (i >= 32 || j >= 32) return 0; + if (i == 0 && j == 0) return 640; /* DC */ + if (i < 4 && j < 4) return (i + 1) * 24 - (j + 1) * 17; + return 0; +} + +/* `inv_txfm2d_add_c`'s DCT_DCT path (av1_inv_txfm2d.c:234-315), transcribed + * for (w, h) with `dequant` in ROW-major order as our Rust side keeps it -- + * libaom's own `input[c * txfm_size_row + r]` column-major addressing is + * reproduced here (`col_major`), not copied into our indexing convention. */ +static void run(const char *name, int w, int h) { + tran_low_t row_major[64 * 64], col_major[64 * 64]; + for (int i = 0; i < h; i++) + for (int j = 0; j < w; j++) row_major[i * w + j] = coeff(i, j); + for (int c = 0; c < w; c++) + for (int r = 0; r < h; r++) col_major[c * h + r] = row_major[r * w + c]; + + int rect_type_abs1 = (__builtin_ctz(w) - __builtin_ctz(h) == 1) || (__builtin_ctz(h) - __builtin_ctz(w) == 1); + int shift0 = row_shift_wh(w, h); + idct_fn row_fn = idct_for(w), col_fn = idct_for(h); + + int32_t buf[64 * 64]; + int32_t temp_in[64], temp_out[64]; + for (int r = 0; r < h; r++) { + for (int c = 0; c < w; c++) { + int32_t v = col_major[c * h + r]; + temp_in[c] = rect_type_abs1 ? round_shift((int64_t)v * 2896, 12) : v; + } + row_fn(temp_in, buf + r * w, INV_COS_BIT, STAGE_RANGE); + for (int c = 0; c < w; c++) buf[r * w + c] = round_shift(buf[r * w + c], shift0); + } + + int32_t out[64 * 64]; + for (int c = 0; c < w; c++) { + for (int r = 0; r < h; r++) temp_in[r] = buf[r * w + c]; + col_fn(temp_in, temp_out, INV_COS_BIT, STAGE_RANGE); + for (int r = 0; r < h; r++) out[r * w + c] = round_shift(temp_out[r], 4); + } + + int64_t checksum = 0; + for (int r = 0; r < h; r++) + for (int c = 0; c < w; c++) { + int idx = r * w + c; + checksum += (int64_t)out[idx] * (int64_t)(idx + 1); + } + (void)name; + printf("%dx%d DCT_DCT checksum=%lld\n", w, h, (long long)checksum); +} + +int main(void) { + run("4x8", 4, 8); + run("8x4", 8, 4); + run("8x16", 8, 16); + run("16x8", 16, 8); + run("16x32", 16, 32); + run("32x16", 32, 16); + run("32x64", 32, 64); + run("64x32", 64, 32); + run("4x16", 4, 16); + run("16x4", 16, 4); + run("8x32", 8, 32); + run("32x8", 32, 8); + run("16x64", 16, 64); + run("64x16", 64, 16); + return 0; +} diff --git a/lanes/recttx_dump.expected.txt b/lanes/recttx_dump.expected.txt new file mode 100644 index 00000000..baaaeb28 --- /dev/null +++ b/lanes/recttx_dump.expected.txt @@ -0,0 +1,14 @@ +4x8 DCT_DCT checksum=7290 +8x4 DCT_DCT checksum=7223 +8x16 DCT_DCT checksum=56211 +16x8 DCT_DCT checksum=56161 +16x32 DCT_DCT checksum=893635 +32x16 DCT_DCT checksum=893210 +32x64 DCT_DCT checksum=14260693 +64x32 DCT_DCT checksum=14265125 +4x16 DCT_DCT checksum=20091 +16x4 DCT_DCT checksum=20156 +8x32 DCT_DCT checksum=159207 +32x8 DCT_DCT checksum=159430 +16x64 DCT_DCT checksum=2537255 +64x16 DCT_DCT checksum=2548119