forge
Explore
Log in

Don't you dare go Hollow

Chroma searches its own uv_mode instead of coding DC unconditionally

Browse files at this commit

b0a80f39af5582b3e21a75e2b2a744c74c3be3c8Ahmet Kaan GümüşParent: 1dcee8a
  • feat
    • chroma searches its own uv_mode instead of coding DC unconditionally
Show full message
feat(av1): chroma searches its own uv_mode instead of coding DC unconditionally

Both chroma planes were predicted DC_PRED at every block because that is all
the tile writer coded. They now search the seven modes that read no further
than the row directly above and the column directly to the left -- DC, V, H,
SMOOTH, SMOOTH_V, SMOOTH_H, PAETH -- which is exactly the set a chroma block
coded with `Reach::none()` may offer; the eight directional modes read past
that and UV_CFL_PRED needs its own alpha syntax.

A chroma block never codes a tx_type symbol: the decoder derives it from the
chroma mode (`Intra_Mode_To_Tx_Type`, spec 9.3), so a non-DC uv_mode moves
chroma onto an ADST-bearing transform. The forward half of that is new here
and measured off the decoder's own inverse network -- a unit coefficient
through `inverse_1d` IS the basis function it synthesises -- rather than
written out, which is safe because only the levels and the derived type reach
the decoder: the reconstruction the search scores still comes back through
the exact inverse.

