forge
Explore
Log in

Don't you dare go Hollow

Search an intra luma transform unit's own tx_type

Browse files at this commit

2fd2ac4f3565bc832ab1230e8c904cb24eafaa41Ahmet Kaan GümüşParent: ad81365
  • feat
    • search an intra luma transform unit's own tx_type
Show full message
feat(av1): search an intra luma transform unit's own tx_type

The writer coded DCT_DCT for every luma transform unit ever written --
the symbol was a constant -- while the five-type reduced-set alphabet
(TX_SET_INTRA_2: IDTX, DCT_DCT, ADST_ADST, ADST_DCT, DCT_ADST) was
already the CDF it wrote into. The search now offers that set per intra
luma unit, priced through the same RDOQ'd trial path (the tx_type symbol
included, coeff_bits_typed), and the writer names the chosen type through
the decoder's own symbol map (decode::tx_type_symbol, keyed by the CDF's
alphabet width, so the two cannot drift).

The forward transform gains the FLIPADST family as well: a flipped axis
is the plain ADST basis over the mirrored residual, which is what the
decoder's ud_flip/lr_flip undoes. All sixteen types now round trip.
crates/ec-av1/src/decode.rsmodified+8 -0
@@ -5988,6 +5988,14 @@ pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
5988 }5988 }
5989 }5989 }
5990 5990
5991+/// [`tx_type_from_symbol`] inverted: which symbol of a `cdf_len`-wide
5992+/// `tx_type` CDF names `tx_type`, or `None` when that set does not hold it
5993+/// (class `table-and-reader-move-together` -- the writer picks its symbol
5994+/// through the reader's own map, so the two cannot drift).
5995+pub(crate) fn tx_type_symbol(cdf_len: usize, tx_type: TxType) -> Option<usize> {
5996+ (0..cdf_len.saturating_sub(1)).find(|&t| tx_type_from_symbol(cdf_len, t) == Some(tx_type))
5997+}
5998+
5991 /// The remainder of a level the base and base-range syntax could not reach5999 /// The remainder of a level the base and base-range syntax could not reach
5992 /// (spec 5.11.40): its bit length in unary, then that many of its own bits,6000 /// (spec 5.11.40): its bit length in unary, then that many of its own bits,
5993 /// most significant first — the exact inverse of [`crate::tile::write_golomb`].6001 /// most significant first — the exact inverse of [`crate::tile::write_golomb`].
crates/ec-av1/src/encode.rsmodified+118 -9
@@ -252,6 +252,40 @@ fn tx_select_inter() -> bool {
252 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_INTER))252 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_INTER))
253 }253 }
254 254
255+/// The transform types an intra luma transform unit of `set` may be coded
256+/// with -- exactly the alphabet the writer's `tx_type` symbol names for that
257+/// set, so a searched type is always one the tile can express (lane-txset).
258+/// `DCT_DCT` first: it is the incumbent every other candidate has to beat.
259+///
260+/// Under this encoder's `reduced_tx_set` header bit every intra set at 16x16
261+/// and below is `TX_SET_INTRA_2` (spec `get_tx_set`), the five types
262+/// [`TxType::from_symbol`] names; 32x32 and 64x64 luma code no symbol at all,
263+/// and inter luma reads the two-type `TX_SET_INTER_3`, left at `DCT_DCT`
264+/// here.
265+pub(crate) fn tx_type_candidates(set: TxbSet) -> &'static [TxType] {
266+ const DCT: [TxType; 1] = [TxType::DctDct];
267+ const INTRA2: [TxType; 5] = [
268+ TxType::DctDct,
269+ TxType::AdstAdst,
270+ TxType::AdstDct,
271+ TxType::DctAdst,
272+ TxType::Idtx,
273+ ];
274+ match set {
275+ TxbSet::Luma16 | TxbSet::Luma8 | TxbSet::Luma4 if tx_type_search() => &INTRA2,
276+ _ => &DCT,
277+ }
278+}
279+
280+fn tx_type_search() -> bool {
281+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
282+ crate::envflags::var("EC_AV1_TXSET")
283+ .ok()
284+ .map(|v| !matches!(v.as_str(), "0" | "off"))
285+ });
286+ ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_TYPE_SEARCH))
287+}
288+
255 fn tx_select() -> bool {289 fn tx_select() -> bool {
256 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {290 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
257 crate::envflags::var("EC_AV1_TX_SELECT")291 crate::envflags::var("EC_AV1_TX_SELECT")
@@ -2128,6 +2162,7 @@ impl Plane<'_> {
2128 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);2162 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2129 let bits = crate::tile::rdoq(2163 let bits = crate::tile::rdoq(
2130 &mut levels, &scaled, side, base_q_idx, at.set, skip_ctx, sign_ctx, rdoq_lambda(),2164 &mut levels, &scaled, side, base_q_idx, at.set, skip_ctx, sign_ctx, rdoq_lambda(),
2165+ tx_type,
2131 );2166 );
2132 (levels, Some(bits))2167 (levels, Some(bits))
2133 } else {2168 } else {
@@ -2182,12 +2217,13 @@ impl Plane<'_> {
2182 } else {2217 } else {
2183 {2218 {
2184 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);2219 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2185- crate::tile::coeff_bits(2220+ crate::tile::coeff_bits_typed(
2186 &levels,2221 &levels,
2187 at.set,2222 at.set,
2188 crate::decode::q_ctx_of(base_q_idx),2223 crate::decode::q_ctx_of(base_q_idx),
2189 skip_ctx,2224 skip_ctx,
2190 sign_ctx,2225 sign_ctx,
2226+ tx_type,
2191 )2227 )
2192 }2228 }
2193 };2229 };
@@ -2258,6 +2294,7 @@ impl Plane<'_> {
2258 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);2294 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
2259 let bits = crate::tile::rdoq(2295 let bits = crate::tile::rdoq(
2260 &mut levels, &scaled, side, base_q_idx, set, skip_ctx, sign_ctx, rdoq_lambda(),2296 &mut levels, &scaled, side, base_q_idx, set, skip_ctx, sign_ctx, rdoq_lambda(),
2297+ TxType::DctDct,
2261 );2298 );
2262 (levels, Some(bits))2299 (levels, Some(bits))
2263 } else {2300 } else {
@@ -2353,7 +2390,7 @@ impl Plane<'_> {
2353 // `filter_intra`), not once over the whole block.2390 // `filter_intra`), not once over the whole block.
2354 filter_intra: Option<u8>,2391 filter_intra: Option<u8>,
2355 search: &Search, fctx: &crate::decode::FrameCtx,2392 search: &Search, fctx: &crate::decode::FrameCtx,
2356- ) -> (Vec<i32>, f64, f64) {2393+ ) -> (Vec<i32>, f64, f64, Vec<TxType>) {
2357 let At { x, y, side, reach, .. } = at;2394 let At { x, y, side, reach, .. } = at;
2358 let tx = side >> depth;2395 let tx = side >> depth;
2359 let n = 1usize << depth;2396 let n = 1usize << depth;
@@ -2369,6 +2406,11 @@ impl Plane<'_> {
2369 // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]).2406 // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]).
2370 self.ctx.tu_split = n > 1;2407 self.ctx.tu_split = n > 1;
2371 let (mut sse, mut bits) = (0.0, 0.0);2408 let (mut sse, mut bits) = (0.0, 0.0);
2409+ // One entry per unit at its own `tu_row * n + tu_col`, which is how
2410+ // the writer indexes them (tile.rs `write_luma_tus`) -- a unit the
2411+ // frame edge cuts away is never coded there, so a compacted list
2412+ // would slide every later unit's type onto the wrong transform.
2413+ let mut tx_types = vec![TxType::DctDct; n * n];
2372 for tu_row in 0..n {2414 for tu_row in 0..n {
2373 for tu_col in 0..n {2415 for tu_col in 0..n {
2374 let (col_off, row_off) = (tu_col * tx, tu_row * tx);2416 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
@@ -2406,7 +2448,27 @@ impl Plane<'_> {
2406 )2448 )
2407 }2449 }
2408 None => {2450 None => {
2409- self.trial(tu, mode, angle_delta, search.base_q_idx, search.deadzone, fctx)2451+ // lane-txset: the unit picks its own transform type
2452+ // out of the set the writer can name it in, priced
2453+ // through the same RDOQ'd trial path (its `bits`
2454+ // already carry the `tx_type` symbol itself).
2455+ let mut best: Option<(f64, TxType, Trial)> = None;
2456+ for &tx_type in tx_type_candidates(set) {
2457+ let candidate = self.trial_typed(
2458+ tu, mode, angle_delta, search.base_q_idx, search.deadzone,
2459+ tx_type, fctx,
2460+ );
2461+ let cost = candidate.sse + search.lambda * candidate.bits;
2462+ if best.as_ref().is_none_or(|(best, _, _)| cost < *best) {
2463+ best = Some((cost, tx_type, candidate));
2464+ }
2465+ }
2466+ let (_, tx_type, trial) =
2467+ best.expect("the candidate list is never empty");
2468+ tx_types[tu_row * n + tu_col] = tx_type;
2469+ TX_TYPE_HITS[tx_type as usize]
2470+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2471+ trial
2410 }2472 }
2411 };2473 };
2412 sse += trial.sse;2474 sse += trial.sse;
@@ -2419,7 +2481,7 @@ impl Plane<'_> {
2419 }2481 }
2420 }2482 }
2421 self.ctx.tu_split = false;2483 self.ctx.tu_split = false;
2422- (levels, sse, bits)2484+ (levels, sse, bits, tx_types)
2423 }2485 }
2424 2486
2425 /// Writes a trial's reconstruction back into the plane, and the2487 /// Writes a trial's reconstruction back into the plane, and the
@@ -2637,7 +2699,7 @@ impl Plane<'_> {
2637 at: At,2699 at: At,
2638 search: &Search,2700 search: &Search,
2639 mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,2701 mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
2640- ) -> (Vec<Coeff>, u8, i32, f64) {2702+ ) -> (Vec<Coeff>, u8, i32, f64, TxType) {
2641 let At {2703 let At {
2642 x, y, side, reach, ..2704 x, y, side, reach, ..
2643 } = at;2705 } = at;
@@ -2777,6 +2839,23 @@ impl Plane<'_> {
2777 ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize]2839 ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize]
2778 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);2840 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2779 }2841 }
2842+ // lane-txset: the block's own transform type, searched on the mode
2843+ // and angle the trials above settled -- the same ordering the angle
2844+ // refinement uses, and the same RD terms.
2845+ let mut tx_type = TxType::DctDct;
2846+ for &candidate_type in tx_type_candidates(at.set).iter().skip(1) {
2847+ let candidate = self.trial_typed(
2848+ at, mode, angle_delta, search.base_q_idx, search.deadzone, candidate_type, fctx,
2849+ );
2850+ let cost_t =
2851+ candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]);
2852+ if cost_t < cost {
2853+ cost = cost_t;
2854+ tx_type = candidate_type;
2855+ trial = candidate;
2856+ }
2857+ }
2858+ TX_TYPE_HITS[tx_type as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2780 if census_on() {2859 if census_on() {
2781 LUMA_RANK[sad_rank(&ranking, mode).min(12)]2860 LUMA_RANK[sad_rank(&ranking, mode).min(12)]
2782 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);2861 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
@@ -2784,7 +2863,7 @@ impl Plane<'_> {
2784 self.commit(x, y, side, &trial);2863 self.commit(x, y, side, &trial);
2785 // A 64-point transform codes only its top-left 32x32 corner, which is2864 // A 64-point transform codes only its top-left 32x32 corner, which is
2786 // the grid `code_from_prediction` hands back (lane-i64).2865 // the grid `code_from_prediction` hands back (lane-i64).
2787- (coeffs(&trial.levels, side.min(BLOCK)), mode, angle_delta, cost)2866+ (coeffs(&trial.levels, side.min(BLOCK)), mode, angle_delta, cost, tx_type)
2788 }2867 }
2789 }2868 }
2790 2869
@@ -3586,6 +3665,18 @@ fn tx_depth_bits(side: usize, depth: usize) -> f64 {
3586 }3665 }
3587 }3666 }
3588 3667
3668+/// How many luma transform units resolved to each [`TxType`], indexed by the
3669+/// enum's own discriminant (lane-txset): the fire count a witness asserts on,
3670+/// and the instrument that says which types the search actually reaches.
3671+pub(crate) static TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
3672+ [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
3673+
3674+/// Reads [`TX_TYPE_HITS`] and zeroes it, so a gate or a test attributes the
3675+/// counts to its own encode.
3676+pub(crate) fn take_tx_type_hits() -> [usize; 16] {
3677+ std::array::from_fn(|t| TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
3678+}
3679+
3589 /// How many blocks resolved to each `tx_depth`, the fire count that says3680 /// How many blocks resolved to each `tx_depth`, the fire count that says
3590 /// whether the depth search below reaches its candidates at all.3681 /// whether the depth search below reaches its candidates at all.
3591 static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =3682 static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =
@@ -4377,8 +4468,9 @@ fn code_square(
4377 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),4468 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
4378 set: luma_set,4469 set: luma_set,
4379 };4470 };
4380- let (mut luma_coeffs, mode, angle_delta, mut cost) =4471+ let (mut luma_coeffs, mode, angle_delta, mut cost, tx_type) =
4381 luma.search_block(at, search, mode_bits, fctx);4472 luma.search_block(at, search, mode_bits, fctx);
4473+ let mut luma_tx_types = vec![tx_type];
4382 // The depth search runs on the mode the whole-block transform picked --4474 // The depth search runs on the mode the whole-block transform picked --
4383 // libaom's own ordering, and the reason it costs one extra pass per depth4475 // libaom's own ordering, and the reason it costs one extra pass per depth
4384 // rather than one per (mode, depth) pair.4476 // rather than one per (mode, depth) pair.
@@ -4398,15 +4490,19 @@ fn code_square(
4398 luma.snapshot(x, y, side),4490 luma.snapshot(x, y, side),
4399 luma_coeffs,4491 luma_coeffs,
4400 );4492 );
4493+ let mut best_types = std::mem::take(&mut luma_tx_types);
4401 for depth in 1..=max_tx_depth(side) {4494 for depth in 1..=max_tx_depth(side) {
4402- let (levels, sse, bits) = luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx);4495+ let (levels, sse, bits, types) =
4496+ luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx);
4403 let cost_d = sse4497 let cost_d = sse
4404 + search.lambda4498 + search.lambda
4405 * (bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth));4499 * (bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth));
4406 if cost_d < best.0 {4500 if cost_d < best.0 {
4407 best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side));4501 best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side));
4502+ best_types = types;
4408 }4503 }
4409 }4504 }
4505+ luma_tx_types = best_types;
4410 luma.restore(x, y, side, &best.2);4506 luma.restore(x, y, side, &best.2);
4411 cost = best.0;4507 cost = best.0;
4412 tx_depth = best.1 as u8;4508 tx_depth = best.1 as u8;
@@ -4503,7 +4599,10 @@ fn code_square(
4503 let mut best: Option<(f64, u8, usize, (Vec<u8>, Vec<CoefCtx>), Vec<Coeff>)> = None;4599 let mut best: Option<(f64, u8, usize, (Vec<u8>, Vec<CoefCtx>), Vec<Coeff>)> = None;
4504 for fi in 0..5u8 {4600 for fi in 0..5u8 {
4505 for depth in 0..=max_depth {4601 for depth in 0..=max_depth {
4506- let (levels, sse, bits) =4602+ // A filter-intra block's units are coded through
4603+ // `code_from_prediction`, which is `DCT_DCT` throughout, so
4604+ // this arm keeps the empty (all-`DCT_DCT`) type list.
4605+ let (levels, sse, bits, _) =
4507 luma.code_tx_depth(at, DC_PRED, 0, depth, Some(fi), search, fctx);4606 luma.code_tx_depth(at, DC_PRED, 0, depth, Some(fi), search, fctx);
4508 let cost_f = sse4607 let cost_f = sse
4509 + search.lambda4608 + search.lambda
@@ -4564,6 +4663,12 @@ fn code_square(
4564 }4663 }
4565 }4664 }
4566 }4665 }
4666+ // A palette or filter-intra block's luma was recoded through `DCT_DCT`
4667+ // (its levels came from `code_from_prediction`), so the searched types
4668+ // belong to a block this one no longer is.
4669+ if palette.is_some() || filter_intra.is_some() {
4670+ luma_tx_types = Vec::new();
4671+ }
4567 (4672 (
4568 BlockCoeffs {4673 BlockCoeffs {
4569 u,4674 u,
@@ -4577,6 +4682,7 @@ fn code_square(
4577 filter_intra,4682 filter_intra,
4578 cfl_alphas,4683 cfl_alphas,
4579 angle_delta_y: angle_delta as i8,4684 angle_delta_y: angle_delta as i8,
4685+ luma_tx_types,
4580 ..BlockCoeffs::default()4686 ..BlockCoeffs::default()
4581 },4687 },
4582 cost,4688 cost,
@@ -5846,6 +5952,7 @@ fn code_square_inter(
5846 palette: None,5952 palette: None,
5847 palette_uv: None,5953 palette_uv: None,
5848 tx_depth,5954 tx_depth,
5955+ luma_tx_types: Vec::new(),
5849 inter: Some(info),5956 inter: Some(info),
5850 motion_mode: motion_won,5957 motion_mode: motion_won,
5851 },5958 },
@@ -5868,6 +5975,7 @@ fn code_square_inter(
5868 chroma[0].commit(x / 2, y / 2, side / 2, &u);5975 chroma[0].commit(x / 2, y / 2, side / 2, &u);
5869 chroma[1].commit(x / 2, y / 2, side / 2, &v);5976 chroma[1].commit(x / 2, y / 2, side / 2, &v);
5870 (BlockCoeffs {5977 (BlockCoeffs {
5978+ luma_tx_types: Vec::new(),
5871 angle_delta_y: 0,5979 angle_delta_y: 0,
5872 cfl_alphas: None,5980 cfl_alphas: None,
5873 filter_intra: None,5981 filter_intra: None,
@@ -9116,6 +9224,7 @@ fn search_inter_block(
9116 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);9224 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
9117 (9225 (
9118 BlockCoeffs {9226 BlockCoeffs {
9227+ luma_tx_types: Vec::new(),
9119 angle_delta_y: 0,9228 angle_delta_y: 0,
9120 cfl_alphas: None,9229 cfl_alphas: None,
9121 filter_intra: None,9230 filter_intra: None,
crates/ec-av1/src/speed.rsmodified+8 -0
@@ -437,6 +437,14 @@ pub(crate) const RESTORATION: [bool; 11] = [
437 /// `encode::TPL_DEPTH`: lookahead pictures the lambda map reads (1 = off).437 /// `encode::TPL_DEPTH`: lookahead pictures the lambda map reads (1 = off).
438 pub(crate) const TPL_DEPTH: [usize; 11] = [crate::encode::TPL_DEPTH, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];438 pub(crate) const TPL_DEPTH: [usize; 11] = [crate::encode::TPL_DEPTH, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
439 439
440+/// `encode::tx_type_search`: whether an intra luma transform unit searches
441+/// its own `tx_type` instead of coding `DCT_DCT` (lane-txset). The five-type
442+/// reduced-set alphabet the writer already codes is what it picks from, so a
443+/// preset that turns it off is byte-identical to the encoder before the lane.
444+pub(crate) const TX_TYPE_SEARCH: [bool; 11] = [
445+ true, true, true, true, true, true, true, false, false, false, false,
446+];
447+
440 /// `filter_search`: whether the deblock ladder's +-1/+-2 refinement stage runs.448 /// `filter_search`: whether the deblock ladder's +-1/+-2 refinement stage runs.
441 pub(crate) const DEBLOCK_REFINE: [bool; 11] = [449 pub(crate) const DEBLOCK_REFINE: [bool; 11] = [
442 true, true, true, true, true, true, true, false, false, false, false,450 true, true, true, true, true, true, true, false, false, false, false,
crates/ec-av1/src/tile.rsmodified+74 -8
@@ -21,6 +21,7 @@ use crate::cdf;
21 use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};21 use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
22 use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect};22 use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect};
23 use crate::msac::SymbolEncoder;23 use crate::msac::SymbolEncoder;
24+use crate::transform::TxType;
24 use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16};25 use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16};
25 26
26 // ---------------------------------------------------------------------------27 // ---------------------------------------------------------------------------
@@ -1674,6 +1675,10 @@ pub struct Coeff {
1674 pub struct BlockCoeffs {1675 pub struct BlockCoeffs {
1675 /// The luma transform's coefficients.1676 /// The luma transform's coefficients.
1676 pub luma: Vec<Coeff>,1677 pub luma: Vec<Coeff>,
1678+ /// One transform type per luma transform unit, raster order (lane-txset).
1679+ /// Empty is `DCT_DCT` throughout -- what every block coded before the
1680+ /// search offered a type, and what an inter block still carries.
1681+ pub luma_tx_types: Vec<TxType>,
1677 /// The U plane's.1682 /// The U plane's.
1678 pub u: Vec<Coeff>,1683 pub u: Vec<Coeff>,
1679 /// The V plane's.1684 /// The V plane's.
@@ -3994,6 +3999,7 @@ fn write_block(
3994 &grids[0],3999 &grids[0],
3995 tx_mode,4000 tx_mode,
3996 all_scans,4001 all_scans,
4002+ &block.luma_tx_types,
3997 )?;4003 )?;
3998 tx < side4004 tx < side
3999 } else {4005 } else {
@@ -4008,6 +4014,7 @@ fn write_block(
4008 &neighbours.around(at, side),4014 &neighbours.around(at, side),
4009 tx_mode,4015 tx_mode,
4010 tx_select,4016 tx_select,
4017+ block_tx_type(block),
4011 );4018 );
4012 neighbours.record_planes(at, side, mode, grids, !split);4019 neighbours.record_planes(at, side, mode, grids, !split);
4013 clear_skip_band(neighbours, at_mi, side);4020 clear_skip_band(neighbours, at_mi, side);
@@ -4092,6 +4099,7 @@ fn write_leaf8(
4092 &grids[0],4099 &grids[0],
4093 tx_mode,4100 tx_mode,
4094 all_scans,4101 all_scans,
4102+ &block.luma_tx_types,
4095 )?;4103 )?;
4096 tx < 84104 tx < 8
4097 } else {4105 } else {
@@ -4106,6 +4114,7 @@ fn write_leaf8(
4106 &neighbours.around_mi(leaf_mi, 8),4114 &neighbours.around_mi(leaf_mi, 8),
4107 tx_mode,4115 tx_mode,
4108 tx_select,4116 tx_select,
4117+ block_tx_type(block),
4109 );4118 );
4110 neighbours.record_mi_planes(leaf_mi, 8, grids, !split);4119 neighbours.record_mi_planes(leaf_mi, 8, grids, !split);
4111 clear_skip_band(neighbours, leaf_mi, 8);4120 clear_skip_band(neighbours, leaf_mi, 8);
@@ -4127,6 +4136,9 @@ fn write_block_planes(
4127 // A block whose luma was already written as several transform units4136 // A block whose luma was already written as several transform units
4128 // ([`write_luma_select`]) has only its chroma planes left here.4137 // ([`write_luma_select`]) has only its chroma planes left here.
4129 skip_luma: bool,4138 skip_luma: bool,
4139+ // This block's single luma transform type (lane-txset); chroma's is
4140+ // derived from its mode by the decoder and codes no symbol.
4141+ luma_tx_type: TxType,
4130 ) {4142 ) {
4131 for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() {4143 for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() {
4132 if plane == 0 && skip_luma {4144 if plane == 0 && skip_luma {
@@ -4153,6 +4165,7 @@ fn write_block_planes(
4153 skip_ctx,4165 skip_ctx,
4154 dc_sign_ctx(around[plane].dc_vote),4166 dc_sign_ctx(around[plane].dc_vote),
4155 Some(plane),4167 Some(plane),
4168+ if plane == 0 { luma_tx_type } else { TxType::DctDct },
4156 );4169 );
4157 #[cfg(test)]4170 #[cfg(test)]
4158 census_record(4171 census_record(
@@ -4173,6 +4186,12 @@ fn write_block_planes(
4173 }4186 }
4174 }4187 }
4175 4188
4189+/// The single luma transform type a block carries, `DCT_DCT` for one that
4190+/// never searched one (lane-txset).
4191+fn block_tx_type(block: &BlockCoeffs) -> TxType {
4192+ block.luma_tx_types.first().copied().unwrap_or(TxType::DctDct)
4193+}
4194+
4176 /// The `(side / tx)^2` transform units of one block's luma residual, raster4195 /// The `(side / tx)^2` transform units of one block's luma residual, raster
4177 /// order, each with its own coefficient context and each published before the4196 /// order, each with its own coefficient context and each published before the
4178 /// next one reads it (decode.rs `decode_block`'s multi-transform-unit branch).4197 /// next one reads it (decode.rs `decode_block`'s multi-transform-unit branch).
@@ -4192,6 +4211,10 @@ fn write_luma_tus(
4192 // lane-av1tx2 r2: an INTER block's split units read the inter coefficient4211 // lane-av1tx2 r2: an INTER block's split units read the inter coefficient
4193 // tables, not the intra ones (`TxbSet::Luma*Inter`).4212 // tables, not the intra ones (`TxbSet::Luma*Inter`).
4194 inter: bool,4213 inter: bool,
4214+ // One transform type per unit in this same raster order (lane-txset).
4215+ // Empty -- what every caller that never searched a type passes -- is
4216+ // `DCT_DCT` throughout, the one type this writer used to code.
4217+ tx_types: &[TxType],
4195 ) -> Result<()> {4218 ) -> Result<()> {
4196 if tx < side && side > 32 && tx < 32 {4219 if tx < side && side > 32 && tx < 32 {
4197 // A 64x64 block's own levels reach the writer as the 32x32 corner a4220 // A 64x64 block's own levels reach the writer as the 32x32 corner a
@@ -4268,6 +4291,10 @@ fn write_luma_tus(
4268 skip_ctx,4291 skip_ctx,
4269 dc_sign_ctx(around.dc_vote),4292 dc_sign_ctx(around.dc_vote),
4270 Some(0),4293 Some(0),
4294+ tx_types
4295+ .get(tu_row * n + tu_col)
4296+ .copied()
4297+ .unwrap_or(TxType::DctDct),
4271 );4298 );
4272 #[cfg(test)]4299 #[cfg(test)]
4273 census_record(4300 census_record(
@@ -4308,6 +4335,7 @@ fn write_luma_select(
4308 grid: &[i32],4335 grid: &[i32],
4309 mode: usize,4336 mode: usize,
4310 scans: &[Vec<u16>; 4],4337 scans: &[Vec<u16>; 4],
4338+ tx_types: &[TxType],
4311 ) -> Result<usize> {4339 ) -> Result<usize> {
4312 let max_tx = side.min(64);4340 let max_tx = side.min(64);
4313 let ctx = neighbours.tx_size_ctx(at_mi, max_tx);4341 let ctx = neighbours.tx_size_ctx(at_mi, max_tx);
@@ -4324,7 +4352,7 @@ fn write_luma_select(
4324 }4352 }
4325 }4353 }
4326 let tx = max_tx >> depth;4354 let tx = max_tx >> depth;
4327- write_luma_tus(enc, cdfs, neighbours, at_mi, side, tx, grid, mode, scans, false)?;4355+ write_luma_tus(enc, cdfs, neighbours, at_mi, side, tx, grid, mode, scans, false, tx_types)?;
4328 neighbours.record_tx(at_mi, side, tx);4356 neighbours.record_tx(at_mi, side, tx);
4329 Ok(tx)4357 Ok(tx)
4330 }4358 }
@@ -4697,6 +4725,19 @@ fn scan_of(side: usize) -> &'static Vec<u16> {
4697 }4725 }
4698 4726
4699 pub(crate) fn coeff_bits(4727 pub(crate) fn coeff_bits(
4728+ grid: &[i32],
4729+ set: TxbSet,
4730+ q_ctx: usize,
4731+ skip_ctx: usize,
4732+ sign_ctx: usize,
4733+) -> f64 {
4734+ coeff_bits_typed(grid, set, q_ctx, skip_ctx, sign_ctx, TxType::DctDct)
4735+}
4736+
4737+/// [`coeff_bits`] for levels a named transform type produced: the `tx_type`
4738+/// symbol is part of what the block spends, so a search comparing types has
4739+/// to see each one's own symbol priced (lane-txset).
4740+pub(crate) fn coeff_bits_typed(
4700 grid: &[i32],4741 grid: &[i32],
4701 set: TxbSet,4742 set: TxbSet,
4702 q_ctx: usize,4743 q_ctx: usize,
@@ -4708,6 +4749,7 @@ pub(crate) fn coeff_bits(
4708 // largest remaining pricer error for every other block.4749 // largest remaining pricer error for every other block.
4709 skip_ctx: usize,4750 skip_ctx: usize,
4710 sign_ctx: usize,4751 sign_ctx: usize,
4752+ tx_type: TxType,
4711 ) -> f64 {4753 ) -> f64 {
4712 // `Cdfs::new` builds every table a tile writer adapts -- tens of4754 // `Cdfs::new` builds every table a tile writer adapts -- tens of
4713 // kilobytes -- and this function is called once per priced candidate:4755 // kilobytes -- and this function is called once per priced candidate:
@@ -4743,7 +4785,7 @@ pub(crate) fn coeff_bits(
4743 }4785 }
4744 let scan = scan_of(coding.side);4786 let scan = scan_of(coding.side);
4745 let mut enc = SymbolEncoder::pricer();4787 let mut enc = SymbolEncoder::pricer();
4746- write_coeffs(&mut enc, &mut coding, grid, scan, skip_ctx, sign_ctx, None);4788+ write_coeffs(&mut enc, &mut coding, grid, scan, skip_ctx, sign_ctx, None, tx_type);
4747 enc.bits()4789 enc.bits()
4748 };4790 };
4749 // lane-av1speed2: 60% of the transform units of an inter stream hold no4791 // lane-av1speed2: 60% of the transform units of an inter stream hold no
@@ -4842,6 +4884,7 @@ pub(crate) fn rdoq(
4842 skip_ctx: usize,4884 skip_ctx: usize,
4843 sign_ctx: usize,4885 sign_ctx: usize,
4844 lambda: f64,4886 lambda: f64,
4887+ tx_type: TxType,
4845 ) -> f64 {4888 ) -> f64 {
4846 // A 64-point transform carries its top-left 32x32 alone, and that corner4889 // A 64-point transform carries its top-left 32x32 alone, and that corner
4847 // is what the writer and the pricer take (`coded_corner`).4890 // is what the writer and the pricer take (`coded_corner`).
@@ -4857,16 +4900,17 @@ pub(crate) fn rdoq(
4857 q_ctx: usize,4900 q_ctx: usize,
4858 skip_ctx: usize,4901 skip_ctx: usize,
4859 sign_ctx: usize,4902 sign_ctx: usize,
4903+ tx_type: TxType,
4860 ) -> f64 {4904 ) -> f64 {
4861 if dense.is_empty() {4905 if dense.is_empty() {
4862- return coeff_bits(levels, set, q_ctx, skip_ctx, sign_ctx);4906+ return coeff_bits_typed(levels, set, q_ctx, skip_ctx, sign_ctx, tx_type);
4863 }4907 }
4864 for row in 0..coded {4908 for row in 0..coded {
4865 dense[row * coded..][..coded].copy_from_slice(&levels[row * side..][..coded]);4909 dense[row * coded..][..coded].copy_from_slice(&levels[row * side..][..coded]);
4866 }4910 }
4867- coeff_bits(dense, set, q_ctx, skip_ctx, sign_ctx)4911+ coeff_bits_typed(dense, set, q_ctx, skip_ctx, sign_ctx, tx_type)
4868 }4912 }
4869- let mut bits = price(levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx);4913+ let mut bits = price(levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx, tx_type);
4870 // The DC has its own quantiser, so its squared error per unit of level is4914 // The DC has its own quantiser, so its squared error per unit of level is
4871 // `(dc_q / ac_q)^2` of an AC coefficient's.4915 // `(dc_q / ac_q)^2` of an AC coefficient's.
4872 let dc = f64::from(crate::quant::dc_q(8, i32::from(base_q_idx)));4916 let dc = f64::from(crate::quant::dc_q(8, i32::from(base_q_idx)));
@@ -4905,7 +4949,7 @@ pub(crate) fn rdoq(
4905 let candidate = level - level.signum();4949 let candidate = level - level.signum();
4906 levels[i] = candidate;4950 levels[i] = candidate;
4907 budget -= 1;4951 budget -= 1;
4908- let after = price(levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx);4952+ let after = price(levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx, tx_type);
4909 let distortion = weight4953 let distortion = weight
4910 * ((s - f64::from(candidate)).powi(2) - (s - f64::from(level)).powi(2));4954 * ((s - f64::from(candidate)).powi(2) - (s - f64::from(level)).powi(2));
4911 if distortion + lambda * (after - bits) < 0.0 {4955 if distortion + lambda * (after - bits) < 0.0 {
@@ -5177,6 +5221,10 @@ fn write_coeffs(
5177 skip_ctx: usize,5221 skip_ctx: usize,
5178 sign_ctx: usize,5222 sign_ctx: usize,
5179 plane: Option<usize>,5223 plane: Option<usize>,
5224+ // Which transform type these levels were produced with (lane-txset).
5225+ // Only a luma set whose alphabet holds more than one type codes it;
5226+ // chroma never codes a `tx_type` symbol at all.
5227+ tx_type: TxType,
5180 ) {5228 ) {
5181 if let Some(plane) = plane {5229 if let Some(plane) = plane {
5182 ec_rng_trace(|| format!("EC_PLANE plane={plane} tell_before={}", enc.tell()));5230 ec_rng_trace(|| format!("EC_PLANE plane={plane} tell_before={}", enc.tell()));
@@ -5212,8 +5260,18 @@ fn write_coeffs(
5212 // A luma transform whose type set holds more than one type codes which it5260 // A luma transform whose type set holds more than one type codes which it
5213 // is, right after the all-zero flag (spec 5.11.39). The writer only ever5261 // is, right after the all-zero flag (spec 5.11.39). The writer only ever
5214 // uses DCT_DCT, which is index one of `Tx_Type_Intra_Inv_Set2`.5262 // uses DCT_DCT, which is index one of `Tx_Type_Intra_Inv_Set2`.
5215- if let Some(tx_type) = coding.tx_type.as_deref_mut() {5263+ if let Some(cdf) = coding.tx_type.as_deref_mut() {
5216- enc.symbol(TX_TYPE_DCT_DCT_SET2, tx_type);5264+ // The symbol comes from the DECODER's own map, keyed by this set's
5265+ // alphabet width, so a type this set cannot express is caught here
5266+ // rather than desyncing the tile. The search only ever offers types
5267+ // the set holds ([`crate::encode::tx_type_candidates`]).
5268+ let symbol = crate::decode::tx_type_symbol(cdf.len(), tx_type);
5269+ debug_assert!(
5270+ symbol.is_some(),
5271+ "{tx_type:?} is not in the {}-symbol tx_type set",
5272+ cdf.len() - 1
5273+ );
5274+ enc.symbol(symbol.unwrap_or(TX_TYPE_DCT_DCT_SET2), cdf);
5217 if plane.is_some() {5275 if plane.is_some() {
5218 ec_rng_trace(|| format!("EC_TXTYPE tell={} rng={}", enc.tell(), enc.rng()));5276 ec_rng_trace(|| format!("EC_TXTYPE tell={} rng={}", enc.tell(), enc.rng()));
5219 }5277 }
@@ -6242,6 +6300,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
6242 0,6300 0,
6243 &all_scans,6301 &all_scans,
6244 true,6302 true,
6303+ &block.luma_tx_types,
6245 )?;6304 )?;
6246 }6305 }
6247 write_block_planes(6306 write_block_planes(
@@ -6253,6 +6312,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
6253 &neighbours.around(sb_at, SB),6312 &neighbours.around(sb_at, SB),
6254 0,6313 0,
6255 split,6314 split,
6315+ block_tx_type(block),
6256 );6316 );
6257 neighbours.record_planes(sb_at, SB, 0, &grids, !split);6317 neighbours.record_planes(sb_at, SB, 0, &grids, !split);
6258 }6318 }
@@ -6690,6 +6750,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
6690 mode_for_tx,6750 mode_for_tx,
6691 &all_scans,6751 &all_scans,
6692 is_inter,6752 is_inter,
6753+ &block.luma_tx_types,
6693 )?;6754 )?;
6694 }6755 }
6695 write_block_planes(6756 write_block_planes(
@@ -6705,6 +6766,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
6705 &neighbours.around(at, BLOCK),6766 &neighbours.around(at, BLOCK),
6706 mode_for_tx,6767 mode_for_tx,
6707 split,6768 split,
6769+ block_tx_type(block),
6708 );6770 );
6709 neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split);6771 neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split);
6710 }6772 }
@@ -6929,6 +6991,7 @@ fn write_inter_frame_leaf(
6929 if split {6991 if split {
6930 write_luma_tus(6992 write_luma_tus(
6931 enc, cdfs, neighbours, at_mi, SUB, tx, &grids[0], mode_for_tx, all_scans, is_inter,6993 enc, cdfs, neighbours, at_mi, SUB, tx, &grids[0], mode_for_tx, all_scans, is_inter,
6994+ &block.luma_tx_types,
6932 )?;6995 )?;
6933 }6996 }
6934 write_block_planes(6997 write_block_planes(
@@ -6944,6 +7007,7 @@ fn write_inter_frame_leaf(
6944 &neighbours.around(at, SUB),7007 &neighbours.around(at, SUB),
6945 mode_for_tx,7008 mode_for_tx,
6946 split,7009 split,
7010+ block_tx_type(block),
6947 );7011 );
6948 neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split);7012 neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split);
6949 }7013 }
@@ -7184,6 +7248,7 @@ fn write_inter_frame_leaf8(
7184 if split {7248 if split {
7185 write_luma_tus(7249 write_luma_tus(
7186 enc, cdfs, neighbours, leaf_mi, 8, tx, &grids[0], mode_for_tx, all_scans, is_inter,7250 enc, cdfs, neighbours, leaf_mi, 8, tx, &grids[0], mode_for_tx, all_scans, is_inter,
7251+ &block.luma_tx_types,
7187 )?;7252 )?;
7188 }7253 }
7189 write_block_planes(7254 write_block_planes(
@@ -7195,6 +7260,7 @@ fn write_inter_frame_leaf8(
7195 &neighbours.around_mi(leaf_mi, 8),7260 &neighbours.around_mi(leaf_mi, 8),
7196 mode_for_tx,7261 mode_for_tx,
7197 split,7262 split,
7263+ block_tx_type(block),
7198 );7264 );
7199 neighbours.record_mi_planes(leaf_mi, 8, &grids, !split);7265 neighbours.record_mi_planes(leaf_mi, 8, &grids, !split);
7200 neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter, block_ref(block));7266 neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter, block_ref(block));
crates/ec-av1/src/transform.rsmodified+40 -6
@@ -1483,11 +1483,25 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType
1483 if tx_type == TxType::DctDct {1483 if tx_type == TxType::DctDct {
1484 return forward_transform_2d(residual, side);1484 return forward_transform_2d(residual, side);
1485 }1485 }
1486- debug_assert_eq!(1486+ // A FLIPADST axis is the plain ADST kernel with the DECODER's output
1487- tx_type.flip(),1487+ // mirrored (`dequant_and_inverse_typed_wh`'s `ud_flip`/`lr_flip`: row
1488- (false, false),1488+ // `h - 1 - i`, column `w - 1 - j`). A mirror is its own inverse, so the
1489- "a flipped ADST needs its residual mirrored before this basis applies"1489+ // analysis half is the same plain basis over the mirrored residual --
1490- );1490+ // lane-txset, which is what lets every FLIPADST-bearing type share the
1491+ // kernels below instead of needing its own.
1492+ let (ud_flip, lr_flip) = tx_type.flip();
1493+ let mirrored: Vec<i32> = if ud_flip || lr_flip {
1494+ (0..side)
1495+ .flat_map(|row| {
1496+ let src = if ud_flip { side - 1 - row } else { row };
1497+ (0..side).map(move |col| (src, if lr_flip { side - 1 - col } else { col }))
1498+ })
1499+ .map(|(r, c)| residual[r * side + c])
1500+ .collect()
1501+ } else {
1502+ Vec::new()
1503+ };
1504+ let residual: &[i32] = if mirrored.is_empty() { residual } else { &mirrored };
1491 let (row_kind, col_kind) = tx_type.axes();1505 let (row_kind, col_kind) = tx_type.axes();
1492 let (hb, vb) = (axis_basis_t(side, row_kind), axis_basis_t(side, col_kind));1506 let (hb, vb) = (axis_basis_t(side, row_kind), axis_basis_t(side, col_kind));
1493 let mut rows = vec![0.0f64; side * side];1507 let mut rows = vec![0.0f64; side * side];
@@ -2162,7 +2176,27 @@ mod tests {
2162 (sum / (side * side) as f64).sqrt()2176 (sum / (side * side) as f64).sqrt()
2163 };2177 };
2164 let dct = rmse(TxType::DctDct);2178 let dct = rmse(TxType::DctDct);
2165- for tx in [TxType::AdstDct, TxType::DctAdst, TxType::AdstAdst] {2179+ // lane-txset: every one of the sixteen types, not just the four
2180+ // the reduced set names -- the FLIPADST and 1D-ADST/DCT families
2181+ // reach the forward side through the mirrored residual, and a
2182+ // mirror on the wrong axis reads exactly as a blown-up rmse here.
2183+ for tx in [
2184+ TxType::AdstDct,
2185+ TxType::DctAdst,
2186+ TxType::AdstAdst,
2187+ TxType::Idtx,
2188+ TxType::VDct,
2189+ TxType::HDct,
2190+ TxType::VAdst,
2191+ TxType::HAdst,
2192+ TxType::VFlipAdst,
2193+ TxType::HFlipAdst,
2194+ TxType::FlipAdstDct,
2195+ TxType::DctFlipAdst,
2196+ TxType::FlipAdstFlipAdst,
2197+ TxType::AdstFlipAdst,
2198+ TxType::FlipAdstAdst,
2199+ ] {
2166 let e = rmse(tx);2200 let e = rmse(tx);
2167 assert!(2201 assert!(
2168 e < 2.0 * dct,2202 e < 2.0 * dct,