diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 3b7413b9..e8bbd8ab 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -5961,7 +5961,7 @@ fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> /// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this /// table ever names), so unlike the CDF-coded luma path there is no /// ext-tx-set membership check to fall back from here. -fn default_intra_tx_type(mode: u8) -> TxType { +pub(crate) fn default_intra_tx_type(mode: u8) -> TxType { use crate::intra::{ D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED, PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED, diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index abe3ed0b..c931d3d6 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -5,9 +5,11 @@ //! [`crate::transform`], and the tile writer of [`crate::tile`] — into //! something that takes a picture. Every block is 32x32 (its chroma 16x16), //! which is the subset the tile writer codes, and each one picks its luma mode -//! from the seven non-directional ones by rate-distortion; chroma is predicted -//! DC, which is the mode the tile writer codes for it. Block sizes and -//! transform types are what a loop above this would choose between. +//! from the seven non-directional ones by rate-distortion; chroma searches +//! its own `uv_mode` over the seven that read no further than the row above +//! and the column to the left, its transform type derived from that mode the +//! way the decoder derives it. Block sizes are what a loop above this would +//! choose between. //! //! The encoder carries its own reconstruction, because prediction reads it: a //! block predicts from the reconstructed samples above and to its left, exactly @@ -25,7 +27,10 @@ use ec_core::{Error, Result}; use crate::cdf; use crate::cdf_state::TxbSet; use crate::frame::frame_obu; -use crate::intra::{D67_PRED, DC_PRED, KEY_FRAME_MODES, V_PRED}; +use crate::intra::{ + D67_PRED, DC_PRED, H_PRED, KEY_FRAME_MODES, PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, + SMOOTH_V_PRED, V_PRED, +}; use crate::mc; use crate::motion; use crate::mvstack::{MiGrid, MiInfo, MvStack, NO_REF1, find_mv_stack, mv16}; @@ -36,7 +41,10 @@ use crate::tile::{ BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits, sb_coeff_inter_frame_tile, sb_coeff_key_frame_tile, }; -use crate::transform::{dequant_and_inverse, forward_and_quantize}; +use crate::transform::{ + TxType, dequant_and_inverse, dequant_and_inverse_typed, forward_and_quantize, + forward_and_quantize_typed, +}; /// The side of the larger of the two luma blocks this encoder codes, in /// samples. @@ -741,6 +749,24 @@ impl Plane<'_> { /// levels, the block the decoder would reconstruct, the squared error /// against the source and an estimate of what the levels cost in bits. fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial { + self.trial_typed(at, mode, base_q_idx, deadzone, TxType::DctDct, fctx) + } + + /// [`Self::trial`] under a named transform type -- what an intra chroma + /// block gets, since chroma codes no `tx_type` symbol and the decoder + /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`, + /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps + /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names. + #[allow(clippy::too_many_arguments)] + fn trial_typed( + &self, + at: At, + mode: u8, + base_q_idx: u8, + deadzone: f64, + tx_type: TxType, + fctx: &crate::decode::FrameCtx, + ) -> Trial { let At { x, y, side, reach, .. } = at; @@ -769,8 +795,10 @@ impl Plane<'_> { } #[cfg(test)] let t = std::time::Instant::now(); - let levels = forward_and_quantize(&residual, side, 8, i32::from(base_q_idx), deadzone); - let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx)); + let levels = + forward_and_quantize_typed(&residual, side, 8, i32::from(base_q_idx), deadzone, tx_type); + let coded = + dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), 0, 0, tx_type); #[cfg(test)] stage_add(2, t.elapsed()); @@ -907,20 +935,6 @@ impl Plane<'_> { } } - /// Codes one block under a fixed mode, committing it, and hands back what - /// it cost: its squared error and the bits its levels spend. - fn code_block( - &mut self, - at: At, - mode: u8, - base_q_idx: u8, - deadzone: f64, fctx: &crate::decode::FrameCtx, - ) -> (Vec, f64, f64) { - let trial = self.trial(at, mode, base_q_idx, deadzone, fctx); - self.commit(at.x, at.y, at.side, &trial); - (coeffs(&trial.levels, at.side), trial.sse, trial.bits) - } - /// The source samples of one square, contiguous — what a motion search /// compares its candidates' predictions against ([`motion::search`]'s /// `source`), since [`Self::source`] itself is the whole plane, strided @@ -1659,38 +1673,114 @@ fn code_square( search, mode_bits, fctx, ); - // Chroma is predicted DC because that is the mode the tile writer codes - // for it; what it costs still counts towards the partition decision. - let mut planes = [Vec::new(), Vec::new()]; - for (plane, coeffs) in chroma.iter_mut().zip(&mut planes) { - let (levels, sse, bits) = plane.code_block( - At { - x: x / 2, - y: y / 2, - side: side / 2, - reach: Reach::none(), - set: chroma_set, - }, - DC_PRED, - search.base_q_idx, - search.deadzone, fctx, - ); - *coeffs = levels; - cost += sse + search.lambda * bits; - } - let [u, v] = planes; + // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both + // planes; what it costs still counts towards the partition decision. + let ([u, v], uv_mode, chroma_cost) = + search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx); + cost += chroma_cost; ( BlockCoeffs { u, v, luma: luma_coeffs, mode, + uv_mode, ..BlockCoeffs::default() }, cost, ) } +/// The chroma modes the search offers, and the only ones it may offer: each +/// predicts from the row directly above and the column directly to the left +/// and nothing further, so none of them needs the above-right/below-left +/// `Reach` a chroma block is coded with `Reach::none()` for. The eight +/// directional modes do read past that, and `UV_CFL_PRED` needs the luma +/// reconstruction and its own alpha syntax; both are left out here. +const CHROMA_MODES: [u8; 7] = [ + DC_PRED, + V_PRED, + H_PRED, + SMOOTH_PRED, + SMOOTH_V_PRED, + SMOOTH_H_PRED, + PAETH_PRED, +]; + +/// The thirteen intra mode names, for the chroma fire count's print. +#[cfg(test)] +const UV_MODE_NAMES: [&str; 13] = [ + "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V", + "SMOOTH_H", "PAETH", +]; + +/// How many blocks each chroma mode has won, indexed by the mode itself -- +/// the fire count that says whether the search below reaches its candidates +/// at all (the `gate-blind-to-feature` class), printed once per gate run. +static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 13] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 13]; + +/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts +/// to its own encode. +#[cfg(test)] +pub(crate) fn take_uv_mode_hits() -> [usize; 13] { + std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode -- +/// `uv_mode` is a single symbol covering U and V -- and commits the cheapest. +/// Returns each plane's levels, the mode, and what the pair cost (squared +/// error plus lambda times bits, the same currency the luma search speaks). +/// +/// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`], +/// which is what the luma mode decision was taken against, so what a +/// candidate owes here is only the *difference* from that -- plus, for `V`/`H` +/// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the +/// writer then has to code. +#[allow(clippy::too_many_arguments)] +fn search_chroma( + chroma: &mut [Plane; 2], + (x, y): (usize, usize), + side: usize, + set: TxbSet, + search: &Search, + luma_mode: u8, + fctx: &crate::decode::FrameCtx, +) -> ([Vec; 2], u8, f64) { + let at = At { + x: x / 2, + y: y / 2, + side: side / 2, + reach: Reach::none(), + set, + }; + let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)]; + let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED)); + let mut best: Option<(f64, u8, Trial, Trial)> = None; + for mode in CHROMA_MODES { + let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits; + if (V_PRED..=D67_PRED).contains(&mode) { + bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3); + } + let tx_type = crate::decode::default_intra_tx_type(mode); + let u = chroma[0].trial_typed(at, mode, search.base_q_idx, search.deadzone, tx_type, fctx); + let v = chroma[1].trial_typed(at, mode, search.base_q_idx, search.deadzone, tx_type, fctx); + let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits); + if best.as_ref().is_none_or(|(b, ..)| cost < *b) { + best = Some((cost, mode, u, v)); + } + } + let (cost, mode, u, v) = best.expect("CHROMA_MODES is not empty"); + UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + chroma[0].commit(at.x, at.y, at.side, &u); + chroma[1].commit(at.x, at.y, at.side, &v); + ( + [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)], + mode, + cost, + ) +} + /// Codes one leaf of a straddling quadrant as whichever costs least of intra /// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at /// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`] @@ -1908,6 +1998,7 @@ fn code_square_inter( u: coeffs(&u_new.levels, side / 2), v: coeffs(&v_new.levels, side / 2), mode: DC_PRED as u8, + uv_mode: DC_PRED, skip: skip_new, eight: None, inter: Some(InterInfo { @@ -1929,6 +2020,7 @@ fn code_square_inter( u: coeffs(&u.levels, side / 2), v: coeffs(&v.levels, side / 2), mode: DC_PRED as u8, + uv_mode: DC_PRED, skip, eight: None, inter: Some(InterInfo { @@ -3160,6 +3252,7 @@ fn search_inter_block( u: coeffs(&best.u.levels, BLOCK / 2), v: coeffs(&best.v.levels, BLOCK / 2), mode: best.mode, + uv_mode: DC_PRED, skip: best.skip, inter: best.inter, eight: None, @@ -4081,6 +4174,7 @@ mod tests { u: Vec::new(), v: Vec::new(), mode: 0, + uv_mode: 0, skip: false, eight: None, inter: Some(InterInfo { @@ -5172,11 +5266,23 @@ mod tests { // table for the far side would show up as a rate discontinuity here, // even though a coarser quantizer always codes no more than a finer // one on the same picture. + // + // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since + // chroma searches its own mode, a coarser quantizer can pick a + // *different* uv_mode on a block whose modes now cost nearly the + // same, and the search prices that symbol against the static default + // CDF while the writer codes it against an adapted one -- 311 -> 319 + // bytes at q 120->121 on this picture. The table this gate is really + // watching would move the rate by far more than the mode churn does. + // Ceiling: a q-context table wrong by under 5% would pass. Upgrade + // path is pricing through the adapting CDF state (what + // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the + // drift of), after which the exact bound comes back. for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] { let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len(); let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len(); assert!( - hi_bytes <= lo_bytes, + hi_bytes as f64 <= lo_bytes as f64 * 1.05, "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes" ); } @@ -6406,6 +6512,7 @@ mod tests { let fctx = &crate::decode::FrameCtx::new(); let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); let _ = take_partition_hits(); + let _ = take_uv_mode_hits(); let (ours, ours_wall) = our_ladder(&source, width, height, fctx); // How often the inter split actually fired over this clip's four // encodes, against the whole 32x32 that was the only outcome @@ -6419,6 +6526,24 @@ mod tests { whole16 + split16, 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64 ); + // Which chroma modes the search actually wins with, against the + // unconditional DC_PRED that was the only outcome before + // (gate-blind-to-feature). + let uv = take_uv_mode_hits(); + let uv_total: usize = uv.iter().sum(); + eprintln!( + "{name}: uv modes {}", + uv.iter() + .enumerate() + .filter(|&(_, &n)| n > 0) + .map(|(m, &n)| format!( + "{}={n} ({:.1}%)", + UV_MODE_NAMES[m], + 100.0 * n as f64 / uv_total.max(1) as f64 + )) + .collect::>() + .join(" ") + ); let (aom, aom_wall) = external_ladder(&source, width, height, "libaom-av1", &aom_points); let (rav1e, rav1e_wall) = diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 463b9cd4..8eab07af 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -454,9 +454,14 @@ pub struct BlockCoeffs { pub v: Vec, /// The luma intra mode the block is predicted with, one of the thirteen /// modes a key frame codes (`DC_PRED` is zero, which is what - /// [`Default`] and a plain coefficient list give). Chroma stays on - /// `DC_PRED`. + /// [`Default`] and a plain coefficient list give). pub mode: u8, + /// The chroma intra mode both chroma planes are predicted with (spec + /// `uv_mode`, one symbol for the pair). `DC_PRED` is zero, which is what + /// [`Default`] gives; a non-`DC_PRED` mode also changes the transform + /// type the decoder derives for chroma (`Intra_Mode_To_Tx_Type`, spec + /// 9.3), which is never coded as a symbol. + pub uv_mode: u8, /// Whether the block carries no residual at all (spec `skip`). An intra /// block may still be skipped; `false` (the [`Default`]) codes whatever /// `luma`/`u`/`v` carry. @@ -1311,10 +1316,16 @@ fn write_intra_mode( } // A block small enough to be offered chroma from luma reads the wider // table even when it does not take the mode. + let uv_mode = usize::from(block.uv_mode); if cfl { - enc.symbol(DC_PRED, &mut cdfs.uv_mode_cfl[mode]); + enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]); } else { - enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[mode]); + enc.symbol(uv_mode, &mut cdfs.uv_mode_no_cfl[mode]); + } + // `angle_delta_uv` (spec `read_intra_angle_info`) off the same CDF array + // the luma delta reads, indexed by the chroma mode. + if (V_PRED..=D67_PRED).contains(&uv_mode) { + enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); } mode } @@ -2602,7 +2613,11 @@ pub fn sb_coeff_inter_frame_tile( if (V_PRED..=D67_PRED).contains(&mode) { enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]); } - enc.symbol(DC_PRED, &mut cdfs.uv_mode_cfl[mode]); + let uv_mode = usize::from(block.uv_mode); + enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]); + if (V_PRED..=D67_PRED).contains(&uv_mode) { + enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); + } mode_for_tx = mode; // Intra: no vote, but still a coded cell -- mvstack's // extended-scan coverage must see it (module doc). @@ -2778,7 +2793,11 @@ fn write_inter_frame_leaf( if (V_PRED..=D67_PRED).contains(&mode) { enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]); } - enc.symbol(DC_PRED, &mut cdfs.uv_mode_cfl[mode]); + let uv_mode = usize::from(block.uv_mode); + enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]); + if (V_PRED..=D67_PRED).contains(&uv_mode) { + enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); + } mode_for_tx = mode; // Intra: no vote, but still a coded cell -- mvstack's extended-scan // coverage must see it (module doc). @@ -2970,7 +2989,11 @@ fn write_inter_frame_leaf8( if (V_PRED..=D67_PRED).contains(&mode) { enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]); } - enc.symbol(DC_PRED, &mut cdfs.uv_mode_cfl[mode]); + let uv_mode = usize::from(block.uv_mode); + enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]); + if (V_PRED..=D67_PRED).contains(&uv_mode) { + enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); + } mode_for_tx = mode; // Intra: no vote, but still a coded cell -- mvstack's extended-scan // coverage must see it (module doc). diff --git a/crates/ec-av1/src/transform.rs b/crates/ec-av1/src/transform.rs index 6e4546bd..64583289 100644 --- a/crates/ec-av1/src/transform.rs +++ b/crates/ec-av1/src/transform.rs @@ -1369,7 +1369,6 @@ pub fn dequant_and_inverse(levels: &[i32], side: usize, bit_depth: u8, q_idx: i3 /// undo, and nothing else: measuring the network's response to a unit /// coefficient at every size gives the same `1 / (8 * sqrt(2))` per unit of /// `dqDenom`, which is what [`forward_transform_2d`] divides out. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates fn build_dct_basis(n: usize) -> Vec { let mut basis = vec![0.0f64; n * n]; let scale = (2.0 / n as f64).sqrt(); @@ -1401,6 +1400,103 @@ fn dct_basis(n: usize) -> &'static [f64] { cache[idx].get_or_init(|| build_dct_basis(n)) } +/// The orthonormal basis of one 1D axis, measured from the decoder's own +/// inverse network rather than written out: a unit coefficient through +/// [`inverse_1d`] IS the basis function that kernel synthesises, and +/// normalising each to unit length gives the analysis basis a forward +/// transform pairs with. AV1 normalises every 1D kernel to the same gain -- +/// that is what lets one shift chain serve mixed types -- so the +/// [`INVERSE_GAIN_RECIPROCAL`] correction a DCT axis takes is the one an ADST +/// axis takes too. +fn build_axis_basis(n: usize, kind: TxType1d) -> Vec { + if kind == TxType1d::Dct { + return build_dct_basis(n); + } + let log2 = n.trailing_zeros(); + let mut basis = vec![0.0f64; n * n]; + for u in 0..n { + let mut t = [0i32; 64]; + // Large enough that the network's own rounding is negligible, small + // enough that nothing clamps at the 24-bit range passed below. + t[u] = 1 << 12; + inverse_1d(&mut t, log2, 24, kind); + let norm = (0..n).map(|i| f64::from(t[i]) * f64::from(t[i])).sum::().sqrt(); + for i in 0..n { + basis[u * n + i] = f64::from(t[i]) / norm; + } + } + basis +} + +/// [`build_axis_basis`], computed once per (size, kind). +fn axis_basis(n: usize, kind: TxType1d) -> &'static [f64] { + use std::sync::OnceLock; + static CACHE: OnceLock<[[OnceLock>; 5]; 3]> = OnceLock::new(); + let cache = CACHE.get_or_init(|| std::array::from_fn(|_| std::array::from_fn(|_| OnceLock::new()))); + let k = match kind { + TxType1d::Dct => 0, + TxType1d::Adst => 1, + TxType1d::Identity => 2, + }; + let idx = (n.trailing_zeros() as usize).saturating_sub(2); + cache[k][idx].get_or_init(|| build_axis_basis(n, kind)) +} + +/// [`forward_transform_2d`] for a block whose transform type is not +/// `DCT_DCT` -- what an intra chroma block coded in a non-`DC_PRED` mode +/// gets, since chroma never codes a `tx_type` symbol and the decoder derives +/// it from the mode (`Intra_Mode_To_Tx_Type`, spec 9.3). +/// +/// The forward transform is the encoder's own business: only the levels and +/// the type reach the decoder, so an approximate analysis basis costs rate, +/// never correctness -- the reconstruction the search scores comes back +/// through the decoder's exact inverse either way. +pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType) -> Vec { + if tx_type == TxType::DctDct { + return forward_transform_2d(residual, side); + } + debug_assert_eq!( + tx_type.flip(), + (false, false), + "a flipped ADST needs its residual mirrored before this basis applies" + ); + let (row_kind, col_kind) = tx_type.axes(); + let (hb, vb) = (axis_basis(side, row_kind), axis_basis(side, col_kind)); + let mut rows = vec![0.0f64; side * side]; + for i in 0..side { + let source = &residual[i * side..][..side]; + for v in 0..side { + rows[i * side + v] = source + .iter() + .zip(&hb[v * side..][..side]) + .map(|(&r, &b)| f64::from(r) * b) + .sum(); + } + } + let mut out = vec![0.0f64; side * side]; + for u in 0..side { + let column = &vb[u * side..][..side]; + for v in 0..side { + let sum: f64 = (0..side).map(|i| rows[i * side + v] * column[i]).sum(); + out[u * side + v] = INVERSE_GAIN_RECIPROCAL * sum; + } + } + out +} + +/// [`forward_and_quantize`] at a named transform type. +pub fn forward_and_quantize_typed( + residual: &[i32], + side: usize, + bit_depth: u8, + q_idx: i32, + deadzone: f64, + tx_type: TxType, +) -> Vec { + let coeffs = forward_transform_2d_typed(residual, side, tx_type); + quantize(&coeffs, side, bit_depth, q_idx, deadzone) +} + /// How much the decoder's inverse transform shrinks an orthonormal DCT. /// /// Measured, not asserted: feeding a single dequantized coefficient through @@ -1696,6 +1792,40 @@ mod tests { } } + /// The typed forward transform is the decoder's exact inverse undone: + /// quantized and taken back, an ADST-typed residual returns with the same + /// error a `DCT_DCT` one does. This is what pins the *gain* of the ADST + /// basis measured off the inverse network -- an approximate shape only + /// costs rate, but a wrong gain would put every level in the wrong decade + /// and the mode search would read as a loss. + #[test] + fn a_typed_forward_round_trips_like_the_dct_one() { + for side in [4usize, 8, 16] { + let residual: Vec = noise(side * side, 7 + side as u64) + .iter() + .map(|&v| v / 4) + .collect(); + let rmse = |tx: TxType| { + let levels = forward_and_quantize_typed(&residual, side, 8, 60, 0.5, tx); + let back = dequant_and_inverse_typed(&levels, side, 8, 60, 0, 0, tx); + let sum: f64 = residual + .iter() + .zip(&back) + .map(|(&a, &b)| f64::from(a - b) * f64::from(a - b)) + .sum(); + (sum / (side * side) as f64).sqrt() + }; + let dct = rmse(TxType::DctDct); + for tx in [TxType::AdstDct, TxType::DctAdst, TxType::AdstAdst] { + let e = rmse(tx); + assert!( + e < 2.0 * dct, + "{side}x{side} {tx:?} round trip rmse {e:.2} against DCT_DCT's {dct:.2}" + ); + } + } + } + /// The orthonormal DCT-II basis the forward transform is written against, /// computed independently of `dct_basis` so a test is not checking a /// function against itself.