BD-rate vs libaom 234.0/260.3/318.5 -> 216.4/235.5/289.2 and vs rav1e
171.9/203.2/155.3 -> 157.8/178.3/141.1 (1080p/2160p/screen), down on all
three against both references. Wall 9.8s -> ~11.1s per clip ladder. The gate's
own ffmpeg-decodes-sample-exact assertion holds, so the writer's uv_mode and
angle_delta_uv syntax and the derived chroma transform agree with a real
decoder. Fire counts printed per clip: DC wins 79.1/84.1/43.8%, PAETH
7.1/6.6/29.0%, H 3.3/2.5/16.6%.
crates/ec-av1/src/decode.rsmodified+1 -1
@@ -5875,7 +5875,7 @@ fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) ->
58755875 /// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
58765876 /// table ever names), so unlike the CDF-coded luma path there is no
58775877 /// ext-tx-set membership check to fall back from here.
5878-fn default_intra_tx_type(mode: u8) -> TxType {
5878+pub(crate) fn default_intra_tx_type(mode: u8) -> TxType {
58795879 use crate::intra::{
58805880 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
58815881 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
crates/ec-av1/src/encode.rsmodified+167 -42
@@ -5,9 +5,11 @@
55 //! [`crate::transform`], and the tile writer of [`crate::tile`] — into
66 //! something that takes a picture. Every block is 32x32 (its chroma 16x16),
77 //! which is the subset the tile writer codes, and each one picks its luma mode
8-//! from the seven non-directional ones by rate-distortion; chroma is predicted
9-//! DC, which is the mode the tile writer codes for it. Block sizes and
10-//! transform types are what a loop above this would choose between.
8+//! from the seven non-directional ones by rate-distortion; chroma searches
9+//! its own `uv_mode` over the seven that read no further than the row above
10+//! and the column to the left, its transform type derived from that mode the
11+//! way the decoder derives it. Block sizes are what a loop above this would
12+//! choose between.
1113 //!
1214 //! The encoder carries its own reconstruction, because prediction reads it: a
1315 //! block predicts from the reconstructed samples above and to its left, exactly
@@ -25,7 +27,10 @@ use ec_core::{Error, Result};
2527 use crate::cdf;
2628 use crate::cdf_state::TxbSet;
2729 use crate::frame::frame_obu;
28-use crate::intra::{D67_PRED, DC_PRED, KEY_FRAME_MODES, V_PRED};
30+use crate::intra::{
31+ D67_PRED, DC_PRED, H_PRED, KEY_FRAME_MODES, PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED,
32+ SMOOTH_V_PRED, V_PRED,
33+};
2934 use crate::mc;
3035 use crate::motion;
3136 use crate::mvstack::{MiGrid, MiInfo, MvStack, NO_REF1, find_mv_stack, mv16};
@@ -36,7 +41,10 @@ use crate::tile::{
3641 BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits,
3742 sb_coeff_inter_frame_tile, sb_coeff_key_frame_tile,
3843 };
39-use crate::transform::{dequant_and_inverse, forward_and_quantize};
44+use crate::transform::{
45+ TxType, dequant_and_inverse, dequant_and_inverse_typed, forward_and_quantize,
46+ forward_and_quantize_typed,
47+};
4048
4149 /// The side of the larger of the two luma blocks this encoder codes, in
4250 /// samples.
@@ -741,6 +749,24 @@ impl Plane<'_> {
741749 /// levels, the block the decoder would reconstruct, the squared error
742750 /// against the source and an estimate of what the levels cost in bits.
743751 fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial {
752+ self.trial_typed(at, mode, base_q_idx, deadzone, TxType::DctDct, fctx)
753+ }
754+
755+ /// [`Self::trial`] under a named transform type -- what an intra chroma
756+ /// block gets, since chroma codes no `tx_type` symbol and the decoder
757+ /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`,
758+ /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
759+ /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
760+ #[allow(clippy::too_many_arguments)]
761+ fn trial_typed(
762+ &self,
763+ at: At,
764+ mode: u8,
765+ base_q_idx: u8,
766+ deadzone: f64,
767+ tx_type: TxType,
768+ fctx: &crate::decode::FrameCtx,
769+ ) -> Trial {
744770 let At {
745771 x, y, side, reach, ..
746772 } = at;
@@ -769,8 +795,10 @@ impl Plane<'_> {
769795 }
770796 #[cfg(test)]
771797 let t = std::time::Instant::now();
772- let levels = forward_and_quantize(&residual, side, 8, i32::from(base_q_idx), deadzone);
773- let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));
798+ let levels =
799+ forward_and_quantize_typed(&residual, side, 8, i32::from(base_q_idx), deadzone, tx_type);
800+ let coded =
801+ dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), 0, 0, tx_type);
774802 #[cfg(test)]
775803 stage_add(2, t.elapsed());
776804
@@ -907,20 +935,6 @@ impl Plane<'_> {
907935 }
908936 }
909937
910- /// Codes one block under a fixed mode, committing it, and hands back what
911- /// it cost: its squared error and the bits its levels spend.
912- fn code_block(
913- &mut self,
914- at: At,
915- mode: u8,
916- base_q_idx: u8,
917- deadzone: f64, fctx: &crate::decode::FrameCtx,
918- ) -> (Vec<Coeff>, f64, f64) {
919- let trial = self.trial(at, mode, base_q_idx, deadzone, fctx);
920- self.commit(at.x, at.y, at.side, &trial);
921- (coeffs(&trial.levels, at.side), trial.sse, trial.bits)
922- }
923-
924938 /// The source samples of one square, contiguous — what a motion search
925939 /// compares its candidates' predictions against ([`motion::search`]'s
926940 /// `source`), since [`Self::source`] itself is the whole plane, strided
@@ -1659,38 +1673,114 @@ fn code_square(
16591673 search,
16601674 mode_bits, fctx,
16611675 );
1662- // Chroma is predicted DC because that is the mode the tile writer codes
1663- // for it; what it costs still counts towards the partition decision.
1664- let mut planes = [Vec::new(), Vec::new()];
1665- for (plane, coeffs) in chroma.iter_mut().zip(&mut planes) {
1666- let (levels, sse, bits) = plane.code_block(
1667- At {
1668- x: x / 2,
1669- y: y / 2,
1670- side: side / 2,
1671- reach: Reach::none(),
1672- set: chroma_set,
1673- },
1674- DC_PRED,
1675- search.base_q_idx,
1676- search.deadzone, fctx,
1677- );
1678- *coeffs = levels;
1679- cost += sse + search.lambda * bits;
1680- }
1681- let [u, v] = planes;
1676+ // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
1677+ // planes; what it costs still counts towards the partition decision.
1678+ let ([u, v], uv_mode, chroma_cost) =
1679+ search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx);
1680+ cost += chroma_cost;
16821681 (
16831682 BlockCoeffs {
16841683 u,
16851684 v,
16861685 luma: luma_coeffs,
16871686 mode,
1687+ uv_mode,
16881688 ..BlockCoeffs::default()
16891689 },
16901690 cost,
16911691 )
16921692 }
16931693
1694+/// The chroma modes the search offers, and the only ones it may offer: each
1695+/// predicts from the row directly above and the column directly to the left
1696+/// and nothing further, so none of them needs the above-right/below-left
1697+/// `Reach` a chroma block is coded with `Reach::none()` for. The eight
1698+/// directional modes do read past that, and `UV_CFL_PRED` needs the luma
1699+/// reconstruction and its own alpha syntax; both are left out here.
1700+const CHROMA_MODES: [u8; 7] = [
1701+ DC_PRED,
1702+ V_PRED,
1703+ H_PRED,
1704+ SMOOTH_PRED,
1705+ SMOOTH_V_PRED,
1706+ SMOOTH_H_PRED,
1707+ PAETH_PRED,
1708+];
1709+
1710+/// The thirteen intra mode names, for the chroma fire count's print.
1711+#[cfg(test)]
1712+const UV_MODE_NAMES: [&str; 13] = [
1713+ "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V",
1714+ "SMOOTH_H", "PAETH",
1715+];
1716+
1717+/// How many blocks each chroma mode has won, indexed by the mode itself --
1718+/// the fire count that says whether the search below reaches its candidates
1719+/// at all (the `gate-blind-to-feature` class), printed once per gate run.
1720+static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 13] =
1721+ [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
1722+
1723+/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
1724+/// to its own encode.
1725+#[cfg(test)]
1726+pub(crate) fn take_uv_mode_hits() -> [usize; 13] {
1727+ std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
1728+}
1729+
1730+/// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
1731+/// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
1732+/// Returns each plane's levels, the mode, and what the pair cost (squared
1733+/// error plus lambda times bits, the same currency the luma search speaks).
1734+///
1735+/// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`],
1736+/// which is what the luma mode decision was taken against, so what a
1737+/// candidate owes here is only the *difference* from that -- plus, for `V`/`H`
1738+/// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
1739+/// writer then has to code.
1740+#[allow(clippy::too_many_arguments)]
1741+fn search_chroma(
1742+ chroma: &mut [Plane; 2],
1743+ (x, y): (usize, usize),
1744+ side: usize,
1745+ set: TxbSet,
1746+ search: &Search,
1747+ luma_mode: u8,
1748+ fctx: &crate::decode::FrameCtx,
1749+) -> ([Vec<Coeff>; 2], u8, f64) {
1750+ let at = At {
1751+ x: x / 2,
1752+ y: y / 2,
1753+ side: side / 2,
1754+ reach: Reach::none(),
1755+ set,
1756+ };
1757+ let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
1758+ let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
1759+ let mut best: Option<(f64, u8, Trial, Trial)> = None;
1760+ for mode in CHROMA_MODES {
1761+ let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
1762+ if (V_PRED..=D67_PRED).contains(&mode) {
1763+ bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
1764+ }
1765+ let tx_type = crate::decode::default_intra_tx_type(mode);
1766+ let u = chroma[0].trial_typed(at, mode, search.base_q_idx, search.deadzone, tx_type, fctx);
1767+ let v = chroma[1].trial_typed(at, mode, search.base_q_idx, search.deadzone, tx_type, fctx);
1768+ let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
1769+ if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
1770+ best = Some((cost, mode, u, v));
1771+ }
1772+ }
1773+ let (cost, mode, u, v) = best.expect("CHROMA_MODES is not empty");
1774+ UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1775+ chroma[0].commit(at.x, at.y, at.side, &u);
1776+ chroma[1].commit(at.x, at.y, at.side, &v);
1777+ (
1778+ [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
1779+ mode,
1780+ cost,
1781+ )
1782+}
1783+
16941784 /// Codes one leaf of a straddling quadrant as whichever costs least of intra
16951785 /// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at
16961786 /// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`]
@@ -1908,6 +1998,7 @@ fn code_square_inter(
19081998 u: coeffs(&u_new.levels, side / 2),
19091999 v: coeffs(&v_new.levels, side / 2),
19102000 mode: DC_PRED as u8,
2001+ uv_mode: DC_PRED,
19112002 skip: skip_new,
19122003 eight: None,
19132004 inter: Some(InterInfo {
@@ -1929,6 +2020,7 @@ fn code_square_inter(
19292020 u: coeffs(&u.levels, side / 2),
19302021 v: coeffs(&v.levels, side / 2),
19312022 mode: DC_PRED as u8,
2023+ uv_mode: DC_PRED,
19322024 skip,
19332025 eight: None,
19342026 inter: Some(InterInfo {
@@ -3160,6 +3252,7 @@ fn search_inter_block(
31603252 u: coeffs(&best.u.levels, BLOCK / 2),
31613253 v: coeffs(&best.v.levels, BLOCK / 2),
31623254 mode: best.mode,
3255+ uv_mode: DC_PRED,
31633256 skip: best.skip,
31643257 inter: best.inter,
31653258 eight: None,
@@ -4081,6 +4174,7 @@ mod tests {
40814174 u: Vec::new(),
40824175 v: Vec::new(),
40834176 mode: 0,
4177+ uv_mode: 0,
40844178 skip: false,
40854179 eight: None,
40864180 inter: Some(InterInfo {
@@ -5172,11 +5266,23 @@ mod tests {
51725266 // table for the far side would show up as a rate discontinuity here,
51735267 // even though a coarser quantizer always codes no more than a finer
51745268 // one on the same picture.
5269+ //
5270+ // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since
5271+ // chroma searches its own mode, a coarser quantizer can pick a
5272+ // *different* uv_mode on a block whose modes now cost nearly the
5273+ // same, and the search prices that symbol against the static default
5274+ // CDF while the writer codes it against an adapted one -- 311 -> 319
5275+ // bytes at q 120->121 on this picture. The table this gate is really
5276+ // watching would move the rate by far more than the mode churn does.
5277+ // Ceiling: a q-context table wrong by under 5% would pass. Upgrade
5278+ // path is pricing through the adapting CDF state (what
5279+ // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
5280+ // drift of), after which the exact bound comes back.
51755281 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
51765282 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len();
51775283 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len();
51785284 assert!(
5179- hi_bytes <= lo_bytes,
5285+ hi_bytes as f64 <= lo_bytes as f64 * 1.05,
51805286 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
51815287 );
51825288 }
@@ -6406,6 +6512,7 @@ mod tests {
64066512 let fctx = &crate::decode::FrameCtx::new();
64076513 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
64086514 let _ = take_partition_hits();
6515+ let _ = take_uv_mode_hits();
64096516 let (ours, ours_wall) = our_ladder(&source, width, height, fctx);
64106517 // How often the inter split actually fired over this clip's four
64116518 // encodes, against the whole 32x32 that was the only outcome
@@ -6419,6 +6526,24 @@ mod tests {
64196526 whole16 + split16,
64206527 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
64216528 );
6529+ // Which chroma modes the search actually wins with, against the
6530+ // unconditional DC_PRED that was the only outcome before
6531+ // (gate-blind-to-feature).
6532+ let uv = take_uv_mode_hits();
6533+ let uv_total: usize = uv.iter().sum();
6534+ eprintln!(
6535+ "{name}: uv modes {}",
6536+ uv.iter()
6537+ .enumerate()
6538+ .filter(|&(_, &n)| n > 0)
6539+ .map(|(m, &n)| format!(
6540+ "{}={n} ({:.1}%)",
6541+ UV_MODE_NAMES[m],
6542+ 100.0 * n as f64 / uv_total.max(1) as f64
6543+ ))
6544+ .collect::<Vec<_>>()
6545+ .join(" ")
6546+ );
64226547 let (aom, aom_wall) =
64236548 external_ladder(&source, width, height, "libaom-av1", &aom_points);
64246549 let (rav1e, rav1e_wall) =
crates/ec-av1/src/tile.rsmodified+30 -7
@@ -454,9 +454,14 @@ pub struct BlockCoeffs {
454454 pub v: Vec<Coeff>,
455455 /// The luma intra mode the block is predicted with, one of the thirteen
456456 /// modes a key frame codes (`DC_PRED` is zero, which is what
457- /// [`Default`] and a plain coefficient list give). Chroma stays on
458- /// `DC_PRED`.
457+ /// [`Default`] and a plain coefficient list give).
459458 pub mode: u8,
459+ /// The chroma intra mode both chroma planes are predicted with (spec
460+ /// `uv_mode`, one symbol for the pair). `DC_PRED` is zero, which is what
461+ /// [`Default`] gives; a non-`DC_PRED` mode also changes the transform
462+ /// type the decoder derives for chroma (`Intra_Mode_To_Tx_Type`, spec
463+ /// 9.3), which is never coded as a symbol.
464+ pub uv_mode: u8,
460465 /// Whether the block carries no residual at all (spec `skip`). An intra
461466 /// block may still be skipped; `false` (the [`Default`]) codes whatever
462467 /// `luma`/`u`/`v` carry.
@@ -1311,10 +1316,16 @@ fn write_intra_mode(
13111316 }
13121317 // A block small enough to be offered chroma from luma reads the wider
13131318 // table even when it does not take the mode.
1319+ let uv_mode = usize::from(block.uv_mode);
13141320 if cfl {
1315- enc.symbol(DC_PRED, &mut cdfs.uv_mode_cfl[mode]);
1321+ enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
13161322 } else {
1317- enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[mode]);
1323+ enc.symbol(uv_mode, &mut cdfs.uv_mode_no_cfl[mode]);
1324+ }
1325+ // `angle_delta_uv` (spec `read_intra_angle_info`) off the same CDF array
1326+ // the luma delta reads, indexed by the chroma mode.
1327+ if (V_PRED..=D67_PRED).contains(&uv_mode) {
1328+ enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
13181329 }
13191330 mode
13201331 }
@@ -2602,7 +2613,11 @@ pub fn sb_coeff_inter_frame_tile(
26022613 if (V_PRED..=D67_PRED).contains(&mode) {
26032614 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);
26042615 }
2605- enc.symbol(DC_PRED, &mut cdfs.uv_mode_cfl[mode]);
2616+ let uv_mode = usize::from(block.uv_mode);
2617+ enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
2618+ if (V_PRED..=D67_PRED).contains(&uv_mode) {
2619+ enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
2620+ }
26062621 mode_for_tx = mode;
26072622 // Intra: no vote, but still a coded cell -- mvstack's
26082623 // extended-scan coverage must see it (module doc).
@@ -2778,7 +2793,11 @@ fn write_inter_frame_leaf(
27782793 if (V_PRED..=D67_PRED).contains(&mode) {
27792794 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);
27802795 }
2781- enc.symbol(DC_PRED, &mut cdfs.uv_mode_cfl[mode]);
2796+ let uv_mode = usize::from(block.uv_mode);
2797+ enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
2798+ if (V_PRED..=D67_PRED).contains(&uv_mode) {
2799+ enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
2800+ }
27822801 mode_for_tx = mode;
27832802 // Intra: no vote, but still a coded cell -- mvstack's extended-scan
27842803 // coverage must see it (module doc).
@@ -2970,7 +2989,11 @@ fn write_inter_frame_leaf8(
29702989 if (V_PRED..=D67_PRED).contains(&mode) {
29712990 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);
29722991 }
2973- enc.symbol(DC_PRED, &mut cdfs.uv_mode_cfl[mode]);
2992+ let uv_mode = usize::from(block.uv_mode);
2993+ enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
2994+ if (V_PRED..=D67_PRED).contains(&uv_mode) {
2995+ enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
2996+ }
29742997 mode_for_tx = mode;
29752998 // Intra: no vote, but still a coded cell -- mvstack's extended-scan
29762999 // coverage must see it (module doc).
crates/ec-av1/src/transform.rsmodified+131 -1
@@ -1369,7 +1369,6 @@ pub fn dequant_and_inverse(levels: &[i32], side: usize, bit_depth: u8, q_idx: i3
13691369 /// undo, and nothing else: measuring the network's response to a unit
13701370 /// coefficient at every size gives the same `1 / (8 * sqrt(2))` per unit of
13711371 /// `dqDenom`, which is what [`forward_transform_2d`] divides out.
1372-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
13731372 fn build_dct_basis(n: usize) -> Vec<f64> {
13741373 let mut basis = vec![0.0f64; n * n];
13751374 let scale = (2.0 / n as f64).sqrt();
@@ -1401,6 +1400,103 @@ fn dct_basis(n: usize) -> &'static [f64] {
14011400 cache[idx].get_or_init(|| build_dct_basis(n))
14021401 }
14031402
1403+/// The orthonormal basis of one 1D axis, measured from the decoder's own
1404+/// inverse network rather than written out: a unit coefficient through
1405+/// [`inverse_1d`] IS the basis function that kernel synthesises, and
1406+/// normalising each to unit length gives the analysis basis a forward
1407+/// transform pairs with. AV1 normalises every 1D kernel to the same gain --
1408+/// that is what lets one shift chain serve mixed types -- so the
1409+/// [`INVERSE_GAIN_RECIPROCAL`] correction a DCT axis takes is the one an ADST
1410+/// axis takes too.
1411+fn build_axis_basis(n: usize, kind: TxType1d) -> Vec<f64> {
1412+ if kind == TxType1d::Dct {
1413+ return build_dct_basis(n);
1414+ }
1415+ let log2 = n.trailing_zeros();
1416+ let mut basis = vec![0.0f64; n * n];
1417+ for u in 0..n {
1418+ let mut t = [0i32; 64];
1419+ // Large enough that the network's own rounding is negligible, small
1420+ // enough that nothing clamps at the 24-bit range passed below.
1421+ t[u] = 1 << 12;
1422+ inverse_1d(&mut t, log2, 24, kind);
1423+ let norm = (0..n).map(|i| f64::from(t[i]) * f64::from(t[i])).sum::<f64>().sqrt();
1424+ for i in 0..n {
1425+ basis[u * n + i] = f64::from(t[i]) / norm;
1426+ }
1427+ }
1428+ basis
1429+}
1430+
1431+/// [`build_axis_basis`], computed once per (size, kind).
1432+fn axis_basis(n: usize, kind: TxType1d) -> &'static [f64] {
1433+ use std::sync::OnceLock;
1434+ static CACHE: OnceLock<[[OnceLock<Vec<f64>>; 5]; 3]> = OnceLock::new();
1435+ let cache = CACHE.get_or_init(|| std::array::from_fn(|_| std::array::from_fn(|_| OnceLock::new())));
1436+ let k = match kind {
1437+ TxType1d::Dct => 0,
1438+ TxType1d::Adst => 1,
1439+ TxType1d::Identity => 2,
1440+ };
1441+ let idx = (n.trailing_zeros() as usize).saturating_sub(2);
1442+ cache[k][idx].get_or_init(|| build_axis_basis(n, kind))
1443+}
1444+
1445+/// [`forward_transform_2d`] for a block whose transform type is not
1446+/// `DCT_DCT` -- what an intra chroma block coded in a non-`DC_PRED` mode
1447+/// gets, since chroma never codes a `tx_type` symbol and the decoder derives
1448+/// it from the mode (`Intra_Mode_To_Tx_Type`, spec 9.3).
1449+///
1450+/// The forward transform is the encoder's own business: only the levels and
1451+/// the type reach the decoder, so an approximate analysis basis costs rate,
1452+/// never correctness -- the reconstruction the search scores comes back
1453+/// through the decoder's exact inverse either way.
1454+pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType) -> Vec<f64> {
1455+ if tx_type == TxType::DctDct {
1456+ return forward_transform_2d(residual, side);
1457+ }
1458+ debug_assert_eq!(
1459+ tx_type.flip(),
1460+ (false, false),
1461+ "a flipped ADST needs its residual mirrored before this basis applies"
1462+ );
1463+ let (row_kind, col_kind) = tx_type.axes();
1464+ let (hb, vb) = (axis_basis(side, row_kind), axis_basis(side, col_kind));
1465+ let mut rows = vec![0.0f64; side * side];
1466+ for i in 0..side {
1467+ let source = &residual[i * side..][..side];
1468+ for v in 0..side {
1469+ rows[i * side + v] = source
1470+ .iter()
1471+ .zip(&hb[v * side..][..side])
1472+ .map(|(&r, &b)| f64::from(r) * b)
1473+ .sum();
1474+ }
1475+ }
1476+ let mut out = vec![0.0f64; side * side];
1477+ for u in 0..side {
1478+ let column = &vb[u * side..][..side];
1479+ for v in 0..side {
1480+ let sum: f64 = (0..side).map(|i| rows[i * side + v] * column[i]).sum();
1481+ out[u * side + v] = INVERSE_GAIN_RECIPROCAL * sum;
1482+ }
1483+ }
1484+ out
1485+}
1486+
1487+/// [`forward_and_quantize`] at a named transform type.
1488+pub fn forward_and_quantize_typed(
1489+ residual: &[i32],
1490+ side: usize,
1491+ bit_depth: u8,
1492+ q_idx: i32,
1493+ deadzone: f64,
1494+ tx_type: TxType,
1495+) -> Vec<i32> {
1496+ let coeffs = forward_transform_2d_typed(residual, side, tx_type);
1497+ quantize(&coeffs, side, bit_depth, q_idx, deadzone)
1498+}
1499+
14041500 /// How much the decoder's inverse transform shrinks an orthonormal DCT.
14051501 ///
14061502 /// Measured, not asserted: feeding a single dequantized coefficient through
@@ -1696,6 +1792,40 @@ mod tests {
16961792 }
16971793 }
16981794
1795+ /// The typed forward transform is the decoder's exact inverse undone:
1796+ /// quantized and taken back, an ADST-typed residual returns with the same
1797+ /// error a `DCT_DCT` one does. This is what pins the *gain* of the ADST
1798+ /// basis measured off the inverse network -- an approximate shape only
1799+ /// costs rate, but a wrong gain would put every level in the wrong decade
1800+ /// and the mode search would read as a loss.
1801+ #[test]
1802+ fn a_typed_forward_round_trips_like_the_dct_one() {
1803+ for side in [4usize, 8, 16] {
1804+ let residual: Vec<i32> = noise(side * side, 7 + side as u64)
1805+ .iter()
1806+ .map(|&v| v / 4)
1807+ .collect();
1808+ let rmse = |tx: TxType| {
1809+ let levels = forward_and_quantize_typed(&residual, side, 8, 60, 0.5, tx);
1810+ let back = dequant_and_inverse_typed(&levels, side, 8, 60, 0, 0, tx);
1811+ let sum: f64 = residual
1812+ .iter()
1813+ .zip(&back)
1814+ .map(|(&a, &b)| f64::from(a - b) * f64::from(a - b))
1815+ .sum();
1816+ (sum / (side * side) as f64).sqrt()
1817+ };
1818+ let dct = rmse(TxType::DctDct);
1819+ for tx in [TxType::AdstDct, TxType::DctAdst, TxType::AdstAdst] {
1820+ let e = rmse(tx);
1821+ assert!(
1822+ e < 2.0 * dct,
1823+ "{side}x{side} {tx:?} round trip rmse {e:.2} against DCT_DCT's {dct:.2}"
1824+ );
1825+ }
1826+ }
1827+ }
1828+
16991829 /// The orthonormal DCT-II basis the forward transform is written against,
17001830 /// computed independently of `dct_basis` so a test is not checking a
17011831 /// function against itself.